diff --git a/.gitignore-revs b/.gitignore-revs new file mode 100644 index 0000000000000000000000000000000000000000..d2101539363e95c4050760ee22a1c2526f8e75fd --- /dev/null +++ b/.gitignore-revs @@ -0,0 +1 @@ +249990732f4c5ca5a53a0d451c4be7dece1f3a73 diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 4a906e4033710e19df2cbc446bc4f1ac1dff878b..30e062e24c36e17d4d92db581447e1e5fb4434eb 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -110,7 +110,6 @@ codequality: - git diff FETCH_HEAD -U0 --no-color | clang-format-diff -p1 -style file | tee clang_format_diff - echo "EOF" - if [[ -s clang_format_diff ]]; then false; fi - allow_failure: true ### We embed script from third party libraries, that we sometimes update from their source. Hence we should NEVER modify them here before submitting the patch upstream! # Ideally, we should remove all this code and use them as packaged libraries. Unfortunately this check only works for merge requests. diff --git a/buildtools/clangformat-helper.sh b/buildtools/clangformat-helper.sh new file mode 100644 index 0000000000000000000000000000000000000000..c8472dfb5891e1a88a9d625c8ef7fd282d44d62e --- /dev/null +++ b/buildtools/clangformat-helper.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0-or-later +## +## usage: clangformat-helper +## +## It runs for all source files, excluding the 3rd party ones. +## + +set -e + +clang-format -i $(find src -name '*.cpp' -o -name '*.h' -o -name '*.c' | grep -E -v '^src/(3rdparty|libnrtype|livarot)') diff --git a/src/actions/actions-base.cpp b/src/actions/actions-base.cpp index 2b8d58e459e4fe2204a33ab59ac6c20c70e25fe6..d4587dbb701862c029106c2496c6fbdd3472e0e3 100644 --- a/src/actions/actions-base.cpp +++ b/src/actions/actions-base.cpp @@ -8,62 +8,55 @@ * */ -#include +#include "actions-base.h" -#include // Not ! To eventually allow a headless version! +#include // Not ! To eventually allow a headless version! #include +#include -#include "actions-base.h" #include "actions-helper.h" - +#include "extension/init.h" // List verbs +#include "file.h" // dpi convert method #include "inkscape-application.h" - -#include "inkscape.h" // Inkscape::Application -#include "inkscape-version.h" // Inkscape version -#include "path-prefix.h" // Extension directory -#include "extension/init.h" // List verbs -#include "verbs.h" // List verbs -#include "selection.h" // Selection -#include "object/sp-root.h" // query_all() -#include "file.h" // dpi convert method +#include "inkscape-version.h" // Inkscape version +#include "inkscape.h" // Inkscape::Application #include "io/resource.h" +#include "object/sp-root.h" // query_all() +#include "path-prefix.h" // Extension directory +#include "selection.h" // Selection +#include "verbs.h" // List verbs -void -print_inkscape_version() +void print_inkscape_version() { std::cout << "Inkscape " << Inkscape::version_string << std::endl; std::cerr << " Pango version: " << pango_version_string() << std::endl; } -void -print_system_data_directory() +void print_system_data_directory() { std::cout << Glib::build_filename(get_inkscape_datadir(), "inkscape") << std::endl; } -void -print_user_data_directory() +void print_user_data_directory() { std::cout << Inkscape::IO::Resource::profile_path("") << std::endl; } -void -print_verb_list() +void print_verb_list() { // This really shouldn't go here, we should init the app. // But, since we're just exiting in this path, there is // no harm, and this is really a better place to put // everything else. - Inkscape::Extension::init(); // extension/init.h - Inkscape::Verb::list(); // verbs.h + Inkscape::Extension::init(); // extension/init.h + Inkscape::Verb::list(); // verbs.h } // Helper function for query_x(), query_y(), query_width(), and query_height(). -void -query_dimension(InkscapeApplication* app, bool extent, Geom::Dim2 const axis) +void query_dimension(InkscapeApplication *app, bool extent, Geom::Dim2 const axis) { - SPDocument* document = nullptr; - Inkscape::Selection* selection = nullptr; + SPDocument *document = nullptr; + Inkscape::Selection *selection = nullptr; if (!get_document_and_selection(app, &document, &selection)) { return; } @@ -93,35 +86,30 @@ query_dimension(InkscapeApplication* app, bool extent, Geom::Dim2 const axis) std::cout << std::endl; } -void -query_x(InkscapeApplication* app) +void query_x(InkscapeApplication *app) { query_dimension(app, false, Geom::X); } -void -query_y(InkscapeApplication* app) +void query_y(InkscapeApplication *app) { query_dimension(app, false, Geom::Y); } -void -query_width(InkscapeApplication* app) +void query_width(InkscapeApplication *app) { query_dimension(app, true, Geom::X); } -void -query_height(InkscapeApplication* app) +void query_height(InkscapeApplication *app) { query_dimension(app, true, Geom::Y); } // Helper for query_all() -void -query_all_recurse (SPObject *o) +void query_all_recurse(SPObject *o) { - SPItem *item = dynamic_cast(o); + SPItem *item = dynamic_cast(o); if (item && item->getId()) { Geom::OptRect area = item->documentVisualBounds(); if (area) { @@ -134,16 +122,15 @@ query_all_recurse (SPObject *o) // clang-format on } - for (auto& child: o->children) { - query_all_recurse (&child); + for (auto &child : o->children) { + query_all_recurse(&child); } } } -void -query_all(InkscapeApplication* app) +void query_all(InkscapeApplication *app) { - SPDocument* doc = app->get_active_document(); + SPDocument *doc = app->get_active_document(); if (!doc) { std::cerr << "query_all: no document!" << std::endl; return; @@ -155,14 +142,12 @@ query_all(InkscapeApplication* app) } } -void -pdf_page(int page) +void pdf_page(int page) { INKSCAPE.set_pdf_page(page); } -void -convert_dpi_method(Glib::ustring method) +void convert_dpi_method(Glib::ustring method) { if (method == "none") { sp_file_convert_dpi_method_commandline = FILE_DPI_UNCHANGED; @@ -175,51 +160,48 @@ convert_dpi_method(Glib::ustring method) } } -void -no_convert_baseline() +void no_convert_baseline() { sp_no_convert_text_baseline_spacing = true; } // Temporary: Verbs are to be replaced by Gio::Actions! -void -verbs(Glib::ustring verblist, InkscapeApplication* app) +void verbs(Glib::ustring verblist, InkscapeApplication *app) { auto tokens = Glib::Regex::split_simple("\\s*;\\s*", verblist); for (auto token : tokens) { - std::vector parts = Glib::Regex::split_simple("\\s*:\\s*", token); // Second part is always ignored... we could implement it but better to switch to Gio::Actions + std::vector parts = + Glib::Regex::split_simple("\\s*:\\s*", token); // Second part is always ignored... we could implement it but + // better to switch to Gio::Actions if (!parts.empty() && !parts[0].empty()) { - Inkscape::Verb* verb = Inkscape::Verb::getbyid(parts[0].c_str()); + Inkscape::Verb *verb = Inkscape::Verb::getbyid(parts[0].c_str()); if (verb == nullptr) { std::cerr << "verbs_action: Invalid verb: " << parts[0] << std::endl; break; } // Inkscape::ActionContext context = INKSCAPE.action_context_for_document(*document); - SPAction* action = verb->get_action(INKSCAPE.active_action_context()); - sp_action_perform(action, nullptr); // Data is ignored! + SPAction *action = verb->get_action(INKSCAPE.active_action_context()); + sp_action_perform(action, nullptr); // Data is ignored! } } } -void -vacuum_defs(InkscapeApplication* app) +void vacuum_defs(InkscapeApplication *app) { - SPDocument* document = nullptr; - Inkscape::Selection* selection = nullptr; + SPDocument *document = nullptr; + Inkscape::Selection *selection = nullptr; if (!get_document_and_selection(app, &document, &selection)) { return; } document->vacuumDocument(); } -void -quit_inkscape(InkscapeApplication* app) +void quit_inkscape(InkscapeApplication *app) { app->on_quit(); } -std::vector> raw_data_base = -{ +std::vector> raw_data_base = { // clang-format off {"app.inkscape-version", "InkscapeVersion", "Base", N_("Print Inkscape version and exit.") }, {"app.system-data-directory", "InkscapeSystemDir", "Base", N_("Print system data directory and exit.") }, @@ -242,9 +224,8 @@ std::vector> raw_data_base = // clang-format on }; -template -void -add_actions_base(ConcreteInkscapeApplication* app) +template +void add_actions_base(ConcreteInkscapeApplication *app) { // Note: "radio" actions are just an easy way to set type without using templating. // clang-format off @@ -272,8 +253,8 @@ add_actions_base(ConcreteInkscapeApplication* app) app->get_action_extra_data().add_data(raw_data_base); } -template void add_actions_base(ConcreteInkscapeApplication* app); -template void add_actions_base(ConcreteInkscapeApplication* app); +template void add_actions_base(ConcreteInkscapeApplication *app); +template void add_actions_base(ConcreteInkscapeApplication *app); /* Local Variables: diff --git a/src/actions/actions-base.h b/src/actions/actions-base.h index cf43b8e02ca755425dadb596ce0c828a3cc96947..444c3a963e1821bbe61d4af91d5987c71584631b 100644 --- a/src/actions/actions-base.h +++ b/src/actions/actions-base.h @@ -11,9 +11,10 @@ #ifndef INK_ACTIONS_BASE_H #define INK_ACTIONS_BASE_H -template class ConcreteInkscapeApplication; +template +class ConcreteInkscapeApplication; -template -void add_actions_base(ConcreteInkscapeApplication* app); +template +void add_actions_base(ConcreteInkscapeApplication *app); #endif // INK_ACTIONS_BASE_H diff --git a/src/actions/actions-canvas-snapping.cpp b/src/actions/actions-canvas-snapping.cpp index e1112b3f2fc34e7b59d3668e8c28695e4cb0218d..768fbf8b11b20e37cb954d2da5aeef9d7d32a9b5 100644 --- a/src/actions/actions-canvas-snapping.cpp +++ b/src/actions/actions-canvas-snapping.cpp @@ -8,20 +8,17 @@ * */ -#include - -#include // Not ! To eventually allow a headless version! -#include - #include "actions-canvas-snapping.h" -#include "inkscape-application.h" -#include "document.h" +#include // Not ! To eventually allow a headless version! +#include +#include #include "attributes.h" #include "desktop.h" #include "document-undo.h" - +#include "document.h" +#include "inkscape-application.h" #include "object/sp-namedview.h" // There are four snapping lists that must be connected: @@ -33,12 +30,11 @@ // This might work better as a class. -static void -canvas_snapping_toggle(SPDocument* document, const SPAttr option) +static void canvas_snapping_toggle(SPDocument *document, const SPAttr option) { - //std::cout << "canvas_snapping_toggle: " << option << std::endl; + // std::cout << "canvas_snapping_toggle: " << option << std::endl; - Inkscape::XML::Node* repr = document->getReprNamedView(); + Inkscape::XML::Node *repr = document->getReprNamedView(); if (repr == nullptr) { std::cerr << "canvas_snapping_toggle: namedview XML repr missing!" << std::endl; @@ -46,8 +42,8 @@ canvas_snapping_toggle(SPDocument* document, const SPAttr option) } // This is a bit ackward. - SPObject* obj = document->getObjectByRepr(repr); - SPNamedView* nv = dynamic_cast (obj); + SPObject *obj = document->getObjectByRepr(repr); + SPNamedView *nv = dynamic_cast(obj); if (nv == nullptr) { std::cerr << "canvas_snapping_toggle: no namedview!" << std::endl; return; @@ -116,7 +112,6 @@ canvas_snapping_toggle(SPDocument* document, const SPAttr option) sp_repr_set_boolean(repr, "inkscape:snap-smooth-nodes", !v); break; - case SPAttr::INKSCAPE_SNAP_LINE_MIDPOINT: v = nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_LINE_MIDPOINT); sp_repr_set_boolean(repr, "inkscape:snap-midpoints", !v); @@ -178,71 +173,100 @@ canvas_snapping_toggle(SPDocument* document, const SPAttr option) // The snapping preferences are stored in the document, and therefore toggling makes the document dirty. document->setModifiedSinceSave(); - } -std::vector> raw_data_canvas_snapping = -{ - {"doc.snap-global-toggle", "Snap", "Snap", N_("Toggle snapping") }, - - {"doc.snap-bbox", "SnapBoundingBox", "Snap", ("Toggle snapping to bounding boxes (global)") }, - {"doc.snap-bbox-edge", "SnapBBoxEdge", "Snap", ("Toggle snapping to bounding box edge") }, - {"doc.snap-bbox-corner", "SnapBBoxCorner", "Snap", ("Toggle snapping to bounding box corner") }, - {"doc.snap-bbox-edge-midpoint", "SnapBBoxEdgeMidpoint", "Snap", ("Toggle snapping to bounding box edge mid-point") }, - {"doc.snap-bbox-center", "SnapBBoxCenter", "Snap", ("Toggle snapping to bounding box center") }, - - {"doc.snap-node-category", "SnapNodes", "Snap", ("Toggle snapping to nodes (global)") }, - {"doc.snap-path", "SnapPath", "Snap", ("Toggle snapping to path") }, - {"doc.snap-path-intersection", "SnapPathIntersection", "Snap", ("Toggle snapping to path intersection") }, - {"doc.snap-node-cusp", "SnapNodeCusp", "Snap", ("Toggle snapping to cusp node") }, - {"doc.snap-node-smooth", "SnapNodeSmooth", "Snap", ("Toggle snapping to smooth node") }, - {"doc.snap-line-midpoint", "SnapLineMidpoint", "Snap", ("Toggle snapping to midpoint of line") }, - - {"doc.snap-others", "SnapOthers", "Snap", ("Toggle snapping to misc. point (global)") }, - {"doc.snap-object-midpoint", "SnapObjectMidpoint", "Snap", ("Toggle snapping to object midpoint") }, - {"doc.snap-rotation-center", "SnapRoationCenter", "Snap", ("Toggle snapping to object rotation center") }, - {"doc.snap-text-baseline", "SnapTextBaseline", "Snap", ("Toggle snapping to text baseline") }, - - {"doc.snap-page-border", "SnapPageBorder", "Snap", ("Toggle snapping to page border") }, - {"doc.snap-grid", "SnapGrid", "Snap", ("Toggle snapping to grid") }, - {"doc.snap-guide", "SnapGuide", "Snap", ("Toggle snapping to guide") }, - - {"doc.snap-path-mask", "SnapPathMask", "Snap", ("Toggle snapping to path of mask") }, - {"doc.snap-path-clip", "SnapPathClip", "Snap", ("Toggle snapping to clip path") }, +std::vector> raw_data_canvas_snapping = { + {"doc.snap-global-toggle", "Snap", "Snap", N_("Toggle snapping")}, + + {"doc.snap-bbox", "SnapBoundingBox", "Snap", ("Toggle snapping to bounding boxes (global)")}, + {"doc.snap-bbox-edge", "SnapBBoxEdge", "Snap", ("Toggle snapping to bounding box edge")}, + {"doc.snap-bbox-corner", "SnapBBoxCorner", "Snap", ("Toggle snapping to bounding box corner")}, + {"doc.snap-bbox-edge-midpoint", "SnapBBoxEdgeMidpoint", "Snap", ("Toggle snapping to bounding box edge mid-point")}, + {"doc.snap-bbox-center", "SnapBBoxCenter", "Snap", ("Toggle snapping to bounding box center")}, + + {"doc.snap-node-category", "SnapNodes", "Snap", ("Toggle snapping to nodes (global)")}, + {"doc.snap-path", "SnapPath", "Snap", ("Toggle snapping to path")}, + {"doc.snap-path-intersection", "SnapPathIntersection", "Snap", ("Toggle snapping to path intersection")}, + {"doc.snap-node-cusp", "SnapNodeCusp", "Snap", ("Toggle snapping to cusp node")}, + {"doc.snap-node-smooth", "SnapNodeSmooth", "Snap", ("Toggle snapping to smooth node")}, + {"doc.snap-line-midpoint", "SnapLineMidpoint", "Snap", ("Toggle snapping to midpoint of line")}, + + {"doc.snap-others", "SnapOthers", "Snap", ("Toggle snapping to misc. point (global)")}, + {"doc.snap-object-midpoint", "SnapObjectMidpoint", "Snap", ("Toggle snapping to object midpoint")}, + {"doc.snap-rotation-center", "SnapRoationCenter", "Snap", ("Toggle snapping to object rotation center")}, + {"doc.snap-text-baseline", "SnapTextBaseline", "Snap", ("Toggle snapping to text baseline")}, + + {"doc.snap-page-border", "SnapPageBorder", "Snap", ("Toggle snapping to page border")}, + {"doc.snap-grid", "SnapGrid", "Snap", ("Toggle snapping to grid")}, + {"doc.snap-guide", "SnapGuide", "Snap", ("Toggle snapping to guide")}, + + {"doc.snap-path-mask", "SnapPathMask", "Snap", ("Toggle snapping to path of mask")}, + {"doc.snap-path-clip", "SnapPathClip", "Snap", ("Toggle snapping to clip path")}, }; -void -add_actions_canvas_snapping(SPDocument* document) +void add_actions_canvas_snapping(SPDocument *document) { Glib::RefPtr map = document->getActionGroup(); - map->add_action_bool( "snap-global-toggle", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_GLOBAL)); - - map->add_action_bool( "snap-bbox", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_BBOX)); - map->add_action_bool( "snap-bbox-edge", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_BBOX_EDGE)); - map->add_action_bool( "snap-bbox-corner", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_BBOX_CORNER)); - map->add_action_bool( "snap-bbox-edge-midpoint", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_BBOX_EDGE_MIDPOINT)); - map->add_action_bool( "snap-bbox-center", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_BBOX_MIDPOINT)); - - map->add_action_bool( "snap-node-category", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_NODE)); - map->add_action_bool( "snap-path", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_PATH)); - map->add_action_bool( "snap-path-intersection", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_PATH_INTERSECTION)); - map->add_action_bool( "snap-node-cusp", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_NODE_CUSP)); - map->add_action_bool( "snap-node-smooth", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_NODE_SMOOTH)); - map->add_action_bool( "snap-line-midpoint", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_LINE_MIDPOINT)); - - map->add_action_bool( "snap-others", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_OTHERS)); - map->add_action_bool( "snap-object-midpoint", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_OBJECT_MIDPOINT)); - map->add_action_bool( "snap-rotation-center", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_ROTATION_CENTER)); - map->add_action_bool( "snap-text-baseline", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_TEXT_BASELINE)); - - map->add_action_bool( "snap-page-border", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_PAGE_BORDER)); - map->add_action_bool( "snap-grid", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_GRID)); - map->add_action_bool( "snap-guide", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_GUIDE)); + map->add_action_bool("snap-global-toggle", + sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_GLOBAL)); + + map->add_action_bool("snap-bbox", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_BBOX)); + map->add_action_bool("snap-bbox-edge", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), + document, SPAttr::INKSCAPE_SNAP_BBOX_EDGE)); + map->add_action_bool("snap-bbox-corner", + sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_BBOX_CORNER)); + map->add_action_bool("snap-bbox-edge-midpoint", + sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_BBOX_EDGE_MIDPOINT)); + map->add_action_bool("snap-bbox-center", + sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_BBOX_MIDPOINT)); + + map->add_action_bool("snap-node-category", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), + document, SPAttr::INKSCAPE_SNAP_NODE)); + map->add_action_bool("snap-path", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_PATH)); + map->add_action_bool("snap-path-intersection", + sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_PATH_INTERSECTION)); + map->add_action_bool("snap-node-cusp", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), + document, SPAttr::INKSCAPE_SNAP_NODE_CUSP)); + map->add_action_bool("snap-node-smooth", + sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_NODE_SMOOTH)); + map->add_action_bool("snap-line-midpoint", + sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_LINE_MIDPOINT)); + + map->add_action_bool("snap-others", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), + document, SPAttr::INKSCAPE_SNAP_OTHERS)); + map->add_action_bool("snap-object-midpoint", + sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_OBJECT_MIDPOINT)); + map->add_action_bool("snap-rotation-center", + sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_ROTATION_CENTER)); + map->add_action_bool("snap-text-baseline", + sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_TEXT_BASELINE)); + + map->add_action_bool("snap-page-border", + sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_PAGE_BORDER)); + map->add_action_bool("snap-grid", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, + SPAttr::INKSCAPE_SNAP_GRID)); + map->add_action_bool("snap-guide", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), + document, SPAttr::INKSCAPE_SNAP_GUIDE)); // Not used in toolbar - map->add_action_bool( "snap-path-mask", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_PATH_MASK)); - map->add_action_bool( "snap-path-clip", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), document, SPAttr::INKSCAPE_SNAP_PATH_CLIP)); + map->add_action_bool("snap-path-mask", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), + document, SPAttr::INKSCAPE_SNAP_PATH_MASK)); + map->add_action_bool("snap-path-clip", sigc::bind(sigc::ptr_fun(&canvas_snapping_toggle), + document, SPAttr::INKSCAPE_SNAP_PATH_CLIP)); // Check if there is already an application instance (GUI or non-GUI). auto app = dynamic_cast(Gio::Application::get_default().get()); @@ -253,9 +277,8 @@ add_actions_canvas_snapping(SPDocument* document) app->get_action_extra_data().add_data(raw_data_canvas_snapping); } - -void -set_actions_canvas_snapping_helper (Glib::RefPtr& map, Glib::ustring action_name, bool state, bool enabled) +void set_actions_canvas_snapping_helper(Glib::RefPtr &map, Glib::ustring action_name, + bool state, bool enabled) { // Glib::RefPtr saction = map->lookup_action(action_name); NOT POSSIBLE! @@ -277,10 +300,9 @@ set_actions_canvas_snapping_helper (Glib::RefPtr& map, G simple->set_enabled(enabled); } -void -set_actions_canvas_snapping(SPDocument* document) +void set_actions_canvas_snapping(SPDocument *document) { - Inkscape::XML::Node* repr = document->getReprNamedView(); + Inkscape::XML::Node *repr = document->getReprNamedView(); if (repr == nullptr) { std::cerr << "set_actions_canvas_snapping: namedview XML repr missing!" << std::endl; @@ -288,8 +310,8 @@ set_actions_canvas_snapping(SPDocument* document) } // This is a bit ackward. - SPObject* obj = document->getObjectByRepr(repr); - SPNamedView* nv = dynamic_cast (obj); + SPObject *obj = document->getObjectByRepr(repr); + SPNamedView *nv = dynamic_cast(obj); if (nv == nullptr) { std::cerr << "set_actions_canvas_snapping: no namedview!" << std::endl; @@ -307,35 +329,62 @@ set_actions_canvas_snapping(SPDocument* document) bool bbox = nv->snap_manager.snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_BBOX_CATEGORY); set_actions_canvas_snapping_helper(map, "snap-bbox", bbox, global); - set_actions_canvas_snapping_helper(map, "snap-bbox-edge", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_BBOX_EDGE), global && bbox); - set_actions_canvas_snapping_helper(map, "snap-bbox-corner", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_BBOX_CORNER), global && bbox); - set_actions_canvas_snapping_helper(map, "snap-bbox-edge-midpoint", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_BBOX_EDGE_MIDPOINT), global && bbox); - set_actions_canvas_snapping_helper(map, "snap-bbox-center", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_BBOX_MIDPOINT), global && bbox); + set_actions_canvas_snapping_helper(map, "snap-bbox-edge", + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_BBOX_EDGE), + global && bbox); + set_actions_canvas_snapping_helper(map, "snap-bbox-corner", + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_BBOX_CORNER), + global && bbox); + set_actions_canvas_snapping_helper( + map, "snap-bbox-edge-midpoint", + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_BBOX_EDGE_MIDPOINT), global && bbox); + set_actions_canvas_snapping_helper( + map, "snap-bbox-center", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_BBOX_MIDPOINT), + global && bbox); bool node = nv->snap_manager.snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_NODE_CATEGORY); set_actions_canvas_snapping_helper(map, "snap-node-category", node, global); - set_actions_canvas_snapping_helper(map, "snap-path", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH), global && node); - set_actions_canvas_snapping_helper(map, "snap-path-intersection", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_INTERSECTION), global && node); - set_actions_canvas_snapping_helper(map, "snap-node-cusp", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_NODE_CUSP), global && node); - set_actions_canvas_snapping_helper(map, "snap-node-smooth", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_NODE_SMOOTH), global && node); - set_actions_canvas_snapping_helper(map, "snap-line-midpoint", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_LINE_MIDPOINT), global && node); + set_actions_canvas_snapping_helper( + map, "snap-path", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH), global && node); + set_actions_canvas_snapping_helper( + map, "snap-path-intersection", + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_INTERSECTION), global && node); + set_actions_canvas_snapping_helper(map, "snap-node-cusp", + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_NODE_CUSP), + global && node); + set_actions_canvas_snapping_helper(map, "snap-node-smooth", + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_NODE_SMOOTH), + global && node); + set_actions_canvas_snapping_helper( + map, "snap-line-midpoint", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_LINE_MIDPOINT), + global && node); bool other = nv->snap_manager.snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_OTHERS_CATEGORY); set_actions_canvas_snapping_helper(map, "snap-others", other, global); - set_actions_canvas_snapping_helper(map, "snap-object-midpoint", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_OBJECT_MIDPOINT), global && other); - set_actions_canvas_snapping_helper(map, "snap-rotation-center", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_ROTATION_CENTER), global && other); - set_actions_canvas_snapping_helper(map, "snap-text-baseline", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_TEXT_BASELINE), global && other); - - set_actions_canvas_snapping_helper(map, "snap-page-border", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PAGE_BORDER), global); - set_actions_canvas_snapping_helper(map, "snap-grid", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_GRID), global); - set_actions_canvas_snapping_helper(map, "snap-guide", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_GUIDE), global); - - set_actions_canvas_snapping_helper(map, "snap-path-mask", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_CLIP), global); - set_actions_canvas_snapping_helper(map, "snap-path-clip", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_MASK), global); + set_actions_canvas_snapping_helper( + map, "snap-object-midpoint", + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_OBJECT_MIDPOINT), global && other); + set_actions_canvas_snapping_helper( + map, "snap-rotation-center", + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_ROTATION_CENTER), global && other); + set_actions_canvas_snapping_helper( + map, "snap-text-baseline", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_TEXT_BASELINE), + global && other); + + set_actions_canvas_snapping_helper(map, "snap-page-border", + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PAGE_BORDER), + global); + set_actions_canvas_snapping_helper( + map, "snap-grid", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_GRID), global); + set_actions_canvas_snapping_helper( + map, "snap-guide", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_GUIDE), global); + + set_actions_canvas_snapping_helper( + map, "snap-path-mask", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_CLIP), global); + set_actions_canvas_snapping_helper( + map, "snap-path-clip", nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_MASK), global); } - - /* Local Variables: mode:c++ diff --git a/src/actions/actions-canvas-snapping.h b/src/actions/actions-canvas-snapping.h index bfc3518634e96beb9ed189ea230b267caaace1e3..8bf39181e53f4d48125e7e45a34224a23df8c12c 100644 --- a/src/actions/actions-canvas-snapping.h +++ b/src/actions/actions-canvas-snapping.h @@ -15,8 +15,8 @@ class SPDocument; -void add_actions_canvas_snapping(SPDocument* document); -void set_actions_canvas_snapping(SPDocument* document); +void add_actions_canvas_snapping(SPDocument *document); +void set_actions_canvas_snapping(SPDocument *document); #endif // INK_ACTIONS_CANVAS_SNAPPING_H diff --git a/src/actions/actions-canvas-transform.cpp b/src/actions/actions-canvas-transform.cpp index 3aa7f50c5081caeb4a2159f2c873c1b01462b215..0b6b475beb61630425001e68ca5f2ece2f124b66 100644 --- a/src/actions/actions-canvas-transform.cpp +++ b/src/actions/actions-canvas-transform.cpp @@ -8,21 +8,21 @@ * */ -#include +#include "actions-canvas-transform.h" -#include // Not ! To eventually allow a headless version! +#include // Not ! To eventually allow a headless version! #include +#include -#include "actions-canvas-transform.h" +#include "desktop.h" #include "inkscape-application.h" #include "inkscape-window.h" -#include "desktop.h" - -#include "ui/tools-switch.h" // TOOLS_FREEHAND_PEN, etc. +#include "ui/tools-switch.h" // TOOLS_FREEHAND_PEN, etc. #include "ui/tools/freehand-base.h" // SP_DRAW_CONTEXT -#include "ui/widget/canvas.h" // Canvas area +#include "ui/widget/canvas.h" // Canvas area -enum { +enum +{ INK_CANVAS_ZOOM_IN, INK_CANVAS_ZOOM_OUT, INK_CANVAS_ZOOM_1_1, @@ -36,15 +36,11 @@ enum { INK_CANVAS_ZOOM_NEXT }; -static void -canvas_zoom_helper(SPDesktop* dt, const Geom::Point& midpoint, double zoom_factor) +static void canvas_zoom_helper(SPDesktop *dt, const Geom::Point &midpoint, double zoom_factor) { - if (tools_isactive(dt, TOOLS_FREEHAND_PENCIL) || - tools_isactive(dt, TOOLS_FREEHAND_PEN ) ) { - + if (tools_isactive(dt, TOOLS_FREEHAND_PENCIL) || tools_isactive(dt, TOOLS_FREEHAND_PEN)) { // Zoom around end of unfinished path. - boost::optional zoom_to = - SP_DRAW_CONTEXT(dt->event_context)->red_curve_get_last_point(); + boost::optional zoom_to = SP_DRAW_CONTEXT(dt->event_context)->red_curve_get_last_point(); if (zoom_to) { dt->zoom_relative_keep_point(*zoom_to, zoom_factor); return; @@ -54,41 +50,39 @@ canvas_zoom_helper(SPDesktop* dt, const Geom::Point& midpoint, double zoom_facto dt->zoom_relative_center_point(midpoint, zoom_factor); } -void -canvas_transform(InkscapeWindow *win, const int& option) +void canvas_transform(InkscapeWindow *win, const int &option) { - SPDesktop* dt = win->get_desktop(); + SPDesktop *dt = win->get_desktop(); // The following might be better done elsewhere: // Get preference dependent parameters Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - double zoom_inc = - prefs->getDoubleLimited("/options/zoomincrement/value", M_SQRT2, 1.01, 10); + double zoom_inc = prefs->getDoubleLimited("/options/zoomincrement/value", M_SQRT2, 1.01, 10); // Get document dependent parameters Geom::Rect const canvas = dt->getCanvas()->get_area_world(); - Geom::Point midpoint = dt->w2d(canvas.midpoint()); // Midpoint of drawing on canvas. + Geom::Point midpoint = dt->w2d(canvas.midpoint()); // Midpoint of drawing on canvas. switch (option) { case INK_CANVAS_ZOOM_IN: - canvas_zoom_helper( dt, midpoint, zoom_inc); + canvas_zoom_helper(dt, midpoint, zoom_inc); break; case INK_CANVAS_ZOOM_OUT: - canvas_zoom_helper( dt, midpoint, 1.0 / zoom_inc); // zoom_inc > 1 + canvas_zoom_helper(dt, midpoint, 1.0 / zoom_inc); // zoom_inc > 1 break; case INK_CANVAS_ZOOM_1_1: - dt->zoom_absolute_center_point( midpoint, 1.0 ); + dt->zoom_absolute_center_point(midpoint, 1.0); break; case INK_CANVAS_ZOOM_1_2: - dt->zoom_absolute_center_point( midpoint, 0.5 ); + dt->zoom_absolute_center_point(midpoint, 0.5); break; case INK_CANVAS_ZOOM_2_1: - dt->zoom_absolute_center_point( midpoint, 2.0 ); + dt->zoom_absolute_center_point(midpoint, 2.0); break; case INK_CANVAS_ZOOM_SELECTION: @@ -120,8 +114,7 @@ canvas_transform(InkscapeWindow *win, const int& option) } } -std::vector> raw_data_canvas_transform = -{ +std::vector> raw_data_canvas_transform = { // clang-format off {"win.canvas-zoom-in", "ZoomIn", "View", N_("Zoom in") }, {"win.canvas-zoom-out", "ZoomOut", "View", N_("Zoom out") }, @@ -138,8 +131,7 @@ std::vector> raw_data_canvas_transform = // clang-format on }; -void -add_actions_canvas_transform(InkscapeWindow* win) +void add_actions_canvas_transform(InkscapeWindow *win) { // clang-format off win->add_action( "canvas-zoom-in", sigc::bind(sigc::ptr_fun(&canvas_transform), win, INK_CANVAS_ZOOM_IN)); @@ -163,7 +155,6 @@ add_actions_canvas_transform(InkscapeWindow* win) app->get_action_extra_data().add_data(raw_data_canvas_transform); } - /* Local Variables: mode:c++ diff --git a/src/actions/actions-canvas-transform.h b/src/actions/actions-canvas-transform.h index ad3538ad194208a72c2c04e79f8f42f4e39102e5..77eb750b580a2c160e4cd6b67474034a354561ef 100644 --- a/src/actions/actions-canvas-transform.h +++ b/src/actions/actions-canvas-transform.h @@ -14,7 +14,7 @@ class InkscapeWindow; class InkscapeApplication; -void add_actions_canvas_transform(InkscapeWindow* win); +void add_actions_canvas_transform(InkscapeWindow *win); #endif // INK_ACTIONS_CANVAS_TRANSFORM_H diff --git a/src/actions/actions-extra-data.cpp b/src/actions/actions-extra-data.cpp index 45094d74a5d1c1824dff8583e270be1e7721f7eb..b6e3d6ace474d7a548c5480f747fc27a72776c34 100644 --- a/src/actions/actions-extra-data.cpp +++ b/src/actions/actions-extra-data.cpp @@ -12,49 +12,44 @@ #include -Glib::ustring -InkActionExtraData::get_label_for_action(Glib::ustring& action_name) +Glib::ustring InkActionExtraData::get_label_for_action(Glib::ustring &action_name) { - Glib::ustring value; - auto search = data.find(action_name); - if (search != data.end()) { - value = search->second.get_label(); - } - return value; + Glib::ustring value; + auto search = data.find(action_name); + if (search != data.end()) { + value = search->second.get_label(); + } + return value; } -Glib::ustring -InkActionExtraData::get_section_for_action(Glib::ustring& action_name) { - - Glib::ustring value; - auto search = data.find(action_name); - if (search != data.end()) { - value = search->second.get_section(); - } - return value; +Glib::ustring InkActionExtraData::get_section_for_action(Glib::ustring &action_name) +{ + Glib::ustring value; + auto search = data.find(action_name); + if (search != data.end()) { + value = search->second.get_section(); + } + return value; } -Glib::ustring -InkActionExtraData::get_tooltip_for_action(Glib::ustring& action_name) { - - Glib::ustring value; - auto search = data.find(action_name); - if (search != data.end()) { - value = search->second.get_tooltip(); - } - return value; +Glib::ustring InkActionExtraData::get_tooltip_for_action(Glib::ustring &action_name) +{ + Glib::ustring value; + auto search = data.find(action_name); + if (search != data.end()) { + value = search->second.get_tooltip(); + } + return value; } -void -InkActionExtraData::add_data(std::vector> &raw_data) +void InkActionExtraData::add_data(std::vector> &raw_data) { - for (auto raw : raw_data) { - InkActionExtraDatum datum(raw[1], raw[2], raw[3]); - data.emplace(raw[0], datum); - } + for (auto raw : raw_data) { + InkActionExtraDatum datum(raw[1], raw[2], raw[3]); + data.emplace(raw[0], datum); + } } - /* Local Variables: mode:c++ diff --git a/src/actions/actions-extra-data.h b/src/actions/actions-extra-data.h index e96234e3b92644cc656c78a9771adc742bdfd5fd..6cd60d74fefa3b1d0e3030a3ba29cd96d8c93aa9 100644 --- a/src/actions/actions-extra-data.h +++ b/src/actions/actions-extra-data.h @@ -11,43 +11,42 @@ #ifndef INK_ACTIONS_EXTRA_DATA_H #define INK_ACTIONS_EXTRA_DATA_H +#include #include #include -#include - -class InkActionExtraDatum { - public: - InkActionExtraDatum(Glib::ustring& label, Glib::ustring& section, Glib::ustring& tooltip) - : action_label(label) - , action_section(section) - , action_tooltip(tooltip) - { - } - - Glib::ustring get_label() { return action_label; } - Glib::ustring get_section() { return action_section; } - Glib::ustring get_tooltip() { return action_tooltip; } - - private: - Glib::ustring action_label; - Glib::ustring action_section; - Glib::ustring action_tooltip; +class InkActionExtraDatum +{ +public: + InkActionExtraDatum(Glib::ustring &label, Glib::ustring §ion, Glib::ustring &tooltip) + : action_label(label) + , action_section(section) + , action_tooltip(tooltip) + {} + + Glib::ustring get_label() { return action_label; } + Glib::ustring get_section() { return action_section; } + Glib::ustring get_tooltip() { return action_tooltip; } + +private: + Glib::ustring action_label; + Glib::ustring action_section; + Glib::ustring action_tooltip; }; -class InkActionExtraData { - - public: - InkActionExtraData() = default; +class InkActionExtraData +{ +public: + InkActionExtraData() = default; - void add_data(std::vector> &raw_data); + void add_data(std::vector> &raw_data); - Glib::ustring get_label_for_action(Glib::ustring& action_name); - Glib::ustring get_section_for_action(Glib::ustring& action_name); - Glib::ustring get_tooltip_for_action(Glib::ustring& action_name); + Glib::ustring get_label_for_action(Glib::ustring &action_name); + Glib::ustring get_section_for_action(Glib::ustring &action_name); + Glib::ustring get_tooltip_for_action(Glib::ustring &action_name); - private: - std::map data; +private: + std::map data; }; #endif // INK_ACTIONS_EXTRA_DATA_H diff --git a/src/actions/actions-file.cpp b/src/actions/actions-file.cpp index c7929cdfa1c355961cb4aec141ccfb52e01d82e3..6515f3a1ac9ad500db2d7fe7a660cc56d1d096b9 100644 --- a/src/actions/actions-file.cpp +++ b/src/actions/actions-file.cpp @@ -8,24 +8,22 @@ * */ -#include +#include "actions-file.h" -#include // Not ! To eventually allow a headless version! +#include // Not ! To eventually allow a headless version! #include +#include -#include "actions-file.h" #include "actions-helper.h" -#include "inkscape-application.h" - -#include "inkscape.h" // Inkscape::Application #include "helper/action-context.h" +#include "inkscape-application.h" +#include "inkscape.h" // Inkscape::Application // Actions for file handling (should be integrated with file dialog). -void -file_open(const Glib::VariantBase& value, InkscapeApplication *app) +void file_open(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant s = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant s = Glib::VariantBase::cast_dynamic>(value); Glib::RefPtr file = Gio::File::create_for_path(s.get()); if (!file->query_exists()) { @@ -44,10 +42,9 @@ file_open(const Glib::VariantBase& value, InkscapeApplication *app) document->ensureUpToDate(); } -void -file_new(const Glib::VariantBase& value, InkscapeApplication *app) +void file_new(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant s = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant s = Glib::VariantBase::cast_dynamic>(value); SPDocument *document = app->document_new(s.get()); INKSCAPE.add_document(document); @@ -67,8 +64,7 @@ file_new(const Glib::VariantBase& value, InkscapeApplication *app) // app->document_revert(app->get_current_document()); // } -void -file_close(InkscapeApplication *app) +void file_close(InkscapeApplication *app) { SPDocument *document = app->get_active_document(); app->document_close(document); @@ -94,8 +90,7 @@ file_close(InkscapeApplication *app) // file_quit ... should just be quit // file_template -std::vector> raw_data_file = -{ +std::vector> raw_data_file = { // clang-format off {"app.file-open", "FileOpen", "File", N_("Open file.") }, {"app.file-new", "FileNew", "File", N_("Open new document using template.") }, @@ -104,11 +99,10 @@ std::vector> raw_data_file = }; template -void -add_actions_file(ConcreteInkscapeApplication* app) +void add_actions_file(ConcreteInkscapeApplication *app) { - Glib::VariantType Bool( Glib::VARIANT_TYPE_BOOL); - Glib::VariantType Int( Glib::VARIANT_TYPE_INT32); + Glib::VariantType Bool(Glib::VARIANT_TYPE_BOOL); + Glib::VariantType Int(Glib::VARIANT_TYPE_INT32); Glib::VariantType Double(Glib::VARIANT_TYPE_DOUBLE); Glib::VariantType String(Glib::VARIANT_TYPE_STRING); Glib::VariantType BString(Glib::VARIANT_TYPE_BYTESTRING); @@ -122,17 +116,15 @@ add_actions_file(ConcreteInkscapeApplication* app) app->add_action( "file-close", sigc::bind(sigc::ptr_fun(&file_close), app)); // clang-format on #else - std::cerr << "add_actions: Some actions require Glibmm 2.52, compiled with: " << glib_major_version << "." << glib_minor_version << std::endl; + std::cerr << "add_actions: Some actions require Glibmm 2.52, compiled with: " << glib_major_version << "." + << glib_minor_version << std::endl; #endif app->get_action_extra_data().add_data(raw_data_file); } - -template void add_actions_file(ConcreteInkscapeApplication* app); -template void add_actions_file(ConcreteInkscapeApplication* app); - - +template void add_actions_file(ConcreteInkscapeApplication *app); +template void add_actions_file(ConcreteInkscapeApplication *app); /* Local Variables: diff --git a/src/actions/actions-file.h b/src/actions/actions-file.h index b4a0b228c37a45fb5223e2a3dc53b863fa6361f7..bf18361f8172954a46af02f0131b47d26bda67ce 100644 --- a/src/actions/actions-file.h +++ b/src/actions/actions-file.h @@ -12,10 +12,11 @@ #define INK_ACTIONS_FILE_H class InkscapeApplication; -template class ConcreteInkscapeApplication; +template +class ConcreteInkscapeApplication; -template -void add_actions_file(ConcreteInkscapeApplication* app); +template +void add_actions_file(ConcreteInkscapeApplication *app); #endif // INK_ACTIONS_FILE_H diff --git a/src/actions/actions-helper.cpp b/src/actions/actions-helper.cpp index e72a15dad1573c94afee154451e05bef6d2a3292..ecce2b1507cc68da06ca175ec1ae17835dedbd83 100644 --- a/src/actions/actions-helper.cpp +++ b/src/actions/actions-helper.cpp @@ -16,8 +16,7 @@ // Helper function: returns true if both document and selection found. Maybe this should // work on current view. Or better, application could return the selection of the current view. -bool -get_document_and_selection(InkscapeApplication* app, SPDocument** document, Inkscape::Selection** selection) +bool get_document_and_selection(InkscapeApplication *app, SPDocument **document, Inkscape::Selection **selection) { *document = app->get_active_document(); if (!(*document)) { diff --git a/src/actions/actions-helper.h b/src/actions/actions-helper.h index da65e10ac4db2d41015272275d3b4a085a4d5bca..7b852cefa75097e33cf051eebe977dcf8d708076 100644 --- a/src/actions/actions-helper.h +++ b/src/actions/actions-helper.h @@ -14,11 +14,10 @@ class InkscapeApplication; class SPDocument; namespace Inkscape { - class Selection; +class Selection; } -bool get_document_and_selection(InkscapeApplication* app, SPDocument** document, Inkscape::Selection** selection); - +bool get_document_and_selection(InkscapeApplication *app, SPDocument **document, Inkscape::Selection **selection); #endif // INK_ACTIONS_HELPER_H diff --git a/src/actions/actions-object.cpp b/src/actions/actions-object.cpp index 1d860123a5e44dbc3f9e6605d18916ba40a09025..970516289354080e9fde94674b22b84936ab0c5a 100644 --- a/src/actions/actions-object.cpp +++ b/src/actions/actions-object.cpp @@ -8,26 +8,23 @@ * */ -#include +#include "actions-object.h" -#include // Not ! To eventually allow a headless version! +#include // Not ! To eventually allow a headless version! #include +#include -#include "actions-object.h" #include "actions-helper.h" #include "document-undo.h" #include "inkscape-application.h" - -#include "inkscape.h" // Inkscape::Application -#include "selection.h" // Selection +#include "inkscape.h" // Inkscape::Application #include "path/path-simplify.h" - +#include "selection.h" // Selection // No sanity checking is done... should probably add. -void -object_set_attribute(const Glib::VariantBase& value, InkscapeApplication *app) +void object_set_attribute(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant s = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant s = Glib::VariantBase::cast_dynamic>(value); std::vector tokens = Glib::Regex::split_simple(",", s.get()); if (tokens.size() != 2) { @@ -52,12 +49,10 @@ object_set_attribute(const Glib::VariantBase& value, InkscapeApplication *app) Inkscape::DocumentUndo::done(app->get_active_document(), 0, "ActionObjectSetAttribute"); } - // No sanity checking is done... should probably add. -void -object_set_property(const Glib::VariantBase& value, InkscapeApplication *app) +void object_set_property(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant s = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant s = Glib::VariantBase::cast_dynamic>(value); std::vector tokens = Glib::Regex::split_simple(",", s.get()); if (tokens.size() != 2) { @@ -85,61 +80,51 @@ object_set_property(const Glib::VariantBase& value, InkscapeApplication *app) Inkscape::DocumentUndo::done(app->get_active_document(), 0, "ActionObjectSetProperty"); } - -void -object_unlink_clones(InkscapeApplication *app) +void object_unlink_clones(InkscapeApplication *app) { auto selection = app->get_active_selection(); // We should not have to do this! - auto document = app->get_active_document(); + auto document = app->get_active_document(); selection->setDocument(document); selection->unlink(); } - -void -object_to_path(InkscapeApplication *app) +void object_to_path(InkscapeApplication *app) { auto selection = app->get_active_selection(); // We should not have to do this! - auto document = app->get_active_document(); + auto document = app->get_active_document(); selection->setDocument(document); - selection->toCurves(); // TODO: Rename toPaths() + selection->toCurves(); // TODO: Rename toPaths() } - -void -object_stroke_to_path(InkscapeApplication *app) +void object_stroke_to_path(InkscapeApplication *app) { auto selection = app->get_active_selection(); // We should not have to do this! - auto document = app->get_active_document(); + auto document = app->get_active_document(); selection->setDocument(document); selection->strokesToPaths(); } - -void -object_simplify_path(InkscapeApplication *app) +void object_simplify_path(InkscapeApplication *app) { auto selection = app->get_active_selection(); // We should not have to do this! - auto document = app->get_active_document(); + auto document = app->get_active_document(); selection->setDocument(document); selection->simplifyPaths(); } - -std::vector> raw_data_object = -{ +std::vector> raw_data_object = { // clang-format off {"app.object-set-attribute", "ObjectSetAttribute", "Object", N_("Set or update an attribute on selected objects. Usage: object-set-attribute:attribute name, attribute value;")}, {"app.object-set-property", "ObjectSetProperty", "Object", N_("Set or update a property on selected objects. Usage: object-set-property:property name, property value;")}, @@ -150,12 +135,11 @@ std::vector> raw_data_object = // clang-format on }; -template -void -add_actions_object(ConcreteInkscapeApplication* app) +template +void add_actions_object(ConcreteInkscapeApplication *app) { - Glib::VariantType Bool( Glib::VARIANT_TYPE_BOOL); - Glib::VariantType Int( Glib::VARIANT_TYPE_INT32); + Glib::VariantType Bool(Glib::VARIANT_TYPE_BOOL); + Glib::VariantType Int(Glib::VARIANT_TYPE_INT32); Glib::VariantType Double(Glib::VARIANT_TYPE_DOUBLE); Glib::VariantType String(Glib::VARIANT_TYPE_STRING); @@ -176,11 +160,8 @@ add_actions_object(ConcreteInkscapeApplication* app) app->get_action_extra_data().add_data(raw_data_object); } - -template void add_actions_object(ConcreteInkscapeApplication* app); -template void add_actions_object(ConcreteInkscapeApplication* app); - - +template void add_actions_object(ConcreteInkscapeApplication *app); +template void add_actions_object(ConcreteInkscapeApplication *app); /* Local Variables: diff --git a/src/actions/actions-object.h b/src/actions/actions-object.h index dbde5435dc55c31fb4f99625cc72c6b6a484e3ad..bd0907a0166ac5ebee9ab3e7cb9c7129c4d92e04 100644 --- a/src/actions/actions-object.h +++ b/src/actions/actions-object.h @@ -11,10 +11,11 @@ #ifndef INK_ACTIONS_OBJECT_H #define INK_ACTIONS_OBJECT_H -template class ConcreteInkscapeApplication; +template +class ConcreteInkscapeApplication; -template -void add_actions_object(ConcreteInkscapeApplication* app); +template +void add_actions_object(ConcreteInkscapeApplication *app); #endif // INK_ACTIONS_OBJECT_H diff --git a/src/actions/actions-output.cpp b/src/actions/actions-output.cpp index 5ab5078217c695f68b6da1d5b253a66ceaea3942..342b222d11ed4f7d40369a7654188f9576f1b72c 100644 --- a/src/actions/actions-output.cpp +++ b/src/actions/actions-output.cpp @@ -8,202 +8,178 @@ * */ -#include +#include "actions-output.h" -#include // Not ! To eventually allow a headless version! +#include // Not ! To eventually allow a headless version! #include +#include -#include "actions-output.h" #include "actions-helper.h" #include "inkscape-application.h" - -#include "inkscape.h" // Inkscape::Application +#include "inkscape.h" // Inkscape::Application // Actions for command line output (should be integrated with file dialog). // These actions are currently stateless and result in changes to an instance of the // InkFileExportCmd class owned by the application. -void -export_type(const Glib::VariantBase& value, InkscapeApplication *app) +void export_type(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant s = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant s = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_type = s.get(); // std::cout << "export-type: " << s.get() << std::endl; } -void -export_filename(const Glib::VariantBase& value, InkscapeApplication *app) +void export_filename(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant s = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant s = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_filename = s.get(); // std::cout << "export-filename: " << s.get() << std::endl; } -void -export_overwrite(const Glib::VariantBase& value, InkscapeApplication *app) +void export_overwrite(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant b = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant b = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_overwrite = b.get(); // std::cout << "export-overwrite: " << std::boolalpha << b.get() << std::endl; } -void -export_area(const Glib::VariantBase& value, InkscapeApplication *app) +void export_area(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant s = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant s = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_area = s.get(); // std::cout << "export-area: " << s.get() << std::endl; } -void -export_area_drawing(const Glib::VariantBase& value, InkscapeApplication *app) +void export_area_drawing(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant b = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant b = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_area_drawing = b.get(); // std::cout << "export-area-drawing: " << std::boolalpha << b.get() << std::endl; } -void -export_area_page(const Glib::VariantBase& value, InkscapeApplication *app) +void export_area_page(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant b = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant b = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_area_page = b.get(); // std::cout << "export-area-page: " << std::boolalpha << b.get() << std::endl; } -void -export_margin(const Glib::VariantBase& value, InkscapeApplication *app) +void export_margin(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant i = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant i = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_margin = i.get(); // std::cout << "export-margin: " << i.get() << std::endl; } -void -export_area_snap(const Glib::VariantBase& value, InkscapeApplication *app) +void export_area_snap(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant b = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant b = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_area_snap = b.get(); // std::cout << "export-area-snap: " << std::boolalpha << b.get() << std::endl; } -void -export_width(const Glib::VariantBase& value, InkscapeApplication *app) +void export_width(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant i = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant i = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_width = i.get(); // std::cout << "export-width: " << i.get() << std::endl; } -void -export_height(const Glib::VariantBase& value, InkscapeApplication *app) +void export_height(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant i = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant i = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_height = i.get(); // std::cout << "export-height: " << i.get() << std::endl; } -void -export_id(const Glib::VariantBase& value, InkscapeApplication *app) +void export_id(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant s = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant s = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_id = s.get(); // std::cout << "export-id: " << s.get() << std::endl; } -void -export_id_only(const Glib::VariantBase& value, InkscapeApplication *app) +void export_id_only(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant b = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant b = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_id_only = b.get(); // std::cout << "export-id-only: " << std::boolalpha << b.get() << std::endl; } -void -export_plain_svg(const Glib::VariantBase& value, InkscapeApplication *app) +void export_plain_svg(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant b = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant b = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_plain_svg = b.get(); // std::cout << "export-plain-svg: " << std::boolalpha << b.get() << std::endl; } -void -export_dpi(const Glib::VariantBase& value, InkscapeApplication *app) +void export_dpi(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant d = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant d = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_dpi = d.get(); // std::cout << "export-dpi: " << d.get() << std::endl; } -void -export_ignore_filters(const Glib::VariantBase& value, InkscapeApplication *app) +void export_ignore_filters(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant b = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant b = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_ignore_filters = b.get(); // std::cout << "export-ignore-filters: " << std::boolalpha << b.get() << std::endl; } -void -export_text_to_path(const Glib::VariantBase& value, InkscapeApplication *app) +void export_text_to_path(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant b = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant b = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_text_to_path = b.get(); // std::cout << "export-text-to-path: " << std::boolalpha << b.get() << std::endl; } -void -export_ps_level(const Glib::VariantBase& value, InkscapeApplication *app) +void export_ps_level(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant i = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant i = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_ps_level = i.get(); // std::cout << "export-ps-level: " << i.get() << std::endl; } -void -export_pdf_level(const Glib::VariantBase& value, InkscapeApplication *app) +void export_pdf_level(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant s = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant s = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_pdf_level = s.get(); // std::cout << "export-pdf-level" << s.get() << std::endl; } -void -export_latex(const Glib::VariantBase& value, InkscapeApplication *app) +void export_latex(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant b = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant b = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_latex = b.get(); // std::cout << "export-latex: " << std::boolalpha << b.get() << std::endl; } -void -export_use_hints(const Glib::VariantBase& value, InkscapeApplication *app) +void export_use_hints(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant b = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant b = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_use_hints = b.get(); // std::cout << "export-use-hints: " << std::boolalpha << b.get() << std::endl; } -void -export_background(const Glib::VariantBase& value, InkscapeApplication *app) +void export_background(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant s = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant s = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_background = s.get(); // std::cout << "export-background: " << s.get() << std::endl; } -void -export_background_opacity(const Glib::VariantBase& value, InkscapeApplication *app) +void export_background_opacity(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant d = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant d = Glib::VariantBase::cast_dynamic>(value); app->file_export()->export_background_opacity = d.get(); // std::cout << d.get() << std::endl; } -void -export_do(InkscapeApplication *app) +void export_do(InkscapeApplication *app) { - SPDocument* document = app->get_active_document(); + SPDocument *document = app->get_active_document(); std::string filename; if (document->getDocumentURI()) { filename = document->getDocumentURI(); @@ -211,8 +187,7 @@ export_do(InkscapeApplication *app) app->file_export()->do_export(document, filename); } -std::vector> raw_data_output = -{ +std::vector> raw_data_output = { // clang-format off {"app.export-type", "ExportType", "Export", N_("Export file type.") }, {"app.export-filename", "ExportFileName", "Export", N_("Export file name.") }, @@ -245,11 +220,10 @@ std::vector> raw_data_output = }; template -void -add_actions_output(ConcreteInkscapeApplication* app) +void add_actions_output(ConcreteInkscapeApplication *app) { - Glib::VariantType Bool( Glib::VARIANT_TYPE_BOOL); - Glib::VariantType Int( Glib::VARIANT_TYPE_INT32); + Glib::VariantType Bool(Glib::VARIANT_TYPE_BOOL); + Glib::VariantType Int(Glib::VARIANT_TYPE_INT32); Glib::VariantType Double(Glib::VARIANT_TYPE_DOUBLE); Glib::VariantType String(Glib::VARIANT_TYPE_STRING); Glib::VariantType BString(Glib::VARIANT_TYPE_BYTESTRING); @@ -289,17 +263,15 @@ add_actions_output(ConcreteInkscapeApplication* app) app->add_action( "export-do", sigc::bind(sigc::ptr_fun(&export_do), app)); // clang-format on #else - std::cerr << "add_actions: Some actions require Glibmm 2.52, compiled with: " << glib_major_version << "." << glib_minor_version << std::endl; + std::cerr << "add_actions: Some actions require Glibmm 2.52, compiled with: " << glib_major_version << "." + << glib_minor_version << std::endl; #endif app->get_action_extra_data().add_data(raw_data_output); } - -template void add_actions_output(ConcreteInkscapeApplication* app); -template void add_actions_output(ConcreteInkscapeApplication* app); - - +template void add_actions_output(ConcreteInkscapeApplication *app); +template void add_actions_output(ConcreteInkscapeApplication *app); /* Local Variables: diff --git a/src/actions/actions-output.h b/src/actions/actions-output.h index 01ea455f73929ff6b91beff16199c6be29d5206b..6f8e21ab561e708af202816fabe657c140157735 100644 --- a/src/actions/actions-output.h +++ b/src/actions/actions-output.h @@ -12,10 +12,11 @@ #define INK_ACTIONS_OUTPUT_H class InkscapeApplication; -template class ConcreteInkscapeApplication; +template +class ConcreteInkscapeApplication; -template -void add_actions_output(ConcreteInkscapeApplication* app); +template +void add_actions_output(ConcreteInkscapeApplication *app); #endif // INK_ACTIONS_OUTPUT_H diff --git a/src/actions/actions-selection.cpp b/src/actions/actions-selection.cpp index 468c233ac310f26149f2674266563d51772ee6c1..c12be0e97ac5f2885401eef5b236246e1962e6ed 100644 --- a/src/actions/actions-selection.cpp +++ b/src/actions/actions-selection.cpp @@ -8,44 +8,40 @@ * */ -#include +#include "actions-selection.h" -#include // Not ! To eventually allow a headless version! +#include // Not ! To eventually allow a headless version! #include +#include -#include "actions-selection.h" #include "actions-helper.h" #include "inkscape-application.h" - #include "inkscape.h" // Inkscape::Application -#include "selection.h" // Selection - -#include "object/sp-root.h" // select_all: document->getRoot(); #include "object/sp-item-group.h" // select_all +#include "object/sp-root.h" // select_all: document->getRoot(); +#include "selection.h" // Selection -void -select_clear(InkscapeApplication* app) +void select_clear(InkscapeApplication *app) { - SPDocument* document = nullptr; - Inkscape::Selection* selection = nullptr; + SPDocument *document = nullptr; + Inkscape::Selection *selection = nullptr; if (!get_document_and_selection(app, &document, &selection)) { return; } selection->clear(); } -void -select_by_id(Glib::ustring ids, InkscapeApplication* app) +void select_by_id(Glib::ustring ids, InkscapeApplication *app) { - SPDocument* document = nullptr; - Inkscape::Selection* selection = nullptr; + SPDocument *document = nullptr; + Inkscape::Selection *selection = nullptr; if (!get_document_and_selection(app, &document, &selection)) { return; } auto tokens = Glib::Regex::split_simple("\\s*,\\s*", ids); for (auto id : tokens) { - SPObject* object = document->getObjectById(id); + SPObject *object = document->getObjectById(id); if (object) { selection->add(object); } else { @@ -54,18 +50,17 @@ select_by_id(Glib::ustring ids, InkscapeApplication* app) } } -void -unselect_by_id(Glib::ustring ids, InkscapeApplication* app) +void unselect_by_id(Glib::ustring ids, InkscapeApplication *app) { - SPDocument* document = nullptr; - Inkscape::Selection* selection = nullptr; + SPDocument *document = nullptr; + Inkscape::Selection *selection = nullptr; if (!get_document_and_selection(app, &document, &selection)) { return; } auto tokens = Glib::Regex::split_simple("\\s*,\\s*", ids); for (auto id : tokens) { - SPObject* object = document->getObjectById(id); + SPObject *object = document->getObjectById(id); if (object) { selection->remove(object); } else { @@ -74,11 +69,10 @@ unselect_by_id(Glib::ustring ids, InkscapeApplication* app) } } -void -select_by_class(Glib::ustring klass, InkscapeApplication* app) +void select_by_class(Glib::ustring klass, InkscapeApplication *app) { - SPDocument* document = nullptr; - Inkscape::Selection* selection = nullptr; + SPDocument *document = nullptr; + Inkscape::Selection *selection = nullptr; if (!get_document_and_selection(app, &document, &selection)) { return; } @@ -87,11 +81,10 @@ select_by_class(Glib::ustring klass, InkscapeApplication* app) selection->add(objects.begin(), objects.end()); } -void -select_by_element(Glib::ustring element, InkscapeApplication* app) +void select_by_element(Glib::ustring element, InkscapeApplication *app) { - SPDocument* document = nullptr; - Inkscape::Selection* selection = nullptr; + SPDocument *document = nullptr; + Inkscape::Selection *selection = nullptr; if (!get_document_and_selection(app, &document, &selection)) { return; } @@ -99,11 +92,10 @@ select_by_element(Glib::ustring element, InkscapeApplication* app) selection->add(objects.begin(), objects.end()); } -void -select_by_selector(Glib::ustring selector, InkscapeApplication* app) +void select_by_selector(Glib::ustring selector, InkscapeApplication *app) { - SPDocument* document = nullptr; - Inkscape::Selection* selection = nullptr; + SPDocument *document = nullptr; + Inkscape::Selection *selection = nullptr; if (!get_document_and_selection(app, &document, &selection)) { return; } @@ -112,10 +104,8 @@ select_by_selector(Glib::ustring selector, InkscapeApplication* app) selection->add(objects.begin(), objects.end()); } - // Helper -void -get_all_items_recursive(std::vector &objects, SPObject *object, Glib::ustring &condition) +void get_all_items_recursive(std::vector &objects, SPObject *object, Glib::ustring &condition) { for (auto &o : object->childList(false)) { if (dynamic_cast(o)) { @@ -150,7 +140,6 @@ get_all_items_recursive(std::vector &objects, SPObject *object, Glib } } - /* * 'layers': All layers. * 'groups': All groups (including layers). @@ -160,17 +149,17 @@ get_all_items_recursive(std::vector &objects, SPObject *object, Glib * * Note: GUI "Select All" requires knowledge of selected layer, which is a desktop property. */ -void -select_all(Glib::ustring condition, InkscapeApplication* app) +void select_all(Glib::ustring condition, InkscapeApplication *app) { - if (condition != "" && condition != "layers" && condition != "no-layers" && - condition != "groups" && condition != "no-groups" && condition != "all") { - std::cerr << "select_all: allowed options are '', 'all', 'layers', 'no-layers', 'groups', and 'no-groups'" << std::endl; + if (condition != "" && condition != "layers" && condition != "no-layers" && condition != "groups" && + condition != "no-groups" && condition != "all") { + std::cerr << "select_all: allowed options are '', 'all', 'layers', 'no-layers', 'groups', and 'no-groups'" + << std::endl; return; } - SPDocument* document = nullptr; - Inkscape::Selection* selection = nullptr; + SPDocument *document = nullptr; + Inkscape::Selection *selection = nullptr; if (!get_document_and_selection(app, &document, &selection)) { return; } @@ -182,17 +171,17 @@ select_all(Glib::ustring condition, InkscapeApplication* app) } /* See above for conditions. */ -void -select_invert(Glib::ustring condition, InkscapeApplication* app) +void select_invert(Glib::ustring condition, InkscapeApplication *app) { - if (condition != "" && condition != "layers" && condition != "no-layers" && - condition != "groups" && condition != "no-groups" && condition != "all") { - std::cerr << "select_all: allowed options are '', 'all', 'layers', 'no-layers', 'groups', and 'no-groups'" << std::endl; + if (condition != "" && condition != "layers" && condition != "no-layers" && condition != "groups" && + condition != "no-groups" && condition != "all") { + std::cerr << "select_all: allowed options are '', 'all', 'layers', 'no-layers', 'groups', and 'no-groups'" + << std::endl; return; } - SPDocument* document = nullptr; - Inkscape::Selection* selection = nullptr; + SPDocument *document = nullptr; + Inkscape::Selection *selection = nullptr; if (!get_document_and_selection(app, &document, &selection)) { return; } @@ -205,23 +194,21 @@ select_invert(Glib::ustring condition, InkscapeApplication* app) std::vector current(selection->items().begin(), selection->items().end()); // Remove current selection from object vector (using "erase remove_if idiom"). - objects.erase( - std::remove_if(std::begin(objects), std::end(objects), [¤t](const SPObject *x) - { - return (std::find(current.begin(), current.end(), x) != current.end()); - }), objects.end()); + objects.erase(std::remove_if(std::begin(objects), std::end(objects), + [¤t](const SPObject *x) { + return (std::find(current.begin(), current.end(), x) != current.end()); + }), + objects.end()); // Set selection to object vector. selection->setList(objects); } - // Debug... print selected items -void -select_list(InkscapeApplication* app) +void select_list(InkscapeApplication *app) { - SPDocument* document = nullptr; - Inkscape::Selection* selection = nullptr; + SPDocument *document = nullptr; + Inkscape::Selection *selection = nullptr; if (!get_document_and_selection(app, &document, &selection)) { return; } @@ -233,8 +220,7 @@ select_list(InkscapeApplication* app) } // SHOULD REALLY BE DOC ACTIONS -std::vector> raw_data_selection = -{ +std::vector> raw_data_selection = { // clang-format off {"app.select-clear", "SelectClear", "Select", N_("Selection clear") }, {"app.select", "Select", "Select", N_("Select by ID (Deprecated)") }, @@ -250,9 +236,8 @@ std::vector> raw_data_selection = // clang-format on }; -template -void -add_actions_selection(ConcreteInkscapeApplication* app) +template +void add_actions_selection(ConcreteInkscapeApplication *app) { // clang-format off app->add_action( "select-clear", sigc::bind(sigc::ptr_fun(&select_clear), app) ); @@ -271,12 +256,8 @@ add_actions_selection(ConcreteInkscapeApplication* app) app->get_action_extra_data().add_data(raw_data_selection); } -template void add_actions_selection(ConcreteInkscapeApplication* app); -template void add_actions_selection(ConcreteInkscapeApplication* app); - - - - +template void add_actions_selection(ConcreteInkscapeApplication *app); +template void add_actions_selection(ConcreteInkscapeApplication *app); /* Local Variables: diff --git a/src/actions/actions-selection.h b/src/actions/actions-selection.h index f792a5cb863e8f9781ed48231a247749caa33e0b..a07aece7b26a7ba20292438e9c02de2dca13bccd 100644 --- a/src/actions/actions-selection.h +++ b/src/actions/actions-selection.h @@ -11,10 +11,11 @@ #ifndef INK_ACTIONS_SELECTION_H #define INK_ACTIONS_SELECTION_H -template class ConcreteInkscapeApplication; +template +class ConcreteInkscapeApplication; -template -void add_actions_selection(ConcreteInkscapeApplication* app); +template +void add_actions_selection(ConcreteInkscapeApplication *app); #endif // INK_ACTIONS_SELECTION_H diff --git a/src/actions/actions-transform.cpp b/src/actions/actions-transform.cpp index 1f5fc843e2f8f785816defafef4514acae4a1e8e..431ef57caf112b6645d72a3e787ac3d1b521a993 100644 --- a/src/actions/actions-transform.cpp +++ b/src/actions/actions-transform.cpp @@ -8,23 +8,21 @@ * */ -#include +#include "actions-transform.h" -#include // Not ! To eventually allow a headless version! +#include // Not ! To eventually allow a headless version! #include +#include -#include "actions-transform.h" #include "actions-helper.h" #include "document-undo.h" #include "inkscape-application.h" +#include "inkscape.h" // Inkscape::Application +#include "selection.h" // Selection -#include "inkscape.h" // Inkscape::Application -#include "selection.h" // Selection - -void -transform_translate(const Glib::VariantBase& value, InkscapeApplication *app) +void transform_translate(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant s = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant s = Glib::VariantBase::cast_dynamic>(value); std::vector tokens = Glib::Regex::split_simple(",", s.get()); if (tokens.size() != 2) { @@ -49,11 +47,9 @@ transform_translate(const Glib::VariantBase& value, InkscapeApplication *app) Inkscape::DocumentUndo::done(app->get_active_document(), 0, "ActionTransformTranslate"); } -void -transform_rotate(const Glib::VariantBase& value, InkscapeApplication *app) +void transform_rotate(const Glib::VariantBase &value, InkscapeApplication *app) { - - Glib::Variant d = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant d = Glib::VariantBase::cast_dynamic>(value); auto selection = app->get_active_selection(); selection->rotate(d.get()); @@ -62,10 +58,9 @@ transform_rotate(const Glib::VariantBase& value, InkscapeApplication *app) Inkscape::DocumentUndo::done(app->get_active_document(), 0, "ActionTransformRotate"); } -void -transform_scale(const Glib::VariantBase& value, InkscapeApplication *app) +void transform_scale(const Glib::VariantBase &value, InkscapeApplication *app) { - Glib::Variant d = Glib::VariantBase::cast_dynamic >(value); + Glib::Variant d = Glib::VariantBase::cast_dynamic>(value); auto selection = app->get_active_selection(); selection->scale(d.get()); @@ -73,8 +68,7 @@ transform_scale(const Glib::VariantBase& value, InkscapeApplication *app) Inkscape::DocumentUndo::done(app->get_active_document(), 0, "ActionTransformScale"); } -void -transform_remove(InkscapeApplication *app) +void transform_remove(InkscapeApplication *app) { auto selection = app->get_active_selection(); selection->removeTransform(); @@ -84,8 +78,7 @@ transform_remove(InkscapeApplication *app) } // SHOULD REALLY BE DOC LEVEL ACTIONS -std::vector> raw_data_transform = -{ +std::vector> raw_data_transform = { // clang-format off {"app.transform-translate", "TransformTranslate", "Transform", N_("Translate selected objects (dx,dy).") }, {"app.transform-rotate", "TransformRotate", "Transform", N_("Rotate selected objects by degrees.") }, @@ -94,12 +87,11 @@ std::vector> raw_data_transform = // clang-format on }; -template -void -add_actions_transform(ConcreteInkscapeApplication* app) +template +void add_actions_transform(ConcreteInkscapeApplication *app) { - Glib::VariantType Bool( Glib::VARIANT_TYPE_BOOL); - Glib::VariantType Int( Glib::VARIANT_TYPE_INT32); + Glib::VariantType Bool(Glib::VARIANT_TYPE_BOOL); + Glib::VariantType Int(Glib::VARIANT_TYPE_INT32); Glib::VariantType Double(Glib::VARIANT_TYPE_DOUBLE); Glib::VariantType String(Glib::VARIANT_TYPE_STRING); @@ -118,11 +110,8 @@ add_actions_transform(ConcreteInkscapeApplication* app) app->get_action_extra_data().add_data(raw_data_transform); } - -template void add_actions_transform(ConcreteInkscapeApplication* app); -template void add_actions_transform(ConcreteInkscapeApplication* app); - - +template void add_actions_transform(ConcreteInkscapeApplication *app); +template void add_actions_transform(ConcreteInkscapeApplication *app); /* Local Variables: diff --git a/src/actions/actions-transform.h b/src/actions/actions-transform.h index 03c2afd97f5bb61f3d9cb9cde1c06fd0fee7bc17..eeb4aadb0914f1050e0de32e0bffe296a344b07e 100644 --- a/src/actions/actions-transform.h +++ b/src/actions/actions-transform.h @@ -11,10 +11,11 @@ #ifndef INK_ACTIONS_TRANSFORM_H #define INK_ACTIONS_TRANSFORM_H -template class ConcreteInkscapeApplication; +template +class ConcreteInkscapeApplication; -template -void add_actions_transform(ConcreteInkscapeApplication* app); +template +void add_actions_transform(ConcreteInkscapeApplication *app); #endif // INK_ACTIONS_TRANSFORM_H diff --git a/src/actions/actions-window.cpp b/src/actions/actions-window.cpp index 238e91539b79b9cc3fa0870e45ad6c0cb1424940..f93942f9adda105847da5f53831011c3545abf9e 100644 --- a/src/actions/actions-window.cpp +++ b/src/actions/actions-window.cpp @@ -8,33 +8,31 @@ * */ -#include +#include "actions-window.h" -#include // Not ! To eventually allow a headless version! +#include // Not ! To eventually allow a headless version! #include +#include -#include "actions-window.h" #include "actions-helper.h" +#include "helper/action-context.h" #include "inkscape-application.h" #include "inkscape-window.h" - -#include "inkscape.h" // Inkscape::Application -#include "helper/action-context.h" +#include "inkscape.h" // Inkscape::Application // Actions for window handling (should be integrated with file dialog). class InkscapeWindow; // Open a window for current document -void -window_open(InkscapeApplication *app) +void window_open(InkscapeApplication *app) { SPDocument *document = app->get_active_document(); if (document) { - InkscapeWindow* window = app->get_active_window(); + InkscapeWindow *window = app->get_active_window(); if (window && window->get_document() && window->get_document()->getVirgin()) { // We have a window with an untouched template document, use this window. - app->document_swap (window, document); + app->document_swap(window, document); } else { app->window_open(document); } @@ -43,14 +41,12 @@ window_open(InkscapeApplication *app) } } -void -window_close(InkscapeApplication *app) +void window_close(InkscapeApplication *app) { app->window_close_active(); } -std::vector> raw_data_window = -{ +std::vector> raw_data_window = { // clang-format off {"app.window-open", "WindowOpen", "Window", N_("Open a window for the active document. GUI only.") }, {"app.window-close", "WindowClose", "Window", N_("Close the active window.") } @@ -58,11 +54,10 @@ std::vector> raw_data_window = }; template -void -add_actions_window(ConcreteInkscapeApplication* app) +void add_actions_window(ConcreteInkscapeApplication *app) { - Glib::VariantType Bool( Glib::VARIANT_TYPE_BOOL); - Glib::VariantType Int( Glib::VARIANT_TYPE_INT32); + Glib::VariantType Bool(Glib::VARIANT_TYPE_BOOL); + Glib::VariantType Int(Glib::VARIANT_TYPE_INT32); Glib::VariantType Double(Glib::VARIANT_TYPE_DOUBLE); Glib::VariantType String(Glib::VARIANT_TYPE_STRING); Glib::VariantType BString(Glib::VARIANT_TYPE_BYTESTRING); @@ -75,17 +70,15 @@ add_actions_window(ConcreteInkscapeApplication* app) app->add_action( "window-close", sigc::bind(sigc::ptr_fun(&window_close), app)); // clang-format on #else - std::cerr << "add_actions: Some actions require Glibmm 2.52, compiled with: " << glib_major_version << "." << glib_minor_version << std::endl; + std::cerr << "add_actions: Some actions require Glibmm 2.52, compiled with: " << glib_major_version << "." + << glib_minor_version << std::endl; #endif app->get_action_extra_data().add_data(raw_data_window); } - -template void add_actions_window(ConcreteInkscapeApplication* app); -template void add_actions_window(ConcreteInkscapeApplication* app); - - +template void add_actions_window(ConcreteInkscapeApplication *app); +template void add_actions_window(ConcreteInkscapeApplication *app); /* Local Variables: diff --git a/src/actions/actions-window.h b/src/actions/actions-window.h index a9f74185f795fb89f24f5946cc14cf02f38f5b68..3ef49311cebd0c1855a961e28379d226f2f4b6fa 100644 --- a/src/actions/actions-window.h +++ b/src/actions/actions-window.h @@ -12,10 +12,11 @@ #define INK_ACTIONS_WINDOW_H class InkscapeApplication; -template class ConcreteInkscapeApplication; +template +class ConcreteInkscapeApplication; -template -void add_actions_window(ConcreteInkscapeApplication* app); +template +void add_actions_window(ConcreteInkscapeApplication *app); #endif // INK_ACTIONS_WINDOW_H diff --git a/src/attribute-rel-css.cpp b/src/attribute-rel-css.cpp index f476d5083012b9dbe60722745b0686ab9c79ee5a..45b8fc1b1333b1fecb066a03aeb7a75ad233cdea 100644 --- a/src/attribute-rel-css.cpp +++ b/src/attribute-rel-css.cpp @@ -21,22 +21,22 @@ * mapping indirectly(only reading). */ +#include "attribute-rel-css.h" + #include -#include #include - -#include "attribute-rel-css.h" +#include #include "io/resource.h" #include "path-prefix.h" #include "preferences.h" -SPAttributeRelCSS * SPAttributeRelCSS::instance = nullptr; +SPAttributeRelCSS *SPAttributeRelCSS::instance = nullptr; bool SPAttributeRelCSS::foundFileProp = false; bool SPAttributeRelCSS::foundFileDefault = false; /* - * This function checks whether an element -> CSS property pair + * This function checks whether an element -> CSS property pair * is allowed or not */ bool SPAttributeRelCSS::findIfValid(Glib::ustring property, Glib::ustring element) @@ -44,14 +44,15 @@ bool SPAttributeRelCSS::findIfValid(Glib::ustring property, Glib::ustring elemen if (SPAttributeRelCSS::instance == nullptr) { SPAttributeRelCSS::instance = new SPAttributeRelCSS(); } - + // Always valid if data file not found! - if( !foundFileProp ) return true; + if (!foundFileProp) + return true; // Strip of "svg:" from the element's name Glib::ustring temp = element; - if ( temp.find("svg:") != std::string::npos ) { - temp.erase( temp.find("svg:"), 4 ); + if (temp.find("svg:") != std::string::npos) { + temp.erase(temp.find("svg:"), 4); } // Don't check for properties with -, role, aria etc. to allow for more accessibility @@ -68,16 +69,16 @@ bool SPAttributeRelCSS::findIfValid(Glib::ustring property, Glib::ustring elemen || property.substr(0,4) == "ns1:" // JessyInk || (SPAttributeRelCSS::instance->propertiesOfElements[temp].find(property) != SPAttributeRelCSS::instance->propertiesOfElements[temp].end()) ) { - // clang-format on + // clang-format on return true; } else { - //g_warning( "Invalid attribute: %s used on <%s>", property.c_str(), element.c_str() ); + // g_warning( "Invalid attribute: %s used on <%s>", property.c_str(), element.c_str() ); return false; } } /* - * This function checks whether an CSS property -> default value + * This function checks whether an CSS property -> default value * pair is allowed or not */ bool SPAttributeRelCSS::findIfDefault(Glib::ustring property, Glib::ustring value) @@ -87,9 +88,10 @@ bool SPAttributeRelCSS::findIfDefault(Glib::ustring property, Glib::ustring valu } // Always false if data file not found! - if( !foundFileDefault ) return false; + if (!foundFileDefault) + return false; - if( instance->defaultValuesOfProps[property] == value) { + if (instance->defaultValuesOfProps[property] == value) { return true; } else { return false; @@ -106,7 +108,8 @@ bool SPAttributeRelCSS::findIfInherit(Glib::ustring property) } // Always false if data file not found! - if( !foundFileDefault ) return false; + if (!foundFileDefault) + return false; return instance->inheritProps[property]; } @@ -121,10 +124,10 @@ bool SPAttributeRelCSS::findIfProperty(Glib::ustring property) } // Always true if data file not found! - if( !foundFileProp ) return true; + if (!foundFileProp) + return true; - return ( instance->defaultValuesOfProps.find( property ) - != instance->defaultValuesOfProps.end() ); + return (instance->defaultValuesOfProps.find(property) != instance->defaultValuesOfProps.end()); } SPAttributeRelCSS::SPAttributeRelCSS() @@ -138,22 +141,21 @@ SPAttributeRelCSS::SPAttributeRelCSS() if (readDataFromFileIn(filepath, SPAttributeRelCSS::prop_element_pair)) { foundFileProp = true; } - + // Read data from standard path filepath = get_path_string(SYSTEM, ATTRIBUTES, "css_defaults"); - + // Try and load data from filepath if (readDataFromFileIn(filepath, SPAttributeRelCSS::prop_defValue_pair)) { foundFileDefault = true; } - } bool SPAttributeRelCSS::readDataFromFileIn(Glib::ustring fileName, storageType type) { std::fstream file; file.open(fileName.c_str(), std::ios::in); - + if (!file.is_open()) { // Display warning for file not open g_warning("Could not open the data file for CSS attribute-element map construction: %s", fileName.c_str()); @@ -165,39 +167,39 @@ bool SPAttributeRelCSS::readDataFromFileIn(Glib::ustring fileName, storageType t std::stringstream ss; std::string s; - std::getline(file,s,'"'); - std::getline(file,s,'"'); + std::getline(file, s, '"'); + std::getline(file, s, '"'); if (s.size() > 0 && s[0] != '\n') { std::string prop = s; - getline(file,s); + getline(file, s); ss << s; - + // Load data to structure that holds element -> set of CSS props if (type == SPAttributeRelCSS::prop_element_pair) { - while (std::getline(ss,s,'"')) { + while (std::getline(ss, s, '"')) { std::string element; - std::getline(ss,s,'"'); - element = s; + std::getline(ss, s, '"'); + element = s; propertiesOfElements[element].insert(prop); } - // Load data to structure that holds CSS prop -> default value + // Load data to structure that holds CSS prop -> default value } else if (type == SPAttributeRelCSS::prop_defValue_pair) { std::string value; - std::getline(ss,s,'"'); - std::getline(ss,s,'"'); + std::getline(ss, s, '"'); + std::getline(ss, s, '"'); value = s; defaultValuesOfProps[prop] = value; - std::getline(ss,s,'"'); - std::getline(ss,s,'"'); + std::getline(ss, s, '"'); + std::getline(ss, s, '"'); gboolean inherit = false; - if ( s.find( "yes" ) != std::string::npos ) { + if (s.find("yes") != std::string::npos) { inherit = true; } inheritProps[prop] = inherit; } } } - + file.close(); return true; } diff --git a/src/attribute-rel-css.h b/src/attribute-rel-css.h index d7af4deaef36d6be7660724a081c2290762b5332..ae51aba824a02d2baddcc02b91b59d6767116032 100644 --- a/src/attribute-rel-css.h +++ b/src/attribute-rel-css.h @@ -17,20 +17,21 @@ * Author: abhishek */ -#include +#include #include #include -#include +#include // This data structure stores the valid (element -> set of CSS properties) pair -typedef std::map > hashList; +typedef std::map> hashList; /* - * Utility class that helps check whether a given element -> CSS property is + * Utility class that helps check whether a given element -> CSS property is * valid or not and whether the value assumed by a CSS property has a default * value. */ -class SPAttributeRelCSS { +class SPAttributeRelCSS +{ public: static bool findIfValid(Glib::ustring property, Glib::ustring element); static bool findIfDefault(Glib::ustring property, Glib::ustring value); @@ -39,15 +40,16 @@ public: private: SPAttributeRelCSS(); - SPAttributeRelCSS(const SPAttributeRelCSS&) = delete; - SPAttributeRelCSS& operator= (const SPAttributeRelCSS&) = delete; + SPAttributeRelCSS(const SPAttributeRelCSS &) = delete; + SPAttributeRelCSS &operator=(const SPAttributeRelCSS &) = delete; private: - /* + /* * Allows checking whether data loading is to be done for element -> CSS properties * or CSS property -> default value. */ - enum storageType { + enum storageType + { prop_element_pair, prop_defValue_pair }; @@ -62,7 +64,6 @@ private: bool readDataFromFileIn(Glib::ustring fileName, storageType type); }; - #endif /* __SP_ATTRIBUTE_REL_CSS_H__ */ /* diff --git a/src/attribute-rel-svg.cpp b/src/attribute-rel-svg.cpp index 8329d3fc619b69c776c2ea27cce1fa7b930a4052..29ac02fb6eb984f015e7b6e49681396ada11e585 100644 --- a/src/attribute-rel-svg.cpp +++ b/src/attribute-rel-svg.cpp @@ -21,16 +21,16 @@ * mapping indirectly(only reading). */ +#include "attribute-rel-svg.h" + #include #include -#include "attribute-rel-svg.h" - #include "io/resource.h" #include "path-prefix.h" #include "preferences.h" -SPAttributeRelSVG * SPAttributeRelSVG::instance = nullptr; +SPAttributeRelSVG *SPAttributeRelSVG::instance = nullptr; bool SPAttributeRelSVG::foundFile = false; /* @@ -43,12 +43,13 @@ bool SPAttributeRelSVG::isSVGElement(Glib::ustring element) } // Always valid if data file not found! - if( !foundFile ) return true; + if (!foundFile) + return true; // Strip off "svg:" from the element's name Glib::ustring temp = element; - if ( temp.find("svg:") != std::string::npos ) { - temp.erase( temp.find("svg:"), 4 ); + if (temp.find("svg:") != std::string::npos) { + temp.erase(temp.find("svg:"), 4); } return (SPAttributeRelSVG::instance->attributesOfElements.count(temp) > 0); @@ -64,14 +65,15 @@ bool SPAttributeRelSVG::findIfValid(Glib::ustring attribute, Glib::ustring eleme } // Always valid if data file not found! - if( !foundFile ) return true; + if (!foundFile) + return true; // Strip off "svg:" from the element's name Glib::ustring temp = element; - if ( temp.find("svg:") != std::string::npos ) { - temp.erase( temp.find("svg:"), 4 ); + if (temp.find("svg:") != std::string::npos) { + temp.erase(temp.find("svg:"), 4); } - + // Check for attributes with -, role, aria etc. to allow for more accessibility // clang-format off if (attribute[0] == '-' @@ -85,10 +87,10 @@ bool SPAttributeRelSVG::findIfValid(Glib::ustring attribute, Glib::ustring eleme || attribute.substr(0,4) == "ns1:" // JessyInk || (SPAttributeRelSVG::instance->attributesOfElements[temp].find(attribute) != SPAttributeRelSVG::instance->attributesOfElements[temp].end()) ) { - // clang-format on + // clang-format on return true; } else { - //g_warning( "Invalid attribute: %s used on <%s>", attribute.c_str(), element.c_str() ); + // g_warning( "Invalid attribute: %s used on <%s>", attribute.c_str(), element.c_str() ); return false; } } @@ -100,7 +102,7 @@ bool SPAttributeRelSVG::findIfValid(Glib::ustring attribute, Glib::ustring eleme SPAttributeRelSVG::SPAttributeRelSVG() { std::fstream f; - + // Read data from standard path using namespace Inkscape::IO::Resource; auto filepath = get_path_string(SYSTEM, ATTRIBUTES, "svgprops"); @@ -111,31 +113,31 @@ SPAttributeRelSVG::SPAttributeRelSVG() // Display warning for file not open g_warning("Could not open the data file for XML attribute-element map construction: %s", filepath.c_str()); f.close(); - return ; + return; } foundFile = true; - while (!f.eof()){ + while (!f.eof()) { std::stringstream ss; std::string s; - std::getline(f,s,'"'); - std::getline(f,s,'"'); - if(s.size() > 0 && s[0] != '\n'){ + std::getline(f, s, '"'); + std::getline(f, s, '"'); + if (s.size() > 0 && s[0] != '\n') { std::string prop = s; - getline(f,s); + getline(f, s); ss << s; - while(std::getline(ss,s,'"')){ + while (std::getline(ss, s, '"')) { std::string element; - std::getline(ss,s,'"'); + std::getline(ss, s, '"'); element = s; attributesOfElements[element].insert(prop); } } } - + f.close(); } diff --git a/src/attribute-rel-svg.h b/src/attribute-rel-svg.h index 2f04c5c7b902c7ca54b9d8f332937e2ae6b570cf..e22c7a40aec3d5511ce7d4d3b52ea831dbdd2e96 100644 --- a/src/attribute-rel-svg.h +++ b/src/attribute-rel-svg.h @@ -17,27 +17,28 @@ * Author: abhishek */ -#include +#include #include #include -#include +#include // This data structure stores the valid (element -> set of attributes) pair -typedef std::map > hashList; +typedef std::map> hashList; -/* +/* * Utility class to check whether a combination of element and attribute * is valid or not. */ -class SPAttributeRelSVG { +class SPAttributeRelSVG +{ public: static bool isSVGElement(Glib::ustring element); static bool findIfValid(Glib::ustring attribute, Glib::ustring element); private: SPAttributeRelSVG(); - SPAttributeRelSVG(const SPAttributeRelSVG&) = delete; - SPAttributeRelSVG& operator= (const SPAttributeRelSVG&) = delete; + SPAttributeRelSVG(const SPAttributeRelSVG &) = delete; + SPAttributeRelSVG &operator=(const SPAttributeRelSVG &) = delete; private: static SPAttributeRelSVG *instance; @@ -45,7 +46,6 @@ private: hashList attributesOfElements; }; - #endif /* __SP_ATTRIBUTE_REL_SVG_H__ */ /* diff --git a/src/attribute-rel-util.cpp b/src/attribute-rel-util.cpp index d3f2915319293530e80493a3a0c46e93eb9f19b9..d8e37021ccb06d682d35924966c273509c0ba39e 100644 --- a/src/attribute-rel-util.cpp +++ b/src/attribute-rel-util.cpp @@ -18,39 +18,43 @@ * Utility functions for cleaning SVG tree of unneeded attributes and style properties. */ +#include "attribute-rel-util.h" + #include -#include #include - -#include "preferences.h" - -#include "xml/attribute-record.h" +#include #include "attribute-rel-css.h" #include "attribute-rel-svg.h" +#include "preferences.h" +#include "xml/attribute-record.h" -#include "attribute-rel-util.h" - -using Inkscape::XML::Node; -using Inkscape::XML::AttributeRecord; using Inkscape::Util::List; +using Inkscape::XML::AttributeRecord; +using Inkscape::XML::Node; /** * Get preferences */ -unsigned int sp_attribute_clean_get_prefs() { - +unsigned int sp_attribute_clean_get_prefs() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); unsigned int flags = 0; - if( prefs->getBool("/options/svgoutput/incorrect_attributes_warn") ) flags += SP_ATTRCLEAN_ATTR_WARN; - if( prefs->getBool("/options/svgoutput/incorrect_attributes_remove") && - !prefs->getBool("/options/svgoutput/disable_optimizations" ) ) flags += SP_ATTRCLEAN_ATTR_REMOVE; - if( prefs->getBool("/options/svgoutput/incorrect_style_properties_warn") ) flags += SP_ATTRCLEAN_STYLE_WARN; - if( prefs->getBool("/options/svgoutput/incorrect_style_properties_remove" ) && - !prefs->getBool("/options/svgoutput/disable_optimizations" ) ) flags += SP_ATTRCLEAN_STYLE_REMOVE; - if( prefs->getBool("/options/svgoutput/style_defaults_warn") ) flags += SP_ATTRCLEAN_DEFAULT_WARN; - if( prefs->getBool("/options/svgoutput/style_defaults_remove") && - !prefs->getBool("/options/svgoutput/disable_optimizations" ) ) flags += SP_ATTRCLEAN_DEFAULT_REMOVE; + if (prefs->getBool("/options/svgoutput/incorrect_attributes_warn")) + flags += SP_ATTRCLEAN_ATTR_WARN; + if (prefs->getBool("/options/svgoutput/incorrect_attributes_remove") && + !prefs->getBool("/options/svgoutput/disable_optimizations")) + flags += SP_ATTRCLEAN_ATTR_REMOVE; + if (prefs->getBool("/options/svgoutput/incorrect_style_properties_warn")) + flags += SP_ATTRCLEAN_STYLE_WARN; + if (prefs->getBool("/options/svgoutput/incorrect_style_properties_remove") && + !prefs->getBool("/options/svgoutput/disable_optimizations")) + flags += SP_ATTRCLEAN_STYLE_REMOVE; + if (prefs->getBool("/options/svgoutput/style_defaults_warn")) + flags += SP_ATTRCLEAN_DEFAULT_WARN; + if (prefs->getBool("/options/svgoutput/style_defaults_remove") && + !prefs->getBool("/options/svgoutput/disable_optimizations")) + flags += SP_ATTRCLEAN_DEFAULT_REMOVE; return flags; } @@ -59,124 +63,119 @@ unsigned int sp_attribute_clean_get_prefs() { * Remove or warn about inappropriate attributes and useless stype properties. * repr: the root node in a document or any other node. */ -void sp_attribute_clean_tree(Node *repr) { +void sp_attribute_clean_tree(Node *repr) +{ + g_return_if_fail(repr != nullptr); - g_return_if_fail (repr != nullptr); + unsigned int flags = sp_attribute_clean_get_prefs(); - unsigned int flags = sp_attribute_clean_get_prefs(); - - if( flags ) { - sp_attribute_clean_recursive( repr, flags ); - } + if (flags) { + sp_attribute_clean_recursive(repr, flags); + } } /** * Clean recursively over all elements. */ -void sp_attribute_clean_recursive(Node *repr, unsigned int flags) { - - g_return_if_fail (repr != nullptr); +void sp_attribute_clean_recursive(Node *repr, unsigned int flags) +{ + g_return_if_fail(repr != nullptr); - if( repr->type() == Inkscape::XML::ELEMENT_NODE ) { - Glib::ustring element = repr->name(); + if (repr->type() == Inkscape::XML::ELEMENT_NODE) { + Glib::ustring element = repr->name(); - // Only clean elements in svg namespace - if( element.substr(0,4) == "svg:" ) { - sp_attribute_clean_element(repr, flags ); + // Only clean elements in svg namespace + if (element.substr(0, 4) == "svg:") { + sp_attribute_clean_element(repr, flags); + } } - } - - for(Node *child=repr->firstChild() ; child ; child = child->next()) { - - // Don't remove default css values if element is in or is a - Glib::ustring element = child->name(); - unsigned int flags_temp = flags; - if( element.compare( "svg:defs" ) == 0 || element.compare( "svg:symbol" ) == 0 ) { - flags_temp &= ~(SP_ATTRCLEAN_DEFAULT_WARN|SP_ATTRCLEAN_DEFAULT_REMOVE); + + for (Node *child = repr->firstChild(); child; child = child->next()) { + // Don't remove default css values if element is in or is a + Glib::ustring element = child->name(); + unsigned int flags_temp = flags; + if (element.compare("svg:defs") == 0 || element.compare("svg:symbol") == 0) { + flags_temp &= ~(SP_ATTRCLEAN_DEFAULT_WARN | SP_ATTRCLEAN_DEFAULT_REMOVE); + } + sp_attribute_clean_recursive(child, flags_temp); } - sp_attribute_clean_recursive( child, flags_temp ); - } } /** * Clean attributes on an element */ -void sp_attribute_clean_element(Node *repr, unsigned int flags) { - - g_return_if_fail (repr != nullptr); - g_return_if_fail (repr->type() == Inkscape::XML::ELEMENT_NODE); +void sp_attribute_clean_element(Node *repr, unsigned int flags) +{ + g_return_if_fail(repr != nullptr); + g_return_if_fail(repr->type() == Inkscape::XML::ELEMENT_NODE); - Glib::ustring element = repr->name(); - Glib::ustring id = (repr->attribute( "id" )==nullptr ? "" : repr->attribute( "id" )); - - // Clean style: this attribute is unique in that normally we want to change it and not simply - // delete it. - sp_attribute_clean_style(repr, flags ); + Glib::ustring element = repr->name(); + Glib::ustring id = (repr->attribute("id") == nullptr ? "" : repr->attribute("id")); - // Clean attributes - List attributes = repr->attributeList(); + // Clean style: this attribute is unique in that normally we want to change it and not simply + // delete it. + sp_attribute_clean_style(repr, flags); - std::set attributesToDelete; - for ( List iter = attributes ; iter ; ++iter ) { + // Clean attributes + List attributes = repr->attributeList(); - Glib::ustring attribute = g_quark_to_string(iter->key); - //Glib::ustring value = (const char*)iter->value; + std::set attributesToDelete; + for (List iter = attributes; iter; ++iter) { + Glib::ustring attribute = g_quark_to_string(iter->key); + // Glib::ustring value = (const char*)iter->value; - bool is_useful = sp_attribute_check_attribute( element, id, attribute, flags & SP_ATTRCLEAN_ATTR_WARN ); - if( !is_useful && (flags & SP_ATTRCLEAN_ATTR_REMOVE) ) { - attributesToDelete.insert( attribute ); + bool is_useful = sp_attribute_check_attribute(element, id, attribute, flags & SP_ATTRCLEAN_ATTR_WARN); + if (!is_useful && (flags & SP_ATTRCLEAN_ATTR_REMOVE)) { + attributesToDelete.insert(attribute); + } } - } - // Do actual deleting (done after so as not to perturb List iterator). - for(const auto & iter_d : attributesToDelete) { - repr->removeAttribute(iter_d); - } + // Do actual deleting (done after so as not to perturb List iterator). + for (const auto &iter_d : attributesToDelete) { + repr->removeAttribute(iter_d); + } } - /** * Clean CSS style on an element. */ -void sp_attribute_clean_style(Node *repr, unsigned int flags) { - - g_return_if_fail (repr != nullptr); - g_return_if_fail (repr->type() == Inkscape::XML::ELEMENT_NODE); - - // Find element's style - SPCSSAttr *css = sp_repr_css_attr( repr, "style" ); - sp_attribute_clean_style(repr, css, flags); - - // Convert css node's properties data to string and set repr node's attribute "style" to that string. - // sp_repr_css_set( repr, css, "style"); // Don't use as it will cause loop. - Glib::ustring value; - sp_repr_css_write_string(css, value); - repr->setAttributeOrRemoveIfEmpty("style", value); - - sp_repr_css_attr_unref( css ); +void sp_attribute_clean_style(Node *repr, unsigned int flags) +{ + g_return_if_fail(repr != nullptr); + g_return_if_fail(repr->type() == Inkscape::XML::ELEMENT_NODE); + + // Find element's style + SPCSSAttr *css = sp_repr_css_attr(repr, "style"); + sp_attribute_clean_style(repr, css, flags); + + // Convert css node's properties data to string and set repr node's attribute "style" to that string. + // sp_repr_css_set( repr, css, "style"); // Don't use as it will cause loop. + Glib::ustring value; + sp_repr_css_write_string(css, value); + repr->setAttributeOrRemoveIfEmpty("style", value); + + sp_repr_css_attr_unref(css); } - /** * Clean CSS style on an element. */ -Glib::ustring sp_attribute_clean_style(Node *repr, gchar const *string, unsigned int flags) { +Glib::ustring sp_attribute_clean_style(Node *repr, gchar const *string, unsigned int flags) +{ + g_return_val_if_fail(repr != nullptr, NULL); + g_return_val_if_fail(repr->type() == Inkscape::XML::ELEMENT_NODE, NULL); - g_return_val_if_fail (repr != nullptr, NULL); - g_return_val_if_fail (repr->type() == Inkscape::XML::ELEMENT_NODE, NULL); + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_attr_add_from_string(css, string); + sp_attribute_clean_style(repr, css, flags); + Glib::ustring string_cleaned; + sp_repr_css_write_string(css, string_cleaned); - SPCSSAttr *css = sp_repr_css_attr_new(); - sp_repr_css_attr_add_from_string( css, string ); - sp_attribute_clean_style(repr, css, flags); - Glib::ustring string_cleaned; - sp_repr_css_write_string (css, string_cleaned); + sp_repr_css_attr_unref(css); - sp_repr_css_attr_unref( css ); - - return string_cleaned; + return string_cleaned; } - /** * Clean CSS style on an element. * @@ -186,161 +185,146 @@ Glib::ustring sp_attribute_clean_style(Node *repr, gchar const *string, unsigned * Is it the same as the parent and it inherits? * Is it the default value (and the property on the parent is not set or does not inherit)? */ -void sp_attribute_clean_style(Node* repr, SPCSSAttr *css, unsigned int flags) { - - g_return_if_fail (repr != nullptr); - g_return_if_fail (css != nullptr); - - Glib::ustring element = repr->name(); - Glib::ustring id = (repr->attribute( "id" )==nullptr ? "" : repr->attribute( "id" )); +void sp_attribute_clean_style(Node *repr, SPCSSAttr *css, unsigned int flags) +{ + g_return_if_fail(repr != nullptr); + g_return_if_fail(css != nullptr); - // Find parent's style, including properties that are inherited. - // Note, a node may not have a parent if it has not yet been added to tree. - SPCSSAttr *css_parent = nullptr; - if( repr->parent() ) css_parent = sp_repr_css_attr_inherited( repr->parent(), "style" ); - - // Loop over all properties in "style" node, keeping track of which to delete. - std::set toDelete; - for ( List iter = css->attributeList() ; iter ; ++iter ) { - - gchar const * property = g_quark_to_string(iter->key); - gchar const * value = iter->value; - - // Check if a property is applicable to an element (i.e. is font-family useful for a ?). - if( !SPAttributeRelCSS::findIfValid( property, element ) ) { - if( flags & SP_ATTRCLEAN_STYLE_WARN ) { - g_warning( "<%s id=\"%s\">: CSS Style property: \"%s\" is inappropriate.", - element.c_str(), id.c_str(), property ); - } - if( flags & SP_ATTRCLEAN_STYLE_REMOVE ) { - toDelete.insert(property); + Glib::ustring element = repr->name(); + Glib::ustring id = (repr->attribute("id") == nullptr ? "" : repr->attribute("id")); + + // Find parent's style, including properties that are inherited. + // Note, a node may not have a parent if it has not yet been added to tree. + SPCSSAttr *css_parent = nullptr; + if (repr->parent()) + css_parent = sp_repr_css_attr_inherited(repr->parent(), "style"); + + // Loop over all properties in "style" node, keeping track of which to delete. + std::set toDelete; + for (List iter = css->attributeList(); iter; ++iter) { + gchar const *property = g_quark_to_string(iter->key); + gchar const *value = iter->value; + + // Check if a property is applicable to an element (i.e. is font-family useful for a ?). + if (!SPAttributeRelCSS::findIfValid(property, element)) { + if (flags & SP_ATTRCLEAN_STYLE_WARN) { + g_warning("<%s id=\"%s\">: CSS Style property: \"%s\" is inappropriate.", element.c_str(), id.c_str(), + property); + } + if (flags & SP_ATTRCLEAN_STYLE_REMOVE) { + toDelete.insert(property); + } + continue; } - continue; - } - // Find parent value for same property (property) - gchar const * value_p = nullptr; - if( css_parent != nullptr ) { - for ( List iter_p = css_parent->attributeList() ; iter_p ; ++iter_p ) { + // Find parent value for same property (property) + gchar const *value_p = nullptr; + if (css_parent != nullptr) { + for (List iter_p = css_parent->attributeList(); iter_p; ++iter_p) { + gchar const *property_p = g_quark_to_string(iter_p->key); - gchar const * property_p = g_quark_to_string(iter_p->key); - - if( !g_strcmp0( property, property_p ) ) { - value_p = iter_p->value; - break; + if (!g_strcmp0(property, property_p)) { + value_p = iter_p->value; + break; + } } } - } - // If parent has same property value and property is inherited, mark for deletion. - if ( !g_strcmp0( value, value_p ) && SPAttributeRelCSS::findIfInherit( property ) ) { - - if ( flags & SP_ATTRCLEAN_DEFAULT_WARN ) { - g_warning( "<%s id=\"%s\">: CSS Style property: \"%s\" has same value as parent (%s).", - element.c_str(), id.c_str(), property, value ); - } - if ( flags & SP_ATTRCLEAN_DEFAULT_REMOVE ) { - toDelete.insert( property ); + // If parent has same property value and property is inherited, mark for deletion. + if (!g_strcmp0(value, value_p) && SPAttributeRelCSS::findIfInherit(property)) { + if (flags & SP_ATTRCLEAN_DEFAULT_WARN) { + g_warning("<%s id=\"%s\">: CSS Style property: \"%s\" has same value as parent (%s).", element.c_str(), + id.c_str(), property, value); + } + if (flags & SP_ATTRCLEAN_DEFAULT_REMOVE) { + toDelete.insert(property); + } + continue; } - continue; - } - // If property value is same as default and the parent value not set or property is not inherited, - // mark for deletion. - if ( SPAttributeRelCSS::findIfDefault( property, value ) && - ( (css_parent != nullptr && value_p == nullptr) || !SPAttributeRelCSS::findIfInherit( property ) ) ) { - - if ( flags & SP_ATTRCLEAN_DEFAULT_WARN ) { - g_warning( "<%s id=\"%s\">: CSS Style property: \"%s\" with default value (%s) not needed.", - element.c_str(), id.c_str(), property, value ); - } - if ( flags & SP_ATTRCLEAN_DEFAULT_REMOVE ) { - toDelete.insert( property ); + // If property value is same as default and the parent value not set or property is not inherited, + // mark for deletion. + if (SPAttributeRelCSS::findIfDefault(property, value) && + ((css_parent != nullptr && value_p == nullptr) || !SPAttributeRelCSS::findIfInherit(property))) { + if (flags & SP_ATTRCLEAN_DEFAULT_WARN) { + g_warning("<%s id=\"%s\">: CSS Style property: \"%s\" with default value (%s) not needed.", + element.c_str(), id.c_str(), property, value); + } + if (flags & SP_ATTRCLEAN_DEFAULT_REMOVE) { + toDelete.insert(property); + } + continue; } - continue; - } - - } // End loop over style properties - // Delete unneeded style properties. Do this at the end so as to not perturb List iterator. - for(const auto & iter_d : toDelete) { - sp_repr_css_set_property( css, iter_d.c_str(), nullptr ); - } + } // End loop over style properties + // Delete unneeded style properties. Do this at the end so as to not perturb List iterator. + for (const auto &iter_d : toDelete) { + sp_repr_css_set_property(css, iter_d.c_str(), nullptr); + } } /** * Remove CSS style properties with default values. */ -void sp_attribute_purge_default_style(SPCSSAttr *css, unsigned int flags) { - - g_return_if_fail (css != nullptr); - - // Loop over all properties in "style" node, keeping track of which to delete. - std::set toDelete; - for ( List iter = css->attributeList() ; iter ; ++iter ) { - - gchar const * property = g_quark_to_string(iter->key); - gchar const * value = iter->value; - - // If property value is same as default mark for deletion. - if ( SPAttributeRelCSS::findIfDefault( property, value ) ) { - - if ( flags & SP_ATTRCLEAN_DEFAULT_WARN ) { - g_warning( "Preferences CSS Style property: \"%s\" with default value (%s) not needed.", - property, value ); - } - if ( flags & SP_ATTRCLEAN_DEFAULT_REMOVE ) { - toDelete.insert( property ); +void sp_attribute_purge_default_style(SPCSSAttr *css, unsigned int flags) +{ + g_return_if_fail(css != nullptr); + + // Loop over all properties in "style" node, keeping track of which to delete. + std::set toDelete; + for (List iter = css->attributeList(); iter; ++iter) { + gchar const *property = g_quark_to_string(iter->key); + gchar const *value = iter->value; + + // If property value is same as default mark for deletion. + if (SPAttributeRelCSS::findIfDefault(property, value)) { + if (flags & SP_ATTRCLEAN_DEFAULT_WARN) { + g_warning("Preferences CSS Style property: \"%s\" with default value (%s) not needed.", property, + value); + } + if (flags & SP_ATTRCLEAN_DEFAULT_REMOVE) { + toDelete.insert(property); + } + continue; } - continue; - } - - } // End loop over style properties - // Delete unneeded style properties. Do this at the end so as to not perturb List iterator. - for(const auto & iter_d : toDelete) { - sp_repr_css_set_property( css, iter_d.c_str(), nullptr ); - } + } // End loop over style properties + // Delete unneeded style properties. Do this at the end so as to not perturb List iterator. + for (const auto &iter_d : toDelete) { + sp_repr_css_set_property(css, iter_d.c_str(), nullptr); + } } /** * Check one attribute on an element */ -bool sp_attribute_check_attribute(Glib::ustring element, Glib::ustring id, Glib::ustring attribute, bool warn) { - +bool sp_attribute_check_attribute(Glib::ustring element, Glib::ustring id, Glib::ustring attribute, bool warn) +{ bool is_useful = true; - if( SPAttributeRelCSS::findIfProperty( attribute ) ) { - + if (SPAttributeRelCSS::findIfProperty(attribute)) { // First check if it is a presentation attribute. Presentation attributes can be applied to // any element. At the moment, we are only going to check if it is a possibly useful // attribute. Note, we don't explicitly check against the list of elements where presentation // attributes are allowed (See SVG1.1 spec, Appendix M.2). - if( !SPAttributeRelCSS::findIfValid( attribute, element ) ) { - + if (!SPAttributeRelCSS::findIfValid(attribute, element)) { // Non-useful presentation attribute on SVG - if( warn ) { - g_warning( "<%s id=\"%s\">: Non-useful presentation attribute: \"%s\" found.", - element.c_str(), - id.c_str(), - attribute.c_str() ); + if (warn) { + g_warning("<%s id=\"%s\">: Non-useful presentation attribute: \"%s\" found.", element.c_str(), + id.c_str(), attribute.c_str()); } is_useful = false; } } else { - // Second check if it is a valid attribute - if ( !SPAttributeRelSVG::findIfValid( attribute, element ) ) { - + if (!SPAttributeRelSVG::findIfValid(attribute, element)) { // Invalid attribute on SVG - if( warn ) { - g_warning( "<%s id=\"%s\">: Invalid attribute: \"%s\" found.", - element.c_str(), - id.c_str(), - attribute.c_str() ); + if (warn) { + g_warning("<%s id=\"%s\">: Invalid attribute: \"%s\" found.", element.c_str(), id.c_str(), + attribute.c_str()); } is_useful = false; } diff --git a/src/attribute-rel-util.h b/src/attribute-rel-util.h index 1ad7a85b80b1249f17bad67c84c3a01e00379089..5173d1b4037a6d75bbae5bc708eda132e9969a35 100644 --- a/src/attribute-rel-util.h +++ b/src/attribute-rel-util.h @@ -18,6 +18,7 @@ */ #include + #include "xml/sp-css-attr.h" using Inkscape::XML::Node; @@ -29,13 +30,14 @@ using Inkscape::XML::Node; /** * Enum for preferences */ -enum SPAttrClean { - SP_ATTRCLEAN_ATTR_WARN = 1, - SP_ATTRCLEAN_ATTR_REMOVE = 2, - SP_ATTRCLEAN_STYLE_WARN = 4, - SP_ATTRCLEAN_STYLE_REMOVE = 8, - SP_ATTRCLEAN_DEFAULT_WARN = 16, - SP_ATTRCLEAN_DEFAULT_REMOVE = 32 +enum SPAttrClean +{ + SP_ATTRCLEAN_ATTR_WARN = 1, + SP_ATTRCLEAN_ATTR_REMOVE = 2, + SP_ATTRCLEAN_STYLE_WARN = 4, + SP_ATTRCLEAN_STYLE_REMOVE = 8, + SP_ATTRCLEAN_DEFAULT_WARN = 16, + SP_ATTRCLEAN_DEFAULT_REMOVE = 32 }; /** @@ -74,7 +76,7 @@ Glib::ustring sp_attribute_clean_style(Node *repr, gchar const *string, unsigned /** * Clean style properties for one CSS. */ -void sp_attribute_clean_style(Node* repr, SPCSSAttr *css, unsigned int flags); +void sp_attribute_clean_style(Node *repr, SPCSSAttr *css, unsigned int flags); /** * Remove CSS style properties with default values. diff --git a/src/attribute-sort-util.cpp b/src/attribute-sort-util.cpp index 95085e8724f63df3884d9b27b5d99459d0eb018c..3ef802422ea1f932f90e1dc94ca35fc97ba30d58 100644 --- a/src/attribute-sort-util.cpp +++ b/src/attribute-sort-util.cpp @@ -18,157 +18,153 @@ * Utility functions for sorting attributes by name. */ +#include "attribute-sort-util.h" + +#include // std::sort #include -#include +#include #include +#include +#include // std::pair #include -#include // std::pair -#include // std::sort - -#include - -#include "attribute-sort-util.h" -#include "xml/repr.h" +#include "attributes.h" #include "xml/attribute-record.h" +#include "xml/repr.h" #include "xml/sp-css-attr.h" -#include "attributes.h" - -using Inkscape::XML::Node; -using Inkscape::XML::AttributeRecord; using Inkscape::Util::List; +using Inkscape::XML::AttributeRecord; +using Inkscape::XML::Node; -static void sp_attribute_sort_recursive(Node& repr); -static void sp_attribute_sort_element(Node& repr); -static void sp_attribute_sort_style(Node& repr); -static void sp_attribute_sort_style(Node& repr, SPCSSAttr& css); +static void sp_attribute_sort_recursive(Node &repr); +static void sp_attribute_sort_element(Node &repr); +static void sp_attribute_sort_style(Node &repr); +static void sp_attribute_sort_style(Node &repr, SPCSSAttr &css); /** * Sort attributes by name. */ -void sp_attribute_sort_tree(Node& repr) { - - sp_attribute_sort_recursive( repr ); +void sp_attribute_sort_tree(Node &repr) +{ + sp_attribute_sort_recursive(repr); } /** * Sort recursively over all elements. */ -static void sp_attribute_sort_recursive(Node& repr) { - - if( repr.type() == Inkscape::XML::ELEMENT_NODE ) { - Glib::ustring element = repr.name(); +static void sp_attribute_sort_recursive(Node &repr) +{ + if (repr.type() == Inkscape::XML::ELEMENT_NODE) { + Glib::ustring element = repr.name(); + + // Only sort elements in svg namespace + if (element.substr(0, 4) == "svg:") { + sp_attribute_sort_element(repr); + } + } - // Only sort elements in svg namespace - if( element.substr(0,4) == "svg:" ) { - sp_attribute_sort_element( repr ); + for (Node *child = repr.firstChild(); child; child = child->next()) { + sp_attribute_sort_recursive(*child); } - } - - for(Node *child=repr.firstChild() ; child ; child = child->next()) { - sp_attribute_sort_recursive( *child ); - } } /** * Compare function */ -static bool cmp(std::pair< Glib::ustring, Glib::ustring > const &a, - std::pair< Glib::ustring, Glib::ustring > const &b) { +static bool cmp(std::pair const &a, std::pair const &b) +{ auto val_a = sp_attribute_lookup(a.first.c_str()); auto val_b = sp_attribute_lookup(b.first.c_str()); - if (val_a == SPAttr::INVALID) return false; // Unknown attributes at end. - if (val_b == SPAttr::INVALID) return true; // Unknown attributes at end. + if (val_a == SPAttr::INVALID) + return false; // Unknown attributes at end. + if (val_b == SPAttr::INVALID) + return true; // Unknown attributes at end. return val_a < val_b; } /** * Sort attributes on an element */ -static void sp_attribute_sort_element(Node& repr) { - - g_return_if_fail (repr.type() == Inkscape::XML::ELEMENT_NODE); - - sp_attribute_sort_style(repr); - - // Sort attributes: - - // It doesn't seem possible to sort a List directly so we dump the list into - // a std::list and sort that. Not very efficient. Sad. - List attributes = repr.attributeList(); - - std::vector > my_list; - for ( List iter = attributes ; iter ; ++iter ) { - - Glib::ustring attribute = g_quark_to_string(iter->key); - Glib::ustring value = (const char*)iter->value; - - // C++11 my_list.emlace_back(attribute, value); - my_list.emplace_back(attribute,value); - } - std::sort(my_list.begin(), my_list.end(), cmp); - // Delete all attributes. - for (const auto& it : my_list) { - // Removing "inkscape:label" results in crash when Layers dialog is open. - if (it.first != "inkscape:label") { - repr.removeAttribute(it.first); - } - } - // Insert all attributes in proper order - for (const auto& it : my_list) { - if (it.first != "inkscape:label") { - repr.setAttribute( it.first, it.second); - } - } -} +static void sp_attribute_sort_element(Node &repr) +{ + g_return_if_fail(repr.type() == Inkscape::XML::ELEMENT_NODE); + + sp_attribute_sort_style(repr); + // Sort attributes: + + // It doesn't seem possible to sort a List directly so we dump the list into + // a std::list and sort that. Not very efficient. Sad. + List attributes = repr.attributeList(); + + std::vector> my_list; + for (List iter = attributes; iter; ++iter) { + Glib::ustring attribute = g_quark_to_string(iter->key); + Glib::ustring value = (const char *)iter->value; + + // C++11 my_list.emlace_back(attribute, value); + my_list.emplace_back(attribute, value); + } + std::sort(my_list.begin(), my_list.end(), cmp); + // Delete all attributes. + for (const auto &it : my_list) { + // Removing "inkscape:label" results in crash when Layers dialog is open. + if (it.first != "inkscape:label") { + repr.removeAttribute(it.first); + } + } + // Insert all attributes in proper order + for (const auto &it : my_list) { + if (it.first != "inkscape:label") { + repr.setAttribute(it.first, it.second); + } + } +} /** * Sort CSS style on an element. */ -static void sp_attribute_sort_style(Node& repr) { - - g_return_if_fail (repr.type() == Inkscape::XML::ELEMENT_NODE); +static void sp_attribute_sort_style(Node &repr) +{ + g_return_if_fail(repr.type() == Inkscape::XML::ELEMENT_NODE); - // Find element's style - SPCSSAttr *css = sp_repr_css_attr( &repr, "style" ); - sp_attribute_sort_style(repr, *css); + // Find element's style + SPCSSAttr *css = sp_repr_css_attr(&repr, "style"); + sp_attribute_sort_style(repr, *css); - // Convert css node's properties data to string and set repr node's attribute "style" to that string. - // sp_repr_css_set( repr, css, "style"); // Don't use as it will cause loop. - Glib::ustring value; - sp_repr_css_write_string(css, value); - repr.setAttributeOrRemoveIfEmpty("style", value); + // Convert css node's properties data to string and set repr node's attribute "style" to that string. + // sp_repr_css_set( repr, css, "style"); // Don't use as it will cause loop. + Glib::ustring value; + sp_repr_css_write_string(css, value); + repr.setAttributeOrRemoveIfEmpty("style", value); - sp_repr_css_attr_unref( css ); + sp_repr_css_attr_unref(css); } - /** * Sort CSS style on an element. */ -static void sp_attribute_sort_style(Node& repr, SPCSSAttr& css) { - - // Loop over all properties in "style" node. - std::vector > my_list; - for ( List iter = css.attributeList() ; iter ; ++iter ) { - - Glib::ustring property = g_quark_to_string(iter->key); - Glib::ustring value = (const char*)iter->value; - - // C++11 my_list.emlace_back(property, value); - my_list.emplace_back(property,value); - } - std::sort(my_list.begin(), my_list.end(), cmp); - // Delete all attributes. - for (const auto& it : my_list) { - sp_repr_css_set_property( &css, it.first.c_str(), nullptr ); - } - // Insert all attributes in proper order - for (const auto& it : my_list) { - sp_repr_css_set_property( &css, it.first.c_str(), it.second.c_str() ); - } +static void sp_attribute_sort_style(Node &repr, SPCSSAttr &css) +{ + // Loop over all properties in "style" node. + std::vector> my_list; + for (List iter = css.attributeList(); iter; ++iter) { + Glib::ustring property = g_quark_to_string(iter->key); + Glib::ustring value = (const char *)iter->value; + + // C++11 my_list.emlace_back(property, value); + my_list.emplace_back(property, value); + } + std::sort(my_list.begin(), my_list.end(), cmp); + // Delete all attributes. + for (const auto &it : my_list) { + sp_repr_css_set_property(&css, it.first.c_str(), nullptr); + } + // Insert all attributes in proper order + for (const auto &it : my_list) { + sp_repr_css_set_property(&css, it.first.c_str(), it.second.c_str()); + } } /* diff --git a/src/attribute-sort-util.h b/src/attribute-sort-util.h index d0dcc55e5a9544fa99de7612ef5f015d23f405ca..28951c021b78cbc79ebe2ce29b1207c3fe9a3a89 100644 --- a/src/attribute-sort-util.h +++ b/src/attribute-sort-util.h @@ -23,7 +23,7 @@ using Inkscape::XML::Node; /** * Sort attributes and CSS properties by name. */ -void sp_attribute_sort_tree(Node& repr); +void sp_attribute_sort_tree(Node &repr); #endif /* __SP_ATTRIBUTE_SORT_UTIL_H__ */ diff --git a/src/attributes.cpp b/src/attributes.cpp index 56bd33c243b4bf5dae6de61b6bac167e0fda0f70..da2b39b1b4e60d90915f4e37f1297bfb0e73e44a 100644 --- a/src/attributes.cpp +++ b/src/attributes.cpp @@ -10,14 +10,14 @@ */ #include "attributes.h" -#include -#include #include +#include #include // g_assert() +#include - -struct SPStyleProp { +struct SPStyleProp +{ SPAttr code; gchar const *name; }; @@ -122,7 +122,8 @@ static SPStyleProp const props[] = { {SPAttr::INKSCAPE_SNAP_BBOX_CORNER, "inkscape:bbox-nodes"}, {SPAttr::INKSCAPE_SNAP_PAGE_BORDER, "inkscape:snap-page"}, {SPAttr::INKSCAPE_CURRENT_LAYER, "inkscape:current-layer"}, - {SPAttr::INKSCAPE_DOCUMENT_UNITS, "inkscape:document-units"}, // This setting sets the Display units, *not* the units used in SVG + {SPAttr::INKSCAPE_DOCUMENT_UNITS, "inkscape:document-units"}, // This setting sets the Display units, *not* the + // units used in SVG {SPAttr::INKSCAPE_LOCKGUIDES, "inkscape:lockguides"}, {SPAttr::UNITS, "units"}, /* SPColorProfile */ @@ -374,9 +375,8 @@ static SPStyleProp const props[] = { {SPAttr::K, "k"}, /**/ - //{SPAttr::FONT_FAMILY, "font-family"}, these are already set for CSS2 (SPAttr::FONT_FAMILY, SPAttr::FONT_STYLE, SPAttr::FONT_VARIANT etc...) - //{SPAttr::FONT_STYLE, "font-style"}, - //{SPAttr::FONT_VARIANT, "font-variant"}, + //{SPAttr::FONT_FAMILY, "font-family"}, these are already set for CSS2 (SPAttr::FONT_FAMILY, SPAttr::FONT_STYLE, + // SPAttr::FONT_VARIANT etc...) {SPAttr::FONT_STYLE, "font-style"}, {SPAttr::FONT_VARIANT, "font-variant"}, //{SPAttr::FONT_WEIGHT, "font-weight"}, //{SPAttr::FONT_STRETCH, "font-stretch"}, //{SPAttr::FONT_SIZE, "font-size"}, @@ -410,17 +410,17 @@ static SPStyleProp const props[] = { /* XML */ {SPAttr::XML_SPACE, "xml:space"}, - {SPAttr::XML_LANG, "xml:lang"}, + {SPAttr::XML_LANG, "xml:lang"}, /* typeset */ {SPAttr::TEXT_NOMARKUP, "inkscape:srcNoMarkup"}, - {SPAttr::TEXT_PANGOMARKUP, "inkscape:srcPango" }, + {SPAttr::TEXT_PANGOMARKUP, "inkscape:srcPango"}, {SPAttr::TEXT_INSHAPE, "inkscape:dstShape"}, {SPAttr::TEXT_ONPATH, "inkscape:dstPath"}, - {SPAttr::TEXT_INBOX,"inkscape:dstBox"}, - {SPAttr::TEXT_INCOLUMN,"inkscape:dstColumn"}, - {SPAttr::TEXT_EXCLUDE,"inkscape:excludeShape"}, - {SPAttr::LAYOUT_OPTIONS,"inkscape:layoutOptions"}, + {SPAttr::TEXT_INBOX, "inkscape:dstBox"}, + {SPAttr::TEXT_INCOLUMN, "inkscape:dstColumn"}, + {SPAttr::TEXT_EXCLUDE, "inkscape:excludeShape"}, + {SPAttr::LAYOUT_OPTIONS, "inkscape:layoutOptions"}, /* CSS & SVG Properites */ @@ -445,7 +445,7 @@ static SPStyleProp const props[] = { {SPAttr::MARKER_END, "marker-end"}, {SPAttr::MARKER_MID, "marker-mid"}, {SPAttr::MARKER_START, "marker-start"}, - {SPAttr::PAINT_ORDER, "paint-order" }, + {SPAttr::PAINT_ORDER, "paint-order"}, {SPAttr::SOLID_COLOR, "solid-color"}, {SPAttr::SOLID_OPACITY, "solid-opacity"}, {SPAttr::VECTOR_EFFECT, "vector-effect"}, @@ -477,16 +477,16 @@ static SPStyleProp const props[] = { {SPAttr::FONT_WEIGHT, "font-weight"}, /* Font Variants CSS 3 */ - {SPAttr::FONT_VARIANT_LIGATURES, "font-variant-ligatures"}, - {SPAttr::FONT_VARIANT_POSITION, "font-variant-position"}, - {SPAttr::FONT_VARIANT_CAPS, "font-variant-caps"}, - {SPAttr::FONT_VARIANT_NUMERIC, "font-variant-numeric"}, + {SPAttr::FONT_VARIANT_LIGATURES, "font-variant-ligatures"}, + {SPAttr::FONT_VARIANT_POSITION, "font-variant-position"}, + {SPAttr::FONT_VARIANT_CAPS, "font-variant-caps"}, + {SPAttr::FONT_VARIANT_NUMERIC, "font-variant-numeric"}, {SPAttr::FONT_VARIANT_ALTERNATES, "font-variant-alternates"}, {SPAttr::FONT_VARIANT_EAST_ASIAN, "font-variant-east-asian"}, - {SPAttr::FONT_FEATURE_SETTINGS, "font-feature-settings"}, + {SPAttr::FONT_FEATURE_SETTINGS, "font-feature-settings"}, /* Variable Fonts (CSS Fonts Module Level 4) */ - {SPAttr::FONT_VARIATION_SETTINGS, "font-variation-settings"}, + {SPAttr::FONT_VARIATION_SETTINGS, "font-variation-settings"}, /* Text */ {SPAttr::TEXT_INDENT, "text-indent"}, @@ -511,19 +511,19 @@ static SPStyleProp const props[] = { {SPAttr::WHITE_SPACE, "white-space"}, /* SVG 2 Text Wrapping */ - {SPAttr::SHAPE_INSIDE, "shape-inside"}, - {SPAttr::SHAPE_SUBTRACT,"shape-subtract"}, + {SPAttr::SHAPE_INSIDE, "shape-inside"}, + {SPAttr::SHAPE_SUBTRACT, "shape-subtract"}, {SPAttr::SHAPE_PADDING, "shape-padding"}, - {SPAttr::SHAPE_MARGIN, "shape-margin"}, - {SPAttr::INLINE_SIZE, "inline-size"}, + {SPAttr::SHAPE_MARGIN, "shape-margin"}, + {SPAttr::INLINE_SIZE, "inline-size"}, /* Text Decoration */ - {SPAttr::TEXT_DECORATION, "text-decoration"}, // CSS 2/CSS3-Shorthand - {SPAttr::TEXT_DECORATION_LINE, "text-decoration-line"}, + {SPAttr::TEXT_DECORATION, "text-decoration"}, // CSS 2/CSS3-Shorthand + {SPAttr::TEXT_DECORATION_LINE, "text-decoration-line"}, {SPAttr::TEXT_DECORATION_STYLE, "text-decoration-style"}, {SPAttr::TEXT_DECORATION_COLOR, "text-decoration-color"}, - {SPAttr::TEXT_DECORATION_FILL, "text-decoration-fill"}, - {SPAttr::TEXT_DECORATION_STROKE,"text-decoration-stroke"}, + {SPAttr::TEXT_DECORATION_FILL, "text-decoration-fill"}, + {SPAttr::TEXT_DECORATION_STROKE, "text-decoration-stroke"}, /* Filter */ {SPAttr::ENABLE_BACKGROUND, "enable-background"}, @@ -567,10 +567,12 @@ static_assert(n_attrs == (int)SPAttr::SPAttr_SIZE, ""); /** * Inverse to the \c props array for lookup by name. */ -class AttributeLookupImpl { +class AttributeLookupImpl +{ friend SPAttr sp_attribute_lookup(gchar const *key); - struct cstrless { + struct cstrless + { bool operator()(char const *lhs, char const *rhs) const { return std::strcmp(lhs, rhs) < 0; } }; @@ -580,15 +582,14 @@ class AttributeLookupImpl { { for (unsigned int i = 1; i < n_attrs; i++) { // sanity check: order of props array must match SPAttr - g_assert( (int)(props[i].code) == i); + g_assert((int)(props[i].code) == i); m_map[props[i].name] = props[i].code; } } }; -SPAttr -sp_attribute_lookup(gchar const *key) +SPAttr sp_attribute_lookup(gchar const *key) { static AttributeLookupImpl const _instance; auto it = _instance.m_map.find(key); @@ -600,8 +601,7 @@ sp_attribute_lookup(gchar const *key) return SPAttr::INVALID; } -gchar const * -sp_attribute_name(SPAttr id) +gchar const *sp_attribute_name(SPAttr id) { g_assert((int)id < n_attrs); return props[(int)id].name; @@ -619,7 +619,8 @@ std::vector sp_attribute_name_list(bool css_only) return result; } -bool SP_ATTRIBUTE_IS_CSS(SPAttr k) { // +bool SP_ATTRIBUTE_IS_CSS(SPAttr k) +{ // return (k >= SPAttr::D) && (k < SPAttr::SYSTEM_LANGUAGE); } diff --git a/src/attributes.h b/src/attributes.h index cfdf18cdcedb330b340e6708b84b9b18b485c20d..a1e20316020195aebd63663a140e0d96e594c423 100644 --- a/src/attributes.h +++ b/src/attributes.h @@ -24,8 +24,9 @@ * line-by-line comparison. Also, inorder for proper parsing, some * properites must be before others (e.g. 'font' before 'font-family'). */ -enum class SPAttr { - INVALID, ///< Must have value 0. +enum class SPAttr +{ + INVALID, ///< Must have value 0. /* SPObject */ ID, STYLE, @@ -229,20 +230,20 @@ enum class SPAttr { TYPE, VALUES, /*feComponentTransfer*/ - //TYPE, + // TYPE, TABLEVALUES, SLOPE, INTERCEPT, AMPLITUDE, EXPONENT, - //OFFSET, + // OFFSET, /*feComposite*/ OPERATOR, K1, K2, K3, K4, - //IN2, + // IN2, /*feConvolveMatrix*/ ORDER, KERNELMATRIX, @@ -256,12 +257,12 @@ enum class SPAttr { /*feDiffuseLighting*/ SURFACESCALE, DIFFUSECONSTANT, - //KERNELUNITLENGTH, + // KERNELUNITLENGTH, /*feDisplacementMap*/ SCALE, XCHANNELSELECTOR, YCHANNELSELECTOR, - //IN2, + // IN2, /*feDistantLight*/ AZIMUTH, ELEVATION, @@ -277,13 +278,13 @@ enum class SPAttr { /*feImage*/ /*feMerge*/ /*feMorphology*/ - //OPERATOR, + // OPERATOR, RADIUS, /*feOffset*/ - //DX, - //DY, + // DX, + // DY, /*feSpecularLighting*/ - //SURFACESCALE, + // SURFACESCALE, SPECULARCONSTANT, SPECULAREXPONENT, /*feTile*/ @@ -292,7 +293,7 @@ enum class SPAttr { NUMOCTAVES, SEED, STITCHTILES, - //TYPE, + // TYPE, /* SPGradient */ GRADIENTUNITS, GRADIENTTRANSFORM, @@ -304,7 +305,7 @@ enum class SPAttr { FR, /* SPMeshPatch */ TENSOR, - //TYPE, + // TYPE, /* SPPattern */ PATTERNUNITS, PATTERNCONTENTUNITS, @@ -327,7 +328,7 @@ enum class SPAttr { MARKERHEIGHT, ORIENT, /* SPStyleElem */ - //TYPE, + // TYPE, /* Animations */ ATTRIBUTENAME, ATTRIBUTETYPE, @@ -342,7 +343,7 @@ enum class SPAttr { /* Interpolating animations */ CALCMODE, - //VALUES, + // VALUES, KEYTIMES, KEYSPLINES, FROM, @@ -362,7 +363,7 @@ enum class SPAttr { UNICODE, GLYPH_NAME, - //ORIENTATION, + // ORIENTATION, ARABIC_FORM, LANG, @@ -374,18 +375,18 @@ enum class SPAttr { K, /**/ -// FONT_FAMILY, -// FONT_STYLE, -// FONT_VARIANT, -// FONT_WEIGHT, -// FONT_STRETCH, -// FONT_SIZE, + // FONT_FAMILY, + // FONT_STYLE, + // FONT_VARIANT, + // FONT_WEIGHT, + // FONT_STRETCH, + // FONT_SIZE, UNICODE_RANGE, UNITS_PER_EM, PANOSE_1, STEMV, STEMH, - //SLOPE, + // SLOPE, CAP_HEIGHT, X_HEIGHT, ACCENT_HEIGHT, @@ -451,7 +452,7 @@ enum class SPAttr { SOLID_COLOR, SOLID_OPACITY, VECTOR_EFFECT, - + /* CSS Blending/Compositing */ MIX_BLEND_MODE, ISOLATION, @@ -470,7 +471,7 @@ enum class SPAttr { /* Font: Order is important! */ FONT, FONT_FAMILY, - INKSCAPE_FONT_SPEC, // Remove me + INKSCAPE_FONT_SPEC, // Remove me FONT_SIZE, FONT_SIZE_ADJUST, FONT_STRETCH, @@ -518,9 +519,9 @@ enum class SPAttr { SHAPE_PADDING, SHAPE_MARGIN, INLINE_SIZE, - + /* Text Decoration */ - TEXT_DECORATION, // CSS 2/CSS3-Shorthand + TEXT_DECORATION, // CSS 2/CSS3-Shorthand TEXT_DECORATION_LINE, TEXT_DECORATION_STYLE, TEXT_DECORATION_COLOR, @@ -588,7 +589,6 @@ std::vector sp_attribute_name_list(bool css_only = false); #endif - /* Local Variables: mode:c++ diff --git a/src/auto-save.cpp b/src/auto-save.cpp index 69779f870a10c877f4750f2fdd7aa58e47a0e091..35a1875378864ba7f6162c7c59c305a421eb85d9 100644 --- a/src/auto-save.cpp +++ b/src/auto-save.cpp @@ -10,20 +10,19 @@ * */ +#include "auto-save.h" + #include +#include // Internationalization #include #include #include -#include // Internationalization - -#include "auto-save.h" #include "document.h" -#include "inkscape-application.h" -#include "preferences.h" - #include "extension/output.h" +#include "inkscape-application.h" #include "io/sys.h" +#include "preferences.h" #include "xml/repr.h" #ifdef _WIN32 @@ -33,15 +32,13 @@ typedef int uid_t; namespace Inkscape { -void -AutoSave::init(InkscapeApplication* app) +void AutoSave::init(InkscapeApplication *app) { _app = app; start(); } -void -AutoSave::start() +void AutoSave::start() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); static sigc::connection autosave_connection; @@ -61,8 +58,7 @@ AutoSave::start() } } -bool -AutoSave::save() +bool AutoSave::save() { std::vector documents = _app->get_documents(); if (documents.empty()) { @@ -81,7 +77,8 @@ AutoSave::save() Glib::RefPtr dir_file = Gio::File::create_for_path(autosave_dir); if (!dir_file->query_exists()) { if (!dir_file->make_directory_with_parents()) { - std::cerr << "InkscapeApplication::document_autosave: Failed to create autosave directory: " << Glib::filename_to_utf8(autosave_dir) << std::endl; + std::cerr << "InkscapeApplication::document_autosave: Failed to create autosave directory: " + << Glib::filename_to_utf8(autosave_dir) << std::endl; return true; } } @@ -99,11 +96,9 @@ AutoSave::save() int docnum = 0; int autosave_max = prefs->getInt("/options/autosave/max", 10); for (auto document : documents) { - ++docnum; // Give each document a unique number. if (document->isModifiedSinceAutoSave()) { - std::string base_name = "inkscape-autosave-" + std::to_string(uid); // The following we do for each document (rather wasteful...) so that @@ -126,8 +121,8 @@ AutoSave::save() // Delete (making room for one more). std::string path = Glib::build_filename(autosave_dir, file_name); if (unlink(path.c_str()) == -1) { - std::cerr << "InkscapeApplication::document_autosave: Failed to unlink file: " - << path << ": " << strerror(errno) << std::endl; + std::cerr << "InkscapeApplication::document_autosave: Failed to unlink file: " << path + << ": " << strerror(errno) << std::endl; } } } @@ -135,12 +130,8 @@ AutoSave::save() // Construct save file path std::stringstream ssf; - ssf << "inkscape-autosave-" - << std::to_string(uid) << "-" - << std::to_string(pid) << "-" - << ss.str() << "-" - << std::setfill('0') << std::setw(3) << std::to_string(docnum) - << ".svg"; + ssf << "inkscape-autosave-" << std::to_string(uid) << "-" << std::to_string(pid) << "-" << ss.str() << "-" + << std::setfill('0') << std::setw(3) << std::to_string(docnum) << ".svg"; std::string path = Glib::build_filename(autosave_dir, ssf.str()); // Try to save the file @@ -177,8 +168,7 @@ AutoSave::save() return true; } -void -AutoSave::restart() +void AutoSave::restart() { AutoSave::getInstance().start(); } diff --git a/src/auto-save.h b/src/auto-save.h index 83cc27db20c41ea993e7f722ffb4646e1b3fc45c..41f5ca0fca55230e4509578861ecac761658c153 100644 --- a/src/auto-save.h +++ b/src/auto-save.h @@ -17,7 +17,8 @@ class InkscapeApplication; namespace Inkscape { -class AutoSave { +class AutoSave +{ private: AutoSave() = default; @@ -39,7 +40,7 @@ public: bool save(); private: - InkscapeApplication* _app = nullptr; + InkscapeApplication *_app = nullptr; }; } // namespace Inkscape diff --git a/src/axis-manip.cpp b/src/axis-manip.cpp index 66b5c82438fdca7cc8df8991e73c5f5b1a0ced30..4117af51c3372807b44d02426af9a62709572a79 100644 --- a/src/axis-manip.cpp +++ b/src/axis-manip.cpp @@ -10,39 +10,44 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "axis-manip.h" +#include + namespace Proj { -Axis axes[4] = { X, Y, Z, W }; +Axis axes[4] = {X, Y, Z, W}; } // namespace Proj - namespace Box3D { -Axis axes[3] = { X, Y, Z }; -Axis planes[3] = { XY, XZ, YZ }; -FrontOrRear face_positions [2] = { FRONT, REAR }; +Axis axes[3] = {X, Y, Z}; +Axis planes[3] = {XY, XZ, YZ}; +FrontOrRear face_positions[2] = {FRONT, REAR}; -std::pair -get_remaining_axes (Axis axis) { - if (!is_single_axis_direction (axis)) return std::make_pair (NONE, NONE); - Axis plane = orth_plane_or_axis (axis); - return std::make_pair (extract_first_axis_direction (plane), extract_second_axis_direction (plane)); +std::pair get_remaining_axes(Axis axis) +{ + if (!is_single_axis_direction(axis)) + return std::make_pair(NONE, NONE); + Axis plane = orth_plane_or_axis(axis); + return std::make_pair(extract_first_axis_direction(plane), extract_second_axis_direction(plane)); } -Glib::ustring string_from_axes (Box3D::Axis axis) { +Glib::ustring string_from_axes(Box3D::Axis axis) +{ Glib::ustring result; - if (axis & Box3D::X) result += "X"; - if (axis & Box3D::Y) result += "Y"; - if (axis & Box3D::Z) result += "Z"; + if (axis & Box3D::X) + result += "X"; + if (axis & Box3D::Y) + result += "Y"; + if (axis & Box3D::Z) + result += "Z"; return result; } -} // namespace Box3D - +} // namespace Box3D + /* Local Variables: mode:c++ diff --git a/src/axis-manip.h b/src/axis-manip.h index a0d019110163e7f60f5e6f880cc30ddbadc54c1d..1d84f763c5f9fdc436dde111e5ba54ae0466a29b 100644 --- a/src/axis-manip.h +++ b/src/axis-manip.h @@ -14,20 +14,22 @@ #define SEEN_AXIS_MANIP_H #include +#include #include #include -#include namespace Proj { -enum VPState { +enum VPState +{ VP_FINITE = 0, VP_INFINITE }; // The X-/Y-/Z-axis corresponds to the first/second/third digit // in binary representation, respectively. -enum Axis { +enum Axis +{ X = 0, Y = 1, Z = 2, @@ -37,14 +39,24 @@ enum Axis { extern Axis axes[4]; -inline char const* -string_from_axis(Proj::Axis axis) { +inline char const *string_from_axis(Proj::Axis axis) +{ switch (axis) { - case X: return "X"; break; - case Y: return "Y"; break; - case Z: return "Z"; break; - case W: return "W"; break; - case NONE: return "NONE"; break; + case X: + return "X"; + break; + case Y: + return "Y"; + break; + case Z: + return "Z"; + break; + case W: + return "W"; + break; + case NONE: + return "NONE"; + break; } return ""; } @@ -57,7 +69,8 @@ const double epsilon = 1e-6; // The X-/Y-/Z-axis corresponds to the first/second/third digit // in binary representation, respectively. -enum Axis { +enum Axis +{ X = 1, Y = 2, Z = 4, @@ -70,65 +83,69 @@ enum Axis { // We use the fourth bit in binary representation // to indicate whether a face is front or rear. -enum FrontOrRear { // find a better name +enum FrontOrRear +{ // find a better name FRONT = 0, REAR = 8 }; // converts X, Y, Z respectively to 0, 1, 2 (for use as array indices, e.g) -inline int axis_to_int(Box3D::Axis axis) { +inline int axis_to_int(Box3D::Axis axis) +{ switch (axis) { - case Box3D::X: - return 0; - case Box3D::Y: - return 1; - case Box3D::Z: - return 2; - case Box3D::NONE: - return -1; - default: - assert(false); - return -1; // help compiler's flow analysis (-Werror=return-value) + case Box3D::X: + return 0; + case Box3D::Y: + return 1; + case Box3D::Z: + return 2; + case Box3D::NONE: + return -1; + default: + assert(false); + return -1; // help compiler's flow analysis (-Werror=return-value) } } -inline Proj::Axis toProj(Box3D::Axis axis) { +inline Proj::Axis toProj(Box3D::Axis axis) +{ switch (axis) { - case Box3D::X: - return Proj::X; - case Box3D::Y: - return Proj::Y; - case Box3D::Z: - return Proj::Z; - case Box3D::NONE: - return Proj::NONE; - default: - assert(false); - return Proj::NONE; // help compiler's flow analysis (-Werror=return-value) + case Box3D::X: + return Proj::X; + case Box3D::Y: + return Proj::Y; + case Box3D::Z: + return Proj::Z; + case Box3D::NONE: + return Proj::NONE; + default: + assert(false); + return Proj::NONE; // help compiler's flow analysis (-Werror=return-value) } } extern Axis axes[3]; extern Axis planes[3]; -extern FrontOrRear face_positions [2]; +extern FrontOrRear face_positions[2]; } // namespace Box3D namespace Proj { -inline Box3D::Axis toAffine(Proj::Axis axis) { +inline Box3D::Axis toAffine(Proj::Axis axis) +{ switch (axis) { - case Proj::X: - return Box3D::X; - case Proj::Y: - return Box3D::Y; - case Proj::Z: - return Box3D::Z; - case Proj::NONE: - return Box3D::NONE; - default: - assert(false); - return Box3D::NONE; // help compiler's flow analysis (-Werror=return-value) + case Proj::X: + return Box3D::X; + case Proj::Y: + return Box3D::Y; + case Proj::Z: + return Box3D::Z; + case Proj::NONE: + return Box3D::NONE; + default: + assert(false); + return Box3D::NONE; // help compiler's flow analysis (-Werror=return-value) } } @@ -136,7 +153,7 @@ inline Box3D::Axis toAffine(Proj::Axis axis) { namespace Box3D { -/* +/* * Identify the axes X, Y, Z with the numbers 0, 1, 2. * A box's face is identified by the axis perpendicular to it. * For a rear face, add 3. @@ -146,39 +163,61 @@ namespace Box3D { // (which is normally used to index an array). Return -1 if the bit sequence // does not specify a face. A face can either be given by its plane (e.g, XY) // or by the axis that is orthogonal to it (e.g., Z). -inline int face_to_int (unsigned int face_id) { +inline int face_to_int(unsigned int face_id) +{ switch (face_id) { - case 1: return 0; - case 2: return 1; - case 4: return 2; - case 3: return 2; - case 5: return 1; - case 6: return 0; - - case 9: return 3; - case 10: return 4; - case 12: return 5; - case 11: return 5; - case 13: return 4; - case 14: return 3; - - default: return -1; + case 1: + return 0; + case 2: + return 1; + case 4: + return 2; + case 3: + return 2; + case 5: + return 1; + case 6: + return 0; + + case 9: + return 3; + case 10: + return 4; + case 12: + return 5; + case 11: + return 5; + case 13: + return 4; + case 14: + return 3; + + default: + return -1; } } -inline int int_to_face (unsigned id) { +inline int int_to_face(unsigned id) +{ switch (id) { - case 0: return Box3D::YZ ^ Box3D::FRONT; - case 1: return Box3D::XZ ^ Box3D::FRONT; - case 2: return Box3D::XY ^ Box3D::FRONT; - case 3: return Box3D::YZ ^ Box3D::REAR; - case 4: return Box3D::XZ ^ Box3D::REAR; - case 5: return Box3D::XY ^ Box3D::REAR; + case 0: + return Box3D::YZ ^ Box3D::FRONT; + case 1: + return Box3D::XZ ^ Box3D::FRONT; + case 2: + return Box3D::XY ^ Box3D::FRONT; + case 3: + return Box3D::YZ ^ Box3D::REAR; + case 4: + return Box3D::XZ ^ Box3D::REAR; + case 5: + return Box3D::XY ^ Box3D::REAR; } return Box3D::NONE; // should not be reached } -inline bool is_face_id (unsigned int face_id) { +inline bool is_face_id(unsigned int face_id) +{ return !((face_id & 0x7) == 0x7); } @@ -188,20 +227,26 @@ inline gint opposite_face (guint face_id) { } **/ -inline unsigned int number_of_axis_directions (Box3D::Axis axis) { +inline unsigned int number_of_axis_directions(Box3D::Axis axis) +{ unsigned int num = 0; - if (axis & Box3D::X) num++; - if (axis & Box3D::Y) num++; - if (axis & Box3D::Z) num++; + if (axis & Box3D::X) + num++; + if (axis & Box3D::Y) + num++; + if (axis & Box3D::Z) + num++; return num; } -inline bool is_plane (Box3D::Axis plane) { - return (number_of_axis_directions (plane) == 2); +inline bool is_plane(Box3D::Axis plane) +{ + return (number_of_axis_directions(plane) == 2); } -inline bool is_single_axis_direction (Box3D::Axis dir) { +inline bool is_single_axis_direction(Box3D::Axis dir) +{ // tests whether dir is nonzero and a power of 2 return (!(dir & (dir - 1)) && dir); } @@ -210,38 +255,50 @@ inline bool is_single_axis_direction (Box3D::Axis dir) { * Given two axis directions out of {X, Y, Z} or the corresponding plane, return the remaining one * We don't check if 'plane' really specifies a plane (i.e., if it consists of precisely two directions). */ -inline Box3D::Axis third_axis_direction (Box3D::Axis dir1, Box3D::Axis dir2) { - return (Box3D::Axis) ((dir1 + dir2) ^ 0x7); +inline Box3D::Axis third_axis_direction(Box3D::Axis dir1, Box3D::Axis dir2) +{ + return (Box3D::Axis)((dir1 + dir2) ^ 0x7); } -inline Box3D::Axis third_axis_direction (Box3D::Axis plane) { - return (Box3D::Axis) (plane ^ 0x7); +inline Box3D::Axis third_axis_direction(Box3D::Axis plane) +{ + return (Box3D::Axis)(plane ^ 0x7); } /* returns the first/second axis direction occurring in the (possibly compound) expression 'dirs' */ -inline Box3D::Axis extract_first_axis_direction (Box3D::Axis dirs) { - if (dirs & Box3D::X) return Box3D::X; - if (dirs & Box3D::Y) return Box3D::Y; - if (dirs & Box3D::Z) return Box3D::Z; +inline Box3D::Axis extract_first_axis_direction(Box3D::Axis dirs) +{ + if (dirs & Box3D::X) + return Box3D::X; + if (dirs & Box3D::Y) + return Box3D::Y; + if (dirs & Box3D::Z) + return Box3D::Z; return Box3D::NONE; } -inline Box3D::Axis extract_second_axis_direction (Box3D::Axis dirs) { - return extract_first_axis_direction ((Box3D::Axis) (dirs ^ extract_first_axis_direction(dirs))); +inline Box3D::Axis extract_second_axis_direction(Box3D::Axis dirs) +{ + return extract_first_axis_direction((Box3D::Axis)(dirs ^ extract_first_axis_direction(dirs))); } -inline Box3D::Axis orth_plane_or_axis (Box3D::Axis axis) { - return (Box3D::Axis) (Box3D::XYZ ^ axis); +inline Box3D::Axis orth_plane_or_axis(Box3D::Axis axis) +{ + return (Box3D::Axis)(Box3D::XYZ ^ axis); } /* returns an axis direction perpendicular to the ones occurring in the (possibly compound) expression 'dirs' */ -inline Box3D::Axis get_perpendicular_axis_direction (Box3D::Axis dirs) { - if (!(dirs & Box3D::X)) return Box3D::X; - if (!(dirs & Box3D::Y)) return Box3D::Y; - if (!(dirs & Box3D::Z)) return Box3D::Z; +inline Box3D::Axis get_perpendicular_axis_direction(Box3D::Axis dirs) +{ + if (!(dirs & Box3D::X)) + return Box3D::X; + if (!(dirs & Box3D::Y)) + return Box3D::Y; + if (!(dirs & Box3D::Z)) + return Box3D::Z; return Box3D::NONE; } -Glib::ustring string_from_axes (Box3D::Axis axis); -std::pair get_remaining_axes (Axis axis); +Glib::ustring string_from_axes(Box3D::Axis axis); +std::pair get_remaining_axes(Axis axis); } // namespace Box3D diff --git a/src/bad-uri-exception.h b/src/bad-uri-exception.h index 2930b224f8ca729cd6aa9743c7fc88c542424447..4d8df01a88d98f7b510609b21d2b20de2de0e370 100644 --- a/src/bad-uri-exception.h +++ b/src/bad-uri-exception.h @@ -14,20 +14,23 @@ namespace Inkscape { -class BadURIException : public std::exception {}; +class BadURIException : public std::exception +{ +}; -class UnsupportedURIException : public BadURIException { +class UnsupportedURIException : public BadURIException +{ public: char const *what() const noexcept override { return "Unsupported URI"; } }; -class MalformedURIException : public BadURIException { +class MalformedURIException : public BadURIException +{ public: char const *what() const noexcept override { return "Malformed URI"; } }; -} - +} // namespace Inkscape #endif /* !SEEN_BAD_URI_EXCEPTION_H */ diff --git a/src/cms-color-types.h b/src/cms-color-types.h index a4aec7cd22f4408fdacf6803c72265be433ace48..ce62c2d818700188ce90aab4de496aa789ab083b 100644 --- a/src/cms-color-types.h +++ b/src/cms-color-types.h @@ -16,53 +16,56 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif - #if HAVE_STDINT_H -# include // uint8_t, etc +#include // uint8_t, etc #endif typedef unsigned int guint32; -typedef void * cmsHPROFILE; -typedef void * cmsHTRANSFORM; - +typedef void *cmsHPROFILE; +typedef void *cmsHTRANSFORM; namespace Inkscape { /** * Opaque holder of a 32-bit signature type. */ -class FourCCSig { +class FourCCSig +{ public: - FourCCSig( FourCCSig const &other ) = default; + FourCCSig(FourCCSig const &other) = default; protected: - FourCCSig( guint32 value ) : value(value) {}; + FourCCSig(guint32 value) + : value(value){}; guint32 value; }; -class ColorSpaceSig : public FourCCSig { +class ColorSpaceSig : public FourCCSig +{ public: - ColorSpaceSig( ColorSpaceSig const &other ) = default; + ColorSpaceSig(ColorSpaceSig const &other) = default; protected: - ColorSpaceSig( guint32 value ) : FourCCSig(value) {}; + ColorSpaceSig(guint32 value) + : FourCCSig(value){}; }; -class ColorProfileClassSig : public FourCCSig { +class ColorProfileClassSig : public FourCCSig +{ public: - ColorProfileClassSig( ColorProfileClassSig const &other ) = default; + ColorProfileClassSig(ColorProfileClassSig const &other) = default; protected: - ColorProfileClassSig( guint32 value ) : FourCCSig(value) {}; + ColorProfileClassSig(guint32 value) + : FourCCSig(value){}; }; } // namespace Inkscape - #endif // SEEN_CMS_COLOR_TYPES_H /* diff --git a/src/cms-system.h b/src/cms-system.h index 99cbcb701d3319d965eced719bad4bba327cb74e..57210f565e7e23e13733e3bab7c4e9f57732f044 100644 --- a/src/cms-system.h +++ b/src/cms-system.h @@ -10,12 +10,13 @@ #ifndef SEEN_COLOR_PROFILE_FNS_H #define SEEN_COLOR_PROFILE_FNS_H -/** \file +/** \file * Macros and fn declarations related to linear gradients. */ -#include #include +#include + #include "cms-color-types.h" class SPDocument; @@ -24,15 +25,16 @@ namespace Inkscape { class ColorProfile; -class CMSSystem { +class CMSSystem +{ public: - static cmsHPROFILE getHandle( SPDocument* document, unsigned int* intent, char const* name ); + static cmsHPROFILE getHandle(SPDocument *document, unsigned int *intent, char const *name); static cmsHTRANSFORM getDisplayTransform(); static std::string getDisplayId(int monitor); - static Glib::ustring setDisplayPer( void* buf, unsigned int bufLen, int monitor ); + static Glib::ustring setDisplayPer(void *buf, unsigned int bufLen, int monitor); static cmsHTRANSFORM getDisplayPer(std::string const &id); @@ -40,7 +42,7 @@ public: static std::vector getSoftproofNames(); - static Glib::ustring getPathForProfile(Glib::ustring const& name); + static Glib::ustring getPathForProfile(Glib::ustring const &name); static void doTransform(cmsHTRANSFORM transform, void *inBuf, void *outBuf, unsigned int size); @@ -49,10 +51,8 @@ public: static int getChannelCount(ColorProfile const *profile); }; - } // namespace Inkscape - #endif // !SEEN_COLOR_PROFILE_FNS_H /* diff --git a/src/color-profile-cms-fns.h b/src/color-profile-cms-fns.h index 857ee60ebee2b88196affcf72b99b4fb1bcec8f0..8e68fe9df23da9872506877c95f2275a07e8fd92 100644 --- a/src/color-profile-cms-fns.h +++ b/src/color-profile-cms-fns.h @@ -11,11 +11,11 @@ #define SEEN_COLOR_PROFILE_CMS_FNS_H #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #if HAVE_LIBLCMS2 -# include +#include #endif // HAVE_LIBLCMS2 #include "cms-color-types.h" @@ -26,30 +26,39 @@ namespace Inkscape { // Note: these can later be adjusted to adapt for lcms2: -class ColorSpaceSigWrapper : public ColorSpaceSig { -public : - ColorSpaceSigWrapper( cmsColorSpaceSignature sig ) : ColorSpaceSig( static_cast(sig) ) {} - ColorSpaceSigWrapper( ColorSpaceSig const &other ) : ColorSpaceSig( other ) {} +class ColorSpaceSigWrapper : public ColorSpaceSig +{ +public: + ColorSpaceSigWrapper(cmsColorSpaceSignature sig) + : ColorSpaceSig(static_cast(sig)) + {} + ColorSpaceSigWrapper(ColorSpaceSig const &other) + : ColorSpaceSig(other) + {} operator cmsColorSpaceSignature() const { return static_cast(value); } }; -class ColorProfileClassSigWrapper : public ColorProfileClassSig { -public : - ColorProfileClassSigWrapper( cmsProfileClassSignature sig ) : ColorProfileClassSig( static_cast(sig) ) {} - ColorProfileClassSigWrapper( ColorProfileClassSig const &other ) : ColorProfileClassSig( other ) {} +class ColorProfileClassSigWrapper : public ColorProfileClassSig +{ +public: + ColorProfileClassSigWrapper(cmsProfileClassSignature sig) + : ColorProfileClassSig(static_cast(sig)) + {} + ColorProfileClassSigWrapper(ColorProfileClassSig const &other) + : ColorProfileClassSig(other) + {} operator cmsProfileClassSignature() const { return static_cast(value); } }; -cmsColorSpaceSignature asICColorSpaceSig(ColorSpaceSig const & sig); -cmsProfileClassSignature asICColorProfileClassSig(ColorProfileClassSig const & sig); +cmsColorSpaceSignature asICColorSpaceSig(ColorSpaceSig const &sig); +cmsProfileClassSignature asICColorProfileClassSig(ColorProfileClassSig const &sig); #endif // defined(HAVE_LIBLCMS2) } // namespace Inkscape - #endif // !SEEN_COLOR_PROFILE_CMS_FNS_H /* diff --git a/src/color-rgba.h b/src/color-rgba.h index fb1aae06da5fa9771641070ab0cc31048f863712..ea45fc4d7b4dc0cc097d9d1482e968bad8fca183 100644 --- a/src/color-rgba.h +++ b/src/color-rgba.h @@ -16,9 +16,9 @@ /** * A class to contain a floating point RGBA color as one unit. */ -class ColorRGBA { +class ColorRGBA +{ public: - /** * A constructor to create the color from four floating point values. * Load the values into the array of floats in this object. @@ -30,8 +30,10 @@ public: */ ColorRGBA(float c0, float c1, float c2, float c3) { - _c[0] = c0; _c[1] = c1; - _c[2] = c2; _c[3] = c3; + _c[0] = c0; + _c[1] = c1; + _c[2] = c2; + _c[3] = c3; } /** @@ -39,7 +41,7 @@ public: */ ColorRGBA() { - for (float & i : _c) + for (float &i : _c) i = 0.0; } @@ -51,11 +53,10 @@ public: */ ColorRGBA(unsigned int intcolor) { - _c[0] = ((intcolor & 0xff000000) >> 24) / 255.0; - _c[1] = ((intcolor & 0x00ff0000) >> 16) / 255.0; - _c[2] = ((intcolor & 0x0000ff00) >> 8) / 255.0; - _c[3] = ((intcolor & 0x000000ff) >> 0) / 255.0; - + _c[0] = ((intcolor & 0xff000000) >> 24) / 255.0; + _c[1] = ((intcolor & 0x00ff0000) >> 16) / 255.0; + _c[2] = ((intcolor & 0x0000ff00) >> 8) / 255.0; + _c[3] = ((intcolor & 0x000000ff) >> 0) / 255.0; } /** @@ -78,8 +79,9 @@ public: * @param m Values to use for the array. * @return This ColorRGBA object. */ - ColorRGBA &operator=(ColorRGBA const &m) { - for (unsigned i = 0 ; i < 4 ; ++i) { + ColorRGBA &operator=(ColorRGBA const &m) + { + for (unsigned i = 0; i < 4; ++i) { _c[i] = m._c[i]; } return *this; @@ -93,8 +95,9 @@ public: * @param i Which value to grab. * @return The requested value. */ - float operator[](unsigned int const i) const { - assert( unsigned(i) < 4 ); + float operator[](unsigned int const i) const + { + assert(unsigned(i) < 4); return _c[i]; } @@ -106,7 +109,8 @@ public: * @param other The guy to check against. * @return Whether or not they are equal. */ - bool operator== (const ColorRGBA &other) const { + bool operator==(const ColorRGBA &other) const + { for (int i = 0; i < 4; i++) { if (_c[i] != other[i]) return false; @@ -114,9 +118,7 @@ public: return true; } - bool operator!=(ColorRGBA const &o) const { - return !(*this == o); - } + bool operator!=(ColorRGBA const &o) const { return !(*this == o); } /** * Average two \c ColorRGBAs to create another one. @@ -130,11 +132,12 @@ public: * this while one is all the second. Default is * half and half. */ - ColorRGBA average (const ColorRGBA &second, const float weight = 0.5) const { + ColorRGBA average(const ColorRGBA &second, const float weight = 0.5) const + { float returnval[4]; for (int i = 0; i < 4; i++) { - returnval[i] = _c[i] * (1.0 - weight) + second[i] * weight; + returnval[i] = _c[i] * (1.0 - weight) + second[i] * weight; } return ColorRGBA(returnval[0], returnval[1], returnval[2], returnval[3]); @@ -146,13 +149,10 @@ public: * WARNING : this reduces color precision (from float to 0->255 int per component) * but it should be expected since we request this kind of output */ - unsigned int getIntValue() const { - - return - (int(round(_c[0]*255)) << 24) | - (int(round(_c[1]*255)) << 16) | - (int(round(_c[2]*255)) << 8) | - (int(round(_c[3]*255))); + unsigned int getIntValue() const + { + return (int(round(_c[0] * 255)) << 24) | (int(round(_c[1] * 255)) << 16) | (int(round(_c[2] * 255)) << 8) | + (int(round(_c[3] * 255))); } private: @@ -160,7 +160,6 @@ private: float _c[4]; }; - #endif // SEEN_COLOR_RGBA_H /* diff --git a/src/color.cpp b/src/color.cpp index dc9760f7586b415ea8cd5a08a5f32d636dbda84b..74e63a20cd907768957e6f6c9ecab2250fe2daa7 100644 --- a/src/color.cpp +++ b/src/color.cpp @@ -17,48 +17,55 @@ #include #include -#define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) -#define MAX(X,Y) ((X) > (Y) ? (X) : (Y)) +#define MIN(X, Y) ((X) < (Y) ? (X) : (Y)) +#define MAX(X, Y) ((X) > (Y) ? (X) : (Y)) #include "color.h" -#include "svg/svg-icc-color.h" -#include "svg/svg-color.h" - #include "svg/css-ostringstream.h" +#include "svg/svg-color.h" +#include "svg/svg-icc-color.h" -#define return_if_fail(x) if (!(x)) { printf("assertion failed: " #x); return; } -#define return_val_if_fail(x, val) if (!(x)) { printf("assertion failed: " #x); return val; } +#define return_if_fail(x) \ + if (!(x)) { \ + printf("assertion failed: " #x); \ + return; \ + } +#define return_val_if_fail(x, val) \ + if (!(x)) { \ + printf("assertion failed: " #x); \ + return val; \ + } using Inkscape::CSSOStringStream; -static bool profileMatches( SVGICCColor const* first, SVGICCColor const* second ); +static bool profileMatches(SVGICCColor const *first, SVGICCColor const *second); #define PROFILE_EPSILON 0.00000001 -SPColor::SPColor() : - icc(nullptr) +SPColor::SPColor() + : icc(nullptr) { v.c[0] = 0; v.c[1] = 0; v.c[2] = 0; } -SPColor::SPColor( SPColor const& other ) : - icc(nullptr) +SPColor::SPColor(SPColor const &other) + : icc(nullptr) { *this = other; } -SPColor::SPColor( float r, float g, float b ) : - icc(nullptr) +SPColor::SPColor(float r, float g, float b) + : icc(nullptr) { - set( r, g, b ); + set(r, g, b); } -SPColor::SPColor( guint32 value ) : - icc(nullptr) +SPColor::SPColor(guint32 value) + : icc(nullptr) { - set( value ); + set(value); } SPColor::~SPColor() @@ -67,19 +74,18 @@ SPColor::~SPColor() icc = nullptr; } - -SPColor& SPColor::operator= (SPColor const& other) +SPColor &SPColor::operator=(SPColor const &other) { - if (this == &other){ + if (this == &other) { return *this; } - - SVGICCColor* tmp_icc = other.icc ? new SVGICCColor(*other.icc) : nullptr; + + SVGICCColor *tmp_icc = other.icc ? new SVGICCColor(*other.icc) : nullptr; v.c[0] = other.v.c[0]; v.c[1] = other.v.c[1]; v.c[2] = other.v.c[2]; - if ( icc ) { + if (icc) { delete icc; } icc = tmp_icc; @@ -87,18 +93,14 @@ SPColor& SPColor::operator= (SPColor const& other) return *this; } - /** * Returns true if colors match. */ -bool SPColor::operator == (SPColor const& other) const +bool SPColor::operator==(SPColor const &other) const { - bool match = - (v.c[0] == other.v.c[0]) && - (v.c[1] == other.v.c[1]) && - (v.c[2] == other.v.c[2]); + bool match = (v.c[0] == other.v.c[0]) && (v.c[1] == other.v.c[1]) && (v.c[2] == other.v.c[2]); - match &= profileMatches( icc, other.icc ); + match &= profileMatches(icc, other.icc); return match; } @@ -107,27 +109,26 @@ bool SPColor::operator == (SPColor const& other) const * Returns true if no RGB value differs epsilon or more in both colors, * false otherwise. */ -bool SPColor::isClose( SPColor const& other, float epsilon ) const +bool SPColor::isClose(SPColor const &other, float epsilon) const { - bool match = (fabs((v.c[0]) - (other.v.c[0])) < epsilon) - && (fabs((v.c[1]) - (other.v.c[1])) < epsilon) - && (fabs((v.c[2]) - (other.v.c[2])) < epsilon); + bool match = (fabs((v.c[0]) - (other.v.c[0])) < epsilon) && (fabs((v.c[1]) - (other.v.c[1])) < epsilon) && + (fabs((v.c[2]) - (other.v.c[2])) < epsilon); - match &= profileMatches( icc, other.icc ); + match &= profileMatches(icc, other.icc); return match; } -static bool profileMatches( SVGICCColor const* first, SVGICCColor const* second ) { +static bool profileMatches(SVGICCColor const *first, SVGICCColor const *second) +{ bool match = false; - if ( !first && !second ) { + if (!first && !second) { match = true; } else { - match = first && second - && (first->colorProfile == second->colorProfile) - && (first->colors.size() == second->colors.size()); - if ( match ) { - for ( unsigned i = 0; i < first->colors.size(); i++ ) { + match = first && second && (first->colorProfile == second->colorProfile) && + (first->colors.size() == second->colors.size()); + if (match) { + for (unsigned i = 0; i < first->colors.size(); i++) { match &= (fabs(first->colors[i] - second->colors[i]) < PROFILE_EPSILON); } } @@ -139,7 +140,7 @@ static bool profileMatches( SVGICCColor const* first, SVGICCColor const* second * Sets RGB values and colorspace in color. * \pre 0 <={r,g,b}<=1 */ -void SPColor::set( float r, float g, float b ) +void SPColor::set(float r, float g, float b) { return_if_fail(r >= 0.0); return_if_fail(r <= 1.0); @@ -157,7 +158,7 @@ void SPColor::set( float r, float g, float b ) /** * Converts 32bit value to RGB floats and sets color. */ -void SPColor::set( guint32 value ) +void SPColor::set(guint32 value) { // TODO clear icc if set? v.c[0] = (value >> 24) / 255.0F; @@ -169,14 +170,12 @@ void SPColor::set( guint32 value ) * Convert SPColor with integer alpha value to 32bit RGBA value. * \pre alpha < 256 */ -guint32 SPColor::toRGBA32( int alpha ) const +guint32 SPColor::toRGBA32(int alpha) const { - return_val_if_fail (alpha <= 0xff, 0x0); + return_val_if_fail(alpha <= 0xff, 0x0); - guint32 rgba = SP_RGBA32_U_COMPOSE( SP_COLOR_F_TO_U(v.c[0]), - SP_COLOR_F_TO_U(v.c[1]), - SP_COLOR_F_TO_U(v.c[2]), - alpha ); + guint32 rgba = + SP_RGBA32_U_COMPOSE(SP_COLOR_F_TO_U(v.c[0]), SP_COLOR_F_TO_U(v.c[1]), SP_COLOR_F_TO_U(v.c[2]), alpha); return rgba; } @@ -184,12 +183,12 @@ guint32 SPColor::toRGBA32( int alpha ) const * Convert SPColor with float alpha value to 32bit RGBA value. * \pre color != NULL && 0 <= alpha <= 1 */ -guint32 SPColor::toRGBA32( double alpha ) const +guint32 SPColor::toRGBA32(double alpha) const { return_val_if_fail(alpha >= 0.0, 0x0); return_val_if_fail(alpha <= 1.0, 0x0); - return toRGBA32( static_cast(SP_COLOR_F_TO_U(alpha)) ); + return toRGBA32(static_cast(SP_COLOR_F_TO_U(alpha))); } std::string SPColor::toString() const @@ -200,8 +199,8 @@ std::string SPColor::toString() const sp_svg_write_color(tmp, sizeof(tmp), toRGBA32(0x0ff)); css << tmp; - if ( icc ) { - if ( !css.str().empty() ) { + if (icc) { + if (!css.str().empty()) { css << " "; } css << "icc-color(" << icc->colorProfile; @@ -214,15 +213,13 @@ std::string SPColor::toString() const return css.str(); } - /** * Fill rgb float array with values from SPColor. * \pre color != NULL && rgb != NULL && rgb[0-2] is meaningful */ -void -SPColor::get_rgb_floatv(float *rgb) const +void SPColor::get_rgb_floatv(float *rgb) const { - return_if_fail (rgb != nullptr); + return_if_fail(rgb != nullptr); rgb[0] = v.c[0]; rgb[1] = v.c[1]; @@ -233,15 +230,11 @@ SPColor::get_rgb_floatv(float *rgb) const * Fill cmyk float array with values from SPColor. * \pre color != NULL && cmyk != NULL && cmyk[0-3] is meaningful */ -void -SPColor::get_cmyk_floatv(float *cmyk) const +void SPColor::get_cmyk_floatv(float *cmyk) const { - return_if_fail (cmyk != nullptr); + return_if_fail(cmyk != nullptr); - SPColor::rgb_to_cmyk_floatv( cmyk, - v.c[0], - v.c[1], - v.c[2] ); + SPColor::rgb_to_cmyk_floatv(cmyk, v.c[0], v.c[1], v.c[2]); } /* Plain mode helpers */ @@ -249,13 +242,12 @@ SPColor::get_cmyk_floatv(float *cmyk) const /** * Fill hsv float array from r,g,b float values. */ -void -SPColor::rgb_to_hsv_floatv (float *hsv, float r, float g, float b) +void SPColor::rgb_to_hsv_floatv(float *hsv, float r, float g, float b) { float max, min, delta; - max = MAX (MAX (r, g), b); - min = MIN (MIN (r, g), b); + max = MAX(MAX(r, g), b); + min = MIN(MIN(r, g), b); delta = max - min; hsv[2] = max; @@ -277,22 +269,21 @@ SPColor::rgb_to_hsv_floatv (float *hsv, float r, float g, float b) hsv[0] = hsv[0] / 6.0; - if (hsv[0] < 0) hsv[0] += 1.0; - } - else + if (hsv[0] < 0) + hsv[0] += 1.0; + } else hsv[0] = 0.0; } /** * Fill rgb float array from h,s,v float values. */ -void -SPColor::hsv_to_rgb_floatv (float *rgb, float h, float s, float v) +void SPColor::hsv_to_rgb_floatv(float *rgb, float h, float s, float v) { double f, w, q, t, d; d = h * 5.99999999; - f = d - floor (d); + f = d - floor(d); w = v * (1.0 - s); q = v * (1.0 - (s * f)); t = v * (1.0 - (s * (1.0 - f))); @@ -327,14 +318,13 @@ SPColor::hsv_to_rgb_floatv (float *rgb, float h, float s, float v) /** * Fill hsl float array from r,g,b float values. */ -void -SPColor::rgb_to_hsl_floatv (float *hsl, float r, float g, float b) +void SPColor::rgb_to_hsl_floatv(float *hsl, float r, float g, float b) { - float max = MAX (MAX (r, g), b); - float min = MIN (MIN (r, g), b); + float max = MAX(MAX(r, g), b); + float min = MIN(MIN(r, g), b); float delta = max - min; - hsl[2] = (max + min)/2.0; + hsl[2] = (max + min) / 2.0; if (delta == 0) { hsl[0] = 0; @@ -345,34 +335,42 @@ SPColor::rgb_to_hsl_floatv (float *hsl, float r, float g, float b) else hsl[1] = delta / (2 - max - min); - if (r == max) hsl[0] = (g - b) / delta; - else if (g == max) hsl[0] = 2.0 + (b - r) / delta; - else if (b == max) hsl[0] = 4.0 + (r - g) / delta; + if (r == max) + hsl[0] = (g - b) / delta; + else if (g == max) + hsl[0] = 2.0 + (b - r) / delta; + else if (b == max) + hsl[0] = 4.0 + (r - g) / delta; hsl[0] = hsl[0] / 6.0; - if (hsl[0] < 0) hsl[0] += 1; - if (hsl[0] > 1) hsl[0] -= 1; + if (hsl[0] < 0) + hsl[0] += 1; + if (hsl[0] > 1) + hsl[0] -= 1; } } -static float -hue_2_rgb (float v1, float v2, float h) +static float hue_2_rgb(float v1, float v2, float h) { - if (h < 0) h += 6.0; - if (h > 6) h -= 6.0; - - if (h < 1) return v1 + (v2 - v1) * h; - if (h < 3) return v2; - if (h < 4) return v1 + (v2 - v1) * (4 - h); + if (h < 0) + h += 6.0; + if (h > 6) + h -= 6.0; + + if (h < 1) + return v1 + (v2 - v1) * h; + if (h < 3) + return v2; + if (h < 4) + return v1 + (v2 - v1) * (4 - h); return v1; } /** * Fill rgb float array from h,s,l float values. */ -void -SPColor::hsl_to_rgb_floatv (float *rgb, float h, float s, float l) +void SPColor::hsl_to_rgb_floatv(float *rgb, float h, float s, float l) { if (s == 0) { rgb[0] = l; @@ -383,28 +381,27 @@ SPColor::hsl_to_rgb_floatv (float *rgb, float h, float s, float l) if (l < 0.5) { v2 = l * (1 + s); } else { - v2 = l + s - l*s; + v2 = l + s - l * s; } - float v1 = 2*l - v2; + float v1 = 2 * l - v2; - rgb[0] = hue_2_rgb (v1, v2, h*6 + 2.0); - rgb[1] = hue_2_rgb (v1, v2, h*6); - rgb[2] = hue_2_rgb (v1, v2, h*6 - 2.0); + rgb[0] = hue_2_rgb(v1, v2, h * 6 + 2.0); + rgb[1] = hue_2_rgb(v1, v2, h * 6); + rgb[2] = hue_2_rgb(v1, v2, h * 6 - 2.0); } } /** * Fill cmyk float array from r,g,b float values. */ -void -SPColor::rgb_to_cmyk_floatv (float *cmyk, float r, float g, float b) +void SPColor::rgb_to_cmyk_floatv(float *cmyk, float r, float g, float b) { float c, m, y, k, kd; c = 1.0 - r; m = 1.0 - g; y = 1.0 - b; - k = MIN (MIN (c, m), y); + k = MIN(MIN(c, m), y); c = c - k; m = m - k; @@ -427,8 +424,7 @@ SPColor::rgb_to_cmyk_floatv (float *cmyk, float r, float g, float b) /** * Fill rgb float array from c,m,y,k float values. */ -void -SPColor::cmyk_to_rgb_floatv (float *rgb, float c, float m, float y, float k) +void SPColor::cmyk_to_rgb_floatv(float *rgb, float c, float m, float y, float k) { float kd; diff --git a/src/color.h b/src/color.h index 60708d24262c9af5d9a53cb09ed75e7aa166cac2..4ebf4ab3285c6cec6814f42e8571d95a6ff5f200 100644 --- a/src/color.h +++ b/src/color.h @@ -22,65 +22,68 @@ typedef unsigned int guint32; // uint is guaranteed to hold up to 2^32 − 1 #define SP_RGBA32_R_U(v) (((v) >> 24) & 0xff) #define SP_RGBA32_G_U(v) (((v) >> 16) & 0xff) #define SP_RGBA32_B_U(v) (((v) >> 8) & 0xff) -#define SP_RGBA32_A_U(v) ((v) & 0xff) +#define SP_RGBA32_A_U(v) ((v)&0xff) #define SP_COLOR_U_TO_F(v) ((v) / 255.0) -#define SP_COLOR_F_TO_U(v) ((unsigned int) ((v) * 255. + .5)) -#define SP_RGBA32_R_F(v) SP_COLOR_U_TO_F (SP_RGBA32_R_U (v)) -#define SP_RGBA32_G_F(v) SP_COLOR_U_TO_F (SP_RGBA32_G_U (v)) -#define SP_RGBA32_B_F(v) SP_COLOR_U_TO_F (SP_RGBA32_B_U (v)) -#define SP_RGBA32_A_F(v) SP_COLOR_U_TO_F (SP_RGBA32_A_U (v)) -#define SP_RGBA32_U_COMPOSE(r,g,b,a) ((((r) & 0xff) << 24) | (((g) & 0xff) << 16) | (((b) & 0xff) << 8) | ((a) & 0xff)) -#define SP_RGBA32_F_COMPOSE(r,g,b,a) SP_RGBA32_U_COMPOSE (SP_COLOR_F_TO_U (r), SP_COLOR_F_TO_U (g), SP_COLOR_F_TO_U (b), SP_COLOR_F_TO_U (a)) -#define SP_RGBA32_C_COMPOSE(c,o) SP_RGBA32_U_COMPOSE(SP_RGBA32_R_U(c),SP_RGBA32_G_U(c),SP_RGBA32_B_U(c),SP_COLOR_F_TO_U(o)) +#define SP_COLOR_F_TO_U(v) ((unsigned int)((v)*255. + .5)) +#define SP_RGBA32_R_F(v) SP_COLOR_U_TO_F(SP_RGBA32_R_U(v)) +#define SP_RGBA32_G_F(v) SP_COLOR_U_TO_F(SP_RGBA32_G_U(v)) +#define SP_RGBA32_B_F(v) SP_COLOR_U_TO_F(SP_RGBA32_B_U(v)) +#define SP_RGBA32_A_F(v) SP_COLOR_U_TO_F(SP_RGBA32_A_U(v)) +#define SP_RGBA32_U_COMPOSE(r, g, b, a) ((((r)&0xff) << 24) | (((g)&0xff) << 16) | (((b)&0xff) << 8) | ((a)&0xff)) +#define SP_RGBA32_F_COMPOSE(r, g, b, a) \ + SP_RGBA32_U_COMPOSE(SP_COLOR_F_TO_U(r), SP_COLOR_F_TO_U(g), SP_COLOR_F_TO_U(b), SP_COLOR_F_TO_U(a)) +#define SP_RGBA32_C_COMPOSE(c, o) \ + SP_RGBA32_U_COMPOSE(SP_RGBA32_R_U(c), SP_RGBA32_G_U(c), SP_RGBA32_B_U(c), SP_COLOR_F_TO_U(o)) struct SVGICCColor; /** * An RGB color with optional icc-color part */ -struct SPColor { +struct SPColor +{ SPColor(); - SPColor( SPColor const& other ); - SPColor( float r, float g, float b ); - SPColor( guint32 value ); + SPColor(SPColor const &other); + SPColor(float r, float g, float b); + SPColor(guint32 value); virtual ~SPColor(); - SPColor& operator= (SPColor const& other); + SPColor &operator=(SPColor const &other); - bool operator == ( SPColor const& other ) const; - bool operator != ( SPColor const& other ) const { return !(*this == other); }; - bool isClose( SPColor const& other, float epsilon ) const; + bool operator==(SPColor const &other) const; + bool operator!=(SPColor const &other) const { return !(*this == other); }; + bool isClose(SPColor const &other, float epsilon) const; - void set( float r, float g, float b ); - void set( guint32 value ); + void set(float r, float g, float b); + void set(guint32 value); - guint32 toRGBA32( int alpha ) const; - guint32 toRGBA32( double alpha ) const; + guint32 toRGBA32(int alpha) const; + guint32 toRGBA32(double alpha) const; std::string toString() const; - SVGICCColor* icc; - union { + SVGICCColor *icc; + union + { float c[3]; } v; - guint32 get_rgba32_ualpha (guint32 alpha) const; - guint32 get_rgba32_falpha (float alpha) const; + guint32 get_rgba32_ualpha(guint32 alpha) const; + guint32 get_rgba32_falpha(float alpha) const; - void get_rgb_floatv (float *rgb) const; - void get_cmyk_floatv (float *cmyk) const; + void get_rgb_floatv(float *rgb) const; + void get_cmyk_floatv(float *cmyk) const; /* Plain mode helpers */ - static void rgb_to_hsv_floatv (float *hsv, float r, float g, float b); - static void hsv_to_rgb_floatv (float *rgb, float h, float s, float v); + static void rgb_to_hsv_floatv(float *hsv, float r, float g, float b); + static void hsv_to_rgb_floatv(float *rgb, float h, float s, float v); - static void rgb_to_hsl_floatv (float *hsl, float r, float g, float b); - static void hsl_to_rgb_floatv (float *rgb, float h, float s, float l); + static void rgb_to_hsl_floatv(float *hsl, float r, float g, float b); + static void hsl_to_rgb_floatv(float *rgb, float h, float s, float l); - static void rgb_to_cmyk_floatv (float *cmyk, float r, float g, float b); - static void cmyk_to_rgb_floatv (float *rgb, float c, float m, float y, float k); + static void rgb_to_cmyk_floatv(float *cmyk, float r, float g, float b); + static void cmyk_to_rgb_floatv(float *rgb, float c, float m, float y, float k); }; - #endif // SEEN_SP_COLOR_H diff --git a/src/colorspace.h b/src/colorspace.h index bed120b5e29eed0787381bf1efb65015841d5328..0de73dee0a79b2ce4d49fd24c40c079c8fb08761 100644 --- a/src/colorspace.h +++ b/src/colorspace.h @@ -12,26 +12,23 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #if HAVE_STDINT_H -# include +#include #endif -#include #include +#include - -namespace Inkscape -{ +namespace Inkscape { class ColorProfile; } // namespace Inkscape -namespace colorspace -{ +namespace colorspace { class Component { @@ -44,9 +41,9 @@ public: guint scale; }; -std::vector getColorSpaceInfo( uint32_t space ); +std::vector getColorSpaceInfo(uint32_t space); -std::vector getColorSpaceInfo( Inkscape::ColorProfile *prof ); +std::vector getColorSpaceInfo(Inkscape::ColorProfile *prof); } // namespace colorspace diff --git a/src/composite-undo-stack-observer.cpp b/src/composite-undo-stack-observer.cpp index 0f66c653c9daff3d3875598e7d2c58b6c8f6ce4d..33db439e80eef9726c3a0ab43d6d1afaf87aeeab 100644 --- a/src/composite-undo-stack-observer.cpp +++ b/src/composite-undo-stack-observer.cpp @@ -10,158 +10,150 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "composite-undo-stack-observer.h" + #include #include -#include "composite-undo-stack-observer.h" #include "xml/event.h" namespace Inkscape { -CompositeUndoStackObserver::CompositeUndoStackObserver() : _iterating(0) { } +CompositeUndoStackObserver::CompositeUndoStackObserver() + : _iterating(0) +{} CompositeUndoStackObserver::~CompositeUndoStackObserver() = default; -void -CompositeUndoStackObserver::add(UndoStackObserver& observer) +void CompositeUndoStackObserver::add(UndoStackObserver &observer) { - if (!this->_iterating) { - this->_active.push_back(UndoStackObserverRecord(observer)); - } else { - this->_pending.push_back(UndoStackObserverRecord(observer)); - } + if (!this->_iterating) { + this->_active.push_back(UndoStackObserverRecord(observer)); + } else { + this->_pending.push_back(UndoStackObserverRecord(observer)); + } } -void -CompositeUndoStackObserver::remove(UndoStackObserver& observer) +void CompositeUndoStackObserver::remove(UndoStackObserver &observer) { - if (!this->_iterating) { - // logical-or operator short-circuits - this->_remove_one(this->_active, observer) || this->_remove_one(this->_pending, observer); - } else { - this->_mark_one(this->_active, observer) || this->_mark_one(this->_pending, observer); - } + if (!this->_iterating) { + // logical-or operator short-circuits + this->_remove_one(this->_active, observer) || this->_remove_one(this->_pending, observer); + } else { + this->_mark_one(this->_active, observer) || this->_mark_one(this->_pending, observer); + } } -void -CompositeUndoStackObserver::notifyUndoEvent(Event* log) +void CompositeUndoStackObserver::notifyUndoEvent(Event *log) { - this->_lock(); - for(UndoObserverRecordList::iterator i = this->_active.begin(); i != _active.end(); ++i) { - if (!i->to_remove) { - i->issueUndo(log); - } - } - this->_unlock(); + this->_lock(); + for (UndoObserverRecordList::iterator i = this->_active.begin(); i != _active.end(); ++i) { + if (!i->to_remove) { + i->issueUndo(log); + } + } + this->_unlock(); } -void -CompositeUndoStackObserver::notifyRedoEvent(Event* log) +void CompositeUndoStackObserver::notifyRedoEvent(Event *log) { - - this->_lock(); - for(UndoObserverRecordList::iterator i = this->_active.begin(); i != _active.end(); ++i) { - if (!i->to_remove) { - i->issueRedo(log); - } - } - this->_unlock(); + this->_lock(); + for (UndoObserverRecordList::iterator i = this->_active.begin(); i != _active.end(); ++i) { + if (!i->to_remove) { + i->issueRedo(log); + } + } + this->_unlock(); } -void -CompositeUndoStackObserver::notifyUndoCommitEvent(Event* log) +void CompositeUndoStackObserver::notifyUndoCommitEvent(Event *log) { - this->_lock(); - for(UndoObserverRecordList::iterator i = this->_active.begin(); i != _active.end(); ++i) { - if (!i->to_remove) { - i->issueUndoCommit(log); - } - } - this->_unlock(); + this->_lock(); + for (UndoObserverRecordList::iterator i = this->_active.begin(); i != _active.end(); ++i) { + if (!i->to_remove) { + i->issueUndoCommit(log); + } + } + this->_unlock(); } -void -CompositeUndoStackObserver::notifyClearUndoEvent() +void CompositeUndoStackObserver::notifyClearUndoEvent() { - this->_lock(); - for(UndoObserverRecordList::iterator i = this->_active.begin(); i != _active.end(); ++i) { - if (!i->to_remove) { - i->issueClearUndo(); - } - } - this->_unlock(); + this->_lock(); + for (UndoObserverRecordList::iterator i = this->_active.begin(); i != _active.end(); ++i) { + if (!i->to_remove) { + i->issueClearUndo(); + } + } + this->_unlock(); } -void -CompositeUndoStackObserver::notifyClearRedoEvent() +void CompositeUndoStackObserver::notifyClearRedoEvent() { - this->_lock(); - for(UndoObserverRecordList::iterator i = this->_active.begin(); i != _active.end(); ++i) { - if (!i->to_remove) { - i->issueClearRedo(); - } - } - this->_unlock(); + this->_lock(); + for (UndoObserverRecordList::iterator i = this->_active.begin(); i != _active.end(); ++i) { + if (!i->to_remove) { + i->issueClearRedo(); + } + } + this->_unlock(); } -bool -CompositeUndoStackObserver::_remove_one(UndoObserverRecordList& list, UndoStackObserver& o) +bool CompositeUndoStackObserver::_remove_one(UndoObserverRecordList &list, UndoStackObserver &o) { - UndoStackObserverRecord eq_comp(o); + UndoStackObserverRecord eq_comp(o); - UndoObserverRecordList::iterator i = std::find_if(list.begin(), list.end(), std::bind(std::equal_to< UndoStackObserverRecord >(), std::placeholders::_1, eq_comp )); + UndoObserverRecordList::iterator i = std::find_if( + list.begin(), list.end(), std::bind(std::equal_to(), std::placeholders::_1, eq_comp)); - if (i != list.end()) { - list.erase(i); - return true; - } else { - return false; - } + if (i != list.end()) { + list.erase(i); + return true; + } else { + return false; + } } -bool -CompositeUndoStackObserver::_mark_one(UndoObserverRecordList& list, UndoStackObserver& o) +bool CompositeUndoStackObserver::_mark_one(UndoObserverRecordList &list, UndoStackObserver &o) { - UndoStackObserverRecord eq_comp(o); + UndoStackObserverRecord eq_comp(o); - UndoObserverRecordList::iterator i = std::find_if(list.begin(), list.end(), std::bind(std::equal_to< UndoStackObserverRecord >(), std::placeholders::_1, eq_comp)); + UndoObserverRecordList::iterator i = std::find_if( + list.begin(), list.end(), std::bind(std::equal_to(), std::placeholders::_1, eq_comp)); - if (i != list.end()) { - (*i).to_remove = true; - return true; - } else { - return false; - } + if (i != list.end()) { + (*i).to_remove = true; + return true; + } else { + return false; + } } -void -CompositeUndoStackObserver::_unlock() +void CompositeUndoStackObserver::_unlock() { - if (!--this->_iterating) { - // Remove marked observers - UndoObserverRecordList::iterator i = this->_active.begin(); - for(; i != this->_active.begin(); ) { - if (i->to_remove) { - i = this->_active.erase(i); - } - else{ - ++i; - } - } - - i = this->_pending.begin(); - for(; i != this->_pending.begin(); ) { - if (i->to_remove) { - i = this->_active.erase(i); - } - else { - ++i; - } - } - - // Merge pending and active - this->_active.insert(this->_active.end(), this->_pending.begin(), this->_pending.end()); - this->_pending.clear(); - } + if (!--this->_iterating) { + // Remove marked observers + UndoObserverRecordList::iterator i = this->_active.begin(); + for (; i != this->_active.begin();) { + if (i->to_remove) { + i = this->_active.erase(i); + } else { + ++i; + } + } + + i = this->_pending.begin(); + for (; i != this->_pending.begin();) { + if (i->to_remove) { + i = this->_active.erase(i); + } else { + ++i; + } + } + + // Merge pending and active + this->_active.insert(this->_active.end(), this->_pending.begin(), this->_pending.end()); + this->_pending.clear(); + } } -} +} // namespace Inkscape diff --git a/src/composite-undo-stack-observer.h b/src/composite-undo-stack-observer.h index daf73b976d02a78b4be7f2081ac050f98edf62b6..5b8fac535a2af3245a59775448dd3dbb20eeea78 100644 --- a/src/composite-undo-stack-observer.h +++ b/src/composite-undo-stack-observer.h @@ -11,11 +11,11 @@ #ifndef SEEN_COMPOSITE_UNDO_COMMIT_OBSERVER_H #define SEEN_COMPOSITE_UNDO_COMMIT_OBSERVER_H +#include + #include "inkgc/gc-alloc.h" #include "undo-stack-observer.h" -#include - namespace Inkscape { struct Event; @@ -26,157 +26,143 @@ struct Event; * * Heavily inspired by Inkscape::XML::CompositeNodeObserver. */ -class CompositeUndoStackObserver : public UndoStackObserver { +class CompositeUndoStackObserver : public UndoStackObserver +{ public: - - /** - * Structure for tracking UndoStackObservers. - */ - struct UndoStackObserverRecord { - public: - /** - * Constructor. - * - * \param o Reference to the UndoStackObserver that this UndoStackObserverRecord - * will track. - */ - UndoStackObserverRecord(UndoStackObserver& o) : to_remove(false), _observer(o) { } - bool to_remove; - - /** - * Overloaded equality test operator to facilitate usage of STL find algorithms. - */ - bool operator==(UndoStackObserverRecord const& _x) const - { - return &(this->_observer) == &(_x._observer); - } - - /** - * Issue a redo event to the UndoStackObserver that is associated with this UndoStackObserverRecord. - * - * \param log The event log generated by the redo event. - */ - void issueRedo(Event* log) - { - this->_observer.notifyRedoEvent(log); - } - - /** - * Issue an undo event to the UndoStackObserver that is associated with this - * UndoStackObserverRecord. - * - * \param log The event log generated by the undo event. - */ - void issueUndo(Event* log) - { - this->_observer.notifyUndoEvent(log); - } - - /** - * Issues a committed event to the UndoStackObserver that is associated with this - * UndoStackObserverRecord. - * - * \param log The event log being committed to the undo stack. - */ - void issueUndoCommit(Event* log) - { - this->_observer.notifyUndoCommitEvent(log); - } - - /** - * Issue a clear undo event to the UndoStackObserver - * that is associated with this - * UndoStackObserverRecord. - */ - void issueClearUndo() - { - this->_observer.notifyClearUndoEvent(); - } - - /** - * Issue a clear redo event to the UndoStackObserver - * that is associated with this - * UndoStackObserverRecord. - */ - void issueClearRedo() - { - this->_observer.notifyClearRedoEvent(); - } - - private: - UndoStackObserver& _observer; - }; - - /// A list of UndoStackObserverRecords, used to aggregate multiple UndoStackObservers. - typedef std::list< UndoStackObserverRecord, GC::Alloc< UndoStackObserverRecord, GC::MANUAL > > UndoObserverRecordList; - - /** - * Constructor. - */ - CompositeUndoStackObserver(); + /** + * Structure for tracking UndoStackObservers. + */ + struct UndoStackObserverRecord + { + public: + /** + * Constructor. + * + * \param o Reference to the UndoStackObserver that this UndoStackObserverRecord + * will track. + */ + UndoStackObserverRecord(UndoStackObserver &o) + : to_remove(false) + , _observer(o) + {} + bool to_remove; + + /** + * Overloaded equality test operator to facilitate usage of STL find algorithms. + */ + bool operator==(UndoStackObserverRecord const &_x) const { return &(this->_observer) == &(_x._observer); } + + /** + * Issue a redo event to the UndoStackObserver that is associated with this UndoStackObserverRecord. + * + * \param log The event log generated by the redo event. + */ + void issueRedo(Event *log) { this->_observer.notifyRedoEvent(log); } + + /** + * Issue an undo event to the UndoStackObserver that is associated with this + * UndoStackObserverRecord. + * + * \param log The event log generated by the undo event. + */ + void issueUndo(Event *log) { this->_observer.notifyUndoEvent(log); } + + /** + * Issues a committed event to the UndoStackObserver that is associated with this + * UndoStackObserverRecord. + * + * \param log The event log being committed to the undo stack. + */ + void issueUndoCommit(Event *log) { this->_observer.notifyUndoCommitEvent(log); } + + /** + * Issue a clear undo event to the UndoStackObserver + * that is associated with this + * UndoStackObserverRecord. + */ + void issueClearUndo() { this->_observer.notifyClearUndoEvent(); } + + /** + * Issue a clear redo event to the UndoStackObserver + * that is associated with this + * UndoStackObserverRecord. + */ + void issueClearRedo() { this->_observer.notifyClearRedoEvent(); } + + private: + UndoStackObserver &_observer; + }; + + /// A list of UndoStackObserverRecords, used to aggregate multiple UndoStackObservers. + typedef std::list> UndoObserverRecordList; + + /** + * Constructor. + */ + CompositeUndoStackObserver(); ~CompositeUndoStackObserver() override; - /** - * Add an UndoStackObserver. - * - * \param observer Reference to an UndoStackObserver to add. - */ - void add(UndoStackObserver& observer); - - /** - * Remove an UndoStackObserver. - * - * \param observer Reference to an UndoStackObserver to remove. - */ - void remove(UndoStackObserver& observer); - - /** - * Notify all registered UndoStackObservers of an undo event. - * - * \param log The event log generated by the undo event. - */ - void notifyUndoEvent(Event* log) override; - - /** - * Notify all registered UndoStackObservers of a redo event. - * - * \param log The event log generated by the redo event. - */ - void notifyRedoEvent(Event* log) override; - - /** - * Notify all registered UndoStackObservers of an event log being committed to the undo stack. - * - * \param log The event log being committed to the undo stack. - */ - void notifyUndoCommitEvent(Event* log) override; - - void notifyClearUndoEvent() override; - void notifyClearRedoEvent() override; + /** + * Add an UndoStackObserver. + * + * \param observer Reference to an UndoStackObserver to add. + */ + void add(UndoStackObserver &observer); + + /** + * Remove an UndoStackObserver. + * + * \param observer Reference to an UndoStackObserver to remove. + */ + void remove(UndoStackObserver &observer); + + /** + * Notify all registered UndoStackObservers of an undo event. + * + * \param log The event log generated by the undo event. + */ + void notifyUndoEvent(Event *log) override; + + /** + * Notify all registered UndoStackObservers of a redo event. + * + * \param log The event log generated by the redo event. + */ + void notifyRedoEvent(Event *log) override; + + /** + * Notify all registered UndoStackObservers of an event log being committed to the undo stack. + * + * \param log The event log being committed to the undo stack. + */ + void notifyUndoCommitEvent(Event *log) override; + + void notifyClearUndoEvent() override; + void notifyClearRedoEvent() override; private: - // Remove an observer from a given list - bool _remove_one(UndoObserverRecordList& list, UndoStackObserver& rec); + // Remove an observer from a given list + bool _remove_one(UndoObserverRecordList &list, UndoStackObserver &rec); - // Mark an observer for removal from a given list - bool _mark_one(UndoObserverRecordList& list, UndoStackObserver& rec); + // Mark an observer for removal from a given list + bool _mark_one(UndoObserverRecordList &list, UndoStackObserver &rec); - // Keep track of whether or not we are notifying observers - unsigned int _iterating; + // Keep track of whether or not we are notifying observers + unsigned int _iterating; - // Observers in the active list - UndoObserverRecordList _active; + // Observers in the active list + UndoObserverRecordList _active; - // Observers to be added - UndoObserverRecordList _pending; + // Observers to be added + UndoObserverRecordList _pending; - // Prevents the observer vector from modifications during - // iteration through the vector - void _lock() { this->_iterating++; } - void _unlock(); + // Prevents the observer vector from modifications during + // iteration through the vector + void _lock() { this->_iterating++; } + void _unlock(); }; -} +} // namespace Inkscape #endif // SEEN_COMPOSITE_UNDO_COMMIT_OBSERVER_H diff --git a/src/conditions.cpp b/src/conditions.cpp index e092ddc8fa12115b69ea198bb7834976b34befee..f217b842061e5458d04765e5d73dd62be4a4278f 100644 --- a/src/conditions.cpp +++ b/src/conditions.cpp @@ -11,21 +11,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include +#include "conditions.h" #include - -#include "conditions.h" -#include "rdf.h" +#include +#include #include "object/sp-item.h" - +#include "rdf.h" #include "xml/repr.h" -typedef bool (* condition_evaluator)(SPItem const *item, gchar const *value); +typedef bool (*condition_evaluator)(SPItem const *item, gchar const *value); -struct Condition { +struct Condition +{ gchar const *attribute; condition_evaluator evaluator; }; @@ -36,37 +35,39 @@ static bool evaluateRequiredExtensions(SPItem const *item, gchar const *value); /* define any conditional attributes and their handler functions in this array */ static Condition _condition_handlers[] = { - { "systemLanguage", evaluateSystemLanguage }, - { "requiredFeatures", evaluateRequiredFeatures }, - { "requiredExtensions", evaluateRequiredExtensions }, + {"systemLanguage", evaluateSystemLanguage}, + {"requiredFeatures", evaluateRequiredFeatures}, + {"requiredExtensions", evaluateRequiredExtensions}, }; // function which evaluates if item should be displayed -bool sp_item_evaluate(SPItem const *item) { +bool sp_item_evaluate(SPItem const *item) +{ bool needDisplay = true; - for ( unsigned int i = 0 ; needDisplay && (i < sizeof(_condition_handlers) / sizeof(_condition_handlers[0])) ; i++ ) { + for (unsigned int i = 0; needDisplay && (i < sizeof(_condition_handlers) / sizeof(_condition_handlers[0])); i++) { gchar const *value = item->getAttribute(_condition_handlers[i].attribute); - if ( value && !_condition_handlers[i].evaluator(item, value) ) { + if (value && !_condition_handlers[i].evaluator(item, value)) { needDisplay = false; } } return needDisplay; } -#define ISALNUM(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || ((c) >= '0' && (c) <= '9')) +#define ISALNUM(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || ((c) >= '0' && (c) <= '9')) // TODO: review and modernize this function -static gchar *preprocessLanguageCode(const gchar *language_code) { - if ( nullptr == language_code || strcmp(language_code, "") == 0) +static gchar *preprocessLanguageCode(const gchar *language_code) +{ + if (nullptr == language_code || strcmp(language_code, "") == 0) return nullptr; gchar *lngcode = g_strdup(language_code); - for ( unsigned int i = 0 ; i < strlen(lngcode) ; i++ ) { - if ( lngcode[i] >= 'A' && lngcode[i] <= 'Z' ) { + for (unsigned int i = 0; i < strlen(lngcode); i++) { + if (lngcode[i] >= 'A' && lngcode[i] <= 'Z') { lngcode[i] = g_ascii_tolower(lngcode[i]); - } else if ( '_' == lngcode[i] ) { + } else if ('_' == lngcode[i]) { lngcode[i] = '-'; - } else if ( !ISALNUM(lngcode[i]) && '-' != lngcode[i] ) { + } else if (!ISALNUM(lngcode[i]) && '-' != lngcode[i]) { // only alpha numeric characters and '-' may be contained in language code g_free(lngcode); return nullptr; @@ -76,24 +77,24 @@ static gchar *preprocessLanguageCode(const gchar *language_code) { return lngcode; } -static bool evaluateSystemLanguage(SPItem const *item, gchar const *value) { - if ( nullptr == value ) +static bool evaluateSystemLanguage(SPItem const *item, gchar const *value) +{ + if (nullptr == value) return true; std::set language_codes; gchar *str = nullptr; - gchar **strlist = g_strsplit( value, ",", 0); + gchar **strlist = g_strsplit(value, ",", 0); - for ( int i = 0 ; (str = strlist[i]) ; i++ ) { + for (int i = 0; (str = strlist[i]); i++) { str = g_strstrip(str); gchar *lngcode = preprocessLanguageCode(str); if (lngcode == nullptr) continue; language_codes.insert(lngcode); - gchar *pos = strchr (lngcode, '-'); - if (pos) - { + gchar *pos = strchr(lngcode, '-'); + if (pos) { // if subtag is used, primary tag is still a perfect match *pos = 0; if (strlen(lngcode) && language_codes.find(lngcode) == language_codes.end()) { @@ -123,14 +124,15 @@ static bool evaluateSystemLanguage(SPItem const *item, gchar const *value) { return false; } -static std::vector splitByWhitespace(gchar const *value) { +static std::vector splitByWhitespace(gchar const *value) +{ std::vector parts; gchar *str = nullptr; - gchar **strlist = g_strsplit( value, ",", 0); + gchar **strlist = g_strsplit(value, ",", 0); - for ( int i = 0 ; (str = strlist[i]) ; i++ ) { + for (int i = 0; (str = strlist[i]); i++) { gchar *part = g_strstrip(str); - if ( 0 == *part ) + if (0 == *part) continue; parts.emplace_back(part); } @@ -138,91 +140,73 @@ static std::vector splitByWhitespace(gchar const *value) { return parts; } -#define SVG11FEATURE "http://www.w3.org/TR/SVG11/feature#" -#define SVG10FEATURE "org.w3c." +#define SVG11FEATURE "http://www.w3.org/TR/SVG11/feature#" +#define SVG10FEATURE "org.w3c." -static bool evaluateSVG11Feature(gchar const *feature) { +static bool evaluateSVG11Feature(gchar const *feature) +{ static gchar const *_supported_features[] = { "SVG", // incomplete "SVG-static" - missing support for "Filter" - /* SVG - user agent supports at least one of the following: - "SVG-static", "SVG-animation", "SVG-dynamic" or "SVGDOM" */ + /* SVG - user agent supports at least one of the following: + "SVG-static", "SVG-animation", "SVG-dynamic" or "SVGDOM" */ // "SVGDOM", // not sure - /* SVGDOM - user agent supports at least one of the following: - "SVGDOM-static", "SVGDOM-animation" or "SVGDOM-dynamic" */ + /* SVGDOM - user agent supports at least one of the following: + "SVGDOM-static", "SVGDOM-animation" or "SVGDOM-dynamic" */ "SVG-static", // incomplete - missing support for "Filter" - /* SVG-static - user agent supports the following features: - "CoreAttribute", "Structure", "ContainerAttribute", - "ConditionalProcessing", "Image", "Style", "ViewportAttribute", - "Shape", "Text", "PaintAttribute", "OpacityAttribute", - "GraphicsAttribute", "Marker", "ColorProfile", - "Gradient", "Pattern", "Clip", "Mask", "Filter", - "XlinkAttribute", "Font", "Extensibility" */ + /* SVG-static - user agent supports the following features: + "CoreAttribute", "Structure", "ContainerAttribute", + "ConditionalProcessing", "Image", "Style", "ViewportAttribute", + "Shape", "Text", "PaintAttribute", "OpacityAttribute", + "GraphicsAttribute", "Marker", "ColorProfile", + "Gradient", "Pattern", "Clip", "Mask", "Filter", + "XlinkAttribute", "Font", "Extensibility" */ // "SVGDOM-static", // not sure - /* SVGDOM-static - All of the DOM interfaces and methods - that correspond to SVG-static */ + /* SVGDOM-static - All of the DOM interfaces and methods + that correspond to SVG-static */ // "SVG-animation", // no support - /* SVG-animation - All of the language features from "SVG-static" - plus the feature "feature#Animation" */ + /* SVG-animation - All of the language features from "SVG-static" + plus the feature "feature#Animation" */ // "SVGDOM-animation", // no support - /* SVGDOM-animation - All of the DOM interfaces and methods - that correspond to SVG-animation */ + /* SVGDOM-animation - All of the DOM interfaces and methods + that correspond to SVG-animation */ // "SVG-dynamic", // no support - /* SVG-dynamic - user agent supports all "SVG-animation" and the following features: - "Hyperlinking", "Scripting", "View", "Cursor", - "GraphicalEventsAttribute", "DocumentEventsAttribute", "AnimationEventsAttribute" */ + /* SVG-dynamic - user agent supports all "SVG-animation" and the following features: + "Hyperlinking", "Scripting", "View", "Cursor", + "GraphicalEventsAttribute", "DocumentEventsAttribute", "AnimationEventsAttribute" */ // "SVGDOM-dynamic", // no support - /* SVGDOM-dynamic - All of the DOM interfaces and methods - that correspond to SVG-dynamic */ - "CoreAttribute", - "Structure", - "BasicStructure", - "ContainerAttribute", - "ConditionalProcessing", - "Image", - "Style", + /* SVGDOM-dynamic - All of the DOM interfaces and methods + that correspond to SVG-dynamic */ + "CoreAttribute", "Structure", "BasicStructure", "ContainerAttribute", "ConditionalProcessing", "Image", "Style", "ViewportAttribute", // not sure - "Shape", - "Text", - "BasicText", - "PaintAttribute", - "BasicPaintAttribute", - "OpacityAttribute", - "GraphicsAttribute", - "BasicGraphicsAttribute", - "Marker", - "ColorProfile", - "Gradient", - "Pattern", - "Clip", - "BasicClip", - "Mask", + "Shape", "Text", "BasicText", "PaintAttribute", "BasicPaintAttribute", "OpacityAttribute", "GraphicsAttribute", + "BasicGraphicsAttribute", "Marker", "ColorProfile", "Gradient", "Pattern", "Clip", "BasicClip", "Mask", // "Filter", // "BasicFilter", // "DocumentEventsAttribute", // "GraphicalEventsAttribute", // "AnimationEventsAttribute", // "Cursor", // not sure - "Hyperlinking", // not sure - "XlinkAttribute", // not sure + "Hyperlinking", // not sure + "XlinkAttribute", // not sure "ExternalResourcesRequired", // not sure "View", // "Script", // "Animation", - "Font", - "BasicFont", + "Font", "BasicFont", "Extensibility", // not sure }; - - for (auto & _supported_feature : _supported_features) { - if ( 0 == strcasecmp(feature, _supported_feature) ) + + for (auto &_supported_feature : _supported_features) { + if (0 == strcasecmp(feature, _supported_feature)) return true; } return false; } -static bool evaluateSVG10Feature(gchar const *feature) { +static bool evaluateSVG10Feature(gchar const *feature) +{ static gchar const *_supported_features[] = { - "svg.static", // incomplete - no filter effects + "svg.static", // incomplete - no filter effects "dom.svg.static", // not sure // "svg.animation", // "dom.svg.animation", @@ -231,47 +215,49 @@ static bool evaluateSVG10Feature(gchar const *feature) { // "svg.all", // "dom.svg.all" }; - for (auto & _supported_feature : _supported_features) { - if ( 0 == strcasecmp(feature, _supported_feature) ) + for (auto &_supported_feature : _supported_features) { + if (0 == strcasecmp(feature, _supported_feature)) return true; } return false; } -static bool evaluateSingleFeature(gchar const *value) { - if ( nullptr == value ) +static bool evaluateSingleFeature(gchar const *value) +{ + if (nullptr == value) return false; gchar const *found; found = strstr(value, SVG11FEATURE); - if ( value == found ) + if (value == found) return evaluateSVG11Feature(found + strlen(SVG11FEATURE)); found = strstr(value, SVG10FEATURE); - if ( value == found ) + if (value == found) return evaluateSVG10Feature(found + strlen(SVG10FEATURE)); return false; } -static bool evaluateRequiredFeatures(SPItem const */*item*/, gchar const *value) { - if ( nullptr == value ) +static bool evaluateRequiredFeatures(SPItem const * /*item*/, gchar const *value) +{ + if (nullptr == value) return true; std::vector parts = splitByWhitespace(value); - if (parts.empty()) - { + if (parts.empty()) { return false; } - - for (auto & part : parts) { + + for (auto &part : parts) { if (!evaluateSingleFeature(part.c_str())) { return false; } } - + return true; } -static bool evaluateRequiredExtensions(SPItem const */*item*/, gchar const *value) { - if ( nullptr == value ) +static bool evaluateRequiredExtensions(SPItem const * /*item*/, gchar const *value) +{ + if (nullptr == value) return true; return false; } @@ -444,7 +430,6 @@ zh Chinese zu Zulu */ - /* Local Variables: mode:c++ diff --git a/src/conn-avoid-ref.cpp b/src/conn-avoid-ref.cpp index ec64cfa8fbbe44ce9a4a6fb7cbefaf9ce3838009..36b0fc46de15104bb45a8db8f76c9760f7619fe7 100644 --- a/src/conn-avoid-ref.cpp +++ b/src/conn-avoid-ref.cpp @@ -11,31 +11,25 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "conn-avoid-ref.h" #include -#include #include +#include #include "2geom/convex-hull.h" #include "2geom/line.h" - -#include "conn-avoid-ref.h" +#include "3rdparty/adaptagrams/libavoid/router.h" +#include "3rdparty/adaptagrams/libavoid/shape.h" #include "desktop.h" +#include "display/curve.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" -#include "verbs.h" - -#include "display/curve.h" - -#include "3rdparty/adaptagrams/libavoid/router.h" -#include "3rdparty/adaptagrams/libavoid/shape.h" - #include "object/sp-namedview.h" #include "object/sp-shape.h" - #include "svg/stringstream.h" - +#include "verbs.h" #include "xml/node.h" using Inkscape::DocumentUndo; @@ -44,16 +38,13 @@ using Avoid::Router; static Avoid::Polygon avoid_item_poly(SPItem const *item); - SPAvoidRef::SPAvoidRef(SPItem *spitem) : shapeRef(nullptr) , item(spitem) , setting(false) , new_setting(false) , _transformed_connection() -{ -} - +{} SPAvoidRef::~SPAvoidRef() { @@ -69,11 +60,10 @@ SPAvoidRef::~SPAvoidRef() shapeRef = nullptr; } - void SPAvoidRef::setAvoid(char const *value) { // Don't keep avoidance information for cloned objects. - if ( !item->cloned ) { + if (!item->cloned) { new_setting = false; if (value && (strcmp(value, "true") == 0)) { new_setting = true; @@ -109,8 +99,7 @@ void SPAvoidRef::handleSettingChange() if (new_setting) { Avoid::Polygon poly = avoid_item_poly(item); if (poly.size() > 0) { - _transformed_connection = item->connectTransformed( - sigc::ptr_fun(&avoid_item_move)); + _transformed_connection = item->connectTransformed(sigc::ptr_fun(&avoid_item_move)); char const *id = item->getAttribute("id"); g_assert(id != nullptr); @@ -120,15 +109,12 @@ void SPAvoidRef::handleSettingChange() shapeRef = new Avoid::ShapeRef(router, poly, itemID); } - } - else if (shapeRef) - { + } else if (shapeRef) { router->deleteShape(shapeRef); shapeRef = nullptr; } } - std::vector SPAvoidRef::getAttachedShapes(const unsigned int type) { std::vector list; @@ -143,7 +129,8 @@ std::vector SPAvoidRef::getAttachedShapes(const unsigned int type) SPObject *obj = item->document->getObjectById(connId); if (obj == nullptr) { g_warning("getAttachedShapes: Object with id=\"%s\" is not " - "found. Skipping.", connId); + "found. Skipping.", + connId); continue; } SPItem *shapeItem = SP_ITEM(obj); @@ -152,7 +139,6 @@ std::vector SPAvoidRef::getAttachedShapes(const unsigned int type) return list; } - std::vector SPAvoidRef::getAttachedConnectors(const unsigned int type) { std::vector list; @@ -167,7 +153,8 @@ std::vector SPAvoidRef::getAttachedConnectors(const unsigned int type) SPObject *obj = item->document->getObjectById(connId); if (obj == nullptr) { g_warning("getAttachedConnectors: Object with id=\"%s\" is not " - "found. Skipping.", connId); + "found. Skipping.", + connId); continue; } SPItem *connItem = SP_ITEM(obj); @@ -189,9 +176,9 @@ static std::vector approxCurveWithPoints(SPCurve *curve) { // The number of segments to use for not straight curves approximation const unsigned NUM_SEGS = 4; - - const Geom::PathVector& curve_pv = curve->get_pathvector(); - + + const Geom::PathVector &curve_pv = curve->get_pathvector(); + // The structure to hold the output std::vector poly_points; @@ -201,29 +188,22 @@ static std::vector approxCurveWithPoints(SPCurve *curve) double at; at = 0; Geom::PathVector::const_iterator pit = curve_pv.begin(); - while (pit != curve_pv.end()) - { + while (pit != curve_pv.end()) { Geom::Path::const_iterator cit = pit->begin(); - while (cit != pit->end()) - { - if (cit == pit->begin()) - { + while (cit != pit->end()) { + if (cit == pit->begin()) { poly_points.push_back(cit->initialPoint()); } - if (dynamic_cast(&*cit)) - { + if (dynamic_cast(&*cit)) { at += seg_size; - if (at <= 1.0 ) + if (at <= 1.0) poly_points.push_back(cit->pointAt(at)); - else - { + else { at = 0.0; ++cit; } - } - else - { + } else { poly_points.push_back(cit->finalPoint()); ++cit; } @@ -233,30 +213,27 @@ static std::vector approxCurveWithPoints(SPCurve *curve) return poly_points; } -static std::vector approxItemWithPoints(SPItem const *item, const Geom::Affine& item_transform) +static std::vector approxItemWithPoints(SPItem const *item, const Geom::Affine &item_transform) { // The structure to hold the output std::vector poly_points; std::unique_ptr item_curve; - if (SP_IS_GROUP(item)) - { - SPGroup* group = SP_GROUP(item); + if (SP_IS_GROUP(item)) { + SPGroup *group = SP_GROUP(item); // consider all first-order children - std::vector itemlist = sp_item_group_item_list(group); + std::vector itemlist = sp_item_group_item_list(group); for (auto child_item : itemlist) { - std::vector child_points = approxItemWithPoints(child_item, item_transform * child_item->transform); + std::vector child_points = + approxItemWithPoints(child_item, item_transform * child_item->transform); poly_points.insert(poly_points.end(), child_points.begin(), child_points.end()); } - } - else if (SP_IS_SHAPE(item)) - { + } else if (SP_IS_SHAPE(item)) { auto shape = static_cast(item); SP_SHAPE(item)->set_shape(); item_curve = SPCurve::copy(shape->curve()); // make sure it has an associated curve - if (item_curve) - { + if (item_curve) { // apply transformations (up to common ancestor) item_curve->transform(item_transform); } @@ -296,36 +273,32 @@ static Avoid::Polygon avoid_item_poly(SPItem const *item) Geom::Line hull_edge(hull.back(), hull.front()); Geom::Line prev_parallel_hull_edge; - prev_parallel_hull_edge.setOrigin(hull_edge.origin()+hull_edge.versor().ccw()*spacing); + prev_parallel_hull_edge.setOrigin(hull_edge.origin() + hull_edge.versor().ccw() * spacing); prev_parallel_hull_edge.setVector(hull_edge.versor()); int hull_size = hull.size(); - for (int i = 0; i < hull_size; ++i) - { + for (int i = 0; i < hull_size; ++i) { if (i + 1 == hull_size) { hull_edge.setPoints(hull.back(), hull.front()); } else { hull_edge.setPoints(hull[i], hull[i + 1]); } Geom::Line parallel_hull_edge; - parallel_hull_edge.setOrigin(hull_edge.origin()+hull_edge.versor().ccw()*spacing); + parallel_hull_edge.setOrigin(hull_edge.origin() + hull_edge.versor().ccw() * spacing); parallel_hull_edge.setVector(hull_edge.versor()); // determine the intersection point try { Geom::OptCrossing int_pt = Geom::intersection(parallel_hull_edge, prev_parallel_hull_edge); - if (int_pt) - { - Avoid::Point avoid_pt((parallel_hull_edge.origin()+parallel_hull_edge.versor()*int_pt->ta)[Geom::X], - (parallel_hull_edge.origin()+parallel_hull_edge.versor()*int_pt->ta)[Geom::Y]); + if (int_pt) { + Avoid::Point avoid_pt( + (parallel_hull_edge.origin() + parallel_hull_edge.versor() * int_pt->ta)[Geom::X], + (parallel_hull_edge.origin() + parallel_hull_edge.versor() * int_pt->ta)[Geom::Y]); poly.ps.push_back(avoid_pt); - } - else - { + } else { // something went wrong... - std::cout<<"conn-avoid-ref.cpp: avoid_item_poly: Geom:intersection failed."< get_avoided_items(std::vector &list, SPObject *from, SPDesktop *desktop, - bool initialised) + bool initialised) { - for (auto& child: from->children) { - if (SP_IS_ITEM(&child) && - !desktop->isLayer(SP_ITEM(&child)) && - !SP_ITEM(&child)->isLocked() && - !desktop->itemIsHidden(SP_ITEM(&child)) && - (!initialised || SP_ITEM(&child)->getAvoidRef().shapeRef) - ) - { + for (auto &child : from->children) { + if (SP_IS_ITEM(&child) && !desktop->isLayer(SP_ITEM(&child)) && !SP_ITEM(&child)->isLocked() && + !desktop->itemIsHidden(SP_ITEM(&child)) && (!initialised || SP_ITEM(&child)->getAvoidRef().shapeRef)) { list.push_back(SP_ITEM(&child)); } @@ -358,8 +325,7 @@ std::vector get_avoided_items(std::vector &list, SPObject *f return list; } - -void avoid_item_move(Geom::Affine const */*mp*/, SPItem *moved_item) +void avoid_item_move(Geom::Affine const * /*mp*/, SPItem *moved_item) { Avoid::ShapeRef *shapeRef = moved_item->getAvoidRef().shapeRef; g_assert(shapeRef); @@ -371,7 +337,6 @@ void avoid_item_move(Geom::Affine const */*mp*/, SPItem *moved_item) } } - void init_avoided_shape_geometry(SPDesktop *desktop) { // Don't count this as changes to the document, @@ -381,15 +346,13 @@ void init_avoided_shape_geometry(SPDesktop *desktop) bool initialised = false; std::vector tmp; - std::vector items = get_avoided_items(tmp, desktop->currentRoot(), desktop, - initialised); + std::vector items = get_avoided_items(tmp, desktop->currentRoot(), desktop, initialised); for (auto item : items) { item->getAvoidRef().handleSettingChange(); } } - /* Local Variables: mode:c++ diff --git a/src/conn-avoid-ref.h b/src/conn-avoid-ref.h index 75f3d9765499a0fb1e1bee492e2c14e73d16eef9..40444d78beda9ab864e4a882da2953787b857819 100644 --- a/src/conn-avoid-ref.h +++ b/src/conn-avoid-ref.h @@ -18,12 +18,15 @@ #include #include -class SPDesktop; +class SPDesktop; class SPObject; -class SPItem; -namespace Avoid { class ShapeRef; } +class SPItem; +namespace Avoid { +class ShapeRef; +} -class SPAvoidRef { +class SPAvoidRef +{ public: SPAvoidRef(SPItem *spitem); virtual ~SPAvoidRef(); @@ -55,8 +58,8 @@ private: sigc::connection _transformed_connection; }; -extern std::vector get_avoided_items(std::vector &list, SPObject *from, - SPDesktop *desktop, bool initialised = true); +extern std::vector get_avoided_items(std::vector &list, SPObject *from, SPDesktop *desktop, + bool initialised = true); extern void avoid_item_move(Geom::Affine const *mp, SPItem *moved_item); extern void init_avoided_shape_geometry(SPDesktop *desktop); diff --git a/src/console-output-undo-observer.cpp b/src/console-output-undo-observer.cpp index 16f99c962badd9dd99a0b2cf6909d3740213ac14..b35236b4a796a93720f6ffda36eaa4e8b4f8e0c0 100644 --- a/src/console-output-undo-observer.cpp +++ b/src/console-output-undo-observer.cpp @@ -16,37 +16,32 @@ namespace Inkscape { -void -ConsoleOutputUndoObserver::notifyUndoEvent(Event* /*log*/) +void ConsoleOutputUndoObserver::notifyUndoEvent(Event * /*log*/) { // g_message("notifyUndoEvent(SPDocumentUndo::undo) called; log=%p\n", log->event); } -void -ConsoleOutputUndoObserver::notifyRedoEvent(Event* /*log*/) +void ConsoleOutputUndoObserver::notifyRedoEvent(Event * /*log*/) { // g_message("notifyRedoEvent(SPDocumentUndo::redo) called; log=%p\n", log->event); } -void -ConsoleOutputUndoObserver::notifyUndoCommitEvent(Event* /*log*/) +void ConsoleOutputUndoObserver::notifyUndoCommitEvent(Event * /*log*/) { - //g_message("notifyUndoCommitEvent(SPDocumentUndo::maybe_done) called; log=%p\n", log->event); + // g_message("notifyUndoCommitEvent(SPDocumentUndo::maybe_done) called; log=%p\n", log->event); } -void -ConsoleOutputUndoObserver::notifyClearUndoEvent() +void ConsoleOutputUndoObserver::notifyClearUndoEvent() { - //g_message("notifyClearUndoEvent(sp_document_clear_undo) called); + // g_message("notifyClearUndoEvent(sp_document_clear_undo) called); } -void -ConsoleOutputUndoObserver::notifyClearRedoEvent() +void ConsoleOutputUndoObserver::notifyClearRedoEvent() { - //g_message("notifyClearRedoEvent(sp_document_clear_redo) called); + // g_message("notifyClearRedoEvent(sp_document_clear_redo) called); } -} +} // namespace Inkscape /* Local Variables: diff --git a/src/console-output-undo-observer.h b/src/console-output-undo-observer.h index b48a6671201e60899740f4ab8c15fd43f9ed600d..0ea3295a1fd8a6c1546d8b0552e1b09fb80242af 100644 --- a/src/console-output-undo-observer.h +++ b/src/console-output-undo-observer.h @@ -21,19 +21,21 @@ namespace Inkscape { * SPDocumentUndo::undo, SPDocumentUndo::redo, SPDocumentUndo::maybe_done. * */ -class ConsoleOutputUndoObserver : public UndoStackObserver { +class ConsoleOutputUndoObserver : public UndoStackObserver +{ public: - ConsoleOutputUndoObserver() : UndoStackObserver() { } + ConsoleOutputUndoObserver() + : UndoStackObserver() + {} ~ConsoleOutputUndoObserver() override = default; - void notifyUndoEvent(Event* log) override; - void notifyRedoEvent(Event* log) override; - void notifyUndoCommitEvent(Event* log) override; + void notifyUndoEvent(Event *log) override; + void notifyRedoEvent(Event *log) override; + void notifyUndoCommitEvent(Event *log) override; void notifyClearUndoEvent() override; void notifyClearRedoEvent() override; - }; -} +} // namespace Inkscape #endif // SEEN_INKSCAPE_CONSOLE_OUTPUT_UNDO_OBSERVER_H diff --git a/src/context-fns.cpp b/src/context-fns.cpp index b6b0c9c7bffdba5b020e121323ac9aec30037bb6..78052b0b3472d3f1d7b46acea9b0c6e95f15300f 100644 --- a/src/context-fns.cpp +++ b/src/context-fns.cpp @@ -7,19 +7,16 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include - #include "context-fns.h" +#include + #include "desktop.h" +#include "display/snap-indicator.h" #include "message-context.h" #include "message-stack.h" -#include "snap.h" - -#include "display/snap-indicator.h" - #include "object/sp-namedview.h" - +#include "snap.h" #include "ui/tools/tool-base.h" static const double midpt_1_goldenratio = (1 + goldenratio) / 2; @@ -40,22 +37,21 @@ bool Inkscape::have_viable_layer(SPDesktop *desktop, MessageContext *message) { SPItem const *layer = SP_ITEM(desktop->currentLayer()); - if ( !layer || desktop->itemIsHidden(layer) ) { - message->flash(Inkscape::ERROR_MESSAGE, - _("Current layer is hidden. Unhide it to be able to draw on it.")); - return false; + if (!layer || desktop->itemIsHidden(layer)) { + message->flash(Inkscape::ERROR_MESSAGE, + _("Current layer is hidden. Unhide it to be able to draw on it.")); + return false; } - if ( !layer || layer->isLocked() ) { - message->flash(Inkscape::ERROR_MESSAGE, - _("Current layer is locked. Unlock it to be able to draw on it.")); - return false; + if (!layer || layer->isLocked()) { + message->flash(Inkscape::ERROR_MESSAGE, + _("Current layer is locked. Unlock it to be able to draw on it.")); + return false; } return true; } - /** * Check to see if the current layer is both unhidden and unlocked. If not, * set a message about it on the given context. @@ -69,24 +65,23 @@ bool Inkscape::have_viable_layer(SPDesktop *desktop, MessageStack *message) { SPItem const *layer = SP_ITEM(desktop->currentLayer()); - if ( !layer || desktop->itemIsHidden(layer) ) { - message->flash(Inkscape::WARNING_MESSAGE, - _("Current layer is hidden. Unhide it to be able to draw on it.")); - return false; + if (!layer || desktop->itemIsHidden(layer)) { + message->flash(Inkscape::WARNING_MESSAGE, + _("Current layer is hidden. Unhide it to be able to draw on it.")); + return false; } - if ( !layer || layer->isLocked() ) { - message->flash(Inkscape::WARNING_MESSAGE, - _("Current layer is locked. Unlock it to be able to draw on it.")); - return false; + if (!layer || layer->isLocked()) { + message->flash(Inkscape::WARNING_MESSAGE, + _("Current layer is locked. Unlock it to be able to draw on it.")); + return false; } return true; } - -Geom::Rect Inkscape::snap_rectangular_box(SPDesktop const *desktop, SPItem *item, - Geom::Point const &pt, Geom::Point const ¢er, int state) +Geom::Rect Inkscape::snap_rectangular_box(SPDesktop const *desktop, SPItem *item, Geom::Point const &pt, + Geom::Point const ¢er, int state) { Geom::Point p[2]; @@ -98,7 +93,6 @@ Geom::Rect Inkscape::snap_rectangular_box(SPDesktop const *desktop, SPItem *item Inkscape::SnappedPoint snappoint; if (control) { - /* Control is down: we are constrained to producing integer-ratio rectangles */ /* Vector from the centre of the box to the point we are dragging to */ @@ -107,7 +101,7 @@ Geom::Rect Inkscape::snap_rectangular_box(SPDesktop const *desktop, SPItem *item /* Round it so that we have an integer-ratio (or golden ratio) box */ if (fabs(delta[Geom::X]) > fabs(delta[Geom::Y]) && (delta[Geom::Y] != 0.0)) { double ratio = delta[Geom::X] / delta[Geom::Y]; - double ratioabs = fabs (ratio); + double ratioabs = fabs(ratio); double sign = (ratio < 0 ? -1 : 1); if (midpt_1_goldenratio < ratioabs && ratioabs < midpt_goldenratio_2) { delta[Geom::X] = sign * goldenratio * delta[Geom::Y]; @@ -116,7 +110,7 @@ Geom::Rect Inkscape::snap_rectangular_box(SPDesktop const *desktop, SPItem *item } } else if (delta[Geom::X] != 0.0) { double ratio = delta[Geom::Y] / delta[Geom::X]; - double ratioabs = fabs (ratio); + double ratioabs = fabs(ratio); double sign = (ratio < 0 ? -1 : 1); if (midpt_1_goldenratio < ratioabs && ratioabs < midpt_goldenratio_2) { delta[Geom::Y] = sign * goldenratio * delta[Geom::X]; @@ -129,7 +123,6 @@ Geom::Rect Inkscape::snap_rectangular_box(SPDesktop const *desktop, SPItem *item p[1] = center + delta; if (shift) { - /* Shift is down, so our origin is the centre point rather than the corner ** point; this means that corner-point movements are bound to each other. */ @@ -162,7 +155,6 @@ Geom::Rect Inkscape::snap_rectangular_box(SPDesktop const *desktop, SPItem *item } } } else { - /* Our origin is the opposite corner. Snap the drag point along the constraint vector */ p[0] = center; snappoint = m.constrainedSnap(Inkscape::SnapCandidatePoint(p[1], Inkscape::SNAPSOURCE_NODE_HANDLE), @@ -173,7 +165,6 @@ Geom::Rect Inkscape::snap_rectangular_box(SPDesktop const *desktop, SPItem *item } } else if (shift) { - /* Shift is down, so our origin is the centre point rather than the corner point; ** this means that corner-point movements are bound to each other. */ @@ -201,7 +192,6 @@ Geom::Rect Inkscape::snap_rectangular_box(SPDesktop const *desktop, SPItem *item } } else { - /* There's no constraint on the corner point, so just snap it to anything */ p[0] = center; p[1] = pt; @@ -221,23 +211,21 @@ Geom::Rect Inkscape::snap_rectangular_box(SPDesktop const *desktop, SPItem *item m.unSetup(); return Geom::Rect(Geom::Point(MIN(p[0][Geom::X], p[1][Geom::X]), MIN(p[0][Geom::Y], p[1][Geom::Y])), - Geom::Point(MAX(p[0][Geom::X], p[1][Geom::X]), MAX(p[0][Geom::Y], p[1][Geom::Y]))); + Geom::Point(MAX(p[0][Geom::X], p[1][Geom::X]), MAX(p[0][Geom::Y], p[1][Geom::Y]))); } - - -Geom::Point Inkscape::setup_for_drag_start(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase* ec, GdkEvent *ev) +Geom::Point Inkscape::setup_for_drag_start(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec, GdkEvent *ev) { ec->xp = static_cast(ev->button.x); ec->yp = static_cast(ev->button.y); ec->within_tolerance = true; Geom::Point const p(ev->button.x, ev->button.y); - ec->item_to_select = Inkscape::UI::Tools::sp_event_context_find_item(desktop, p, ev->button.state & GDK_MOD1_MASK, TRUE); + ec->item_to_select = + Inkscape::UI::Tools::sp_event_context_find_item(desktop, p, ev->button.state & GDK_MOD1_MASK, TRUE); return ec->getDesktop()->w2d(p); } - /* Local Variables: mode:c++ diff --git a/src/context-fns.h b/src/context-fns.h index 21ef313e3365e93ac7092609b1b89fc19743c197..1e63b2d3c96e1ce874ce8d094f48c08190671ef0 100644 --- a/src/context-fns.h +++ b/src/context-fns.h @@ -26,18 +26,18 @@ namespace Tools { class ToolBase; } -} +} // namespace UI class MessageContext; class MessageStack; extern bool have_viable_layer(SPDesktop *desktop, MessageContext *message); extern bool have_viable_layer(SPDesktop *desktop, MessageStack *message); -Geom::Rect snap_rectangular_box(SPDesktop const *desktop, SPItem *item, - Geom::Point const &pt, Geom::Point const ¢er, int state); -Geom::Point setup_for_drag_start(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase* ec, GdkEvent *ev); +Geom::Rect snap_rectangular_box(SPDesktop const *desktop, SPItem *item, Geom::Point const &pt, + Geom::Point const ¢er, int state); +Geom::Point setup_for_drag_start(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec, GdkEvent *ev); -} +} // namespace Inkscape #endif // !SEEN_CONTEXT_FNS_H diff --git a/src/debug/demangle.cpp b/src/debug/demangle.cpp index abf046b102a87d9520eb443b83617a08041f3852..00284c26183b18d175505f284ada91799ddb454f 100644 --- a/src/debug/demangle.cpp +++ b/src/debug/demangle.cpp @@ -10,12 +10,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "debug/demangle.h" + #include #include #include #include #include -#include "debug/demangle.h" namespace Inkscape { @@ -23,20 +24,20 @@ namespace Debug { namespace { -struct string_less_than { - bool operator()(char const *a, char const *b) const { - return ( strcmp(a, b) < 0 ); - } +struct string_less_than +{ + bool operator()(char const *a, char const *b) const { return (strcmp(a, b) < 0); } }; typedef std::map, string_less_than> MangleCache; MangleCache mangle_cache; -} +} // namespace -std::shared_ptr demangle(char const *name) { - MangleCache::iterator found=mangle_cache.find(name); - if ( found != mangle_cache.end() ) { +std::shared_ptr demangle(char const *name) +{ + MangleCache::iterator found = mangle_cache.find(name); + if (found != mangle_cache.end()) { return (*found).second; } @@ -44,9 +45,9 @@ std::shared_ptr demangle(char const *name) { return mangle_cache[name] = std::make_shared(result); } -} +} // namespace Debug -} +} // namespace Inkscape /* Local Variables: diff --git a/src/debug/demangle.h b/src/debug/demangle.h index ba747cd3abcbe914be49d97898249eb473cf32b6..08268964b4c66988e4687ef973e87df1058cb70d 100644 --- a/src/debug/demangle.h +++ b/src/debug/demangle.h @@ -24,7 +24,7 @@ std::shared_ptr demangle(char const *name); } -} +} // namespace Inkscape #endif /* diff --git a/src/debug/event-tracker.h b/src/debug/event-tracker.h index a728bac467fb94b870f484c83f757707d6ba6ad3..4751061704399052a046efe9b0621a6789cf4b63 100644 --- a/src/debug/event-tracker.h +++ b/src/debug/event-tracker.h @@ -21,27 +21,39 @@ namespace Debug { #ifdef NDEBUG // Make event tracking a no-op for non-debug builds -template struct EventTracker { - template EventTracker(Args &&...) {} - template void set(Args &&...) {} +template +struct EventTracker +{ + template + EventTracker(Args &&...) + {} + template + void set(Args &&...) + {} void clear() {} }; #else -struct NoInitialEvent {}; +struct NoInitialEvent +{ +}; -template class EventTracker; +template +class EventTracker; -class EventTrackerBase { +class EventTrackerBase +{ public: - virtual ~EventTrackerBase() { + virtual ~EventTrackerBase() + { if (_active) { Logger::finish(); } } template - inline void set() { + inline void set() + { if (_active) { Logger::finish(); } @@ -50,7 +62,8 @@ public: } template - inline void set(A const &a) { + inline void set(A const &a) + { if (_active) { Logger::finish(); } @@ -59,7 +72,8 @@ public: } template - inline void set(A const &a, B const &b) { + inline void set(A const &a, B const &b) + { if (_active) { Logger::finish(); } @@ -68,7 +82,8 @@ public: } template - inline void set(A const &a, B const &b, C const &c) { + inline void set(A const &a, B const &b, C const &c) + { if (_active) { Logger::finish(); } @@ -76,9 +91,9 @@ public: _active = true; } - template - inline void set(A const &a, B const &b, C const &c, D const &d) { + template + inline void set(A const &a, B const &b, C const &c, D const &d) + { if (_active) { Logger::finish(); } @@ -86,8 +101,7 @@ public: _active = true; } - template + template inline void set(A const &a, B const &b, C const &c, D const &d, E const &e) { if (_active) { @@ -97,10 +111,8 @@ public: _active = true; } - template - inline void set(A const &a, B const &b, C const &c, - D const &d, E const &e, F const &f) + template + inline void set(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f) { if (_active) { Logger::finish(); @@ -109,11 +121,8 @@ public: _active = true; } - template - inline void set(A const &a, B const &b, C const &c, D const &d, - E const &e, F const &f, G const &g) + template + inline void set(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f, G const &g) { if (_active) { Logger::finish(); @@ -122,11 +131,9 @@ public: _active = true; } - template - inline void set(A const &a, B const &b, C const &c, D const &d, - E const &e, F const &f, G const &g, H const &h) + template + inline void set(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f, G const &g, H const &h) { if (_active) { Logger::finish(); @@ -135,7 +142,8 @@ public: _active = true; } - void clear() { + void clear() + { if (_active) { Logger::finish(); _active = false; @@ -143,85 +151,97 @@ public: } protected: - EventTrackerBase(bool active) : _active(active) {} + EventTrackerBase(bool active) + : _active(active) + {} private: EventTrackerBase(EventTrackerBase const &) = delete; // no copy - void operator=(EventTrackerBase const &) = delete; // no assign + void operator=(EventTrackerBase const &) = delete; // no assign bool _active; }; -template class EventTracker : public EventTrackerBase { +template +class EventTracker : public EventTrackerBase +{ public: - EventTracker() : EventTrackerBase(true) { Logger::start(); } + EventTracker() + : EventTrackerBase(true) + { + Logger::start(); + } template - EventTracker(A const &a) : EventTrackerBase(true) { + EventTracker(A const &a) + : EventTrackerBase(true) + { Logger::start(a); } template - EventTracker(A const &a, B const &b) : EventTrackerBase(true) { + EventTracker(A const &a, B const &b) + : EventTrackerBase(true) + { Logger::start(a, b); } template - EventTracker(A const &a, B const &b, C const &c) : EventTrackerBase(true) { + EventTracker(A const &a, B const &b, C const &c) + : EventTrackerBase(true) + { Logger::start(a, b, c); } template EventTracker(A const &a, B const &b, C const &c, D const &d) - : EventTrackerBase(true) + : EventTrackerBase(true) { Logger::start(a, b, c, d); } template EventTracker(A const &a, B const &b, C const &c, D const &d, E const &e) - : EventTrackerBase(true) + : EventTrackerBase(true) { Logger::start(a, b, c, d, e); } - template - EventTracker(A const &a, B const &b, C const &c, D const &d, - E const &e, F const &f) - : EventTrackerBase(true) + template + EventTracker(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f) + : EventTrackerBase(true) { Logger::start(a, b, c, d, e, f); } - template - EventTracker(A const &a, B const &b, C const &c, D const &d, - E const &e, F const &f, G const &g) - : EventTrackerBase(true) + template + EventTracker(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f, G const &g) + : EventTrackerBase(true) { Logger::start(a, b, c, d, e, f, g); } - template - EventTracker(A const &a, B const &b, C const &c, D const &d, - E const &e, F const &f, G const &g, H const &h) - : EventTrackerBase(true) + template + EventTracker(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f, G const &g, H const &h) + : EventTrackerBase(true) { Logger::start(a, b, c, d, e, f, g, h); } }; -template <> class EventTracker : public EventTrackerBase { +template <> +class EventTracker : public EventTrackerBase +{ public: - EventTracker() : EventTrackerBase(false) {} + EventTracker() + : EventTrackerBase(false) + {} }; #endif -} +} // namespace Debug -} +} // namespace Inkscape #endif /* diff --git a/src/debug/event.h b/src/debug/event.h index 3bc6089f09b885500912e95eb231a12aaf021623..c2c312391ea71fd84832042ce3b4c2fa64f3aa5a 100644 --- a/src/debug/event.h +++ b/src/debug/event.h @@ -21,12 +21,14 @@ namespace Inkscape { namespace Debug { -class Event { +class Event +{ public: virtual ~Event() = default; - enum Category { - CORE=0, + enum Category + { + CORE = 0, XML, SPOBJECT, DOCUMENT, @@ -37,16 +39,23 @@ public: CONFIGURATION, OTHER }; - enum { N_CATEGORIES=OTHER+1 }; + enum + { + N_CATEGORIES = OTHER + 1 + }; - struct PropertyPair { + struct PropertyPair + { public: PropertyPair() = default; - PropertyPair(char const *n, std::shared_ptr&& v) - : name(n), value(std::move(v)) {} + PropertyPair(char const *n, std::shared_ptr &&v) + : name(n) + , value(std::move(v)) + {} PropertyPair(char const *n, char const *v) - : name(n), - value(std::make_shared(v)) {} + : name(n) + , value(std::make_shared(v)) + {} char const *name; std::shared_ptr value; @@ -57,16 +66,16 @@ public: // To reduce allocations, we assume the name here is always allocated statically and will never // need to be deallocated. It would be nice to be able to assert that during the creation of // the Event though. - virtual char const *name() const=0; - virtual unsigned propertyCount() const=0; - virtual PropertyPair property(unsigned property) const=0; + virtual char const *name() const = 0; + virtual unsigned propertyCount() const = 0; + virtual PropertyPair property(unsigned property) const = 0; - virtual void generateChildEvents() const=0; + virtual void generateChildEvents() const = 0; }; -} +} // namespace Debug -} +} // namespace Inkscape #endif /* diff --git a/src/debug/gc-heap.h b/src/debug/gc-heap.h index e0fd8f159f46bff65ffe79c947da24631bcace1c..fc90c7f17da110036999a69d2dcd7fbd0944e4b4 100644 --- a/src/debug/gc-heap.h +++ b/src/debug/gc-heap.h @@ -13,21 +13,19 @@ #ifndef SEEN_INKSCAPE_DEBUG_GC_HEAP_H #define SEEN_INKSCAPE_DEBUG_GC_HEAP_H -#include "inkgc/gc-core.h" #include "debug/heap.h" +#include "inkgc/gc-core.h" namespace Inkscape { namespace Debug { -class GCHeap : public Debug::Heap { +class GCHeap : public Debug::Heap +{ public: - int features() const override { - return SIZE_AVAILABLE | USED_AVAILABLE | GARBAGE_COLLECTED; - } - char const *name() const override { - return "libgc"; - } - Heap::Stats stats() const override { + int features() const override { return SIZE_AVAILABLE | USED_AVAILABLE | GARBAGE_COLLECTED; } + char const *name() const override { return "libgc"; } + Heap::Stats stats() const override + { Stats stats; stats.size = GC::Core::get_heap_size(); stats.bytes_used = stats.size - GC::Core::get_free_bytes(); @@ -36,8 +34,8 @@ public: void force_collect() override { GC::Core::gcollect(); } }; -} -} +} // namespace Debug +} // namespace Inkscape #endif diff --git a/src/debug/gdk-event-latency-tracker.cpp b/src/debug/gdk-event-latency-tracker.cpp index 57d3e1f2568a14909bdbbdd0f2afdd571c542206..8ffb44a9699309d1dde29b4f3aaac81f53f1cc6a 100644 --- a/src/debug/gdk-event-latency-tracker.cpp +++ b/src/debug/gdk-event-latency-tracker.cpp @@ -10,23 +10,29 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "debug/gdk-event-latency-tracker.h" + #include -#include "debug/gdk-event-latency-tracker.h" #include "preferences.h" namespace Inkscape { namespace Debug { GdkEventLatencyTracker::GdkEventLatencyTracker() - : start_seconds(0.0), max_latency(0.0), skew(1.0), last_elapsed(0.0), last_seconds(0.0) + : start_seconds(0.0) + , max_latency(0.0) + , skew(1.0) + , last_elapsed(0.0) + , last_seconds(0.0) { elapsed.stop(); elapsed.reset(); } -boost::optional GdkEventLatencyTracker::process(GdkEvent const *event) { - guint32 const timestamp=gdk_event_get_time(const_cast(event)); +boost::optional GdkEventLatencyTracker::process(GdkEvent const *event) +{ + guint32 const timestamp = gdk_event_get_time(const_cast(event)); if (timestamp == GDK_CURRENT_TIME) { return boost::optional(); } @@ -53,7 +59,8 @@ boost::optional GdkEventLatencyTracker::process(GdkEvent const *event) { } } -double GdkEventLatencyTracker::getSkew() { +double GdkEventLatencyTracker::getSkew() +{ double val = 0.0; if ((last_elapsed > 0.0) && (last_seconds > 0.0)) { val = (last_seconds - start_seconds) / last_elapsed; @@ -61,13 +68,14 @@ double GdkEventLatencyTracker::getSkew() { return val; } -GdkEventLatencyTracker &GdkEventLatencyTracker::default_tracker() { +GdkEventLatencyTracker &GdkEventLatencyTracker::default_tracker() +{ static GdkEventLatencyTracker tracker; return tracker; } -} -} +} // namespace Debug +} // namespace Inkscape /* Local Variables: diff --git a/src/debug/gdk-event-latency-tracker.h b/src/debug/gdk-event-latency-tracker.h index 9c1cd1fb38d94a1222de31c968ada69f50cca783..64577671958850f86fa5d9e48885fcf801a5f103 100644 --- a/src/debug/gdk-event-latency-tracker.h +++ b/src/debug/gdk-event-latency-tracker.h @@ -14,13 +14,14 @@ #define SEEN_INKSCAPE_DEBUG_GDK_EVENT_LATENCY_TRACKER_H typedef union _GdkEvent GdkEvent; -#include #include +#include namespace Inkscape { namespace Debug { -class GdkEventLatencyTracker { +class GdkEventLatencyTracker +{ public: GdkEventLatencyTracker(); boost::optional process(GdkEvent const *e); @@ -31,7 +32,7 @@ public: private: GdkEventLatencyTracker(GdkEventLatencyTracker const &) = delete; // no copy - void operator=(GdkEventLatencyTracker const &) = delete; // no assign + void operator=(GdkEventLatencyTracker const &) = delete; // no assign double start_seconds; double max_latency; @@ -41,8 +42,8 @@ private: Glib::Timer elapsed; }; -} -} +} // namespace Debug +} // namespace Inkscape #endif /* diff --git a/src/debug/heap.cpp b/src/debug/heap.cpp index ce9cacfa987ed058a2c06248fdb1790d8b407b4d..e228e88bf21d925b74a83a29d9378859a63a06c9 100644 --- a/src/debug/heap.cpp +++ b/src/debug/heap.cpp @@ -10,20 +10,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "inkgc/gc-alloc.h" +#include + #include "debug/gc-heap.h" #include "debug/sysv-heap.h" -#include +#include "inkgc/gc-alloc.h" namespace Inkscape { namespace Debug { namespace { -typedef std::vector > HeapCollection; +typedef std::vector> HeapCollection; -HeapCollection &heaps() { - static bool is_initialized=false; +HeapCollection &heaps() +{ + static bool is_initialized = false; static HeapCollection heaps; if (!is_initialized) { heaps.push_back(new SysVHeap()); @@ -33,22 +35,25 @@ HeapCollection &heaps() { return heaps; } -} +} // namespace -unsigned heap_count() { +unsigned heap_count() +{ return heaps().size(); } -Heap *get_heap(unsigned i) { +Heap *get_heap(unsigned i) +{ return heaps()[i]; } -void register_extra_heap(Heap &heap) { +void register_extra_heap(Heap &heap) +{ heaps().push_back(&heap); } -} -} +} // namespace Debug +} // namespace Inkscape /* Local Variables: diff --git a/src/debug/heap.h b/src/debug/heap.h index 81e7b73ebf491e1745f08e55262e9cc987eaa5c1..f3ed7404ee82808c4fae449a6bb1f6c1923eaa15 100644 --- a/src/debug/heap.h +++ b/src/debug/heap.h @@ -19,26 +19,29 @@ namespace Inkscape { namespace Debug { -class Heap { +class Heap +{ public: virtual ~Heap() = default; - struct Stats { + struct Stats + { std::size_t size; std::size_t bytes_used; }; - enum { - SIZE_AVAILABLE = ( 1 << 0 ), - USED_AVAILABLE = ( 1 << 1 ), - GARBAGE_COLLECTED = ( 1 << 2 ) + enum + { + SIZE_AVAILABLE = (1 << 0), + USED_AVAILABLE = (1 << 1), + GARBAGE_COLLECTED = (1 << 2) }; - virtual int features() const=0; + virtual int features() const = 0; - virtual char const *name() const=0; - virtual Stats stats() const=0; - virtual void force_collect()=0; + virtual char const *name() const = 0; + virtual Stats stats() const = 0; + virtual void force_collect() = 0; }; unsigned heap_count(); @@ -46,9 +49,9 @@ Heap *get_heap(unsigned i); void register_extra_heap(Heap &heap); -} +} // namespace Debug -} +} // namespace Inkscape #endif /* diff --git a/src/debug/log-display-config.cpp b/src/debug/log-display-config.cpp index 7de69bea62b5693cb260e42c911a16f4948cbf78..88f50d77e21160ed24595b175d5e50ceb6b8cccf 100644 --- a/src/debug/log-display-config.cpp +++ b/src/debug/log-display-config.cpp @@ -10,13 +10,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include +#include "debug/log-display-config.h" + #include +#include +#include + #include "debug/event-tracker.h" #include "debug/logger.h" #include "debug/simple-event.h" -#include "debug/log-display-config.h" namespace Inkscape { @@ -26,7 +28,8 @@ namespace { typedef SimpleEvent ConfigurationEvent; -class Monitor : public ConfigurationEvent { +class Monitor : public ConfigurationEvent +{ public: Monitor(GdkMonitor *monitor) : ConfigurationEvent("monitor") @@ -41,11 +44,15 @@ public: } }; -class Display : public ConfigurationEvent { +class Display : public ConfigurationEvent +{ public: - Display() : ConfigurationEvent("display") {} - void generateChildEvents() const override { - GdkDisplay *display=gdk_display_get_default(); + Display() + : ConfigurationEvent("display") + {} + void generateChildEvents() const override + { + GdkDisplay *display = gdk_display_get_default(); gint const n_monitors = gdk_display_get_n_monitors(display); @@ -57,15 +64,16 @@ public: } }; -} +} // namespace -void log_display_config() { +void log_display_config() +{ Logger::write(); } -} +} // namespace Debug -} +} // namespace Inkscape /* Local Variables: diff --git a/src/debug/log-display-config.h b/src/debug/log-display-config.h index df9be18ac6b2daebbf89d7063c3127ca46f18330..76e5cbbc15c037b888bd73bb0f63b3290a00a0fb 100644 --- a/src/debug/log-display-config.h +++ b/src/debug/log-display-config.h @@ -21,7 +21,7 @@ void log_display_config(); } -} +} // namespace Inkscape #endif /* diff --git a/src/debug/logger.cpp b/src/debug/logger.cpp index 37b8221bf1ff031a60ce25d9f0703fe9cdc72c60..842a230e61d7ca979d564d13fa26b66709cf67b2 100644 --- a/src/debug/logger.cpp +++ b/src/debug/logger.cpp @@ -10,82 +10,87 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "debug/logger.h" + #include #include +#include #include #include #include -#include -#include "inkscape-version.h" -#include "debug/logger.h" + #include "debug/simple-event.h" +#include "inkscape-version.h" namespace Inkscape { namespace Debug { -bool Logger::_enabled=false; +bool Logger::_enabled = false; bool Logger::_category_mask[Event::N_CATEGORIES]; namespace { -static void write_escaped_value(std::ostream &os, char const *value) { - for ( char const *current=value ; *current ; ++current ) { +static void write_escaped_value(std::ostream &os, char const *value) +{ + for (char const *current = value; *current; ++current) { switch (*current) { - case '&': - os << "&"; - break; - case '"': - os << """; - break; - case '\'': - os << "'"; - break; - case '<': - os << "<"; - break; - case '>': - os << ">"; - break; - default: - os.put(*current); + case '&': + os << "&"; + break; + case '"': + os << """; + break; + case '\'': + os << "'"; + break; + case '<': + os << "<"; + break; + case '>': + os << ">"; + break; + default: + os.put(*current); } } } -static void write_indent(std::ostream &os, unsigned depth) { - for ( unsigned i = 0 ; i < depth ; i++ ) { +static void write_indent(std::ostream &os, unsigned depth) +{ + for (unsigned i = 0; i < depth; i++) { os.write(" ", 2); } } static std::ofstream log_stream; -static bool empty_tag=false; +static bool empty_tag = false; typedef std::vector> TagStack; -static TagStack &tag_stack() { +static TagStack &tag_stack() +{ static TagStack stack; return stack; } -static void do_shutdown() { +static void do_shutdown() +{ Debug::Logger::shutdown(); } -static bool equal_range(char const *c_string, - char const *start, char const *end) +static bool equal_range(char const *c_string, char const *start, char const *end) { - return !std::strncmp(start, c_string, end - start) && - !c_string[end - start]; + return !std::strncmp(start, c_string, end - start) && !c_string[end - start]; } -static void set_category_mask(bool * const mask, char const *filter) { +static void set_category_mask(bool *const mask, char const *filter) +{ if (!filter) { - for ( unsigned i = 0 ; i < Event::N_CATEGORIES ; i++ ) { + for (unsigned i = 0; i < Event::N_CATEGORIES; i++) { mask[i] = true; } return; } else { - for ( unsigned i = 0 ; i < Event::N_CATEGORIES ; i++ ) { + for (unsigned i = 0; i < Event::N_CATEGORIES; i++) { mask[i] = false; } mask[Event::CORE] = true; @@ -95,27 +100,28 @@ static void set_category_mask(bool * const mask, char const *filter) { char const *end; start = end = filter; while (*end) { - while ( *end && *end != ',' ) { end++; } - if ( start != end ) { - struct CategoryName { + while (*end && *end != ',') { + end++; + } + if (start != end) { + struct CategoryName + { char const *name; Event::Category category; }; - static const CategoryName category_names[] = { - { "CORE", Event::CORE }, - { "XML", Event::XML }, - { "SPOBJECT", Event::SPOBJECT }, - { "DOCUMENT", Event::DOCUMENT }, - { "REFCOUNT", Event::REFCOUNT }, - { "EXTENSION", Event::EXTENSION }, - { "FINALIZERS", Event::FINALIZERS }, - { "INTERACTION", Event::INTERACTION }, - { "CONFIGURATION", Event::CONFIGURATION }, - { "OTHER", Event::OTHER }, - { nullptr, Event::OTHER } - }; + static const CategoryName category_names[] = {{"CORE", Event::CORE}, + {"XML", Event::XML}, + {"SPOBJECT", Event::SPOBJECT}, + {"DOCUMENT", Event::DOCUMENT}, + {"REFCOUNT", Event::REFCOUNT}, + {"EXTENSION", Event::EXTENSION}, + {"FINALIZERS", Event::FINALIZERS}, + {"INTERACTION", Event::INTERACTION}, + {"CONFIGURATION", Event::CONFIGURATION}, + {"OTHER", Event::OTHER}, + {nullptr, Event::OTHER}}; CategoryName const *iter; - for ( iter = category_names ; iter->name ; iter++ ) { + for (iter = category_names; iter->name; iter++) { if (equal_range(iter->name, start, end)) { mask[iter->category] = true; break; @@ -133,22 +139,26 @@ static void set_category_mask(bool * const mask, char const *filter) { typedef SimpleEvent CoreEvent; -class SessionEvent : public CoreEvent { +class SessionEvent : public CoreEvent +{ public: - SessionEvent() : CoreEvent("session") { + SessionEvent() + : CoreEvent("session") + { _addProperty("inkscape-version", Inkscape::version_string); } }; -} +} // namespace -void Logger::init() { +void Logger::init() +{ if (!_enabled) { - char const *log_filename=std::getenv("INKSCAPE_DEBUG_LOG"); + char const *log_filename = std::getenv("INKSCAPE_DEBUG_LOG"); if (log_filename) { log_stream.open(log_filename); if (log_stream.is_open()) { - char const *log_filter=std::getenv("INKSCAPE_DEBUG_FILTER"); + char const *log_filter = std::getenv("INKSCAPE_DEBUG_FILTER"); set_category_mask(_category_mask, log_filter); log_stream << "\n"; log_stream.flush(); @@ -160,8 +170,9 @@ void Logger::init() { } } -void Logger::_start(Event const &event) { - char const *name=event.name(); +void Logger::_start(Event const &event) +{ + char const *name = event.name(); if (empty_tag) { log_stream << ">\n"; @@ -171,9 +182,9 @@ void Logger::_start(Event const &event) { log_stream << "<" << name; - unsigned property_count=event.propertyCount(); - for ( unsigned i = 0 ; i < property_count ; i++ ) { - Event::PropertyPair property=event.property(i); + unsigned property_count = event.propertyCount(); + for (unsigned i = 0; i < property_count; i++) { + Event::PropertyPair property = event.property(i); log_stream << " " << property.name << "=\""; write_escaped_value(log_stream, property.value->c_str()); log_stream << "\""; @@ -187,11 +198,13 @@ void Logger::_start(Event const &event) { event.generateChildEvents(); } -void Logger::_skip() { +void Logger::_skip() +{ tag_stack().push_back(nullptr); } -void Logger::_finish() { +void Logger::_finish() +{ if (tag_stack().back()) { if (empty_tag) { log_stream << "/>\n"; @@ -207,7 +220,8 @@ void Logger::_finish() { tag_stack().pop_back(); } -void Logger::shutdown() { +void Logger::shutdown() +{ if (_enabled) { while (!tag_stack().empty()) { finish(); @@ -215,9 +229,9 @@ void Logger::shutdown() { } } -} +} // namespace Debug -} +} // namespace Inkscape /* Local Variables: diff --git a/src/debug/logger.h b/src/debug/logger.h index ab6c826418ad32457794a3487c3bbc509d539fc3..c0018856e941517e2b0822ff09a40f72dc7a0cf1 100644 --- a/src/debug/logger.h +++ b/src/debug/logger.h @@ -19,12 +19,14 @@ namespace Inkscape { namespace Debug { -class Logger { +class Logger +{ public: static void init(); template - inline static void start() { + inline static void start() + { if (_enabled) { if (_category_mask[EventType::category()]) { _start(EventType()); @@ -35,7 +37,8 @@ public: } template - inline static void start(A const &a) { + inline static void start(A const &a) + { if (_enabled) { if (_category_mask[EventType::category()]) { _start(EventType(a)); @@ -46,7 +49,8 @@ public: } template - inline static void start(A const &a, B const &b) { + inline static void start(A const &a, B const &b) + { if (_enabled) { if (_category_mask[EventType::category()]) { _start(EventType(a, b)); @@ -57,7 +61,8 @@ public: } template - inline static void start(A const &a, B const &b, C const &c) { + inline static void start(A const &a, B const &b, C const &c) + { if (_enabled) { if (_category_mask[EventType::category()]) { _start(EventType(a, b, c)); @@ -67,9 +72,9 @@ public: } } - template - inline static void start(A const &a, B const &b, C const &c, D const &d) { + template + inline static void start(A const &a, B const &b, C const &c, D const &d) + { if (_enabled) { if (_category_mask[EventType::category()]) { _start(EventType(a, b, c, d)); @@ -79,10 +84,8 @@ public: } } - template - inline static void start(A const &a, B const &b, C const &c, - D const &d, E const &e) + template + inline static void start(A const &a, B const &b, C const &c, D const &d, E const &e) { if (_enabled) { if (_category_mask[EventType::category()]) { @@ -93,10 +96,8 @@ public: } } - template - inline static void start(A const &a, B const &b, C const &c, - D const &d, E const &e, F const &f) + template + inline static void start(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f) { if (_enabled) { if (_category_mask[EventType::category()]) { @@ -107,11 +108,8 @@ public: } } - template - inline static void start(A const &a, B const &b, C const &c, D const &d, - E const &e, F const &f, G const &g) + template + inline static void start(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f, G const &g) { if (_enabled) { if (_category_mask[EventType::category()]) { @@ -122,11 +120,10 @@ public: } } - template - inline static void start(A const &a, B const &b, C const &c, D const &d, - E const &e, F const &f, G const &g, H const &h) + template + inline static void start(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f, G const &g, + H const &h) { if (_enabled) { if (_category_mask[EventType::category()]) { @@ -137,82 +134,73 @@ public: } } - inline static void finish() { + inline static void finish() + { if (_enabled) { _finish(); } } template - inline static void write() { + inline static void write() + { start(); finish(); } template - inline static void write(A const &a) { + inline static void write(A const &a) + { start(a); finish(); } template - inline static void write(A const &a, B const &b) { + inline static void write(A const &a, B const &b) + { start(a, b); finish(); } template - inline static void write(A const &a, B const &b, C const &c) { + inline static void write(A const &a, B const &b, C const &c) + { start(a, b, c); finish(); } - template - inline static void write(A const &a, B const &b, C const &c, D const &d) { + template + inline static void write(A const &a, B const &b, C const &c, D const &d) + { start(a, b, c, d); finish(); } - template - inline static void write(A const &a, B const &b, C const &c, - D const &d, E const &e) + template + inline static void write(A const &a, B const &b, C const &c, D const &d, E const &e) { start(a, b, c, d, e); finish(); } - template - inline static void write(A const &a, B const &b, C const &c, - D const &d, E const &e, F const &f) + template + inline static void write(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f) { start(a, b, c, d, e, f); finish(); } - template - inline static void write(A const &a, B const &b, C const &c, - D const &d, E const &e, F const &f, - G const &g) + template + inline static void write(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f, G const &g) { start(a, b, c, d, e, f, g); finish(); } - template - inline static void write(A const &a, B const &b, C const &c, - D const &d, E const &e, F const &f, - G const &g, H const &h) + template + inline static void write(A const &a, B const &b, C const &c, D const &d, E const &e, F const &f, G const &g, + H const &h) { start(a, b, c, d, e, f, g, h); finish(); @@ -230,9 +218,9 @@ private: static bool _category_mask[Event::N_CATEGORIES]; }; -} +} // namespace Debug -} +} // namespace Inkscape #endif /* diff --git a/src/debug/simple-event.h b/src/debug/simple-event.h index 58719b7fbb055878f5b758826f791c5ab64e6c79..26124bde31f4af056cc0ad40accadb5b33b1a9d9 100644 --- a/src/debug/simple-event.h +++ b/src/debug/simple-event.h @@ -14,10 +14,10 @@ #define SEEN_INKSCAPE_DEBUG_SIMPLE_EVENT_H #include +#include // g_assert() #include #include #include -#include // g_assert() #include "debug/event.h" @@ -25,10 +25,13 @@ namespace Inkscape { namespace Debug { -template -class SimpleEvent : public Event { +template +class SimpleEvent : public Event +{ public: - explicit SimpleEvent(char const *name) : _name(name) {} + explicit SimpleEvent(char const *name) + : _name(name) + {} // default copy // default assign @@ -37,22 +40,17 @@ public: char const *name() const override { return _name; } unsigned propertyCount() const override { return _properties.size(); } - PropertyPair property(unsigned property) const override { - return _properties[property]; - } + PropertyPair property(unsigned property) const override { return _properties[property]; } void generateChildEvents() const override {} protected: - void _addProperty(char const *name, std::shared_ptr&& value) { + void _addProperty(char const *name, std::shared_ptr &&value) + { _properties.emplace_back(name, std::move(value)); } - void _addProperty(char const *name, char const *value) { - _addProperty(name, std::make_shared(value)); - } - void _addProperty(char const *name, long value) { - _addFormattedProperty(name, "%ld", value); - } + void _addProperty(char const *name, char const *value) { _addProperty(name, std::make_shared(value)); } + void _addProperty(char const *name, long value) { _addFormattedProperty(name, "%ld", value); } private: char const *_name; @@ -62,7 +60,7 @@ private: { va_list args; va_start(args, format); - gchar *value=g_strdup_vprintf(format, args); + gchar *value = g_strdup_vprintf(format, args); g_assert(value != nullptr); va_end(args); _addProperty(name, value); @@ -70,9 +68,9 @@ private: } }; -} +} // namespace Debug -} +} // namespace Inkscape #endif /* diff --git a/src/debug/sysv-heap.cpp b/src/debug/sysv-heap.cpp index 41455e62a5e8b5ff5c7ed33697cc37919380bf1c..93afdd72bf85d2892d58db652facdb25f415d3aa 100644 --- a/src/debug/sysv-heap.cpp +++ b/src/debug/sysv-heap.cpp @@ -11,11 +11,11 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef HAVE_MALLOC_H -# include +#include #endif #include "debug/sysv-heap.h" @@ -23,7 +23,8 @@ namespace Inkscape { namespace Debug { -int SysVHeap::features() const { +int SysVHeap::features() const +{ #ifdef HAVE_MALLINFO return SIZE_AVAILABLE | USED_AVAILABLE; #else @@ -31,11 +32,12 @@ int SysVHeap::features() const { #endif } -Heap::Stats SysVHeap::stats() const { - Stats stats = { 0, 0 }; +Heap::Stats SysVHeap::stats() const +{ + Stats stats = {0, 0}; #ifdef HAVE_MALLINFO - struct mallinfo info=mallinfo(); + struct mallinfo info = mallinfo(); #ifdef HAVE_STRUCT_MALLINFO_USMBLKS stats.size += info.usmblks; @@ -65,8 +67,8 @@ Heap::Stats SysVHeap::stats() const { return stats; } -} -} +} // namespace Debug +} // namespace Inkscape /* Local Variables: diff --git a/src/debug/sysv-heap.h b/src/debug/sysv-heap.h index f7ed27107143b6d3e2fc801f6d8e241b8af89279..a4628bfe3bf9e4bb95dd54623274ddb00762c727 100644 --- a/src/debug/sysv-heap.h +++ b/src/debug/sysv-heap.h @@ -18,21 +18,20 @@ namespace Inkscape { namespace Debug { -class SysVHeap : public Heap { +class SysVHeap : public Heap +{ public: SysVHeap() = default; - + int features() const override; - char const *name() const override { - return "standard malloc()"; - } + char const *name() const override { return "standard malloc()"; } Stats stats() const override; void force_collect() override {} }; -} -} +} // namespace Debug +} // namespace Inkscape #endif diff --git a/src/debug/timestamp.cpp b/src/debug/timestamp.cpp index dab4e733a63a2f60e6ee2f7ec2149207ee1be3bb..55bbc003d613a300e3a694b2e905fc72496477d8 100644 --- a/src/debug/timestamp.cpp +++ b/src/debug/timestamp.cpp @@ -10,19 +10,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "timestamp.h" #include #include #include #include + #include "debug/simple-event.h" -#include "timestamp.h" namespace Inkscape { namespace Debug { -std::shared_ptr timestamp() { +std::shared_ptr timestamp() +{ gint64 micr = g_get_monotonic_time(); gchar *value = g_strdup_printf("%.6f", (gdouble)micr / 1000000.0); std::shared_ptr result = std::make_shared(value); @@ -30,9 +32,9 @@ std::shared_ptr timestamp() { return result; } -} +} // namespace Debug -} +} // namespace Inkscape /* Local Variables: diff --git a/src/debug/timestamp.h b/src/debug/timestamp.h index a4db90dc6f27aee8ed3de0cdf3a34b9cdb6f28f0..97593165fc6c9f24174dc6da12c4a0954a041306 100644 --- a/src/debug/timestamp.h +++ b/src/debug/timestamp.h @@ -24,7 +24,7 @@ std::shared_ptr timestamp(); } -} +} // namespace Inkscape #endif /* diff --git a/src/desktop-events.cpp b/src/desktop-events.cpp index f7ec8844958935e593b422235ba2520cecf5970e..acc5e5f2dd9f5e1b81439c60fa685093642ec879 100644 --- a/src/desktop-events.cpp +++ b/src/desktop-events.cpp @@ -13,85 +13,72 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include - #include "desktop-events.h" +#include <2geom/angle.h> +#include <2geom/line.h> #include #include - -#include - #include - -#include <2geom/line.h> -#include <2geom/angle.h> +#include +#include +#include #include "desktop.h" -#include "document-undo.h" -#include "document.h" -#include "message-context.h" -#include "preferences.h" -#include "snap.h" -#include "sp-cursor.h" -#include "verbs.h" - #include "display/canvas-grid.h" #include "display/guideline.h" #include "display/snap-indicator.h" - +#include "document-undo.h" +#include "document.h" #include "helper/action.h" - -#include "ui/pixmaps/cursor-select.xpm" - +#include "message-context.h" #include "object/sp-guide.h" #include "object/sp-namedview.h" #include "object/sp-root.h" - +#include "preferences.h" +#include "snap.h" +#include "sp-cursor.h" #include "ui/dialog-events.h" -#include "ui/tools-switch.h" #include "ui/dialog/guides.h" +#include "ui/pixmaps/cursor-select.xpm" +#include "ui/tools-switch.h" #include "ui/tools/tool-base.h" -#include "ui/widget/canvas.h" // Desktop hidden in g_object data. - +#include "ui/widget/canvas.h" // Desktop hidden in g_object data. +#include "verbs.h" #include "widgets/desktop-widget.h" - #include "xml/repr.h" using Inkscape::DocumentUndo; -static void snoop_extended(GdkEvent* event, SPDesktop *desktop); +static void snoop_extended(GdkEvent *event, SPDesktop *desktop); static void init_extended(); /* Root item handler */ -int sp_desktop_root_handler(SPCanvasItem */*item*/, GdkEvent *event, SPDesktop *desktop) +int sp_desktop_root_handler(SPCanvasItem * /*item*/, GdkEvent *event, SPDesktop *desktop) { static bool watch = false; static bool first = true; - if ( first ) { + if (first) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if ( prefs->getBool("/options/useextinput/value", true) - && prefs->getBool("/options/switchonextinput/value") ) { + if (prefs->getBool("/options/useextinput/value", true) && prefs->getBool("/options/switchonextinput/value")) { watch = true; init_extended(); } first = false; } - if ( watch ) { + if (watch) { snoop_extended(event, desktop); } return sp_event_context_root_handler(desktop->event_context, event); } - - static Geom::Point drag_origin; static SPGuideDragType drag_type = SP_DRAG_NONE; -//static bool reset_drag_origin = false; // when Ctrl is pressed while dragging, this is used to trigger resetting of the +// static bool reset_drag_origin = false; // when Ctrl is pressed while dragging, this is used to trigger resetting of +// the // // drag origin to that location so that constrained movement is more intuitive // Min distance from anchor to initiate rotation, measured in screenpixels @@ -103,14 +90,13 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) gint ret = FALSE; SPGuide *guide = SP_GUIDE(data); - SPDesktop *desktop = - static_cast(item->canvas->get_data("SPDesktop")); + SPDesktop *desktop = static_cast(item->canvas->get_data("SPDesktop")); if (!desktop) { std::cerr << "sp_dt_guide_event: No desktop!" << std::endl; } switch (event->type) { - case GDK_2BUTTON_PRESS: + case GDK_2BUTTON_PRESS: if (event->button.button == 1) { drag_type = SP_DRAG_NONE; sp_event_context_discard_delayed_snap_event(desktop->event_context); @@ -119,7 +105,7 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) ret = TRUE; } break; - case GDK_BUTTON_PRESS: + case GDK_BUTTON_PRESS: if (event->button.button == 1) { Geom::Point const event_w(event->button.x, event->button.y); Geom::Point const event_dt(desktop->w2d(event_w)); @@ -144,22 +130,21 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) if (drag_type == SP_DRAG_ROTATE || drag_type == SP_DRAG_TRANSLATE) { sp_canvas_item_grab(item, - ( GDK_BUTTON_RELEASE_MASK | - GDK_BUTTON_PRESS_MASK | - GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK ), - nullptr, - event->button.time); + (GDK_BUTTON_RELEASE_MASK | GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | + GDK_POINTER_MOTION_HINT_MASK), + nullptr, event->button.time); } ret = TRUE; } break; case GDK_MOTION_NOTIFY: if (drag_type != SP_DRAG_NONE) { - Geom::Point const motion_w(event->motion.x, - event->motion.y); + Geom::Point const motion_w(event->motion.x, event->motion.y); Geom::Point motion_dt(desktop->w2d(motion_w)); - sp_event_context_snap_delay_handler(desktop->event_context, (gpointer) item, data, (GdkEventMotion *)event, Inkscape::UI::Tools::DelayedSnapEvent::GUIDE_HANDLER); + sp_event_context_snap_delay_handler(desktop->event_context, (gpointer)item, data, + (GdkEventMotion *)event, + Inkscape::UI::Tools::DelayedSnapEvent::GUIDE_HANDLER); // This is for snapping while dragging existing guidelines. New guidelines, // which are dragged off the ruler, are being snapped in sp_dt_ruler_event @@ -192,19 +177,18 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) m.unSetup(); switch (drag_type) { - case SP_DRAG_TRANSLATE: - { + case SP_DRAG_TRANSLATE: { guide->moveto(motion_dt, false); break; } - case SP_DRAG_ROTATE: - { + case SP_DRAG_ROTATE: { Geom::Point pt = motion_dt - guide->getPoint(); Geom::Angle angle(pt); if (event->motion.state & GDK_CONTROL_MASK) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); unsigned const snaps = abs(prefs->getInt("/options/rotationsnapsperpi/value", 12)); - bool const relative_snaps = prefs->getBool("/options/relativeguiderotationsnap/value", false); + bool const relative_snaps = + prefs->getBool("/options/relativeguiderotationsnap/value", false); if (snaps) { if (relative_snaps) { Geom::Angle orig_angle(guide->getNormal()); @@ -220,8 +204,7 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) guide->set_normal(Geom::Point::polar(angle).cw(), false); break; } - case SP_DRAG_MOVE_ORIGIN: - { + case SP_DRAG_MOVE_ORIGIN: { guide->moveto(motion_dt, false); break; } @@ -235,13 +218,12 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) ret = TRUE; } break; - case GDK_BUTTON_RELEASE: + case GDK_BUTTON_RELEASE: if (drag_type != SP_DRAG_NONE && event->button.button == 1) { sp_event_context_discard_delayed_snap_event(desktop->event_context); if (moved) { - Geom::Point const event_w(event->button.x, - event->button.y); + Geom::Point const event_w(event->button.x, event->button.y); Geom::Point event_dt(desktop->w2d(event_w)); SnapManager &m = desktop->namedview->snap_manager; @@ -274,19 +256,18 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) if (item->canvas->world_point_inside_canvas(event_w)) { switch (drag_type) { - case SP_DRAG_TRANSLATE: - { + case SP_DRAG_TRANSLATE: { guide->moveto(event_dt, true); break; } - case SP_DRAG_ROTATE: - { + case SP_DRAG_ROTATE: { Geom::Point pt = event_dt - guide->getPoint(); Geom::Angle angle(pt); if (event->motion.state & GDK_CONTROL_MASK) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); unsigned const snaps = abs(prefs->getInt("/options/rotationsnapsperpi/value", 12)); - bool const relative_snaps = prefs->getBool("/options/relativeguiderotationsnap/value", false); + bool const relative_snaps = + prefs->getBool("/options/relativeguiderotationsnap/value", false); if (snaps) { if (relative_snaps) { Geom::Angle orig_angle(guide->getNormal()); @@ -302,8 +283,7 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) guide->set_normal(Geom::Point::polar(angle).cw(), true); break; } - case SP_DRAG_MOVE_ORIGIN: - { + case SP_DRAG_MOVE_ORIGIN: { guide->moveto(event_dt, true); break; } @@ -311,8 +291,7 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) assert(false); break; } - DocumentUndo::done(desktop->getDocument(), SP_VERB_NONE, - _("Move guide")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_NONE, _("Move guide")); } else { /* Undo movement of any attached shapes. */ guide->moveto(guide->getPoint(), false); @@ -320,19 +299,17 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) sp_guide_remove(guide); desktop->getCanvas()->get_window()->set_cursor(desktop->event_context->cursor); - DocumentUndo::done(desktop->getDocument(), SP_VERB_NONE, - _("Delete guide")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_NONE, _("Delete guide")); } moved = false; desktop->set_coordinate_status(event_dt); } drag_type = SP_DRAG_NONE; sp_canvas_item_ungrab(item); - ret=TRUE; + ret = TRUE; } break; - case GDK_ENTER_NOTIFY: - { + case GDK_ENTER_NOTIFY: { if (!guide->getLocked()) { sp_guideline_set_color(SP_GUIDELINE(item), guide->getHiColor()); } @@ -350,18 +327,19 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) } GdkCursor *guide_cursor = gdk_cursor_new_for_display(display, cursor_type); - if(guide->getLocked()){ + if (guide->getLocked()) { guide_cursor = sp_cursor_from_xpm(cursor_select_xpm); } - gdk_window_set_cursor(gtk_widget_get_window (GTK_WIDGET(desktop->getCanvas()->gobj())), guide_cursor); + gdk_window_set_cursor(gtk_widget_get_window(GTK_WIDGET(desktop->getCanvas()->gobj())), guide_cursor); g_object_unref(guide_cursor); char *guide_description = guide->description(); - desktop->guidesMessageContext()->setF(Inkscape::NORMAL_MESSAGE, _("Guideline: %s"), guide_description); + desktop->guidesMessageContext()->setF(Inkscape::NORMAL_MESSAGE, _("Guideline: %s"), + guide_description); g_free(guide_description); break; - } - case GDK_LEAVE_NOTIFY: + } + case GDK_LEAVE_NOTIFY: sp_guideline_set_color(SP_GUIDELINE(item), guide->getColor()); // restore event context's cursor @@ -370,11 +348,10 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) desktop->guidesMessageContext()->clear(); break; case GDK_KEY_PRESS: - switch (Inkscape::UI::Tools::get_latin_keyval (&event->key)) { + switch (Inkscape::UI::Tools::get_latin_keyval(&event->key)) { case GDK_KEY_Delete: case GDK_KEY_KP_Delete: - case GDK_KEY_BackSpace: - { + case GDK_KEY_BackSpace: { SPDocument *doc = guide->document; sp_guide_remove(guide); DocumentUndo::done(doc, SP_VERB_NONE, _("Delete guide")); @@ -399,10 +376,9 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) } break; case GDK_KEY_RELEASE: - switch (Inkscape::UI::Tools::get_latin_keyval (&event->key)) { + switch (Inkscape::UI::Tools::get_latin_keyval(&event->key)) { case GDK_KEY_Shift_L: - case GDK_KEY_Shift_R: - { + case GDK_KEY_Shift_R: { auto display = Gdk::Display::get_default(); auto guide_cursor = Gdk::Cursor::create(display, Gdk::HAND1); desktop->getCanvas()->get_window()->set_cursor(guide_cursor); @@ -413,14 +389,14 @@ gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data) break; } break; - default: - break; + default: + break; } return ret; } -//static std::map switchMap; +// static std::map switchMap; static std::map toolToUse; static std::string lastName; static GdkInputSource lastType = GDK_SOURCE_MOUSE; @@ -431,19 +407,17 @@ static void init_extended() auto display = Gdk::Display::get_default(); auto seat = display->get_default_seat(); auto const devices = seat->get_slaves(Gdk::SEAT_CAPABILITY_ALL); - - if ( !devices.empty() ) { + + if (!devices.empty()) { for (auto const dev : devices) { auto const devName = dev->get_name(); auto devSrc = dev->get_source(); - - if ( !devName.empty() - && (avoidName != devName) - && (devSrc != Gdk::SOURCE_MOUSE) ) { -// g_message("Adding '%s' as [%d]", devName, devSrc); + + if (!devName.empty() && (avoidName != devName) && (devSrc != Gdk::SOURCE_MOUSE)) { + // g_message("Adding '%s' as [%d]", devName, devSrc); // Set the initial tool for the device - switch ( devSrc ) { + switch (devSrc) { case Gdk::SOURCE_PEN: toolToUse[devName] = TOOLS_CALLIGRAPHIC; break; @@ -453,75 +427,64 @@ static void init_extended() case Gdk::SOURCE_CURSOR: toolToUse[devName] = TOOLS_SELECT; break; - default: - ; // do not add + default:; // do not add } -// } else if (devName) { -// g_message("Skippn '%s' as [%d]", devName, devSrc); + // } else if (devName) { + // g_message("Skippn '%s' as [%d]", devName, devSrc); } } } } - -void snoop_extended(GdkEvent* event, SPDesktop *desktop) +void snoop_extended(GdkEvent *event, SPDesktop *desktop) { GdkInputSource source = GDK_SOURCE_MOUSE; std::string name; - switch ( event->type ) { - case GDK_MOTION_NOTIFY: - { - GdkEventMotion* event2 = reinterpret_cast(event); - if ( event2->device ) { + switch (event->type) { + case GDK_MOTION_NOTIFY: { + GdkEventMotion *event2 = reinterpret_cast(event); + if (event2->device) { source = gdk_device_get_source(event2->device); name = gdk_device_get_name(event2->device); } - } - break; + } break; case GDK_BUTTON_PRESS: case GDK_2BUTTON_PRESS: case GDK_3BUTTON_PRESS: - case GDK_BUTTON_RELEASE: - { - GdkEventButton* event2 = reinterpret_cast(event); - if ( event2->device ) { + case GDK_BUTTON_RELEASE: { + GdkEventButton *event2 = reinterpret_cast(event); + if (event2->device) { source = gdk_device_get_source(event2->device); name = gdk_device_get_name(event2->device); } - } - break; + } break; - case GDK_SCROLL: - { - GdkEventScroll* event2 = reinterpret_cast(event); - if ( event2->device ) { + case GDK_SCROLL: { + GdkEventScroll *event2 = reinterpret_cast(event); + if (event2->device) { source = gdk_device_get_source(event2->device); name = gdk_device_get_name(event2->device); } - } - break; + } break; case GDK_PROXIMITY_IN: - case GDK_PROXIMITY_OUT: - { - GdkEventProximity* event2 = reinterpret_cast(event); - if ( event2->device ) { + case GDK_PROXIMITY_OUT: { + GdkEventProximity *event2 = reinterpret_cast(event); + if (event2->device) { source = gdk_device_get_source(event2->device); name = gdk_device_get_name(event2->device); } - } - break; + } break; - default: - ; + default:; } if (!name.empty()) { - if ( lastType != source || lastName != name ) { + if (lastType != source || lastName != name) { // The device switched. See if it is one we 'count' - //g_message("Changed device %s -> %s", lastName.c_str(), name.c_str()); + // g_message("Changed device %s -> %s", lastName.c_str(), name.c_str()); std::map::iterator it = toolToUse.find(lastName); if (it != toolToUse.end()) { // Save the tool currently selected for next time the input @@ -530,7 +493,7 @@ void snoop_extended(GdkEvent* event, SPDesktop *desktop) } it = toolToUse.find(name); - if (it != toolToUse.end() ) { + if (it != toolToUse.end()) { tools_switch(desktop, it->second); } @@ -549,4 +512,3 @@ void snoop_extended(GdkEvent* event, SPDesktop *desktop) End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - diff --git a/src/desktop-events.h b/src/desktop-events.h index 8ef9d2f23ea9156ac0442e10ac7150ff7ddceb80..b382961071e45d230f5c429406f44a50b4a42439 100644 --- a/src/desktop-events.h +++ b/src/desktop-events.h @@ -16,32 +16,31 @@ #include -class SPDesktop; +class SPDesktop; struct SPDesktopWidget; struct SPCanvasItem; -typedef union _GdkEvent GdkEvent; +typedef union _GdkEvent GdkEvent; typedef struct _GdkEventCrossing GdkEventCrossing; -typedef struct _GdkEventMotion GdkEventMotion; -typedef struct _GtkWidget GtkWidget; +typedef struct _GdkEventMotion GdkEventMotion; +typedef struct _GtkWidget GtkWidget; /* Item handlers */ -int sp_desktop_root_handler (SPCanvasItem *item, GdkEvent *event, SPDesktop *desktop); +int sp_desktop_root_handler(SPCanvasItem *item, GdkEvent *event, SPDesktop *desktop); /* Default handlers */ -gint sp_canvas_enter_notify (GtkWidget *widget, GdkEventCrossing *event, SPDesktop *desktop); -gint sp_canvas_leave_notify (GtkWidget *widget, GdkEventCrossing *event, SPDesktop *desktop); -gint sp_canvas_motion_notify (GtkWidget *widget,GdkEventMotion *motion, SPDesktop *desktop); +gint sp_canvas_enter_notify(GtkWidget *widget, GdkEventCrossing *event, SPDesktop *desktop); +gint sp_canvas_leave_notify(GtkWidget *widget, GdkEventCrossing *event, SPDesktop *desktop); +gint sp_canvas_motion_notify(GtkWidget *widget, GdkEventMotion *motion, SPDesktop *desktop); /* Guides */ -gint sp_dt_guide_event (SPCanvasItem *item, GdkEvent *event, gpointer data); +gint sp_dt_guide_event(SPCanvasItem *item, GdkEvent *event, gpointer data); #endif - /* Local Variables: mode:c++ diff --git a/src/desktop-style.cpp b/src/desktop-style.cpp index 421981bdb66a3c14f76d3836133e28dc502981ff..69a54a17032c5c81e3c5ddfdf3acec52e77ed60c 100644 --- a/src/desktop-style.cpp +++ b/src/desktop-style.cpp @@ -13,19 +13,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include +#include "desktop-style.h" +#include #include - -#include "desktop-style.h" +#include #include "color-rgba.h" #include "desktop.h" #include "filter-chemistry.h" #include "inkscape.h" -#include "selection.h" - #include "object/box3d-side.h" #include "object/filters/blend.h" #include "object/filters/gaussian-blur.h" @@ -41,28 +38,26 @@ #include "object/sp-tref.h" #include "object/sp-tspan.h" #include "object/sp-use.h" +#include "selection.h" #include "style.h" - #include "svg/css-ostringstream.h" #include "svg/svg-color.h" #include "svg/svg.h" - #include "ui/tools/tool-base.h" - #include "xml/sp-css-attr.h" namespace { bool isTextualItem(SPObject const *obj) { - bool isTextual = dynamic_cast(obj) // - || dynamic_cast(obj) // - || dynamic_cast(obj) // - || dynamic_cast(obj) // - || dynamic_cast(obj) // - || dynamic_cast(obj) // - || dynamic_cast(obj) // - || dynamic_cast(obj); + bool isTextual = dynamic_cast(obj) // + || dynamic_cast(obj) // + || dynamic_cast(obj) // + || dynamic_cast(obj) // + || dynamic_cast(obj) // + || dynamic_cast(obj) // + || dynamic_cast(obj) // + || dynamic_cast(obj); return isTextual; } @@ -72,8 +67,7 @@ bool isTextualItem(SPObject const *obj) /** * Set color on selection on desktop. */ -void -sp_desktop_set_color(SPDesktop *desktop, ColorRGBA const &color, bool is_relative, bool fill) +void sp_desktop_set_color(SPDesktop *desktop, ColorRGBA const &color, bool is_relative, bool fill) { /// \todo relative color setting if (is_relative) { @@ -105,8 +99,7 @@ sp_desktop_set_color(SPDesktop *desktop, ColorRGBA const &color, bool is_relativ /** * Apply style on object and children, recursively. */ -void -sp_desktop_apply_css_recursive(SPObject *o, SPCSSAttr *css, bool skip_lines) +void sp_desktop_apply_css_recursive(SPObject *o, SPCSSAttr *css, bool skip_lines) { // non-items should not have style SPItem *item = dynamic_cast(o); @@ -124,24 +117,13 @@ sp_desktop_apply_css_recursive(SPObject *o, SPCSSAttr *css, bool skip_lines) SPTSpan *tspan = dynamic_cast(o); - if (!(skip_lines - && ((tspan && tspan->role == SP_TSPAN_ROLE_LINE) - || dynamic_cast(o) - || dynamic_cast(o) - || dynamic_cast(o)) - && !o->getAttribute("style")) - && - !(dynamic_cast(o) || - dynamic_cast(o) || - (dynamic_cast(o) && - o->parent && - (dynamic_cast(o->parent) || - dynamic_cast(o->parent) - ) - ) - ) - ) { - + if (!(skip_lines && + ((tspan && tspan->role == SP_TSPAN_ROLE_LINE) || dynamic_cast(o) || + dynamic_cast(o) || dynamic_cast(o)) && + !o->getAttribute("style")) && + !(dynamic_cast(o) || dynamic_cast(o) || + (dynamic_cast(o) && o->parent && + (dynamic_cast(o->parent) || dynamic_cast(o->parent))))) { SPCSSAttr *css_set = sp_repr_css_attr_new(); sp_repr_css_merge(css_set, css); @@ -149,13 +131,12 @@ sp_desktop_apply_css_recursive(SPObject *o, SPCSSAttr *css, bool skip_lines) { Geom::Affine const local(item->i2doc_affine()); double const ex(local.descrim()); - if ( ( ex != 0. ) - && ( ex != 1. ) ) { - sp_css_attr_scale(css_set, 1/ex); + if ((ex != 0.) && (ex != 1.)) { + sp_css_attr_scale(css_set, 1 / ex); } } - o->changeCSS(css_set,"style"); + o->changeCSS(css_set, "style"); sp_repr_css_attr_unref(css_set); } @@ -165,10 +146,11 @@ sp_desktop_apply_css_recursive(SPObject *o, SPCSSAttr *css, bool skip_lines) return; } - for (auto& child: o->children) { + for (auto &child : o->children) { if (sp_repr_css_property(css, "opacity", nullptr) != nullptr) { // Unset properties which are accumulating and thus should not be set recursively. - // For example, setting opacity 0.5 on a group recursively would result in the visible opacity of 0.25 for an item in the group. + // For example, setting opacity 0.5 on a group recursively would result in the visible opacity of 0.25 for + // an item in the group. SPCSSAttr *css_recurse = sp_repr_css_attr_new(); sp_repr_css_merge(css_recurse, css); sp_repr_css_set_property(css_recurse, "opacity", nullptr); @@ -183,12 +165,12 @@ sp_desktop_apply_css_recursive(SPObject *o, SPCSSAttr *css, bool skip_lines) /** * Apply style on selection on desktop. */ - void sp_desktop_set_style(SPDesktop *desktop, SPCSSAttr *css, bool change, bool write_current){ +void sp_desktop_set_style(SPDesktop *desktop, SPCSSAttr *css, bool change, bool write_current) +{ return sp_desktop_set_style(desktop->getSelection(), desktop, css, change, write_current); } -void -sp_desktop_set_style(Inkscape::ObjectSet *set, SPDesktop *desktop, SPCSSAttr *css, bool change, bool write_current) +void sp_desktop_set_style(Inkscape::ObjectSet *set, SPDesktop *desktop, SPCSSAttr *css, bool change, bool write_current) { if (write_current) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -201,13 +183,12 @@ sp_desktop_set_style(Inkscape::ObjectSet *set, SPDesktop *desktop, SPCSSAttr *cs sp_css_attr_unset_uris(css_write); prefs->mergeStyle("/desktop/style", css_write); auto itemlist = set->items(); - for (auto i = itemlist.begin(); i!= itemlist.end(); ++i) { + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { /* last used styles for 3D box faces are stored separately */ SPObject *obj = *i; Box3DSide *side = dynamic_cast(obj); if (side) { - prefs->mergeStyle( - Glib::ustring("/desktop/") + side->axes_string() + "/style", css_write); + prefs->mergeStyle(Glib::ustring("/desktop/") + side->axes_string() + "/style", css_write); } } sp_repr_css_attr_unref(css_write); @@ -216,18 +197,19 @@ sp_desktop_set_style(Inkscape::ObjectSet *set, SPDesktop *desktop, SPCSSAttr *cs if (!change) return; -// 2. Emit signal... See desktop->connectSetStyle in text-tool, tweak-tool, and gradient-drag. + // 2. Emit signal... See desktop->connectSetStyle in text-tool, tweak-tool, and gradient-drag. bool intercepted = desktop->_set_style_signal.emit(css); -/** \todo - * FIXME: in set_style, compensate pattern and gradient fills, stroke width, - * rect corners, font size for the object's own transform so that pasting - * fills does not depend on preserve/optimize. - */ + /** \todo + * FIXME: in set_style, compensate pattern and gradient fills, stroke width, + * rect corners, font size for the object's own transform so that pasting + * fills does not depend on preserve/optimize. + */ -// 3. If nobody has intercepted the signal, apply the style to the selection + // 3. If nobody has intercepted the signal, apply the style to the selection if (!intercepted) { - // If we have an event context, update its cursor (TODO: it could be neater to do this with the signal sent above, but what if the signal gets intercepted?) + // If we have an event context, update its cursor (TODO: it could be neater to do this with the signal sent + // above, but what if the signal gets intercepted?) if (desktop->event_context) { desktop->event_context->sp_event_context_update_cursor(); } @@ -239,24 +221,21 @@ sp_desktop_set_style(Inkscape::ObjectSet *set, SPDesktop *desktop, SPCSSAttr *cs css_no_text = sp_css_attr_unset_text(css_no_text); auto itemlist = set->items(); - for (auto i = itemlist.begin(); i!= itemlist.end(); ++i) { + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; // If not text, don't apply text attributes (can a group have text attributes? Yes! FIXME) if (isTextualItem(item)) { - // If any font property has changed, then we have written out the font // properties in longhand and we need to remove the 'font' shorthand. - if( !sp_repr_css_property_is_unset(css, "font-family") ) { + if (!sp_repr_css_property_is_unset(css, "font-family")) { sp_repr_css_unset_property(css, "font"); } sp_desktop_apply_css_recursive(item, css, true); } else { - sp_desktop_apply_css_recursive(item, css_no_text, true); - } } sp_repr_css_attr_unref(css_no_text); @@ -266,8 +245,7 @@ sp_desktop_set_style(Inkscape::ObjectSet *set, SPDesktop *desktop, SPCSSAttr *cs /** * Return the desktop's current style. */ -SPCSSAttr * -sp_desktop_get_style(SPDesktop *desktop, bool with_text) +SPCSSAttr *sp_desktop_get_style(SPDesktop *desktop, bool with_text) { SPCSSAttr *css = sp_repr_css_attr_new(); sp_repr_css_merge(css, desktop->current); @@ -285,15 +263,12 @@ sp_desktop_get_style(SPDesktop *desktop, bool with_text) /** * Return the desktop's current color. */ -guint32 -sp_desktop_get_color(SPDesktop *desktop, bool is_fill) +guint32 sp_desktop_get_color(SPDesktop *desktop, bool is_fill) { guint32 r = 0; // if there's no color, return black - gchar const *property = sp_repr_css_property(desktop->current, - is_fill ? "fill" : "stroke", - "#000"); + gchar const *property = sp_repr_css_property(desktop->current, is_fill ? "fill" : "stroke", "#000"); - if (desktop->current && property) { // if there is style and the property in it, + if (desktop->current && property) { // if there is style and the property in it, if (strncmp(property, "url", 3)) { // and if it's not url, // read it r = sp_svg_read_color(property, r); @@ -303,8 +278,7 @@ sp_desktop_get_color(SPDesktop *desktop, bool is_fill) return r; } -double -sp_desktop_get_master_opacity_tool(SPDesktop *desktop, Glib::ustring const &tool, bool *has_opacity) +double sp_desktop_get_master_opacity_tool(SPDesktop *desktop, Glib::ustring const &tool, bool *has_opacity) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); SPCSSAttr *css = nullptr; @@ -321,11 +295,11 @@ sp_desktop_get_master_opacity_tool(SPDesktop *desktop, Glib::ustring const &tool gchar const *property = css ? sp_repr_css_property(css, "opacity", "1.000") : nullptr; if (desktop->current && property) { // if there is style and the property in it, - if ( !sp_svg_number_read_f(property, &value) ) { + if (!sp_svg_number_read_f(property, &value)) { value = 1.0; // things failed. set back to the default } else { if (has_opacity) - *has_opacity = true; + *has_opacity = true; } } @@ -334,8 +308,7 @@ sp_desktop_get_master_opacity_tool(SPDesktop *desktop, Glib::ustring const &tool return value; } -double -sp_desktop_get_opacity_tool(SPDesktop *desktop, Glib::ustring const &tool, bool is_fill) +double sp_desktop_get_opacity_tool(SPDesktop *desktop, Glib::ustring const &tool, bool is_fill) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); SPCSSAttr *css = nullptr; @@ -347,10 +320,11 @@ sp_desktop_get_opacity_tool(SPDesktop *desktop, Glib::ustring const &tool, bool } if (css) { - gchar const *property = css ? sp_repr_css_property(css, is_fill ? "fill-opacity": "stroke-opacity", "1.000") : nullptr; + gchar const *property = + css ? sp_repr_css_property(css, is_fill ? "fill-opacity" : "stroke-opacity", "1.000") : nullptr; if (desktop->current && property) { // if there is style and the property in it, - if ( !sp_svg_number_read_f(property, &value) ) { + if (!sp_svg_number_read_f(property, &value)) { value = 1.0; // things failed. set back to the default } } @@ -361,8 +335,7 @@ sp_desktop_get_opacity_tool(SPDesktop *desktop, Glib::ustring const &tool, bool return value; } -guint32 -sp_desktop_get_color_tool(SPDesktop *desktop, Glib::ustring const &tool, bool is_fill, bool *has_color) +guint32 sp_desktop_get_color_tool(SPDesktop *desktop, Glib::ustring const &tool, bool is_fill, bool *has_color) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); SPCSSAttr *css = nullptr; @@ -398,8 +371,8 @@ sp_desktop_get_color_tool(SPDesktop *desktop, Glib::ustring const &tool, bool is /** * Apply the desktop's current style or the tool style to repr. */ -void -sp_desktop_apply_style_tool(SPDesktop *desktop, Inkscape::XML::Node *repr, Glib::ustring const &tool_path, bool with_text) +void sp_desktop_apply_style_tool(SPDesktop *desktop, Inkscape::XML::Node *repr, Glib::ustring const &tool_path, + bool with_text) { SPCSSAttr *css_current = sp_desktop_get_style(desktop, with_text); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -420,9 +393,8 @@ sp_desktop_apply_style_tool(SPDesktop *desktop, Inkscape::XML::Node *repr, Glib: /** * Returns the font size (in SVG pixels) of the text tool style (if text * tool uses its own style) or desktop style (otherwise). -*/ -double -sp_desktop_get_font_size_tool(SPDesktop *desktop) + */ +double sp_desktop_get_font_size_tool(SPDesktop *desktop) { (void)desktop; // TODO cleanup Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -445,8 +417,7 @@ sp_desktop_get_font_size_tool(SPDesktop *desktop) /** Determine average stroke width, simple method */ // see TODO in dialogs/stroke-style.cpp on how to get rid of this eventually -gdouble -stroke_average_width (const std::vector &objects) +gdouble stroke_average_width(const std::vector &objects) { if (objects.empty()) return Geom::infinity(); @@ -464,8 +435,8 @@ stroke_average_width (const std::vector &objects) double width = item->style->stroke_width.computed * i2dt.descrim(); // Width becomes NaN when scaling a diagonal line to a horizontal line (lp:825840) - if ( std::isnan(width)) { - ++n_notstroked; // do not count nonstroked objects + if (std::isnan(width)) { + ++n_notstroked; // do not count nonstroked objects continue; } else { notstroked = false; @@ -480,25 +451,23 @@ stroke_average_width (const std::vector &objects) return avgwidth / (objects.size() - n_notstroked); } -static bool vectorsClose( std::vector const &lhs, std::vector const &rhs ) +static bool vectorsClose(std::vector const &lhs, std::vector const &rhs) { bool isClose = false; - if ( lhs.size() == rhs.size() ) { + if (lhs.size() == rhs.size()) { static double epsilon = 1e-6; isClose = true; - for ( size_t i = 0; (i < lhs.size()) && isClose; ++i ) { + for (size_t i = 0; (i < lhs.size()) && isClose; ++i) { isClose = fabs(lhs[i] - rhs[i]) < epsilon; } } return isClose; } - /** * Write to style_res the average fill or stroke of list of objects, if applicable. */ -int -objects_query_fillstroke (const std::vector &objects, SPStyle *style_res, bool const isfill) +int objects_query_fillstroke(const std::vector &objects, SPStyle *style_res, bool const isfill) { if (objects.empty()) { /* No objects, set empty */ @@ -509,7 +478,7 @@ objects_query_fillstroke (const std::vector &objects, SPStyle *style_re bool paintImpossible = true; paint_res->set = true; - SVGICCColor* iccColor = nullptr; + SVGICCColor *iccColor = nullptr; bool iccSeen = false; gfloat c[4]; @@ -537,15 +506,16 @@ objects_query_fillstroke (const std::vector &objects, SPStyle *style_re // We consider paint "effectively set" for anything within text hierarchy SPObject *parent = obj->parent; bool paint_effectively_set = - paint->set || (dynamic_cast(parent) || dynamic_cast(parent) || dynamic_cast(parent) - || dynamic_cast(parent) || dynamic_cast(parent) || dynamic_cast(parent) - || dynamic_cast(parent) || dynamic_cast(parent)); + paint->set || (dynamic_cast(parent) || dynamic_cast(parent) || + dynamic_cast(parent) || dynamic_cast(parent) || + dynamic_cast(parent) || dynamic_cast(parent) || + dynamic_cast(parent) || dynamic_cast(parent)); // 1. Bail out with QUERY_STYLE_MULTIPLE_DIFFERENT if necessary // cppcheck-suppress comparisonOfBoolWithInt if ((!paintImpossible) && (!paint->isSameType(*paint_res) || (paint_res->set != paint_effectively_set))) { - return QUERY_STYLE_MULTIPLE_DIFFERENT; // different types of paint + return QUERY_STYLE_MULTIPLE_DIFFERENT; // different types of paint } if (paint_res->set && paint->set && paint_res->isPaintserver()) { @@ -563,35 +533,35 @@ objects_query_fillstroke (const std::vector &objects, SPStyle *style_re if (linear_res) { SPLinearGradient *linear = dynamic_cast(server); if (!linear) { - return QUERY_STYLE_MULTIPLE_DIFFERENT; // different kind of server + return QUERY_STYLE_MULTIPLE_DIFFERENT; // different kind of server } SPGradient *vector = linear->getVector(); SPGradient *vector_res = linear_res->getVector(); if (vector_res != vector) { - return QUERY_STYLE_MULTIPLE_DIFFERENT; // different gradient vectors + return QUERY_STYLE_MULTIPLE_DIFFERENT; // different gradient vectors } } else if (radial_res) { SPRadialGradient *radial = dynamic_cast(server); if (!radial) { - return QUERY_STYLE_MULTIPLE_DIFFERENT; // different kind of server + return QUERY_STYLE_MULTIPLE_DIFFERENT; // different kind of server } SPGradient *vector = radial->getVector(); SPGradient *vector_res = radial_res->getVector(); if (vector_res != vector) { - return QUERY_STYLE_MULTIPLE_DIFFERENT; // different gradient vectors + return QUERY_STYLE_MULTIPLE_DIFFERENT; // different gradient vectors } } else if (pattern_res) { SPPattern *pattern = dynamic_cast(server); if (!pattern) { - return QUERY_STYLE_MULTIPLE_DIFFERENT; // different kind of server + return QUERY_STYLE_MULTIPLE_DIFFERENT; // different kind of server } - SPPattern *pat = SP_PATTERN (server)->rootPattern(); - SPPattern *pat_res = SP_PATTERN (server_res)->rootPattern(); + SPPattern *pat = SP_PATTERN(server)->rootPattern(); + SPPattern *pat_res = SP_PATTERN(server_res)->rootPattern(); if (pat_res != pat) { - return QUERY_STYLE_MULTIPLE_DIFFERENT; // different pattern roots + return QUERY_STYLE_MULTIPLE_DIFFERENT; // different pattern roots } } else if (hatch_res) { SPHatch *hatch = dynamic_cast(server); @@ -626,10 +596,9 @@ objects_query_fillstroke (const std::vector &objects, SPStyle *style_re same_color = false; iccColor = nullptr; } - if ( iccSeen && iccColor ) { - if ( !paint->value.color.icc - || (iccColor->colorProfile != paint->value.color.icc->colorProfile) - || !vectorsClose(iccColor->colors, paint->value.color.icc->colors) ) { + if (iccSeen && iccColor) { + if (!paint->value.color.icc || (iccColor->colorProfile != paint->value.color.icc->colorProfile) || + !vectorsClose(iccColor->colors, paint->value.color.icc->colors)) { same_color = false; iccColor = nullptr; } @@ -640,28 +609,28 @@ objects_query_fillstroke (const std::vector &objects, SPStyle *style_re c[0] += d[0]; c[1] += d[1]; c[2] += d[2]; - c[3] += SP_SCALE24_TO_FLOAT (isfill? style->fill_opacity.value : style->stroke_opacity.value); + c[3] += SP_SCALE24_TO_FLOAT(isfill ? style->fill_opacity.value : style->stroke_opacity.value); - num ++; + num++; } - paintImpossible = false; - paint_res->colorSet = paint->colorSet; - paint_res->paintOrigin = paint->paintOrigin; - if (paint_res->set && paint_effectively_set && paint->isPaintserver()) { // copy the server - if (isfill) { - sp_style_set_to_uri(style_res, true, style->getFillURI()); - } else { - sp_style_set_to_uri(style_res, false, style->getStrokeURI()); - } - } - paint_res->set = paint_effectively_set; - style_res->fill_rule.computed = style->fill_rule.computed; // no averaging on this, just use the last one + paintImpossible = false; + paint_res->colorSet = paint->colorSet; + paint_res->paintOrigin = paint->paintOrigin; + if (paint_res->set && paint_effectively_set && paint->isPaintserver()) { // copy the server + if (isfill) { + sp_style_set_to_uri(style_res, true, style->getFillURI()); + } else { + sp_style_set_to_uri(style_res, false, style->getStrokeURI()); + } + } + paint_res->set = paint_effectively_set; + style_res->fill_rule.computed = style->fill_rule.computed; // no averaging on this, just use the last one } // After all objects processed, divide the color if necessary and return if (paint_res->set && paint_res->isColor()) { // set the color - g_assert (num >= 1); + g_assert(num >= 1); c[0] /= num; c[1] /= num; @@ -669,15 +638,14 @@ objects_query_fillstroke (const std::vector &objects, SPStyle *style_re c[3] /= num; paint_res->setColor(c[0], c[1], c[2]); if (isfill) { - style_res->fill_opacity.value = SP_SCALE24_FROM_FLOAT (c[3]); + style_res->fill_opacity.value = SP_SCALE24_FROM_FLOAT(c[3]); } else { - style_res->stroke_opacity.value = SP_SCALE24_FROM_FLOAT (c[3]); + style_res->stroke_opacity.value = SP_SCALE24_FROM_FLOAT(c[3]); } - - if ( iccSeen && iccColor ) { + if (iccSeen && iccColor) { // TODO check for existing - SVGICCColor* tmp = new SVGICCColor(*iccColor); + SVGICCColor *tmp = new SVGICCColor(*iccColor); paint_res->value.color.icc = tmp; } @@ -702,8 +670,7 @@ objects_query_fillstroke (const std::vector &objects, SPStyle *style_re /** * Write to style_res the average opacity of a list of objects. */ -int -objects_query_opacity (const std::vector &objects, SPStyle *style_res) +int objects_query_opacity(const std::vector &objects, SPStyle *style_res) { if (objects.empty()) { /* No objects, set empty */ @@ -715,7 +682,6 @@ objects_query_opacity (const std::vector &objects, SPStyle *style_res) bool same_opacity = true; guint opacity_items = 0; - for (auto obj : objects) { if (!obj) { continue; @@ -731,7 +697,7 @@ objects_query_opacity (const std::vector &objects, SPStyle *style_res) same_opacity = false; } opacity_prev = opacity; - opacity_items ++; + opacity_items++; } if (opacity_items > 1) { opacity_sum /= opacity_items; @@ -755,8 +721,7 @@ objects_query_opacity (const std::vector &objects, SPStyle *style_res) /** * Write to style_res the average stroke width of a list of objects. */ -int -objects_query_strokewidth (const std::vector &objects, SPStyle *style_res) +int objects_query_strokewidth(const std::vector &objects, SPStyle *style_res) { if (objects.empty()) { /* No objects, set empty */ @@ -795,7 +760,7 @@ objects_query_strokewidth (const std::vector &objects, SPStyle *style_r prev_sw = sw; avgwidth += sw; - n_stroked ++; + n_stroked++; } } @@ -821,8 +786,7 @@ objects_query_strokewidth (const std::vector &objects, SPStyle *style_r /** * Write to style_res the average miter limit of a list of objects. */ -int -objects_query_miterlimit (const std::vector &objects, SPStyle *style_res) +int objects_query_miterlimit(const std::vector &objects, SPStyle *style_res) { if (objects.empty()) { /* No objects, set empty */ @@ -844,11 +808,11 @@ objects_query_miterlimit (const std::vector &objects, SPStyle *style_re continue; } - if ( style->stroke.isNone() ) { + if (style->stroke.isNone()) { continue; } - n_stroked ++; + n_stroked++; if (prev_ml != -1 && fabs(style->stroke_miterlimit.value - prev_ml) > 1e-3) { same_ml = false; @@ -880,8 +844,7 @@ objects_query_miterlimit (const std::vector &objects, SPStyle *style_re /** * Write to style_res the stroke cap of a list of objects. */ -int -objects_query_strokecap (const std::vector &objects, SPStyle *style_res) +int objects_query_strokecap(const std::vector &objects, SPStyle *style_res) { if (objects.empty()) { /* No objects, set empty */ @@ -901,11 +864,11 @@ objects_query_strokecap (const std::vector &objects, SPStyle *style_res continue; } - if ( style->stroke.isNone() ) { + if (style->stroke.isNone()) { continue; } - n_stroked ++; + n_stroked++; if (n_stroked > 1 && style->stroke_linecap.value != prev_cap) same_cap = false; @@ -930,8 +893,7 @@ objects_query_strokecap (const std::vector &objects, SPStyle *style_res /** * Write to style_res the stroke join of a list of objects. */ -int -objects_query_strokejoin (const std::vector &objects, SPStyle *style_res) +int objects_query_strokejoin(const std::vector &objects, SPStyle *style_res) { if (objects.empty()) { /* No objects, set empty */ @@ -951,11 +913,11 @@ objects_query_strokejoin (const std::vector &objects, SPStyle *style_re continue; } - if ( style->stroke.isNone() ) { + if (style->stroke.isNone()) { continue; } - n_stroked ++; + n_stroked++; if (n_stroked > 1 && style->stroke_linejoin.value != prev_join) { same_join = false; @@ -981,8 +943,7 @@ objects_query_strokejoin (const std::vector &objects, SPStyle *style_re /** * Write to style_res the paint order of a list of objects. */ -int -objects_query_paintorder (const std::vector &objects, SPStyle *style_res) +int objects_query_paintorder(const std::vector &objects, SPStyle *style_res) { if (objects.empty()) { /* No objects, set empty */ @@ -1002,23 +963,22 @@ objects_query_paintorder (const std::vector &objects, SPStyle *style_re continue; } - if ( style->stroke.isNone() ) { + if (style->stroke.isNone()) { continue; } - n_order ++; + n_order++; if (style->paint_order.set) { - if (!prev_order.empty() && prev_order.compare( style->paint_order.value ) != 0) { + if (!prev_order.empty() && prev_order.compare(style->paint_order.value) != 0) { same_order = false; } prev_order = style->paint_order.value; } } - - g_free( style_res->paint_order.value ); - style_res->paint_order.value= g_strdup( prev_order.c_str() ); + g_free(style_res->paint_order.value); + style_res->paint_order.value = g_strdup(prev_order.c_str()); style_res->paint_order.set = true; if (n_order == 0) { @@ -1036,8 +996,7 @@ objects_query_paintorder (const std::vector &objects, SPStyle *style_re /** * Write to style_res the average font size and spacing of objects. */ -int -objects_query_fontnumbers (const std::vector &objects, SPStyle *style_res) +int objects_query_fontnumbers(const std::vector &objects, SPStyle *style_res) { bool different = false; bool different_lineheight = false; @@ -1058,7 +1017,7 @@ objects_query_fontnumbers (const std::vector &objects, SPStyle *style_r double letterspacing_prev = 0; double wordspacing_prev = 0; double lineheight_prev = 0; - int lineheight_unit_prev = -1; + int lineheight_unit_prev = -1; int texts = 0; int no_size = 0; @@ -1073,7 +1032,7 @@ objects_query_fontnumbers (const std::vector &objects, SPStyle *style_r continue; } - texts ++; + texts++; SPItem *item = dynamic_cast(obj); g_assert(item != nullptr); @@ -1093,7 +1052,8 @@ objects_query_fontnumbers (const std::vector &objects, SPStyle *style_r letterspacing_normal = true; } } else { - letterspacing += style->letter_spacing.computed * doc_scale;; /// \todo FIXME: we assume non-% units here + letterspacing += style->letter_spacing.computed * doc_scale; + ; /// \todo FIXME: we assume non-% units here letterspacing_normal = false; } @@ -1111,17 +1071,14 @@ objects_query_fontnumbers (const std::vector &objects, SPStyle *style_r // Else if all line spacings proportional, use % (average line spacing). // Else use default. double lineheight_current; - int lineheight_unit_current; + int lineheight_unit_current; if (style->line_height.normal) { lineheight_current = Inkscape::Text::Layout::LINE_HEIGHT_NORMAL; lineheight_unit_current = SP_CSS_UNIT_NONE; - if (!different_lineheight && - (lineheight_prev == 0 || lineheight_prev == lineheight_current)) + if (!different_lineheight && (lineheight_prev == 0 || lineheight_prev == lineheight_current)) lineheight_normal = true; - } else if (style->line_height.unit == SP_CSS_UNIT_NONE || - style->line_height.unit == SP_CSS_UNIT_PERCENT || - style->line_height.unit == SP_CSS_UNIT_EM || - style->line_height.unit == SP_CSS_UNIT_EX || + } else if (style->line_height.unit == SP_CSS_UNIT_NONE || style->line_height.unit == SP_CSS_UNIT_PERCENT || + style->line_height.unit == SP_CSS_UNIT_EM || style->line_height.unit == SP_CSS_UNIT_EX || style->font_size.computed == 0) { lineheight_current = style->line_height.value; lineheight_unit_current = style->line_height.unit; @@ -1199,7 +1156,7 @@ objects_query_fontnumbers (const std::vector &objects, SPStyle *style_r if (lineheight_unit_absolute && lineheight_unit_proportional) { // Mixed types of units, fallback to default style_res->line_height.computed = Inkscape::Text::Layout::LINE_HEIGHT_NORMAL * 100.0; - style_res->line_height.value = Inkscape::Text::Layout::LINE_HEIGHT_NORMAL * 100.0; + style_res->line_height.value = Inkscape::Text::Layout::LINE_HEIGHT_NORMAL * 100.0; } } else { // Same units. @@ -1209,7 +1166,7 @@ objects_query_fontnumbers (const std::vector &objects, SPStyle *style_r // No text object... use default. style_res->line_height.unit = SP_CSS_UNIT_NONE; style_res->line_height.computed = Inkscape::Text::Layout::LINE_HEIGHT_NORMAL; - style_res->line_height.value = Inkscape::Text::Layout::LINE_HEIGHT_NORMAL; + style_res->line_height.value = Inkscape::Text::Layout::LINE_HEIGHT_NORMAL; } } @@ -1230,8 +1187,7 @@ objects_query_fontnumbers (const std::vector &objects, SPStyle *style_r /** * Write to style_res the average font style of objects. */ -int -objects_query_fontstyle (const std::vector &objects, SPStyle *style_res) +int objects_query_fontstyle(const std::vector &objects, SPStyle *style_res) { bool different = false; bool set = false; @@ -1248,15 +1204,14 @@ objects_query_fontstyle (const std::vector &objects, SPStyle *style_res continue; } - texts ++; + texts++; - if (set && - ( ( style_res->font_weight.computed != style->font_weight.computed ) || - ( style_res->font_style.computed != style->font_style.computed ) || - ( style_res->font_stretch.computed != style->font_stretch.computed ) || - ( style_res->font_variant.computed != style->font_variant.computed ) || - ( style_res->font_variation_settings != style->font_variation_settings ) ) ) { - different = true; // different styles + if (set && ((style_res->font_weight.computed != style->font_weight.computed) || + (style_res->font_style.computed != style->font_style.computed) || + (style_res->font_stretch.computed != style->font_stretch.computed) || + (style_res->font_variant.computed != style->font_variant.computed) || + (style_res->font_variation_settings != style->font_variation_settings))) { + different = true; // different styles } set = true; @@ -1284,30 +1239,29 @@ objects_query_fontstyle (const std::vector &objects, SPStyle *style_res } } -int -objects_query_fontvariants (const std::vector &objects, SPStyle *style_res) +int objects_query_fontvariants(const std::vector &objects, SPStyle *style_res) { bool set = false; int texts = 0; - SPILigatures* ligatures_res = &(style_res->font_variant_ligatures); - SPINumeric* numeric_res = &(style_res->font_variant_numeric); - SPIEastAsian* asian_res = &(style_res->font_variant_east_asian); + SPILigatures *ligatures_res = &(style_res->font_variant_ligatures); + SPINumeric *numeric_res = &(style_res->font_variant_numeric); + SPIEastAsian *asian_res = &(style_res->font_variant_east_asian); // Stores 'and' of all values ligatures_res->computed = SP_CSS_FONT_VARIANT_LIGATURES_NORMAL; - int position_computed = SP_CSS_FONT_VARIANT_POSITION_NORMAL; - int caps_computed = SP_CSS_FONT_VARIANT_CAPS_NORMAL; - numeric_res->computed = SP_CSS_FONT_VARIANT_NUMERIC_NORMAL; - asian_res->computed = SP_CSS_FONT_VARIANT_EAST_ASIAN_NORMAL; + int position_computed = SP_CSS_FONT_VARIANT_POSITION_NORMAL; + int caps_computed = SP_CSS_FONT_VARIANT_CAPS_NORMAL; + numeric_res->computed = SP_CSS_FONT_VARIANT_NUMERIC_NORMAL; + asian_res->computed = SP_CSS_FONT_VARIANT_EAST_ASIAN_NORMAL; // Stores only differences ligatures_res->value = 0; - int position_value = 0; - int caps_value = 0; - numeric_res->value = 0; - asian_res->value = 0; + int position_value = 0; + int caps_value = 0; + numeric_res->value = 0; + asian_res->value = 0; for (auto obj : objects) { if (!isTextualItem(obj)) { @@ -1319,19 +1273,19 @@ objects_query_fontvariants (const std::vector &objects, SPStyle *style_ continue; } - texts ++; + texts++; - SPILigatures* ligatures_in = &(style->font_variant_ligatures); - auto* position_in = &(style->font_variant_position); - auto* caps_in = &(style->font_variant_caps); - SPINumeric* numeric_in = &(style->font_variant_numeric); - SPIEastAsian* asian_in = &(style->font_variant_east_asian); + SPILigatures *ligatures_in = &(style->font_variant_ligatures); + auto *position_in = &(style->font_variant_position); + auto *caps_in = &(style->font_variant_caps); + SPINumeric *numeric_in = &(style->font_variant_numeric); + SPIEastAsian *asian_in = &(style->font_variant_east_asian); // computed stores which bits are on/off, only valid if same between all selected objects. // value stores which bits are different between objects. This is a bit of an abuse of // the values but then we don't need to add new variables to class. if (set) { - ligatures_res->value |= (ligatures_res->computed ^ ligatures_in->computed ); + ligatures_res->value |= (ligatures_res->computed ^ ligatures_in->computed); ligatures_res->computed &= ligatures_in->computed; position_value |= (position_computed ^ position_in->computed); @@ -1340,18 +1294,18 @@ objects_query_fontvariants (const std::vector &objects, SPStyle *style_ caps_value |= (caps_computed ^ caps_in->computed); caps_computed &= caps_in->computed; - numeric_res->value |= (numeric_res->computed ^ numeric_in->computed ); + numeric_res->value |= (numeric_res->computed ^ numeric_in->computed); numeric_res->computed &= numeric_in->computed; - asian_res->value |= (asian_res->computed ^ asian_in->computed ); + asian_res->value |= (asian_res->computed ^ asian_in->computed); asian_res->computed &= asian_in->computed; } else { - ligatures_res->computed = ligatures_in->computed; - position_computed = position_in->computed; - caps_computed = caps_in->computed; - numeric_res->computed = numeric_in->computed; - asian_res->computed = asian_in->computed; + ligatures_res->computed = ligatures_in->computed; + position_computed = position_in->computed; + caps_computed = caps_in->computed; + numeric_res->computed = numeric_in->computed; + asian_res->computed = asian_in->computed; } set = true; @@ -1363,11 +1317,8 @@ objects_query_fontvariants (const std::vector &objects, SPStyle *style_ style_res->font_variant_caps.value = static_cast(caps_value); style_res->font_variant_caps.computed = static_cast(caps_computed); - bool different = (style_res->font_variant_ligatures.value != 0 || - position_value != 0 || - caps_value != 0 || - style_res->font_variant_numeric.value != 0 || - style_res->font_variant_east_asian.value != 0); + bool different = (style_res->font_variant_ligatures.value != 0 || position_value != 0 || caps_value != 0 || + style_res->font_variant_numeric.value != 0 || style_res->font_variant_east_asian.value != 0); if (texts == 0 || !set) return QUERY_STYLE_NOTHING; @@ -1383,12 +1334,10 @@ objects_query_fontvariants (const std::vector &objects, SPStyle *style_ } } - /** * Write to style_res the average writing modes style of objects. */ -int -objects_query_writing_modes (const std::vector &objects, SPStyle *style_res) +int objects_query_writing_modes(const std::vector &objects, SPStyle *style_res) { bool different = false; bool set = false; @@ -1405,13 +1354,12 @@ objects_query_writing_modes (const std::vector &objects, SPStyle *style continue; } - texts ++; + texts++; - if (set && - ( ( style_res->writing_mode.computed != style->writing_mode.computed ) || - ( style_res->direction.computed != style->direction.computed ) || - ( style_res->text_orientation.computed != style->text_orientation.computed ) ) ) { - different = true; // different styles + if (set && ((style_res->writing_mode.computed != style->writing_mode.computed) || + (style_res->direction.computed != style->direction.computed) || + (style_res->text_orientation.computed != style->text_orientation.computed))) { + different = true; // different styles } set = true; @@ -1434,8 +1382,7 @@ objects_query_writing_modes (const std::vector &objects, SPStyle *style } } -int -objects_query_fontfeaturesettings (const std::vector &objects, SPStyle *style_res) +int objects_query_fontfeaturesettings(const std::vector &objects, SPStyle *style_res) { bool different = false; int texts = 0; @@ -1453,12 +1400,11 @@ objects_query_fontfeaturesettings (const std::vector &objects, SPStyle continue; } - texts ++; + texts++; if (style_res->font_feature_settings.set && // - strcmp(style_res->font_feature_settings.value(), - style->font_feature_settings.value())) { - different = true; // different fonts + strcmp(style_res->font_feature_settings.value(), style->font_feature_settings.value())) { + different = true; // different fonts } style_res->font_feature_settings = style->font_feature_settings; @@ -1480,12 +1426,10 @@ objects_query_fontfeaturesettings (const std::vector &objects, SPStyle } } - /** * Write to style_res the baseline numbers. */ -static int -objects_query_baselines (const std::vector &objects, SPStyle *style_res) +static int objects_query_baselines(const std::vector &objects, SPStyle *style_res) { bool different = false; @@ -1514,25 +1458,20 @@ objects_query_baselines (const std::vector &objects, SPStyle *style_res continue; } - texts ++; + texts++; SPIBaselineShift current; - if(style->baseline_shift.set) { - - current.set = style->baseline_shift.set; - current.inherit = style->baseline_shift.inherit; - current.type = style->baseline_shift.type; - current.literal = style->baseline_shift.literal; - current.value = style->baseline_shift.value; + if (style->baseline_shift.set) { + current.set = style->baseline_shift.set; + current.inherit = style->baseline_shift.inherit; + current.type = style->baseline_shift.type; + current.literal = style->baseline_shift.literal; + current.value = style->baseline_shift.value; current.computed = style->baseline_shift.computed; - if( set ) { - if( current.set != old.set || - current.inherit != old.inherit || - current.type != old.type || - current.literal != old.literal || - current.value != old.value || - current.computed != old.computed ) { + if (set) { + if (current.set != old.set || current.inherit != old.inherit || current.type != old.type || + current.literal != old.literal || current.value != old.value || current.computed != old.computed) { // Maybe this needs to be better thought out. different = true; } @@ -1540,24 +1479,24 @@ objects_query_baselines (const std::vector &objects, SPStyle *style_res set = true; - old.set = current.set; - old.inherit = current.inherit; - old.type = current.type; - old.literal = current.literal; - old.value = current.value; + old.set = current.set; + old.inherit = current.inherit; + old.type = current.type; + old.literal = current.literal; + old.value = current.value; old.computed = current.computed; } } - if (different || !set ) { + if (different || !set) { style_res->baseline_shift.set = false; style_res->baseline_shift.computed = 0.0; } else { - style_res->baseline_shift.set = old.set; - style_res->baseline_shift.inherit = old.inherit; - style_res->baseline_shift.type = old.type; - style_res->baseline_shift.literal = old.literal; - style_res->baseline_shift.value = old.value; + style_res->baseline_shift.set = old.set; + style_res->baseline_shift.inherit = old.inherit; + style_res->baseline_shift.type = old.type; + style_res->baseline_shift.literal = old.literal; + style_res->baseline_shift.value = old.value; style_res->baseline_shift.computed = old.computed; } @@ -1578,8 +1517,7 @@ objects_query_baselines (const std::vector &objects, SPStyle *style_res /** * Write to style_res the average font family of objects. */ -int -objects_query_fontfamily (const std::vector &objects, SPStyle *style_res) +int objects_query_fontfamily(const std::vector &objects, SPStyle *style_res) { bool different = false; int texts = 0; @@ -1597,11 +1535,11 @@ objects_query_fontfamily (const std::vector &objects, SPStyle *style_re continue; } - texts ++; + texts++; if (style_res->font_family.set && // strcmp(style_res->font_family.value(), style->font_family.value())) { - different = true; // different fonts + different = true; // different fonts } style_res->font_family = style->font_family; @@ -1623,8 +1561,7 @@ objects_query_fontfamily (const std::vector &objects, SPStyle *style_re } } -static int -objects_query_fontspecification (const std::vector &objects, SPStyle *style_res) +static int objects_query_fontspecification(const std::vector &objects, SPStyle *style_res) { bool different = false; int texts = 0; @@ -1642,11 +1579,11 @@ objects_query_fontspecification (const std::vector &objects, SPStyle *s continue; } - texts ++; + texts++; if (style_res->font_specification.set && g_strcmp0(style_res->font_specification.value(), style->font_specification.value())) { - different = true; // different fonts + different = true; // different fonts } if (style->font_specification.set) { @@ -1670,8 +1607,7 @@ objects_query_fontspecification (const std::vector &objects, SPStyle *s } } -int -objects_query_blend (const std::vector &objects, SPStyle *style_res) +int objects_query_blend(const std::vector &objects, SPStyle *style_res) { auto blend = SP_CSS_BLEND_NORMAL; auto blend_prev = blend; @@ -1715,7 +1651,7 @@ objects_query_blend (const std::vector &objects, SPStyle *style_res) } else if (items == 1) { return QUERY_STYLE_SINGLE; } else { - if(same_blend) + if (same_blend) return QUERY_STYLE_MULTIPLE_SAME; else return QUERY_STYLE_MULTIPLE_DIFFERENT; @@ -1742,8 +1678,7 @@ int objects_query_isolation(const std::vector &objects, SPStyle *style if (style->isolation.set) { isolation = style->isolation.value; - } - else { + } else { isolation = SP_CSS_ISOLATION_AUTO; } @@ -1771,10 +1706,9 @@ int objects_query_isolation(const std::vector &objects, SPStyle *style /** * Write to style_res the average blurring of a list of objects. */ -int -objects_query_blur (const std::vector &objects, SPStyle *style_res) +int objects_query_blur(const std::vector &objects, SPStyle *style_res) { - if (objects.empty()) { + if (objects.empty()) { /* No objects, set empty */ return QUERY_STYLE_NOTHING; } @@ -1800,27 +1734,28 @@ objects_query_blur (const std::vector &objects, SPStyle *style_res) Geom::Affine i2d = item->i2dt_affine(); - items ++; + items++; - //if object has a filter + // if object has a filter if (style->filter.set && style->getFilter()) { - //cycle through filter primitives - for(auto& primitive_obj: style->getFilter()->children) { + // cycle through filter primitives + for (auto &primitive_obj : style->getFilter()->children) { SPFilterPrimitive *primitive = dynamic_cast(&primitive_obj); if (primitive) { - - //if primitive is gaussianblur - SPGaussianBlur * spblur = dynamic_cast(primitive); + // if primitive is gaussianblur + SPGaussianBlur *spblur = dynamic_cast(primitive); if (spblur) { float num = spblur->stdDeviation.getNumber(); float dummy = num * i2d.descrim(); if (!std::isnan(dummy)) { blur_sum += dummy; - if (blur_prev != -1 && fabs (num - blur_prev) > 1e-2) // rather low tolerance because difference in blur radii is much harder to notice than e.g. difference in sizes + if (blur_prev != -1 && + fabs(num - blur_prev) > 1e-2) // rather low tolerance because difference in blur radii + // is much harder to notice than e.g. difference in sizes same_blur = false; blur_prev = num; - //TODO: deal with opt number, for the moment it's not necessary to the ui. - blur_items ++; + // TODO: deal with opt number, for the moment it's not necessary to the ui. + blur_items++; } } } @@ -1850,62 +1785,59 @@ objects_query_blur (const std::vector &objects, SPStyle *style_res) * Query the given list of objects for the given property, write * the result to style, return appropriate flag. */ -int -sp_desktop_query_style_from_list (const std::vector &list, SPStyle *style, int property) +int sp_desktop_query_style_from_list(const std::vector &list, SPStyle *style, int property) { if (property == QUERY_STYLE_PROPERTY_FILL) { - return objects_query_fillstroke (list, style, true); + return objects_query_fillstroke(list, style, true); } else if (property == QUERY_STYLE_PROPERTY_STROKE) { - return objects_query_fillstroke (list, style, false); + return objects_query_fillstroke(list, style, false); } else if (property == QUERY_STYLE_PROPERTY_STROKEWIDTH) { - return objects_query_strokewidth (list, style); + return objects_query_strokewidth(list, style); } else if (property == QUERY_STYLE_PROPERTY_STROKEMITERLIMIT) { - return objects_query_miterlimit (list, style); + return objects_query_miterlimit(list, style); } else if (property == QUERY_STYLE_PROPERTY_STROKECAP) { - return objects_query_strokecap (list, style); + return objects_query_strokecap(list, style); } else if (property == QUERY_STYLE_PROPERTY_STROKEJOIN) { - return objects_query_strokejoin (list, style); + return objects_query_strokejoin(list, style); } else if (property == QUERY_STYLE_PROPERTY_PAINTORDER) { - return objects_query_paintorder (list, style); + return objects_query_paintorder(list, style); } else if (property == QUERY_STYLE_PROPERTY_MASTEROPACITY) { - return objects_query_opacity (list, style); + return objects_query_opacity(list, style); } else if (property == QUERY_STYLE_PROPERTY_FONT_SPECIFICATION) { - return objects_query_fontspecification (list, style); + return objects_query_fontspecification(list, style); } else if (property == QUERY_STYLE_PROPERTY_FONTFAMILY) { - return objects_query_fontfamily (list, style); + return objects_query_fontfamily(list, style); } else if (property == QUERY_STYLE_PROPERTY_FONTSTYLE) { - return objects_query_fontstyle (list, style); + return objects_query_fontstyle(list, style); } else if (property == QUERY_STYLE_PROPERTY_FONTVARIANTS) { - return objects_query_fontvariants (list, style); + return objects_query_fontvariants(list, style); } else if (property == QUERY_STYLE_PROPERTY_FONTFEATURESETTINGS) { - return objects_query_fontfeaturesettings (list, style); + return objects_query_fontfeaturesettings(list, style); } else if (property == QUERY_STYLE_PROPERTY_FONTNUMBERS) { - return objects_query_fontnumbers (list, style); + return objects_query_fontnumbers(list, style); } else if (property == QUERY_STYLE_PROPERTY_WRITINGMODES) { - return objects_query_writing_modes (list, style); + return objects_query_writing_modes(list, style); } else if (property == QUERY_STYLE_PROPERTY_BASELINES) { - return objects_query_baselines (list, style); + return objects_query_baselines(list, style); } else if (property == QUERY_STYLE_PROPERTY_BLEND) { - return objects_query_blend (list, style); + return objects_query_blend(list, style); } else if (property == QUERY_STYLE_PROPERTY_ISOLATION) { return objects_query_isolation(list, style); } else if (property == QUERY_STYLE_PROPERTY_BLUR) { - return objects_query_blur (list, style); + return objects_query_blur(list, style); } return QUERY_STYLE_NOTHING; } - /** * Query the subselection (if any) or selection on the given desktop for the given property, write * the result to style, return appropriate flag. */ -int -sp_desktop_query_style(SPDesktop *desktop, SPStyle *style, int property) +int sp_desktop_query_style(SPDesktop *desktop, SPStyle *style, int property) { // Used by text tool and in gradient dragging. See connectQueryStyle. int ret = desktop->_query_style_signal.emit(style, property); @@ -1916,7 +1848,7 @@ sp_desktop_query_style(SPDesktop *desktop, SPStyle *style, int property) // otherwise, do querying and averaging over selection if (desktop->selection != nullptr) { std::vector vec(desktop->selection->items().begin(), desktop->selection->items().end()); - return sp_desktop_query_style_from_list (vec, style, property); + return sp_desktop_query_style_from_list(vec, style, property); } return QUERY_STYLE_NOTHING; @@ -1926,43 +1858,34 @@ sp_desktop_query_style(SPDesktop *desktop, SPStyle *style, int property) * Do the same as sp_desktop_query_style for all (defined) style properties, return true if at * least one of the properties did not return QUERY_STYLE_NOTHING. */ -bool -sp_desktop_query_style_all (SPDesktop *desktop, SPStyle *query) +bool sp_desktop_query_style_all(SPDesktop *desktop, SPStyle *query) { - int result_family = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_FONTFAMILY); - int result_fstyle = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_FONTSTYLE); - int result_fnumbers = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_FONTNUMBERS); - int result_fill = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_FILL); - int result_stroke = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_STROKE); - int result_strokewidth = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_STROKEWIDTH); - int result_strokemiterlimit = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_STROKEMITERLIMIT); - int result_strokecap = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_STROKECAP); - int result_strokejoin = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_STROKEJOIN); - - int result_paintorder = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_PAINTORDER); - - int result_opacity = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_MASTEROPACITY); - int result_blur = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_BLUR); - int result_blend = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_BLEND); - int result_isolation = sp_desktop_query_style (desktop, query, QUERY_STYLE_PROPERTY_ISOLATION); - - return (result_family != QUERY_STYLE_NOTHING || - result_fstyle != QUERY_STYLE_NOTHING || - result_fnumbers != QUERY_STYLE_NOTHING || - result_fill != QUERY_STYLE_NOTHING || - result_stroke != QUERY_STYLE_NOTHING || - result_opacity != QUERY_STYLE_NOTHING || - result_strokewidth != QUERY_STYLE_NOTHING || - result_strokemiterlimit != QUERY_STYLE_NOTHING || - result_strokecap != QUERY_STYLE_NOTHING || - result_strokejoin != QUERY_STYLE_NOTHING || - result_paintorder != QUERY_STYLE_NOTHING || - result_blur != QUERY_STYLE_NOTHING || - result_isolation != QUERY_STYLE_NOTHING || - result_blend != QUERY_STYLE_NOTHING); + int result_family = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_FONTFAMILY); + int result_fstyle = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_FONTSTYLE); + int result_fnumbers = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_FONTNUMBERS); + int result_fill = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_FILL); + int result_stroke = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_STROKE); + int result_strokewidth = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_STROKEWIDTH); + int result_strokemiterlimit = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_STROKEMITERLIMIT); + int result_strokecap = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_STROKECAP); + int result_strokejoin = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_STROKEJOIN); + + int result_paintorder = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_PAINTORDER); + + int result_opacity = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_MASTEROPACITY); + int result_blur = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_BLUR); + int result_blend = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_BLEND); + int result_isolation = sp_desktop_query_style(desktop, query, QUERY_STYLE_PROPERTY_ISOLATION); + + return (result_family != QUERY_STYLE_NOTHING || result_fstyle != QUERY_STYLE_NOTHING || + result_fnumbers != QUERY_STYLE_NOTHING || result_fill != QUERY_STYLE_NOTHING || + result_stroke != QUERY_STYLE_NOTHING || result_opacity != QUERY_STYLE_NOTHING || + result_strokewidth != QUERY_STYLE_NOTHING || result_strokemiterlimit != QUERY_STYLE_NOTHING || + result_strokecap != QUERY_STYLE_NOTHING || result_strokejoin != QUERY_STYLE_NOTHING || + result_paintorder != QUERY_STYLE_NOTHING || result_blur != QUERY_STYLE_NOTHING || + result_isolation != QUERY_STYLE_NOTHING || result_blend != QUERY_STYLE_NOTHING); } - /* Local Variables: mode:c++ diff --git a/src/desktop-style.h b/src/desktop-style.h index c32bc244797c57002069e26dc8af97a44836e36d..2eb362079d40dbcb7fcabc0d030c917f9f116726 100644 --- a/src/desktop-style.h +++ b/src/desktop-style.h @@ -14,9 +14,8 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include - #include +#include class ColorRGBA; class SPCSSAttr; @@ -29,76 +28,82 @@ class ObjectSet; namespace XML { class Node; } +} // namespace Inkscape +namespace Glib { +class ustring; } -namespace Glib { class ustring; } -enum { // what kind of a style the query is returning - QUERY_STYLE_NOTHING, // nothing was queried - e.g. no selection - QUERY_STYLE_SINGLE, // single object was queried - QUERY_STYLE_MULTIPLE_SAME, // multiple objects were queried, the results were the same +enum +{ // what kind of a style the query is returning + QUERY_STYLE_NOTHING, // nothing was queried - e.g. no selection + QUERY_STYLE_SINGLE, // single object was queried + QUERY_STYLE_MULTIPLE_SAME, // multiple objects were queried, the results were the same QUERY_STYLE_MULTIPLE_DIFFERENT, // multiple objects were queried, the results could NOT be meaningfully averaged - QUERY_STYLE_MULTIPLE_AVERAGED // multiple objects were queried, the results were meaningfully averaged + QUERY_STYLE_MULTIPLE_AVERAGED // multiple objects were queried, the results were meaningfully averaged }; -enum { // which property was queried (add when you need more) +enum +{ // which property was queried (add when you need more) QUERY_STYLE_PROPERTY_EVERYTHING, - QUERY_STYLE_PROPERTY_FILL, // fill, fill-opacity - QUERY_STYLE_PROPERTY_STROKE, // stroke, stroke-opacity - QUERY_STYLE_PROPERTY_STROKEWIDTH, // stroke-width - QUERY_STYLE_PROPERTY_STROKEMITERLIMIT, // miter limit - QUERY_STYLE_PROPERTY_STROKEJOIN, // stroke join - QUERY_STYLE_PROPERTY_STROKECAP, // stroke cap - QUERY_STYLE_PROPERTY_STROKESTYLE, // markers, dasharray, miterlimit, stroke-width, stroke-cap, stroke-join - QUERY_STYLE_PROPERTY_PAINTORDER, // paint-order - QUERY_STYLE_PROPERTY_FONT_SPECIFICATION, //-inkscape-font-specification - QUERY_STYLE_PROPERTY_FONTFAMILY, // font-family - QUERY_STYLE_PROPERTY_FONTSTYLE, // font style - QUERY_STYLE_PROPERTY_FONTVARIANTS, // font variants (OpenType features) + QUERY_STYLE_PROPERTY_FILL, // fill, fill-opacity + QUERY_STYLE_PROPERTY_STROKE, // stroke, stroke-opacity + QUERY_STYLE_PROPERTY_STROKEWIDTH, // stroke-width + QUERY_STYLE_PROPERTY_STROKEMITERLIMIT, // miter limit + QUERY_STYLE_PROPERTY_STROKEJOIN, // stroke join + QUERY_STYLE_PROPERTY_STROKECAP, // stroke cap + QUERY_STYLE_PROPERTY_STROKESTYLE, // markers, dasharray, miterlimit, stroke-width, stroke-cap, stroke-join + QUERY_STYLE_PROPERTY_PAINTORDER, // paint-order + QUERY_STYLE_PROPERTY_FONT_SPECIFICATION, //-inkscape-font-specification + QUERY_STYLE_PROPERTY_FONTFAMILY, // font-family + QUERY_STYLE_PROPERTY_FONTSTYLE, // font style + QUERY_STYLE_PROPERTY_FONTVARIANTS, // font variants (OpenType features) QUERY_STYLE_PROPERTY_FONTFEATURESETTINGS, // font feature settings (OpenType features) - QUERY_STYLE_PROPERTY_FONTNUMBERS, // size, spacings - QUERY_STYLE_PROPERTY_BASELINES, // baseline-shift - QUERY_STYLE_PROPERTY_WRITINGMODES, // writing-mode, text-orientation - QUERY_STYLE_PROPERTY_MASTEROPACITY, // opacity - QUERY_STYLE_PROPERTY_ISOLATION, // isolation - QUERY_STYLE_PROPERTY_BLEND, // blend - QUERY_STYLE_PROPERTY_BLUR // blur + QUERY_STYLE_PROPERTY_FONTNUMBERS, // size, spacings + QUERY_STYLE_PROPERTY_BASELINES, // baseline-shift + QUERY_STYLE_PROPERTY_WRITINGMODES, // writing-mode, text-orientation + QUERY_STYLE_PROPERTY_MASTEROPACITY, // opacity + QUERY_STYLE_PROPERTY_ISOLATION, // isolation + QUERY_STYLE_PROPERTY_BLEND, // blend + QUERY_STYLE_PROPERTY_BLUR // blur }; void sp_desktop_apply_css_recursive(SPObject *o, SPCSSAttr *css, bool skip_lines); void sp_desktop_set_color(SPDesktop *desktop, ColorRGBA const &color, bool is_relative, bool fill); -void sp_desktop_set_style(Inkscape::ObjectSet *set, SPDesktop *desktop, SPCSSAttr *css, bool change = true, bool write_current = true); +void sp_desktop_set_style(Inkscape::ObjectSet *set, SPDesktop *desktop, SPCSSAttr *css, bool change = true, + bool write_current = true); void sp_desktop_set_style(SPDesktop *desktop, SPCSSAttr *css, bool change = true, bool write_current = true); SPCSSAttr *sp_desktop_get_style(SPDesktop *desktop, bool with_text); -guint32 sp_desktop_get_color (SPDesktop *desktop, bool is_fill); -double sp_desktop_get_master_opacity_tool(SPDesktop *desktop, Glib::ustring const &tool, bool* has_opacity = nullptr); +guint32 sp_desktop_get_color(SPDesktop *desktop, bool is_fill); +double sp_desktop_get_master_opacity_tool(SPDesktop *desktop, Glib::ustring const &tool, bool *has_opacity = nullptr); double sp_desktop_get_opacity_tool(SPDesktop *desktop, Glib::ustring const &tool, bool is_fill); -guint32 sp_desktop_get_color_tool(SPDesktop *desktop, Glib::ustring const &tool, bool is_fill, bool* has_color = nullptr); -double sp_desktop_get_font_size_tool (SPDesktop *desktop); -void sp_desktop_apply_style_tool(SPDesktop *desktop, Inkscape::XML::Node *repr, Glib::ustring const &tool, bool with_text); +guint32 sp_desktop_get_color_tool(SPDesktop *desktop, Glib::ustring const &tool, bool is_fill, + bool *has_color = nullptr); +double sp_desktop_get_font_size_tool(SPDesktop *desktop); +void sp_desktop_apply_style_tool(SPDesktop *desktop, Inkscape::XML::Node *repr, Glib::ustring const &tool, + bool with_text); -gdouble stroke_average_width (const std::vector &objects); +gdouble stroke_average_width(const std::vector &objects); -int objects_query_fillstroke (const std::vector &objects, SPStyle *style_res, bool const isfill); -int objects_query_fontnumbers (const std::vector &objects, SPStyle *style_res); -int objects_query_fontstyle (const std::vector &objects, SPStyle *style_res); -int objects_query_fontfamily (const std::vector &objects, SPStyle *style_res); -int objects_query_fontvariants (const std::vector &objects, SPStyle *style_res); -int objects_query_opacity (const std::vector &objects, SPStyle *style_res); -int objects_query_strokewidth (const std::vector &objects, SPStyle *style_res); -int objects_query_miterlimit (const std::vector &objects, SPStyle *style_res); -int objects_query_strokecap (const std::vector &objects, SPStyle *style_res); -int objects_query_strokejoin (const std::vector &objects, SPStyle *style_res); +int objects_query_fillstroke(const std::vector &objects, SPStyle *style_res, bool const isfill); +int objects_query_fontnumbers(const std::vector &objects, SPStyle *style_res); +int objects_query_fontstyle(const std::vector &objects, SPStyle *style_res); +int objects_query_fontfamily(const std::vector &objects, SPStyle *style_res); +int objects_query_fontvariants(const std::vector &objects, SPStyle *style_res); +int objects_query_opacity(const std::vector &objects, SPStyle *style_res); +int objects_query_strokewidth(const std::vector &objects, SPStyle *style_res); +int objects_query_miterlimit(const std::vector &objects, SPStyle *style_res); +int objects_query_strokecap(const std::vector &objects, SPStyle *style_res); +int objects_query_strokejoin(const std::vector &objects, SPStyle *style_res); -int objects_query_blur (const std::vector &objects, SPStyle *style_res); -int objects_query_blend (const std::vector &objects, SPStyle *style_res); +int objects_query_blur(const std::vector &objects, SPStyle *style_res); +int objects_query_blend(const std::vector &objects, SPStyle *style_res); -int sp_desktop_query_style_from_list (const std::vector &list, SPStyle *style, int property); +int sp_desktop_query_style_from_list(const std::vector &list, SPStyle *style, int property); int sp_desktop_query_style(SPDesktop *desktop, SPStyle *style, int property); -bool sp_desktop_query_style_all (SPDesktop *desktop, SPStyle *query); +bool sp_desktop_query_style_all(SPDesktop *desktop, SPStyle *query); #endif // SEEN_SP_DESKTOP_STYLE_H - /* Local Variables: mode:c++ diff --git a/src/desktop.cpp b/src/desktop.cpp index 0d5613e365aa7fc3cc3c49784688a120acd7ef77..ff18767ab255edf9b7d6622f3c6d799c08a7c022 100644 --- a/src/desktop.cpp +++ b/src/desktop.cpp @@ -22,25 +22,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include <2geom/transforms.h> +#include "desktop.h" + #include <2geom/rect.h> +#include <2geom/transforms.h> +#include #include -#include "desktop.h" - #include "color.h" #include "desktop-events.h" #include "desktop-style.h" #include "device-manager.h" -#include "document-undo.h" -#include "event-log.h" -#include "inkscape-window.h" -#include "layer-fns.h" -#include "layer-manager.h" -#include "message-context.h" -#include "message-stack.h" - #include "display/canvas-arena.h" #include "display/canvas-debug.h" #include "display/canvas-grid.h" @@ -52,42 +44,48 @@ #include "display/sodipodi-ctrlrect.h" #include "display/sp-canvas-group.h" #include "display/sp-canvas-util.h" - +#include "document-undo.h" +#include "event-log.h" #include "helper/action-context.h" #include "helper/action.h" //sp_action_perform - +#include "inkscape-window.h" #include "io/resource-manager.h" - +#include "layer-fns.h" +#include "layer-manager.h" +#include "message-context.h" +#include "message-stack.h" #include "object/sp-namedview.h" #include "object/sp-root.h" - #include "ui/desktop/menubar.h" #include "ui/dialog/dialog-manager.h" #include "ui/interface.h" // Only for getLayoutPrefPath #include "ui/tool-factory.h" -#include "ui/tools/tool-base.h" #include "ui/tools/box3d-tool.h" #include "ui/tools/select-tool.h" +#include "ui/tools/tool-base.h" #include "ui/widget/canvas.h" #include "ui/widget/dock.h" - #include "widgets/desktop-widget.h" // TODO those includes are only for node tool quick zoom. Remove them after fixing it. -#include "ui/tools/node-tool.h" #include "ui/tool/control-point-selection.h" +#include "ui/tools/node-tool.h" -namespace Inkscape { namespace XML { class Node; }} +namespace Inkscape { +namespace XML { +class Node; +} +} // namespace Inkscape // Callback declarations -static void _onSelectionChanged (Inkscape::Selection *selection, SPDesktop *desktop); -static gint _arena_handler (SPCanvasArena *arena, Inkscape::DrawingItem *ai, GdkEvent *event, SPDesktop *desktop); +static void _onSelectionChanged(Inkscape::Selection *selection, SPDesktop *desktop); +static gint _arena_handler(SPCanvasArena *arena, Inkscape::DrawingItem *ai, GdkEvent *event, SPDesktop *desktop); static void _layer_activated(SPObject *layer, SPDesktop *desktop); static void _layer_deactivated(SPObject *layer, SPDesktop *desktop); static void _layer_hierarchy_changed(SPObject *top, SPObject *bottom, SPDesktop *desktop); -static void _reconstruction_start(SPDesktop * desktop); -static void _reconstruction_finish(SPDesktop * desktop); -static void _namedview_modified (SPObject *obj, guint flags, SPDesktop *desktop); +static void _reconstruction_start(SPDesktop *desktop); +static void _reconstruction_finish(SPDesktop *desktop); +static void _namedview_modified(SPObject *obj, guint flags, SPDesktop *desktop); static gdouble _pinch_begin_zoom = 1.; @@ -159,11 +157,10 @@ SPDesktop::SPDesktop() layers->_layer_activated_signal.connect(sigc::bind(sigc::ptr_fun(_layer_activated), this)); layers->_layer_deactivated_signal.connect(sigc::bind(sigc::ptr_fun(_layer_deactivated), this)); layers->_layer_changed_signal.connect(sigc::bind(sigc::ptr_fun(_layer_hierarchy_changed), this)); - selection = Inkscape::GC::release( new Inkscape::Selection(layers, this) ); + selection = Inkscape::GC::release(new Inkscape::Selection(layers, this)); } -void -SPDesktop::init (SPNamedView *nv, Inkscape::UI::Widget::Canvas *acanvas, SPDesktopWidget *widget) +void SPDesktop::init(SPNamedView *nv, Inkscape::UI::Widget::Canvas *acanvas, SPDesktopWidget *widget) { namedview = nv; canvas = acanvas; @@ -210,40 +207,40 @@ SPDesktop::init (SPNamedView *nv, Inkscape::UI::Widget::Canvas *acanvas, SPDeskt layers->setDisplayKey(dkey); /* Connect document */ - setDocument (document); + setDocument(document); number = namedview->getViewCount(); - /* Setup Canvas */ canvas->set_data("SPDesktop", this); // HORRID! Used by sp_dt_guide_event. SPCanvasGroup *root = canvas->get_canvas_item_root(); /* Setup administrative layers */ - acetate = sp_canvas_item_new (root, GNOME_TYPE_CANVAS_ACETATE, nullptr); - g_signal_connect (G_OBJECT (acetate), "event", G_CALLBACK (sp_desktop_root_handler), this); - main = (SPCanvasGroup *) sp_canvas_item_new (root, SP_TYPE_CANVAS_GROUP, nullptr); + acetate = sp_canvas_item_new(root, GNOME_TYPE_CANVAS_ACETATE, nullptr); + g_signal_connect(G_OBJECT(acetate), "event", G_CALLBACK(sp_desktop_root_handler), this); + main = (SPCanvasGroup *)sp_canvas_item_new(root, SP_TYPE_CANVAS_GROUP, nullptr); SP_CANVAS_ITEM(main)->name = "CanvasGroup:main"; - g_signal_connect (G_OBJECT (main), "event", G_CALLBACK (sp_desktop_root_handler), this); + g_signal_connect(G_OBJECT(main), "event", G_CALLBACK(sp_desktop_root_handler), this); /* This is the background the page sits on. */ canvas->set_background_color(0xffffff00); - page = sp_canvas_item_new (main, SP_TYPE_CTRLRECT, nullptr); - ((CtrlRect *) page)->setColor(0x00000000, FALSE, 0x00000000); - page_border = sp_canvas_item_new (main, SP_TYPE_CTRLRECT, nullptr); + page = sp_canvas_item_new(main, SP_TYPE_CTRLRECT, nullptr); + ((CtrlRect *)page)->setColor(0x00000000, FALSE, 0x00000000); + page_border = sp_canvas_item_new(main, SP_TYPE_CTRLRECT, nullptr); - drawing = sp_canvas_item_new (main, SP_TYPE_CANVAS_ARENA, nullptr); - g_signal_connect (G_OBJECT (drawing), "arena_event", G_CALLBACK (_arena_handler), this); + drawing = sp_canvas_item_new(main, SP_TYPE_CANVAS_ARENA, nullptr); + g_signal_connect(G_OBJECT(drawing), "arena_event", G_CALLBACK(_arena_handler), this); // pinch zoom zoomgesture = gtk_gesture_zoom_new(GTK_WIDGET(canvas->gobj())); - gtk_event_controller_set_propagation_phase (GTK_EVENT_CONTROLLER (zoomgesture), GTK_PHASE_CAPTURE); + gtk_event_controller_set_propagation_phase(GTK_EVENT_CONTROLLER(zoomgesture), GTK_PHASE_CAPTURE); g_signal_connect(zoomgesture, "begin", G_CALLBACK(_pinch_begin_handler), this); g_signal_connect(zoomgesture, "scale-changed", G_CALLBACK(_pinch_scale_changed_handler), this); - SP_CANVAS_ARENA (drawing)->drawing.delta = prefs->getDouble("/options/cursortolerance/value", 1.0); // default is 1 px + SP_CANVAS_ARENA(drawing)->drawing.delta = + prefs->getDouble("/options/cursortolerance/value", 1.0); // default is 1 px if (prefs->getBool("/options/startmode/outline")) { // Start in outline mode @@ -263,17 +260,17 @@ SPDesktop::init (SPNamedView *nv, Inkscape::UI::Widget::Canvas *acanvas, SPDeskt // will not work (the snap indicator is on top of the node handler; is the snapindicator // being selected? or does it intercept some of the events that should have gone to the // node handler? see bug https://bugs.launchpad.net/inkscape/+bug/414142) - gridgroup = (SPCanvasGroup *) sp_canvas_item_new (main, SP_TYPE_CANVAS_GROUP, nullptr); - guides = (SPCanvasGroup *) sp_canvas_item_new (main, SP_TYPE_CANVAS_GROUP, nullptr); - sketch = (SPCanvasGroup *) sp_canvas_item_new (main, SP_TYPE_CANVAS_GROUP, nullptr); - tempgroup = (SPCanvasGroup *) sp_canvas_item_new (main, SP_TYPE_CANVAS_GROUP, nullptr); - controls = (SPCanvasGroup *) sp_canvas_item_new (main, SP_TYPE_CANVAS_GROUP, nullptr); + gridgroup = (SPCanvasGroup *)sp_canvas_item_new(main, SP_TYPE_CANVAS_GROUP, nullptr); + guides = (SPCanvasGroup *)sp_canvas_item_new(main, SP_TYPE_CANVAS_GROUP, nullptr); + sketch = (SPCanvasGroup *)sp_canvas_item_new(main, SP_TYPE_CANVAS_GROUP, nullptr); + tempgroup = (SPCanvasGroup *)sp_canvas_item_new(main, SP_TYPE_CANVAS_GROUP, nullptr); + controls = (SPCanvasGroup *)sp_canvas_item_new(main, SP_TYPE_CANVAS_GROUP, nullptr); SP_CANVAS_ITEM(gridgroup)->name = "CanvasGroup:Grid"; - SP_CANVAS_ITEM(guides)->name = "CanvasGroup:Guides"; - SP_CANVAS_ITEM(sketch)->name = "CanvasGroup:Sketch"; + SP_CANVAS_ITEM(guides)->name = "CanvasGroup:Guides"; + SP_CANVAS_ITEM(sketch)->name = "CanvasGroup:Sketch"; SP_CANVAS_ITEM(tempgroup)->name = "CanvasGroup:Temp"; - SP_CANVAS_ITEM(controls)->name = "CanvasGroup:Controls"; + SP_CANVAS_ITEM(controls)->name = "CanvasGroup:Controls"; // Set the select tool as the active tool. setEventContext("/tools/select"); @@ -294,33 +291,29 @@ SPDesktop::init (SPNamedView *nv, Inkscape::UI::Widget::Canvas *acanvas, SPDeskt 0 is used, then the constructor for a shadow is not initialized. */ - if ( namedview->pageshadow != 0 && namedview->showpageshadow ) { + if (namedview->pageshadow != 0 && namedview->showpageshadow) { SP_CTRLRECT(page_border)->setShadow(namedview->pageshadow, 0x3f3f3fff); } - /* Connect event for page resize */ - sp_canvas_item_affine_absolute (SP_CANVAS_ITEM (drawing), doc2dt()); + sp_canvas_item_affine_absolute(SP_CANVAS_ITEM(drawing), doc2dt()); - _modified_connection = - namedview->connectModified(sigc::bind<2>(sigc::ptr_fun(&_namedview_modified), this)); + _modified_connection = namedview->connectModified(sigc::bind<2>(sigc::ptr_fun(&_namedview_modified), this)); - Inkscape::DrawingItem *ai = document->getRoot()->invoke_show( - SP_CANVAS_ARENA (drawing)->drawing, - dkey, - SP_ITEM_SHOW_DISPLAY); + Inkscape::DrawingItem *ai = + document->getRoot()->invoke_show(SP_CANVAS_ARENA(drawing)->drawing, dkey, SP_ITEM_SHOW_DISPLAY); if (ai) { - SP_CANVAS_ARENA (drawing)->drawing.root()->prependChild(ai); + SP_CANVAS_ARENA(drawing)->drawing.root()->prependChild(ai); } namedview->show(this); /* Ugly hack */ - activate_guides (true); + activate_guides(true); /* Ugly hack */ - _namedview_modified (namedview, SP_OBJECT_MODIFIED_FLAG, this); + _namedview_modified(namedview, SP_OBJECT_MODIFIED_FLAG, this); -/* Set up notification of rebuilding the document, this allows - for saving object related settings in the document. */ + /* Set up notification of rebuilding the document, this allows + for saving object related settings in the document. */ _reconstruction_start_connection = document->connectReconstructionStart(sigc::bind(sigc::ptr_fun(_reconstruction_start), this)); _reconstruction_finish_connection = @@ -330,44 +323,23 @@ SPDesktop::init (SPNamedView *nv, Inkscape::UI::Widget::Canvas *acanvas, SPDeskt // ? // sp_active_desktop_set (desktop); - _activate_connection = _activate_signal.connect( - sigc::bind( - sigc::ptr_fun(_onActivate), - this - ) - ); - _deactivate_connection = _deactivate_signal.connect( - sigc::bind( - sigc::ptr_fun(_onDeactivate), - this - ) - ); - - _sel_modified_connection = selection->connectModified( - sigc::bind( - sigc::ptr_fun(&_onSelectionModified), - this - ) - ); - _sel_changed_connection = selection->connectChanged( - sigc::bind( - sigc::ptr_fun(&_onSelectionChanged), - this - ) - ); + _activate_connection = _activate_signal.connect(sigc::bind(sigc::ptr_fun(_onActivate), this)); + _deactivate_connection = _deactivate_signal.connect(sigc::bind(sigc::ptr_fun(_onDeactivate), this)); + _sel_modified_connection = selection->connectModified(sigc::bind(sigc::ptr_fun(&_onSelectionModified), this)); + _sel_changed_connection = selection->connectChanged(sigc::bind(sigc::ptr_fun(&_onSelectionChanged), this)); /* setup LayerManager */ // (Setting up after the connections are all in place, as it may use some of them) - layer_manager = new Inkscape::LayerManager( this ); + layer_manager = new Inkscape::LayerManager(this); showGrids(namedview->grids_visible, false); - temporary_item_list = new Inkscape::Display::TemporaryItemList( this ); - snapindicator = new Inkscape::Display::SnapIndicator ( this ); + temporary_item_list = new Inkscape::Display::TemporaryItemList(this); + snapindicator = new Inkscape::Display::SnapIndicator(this); - canvas_rotate = sp_canvas_item_new (root, SP_TYPE_CANVAS_ROTATE, nullptr); - sp_canvas_item_hide( canvas_rotate ); + canvas_rotate = sp_canvas_item_new(root, SP_TYPE_CANVAS_ROTATE, nullptr); + sp_canvas_item_hide(canvas_rotate); // canvas_debug = sp_canvas_item_new (main, SP_TYPE_CANVAS_DEBUG, NULL); } @@ -401,9 +373,9 @@ void SPDesktop::destroy() _reconstruction_start_connection.disconnect(); _reconstruction_finish_connection.disconnect(); - g_signal_handlers_disconnect_by_func(G_OBJECT (acetate), (gpointer) G_CALLBACK(sp_desktop_root_handler), this); - g_signal_handlers_disconnect_by_func(G_OBJECT (main), (gpointer) G_CALLBACK(sp_desktop_root_handler), this); - g_signal_handlers_disconnect_by_func(G_OBJECT (drawing), (gpointer) G_CALLBACK(_arena_handler), this); + g_signal_handlers_disconnect_by_func(G_OBJECT(acetate), (gpointer)G_CALLBACK(sp_desktop_root_handler), this); + g_signal_handlers_disconnect_by_func(G_OBJECT(main), (gpointer)G_CALLBACK(sp_desktop_root_handler), this); + g_signal_handlers_disconnect_by_func(G_OBJECT(drawing), (gpointer)G_CALLBACK(_arena_handler), this); if (zoomgesture) { g_signal_handlers_disconnect_by_data(zoomgesture, this); @@ -429,72 +401,81 @@ void SPDesktop::destroy() _dlg_mgr_owned = nullptr; } -SPDesktop::~SPDesktop() -= default; - +SPDesktop::~SPDesktop() = default; -Inkscape::UI::Tools::ToolBase* SPDesktop::getEventContext() const { - return event_context; +Inkscape::UI::Tools::ToolBase *SPDesktop::getEventContext() const +{ + return event_context; } -Inkscape::Selection* SPDesktop::getSelection() const { - return selection; +Inkscape::Selection *SPDesktop::getSelection() const +{ + return selection; } -SPDocument* SPDesktop::getDocument() const { - return doc(); +SPDocument *SPDesktop::getDocument() const +{ + return doc(); } -Inkscape::UI::Widget::Canvas* SPDesktop::getCanvas() const { - return canvas; +Inkscape::UI::Widget::Canvas *SPDesktop::getCanvas() const +{ + return canvas; } -SPCanvasItem* SPDesktop::getAcetate() const { - return acetate; +SPCanvasItem *SPDesktop::getAcetate() const +{ + return acetate; } -SPCanvasGroup* SPDesktop::getMain() const { - return main; +SPCanvasGroup *SPDesktop::getMain() const +{ + return main; } -SPCanvasGroup* SPDesktop::getGridGroup() const { - return gridgroup; +SPCanvasGroup *SPDesktop::getGridGroup() const +{ + return gridgroup; } -SPCanvasGroup* SPDesktop::getGuides() const { - return guides; +SPCanvasGroup *SPDesktop::getGuides() const +{ + return guides; } -SPCanvasItem* SPDesktop::getDrawing() const { - return drawing; +SPCanvasItem *SPDesktop::getDrawing() const +{ + return drawing; } -SPCanvasGroup* SPDesktop::getSketch() const { - return sketch; +SPCanvasGroup *SPDesktop::getSketch() const +{ + return sketch; } -SPCanvasGroup* SPDesktop::getControls() const { - return controls; +SPCanvasGroup *SPDesktop::getControls() const +{ + return controls; } -SPCanvasGroup* SPDesktop::getTempGroup() const { - return tempgroup; +SPCanvasGroup *SPDesktop::getTempGroup() const +{ + return tempgroup; } -Inkscape::MessageStack* SPDesktop::getMessageStack() const { - return messageStack().get(); +Inkscape::MessageStack *SPDesktop::getMessageStack() const +{ + return messageStack().get(); } -SPNamedView* SPDesktop::getNamedView() const { - return namedview; +SPNamedView *SPDesktop::getNamedView() const +{ + return namedview; } - - //-------------------------------------------------------------------- /* Public methods */ - /* These methods help for temporarily showing things on-canvas. * The *only* valid use of the TemporaryItem* that you get from add_temporary_canvasitem * is when you want to prematurely remove the item from the canvas, by calling @@ -506,10 +487,11 @@ SPNamedView* SPDesktop::getNamedView() const { * It is perfectly safe to ignore the returned pointer: the object is deleted by itself, so don't delete it elsewhere! * The *only* valid use of the returned TemporaryItem* is as argument for SPDesktop::remove_temporary_canvasitem, * because the object might be deleted already without you knowing it. - * move_to_bottom = true by default so the item does not interfere with handling of other items on the canvas like nodes. + * move_to_bottom = true by default so the item does not interfere with handling of other items on the canvas like + * nodes. */ -Inkscape::Display::TemporaryItem * -SPDesktop::add_temporary_canvasitem (SPCanvasItem *item, guint lifetime, bool move_to_bottom) +Inkscape::Display::TemporaryItem *SPDesktop::add_temporary_canvasitem(SPCanvasItem *item, guint lifetime, + bool move_to_bottom) { if (move_to_bottom) { sp_canvas_item_move_to_z(item, 0); @@ -519,22 +501,24 @@ SPDesktop::add_temporary_canvasitem (SPCanvasItem *item, guint lifetime, bool mo } /** It is perfectly safe to call this function while the object has already been deleted due to a timeout. -*/ -void -SPDesktop::remove_temporary_canvasitem (Inkscape::Display::TemporaryItem * tempitem) + */ +void SPDesktop::remove_temporary_canvasitem(Inkscape::Display::TemporaryItem *tempitem) { - // check for non-null temporary_item_list, because during destruction of desktop, some destructor might try to access this list! + // check for non-null temporary_item_list, because during destruction of desktop, some destructor might try to + // access this list! if (tempitem && temporary_item_list) { temporary_item_list->delete_item(tempitem); } } -void SPDesktop::redrawDesktop() { - sp_canvas_item_affine_absolute (SP_CANVAS_ITEM (main), _current_affine.d2w()); // redraw +void SPDesktop::redrawDesktop() +{ + sp_canvas_item_affine_absolute(SP_CANVAS_ITEM(main), _current_affine.d2w()); // redraw } // THIS SHOULD BE A CANVAS FUNCTION -void SPDesktop::_setDisplayMode(Inkscape::RenderMode mode) { +void SPDesktop::_setDisplayMode(Inkscape::RenderMode mode) +{ // Why set three places? canvas->set_render_mode(mode); _display_mode = mode; @@ -547,73 +531,71 @@ void SPDesktop::_setDisplayMode(Inkscape::RenderMode mode) { toggleXRay(); } } - _widget->updateTitle( this->getDocument()->getDocumentName() ); + _widget->updateTitle(this->getDocument()->getDocumentName()); } // THIS SHOULD BE A CANVAS FUNCTION -void SPDesktop::_setDisplayColorMode(Inkscape::ColorMode mode) { +void SPDesktop::_setDisplayColorMode(Inkscape::ColorMode mode) +{ // reload grayscale matrix from prefs if (mode == Inkscape::COLORMODE_GRAYSCALE) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - gdouble r = prefs->getDoubleLimited("/options/rendering/grayscale/red-factor",0.21,0.,1.); - gdouble g = prefs->getDoubleLimited("/options/rendering/grayscale/green-factor",0.72,0.,1.); - gdouble b = prefs->getDoubleLimited("/options/rendering/grayscale/blue-factor",0.072,0.,1.); - gdouble grayscale_value_matrix[20] = { r, g, b, 0, 0, - r, g, b, 0, 0, - r, g, b, 0, 0, - 0, 0, 0, 1, 0 }; + gdouble r = prefs->getDoubleLimited("/options/rendering/grayscale/red-factor", 0.21, 0., 1.); + gdouble g = prefs->getDoubleLimited("/options/rendering/grayscale/green-factor", 0.72, 0., 1.); + gdouble b = prefs->getDoubleLimited("/options/rendering/grayscale/blue-factor", 0.072, 0., 1.); + gdouble grayscale_value_matrix[20] = {r, g, b, 0, 0, r, g, b, 0, 0, r, g, b, 0, 0, 0, 0, 0, 1, 0}; // g_message("%g",grayscale_value_matrix[0]); - SP_CANVAS_ARENA (drawing)->drawing.setGrayscaleMatrix(grayscale_value_matrix); + SP_CANVAS_ARENA(drawing)->drawing.setGrayscaleMatrix(grayscale_value_matrix); } // Why set three places? FIXME - SP_CANVAS_ARENA (drawing)->drawing.setColorMode(mode); + SP_CANVAS_ARENA(drawing)->drawing.setColorMode(mode); canvas->set_color_mode(mode); _display_color_mode = mode; redrawDesktop(); - _widget->updateTitle( this->getDocument()->getDocumentName() ); + _widget->updateTitle(this->getDocument()->getDocumentName()); } bool SPDesktop::displayModeToggle() { Inkscape::Verb *verb = Inkscape::Verb::get(SP_VERB_VIEW_MODE_NORMAL); switch (_display_mode) { - case Inkscape::RENDERMODE_NORMAL: - _setDisplayMode(Inkscape::RENDERMODE_NO_FILTERS); - verb = Inkscape::Verb::get(SP_VERB_VIEW_MODE_NO_FILTERS); - if (verb) { - _menu_update.emit(verb->get_code(), setDisplayModeNoFilters()); - } - break; - case Inkscape::RENDERMODE_NO_FILTERS: - _setDisplayMode(Inkscape::RENDERMODE_OUTLINE); - verb = Inkscape::Verb::get(SP_VERB_VIEW_MODE_OUTLINE); - if (verb) { - _menu_update.emit(verb->get_code(), setDisplayModeOutline()); - } + case Inkscape::RENDERMODE_NORMAL: + _setDisplayMode(Inkscape::RENDERMODE_NO_FILTERS); + verb = Inkscape::Verb::get(SP_VERB_VIEW_MODE_NO_FILTERS); + if (verb) { + _menu_update.emit(verb->get_code(), setDisplayModeNoFilters()); + } + break; + case Inkscape::RENDERMODE_NO_FILTERS: + _setDisplayMode(Inkscape::RENDERMODE_OUTLINE); + verb = Inkscape::Verb::get(SP_VERB_VIEW_MODE_OUTLINE); + if (verb) { + _menu_update.emit(verb->get_code(), setDisplayModeOutline()); + } - break; - case Inkscape::RENDERMODE_OUTLINE: - _setDisplayMode(Inkscape::RENDERMODE_VISIBLE_HAIRLINES); - verb = Inkscape::Verb::get(SP_VERB_VIEW_MODE_VISIBLE_HAIRLINES); - if (verb) { - _menu_update.emit(verb->get_code(), setDisplayModeVisibleHairlines()); - } - break; - case Inkscape::RENDERMODE_VISIBLE_HAIRLINES: - _setDisplayMode(Inkscape::RENDERMODE_NORMAL); - verb = Inkscape::Verb::get(SP_VERB_VIEW_MODE_NORMAL); - if (verb) { - _menu_update.emit(verb->get_code(), setDisplayModeNormal()); - } - break; - default: - _setDisplayMode(Inkscape::RENDERMODE_NORMAL); - verb = Inkscape::Verb::get(SP_VERB_VIEW_MODE_NORMAL); - if (verb) { - _menu_update.emit(verb->get_code(), setDisplayModeNormal()); - } + break; + case Inkscape::RENDERMODE_OUTLINE: + _setDisplayMode(Inkscape::RENDERMODE_VISIBLE_HAIRLINES); + verb = Inkscape::Verb::get(SP_VERB_VIEW_MODE_VISIBLE_HAIRLINES); + if (verb) { + _menu_update.emit(verb->get_code(), setDisplayModeVisibleHairlines()); + } + break; + case Inkscape::RENDERMODE_VISIBLE_HAIRLINES: + _setDisplayMode(Inkscape::RENDERMODE_NORMAL); + verb = Inkscape::Verb::get(SP_VERB_VIEW_MODE_NORMAL); + if (verb) { + _menu_update.emit(verb->get_code(), setDisplayModeNormal()); + } + break; + default: + _setDisplayMode(Inkscape::RENDERMODE_NORMAL); + verb = Inkscape::Verb::get(SP_VERB_VIEW_MODE_NORMAL); + if (verb) { + _menu_update.emit(verb->get_code(), setDisplayModeNormal()); + } } return true; } @@ -621,25 +603,25 @@ bool SPDesktop::displayColorModeToggle() { Inkscape::Verb *verb = Inkscape::Verb::get(SP_VERB_VIEW_COLOR_MODE_NORMAL); switch (_display_color_mode) { - case Inkscape::COLORMODE_NORMAL: - _setDisplayColorMode(Inkscape::COLORMODE_GRAYSCALE); - verb = Inkscape::Verb::get(SP_VERB_VIEW_COLOR_MODE_GRAYSCALE); - if (verb) { - _menu_update.emit(verb->get_code(), setDisplayColorModeGrayscale()); - } - break; - case Inkscape::COLORMODE_GRAYSCALE: - _setDisplayColorMode(Inkscape::COLORMODE_NORMAL); - if (verb) { - _menu_update.emit(verb->get_code(), setDisplayColorModeNormal()); - } - break; -// case Inkscape::COLORMODE_PRINT_COLORS_PREVIEW: - default: - _setDisplayColorMode(Inkscape::COLORMODE_NORMAL); - if (verb) { - _menu_update.emit(verb->get_code(), setDisplayColorModeNormal()); - } + case Inkscape::COLORMODE_NORMAL: + _setDisplayColorMode(Inkscape::COLORMODE_GRAYSCALE); + verb = Inkscape::Verb::get(SP_VERB_VIEW_COLOR_MODE_GRAYSCALE); + if (verb) { + _menu_update.emit(verb->get_code(), setDisplayColorModeGrayscale()); + } + break; + case Inkscape::COLORMODE_GRAYSCALE: + _setDisplayColorMode(Inkscape::COLORMODE_NORMAL); + if (verb) { + _menu_update.emit(verb->get_code(), setDisplayColorModeNormal()); + } + break; + // case Inkscape::COLORMODE_PRINT_COLORS_PREVIEW: + default: + _setDisplayColorMode(Inkscape::COLORMODE_NORMAL); + if (verb) { + _menu_update.emit(verb->get_code(), setDisplayColorModeNormal()); + } } return true; } @@ -688,7 +670,7 @@ bool SPDesktop::isLayer(SPObject *object) const /** * True if desktop viewport intersects \a item's bbox. */ -bool SPDesktop::isWithinViewport (SPItem *item) const +bool SPDesktop::isWithinViewport(SPItem *item) const { auto const viewport = get_display_area(); Geom::OptRect const bbox = item->desktopVisualBounds(); @@ -700,15 +682,15 @@ bool SPDesktop::isWithinViewport (SPItem *item) const } /// -bool SPDesktop::itemIsHidden(SPItem const *item) const { +bool SPDesktop::itemIsHidden(SPItem const *item) const +{ return item->isHidden(this->dkey); } /** * Set activate property of desktop; emit signal if changed. */ -void -SPDesktop::set_active (bool new_active) +void SPDesktop::set_active(bool new_active) { if (new_active != _active) { _active = new_active; @@ -723,8 +705,7 @@ SPDesktop::set_active (bool new_active) /** * Set activate status of current desktop's named view. */ -void -SPDesktop::activate_guides(bool activate) +void SPDesktop::activate_guides(bool activate) { guides_active = activate; namedview->activateGuides(this, activate); @@ -733,15 +714,14 @@ SPDesktop::activate_guides(bool activate) /** * Make desktop switch documents. */ -void -SPDesktop::change_document (SPDocument *theDocument) +void SPDesktop::change_document(SPDocument *theDocument) { - g_return_if_fail (theDocument != nullptr); + g_return_if_fail(theDocument != nullptr); /* unselect everything before switching documents */ selection->clear(); - setDocument (theDocument); + setDocument(theDocument); /* update the rulers, connect the desktop widget's signal to the new namedview etc. (this can probably be done in a better way) */ @@ -756,15 +736,15 @@ SPDesktop::change_document (SPDocument *theDocument) std::cerr << "SPDesktop::change_document: failed to get desktop widget!" << std::endl; } - _namedview_modified (namedview, SP_OBJECT_MODIFIED_FLAG, this); - _document_replaced_signal.emit (this, theDocument); + _namedview_modified(namedview, SP_OBJECT_MODIFIED_FLAG, this); + _document_replaced_signal.emit(this, theDocument); } /** * Replaces the currently active tool with a new one. Pass the empty string to * unset and free the current tool. */ -void SPDesktop::setEventContext(const std::string& toolName) +void SPDesktop::setEventContext(const std::string &toolName) { // Tool should be able to be replaced with itself. See commit 29df5ca05d if (event_context) { @@ -777,7 +757,8 @@ void SPDesktop::setEventContext(const std::string& toolName) } else { event_context = ToolFactory::createObject(toolName); event_context->setDesktop(this); - event_context->message_context = std::unique_ptr(new Inkscape::MessageContext(this->messageStack())); + event_context->message_context = + std::unique_ptr(new Inkscape::MessageContext(this->messageStack())); event_context->setup(); // Make sure no delayed snapping events are carried over after switching tools @@ -792,21 +773,22 @@ void SPDesktop::setEventContext(const std::string& toolName) /** * Sets the coordinate status to a given point */ -void -SPDesktop::set_coordinate_status (Geom::Point p) { +void SPDesktop::set_coordinate_status(Geom::Point p) +{ _widget->setCoordinateStatus(p); } -Inkscape::UI::Widget::Dock* SPDesktop::getDock() { - return _widget->getDock(); +Inkscape::UI::Widget::Dock *SPDesktop::getDock() +{ + return _widget->getDock(); } /** * \see SPDocument::getItemFromListAtPointBottom() */ -SPItem *SPDesktop::getItemFromListAtPointBottom(const std::vector &list, Geom::Point const &p) const +SPItem *SPDesktop::getItemFromListAtPointBottom(const std::vector &list, Geom::Point const &p) const { - g_return_val_if_fail (doc() != nullptr, NULL); + g_return_val_if_fail(doc() != nullptr, NULL); return SPDocument::getItemFromListAtPointBottom(dkey, doc()->getRoot(), list, p); } @@ -815,8 +797,8 @@ SPItem *SPDesktop::getItemFromListAtPointBottom(const std::vector &list */ SPItem *SPDesktop::getItemAtPoint(Geom::Point const &p, bool into_groups, SPItem *upto) const { - g_return_val_if_fail (doc() != nullptr, NULL); - return doc()->getItemAtPoint( dkey, p, into_groups, upto); + g_return_val_if_fail(doc() != nullptr, NULL); + return doc()->getItemAtPoint(dkey, p, into_groups, upto); } /** @@ -824,7 +806,7 @@ SPItem *SPDesktop::getItemAtPoint(Geom::Point const &p, bool into_groups, SPItem */ SPItem *SPDesktop::getGroupAtPoint(Geom::Point const &p) const { - g_return_val_if_fail (doc() != nullptr, NULL); + g_return_val_if_fail(doc() != nullptr, NULL); return doc()->getGroupAtPoint(dkey, p); } @@ -847,13 +829,11 @@ Geom::Point SPDesktop::point(bool outside_canvas) const return (r0 + r1) / 2.0; } - /** * Revert back to previous transform if possible. Note: current transform is * always at front of stack. */ -void -SPDesktop::prev_transform() +void SPDesktop::prev_transform() { if (transforms_past.empty()) { std::cerr << "SPDesktop::prev_transform: current transform missing!" << std::endl; @@ -866,18 +846,16 @@ SPDesktop::prev_transform() } // Push current transform into future transforms list. - transforms_future.push_front( _current_affine ); + transforms_future.push_front(_current_affine); // Remove the current transform from the past transforms list. transforms_past.pop_front(); // restore previous transform _current_affine = transforms_past.front(); - set_display_area (false); - + set_display_area(false); } - /** * Set transform to next in list. */ @@ -890,38 +868,34 @@ void SPDesktop::next_transform() // restore next transform _current_affine = transforms_future.front(); - set_display_area (false); + set_display_area(false); // remove the just-used transform from the future transforms list transforms_future.pop_front(); // push current transform into past transforms list - transforms_past.push_front( _current_affine ); + transforms_past.push_front(_current_affine); } - /** * Clear transform lists. */ -void -SPDesktop::clear_transform_history() +void SPDesktop::clear_transform_history() { transforms_past.clear(); transforms_future.clear(); } - /** * Does all the dirty work in setting the display area. * _current_affine must already be full updated (including offset). * log: if true, save transform in transform stack for reuse. */ -void -SPDesktop::set_display_area (bool log) +void SPDesktop::set_display_area(bool log) { // Save the transform if (log) { - transforms_past.push_front( _current_affine ); + transforms_past.push_front(_current_affine); // if we do a logged transform, our transform-forward list is invalidated, so delete it transforms_future.clear(); } @@ -936,7 +910,7 @@ SPDesktop::set_display_area (bool log) /* Update perspective lines if we are in the 3D box tool (so that infinite ones are shown * correctly) */ if (SP_IS_BOX3D_CONTEXT(event_context)) { - SP_BOX3D_CONTEXT(event_context)->_vpdrag->updateLines(); + SP_BOX3D_CONTEXT(event_context)->_vpdrag->updateLines(); } // Update GUI (TODO: should be handled by CanvasGrid). @@ -945,57 +919,52 @@ SPDesktop::set_display_area (bool log) _widget->update_zoom(); _widget->update_rotation(); - signal_zoom_changed.emit(_current_affine.getZoom()); // Observed by path-manipulator to update arrows. + signal_zoom_changed.emit(_current_affine.getZoom()); // Observed by path-manipulator to update arrows. } - /** * Map the drawing to the window so that 'c' lies at 'w' where where 'c' * is a point on the canvas and 'w' is position in window in screen pixels. */ -void -SPDesktop::set_display_area (Geom::Point const &c, Geom::Point const &w, bool log) +void SPDesktop::set_display_area(Geom::Point const &c, Geom::Point const &w, bool log) { // The relative offset needed to keep c at w. Geom::Point offset = d2w(c) - w; - _current_affine.addOffset( offset ); - set_display_area( log ); + _current_affine.addOffset(offset); + set_display_area(log); } - /** * Map the center of rectangle 'r' (which specifies a non-rotated region of the * drawing) to lie at the center of the window. The zoom factor is calculated such that * the edges of 'r' closest to 'w' are 'border' length inside of the window (if * there is no rotation). 'r' is in document pixel units, 'border' is in screen pixels. */ -void -SPDesktop::set_display_area( Geom::Rect const &r, double border, bool log) +void SPDesktop::set_display_area(Geom::Rect const &r, double border, bool log) { // Create a rectangle the size of the window aligned with origin. - Geom::Rect w( Geom::Point(), canvas->get_area_world().dimensions() ); + Geom::Rect w(Geom::Point(), canvas->get_area_world().dimensions()); // Shrink window to account for border padding. - w.expandBy( -border ); + w.expandBy(-border); double zoom = 1.0; // Determine which direction limits scale: // if (r.width/w.width > r.height/w.height) then zoom using width. // Avoiding division in test: - if ( r.width()*w.height() > r.height()*w.width() ) { + if (r.width() * w.height() > r.height() * w.width()) { zoom = w.width() / r.width(); } else { zoom = w.height() / r.height(); } zoom = CLAMP(zoom, SP_DESKTOP_ZOOM_MIN, SP_DESKTOP_ZOOM_MAX); - _current_affine.setScale( Geom::Scale(zoom, yaxisdir() * zoom) ); + _current_affine.setScale(Geom::Scale(zoom, yaxisdir() * zoom)); // Zero offset, actual offset calculated later. - _current_affine.setOffset( Geom::Point( 0, 0 ) ); + _current_affine.setOffset(Geom::Point(0, 0)); - set_display_area( r.midpoint(), w.midpoint(), log ); + set_display_area(r.midpoint(), w.midpoint(), log); } - /** * Return canvas viewbox in desktop coordinates */ @@ -1011,53 +980,43 @@ Geom::Parallelogram SPDesktop::get_display_area(bool use_integer_viewbox) const /** * Zoom keeping the point 'c' fixed in the desktop window. */ -void -SPDesktop::zoom_absolute_keep_point (Geom::Point const &c, double zoom) +void SPDesktop::zoom_absolute_keep_point(Geom::Point const &c, double zoom) { - zoom = CLAMP (zoom, SP_DESKTOP_ZOOM_MIN, SP_DESKTOP_ZOOM_MAX); - Geom::Point w = d2w( c ); // Must be before zoom changed. - _current_affine.setScale( Geom::Scale(zoom, yaxisdir() * zoom) ); - set_display_area( c, w ); + zoom = CLAMP(zoom, SP_DESKTOP_ZOOM_MIN, SP_DESKTOP_ZOOM_MAX); + Geom::Point w = d2w(c); // Must be before zoom changed. + _current_affine.setScale(Geom::Scale(zoom, yaxisdir() * zoom)); + set_display_area(c, w); } - -void -SPDesktop::zoom_relative_keep_point (Geom::Point const &c, double zoom) +void SPDesktop::zoom_relative_keep_point(Geom::Point const &c, double zoom) { double new_zoom = _current_affine.getZoom() * zoom; - zoom_absolute_keep_point( c, new_zoom ); + zoom_absolute_keep_point(c, new_zoom); } - /** * Zoom aligning the point 'c' to the center of desktop window. */ -void -SPDesktop::zoom_absolute_center_point (Geom::Point const &c, double zoom) +void SPDesktop::zoom_absolute_center_point(Geom::Point const &c, double zoom) { - zoom = CLAMP (zoom, SP_DESKTOP_ZOOM_MIN, SP_DESKTOP_ZOOM_MAX); - _current_affine.setScale( Geom::Scale(zoom, yaxisdir() * zoom) ); + zoom = CLAMP(zoom, SP_DESKTOP_ZOOM_MIN, SP_DESKTOP_ZOOM_MAX); + _current_affine.setScale(Geom::Scale(zoom, yaxisdir() * zoom)); Geom::Rect viewbox = canvas->get_area_world(); - set_display_area( c, viewbox.midpoint() ); + set_display_area(c, viewbox.midpoint()); } - -void -SPDesktop::zoom_relative_center_point (Geom::Point const &c, double zoom) +void SPDesktop::zoom_relative_center_point(Geom::Point const &c, double zoom) { double new_zoom = _current_affine.getZoom() * zoom; - zoom_absolute_center_point( c, new_zoom ); + zoom_absolute_center_point(c, new_zoom); } - /** * Set display area to origin and current document dimensions. */ -void -SPDesktop::zoom_page() +void SPDesktop::zoom_page() { - Geom::Rect d(Geom::Point(0, 0), - Geom::Point(doc()->getWidth().value("px"), doc()->getHeight().value("px"))); + Geom::Rect d(Geom::Point(0, 0), Geom::Point(doc()->getWidth().value("px"), doc()->getHeight().value("px"))); if (d.minExtent() < 1.0) { return; @@ -1069,8 +1028,7 @@ SPDesktop::zoom_page() /** * Set display area to current document width. */ -void -SPDesktop::zoom_page_width() +void SPDesktop::zoom_page_width() { if (doc()->getWidth().value("px") < 1.0) { return; @@ -1084,16 +1042,14 @@ SPDesktop::zoom_page_width() set_display_area(d, 10); } - /** * Zoom to whole drawing. */ -void -SPDesktop::zoom_drawing() +void SPDesktop::zoom_drawing() { - g_return_if_fail (doc() != nullptr); + g_return_if_fail(doc() != nullptr); SPItem *docitem = doc()->getRoot(); - g_return_if_fail (docitem != nullptr); + g_return_if_fail(docitem != nullptr); docitem->bbox_valid = FALSE; Geom::OptRect d = docitem->desktopVisualBounds(); @@ -1101,23 +1057,21 @@ SPDesktop::zoom_drawing() /* Note that the second condition here indicates that ** there are no items in the drawing. */ - if ( !d || d->minExtent() < 0.1 ) { + if (!d || d->minExtent() < 0.1) { return; } set_display_area(*d, 10); } - /** * Zoom to selection. */ -void -SPDesktop::zoom_selection() +void SPDesktop::zoom_selection() { Geom::OptRect const d = selection->visualBounds(); - if ( !d || d->minExtent() < 0.1 ) { + if (!d || d->minExtent() < 0.1) { return; } @@ -1129,10 +1083,12 @@ SPDesktop::zoom_selection() */ void SPDesktop::zoom_center_page() { - zoom_absolute_center_point(Geom::Point(doc()->getWidth().value("px")/2, doc()->getHeight().value("px")/2), this->current_zoom()); + zoom_absolute_center_point(Geom::Point(doc()->getWidth().value("px") / 2, doc()->getHeight().value("px") / 2), + this->current_zoom()); } -Geom::Point SPDesktop::current_center() const { +Geom::Point SPDesktop::current_center() const +{ return canvas->get_area_world().midpoint() * _current_affine.w2d(); } @@ -1154,7 +1110,7 @@ void SPDesktop::zoom_quick(bool enable) // TODO This needs to migrate into the node tool, but currently the design // of this method is sufficiently wrong to prevent this. if (!zoomed && INK_IS_NODE_TOOL(event_context)) { - Inkscape::UI::Tools::NodeTool *nt = static_cast(event_context); + Inkscape::UI::Tools::NodeTool *nt = static_cast(event_context); if (!nt->_selected_nodes->empty()) { Geom::Rect nodes = *nt->_selected_nodes->bounds(); double area = nodes.area(); @@ -1182,259 +1138,228 @@ void SPDesktop::zoom_quick(bool enable) } } else { _current_affine = _quick_zoom_affine; - set_display_area( false ); + set_display_area(false); } _quick_zoom_enabled = enable; return; } - /** * Tell widget to let zoom widget grab keyboard focus. */ -void -SPDesktop::zoom_grab_focus() +void SPDesktop::zoom_grab_focus() { _widget->letZoomGrabFocus(); } - /** * Set new rotation, keeping the point 'c' fixed in the desktop window. * * @param c Point in desktop coordinates * @param rotate Angle in clockwise direction */ -void -SPDesktop::rotate_absolute_keep_point (Geom::Point const &c, double rotate) +void SPDesktop::rotate_absolute_keep_point(Geom::Point const &c, double rotate) { - Geom::Point w = d2w( c ); // Must be before rotate changed. - _current_affine.setRotate( rotate ); - set_display_area( c, w ); + Geom::Point w = d2w(c); // Must be before rotate changed. + _current_affine.setRotate(rotate); + set_display_area(c, w); } - /** * Rotate keeping the point 'c' fixed in the desktop window. * * @param c Point in desktop coordinates * @param rotate Angle in clockwise direction */ -void -SPDesktop::rotate_relative_keep_point (Geom::Point const &c, double rotate) +void SPDesktop::rotate_relative_keep_point(Geom::Point const &c, double rotate) { - Geom::Point w = d2w( c ); // Must be before rotate changed. - _current_affine.addRotate( rotate ); - set_display_area( c, w ); + Geom::Point w = d2w(c); // Must be before rotate changed. + _current_affine.addRotate(rotate); + set_display_area(c, w); } - /** * Set new rotation, aligning the point 'c' to the center of desktop window. * * @param c Point in desktop coordinates * @param rotate Angle in clockwise direction */ -void -SPDesktop::rotate_absolute_center_point (Geom::Point const &c, double rotate) +void SPDesktop::rotate_absolute_center_point(Geom::Point const &c, double rotate) { - _current_affine.setRotate( rotate ); + _current_affine.setRotate(rotate); Geom::Rect viewbox = canvas->get_area_world(); set_display_area(c, viewbox.midpoint()); } - /** * Rotate aligning the point 'c' to the center of desktop window. * * @param c Point in desktop coordinates * @param rotate Angle in clockwise direction */ -void -SPDesktop::rotate_relative_center_point (Geom::Point const &c, double rotate) +void SPDesktop::rotate_relative_center_point(Geom::Point const &c, double rotate) { - _current_affine.addRotate( rotate ); + _current_affine.addRotate(rotate); Geom::Rect viewbox = canvas->get_area_world(); set_display_area(c, viewbox.midpoint()); } - /** * Set new flip direction, keeping the point 'c' fixed in the desktop window. * * @param c Point in desktop coordinates * @param flip Direction the canvas will be set as. */ -void -SPDesktop::flip_absolute_keep_point (Geom::Point const &c, CanvasFlip flip) +void SPDesktop::flip_absolute_keep_point(Geom::Point const &c, CanvasFlip flip) { Geom::Point w = d2w(c); // Must be before flip. _current_affine.setFlip(flip); set_display_area(c, w); } - /** * Flip direction, keeping the point 'c' fixed in the desktop window. * * @param c Point in desktop coordinates * @param flip Direction to flip canvas */ -void -SPDesktop::flip_relative_keep_point (Geom::Point const &c, CanvasFlip flip) +void SPDesktop::flip_relative_keep_point(Geom::Point const &c, CanvasFlip flip) { Geom::Point w = d2w(c); // Must be before flip. _current_affine.addFlip(flip); set_display_area(c, w); } - /** * Set new flip direction, aligning the point 'c' to the center of desktop window. * * @param c Point in desktop coordinates * @param flip Direction the canvas will be set as. */ -void -SPDesktop::flip_absolute_center_point (Geom::Point const &c, CanvasFlip flip) +void SPDesktop::flip_absolute_center_point(Geom::Point const &c, CanvasFlip flip) { _current_affine.setFlip(flip); Geom::Rect viewbox = canvas->get_area_world(); set_display_area(c, viewbox.midpoint()); } - /** * Flip direction, aligning the point 'c' to the center of desktop window. * * @param c Point in desktop coordinates * @param flip Direction to flip canvas */ -void -SPDesktop::flip_relative_center_point (Geom::Point const &c, CanvasFlip flip) +void SPDesktop::flip_relative_center_point(Geom::Point const &c, CanvasFlip flip) { _current_affine.addFlip(flip); Geom::Rect viewbox = canvas->get_area_world(); set_display_area(c, viewbox.midpoint()); } -bool -SPDesktop::is_flipped (CanvasFlip flip) +bool SPDesktop::is_flipped(CanvasFlip flip) { return _current_affine.isFlipped(flip); } - /** * Scroll canvas by to a particular point (window coordinates). */ -void -SPDesktop::scroll_absolute (Geom::Point const &point, bool is_scrolling) +void SPDesktop::scroll_absolute(Geom::Point const &point, bool is_scrolling) { canvas->scroll_to(point, false); - _current_affine.setOffset( point ); + _current_affine.setOffset(point); /* update perspective lines if we are in the 3D box tool (so that infinite ones are shown correctly) */ - //sp_box3d_context_update_lines(event_context); + // sp_box3d_context_update_lines(event_context); if (SP_IS_BOX3D_CONTEXT(event_context)) { - SP_BOX3D_CONTEXT(event_context)->_vpdrag->updateLines(); - } + SP_BOX3D_CONTEXT(event_context)->_vpdrag->updateLines(); + } _widget->update_rulers(); _widget->update_scrollbars(_current_affine.getZoom()); } - /** * Scroll canvas by specific coordinate amount (window coordinates). */ -void -SPDesktop::scroll_relative (Geom::Point const &delta, bool is_scrolling) +void SPDesktop::scroll_relative(Geom::Point const &delta, bool is_scrolling) { Geom::Rect const viewbox = canvas->get_area_world(); - scroll_absolute( viewbox.min() - delta, is_scrolling ); + scroll_absolute(viewbox.min() - delta, is_scrolling); } - /** * Scroll canvas by specific coordinate amount in svg coordinates. */ -void -SPDesktop::scroll_relative_in_svg_coords (double dx, double dy, bool is_scrolling) +void SPDesktop::scroll_relative_in_svg_coords(double dx, double dy, bool is_scrolling) { double scale = _current_affine.getZoom(); - scroll_relative(Geom::Point(dx*scale, dy*scale), is_scrolling); + scroll_relative(Geom::Point(dx * scale, dy * scale), is_scrolling); } - /** * Scroll screen so as to keep point 'p' visible in window. * (Used, for example, when a node is being dragged.) * 'p': The point in desktop coordinates. * 'autoscrollspeed': The scroll speed (or zero to use preferences' value). */ -bool -SPDesktop::scroll_to_point (Geom::Point const &p, gdouble autoscrollspeed) +bool SPDesktop::scroll_to_point(Geom::Point const &p, gdouble autoscrollspeed) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); // autoscrolldistance is in screen pixels. - gdouble autoscrolldistance = (gdouble) prefs->getIntLimited("/options/autoscrolldistance/value", 0, -1000, 10000); + gdouble autoscrolldistance = (gdouble)prefs->getIntLimited("/options/autoscrolldistance/value", 0, -1000, 10000); Geom::Rect w = canvas->get_area_world(); // Window in screen coordinates. - w.expandBy(-autoscrolldistance); // Shrink window + w.expandBy(-autoscrolldistance); // Shrink window - Geom::Point c = d2w(p); // Point 'p' in screen coordinates. + Geom::Point c = d2w(p); // Point 'p' in screen coordinates. if (!w.contains(c)) { - Geom::Point c2 = w.clamp(c); // Constrain c to window. if (autoscrollspeed == 0) autoscrollspeed = prefs->getDoubleLimited("/options/autoscrollspeed/value", 1, 0, 10); if (autoscrollspeed != 0) - scroll_relative (autoscrollspeed * (c2 - c) ); + scroll_relative(autoscrollspeed * (c2 - c)); return true; } return false; } -bool -SPDesktop::is_iconified() +bool SPDesktop::is_iconified() { - return 0!=(window_state & GDK_WINDOW_STATE_ICONIFIED); + return 0 != (window_state & GDK_WINDOW_STATE_ICONIFIED); } -void -SPDesktop::iconify() +void SPDesktop::iconify() { _widget->iconify(); } -bool SPDesktop::is_darktheme() { return getToplevel()->get_style_context()->has_class("dark"); } +bool SPDesktop::is_darktheme() +{ + return getToplevel()->get_style_context()->has_class("dark"); +} -bool -SPDesktop::is_maximized() +bool SPDesktop::is_maximized() { - return 0!=(window_state & GDK_WINDOW_STATE_MAXIMIZED); + return 0 != (window_state & GDK_WINDOW_STATE_MAXIMIZED); } -void -SPDesktop::maximize() +void SPDesktop::maximize() { _widget->maximize(); } -bool -SPDesktop::is_fullscreen() +bool SPDesktop::is_fullscreen() { - return 0!=(window_state & GDK_WINDOW_STATE_FULLSCREEN); + return 0 != (window_state & GDK_WINDOW_STATE_FULLSCREEN); } -void -SPDesktop::fullscreen() +void SPDesktop::fullscreen() { _widget->fullscreen(); } @@ -1456,75 +1381,68 @@ bool SPDesktop::is_focusMode() */ void SPDesktop::focusMode(bool mode) { - if (mode == _focusMode) { return; } + if (mode == _focusMode) { + return; + } _focusMode = mode; layoutWidget(); - //sp_desktop_widget_layout(SPDesktopWidget); + // sp_desktop_widget_layout(SPDesktopWidget); return; } -void -SPDesktop::getWindowGeometry (gint &x, gint &y, gint &w, gint &h) +void SPDesktop::getWindowGeometry(gint &x, gint &y, gint &w, gint &h) { - _widget->getWindowGeometry (x, y, w, h); + _widget->getWindowGeometry(x, y, w, h); } -void -SPDesktop::setWindowPosition (Geom::Point p) +void SPDesktop::setWindowPosition(Geom::Point p) { - _widget->setWindowPosition (p); + _widget->setWindowPosition(p); } -void -SPDesktop::setWindowSize (gint w, gint h) +void SPDesktop::setWindowSize(gint w, gint h) { - _widget->setWindowSize (w, h); + _widget->setWindowSize(w, h); } -void -SPDesktop::setWindowTransient (void *p, int transient_policy) +void SPDesktop::setWindowTransient(void *p, int transient_policy) { - _widget->setWindowTransient (p, transient_policy); + _widget->setWindowTransient(p, transient_policy); } -Gtk::Window* -SPDesktop::getToplevel( ) +Gtk::Window *SPDesktop::getToplevel() { return _widget->window; } -InkscapeWindow* -SPDesktop::getInkscapeWindow( ) +InkscapeWindow *SPDesktop::getInkscapeWindow() { - InkscapeWindow* window = dynamic_cast(_widget->window); + InkscapeWindow *window = dynamic_cast(_widget->window); if (!window) { std::cerr << "SPDesktop::getInkscapeWindow: Failed to get window." << std::endl; } return window; } -void -SPDesktop::presentWindow() +void SPDesktop::presentWindow() { _widget->presentWindow(); } -bool SPDesktop::showInfoDialog( Glib::ustring const & message ) +bool SPDesktop::showInfoDialog(Glib::ustring const &message) { - return _widget->showInfoDialog( message ); + return _widget->showInfoDialog(message); } -bool -SPDesktop::warnDialog (Glib::ustring const &text) +bool SPDesktop::warnDialog(Glib::ustring const &text) { - return _widget->warnDialog (text); + return _widget->warnDialog(text); } -void -SPDesktop::toggleRulers() +void SPDesktop::toggleRulers() { _widget->toggle_rulers(); Inkscape::Verb *verb = Inkscape::Verb::get(SP_VERB_TOGGLE_RULERS); @@ -1533,8 +1451,7 @@ SPDesktop::toggleRulers() } } -void -SPDesktop::toggleScrollbars() +void SPDesktop::toggleScrollbars() { _widget->toggle_scrollbars(); Inkscape::Verb *verb = Inkscape::Verb::get(SP_VERB_TOGGLE_SCROLLBARS); @@ -1543,7 +1460,6 @@ SPDesktop::toggleScrollbars() } } - void SPDesktop::toggleToolbar(gchar const *toolbar_name, unsigned int verbenum) { Glib::ustring pref_path = getLayoutPrefPath(this) + toolbar_name + "/state"; @@ -1557,29 +1473,26 @@ void SPDesktop::toggleToolbar(gchar const *toolbar_name, unsigned int verbenum) layoutWidget(); } -void -SPDesktop::layoutWidget() +void SPDesktop::layoutWidget() { _widget->layoutWidgets(); } -void -SPDesktop::destroyWidget() +void SPDesktop::destroyWidget() { auto *window = _widget->window; _widget->window = nullptr; delete window; // may also delete _widget Check if this is logical! } -bool -SPDesktop::shutdown() +bool SPDesktop::shutdown() { return _widget->shutdown(); } -bool SPDesktop::onDeleteUI (GdkEventAny*) +bool SPDesktop::onDeleteUI(GdkEventAny *) { - if(shutdown()) + if (shutdown()) return true; destroyWidget(); @@ -1593,35 +1506,33 @@ bool SPDesktop::onDeleteUI (GdkEventAny*) * Since GTK doesn't have a way to query this state information directly, we * record it for the desktop here, and also possibly trigger a layout. */ -bool -SPDesktop::onWindowStateEvent (GdkEventWindowState* event) +bool SPDesktop::onWindowStateEvent(GdkEventWindowState *event) { // Record the desktop window's state window_state = event->new_window_state; // Layout may differ depending on full-screen mode or not GdkWindowState changed = event->changed_mask; - if (changed & (GDK_WINDOW_STATE_FULLSCREEN|GDK_WINDOW_STATE_MAXIMIZED)) { + if (changed & (GDK_WINDOW_STATE_FULLSCREEN | GDK_WINDOW_STATE_MAXIMIZED)) { layoutWidget(); } return false; } - /** - * Apply the desktop's current style or the tool style to the object. - */ + * Apply the desktop's current style or the tool style to the object. + */ void SPDesktop::applyCurrentOrToolStyle(SPObject *obj, Glib::ustring const &tool_path, bool with_text) { SPCSSAttr *css_current = sp_desktop_get_style(this, with_text); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs->getBool(tool_path + "/usecurrent") && css_current) { - obj->setCSS(css_current,"style"); + obj->setCSS(css_current, "style"); } else { SPCSSAttr *css = prefs->getInheritedStyle(tool_path + "/style"); - obj->setCSS(css,"style"); + obj->setCSS(css, "style"); sp_repr_css_attr_unref(css); } if (css_current) { @@ -1629,36 +1540,30 @@ void SPDesktop::applyCurrentOrToolStyle(SPObject *obj, Glib::ustring const &tool } } - -void -SPDesktop::setToolboxFocusTo (gchar const *label) +void SPDesktop::setToolboxFocusTo(gchar const *label) { - _widget->setToolboxFocusTo (label); + _widget->setToolboxFocusTo(label); } -void -SPDesktop::setToolboxAdjustmentValue (gchar const* id, double val) +void SPDesktop::setToolboxAdjustmentValue(gchar const *id, double val) { - _widget->setToolboxAdjustmentValue (id, val); + _widget->setToolboxAdjustmentValue(id, val); } -Gtk::Toolbar* -SPDesktop::get_toolbar_by_name(const Glib::ustring& name) +Gtk::Toolbar *SPDesktop::get_toolbar_by_name(const Glib::ustring &name) { return _widget->get_toolbar_by_name(name); } -bool -SPDesktop::isToolboxButtonActive (gchar const *id) +bool SPDesktop::isToolboxButtonActive(gchar const *id) { - return _widget->isToolboxButtonActive (id); + return _widget->isToolboxButtonActive(id); } -void -SPDesktop::emitToolSubselectionChanged(gpointer data) +void SPDesktop::emitToolSubselectionChanged(gpointer data) { _tool_subselection_changed.emit(data); - INKSCAPE.subselection_changed (this); + INKSCAPE.subselection_changed(this); } void SPDesktop::updateNow() @@ -1666,15 +1571,14 @@ void SPDesktop::updateNow() canvas->redraw_now(); } -void -SPDesktop::enableInteraction() +void SPDesktop::enableInteraction() { - _widget->enableInteraction(); + _widget->enableInteraction(); } void SPDesktop::disableInteraction() { - _widget->disableInteraction(); + _widget->disableInteraction(); } void SPDesktop::setWaitingCursor() @@ -1687,10 +1591,11 @@ void SPDesktop::setWaitingCursor() waiting_cursor = true; } -void SPDesktop::clearWaitingCursor() { - if (waiting_cursor) { - this->event_context->sp_event_context_update_cursor(); - } +void SPDesktop::clearWaitingCursor() +{ + if (waiting_cursor) { + this->event_context->sp_event_context_update_cursor(); + } } void SPDesktop::toggleColorProfAdjust() @@ -1718,12 +1623,12 @@ bool SPDesktop::colorProfAdjustEnabled() void SPDesktop::toggleGrids() { - if (! namedview->grids.empty()) { - if(gridgroup) { + if (!namedview->grids.empty()) { + if (gridgroup) { showGrids(!grids_visible); } } else { - //there is no grid present at the moment. add a rectangular grid and make it visible + // there is no grid present at the moment. add a rectangular grid and make it visible namedview->writeNewGrid(this->getDocument(), Inkscape::GRID_RECTANGULAR); showGrids(true); } @@ -1734,9 +1639,10 @@ void SPDesktop::toggleGrids() } // This will be replaced by an action! -void SPDesktop::setSplitMode(Inkscape::SplitMode mode) { +void SPDesktop::setSplitMode(Inkscape::SplitMode mode) +{ _split_canvas = (mode == Inkscape::SPLITMODE_SPLIT); - _xray = (mode == Inkscape::SPLITMODE_XRAY); + _xray = (mode == Inkscape::SPLITMODE_XRAY); canvas->set_split_mode(mode); Inkscape::Verb *verb1 = Inkscape::Verb::get(SP_VERB_VIEW_TOGGLE_SPLIT); @@ -1752,12 +1658,12 @@ void SPDesktop::setSplitMode(Inkscape::SplitMode mode) { void SPDesktop::toggleSplitMode() { - setSplitMode( _split_canvas ? Inkscape::SPLITMODE_NORMAL : Inkscape::SPLITMODE_SPLIT); + setSplitMode(_split_canvas ? Inkscape::SPLITMODE_NORMAL : Inkscape::SPLITMODE_SPLIT); } void SPDesktop::toggleXRay() { - setSplitMode( _xray ? Inkscape::SPLITMODE_NORMAL : Inkscape::SPLITMODE_XRAY); + setSplitMode(_xray ? Inkscape::SPLITMODE_NORMAL : Inkscape::SPLITMODE_XRAY); } void SPDesktop::showGrids(bool show, bool dirty_document) @@ -1780,10 +1686,9 @@ void SPDesktop::toggleSnapGlobal() //---------------------------------------------------------------------- // Callback implementations. The virtual ones are connected by the view. -void -SPDesktop::onResized (double /*x*/, double /*y*/) +void SPDesktop::onResized(double /*x*/, double /*y*/) { - // Nothing called here + // Nothing called here } /** @@ -1799,27 +1704,25 @@ void SPDesktop::storeDesktopPosition() /** * Redraw callback; queues Gtk redraw; connected by View. */ -void -SPDesktop::onRedrawRequested () +void SPDesktop::onRedrawRequested() { if (main) { _widget->requestCanvasUpdate(); } } -void -SPDesktop::updateCanvasNow() +void SPDesktop::updateCanvasNow() { - _widget->requestCanvasUpdateAndWait(); + _widget->requestCanvasUpdateAndWait(); } /** * Associate document with desktop. */ -void -SPDesktop::setDocument (SPDocument *doc) +void SPDesktop::setDocument(SPDocument *doc) { - if (!doc) return; + if (!doc) + return; if (this->doc()) { namedview->hide(this); @@ -1854,40 +1757,34 @@ SPDesktop::setDocument (SPDocument *doc) if (drawing) { Inkscape::DrawingItem *ai = nullptr; - namedview = sp_document_namedview (doc, nullptr); + namedview = sp_document_namedview(doc, nullptr); _modified_connection = namedview->connectModified(sigc::bind<2>(sigc::ptr_fun(&_namedview_modified), this)); number = namedview->getViewCount(); - ai = doc->getRoot()->invoke_show( - SP_CANVAS_ARENA (drawing)->drawing, - dkey, - SP_ITEM_SHOW_DISPLAY); + ai = doc->getRoot()->invoke_show(SP_CANVAS_ARENA(drawing)->drawing, dkey, SP_ITEM_SHOW_DISPLAY); if (ai) { - SP_CANVAS_ARENA (drawing)->drawing.root()->prependChild(ai); + SP_CANVAS_ARENA(drawing)->drawing.root()->prependChild(ai); } namedview->show(this); /* Ugly hack */ - activate_guides (true); + activate_guides(true); /* Ugly hack */ - _namedview_modified (namedview, SP_OBJECT_MODIFIED_FLAG, this); + _namedview_modified(namedview, SP_OBJECT_MODIFIED_FLAG, this); } - _document_replaced_signal.emit (this, doc); + _document_replaced_signal.emit(this, doc); - View::setDocument (doc); + View::setDocument(doc); } -void -SPDesktop::onStatusMessage -(Inkscape::MessageType type, gchar const *message) +void SPDesktop::onStatusMessage(Inkscape::MessageType type, gchar const *message) { if (_widget) { _widget->setMessage(type, message); } } -void -SPDesktop::onDocumentURISet (gchar const* uri) +void SPDesktop::onDocumentURISet(gchar const *uri) { _widget->updateTitle(uri); } @@ -1895,51 +1792,46 @@ SPDesktop::onDocumentURISet (gchar const* uri) /** * Resized callback. */ -void -SPDesktop::onDocumentResized (gdouble width, gdouble height) +void SPDesktop::onDocumentResized(gdouble width, gdouble height) { - sp_canvas_item_affine_absolute (SP_CANVAS_ITEM (drawing), doc2dt()); + sp_canvas_item_affine_absolute(SP_CANVAS_ITEM(drawing), doc2dt()); Geom::Rect const a(Geom::Point(0, 0), Geom::Point(width, height)); SP_CTRLRECT(page)->setRectangle(a); SP_CTRLRECT(page_border)->setRectangle(a); } - -void -SPDesktop::_onActivate (SPDesktop* dt) +void SPDesktop::_onActivate(SPDesktop *dt) { - if (!dt->_widget) return; + if (!dt->_widget) + return; sp_dtw_desktop_activate(dt->_widget); } -void -SPDesktop::_onDeactivate (SPDesktop* dt) +void SPDesktop::_onDeactivate(SPDesktop *dt) { - if (!dt->_widget) return; + if (!dt->_widget) + return; sp_dtw_desktop_deactivate(dt->_widget); } -void -SPDesktop::_onSelectionModified -(Inkscape::Selection */*selection*/, guint /*flags*/, SPDesktop *dt) +void SPDesktop::_onSelectionModified(Inkscape::Selection * /*selection*/, guint /*flags*/, SPDesktop *dt) { - if (!dt->_widget) return; - dt->_widget->update_scrollbars (dt->_current_affine.getZoom()); + if (!dt->_widget) + return; + dt->_widget->update_scrollbars(dt->_current_affine.getZoom()); } -static void -_onSelectionChanged -(Inkscape::Selection *selection, SPDesktop *desktop) +static void _onSelectionChanged(Inkscape::Selection *selection, SPDesktop *desktop) { /** \todo * only change the layer for single selections, or what? * This seems reasonable -- for multiple selections there can be many * different layers involved. */ - SPItem *item=selection->singleItem(); + SPItem *item = selection->singleItem(); if (item) { - SPObject *layer=desktop->layers->layerForObject(item); - if ( layer && layer != desktop->currentLayer() ) { + SPObject *layer = desktop->layers->layerForObject(item); + if (layer && layer != desktop->currentLayer()) { desktop->layers->setCurrentLayer(layer); } } @@ -1950,46 +1842,41 @@ _onSelectionChanged * \param arena Unused * \todo fixme */ -static gint -_arena_handler (SPCanvasArena */*arena*/, Inkscape::DrawingItem *ai, GdkEvent *event, SPDesktop *desktop) +static gint _arena_handler(SPCanvasArena * /*arena*/, Inkscape::DrawingItem *ai, GdkEvent *event, SPDesktop *desktop) { - if (event->type == GDK_KEY_PRESS && - Inkscape::UI::Tools::get_latin_keyval(&event->key) == GDK_KEY_space && - desktop->event_context->space_panning) - { + if (event->type == GDK_KEY_PRESS && Inkscape::UI::Tools::get_latin_keyval(&event->key) == GDK_KEY_space && + desktop->event_context->space_panning) { return true; } if (ai) { SPItem *spi = ai->getItem(); - return sp_event_context_item_handler (desktop->event_context, spi, event); + return sp_event_context_item_handler(desktop->event_context, spi, event); } else { - return sp_event_context_root_handler (desktop->event_context, event); + return sp_event_context_root_handler(desktop->event_context, event); } } -static void -_layer_activated(SPObject *layer, SPDesktop *desktop) { +static void _layer_activated(SPObject *layer, SPDesktop *desktop) +{ g_return_if_fail(SP_IS_GROUP(layer)); SP_GROUP(layer)->setLayerDisplayMode(desktop->dkey, SPGroup::LAYER); } /// Callback -static void -_layer_deactivated(SPObject *layer, SPDesktop *desktop) { +static void _layer_deactivated(SPObject *layer, SPDesktop *desktop) +{ g_return_if_fail(SP_IS_GROUP(layer)); SP_GROUP(layer)->setLayerDisplayMode(desktop->dkey, SPGroup::GROUP); } /// Callback -static void -_layer_hierarchy_changed(SPObject */*top*/, SPObject *bottom, - SPDesktop *desktop) +static void _layer_hierarchy_changed(SPObject * /*top*/, SPObject *bottom, SPDesktop *desktop) { - desktop->_layer_changed_signal.emit (bottom); + desktop->_layer_changed_signal.emit(bottom); } /// Called when document is starting to be rebuilt. -static void _reconstruction_start(SPDesktop * desktop) +static void _reconstruction_start(SPDesktop *desktop) { desktop->_reconstruction_old_layer_id = desktop->currentLayer()->getId() ? desktop->currentLayer()->getId() : ""; desktop->layers->reset(); @@ -1998,11 +1885,11 @@ static void _reconstruction_start(SPDesktop * desktop) } /// Called when document rebuild is finished. -static void _reconstruction_finish(SPDesktop * desktop) +static void _reconstruction_finish(SPDesktop *desktop) { g_debug("Desktop, finishing reconstruction\n"); - if ( !desktop->_reconstruction_old_layer_id.empty() ) { - SPObject * newLayer = desktop->namedview->document->getObjectById(desktop->_reconstruction_old_layer_id); + if (!desktop->_reconstruction_old_layer_id.empty()) { + SPObject *newLayer = desktop->namedview->document->getObjectById(desktop->_reconstruction_old_layer_id); if (newLayer != nullptr) { desktop->layers->setCurrentLayer(newLayer); } @@ -2015,9 +1902,9 @@ static void _reconstruction_finish(SPDesktop * desktop) /** * Namedview_modified callback. */ -static void _namedview_modified (SPObject *obj, guint flags, SPDesktop *desktop) +static void _namedview_modified(SPObject *obj, guint flags, SPDesktop *desktop) { - SPNamedView *nv=SP_NAMEDVIEW(obj); + SPNamedView *nv = SP_NAMEDVIEW(obj); if (flags & SP_OBJECT_MODIFIED_FLAG) { if (nv->pagecheckerboard) { @@ -2029,43 +1916,43 @@ static void _namedview_modified (SPObject *obj, guint flags, SPDesktop *desktop) /* Show/hide page border */ if (nv->showborder) { // show - sp_canvas_item_show (desktop->page_border); + sp_canvas_item_show(desktop->page_border); // set color and shadow - ((CtrlRect *) desktop->page_border)->setColor(nv->bordercolor, false, 0x00000000); + ((CtrlRect *)desktop->page_border)->setColor(nv->bordercolor, false, 0x00000000); if (nv->pageshadow) { - ((CtrlRect *) desktop->page_border)->setShadow(nv->pageshadow, nv->bordercolor); + ((CtrlRect *)desktop->page_border)->setShadow(nv->pageshadow, nv->bordercolor); } // place in the z-order stack if (nv->borderlayer == SP_BORDER_LAYER_BOTTOM) { - sp_canvas_item_move_to_z (desktop->page_border, 1); + sp_canvas_item_move_to_z(desktop->page_border, 1); } else { - int order = sp_canvas_item_order (desktop->page_border); - int morder = sp_canvas_item_order (desktop->drawing); - if (morder > order) sp_canvas_item_raise (desktop->page_border, - morder - order); + int order = sp_canvas_item_order(desktop->page_border); + int morder = sp_canvas_item_order(desktop->drawing); + if (morder > order) + sp_canvas_item_raise(desktop->page_border, morder - order); } } else { - sp_canvas_item_hide (desktop->page_border); - if (nv->pageshadow) { - ((CtrlRect *) desktop->page)->setShadow(0, 0x00000000); - } + sp_canvas_item_hide(desktop->page_border); + if (nv->pageshadow) { + ((CtrlRect *)desktop->page)->setShadow(0, 0x00000000); + } } /* Show/hide page shadow */ if (nv->showpageshadow && nv->pageshadow) { - ((CtrlRect *) desktop->page_border)->setShadow(nv->pageshadow, nv->bordercolor); + ((CtrlRect *)desktop->page_border)->setShadow(nv->pageshadow, nv->bordercolor); } else { - ((CtrlRect *) desktop->page_border)->setShadow(0, 0x00000000); + ((CtrlRect *)desktop->page_border)->setShadow(0, 0x00000000); } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (SP_RGBA32_R_U(nv->pagecolor) + - SP_RGBA32_G_U(nv->pagecolor) + - SP_RGBA32_B_U(nv->pagecolor) >= 384) { + if (SP_RGBA32_R_U(nv->pagecolor) + SP_RGBA32_G_U(nv->pagecolor) + SP_RGBA32_B_U(nv->pagecolor) >= 384) { // the background color is light, use black outline - SP_CANVAS_ARENA (desktop->drawing)->drawing.outlinecolor = prefs->getInt("/options/wireframecolors/onlight", 0xff); + SP_CANVAS_ARENA(desktop->drawing)->drawing.outlinecolor = + prefs->getInt("/options/wireframecolors/onlight", 0xff); } else { // use white outline - SP_CANVAS_ARENA (desktop->drawing)->drawing.outlinecolor = prefs->getInt("/options/wireframecolors/ondark", 0xffffffff); + SP_CANVAS_ARENA(desktop->drawing)->drawing.outlinecolor = + prefs->getInt("/options/wireframecolors/ondark", 0xffffffff); } } } @@ -2107,10 +1994,8 @@ Geom::Point SPDesktop::dt2doc(Geom::Point const &p) const return p * dt2doc(); } -void -SPDesktop::show_dialogs() +void SPDesktop::show_dialogs() { - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs == nullptr) { return; @@ -2128,46 +2013,46 @@ SPDesktop::show_dialogs() showing_dialogs = TRUE; - /* - * Get each dialogs previous state from preferences and reopen on startup if needed, without grabbing focus (canvas retains focus). - * Map dialog manager's dialog IDs to dialog last visible state preference. FIXME: store this correspondence in dialogs themselves! + * Get each dialogs previous state from preferences and reopen on startup if needed, without grabbing focus (canvas + * retains focus). Map dialog manager's dialog IDs to dialog last visible state preference. FIXME: store this + * correspondence in dialogs themselves! */ std::map mapVerbPreference; - mapVerbPreference.insert(std::make_pair ("LayersPanel", "/dialogs/layers") ); - mapVerbPreference.insert(std::make_pair ("FillAndStroke", "/dialogs/fillstroke") ); - mapVerbPreference.insert(std::make_pair ("ExtensionEditor", "/dialogs/extensioneditor") ); - mapVerbPreference.insert(std::make_pair ("AlignAndDistribute", "/dialogs/align") ); - mapVerbPreference.insert(std::make_pair ("DocumentProperties", "/dialogs/documentoptions") ); - mapVerbPreference.insert(std::make_pair ("FilterEffectsDialog", "/dialogs/filtereffects") ); - mapVerbPreference.insert(std::make_pair ("Find", "/dialogs/find") ); - mapVerbPreference.insert(std::make_pair ("Glyphs", "/dialogs/glyphs") ); - mapVerbPreference.insert(std::make_pair ("Messages", "/dialogs/messages") ); - mapVerbPreference.insert(std::make_pair ("Memory", "/dialogs/memory") ); - mapVerbPreference.insert(std::make_pair ("LivePathEffect", "/dialogs/livepatheffect") ); - mapVerbPreference.insert(std::make_pair ("UndoHistory", "/dialogs/undo-history") ); - mapVerbPreference.insert(std::make_pair ("Transformation", "/dialogs/transformation") ); - mapVerbPreference.insert(std::make_pair ("Swatches", "/dialogs/swatches") ); - mapVerbPreference.insert(std::make_pair ("IconPreviewPanel", "/dialogs/iconpreview") ); - mapVerbPreference.insert(std::make_pair ("SvgFontsDialog", "/dialogs/svgfonts") ); - mapVerbPreference.insert(std::make_pair ("InputDevices", "/dialogs/inputdevices") ); - mapVerbPreference.insert(std::make_pair ("InkscapePreferences", "/dialogs/preferences") ); - mapVerbPreference.insert(std::make_pair ("TileDialog", "/dialogs/gridtiler") ); - mapVerbPreference.insert(std::make_pair ("Trace", "/dialogs/trace") ); - mapVerbPreference.insert(std::make_pair ("TextFont", "/dialogs/textandfont") ); - mapVerbPreference.insert(std::make_pair ("Export", "/dialogs/export") ); - mapVerbPreference.insert(std::make_pair ("XmlTree", "/dialogs/xml") ); - mapVerbPreference.insert(std::make_pair ("Selectors", "/dialogs/selectors") ); - mapVerbPreference.insert(std::make_pair ("CloneTiler", "/dialogs/clonetiler") ); - mapVerbPreference.insert(std::make_pair ("ObjectProperties", "/dialogs/object") ); - mapVerbPreference.insert(std::make_pair ("SpellCheck", "/dialogs/spellcheck") ); - mapVerbPreference.insert(std::make_pair ("Symbols", "/dialogs/symbols") ); - mapVerbPreference.insert(std::make_pair ("PaintServers", "/dialogs/paint") ); - mapVerbPreference.insert(std::make_pair ("ObjectsPanel", "/dialogs/objects") ); - mapVerbPreference.insert(std::make_pair ("Prototype", "/dialogs/prototype") ); - - - for (std::map::const_iterator iter = mapVerbPreference.begin(); iter != mapVerbPreference.end(); ++iter) { + mapVerbPreference.insert(std::make_pair("LayersPanel", "/dialogs/layers")); + mapVerbPreference.insert(std::make_pair("FillAndStroke", "/dialogs/fillstroke")); + mapVerbPreference.insert(std::make_pair("ExtensionEditor", "/dialogs/extensioneditor")); + mapVerbPreference.insert(std::make_pair("AlignAndDistribute", "/dialogs/align")); + mapVerbPreference.insert(std::make_pair("DocumentProperties", "/dialogs/documentoptions")); + mapVerbPreference.insert(std::make_pair("FilterEffectsDialog", "/dialogs/filtereffects")); + mapVerbPreference.insert(std::make_pair("Find", "/dialogs/find")); + mapVerbPreference.insert(std::make_pair("Glyphs", "/dialogs/glyphs")); + mapVerbPreference.insert(std::make_pair("Messages", "/dialogs/messages")); + mapVerbPreference.insert(std::make_pair("Memory", "/dialogs/memory")); + mapVerbPreference.insert(std::make_pair("LivePathEffect", "/dialogs/livepatheffect")); + mapVerbPreference.insert(std::make_pair("UndoHistory", "/dialogs/undo-history")); + mapVerbPreference.insert(std::make_pair("Transformation", "/dialogs/transformation")); + mapVerbPreference.insert(std::make_pair("Swatches", "/dialogs/swatches")); + mapVerbPreference.insert(std::make_pair("IconPreviewPanel", "/dialogs/iconpreview")); + mapVerbPreference.insert(std::make_pair("SvgFontsDialog", "/dialogs/svgfonts")); + mapVerbPreference.insert(std::make_pair("InputDevices", "/dialogs/inputdevices")); + mapVerbPreference.insert(std::make_pair("InkscapePreferences", "/dialogs/preferences")); + mapVerbPreference.insert(std::make_pair("TileDialog", "/dialogs/gridtiler")); + mapVerbPreference.insert(std::make_pair("Trace", "/dialogs/trace")); + mapVerbPreference.insert(std::make_pair("TextFont", "/dialogs/textandfont")); + mapVerbPreference.insert(std::make_pair("Export", "/dialogs/export")); + mapVerbPreference.insert(std::make_pair("XmlTree", "/dialogs/xml")); + mapVerbPreference.insert(std::make_pair("Selectors", "/dialogs/selectors")); + mapVerbPreference.insert(std::make_pair("CloneTiler", "/dialogs/clonetiler")); + mapVerbPreference.insert(std::make_pair("ObjectProperties", "/dialogs/object")); + mapVerbPreference.insert(std::make_pair("SpellCheck", "/dialogs/spellcheck")); + mapVerbPreference.insert(std::make_pair("Symbols", "/dialogs/symbols")); + mapVerbPreference.insert(std::make_pair("PaintServers", "/dialogs/paint")); + mapVerbPreference.insert(std::make_pair("ObjectsPanel", "/dialogs/objects")); + mapVerbPreference.insert(std::make_pair("Prototype", "/dialogs/prototype")); + + for (std::map::const_iterator iter = mapVerbPreference.begin(); + iter != mapVerbPreference.end(); ++iter) { Glib::ustring pref = iter->second; int visible = prefs->getInt(pref + "/visible", 0); @@ -2176,7 +2061,8 @@ SPDesktop::show_dialogs() // There must be a better way of handling this problem! INKSCAPE.activate_desktop(this); - _dlg_mgr->showDialog(iter->first.c_str(), false); // without grabbing focus, we need focus to remain on the canvas + _dlg_mgr->showDialog(iter->first.c_str(), + false); // without grabbing focus, we need focus to remain on the canvas } } diff --git a/src/desktop.h b/src/desktop.h index 4fc4effd3cbd3a68d791a114965444b0331aeba5..e2639885aaa6693281992392eb810d6a397a3513 100644 --- a/src/desktop.h +++ b/src/desktop.h @@ -22,20 +22,16 @@ * */ -#include -#include -#include - #include <2geom/affine.h> -#include <2geom/transforms.h> #include <2geom/parallelogram.h> - -#include "preferences.h" +#include <2geom/transforms.h> +#include +#include +#include #include "display/rendermode.h" - #include "object/sp-gradient.h" // TODO refactor enums out to their own .h file - +#include "preferences.h" #include "ui/dialog/print.h" #include "ui/view/view.h" @@ -52,22 +48,21 @@ namespace Tools { class ToolBase; } -} -} +} // namespace UI +} // namespace Inkscape class SPItem; class SPNamedView; class SPObject; class SPStyle; -typedef struct _DocumentInterface DocumentInterface;//struct DocumentInterface; +typedef struct _DocumentInterface DocumentInterface; // struct DocumentInterface; class InkscapeWindow; -namespace Gtk -{ - class Toolbar; - class Window; -} +namespace Gtk { +class Toolbar; +class Window; +} // namespace Gtk typedef int sp_verb_t; @@ -79,28 +74,28 @@ typedef struct _GdkEventWindowState GdkEventWindowState; struct InkscapeApplication; namespace Inkscape { - class LayerModel; - class MessageContext; - class Selection; - class LayerManager; - class EventLog; - namespace UI { - namespace Dialog { - class DialogManager; - } - - namespace Widget { - class Canvas; - class Dock; - } - } - namespace Display { - class TemporaryItemList; - class TemporaryItem; - class SnapIndicator; - } +class LayerModel; +class MessageContext; +class Selection; +class LayerManager; +class EventLog; +namespace UI { +namespace Dialog { +class DialogManager; } +namespace Widget { +class Canvas; +class Dock; +} // namespace Widget +} // namespace UI +namespace Display { +class TemporaryItemList; +class TemporaryItem; +class SnapIndicator; +} // namespace Display +} // namespace Inkscape + #define SP_DESKTOP_ZOOM_MAX 256.0 #define SP_DESKTOP_ZOOM_MIN 0.01 @@ -138,49 +133,49 @@ class SPDesktop : public Inkscape::UI::View::View public: Inkscape::UI::Dialog::DialogManager *_dlg_mgr; Inkscape::UI::Dialog::DialogManager *_dlg_mgr_owned = nullptr; - SPNamedView *namedview; - Inkscape::LayerModel *layers; + SPNamedView *namedview; + Inkscape::LayerModel *layers; /// current selection; will never generally be NULL - Inkscape::Selection *selection; - Inkscape::UI::Tools::ToolBase *event_context; - Inkscape::LayerManager *layer_manager; - Inkscape::EventLog *event_log; + Inkscape::Selection *selection; + Inkscape::UI::Tools::ToolBase *event_context; + Inkscape::LayerManager *layer_manager; + Inkscape::EventLog *event_log; DocumentInterface *dbus_document_interface; Inkscape::Display::TemporaryItemList *temporary_item_list; Inkscape::Display::SnapIndicator *snapindicator; /// Stored settings for print dialogue Inkscape::UI::Dialog::PrinterSettings printer_settings; - Inkscape::UI::Tools::ToolBase* getEventContext() const; - Inkscape::Selection* getSelection() const; - SPDocument* getDocument() const; - Inkscape::UI::Widget::Canvas* getCanvas() const; - SPCanvasItem* getAcetate() const; - SPCanvasGroup* getMain() const; - SPCanvasGroup* getGridGroup() const; - SPCanvasGroup* getGuides() const; - SPCanvasItem* getDrawing() const; - SPCanvasGroup* getSketch() const; - SPCanvasGroup* getControls() const; - SPCanvasGroup* getTempGroup() const; - Inkscape::MessageStack* getMessageStack() const; - SPNamedView* getNamedView() const; + Inkscape::UI::Tools::ToolBase *getEventContext() const; + Inkscape::Selection *getSelection() const; + SPDocument *getDocument() const; + Inkscape::UI::Widget::Canvas *getCanvas() const; + SPCanvasItem *getAcetate() const; + SPCanvasGroup *getMain() const; + SPCanvasGroup *getGridGroup() const; + SPCanvasGroup *getGuides() const; + SPCanvasItem *getDrawing() const; + SPCanvasGroup *getSketch() const; + SPCanvasGroup *getControls() const; + SPCanvasGroup *getTempGroup() const; + Inkscape::MessageStack *getMessageStack() const; + SPNamedView *getNamedView() const; Inkscape::UI::Widget::Canvas *canvas; - SPCanvasItem *acetate; + SPCanvasItem *acetate; SPCanvasGroup *main; SPCanvasGroup *gridgroup; SPCanvasGroup *guides; - SPCanvasItem *drawing; + SPCanvasItem *drawing; SPCanvasGroup *sketch; SPCanvasGroup *controls; - SPCanvasGroup *tempgroup; ///< contains temporary canvas items - SPCanvasItem *page; ///< page background - SPCanvasItem *page_border; ///< page border - SPCanvasItem *canvas_rotate; ///< quickly show canvas rotation - SPCanvasItem *canvas_debug; ///< shows tiling - SPCSSAttr *current; ///< current style - bool _focusMode; ///< Whether we're focused working or general working + SPCanvasGroup *tempgroup; ///< contains temporary canvas items + SPCanvasItem *page; ///< page background + SPCanvasItem *page_border; ///< page border + SPCanvasItem *canvas_rotate; ///< quickly show canvas rotation + SPCanvasItem *canvas_debug; ///< shows tiling + SPCSSAttr *current; ///< current style + bool _focusMode; ///< Whether we're focused working or general working unsigned int dkey; unsigned int number; @@ -195,50 +190,51 @@ public: // storage for selected dragger used by GrDrag as it's // created and deleted by tools SPItem *gr_item; - GrPointType gr_point_type; - guint gr_point_i; + GrPointType gr_point_type; + guint gr_point_i; Inkscape::PaintTarget gr_fill_or_stroke; Glib::ustring _reconstruction_old_layer_id; - sigc::signal _tool_changed; + sigc::signal _tool_changed; sigc::signal _menu_update; - sigc::signal _layer_changed_signal; + sigc::signal _layer_changed_signal; sigc::signal::accumulated _set_style_signal; sigc::signal::accumulated _query_style_signal; - + /// Emitted when the zoom factor changes (not emitted when scrolling). /// The parameter is the new zoom factor sigc::signal signal_zoom_changed; - sigc::connection connectDestroy(const sigc::slot &slot) - { - return _destroy_signal.connect(slot); - } + sigc::connection connectDestroy(const sigc::slot &slot) { return _destroy_signal.connect(slot); } - sigc::connection connectDocumentReplaced (const sigc::slot & slot) + sigc::connection connectDocumentReplaced(const sigc::slot &slot) { - return _document_replaced_signal.connect (slot); + return _document_replaced_signal.connect(slot); } - sigc::connection connectEventContextChanged (const sigc::slot & slot) + sigc::connection + connectEventContextChanged(const sigc::slot &slot) { - return _event_context_changed_signal.connect (slot); + return _event_context_changed_signal.connect(slot); } - sigc::connection connectSetStyle (const sigc::slot & slot) + sigc::connection connectSetStyle(const sigc::slot &slot) { - return _set_style_signal.connect (slot); + return _set_style_signal.connect(slot); } - sigc::connection connectQueryStyle (const sigc::slot & slot) + sigc::connection connectQueryStyle(const sigc::slot &slot) { - return _query_style_signal.connect (slot); + return _query_style_signal.connect(slot); } - // subselection is some sort of selection which is specific to the tool, such as a handle in gradient tool, or a text selection - sigc::connection connectToolSubselectionChanged(const sigc::slot & slot) { + // subselection is some sort of selection which is specific to the tool, such as a handle in gradient tool, or a + // text selection + sigc::connection connectToolSubselectionChanged(const sigc::slot &slot) + { return _tool_subselection_changed.connect(slot); } void emitToolSubselectionChanged(gpointer data); - sigc::connection connectCurrentLayerChanged(const sigc::slot & slot) { + sigc::connection connectCurrentLayerChanged(const sigc::slot &slot) + { return _layer_changed_signal.connect(slot); } @@ -249,16 +245,15 @@ public: */ SPDesktop(); - void init (SPNamedView* nv, Inkscape::UI::Widget::Canvas* new_canvas, SPDesktopWidget *widget); + void init(SPNamedView *nv, Inkscape::UI::Widget::Canvas *new_canvas, SPDesktopWidget *widget); ~SPDesktop() override; void destroy(); - Inkscape::MessageContext *guidesMessageContext() const { - return _guides_message_context.get(); - } + Inkscape::MessageContext *guidesMessageContext() const { return _guides_message_context.get(); } - Inkscape::Display::TemporaryItem * add_temporary_canvasitem (SPCanvasItem *item, guint lifetime, bool move_to_bottom = true); - void remove_temporary_canvasitem (Inkscape::Display::TemporaryItem * tempitem); + Inkscape::Display::TemporaryItem *add_temporary_canvasitem(SPCanvasItem *item, guint lifetime, + bool move_to_bottom = true); + void remove_temporary_canvasitem(Inkscape::Display::TemporaryItem *tempitem); void redrawDesktop(); @@ -298,16 +293,16 @@ public: _setDisplayColorMode(Inkscape::COLORMODE_GRAYSCALE); return true; } -// void setDisplayColorModePrintColorsPreview() { -// _setDisplayColorMode(Inkscape::COLORMODE_PRINT_COLORS_PREVIEW); -// } + // void setDisplayColorModePrintColorsPreview() { + // _setDisplayColorMode(Inkscape::COLORMODE_PRINT_COLORS_PREVIEW); + // } bool displayColorModeToggle(); Inkscape::ColorMode _display_color_mode; Inkscape::ColorMode getColorMode() const { return _display_color_mode; } - Inkscape::UI::Widget::Dock* getDock(); + Inkscape::UI::Widget::Dock *getDock(); - void set_active (bool new_active); + void set_active(bool new_active); // Could make all callers use this->layers instead of passing calls through? SPObject *currentRoot() const; @@ -322,14 +317,13 @@ public: bool isWithinViewport(SPItem *item) const; bool itemIsHidden(SPItem const *item) const; - void activate_guides (bool activate); - void change_document (SPDocument *document); - + void activate_guides(bool activate); + void change_document(SPDocument *document); - void setEventContext(const std::string& toolName); + void setEventContext(const std::string &toolName); - void set_coordinate_status (Geom::Point p); - SPItem *getItemFromListAtPointBottom(const std::vector &list, Geom::Point const &p) const; + void set_coordinate_status(Geom::Point p); + SPItem *getItemFromListAtPointBottom(const std::vector &list, Geom::Point const &p) const; SPItem *getItemAtPoint(Geom::Point const &p, bool into_groups, SPItem *upto = nullptr) const; SPItem *getGroupAtPoint(Geom::Point const &p) const; Geom::Point point(bool outside_canvas = false) const; @@ -337,16 +331,16 @@ public: void prev_transform(); void next_transform(); void clear_transform_history(); - - void set_display_area (bool log = true); - void set_display_area (Geom::Point const &c, Geom::Point const &w, bool log = true); - void set_display_area (Geom::Rect const &a, Geom::Coord border, bool log = true); + + void set_display_area(bool log = true); + void set_display_area(Geom::Point const &c, Geom::Point const &w, bool log = true); + void set_display_area(Geom::Rect const &a, Geom::Coord border, bool log = true); Geom::Parallelogram get_display_area(bool use_integer_viewbox = false) const; - void zoom_absolute_keep_point (Geom::Point const &c, double const zoom); - void zoom_relative_keep_point (Geom::Point const &c, double const zoom); - void zoom_absolute_center_point (Geom::Point const &c, double const zoom); - void zoom_relative_center_point (Geom::Point const &c, double const zoom); + void zoom_absolute_keep_point(Geom::Point const &c, double const zoom); + void zoom_relative_keep_point(Geom::Point const &c, double const zoom); + void zoom_absolute_center_point(Geom::Point const &c, double const zoom); + void zoom_relative_center_point(Geom::Point const &c, double const zoom); void zoom_page(); void zoom_page_width(); @@ -366,46 +360,47 @@ public: void zoom_grab_focus(); - void rotate_absolute_keep_point (Geom::Point const &c, double const rotate); - void rotate_relative_keep_point (Geom::Point const &c, double const rotate); - void rotate_absolute_center_point (Geom::Point const &c, double const rotate); - void rotate_relative_center_point (Geom::Point const &c, double const rotate); + void rotate_absolute_keep_point(Geom::Point const &c, double const rotate); + void rotate_relative_keep_point(Geom::Point const &c, double const rotate); + void rotate_absolute_center_point(Geom::Point const &c, double const rotate); + void rotate_relative_center_point(Geom::Point const &c, double const rotate); - enum CanvasFlip { - FLIP_NONE = 0, + enum CanvasFlip + { + FLIP_NONE = 0, FLIP_HORIZONTAL = 1, - FLIP_VERTICAL = 2 + FLIP_VERTICAL = 2 }; - void flip_absolute_keep_point (Geom::Point const &c, CanvasFlip flip); - void flip_relative_keep_point (Geom::Point const &c, CanvasFlip flip); - void flip_absolute_center_point (Geom::Point const &c, CanvasFlip flip); - void flip_relative_center_point (Geom::Point const &c, CanvasFlip flip); - bool is_flipped (CanvasFlip flip); + void flip_absolute_keep_point(Geom::Point const &c, CanvasFlip flip); + void flip_relative_keep_point(Geom::Point const &c, CanvasFlip flip); + void flip_absolute_center_point(Geom::Point const &c, CanvasFlip flip); + void flip_relative_center_point(Geom::Point const &c, CanvasFlip flip); + bool is_flipped(CanvasFlip flip); double current_rotation() const { return _current_affine.getRotation(); } - void scroll_absolute (Geom::Point const &point, bool is_scrolling = false); - void scroll_relative (Geom::Point const &delta, bool is_scrolling = false); - void scroll_relative_in_svg_coords (double dx, double dy, bool is_scrolling = false); - bool scroll_to_point (Geom::Point const &s_dt, gdouble autoscrollspeed = 0); - - void getWindowGeometry (gint &x, gint &y, gint &w, gint &h); - void setWindowPosition (Geom::Point p); - void setWindowSize (gint w, gint h); - void setWindowTransient (void* p, int transient_policy=1); - Gtk::Window* getToplevel(); // To be removed in favor of getInkscapeWindow - InkscapeWindow* getInkscapeWindow(); + void scroll_absolute(Geom::Point const &point, bool is_scrolling = false); + void scroll_relative(Geom::Point const &delta, bool is_scrolling = false); + void scroll_relative_in_svg_coords(double dx, double dy, bool is_scrolling = false); + bool scroll_to_point(Geom::Point const &s_dt, gdouble autoscrollspeed = 0); + + void getWindowGeometry(gint &x, gint &y, gint &w, gint &h); + void setWindowPosition(Geom::Point p); + void setWindowSize(gint w, gint h); + void setWindowTransient(void *p, int transient_policy = 1); + Gtk::Window *getToplevel(); // To be removed in favor of getInkscapeWindow + InkscapeWindow *getInkscapeWindow(); void presentWindow(); - bool showInfoDialog( Glib::ustring const &message ); - bool warnDialog (Glib::ustring const &text); + bool showInfoDialog(Glib::ustring const &message); + bool warnDialog(Glib::ustring const &text); void toggleRulers(); void toggleScrollbars(); void layoutWidget(); void destroyWidget(); - void setToolboxFocusTo (gchar const* label); - Gtk::Toolbar* get_toolbar_by_name(const Glib::ustring& name); - void setToolboxAdjustmentValue (gchar const* id, double val); - bool isToolboxButtonActive (gchar const *id); + void setToolboxFocusTo(gchar const *label); + Gtk::Toolbar *get_toolbar_by_name(const Glib::ustring &name); + void setToolboxAdjustmentValue(gchar const *id, double val); + bool isToolboxButtonActive(gchar const *id); void updateNow(); void updateCanvasNow(); void storeDesktopPosition(); @@ -449,12 +444,12 @@ public: void show_dialogs(); // TODO return const ref instead of copy - Geom::Affine w2d() const; //transformation from window to desktop coordinates (zoom/rotate). + Geom::Affine w2d() const; // transformation from window to desktop coordinates (zoom/rotate). Geom::Point w2d(Geom::Point const &p) const; /// Transformation from desktop to window coordinates Geom::Affine d2w() const { return _current_affine.d2w(); } Geom::Point d2w(Geom::Point const &p) const; - const Geom::Affine& doc2dt() const; + const Geom::Affine &doc2dt() const; Geom::Affine dt2doc() const; Geom::Point doc2dt(Geom::Point const &p) const; Geom::Point dt2doc(Geom::Point const &p) const; @@ -462,18 +457,18 @@ public: bool is_yaxisdown() const { return doc2dt()[3] > 0; } double yaxisdir() const { return doc2dt()[3]; } - void setDocument (SPDocument* doc) override; + void setDocument(SPDocument *doc) override; bool shutdown() override; - virtual bool onDeleteUI (GdkEventAny*); - virtual bool onWindowStateEvent (GdkEventWindowState* event); + virtual bool onDeleteUI(GdkEventAny *); + virtual bool onWindowStateEvent(GdkEventWindowState *event); void applyCurrentOrToolStyle(SPObject *obj, Glib::ustring const &tool_path, bool with_text); private: GtkGesture *zoomgesture = nullptr; - SPDesktopWidget *_widget; + SPDesktopWidget *_widget; std::unique_ptr _guides_message_context; bool _active; @@ -481,43 +476,52 @@ private: // We keep rotation and scale separate to avoid having to extract them from the affine. // With offset, this describes fully how to map the drawing to the window. // Future: merge offset as a translation in w2d. - class DesktopAffine { - public: + class DesktopAffine + { + public: Geom::Affine w2d() const { return _w2d; }; Geom::Affine d2w() const { return _d2w; }; - void setScale( Geom::Scale scale ) { + void setScale(Geom::Scale scale) + { _scale = scale; _update(); } - void addScale( Geom::Scale scale) { + void addScale(Geom::Scale scale) + { _scale *= scale; _update(); } - void setRotate( Geom::Rotate rotate ) { + void setRotate(Geom::Rotate rotate) + { _rotate = rotate; _update(); } - void setRotate( double rotate ) { - _rotate = Geom::Rotate( rotate ); + void setRotate(double rotate) + { + _rotate = Geom::Rotate(rotate); _update(); } - void addRotate( Geom::Rotate rotate ) { + void addRotate(Geom::Rotate rotate) + { _rotate *= rotate; _update(); } - void addRotate( double rotate ) { - _rotate *= Geom::Rotate( rotate ); + void addRotate(double rotate) + { + _rotate *= Geom::Rotate(rotate); _update(); } - void setFlip( CanvasFlip flip ) { + void setFlip(CanvasFlip flip) + { _flip = Geom::Scale(); - addFlip( flip ); + addFlip(flip); } - bool isFlipped( CanvasFlip flip ) { + bool isFlipped(CanvasFlip flip) + { if ((flip & FLIP_HORIZONTAL) && Geom::are_near(_flip[0], -1)) { return true; } @@ -527,7 +531,8 @@ private: return false; } - void addFlip( CanvasFlip flip ) { + void addFlip(CanvasFlip flip) + { if (flip & FLIP_HORIZONTAL) { _flip *= Geom::Scale(-1.0, 1.0); } @@ -537,35 +542,26 @@ private: _update(); } - double getZoom() const { - return _d2w.descrim(); - } + double getZoom() const { return _d2w.descrim(); } - double getRotation() const { - return _rotate.angle(); - } + double getRotation() const { return _rotate.angle(); } - void setOffset( Geom::Point offset ) { - _offset = offset; - } - void addOffset( Geom::Point offset ) { - _offset += offset; - } - Geom::Point getOffset() { - return _offset; - } + void setOffset(Geom::Point offset) { _offset = offset; } + void addOffset(Geom::Point offset) { _offset += offset; } + Geom::Point getOffset() { return _offset; } - private: - void _update() { + private: + void _update() + { _d2w = _scale * _rotate * _flip; _w2d = _d2w.inverse(); - } - Geom::Affine _w2d; // Window to desktop - Geom::Affine _d2w; // Desktop to window - Geom::Rotate _rotate; // Rotate part of _w2d - Geom::Scale _scale; // Scale part of _w2d, holds y-axis direction - Geom::Scale _flip; // Flip part of _w2d - Geom::Point _offset; // Point on canvas to align to (0,0) of window + } + Geom::Affine _w2d; // Window to desktop + Geom::Affine _d2w; // Desktop to window + Geom::Rotate _rotate; // Rotate part of _w2d + Geom::Scale _scale; // Scale part of _w2d, holds y-axis direction + Geom::Scale _flip; // Flip part of _w2d + Geom::Point _offset; // Point on canvas to align to (0,0) of window }; DesktopAffine _current_affine; @@ -573,24 +569,25 @@ private: std::list transforms_future; bool _split_canvas; bool _xray; - bool _quick_zoom_enabled; ///< Signifies that currently we're in quick zoom mode - DesktopAffine _quick_zoom_affine; ///< The transform of the screen before quick zoom + bool _quick_zoom_enabled; ///< Signifies that currently we're in quick zoom mode + DesktopAffine _quick_zoom_affine; ///< The transform of the screen before quick zoom /* * Allow redrawing or refreshing if preferences change */ - class DesktopPrefObserver : public Inkscape::Preferences::Observer { - public: + class DesktopPrefObserver : public Inkscape::Preferences::Observer + { + public: DesktopPrefObserver(SPDesktop *desktop, Glib::ustring const &path) : Inkscape::Preferences::Observer(path) - , _desktop(desktop) { + , _desktop(desktop) + { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->addObserver(*this); } - private: - void notify(Inkscape::Preferences::Entry const &) override { - _desktop->redrawDesktop(); - } + + private: + void notify(Inkscape::Preferences::Entry const &) override { _desktop->redrawDesktop(); } SPDesktop *_desktop; }; @@ -599,12 +596,12 @@ private: bool grids_visible; /* don't set this variable directly, use the method below */ void set_grids_visible(bool visible); - sigc::signal _destroy_signal; - sigc::signal _document_replaced_signal; - sigc::signal _activate_signal; - sigc::signal _deactivate_signal; - sigc::signal _event_context_changed_signal; - sigc::signal _tool_subselection_changed; + sigc::signal _destroy_signal; + sigc::signal _document_replaced_signal; + sigc::signal _activate_signal; + sigc::signal _deactivate_signal; + sigc::signal _event_context_changed_signal; + sigc::signal _tool_subselection_changed; sigc::connection _activate_connection; sigc::connection _deactivate_connection; @@ -615,15 +612,15 @@ private: sigc::connection _commit_connection; sigc::connection _modified_connection; - void onResized (double, double) override; + void onResized(double, double) override; void onRedrawRequested() override; - void onStatusMessage (Inkscape::MessageType type, gchar const *message) override; - void onDocumentURISet (gchar const* uri) override; - void onDocumentResized (double, double) override; + void onStatusMessage(Inkscape::MessageType type, gchar const *message) override; + void onDocumentURISet(gchar const *uri) override; + void onDocumentResized(double, double) override; - static void _onActivate (SPDesktop* dt); - static void _onDeactivate (SPDesktop* dt); - static void _onSelectionModified (Inkscape::Selection *selection, guint flags, SPDesktop *dt); + static void _onActivate(SPDesktop *dt); + static void _onDeactivate(SPDesktop *dt); + static void _onSelectionModified(Inkscape::Selection *selection, guint flags, SPDesktop *dt); }; #endif // SEEN_SP_DESKTOP_H diff --git a/src/device-manager.cpp b/src/device-manager.cpp index e9841a34bb17aeeabe22ccb937b0c30351b5e5e9..f6dabb58c055368b08f656c9fe6a61da2c920bba 100644 --- a/src/device-manager.cpp +++ b/src/device-manager.cpp @@ -16,30 +16,26 @@ #include "preferences.h" // Only needed for gtk_accelerator_parse(). Can probably drop when we switch to Gtk+ 4 -#include - -#include - #include #include - +#include +#include #include #define noDEBUG_VERBOSE 1 - // This is a copy of the private fields of the GdkDevice object, used in order // to create a list of "fake" devices. -struct GdkDeviceFake { - Glib::ustring name; - Gdk::InputSource source; - Gdk::InputMode mode; - bool has_cursor; - int num_axes; - int num_keys; +struct GdkDeviceFake +{ + Glib::ustring name; + Gdk::InputSource source; + Gdk::InputMode mode; + bool has_cursor; + int num_axes; + int num_keys; }; - static void createFakeList(); static std::vector fakeList; @@ -47,15 +43,14 @@ static bool isValidDevice(Glib::RefPtr device) { bool valid = true; for (std::vector::iterator it = fakeList.begin(); it != fakeList.end() && valid; ++it) { - const bool name_matches = (device->get_name() == (*it).name); - const bool source_matches = (device->get_source() == (*it).source); - const bool mode_matches = (device->get_mode() == (*it).mode); - const bool num_axes_matches = (device->get_n_axes() == (*it).num_axes); - const bool num_keys_matches = (device->get_n_keys() == (*it).num_keys); - - if (name_matches && source_matches && mode_matches - && num_axes_matches && num_keys_matches) - valid = false; + const bool name_matches = (device->get_name() == (*it).name); + const bool source_matches = (device->get_source() == (*it).source); + const bool mode_matches = (device->get_mode() == (*it).mode); + const bool num_axes_matches = (device->get_n_axes() == (*it).num_axes); + const bool num_keys_matches = (device->get_n_keys() == (*it).num_keys); + + if (name_matches && source_matches && mode_matches && num_axes_matches && num_keys_matches) + valid = false; } return valid; @@ -66,16 +61,16 @@ namespace Inkscape { using std::pair; static pair vals[] = { - pair(0, 1), pair(1, 1 << 1), pair(2, 1 << 2), pair(3, 1 << 3), - pair(4, 1 << 4), pair(5, 1 << 5), pair(6, 1 << 6), pair(7, 1 << 7), - pair(8, 1 << 8), pair(9, 1 << 9), pair(10, 1 << 10), pair(11, 1 << 11), - pair(12, 1 << 12), pair(13, 1 << 13), pair(14, 1 << 14), pair(15, 1 << 15), - pair(16, 1 << 16), pair(17, 1 << 17), pair(18, 1 << 18), pair(19, 1 << 19), - pair(20, 1 << 20), pair(21, 1 << 21), pair(22, 1 << 22), pair(23, 1 << 23) -}; + pair(0, 1), pair(1, 1 << 1), pair(2, 1 << 2), + pair(3, 1 << 3), pair(4, 1 << 4), pair(5, 1 << 5), + pair(6, 1 << 6), pair(7, 1 << 7), pair(8, 1 << 8), + pair(9, 1 << 9), pair(10, 1 << 10), pair(11, 1 << 11), + pair(12, 1 << 12), pair(13, 1 << 13), pair(14, 1 << 14), + pair(15, 1 << 15), pair(16, 1 << 16), pair(17, 1 << 17), + pair(18, 1 << 18), pair(19, 1 << 19), pair(20, 1 << 20), + pair(21, 1 << 21), pair(22, 1 << 22), pair(23, 1 << 23)}; static std::map bitVals(vals, &vals[G_N_ELEMENTS(vals)]); - static const int RUNAWAY_MAX = 1000; static Glib::ustring getBaseDeviceName(Gdk::InputSource source) @@ -106,13 +101,13 @@ static std::map &getStringToAxis() static std::map mapping; if (!init) { init = true; - mapping["ignore"] = Gdk::AXIS_IGNORE; - mapping["x"] = Gdk::AXIS_X; - mapping["y"] = Gdk::AXIS_Y; + mapping["ignore"] = Gdk::AXIS_IGNORE; + mapping["x"] = Gdk::AXIS_X; + mapping["y"] = Gdk::AXIS_Y; mapping["pressure"] = Gdk::AXIS_PRESSURE; - mapping["xtilt"] = Gdk::AXIS_XTILT; - mapping["ytilt"] = Gdk::AXIS_YTILT; - mapping["wheel"] = Gdk::AXIS_WHEEL; + mapping["xtilt"] = Gdk::AXIS_XTILT; + mapping["ytilt"] = Gdk::AXIS_YTILT; + mapping["wheel"] = Gdk::AXIS_WHEEL; } return mapping; } @@ -123,7 +118,7 @@ static std::map &getAxisToString() static std::map mapping; if (!init) { init = true; - for (auto & it : getStringToAxis()) { + for (auto &it : getStringToAxis()) { mapping.insert(std::make_pair(it.second, it.first)); } } @@ -137,8 +132,8 @@ static std::map &getStringToMode() if (!init) { init = true; mapping["disabled"] = Gdk::MODE_DISABLED; - mapping["screen"] = Gdk::MODE_SCREEN; - mapping["window"] = Gdk::MODE_WINDOW; + mapping["screen"] = Gdk::MODE_SCREEN; + mapping["window"] = Gdk::MODE_WINDOW; } return mapping; } @@ -149,46 +144,45 @@ static std::map &getModeToString() static std::map mapping; if (!init) { init = true; - for (auto & it : getStringToMode()) { + for (auto &it : getStringToMode()) { mapping.insert(std::make_pair(it.second, it.first)); } } return mapping; } - - InputDevice::InputDevice() : Glib::Object() {} InputDevice::~InputDevice() = default; -class InputDeviceImpl : public InputDevice { +class InputDeviceImpl : public InputDevice +{ public: InputDeviceImpl(Glib::RefPtr device, std::set &knownIDs); ~InputDeviceImpl() override = default; - Glib::ustring getId() const override {return id;} - Glib::ustring getName() const override {return name;} - Gdk::InputSource getSource() const override {return source;} - Gdk::InputMode getMode() const override {return (device->get_mode());} - gint getNumAxes() const override {return device->get_n_axes();} - bool hasCursor() const override {return device->get_has_cursor();} - int getNumKeys() const override {return device->get_n_keys();} - Glib::ustring getLink() const override {return link;} - virtual void setLink( Glib::ustring const& link ) {this->link = link;} - gint getLiveAxes() const override {return liveAxes;} - virtual void setLiveAxes(gint axes) {liveAxes = axes;} - gint getLiveButtons() const override {return liveButtons;} - virtual void setLiveButtons(gint buttons) {liveButtons = buttons;} + Glib::ustring getId() const override { return id; } + Glib::ustring getName() const override { return name; } + Gdk::InputSource getSource() const override { return source; } + Gdk::InputMode getMode() const override { return (device->get_mode()); } + gint getNumAxes() const override { return device->get_n_axes(); } + bool hasCursor() const override { return device->get_has_cursor(); } + int getNumKeys() const override { return device->get_n_keys(); } + Glib::ustring getLink() const override { return link; } + virtual void setLink(Glib::ustring const &link) { this->link = link; } + gint getLiveAxes() const override { return liveAxes; } + virtual void setLiveAxes(gint axes) { liveAxes = axes; } + gint getLiveButtons() const override { return liveButtons; } + virtual void setLiveButtons(gint buttons) { liveButtons = buttons; } // internal methods not on public superclass: - virtual Glib::RefPtr getDevice() {return device;} + virtual Glib::RefPtr getDevice() { return device; } private: InputDeviceImpl(InputDeviceImpl const &) = delete; // no copy - void operator=(InputDeviceImpl const &) = delete; // no assign + void operator=(InputDeviceImpl const &) = delete; // no assign static Glib::ustring createId(Glib::ustring const &id, Gdk::InputSource source, std::set &knownIDs); @@ -201,40 +195,44 @@ private: guint liveButtons; }; -class IdMatcher : public std::unary_function&, bool> { +class IdMatcher : public std::unary_function &, bool> +{ public: - IdMatcher(Glib::ustring const& target):target(target) {} - bool operator ()(Glib::RefPtr& dev) {return dev && (target == dev->getId());} + IdMatcher(Glib::ustring const &target) + : target(target) + {} + bool operator()(Glib::RefPtr &dev) { return dev && (target == dev->getId()); } private: - Glib::ustring const& target; + Glib::ustring const ⌖ }; -class LinkMatcher : public std::unary_function&, bool> { +class LinkMatcher : public std::unary_function &, bool> +{ public: - LinkMatcher(Glib::ustring const& target):target(target) {} - bool operator ()(Glib::RefPtr& dev) {return dev && (target == dev->getLink());} + LinkMatcher(Glib::ustring const &target) + : target(target) + {} + bool operator()(Glib::RefPtr &dev) { return dev && (target == dev->getLink()); } private: - Glib::ustring const& target; + Glib::ustring const ⌖ }; InputDeviceImpl::InputDeviceImpl(Glib::RefPtr device, std::set &knownIDs) - : InputDevice(), - device(device), - id(), - name(!device->get_name().empty() ? device->get_name() : ""), - source(device->get_source()), - link(), - liveAxes(0), - liveButtons(0) + : InputDevice() + , device(device) + , id() + , name(!device->get_name().empty() ? device->get_name() : "") + , source(device->get_source()) + , link() + , liveAxes(0) + , liveButtons(0) { id = createId(name, source, knownIDs); } - -Glib::ustring InputDeviceImpl::createId(Glib::ustring const &id, - Gdk::InputSource source, +Glib::ustring InputDeviceImpl::createId(Glib::ustring const &id, Gdk::InputSource source, std::set &knownIDs) { // Start with only allowing printable ASCII. Check later for more refinements. @@ -244,7 +242,7 @@ Glib::ustring InputDeviceImpl::createId(Glib::ustring const &id, } Glib::ustring base; - switch ( source ) { + switch (source) { case Gdk::SOURCE_MOUSE: base = "M:"; break; @@ -278,70 +276,65 @@ Glib::ustring InputDeviceImpl::createId(Glib::ustring const &id, return result; } - - - - -class DeviceManagerImpl : public DeviceManager { +class DeviceManagerImpl : public DeviceManager +{ public: DeviceManagerImpl(); void loadConfig() override; void saveConfig() override; - std::list > getDevices() override; + std::list> getDevices() override; - sigc::signal > signalDeviceChanged() override; - sigc::signal > signalAxesChanged() override; - sigc::signal > signalButtonsChanged() override; - sigc::signal > signalLinkChanged() override; + sigc::signal> signalDeviceChanged() override; + sigc::signal> signalAxesChanged() override; + sigc::signal> signalButtonsChanged() override; + sigc::signal> signalLinkChanged() override; - void addAxis(Glib::ustring const & id, gint axis) override; - void addButton(Glib::ustring const & id, gint button) override; - void setLinkedTo(Glib::ustring const & id, Glib::ustring const& link) override; + void addAxis(Glib::ustring const &id, gint axis) override; + void addButton(Glib::ustring const &id, gint button) override; + void setLinkedTo(Glib::ustring const &id, Glib::ustring const &link) override; - void setMode( Glib::ustring const & id, Gdk::InputMode mode ) override; - void setAxisUse( Glib::ustring const & id, guint index, Gdk::AxisUse use ) override; - void setKey( Glib::ustring const & id, guint index, guint keyval, Gdk::ModifierType mods ) override; + void setMode(Glib::ustring const &id, Gdk::InputMode mode) override; + void setAxisUse(Glib::ustring const &id, guint index, Gdk::AxisUse use) override; + void setKey(Glib::ustring const &id, guint index, guint keyval, Gdk::ModifierType mods) override; protected: - std::list > devices; + std::list> devices; - sigc::signal > signalDeviceChangedPriv; - sigc::signal > signalAxesChangedPriv; - sigc::signal > signalButtonsChangedPriv; - sigc::signal > signalLinkChangedPriv; + sigc::signal> signalDeviceChangedPriv; + sigc::signal> signalAxesChangedPriv; + sigc::signal> signalButtonsChangedPriv; + sigc::signal> signalLinkChangedPriv; }; - -DeviceManagerImpl::DeviceManagerImpl() : - DeviceManager(), - devices() +DeviceManagerImpl::DeviceManagerImpl() + : DeviceManager() + , devices() { auto display = Gdk::Display::get_default(); - auto seat = display->get_default_seat(); + auto seat = display->get_default_seat(); auto devList = seat->get_slaves(Gdk::SEAT_CAPABILITY_ALL); if (fakeList.empty()) { createFakeList(); } - //devList = fakeList; + // devList = fakeList; std::set knownIDs; for (auto dev : devList) { - // GTK+ 3 has added keyboards to the list of supported devices. - if(dev->get_source() != Gdk::SOURCE_KEYBOARD) { - + // GTK+ 3 has added keyboards to the list of supported devices. + if (dev->get_source() != Gdk::SOURCE_KEYBOARD) { #if DEBUG_VERBOSE - g_message("device: name[%s] source[0x%x] mode[0x%x] cursor[%s] axis count[%d] key count[%d]", dev->name, dev->source, dev->mode, - dev->has_cursor?"Yes":"no", dev->num_axes, dev->num_keys); + g_message("device: name[%s] source[0x%x] mode[0x%x] cursor[%s] axis count[%d] key count[%d]", dev->name, + dev->source, dev->mode, dev->has_cursor ? "Yes" : "no", dev->num_axes, dev->num_keys); #endif - InputDeviceImpl* device = new InputDeviceImpl(dev, knownIDs); - device->reference(); - devices.emplace_back(device); - } + InputDeviceImpl *device = new InputDeviceImpl(dev, knownIDs); + device->reference(); + devices.emplace_back(device); + } } } @@ -349,7 +342,7 @@ void DeviceManagerImpl::loadConfig() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - for (auto & device : devices) { + for (auto &device : devices) { if (device->getSource() != Gdk::SOURCE_MOUSE) { Glib::ustring path = "/devices/" + device->getId(); @@ -359,7 +352,7 @@ void DeviceManagerImpl::loadConfig() mode = getStringToMode()[val]; } if (device->getMode() != mode) { - setMode( device->getId(), mode ); + setMode(device->getId(), mode); } // @@ -371,7 +364,7 @@ void DeviceManagerImpl::loadConfig() Glib::ustring name = parts[i]; if (getStringToAxis().find(name) != getStringToAxis().end()) { Gdk::AxisUse use = getStringToAxis()[name]; - setAxisUse( device->getId(), i, use ); + setAxisUse(device->getId(), i, use); } } } @@ -384,8 +377,8 @@ void DeviceManagerImpl::loadConfig() if (!keyStr.empty()) { guint key = 0; GdkModifierType mods = static_cast(0); - gtk_accelerator_parse( keyStr.c_str(), &key, &mods ); - setKey( device->getId(), i, key, static_cast(mods) ); + gtk_accelerator_parse(keyStr.c_str(), &key, &mods); + setKey(device->getId(), i, key, static_cast(mods)); } } } @@ -397,11 +390,11 @@ void DeviceManagerImpl::saveConfig() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - for (auto & it : devices) { + for (auto &it : devices) { if (it->getSource() != Gdk::SOURCE_MOUSE) { Glib::ustring path = "/devices/" + it->getId(); - prefs->setString( path + "/mode", getModeToString()[it->getMode()].c_str() ); + prefs->setString(path + "/mode", getModeToString()[it->getMode()].c_str()); Glib::ustring tmp; for (gint i = 0; i < it->getNumAxes(); ++i) { @@ -411,7 +404,7 @@ void DeviceManagerImpl::saveConfig() Glib::RefPtr device = it->getDevice(); tmp += getAxisToString()[device->get_axis_use(i)]; } - prefs->setString( path + "/axes", tmp ); + prefs->setString(path + "/axes", tmp); tmp = ""; for (gint i = 0; i < it->getNumKeys(); ++i) { @@ -419,32 +412,32 @@ void DeviceManagerImpl::saveConfig() tmp += ";"; } Glib::RefPtr device = it->getDevice(); - guint keyval; + guint keyval; Gdk::ModifierType modifiers; - device->get_key(i, keyval, modifiers); + device->get_key(i, keyval, modifiers); Gtk::AccelKey accelkey(keyval, modifiers); tmp += accelkey.get_abbrev(); } - prefs->setString( path + "/keys", tmp ); + prefs->setString(path + "/keys", tmp); } } } -std::list > DeviceManagerImpl::getDevices() +std::list> DeviceManagerImpl::getDevices() { - std::list > tmp; - for ( std::list >::const_iterator it = devices.begin(); it != devices.end(); ++it ) { + std::list> tmp; + for (std::list>::const_iterator it = devices.begin(); it != devices.end(); ++it) { tmp.emplace_back(*it); } return tmp; } -void DeviceManagerImpl::setMode( Glib::ustring const & id, Gdk::InputMode mode ) +void DeviceManagerImpl::setMode(Glib::ustring const &id, Gdk::InputMode mode) { - std::list >::iterator it = std::find_if(devices.begin(), devices.end(), IdMatcher(id)); - if ( it != devices.end() ) { + std::list>::iterator it = std::find_if(devices.begin(), devices.end(), IdMatcher(id)); + if (it != devices.end()) { Glib::RefPtr device = (*it)->getDevice(); - if (isValidDevice(device) && ((*it)->getMode() != mode) ) { + if (isValidDevice(device) && ((*it)->getMode() != mode)) { bool success = device->set_mode(mode); if (success) { signalDeviceChangedPriv.emit(*it); @@ -455,10 +448,10 @@ void DeviceManagerImpl::setMode( Glib::ustring const & id, Gdk::InputMode mode ) } } -void DeviceManagerImpl::setAxisUse( Glib::ustring const & id, guint index, Gdk::AxisUse use ) +void DeviceManagerImpl::setAxisUse(Glib::ustring const &id, guint index, Gdk::AxisUse use) { - std::list >::iterator it = std::find_if(devices.begin(), devices.end(), IdMatcher(id)); - if ( it != devices.end() ) { + std::list>::iterator it = std::find_if(devices.begin(), devices.end(), IdMatcher(id)); + if (it != devices.end()) { if (isValidDevice((*it)->getDevice())) { if (static_cast(index) <= (*it)->getNumAxes()) { Glib::RefPtr device = (*it)->getDevice(); @@ -474,13 +467,13 @@ void DeviceManagerImpl::setAxisUse( Glib::ustring const & id, guint index, Gdk:: } } -void DeviceManagerImpl::setKey( Glib::ustring const & id, guint index, guint keyval, Gdk::ModifierType mods ) +void DeviceManagerImpl::setKey(Glib::ustring const &id, guint index, guint keyval, Gdk::ModifierType mods) { - //static void setDeviceKey( GdkDevice* device, guint index, guint keyval, GdkModifierType modifiers ) + // static void setDeviceKey( GdkDevice* device, guint index, guint keyval, GdkModifierType modifiers ) // - std::list >::iterator it = std::find_if(devices.begin(), devices.end(), IdMatcher(id)); - if ( it != devices.end() ) { + std::list>::iterator it = std::find_if(devices.begin(), devices.end(), IdMatcher(id)); + if (it != devices.end()) { if (isValidDevice((*it)->getDevice())) { Glib::RefPtr device = (*it)->getDevice(); device->set_key(index, keyval, mods); @@ -489,33 +482,34 @@ void DeviceManagerImpl::setKey( Glib::ustring const & id, guint index, guint key } } -sigc::signal > DeviceManagerImpl::signalDeviceChanged() +sigc::signal> DeviceManagerImpl::signalDeviceChanged() { return signalDeviceChangedPriv; } -sigc::signal > DeviceManagerImpl::signalAxesChanged() +sigc::signal> DeviceManagerImpl::signalAxesChanged() { return signalAxesChangedPriv; } -sigc::signal > DeviceManagerImpl::signalButtonsChanged() +sigc::signal> DeviceManagerImpl::signalButtonsChanged() { return signalButtonsChangedPriv; } -sigc::signal > DeviceManagerImpl::signalLinkChanged() +sigc::signal> DeviceManagerImpl::signalLinkChanged() { return signalLinkChangedPriv; } -void DeviceManagerImpl::addAxis(Glib::ustring const & id, gint axis) +void DeviceManagerImpl::addAxis(Glib::ustring const &id, gint axis) { - if ( axis >= 0 && axis < static_cast(bitVals.size()) ) { - std::list >::iterator it = std::find_if(devices.begin(), devices.end(), IdMatcher(id)); - if ( it != devices.end() ) { + if (axis >= 0 && axis < static_cast(bitVals.size())) { + std::list>::iterator it = + std::find_if(devices.begin(), devices.end(), IdMatcher(id)); + if (it != devices.end()) { gint mask = bitVals[axis]; - if ( (mask & (*it)->getLiveAxes()) == 0 ) { + if ((mask & (*it)->getLiveAxes()) == 0) { (*it)->setLiveAxes((*it)->getLiveAxes() | mask); // Only signal if a new axis was added @@ -526,13 +520,14 @@ void DeviceManagerImpl::addAxis(Glib::ustring const & id, gint axis) } } -void DeviceManagerImpl::addButton(Glib::ustring const & id, gint button) +void DeviceManagerImpl::addButton(Glib::ustring const &id, gint button) { - if ( button >= 0 && button < static_cast(bitVals.size()) ) { - std::list >::iterator it = std::find_if(devices.begin(), devices.end(), IdMatcher(id)); - if ( it != devices.end() ) { + if (button >= 0 && button < static_cast(bitVals.size())) { + std::list>::iterator it = + std::find_if(devices.begin(), devices.end(), IdMatcher(id)); + if (it != devices.end()) { gint mask = bitVals[button]; - if ( (mask & (*it)->getLiveButtons()) == 0 ) { + if ((mask & (*it)->getLiveButtons()) == 0) { (*it)->setLiveButtons((*it)->getLiveButtons() | mask); // Only signal if a new button was added @@ -543,48 +538,47 @@ void DeviceManagerImpl::addButton(Glib::ustring const & id, gint button) } } -void DeviceManagerImpl::setLinkedTo(Glib::ustring const & id, Glib::ustring const& link) +void DeviceManagerImpl::setLinkedTo(Glib::ustring const &id, Glib::ustring const &link) { - std::list >::iterator it = std::find_if(devices.begin(), devices.end(), IdMatcher(id)); - if ( it != devices.end() ) { + std::list>::iterator it = std::find_if(devices.begin(), devices.end(), IdMatcher(id)); + if (it != devices.end()) { Glib::RefPtr dev = *it; Glib::RefPtr targetDev; - if ( !link.empty() ) { + if (!link.empty()) { // Need to be sure the target of the link exists it = std::find_if(devices.begin(), devices.end(), IdMatcher(link)); - if ( it != devices.end() ) { + if (it != devices.end()) { targetDev = *it; } } - - if ( (link.empty() && !dev->getLink().empty()) - || (targetDev && (targetDev->getLink() != id)) ) { + if ((link.empty() && !dev->getLink().empty()) || (targetDev && (targetDev->getLink() != id))) { // only muck about if they aren't already linked - std::list > changedItems; + std::list> changedItems; - if ( targetDev ) { - // Is something else already using that link? + if (targetDev) { + // Is something else already using that link? it = std::find_if(devices.begin(), devices.end(), LinkMatcher(link)); - if ( it != devices.end() ) { + if (it != devices.end()) { (*it)->setLink(""); changedItems.push_back(*it); } } it = std::find_if(devices.begin(), devices.end(), LinkMatcher(id)); - if ( it != devices.end() ) { + if (it != devices.end()) { (*it)->setLink(""); changedItems.push_back(*it); } - if ( targetDev ) { + if (targetDev) { targetDev->setLink(id); changedItems.push_back(targetDev); } dev->setLink(link); changedItems.push_back(dev); - for ( std::list >::const_iterator iter = changedItems.begin(); iter != changedItems.end(); ++iter ) { + for (std::list>::const_iterator iter = changedItems.begin(); + iter != changedItems.end(); ++iter) { (*iter)->reference(); signalLinkChangedPriv.emit(*iter); } @@ -592,22 +586,17 @@ void DeviceManagerImpl::setLinkedTo(Glib::ustring const & id, Glib::ustring cons } } - - - - - -static DeviceManagerImpl* theInstance = nullptr; +static DeviceManagerImpl *theInstance = nullptr; DeviceManager::DeviceManager() : Glib::Object() -{ -} +{} DeviceManager::~DeviceManager() = default; -DeviceManager& DeviceManager::getManager() { - if ( !theInstance ) { +DeviceManager &DeviceManager::getManager() +{ + if (!theInstance) { theInstance = new DeviceManagerImpl(); } @@ -616,45 +605,45 @@ DeviceManager& DeviceManager::getManager() { } // namespace Inkscape - -static void createFakeList() { +static void createFakeList() +{ if (fakeList.empty()) { fakeList.resize(5); - fakeList[0].name = "pad"; - fakeList[0].source = Gdk::SOURCE_PEN; - fakeList[0].mode = Gdk::MODE_SCREEN; + fakeList[0].name = "pad"; + fakeList[0].source = Gdk::SOURCE_PEN; + fakeList[0].mode = Gdk::MODE_SCREEN; fakeList[0].has_cursor = true; - fakeList[0].num_axes = 6; - fakeList[0].num_keys = 8; + fakeList[0].num_axes = 6; + fakeList[0].num_keys = 8; - fakeList[1].name = "eraser"; - fakeList[1].source = Gdk::SOURCE_ERASER; - fakeList[1].mode = Gdk::MODE_SCREEN; + fakeList[1].name = "eraser"; + fakeList[1].source = Gdk::SOURCE_ERASER; + fakeList[1].mode = Gdk::MODE_SCREEN; fakeList[1].has_cursor = true; - fakeList[1].num_axes = 6; - fakeList[1].num_keys = 7; + fakeList[1].num_axes = 6; + fakeList[1].num_keys = 7; - fakeList[2].name = "cursor"; - fakeList[2].source = Gdk::SOURCE_CURSOR; - fakeList[2].mode = Gdk::MODE_SCREEN; + fakeList[2].name = "cursor"; + fakeList[2].source = Gdk::SOURCE_CURSOR; + fakeList[2].mode = Gdk::MODE_SCREEN; fakeList[2].has_cursor = true; - fakeList[2].num_axes = 6; - fakeList[2].num_keys = 7; + fakeList[2].num_axes = 6; + fakeList[2].num_keys = 7; - fakeList[3].name = "stylus"; - fakeList[3].source = Gdk::SOURCE_PEN; - fakeList[3].mode = Gdk::MODE_SCREEN; + fakeList[3].name = "stylus"; + fakeList[3].source = Gdk::SOURCE_PEN; + fakeList[3].mode = Gdk::MODE_SCREEN; fakeList[3].has_cursor = true; - fakeList[3].num_axes = 6; - fakeList[3].num_keys = 7; + fakeList[3].num_axes = 6; + fakeList[3].num_keys = 7; // try to find the first *real* core pointer auto display = Gdk::Display::get_default(); - auto seat = display->get_default_seat(); + auto seat = display->get_default_seat(); auto devList = seat->get_slaves(Gdk::SEAT_CAPABILITY_ALL); // Set iterator to point at beginning of device list - std::vector< Glib::RefPtr >::iterator dev = devList.begin(); + std::vector>::iterator dev = devList.begin(); // Skip past any items in the device list that are not mice while (dev != devList.end() && (*dev)->get_source() != Gdk::SOURCE_MOUSE) { @@ -663,19 +652,19 @@ static void createFakeList() { if (dev != devList.end()) { Glib::RefPtr device = *dev; - fakeList[4].name = device->get_name(); - fakeList[4].source = device->get_source(); - fakeList[4].mode = device->get_mode(); + fakeList[4].name = device->get_name(); + fakeList[4].source = device->get_source(); + fakeList[4].mode = device->get_mode(); fakeList[4].has_cursor = device->get_has_cursor(); - fakeList[4].num_axes = device->get_n_axes(); - fakeList[4].num_keys = device->get_n_keys(); + fakeList[4].num_axes = device->get_n_axes(); + fakeList[4].num_keys = device->get_n_keys(); } else { - fakeList[4].name = "Core Pointer"; - fakeList[4].source = Gdk::SOURCE_MOUSE; - fakeList[4].mode = Gdk::MODE_SCREEN; + fakeList[4].name = "Core Pointer"; + fakeList[4].source = Gdk::SOURCE_MOUSE; + fakeList[4].mode = Gdk::MODE_SCREEN; fakeList[4].has_cursor = true; - fakeList[4].num_axes = 2; - fakeList[4].num_keys = 0; + fakeList[4].num_axes = 2; + fakeList[4].num_keys = 0; } } } diff --git a/src/device-manager.h b/src/device-manager.h index 07f4508cecf9ab05b9eabfdb78e4129760b1f224..85754b1d78ef786734efe4702d08d8fb3753a121 100644 --- a/src/device-manager.h +++ b/src/device-manager.h @@ -10,14 +10,14 @@ #ifndef SEEN_INKSCAPE_DEVICE_MANAGER_H #define SEEN_INKSCAPE_DEVICE_MANAGER_H - #include -#include #include +#include namespace Inkscape { -class InputDevice : public Glib::Object { +class InputDevice : public Glib::Object +{ public: virtual Glib::ustring getId() const = 0; virtual Glib::ustring getName() const = 0; @@ -35,43 +35,42 @@ protected: ~InputDevice() override; private: - InputDevice(InputDevice const &) = delete; // no copy + InputDevice(InputDevice const &) = delete; // no copy void operator=(InputDevice const &) = delete; // no assign }; -class DeviceManager : public Glib::Object { +class DeviceManager : public Glib::Object +{ public: - static DeviceManager& getManager(); + static DeviceManager &getManager(); virtual void loadConfig() = 0; virtual void saveConfig() = 0; - virtual std::list > getDevices() = 0; + virtual std::list> getDevices() = 0; - virtual sigc::signal > signalDeviceChanged() = 0; - virtual sigc::signal > signalAxesChanged() = 0; - virtual sigc::signal > signalButtonsChanged() = 0; - virtual sigc::signal > signalLinkChanged() = 0; + virtual sigc::signal> signalDeviceChanged() = 0; + virtual sigc::signal> signalAxesChanged() = 0; + virtual sigc::signal> signalButtonsChanged() = 0; + virtual sigc::signal> signalLinkChanged() = 0; - virtual void addAxis(Glib::ustring const & id, gint axis) = 0; - virtual void addButton(Glib::ustring const & id, gint button) = 0; - virtual void setLinkedTo(Glib::ustring const & id, Glib::ustring const& link) = 0; + virtual void addAxis(Glib::ustring const &id, gint axis) = 0; + virtual void addButton(Glib::ustring const &id, gint button) = 0; + virtual void setLinkedTo(Glib::ustring const &id, Glib::ustring const &link) = 0; - virtual void setMode( Glib::ustring const & id, Gdk::InputMode mode ) = 0; - virtual void setAxisUse( Glib::ustring const & id, guint index, Gdk::AxisUse use ) = 0; - virtual void setKey( Glib::ustring const & id, guint index, guint keyval, Gdk::ModifierType mods ) = 0; + virtual void setMode(Glib::ustring const &id, Gdk::InputMode mode) = 0; + virtual void setAxisUse(Glib::ustring const &id, guint index, Gdk::AxisUse use) = 0; + virtual void setKey(Glib::ustring const &id, guint index, guint keyval, Gdk::ModifierType mods) = 0; protected: DeviceManager(); ~DeviceManager() override; private: - DeviceManager(DeviceManager const &) = delete; // no copy + DeviceManager(DeviceManager const &) = delete; // no copy void operator=(DeviceManager const &) = delete; // no assign }; - - } // namespace Inkscape #endif // SEEN_INKSCAPE_DEVICE_MANAGER_H diff --git a/src/display/cairo-templates.h b/src/display/cairo-templates.h index 9a3dd66da0a51d9a97cd508202c70d0f146e64f8..45d08df855531729084d7dabb3912082a44fbee4 100644 --- a/src/display/cairo-templates.h +++ b/src/display/cairo-templates.h @@ -14,13 +14,14 @@ #define SEEN_INKSCAPE_DISPLAY_CAIRO_TEMPLATES_H #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include #ifdef HAVE_OPENMP #include + #include "preferences.h" // single-threaded operation if the number of pixels is below this threshold static const int OPENMP_THRESHOLD = 2048; @@ -29,8 +30,9 @@ static const int OPENMP_THRESHOLD = 2048; #include #include #include -#include "display/nr-3dutils.h" + #include "display/cairo-utils.h" +#include "display/nr-3dutils.h" /** * Blend two surfaces using the supplied functor. @@ -53,11 +55,11 @@ void ink_cairo_surface_blend(cairo_surface_t *in1, cairo_surface_t *in2, cairo_s int w = cairo_image_surface_get_width(in2); int h = cairo_image_surface_get_height(in2); - int stride1 = cairo_image_surface_get_stride(in1); - int stride2 = cairo_image_surface_get_stride(in2); + int stride1 = cairo_image_surface_get_stride(in1); + int stride2 = cairo_image_surface_get_stride(in2); int strideout = cairo_image_surface_get_stride(out); - int bpp1 = cairo_image_surface_get_format(in1) == CAIRO_FORMAT_A8 ? 1 : 4; - int bpp2 = cairo_image_surface_get_format(in2) == CAIRO_FORMAT_A8 ? 1 : 4; + int bpp1 = cairo_image_surface_get_format(in1) == CAIRO_FORMAT_A8 ? 1 : 4; + int bpp2 = cairo_image_surface_get_format(in2) == CAIRO_FORMAT_A8 ? 1 : 4; int bppout = std::max(bpp1, bpp2); // Check whether we can loop over pixels without taking stride into account. @@ -68,106 +70,119 @@ void ink_cairo_surface_blend(cairo_surface_t *in1, cairo_surface_t *in2, cairo_s int limit = w * h; - guint32 *const in1_data = reinterpret_cast(cairo_image_surface_get_data(in1)); - guint32 *const in2_data = reinterpret_cast(cairo_image_surface_get_data(in2)); - guint32 *const out_data = reinterpret_cast(cairo_image_surface_get_data(out)); + guint32 *const in1_data = reinterpret_cast(cairo_image_surface_get_data(in1)); + guint32 *const in2_data = reinterpret_cast(cairo_image_surface_get_data(in2)); + guint32 *const out_data = reinterpret_cast(cairo_image_surface_get_data(out)); - // NOTE - // OpenMP probably doesn't help much here. - // It would be better to render more than 1 tile at a time. - #if HAVE_OPENMP +// NOTE +// OpenMP probably doesn't help much here. +// It would be better to render more than 1 tile at a time. +#if HAVE_OPENMP Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int numOfThreads = prefs->getIntLimited("/options/threading/numthreads", omp_get_num_procs(), 1, 256); - if (numOfThreads){} // inform compiler we are using it. - #endif + if (numOfThreads) { + } // inform compiler we are using it. +#endif // The number of code paths here is evil. if (bpp1 == 4) { if (bpp2 == 4) { if (fast_path) { - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < limit; ++i) { *(out_data + i) = blend(*(in1_data + i), *(in2_data + i)); } } else { - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < h; ++i) { - guint32 *in1_p = in1_data + i * stride1/4; - guint32 *in2_p = in2_data + i * stride2/4; - guint32 *out_p = out_data + i * strideout/4; + guint32 *in1_p = in1_data + i * stride1 / 4; + guint32 *in2_p = in2_data + i * stride2 / 4; + guint32 *out_p = out_data + i * strideout / 4; for (int j = 0; j < w; ++j) { *out_p = blend(*in1_p, *in2_p); - ++in1_p; ++in2_p; ++out_p; + ++in1_p; + ++in2_p; + ++out_p; } } } } else { - // bpp2 == 1 - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +// bpp2 == 1 +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < h; ++i) { - guint32 *in1_p = in1_data + i * stride1/4; - guint8 *in2_p = reinterpret_cast(in2_data) + i * stride2; - guint32 *out_p = out_data + i * strideout/4; + guint32 *in1_p = in1_data + i * stride1 / 4; + guint8 *in2_p = reinterpret_cast(in2_data) + i * stride2; + guint32 *out_p = out_data + i * strideout / 4; for (int j = 0; j < w; ++j) { guint32 in2_px = *in2_p; in2_px <<= 24; *out_p = blend(*in1_p, in2_px); - ++in1_p; ++in2_p; ++out_p; + ++in1_p; + ++in2_p; + ++out_p; } } } } else { if (bpp2 == 4) { - // bpp1 == 1 - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +// bpp1 == 1 +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < h; ++i) { - guint8 *in1_p = reinterpret_cast(in1_data) + i * stride1; - guint32 *in2_p = in2_data + i * stride2/4; - guint32 *out_p = out_data + i * strideout/4; + guint8 *in1_p = reinterpret_cast(in1_data) + i * stride1; + guint32 *in2_p = in2_data + i * stride2 / 4; + guint32 *out_p = out_data + i * strideout / 4; for (int j = 0; j < w; ++j) { guint32 in1_px = *in1_p; in1_px <<= 24; *out_p = blend(in1_px, *in2_p); - ++in1_p; ++in2_p; ++out_p; + ++in1_p; + ++in2_p; + ++out_p; } } } else { // bpp1 == 1 && bpp2 == 1 if (fast_path) { - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < limit; ++i) { - guint8 *in1_p = reinterpret_cast(in1_data) + i; - guint8 *in2_p = reinterpret_cast(in2_data) + i; - guint8 *out_p = reinterpret_cast(out_data) + i; - guint32 in1_px = *in1_p; in1_px <<= 24; - guint32 in2_px = *in2_p; in2_px <<= 24; + guint8 *in1_p = reinterpret_cast(in1_data) + i; + guint8 *in2_p = reinterpret_cast(in2_data) + i; + guint8 *out_p = reinterpret_cast(out_data) + i; + guint32 in1_px = *in1_p; + in1_px <<= 24; + guint32 in2_px = *in2_p; + in2_px <<= 24; guint32 out_px = blend(in1_px, in2_px); *out_p = out_px >> 24; } } else { - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < h; ++i) { - guint8 *in1_p = reinterpret_cast(in1_data) + i * stride1; - guint8 *in2_p = reinterpret_cast(in2_data) + i * stride2; - guint8 *out_p = reinterpret_cast(out_data) + i * strideout; + guint8 *in1_p = reinterpret_cast(in1_data) + i * stride1; + guint8 *in2_p = reinterpret_cast(in2_data) + i * stride2; + guint8 *out_p = reinterpret_cast(out_data) + i * strideout; for (int j = 0; j < w; ++j) { - guint32 in1_px = *in1_p; in1_px <<= 24; - guint32 in2_px = *in2_p; in2_px <<= 24; + guint32 in1_px = *in1_p; + in1_px <<= 24; + guint32 in2_px = *in2_p; + in2_px <<= 24; guint32 out_px = blend(in1_px, in2_px); *out_p = out_px >> 24; - ++in1_p; ++in2_p; ++out_p; + ++in1_p; + ++in2_p; + ++out_p; } } } @@ -190,7 +205,7 @@ void ink_cairo_surface_filter(cairo_surface_t *in, cairo_surface_t *out, Filter int w = cairo_image_surface_get_width(in); int h = cairo_image_surface_get_height(in); - int stridein = cairo_image_surface_get_stride(in); + int stridein = cairo_image_surface_get_stride(in); int strideout = cairo_image_surface_get_stride(out); int bppin = cairo_image_surface_get_format(in) == CAIRO_FORMAT_A8 ? 1 : 4; int bppout = cairo_image_surface_get_format(out) == CAIRO_FORMAT_A8 ? 1 : 4; @@ -201,31 +216,33 @@ void ink_cairo_surface_filter(cairo_surface_t *in, cairo_surface_t *out, Filter fast_path &= (stridein == w * bppin); fast_path &= (strideout == w * bppout); - guint32 *const in_data = reinterpret_cast(cairo_image_surface_get_data(in)); - guint32 *const out_data = reinterpret_cast(cairo_image_surface_get_data(out)); + guint32 *const in_data = reinterpret_cast(cairo_image_surface_get_data(in)); + guint32 *const out_data = reinterpret_cast(cairo_image_surface_get_data(out)); - #if HAVE_OPENMP +#if HAVE_OPENMP Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int numOfThreads = prefs->getIntLimited("/options/threading/numthreads", omp_get_num_procs(), 1, 256); - if (numOfThreads){} // inform compiler we are using it. - #endif + if (numOfThreads) { + } // inform compiler we are using it. +#endif // this is provided just in case, to avoid problems with strict aliasing rules if (in == out) { if (bppin == 4) { - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < limit; ++i) { *(in_data + i) = filter(*(in_data + i)); } } else { - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < limit; ++i) { - guint8 *in_p = reinterpret_cast(in_data) + i; - guint32 in_px = *in_p; in_px <<= 24; + guint8 *in_p = reinterpret_cast(in_data) + i; + guint32 in_px = *in_p; + in_px <<= 24; guint32 out_px = filter(in_px); *in_p = out_px >> 24; } @@ -238,38 +255,40 @@ void ink_cairo_surface_filter(cairo_surface_t *in, cairo_surface_t *out, Filter if (bppout == 4) { // bppin == 4, bppout == 4 if (fast_path) { - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < limit; ++i) { *(out_data + i) = filter(*(in_data + i)); } } else { - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < h; ++i) { - guint32 *in_p = in_data + i * stridein/4; - guint32 *out_p = out_data + i * strideout/4; + guint32 *in_p = in_data + i * stridein / 4; + guint32 *out_p = out_data + i * strideout / 4; for (int j = 0; j < w; ++j) { *out_p = filter(*in_p); - ++in_p; ++out_p; + ++in_p; + ++out_p; } } } } else { - // bppin == 4, bppout == 1 - // we use this path with COLORMATRIX_LUMINANCETOALPHA - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +// bppin == 4, bppout == 1 +// we use this path with COLORMATRIX_LUMINANCETOALPHA +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < h; ++i) { - guint32 *in_p = in_data + i * stridein/4; - guint8 *out_p = reinterpret_cast(out_data) + i * strideout; + guint32 *in_p = in_data + i * stridein / 4; + guint8 *out_p = reinterpret_cast(out_data) + i * strideout; for (int j = 0; j < w; ++j) { guint32 out_px = filter(*in_p); *out_p = out_px >> 24; - ++in_p; ++out_p; + ++in_p; + ++out_p; } } } @@ -277,28 +296,31 @@ void ink_cairo_surface_filter(cairo_surface_t *in, cairo_surface_t *out, Filter // bppin == 1, bppout == 1 // Note: there is no path for bppin == 1, bppout == 4 because it is useless if (fast_path) { - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < limit; ++i) { - guint8 *in_p = reinterpret_cast(in_data) + i; - guint8 *out_p = reinterpret_cast(out_data) + i; - guint32 in_px = *in_p; in_px <<= 24; + guint8 *in_p = reinterpret_cast(in_data) + i; + guint8 *out_p = reinterpret_cast(out_data) + i; + guint32 in_px = *in_p; + in_px <<= 24; guint32 out_px = filter(in_px); *out_p = out_px >> 24; } } else { - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = 0; i < h; ++i) { - guint8 *in_p = reinterpret_cast(in_data) + i * stridein; - guint8 *out_p = reinterpret_cast(out_data) + i * strideout; + guint8 *in_p = reinterpret_cast(in_data) + i * stridein; + guint8 *out_p = reinterpret_cast(out_data) + i * strideout; for (int j = 0; j < w; ++j) { - guint32 in_px = *in_p; in_px <<= 24; + guint32 in_px = *in_p; + in_px <<= 24; guint32 out_px = filter(in_px); *out_p = out_px >> 24; - ++in_p; ++out_p; + ++in_p; + ++out_p; } } } @@ -306,7 +328,6 @@ void ink_cairo_surface_filter(cairo_surface_t *in, cairo_surface_t *out, Filter cairo_surface_mark_dirty(out); } - /** * Synthesize surface pixels based on their position. * This template accepts a functor that gets called with the x and y coordinates of the pixels, @@ -330,29 +351,30 @@ void ink_cairo_surface_synthesize(cairo_surface_t *out, cairo_rectangle_t const unsigned char *out_data = cairo_image_surface_get_data(out); - #if HAVE_OPENMP +#if HAVE_OPENMP int limit = w * h; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int numOfThreads = prefs->getIntLimited("/options/threading/numthreads", omp_get_num_procs(), 1, 256); - if (numOfThreads){} // inform compiler we are using it. - #endif + if (numOfThreads) { + } // inform compiler we are using it. +#endif if (bppout == 4) { - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = out_area.y; i < h; ++i) { - guint32 *out_p = reinterpret_cast(out_data + i * strideout); + guint32 *out_p = reinterpret_cast(out_data + i * strideout); for (int j = out_area.x; j < w; ++j) { *out_p = synth(j, i); ++out_p; } } } else { - // bppout == 1 - #if HAVE_OPENMP - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif +// bppout == 1 +#if HAVE_OPENMP +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif for (int i = out_area.y; i < h; ++i) { guint8 *out_p = out_data + i * strideout; for (int j = out_area.x; j < w; ++j) { @@ -380,7 +402,8 @@ void ink_cairo_surface_synthesize(cairo_surface_t *out, Synth synth) ink_cairo_surface_synthesize(out, area, synth); } -struct SurfaceSynth { +struct SurfaceSynth +{ SurfaceSynth(cairo_surface_t *surface) : _px(cairo_image_surface_get_data(surface)) , _w(cairo_image_surface_get_width(surface)) @@ -391,28 +414,31 @@ struct SurfaceSynth { cairo_surface_flush(surface); } - guint32 pixelAt(int x, int y) const { + guint32 pixelAt(int x, int y) const + { if (_alpha) { - unsigned char *px = _px + y*_stride + x; + unsigned char *px = _px + y * _stride + x; return *px << 24; } else { - unsigned char *px = _px + y*_stride + x*4; - return *reinterpret_cast(px); + unsigned char *px = _px + y * _stride + x * 4; + return *reinterpret_cast(px); } } - guint32 alphaAt(int x, int y) const { + guint32 alphaAt(int x, int y) const + { if (_alpha) { - unsigned char *px = _px + y*_stride + x; + unsigned char *px = _px + y * _stride + x; return *px; } else { - unsigned char *px = _px + y*_stride + x*4; - guint32 p = *reinterpret_cast(px); + unsigned char *px = _px + y * _stride + x * 4; + guint32 p = *reinterpret_cast(px); return (p & 0xff000000) >> 24; } } // retrieve a pixel value with bilinear interpolation - guint32 pixelAt(double x, double y) const { + guint32 pixelAt(double x, double y) const + { if (_alpha) { return alphaAt(x, y) << 24; } @@ -422,26 +448,28 @@ struct SurfaceSynth { guint32 xif = round((x - xf) * 255), yif = round((y - yf) * 255); guint32 p00, p01, p10, p11; - unsigned char *pxi = _px + yi*_stride + xi*4; - guint32 *pxu = reinterpret_cast(pxi); - guint32 *pxl = reinterpret_cast(pxi + _stride); - p00 = *pxu; p10 = *(pxu + 1); - p01 = *pxl; p11 = *(pxl + 1); + unsigned char *pxi = _px + yi * _stride + xi * 4; + guint32 *pxu = reinterpret_cast(pxi); + guint32 *pxl = reinterpret_cast(pxi + _stride); + p00 = *pxu; + p10 = *(pxu + 1); + p01 = *pxl; + p11 = *(pxl + 1); guint32 comp[4]; for (unsigned i = 0; i < 4; ++i) { - guint32 shift = i*8; + guint32 shift = i * 8; guint32 mask = 0xff << shift; guint32 c00 = (p00 & mask) >> shift; guint32 c10 = (p10 & mask) >> shift; guint32 c01 = (p01 & mask) >> shift; guint32 c11 = (p11 & mask) >> shift; - guint32 iu = (255-xif) * c00 + xif * c10; - guint32 il = (255-xif) * c01 + xif * c11; - comp[i] = (255-yif) * iu + yif * il; - comp[i] = (comp[i] + (255*255/2)) / (255*255); + guint32 iu = (255 - xif) * c00 + xif * c10; + guint32 il = (255 - xif) * c01 + xif * c11; + comp[i] = (255 - yif) * iu + yif * il; + comp[i] = (comp[i] + (255 * 255 / 2)) / (255 * 255); } guint32 result = comp[0] | (comp[1] << 8) | (comp[2] << 16) | (comp[3] << 24); @@ -449,164 +477,129 @@ struct SurfaceSynth { } // retrieve an alpha value with bilinear interpolation - guint32 alphaAt(double x, double y) const { + guint32 alphaAt(double x, double y) const + { double xf = floor(x), yf = floor(y); int xi = xf, yi = yf; guint32 xif = round((x - xf) * 255), yif = round((y - yf) * 255); guint32 p00, p01, p10, p11; if (_alpha) { - unsigned char *pxu = _px + yi*_stride + xi; + unsigned char *pxu = _px + yi * _stride + xi; unsigned char *pxl = pxu + _stride; - p00 = *pxu; p10 = *(pxu + 1); - p01 = *pxl; p11 = *(pxl + 1); + p00 = *pxu; + p10 = *(pxu + 1); + p01 = *pxl; + p11 = *(pxl + 1); } else { - unsigned char *pxi = _px + yi*_stride + xi*4; - guint32 *pxu = reinterpret_cast(pxi); - guint32 *pxl = reinterpret_cast(pxi + _stride); - p00 = (*pxu & 0xff000000) >> 24; p10 = (*(pxu + 1) & 0xff000000) >> 24; - p01 = (*pxl & 0xff000000) >> 24; p11 = (*(pxl + 1) & 0xff000000) >> 24; + unsigned char *pxi = _px + yi * _stride + xi * 4; + guint32 *pxu = reinterpret_cast(pxi); + guint32 *pxl = reinterpret_cast(pxi + _stride); + p00 = (*pxu & 0xff000000) >> 24; + p10 = (*(pxu + 1) & 0xff000000) >> 24; + p01 = (*pxl & 0xff000000) >> 24; + p11 = (*(pxl + 1) & 0xff000000) >> 24; } - guint32 iu = (255-xif) * p00 + xif * p10; - guint32 il = (255-xif) * p01 + xif * p11; - guint32 result = (255-yif) * iu + yif * il; - result = (result + (255*255/2)) / (255*255); + guint32 iu = (255 - xif) * p00 + xif * p10; + guint32 il = (255 - xif) * p01 + xif * p11; + guint32 result = (255 - yif) * iu + yif * il; + result = (result + (255 * 255 / 2)) / (255 * 255); return result; } // compute surface normal at given coordinates using 3x3 Sobel gradient filter - NR::Fvector surfaceNormalAt(int x, int y, double scale) const { + NR::Fvector surfaceNormalAt(int x, int y, double scale) const + { // Below there are some multiplies by zero. They will be optimized out. // Do not remove them, because they improve readability. // NOTE: fetching using alphaAt is slightly lazy. NR::Fvector normal; - double fx = -scale/255.0, fy = -scale/255.0; + double fx = -scale / 255.0, fy = -scale / 255.0; normal[Z_3D] = 1.0; if (G_UNLIKELY(x == 0)) { // leftmost column if (G_UNLIKELY(y == 0)) { // upper left corner - fx *= (2.0/3.0); - fy *= (2.0/3.0); - double p00 = alphaAt(x,y), p10 = alphaAt(x+1, y), - p01 = alphaAt(x,y+1), p11 = alphaAt(x+1, y+1); - normal[X_3D] = - -2.0 * p00 +2.0 * p10 - -1.0 * p01 +1.0 * p11; - normal[Y_3D] = - -2.0 * p00 -1.0 * p10 - +2.0 * p01 +1.0 * p11; + fx *= (2.0 / 3.0); + fy *= (2.0 / 3.0); + double p00 = alphaAt(x, y), p10 = alphaAt(x + 1, y), p01 = alphaAt(x, y + 1), + p11 = alphaAt(x + 1, y + 1); + normal[X_3D] = -2.0 * p00 + 2.0 * p10 - 1.0 * p01 + 1.0 * p11; + normal[Y_3D] = -2.0 * p00 - 1.0 * p10 + 2.0 * p01 + 1.0 * p11; } else if (G_UNLIKELY(y == (_h - 1))) { // lower left corner - fx *= (2.0/3.0); - fy *= (2.0/3.0); - double p00 = alphaAt(x,y-1), p10 = alphaAt(x+1, y-1), - p01 = alphaAt(x,y ), p11 = alphaAt(x+1, y); - normal[X_3D] = - -1.0 * p00 +1.0 * p10 - -2.0 * p01 +2.0 * p11; - normal[Y_3D] = - -2.0 * p00 -1.0 * p10 - +2.0 * p01 +1.0 * p11; + fx *= (2.0 / 3.0); + fy *= (2.0 / 3.0); + double p00 = alphaAt(x, y - 1), p10 = alphaAt(x + 1, y - 1), p01 = alphaAt(x, y), + p11 = alphaAt(x + 1, y); + normal[X_3D] = -1.0 * p00 + 1.0 * p10 - 2.0 * p01 + 2.0 * p11; + normal[Y_3D] = -2.0 * p00 - 1.0 * p10 + 2.0 * p01 + 1.0 * p11; } else { // leftmost column - fx *= (1.0/2.0); - fy *= (1.0/3.0); - double p00 = alphaAt(x, y-1), p10 = alphaAt(x+1, y-1), - p01 = alphaAt(x, y ), p11 = alphaAt(x+1, y ), - p02 = alphaAt(x, y+1), p12 = alphaAt(x+1, y+1); - normal[X_3D] = - -1.0 * p00 +1.0 * p10 - -2.0 * p01 +2.0 * p11 - -1.0 * p02 +1.0 * p12; - normal[Y_3D] = - -2.0 * p00 -1.0 * p10 - +0.0 * p01 +0.0 * p11 // this will be optimized out - +2.0 * p02 +1.0 * p12; + fx *= (1.0 / 2.0); + fy *= (1.0 / 3.0); + double p00 = alphaAt(x, y - 1), p10 = alphaAt(x + 1, y - 1), p01 = alphaAt(x, y), + p11 = alphaAt(x + 1, y), p02 = alphaAt(x, y + 1), p12 = alphaAt(x + 1, y + 1); + normal[X_3D] = -1.0 * p00 + 1.0 * p10 - 2.0 * p01 + 2.0 * p11 - 1.0 * p02 + 1.0 * p12; + normal[Y_3D] = -2.0 * p00 - 1.0 * p10 + 0.0 * p01 + 0.0 * p11 // this will be optimized out + + 2.0 * p02 + 1.0 * p12; } } else if (G_UNLIKELY(x == (_w - 1))) { // rightmost column if (G_UNLIKELY(y == 0)) { // top right corner - fx *= (2.0/3.0); - fy *= (2.0/3.0); - double p00 = alphaAt(x-1,y), p10 = alphaAt(x, y), - p01 = alphaAt(x-1,y+1), p11 = alphaAt(x, y+1); - normal[X_3D] = - -2.0 * p00 +2.0 * p10 - -1.0 * p01 +1.0 * p11; - normal[Y_3D] = - -1.0 * p00 -2.0 * p10 - +1.0 * p01 +2.0 * p11; + fx *= (2.0 / 3.0); + fy *= (2.0 / 3.0); + double p00 = alphaAt(x - 1, y), p10 = alphaAt(x, y), p01 = alphaAt(x - 1, y + 1), + p11 = alphaAt(x, y + 1); + normal[X_3D] = -2.0 * p00 + 2.0 * p10 - 1.0 * p01 + 1.0 * p11; + normal[Y_3D] = -1.0 * p00 - 2.0 * p10 + 1.0 * p01 + 2.0 * p11; } else if (G_UNLIKELY(y == (_h - 1))) { // bottom right corner - fx *= (2.0/3.0); - fy *= (2.0/3.0); - double p00 = alphaAt(x-1,y-1), p10 = alphaAt(x, y-1), - p01 = alphaAt(x-1,y ), p11 = alphaAt(x, y); - normal[X_3D] = - -1.0 * p00 +1.0 * p10 - -2.0 * p01 +2.0 * p11; - normal[Y_3D] = - -1.0 * p00 -2.0 * p10 - +1.0 * p01 +2.0 * p11; + fx *= (2.0 / 3.0); + fy *= (2.0 / 3.0); + double p00 = alphaAt(x - 1, y - 1), p10 = alphaAt(x, y - 1), p01 = alphaAt(x - 1, y), + p11 = alphaAt(x, y); + normal[X_3D] = -1.0 * p00 + 1.0 * p10 - 2.0 * p01 + 2.0 * p11; + normal[Y_3D] = -1.0 * p00 - 2.0 * p10 + 1.0 * p01 + 2.0 * p11; } else { // rightmost column - fx *= (1.0/2.0); - fy *= (1.0/3.0); - double p00 = alphaAt(x-1, y-1), p10 = alphaAt(x, y-1), - p01 = alphaAt(x-1, y ), p11 = alphaAt(x, y ), - p02 = alphaAt(x-1, y+1), p12 = alphaAt(x, y+1); - normal[X_3D] = - -1.0 * p00 +1.0 * p10 - -2.0 * p01 +2.0 * p11 - -1.0 * p02 +1.0 * p12; - normal[Y_3D] = - -1.0 * p00 -2.0 * p10 - +0.0 * p01 +0.0 * p11 - +1.0 * p02 +2.0 * p12; + fx *= (1.0 / 2.0); + fy *= (1.0 / 3.0); + double p00 = alphaAt(x - 1, y - 1), p10 = alphaAt(x, y - 1), p01 = alphaAt(x - 1, y), + p11 = alphaAt(x, y), p02 = alphaAt(x - 1, y + 1), p12 = alphaAt(x, y + 1); + normal[X_3D] = -1.0 * p00 + 1.0 * p10 - 2.0 * p01 + 2.0 * p11 - 1.0 * p02 + 1.0 * p12; + normal[Y_3D] = -1.0 * p00 - 2.0 * p10 + 0.0 * p01 + 0.0 * p11 + 1.0 * p02 + 2.0 * p12; } } else { // interior if (G_UNLIKELY(y == 0)) { // top row - fx *= (1.0/3.0); - fy *= (1.0/2.0); - double p00 = alphaAt(x-1, y ), p10 = alphaAt(x, y ), p20 = alphaAt(x+1, y ), - p01 = alphaAt(x-1, y+1), p11 = alphaAt(x, y+1), p21 = alphaAt(x+1, y+1); - normal[X_3D] = - -2.0 * p00 +0.0 * p10 +2.0 * p20 - -1.0 * p01 +0.0 * p11 +1.0 * p21; - normal[Y_3D] = - -1.0 * p00 -2.0 * p10 -1.0 * p20 - +1.0 * p01 +2.0 * p11 +1.0 * p21; + fx *= (1.0 / 3.0); + fy *= (1.0 / 2.0); + double p00 = alphaAt(x - 1, y), p10 = alphaAt(x, y), p20 = alphaAt(x + 1, y), + p01 = alphaAt(x - 1, y + 1), p11 = alphaAt(x, y + 1), p21 = alphaAt(x + 1, y + 1); + normal[X_3D] = -2.0 * p00 + 0.0 * p10 + 2.0 * p20 - 1.0 * p01 + 0.0 * p11 + 1.0 * p21; + normal[Y_3D] = -1.0 * p00 - 2.0 * p10 - 1.0 * p20 + 1.0 * p01 + 2.0 * p11 + 1.0 * p21; } else if (G_UNLIKELY(y == (_h - 1))) { // bottom row - fx *= (1.0/3.0); - fy *= (1.0/2.0); - double p00 = alphaAt(x-1, y-1), p10 = alphaAt(x, y-1), p20 = alphaAt(x+1, y-1), - p01 = alphaAt(x-1, y ), p11 = alphaAt(x, y ), p21 = alphaAt(x+1, y ); - normal[X_3D] = - -1.0 * p00 +0.0 * p10 +1.0 * p20 - -2.0 * p01 +0.0 * p11 +2.0 * p21; - normal[Y_3D] = - -1.0 * p00 -2.0 * p10 -1.0 * p20 - +1.0 * p01 +2.0 * p11 +1.0 * p21; + fx *= (1.0 / 3.0); + fy *= (1.0 / 2.0); + double p00 = alphaAt(x - 1, y - 1), p10 = alphaAt(x, y - 1), p20 = alphaAt(x + 1, y - 1), + p01 = alphaAt(x - 1, y), p11 = alphaAt(x, y), p21 = alphaAt(x + 1, y); + normal[X_3D] = -1.0 * p00 + 0.0 * p10 + 1.0 * p20 - 2.0 * p01 + 0.0 * p11 + 2.0 * p21; + normal[Y_3D] = -1.0 * p00 - 2.0 * p10 - 1.0 * p20 + 1.0 * p01 + 2.0 * p11 + 1.0 * p21; } else { // interior pixels // note: p11 is actually unused, so we don't fetch its value - fx *= (1.0/4.0); - fy *= (1.0/4.0); - double p00 = alphaAt(x-1, y-1), p10 = alphaAt(x, y-1), p20 = alphaAt(x+1, y-1), - p01 = alphaAt(x-1, y ), p11 = 0.0, p21 = alphaAt(x+1, y ), - p02 = alphaAt(x-1, y+1), p12 = alphaAt(x, y+1), p22 = alphaAt(x+1, y+1); - normal[X_3D] = - -1.0 * p00 +0.0 * p10 +1.0 * p20 - -2.0 * p01 +0.0 * p11 +2.0 * p21 - -1.0 * p02 +0.0 * p12 +1.0 * p22; - normal[Y_3D] = - -1.0 * p00 -2.0 * p10 -1.0 * p20 - +0.0 * p01 +0.0 * p11 +0.0 * p21 - +1.0 * p02 +2.0 * p12 +1.0 * p22; + fx *= (1.0 / 4.0); + fy *= (1.0 / 4.0); + double p00 = alphaAt(x - 1, y - 1), p10 = alphaAt(x, y - 1), p20 = alphaAt(x + 1, y - 1), + p01 = alphaAt(x - 1, y), p11 = 0.0, p21 = alphaAt(x + 1, y), p02 = alphaAt(x - 1, y + 1), + p12 = alphaAt(x, y + 1), p22 = alphaAt(x + 1, y + 1); + normal[X_3D] = -1.0 * p00 + 0.0 * p10 + 1.0 * p20 - 2.0 * p01 + 0.0 * p11 + 2.0 * p21 - 1.0 * p02 + + 0.0 * p12 + 1.0 * p22; + normal[Y_3D] = -1.0 * p00 - 2.0 * p10 - 1.0 * p20 + 0.0 * p01 + 0.0 * p11 + 0.0 * p21 + 1.0 * p02 + + 2.0 * p12 + 1.0 * p22; } } normal[X_3D] *= fx; @@ -677,13 +670,15 @@ private: };*/ // Some helpers for pixel manipulation -G_GNUC_CONST inline gint32 -pxclamp(gint32 v, gint32 low, gint32 high) { +G_GNUC_CONST inline gint32 pxclamp(gint32 v, gint32 low, gint32 high) +{ // NOTE: it is possible to write a "branchless" clamping operation. // However, it will be slower than this function, because the code below // is compiled to conditional moves. - if (v < low) return low; - if (v > high) return high; + if (v < low) + return low; + if (v > high) + return high; return v; } diff --git a/src/display/cairo-utils.cpp b/src/display/cairo-utils.cpp index afcbfc1847e0aba1173f10d52bbb116278d4fdd1..d690ef998104bf4048582c82c0ad95f27e095916 100644 --- a/src/display/cairo-utils.cpp +++ b/src/display/cairo-utils.cpp @@ -11,31 +11,27 @@ #include "display/cairo-utils.h" -#include - -#include -#include -#include - -#include <2geom/pathvector.h> -#include <2geom/curves.h> #include <2geom/affine.h> -#include <2geom/point.h> +#include <2geom/curves.h> #include <2geom/path.h> -#include <2geom/transforms.h> +#include <2geom/pathvector.h> +#include <2geom/point.h> #include <2geom/sbasis-to-bezier.h> - +#include <2geom/transforms.h> #include #include #include +#include +#include +#include +#include -#include "color.h" #include "cairo-templates.h" +#include "color.h" #include "document.h" +#include "helper/pixbuf-ops.h" #include "preferences.h" #include "util/units.h" -#include "helper/pixbuf-ops.h" - /** * Key for cairo_surface_t to keep track of current color interpolation value @@ -47,22 +43,29 @@ cairo_user_data_key_t ink_pixbuf_key; namespace Inkscape { -CairoGroup::CairoGroup(cairo_t *_ct) : ct(_ct), pushed(false) {} -CairoGroup::~CairoGroup() { +CairoGroup::CairoGroup(cairo_t *_ct) + : ct(_ct) + , pushed(false) +{} +CairoGroup::~CairoGroup() +{ if (pushed) { cairo_pattern_t *p = cairo_pop_group(ct); cairo_pattern_destroy(p); } } -void CairoGroup::push() { +void CairoGroup::push() +{ cairo_push_group(ct); pushed = true; } -void CairoGroup::push_with_content(cairo_content_t content) { +void CairoGroup::push_with_content(cairo_content_t content) +{ cairo_push_group_with_content(ct, content); pushed = true; } -cairo_pattern_t *CairoGroup::pop() { +cairo_pattern_t *CairoGroup::pop() +{ if (pushed) { cairo_pattern_t *ret = cairo_pop_group(ct); pushed = false; @@ -71,7 +74,8 @@ cairo_pattern_t *CairoGroup::pop() { throw std::logic_error("Cairo group popped without pushing it first"); } } -Cairo::RefPtr CairoGroup::popmm() { +Cairo::RefPtr CairoGroup::popmm() +{ if (pushed) { cairo_pattern_t *ret = cairo_pop_group(ct); Cairo::RefPtr retmm(new Cairo::Pattern(ret, true)); @@ -81,7 +85,8 @@ Cairo::RefPtr CairoGroup::popmm() { throw std::logic_error("Cairo group popped without pushing it first"); } } -void CairoGroup::pop_to_source() { +void CairoGroup::pop_to_source() +{ if (pushed) { cairo_pop_group_to_source(ct); pushed = false; @@ -125,9 +130,8 @@ Cairo::RefPtr CairoContext::create(Cairo::RefPtr c return ret; } - /* The class below implement the following hack: - * + * * The pixels formats of Cairo and GdkPixbuf are different. * GdkPixbuf accesses pixels as bytes, alpha is not premultiplied, * and successive bytes of a single pixel contain R, G, B and A components. @@ -156,11 +160,9 @@ Cairo::RefPtr CairoContext::create(Cairo::RefPtr c * The constructor takes ownership of the passed surface, * so it should not be destroyed. */ Pixbuf::Pixbuf(cairo_surface_t *s) - : _pixbuf(gdk_pixbuf_new_from_data( - cairo_image_surface_get_data(s), GDK_COLORSPACE_RGB, TRUE, 8, - cairo_image_surface_get_width(s), cairo_image_surface_get_height(s), - cairo_image_surface_get_stride(s), - ink_cairo_pixbuf_cleanup, s)) + : _pixbuf(gdk_pixbuf_new_from_data(cairo_image_surface_get_data(s), GDK_COLORSPACE_RGB, TRUE, 8, + cairo_image_surface_get_width(s), cairo_image_surface_get_height(s), + cairo_image_surface_get_stride(s), ink_cairo_pixbuf_cleanup, s)) , _surface(s) , _mod_time(0) , _pixel_format(PF_CAIRO) @@ -178,16 +180,16 @@ Pixbuf::Pixbuf(GdkPixbuf *pb) , _cairo_store(false) { _forceAlpha(); - _surface = cairo_image_surface_create_for_data( - gdk_pixbuf_get_pixels(_pixbuf), CAIRO_FORMAT_ARGB32, - gdk_pixbuf_get_width(_pixbuf), gdk_pixbuf_get_height(_pixbuf), gdk_pixbuf_get_rowstride(_pixbuf)); + _surface = cairo_image_surface_create_for_data(gdk_pixbuf_get_pixels(_pixbuf), CAIRO_FORMAT_ARGB32, + gdk_pixbuf_get_width(_pixbuf), gdk_pixbuf_get_height(_pixbuf), + gdk_pixbuf_get_rowstride(_pixbuf)); } Pixbuf::Pixbuf(Inkscape::Pixbuf const &other) : _pixbuf(gdk_pixbuf_copy(other._pixbuf)) - , _surface(cairo_image_surface_create_for_data( - gdk_pixbuf_get_pixels(_pixbuf), CAIRO_FORMAT_ARGB32, - gdk_pixbuf_get_width(_pixbuf), gdk_pixbuf_get_height(_pixbuf), gdk_pixbuf_get_rowstride(_pixbuf))) + , _surface(cairo_image_surface_create_for_data(gdk_pixbuf_get_pixels(_pixbuf), CAIRO_FORMAT_ARGB32, + gdk_pixbuf_get_width(_pixbuf), gdk_pixbuf_get_height(_pixbuf), + gdk_pixbuf_get_rowstride(_pixbuf))) , _mod_time(other._mod_time) , _path(other._path) , _pixel_format(other._pixel_format) @@ -239,39 +241,34 @@ Pixbuf *Pixbuf::create_from_data_uri(gchar const *uri_data, double svgdpi) gchar const *data = uri_data; while (*data) { - if (strncmp(data,"base64",6) == 0) { + if (strncmp(data, "base64", 6) == 0) { /* base64-encoding */ data_is_base64 = true; - data_is_image = true; // Illustrator produces embedded images without MIME type, so we assume it's image no matter what + data_is_image = + true; // Illustrator produces embedded images without MIME type, so we assume it's image no matter what data += 6; - } - else if (strncmp(data,"image/png",9) == 0) { + } else if (strncmp(data, "image/png", 9) == 0) { /* PNG image */ data_is_image = true; data += 9; - } - else if (strncmp(data,"image/jpg",9) == 0) { + } else if (strncmp(data, "image/jpg", 9) == 0) { /* JPEG image */ data_is_image = true; data += 9; - } - else if (strncmp(data,"image/jpeg",10) == 0) { + } else if (strncmp(data, "image/jpeg", 10) == 0) { /* JPEG image */ data_is_image = true; data += 10; - } - else if (strncmp(data,"image/jp2",9) == 0) { + } else if (strncmp(data, "image/jp2", 9) == 0) { /* JPEG2000 image */ data_is_image = true; data += 9; - } - else if (strncmp(data,"image/svg+xml",13) == 0) { + } else if (strncmp(data, "image/svg+xml", 13) == 0) { /* JPEG2000 image */ data_is_svg = true; data_is_image = true; data += 13; - } - else { /* unrecognized option; skip it */ + } else { /* unrecognized option; skip it */ while (*data) { if (((*data) == ';') || ((*data) == ',')) { break; @@ -292,7 +289,8 @@ Pixbuf *Pixbuf::create_from_data_uri(gchar const *uri_data, double svgdpi) if ((*data) && data_is_image && !data_is_svg && data_is_base64) { GdkPixbufLoader *loader = gdk_pixbuf_loader_new(); - if (!loader) return nullptr; + if (!loader) + return nullptr; gsize decoded_len = 0; guchar *decoded = g_base64_decode(data, &decoded_len); @@ -316,7 +314,7 @@ Pixbuf *Pixbuf::create_from_data_uri(gchar const *uri_data, double svgdpi) } g_object_unref(loader); } - + if ((*data) && data_is_image && data_is_svg && data_is_base64) { gsize decoded_len = 0; guchar *decoded = g_base64_decode(data, &decoded_len); @@ -326,8 +324,7 @@ Pixbuf *Pixbuf::create_from_data_uri(gchar const *uri_data, double svgdpi) if (svgDoc == nullptr) { return nullptr; } - if (svgDoc->getRoot() == nullptr) - { + if (svgDoc->getRoot() == nullptr) { return nullptr; } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -346,10 +343,10 @@ Pixbuf *Pixbuf::create_from_data_uri(gchar const *uri_data, double svgdpi) svgHeight_px); return nullptr; } - + // Now get the resized values - const int scaledSvgWidth = round(svgWidth_px/(96.0/dpi)); - const int scaledSvgHeight = round(svgHeight_px/(96.0/dpi)); + const int scaledSvgWidth = round(svgWidth_px / (96.0 / dpi)); + const int scaledSvgHeight = round(svgHeight_px / (96.0 / dpi)); assert(!pixbuf); pixbuf = sp_generate_internal_bitmap(svgDoc.get(), nullptr, 0, 0, svgWidth_px, svgHeight_px, scaledSvgWidth, @@ -374,12 +371,12 @@ Pixbuf *Pixbuf::create_from_file(std::string const &fn, double svgdpi) { Pixbuf *pb = nullptr; // test correctness of filename - if (!g_file_test(fn.c_str(), G_FILE_TEST_EXISTS)) { + if (!g_file_test(fn.c_str(), G_FILE_TEST_EXISTS)) { return nullptr; } GStatBuf stdir; int val = g_stat(fn.c_str(), &stdir); - if (val == 0 && stdir.st_mode & S_IFDIR){ + if (val == 0 && stdir.st_mode & S_IFDIR) { return nullptr; } // we need to load the entire file into memory, @@ -389,7 +386,6 @@ Pixbuf *Pixbuf::create_from_file(std::string const &fn, double svgdpi) GError *error = nullptr; if (g_file_get_contents(fn.c_str(), &data, &len, &error)) { - if (error != nullptr) { std::cerr << "Pixbuf::create_from_file: " << error->message << std::endl; std::cerr << " (" << fn << ")" << std::endl; @@ -424,19 +420,16 @@ Pixbuf *Pixbuf::create_from_buffer(gchar *&&data, gsize len, double svgdpi, std: GdkPixbufLoader *loader = nullptr; std::string::size_type idx; idx = fn.rfind('.'); - bool is_svg = false; - if(idx != std::string::npos) - { - if (boost::iequals(fn.substr(idx+1).c_str(), "svg")) { - + bool is_svg = false; + if (idx != std::string::npos) { + if (boost::iequals(fn.substr(idx + 1).c_str(), "svg")) { std::unique_ptr svgDoc(SPDocument::createNewDocFromMem(data, len, true)); // Check the document loaded properly if (svgDoc == nullptr) { return nullptr; } - if (svgDoc->getRoot() == nullptr) - { + if (svgDoc->getRoot() == nullptr) { return nullptr; } @@ -458,8 +451,8 @@ Pixbuf *Pixbuf::create_from_buffer(gchar *&&data, gsize len, double svgdpi, std: } // Now get the resized values - const int scaledSvgWidth = round(svgWidth_px/(96.0/dpi)); - const int scaledSvgHeight = round(svgHeight_px/(96.0/dpi)); + const int scaledSvgWidth = round(svgWidth_px / (96.0 / dpi)); + const int scaledSvgHeight = round(svgHeight_px / (96.0 / dpi)); pb = sp_generate_internal_bitmap(svgDoc.get(), nullptr, 0, 0, svgWidth_px, svgHeight_px, scaledSvgWidth, scaledSvgHeight, dpi, dpi, 0xffffff00); @@ -475,7 +468,7 @@ Pixbuf *Pixbuf::create_from_buffer(gchar *&&data, gsize len, double svgdpi, std: } if (!is_svg) { loader = gdk_pixbuf_loader_new(); - gdk_pixbuf_loader_write(loader, (guchar *) data, len, &error); + gdk_pixbuf_loader_write(loader, (guchar *)data, len, &error); if (error != nullptr) { std::cerr << "Pixbuf::create_from_file: " << error->message << std::endl; std::cerr << " (" << fn << ")" << std::endl; @@ -492,7 +485,7 @@ Pixbuf *Pixbuf::create_from_buffer(gchar *&&data, gsize len, double svgdpi, std: g_object_unref(loader); return nullptr; } - + buf = gdk_pixbuf_loader_get_pixbuf(loader); if (buf) { // gdk_pixbuf_loader_get_pixbuf returns a borrowed reference @@ -506,11 +499,11 @@ Pixbuf *Pixbuf::create_from_buffer(gchar *&&data, gsize len, double svgdpi, std: if (!is_svg) { GdkPixbufFormat *fmt = gdk_pixbuf_loader_get_format(loader); gchar *fmt_name = gdk_pixbuf_format_get_name(fmt); - pb->_setMimeData((guchar *) data, len, fmt_name); + pb->_setMimeData((guchar *)data, len, fmt_name); g_free(fmt_name); g_object_unref(loader); } else { - pb->_setMimeData((guchar *) data, len, "svg"); + pb->_setMimeData((guchar *)data, len, "svg"); } } else { std::cerr << "Pixbuf::create_from_file: failed to load contents: " << fn << std::endl; @@ -580,17 +573,16 @@ Cairo::RefPtr Pixbuf::getSurface(bool convert_format) * The returned data belongs to the object and should not be freed. */ guchar const *Pixbuf::getMimeData(gsize &len, std::string &mimetype) const { - static gchar const *mimetypes[] = { - CAIRO_MIME_TYPE_JPEG, CAIRO_MIME_TYPE_JP2, CAIRO_MIME_TYPE_PNG, nullptr }; - static guint mimetypes_len = g_strv_length(const_cast(mimetypes)); + static gchar const *mimetypes[] = {CAIRO_MIME_TYPE_JPEG, CAIRO_MIME_TYPE_JP2, CAIRO_MIME_TYPE_PNG, nullptr}; + static guint mimetypes_len = g_strv_length(const_cast(mimetypes)); guchar const *data = nullptr; for (guint i = 0; i < mimetypes_len; ++i) { unsigned long len_long = 0; - cairo_surface_get_mime_data(const_cast(_surface), mimetypes[i], &data, &len_long); + cairo_surface_get_mime_data(const_cast(_surface), mimetypes[i], &data, &len_long); if (data != nullptr) { - len = len_long; + len = len_long; mimetype = mimetypes[i]; break; } @@ -599,28 +591,35 @@ guchar const *Pixbuf::getMimeData(gsize &len, std::string &mimetype) const return data; } -int Pixbuf::width() const { - return gdk_pixbuf_get_width(const_cast(_pixbuf)); +int Pixbuf::width() const +{ + return gdk_pixbuf_get_width(const_cast(_pixbuf)); } -int Pixbuf::height() const { - return gdk_pixbuf_get_height(const_cast(_pixbuf)); +int Pixbuf::height() const +{ + return gdk_pixbuf_get_height(const_cast(_pixbuf)); } -int Pixbuf::rowstride() const { - return gdk_pixbuf_get_rowstride(const_cast(_pixbuf)); +int Pixbuf::rowstride() const +{ + return gdk_pixbuf_get_rowstride(const_cast(_pixbuf)); } -guchar const *Pixbuf::pixels() const { - return gdk_pixbuf_get_pixels(const_cast(_pixbuf)); +guchar const *Pixbuf::pixels() const +{ + return gdk_pixbuf_get_pixels(const_cast(_pixbuf)); } -guchar *Pixbuf::pixels() { +guchar *Pixbuf::pixels() +{ return gdk_pixbuf_get_pixels(_pixbuf); } -void Pixbuf::markDirty() { +void Pixbuf::markDirty() +{ cairo_surface_mark_dirty(_surface); } void Pixbuf::_forceAlpha() { - if (gdk_pixbuf_get_has_alpha(_pixbuf)) return; + if (gdk_pixbuf_get_has_alpha(_pixbuf)) + return; GdkPixbuf *old = _pixbuf; _pixbuf = gdk_pixbuf_add_alpha(old, FALSE, 0, 0, 0); @@ -641,10 +640,10 @@ void Pixbuf::_setMimeData(guchar *data, gsize len, Glib::ustring const &format) if (mimetype != nullptr) { cairo_surface_set_mime_data(_surface, mimetype, data, len, g_free, data); - //g_message("Setting Cairo MIME data: %s", mimetype); + // g_message("Setting Cairo MIME data: %s", mimetype); } else { g_free(data); - //g_message("Not setting Cairo MIME data: unknown format %s", name.c_str()); + // g_message("Not setting Cairo MIME data: unknown format %s", name.c_str()); } } @@ -655,11 +654,8 @@ void Pixbuf::ensurePixelFormat(PixelFormat fmt) return; } if (fmt == PF_CAIRO) { - convert_pixels_pixbuf_to_argb32( - gdk_pixbuf_get_pixels(_pixbuf), - gdk_pixbuf_get_width(_pixbuf), - gdk_pixbuf_get_height(_pixbuf), - gdk_pixbuf_get_rowstride(_pixbuf)); + convert_pixels_pixbuf_to_argb32(gdk_pixbuf_get_pixels(_pixbuf), gdk_pixbuf_get_width(_pixbuf), + gdk_pixbuf_get_height(_pixbuf), gdk_pixbuf_get_rowstride(_pixbuf)); _pixel_format = fmt; return; } @@ -667,11 +663,8 @@ void Pixbuf::ensurePixelFormat(PixelFormat fmt) } if (_pixel_format == PF_CAIRO) { if (fmt == PF_GDK) { - convert_pixels_argb32_to_pixbuf( - gdk_pixbuf_get_pixels(_pixbuf), - gdk_pixbuf_get_width(_pixbuf), - gdk_pixbuf_get_height(_pixbuf), - gdk_pixbuf_get_rowstride(_pixbuf)); + convert_pixels_argb32_to_pixbuf(gdk_pixbuf_get_pixels(_pixbuf), gdk_pixbuf_get_width(_pixbuf), + gdk_pixbuf_get_height(_pixbuf), gdk_pixbuf_get_rowstride(_pixbuf)); _pixel_format = fmt; return; } @@ -689,84 +682,78 @@ void Pixbuf::ensurePixelFormat(PixelFormat fmt) * Can be called recursively. * If optimize_stroke == false, the view Rect is not used. */ -static void -feed_curve_to_cairo(cairo_t *cr, Geom::Curve const &c, Geom::Affine const & trans, Geom::Rect view, bool optimize_stroke) +static void feed_curve_to_cairo(cairo_t *cr, Geom::Curve const &c, Geom::Affine const &trans, Geom::Rect view, + bool optimize_stroke) { using Geom::X; using Geom::Y; unsigned order = 0; - if (Geom::BezierCurve const* b = dynamic_cast(&c)) { + if (Geom::BezierCurve const *b = dynamic_cast(&c)) { order = b->order(); } // handle the three typical curve cases switch (order) { - case 1: - { - Geom::Point end_tr = c.finalPoint() * trans; - if (!optimize_stroke) { - cairo_line_to(cr, end_tr[0], end_tr[1]); - } else { - Geom::Rect swept(c.initialPoint()*trans, end_tr); - if (swept.intersects(view)) { + case 1: { + Geom::Point end_tr = c.finalPoint() * trans; + if (!optimize_stroke) { cairo_line_to(cr, end_tr[0], end_tr[1]); } else { - cairo_move_to(cr, end_tr[0], end_tr[1]); + Geom::Rect swept(c.initialPoint() * trans, end_tr); + if (swept.intersects(view)) { + cairo_line_to(cr, end_tr[0], end_tr[1]); + } else { + cairo_move_to(cr, end_tr[0], end_tr[1]); + } } - } - } - break; - case 2: - { - Geom::QuadraticBezier const *quadratic_bezier = static_cast(&c); - std::vector points = quadratic_bezier->controlPoints(); - points[0] *= trans; - points[1] *= trans; - points[2] *= trans; - // degree-elevate to cubic Bezier, since Cairo doesn't do quadratic Beziers - Geom::Point b1 = points[0] + (2./3) * (points[1] - points[0]); - Geom::Point b2 = b1 + (1./3) * (points[2] - points[0]); - if (!optimize_stroke) { - cairo_curve_to(cr, b1[X], b1[Y], b2[X], b2[Y], points[2][X], points[2][Y]); - } else { - Geom::Rect swept(points[0], points[2]); - swept.expandTo(points[1]); - if (swept.intersects(view)) { + } break; + case 2: { + Geom::QuadraticBezier const *quadratic_bezier = static_cast(&c); + std::vector points = quadratic_bezier->controlPoints(); + points[0] *= trans; + points[1] *= trans; + points[2] *= trans; + // degree-elevate to cubic Bezier, since Cairo doesn't do quadratic Beziers + Geom::Point b1 = points[0] + (2. / 3) * (points[1] - points[0]); + Geom::Point b2 = b1 + (1. / 3) * (points[2] - points[0]); + if (!optimize_stroke) { cairo_curve_to(cr, b1[X], b1[Y], b2[X], b2[Y], points[2][X], points[2][Y]); } else { - cairo_move_to(cr, points[2][X], points[2][Y]); + Geom::Rect swept(points[0], points[2]); + swept.expandTo(points[1]); + if (swept.intersects(view)) { + cairo_curve_to(cr, b1[X], b1[Y], b2[X], b2[Y], points[2][X], points[2][Y]); + } else { + cairo_move_to(cr, points[2][X], points[2][Y]); + } } - } - } - break; - case 3: - { - Geom::CubicBezier const *cubic_bezier = static_cast(&c); - std::vector points = cubic_bezier->controlPoints(); - //points[0] *= trans; // don't do this one here for fun: it is only needed for optimized strokes - points[1] *= trans; - points[2] *= trans; - points[3] *= trans; - if (!optimize_stroke) { - cairo_curve_to(cr, points[1][X], points[1][Y], points[2][X], points[2][Y], points[3][X], points[3][Y]); - } else { - points[0] *= trans; // didn't transform this point yet - Geom::Rect swept(points[0], points[3]); - swept.expandTo(points[1]); - swept.expandTo(points[2]); - if (swept.intersects(view)) { + } break; + case 3: { + Geom::CubicBezier const *cubic_bezier = static_cast(&c); + std::vector points = cubic_bezier->controlPoints(); + // points[0] *= trans; // don't do this one here for fun: it is only needed for optimized strokes + points[1] *= trans; + points[2] *= trans; + points[3] *= trans; + if (!optimize_stroke) { cairo_curve_to(cr, points[1][X], points[1][Y], points[2][X], points[2][Y], points[3][X], points[3][Y]); } else { - cairo_move_to(cr, points[3][X], points[3][Y]); + points[0] *= trans; // didn't transform this point yet + Geom::Rect swept(points[0], points[3]); + swept.expandTo(points[1]); + swept.expandTo(points[2]); + if (swept.intersects(view)) { + cairo_curve_to(cr, points[1][X], points[1][Y], points[2][X], points[2][Y], points[3][X], + points[3][Y]); + } else { + cairo_move_to(cr, points[3][X], points[3][Y]); + } } - } - } - break; - default: - { - if (Geom::EllipticalArc const *a = dynamic_cast(&c)) { - //if (!optimize_stroke || a->boundsFast().intersects(view)) { + } break; + default: { + if (Geom::EllipticalArc const *a = dynamic_cast(&c)) { + // if (!optimize_stroke || a->boundsFast().intersects(view)) { Geom::Affine xform = a->unitCircleTransform() * trans; Geom::Point ang(a->initialAngle().radians(), a->finalAngle().radians()); @@ -790,37 +777,35 @@ feed_curve_to_cairo(cairo_t *cr, Geom::Curve const &c, Geom::Affine const & tran } // Revert the current context cairo_restore(cr); - //} else { - // Geom::Point f = a->finalPoint() * trans; - // cairo_move_to(cr, f[X], f[Y]); - //} - } else { - // handles sbasis as well as all other curve types - // this is very slow - Geom::Path sbasis_path = Geom::cubicbezierpath_from_sbasis(c.toSBasis(), 0.1); + //} else { + // Geom::Point f = a->finalPoint() * trans; + // cairo_move_to(cr, f[X], f[Y]); + //} + } else { + // handles sbasis as well as all other curve types + // this is very slow + Geom::Path sbasis_path = Geom::cubicbezierpath_from_sbasis(c.toSBasis(), 0.1); - // recurse to convert the new path resulting from the sbasis to svgd - for (const auto & iter : sbasis_path) { - feed_curve_to_cairo(cr, iter, trans, view, optimize_stroke); + // recurse to convert the new path resulting from the sbasis to svgd + for (const auto &iter : sbasis_path) { + feed_curve_to_cairo(cr, iter, trans, view, optimize_stroke); + } } - } - } - break; + } break; } } - /** Feeds path-creating calls to the cairo context translating them from the Path */ -static void -feed_path_to_cairo (cairo_t *ct, Geom::Path const &path) +static void feed_path_to_cairo(cairo_t *ct, Geom::Path const &path) { if (path.empty()) return; - cairo_move_to(ct, path.initialPoint()[0], path.initialPoint()[1] ); + cairo_move_to(ct, path.initialPoint()[0], path.initialPoint()[1]); for (Geom::Path::const_iterator cit = path.begin(); cit != path.end_open(); ++cit) { - feed_curve_to_cairo(ct, *cit, Geom::identity(), Geom::Rect(), false); // optimize_stroke is false, so the view rect is not used + feed_curve_to_cairo(ct, *cit, Geom::identity(), Geom::Rect(), + false); // optimize_stroke is false, so the view rect is not used } if (path.closed()) { @@ -829,8 +814,8 @@ feed_path_to_cairo (cairo_t *ct, Geom::Path const &path) } /** Feeds path-creating calls to the cairo context translating them from the Path, with the given transform and shift */ -static void -feed_path_to_cairo (cairo_t *ct, Geom::Path const &path, Geom::Affine trans, Geom::OptRect area, bool optimize_stroke, double stroke_width) +static void feed_path_to_cairo(cairo_t *ct, Geom::Path const &path, Geom::Affine trans, Geom::OptRect area, + bool optimize_stroke, double stroke_width) { if (!area) return; @@ -840,15 +825,15 @@ feed_path_to_cairo (cairo_t *ct, Geom::Path const &path, Geom::Affine trans, Geo // Transform all coordinates to coords within "area" Geom::Point shift = area->min(); Geom::Rect view = *area; - view.expandBy (stroke_width); + view.expandBy(stroke_width); view = view * (Geom::Affine)Geom::Translate(-shift); // Pass transformation to feed_curve, so that we don't need to create a whole new path. Geom::Affine transshift(trans * Geom::Translate(-shift)); Geom::Point initial = path.initialPoint() * transshift; - cairo_move_to(ct, initial[0], initial[1] ); + cairo_move_to(ct, initial[0], initial[1]); - for(Geom::Path::const_iterator cit = path.begin(); cit != path.end_open(); ++cit) { + for (Geom::Path::const_iterator cit = path.begin(); cit != path.end_open(); ++cit) { feed_curve_to_cairo(ct, *cit, transshift, view, optimize_stroke); } @@ -858,13 +843,13 @@ feed_path_to_cairo (cairo_t *ct, Geom::Path const &path, Geom::Affine trans, Geo } else { cairo_line_to(ct, initial[0], initial[1]); /* We cannot use cairo_close_path(ct) here because some parts of the path may have been - clipped and not drawn (maybe the before last segment was outside view area), which + clipped and not drawn (maybe the before last segment was outside view area), which would result in closing the "subpath" after the last interruption, not the entire path. However, according to cairo documentation: - The behavior of cairo_close_path() is distinct from simply calling cairo_line_to() with the equivalent coordinate - in the case of stroking. When a closed sub-path is stroked, there are no caps on the ends of the sub-path. Instead, - there is a line join connecting the final and initial segments of the sub-path. + The behavior of cairo_close_path() is distinct from simply calling cairo_line_to() with the equivalent + coordinate in the case of stroking. When a closed sub-path is stroked, there are no caps on the ends of + the sub-path. Instead, there is a line join connecting the final and initial segments of the sub-path. The correct fix will be possible when cairo introduces methods for moving without ending/starting subpaths, which we will use for skipping invisible segments; then we @@ -875,39 +860,38 @@ feed_path_to_cairo (cairo_t *ct, Geom::Path const &path, Geom::Affine trans, Geo } } -/** Feeds path-creating calls to the cairo context translating them from the PathVector, with the given transform and shift - * One must have done cairo_new_path(ct); before calling this function. */ -void -feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv, Geom::Affine trans, Geom::OptRect area, bool optimize_stroke, double stroke_width) +/** Feeds path-creating calls to the cairo context translating them from the PathVector, with the given transform and + * shift One must have done cairo_new_path(ct); before calling this function. */ +void feed_pathvector_to_cairo(cairo_t *ct, Geom::PathVector const &pathv, Geom::Affine trans, Geom::OptRect area, + bool optimize_stroke, double stroke_width) { if (!area) return; if (pathv.empty()) return; - for(const auto & it : pathv) { + for (const auto &it : pathv) { feed_path_to_cairo(ct, it, trans, area, optimize_stroke, stroke_width); } } /** Feeds path-creating calls to the cairo context translating them from the PathVector * One must have done cairo_new_path(ct); before calling this function. */ -void -feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv) +void feed_pathvector_to_cairo(cairo_t *ct, Geom::PathVector const &pathv) { if (pathv.empty()) return; - for(const auto & it : pathv) { + for (const auto &it : pathv) { feed_path_to_cairo(ct, it); } } -SPColorInterpolation -get_cairo_surface_ci(cairo_surface_t *surface) { - void* data = cairo_surface_get_user_data( surface, &ink_color_interpolation_key ); - if( data != nullptr ) { - return (SPColorInterpolation)GPOINTER_TO_INT( data ); +SPColorInterpolation get_cairo_surface_ci(cairo_surface_t *surface) +{ + void *data = cairo_surface_get_user_data(surface, &ink_color_interpolation_key); + if (data != nullptr) { + return (SPColorInterpolation)GPOINTER_TO_INT(data); } else { return SP_CSS_COLOR_INTERPOLATION_AUTO; } @@ -915,39 +899,34 @@ get_cairo_surface_ci(cairo_surface_t *surface) { /** Set the color_interpolation_value for a Cairo surface. * Transform the surface between sRGB and linearRGB if necessary. */ -void -set_cairo_surface_ci(cairo_surface_t *surface, SPColorInterpolation ci) { - - if( cairo_surface_get_content( surface ) != CAIRO_CONTENT_ALPHA ) { - - SPColorInterpolation ci_in = get_cairo_surface_ci( surface ); +void set_cairo_surface_ci(cairo_surface_t *surface, SPColorInterpolation ci) +{ + if (cairo_surface_get_content(surface) != CAIRO_CONTENT_ALPHA) { + SPColorInterpolation ci_in = get_cairo_surface_ci(surface); - if( ci_in == SP_CSS_COLOR_INTERPOLATION_SRGB && - ci == SP_CSS_COLOR_INTERPOLATION_LINEARRGB ) { - ink_cairo_surface_srgb_to_linear( surface ); + if (ci_in == SP_CSS_COLOR_INTERPOLATION_SRGB && ci == SP_CSS_COLOR_INTERPOLATION_LINEARRGB) { + ink_cairo_surface_srgb_to_linear(surface); } - if( ci_in == SP_CSS_COLOR_INTERPOLATION_LINEARRGB && - ci == SP_CSS_COLOR_INTERPOLATION_SRGB ) { - ink_cairo_surface_linear_to_srgb( surface ); + if (ci_in == SP_CSS_COLOR_INTERPOLATION_LINEARRGB && ci == SP_CSS_COLOR_INTERPOLATION_SRGB) { + ink_cairo_surface_linear_to_srgb(surface); } - cairo_surface_set_user_data(surface, &ink_color_interpolation_key, GINT_TO_POINTER (ci), nullptr); + cairo_surface_set_user_data(surface, &ink_color_interpolation_key, GINT_TO_POINTER(ci), nullptr); } } -void -copy_cairo_surface_ci(cairo_surface_t *in, cairo_surface_t *out) { - cairo_surface_set_user_data(out, &ink_color_interpolation_key, cairo_surface_get_user_data(in, &ink_color_interpolation_key), nullptr); +void copy_cairo_surface_ci(cairo_surface_t *in, cairo_surface_t *out) +{ + cairo_surface_set_user_data(out, &ink_color_interpolation_key, + cairo_surface_get_user_data(in, &ink_color_interpolation_key), nullptr); } -void -ink_cairo_set_source_rgba32(cairo_t *ct, guint32 rgba) +void ink_cairo_set_source_rgba32(cairo_t *ct, guint32 rgba) { cairo_set_source_rgba(ct, SP_RGBA32_R_F(rgba), SP_RGBA32_G_F(rgba), SP_RGBA32_B_F(rgba), SP_RGBA32_A_F(rgba)); } -void -ink_cairo_set_source_color(cairo_t *ct, SPColor const &c, double opacity) +void ink_cairo_set_source_color(cairo_t *ct, SPColor const &c, double opacity) { cairo_set_source_rgba(ct, c.v.c[0], c.v.c[1], c.v.c[2], opacity); } @@ -972,16 +951,14 @@ void ink_matrix_to_cairo(cairo_matrix_t &cm, Geom::Affine const &m) cm.y0 = m[5]; } -void -ink_cairo_transform(cairo_t *ct, Geom::Affine const &m) +void ink_cairo_transform(cairo_t *ct, Geom::Affine const &m) { cairo_matrix_t cm; ink_matrix_to_cairo(cm, m); cairo_transform(ct, &cm); } -void -ink_cairo_pattern_set_matrix(cairo_pattern_t *cp, Geom::Affine const &m) +void ink_cairo_pattern_set_matrix(cairo_pattern_t *cp, Geom::Affine const &m) { cairo_matrix_t cm; ink_matrix_to_cairo(cm, m); @@ -993,8 +970,7 @@ ink_cairo_pattern_set_matrix(cairo_pattern_t *cp, Geom::Affine const &m) * Creates a surface that has the same type, content type, dimensions and contents * as the specified surface. */ -cairo_surface_t * -ink_cairo_surface_copy(cairo_surface_t *s) +cairo_surface_t *ink_cairo_surface_copy(cairo_surface_t *s) { cairo_surface_t *ns = ink_cairo_surface_create_identical(s); @@ -1022,30 +998,27 @@ ink_cairo_surface_copy(cairo_surface_t *s) * Creates a surface that has the same type, content type and dimensions * as the specified surface. Pixel contents are not copied. */ -cairo_surface_t * -ink_cairo_surface_create_identical(cairo_surface_t *s) +cairo_surface_t *ink_cairo_surface_create_identical(cairo_surface_t *s) { cairo_surface_t *ns = ink_cairo_surface_create_same_size(s, cairo_surface_get_content(s)); - cairo_surface_set_user_data(ns, &ink_color_interpolation_key, cairo_surface_get_user_data(s, &ink_color_interpolation_key), nullptr); + cairo_surface_set_user_data(ns, &ink_color_interpolation_key, + cairo_surface_get_user_data(s, &ink_color_interpolation_key), nullptr); return ns; } -cairo_surface_t * -ink_cairo_surface_create_same_size(cairo_surface_t *s, cairo_content_t c) +cairo_surface_t *ink_cairo_surface_create_same_size(cairo_surface_t *s, cairo_content_t c) { // ink_cairo_surface_get_width()/height() returns value in pixels // cairo_surface_create_similar() uses device units double x_scale = 0; double y_scale = 0; - cairo_surface_get_device_scale( s, &x_scale, &y_scale ); + cairo_surface_get_device_scale(s, &x_scale, &y_scale); - assert (x_scale > 0); - assert (y_scale > 0); + assert(x_scale > 0); + assert(y_scale > 0); - cairo_surface_t *ns = - cairo_surface_create_similar(s, c, - ink_cairo_surface_get_width(s)/x_scale, - ink_cairo_surface_get_height(s)/y_scale); + cairo_surface_t *ns = cairo_surface_create_similar(s, c, ink_cairo_surface_get_width(s) / x_scale, + ink_cairo_surface_get_height(s) / y_scale); return ns; } @@ -1054,8 +1027,7 @@ ink_cairo_surface_create_same_size(cairo_surface_t *s, cairo_content_t c) * Creates a surface with a content type of CAIRO_CONTENT_ALPHA that contains * the alpha values of pixels from @a s. */ -cairo_surface_t * -ink_cairo_extract_alpha(cairo_surface_t *s) +cairo_surface_t *ink_cairo_extract_alpha(cairo_surface_t *s) { cairo_surface_t *alpha = ink_cairo_surface_create_same_size(s, CAIRO_CONTENT_ALPHA); @@ -1068,8 +1040,7 @@ ink_cairo_extract_alpha(cairo_surface_t *s) return alpha; } -cairo_surface_t * -ink_cairo_surface_create_output(cairo_surface_t *image, cairo_surface_t *bg) +cairo_surface_t *ink_cairo_surface_create_output(cairo_surface_t *image, cairo_surface_t *bg) { cairo_content_t imgt = cairo_surface_get_content(image); cairo_content_t bgt = cairo_surface_get_content(bg); @@ -1084,16 +1055,14 @@ ink_cairo_surface_create_output(cairo_surface_t *image, cairo_surface_t *bg) return out; } -void -ink_cairo_surface_blit(cairo_surface_t *src, cairo_surface_t *dest) +void ink_cairo_surface_blit(cairo_surface_t *src, cairo_surface_t *dest) { if (cairo_surface_get_type(src) == CAIRO_SURFACE_TYPE_IMAGE && cairo_surface_get_type(dest) == CAIRO_SURFACE_TYPE_IMAGE && cairo_image_surface_get_format(src) == cairo_image_surface_get_format(dest) && cairo_image_surface_get_height(src) == cairo_image_surface_get_height(dest) && cairo_image_surface_get_width(src) == cairo_image_surface_get_width(dest) && - cairo_image_surface_get_stride(src) == cairo_image_surface_get_stride(dest)) - { + cairo_image_surface_get_stride(src) == cairo_image_surface_get_stride(dest)) { // use memory copy instead of using a Cairo context cairo_surface_flush(src); int stride = cairo_image_surface_get_stride(src); @@ -1113,8 +1082,7 @@ ink_cairo_surface_blit(cairo_surface_t *src, cairo_surface_t *dest) /** * Return width in pixels. */ -int -ink_cairo_surface_get_width(cairo_surface_t *surface) +int ink_cairo_surface_get_width(cairo_surface_t *surface) { // For now only image surface is handled. // Later add others, e.g. cairo-gl @@ -1125,14 +1093,14 @@ ink_cairo_surface_get_width(cairo_surface_t *surface) /** * Return height in pixels. */ -int -ink_cairo_surface_get_height(cairo_surface_t *surface) +int ink_cairo_surface_get_height(cairo_surface_t *surface) { assert(cairo_surface_get_type(surface) == CAIRO_SURFACE_TYPE_IMAGE); return cairo_image_surface_get_height(surface); } -static int ink_cairo_surface_average_color_internal(cairo_surface_t *surface, double &rf, double &gf, double &bf, double &af) +static int ink_cairo_surface_average_color_internal(cairo_surface_t *surface, double &rf, double &gf, double &bf, + double &af) { rf = gf = bf = af = 0.0; cairo_surface_flush(surface); @@ -1144,8 +1112,8 @@ static int ink_cairo_surface_average_color_internal(cairo_surface_t *surface, do /* TODO convert this to OpenMP somehow */ for (int y = 0; y < height; ++y, data += stride) { for (int x = 0; x < width; ++x) { - guint32 px = *reinterpret_cast(data + 4*x); - EXTRACT_ARGB32(px, a,r,g,b) + guint32 px = *reinterpret_cast(data + 4 * x); + EXTRACT_ARGB32(px, a, r, g, b) rf += r / 255.0; gf += g / 255.0; bf += b / 255.0; @@ -1157,19 +1125,19 @@ static int ink_cairo_surface_average_color_internal(cairo_surface_t *surface, do guint32 ink_cairo_surface_average_color(cairo_surface_t *surface) { - double rf,gf,bf,af; - ink_cairo_surface_average_color_premul(surface, rf,gf,bf,af); + double rf, gf, bf, af; + ink_cairo_surface_average_color_premul(surface, rf, gf, bf, af); guint32 r = round(rf * 255); guint32 g = round(gf * 255); guint32 b = round(bf * 255); guint32 a = round(af * 255); - ASSEMBLE_ARGB32(px, a,r,g,b); + ASSEMBLE_ARGB32(px, a, r, g, b); return px; } void ink_cairo_surface_average_color(cairo_surface_t *surface, double &r, double &g, double &b, double &a) { - int count = ink_cairo_surface_average_color_internal(surface, r,g,b,a); + int count = ink_cairo_surface_average_color_internal(surface, r, g, b, a); r /= a; g /= a; @@ -1184,7 +1152,7 @@ void ink_cairo_surface_average_color(cairo_surface_t *surface, double &r, double void ink_cairo_surface_average_color_premul(cairo_surface_t *surface, double &r, double &g, double &b, double &a) { - int count = ink_cairo_surface_average_color_internal(surface, r,g,b,a); + int count = ink_cairo_surface_average_color_internal(surface, r, g, b, a); r /= count; g /= count; @@ -1197,54 +1165,56 @@ void ink_cairo_surface_average_color_premul(cairo_surface_t *surface, double &r, a = CLAMP(a, 0.0, 1.0); } -static guint32 srgb_to_linear( const guint32 c, const guint32 a ) { - - const guint32 c1 = unpremul_alpha( c, a ); +static guint32 srgb_to_linear(const guint32 c, const guint32 a) +{ + const guint32 c1 = unpremul_alpha(c, a); - double cc = c1/255.0; + double cc = c1 / 255.0; - if( cc < 0.04045 ) { + if (cc < 0.04045) { cc /= 12.92; } else { - cc = pow( (cc+0.055)/1.055, 2.4 ); + cc = pow((cc + 0.055) / 1.055, 2.4); } cc *= 255.0; const guint32 c2 = (int)cc; - return premul_alpha( c2, a ); + return premul_alpha(c2, a); } -static guint32 linear_to_srgb( const guint32 c, const guint32 a ) { - - const guint32 c1 = unpremul_alpha( c, a ); +static guint32 linear_to_srgb(const guint32 c, const guint32 a) +{ + const guint32 c1 = unpremul_alpha(c, a); - double cc = c1/255.0; + double cc = c1 / 255.0; - if( cc < 0.0031308 ) { + if (cc < 0.0031308) { cc *= 12.92; } else { - cc = pow( cc, 1.0/2.4 )*1.055-0.055; + cc = pow(cc, 1.0 / 2.4) * 1.055 - 0.055; } cc *= 255.0; const guint32 c2 = (int)cc; - return premul_alpha( c2, a ); + return premul_alpha(c2, a); } -struct SurfaceSrgbToLinear { - - guint32 operator()(guint32 in) { - EXTRACT_ARGB32(in, a,r,g,b) ; // Unneeded semi-colon for indenting - if( a != 0 ) { - r = srgb_to_linear( r, a ); - g = srgb_to_linear( g, a ); - b = srgb_to_linear( b, a ); +struct SurfaceSrgbToLinear +{ + guint32 operator()(guint32 in) + { + EXTRACT_ARGB32(in, a, r, g, b); // Unneeded semi-colon for indenting + if (a != 0) { + r = srgb_to_linear(r, a); + g = srgb_to_linear(g, a); + b = srgb_to_linear(b, a); } - ASSEMBLE_ARGB32(out, a,r,g,b); + ASSEMBLE_ARGB32(out, a, r, g, b); return out; } + private: /* None */ }; @@ -1257,7 +1227,7 @@ int ink_cairo_surface_srgb_to_linear(cairo_surface_t *surface) // int stride = cairo_image_surface_get_stride(surface); // unsigned char *data = cairo_image_surface_get_data(surface); - ink_cairo_surface_filter( surface, surface, SurfaceSrgbToLinear() ); + ink_cairo_surface_filter(surface, surface, SurfaceSrgbToLinear()); /* TODO convert this to OpenMP somehow */ // for (int y = 0; y < height; ++y, data += stride) { @@ -1276,18 +1246,20 @@ int ink_cairo_surface_srgb_to_linear(cairo_surface_t *surface) return width * height; } -struct SurfaceLinearToSrgb { - - guint32 operator()(guint32 in) { - EXTRACT_ARGB32(in, a,r,g,b) ; // Unneeded semi-colon for indenting - if( a != 0 ) { - r = linear_to_srgb( r, a ); - g = linear_to_srgb( g, a ); - b = linear_to_srgb( b, a ); +struct SurfaceLinearToSrgb +{ + guint32 operator()(guint32 in) + { + EXTRACT_ARGB32(in, a, r, g, b); // Unneeded semi-colon for indenting + if (a != 0) { + r = linear_to_srgb(r, a); + g = linear_to_srgb(g, a); + b = linear_to_srgb(b, a); } - ASSEMBLE_ARGB32(out, a,r,g,b); + ASSEMBLE_ARGB32(out, a, r, g, b); return out; } + private: /* None */ }; @@ -1414,8 +1386,6 @@ cairo_operator_t ink_css_blend_to_cairo_operator(SPBlendMode css_blend) return res; } - - int ink_cairo_surface_linear_to_srgb(cairo_surface_t *surface) { cairo_surface_flush(surface); @@ -1424,7 +1394,7 @@ int ink_cairo_surface_linear_to_srgb(cairo_surface_t *surface) // int stride = cairo_image_surface_get_stride(surface); // unsigned char *data = cairo_image_surface_get_data(surface); - ink_cairo_surface_filter( surface, surface, SurfaceLinearToSrgb() ); + ink_cairo_surface_filter(surface, surface, SurfaceLinearToSrgb()); // /* TODO convert this to OpenMP somehow */ // for (int y = 0; y < height; ++y, data += stride) { @@ -1443,8 +1413,7 @@ int ink_cairo_surface_linear_to_srgb(cairo_surface_t *surface) return width * height; } -cairo_pattern_t * -ink_cairo_pattern_create_checkerboard(guint32 rgba) +cairo_pattern_t *ink_cairo_pattern_create_checkerboard(guint32 rgba) { int const w = 6; int const h = 6; @@ -1454,13 +1423,13 @@ ink_cairo_pattern_create_checkerboard(guint32 rgba) double b = SP_RGBA32_B_F(rgba); float hsl[3]; - SPColor::rgb_to_hsl_floatv(hsl, r, g, b); + SPColor::rgb_to_hsl_floatv(hsl, r, g, b); hsl[2] += hsl[2] < 0.08 ? 0.08 : -0.08; // 0.08 = 0.77-0.69, the original checkerboard colors. float rgb2[3]; SPColor::hsl_to_rgb_floatv(rgb2, hsl[0], hsl[1], hsl[2]); - cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 2*w, 2*h); + cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 2 * w, 2 * h); cairo_t *ct = cairo_create(s); cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); @@ -1499,9 +1468,8 @@ GdkPixbuf *ink_pixbuf_create_from_cairo_surface(cairo_surface_t *s) convert_pixels_argb32_to_pixbuf(pixels, w, h, rs); - GdkPixbuf *pb = gdk_pixbuf_new_from_data( - pixels, GDK_COLORSPACE_RGB, TRUE, 8, - w, h, rs, ink_cairo_pixbuf_cleanup, s); + GdkPixbuf *pb = + gdk_pixbuf_new_from_data(pixels, GDK_COLORSPACE_RGB, TRUE, 8, w, h, rs, ink_cairo_pixbuf_cleanup, s); return pb; } @@ -1514,7 +1482,7 @@ GdkPixbuf *ink_pixbuf_create_from_cairo_surface(cairo_surface_t *s) */ void ink_cairo_pixbuf_cleanup(guchar * /*pixels*/, void *data) { - cairo_surface_t *surface = static_cast(data); + cairo_surface_t *surface = static_cast(data); cairo_surface_destroy(surface); } @@ -1554,7 +1522,8 @@ guint32 argb32_from_pixbuf(guint32 c) guint32 pixbuf_from_argb32(guint32 c) { guint32 a = (c & 0xff000000) >> 24; - if (a == 0) return 0; + if (a == 0) + return 0; // extract color components guint32 r = (c & 0x00ff0000) >> 16; @@ -1562,9 +1531,9 @@ guint32 pixbuf_from_argb32(guint32 c) guint32 b = (c & 0x000000ff); // unpremultiply; adding a/2 gives correct rounding // (taken from Cairo sources) - r = (r * 255 + a/2) / a; - b = (b * 255 + a/2) / a; - g = (g * 255 + a/2) / a; + r = (r * 255 + a / 2) / a; + b = (b * 255 + a / 2) / a; + g = (g * 255 + a / 2) / a; // combine into output #if G_BYTE_ORDER == G_LITTLE_ENDIAN guint32 o = (r) | (g << 8) | (b << 16) | (a << 24); @@ -1581,11 +1550,10 @@ guint32 pixbuf_from_argb32(guint32 c) * Pixbuf data must have an alpha channel, otherwise the results are undefined * (usually a segfault). */ -void -convert_pixels_pixbuf_to_argb32(guchar *data, int w, int h, int stride) +void convert_pixels_pixbuf_to_argb32(guchar *data, int w, int h, int stride) { for (size_t i = 0; i < h; ++i) { - guint32 *px = reinterpret_cast(data + i*stride); + guint32 *px = reinterpret_cast(data + i * stride); for (int j = 0; j < w; ++j) { *px = argb32_from_pixbuf(*px); ++px; @@ -1598,11 +1566,10 @@ convert_pixels_pixbuf_to_argb32(guchar *data, int w, int h, int stride) * This will convert pixel data from GdkPixbuf format to Cairo's native pixel format. * This involves premultiplying alpha and shuffling around the channels. */ -void -convert_pixels_argb32_to_pixbuf(guchar *data, int w, int h, int stride) +void convert_pixels_argb32_to_pixbuf(guchar *data, int w, int h, int stride) { for (size_t i = 0; i < h; ++i) { - guint32 *px = reinterpret_cast(data + i*stride); + guint32 *px = reinterpret_cast(data + i * stride); for (int j = 0; j < w; ++j) { *px = pixbuf_from_argb32(*px); ++px; @@ -1616,20 +1583,16 @@ convert_pixels_argb32_to_pixbuf(guchar *data, int w, int h, int stride) * Note that this is a hack intended to save memory. When the pixbuf is in Cairo's format, * using it with GTK will result in corrupted drawings. */ -void -ink_pixbuf_ensure_argb32(GdkPixbuf *pb) +void ink_pixbuf_ensure_argb32(GdkPixbuf *pb) { - gchar *pixel_format = reinterpret_cast(g_object_get_data(G_OBJECT(pb), "pixel_format")); + gchar *pixel_format = reinterpret_cast(g_object_get_data(G_OBJECT(pb), "pixel_format")); if (pixel_format != nullptr && strcmp(pixel_format, "argb32") == 0) { // nothing to do return; } - convert_pixels_pixbuf_to_argb32( - gdk_pixbuf_get_pixels(pb), - gdk_pixbuf_get_width(pb), - gdk_pixbuf_get_height(pb), - gdk_pixbuf_get_rowstride(pb)); + convert_pixels_pixbuf_to_argb32(gdk_pixbuf_get_pixels(pb), gdk_pixbuf_get_width(pb), gdk_pixbuf_get_height(pb), + gdk_pixbuf_get_rowstride(pb)); g_object_set_data_full(G_OBJECT(pb), "pixel_format", g_strdup("argb32"), g_free); } @@ -1637,20 +1600,16 @@ ink_pixbuf_ensure_argb32(GdkPixbuf *pb) * Converts GdkPixbuf's data back to its native format. * Once this is done, the pixbuf can be used with GTK again. */ -void -ink_pixbuf_ensure_normal(GdkPixbuf *pb) +void ink_pixbuf_ensure_normal(GdkPixbuf *pb) { - gchar *pixel_format = reinterpret_cast(g_object_get_data(G_OBJECT(pb), "pixel_format")); + gchar *pixel_format = reinterpret_cast(g_object_get_data(G_OBJECT(pb), "pixel_format")); if (pixel_format == nullptr || strcmp(pixel_format, "pixbuf") == 0) { // nothing to do return; } - convert_pixels_argb32_to_pixbuf( - gdk_pixbuf_get_pixels(pb), - gdk_pixbuf_get_width(pb), - gdk_pixbuf_get_height(pb), - gdk_pixbuf_get_rowstride(pb)); + convert_pixels_argb32_to_pixbuf(gdk_pixbuf_get_pixels(pb), gdk_pixbuf_get_width(pb), gdk_pixbuf_get_height(pb), + gdk_pixbuf_get_rowstride(pb)); g_object_set_data_full(G_OBJECT(pb), "pixel_format", g_strdup("pixbuf"), g_free); } @@ -1660,97 +1619,102 @@ guint32 argb32_from_rgba(guint32 in) a = (in & 0x000000ff); r = premul_alpha((in & 0xff000000) >> 24, a); g = premul_alpha((in & 0x00ff0000) >> 16, a); - b = premul_alpha((in & 0x0000ff00) >> 8, a); + b = premul_alpha((in & 0x0000ff00) >> 8, a); ASSEMBLE_ARGB32(px, a, r, g, b) return px; } - /** * Converts a pixbuf to a PNG data structure. * For 8-but RGBA png, this is like copying. * */ -const guchar* pixbuf_to_png(guchar const**rows, guchar* px, int num_rows, int num_cols, int stride, int color_type, int bit_depth) -{ - int n_fields = 1 + (color_type&2) + (color_type&4)/4; - const guchar* new_data = (const guchar*)malloc((n_fields * bit_depth * num_rows * num_cols)/8 + 64); - char* ptr = (char*) new_data; - int pad=0; //used when we write image data smaller than one byte (for instance in black and white images where 1px = 1bit) - for(int row = 0; row < num_rows; ++row){ - rows[row] = (const guchar*)ptr; - for(int col = 0; col < num_cols; ++col){ - guint32 *pixel = reinterpret_cast(px + row*stride)+col; +const guchar *pixbuf_to_png(guchar const **rows, guchar *px, int num_rows, int num_cols, int stride, int color_type, + int bit_depth) +{ + int n_fields = 1 + (color_type & 2) + (color_type & 4) / 4; + const guchar *new_data = (const guchar *)malloc((n_fields * bit_depth * num_rows * num_cols) / 8 + 64); + char *ptr = (char *)new_data; + int pad = 0; // used when we write image data smaller than one byte (for instance in black and white images where + // 1px = 1bit) + for (int row = 0; row < num_rows; ++row) { + rows[row] = (const guchar *)ptr; + for (int col = 0; col < num_cols; ++col) { + guint32 *pixel = reinterpret_cast(px + row * stride) + col; #if G_BYTE_ORDER == G_LITTLE_ENDIAN - //this part should probably be rewritten as (a tested, working) big endian, using htons() and ntohs() + // this part should probably be rewritten as (a tested, working) big endian, using htons() and ntohs() guint64 a = (*pixel & 0xff000000) >> 24; guint64 b = (*pixel & 0x00ff0000) >> 16; guint64 g = (*pixel & 0x0000ff00) >> 8; guint64 r = (*pixel & 0x000000ff); - //one of possible rgb to greyscale formulas. This one is called "luminance, "luminosity" or "luma" - guint16 gray = (guint16)((guint32)((0.2126*(r<<24) + 0.7152*(g<<24) + 0.0722*(b<<24)))>>16); - - if (!pad) *((guint64*)ptr)=0; - if (color_type & 2) { //RGB - // for 8bit->16bit transition, I take the FF -> FFFF convention (multiplication by 0x101). + // one of possible rgb to greyscale formulas. This one is called "luminance, "luminosity" or "luma" + guint16 gray = (guint16)((guint32)((0.2126 * (r << 24) + 0.7152 * (g << 24) + 0.0722 * (b << 24))) >> 16); + + if (!pad) + *((guint64 *)ptr) = 0; + if (color_type & 2) { // RGB + // for 8bit->16bit transition, I take the FF -> FFFF convention (multiplication by 0x101). // If you prefer FF -> FF00 (multiplication by 0x100), remove the <<8, <<24, <<40 and <<56 - if (color_type & 4) { //RGBA - if (bit_depth==8) - *((guint32*)ptr) = *pixel; - else - *((guint64*)ptr) = (guint64)((a<<56)+(a<<48)+(b<<40)+(b<<32)+(g<<24)+(g<<16)+(r<<8)+(r)); - } - else{ //no alpha - if(bit_depth==8) - *((guint32*)ptr) = ((*pixel)<<8)>>8; - else - *((guint64*)ptr) = (guint64)((b<<40)+(b<<32)+(g<<24)+(g<<16)+(r<<8)+r); + if (color_type & 4) { // RGBA + if (bit_depth == 8) + *((guint32 *)ptr) = *pixel; + else + *((guint64 *)ptr) = (guint64)((a << 56) + (a << 48) + (b << 40) + (b << 32) + (g << 24) + + (g << 16) + (r << 8) + (r)); + } else { // no alpha + if (bit_depth == 8) + *((guint32 *)ptr) = ((*pixel) << 8) >> 8; + else + *((guint64 *)ptr) = (guint64)((b << 40) + (b << 32) + (g << 24) + (g << 16) + (r << 8) + r); } - } else { //Grayscale - int realpad = 8 - bit_depth - pad; // in PNG numbers are stored left to right, but in most significant bits first, so the first one processed is the ``big'' mask, etc. - if(bit_depth==16) - *(guint16*)ptr= ((gray & 0xff00)>>8) + ((gray &0x00ff)<<8); - else *((guint16*)ptr) += guint16(((gray >> (16-bit_depth))< popmm(); void pop_to_source(); + private: cairo_t *ct; bool pushed; }; /** RAII idiom for Cairo state saving. */ -class CairoSave { +class CairoSave +{ public: - CairoSave(cairo_t *_ct, bool save=false) + CairoSave(cairo_t *_ct, bool save = false) : ct(_ct) , saved(save) { @@ -55,23 +59,27 @@ public: cairo_save(ct); } } - void save() { + void save() + { if (!saved) { cairo_save(ct); saved = true; } } - ~CairoSave() { + ~CairoSave() + { if (saved) cairo_restore(ct); } + private: cairo_t *ct; bool saved; }; /** Cairo context with Inkscape-specific operations. */ -class CairoContext : public Cairo::Context { +class CairoContext : public Cairo::Context +{ public: CairoContext(cairo_t *obj, bool ref = false); @@ -84,9 +92,11 @@ public: /** Class to hold image data for raster images. * Allows easy interoperation with GdkPixbuf and Cairo. */ -class Pixbuf { +class Pixbuf +{ public: - enum PixelFormat { + enum PixelFormat + { PF_CAIRO = 1, PF_GDK = 2, PF_LAST @@ -98,7 +108,7 @@ public: ~Pixbuf(); GdkPixbuf *getPixbufRaw(bool convert_format = true); - //Glib::RefPtr getPixbuf(bool convert_format = true); + // Glib::RefPtr getPixbuf(bool convert_format = true); cairo_surface_t *getSurfaceRaw(bool convert_format = true); Cairo::RefPtr getSurface(bool convert_format = true); @@ -122,7 +132,7 @@ public: static Pixbuf *create_from_file(std::string const &fn, double svgddpi = 0); static Pixbuf *create_from_buffer(std::string const &, double svgddpi = 0, std::string const &fn = ""); - private: +private: static Pixbuf *create_from_buffer(gchar *&&, gsize, double svgddpi = 0, std::string const &fn = ""); void _ensurePixelsARGB32(); @@ -170,7 +180,7 @@ guint32 ink_cairo_surface_average_color(cairo_surface_t *surface); void ink_cairo_surface_average_color(cairo_surface_t *surface, double &r, double &g, double &b, double &a); void ink_cairo_surface_average_color_premul(cairo_surface_t *surface, double &r, double &g, double &b, double &a); -double srgb_to_linear( const double c ); +double srgb_to_linear(const double c); int ink_cairo_surface_srgb_to_linear(cairo_surface_t *surface); int ink_cairo_surface_linear_to_srgb(cairo_surface_t *surface); @@ -182,66 +192,63 @@ void convert_pixels_argb32_to_pixbuf(guchar *data, int w, int h, int rs); G_GNUC_CONST guint32 argb32_from_pixbuf(guint32 in); G_GNUC_CONST guint32 pixbuf_from_argb32(guint32 in); -const guchar* pixbuf_to_png(guchar const**rows, guchar* px, int nrows, int ncols, int stride, int color_type, int bit_depth); +const guchar *pixbuf_to_png(guchar const **rows, guchar *px, int nrows, int ncols, int stride, int color_type, + int bit_depth); /** Convert a pixel in 0xRRGGBBAA format to Cairo ARGB32 format. */ G_GNUC_CONST guint32 argb32_from_rgba(guint32 in); - -G_GNUC_CONST inline guint32 -premul_alpha(const guint32 color, const guint32 alpha) +G_GNUC_CONST inline guint32 premul_alpha(const guint32 color, const guint32 alpha) { const guint32 temp = alpha * color + 128; return (temp + (temp >> 8)) >> 8; } -G_GNUC_CONST inline guint32 -unpremul_alpha(const guint32 color, const guint32 alpha) +G_GNUC_CONST inline guint32 unpremul_alpha(const guint32 color, const guint32 alpha) { // NOTE: you must check for alpha != 0 yourself. - return (255 * color + alpha/2) / alpha; + return (255 * color + alpha / 2) / alpha; } // TODO: move those to 2Geom -void feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv, Geom::Affine trans, Geom::OptRect area, bool optimize_stroke, double stroke_width); -void feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv); +void feed_pathvector_to_cairo(cairo_t *ct, Geom::PathVector const &pathv, Geom::Affine trans, Geom::OptRect area, + bool optimize_stroke, double stroke_width); +void feed_pathvector_to_cairo(cairo_t *ct, Geom::PathVector const &pathv); -#define EXTRACT_ARGB32(px,a,r,g,b) \ - guint32 a, r, g, b; \ - a = ((px) & 0xff000000) >> 24; \ - r = ((px) & 0x00ff0000) >> 16; \ - g = ((px) & 0x0000ff00) >> 8; \ - b = ((px) & 0x000000ff); +#define EXTRACT_ARGB32(px, a, r, g, b) \ + guint32 a, r, g, b; \ + a = ((px)&0xff000000) >> 24; \ + r = ((px)&0x00ff0000) >> 16; \ + g = ((px)&0x0000ff00) >> 8; \ + b = ((px)&0x000000ff); -#define ASSEMBLE_ARGB32(px,a,r,g,b) \ - guint32 px = (a << 24) | (r << 16) | (g << 8) | b; +#define ASSEMBLE_ARGB32(px, a, r, g, b) guint32 px = (a << 24) | (r << 16) | (g << 8) | b; -inline double srgb_to_linear( const double c ) { - if( c < 0.04045 ) { +inline double srgb_to_linear(const double c) +{ + if (c < 0.04045) { return c / 12.92; } else { - return pow( (c+0.055)/1.055, 2.4 ); + return pow((c + 0.055) / 1.055, 2.4); } } - namespace Inkscape { -namespace Display -{ +namespace Display { inline void ExtractARGB32(guint32 px, guint32 &a, guint32 &r, guint32 &g, guint &b) { - a = ((px) & 0xff000000) >> 24; - r = ((px) & 0x00ff0000) >> 16; - g = ((px) & 0x0000ff00) >> 8; - b = ((px) & 0x000000ff); + a = ((px)&0xff000000) >> 24; + r = ((px)&0x00ff0000) >> 16; + g = ((px)&0x0000ff00) >> 8; + b = ((px)&0x000000ff); } inline void ExtractRGB32(guint32 px, guint32 &r, guint32 &g, guint &b) { - r = ((px) & 0x00ff0000) >> 16; - g = ((px) & 0x0000ff00) >> 8; - b = ((px) & 0x000000ff); + r = ((px)&0x00ff0000) >> 16; + g = ((px)&0x0000ff00) >> 8; + b = ((px)&0x000000ff); } inline guint AssembleARGB32(guint32 a, guint32 r, guint32 g, guint32 b) diff --git a/src/display/canvas-arena.cpp b/src/display/canvas-arena.cpp index 28c15f56c1c9165ec5218fc1a8c069a7bd216636..88a320fd1a091249f2e2fca821c698f9fd18f189 100644 --- a/src/display/canvas-arena.cpp +++ b/src/display/canvas-arena.cpp @@ -12,25 +12,24 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "canvas-arena.h" + #include -#include "sp-canvas-util.h" -#include "canvas-arena.h" #include "cairo-utils.h" #include "drawing-context.h" -#include "drawing-item.h" #include "drawing-group.h" +#include "drawing-item.h" #include "drawing-surface.h" - -#include "preferences.h" - #include "helper/sp-marshal.h" - +#include "preferences.h" +#include "sp-canvas-util.h" #include "ui/widget/canvas.h" using namespace Inkscape; -enum { +enum +{ ARENA_EVENT, LAST_SIGNAL }; @@ -38,32 +37,34 @@ enum { static void sp_canvas_arena_destroy(SPCanvasItem *object); static void sp_canvas_arena_item_deleted(SPCanvasArena *arena, Inkscape::DrawingItem *item); -static void sp_canvas_arena_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); -static void sp_canvas_arena_render (SPCanvasItem *item, SPCanvasBuf *buf); -static double sp_canvas_arena_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item); -static void sp_canvas_arena_viewbox_changed (SPCanvasItem *item, Geom::IntRect const &new_area); -static gint sp_canvas_arena_event (SPCanvasItem *item, GdkEvent *event); +static void sp_canvas_arena_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); +static void sp_canvas_arena_render(SPCanvasItem *item, SPCanvasBuf *buf); +static double sp_canvas_arena_point(SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item); +static void sp_canvas_arena_viewbox_changed(SPCanvasItem *item, Geom::IntRect const &new_area); +static gint sp_canvas_arena_event(SPCanvasItem *item, GdkEvent *event); -static gint sp_canvas_arena_send_event (SPCanvasArena *arena, GdkEvent *event); +static gint sp_canvas_arena_send_event(SPCanvasArena *arena, GdkEvent *event); -static void sp_canvas_arena_request_update (SPCanvasArena *ca, DrawingItem *item); -static void sp_canvas_arena_request_render (SPCanvasArena *ca, Geom::IntRect const &area); +static void sp_canvas_arena_request_update(SPCanvasArena *ca, DrawingItem *item); +static void sp_canvas_arena_request_render(SPCanvasArena *ca, Geom::IntRect const &area); static guint signals[LAST_SIGNAL] = {0}; -struct CachePrefObserver : public Inkscape::Preferences::Observer { +struct CachePrefObserver : public Inkscape::Preferences::Observer +{ CachePrefObserver(SPCanvasArena *arena) : Inkscape::Preferences::Observer("/options/renderingcache") , _arena(arena) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); std::vector v = prefs->getAllEntries(observed_path); - for (const auto & i : v) { + for (const auto &i : v) { notify(i); } prefs->addObserver(*this); } - void notify(Preferences::Entry const &v) override { + void notify(Preferences::Entry const &v) override + { Glib::ustring name = v.getEntryName(); if (name == "size") { _arena->drawing.setCacheBudget((1 << 20) * v.getIntLimited(64, 0, 4096)); @@ -74,18 +75,13 @@ struct CachePrefObserver : public Inkscape::Preferences::Observer { G_DEFINE_TYPE(SPCanvasArena, sp_canvas_arena, SP_TYPE_CANVAS_ITEM); -static void -sp_canvas_arena_class_init (SPCanvasArenaClass *klass) +static void sp_canvas_arena_class_init(SPCanvasArenaClass *klass) { - SPCanvasItemClass *item_class = (SPCanvasItemClass *) klass; + SPCanvasItemClass *item_class = (SPCanvasItemClass *)klass; - signals[ARENA_EVENT] = g_signal_new ("arena_event", - G_TYPE_FROM_CLASS(item_class), - G_SIGNAL_RUN_LAST, - ((glong)((guint8*)&(klass->arena_event) - (guint8*)klass)), - nullptr, nullptr, - sp_marshal_INT__POINTER_POINTER, - G_TYPE_INT, 2, G_TYPE_POINTER, G_TYPE_POINTER); + signals[ARENA_EVENT] = g_signal_new("arena_event", G_TYPE_FROM_CLASS(item_class), G_SIGNAL_RUN_LAST, + ((glong)((guint8 *)&(klass->arena_event) - (guint8 *)klass)), nullptr, nullptr, + sp_marshal_INT__POINTER_POINTER, G_TYPE_INT, 2, G_TYPE_POINTER, G_TYPE_POINTER); item_class->destroy = sp_canvas_arena_destroy; item_class->update = sp_canvas_arena_update; @@ -95,8 +91,7 @@ sp_canvas_arena_class_init (SPCanvasArenaClass *klass) item_class->viewbox_changed = sp_canvas_arena_viewbox_changed; } -static void -sp_canvas_arena_init (SPCanvasArena *arena) +static void sp_canvas_arena_init(SPCanvasArena *arena) { SP_CANVAS_ITEM(arena)->name = "CanvasArena"; @@ -110,18 +105,9 @@ sp_canvas_arena_init (SPCanvasArena *arena) arena->observer = new CachePrefObserver(arena); - arena->drawing.signal_request_update.connect( - sigc::bind<0>( - sigc::ptr_fun(&sp_canvas_arena_request_update), - arena)); - arena->drawing.signal_request_render.connect( - sigc::bind<0>( - sigc::ptr_fun(&sp_canvas_arena_request_render), - arena)); - arena->drawing.signal_item_deleted.connect( - sigc::bind<0>( - sigc::ptr_fun(&sp_canvas_arena_item_deleted), - arena)); + arena->drawing.signal_request_update.connect(sigc::bind<0>(sigc::ptr_fun(&sp_canvas_arena_request_update), arena)); + arena->drawing.signal_request_render.connect(sigc::bind<0>(sigc::ptr_fun(&sp_canvas_arena_request_render), arena)); + arena->drawing.signal_item_deleted.connect(sigc::bind<0>(sigc::ptr_fun(&sp_canvas_arena_item_deleted), arena)); arena->active = nullptr; } @@ -137,10 +123,9 @@ static void sp_canvas_arena_destroy(SPCanvasItem *object) SP_CANVAS_ITEM_CLASS(sp_canvas_arena_parent_class)->destroy(object); } -static void -sp_canvas_arena_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) +static void sp_canvas_arena_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) { - SPCanvasArena *arena = SP_CANVAS_ARENA (item); + SPCanvasArena *arena = SP_CANVAS_ARENA(item); if (SP_CANVAS_ITEM_CLASS(sp_canvas_arena_parent_class)->update) SP_CANVAS_ITEM_CLASS(sp_canvas_arena_parent_class)->update(item, affine, flags); @@ -163,7 +148,7 @@ sp_canvas_arena_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned DrawingItem *new_arena = arena->drawing.pick(arena->c, arena->drawing.delta, arena->sticky); if (new_arena != arena->active) { GdkEventCrossing ec; - ec.window = gtk_widget_get_window (GTK_WIDGET (item->canvas->gobj())); + ec.window = gtk_widget_get_window(GTK_WIDGET(item->canvas->gobj())); ec.send_event = TRUE; ec.subwindow = ec.window; ec.time = GDK_CURRENT_TIME; @@ -172,33 +157,32 @@ sp_canvas_arena_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned /* fixme: */ if (arena->active) { ec.type = GDK_LEAVE_NOTIFY; - sp_canvas_arena_send_event (arena, (GdkEvent *) &ec); + sp_canvas_arena_send_event(arena, (GdkEvent *)&ec); } arena->active = new_arena; if (arena->active) { ec.type = GDK_ENTER_NOTIFY; - sp_canvas_arena_send_event (arena, (GdkEvent *) &ec); + sp_canvas_arena_send_event(arena, (GdkEvent *)&ec); } } } } -static void -sp_canvas_arena_item_deleted(SPCanvasArena *arena, Inkscape::DrawingItem *item) +static void sp_canvas_arena_item_deleted(SPCanvasArena *arena, Inkscape::DrawingItem *item) { if (arena->active == item) { arena->active = nullptr; } } -static void -sp_canvas_arena_render (SPCanvasItem *item, SPCanvasBuf *buf) +static void sp_canvas_arena_render(SPCanvasItem *item, SPCanvasBuf *buf) { // todo: handle NR_ARENA_ITEM_RENDER_NO_CACHE - SPCanvasArena *arena = SP_CANVAS_ARENA (item); + SPCanvasArena *arena = SP_CANVAS_ARENA(item); Geom::OptIntRect r = buf->rect; - if (!r || r->hasZeroArea()) return; + if (!r || r->hasZeroArea()) + return; Inkscape::DrawingContext dc(buf->ct, r->min()); @@ -206,10 +190,9 @@ sp_canvas_arena_render (SPCanvasItem *item, SPCanvasBuf *buf) arena->drawing.render(dc, *r); } -static double -sp_canvas_arena_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item) +static double sp_canvas_arena_point(SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item) { - SPCanvasArena *arena = SP_CANVAS_ARENA (item); + SPCanvasArena *arena = SP_CANVAS_ARENA(item); arena->drawing.update(Geom::IntRect::infinite(), arena->ctx, DrawingItem::STATE_PICK | DrawingItem::STATE_BBOX); DrawingItem *picked = arena->drawing.pick(p, arena->drawing.delta, arena->sticky); @@ -224,13 +207,12 @@ sp_canvas_arena_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_ return 1e18; } -static void -sp_canvas_arena_viewbox_changed (SPCanvasItem *item, Geom::IntRect const &new_area) +static void sp_canvas_arena_viewbox_changed(SPCanvasItem *item, Geom::IntRect const &new_area) { SPCanvasArena *arena = SP_CANVAS_ARENA(item); // make the cache limit larger than screen to facilitate smooth scrolling Geom::IntRect expanded = new_area; - Geom::IntPoint expansion(new_area.width()/2, new_area.height()/2); + Geom::IntPoint expansion(new_area.width() / 2, new_area.height() / 2); expanded.expandBy(expansion); arena->drawing.setCacheLimit(expanded); } @@ -238,20 +220,19 @@ sp_canvas_arena_viewbox_changed (SPCanvasItem *item, Geom::IntRect const &new_ar // What is this used for? It appears to allow one to get signals on entering/leaving elements which // is intend to be used by Inkview to change the cursor when over an anchor. However arena->active // appears to only be set to root. -static gint -sp_canvas_arena_event (SPCanvasItem *item, GdkEvent *event) +static gint sp_canvas_arena_event(SPCanvasItem *item, GdkEvent *event) { Inkscape::DrawingItem *new_arena; /* fixme: This sucks, we have to handle enter/leave notifiers */ - SPCanvasArena *arena = SP_CANVAS_ARENA (item); + SPCanvasArena *arena = SP_CANVAS_ARENA(item); gint ret = FALSE; switch (event->type) { case GDK_ENTER_NOTIFY: if (!arena->cursor) { if (arena->active) { - //g_warning ("Cursor entered to arena with already active item"); + // g_warning ("Cursor entered to arena with already active item"); } arena->cursor = TRUE; @@ -260,15 +241,15 @@ sp_canvas_arena_event (SPCanvasItem *item, GdkEvent *event) /* fixme: Not sure abut this, but seems the right thing (Lauris) */ arena->drawing.update(Geom::IntRect::infinite(), arena->ctx, - DrawingItem::STATE_PICK | DrawingItem::STATE_BBOX, 0); + DrawingItem::STATE_PICK | DrawingItem::STATE_BBOX, 0); arena->active = arena->drawing.pick(arena->c, arena->drawing.delta, arena->sticky); - ret = sp_canvas_arena_send_event (arena, event); + ret = sp_canvas_arena_send_event(arena, event); } break; case GDK_LEAVE_NOTIFY: if (arena->cursor) { - ret = sp_canvas_arena_send_event (arena, event); + ret = sp_canvas_arena_send_event(arena, event); arena->active = nullptr; arena->cursor = FALSE; } @@ -280,7 +261,7 @@ sp_canvas_arena_event (SPCanvasItem *item, GdkEvent *event) /* fixme: Not sure abut this, but seems the right thing (Lauris) */ arena->drawing.update(Geom::IntRect::infinite(), arena->ctx, - DrawingItem::STATE_PICK | DrawingItem::STATE_BBOX); + DrawingItem::STATE_PICK | DrawingItem::STATE_BBOX); new_arena = arena->drawing.pick(arena->c, arena->drawing.delta, arena->sticky); if (new_arena != arena->active) { GdkEventCrossing ec; @@ -293,15 +274,15 @@ sp_canvas_arena_event (SPCanvasItem *item, GdkEvent *event) /* fixme: */ if (arena->active) { ec.type = GDK_LEAVE_NOTIFY; - ret = sp_canvas_arena_send_event (arena, (GdkEvent *) &ec); + ret = sp_canvas_arena_send_event(arena, (GdkEvent *)&ec); } arena->active = new_arena; if (arena->active) { ec.type = GDK_ENTER_NOTIFY; - ret = sp_canvas_arena_send_event (arena, (GdkEvent *) &ec); + ret = sp_canvas_arena_send_event(arena, (GdkEvent *)&ec); } } - ret = ret || sp_canvas_arena_send_event (arena, event); + ret = ret || sp_canvas_arena_send_event(arena, event); break; case GDK_SCROLL: { @@ -312,67 +293,63 @@ sp_canvas_arena_event (SPCanvasItem *item, GdkEvent *event) /* Zoom is emitted by the canvas as well, ignore here */ return FALSE; } - ret = sp_canvas_arena_send_event (arena, event); + ret = sp_canvas_arena_send_event(arena, event); break; - } + } default: /* Just send event */ - ret = sp_canvas_arena_send_event (arena, event); + ret = sp_canvas_arena_send_event(arena, event); break; } return ret; } -static gint -sp_canvas_arena_send_event (SPCanvasArena *arena, GdkEvent *event) +static gint sp_canvas_arena_send_event(SPCanvasArena *arena, GdkEvent *event) { gint ret = FALSE; /* Send event to arena */ - g_signal_emit (G_OBJECT (arena), signals[ARENA_EVENT], 0, arena->active, event, &ret); + g_signal_emit(G_OBJECT(arena), signals[ARENA_EVENT], 0, arena->active, event, &ret); return ret; } -static void -sp_canvas_arena_request_update (SPCanvasArena *ca, DrawingItem */*item*/) +static void sp_canvas_arena_request_update(SPCanvasArena *ca, DrawingItem * /*item*/) { - sp_canvas_item_request_update (SP_CANVAS_ITEM (ca)); + sp_canvas_item_request_update(SP_CANVAS_ITEM(ca)); } static void sp_canvas_arena_request_render(SPCanvasArena *ca, Geom::IntRect const &area) { - Inkscape:UI::Widget::Canvas *canvas = SP_CANVAS_ITEM(ca)->canvas; +Inkscape: + UI::Widget::Canvas *canvas = SP_CANVAS_ITEM(ca)->canvas; canvas->redraw_area(area.left(), area.top(), area.right(), area.bottom()); } -void -sp_canvas_arena_set_pick_delta (SPCanvasArena *ca, gdouble delta) +void sp_canvas_arena_set_pick_delta(SPCanvasArena *ca, gdouble delta) { - g_return_if_fail (ca != nullptr); - g_return_if_fail (SP_IS_CANVAS_ARENA (ca)); + g_return_if_fail(ca != nullptr); + g_return_if_fail(SP_IS_CANVAS_ARENA(ca)); /* fixme: repick? */ ca->delta = delta; } -void -sp_canvas_arena_set_sticky (SPCanvasArena *ca, gboolean sticky) +void sp_canvas_arena_set_sticky(SPCanvasArena *ca, gboolean sticky) { - g_return_if_fail (ca != nullptr); - g_return_if_fail (SP_IS_CANVAS_ARENA (ca)); + g_return_if_fail(ca != nullptr); + g_return_if_fail(SP_IS_CANVAS_ARENA(ca)); /* fixme: repick? */ ca->sticky = sticky; } -void -sp_canvas_arena_render_surface (SPCanvasArena *ca, cairo_surface_t *surface, Geom::IntRect const &r) +void sp_canvas_arena_render_surface(SPCanvasArena *ca, cairo_surface_t *surface, Geom::IntRect const &r) { - g_return_if_fail (ca != nullptr); - g_return_if_fail (SP_IS_CANVAS_ARENA (ca)); + g_return_if_fail(ca != nullptr); + g_return_if_fail(SP_IS_CANVAS_ARENA(ca)); Inkscape::DrawingContext dc(surface, r.min()); ca->drawing.update(Geom::IntRect::infinite(), ca->ctx); diff --git a/src/display/canvas-arena.h b/src/display/canvas-arena.h index 3f705a2be80ddb58dc3ff57feaf714461978bdfb..857cac0f531196a0bc4bd3fd84fe231237f368a9 100644 --- a/src/display/canvas-arena.h +++ b/src/display/canvas-arena.h @@ -16,19 +16,19 @@ #include <2geom/rect.h> -#include "display/drawing.h" #include "display/drawing-item.h" +#include "display/drawing.h" #include "display/sp-canvas-item.h" -#define SP_TYPE_CANVAS_ARENA (sp_canvas_arena_get_type ()) -#define SP_CANVAS_ARENA(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SP_TYPE_CANVAS_ARENA, SPCanvasArena)) -#define SP_CANVAS_ARENA_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), SP_TYPE_CANVAS_ARENA, SPCanvasArenaClass)) -#define SP_IS_CANVAS_ARENA(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SP_TYPE_CANVAS_ARENA)) -#define SP_IS_CANVAS_ARENA_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), SP_TYPE_CANVAS_ARENA)) +#define SP_TYPE_CANVAS_ARENA (sp_canvas_arena_get_type()) +#define SP_CANVAS_ARENA(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CANVAS_ARENA, SPCanvasArena)) +#define SP_CANVAS_ARENA_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), SP_TYPE_CANVAS_ARENA, SPCanvasArenaClass)) +#define SP_IS_CANVAS_ARENA(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CANVAS_ARENA)) +#define SP_IS_CANVAS_ARENA_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), SP_TYPE_CANVAS_ARENA)) -typedef struct _SPCanvasArena SPCanvasArena; +typedef struct _SPCanvasArena SPCanvasArena; typedef struct _SPCanvasArenaClass SPCanvasArenaClass; -typedef struct _cairo_surface cairo_surface_t; +typedef struct _cairo_surface cairo_surface_t; struct CachePrefObserver; namespace Inkscape { @@ -38,7 +38,8 @@ class DrawingItem; } // namespace Inkscape -struct _SPCanvasArena { +struct _SPCanvasArena +{ SPCanvasItem item; guint cursor : 1; @@ -55,17 +56,18 @@ struct _SPCanvasArena { double delta; }; -struct _SPCanvasArenaClass { +struct _SPCanvasArenaClass +{ SPCanvasItemClass parent_class; - gint (* arena_event) (SPCanvasArena *carena, Inkscape::DrawingItem *item, GdkEvent *event); + gint (*arena_event)(SPCanvasArena *carena, Inkscape::DrawingItem *item, GdkEvent *event); }; -GType sp_canvas_arena_get_type (); +GType sp_canvas_arena_get_type(); -void sp_canvas_arena_set_pick_delta (SPCanvasArena *ca, gdouble delta); -void sp_canvas_arena_set_sticky (SPCanvasArena *ca, gboolean sticky); +void sp_canvas_arena_set_pick_delta(SPCanvasArena *ca, gdouble delta); +void sp_canvas_arena_set_sticky(SPCanvasArena *ca, gboolean sticky); -void sp_canvas_arena_render_surface (SPCanvasArena *ca, cairo_surface_t *surface, Geom::IntRect const &area); +void sp_canvas_arena_render_surface(SPCanvasArena *ca, cairo_surface_t *surface, Geom::IntRect const &area); #endif // SEEN_SP_CANVAS_ARENA_H diff --git a/src/display/canvas-axonomgrid.cpp b/src/display/canvas-axonomgrid.cpp index f0309d41df140404f4f35bea35dc18b41a609188..c5e80793be2b6c38596d6be3924a31b592de2e65 100644 --- a/src/display/canvas-axonomgrid.cpp +++ b/src/display/canvas-axonomgrid.cpp @@ -14,42 +14,44 @@ * to the right). The x-axis will always have an angle between 0 and 90 degrees. */ -#include -#include -#include +#include "display/canvas-axonomgrid.h" #include +#include +#include +#include -#include "display/canvas-axonomgrid.h" - -#include "ui/widget/registered-widget.h" +#include "2geom/angle.h" +#include "2geom/line.h" #include "desktop.h" - #include "display/cairo-utils.h" #include "display/canvas-grid.h" #include "display/sp-canvas-util.h" #include "document.h" +#include "helper/mathfns.h" #include "inkscape.h" -#include "preferences.h" #include "object/sp-namedview.h" #include "object/sp-object.h" #include "object/sp-root.h" +#include "preferences.h" #include "svg/svg-color.h" -#include "2geom/line.h" -#include "2geom/angle.h" -#include "helper/mathfns.h" +#include "ui/widget/registered-widget.h" #include "util/units.h" using Inkscape::Util::unit_table; -enum Dim3 { X=0, Y, Z }; +enum Dim3 +{ + X = 0, + Y, + Z +}; /** * This function calls Cairo to render a line on a particular canvas buffer. * Coordinates are interpreted as SCREENcoordinates */ -static void -sp_caxonomgrid_drawline (SPCanvasBuf *buf, gint x0, gint y0, gint x1, gint y1, guint32 rgba) +static void sp_caxonomgrid_drawline(SPCanvasBuf *buf, gint x0, gint y0, gint x1, gint y1, guint32 rgba) { cairo_move_to(buf->ct, 0.5 + x0, 0.5 + y0); cairo_line_to(buf->ct, 0.5 + x1, 0.5 + y1); @@ -57,8 +59,7 @@ sp_caxonomgrid_drawline (SPCanvasBuf *buf, gint x0, gint y0, gint x1, gint y1, g cairo_stroke(buf->ct); } -static void -sp_grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba) +static void sp_grid_vline(SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba) { if ((x < buf->rect.left()) || (x >= buf->rect.right())) return; @@ -71,8 +72,7 @@ sp_grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba) namespace Inkscape { - -CanvasAxonomGrid::CanvasAxonomGrid (SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument * in_doc) +CanvasAxonomGrid::CanvasAxonomGrid(SPNamedView *nv, Inkscape::XML::Node *in_repr, SPDocument *in_doc) : CanvasGrid(nv, in_repr, in_doc, GRID_AXONOMETRIC) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -80,12 +80,15 @@ CanvasAxonomGrid::CanvasAxonomGrid (SPNamedView * nv, Inkscape::XML::Node * in_r if (!gridunit) { gridunit = unit_table.getUnit("px"); } - origin[Geom::X] = Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/axonom/origin_x", 0.0), gridunit, "px"); - origin[Geom::Y] = Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/axonom/origin_y", 0.0), gridunit, "px"); + origin[Geom::X] = + Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/axonom/origin_x", 0.0), gridunit, "px"); + origin[Geom::Y] = + Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/axonom/origin_y", 0.0), gridunit, "px"); color = prefs->getInt("/options/grids/axonom/color", GRID_DEFAULT_COLOR); empcolor = prefs->getInt("/options/grids/axonom/empcolor", GRID_DEFAULT_EMPCOLOR); empspacing = prefs->getInt("/options/grids/axonom/empspacing", 5); - lengthy = Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/axonom/spacing_y", 1.0), gridunit, "px"); + lengthy = + Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/axonom/spacing_y", 1.0), gridunit, "px"); angle_deg[X] = prefs->getDouble("/options/grids/axonom/angle_x", 30.0); angle_deg[Z] = prefs->getDouble("/options/grids/axonom/angle_z", 30.0); angle_deg[Y] = 0; @@ -97,12 +100,14 @@ CanvasAxonomGrid::CanvasAxonomGrid (SPNamedView * nv, Inkscape::XML::Node * in_r snapper = new CanvasAxonomGridSnapper(this, &namedview->snap_manager, 0); - if (repr) readRepr(); + if (repr) + readRepr(); } -CanvasAxonomGrid::~CanvasAxonomGrid () +CanvasAxonomGrid::~CanvasAxonomGrid() { - if (snapper) delete snapper; + if (snapper) + delete snapper; } static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color) @@ -118,25 +123,22 @@ static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color) } v = CLAMP(v, 0.0, 1.0); - *color = (*color & 0xffffff00) | (guint32) floor(v * 255.9999); + *color = (*color & 0xffffff00) | (guint32)floor(v * 255.9999); return TRUE; } - - -void -CanvasAxonomGrid::readRepr() +void CanvasAxonomGrid::readRepr() { SPRoot *root = doc->getRoot(); double scale_x = 1.0; double scale_y = 1.0; - if( root->viewBox_set ) { - scale_x = root->width.computed / root->viewBox.width(); + if (root->viewBox_set) { + scale_x = root->width.computed / root->viewBox.width(); scale_y = root->height.computed / root->viewBox.height(); if (Geom::are_near(scale_x / scale_y, 1.0, Geom::EPSILON)) { // scaling is uniform, try to reduce numerical error - scale_x = (scale_x + scale_y)/2.0; + scale_x = (scale_x + scale_y) / 2.0; double scale_none = Inkscape::Util::Quantity::convert(1, doc->getDisplayUnit(), "px"); if (Geom::are_near(scale_x / scale_none, 1.0, Geom::EPSILON)) scale_x = scale_none; // objects are same size, reduce numerical error @@ -146,11 +148,10 @@ CanvasAxonomGrid::readRepr() gchar const *value; - if ( (value = repr->attribute("originx")) ) { - + if ((value = repr->attribute("originx"))) { Inkscape::Util::Quantity q = unit_table.parseQuantity(value); - if( q.unit->type == UNIT_TYPE_LINEAR ) { + if (q.unit->type == UNIT_TYPE_LINEAR) { // Legacy grid not in 'user units' origin[Geom::X] = q.value("px"); } else { @@ -159,11 +160,10 @@ CanvasAxonomGrid::readRepr() } } - if ( (value = repr->attribute("originy")) ) { - + if ((value = repr->attribute("originy"))) { Inkscape::Util::Quantity q = unit_table.parseQuantity(value); - if( q.unit->type == UNIT_TYPE_LINEAR ) { + if (q.unit->type == UNIT_TYPE_LINEAR) { // Legacy grid not in 'user units' origin[Geom::Y] = q.value("px"); } else { @@ -172,74 +172,78 @@ CanvasAxonomGrid::readRepr() } } - if ( (value = repr->attribute("spacingy")) ) { - + if ((value = repr->attribute("spacingy"))) { Inkscape::Util::Quantity q = unit_table.parseQuantity(value); - if( q.unit->type == UNIT_TYPE_LINEAR ) { + if (q.unit->type == UNIT_TYPE_LINEAR) { // Legacy grid not in 'user units' lengthy = q.value("px"); } else { // Grid in 'user units' lengthy = q.quantity * scale_y; // We do not handle scale_x != scale_y } - if (lengthy < 0.0500) lengthy = 0.0500; + if (lengthy < 0.0500) + lengthy = 0.0500; } - if ( (value = repr->attribute("gridanglex")) ) { + if ((value = repr->attribute("gridanglex"))) { angle_deg[X] = g_ascii_strtod(value, nullptr); - if (angle_deg[X] < 0.) angle_deg[X] = 0.; - if (angle_deg[X] > 89.0) angle_deg[X] = 89.0; + if (angle_deg[X] < 0.) + angle_deg[X] = 0.; + if (angle_deg[X] > 89.0) + angle_deg[X] = 89.0; angle_rad[X] = Geom::rad_from_deg(angle_deg[X]); tan_angle[X] = tan(angle_rad[X]); } - if ( (value = repr->attribute("gridanglez")) ) { + if ((value = repr->attribute("gridanglez"))) { angle_deg[Z] = g_ascii_strtod(value, nullptr); - if (angle_deg[Z] < 0.) angle_deg[Z] = 0.; - if (angle_deg[Z] > 89.0) angle_deg[Z] = 89.0; + if (angle_deg[Z] < 0.) + angle_deg[Z] = 0.; + if (angle_deg[Z] > 89.0) + angle_deg[Z] = 89.0; angle_rad[Z] = Geom::rad_from_deg(angle_deg[Z]); tan_angle[Z] = tan(angle_rad[Z]); } - if ( (value = repr->attribute("color")) ) { + if ((value = repr->attribute("color"))) { color = (color & 0xff) | sp_svg_read_color(value, color); } - if ( (value = repr->attribute("empcolor")) ) { + if ((value = repr->attribute("empcolor"))) { empcolor = (empcolor & 0xff) | sp_svg_read_color(value, empcolor); } - if ( (value = repr->attribute("opacity")) ) { + if ((value = repr->attribute("opacity"))) { sp_nv_read_opacity(value, &color); } - if ( (value = repr->attribute("empopacity")) ) { + if ((value = repr->attribute("empopacity"))) { sp_nv_read_opacity(value, &empcolor); } - if ( (value = repr->attribute("empspacing")) ) { + if ((value = repr->attribute("empspacing"))) { empspacing = atoi(value); } - if ( (value = repr->attribute("visible")) ) { - visible = (strcmp(value,"false") != 0 && strcmp(value, "0") != 0); + if ((value = repr->attribute("visible"))) { + visible = (strcmp(value, "false") != 0 && strcmp(value, "0") != 0); } - if ( (value = repr->attribute("enabled")) ) { + if ((value = repr->attribute("enabled"))) { g_assert(snapper != nullptr); - snapper->setEnabled(strcmp(value,"false") != 0 && strcmp(value, "0") != 0); + snapper->setEnabled(strcmp(value, "false") != 0 && strcmp(value, "0") != 0); } - if ( (value = repr->attribute("snapvisiblegridlinesonly")) ) { + if ((value = repr->attribute("snapvisiblegridlinesonly"))) { g_assert(snapper != nullptr); - snapper->setSnapVisibleOnly(strcmp(value,"false") != 0 && strcmp(value, "0") != 0); + snapper->setSnapVisibleOnly(strcmp(value, "false") != 0 && strcmp(value, "0") != 0); } - if ( (value = repr->attribute("units")) ) { + if ((value = repr->attribute("units"))) { gridunit = unit_table.getUnit(value); // Display unit identifier in grid menu } - for (auto i:canvasitems) { + for (auto i : canvasitems) { sp_canvas_item_request_update(i); } return; @@ -248,44 +252,40 @@ CanvasAxonomGrid::readRepr() /** * Called when XML node attribute changed; updates dialog widgets if change was not done by widgets themselves. */ -void -CanvasAxonomGrid::onReprAttrChanged(Inkscape::XML::Node */*repr*/, gchar const */*key*/, gchar const */*oldval*/, gchar const */*newval*/, bool /*is_interactive*/) +void CanvasAxonomGrid::onReprAttrChanged(Inkscape::XML::Node * /*repr*/, gchar const * /*key*/, + gchar const * /*oldval*/, gchar const * /*newval*/, bool /*is_interactive*/) { readRepr(); - if ( ! (_wr.isUpdating()) ) + if (!(_wr.isUpdating())) updateWidgets(); } -Gtk::Widget * -CanvasAxonomGrid::newSpecificWidget() +Gtk::Widget *CanvasAxonomGrid::newSpecificWidget() { - _rumg = Gtk::manage( new Inkscape::UI::Widget::RegisteredUnitMenu( - _("Grid _units:"), "units", _wr, repr, doc) ); - _rsu_ox = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit( - _("_Origin X:"), _("X coordinate of grid origin"), "originx", - *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_x) ); - _rsu_oy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit( - _("O_rigin Y:"), _("Y coordinate of grid origin"), "originy", - *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_y) ); - _rsu_sy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit( - _("Spacing _Y:"), _("Base length of z-axis"), "spacingy", - *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_y) ); - _rsu_ax = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalar( - _("Angle X:"), _("Angle of x-axis"), "gridanglex", _wr, repr, doc ) ); - _rsu_az = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalar( - _("Angle Z:"), _("Angle of z-axis"), "gridanglez", _wr, repr, doc ) ); - - _rcp_gcol = Gtk::manage( new Inkscape::UI::Widget::RegisteredColorPicker( - _("Minor grid line _color:"), _("Minor grid line color"), _("Color of the minor grid lines"), - "color", "opacity", _wr, repr, doc)); - _rcp_gmcol = Gtk::manage( new Inkscape::UI::Widget::RegisteredColorPicker( - _("Ma_jor grid line color:"), _("Major grid line color"), - _("Color of the major (highlighted) grid lines"), - "empcolor", "empopacity", _wr, repr, doc)); - - _rsi = Gtk::manage( new Inkscape::UI::Widget::RegisteredSuffixedInteger( - _("_Major grid line every:"), "", _("lines"), "empspacing", _wr, repr, doc ) ); + _rumg = Gtk::manage(new Inkscape::UI::Widget::RegisteredUnitMenu(_("Grid _units:"), "units", _wr, repr, doc)); + _rsu_ox = Gtk::manage( + new Inkscape::UI::Widget::RegisteredScalarUnit(_("_Origin X:"), _("X coordinate of grid origin"), "originx", + *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_x)); + _rsu_oy = Gtk::manage( + new Inkscape::UI::Widget::RegisteredScalarUnit(_("O_rigin Y:"), _("Y coordinate of grid origin"), "originy", + *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_y)); + _rsu_sy = Gtk::manage(new Inkscape::UI::Widget::RegisteredScalarUnit( + _("Spacing _Y:"), _("Base length of z-axis"), "spacingy", *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_y)); + _rsu_ax = Gtk::manage( + new Inkscape::UI::Widget::RegisteredScalar(_("Angle X:"), _("Angle of x-axis"), "gridanglex", _wr, repr, doc)); + _rsu_az = Gtk::manage( + new Inkscape::UI::Widget::RegisteredScalar(_("Angle Z:"), _("Angle of z-axis"), "gridanglez", _wr, repr, doc)); + + _rcp_gcol = Gtk::manage(new Inkscape::UI::Widget::RegisteredColorPicker( + _("Minor grid line _color:"), _("Minor grid line color"), _("Color of the minor grid lines"), "color", + "opacity", _wr, repr, doc)); + _rcp_gmcol = Gtk::manage(new Inkscape::UI::Widget::RegisteredColorPicker( + _("Ma_jor grid line color:"), _("Major grid line color"), _("Color of the major (highlighted) grid lines"), + "empcolor", "empopacity", _wr, repr, doc)); + + _rsi = Gtk::manage(new Inkscape::UI::Widget::RegisteredSuffixedInteger(_("_Major grid line every:"), "", _("lines"), + "empspacing", _wr, repr, doc)); _rumg->set_hexpand(); _rsu_ox->set_hexpand(); @@ -298,7 +298,7 @@ CanvasAxonomGrid::newSpecificWidget() _rsi->set_hexpand(); // set widget values - _wr.setUpdating (true); + _wr.setUpdating(true); _rsu_ox->setDigits(5); _rsu_ox->setIncrements(0.1, 1.0); @@ -309,27 +309,27 @@ CanvasAxonomGrid::newSpecificWidget() _rsu_sy->setDigits(5); _rsu_sy->setIncrements(0.1, 1.0); - _rumg->setUnit (gridunit->abbr); + _rumg->setUnit(gridunit->abbr); gdouble val; val = origin[Geom::X]; val = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_ox->setValue (val); + _rsu_ox->setValue(val); val = origin[Geom::Y]; val = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_oy->setValue (val); + _rsu_oy->setValue(val); val = lengthy; double gridy = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_sy->setValue (gridy); + _rsu_sy->setValue(gridy); _rsu_ax->setValue(angle_deg[X]); _rsu_az->setValue(angle_deg[Z]); - _rcp_gcol->setRgba32 (color); - _rcp_gmcol->setRgba32 (empcolor); - _rsi->setValue (empspacing); + _rcp_gcol->setRgba32(color); + _rcp_gmcol->setRgba32(empcolor); + _rsi->setValue(empspacing); - _wr.setUpdating (false); + _wr.setUpdating(false); _rsu_ox->setProgrammatically = false; _rsu_oy->setProgrammatically = false; @@ -348,19 +348,19 @@ CanvasAxonomGrid::newSpecificWidget() return column; } - /** * Update dialog widgets from object's values. */ -void -CanvasAxonomGrid::updateWidgets() +void CanvasAxonomGrid::updateWidgets() { - if (_wr.isUpdating()) return; + if (_wr.isUpdating()) + return; - //no widgets (grid created with the document, not with the dialog) - if (!_rcb_visible) return; + // no widgets (grid created with the document, not with the dialog) + if (!_rcb_visible) + return; - _wr.setUpdating (true); + _wr.setUpdating(true); _rcb_visible->setActive(visible); if (snapper != nullptr) { @@ -368,21 +368,21 @@ CanvasAxonomGrid::updateWidgets() _rcb_snap_visible_only->setActive(snapper->getSnapVisibleOnly()); } - _rumg->setUnit (gridunit->abbr); + _rumg->setUnit(gridunit->abbr); gdouble val; val = origin[Geom::X]; val = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_ox->setValue (val); + _rsu_ox->setValue(val); val = origin[Geom::Y]; val = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_oy->setValue (val); + _rsu_oy->setValue(val); val = lengthy; val = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_sy->setValue (val); + _rsu_sy->setValue(val); _rsu_ax->setValue(angle_deg[X]); _rsu_az->setValue(angle_deg[Z]); @@ -393,32 +393,29 @@ CanvasAxonomGrid::updateWidgets() _rsu_ax->setProgrammatically = false; _rsu_az->setProgrammatically = false; - _rcp_gcol->setRgba32 (color); - _rcp_gmcol->setRgba32 (empcolor); - _rsi->setValue (empspacing); + _rcp_gcol->setRgba32(color); + _rcp_gmcol->setRgba32(empcolor); + _rsi->setValue(empspacing); - _wr.setUpdating (false); + _wr.setUpdating(false); } - - -void -CanvasAxonomGrid::Update (Geom::Affine const &affine, unsigned int /*flags*/) +void CanvasAxonomGrid::Update(Geom::Affine const &affine, unsigned int /*flags*/) { ow = origin * affine; - sw = Geom::Point(fabs(affine[0]),fabs(affine[3])); + sw = Geom::Point(fabs(affine[0]), fabs(affine[3])); sw *= lengthy; scaled = false; - for(int dim = 0; dim < 2; dim++) { + for (int dim = 0; dim < 2; dim++) { gint scaling_factor = empspacing; if (scaling_factor <= 1) scaling_factor = 5; int watchdog = 0; - while ( (sw[dim] < 8.0) & (watchdog < 100) ) { + while ((sw[dim] < 8.0) & (watchdog < 100)) { scaled = true; sw[dim] *= scaling_factor; // First pass, go up to the major line spacing, then @@ -426,45 +423,51 @@ CanvasAxonomGrid::Update (Geom::Affine const &affine, unsigned int /*flags*/) scaling_factor = 2; watchdog++; } - } - spacing_ylines = sw[Geom::X] /(tan_angle[X] + tan_angle[Z]); - lyw = sw[Geom::Y]; - lxw_x = Geom::are_near(tan_angle[X],0.) ? Geom::infinity() : sw[Geom::X] / tan_angle[X]; - lxw_z = Geom::are_near(tan_angle[Z],0.) ? Geom::infinity() : sw[Geom::X] / tan_angle[Z]; + spacing_ylines = sw[Geom::X] / (tan_angle[X] + tan_angle[Z]); + lyw = sw[Geom::Y]; + lxw_x = Geom::are_near(tan_angle[X], 0.) ? Geom::infinity() : sw[Geom::X] / tan_angle[X]; + lxw_z = Geom::are_near(tan_angle[Z], 0.) ? Geom::infinity() : sw[Geom::X] / tan_angle[Z]; if (empspacing == 0) { scaled = true; } } -void -CanvasAxonomGrid::Render (SPCanvasBuf *buf) +void CanvasAxonomGrid::Render(SPCanvasBuf *buf) { - //set correct coloring, depending preference (when zoomed out, always major coloring or minor coloring) + // set correct coloring, depending preference (when zoomed out, always major coloring or minor coloring) Inkscape::Preferences *prefs = Inkscape::Preferences::get(); guint32 _empcolor; guint32 _color = color; bool preference = prefs->getBool("/options/grids/no_emphasize_when_zoomedout", false); - if( scaled && preference ) { + if (scaled && preference) { _empcolor = color; } else { _empcolor = empcolor; } bool xrayactive = prefs->getBool("/desktop/xrayactive", false); - if (xrayactive) { //this allow good looking on xray zones + if (xrayactive) { // this allow good looking on xray zones guint32 bg = namedview->pagecolor; _color = SP_RGBA32_F_COMPOSE( - CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_R_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_R_F(_color)), 0.0, 1.0), - CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_G_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_G_F(_color)), 0.0, 1.0), - CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_B_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_B_F(_color)), 0.0, 1.0), - 1.0); - _empcolor = SP_RGBA32_F_COMPOSE( - CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_R_F(bg)) + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_R_F(_empcolor)), 0.0, 1.0), - CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_G_F(bg)) + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_G_F(_empcolor)), 0.0, 1.0), - CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_B_F(bg)) + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_B_F(_empcolor)), 0.0, 1.0), - 1.0); + CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_R_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_R_F(_color)), + 0.0, 1.0), + CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_G_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_G_F(_color)), + 0.0, 1.0), + CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_B_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_B_F(_color)), + 0.0, 1.0), + 1.0); + _empcolor = SP_RGBA32_F_COMPOSE(CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_R_F(bg)) + + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_R_F(_empcolor)), + 0.0, 1.0), + CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_G_F(bg)) + + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_G_F(_empcolor)), + 0.0, 1.0), + CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_B_F(bg)) + + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_B_F(_empcolor)), + 0.0, 1.0), + 1.0); } cairo_save(buf->ct); cairo_translate(buf->ct, -buf->rect.left(), -buf->rect.top()); @@ -478,57 +481,56 @@ CanvasAxonomGrid::Render (SPCanvasBuf *buf) // tl = topleft ; br = bottomright Geom::Point buf_tl_gc; Geom::Point buf_br_gc; - buf_tl_gc[Geom::X] = buf->rect.left() - ow[Geom::X]; - buf_tl_gc[Geom::Y] = buf->rect.top() - ow[Geom::Y]; - buf_br_gc[Geom::X] = buf->rect.right() - ow[Geom::X]; + buf_tl_gc[Geom::X] = buf->rect.left() - ow[Geom::X]; + buf_tl_gc[Geom::Y] = buf->rect.top() - ow[Geom::Y]; + buf_br_gc[Geom::X] = buf->rect.right() - ow[Geom::X]; buf_br_gc[Geom::Y] = buf->rect.bottom() - ow[Geom::Y]; // render the three separate line groups representing the main-axes // x-axis always goes from topleft to bottomright. (0,0) - (1,1) - gdouble const xintercept_y_bc = (buf_tl_gc[Geom::X] * tan_angle[X]) - buf_tl_gc[Geom::Y] ; - gdouble const xstart_y_sc = ( xintercept_y_bc - floor(xintercept_y_bc/lyw)*lyw ) + buf->rect.top(); - gint const xlinestart = round( (xstart_y_sc - buf_tl_gc[Geom::X]*tan_angle[X] - ow[Geom::Y]) / lyw ); + gdouble const xintercept_y_bc = (buf_tl_gc[Geom::X] * tan_angle[X]) - buf_tl_gc[Geom::Y]; + gdouble const xstart_y_sc = (xintercept_y_bc - floor(xintercept_y_bc / lyw) * lyw) + buf->rect.top(); + gint const xlinestart = round((xstart_y_sc - buf_tl_gc[Geom::X] * tan_angle[X] - ow[Geom::Y]) / lyw); gint xlinenum = xlinestart; // lines starting on left side. for (gdouble y = xstart_y_sc; y < buf->rect.bottom(); y += lyw, xlinenum++) { gint const x0 = buf->rect.left(); gint const y0 = round(y); - gint x1 = x0 + round( (buf->rect.bottom() - y) / tan_angle[X] ); + gint x1 = x0 + round((buf->rect.bottom() - y) / tan_angle[X]); gint y1 = buf->rect.bottom(); - if ( Geom::are_near(tan_angle[X],0.) ) { + if (Geom::are_near(tan_angle[X], 0.)) { x1 = buf->rect.right(); y1 = y0; } if (!scaled && (xlinenum % empspacing) != 0) { - sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, _color); + sp_caxonomgrid_drawline(buf, x0, y0, x1, y1, _color); } else { - sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, _empcolor); + sp_caxonomgrid_drawline(buf, x0, y0, x1, y1, _empcolor); } } // lines starting from top side - if (!Geom::are_near(tan_angle[X],0.)) - { - gdouble const xstart_x_sc = buf->rect.left() + (lxw_x - (xstart_y_sc - buf->rect.top()) / tan_angle[X]) ; - xlinenum = xlinestart-1; + if (!Geom::are_near(tan_angle[X], 0.)) { + gdouble const xstart_x_sc = buf->rect.left() + (lxw_x - (xstart_y_sc - buf->rect.top()) / tan_angle[X]); + xlinenum = xlinestart - 1; for (gdouble x = xstart_x_sc; x < buf->rect.right(); x += lxw_x, xlinenum--) { gint const y0 = buf->rect.top(); gint const y1 = buf->rect.bottom(); gint const x0 = round(x); - gint const x1 = x0 + round( (y1 - y0) / tan_angle[X] ); + gint const x1 = x0 + round((y1 - y0) / tan_angle[X]); if (!scaled && (xlinenum % empspacing) != 0) { - sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, _color); + sp_caxonomgrid_drawline(buf, x0, y0, x1, y1, _color); } else { - sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, _empcolor); + sp_caxonomgrid_drawline(buf, x0, y0, x1, y1, _empcolor); } } } // y-axis lines (vertical) - gdouble const ystart_x_sc = floor (buf_tl_gc[Geom::X] / spacing_ylines) * spacing_ylines + ow[Geom::X]; - gint const ylinestart = round((ystart_x_sc - ow[Geom::X]) / spacing_ylines); + gdouble const ystart_x_sc = floor(buf_tl_gc[Geom::X] / spacing_ylines) * spacing_ylines + ow[Geom::X]; + gint const ylinestart = round((ystart_x_sc - ow[Geom::X]) / spacing_ylines); gint ylinenum = ylinestart; for (gdouble x = ystart_x_sc; x < buf->rect.right(); x += spacing_ylines, ylinenum++) { gint const x0 = floor(x); // sp_grid_vline will add 0.5 again, so we'll pre-emptively use floor() @@ -536,49 +538,48 @@ CanvasAxonomGrid::Render (SPCanvasBuf *buf) // CanvasXYGrid::Render() for more details if (!scaled && (ylinenum % empspacing) != 0) { - sp_grid_vline (buf, x0, buf->rect.top(), buf->rect.bottom() - 1, _color); + sp_grid_vline(buf, x0, buf->rect.top(), buf->rect.bottom() - 1, _color); } else { - sp_grid_vline (buf, x0, buf->rect.top(), buf->rect.bottom() - 1, _empcolor); + sp_grid_vline(buf, x0, buf->rect.top(), buf->rect.bottom() - 1, _empcolor); } } // z-axis always goes from bottomleft to topright. (0,1) - (1,0) - gdouble const zintercept_y_bc = (buf_tl_gc[Geom::X] * -tan_angle[Z]) - buf_tl_gc[Geom::Y] ; - gdouble const zstart_y_sc = ( zintercept_y_bc - floor(zintercept_y_bc/lyw)*lyw ) + buf->rect.top(); - gint const zlinestart = round( (zstart_y_sc + buf_tl_gc[Geom::X]*tan_angle[Z] - ow[Geom::Y]) / lyw ); + gdouble const zintercept_y_bc = (buf_tl_gc[Geom::X] * -tan_angle[Z]) - buf_tl_gc[Geom::Y]; + gdouble const zstart_y_sc = (zintercept_y_bc - floor(zintercept_y_bc / lyw) * lyw) + buf->rect.top(); + gint const zlinestart = round((zstart_y_sc + buf_tl_gc[Geom::X] * tan_angle[Z] - ow[Geom::Y]) / lyw); gint zlinenum = zlinestart; // lines starting from left side gdouble next_y = zstart_y_sc; for (gdouble y = zstart_y_sc; y < buf->rect.bottom(); y += lyw, zlinenum++, next_y = y) { gint const x0 = buf->rect.left(); gint const y0 = round(y); - gint x1 = x0 + round( (y - buf->rect.top() ) / tan_angle[Z] ); + gint x1 = x0 + round((y - buf->rect.top()) / tan_angle[Z]); gint y1 = buf->rect.top(); - if ( Geom::are_near(tan_angle[Z],0.) ) { + if (Geom::are_near(tan_angle[Z], 0.)) { x1 = buf->rect.right(); y1 = y0; } if (!scaled && (zlinenum % empspacing) != 0) { - sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, _color); + sp_caxonomgrid_drawline(buf, x0, y0, x1, y1, _color); } else { - sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, _empcolor); + sp_caxonomgrid_drawline(buf, x0, y0, x1, y1, _empcolor); } } // draw lines from bottom-up - if (!Geom::are_near(tan_angle[Z],0.)) - { - gdouble const zstart_x_sc = buf->rect.left() + (next_y - buf->rect.bottom()) / tan_angle[Z] ; + if (!Geom::are_near(tan_angle[Z], 0.)) { + gdouble const zstart_x_sc = buf->rect.left() + (next_y - buf->rect.bottom()) / tan_angle[Z]; for (gdouble x = zstart_x_sc; x < buf->rect.right(); x += lxw_z, zlinenum++) { gint const y0 = buf->rect.bottom(); gint const y1 = buf->rect.top(); gint const x0 = round(x); - gint const x1 = x0 + round(buf->rect.height() / tan_angle[Z] ); + gint const x1 = x0 + round(buf->rect.height() / tan_angle[Z]); if (!scaled && (zlinenum % empspacing) != 0) { - sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, _color); + sp_caxonomgrid_drawline(buf, x0, y0, x1, y1, _color); } else { - sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, _empcolor); + sp_caxonomgrid_drawline(buf, x0, y0, x1, y1, _empcolor); } } } @@ -586,7 +587,8 @@ CanvasAxonomGrid::Render (SPCanvasBuf *buf) cairo_restore(buf->ct); } -CanvasAxonomGridSnapper::CanvasAxonomGridSnapper(CanvasAxonomGrid *grid, SnapManager *sm, Geom::Coord const d) : LineSnapper(sm, d) +CanvasAxonomGridSnapper::CanvasAxonomGridSnapper(CanvasAxonomGrid *grid, SnapManager *sm, Geom::Coord const d) + : LineSnapper(sm, d) { this->grid = grid; } @@ -597,21 +599,21 @@ CanvasAxonomGridSnapper::CanvasAxonomGridSnapper(CanvasAxonomGrid *grid, SnapMan Geom::Coord CanvasAxonomGridSnapper::getSnapperTolerance() const { SPDesktop const *dt = _snapmanager->getDesktop(); - double const zoom = dt ? dt->current_zoom() : 1; + double const zoom = dt ? dt->current_zoom() : 1; return _snapmanager->snapprefs.getGridTolerance() / zoom; } bool CanvasAxonomGridSnapper::getSnapperAlwaysSnap() const { - return _snapmanager->snapprefs.getGridTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp + return _snapmanager->snapprefs.getGridTolerance() == + 10000; // TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp } -LineSnapper::LineList -CanvasAxonomGridSnapper::_getSnapLines(Geom::Point const &p) const +LineSnapper::LineList CanvasAxonomGridSnapper::_getSnapLines(Geom::Point const &p) const { LineList s; - if ( grid == nullptr ) { + if (grid == nullptr) { return s; } @@ -629,7 +631,7 @@ CanvasAxonomGridSnapper::_getSnapLines(Geom::Point const &p) const if (getSnapVisibleOnly()) { // Only snapping to visible grid lines spacing_h = grid->spacing_ylines; // this is the spacing of the visible grid lines measured in screen pixels - spacing_v = grid->lyw; // vertical + spacing_v = grid->lyw; // vertical // convert screen pixels to px // FIXME: after we switch to snapping dist in screen pixels, this will be unnecessary if (dt) { @@ -638,9 +640,8 @@ CanvasAxonomGridSnapper::_getSnapLines(Geom::Point const &p) const } } else { // Snapping to any grid line, whether it's visible or not - spacing_h = grid->lengthy /(grid->tan_angle[X] + grid->tan_angle[Z]); + spacing_h = grid->lengthy / (grid->tan_angle[X] + grid->tan_angle[Z]); spacing_v = grid->lengthy; - } // In an axonometric grid, any point will be surrounded by 6 grid lines: @@ -655,10 +656,14 @@ CanvasAxonomGridSnapper::_getSnapLines(Geom::Point const &p) const // Calculate the y coordinate of the intersection of the angled grid lines with the y-axis double y_proj_along_z = p[Geom::Y] - ta_z * (p[Geom::X] - grid->origin[Geom::X]); double y_proj_along_x = p[Geom::Y] + ta_x * (p[Geom::X] - grid->origin[Geom::X]); - double y_proj_along_z_max = Inkscape::Util::round_to_upper_multiple_plus(y_proj_along_z, spacing_v, grid->origin[Geom::Y]); - double y_proj_along_z_min = Inkscape::Util::round_to_lower_multiple_plus(y_proj_along_z, spacing_v, grid->origin[Geom::Y]); - double y_proj_along_x_max = Inkscape::Util::round_to_upper_multiple_plus(y_proj_along_x, spacing_v, grid->origin[Geom::Y]); - double y_proj_along_x_min = Inkscape::Util::round_to_lower_multiple_plus(y_proj_along_x, spacing_v, grid->origin[Geom::Y]); + double y_proj_along_z_max = + Inkscape::Util::round_to_upper_multiple_plus(y_proj_along_z, spacing_v, grid->origin[Geom::Y]); + double y_proj_along_z_min = + Inkscape::Util::round_to_lower_multiple_plus(y_proj_along_z, spacing_v, grid->origin[Geom::Y]); + double y_proj_along_x_max = + Inkscape::Util::round_to_upper_multiple_plus(y_proj_along_x, spacing_v, grid->origin[Geom::Y]); + double y_proj_along_x_min = + Inkscape::Util::round_to_lower_multiple_plus(y_proj_along_x, spacing_v, grid->origin[Geom::Y]); // Calculate the versor for the angled grid lines Geom::Point vers_x = Geom::Point(1, -ta_x); @@ -681,12 +686,9 @@ CanvasAxonomGridSnapper::_getSnapLines(Geom::Point const &p) const Geom::Line line_z(p_z, p_z + vers_z); Geom::OptCrossing inters = Geom::OptCrossing(); // empty by default - try - { + try { inters = Geom::intersection(line_x, line_z); - } - catch (Geom::InfiniteSolutions &e) - { + } catch (Geom::InfiniteSolutions &e) { // We're probably dealing with parallel lines; this is useless! return s; } @@ -718,21 +720,33 @@ CanvasAxonomGridSnapper::_getSnapLines(Geom::Point const &p) const return s; } -void CanvasAxonomGridSnapper::_addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, Geom::Point const &normal_to_line, Geom::Point const &point_on_line) const +void CanvasAxonomGridSnapper::_addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, Geom::Point const &normal_to_line, + Geom::Point const &point_on_line) const { - SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, source, source_num, Inkscape::SNAPTARGET_GRID, getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line); + SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, source, source_num, Inkscape::SNAPTARGET_GRID, + getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line); isr.grid_lines.push_back(dummy); } -void CanvasAxonomGridSnapper::_addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const +void CanvasAxonomGridSnapper::_addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, bool constrained_snap) const { - SnappedPoint dummy = SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GRID, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); + SnappedPoint dummy = SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GRID, snapped_distance, + getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); isr.points.push_back(dummy); } -void CanvasAxonomGridSnapper::_addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const +void CanvasAxonomGridSnapper::_addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, + bool constrained_snap) const { - SnappedPoint dummy = SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GRID_PERPENDICULAR, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); + SnappedPoint dummy = + SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GRID_PERPENDICULAR, snapped_distance, + getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); isr.points.push_back(dummy); } @@ -741,10 +755,8 @@ bool CanvasAxonomGridSnapper::ThisSnapperMightSnap() const return _snap_enabled && _snapmanager->snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_GRID); } - }; // namespace Inkscape - /* Local Variables: mode:c++ diff --git a/src/display/canvas-axonomgrid.h b/src/display/canvas-axonomgrid.h index ce4a19edf53070dee0045bba4d2b4b2de6e57a49..e9f94e3e92a2383658dbd846c1d2afa2162eacff 100644 --- a/src/display/canvas-axonomgrid.h +++ b/src/display/canvas-axonomgrid.h @@ -10,51 +10,53 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "line-snapper.h" #include "canvas-grid.h" +#include "line-snapper.h" struct SPCanvasBuf; class SPNamedView; namespace Inkscape { namespace XML { - class Node; +class Node; }; -class CanvasAxonomGrid : public CanvasGrid { +class CanvasAxonomGrid : public CanvasGrid +{ public: - CanvasAxonomGrid(SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument * in_doc); + CanvasAxonomGrid(SPNamedView *nv, Inkscape::XML::Node *in_repr, SPDocument *in_doc); ~CanvasAxonomGrid() override; - void Update (Geom::Affine const &affine, unsigned int flags) override; - void Render (SPCanvasBuf *buf) override; + void Update(Geom::Affine const &affine, unsigned int flags) override; + void Render(SPCanvasBuf *buf) override; void readRepr() override; - void onReprAttrChanged (Inkscape::XML::Node * repr, char const *key, char const *oldval, char const *newval, bool is_interactive) override; + void onReprAttrChanged(Inkscape::XML::Node *repr, char const *key, char const *oldval, char const *newval, + bool is_interactive) override; - double lengthy; /**< The lengths of the primary y-axis */ - double angle_deg[3]; /**< Angle of each axis (note that angle[2] == 0) */ - double angle_rad[3]; /**< Angle of each axis (note that angle[2] == 0) */ - double tan_angle[3]; /**< tan(angle[.]) */ + double lengthy; /**< The lengths of the primary y-axis */ + double angle_deg[3]; /**< Angle of each axis (note that angle[2] == 0) */ + double angle_rad[3]; /**< Angle of each axis (note that angle[2] == 0) */ + double tan_angle[3]; /**< tan(angle[.]) */ - bool scaled; /**< Whether the grid is in scaled mode */ + bool scaled; /**< Whether the grid is in scaled mode */ protected: friend class CanvasAxonomGridSnapper; - Geom::Point ow; /**< Transformed origin by the affine for the zoom */ - double lyw; /**< Transformed length y by the affine for the zoom */ + Geom::Point ow; /**< Transformed origin by the affine for the zoom */ + double lyw; /**< Transformed length y by the affine for the zoom */ double lxw_x; double lxw_z; double spacing_ylines; - Geom::Point sw; /**< the scaling factors of the affine transform */ + Geom::Point sw; /**< the scaling factors of the affine transform */ - Gtk::Widget * newSpecificWidget() override; + Gtk::Widget *newSpecificWidget() override; private: - CanvasAxonomGrid(const CanvasAxonomGrid&) = delete; - CanvasAxonomGrid& operator=(const CanvasAxonomGrid&) = delete; + CanvasAxonomGrid(const CanvasAxonomGrid &) = delete; + CanvasAxonomGrid &operator=(const CanvasAxonomGrid &) = delete; void updateWidgets(); @@ -69,31 +71,31 @@ private: Inkscape::UI::Widget::RegisteredSuffixedInteger *_rsi; }; - - class CanvasAxonomGridSnapper : public LineSnapper { public: CanvasAxonomGridSnapper(CanvasAxonomGrid *grid, SnapManager *sm, Geom::Coord const d); bool ThisSnapperMightSnap() const override; - Geom::Coord getSnapperTolerance() const override; //returns the tolerance of the snapper in screen pixels (i.e. independent of zoom) - bool getSnapperAlwaysSnap() const override; //if true, then the snapper will always snap, regardless of its tolerance + Geom::Coord getSnapperTolerance() const override; // returns the tolerance of the snapper in screen pixels (i.e. + // independent of zoom) + bool getSnapperAlwaysSnap() const override; // if true, then the snapper will always snap, regardless of its + // tolerance private: LineList _getSnapLines(Geom::Point const &p) const override; - void _addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, Geom::Point const &normal_to_line, const Geom::Point &point_on_line) const override; - void _addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const override; - void _addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const override; + void _addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, Geom::Point const &normal_to_line, + const Geom::Point &point_on_line) const override; + void _addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, bool constrained_snap) const override; + void _addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, bool constrained_snap) const override; CanvasAxonomGrid *grid; }; - -}; //namespace Inkscape - - +}; // namespace Inkscape #endif - - diff --git a/src/display/canvas-bpath.cpp b/src/display/canvas-bpath.cpp index 81577001e547bf4e73c679dee45cf519d6af65a1..789e14a5df569790eb75f4bf3eae5dc80136fb8e 100644 --- a/src/display/canvas-bpath.cpp +++ b/src/display/canvas-bpath.cpp @@ -12,33 +12,31 @@ * */ -#include +#include "canvas-bpath.h" + #include -#include "desktop.h" +#include +#include "cairo-utils.h" #include "color.h" - -#include "sp-canvas-group.h" -#include "sp-canvas-util.h" -#include "canvas-bpath.h" #include "curve.h" -#include "cairo-utils.h" - +#include "desktop.h" #include "helper/geom.h" - +#include "sp-canvas-group.h" +#include "sp-canvas-util.h" #include "ui/widget/canvas.h" static void sp_canvas_bpath_destroy(SPCanvasItem *object); -static void sp_canvas_bpath_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); -static void sp_canvas_bpath_render (SPCanvasItem *item, SPCanvasBuf *buf); -static double sp_canvas_bpath_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item); +static void sp_canvas_bpath_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); +static void sp_canvas_bpath_render(SPCanvasItem *item, SPCanvasBuf *buf); +static double sp_canvas_bpath_point(SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item); G_DEFINE_TYPE(SPCanvasBPath, sp_canvas_bpath, SP_TYPE_CANVAS_ITEM); static void sp_canvas_bpath_class_init(SPCanvasBPathClass *klass) { - SPCanvasItemClass *item_class = (SPCanvasItemClass *) klass; + SPCanvasItemClass *item_class = (SPCanvasItemClass *)klass; item_class->destroy = sp_canvas_bpath_destroy; item_class->update = sp_canvas_bpath_update; @@ -46,8 +44,7 @@ static void sp_canvas_bpath_class_init(SPCanvasBPathClass *klass) item_class->point = sp_canvas_bpath_point; } -static void -sp_canvas_bpath_init (SPCanvasBPath * bpath) +static void sp_canvas_bpath_init(SPCanvasBPath *bpath) { bpath->fill_rgba = 0x00000000; bpath->fill_rule = SP_WIND_RULE_EVENODD; @@ -64,28 +61,29 @@ sp_canvas_bpath_init (SPCanvasBPath * bpath) static void sp_canvas_bpath_destroy(SPCanvasItem *object) { - SPCanvasBPath *cbp = SP_CANVAS_BPATH (object); + SPCanvasBPath *cbp = SP_CANVAS_BPATH(object); // C++ member in C-allocated struct std::destroy_at(&cbp->curve); if (SP_CANVAS_ITEM_CLASS(sp_canvas_bpath_parent_class)->destroy) - (* SP_CANVAS_ITEM_CLASS(sp_canvas_bpath_parent_class)->destroy) (object); + (*SP_CANVAS_ITEM_CLASS(sp_canvas_bpath_parent_class)->destroy)(object); } static void sp_canvas_bpath_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) { SPCanvasBPath *cbp = SP_CANVAS_BPATH(item); - item->canvas->redraw_area((int)item->x1 - 1, (int)item->y1 - 1, (int)item->x2 + 1 , (int)item->y2 + 1); + item->canvas->redraw_area((int)item->x1 - 1, (int)item->y1 - 1, (int)item->x2 + 1, (int)item->y2 + 1); if (reinterpret_cast(sp_canvas_bpath_parent_class)->update) { reinterpret_cast(sp_canvas_bpath_parent_class)->update(item, affine, flags); } - sp_canvas_item_reset_bounds (item); + sp_canvas_item_reset_bounds(item); - if (!cbp->curve) return; + if (!cbp->curve) + return; cbp->affine = affine; @@ -105,16 +103,14 @@ static void sp_canvas_bpath_update(SPCanvasItem *item, Geom::Affine const &affin item->canvas->redraw_area((int)item->x1, (int)item->y1, (int)item->x2, (int)item->y2); } -static void -sp_canvas_bpath_render (SPCanvasItem *item, SPCanvasBuf *buf) +static void sp_canvas_bpath_render(SPCanvasItem *item, SPCanvasBuf *buf) { - SPCanvasBPath *cbp = SP_CANVAS_BPATH (item); + SPCanvasBPath *cbp = SP_CANVAS_BPATH(item); Geom::Rect area = buf->rect; - if ( !cbp->curve || - ((cbp->stroke_rgba & 0xff) == 0 && (cbp->fill_rgba & 0xff) == 0 ) || - cbp->curve->get_segment_count() < 1) + if (!cbp->curve || ((cbp->stroke_rgba & 0xff) == 0 && (cbp->fill_rgba & 0xff) == 0) || + cbp->curve->get_segment_count() < 1) return; if (!buf->ct) @@ -126,14 +122,14 @@ sp_canvas_bpath_render (SPCanvasItem *item, SPCanvasBuf *buf) cairo_set_tolerance(buf->ct, 0.5); cairo_new_path(buf->ct); - feed_pathvector_to_cairo (buf->ct, cbp->curve->get_pathvector(), cbp->affine, area, - /* optimized_stroke = */ !dofill, 1); + feed_pathvector_to_cairo(buf->ct, cbp->curve->get_pathvector(), cbp->affine, area, + /* optimized_stroke = */ !dofill, 1); if (dofill) { // RGB / BGR ink_cairo_set_source_rgba32(buf->ct, cbp->fill_rgba); - cairo_set_fill_rule(buf->ct, cbp->fill_rule == SP_WIND_RULE_EVENODD? CAIRO_FILL_RULE_EVEN_ODD - : CAIRO_FILL_RULE_WINDING); + cairo_set_fill_rule(buf->ct, cbp->fill_rule == SP_WIND_RULE_EVENODD ? CAIRO_FILL_RULE_EVEN_ODD + : CAIRO_FILL_RULE_WINDING); cairo_fill_preserve(buf->ct); } @@ -141,13 +137,13 @@ sp_canvas_bpath_render (SPCanvasItem *item, SPCanvasBuf *buf) ink_cairo_set_source_rgba32(buf->ct, 0xffffff4d); cairo_set_line_width(buf->ct, 2); if (cbp->dashes[0] != 0 && cbp->dashes[1] != 0) { - cairo_set_dash (buf->ct, cbp->dashes, 2, 0); + cairo_set_dash(buf->ct, cbp->dashes, 2, 0); } cairo_stroke(buf->ct); cairo_set_tolerance(buf->ct, 0.5); cairo_new_path(buf->ct); - feed_pathvector_to_cairo (buf->ct, cbp->curve->get_pathvector(), cbp->affine, area, - /* optimized_stroke = */ !dofill, 1); + feed_pathvector_to_cairo(buf->ct, cbp->curve->get_pathvector(), cbp->affine, area, + /* optimized_stroke = */ !dofill, 1); ink_cairo_set_source_rgba32(buf->ct, cbp->stroke_rgba); cairo_set_line_width(buf->ct, 1); cairo_stroke(buf->ct); @@ -155,7 +151,7 @@ sp_canvas_bpath_render (SPCanvasItem *item, SPCanvasBuf *buf) ink_cairo_set_source_rgba32(buf->ct, cbp->stroke_rgba); cairo_set_line_width(buf->ct, 1); if (cbp->dashes[0] != 0 && cbp->dashes[1] != 0) { - cairo_set_dash (buf->ct, cbp->dashes, 2, 0); + cairo_set_dash(buf->ct, cbp->dashes, 2, 0); } cairo_stroke(buf->ct); } else { @@ -163,21 +159,20 @@ sp_canvas_bpath_render (SPCanvasItem *item, SPCanvasBuf *buf) } } -static double -sp_canvas_bpath_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item) +static double sp_canvas_bpath_point(SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item) { - SPCanvasBPath *cbp = SP_CANVAS_BPATH (item); + SPCanvasBPath *cbp = SP_CANVAS_BPATH(item); - if ( !cbp->curve || - ((cbp->stroke_rgba & 0xff) == 0 && (cbp->fill_rgba & 0xff) == 0 ) || - cbp->curve->get_segment_count() < 1) + if (!cbp->curve || ((cbp->stroke_rgba & 0xff) == 0 && (cbp->fill_rgba & 0xff) == 0) || + cbp->curve->get_segment_count() < 1) return Geom::infinity(); double width = 0.5; Geom::Rect viewbox = item->canvas->get_area_world(); - viewbox.expandBy (width); + viewbox.expandBy(width); double dist = Geom::infinity(); - pathv_matrix_point_bbox_wind_distance(cbp->curve->get_pathvector(), cbp->affine, p, nullptr, nullptr, &dist, 0.5, &viewbox); + pathv_matrix_point_bbox_wind_distance(cbp->curve->get_pathvector(), cbp->affine, p, nullptr, nullptr, &dist, 0.5, + &viewbox); if (dist <= 1.0) { *actual_item = item; @@ -186,63 +181,60 @@ sp_canvas_bpath_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_ return dist; } -SPCanvasItem * -sp_canvas_bpath_new (SPCanvasGroup *parent, SPCurve *curve, bool phantom_line) +SPCanvasItem *sp_canvas_bpath_new(SPCanvasGroup *parent, SPCurve *curve, bool phantom_line) { - g_return_val_if_fail (parent != nullptr, NULL); - g_return_val_if_fail (SP_IS_CANVAS_GROUP (parent), NULL); + g_return_val_if_fail(parent != nullptr, NULL); + g_return_val_if_fail(SP_IS_CANVAS_GROUP(parent), NULL); - SPCanvasItem *item = sp_canvas_item_new (parent, SP_TYPE_CANVAS_BPATH, nullptr); + SPCanvasItem *item = sp_canvas_item_new(parent, SP_TYPE_CANVAS_BPATH, nullptr); auto cbp = SP_CANVAS_BPATH(item); // C++ member in C-allocated struct new (&cbp->curve) decltype(cbp->curve)(); - sp_canvas_bpath_set_bpath (SP_CANVAS_BPATH (item), curve, phantom_line); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(item), curve, phantom_line); return item; } -void -sp_canvas_bpath_set_bpath (SPCanvasBPath *cbp, SPCurve *curve, bool phantom_line) +void sp_canvas_bpath_set_bpath(SPCanvasBPath *cbp, SPCurve *curve, bool phantom_line) { - g_return_if_fail (cbp != nullptr); - g_return_if_fail (SP_IS_CANVAS_BPATH (cbp)); + g_return_if_fail(cbp != nullptr); + g_return_if_fail(SP_IS_CANVAS_BPATH(cbp)); cbp->phantom_line = phantom_line; cbp->curve = curve ? curve->ref() : nullptr; - sp_canvas_item_request_update (SP_CANVAS_ITEM (cbp)); + sp_canvas_item_request_update(SP_CANVAS_ITEM(cbp)); } -void -sp_canvas_bpath_set_fill (SPCanvasBPath *cbp, guint32 rgba, SPWindRule rule) +void sp_canvas_bpath_set_fill(SPCanvasBPath *cbp, guint32 rgba, SPWindRule rule) { - g_return_if_fail (cbp != nullptr); - g_return_if_fail (SP_IS_CANVAS_BPATH (cbp)); + g_return_if_fail(cbp != nullptr); + g_return_if_fail(SP_IS_CANVAS_BPATH(cbp)); cbp->fill_rgba = rgba; cbp->fill_rule = rule; - sp_canvas_item_request_update (SP_CANVAS_ITEM (cbp)); + sp_canvas_item_request_update(SP_CANVAS_ITEM(cbp)); } -void -sp_canvas_bpath_set_stroke (SPCanvasBPath *cbp, guint32 rgba, gdouble width, SPStrokeJoinType join, SPStrokeCapType cap, double dash, double gap) +void sp_canvas_bpath_set_stroke(SPCanvasBPath *cbp, guint32 rgba, gdouble width, SPStrokeJoinType join, + SPStrokeCapType cap, double dash, double gap) { - g_return_if_fail (cbp != nullptr); - g_return_if_fail (SP_IS_CANVAS_BPATH (cbp)); + g_return_if_fail(cbp != nullptr); + g_return_if_fail(SP_IS_CANVAS_BPATH(cbp)); cbp->stroke_rgba = rgba; - cbp->stroke_width = MAX (width, 0.1); + cbp->stroke_width = MAX(width, 0.1); cbp->stroke_linejoin = join; cbp->stroke_linecap = cap; cbp->dashes[0] = dash; cbp->dashes[1] = gap; - sp_canvas_item_request_update (SP_CANVAS_ITEM (cbp)); + sp_canvas_item_request_update(SP_CANVAS_ITEM(cbp)); } /* diff --git a/src/display/canvas-bpath.h b/src/display/canvas-bpath.h index f5c52c37f1bcfb84c394372a386bb339fa41396c..46e34543729b80277e50781fff7603f32956ee3a 100644 --- a/src/display/canvas-bpath.h +++ b/src/display/canvas-bpath.h @@ -18,29 +18,28 @@ #include #include - -#include "style-enums.h" +#include #include "sp-canvas-item.h" - -#include +#include "style-enums.h" struct SPCanvasBPath; struct SPCanvasBPathClass; struct SPCanvasGroup; class SPCurve; -#define SP_TYPE_CANVAS_BPATH (sp_canvas_bpath_get_type ()) -#define SP_CANVAS_BPATH(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SP_TYPE_CANVAS_BPATH, SPCanvasBPath)) -#define SP_CANVAS_BPATH_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), SP_TYPE_CANVAS_BPATH, SPCanvasBPathClass)) -#define SP_IS_CANVAS_BPATH(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SP_TYPE_CANVAS_BPATH)) -#define SP_IS_CANVAS_BPATH_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), SP_TYPE_CANVAS_BPATH)) +#define SP_TYPE_CANVAS_BPATH (sp_canvas_bpath_get_type()) +#define SP_CANVAS_BPATH(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CANVAS_BPATH, SPCanvasBPath)) +#define SP_CANVAS_BPATH_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), SP_TYPE_CANVAS_BPATH, SPCanvasBPathClass)) +#define SP_IS_CANVAS_BPATH(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CANVAS_BPATH)) +#define SP_IS_CANVAS_BPATH_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), SP_TYPE_CANVAS_BPATH)) #define bpath_liv class Shape; -struct SPCanvasBPath { +struct SPCanvasBPath +{ SPCanvasItem item; /* Line def */ @@ -60,21 +59,23 @@ struct SPCanvasBPath { gdouble stroke_miterlimit; bool phantom_line; /* State */ - Shape *fill_shp; - Shape *stroke_shp; + Shape *fill_shp; + Shape *stroke_shp; }; -struct SPCanvasBPathClass { +struct SPCanvasBPathClass +{ SPCanvasItemClass parent_class; }; -GType sp_canvas_bpath_get_type (); +GType sp_canvas_bpath_get_type(); -SPCanvasItem *sp_canvas_bpath_new (SPCanvasGroup *parent, SPCurve *curve, bool phantom_line = false); +SPCanvasItem *sp_canvas_bpath_new(SPCanvasGroup *parent, SPCurve *curve, bool phantom_line = false); -void sp_canvas_bpath_set_bpath (SPCanvasBPath *cbp, SPCurve *curve, bool phantom_line = false); -void sp_canvas_bpath_set_fill (SPCanvasBPath *cbp, guint32 rgba, SPWindRule rule); -void sp_canvas_bpath_set_stroke (SPCanvasBPath *cbp, guint32 rgba, gdouble width, SPStrokeJoinType join, SPStrokeCapType cap, double dash=0, double gap=0); +void sp_canvas_bpath_set_bpath(SPCanvasBPath *cbp, SPCurve *curve, bool phantom_line = false); +void sp_canvas_bpath_set_fill(SPCanvasBPath *cbp, guint32 rgba, SPWindRule rule); +void sp_canvas_bpath_set_stroke(SPCanvasBPath *cbp, guint32 rgba, gdouble width, SPStrokeJoinType join, + SPStrokeCapType cap, double dash = 0, double gap = 0); #endif diff --git a/src/display/canvas-debug.cpp b/src/display/canvas-debug.cpp index 1e4ee856344614a1fdb9f73664ddb4e2335c24a1..b5f4493a539236a47fb6aff441666a192ecb24e6 100644 --- a/src/display/canvas-debug.cpp +++ b/src/display/canvas-debug.cpp @@ -11,29 +11,30 @@ */ #include "canvas-debug.h" + #include "cairo-utils.h" #include "ui/event-debug.h" namespace { -static void sp_canvas_debug_destroy(SPCanvasItem *item); -static void sp_canvas_debug_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); -static void sp_canvas_debug_render (SPCanvasItem *item, SPCanvasBuf *buf); -static int sp_canvas_debug_event (SPCanvasItem *item, GdkEvent *event); +static void sp_canvas_debug_destroy(SPCanvasItem *item); +static void sp_canvas_debug_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); +static void sp_canvas_debug_render(SPCanvasItem *item, SPCanvasBuf *buf); +static int sp_canvas_debug_event(SPCanvasItem *item, GdkEvent *event); } // namespace G_DEFINE_TYPE(SPCanvasDebug, sp_canvas_debug, SP_TYPE_CANVAS_ITEM); -static void sp_canvas_debug_class_init (SPCanvasDebugClass *klass) +static void sp_canvas_debug_class_init(SPCanvasDebugClass *klass) { klass->destroy = sp_canvas_debug_destroy; - klass->update = sp_canvas_debug_update; - klass->render = sp_canvas_debug_render; - klass->event = sp_canvas_debug_event; + klass->update = sp_canvas_debug_update; + klass->render = sp_canvas_debug_render; + klass->event = sp_canvas_debug_event; } -static void sp_canvas_debug_init (SPCanvasDebug *debug) +static void sp_canvas_debug_init(SPCanvasDebug *debug) { debug->pickable = true; // So we can receive events. @@ -41,17 +42,17 @@ static void sp_canvas_debug_init (SPCanvasDebug *debug) } namespace { -static void sp_canvas_debug_destroy (SPCanvasItem *object) +static void sp_canvas_debug_destroy(SPCanvasItem *object) { - g_return_if_fail (object != nullptr); - g_return_if_fail (SP_IS_CANVAS_DEBUG (object)); + g_return_if_fail(object != nullptr); + g_return_if_fail(SP_IS_CANVAS_DEBUG(object)); if (SP_CANVAS_ITEM_CLASS(sp_canvas_debug_parent_class)->destroy) { SP_CANVAS_ITEM_CLASS(sp_canvas_debug_parent_class)->destroy(object); } } -static void sp_canvas_debug_update( SPCanvasItem *item, Geom::Affine const &/*affine*/, unsigned int /*flags*/ ) +static void sp_canvas_debug_update(SPCanvasItem *item, Geom::Affine const & /*affine*/, unsigned int /*flags*/) { // We cover the entire canvas item->x1 = -G_MAXINT; @@ -60,28 +61,28 @@ static void sp_canvas_debug_update( SPCanvasItem *item, Geom::Affine const &/*af item->y2 = G_MAXINT; } -static void sp_canvas_debug_render( SPCanvasItem *item, SPCanvasBuf *buf) +static void sp_canvas_debug_render(SPCanvasItem *item, SPCanvasBuf *buf) { if (!buf->ct) { return; } - cairo_set_line_width (buf->ct, 2); + cairo_set_line_width(buf->ct, 2); // Draw box around buffer (for debugging) - cairo_new_path (buf->ct); - cairo_move_to (buf->ct, 0, 0); - cairo_line_to (buf->ct, buf->rect.width(), 0); - cairo_line_to (buf->ct, buf->rect.width(), buf->rect.height()); - cairo_line_to (buf->ct, 0, buf->rect.height()); - cairo_close_path (buf->ct); - ink_cairo_set_source_rgba32 (buf->ct, 0xff7f7f7f); - cairo_stroke (buf->ct); + cairo_new_path(buf->ct); + cairo_move_to(buf->ct, 0, 0); + cairo_line_to(buf->ct, buf->rect.width(), 0); + cairo_line_to(buf->ct, buf->rect.width(), buf->rect.height()); + cairo_line_to(buf->ct, 0, buf->rect.height()); + cairo_close_path(buf->ct); + ink_cairo_set_source_rgba32(buf->ct, 0xff7f7f7f); + cairo_stroke(buf->ct); } -static int sp_canvas_debug_event (SPCanvasItem *item, GdkEvent *event) +static int sp_canvas_debug_event(SPCanvasItem *item, GdkEvent *event) { - ui_dump_event (event, Glib::ustring("sp_canvas_debug_event")); + ui_dump_event(event, Glib::ustring("sp_canvas_debug_event")); return false; // We don't use any events... } diff --git a/src/display/canvas-debug.h b/src/display/canvas-debug.h index 19ccd154ca36342c3202c984b5d5ac8043c1cce9..dd21a9cf5e4c45b04705bfeb77cda02c455459c8 100644 --- a/src/display/canvas-debug.h +++ b/src/display/canvas-debug.h @@ -17,16 +17,19 @@ class SPItem; -#define SP_TYPE_CANVAS_DEBUG (sp_canvas_debug_get_type ()) -#define SP_CANVAS_DEBUG(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SP_TYPE_CANVAS_DEBUG, SPCanvasDebug)) -#define SP_IS_CANVAS_DEBUG(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SP_TYPE_CANVAS_DEBUG)) +#define SP_TYPE_CANVAS_DEBUG (sp_canvas_debug_get_type()) +#define SP_CANVAS_DEBUG(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CANVAS_DEBUG, SPCanvasDebug)) +#define SP_IS_CANVAS_DEBUG(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CANVAS_DEBUG)) -struct SPCanvasDebug : public SPCanvasItem { +struct SPCanvasDebug : public SPCanvasItem +{ }; -GType sp_canvas_debug_get_type (); +GType sp_canvas_debug_get_type(); -struct SPCanvasDebugClass : public SPCanvasItemClass{}; +struct SPCanvasDebugClass : public SPCanvasItemClass +{ +}; #endif // SEEN_SP_CANVAS_DEBUG_H diff --git a/src/display/canvas-grid.cpp b/src/display/canvas-grid.cpp index 49fb483861235a17c28ba16dba7f4d659819e4e3..a730b0a4a968729863dcb23c40612b8c0bf8b708 100644 --- a/src/display/canvas-grid.cpp +++ b/src/display/canvas-grid.cpp @@ -19,37 +19,30 @@ * Don't be shy to correct things. */ -#include -#include -#include +#include "display/canvas-grid.h" #include +#include +#include +#include +#include "desktop.h" #include "display/cairo-utils.h" #include "display/canvas-axonomgrid.h" -#include "display/canvas-grid.h" #include "display/sp-canvas-group.h" - -#include "desktop.h" #include "document.h" -#include "inkscape.h" -#include "preferences.h" -#include "sp-canvas-util.h" -#include "verbs.h" - #include "helper/mathfns.h" - +#include "inkscape.h" #include "object/sp-namedview.h" #include "object/sp-object.h" #include "object/sp-root.h" - +#include "preferences.h" +#include "sp-canvas-util.h" #include "svg/stringstream.h" #include "svg/svg-color.h" - #include "ui/widget/canvas.h" - #include "util/units.h" - +#include "verbs.h" #include "xml/node-event-vector.h" using Inkscape::DocumentUndo; @@ -57,35 +50,27 @@ using Inkscape::Util::unit_table; namespace Inkscape { -static gchar const *const grid_name[] = { - N_("Rectangular grid"), - N_("Axonometric grid") -}; -static gchar const *const grid_svgname[] = { - "xygrid", - "axonomgrid" -}; - +static gchar const *const grid_name[] = {N_("Rectangular grid"), N_("Axonometric grid")}; +static gchar const *const grid_svgname[] = {"xygrid", "axonomgrid"}; // ########################################################## // Grid CanvasItem static void grid_canvasitem_destroy(SPCanvasItem *object); -static void grid_canvasitem_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); -static void grid_canvasitem_render (SPCanvasItem *item, SPCanvasBuf *buf); +static void grid_canvasitem_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); +static void grid_canvasitem_render(SPCanvasItem *item, SPCanvasBuf *buf); G_DEFINE_TYPE(GridCanvasItem, grid_canvasitem, SP_TYPE_CANVAS_ITEM); static void grid_canvasitem_class_init(GridCanvasItemClass *klass) { - SPCanvasItemClass *item_class = (SPCanvasItemClass *) klass; + SPCanvasItemClass *item_class = (SPCanvasItemClass *)klass; item_class->destroy = grid_canvasitem_destroy; item_class->update = grid_canvasitem_update; item_class->render = grid_canvasitem_render; } -static void -grid_canvasitem_init (GridCanvasItem *griditem) +static void grid_canvasitem_init(GridCanvasItem *griditem) { griditem->grid = nullptr; SP_CANVAS_ITEM(griditem)->name = "CanvasGrid"; @@ -93,30 +78,28 @@ grid_canvasitem_init (GridCanvasItem *griditem) static void grid_canvasitem_destroy(SPCanvasItem *object) { - g_return_if_fail (object != nullptr); - g_return_if_fail (INKSCAPE_IS_GRID_CANVASITEM (object)); + g_return_if_fail(object != nullptr); + g_return_if_fail(INKSCAPE_IS_GRID_CANVASITEM(object)); if (SP_CANVAS_ITEM_CLASS(grid_canvasitem_parent_class)->destroy) - (* SP_CANVAS_ITEM_CLASS(grid_canvasitem_parent_class)->destroy) (object); + (*SP_CANVAS_ITEM_CLASS(grid_canvasitem_parent_class)->destroy)(object); } /** -*/ -static void -grid_canvasitem_render (SPCanvasItem * item, SPCanvasBuf * buf) + */ +static void grid_canvasitem_render(SPCanvasItem *item, SPCanvasBuf *buf) { - GridCanvasItem *gridcanvasitem = INKSCAPE_GRID_CANVASITEM (item); + GridCanvasItem *gridcanvasitem = INKSCAPE_GRID_CANVASITEM(item); - if ( gridcanvasitem->grid && gridcanvasitem->grid->isVisible() ) { - sp_canvas_prepare_buffer (buf); + if (gridcanvasitem->grid && gridcanvasitem->grid->isVisible()) { + sp_canvas_prepare_buffer(buf); gridcanvasitem->grid->Render(buf); } } -static void -grid_canvasitem_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) +static void grid_canvasitem_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) { - GridCanvasItem *gridcanvasitem = INKSCAPE_GRID_CANVASITEM (item); + GridCanvasItem *gridcanvasitem = INKSCAPE_GRID_CANVASITEM(item); if (SP_CANVAS_ITEM_CLASS(grid_canvasitem_parent_class)->update) SP_CANVAS_ITEM_CLASS(grid_canvasitem_parent_class)->update(item, affine, flags); @@ -131,26 +114,26 @@ grid_canvasitem_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned } } - - // ########################################################## // CanvasGrid - static Inkscape::XML::NodeEventVector const _repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - CanvasGrid::on_repr_attr_changed, - nullptr, /* content_changed */ - nullptr /* order_changed */ - }; +static Inkscape::XML::NodeEventVector const _repr_events = { + nullptr, /* child_added */ + nullptr, /* child_removed */ + CanvasGrid::on_repr_attr_changed, nullptr, /* content_changed */ + nullptr /* order_changed */ +}; -CanvasGrid::CanvasGrid(SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument *in_doc, GridType type) - : visible(true), gridtype(type), legacy(false), pixel(false) +CanvasGrid::CanvasGrid(SPNamedView *nv, Inkscape::XML::Node *in_repr, SPDocument *in_doc, GridType type) + : visible(true) + , gridtype(type) + , legacy(false) + , pixel(false) { repr = in_repr; doc = in_doc; if (repr) { - repr->addListener (&_repr_events, this); + repr->addListener(&_repr_events, this); } namedview = nv; @@ -159,79 +142,76 @@ CanvasGrid::CanvasGrid(SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocume CanvasGrid::~CanvasGrid() { if (repr) { - repr->removeListenerByData (this); + repr->removeListenerByData(this); } - for (auto i:canvasitems) + for (auto i : canvasitems) sp_canvas_item_destroy(i); canvasitems.clear(); } -const char * -CanvasGrid::getName() const +const char *CanvasGrid::getName() const { return _(grid_name[gridtype]); } -const char * -CanvasGrid::getSVGName() const +const char *CanvasGrid::getSVGName() const { return grid_svgname[gridtype]; } -GridType -CanvasGrid::getGridType() const +GridType CanvasGrid::getGridType() const { return gridtype; } - -char const * -CanvasGrid::getName(GridType type) +char const *CanvasGrid::getName(GridType type) { return _(grid_name[type]); } -char const * -CanvasGrid::getSVGName(GridType type) +char const *CanvasGrid::getSVGName(GridType type) { return grid_svgname[type]; } -GridType -CanvasGrid::getGridTypeFromSVGName(char const *typestr) +GridType CanvasGrid::getGridTypeFromSVGName(char const *typestr) { - if (!typestr) return GRID_RECTANGULAR; + if (!typestr) + return GRID_RECTANGULAR; gint t = 0; - for (t = GRID_MAXTYPENR; t >= 0; t--) { //this automatically defaults to grid0 which is rectangular grid - if (!strcmp(typestr, grid_svgname[t])) break; + for (t = GRID_MAXTYPENR; t >= 0; t--) { // this automatically defaults to grid0 which is rectangular grid + if (!strcmp(typestr, grid_svgname[t])) + break; } - return (GridType) t; + return (GridType)t; } -GridType -CanvasGrid::getGridTypeFromName(char const *typestr) +GridType CanvasGrid::getGridTypeFromName(char const *typestr) { - if (!typestr) return GRID_RECTANGULAR; + if (!typestr) + return GRID_RECTANGULAR; gint t = 0; - for (t = GRID_MAXTYPENR; t >= 0; t--) { //this automatically defaults to grid0 which is rectangular grid - if (!strcmp(typestr, _(grid_name[t]))) break; + for (t = GRID_MAXTYPENR; t >= 0; t--) { // this automatically defaults to grid0 which is rectangular grid + if (!strcmp(typestr, _(grid_name[t]))) + break; } - return (GridType) t; + return (GridType)t; } - /* -* writes an child to repr. -*/ -void -CanvasGrid::writeNewGridToRepr(Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype) + * writes an child to repr. + */ +void CanvasGrid::writeNewGridToRepr(Inkscape::XML::Node *repr, SPDocument *doc, GridType gridtype) { - if (!repr) return; - if (gridtype > GRID_MAXTYPENR) return; + if (!repr) + return; + if (gridtype > GRID_MAXTYPENR) + return; - // first create the child xml node, then hook it to repr. This order is important, to not set off listeners to repr before the new node is complete. + // first create the child xml node, then hook it to repr. This order is important, to not set off listeners to repr + // before the new node is complete. Inkscape::XML::Document *xml_doc = doc->getReprDoc(); Inkscape::XML::Node *newnode; @@ -245,12 +225,12 @@ CanvasGrid::writeNewGridToRepr(Inkscape::XML::Node * repr, SPDocument * doc, Gri } /* -* Creates a new CanvasGrid object of type gridtype -*/ -CanvasGrid* -CanvasGrid::NewGrid(SPNamedView * nv, Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype) + * Creates a new CanvasGrid object of type gridtype + */ +CanvasGrid *CanvasGrid::NewGrid(SPNamedView *nv, Inkscape::XML::Node *repr, SPDocument *doc, GridType gridtype) { - if (!repr) return nullptr; + if (!repr) + return nullptr; if (!doc) { g_error("CanvasGrid::NewGrid - doc==NULL"); return nullptr; @@ -258,47 +238,47 @@ CanvasGrid::NewGrid(SPNamedView * nv, Inkscape::XML::Node * repr, SPDocument * d switch (gridtype) { case GRID_RECTANGULAR: - return dynamic_cast(new CanvasXYGrid(nv, repr, doc)); + return dynamic_cast(new CanvasXYGrid(nv, repr, doc)); case GRID_AXONOMETRIC: - return dynamic_cast(new CanvasAxonomGrid(nv, repr, doc)); + return dynamic_cast(new CanvasAxonomGrid(nv, repr, doc)); } return nullptr; } - /** -* creates a new grid canvasitem for the SPDesktop given as parameter. Keeps a link to this canvasitem in the canvasitems list. -*/ -GridCanvasItem * -CanvasGrid::createCanvasItem(SPDesktop * desktop) + * creates a new grid canvasitem for the SPDesktop given as parameter. Keeps a link to this canvasitem in the + * canvasitems list. + */ +GridCanvasItem *CanvasGrid::createCanvasItem(SPDesktop *desktop) { - if (!desktop) return nullptr; -// Johan: I think for multiple desktops it is best if each has their own canvasitem, -// but share the same CanvasGrid object; that is what this function is for. + if (!desktop) + return nullptr; + // Johan: I think for multiple desktops it is best if each has their own canvasitem, + // but share the same CanvasGrid object; that is what this function is for. // check if there is already a canvasitem on this desktop linking to this grid - for (auto i:canvasitems) { - if ( desktop->getGridGroup() == SP_CANVAS_GROUP(i->parent) ) { + for (auto i : canvasitems) { + if (desktop->getGridGroup() == SP_CANVAS_GROUP(i->parent)) { return nullptr; } } - GridCanvasItem * item = INKSCAPE_GRID_CANVASITEM( sp_canvas_item_new(desktop->getGridGroup(), INKSCAPE_TYPE_GRID_CANVASITEM, nullptr) ); + GridCanvasItem *item = + INKSCAPE_GRID_CANVASITEM(sp_canvas_item_new(desktop->getGridGroup(), INKSCAPE_TYPE_GRID_CANVASITEM, nullptr)); item->grid = this; sp_canvas_item_show(SP_CANVAS_ITEM(item)); - g_object_ref(item); // since we're keeping a link to this item, we need to bump up the ref count + g_object_ref(item); // since we're keeping a link to this item, we need to bump up the ref count canvasitems.push_back(item); return item; } -Gtk::Widget * -CanvasGrid::newWidget() +Gtk::Widget *CanvasGrid::newWidget() { - Gtk::VBox * vbox = Gtk::manage( new Gtk::VBox() ); - Gtk::Label * namelabel = Gtk::manage(new Gtk::Label("", Gtk::ALIGN_CENTER) ); + Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox()); + Gtk::Label *namelabel = Gtk::manage(new Gtk::Label("", Gtk::ALIGN_CENTER)); Glib::ustring str(""); str += getName(); @@ -306,22 +286,21 @@ CanvasGrid::newWidget() namelabel->set_markup(str); vbox->pack_start(*namelabel, false, false); - _rcb_enabled = Gtk::manage( new Inkscape::UI::Widget::RegisteredCheckButton( - _("_Enabled"), - _("Makes the grid available for working with on the canvas."), - "enabled", _wr, false, repr, doc) ); + _rcb_enabled = Gtk::manage(new Inkscape::UI::Widget::RegisteredCheckButton( + _("_Enabled"), _("Makes the grid available for working with on the canvas."), "enabled", _wr, false, repr, + doc)); - _rcb_snap_visible_only = Gtk::manage( new Inkscape::UI::Widget::RegisteredCheckButton( - _("Snap to visible _grid lines only"), - _("When zoomed out, not all grid lines will be displayed. Only the visible ones will be snapped to"), - "snapvisiblegridlinesonly", _wr, false, repr, doc) ); + _rcb_snap_visible_only = Gtk::manage(new Inkscape::UI::Widget::RegisteredCheckButton( + _("Snap to visible _grid lines only"), + _("When zoomed out, not all grid lines will be displayed. Only the visible ones will be snapped to"), + "snapvisiblegridlinesonly", _wr, false, repr, doc)); - _rcb_visible = Gtk::manage( new Inkscape::UI::Widget::RegisteredCheckButton( - _("_Visible"), - _("Determines whether the grid is displayed or not. Objects are still snapped to invisible grids."), - "visible", _wr, false, repr, doc) ); + _rcb_visible = Gtk::manage(new Inkscape::UI::Widget::RegisteredCheckButton( + _("_Visible"), + _("Determines whether the grid is displayed or not. Objects are still snapped to invisible grids."), "visible", + _wr, false, repr, doc)); - _as_alignment = Gtk::manage( new Inkscape::UI::Widget::AlignmentSelector() ); + _as_alignment = Gtk::manage(new Inkscape::UI::Widget::AlignmentSelector()); _as_alignment->on_alignmentClicked().connect(sigc::mem_fun(*this, &CanvasGrid::align_clicked)); Gtk::Box *left = new Gtk::Box(Gtk::ORIENTATION_VERTICAL, 4); @@ -330,9 +309,9 @@ CanvasGrid::newWidget() left->pack_start(*_rcb_snap_visible_only, false, false); if (getGridType() == GRID_RECTANGULAR) { - _rcb_dotted = Gtk::manage( new Inkscape::UI::Widget::RegisteredCheckButton( - _("_Show dots instead of lines"), _("If set, displays dots at gridpoints instead of gridlines"), - "dotted", _wr, false, repr, doc) ); + _rcb_dotted = Gtk::manage(new Inkscape::UI::Widget::RegisteredCheckButton( + _("_Show dots instead of lines"), _("If set, displays dots at gridpoints instead of gridlines"), "dotted", + _wr, false, repr, doc)); _rcb_dotted->setActive(render_dotted); left->pack_start(*_rcb_dotted, false, false); } @@ -349,7 +328,7 @@ CanvasGrid::newWidget() vbox->pack_start(*inner, false, false); vbox->set_border_width(4); - std::list slaves; + std::list slaves; for (auto &item : left->get_children()) { if (item != _rcb_enabled) { slaves.push_back(item); @@ -359,29 +338,29 @@ CanvasGrid::newWidget() _rcb_enabled->setSlaveWidgets(slaves); // set widget values - _wr.setUpdating (true); + _wr.setUpdating(true); _rcb_visible->setActive(visible); if (snapper != nullptr) { _rcb_enabled->setActive(snapper->getEnabled()); _rcb_snap_visible_only->setActive(snapper->getSnapVisibleOnly()); } - _wr.setUpdating (false); - return dynamic_cast (vbox); + _wr.setUpdating(false); + return dynamic_cast(vbox); } -void -CanvasGrid::on_repr_attr_changed(Inkscape::XML::Node *repr, gchar const *key, gchar const *oldval, gchar const *newval, bool is_interactive, void *data) +void CanvasGrid::on_repr_attr_changed(Inkscape::XML::Node *repr, gchar const *key, gchar const *oldval, + gchar const *newval, bool is_interactive, void *data) { if (!data) return; - (static_cast(data))->onReprAttrChanged(repr, key, oldval, newval, is_interactive); + (static_cast(data))->onReprAttrChanged(repr, key, oldval, newval, is_interactive); } bool CanvasGrid::isEnabled() const { if (snapper == nullptr) { - return false; + return false; } return snapper->getEnabled(); @@ -393,8 +372,8 @@ void CanvasGrid::setOrigin(Geom::Point const &origin_px) SPRoot *root = doc->getRoot(); double scale_x = 1.0; double scale_y = 1.0; - if( root->viewBox_set ) { - scale_x = root->viewBox.width() / root->width.computed; + if (root->viewBox_set) { + scale_x = root->viewBox.width() / root->width.computed; scale_y = root->viewBox.height() / root->height.computed; } @@ -415,12 +394,10 @@ void CanvasGrid::align_clicked(int align) setOrigin(dimensions); } - - // ########################################################## // CanvasXYGrid -CanvasXYGrid::CanvasXYGrid (SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument * in_doc) +CanvasXYGrid::CanvasXYGrid(SPNamedView *nv, Inkscape::XML::Node *in_repr, SPDocument *in_doc) : CanvasGrid(nv, in_repr, in_doc, GRID_RECTANGULAR) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -428,23 +405,29 @@ CanvasXYGrid::CanvasXYGrid (SPNamedView * nv, Inkscape::XML::Node * in_repr, SPD if (!gridunit) { gridunit = unit_table.getUnit("px"); } - origin[Geom::X] = Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/xy/origin_x", 0.0), gridunit, "px"); - origin[Geom::Y] = Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/xy/origin_y", 0.0), gridunit, "px"); + origin[Geom::X] = + Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/xy/origin_x", 0.0), gridunit, "px"); + origin[Geom::Y] = + Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/xy/origin_y", 0.0), gridunit, "px"); color = prefs->getInt("/options/grids/xy/color", GRID_DEFAULT_COLOR); empcolor = prefs->getInt("/options/grids/xy/empcolor", GRID_DEFAULT_EMPCOLOR); empspacing = prefs->getInt("/options/grids/xy/empspacing", 5); - spacing[Geom::X] = Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/xy/spacing_x", 0.0), gridunit, "px"); - spacing[Geom::Y] = Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/xy/spacing_y", 0.0), gridunit, "px"); + spacing[Geom::X] = + Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/xy/spacing_x", 0.0), gridunit, "px"); + spacing[Geom::Y] = + Inkscape::Util::Quantity::convert(prefs->getDouble("/options/grids/xy/spacing_y", 0.0), gridunit, "px"); render_dotted = prefs->getBool("/options/grids/xy/dotted", false); snapper = new CanvasXYGridSnapper(this, &namedview->snap_manager, 0); - if (repr) readRepr(); + if (repr) + readRepr(); } -CanvasXYGrid::~CanvasXYGrid () +CanvasXYGrid::~CanvasXYGrid() { - if (snapper) delete snapper; + if (snapper) + delete snapper; } static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color) @@ -460,7 +443,7 @@ static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color) } v = CLAMP(v, 0.0, 1.0); - *color = (*color & 0xffffff00) | (guint32) floor(v * 255.9999); + *color = (*color & 0xffffff00) | (guint32)floor(v * 255.9999); return TRUE; } @@ -472,37 +455,35 @@ static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color) @param pTarget The int to validate. @param widget Widget associated with the int. */ -static void validateInt(gint oldVal, - gint* pTarget) +static void validateInt(gint oldVal, gint *pTarget) { // Avoid nullness. - if ( pTarget == nullptr ) + if (pTarget == nullptr) return; // Invalid new value? - if ( *pTarget <= 0 ) { + if (*pTarget <= 0) { // If the old value is somehow invalid as well, then default to 1. - if ( oldVal <= 0 ) + if (oldVal <= 0) oldVal = 1; // Reset the int and associated widget to the old value. *pTarget = oldVal; - } //if + } // if -} //validateInt +} // validateInt -void -CanvasXYGrid::readRepr() +void CanvasXYGrid::readRepr() { SPRoot *root = doc->getRoot(); double scale_x = 1.0; double scale_y = 1.0; - if( root->viewBox_set ) { - scale_x = root->width.computed / root->viewBox.width(); + if (root->viewBox_set) { + scale_x = root->width.computed / root->viewBox.width(); scale_y = root->height.computed / root->viewBox.height(); if (Geom::are_near(scale_x / scale_y, 1.0, Geom::EPSILON)) { // scaling is uniform, try to reduce numerical error - scale_x = (scale_x + scale_y)/2.0; + scale_x = (scale_x + scale_y) / 2.0; double scale_none = Inkscape::Util::Quantity::convert(1, doc->getDisplayUnit(), "px"); if (Geom::are_near(scale_x / scale_none, 1.0, Geom::EPSILON)) scale_x = scale_none; // objects are same size, reduce numerical error @@ -512,15 +493,14 @@ CanvasXYGrid::readRepr() gchar const *value; - if ( (value = repr->attribute("originx")) ) { - + if ((value = repr->attribute("originx"))) { Inkscape::Util::Quantity q = unit_table.parseQuantity(value); - if( q.unit->type == UNIT_TYPE_LINEAR ) { + if (q.unit->type == UNIT_TYPE_LINEAR) { // Legacy grid not in 'user units' origin[Geom::X] = q.value("px"); legacy = true; - if (q.unit->abbr == "px" ) { + if (q.unit->abbr == "px") { pixel = true; } } else { @@ -529,15 +509,14 @@ CanvasXYGrid::readRepr() } } - if ( (value = repr->attribute("originy")) ) { - + if ((value = repr->attribute("originy"))) { Inkscape::Util::Quantity q = unit_table.parseQuantity(value); - if( q.unit->type == UNIT_TYPE_LINEAR ) { + if (q.unit->type == UNIT_TYPE_LINEAR) { // Legacy grid not in 'user units' origin[Geom::Y] = q.value("px"); legacy = true; - if (q.unit->abbr == "px" ) { + if (q.unit->abbr == "px") { pixel = true; } } else { @@ -546,20 +525,19 @@ CanvasXYGrid::readRepr() } } - if ( (value = repr->attribute("spacingx")) ) { - + if ((value = repr->attribute("spacingx"))) { // Ensure a valid default value - if( spacing[Geom::X] <= 0.0 ) + if (spacing[Geom::X] <= 0.0) spacing[Geom::X] = 1.0; Inkscape::Util::Quantity q = unit_table.parseQuantity(value); // Ensure a valid new value - if( q.quantity > 0 ) { - if( q.unit->type == UNIT_TYPE_LINEAR ) { + if (q.quantity > 0) { + if (q.unit->type == UNIT_TYPE_LINEAR) { // Legacy grid not in 'user units' spacing[Geom::X] = q.value("px"); legacy = true; - if (q.unit->abbr == "px" ) { + if (q.unit->abbr == "px") { pixel = true; } } else { @@ -569,20 +547,19 @@ CanvasXYGrid::readRepr() } } - if ( (value = repr->attribute("spacingy")) ) { - + if ((value = repr->attribute("spacingy"))) { // Ensure a valid default value - if( spacing[Geom::Y] <= 0.0 ) + if (spacing[Geom::Y] <= 0.0) spacing[Geom::Y] = 1.0; Inkscape::Util::Quantity q = unit_table.parseQuantity(value); // Ensure a valid new value - if( q.quantity > 0 ) { - if( q.unit->type == UNIT_TYPE_LINEAR ) { + if (q.quantity > 0) { + if (q.unit->type == UNIT_TYPE_LINEAR) { // Legacy grid not in 'user units' spacing[Geom::Y] = q.value("px"); legacy = true; - if (q.unit->abbr == "px" ) { + if (q.unit->abbr == "px") { pixel = true; } } else { @@ -592,50 +569,50 @@ CanvasXYGrid::readRepr() } } - if ( (value = repr->attribute("color")) ) { + if ((value = repr->attribute("color"))) { color = (color & 0xff) | sp_svg_read_color(value, color); } - if ( (value = repr->attribute("empcolor")) ) { + if ((value = repr->attribute("empcolor"))) { empcolor = (empcolor & 0xff) | sp_svg_read_color(value, empcolor); } - if ( (value = repr->attribute("opacity")) ) { + if ((value = repr->attribute("opacity"))) { sp_nv_read_opacity(value, &color); } - if ( (value = repr->attribute("empopacity")) ) { + if ((value = repr->attribute("empopacity"))) { sp_nv_read_opacity(value, &empcolor); } - if ( (value = repr->attribute("empspacing")) ) { + if ((value = repr->attribute("empspacing"))) { gint oldVal = empspacing; empspacing = atoi(value); - validateInt( oldVal, &empspacing); + validateInt(oldVal, &empspacing); } - if ( (value = repr->attribute("dotted")) ) { - render_dotted = (strcmp(value,"false") != 0 && strcmp(value, "0") != 0); + if ((value = repr->attribute("dotted"))) { + render_dotted = (strcmp(value, "false") != 0 && strcmp(value, "0") != 0); } - if ( (value = repr->attribute("visible")) ) { - visible = (strcmp(value,"false") != 0 && strcmp(value, "0") != 0); + if ((value = repr->attribute("visible"))) { + visible = (strcmp(value, "false") != 0 && strcmp(value, "0") != 0); } - if ( (value = repr->attribute("enabled")) ) { + if ((value = repr->attribute("enabled"))) { g_assert(snapper != nullptr); - snapper->setEnabled(strcmp(value,"false") != 0 && strcmp(value, "0") != 0); + snapper->setEnabled(strcmp(value, "false") != 0 && strcmp(value, "0") != 0); } - if ( (value = repr->attribute("snapvisiblegridlinesonly")) ) { + if ((value = repr->attribute("snapvisiblegridlinesonly"))) { g_assert(snapper != nullptr); - snapper->setSnapVisibleOnly(strcmp(value,"false") != 0 && strcmp(value, "0") != 0); + snapper->setSnapVisibleOnly(strcmp(value, "false") != 0 && strcmp(value, "0") != 0); } - if ( (value = repr->attribute("units")) ) { + if ((value = repr->attribute("units"))) { gridunit = unit_table.getUnit(value); // Display unit identifier in grid menu } - for (auto i:canvasitems) { + for (auto i : canvasitems) { sp_canvas_item_request_update(i); } @@ -645,43 +622,39 @@ CanvasXYGrid::readRepr() /** * Called when XML node attribute changed; updates dialog widgets if change was not done by widgets themselves. */ -void -CanvasXYGrid::onReprAttrChanged(Inkscape::XML::Node */*repr*/, gchar const */*key*/, gchar const */*oldval*/, gchar const */*newval*/, bool /*is_interactive*/) +void CanvasXYGrid::onReprAttrChanged(Inkscape::XML::Node * /*repr*/, gchar const * /*key*/, gchar const * /*oldval*/, + gchar const * /*newval*/, bool /*is_interactive*/) { readRepr(); updateWidgets(); } - -Gtk::Widget * -CanvasXYGrid::newSpecificWidget() +Gtk::Widget *CanvasXYGrid::newSpecificWidget() { - _rumg = Gtk::manage( new Inkscape::UI::Widget::RegisteredUnitMenu( - _("Grid _units:"), "units", _wr, repr, doc) ); - _rsu_ox = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit( - _("_Origin X:"), _("X coordinate of grid origin"), "originx", - *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_x) ); - _rsu_oy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit( - _("O_rigin Y:"), _("Y coordinate of grid origin"), "originy", - *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_y) ); - _rsu_sx = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit( - _("Spacing _X:"), _("Distance between vertical grid lines"), "spacingx", - *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_x) ); - _rsu_sy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit( - _("Spacing _Y:"), _("Distance between horizontal grid lines"), "spacingy", - *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_y) ); - - _rcp_gcol = Gtk::manage( new Inkscape::UI::Widget::RegisteredColorPicker( - _("Minor grid line _color:"), _("Minor grid line color"), _("Color of the minor grid lines"), - "color", "opacity", _wr, repr, doc) ); - - _rcp_gmcol = Gtk::manage( new Inkscape::UI::Widget::RegisteredColorPicker( - _("Ma_jor grid line color:"), _("Major grid line color"), - _("Color of the major (highlighted) grid lines"), "empcolor", "empopacity", - _wr, repr, doc) ); - - _rsi = Gtk::manage( new Inkscape::UI::Widget::RegisteredSuffixedInteger( - _("_Major grid line every:"), "", _("lines"), "empspacing", _wr, repr, doc) ); + _rumg = Gtk::manage(new Inkscape::UI::Widget::RegisteredUnitMenu(_("Grid _units:"), "units", _wr, repr, doc)); + _rsu_ox = Gtk::manage( + new Inkscape::UI::Widget::RegisteredScalarUnit(_("_Origin X:"), _("X coordinate of grid origin"), "originx", + *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_x)); + _rsu_oy = Gtk::manage( + new Inkscape::UI::Widget::RegisteredScalarUnit(_("O_rigin Y:"), _("Y coordinate of grid origin"), "originy", + *_rumg, _wr, repr, doc, Inkscape::UI::Widget::RSU_y)); + _rsu_sx = Gtk::manage(new Inkscape::UI::Widget::RegisteredScalarUnit( + _("Spacing _X:"), _("Distance between vertical grid lines"), "spacingx", *_rumg, _wr, repr, doc, + Inkscape::UI::Widget::RSU_x)); + _rsu_sy = Gtk::manage(new Inkscape::UI::Widget::RegisteredScalarUnit( + _("Spacing _Y:"), _("Distance between horizontal grid lines"), "spacingy", *_rumg, _wr, repr, doc, + Inkscape::UI::Widget::RSU_y)); + + _rcp_gcol = Gtk::manage(new Inkscape::UI::Widget::RegisteredColorPicker( + _("Minor grid line _color:"), _("Minor grid line color"), _("Color of the minor grid lines"), "color", + "opacity", _wr, repr, doc)); + + _rcp_gmcol = Gtk::manage(new Inkscape::UI::Widget::RegisteredColorPicker( + _("Ma_jor grid line color:"), _("Major grid line color"), _("Color of the major (highlighted) grid lines"), + "empcolor", "empopacity", _wr, repr, doc)); + + _rsi = Gtk::manage(new Inkscape::UI::Widget::RegisteredSuffixedInteger(_("_Major grid line every:"), "", _("lines"), + "empspacing", _wr, repr, doc)); _rumg->set_hexpand(); _rsu_ox->set_hexpand(); @@ -693,7 +666,7 @@ CanvasXYGrid::newSpecificWidget() _rsi->set_hexpand(); // set widget values - _wr.setUpdating (true); + _wr.setUpdating(true); _rsu_ox->setDigits(5); _rsu_ox->setIncrements(0.1, 1.0); @@ -707,27 +680,27 @@ CanvasXYGrid::newSpecificWidget() _rsu_sy->setDigits(5); _rsu_sy->setIncrements(0.1, 1.0); - _rumg->setUnit (gridunit->abbr); + _rumg->setUnit(gridunit->abbr); gdouble val; val = origin[Geom::X]; val = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_ox->setValue (val); + _rsu_ox->setValue(val); val = origin[Geom::Y]; val = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_oy->setValue (val); + _rsu_oy->setValue(val); val = spacing[Geom::X]; double gridx = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_sx->setValue (gridx); + _rsu_sx->setValue(gridx); val = spacing[Geom::Y]; double gridy = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_sy->setValue (gridy); + _rsu_sy->setValue(gridy); - _rcp_gcol->setRgba32 (color); - _rcp_gmcol->setRgba32 (empcolor); - _rsi->setValue (empspacing); + _rcp_gcol->setRgba32(color); + _rcp_gmcol->setRgba32(empcolor); + _rsi->setValue(empspacing); - _wr.setUpdating (false); + _wr.setUpdating(false); _rsu_ox->setProgrammatically = false; _rsu_oy->setProgrammatically = false; @@ -747,19 +720,19 @@ CanvasXYGrid::newSpecificWidget() return column; } - /** * Update dialog widgets from object's values. */ -void -CanvasXYGrid::updateWidgets() +void CanvasXYGrid::updateWidgets() { - if (_wr.isUpdating()) return; + if (_wr.isUpdating()) + return; - //no widgets (grid created with the document, not with the dialog) - if (!_rcb_visible) return; + // no widgets (grid created with the document, not with the dialog) + if (!_rcb_visible) + return; - _wr.setUpdating (true); + _wr.setUpdating(true); _rcb_visible->setActive(visible); if (snapper != nullptr) { @@ -767,42 +740,42 @@ CanvasXYGrid::updateWidgets() _rcb_snap_visible_only->setActive(snapper->getSnapVisibleOnly()); } - _rumg->setUnit (gridunit->abbr); + _rumg->setUnit(gridunit->abbr); gdouble val; val = origin[Geom::X]; val = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_ox->setValue (val); + _rsu_ox->setValue(val); val = origin[Geom::Y]; val = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_oy->setValue (val); + _rsu_oy->setValue(val); val = spacing[Geom::X]; val = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_sx->setValue (val); + _rsu_sx->setValue(val); val = spacing[Geom::Y]; val = Inkscape::Util::Quantity::convert(val, "px", gridunit); - _rsu_sy->setValue (val); + _rsu_sy->setValue(val); _rsu_ox->setProgrammatically = false; _rsu_oy->setProgrammatically = false; _rsu_sx->setProgrammatically = false; _rsu_sy->setProgrammatically = false; - _rcp_gcol->setRgba32 (color); - _rcp_gmcol->setRgba32 (empcolor); - _rsi->setValue (empspacing); - _rcb_dotted->setActive (render_dotted); + _rcp_gcol->setRgba32(color); + _rcp_gmcol->setRgba32(empcolor); + _rsi->setValue(empspacing); + _rcb_dotted->setActive(render_dotted); - _wr.setUpdating (false); + _wr.setUpdating(false); } // For correcting old SVG Inkscape files -void -CanvasXYGrid::Scale (Geom::Scale const &scale ) { +void CanvasXYGrid::Scale(Geom::Scale const &scale) +{ origin *= scale; spacing *= scale; @@ -812,21 +785,20 @@ CanvasXYGrid::Scale (Geom::Scale const &scale ) { os_y << origin[Geom::Y]; ss_x << spacing[Geom::X]; ss_y << spacing[Geom::Y]; - repr->setAttribute("originx", os_x.str()); - repr->setAttribute("originy", os_y.str()); + repr->setAttribute("originx", os_x.str()); + repr->setAttribute("originy", os_y.str()); repr->setAttribute("spacingx", ss_x.str()); repr->setAttribute("spacingy", ss_y.str()); } -void -CanvasXYGrid::Update (Geom::Affine const &affine, unsigned int /*flags*/) +void CanvasXYGrid::Update(Geom::Affine const &affine, unsigned int /*flags*/) { ow = origin * affine; sw[0] = Geom::Point(spacing[0], 0) * affine.withoutTranslation(); sw[1] = Geom::Point(0, spacing[1]) * affine.withoutTranslation(); // Find suitable grid spacing for display - for(int dim = 0; dim < 2; dim++) { + for (int dim = 0; dim < 2; dim++) { gint scaling_factor = empspacing; if (scaling_factor <= 1) @@ -843,24 +815,22 @@ CanvasXYGrid::Update (Geom::Affine const &affine, unsigned int /*flags*/) } } - // Find intersections of line with rectangle. There should be zero or two. // If line is degenerate with rectangle side, two corner points are returned. -static std::vector -intersect_line_rectangle( Geom::Line const &line, Geom::Rect const &rect ) +static std::vector intersect_line_rectangle(Geom::Line const &line, Geom::Rect const &rect) { std::vector intersections; for (unsigned i = 0; i < 4; ++i) { - Geom::LineSegment side( rect.corner(i), rect.corner((i+1)%4) ); + Geom::LineSegment side(rect.corner(i), rect.corner((i + 1) % 4)); try { Geom::OptCrossing oc = Geom::intersection(line, side); if (oc) { - intersections.push_back( line.pointAt((*oc).ta)); + intersections.push_back(line.pointAt((*oc).ta)); } } catch (Geom::InfiniteSolutions) { intersections.clear(); - intersections.push_back( side.pointAt(0) ); - intersections.push_back( side.pointAt(1) ); + intersections.push_back(side.pointAt(0)); + intersections.push_back(side.pointAt(1)); return intersections; } } @@ -869,27 +839,25 @@ intersect_line_rectangle( Geom::Line const &line, Geom::Rect const &rect ) // Find the signed distance of a point to a line. The distance is negative if // the point lies to the left of the line considering the line's versor. -static double -signed_distance( Geom::Point const &point, Geom::Line const &line ) { - Geom::Coord t = line.nearestTime( point ); +static double signed_distance(Geom::Point const &point, Geom::Line const &line) +{ + Geom::Coord t = line.nearestTime(point); Geom::Point p = line.pointAt(t); - double distance = Geom::distance( p, point ); - if ( Geom::cross( Geom::Line( p, point ).versor(), line.versor() ) < 0.0 ) { + double distance = Geom::distance(p, point); + if (Geom::cross(Geom::Line(p, point).versor(), line.versor()) < 0.0) { distance = -distance; } return distance; } -void -CanvasXYGrid::Render (SPCanvasBuf *buf) +void CanvasXYGrid::Render(SPCanvasBuf *buf) { - // no_emphasize_when_zoomedout determines color (minor or major) when only major grid lines/dots shown. Inkscape::Preferences *prefs = Inkscape::Preferences::get(); guint32 _empcolor; guint32 _color = color; bool no_emp_when_zoomed_out = prefs->getBool("/options/grids/no_emphasize_when_zoomedout", false); - if( (scaled[Geom::X] || scaled[Geom::Y]) && no_emp_when_zoomed_out ) { + if ((scaled[Geom::X] || scaled[Geom::Y]) && no_emp_when_zoomed_out) { _empcolor = color; } else { _empcolor = empcolor; @@ -899,50 +867,57 @@ CanvasXYGrid::Render (SPCanvasBuf *buf) if (xrayactive) { guint32 bg = namedview->pagecolor; _color = SP_RGBA32_F_COMPOSE( - CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_R_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_R_F(_color)), 0.0, 1.0), - CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_G_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_G_F(_color)), 0.0, 1.0), - CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_B_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_B_F(_color)), 0.0, 1.0), - 1.0); - _empcolor = SP_RGBA32_F_COMPOSE( - CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_R_F(bg)) + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_R_F(_empcolor)), 0.0, 1.0), - CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_G_F(bg)) + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_G_F(_empcolor)), 0.0, 1.0), - CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_B_F(bg)) + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_B_F(_empcolor)), 0.0, 1.0), - 1.0); + CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_R_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_R_F(_color)), + 0.0, 1.0), + CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_G_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_G_F(_color)), + 0.0, 1.0), + CLAMP(((1 - SP_RGBA32_A_F(_color)) * SP_RGBA32_B_F(bg)) + (SP_RGBA32_A_F(_color) * SP_RGBA32_B_F(_color)), + 0.0, 1.0), + 1.0); + _empcolor = SP_RGBA32_F_COMPOSE(CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_R_F(bg)) + + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_R_F(_empcolor)), + 0.0, 1.0), + CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_G_F(bg)) + + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_G_F(_empcolor)), + 0.0, 1.0), + CLAMP(((1 - SP_RGBA32_A_F(_empcolor)) * SP_RGBA32_B_F(bg)) + + (SP_RGBA32_A_F(_empcolor) * SP_RGBA32_B_F(_empcolor)), + 0.0, 1.0), + 1.0); } cairo_save(buf->ct); cairo_translate(buf->ct, -buf->rect.left(), -buf->rect.top()); cairo_set_line_width(buf->ct, 1.0); cairo_set_line_cap(buf->ct, CAIRO_LINE_CAP_SQUARE); - // Adding a 2 px margin to the buffer rectangle to avoid missing intersections (in case of rounding errors, and due to adding 0.5 below) + // Adding a 2 px margin to the buffer rectangle to avoid missing intersections (in case of rounding errors, and due + // to adding 0.5 below) Geom::IntRect buf_rect_with_margin = buf->rect; buf_rect_with_margin.expandBy(2); for (unsigned dim = 0; dim < 2; ++dim) { - // std::cout << "\n " << (dim==0?"Horizontal":"Vertical") << " ------------" << std::endl; // Construct an axis line through origin with direction normal to grid spacing. - Geom::Line axis = Geom::Line::from_origin_and_vector( ow, sw[dim] ); - Geom::Line orth = Geom::Line::from_origin_and_vector( ow, sw[(dim+1)%2] ); + Geom::Line axis = Geom::Line::from_origin_and_vector(ow, sw[dim]); + Geom::Line orth = Geom::Line::from_origin_and_vector(ow, sw[(dim + 1) % 2]); - double spacing = sw[(dim+1)%2].length(); // Spacing between grid lines. - double dash = sw[dim].length(); // Total length of dash pattern. + double spacing = sw[(dim + 1) % 2].length(); // Spacing between grid lines. + double dash = sw[dim].length(); // Total length of dash pattern. // std::cout << " axis: " << axis.origin() << ", " << axis.vector() << std::endl; // std::cout << " spacing: " << spacing << std::endl; // std::cout << " dash period: " << dash << std::endl; // Find the minimum and maximum distances of the buffer corners from axis. - double min = 1000000; + double min = 1000000; double max = -1000000; for (unsigned c = 0; c < 4; ++c) { - // We need signed distance... lib2geom offers only positive distance. - double distance = signed_distance( buf_rect_with_margin.corner(c), axis ); + double distance = signed_distance(buf_rect_with_margin.corner(c), axis); // Correct it for coordinate flips (inverts handedness). - if (Geom::cross( axis.vector(), orth.vector() ) > 0 ) { + if (Geom::cross(axis.vector(), orth.vector()) > 0) { distance = -distance; } @@ -951,34 +926,34 @@ CanvasXYGrid::Render (SPCanvasBuf *buf) if (distance > max) max = distance; } - int start = floor( min/spacing ); - int stop = floor( max/spacing ); + int start = floor(min / spacing); + int stop = floor(max / spacing); // std::cout << " rect: " << buf->rect << std::endl; // std::cout << " min: " << min << " max: " << max << std::endl; // std::cout << " start: " << start << " stop: " << stop << std::endl; // Loop over grid lines that intersected buf rectangle. - for (int j = start+1; j <= stop; ++j) { - - Geom::Line grid_line = Geom::make_parallel_line( ow + j * sw[(dim+1)%2], axis ); + for (int j = start + 1; j <= stop; ++j) { + Geom::Line grid_line = Geom::make_parallel_line(ow + j * sw[(dim + 1) % 2], axis); - std::vector x = intersect_line_rectangle( grid_line, buf_rect_with_margin ); + std::vector x = intersect_line_rectangle(grid_line, buf_rect_with_margin); // If we have two intersections, grid line intersects buffer rectangle. - if (x.size() == 2 ) { + if (x.size() == 2) { // Make sure lines are always drawn in the same direction (or dashes misplaced). - Geom::Line vector( x[0], x[1]); - if (Geom::dot( vector.vector(), axis.vector() ) < 0.0) { + Geom::Line vector(x[0], x[1]); + if (Geom::dot(vector.vector(), axis.vector()) < 0.0) { std::swap(x[0], x[1]); } - // Set up line. Need to use floor()+0.5 such that Cairo will draw us lines with a width of a single pixel, without any aliasing. - // For this we need to position the lines at exactly half pixels, see https://www.cairographics.org/FAQ/#sharp_lines - // Must be consistent with the pixel alignment of the guide lines, see CanvasXYGrid::Render(), and the drawing of the rulers + // Set up line. Need to use floor()+0.5 such that Cairo will draw us lines with a width of a single + // pixel, without any aliasing. For this we need to position the lines at exactly half pixels, see + // https://www.cairographics.org/FAQ/#sharp_lines Must be consistent with the pixel alignment of the + // guide lines, see CanvasXYGrid::Render(), and the drawing of the rulers cairo_move_to(buf->ct, floor(x[0][Geom::X]) + 0.5, floor(x[0][Geom::Y]) + 0.5); cairo_line_to(buf->ct, floor(x[1][Geom::X]) + 0.5, floor(x[1][Geom::Y]) + 0.5); - + // Set dash pattern and color. if (render_dotted) { // alpha needs to be larger than in the line case to maintain a similar @@ -997,8 +972,8 @@ CanvasXYGrid::Render (SPCanvasBuf *buf) // Dash pattern must use spacing from orthogonal direction. // Offset is to center dash on orthogonal lines. - double offset = fmod( signed_distance( x[0], orth ), sw[dim].length()); - if (Geom::cross( axis.vector(), orth.vector() ) > 0 ) { + double offset = fmod(signed_distance(x[0], orth), sw[dim].length()); + if (Geom::cross(axis.vector(), orth.vector()) > 0) { offset = -offset; } @@ -1006,7 +981,7 @@ CanvasXYGrid::Render (SPCanvasBuf *buf) if (!scaled[dim] && (j % empspacing) != 0) { // Minor lines dashes[0] = 1; - dashes[1] = dash -1; + dashes[1] = dash - 1; offset -= 0.5; ink_cairo_set_source_rgba32(buf->ct, _colordot); } else { @@ -1021,14 +996,13 @@ CanvasXYGrid::Render (SPCanvasBuf *buf) cairo_set_dash(buf->ct, dashes, 2, -offset); } else { - // Solid lines // Set color if (!scaled[dim] && (j % empspacing) != 0) { - ink_cairo_set_source_rgba32(buf->ct, _color ); + ink_cairo_set_source_rgba32(buf->ct, _color); } else { - ink_cairo_set_source_rgba32(buf->ct, _empcolor ); + ink_cairo_set_source_rgba32(buf->ct, _empcolor); } } @@ -1043,7 +1017,8 @@ CanvasXYGrid::Render (SPCanvasBuf *buf) cairo_restore(buf->ct); } -CanvasXYGridSnapper::CanvasXYGridSnapper(CanvasXYGrid *grid, SnapManager *sm, Geom::Coord const d) : LineSnapper(sm, d) +CanvasXYGridSnapper::CanvasXYGridSnapper(CanvasXYGrid *grid, SnapManager *sm, Geom::Coord const d) + : LineSnapper(sm, d) { this->grid = grid; } @@ -1054,26 +1029,25 @@ CanvasXYGridSnapper::CanvasXYGridSnapper(CanvasXYGrid *grid, SnapManager *sm, Ge Geom::Coord CanvasXYGridSnapper::getSnapperTolerance() const { SPDesktop const *dt = _snapmanager->getDesktop(); - double const zoom = dt ? dt->current_zoom() : 1; + double const zoom = dt ? dt->current_zoom() : 1; return _snapmanager->snapprefs.getGridTolerance() / zoom; } bool CanvasXYGridSnapper::getSnapperAlwaysSnap() const { - return _snapmanager->snapprefs.getGridTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp + return _snapmanager->snapprefs.getGridTolerance() == + 10000; // TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp } -LineSnapper::LineList -CanvasXYGridSnapper::_getSnapLines(Geom::Point const &p) const +LineSnapper::LineList CanvasXYGridSnapper::_getSnapLines(Geom::Point const &p) const { LineList s; - if ( grid == nullptr ) { + if (grid == nullptr) { return s; } for (unsigned int i = 0; i < 2; ++i) { - double spacing; if (getSnapVisibleOnly()) { @@ -1092,7 +1066,7 @@ CanvasXYGridSnapper::_getSnapLines(Geom::Point const &p) const Geom::Coord rounded; Geom::Point point_on_line; - Geom::Point cvec(0.,0.); + Geom::Point cvec(0., 0.); cvec[i] = 1.; rounded = Inkscape::Util::round_to_upper_multiple_plus(p[i], spacing, grid->origin[i]); @@ -1107,21 +1081,33 @@ CanvasXYGridSnapper::_getSnapLines(Geom::Point const &p) const return s; } -void CanvasXYGridSnapper::_addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, Geom::Point const &normal_to_line, Geom::Point const &point_on_line) const +void CanvasXYGridSnapper::_addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, Geom::Point const &normal_to_line, + Geom::Point const &point_on_line) const { - SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, source, source_num, Inkscape::SNAPTARGET_GRID, getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line); + SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, source, source_num, Inkscape::SNAPTARGET_GRID, + getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line); isr.grid_lines.push_back(dummy); } -void CanvasXYGridSnapper::_addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const +void CanvasXYGridSnapper::_addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, bool constrained_snap) const { - SnappedPoint dummy = SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GRID, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); + SnappedPoint dummy = SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GRID, snapped_distance, + getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); isr.points.push_back(dummy); } -void CanvasXYGridSnapper::_addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const +void CanvasXYGridSnapper::_addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, + bool constrained_snap) const { - SnappedPoint dummy = SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GRID_PERPENDICULAR, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); + SnappedPoint dummy = + SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GRID_PERPENDICULAR, snapped_distance, + getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); isr.points.push_back(dummy); } @@ -1135,7 +1121,6 @@ bool CanvasXYGridSnapper::ThisSnapperMightSnap() const } // namespace Inkscape - /* Local Variables: mode:c++ diff --git a/src/display/canvas-grid.h b/src/display/canvas-grid.h index 73fe587cef1735c975a97686c27aaebda6797543..1b0f5c40dd9b1a3f5df7f698eb4af0f57c52b4d3 100644 --- a/src/display/canvas-grid.h +++ b/src/display/canvas-grid.h @@ -13,19 +13,19 @@ #ifndef INKSCAPE_CANVAS_GRID_H #define INKSCAPE_CANVAS_GRID_H +#include "line-snapper.h" #include "sp-canvas-item.h" #include "ui/widget/alignment-selector.h" #include "ui/widget/registered-widget.h" #include "ui/widget/registry.h" -#include "line-snapper.h" -class SPDesktop; +class SPDesktop; class SPNamedView; struct SPCanvasBuf; -class SPDocument; +class SPDocument; namespace Gtk { - class Widget; +class Widget; } namespace Inkscape { @@ -39,17 +39,19 @@ namespace Util { class Unit; } -enum GridType { +enum GridType +{ GRID_RECTANGULAR = 0, GRID_AXONOMETRIC = 1 }; #define GRID_MAXTYPENR 1 -#define INKSCAPE_TYPE_GRID_CANVASITEM (Inkscape::grid_canvasitem_get_type ()) -#define INKSCAPE_GRID_CANVASITEM(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), INKSCAPE_TYPE_GRID_CANVASITEM, GridCanvasItem)) -#define INKSCAPE_GRID_CANVASITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), INKSCAPE_TYPE_GRID_CANVASITEM, GridCanvasItem)) -#define INKSCAPE_IS_GRID_CANVASITEM(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), INKSCAPE_TYPE_GRID_CANVASITEM)) -#define INKSCAPE_IS_GRID_CANVASITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), INKSCAPE_TYPE_GRID_CANVASITEM)) +#define INKSCAPE_TYPE_GRID_CANVASITEM (Inkscape::grid_canvasitem_get_type()) +#define INKSCAPE_GRID_CANVASITEM(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), INKSCAPE_TYPE_GRID_CANVASITEM, GridCanvasItem)) +#define INKSCAPE_GRID_CANVASITEM_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass), INKSCAPE_TYPE_GRID_CANVASITEM, GridCanvasItem)) +#define INKSCAPE_IS_GRID_CANVASITEM(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), INKSCAPE_TYPE_GRID_CANVASITEM)) +#define INKSCAPE_IS_GRID_CANVASITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), INKSCAPE_TYPE_GRID_CANVASITEM)) #define GRID_DEFAULT_COLOR 0x3F3FFF20 #define GRID_DEFAULT_EMPCOLOR 0x3F3FFF40 @@ -57,77 +59,80 @@ enum GridType { class CanvasGrid; /** All the variables that are tracked for a grid specific canvas item. */ -struct GridCanvasItem : public SPCanvasItem{ +struct GridCanvasItem : public SPCanvasItem +{ CanvasGrid *grid; // the owning grid object }; -struct GridCanvasItemClass { +struct GridCanvasItemClass +{ SPCanvasItemClass parent_class; }; /* Standard Gtk function */ -GType grid_canvasitem_get_type (); - +GType grid_canvasitem_get_type(); - -class CanvasGrid { +class CanvasGrid +{ public: virtual ~CanvasGrid(); // TODO: see effect.h and effect.cpp from live_effects how to link enums to SVGname to typename properly. (johan) - const char * getName() const; - const char * getSVGName() const; - GridType getGridType() const; - static const char * getName(GridType type); - static const char * getSVGName(GridType type); - static GridType getGridTypeFromSVGName(const char * typestr); - static GridType getGridTypeFromName(const char * typestr); + const char *getName() const; + const char *getSVGName() const; + GridType getGridType() const; + static const char *getName(GridType type); + static const char *getSVGName(GridType type); + static GridType getGridTypeFromSVGName(const char *typestr); + static GridType getGridTypeFromName(const char *typestr); - static CanvasGrid* NewGrid(SPNamedView * nv, Inkscape::XML::Node * repr, SPDocument *doc, GridType gridtype); - static void writeNewGridToRepr(Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype); + static CanvasGrid *NewGrid(SPNamedView *nv, Inkscape::XML::Node *repr, SPDocument *doc, GridType gridtype); + static void writeNewGridToRepr(Inkscape::XML::Node *repr, SPDocument *doc, GridType gridtype); - GridCanvasItem * createCanvasItem(SPDesktop * desktop); + GridCanvasItem *createCanvasItem(SPDesktop *desktop); - virtual void Update (Geom::Affine const &affine, unsigned int flags) = 0; - virtual void Render (SPCanvasBuf *buf) = 0; + virtual void Update(Geom::Affine const &affine, unsigned int flags) = 0; + virtual void Render(SPCanvasBuf *buf) = 0; virtual void readRepr() = 0; - virtual void onReprAttrChanged (Inkscape::XML::Node * /*repr*/, char const */*key*/, char const */*oldval*/, char const */*newval*/, bool /*is_interactive*/) = 0; + virtual void onReprAttrChanged(Inkscape::XML::Node * /*repr*/, char const * /*key*/, char const * /*oldval*/, + char const * /*newval*/, bool /*is_interactive*/) = 0; - Gtk::Widget * newWidget(); + Gtk::Widget *newWidget(); void setOrigin(Geom::Point const &origin_px); /**< writes new origin (specified in px units) to SVG */ - Geom::Point origin; /**< Origin of the grid */ + Geom::Point origin; /**< Origin of the grid */ - guint32 color; /**< Color for normal lines */ - guint32 empcolor; /**< Color for emphasis lines */ - gint empspacing; /**< Spacing between emphasis lines */ + guint32 color; /**< Color for normal lines */ + guint32 empcolor; /**< Color for emphasis lines */ + gint empspacing; /**< Spacing between emphasis lines */ - Inkscape::Util::Unit const* gridunit; /**< points to Unit object in UnitTable (so don't delete it) */ + Inkscape::Util::Unit const *gridunit; /**< points to Unit object in UnitTable (so don't delete it) */ - Inkscape::XML::Node * repr; + Inkscape::XML::Node *repr; SPDocument *doc; - Inkscape::Snapper* snapper; + Inkscape::Snapper *snapper; - static void on_repr_attr_changed (Inkscape::XML::Node * repr, const gchar *key, const gchar *oldval, const gchar *newval, bool is_interactive, void * data); + static void on_repr_attr_changed(Inkscape::XML::Node *repr, const gchar *key, const gchar *oldval, + const gchar *newval, bool is_interactive, void *data); bool isLegacy() const { return legacy; } bool isPixel() const { return pixel; } - bool isVisible() const { return (isEnabled() &&visible); }; + bool isVisible() const { return (isEnabled() && visible); }; bool isEnabled() const; void align_clicked(int align); protected: - CanvasGrid(SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument *in_doc, GridType type); + CanvasGrid(SPNamedView *nv, Inkscape::XML::Node *in_repr, SPDocument *in_doc, GridType type); - virtual Gtk::Widget * newSpecificWidget() = 0; + virtual Gtk::Widget *newSpecificWidget() = 0; - std::vector canvasitems; // list of created canvasitems + std::vector canvasitems; // list of created canvasitems - SPNamedView * namedview; + SPNamedView *namedview; Inkscape::UI::Widget::Registry _wr; bool visible; @@ -143,39 +148,40 @@ protected: Inkscape::UI::Widget::RegisteredCheckButton *_rcb_snap_visible_only = nullptr; Inkscape::UI::Widget::RegisteredCheckButton *_rcb_visible = nullptr; Inkscape::UI::Widget::RegisteredCheckButton *_rcb_dotted = nullptr; - Inkscape::UI::Widget::AlignmentSelector *_as_alignment = nullptr; + Inkscape::UI::Widget::AlignmentSelector *_as_alignment = nullptr; private: - CanvasGrid(const CanvasGrid&) = delete; - CanvasGrid& operator=(const CanvasGrid&) = delete; + CanvasGrid(const CanvasGrid &) = delete; + CanvasGrid &operator=(const CanvasGrid &) = delete; }; - -class CanvasXYGrid : public CanvasGrid { +class CanvasXYGrid : public CanvasGrid +{ public: - CanvasXYGrid(SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument * in_doc); + CanvasXYGrid(SPNamedView *nv, Inkscape::XML::Node *in_repr, SPDocument *in_doc); ~CanvasXYGrid() override; - virtual void Scale (Geom::Scale const &scale); - void Update (Geom::Affine const &affine, unsigned int flags) override; - void Render (SPCanvasBuf *buf) override; + virtual void Scale(Geom::Scale const &scale); + void Update(Geom::Affine const &affine, unsigned int flags) override; + void Render(SPCanvasBuf *buf) override; void readRepr() override; - void onReprAttrChanged (Inkscape::XML::Node * repr, char const *key, char const *oldval, char const *newval, bool is_interactive) override; + void onReprAttrChanged(Inkscape::XML::Node *repr, char const *key, char const *oldval, char const *newval, + bool is_interactive) override; Geom::Point spacing; /**< Spacing between elements of the grid */ - bool scaled[2]; /**< Whether the grid is in scaled mode, which can - be different in the X or Y direction, hence two - variables */ + bool scaled[2]; /**< Whether the grid is in scaled mode, which can + be different in the X or Y direction, hence two + variables */ Geom::Point ow; /**< Transformed origin by the affine for the zoom */ Geom::Point sw[2]; /**< Transformed spacing by the affine for the zoom */ protected: - Gtk::Widget * newSpecificWidget() override; + Gtk::Widget *newSpecificWidget() override; private: - CanvasXYGrid(const CanvasXYGrid&) = delete; - CanvasXYGrid& operator=(const CanvasXYGrid&) = delete; + CanvasXYGrid(const CanvasXYGrid &) = delete; + CanvasXYGrid &operator=(const CanvasXYGrid &) = delete; void updateWidgets(); @@ -189,28 +195,30 @@ private: Inkscape::UI::Widget::RegisteredSuffixedInteger *_rsi = nullptr; }; - - class CanvasXYGridSnapper : public LineSnapper { public: CanvasXYGridSnapper(CanvasXYGrid *grid, SnapManager *sm, Geom::Coord const d); bool ThisSnapperMightSnap() const override; - Geom::Coord getSnapperTolerance() const override; //returns the tolerance of the snapper in screen pixels (i.e. independent of zoom) - bool getSnapperAlwaysSnap() const override; //if true, then the snapper will always snap, regardless of its tolerance + Geom::Coord getSnapperTolerance() const override; // returns the tolerance of the snapper in screen pixels (i.e. + // independent of zoom) + bool getSnapperAlwaysSnap() const override; // if true, then the snapper will always snap, regardless of its + // tolerance private: LineList _getSnapLines(Geom::Point const &p) const override; - void _addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, Geom::Point const &normal_to_line, const Geom::Point &point_on_line) const override; - void _addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const override; - void _addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const override; + void _addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, Geom::Point const &normal_to_line, + const Geom::Point &point_on_line) const override; + void _addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, bool constrained_snap) const override; + void _addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, bool constrained_snap) const override; CanvasXYGrid *grid; }; }; /* namespace Inkscape */ - - - #endif diff --git a/src/display/canvas-rotate.cpp b/src/display/canvas-rotate.cpp index d54bbb85a083af63261b7399a543207b3b1c5ccc..b479fa998f6d9c5275464a188fa313268f88d7d6 100644 --- a/src/display/canvas-rotate.cpp +++ b/src/display/canvas-rotate.cpp @@ -10,39 +10,36 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include <2geom/point.h> -#include <2geom/rect.h> - #include "canvas-rotate.h" -#include "inkscape.h" -#include "desktop.h" +#include <2geom/point.h> +#include <2geom/rect.h> +#include #include "cairo-utils.h" - +#include "desktop.h" +#include "inkscape.h" #include "ui/event-debug.h" #include "ui/widget/canvas.h" - namespace { -static void sp_canvas_rotate_destroy(SPCanvasItem *item); -static int sp_canvas_rotate_event (SPCanvasItem *item, GdkEvent *event); +static void sp_canvas_rotate_destroy(SPCanvasItem *item); +static int sp_canvas_rotate_event(SPCanvasItem *item, GdkEvent *event); } // namespace -void sp_canvas_rotate_paint (SPCanvasRotate *canvas_rotate, cairo_surface_t *background); +void sp_canvas_rotate_paint(SPCanvasRotate *canvas_rotate, cairo_surface_t *background); G_DEFINE_TYPE(SPCanvasRotate, sp_canvas_rotate, SP_TYPE_CANVAS_ITEM); -static void sp_canvas_rotate_class_init (SPCanvasRotateClass *klass) +static void sp_canvas_rotate_class_init(SPCanvasRotateClass *klass) { klass->destroy = sp_canvas_rotate_destroy; - klass->event = sp_canvas_rotate_event; + klass->event = sp_canvas_rotate_event; } -static void sp_canvas_rotate_init (SPCanvasRotate *rotate) +static void sp_canvas_rotate_init(SPCanvasRotate *rotate) { rotate->pickable = true; // So we can receive events. rotate->angle = 0.0; @@ -54,34 +51,33 @@ static void sp_canvas_rotate_init (SPCanvasRotate *rotate) } namespace { -static void sp_canvas_rotate_destroy (SPCanvasItem *object) +static void sp_canvas_rotate_destroy(SPCanvasItem *object) { - g_return_if_fail (object != nullptr); - g_return_if_fail (SP_IS_CANVAS_ROTATE (object)); + g_return_if_fail(object != nullptr); + g_return_if_fail(SP_IS_CANVAS_ROTATE(object)); if (SP_CANVAS_ITEM_CLASS(sp_canvas_rotate_parent_class)->destroy) { SP_CANVAS_ITEM_CLASS(sp_canvas_rotate_parent_class)->destroy(object); } } -static int sp_canvas_rotate_event (SPCanvasItem *item, GdkEvent *event) +static int sp_canvas_rotate_event(SPCanvasItem *item, GdkEvent *event) { SPCanvasRotate *cr = SP_CANVAS_ROTATE(item); -// ui_dump_event (event, Glib::ustring("sp_canvas_rotate_event")); + // ui_dump_event (event, Glib::ustring("sp_canvas_rotate_event")); SPDesktop *desktop = SP_ACTIVE_DESKTOP; Geom::Rect viewbox = desktop->canvas->get_area_world(); cr->center = viewbox.midpoint(); switch (event->type) { - case GDK_MOTION_NOTIFY: - { - Geom::Point cursor( event->motion.x, event->motion.y ); + case GDK_MOTION_NOTIFY: { + Geom::Point cursor(event->motion.x, event->motion.y); // Both cursor and center are in window coordinates - Geom::Point rcursor( cursor - cr->center ); - double angle = Geom::deg_from_rad( Geom::atan2(rcursor) ); + Geom::Point rcursor(cursor - cr->center); + double angle = Geom::deg_from_rad(Geom::atan2(rcursor)); // Set start angle if (cr->start_angle < -360) { @@ -92,11 +88,10 @@ static int sp_canvas_rotate_event (SPCanvasItem *item, GdkEvent *event) double delta_angle = cr->start_angle - angle; - if (event->motion.state & GDK_SHIFT_MASK && - event->motion.state & GDK_CONTROL_MASK) { + if (event->motion.state & GDK_SHIFT_MASK && event->motion.state & GDK_CONTROL_MASK) { delta_angle = 0; } else if (event->motion.state & GDK_SHIFT_MASK) { - delta_angle = round(delta_angle/rotation_snap) * rotation_snap; + delta_angle = round(delta_angle / rotation_snap) * rotation_snap; } else if (event->motion.state & GDK_CONTROL_MASK) { // ? } else if (event->motion.state & GDK_MOD1_MASK) { @@ -109,32 +104,31 @@ static int sp_canvas_rotate_event (SPCanvasItem *item, GdkEvent *event) // Correct line for snapping of angle double distance = rcursor.length(); - cr->cursor = Geom::Point::polar( Geom::rad_from_deg(angle), distance ); + cr->cursor = Geom::Point::polar(Geom::rad_from_deg(angle), distance); // Update screen // sp_canvas_item_request_update( item ); auto backing_store = item->canvas->get_backing_store(); - sp_canvas_rotate_paint (cr, backing_store->cobj()); + sp_canvas_rotate_paint(cr, backing_store->cobj()); break; } case GDK_BUTTON_RELEASE: // Rotate the actual canvas - desktop->rotate_relative_center_point (desktop->w2d(cr->center), - (desktop->w2d().det() > 0 ? -1 : 1) * - Geom::rad_from_deg(cr->angle) ); + desktop->rotate_relative_center_point(desktop->w2d(cr->center), + (desktop->w2d().det() > 0 ? -1 : 1) * Geom::rad_from_deg(cr->angle)); // We're done - sp_canvas_item_ungrab (item); - sp_canvas_item_hide (item); + sp_canvas_item_ungrab(item); + sp_canvas_item_hide(item); cr->start_angle = -1000; if (cr->surface_copy != nullptr) { - cairo_surface_destroy( cr->surface_copy ); + cairo_surface_destroy(cr->surface_copy); cr->surface_copy = nullptr; } if (cr->surface_rotated != nullptr) { - cairo_surface_destroy( cr->surface_rotated ); + cairo_surface_destroy(cr->surface_rotated); cr->surface_rotated = nullptr; } // sp_canvas_item_show (desktop->drawing); @@ -151,14 +145,15 @@ static int sp_canvas_rotate_event (SPCanvasItem *item, GdkEvent *event) break; } - if (event->type == GDK_KEY_PRESS) return false; + if (event->type == GDK_KEY_PRESS) + return false; return true; } } // namespace -void sp_canvas_rotate_start (SPCanvasRotate *canvas_rotate, cairo_surface_t *background) +void sp_canvas_rotate_start(SPCanvasRotate *canvas_rotate, cairo_surface_t *background) { if (background == nullptr) { std::cerr << "sp_canvas_rotate_start: background is NULL!" << std::endl; @@ -168,35 +163,35 @@ void sp_canvas_rotate_start (SPCanvasRotate *canvas_rotate, cairo_surface_t *bac canvas_rotate->angle = 0.0; // Copy current background - canvas_rotate->surface_copy = ink_cairo_surface_copy( background ); + canvas_rotate->surface_copy = ink_cairo_surface_copy(background); // Paint canvas with background... since we are hiding drawing. - sp_canvas_item_request_update( canvas_rotate ); + sp_canvas_item_request_update(canvas_rotate); } // Paint the canvas ourselves for speed.... -void sp_canvas_rotate_paint (SPCanvasRotate *canvas_rotate, cairo_surface_t *background) +void sp_canvas_rotate_paint(SPCanvasRotate *canvas_rotate, cairo_surface_t *background) { if (background == nullptr) { std::cerr << "sp_canvas_rotate_paint: background is NULL!" << std::endl; return; } - double width = cairo_image_surface_get_width (background); - double height = cairo_image_surface_get_height (background); + double width = cairo_image_surface_get_width(background); + double height = cairo_image_surface_get_height(background); // Draw rotated canvas - cairo_t *context = cairo_create( background ); - - cairo_save (context); - cairo_set_operator( context, CAIRO_OPERATOR_SOURCE ); - cairo_translate( context, width/2.0, height/2.0 ); - cairo_rotate( context, Geom::rad_from_deg(-canvas_rotate->angle) ); - cairo_translate( context, -width/2.0, -height/2.0 ); - cairo_set_source_surface( context, canvas_rotate->surface_copy, 0, 0 ); - cairo_paint( context ); - cairo_restore( context ); - cairo_destroy( context ); + cairo_t *context = cairo_create(background); + + cairo_save(context); + cairo_set_operator(context, CAIRO_OPERATOR_SOURCE); + cairo_translate(context, width / 2.0, height / 2.0); + cairo_rotate(context, Geom::rad_from_deg(-canvas_rotate->angle)); + cairo_translate(context, -width / 2.0, -height / 2.0); + cairo_set_source_surface(context, canvas_rotate->surface_copy, 0, 0); + cairo_paint(context); + cairo_restore(context); + cairo_destroy(context); canvas_rotate->canvas->queue_draw(); } diff --git a/src/display/canvas-rotate.h b/src/display/canvas-rotate.h index 3eb38e5a65c7723ac4c08cd259dd576724ed0978..60bdc2e1161bbe9ebaf8d08fa22bae357cb5f729 100644 --- a/src/display/canvas-rotate.h +++ b/src/display/canvas-rotate.h @@ -13,30 +13,34 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "sp-canvas-item.h" #include <2geom/point.h> #include -class SPItem; +#include "sp-canvas-item.h" -#define SP_TYPE_CANVAS_ROTATE (sp_canvas_rotate_get_type ()) -#define SP_CANVAS_ROTATE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SP_TYPE_CANVAS_ROTATE, SPCanvasRotate)) -#define SP_IS_CANVAS_ROTATE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SP_TYPE_CANVAS_ROTATE)) +class SPItem; -struct SPCanvasRotate : public SPCanvasItem { - Geom::Point center; // Center of screen - Geom::Point cursor; // Position of cursor relative to center (after angle snapping) - double angle; // Rotation angle in degrees - double start_angle; // Starting angle of cursor - cairo_surface_t *surface_copy; // Copy of original surface +#define SP_TYPE_CANVAS_ROTATE (sp_canvas_rotate_get_type()) +#define SP_CANVAS_ROTATE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CANVAS_ROTATE, SPCanvasRotate)) +#define SP_IS_CANVAS_ROTATE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CANVAS_ROTATE)) + +struct SPCanvasRotate : public SPCanvasItem +{ + Geom::Point center; // Center of screen + Geom::Point cursor; // Position of cursor relative to center (after angle snapping) + double angle; // Rotation angle in degrees + double start_angle; // Starting angle of cursor + cairo_surface_t *surface_copy; // Copy of original surface cairo_surface_t *surface_rotated; // Copy of original surface, rotated }; -void sp_canvas_rotate_start( SPCanvasRotate *canvas_rotate, cairo_surface_t *background ); +void sp_canvas_rotate_start(SPCanvasRotate *canvas_rotate, cairo_surface_t *background); -GType sp_canvas_rotate_get_type (); +GType sp_canvas_rotate_get_type(); -struct SPCanvasRotateClass : public SPCanvasItemClass{}; +struct SPCanvasRotateClass : public SPCanvasItemClass +{ +}; #endif // SEEN_SP_CANVAS_ROTATE_H diff --git a/src/display/canvas-temporary-item-list.cpp b/src/display/canvas-temporary-item-list.cpp index caa960969981bf442bb30864cf8a82b634bef3ff..85f0f56ee1ddcdb3eda784c778fc3c9561eca99c 100644 --- a/src/display/canvas-temporary-item-list.cpp +++ b/src/display/canvas-temporary-item-list.cpp @@ -11,17 +11,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "display/canvas-temporary-item.h" #include "display/canvas-temporary-item-list.h" +#include "display/canvas-temporary-item.h" + namespace Inkscape { namespace Display { TemporaryItemList::TemporaryItemList(SPDesktop *desktop) : desktop(desktop) -{ - -} +{} TemporaryItemList::~TemporaryItemList() { @@ -32,24 +31,23 @@ TemporaryItemList::~TemporaryItemList() itemlist.clear(); } -/* Note that TemporaryItem or TemporaryItemList is responsible for deletion and such, so this return pointer can safely be ignored. */ -TemporaryItem * -TemporaryItemList::add_item(SPCanvasItem *item, unsigned int lifetime) +/* Note that TemporaryItem or TemporaryItemList is responsible for deletion and such, so this return pointer can safely + * be ignored. */ +TemporaryItem *TemporaryItemList::add_item(SPCanvasItem *item, unsigned int lifetime) { // beware of strange things happening due to very short timeouts - TemporaryItem * tempitem = new TemporaryItem(item, lifetime); + TemporaryItem *tempitem = new TemporaryItem(item, lifetime); itemlist.push_back(tempitem); - tempitem->signal_timeout.connect( sigc::mem_fun(*this, &TemporaryItemList::_item_timeout) ); + tempitem->signal_timeout.connect(sigc::mem_fun(*this, &TemporaryItemList::_item_timeout)); return tempitem; } -void -TemporaryItemList::delete_item( TemporaryItem * tempitem ) +void TemporaryItemList::delete_item(TemporaryItem *tempitem) { // check if the item is in the list, if so, delete it. (in other words, don't wait for the item to delete itself) bool in_list = false; - for (auto & it : itemlist) { - if ( it == tempitem ) { + for (auto &it : itemlist) { + if (it == tempitem) { in_list = true; break; } @@ -60,14 +58,13 @@ TemporaryItemList::delete_item( TemporaryItem * tempitem ) } } -void -TemporaryItemList::_item_timeout(TemporaryItem * tempitem) +void TemporaryItemList::_item_timeout(TemporaryItem *tempitem) { itemlist.remove(tempitem); // no need to delete the item, it does that itself after signal_timeout.emit() completes } -} //namespace Display +} // namespace Display } /* namespace Inkscape */ /* diff --git a/src/display/canvas-temporary-item-list.h b/src/display/canvas-temporary-item-list.h index 4681c592f716e79684fcf3dd072e560604b13f05..5add551213b77b18a988effba5f5f2221284dc19 100644 --- a/src/display/canvas-temporary-item-list.h +++ b/src/display/canvas-temporary-item-list.h @@ -24,28 +24,29 @@ class TemporaryItem; /** * Provides a class that can contain active TemporaryItem[s] on a desktop. */ -class TemporaryItemList { +class TemporaryItemList +{ public: TemporaryItemList(SPDesktop *desktop); virtual ~TemporaryItemList(); - TemporaryItem* add_item (SPCanvasItem *item, unsigned int lifetime); - void delete_item (TemporaryItem * tempitem); + TemporaryItem *add_item(SPCanvasItem *item, unsigned int lifetime); + void delete_item(TemporaryItem *tempitem); protected: - SPDesktop *desktop; /** Desktop we are on. */ + SPDesktop *desktop; /** Desktop we are on. */ - std::list itemlist; /** list of temp items */ + std::list itemlist; /** list of temp items */ - void _item_timeout (TemporaryItem * tempitem); + void _item_timeout(TemporaryItem *tempitem); private: - TemporaryItemList(const TemporaryItemList&) = delete; - TemporaryItemList& operator=(const TemporaryItemList&) = delete; + TemporaryItemList(const TemporaryItemList &) = delete; + TemporaryItemList &operator=(const TemporaryItemList &) = delete; }; -} //namespace Display -} //namespace Inkscape +} // namespace Display +} // namespace Inkscape #endif diff --git a/src/display/canvas-temporary-item.cpp b/src/display/canvas-temporary-item.cpp index 38266872bdea6ac167500bf904458395f21e32b1..f46ec83db8cc724e9b443c26fe0ca971bc8618cc 100644 --- a/src/display/canvas-temporary-item.cpp +++ b/src/display/canvas-temporary-item.cpp @@ -18,6 +18,7 @@ #include "display/canvas-temporary-item.h" #include + #include "display/sp-canvas-item.h" namespace Inkscape { @@ -26,12 +27,12 @@ namespace Display { /** lifetime is measured in milliseconds */ TemporaryItem::TemporaryItem(SPCanvasItem *item, guint lifetime, bool deselect_destroy) - : canvasitem(item), - timeout_id(0), - destroy_on_deselect(deselect_destroy) + : canvasitem(item) + , timeout_id(0) + , destroy_on_deselect(deselect_destroy) { if (lifetime > 0 && destroy_on_deselect) { - g_print ("Warning: lifetime should be 0 when destroy_on_deselect is true\n"); + g_print("Warning: lifetime should be 0 when destroy_on_deselect is true\n"); lifetime = 0; } // zero lifetime means stay forever, so do not add timeout event. @@ -56,7 +57,8 @@ TemporaryItem::~TemporaryItem() } /* static method */ -int TemporaryItem::_timeout(void* data) { +int TemporaryItem::_timeout(void *data) +{ TemporaryItem *tempitem = static_cast(data); tempitem->timeout_id = 0; tempitem->signal_timeout.emit(tempitem); @@ -64,8 +66,7 @@ int TemporaryItem::_timeout(void* data) { return FALSE; } - -} //namespace Display +} // namespace Display } /* namespace Inkscape */ /* diff --git a/src/display/canvas-temporary-item.h b/src/display/canvas-temporary-item.h index 4e60e4333d3b8d4d6b88c4f4a87603c2fee96fc4..1d92a0d7fbb694b662ab579b2f35fa6ca3f7a19b 100644 --- a/src/display/canvas-temporary-item.h +++ b/src/display/canvas-temporary-item.h @@ -11,7 +11,6 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include struct SPCanvasItem; @@ -22,28 +21,29 @@ namespace Display { /** * Provides a class to put a canvasitem temporarily on-canvas. */ -class TemporaryItem { +class TemporaryItem +{ public: TemporaryItem(SPCanvasItem *item, unsigned int lifetime, bool destroy_on_deselect = false); virtual ~TemporaryItem(); - TemporaryItem(const TemporaryItem&) = delete; - TemporaryItem& operator=(const TemporaryItem&) = delete; + TemporaryItem(const TemporaryItem &) = delete; + TemporaryItem &operator=(const TemporaryItem &) = delete; sigc::signal signal_timeout; protected: friend class TemporaryItemList; - SPCanvasItem * canvasitem; /** The item we are holding on to */ - unsigned int timeout_id; /** ID by which glib knows the timeout event */ + SPCanvasItem *canvasitem; /** The item we are holding on to */ + unsigned int timeout_id; /** ID by which glib knows the timeout event */ bool destroy_on_deselect; // only destroy when parent item is deselected, not when mouse leaves - static int _timeout(void* data); ///< callback for when lifetime expired + static int _timeout(void *data); ///< callback for when lifetime expired }; -} //namespace Display -} //namespace Inkscape +} // namespace Display +} // namespace Inkscape #endif diff --git a/src/display/canvas-text.cpp b/src/display/canvas-text.cpp index 3c155f6531d62b3c1104dd5b5d6e1738f8aeda96..493a8fe4efe982ccde246de1608f136a68c47d22 100644 --- a/src/display/canvas-text.cpp +++ b/src/display/canvas-text.cpp @@ -13,21 +13,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include - -#include "sp-canvas-util.h" #include "canvas-text.h" -#include "display/cairo-utils.h" -#include "desktop.h" -#include "ui/widget/canvas.h" // Request redraw +#include +#include +#include "desktop.h" +#include "display/cairo-utils.h" +#include "sp-canvas-util.h" +#include "ui/widget/canvas.h" // Request redraw static void sp_canvastext_destroy(SPCanvasItem *object); -static void sp_canvastext_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); -static void sp_canvastext_render (SPCanvasItem *item, SPCanvasBuf *buf); +static void sp_canvastext_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); +static void sp_canvastext_render(SPCanvasItem *item, SPCanvasBuf *buf); G_DEFINE_TYPE(SPCanvasText, sp_canvastext, SP_TYPE_CANVAS_ITEM); @@ -40,8 +39,7 @@ static void sp_canvastext_class_init(SPCanvasTextClass *klass) item_class->render = sp_canvastext_render; } -static void -sp_canvastext_init (SPCanvasText *canvastext) +static void sp_canvastext_init(SPCanvasText *canvastext) { canvastext->anchor_position = TEXT_ANCHOR_CENTER; canvastext->anchor_pos_x_manual = 0; @@ -60,17 +58,18 @@ sp_canvastext_init (SPCanvasText *canvastext) canvastext->text = nullptr; canvastext->outline = false; canvastext->background = false; - canvastext->border = 3; // must be a constant, and not proportional to any width, height, or fontsize to allow alignment with other text boxes + canvastext->border = 3; // must be a constant, and not proportional to any width, height, or fontsize to allow + // alignment with other text boxes canvastext->name = "CanvasText"; } static void sp_canvastext_destroy(SPCanvasItem *object) { - g_return_if_fail (object != nullptr); - g_return_if_fail (SP_IS_CANVASTEXT (object)); + g_return_if_fail(object != nullptr); + g_return_if_fail(SP_IS_CANVASTEXT(object)); - SPCanvasText *canvastext = SP_CANVASTEXT (object); + SPCanvasText *canvastext = SP_CANVASTEXT(object); g_free(canvastext->text); canvastext->text = nullptr; @@ -80,10 +79,9 @@ static void sp_canvastext_destroy(SPCanvasItem *object) SP_CANVAS_ITEM_CLASS(sp_canvastext_parent_class)->destroy(object); } -static void -sp_canvastext_render (SPCanvasItem *item, SPCanvasBuf *buf) +static void sp_canvastext_render(SPCanvasItem *item, SPCanvasBuf *buf) { - SPCanvasText *cl = SP_CANVASTEXT (item); + SPCanvasText *cl = SP_CANVASTEXT(item); if (!buf->ct) return; @@ -91,14 +89,12 @@ sp_canvastext_render (SPCanvasItem *item, SPCanvasBuf *buf) cairo_select_font_face(buf->ct, "sans-serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); cairo_set_font_size(buf->ct, cl->fontsize); - if (cl->background){ + if (cl->background) { cairo_text_extents_t extents; cairo_text_extents(buf->ct, cl->text, &extents); - cairo_rectangle(buf->ct, item->x1 - buf->rect.left(), - item->y1 - buf->rect.top(), - item->x2 - item->x1, - item->y2 - item->y1); + cairo_rectangle(buf->ct, item->x1 - buf->rect.left(), item->y1 - buf->rect.top(), item->x2 - item->x1, + item->y2 - item->y1); ink_cairo_set_source_rgba32(buf->ct, cl->rgba_background); cairo_fill(buf->ct); @@ -111,37 +107,37 @@ sp_canvastext_render (SPCanvasItem *item, SPCanvasBuf *buf) cairo_move_to(buf->ct, round(offsetx), round(offsety)); cairo_text_path(buf->ct, cl->text); - if (cl->outline){ + if (cl->outline) { ink_cairo_set_source_rgba32(buf->ct, cl->rgba_stroke); - cairo_set_line_width (buf->ct, 2.0); + cairo_set_line_width(buf->ct, 2.0); cairo_stroke_preserve(buf->ct); } ink_cairo_set_source_rgba32(buf->ct, cl->rgba); cairo_fill(buf->ct); } -static void -sp_canvastext_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) +static void sp_canvastext_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) { - SPCanvasText *cl = SP_CANVASTEXT (item); + SPCanvasText *cl = SP_CANVASTEXT(item); item->canvas->redraw_area((int)item->x1, (int)item->y1, (int)item->x2, (int)item->y2); if (SP_CANVAS_ITEM_CLASS(sp_canvastext_parent_class)->update) SP_CANVAS_ITEM_CLASS(sp_canvastext_parent_class)->update(item, affine, flags); - sp_canvas_item_reset_bounds (item); + sp_canvas_item_reset_bounds(item); cl->affine = affine; Geom::Point s = cl->s * affine; - // Point s specifies the position of the anchor, which is at the bounding box of the text itself (i.e. not at the border of the filled background rectangle) - // The relative position of the anchor can be set using e.g. anchor_position = TEXT_ANCHOR_LEFT + // Point s specifies the position of the anchor, which is at the bounding box of the text itself (i.e. not at the + // border of the filled background rectangle) The relative position of the anchor can be set using e.g. + // anchor_position = TEXT_ANCHOR_LEFT // Set up a temporary cairo_t to measure the text extents; it would be better to compute this in the render() // method but update() seems to be called before so we don't have the information available when we need it cairo_surface_t *tmp_surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1); - cairo_t* tmp_buf = cairo_create(tmp_surface); + cairo_t *tmp_buf = cairo_create(tmp_surface); cairo_select_font_face(tmp_buf, "sans-serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); cairo_set_font_size(tmp_buf, cl->fontsize); @@ -151,8 +147,8 @@ sp_canvastext_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned i item->x1 = s[Geom::X] + extents.x_bearing - border; item->y1 = s[Geom::Y] + extents.y_bearing - border; - item->x2 = item->x1 + extents.width + 2*border; - item->y2 = item->y1 + extents.height + 2*border; + item->x2 = item->x1 + extents.width + 2 * border; + item->y2 = item->y1 + extents.height + 2 * border; /* FROM: http://lists.cairographics.org/archives/cairo-bugs/2009-March/003014.html - Glyph surfaces: In most font rendering systems, glyph surfaces @@ -184,22 +180,21 @@ sp_canvastext_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned i // adjust update region according to anchor shift - - switch (cl->anchor_position){ + switch (cl->anchor_position) { case TEXT_ANCHOR_LEFT: cl->anchor_offset_x = 0; - cl->anchor_offset_y = -extents.height/2; + cl->anchor_offset_y = -extents.height / 2; break; case TEXT_ANCHOR_RIGHT: cl->anchor_offset_x = extents.width; - cl->anchor_offset_y = -extents.height/2; + cl->anchor_offset_y = -extents.height / 2; break; case TEXT_ANCHOR_BOTTOM: - cl->anchor_offset_x = extents.width/2; + cl->anchor_offset_x = extents.width / 2; cl->anchor_offset_y = 0; break; case TEXT_ANCHOR_TOP: - cl->anchor_offset_x = extents.width/2; + cl->anchor_offset_x = extents.width / 2; cl->anchor_offset_y = -extents.height; break; case TEXT_ANCHOR_ZERO: @@ -207,13 +202,13 @@ sp_canvastext_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned i cl->anchor_offset_y = 0; break; case TEXT_ANCHOR_MANUAL: - cl->anchor_offset_x = (1 + cl->anchor_pos_x_manual) * extents.width/2; - cl->anchor_offset_y = -(1 + cl->anchor_pos_y_manual) * extents.height/2; + cl->anchor_offset_x = (1 + cl->anchor_pos_x_manual) * extents.width / 2; + cl->anchor_offset_y = -(1 + cl->anchor_pos_y_manual) * extents.height / 2; break; case TEXT_ANCHOR_CENTER: default: - cl->anchor_offset_x = extents.width/2; - cl->anchor_offset_y = -extents.height/2; + cl->anchor_offset_x = extents.width / 2; + cl->anchor_offset_y = -extents.height / 2; break; } @@ -230,8 +225,9 @@ sp_canvastext_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned i SPCanvasText *sp_canvastext_new(SPCanvasGroup *parent, SPDesktop *desktop, Geom::Point pos, gchar const *new_text) { - // Pos specifies the position of the anchor, which is at the bounding box of the text itself (i.e. not at the border of the filled background rectangle) - // The relative position of the anchor can be set using e.g. anchor_position = TEXT_ANCHOR_LEFT + // Pos specifies the position of the anchor, which is at the bounding box of the text itself (i.e. not at the border + // of the filled background rectangle) The relative position of the anchor can be set using e.g. anchor_position = + // TEXT_ANCHOR_LEFT SPCanvasItem *item = sp_canvas_item_new(parent, SP_TYPE_CANVASTEXT, nullptr); SPCanvasText *ct = SP_CANVASTEXT(item); @@ -245,76 +241,67 @@ SPCanvasText *sp_canvastext_new(SPCanvasGroup *parent, SPDesktop *desktop, Geom: return ct; } - -void -sp_canvastext_set_rgba32 (SPCanvasText *ct, guint32 rgba, guint32 rgba_stroke) +void sp_canvastext_set_rgba32(SPCanvasText *ct, guint32 rgba, guint32 rgba_stroke) { - g_return_if_fail (ct != nullptr); - g_return_if_fail (SP_IS_CANVASTEXT (ct)); + g_return_if_fail(ct != nullptr); + g_return_if_fail(SP_IS_CANVASTEXT(ct)); if (rgba != ct->rgba || rgba_stroke != ct->rgba_stroke) { ct->rgba = rgba; ct->rgba_stroke = rgba_stroke; - SPCanvasItem *item = SP_CANVAS_ITEM (ct); - sp_canvas_item_request_update( item ); + SPCanvasItem *item = SP_CANVAS_ITEM(ct); + sp_canvas_item_request_update(item); } } #define EPSILON 1e-6 -#define DIFFER(a,b) (fabs ((a) - (b)) > EPSILON) +#define DIFFER(a, b) (fabs((a) - (b)) > EPSILON) -void -sp_canvastext_set_coords (SPCanvasText *ct, gdouble x0, gdouble y0) +void sp_canvastext_set_coords(SPCanvasText *ct, gdouble x0, gdouble y0) { sp_canvastext_set_coords(ct, Geom::Point(x0, y0)); } -void -sp_canvastext_set_coords (SPCanvasText *ct, const Geom::Point start) +void sp_canvastext_set_coords(SPCanvasText *ct, const Geom::Point start) { - g_return_if_fail (ct && ct->desktop); - g_return_if_fail (SP_IS_CANVASTEXT (ct)); - + g_return_if_fail(ct && ct->desktop); + g_return_if_fail(SP_IS_CANVASTEXT(ct)); + Geom::Point pos = ct->desktop->doc2dt(start); - if (DIFFER (pos[0], ct->s[Geom::X]) || DIFFER (pos[1], ct->s[Geom::Y])) { + if (DIFFER(pos[0], ct->s[Geom::X]) || DIFFER(pos[1], ct->s[Geom::Y])) { ct->s[Geom::X] = pos[0]; ct->s[Geom::Y] = pos[1]; - sp_canvas_item_request_update (SP_CANVAS_ITEM (ct)); + sp_canvas_item_request_update(SP_CANVAS_ITEM(ct)); } } -void -sp_canvastext_set_text (SPCanvasText *ct, gchar const * new_text) +void sp_canvastext_set_text(SPCanvasText *ct, gchar const *new_text) { - g_free (ct->text); + g_free(ct->text); ct->text = g_strdup(new_text); - sp_canvas_item_request_update (SP_CANVAS_ITEM (ct)); + sp_canvas_item_request_update(SP_CANVAS_ITEM(ct)); } -void -sp_canvastext_set_number_as_text (SPCanvasText *ct, int num) +void sp_canvastext_set_number_as_text(SPCanvasText *ct, int num) { std::ostringstream number; number << num; sp_canvastext_set_text(ct, number.str().c_str()); } -void -sp_canvastext_set_fontsize (SPCanvasText *ct, double size) +void sp_canvastext_set_fontsize(SPCanvasText *ct, double size) { ct->fontsize = size; } -void -sp_canvastext_set_anchor_manually (SPCanvasText *ct, double anchor_x, double anchor_y) +void sp_canvastext_set_anchor_manually(SPCanvasText *ct, double anchor_x, double anchor_y) { ct->anchor_pos_x_manual = anchor_x; ct->anchor_pos_y_manual = anchor_y; ct->anchor_position = TEXT_ANCHOR_MANUAL; } - /* Local Variables: mode:c++ diff --git a/src/display/canvas-text.h b/src/display/canvas-text.h index 257f360a68dc36e482b2f715d32d20a8091659aa..089e0e96d5c5b5865bababb1940234ee44ea8a89 100644 --- a/src/display/canvas-text.h +++ b/src/display/canvas-text.h @@ -20,11 +20,12 @@ class SPItem; class SPDesktop; -#define SP_TYPE_CANVASTEXT (sp_canvastext_get_type ()) -#define SP_CANVASTEXT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SP_TYPE_CANVASTEXT, SPCanvasText)) -#define SP_IS_CANVASTEXT(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SP_TYPE_CANVASTEXT)) +#define SP_TYPE_CANVASTEXT (sp_canvastext_get_type()) +#define SP_CANVASTEXT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CANVASTEXT, SPCanvasText)) +#define SP_IS_CANVASTEXT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CANVASTEXT)) -enum CanvasTextAnchorPositionEnum { +enum CanvasTextAnchorPositionEnum +{ TEXT_ANCHOR_CENTER, TEXT_ANCHOR_TOP, TEXT_ANCHOR_BOTTOM, @@ -34,8 +35,9 @@ enum CanvasTextAnchorPositionEnum { TEXT_ANCHOR_MANUAL }; -struct SPCanvasText : public SPCanvasItem { - SPItem *item; // the item to which this line belongs in some sense; may be NULL for some users +struct SPCanvasText : public SPCanvasItem +{ + SPItem *item; // the item to which this line belongs in some sense; may be NULL for some users guint32 rgba; guint32 rgba_stroke; guint32 rgba_background; @@ -43,11 +45,14 @@ struct SPCanvasText : public SPCanvasItem { bool background; double border; - SPDesktop *desktop; // the desktop to which this text is attached; needed for coordinate transforms (TODO: these should be eliminated) + SPDesktop *desktop; // the desktop to which this text is attached; needed for coordinate transforms (TODO: these + // should be eliminated) - gchar* text; - Geom::Point s; // Is the coordinate of the anchor, which is related to the rectangle filled with the background color - CanvasTextAnchorPositionEnum anchor_position; // The anchor position specifies where the anchor is with respect to the rectangle filled with the background color + gchar *text; + Geom::Point s; // Is the coordinate of the anchor, which is related to the rectangle filled with the background + // color + CanvasTextAnchorPositionEnum anchor_position; // The anchor position specifies where the anchor is with respect to + // the rectangle filled with the background color double anchor_pos_x_manual; double anchor_pos_y_manual; Geom::Affine affine; @@ -55,24 +60,24 @@ struct SPCanvasText : public SPCanvasItem { double anchor_offset_x; double anchor_offset_y; }; -struct SPCanvasTextClass : public SPCanvasItemClass{}; +struct SPCanvasTextClass : public SPCanvasItemClass +{ +}; -GType sp_canvastext_get_type (); +GType sp_canvastext_get_type(); SPCanvasText *sp_canvastext_new(SPCanvasGroup *parent, SPDesktop *desktop, Geom::Point pos, gchar const *text); -void sp_canvastext_set_rgba32 (SPCanvasText *ct, guint32 rgba, guint32 rgba_stroke); -void sp_canvastext_set_coords (SPCanvasText *ct, gdouble x0, gdouble y0); -void sp_canvastext_set_coords (SPCanvasText *ct, const Geom::Point start); -void sp_canvastext_set_text (SPCanvasText *ct, gchar const* new_text); -void sp_canvastext_set_number_as_text (SPCanvasText *ct, int num); -void sp_canvastext_set_fontsize (SPCanvasText *ct, double size); -void sp_canvastext_set_anchor_manually (SPCanvasText *ct, double anchor_x, double anchor_y); +void sp_canvastext_set_rgba32(SPCanvasText *ct, guint32 rgba, guint32 rgba_stroke); +void sp_canvastext_set_coords(SPCanvasText *ct, gdouble x0, gdouble y0); +void sp_canvastext_set_coords(SPCanvasText *ct, const Geom::Point start); +void sp_canvastext_set_text(SPCanvasText *ct, gchar const *new_text); +void sp_canvastext_set_number_as_text(SPCanvasText *ct, int num); +void sp_canvastext_set_fontsize(SPCanvasText *ct, double size); +void sp_canvastext_set_anchor_manually(SPCanvasText *ct, double anchor_x, double anchor_y); #endif // SEEN_SP_CANVASTEXT_H - - /* Local Variables: mode:c++ diff --git a/src/display/curve.cpp b/src/display/curve.cpp index ba46aa1e4ef298e2a61612f06ee9b2a2c33b49b0..d7f9d4a6026c643a0fa0513d80cff8112abcd8fb 100644 --- a/src/display/curve.cpp +++ b/src/display/curve.cpp @@ -14,12 +14,11 @@ #include "display/curve.h" -#include #include <2geom/pathvector.h> +#include <2geom/point.h> #include <2geom/sbasis-geometric.h> #include <2geom/sbasis-to-bezier.h> -#include <2geom/point.h> - +#include #include /** @@ -34,14 +33,14 @@ SPCurve::new_from_rect(Geom::Rect const &rect, bool all_four_sides) Geom::Point p = rect.corner(0); c->moveto(p); - for (int i=3; i>=1; --i) { + for (int i = 3; i >= 1; --i) { c->lineto(rect.corner(i)); } if (all_four_sides) { - // When _constrained_ snapping to a path, the 2geom::SimpleCrosser will be invoked which doesn't consider the closing segment. - // of a path. Consequently, in case we want to snap to for example the page border, we must provide all four sides of the - // rectangle explicitly + // When _constrained_ snapping to a path, the 2geom::SimpleCrosser will be invoked which doesn't consider the + // closing segment. of a path. Consequently, in case we want to snap to for example the page border, we must + // provide all four sides of the rectangle explicitly c->lineto(rect.corner(0)); } else { // ... instead of just three plus a closing segment @@ -51,19 +50,16 @@ SPCurve::new_from_rect(Geom::Rect const &rect, bool all_four_sides) return c; } -SPCurve::~SPCurve() -= default; +SPCurve::~SPCurve() = default; /* Methods */ -void -SPCurve::set_pathvector(Geom::PathVector const & new_pathv) +void SPCurve::set_pathvector(Geom::PathVector const &new_pathv) { _pathv = new_pathv; } -Geom::PathVector const & -SPCurve::get_pathvector() const +Geom::PathVector const &SPCurve::get_pathvector() const { return _pathv; } @@ -72,8 +68,7 @@ SPCurve::get_pathvector() const * Returns the number of segments of all paths summed * This count includes the closing line segment of a closed path. */ -size_t -SPCurve::get_segment_count() const +size_t SPCurve::get_segment_count() const { return _pathv.curveCount(); } @@ -128,10 +123,10 @@ SPCurve::split() const { std::list l; - for (const auto & path_it : _pathv) { + for (const auto &path_it : _pathv) { Geom::PathVector newpathv; newpathv.push_back(path_it); - SPCurve * newcurve = new SPCurve(newpathv); + SPCurve *newcurve = new SPCurve(newpathv); l.emplace_back(newcurve); } @@ -141,8 +136,7 @@ SPCurve::split() const /** * Transform all paths in curve using matrix. */ -void -SPCurve::transform(Geom::Affine const &m) +void SPCurve::transform(Geom::Affine const &m) { _pathv *= m; } @@ -151,8 +145,7 @@ SPCurve::transform(Geom::Affine const &m) * Set curve to empty curve. * In more detail: this clears the internal pathvector from all its paths. */ -void -SPCurve::reset() +void SPCurve::reset() { _pathv.clear(); } @@ -164,8 +157,7 @@ SPCurve::reset() /** * Calls SPCurve::moveto() with point made of given coordinates. */ -void -SPCurve::moveto(double x, double y) +void SPCurve::moveto(double x, double y) { moveto(Geom::Point(x, y)); } @@ -173,8 +165,7 @@ SPCurve::moveto(double x, double y) * Perform a moveto to a point, thus starting a new subpath. * Point p must be finite. */ -void -SPCurve::moveto(Geom::Point const &p) +void SPCurve::moveto(Geom::Point const &p) { Geom::Path path(p); path.setStitching(true); @@ -185,66 +176,65 @@ SPCurve::moveto(Geom::Point const &p) * Adds a line to the current subpath. * Point p must be finite. */ -void -SPCurve::lineto(Geom::Point const &p) +void SPCurve::lineto(Geom::Point const &p) { - if (_pathv.empty()) g_message("SPCurve::lineto - path is empty!"); - else _pathv.back().appendNew( p ); + if (_pathv.empty()) + g_message("SPCurve::lineto - path is empty!"); + else + _pathv.back().appendNew(p); } /** * Calls SPCurve::lineto( Geom::Point(x,y) ) */ -void -SPCurve::lineto(double x, double y) +void SPCurve::lineto(double x, double y) { - lineto(Geom::Point(x,y)); + lineto(Geom::Point(x, y)); } /** * Adds a quadratic bezier segment to the current subpath. * All points must be finite. */ -void -SPCurve::quadto(Geom::Point const &p1, Geom::Point const &p2) +void SPCurve::quadto(Geom::Point const &p1, Geom::Point const &p2) { - if (_pathv.empty()) g_message("SPCurve::quadto - path is empty!"); - else _pathv.back().appendNew( p1, p2); + if (_pathv.empty()) + g_message("SPCurve::quadto - path is empty!"); + else + _pathv.back().appendNew(p1, p2); } /** * Calls SPCurve::quadto( Geom::Point(x1,y1), Geom::Point(x2,y2) ) * All coordinates must be finite. */ -void -SPCurve::quadto(double x1, double y1, double x2, double y2) +void SPCurve::quadto(double x1, double y1, double x2, double y2) { - quadto( Geom::Point(x1,y1), Geom::Point(x2,y2) ); + quadto(Geom::Point(x1, y1), Geom::Point(x2, y2)); } /** * Adds a bezier segment to the current subpath. * All points must be finite. */ -void -SPCurve::curveto(Geom::Point const &p0, Geom::Point const &p1, Geom::Point const &p2) +void SPCurve::curveto(Geom::Point const &p0, Geom::Point const &p1, Geom::Point const &p2) { - if (_pathv.empty()) g_message("SPCurve::curveto - path is empty!"); - else _pathv.back().appendNew( p0, p1, p2 ); + if (_pathv.empty()) + g_message("SPCurve::curveto - path is empty!"); + else + _pathv.back().appendNew(p0, p1, p2); } /** * Calls SPCurve::curveto( Geom::Point(x0,y0), Geom::Point(x1,y1), Geom::Point(x2,y2) ) * All coordinates must be finite. */ -void -SPCurve::curveto(double x0, double y0, double x1, double y1, double x2, double y2) +void SPCurve::curveto(double x0, double y0, double x1, double y1, double x2, double y2) { - curveto( Geom::Point(x0,y0), Geom::Point(x1,y1), Geom::Point(x2,y2) ); + curveto(Geom::Point(x0, y0), Geom::Point(x1, y1), Geom::Point(x2, y2)); } /** * Close current subpath by possibly adding a line between start and end. */ -void -SPCurve::closepath() +void SPCurve::closepath() { _pathv.back().close(true); } @@ -254,8 +244,7 @@ SPCurve::closepath() Used for freehand drawing when the user draws back to the start point. **/ -void -SPCurve::closepath_current() +void SPCurve::closepath_current() { if (_pathv.back().size() > 0 && dynamic_cast(&_pathv.back().back_open())) { _pathv.back().erase_last(); @@ -268,8 +257,7 @@ SPCurve::closepath_current() /** * True if no paths are in curve. If it only contains a path with only a moveto, the path is considered NON-empty */ -bool -SPCurve::is_empty() const +bool SPCurve::is_empty() const { return _pathv.empty(); } @@ -277,8 +265,7 @@ SPCurve::is_empty() const /** * True if paths are in curve. If it only contains a path with only a moveto, the path is considered as unset FALSE */ -bool -SPCurve::is_unset() const +bool SPCurve::is_unset() const { if (get_segment_count()) { return false; @@ -290,20 +277,19 @@ SPCurve::is_unset() const * True iff all subpaths are closed. * Returns false if the curve is empty. */ -bool -SPCurve::is_closed() const +bool SPCurve::is_closed() const { if (is_empty()) { return false; - } - - for (const auto & it : _pathv) { - if ( ! it.closed() ) { + } + + for (const auto &it : _pathv) { + if (!it.closed()) { return false; } } - - return true; + + return true; } /** @@ -311,14 +297,14 @@ SPCurve::is_closed() const */ bool SPCurve::is_equal(SPCurve const *other) const { - if(other == nullptr) { + if (other == nullptr) { return false; - } + } - if(_pathv == other->get_pathvector()){ + if (_pathv == other->get_pathvector()) { return true; } - + return false; } @@ -326,8 +312,7 @@ bool SPCurve::is_equal(SPCurve const *other) const * Return last pathsegment (possibly the closing path segment) of the last path in PathVector or NULL. * If the last path is empty (contains only a moveto), the function returns NULL */ -Geom::Curve const * -SPCurve::last_segment() const +Geom::Curve const *SPCurve::last_segment() const { if (is_empty()) { return nullptr; @@ -342,8 +327,7 @@ SPCurve::last_segment() const /** * Return last path in PathVector or NULL. */ -Geom::Path const * -SPCurve::last_path() const +Geom::Path const *SPCurve::last_path() const { if (is_empty()) { return nullptr; @@ -356,8 +340,7 @@ SPCurve::last_path() const * Return first pathsegment in PathVector or NULL. * equal in functionality to SPCurve::first_bpath() */ -Geom::Curve const * -SPCurve::first_segment() const +Geom::Curve const *SPCurve::first_segment() const { if (is_empty()) { return nullptr; @@ -372,8 +355,7 @@ SPCurve::first_segment() const /** * Return first path in PathVector or NULL. */ -Geom::Path const * -SPCurve::first_path() const +Geom::Path const *SPCurve::first_path() const { if (is_empty()) { return nullptr; @@ -385,8 +367,7 @@ SPCurve::first_path() const /** * Return first point of first subpath or nothing when the path is empty. */ -boost::optional -SPCurve::first_point() const +boost::optional SPCurve::first_point() const { boost::optional retval; @@ -403,8 +384,7 @@ SPCurve::first_point() const * returns the first point of the second path, if it exists. If there is no 2nd path, it returns the * first point of the first path. */ -boost::optional -SPCurve::second_point() const +boost::optional SPCurve::second_point() const { boost::optional retval; if (!is_empty()) { @@ -427,8 +407,7 @@ SPCurve::second_point() const /** * Return the second-last point of last subpath or first point when that last subpath has only a moveto. */ -boost::optional -SPCurve::penultimate_point() const +boost::optional SPCurve::penultimate_point() const { boost::optional retval; if (!is_empty()) { @@ -448,8 +427,7 @@ SPCurve::penultimate_point() const * Return last point of last subpath or nothing when the curve is empty. * If the last path is only a moveto, then return that point. */ -boost::optional -SPCurve::last_point() const +boost::optional SPCurve::last_point() const { boost::optional retval; @@ -475,11 +453,10 @@ SPCurve::create_reverse() const /** * Append \a curve2 to \a this. * If \a use_lineto is false, simply add all paths in \a curve2 to \a this; - * if \a use_lineto is true, combine \a this's last path and \a curve2's first path and add the rest of the paths in \a curve2 to \a this. + * if \a use_lineto is true, combine \a this's last path and \a curve2's first path and add the rest of the paths in \a + * curve2 to \a this. */ -void -SPCurve::append(SPCurve const &curve2, - bool use_lineto) +void SPCurve::append(SPCurve const &curve2, bool use_lineto) { append(curve2._pathv, use_lineto); } @@ -490,28 +467,29 @@ void SPCurve::append(Geom::PathVector const &pathv, bool use_lineto) if (use_lineto) { Geom::PathVector::const_iterator it = pathv.begin(); - if ( ! _pathv.empty() ) { - Geom::Path & lastpath = _pathv.back(); - lastpath.appendNew( (*it).initialPoint() ); - lastpath.append( (*it) ); + if (!_pathv.empty()) { + Geom::Path &lastpath = _pathv.back(); + lastpath.appendNew((*it).initialPoint()); + lastpath.append((*it)); } else { - _pathv.push_back( (*it) ); + _pathv.push_back((*it)); } for (++it; it != pathv.end(); ++it) { - _pathv.push_back( (*it) ); + _pathv.push_back((*it)); } } else { for (const auto &it : pathv) { - _pathv.push_back( it ); + _pathv.push_back(it); } } } /** - * Append \a c1 to \a this with possible fusing of close endpoints. If the end of this curve and the start of c1 are within tolerance distance, - * then the startpoint of c1 is moved to the end of this curve and the first subpath of c1 is appended to the last subpath of this curve. - * When one of the curves is empty, this curves path becomes the non-empty path. + * Append \a c1 to \a this with possible fusing of close endpoints. If the end of this curve and the start of c1 are + * within tolerance distance, then the startpoint of c1 is moved to the end of this curve and the first subpath of c1 is + * appended to the last subpath of this curve. When one of the curves is empty, this curves path becomes the non-empty + * path. * * @param tolerance Tolerance for enpoint fusion (applied to x and y separately) * @return False if one of the curves (this curve or the argument curve) is closed, true otherwise. @@ -533,16 +511,16 @@ bool SPCurve::append_continuous(SPCurve const &c1, double tolerance) if ((fabs(last_point()->x() - c1.first_point()->x()) <= tolerance) && (fabs(last_point()->y() - c1.first_point()->y()) <= tolerance)) { - // c1's first subpath can be appended to this curve's last subpath + // c1's first subpath can be appended to this curve's last subpath Geom::PathVector::const_iterator path_it = c1._pathv.begin(); - Geom::Path & lastpath = _pathv.back(); + Geom::Path &lastpath = _pathv.back(); Geom::Path newfirstpath(*path_it); newfirstpath.setInitial(lastpath.finalPoint()); - lastpath.append( newfirstpath ); + lastpath.append(newfirstpath); for (++path_it; path_it != c1._pathv.end(); ++path_it) { - _pathv.push_back( (*path_it) ); + _pathv.push_back((*path_it)); } } else { @@ -556,13 +534,12 @@ bool SPCurve::append_continuous(SPCurve const &c1, double tolerance) * Remove last segment of curve. * (Only used once in /src/pen-context.cpp) */ -void -SPCurve::backspace() +void SPCurve::backspace() { - if ( is_empty() ) + if (is_empty()) return; - if ( !_pathv.back().empty() ) { + if (!_pathv.back().empty()) { _pathv.back().erase_last(); _pathv.back().close(false); } @@ -575,39 +552,39 @@ SPCurve::backspace() (2:08:29 AM) Johan: to move the knots (2:08:36 AM) Johan: then i add it (2:08:40 AM) Johan: then convert back to path -If I remember correctly, this moves the firstpoint to new_p0, and the lastpoint to new_p1, and moves all nodes in between according to their arclength (interpolates the movement amount) +If I remember correctly, this moves the firstpoint to new_p0, and the lastpoint to new_p1, and moves all nodes in +between according to their arclength (interpolates the movement amount) */ -void -SPCurve::stretch_endpoints(Geom::Point const &new_p0, Geom::Point const &new_p1) +void SPCurve::stretch_endpoints(Geom::Point const &new_p0, Geom::Point const &new_p1) { if (is_empty()) { return; } - Geom::Point const offset0( new_p0 - *first_point() ); - Geom::Point const offset1( new_p1 - *last_point() ); + Geom::Point const offset0(new_p0 - *first_point()); + Geom::Point const offset1(new_p1 - *last_point()); - Geom::Piecewise > pwd2 = _pathv.front().toPwSb(); + Geom::Piecewise> pwd2 = _pathv.front().toPwSb(); Geom::Piecewise arclength = Geom::arcLengthSb(pwd2); - if ( arclength.lastValue() <= 0 ) { + if (arclength.lastValue() <= 0) { g_error("SPCurve::stretch_endpoints - arclength <= 0"); throw; } - arclength *= 1./arclength.lastValue(); - Geom::Point const A( offset0 ); - Geom::Point const B( offset1 ); - Geom::Piecewise offsetx = (arclength*-1.+1)*A[0] + arclength*B[0]; - Geom::Piecewise offsety = (arclength*-1.+1)*A[1] + arclength*B[1]; - Geom::Piecewise > offsetpath = Geom::sectionize( Geom::D2 >(offsetx, offsety) ); + arclength *= 1. / arclength.lastValue(); + Geom::Point const A(offset0); + Geom::Point const B(offset1); + Geom::Piecewise offsetx = (arclength * -1. + 1) * A[0] + arclength * B[0]; + Geom::Piecewise offsety = (arclength * -1. + 1) * A[1] + arclength * B[1]; + Geom::Piecewise> offsetpath = + Geom::sectionize(Geom::D2>(offsetx, offsety)); pwd2 += offsetpath; - _pathv = Geom::path_from_piecewise( pwd2, 0.001 ); + _pathv = Geom::path_from_piecewise(pwd2, 0.001); } /** * sets start of first path to new_p0, and end of first path to new_p1 */ -void -SPCurve::move_endpoints(Geom::Point const &new_p0, Geom::Point const &new_p1) +void SPCurve::move_endpoints(Geom::Point const &new_p0, Geom::Point const &new_p1) { if (is_empty()) { return; @@ -619,13 +596,13 @@ SPCurve::move_endpoints(Geom::Point const &new_p0, Geom::Point const &new_p1) /** * returns the number of nodes in a path, used for statusbar text when selecting an spcurve. * Sum of nodes in all the paths. When a path is closed, and its closing line segment is of zero-length, - * this function will not count the closing knot double (so basically ignores the closing line segment when it has zero length) + * this function will not count the closing knot double (so basically ignores the closing line segment when it has zero + * length) */ -size_t -SPCurve::nodes_in_path() const +size_t SPCurve::nodes_in_path() const { size_t nr = 0; - for(const auto & it : _pathv) { + for (const auto &it : _pathv) { // if the path does not have any segments, it is a naked moveto, // and therefore any path has at least one valid node size_t psize = std::max(1, it.size_closed()); @@ -650,21 +627,20 @@ SPCurve::nodes_in_path() const /** * Adds p to the last point (and last handle if present) of the last path */ -void -SPCurve::last_point_additive_move(Geom::Point const & p) +void SPCurve::last_point_additive_move(Geom::Point const &p) { if (is_empty()) { return; } - _pathv.back().setFinal( _pathv.back().finalPoint() + p ); + _pathv.back().setFinal(_pathv.back().finalPoint() + p); // Move handle as well when the last segment is a cubic bezier segment: // TODO: what to do for quadratic beziers? - if ( Geom::CubicBezier const *lastcube = dynamic_cast(&_pathv.back().back()) ) { - Geom::CubicBezier newcube( *lastcube ); + if (Geom::CubicBezier const *lastcube = dynamic_cast(&_pathv.back().back())) { + Geom::CubicBezier newcube(*lastcube); newcube.setPoint(2, newcube[2] + p); - _pathv.back().replace( --_pathv.back().end(), newcube ); + _pathv.back().replace(--_pathv.back().end(), newcube); } } diff --git a/src/display/curve.h b/src/display/curve.h index 69319803c2a4967ac56593706a2fc0d5e449d5f5..73f997fc168cf75cf11714acb2b273160359a4b1 100644 --- a/src/display/curve.h +++ b/src/display/curve.h @@ -15,8 +15,8 @@ #define SEEN_DISPLAY_CURVE_H #include <2geom/pathvector.h> -#include #include +#include #include #include #include @@ -26,7 +26,8 @@ class SPCurve; /** * Wrapper around a Geom::PathVector object. */ -class SPCurve { +class SPCurve +{ //! Preferred smart pointer type for SPCurve using smart_pointer = ::std::unique_ptr; @@ -53,11 +54,11 @@ public: virtual ~SPCurve(); // Don't implement these: - SPCurve(const SPCurve&) = delete; - SPCurve& operator=(const SPCurve&) = delete; + SPCurve(const SPCurve &) = delete; + SPCurve &operator=(const SPCurve &) = delete; - void set_pathvector(Geom::PathVector const & new_pathv); - Geom::PathVector const & get_pathvector() const; + void set_pathvector(Geom::PathVector const &new_pathv); + Geom::PathVector const &get_pathvector() const; smart_pointer ref(); smart_pointer copy() const; @@ -69,10 +70,10 @@ public: bool is_unset() const; bool is_closed() const; bool is_equal(SPCurve const *other) const; - Geom::Curve const * last_segment() const; - Geom::Path const * last_path() const; - Geom::Curve const * first_segment() const; - Geom::Path const * first_path() const; + Geom::Curve const *last_segment() const; + Geom::Path const *last_path() const; + Geom::Curve const *first_segment() const; + Geom::Path const *first_path() const; boost::optional first_point() const; boost::optional last_point() const; boost::optional second_point() const; @@ -95,7 +96,7 @@ public: void transform(Geom::Affine const &m); void stretch_endpoints(Geom::Point const &, Geom::Point const &); void move_endpoints(Geom::Point const &, Geom::Point const &); - void last_point_additive_move(Geom::Point const & p); + void last_point_additive_move(Geom::Point const &p); void append(Geom::PathVector const &, bool use_lineto = false); void append(SPCurve const &curve2, bool use_lineto = false); diff --git a/src/display/drawing-context.cpp b/src/display/drawing-context.cpp index ac45df2e805a507f1579cd1588ade94c8132f5d6..475ae561b0b3897a002f9fb7dd77d49059224984 100644 --- a/src/display/drawing-context.cpp +++ b/src/display/drawing-context.cpp @@ -11,8 +11,9 @@ */ #include "display/drawing-context.h" -#include "display/drawing-surface.h" + #include "display/cairo-utils.h" +#include "display/drawing-surface.h" namespace Inkscape { @@ -113,26 +114,34 @@ void DrawingContext::arc(Geom::Point const ¢er, double radius, Geom::AngleIn } // Applies transform to Cairo surface -void DrawingContext::transform(Geom::Affine const &trans) { +void DrawingContext::transform(Geom::Affine const &trans) +{ ink_cairo_transform(_ct, trans); } -void DrawingContext::path(Geom::PathVector const &pv) { +void DrawingContext::path(Geom::PathVector const &pv) +{ feed_pathvector_to_cairo(_ct, pv); } -void DrawingContext::paint(double alpha) { - if (alpha == 1.0) cairo_paint(_ct); - else cairo_paint_with_alpha(_ct, alpha); +void DrawingContext::paint(double alpha) +{ + if (alpha == 1.0) + cairo_paint(_ct); + else + cairo_paint_with_alpha(_ct, alpha); } -void DrawingContext::setSource(guint32 rgba) { +void DrawingContext::setSource(guint32 rgba) +{ ink_cairo_set_source_rgba32(_ct, rgba); } -void DrawingContext::setSource(DrawingSurface *s) { +void DrawingContext::setSource(DrawingSurface *s) +{ Geom::Point origin = s->origin(); cairo_set_source_surface(_ct, s->raw(), origin[X], origin[Y]); } -void DrawingContext::setSourceCheckerboard() { +void DrawingContext::setSourceCheckerboard() +{ cairo_pattern_t *check = ink_cairo_pattern_create_checkerboard(); cairo_set_source(_ct, check); cairo_pattern_destroy(check); diff --git a/src/display/drawing-context.h b/src/display/drawing-context.h index aedb87ea2d3250f7a11200a55af57b869ba964db..100b0eae220f2dcaa17f8266b079a259ecc18b3c 100644 --- a/src/display/drawing-context.h +++ b/src/display/drawing-context.h @@ -23,16 +23,17 @@ namespace Inkscape { class DrawingSurface; -class DrawingContext - : boost::noncopyable +class DrawingContext : boost::noncopyable { public: - class Save { + class Save + { public: Save(); Save(DrawingContext &dc); ~Save(); void save(DrawingContext &dc); + private: DrawingContext *_dc; }; @@ -41,7 +42,7 @@ public: DrawingContext(cairo_surface_t *surface, Geom::Point const &origin); DrawingContext(DrawingSurface &s); ~DrawingContext(); - + void save() { cairo_save(_ct); } void restore() { cairo_restore(_ct); } void pushGroup() { cairo_push_group(_ct); } @@ -58,31 +59,30 @@ public: void moveTo(Geom::Point const &p) { cairo_move_to(_ct, p[Geom::X], p[Geom::Y]); } void lineTo(Geom::Point const &p) { cairo_line_to(_ct, p[Geom::X], p[Geom::Y]); } - void curveTo(Geom::Point const &p1, Geom::Point const &p2, Geom::Point const &p3) { + void curveTo(Geom::Point const &p1, Geom::Point const &p2, Geom::Point const &p3) + { cairo_curve_to(_ct, p1[Geom::X], p1[Geom::Y], p2[Geom::X], p2[Geom::Y], p3[Geom::X], p3[Geom::Y]); } void arc(Geom::Point const ¢er, double radius, Geom::AngleInterval const &angle); void closePath() { cairo_close_path(_ct); } - void rectangle(Geom::Rect const &r) { - cairo_rectangle(_ct, r.left(), r.top(), r.width(), r.height()); - } - void rectangle(Geom::IntRect const &r) { - cairo_rectangle(_ct, r.left(), r.top(), r.width(), r.height()); - } + void rectangle(Geom::Rect const &r) { cairo_rectangle(_ct, r.left(), r.top(), r.width(), r.height()); } + void rectangle(Geom::IntRect const &r) { cairo_rectangle(_ct, r.left(), r.top(), r.width(), r.height()); } // Used in drawing-text.cpp to overwrite glyphs, which have the opposite path rotation as a regular rect - void revrectangle(Geom::Rect const &r) { - cairo_move_to ( _ct, r.left(), r.top() ); - cairo_rel_line_to (_ct, 0, r.height() ); - cairo_rel_line_to (_ct, r.width(), 0 ); - cairo_rel_line_to (_ct, 0, -r.height() ); - cairo_close_path ( _ct); + void revrectangle(Geom::Rect const &r) + { + cairo_move_to(_ct, r.left(), r.top()); + cairo_rel_line_to(_ct, 0, r.height()); + cairo_rel_line_to(_ct, r.width(), 0); + cairo_rel_line_to(_ct, 0, -r.height()); + cairo_close_path(_ct); } - void revrectangle(Geom::IntRect const &r) { - cairo_move_to ( _ct, r.left(), r.top() ); - cairo_rel_line_to (_ct, 0, r.height() ); - cairo_rel_line_to (_ct, r.width(), 0 ); - cairo_rel_line_to (_ct, 0, -r.height() ); - cairo_close_path ( _ct); + void revrectangle(Geom::IntRect const &r) + { + cairo_move_to(_ct, r.left(), r.top()); + cairo_rel_line_to(_ct, 0, r.height()); + cairo_rel_line_to(_ct, r.width(), 0); + cairo_rel_line_to(_ct, 0, -r.height()); + cairo_close_path(_ct); } void newPath() { cairo_new_path(_ct); } void newSubpath() { cairo_new_sub_path(_ct); } @@ -104,19 +104,13 @@ public: cairo_operator_t getOperator() { return cairo_get_operator(_ct); } void setTolerance(double tol) { cairo_set_tolerance(_ct, tol); } void setSource(cairo_pattern_t *source) { cairo_set_source(_ct, source); } - void setSource(cairo_surface_t *surface, double x, double y) { - cairo_set_source_surface(_ct, surface, x, y); - } - void setSource(double r, double g, double b, double a = 1.0) { - cairo_set_source_rgba(_ct, r, g, b, a); - } + void setSource(cairo_surface_t *surface, double x, double y) { cairo_set_source_surface(_ct, surface, x, y); } + void setSource(double r, double g, double b, double a = 1.0) { cairo_set_source_rgba(_ct, r, g, b, a); } void setSource(guint32 rgba); void setSource(DrawingSurface *s); void setSourceCheckerboard(); - void patternSetFilter(cairo_filter_t filter) { - cairo_pattern_set_filter(cairo_get_source(_ct), filter); - } + void patternSetFilter(cairo_filter_t filter) { cairo_pattern_set_filter(cairo_get_source(_ct), filter); } void patternSetExtend(cairo_extend_t extend) { cairo_pattern_set_extend(cairo_get_source(_ct), extend); } Geom::Rect targetLogicalBounds() const; diff --git a/src/display/drawing-group.cpp b/src/display/drawing-group.cpp index 397b30c677a4dc33745aae8f468c7c5443acb968..26d59226fe821e37b352fa17180a372bd236b5eb 100644 --- a/src/display/drawing-group.cpp +++ b/src/display/drawing-group.cpp @@ -11,6 +11,7 @@ */ #include "display/drawing-group.h" + #include "display/cairo-utils.h" #include "display/drawing-context.h" #include "display/drawing-item.h" @@ -35,8 +36,7 @@ DrawingGroup::~DrawingGroup() * Set whether the group returns children from pick calls. * Previously this feature was called "transparent groups". */ -void -DrawingGroup::setPickChildren(bool p) +void DrawingGroup::setPickChildren(bool p) { _pick_children = p; } @@ -46,8 +46,7 @@ DrawingGroup::setPickChildren(bool p) * This is applied after the normal transform and mainly useful for * markers, clipping paths, etc. */ -void -DrawingGroup::setChildTransform(Geom::Affine const &new_trans) +void DrawingGroup::setChildTransform(Geom::Affine const &new_trans) { Geom::Affine current; if (_child_transform) { @@ -67,8 +66,7 @@ DrawingGroup::setChildTransform(Geom::Affine const &new_trans) } } -unsigned -DrawingGroup::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) +unsigned DrawingGroup::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) { unsigned beststate = STATE_ALL; bool outline = _drawing.outline(); @@ -77,12 +75,12 @@ DrawingGroup::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, u if (_child_transform) { child_ctx.ctm = *_child_transform * ctx.ctm; } - for (auto & i : _children) { + for (auto &i : _children) { i.update(area, child_ctx, flags, reset); } if (beststate & STATE_BBOX) { _bbox = Geom::OptIntRect(); - for (auto & i : _children) { + for (auto &i : _children) { if (i.visible()) { _bbox.unionWith(outline ? i.geometricBounds() : i.visualBounds()); } @@ -91,8 +89,7 @@ DrawingGroup::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, u return beststate; } -unsigned -DrawingGroup::_renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) +unsigned DrawingGroup::_renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) { if (stop_at == nullptr) { // normal rendering @@ -119,18 +116,16 @@ DrawingGroup::_renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigne return RENDER_OK; } -void -DrawingGroup::_clipItem(DrawingContext &dc, Geom::IntRect const &area) +void DrawingGroup::_clipItem(DrawingContext &dc, Geom::IntRect const &area) { - for (auto & i : _children) { + for (auto &i : _children) { i.clip(dc, area); } } -DrawingItem * -DrawingGroup::_pickItem(Geom::Point const &p, double delta, unsigned flags) +DrawingItem *DrawingGroup::_pickItem(Geom::Point const &p, double delta, unsigned flags) { - for (auto & i : _children) { + for (auto &i : _children) { DrawingItem *picked = i.pick(p, delta, flags); if (picked) { return _pick_children ? picked : this; @@ -139,8 +134,7 @@ DrawingGroup::_pickItem(Geom::Point const &p, double delta, unsigned flags) return nullptr; } -bool -DrawingGroup::_canClip() +bool DrawingGroup::_canClip() { return true; } diff --git a/src/display/drawing-group.h b/src/display/drawing-group.h index 1f5f283934853b62fbc592ca3a1b4d1b005a7092..3ec08b10f3e25ed77f1526de28903a7bd5e0a0ed 100644 --- a/src/display/drawing-group.h +++ b/src/display/drawing-group.h @@ -17,8 +17,7 @@ namespace Inkscape { -class DrawingGroup - : public DrawingItem +class DrawingGroup : public DrawingItem { public: DrawingGroup(Drawing &drawing); @@ -30,10 +29,8 @@ public: void setChildTransform(Geom::Affine const &new_trans); protected: - unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, - unsigned flags, unsigned reset) override; - unsigned _renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, - DrawingItem *stop_at) override; + unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) override; + unsigned _renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) override; void _clipItem(DrawingContext &dc, Geom::IntRect const &area) override; DrawingItem *_pickItem(Geom::Point const &p, double delta, unsigned flags) override; bool _canClip() override; diff --git a/src/display/drawing-image.cpp b/src/display/drawing-image.cpp index 0ac716dfb29ed69449109167c086a731f335cea1..764de8cd2bedd9b3c6303202f1baa5db71bbd29f 100644 --- a/src/display/drawing-image.cpp +++ b/src/display/drawing-image.cpp @@ -10,15 +10,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/drawing-image.h" + #include <2geom/bezier-curve.h> -#include "display/drawing.h" +#include "display/cairo-utils.h" #include "display/drawing-context.h" -#include "display/drawing-image.h" +#include "display/drawing.h" #include "preferences.h" -#include "display/cairo-utils.h" - namespace Inkscape { DrawingImage::DrawingImage(Drawing &drawing) @@ -31,54 +31,49 @@ DrawingImage::~DrawingImage() // _pixbuf is owned by SPImage - do not delete it } -void -DrawingImage::setPixbuf(Inkscape::Pixbuf *pb) +void DrawingImage::setPixbuf(Inkscape::Pixbuf *pb) { _pixbuf = pb; _markForUpdate(STATE_ALL, false); } -void -DrawingImage::setScale(double sx, double sy) +void DrawingImage::setScale(double sx, double sy) { _scale = Geom::Scale(sx, sy); _markForUpdate(STATE_ALL, false); } -void -DrawingImage::setOrigin(Geom::Point const &o) +void DrawingImage::setOrigin(Geom::Point const &o) { _origin = o; _markForUpdate(STATE_ALL, false); } -void -DrawingImage::setClipbox(Geom::Rect const &box) +void DrawingImage::setClipbox(Geom::Rect const &box) { _clipbox = box; _markForUpdate(STATE_ALL, false); } -Geom::Rect -DrawingImage::bounds() const +Geom::Rect DrawingImage::bounds() const { - if (!_pixbuf) return _clipbox; + if (!_pixbuf) + return _clipbox; double pw = _pixbuf->width(); double ph = _pixbuf->height(); double vw = pw * _scale[Geom::X]; double vh = ph * _scale[Geom::Y]; Geom::Point wh(vw, vh); - Geom::Rect view(_origin, _origin+wh); + Geom::Rect view(_origin, _origin + wh); Geom::OptRect res = _clipbox & view; Geom::Rect ret = res ? *res : _clipbox; return ret; } -unsigned -DrawingImage::_updateItem(Geom::IntRect const &, UpdateContext const &, unsigned, unsigned) +unsigned DrawingImage::_updateItem(Geom::IntRect const &, UpdateContext const &, unsigned, unsigned) { _markForRendering(); @@ -93,7 +88,8 @@ DrawingImage::_updateItem(Geom::IntRect const &, UpdateContext const &, unsigned return STATE_ALL; } -unsigned DrawingImage::_renderItem(DrawingContext &dc, Geom::IntRect const &/*area*/, unsigned /*flags*/, DrawingItem * /*stop_at*/) +unsigned DrawingImage::_renderItem(DrawingContext &dc, Geom::IntRect const & /*area*/, unsigned /*flags*/, + DrawingItem * /*stop_at*/) { bool outline = _drawing.outline(); @@ -101,7 +97,8 @@ unsigned DrawingImage::_renderItem(DrawingContext &dc, Geom::IntRect const &/*ar bool imgoutline = prefs->getBool("/options/rendering/imageinoutlinemode", false); if (!outline || imgoutline) { - if (!_pixbuf) return RENDER_OK; + if (!_pixbuf) + return RENDER_OK; Inkscape::DrawingContext::Save save(dc); dc.transform(_ctm); @@ -127,13 +124,13 @@ unsigned DrawingImage::_renderItem(DrawingContext &dc, Geom::IntRect const &/*ar case SP_CSS_IMAGE_RENDERING_PIXELATED: // we don't have an implementation for crisp-edges, but it should *not* smooth or blur case SP_CSS_IMAGE_RENDERING_CRISPEDGES: - dc.patternSetFilter( CAIRO_FILTER_NEAREST ); + dc.patternSetFilter(CAIRO_FILTER_NEAREST); break; case SP_CSS_IMAGE_RENDERING_AUTO: case SP_CSS_IMAGE_RENDERING_OPTIMIZEQUALITY: default: // In recent Cairo, BEST used Lanczos3, which is prohibitively slow - dc.patternSetFilter( CAIRO_FILTER_GOOD ); + dc.patternSetFilter(CAIRO_FILTER_GOOD); break; } } @@ -144,7 +141,8 @@ unsigned DrawingImage::_renderItem(DrawingContext &dc, Geom::IntRect const &/*ar guint32 rgba = prefs->getInt("/options/wireframecolors/images", 0xff0000ff); - { Inkscape::DrawingContext::Save save(dc); + { + Inkscape::DrawingContext::Save save(dc); dc.transform(_ctm); dc.newPath(); @@ -174,18 +172,17 @@ unsigned DrawingImage::_renderItem(DrawingContext &dc, Geom::IntRect const &/*ar } /** Calculates the closest distance from p to the segment a1-a2*/ -static double -distance_to_segment (Geom::Point const &p, Geom::Point const &a1, Geom::Point const &a2) +static double distance_to_segment(Geom::Point const &p, Geom::Point const &a1, Geom::Point const &a2) { Geom::LineSegment l(a1, a2); Geom::Point np = l.pointAt(l.nearestTime(p)); return Geom::distance(np, p); } -DrawingItem * -DrawingImage::_pickItem(Geom::Point const &p, double delta, unsigned /*sticky*/) +DrawingItem *DrawingImage::_pickItem(Geom::Point const &p, double delta, unsigned /*sticky*/) { - if (!_pixbuf) return nullptr; + if (!_pixbuf) + return nullptr; bool outline = _drawing.outline() || _drawing.getOutlineSensitive(); @@ -196,7 +193,7 @@ DrawingImage::_pickItem(Geom::Point const &p, double delta, unsigned /*sticky*/) // find whether any side or diagonal is within delta // to do so, iterate over all pairs of corners for (unsigned i = 0; i < 3; ++i) { // for i=3, there is nothing to do - for (unsigned j = i+1; j < 4; ++j) { + for (unsigned j = i + 1; j < 4; ++j) { if (distance_to_segment(pick, r.corner(i), r.corner(j)) < delta) { return this; } diff --git a/src/display/drawing-image.h b/src/display/drawing-image.h index fd962dbb51bf44187438c28e4772e04e4dfbf999..e2b62b266231ac4d38af5984e7cffb7d02017a34 100644 --- a/src/display/drawing-image.h +++ b/src/display/drawing-image.h @@ -13,17 +13,16 @@ #ifndef SEEN_INKSCAPE_DISPLAY_DRAWING_IMAGE_H #define SEEN_INKSCAPE_DISPLAY_DRAWING_IMAGE_H +#include <2geom/transforms.h> #include #include -#include <2geom/transforms.h> #include "display/drawing-item.h" namespace Inkscape { class Pixbuf; -class DrawingImage - : public DrawingItem +class DrawingImage : public DrawingItem { public: DrawingImage(Drawing &drawing); @@ -36,10 +35,8 @@ public: Geom::Rect bounds() const; protected: - unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, - unsigned flags, unsigned reset) override; - unsigned _renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, - DrawingItem *stop_at) override; + unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) override; + unsigned _renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) override; DrawingItem *_pickItem(Geom::Point const &p, double delta, unsigned flags) override; Inkscape::Pixbuf *_pixbuf; diff --git a/src/display/drawing-item.cpp b/src/display/drawing-item.cpp index 9daf8af478a40d6cd7ef9d7006f7e3ac75904524..ab1a32ca910ec9c07a6085f853e05806a4f953ec 100644 --- a/src/display/drawing-item.cpp +++ b/src/display/drawing-item.cpp @@ -10,24 +10,23 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/drawing-item.h" + #include +#include "display/cairo-templates.h" +#include "display/cairo-utils.h" #include "display/drawing-context.h" #include "display/drawing-group.h" -#include "display/drawing-item.h" #include "display/drawing-pattern.h" #include "display/drawing-surface.h" #include "display/drawing-text.h" #include "display/drawing.h" #include "nr-filter.h" +#include "object/sp-item.h" #include "preferences.h" #include "style.h" -#include "display/cairo-utils.h" -#include "display/cairo-templates.h" - -#include "object/sp-item.h" - namespace Inkscape { /** * @class DrawingItem @@ -86,7 +85,7 @@ DrawingItem::DrawingItem(Drawing &drawing) DrawingItem::~DrawingItem() { _drawing.signal_item_deleted.emit(this); - //if (!_children.empty()) { + // if (!_children.empty()) { // g_warning("Removing item with children"); //} @@ -98,28 +97,28 @@ DrawingItem::~DrawingItem() _markForRendering(); } switch (_child_type) { - case CHILD_NORMAL: { - ChildrenList::iterator ithis = _parent->_children.iterator_to(*this); - _parent->_children.erase(ithis); + case CHILD_NORMAL: { + ChildrenList::iterator ithis = _parent->_children.iterator_to(*this); + _parent->_children.erase(ithis); } break; - case CHILD_CLIP: - // we cannot call setClip(NULL) or setMask(NULL), - // because that would be an endless loop - _parent->_clip = nullptr; - break; - case CHILD_MASK: - _parent->_mask = nullptr; - break; - case CHILD_ROOT: - _drawing._root = nullptr; - break; - case CHILD_FILL_PATTERN: - _parent->_fill_pattern = nullptr; - break; - case CHILD_STROKE_PATTERN: - _parent->_stroke_pattern = nullptr; - break; - default: ; + case CHILD_CLIP: + // we cannot call setClip(NULL) or setMask(NULL), + // because that would be an endless loop + _parent->_clip = nullptr; + break; + case CHILD_MASK: + _parent->_mask = nullptr; + break; + case CHILD_ROOT: + _drawing._root = nullptr; + break; + case CHILD_FILL_PATTERN: + _parent->_fill_pattern = nullptr; + break; + case CHILD_STROKE_PATTERN: + _parent->_stroke_pattern = nullptr; + break; + default:; } if (_parent) { @@ -132,12 +131,11 @@ DrawingItem::~DrawingItem() delete _clip; delete _mask; delete _filter; - if(_style) + if (_style) sp_style_unref(_style); } -DrawingItem * -DrawingItem::parent() const +DrawingItem *DrawingItem::parent() const { // initially I wanted to return NULL if we are a clip or mask child, // but the previous behavior was just to return the parent regardless of child type @@ -145,17 +143,16 @@ DrawingItem::parent() const } /// Returns true if item is among the descendants. Will return false if item == this. -bool -DrawingItem::isAncestorOf(DrawingItem *item) const +bool DrawingItem::isAncestorOf(DrawingItem *item) const { for (DrawingItem *i = item->_parent; i; i = i->_parent) { - if (i == this) return true; + if (i == this) + return true; } return false; } -void -DrawingItem::appendChild(DrawingItem *item) +void DrawingItem::appendChild(DrawingItem *item) { item->_parent = this; assert(item->_child_type == CHILD_ORPHAN); @@ -171,8 +168,7 @@ DrawingItem::appendChild(DrawingItem *item) item->_markForUpdate(STATE_ALL, true); } -void -DrawingItem::prependChild(DrawingItem *item) +void DrawingItem::prependChild(DrawingItem *item) { item->_parent = this; assert(item->_child_type == CHILD_ORPHAN); @@ -184,16 +180,16 @@ DrawingItem::prependChild(DrawingItem *item) } /// Delete all regular children of this item (not mask or clip). -void -DrawingItem::clearChildren() +void DrawingItem::clearChildren() { - if (_children.empty()) return; + if (_children.empty()) + return; _markForRendering(); // prevent children from referencing the parent during deletion // this way, children won't try to remove themselves from a list // from which they have already been removed by clear_and_dispose - for (auto & i : _children) { + for (auto &i : _children) { i._parent = NULL; i._child_type = CHILD_ORPHAN; } @@ -202,14 +198,13 @@ DrawingItem::clearChildren() } /// Set the incremental transform for this item -void -DrawingItem::setTransform(Geom::Affine const &new_trans) +void DrawingItem::setTransform(Geom::Affine const &new_trans) { Geom::Affine current; if (_transform) { current = *_transform; } - + if (!Geom::are_near(current, new_trans, 1e-18)) { // mark the area where the object was for redraw. _markForRendering(); @@ -223,8 +218,7 @@ DrawingItem::setTransform(Geom::Affine const &new_trans) } } -void -DrawingItem::setOpacity(float opacity) +void DrawingItem::setOpacity(float opacity) { if (_opacity != opacity) { _opacity = opacity; @@ -232,8 +226,7 @@ DrawingItem::setOpacity(float opacity) } } -void -DrawingItem::setAntialiasing(unsigned a) +void DrawingItem::setAntialiasing(unsigned a) { if (_antialias != a) { _antialias = a; @@ -241,24 +234,21 @@ DrawingItem::setAntialiasing(unsigned a) } } -void -DrawingItem::setIsolation(bool isolation) +void DrawingItem::setIsolation(bool isolation) { _isolation = isolation; - //if( isolation != 0 ) std::cout << "isolation: " << isolation << std::endl; + // if( isolation != 0 ) std::cout << "isolation: " << isolation << std::endl; _markForRendering(); } -void -DrawingItem::setBlendMode(SPBlendMode mix_blend_mode) +void DrawingItem::setBlendMode(SPBlendMode mix_blend_mode) { _mix_blend_mode = mix_blend_mode; - //if( mix_blend_mode != 0 ) std::cout << "setBlendMode: " << mix_blend_mode << std::endl; + // if( mix_blend_mode != 0 ) std::cout << "setBlendMode: " << mix_blend_mode << std::endl; _markForRendering(); } -void -DrawingItem::setVisible(bool v) +void DrawingItem::setVisible(bool v) { if (_visible != v) { _visible = v; @@ -267,8 +257,7 @@ DrawingItem::setVisible(bool v) } /// This is currently unused -void -DrawingItem::setSensitive(bool s) +void DrawingItem::setSensitive(bool s) { _sensitive = s; } @@ -277,11 +266,11 @@ DrawingItem::setSensitive(bool s) * Enable / disable storing the rendering in memory. * Calling setCached(false, true) will also remove the persistent status */ -void -DrawingItem::setCached(bool cached, bool persistent) +void DrawingItem::setCached(bool cached, bool persistent) { static const char *cache_env = getenv("_INKSCAPE_DISABLE_CACHE"); - if (cache_env) return; + if (cache_env) + return; if (_cached_persistent && !persistent) return; @@ -306,18 +295,19 @@ DrawingItem::setCached(bool cached, bool persistent) * * Note: _style is not used by DrawingGlyphs which uses its parent style. */ -void -DrawingItem::setStyle(SPStyle *style, SPStyle *context_style) +void DrawingItem::setStyle(SPStyle *style, SPStyle *context_style) { // std::cout << "DrawingItem::setStyle: " << name() << " " << style // << " " << context_style << std::endl; - if( style != _style ) { - if (style) sp_style_ref(style); - if (_style) sp_style_unref(_style); + if (style != _style) { + if (style) + sp_style_ref(style); + if (_style) + sp_style_unref(_style); _style = style; } - + if (style && style->filter.set && style->getFilter()) { if (!_filter) { int primitives = style->getFilter()->primitive_count(); @@ -352,7 +342,6 @@ DrawingItem::setStyle(SPStyle *style, SPStyle *context_style) _markForUpdate(STATE_ALL, false); } - /** * Recursively update children style. * The purpose of this call is to update fill and stroke for markers that have elements with @@ -360,18 +349,15 @@ DrawingItem::setStyle(SPStyle *style, SPStyle *context_style) * updated like other 'clones' as marker instances are not included the SP object tree. * Note: this is a virtual function. */ -void -DrawingItem::setChildrenStyle(SPStyle* context_style) +void DrawingItem::setChildrenStyle(SPStyle *context_style) { _context_style = context_style; - for (auto & i : _children) { - i.setChildrenStyle( context_style ); + for (auto &i : _children) { + i.setChildrenStyle(context_style); } } - -void -DrawingItem::setClip(DrawingItem *item) +void DrawingItem::setClip(DrawingItem *item) { _markForRendering(); delete _clip; @@ -384,13 +370,12 @@ DrawingItem::setClip(DrawingItem *item) _markForUpdate(STATE_ALL, true); } -void -DrawingItem::setMask(DrawingItem *item) +void DrawingItem::setMask(DrawingItem *item) { _markForRendering(); delete _mask; _mask = item; - if (item) { + if (item) { item->_parent = this; assert(item->_child_type == CHILD_ORPHAN); item->_child_type = CHILD_MASK; @@ -398,8 +383,7 @@ DrawingItem::setMask(DrawingItem *item) _markForUpdate(STATE_ALL, true); } -void -DrawingItem::setFillPattern(DrawingPattern *pattern) +void DrawingItem::setFillPattern(DrawingPattern *pattern) { _markForRendering(); delete _fill_pattern; @@ -412,8 +396,7 @@ DrawingItem::setFillPattern(DrawingPattern *pattern) _markForUpdate(STATE_ALL, true); } -void -DrawingItem::setStrokePattern(DrawingPattern *pattern) +void DrawingItem::setStrokePattern(DrawingPattern *pattern) { _markForRendering(); delete _stroke_pattern; @@ -428,10 +411,10 @@ DrawingItem::setStrokePattern(DrawingPattern *pattern) /// Move this item to the given place in the Z order of siblings. /// Does nothing if the item has no parent. -void -DrawingItem::setZOrder(unsigned z) +void DrawingItem::setZOrder(unsigned z) { - if (!_parent) return; + if (!_parent) + return; ChildrenList::iterator it = _parent->_children.iterator_to(*this); _parent->_children.erase(it); @@ -442,8 +425,7 @@ DrawingItem::setZOrder(unsigned z) _markForRendering(); } -void -DrawingItem::setItemBounds(Geom::OptRect const &bounds) +void DrawingItem::setItemBounds(Geom::OptRect const &bounds) { _item_bbox = bounds; } @@ -470,8 +452,7 @@ DrawingItem::setItemBounds(Geom::OptRect const &bounds) * propagating bounding box recomputation to children when the item's * transform changes. */ -void -DrawingItem::update(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) +void DrawingItem::update(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) { bool render_filters = _drawing.renderFilters(); bool outline = _drawing.outline(); @@ -482,12 +463,14 @@ DrawingItem::update(Geom::IntRect const &area, UpdateContext const &ctx, unsigne _state &= ~reset; // reset state of this item - if ((~_state & flags) == 0) return; // nothing to do + if ((~_state & flags) == 0) + return; // nothing to do // TODO this might be wrong if (_state & STATE_BBOX) { // we have up-to-date bbox - if (!area.intersects(outline ? _bbox : _drawbox)) return; + if (!area.intersects(outline ? _bbox : _drawbox)) + return; } // compute which elements need an update @@ -507,18 +490,17 @@ DrawingItem::update(Geom::IntRect const &area, UpdateContext const &ctx, unsigne // Vector effects if (_style) { - if (_style->vector_effect.fixed) { - child_ctx.ctm.setTranslation(Geom::Point(0,0)); + child_ctx.ctm.setTranslation(Geom::Point(0, 0)); } if (_style->vector_effect.size) { double value = sqrt(child_ctx.ctm.det()); - if (value > 0 ) { - child_ctx.ctm[0] = child_ctx.ctm[0]/value; - child_ctx.ctm[1] = child_ctx.ctm[1]/value; - child_ctx.ctm[2] = child_ctx.ctm[2]/value; - child_ctx.ctm[3] = child_ctx.ctm[3]/value; + if (value > 0) { + child_ctx.ctm[0] = child_ctx.ctm[0] / value; + child_ctx.ctm[1] = child_ctx.ctm[1] / value; + child_ctx.ctm[2] = child_ctx.ctm[2] / value; + child_ctx.ctm[3] = child_ctx.ctm[3] / value; } } @@ -627,15 +609,17 @@ DrawingItem::update(Geom::IntRect const &area, UpdateContext const &ctx, unsigne } } -struct MaskLuminanceToAlpha { - guint32 operator()(guint32 in) { +struct MaskLuminanceToAlpha +{ + guint32 operator()(guint32 in) + { guint r = 0, g = 0, b = 0; Display::ExtractRGB32(in, r, g, b); // the operation of unpremul -> luminance-to-alpha -> multiply by alpha // is equivalent to luminance-to-alpha on premultiplied color values // original computation in double: r*0.2125 + g*0.7154 + b*0.0721 - guint32 ao = r*109 + g*366 + b*37; // coeffs add up to 512 - return ((ao + 256) << 15) & 0xff000000; // equivalent to ((ao + 256) / 512) << 24 + guint32 ao = r * 109 + g * 366 + b * 37; // coeffs add up to 512 + return ((ao + 256) << 15) & 0xff000000; // equivalent to ((ao + 256) / 512) << 24 } }; @@ -649,8 +633,7 @@ struct MaskLuminanceToAlpha { * * @param flags Rendering options. This deals mainly with cache control. */ -unsigned -DrawingItem::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) +unsigned DrawingItem::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) { bool outline = _drawing.outline(); bool render_filters = _drawing.renderFilters(); @@ -686,7 +669,7 @@ DrawingItem::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flag // (incomplete filter dependence region). // Note 2: We only need to render carea of clip and mask, but // iarea of the object. - + Geom::OptIntRect iarea = carea; // expand carea to contain the dependent area of filters. if (_filter && render_filters) { @@ -704,11 +687,11 @@ DrawingItem::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flag if (!iarea) { return RENDER_OK; } - + // Device scale for HiDPI screens (typically 1 or 2) int device_scale = dc.surface()->device_scale(); - switch(_antialias){ + switch (_antialias) { case 0: cairo_set_antialias(dc.raw(), CAIRO_ANTIALIAS_NONE); break; @@ -754,19 +737,19 @@ DrawingItem::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flag bool &nir = needs_intermediate_rendering; bool needs_opacity = (_opacity < 0.995); - // this item needs an intermediate rendering if: + // this item needs an intermediate rendering if: nir |= (_clip != nullptr); // 1. it has a clipping path nir |= (_mask != nullptr); // 2. it has a mask nir |= (_filter != nullptr && render_filters); // 3. it has a filter nir |= needs_opacity; // 4. it is non-opaque - nir |= (_mix_blend_mode != SP_CSS_BLEND_NORMAL); // 5. it has blend mode - nir |= (_isolation == SP_CSS_ISOLATION_ISOLATE); // 6. it is isolated + nir |= (_mix_blend_mode != SP_CSS_BLEND_NORMAL); // 5. it has blend mode + nir |= (_isolation == SP_CSS_ISOLATION_ISOLATE); // 6. it is isolated nir |= !parent(); // 7. is root, need isolation from background if (_prev_nir && !needs_intermediate_rendering) { setCached(false, true); } _prev_nir = needs_intermediate_rendering; - nir |= (_cache != nullptr); // 5. it is to be cached + nir |= (_cache != nullptr); // 5. it is to be cached /* How the rendering is done. * @@ -778,7 +761,7 @@ DrawingItem::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flag * value corresponding to the opacity. If there is no clipping path, * the entire intermediate surface is painted with alpha corresponding * to the opacity value. - * + * */ // Short-circuit the simple case. // We also use this path for filter background rendering, because masking, clipping, @@ -790,7 +773,6 @@ DrawingItem::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flag return _renderItem(dc, *iarea, flags & ~RENDER_FILTER_BACKGROUND, stop_at); } - DrawingSurface intermediate(*iarea, device_scale); DrawingContext ict(intermediate); @@ -807,7 +789,7 @@ DrawingItem::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flag unsigned render_result = RENDER_OK; // 1. Render clipping path with alpha = opacity. - ict.setSource(0,0,0,_opacity); + ict.setSource(0, 0, 0, _opacity); // Since clip can be combined with opacity, the result could be incorrect // for overlapping clip children. To fix this we use the SOURCE operator // instead of the default OVER. @@ -846,7 +828,8 @@ DrawingItem::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flag if (_filter->uses_background() && _background_accumulate) { DrawingItem *bg_root = this; for (; bg_root; bg_root = bg_root->_parent) { - if (bg_root->_background_new) break; + if (bg_root->_background_new) + break; } if (bg_root) { DrawingSurface bg(*iarea, device_scale); @@ -889,22 +872,21 @@ DrawingItem::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flag // 7. Render blend mode dc.setOperator(ink_css_blend_to_cairo_operator(_mix_blend_mode)); dc.fill(); - dc.setSource(0,0,0,0); + dc.setSource(0, 0, 0, 0); // Web isolation only works if parent doesnt have transform - // the call above is to clear a ref on the intermediate surface held by dc return render_result; } -void -DrawingItem::_renderOutline(DrawingContext &dc, Geom::IntRect const &area, unsigned flags) +void DrawingItem::_renderOutline(DrawingContext &dc, Geom::IntRect const &area, unsigned flags) { // intersect with bbox rather than drawbox, as we want to render things outside // of the clipping path as well Geom::OptIntRect carea = Geom::intersect(area, _bbox); - if (!carea) return; + if (!carea) + return; // just render everything: item, clip, mask // First, render the object itself @@ -934,15 +916,17 @@ DrawingItem::_renderOutline(DrawingContext &dc, Geom::IntRect const &area, unsig * the result of this call using the IN operator. See the implementation * of render() for details. */ -void -DrawingItem::clip(Inkscape::DrawingContext &dc, Geom::IntRect const &area) +void DrawingItem::clip(Inkscape::DrawingContext &dc, Geom::IntRect const &area) { // don't bother if the object does not implement clipping (e.g. DrawingImage) - if (!_canClip()) return; - if (!_visible) return; - if (!area.intersects(_bbox)) return; + if (!_canClip()) + return; + if (!_visible) + return; + if (!area.intersects(_bbox)) + return; - dc.setSource(0,0,0,1); + dc.setSource(0, 0, 0, 1); dc.pushGroup(); // rasterize the clipping path _clipItem(dc, area); @@ -959,7 +943,7 @@ DrawingItem::clip(Inkscape::DrawingContext &dc, Geom::IntRect const &area) dc.popGroupToSource(); dc.setOperator(CAIRO_OPERATOR_OVER); dc.paint(); - dc.setSource(0,0,0,0); + dc.setSource(0, 0, 0, 0); } /** @@ -973,14 +957,13 @@ DrawingItem::clip(Inkscape::DrawingContext &dc, Geom::IntRect const &area) * When false, only visible and sensitive objects are considered. * When true, invisible and insensitive objects can also be picked. */ -DrawingItem * -DrawingItem::pick(Geom::Point const &p, double delta, unsigned flags) +DrawingItem *DrawingItem::pick(Geom::Point const &p, double delta, unsigned flags) { // Sometimes there's no BBOX in state, reason unknown (bug 992817) // I made this not an assert to remove the warning if (!(_state & STATE_BBOX) || !(_state & STATE_PICK)) { - g_warning("Invalid state when picking: STATE_BBOX = %d, STATE_PICK = %d", - _state & STATE_BBOX, _state & STATE_PICK); + g_warning("Invalid state when picking: STATE_BBOX = %d, STATE_PICK = %d", _state & STATE_BBOX, + _state & STATE_PICK); return nullptr; } // ignore invisible and insensitive items unless sticky @@ -1026,8 +1009,7 @@ DrawingItem::pick(Geom::Point const &p, double delta, unsigned flags) } // For debugging -Glib::ustring -DrawingItem::name() +Glib::ustring DrawingItem::name() { if (_item) { if (_item->getId()) @@ -1040,8 +1022,7 @@ DrawingItem::name() } // For debugging: Print drawing tree structure. -void -DrawingItem::recursivePrintTree( unsigned level ) +void DrawingItem::recursivePrintTree(unsigned level) { if (level == 0) { std::cout << "Display Item Tree" << std::endl; @@ -1051,27 +1032,26 @@ DrawingItem::recursivePrintTree( unsigned level ) std::cout << " "; } std::cout << name() << std::endl; - for (auto & i : _children) { - i.recursivePrintTree( level+1 ); + for (auto &i : _children) { + i.recursivePrintTree(level + 1); } } - /** * Marks the current visual bounding box of the item for redrawing. * This is called whenever the object changes its visible appearance. * For some cases (such as setting opacity) this is enough, but for others * _markForUpdate() also needs to be called. */ -void -DrawingItem::_markForRendering() +void DrawingItem::_markForRendering() { // TODO: this function does too much work when a large subtree // is invalidated - fix bool outline = _drawing.outline(); Geom::OptIntRect dirty = outline ? _bbox : _drawbox; - if (!dirty) return; + if (!dirty) + return; // dirty the caches of all parents DrawingItem *bkg_root = nullptr; @@ -1094,16 +1074,16 @@ DrawingItem::_markForRendering() _drawing.signal_request_render.emit(*dirty); } -void -DrawingItem::_invalidateFilterBackground(Geom::IntRect const &area) +void DrawingItem::_invalidateFilterBackground(Geom::IntRect const &area) { - if (!_drawbox.intersects(area)) return; + if (!_drawbox.intersects(area)) + return; if (_cache && _filter && _filter->uses_background()) { _cache->markDirty(area); } - for (auto & i : _children) { + for (auto &i : _children) { i._invalidateFilterBackground(area); } } @@ -1123,8 +1103,7 @@ DrawingItem::_invalidateFilterBackground(Geom::IntRect const &area) * With _propagate we do this during the update call, when we have to recurse * into children anyway. */ -void -DrawingItem::_markForUpdate(unsigned flags, bool propagate) +void DrawingItem::_markForUpdate(unsigned flags, bool propagate) { if (propagate) { _propagate_state |= flags; @@ -1152,16 +1131,16 @@ DrawingItem::_markForUpdate(unsigned flags, bool propagate) * Higher scores mean the item is more aggressively prioritized for automatic * caching by Inkscape::Drawing. */ -double -DrawingItem::_cacheScore() +double DrawingItem::_cacheScore() { Geom::OptIntRect cache_rect = _cacheRect(); - if (!cache_rect) return -1.0; + if (!cache_rect) + return -1.0; // a crude first approximation: // the basic score is the number of pixels in the drawbox double score = cache_rect->area(); // this is multiplied by the filter complexity and its expansion - if (_filter &&_drawing.renderFilters()) { + if (_filter && _drawing.renderFilters()) { score *= _filter->complexity(_ctm); Geom::IntRect ref_area = Geom::IntRect::from_xywh(0, 0, 16, 16); Geom::IntRect test_area = ref_area; @@ -1179,7 +1158,7 @@ DrawingItem::_cacheScore() if (_mask) { score += _mask->_cacheScore(); } - //g_message("caching score: %f", score); + // g_message("caching score: %f", score); return score; } @@ -1189,7 +1168,6 @@ inline void expandByScale(Geom::IntRect &rect, double scale) rect.expandBy(rect.width() * fraction, rect.height() * fraction); } - Geom::OptIntRect DrawingItem::_cacheRect() { Geom::OptIntRect r = _drawbox & _drawing.cacheLimit(); diff --git a/src/display/drawing-item.h b/src/display/drawing-item.h index 1cd677bd2827d55c183b4c93ff3cc4fe2deaa983..3fa764ab6788450aad5c27a971b67cbbdfe9f054 100644 --- a/src/display/drawing-item.h +++ b/src/display/drawing-item.h @@ -13,11 +13,11 @@ #ifndef SEEN_INKSCAPE_DISPLAY_DRAWING_ITEM_H #define SEEN_INKSCAPE_DISPLAY_DRAWING_ITEM_H -#include <2geom/rect.h> #include <2geom/affine.h> +#include <2geom/rect.h> +#include #include #include -#include #include #include @@ -44,14 +44,12 @@ class Filter; } // namespace Filters - - -struct UpdateContext { +struct UpdateContext +{ Geom::Affine ctm; }; -struct CacheRecord - : boost::totally_ordered +struct CacheRecord : boost::totally_ordered { bool operator<(CacheRecord const &other) const { return score < other.score; } bool operator==(CacheRecord const &other) const { return score == other.score; } @@ -62,35 +60,36 @@ struct CacheRecord }; typedef std::list CacheList; -class InvalidItemException : public std::exception { - const char *what() const noexcept override { - return "Invalid item in drawing"; - } +class InvalidItemException : public std::exception +{ + const char *what() const noexcept override { return "Invalid item in drawing"; } }; -class DrawingItem - : boost::noncopyable +class DrawingItem : boost::noncopyable { public: - enum RenderFlags { + enum RenderFlags + { RENDER_DEFAULT = 0, RENDER_CACHE_ONLY = 1, RENDER_BYPASS_CACHE = 2, RENDER_FILTER_BACKGROUND = 4 }; - enum StateFlags { + enum StateFlags + { STATE_NONE = 0, - STATE_BBOX = (1<<0), // bounding boxes are up-to-date - STATE_CACHE = (1<<1), // cache extents and clean area are up-to-date - STATE_PICK = (1<<2), // can process pick requests - STATE_RENDER = (1<<3), // can be rendered - STATE_BACKGROUND = (1<<4), // filter background data is up to date - STATE_ALL = (1<<5)-1 + STATE_BBOX = (1 << 0), // bounding boxes are up-to-date + STATE_CACHE = (1 << 1), // cache extents and clean area are up-to-date + STATE_PICK = (1 << 2), // can process pick requests + STATE_RENDER = (1 << 3), // can be rendered + STATE_BACKGROUND = (1 << 4), // filter background data is up to date + STATE_ALL = (1 << 5) - 1 }; - enum PickFlags { - PICK_NORMAL = 0, // normal pick - PICK_STICKY = (1<<0), // sticky pick - ignore visibility and sensitivity - PICK_AS_CLIP = (1<<2) // pick with no stroke and opaque fill regardless of item style + enum PickFlags + { + PICK_NORMAL = 0, // normal pick + PICK_STICKY = (1 << 0), // sticky pick - ignore visibility and sensitivity + PICK_AS_CLIP = (1 << 2) // pick with no stroke and opaque fill regardless of item style }; DrawingItem(Drawing &drawing); @@ -134,28 +133,30 @@ public: void setKey(unsigned key) { _key = key; } unsigned key() const { return _key; } void setItem(SPItem *item) { _item = item; } - SPItem* getItem() const { return _item; } // SPItem + SPItem *getItem() const { return _item; } // SPItem - - void update(Geom::IntRect const &area = Geom::IntRect::infinite(), UpdateContext const &ctx = UpdateContext(), unsigned flags = STATE_ALL, unsigned reset = 0); + void update(Geom::IntRect const &area = Geom::IntRect::infinite(), UpdateContext const &ctx = UpdateContext(), + unsigned flags = STATE_ALL, unsigned reset = 0); unsigned render(DrawingContext &dc, Geom::IntRect const &area, unsigned flags = 0, DrawingItem *stop_at = nullptr); void clip(DrawingContext &dc, Geom::IntRect const &area); DrawingItem *pick(Geom::Point const &p, double delta, unsigned flags = 0); - virtual Glib::ustring name(); // For debugging - void recursivePrintTree(unsigned level = 0); // For debugging + virtual Glib::ustring name(); // For debugging + void recursivePrintTree(unsigned level = 0); // For debugging protected: - enum ChildType { - CHILD_ORPHAN = 0, // no parent - implies _parent == NULL - CHILD_NORMAL = 1, // contained in _children of parent - CHILD_CLIP = 2, // referenced by _clip member of parent - CHILD_MASK = 3, // referenced by _mask member of parent - CHILD_ROOT = 4, // root item of _drawing - CHILD_FILL_PATTERN = 5, // referenced by fill pattern of parent + enum ChildType + { + CHILD_ORPHAN = 0, // no parent - implies _parent == NULL + CHILD_NORMAL = 1, // contained in _children of parent + CHILD_CLIP = 2, // referenced by _clip member of parent + CHILD_MASK = 3, // referenced by _mask member of parent + CHILD_ROOT = 4, // root item of _drawing + CHILD_FILL_PATTERN = 5, // referenced by fill pattern of parent CHILD_STROKE_PATTERN = 6 // referenced by stroke pattern of parent }; - enum RenderResult { + enum RenderResult + { RENDER_OK = 0, RENDER_STOP = 1 }; @@ -165,12 +166,18 @@ protected: void _invalidateFilterBackground(Geom::IntRect const &area); double _cacheScore(); Geom::OptIntRect _cacheRect(); - virtual unsigned _updateItem(Geom::IntRect const &/*area*/, UpdateContext const &/*ctx*/, - unsigned /*flags*/, unsigned /*reset*/) { return 0; } - virtual unsigned _renderItem(DrawingContext &/*dc*/, Geom::IntRect const &/*area*/, unsigned /*flags*/, - DrawingItem * /*stop_at*/) { return RENDER_OK; } - virtual void _clipItem(DrawingContext &/*dc*/, Geom::IntRect const &/*area*/) {} - virtual DrawingItem *_pickItem(Geom::Point const &/*p*/, double /*delta*/, unsigned /*flags*/) { return nullptr; } + virtual unsigned _updateItem(Geom::IntRect const & /*area*/, UpdateContext const & /*ctx*/, unsigned /*flags*/, + unsigned /*reset*/) + { + return 0; + } + virtual unsigned _renderItem(DrawingContext & /*dc*/, Geom::IntRect const & /*area*/, unsigned /*flags*/, + DrawingItem * /*stop_at*/) + { + return RENDER_OK; + } + virtual void _clipItem(DrawingContext & /*dc*/, Geom::IntRect const & /*area*/) {} + virtual DrawingItem *_pickItem(Geom::Point const & /*p*/, double /*delta*/, unsigned /*flags*/) { return nullptr; } virtual bool _canClip() { return false; } // member variables start here @@ -181,26 +188,25 @@ protected: typedef boost::intrusive::list_member_hook<> ListHook; ListHook _child_hook; - typedef boost::intrusive::list< - DrawingItem, - boost::intrusive::member_hook - > ChildrenList; + typedef boost::intrusive::list> + ChildrenList; ChildrenList _children; - unsigned _key; ///< Some SPItems can have more than one DrawingItem; - /// this value is a hack used to distinguish between them - SPStyle *_style; // Not used by DrawingGlyphs + unsigned _key; ///< Some SPItems can have more than one DrawingItem; + /// this value is a hack used to distinguish between them + SPStyle *_style; // Not used by DrawingGlyphs SPStyle *_context_style; // Used for 'context-fill', 'context-stroke' - + float _opacity; - Geom::Affine *_transform; ///< Incremental transform from parent to this item's coords - Geom::Affine _ctm; ///< Total transform from item coords to display coords - Geom::OptIntRect _bbox; ///< Bounding box in display (pixel) coords including stroke + Geom::Affine *_transform; ///< Incremental transform from parent to this item's coords + Geom::Affine _ctm; ///< Total transform from item coords to display coords + Geom::OptIntRect _bbox; ///< Bounding box in display (pixel) coords including stroke Geom::OptIntRect _drawbox; ///< Full visual bounding box - enlarged by filters, shrunk by clips and masks - Geom::OptRect _item_bbox; ///< Geometric bounding box in item's user space. - /// This is used to compute the filter effect region and render in - /// objectBoundingBox units. + Geom::OptRect _item_bbox; ///< Geometric bounding box in item's user space. + /// This is used to compute the filter effect region and render in + /// objectBoundingBox units. DrawingItem *_clip; DrawingItem *_mask; @@ -215,20 +221,20 @@ protected: unsigned _state : 8; unsigned _propagate_state : 8; - unsigned _child_type : 3; // see ChildType enum - unsigned _background_new : 1; ///< Whether enable-background: new is set for this element - unsigned _background_accumulate : 1; ///< Whether this element accumulates background + unsigned _child_type : 3; // see ChildType enum + unsigned _background_new : 1; ///< Whether enable-background: new is set for this element + unsigned _background_accumulate : 1; ///< Whether this element accumulates background /// (has any ancestor with enable-background: new) unsigned _visible : 1; - unsigned _sensitive : 1; ///< Whether this item responds to events - unsigned _cached : 1; ///< Whether the rendering is stored for reuse - unsigned _cached_persistent : 1; ///< If set, will always be cached regardless of score + unsigned _sensitive : 1; ///< Whether this item responds to events + unsigned _cached : 1; ///< Whether the rendering is stored for reuse + unsigned _cached_persistent : 1; ///< If set, will always be cached regardless of score unsigned _has_cache_iterator : 1; ///< If set, _cache_iterator is valid - unsigned _propagate : 1; ///< Whether to call update for all children on next update - //unsigned _renders_opacity : 1; ///< Whether object needs temporary surface for opacity + unsigned _propagate : 1; ///< Whether to call update for all children on next update + // unsigned _renders_opacity : 1; ///< Whether object needs temporary surface for opacity unsigned _pick_children : 1; ///< For groups: if true, children are returned from pick(), /// otherwise the group is returned - unsigned _antialias : 2; ///< antialiasing level (NONE/FAST/GOOD(DEFAULT)/BEST) + unsigned _antialias : 2; ///< antialiasing level (NONE/FAST/GOOD(DEFAULT)/BEST) bool _isolation : 1; SPBlendMode _mix_blend_mode; @@ -236,7 +242,8 @@ protected: friend class Drawing; }; -struct DeleteDisposer { +struct DeleteDisposer +{ void operator()(DrawingItem *item) { delete item; } }; diff --git a/src/display/drawing-pattern.cpp b/src/display/drawing-pattern.cpp index 90bad039b58f5b4efacf653cba90c0e9c533e83a..8ab715e476ca85b1fbf3fa5ff415bf70e8eb601e 100644 --- a/src/display/drawing-pattern.cpp +++ b/src/display/drawing-pattern.cpp @@ -10,9 +10,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/drawing-pattern.h" + #include "display/cairo-utils.h" #include "display/drawing-context.h" -#include "display/drawing-pattern.h" #include "display/drawing-surface.h" namespace Inkscape { @@ -22,16 +23,15 @@ DrawingPattern::DrawingPattern(Drawing &drawing, bool debug) , _pattern_to_user(nullptr) , _overflow_steps(1) , _debug(debug) -{ -} +{} DrawingPattern::~DrawingPattern() { delete _pattern_to_user; // delete NULL; is safe } -void -DrawingPattern::setPatternToUserTransform(Geom::Affine const &new_trans) { +void DrawingPattern::setPatternToUserTransform(Geom::Affine const &new_trans) +{ Geom::Affine current; if (_pattern_to_user) { current = *_pattern_to_user; @@ -50,20 +50,20 @@ DrawingPattern::setPatternToUserTransform(Geom::Affine const &new_trans) { } } -void -DrawingPattern::setTileRect(Geom::Rect const &tile_rect) { +void DrawingPattern::setTileRect(Geom::Rect const &tile_rect) +{ _tile_rect = tile_rect; } -void -DrawingPattern::setOverflow(Geom::Affine initial_transform, int steps, Geom::Affine step_transform) { +void DrawingPattern::setOverflow(Geom::Affine initial_transform, int steps, Geom::Affine step_transform) +{ _overflow_initial_transform = initial_transform; _overflow_steps = steps; _overflow_step_transform = step_transform; } -cairo_pattern_t * -DrawingPattern::renderPattern(float opacity) { +cairo_pattern_t *DrawingPattern::renderPattern(float opacity) +{ bool needs_opacity = (1.0 - opacity) >= 1e-3; bool visible = opacity >= 1e-3; @@ -76,7 +76,7 @@ DrawingPattern::renderPattern(float opacity) { } Geom::Rect pattern_tile = *_tile_rect; - //TODO: If pattern_to_user set it to identity transform + // TODO: If pattern_to_user set it to identity transform // The DrawingSurface class handles the mapping from "logical space" // (coordinates in the rendering) to "physical space" (surface pixels). @@ -86,7 +86,7 @@ DrawingPattern::renderPattern(float opacity) { // based on required resolution (c). Inkscape::DrawingSurface pattern_surface(pattern_tile, _pattern_resolution); Inkscape::DrawingContext dc(pattern_surface); - dc.transform( pattern_surface.drawingTransform().inverse() ); + dc.transform(pattern_surface.drawingTransform().inverse()); pattern_tile *= pattern_surface.drawingTransform(); Geom::IntRect one_tile = pattern_tile.roundOutwards(); @@ -101,12 +101,12 @@ DrawingPattern::renderPattern(float opacity) { dc.paint(); } - //FIXME: What flags to choose? + // FIXME: What flags to choose? if (_overflow_steps == 1) { render(dc, one_tile, RENDER_DEFAULT); } else { - //Overflow transforms need to be transformed to the new coordinate system - //introduced by dc.transform( pattern_surface.drawingTransform().inverse() ); + // Overflow transforms need to be transformed to the new coordinate system + // introduced by dc.transform( pattern_surface.drawingTransform().inverse() ); Geom::Affine dt = pattern_surface.drawingTransform(); Geom::Affine idt = pattern_surface.drawingTransform().inverse(); Geom::Affine initial_transform = idt * _overflow_initial_transform * dt; @@ -133,7 +133,7 @@ DrawingPattern::renderPattern(float opacity) { if (needs_opacity) { dc.popGroupToSource(); // pop raw pattern - dc.paint(opacity); // apply opacity + dc.paint(opacity); // apply opacity } cairo_pattern_t *cp = cairo_pattern_create_for_surface(pattern_surface.raw()); @@ -154,7 +154,8 @@ DrawingPattern::renderPattern(float opacity) { } // TODO investigate if area should be used. -unsigned DrawingPattern::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) +unsigned DrawingPattern::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, + unsigned reset) { UpdateContext pattern_ctx; @@ -167,15 +168,15 @@ unsigned DrawingPattern::_updateItem(Geom::IntRect const &area, UpdateContext co Geom::Coord det_ps2user = _pattern_to_user ? _pattern_to_user->descrim() : 1.0; Geom::Coord det_child_transform = _child_transform ? _child_transform->descrim() : 1.0; const double oversampling = 2.0; - double scale = det_ctm*det_ps2user*det_child_transform * oversampling; - //FIXME: When scale is too big (zooming in a hatch), cairo doesn't render the pattern - //More precisely it fails when setting pattern matrix in DrawingPattern::renderPattern - //Fully correct solution should make use of visible area bbox and change hatch tile rect - //accordingly + double scale = det_ctm * det_ps2user * det_child_transform * oversampling; + // FIXME: When scale is too big (zooming in a hatch), cairo doesn't render the pattern + // More precisely it fails when setting pattern matrix in DrawingPattern::renderPattern + // Fully correct solution should make use of visible area bbox and change hatch tile rect + // accordingly if (scale > 25) { scale = 25; } - Geom::Point c(pattern_tile.dimensions()*scale*oversampling); + Geom::Point c(pattern_tile.dimensions() * scale * oversampling); _pattern_resolution = c.ceil(); Inkscape::DrawingSurface pattern_surface(pattern_tile, _pattern_resolution); diff --git a/src/display/drawing-pattern.h b/src/display/drawing-pattern.h index 86b881ae1f4b1b7d9d006ec3e80c954388f9db0f..0f343fd22fe57f6f882ac0a4af55cd9cc0d60e2d 100644 --- a/src/display/drawing-pattern.h +++ b/src/display/drawing-pattern.h @@ -27,8 +27,7 @@ namespace Inkscape { * It renders it's children to a cairo_pattern_t structure that can be * applied as source for fill or stroke operations. */ -class DrawingPattern - : public DrawingGroup +class DrawingPattern : public DrawingGroup { public: DrawingPattern(Drawing &drawing, bool debug = false); @@ -56,9 +55,9 @@ public: * Returns caito_pattern_t structure that can be set as source surface. */ cairo_pattern_t *renderPattern(float opacity); + protected: - unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, - unsigned flags, unsigned reset) override; + unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) override; Geom::Affine *_pattern_to_user; Geom::Affine _overflow_initial_transform; diff --git a/src/display/drawing-shape.cpp b/src/display/drawing-shape.cpp index 0fde02692e1b2decb6d5e468b2499546448df244..bcbef3b90d6ef64f777295e2073787e6cb0c5269 100644 --- a/src/display/drawing-shape.cpp +++ b/src/display/drawing-shape.cpp @@ -10,26 +10,24 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "display/drawing-shape.h" + #include <2geom/curves.h> -#include <2geom/pathvector.h> #include <2geom/path-sink.h> +#include <2geom/pathvector.h> #include <2geom/svg-path-parser.h> - -#include "preferences.h" -#include "style.h" +#include #include "display/cairo-utils.h" #include "display/canvas-arena.h" #include "display/curve.h" -#include "display/drawing.h" #include "display/drawing-context.h" #include "display/drawing-group.h" -#include "display/drawing-shape.h" - +#include "display/drawing.h" #include "helper/geom-curves.h" #include "helper/geom.h" - +#include "preferences.h" +#include "style.h" #include "svg/svg.h" #include "ui/widget/canvas.h" // Canvas area @@ -42,12 +40,9 @@ DrawingShape::DrawingShape(Drawing &drawing) , _repick_after(0) {} -DrawingShape::~DrawingShape() -{ -} +DrawingShape::~DrawingShape() {} -void -DrawingShape::setPath(SPCurve *curve) +void DrawingShape::setPath(SPCurve *curve) { _markForRendering(); @@ -56,29 +51,26 @@ DrawingShape::setPath(SPCurve *curve) _markForUpdate(STATE_ALL, false); } -void -DrawingShape::setStyle(SPStyle *style, SPStyle *context_style) +void DrawingShape::setStyle(SPStyle *style, SPStyle *context_style) { DrawingItem::setStyle(style, context_style); // Must be first _nrstyle.set(_style, _context_style); } -void -DrawingShape::setChildrenStyle(SPStyle* context_style) +void DrawingShape::setChildrenStyle(SPStyle *context_style) { - DrawingItem::setChildrenStyle( context_style ); + DrawingItem::setChildrenStyle(context_style); _nrstyle.set(_style, _context_style); } -unsigned -DrawingShape::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) +unsigned DrawingShape::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) { Geom::OptRect boundingbox; unsigned beststate = STATE_ALL; // update markers - for (auto & i : _children) { + for (auto &i : _children) { i.update(area, ctx, flags, reset); } @@ -94,7 +86,7 @@ DrawingShape::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, u } } if (beststate & STATE_BBOX) { - for (auto & i : _children) { + for (auto &i : _children) { _bbox.unionWith(i.geometricBounds()); } } @@ -115,12 +107,12 @@ DrawingShape::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, u float width, scale; scale = ctx.ctm.descrim(); width = std::max(0.125f, _nrstyle.stroke_width * scale); - if ( fabs(_nrstyle.stroke_width * scale) > 0.01 ) { // FIXME: this is always true + if (fabs(_nrstyle.stroke_width * scale) > 0.01) { // FIXME: this is always true boundingbox->expandBy(width); } // those pesky miters, now float miterMax = width * _nrstyle.miter_limit; - if ( miterMax > 0.01 ) { + if (miterMax > 0.01) { // grunt mode. we should compute the various miters instead // (one for each point on the curve) boundingbox->expandBy(miterMax); @@ -130,30 +122,26 @@ DrawingShape::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, u _bbox = boundingbox ? boundingbox->roundOutwards() : Geom::OptIntRect(); - if (!_curve || - !_style || - _curve->is_empty()) - { + if (!_curve || !_style || _curve->is_empty()) { return STATE_ALL; } if (beststate & STATE_BBOX) { - for (auto & i : _children) { + for (auto &i : _children) { _bbox.unionWith(i.geometricBounds()); } } return STATE_ALL; } -void -DrawingShape::_renderFill(DrawingContext &dc) +void DrawingShape::_renderFill(DrawingContext &dc) { Inkscape::DrawingContext::Save save(dc); dc.transform(_ctm); - bool has_fill = _nrstyle.prepareFill(dc, _item_bbox, _fill_pattern); + bool has_fill = _nrstyle.prepareFill(dc, _item_bbox, _fill_pattern); - if( has_fill ) { + if (has_fill) { dc.path(_curve->get_pathvector()); _nrstyle.applyFill(dc); dc.fillPreserve(); @@ -161,8 +149,7 @@ DrawingShape::_renderFill(DrawingContext &dc) } } -void -DrawingShape::_renderStroke(DrawingContext &dc) +void DrawingShape::_renderStroke(DrawingContext &dc) { Inkscape::DrawingContext::Save save(dc); dc.transform(_ctm); @@ -170,7 +157,7 @@ DrawingShape::_renderStroke(DrawingContext &dc) bool has_stroke = _nrstyle.prepareStroke(dc, _item_bbox, _stroke_pattern); has_stroke &= (_nrstyle.stroke_width != 0); - if( has_stroke ) { + if (has_stroke) { // TODO: remove segments outside of bbox when no dashes present dc.path(_curve->get_pathvector()); if (_style && _style->vector_effect.stroke) { @@ -194,20 +181,20 @@ DrawingShape::_renderStroke(DrawingContext &dc) } } -void -DrawingShape::_renderMarkers(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) +void DrawingShape::_renderMarkers(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) { // marker rendering - for (auto & i : _children) { + for (auto &i : _children) { i.render(dc, area, flags, stop_at); } } -unsigned -DrawingShape::_renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) +unsigned DrawingShape::_renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) { - if (!_curve || !_style) return RENDER_OK; - if (!area.intersects(_bbox)) return RENDER_OK; // skip if not within bounding box + if (!_curve || !_style) + return RENDER_OK; + if (!area.intersects(_bbox)) + return RENDER_OK; // skip if not within bounding box bool outline = _drawing.outline(); @@ -215,11 +202,13 @@ DrawingShape::_renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigne guint32 rgba = _drawing.outlinecolor; // paint-order doesn't matter - { Inkscape::DrawingContext::Save save(dc); + { + Inkscape::DrawingContext::Save save(dc); dc.transform(_ctm); dc.path(_curve->get_pathvector()); } - { Inkscape::DrawingContext::Save save(dc); + { + Inkscape::DrawingContext::Save save(dc); dc.setSource(rgba); dc.setLineWidth(0.5); dc.setTolerance(0.5); @@ -228,10 +217,9 @@ DrawingShape::_renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigne _renderMarkers(dc, area, flags, stop_at); return RENDER_OK; - } - if( _nrstyle.paint_order_layer[0] == NRStyle::PAINT_ORDER_NORMAL ) { + if (_nrstyle.paint_order_layer[0] == NRStyle::PAINT_ORDER_NORMAL) { // This is the most common case, special case so we don't call get_pathvector(), etc. twice { @@ -239,11 +227,10 @@ DrawingShape::_renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigne Inkscape::DrawingContext::Save save(dc); dc.transform(_ctm); - // update fill and stroke paints. // this cannot be done during nr_arena_shape_update, because we need a Cairo context // to render svg:pattern - bool has_fill = _nrstyle.prepareFill(dc, _item_bbox, _fill_pattern); + bool has_fill = _nrstyle.prepareFill(dc, _item_bbox, _fill_pattern); bool has_stroke = _nrstyle.prepareStroke(dc, _item_bbox, _stroke_pattern); has_stroke &= (_nrstyle.stroke_width != 0); if (has_fill || has_stroke) { @@ -273,15 +260,14 @@ DrawingShape::_renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigne dc.strokePreserve(); } dc.newPath(); // clear path - } // has fill or stroke pattern + } // has fill or stroke pattern } _renderMarkers(dc, area, flags, stop_at); return RENDER_OK; - } // Handle different paint orders - for (auto & i : _nrstyle.paint_order_layer) { + for (auto &i : _nrstyle.paint_order_layer) { switch (i) { case NRStyle::PAINT_ORDER_FILL: _renderFill(dc); @@ -302,7 +288,8 @@ DrawingShape::_renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigne void DrawingShape::_clipItem(DrawingContext &dc, Geom::IntRect const & /*area*/) { - if (!_curve) return; + if (!_curve) + return; Inkscape::DrawingContext::Save save(dc); // handle clip-rule @@ -318,8 +305,7 @@ void DrawingShape::_clipItem(DrawingContext &dc, Geom::IntRect const & /*area*/) dc.fill(); } -DrawingItem * -DrawingShape::_pickItem(Geom::Point const &p, double delta, unsigned flags) +DrawingItem *DrawingShape::_pickItem(Geom::Point const &p, double delta, unsigned flags) { if (_repick_after > 0) --_repick_after; @@ -327,12 +313,14 @@ DrawingShape::_pickItem(Geom::Point const &p, double delta, unsigned flags) if (_repick_after > 0) // we are a slow, huge path return _last_pick; // skip this pick, returning what was returned last time - if (!_curve) return nullptr; - if (!_style) return nullptr; + if (!_curve) + return nullptr; + if (!_style) + return nullptr; bool outline = _drawing.outline() || _drawing.getOutlineSensitive(); bool pick_as_clip = flags & PICK_AS_CLIP; - if (SP_SCALE24_TO_FLOAT(_style->opacity.value) == 0 && !outline && !pick_as_clip) + if (SP_SCALE24_TO_FLOAT(_style->opacity.value) == 0 && !outline && !pick_as_clip) // fully transparent, no pick unless outline mode return nullptr; @@ -355,23 +343,25 @@ DrawingShape::_pickItem(Geom::Point const &p, double delta, unsigned flags) double dist = Geom::infinity(); int wind = 0; - bool needfill = pick_as_clip || (_nrstyle.fill.type != NRStyle::PAINT_NONE && - _nrstyle.fill.opacity > 1e-3 && !outline); - bool wind_evenodd = pick_as_clip ? (_style->clip_rule.computed == SP_WIND_RULE_EVENODD) : - (_style->fill_rule.computed == SP_WIND_RULE_EVENODD); + bool needfill = + pick_as_clip || (_nrstyle.fill.type != NRStyle::PAINT_NONE && _nrstyle.fill.opacity > 1e-3 && !outline); + bool wind_evenodd = pick_as_clip ? (_style->clip_rule.computed == SP_WIND_RULE_EVENODD) + : (_style->fill_rule.computed == SP_WIND_RULE_EVENODD); // actual shape picking if (_drawing.arena()) { Geom::Rect viewbox = _drawing.arena()->item.canvas->get_area_world(); - viewbox.expandBy (width); - pathv_matrix_point_bbox_wind_distance(_curve->get_pathvector(), _ctm, p, nullptr, needfill? &wind : nullptr, &dist, 0.5, &viewbox); + viewbox.expandBy(width); + pathv_matrix_point_bbox_wind_distance(_curve->get_pathvector(), _ctm, p, nullptr, needfill ? &wind : nullptr, + &dist, 0.5, &viewbox); } else { - pathv_matrix_point_bbox_wind_distance(_curve->get_pathvector(), _ctm, p, nullptr, needfill? &wind : nullptr, &dist, 0.5, nullptr); + pathv_matrix_point_bbox_wind_distance(_curve->get_pathvector(), _ctm, p, nullptr, needfill ? &wind : nullptr, + &dist, 0.5, nullptr); } gint64 tfinish = g_get_monotonic_time(); gint64 this_pick = tfinish - tstart; - //g_print ("pick time %lu\n", this_pick); + // g_print ("pick time %lu\n", this_pick); if (this_pick > 10000) { // slow picking, remember to skip several new picks _repick_after = this_pick / 5000; } @@ -401,7 +391,7 @@ DrawingShape::_pickItem(Geom::Point const &p, double delta, unsigned flags) } // if not picked on the shape itself, try its markers - for (auto & i : _children) { + for (auto &i : _children) { DrawingItem *ret = i.pick(p, delta, flags & ~PICK_STICKY); if (ret) { _last_pick = this; @@ -413,8 +403,7 @@ DrawingShape::_pickItem(Geom::Point const &p, double delta, unsigned flags) return nullptr; } -bool -DrawingShape::_canClip() +bool DrawingShape::_canClip() { return true; } diff --git a/src/display/drawing-shape.h b/src/display/drawing-shape.h index 319e0e12ceb1c43171c95d449b2ba1d4b688eadb..cc35c805baee80cba44de6b912b039b93ec6a3ab 100644 --- a/src/display/drawing-shape.h +++ b/src/display/drawing-shape.h @@ -13,18 +13,17 @@ #ifndef SEEN_INKSCAPE_DISPLAY_DRAWING_SHAPE_H #define SEEN_INKSCAPE_DISPLAY_DRAWING_SHAPE_H +#include + #include "display/drawing-item.h" #include "display/nr-style.h" -#include - class SPStyle; class SPCurve; namespace Inkscape { -class DrawingShape - : public DrawingItem +class DrawingShape : public DrawingItem { public: DrawingShape(Drawing &drawing); @@ -35,18 +34,15 @@ public: void setChildrenStyle(SPStyle *context_style) override; protected: - unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, - unsigned flags, unsigned reset) override; - unsigned _renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, - DrawingItem *stop_at) override; + unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) override; + unsigned _renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) override; void _clipItem(DrawingContext &dc, Geom::IntRect const &area) override; DrawingItem *_pickItem(Geom::Point const &p, double delta, unsigned flags) override; bool _canClip() override; void _renderFill(DrawingContext &dc); void _renderStroke(DrawingContext &dc); - void _renderMarkers(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, - DrawingItem *stop_at); + void _renderMarkers(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at); std::unique_ptr _curve; NRStyle _nrstyle; diff --git a/src/display/drawing-surface.cpp b/src/display/drawing-surface.cpp index c84e358f861354c00e90a7f6b5705d25b377737c..0d863cf2ebc1b182cd708a31096b438c757d361c 100644 --- a/src/display/drawing-surface.cpp +++ b/src/display/drawing-surface.cpp @@ -12,15 +12,15 @@ //#include #include "display/drawing-surface.h" -#include "display/drawing-context.h" + #include "display/cairo-utils.h" +#include "display/drawing-context.h" namespace Inkscape { using Geom::X; using Geom::Y; - /** * @class DrawingSurface * Drawing surface that remembers its origin. @@ -70,7 +70,7 @@ DrawingSurface::DrawingSurface(Geom::Rect const &logbox, Geom::IntPoint const &p assert(_device_scale > 0); } -/** +/** * Wrap a cairo_surface_t. * This constructor will take an extra reference on @a surface, which will * be released on destruction. @@ -84,15 +84,15 @@ DrawingSurface::DrawingSurface(cairo_surface_t *surface, Geom::Point const &orig double x_scale = 0; double y_scale = 0; - cairo_surface_get_device_scale( surface, &x_scale, &y_scale); + cairo_surface_get_device_scale(surface, &x_scale, &y_scale); if (x_scale != y_scale) { std::cerr << "DrawingSurface::DrawingSurface: non-uniform device scale!" << std::endl; } _device_scale = x_scale; assert(_device_scale > 0); - _pixels[X] = cairo_image_surface_get_width(surface)/_device_scale; - _pixels[Y] = cairo_image_surface_get_height(surface)/_device_scale; + _pixels[X] = cairo_image_surface_get_width(surface) / _device_scale; + _pixels[Y] = cairo_image_surface_get_height(surface) / _device_scale; } DrawingSurface::~DrawingSurface() @@ -102,65 +102,56 @@ DrawingSurface::~DrawingSurface() } /// Get the logical extents of the surface. -Geom::Rect -DrawingSurface::area() const +Geom::Rect DrawingSurface::area() const { Geom::Rect r = Geom::Rect::from_xywh(_origin, dimensions()); return r; } /// Get the pixel dimensions of the surface -Geom::IntPoint -DrawingSurface::pixels() const +Geom::IntPoint DrawingSurface::pixels() const { return _pixels; } /// Get the logical width and weight of the surface as a point. -Geom::Point -DrawingSurface::dimensions() const +Geom::Point DrawingSurface::dimensions() const { Geom::Point logical_dims(_pixels[X] / _scale[X], _pixels[Y] / _scale[Y]); return logical_dims; } -Geom::Point -DrawingSurface::origin() const +Geom::Point DrawingSurface::origin() const { return _origin; } -Geom::Scale -DrawingSurface::scale() const +Geom::Scale DrawingSurface::scale() const { return _scale; } /// Device scale for HiDPI screens -int -DrawingSurface::device_scale() const +int DrawingSurface::device_scale() const { return _device_scale; } /// Get the transformation applied to the drawing context on construction. -Geom::Affine -DrawingSurface::drawingTransform() const +Geom::Affine DrawingSurface::drawingTransform() const { Geom::Affine ret = Geom::Translate(-_origin) * _scale; return ret; } -cairo_surface_type_t -DrawingSurface::type() const +cairo_surface_type_t DrawingSurface::type() const { // currently hardcoded return CAIRO_SURFACE_TYPE_IMAGE; } /// Drop contents of the surface and release the underlying Cairo object. -void -DrawingSurface::dropContents() +void DrawingSurface::dropContents() { if (_surface) { cairo_surface_destroy(_surface); @@ -172,14 +163,12 @@ DrawingSurface::dropContents() * Create a drawing context for this surface. * It's better to use the surface constructor of DrawingContext. */ -cairo_t * -DrawingSurface::createRawContext() +cairo_t *DrawingSurface::createRawContext() { // deferred allocation if (!_surface) { - _surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, - _pixels[X] * _device_scale, - _pixels[Y] * _device_scale); + _surface = + cairo_image_surface_create(CAIRO_FORMAT_ARGB32, _pixels[X] * _device_scale, _pixels[Y] * _device_scale); cairo_surface_set_device_scale(_surface, _device_scale, _device_scale); } cairo_t *ct = cairo_create(_surface); @@ -190,8 +179,7 @@ DrawingSurface::createRawContext() return ct; } -Geom::IntRect -DrawingSurface::pixelArea() const +Geom::IntRect DrawingSurface::pixelArea() const { Geom::IntRect ret = Geom::IntRect::from_xywh(_origin.round(), _pixels); return ret; @@ -210,24 +198,22 @@ DrawingCache::~DrawingCache() cairo_region_destroy(_clean_region); } -void -DrawingCache::markDirty(Geom::IntRect const &area) +void DrawingCache::markDirty(Geom::IntRect const &area) { cairo_rectangle_int_t dirty = _convertRect(area); cairo_region_subtract_rectangle(_clean_region, &dirty); } -void -DrawingCache::markClean(Geom::IntRect const &area) +void DrawingCache::markClean(Geom::IntRect const &area) { Geom::OptIntRect r = Geom::intersect(area, pixelArea()); - if (!r) return; + if (!r) + return; cairo_rectangle_int_t clean = _convertRect(*r); cairo_region_union_rectangle(_clean_region, &clean); } /// Call this during the update phase to schedule a transformation of the cache. -void -DrawingCache::scheduleTransform(Geom::IntRect const &new_area, Geom::Affine const &trans) +void DrawingCache::scheduleTransform(Geom::IntRect const &new_area, Geom::Affine const &trans) { _pending_area = new_area; _pending_transform *= trans; @@ -235,12 +221,12 @@ DrawingCache::scheduleTransform(Geom::IntRect const &new_area, Geom::Affine cons /// Transforms the cache according to the transform specified during the update phase. /// Call this during render phase, before painting. -void -DrawingCache::prepare() +void DrawingCache::prepare() { Geom::IntRect old_area = pixelArea(); bool is_identity = _pending_transform.isIdentity(); - if (is_identity && _pending_area == old_area) return; // no change + if (is_identity && _pending_area == old_area) + return; // no change bool is_integer_translation = is_identity; if (!is_identity && _pending_transform.isTranslation()) { @@ -288,7 +274,7 @@ DrawingCache::prepare() _clean_region = cairo_region_create(); } - //std::cout << _pending_transform << old_area << _pending_area << std::endl; + // std::cout << _pending_transform << old_area << _pending_area << std::endl; cairo_surface_destroy(old_surface); _pending_transform.setIdentity(); } @@ -299,7 +285,8 @@ DrawingCache::prepare() */ void DrawingCache::paintFromCache(DrawingContext &dc, Geom::OptIntRect &area, bool is_filter) { - if (!area) return; + if (!area) + return; // We subtract the clean region from the area, then get the bounds // of the resulting region. This is the area that needs to be repainted @@ -339,8 +326,7 @@ void DrawingCache::paintFromCache(DrawingContext &dc, Geom::OptIntRect &area, bo } // debugging utility -void -DrawingCache::_dumpCache(Geom::OptIntRect const &area) +void DrawingCache::_dumpCache(Geom::OptIntRect const &area) { static int dumpnr = 0; cairo_surface_t *surface = ink_cairo_surface_copy(_surface); @@ -353,11 +339,11 @@ DrawingCache::_dumpCache(Geom::OptIntRect const &area) cairo_region_get_rectangle(_clean_region, i, &tmp); dc.rectangle(_convertRect(tmp)); } - dc.setSource(0,1,0,0.1); + dc.setSource(0, 1, 0, 0.1); dc.fill(); } dc.rectangle(*area); - dc.setSource(1,0,0,0.1); + dc.setSource(1, 0, 0, 0.1); dc.fill(); char *fn = g_strdup_printf("dump%d.png", dumpnr++); cairo_surface_write_to_png(surface, fn); @@ -365,8 +351,7 @@ DrawingCache::_dumpCache(Geom::OptIntRect const &area) g_free(fn); } -cairo_rectangle_int_t -DrawingCache::_convertRect(Geom::IntRect const &area) +cairo_rectangle_int_t DrawingCache::_convertRect(Geom::IntRect const &area) { cairo_rectangle_int_t ret; ret.x = area.left(); @@ -376,12 +361,9 @@ DrawingCache::_convertRect(Geom::IntRect const &area) return ret; } -Geom::IntRect -DrawingCache::_convertRect(cairo_rectangle_int_t const &r) +Geom::IntRect DrawingCache::_convertRect(cairo_rectangle_int_t const &r) { - Geom::IntRect ret = Geom::IntRect::from_xywh( - r.x, r.y, - r.width, r.height); + Geom::IntRect ret = Geom::IntRect::from_xywh(r.x, r.y, r.width, r.height); return ret; } diff --git a/src/display/drawing-surface.h b/src/display/drawing-surface.h index 0522b53e611aa7df7114d3d8f5636e2171ff6b5d..37ef8a72b7f954aa0f8a7792a25e686ec3e93382 100644 --- a/src/display/drawing-surface.h +++ b/src/display/drawing-surface.h @@ -13,10 +13,10 @@ #ifndef SEEN_INKSCAPE_DISPLAY_DRAWING_SURFACE_H #define SEEN_INKSCAPE_DISPLAY_DRAWING_SURFACE_H -#include #include <2geom/affine.h> #include <2geom/rect.h> #include <2geom/transforms.h> +#include extern "C" { typedef struct _cairo cairo_t; @@ -61,8 +61,7 @@ protected: friend class DrawingContext; }; -class DrawingCache - : public DrawingSurface +class DrawingCache : public DrawingSurface { public: explicit DrawingCache(Geom::IntRect const &area, int device_scale = 1); @@ -74,10 +73,11 @@ public: void prepare(); void paintFromCache(DrawingContext &dc, Geom::OptIntRect &area, bool is_filter); - protected: +protected: cairo_region_t *_clean_region; Geom::IntRect _pending_area; Geom::Affine _pending_transform; + private: void _dumpCache(Geom::OptIntRect const &area); static cairo_rectangle_int_t _convertRect(Geom::IntRect const &r); diff --git a/src/display/drawing-text.cpp b/src/display/drawing-text.cpp index 391c36e1b8240c209900076193b5e3e081a48b35..543196063016ed49f34f9ee4dceaa7c2fd0b80c2 100644 --- a/src/display/drawing-text.cpp +++ b/src/display/drawing-text.cpp @@ -10,23 +10,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "2geom/pathvector.h" - -#include "style.h" +#include "display/drawing-text.h" +#include "2geom/pathvector.h" #include "display/cairo-utils.h" #include "display/drawing-context.h" #include "display/drawing-surface.h" -#include "display/drawing-text.h" #include "display/drawing.h" - #include "helper/geom.h" - #include "libnrtype/font-instance.h" +#include "style.h" namespace Inkscape { - DrawingGlyphs::DrawingGlyphs(Drawing &drawing) : DrawingItem(drawing) , _font(nullptr) @@ -41,29 +37,29 @@ DrawingGlyphs::~DrawingGlyphs() } } -void -DrawingGlyphs::setGlyph(font_instance *font, int glyph, Geom::Affine const &trans) +void DrawingGlyphs::setGlyph(font_instance *font, int glyph, Geom::Affine const &trans) { _markForRendering(); setTransform(trans); - if (font) font->Ref(); - if (_font) _font->Unref(); + if (font) + font->Ref(); + if (_font) + _font->Unref(); _font = font; _glyph = glyph; _markForUpdate(STATE_ALL, false); } -void -DrawingGlyphs::setStyle(SPStyle * /*style*/, SPStyle * /*context_style*/) +void DrawingGlyphs::setStyle(SPStyle * /*style*/, SPStyle * /*context_style*/) { std::cerr << "DrawingGlyphs: Use parent style" << std::endl; } - -unsigned DrawingGlyphs::_updateItem(Geom::IntRect const &/*area*/, UpdateContext const &ctx, unsigned /*flags*/, unsigned /*reset*/) +unsigned DrawingGlyphs::_updateItem(Geom::IntRect const & /*area*/, UpdateContext const &ctx, unsigned /*flags*/, + unsigned /*reset*/) { DrawingText *ggroup = dynamic_cast(_parent); if (!ggroup) { @@ -74,7 +70,6 @@ unsigned DrawingGlyphs::_updateItem(Geom::IntRect const &/*area*/, UpdateContext return STATE_ALL; } - _pick_bbox = Geom::IntRect(); _bbox = Geom::IntRect(); @@ -103,12 +98,14 @@ unsigned DrawingGlyphs::_updateItem(Geom::IntRect const &/*area*/, UpdateContext if (_drawable) { Geom::OptRect tiltb = bounds_exact(*_font->PathVector(_glyph)); if (tiltb) { - Geom::Rect bigbox(Geom::Point(tiltb->left(),-_dsc*scale_bigbox*1.1),Geom::Point(tiltb->right(),_asc*scale_bigbox*1.1)); + Geom::Rect bigbox(Geom::Point(tiltb->left(), -_dsc * scale_bigbox * 1.1), + Geom::Point(tiltb->right(), _asc * scale_bigbox * 1.1)); b = bigbox * ctx.ctm; } } if (b.hasZeroArea()) { // Fallback, spaces mostly - Geom::Rect bigbox(Geom::Point(0.0, -_dsc*scale_bigbox*1.1),Geom::Point(_width*scale_bigbox, _asc*scale_bigbox*1.1)); + Geom::Rect bigbox(Geom::Point(0.0, -_dsc * scale_bigbox * 1.1), + Geom::Point(_width * scale_bigbox, _asc * scale_bigbox * 1.1)); b = bigbox * ctx.ctm; } @@ -138,10 +135,10 @@ unsigned DrawingGlyphs::_updateItem(Geom::IntRect const &/*area*/, UpdateContext } } if (!pb) { // Fallback - Geom::Rect pbigbox(Geom::Point(0.0, _asc*scale_bigbox*0.66),Geom::Point(_width*scale_bigbox, 0.0)); + Geom::Rect pbigbox(Geom::Point(0.0, _asc * scale_bigbox * 0.66), Geom::Point(_width * scale_bigbox, 0.0)); pb = pbigbox * ctx.ctm; } - + #if 0 /* FIXME if this is commented out then not even an approximation of pick on decorations */ /* adjust the pick box up or down to include the decorations. @@ -167,16 +164,16 @@ unsigned DrawingGlyphs::_updateItem(Geom::IntRect const &/*area*/, UpdateContext scale /= _transform->descrim(); // FIXME temporary hack } float width = MAX(0.125, ggroup->_nrstyle.stroke_width * scale); - if ( fabs(ggroup->_nrstyle.stroke_width * scale) > 0.01 ) { // FIXME: this is always true + if (fabs(ggroup->_nrstyle.stroke_width * scale) > 0.01) { // FIXME: this is always true b.expandBy(0.5 * width); pb->expandBy(0.5 * width); } - // save bbox without miters for picking + // save bbox without miters for picking _pick_bbox = pb->roundOutwards(); float miterMax = width * ggroup->_nrstyle.miter_limit; - if ( miterMax > 0.01 ) { + if (miterMax > 0.01) { // grunt mode. we should compute the various miters instead // (one for each point on the curve) b.expandBy(miterMax); @@ -196,8 +193,8 @@ DrawingItem *DrawingGlyphs::_pickItem(Geom::Point const &p, double /*delta*/, un throw InvalidItemException(); } DrawingItem *result = nullptr; - bool invisible = (ggroup->_nrstyle.fill.type == NRStyle::PAINT_NONE) && - (ggroup->_nrstyle.stroke.type == NRStyle::PAINT_NONE); + bool invisible = + (ggroup->_nrstyle.fill.type == NRStyle::PAINT_NONE) && (ggroup->_nrstyle.stroke.type == NRStyle::PAINT_NONE); if (_font && _bbox && (_drawing.outline() || _drawing.getOutlineSensitive() || !invisible)) { // With text we take a simple approach: pick if the point is in a character bbox @@ -211,76 +208,73 @@ DrawingItem *DrawingGlyphs::_pickItem(Geom::Point const &p, double /*delta*/, un return result; } - - DrawingText::DrawingText(Drawing &drawing) : DrawingGroup(drawing) {} -DrawingText::~DrawingText() -= default; +DrawingText::~DrawingText() = default; -void -DrawingText::clear() +void DrawingText::clear() { _markForRendering(); _children.clear_and_dispose(DeleteDisposer()); } -bool -DrawingText::addComponent(font_instance *font, int glyph, Geom::Affine const &trans, - float width, float ascent, float descent, float phase_length) +bool DrawingText::addComponent(font_instance *font, int glyph, Geom::Affine const &trans, float width, float ascent, + float descent, float phase_length) { -/* original, did not save a glyph for white space characters, causes problems for text-decoration - if (!font || !font->PathVector(glyph)) { - return(false); - } -*/ - if (!font)return(false); + /* original, did not save a glyph for white space characters, causes problems for text-decoration + if (!font || !font->PathVector(glyph)) { + return(false); + } + */ + if (!font) + return (false); _markForRendering(); DrawingGlyphs *ng = new DrawingGlyphs(_drawing); ng->setGlyph(font, glyph, trans); - if(font->PathVector(glyph)){ ng->_drawable = true; } - else { ng->_drawable = false; } - ng->_width = width; // used especially when _drawable = false, otherwise, it is the advance of the font - ng->_asc = ascent; // of font, not of this one character - ng->_dsc = descent; // of font, not of this one character - ng->_pl = phase_length; // used for phase of dots, dashes, and wavy + if (font->PathVector(glyph)) { + ng->_drawable = true; + } else { + ng->_drawable = false; + } + ng->_width = width; // used especially when _drawable = false, otherwise, it is the advance of the font + ng->_asc = ascent; // of font, not of this one character + ng->_dsc = descent; // of font, not of this one character + ng->_pl = phase_length; // used for phase of dots, dashes, and wavy appendChild(ng); - return(true); + return (true); } -void -DrawingText::setStyle(SPStyle *style, SPStyle *context_style) +void DrawingText::setStyle(SPStyle *style, SPStyle *context_style) { DrawingGroup::setStyle(style, context_style); // Must be first _nrstyle.set(_style, _context_style); } -void -DrawingText::setChildrenStyle(SPStyle* context_style) +void DrawingText::setChildrenStyle(SPStyle *context_style) { - DrawingGroup::setChildrenStyle( context_style ); + DrawingGroup::setChildrenStyle(context_style); _nrstyle.set(_style, _context_style); } -unsigned -DrawingText::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) +unsigned DrawingText::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) { _nrstyle.update(); return DrawingGroup::_updateItem(area, ctx, flags, reset); } -void DrawingText::decorateStyle(DrawingContext &dc, double vextent, double xphase, Geom::Point const &p1, Geom::Point const &p2, double thickness) +void DrawingText::decorateStyle(DrawingContext &dc, double vextent, double xphase, Geom::Point const &p1, + Geom::Point const &p2, double thickness) { - double wave[16]={ + double wave[16] = { // clang-format off 0.000000, 0.382499, 0.706825, 0.923651, 1.000000, 0.923651, 0.706825, 0.382499, 0.000000, -0.382499, -0.706825, -0.923651, -1.000000, -0.923651, -0.706825, -0.382499, // clang-format on }; - int dashes[16]={ + int dashes[16] = { // clang-format off 8, 7, 6, 5, 4, 3, 2, 1, @@ -288,7 +282,7 @@ void DrawingText::decorateStyle(DrawingContext &dc, double vextent, double xphas -4, -3, -2, -1 // clang-format on }; - int dots[16]={ + int dots[16] = { // clang-format off 4, 3, 2, 1, -4, -3, -2, -1, @@ -296,8 +290,8 @@ void DrawingText::decorateStyle(DrawingContext &dc, double vextent, double xphas -4, -3, -2, -1 // clang-format on }; - double step = vextent/32.0; - unsigned i = 15 & (unsigned) round(xphase/step); // xphase is >= 0.0 + double step = vextent / 32.0; + unsigned i = 15 & (unsigned)round(xphase / step); // xphase is >= 0.0 /* For most spans draw the last little bit right to p2 or even a little beyond. This allows decoration continuity within the line, and does not step outside the clip box off the end @@ -305,39 +299,40 @@ void DrawingText::decorateStyle(DrawingContext &dc, double vextent, double xphas text is dragged it may "spray" pixels. */ /* snap to nearest step in X */ - Geom::Point ps = Geom::Point(step * round(p1[Geom::X]/step),p1[Geom::Y]); - Geom::Point pf = Geom::Point(step * round(p2[Geom::X]/step),p2[Geom::Y]); - Geom::Point poff = Geom::Point(0,thickness/2.0); - - if(_nrstyle.text_decoration_style & NRStyle::TEXT_DECORATION_STYLE_ISDOUBLE){ - ps -= Geom::Point(0, vextent/12.0); - pf -= Geom::Point(0, vextent/12.0); - dc.rectangle( Geom::Rect(ps + poff, pf - poff)); - ps += Geom::Point(0, vextent/6.0); - pf += Geom::Point(0, vextent/6.0); - dc.rectangle( Geom::Rect(ps + poff, pf - poff)); + Geom::Point ps = Geom::Point(step * round(p1[Geom::X] / step), p1[Geom::Y]); + Geom::Point pf = Geom::Point(step * round(p2[Geom::X] / step), p2[Geom::Y]); + Geom::Point poff = Geom::Point(0, thickness / 2.0); + + if (_nrstyle.text_decoration_style & NRStyle::TEXT_DECORATION_STYLE_ISDOUBLE) { + ps -= Geom::Point(0, vextent / 12.0); + pf -= Geom::Point(0, vextent / 12.0); + dc.rectangle(Geom::Rect(ps + poff, pf - poff)); + ps += Geom::Point(0, vextent / 6.0); + pf += Geom::Point(0, vextent / 6.0); + dc.rectangle(Geom::Rect(ps + poff, pf - poff)); } /* The next three have a problem in that they are phase dependent. The bits of a line are not necessarily passing through this routine in order, so we have to use the xphase information to figure where in each of their cycles to start. Only accurate to 1 part in 16. Huge positive offset should keep the phase calculation from ever being negative. */ - else if(_nrstyle.text_decoration_style & NRStyle::TEXT_DECORATION_STYLE_DOTTED){ + else if (_nrstyle.text_decoration_style & NRStyle::TEXT_DECORATION_STYLE_DOTTED) { // FIXME: Per spec, this should produce round dots. Geom::Point pv = ps; - while(true){ + while (true) { Geom::Point pvlast = pv; - if(dots[i]>0){ - if(pv[Geom::X] > pf[Geom::X]) break; + if (dots[i] > 0) { + if (pv[Geom::X] > pf[Geom::X]) + break; pv += Geom::Point(step * (double)dots[i], 0.0); - if(pv[Geom::X]>= pf[Geom::X]){ + if (pv[Geom::X] >= pf[Geom::X]) { // Last dot - dc.rectangle( Geom::Rect(pvlast + poff, pf - poff)); + dc.rectangle(Geom::Rect(pvlast + poff, pf - poff)); break; } else { - dc.rectangle( Geom::Rect(pvlast + poff, pv - poff)); + dc.rectangle(Geom::Rect(pvlast + poff, pv - poff)); } pv += Geom::Point(step * 4.0, 0.0); @@ -345,24 +340,24 @@ void DrawingText::decorateStyle(DrawingContext &dc, double vextent, double xphas } else { pv += Geom::Point(step * -(double)dots[i], 0.0); } - i = 0; // once in phase, it stays in phase + i = 0; // once in phase, it stays in phase } - } - else if(_nrstyle.text_decoration_style & NRStyle::TEXT_DECORATION_STYLE_DASHED){ + } else if (_nrstyle.text_decoration_style & NRStyle::TEXT_DECORATION_STYLE_DASHED) { Geom::Point pv = ps; - while(true){ + while (true) { Geom::Point pvlast = pv; - if(dashes[i]>0){ - if(pv[Geom::X]> pf[Geom::X]) break; + if (dashes[i] > 0) { + if (pv[Geom::X] > pf[Geom::X]) + break; pv += Geom::Point(step * (double)dashes[i], 0.0); - if(pv[Geom::X]>= pf[Geom::X]){ + if (pv[Geom::X] >= pf[Geom::X]) { // Last dash - dc.rectangle( Geom::Rect(pvlast + poff, pf - poff)); + dc.rectangle(Geom::Rect(pvlast + poff, pf - poff)); break; } else { - dc.rectangle( Geom::Rect(pvlast + poff, pv - poff)); + dc.rectangle(Geom::Rect(pvlast + poff, pv - poff)); } pv += Geom::Point(step * 8.0, 0.0); @@ -370,93 +365,96 @@ void DrawingText::decorateStyle(DrawingContext &dc, double vextent, double xphas } else { pv += Geom::Point(step * -(double)dashes[i], 0.0); } - i = 0; // once in phase, it stays in phase + i = 0; // once in phase, it stays in phase } - } - else if(_nrstyle.text_decoration_style & NRStyle::TEXT_DECORATION_STYLE_WAVY){ - double amp = vextent/10.0; - double x = ps[Geom::X]; - double y = ps[Geom::Y] + poff[Geom::Y]; + } else if (_nrstyle.text_decoration_style & NRStyle::TEXT_DECORATION_STYLE_WAVY) { + double amp = vextent / 10.0; + double x = ps[Geom::X]; + double y = ps[Geom::Y] + poff[Geom::Y]; dc.moveTo(Geom::Point(x, y + amp * wave[i])); - while(true){ - i = ((i + 1) & 15); - x += step; - dc.lineTo(Geom::Point(x, y + amp * wave[i])); - if(x >= pf[Geom::X])break; + while (true) { + i = ((i + 1) & 15); + x += step; + dc.lineTo(Geom::Point(x, y + amp * wave[i])); + if (x >= pf[Geom::X]) + break; } y = ps[Geom::Y] - poff[Geom::Y]; dc.lineTo(Geom::Point(x, y + amp * wave[i])); - while(true){ - i = ((i - 1) & 15); - x -= step; - dc.lineTo(Geom::Point(x, y + amp * wave[i])); - if(x <= ps[Geom::X])break; + while (true) { + i = ((i - 1) & 15); + x -= step; + dc.lineTo(Geom::Point(x, y + amp * wave[i])); + if (x <= ps[Geom::X]) + break; } dc.closePath(); - } - else { // TEXT_DECORATION_STYLE_SOLID, also default in case it was not set for some reason - dc.rectangle( Geom::Rect(ps + poff, pf - poff)); + } else { // TEXT_DECORATION_STYLE_SOLID, also default in case it was not set for some reason + dc.rectangle(Geom::Rect(ps + poff, pf - poff)); } } /* returns scaled line thickness */ void DrawingText::decorateItem(DrawingContext &dc, double phase_length, bool under) { - if ( _nrstyle.font_size <= 1.0e-32 )return; // might cause a divide by zero or overflow and nothing would be visible anyway - double tsp_width_adj = _nrstyle.tspan_width / _nrstyle.font_size; - double tsp_asc_adj = _nrstyle.ascender / _nrstyle.font_size; - double tsp_size_adj = (_nrstyle.ascender + _nrstyle.descender) / _nrstyle.font_size; + if (_nrstyle.font_size <= 1.0e-32) + return; // might cause a divide by zero or overflow and nothing would be visible anyway + double tsp_width_adj = _nrstyle.tspan_width / _nrstyle.font_size; + double tsp_asc_adj = _nrstyle.ascender / _nrstyle.font_size; + double tsp_size_adj = (_nrstyle.ascender + _nrstyle.descender) / _nrstyle.font_size; - double final_underline_thickness = CLAMP(_nrstyle.underline_thickness, tsp_size_adj/30.0, tsp_size_adj/10.0); - double final_line_through_thickness = CLAMP(_nrstyle.line_through_thickness, tsp_size_adj/30.0, tsp_size_adj/10.0); + double final_underline_thickness = CLAMP(_nrstyle.underline_thickness, tsp_size_adj / 30.0, tsp_size_adj / 10.0); + double final_line_through_thickness = + CLAMP(_nrstyle.line_through_thickness, tsp_size_adj / 30.0, tsp_size_adj / 10.0); - double xphase = phase_length/ _nrstyle.font_size; // used to figure out phase of patterns + double xphase = phase_length / _nrstyle.font_size; // used to figure out phase of patterns Geom::Point p1; Geom::Point p2; // All lines must be the same thickness, in combinations, line_through trumps underline double thickness = final_underline_thickness; - if ( thickness <= 1.0e-32 )return; // might cause a divide by zero or overflow and nothing would be visible anyway + if (thickness <= 1.0e-32) + return; // might cause a divide by zero or overflow and nothing would be visible anyway dc.setTolerance(0.5); // Is this really necessary... could effect dots. - if( under ) { - - if(_nrstyle.text_decoration_line & NRStyle::TEXT_DECORATION_LINE_UNDERLINE){ - p1 = Geom::Point(0.0, -_nrstyle.underline_position); - p2 = Geom::Point(tsp_width_adj,-_nrstyle.underline_position); + if (under) { + if (_nrstyle.text_decoration_line & NRStyle::TEXT_DECORATION_LINE_UNDERLINE) { + p1 = Geom::Point(0.0, -_nrstyle.underline_position); + p2 = Geom::Point(tsp_width_adj, -_nrstyle.underline_position); decorateStyle(dc, tsp_size_adj, xphase, p1, p2, thickness); } - if(_nrstyle.text_decoration_line & NRStyle::TEXT_DECORATION_LINE_OVERLINE){ - p1 = Geom::Point(0.0, tsp_asc_adj -_nrstyle.underline_position + 1 * final_underline_thickness); - p2 = Geom::Point(tsp_width_adj,tsp_asc_adj -_nrstyle.underline_position + 1 * final_underline_thickness); - decorateStyle(dc, tsp_size_adj, xphase, p1, p2, thickness); + if (_nrstyle.text_decoration_line & NRStyle::TEXT_DECORATION_LINE_OVERLINE) { + p1 = Geom::Point(0.0, tsp_asc_adj - _nrstyle.underline_position + 1 * final_underline_thickness); + p2 = Geom::Point(tsp_width_adj, tsp_asc_adj - _nrstyle.underline_position + 1 * final_underline_thickness); + decorateStyle(dc, tsp_size_adj, xphase, p1, p2, thickness); } } else { // Over - if(_nrstyle.text_decoration_line & NRStyle::TEXT_DECORATION_LINE_LINETHROUGH){ + if (_nrstyle.text_decoration_line & NRStyle::TEXT_DECORATION_LINE_LINETHROUGH) { thickness = final_line_through_thickness; - p1 = Geom::Point(0.0, _nrstyle.line_through_position); - p2 = Geom::Point(tsp_width_adj,_nrstyle.line_through_position); - decorateStyle(dc, tsp_size_adj, xphase, p1, p2, thickness); + p1 = Geom::Point(0.0, _nrstyle.line_through_position); + p2 = Geom::Point(tsp_width_adj, _nrstyle.line_through_position); + decorateStyle(dc, tsp_size_adj, xphase, p1, p2, thickness); } // Obviously this does not blink, but it does indicate which text has been set with that attribute - if(_nrstyle.text_decoration_line & NRStyle::TEXT_DECORATION_LINE_BLINK){ + if (_nrstyle.text_decoration_line & NRStyle::TEXT_DECORATION_LINE_BLINK) { thickness = final_line_through_thickness; - p1 = Geom::Point(0.0, _nrstyle.line_through_position - 2*final_line_through_thickness); - p2 = Geom::Point(tsp_width_adj,_nrstyle.line_through_position - 2*final_line_through_thickness); - decorateStyle(dc, tsp_size_adj, xphase, p1, p2, thickness); - p1 = Geom::Point(0.0, _nrstyle.line_through_position + 2*final_line_through_thickness); - p2 = Geom::Point(tsp_width_adj,_nrstyle.line_through_position + 2*final_line_through_thickness); - decorateStyle(dc, tsp_size_adj, xphase, p1, p2, thickness); + p1 = Geom::Point(0.0, _nrstyle.line_through_position - 2 * final_line_through_thickness); + p2 = Geom::Point(tsp_width_adj, _nrstyle.line_through_position - 2 * final_line_through_thickness); + decorateStyle(dc, tsp_size_adj, xphase, p1, p2, thickness); + p1 = Geom::Point(0.0, _nrstyle.line_through_position + 2 * final_line_through_thickness); + p2 = Geom::Point(tsp_width_adj, _nrstyle.line_through_position + 2 * final_line_through_thickness); + decorateStyle(dc, tsp_size_adj, xphase, p1, p2, thickness); } } } -unsigned DrawingText::_renderItem(DrawingContext &dc, Geom::IntRect const &/*area*/, unsigned /*flags*/, DrawingItem * /*stop_at*/) +unsigned DrawingText::_renderItem(DrawingContext &dc, Geom::IntRect const & /*area*/, unsigned /*flags*/, + DrawingItem * /*stop_at*/) { if (_drawing.outline()) { guint32 rgba = _drawing.outlinecolor; @@ -464,15 +462,17 @@ unsigned DrawingText::_renderItem(DrawingContext &dc, Geom::IntRect const &/*are dc.setSource(rgba); dc.setTolerance(0.5); // low quality, but good enough for outline mode - for (auto & i : _children) { + for (auto &i : _children) { DrawingGlyphs *g = dynamic_cast(&i); - if (!g) throw InvalidItemException(); + if (!g) + throw InvalidItemException(); Inkscape::DrawingContext::Save save(dc); // skip glyphs with singular transforms - if (g->_ctm.isSingular()) continue; + if (g->_ctm.isSingular()) + continue; dc.transform(g->_ctm); - if(g->_drawable){ + if (g->_drawable) { dc.path(*g->_font->PathVector(g->_glyph)); dc.fill(); } @@ -483,57 +483,53 @@ unsigned DrawingText::_renderItem(DrawingContext &dc, Geom::IntRect const &/*are // NOTE: This is very similar to drawing-shape.cpp; the only differences are in path feeding // and in applying text decorations. - // Do we have text decorations? - bool decorate = (_nrstyle.text_decoration_line != NRStyle::TEXT_DECORATION_LINE_CLEAR ); + bool decorate = (_nrstyle.text_decoration_line != NRStyle::TEXT_DECORATION_LINE_CLEAR); // prepareFill / prepareStroke need to be called with _ctm in effect. // However, we might need to apply a different ctm for glyphs. // Therefore, only apply this ctm temporarily. - bool has_stroke = false; - bool has_fill = false; - bool has_td_fill = false; + bool has_stroke = false; + bool has_fill = false; + bool has_td_fill = false; bool has_td_stroke = false; { Inkscape::DrawingContext::Save save(dc); dc.transform(_ctm); - has_fill = _nrstyle.prepareFill( dc, _item_bbox, _fill_pattern); - has_stroke = _nrstyle.prepareStroke( dc, _item_bbox, _stroke_pattern); + has_fill = _nrstyle.prepareFill(dc, _item_bbox, _fill_pattern); + has_stroke = _nrstyle.prepareStroke(dc, _item_bbox, _stroke_pattern); // Avoid creating patterns if not needed - if( decorate ) { - has_td_fill = _nrstyle.prepareTextDecorationFill( dc, _item_bbox, _fill_pattern); + if (decorate) { + has_td_fill = _nrstyle.prepareTextDecorationFill(dc, _item_bbox, _fill_pattern); has_td_stroke = _nrstyle.prepareTextDecorationStroke(dc, _item_bbox, _stroke_pattern); } } if (has_fill || has_stroke || has_td_fill || has_td_stroke) { - // Determine order for fill and stroke. // Text doesn't have markers, we can do paint-order quick and dirty. bool fill_first = false; - if( _nrstyle.paint_order_layer[0] == NRStyle::PAINT_ORDER_NORMAL || - _nrstyle.paint_order_layer[0] == NRStyle::PAINT_ORDER_FILL || - _nrstyle.paint_order_layer[2] == NRStyle::PAINT_ORDER_STROKE ) { + if (_nrstyle.paint_order_layer[0] == NRStyle::PAINT_ORDER_NORMAL || + _nrstyle.paint_order_layer[0] == NRStyle::PAINT_ORDER_FILL || + _nrstyle.paint_order_layer[2] == NRStyle::PAINT_ORDER_STROKE) { fill_first = true; } // Won't get "stroke fill stroke" but that isn't 'valid' - // Determine geometry of text decoration double phase_length = 0.0; Geom::Affine aff; - if( decorate ) { - + if (decorate) { Geom::Affine rotinv; - bool invset = false; - double leftmost = DBL_MAX; - bool first_y = true; - double start_y = 0.0; - for (auto & i : _children) { - + bool invset = false; + double leftmost = DBL_MAX; + bool first_y = true; + double start_y = 0.0; + for (auto &i : _children) { DrawingGlyphs *g = dynamic_cast(&i); - if (!g) throw InvalidItemException(); + if (!g) + throw InvalidItemException(); if (!invset) { rotinv = g->_ctm.withoutTranslation().inverse(); @@ -542,8 +538,8 @@ unsigned DrawingText::_renderItem(DrawingContext &dc, Geom::IntRect const &/*are Geom::Point pt = g->_ctm.translation() * rotinv; if (pt[Geom::X] < leftmost) { - leftmost = pt[Geom::X]; - aff = g->_ctm; + leftmost = pt[Geom::X]; + aff = g->_ctm; phase_length = g->_pl; } @@ -551,8 +547,7 @@ unsigned DrawingText::_renderItem(DrawingContext &dc, Geom::IntRect const &/*are if (first_y) { first_y = false; start_y = pt[Geom::Y]; - } - else if (fabs(pt[Geom::Y] - start_y) > 1.0e-6) { + } else if (fabs(pt[Geom::Y] - start_y) > 1.0e-6) { // If the text has been mapped onto a path, which causes y to vary, drop the // text decorations. To handle that properly would need a conformal map. decorate = false; @@ -561,17 +556,16 @@ unsigned DrawingText::_renderItem(DrawingContext &dc, Geom::IntRect const &/*are } // Draw text decorations that go UNDER the text (underline, over-line) - if( decorate ) { - + if (decorate) { { Inkscape::DrawingContext::Save save(dc); - dc.transform(aff); // must be leftmost affine in span + dc.transform(aff); // must be leftmost affine in span decorateItem(dc, phase_length, true); } { Inkscape::DrawingContext::Save save(dc); - dc.transform(_ctm); // Needed so that fill pattern rotates with text + dc.transform(_ctm); // Needed so that fill pattern rotates with text if (has_td_fill && fill_first) { _nrstyle.applyTextDecorationFill(dc); @@ -587,23 +581,24 @@ unsigned DrawingText::_renderItem(DrawingContext &dc, Geom::IntRect const &/*are _nrstyle.applyTextDecorationFill(dc); dc.fillPreserve(); } - } dc.newPath(); // Clear text-decoration path } // Accumulate the path that represents the glyphs and/or draw SVG glyphs. - for (auto & i : _children) { + for (auto &i : _children) { DrawingGlyphs *g = dynamic_cast(&i); - if (!g) throw InvalidItemException(); + if (!g) + throw InvalidItemException(); Inkscape::DrawingContext::Save save(dc); - if (g->_ctm.isSingular()) continue; + if (g->_ctm.isSingular()) + continue; dc.transform(g->_ctm); if (g->_drawable) { if (g->_font->FontHasSVG()) { - Inkscape::Pixbuf* pixbuf = g->_font->PixBuf(g->_glyph); + Inkscape::Pixbuf *pixbuf = g->_font->PixBuf(g->_glyph); if (pixbuf) { // Geom::OptRect box = bounds_exact(*g->_font->PathVector(g->_glyph)); // if (box) { @@ -617,10 +612,11 @@ unsigned DrawingText::_renderItem(DrawingContext &dc, Geom::IntRect const &/*are { // pixbuf is in font design units, scale to embox. double scale = g->_font->GetDesignUnits(); - if (scale <= 0) scale = 1000; + if (scale <= 0) + scale = 1000; Inkscape::DrawingContext::Save save(dc); dc.translate(0, 1); - dc.scale(1.0/scale, -1.0/scale); + dc.scale(1.0 / scale, -1.0 / scale); dc.setSource(pixbuf->getSurfaceRaw(), 0, 0); dc.paint(1); } @@ -675,16 +671,15 @@ unsigned DrawingText::_renderItem(DrawingContext &dc, Geom::IntRect const &/*are // Draw text decorations that go OVER the text (line through, blink) if (decorate) { - { Inkscape::DrawingContext::Save save(dc); - dc.transform(aff); // must be leftmost affine in span + dc.transform(aff); // must be leftmost affine in span decorateItem(dc, phase_length, false); } { Inkscape::DrawingContext::Save save(dc); - dc.transform(_ctm); // Needed so that fill pattern rotates with text + dc.transform(_ctm); // Needed so that fill pattern rotates with text if (has_td_fill && fill_first) { _nrstyle.applyTextDecorationFill(dc); @@ -700,17 +695,15 @@ unsigned DrawingText::_renderItem(DrawingContext &dc, Geom::IntRect const &/*are _nrstyle.applyTextDecorationFill(dc); dc.fillPreserve(); } - } dc.newPath(); // Clear text-decoration path } - } return RENDER_OK; } -void DrawingText::_clipItem(DrawingContext &dc, Geom::IntRect const &/*area*/) +void DrawingText::_clipItem(DrawingContext &dc, Geom::IntRect const & /*area*/) { Inkscape::DrawingContext::Save save(dc); @@ -723,7 +716,7 @@ void DrawingText::_clipItem(DrawingContext &dc, Geom::IntRect const &/*area*/) } } - for (auto & i : _children) { + for (auto &i : _children) { DrawingGlyphs *g = dynamic_cast(&i); if (!g) { throw InvalidItemException(); @@ -731,21 +724,19 @@ void DrawingText::_clipItem(DrawingContext &dc, Geom::IntRect const &/*area*/) Inkscape::DrawingContext::Save save(dc); dc.transform(g->_ctm); - if(g->_drawable){ + if (g->_drawable) { dc.path(*g->_font->PathVector(g->_glyph)); } } dc.fill(); } -DrawingItem * -DrawingText::_pickItem(Geom::Point const &p, double delta, unsigned flags) +DrawingItem *DrawingText::_pickItem(Geom::Point const &p, double delta, unsigned flags) { return DrawingGroup::_pickItem(p, delta, flags) ? this : nullptr; } -bool -DrawingText::_canClip() +bool DrawingText::_canClip() { return true; } diff --git a/src/display/drawing-text.h b/src/display/drawing-text.h index 084c7939219d38eb9ed4fd616b4809c87e880bcf..11061ed4d216a530038f5ca3d48763f8507351e2 100644 --- a/src/display/drawing-text.h +++ b/src/display/drawing-text.h @@ -21,8 +21,7 @@ class font_instance; namespace Inkscape { -class DrawingGlyphs - : public DrawingItem +class DrawingGlyphs : public DrawingItem { public: DrawingGlyphs(Drawing &drawing); @@ -32,47 +31,44 @@ public: void setStyle(SPStyle *style, SPStyle *context_style = nullptr) override; // Not to be used Geom::IntRect getPickBox() const { return _pick_bbox; }; - protected: - unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, - unsigned flags, unsigned reset) override; +protected: + unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) override; DrawingItem *_pickItem(Geom::Point const &p, double delta, unsigned flags) override; font_instance *_font; - int _glyph; - bool _drawable; - float _width; // These three are used to set up bounding box - float _asc; // - float _dsc; // - float _pl; // phase length - Geom::IntRect _pick_bbox; + int _glyph; + bool _drawable; + float _width; // These three are used to set up bounding box + float _asc; // + float _dsc; // + float _pl; // phase length + Geom::IntRect _pick_bbox; friend class DrawingText; }; -class DrawingText - : public DrawingGroup +class DrawingText : public DrawingGroup { public: DrawingText(Drawing &drawing); ~DrawingText() override; void clear(); - bool addComponent(font_instance *font, int glyph, Geom::Affine const &trans, - float width, float ascent, float descent, float phase_length); + bool addComponent(font_instance *font, int glyph, Geom::Affine const &trans, float width, float ascent, + float descent, float phase_length); void setStyle(SPStyle *style, SPStyle *context_style = nullptr) override; void setChildrenStyle(SPStyle *context_style) override; protected: - unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, - unsigned flags, unsigned reset) override; - unsigned _renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, - DrawingItem *stop_at) override; + unsigned _updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) override; + unsigned _renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) override; void _clipItem(DrawingContext &dc, Geom::IntRect const &area) override; DrawingItem *_pickItem(Geom::Point const &p, double delta, unsigned flags) override; bool _canClip() override; void decorateItem(DrawingContext &dc, double phase_length, bool under); - void decorateStyle(DrawingContext &dc, double vextent, double xphase, Geom::Point const &p1, Geom::Point const &p2, double thickness); + void decorateStyle(DrawingContext &dc, double vextent, double xphase, Geom::Point const &p1, Geom::Point const &p2, + double thickness); NRStyle _nrstyle; friend class DrawingGlyphs; diff --git a/src/display/drawing.cpp b/src/display/drawing.cpp index 9eee77a313e60a9e8f887a2762967fa7bf798579..23197382faecf1f254b12822126778410cbde895 100644 --- a/src/display/drawing.cpp +++ b/src/display/drawing.cpp @@ -11,25 +11,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "display/drawing.h" + +#include + #include "nr-filter-gaussian.h" #include "nr-filter-types.h" -//grayscale colormode: +// grayscale colormode: #include "cairo-templates.h" #include "drawing-context.h" - namespace Inkscape { // hardcoded grayscale color matrix values as default -static const gdouble grayscale_value_matrix[20] = { - 0.21, 0.72, 0.072, 0, 0, - 0.21, 0.72, 0.072, 0, 0, - 0.21, 0.72, 0.072, 0, 0, - 0 , 0 , 0 , 1, 0 -}; +static const gdouble grayscale_value_matrix[20] = {0.21, 0.72, 0.072, 0, 0, 0.21, 0.72, 0.072, 0, 0, + 0.21, 0.72, 0.072, 0, 0, 0, 0, 0, 1, 0}; Drawing::Drawing(SPCanvasArena *arena) : _root(nullptr) @@ -45,17 +42,14 @@ Drawing::Drawing(SPCanvasArena *arena) , _cache_budget(0) , _grayscale_colormatrix(std::vector(grayscale_value_matrix, grayscale_value_matrix + 20)) , _canvasarena(arena) -{ - -} +{} Drawing::~Drawing() { delete _root; } -void -Drawing::setRoot(DrawingItem *item) +void Drawing::setRoot(DrawingItem *item) { delete _root; _root = item; @@ -65,33 +59,27 @@ Drawing::setRoot(DrawingItem *item) } } -RenderMode -Drawing::renderMode() const +RenderMode Drawing::renderMode() const { return _exact ? RENDERMODE_NORMAL : _rendermode; } -ColorMode -Drawing::colorMode() const +ColorMode Drawing::colorMode() const { return (outline() || _exact) ? COLORMODE_NORMAL : _colormode; } -bool -Drawing::outline() const +bool Drawing::outline() const { return renderMode() == RENDERMODE_OUTLINE; } -bool -Drawing::visibleHairlines() const +bool Drawing::visibleHairlines() const { return renderMode() == RENDERMODE_VISIBLE_HAIRLINES; } -bool -Drawing::renderFilters() const +bool Drawing::renderFilters() const { return renderMode() == RENDERMODE_NORMAL || renderMode() == RENDERMODE_VISIBLE_HAIRLINES; } -int -Drawing::blurQuality() const +int Drawing::blurQuality() const { if (renderMode() == RENDERMODE_NORMAL) { return _exact ? BLUR_QUALITY_BEST : _blur_quality; @@ -99,8 +87,7 @@ Drawing::blurQuality() const return BLUR_QUALITY_WORST; } } -int -Drawing::filterQuality() const +int Drawing::filterQuality() const { if (renderMode() == RENDERMODE_NORMAL) { return _exact ? Filters::FILTER_QUALITY_BEST : _filter_quality; @@ -109,65 +96,58 @@ Drawing::filterQuality() const } } -void -Drawing::setRenderMode(RenderMode mode) +void Drawing::setRenderMode(RenderMode mode) { _rendermode = mode; } -void -Drawing::setColorMode(ColorMode mode) +void Drawing::setColorMode(ColorMode mode) { _colormode = mode; } -void -Drawing::setBlurQuality(int q) +void Drawing::setBlurQuality(int q) { _blur_quality = q; } -void -Drawing::setFilterQuality(int q) +void Drawing::setFilterQuality(int q) { _filter_quality = q; } -void -Drawing::setExact(bool e) +void Drawing::setExact(bool e) { _exact = e; } -void Drawing::setOutlineSensitive(bool e) { _outline_sensitive = e; }; +void Drawing::setOutlineSensitive(bool e) +{ + _outline_sensitive = e; +}; -Geom::OptIntRect const & -Drawing::cacheLimit() const +Geom::OptIntRect const &Drawing::cacheLimit() const { return _cache_limit; } -void -Drawing::setCacheLimit(Geom::OptIntRect const &r, bool update_cache) +void Drawing::setCacheLimit(Geom::OptIntRect const &r, bool update_cache) { _cache_limit = r; if (update_cache) { - for (auto _cached_item : _cached_items) - { + for (auto _cached_item : _cached_items) { _cached_item->_markForUpdate(DrawingItem::STATE_CACHE, false); } } } -void -Drawing::setCacheBudget(size_t bytes) +void Drawing::setCacheBudget(size_t bytes) { _cache_budget = bytes; _pickItemsForCaching(); } -void -Drawing::setGrayscaleMatrix(gdouble value_matrix[20]) { - _grayscale_colormatrix = Filters::FilterColorMatrix::ColorMatrixMatrix( - std::vector (value_matrix, value_matrix + 20) ); +void Drawing::setGrayscaleMatrix(gdouble value_matrix[20]) +{ + _grayscale_colormatrix = + Filters::FilterColorMatrix::ColorMatrixMatrix(std::vector(value_matrix, value_matrix + 20)); } -void -Drawing::update(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) +void Drawing::update(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) { if (_root) { _root->update(area, ctx, flags, reset); @@ -178,12 +158,11 @@ Drawing::update(Geom::IntRect const &area, UpdateContext const &ctx, unsigned fl } } -void -Drawing::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, int antialiasing) +void Drawing::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, int antialiasing) { if (_root) { int prev_a = _root->_antialias; - if(antialiasing >= 0) + if (antialiasing >= 0) _root->setAntialiasing(antialiasing); _root->render(dc, area, flags); _root->setAntialiasing(prev_a); @@ -199,13 +178,12 @@ Drawing::render(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, i dc.setOperator(CAIRO_OPERATOR_SOURCE); dc.paint(); dc.setOperator(CAIRO_OPERATOR_OVER); - + cairo_surface_destroy(out); } } -DrawingItem * -Drawing::pick(Geom::Point const &p, double delta, unsigned flags) +DrawingItem *Drawing::pick(Geom::Point const &p, double delta, unsigned flags) { if (_root) { return _root->pick(p, delta, flags); @@ -213,19 +191,19 @@ Drawing::pick(Geom::Point const &p, double delta, unsigned flags) return nullptr; } -void -Drawing::_pickItemsForCaching() +void Drawing::_pickItemsForCaching() { // we cache the objects with the highest score until the budget is exhausted _candidate_items.sort(std::greater()); size_t used = 0; CandidateList::iterator i; for (i = _candidate_items.begin(); i != _candidate_items.end(); ++i) { - if (used + i->cache_size > _cache_budget) break; + if (used + i->cache_size > _cache_budget) + break; used += i->cache_size; } - std::set to_cache; + std::set to_cache; for (CandidateList::iterator j = _candidate_items.begin(); j != i; ++j) { j->item->setCached(true); to_cache.insert(j->item); @@ -233,9 +211,8 @@ Drawing::_pickItemsForCaching() // Everything which is now in _cached_items but not in to_cache must be uncached // Note that calling setCached on an item modifies _cached_items // TODO: find a way to avoid the set copy - std::set to_uncache; - std::set_difference(_cached_items.begin(), _cached_items.end(), - to_cache.begin(), to_cache.end(), + std::set to_uncache; + std::set_difference(_cached_items.begin(), _cached_items.end(), to_cache.begin(), to_cache.end(), std::inserter(to_uncache, to_uncache.end())); for (auto j : to_uncache) { j->setCached(false); diff --git a/src/display/drawing.h b/src/display/drawing.h index 6d6a9cd02948b5ed2fd8cc91f73807d44daabdd4..f4fd9c1201c0f741daf031a8f22a5fc15d8b1d2a 100644 --- a/src/display/drawing.h +++ b/src/display/drawing.h @@ -30,11 +30,11 @@ namespace Inkscape { class DrawingItem; -class Drawing - : boost::noncopyable +class Drawing : boost::noncopyable { public: - struct OutlineColors { + struct OutlineColors + { guint32 paths; guint32 clippaths; guint32 masks; @@ -72,7 +72,8 @@ public: void setGrayscaleMatrix(double value_matrix[20]); - void update(Geom::IntRect const &area = Geom::IntRect::infinite(), UpdateContext const &ctx = UpdateContext(), unsigned flags = DrawingItem::STATE_ALL, unsigned reset = 0); + void update(Geom::IntRect const &area = Geom::IntRect::infinite(), UpdateContext const &ctx = UpdateContext(), + unsigned flags = DrawingItem::STATE_ALL, unsigned reset = 0); void render(DrawingContext &dc, Geom::IntRect const &area, unsigned flags = 0, int antialiasing = -1); DrawingItem *pick(Geom::Point const &p, double delta, unsigned flags); @@ -88,12 +89,14 @@ private: DrawingItem *_root; std::set _cached_items; // modified by DrawingItem::setCached() CacheList _candidate_items; + public: // TODO: remove these temporarily public members guint32 outlinecolor; double delta; + private: - bool _exact; // if true then rendering must be exact + bool _exact; // if true then rendering must be exact RenderMode _rendermode; ColorMode _colormode; int _blur_quality; @@ -101,7 +104,7 @@ private: Geom::OptIntRect _cache_limit; double _cache_score_threshold; ///< do not consider objects for caching below this score - size_t _cache_budget; ///< maximum allowed size of cache + size_t _cache_budget; ///< maximum allowed size of cache OutlineColors _colors; Filters::FilterColorMatrix::ColorMatrixMatrix _grayscale_colormatrix; diff --git a/src/display/gnome-canvas-acetate.cpp b/src/display/gnome-canvas-acetate.cpp index cd8728f261389690da52b7c21bce0d18ece99279..bab03c3535675438eb24f9df9f8a3868d4636f78 100644 --- a/src/display/gnome-canvas-acetate.cpp +++ b/src/display/gnome-canvas-acetate.cpp @@ -15,39 +15,40 @@ */ #include "gnome-canvas-acetate.h" + #include "ui/event-debug.h" static void sp_canvas_acetate_destroy(SPCanvasItem *object); -static void sp_canvas_acetate_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); -static double sp_canvas_acetate_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item); +static void sp_canvas_acetate_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); +static double sp_canvas_acetate_point(SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item); G_DEFINE_TYPE(SPCanvasAcetate, sp_canvas_acetate, SP_TYPE_CANVAS_ITEM); -static void sp_canvas_acetate_class_init (SPCanvasAcetateClass *klass) +static void sp_canvas_acetate_class_init(SPCanvasAcetateClass *klass) { - SPCanvasItemClass *item_class = (SPCanvasItemClass *) klass; + SPCanvasItemClass *item_class = (SPCanvasItemClass *)klass; - item_class->destroy = sp_canvas_acetate_destroy; - item_class->update = sp_canvas_acetate_update; - item_class->point = sp_canvas_acetate_point; + item_class->destroy = sp_canvas_acetate_destroy; + item_class->update = sp_canvas_acetate_update; + item_class->point = sp_canvas_acetate_point; } -static void sp_canvas_acetate_init (SPCanvasAcetate *acetate) +static void sp_canvas_acetate_init(SPCanvasAcetate *acetate) { SP_CANVAS_ITEM(acetate)->name = "Acetate"; } static void sp_canvas_acetate_destroy(SPCanvasItem *object) { - g_return_if_fail (object != nullptr); - g_return_if_fail (GNOME_IS_CANVAS_ACETATE (object)); + g_return_if_fail(object != nullptr); + g_return_if_fail(GNOME_IS_CANVAS_ACETATE(object)); - if (SP_CANVAS_ITEM_CLASS(sp_canvas_acetate_parent_class)->destroy) - SP_CANVAS_ITEM_CLASS(sp_canvas_acetate_parent_class)->destroy(object); + if (SP_CANVAS_ITEM_CLASS(sp_canvas_acetate_parent_class)->destroy) + SP_CANVAS_ITEM_CLASS(sp_canvas_acetate_parent_class)->destroy(object); } -static void sp_canvas_acetate_update( SPCanvasItem *item, Geom::Affine const &/*affine*/, unsigned int /*flags*/ ) +static void sp_canvas_acetate_update(SPCanvasItem *item, Geom::Affine const & /*affine*/, unsigned int /*flags*/) { item->x1 = -G_MAXINT; item->y1 = -G_MAXINT; @@ -55,7 +56,7 @@ static void sp_canvas_acetate_update( SPCanvasItem *item, Geom::Affine const &/* item->y2 = G_MAXINT; } -static double sp_canvas_acetate_point( SPCanvasItem *item, Geom::Point /*p*/, SPCanvasItem **actual_item ) +static double sp_canvas_acetate_point(SPCanvasItem *item, Geom::Point /*p*/, SPCanvasItem **actual_item) { *actual_item = item; diff --git a/src/display/gnome-canvas-acetate.h b/src/display/gnome-canvas-acetate.h index d08667daa10eddc7fdc2c8ab66dc5c773b93210e..82211fcfdcb92ff25b871445277df310097fbf49 100644 --- a/src/display/gnome-canvas-acetate.h +++ b/src/display/gnome-canvas-acetate.h @@ -18,22 +18,24 @@ #include "display/sp-canvas-item.h" -#define GNOME_TYPE_CANVAS_ACETATE (sp_canvas_acetate_get_type ()) -#define SP_CANVAS_ACETATE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GNOME_TYPE_CANVAS_ACETATE, SPCanvasAcetate)) -#define SP_CANVAS_ACETATE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GNOME_TYPE_CANVAS_ACETATE, SPCanvasAcetateClass)) -#define GNOME_IS_CANVAS_ACETATE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GNOME_TYPE_CANVAS_ACETATE)) -#define GNOME_IS_CANVAS_ACETATE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GNOME_TYPE_CANVAS_ACETATE)) - - -struct SPCanvasAcetate { +#define GNOME_TYPE_CANVAS_ACETATE (sp_canvas_acetate_get_type()) +#define SP_CANVAS_ACETATE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GNOME_TYPE_CANVAS_ACETATE, SPCanvasAcetate)) +#define SP_CANVAS_ACETATE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass), GNOME_TYPE_CANVAS_ACETATE, SPCanvasAcetateClass)) +#define GNOME_IS_CANVAS_ACETATE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GNOME_TYPE_CANVAS_ACETATE)) +#define GNOME_IS_CANVAS_ACETATE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), GNOME_TYPE_CANVAS_ACETATE)) + +struct SPCanvasAcetate +{ SPCanvasItem item; }; -struct SPCanvasAcetateClass { +struct SPCanvasAcetateClass +{ SPCanvasItemClass parent_class; }; -GType sp_canvas_acetate_get_type (); +GType sp_canvas_acetate_get_type(); #endif // SEEN_SP_CANVAS_ACETATE_H diff --git a/src/display/grayscale.cpp b/src/display/grayscale.cpp index fb77dfa87bad12a13bf5103b721d9a8ab597acba..fcfa322095e362c7c2905ee069da1ea44dd10c3f 100644 --- a/src/display/grayscale.cpp +++ b/src/display/grayscale.cpp @@ -13,12 +13,13 @@ */ #include "display/grayscale.h" + #include "color.h" // for activeDesktopIsGrayscale: +#include "desktop.h" #include "display/rendermode.h" #include "inkscape.h" -#include "desktop.h" namespace Grayscale { @@ -33,12 +34,13 @@ const float red_factor = 0.2125; const float green_factor = 0.7154; const float blue_factor = 0.0721; -guint32 process(guint32 rgba) { +guint32 process(guint32 rgba) +{ return process(SP_RGBA32_R_U(rgba), SP_RGBA32_G_U(rgba), SP_RGBA32_B_U(rgba), SP_RGBA32_A_U(rgba)); } -guint32 process(unsigned char r, unsigned char g, unsigned char b, unsigned char a) { - +guint32 process(unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ /** To reduce banding in gradients, this calculation is tweaked a bit * by outputting blue+1 or red+1 or both. The luminance is calculated * times 4. Then last two bits are used to determine if red and/or blue @@ -48,9 +50,7 @@ guint32 process(unsigned char r, unsigned char g, unsigned char b, unsigned char * (hope this trick works :-) Johan) */ - guint32 luminance = ( red_factor * (r << 3) - + green_factor * (g << 3) - + blue_factor * (b << 3) ); + guint32 luminance = (red_factor * (r << 3) + green_factor * (g << 3) + blue_factor * (b << 3)); unsigned blue_plus_one = (luminance & 0x01) ? 1 : 0; unsigned red_plus_one = (luminance & 0x02) ? 1 : 0; unsigned green_plus_one = (luminance & 0x04) ? 1 : 0; @@ -63,10 +63,9 @@ guint32 process(unsigned char r, unsigned char g, unsigned char b, unsigned char } } -unsigned char luminance(unsigned char r, unsigned char g, unsigned char b) { - guint32 luminance = ( red_factor * r - + green_factor * g - + blue_factor * b ); +unsigned char luminance(unsigned char r, unsigned char g, unsigned char b) +{ + guint32 luminance = (red_factor * r + green_factor * g + blue_factor * b); if (luminance > 0xff) { luminance = 0xff; } @@ -82,16 +81,16 @@ unsigned char luminance(unsigned char r, unsigned char g, unsigned char b) { * the global SP_ACTIVE_DESKTOP macro. Then use this method, so we know where the abuse is * happening... */ -bool activeDesktopIsGrayscale() { +bool activeDesktopIsGrayscale() +{ if (SP_ACTIVE_DESKTOP) { return (SP_ACTIVE_DESKTOP->getColorMode() == Inkscape::COLORMODE_GRAYSCALE); } - + return false; } - -}; +}; // namespace Grayscale /* Local Variables: diff --git a/src/display/grayscale.h b/src/display/grayscale.h index fad1205211f84729c935e4629501ea0cb5bb3bb8..54a2d819ed9a0c246ed64a7233af28dd7b29f603 100644 --- a/src/display/grayscale.h +++ b/src/display/grayscale.h @@ -17,12 +17,12 @@ typedef unsigned int guint32; * Provide methods to calculate grayscale values (e.g. convert rgba value to grayscale rgba value). */ namespace Grayscale { - guint32 process(guint32 rgba); - guint32 process(unsigned char r, unsigned char g, unsigned char b, unsigned char a); - unsigned char luminance(unsigned char r, unsigned char g, unsigned char b); +guint32 process(guint32 rgba); +guint32 process(unsigned char r, unsigned char g, unsigned char b, unsigned char a); +unsigned char luminance(unsigned char r, unsigned char g, unsigned char b); - bool activeDesktopIsGrayscale(); -}; +bool activeDesktopIsGrayscale(); +}; // namespace Grayscale #endif // !SEEN_DISPLAY_GRAYSCALE_H diff --git a/src/display/guideline.cpp b/src/display/guideline.cpp index 8faabda5229a0f766d063190bf2dd09ad5be6272..cf669b69f822be4051294a99b1a8c4cc2234d027 100644 --- a/src/display/guideline.cpp +++ b/src/display/guideline.cpp @@ -16,18 +16,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "guideline.h" + #include <2geom/coord.h> -#include <2geom/transforms.h> #include <2geom/line.h> - -#include "sp-canvas-util.h" -#include "inkscape.h" -#include "guideline.h" +#include <2geom/transforms.h> #include "display/cairo-utils.h" #include "display/sodipodi-ctrl.h" - +#include "inkscape.h" #include "object/sp-namedview.h" +#include "sp-canvas-util.h" static void sp_guideline_destroy(SPCanvasItem *object); @@ -52,9 +51,9 @@ static void sp_guideline_init(SPGuideLine *gl) gl->rgba = 0x0000ff7f; gl->locked = false; - gl->normal_to_line = Geom::Point(0,1); + gl->normal_to_line = Geom::Point(0, 1); gl->angle = M_PI_2; - gl->point_on_line = Geom::Point(0,0); + gl->point_on_line = Geom::Point(0, 0); gl->sensitive = 0; gl->origin = nullptr; @@ -65,8 +64,8 @@ static void sp_guideline_init(SPGuideLine *gl) static void sp_guideline_destroy(SPCanvasItem *object) { - g_return_if_fail (object != nullptr); - g_return_if_fail (SP_IS_GUIDELINE (object)); + g_return_if_fail(object != nullptr); + g_return_if_fail(SP_IS_GUIDELINE(object)); SPGuideLine *gl = SP_GUIDELINE(object); @@ -83,20 +82,25 @@ static void sp_guideline_destroy(SPCanvasItem *object) static void sp_guideline_render(SPCanvasItem *item, SPCanvasBuf *buf) { - SPGuideLine const *gl = SP_GUIDELINE (item); + SPGuideLine const *gl = SP_GUIDELINE(item); cairo_save(buf->ct); cairo_translate(buf->ct, -buf->rect.left(), -buf->rect.top()); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool xrayactive = prefs->getBool("/desktop/xrayactive", false); - SPDesktop * desktop = SP_ACTIVE_DESKTOP; + SPDesktop *desktop = SP_ACTIVE_DESKTOP; if (xrayactive && desktop) { guint32 bg = desktop->getNamedView()->pagecolor; - guint32 _color = SP_RGBA32_F_COMPOSE( - CLAMP(((1 - SP_RGBA32_A_F(gl->rgba)) * SP_RGBA32_R_F(bg)) + (SP_RGBA32_A_F(gl->rgba) * SP_RGBA32_R_F(gl->rgba)), 0.0, 1.0), - CLAMP(((1 - SP_RGBA32_A_F(gl->rgba)) * SP_RGBA32_G_F(bg)) + (SP_RGBA32_A_F(gl->rgba) * SP_RGBA32_G_F(gl->rgba)), 0.0, 1.0), - CLAMP(((1 - SP_RGBA32_A_F(gl->rgba)) * SP_RGBA32_B_F(bg)) + (SP_RGBA32_A_F(gl->rgba) * SP_RGBA32_B_F(gl->rgba)), 0.0, 1.0), - 1.0); + guint32 _color = SP_RGBA32_F_COMPOSE(CLAMP(((1 - SP_RGBA32_A_F(gl->rgba)) * SP_RGBA32_R_F(bg)) + + (SP_RGBA32_A_F(gl->rgba) * SP_RGBA32_R_F(gl->rgba)), + 0.0, 1.0), + CLAMP(((1 - SP_RGBA32_A_F(gl->rgba)) * SP_RGBA32_G_F(bg)) + + (SP_RGBA32_A_F(gl->rgba) * SP_RGBA32_G_F(gl->rgba)), + 0.0, 1.0), + CLAMP(((1 - SP_RGBA32_A_F(gl->rgba)) * SP_RGBA32_B_F(bg)) + + (SP_RGBA32_A_F(gl->rgba) * SP_RGBA32_B_F(gl->rgba)), + 0.0, 1.0), + 1.0); ink_cairo_set_source_rgba32(buf->ct, _color); } else { ink_cairo_set_source_rgba32(buf->ct, gl->rgba); @@ -106,8 +110,8 @@ static void sp_guideline_render(SPCanvasItem *item, SPCanvasBuf *buf) cairo_set_font_size(buf->ct, 10); // normal_dt does not have unit length - Geom::Point normal_dt = gl->normal_to_line * gl->affine.withoutTranslation(); - Geom::Point point_on_line_dt = gl->point_on_line * gl->affine; + Geom::Point normal_dt = gl->normal_to_line * gl->affine.withoutTranslation(); + Geom::Point point_on_line_dt = gl->point_on_line * gl->affine; if (gl->label) { int px = round(point_on_line_dt[Geom::X]); @@ -123,20 +127,21 @@ static void sp_guideline_render(SPCanvasItem *item, SPCanvasBuf *buf) // Draw guide. // Special case horizontal and vertical lines so they accurately align to the to pixels. - + // Need to use floor()+0.5 such that Cairo will draw us lines with a width of a single pixel, without any aliasing. // For this we need to position the lines at exactly half pixels, see https://www.cairographics.org/FAQ/#sharp_lines - // Must be consistent with the pixel alignment of the grid lines, see CanvasXYGrid::Render(), and the drawing of the rulers - + // Must be consistent with the pixel alignment of the grid lines, see CanvasXYGrid::Render(), and the drawing of the + // rulers + // Don't use isHorizontal()/isVertical() as they test only exact matches. - if ( Geom::are_near(normal_dt[Geom::Y], 0.0) ) { // Vertical? + if (Geom::are_near(normal_dt[Geom::Y], 0.0)) { // Vertical? double position = floor(point_on_line_dt[Geom::X]) + 0.5; cairo_move_to(buf->ct, position, buf->rect.top() + 0.5); cairo_line_to(buf->ct, position, buf->rect.bottom() - 0.5); cairo_stroke(buf->ct); - } else if ( Geom::are_near(normal_dt[Geom::X], 0.0) ) { // Horizontal? + } else if (Geom::are_near(normal_dt[Geom::X], 0.0)) { // Horizontal? double position = floor(point_on_line_dt[Geom::Y]) + 0.5; cairo_move_to(buf->ct, buf->rect.left() + 0.5, position); @@ -144,18 +149,16 @@ static void sp_guideline_render(SPCanvasItem *item, SPCanvasBuf *buf) cairo_stroke(buf->ct); } else { - - Geom::Line guide = - Geom::Line::from_origin_and_vector( point_on_line_dt, Geom::rot90(normal_dt) ); + Geom::Line guide = Geom::Line::from_origin_and_vector(point_on_line_dt, Geom::rot90(normal_dt)); // Find intersections of guide with buf rectangle. There should be zero or two. std::vector intersections; for (unsigned i = 0; i < 4; ++i) { - Geom::LineSegment side( buf->rect.corner(i), buf->rect.corner((i+1)%4) ); + Geom::LineSegment side(buf->rect.corner(i), buf->rect.corner((i + 1) % 4)); try { Geom::OptCrossing oc = Geom::intersection(guide, side); if (oc) { - intersections.push_back( guide.pointAt((*oc).ta)); + intersections.push_back(guide.pointAt((*oc).ta)); } } catch (Geom::InfiniteSolutions) { // Shouldn't happen as we have already taken care of horizontal/vertical guides. @@ -187,13 +190,11 @@ static void sp_guideline_update(SPCanvasItem *item, Geom::Affine const &affine, if (item->visible) { if (gl->locked) { - g_object_set(G_OBJECT(gl->origin), "stroke_color", 0x0000ff88, - "shape", SP_CTRL_SHAPE_CROSS, - "size", 7, NULL); + g_object_set(G_OBJECT(gl->origin), "stroke_color", 0x0000ff88, "shape", SP_CTRL_SHAPE_CROSS, "size", 7, + NULL); } else { - g_object_set(G_OBJECT(gl->origin), "stroke_color", 0xff000088, - "shape", SP_CTRL_SHAPE_CIRCLE, - "size", 5, NULL); + g_object_set(G_OBJECT(gl->origin), "stroke_color", 0xff000088, "shape", SP_CTRL_SHAPE_CIRCLE, "size", 5, + NULL); } gl->origin->moveto(gl->point_on_line); sp_canvas_item_request_update(SP_CANVAS_ITEM(gl->origin)); @@ -202,14 +203,13 @@ static void sp_guideline_update(SPCanvasItem *item, Geom::Affine const &affine, gl->affine = affine; // Rotated canvas requires large bbox for all guides. - sp_canvas_update_bbox (item, -1000000, -1000000, 1000000, 1000000); - + sp_canvas_update_bbox(item, -1000000, -1000000, 1000000, 1000000); } // Returns 0.0 if point is on the guideline static double sp_guideline_point(SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item) { - SPGuideLine *gl = SP_GUIDELINE (item); + SPGuideLine *gl = SP_GUIDELINE(item); if (!gl->sensitive) { return Geom::infinity(); @@ -219,10 +219,10 @@ static double sp_guideline_point(SPCanvasItem *item, Geom::Point p, SPCanvasItem Geom::Point vec = gl->normal_to_line * gl->affine.withoutTranslation(); double distance = Geom::dot((p - gl->point_on_line * gl->affine), unit_vector(vec)); - return MAX(fabs(distance)-1, 0); + return MAX(fabs(distance) - 1, 0); } -SPCanvasItem *sp_guideline_new(SPCanvasGroup *parent, char* label, Geom::Point point_on_line, Geom::Point normal) +SPCanvasItem *sp_guideline_new(SPCanvasGroup *parent, char *label, Geom::Point point_on_line, Geom::Point normal) { SPCanvasItem *item = sp_canvas_item_new(parent, SP_TYPE_GUIDELINE, nullptr); SPGuideLine *gl = SP_GUIDELINE(item); @@ -231,49 +231,46 @@ SPCanvasItem *sp_guideline_new(SPCanvasGroup *parent, char* label, Geom::Point p gl->label = label; gl->locked = false; gl->normal_to_line = normal; - gl->angle = tan( -gl->normal_to_line[Geom::X] / gl->normal_to_line[Geom::Y]); + gl->angle = tan(-gl->normal_to_line[Geom::X] / gl->normal_to_line[Geom::Y]); sp_guideline_set_position(gl, point_on_line); - gl->origin = (SPCtrl *) sp_canvas_item_new(parent, SP_TYPE_CTRL, - "anchor", SP_ANCHOR_CENTER, - "mode", SP_CTRL_MODE_COLOR, - "filled", FALSE, - "stroked", TRUE, - "stroke_color", 0x01000000, NULL); + gl->origin = + (SPCtrl *)sp_canvas_item_new(parent, SP_TYPE_CTRL, "anchor", SP_ANCHOR_CENTER, "mode", SP_CTRL_MODE_COLOR, + "filled", FALSE, "stroked", TRUE, "stroke_color", 0x01000000, NULL); gl->origin->name = "SPCtrl:GuidelineOrigin"; gl->origin->pickable = false; return item; } -void sp_guideline_set_label(SPGuideLine *gl, const char* label) +void sp_guideline_set_label(SPGuideLine *gl, const char *label) { if (gl->label) { g_free(gl->label); } gl->label = g_strdup(label); - sp_canvas_item_request_update(SP_CANVAS_ITEM (gl)); + sp_canvas_item_request_update(SP_CANVAS_ITEM(gl)); } void sp_guideline_set_locked(SPGuideLine *gl, const bool locked) { gl->locked = locked; - sp_canvas_item_request_update(SP_CANVAS_ITEM (gl)); + sp_canvas_item_request_update(SP_CANVAS_ITEM(gl)); } void sp_guideline_set_position(SPGuideLine *gl, Geom::Point point_on_line) { gl->point_on_line = point_on_line; - sp_canvas_item_request_update(SP_CANVAS_ITEM (gl)); + sp_canvas_item_request_update(SP_CANVAS_ITEM(gl)); } void sp_guideline_set_normal(SPGuideLine *gl, Geom::Point normal_to_line) { gl->normal_to_line = normal_to_line; - gl->angle = tan( -normal_to_line[Geom::X] / normal_to_line[Geom::Y]); + gl->angle = tan(-normal_to_line[Geom::X] / normal_to_line[Geom::Y]); - sp_canvas_item_request_update(SP_CANVAS_ITEM (gl)); + sp_canvas_item_request_update(SP_CANVAS_ITEM(gl)); } void sp_guideline_set_color(SPGuideLine *gl, unsigned int rgba) diff --git a/src/display/guideline.h b/src/display/guideline.h index e81cb35f5b78239f5a3fd8c0e045342bcb1ef022..77a04e9a0dac4e3695da145ecfe6e2ff6d264076 100644 --- a/src/display/guideline.h +++ b/src/display/guideline.h @@ -16,6 +16,7 @@ */ #include <2geom/point.h> + #include "sp-canvas-item.h" #define SP_TYPE_GUIDELINE (sp_guideline_get_type()) @@ -24,7 +25,8 @@ struct SPCtrl; -struct SPGuideLine { +struct SPGuideLine +{ SPCanvasItem item; Geom::Affine affine; @@ -32,7 +34,7 @@ struct SPGuideLine { guint32 rgba; - char* label; + char *label; bool locked; Geom::Point normal_to_line; Geom::Point point_on_line; @@ -44,15 +46,16 @@ struct SPGuideLine { inline bool is_vertical() const { return (normal_to_line[Geom::Y] == 0.); }; }; -struct SPGuideLineClass { +struct SPGuideLineClass +{ SPCanvasItemClass parent_class; }; GType sp_guideline_get_type(); -SPCanvasItem *sp_guideline_new(SPCanvasGroup *parent, char* label, Geom::Point point_on_line, Geom::Point normal); +SPCanvasItem *sp_guideline_new(SPCanvasGroup *parent, char *label, Geom::Point point_on_line, Geom::Point normal); -void sp_guideline_set_label(SPGuideLine *gl, const char* label); +void sp_guideline_set_label(SPGuideLine *gl, const char *label); void sp_guideline_set_locked(SPGuideLine *gl, const bool locked); void sp_guideline_set_position(SPGuideLine *gl, Geom::Point point_on_line); void sp_guideline_set_normal(SPGuideLine *gl, Geom::Point normal_to_line); diff --git a/src/display/nr-3dutils.cpp b/src/display/nr-3dutils.cpp index 3c0eb5eeb0be30fc4f3e124065fd8a985d13a5f0..a1fc9bb5d21021eda76498d024fcd5914064af8d 100644 --- a/src/display/nr-3dutils.cpp +++ b/src/display/nr-3dutils.cpp @@ -10,16 +10,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include - #include "display/nr-3dutils.h" -#include -#include <2geom/point.h> + #include <2geom/affine.h> +#include <2geom/point.h> +#include +#include namespace NR { -void convert_coord(gdouble &x, gdouble &y, gdouble &z, Geom::Affine const &trans) { +void convert_coord(gdouble &x, gdouble &y, gdouble &z, Geom::Affine const &trans) +{ Geom::Point p = Geom::Point(x, y); p *= trans; x = p[Geom::X]; @@ -27,32 +28,34 @@ void convert_coord(gdouble &x, gdouble &y, gdouble &z, Geom::Affine const &trans z *= trans[0]; } -gdouble norm(const Fvector &v) { - return sqrt(v[X_3D]*v[X_3D] + v[Y_3D]*v[Y_3D] + v[Z_3D]*v[Z_3D]); +gdouble norm(const Fvector &v) +{ + return sqrt(v[X_3D] * v[X_3D] + v[Y_3D] * v[Y_3D] + v[Z_3D] * v[Z_3D]); } -void normalize_vector(Fvector &v) { +void normalize_vector(Fvector &v) +{ gdouble nv = norm(v); - //TODO test nv == 0 + // TODO test nv == 0 for (int j = 0; j < 3; j++) { v[j] /= nv; } } -gdouble scalar_product(const Fvector &a, const Fvector &b) { - return a[X_3D] * b[X_3D] + - a[Y_3D] * b[Y_3D] + - a[Z_3D] * b[Z_3D]; +gdouble scalar_product(const Fvector &a, const Fvector &b) +{ + return a[X_3D] * b[X_3D] + a[Y_3D] * b[Y_3D] + a[Z_3D] * b[Z_3D]; } -void normalized_sum(Fvector &r, const Fvector &a, const Fvector &b) { +void normalized_sum(Fvector &r, const Fvector &a, const Fvector &b) +{ r[X_3D] = a[X_3D] + b[X_3D]; r[Y_3D] = a[Y_3D] + b[Y_3D]; r[Z_3D] = a[Z_3D] + b[Z_3D]; normalize_vector(r); } -}/* namespace NR */ +} /* namespace NR */ /* Local Variables: diff --git a/src/display/nr-3dutils.h b/src/display/nr-3dutils.h index 21fcf5fc8bb3551a318e79aeafaec1610f8e888d..4e09a01844bd2609163b4a018595175bc95ded8b 100644 --- a/src/display/nr-3dutils.h +++ b/src/display/nr-3dutils.h @@ -26,11 +26,11 @@ namespace NR { /** * a type of 3 gdouble components vectors */ -struct Fvector { - Fvector() { - v[0] = v[1] = v[2] = 0.0; - } - Fvector(double x, double y, double z) { +struct Fvector +{ + Fvector() { v[0] = v[1] = v[2] = 0.0; } + Fvector(double x, double y, double z) + { v[0] = x; v[1] = y; v[2] = z; diff --git a/src/display/nr-filter-blend.cpp b/src/display/nr-filter-blend.cpp index e68407efdd2a19471c00555eb2aa0b7d2a637a80..24971c25ff9b1c28c9aa5aca18661766c549db41 100644 --- a/src/display/nr-filter-blend.cpp +++ b/src/display/nr-filter-blend.cpp @@ -17,10 +17,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/nr-filter-blend.h" + #include + #include "display/cairo-templates.h" #include "display/cairo-utils.h" -#include "display/nr-filter-blend.h" #include "display/nr-filter-primitive.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-types.h" @@ -29,7 +31,7 @@ namespace Inkscape { namespace Filters { -const std::set FilterBlend::_valid_modes { +const std::set FilterBlend::_valid_modes{ // clang-format off SP_CSS_BLEND_NORMAL, SP_CSS_BLEND_MULTIPLY, SP_CSS_BLEND_SCREEN, SP_CSS_BLEND_DARKEN, @@ -40,58 +42,58 @@ const std::set FilterBlend::_valid_modes { SP_CSS_BLEND_HUE, SP_CSS_BLEND_SATURATION, SP_CSS_BLEND_COLOR, SP_CSS_BLEND_LUMINOSITY // clang-format on - }; +}; FilterBlend::FilterBlend() - : _blend_mode(SP_CSS_BLEND_NORMAL), - _input2(NR_FILTER_SLOT_NOT_SET) + : _blend_mode(SP_CSS_BLEND_NORMAL) + , _input2(NR_FILTER_SLOT_NOT_SET) {} -FilterPrimitive * FilterBlend::create() { +FilterPrimitive *FilterBlend::create() +{ return new FilterBlend(); } -FilterBlend::~FilterBlend() -= default; +FilterBlend::~FilterBlend() = default; static inline cairo_operator_t get_cairo_op(SPBlendMode _blend_mode) { switch (_blend_mode) { - case SP_CSS_BLEND_MULTIPLY: - return CAIRO_OPERATOR_MULTIPLY; - case SP_CSS_BLEND_SCREEN: - return CAIRO_OPERATOR_SCREEN; - case SP_CSS_BLEND_DARKEN: - return CAIRO_OPERATOR_DARKEN; - case SP_CSS_BLEND_LIGHTEN: - return CAIRO_OPERATOR_LIGHTEN; - // New in CSS Compositing and Blending Level 1 - case SP_CSS_BLEND_OVERLAY: - return CAIRO_OPERATOR_OVERLAY; - case SP_CSS_BLEND_COLORDODGE: - return CAIRO_OPERATOR_COLOR_DODGE; - case SP_CSS_BLEND_COLORBURN: - return CAIRO_OPERATOR_COLOR_BURN; - case SP_CSS_BLEND_HARDLIGHT: - return CAIRO_OPERATOR_HARD_LIGHT; - case SP_CSS_BLEND_SOFTLIGHT: - return CAIRO_OPERATOR_SOFT_LIGHT; - case SP_CSS_BLEND_DIFFERENCE: - return CAIRO_OPERATOR_DIFFERENCE; - case SP_CSS_BLEND_EXCLUSION: - return CAIRO_OPERATOR_EXCLUSION; - case SP_CSS_BLEND_HUE: - return CAIRO_OPERATOR_HSL_HUE; - case SP_CSS_BLEND_SATURATION: - return CAIRO_OPERATOR_HSL_SATURATION; - case SP_CSS_BLEND_COLOR: - return CAIRO_OPERATOR_HSL_COLOR; - case SP_CSS_BLEND_LUMINOSITY: - return CAIRO_OPERATOR_HSL_LUMINOSITY; - - case SP_CSS_BLEND_NORMAL: - default: - return CAIRO_OPERATOR_OVER; + case SP_CSS_BLEND_MULTIPLY: + return CAIRO_OPERATOR_MULTIPLY; + case SP_CSS_BLEND_SCREEN: + return CAIRO_OPERATOR_SCREEN; + case SP_CSS_BLEND_DARKEN: + return CAIRO_OPERATOR_DARKEN; + case SP_CSS_BLEND_LIGHTEN: + return CAIRO_OPERATOR_LIGHTEN; + // New in CSS Compositing and Blending Level 1 + case SP_CSS_BLEND_OVERLAY: + return CAIRO_OPERATOR_OVERLAY; + case SP_CSS_BLEND_COLORDODGE: + return CAIRO_OPERATOR_COLOR_DODGE; + case SP_CSS_BLEND_COLORBURN: + return CAIRO_OPERATOR_COLOR_BURN; + case SP_CSS_BLEND_HARDLIGHT: + return CAIRO_OPERATOR_HARD_LIGHT; + case SP_CSS_BLEND_SOFTLIGHT: + return CAIRO_OPERATOR_SOFT_LIGHT; + case SP_CSS_BLEND_DIFFERENCE: + return CAIRO_OPERATOR_DIFFERENCE; + case SP_CSS_BLEND_EXCLUSION: + return CAIRO_OPERATOR_EXCLUSION; + case SP_CSS_BLEND_HUE: + return CAIRO_OPERATOR_HSL_HUE; + case SP_CSS_BLEND_SATURATION: + return CAIRO_OPERATOR_HSL_SATURATION; + case SP_CSS_BLEND_COLOR: + return CAIRO_OPERATOR_HSL_COLOR; + case SP_CSS_BLEND_LUMINOSITY: + return CAIRO_OPERATOR_HSL_LUMINOSITY; + + case SP_CSS_BLEND_NORMAL: + default: + return CAIRO_OPERATOR_OVER; } } @@ -103,17 +105,17 @@ void FilterBlend::render_cairo(FilterSlot &slot) // We may need to transform input surface to correct color interpolation space. The input surface // might be used as input to another primitive but it is likely that all the primitives in a given // filter use the same color interpolation space so we don't copy the input before converting. - SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; - if( _style ) { + SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; + if (_style) { ci_fp = (SPColorInterpolation)_style->color_interpolation_filters.computed; } - set_cairo_surface_ci( input1, ci_fp ); - set_cairo_surface_ci( input2, ci_fp ); + set_cairo_surface_ci(input1, ci_fp); + set_cairo_surface_ci(input2, ci_fp); // input2 is the "background" image // out should be ARGB32 if any of the inputs is ARGB32 cairo_surface_t *out = ink_cairo_surface_create_output(input1, input2); - set_cairo_surface_ci( out, ci_fp ); + set_cairo_surface_ci(out, ci_fp); ink_cairo_surface_blit(input2, out); cairo_t *out_ct = cairo_create(out); @@ -148,18 +150,22 @@ bool FilterBlend::uses_background() _input2 == NR_FILTER_BACKGROUNDIMAGE || _input2 == NR_FILTER_BACKGROUNDALPHA); } -void FilterBlend::set_input(int slot) { +void FilterBlend::set_input(int slot) +{ _input = slot; } -void FilterBlend::set_input(int input, int slot) { - if (input == 0) _input = slot; - if (input == 1) _input2 = slot; +void FilterBlend::set_input(int input, int slot) +{ + if (input == 0) + _input = slot; + if (input == 1) + _input2 = slot; } -void FilterBlend::set_mode(SPBlendMode mode) { - if (_valid_modes.count(mode)) - { +void FilterBlend::set_mode(SPBlendMode mode) +{ + if (_valid_modes.count(mode)) { _blend_mode = mode; } } diff --git a/src/display/nr-filter-blend.h b/src/display/nr-filter-blend.h index 01cffeb79230e575b475bc4ab5a5e7720b5f6510..30d0f66006db275663bdb133eb2d60172920f034 100644 --- a/src/display/nr-filter-blend.h +++ b/src/display/nr-filter-blend.h @@ -18,13 +18,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include -#include "style-enums.h" + #include "display/nr-filter-primitive.h" +#include "style-enums.h" namespace Inkscape { namespace Filters { -class FilterBlend : public FilterPrimitive { +class FilterBlend : public FilterPrimitive +{ public: FilterBlend(); static FilterPrimitive *create(); @@ -47,13 +49,9 @@ private: int _input2; }; - } /* namespace Filters */ } /* namespace Inkscape */ - - - #endif /* __NR_FILTER_BLEND_H__ */ /* Local Variables: diff --git a/src/display/nr-filter-colormatrix.cpp b/src/display/nr-filter-colormatrix.cpp index eff5d93a648349edf774b28917c830efb3ad4d8a..476efc22b148fffa2ca7bfde21ee7f7952348298 100644 --- a/src/display/nr-filter-colormatrix.cpp +++ b/src/display/nr-filter-colormatrix.cpp @@ -11,34 +11,36 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "display/nr-filter-colormatrix.h" + +#include <2geom/math-utils.h> #include +#include + #include "display/cairo-templates.h" #include "display/cairo-utils.h" -#include "display/nr-filter-colormatrix.h" #include "display/nr-filter-slot.h" -#include <2geom/math-utils.h> namespace Inkscape { namespace Filters { -FilterColorMatrix::FilterColorMatrix() -= default; +FilterColorMatrix::FilterColorMatrix() = default; -FilterPrimitive * FilterColorMatrix::create() { +FilterPrimitive *FilterColorMatrix::create() +{ return new FilterColorMatrix(); } -FilterColorMatrix::~FilterColorMatrix() -= default; +FilterColorMatrix::~FilterColorMatrix() = default; -FilterColorMatrix::ColorMatrixMatrix::ColorMatrixMatrix(std::vector const &values) { +FilterColorMatrix::ColorMatrixMatrix::ColorMatrixMatrix(std::vector const &values) +{ unsigned limit = std::min(static_cast(20), values.size()); for (unsigned i = 0; i < limit; ++i) { if (i % 5 == 4) { - _v[i] = round(values[i]*255*255); + _v[i] = round(values[i] * 255 * 255); } else { - _v[i] = round(values[i]*255); + _v[i] = round(values[i] * 255); } } for (unsigned i = limit; i < 20; ++i) { @@ -46,7 +48,8 @@ FilterColorMatrix::ColorMatrixMatrix::ColorMatrixMatrix(std::vector cons } } -guint32 FilterColorMatrix::ColorMatrixMatrix::operator()(guint32 in) { +guint32 FilterColorMatrix::ColorMatrixMatrix::operator()(guint32 in) +{ EXTRACT_ARGB32(in, a, r, g, b) // we need to un-premultiply alpha values for this type of matrix // TODO: unpremul can be ignored if there is an identity mapping on the alpha channel @@ -56,14 +59,14 @@ guint32 FilterColorMatrix::ColorMatrixMatrix::operator()(guint32 in) { b = unpremul_alpha(b, a); } - gint32 ro = r*_v[0] + g*_v[1] + b*_v[2] + a*_v[3] + _v[4]; - gint32 go = r*_v[5] + g*_v[6] + b*_v[7] + a*_v[8] + _v[9]; - gint32 bo = r*_v[10] + g*_v[11] + b*_v[12] + a*_v[13] + _v[14]; - gint32 ao = r*_v[15] + g*_v[16] + b*_v[17] + a*_v[18] + _v[19]; - ro = (pxclamp(ro, 0, 255*255) + 127) / 255; - go = (pxclamp(go, 0, 255*255) + 127) / 255; - bo = (pxclamp(bo, 0, 255*255) + 127) / 255; - ao = (pxclamp(ao, 0, 255*255) + 127) / 255; + gint32 ro = r * _v[0] + g * _v[1] + b * _v[2] + a * _v[3] + _v[4]; + gint32 go = r * _v[5] + g * _v[6] + b * _v[7] + a * _v[8] + _v[9]; + gint32 bo = r * _v[10] + g * _v[11] + b * _v[12] + a * _v[13] + _v[14]; + gint32 ao = r * _v[15] + g * _v[16] + b * _v[17] + a * _v[18] + _v[19]; + ro = (pxclamp(ro, 0, 255 * 255) + 127) / 255; + go = (pxclamp(go, 0, 255 * 255) + 127) / 255; + bo = (pxclamp(bo, 0, 255 * 255) + 127) / 255; + ao = (pxclamp(ao, 0, 255 * 255) + 127) / 255; ro = premul_alpha(ro, ao); go = premul_alpha(go, ao); @@ -73,55 +76,67 @@ guint32 FilterColorMatrix::ColorMatrixMatrix::operator()(guint32 in) { return pxout; } - -struct ColorMatrixSaturate { - ColorMatrixSaturate(double v_in) { +struct ColorMatrixSaturate +{ + ColorMatrixSaturate(double v_in) + { // clamp parameter instead of clamping color values double v = CLAMP(v_in, 0.0, 1.0); - _v[0] = 0.213+0.787*v; _v[1] = 0.715-0.715*v; _v[2] = 0.072-0.072*v; - _v[3] = 0.213-0.213*v; _v[4] = 0.715+0.285*v; _v[5] = 0.072-0.072*v; - _v[6] = 0.213-0.213*v; _v[7] = 0.715-0.715*v; _v[8] = 0.072+0.928*v; + _v[0] = 0.213 + 0.787 * v; + _v[1] = 0.715 - 0.715 * v; + _v[2] = 0.072 - 0.072 * v; + _v[3] = 0.213 - 0.213 * v; + _v[4] = 0.715 + 0.285 * v; + _v[5] = 0.072 - 0.072 * v; + _v[6] = 0.213 - 0.213 * v; + _v[7] = 0.715 - 0.715 * v; + _v[8] = 0.072 + 0.928 * v; } - guint32 operator()(guint32 in) { + guint32 operator()(guint32 in) + { EXTRACT_ARGB32(in, a, r, g, b) // Note: this cannot be done in fixed point, because the loss of precision // causes overflow for some values of v - guint32 ro = r*_v[0] + g*_v[1] + b*_v[2] + 0.5; - guint32 go = r*_v[3] + g*_v[4] + b*_v[5] + 0.5; - guint32 bo = r*_v[6] + g*_v[7] + b*_v[8] + 0.5; + guint32 ro = r * _v[0] + g * _v[1] + b * _v[2] + 0.5; + guint32 go = r * _v[3] + g * _v[4] + b * _v[5] + 0.5; + guint32 bo = r * _v[6] + g * _v[7] + b * _v[8] + 0.5; ASSEMBLE_ARGB32(pxout, a, ro, go, bo) return pxout; } + private: double _v[9]; }; -struct ColorMatrixHueRotate { - ColorMatrixHueRotate(double v) { +struct ColorMatrixHueRotate +{ + ColorMatrixHueRotate(double v) + { double sinhue, coshue; - Geom::sincos(v * M_PI/180.0, sinhue, coshue); + Geom::sincos(v * M_PI / 180.0, sinhue, coshue); - _v[0] = round((0.213 +0.787*coshue -0.213*sinhue)*255); - _v[1] = round((0.715 -0.715*coshue -0.715*sinhue)*255); - _v[2] = round((0.072 -0.072*coshue +0.928*sinhue)*255); + _v[0] = round((0.213 + 0.787 * coshue - 0.213 * sinhue) * 255); + _v[1] = round((0.715 - 0.715 * coshue - 0.715 * sinhue) * 255); + _v[2] = round((0.072 - 0.072 * coshue + 0.928 * sinhue) * 255); - _v[3] = round((0.213 -0.213*coshue +0.143*sinhue)*255); - _v[4] = round((0.715 +0.285*coshue +0.140*sinhue)*255); - _v[5] = round((0.072 -0.072*coshue -0.283*sinhue)*255); + _v[3] = round((0.213 - 0.213 * coshue + 0.143 * sinhue) * 255); + _v[4] = round((0.715 + 0.285 * coshue + 0.140 * sinhue) * 255); + _v[5] = round((0.072 - 0.072 * coshue - 0.283 * sinhue) * 255); - _v[6] = round((0.213 -0.213*coshue -0.787*sinhue)*255); - _v[7] = round((0.715 -0.715*coshue +0.715*sinhue)*255); - _v[8] = round((0.072 +0.928*coshue +0.072*sinhue)*255); + _v[6] = round((0.213 - 0.213 * coshue - 0.787 * sinhue) * 255); + _v[7] = round((0.715 - 0.715 * coshue + 0.715 * sinhue) * 255); + _v[8] = round((0.072 + 0.928 * coshue + 0.072 * sinhue) * 255); } - guint32 operator()(guint32 in) { + guint32 operator()(guint32 in) + { EXTRACT_ARGB32(in, a, r, g, b) - gint32 maxpx = a*255; - gint32 ro = r*_v[0] + g*_v[1] + b*_v[2]; - gint32 go = r*_v[3] + g*_v[4] + b*_v[5]; - gint32 bo = r*_v[6] + g*_v[7] + b*_v[8]; + gint32 maxpx = a * 255; + gint32 ro = r * _v[0] + g * _v[1] + b * _v[2]; + gint32 go = r * _v[3] + g * _v[4] + b * _v[5]; + gint32 bo = r * _v[6] + g * _v[7] + b * _v[8]; ro = (pxclamp(ro, 0, maxpx) + 127) / 255; go = (pxclamp(go, 0, maxpx) + 127) / 255; bo = (pxclamp(bo, 0, maxpx) + 127) / 255; @@ -129,12 +144,15 @@ struct ColorMatrixHueRotate { ASSEMBLE_ARGB32(pxout, a, ro, go, bo) return pxout; } + private: gint32 _v[9]; }; -struct ColorMatrixLuminanceToAlpha { - guint32 operator()(guint32 in) { +struct ColorMatrixLuminanceToAlpha +{ + guint32 operator()(guint32 in) + { // original computation in double: r*0.2125 + g*0.7154 + b*0.0721 EXTRACT_ARGB32(in, a, r, g, b) // unpremultiply color values @@ -143,7 +161,7 @@ struct ColorMatrixLuminanceToAlpha { g = unpremul_alpha(g, a); b = unpremul_alpha(b, a); } - guint32 ao = r*54 + g*182 + b*18; + guint32 ao = r * 54 + g * 182 + b * 18; return ((ao + 127) / 255) << 24; } }; @@ -157,10 +175,10 @@ void FilterColorMatrix::render_cairo(FilterSlot &slot) // might be used as input to another primitive but it is likely that all the primitives in a given // filter use the same color interpolation space so we don't copy the input before converting. SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; - if( _style ) { + if (_style) { ci_fp = (SPColorInterpolation)_style->color_interpolation_filters.computed; } - set_cairo_surface_ci( input, ci_fp ); + set_cairo_surface_ci(input, ci_fp); if (type == COLORMATRIX_LUMINANCETOALPHA) { out = ink_cairo_surface_create_same_size(input, CAIRO_CONTENT_ALPHA); @@ -171,21 +189,21 @@ void FilterColorMatrix::render_cairo(FilterSlot &slot) } switch (type) { - case COLORMATRIX_MATRIX: - ink_cairo_surface_filter(input, out, FilterColorMatrix::ColorMatrixMatrix(values)); - break; - case COLORMATRIX_SATURATE: - ink_cairo_surface_filter(input, out, ColorMatrixSaturate(value)); - break; - case COLORMATRIX_HUEROTATE: - ink_cairo_surface_filter(input, out, ColorMatrixHueRotate(value)); - break; - case COLORMATRIX_LUMINANCETOALPHA: - ink_cairo_surface_filter(input, out, ColorMatrixLuminanceToAlpha()); - break; - case COLORMATRIX_ENDTYPE: - default: - break; + case COLORMATRIX_MATRIX: + ink_cairo_surface_filter(input, out, FilterColorMatrix::ColorMatrixMatrix(values)); + break; + case COLORMATRIX_SATURATE: + ink_cairo_surface_filter(input, out, ColorMatrixSaturate(value)); + break; + case COLORMATRIX_HUEROTATE: + ink_cairo_surface_filter(input, out, ColorMatrixHueRotate(value)); + break; + case COLORMATRIX_LUMINANCETOALPHA: + ink_cairo_surface_filter(input, out, ColorMatrixLuminanceToAlpha()); + break; + case COLORMATRIX_ENDTYPE: + default: + break; } slot.set(_output, out); @@ -202,16 +220,19 @@ double FilterColorMatrix::complexity(Geom::Affine const &) return 2.0; } -void FilterColorMatrix::set_type(FilterColorMatrixType t){ - type = t; +void FilterColorMatrix::set_type(FilterColorMatrixType t) +{ + type = t; } -void FilterColorMatrix::set_value(gdouble v){ - value = v; +void FilterColorMatrix::set_value(gdouble v) +{ + value = v; } -void FilterColorMatrix::set_values(std::vector const &v){ - values = v; +void FilterColorMatrix::set_values(std::vector const &v) +{ + values = v; } } /* namespace Filters */ diff --git a/src/display/nr-filter-colormatrix.h b/src/display/nr-filter-colormatrix.h index 8e35a358e339eb9876a2fc30e52eef08c1186476..c700c3cbe3dcee1c83511d01d462051d1e8babf4 100644 --- a/src/display/nr-filter-colormatrix.h +++ b/src/display/nr-filter-colormatrix.h @@ -13,8 +13,9 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include <2geom/forward.h> +#include + #include "display/nr-filter-primitive.h" typedef unsigned int guint32; @@ -25,7 +26,8 @@ namespace Filters { class FilterSlot; -enum FilterColorMatrixType { +enum FilterColorMatrixType +{ COLORMATRIX_MATRIX, COLORMATRIX_SATURATE, COLORMATRIX_HUEROTATE, @@ -33,7 +35,8 @@ enum FilterColorMatrixType { COLORMATRIX_ENDTYPE }; -class FilterColorMatrix : public FilterPrimitive { +class FilterColorMatrix : public FilterPrimitive +{ public: FilterColorMatrix(); static FilterPrimitive *create(); @@ -50,9 +53,11 @@ public: Glib::ustring name() override { return Glib::ustring("Color Matrix"); } public: - struct ColorMatrixMatrix { + struct ColorMatrixMatrix + { ColorMatrixMatrix(std::vector const &values); guint32 operator()(guint32 in); + private: gint32 _v[20]; }; diff --git a/src/display/nr-filter-component-transfer.cpp b/src/display/nr-filter-component-transfer.cpp index a9439ec93152d3835c883b58945fbac48a490ba5..4cb75c8b2c13cd14b84533b8f20d303de0c82b45 100644 --- a/src/display/nr-filter-component-transfer.cpp +++ b/src/display/nr-filter-component-transfer.cpp @@ -11,29 +11,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/nr-filter-component-transfer.h" + #include + #include "display/cairo-templates.h" #include "display/cairo-utils.h" -#include "display/nr-filter-component-transfer.h" #include "display/nr-filter-slot.h" namespace Inkscape { namespace Filters { -FilterComponentTransfer::FilterComponentTransfer() -= default; +FilterComponentTransfer::FilterComponentTransfer() = default; -FilterPrimitive * FilterComponentTransfer::create() { +FilterPrimitive *FilterComponentTransfer::create() +{ return new FilterComponentTransfer(); } -FilterComponentTransfer::~FilterComponentTransfer() -= default; +FilterComponentTransfer::~FilterComponentTransfer() = default; -struct UnmultiplyAlpha { - guint32 operator()(guint32 in) { +struct UnmultiplyAlpha +{ + guint32 operator()(guint32 in) + { EXTRACT_ARGB32(in, a, r, g, b); - if (a == 0 ) + if (a == 0) return in; r = unpremul_alpha(r, a); g = unpremul_alpha(g, a); @@ -43,10 +46,12 @@ struct UnmultiplyAlpha { } }; -struct MultiplyAlpha { - guint32 operator()(guint32 in) { +struct MultiplyAlpha +{ + guint32 operator()(guint32 in) + { EXTRACT_ARGB32(in, a, r, g, b); - if (a == 0 ) + if (a == 0) return in; r = premul_alpha(r, a); g = premul_alpha(g, a); @@ -56,90 +61,106 @@ struct MultiplyAlpha { } }; -struct ComponentTransfer { +struct ComponentTransfer +{ ComponentTransfer(guint32 color) : _shift(color * 8) , _mask(0xff << _shift) {} + protected: guint32 _shift; guint32 _mask; }; -struct ComponentTransferTable : public ComponentTransfer { +struct ComponentTransferTable : public ComponentTransfer +{ ComponentTransferTable(guint32 color, std::vector const &values) : ComponentTransfer(color) , _v(values.size()) { - for (unsigned i = 0; i< values.size(); ++i) { + for (unsigned i = 0; i < values.size(); ++i) { _v[i] = round(CLAMP(values[i], 0.0, 1.0) * 255); } } - guint32 operator()(guint32 in) { + guint32 operator()(guint32 in) + { guint32 component = (in & _mask) >> _shift; guint32 k = (_v.size() - 1) * component; - guint32 dx = k % 255; k /= 255; - component = _v[k]*255 + (_v[k+1] - _v[k])*dx; + guint32 dx = k % 255; + k /= 255; + component = _v[k] * 255 + (_v[k + 1] - _v[k]) * dx; component = (component + 127) / 255; return (in & ~_mask) | (component << _shift); } + private: std::vector _v; }; -struct ComponentTransferDiscrete : public ComponentTransfer { +struct ComponentTransferDiscrete : public ComponentTransfer +{ ComponentTransferDiscrete(guint32 color, std::vector const &values) : ComponentTransfer(color) , _v(values.size()) { - for (unsigned i = 0; i< values.size(); ++i) { + for (unsigned i = 0; i < values.size(); ++i) { _v[i] = round(CLAMP(values[i], 0.0, 1.0) * 255); } } - guint32 operator()(guint32 in) { + guint32 operator()(guint32 in) + { guint32 component = (in & _mask) >> _shift; guint32 k = (_v.size()) * component / 255; - if( k == _v.size() ) --k; + if (k == _v.size()) + --k; component = _v[k]; return (in & ~_mask) | ((guint32)component << _shift); } + private: std::vector _v; }; -struct ComponentTransferLinear : public ComponentTransfer { +struct ComponentTransferLinear : public ComponentTransfer +{ ComponentTransferLinear(guint32 color, double intercept, double slope) : ComponentTransfer(color) - , _intercept(round(intercept*255*255)) - , _slope(round(slope*255)) + , _intercept(round(intercept * 255 * 255)) + , _slope(round(slope * 255)) {} - guint32 operator()(guint32 in) { + guint32 operator()(guint32 in) + { gint32 component = (in & _mask) >> _shift; // TODO: this can probably be reduced to something simpler - component = pxclamp(_slope * component + _intercept, 0, 255*255); + component = pxclamp(_slope * component + _intercept, 0, 255 * 255); component = (component + 127) / 255; return (in & ~_mask) | (component << _shift); } + private: gint32 _intercept; gint32 _slope; }; -struct ComponentTransferGamma : public ComponentTransfer { +struct ComponentTransferGamma : public ComponentTransfer +{ ComponentTransferGamma(guint32 color, double amplitude, double exponent, double offset) : ComponentTransfer(color) , _amplitude(amplitude) , _exponent(exponent) , _offset(offset) {} - guint32 operator()(guint32 in) { + guint32 operator()(guint32 in) + { double component = (in & _mask) >> _shift; component /= 255.0; component = _amplitude * pow(component, _exponent) + _offset; guint32 cpx = pxclamp(component * 255.0, 0, 255); return (in & ~_mask) | (cpx << _shift); } + private: double _amplitude; double _exponent; @@ -155,13 +176,13 @@ void FilterComponentTransfer::render_cairo(FilterSlot &slot) // might be used as input to another primitive but it is likely that all the primitives in a given // filter use the same color interpolation space so we don't copy the input before converting. SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; - if( _style ) { + if (_style) { ci_fp = (SPColorInterpolation)_style->color_interpolation_filters.computed; - set_cairo_surface_ci(out, ci_fp ); + set_cairo_surface_ci(out, ci_fp); } - set_cairo_surface_ci( input, ci_fp ); + set_cairo_surface_ci(input, ci_fp); - //cairo_surface_t *outtemp = ink_cairo_surface_create_identical(out); + // cairo_surface_t *outtemp = ink_cairo_surface_create_identical(out); ink_cairo_surface_blit(input, out); // We need to operate on unmultipled by alpha color values otherwise a change in alpha screws @@ -172,44 +193,40 @@ void FilterComponentTransfer::render_cairo(FilterSlot &slot) // Cairo: R = 2, G = 1, B = 0, A = 3 // If tableValues is empty, use identity. for (unsigned i = 0; i < 4; ++i) { - guint32 color = 2 - i; - if(i==3) color = 3; // alpha + if (i == 3) + color = 3; // alpha switch (type[i]) { - case COMPONENTTRANSFER_TYPE_TABLE: - if(!tableValues[i].empty()) { - ink_cairo_surface_filter(out, out, - ComponentTransferTable(color, tableValues[i])); - } - break; - case COMPONENTTRANSFER_TYPE_DISCRETE: - if(!tableValues[i].empty()) { - ink_cairo_surface_filter(out, out, - ComponentTransferDiscrete(color, tableValues[i])); - } - break; - case COMPONENTTRANSFER_TYPE_LINEAR: - ink_cairo_surface_filter(out, out, - ComponentTransferLinear(color, intercept[i], slope[i])); - break; - case COMPONENTTRANSFER_TYPE_GAMMA: - ink_cairo_surface_filter(out, out, - ComponentTransferGamma(color, amplitude[i], exponent[i], offset[i])); - break; - case COMPONENTTRANSFER_TYPE_ERROR: - case COMPONENTTRANSFER_TYPE_IDENTITY: - default: - break; + case COMPONENTTRANSFER_TYPE_TABLE: + if (!tableValues[i].empty()) { + ink_cairo_surface_filter(out, out, ComponentTransferTable(color, tableValues[i])); + } + break; + case COMPONENTTRANSFER_TYPE_DISCRETE: + if (!tableValues[i].empty()) { + ink_cairo_surface_filter(out, out, ComponentTransferDiscrete(color, tableValues[i])); + } + break; + case COMPONENTTRANSFER_TYPE_LINEAR: + ink_cairo_surface_filter(out, out, ComponentTransferLinear(color, intercept[i], slope[i])); + break; + case COMPONENTTRANSFER_TYPE_GAMMA: + ink_cairo_surface_filter(out, out, ComponentTransferGamma(color, amplitude[i], exponent[i], offset[i])); + break; + case COMPONENTTRANSFER_TYPE_ERROR: + case COMPONENTTRANSFER_TYPE_IDENTITY: + default: + break; } - //ink_cairo_surface_blit(out, outtemp); + // ink_cairo_surface_blit(out, outtemp); } ink_cairo_surface_filter(out, out, MultiplyAlpha()); slot.set(_output, out); cairo_surface_destroy(out); - //cairo_surface_destroy(outtemp); + // cairo_surface_destroy(outtemp); } bool FilterComponentTransfer::can_handle_affine(Geom::Affine const &) diff --git a/src/display/nr-filter-component-transfer.h b/src/display/nr-filter-component-transfer.h index 9d1ea1456ed35de04b5ff31031506a339d5aa141..239f243ec9355f5dbbc9c9b7c692477671f9c415 100644 --- a/src/display/nr-filter-component-transfer.h +++ b/src/display/nr-filter-component-transfer.h @@ -14,6 +14,7 @@ */ #include + #include "display/nr-filter-primitive.h" namespace Inkscape { @@ -21,7 +22,8 @@ namespace Filters { class FilterSlot; -enum FilterComponentTransferType { +enum FilterComponentTransferType +{ COMPONENTTRANSFER_TYPE_IDENTITY, COMPONENTTRANSFER_TYPE_TABLE, COMPONENTTRANSFER_TYPE_DISCRETE, @@ -30,7 +32,8 @@ enum FilterComponentTransferType { COMPONENTTRANSFER_TYPE_ERROR }; -class FilterComponentTransfer : public FilterPrimitive { +class FilterComponentTransfer : public FilterPrimitive +{ public: FilterComponentTransfer(); static FilterPrimitive *create(); diff --git a/src/display/nr-filter-composite.cpp b/src/display/nr-filter-composite.cpp index 4bb5685b080cdc4be3a5d12a81083573a61a20cd..b2bdb45efb536c1b3de9fd0087eb2eb9e7d83c0d 100644 --- a/src/display/nr-filter-composite.cpp +++ b/src/display/nr-filter-composite.cpp @@ -10,54 +10,62 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/nr-filter-composite.h" + #include #include "display/cairo-templates.h" #include "display/cairo-utils.h" -#include "display/nr-filter-composite.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" namespace Inkscape { namespace Filters { -FilterComposite::FilterComposite() : - op(COMPOSITE_DEFAULT), k1(0), k2(0), k3(0), k4(0), - _input2(Inkscape::Filters::NR_FILTER_SLOT_NOT_SET) +FilterComposite::FilterComposite() + : op(COMPOSITE_DEFAULT) + , k1(0) + , k2(0) + , k3(0) + , k4(0) + , _input2(Inkscape::Filters::NR_FILTER_SLOT_NOT_SET) {} -FilterPrimitive * FilterComposite::create() { +FilterPrimitive *FilterComposite::create() +{ return new FilterComposite(); } -FilterComposite::~FilterComposite() -= default; +FilterComposite::~FilterComposite() = default; -struct ComposeArithmetic { +struct ComposeArithmetic +{ ComposeArithmetic(double k1, double k2, double k3, double k4) : _k1(round(k1 * 255)) - , _k2(round(k2 * 255*255)) - , _k3(round(k3 * 255*255)) - , _k4(round(k4 * 255*255*255)) + , _k2(round(k2 * 255 * 255)) + , _k3(round(k3 * 255 * 255)) + , _k4(round(k4 * 255 * 255 * 255)) {} - guint32 operator()(guint32 in1, guint32 in2) { + guint32 operator()(guint32 in1, guint32 in2) + { EXTRACT_ARGB32(in1, aa, ra, ga, ba) EXTRACT_ARGB32(in2, ab, rb, gb, bb) - gint32 ao = _k1*aa*ab + _k2*aa + _k3*ab + _k4; - gint32 ro = _k1*ra*rb + _k2*ra + _k3*rb + _k4; - gint32 go = _k1*ga*gb + _k2*ga + _k3*gb + _k4; - gint32 bo = _k1*ba*bb + _k2*ba + _k3*bb + _k4; + gint32 ao = _k1 * aa * ab + _k2 * aa + _k3 * ab + _k4; + gint32 ro = _k1 * ra * rb + _k2 * ra + _k3 * rb + _k4; + gint32 go = _k1 * ga * gb + _k2 * ga + _k3 * gb + _k4; + gint32 bo = _k1 * ba * bb + _k2 * ba + _k3 * bb + _k4; - ao = pxclamp(ao, 0, 255*255*255); // r, g and b are premultiplied, so should be clamped to the alpha channel - ro = (pxclamp(ro, 0, ao) + (255*255/2)) / (255*255); - go = (pxclamp(go, 0, ao) + (255*255/2)) / (255*255); - bo = (pxclamp(bo, 0, ao) + (255*255/2)) / (255*255); - ao = (ao + (255*255/2)) / (255*255); + ao = pxclamp(ao, 0, 255 * 255 * 255); // r, g and b are premultiplied, so should be clamped to the alpha channel + ro = (pxclamp(ro, 0, ao) + (255 * 255 / 2)) / (255 * 255); + go = (pxclamp(go, 0, ao) + (255 * 255 / 2)) / (255 * 255); + bo = (pxclamp(bo, 0, ao) + (255 * 255 / 2)) / (255 * 255); + ao = (ao + (255 * 255 / 2)) / (255 * 255); ASSEMBLE_ARGB32(pxout, ao, ro, go, bo) return pxout; } + private: gint32 _k1, _k2, _k3, _k4; }; @@ -70,17 +78,17 @@ void FilterComposite::render_cairo(FilterSlot &slot) // We may need to transform input surface to correct color interpolation space. The input surface // might be used as input to another primitive but it is likely that all the primitives in a given // filter use the same color interpolation space so we don't copy the input before converting. - SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; - if( _style ) { + SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; + if (_style) { ci_fp = (SPColorInterpolation)_style->color_interpolation_filters.computed; } - set_cairo_surface_ci( input1, ci_fp ); - set_cairo_surface_ci( input2, ci_fp ); + set_cairo_surface_ci(input1, ci_fp); + set_cairo_surface_ci(input2, ci_fp); cairo_surface_t *out = ink_cairo_surface_create_output(input1, input2); - set_cairo_surface_ci(out, ci_fp ); + set_cairo_surface_ci(out, ci_fp); - Geom::Rect vp = filter_primitive_area( slot.get_units() ); + Geom::Rect vp = filter_primitive_area(slot.get_units()); slot.set_primitive_area(_output, vp); // Needed for tiling if (op == COMPOSITE_ARITHMETIC) { @@ -89,51 +97,51 @@ void FilterComposite::render_cairo(FilterSlot &slot) ink_cairo_surface_blit(input2, out); cairo_t *ct = cairo_create(out); cairo_set_source_surface(ct, input1, 0, 0); - switch(op) { - case COMPOSITE_IN: - cairo_set_operator(ct, CAIRO_OPERATOR_IN); - break; - case COMPOSITE_OUT: - cairo_set_operator(ct, CAIRO_OPERATOR_OUT); - break; - case COMPOSITE_ATOP: - cairo_set_operator(ct, CAIRO_OPERATOR_ATOP); - break; - case COMPOSITE_XOR: - cairo_set_operator(ct, CAIRO_OPERATOR_XOR); - break; + switch (op) { + case COMPOSITE_IN: + cairo_set_operator(ct, CAIRO_OPERATOR_IN); + break; + case COMPOSITE_OUT: + cairo_set_operator(ct, CAIRO_OPERATOR_OUT); + break; + case COMPOSITE_ATOP: + cairo_set_operator(ct, CAIRO_OPERATOR_ATOP); + break; + case COMPOSITE_XOR: + cairo_set_operator(ct, CAIRO_OPERATOR_XOR); + break; #ifdef WITH_CSSCOMPOSITE - /* New CSS Operators */ - case COMPOSITE_CLEAR: - cairo_set_operator(ct, CAIRO_OPERATOR_CLEAR); - break; - case COMPOSITE_COPY: - cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); - break; - case COMPOSITE_DESTINATION: - cairo_set_operator(ct, CAIRO_OPERATOR_DEST); - break; - case COMPOSITE_DESTINATION_OVER: - cairo_set_operator(ct, CAIRO_OPERATOR_DEST_OVER); - break; - case COMPOSITE_DESTINATION_IN: - cairo_set_operator(ct, CAIRO_OPERATOR_DEST_IN); - break; - case COMPOSITE_DESTINATION_OUT: - cairo_set_operator(ct, CAIRO_OPERATOR_DEST_OUT); - break; - case COMPOSITE_DESTINATION_ATOP: - cairo_set_operator(ct, CAIRO_OPERATOR_DEST_ATOP); - break; - case COMPOSITE_LIGHTER: - cairo_set_operator(ct, CAIRO_OPERATOR_ADD); - break; + /* New CSS Operators */ + case COMPOSITE_CLEAR: + cairo_set_operator(ct, CAIRO_OPERATOR_CLEAR); + break; + case COMPOSITE_COPY: + cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); + break; + case COMPOSITE_DESTINATION: + cairo_set_operator(ct, CAIRO_OPERATOR_DEST); + break; + case COMPOSITE_DESTINATION_OVER: + cairo_set_operator(ct, CAIRO_OPERATOR_DEST_OVER); + break; + case COMPOSITE_DESTINATION_IN: + cairo_set_operator(ct, CAIRO_OPERATOR_DEST_IN); + break; + case COMPOSITE_DESTINATION_OUT: + cairo_set_operator(ct, CAIRO_OPERATOR_DEST_OUT); + break; + case COMPOSITE_DESTINATION_ATOP: + cairo_set_operator(ct, CAIRO_OPERATOR_DEST_ATOP); + break; + case COMPOSITE_LIGHTER: + cairo_set_operator(ct, CAIRO_OPERATOR_ADD); + break; #endif - case COMPOSITE_OVER: - case COMPOSITE_DEFAULT: - default: - // OVER is the default operator - break; + case COMPOSITE_OVER: + case COMPOSITE_DEFAULT: + default: + // OVER is the default operator + break; } cairo_paint(ct); cairo_destroy(ct); @@ -148,16 +156,21 @@ bool FilterComposite::can_handle_affine(Geom::Affine const &) return true; } -void FilterComposite::set_input(int input) { +void FilterComposite::set_input(int input) +{ _input = input; } -void FilterComposite::set_input(int input, int slot) { - if (input == 0) _input = slot; - if (input == 1) _input2 = slot; +void FilterComposite::set_input(int input, int slot) +{ + if (input == 0) + _input = slot; + if (input == 1) + _input2 = slot; } -void FilterComposite::set_operator(FeCompositeOperator op) { +void FilterComposite::set_operator(FeCompositeOperator op) +{ if (op == COMPOSITE_DEFAULT) { this->op = COMPOSITE_OVER; } else if (op != COMPOSITE_ENDOPERATOR) { @@ -165,7 +178,8 @@ void FilterComposite::set_operator(FeCompositeOperator op) { } } -void FilterComposite::set_arithmetic(double k1, double k2, double k3, double k4) { +void FilterComposite::set_arithmetic(double k1, double k2, double k3, double k4) +{ if (!std::isfinite(k1) || !std::isfinite(k2) || !std::isfinite(k3) || !std::isfinite(k4)) { g_warning("Non-finite parameter for feComposite arithmetic operator"); return; diff --git a/src/display/nr-filter-composite.h b/src/display/nr-filter-composite.h index a76f4cc413e549ab0e2fa280424c221770b88a5f..71a9093dc000a7c7bb4090002fcb8a41c79566ee 100644 --- a/src/display/nr-filter-composite.h +++ b/src/display/nr-filter-composite.h @@ -13,15 +13,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "object/filters/composite.h" #include "display/nr-filter-primitive.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" +#include "object/filters/composite.h" namespace Inkscape { namespace Filters { -class FilterComposite : public FilterPrimitive { +class FilterComposite : public FilterPrimitive +{ public: FilterComposite(); static FilterPrimitive *create(); diff --git a/src/display/nr-filter-convolve-matrix.cpp b/src/display/nr-filter-convolve-matrix.cpp index 1e9bdb0c671140c1aaae47f89ea2e9b0e31b4b36..91d7aa7b572745c67f586e5ba7ffdfb1aa4a1d77 100644 --- a/src/display/nr-filter-convolve-matrix.cpp +++ b/src/display/nr-filter-convolve-matrix.cpp @@ -11,10 +11,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/nr-filter-convolve-matrix.h" + #include + #include "display/cairo-templates.h" #include "display/cairo-utils.h" -#include "display/nr-filter-convolve-matrix.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" #include "display/nr-filter-utils.h" @@ -22,25 +24,26 @@ namespace Inkscape { namespace Filters { -FilterConvolveMatrix::FilterConvolveMatrix() -= default; +FilterConvolveMatrix::FilterConvolveMatrix() = default; -FilterPrimitive * FilterConvolveMatrix::create() { +FilterPrimitive *FilterConvolveMatrix::create() +{ return new FilterConvolveMatrix(); } -FilterConvolveMatrix::~FilterConvolveMatrix() -= default; +FilterConvolveMatrix::~FilterConvolveMatrix() = default; -enum PreserveAlphaMode { +enum PreserveAlphaMode +{ PRESERVE_ALPHA, NO_PRESERVE_ALPHA }; template -struct ConvolveMatrix : public SurfaceSynth { - ConvolveMatrix(cairo_surface_t *s, int targetX, int targetY, int orderX, int orderY, - double divisor, double bias, std::vector const &kernel) +struct ConvolveMatrix : public SurfaceSynth +{ + ConvolveMatrix(cairo_surface_t *s, int targetX, int targetY, int orderX, int orderY, double divisor, double bias, + std::vector const &kernel) : SurfaceSynth(s) , _kernel(kernel.size()) , _targetX(targetX) @@ -57,7 +60,8 @@ struct ConvolveMatrix : public SurfaceSynth { std::reverse(_kernel.begin(), _kernel.end()); } - guint32 operator()(int x, int y) const { + guint32 operator()(int x, int y) const + { int startx = std::max(0, x - _targetX); int starty = std::max(0, y - _targetY); int endx = std::min(_w, startx + _orderX); @@ -70,7 +74,7 @@ struct ConvolveMatrix : public SurfaceSynth { for (int j = 0; j < limitx; ++j) { guint32 px = pixelAt(startx + j, starty + i); double coeff = _kernel[i * _orderX + j]; - EXTRACT_ARGB32(px, a,r,g,b) + EXTRACT_ARGB32(px, a, r, g, b) sumr += r * coeff; sumg += g * coeff; @@ -90,7 +94,7 @@ struct ConvolveMatrix : public SurfaceSynth { guint32 ro = pxclamp(round(sumr + ao * _bias), 0, ao); guint32 go = pxclamp(round(sumg + ao * _bias), 0, ao); guint32 bo = pxclamp(round(sumb + ao * _bias), 0, ao); - ASSEMBLE_ARGB32(pxout, ao,ro,go,bo); + ASSEMBLE_ARGB32(pxout, ao, ro, go, bo); return pxout; } @@ -105,16 +109,16 @@ void FilterConvolveMatrix::render_cairo(FilterSlot &slot) static bool bias_warning = false; static bool edge_warning = false; - if (orderX<=0 || orderY<=0) { + if (orderX <= 0 || orderY <= 0) { g_warning("Empty kernel!"); return; } - if (targetX<0 || targetX>=orderX || targetY<0 || targetY>=orderY) { + if (targetX < 0 || targetX >= orderX || targetY < 0 || targetY >= orderY) { g_warning("Invalid target!"); return; } - if (kernelMatrix.size()!=(unsigned int)(orderX*orderY)) { - //g_warning("kernelMatrix does not have orderX*orderY elements!"); + if (kernelMatrix.size() != (unsigned int)(orderX * orderY)) { + // g_warning("kernelMatrix does not have orderX*orderY elements!"); return; } @@ -125,13 +129,13 @@ void FilterConvolveMatrix::render_cairo(FilterSlot &slot) // might be used as input to another primitive but it is likely that all the primitives in a given // filter use the same color interpolation space so we don't copy the input before converting. SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; - if( _style ) { + if (_style) { ci_fp = (SPColorInterpolation)_style->color_interpolation_filters.computed; set_cairo_surface_ci(out, ci_fp); } - set_cairo_surface_ci( input, ci_fp ); + set_cairo_surface_ci(input, ci_fp); - if (bias!=0 && !bias_warning) { + if (bias != 0 && !bias_warning) { g_warning("It is unknown whether Inkscape's implementation of bias in feConvolveMatrix " "is correct!"); bias_warning = true; @@ -143,16 +147,16 @@ void FilterConvolveMatrix::render_cairo(FilterSlot &slot) // but this does appear to go against the standard. // Note that Batik simply does not support bias!=0 } - if (edgeMode!=CONVOLVEMATRIX_EDGEMODE_NONE && !edge_warning) { + if (edgeMode != CONVOLVEMATRIX_EDGEMODE_NONE && !edge_warning) { g_warning("Inkscape only supports edgeMode=\"none\" (and a filter uses a different one)!"); edge_warning = true; } - //guint32 *in_data = reinterpret_cast(cairo_image_surface_get_data(input)); - //guint32 *out_data = reinterpret_cast(cairo_image_surface_get_data(out)); + // guint32 *in_data = reinterpret_cast(cairo_image_surface_get_data(input)); + // guint32 *out_data = reinterpret_cast(cairo_image_surface_get_data(out)); - //int width = cairo_image_surface_get_width(input); - //int height = cairo_image_surface_get_height(input); + // int width = cairo_image_surface_get_width(input); + // int height = cairo_image_surface_get_height(input); // Set up predivided kernel matrix /*std::vector kernel(kernelMatrix); @@ -161,66 +165,75 @@ void FilterConvolveMatrix::render_cairo(FilterSlot &slot) }*/ if (preserveAlpha) { - //convolve2D(out_data, in_data, width, height, &kernel.front(), orderX, orderY, + // convolve2D(out_data, in_data, width, height, &kernel.front(), orderX, orderY, // targetX, targetY, bias); - ink_cairo_surface_synthesize(out, ConvolveMatrix(input, - targetX, targetY, orderX, orderY, divisor, bias, kernelMatrix)); + ink_cairo_surface_synthesize( + out, ConvolveMatrix(input, targetX, targetY, orderX, orderY, divisor, bias, kernelMatrix)); } else { - //convolve2D(out_data, in_data, width, height, &kernel.front(), orderX, orderY, + // convolve2D(out_data, in_data, width, height, &kernel.front(), orderX, orderY, // targetX, targetY, bias); - ink_cairo_surface_synthesize(out, ConvolveMatrix(input, - targetX, targetY, orderX, orderY, divisor, bias, kernelMatrix)); + ink_cairo_surface_synthesize(out, ConvolveMatrix(input, targetX, targetY, orderX, orderY, + divisor, bias, kernelMatrix)); } slot.set(_output, out); cairo_surface_destroy(out); } -void FilterConvolveMatrix::set_targetX(int coord) { +void FilterConvolveMatrix::set_targetX(int coord) +{ targetX = coord; } -void FilterConvolveMatrix::set_targetY(int coord) { +void FilterConvolveMatrix::set_targetY(int coord) +{ targetY = coord; } -void FilterConvolveMatrix::set_orderX(int coord) { +void FilterConvolveMatrix::set_orderX(int coord) +{ orderX = coord; } -void FilterConvolveMatrix::set_orderY(int coord) { +void FilterConvolveMatrix::set_orderY(int coord) +{ orderY = coord; } -void FilterConvolveMatrix::set_divisor(double d) { +void FilterConvolveMatrix::set_divisor(double d) +{ divisor = d; } -void FilterConvolveMatrix::set_bias(double b) { +void FilterConvolveMatrix::set_bias(double b) +{ bias = b; } -void FilterConvolveMatrix::set_kernelMatrix(std::vector &km) { +void FilterConvolveMatrix::set_kernelMatrix(std::vector &km) +{ kernelMatrix = km; } -void FilterConvolveMatrix::set_edgeMode(FilterConvolveMatrixEdgeMode mode){ +void FilterConvolveMatrix::set_edgeMode(FilterConvolveMatrixEdgeMode mode) +{ edgeMode = mode; } -void FilterConvolveMatrix::set_preserveAlpha(bool pa){ +void FilterConvolveMatrix::set_preserveAlpha(bool pa) +{ preserveAlpha = pa; } -void FilterConvolveMatrix::area_enlarge(Geom::IntRect &area, Geom::Affine const &/*trans*/) +void FilterConvolveMatrix::area_enlarge(Geom::IntRect &area, Geom::Affine const & /*trans*/) { - //Seems to me that since this filter's operation is resolution dependent, + // Seems to me that since this filter's operation is resolution dependent, // some spurious pixels may still appear at the borders when low zooming or rotating. Needs a better fix. area.setMin(area.min() - Geom::IntPoint(targetX, targetY)); // This makes sure the last row/column in the original image corresponds // to the last row/column in the new image that can be convolved without // adjusting the boundary conditions). - area.setMax(area.max() + Geom::IntPoint(orderX - targetX - 1, orderY - targetY -1)); + area.setMax(area.max() + Geom::IntPoint(orderX - targetX - 1, orderY - targetY - 1)); } double FilterConvolveMatrix::complexity(Geom::Affine const &) diff --git a/src/display/nr-filter-convolve-matrix.h b/src/display/nr-filter-convolve-matrix.h index 26b2bf3224921ecb3c3d1b7633a52767ea44a8fd..80f003c63fcde339a0ec3caf20cd4e8acdb5543b 100644 --- a/src/display/nr-filter-convolve-matrix.h +++ b/src/display/nr-filter-convolve-matrix.h @@ -13,22 +13,25 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "display/nr-filter-primitive.h" #include +#include "display/nr-filter-primitive.h" + namespace Inkscape { namespace Filters { class FilterSlot; -enum FilterConvolveMatrixEdgeMode { +enum FilterConvolveMatrixEdgeMode +{ CONVOLVEMATRIX_EDGEMODE_DUPLICATE, CONVOLVEMATRIX_EDGEMODE_WRAP, CONVOLVEMATRIX_EDGEMODE_NONE, CONVOLVEMATRIX_EDGEMODE_ENDTYPE }; -class FilterConvolveMatrix : public FilterPrimitive { +class FilterConvolveMatrix : public FilterPrimitive +{ public: FilterConvolveMatrix(); static FilterPrimitive *create(); @@ -42,10 +45,10 @@ public: void set_targetX(int coord); void set_orderY(int coord); void set_orderX(int coord); - void set_kernelMatrix(std::vector& km); + void set_kernelMatrix(std::vector &km); void set_bias(double b); void set_divisor(double d); - void set_edgeMode(FilterConvolveMatrixEdgeMode mode); + void set_edgeMode(FilterConvolveMatrixEdgeMode mode); void set_preserveAlpha(bool pa); Glib::ustring name() override { return Glib::ustring("Convolve Matrix"); } diff --git a/src/display/nr-filter-diffuselighting.cpp b/src/display/nr-filter-diffuselighting.cpp index d33d513e6a5442c5e2a0c655b39db7041c9c8d97..f44f1b179408cd4b2741511fcd14d1274b091011 100644 --- a/src/display/nr-filter-diffuselighting.cpp +++ b/src/display/nr-filter-diffuselighting.cpp @@ -13,7 +13,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include @@ -26,13 +26,13 @@ #include "display/nr-filter-units.h" #include "display/nr-filter-utils.h" #include "display/nr-light.h" -#include "svg/svg-icc-color.h" #include "svg/svg-color.h" +#include "svg/svg-icc-color.h" namespace Inkscape { namespace Filters { -FilterDiffuseLighting::FilterDiffuseLighting() +FilterDiffuseLighting::FilterDiffuseLighting() { light_type = NO_LIGHT; diffuseConstant = 1; @@ -40,14 +40,15 @@ FilterDiffuseLighting::FilterDiffuseLighting() lighting_color = 0xffffffff; } -FilterPrimitive * FilterDiffuseLighting::create() { +FilterPrimitive *FilterDiffuseLighting::create() +{ return new FilterDiffuseLighting(); } -FilterDiffuseLighting::~FilterDiffuseLighting() -= default; +FilterDiffuseLighting::~FilterDiffuseLighting() = default; -struct DiffuseLight : public SurfaceSynth { +struct DiffuseLight : public SurfaceSynth +{ DiffuseLight(cairo_surface_t *bumpmap, double scale, double kd) : SurfaceSynth(bumpmap) , _scale(scale) @@ -55,7 +56,8 @@ struct DiffuseLight : public SurfaceSynth { {} protected: - guint32 diffuseLighting(int x, int y, NR::Fvector const &light, NR::Fvector const &light_components) { + guint32 diffuseLighting(int x, int y, NR::Fvector const &light, NR::Fvector const &light_components) + { NR::Fvector normal = surfaceNormalAt(x, y, _scale); double k = _kd * NR::scalar_product(normal, light); @@ -63,15 +65,16 @@ protected: guint32 g = CLAMP_D_TO_U8(k * light_components[LIGHT_GREEN]); guint32 b = CLAMP_D_TO_U8(k * light_components[LIGHT_BLUE]); - ASSEMBLE_ARGB32(pxout, 255,r,g,b) + ASSEMBLE_ARGB32(pxout, 255, r, g, b) return pxout; } double _scale, _kd; }; -struct DiffuseDistantLight : public DiffuseLight { - DiffuseDistantLight(cairo_surface_t *bumpmap, SPFeDistantLight *light, guint32 color, - double scale, double diffuse_constant) +struct DiffuseDistantLight : public DiffuseLight +{ + DiffuseDistantLight(cairo_surface_t *bumpmap, SPFeDistantLight *light, guint32 color, double scale, + double diffuse_constant) : DiffuseLight(bumpmap, scale, diffuse_constant) { DistantLight dl(light, color); @@ -79,17 +82,16 @@ struct DiffuseDistantLight : public DiffuseLight { dl.light_components(_light_components); } - guint32 operator()(int x, int y) { - return diffuseLighting(x, y, _lightv, _light_components); - } + guint32 operator()(int x, int y) { return diffuseLighting(x, y, _lightv, _light_components); } + private: NR::Fvector _lightv, _light_components; }; -struct DiffusePointLight : public DiffuseLight { - DiffusePointLight(cairo_surface_t *bumpmap, SPFePointLight *light, guint32 color, - Geom::Affine const &trans, double scale, double diffuse_constant, - double x0, double y0, int device_scale) +struct DiffusePointLight : public DiffuseLight +{ + DiffusePointLight(cairo_surface_t *bumpmap, SPFePointLight *light, guint32 color, Geom::Affine const &trans, + double scale, double diffuse_constant, double x0, double y0, int device_scale) : DiffuseLight(bumpmap, scale, diffuse_constant) , _light(light, color, trans, device_scale) , _x0(x0) @@ -98,33 +100,37 @@ struct DiffusePointLight : public DiffuseLight { _light.light_components(_light_components); } - guint32 operator()(int x, int y) { + guint32 operator()(int x, int y) + { NR::Fvector light; - _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y)/255.0); + _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y) / 255.0); return diffuseLighting(x, y, light, _light_components); } + private: PointLight _light; NR::Fvector _light_components; double _x0, _y0; }; -struct DiffuseSpotLight : public DiffuseLight { - DiffuseSpotLight(cairo_surface_t *bumpmap, SPFeSpotLight *light, guint32 color, - Geom::Affine const &trans, double scale, double diffuse_constant, - double x0, double y0, int device_scale) +struct DiffuseSpotLight : public DiffuseLight +{ + DiffuseSpotLight(cairo_surface_t *bumpmap, SPFeSpotLight *light, guint32 color, Geom::Affine const &trans, + double scale, double diffuse_constant, double x0, double y0, int device_scale) : DiffuseLight(bumpmap, scale, diffuse_constant) , _light(light, color, trans, device_scale) , _x0(x0) , _y0(y0) {} - guint32 operator()(int x, int y) { + guint32 operator()(int x, int y) + { NR::Fvector light, light_components; - _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y)/255.0); + _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y) / 255.0); _light.light_components(light_components, light); return diffuseLighting(x, y, light, light_components); } + private: SpotLight _light; double _x0, _y0; @@ -151,21 +157,21 @@ void FilterDiffuseLighting::render_cairo(FilterSlot &slot) #endif // Only alpha channel of input is used, no need to check input color_interpolation_filter value. - SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; - if( _style ) { + SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; + if (_style) { ci_fp = (SPColorInterpolation)_style->color_interpolation_filters.computed; // Lighting color is always defined in terms of sRGB, preconvert to linearRGB // if color_interpolation_filters set to linearRGB (for efficiency assuming // next filter primitive has same value of cif). - if( ci_fp == SP_CSS_COLOR_INTERPOLATION_LINEARRGB ) { - r = srgb_to_linear( r ); - g = srgb_to_linear( g ); - b = srgb_to_linear( b ); + if (ci_fp == SP_CSS_COLOR_INTERPOLATION_LINEARRGB) { + r = srgb_to_linear(r); + g = srgb_to_linear(g); + b = srgb_to_linear(b); } } - set_cairo_surface_ci(out, ci_fp ); - guint32 color = SP_RGBA32_F_COMPOSE( r, g, b, 1.0 ); + set_cairo_surface_ci(out, ci_fp); + guint32 color = SP_RGBA32_F_COMPOSE(r, g, b, 1.0); int device_scale = slot.get_device_scale(); @@ -181,24 +187,23 @@ void FilterDiffuseLighting::render_cairo(FilterSlot &slot) double scale = surfaceScale * trans.descrim() * device_scale; switch (light_type) { - case DISTANT_LIGHT: - ink_cairo_surface_synthesize(out, - DiffuseDistantLight(input, light.distant, color, scale, diffuseConstant)); - break; - case POINT_LIGHT: - ink_cairo_surface_synthesize(out, - DiffusePointLight(input, light.point, color, trans, scale, diffuseConstant, x0, y0, device_scale)); - break; - case SPOT_LIGHT: - ink_cairo_surface_synthesize(out, - DiffuseSpotLight(input, light.spot, color, trans, scale, diffuseConstant, x0, y0, device_scale)); - break; - default: { - cairo_t *ct = cairo_create(out); - cairo_set_source_rgba(ct, 0,0,0,1); - cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); - cairo_paint(ct); - cairo_destroy(ct); + case DISTANT_LIGHT: + ink_cairo_surface_synthesize(out, DiffuseDistantLight(input, light.distant, color, scale, diffuseConstant)); + break; + case POINT_LIGHT: + ink_cairo_surface_synthesize( + out, DiffusePointLight(input, light.point, color, trans, scale, diffuseConstant, x0, y0, device_scale)); + break; + case SPOT_LIGHT: + ink_cairo_surface_synthesize( + out, DiffuseSpotLight(input, light.spot, color, trans, scale, diffuseConstant, x0, y0, device_scale)); + break; + default: { + cairo_t *ct = cairo_create(out); + cairo_set_source_rgba(ct, 0, 0, 0, 1); + cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(ct); + cairo_destroy(ct); } break; } @@ -206,7 +211,8 @@ void FilterDiffuseLighting::render_cairo(FilterSlot &slot) cairo_surface_destroy(out); } -void FilterDiffuseLighting::set_icc(SVGICCColor *icc_color) { +void FilterDiffuseLighting::set_icc(SVGICCColor *icc_color) +{ icc = icc_color; } diff --git a/src/display/nr-filter-diffuselighting.h b/src/display/nr-filter-diffuselighting.h index 5bf777b795fa100a363d4d3a817241c0440c335d..9bd2b712e5b58be11a404af0d6d2011eca4df863 100644 --- a/src/display/nr-filter-diffuselighting.h +++ b/src/display/nr-filter-diffuselighting.h @@ -14,10 +14,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "display/nr-light-types.h" #include "display/nr-filter-primitive.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" +#include "display/nr-light-types.h" class SPFeDistantLight; class SPFePointLight; @@ -28,7 +28,8 @@ typedef unsigned int guint32; namespace Inkscape { namespace Filters { -class FilterDiffuseLighting : public FilterPrimitive { +class FilterDiffuseLighting : public FilterPrimitive +{ public: FilterDiffuseLighting(); static FilterPrimitive *create(); @@ -38,7 +39,8 @@ public: void area_enlarge(Geom::IntRect &area, Geom::Affine const &trans) override; double complexity(Geom::Affine const &ctm) override; - union { + union + { SPFeDistantLight *distant; SPFePointLight *point; SPFeSpotLight *spot; diff --git a/src/display/nr-filter-displacement-map.cpp b/src/display/nr-filter-displacement-map.cpp index 9d83e54175767f4fa8dfe3c56a55fbef72417d04..7012067f92b0386d35ae7952183f88e1ae08457f 100644 --- a/src/display/nr-filter-displacement-map.cpp +++ b/src/display/nr-filter-displacement-map.cpp @@ -10,59 +10,61 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/nr-filter-displacement-map.h" + #include "display/cairo-templates.h" #include "display/cairo-utils.h" -#include "display/nr-filter-displacement-map.h" #include "display/nr-filter-types.h" #include "display/nr-filter-units.h" namespace Inkscape { namespace Filters { -FilterDisplacementMap::FilterDisplacementMap() -= default; +FilterDisplacementMap::FilterDisplacementMap() = default; -FilterPrimitive * FilterDisplacementMap::create() { +FilterPrimitive *FilterDisplacementMap::create() +{ return new FilterDisplacementMap(); } -FilterDisplacementMap::~FilterDisplacementMap() -= default; +FilterDisplacementMap::~FilterDisplacementMap() = default; -struct Displace { - Displace(cairo_surface_t *texture, cairo_surface_t *map, - unsigned xch, unsigned ych, double scalex, double scaley) +struct Displace +{ + Displace(cairo_surface_t *texture, cairo_surface_t *map, unsigned xch, unsigned ych, double scalex, double scaley) : _texture(texture) , _map(map) , _xch(xch) , _ych(ych) - , _scalex(scalex/255.0) - , _scaley(scaley/255.0) + , _scalex(scalex / 255.0) + , _scaley(scaley / 255.0) {} - guint32 operator()(int x, int y) { + guint32 operator()(int x, int y) + { guint32 mappx = _map.pixelAt(x, y); guint32 a = (mappx & 0xff000000) >> 24; guint32 xpx = 0, ypx = 0; double xtex = x, ytex = y; - + guint32 xshift = _xch * 8, yshift = _ych * 8; xpx = (mappx & (0xff << xshift)) >> xshift; ypx = (mappx & (0xff << yshift)) >> yshift; if (a) { - if (_xch != 3) xpx = unpremul_alpha(xpx, a); - if (_ych != 3) ypx = unpremul_alpha(ypx, a); + if (_xch != 3) + xpx = unpremul_alpha(xpx, a); + if (_ych != 3) + ypx = unpremul_alpha(ypx, a); } xtex += _scalex * (xpx - 127.5); ytex += _scaley * (ypx - 127.5); - if (xtex >= 0 && xtex < (_texture._w - 1) && - ytex >= 0 && ytex < (_texture._h - 1)) - { + if (xtex >= 0 && xtex < (_texture._w - 1) && ytex >= 0 && ytex < (_texture._h - 1)) { return _texture.pixelAt(xtex, ytex); } else { return 0; } } + private: SurfaceSynth _texture; SurfaceSynth _map; @@ -76,16 +78,16 @@ void FilterDisplacementMap::render_cairo(FilterSlot &slot) cairo_surface_t *map = slot.getcairo(_input2); cairo_surface_t *out = ink_cairo_surface_create_identical(texture); // color_interpolation_filters for out same as texture. See spec. - copy_cairo_surface_ci( texture, out ); + copy_cairo_surface_ci(texture, out); // We may need to transform map surface to correct color interpolation space. The map surface // might be used as input to another primitive but it is likely that all the primitives in a given // filter use the same color interpolation space so we don't copy the map before converting. SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; - if( _style ) { + if (_style) { ci_fp = (SPColorInterpolation)_style->color_interpolation_filters.computed; } - set_cairo_surface_ci( map, ci_fp ); + set_cairo_surface_ci(map, ci_fp); Geom::Affine trans = slot.get_units().get_matrix_primitiveunits2pb(); @@ -99,20 +101,26 @@ void FilterDisplacementMap::render_cairo(FilterSlot &slot) cairo_surface_destroy(out); } -void FilterDisplacementMap::set_input(int slot) { +void FilterDisplacementMap::set_input(int slot) +{ _input = slot; } -void FilterDisplacementMap::set_scale(double s) { +void FilterDisplacementMap::set_scale(double s) +{ scale = s; } -void FilterDisplacementMap::set_input(int input, int slot) { - if (input == 0) _input = slot; - if (input == 1) _input2 = slot; +void FilterDisplacementMap::set_input(int input, int slot) +{ + if (input == 0) + _input = slot; + if (input == 1) + _input2 = slot; } -void FilterDisplacementMap::set_channel_selector(int s, FilterDisplacementMapChannelSelector channel) { +void FilterDisplacementMap::set_channel_selector(int s, FilterDisplacementMapChannelSelector channel) +{ if (channel > DISPLACEMENTMAP_CHANNEL_ALPHA || channel < DISPLACEMENTMAP_CHANNEL_RED) { g_warning("Selected an invalid channel value. (%d)", channel); return; @@ -124,32 +132,40 @@ void FilterDisplacementMap::set_channel_selector(int s, FilterDisplacementMapCha // component = (color & (ch*8)) >> (ch*8) unsigned ch = 4; switch (channel) { - case DISPLACEMENTMAP_CHANNEL_ALPHA: - ch = 3; break; - case DISPLACEMENTMAP_CHANNEL_RED: - ch = 2; break; - case DISPLACEMENTMAP_CHANNEL_GREEN: - ch = 1; break; - case DISPLACEMENTMAP_CHANNEL_BLUE: - ch = 0; break; - default: break; + case DISPLACEMENTMAP_CHANNEL_ALPHA: + ch = 3; + break; + case DISPLACEMENTMAP_CHANNEL_RED: + ch = 2; + break; + case DISPLACEMENTMAP_CHANNEL_GREEN: + ch = 1; + break; + case DISPLACEMENTMAP_CHANNEL_BLUE: + ch = 0; + break; + default: + break; } - if (ch == 4) return; + if (ch == 4) + return; - if (s == 0) Xchannel = ch; - if (s == 1) Ychannel = ch; + if (s == 0) + Xchannel = ch; + if (s == 1) + Ychannel = ch; } void FilterDisplacementMap::area_enlarge(Geom::IntRect &area, Geom::Affine const &trans) { - //I assume scale is in user coordinates (?!?) - //FIXME: trans should be multiplied by some primitiveunits2user, shouldn't it? - - double scalex = scale/2.*(std::fabs(trans[0])+std::fabs(trans[1])); - double scaley = scale/2.*(std::fabs(trans[2])+std::fabs(trans[3])); - - //FIXME: no +2 should be there!... (noticeable only for big scales at big zoom factor) - area.expandBy(scalex+2, scaley+2); + // I assume scale is in user coordinates (?!?) + // FIXME: trans should be multiplied by some primitiveunits2user, shouldn't it? + + double scalex = scale / 2. * (std::fabs(trans[0]) + std::fabs(trans[1])); + double scaley = scale / 2. * (std::fabs(trans[2]) + std::fabs(trans[3])); + + // FIXME: no +2 should be there!... (noticeable only for big scales at big zoom factor) + area.expandBy(scalex + 2, scaley + 2); } double FilterDisplacementMap::complexity(Geom::Affine const &) diff --git a/src/display/nr-filter-displacement-map.h b/src/display/nr-filter-displacement-map.h index 32afcfb7641f52aad5011a4b19eb9b8f11003900..566e885d0a498e3fbdcaeeacd6b880453f535d1d 100644 --- a/src/display/nr-filter-displacement-map.h +++ b/src/display/nr-filter-displacement-map.h @@ -13,15 +13,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "object/filters/displacementmap.h" #include "display/nr-filter-primitive.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" +#include "object/filters/displacementmap.h" namespace Inkscape { namespace Filters { -class FilterDisplacementMap : public FilterPrimitive { +class FilterDisplacementMap : public FilterPrimitive +{ public: FilterDisplacementMap(); static FilterPrimitive *create(); diff --git a/src/display/nr-filter-flood.cpp b/src/display/nr-filter-flood.cpp index 05c32939fa58a18c726c1c8dbb0287d32e6dc7a7..9c367ee494d20f95b2e06844055bd25dbe7c6a8c 100644 --- a/src/display/nr-filter-flood.cpp +++ b/src/display/nr-filter-flood.cpp @@ -12,28 +12,27 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif +#include "color.h" #include "display/cairo-utils.h" #include "display/nr-filter-flood.h" #include "display/nr-filter-slot.h" -#include "svg/svg-icc-color.h" #include "svg/svg-color.h" -#include "color.h" +#include "svg/svg-icc-color.h" namespace Inkscape { namespace Filters { -FilterFlood::FilterFlood() -= default; +FilterFlood::FilterFlood() = default; -FilterPrimitive * FilterFlood::create() { +FilterPrimitive *FilterFlood::create() +{ return new FilterFlood(); } -FilterFlood::~FilterFlood() -= default; +FilterFlood::~FilterFlood() = default; void FilterFlood::render_cairo(FilterSlot &slot) { @@ -57,23 +56,23 @@ void FilterFlood::render_cairo(FilterSlot &slot) cairo_surface_t *out = ink_cairo_surface_create_same_size(input, CAIRO_CONTENT_COLOR_ALPHA); - SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; - if( _style ) { + SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; + if (_style) { ci_fp = (SPColorInterpolation)_style->color_interpolation_filters.computed; // Flood color is always defined in terms of sRGB, preconvert to linearRGB // if color_interpolation_filters set to linearRGB (for efficiency assuming // next filter primitive has same value of cif). - if( ci_fp == SP_CSS_COLOR_INTERPOLATION_LINEARRGB ) { - r = srgb_to_linear( r ); - g = srgb_to_linear( g ); - b = srgb_to_linear( b ); + if (ci_fp == SP_CSS_COLOR_INTERPOLATION_LINEARRGB) { + r = srgb_to_linear(r); + g = srgb_to_linear(g); + b = srgb_to_linear(b); } } - set_cairo_surface_ci(out, ci_fp ); + set_cairo_surface_ci(out, ci_fp); // Get filter primitive area in user units - Geom::Rect fp = filter_primitive_area( slot.get_units() ); + Geom::Rect fp = filter_primitive_area(slot.get_units()); // Convert to Cairo units Geom::Rect fp_cairo = fp * slot.get_units().get_matrix_user2pb(); @@ -82,20 +81,21 @@ void FilterFlood::render_cairo(FilterSlot &slot) Geom::Rect sa = slot.get_slot_area(); // Get overlap - Geom::OptRect optoverlap = intersect( fp_cairo, sa ); - if( optoverlap ) { - + Geom::OptRect optoverlap = intersect(fp_cairo, sa); + if (optoverlap) { Geom::Rect overlap = *optoverlap; double dx = fp_cairo.min()[Geom::X] - sa.min()[Geom::X]; double dy = fp_cairo.min()[Geom::Y] - sa.min()[Geom::Y]; - if( dx < 0.0 ) dx = 0.0; - if( dy < 0.0 ) dy = 0.0; + if (dx < 0.0) + dx = 0.0; + if (dy < 0.0) + dy = 0.0; cairo_t *ct = cairo_create(out); cairo_set_source_rgba(ct, r, g, b, a); cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); - cairo_rectangle(ct, dx, dy, overlap.width(), overlap.height() ); + cairo_rectangle(ct, dx, dy, overlap.width(), overlap.height()); cairo_fill(ct); cairo_destroy(ct); } @@ -110,15 +110,18 @@ bool FilterFlood::can_handle_affine(Geom::Affine const &) return true; } -void FilterFlood::set_color(guint32 c) { +void FilterFlood::set_color(guint32 c) +{ color = c; } -void FilterFlood::set_opacity(double o) { +void FilterFlood::set_opacity(double o) +{ opacity = o; } -void FilterFlood::set_icc(SVGICCColor *icc_color) { +void FilterFlood::set_icc(SVGICCColor *icc_color) +{ icc = icc_color; } double FilterFlood::complexity(Geom::Affine const &) diff --git a/src/display/nr-filter-flood.h b/src/display/nr-filter-flood.h index c2f51fa21031ef94a58e8df2af4751d4b3b30184..4f81727a40e5ba8e8357f6b65c1847d81922f0f0 100644 --- a/src/display/nr-filter-flood.h +++ b/src/display/nr-filter-flood.h @@ -21,7 +21,8 @@ typedef unsigned int guint32; namespace Inkscape { namespace Filters { -class FilterFlood : public FilterPrimitive { +class FilterFlood : public FilterPrimitive +{ public: FilterFlood(); static FilterPrimitive *create(); @@ -31,7 +32,7 @@ public: bool can_handle_affine(Geom::Affine const &) override; double complexity(Geom::Affine const &ctm) override; bool uses_background() override { return false; } - + virtual void set_opacity(double o); virtual void set_color(guint32 c); virtual void set_icc(SVGICCColor *icc_color); diff --git a/src/display/nr-filter-gaussian.cpp b/src/display/nr-filter-gaussian.cpp index f145ba56cb1cff9fc1d88cd48e9af2c3091d613b..fc8f29758c64b2f5af58b7c7806ac22adfeec790 100644 --- a/src/display/nr-filter-gaussian.cpp +++ b/src/display/nr-filter-gaussian.cpp @@ -13,7 +13,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include @@ -24,17 +24,18 @@ #include #if HAVE_OPENMP #include -#endif //HAVE_OPENMP +#endif // HAVE_OPENMP + +#include <2geom/affine.h> #include "display/cairo-utils.h" -#include "display/nr-filter-primitive.h" #include "display/nr-filter-gaussian.h" +#include "display/nr-filter-primitive.h" +#include "display/nr-filter-slot.h" #include "display/nr-filter-types.h" #include "display/nr-filter-units.h" -#include "display/nr-filter-slot.h" -#include <2geom/affine.h> -#include "util/fixed_point.h" #include "preferences.h" +#include "util/fixed_point.h" #ifndef INK_UNUSED #define INK_UNUSED(x) ((void)(x)) @@ -57,29 +58,41 @@ // filters are used). static size_t const N = 3; -template -inline void copy_n(InIt beg_in, Size N, OutIt beg_out) { - std::copy(beg_in, beg_in+N, beg_out); +template +inline void copy_n(InIt beg_in, Size N, OutIt beg_out) +{ + std::copy(beg_in, beg_in + N, beg_out); } -// Type used for IIR filter coefficients (can be 10.21 signed fixed point, see Anisotropic Gaussian Filtering Using Fixed Point Arithmetic, Christoph H. Lampert & Oliver Wirjadi, 2006) +// Type used for IIR filter coefficients (can be 10.21 signed fixed point, see Anisotropic Gaussian Filtering Using +// Fixed Point Arithmetic, Christoph H. Lampert & Oliver Wirjadi, 2006) typedef double IIRValue; -// Type used for FIR filter coefficients (can be 16.16 unsigned fixed point, should have 8 or more bits in the fractional part, the integer part should be capable of storing approximately 20*255) -typedef Inkscape::Util::FixedPoint FIRValue; +// Type used for FIR filter coefficients (can be 16.16 unsigned fixed point, should have 8 or more bits in the +// fractional part, the integer part should be capable of storing approximately 20*255) +typedef Inkscape::Util::FixedPoint FIRValue; -template static inline T sqr(T const& v) { return v*v; } +template +static inline T sqr(T const &v) +{ + return v * v; +} -template static inline T clip(T const& v, T const& a, T const& b) { - if ( v < a ) return a; - if ( v > b ) return b; +template +static inline T clip(T const &v, T const &a, T const &b) +{ + if (v < a) + return a; + if (v > b) + return b; return v; } -template -static inline Tt round_cast(Ts v) { +template +static inline Tt round_cast(Ts v) +{ static Ts const rndoffset(.5); - return static_cast(v+rndoffset); + return static_cast(v + rndoffset); } /* template<> @@ -100,24 +113,30 @@ inline unsigned char round_cast(double v) { #endif }*/ -template -static inline Tt clip_round_cast(Ts const v) { +template +static inline Tt clip_round_cast(Ts const v) +{ Ts const minval = std::numeric_limits::min(); Ts const maxval = std::numeric_limits::max(); Tt const minval_rounded = std::numeric_limits::min(); Tt const maxval_rounded = std::numeric_limits::max(); - if ( v < minval ) return minval_rounded; - if ( v > maxval ) return maxval_rounded; + if (v < minval) + return minval_rounded; + if (v > maxval) + return maxval_rounded; return round_cast(v); } -template -static inline Tt clip_round_cast_varmax(Ts const v, Tt const maxval_rounded) { +template +static inline Tt clip_round_cast_varmax(Ts const v, Tt const maxval_rounded) +{ Ts const minval = std::numeric_limits::min(); Tt const maxval = maxval_rounded; Tt const minval_rounded = std::numeric_limits::min(); - if ( v < minval ) return minval_rounded; - if ( v > maxval ) return maxval_rounded; + if (v < minval) + return minval_rounded; + if (v > maxval) + return maxval_rounded; return round_cast(v); } @@ -139,39 +158,40 @@ FilterGaussian::~FilterGaussian() // Nothing to do here } -static int -_effect_area_scr(double const deviation) +static int _effect_area_scr(double const deviation) { return (int)std::ceil(std::fabs(deviation) * 3.0); } -static void -_make_kernel(FIRValue *const kernel, double const deviation) +static void _make_kernel(FIRValue *const kernel, double const deviation) { int const scr_len = _effect_area_scr(deviation); g_assert(scr_len >= 0); double const d_sq = sqr(deviation) * 2; - double k[scr_len+1]; // This is only called for small kernel sizes (above approximately 10 coefficients the IIR filter is used) + double k[scr_len + 1]; // This is only called for small kernel sizes (above approximately 10 coefficients the IIR + // filter is used) // Compute kernel and sum of coefficients // Note that actually only half the kernel is computed, as it is symmetric double sum = 0; - for ( int i = scr_len; i >= 0 ; i-- ) { + for (int i = scr_len; i >= 0; i--) { k[i] = std::exp(-sqr(i) / d_sq); - if ( i > 0 ) sum += k[i]; + if (i > 0) + sum += k[i]; } - // the sum of the complete kernel is twice as large (plus the center element which we skipped above to prevent counting it twice) - sum = 2*sum + k[0]; + // the sum of the complete kernel is twice as large (plus the center element which we skipped above to prevent + // counting it twice) + sum = 2 * sum + k[0]; // Normalize kernel (making sure the sum is exactly 1) double ksum = 0; FIRValue kernelsum = 0; - for ( int i = scr_len; i >= 1 ; i-- ) { - ksum += k[i]/sum; - kernel[i] = ksum-static_cast(kernelsum); + for (int i = scr_len; i >= 1; i--) { + ksum += k[i] / sum; + kernel[i] = ksum - static_cast(kernelsum); kernelsum += kernel[i]; } - kernel[0] = FIRValue(1)-2*kernelsum; + kernel[0] = FIRValue(1) - 2 * kernelsum; } // Return value (v) should satisfy: @@ -181,8 +201,7 @@ _make_kernel(FIRValue *const kernel, double const deviation) // 8<=32-2*v // 2*v<=24 // v<=12 -static int -_effect_subsample_step_log2(double const deviation, int const quality) +static int _effect_subsample_step_log2(double const deviation, int const quality) { // To make sure FIR will always be used (unless the kernel is VERY big): // deviation/step <= 3 @@ -196,19 +215,19 @@ _effect_subsample_step_log2(double const deviation, int const quality) // 2 == log(x*8/3)) // 2^2 == x*2^3/3 // x == 3/2 - stepsize_l2 = clip(static_cast(log(deviation*(3./2.))/log(2.)), 0, 12); + stepsize_l2 = clip(static_cast(log(deviation * (3. / 2.)) / log(2.)), 0, 12); break; case BLUR_QUALITY_WORSE: // 2 == log(x*16/3)) // 2^2 == x*2^4/3 // x == 3/2^2 - stepsize_l2 = clip(static_cast(log(deviation*(3./4.))/log(2.)), 0, 12); + stepsize_l2 = clip(static_cast(log(deviation * (3. / 4.)) / log(2.)), 0, 12); break; case BLUR_QUALITY_BETTER: // 2 == log(x*32/3)) // 2 == x*2^5/3 // x == 3/2^4 - stepsize_l2 = clip(static_cast(log(deviation*(3./16.))/log(2.)), 0, 12); + stepsize_l2 = clip(static_cast(log(deviation * (3. / 16.)) / log(2.)), 0, 12); break; case BLUR_QUALITY_BEST: stepsize_l2 = 0; // no subsampling at all @@ -218,148 +237,164 @@ _effect_subsample_step_log2(double const deviation, int const quality) // 2 == log(x*16/3)) // 2 == x*2^4/3 // x == 3/2^3 - stepsize_l2 = clip(static_cast(log(deviation*(3./8.))/log(2.)), 0, 12); + stepsize_l2 = clip(static_cast(log(deviation * (3. / 8.)) / log(2.)), 0, 12); break; } return stepsize_l2; } -static void calcFilter(double const sigma, double b[N]) { - assert(N==3); - std::complex const d1_org(1.40098, 1.00236); +static void calcFilter(double const sigma, double b[N]) +{ + assert(N == 3); + std::complex const d1_org(1.40098, 1.00236); double const d3_org = 1.85132; double qbeg = 1; // Don't go lower than sigma==2 (we'd probably want a normal convolution in that case anyway) - double qend = 2*sigma; + double qend = 2 * sigma; double const sigmasqr = sqr(sigma); do { // Binary search for right q (a linear interpolation scheme is suggested, but this should work fine as well) - double const q = (qbeg+qend)/2; + double const q = (qbeg + qend) / 2; // Compute scaled filter coefficients - std::complex const d1 = pow(d1_org, 1.0/q); - double const d3 = pow(d3_org, 1.0/q); + std::complex const d1 = pow(d1_org, 1.0 / q); + double const d3 = pow(d3_org, 1.0 / q); // Compute actual sigma^2 - double const ssqr = 2*(2*(d1/sqr(d1-1.)).real()+d3/sqr(d3-1.)); - if ( ssqr < sigmasqr ) { + double const ssqr = 2 * (2 * (d1 / sqr(d1 - 1.)).real() + d3 / sqr(d3 - 1.)); + if (ssqr < sigmasqr) { qbeg = q; } else { qend = q; } - } while(qend-qbeg>(sigma/(1<<30))); + } while (qend - qbeg > (sigma / (1 << 30))); // Compute filter coefficients - double const q = (qbeg+qend)/2; - std::complex const d1 = pow(d1_org, 1.0/q); - double const d3 = pow(d3_org, 1.0/q); + double const q = (qbeg + qend) / 2; + std::complex const d1 = pow(d1_org, 1.0 / q); + double const d3 = pow(d3_org, 1.0 / q); double const absd1sqr = std::norm(d1); // d1*d2 = d1*conj(d1) = |d1|^2 = std::norm(d1) - double const re2d1 = 2*d1.real(); // d1+d2 = d1+conj(d1) = 2*real(d1) - double const bscale = 1.0/(absd1sqr*d3); + double const re2d1 = 2 * d1.real(); // d1+d2 = d1+conj(d1) = 2*real(d1) + double const bscale = 1.0 / (absd1sqr * d3); b[2] = -bscale; - b[1] = bscale*(d3+re2d1); - b[0] = -bscale*(absd1sqr+d3*re2d1); + b[1] = bscale * (d3 + re2d1); + b[0] = -bscale * (absd1sqr + d3 * re2d1); } -static void calcTriggsSdikaM(double const b[N], double M[N*N]) { - assert(N==3); - double a1=b[0], a2=b[1], a3=b[2]; - double const Mscale = 1.0/((1+a1-a2+a3)*(1-a1-a2-a3)*(1+a2+(a1-a3)*a3)); - M[0] = 1-a2-a1*a3-sqr(a3); - M[1] = (a1+a3)*(a2+a1*a3); - M[2] = a3*(a1+a2*a3); - M[3] = a1+a2*a3; - M[4] = (1-a2)*(a2+a1*a3); - M[5] = a3*(1-a2-a1*a3-sqr(a3)); - M[6] = a1*(a1+a3)+a2*(1-a2); - M[7] = a1*(a2-sqr(a3))+a3*(1+a2*(a2-1)-sqr(a3)); - M[8] = a3*(a1+a2*a3); - for(unsigned int i=0; i<9; i++) M[i] *= Mscale; +static void calcTriggsSdikaM(double const b[N], double M[N * N]) +{ + assert(N == 3); + double a1 = b[0], a2 = b[1], a3 = b[2]; + double const Mscale = 1.0 / ((1 + a1 - a2 + a3) * (1 - a1 - a2 - a3) * (1 + a2 + (a1 - a3) * a3)); + M[0] = 1 - a2 - a1 * a3 - sqr(a3); + M[1] = (a1 + a3) * (a2 + a1 * a3); + M[2] = a3 * (a1 + a2 * a3); + M[3] = a1 + a2 * a3; + M[4] = (1 - a2) * (a2 + a1 * a3); + M[5] = a3 * (1 - a2 - a1 * a3 - sqr(a3)); + M[6] = a1 * (a1 + a3) + a2 * (1 - a2); + M[7] = a1 * (a2 - sqr(a3)) + a3 * (1 + a2 * (a2 - 1) - sqr(a3)); + M[8] = a3 * (a1 + a2 * a3); + for (unsigned int i = 0; i < 9; i++) + M[i] *= Mscale; } -template -static void calcTriggsSdikaInitialization(double const M[N*N], IIRValue const uold[N][SIZE], IIRValue const uplus[SIZE], IIRValue const vplus[SIZE], IIRValue const alpha, IIRValue vold[N][SIZE]) { - for(unsigned int c=0; c +static void calcTriggsSdikaInitialization(double const M[N * N], IIRValue const uold[N][SIZE], + IIRValue const uplus[SIZE], IIRValue const vplus[SIZE], IIRValue const alpha, + IIRValue vold[N][SIZE]) +{ + for (unsigned int c = 0; c < SIZE; c++) { double uminp[N]; - for(unsigned int i=0; i -static void -filter2D_IIR(PT *const dest, int const dstr1, int const dstr2, - PT const *const src, int const sstr1, int const sstr2, - int const n1, int const n2, IIRValue const b[N+1], double const M[N*N], - IIRValue *const tmpdata[], int const num_threads) +template +static void filter2D_IIR(PT *const dest, int const dstr1, int const dstr2, PT const *const src, int const sstr1, + int const sstr2, int const n1, int const n2, IIRValue const b[N + 1], double const M[N * N], + IIRValue *const tmpdata[], int const num_threads) { #if G_BYTE_ORDER == G_LITTLE_ENDIAN - static unsigned int const alpha_PC = PC-1; - #define PREMUL_ALPHA_LOOP for(unsigned int c=0; c0; i--) copy_n(u[i-1], PC, u[i]); + IIRValue u[N + 1][PC]; + for (unsigned int i = 0; i < N; i++) + copy_n(imin, PC, u[i]); + for (int c1 = 0; c1 < n1; c1++) { + for (unsigned int i = N; i > 0; i--) + copy_n(u[i - 1], PC, u[i]); copy_n(srcimg, PC, u[0]); srcimg += sstr1; - for(unsigned int c=0; c(M, u, iplus, iplus, b[0], v); dstimg -= dstr1; - if ( PREMULTIPLIED_ALPHA ) { + if (PREMULTIPLIED_ALPHA) { dstimg[alpha_PC] = clip_round_cast(v[0][alpha_PC]); PREMUL_ALPHA_LOOP dstimg[c] = clip_round_cast_varmax(v[0][c], dstimg[alpha_PC]); } else { - for(unsigned int c=0; c(v[0][c]); + for (unsigned int c = 0; c < PC; c++) + dstimg[c] = clip_round_cast(v[0][c]); } - int c1=n1-1; - while(c1-->0) { - for(unsigned int i=N; i>0; i--) copy_n(v[i-1], PC, v[i]); - copy_n(tmpdata[tid]+c1*PC, PC, v[0]); - for(unsigned int c=0; c 0) { + for (unsigned int i = N; i > 0; i--) + copy_n(v[i - 1], PC, v[i]); + copy_n(tmpdata[tid] + c1 * PC, PC, v[0]); + for (unsigned int c = 0; c < PC; c++) + v[0][c] *= b[0]; + for (unsigned int i = 1; i < N + 1; i++) { + for (unsigned int c = 0; c < PC; c++) + v[0][c] += v[i][c] * b[i]; } dstimg -= dstr1; - if ( PREMULTIPLIED_ALPHA ) { + if (PREMULTIPLIED_ALPHA) { dstimg[alpha_PC] = clip_round_cast(v[0][alpha_PC]); PREMUL_ALPHA_LOOP dstimg[c] = clip_round_cast_varmax(v[0][c], dstimg[alpha_PC]); } else { - for(unsigned int c=0; c(v[0][c]); + for (unsigned int c = 0; c < PC; c++) + dstimg[c] = clip_round_cast(v[0][c]); } } } @@ -368,21 +403,19 @@ INK_UNUSED(num_threads); // to suppress unused argument compiler warning // Filters over 1st dimension // Assumes kernel is symmetric // Kernel should have scr_len+1 elements -template -static void -filter2D_FIR(PT *const dst, int const dstr1, int const dstr2, - PT const *const src, int const sstr1, int const sstr2, - int const n1, int const n2, FIRValue const *const kernel, int const scr_len, int const num_threads) +template +static void filter2D_FIR(PT *const dst, int const dstr1, int const dstr2, PT const *const src, int const sstr1, + int const sstr2, int const n1, int const n2, FIRValue const *const kernel, int const scr_len, + int const num_threads) { // Past pixels seen (to enable in-place operation) - PT history[scr_len+1][PC]; + PT history[scr_len + 1][PC]; -INK_UNUSED(num_threads); // suppresses unused argument compiler warning + INK_UNUSED(num_threads); // suppresses unused argument compiler warning #if HAVE_OPENMP #pragma omp parallel for num_threads(num_threads) private(history) #endif // HAVE_OPENMP - for ( int c2 = 0 ; c2 < n2 ; c2++ ) { - + for (int c2 = 0; c2 < n2; c2++) { // corresponding line in the source buffer int const src_line = c2 * sstr2; @@ -392,34 +425,37 @@ INK_UNUSED(num_threads); // suppresses unused argument compiler warning int skipbuf[4] = {INT_MIN, INT_MIN, INT_MIN, INT_MIN}; // history initialization - PT imin[PC]; copy_n(src + src_line, PC, imin); - for(int i=0; i0; i--) copy_n(history[i-1], PC, history[i]); + for (int i = scr_len; i > 0; i--) + copy_n(history[i - 1], PC, history[i]); copy_n(src + src_disp, PC, history[0]); // for all bytes of the pixel - for ( unsigned int byte = 0 ; byte < PC ; byte++) { - - if(skipbuf[byte] > c1) continue; + for (unsigned int byte = 0; byte < PC; byte++) { + if (skipbuf[byte] > c1) + continue; FIRValue sum = 0; int last_in = -1; int different_count = 0; // go over our point's neighbours in the history - for ( int i = 0 ; i <= scr_len ; i++ ) { + for (int i = 0; i <= scr_len; i++) { // value at the pixel PT in_byte = history[i][byte]; // is it the same as last one we saw? - if(in_byte != last_in) different_count++; + if (in_byte != last_in) + different_count++; last_in = in_byte; // sum pixels weighted by the kernel @@ -428,7 +464,7 @@ INK_UNUSED(num_threads); // suppresses unused argument compiler warning // go over our point's neighborhood on x axis in the in buffer int nb_src_disp = src_disp + byte; - for ( int i = 1 ; i <= scr_len ; i++ ) { + for (int i = 1; i <= scr_len; i++) { // the pixel we're looking at int c1_in = c1 + i; if (c1_in >= n1) { @@ -441,7 +477,8 @@ INK_UNUSED(num_threads); // suppresses unused argument compiler warning PT in_byte = src[nb_src_disp]; // is it the same as last one we saw? - if(in_byte != last_in) different_count++; + if (in_byte != last_in) + different_count++; last_in = in_byte; // sum pixels weighted by the kernel @@ -454,11 +491,13 @@ INK_UNUSED(num_threads); // suppresses unused argument compiler warning // optimization: if there was no variation within this point's neighborhood, // skip ahead while we keep seeing the same last_in byte: // blurring flat color would not change it anyway - if (different_count <= 1) { // note that different_count is at least 1, because last_in is initialized to -1 + if (different_count <= 1) { // note that different_count is at least 1, because last_in is initialized + // to -1 int pos = c1 + 1; - int nb_src_disp = src_disp + (1+scr_len)*sstr1 + byte; // src_line + (pos+scr_len) * sstr1 + byte - int nb_dst_disp = dst_disp + (1) *dstr1 + byte; // dst_line + (pos) * sstr1 + byte - while(pos + scr_len < n1 && src[nb_src_disp] == last_in) { + int nb_src_disp = + src_disp + (1 + scr_len) * sstr1 + byte; // src_line + (pos+scr_len) * sstr1 + byte + int nb_dst_disp = dst_disp + (1) * dstr1 + byte; // dst_line + (pos) * sstr1 + byte + while (pos + scr_len < n1 && src[nb_src_disp] == last_in) { dst[nb_dst_disp] = last_in; pos++; nb_src_disp += sstr1; @@ -471,22 +510,22 @@ INK_UNUSED(num_threads); // suppresses unused argument compiler warning } } -static void -gaussian_pass_IIR(Geom::Dim2 d, double deviation, cairo_surface_t *src, cairo_surface_t *dest, - IIRValue **tmpdata, int num_threads) +static void gaussian_pass_IIR(Geom::Dim2 d, double deviation, cairo_surface_t *src, cairo_surface_t *dest, + IIRValue **tmpdata, int num_threads) { // Filter variables - IIRValue b[N+1]; // scaling coefficient + filter coefficients (can be 10.21 fixed point) - double bf[N]; // computed filter coefficients - double M[N*N]; // matrix used for initialization procedure (has to be double) + IIRValue b[N + 1]; // scaling coefficient + filter coefficients (can be 10.21 fixed point) + double bf[N]; // computed filter coefficients + double M[N * N]; // matrix used for initialization procedure (has to be double) // Compute filter calcFilter(deviation, bf); - for(double & i : bf) i = -i; + for (double &i : bf) + i = -i; b[0] = 1; // b[0] == alpha (scaling coefficient) - for(size_t i=0; i( - cairo_image_surface_get_data(dest), d == Geom::X ? 1 : stride, d == Geom::X ? stride : 1, - cairo_image_surface_get_data(src), d == Geom::X ? 1 : stride, d == Geom::X ? stride : 1, - w, h, b, M, tmpdata, num_threads); - break; - case CAIRO_FORMAT_ARGB32: ///< Premultiplied 8 bit RGBA - filter2D_IIR( - cairo_image_surface_get_data(dest), d == Geom::X ? 4 : stride, d == Geom::X ? stride : 4, - cairo_image_surface_get_data(src), d == Geom::X ? 4 : stride, d == Geom::X ? stride : 4, - w, h, b, M, tmpdata, num_threads); - break; - default: - g_warning("gaussian_pass_IIR: unsupported image format"); + case CAIRO_FORMAT_A8: ///< Grayscale + filter2D_IIR(cairo_image_surface_get_data(dest), d == Geom::X ? 1 : stride, + d == Geom::X ? stride : 1, cairo_image_surface_get_data(src), + d == Geom::X ? 1 : stride, d == Geom::X ? stride : 1, w, h, b, M, + tmpdata, num_threads); + break; + case CAIRO_FORMAT_ARGB32: ///< Premultiplied 8 bit RGBA + filter2D_IIR(cairo_image_surface_get_data(dest), d == Geom::X ? 4 : stride, + d == Geom::X ? stride : 4, cairo_image_surface_get_data(src), + d == Geom::X ? 4 : stride, d == Geom::X ? stride : 4, w, h, b, M, + tmpdata, num_threads); + break; + default: + g_warning("gaussian_pass_IIR: unsupported image format"); }; } -static void -gaussian_pass_FIR(Geom::Dim2 d, double deviation, cairo_surface_t *src, cairo_surface_t *dest, - int num_threads) +static void gaussian_pass_FIR(Geom::Dim2 d, double deviation, cairo_surface_t *src, cairo_surface_t *dest, + int num_threads) { int scr_len = _effect_area_scr(deviation); // Filter kernel for x direction @@ -528,40 +567,42 @@ gaussian_pass_FIR(Geom::Dim2 d, double deviation, cairo_surface_t *src, cairo_su int stride = cairo_image_surface_get_stride(src); int w = cairo_image_surface_get_width(src); int h = cairo_image_surface_get_height(src); - if (d != Geom::X) std::swap(w, h); + if (d != Geom::X) + std::swap(w, h); // Filter (x) switch (cairo_image_surface_get_format(src)) { - case CAIRO_FORMAT_A8: ///< Grayscale - filter2D_FIR( - cairo_image_surface_get_data(dest), d == Geom::X ? 1 : stride, d == Geom::X ? stride : 1, - cairo_image_surface_get_data(src), d == Geom::X ? 1 : stride, d == Geom::X ? stride : 1, - w, h, &kernel[0], scr_len, num_threads); - break; - case CAIRO_FORMAT_ARGB32: ///< Premultiplied 8 bit RGBA - filter2D_FIR( - cairo_image_surface_get_data(dest), d == Geom::X ? 4 : stride, d == Geom::X ? stride : 4, - cairo_image_surface_get_data(src), d == Geom::X ? 4 : stride, d == Geom::X ? stride : 4, - w, h, &kernel[0], scr_len, num_threads); - break; - default: - g_warning("gaussian_pass_FIR: unsupported image format"); + case CAIRO_FORMAT_A8: ///< Grayscale + filter2D_FIR(cairo_image_surface_get_data(dest), d == Geom::X ? 1 : stride, + d == Geom::X ? stride : 1, cairo_image_surface_get_data(src), + d == Geom::X ? 1 : stride, d == Geom::X ? stride : 1, w, h, &kernel[0], + scr_len, num_threads); + break; + case CAIRO_FORMAT_ARGB32: ///< Premultiplied 8 bit RGBA + filter2D_FIR(cairo_image_surface_get_data(dest), d == Geom::X ? 4 : stride, + d == Geom::X ? stride : 4, cairo_image_surface_get_data(src), + d == Geom::X ? 4 : stride, d == Geom::X ? stride : 4, w, h, &kernel[0], + scr_len, num_threads); + break; + default: + g_warning("gaussian_pass_FIR: unsupported image format"); }; } void FilterGaussian::render_cairo(FilterSlot &slot) { cairo_surface_t *in = slot.getcairo(_input); - if (!in) return; + if (!in) + return; // We may need to transform input surface to correct color interpolation space. The input surface // might be used as input to another primitive but it is likely that all the primitives in a given // filter use the same color interpolation space so we don't copy the input before converting. SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; - if( _style ) { + if (_style) { ci_fp = (SPColorInterpolation)_style->color_interpolation_filters.computed; } - set_cairo_surface_ci( in, ci_fp ); + set_cairo_surface_ci(in, ci_fp); // zero deviation = no change in output if (_deviation_x <= 0 && _deviation_y <= 0) { @@ -574,9 +615,9 @@ void FilterGaussian::render_cairo(FilterSlot &slot) // Handle bounding box case. double dx = _deviation_x; double dy = _deviation_y; - if( slot.get_units().get_primitive_units() == SP_FILTER_UNITS_OBJECTBOUNDINGBOX ) { + if (slot.get_units().get_primitive_units() == SP_FILTER_UNITS_OBJECTBOUNDINGBOX) { Geom::OptRect const bbox = slot.get_units().get_item_bbox(); - if( bbox ) { + if (bbox) { dx *= (*bbox).width(); dy *= (*bbox).height(); } @@ -596,10 +637,12 @@ void FilterGaussian::render_cairo(FilterSlot &slot) int bytes_per_pixel = 0; switch (fmt) { case CAIRO_FORMAT_A8: - bytes_per_pixel = 1; break; + bytes_per_pixel = 1; + break; case CAIRO_FORMAT_ARGB32: default: - bytes_per_pixel = 4; break; + bytes_per_pixel = 4; + break; } #if HAVE_OPENMP @@ -613,10 +656,10 @@ void FilterGaussian::render_cairo(FilterSlot &slot) int x_step = 1 << _effect_subsample_step_log2(deviation_x_orig, quality); int y_step = 1 << _effect_subsample_step_log2(deviation_y_orig, quality); bool resampling = x_step > 1 || y_step > 1; - int w_orig = ink_cairo_surface_get_width(in); // Pixels + int w_orig = ink_cairo_surface_get_width(in); // Pixels int h_orig = ink_cairo_surface_get_height(in); - int w_downsampled = resampling ? static_cast(ceil(static_cast(w_orig)/x_step))+1 : w_orig; - int h_downsampled = resampling ? static_cast(ceil(static_cast(h_orig)/y_step))+1 : h_orig; + int w_downsampled = resampling ? static_cast(ceil(static_cast(w_orig) / x_step)) + 1 : w_orig; + int h_downsampled = resampling ? static_cast(ceil(static_cast(h_orig) / y_step)) + 1 : h_orig; double deviation_x = deviation_x_orig / x_step; double deviation_y = deviation_y_orig / y_step; int scr_len_x = _effect_area_scr(deviation_x); @@ -632,11 +675,11 @@ void FilterGaussian::render_cairo(FilterSlot &slot) // Temporary storage for IIR filter // NOTE: This can be eliminated, but it reduces the precision a bit - IIRValue * tmpdata[threads]; - std::fill_n(tmpdata, threads, (IIRValue*)0); - if ( use_IIR_x || use_IIR_y ) { - for(int i = 0; i < threads; ++i) { - tmpdata[i] = new IIRValue[std::max(w_downsampled,h_downsampled)*bytes_per_pixel]; + IIRValue *tmpdata[threads]; + std::fill_n(tmpdata, threads, (IIRValue *)0); + if (use_IIR_x || use_IIR_y) { + for (int i = 0; i < threads; ++i) { + tmpdata[i] = new IIRValue[std::max(w_downsampled, h_downsampled) * bytes_per_pixel]; } } @@ -644,10 +687,10 @@ void FilterGaussian::render_cairo(FilterSlot &slot) if (resampling) { // Divide by device scale as w_downsampled is in pixels while // cairo_surface_create_similar() uses device units. - downsampled = cairo_surface_create_similar(in, cairo_surface_get_content(in), - w_downsampled/device_scale, h_downsampled/device_scale); + downsampled = cairo_surface_create_similar(in, cairo_surface_get_content(in), w_downsampled / device_scale, + h_downsampled / device_scale); cairo_t *ct = cairo_create(downsampled); - cairo_scale(ct, static_cast(w_downsampled)/w_orig, static_cast(h_downsampled)/h_orig); + cairo_scale(ct, static_cast(w_downsampled) / w_orig, static_cast(h_downsampled) / h_orig); cairo_set_source_surface(ct, in, 0, 0); cairo_paint(ct); cairo_destroy(ct); @@ -673,8 +716,8 @@ void FilterGaussian::render_cairo(FilterSlot &slot) } // free the temporary data - if ( use_IIR_x || use_IIR_y ) { - for(int i = 0; i < threads; ++i) { + if (use_IIR_x || use_IIR_y) { + for (int i = 0; i < threads; ++i) { delete[] tmpdata[i]; } } @@ -682,20 +725,20 @@ void FilterGaussian::render_cairo(FilterSlot &slot) cairo_surface_mark_dirty(downsampled); if (resampling) { cairo_surface_t *upsampled = cairo_surface_create_similar(downsampled, cairo_surface_get_content(downsampled), - w_orig/device_scale, h_orig/device_scale); + w_orig / device_scale, h_orig / device_scale); cairo_t *ct = cairo_create(upsampled); - cairo_scale(ct, static_cast(w_orig)/w_downsampled, static_cast(h_orig)/h_downsampled); + cairo_scale(ct, static_cast(w_orig) / w_downsampled, static_cast(h_orig) / h_downsampled); cairo_set_source_surface(ct, downsampled, 0, 0); cairo_paint(ct); cairo_destroy(ct); - set_cairo_surface_ci( upsampled, ci_fp ); + set_cairo_surface_ci(upsampled, ci_fp); slot.set(_output, upsampled); cairo_surface_destroy(upsampled); cairo_surface_destroy(downsampled); } else { - set_cairo_surface_ci( downsampled, ci_fp ); + set_cairo_surface_ci(downsampled, ci_fp); slot.set(_output, downsampled); cairo_surface_destroy(downsampled); @@ -730,14 +773,14 @@ double FilterGaussian::complexity(Geom::Affine const &trans) void FilterGaussian::set_deviation(double deviation) { - if(std::isfinite(deviation) && deviation >= 0) { + if (std::isfinite(deviation) && deviation >= 0) { _deviation_x = _deviation_y = deviation; } } void FilterGaussian::set_deviation(double x, double y) { - if(std::isfinite(x) && x >= 0 && std::isfinite(y) && y >= 0) { + if (std::isfinite(x) && x >= 0 && std::isfinite(y) && y >= 0) { _deviation_x = x; _deviation_y = y; } diff --git a/src/display/nr-filter-gaussian.h b/src/display/nr-filter-gaussian.h index 28ffb00db047231f85d31cd7d27c225bd383c618..1df784417951314de2e5f6b9479898f6e3f9ee36 100644 --- a/src/display/nr-filter-gaussian.h +++ b/src/display/nr-filter-gaussian.h @@ -16,9 +16,11 @@ */ #include <2geom/forward.h> + #include "display/nr-filter-primitive.h" -enum { +enum +{ BLUR_QUALITY_BEST = 2, BLUR_QUALITY_BETTER = 1, BLUR_QUALITY_NORMAL = 0, @@ -29,7 +31,8 @@ enum { namespace Inkscape { namespace Filters { -class FilterGaussian : public FilterPrimitive { +class FilterGaussian : public FilterPrimitive +{ public: FilterGaussian(); static FilterPrimitive *create(); @@ -64,13 +67,9 @@ private: double _deviation_y; }; - } /* namespace Filters */ } /* namespace Inkscape */ - - - #endif /* __NR_FILTER_GAUSSIAN_H__ */ /* Local Variables: diff --git a/src/display/nr-filter-image.cpp b/src/display/nr-filter-image.cpp index bfc2b6bb1f5eaf10604d5b4fed456d0b8b5a44f5..b962fde6bb92dc4c019b591acbcf55fc094d6219 100644 --- a/src/display/nr-filter-image.cpp +++ b/src/display/nr-filter-image.cpp @@ -12,17 +12,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "display/nr-filter-image.h" -#include "document.h" -#include "object/sp-item.h" + +#include + #include "display/cairo-utils.h" #include "display/drawing-context.h" -#include "display/drawing.h" #include "display/drawing-item.h" -#include "display/nr-filter.h" +#include "display/drawing.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" +#include "display/nr-filter.h" +#include "document.h" #include "enums.h" -#include +#include "object/sp-item.h" namespace Inkscape { namespace Filters { @@ -33,9 +35,10 @@ FilterImage::FilterImage() , feImageHref(nullptr) , image(nullptr) , broken_ref(false) -{ } +{} -FilterPrimitive * FilterImage::create() { +FilterPrimitive *FilterImage::create() +{ return new FilterImage(); } @@ -52,17 +55,17 @@ void FilterImage::render_cairo(FilterSlot &slot) if (!feImageHref) return; - //cairo_surface_t *input = slot.getcairo(_input); + // cairo_surface_t *input = slot.getcairo(_input); // Viewport is filter primitive area (in user coordinates). // Note: viewport calculation in non-trivial. Do not rely // on get_matrix_primitiveunits2pb(). - Geom::Rect vp = filter_primitive_area( slot.get_units() ); + Geom::Rect vp = filter_primitive_area(slot.get_units()); slot.set_primitive_area(_output, vp); // Needed for tiling - double feImageX = vp.min()[Geom::X]; - double feImageY = vp.min()[Geom::Y]; - double feImageWidth = vp.width(); + double feImageX = vp.min()[Geom::X]; + double feImageY = vp.min()[Geom::Y]; + double feImageWidth = vp.width(); double feImageHeight = vp.height(); // feImage is suppose to use the same parameters as a normal SVG image. @@ -71,21 +74,24 @@ void FilterImage::render_cairo(FilterSlot &slot) // filter test expect this behavior. If the width and/or height are zero, we use // the width and height of the object bounding box. Geom::Affine m = slot.get_units().get_matrix_user2filterunits().inverse(); - Geom::Point bbox_00 = Geom::Point(0,0) * m; - Geom::Point bbox_w0 = Geom::Point(1,0) * m; - Geom::Point bbox_0h = Geom::Point(0,1) * m; + Geom::Point bbox_00 = Geom::Point(0, 0) * m; + Geom::Point bbox_w0 = Geom::Point(1, 0) * m; + Geom::Point bbox_0h = Geom::Point(0, 1) * m; double bbox_width = Geom::distance(bbox_00, bbox_w0); double bbox_height = Geom::distance(bbox_00, bbox_0h); - if( feImageWidth == 0 ) feImageWidth = bbox_width; - if( feImageHeight == 0 ) feImageHeight = bbox_height; + if (feImageWidth == 0) + feImageWidth = bbox_width; + if (feImageHeight == 0) + feImageHeight = bbox_height; int device_scale = slot.get_device_scale(); // Internal image, like if (from_element) { std::cout << " Internal image" << std::endl; - if (!SVGElem) return; + if (!SVGElem) + return; // TODO: do not recreate the rendering tree every time // TODO: the entire thing is a hack, we should give filter primitives an "update" method @@ -94,7 +100,8 @@ void FilterImage::render_cairo(FilterSlot &slot) Drawing drawing; Geom::OptRect optarea = SVGElem->visualBounds(); - if (!optarea) return; + if (!optarea) + return; unsigned const key = SPItem::display_key_new(1); DrawingItem *ai = SVGElem->invoke_show(drawing, key, SP_ITEM_SHOW_DISPLAY); @@ -114,18 +121,16 @@ void FilterImage::render_cairo(FilterSlot &slot) Geom::Rect sa = slot.get_slot_area(); cairo_surface_t *out = - cairo_image_surface_create(CAIRO_FORMAT_ARGB32, - sa.width() * device_scale, - sa.height() * device_scale); + cairo_image_surface_create(CAIRO_FORMAT_ARGB32, sa.width() * device_scale, sa.height() * device_scale); cairo_surface_set_device_scale(out, device_scale, device_scale); Inkscape::DrawingContext dc(out, sa.min()); dc.transform(user2pb); // we are now in primitive units dc.translate(feImageX, feImageY); -// dc.scale(scaleX, scaleY); No scaling should be done + // dc.scale(scaleX, scaleY); No scaling should be done Geom::IntRect render_rect = area.roundOutwards(); -// dc.translate(render_rect.min()); This seems incorrect + // dc.translate(render_rect.min()); This seems incorrect // Update to renderable state drawing.update(render_rect); @@ -137,7 +142,7 @@ void FilterImage::render_cairo(FilterSlot &slot) slot.set(_output, out); cairo_surface_destroy(out); - std::cout << " feImage: out: " << cairo_image_surface_get_width( out) << std::endl; + std::cout << " feImage: out: " << cairo_image_surface_get_width(out) << std::endl; std::cout << "FilterImage::render_cairo: Exit 2" << std::endl; return; } @@ -155,21 +160,22 @@ void FilterImage::render_cairo(FilterSlot &slot) * (i.e. interpreting it as relative to our current working directory). * (See http://www.w3.org/TR/xmlbase/#resolution .) */ gchar *fullname = feImageHref; - if ( !g_file_test( fullname, G_FILE_TEST_EXISTS ) ) { + if (!g_file_test(fullname, G_FILE_TEST_EXISTS)) { // Try to load from relative position combined with document base - if( document ) { - fullname = g_build_filename( document->getDocumentBase(), feImageHref, NULL ); + if (document) { + fullname = g_build_filename(document->getDocumentBase(), feImageHref, NULL); } } - if ( !g_file_test( fullname, G_FILE_TEST_EXISTS ) ) { + if (!g_file_test(fullname, G_FILE_TEST_EXISTS)) { // Should display Broken Image png. - g_warning("FilterImage::render: Can not find: %s", feImageHref ); + g_warning("FilterImage::render: Can not find: %s", feImageHref); return; } image = Inkscape::Pixbuf::create_from_file(fullname); - if( fullname != feImageHref ) g_free( fullname ); + if (fullname != feImageHref) + g_free(fullname); - if ( !image ) { + if (!image) { g_warning("FilterImage::render: failed to load image: %s", feImageHref); return; } @@ -184,9 +190,9 @@ void FilterImage::render_cairo(FilterSlot &slot) cairo_surface_t *image_surface = image->getSurfaceRaw(); std::cout << " image: " << cairo_image_surface_get_width(image_surface) << std::endl; Geom::Rect sa = slot.get_slot_area(); - cairo_surface_t *out = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, - sa.width() * device_scale, sa.height() * device_scale); - cairo_surface_set_device_scale( out, device_scale, device_scale ); + cairo_surface_t *out = + cairo_image_surface_create(CAIRO_FORMAT_ARGB32, sa.width() * device_scale, sa.height() * device_scale); + cairo_surface_set_device_scale(out, device_scale, device_scale); std::cout << " out: " << cairo_image_surface_get_width(out) << std::endl; // For the moment, we'll assume that any image is in sRGB color space @@ -205,15 +211,14 @@ void FilterImage::render_cairo(FilterSlot &slot) // Partially copied from sp-image.cpp. // Do nothing if preserveAspectRatio is "none". - if( aspect_align != SP_ASPECT_NONE ) { - + if (aspect_align != SP_ASPECT_NONE) { // Check aspect ratio of image vs. viewport - double feAspect = feImageHeight/feImageWidth; - double aspect = (double)image->height()/(double)image->width(); + double feAspect = feImageHeight / feImageWidth; + double aspect = (double)image->height() / (double)image->width(); bool ratio = (feAspect < aspect); double ax, ay; // Align side - switch( aspect_align ) { + switch (aspect_align) { case SP_ASPECT_XMIN_YMIN: ax = 0.0; ay = 0.0; @@ -256,25 +261,25 @@ void FilterImage::render_cairo(FilterSlot &slot) break; } - if( aspect_clip == SP_ASPECT_SLICE ) { + if (aspect_clip == SP_ASPECT_SLICE) { // image clipped by viewbox - if( ratio ) { + if (ratio) { // clip top/bottom feImageY -= ay * (feImageWidth * aspect - feImageHeight); feImageHeight = feImageWidth * aspect; } else { // clip sides - feImageX -= ax * (feImageHeight / aspect - feImageWidth); + feImageX -= ax * (feImageHeight / aspect - feImageWidth); feImageWidth = feImageHeight / aspect; } } else { // image fits into viewbox - if( ratio ) { + if (ratio) { // fit to height - feImageX += ax * (feImageWidth - feImageHeight / aspect ); + feImageX += ax * (feImageWidth - feImageHeight / aspect); feImageWidth = feImageHeight / aspect; } else { // fit to width @@ -307,25 +312,29 @@ double FilterImage::complexity(Geom::Affine const &) return 1.1; } -void FilterImage::set_href(const gchar *href){ - - if (feImageHref) g_free (feImageHref); - feImageHref = (href) ? g_strdup (href) : nullptr; +void FilterImage::set_href(const gchar *href) +{ + if (feImageHref) + g_free(feImageHref); + feImageHref = (href) ? g_strdup(href) : nullptr; delete image; image = nullptr; broken_ref = false; } -void FilterImage::set_document(SPDocument *doc){ +void FilterImage::set_document(SPDocument *doc) +{ document = doc; } -void FilterImage::set_align( unsigned int align ) { +void FilterImage::set_align(unsigned int align) +{ aspect_align = align; } -void FilterImage::set_clip( unsigned int clip ) { +void FilterImage::set_clip(unsigned int clip) +{ aspect_clip = clip; } diff --git a/src/display/nr-filter-image.h b/src/display/nr-filter-image.h index 6080bb4a2deaa39a45517fc49e993eb33efee158..b4466183ff28038a460fb292974d1b23301d74e8 100644 --- a/src/display/nr-filter-image.h +++ b/src/display/nr-filter-image.h @@ -24,7 +24,8 @@ class Pixbuf; namespace Filters { class FilterSlot; -class FilterImage : public FilterPrimitive { +class FilterImage : public FilterPrimitive +{ public: FilterImage(); static FilterPrimitive *create(); @@ -34,12 +35,12 @@ public: bool can_handle_affine(Geom::Affine const &) override; double complexity(Geom::Affine const &ctm) override; - void set_document( SPDocument *document ); + void set_document(SPDocument *document); void set_href(char const *href); - void set_align( unsigned int align ); - void set_clip( unsigned int clip ); + void set_align(unsigned int align); + void set_clip(unsigned int clip); bool from_element; - SPItem* SVGElem; + SPItem *SVGElem; Glib::ustring name() override { return Glib::ustring("Image"); } diff --git a/src/display/nr-filter-merge.cpp b/src/display/nr-filter-merge.cpp index 9ebfe40756b2c9eb57971e7df1a7ecb5a4882b13..c32dafb95e4c0dc81fb25970c1be6647e1c7f299 100644 --- a/src/display/nr-filter-merge.cpp +++ b/src/display/nr-filter-merge.cpp @@ -10,46 +10,49 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/nr-filter-merge.h" + #include + #include "display/cairo-utils.h" -#include "display/nr-filter-merge.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-utils.h" namespace Inkscape { namespace Filters { -FilterMerge::FilterMerge() : - _input_image(1, NR_FILTER_SLOT_NOT_SET) +FilterMerge::FilterMerge() + : _input_image(1, NR_FILTER_SLOT_NOT_SET) {} -FilterPrimitive * FilterMerge::create() { +FilterPrimitive *FilterMerge::create() +{ return new FilterMerge(); } -FilterMerge::~FilterMerge() -= default; +FilterMerge::~FilterMerge() = default; void FilterMerge::render_cairo(FilterSlot &slot) { - if (_input_image.empty()) return; + if (_input_image.empty()) + return; - SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; - if( _style ) { + SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; + if (_style) { ci_fp = (SPColorInterpolation)_style->color_interpolation_filters.computed; } - Geom::Rect vp = filter_primitive_area( slot.get_units() ); + Geom::Rect vp = filter_primitive_area(slot.get_units()); slot.set_primitive_area(_output, vp); // Needed for tiling // output is RGBA if at least one input is RGBA bool rgba32 = false; cairo_surface_t *out = nullptr; - for (int & i : _input_image) { + for (int &i : _input_image) { cairo_surface_t *in = slot.getcairo(i); if (cairo_surface_get_content(in) == CAIRO_CONTENT_COLOR_ALPHA) { out = ink_cairo_surface_create_identical(in); - set_cairo_surface_ci( out, ci_fp ); + set_cairo_surface_ci(out, ci_fp); rgba32 = true; break; } @@ -60,10 +63,10 @@ void FilterMerge::render_cairo(FilterSlot &slot) } cairo_t *out_ct = cairo_create(out); - for (int & i : _input_image) { + for (int &i : _input_image) { cairo_surface_t *in = slot.getcairo(i); - set_cairo_surface_ci( in, ci_fp ); + set_cairo_surface_ci(in, ci_fp); cairo_set_source_surface(out_ct, in, 0, 0); cairo_paint(out_ct); } @@ -94,17 +97,20 @@ bool FilterMerge::uses_background() return false; } -void FilterMerge::set_input(int slot) { +void FilterMerge::set_input(int slot) +{ _input_image[0] = slot; } -void FilterMerge::set_input(int input, int slot) { - if (input < 0) return; +void FilterMerge::set_input(int input, int slot) +{ + if (input < 0) + return; if (static_cast(_input_image.size()) > input) { _input_image[input] = slot; } else { - for (int i = static_cast(_input_image.size()) ; i < input ; i++) { + for (int i = static_cast(_input_image.size()); i < input; i++) { _input_image.push_back(NR_FILTER_SLOT_NOT_SET); } _input_image.push_back(slot); diff --git a/src/display/nr-filter-merge.h b/src/display/nr-filter-merge.h index 72356dcea9d9cfc66ee3ff39dbbfc10bdcc8178c..7185c11e179eb9495f24aedfb9d610558aca6a6b 100644 --- a/src/display/nr-filter-merge.h +++ b/src/display/nr-filter-merge.h @@ -14,12 +14,14 @@ */ #include + #include "display/nr-filter-primitive.h" namespace Inkscape { namespace Filters { -class FilterMerge : public FilterPrimitive { +class FilterMerge : public FilterPrimitive +{ public: FilterMerge(); static FilterPrimitive *create(); diff --git a/src/display/nr-filter-morphology.cpp b/src/display/nr-filter-morphology.cpp index 700d69f093f3ccc845799648255d6339fdb24dbe..7c779925edc06a089b1bfef02cc846e7e0a91769 100644 --- a/src/display/nr-filter-morphology.cpp +++ b/src/display/nr-filter-morphology.cpp @@ -11,13 +11,14 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include #include +#include #include #include + #include "display/cairo-templates.h" #include "display/cairo-utils.h" #include "display/nr-filter-morphology.h" @@ -27,38 +28,42 @@ namespace Inkscape { namespace Filters { -FilterMorphology::FilterMorphology() -= default; +FilterMorphology::FilterMorphology() = default; -FilterPrimitive * FilterMorphology::create() { +FilterPrimitive *FilterMorphology::create() +{ return new FilterMorphology(); } -FilterMorphology::~FilterMorphology() -= default; +FilterMorphology::~FilterMorphology() = default; -enum MorphologyOp { +enum MorphologyOp +{ ERODE, DILATE }; namespace { -/* This performs one "half" of the morphology operation by calculating +/* This performs one "half" of the morphology operation by calculating * the componentwise extreme in the specified axis with the given radius. * Extreme of row extremes is equal to the extreme of components, so this * doesn't change the result. - * The algorithm is due to: Petr Dokládal, Eva Dokládalová (2011), "Computationally efficient, one-pass algorithm for morphological filters" - * TODO: Currently only the 1D algorithm is implemented, but it should not be too difficult (and at the very least more memory efficient) to implement the full 2D algorithm. - * One problem with the 2D algorithm is that it is harder to parallelize. + * The algorithm is due to: Petr Dokládal, Eva Dokládalová (2011), "Computationally efficient, one-pass algorithm for + * morphological filters" + * TODO: Currently only the 1D algorithm is implemented, but it should not be too difficult (and at the very least more + * memory efficient) to implement the full 2D algorithm. One problem with the 2D algorithm is that it is harder to + * parallelize. */ template -void morphologicalFilter1D(cairo_surface_t * const input, cairo_surface_t * const out, double radius) { +void morphologicalFilter1D(cairo_surface_t *const input, cairo_surface_t *const out, double radius) +{ Comparison comp; int w = cairo_image_surface_get_width(out); int h = cairo_image_surface_get_height(out); - if (axis == Geom::Y) std::swap(w,h); + if (axis == Geom::Y) + std::swap(w, h); int stridein = cairo_image_surface_get_stride(input); int strideout = cairo_image_surface_get_stride(out); @@ -67,22 +72,25 @@ void morphologicalFilter1D(cairo_surface_t * const input, cairo_surface_t * cons unsigned char *out_data = cairo_image_surface_get_data(out); int ri = round(radius); // TODO: Support fractional radii? - int wi = 2*ri+1; + int wi = 2 * ri + 1; - #if HAVE_OPENMP +#if HAVE_OPENMP int limit = w * h; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int numOfThreads = prefs->getIntLimited("/options/threading/numthreads", omp_get_num_procs(), 1, 256); - (void) numOfThreads; // suppress unused variable warning - #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(numOfThreads) - #endif // HAVE_OPENMP + (void)numOfThreads; // suppress unused variable warning +#pragma omp parallel for if (limit > OPENMP_THRESHOLD) num_threads(numOfThreads) +#endif // HAVE_OPENMP for (int i = 0; i < h; ++i) { - // TODO: Store position and value in one 32 bit integer? 24 bits should be enough for a position, it would be quite strange to have an image with a width/height of more than 16 million(!). - std::deque< std::pair > vals[BPP]; // In my tests it was actually slightly faster to allocate it here than allocate it once for all threads and retrieving the correct set based on the thread id. + // TODO: Store position and value in one 32 bit integer? 24 bits should be enough for a position, it would be + // quite strange to have an image with a width/height of more than 16 million(!). + std::deque> vals[BPP]; // In my tests it was actually slightly faster to allocate + // it here than allocate it once for all threads and + // retrieving the correct set based on the thread id. // Initialize with transparent black - for(int p = 0; p < BPP; ++p) { - vals[p].push_back(std::pair(-1,0)); // TODO: Only do this when performing an erosion? + for (int p = 0; p < BPP; ++p) { + vals[p].push_back(std::pair(-1, 0)); // TODO: Only do this when performing an erosion? } // Process "row" @@ -97,8 +105,8 @@ void morphologicalFilter1D(cairo_surface_t * const input, cairo_surface_t * cons while(!vals[p].empty() && !comp(vals[p].back().second, *in_p)) vals[p].pop_back(); // useless vals[p].push_back(std::make_pair(j, *in_p)); ++in_p; - } else if (j == w) { // Transparent black beyond the image. TODO: Only do this when performing an erosion? - while(!vals[p].empty() && !comp(vals[p].back().second, 0)) vals[p].pop_back(); + } else if (j == w) { // Transparent black beyond the image. TODO: Only do this when performing an + erosion? while(!vals[p].empty() && !comp(vals[p].back().second, 0)) vals[p].pop_back(); vals[p].push_back(std::make_pair(j, 0)); } // Set output @@ -110,24 +118,29 @@ void morphologicalFilter1D(cairo_surface_t * const input, cairo_surface_t * cons if (axis == Geom::Y && j < w ) in_p += stridein - BPP; if (axis == Geom::Y && j >= ri) out_p += strideout - BPP; }*/ - for (int j = 0; j < std::min(ri,w); ++j) { - for(int p = 0; p < BPP; ++p) { // Iterate over channels + for (int j = 0; j < std::min(ri, w); ++j) { + for (int p = 0; p < BPP; ++p) { // Iterate over channels // Push new value onto FIFO, erasing any previous values that are "useless" (see paper) or out-of-range - if (!vals[p].empty() && vals[p].front().first <= j) vals[p].pop_front(); // out-of-range - while(!vals[p].empty() && !comp(vals[p].back().second, *in_p)) vals[p].pop_back(); // useless - vals[p].push_back(std::make_pair(j+wi, *in_p)); + if (!vals[p].empty() && vals[p].front().first <= j) + vals[p].pop_front(); // out-of-range + while (!vals[p].empty() && !comp(vals[p].back().second, *in_p)) + vals[p].pop_back(); // useless + vals[p].push_back(std::make_pair(j + wi, *in_p)); ++in_p; } - if (axis == Geom::Y) in_p += stridein - BPP; + if (axis == Geom::Y) + in_p += stridein - BPP; } // We have now done all preparatory work. // If w<=ri, then the following loop does nothing (which is as it should). for (int j = ri; j < w; ++j) { - for(int p = 0; p < BPP; ++p) { // Iterate over channels + for (int p = 0; p < BPP; ++p) { // Iterate over channels // Push new value onto FIFO, erasing any previous values that are "useless" (see paper) or out-of-range - if (!vals[p].empty() && vals[p].front().first <= j) vals[p].pop_front(); // out-of-range - while(!vals[p].empty() && !comp(vals[p].back().second, *in_p)) vals[p].pop_back(); // useless - vals[p].push_back(std::make_pair(j+wi, *in_p)); + if (!vals[p].empty() && vals[p].front().first <= j) + vals[p].pop_front(); // out-of-range + while (!vals[p].empty() && !comp(vals[p].back().second, *in_p)) + vals[p].pop_back(); // useless + vals[p].push_back(std::make_pair(j + wi, *in_p)); ++in_p; // Set output *out_p = vals[p].front().second; @@ -140,20 +153,23 @@ void morphologicalFilter1D(cairo_surface_t * const input, cairo_surface_t * cons } // We have now done all work which involves both input and output. // The following loop makes sure that the border is handled correctly. - for(int p = 0; p < BPP; ++p) { // Iterate over channels - while(!vals[p].empty() && !comp(vals[p].back().second, 0)) vals[p].pop_back(); - vals[p].push_back(std::make_pair(w+wi, 0)); + for (int p = 0; p < BPP; ++p) { // Iterate over channels + while (!vals[p].empty() && !comp(vals[p].back().second, 0)) + vals[p].pop_back(); + vals[p].push_back(std::make_pair(w + wi, 0)); } // Now we just have to finish the output. - for (int j = std::max(w,ri); j < w+ri; ++j) { - for(int p = 0; p < BPP; ++p) { // Iterate over channels + for (int j = std::max(w, ri); j < w + ri; ++j) { + for (int p = 0; p < BPP; ++p) { // Iterate over channels // Remove out-of-range values - if (!vals[p].empty() && vals[p].front().first <= j) vals[p].pop_front(); // out-of-range + if (!vals[p].empty() && vals[p].front().first <= j) + vals[p].pop_front(); // out-of-range // Set output *out_p = vals[p].front().second; ++out_p; } - if (axis == Geom::Y) out_p += strideout - BPP; + if (axis == Geom::Y) + out_p += strideout - BPP; } } @@ -185,15 +201,15 @@ void FilterMorphology::render_cairo(FilterSlot &slot) if (Operator == MORPHOLOGY_OPERATOR_DILATE) { if (bpp == 1) { - morphologicalFilter1D< std::greater, Geom::X, 1 >(input, interm, xr); + morphologicalFilter1D, Geom::X, 1>(input, interm, xr); } else { - morphologicalFilter1D< std::greater, Geom::X, 4 >(input, interm, xr); + morphologicalFilter1D, Geom::X, 4>(input, interm, xr); } } else { if (bpp == 1) { - morphologicalFilter1D< std::less, Geom::X, 1 >(input, interm, xr); + morphologicalFilter1D, Geom::X, 1>(input, interm, xr); } else { - morphologicalFilter1D< std::less, Geom::X, 4 >(input, interm, xr); + morphologicalFilter1D, Geom::X, 4>(input, interm, xr); } } @@ -204,15 +220,15 @@ void FilterMorphology::render_cairo(FilterSlot &slot) if (Operator == MORPHOLOGY_OPERATOR_DILATE) { if (bpp == 1) { - morphologicalFilter1D< std::greater, Geom::Y, 1 >(interm, out, yr); + morphologicalFilter1D, Geom::Y, 1>(interm, out, yr); } else { - morphologicalFilter1D< std::greater, Geom::Y, 4 >(interm, out, yr); + morphologicalFilter1D, Geom::Y, 4>(interm, out, yr); } } else { if (bpp == 1) { - morphologicalFilter1D< std::less, Geom::Y, 1 >(interm, out, yr); + morphologicalFilter1D, Geom::Y, 1>(interm, out, yr); } else { - morphologicalFilter1D< std::less, Geom::Y, 4 >(interm, out, yr); + morphologicalFilter1D, Geom::Y, 4>(interm, out, yr); } } @@ -237,15 +253,18 @@ double FilterMorphology::complexity(Geom::Affine const &trans) return enlarge_x * enlarge_y; } -void FilterMorphology::set_operator(FilterMorphologyOperator &o){ +void FilterMorphology::set_operator(FilterMorphologyOperator &o) +{ Operator = o; } -void FilterMorphology::set_xradius(double x){ +void FilterMorphology::set_xradius(double x) +{ xradius = x; } -void FilterMorphology::set_yradius(double y){ +void FilterMorphology::set_yradius(double y) +{ yradius = y; } diff --git a/src/display/nr-filter-morphology.h b/src/display/nr-filter-morphology.h index f91192b51d310104423f5ef9e39386acfc1cb1ea..d26d90b8ca6ce832f24c84a08d5eada206a24070 100644 --- a/src/display/nr-filter-morphology.h +++ b/src/display/nr-filter-morphology.h @@ -20,13 +20,15 @@ namespace Filters { class FilterSlot; -enum FilterMorphologyOperator { +enum FilterMorphologyOperator +{ MORPHOLOGY_OPERATOR_ERODE, MORPHOLOGY_OPERATOR_DILATE, MORPHOLOGY_OPERATOR_END }; -class FilterMorphology : public FilterPrimitive { +class FilterMorphology : public FilterPrimitive +{ public: FilterMorphology(); static FilterPrimitive *create(); diff --git a/src/display/nr-filter-offset.cpp b/src/display/nr-filter-offset.cpp index 2f733893cb069e57468bd82211404673f07638eb..3fc949975dc1b601c8b63c7a9bd467f2e605f4c8 100644 --- a/src/display/nr-filter-offset.cpp +++ b/src/display/nr-filter-offset.cpp @@ -10,8 +10,9 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "display/cairo-utils.h" #include "display/nr-filter-offset.h" + +#include "display/cairo-utils.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" @@ -21,16 +22,17 @@ namespace Filters { using Geom::X; using Geom::Y; -FilterOffset::FilterOffset() : - dx(0), dy(0) +FilterOffset::FilterOffset() + : dx(0) + , dy(0) {} -FilterPrimitive * FilterOffset::create() { +FilterPrimitive *FilterOffset::create() +{ return new FilterOffset(); } -FilterOffset::~FilterOffset() -= default; +FilterOffset::~FilterOffset() = default; void FilterOffset::render_cairo(FilterSlot &slot) { @@ -40,7 +42,7 @@ void FilterOffset::render_cairo(FilterSlot &slot) copy_cairo_surface_ci(in, out); cairo_t *ct = cairo_create(out); - Geom::Rect vp = filter_primitive_area( slot.get_units() ); + Geom::Rect vp = filter_primitive_area(slot.get_units()); slot.set_primitive_area(_output, vp); // Needed for tiling Geom::Affine p2pb = slot.get_units().get_matrix_primitiveunits2pb(); @@ -60,11 +62,13 @@ bool FilterOffset::can_handle_affine(Geom::Affine const &) return true; } -void FilterOffset::set_dx(double amount) { +void FilterOffset::set_dx(double amount) +{ dx = amount; } -void FilterOffset::set_dy(double amount) { +void FilterOffset::set_dy(double amount) +{ dy = amount; } diff --git a/src/display/nr-filter-offset.h b/src/display/nr-filter-offset.h index 30e852707bacba4203f43fb1e72d067727ad429c..b88f209618080b5f07b116e33f17a177caf44383 100644 --- a/src/display/nr-filter-offset.h +++ b/src/display/nr-filter-offset.h @@ -20,7 +20,8 @@ namespace Inkscape { namespace Filters { -class FilterOffset : public FilterPrimitive { +class FilterOffset : public FilterPrimitive +{ public: FilterOffset(); static FilterPrimitive *create(); diff --git a/src/display/nr-filter-primitive.cpp b/src/display/nr-filter-primitive.cpp index 65133eace2b3a7a5d783d82be7cda81c470316f9..bbfab2845bfa876b6552edb754cab15d80b3bb44 100644 --- a/src/display/nr-filter-primitive.cpp +++ b/src/display/nr-filter-primitive.cpp @@ -12,15 +12,14 @@ */ #include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-types.h" -#include "svg/svg-length.h" -#include "inkscape.h" #include "desktop.h" - +#include "display/nr-filter-slot.h" +#include "display/nr-filter-types.h" #include "document.h" +#include "inkscape.h" #include "style.h" +#include "svg/svg-length.h" namespace Inkscape { namespace Filters { @@ -52,7 +51,7 @@ FilterPrimitive::FilterPrimitive() FilterPrimitive::~FilterPrimitive() { - if(_style) + if (_style) sp_style_unref(_style); } @@ -63,21 +62,26 @@ void FilterPrimitive::render_cairo(FilterSlot &slot) slot.set(_output, in); } -void FilterPrimitive::area_enlarge(Geom::IntRect &/*area*/, Geom::Affine const &/*m*/) +void FilterPrimitive::area_enlarge(Geom::IntRect & /*area*/, Geom::Affine const & /*m*/) { // This doesn't need to do anything by default } -void FilterPrimitive::set_input(int slot) { +void FilterPrimitive::set_input(int slot) +{ set_input(0, slot); } -void FilterPrimitive::set_input(int input, int slot) { - if (input == 0) _input = slot; +void FilterPrimitive::set_input(int input, int slot) +{ + if (input == 0) + _input = slot; } -void FilterPrimitive::set_output(int slot) { - if (slot >= 0) _output = slot; +void FilterPrimitive::set_output(int slot) +{ + if (slot >= 0) + _output = slot; } // We need to copy reference even if unset as we need to know if @@ -100,8 +104,9 @@ void FilterPrimitive::set_height(SVGLength const &length) _subregion_height = length; } -void FilterPrimitive::set_subregion(SVGLength const &x, SVGLength const &y, - SVGLength const &width, SVGLength const &height) { +void FilterPrimitive::set_subregion(SVGLength const &x, SVGLength const &y, SVGLength const &width, + SVGLength const &height) +{ _subregion_x = x; _subregion_y = y; _subregion_width = width; @@ -113,7 +118,7 @@ Geom::Rect FilterPrimitive::filter_primitive_area(FilterUnits const &units) Geom::OptRect const fa_opt = units.get_filter_area(); if (!fa_opt) { std::cerr << "FilterPrimitive::filter_primitive_area: filter area undefined." << std::endl; - return Geom::Rect (Geom::Point(0.,0.), Geom::Point(0.,0.)); + return Geom::Rect(Geom::Point(0., 0.), Geom::Point(0., 0.)); } Geom::Rect fa = *fa_opt; @@ -126,21 +131,25 @@ Geom::Rect FilterPrimitive::filter_primitive_area(FilterUnits const &units) double height = 0; // If subregion not set, by special case use filter region. - if( !_subregion_x._set ) x = fa.min()[X]; - if( !_subregion_y._set ) y = fa.min()[Y]; - if( !_subregion_width._set ) width = fa.width(); - if( !_subregion_height._set ) height = fa.height(); - - if( units.get_primitive_units() == SP_FILTER_UNITS_OBJECTBOUNDINGBOX ) { - + if (!_subregion_x._set) + x = fa.min()[X]; + if (!_subregion_y._set) + y = fa.min()[Y]; + if (!_subregion_width._set) + width = fa.width(); + if (!_subregion_height._set) + height = fa.height(); + + if (units.get_primitive_units() == SP_FILTER_UNITS_OBJECTBOUNDINGBOX) { Geom::OptRect const bb_opt = units.get_item_bbox(); if (!bb_opt) { - std::cerr << "FilterPrimitive::filter_primitive_area: bounding box undefined and 'primitiveUnits' is 'objectBoundingBox'." << std::endl; - return Geom::Rect (Geom::Point(0.,0.), Geom::Point(0.,0.)); + std::cerr << "FilterPrimitive::filter_primitive_area: bounding box undefined and 'primitiveUnits' is " + "'objectBoundingBox'." + << std::endl; + return Geom::Rect(Geom::Point(0., 0.), Geom::Point(0., 0.)); } Geom::Rect bb = *bb_opt; - // Update computed values for ex, em, %. // For %, assumes primitive unit is objectBoundingBox. // TODO: fetch somehow the object ex and em lengths; 12, 6 are just dummy values. @@ -152,36 +161,50 @@ Geom::Rect FilterPrimitive::filter_primitive_area(FilterUnits const &units) _subregion_height.update(12, 6, len_y); // Values are in terms of fraction of bounding box. - if( _subregion_x._set && (_subregion_x.unit != SVGLength::PERCENT) ) x = bb.min()[X] + bb.width() * _subregion_x.value; - if( _subregion_y._set && (_subregion_y.unit != SVGLength::PERCENT) ) y = bb.min()[Y] + bb.height() * _subregion_y.value; - if( _subregion_width._set && (_subregion_width.unit != SVGLength::PERCENT) ) width = bb.width() * _subregion_width.value; - if( _subregion_height._set && (_subregion_height.unit != SVGLength::PERCENT) ) height = bb.height() * _subregion_height.value; - // Values are in terms of percent - if( _subregion_x._set && (_subregion_x.unit == SVGLength::PERCENT) ) x = bb.min()[X] + _subregion_x.computed; - if( _subregion_y._set && (_subregion_y.unit == SVGLength::PERCENT) ) y = bb.min()[Y] + _subregion_y.computed; - if( _subregion_width._set && (_subregion_width.unit == SVGLength::PERCENT) ) width = _subregion_width.computed; - if( _subregion_height._set && (_subregion_height.unit == SVGLength::PERCENT) ) height = _subregion_height.computed; + if (_subregion_x._set && (_subregion_x.unit != SVGLength::PERCENT)) + x = bb.min()[X] + bb.width() * _subregion_x.value; + if (_subregion_y._set && (_subregion_y.unit != SVGLength::PERCENT)) + y = bb.min()[Y] + bb.height() * _subregion_y.value; + if (_subregion_width._set && (_subregion_width.unit != SVGLength::PERCENT)) + width = bb.width() * _subregion_width.value; + if (_subregion_height._set && (_subregion_height.unit != SVGLength::PERCENT)) + height = bb.height() * _subregion_height.value; + // Values are in terms of percent + if (_subregion_x._set && (_subregion_x.unit == SVGLength::PERCENT)) + x = bb.min()[X] + _subregion_x.computed; + if (_subregion_y._set && (_subregion_y.unit == SVGLength::PERCENT)) + y = bb.min()[Y] + _subregion_y.computed; + if (_subregion_width._set && (_subregion_width.unit == SVGLength::PERCENT)) + width = _subregion_width.computed; + if (_subregion_height._set && (_subregion_height.unit == SVGLength::PERCENT)) + height = _subregion_height.computed; } else { - // Values are in terms of user space coordinates or percent of viewport (already calculated in sp-filter-primitive.cpp). - if( _subregion_x._set ) x = _subregion_x.computed; - if( _subregion_y._set ) y = _subregion_y.computed; - if( _subregion_width._set ) width = _subregion_width.computed; - if( _subregion_height._set ) height = _subregion_height.computed; + // Values are in terms of user space coordinates or percent of viewport (already calculated in + // sp-filter-primitive.cpp). + if (_subregion_x._set) + x = _subregion_x.computed; + if (_subregion_y._set) + y = _subregion_y.computed; + if (_subregion_width._set) + width = _subregion_width.computed; + if (_subregion_height._set) + height = _subregion_height.computed; } - return Geom::Rect (Geom::Point(x,y), Geom::Point(x + width, y + height)); + return Geom::Rect(Geom::Point(x, y), Geom::Point(x + width, y + height)); } void FilterPrimitive::setStyle(SPStyle *style) { - if( style != _style ) { - if (style) sp_style_ref(style); - if (_style) sp_style_unref(_style); + if (style != _style) { + if (style) + sp_style_ref(style); + if (_style) + sp_style_unref(_style); _style = style; } } - } /* namespace Filters */ } /* namespace Inkscape */ diff --git a/src/display/nr-filter-primitive.h b/src/display/nr-filter-primitive.h index 89cffac49a1c2b421998a12c020a3934843a17a1..b0c3a026b8fa075f17eb5865b4884afb1c2c4069 100644 --- a/src/display/nr-filter-primitive.h +++ b/src/display/nr-filter-primitive.h @@ -14,7 +14,6 @@ #include <2geom/forward.h> #include <2geom/rect.h> - #include #include "display/nr-filter-types.h" @@ -28,7 +27,8 @@ namespace Filters { class FilterSlot; class FilterUnits; -class FilterPrimitive { +class FilterPrimitive +{ public: FilterPrimitive(); virtual ~FilterPrimitive(); @@ -71,9 +71,10 @@ public: // returns cache score factor, reflecting the cost of rendering this filter // this should return how many times slower this primitive is that normal rendering - virtual double complexity(Geom::Affine const &/*ctm*/) { return 1.0; } + virtual double complexity(Geom::Affine const & /*ctm*/) { return 1.0; } - virtual bool uses_background() { + virtual bool uses_background() + { if (_input == NR_FILTER_BACKGROUNDIMAGE || _input == NR_FILTER_BACKGROUNDALPHA) { return true; } else { @@ -90,8 +91,7 @@ public: void set_y(SVGLength const &length); void set_width(SVGLength const &length); void set_height(SVGLength const &length); - void set_subregion(SVGLength const &x, SVGLength const &y, - SVGLength const &width, SVGLength const &height); + void set_subregion(SVGLength const &x, SVGLength const &y, SVGLength const &width, SVGLength const &height); /** * Resets the filter primitive subregion to its default value @@ -140,7 +140,6 @@ protected: SPStyle *_style; }; - } /* namespace Filters */ } /* namespace Inkscape */ diff --git a/src/display/nr-filter-skeleton.cpp b/src/display/nr-filter-skeleton.cpp index 072abc155b0122e79486064bcfacbf579e618616..1a4784fbdedb4e699bca59c86888f2ff322a8c8b 100644 --- a/src/display/nr-filter-skeleton.cpp +++ b/src/display/nr-filter-skeleton.cpp @@ -23,6 +23,7 @@ */ #include "display/nr-filter-skeleton.h" + #include "display/cairo-utils.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" @@ -30,25 +31,25 @@ namespace Inkscape { namespace Filters { -FilterSkeleton::FilterSkeleton() -{} +FilterSkeleton::FilterSkeleton() {} -FilterPrimitive * FilterSkeleton::create() { +FilterPrimitive *FilterSkeleton::create() +{ return new FilterSkeleton(); } -FilterSkeleton::~FilterSkeleton() -{} +FilterSkeleton::~FilterSkeleton() {} -void FilterSkeleton::render_cairo(FilterSlot &slot) { +void FilterSkeleton::render_cairo(FilterSlot &slot) +{ cairo_surface_t *in = slot.getcairo(_input); cairo_surface_t *out = ink_cairo_surface_create_identical(in); -// cairo_t *ct = cairo_create(out); + // cairo_t *ct = cairo_create(out); -// cairo_set_source_surface(ct, in, offset[X], offset[Y]); -// cairo_paint(ct); -// cairo_destroy(ct); + // cairo_set_source_surface(ct, in, offset[X], offset[Y]); + // cairo_paint(ct); + // cairo_destroy(ct); slot.set(_output, out); cairo_surface_destroy(out); diff --git a/src/display/nr-filter-skeleton.h b/src/display/nr-filter-skeleton.h index 83f18074841ea5fc42d393ef859b5e8b75054ce5..35bcf15f697fef38bf2bc27f604324787d9ab0c0 100644 --- a/src/display/nr-filter-skeleton.h +++ b/src/display/nr-filter-skeleton.h @@ -32,7 +32,8 @@ namespace Inkscape { namespace Filters { -class FilterSkeleton : public FilterPrimitive { +class FilterSkeleton : public FilterPrimitive +{ public: FilterSkeleton(); static FilterPrimitive *create(); @@ -41,7 +42,6 @@ public: virtual void render_cairo(FilterSlot &slot); private: - }; } /* namespace Filters */ diff --git a/src/display/nr-filter-slot.cpp b/src/display/nr-filter-slot.cpp index 4d9dc239d4c6d3f5b064aec3d6224aaa9939d0f0..bc794685b309b60f869807c21253c40a604c3399 100644 --- a/src/display/nr-filter-slot.cpp +++ b/src/display/nr-filter-slot.cpp @@ -12,26 +12,26 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/nr-filter-slot.h" + +#include <2geom/transforms.h> #include #include -#include <2geom/transforms.h> #include "display/cairo-utils.h" #include "display/drawing-context.h" -#include "display/nr-filter-types.h" #include "display/nr-filter-gaussian.h" -#include "display/nr-filter-slot.h" +#include "display/nr-filter-types.h" #include "display/nr-filter-units.h" namespace Inkscape { namespace Filters { -FilterSlot::FilterSlot(DrawingItem *item, DrawingContext *bgdc, - DrawingContext &graphic, FilterUnits const &u) +FilterSlot::FilterSlot(DrawingItem *item, DrawingContext *bgdc, DrawingContext &graphic, FilterUnits const &u) : _item(item) , _source_graphic(graphic.rawTarget()) , _background_ct(bgdc ? bgdc->raw() : nullptr) - , _source_graphic_area(graphic.targetLogicalBounds().roundOutwards()) // fixme + , _source_graphic_area(graphic.targetLogicalBounds().roundOutwards()) // fixme , _background_area(bgdc ? bgdc->targetLogicalBounds().roundOutwards() : Geom::IntRect()) // fixme , _units(u) , _last_out(NR_FILTER_SOURCEGRAPHIC) @@ -59,7 +59,7 @@ FilterSlot::FilterSlot(DrawingItem *item, DrawingContext *bgdc, FilterSlot::~FilterSlot() { - for (auto & _slot : _slots) { + for (auto &_slot : _slots) { cairo_surface_destroy(_slot.second); } } @@ -73,26 +73,21 @@ cairo_surface_t *FilterSlot::getcairo(int slot_nr) /* If we didn't have the specified image, but we could create it * from the other information we have, let's do that */ - if (s == _slots.end() - && (slot_nr == NR_FILTER_SOURCEGRAPHIC - || slot_nr == NR_FILTER_SOURCEALPHA - || slot_nr == NR_FILTER_BACKGROUNDIMAGE - || slot_nr == NR_FILTER_BACKGROUNDALPHA - || slot_nr == NR_FILTER_FILLPAINT - || slot_nr == NR_FILTER_STROKEPAINT)) - { + if (s == _slots.end() && (slot_nr == NR_FILTER_SOURCEGRAPHIC || slot_nr == NR_FILTER_SOURCEALPHA || + slot_nr == NR_FILTER_BACKGROUNDIMAGE || slot_nr == NR_FILTER_BACKGROUNDALPHA || + slot_nr == NR_FILTER_FILLPAINT || slot_nr == NR_FILTER_STROKEPAINT)) { switch (slot_nr) { case NR_FILTER_SOURCEGRAPHIC: { cairo_surface_t *tr = _get_transformed_source_graphic(); // Assume all source graphics are sRGB - set_cairo_surface_ci( tr, SP_CSS_COLOR_INTERPOLATION_SRGB ); + set_cairo_surface_ci(tr, SP_CSS_COLOR_INTERPOLATION_SRGB); _set_internal(NR_FILTER_SOURCEGRAPHIC, tr); cairo_surface_destroy(tr); } break; case NR_FILTER_BACKGROUNDIMAGE: { cairo_surface_t *bg = _get_transformed_background(); // Assume all backgrounds are sRGB - set_cairo_surface_ci( bg, SP_CSS_COLOR_INTERPOLATION_SRGB ); + set_cairo_surface_ci(bg, SP_CSS_COLOR_INTERPOLATION_SRGB); _set_internal(NR_FILTER_BACKGROUNDIMAGE, bg); cairo_surface_destroy(bg); } break; @@ -108,8 +103,8 @@ cairo_surface_t *FilterSlot::getcairo(int slot_nr) _set_internal(NR_FILTER_BACKGROUNDALPHA, ba); cairo_surface_destroy(ba); } break; - case NR_FILTER_FILLPAINT: //TODO - case NR_FILTER_STROKEPAINT: //TODO + case NR_FILTER_FILLPAINT: // TODO + case NR_FILTER_STROKEPAINT: // TODO default: break; } @@ -118,9 +113,8 @@ cairo_surface_t *FilterSlot::getcairo(int slot_nr) if (s == _slots.end()) { // create empty surface - cairo_surface_t *empty = cairo_surface_create_similar( - _source_graphic, cairo_surface_get_content(_source_graphic), - _slot_w, _slot_h); + cairo_surface_t *empty = + cairo_surface_create_similar(_source_graphic, cairo_surface_get_content(_source_graphic), _slot_w, _slot_h); _set_internal(slot_nr, empty); cairo_surface_destroy(empty); s = _slots.find(slot_nr); @@ -137,9 +131,8 @@ cairo_surface_t *FilterSlot::_get_transformed_source_graphic() return _source_graphic; } - cairo_surface_t *tsg = cairo_surface_create_similar( - _source_graphic, cairo_surface_get_content(_source_graphic), - _slot_w, _slot_h); + cairo_surface_t *tsg = + cairo_surface_create_similar(_source_graphic, cairo_surface_get_content(_source_graphic), _slot_w, _slot_h); cairo_t *tsg_ct = cairo_create(tsg); cairo_translate(tsg_ct, -_slot_x, -_slot_y); @@ -161,9 +154,7 @@ cairo_surface_t *FilterSlot::_get_transformed_background() if (_background_ct) { cairo_surface_t *bg = cairo_get_group_target(_background_ct); - tbg = cairo_surface_create_similar( - bg, cairo_surface_get_content(bg), - _slot_w, _slot_h); + tbg = cairo_surface_create_similar(bg, cairo_surface_get_content(bg), _slot_w, _slot_h); cairo_t *tbg_ct = cairo_create(tbg); cairo_translate(tbg_ct, -_slot_x, -_slot_y); @@ -190,11 +181,9 @@ cairo_surface_t *FilterSlot::get_result(int res) return result; } - cairo_surface_t *r = cairo_surface_create_similar(_source_graphic, - cairo_surface_get_content(_source_graphic), - _source_graphic_area.width(), - _source_graphic_area.height()); - copy_cairo_surface_ci( result, r ); + cairo_surface_t *r = cairo_surface_create_similar(_source_graphic, cairo_surface_get_content(_source_graphic), + _source_graphic_area.width(), _source_graphic_area.height()); + copy_cairo_surface_ci(result, r); cairo_t *r_ct = cairo_create(r); cairo_translate(r_ct, -_source_graphic_area.left(), -_source_graphic_area.top()); @@ -259,30 +248,36 @@ int FilterSlot::get_slot_count() return _slots.size(); } -void FilterSlot::set_quality(FilterQuality const q) { +void FilterSlot::set_quality(FilterQuality const q) +{ filterquality = q; } -void FilterSlot::set_blurquality(int const q) { +void FilterSlot::set_blurquality(int const q) +{ blurquality = q; } -int FilterSlot::get_blurquality() { +int FilterSlot::get_blurquality() +{ return blurquality; } -void FilterSlot::set_device_scale(int const s) { +void FilterSlot::set_device_scale(int const s) +{ device_scale = s; } -int FilterSlot::get_device_scale() { +int FilterSlot::get_device_scale() +{ return device_scale; } -Geom::Rect FilterSlot::get_slot_area() const { +Geom::Rect FilterSlot::get_slot_area() const +{ Geom::Point p(_slot_x, _slot_y); Geom::Point dim(_slot_w, _slot_h); - Geom::Rect r(p, p+dim); + Geom::Rect r(p, p + dim); return r; } diff --git a/src/display/nr-filter-slot.h b/src/display/nr-filter-slot.h index 1a695c4565217808eb87f96b92e8bebd220824cf..aca44de956e176e74de1de2420ab714448f54f92 100644 --- a/src/display/nr-filter-slot.h +++ b/src/display/nr-filter-slot.h @@ -16,6 +16,7 @@ */ #include + #include "display/nr-filter-types.h" #include "display/nr-filter-units.h" @@ -30,11 +31,11 @@ class DrawingItem; namespace Filters { -class FilterSlot { +class FilterSlot +{ public: /** Creates a new FilterSlot object. */ - FilterSlot(DrawingItem *item, DrawingContext *bgdc, - DrawingContext &graphic, FilterUnits const &u); + FilterSlot(DrawingItem *item, DrawingContext *bgdc, DrawingContext &graphic, FilterUnits const &u); /** Destroys the FilterSlot object and all its contents */ virtual ~FilterSlot(); @@ -57,12 +58,12 @@ public: void set_primitive_area(int slot, Geom::Rect &area); Geom::Rect get_primitive_area(int slot); - + /** Returns the number of slots in use. */ int get_slot_count(); /** Sets the unit system to be used for the internal images. */ - //void set_units(FilterUnits const &units); + // void set_units(FilterUnits const &units); /** Sets the filtering quality. Affects used interpolation methods */ void set_quality(FilterQuality const q); @@ -92,8 +93,8 @@ private: DrawingItem *_item; - //Geom::Rect _source_bbox; ///< bounding box of source graphic surface - //Geom::Rect _intermediate_bbox; ///< bounding box of intermediate surfaces + // Geom::Rect _source_bbox; ///< bounding box of source graphic surface + // Geom::Rect _intermediate_bbox; ///< bounding box of intermediate surfaces int _slot_w, _slot_h; double _slot_x, _slot_y; diff --git a/src/display/nr-filter-specularlighting.cpp b/src/display/nr-filter-specularlighting.cpp index 330f19c365d944ccb36f9d41b096e4f57c124722..e579e87efecaf51315f04aafa12bb00b90ef468a 100644 --- a/src/display/nr-filter-specularlighting.cpp +++ b/src/display/nr-filter-specularlighting.cpp @@ -12,22 +12,22 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include #include +#include #include "display/cairo-templates.h" #include "display/cairo-utils.h" #include "display/nr-3dutils.h" -#include "display/nr-filter-specularlighting.h" #include "display/nr-filter-slot.h" +#include "display/nr-filter-specularlighting.h" #include "display/nr-filter-units.h" #include "display/nr-filter-utils.h" #include "display/nr-light.h" -#include "svg/svg-icc-color.h" #include "svg/svg-color.h" +#include "svg/svg-icc-color.h" namespace Inkscape { namespace Filters { @@ -41,23 +41,25 @@ FilterSpecularLighting::FilterSpecularLighting() lighting_color = 0xffffffff; } -FilterPrimitive * FilterSpecularLighting::create() { +FilterPrimitive *FilterSpecularLighting::create() +{ return new FilterSpecularLighting(); } -FilterSpecularLighting::~FilterSpecularLighting() -= default; +FilterSpecularLighting::~FilterSpecularLighting() = default; -struct SpecularLight : public SurfaceSynth { - SpecularLight(cairo_surface_t *bumpmap, double scale, double specular_constant, - double specular_exponent) +struct SpecularLight : public SurfaceSynth +{ + SpecularLight(cairo_surface_t *bumpmap, double scale, double specular_constant, double specular_exponent) : SurfaceSynth(bumpmap) , _scale(scale) , _ks(specular_constant) , _exp(specular_exponent) {} + protected: - guint32 specularLighting(int x, int y, NR::Fvector const &halfway, NR::Fvector const &light_components) { + guint32 specularLighting(int x, int y, NR::Fvector const &halfway, NR::Fvector const &light_components) + { NR::Fvector normal = surfaceNormalAt(x, y, _scale); double sp = NR::scalar_product(normal, halfway); double k = sp <= 0.0 ? 0.0 : _ks * pow(sp, _exp); @@ -71,15 +73,16 @@ protected: g = premul_alpha(g, a); b = premul_alpha(b, a); - ASSEMBLE_ARGB32(pxout, a,r,g,b) + ASSEMBLE_ARGB32(pxout, a, r, g, b) return pxout; } double _scale, _ks, _exp; }; -struct SpecularDistantLight : public SpecularLight { - SpecularDistantLight(cairo_surface_t *bumpmap, SPFeDistantLight *light, guint32 color, - double scale, double specular_constant, double specular_exponent) +struct SpecularDistantLight : public SpecularLight +{ + SpecularDistantLight(cairo_surface_t *bumpmap, SPFeDistantLight *light, guint32 color, double scale, + double specular_constant, double specular_exponent) : SpecularLight(bumpmap, scale, specular_constant, specular_exponent) { DistantLight dl(light, color); @@ -88,17 +91,17 @@ struct SpecularDistantLight : public SpecularLight { dl.light_components(_light_components); NR::normalized_sum(_halfway, lv, NR::EYE_VECTOR); } - guint32 operator()(int x, int y) { - return specularLighting(x, y, _halfway, _light_components); - } + guint32 operator()(int x, int y) { return specularLighting(x, y, _halfway, _light_components); } + private: NR::Fvector _halfway, _light_components; }; -struct SpecularPointLight : public SpecularLight { - SpecularPointLight(cairo_surface_t *bumpmap, SPFePointLight *light, guint32 color, - Geom::Affine const &trans, double scale, double specular_constant, - double specular_exponent, double x0, double y0, int device_scale) +struct SpecularPointLight : public SpecularLight +{ + SpecularPointLight(cairo_surface_t *bumpmap, SPFePointLight *light, guint32 color, Geom::Affine const &trans, + double scale, double specular_constant, double specular_exponent, double x0, double y0, + int device_scale) : SpecularLight(bumpmap, scale, specular_constant, specular_exponent) , _light(light, color, trans, device_scale) , _x0(x0) @@ -107,35 +110,40 @@ struct SpecularPointLight : public SpecularLight { _light.light_components(_light_components); } - guint32 operator()(int x, int y) { + guint32 operator()(int x, int y) + { NR::Fvector light, halfway; - _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y)/255.0); + _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y) / 255.0); NR::normalized_sum(halfway, light, NR::EYE_VECTOR); return specularLighting(x, y, halfway, _light_components); } + private: PointLight _light; NR::Fvector _light_components; double _x0, _y0; }; -struct SpecularSpotLight : public SpecularLight { - SpecularSpotLight(cairo_surface_t *bumpmap, SPFeSpotLight *light, guint32 color, - Geom::Affine const &trans, double scale, double specular_constant, - double specular_exponent, double x0, double y0, int device_scale) +struct SpecularSpotLight : public SpecularLight +{ + SpecularSpotLight(cairo_surface_t *bumpmap, SPFeSpotLight *light, guint32 color, Geom::Affine const &trans, + double scale, double specular_constant, double specular_exponent, double x0, double y0, + int device_scale) : SpecularLight(bumpmap, scale, specular_constant, specular_exponent) , _light(light, color, trans, device_scale) , _x0(x0) , _y0(y0) {} - guint32 operator()(int x, int y) { + guint32 operator()(int x, int y) + { NR::Fvector light, halfway, light_components; - _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y)/255.0); + _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y) / 255.0); _light.light_components(light_components, light); NR::normalized_sum(halfway, light, NR::EYE_VECTOR); return specularLighting(x, y, halfway, light_components); } + private: SpotLight _light; double _x0, _y0; @@ -162,21 +170,21 @@ void FilterSpecularLighting::render_cairo(FilterSlot &slot) #endif // Only alpha channel of input is used, no need to check input color_interpolation_filter value. - SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; - if( _style ) { + SPColorInterpolation ci_fp = SP_CSS_COLOR_INTERPOLATION_AUTO; + if (_style) { ci_fp = (SPColorInterpolation)_style->color_interpolation_filters.computed; // Lighting color is always defined in terms of sRGB, preconvert to linearRGB // if color_interpolation_filters set to linearRGB (for efficiency assuming // next filter primitive has same value of cif). - if( ci_fp == SP_CSS_COLOR_INTERPOLATION_LINEARRGB ) { - r = srgb_to_linear( r ); - g = srgb_to_linear( g ); - b = srgb_to_linear( b ); + if (ci_fp == SP_CSS_COLOR_INTERPOLATION_LINEARRGB) { + r = srgb_to_linear(r); + g = srgb_to_linear(g); + b = srgb_to_linear(b); } } - set_cairo_surface_ci(out, ci_fp ); - guint32 color = SP_RGBA32_F_COMPOSE( r, g, b, 1.0 ); + set_cairo_surface_ci(out, ci_fp); + guint32 color = SP_RGBA32_F_COMPOSE(r, g, b, 1.0); int device_scale = slot.get_device_scale(); @@ -193,24 +201,23 @@ void FilterSpecularLighting::render_cairo(FilterSlot &slot) double se = specularExponent; switch (light_type) { - case DISTANT_LIGHT: - ink_cairo_surface_synthesize(out, - SpecularDistantLight(input, light.distant, color, scale, ks, se)); - break; - case POINT_LIGHT: - ink_cairo_surface_synthesize(out, - SpecularPointLight(input, light.point, color, trans, scale, ks, se, x0, y0, device_scale)); - break; - case SPOT_LIGHT: - ink_cairo_surface_synthesize(out, - SpecularSpotLight(input, light.spot, color, trans, scale, ks, se, x0, y0, device_scale)); - break; - default: { - cairo_t *ct = cairo_create(out); - cairo_set_source_rgba(ct, 0,0,0,1); - cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); - cairo_paint(ct); - cairo_destroy(ct); + case DISTANT_LIGHT: + ink_cairo_surface_synthesize(out, SpecularDistantLight(input, light.distant, color, scale, ks, se)); + break; + case POINT_LIGHT: + ink_cairo_surface_synthesize( + out, SpecularPointLight(input, light.point, color, trans, scale, ks, se, x0, y0, device_scale)); + break; + case SPOT_LIGHT: + ink_cairo_surface_synthesize( + out, SpecularSpotLight(input, light.spot, color, trans, scale, ks, se, x0, y0, device_scale)); + break; + default: { + cairo_t *ct = cairo_create(out); + cairo_set_source_rgba(ct, 0, 0, 0, 1); + cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(ct); + cairo_destroy(ct); } break; } @@ -218,7 +225,8 @@ void FilterSpecularLighting::render_cairo(FilterSlot &slot) cairo_surface_destroy(out); } -void FilterSpecularLighting::set_icc(SVGICCColor *icc_color) { +void FilterSpecularLighting::set_icc(SVGICCColor *icc_color) +{ icc = icc_color; } diff --git a/src/display/nr-filter-specularlighting.h b/src/display/nr-filter-specularlighting.h index 86fd8b59efbe884eefbef9d7a04bcc07097df9cf..906cb89a6fd7f6741e47bffe761e03e56cdae1df 100644 --- a/src/display/nr-filter-specularlighting.h +++ b/src/display/nr-filter-specularlighting.h @@ -14,8 +14,8 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "display/nr-light-types.h" #include "display/nr-filter-primitive.h" +#include "display/nr-light-types.h" class SPFeDistantLight; class SPFePointLight; @@ -28,7 +28,8 @@ namespace Filters { class FilterSlot; -class FilterSpecularLighting : public FilterPrimitive { +class FilterSpecularLighting : public FilterPrimitive +{ public: FilterSpecularLighting(); static FilterPrimitive *create(); @@ -39,7 +40,8 @@ public: void area_enlarge(Geom::IntRect &area, Geom::Affine const &trans) override; double complexity(Geom::Affine const &ctm) override; - union { + union + { SPFeDistantLight *distant; SPFePointLight *point; SPFeSpotLight *spot; diff --git a/src/display/nr-filter-tile.cpp b/src/display/nr-filter-tile.cpp index 4605ddeec6baefecb934749881bf31f281140c70..bccdbdd1eba999b9b53402b50270bd36744766c3 100644 --- a/src/display/nr-filter-tile.cpp +++ b/src/display/nr-filter-tile.cpp @@ -10,25 +10,25 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/nr-filter-tile.h" + #include #include "display/cairo-utils.h" -#include "display/nr-filter-tile.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" namespace Inkscape { namespace Filters { -FilterTile::FilterTile() -= default; +FilterTile::FilterTile() = default; -FilterPrimitive * FilterTile::create() { +FilterPrimitive *FilterTile::create() +{ return new FilterTile(); } -FilterTile::~FilterTile() -= default; +FilterTile::~FilterTile() = default; void FilterTile::render_cairo(FilterSlot &slot) { @@ -45,13 +45,11 @@ void FilterTile::render_cairo(FilterSlot &slot) // This is the feTile source area as determined by the input primitive area (see SVG spec). Geom::Rect tile_area = slot.get_primitive_area(_input); - if( tile_area.width() == 0.0 || tile_area.height() == 0.0 ) { - + if (tile_area.width() == 0.0 || tile_area.height() == 0.0) { slot.set(_output, in); std::cerr << "FileTile::render_cairo: tile has zero width or height" << std::endl; } else { - cairo_surface_t *out = ink_cairo_surface_create_identical(in); // color_interpolation_filters for out same as in. copy_cairo_surface_ci(in, out); @@ -66,38 +64,37 @@ void FilterTile::render_cairo(FilterSlot &slot) // Get tile area in pixbuf units (tile transformed). Geom::Rect tt = tile_area * trans; - + // Shift between "rendering" tile and feTile tile - Geom::Point shift = sa.min() - tt.min(); + Geom::Point shift = sa.min() - tt.min(); // Create feTile tile surface - cairo_surface_t *tile = cairo_surface_create_similar(in, cairo_surface_get_content(in), - tt.width(), tt.height()); + cairo_surface_t *tile = + cairo_surface_create_similar(in, cairo_surface_get_content(in), tt.width(), tt.height()); cairo_t *ct_tile = cairo_create(tile); cairo_set_source_surface(ct_tile, in, shift[Geom::X], shift[Geom::Y]); cairo_paint(ct_tile); // Paint tiles ------------------ - + // For debugging // std::stringstream filename; // filename << "tile." << i << ".png"; // cairo_surface_write_to_png( tile, filename.str().c_str() ); - + // Determine number of feTile rows and columns - Geom::Rect pr = filter_primitive_area( slot.get_units() ); - int tile_cols = ceil( pr.width() / tile_area.width() ); - int tile_rows = ceil( pr.height() / tile_area.height() ); + Geom::Rect pr = filter_primitive_area(slot.get_units()); + int tile_cols = ceil(pr.width() / tile_area.width()); + int tile_rows = ceil(pr.height() / tile_area.height()); // Do tiling (TO DO: restrict to slot area.) - for( int col=0; col < tile_cols; ++col ) { - for( int row=0; row < tile_rows; ++row ) { - - Geom::Point offset( col*tile_area.width(), row*tile_area.height() ); + for (int col = 0; col < tile_cols; ++col) { + for (int row = 0; row < tile_rows; ++row) { + Geom::Point offset(col * tile_area.width(), row * tile_area.height()); offset *= trans; offset[Geom::X] -= trans[4]; offset[Geom::Y] -= trans[5]; - + cairo_set_source_surface(ct, tile, offset[Geom::X], offset[Geom::Y]); cairo_paint(ct); } @@ -117,8 +114,8 @@ void FilterTile::area_enlarge(Geom::IntRect &area, Geom::Affine const &trans) // Set to very large rectangle so we get tile source. It will be clipped later. // Note, setting to infinite using Geom::IntRect::infinite() causes overflow/underflow problems. - Geom::IntCoord max = std::numeric_limits::max()/4; - area = Geom::IntRect(-max,-max,max,max); + Geom::IntCoord max = std::numeric_limits::max() / 4; + area = Geom::IntRect(-max, -max, max, max); } double FilterTile::complexity(Geom::Affine const &) diff --git a/src/display/nr-filter-tile.h b/src/display/nr-filter-tile.h index 867d129630fcd231ed80dc0ea3d17e1d1e48bb2f..efc45bde3f54e004efb06365814cd0cee659ea18 100644 --- a/src/display/nr-filter-tile.h +++ b/src/display/nr-filter-tile.h @@ -20,7 +20,8 @@ namespace Filters { class FilterSlot; -class FilterTile : public FilterPrimitive { +class FilterTile : public FilterPrimitive +{ public: FilterTile(); static FilterPrimitive *create(); diff --git a/src/display/nr-filter-turbulence.cpp b/src/display/nr-filter-turbulence.cpp index 91a71abcd575ed9f143dbbf59a069c3a9bbb4376..03b123856612be2f1532d5db0d394c07c6d24b2c 100644 --- a/src/display/nr-filter-turbulence.cpp +++ b/src/display/nr-filter-turbulence.cpp @@ -18,37 +18,39 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/nr-filter-turbulence.h" + +#include + #include "display/cairo-templates.h" #include "display/cairo-utils.h" -#include "display/nr-filter.h" -#include "display/nr-filter-turbulence.h" #include "display/nr-filter-units.h" #include "display/nr-filter-utils.h" -#include +#include "display/nr-filter.h" namespace Inkscape { -namespace Filters{ +namespace Filters { -class TurbulenceGenerator { +class TurbulenceGenerator +{ public: - TurbulenceGenerator() : - _tile(), - _baseFreq(), - _latticeSelector(), - _gradient(), - _seed(0), - _octaves(0), - _stitchTiles(false), - _wrapx(0), - _wrapy(0), - _wrapw(0), - _wraph(0), - _inited(false), - _fractalnoise(false) + TurbulenceGenerator() + : _tile() + , _baseFreq() + , _latticeSelector() + , _gradient() + , _seed(0) + , _octaves(0) + , _stitchTiles(false) + , _wrapx(0) + , _wrapy(0) + , _wrapw(0) + , _wraph(0) + , _inited(false) + , _fractalnoise(false) {} - void init(long seed, Geom::Rect const &tile, Geom::Point const &freq, bool stitch, - bool fractalnoise, int octaves) + void init(long seed, Geom::Rect const &tile, Geom::Point const &freq, bool stitch, bool fractalnoise, int octaves) { // setup random number generator _setupSeed(seed); @@ -66,9 +68,9 @@ public: _latticeSelector[i] = i; do { - _gradient[i][k][0] = static_cast(_random() % (BSize*2) - BSize) / BSize; - _gradient[i][k][1] = static_cast(_random() % (BSize*2) - BSize) / BSize; - } while(_gradient[i][k][0] == 0 && _gradient[i][k][1] == 0); + _gradient[i][k][0] = static_cast(_random() % (BSize * 2) - BSize) / BSize; + _gradient[i][k][1] = static_cast(_random() % (BSize * 2) - BSize) / BSize; + } while (_gradient[i][k][0] == 0 && _gradient[i][k][1] == 0); // normalize gradient double s = hypot(_gradient[i][k][0], _gradient[i][k][1]); @@ -83,11 +85,10 @@ public: } // fill out the remaining part of the gradient - for (i = 0; i < BSize + 2; ++i) - { + for (i = 0; i < BSize + 2; ++i) { _latticeSelector[BSize + i] = _latticeSelector[i]; - for(int k = 0; k < 4; ++k) { + for (int k = 0; k < 4; ++k) { _gradient[BSize + i][k][0] = _gradient[i][k][0]; _gradient[BSize + i][k][1] = _gradient[i][k][1]; } @@ -96,15 +97,13 @@ public: // When stitching tiled turbulence, the frequencies must be adjusted // so that the tile borders will be continuous. if (_stitchTiles) { - if (_baseFreq[Geom::X] != 0.0) - { + if (_baseFreq[Geom::X] != 0.0) { double freq = _baseFreq[Geom::X]; double lo = floor(_tile.width() * freq) / _tile.width(); double hi = ceil(_tile.width() * freq) / _tile.width(); _baseFreq[Geom::X] = freq / lo < hi / freq ? lo : hi; } - if (_baseFreq[Geom::Y] != 0.0) - { + if (_baseFreq[Geom::Y] != 0.0) { double freq = _baseFreq[Geom::Y]; double lo = floor(_tile.height() * freq) / _tile.height(); double hi = ceil(_tile.height() * freq) / _tile.height(); @@ -120,7 +119,8 @@ public: } G_GNUC_PURE - guint32 turbulencePixel(Geom::Point const &p) const { + guint32 turbulencePixel(Geom::Point const &p) const + { int wrapx = _wrapx, wrapy = _wrapy, wrapw = _wrapw, wraph = _wraph; double pixel[4]; @@ -128,11 +128,10 @@ public: double y = p[Geom::Y] * _baseFreq[Geom::Y]; double ratio = 1.0; - for (double & k : pixel) + for (double &k : pixel) k = 0.0; - for(int octave = 0; octave < _octaves; ++octave) - { + for (int octave = 0; octave < _octaves; ++octave) { double tx = x + PerlinOffset; double bx = floor(tx); double rx0 = tx - bx, rx1 = rx0 - 1.0; @@ -144,10 +143,14 @@ public: int by0 = by, by1 = by0 + 1; if (_stitchTiles) { - if (bx0 >= wrapx) bx0 -= wrapw; - if (bx1 >= wrapx) bx1 -= wrapw; - if (by0 >= wrapy) by0 -= wraph; - if (by1 >= wrapy) by1 -= wraph; + if (bx0 >= wrapx) + bx0 -= wrapw; + if (bx1 >= wrapx) + bx1 -= wrapw; + if (by0 >= wrapy) + by0 -= wraph; + if (by1 >= wrapy) + by1 -= wraph; } bx0 &= BMask; bx1 &= BMask; @@ -169,12 +172,10 @@ public: for (int k = 0; k < 4; ++k) { double const *qxa = _gradient[b00][k]; double const *qxb = _gradient[b10][k]; - double a = _lerp(sx, rx0 * qxa[0] + ry0 * qxa[1], - rx1 * qxb[0] + ry0 * qxb[1]); + double a = _lerp(sx, rx0 * qxa[0] + ry0 * qxa[1], rx1 * qxb[0] + ry0 * qxb[1]); double const *qya = _gradient[b01][k]; double const *qyb = _gradient[b11][k]; - double b = _lerp(sx, rx0 * qya[0] + ry1 * qya[1], - rx1 * qyb[0] + ry1 * qyb[1]); + double b = _lerp(sx, rx0 * qya[0] + ry1 * qya[1], rx1 * qyb[0] + ry1 * qyb[1]); result[k] = _lerp(sy, a, b); } @@ -190,41 +191,40 @@ public: y *= 2; ratio *= 2; - if(_stitchTiles) - { + if (_stitchTiles) { // Update stitch values. Subtracting PerlinOffset before the multiplication and // adding it afterward simplifies to subtracting it once. wrapw *= 2; wraph *= 2; - wrapx = wrapx*2 - PerlinOffset; - wrapy = wrapy*2 - PerlinOffset; + wrapx = wrapx * 2 - PerlinOffset; + wrapy = wrapy * 2 - PerlinOffset; } } if (_fractalnoise) { - guint32 r = CLAMP_D_TO_U8((pixel[0]*255.0 + 255.0) / 2); - guint32 g = CLAMP_D_TO_U8((pixel[1]*255.0 + 255.0) / 2); - guint32 b = CLAMP_D_TO_U8((pixel[2]*255.0 + 255.0) / 2); - guint32 a = CLAMP_D_TO_U8((pixel[3]*255.0 + 255.0) / 2); + guint32 r = CLAMP_D_TO_U8((pixel[0] * 255.0 + 255.0) / 2); + guint32 g = CLAMP_D_TO_U8((pixel[1] * 255.0 + 255.0) / 2); + guint32 b = CLAMP_D_TO_U8((pixel[2] * 255.0 + 255.0) / 2); + guint32 a = CLAMP_D_TO_U8((pixel[3] * 255.0 + 255.0) / 2); r = premul_alpha(r, a); g = premul_alpha(g, a); b = premul_alpha(b, a); - ASSEMBLE_ARGB32(pxout, a,r,g,b); + ASSEMBLE_ARGB32(pxout, a, r, g, b); return pxout; } else { - guint32 r = CLAMP_D_TO_U8(pixel[0]*255.0); - guint32 g = CLAMP_D_TO_U8(pixel[1]*255.0); - guint32 b = CLAMP_D_TO_U8(pixel[2]*255.0); - guint32 a = CLAMP_D_TO_U8(pixel[3]*255.0); + guint32 r = CLAMP_D_TO_U8(pixel[0] * 255.0); + guint32 g = CLAMP_D_TO_U8(pixel[1] * 255.0); + guint32 b = CLAMP_D_TO_U8(pixel[2] * 255.0); + guint32 a = CLAMP_D_TO_U8(pixel[3] * 255.0); r = premul_alpha(r, a); g = premul_alpha(g, a); b = premul_alpha(b, a); - ASSEMBLE_ARGB32(pxout, a,r,g,b); + ASSEMBLE_ARGB32(pxout, a, r, g, b); return pxout; } } - //G_GNUC_PURE + // G_GNUC_PURE /*guint32 turbulencePixel(Geom::Point const &p) const { if (!_fractalnoise) { guint32 r = CLAMP_D_TO_U8(turbulence(0, p)*255.0); @@ -253,12 +253,16 @@ public: void dirty() { _inited = false; } private: - void _setupSeed(long seed) { + void _setupSeed(long seed) + { _seed = seed; - if (_seed <= 0) _seed = -(_seed % (RAND_m - 1)) + 1; - if (_seed > RAND_m - 1) _seed = RAND_m - 1; + if (_seed <= 0) + _seed = -(_seed % (RAND_m - 1)) + 1; + if (_seed > RAND_m - 1) + _seed = RAND_m - 1; } - long _random() { + long _random() + { /* Produces results in the range [1, 2**31 - 2]. * Algorithm is: r = (a * r) mod m * where a = 16807 and m = 2**31 - 1 = 2147483647 @@ -266,22 +270,18 @@ private: * To test: the algorithm should produce the result 1043618065 * as the 10,000th generated number if the original seed is 1. */ _seed = RAND_a * (_seed % RAND_q) - RAND_r * (_seed / RAND_q); - if (_seed <= 0) _seed += RAND_m; + if (_seed <= 0) + _seed += RAND_m; return _seed; } - static inline double _scurve(double t) { - return t * t * (3.0 - 2.0*t); - } - static inline double _lerp(double t, double a, double b) { - return a + t * (b-a); - } + static inline double _scurve(double t) { return t * t * (3.0 - 2.0 * t); } + static inline double _lerp(double t, double a, double b) { return a + t * (b - a); } // random number generator constants - static long const - RAND_m = 2147483647, // 2**31 - 1 - RAND_a = 16807, // 7**5; primitive root of m - RAND_q = 127773, // m / a - RAND_r = 2836; // m % a + static long const RAND_m = 2147483647, // 2**31 - 1 + RAND_a = 16807, // 7**5; primitive root of m + RAND_q = 127773, // m / a + RAND_r = 2836; // m % a // other constants static int const BSize = 0x100; @@ -291,8 +291,8 @@ private: Geom::Rect _tile; Geom::Point _baseFreq; - int _latticeSelector[2*BSize + 2]; - double _gradient[2*BSize + 2][4][2]; + int _latticeSelector[2 * BSize + 2]; + double _gradient[2 * BSize + 2][4][2]; long _seed; int _octaves; bool _stitchTiles; @@ -311,14 +311,14 @@ FilterTurbulence::FilterTurbulence() , numOctaves(1) , seed(0) , updated(false) - , fTileWidth(10) //guessed - , fTileHeight(10) //guessed - , fTileX(1) //guessed - , fTileY(1) //guessed -{ -} + , fTileWidth(10) // guessed + , fTileHeight(10) // guessed + , fTileX(1) // guessed + , fTileY(1) // guessed +{} -FilterPrimitive * FilterTurbulence::create() { +FilterPrimitive *FilterTurbulence::create() +{ return new FilterTurbulence(); } @@ -327,47 +327,56 @@ FilterTurbulence::~FilterTurbulence() delete gen; } -void FilterTurbulence::set_baseFrequency(int axis, double freq){ - if (axis==0) XbaseFrequency=freq; - if (axis==1) YbaseFrequency=freq; +void FilterTurbulence::set_baseFrequency(int axis, double freq) +{ + if (axis == 0) + XbaseFrequency = freq; + if (axis == 1) + YbaseFrequency = freq; gen->dirty(); } -void FilterTurbulence::set_numOctaves(int num){ +void FilterTurbulence::set_numOctaves(int num) +{ numOctaves = num; gen->dirty(); } -void FilterTurbulence::set_seed(double s){ +void FilterTurbulence::set_seed(double s) +{ seed = s; gen->dirty(); } -void FilterTurbulence::set_stitchTiles(bool st){ +void FilterTurbulence::set_stitchTiles(bool st) +{ stitchTiles = st; gen->dirty(); } -void FilterTurbulence::set_type(FilterTurbulenceType t){ +void FilterTurbulence::set_type(FilterTurbulenceType t) +{ type = t; gen->dirty(); } -void FilterTurbulence::set_updated(bool /*u*/) -{ -} +void FilterTurbulence::set_updated(bool /*u*/) {} -struct Turbulence { +struct Turbulence +{ Turbulence(TurbulenceGenerator const &gen, Geom::Affine const &trans, int x0, int y0) : _gen(gen) , _trans(trans) - , _x0(x0), _y0(y0) + , _x0(x0) + , _y0(y0) {} - guint32 operator()(int x, int y) { + guint32 operator()(int x, int y) + { Geom::Point point(x + _x0, y + _y0); point *= _trans; return _gen.turbulencePixel(point); } + private: TurbulenceGenerator const &_gen; Geom::Affine _trans; @@ -387,22 +396,21 @@ void FilterTurbulence::render_cairo(FilterSlot &slot) double x_scale = 0; double y_scale = 0; cairo_surface_get_device_scale(input, &x_scale, &y_scale); - int width = ceil(cairo_image_surface_get_width( input)/x_scale/x_scale); - int height = ceil(cairo_image_surface_get_height(input)/y_scale/y_scale); - cairo_surface_t *temp = cairo_surface_create_similar (input, CAIRO_CONTENT_COLOR_ALPHA, width, height); - cairo_surface_set_device_scale( temp, 1, 1 ); + int width = ceil(cairo_image_surface_get_width(input) / x_scale / x_scale); + int height = ceil(cairo_image_surface_get_height(input) / y_scale / y_scale); + cairo_surface_t *temp = cairo_surface_create_similar(input, CAIRO_CONTENT_COLOR_ALPHA, width, height); + cairo_surface_set_device_scale(temp, 1, 1); // color_interpolation_filter is determined by CSS value (see spec. Turbulence). - if( _style ) { - set_cairo_surface_ci(out, (SPColorInterpolation)_style->color_interpolation_filters.computed ); + if (_style) { + set_cairo_surface_ci(out, (SPColorInterpolation)_style->color_interpolation_filters.computed); } if (!gen->ready()) { Geom::Point ta(fTileX, fTileY); Geom::Point tb(fTileX + fTileWidth, fTileY + fTileHeight); - gen->init(seed, Geom::Rect(ta, tb), - Geom::Point(XbaseFrequency, YbaseFrequency), stitchTiles, - type == TURBULENCE_FRACTALNOISE, numOctaves); + gen->init(seed, Geom::Rect(ta, tb), Geom::Point(XbaseFrequency, YbaseFrequency), stitchTiles, + type == TURBULENCE_FRACTALNOISE, numOctaves); } Geom::Affine unit_trans = slot.get_units().get_matrix_primitiveunits2pb().inverse(); diff --git a/src/display/nr-filter-turbulence.h b/src/display/nr-filter-turbulence.h index de21c5801e4cfde8f5955a53d3a458f4a9ec4ab4..1b40695884bab5c18c29d26374efb0d1bb777239 100644 --- a/src/display/nr-filter-turbulence.h +++ b/src/display/nr-filter-turbulence.h @@ -31,7 +31,8 @@ namespace Inkscape { namespace Filters { -enum FilterTurbulenceType { +enum FilterTurbulenceType +{ TURBULENCE_FRACTALNOISE, TURBULENCE_TURBULENCE, TURBULENCE_ENDTYPE @@ -39,7 +40,8 @@ enum FilterTurbulenceType { class TurbulenceGenerator; -class FilterTurbulence : public FilterPrimitive { +class FilterTurbulence : public FilterPrimitive +{ public: FilterTurbulence(); static FilterPrimitive *create(); @@ -59,7 +61,6 @@ public: Glib::ustring name() override { return Glib::ustring("Turbulence"); } private: - TurbulenceGenerator *gen; void turbulenceInit(long seed); @@ -77,7 +78,6 @@ private: double fTileX; double fTileY; - }; } /* namespace Filters */ diff --git a/src/display/nr-filter-types.h b/src/display/nr-filter-types.h index 34cfdeb848c61688bb345f054d8626972e97b3e3..34ebc9f9cc33ca1aaa4cb862ead113a388c87666 100644 --- a/src/display/nr-filter-types.h +++ b/src/display/nr-filter-types.h @@ -13,7 +13,8 @@ namespace Inkscape { namespace Filters { -enum FilterPrimitiveType { +enum FilterPrimitiveType +{ NR_FILTER_BLEND, NR_FILTER_COLORMATRIX, NR_FILTER_COMPONENTTRANSFER, @@ -32,9 +33,10 @@ enum FilterPrimitiveType { NR_FILTER_TURBULENCE, NR_FILTER_ENDPRIMITIVETYPE // This must be last }; -//const int Filter::_filter_primitive_type_count = 16; +// const int Filter::_filter_primitive_type_count = 16; -enum FilterSlotType { +enum FilterSlotType +{ NR_FILTER_SLOT_NOT_SET = -1, NR_FILTER_SOURCEGRAPHIC = -2, NR_FILTER_SOURCEALPHA = -3, @@ -47,7 +49,8 @@ enum FilterSlotType { /* Unnamed slot is for Inkscape::Filters::FilterSlot internal use. Passing it as * parameter to Inkscape::Filters::FilterSlot accessors may have unforeseen consequences. */ -enum FilterQuality { +enum FilterQuality +{ FILTER_QUALITY_BEST = 2, FILTER_QUALITY_BETTER = 1, FILTER_QUALITY_NORMAL = 0, diff --git a/src/display/nr-filter-units.cpp b/src/display/nr-filter-units.cpp index 7fdf936d60428cdead5f11370a6a798f613f62c9..adee43eb42facbe5a12995b5a4c5f2fc9970dcbf 100644 --- a/src/display/nr-filter-units.cpp +++ b/src/display/nr-filter-units.cpp @@ -10,11 +10,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/nr-filter-units.h" + +#include <2geom/transforms.h> #include -#include "display/nr-filter-units.h" #include "object/sp-filter-units.h" -#include <2geom/transforms.h> using Geom::X; using Geom::Y; @@ -22,24 +23,31 @@ using Geom::Y; namespace Inkscape { namespace Filters { -FilterUnits::FilterUnits() : - filterUnits(SP_FILTER_UNITS_OBJECTBOUNDINGBOX), - primitiveUnits(SP_FILTER_UNITS_USERSPACEONUSE), - resolution_x(-1), resolution_y(-1), - paraller_axis(false), automatic_resolution(true) +FilterUnits::FilterUnits() + : filterUnits(SP_FILTER_UNITS_OBJECTBOUNDINGBOX) + , primitiveUnits(SP_FILTER_UNITS_USERSPACEONUSE) + , resolution_x(-1) + , resolution_y(-1) + , paraller_axis(false) + , automatic_resolution(true) {} -FilterUnits::FilterUnits(SPFilterUnits const filterUnits, SPFilterUnits const primitiveUnits) : - filterUnits(filterUnits), primitiveUnits(primitiveUnits), - resolution_x(-1), resolution_y(-1), - paraller_axis(false), automatic_resolution(true) +FilterUnits::FilterUnits(SPFilterUnits const filterUnits, SPFilterUnits const primitiveUnits) + : filterUnits(filterUnits) + , primitiveUnits(primitiveUnits) + , resolution_x(-1) + , resolution_y(-1) + , paraller_axis(false) + , automatic_resolution(true) {} -void FilterUnits::set_ctm(Geom::Affine const &ctm) { +void FilterUnits::set_ctm(Geom::Affine const &ctm) +{ this->ctm = ctm; } -void FilterUnits::set_resolution(double const x_res, double const y_res) { +void FilterUnits::set_resolution(double const x_res, double const y_res) +{ g_assert(x_res > 0); g_assert(y_res > 0); @@ -47,23 +55,28 @@ void FilterUnits::set_resolution(double const x_res, double const y_res) { resolution_y = y_res; } -void FilterUnits::set_item_bbox(Geom::OptRect const &bbox) { +void FilterUnits::set_item_bbox(Geom::OptRect const &bbox) +{ item_bbox = bbox; } -void FilterUnits::set_filter_area(Geom::OptRect const &area) { +void FilterUnits::set_filter_area(Geom::OptRect const &area) +{ filter_area = area; } -void FilterUnits::set_paraller(bool const paraller) { +void FilterUnits::set_paraller(bool const paraller) +{ paraller_axis = paraller; } -void FilterUnits::set_automatic_resolution(bool const automatic) { +void FilterUnits::set_automatic_resolution(bool const automatic) +{ automatic_resolution = automatic; } -Geom::Affine FilterUnits::get_matrix_user2pb() const { +Geom::Affine FilterUnits::get_matrix_user2pb() const +{ g_assert(resolution_x > 0); g_assert(resolution_y > 0); g_assert(filter_area); @@ -82,9 +95,9 @@ Geom::Affine FilterUnits::get_matrix_user2pb() const { return u2pb; } -Geom::Affine FilterUnits::get_matrix_units2pb(SPFilterUnits units) const { - if ( item_bbox && (units == SP_FILTER_UNITS_OBJECTBOUNDINGBOX) ) { - +Geom::Affine FilterUnits::get_matrix_units2pb(SPFilterUnits units) const +{ + if (item_bbox && (units == SP_FILTER_UNITS_OBJECTBOUNDINGBOX)) { Geom::Affine u2pb = get_matrix_user2pb(); /* TODO: make sure that user coordinate system (0,0) is in correct @@ -101,27 +114,32 @@ Geom::Affine FilterUnits::get_matrix_units2pb(SPFilterUnits units) const { } } -Geom::Affine FilterUnits::get_matrix_filterunits2pb() const { +Geom::Affine FilterUnits::get_matrix_filterunits2pb() const +{ return get_matrix_units2pb(filterUnits); } -Geom::Affine FilterUnits::get_matrix_primitiveunits2pb() const { +Geom::Affine FilterUnits::get_matrix_primitiveunits2pb() const +{ return get_matrix_units2pb(primitiveUnits); } -Geom::Affine FilterUnits::get_matrix_display2pb() const { +Geom::Affine FilterUnits::get_matrix_display2pb() const +{ Geom::Affine d2pb = ctm.inverse(); d2pb *= get_matrix_user2pb(); return d2pb; } -Geom::Affine FilterUnits::get_matrix_pb2display() const { +Geom::Affine FilterUnits::get_matrix_pb2display() const +{ Geom::Affine pb2d = get_matrix_user2pb().inverse(); pb2d *= ctm; return pb2d; } -Geom::Affine FilterUnits::get_matrix_user2units(SPFilterUnits units) const { +Geom::Affine FilterUnits::get_matrix_user2units(SPFilterUnits units) const +{ if (item_bbox && units == SP_FILTER_UNITS_OBJECTBOUNDINGBOX) { /* No need to worry about rotations: bounding box coordinates * always have base vectors paraller with userspace coordinates */ @@ -129,10 +147,8 @@ Geom::Affine FilterUnits::get_matrix_user2units(SPFilterUnits units) const { Geom::Point max(item_bbox->max()); double scale_x = 1.0 / (max[X] - min[X]); double scale_y = 1.0 / (max[Y] - min[Y]); - //return Geom::Translate(min) * Geom::Scale(scale_x,scale_y); ? - return Geom::Affine(scale_x, 0, - 0, scale_y, - min[X] * scale_x, min[Y] * scale_y); + // return Geom::Translate(min) * Geom::Scale(scale_x,scale_y); ? + return Geom::Affine(scale_x, 0, 0, scale_y, min[X] * scale_x, min[Y] * scale_y); } else if (units == SP_FILTER_UNITS_USERSPACEONUSE) { return Geom::identity(); } else { @@ -141,15 +157,18 @@ Geom::Affine FilterUnits::get_matrix_user2units(SPFilterUnits units) const { } } -Geom::Affine FilterUnits::get_matrix_user2filterunits() const { +Geom::Affine FilterUnits::get_matrix_user2filterunits() const +{ return get_matrix_user2units(filterUnits); } -Geom::Affine FilterUnits::get_matrix_user2primitiveunits() const { +Geom::Affine FilterUnits::get_matrix_user2primitiveunits() const +{ return get_matrix_user2units(primitiveUnits); } -Geom::IntRect FilterUnits::get_pixblock_filterarea_paraller() const { +Geom::IntRect FilterUnits::get_pixblock_filterarea_paraller() const +{ g_assert(filter_area); Geom::Affine u2pb = get_matrix_user2pb(); @@ -158,12 +177,11 @@ Geom::IntRect FilterUnits::get_pixblock_filterarea_paraller() const { return ir; } -FilterUnits& FilterUnits::operator=(FilterUnits const &other) = default; +FilterUnits &FilterUnits::operator=(FilterUnits const &other) = default; } /* namespace Filters */ } /* namespace Inkscape */ - /* Local Variables: mode:c++ diff --git a/src/display/nr-filter-units.h b/src/display/nr-filter-units.h index 432e6817323a134feb56affdeb326d6eaa9a4781..5257716f9cd7d48513a7c52795494b2d3ff20a7e 100644 --- a/src/display/nr-filter-units.h +++ b/src/display/nr-filter-units.h @@ -13,10 +13,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "object/sp-filter-units.h" #include <2geom/affine.h> #include <2geom/rect.h> +#include "object/sp-filter-units.h" + namespace Inkscape { namespace Filters { @@ -32,7 +33,8 @@ namespace Filters { * - "display" are world coordinates of the canvas - pixel grid coordinates * of the drawing area translated so that (0,0) corresponds to the document origin */ -class FilterUnits { +class FilterUnits +{ public: FilterUnits(); FilterUnits(SPFilterUnits const filterUnits, SPFilterUnits const primitiveUnits); @@ -135,7 +137,7 @@ public: * by simple rectangle otherwise. */ Geom::IntRect get_pixblock_filterarea_paraller() const; - FilterUnits& operator=(FilterUnits const &other); + FilterUnits &operator=(FilterUnits const &other); private: Geom::Affine get_matrix_units2pb(SPFilterUnits units) const; @@ -148,14 +150,11 @@ private: Geom::Affine ctm; Geom::OptRect item_bbox; Geom::OptRect filter_area; - }; - } /* namespace Filters */ } /* namespace Inkscape */ - #endif /* __NR_FILTER_UNITS_H__ */ /* Local Variables: diff --git a/src/display/nr-filter-utils.h b/src/display/nr-filter-utils.h index 0e7612dee9a178bcd08883ce6b51eefec13873d2..f34886296b504c21677148c18b017d7af0178a88 100644 --- a/src/display/nr-filter-utils.h +++ b/src/display/nr-filter-utils.h @@ -25,9 +25,12 @@ namespace Filters { * \return 0 if the value is smaller than 0, 255 if it is greater 255, else v * \param v the value to clamp */ -inline int clamp(int const val) { - if (val < 0) return 0; - if (val > 255) return 255; +inline int clamp(int const val) +{ + if (val < 0) + return 0; + if (val > 255) + return 255; return val; } @@ -37,16 +40,19 @@ inline int clamp(int const val) { * \return 0 if the value is smaller than 0, 255^3 (16581375) if it is greater than 255^3, else v * \param v the value to clamp */ -inline int clamp3(int const val) { - if (val < 0) return 0; - if (val > 16581375) return 16581375; +inline int clamp3(int const val) +{ + if (val < 0) + return 0; + if (val > 16581375) + return 16581375; return val; } /** * Macro to use the clamp function with double inputs and unsigned char output */ -#define CLAMP_D_TO_U8(v) (unsigned char) clamp((int)round((v))) +#define CLAMP_D_TO_U8(v) (unsigned char)clamp((int)round((v))) /** * Clamps an integer to a value between 0 and alpha. Useful when handling @@ -56,16 +62,19 @@ inline int clamp3(int const val) { * \param val the value to clamp * \param alpha the maximum value to clamp to */ -inline int clamp_alpha(int const val, int const alpha) { - if (val < 0) return 0; - if (val > alpha) return alpha; +inline int clamp_alpha(int const val, int const alpha) +{ + if (val < 0) + return 0; + if (val > alpha) + return alpha; return val; } /** * Macro to use the clamp function with double inputs and unsigned char output */ -#define CLAMP_D_TO_U8_ALPHA(v,a) (unsigned char) clamp_alpha((int)round((v)),(a)) +#define CLAMP_D_TO_U8_ALPHA(v, a) (unsigned char)clamp_alpha((int)round((v)), (a)) } /* namespace Filters */ } /* namespace Inkscape */ diff --git a/src/display/nr-filter.cpp b/src/display/nr-filter.cpp index eec7c1aa6d3e64dbcc245b709538b86198d0beba..eb6b392fbcae44bc60107b83b2378629054046b1 100644 --- a/src/display/nr-filter.cpp +++ b/src/display/nr-filter.cpp @@ -10,42 +10,41 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "display/nr-filter.h" + +#include <2geom/affine.h> +#include <2geom/rect.h> +#include #include #include +#include #include -#include - -#include "display/nr-filter.h" -#include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-types.h" -#include "display/nr-filter-units.h" +#include "display/cairo-utils.h" +#include "display/drawing-context.h" +#include "display/drawing-item.h" +#include "display/drawing-surface.h" +#include "display/drawing.h" #include "display/nr-filter-blend.h" -#include "display/nr-filter-composite.h" -#include "display/nr-filter-convolve-matrix.h" #include "display/nr-filter-colormatrix.h" #include "display/nr-filter-component-transfer.h" +#include "display/nr-filter-composite.h" +#include "display/nr-filter-convolve-matrix.h" #include "display/nr-filter-diffuselighting.h" #include "display/nr-filter-displacement-map.h" -#include "display/nr-filter-image.h" #include "display/nr-filter-flood.h" #include "display/nr-filter-gaussian.h" +#include "display/nr-filter-image.h" #include "display/nr-filter-merge.h" #include "display/nr-filter-morphology.h" #include "display/nr-filter-offset.h" +#include "display/nr-filter-primitive.h" +#include "display/nr-filter-slot.h" #include "display/nr-filter-specularlighting.h" #include "display/nr-filter-tile.h" #include "display/nr-filter-turbulence.h" - -#include "display/cairo-utils.h" -#include "display/drawing.h" -#include "display/drawing-item.h" -#include "display/drawing-context.h" -#include "display/drawing-surface.h" -#include <2geom/affine.h> -#include <2geom/rect.h> +#include "display/nr-filter-types.h" +#include "display/nr-filter-units.h" #include "svg/svg-length.h" //#include "sp-filter-units.h" #include "preferences.h" @@ -63,11 +62,13 @@ Filter::Filter() Filter::Filter(int n) { - if (n > 0) _primitive.reserve(n); + if (n > 0) + _primitive.reserve(n); _common_init(); } -void Filter::_common_init() { +void Filter::_common_init() +{ _slot_count = 1; // Having "not set" here as value means the output of last filter // primitive will be used as output of this filter @@ -94,7 +95,6 @@ Filter::~Filter() clear_primitives(); } - int Filter::render(Inkscape::DrawingItem const *item, DrawingContext &graphic, DrawingContext *bgdc) { // std::cout << "Filter::render() for: " << const_cast(item)->name() << std::endl; @@ -102,7 +102,7 @@ int Filter::render(Inkscape::DrawingItem const *item, DrawingContext &graphic, D if (_primitive.empty()) { // when no primitives are defined, clear source graphic - graphic.setSource(0,0,0,0); + graphic.setSource(0, 0, 0, 0); graphic.setOperator(CAIRO_OPERATOR_SOURCE); graphic.paint(); graphic.setOperator(CAIRO_OPERATOR_OVER); @@ -117,18 +117,18 @@ int Filter::render(Inkscape::DrawingItem const *item, DrawingContext &graphic, D Geom::Affine trans = item->ctm(); Geom::OptRect filter_area = filter_effect_area(item->itemBounds()); - if (!filter_area) return 1; + if (!filter_area) + return 1; FilterUnits units(_filter_units, _primitive_units); units.set_ctm(trans); units.set_item_bbox(item->itemBounds()); units.set_filter_area(*filter_area); - std::pair resolution - = _filter_resolution(*filter_area, trans, filterquality); + std::pair resolution = _filter_resolution(*filter_area, trans, filterquality); if (!(resolution.first > 0 && resolution.second > 0)) { // zero resolution - clear source graphic and return - graphic.setSource(0,0,0,0); + graphic.setSource(0, 0, 0, 0); graphic.setOperator(CAIRO_OPERATOR_SOURCE); graphic.paint(); graphic.setOperator(CAIRO_OPERATOR_OVER); @@ -138,26 +138,25 @@ int Filter::render(Inkscape::DrawingItem const *item, DrawingContext &graphic, D units.set_resolution(resolution.first, resolution.second); if (_x_pixels > 0) { units.set_automatic_resolution(false); - } - else { + } else { units.set_automatic_resolution(true); } units.set_paraller(false); Geom::Affine pbtrans = units.get_matrix_display2pb(); - for (auto & i : _primitive) { + for (auto &i : _primitive) { if (!i->can_handle_affine(pbtrans)) { units.set_paraller(true); break; } } - FilterSlot slot(const_cast(item), bgdc, graphic, units); + FilterSlot slot(const_cast(item), bgdc, graphic, units); slot.set_quality(filterquality); slot.set_blurquality(blurquality); slot.set_device_scale(graphic.surface()->device_scale()); - for (auto & i : _primitive) { + for (auto &i : _primitive) { i->render_cairo(slot); } @@ -165,7 +164,7 @@ int Filter::render(Inkscape::DrawingItem const *item, DrawingContext &graphic, D cairo_surface_t *result = slot.get_result(_output_slot); // Assume for the moment that we paint the filter in sRGB - set_cairo_surface_ci( result, SP_CSS_COLOR_INTERPOLATION_SRGB ); + set_cairo_surface_ci(result, SP_CSS_COLOR_INTERPOLATION_SRGB); graphic.setSource(result, origin[Geom::X], origin[Geom::Y]); graphic.setOperator(CAIRO_OPERATOR_SOURCE); @@ -176,50 +175,54 @@ int Filter::render(Inkscape::DrawingItem const *item, DrawingContext &graphic, D return 0; } -void Filter::set_filter_units(SPFilterUnits unit) { +void Filter::set_filter_units(SPFilterUnits unit) +{ _filter_units = unit; } -void Filter::set_primitive_units(SPFilterUnits unit) { +void Filter::set_primitive_units(SPFilterUnits unit) +{ _primitive_units = unit; } -void Filter::area_enlarge(Geom::IntRect &bbox, Inkscape::DrawingItem const *item) const { +void Filter::area_enlarge(Geom::IntRect &bbox, Inkscape::DrawingItem const *item) const +{ for (auto i : _primitive) { - if (i) i->area_enlarge(bbox, item->ctm()); + if (i) + i->area_enlarge(bbox, item->ctm()); } -/* - TODO: something. See images at the bottom of filters.svg with medium-low - filtering quality. + /* + TODO: something. See images at the bottom of filters.svg with medium-low + filtering quality. - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - FilterQuality const filterquality = (FilterQuality)prefs->getInt("/options/filterquality/value"); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + FilterQuality const filterquality = (FilterQuality)prefs->getInt("/options/filterquality/value"); - if (_x_pixels <= 0 && (filterquality == FILTER_QUALITY_BEST || - filterquality == FILTER_QUALITY_BETTER)) { - return; - } + if (_x_pixels <= 0 && (filterquality == FILTER_QUALITY_BEST || + filterquality == FILTER_QUALITY_BETTER)) { + return; + } - Geom::Rect item_bbox; - Geom::OptRect maybe_bbox = item->itemBounds(); - if (maybe_bbox.empty()) { - // Code below needs a bounding box - return; - } - item_bbox = *maybe_bbox; - - std::pair res_low - = _filter_resolution(item_bbox, item->ctm(), filterquality); - //std::pair res_full - // = _filter_resolution(item_bbox, item->ctm(), FILTER_QUALITY_BEST); - double pixels_per_block = fmax(item_bbox.width() / res_low.first, - item_bbox.height() / res_low.second); - bbox.x0 -= (int)pixels_per_block; - bbox.x1 += (int)pixels_per_block; - bbox.y0 -= (int)pixels_per_block; - bbox.y1 += (int)pixels_per_block; -*/ + Geom::Rect item_bbox; + Geom::OptRect maybe_bbox = item->itemBounds(); + if (maybe_bbox.empty()) { + // Code below needs a bounding box + return; + } + item_bbox = *maybe_bbox; + + std::pair res_low + = _filter_resolution(item_bbox, item->ctm(), filterquality); + //std::pair res_full + // = _filter_resolution(item_bbox, item->ctm(), FILTER_QUALITY_BEST); + double pixels_per_block = fmax(item_bbox.width() / res_low.first, + item_bbox.height() / res_low.second); + bbox.x0 -= (int)pixels_per_block; + bbox.x1 += (int)pixels_per_block; + bbox.y0 -= (int)pixels_per_block; + bbox.y1 += (int)pixels_per_block; + */ } Geom::OptRect Filter::filter_effect_area(Geom::OptRect const &bbox) @@ -227,7 +230,6 @@ Geom::OptRect Filter::filter_effect_area(Geom::OptRect const &bbox) Geom::Point minp, maxp; if (_filter_units == SP_FILTER_UNITS_OBJECTBOUNDINGBOX) { - double len_x = bbox ? bbox->width() : 0; double len_y = bbox ? bbox->height() : 0; /* TODO: fetch somehow the object ex and em lengths */ @@ -238,7 +240,8 @@ Geom::OptRect Filter::filter_effect_area(Geom::OptRect const &bbox) _region_width.update(12, 6, len_x); _region_height.update(12, 6, len_y); - if (!bbox) return Geom::OptRect(); + if (!bbox) + return Geom::OptRect(); if (_region_x.unit == SVGLength::PERCENT) { minp[X] = bbox->left() + _region_x.computed; @@ -279,7 +282,7 @@ Geom::OptRect Filter::filter_effect_area(Geom::OptRect const &bbox) double Filter::complexity(Geom::Affine const &ctm) { double factor = 1.0; - for (auto & i : _primitive) { + for (auto &i : _primitive) { if (i) { double f = i->complexity(ctm); factor += (f - 1.0); @@ -290,7 +293,7 @@ double Filter::complexity(Geom::Affine const &ctm) bool Filter::uses_background() { - for (auto & i : _primitive) { + for (auto &i : _primitive) { if (i && i->uses_background()) { return true; } @@ -303,17 +306,18 @@ bool Filter::uses_background() * for example method in _constructor[NR_FILTER_GAUSSIANBLUR] * returns a filter object of type Inkscape::Filters::FilterGaussian. */ -typedef FilterPrimitive*(*FilterConstructor)(); +typedef FilterPrimitive *(*FilterConstructor)(); static FilterConstructor _constructor[NR_FILTER_ENDPRIMITIVETYPE]; void Filter::_create_constructor_table() { // Constructor table won't change in run-time, so no need to recreate static bool created = false; - if(created) return; + if (created) + return; -/* Some filter classes are not implemented yet. - Some of them still have only boilerplate code.*/ + /* Some filter classes are not implemented yet. + Some of them still have only boilerplate code.*/ _constructor[NR_FILTER_BLEND] = &FilterBlend::create; _constructor[NR_FILTER_COLORMATRIX] = &FilterColorMatrix::create; _constructor[NR_FILTER_COMPONENTTRANSFER] = &FilterComponentTransfer::create; @@ -340,7 +344,8 @@ int Filter::add_primitive(FilterPrimitiveType type) // Check that we can create a new filter of specified type if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE) return -1; - if (!_constructor[type]) return -1; + if (!_constructor[type]) + return -1; FilterPrimitive *created = _constructor[type](); int handle = _primitive.size(); @@ -353,13 +358,16 @@ int Filter::replace_primitive(int target, FilterPrimitiveType type) _create_constructor_table(); // Check that target is valid primitive inside this filter - if (target < 0) return -1; - if (static_cast(target) >= _primitive.size()) return -1; + if (target < 0) + return -1; + if (static_cast(target) >= _primitive.size()) + return -1; // Check that we can create a new filter of specified type if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE) return -1; - if (!_constructor[type]) return -1; + if (!_constructor[type]) + return -1; FilterPrimitive *created = _constructor[type](); delete _primitive[target]; @@ -367,14 +375,16 @@ int Filter::replace_primitive(int target, FilterPrimitiveType type) return target; } -FilterPrimitive *Filter::get_primitive(int handle) { - if (handle < 0 || handle >= static_cast(_primitive.size())) return nullptr; +FilterPrimitive *Filter::get_primitive(int handle) +{ + if (handle < 0 || handle >= static_cast(_primitive.size())) + return nullptr; return _primitive[handle]; } void Filter::clear_primitives() { - for (auto & i : _primitive) { + for (auto &i : _primitive) { delete i; } _primitive.clear(); @@ -382,45 +392,49 @@ void Filter::clear_primitives() void Filter::set_x(SVGLength const &length) { - if (length._set) - _region_x = length; + if (length._set) + _region_x = length; } void Filter::set_y(SVGLength const &length) { - if (length._set) - _region_y = length; + if (length._set) + _region_y = length; } void Filter::set_width(SVGLength const &length) { - if (length._set) - _region_width = length; + if (length._set) + _region_width = length; } void Filter::set_height(SVGLength const &length) { - if (length._set) - _region_height = length; + if (length._set) + _region_height = length; } -void Filter::set_resolution(double const pixels) { +void Filter::set_resolution(double const pixels) +{ if (pixels > 0) { _x_pixels = pixels; _y_pixels = pixels; } } -void Filter::set_resolution(double const x_pixels, double const y_pixels) { +void Filter::set_resolution(double const x_pixels, double const y_pixels) +{ if (x_pixels >= 0 && y_pixels >= 0) { _x_pixels = x_pixels; _y_pixels = y_pixels; } } -void Filter::reset_resolution() { +void Filter::reset_resolution() +{ _x_pixels = -1; _y_pixels = -1; } -int Filter::_resolution_limit(FilterQuality const quality) const { +int Filter::_resolution_limit(FilterQuality const quality) const +{ int limit = -1; switch (quality) { case FILTER_QUALITY_WORST: @@ -440,18 +454,16 @@ int Filter::_resolution_limit(FilterQuality const quality) const { return limit; } -std::pair Filter::_filter_resolution( - Geom::Rect const &area, Geom::Affine const &trans, - FilterQuality const filterquality) const +std::pair Filter::_filter_resolution(Geom::Rect const &area, Geom::Affine const &trans, + FilterQuality const filterquality) const { - std::pair resolution; + std::pair resolution; if (_x_pixels > 0) { double y_len; if (_y_pixels > 0) { y_len = _y_pixels; } else { - y_len = (_x_pixels * (area.max()[Y] - area.min()[Y])) - / (area.max()[X] - area.min()[X]); + y_len = (_x_pixels * (area.max()[Y] - area.min()[Y])) / (area.max()[X] - area.min()[X]); } resolution.first = _x_pixels; resolution.second = y_len; @@ -462,18 +474,17 @@ std::pair Filter::_filter_resolution( max_i *= trans; Geom::Point max_j(area.min()[X], area.max()[Y]); max_j *= trans; - double i_len = sqrt((origo[X] - max_i[X]) * (origo[X] - max_i[X]) - + (origo[Y] - max_i[Y]) * (origo[Y] - max_i[Y])); - double j_len = sqrt((origo[X] - max_j[X]) * (origo[X] - max_j[X]) - + (origo[Y] - max_j[Y]) * (origo[Y] - max_j[Y])); + double i_len = + sqrt((origo[X] - max_i[X]) * (origo[X] - max_i[X]) + (origo[Y] - max_i[Y]) * (origo[Y] - max_i[Y])); + double j_len = + sqrt((origo[X] - max_j[X]) * (origo[X] - max_j[X]) + (origo[Y] - max_j[Y]) * (origo[Y] - max_j[Y])); int limit = _resolution_limit(filterquality); if (limit > 0 && (i_len > limit || j_len > limit)) { double aspect_ratio = i_len / j_len; if (i_len > j_len) { i_len = limit; j_len = i_len / aspect_ratio; - } - else { + } else { j_len = limit; i_len = j_len * aspect_ratio; } diff --git a/src/display/nr-filter.h b/src/display/nr-filter.h index caa718897c42a0bb258b2ab17125f5d9b817eab4..ae1a664983a8f13799b5304a7ecca67fb18d12b4 100644 --- a/src/display/nr-filter.h +++ b/src/display/nr-filter.h @@ -15,11 +15,12 @@ //#include "display/nr-arena-item.h" #include + #include "display/nr-filter-primitive.h" #include "display/nr-filter-types.h" -#include "svg/svg-length.h" -#include "object/sp-filter-units.h" #include "inkgc/gc-managed.h" +#include "object/sp-filter-units.h" +#include "svg/svg-length.h" namespace Inkscape { class DrawingContext; @@ -27,7 +28,8 @@ class DrawingItem; namespace Filters { -class Filter { +class Filter +{ public: /** Given background state from @a bgdc and an intermediate rendering from the surface * backing @a graphic, modify the contents of the surface backing @a graphic to represent @@ -97,8 +99,7 @@ public: * If any of these parameters does not get set, the default value, as * defined in SVG standard, for that parameter is used instead. */ - void set_region(SVGLength const &x, SVGLength const &y, - SVGLength const &width, SVGLength const &height); + void set_region(SVGLength const &x, SVGLength const &y, SVGLength const &width, SVGLength const &height); /** * Resets the filter effects region to its default value as defined @@ -128,7 +129,7 @@ public: void reset_resolution(); /** - * Set the filterUnits-property. If not set, the default value of + * Set the filterUnits-property. If not set, the default value of * objectBoundingBox is used. If the parameter value is not a * valid enumeration value from SPFilterUnits, no changes to filter state * are made. @@ -143,7 +144,7 @@ public: */ void set_primitive_units(SPFilterUnits unit); - /** + /** * Modifies the given area to accommodate for filters needing pixels * outside the rendered area. * When this function returns, area contains the area that needs @@ -166,7 +167,7 @@ public: /** Creates a new filter with space for one filter element */ Filter(); - /** + /** * Creates a new filter with space for n filter elements. If number of * filter elements is known beforehand, it's better to use this * constructor. @@ -176,7 +177,7 @@ public: virtual ~Filter(); private: - std::vector _primitive; + std::vector _primitive; /** Amount of image slots used, when this filter was rendered last time */ int _slot_count; @@ -201,16 +202,13 @@ private: void _create_constructor_table(); void _common_init(); int _resolution_limit(FilterQuality const quality) const; - std::pair _filter_resolution(Geom::Rect const &area, - Geom::Affine const &trans, - FilterQuality const q) const; + std::pair _filter_resolution(Geom::Rect const &area, Geom::Affine const &trans, + FilterQuality const q) const; }; - } /* namespace Filters */ } /* namespace Inkscape */ - #endif /* __NR_FILTER_H__ */ /* Local Variables: diff --git a/src/display/nr-light-types.h b/src/display/nr-light-types.h index 8de142f7cad6191657135c5c85a1a2c1d793861f..bfd0a18ad4366e4f680a319528a079ab62ab14c5 100644 --- a/src/display/nr-light-types.h +++ b/src/display/nr-light-types.h @@ -13,7 +13,8 @@ namespace Inkscape { namespace Filters { -enum LightType{ +enum LightType +{ NO_LIGHT = 0, DISTANT_LIGHT, POINT_LIGHT, diff --git a/src/display/nr-light.cpp b/src/display/nr-light.cpp index 300995570c33e26c1e9eac913b43dcde3d0f9f09..3a3a67ff9eaed3fbdea8874513fd2fb534f8e852 100644 --- a/src/display/nr-light.cpp +++ b/src/display/nr-light.cpp @@ -10,19 +10,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "display/nr-light.h" + #include -#include "display/nr-light.h" +#include "color.h" #include "display/nr-3dutils.h" #include "object/filters/distantlight.h" #include "object/filters/pointlight.h" #include "object/filters/spotlight.h" -#include "color.h" namespace Inkscape { namespace Filters { - -DistantLight::DistantLight(SPFeDistantLight *light, guint32 lighting_color) { + +DistantLight::DistantLight(SPFeDistantLight *light, guint32 lighting_color) +{ color = lighting_color; azimuth = M_PI / 180 * light->azimuth; elevation = M_PI / 180 * light->elevation; @@ -30,19 +32,22 @@ DistantLight::DistantLight(SPFeDistantLight *light, guint32 lighting_color) { DistantLight::~DistantLight() = default; -void DistantLight::light_vector(NR::Fvector &v) { - v[X_3D] = std::cos(azimuth)*std::cos(elevation); - v[Y_3D] = std::sin(azimuth)*std::cos(elevation); +void DistantLight::light_vector(NR::Fvector &v) +{ + v[X_3D] = std::cos(azimuth) * std::cos(elevation); + v[Y_3D] = std::sin(azimuth) * std::cos(elevation); v[Z_3D] = std::sin(elevation); -} +} -void DistantLight::light_components(NR::Fvector &lc) { +void DistantLight::light_components(NR::Fvector &lc) +{ lc[LIGHT_RED] = SP_RGBA32_R_U(color); lc[LIGHT_GREEN] = SP_RGBA32_G_U(color); lc[LIGHT_BLUE] = SP_RGBA32_B_U(color); } -PointLight::PointLight(SPFePointLight *light, guint32 lighting_color, const Geom::Affine &trans, int device_scale) { +PointLight::PointLight(SPFePointLight *light, guint32 lighting_color, const Geom::Affine &trans, int device_scale) +{ color = lighting_color; l_x = light->x * device_scale; l_y = light->y * device_scale; @@ -52,20 +57,23 @@ PointLight::PointLight(SPFePointLight *light, guint32 lighting_color, const Geom PointLight::~PointLight() = default; -void PointLight::light_vector(NR::Fvector &v, double x, double y, double z) { +void PointLight::light_vector(NR::Fvector &v, double x, double y, double z) +{ v[X_3D] = l_x - x; v[Y_3D] = l_y - y; v[Z_3D] = l_z - z; NR::normalize_vector(v); -} +} -void PointLight::light_components(NR::Fvector &lc) { +void PointLight::light_components(NR::Fvector &lc) +{ lc[LIGHT_RED] = SP_RGBA32_R_U(color); lc[LIGHT_GREEN] = SP_RGBA32_G_U(color); lc[LIGHT_BLUE] = SP_RGBA32_B_U(color); } -SpotLight::SpotLight(SPFeSpotLight *light, guint32 lighting_color, const Geom::Affine &trans, int device_scale) { +SpotLight::SpotLight(SPFeSpotLight *light, guint32 lighting_color, const Geom::Affine &trans, int device_scale) +{ double p_x, p_y, p_z; color = lighting_color; l_x = light->x * device_scale; @@ -82,19 +90,20 @@ SpotLight::SpotLight(SPFeSpotLight *light, guint32 lighting_color, const Geom::A S[Y_3D] = p_y - l_y; S[Z_3D] = p_z - l_z; NR::normalize_vector(S); - } SpotLight::~SpotLight() = default; -void SpotLight::light_vector(NR::Fvector &v, double x, double y, double z) { +void SpotLight::light_vector(NR::Fvector &v, double x, double y, double z) +{ v[X_3D] = l_x - x; v[Y_3D] = l_y - y; v[Z_3D] = l_z - z; NR::normalize_vector(v); -} +} -void SpotLight::light_components(NR::Fvector &lc, const NR::Fvector &L) { +void SpotLight::light_components(NR::Fvector &lc, const NR::Fvector &L) +{ double spmod = (-1) * NR::scalar_product(L, S); if (spmod <= cos_lca) spmod = 0; diff --git a/src/display/nr-light.h b/src/display/nr-light.h index ae119ce404356282064e76182d4977da5505f208..d0a007e079c174256b106222a938eb3f45b86f80 100644 --- a/src/display/nr-light.h +++ b/src/display/nr-light.h @@ -31,133 +31,136 @@ typedef unsigned int guint32; namespace Inkscape { namespace Filters { -enum LightComponent { +enum LightComponent +{ LIGHT_RED = 0, LIGHT_GREEN, LIGHT_BLUE }; -class DistantLight { - public: - /** - * Constructor - * - * \param light the sp light object - * \param lighting_color the lighting_color used - */ - DistantLight(SPFeDistantLight *light, guint32 lighting_color); - virtual ~DistantLight(); - - /** - * Computes the light vector of the distant light - * - * \param v a Fvector reference where we store the result - */ - void light_vector(NR::Fvector &v); - - /** - * Computes the light components of the distant light - * - * \param lc a Fvector reference where we store the result, X=R, Y=G, Z=B - */ - void light_components(NR::Fvector &lc); - - private: - guint32 color; - double azimuth; //azimuth in rad - double elevation; //elevation in rad +class DistantLight +{ +public: + /** + * Constructor + * + * \param light the sp light object + * \param lighting_color the lighting_color used + */ + DistantLight(SPFeDistantLight *light, guint32 lighting_color); + virtual ~DistantLight(); + + /** + * Computes the light vector of the distant light + * + * \param v a Fvector reference where we store the result + */ + void light_vector(NR::Fvector &v); + + /** + * Computes the light components of the distant light + * + * \param lc a Fvector reference where we store the result, X=R, Y=G, Z=B + */ + void light_components(NR::Fvector &lc); + +private: + guint32 color; + double azimuth; // azimuth in rad + double elevation; // elevation in rad }; -class PointLight { - public: - /** - * Constructor - * - * \param light the sp light object - * \param lighting_color the lighting_color used - * \param trans the transformation between absolute coordinate (those - * employed in the sp light object) and current coordinate (those - * employed in the rendering) - * \param device_scale for high DPI monitors. - */ - PointLight(SPFePointLight *light, guint32 lighting_color, const Geom::Affine &trans, int device_scale = 1); - virtual ~PointLight(); - /** - * Computes the light vector of the distant light at point (x,y,z). - * x, y and z are given in the arena_item coordinate, they are used as - * is - * - * \param v a Fvector reference where we store the result - * \param x x coordinate of the current point - * \param y y coordinate of the current point - * \param z z coordinate of the current point - */ - void light_vector(NR::Fvector &v, double x, double y, double z); - - /** - * Computes the light components of the distant light - * - * \param lc a Fvector reference where we store the result, X=R, Y=G, Z=B - */ - void light_components(NR::Fvector &lc); - - private: - guint32 color; - //light position coordinates in render setting - double l_x; - double l_y; - double l_z; +class PointLight +{ +public: + /** + * Constructor + * + * \param light the sp light object + * \param lighting_color the lighting_color used + * \param trans the transformation between absolute coordinate (those + * employed in the sp light object) and current coordinate (those + * employed in the rendering) + * \param device_scale for high DPI monitors. + */ + PointLight(SPFePointLight *light, guint32 lighting_color, const Geom::Affine &trans, int device_scale = 1); + virtual ~PointLight(); + /** + * Computes the light vector of the distant light at point (x,y,z). + * x, y and z are given in the arena_item coordinate, they are used as + * is + * + * \param v a Fvector reference where we store the result + * \param x x coordinate of the current point + * \param y y coordinate of the current point + * \param z z coordinate of the current point + */ + void light_vector(NR::Fvector &v, double x, double y, double z); + + /** + * Computes the light components of the distant light + * + * \param lc a Fvector reference where we store the result, X=R, Y=G, Z=B + */ + void light_components(NR::Fvector &lc); + +private: + guint32 color; + // light position coordinates in render setting + double l_x; + double l_y; + double l_z; }; -class SpotLight { - public: - /** - * Constructor - * - * \param light the sp light object - * \param lighting_color the lighting_color used - * \param trans the transformation between absolute coordinate (those - * employed in the sp light object) and current coordinate (those - * employed in the rendering) - * \param device_scale for high DPI monitors. - */ - SpotLight(SPFeSpotLight *light, guint32 lighting_color, const Geom::Affine &trans, int device_scale = 1); - virtual ~SpotLight(); - - /** - * Computes the light vector of the distant light at point (x,y,z). - * x, y and z are given in the arena_item coordinate, they are used as - * is - * - * \param v a Fvector reference where we store the result - * \param x x coordinate of the current point - * \param y y coordinate of the current point - * \param z z coordinate of the current point - */ - void light_vector(NR::Fvector &v, double x, double y, double z); - - /** - * Computes the light components of the distant light at the current - * point. We only need the light vector to compute these - * - * \param lc a Fvector reference where we store the result, X=R, Y=G, Z=B - * \param L the light vector of the current point - */ - void light_components(NR::Fvector &lc, const NR::Fvector &L); - - private: - guint32 color; - //light position coordinates in render setting - double l_x; - double l_y; - double l_z; - double cos_lca; //cos of the limiting cone angle - double speExp; //specular exponent; - NR::Fvector S; //unit vector from light position in the direction - //the spot point at +class SpotLight +{ +public: + /** + * Constructor + * + * \param light the sp light object + * \param lighting_color the lighting_color used + * \param trans the transformation between absolute coordinate (those + * employed in the sp light object) and current coordinate (those + * employed in the rendering) + * \param device_scale for high DPI monitors. + */ + SpotLight(SPFeSpotLight *light, guint32 lighting_color, const Geom::Affine &trans, int device_scale = 1); + virtual ~SpotLight(); + + /** + * Computes the light vector of the distant light at point (x,y,z). + * x, y and z are given in the arena_item coordinate, they are used as + * is + * + * \param v a Fvector reference where we store the result + * \param x x coordinate of the current point + * \param y y coordinate of the current point + * \param z z coordinate of the current point + */ + void light_vector(NR::Fvector &v, double x, double y, double z); + + /** + * Computes the light components of the distant light at the current + * point. We only need the light vector to compute these + * + * \param lc a Fvector reference where we store the result, X=R, Y=G, Z=B + * \param L the light vector of the current point + */ + void light_components(NR::Fvector &lc, const NR::Fvector &L); + +private: + guint32 color; + // light position coordinates in render setting + double l_x; + double l_y; + double l_z; + double cos_lca; // cos of the limiting cone angle + double speExp; // specular exponent; + NR::Fvector S; // unit vector from light position in the direction + // the spot point at }; - } /* namespace Filters */ } /* namespace Inkscape */ diff --git a/src/display/nr-style.cpp b/src/display/nr-style.cpp index 5916306e9e8e3cc6285df8b0247deaeb294ba086..d4c4562d8e561d3fb4275b09814dd05c0811775e 100644 --- a/src/display/nr-style.cpp +++ b/src/display/nr-style.cpp @@ -11,12 +11,11 @@ */ #include "display/nr-style.h" -#include "style.h" #include "display/drawing-context.h" #include "display/drawing-pattern.h" - #include "object/sp-paint-server.h" +#include "style.h" void NRStyle::Paint::clear() { @@ -44,10 +43,10 @@ void NRStyle::Paint::set(SPPaintServer *ps) } } -void NRStyle::Paint::set(const SPIPaint* paint) +void NRStyle::Paint::set(const SPIPaint *paint) { if (paint->isPaintserver()) { - SPPaintServer* server = paint->value.href->getObject(); + SPPaintServer *server = paint->value.href->getObject(); if (server && server->isValid()) { set(server); } else if (paint->colorSet) { @@ -68,7 +67,6 @@ void NRStyle::Paint::set(const SPIPaint* paint) } } - NRStyle::NRStyle() : fill() , stroke() @@ -106,12 +104,16 @@ NRStyle::NRStyle() NRStyle::~NRStyle() { - if (fill_pattern) cairo_pattern_destroy(fill_pattern); - if (stroke_pattern) cairo_pattern_destroy(stroke_pattern); - if (text_decoration_fill_pattern) cairo_pattern_destroy(text_decoration_fill_pattern); - if (text_decoration_stroke_pattern) cairo_pattern_destroy(text_decoration_stroke_pattern); - if (dash){ - delete [] dash; + if (fill_pattern) + cairo_pattern_destroy(fill_pattern); + if (stroke_pattern) + cairo_pattern_destroy(stroke_pattern); + if (text_decoration_fill_pattern) + cairo_pattern_destroy(text_decoration_fill_pattern); + if (text_decoration_stroke_pattern) + cairo_pattern_destroy(text_decoration_stroke_pattern); + if (dash) { + delete[] dash; } fill.clear(); stroke.clear(); @@ -123,21 +125,21 @@ void NRStyle::set(SPStyle *style, SPStyle *context_style) { // Handle 'context-fill' and 'context-stroke': Work in progress const SPIPaint *style_fill = &(style->fill); - if( style_fill->paintOrigin == SP_CSS_PAINT_ORIGIN_CONTEXT_FILL ) { - if( context_style != nullptr ) { + if (style_fill->paintOrigin == SP_CSS_PAINT_ORIGIN_CONTEXT_FILL) { + if (context_style != nullptr) { style_fill = &(context_style->fill); } else { // A marker in the defs section will result in ending up here. - //std::cerr << "NRStyle::set: 'context-fill': 'context_style' is NULL" << std::endl; + // std::cerr << "NRStyle::set: 'context-fill': 'context_style' is NULL" << std::endl; } - } else if ( style_fill->paintOrigin == SP_CSS_PAINT_ORIGIN_CONTEXT_STROKE ) { - if( context_style != nullptr ) { + } else if (style_fill->paintOrigin == SP_CSS_PAINT_ORIGIN_CONTEXT_STROKE) { + if (context_style != nullptr) { style_fill = &(context_style->stroke); } else { - //std::cerr << "NRStyle::set: 'context-stroke': 'context_style' is NULL" << std::endl; + // std::cerr << "NRStyle::set: 'context-stroke': 'context_style' is NULL" << std::endl; } } - + fill.set(style_fill); fill.opacity = SP_SCALE24_TO_FLOAT(style->fill_opacity.value); @@ -153,17 +155,17 @@ void NRStyle::set(SPStyle *style, SPStyle *context_style) } const SPIPaint *style_stroke = &(style->stroke); - if( style_stroke->paintOrigin == SP_CSS_PAINT_ORIGIN_CONTEXT_FILL ) { - if( context_style != nullptr ) { + if (style_stroke->paintOrigin == SP_CSS_PAINT_ORIGIN_CONTEXT_FILL) { + if (context_style != nullptr) { style_stroke = &(context_style->fill); } else { - //std::cerr << "NRStyle::set: 'context-fill': 'context_style' is NULL" << std::endl; + // std::cerr << "NRStyle::set: 'context-fill': 'context_style' is NULL" << std::endl; } - } else if ( style_stroke->paintOrigin == SP_CSS_PAINT_ORIGIN_CONTEXT_STROKE ) { - if( context_style != nullptr ) { + } else if (style_stroke->paintOrigin == SP_CSS_PAINT_ORIGIN_CONTEXT_STROKE) { + if (context_style != nullptr) { style_stroke = &(context_style->stroke); } else { - //std::cerr << "NRStyle::set: 'context-stroke': 'context_style' is NULL" << std::endl; + // std::cerr << "NRStyle::set: 'context-stroke': 'context_style' is NULL" << std::endl; } } @@ -198,8 +200,8 @@ void NRStyle::set(SPStyle *style, SPStyle *context_style) } miter_limit = style->stroke_miterlimit.value; - if (dash){ - delete [] dash; + if (dash) { + delete[] dash; } n_dash = style->stroke_dasharray.values.size(); @@ -214,49 +216,70 @@ void NRStyle::set(SPStyle *style, SPStyle *context_style) dash = nullptr; } - - for( unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i) { + for (unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i) { switch (style->paint_order.layer[i]) { case SP_CSS_PAINT_ORDER_NORMAL: - paint_order_layer[i]=PAINT_ORDER_NORMAL; + paint_order_layer[i] = PAINT_ORDER_NORMAL; break; case SP_CSS_PAINT_ORDER_FILL: - paint_order_layer[i]=PAINT_ORDER_FILL; + paint_order_layer[i] = PAINT_ORDER_FILL; break; case SP_CSS_PAINT_ORDER_STROKE: - paint_order_layer[i]=PAINT_ORDER_STROKE; + paint_order_layer[i] = PAINT_ORDER_STROKE; break; case SP_CSS_PAINT_ORDER_MARKER: - paint_order_layer[i]=PAINT_ORDER_MARKER; + paint_order_layer[i] = PAINT_ORDER_MARKER; break; } } text_decoration_line = TEXT_DECORATION_LINE_CLEAR; - if(style->text_decoration_line.inherit ){ text_decoration_line |= TEXT_DECORATION_LINE_INHERIT; } - if(style->text_decoration_line.underline ){ text_decoration_line |= TEXT_DECORATION_LINE_UNDERLINE + TEXT_DECORATION_LINE_SET; } - if(style->text_decoration_line.overline ){ text_decoration_line |= TEXT_DECORATION_LINE_OVERLINE + TEXT_DECORATION_LINE_SET; } - if(style->text_decoration_line.line_through){ text_decoration_line |= TEXT_DECORATION_LINE_LINETHROUGH + TEXT_DECORATION_LINE_SET; } - if(style->text_decoration_line.blink ){ text_decoration_line |= TEXT_DECORATION_LINE_BLINK + TEXT_DECORATION_LINE_SET; } + if (style->text_decoration_line.inherit) { + text_decoration_line |= TEXT_DECORATION_LINE_INHERIT; + } + if (style->text_decoration_line.underline) { + text_decoration_line |= TEXT_DECORATION_LINE_UNDERLINE + TEXT_DECORATION_LINE_SET; + } + if (style->text_decoration_line.overline) { + text_decoration_line |= TEXT_DECORATION_LINE_OVERLINE + TEXT_DECORATION_LINE_SET; + } + if (style->text_decoration_line.line_through) { + text_decoration_line |= TEXT_DECORATION_LINE_LINETHROUGH + TEXT_DECORATION_LINE_SET; + } + if (style->text_decoration_line.blink) { + text_decoration_line |= TEXT_DECORATION_LINE_BLINK + TEXT_DECORATION_LINE_SET; + } text_decoration_style = TEXT_DECORATION_STYLE_CLEAR; - if(style->text_decoration_style.inherit ){ text_decoration_style |= TEXT_DECORATION_STYLE_INHERIT; } - if(style->text_decoration_style.solid ){ text_decoration_style |= TEXT_DECORATION_STYLE_SOLID + TEXT_DECORATION_STYLE_SET; } - if(style->text_decoration_style.isdouble ){ text_decoration_style |= TEXT_DECORATION_STYLE_ISDOUBLE + TEXT_DECORATION_STYLE_SET; } - if(style->text_decoration_style.dotted ){ text_decoration_style |= TEXT_DECORATION_STYLE_DOTTED + TEXT_DECORATION_STYLE_SET; } - if(style->text_decoration_style.dashed ){ text_decoration_style |= TEXT_DECORATION_STYLE_DASHED + TEXT_DECORATION_STYLE_SET; } - if(style->text_decoration_style.wavy ){ text_decoration_style |= TEXT_DECORATION_STYLE_WAVY + TEXT_DECORATION_STYLE_SET; } - + if (style->text_decoration_style.inherit) { + text_decoration_style |= TEXT_DECORATION_STYLE_INHERIT; + } + if (style->text_decoration_style.solid) { + text_decoration_style |= TEXT_DECORATION_STYLE_SOLID + TEXT_DECORATION_STYLE_SET; + } + if (style->text_decoration_style.isdouble) { + text_decoration_style |= TEXT_DECORATION_STYLE_ISDOUBLE + TEXT_DECORATION_STYLE_SET; + } + if (style->text_decoration_style.dotted) { + text_decoration_style |= TEXT_DECORATION_STYLE_DOTTED + TEXT_DECORATION_STYLE_SET; + } + if (style->text_decoration_style.dashed) { + text_decoration_style |= TEXT_DECORATION_STYLE_DASHED + TEXT_DECORATION_STYLE_SET; + } + if (style->text_decoration_style.wavy) { + text_decoration_style |= TEXT_DECORATION_STYLE_WAVY + TEXT_DECORATION_STYLE_SET; + } + /* FIXME The meaning of text-decoration-color in CSS3 for SVG is ambiguous (2014-05-06). Set it for fill, for stroke, for both? Both would seem like the obvious choice but what happens is that for text which is just fill (very common) it makes the lines fatter because it enables stroke on the decorations when it wasn't present on the text. That contradicts the usual behavior where the text and decorations by default have the same fill/stroke. - + The behavior here is that if color is defined it is applied to text_decoration_fill/stroke ONLY if the corresponding fill/stroke is also present. - + Hopefully the standard will be clarified to resolve this issue. */ @@ -264,8 +287,9 @@ void NRStyle::set(SPStyle *style, SPStyle *context_style) // closest ancestor where 'text-decoration' was set. That is, setting // 'text-decoration' on an ancestor fixes the fill and stroke of the // decoration to the fill and stroke values of that ancestor. - SPStyle* style_td = style; - if ( style->text_decoration.style_td ) style_td = style->text_decoration.style_td; + SPStyle *style_td = style; + if (style->text_decoration.style_td) + style_td = style->text_decoration.style_td; text_decoration_stroke.opacity = SP_SCALE24_TO_FLOAT(style_td->stroke_opacity.value); text_decoration_stroke_width = style_td->stroke_width.computed; @@ -276,7 +300,7 @@ void NRStyle::set(SPStyle *style, SPStyle *context_style) if (style_td->text_decoration_fill.set) { text_decoration_fill.set(&(style_td->text_decoration_fill)); } else if (style_td->text_decoration_color.set) { - if(style->fill.isPaintserver() || style->fill.isColor()) { + if (style->fill.isPaintserver() || style->fill.isColor()) { // SVG sets color specifically text_decoration_fill.set(style->text_decoration_color.value.color); } else { @@ -291,7 +315,7 @@ void NRStyle::set(SPStyle *style, SPStyle *context_style) if (style_td->text_decoration_stroke.set) { text_decoration_stroke.set(&(style_td->text_decoration_stroke)); } else if (style_td->text_decoration_color.set) { - if(style->stroke.isPaintserver() || style->stroke.isColor()) { + if (style->stroke.isPaintserver() || style->stroke.isColor()) { // SVG sets color specifically text_decoration_stroke.set(style->text_decoration_color.value.color); } else { @@ -304,17 +328,17 @@ void NRStyle::set(SPStyle *style, SPStyle *context_style) } if (text_decoration_line != TEXT_DECORATION_LINE_CLEAR) { - phase_length = style->text_decoration_data.phase_length; - tspan_line_start = style->text_decoration_data.tspan_line_start; - tspan_line_end = style->text_decoration_data.tspan_line_end; - tspan_width = style->text_decoration_data.tspan_width; - ascender = style->text_decoration_data.ascender; - descender = style->text_decoration_data.descender; - underline_thickness = style->text_decoration_data.underline_thickness; - underline_position = style->text_decoration_data.underline_position; + phase_length = style->text_decoration_data.phase_length; + tspan_line_start = style->text_decoration_data.tspan_line_start; + tspan_line_end = style->text_decoration_data.tspan_line_end; + tspan_width = style->text_decoration_data.tspan_width; + ascender = style->text_decoration_data.ascender; + descender = style->text_decoration_data.descender; + underline_thickness = style->text_decoration_data.underline_thickness; + underline_position = style->text_decoration_data.underline_position; line_through_thickness = style->text_decoration_data.line_through_thickness; - line_through_position = style->text_decoration_data.line_through_position; - font_size = style->font_size.computed; + line_through_position = style->text_decoration_data.line_through_position; + font_size = style->font_size.computed; } text_direction = style->direction.computed; @@ -322,9 +346,10 @@ void NRStyle::set(SPStyle *style, SPStyle *context_style) update(); } -cairo_pattern_t* NRStyle::preparePaint(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, Inkscape::DrawingPattern *pattern, Paint& paint) +cairo_pattern_t *NRStyle::preparePaint(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, + Inkscape::DrawingPattern *pattern, Paint &paint) { - cairo_pattern_t* cpattern = nullptr; + cairo_pattern_t *cpattern = nullptr; switch (paint.type) { case PAINT_SERVER: @@ -336,42 +361,48 @@ cairo_pattern_t* NRStyle::preparePaint(Inkscape::DrawingContext &dc, Geom::OptRe break; case PAINT_COLOR: { SPColor const &c = paint.color; - cpattern = cairo_pattern_create_rgba( - c.v.c[0], c.v.c[1], c.v.c[2], paint.opacity); + cpattern = cairo_pattern_create_rgba(c.v.c[0], c.v.c[1], c.v.c[2], paint.opacity); double red = 0; double green = 0; double blue = 0; double alpha = 0; cairo_pattern_get_rgba(cpattern, &red, &green, &blue, &alpha); - } - break; + } break; default: break; } return cpattern; } -bool NRStyle::prepareFill(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, Inkscape::DrawingPattern *pattern) +bool NRStyle::prepareFill(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, + Inkscape::DrawingPattern *pattern) { - if (!fill_pattern) fill_pattern = preparePaint(dc, paintbox, pattern, fill); + if (!fill_pattern) + fill_pattern = preparePaint(dc, paintbox, pattern, fill); return fill_pattern != nullptr; } -bool NRStyle::prepareStroke(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, Inkscape::DrawingPattern *pattern) +bool NRStyle::prepareStroke(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, + Inkscape::DrawingPattern *pattern) { - if (!stroke_pattern) stroke_pattern = preparePaint(dc, paintbox, pattern, stroke); + if (!stroke_pattern) + stroke_pattern = preparePaint(dc, paintbox, pattern, stroke); return stroke_pattern != nullptr; } -bool NRStyle::prepareTextDecorationFill(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, Inkscape::DrawingPattern *pattern) +bool NRStyle::prepareTextDecorationFill(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, + Inkscape::DrawingPattern *pattern) { - if (!text_decoration_fill_pattern) text_decoration_fill_pattern = preparePaint(dc, paintbox, pattern, text_decoration_fill); + if (!text_decoration_fill_pattern) + text_decoration_fill_pattern = preparePaint(dc, paintbox, pattern, text_decoration_fill); return text_decoration_fill_pattern != nullptr; } -bool NRStyle::prepareTextDecorationStroke(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, Inkscape::DrawingPattern *pattern) +bool NRStyle::prepareTextDecorationStroke(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, + Inkscape::DrawingPattern *pattern) { - if (!text_decoration_stroke_pattern) text_decoration_stroke_pattern = preparePaint(dc, paintbox, pattern, text_decoration_stroke); + if (!text_decoration_stroke_pattern) + text_decoration_stroke_pattern = preparePaint(dc, paintbox, pattern, text_decoration_stroke); return text_decoration_stroke_pattern != nullptr; } @@ -410,10 +441,14 @@ void NRStyle::applyTextDecorationStroke(Inkscape::DrawingContext &dc) void NRStyle::update() { // force pattern update - if (fill_pattern) cairo_pattern_destroy(fill_pattern); - if (stroke_pattern) cairo_pattern_destroy(stroke_pattern); - if (text_decoration_fill_pattern) cairo_pattern_destroy(text_decoration_fill_pattern); - if (text_decoration_stroke_pattern) cairo_pattern_destroy(text_decoration_stroke_pattern); + if (fill_pattern) + cairo_pattern_destroy(fill_pattern); + if (stroke_pattern) + cairo_pattern_destroy(stroke_pattern); + if (text_decoration_fill_pattern) + cairo_pattern_destroy(text_decoration_fill_pattern); + if (text_decoration_stroke_pattern) + cairo_pattern_destroy(text_decoration_stroke_pattern); fill_pattern = nullptr; stroke_pattern = nullptr; text_decoration_fill_pattern = nullptr; diff --git a/src/display/nr-style.h b/src/display/nr-style.h index f9d7fa579a5a8865bab131a4bad512de686081f3..10bd596fab2a008c34ddb8edd7307f63e764f050 100644 --- a/src/display/nr-style.h +++ b/src/display/nr-style.h @@ -14,8 +14,9 @@ #ifndef SEEN_INKSCAPE_DISPLAY_NR_ARENA_STYLE_H #define SEEN_INKSCAPE_DISPLAY_NR_ARENA_STYLE_H -#include #include <2geom/rect.h> +#include + #include "color.h" class SPPaintServer; @@ -25,21 +26,29 @@ class SPIPaint; namespace Inkscape { class DrawingContext; class DrawingPattern; -} +} // namespace Inkscape -struct NRStyle { +struct NRStyle +{ NRStyle(); ~NRStyle(); - enum PaintType { + enum PaintType + { PAINT_NONE, PAINT_COLOR, PAINT_SERVER }; - class Paint { - public: - Paint() : type(PAINT_NONE), color(0), server(nullptr), opacity(1.0) {} + class Paint + { + public: + Paint() + : type(PAINT_NONE) + , color(0) + , server(nullptr) + , opacity(1.0) + {} ~Paint() { clear(); } PaintType type; @@ -50,15 +59,18 @@ struct NRStyle { void clear(); void set(SPColor const &c); void set(SPPaintServer *ps); - void set(const SPIPaint* paint); + void set(const SPIPaint *paint); }; void set(SPStyle *style, SPStyle *context_style = nullptr); - cairo_pattern_t* preparePaint(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, Inkscape::DrawingPattern *pattern, Paint& paint); + cairo_pattern_t *preparePaint(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, + Inkscape::DrawingPattern *pattern, Paint &paint); bool prepareFill(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, Inkscape::DrawingPattern *pattern); bool prepareStroke(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, Inkscape::DrawingPattern *pattern); - bool prepareTextDecorationFill(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, Inkscape::DrawingPattern *pattern); - bool prepareTextDecorationStroke(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, Inkscape::DrawingPattern *pattern); + bool prepareTextDecorationFill(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, + Inkscape::DrawingPattern *pattern); + bool prepareTextDecorationStroke(Inkscape::DrawingContext &dc, Geom::OptRect const &paintbox, + Inkscape::DrawingPattern *pattern); void applyFill(Inkscape::DrawingContext &dc); void applyStroke(Inkscape::DrawingContext &dc); void applyTextDecorationFill(Inkscape::DrawingContext &dc); @@ -81,7 +93,8 @@ struct NRStyle { cairo_pattern_t *text_decoration_fill_pattern; cairo_pattern_t *text_decoration_stroke_pattern; - enum PaintOrderType { + enum PaintOrderType + { PAINT_ORDER_NORMAL, PAINT_ORDER_FILL, PAINT_ORDER_STROKE, @@ -91,52 +104,53 @@ struct NRStyle { static const size_t PAINT_ORDER_LAYERS = 3; PaintOrderType paint_order_layer[PAINT_ORDER_LAYERS]; - enum TextDecorationLine { - TEXT_DECORATION_LINE_CLEAR = 0x00, - TEXT_DECORATION_LINE_SET = 0x01, - TEXT_DECORATION_LINE_INHERIT = 0x02, - TEXT_DECORATION_LINE_UNDERLINE = 0x04, - TEXT_DECORATION_LINE_OVERLINE = 0x08, + enum TextDecorationLine + { + TEXT_DECORATION_LINE_CLEAR = 0x00, + TEXT_DECORATION_LINE_SET = 0x01, + TEXT_DECORATION_LINE_INHERIT = 0x02, + TEXT_DECORATION_LINE_UNDERLINE = 0x04, + TEXT_DECORATION_LINE_OVERLINE = 0x08, TEXT_DECORATION_LINE_LINETHROUGH = 0x10, - TEXT_DECORATION_LINE_BLINK = 0x20 + TEXT_DECORATION_LINE_BLINK = 0x20 }; - enum TextDecorationStyle { - TEXT_DECORATION_STYLE_CLEAR = 0x00, - TEXT_DECORATION_STYLE_SET = 0x01, - TEXT_DECORATION_STYLE_INHERIT = 0x02, - TEXT_DECORATION_STYLE_SOLID = 0x04, - TEXT_DECORATION_STYLE_ISDOUBLE = 0x08, - TEXT_DECORATION_STYLE_DOTTED = 0x10, - TEXT_DECORATION_STYLE_DASHED = 0x20, - TEXT_DECORATION_STYLE_WAVY = 0x40 + enum TextDecorationStyle + { + TEXT_DECORATION_STYLE_CLEAR = 0x00, + TEXT_DECORATION_STYLE_SET = 0x01, + TEXT_DECORATION_STYLE_INHERIT = 0x02, + TEXT_DECORATION_STYLE_SOLID = 0x04, + TEXT_DECORATION_STYLE_ISDOUBLE = 0x08, + TEXT_DECORATION_STYLE_DOTTED = 0x10, + TEXT_DECORATION_STYLE_DASHED = 0x20, + TEXT_DECORATION_STYLE_WAVY = 0x40 }; - int text_decoration_line; - int text_decoration_style; + int text_decoration_line; + int text_decoration_style; Paint text_decoration_fill; Paint text_decoration_stroke; float text_decoration_stroke_width; // These are the same as in style.h float phase_length; - bool tspan_line_start; - bool tspan_line_end; + bool tspan_line_start; + bool tspan_line_end; float tspan_width; float ascender; float descender; float underline_thickness; - float underline_position; + float underline_position; float line_through_thickness; float line_through_position; float font_size; - int text_direction; + int text_direction; }; #endif - /* Local Variables: mode:c++ diff --git a/src/display/nr-svgfonts.cpp b/src/display/nr-svgfonts.cpp index 1d75027a9bb636a4103a5157f264efde62a4a13f..cb444a5e078ec28c13d0626429fad1e78f8b8204 100644 --- a/src/display/nr-svgfonts.cpp +++ b/src/display/nr-svgfonts.cpp @@ -12,297 +12,284 @@ * Read the file 'COPYING' for more information. */ +#include "display/nr-svgfonts.h" + #include <2geom/pathvector.h> #include <2geom/transforms.h> #include #include -#include "svg/svg.h" #include "display/cairo-utils.h" -#include "display/nr-svgfonts.h" -#include "display/nr-svgfonts.h" #include "display/curve.h" - -#include "xml/repr.h" - -#include "object/sp-path.h" -#include "object/sp-object-group.h" -#include "object/sp-use.h" -#include "object/sp-use-reference.h" +#include "display/nr-svgfonts.h" #include "object/sp-font-face.h" -#include "object/sp-glyph.h" -#include "object/sp-missing-glyph.h" #include "object/sp-font.h" #include "object/sp-glyph-kerning.h" +#include "object/sp-glyph.h" +#include "object/sp-missing-glyph.h" +#include "object/sp-object-group.h" +#include "object/sp-path.h" +#include "object/sp-use-reference.h" +#include "object/sp-use.h" +#include "svg/svg.h" +#include "xml/repr.h" // ************************// // UserFont Implementation // // ************************// -// I wrote this binding code because Cairomm does not yet support userfonts. I have moved this code to cairomm and sent them a patch. -// Once Cairomm incorporate the UserFonts binding, this code should be removed from inkscape and Cairomm API should be used. +// I wrote this binding code because Cairomm does not yet support userfonts. I have moved this code to cairomm and sent +// them a patch. Once Cairomm incorporate the UserFonts binding, this code should be removed from inkscape and Cairomm +// API should be used. static cairo_user_data_key_t key; -static cairo_status_t font_init_cb (cairo_scaled_font_t *scaled_font, - cairo_t * /*cairo*/, cairo_font_extents_t *metrics){ - cairo_font_face_t* face = cairo_scaled_font_get_font_face(scaled_font); - SvgFont* instance = static_cast(cairo_font_face_get_user_data(face, &key)); +static cairo_status_t font_init_cb(cairo_scaled_font_t *scaled_font, cairo_t * /*cairo*/, cairo_font_extents_t *metrics) +{ + cairo_font_face_t *face = cairo_scaled_font_get_font_face(scaled_font); + SvgFont *instance = static_cast(cairo_font_face_get_user_data(face, &key)); return instance->scaled_font_init(scaled_font, metrics); } -static cairo_status_t font_text_to_glyphs_cb ( cairo_scaled_font_t *scaled_font, - const char *utf8, - int utf8_len, - cairo_glyph_t **glyphs, - int *num_glyphs, - cairo_text_cluster_t **clusters, - int *num_clusters, - cairo_text_cluster_flags_t *flags){ - cairo_font_face_t* face = cairo_scaled_font_get_font_face(scaled_font); - SvgFont* instance = static_cast(cairo_font_face_get_user_data(face, &key)); - return instance->scaled_font_text_to_glyphs(scaled_font, utf8, utf8_len, glyphs, num_glyphs, clusters, num_clusters, flags); +static cairo_status_t font_text_to_glyphs_cb(cairo_scaled_font_t *scaled_font, const char *utf8, int utf8_len, + cairo_glyph_t **glyphs, int *num_glyphs, cairo_text_cluster_t **clusters, + int *num_clusters, cairo_text_cluster_flags_t *flags) +{ + cairo_font_face_t *face = cairo_scaled_font_get_font_face(scaled_font); + SvgFont *instance = static_cast(cairo_font_face_get_user_data(face, &key)); + return instance->scaled_font_text_to_glyphs(scaled_font, utf8, utf8_len, glyphs, num_glyphs, clusters, num_clusters, + flags); } -static cairo_status_t font_render_glyph_cb (cairo_scaled_font_t *scaled_font, - unsigned long glyph, - cairo_t *cr, - cairo_text_extents_t *metrics){ - cairo_font_face_t* face = cairo_scaled_font_get_font_face(scaled_font); - SvgFont* instance = static_cast(cairo_font_face_get_user_data(face, &key)); +static cairo_status_t font_render_glyph_cb(cairo_scaled_font_t *scaled_font, unsigned long glyph, cairo_t *cr, + cairo_text_extents_t *metrics) +{ + cairo_font_face_t *face = cairo_scaled_font_get_font_face(scaled_font); + SvgFont *instance = static_cast(cairo_font_face_get_user_data(face, &key)); return instance->scaled_font_render_glyph(scaled_font, glyph, cr, metrics); } -UserFont::UserFont(SvgFont* instance){ - this->face = cairo_user_font_face_create (); - cairo_user_font_face_set_init_func (this->face, font_init_cb); - cairo_user_font_face_set_render_glyph_func (this->face, font_render_glyph_cb); +UserFont::UserFont(SvgFont *instance) +{ + this->face = cairo_user_font_face_create(); + cairo_user_font_face_set_init_func(this->face, font_init_cb); + cairo_user_font_face_set_render_glyph_func(this->face, font_render_glyph_cb); cairo_user_font_face_set_text_to_glyphs_func(this->face, font_text_to_glyphs_cb); - cairo_font_face_set_user_data (this->face, &key, (void*)instance, (cairo_destroy_func_t) nullptr); + cairo_font_face_set_user_data(this->face, &key, (void *)instance, (cairo_destroy_func_t) nullptr); } //******************************// // SvgFont class Implementation // //******************************// -SvgFont::SvgFont(SPFont* spfont){ +SvgFont::SvgFont(SPFont *spfont) +{ this->font = spfont; this->missingglyph = nullptr; this->userfont = nullptr; } -cairo_status_t -SvgFont::scaled_font_init (cairo_scaled_font_t */*scaled_font*/, - cairo_font_extents_t */*metrics*/) +cairo_status_t SvgFont::scaled_font_init(cairo_scaled_font_t * /*scaled_font*/, cairo_font_extents_t * /*metrics*/) { -//TODO -// metrics->ascent = .75; -// metrics->descent = .25; - return CAIRO_STATUS_SUCCESS; + // TODO + // metrics->ascent = .75; + // metrics->descent = .25; + return CAIRO_STATUS_SUCCESS; } -unsigned int size_of_substring(const char* substring, gchar* str){ - const gchar* original_substring = substring; +unsigned int size_of_substring(const char *substring, gchar *str) +{ + const gchar *original_substring = substring; - while((g_utf8_get_char(substring)==g_utf8_get_char(str)) && g_utf8_get_char(substring) != 0 && g_utf8_get_char(str) != 0){ + while ((g_utf8_get_char(substring) == g_utf8_get_char(str)) && g_utf8_get_char(substring) != 0 && + g_utf8_get_char(str) != 0) { substring = g_utf8_next_char(substring); str = g_utf8_next_char(str); } - if (g_utf8_get_char(substring)==0) + if (g_utf8_get_char(substring) == 0) return substring - original_substring; else return 0; } - namespace { -//TODO: in these functions, verify what happens when using unicode strings. +// TODO: in these functions, verify what happens when using unicode strings. -bool MatchVKerningRule(SPVkern const *vkern, - SPGlyph *glyph, - char const *previous_unicode, +bool MatchVKerningRule(SPVkern const *vkern, SPGlyph *glyph, char const *previous_unicode, gchar const *previous_glyph_name) { - bool value = (vkern->u1->contains(previous_unicode[0]) - || vkern->g1->contains(previous_glyph_name)) - && (vkern->u2->contains(glyph->unicode[0]) - || vkern->g2->contains(glyph->glyph_name.c_str())); + bool value = (vkern->u1->contains(previous_unicode[0]) || vkern->g1->contains(previous_glyph_name)) && + (vkern->u2->contains(glyph->unicode[0]) || vkern->g2->contains(glyph->glyph_name.c_str())); return value; } -bool MatchHKerningRule(SPHkern const *hkern, - SPGlyph *glyph, - char const *previous_unicode, +bool MatchHKerningRule(SPHkern const *hkern, SPGlyph *glyph, char const *previous_unicode, gchar const *previous_glyph_name) { - bool value = (hkern->u1->contains(previous_unicode[0]) - || hkern->g1->contains(previous_glyph_name)) - && (hkern->u2->contains(glyph->unicode[0]) - || hkern->g2->contains(glyph->glyph_name.c_str())); + bool value = (hkern->u1->contains(previous_unicode[0]) || hkern->g1->contains(previous_glyph_name)) && + (hkern->u2->contains(glyph->unicode[0]) || hkern->g2->contains(glyph->glyph_name.c_str())); return value; } } // namespace -cairo_status_t -SvgFont::scaled_font_text_to_glyphs (cairo_scaled_font_t */*scaled_font*/, - const char *utf8, - int /*utf8_len*/, - cairo_glyph_t **glyphs, - int *num_glyphs, - cairo_text_cluster_t **/*clusters*/, - int */*num_clusters*/, - cairo_text_cluster_flags_t */*flags*/) +cairo_status_t SvgFont::scaled_font_text_to_glyphs(cairo_scaled_font_t * /*scaled_font*/, const char *utf8, + int /*utf8_len*/, cairo_glyph_t **glyphs, int *num_glyphs, + cairo_text_cluster_t ** /*clusters*/, int * /*num_clusters*/, + cairo_text_cluster_flags_t * /*flags*/) { - //This function receives a text string to be rendered. It then defines what is the sequence of glyphs that + // This function receives a text string to be rendered. It then defines what is the sequence of glyphs that // is used to properly render this string. It also defines the respective coordinates of each glyph. Thus, it // has to read the attributes of the SVGFont hkern and vkern nodes in order to adjust the glyph kerning. - //It also determines the usage of the missing-glyph in portions of the string that does not match any of the declared glyphs. + // It also determines the usage of the missing-glyph in portions of the string that does not match any of the + // declared glyphs. unsigned long i; int count = 0; - gchar* _utf8 = (gchar*) utf8; + gchar *_utf8 = (gchar *)utf8; unsigned int len; bool missing; - //First we find out what's the number of glyphs needed. - while(g_utf8_get_char(_utf8)){ + // First we find out what's the number of glyphs needed. + while (g_utf8_get_char(_utf8)) { missing = true; - for (i=0; i < (unsigned long) this->glyphs.size(); i++){ - if ( (len = size_of_substring(this->glyphs[i]->unicode.c_str(), _utf8)) ){ - //TODO: store this cluster - _utf8+=len; + for (i = 0; i < (unsigned long)this->glyphs.size(); i++) { + if ((len = size_of_substring(this->glyphs[i]->unicode.c_str(), _utf8))) { + // TODO: store this cluster + _utf8 += len; count++; - missing=false; + missing = false; break; } } - if (missing){ - //TODO: store this cluster + if (missing) { + // TODO: store this cluster _utf8++; count++; } } + // We use that info to allocate memory for the glyphs + *glyphs = (cairo_glyph_t *)malloc(count * sizeof(cairo_glyph_t)); - //We use that info to allocate memory for the glyphs - *glyphs = (cairo_glyph_t*) malloc(count*sizeof(cairo_glyph_t)); - - char* previous_unicode = nullptr; //This is used for kerning - gchar* previous_glyph_name = nullptr; //This is used for kerning + char *previous_unicode = nullptr; // This is used for kerning + gchar *previous_glyph_name = nullptr; // This is used for kerning - count=0; - double x=0, y=0;//These vars store the position of the glyph within the rendered string - bool is_horizontal_text = true; //TODO - _utf8 = (char*) utf8; + count = 0; + double x = 0, y = 0; // These vars store the position of the glyph within the rendered string + bool is_horizontal_text = true; // TODO + _utf8 = (char *)utf8; double font_height = units_per_em(); - while(g_utf8_get_char(_utf8)){ + while (g_utf8_get_char(_utf8)) { len = 0; - for (i=0; i < (unsigned long) this->glyphs.size(); i++){ - //check whether is there a glyph declared on the SVG document + for (i = 0; i < (unsigned long)this->glyphs.size(); i++) { + // check whether is there a glyph declared on the SVG document // that matches with the text string in its current position - if ( (len = size_of_substring(this->glyphs[i]->unicode.c_str(), _utf8)) ){ - for(auto& node: font->children) { + if ((len = size_of_substring(this->glyphs[i]->unicode.c_str(), _utf8))) { + for (auto &node : font->children) { if (!previous_unicode) { break; } - //apply glyph kerning if appropriate + // apply glyph kerning if appropriate SPHkern *hkern = dynamic_cast(&node); if (hkern && is_horizontal_text && - MatchHKerningRule(hkern, this->glyphs[i], previous_unicode, previous_glyph_name) ){ + MatchHKerningRule(hkern, this->glyphs[i], previous_unicode, previous_glyph_name)) { x -= (hkern->k / font_height); } SPVkern *vkern = dynamic_cast(&node); if (vkern && !is_horizontal_text && - MatchVKerningRule(vkern, this->glyphs[i], previous_unicode, previous_glyph_name) ){ + MatchVKerningRule(vkern, this->glyphs[i], previous_unicode, previous_glyph_name)) { y -= (vkern->k / font_height); } } - previous_unicode = const_cast(this->glyphs[i]->unicode.c_str());//used for kerning checking - previous_glyph_name = const_cast(this->glyphs[i]->glyph_name.c_str());//used for kerning checking + previous_unicode = const_cast(this->glyphs[i]->unicode.c_str()); // used for kerning checking + previous_glyph_name = + const_cast(this->glyphs[i]->glyph_name.c_str()); // used for kerning checking (*glyphs)[count].index = i; (*glyphs)[count].x = x; (*glyphs)[count++].y = y; - //advance glyph coordinates: + // advance glyph coordinates: if (is_horizontal_text) { if (this->glyphs[i]->horiz_adv_x != 0) { - x+=(this->glyphs[i]->horiz_adv_x/font_height); + x += (this->glyphs[i]->horiz_adv_x / font_height); } else { - x+=(this->font->horiz_adv_x/font_height); + x += (this->font->horiz_adv_x / font_height); } } else { - y+=(this->font->vert_adv_y/font_height); + y += (this->font->vert_adv_y / font_height); } - _utf8+=len; //advance 'len' bytes in our string pointer - //continue; + _utf8 += len; // advance 'len' bytes in our string pointer + // continue; goto raptorz; } } raptorz: - if (len==0){ + if (len == 0) { (*glyphs)[count].index = i; (*glyphs)[count].x = x; (*glyphs)[count++].y = y; - //advance glyph coordinates: - if (is_horizontal_text) x+=(this->font->horiz_adv_x/font_height);//TODO: use here the height of the font - else y+=(this->font->vert_adv_y/font_height);//TODO: use here the "height" of the font + // advance glyph coordinates: + if (is_horizontal_text) + x += (this->font->horiz_adv_x / font_height); // TODO: use here the height of the font + else + y += (this->font->vert_adv_y / font_height); // TODO: use here the "height" of the font - _utf8 = g_utf8_next_char(_utf8); //advance 1 char in our string pointer + _utf8 = g_utf8_next_char(_utf8); // advance 1 char in our string pointer } } *num_glyphs = count; return CAIRO_STATUS_SUCCESS; } -void -SvgFont::render_glyph_path(cairo_t* cr, Geom::PathVector* pathv){ - if (!pathv->empty()){ - //This glyph has a path description on its d attribute, so we render it: +void SvgFont::render_glyph_path(cairo_t *cr, Geom::PathVector *pathv) +{ + if (!pathv->empty()) { + // This glyph has a path description on its d attribute, so we render it: cairo_new_path(cr); - //adjust scale of the glyph - Geom::Scale s(1.0/units_per_em()); - Geom::Rect area( Geom::Point(0,0), Geom::Point(1,1) ); //I need help here! (reaction: note that the 'area' parameter is an *optional* rect, so you can pass an empty Geom::OptRect() ) + // adjust scale of the glyph + Geom::Scale s(1.0 / units_per_em()); + Geom::Rect area(Geom::Point(0, 0), + Geom::Point(1, 1)); // I need help here! (reaction: note that the 'area' parameter is an + // *optional* rect, so you can pass an empty Geom::OptRect() ) - feed_pathvector_to_cairo (cr, *pathv, s, area, false, 0); + feed_pathvector_to_cairo(cr, *pathv, s, area, false, 0); cairo_fill(cr); } } -void -SvgFont::glyph_modified(SPObject* /* blah */, unsigned int /* bleh */){ +void SvgFont::glyph_modified(SPObject * /* blah */, unsigned int /* bleh */) +{ this->refresh(); - //TODO: update rendering on svgfonts preview widget (in the svg fonts dialog) + // TODO: update rendering on svgfonts preview widget (in the svg fonts dialog) } -Geom::PathVector -SvgFont::flip_coordinate_system(SPFont* spfont, Geom::PathVector pathv){ +Geom::PathVector SvgFont::flip_coordinate_system(SPFont *spfont, Geom::PathVector pathv) +{ double units_per_em = 1024; - for(auto& obj: spfont->children) { + for (auto &obj : spfont->children) { if (dynamic_cast(&obj)) { - //XML Tree being directly used here while it shouldn't be. + // XML Tree being directly used here while it shouldn't be. sp_repr_get_double(obj.getRepr(), "units_per_em", &units_per_em); } } double baseline_offset = units_per_em - spfont->horiz_origin_y; - //This matrix flips y-axis and places the origin at baseline - Geom::Affine m(Geom::Coord(1),Geom::Coord(0),Geom::Coord(0),Geom::Coord(-1),Geom::Coord(0),Geom::Coord(baseline_offset)); - return pathv*m; + // This matrix flips y-axis and places the origin at baseline + Geom::Affine m(Geom::Coord(1), Geom::Coord(0), Geom::Coord(0), Geom::Coord(-1), Geom::Coord(0), + Geom::Coord(baseline_offset)); + return pathv * m; } -cairo_status_t -SvgFont::scaled_font_render_glyph (cairo_scaled_font_t */*scaled_font*/, - unsigned long glyph, - cairo_t *cr, - cairo_text_extents_t */*metrics*/) +cairo_status_t SvgFont::scaled_font_render_glyph(cairo_scaled_font_t * /*scaled_font*/, unsigned long glyph, + cairo_t *cr, cairo_text_extents_t * /*metrics*/) { // This method does the actual rendering of glyphs. @@ -310,10 +297,11 @@ SvgFont::scaled_font_render_glyph (cairo_scaled_font_t */*scaled_font*/, // The id of the missing-glyph is always equal to glyphs.size() // All the other glyphs have ids ranging from 0 to glyphs.size()-1 - if (glyph > this->glyphs.size()) return CAIRO_STATUS_SUCCESS;//TODO: this is an error! + if (glyph > this->glyphs.size()) + return CAIRO_STATUS_SUCCESS; // TODO: this is an error! SPObject *node = nullptr; - if (glyph == glyphs.size()){ + if (glyph == glyphs.size()) { if (!missingglyph) { return CAIRO_STATUS_SUCCESS; } @@ -323,19 +311,19 @@ SvgFont::scaled_font_render_glyph (cairo_scaled_font_t */*scaled_font*/, } if (!dynamic_cast(node) && !dynamic_cast(node)) { - return CAIRO_STATUS_SUCCESS; // FIXME: is this the right code to return? + return CAIRO_STATUS_SUCCESS; // FIXME: is this the right code to return? } - SPFont* spfont = dynamic_cast(node->parent); + SPFont *spfont = dynamic_cast(node->parent); if (!spfont) { - return CAIRO_STATUS_SUCCESS; // FIXME: is this the right code to return? + return CAIRO_STATUS_SUCCESS; // FIXME: is this the right code to return? } - //glyphs can be described by arbitrary SVG declared in the childnodes of a glyph node + // glyphs can be described by arbitrary SVG declared in the childnodes of a glyph node // or using the d attribute of a glyph node. // pathv stores the path description from the d attribute: Geom::PathVector pathv; - + SPGlyph *glyphNode = dynamic_cast(node); if (glyphNode && glyphNode->d) { pathv = sp_svg_read_pathv(glyphNode->d); @@ -350,9 +338,9 @@ SvgFont::scaled_font_render_glyph (cairo_scaled_font_t */*scaled_font*/, } } - if (node->hasChildren()){ - //render the SVG described on this glyph's child nodes. - for(auto& child: node->children) { + if (node->hasChildren()) { + // render the SVG described on this glyph's child nodes. + for (auto &child : node->children) { { SPPath *path = dynamic_cast(&child); if (path) { @@ -366,7 +354,7 @@ SvgFont::scaled_font_render_glyph (cairo_scaled_font_t */*scaled_font*/, } SPUse *use = dynamic_cast(&child); if (use) { - SPItem* item = use->ref->getObject(); + SPItem *item = use->ref->getObject(); SPPath *path = dynamic_cast(item); if (path) { SPShape *shape = dynamic_cast(item); @@ -384,10 +372,10 @@ SvgFont::scaled_font_render_glyph (cairo_scaled_font_t */*scaled_font*/, return CAIRO_STATUS_SUCCESS; } -cairo_font_face_t* -SvgFont::get_font_face(){ +cairo_font_face_t *SvgFont::get_font_face() +{ if (!this->userfont) { - for(auto& node: font->children) { + for (auto &node : font->children) { SPGlyph *glyph = dynamic_cast(&node); if (glyph) { glyphs.push_back(glyph); @@ -402,17 +390,19 @@ SvgFont::get_font_face(){ return this->userfont->face; } -void SvgFont::refresh(){ +void SvgFont::refresh() +{ this->glyphs.clear(); delete this->userfont; this->userfont = nullptr; } -double SvgFont::units_per_em() { +double SvgFont::units_per_em() +{ double units_per_em = 1024; - for (auto& obj: font->children) { + for (auto &obj : font->children) { if (dynamic_cast(&obj)) { - //XML Tree being directly used here while it shouldn't be. + // XML Tree being directly used here while it shouldn't be. sp_repr_get_double(obj.getRepr(), "units-per-em", &units_per_em); } } @@ -421,7 +411,7 @@ double SvgFont::units_per_em() { } return units_per_em; } - + /* Local Variables: mode:c++ diff --git a/src/display/nr-svgfonts.h b/src/display/nr-svgfonts.h index ffc54f67d1f68a0709a594c53b6bf138734cc683..d046234c80da021c36d1dbc6ae947d67e0cb6a38 100644 --- a/src/display/nr-svgfonts.h +++ b/src/display/nr-svgfonts.h @@ -13,9 +13,9 @@ * Read the file 'COPYING' for more information. */ +#include <2geom/pathvector.h> #include #include -#include <2geom/pathvector.h> class SvgFont; class SPFont; @@ -23,40 +23,47 @@ class SPGlyph; class SPMissingGlyph; class SPObject; -extern "C" { typedef struct _GdkEventExpose GdkEventExpose; } +extern "C" { +typedef struct _GdkEventExpose GdkEventExpose; +} namespace Gtk { class Widget; } -class UserFont { +class UserFont +{ public: - UserFont(SvgFont* instance); - cairo_font_face_t* face; + UserFont(SvgFont *instance); + cairo_font_face_t *face; }; -class SvgFont { +class SvgFont +{ public: - SvgFont(SPFont* spfont); + SvgFont(SPFont *spfont); void refresh(); - cairo_font_face_t* get_font_face(); - cairo_status_t scaled_font_init (cairo_scaled_font_t *scaled_font, cairo_font_extents_t *metrics); - cairo_status_t scaled_font_text_to_glyphs (cairo_scaled_font_t *scaled_font, const char *utf8, int utf8_len, cairo_glyph_t **glyphs, int *num_glyphs, cairo_text_cluster_t **clusters, int *num_clusters, cairo_text_cluster_flags_t *flags); - cairo_status_t scaled_font_render_glyph (cairo_scaled_font_t *scaled_font, unsigned long glyph, cairo_t *cr, cairo_text_extents_t *metrics); + cairo_font_face_t *get_font_face(); + cairo_status_t scaled_font_init(cairo_scaled_font_t *scaled_font, cairo_font_extents_t *metrics); + cairo_status_t scaled_font_text_to_glyphs(cairo_scaled_font_t *scaled_font, const char *utf8, int utf8_len, + cairo_glyph_t **glyphs, int *num_glyphs, cairo_text_cluster_t **clusters, + int *num_clusters, cairo_text_cluster_flags_t *flags); + cairo_status_t scaled_font_render_glyph(cairo_scaled_font_t *scaled_font, unsigned long glyph, cairo_t *cr, + cairo_text_extents_t *metrics); - Geom::PathVector flip_coordinate_system(SPFont* spfont, Geom::PathVector pathv); - void render_glyph_path(cairo_t* cr, Geom::PathVector* pathv); + Geom::PathVector flip_coordinate_system(SPFont *spfont, Geom::PathVector pathv); + void render_glyph_path(cairo_t *cr, Geom::PathVector *pathv); void glyph_modified(SPObject *, unsigned int); private: - SPFont* font; - UserFont* userfont; - std::vector glyphs; - SPMissingGlyph* missingglyph; + SPFont *font; + UserFont *userfont; + std::vector glyphs; + SPMissingGlyph *missingglyph; sigc::connection glyph_modified_connection; double units_per_em(); - //bool drawing_expose_cb (Gtk::Widget *widget, GdkEventExpose *event, void* data); + // bool drawing_expose_cb (Gtk::Widget *widget, GdkEventExpose *event, void* data); }; #endif //#ifndef NR_SVGFONTS_H_SEEN diff --git a/src/display/rendermode.h b/src/display/rendermode.h index ece8b58ca3b1aec2c32cdef1c0e06b60b5c41cf0..c9ad5be24d7ab32e9583f997efe68b0b82dc8d9c 100644 --- a/src/display/rendermode.h +++ b/src/display/rendermode.h @@ -18,20 +18,23 @@ namespace Inkscape { -enum RenderMode { +enum RenderMode +{ RENDERMODE_NORMAL, RENDERMODE_NO_FILTERS, RENDERMODE_OUTLINE, RENDERMODE_VISIBLE_HAIRLINES }; -enum SplitMode { +enum SplitMode +{ SPLITMODE_NORMAL, SPLITMODE_SPLIT, SPLITMODE_XRAY }; -enum SplitDirection { +enum SplitDirection +{ SPLITDIRECTION_NONE, SPLITDIRECTION_NORTH, SPLITDIRECTION_EAST, @@ -41,7 +44,8 @@ enum SplitDirection { SPLITDIRECTION_VERTICAL // Only used when hovering }; -enum ColorMode { +enum ColorMode +{ COLORMODE_NORMAL, COLORMODE_GRAYSCALE, COLORMODE_PRINT_COLORS_PREVIEW diff --git a/src/display/snap-indicator.cpp b/src/display/snap-indicator.cpp index cb798e612d3e422179c5446aa45b02bf0e71337a..9e5922fcaa3b06d65c391bc3ff3145e8fbaccd68 100644 --- a/src/display/snap-indicator.cpp +++ b/src/display/snap-indicator.cpp @@ -14,30 +14,29 @@ #include "display/snap-indicator.h" -#include "desktop.h" +#include +#include "desktop.h" +#include "display/canvas-text.h" #include "display/sodipodi-ctrl.h" #include "display/sodipodi-ctrlrect.h" -#include "display/canvas-text.h" #include "display/sp-canvas-util.h" +#include "enums.h" #include "knot.h" #include "preferences.h" -#include #include "ui/tools-switch.h" -#include "enums.h" namespace Inkscape { namespace Display { -SnapIndicator::SnapIndicator(SPDesktop * desktop) - : _snaptarget(nullptr), - _snaptarget_tooltip(nullptr), - _snaptarget_bbox(nullptr), - _snapsource(nullptr), - _snaptarget_is_presnap(false), - _desktop(desktop) -{ -} +SnapIndicator::SnapIndicator(SPDesktop *desktop) + : _snaptarget(nullptr) + , _snaptarget_tooltip(nullptr) + , _snaptarget_bbox(nullptr) + , _snapsource(nullptr) + , _snaptarget_is_presnap(false) + , _desktop(desktop) +{} SnapIndicator::~SnapIndicator() { @@ -46,10 +45,9 @@ SnapIndicator::~SnapIndicator() remove_snapsource(); } -void -SnapIndicator::set_new_snaptarget(Inkscape::SnappedPoint const &p, bool pre_snap) +void SnapIndicator::set_new_snaptarget(Inkscape::SnappedPoint const &p, bool pre_snap) { - remove_snaptarget(); //only display one snaptarget at a time + remove_snaptarget(); // only display one snaptarget at a time g_assert(_desktop != nullptr); @@ -241,21 +239,15 @@ SnapIndicator::set_new_snaptarget(Inkscape::SnappedPoint const &p, bool pre_snap g_warning("Snap source not in SnapSourceType enum"); break; } - //std::cout << "Snapped " << source_name << " to " << target_name << std::endl; + // std::cout << "Snapped " << source_name << " to " << target_name << std::endl; remove_snapsource(); // Don't set both the source and target indicators, as these will overlap // Display the snap indicator (i.e. the cross) - SPCanvasItem * canvasitem = nullptr; - canvasitem = sp_canvas_item_new(_desktop->getTempGroup(), - SP_TYPE_CTRL, - "anchor", SP_ANCHOR_CENTER, - "size", 11, - "stroked", TRUE, - "stroke_color", pre_snap ? 0x7f7f7fff : 0xff0000ff, - "mode", SP_KNOT_MODE_XOR, - "shape", SP_KNOT_SHAPE_CROSS, - NULL ); + SPCanvasItem *canvasitem = nullptr; + canvasitem = sp_canvas_item_new(_desktop->getTempGroup(), SP_TYPE_CTRL, "anchor", SP_ANCHOR_CENTER, "size", 11, + "stroked", TRUE, "stroke_color", pre_snap ? 0x7f7f7fff : 0xff0000ff, "mode", + SP_KNOT_MODE_XOR, "shape", SP_KNOT_SHAPE_CROSS, NULL); double timeout_val = prefs->getDouble("/options/snapindicatorpersistence/value", 2.0); if (timeout_val < 0.1) { @@ -263,7 +255,6 @@ SnapIndicator::set_new_snaptarget(Inkscape::SnappedPoint const &p, bool pre_snap // Besides, negatives values would ....? } - // The snap indicator will be deleted after some time-out, and sp_canvas_item_dispose // will be called. This will set canvas->current_item to NULL if the snap indicator was // the current item, after which any events will go to the root handler instead of any @@ -278,12 +269,12 @@ SnapIndicator::set_new_snaptarget(Inkscape::SnappedPoint const &p, bool pre_snap SP_CTRL(canvasitem)->pickable = false; SP_CTRL(canvasitem)->moveto(p.getPoint()); - _snaptarget = _desktop->add_temporary_canvasitem(canvasitem, timeout_val*1000.0); + _snaptarget = _desktop->add_temporary_canvasitem(canvasitem, timeout_val * 1000.0); _snaptarget_is_presnap = pre_snap; // Display the tooltip, which reveals the type of snap source and the type of snap target gchar *tooltip_str = nullptr; - if ( (p.getSource() != SNAPSOURCE_GRID_PITCH) && (p.getTarget() != SNAPTARGET_UNDEFINED) ) { + if ((p.getSource() != SNAPSOURCE_GRID_PITCH) && (p.getTarget() != SNAPTARGET_UNDEFINED)) { tooltip_str = g_strconcat(source_name, _(" to "), target_name, NULL); } else if (p.getSource() != SNAPSOURCE_UNDEFINED) { tooltip_str = g_strdup(source_name); @@ -294,12 +285,13 @@ SnapIndicator::set_new_snaptarget(Inkscape::SnappedPoint const &p, bool pre_snap Geom::Point tooltip_pos = p.getPoint(); if (tools_isactive(_desktop, TOOLS_MEASURE)) { // Make sure that the snap tooltips do not overlap the ones from the measure tool - tooltip_pos += _desktop->w2d(Geom::Point(0, -3*fontsize)); + tooltip_pos += _desktop->w2d(Geom::Point(0, -3 * fontsize)); } else { - tooltip_pos += _desktop->w2d(Geom::Point(0, -2*fontsize)); + tooltip_pos += _desktop->w2d(Geom::Point(0, -2 * fontsize)); } - SPCanvasItem *canvas_tooltip = sp_canvastext_new(_desktop->getTempGroup(), _desktop, tooltip_pos, tooltip_str); + SPCanvasItem *canvas_tooltip = + sp_canvastext_new(_desktop->getTempGroup(), _desktop, tooltip_pos, tooltip_str); sp_canvastext_set_fontsize(SP_CANVASTEXT(canvas_tooltip), fontsize); SP_CANVASTEXT(canvas_tooltip)->pickable = false; // See the extensive comment above SP_CANVASTEXT(canvas_tooltip)->rgba = 0xffffffff; @@ -313,28 +305,25 @@ SnapIndicator::set_new_snaptarget(Inkscape::SnappedPoint const &p, bool pre_snap SP_CANVASTEXT(canvas_tooltip)->anchor_position = TEXT_ANCHOR_CENTER; g_free(tooltip_str); - _snaptarget_tooltip = _desktop->add_temporary_canvasitem(canvas_tooltip, timeout_val*1000.0); + _snaptarget_tooltip = _desktop->add_temporary_canvasitem(canvas_tooltip, timeout_val * 1000.0); } // Display the bounding box, if we snapped to one Geom::OptRect const bbox = p.getTargetBBox(); if (bbox) { - SPCanvasItem* box = sp_canvas_item_new(_desktop->getTempGroup(), - SP_TYPE_CTRLRECT, - nullptr); + SPCanvasItem *box = sp_canvas_item_new(_desktop->getTempGroup(), SP_TYPE_CTRLRECT, nullptr); SP_CTRLRECT(box)->setRectangle(*bbox); SP_CTRLRECT(box)->setColor(pre_snap ? 0x7f7f7fff : 0xff0000ff, false, 0); SP_CTRLRECT(box)->setDashed(true); - SP_CTRLRECT(box)->pickable = false; // See the extensive comment above + SP_CTRLRECT(box)->pickable = false; // See the extensive comment above sp_canvas_item_move_to_z(box, 0); - _snaptarget_bbox = _desktop->add_temporary_canvasitem(box, timeout_val*1000.0); + _snaptarget_bbox = _desktop->add_temporary_canvasitem(box, timeout_val * 1000.0); } } } -void -SnapIndicator::remove_snaptarget(bool only_if_presnap) +void SnapIndicator::remove_snaptarget(bool only_if_presnap) { if (only_if_presnap && !_snaptarget_is_presnap) { return; @@ -355,56 +344,40 @@ SnapIndicator::remove_snaptarget(bool only_if_presnap) _desktop->remove_temporary_canvasitem(_snaptarget_bbox); _snaptarget_bbox = nullptr; } - } -void -SnapIndicator::set_new_snapsource(Inkscape::SnapCandidatePoint const &p) +void SnapIndicator::set_new_snapsource(Inkscape::SnapCandidatePoint const &p) { remove_snapsource(); - g_assert(_desktop != nullptr); // If this fails, then likely setup() has not been called on the snap manager (see snap.cpp -> setup()) + g_assert(_desktop != nullptr); // If this fails, then likely setup() has not been called on the snap manager (see + // snap.cpp -> setup()) Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool value = prefs->getBool("/options/snapindicator/value", true); if (value) { - SPCanvasItem * canvasitem = sp_canvas_item_new( _desktop->getTempGroup(), - SP_TYPE_CTRL, - "anchor", SP_ANCHOR_CENTER, - "size", 7, - "stroked", TRUE, - "stroke_color", 0xff0000ff, - "mode", SP_KNOT_MODE_XOR, - "shape", SP_KNOT_SHAPE_CIRCLE, - NULL ); + SPCanvasItem *canvasitem = sp_canvas_item_new( + _desktop->getTempGroup(), SP_TYPE_CTRL, "anchor", SP_ANCHOR_CENTER, "size", 7, "stroked", TRUE, + "stroke_color", 0xff0000ff, "mode", SP_KNOT_MODE_XOR, "shape", SP_KNOT_SHAPE_CIRCLE, NULL); SP_CTRL(canvasitem)->moveto(p.getPoint()); _snapsource = _desktop->add_temporary_canvasitem(canvasitem, 1000); } } -void -SnapIndicator::set_new_debugging_point(Geom::Point const &p) +void SnapIndicator::set_new_debugging_point(Geom::Point const &p) { g_assert(_desktop != nullptr); - SPCanvasItem * canvasitem = sp_canvas_item_new( _desktop->getTempGroup(), - SP_TYPE_CTRL, - "anchor", SP_ANCHOR_CENTER, - "size", 11, - "fill_color", 0x00ff00ff, - "stroked", FALSE, - "mode", SP_KNOT_MODE_XOR, - "shape", SP_KNOT_SHAPE_DIAMOND, - NULL ); + SPCanvasItem *canvasitem = sp_canvas_item_new(_desktop->getTempGroup(), SP_TYPE_CTRL, "anchor", SP_ANCHOR_CENTER, + "size", 11, "fill_color", 0x00ff00ff, "stroked", FALSE, "mode", + SP_KNOT_MODE_XOR, "shape", SP_KNOT_SHAPE_DIAMOND, NULL); SP_CTRL(canvasitem)->moveto(p); _debugging_points.push_back(_desktop->add_temporary_canvasitem(canvasitem, 5000)); - } -void -SnapIndicator::remove_snapsource() +void SnapIndicator::remove_snapsource() { if (_snapsource) { _desktop->remove_temporary_canvasitem(_snapsource); @@ -412,8 +385,7 @@ SnapIndicator::remove_snapsource() } } -void -SnapIndicator::remove_debugging_points() +void SnapIndicator::remove_debugging_points() { for (std::list::const_iterator i = _debugging_points.begin(); i != _debugging_points.end(); ++i) { _desktop->remove_temporary_canvasitem(*i); @@ -421,11 +393,9 @@ SnapIndicator::remove_debugging_points() _debugging_points.clear(); } - -} //namespace Display +} // namespace Display } /* namespace Inkscape */ - /* Local Variables: mode:c++ diff --git a/src/display/snap-indicator.h b/src/display/snap-indicator.h index 463acaf9f2682601781a674a557b9d407666777c..0356d4fed09cb2070c517d064742c784f63c178a 100644 --- a/src/display/snap-indicator.h +++ b/src/display/snap-indicator.h @@ -26,7 +26,8 @@ namespace Display { class TemporaryItem; -class SnapIndicator { +class SnapIndicator +{ public: SnapIndicator(SPDesktop *desktop); virtual ~SnapIndicator(); @@ -50,12 +51,12 @@ protected: SPDesktop *_desktop; private: - SnapIndicator(const SnapIndicator&) = delete; - SnapIndicator& operator=(const SnapIndicator&) = delete; + SnapIndicator(const SnapIndicator &) = delete; + SnapIndicator &operator=(const SnapIndicator &) = delete; }; -} //namespace Display -} //namespace Inkscape +} // namespace Display +} // namespace Inkscape #endif diff --git a/src/display/sodipodi-ctrl.cpp b/src/display/sodipodi-ctrl.cpp index 95144819a75e806209a660fe9fd740ca338addfe..b9f5f333ec197135324b178cbc8ec3fbd42b81b8 100644 --- a/src/display/sodipodi-ctrl.cpp +++ b/src/display/sodipodi-ctrl.cpp @@ -15,16 +15,17 @@ * */ -#include <2geom/transforms.h> +#include "sodipodi-ctrl.h" + #include <2geom/line.h> +#include <2geom/transforms.h> -#include "sp-canvas-util.h" -#include "sodipodi-ctrl.h" #include "cairo-utils.h" - +#include "sp-canvas-util.h" #include "ui/widget/canvas.h" // Request redraw -enum { +enum +{ ARG_0, ARG_SHAPE, ARG_MODE, @@ -39,44 +40,52 @@ enum { }; static void sp_ctrl_destroy(SPCanvasItem *object); -static void sp_ctrl_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec); -static void sp_ctrl_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec); -static void sp_ctrl_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); -static void sp_ctrl_render (SPCanvasItem *item, SPCanvasBuf *buf); +static void sp_ctrl_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec); +static void sp_ctrl_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec); +static void sp_ctrl_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); +static void sp_ctrl_render(SPCanvasItem *item, SPCanvasBuf *buf); -static double sp_ctrl_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item); +static double sp_ctrl_point(SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item); G_DEFINE_TYPE(SPCtrl, sp_ctrl, SP_TYPE_CANVAS_ITEM); -static void -sp_ctrl_class_init (SPCtrlClass *klass) +static void sp_ctrl_class_init(SPCtrlClass *klass) { SPCanvasItemClass *item_class = SP_CANVAS_ITEM_CLASS(klass); - GObjectClass *g_object_class = (GObjectClass *) klass; + GObjectClass *g_object_class = (GObjectClass *)klass; g_object_class->set_property = sp_ctrl_set_property; g_object_class->get_property = sp_ctrl_get_property; - g_object_class_install_property (g_object_class, - ARG_SHAPE, g_param_spec_int ("shape", "shape", "Shape", 0, G_MAXINT, SP_CTRL_SHAPE_SQUARE, (GParamFlags) G_PARAM_READWRITE)); - g_object_class_install_property (g_object_class, - ARG_MODE, g_param_spec_int ("mode", "mode", "Mode", 0, G_MAXINT, SP_CTRL_MODE_COLOR, (GParamFlags) G_PARAM_READWRITE)); - g_object_class_install_property (g_object_class, - ARG_ANCHOR, g_param_spec_int ("anchor", "anchor", "Anchor", 0, G_MAXINT, SP_ANCHOR_CENTER, (GParamFlags) G_PARAM_READWRITE)); - g_object_class_install_property (g_object_class, - ARG_SIZE, g_param_spec_uint ("size", "size", "Size", 0, G_MAXUINT, 7, (GParamFlags) G_PARAM_READWRITE)); - g_object_class_install_property (g_object_class, - ARG_ANGLE, g_param_spec_double ("angle", "angle", "Angle", -G_MAXDOUBLE, G_MAXDOUBLE, 0.0, (GParamFlags) G_PARAM_READWRITE)); - g_object_class_install_property (g_object_class, - ARG_FILLED, g_param_spec_boolean ("filled", "filled", "Filled", TRUE, (GParamFlags) G_PARAM_READWRITE)); - g_object_class_install_property (g_object_class, - ARG_FILL_COLOR, g_param_spec_int ("fill_color", "fill_color", "Fill Color", G_MININT, G_MAXINT, 0x000000ff, (GParamFlags) G_PARAM_READWRITE)); - g_object_class_install_property (g_object_class, - ARG_STROKED, g_param_spec_boolean ("stroked", "stroked", "Stroked", FALSE, (GParamFlags) G_PARAM_READWRITE)); - g_object_class_install_property (g_object_class, - ARG_STROKE_COLOR, g_param_spec_int ("stroke_color", "stroke_color", "Stroke Color", G_MININT, G_MAXINT, 0x000000ff, (GParamFlags) G_PARAM_READWRITE)); - g_object_class_install_property (g_object_class, - ARG_PIXBUF, g_param_spec_pointer ("pixbuf", "pixbuf", "Pixbuf", (GParamFlags) G_PARAM_READWRITE)); + g_object_class_install_property( + g_object_class, ARG_SHAPE, + g_param_spec_int("shape", "shape", "Shape", 0, G_MAXINT, SP_CTRL_SHAPE_SQUARE, (GParamFlags)G_PARAM_READWRITE)); + g_object_class_install_property( + g_object_class, ARG_MODE, + g_param_spec_int("mode", "mode", "Mode", 0, G_MAXINT, SP_CTRL_MODE_COLOR, (GParamFlags)G_PARAM_READWRITE)); + g_object_class_install_property( + g_object_class, ARG_ANCHOR, + g_param_spec_int("anchor", "anchor", "Anchor", 0, G_MAXINT, SP_ANCHOR_CENTER, (GParamFlags)G_PARAM_READWRITE)); + g_object_class_install_property( + g_object_class, ARG_SIZE, + g_param_spec_uint("size", "size", "Size", 0, G_MAXUINT, 7, (GParamFlags)G_PARAM_READWRITE)); + g_object_class_install_property( + g_object_class, ARG_ANGLE, + g_param_spec_double("angle", "angle", "Angle", -G_MAXDOUBLE, G_MAXDOUBLE, 0.0, (GParamFlags)G_PARAM_READWRITE)); + g_object_class_install_property( + g_object_class, ARG_FILLED, + g_param_spec_boolean("filled", "filled", "Filled", TRUE, (GParamFlags)G_PARAM_READWRITE)); + g_object_class_install_property(g_object_class, ARG_FILL_COLOR, + g_param_spec_int("fill_color", "fill_color", "Fill Color", G_MININT, G_MAXINT, + 0x000000ff, (GParamFlags)G_PARAM_READWRITE)); + g_object_class_install_property( + g_object_class, ARG_STROKED, + g_param_spec_boolean("stroked", "stroked", "Stroked", FALSE, (GParamFlags)G_PARAM_READWRITE)); + g_object_class_install_property(g_object_class, ARG_STROKE_COLOR, + g_param_spec_int("stroke_color", "stroke_color", "Stroke Color", G_MININT, G_MAXINT, + 0x000000ff, (GParamFlags)G_PARAM_READWRITE)); + g_object_class_install_property(g_object_class, ARG_PIXBUF, + g_param_spec_pointer("pixbuf", "pixbuf", "Pixbuf", (GParamFlags)G_PARAM_READWRITE)); item_class->destroy = sp_ctrl_destroy; item_class->update = sp_ctrl_update; @@ -84,75 +93,71 @@ sp_ctrl_class_init (SPCtrlClass *klass) item_class->point = sp_ctrl_point; } -static void -sp_ctrl_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) +static void sp_ctrl_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { - SPCanvasItem *item; SPCtrl *ctrl; - GdkPixbuf * pixbuf = nullptr; + GdkPixbuf *pixbuf = nullptr; - item = SP_CANVAS_ITEM (object); - ctrl = SP_CTRL (object); + item = SP_CANVAS_ITEM(object); + ctrl = SP_CTRL(object); switch (prop_id) { - case ARG_SHAPE: - ctrl->shape = (SPCtrlShapeType) g_value_get_int(value); - break; - case ARG_MODE: - ctrl->mode = (SPCtrlModeType) g_value_get_int(value); - break; - case ARG_ANCHOR: - ctrl->anchor = (SPAnchorType) g_value_get_int(value); - break; - case ARG_SIZE: - ctrl->width = g_value_get_uint(value); - ctrl->height = ctrl->width; - ctrl->defined = (ctrl->width > 0); - break; - case ARG_ANGLE: - ctrl->angle = (double)g_value_get_double(value); - break; - case ARG_FILLED: - ctrl->filled = g_value_get_boolean(value); - break; - case ARG_FILL_COLOR: - ctrl->fill_color = (guint32)g_value_get_int(value); - break; - case ARG_STROKED: - ctrl->stroked = g_value_get_boolean(value); - break; - case ARG_STROKE_COLOR: - ctrl->stroke_color = (guint32)g_value_get_int(value); - break; - case ARG_PIXBUF: - pixbuf = (GdkPixbuf*) g_value_get_pointer(value); - // A pixbuf defines it's own size, don't mess about with size. - ctrl->width = gdk_pixbuf_get_width(pixbuf); - ctrl->height = gdk_pixbuf_get_height(pixbuf); - if (gdk_pixbuf_get_has_alpha(pixbuf)) { - ctrl->pixbuf = pixbuf; - } else { - ctrl->pixbuf = gdk_pixbuf_add_alpha(pixbuf, FALSE, 0, 0, 0); - g_object_unref(pixbuf); - } - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); - return; // Do not do an update + case ARG_SHAPE: + ctrl->shape = (SPCtrlShapeType)g_value_get_int(value); + break; + case ARG_MODE: + ctrl->mode = (SPCtrlModeType)g_value_get_int(value); + break; + case ARG_ANCHOR: + ctrl->anchor = (SPAnchorType)g_value_get_int(value); + break; + case ARG_SIZE: + ctrl->width = g_value_get_uint(value); + ctrl->height = ctrl->width; + ctrl->defined = (ctrl->width > 0); + break; + case ARG_ANGLE: + ctrl->angle = (double)g_value_get_double(value); + break; + case ARG_FILLED: + ctrl->filled = g_value_get_boolean(value); + break; + case ARG_FILL_COLOR: + ctrl->fill_color = (guint32)g_value_get_int(value); + break; + case ARG_STROKED: + ctrl->stroked = g_value_get_boolean(value); + break; + case ARG_STROKE_COLOR: + ctrl->stroke_color = (guint32)g_value_get_int(value); + break; + case ARG_PIXBUF: + pixbuf = (GdkPixbuf *)g_value_get_pointer(value); + // A pixbuf defines it's own size, don't mess about with size. + ctrl->width = gdk_pixbuf_get_width(pixbuf); + ctrl->height = gdk_pixbuf_get_height(pixbuf); + if (gdk_pixbuf_get_has_alpha(pixbuf)) { + ctrl->pixbuf = pixbuf; + } else { + ctrl->pixbuf = gdk_pixbuf_add_alpha(pixbuf, FALSE, 0, 0, 0); + g_object_unref(pixbuf); + } + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); + return; // Do not do an update } ctrl->build = FALSE; sp_canvas_item_request_update(item); } -static void -sp_ctrl_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) +static void sp_ctrl_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { SPCtrl *ctrl; - ctrl = SP_CTRL (object); + ctrl = SP_CTRL(object); switch (prop_id) { - case ARG_SHAPE: g_value_set_int(value, ctrl->shape); break; @@ -197,10 +202,8 @@ sp_ctrl_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } - } -static void -sp_ctrl_init (SPCtrl *ctrl) +static void sp_ctrl_init(SPCtrl *ctrl) { ctrl->shape = SP_CTRL_SHAPE_SQUARE; ctrl->mode = SP_CTRL_MODE_COLOR; @@ -216,21 +219,21 @@ sp_ctrl_init (SPCtrl *ctrl) ctrl->stroke_color = 0x000000ff; ctrl->angle = 0.0; - new (&ctrl->box) Geom::IntRect(0,0,0,0); + new (&ctrl->box) Geom::IntRect(0, 0, 0, 0); ctrl->cache = nullptr; ctrl->pixbuf = nullptr; - ctrl->_point = Geom::Point(0,0); + ctrl->_point = Geom::Point(0, 0); ctrl->name = "SPCtrl"; } static void sp_ctrl_destroy(SPCanvasItem *object) { - g_return_if_fail (object != nullptr); - g_return_if_fail (SP_IS_CTRL (object)); + g_return_if_fail(object != nullptr); + g_return_if_fail(SP_IS_CTRL(object)); - SPCtrl *ctrl = SP_CTRL (object); + SPCtrl *ctrl = SP_CTRL(object); if (ctrl->cache) { delete[] ctrl->cache; @@ -241,25 +244,25 @@ static void sp_ctrl_destroy(SPCanvasItem *object) SP_CANVAS_ITEM_CLASS(sp_ctrl_parent_class)->destroy(object); } -static void -sp_ctrl_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) +static void sp_ctrl_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) { SPCtrl *ctrl; - ctrl = SP_CTRL (item); + ctrl = SP_CTRL(item); if (SP_CANVAS_ITEM_CLASS(sp_ctrl_parent_class)->update) SP_CANVAS_ITEM_CLASS(sp_ctrl_parent_class)->update(item, affine, flags); - sp_canvas_item_reset_bounds (item); + sp_canvas_item_reset_bounds(item); if (ctrl->shown) { item->canvas->redraw_area(ctrl->box.left(), ctrl->box.top(), ctrl->box.right() + 1, ctrl->box.bottom() + 1); } - if (!ctrl->defined) return; + if (!ctrl->defined) + return; - int w_half = floor(ctrl->width/2.0); - int h_half = floor(ctrl->height/2.0); + int w_half = floor(ctrl->width / 2.0); + int h_half = floor(ctrl->height / 2.0); int x = floor(affine[4]) - w_half; int y = floor(affine[5]) - h_half; @@ -303,39 +306,39 @@ sp_ctrl_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int fla } ctrl->box = Geom::IntRect::from_xywh(x, y, lround(ctrl->width), lround(ctrl->height)); - sp_canvas_update_bbox (item, ctrl->box.left(), ctrl->box.top(), ctrl->box.right() + 1, ctrl->box.bottom() + 1); + sp_canvas_update_bbox(item, ctrl->box.left(), ctrl->box.top(), ctrl->box.right() + 1, ctrl->box.bottom() + 1); } -static double -sp_ctrl_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item) +static double sp_ctrl_point(SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item) { - SPCtrl *ctrl = SP_CTRL (item); + SPCtrl *ctrl = SP_CTRL(item); *actual_item = item; - if (ctrl->box.contains(p.floor())) return 0.0; + if (ctrl->box.contains(p.floor())) + return 0.0; return 1e18; } -bool -sp_point_inside_line(Geom::Point a, Geom::Point b, Geom::Point c, double tolerance = 0.1) { +bool sp_point_inside_line(Geom::Point a, Geom::Point b, Geom::Point c, double tolerance = 0.1) +{ Geom::LineSegment segment(a, b); return Geom::are_near(c, segment, tolerance); } -bool -sp_point_inside_triangle(Geom::Point p1,Geom::Point p2,Geom::Point p3, Geom::Point point){ +bool sp_point_inside_triangle(Geom::Point p1, Geom::Point p2, Geom::Point p3, Geom::Point point) +{ using Geom::X; using Geom::Y; - double denominator = (p1[X]*(p2[Y] - p3[Y]) + p1[Y]*(p3[X] - p2[X]) + p2[X]*p3[Y] - p2[Y]*p3[X]); - double t1 = (point[X]*(p3[Y] - p1[Y]) + point[Y]*(p1[X] - p3[X]) - p1[X]*p3[Y] + p1[Y]*p3[X]) / denominator; - double t2 = (point[X]*(p2[Y] - p1[Y]) + point[Y]*(p1[X] - p2[X]) - p1[X]*p2[Y] + p1[Y]*p2[X]) / -denominator; + double denominator = (p1[X] * (p2[Y] - p3[Y]) + p1[Y] * (p3[X] - p2[X]) + p2[X] * p3[Y] - p2[Y] * p3[X]); + double t1 = (point[X] * (p3[Y] - p1[Y]) + point[Y] * (p1[X] - p3[X]) - p1[X] * p3[Y] + p1[Y] * p3[X]) / denominator; + double t2 = + (point[X] * (p2[Y] - p1[Y]) + point[Y] * (p1[X] - p2[X]) - p1[X] * p2[Y] + p1[Y] * p2[X]) / -denominator; double see = t1 + t2; return 0 <= t1 && t1 <= 1 && 0 <= t2 && t2 <= 1 && see <= 1; } -static void -sp_ctrl_build_cache (SPCtrl *ctrl, int device_scale) +static void sp_ctrl_build_cache(SPCtrl *ctrl, int device_scale) { guint32 stroke_color, fill_color; if (ctrl->filled) { @@ -358,26 +361,25 @@ sp_ctrl_build_cache (SPCtrl *ctrl, int device_scale) stroke_color = fill_color; } - gint width = ctrl->width * device_scale; + gint width = ctrl->width * device_scale; gint height = ctrl->height * device_scale; - if (width < 2) return; + if (width < 2) + return; gint size = width * height; - if (ctrl->cache) delete[] ctrl->cache; + if (ctrl->cache) + delete[] ctrl->cache; ctrl->cache = new guint32[size]; switch (ctrl->shape) { - case SP_CTRL_SHAPE_SQUARE: - { - guint32* p = ctrl->cache; + case SP_CTRL_SHAPE_SQUARE: { + guint32 *p = ctrl->cache; for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { - if ( i > device_scale - 1 && - j > device_scale - 1 && - width - i > device_scale && - height -j > device_scale) { + if (i > device_scale - 1 && j > device_scale - 1 && width - i > device_scale && + height - j > device_scale) { *p++ = fill_color; } else { *p++ = stroke_color; @@ -389,24 +391,19 @@ sp_ctrl_build_cache (SPCtrl *ctrl, int device_scale) break; } - case SP_CTRL_SHAPE_DIAMOND: - { + case SP_CTRL_SHAPE_DIAMOND: { // width == height - guint32* p = ctrl->cache; - int m = (width+1)/2; + guint32 *p = ctrl->cache; + int m = (width + 1) / 2; for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { - if ( i + j > m-1+device_scale && - (width-1-i) + j > m-1+device_scale && - (width-1-i) + (height-1-j) > m-1+device_scale && - i + (height-1-j) > m-1+device_scale ) { + if (i + j > m - 1 + device_scale && (width - 1 - i) + j > m - 1 + device_scale && + (width - 1 - i) + (height - 1 - j) > m - 1 + device_scale && + i + (height - 1 - j) > m - 1 + device_scale) { *p++ = fill_color; - } else - if ( i + j > m-2 && - (width-1-i) + j > m-2 && - (width-1-i) + (height-1-j) > m-2 && - i + (height-1-j) > m-2 ) { + } else if (i + j > m - 2 && (width - 1 - i) + j > m - 2 && + (width - 1 - i) + (height - 1 - j) > m - 2 && i + (height - 1 - j) > m - 2) { *p++ = stroke_color; } else { *p++ = 0; @@ -418,21 +415,19 @@ sp_ctrl_build_cache (SPCtrl *ctrl, int device_scale) break; } - case SP_CTRL_SHAPE_CIRCLE: - { - guint32* p = ctrl->cache; + case SP_CTRL_SHAPE_CIRCLE: { + guint32 *p = ctrl->cache; - double rs = width/2.0; - double rs2 = rs*rs; - double rf = rs-device_scale; - double rf2 = rf*rf; + double rs = width / 2.0; + double rs2 = rs * rs; + double rf = rs - device_scale; + double rf2 = rf * rf; for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { - - double rx = i - (width /2.0) + 0.5; - double ry = j - (height/2.0) + 0.5; - double r2 = rx*rx + ry*ry; + double rx = i - (width / 2.0) + 0.5; + double ry = j - (height / 2.0) + 0.5; + double r2 = rx * rx + ry * ry; if (r2 < rf2) { *p++ = fill_color; @@ -448,47 +443,45 @@ sp_ctrl_build_cache (SPCtrl *ctrl, int device_scale) break; } - case SP_CTRL_SHAPE_TRIANGLE: - { - guint* p = ctrl->cache; + case SP_CTRL_SHAPE_TRIANGLE: { + guint *p = ctrl->cache; - Geom::Affine m = Geom::Translate(Geom::Point(-width/2.0,-height/2.0)); + Geom::Affine m = Geom::Translate(Geom::Point(-width / 2.0, -height / 2.0)); m *= Geom::Rotate(-ctrl->angle); - m *= Geom::Translate(Geom::Point(width/2.0, height/2.0)); + m *= Geom::Translate(Geom::Point(width / 2.0, height / 2.0)); // Construct an arrowhead (triangle) of maximum size that won't leak out of rectangle // defined by width and height, assuming width == height. - double w2 = width/2.0; - double h2 = height/2.0; - double w2cos = w2 * cos( M_PI/6 ); - double h2sin = h2 * sin( M_PI/6 ); + double w2 = width / 2.0; + double h2 = height / 2.0; + double w2cos = w2 * cos(M_PI / 6); + double h2sin = h2 * sin(M_PI / 6); Geom::Point p1s(0, h2); Geom::Point p2s(w2 + w2cos, h2 + h2sin); Geom::Point p3s(w2 + w2cos, h2 - h2sin); // Needed for constructing smaller arrowhead below. - double theta = atan2( Geom::Point( p2s - p1s ) ); + double theta = atan2(Geom::Point(p2s - p1s)); p1s *= m; p2s *= m; p3s *= m; // Construct a smaller arrow head for fill. - Geom::Point p1f(device_scale/sin(theta), h2); - Geom::Point p2f(w2 + w2cos, h2 - h2sin + device_scale/cos(theta)); - Geom::Point p3f(w2 + w2cos, h2 + h2sin - device_scale/cos(theta)); + Geom::Point p1f(device_scale / sin(theta), h2); + Geom::Point p2f(w2 + w2cos, h2 - h2sin + device_scale / cos(theta)); + Geom::Point p3f(w2 + w2cos, h2 + h2sin - device_scale / cos(theta)); p1f *= m; p2f *= m; p3f *= m; - for(int y = 0; y < height; y++) { - for(int x = 0; x < width; x++) { - Geom::Point point = Geom::Point(x+0.5,y+0.5); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + Geom::Point point = Geom::Point(x + 0.5, y + 0.5); if (sp_point_inside_triangle(p1f, p2f, p3f, point)) { - p[(y*width)+x] = fill_color; - } else - if (sp_point_inside_triangle(p1s, p2s, p3s, point)) { - p[(y*width)+x] = stroke_color; + p[(y * width) + x] = fill_color; + } else if (sp_point_inside_triangle(p1s, p2s, p3s, point)) { + p[(y * width) + x] = stroke_color; } else { - p[(y*width)+x] = 0; + p[(y * width) + x] = 0; } } } @@ -497,13 +490,11 @@ sp_ctrl_build_cache (SPCtrl *ctrl, int device_scale) break; } - case SP_CTRL_SHAPE_CROSS: - { - guint* p = ctrl->cache; - for(int y = 0; y < height; y++) { - for(int x = 0; x < width; x++) { - if ( abs(x - y) < device_scale || - abs(width - 1 - x - y) < device_scale ) { + case SP_CTRL_SHAPE_CROSS: { + guint *p = ctrl->cache; + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (abs(x - y) < device_scale || abs(width - 1 - x - y) < device_scale) { *p++ = stroke_color; } else { *p++ = 0; @@ -515,14 +506,13 @@ sp_ctrl_build_cache (SPCtrl *ctrl, int device_scale) break; } - case SP_CTRL_SHAPE_BITMAP: - { + case SP_CTRL_SHAPE_BITMAP: { if (ctrl->pixbuf) { - unsigned char* px = gdk_pixbuf_get_pixels (ctrl->pixbuf); - unsigned int rs = gdk_pixbuf_get_rowstride (ctrl->pixbuf); - for (int y = 0; y < height/device_scale; y++){ - for (int x = 0; x < width/device_scale; x++) { - unsigned char *s = px + rs*y + 4*x; + unsigned char *px = gdk_pixbuf_get_pixels(ctrl->pixbuf); + unsigned int rs = gdk_pixbuf_get_rowstride(ctrl->pixbuf); + for (int y = 0; y < height / device_scale; y++) { + for (int x = 0; x < width / device_scale; x++) { + unsigned char *s = px + rs * y + 4 * x; guint32 color; if (s[3] < 0x80) { color = 0; @@ -535,45 +525,42 @@ sp_ctrl_build_cache (SPCtrl *ctrl, int device_scale) // Fill in device_scale x device_scale block for (int i = 0; i < device_scale; ++i) { for (int j = 0; j < device_scale; ++j) { - guint* p = ctrl->cache + - (x * device_scale + i) + // Column - (y * device_scale + j) * width; // Row + guint *p = ctrl->cache + (x * device_scale + i) + // Column + (y * device_scale + j) * width; // Row *p = color; } } } } } else { - g_print ("control has no pixbuf\n"); + g_print("control has no pixbuf\n"); } ctrl->build = TRUE; break; } - case SP_CTRL_SHAPE_IMAGE: - { + case SP_CTRL_SHAPE_IMAGE: { if (ctrl->pixbuf) { - guint rs = gdk_pixbuf_get_rowstride (ctrl->pixbuf); - guchar *data = gdk_pixbuf_get_pixels (ctrl->pixbuf); + guint rs = gdk_pixbuf_get_rowstride(ctrl->pixbuf); + guchar *data = gdk_pixbuf_get_pixels(ctrl->pixbuf); - for (int y = 0; y < height/device_scale; y++){ - for (int x = 0; x < width/device_scale; x++) { - guint32 *px = reinterpret_cast(data + rs*y + 4*x); + for (int y = 0; y < height / device_scale; y++) { + for (int x = 0; x < width / device_scale; x++) { + guint32 *px = reinterpret_cast(data + rs * y + 4 * x); // Fill in device_scale x device_scale block for (int i = 0; i < device_scale; ++i) { for (int j = 0; j < device_scale; ++j) { - guint* p = ctrl->cache + - (x * device_scale + i) + // Column - (y * device_scale + j) * width; // Row + guint *p = ctrl->cache + (x * device_scale + i) + // Column + (y * device_scale + j) * width; // Row *p = *px; } } } } } else { - g_print ("control has no pixbuf\n"); + g_print("control has no pixbuf\n"); } ctrl->build = TRUE; break; @@ -586,21 +573,22 @@ sp_ctrl_build_cache (SPCtrl *ctrl, int device_scale) static inline guint32 compose_xor(guint32 bg, guint32 fg, guint32 a) { - guint32 c = bg * (255-a) + (((bg ^ ~fg) + (bg >> 2) - (bg > 127 ? 63 : 0)) & 255) * a; + guint32 c = bg * (255 - a) + (((bg ^ ~fg) + (bg >> 2) - (bg > 127 ? 63 : 0)) & 255) * a; return (c + 127) / 255; } -static void -sp_ctrl_render (SPCanvasItem *item, SPCanvasBuf *buf) +static void sp_ctrl_render(SPCanvasItem *item, SPCanvasBuf *buf) { - SPCtrl *ctrl = SP_CTRL (item); + SPCtrl *ctrl = SP_CTRL(item); - if (!ctrl->defined) return; - if ((!ctrl->filled) && (!ctrl->stroked)) return; + if (!ctrl->defined) + return; + if ((!ctrl->filled) && (!ctrl->stroked)) + return; // the control-image is rendered into ctrl->cache if (!ctrl->build) { - sp_ctrl_build_cache (ctrl, buf->device_scale); + sp_ctrl_build_cache(ctrl, buf->device_scale); } // Must match width/height sp_ctrl_build_cache. @@ -612,13 +600,12 @@ sp_ctrl_render (SPCanvasItem *item, SPCanvasBuf *buf) // The code below works even when the target is not an image surface if (ctrl->mode == SP_CTRL_MODE_XOR) { - // 1. Copy the affected part of output to a temporary surface // Size in device pixels. Does not set device scale. cairo_surface_t *work = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h); cairo_surface_set_device_scale(work, buf->device_scale, buf->device_scale); - + cairo_t *cr = cairo_create(work); cairo_translate(cr, -ctrl->box.left(), -ctrl->box.top()); cairo_set_source_surface(cr, cairo_get_target(buf->ct), buf->rect.left(), buf->rect.top()); @@ -632,19 +619,19 @@ sp_ctrl_render (SPCanvasItem *item, SPCanvasBuf *buf) unsigned char *pxb = cairo_image_surface_get_data(work); guint32 *p = ctrl->cache; - for (int i=0; i(pxb + i*strideb); - for (int j=0; j(pxb + i * strideb); + for (int j = 0; j < w; ++j) { guint32 cc = *p++; guint32 ac = cc & 0xff; if (ac == 0 && cc != 0) { *pb++ = argb32_from_rgba(cc | 0x000000ff); } else { - EXTRACT_ARGB32(*pb, ab,rb,gb,bb) + EXTRACT_ARGB32(*pb, ab, rb, gb, bb) guint32 ro = compose_xor(rb, (cc & 0xff000000) >> 24, ac); guint32 go = compose_xor(gb, (cc & 0x00ff0000) >> 16, ac); - guint32 bo = compose_xor(bb, (cc & 0x0000ff00) >> 8, ac); - ASSEMBLE_ARGB32(px, ab,ro,go,bo) + guint32 bo = compose_xor(bb, (cc & 0x0000ff00) >> 8, ac); + ASSEMBLE_ARGB32(px, ab, ro, go, bo) *pb++ = px; } } @@ -655,38 +642,37 @@ sp_ctrl_render (SPCanvasItem *item, SPCanvasBuf *buf) // 3. Replace the affected part of output with contents of temporary surface cairo_save(buf->ct); cairo_set_source_surface(buf->ct, work, x, y); - cairo_rectangle(buf->ct, x, y, w/buf->device_scale, h/buf->device_scale); + cairo_rectangle(buf->ct, x, y, w / buf->device_scale, h / buf->device_scale); cairo_clip(buf->ct); cairo_set_operator(buf->ct, CAIRO_OPERATOR_SOURCE); cairo_paint(buf->ct); cairo_restore(buf->ct); cairo_surface_destroy(work); } else { - cairo_surface_t *cache = cairo_image_surface_create_for_data( - reinterpret_cast(ctrl->cache), CAIRO_FORMAT_ARGB32, w, h, w*4); + cairo_surface_t *cache = cairo_image_surface_create_for_data(reinterpret_cast(ctrl->cache), + CAIRO_FORMAT_ARGB32, w, h, w * 4); cairo_surface_set_device_scale(cache, buf->device_scale, buf->device_scale); cairo_surface_mark_dirty(cache); cairo_save(buf->ct); cairo_set_source_surface(buf->ct, cache, x, y); - cairo_rectangle(buf->ct, x, y, w/buf->device_scale, h/buf->device_scale); + cairo_rectangle(buf->ct, x, y, w / buf->device_scale, h / buf->device_scale); cairo_clip(buf->ct); cairo_paint(buf->ct); // cairo_surface_write_to_png(cache, "ctrl_cache.png" ); cairo_restore(buf->ct); cairo_surface_destroy(cache); - } ctrl->shown = TRUE; } -void SPCtrl::moveto (Geom::Point const p) { +void SPCtrl::moveto(Geom::Point const p) +{ if (p != _point) { - sp_canvas_item_affine_absolute (SP_CANVAS_ITEM (this), Geom::Affine(Geom::Translate (p))); + sp_canvas_item_affine_absolute(SP_CANVAS_ITEM(this), Geom::Affine(Geom::Translate(p))); } _point = p; } - /* Local Variables: mode:c++ diff --git a/src/display/sodipodi-ctrl.h b/src/display/sodipodi-ctrl.h index 184c77eecea2194ab1cefcf2679f9e5a741633f3..19972f168defd9ac8fe8f2188166dd762d27a69f 100644 --- a/src/display/sodipodi-ctrl.h +++ b/src/display/sodipodi-ctrl.h @@ -17,17 +17,18 @@ */ #include -#include "sp-canvas-item.h" -#include "enums.h" +#include "enums.h" +#include "sp-canvas-item.h" -#define SP_TYPE_CTRL (sp_ctrl_get_type ()) -#define SP_CTRL(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SP_TYPE_CTRL, SPCtrl)) -#define SP_CTRL_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), SP_TYPE_CTRL, SPCtrlClass)) -#define SP_IS_CTRL(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SP_TYPE_CTRL)) -#define SP_IS_CTRL_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), SP_TYPE_CTRL)) +#define SP_TYPE_CTRL (sp_ctrl_get_type()) +#define SP_CTRL(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CTRL, SPCtrl)) +#define SP_CTRL_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), SP_TYPE_CTRL, SPCtrlClass)) +#define SP_IS_CTRL(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CTRL)) +#define SP_IS_CTRL_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), SP_TYPE_CTRL)) -enum SPCtrlShapeType { +enum SPCtrlShapeType +{ SP_CTRL_SHAPE_SQUARE, SP_CTRL_SHAPE_DIAMOND, SP_CTRL_SHAPE_CIRCLE, @@ -37,44 +38,43 @@ enum SPCtrlShapeType { SP_CTRL_SHAPE_IMAGE }; - -enum SPCtrlModeType { +enum SPCtrlModeType +{ SP_CTRL_MODE_COLOR, SP_CTRL_MODE_XOR }; -struct SPCtrl : public SPCanvasItem { +struct SPCtrl : public SPCanvasItem +{ SPCtrlShapeType shape; SPCtrlModeType mode; SPAnchorType anchor; unsigned int width; unsigned int height; - + guint defined : 1; - guint shown : 1; - guint build : 1; - guint filled : 1; + guint shown : 1; + guint build : 1; + guint filled : 1; guint stroked : 1; guint32 fill_color; guint32 stroke_color; gdouble angle; - Geom::IntRect box; /* NB! x1 & y1 are included */ + Geom::IntRect box; /* NB! x1 & y1 are included */ guint32 *cache; - GdkPixbuf * pixbuf; + GdkPixbuf *pixbuf; void moveto(Geom::Point const p); Geom::Point _point; }; -struct SPCtrlClass : public SPCanvasItemClass{ +struct SPCtrlClass : public SPCanvasItemClass +{ }; - - /* Standard Gtk function */ -GType sp_ctrl_get_type (); - +GType sp_ctrl_get_type(); #endif /* !INKSCAPE_CTRL_H */ diff --git a/src/display/sodipodi-ctrlrect.cpp b/src/display/sodipodi-ctrlrect.cpp index 2043a8c20252c8169c9c3f4192d9cb8e03c6b4c7..81b19308444cdbc4681f7d92f0f081d3b3e66de7 100644 --- a/src/display/sodipodi-ctrlrect.cpp +++ b/src/display/sodipodi-ctrlrect.cpp @@ -17,12 +17,14 @@ * */ -#include "inkscape.h" #include "sodipodi-ctrlrect.h" -#include "sp-canvas-util.h" -#include "display/cairo-utils.h" + #include <2geom/transforms.h> +#include "display/cairo-utils.h" +#include "inkscape.h" +#include "sp-canvas-util.h" + /* * Currently we do not have point method, as it should always be painted * during some transformation, which takes care of events... @@ -55,24 +57,20 @@ static void sp_ctrlrect_init(CtrlRect *cr) static void sp_ctrlrect_destroy(SPCanvasItem *object) { if (SP_CANVAS_ITEM_CLASS(sp_ctrlrect_parent_class)->destroy) { - (* SP_CANVAS_ITEM_CLASS(sp_ctrlrect_parent_class)->destroy)(object); + (*SP_CANVAS_ITEM_CLASS(sp_ctrlrect_parent_class)->destroy)(object); } } - static void sp_ctrlrect_render(SPCanvasItem *item, SPCanvasBuf *buf) { SP_CTRLRECT(item)->render(buf); } - static void sp_ctrlrect_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) { SP_CTRLRECT(item)->update(affine, flags); } - - void CtrlRect::init() { _has_fill = false; @@ -83,7 +81,7 @@ void CtrlRect::init() _area = Geom::OptIntRect(); - _rect = Geom::Rect(Geom::Point(0,0),Geom::Point(0,0)); + _rect = Geom::Rect(Geom::Point(0, 0), Geom::Point(0, 0)); _border_color = 0x000000ff; _fill_color = 0xffffffff; @@ -91,7 +89,6 @@ void CtrlRect::init() _inverted = false; } - void CtrlRect::render(SPCanvasBuf *buf) { using Geom::X; @@ -102,18 +99,16 @@ void CtrlRect::render(SPCanvasBuf *buf) } Geom::IntRect area = *_area; // _area already includes space for shadow. - if ( area.intersects(buf->rect) ) - { - + if (area.intersects(buf->rect)) { cairo_save(buf->ct); cairo_translate(buf->ct, -buf->rect.left(), -buf->rect.top()); - + // Get canvas rotation (scale is isotropic). - double rotation = atan2( _affine[1], _affine[0] ); + double rotation = atan2(_affine[1], _affine[0]); // Are we axis aligned? double mod_rot = fmod(rotation * M_2_PI, 1); - bool axis_aligned = Geom::are_near( mod_rot, 0 ) || Geom::are_near( mod_rot, 1.0 ); + bool axis_aligned = Geom::are_near(mod_rot, 0) || Geom::are_near(mod_rot, 1.0); // Get the points we need transformed to window coordinates. Geom::Point rect_transformed[4]; @@ -121,13 +116,13 @@ void CtrlRect::render(SPCanvasBuf *buf) rect_transformed[i] = _rect.corner(i) * _affine; } - if(_inverted) { + if (_inverted) { cairo_set_operator(buf->ct, CAIRO_OPERATOR_DIFFERENCE); } // Draw shadow first. Shadow extends under rectangle to reduce aliasing effects. if (_shadow_width > 0 && !_dashed) { - Geom::Point const * corners = rect_transformed; + Geom::Point const *corners = rect_transformed; double shadowydir = _affine.det() > 0 ? -1 : 1; // is the desktop y-axis downwards? @@ -138,56 +133,42 @@ void CtrlRect::render(SPCanvasBuf *buf) // Offset by half stroke width (_shadow_width is in window coordinates). // Need to handle change in handedness with flips. - Geom::Point shadow( _shadow_width/2.0, shadowydir * _shadow_width/2.0 ); - shadow *= Geom::Rotate( rotation ); + Geom::Point shadow(_shadow_width / 2.0, shadowydir * _shadow_width / 2.0); + shadow *= Geom::Rotate(rotation); if (axis_aligned) { // Snap to pixel grid (add 0.5 to center on pixel). - cairo_move_to( buf->ct, - floor(corners[0][X] + shadow[X]+0.5) + 0.5, - floor(corners[0][Y] + shadow[Y]+0.5) + 0.5 ); - cairo_line_to( buf->ct, - floor(corners[1][X] + shadow[X]+0.5) + 0.5, - floor(corners[1][Y] + shadow[Y]+0.5) + 0.5 ); - cairo_line_to( buf->ct, - floor(corners[2][X] + shadow[X]+0.5) + 0.5, - floor(corners[2][Y] + shadow[Y]+0.5) + 0.5 ); + cairo_move_to(buf->ct, floor(corners[0][X] + shadow[X] + 0.5) + 0.5, + floor(corners[0][Y] + shadow[Y] + 0.5) + 0.5); + cairo_line_to(buf->ct, floor(corners[1][X] + shadow[X] + 0.5) + 0.5, + floor(corners[1][Y] + shadow[Y] + 0.5) + 0.5); + cairo_line_to(buf->ct, floor(corners[2][X] + shadow[X] + 0.5) + 0.5, + floor(corners[2][Y] + shadow[Y] + 0.5) + 0.5); } else { - cairo_move_to( buf->ct, - corners[0][X] + shadow[X], - corners[0][Y] + shadow[Y] ); - cairo_line_to( buf->ct, - corners[1][X] + shadow[X], - corners[1][Y] + shadow[Y] ); - cairo_line_to( buf->ct, - corners[2][X] + shadow[X], - corners[2][Y] + shadow[Y] ); - } - - ink_cairo_set_source_rgba32( buf->ct, _shadow_color ); - cairo_set_line_width( buf->ct, _shadow_width + 1 ); - cairo_stroke( buf->ct ); - } + cairo_move_to(buf->ct, corners[0][X] + shadow[X], corners[0][Y] + shadow[Y]); + cairo_line_to(buf->ct, corners[1][X] + shadow[X], corners[1][Y] + shadow[Y]); + cairo_line_to(buf->ct, corners[2][X] + shadow[X], corners[2][Y] + shadow[Y]); + } + ink_cairo_set_source_rgba32(buf->ct, _shadow_color); + cairo_set_line_width(buf->ct, _shadow_width + 1); + cairo_stroke(buf->ct); + } // Setup rectangle path if (axis_aligned) { - // Snap to pixel grid - Geom::Rect outline( _rect.min() * _affine, _rect.max() * _affine); - cairo_rectangle (buf->ct, - floor(outline.min()[X])+0.5, - floor(outline.min()[Y])+0.5, - floor(outline.max()[X]) - floor(outline.min()[X]), - floor(outline.max()[Y]) - floor(outline.min()[Y])); + Geom::Rect outline(_rect.min() * _affine, _rect.max() * _affine); + cairo_rectangle(buf->ct, floor(outline.min()[X]) + 0.5, floor(outline.min()[Y]) + 0.5, + floor(outline.max()[X]) - floor(outline.min()[X]), + floor(outline.max()[Y]) - floor(outline.min()[Y])); } else { - // Angled - cairo_move_to( buf->ct, rect_transformed[0][X], rect_transformed[0][Y] ); - cairo_line_to( buf->ct, rect_transformed[1][X], rect_transformed[1][Y] ); - cairo_line_to( buf->ct, rect_transformed[2][X], rect_transformed[2][Y] ); - cairo_line_to( buf->ct, rect_transformed[3][X], rect_transformed[3][Y] ); - cairo_close_path( buf->ct ); + cairo_move_to(buf->ct, rect_transformed[0][X], rect_transformed[0][Y]); + cairo_line_to(buf->ct, rect_transformed[1][X], rect_transformed[1][Y]); + cairo_line_to(buf->ct, rect_transformed[2][X], rect_transformed[2][Y]); + cairo_line_to(buf->ct, rect_transformed[3][X], rect_transformed[3][Y]); + cairo_close_path(buf->ct); } // This doesn't seem to be used anywhere. If it is, then we should @@ -208,7 +189,8 @@ void CtrlRect::render(SPCanvasBuf *buf) ink_cairo_set_source_rgba32(buf->ct, _border_color); cairo_set_line_width(buf->ct, 1); static double const dashes[2] = {4.0, 4.0}; - if (_dashed) cairo_set_dash(buf->ct, dashes, 2, 0); + if (_dashed) + cairo_set_dash(buf->ct, dashes, 2, 0); // Stroke rectangle. cairo_stroke_preserve(buf->ct); @@ -225,7 +207,6 @@ void CtrlRect::render(SPCanvasBuf *buf) } } - void CtrlRect::update(Geom::Affine const &affine, unsigned int flags) { using Geom::X; @@ -243,7 +224,7 @@ void CtrlRect::update(Geom::Affine const &affine, unsigned int flags) bbox *= affine; // Enlarge bbox by twice shadow size (to allow for shadow on any side with a 45deg rotation). - bbox.expandBy( 2.0 *_shadow_width ); + bbox.expandBy(2.0 * _shadow_width); // Generate an integer rectangle that includes bbox. Geom::OptIntRect _area_old = _area; @@ -267,7 +248,6 @@ void CtrlRect::update(Geom::Affine const &affine, unsigned int flags) _affine = affine; } - void CtrlRect::setColor(guint32 b, bool h, guint f) { _border_color = b; @@ -283,7 +263,8 @@ void CtrlRect::setShadow(int s, guint c) _requestUpdate(); } -void CtrlRect::setInvert(bool invert) { +void CtrlRect::setInvert(bool invert) +{ _inverted = invert; _requestUpdate(); } diff --git a/src/display/sodipodi-ctrlrect.h b/src/display/sodipodi-ctrlrect.h index cdc4a3de61dc1ca9df34e86bb93e091f609cc661..a92692a37a2215412914af791134cfc21557afbd 100644 --- a/src/display/sodipodi-ctrlrect.h +++ b/src/display/sodipodi-ctrlrect.h @@ -21,24 +21,24 @@ * */ -#include -#include "sp-canvas-item.h" -#include <2geom/rect.h> #include <2geom/int-rect.h> +#include <2geom/rect.h> #include <2geom/transforms.h> +#include + +#include "sp-canvas-item.h" struct SPCanvasBuf; -#define SP_TYPE_CTRLRECT (sp_ctrlrect_get_type ()) +#define SP_TYPE_CTRLRECT (sp_ctrlrect_get_type()) #define SP_CTRLRECT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CTRLRECT, CtrlRect)) #define SP_CTRLRECT_CLASS(c) (G_TYPE_CHECK_CLASS_CAST((c), SP_TYPE_CTRLRECT, CtrlRectClass)) -#define SP_IS_CTRLRECT(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SP_TYPE_CTRLRECT)) -#define SP_IS_CTRLRECT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), SP_TYPE_CTRLRECT)) +#define SP_IS_CTRLRECT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CTRLRECT)) +#define SP_IS_CTRLRECT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), SP_TYPE_CTRLRECT)) class CtrlRect : public SPCanvasItem { public: - void init(); void setColor(guint32 b, bool h, guint f); void setShadow(int s, guint c); @@ -49,10 +49,10 @@ public: void render(SPCanvasBuf *buf); void update(Geom::Affine const &affine, unsigned int flags); - + private: void _requestUpdate(); - + Geom::Rect _rect; Geom::Affine _affine; @@ -65,10 +65,12 @@ private: gint _shadow_width; guint32 _border_color; guint32 _fill_color; - guint32 _shadow_color; + guint32 _shadow_color; }; -struct CtrlRectClass : public SPCanvasItemClass {}; +struct CtrlRectClass : public SPCanvasItemClass +{ +}; GType sp_ctrlrect_get_type(); diff --git a/src/display/sp-canvas-group.cpp b/src/display/sp-canvas-group.cpp index dfa88cb1c37e1bd93c3c7a762328ce8af614669f..80f970d13c7cecf255c2abad6f6c75c890e2f3e2 100644 --- a/src/display/sp-canvas-group.cpp +++ b/src/display/sp-canvas-group.cpp @@ -19,7 +19,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include "sp-canvas-group.h" @@ -39,7 +39,7 @@ static void sp_canvas_group_class_init(SPCanvasGroupClass *klass) item_class->viewbox_changed = SPCanvasGroup::viewboxChanged; } -static void sp_canvas_group_init(SPCanvasGroup * group) +static void sp_canvas_group_init(SPCanvasGroup *group) { new (&group->items) SPCanvasItemList; SP_CANVAS_ITEM(group)->name = "CanvasGroup"; @@ -62,7 +62,7 @@ void SPCanvasGroup::destroy(SPCanvasItem *object) group->items.~SPCanvasItemList(); // invoke manually if (SP_CANVAS_ITEM_CLASS(sp_canvas_group_parent_class)->destroy) { - (* SP_CANVAS_ITEM_CLASS(sp_canvas_group_parent_class)->destroy)(object); + (*SP_CANVAS_ITEM_CLASS(sp_canvas_group_parent_class)->destroy)(object); } } @@ -71,12 +71,12 @@ void SPCanvasGroup::update(SPCanvasItem *item, Geom::Affine const &affine, unsig SPCanvasGroup *group = SP_CANVAS_GROUP(item); Geom::OptRect bounds; - for (auto & item : group->items) { + for (auto &item : group->items) { SPCanvasItem *i = &item; - sp_canvas_item_invoke_update (i, affine, flags); + sp_canvas_item_invoke_update(i, affine, flags); - if ( (i->x2 > i->x1) && (i->y2 > i->y1) ) { + if ((i->x2 > i->x1) && (i->y2 > i->y1)) { bounds.expandTo(Geom::Point(i->x1, i->y1)); bounds.expandTo(Geom::Point(i->x2, i->y2)); } @@ -103,7 +103,7 @@ double SPCanvasGroup::point(SPCanvasItem *item, Geom::Point p, SPCanvasItem **ac *actual_item = nullptr; double dist = 0.0; - for (auto & it : group->items) { + for (auto &it : group->items) { SPCanvasItem *child = ⁢ if ((child->x1 <= x) && (x <= child->x2) && (child->y1 <= y) && (y <= child->y2)) { @@ -123,7 +123,7 @@ double SPCanvasGroup::point(SPCanvasItem *item, Geom::Point p, SPCanvasItem **ac // of the item to be focused, and have that one selected. Of course this will only work if the // centers are not coincident, but at least it's better than what we have now. // See the extensive comment in Inkscape::SelTrans::_updateHandles() - if (pickable && point_item && ((int) (dist + 0.5) <= 0)) { // THIS IS NEVER TRUE! + if (pickable && point_item && ((int)(dist + 0.5) <= 0)) { // THIS IS NEVER TRUE! best = dist; *actual_item = point_item; } @@ -137,12 +137,10 @@ void SPCanvasGroup::render(SPCanvasItem *item, SPCanvasBuf *buf) { SPCanvasGroup *group = SP_CANVAS_GROUP(item); - for (auto & item : group->items) { + for (auto &item : group->items) { SPCanvasItem *child = &item; if (child->visible) { - if ((child->x1 < buf->rect.right()) && - (child->y1 < buf->rect.bottom()) && - (child->x2 > buf->rect.left()) && + if ((child->x1 < buf->rect.right()) && (child->y1 < buf->rect.bottom()) && (child->x2 > buf->rect.left()) && (child->y2 > buf->rect.top())) { if (SP_CANVAS_ITEM_GET_CLASS(child)->render) { SP_CANVAS_ITEM_GET_CLASS(child)->render(child, buf); @@ -155,7 +153,7 @@ void SPCanvasGroup::render(SPCanvasItem *item, SPCanvasBuf *buf) void SPCanvasGroup::viewboxChanged(SPCanvasItem *item, Geom::IntRect const &new_area) { SPCanvasGroup *group = SP_CANVAS_GROUP(item); - for (auto & item : group->items) { + for (auto &item : group->items) { SPCanvasItem *child = &item; if (child->visible) { if (SP_CANVAS_ITEM_GET_CLASS(child)->viewbox_changed) { @@ -187,11 +185,8 @@ void SPCanvasGroup::remove(SPCanvasItem *item) // Unparent the child item->parent = nullptr; g_object_unref(item); - } - - /* Local Variables: mode:c++ diff --git a/src/display/sp-canvas-group.h b/src/display/sp-canvas-group.h index 03acfbecb35573ef1627eb368366492b26e25c4b..f599c86b864be7139c37433efa7ff91ff795a5af 100644 --- a/src/display/sp-canvas-group.h +++ b/src/display/sp-canvas-group.h @@ -24,7 +24,6 @@ #include "sp-canvas-item.h" - #define SP_TYPE_CANVAS_GROUP (sp_canvas_group_get_type()) #define SP_CANVAS_GROUP(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CANVAS_GROUP, SPCanvasGroup)) #define SP_IS_CANVAS_GROUP(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CANVAS_GROUP)) @@ -34,15 +33,16 @@ GType sp_canvas_group_get_type(); /** * The SPCanvasGroup vtable. */ -struct SPCanvasGroupClass { +struct SPCanvasGroupClass +{ SPCanvasItemClass parent_class; }; - /** * A group of items. */ -struct SPCanvasGroup { +struct SPCanvasGroup +{ /** * Adds an item to a canvas group. */ @@ -86,7 +86,6 @@ struct SPCanvasGroup { static void viewboxChanged(SPCanvasItem *item, Geom::IntRect const &new_area); - // Data members: ---------------------------------------------------------- SPCanvasItem item; @@ -94,7 +93,6 @@ struct SPCanvasGroup { SPCanvasItemList items; }; - #endif // SEEN_SP_CANVAS_GROUP_H /* diff --git a/src/display/sp-canvas-item.cpp b/src/display/sp-canvas-item.cpp index d3636b315484eb78411a04a3780b8b1f10543d2b..1e21d501ec40da4fc1842cd4090122f2254f9ed2 100644 --- a/src/display/sp-canvas-item.cpp +++ b/src/display/sp-canvas-item.cpp @@ -19,38 +19,36 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include -#include "sp-canvas-item.h" -#include "sp-canvas-group.h" -#include "sodipodi-ctrlrect.h" - #include "helper/sp-marshal.h" - +#include "sodipodi-ctrlrect.h" +#include "sp-canvas-group.h" +#include "sp-canvas-item.h" #include "ui/widget/canvas.h" void trackLatency(GdkEvent const *event); -enum { - DESTROY, - LAST_SIGNAL +enum +{ + DESTROY, + LAST_SIGNAL }; -static guint object_signals[LAST_SIGNAL] = { 0 }; +static guint object_signals[LAST_SIGNAL] = {0}; guint item_signals[] = {0}; /** * Callback that removes item from all referrers and destroys it. */ -void sp_canvas_item_dispose(GObject *object); -void sp_canvas_item_finalize(GObject *object); +void sp_canvas_item_dispose(GObject *object); +void sp_canvas_item_finalize(GObject *object); void sp_canvas_item_real_destroy(SPCanvasItem *object); - /** * Sets up the newly created SPCanvasItem. * @@ -63,40 +61,27 @@ void sp_canvas_item_construct(SPCanvasItem *item, SPCanvasGroup *parent, gchar c */ bool is_descendant(SPCanvasItem const *item, SPCanvasItem const *parent); - - G_DEFINE_TYPE(SPCanvasItem, sp_canvas_item, G_TYPE_INITIALLY_UNOWNED); -static void -sp_canvas_item_class_init(SPCanvasItemClass *klass) +static void sp_canvas_item_class_init(SPCanvasItemClass *klass) { - GObjectClass *gobject_class = (GObjectClass *) klass; - - item_signals[ITEM_EVENT] = g_signal_new ("event", - G_TYPE_FROM_CLASS (klass), - G_SIGNAL_RUN_LAST, - ((glong)((guint8*)&(klass->event) - (guint8*)klass)), - nullptr, nullptr, - sp_marshal_BOOLEAN__POINTER, - G_TYPE_BOOLEAN, 1, - GDK_TYPE_EVENT); - - gobject_class->dispose = sp_canvas_item_dispose; + GObjectClass *gobject_class = (GObjectClass *)klass; + + item_signals[ITEM_EVENT] = g_signal_new("event", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_LAST, + ((glong)((guint8 *)&(klass->event) - (guint8 *)klass)), nullptr, nullptr, + sp_marshal_BOOLEAN__POINTER, G_TYPE_BOOLEAN, 1, GDK_TYPE_EVENT); + + gobject_class->dispose = sp_canvas_item_dispose; gobject_class->finalize = sp_canvas_item_finalize; - klass->destroy = sp_canvas_item_real_destroy; - - object_signals[DESTROY] = - g_signal_new ("destroy", - G_TYPE_FROM_CLASS (gobject_class), - (GSignalFlags)(G_SIGNAL_RUN_CLEANUP | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS), - G_STRUCT_OFFSET (SPCanvasItemClass, destroy), - nullptr, nullptr, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0); + klass->destroy = sp_canvas_item_real_destroy; + + object_signals[DESTROY] = g_signal_new( + "destroy", G_TYPE_FROM_CLASS(gobject_class), + (GSignalFlags)(G_SIGNAL_RUN_CLEANUP | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS), + G_STRUCT_OFFSET(SPCanvasItemClass, destroy), nullptr, nullptr, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); } -static void -sp_canvas_item_init(SPCanvasItem *item) +static void sp_canvas_item_init(SPCanvasItem *item) { item->xform = Geom::Affine(Geom::identity()); item->ctrlResize = 0; @@ -157,52 +142,52 @@ static void redraw_if_visible(SPCanvasItem *item) int y0 = (int)(item->y1); int y1 = (int)(item->y2); - if (x0 !=0 || x1 !=0 || y0 !=0 || y1 !=0) { - item->canvas->redraw_area((int)(item->x1 - 1), (int)(item->y1 -1), (int)(item->x2 + 1), (int)(item->y2 + 1)); + if (x0 != 0 || x1 != 0 || y0 != 0 || y1 != 0) { + item->canvas->redraw_area((int)(item->x1 - 1), (int)(item->y1 - 1), (int)(item->x2 + 1), + (int)(item->y2 + 1)); } } } void sp_canvas_item_destroy(SPCanvasItem *item) { - g_return_if_fail(SP_IS_CANVAS_ITEM(item)); + g_return_if_fail(SP_IS_CANVAS_ITEM(item)); - if (!item->in_destruction) - g_object_run_dispose(G_OBJECT(item)); + if (!item->in_destruction) + g_object_run_dispose(G_OBJECT(item)); } void sp_canvas_item_dispose(GObject *object) { - SPCanvasItem *item = SP_CANVAS_ITEM (object); + SPCanvasItem *item = SP_CANVAS_ITEM(object); /* guard against reinvocations during * destruction with the in_destruction flag. */ - if (!item->in_destruction) - { - item->in_destruction=true; - - if (item->canvas) { - // Hack: if this is a ctrlrect, move it to 0,0; - // this redraws only the stroke of the rect to be deleted, - // avoiding redraw of the entire area - if (SP_IS_CTRLRECT(item)) { - SP_CTRLRECT(object)->setRectangle(Geom::Rect(Geom::Point(0,0),Geom::Point(0,0))); - SP_CTRLRECT(object)->update(item->xform, 0); - } else { - redraw_if_visible (item); - } - item->visible = FALSE; - - item->canvas->canvas_item_clear(item); - } - - if (item->parent) { - SP_CANVAS_GROUP(item->parent)->remove(item); - } - - g_signal_emit (object, object_signals[DESTROY], 0); - item->in_destruction = false; + if (!item->in_destruction) { + item->in_destruction = true; + + if (item->canvas) { + // Hack: if this is a ctrlrect, move it to 0,0; + // this redraws only the stroke of the rect to be deleted, + // avoiding redraw of the entire area + if (SP_IS_CTRLRECT(item)) { + SP_CTRLRECT(object)->setRectangle(Geom::Rect(Geom::Point(0, 0), Geom::Point(0, 0))); + SP_CTRLRECT(object)->update(item->xform, 0); + } else { + redraw_if_visible(item); + } + item->visible = FALSE; + + item->canvas->canvas_item_clear(item); + } + + if (item->parent) { + SP_CANVAS_GROUP(item->parent)->remove(item); + } + + g_signal_emit(object, object_signals[DESTROY], 0); + item->in_destruction = false; } G_OBJECT_CLASS(sp_canvas_item_parent_class)->dispose(object); @@ -210,22 +195,21 @@ void sp_canvas_item_dispose(GObject *object) void sp_canvas_item_real_destroy(SPCanvasItem *object) { - g_signal_handlers_destroy(object); + g_signal_handlers_destroy(object); } void sp_canvas_item_finalize(GObject *gobject) { - SPCanvasItem *object = SP_CANVAS_ITEM(gobject); - - if (g_object_is_floating (object)) - { - g_warning ("A floating object was finalized. This means that someone\n" - "called g_object_unref() on an object that had only a floating\n" - "reference; the initial floating reference is not owned by anyone\n" - "and must be removed with g_object_ref_sink()."); + SPCanvasItem *object = SP_CANVAS_ITEM(gobject); + + if (g_object_is_floating(object)) { + g_warning("A floating object was finalized. This means that someone\n" + "called g_object_unref() on an object that had only a floating\n" + "reference; the initial floating reference is not owned by anyone\n" + "and must be removed with g_object_ref_sink()."); } - G_OBJECT_CLASS (sp_canvas_item_parent_class)->finalize (gobject); + G_OBJECT_CLASS(sp_canvas_item_parent_class)->finalize(gobject); } /** @@ -250,8 +234,8 @@ void sp_canvas_item_invoke_update(SPCanvasItem *item, Geom::Affine const &affine } if (child_flags & (SP_CANVAS_UPDATE_REQUESTED | SP_CANVAS_UPDATE_AFFINE)) { - if (SP_CANVAS_ITEM_GET_CLASS (item)->update) { - SP_CANVAS_ITEM_GET_CLASS (item)->update(item, child_affine, child_flags); + if (SP_CANVAS_ITEM_GET_CLASS(item)->update) { + SP_CANVAS_ITEM_GET_CLASS(item)->update(item, child_affine, child_flags); } } @@ -268,9 +252,9 @@ void sp_canvas_item_invoke_update(SPCanvasItem *item, Geom::Affine const &affine */ double sp_canvas_item_invoke_point(SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item) { -// std::cout << "sp_canvas_item_invoke_point: " << item->name << std::endl; + // std::cout << "sp_canvas_item_invoke_point: " << item->name << std::endl; if (SP_CANVAS_ITEM_GET_CLASS(item)->point) { - return SP_CANVAS_ITEM_GET_CLASS (item)->point (item, p, actual_item); + return SP_CANVAS_ITEM_GET_CLASS(item)->point(item, p, actual_item); } return Geom::infinity(); @@ -290,7 +274,7 @@ void sp_canvas_item_affine_absolute(SPCanvasItem *item, Geom::Affine const &affi if (!item->need_affine) { item->need_affine = TRUE; if (item->parent != nullptr) { - sp_canvas_item_request_update (item->parent); + sp_canvas_item_request_update(item->parent); } else { item->canvas->request_update(); } @@ -310,15 +294,15 @@ void sp_canvas_item_affine_absolute(SPCanvasItem *item, Geom::Affine const &affi */ void sp_canvas_item_raise(SPCanvasItem *item, int positions) { - g_return_if_fail (item != nullptr); - g_return_if_fail (SP_IS_CANVAS_ITEM (item)); - g_return_if_fail (positions >= 0); + g_return_if_fail(item != nullptr); + g_return_if_fail(SP_IS_CANVAS_ITEM(item)); + g_return_if_fail(positions >= 0); if (!item->parent || positions == 0) { return; } - SPCanvasGroup *parent = SP_CANVAS_GROUP (item->parent); + SPCanvasGroup *parent = SP_CANVAS_GROUP(item->parent); auto from = parent->items.iterator_to(*item); auto to = from; @@ -329,25 +313,23 @@ void sp_canvas_item_raise(SPCanvasItem *item, int positions) parent->items.erase(from); parent->items.insert(to, *item); - redraw_if_visible (item); + redraw_if_visible(item); item->canvas->set_need_repick(); } void sp_canvas_item_raise_to_top(SPCanvasItem *item) { - g_return_if_fail (item != nullptr); - g_return_if_fail (SP_IS_CANVAS_ITEM (item)); + g_return_if_fail(item != nullptr); + g_return_if_fail(SP_IS_CANVAS_ITEM(item)); if (!item->parent) return; - SPCanvasGroup *parent = SP_CANVAS_GROUP (item->parent); + SPCanvasGroup *parent = SP_CANVAS_GROUP(item->parent); parent->items.erase(parent->items.iterator_to(*item)); parent->items.push_back(*item); - redraw_if_visible (item); + redraw_if_visible(item); item->canvas->set_need_repick(); } - - /** * Lowers the item in its parent's stack by the specified number of positions. * @@ -359,9 +341,9 @@ void sp_canvas_item_raise_to_top(SPCanvasItem *item) */ void sp_canvas_item_lower(SPCanvasItem *item, int positions) { - g_return_if_fail (item != nullptr); - g_return_if_fail (SP_IS_CANVAS_ITEM (item)); - g_return_if_fail (positions >= 1); + g_return_if_fail(item != nullptr); + g_return_if_fail(SP_IS_CANVAS_ITEM(item)); + g_return_if_fail(positions >= 1); SPCanvasGroup *parent = SP_CANVAS_GROUP(item->parent); @@ -380,20 +362,20 @@ void sp_canvas_item_lower(SPCanvasItem *item, int positions) parent->items.erase(from); parent->items.insert(to, *item); - redraw_if_visible (item); + redraw_if_visible(item); item->canvas->set_need_repick(); } void sp_canvas_item_lower_to_bottom(SPCanvasItem *item) { - g_return_if_fail (item != nullptr); - g_return_if_fail (SP_IS_CANVAS_ITEM (item)); + g_return_if_fail(item != nullptr); + g_return_if_fail(SP_IS_CANVAS_ITEM(item)); if (!item->parent) return; - SPCanvasGroup *parent = SP_CANVAS_GROUP (item->parent); + SPCanvasGroup *parent = SP_CANVAS_GROUP(item->parent); parent->items.erase(parent->items.iterator_to(*item)); parent->items.push_front(*item); - redraw_if_visible (item); + redraw_if_visible(item); item->canvas->set_need_repick(); } @@ -407,8 +389,8 @@ bool sp_canvas_item_is_visible(SPCanvasItem *item) */ void sp_canvas_item_show(SPCanvasItem *item) { - g_return_if_fail (item != nullptr); - g_return_if_fail (SP_IS_CANVAS_ITEM (item)); + g_return_if_fail(item != nullptr); + g_return_if_fail(SP_IS_CANVAS_ITEM(item)); if (item->visible) { return; @@ -421,9 +403,9 @@ void sp_canvas_item_show(SPCanvasItem *item) int y0 = (int)(item->y1); int y1 = (int)(item->y2); - if (x0 !=0 || x1 !=0 || y0 !=0 || y1 !=0) { + if (x0 != 0 || x1 != 0 || y0 != 0 || y1 != 0) { // This looks funny, why can't x0 be 0? - item->canvas->redraw_area(x0, y0, x1+1, y1+1); + item->canvas->redraw_area(x0, y0, x1 + 1, y1 + 1); item->canvas->set_need_repick(); } } @@ -433,8 +415,8 @@ void sp_canvas_item_show(SPCanvasItem *item) */ void sp_canvas_item_hide(SPCanvasItem *item) { - g_return_if_fail (item != nullptr); - g_return_if_fail (SP_IS_CANVAS_ITEM (item)); + g_return_if_fail(item != nullptr); + g_return_if_fail(SP_IS_CANVAS_ITEM(item)); if (!item->visible) { return; @@ -447,8 +429,8 @@ void sp_canvas_item_hide(SPCanvasItem *item) int y0 = (int)(item->y1); int y1 = (int)(item->y2); - if (x0 !=0 || x1 !=0 || y0 !=0 || y1 !=0) { - item->canvas->redraw_area(x0, y0, x1+1, y1+1); + if (x0 != 0 || x1 != 0 || y0 != 0 || y1 != 0) { + item->canvas->redraw_area(x0, y0, x1 + 1, y1 + 1); item->canvas->set_need_repick(); } } @@ -460,9 +442,9 @@ void sp_canvas_item_hide(SPCanvasItem *item) */ int sp_canvas_item_grab(SPCanvasItem *item, guint event_mask, GdkCursor *cursor, guint32 etime) { - g_return_val_if_fail (item != nullptr, -1); - g_return_val_if_fail (SP_IS_CANVAS_ITEM (item), -1); -// g_return_val_if_fail (gtk_widget_get_mapped (GTK_WIDGET (item->canvas)), -1); + g_return_val_if_fail(item != nullptr, -1); + g_return_val_if_fail(SP_IS_CANVAS_ITEM(item), -1); + // g_return_val_if_fail (gtk_widget_get_mapped (GTK_WIDGET (item->canvas)), -1); // Don't grab if we alread have a grabbed item! if (item->canvas->get_grabbed_item()) { @@ -474,23 +456,16 @@ int sp_canvas_item_grab(SPCanvasItem *item, guint event_mask, GdkCursor *cursor, // where it is used for object selection and rubberbanding. There seems to be nothing // preventing this except this test, so I removed it. // -- Krzysztof KosiÅ„ski, 2009.08.12 - //if (!(item->flags & SP_CANVAS_ITEM_VISIBLE)) + // if (!(item->flags & SP_CANVAS_ITEM_VISIBLE)) // return -1; // fixme: Top hack (Lauris) // fixme: If we add key masks to event mask, Gdk will abort (Lauris) // fixme: But Canvas actually does get key events, so all we need is routing these here auto display = gdk_display_get_default(); - auto seat = gdk_display_get_default_seat(display); + auto seat = gdk_display_get_default_seat(display); GdkWindow *window = gtk_widget_get_window(reinterpret_cast(item->canvas->gobj())); - gdk_seat_grab(seat, - window, - GDK_SEAT_CAPABILITY_ALL_POINTING, - FALSE, - cursor, - nullptr, - nullptr, - nullptr); + gdk_seat_grab(seat, window, GDK_SEAT_CAPABILITY_ALL_POINTING, FALSE, cursor, nullptr, nullptr, nullptr); item->canvas->set_grabbed_item(item, event_mask); item->canvas->set_current_item(item); // So that events go to the grabbed item @@ -506,8 +481,8 @@ int sp_canvas_item_grab(SPCanvasItem *item, guint event_mask, GdkCursor *cursor, */ void sp_canvas_item_ungrab(SPCanvasItem *item) { - g_return_if_fail (item != nullptr); - g_return_if_fail (SP_IS_CANVAS_ITEM (item)); + g_return_if_fail(item != nullptr); + g_return_if_fail(SP_IS_CANVAS_ITEM(item)); if (item->canvas->get_grabbed_item() != item) { return; @@ -516,7 +491,7 @@ void sp_canvas_item_ungrab(SPCanvasItem *item) item->canvas->set_grabbed_item(nullptr, 0); auto const display = Gdk::Display::get_default(); - auto const seat = display->get_default_seat(); + auto const seat = display->get_default_seat(); seat->ungrab(); } @@ -526,7 +501,7 @@ void sp_canvas_item_ungrab(SPCanvasItem *item) */ Geom::Affine sp_canvas_item_i2w_affine(SPCanvasItem const *item) { - g_assert (SP_IS_CANVAS_ITEM (item)); // should we get this? + g_assert(SP_IS_CANVAS_ITEM(item)); // should we get this? Geom::Affine affine = Geom::identity(); @@ -537,7 +512,6 @@ Geom::Affine sp_canvas_item_i2w_affine(SPCanvasItem const *item) return affine; } - bool is_descendant(SPCanvasItem const *item, SPCanvasItem const *parent) { while (item) { @@ -550,7 +524,6 @@ bool is_descendant(SPCanvasItem const *item, SPCanvasItem const *parent) return false; } - /** * Requests that the canvas queue an update for the specified item. * @@ -566,7 +539,7 @@ void sp_canvas_item_request_update(SPCanvasItem *item) if (item->parent != nullptr) { // Recurse up the tree - sp_canvas_item_request_update (item->parent); + sp_canvas_item_request_update(item->parent); } else { // Have reached the top of the tree, make sure the update call gets scheduled. item->canvas->request_update(); @@ -576,9 +549,9 @@ void sp_canvas_item_request_update(SPCanvasItem *item) /** * Returns position of item in group. */ -gint sp_canvas_item_order (SPCanvasItem * item) +gint sp_canvas_item_order(SPCanvasItem *item) { - SPCanvasGroup * p = SP_CANVAS_GROUP(item->parent); + SPCanvasGroup *p = SP_CANVAS_GROUP(item->parent); size_t index = 0; for (auto it = p->items.begin(); it != p->items.end(); ++it, ++index) { if (item == &(*it)) { @@ -590,8 +563,7 @@ gint sp_canvas_item_order (SPCanvasItem * item) } // For debugging: Print canvas item tree. -void -sp_canvas_item_recursive_print_tree (unsigned level, SPCanvasItem* item) +void sp_canvas_item_recursive_print_tree(unsigned level, SPCanvasItem *item) { if (level == 0) { std::cout << "Canvas Item Tree" << std::endl; @@ -610,8 +582,8 @@ sp_canvas_item_recursive_print_tree (unsigned level, SPCanvasItem* item) if (SP_IS_CANVAS_GROUP(item)) { SPCanvasGroup *group = SP_CANVAS_GROUP(item); - for (auto & item : group->items) { - sp_canvas_item_recursive_print_tree(level+1, &item); + for (auto &item : group->items) { + sp_canvas_item_recursive_print_tree(level + 1, &item); } } } diff --git a/src/display/sp-canvas-item.h b/src/display/sp-canvas-item.h index 2726b28ac98dcc89876e2276958e3b4982e63b2d..98fc416fccd4566f337433c41f7daecd0d13b0de 100644 --- a/src/display/sp-canvas-item.h +++ b/src/display/sp-canvas-item.h @@ -22,8 +22,8 @@ #include <2geom/rect.h> #include -#include #include +#include #include "ui/control-types.h" @@ -36,31 +36,34 @@ class Canvas; } typedef struct _SPCanvasItemClass SPCanvasItemClass; -typedef union _GdkEvent GdkEvent; -typedef struct _GdkCursor GdkCursor; +typedef union _GdkEvent GdkEvent; +typedef struct _GdkCursor GdkCursor; #define SP_TYPE_CANVAS_ITEM (sp_canvas_item_get_type()) #define SP_CANVAS_ITEM(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CANVAS_ITEM, SPCanvasItem)) -#define SP_CANVAS_ITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), SP_TYPE_CANVAS_ITEM, SPCanvasItemClass)) +#define SP_CANVAS_ITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), SP_TYPE_CANVAS_ITEM, SPCanvasItemClass)) #define SP_IS_CANVAS_ITEM(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CANVAS_ITEM)) #define SP_CANVAS_ITEM_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS((o), SP_TYPE_CANVAS_ITEM, SPCanvasItemClass)) -enum { +enum +{ ITEM_EVENT, ITEM_LAST_SIGNAL }; extern guint item_signals[ITEM_LAST_SIGNAL]; -enum { - SP_CANVAS_UPDATE_REQUESTED = 1 << 0, - SP_CANVAS_UPDATE_AFFINE = 1 << 1 +enum +{ + SP_CANVAS_UPDATE_REQUESTED = 1 << 0, + SP_CANVAS_UPDATE_AFFINE = 1 << 1 }; /** * Structure used when rendering canvas items. */ -struct SPCanvasBuf { +struct SPCanvasBuf +{ cairo_t *ct; Geom::IntRect rect; Geom::IntRect canvas_rect; // visible window in world coordinates (i.e. offset by _x0, _y0) @@ -75,7 +78,8 @@ struct SPCanvasBuf { * An SPCanvasItem refers to a SPCanvas and to its parent item; it has * four coordinates, a bounding rectangle, and a transformation matrix. */ -struct SPCanvasItem { +struct SPCanvasItem +{ GInitiallyUnowned parent_instance; // boost linked list member hook @@ -112,25 +116,26 @@ struct SPCanvasItem { GType sp_canvas_item_get_type(); -//Define type for linked list storing SPCanvasItems +// Define type for linked list storing SPCanvasItems typedef boost::intrusive::list< SPCanvasItem, - boost::intrusive::member_hook, &SPCanvasItem::member_hook_> > + boost::intrusive::member_hook, &SPCanvasItem::member_hook_>> SPCanvasItemList; /** * The vtable of an SPCanvasItem. */ -struct _SPCanvasItemClass { +struct _SPCanvasItemClass +{ GInitiallyUnownedClass parent_class; - void (* update) (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); + void (*update)(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); - void (* render) (SPCanvasItem *item, SPCanvasBuf *buf); - double (* point) (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item); + void (*render)(SPCanvasItem *item, SPCanvasBuf *buf); + double (*point)(SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item); - int (* event) (SPCanvasItem *item, GdkEvent *event); - void (* viewbox_changed) (SPCanvasItem *item, Geom::IntRect const &new_area); + int (*event)(SPCanvasItem *item, GdkEvent *event); + void (*viewbox_changed)(SPCanvasItem *item, Geom::IntRect const &new_area); /* Default signal handler for the ::destroy signal, which is * invoked to request that references to the widget be dropped. @@ -140,7 +145,7 @@ struct _SPCanvasItemClass { * own cleanup. (See gtk_widget_real_destroy() for an example of * how to do this). */ - void (*destroy) (SPCanvasItem *object); + void (*destroy)(SPCanvasItem *object); }; /** @@ -150,7 +155,6 @@ SPCanvasItem *sp_canvas_item_new(SPCanvasGroup *parent, GType type, const gchar G_END_DECLS - void sp_canvas_item_affine_absolute(SPCanvasItem *item, Geom::Affine const &aff); void sp_canvas_item_raise(SPCanvasItem *item, int positions); @@ -178,9 +182,9 @@ void sp_canvas_item_request_update(SPCanvasItem *item); /* get item z-order in parent group */ -gint sp_canvas_item_order(SPCanvasItem * item); +gint sp_canvas_item_order(SPCanvasItem *item); -void sp_canvas_item_recursive_print_tree(unsigned level, SPCanvasItem* item); +void sp_canvas_item_recursive_print_tree(unsigned level, SPCanvasItem *item); #endif // SEEN_SP_CANVAS_ITEM_H diff --git a/src/display/sp-canvas-util.cpp b/src/display/sp-canvas-util.cpp index 6ccd7aff2b87d45280f67dcbad4f7a91a82466d1..9ec4d6de27d5e78d77a4707755b8463a7aac46e1 100644 --- a/src/display/sp-canvas-util.cpp +++ b/src/display/sp-canvas-util.cpp @@ -12,9 +12,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-canvas-util.h" #include <2geom/affine.h> -#include "sp-canvas-util.h" + #include "sp-canvas-item.h" #include "ui/widget/canvas.h" @@ -28,8 +29,7 @@ void sp_canvas_update_bbox(SPCanvasItem *item, int x1, int y1, int x2, int y2) item->canvas->redraw_area((int)item->x1, (int)item->y1, (int)item->x2, (int)item->y2); } -void -sp_canvas_item_reset_bounds (SPCanvasItem *item) +void sp_canvas_item_reset_bounds(SPCanvasItem *item) { item->x1 = 0.0; item->y1 = 0.0; @@ -37,42 +37,40 @@ sp_canvas_item_reset_bounds (SPCanvasItem *item) item->y2 = 0.0; } -void sp_canvas_prepare_buffer(SPCanvasBuf *) -{ -} +void sp_canvas_prepare_buffer(SPCanvasBuf *) {} -Geom::Affine sp_canvas_item_i2p_affine (SPCanvasItem * item) +Geom::Affine sp_canvas_item_i2p_affine(SPCanvasItem *item) { - g_assert (item != nullptr); /* this may be overly zealous - it is - * plausible that this gets called - * with item == 0. */ + g_assert(item != nullptr); /* this may be overly zealous - it is + * plausible that this gets called + * with item == 0. */ return item->xform; } -Geom::Affine sp_canvas_item_i2i_affine (SPCanvasItem * from, SPCanvasItem * to) +Geom::Affine sp_canvas_item_i2i_affine(SPCanvasItem *from, SPCanvasItem *to) { - g_assert (from != nullptr); - g_assert (to != nullptr); + g_assert(from != nullptr); + g_assert(to != nullptr); return sp_canvas_item_i2w_affine(from) * sp_canvas_item_i2w_affine(to).inverse(); } -void sp_canvas_item_set_i2w_affine (SPCanvasItem * item, Geom::Affine const &i2w) +void sp_canvas_item_set_i2w_affine(SPCanvasItem *item, Geom::Affine const &i2w) { - g_assert (item != nullptr); + g_assert(item != nullptr); sp_canvas_item_affine_absolute(item, i2w * sp_canvas_item_i2w_affine(item->parent).inverse()); } -void sp_canvas_item_move_to_z (SPCanvasItem * item, gint z) +void sp_canvas_item_move_to_z(SPCanvasItem *item, gint z) { - g_assert (item != nullptr); - + g_assert(item != nullptr); + if (z == 0) return sp_canvas_item_lower_to_bottom(item); - gint current_z = sp_canvas_item_order (item); + gint current_z = sp_canvas_item_order(item); if (current_z == -1) // not found in its parent return; @@ -81,20 +79,21 @@ void sp_canvas_item_move_to_z (SPCanvasItem * item, gint z) return; if (z > current_z) { - sp_canvas_item_raise (item, z - current_z); + sp_canvas_item_raise(item, z - current_z); } else { - sp_canvas_item_lower (item, current_z - z); + sp_canvas_item_lower(item, current_z - z); } } -gint -sp_canvas_item_compare_z (SPCanvasItem * a, SPCanvasItem * b) +gint sp_canvas_item_compare_z(SPCanvasItem *a, SPCanvasItem *b) { - gint const o_a = sp_canvas_item_order (a); - gint const o_b = sp_canvas_item_order (b); + gint const o_a = sp_canvas_item_order(a); + gint const o_b = sp_canvas_item_order(b); - if (o_a > o_b) return -1; - if (o_a < o_b) return 1; + if (o_a > o_b) + return -1; + if (o_a < o_b) + return 1; return 0; } diff --git a/src/display/sp-canvas-util.h b/src/display/sp-canvas-util.h index f58deb12f983adb62ae9f6a5204a1c0a4545f9c8..ff123d19148c757448c47cea69068821e9d85c27 100644 --- a/src/display/sp-canvas-util.h +++ b/src/display/sp-canvas-util.h @@ -20,30 +20,30 @@ struct SPCanvasItem; struct SPCanvasBuf; namespace Geom { - class Affine; +class Affine; } /* Miscellaneous utility & convenience functions for general canvas objects */ -void sp_canvas_update_bbox (SPCanvasItem *item, int x1, int y1, int x2, int y2); -void sp_canvas_item_reset_bounds (SPCanvasItem *item); -void sp_canvas_prepare_buffer (SPCanvasBuf *buf); +void sp_canvas_update_bbox(SPCanvasItem *item, int x1, int y1, int x2, int y2); +void sp_canvas_item_reset_bounds(SPCanvasItem *item); +void sp_canvas_prepare_buffer(SPCanvasBuf *buf); /* get i2p (item to parent) affine transformation as general 6-element array */ -Geom::Affine sp_canvas_item_i2p_affine (SPCanvasItem * item); +Geom::Affine sp_canvas_item_i2p_affine(SPCanvasItem *item); /* get i2i (item to item) affine transformation as general 6-element array */ -Geom::Affine sp_canvas_item_i2i_affine (SPCanvasItem * from, SPCanvasItem * to); +Geom::Affine sp_canvas_item_i2i_affine(SPCanvasItem *from, SPCanvasItem *to); /* set item affine matrix to achieve given i2w matrix */ -void sp_canvas_item_set_i2w_affine (SPCanvasItem * item, Geom::Affine const & aff); +void sp_canvas_item_set_i2w_affine(SPCanvasItem *item, Geom::Affine const &aff); -void sp_canvas_item_move_to_z (SPCanvasItem * item, gint z); +void sp_canvas_item_move_to_z(SPCanvasItem *item, gint z); -gint sp_canvas_item_compare_z (SPCanvasItem * a, SPCanvasItem * b); +gint sp_canvas_item_compare_z(SPCanvasItem *a, SPCanvasItem *b); #endif diff --git a/src/display/sp-ctrlcurve.cpp b/src/display/sp-ctrlcurve.cpp index 35ab48dcffdc7de0825969ecdbab55543ca5a9b2..87b7fa50b81dfdb2f98a34b464d755187d7fb5b5 100644 --- a/src/display/sp-ctrlcurve.cpp +++ b/src/display/sp-ctrlcurve.cpp @@ -13,11 +13,10 @@ */ #include "sp-ctrlcurve.h" -#include "sp-canvas-util.h" -#include "cairo-utils.h" +#include "cairo-utils.h" #include "color.h" - +#include "sp-canvas-util.h" #include "ui/widget/canvas.h" // Request redraw namespace { @@ -30,8 +29,7 @@ static void sp_ctrlcurve_render(SPCanvasItem *item, SPCanvasBuf *buf); G_DEFINE_TYPE(SPCtrlCurve, sp_ctrlcurve, SP_TYPE_CANVAS_ITEM); -static void -sp_ctrlcurve_class_init(SPCtrlCurveClass *klass) +static void sp_ctrlcurve_class_init(SPCtrlCurveClass *klass) { klass->destroy = sp_ctrlcurve_destroy; @@ -39,12 +37,11 @@ sp_ctrlcurve_class_init(SPCtrlCurveClass *klass) klass->render = sp_ctrlcurve_render; } -static void -sp_ctrlcurve_init(SPCtrlCurve *ctrlcurve) +static void sp_ctrlcurve_init(SPCtrlCurve *ctrlcurve) { // Points are initialized to 0,0 ctrlcurve->rgba = 0x0000ff7f; - ctrlcurve->item=nullptr; + ctrlcurve->item = nullptr; ctrlcurve->corner0 = -1; ctrlcurve->corner1 = -1; @@ -52,31 +49,27 @@ sp_ctrlcurve_init(SPCtrlCurve *ctrlcurve) } namespace { -static void -sp_ctrlcurve_destroy(SPCanvasItem *object) +static void sp_ctrlcurve_destroy(SPCanvasItem *object) { - g_return_if_fail (object != nullptr); - g_return_if_fail (SP_IS_CTRLCURVE (object)); + g_return_if_fail(object != nullptr); + g_return_if_fail(SP_IS_CTRLCURVE(object)); - SPCtrlCurve *ctrlcurve = SP_CTRLCURVE (object); + SPCtrlCurve *ctrlcurve = SP_CTRLCURVE(object); - ctrlcurve->item=nullptr; + ctrlcurve->item = nullptr; if (SP_CANVAS_ITEM_CLASS(sp_ctrlcurve_parent_class)->destroy) SP_CANVAS_ITEM_CLASS(sp_ctrlcurve_parent_class)->destroy(object); } -static void -sp_ctrlcurve_render(SPCanvasItem *item, SPCanvasBuf *buf) +static void sp_ctrlcurve_render(SPCanvasItem *item, SPCanvasBuf *buf) { - SPCtrlCurve *cl = SP_CTRLCURVE (item); + SPCtrlCurve *cl = SP_CTRLCURVE(item); if (!buf->ct) return; - if ( cl->p0 == cl->p1 && - cl->p1 == cl->p2 && - cl->p2 == cl->p3 ) + if (cl->p0 == cl->p1 && cl->p1 == cl->p2 && cl->p2 == cl->p3) return; ink_cairo_set_source_rgba32(buf->ct, cl->rgba); @@ -88,33 +81,30 @@ sp_ctrlcurve_render(SPCanvasItem *item, SPCanvasBuf *buf) Geom::Point p2 = cl->p2 * cl->affine; Geom::Point p3 = cl->p3 * cl->affine; - cairo_move_to (buf->ct, p0[Geom::X] - buf->rect.left(), p0[Geom::Y] - buf->rect.top()); - cairo_curve_to (buf->ct, - p1[Geom::X] - buf->rect.left(), p1[Geom::Y] - buf->rect.top(), - p2[Geom::X] - buf->rect.left(), p2[Geom::Y] - buf->rect.top(), - p3[Geom::X] - buf->rect.left(), p3[Geom::Y] - buf->rect.top() ); + cairo_move_to(buf->ct, p0[Geom::X] - buf->rect.left(), p0[Geom::Y] - buf->rect.top()); + cairo_curve_to(buf->ct, p1[Geom::X] - buf->rect.left(), p1[Geom::Y] - buf->rect.top(), + p2[Geom::X] - buf->rect.left(), p2[Geom::Y] - buf->rect.top(), p3[Geom::X] - buf->rect.left(), + p3[Geom::Y] - buf->rect.top()); cairo_stroke(buf->ct); } -static void -sp_ctrlcurve_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) +static void sp_ctrlcurve_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) { - SPCtrlCurve *cl = SP_CTRLCURVE (item); + SPCtrlCurve *cl = SP_CTRLCURVE(item); item->canvas->redraw_area(item->x1, item->y1, item->x2, item->y2); if (SP_CANVAS_ITEM_CLASS(sp_ctrlcurve_parent_class)->update) SP_CANVAS_ITEM_CLASS(sp_ctrlcurve_parent_class)->update(item, affine, flags); - sp_canvas_item_reset_bounds (item); + sp_canvas_item_reset_bounds(item); cl->affine = affine; - if (cl->p0 == cl->p1 && cl->p1 == cl->p2 && cl->p2 == cl->p3 ) { + if (cl->p0 == cl->p1 && cl->p1 == cl->p2 && cl->p2 == cl->p3) { item->x1 = item->x2 = item->y1 = item->y2 = 0; } else { - Geom::Point p0 = cl->p0 * affine; Geom::Point p1 = cl->p1 * affine; Geom::Point p2 = cl->p2 * affine; @@ -125,61 +115,56 @@ sp_ctrlcurve_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int double max_x = p0[Geom::X]; double max_y = p0[Geom::Y]; - min_x = MIN( min_x, p1[Geom::X] ); - min_y = MIN( min_y, p1[Geom::Y] ); - max_x = MAX( max_x, p1[Geom::X] ); - max_y = MAX( max_y, p1[Geom::Y] ); + min_x = MIN(min_x, p1[Geom::X]); + min_y = MIN(min_y, p1[Geom::Y]); + max_x = MAX(max_x, p1[Geom::X]); + max_y = MAX(max_y, p1[Geom::Y]); - min_x = MIN( min_x, p2[Geom::X] ); - min_y = MIN( min_y, p2[Geom::Y] ); - max_x = MAX( max_x, p2[Geom::X] ); - max_y = MAX( max_y, p2[Geom::Y] ); + min_x = MIN(min_x, p2[Geom::X]); + min_y = MIN(min_y, p2[Geom::Y]); + max_x = MAX(max_x, p2[Geom::X]); + max_y = MAX(max_y, p2[Geom::Y]); - min_x = MIN( min_x, p3[Geom::X] ); - min_y = MIN( min_y, p3[Geom::Y] ); - max_x = MAX( max_x, p3[Geom::X] ); - max_y = MAX( max_y, p3[Geom::Y] ); + min_x = MIN(min_x, p3[Geom::X]); + min_y = MIN(min_y, p3[Geom::Y]); + max_x = MAX(max_x, p3[Geom::X]); + max_y = MAX(max_y, p3[Geom::Y]); - item->x1 = round( min_x - 1 ); - item->y1 = round( min_y - 1 ); - item->x2 = round( max_x + 1 ); - item->y2 = round( max_y + 1 ); + item->x1 = round(min_x - 1); + item->y1 = round(min_y - 1); + item->x2 = round(max_x + 1); + item->y2 = round(max_y + 1); item->canvas->redraw_area(item->x1, item->y1, item->x2, item->y2); - } } } // namespace #define EPSILON 1e-6 -#define DIFFER(a,b) (fabs ((a) - (b)) > EPSILON) +#define DIFFER(a, b) (fabs((a) - (b)) > EPSILON) -void SPCtrlCurve::setCoords( gdouble x0, gdouble y0, gdouble x1, gdouble y1, - gdouble x2, gdouble y2, gdouble x3, gdouble y3 ) +void SPCtrlCurve::setCoords(gdouble x0, gdouble y0, gdouble x1, gdouble y1, gdouble x2, gdouble y2, gdouble x3, + gdouble y3) { + Geom::Point q0(x0, y0); + Geom::Point q1(x1, y1); + Geom::Point q2(x2, y2); + Geom::Point q3(x3, y3); - Geom::Point q0( x0, y0 ); - Geom::Point q1( x1, y1 ); - Geom::Point q2( x2, y2 ); - Geom::Point q3( x3, y3 ); - - setCoords( q0, q1, q2, q3 ); - + setCoords(q0, q1, q2, q3); } -void SPCtrlCurve::setCoords( Geom::Point const &q0, Geom::Point const &q1, - Geom::Point const &q2, Geom::Point const &q3) +void SPCtrlCurve::setCoords(Geom::Point const &q0, Geom::Point const &q1, Geom::Point const &q2, Geom::Point const &q3) { - if (DIFFER(p0[Geom::X], q0[Geom::X]) || DIFFER(p0[Geom::Y], q0[Geom::Y]) || - DIFFER(p1[Geom::X], q1[Geom::X]) || DIFFER(p1[Geom::Y], q1[Geom::Y]) || - DIFFER(p2[Geom::X], q2[Geom::X]) || DIFFER(p2[Geom::Y], q2[Geom::Y]) || - DIFFER(p3[Geom::X], q3[Geom::X]) || DIFFER(p3[Geom::Y], q3[Geom::Y]) ) { + if (DIFFER(p0[Geom::X], q0[Geom::X]) || DIFFER(p0[Geom::Y], q0[Geom::Y]) || DIFFER(p1[Geom::X], q1[Geom::X]) || + DIFFER(p1[Geom::Y], q1[Geom::Y]) || DIFFER(p2[Geom::X], q2[Geom::X]) || DIFFER(p2[Geom::Y], q2[Geom::Y]) || + DIFFER(p3[Geom::X], q3[Geom::X]) || DIFFER(p3[Geom::Y], q3[Geom::Y])) { p0 = q0; p1 = q1; p2 = q2; p3 = q3; - sp_canvas_item_request_update( this ); + sp_canvas_item_request_update(this); } } diff --git a/src/display/sp-ctrlcurve.h b/src/display/sp-ctrlcurve.h index a499d52adc37e2919d6cd9be8a8e757a647e4840..ecdd425de71efa9658dc5bb31807bafd0667b746 100644 --- a/src/display/sp-ctrlcurve.h +++ b/src/display/sp-ctrlcurve.h @@ -21,25 +21,26 @@ class SPItem; #define SP_TYPE_CTRLCURVE (sp_ctrlcurve_get_type()) -#define SP_CTRLCURVE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SP_TYPE_CTRLCURVE, SPCtrlCurve)) -#define SP_IS_CTRLCURVE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SP_TYPE_CTRLCURVE)) +#define SP_CTRLCURVE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CTRLCURVE, SPCtrlCurve)) +#define SP_IS_CTRLCURVE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CTRLCURVE)) -struct SPCtrlCurve : public SPCtrlLine { - void setCoords( gdouble x0, gdouble y0, gdouble x1, gdouble y1, - gdouble x2, gdouble y2, gdouble x3, gdouble y3 ); +struct SPCtrlCurve : public SPCtrlLine +{ + void setCoords(gdouble x0, gdouble y0, gdouble x1, gdouble y1, gdouble x2, gdouble y2, gdouble x3, gdouble y3); - void setCoords( Geom::Point const &q0, Geom::Point const &q1, - Geom::Point const &q2, Geom::Point const &q3); + void setCoords(Geom::Point const &q0, Geom::Point const &q1, Geom::Point const &q2, Geom::Point const &q3); Geom::Point p0, p1, p2, p3; - int corner0; // Used to store index of corner for finding dragger. + int corner0; // Used to store index of corner for finding dragger. int corner1; }; GType sp_ctrlcurve_get_type(); -struct SPCtrlCurveClass : public SPCtrlLineClass{}; +struct SPCtrlCurveClass : public SPCtrlLineClass +{ +}; #endif // SEEN_INKSCAPE_CTRLCURVE_H diff --git a/src/display/sp-ctrlline.cpp b/src/display/sp-ctrlline.cpp index 59ad0f105b6546d01646aae764ab5fce75ba846b..e24e37eaf7997d69afc38bd9b9401f696672a459 100644 --- a/src/display/sp-ctrlline.cpp +++ b/src/display/sp-ctrlline.cpp @@ -20,11 +20,10 @@ */ #include "sp-ctrlline.h" -#include "sp-canvas-util.h" -#include "cairo-utils.h" +#include "cairo-utils.h" #include "color.h" - +#include "sp-canvas-util.h" #include "ui/widget/canvas.h" namespace { @@ -50,7 +49,7 @@ static void sp_ctrlline_init(SPCtrlLine *ctrlline) { ctrlline->rgba = 0x0000ff7f; ctrlline->s[Geom::X] = ctrlline->s[Geom::Y] = ctrlline->e[Geom::X] = ctrlline->e[Geom::Y] = 0.0; - ctrlline->item=nullptr; + ctrlline->item = nullptr; ctrlline->is_fill = true; ctrlline->name = "CtrlLine"; @@ -66,8 +65,8 @@ void sp_ctrlline_destroy(SPCanvasItem *object) ctrlline->item = nullptr; - if(SP_CANVAS_ITEM_CLASS (sp_ctrlline_parent_class)->destroy) { - SP_CANVAS_ITEM_CLASS (sp_ctrlline_parent_class)->destroy(object); + if (SP_CANVAS_ITEM_CLASS(sp_ctrlline_parent_class)->destroy) { + SP_CANVAS_ITEM_CLASS(sp_ctrlline_parent_class)->destroy(object); } } @@ -95,7 +94,6 @@ void sp_ctrlline_render(SPCanvasItem *item, SPCanvasBuf *buf) cairo_stroke(buf->ct); - ink_cairo_set_source_rgba32(buf->ct, cl->rgba); cairo_set_line_width(buf->ct, 1); cairo_new_path(buf->ct); @@ -123,7 +121,6 @@ void sp_ctrlline_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned if (cl->s == cl->e) { item->x1 = item->x2 = item->y1 = item->y2 = 0; } else { - Geom::Point s = cl->s * affine; Geom::Point e = cl->e * affine; @@ -147,7 +144,7 @@ void SPCtrlLine::setRgba32(guint32 rgba) } #define EPSILON 1e-6 -#define DIFFER(a,b) (fabs ((a) - (b)) > EPSILON) +#define DIFFER(a, b) (fabs((a) - (b)) > EPSILON) void SPCtrlLine::setCoords(gdouble x0, gdouble y0, gdouble x1, gdouble y1) { diff --git a/src/display/sp-ctrlline.h b/src/display/sp-ctrlline.h index 5ecd1ca22931f0ba0c78c8cc9be39019cdaaf3f5..e5eb26f8da51f25697916027263a47d60884c115 100644 --- a/src/display/sp-ctrlline.h +++ b/src/display/sp-ctrlline.h @@ -22,19 +22,19 @@ class SPItem; #define SP_TYPE_CTRLLINE (sp_ctrlline_get_type()) -#define SP_CTRLLINE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SP_TYPE_CTRLLINE, SPCtrlLine)) -#define SP_IS_CTRLLINE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SP_TYPE_CTRLLINE)) +#define SP_CTRLLINE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CTRLLINE, SPCtrlLine)) +#define SP_IS_CTRLLINE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CTRLLINE)) -struct SPCtrlLine : public SPCanvasItem { +struct SPCtrlLine : public SPCanvasItem +{ void setRgba32(guint32 rgba); void setCoords(gdouble x0, gdouble y0, gdouble x1, gdouble y1); void setCoords(Geom::Point const &start, Geom::Point const &end); - - SPItem *item; // the item to which this line belongs in some sense; may be NULL for some users - bool is_fill; // fill or stroke... used with meshes. + SPItem *item; // the item to which this line belongs in some sense; may be NULL for some users + bool is_fill; // fill or stroke... used with meshes. guint32 rgba; Geom::Point s; @@ -44,9 +44,9 @@ struct SPCtrlLine : public SPCanvasItem { GType sp_ctrlline_get_type(); -struct SPCtrlLineClass : public SPCanvasItemClass{}; - - +struct SPCtrlLineClass : public SPCanvasItemClass +{ +}; #endif // SEEN_INKSCAPE_CTRLLINE_H diff --git a/src/display/sp-ctrlquadr.cpp b/src/display/sp-ctrlquadr.cpp index 80e1959160435c70f6257b80bd2e0adbc9f12668..2b5fad87f7f01402b79968e26bc5de6bbc95fa87 100644 --- a/src/display/sp-ctrlquadr.cpp +++ b/src/display/sp-ctrlquadr.cpp @@ -11,32 +11,33 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "sp-canvas-item.h" -#include "sp-canvas-util.h" #include "sp-ctrlquadr.h" -#include "cairo-utils.h" +#include "cairo-utils.h" #include "color.h" - +#include "sp-canvas-item.h" +#include "sp-canvas-util.h" #include "ui/widget/canvas.h" -struct SPCtrlQuadr : public SPCanvasItem{ +struct SPCtrlQuadr : public SPCanvasItem +{ guint32 rgba; Geom::Point p1, p2, p3, p4; - Geom::Affine affine; + Geom::Affine affine; }; -struct SPCtrlQuadrClass : public SPCanvasItemClass{}; +struct SPCtrlQuadrClass : public SPCanvasItemClass +{ +}; static void sp_ctrlquadr_destroy(SPCanvasItem *object); -static void sp_ctrlquadr_update (SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); -static void sp_ctrlquadr_render (SPCanvasItem *item, SPCanvasBuf *buf); +static void sp_ctrlquadr_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags); +static void sp_ctrlquadr_render(SPCanvasItem *item, SPCanvasBuf *buf); G_DEFINE_TYPE(SPCtrlQuadr, sp_ctrlquadr, SP_TYPE_CANVAS_ITEM); -static void -sp_ctrlquadr_class_init (SPCtrlQuadrClass *klass) +static void sp_ctrlquadr_class_init(SPCtrlQuadrClass *klass) { SPCanvasItemClass *item_class = SP_CANVAS_ITEM_CLASS(klass); @@ -45,8 +46,7 @@ sp_ctrlquadr_class_init (SPCtrlQuadrClass *klass) item_class->render = sp_ctrlquadr_render; } -static void -sp_ctrlquadr_init (SPCtrlQuadr *ctrlquadr) +static void sp_ctrlquadr_init(SPCtrlQuadr *ctrlquadr) { ctrlquadr->rgba = 0x000000ff; ctrlquadr->p1 = Geom::Point(0, 0); @@ -59,17 +59,16 @@ sp_ctrlquadr_init (SPCtrlQuadr *ctrlquadr) static void sp_ctrlquadr_destroy(SPCanvasItem *object) { - g_return_if_fail (object != nullptr); - g_return_if_fail (SP_IS_CTRLQUADR (object)); + g_return_if_fail(object != nullptr); + g_return_if_fail(SP_IS_CTRLQUADR(object)); if (SP_CANVAS_ITEM_CLASS(sp_ctrlquadr_parent_class)->destroy) - (* SP_CANVAS_ITEM_CLASS(sp_ctrlquadr_parent_class)->destroy) (object); + (*SP_CANVAS_ITEM_CLASS(sp_ctrlquadr_parent_class)->destroy)(object); } -static void -sp_ctrlquadr_render (SPCanvasItem *item, SPCanvasBuf *buf) +static void sp_ctrlquadr_render(SPCanvasItem *item, SPCanvasBuf *buf) { - SPCtrlQuadr *cq = SP_CTRLQUADR (item); + SPCtrlQuadr *cq = SP_CTRLQUADR(item); if (!buf->ct) return; @@ -91,24 +90,18 @@ sp_ctrlquadr_render (SPCanvasItem *item, SPCanvasBuf *buf) cairo_line_to(buf->ct, p1[Geom::X], p1[Geom::Y]); // FIXME: this is supposed to draw inverse but cairo apparently is unable of this trick :( - //cairo_set_operator (buf->ct, CAIRO_OPERATOR_XOR); + // cairo_set_operator (buf->ct, CAIRO_OPERATOR_XOR); - cairo_set_source_rgba(buf->ct, SP_RGBA32_B_F(cq->rgba), SP_RGBA32_G_F(cq->rgba), SP_RGBA32_R_F(cq->rgba), SP_RGBA32_A_F(cq->rgba)); + cairo_set_source_rgba(buf->ct, SP_RGBA32_B_F(cq->rgba), SP_RGBA32_G_F(cq->rgba), SP_RGBA32_R_F(cq->rgba), + SP_RGBA32_A_F(cq->rgba)); cairo_fill(buf->ct); } -#define MIN4(a,b,c,d)\ - ((a <= b && a <= c && a <= d) ? a : \ - (b <= a && b <= c && b <= d) ? b : \ - (c <= a && c <= b && c <= d) ? c : \ - d ) - -#define MAX4(a,b,c,d)\ - ((a >= b && a >= c && a >= d) ? a : \ - (b >= a && b >= c && b >= d) ? b : \ - (c >= a && c >= b && c >= d) ? c : \ - d ) +#define MIN4(a, b, c, d) \ + ((a <= b && a <= c && a <= d) ? a : (b <= a && b <= c && b <= d) ? b : (c <= a && c <= b && c <= d) ? c : d) +#define MAX4(a, b, c, d) \ + ((a >= b && a >= c && a >= d) ? a : (b >= a && b >= c && b >= d) ? b : (c >= a && c >= b && c >= d) ? c : d) static void sp_ctrlquadr_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) { @@ -120,7 +113,7 @@ static void sp_ctrlquadr_update(SPCanvasItem *item, Geom::Affine const &affine, SP_CANVAS_ITEM_CLASS(sp_ctrlquadr_parent_class)->update(item, affine, flags); } - sp_canvas_item_reset_bounds (item); + sp_canvas_item_reset_bounds(item); cq->affine = affine; @@ -128,7 +121,7 @@ static void sp_ctrlquadr_update(SPCanvasItem *item, Geom::Affine const &affine, Geom::Point p2(cq->p2 * affine); Geom::Point p3(cq->p3 * affine); Geom::Point p4(cq->p4 * affine); - + item->x1 = (int)(MIN4(p1[Geom::X], p2[Geom::X], p3[Geom::X], p4[Geom::X])); item->y1 = (int)(MIN4(p1[Geom::Y], p2[Geom::Y], p3[Geom::Y], p4[Geom::Y])); item->x2 = (int)(MAX4(p1[Geom::X], p2[Geom::X], p3[Geom::X], p4[Geom::X])); @@ -137,32 +130,30 @@ static void sp_ctrlquadr_update(SPCanvasItem *item, Geom::Affine const &affine, item->canvas->redraw_area((int)item->x1, (int)item->y1, (int)item->x2, (int)item->y2); } -void -sp_ctrlquadr_set_rgba32 (SPCtrlQuadr *cl, guint32 rgba) +void sp_ctrlquadr_set_rgba32(SPCtrlQuadr *cl, guint32 rgba) { - g_return_if_fail (cl != nullptr); - g_return_if_fail (SP_IS_CTRLQUADR (cl)); + g_return_if_fail(cl != nullptr); + g_return_if_fail(SP_IS_CTRLQUADR(cl)); if (rgba != cl->rgba) { SPCanvasItem *item; cl->rgba = rgba; - item = SP_CANVAS_ITEM (cl); + item = SP_CANVAS_ITEM(cl); item->canvas->redraw_area((int)item->x1, (int)item->y1, (int)item->x2, (int)item->y2); } } -void -sp_ctrlquadr_set_coords (SPCtrlQuadr *cl, Geom::Point p1, Geom::Point p2, Geom::Point p3, Geom::Point p4) +void sp_ctrlquadr_set_coords(SPCtrlQuadr *cl, Geom::Point p1, Geom::Point p2, Geom::Point p3, Geom::Point p4) { - g_return_if_fail (cl != nullptr); - g_return_if_fail (SP_IS_CTRLQUADR (cl)); + g_return_if_fail(cl != nullptr); + g_return_if_fail(SP_IS_CTRLQUADR(cl)); if (p1 != cl->p1 || p2 != cl->p2 || p3 != cl->p3 || p4 != cl->p4) { cl->p1 = p1; cl->p2 = p2; cl->p3 = p3; cl->p4 = p4; - sp_canvas_item_request_update (SP_CANVAS_ITEM (cl)); + sp_canvas_item_request_update(SP_CANVAS_ITEM(cl)); } } diff --git a/src/display/sp-ctrlquadr.h b/src/display/sp-ctrlquadr.h index a3295c241db0ef93898db3ea6eb5dd4023164197..3b581b92bf0a1240eba656f125fa84dcdb12946d 100644 --- a/src/display/sp-ctrlquadr.h +++ b/src/display/sp-ctrlquadr.h @@ -14,21 +14,21 @@ */ #include <2geom/point.h> -#include #include +#include -#define SP_TYPE_CTRLQUADR (sp_ctrlquadr_get_type ()) -#define SP_CTRLQUADR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SP_TYPE_CTRLQUADR, SPCtrlQuadr)) -#define SP_IS_CTRLQUADR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SP_TYPE_CTRLQUADR)) +#define SP_TYPE_CTRLQUADR (sp_ctrlquadr_get_type()) +#define SP_CTRLQUADR(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CTRLQUADR, SPCtrlQuadr)) +#define SP_IS_CTRLQUADR(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CTRLQUADR)) struct SPCtrlQuadr; struct SPCtrlQuadrClass; -GType sp_ctrlquadr_get_type (); - -void sp_ctrlquadr_set_rgba32 (SPCtrlQuadr *cl, guint32 rgba); -void sp_ctrlquadr_set_coords (SPCtrlQuadr *cl, const Geom::Point p1, const Geom::Point p2, const Geom::Point p3, const Geom::Point p4); +GType sp_ctrlquadr_get_type(); +void sp_ctrlquadr_set_rgba32(SPCtrlQuadr *cl, guint32 rgba); +void sp_ctrlquadr_set_coords(SPCtrlQuadr *cl, const Geom::Point p1, const Geom::Point p2, const Geom::Point p3, + const Geom::Point p4); #endif diff --git a/src/document-subset.cpp b/src/document-subset.cpp index 8cbd9bc45c47336843776ab92585df3d0b7ec186..15b664bc59792879f6e6c3b8e35b178559730a29 100644 --- a/src/document-subset.cpp +++ b/src/document-subset.cpp @@ -9,55 +9,60 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "document-subset.h" + #include -#include "gc-finalized.h" -#include "document-subset.h" #include "document.h" - +#include "gc-finalized.h" #include "object/sp-object.h" - namespace Inkscape { -struct DocumentSubset::Relations : public GC::Managed, - public GC::Finalized +struct DocumentSubset::Relations + : public GC::Managed + , public GC::Finalized { typedef std::vector Siblings; - struct Record { + struct Record + { SPObject *parent; Siblings children; sigc::connection release_connection; sigc::connection position_changed_connection; - Record() : parent(nullptr) {} + Record() + : parent(nullptr) + {} - unsigned childIndex(SPObject *obj) { + unsigned childIndex(SPObject *obj) + { Siblings::iterator found; found = std::find(children.begin(), children.end(), obj); - if ( found != children.end() ) { + if (found != children.end()) { return found - children.begin(); } else { return 0; } } - unsigned findInsertIndex(SPObject *obj) const { + unsigned findInsertIndex(SPObject *obj) const + { if (children.empty()) { return 0; } else { - Siblings::const_iterator first=children.begin(); - Siblings::const_iterator last=children.end() - 1; + Siblings::const_iterator first = children.begin(); + Siblings::const_iterator last = children.end() - 1; - while ( first != last ) { - Siblings::const_iterator mid = first + ( last - first + 1 ) / 2; + while (first != last) { + Siblings::const_iterator mid = first + (last - first + 1) / 2; int pos = sp_object_compare_position(*mid, obj); - if ( pos < 0 ) { + if (pos < 0) { first = mid; - } else if ( pos > 0 ) { - if ( last == mid ) { + } else if (pos > 0) { + if (last == mid) { last = mid - 1; // already at the top limit } else { last = mid; @@ -67,10 +72,10 @@ struct DocumentSubset::Relations : public GC::Managed, } } - if ( first == last ) { + if (first == last) { // compare to the single possibility left int pos = sp_object_compare_position(*last, obj); - if ( pos < 0 ) { + if (pos < 0) { ++last; } } @@ -79,25 +84,22 @@ struct DocumentSubset::Relations : public GC::Managed, } } - void addChild(SPObject *obj) { - unsigned index=findInsertIndex(obj); - children.insert(children.begin()+index, obj); + void addChild(SPObject *obj) + { + unsigned index = findInsertIndex(obj); + children.insert(children.begin() + index, obj); } template - void extractDescendants(OutputIterator descendants, - SPObject *obj) + void extractDescendants(OutputIterator descendants, SPObject *obj) { Siblings new_children; - bool found_one=false; - for ( Siblings::iterator iter=children.begin() - ; iter != children.end() ; ++iter ) - { + bool found_one = false; + for (Siblings::iterator iter = children.begin(); iter != children.end(); ++iter) { if (obj->isAncestorOf(*iter)) { if (!found_one) { found_one = true; - new_children.insert(new_children.end(), - children.begin(), iter); + new_children.insert(new_children.end(), children.begin(), iter); } *descendants++ = *iter; } else if (found_one) { @@ -109,11 +111,12 @@ struct DocumentSubset::Relations : public GC::Managed, } } - unsigned removeChild(SPObject *obj) { + unsigned removeChild(SPObject *obj) + { Siblings::iterator found; found = std::find(children.begin(), children.end(), obj); unsigned index = found - children.begin(); - if ( found != children.end() ) { + if (found != children.end()) { children.erase(found); } return index; @@ -129,21 +132,22 @@ struct DocumentSubset::Relations : public GC::Managed, Relations() { records[nullptr]; } - ~Relations() override { - for (auto & iter : records) - { + ~Relations() override + { + for (auto &iter : records) { if (iter.first) { sp_object_unref(iter.first); - Record &record=iter.second; + Record &record = iter.second; record.release_connection.disconnect(); record.position_changed_connection.disconnect(); } } } - Record *get(SPObject *obj) { - Map::iterator found=records.find(obj); - if ( found != records.end() ) { + Record *get(SPObject *obj) + { + Map::iterator found = records.find(obj); + if (found != records.end()) { return &(*found).second; } else { return nullptr; @@ -156,32 +160,26 @@ struct DocumentSubset::Relations : public GC::Managed, void clear(); private: - Record &_doAdd(SPObject *obj) { + Record &_doAdd(SPObject *obj) + { sp_object_ref(obj); - Record &record=records[obj]; - record.release_connection - = obj->connectRelease( - sigc::mem_fun(this, &Relations::_release_object) - ); - record.position_changed_connection - = obj->connectPositionChanged( - sigc::mem_fun(this, &Relations::reorder) - ); + Record &record = records[obj]; + record.release_connection = obj->connectRelease(sigc::mem_fun(this, &Relations::_release_object)); + record.position_changed_connection = obj->connectPositionChanged(sigc::mem_fun(this, &Relations::reorder)); return record; } - void _notifyAdded(SPObject *obj) { - added_signal.emit(obj); - } + void _notifyAdded(SPObject *obj) { added_signal.emit(obj); } - void _doRemove(SPObject *obj) { - Record &record=records[obj]; + void _doRemove(SPObject *obj) + { + Record &record = records[obj]; - if ( record.parent == nullptr ) { + if (record.parent == nullptr) { Record &root = records[nullptr]; - for ( Siblings::iterator it = root.children.begin(); it != root.children.end(); ++it ) { - if ( *it == obj ) { - root.children.erase( it ); + for (Siblings::iterator it = root.children.begin(); it != root.children.end(); ++it) { + if (*it == obj) { + root.children.erase(it); break; } } @@ -194,19 +192,20 @@ private: sp_object_unref(obj); } - void _doRemoveSubtree(SPObject *obj) { - Record *record=get(obj); + void _doRemoveSubtree(SPObject *obj) + { + Record *record = get(obj); if (record) { - Siblings &children=record->children; - for (auto & iter : children) - { + Siblings &children = record->children; + for (auto &iter : children) { _doRemoveSubtree(iter); } _doRemove(obj); } } - void _release_object(SPObject *obj) { + void _release_object(SPObject *obj) + { if (get(obj)) { remove(obj, true); } @@ -214,21 +213,19 @@ private: }; DocumentSubset::DocumentSubset() -: _relations(new DocumentSubset::Relations()) -{ -} + : _relations(new DocumentSubset::Relations()) +{} -void DocumentSubset::Relations::addOne(SPObject *obj) { - g_return_if_fail( obj != nullptr ); - g_return_if_fail( get(obj) == nullptr ); +void DocumentSubset::Relations::addOne(SPObject *obj) +{ + g_return_if_fail(obj != nullptr); + g_return_if_fail(get(obj) == nullptr); - Record &record=_doAdd(obj); + Record &record = _doAdd(obj); /* find the nearest ancestor in the subset */ - Record *parent_record=nullptr; - for ( SPObject::ParentIterator parent_iter=obj->parent - ; !parent_record && parent_iter ; ++parent_iter ) - { + Record *parent_record = nullptr; + for (SPObject::ParentIterator parent_iter = obj->parent; !parent_record && parent_iter; ++parent_iter) { parent_record = get(parent_iter); if (parent_record) { record.parent = parent_iter; @@ -236,20 +233,16 @@ void DocumentSubset::Relations::addOne(SPObject *obj) { } if (!parent_record) { parent_record = get(nullptr); - g_assert( parent_record != nullptr ); + g_assert(parent_record != nullptr); } - Siblings &children=record.children; + Siblings &children = record.children; /* reparent descendants of obj to obj */ - parent_record->extractDescendants( - std::back_insert_iterator(children), - obj - ); - for (auto & iter : children) - { - Record *child_record=get(iter); - g_assert( child_record != nullptr ); + parent_record->extractDescendants(std::back_insert_iterator(children), obj); + for (auto &iter : children) { + Record *child_record = get(iter); + g_assert(child_record != nullptr); child_record->parent = obj; } @@ -260,30 +253,29 @@ void DocumentSubset::Relations::addOne(SPObject *obj) { changed_signal.emit(); } -void DocumentSubset::Relations::remove(SPObject *obj, bool subtree) { - g_return_if_fail( obj != nullptr ); +void DocumentSubset::Relations::remove(SPObject *obj, bool subtree) +{ + g_return_if_fail(obj != nullptr); - Record *record=get(obj); - g_return_if_fail( record != nullptr ); + Record *record = get(obj); + g_return_if_fail(record != nullptr); - Record *parent_record=get(record->parent); - g_assert( parent_record != nullptr ); + Record *parent_record = get(record->parent); + g_assert(parent_record != nullptr); - unsigned index=parent_record->removeChild(obj); + unsigned index = parent_record->removeChild(obj); if (subtree) { _doRemoveSubtree(obj); } else { /* reparent obj's orphaned children to their grandparent */ - Siblings &siblings=parent_record->children; - Siblings &children=record->children; - siblings.insert(siblings.begin()+index, - children.begin(), children.end()); + Siblings &siblings = parent_record->children; + Siblings &children = record->children; + siblings.insert(siblings.begin() + index, children.begin(), children.end()); - for (auto & iter : children) - { - Record *child_record=get(iter); - g_assert( child_record != nullptr ); + for (auto &iter : children) { + Record *child_record = get(iter); + g_assert(child_record != nullptr); child_record->parent = record->parent; } @@ -294,8 +286,9 @@ void DocumentSubset::Relations::remove(SPObject *obj, bool subtree) { changed_signal.emit(); } -void DocumentSubset::Relations::clear() { - Record &root=records[nullptr]; +void DocumentSubset::Relations::clear() +{ + Record &root = records[nullptr]; while (!root.children.empty()) { _doRemoveSubtree(root.children.front()); @@ -304,11 +297,12 @@ void DocumentSubset::Relations::clear() { changed_signal.emit(); } -void DocumentSubset::Relations::reorder(SPObject *obj) { - SPObject::ParentIterator parent=obj; +void DocumentSubset::Relations::reorder(SPObject *obj) +{ + SPObject::ParentIterator parent = obj; /* find nearest ancestor in the subset */ - Record *parent_record=nullptr; + Record *parent_record = nullptr; while (!parent_record) { parent_record = get(++parent); } @@ -321,72 +315,77 @@ void DocumentSubset::Relations::reorder(SPObject *obj) { } else { /* otherwise, move any top-level descendants */ Siblings descendants; - parent_record->extractDescendants( - std::back_insert_iterator(descendants), - obj - ); + parent_record->extractDescendants(std::back_insert_iterator(descendants), obj); if (!descendants.empty()) { - unsigned index=parent_record->findInsertIndex(obj); - Siblings &family=parent_record->children; - family.insert(family.begin()+index, - descendants.begin(), descendants.end()); + unsigned index = parent_record->findInsertIndex(obj); + Siblings &family = parent_record->children; + family.insert(family.begin() + index, descendants.begin(), descendants.end()); changed_signal.emit(); } } } -void DocumentSubset::_addOne(SPObject *obj) { +void DocumentSubset::_addOne(SPObject *obj) +{ _relations->addOne(obj); } -void DocumentSubset::_remove(SPObject *obj, bool subtree) { +void DocumentSubset::_remove(SPObject *obj, bool subtree) +{ _relations->remove(obj, subtree); } -void DocumentSubset::_clear() { +void DocumentSubset::_clear() +{ _relations->clear(); } -bool DocumentSubset::includes(SPObject *obj) const { +bool DocumentSubset::includes(SPObject *obj) const +{ return _relations->get(obj); } -SPObject *DocumentSubset::parentOf(SPObject *obj) const { - Relations::Record *record=_relations->get(obj); - return ( record ? record->parent : nullptr ); +SPObject *DocumentSubset::parentOf(SPObject *obj) const +{ + Relations::Record *record = _relations->get(obj); + return (record ? record->parent : nullptr); } -unsigned DocumentSubset::childCount(SPObject *obj) const { - Relations::Record *record=_relations->get(obj); - return ( record ? record->children.size() : 0 ); +unsigned DocumentSubset::childCount(SPObject *obj) const +{ + Relations::Record *record = _relations->get(obj); + return (record ? record->children.size() : 0); } -unsigned DocumentSubset::indexOf(SPObject *obj) const { - SPObject *parent=parentOf(obj); - Relations::Record *record=_relations->get(parent); - return ( record ? record->childIndex(obj) : 0 ); +unsigned DocumentSubset::indexOf(SPObject *obj) const +{ + SPObject *parent = parentOf(obj); + Relations::Record *record = _relations->get(parent); + return (record ? record->childIndex(obj) : 0); } -SPObject *DocumentSubset::nthChildOf(SPObject *obj, unsigned n) const { - Relations::Record *record=_relations->get(obj); - return ( record ? record->children[n] : nullptr ); +SPObject *DocumentSubset::nthChildOf(SPObject *obj, unsigned n) const +{ + Relations::Record *record = _relations->get(obj); + return (record ? record->children[n] : nullptr); } -sigc::connection DocumentSubset::connectChanged(sigc::slot slot) const { +sigc::connection DocumentSubset::connectChanged(sigc::slot slot) const +{ return _relations->changed_signal.connect(slot); } -sigc::connection -DocumentSubset::connectAdded(sigc::slot slot) const { +sigc::connection DocumentSubset::connectAdded(sigc::slot slot) const +{ return _relations->added_signal.connect(slot); } -sigc::connection -DocumentSubset::connectRemoved(sigc::slot slot) const { +sigc::connection DocumentSubset::connectRemoved(sigc::slot slot) const +{ return _relations->removed_signal.connect(slot); } -} +} // namespace Inkscape /* Local Variables: diff --git a/src/document-subset.h b/src/document-subset.h index bbdf32e7688f0ef7071ca417804023677e70283a..760fe0c9bd05eaeea6f9d5b54aba59be77b9ec8b 100644 --- a/src/document-subset.h +++ b/src/document-subset.h @@ -15,16 +15,17 @@ #include #include -#include "inkgc/gc-managed.h" #include "gc-anchored.h" +#include "inkgc/gc-managed.h" class SPObject; class SPDocument; namespace Inkscape { -class DocumentSubset : public GC::Managed<>, - public GC::Anchored +class DocumentSubset + : public GC::Managed<> + , public GC::Anchored { public: bool includes(SPObject *obj) const; @@ -57,7 +58,7 @@ private: Relations *_relations; }; -} +} // namespace Inkscape #endif /* diff --git a/src/document-undo.cpp b/src/document-undo.cpp index de526a60c928df9f156976da28007c3cfe47e001..fa1187fdf1dedf3ce332d2887a898701b0ac2002 100644 --- a/src/document-undo.cpp +++ b/src/document-undo.cpp @@ -45,15 +45,16 @@ * (Lauris Kaplinski) */ -#include -#include "xml/repr.h" -#include "inkscape.h" #include "document-undo.h" + +#include + #include "debug/event-tracker.h" #include "debug/simple-event.h" #include "debug/timestamp.h" #include "event.h" - +#include "inkscape.h" +#include "xml/repr.h" /* * Undo & redo @@ -61,53 +62,52 @@ void Inkscape::DocumentUndo::setUndoSensitive(SPDocument *doc, bool sensitive) { - g_assert (doc != nullptr); + g_assert(doc != nullptr); - if ( sensitive == doc->sensitive ) - return; + if (sensitive == doc->sensitive) + return; - if (sensitive) { - sp_repr_begin_transaction (doc->rdoc); - } else { - doc->partial = sp_repr_coalesce_log ( - doc->partial, - sp_repr_commit_undoable (doc->rdoc) - ); - } + if (sensitive) { + sp_repr_begin_transaction(doc->rdoc); + } else { + doc->partial = sp_repr_coalesce_log(doc->partial, sp_repr_commit_undoable(doc->rdoc)); + } - doc->sensitive = sensitive; + doc->sensitive = sensitive; } -bool Inkscape::DocumentUndo::getUndoSensitive(SPDocument const *document) { - g_assert(document != nullptr); +bool Inkscape::DocumentUndo::getUndoSensitive(SPDocument const *document) +{ + g_assert(document != nullptr); - return document->sensitive; + return document->sensitive; } -void Inkscape::DocumentUndo::done(SPDocument *doc, const unsigned int event_type, Glib::ustring const &event_description) +void Inkscape::DocumentUndo::done(SPDocument *doc, const unsigned int event_type, + Glib::ustring const &event_description) { maybeDone(doc, nullptr, event_type, event_description); } -void Inkscape::DocumentUndo::resetKey( SPDocument *doc ) +void Inkscape::DocumentUndo::resetKey(SPDocument *doc) { doc->actionkey.clear(); } namespace { +using Inkscape::Verb; using Inkscape::Debug::Event; using Inkscape::Debug::SimpleEvent; using Inkscape::Debug::timestamp; -using Inkscape::Verb; typedef SimpleEvent InteractionEvent; -class CommitEvent : public InteractionEvent { +class CommitEvent : public InteractionEvent +{ public: - CommitEvent(SPDocument *doc, const gchar *key, const unsigned int type) - : InteractionEvent("commit") + : InteractionEvent("commit") { _addProperty("timestamp", timestamp()); _addProperty("document", doc->serial()); @@ -121,103 +121,104 @@ public: } }; -} +} // namespace void Inkscape::DocumentUndo::maybeDone(SPDocument *doc, const gchar *key, const unsigned int event_type, Glib::ustring const &event_description) { - g_assert (doc != nullptr); - g_assert (doc->sensitive); - if ( key && !*key ) { - g_warning("Blank undo key specified."); - } + g_assert(doc != nullptr); + g_assert(doc->sensitive); + if (key && !*key) { + g_warning("Blank undo key specified."); + } - Inkscape::Debug::EventTracker tracker(doc, key, event_type); + Inkscape::Debug::EventTracker tracker(doc, key, event_type); - doc->collectOrphans(); + doc->collectOrphans(); - doc->ensureUpToDate(); + doc->ensureUpToDate(); - DocumentUndo::clearRedo(doc); + DocumentUndo::clearRedo(doc); - Inkscape::XML::Event *log = sp_repr_coalesce_log (doc->partial, sp_repr_commit_undoable (doc->rdoc)); - doc->partial = nullptr; + Inkscape::XML::Event *log = sp_repr_coalesce_log(doc->partial, sp_repr_commit_undoable(doc->rdoc)); + doc->partial = nullptr; - if (!log) { - sp_repr_begin_transaction (doc->rdoc); - return; - } + if (!log) { + sp_repr_begin_transaction(doc->rdoc); + return; + } - if (key && !doc->actionkey.empty() && (doc->actionkey == key) && !doc->undo.empty()) { - (doc->undo.back())->event = - sp_repr_coalesce_log ((doc->undo.back())->event, log); - } else { - Inkscape::Event *event = new Inkscape::Event(log, event_type, event_description); - doc->undo.push_back(event); - doc->history_size++; - doc->undoStackObservers.notifyUndoCommitEvent(event); - } + if (key && !doc->actionkey.empty() && (doc->actionkey == key) && !doc->undo.empty()) { + (doc->undo.back())->event = sp_repr_coalesce_log((doc->undo.back())->event, log); + } else { + Inkscape::Event *event = new Inkscape::Event(log, event_type, event_description); + doc->undo.push_back(event); + doc->history_size++; + doc->undoStackObservers.notifyUndoCommitEvent(event); + } - if ( key ) { - doc->actionkey = key; - } else { - doc->actionkey.clear(); - } + if (key) { + doc->actionkey = key; + } else { + doc->actionkey.clear(); + } - doc->virgin = FALSE; - doc->setModifiedSinceSave(); + doc->virgin = FALSE; + doc->setModifiedSinceSave(); - sp_repr_begin_transaction (doc->rdoc); + sp_repr_begin_transaction(doc->rdoc); - doc->commit_signal.emit(); + doc->commit_signal.emit(); } void Inkscape::DocumentUndo::cancel(SPDocument *doc) { - g_assert (doc != nullptr); - g_assert (doc->sensitive); + g_assert(doc != nullptr); + g_assert(doc->sensitive); - sp_repr_rollback (doc->rdoc); + sp_repr_rollback(doc->rdoc); - if (doc->partial) { - sp_repr_undo_log (doc->partial); - doc->emitReconstructionFinish(); - sp_repr_free_log (doc->partial); - doc->partial = nullptr; - } + if (doc->partial) { + sp_repr_undo_log(doc->partial); + doc->emitReconstructionFinish(); + sp_repr_free_log(doc->partial); + doc->partial = nullptr; + } - sp_repr_begin_transaction (doc->rdoc); + sp_repr_begin_transaction(doc->rdoc); } // Member function for friend access to SPDocument privates. -void Inkscape::DocumentUndo::finish_incomplete_transaction(SPDocument &doc) { - Inkscape::XML::Event *log=sp_repr_commit_undoable(doc.rdoc); - if (log || doc.partial) { - g_warning ("Incomplete undo transaction:"); - doc.partial = sp_repr_coalesce_log(doc.partial, log); - sp_repr_debug_print_log(doc.partial); - Inkscape::Event *event = new Inkscape::Event(doc.partial); - doc.undo.push_back(event); - doc.undoStackObservers.notifyUndoCommitEvent(event); - doc.partial = nullptr; - } +void Inkscape::DocumentUndo::finish_incomplete_transaction(SPDocument &doc) +{ + Inkscape::XML::Event *log = sp_repr_commit_undoable(doc.rdoc); + if (log || doc.partial) { + g_warning("Incomplete undo transaction:"); + doc.partial = sp_repr_coalesce_log(doc.partial, log); + sp_repr_debug_print_log(doc.partial); + Inkscape::Event *event = new Inkscape::Event(doc.partial); + doc.undo.push_back(event); + doc.undoStackObservers.notifyUndoCommitEvent(event); + doc.partial = nullptr; + } } // Member function for friend access to SPDocument privates. -void Inkscape::DocumentUndo::perform_document_update(SPDocument &doc) { +void Inkscape::DocumentUndo::perform_document_update(SPDocument &doc) +{ sp_repr_begin_transaction(doc.rdoc); doc.ensureUpToDate(); - Inkscape::XML::Event *update_log=sp_repr_commit_undoable(doc.rdoc); + Inkscape::XML::Event *update_log = sp_repr_commit_undoable(doc.rdoc); doc.emitReconstructionFinish(); if (update_log != nullptr) { g_warning("Document was modified while being updated after undo operation"); sp_repr_debug_print_log(update_log); - //Coalesce the update changes with the last action performed by user + // Coalesce the update changes with the last action performed by user if (!doc.undo.empty()) { - Inkscape::Event* undo_stack_top = doc.undo.back(); + Inkscape::Event *undo_stack_top = doc.undo.back(); undo_stack_top->event = sp_repr_coalesce_log(undo_stack_top->event, update_log); } else { sp_repr_free_log(update_log); @@ -232,95 +233,96 @@ gboolean Inkscape::DocumentUndo::undo(SPDocument *doc) gboolean ret; - EventTracker > tracker("undo"); + EventTracker> tracker("undo"); - g_assert (doc != nullptr); - g_assert (doc->sensitive); + g_assert(doc != nullptr); + g_assert(doc->sensitive); doc->sensitive = FALSE; - doc->seeking = true; + doc->seeking = true; doc->actionkey.clear(); finish_incomplete_transaction(*doc); - if (! doc->undo.empty()) { - Inkscape::Event *log = doc->undo.back(); - doc->undo.pop_back(); - sp_repr_undo_log (log->event); - perform_document_update(*doc); + if (!doc->undo.empty()) { + Inkscape::Event *log = doc->undo.back(); + doc->undo.pop_back(); + sp_repr_undo_log(log->event); + perform_document_update(*doc); - doc->redo.push_back(log); + doc->redo.push_back(log); - doc->setModifiedSinceSave(); - doc->undoStackObservers.notifyUndoEvent(log); + doc->setModifiedSinceSave(); + doc->undoStackObservers.notifyUndoEvent(log); - ret = TRUE; + ret = TRUE; } else { - ret = FALSE; + ret = FALSE; } - sp_repr_begin_transaction (doc->rdoc); + sp_repr_begin_transaction(doc->rdoc); doc->sensitive = TRUE; - doc->seeking = false; + doc->seeking = false; - if (ret) INKSCAPE.external_change(); + if (ret) + INKSCAPE.external_change(); return ret; } gboolean Inkscape::DocumentUndo::redo(SPDocument *doc) { - using Inkscape::Debug::EventTracker; - using Inkscape::Debug::SimpleEvent; + using Inkscape::Debug::EventTracker; + using Inkscape::Debug::SimpleEvent; - gboolean ret; + gboolean ret; - EventTracker > tracker("redo"); + EventTracker> tracker("redo"); - g_assert (doc != nullptr); - g_assert (doc->sensitive); + g_assert(doc != nullptr); + g_assert(doc->sensitive); - doc->sensitive = FALSE; - doc->seeking = true; + doc->sensitive = FALSE; + doc->seeking = true; - doc->actionkey.clear(); + doc->actionkey.clear(); - finish_incomplete_transaction(*doc); + finish_incomplete_transaction(*doc); - if (! doc->redo.empty()) { - Inkscape::Event *log = doc->redo.back(); - doc->redo.pop_back(); - sp_repr_replay_log (log->event); - doc->undo.push_back(log); + if (!doc->redo.empty()) { + Inkscape::Event *log = doc->redo.back(); + doc->redo.pop_back(); + sp_repr_replay_log(log->event); + doc->undo.push_back(log); - doc->setModifiedSinceSave(); - doc->undoStackObservers.notifyRedoEvent(log); + doc->setModifiedSinceSave(); + doc->undoStackObservers.notifyRedoEvent(log); - ret = TRUE; - } else { - ret = FALSE; - } + ret = TRUE; + } else { + ret = FALSE; + } - sp_repr_begin_transaction (doc->rdoc); + sp_repr_begin_transaction(doc->rdoc); - doc->sensitive = TRUE; - doc->seeking = false; + doc->sensitive = TRUE; + doc->seeking = false; - if (ret) { - INKSCAPE.external_change(); - doc->emitReconstructionFinish(); - } + if (ret) { + INKSCAPE.external_change(); + doc->emitReconstructionFinish(); + } - return ret; + return ret; } void Inkscape::DocumentUndo::clearUndo(SPDocument *doc) { - if (! doc->undo.empty()) + if (!doc->undo.empty()) doc->undoStackObservers.notifyClearUndoEvent(); - while (! doc->undo.empty()) { + while (!doc->undo.empty()) { Inkscape::Event *e = doc->undo.back(); doc->undo.pop_back(); delete e; @@ -330,10 +332,10 @@ void Inkscape::DocumentUndo::clearUndo(SPDocument *doc) void Inkscape::DocumentUndo::clearRedo(SPDocument *doc) { - if (!doc->redo.empty()) - doc->undoStackObservers.notifyClearRedoEvent(); + if (!doc->redo.empty()) + doc->undoStackObservers.notifyClearRedoEvent(); - while (! doc->redo.empty()) { + while (!doc->redo.empty()) { Inkscape::Event *e = doc->redo.back(); doc->redo.pop_back(); delete e; diff --git a/src/document-undo.h b/src/document-undo.h index 73c41819c9cb9188ca6dba5a4b5ce76b1f8419c4..15fbf2079e62288de5faddae6f77b09a29023f64 100644 --- a/src/document-undo.h +++ b/src/document-undo.h @@ -10,10 +10,10 @@ #ifndef SEEN_SP_DOCUMENT_UNDO_H #define SEEN_SP_DOCUMENT_UNDO_H -#include // gboolean, gchar +#include // gboolean, gchar namespace Glib { - class ustring; +class ustring; } class SPDocument; @@ -23,12 +23,11 @@ namespace Inkscape { class DocumentUndo { public: - /** * Set undo sensitivity. * * Don't use this to temporarily turn sensitivity off, use ScopedInsensitive instead. - */ + */ static void setUndoSensitive(SPDocument *doc, bool sensitive); static bool getUndoSensitive(SPDocument const *document); @@ -39,7 +38,8 @@ public: static void done(SPDocument *document, unsigned int event_type, Glib::ustring const &event_description); - static void maybeDone(SPDocument *document, const gchar *keyconst, unsigned int event_type, Glib::ustring const &event_description); + static void maybeDone(SPDocument *document, const gchar *keyconst, unsigned int event_type, + Glib::ustring const &event_description); private: static void finish_incomplete_transaction(SPDocument &document); @@ -65,11 +65,12 @@ public: // "tmp" goes out of scope here and automatically restores undo-sensitivity } \endverbatim */ - class ScopedInsensitive { - SPDocument * m_doc; + class ScopedInsensitive + { + SPDocument *m_doc; bool m_saved; - public: + public: ScopedInsensitive(SPDocument *doc) : m_doc(doc) { diff --git a/src/document.cpp b/src/document.cpp index 11c34790e19dceec0c7862198810048a29c17278..753972ea622a69979883b205bdee4014125ad466 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -33,37 +33,28 @@ * the 'modified' signal, as well. */ - #define noSP_DOCUMENT_DEBUG_IDLE #define noSP_DOCUMENT_DEBUG_UNDO -#include -#include -#include - #include <2geom/transforms.h> +#include +#include +#include +#include "3rdparty/adaptagrams/libavoid/router.h" +#include "3rdparty/libcroco/cr-parser.h" +#include "3rdparty/libcroco/cr-sel-eng.h" +#include "3rdparty/libcroco/cr-selector.h" +#include "actions/actions-canvas-snapping.h" #include "desktop.h" -#include "io/dir-util.h" +#include "display/drawing.h" #include "document-undo.h" #include "file.h" #include "id-clash.h" #include "inkscape-version.h" -#include "inkscape.h" #include "inkscape-window.h" -#include "profile-manager.h" -#include "rdf.h" - -#include "actions/actions-canvas-snapping.h" - -#include "display/drawing.h" - -#include "3rdparty/adaptagrams/libavoid/router.h" - -#include "3rdparty/libcroco/cr-parser.h" -#include "3rdparty/libcroco/cr-sel-eng.h" -#include "3rdparty/libcroco/cr-selector.h" - +#include "inkscape.h" +#include "io/dir-util.h" #include "live_effects/lpeobject.h" #include "object/persp3d.h" #include "object/sp-defs.h" @@ -71,9 +62,9 @@ #include "object/sp-namedview.h" #include "object/sp-root.h" #include "object/sp-symbol.h" - +#include "profile-manager.h" +#include "rdf.h" #include "widgets/desktop-widget.h" - #include "xml/croco-node-iface.h" #include "xml/rebase-hrefs.h" @@ -89,32 +80,33 @@ using Inkscape::Util::unit_table; bool sp_no_convert_text_baseline_spacing = false; -//gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data); +// gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data); static gint doc_count = 0; static gint doc_mem_count = 0; static unsigned long next_serial = 0; -SPDocument::SPDocument() : - keepalive(false), - virgin(true), - rdoc(nullptr), - rroot(nullptr), - root(nullptr), - style_cascade(cr_cascade_new(nullptr, nullptr, nullptr)), - document_uri(nullptr), - document_base(nullptr), - document_name(nullptr), - actionkey(), - profileManager(nullptr), // deferred until after other initialization - router(new Avoid::Router(Avoid::PolyLineRouting|Avoid::OrthogonalRouting)), - oldSignalsConnected(false), - current_persp3d(nullptr), - current_persp3d_impl(nullptr), - _parent_document(nullptr), - _node_cache_valid(false), - _activexmltree(nullptr) +SPDocument::SPDocument() + : keepalive(false) + , virgin(true) + , rdoc(nullptr) + , rroot(nullptr) + , root(nullptr) + , style_cascade(cr_cascade_new(nullptr, nullptr, nullptr)) + , document_uri(nullptr) + , document_base(nullptr) + , document_name(nullptr) + , actionkey() + , profileManager(nullptr) + , // deferred until after other initialization + router(new Avoid::Router(Avoid::PolyLineRouting | Avoid::OrthogonalRouting)) + , oldSignalsConnected(false) + , current_persp3d(nullptr) + , current_persp3d_impl(nullptr) + , _parent_document(nullptr) + , _node_cache_valid(false) + , _activexmltree(nullptr) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -138,18 +130,19 @@ SPDocument::SPDocument() : // XXX only for testing! undoStackObservers.add(console_output_undo_observer); - _node_cache = std::deque(); + _node_cache = std::deque(); // Actions action_group = Gio::SimpleActionGroup::create(); add_actions_canvas_snapping(this); } -SPDocument::~SPDocument() { +SPDocument::~SPDocument() +{ destroySignal.emit(); // kill/unhook this first - if ( profileManager ) { + if (profileManager) { delete profileManager; profileManager = nullptr; } @@ -181,7 +174,8 @@ SPDocument::~SPDocument() { root = nullptr; } - if (rdoc) Inkscape::GC::release(rdoc); + if (rdoc) + Inkscape::GC::release(rdoc); /* Free resources */ resources.clear(); @@ -221,7 +215,7 @@ SPDocument::~SPDocument() { Inkscape::XML::Node *SPDocument::getReprNamedView() { - return sp_repr_lookup_name (rroot, "sodipodi:namedview"); + return sp_repr_lookup_name(rroot, "sodipodi:namedview"); } SPDefs *SPDocument::getDefs() @@ -232,29 +226,31 @@ SPDefs *SPDocument::getDefs() return root->defs; } -Persp3D *SPDocument::getCurrentPersp3D() { +Persp3D *SPDocument::getCurrentPersp3D() +{ // Check if current_persp3d is still valid - std::vector plist; + std::vector plist; getPerspectivesInDefs(plist); - for (auto & i : plist) { + for (auto &i : plist) { if (current_persp3d == i) return current_persp3d; } // If not, return the first perspective in defs (which may be NULL of none exists) - current_persp3d = Persp3D::document_first_persp (this); + current_persp3d = Persp3D::document_first_persp(this); return current_persp3d; } -void SPDocument::setCurrentPersp3D(Persp3D * const persp) { +void SPDocument::setCurrentPersp3D(Persp3D *const persp) +{ current_persp3d = persp; - //current_persp3d_impl = persp->perspective_impl; + // current_persp3d_impl = persp->perspective_impl; } -void SPDocument::getPerspectivesInDefs(std::vector &list) const +void SPDocument::getPerspectivesInDefs(std::vector &list) const { - for (auto& i: root->defs->children) { + for (auto &i : root->defs->children) { if (SP_IS_PERSP3D(&i)) { list.push_back(SP_PERSP3D(&i)); } @@ -271,7 +267,8 @@ void SPDocument::initialize_current_persp3d() } **/ -void SPDocument::queueForOrphanCollection(SPObject *object) { +void SPDocument::queueForOrphanCollection(SPObject *object) +{ g_return_if_fail(object != nullptr); g_return_if_fail(object->document == this); @@ -279,7 +276,8 @@ void SPDocument::queueForOrphanCollection(SPObject *object) { _collection_queue.push_back(object); } -void SPDocument::collectOrphans() { +void SPDocument::collectOrphans() +{ while (!_collection_queue.empty()) { std::vector objects(_collection_queue); _collection_queue.clear(); @@ -290,12 +288,8 @@ void SPDocument::collectOrphans() { } } -SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc, - gchar const *document_uri, - gchar const *document_base, - gchar const *document_name, - bool keepalive, - SPDocument *parent) +SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc, gchar const *document_uri, gchar const *document_base, + gchar const *document_name, bool keepalive, SPDocument *parent) { SPDocument *document = new SPDocument(); @@ -311,15 +305,15 @@ SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc, parent->_child_documents.push_back(document); } - if (document->document_uri){ + if (document->document_uri) { g_free(document->document_uri); document->document_uri = nullptr; } - if (document->document_base){ + if (document->document_base) { g_free(document->document_base); document->document_base = nullptr; } - if (document->document_name){ + if (document->document_name) { g_free(document->document_name); document->document_name = nullptr; } @@ -327,12 +321,12 @@ SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc, document->document_uri = prepend_current_dir_if_relative(document_uri); #else // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test! - document->document_uri = document_uri? g_strdup(document_uri) : NULL; + document->document_uri = document_uri ? g_strdup(document_uri) : NULL; #endif // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../" // which is why we use g_get_current_dir() in calculating the abs path above - //This is NULL for a new document + // This is NULL for a new document if (document_base) { document->document_base = g_strdup(document_base); } else { @@ -342,15 +336,15 @@ SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc, // Create SPRoot element const std::string typeString = NodeTraits::get_type_string(*rroot); - SPObject* rootObj = SPFactory::createObject(typeString); - document->root = dynamic_cast(rootObj); + SPObject *rootObj = SPFactory::createObject(typeString); + document->root = dynamic_cast(rootObj); if (document->root == nullptr) { - // Node is not a valid root element - delete rootObj; + // Node is not a valid root element + delete rootObj; - // fixme: what to do here? - throw; + // fixme: what to do here? + throw; } // Recursively build object tree @@ -368,7 +362,7 @@ SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc, Inkscape::XML::Node *rnew = nullptr; rnew = rdoc->createElement("sodipodi:namedview"); - //rnew->setAttribute("id", "base"); + // rnew->setAttribute("id", "base"); // Add namedview data from the preferences // we can't use getAllEntries because this could produce non-SVG doubles @@ -380,22 +374,15 @@ SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc, rnew->setAttributeOrRemoveIfEmpty("bordercolor", bordercolor.data()); - sp_repr_set_svg_double(rnew, "borderopacity", - prefs->getDouble("/template/base/borderopacity", 1.0)); - sp_repr_set_svg_double(rnew, "objecttolerance", - prefs->getDouble("/template/base/objecttolerance", 10.0)); - sp_repr_set_svg_double(rnew, "gridtolerance", - prefs->getDouble("/template/base/gridtolerance", 10.0)); - sp_repr_set_svg_double(rnew, "guidetolerance", - prefs->getDouble("/template/base/guidetolerance", 10.0)); + sp_repr_set_svg_double(rnew, "borderopacity", prefs->getDouble("/template/base/borderopacity", 1.0)); + sp_repr_set_svg_double(rnew, "objecttolerance", prefs->getDouble("/template/base/objecttolerance", 10.0)); + sp_repr_set_svg_double(rnew, "gridtolerance", prefs->getDouble("/template/base/gridtolerance", 10.0)); + sp_repr_set_svg_double(rnew, "guidetolerance", prefs->getDouble("/template/base/guidetolerance", 10.0)); sp_repr_set_svg_double(rnew, "inkscape:pageopacity", - prefs->getDouble("/template/base/inkscape:pageopacity", 0.0)); - sp_repr_set_int(rnew, "inkscape:pageshadow", - prefs->getInt("/template/base/inkscape:pageshadow", 2)); - sp_repr_set_int(rnew, "inkscape:window-width", - prefs->getInt("/template/base/inkscape:window-width", 640)); - sp_repr_set_int(rnew, "inkscape:window-height", - prefs->getInt("/template/base/inkscape:window-height", 480)); + prefs->getDouble("/template/base/inkscape:pageopacity", 0.0)); + sp_repr_set_int(rnew, "inkscape:pageshadow", prefs->getInt("/template/base/inkscape:pageshadow", 2)); + sp_repr_set_int(rnew, "inkscape:window-width", prefs->getInt("/template/base/inkscape:window-width", 640)); + sp_repr_set_int(rnew, "inkscape:window-height", prefs->getInt("/template/base/inkscape:window-height", 480)); // insert into the document rroot->addChild(rnew, nullptr); @@ -412,7 +399,7 @@ SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc, } /* Default RDF */ - rdf_set_defaults( document ); + rdf_set_defaults(document); if (keepalive) { inkscape_ref(INKSCAPE); @@ -422,7 +409,7 @@ SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc, // document). If not, create a new one and set it as the current perspective. document->setCurrentPersp3D(Persp3D::document_first_persp(document)); if (!document->getCurrentPersp3D()) { - //document->setCurrentPersp3D(Persp3D::create_xml_element (document)); + // document->setCurrentPersp3D(Persp3D::create_xml_element (document)); Persp3DImpl *persp_impl = new Persp3DImpl(); document->setCurrentPersp3DImpl(persp_impl); } @@ -431,31 +418,25 @@ SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc, // reset undo key when selection changes, so that same-key actions on different objects are not coalesced document->selChangeConnection = INKSCAPE.signal_selection_changed.connect( - sigc::hide(sigc::bind( - sigc::ptr_fun(&DocumentUndo::resetKey), document) - )); + sigc::hide(sigc::bind(sigc::ptr_fun(&DocumentUndo::resetKey), document))); document->desktopActivatedConnection = INKSCAPE.signal_activate_desktop.connect( - sigc::hide(sigc::bind( - sigc::ptr_fun(&DocumentUndo::resetKey), document) - )); + sigc::hide(sigc::bind(sigc::ptr_fun(&DocumentUndo::resetKey), document))); document->oldSignalsConnected = true; - // ************* Fix Document ************** // Move to separate function? /** Fix OSB **/ sp_file_fix_osb(document->getRoot()); - /** Fix baseline spacing (pre-92 files) **/ - if ( (!sp_no_convert_text_baseline_spacing) - && sp_version_inside_range( document->root->version.inkscape, 0, 1, 0, 92 ) ) { + if ((!sp_no_convert_text_baseline_spacing) && + sp_version_inside_range(document->root->version.inkscape, 0, 1, 0, 92)) { sp_file_convert_text_baseline_spacing(document); } /** Fix font names in legacy documents (pre-92 files) **/ - if ( sp_version_inside_range( document->root->version.inkscape, 0, 1, 0, 92 ) ) { + if (sp_version_inside_range(document->root->version.inkscape, 0, 1, 0, 92)) { sp_file_convert_font_name(document); } @@ -465,12 +446,12 @@ SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc, } /** Fix dpi (pre-92 files). With GUI fixed in Inkscape::Application::fix_document. **/ - if ( !(INKSCAPE.use_gui()) && sp_version_inside_range( document->root->version.inkscape, 0, 1, 0, 92 ) ) { + if (!(INKSCAPE.use_gui()) && sp_version_inside_range(document->root->version.inkscape, 0, 1, 0, 92)) { sp_file_convert_dpi(document); } // Update LPE's See: Related bug:#1769679 #18 - SPDefs * defs = document->getDefs(); + SPDefs *defs = document->getDefs(); if (defs) { defs->emitModified(SP_OBJECT_MODIFIED_CASCADE); } @@ -489,17 +470,16 @@ SPDocument *SPDocument::createChildDoc(std::string const &document_uri) SPDocument *parent = this; SPDocument *document = nullptr; - while(parent != nullptr && parent->getDocumentURI() != nullptr && document == nullptr) { + while (parent != nullptr && parent->getDocumentURI() != nullptr && document == nullptr) { // Check myself and any parents in the chain - if(document_uri == parent->getDocumentURI()) { + if (document_uri == parent->getDocumentURI()) { document = parent; break; } // Then check children of those. boost::ptr_list::iterator iter; - for (iter = parent->_child_documents.begin(); - iter != parent->_child_documents.end(); ++iter) { - if(document_uri == iter->getDocumentURI()) { + for (iter = parent->_child_documents.begin(); iter != parent->_child_documents.end(); ++iter) { + if (document_uri == iter->getDocumentURI()) { document = &*iter; break; } @@ -508,7 +488,7 @@ SPDocument *SPDocument::createChildDoc(std::string const &document_uri) } // Load a fresh document from the svg source. - if(!document) { + if (!document) { std::string path; if (Glib::path_is_absolute(document_uri)) { path = document_uri; @@ -534,11 +514,13 @@ SPDocument *SPDocument::createNewDoc(gchar const *document_uri, bool keepalive, /* Try to fetch repr from file */ rdoc = sp_repr_read_file(document_uri, SP_SVG_NS_URI); /* If file cannot be loaded, return NULL without warning */ - if (rdoc == nullptr) return nullptr; + if (rdoc == nullptr) + return nullptr; rroot = rdoc->root(); /* If xml file is not svg, return NULL without warning */ /* fixme: destroy document */ - if (strcmp(rroot->name(), "svg:svg") != 0) return nullptr; + if (strcmp(rroot->name(), "svg:svg") != 0) + return nullptr; if (make_new) { document_base = nullptr; @@ -576,14 +558,14 @@ SPDocument *SPDocument::createNewDocFromMem(gchar const *buffer, gint length, bo SPDocument *doc = nullptr; Inkscape::XML::Document *rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI); - if ( rdoc ) { + if (rdoc) { // Only continue to create a non-null doc if it could be loaded Inkscape::XML::Node *rroot = rdoc->root(); - if ( strcmp(rroot->name(), "svg:svg") != 0 ) { + if (strcmp(rroot->name(), "svg:svg") != 0) { // If xml file is not svg, return NULL without warning // TODO fixme: destroy document } else { - Glib::ustring document_name = Glib::ustring::compose( _("Memory document %1"), ++doc_mem_count ); + Glib::ustring document_name = Glib::ustring::compose(_("Memory document %1"), ++doc_mem_count); doc = createDoc(rdoc, nullptr, nullptr, document_name.c_str(), keepalive, nullptr); } } @@ -598,27 +580,25 @@ std::unique_ptr SPDocument::doRef() } /// guaranteed not to return nullptr -Inkscape::Util::Unit const* SPDocument::getDisplayUnit() const +Inkscape::Util::Unit const *SPDocument::getDisplayUnit() const { - SPNamedView const* nv = sp_document_namedview(this, nullptr); + SPNamedView const *nv = sp_document_namedview(this, nullptr); return nv ? nv->getDisplayUnit() : unit_table.getUnit("px"); } /// Sets document scale (by changing viewBox) -void SPDocument::setDocumentScale( double scaleX, double scaleY ) { - - root->viewBox = Geom::Rect::from_xywh( - root->viewBox.left(), - root->viewBox.top(), - root->width.computed * scaleX, - root->height.computed * scaleY ); +void SPDocument::setDocumentScale(double scaleX, double scaleY) +{ + root->viewBox = Geom::Rect::from_xywh(root->viewBox.left(), root->viewBox.top(), root->width.computed * scaleX, + root->height.computed * scaleY); root->viewBox_set = true; root->updateRepr(); } /// Sets document scale (by changing viewBox, x and y scaling equal) -void SPDocument::setDocumentScale( double scale ) { - setDocumentScale( scale, scale ); +void SPDocument::setDocumentScale(double scale) +{ + setDocumentScale(scale, scale); } /// Returns document scale as defined by width/height (in pixels) and viewBox (real world to @@ -626,13 +606,13 @@ void SPDocument::setDocumentScale( double scale ) { Geom::Scale SPDocument::getDocumentScale() const { Geom::Scale scale; - if( root->viewBox_set ) { + if (root->viewBox_set) { double scale_x = 1.0; double scale_y = 1.0; - if( root->viewBox.width() > 0.0 ) { + if (root->viewBox.width() > 0.0) { scale_x = root->width.computed / root->viewBox.width(); } - if( root->viewBox.height() > 0.0 ) { + if (root->viewBox.height() > 0.0) { scale_y = root->height.computed / root->viewBox.height(); } scale = Geom::Scale(scale_x, scale_y); @@ -643,12 +623,13 @@ Geom::Scale SPDocument::getDocumentScale() const // Avoid calling root->updateRepr() twice by combining setting width and height. // (As done on every delete as clipboard calls this via fitToRect(). Also called in page-sizer.cpp) -void SPDocument::setWidthAndHeight(const Inkscape::Util::Quantity &width, const Inkscape::Util::Quantity &height, bool changeSize) +void SPDocument::setWidthAndHeight(const Inkscape::Util::Quantity &width, const Inkscape::Util::Quantity &height, + bool changeSize) { Inkscape::Util::Unit const *old_width_units = unit_table.getUnit("px"); if (root->width.unit) old_width_units = unit_table.getUnit(root->width.unit); - gdouble old_width_converted; // old width converted to new units + gdouble old_width_converted; // old width converted to new units if (root->width.unit == SVGLength::PERCENT) old_width_converted = Inkscape::Util::Quantity::convert(root->width.computed, "px", width.unit); else @@ -656,12 +637,12 @@ void SPDocument::setWidthAndHeight(const Inkscape::Util::Quantity &width, const root->width.computed = width.value("px"); root->width.value = width.quantity; - root->width.unit = (SVGLength::Unit) width.unit->svgUnit(); + root->width.unit = (SVGLength::Unit)width.unit->svgUnit(); Inkscape::Util::Unit const *old_height_units = unit_table.getUnit("px"); if (root->height.unit) old_height_units = unit_table.getUnit(root->height.unit); - gdouble old_height_converted; // old height converted to new units + gdouble old_height_converted; // old height converted to new units if (root->height.unit == SVGLength::PERCENT) old_height_converted = Inkscape::Util::Quantity::convert(root->height.computed, "px", height.unit); else @@ -669,13 +650,13 @@ void SPDocument::setWidthAndHeight(const Inkscape::Util::Quantity &width, const root->height.computed = height.value("px"); root->height.value = height.quantity; - root->height.unit = (SVGLength::Unit) height.unit->svgUnit(); + root->height.unit = (SVGLength::Unit)height.unit->svgUnit(); // viewBox scaled by relative change in page size (maintains document scale). if (root->viewBox_set && changeSize) { - root->viewBox.setMax(Geom::Point( - root->viewBox.left() + (root->width.value / old_width_converted ) * root->viewBox.width(), - root->viewBox.top() + (root->height.value / old_height_converted) * root->viewBox.height())); + root->viewBox.setMax( + Geom::Point(root->viewBox.left() + (root->width.value / old_width_converted) * root->viewBox.width(), + root->viewBox.top() + (root->height.value / old_height_converted) * root->viewBox.height())); } root->updateRepr(); } @@ -701,7 +682,7 @@ void SPDocument::setWidth(const Inkscape::Util::Quantity &width, bool changeSize Inkscape::Util::Unit const *old_width_units = unit_table.getUnit("px"); if (root->width.unit) old_width_units = unit_table.getUnit(root->width.unit); - gdouble old_width_converted; // old width converted to new units + gdouble old_width_converted; // old width converted to new units if (root->width.unit == SVGLength::PERCENT) old_width_converted = Inkscape::Util::Quantity::convert(root->width.computed, "px", width.unit); else @@ -709,15 +690,16 @@ void SPDocument::setWidth(const Inkscape::Util::Quantity &width, bool changeSize root->width.computed = width.value("px"); root->width.value = width.quantity; - root->width.unit = (SVGLength::Unit) width.unit->svgUnit(); + root->width.unit = (SVGLength::Unit)width.unit->svgUnit(); if (root->viewBox_set && changeSize) - root->viewBox.setMax(Geom::Point(root->viewBox.left() + (root->width.value / old_width_converted) * root->viewBox.width(), root->viewBox.bottom())); + root->viewBox.setMax( + Geom::Point(root->viewBox.left() + (root->width.value / old_width_converted) * root->viewBox.width(), + root->viewBox.bottom())); root->updateRepr(); } - Inkscape::Util::Quantity SPDocument::getHeight() const { g_return_val_if_fail(this->root != nullptr, Inkscape::Util::Quantity(0.0, unit_table.getUnit(""))); @@ -739,7 +721,7 @@ void SPDocument::setHeight(const Inkscape::Util::Quantity &height, bool changeSi Inkscape::Util::Unit const *old_height_units = unit_table.getUnit("px"); if (root->height.unit) old_height_units = unit_table.getUnit(root->height.unit); - gdouble old_height_converted; // old height converted to new units + gdouble old_height_converted; // old height converted to new units if (root->height.unit == SVGLength::PERCENT) old_height_converted = Inkscape::Util::Quantity::convert(root->height.computed, "px", height.unit); else @@ -747,10 +729,12 @@ void SPDocument::setHeight(const Inkscape::Util::Quantity &height, bool changeSi root->height.computed = height.value("px"); root->height.value = height.quantity; - root->height.unit = (SVGLength::Unit) height.unit->svgUnit(); + root->height.unit = (SVGLength::Unit)height.unit->svgUnit(); if (root->viewBox_set && changeSize) - root->viewBox.setMax(Geom::Point(root->viewBox.right(), root->viewBox.top() + (root->height.value / old_height_converted) * root->viewBox.height())); + root->viewBox.setMax( + Geom::Point(root->viewBox.right(), + root->viewBox.top() + (root->height.value / old_height_converted) * root->viewBox.height())); root->updateRepr(); } @@ -770,7 +754,7 @@ Geom::Rect SPDocument::getViewBox() const if (root->viewBox_set) { viewBox = root->viewBox; } else { - viewBox = Geom::Rect::from_xywh( 0, 0, getWidth().value("px"), getHeight().value("px")); + viewBox = Geom::Rect::from_xywh(0, 0, getWidth().value("px"), getHeight().value("px")); } return viewBox; } @@ -780,10 +764,7 @@ Geom::Rect SPDocument::getViewBox() const */ void SPDocument::setViewBox() { - setViewBox(Geom::Rect(0, - 0, - getWidth().value(getDisplayUnit()), - getHeight().value(getDisplayUnit()))); + setViewBox(Geom::Rect(0, 0, getWidth().value(getDisplayUnit()), getHeight().value(getDisplayUnit()))); } void SPDocument::setViewBox(const Geom::Rect &viewBox) @@ -800,7 +781,7 @@ Geom::Point SPDocument::getDimensions() const Geom::OptRect SPDocument::preferredBounds() const { - return Geom::OptRect( Geom::Point(0, 0), getDimensions() ); + return Geom::OptRect(Geom::Point(0, 0), getDimensions()); } /** @@ -843,17 +824,16 @@ void SPDocument::fitToRect(Geom::Rect const &rect, bool with_margins) double y_dir = yaxisdir(); - Geom::Rect const rect_with_margins( - rect.min() - Geom::Point(margin_left, margin_top), - rect.max() + Geom::Point(margin_right, margin_bottom)); + Geom::Rect const rect_with_margins(rect.min() - Geom::Point(margin_left, margin_top), + rect.max() + Geom::Point(margin_right, margin_bottom)); // rect in desktop coordinates before changing document dimensions auto rect_with_margins_dt_old = rect_with_margins * doc2dt(); - setWidthAndHeight( - Inkscape::Util::Quantity(Inkscape::Util::Quantity::convert(rect_with_margins.width(), "px", nv_units), nv_units), - Inkscape::Util::Quantity(Inkscape::Util::Quantity::convert(rect_with_margins.height(), "px", nv_units), nv_units) - ); + setWidthAndHeight(Inkscape::Util::Quantity( + Inkscape::Util::Quantity::convert(rect_with_margins.width(), "px", nv_units), nv_units), + Inkscape::Util::Quantity( + Inkscape::Util::Quantity::convert(rect_with_margins.height(), "px", nv_units), nv_units)); // rect in desktop coordinates after changing document dimensions auto rect_with_margins_dt_new = rect_with_margins * doc2dt(); @@ -861,7 +841,7 @@ void SPDocument::fitToRect(Geom::Rect const &rect, bool with_margins) Geom::Translate const tr(-rect_with_margins_dt_new.min()); root->translateChildItems(tr); - if(nv) { + if (nv) { Geom::Translate tr2(-rect_with_margins_dt_old.min()); nv->translateGuides(tr2); nv->translateGrids(tr2); @@ -871,7 +851,7 @@ void SPDocument::fitToRect(Geom::Rect const &rect, bool with_margins) } } -void SPDocument::setDocumentBase( gchar const* document_base ) +void SPDocument::setDocumentBase(gchar const *document_base) { if (this->document_base) { g_free(this->document_base); @@ -888,7 +868,6 @@ void SPDocument::do_change_uri(gchar const *const filename, bool const rebase) gchar *new_document_name = nullptr; gchar *new_document_uri = nullptr; if (filename) { - #ifndef _WIN32 new_document_uri = prepend_current_dir_if_relative(filename); #else @@ -917,11 +896,10 @@ void SPDocument::do_change_uri(gchar const *const filename, bool const rebase) Inkscape::XML::rebase_hrefs(this, new_document_base, use_sodipodi_absref); } - if (strncmp(new_document_name, "ink_ext_XXXXXX", 14)) // do not use temporary filenames + if (strncmp(new_document_name, "ink_ext_XXXXXX", 14)) // do not use temporary filenames repr->setAttribute("sodipodi:docname", new_document_name); DocumentUndo::setUndoSensitive(this, saved); - g_free(this->document_name); g_free(this->document_base); g_free(this->document_uri); @@ -955,23 +933,24 @@ void SPDocument::changeUriAndHrefs(gchar const *filename) do_change_uri(filename, true); } -void SPDocument::bindObjectToId(gchar const *id, SPObject *object) { +void SPDocument::bindObjectToId(gchar const *id, SPObject *object) +{ GQuark idq = g_quark_from_string(id); if (object) { - if(object->getId()) + if (object->getId()) iddef.erase(object->getId()); - g_assert(iddef.find(id)==iddef.end()); + g_assert(iddef.find(id) == iddef.end()); iddef[id] = object; } else { - g_assert(iddef.find(id)!=iddef.end()); + g_assert(iddef.find(id) != iddef.end()); iddef.erase(id); } SPDocument::IDChangedSignalMap::iterator pos; pos = id_changed_signals.find(idq); - if ( pos != id_changed_signals.end() ) { + if (pos != id_changed_signals.end()) { if (!(*pos).second.empty()) { (*pos).second.emit(object); } else { // discard unused signal @@ -1012,13 +991,13 @@ void _getObjectsByClassRecursive(Glib::ustring const &klass, SPObject *parent, s class_attribute = temp; } - if (class_attribute.find( klass ) != std::string::npos) { - objects.push_back( parent ); + if (class_attribute.find(klass) != std::string::npos) { + objects.push_back(parent); } // Check children - for (auto& child : parent->children) { - _getObjectsByClassRecursive( klass, &child, objects ); + for (auto &child : parent->children) { + _getObjectsByClassRecursive(klass, &child, objects); } } } @@ -1032,8 +1011,7 @@ std::vector SPDocument::getObjectsByClass(Glib::ustring const &klass return objects; } -void _getObjectsByElementRecursive(Glib::ustring const &element, SPObject *parent, - std::vector &objects) +void _getObjectsByElementRecursive(Glib::ustring const &element, SPObject *parent, std::vector &objects) { if (parent) { Glib::ustring prefixed = "svg:" + element; @@ -1042,7 +1020,7 @@ void _getObjectsByElementRecursive(Glib::ustring const &element, SPObject *paren } // Check children - for (auto& child : parent->children) { + for (auto &child : parent->children) { _getObjectsByElementRecursive(element, &child, objects); } } @@ -1057,19 +1035,18 @@ std::vector SPDocument::getObjectsByElement(Glib::ustring const &ele return objects; } -void _getObjectsBySelectorRecursive(SPObject *parent, - CRSelEng *sel_eng, CRSimpleSel *simple_sel, +void _getObjectsBySelectorRecursive(SPObject *parent, CRSelEng *sel_eng, CRSimpleSel *simple_sel, std::vector &objects) { if (parent) { gboolean result = false; - cr_sel_eng_matches_node( sel_eng, simple_sel, parent->getRepr(), &result ); + cr_sel_eng_matches_node(sel_eng, simple_sel, parent->getRepr(), &result); if (result) { objects.push_back(parent); } // Check children - for (auto& child : parent->children) { + for (auto &child : parent->children) { _getObjectsBySelectorRecursive(&child, sel_eng, simple_sel, objects); } } @@ -1088,13 +1065,13 @@ std::vector SPDocument::getObjectsBySelector(Glib::ustring const &se cr_sel_eng_set_node_iface(sel_eng, &Inkscape::XML::croco_node_iface); } - Glib::ustring my_selector = selector + " {"; // Parsing fails sometimes without '{'. Fix me - CRSelector *cr_selector = cr_selector_parse_from_buf ((guchar*)my_selector.c_str(), CR_UTF_8); + Glib::ustring my_selector = selector + " {"; // Parsing fails sometimes without '{'. Fix me + CRSelector *cr_selector = cr_selector_parse_from_buf((guchar *)my_selector.c_str(), CR_UTF_8); // char * cr_string = (char*)cr_selector_to_string( cr_selector ); // std::cout << " selector: |" << (cr_string?cr_string:"Empty") << "|" << std::endl; CRSelector const *cur = nullptr; for (cur = cr_selector; cur; cur = cur->next) { - if (cur->simple_sel ) { + if (cur->simple_sel) { _getObjectsBySelectorRecursive(root, sel_eng, cur->simple_sel, objects); } } @@ -1104,10 +1081,10 @@ std::vector SPDocument::getObjectsBySelector(Glib::ustring const &se void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) { if (object) { - g_assert(reprdef.find(repr)==reprdef.end()); + g_assert(reprdef.find(repr) == reprdef.end()); reprdef[repr] = object; } else { - g_assert(reprdef.find(repr)!=reprdef.end()); + g_assert(reprdef.find(repr) != reprdef.end()); reprdef.erase(repr); } } @@ -1116,7 +1093,7 @@ SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) const { g_return_val_if_fail(repr != nullptr, NULL); std::map::const_iterator rv = reprdef.find(repr); - if(rv != reprdef.end()) + if (rv != reprdef.end()) return (rv->second); else return nullptr; @@ -1145,8 +1122,8 @@ std::vector SPDocument::getLanguages() const // get language from system locale (will also match the interface language preference as we set LANG accordingly) // TODO: This includes locales with encodings like "de_DE.UTF-8" - is this useful or should we skip these? // TODO: This includes the default "C" locale - is this useful or should we skip it? - const gchar * const * names = g_get_language_names(); - for (int i=0; names[i]; i++) { + const gchar *const *names = g_get_language_names(); + for (int i = 0; names[i]; i++) { document_languages.emplace_back(names[i]); } @@ -1159,14 +1136,12 @@ void SPDocument::requestModified() { if (modified_connection.empty()) { modified_connection = - Glib::signal_idle().connect(sigc::mem_fun(*this, &SPDocument::idle_handler), - SP_DOCUMENT_UPDATE_PRIORITY); + Glib::signal_idle().connect(sigc::mem_fun(*this, &SPDocument::idle_handler), SP_DOCUMENT_UPDATE_PRIORITY); } if (rerouting_connection.empty()) { - rerouting_connection = - Glib::signal_idle().connect(sigc::mem_fun(*this, &SPDocument::rerouting_handler), - SP_DOCUMENT_REROUTING_PRIORITY); + rerouting_connection = Glib::signal_idle().connect(sigc::mem_fun(*this, &SPDocument::rerouting_handler), + SP_DOCUMENT_REROUTING_PRIORITY); } } @@ -1178,7 +1153,8 @@ void SPDocument::setupViewport(SPItemCtx *ctx) if (root->viewBox_set) { // if set, take from viewBox ctx->viewport = root->viewBox; } else { // as a last resort, set size to A4 - ctx->viewport = Geom::Rect::from_xywh(0, 0, Inkscape::Util::Quantity::convert(210, "mm", "px"), Inkscape::Util::Quantity::convert(297, "mm", "px")); + ctx->viewport = Geom::Rect::from_xywh(0, 0, Inkscape::Util::Quantity::convert(210, "mm", "px"), + Inkscape::Util::Quantity::convert(297, "mm", "px")); } ctx->i2vp = Geom::identity(); } @@ -1188,8 +1164,7 @@ void SPDocument::setupViewport(SPItemCtx *ctx) * "update required" flags, and return true if the document has * been brought fully up to date. */ -bool -SPDocument::_updateDocument(int update_flags) +bool SPDocument::_updateDocument(int update_flags) { /* Process updates */ if (this->root->uflags || this->root->mflags) { @@ -1207,7 +1182,6 @@ SPDocument::_updateDocument(int update_flags) return !(this->root->uflags || this->root->mflags); } - /** * Repeatedly works on getting the document updated, since sometimes * it takes more than one pass to get the document updated. But it @@ -1231,14 +1205,13 @@ gint SPDocument::ensureUpToDate() } counter--; } - if (counter == 0) - { + if (counter == 0) { break; } // After updates on the first pass we get libavoid to process all the // changed objects and provide new routings. This may cause some objects - // to be modified, hence the second update pass. + // to be modified, hence the second update pass. if (pass == 1) { router->processTransaction(); } @@ -1255,8 +1228,7 @@ gint SPDocument::ensureUpToDate() * An idle handler to update the document. Returns true if * the document needs further updates. */ -bool -SPDocument::idle_handler() +bool SPDocument::idle_handler() { bool status = !_updateDocument(0); // method TRUE if it does NOT need further modification, so invert if (!status) { @@ -1268,8 +1240,7 @@ SPDocument::idle_handler() /** * An idle handler to reroute connectors in the document. */ -bool -SPDocument::rerouting_handler() +bool SPDocument::rerouting_handler() { // Process any queued movement actions and determine new routings for // object-avoiding connectors. Callbacks will be used to update and @@ -1294,18 +1265,15 @@ static bool overlaps(Geom::Rect const &area, Geom::Rect const &box) /** * @param area Area in document coordinates */ -static std::vector &find_items_in_area(std::vector &s, - SPGroup *group, unsigned int dkey, - Geom::Rect const &area, - bool (*test)(Geom::Rect const &, Geom::Rect const &), - bool take_hidden = false, - bool take_insensitive = false, - bool take_groups = true, - bool enter_groups = false) +static std::vector &find_items_in_area(std::vector &s, SPGroup *group, unsigned int dkey, + Geom::Rect const &area, + bool (*test)(Geom::Rect const &, Geom::Rect const &), + bool take_hidden = false, bool take_insensitive = false, + bool take_groups = true, bool enter_groups = false) { g_return_val_if_fail(SP_IS_GROUP(group), s); - for (auto& o: group->children) { + for (auto &o : group->children) { if (SPItem *item = dynamic_cast(&o)) { if (!take_insensitive && item->isLocked()) { continue; @@ -1315,10 +1283,11 @@ static std::vector &find_items_in_area(std::vector &s, continue; } - if (SPGroup * childgroup = dynamic_cast(item)) { + if (SPGroup *childgroup = dynamic_cast(item)) { bool is_layer = childgroup->effectiveLayerMode(dkey) == SPGroup::LAYER; if (is_layer || (enter_groups)) { - s = find_items_in_area(s, childgroup, dkey, area, test, take_hidden, take_insensitive, take_groups, enter_groups); + s = find_items_in_area(s, childgroup, dkey, area, test, take_hidden, take_insensitive, take_groups, + enter_groups); } if (!take_groups || is_layer) { continue; @@ -1333,7 +1302,8 @@ static std::vector &find_items_in_area(std::vector &s, return s; } -SPItem *SPDocument::getItemFromListAtPointBottom(unsigned int dkey, SPGroup *group, std::vector const &list,Geom::Point const &p, bool take_insensitive) +SPItem *SPDocument::getItemFromListAtPointBottom(unsigned int dkey, SPGroup *group, std::vector const &list, + Geom::Point const &p, bool take_insensitive) { g_return_val_if_fail(group, NULL); SPItem *bottomMost = nullptr; @@ -1341,7 +1311,7 @@ SPItem *SPDocument::getItemFromListAtPointBottom(unsigned int dkey, SPGroup *gro Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0); - for (auto& o: group->children) { + for (auto &o : group->children) { if (bottomMost) { break; } @@ -1353,8 +1323,8 @@ SPItem *SPDocument::getItemFromListAtPointBottom(unsigned int dkey, SPGroup *gro arenaitem->drawing().update(); } - if (arenaitem && arenaitem->pick(p, delta, 1) != nullptr - && (take_insensitive || item->isVisibleAndUnlocked(dkey))) { + if (arenaitem && arenaitem->pick(p, delta, 1) != nullptr && + (take_insensitive || item->isVisibleAndUnlocked(dkey))) { if (find(list.begin(), list.end(), item) != list.end()) { bottomMost = item; } @@ -1376,7 +1346,7 @@ The list can be persisted, which improves "find at multiple points" speed. // TODO: study add `gboolean with_groups = false` as parameter. void SPDocument::build_flat_item_list(unsigned int dkey, SPGroup *group, gboolean into_groups) const { - for (auto& o: group->children) { + for (auto &o : group->children) { if (!SP_IS_ITEM(&o)) { continue; } @@ -1401,7 +1371,8 @@ upwards in z-order and returns what it has found so far (i.e. the found item is guaranteed to be lower than upto). Requires a list of nodes built by build_flat_item_list. */ -static SPItem *find_item_at_point(std::deque *nodes, unsigned int dkey, Geom::Point const &p, SPItem* upto=nullptr) +static SPItem *find_item_at_point(std::deque *nodes, unsigned int dkey, Geom::Point const &p, + SPItem *upto = nullptr) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0); @@ -1411,8 +1382,8 @@ static SPItem *find_item_at_point(std::deque *nodes, unsigned int dkey, bool seen_upto = (!upto); for (auto node : *nodes) { child = node; - if (!seen_upto){ - if(child == upto) + if (!seen_upto) { + if (child == upto) seen_upto = true; continue; } @@ -1439,7 +1410,7 @@ static SPItem *find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Poin Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0); - for (auto& o: group->children) { + for (auto &o : group->children) { if (!SP_IS_ITEM(&o)) { continue; } @@ -1449,7 +1420,7 @@ static SPItem *find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Poin seen = newseen; } } - if (SP_IS_GROUP(&o) && SP_GROUP(&o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) { + if (SP_IS_GROUP(&o) && SP_GROUP(&o)->effectiveLayerMode(dkey) != SPGroup::LAYER) { SPItem *child = SP_ITEM(&o); Inkscape::DrawingItem *arenaitem = child->get_arenaitem(dkey); if (arenaitem) { @@ -1465,17 +1436,18 @@ static SPItem *find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Poin return seen; } - /** * Return list of items, contained in box * * @param box area to find items, in document coordinates */ -std::vector SPDocument::getItemsInBox(unsigned int dkey, Geom::Rect const &box, bool take_hidden, bool take_insensitive, bool take_groups, bool enter_groups) const +std::vector SPDocument::getItemsInBox(unsigned int dkey, Geom::Rect const &box, bool take_hidden, + bool take_insensitive, bool take_groups, bool enter_groups) const { - std::vector x; - return find_items_in_area(x, SP_GROUP(this->root), dkey, box, is_within, take_hidden, take_insensitive, take_groups, enter_groups); + std::vector x; + return find_items_in_area(x, SP_GROUP(this->root), dkey, box, is_within, take_hidden, take_insensitive, take_groups, + enter_groups); } /** @@ -1489,15 +1461,19 @@ std::vector SPDocument::getItemsInBox(unsigned int dkey, Geom::Rect con * @return Return list of items, that the parts of the item contained in box */ -std::vector SPDocument::getItemsPartiallyInBox(unsigned int dkey, Geom::Rect const &box, bool take_hidden, bool take_insensitive, bool take_groups, bool enter_groups) const +std::vector SPDocument::getItemsPartiallyInBox(unsigned int dkey, Geom::Rect const &box, bool take_hidden, + bool take_insensitive, bool take_groups, + bool enter_groups) const { - std::vector x; - return find_items_in_area(x, SP_GROUP(this->root), dkey, box, overlaps, take_hidden, take_insensitive, take_groups, enter_groups); + std::vector x; + return find_items_in_area(x, SP_GROUP(this->root), dkey, box, overlaps, take_hidden, take_insensitive, take_groups, + enter_groups); } -std::vector SPDocument::getItemsAtPoints(unsigned const key, std::vector points, bool all_layers, size_t limit) const +std::vector SPDocument::getItemsAtPoints(unsigned const key, std::vector points, bool all_layers, + size_t limit) const { - std::vector items; + std::vector items; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); // When picking along the path, we don't want small objects close together @@ -1507,27 +1483,27 @@ std::vector SPDocument::getItemsAtPoints(unsigned const key, std::vecto prefs->setDouble("/options/cursortolerance/value", 0.25); // Cache a flattened SVG DOM to speed up selection. - if(!_node_cache_valid){ + if (!_node_cache_valid) { _node_cache.clear(); build_flat_item_list(key, SP_GROUP(this->root), true); - _node_cache_valid=true; + _node_cache_valid = true; } SPObject *current_layer = nullptr; SPDesktop *desktop = SP_ACTIVE_DESKTOP; Inkscape::LayerModel *layer_model = nullptr; - if(desktop){ + if (desktop) { current_layer = desktop->currentLayer(); layer_model = desktop->layers; } size_t item_counter = 0; - for(int i = points.size()-1;i>=0; i--) { + for (int i = points.size() - 1; i >= 0; i--) { SPItem *item = find_item_at_point(&_node_cache, key, points[i]); - if (item && items.end()==find(items.begin(),items.end(), item)) - if(all_layers || (layer_model && layer_model->layerForObject(item) == current_layer)){ + if (item && items.end() == find(items.begin(), items.end(), item)) + if (all_layers || (layer_model && layer_model->layerForObject(item) == current_layer)) { items.push_back(item); item_counter++; - //limit 0 = no limit - if(item_counter == limit){ + // limit 0 = no limit + if (item_counter == limit) { prefs->setDouble("/options/cursortolerance/value", saved_delta); return items; } @@ -1540,23 +1516,22 @@ std::vector SPDocument::getItemsAtPoints(unsigned const key, std::vecto return items; } -SPItem *SPDocument::getItemAtPoint( unsigned const key, Geom::Point const &p, - bool const into_groups, SPItem *upto) const +SPItem *SPDocument::getItemAtPoint(unsigned const key, Geom::Point const &p, bool const into_groups, SPItem *upto) const { // Build a flattened SVG DOM for find_item_at_point. - std::deque bak(_node_cache); - if(!into_groups){ + std::deque bak(_node_cache); + if (!into_groups) { _node_cache.clear(); build_flat_item_list(key, SP_GROUP(this->root), into_groups); } - if(!_node_cache_valid && into_groups){ + if (!_node_cache_valid && into_groups) { _node_cache.clear(); build_flat_item_list(key, SP_GROUP(this->root), true); - _node_cache_valid=true; + _node_cache_valid = true; } SPItem *res = find_item_at_point(&_node_cache, key, p, upto); - if(!into_groups) + if (!into_groups) _node_cache = bak; return res; } @@ -1577,10 +1552,10 @@ bool SPDocument::addResource(gchar const *key, SPObject *object) bool result = false; - if ( !object->cloned ) { + if (!object->cloned) { std::vector rlist = resources[key]; - g_return_val_if_fail(std::find(rlist.begin(),rlist.end(),object) == rlist.end(), false); - resources[key].insert(resources[key].begin(),object); + g_return_val_if_fail(std::find(rlist.begin(), rlist.end(), object) == rlist.end(), false); + resources[key].insert(resources[key].begin(), object); GQuark q = g_quark_from_string(key); @@ -1590,7 +1565,7 @@ bool SPDocument::addResource(gchar const *key, SPObject *object) [this check should be more generally presend on emit() calls since the backtrace is unusable with crashed from this cause] */ - if(object->getId() || dynamic_cast(object) ) + if (object->getId() || dynamic_cast(object)) resources_changed_signals[q].emit(); result = true; @@ -1608,10 +1583,10 @@ bool SPDocument::removeResource(gchar const *key, SPObject *object) bool result = false; - if ( !object->cloned ) { + if (!object->cloned) { std::vector rlist = resources[key]; g_return_val_if_fail(!rlist.empty(), false); - std::vector::iterator it = std::find(resources[key].begin(),resources[key].end(),object); + std::vector::iterator it = std::find(resources[key].begin(), resources[key].end(), object); g_return_val_if_fail(it != rlist.end(), false); resources[key].erase(it); @@ -1639,7 +1614,7 @@ static unsigned int count_objects_recursive(SPObject *obj, unsigned int count) { count++; // obj itself - for (auto& i: obj->children) { + for (auto &i : obj->children) { count = count_objects_recursive(&i, count); } @@ -1665,12 +1640,12 @@ static unsigned int objects_in_document(SPDocument *document) static void vacuum_document_recursive(SPObject *obj) { if (SP_IS_DEFS(obj)) { - for (auto& def: obj->children) { + for (auto &def : obj->children) { // fixme: some inkscape-internal nodes in the future might not be collectable def.requestOrphanCollection(); } } else { - for (auto& i: obj->children) { + for (auto &i : obj->children) { vacuum_document_recursive(&i); } } @@ -1699,29 +1674,31 @@ unsigned int SPDocument::vacuumDocument() newend = objects_in_document(this); } while (iterations < 100 && newend < end); - // We stop if vacuum_document_recursive doesn't remove any more objects or after 100 iterations, whichever occurs first. + // We stop if vacuum_document_recursive doesn't remove any more objects or after 100 iterations, whichever occurs + // first. return start - newend; } /** - * Indicate to the user if the document has been modified since the last save by displaying a "*" in front of the name of the file in the window title. + * Indicate to the user if the document has been modified since the last save by displaying a "*" in front of the name + * of the file in the window title. * * @param[in] modified True if the document has been modified. */ -void SPDocument::setModifiedSinceSave(bool modified) { +void SPDocument::setModifiedSinceSave(bool modified) +{ this->modified_since_save = modified; this->modified_since_autosave = modified; if (SP_ACTIVE_DESKTOP) { InkscapeWindow *window = SP_ACTIVE_DESKTOP->getInkscapeWindow(); if (window) { // during load, SP_ACTIVE_DESKTOP may be !nullptr, but parent might still be nullptr SPDesktopWidget *dtw = window->get_desktop_widget(); - dtw->updateTitle( this->getDocumentName() ); + dtw->updateTitle(this->getDocumentName()); } } } - /** * Paste SVG defs from the document retrieved from the clipboard or imported document into the active document. * @param clipdoc The document to paste. @@ -1735,14 +1712,14 @@ void SPDocument::importDefs(SPDocument *source) prevent_id_clashes(source, this); - for (auto & defsNode : defsNodes) { - _importDefsNode(source, const_cast(defsNode), target_defs); + for (auto &defsNode : defsNodes) { + _importDefsNode(source, const_cast(defsNode), target_defs); } } void SPDocument::_importDefsNode(SPDocument *source, Inkscape::XML::Node *defs, Inkscape::XML::Node *target_defs) { - int stagger=0; + int stagger = 0; /* Note, "clipboard" throughout the comments means "the document that is either the clipboard or an imported document", as importDefs is called in both contexts. @@ -1783,13 +1760,15 @@ void SPDocument::_importDefsNode(SPDocument *source, Inkscape::XML::Node *defs, std::string DuplicateDefString = "RESERVED_FOR_INKSCAPE_DUPLICATE_DEF"; /* First pass: remove duplicates in clipboard of definitions in document */ - for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) { - if(def->type() != Inkscape::XML::ELEMENT_NODE)continue; + for (Inkscape::XML::Node *def = defs->firstChild(); def; def = def->next()) { + if (def->type() != Inkscape::XML::ELEMENT_NODE) + continue; /* If this clipboard has been pasted into one document, and is now being pasted into another, or pasted again into the same, it will already have been processed. If we detect that then skip the rest of this pass. */ Glib::ustring defid = def->attribute("id"); - if( defid.find( DuplicateDefString ) != Glib::ustring::npos )break; + if (defid.find(DuplicateDefString) != Glib::ustring::npos) + break; SPObject *src = source->getObjectByRepr(def); @@ -1797,7 +1776,7 @@ void SPDocument::_importDefsNode(SPDocument *source, Inkscape::XML::Node *defs, SPGradient *s_gr = dynamic_cast(src); LivePathEffectObject *s_lpeobj = dynamic_cast(src); if (src && (s_gr || s_lpeobj)) { - for (auto& trg: getDefs()->children) { + for (auto &trg : getDefs()->children) { SPGradient *t_gr = dynamic_cast(&trg); if (src != &trg && s_gr && t_gr) { if (s_gr->isEquivalent(t_gr)) { @@ -1831,15 +1810,17 @@ void SPDocument::_importDefsNode(SPDocument *source, Inkscape::XML::Node *defs, } /* Second pass: remove duplicates in clipboard of earlier definitions in clipboard */ - for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) { - if(def->type() != Inkscape::XML::ELEMENT_NODE)continue; + for (Inkscape::XML::Node *def = defs->firstChild(); def; def = def->next()) { + if (def->type() != Inkscape::XML::ELEMENT_NODE) + continue; Glib::ustring defid = def->attribute("id"); - if( defid.find( DuplicateDefString ) != Glib::ustring::npos )continue; // this one already handled + if (defid.find(DuplicateDefString) != Glib::ustring::npos) + continue; // this one already handled SPObject *src = source->getObjectByRepr(def); LivePathEffectObject *s_lpeobj = dynamic_cast(src); SPGradient *s_gr = dynamic_cast(src); if (src && (s_gr || s_lpeobj)) { - for (Inkscape::XML::Node *laterDef = def->next() ; laterDef ; laterDef = laterDef->next()) { + for (Inkscape::XML::Node *laterDef = def->next(); laterDef; laterDef = laterDef->next()) { SPObject *trg = source->getObjectByRepr(laterDef); SPGradient *t_gr = dynamic_cast(trg); if (trg && (src != trg) && s_gr && t_gr) { @@ -1876,12 +1857,14 @@ void SPDocument::_importDefsNode(SPDocument *source, Inkscape::XML::Node *defs, } /* Final pass: copy over those parts which are not duplicates */ - for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) { - if(def->type() != Inkscape::XML::ELEMENT_NODE)continue; + for (Inkscape::XML::Node *def = defs->firstChild(); def; def = def->next()) { + if (def->type() != Inkscape::XML::ELEMENT_NODE) + continue; /* Ignore duplicate defs marked in the first pass */ Glib::ustring defid = def->attribute("id"); - if( defid.find( DuplicateDefString ) != Glib::ustring::npos )continue; + if (defid.find(DuplicateDefString) != Glib::ustring::npos) + continue; bool duplicate = false; SPObject *src = source->getObjectByRepr(def); @@ -1890,33 +1873,31 @@ void SPDocument::_importDefsNode(SPDocument *source, Inkscape::XML::Node *defs, // The tag "_inkscape_duplicate" is added to "id" by ClipboardManagerImpl::copySymbol(). // We assume that symbols are in defs section (not required by SVG spec). if (src && SP_IS_SYMBOL(src)) { - Glib::ustring id = src->getRepr()->attribute("id"); - size_t pos = id.find( "_inkscape_duplicate" ); - if( pos != Glib::ustring::npos ) { - + size_t pos = id.find("_inkscape_duplicate"); + if (pos != Glib::ustring::npos) { // This is our symbol, now get rid of tag - id.erase( pos ); + id.erase(pos); // Check that it really is a duplicate - for (auto& trg: getDefs()->children) { + for (auto &trg : getDefs()->children) { if (SP_IS_SYMBOL(&trg) && src != &trg) { std::string id2 = trg.getRepr()->attribute("id"); - if( !id.compare( id2 ) ) { + if (!id.compare(id2)) { duplicate = true; break; } } } - if ( !duplicate ) { + if (!duplicate) { src->setAttribute("id", id); } } } if (!duplicate) { - Inkscape::XML::Node * dup = def->duplicate(this->getReprDoc()); + Inkscape::XML::Node *dup = def->duplicate(this->getReprDoc()); target_defs->appendChild(dup); Inkscape::GC::release(dup); } @@ -1925,14 +1906,12 @@ void SPDocument::_importDefsNode(SPDocument *source, Inkscape::XML::Node *defs, // Signals ------------------------------ -void -SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer) +void SPDocument::addUndoObserver(Inkscape::UndoStackObserver &observer) { this->undoStackObservers.add(observer); } -void -SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer) +void SPDocument::removeUndoObserver(Inkscape::UndoStackObserver &observer) { this->undoStackObservers.remove(observer); } @@ -1962,8 +1941,7 @@ sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type s return commit_signal.connect(slot); } -sigc::connection SPDocument::connectIdChanged(gchar const *id, - SPDocument::IDChangedSignal::slot_type slot) +sigc::connection SPDocument::connectIdChanged(gchar const *id, SPDocument::IDChangedSignal::slot_type slot) { return id_changed_signals[g_quark_from_string(id)].connect(slot); } @@ -1975,34 +1953,31 @@ sigc::connection SPDocument::connectResourcesChanged(gchar const *key, return resources_changed_signals[q].connect(slot); } -sigc::connection -SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot) +sigc::connection SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot) { return _reconstruction_start_signal.connect(slot); } -sigc::connection -SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot) +sigc::connection SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot) { return _reconstruction_finish_signal.connect(slot); } -void SPDocument::_emitModified() { +void SPDocument::_emitModified() +{ static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG; root->emitModified(0); modified_signal.emit(flags); - _node_cache_valid=false; + _node_cache_valid = false; } -void -SPDocument::emitReconstructionStart() +void SPDocument::emitReconstructionStart() { // printf("Starting Reconstruction\n"); _reconstruction_start_signal.emit(); } -void -SPDocument::emitReconstructionFinish() +void SPDocument::emitReconstructionFinish() { // printf("Finishing Reconstruction\n"); _reconstruction_finish_signal.emit(); @@ -2010,10 +1985,10 @@ SPDocument::emitReconstructionFinish() resources_changed_signals[g_quark_from_string("gradient")].emit(); resources_changed_signals[g_quark_from_string("filter")].emit(); -/** - // Reference to the old persp3d object is invalid after reconstruction. - initialize_current_persp3d(); -**/ + /** + // Reference to the old persp3d object is invalid after reconstruction. + initialize_current_persp3d(); + **/ } void SPDocument::emitResizedSignal(gdouble width, gdouble height) @@ -2021,7 +1996,6 @@ void SPDocument::emitResizedSignal(gdouble width, gdouble height) this->resized_signal.emit(width, height); } - /* Local Variables: mode:c++ diff --git a/src/document.h b/src/document.h index f6145ce80725a2d099e430f7fa4d922cb9f4e210..9be29f061aff8cdb671eb9fe2a2146e8ae39315b 100644 --- a/src/document.h +++ b/src/document.h @@ -18,53 +18,42 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - +#include <2geom/affine.h> +#include <2geom/forward.h> +#include #include #include +#include +#include #include #include -#include - -#include - -#include -#include #include - -#include <2geom/affine.h> -#include <2geom/forward.h> +#include #include "3rdparty/libcroco/cr-cascade.h" - +#include "composite-undo-stack-observer.h" #include "document-undo.h" #include "event.h" #include "gc-anchored.h" #include "gc-finalized.h" - #include "inkgc/gc-managed.h" - -#include "composite-undo-stack-observer.h" // XXX only for testing! #include "console-output-undo-observer.h" // This variable is introduced with 0.92.1 -// with the introduction of automatic fix -// for files detected to have been created +// with the introduction of automatic fix +// for files detected to have been created // with previous versions to have a similar // look in 0.92+. extern bool sp_no_convert_text_baseline_spacing; - - // This variable is introduced with 0.92.1 -// with the introduction of automatic fix -// for files detected to have been created +// with the introduction of automatic fix +// for files detected to have been created // with previous versions to have a similar // look in 0.92+. extern bool sp_do_not_fix_pre_92; - - namespace Avoid { class Router; } @@ -75,19 +64,19 @@ class SPGroup; class SPRoot; namespace Inkscape { - class Selection; - class UndoStackObserver; - class EventLog; - class ProfileManager; - namespace XML { - struct Document; - class Node; - } - namespace Util { - class Unit; - class Quantity; - } -} +class Selection; +class UndoStackObserver; +class EventLog; +class ProfileManager; +namespace XML { +struct Document; +class Node; +} // namespace XML +namespace Util { +class Unit; +class Quantity; +} // namespace Util +} // namespace Inkscape class SPDefs; class Persp3D; @@ -95,15 +84,15 @@ class Persp3DImpl; class SPItemCtx; namespace Proj { - class TransfMat3x4; +class TransfMat3x4; } /// Typed SVG document implementation. -class SPDocument : public Inkscape::GC::Managed<>, - public Inkscape::GC::Finalized, - public Inkscape::GC::Anchored +class SPDocument + : public Inkscape::GC::Managed<> + , public Inkscape::GC::Finalized + , public Inkscape::GC::Anchored { - public: /// For sanity check in SPObject::requestDisplayUpdate unsigned update_in_progress = 0; @@ -113,19 +102,16 @@ public: // Fundamental ------------------------ SPDocument(); ~SPDocument() override; - SPDocument(SPDocument const &) = delete; // no copy + SPDocument(SPDocument const &) = delete; // no copy void operator=(SPDocument const &) = delete; // no assign - // Document creation ------------------ - static SPDocument *createDoc(Inkscape::XML::Document *rdoc, char const *uri, - char const *base, char const *name, bool keepalive, - SPDocument *parent); - static SPDocument *createNewDoc(char const*uri, bool keepalive, - bool make_new = false, SPDocument *parent=nullptr ); - static SPDocument *createNewDocFromMem(char const*buffer, int length, bool keepalive); - SPDocument *createChildDoc(std::string const &uri); - + static SPDocument *createDoc(Inkscape::XML::Document *rdoc, char const *uri, char const *base, char const *name, + bool keepalive, SPDocument *parent); + static SPDocument *createNewDoc(char const *uri, bool keepalive, bool make_new = false, + SPDocument *parent = nullptr); + static SPDocument *createNewDocFromMem(char const *buffer, int length, bool keepalive); + SPDocument *createChildDoc(std::string const &uri); // Document status -------------------- void setVirgin(bool Virgin) { virgin = Virgin; } @@ -155,11 +141,11 @@ public: void setXMLDialogSelectedObject(SPObject *activexmltree) { _activexmltree = activexmltree; } SPObject *getXMLDialogSelectedObject() { return _activexmltree; } - private: +private: void _importDefsNode(SPDocument *source, Inkscape::XML::Node *defs, Inkscape::XML::Node *target_defs); SPObject *_activexmltree; - public: +public: void importDefs(SPDocument *source); unsigned int vacuumDocument(); @@ -167,10 +153,9 @@ public: /******** Getters and Setters **********/ // Document structure ----------------- - Inkscape::ProfileManager* getProfileManager() const { return profileManager; } - Avoid::Router* getRouter() const { return router; } + Inkscape::ProfileManager *getProfileManager() const { return profileManager; } + Avoid::Router *getRouter() const { return router; } - /** Returns our SPRoot */ SPRoot *getRoot() { return root; } SPRoot const *getRoot() const { return root; } @@ -185,11 +170,10 @@ public: Inkscape::XML::Document *getReprDoc() { return rdoc; } Inkscape::XML::Document const *getReprDoc() const { return rdoc; } - std::vector getLanguages() const; // Styling - CRCascade *getStyleCascade() { return style_cascade; } + CRCascade *getStyleCascade() { return style_cascade; } // File information -------------------- @@ -198,25 +182,25 @@ public: char const *getDocumentURI() const { return document_uri; } /** To be used for resolving relative hrefs. */ - void setDocumentBase( char const* document_base ); + void setDocumentBase(char const *document_base); char const *getDocumentBase() const { return document_base; }; /** basename(uri) or other human-readable label for the document. */ - char const* getDocumentName() const { return document_name; } - + char const *getDocumentName() const { return document_name; } // Document geometry ------------------------ - Inkscape::Util::Unit const* getDisplayUnit() const; + Inkscape::Util::Unit const *getDisplayUnit() const; - void setDocumentScale( const double scaleX, const double scaleY ); - void setDocumentScale( const double scale ); + void setDocumentScale(const double scaleX, const double scaleY); + void setDocumentScale(const double scale); Geom::Scale getDocumentScale() const; - void setWidthAndHeight(const Inkscape::Util::Quantity &width, const Inkscape::Util::Quantity &height, bool changeSize=true); + void setWidthAndHeight(const Inkscape::Util::Quantity &width, const Inkscape::Util::Quantity &height, + bool changeSize = true); Geom::Point getDimensions() const; - void setWidth(const Inkscape::Util::Quantity &width, bool changeSize=true); - void setHeight(const Inkscape::Util::Quantity &height, bool changeSize=true); + void setWidth(const Inkscape::Util::Quantity &width, bool changeSize = true); + void setHeight(const Inkscape::Util::Quantity &height, bool changeSize = true); Inkscape::Util::Quantity getWidth() const; Inkscape::Util::Quantity getHeight() const; @@ -228,7 +212,6 @@ public: void fitToRect(Geom::Rect const &rect, bool with_margins = false); void setupViewport(SPItemCtx *ctx); - // Find items ----------------------------- void bindObjectToId(char const *id, SPObject *object); SPObject *getObjectById(Glib::ustring const &id) const; @@ -241,67 +224,68 @@ public: std::vector getObjectsByElement(Glib::ustring const &element) const; std::vector getObjectsBySelector(Glib::ustring const &selector) const; - // Find items by geometry -------------------- void build_flat_item_list(unsigned int dkey, SPGroup *group, gboolean into_groups) const; - std::vector getItemsInBox (unsigned int dkey, Geom::Rect const &box, bool take_hidden = false, bool take_insensitive = false, bool take_groups = true, bool enter_groups = false) const; - std::vector getItemsPartiallyInBox(unsigned int dkey, Geom::Rect const &box, bool take_hidden = false, bool take_insensitive = false, bool take_groups = true, bool enter_groups = false) const; + std::vector getItemsInBox(unsigned int dkey, Geom::Rect const &box, bool take_hidden = false, + bool take_insensitive = false, bool take_groups = true, + bool enter_groups = false) const; + std::vector getItemsPartiallyInBox(unsigned int dkey, Geom::Rect const &box, bool take_hidden = false, + bool take_insensitive = false, bool take_groups = true, + bool enter_groups = false) const; SPItem *getItemAtPoint(unsigned int key, Geom::Point const &p, bool into_groups, SPItem *upto = nullptr) const; - std::vector getItemsAtPoints(unsigned const key, std::vector points, bool all_layers = true, size_t limit = 0) const ; - SPItem *getGroupAtPoint(unsigned int key, Geom::Point const &p) const; + std::vector getItemsAtPoints(unsigned const key, std::vector points, bool all_layers = true, + size_t limit = 0) const; + SPItem *getGroupAtPoint(unsigned int key, Geom::Point const &p) const; /** * Returns the bottommost item from the list which is at the point, or NULL if none. */ - static SPItem *getItemFromListAtPointBottom(unsigned int dkey, SPGroup *group, const std::vector &list, Geom::Point const &p, bool take_insensitive = false); - + static SPItem *getItemFromListAtPointBottom(unsigned int dkey, SPGroup *group, const std::vector &list, + Geom::Point const &p, bool take_insensitive = false); // Box tool ------------------------------- - void setCurrentPersp3D(Persp3D * const persp); + void setCurrentPersp3D(Persp3D *const persp); /* * getCurrentPersp3D returns current_persp3d (if non-NULL) or the first * perspective in the defs. If no perspective exists, returns NULL. */ - Persp3D * getCurrentPersp3D(); + Persp3D *getCurrentPersp3D(); - void setCurrentPersp3DImpl(Persp3DImpl * const persp_impl) { current_persp3d_impl = persp_impl; } - Persp3DImpl * getCurrentPersp3DImpl() { return current_persp3d_impl; } + void setCurrentPersp3DImpl(Persp3DImpl *const persp_impl) { current_persp3d_impl = persp_impl; } + Persp3DImpl *getCurrentPersp3DImpl() { return current_persp3d_impl; } - void getPerspectivesInDefs(std::vector &list) const; - unsigned int numPerspectivesInDefs() const { - std::vector list; + void getPerspectivesInDefs(std::vector &list) const; + unsigned int numPerspectivesInDefs() const + { + std::vector list; getPerspectivesInDefs(list); return list.size(); } - // Document undo/redo ---------------------- - unsigned long serial() const { return _serial; } // Returns document's unique number. - bool isSeeking() const {return seeking;} // In a transition between two "good" states of document? + unsigned long serial() const { return _serial; } // Returns document's unique number. + bool isSeeking() const { return seeking; } // In a transition between two "good" states of document? void reset_key(void *dummy) { actionkey.clear(); } bool isSensitive() const { return sensitive; } - // Garbage collecting ---------------------- void queueForOrphanCollection(SPObject *object); void collectOrphans(); - // Actions --------------------------------- Glib::RefPtr getActionGroup() { return action_group; } /************* Data ***************/ private: - // Document ------------------------------ - Inkscape::ProfileManager* profileManager; // Color profile. - Avoid::Router *router; // Instance of the connector router + Inkscape::ProfileManager *profileManager; // Color profile. + Avoid::Router *router; // Instance of the connector router // Document status ----------------------- bool keepalive; ///< false if temporary document (e.g. to generate a PNG for display in a dialog). - bool virgin ; ///< Has the document never been touched? + bool virgin; ///< Has the document never been touched? bool modified_since_save = false; bool modified_since_autosave = false; sigc::connection modified_connection; @@ -309,9 +293,9 @@ private: // Document structure -------------------- Inkscape::XML::Document *rdoc; ///< Our Inkscape::XML::Document - Inkscape::XML::Node *rroot; ///< Root element of Inkscape::XML::Document + Inkscape::XML::Node *rroot; ///< Root element of Inkscape::XML::Document - SPRoot *root; ///< Our SPRoot + SPRoot *root; ///< Our SPRoot // A list of svg documents being used or shown within this document boost::ptr_list _child_documents; @@ -322,16 +306,16 @@ private: CRCascade *style_cascade; // File information ---------------------- - char *document_uri; ///< A filename (not a URI yet), or NULL - char *document_base; ///< To be used for resolving relative hrefs. - char *document_name; ///< basename(uri) or other human-readable label for the document. + char *document_uri; ///< A filename (not a URI yet), or NULL + char *document_base; ///< To be used for resolving relative hrefs. + char *document_name; ///< basename(uri) or other human-readable label for the document. // Find items ---------------------------- std::map iddef; std::map reprdef; // Find items by geometry -------------------- - mutable std::deque _node_cache; // Used to speed up search. + mutable std::deque _node_cache; // Used to speed up search. mutable bool _node_cache_valid; // Box tool ---------------------------- @@ -342,8 +326,8 @@ private: friend Inkscape::DocumentUndo; /* Undo/Redo state */ - bool sensitive; /* If we save actions to undo stack */ - Inkscape::XML::Event * partial; /* partial undo log when interrupted */ + bool sensitive; /* If we save actions to undo stack */ + Inkscape::XML::Event *partial; /* partial undo log when interrupted */ int history_size; std::vector undo; /* Undo stack of reprs */ std::vector redo; /* Redo stack of reprs */ @@ -354,8 +338,8 @@ private: // XXX only for testing! Inkscape::ConsoleOutputUndoObserver console_output_undo_observer; - bool seeking; // Related to undo/redo/unique id - unsigned long _serial; // Unique document number (used by undo/redo). + bool seeking; // Related to undo/redo/unique id + unsigned long _serial; // Unique document number (used by undo/redo). Glib::ustring actionkey; // Last action key, used to combine actions in undo. // Garbage collecting ---------------------- @@ -386,7 +370,7 @@ private: SPDocument::URISetSignal uri_set_signal; SPDocument::ResizedSignal resized_signal; SPDocument::ReconstructionStart _reconstruction_start_signal; - SPDocument::ReconstructionFinish _reconstruction_finish_signal; + SPDocument::ReconstructionFinish _reconstruction_finish_signal; SPDocument::CommitSignal commit_signal; // Used by friend Inkscape::DocumentUndo bool oldSignalsConnected; @@ -414,8 +398,8 @@ public: /// "1" if the desktop Y-axis points down, "-1" if it points up. double yaxisdir() const { return _doc2dt[3]; } - void addUndoObserver(Inkscape::UndoStackObserver& observer); - void removeUndoObserver(Inkscape::UndoStackObserver& observer); + void addUndoObserver(Inkscape::UndoStackObserver &observer); + void removeUndoObserver(Inkscape::UndoStackObserver &observer); sigc::connection connectDestroy(sigc::signal::slot_type slot); sigc::connection connectModified(ModifiedSignal::slot_type slot); @@ -428,10 +412,10 @@ public: sigc::connection connectReconstructionFinish(ReconstructionFinish::slot_type slot); /* Resources */ - std::map > resources; + std::map> resources; ResourcesChangedSignalMap resources_changed_signals; // Used by Extension::Internal::Filter - void _emitModified(); // Used by SPItem + void _emitModified(); // Used by SPItem void emitReconstructionStart(); void emitReconstructionFinish(); void emitResizedSignal(double width, double height); @@ -439,7 +423,8 @@ public: namespace std { template <> -struct default_delete { +struct default_delete +{ void operator()(SPDocument *ptr) const { Inkscape::GC::release(ptr); } }; }; // namespace std diff --git a/src/ege-color-prof-tracker.cpp b/src/ege-color-prof-tracker.cpp index 8442eaef4e6acfbdf8697e519001b37b2a2c7018..c1e32656aedbbc1b792e0d040246f8ab520021d5 100644 --- a/src/ege-color-prof-tracker.cpp +++ b/src/ege-color-prof-tracker.cpp @@ -40,22 +40,21 @@ /* Note: this file should be kept compilable as both .cpp and .c */ -#include -#include #include - +#include #include +#include #ifdef GDK_WINDOWING_X11 #include - #include #endif /* GDK_WINDOWING_X11 */ #include "ege-color-prof-tracker.h" #include "helper/sp-marshal.h" -enum { +enum +{ CHANGED = 0, ADDED, REMOVED, @@ -63,29 +62,29 @@ enum { LAST_SIGNAL }; -static void ege_color_prof_tracker_get_property( GObject* obj, guint propId, GValue* value, GParamSpec * pspec ); -static void ege_color_prof_tracker_set_property( GObject* obj, guint propId, const GValue *value, GParamSpec* pspec ); +static void ege_color_prof_tracker_get_property(GObject *obj, guint propId, GValue *value, GParamSpec *pspec); +static void ege_color_prof_tracker_set_property(GObject *obj, guint propId, const GValue *value, GParamSpec *pspec); static void ege_color_prof_tracker_dispose(GObject *); -class ScreenTrack { - public: +class ScreenTrack +{ +public: #ifdef GDK_WINDOWING_X11 gboolean zeroSeen; gboolean otherSeen; #endif /* GDK_WINDOWING_X11 */ std::vector *trackers; - GPtrArray* profiles; - ~ScreenTrack(){ delete trackers; } + GPtrArray *profiles; + ~ScreenTrack() { delete trackers; } }; - #ifdef GDK_WINDOWING_X11 GdkFilterReturn x11_win_filter(GdkXEvent *xevent, GdkEvent *event, gpointer data); -void handle_property_change(GdkScreen* screen, const gchar* name); -void add_x11_tracking_for_screen(GdkScreen* screen); +void handle_property_change(GdkScreen *screen, const gchar *name); +void add_x11_tracking_for_screen(GdkScreen *screen); static void fire(gint monitor); -static void clear_profile( guint monitor ); -static void set_profile( guint monitor, const guint8* data, guint len ); +static void clear_profile(guint monitor); +static void set_profile(guint monitor, const guint8 *data, guint len); #endif /* GDK_WINDOWING_X11 */ static guint signals[LAST_SIGNAL] = {0}; @@ -97,25 +96,25 @@ static std::vector abstract_trackers; typedef struct { - GtkWidget* _target; + GtkWidget *_target; gint _monitor; } EgeColorProfTrackerPrivate; -#define EGE_COLOR_PROF_TRACKER_GET_PRIVATE( o ) \ - reinterpret_cast( ege_color_prof_tracker_get_instance_private (o)) +#define EGE_COLOR_PROF_TRACKER_GET_PRIVATE(o) \ + reinterpret_cast(ege_color_prof_tracker_get_instance_private(o)) -static void event_after_cb( GtkWidget* widget, GdkEvent* event, gpointer user_data ); -static void target_hierarchy_changed_cb(GtkWidget* widget, GtkWidget* prev_top, gpointer user_data); -static void target_screen_changed_cb(GtkWidget* widget, GdkScreen* prev_screen, gpointer user_data); -static void screen_size_changed_cb(GdkScreen* screen, gpointer user_data); -static void track_screen( GdkScreen* screen, EgeColorProfTracker* tracker ); +static void event_after_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data); +static void target_hierarchy_changed_cb(GtkWidget *widget, GtkWidget *prev_top, gpointer user_data); +static void target_screen_changed_cb(GtkWidget *widget, GdkScreen *prev_screen, gpointer user_data); +static void screen_size_changed_cb(GdkScreen *screen, gpointer user_data); +static void track_screen(GdkScreen *screen, EgeColorProfTracker *tracker); -G_DEFINE_TYPE_WITH_PRIVATE (EgeColorProfTracker, ege_color_prof_tracker, G_TYPE_OBJECT); +G_DEFINE_TYPE_WITH_PRIVATE(EgeColorProfTracker, ege_color_prof_tracker, G_TYPE_OBJECT); -void ege_color_prof_tracker_class_init( EgeColorProfTrackerClass* klass ) +void ege_color_prof_tracker_class_init(EgeColorProfTrackerClass *klass) { - if ( klass ) { - GObjectClass* objClass = G_OBJECT_CLASS( klass ); + if (klass) { + GObjectClass *objClass = G_OBJECT_CLASS(klass); objClass->get_property = ege_color_prof_tracker_get_property; objClass->set_property = ege_color_prof_tracker_set_property; @@ -123,78 +122,51 @@ void ege_color_prof_tracker_class_init( EgeColorProfTrackerClass* klass ) objClass->dispose = ege_color_prof_tracker_dispose; - signals[CHANGED] = g_signal_new( "changed", - G_TYPE_FROM_CLASS(klass), - G_SIGNAL_RUN_FIRST, - G_STRUCT_OFFSET(EgeColorProfTrackerClass, changed), - nullptr, nullptr, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0 ); - - signals[ADDED] = g_signal_new( "added", - G_TYPE_FROM_CLASS(klass), - G_SIGNAL_RUN_FIRST, - 0, - nullptr, nullptr, - sp_marshal_VOID__INT_INT, - G_TYPE_NONE, 2, - G_TYPE_INT, - G_TYPE_INT); - - signals[REMOVED] = g_signal_new( "removed", - G_TYPE_FROM_CLASS(klass), - G_SIGNAL_RUN_FIRST, - 0, - nullptr, nullptr, - sp_marshal_VOID__INT_INT, - G_TYPE_NONE, 2, - G_TYPE_INT, - G_TYPE_INT); - - signals[MODIFIED] = g_signal_new( "modified", - G_TYPE_FROM_CLASS(klass), - G_SIGNAL_RUN_FIRST, - 0, - nullptr, nullptr, - g_cclosure_marshal_VOID__INT, - G_TYPE_NONE, 1, - G_TYPE_INT); + signals[CHANGED] = g_signal_new("changed", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_FIRST, + G_STRUCT_OFFSET(EgeColorProfTrackerClass, changed), nullptr, nullptr, + g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); + + signals[ADDED] = g_signal_new("added", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_FIRST, 0, nullptr, nullptr, + sp_marshal_VOID__INT_INT, G_TYPE_NONE, 2, G_TYPE_INT, G_TYPE_INT); + + signals[REMOVED] = g_signal_new("removed", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_FIRST, 0, nullptr, nullptr, + sp_marshal_VOID__INT_INT, G_TYPE_NONE, 2, G_TYPE_INT, G_TYPE_INT); + + signals[MODIFIED] = g_signal_new("modified", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_FIRST, 0, nullptr, nullptr, + g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); } } - -void ege_color_prof_tracker_init( EgeColorProfTracker* tracker ) +void ege_color_prof_tracker_init(EgeColorProfTracker *tracker) { - auto priv = EGE_COLOR_PROF_TRACKER_GET_PRIVATE( tracker ); + auto priv = EGE_COLOR_PROF_TRACKER_GET_PRIVATE(tracker); priv->_target = nullptr; priv->_monitor = 0; } -EgeColorProfTracker* ege_color_prof_tracker_new( GtkWidget* target ) +EgeColorProfTracker *ege_color_prof_tracker_new(GtkWidget *target) { - GObject* obj = (GObject*)g_object_new( EGE_TYPE_COLOR_PROF_TRACKER, - nullptr ); + GObject *obj = (GObject *)g_object_new(EGE_TYPE_COLOR_PROF_TRACKER, nullptr); - EgeColorProfTracker* tracker = EGE_COLOR_PROF_TRACKER( obj ); - auto priv = EGE_COLOR_PROF_TRACKER_GET_PRIVATE (tracker); + EgeColorProfTracker *tracker = EGE_COLOR_PROF_TRACKER(obj); + auto priv = EGE_COLOR_PROF_TRACKER_GET_PRIVATE(tracker); priv->_target = target; - if ( target ) { - g_signal_connect( G_OBJECT(target), "hierarchy-changed", G_CALLBACK( target_hierarchy_changed_cb ), obj ); - g_signal_connect( G_OBJECT(target), "screen-changed", G_CALLBACK( target_screen_changed_cb ), obj ); + if (target) { + g_signal_connect(G_OBJECT(target), "hierarchy-changed", G_CALLBACK(target_hierarchy_changed_cb), obj); + g_signal_connect(G_OBJECT(target), "screen-changed", G_CALLBACK(target_screen_changed_cb), obj); /* invoke the callbacks now to connect if the widget is already visible */ - target_hierarchy_changed_cb( target, nullptr, obj ); - target_screen_changed_cb( target, nullptr, obj ); + target_hierarchy_changed_cb(target, nullptr, obj); + target_screen_changed_cb(target, nullptr, obj); } else { abstract_trackers.push_back(tracker); - if(tracked_screen) { - for ( gint monitor = 0; monitor < (gint)tracked_screen->profiles->len; monitor++ ) { - g_signal_emit( G_OBJECT(tracker), signals[MODIFIED], 0, monitor ); + if (tracked_screen) { + for (gint monitor = 0; monitor < (gint)tracked_screen->profiles->len; monitor++) { + g_signal_emit(G_OBJECT(tracker), signals[MODIFIED], 0, monitor); } } - } return tracker; @@ -227,18 +199,19 @@ void ege_color_prof_tracker_dispose(GObject *obj) } } -void ege_color_prof_tracker_get_profile( EgeColorProfTracker const * tracker, gpointer* ptr, guint* len ) +void ege_color_prof_tracker_get_profile(EgeColorProfTracker const *tracker, gpointer *ptr, guint *len) { - auto priv = EGE_COLOR_PROF_TRACKER_GET_PRIVATE( const_cast(tracker) ); + auto priv = EGE_COLOR_PROF_TRACKER_GET_PRIVATE(const_cast(tracker)); gpointer dataPos = nullptr; guint dataLen = 0; if (tracker) { - if (priv->_target ) { - //GdkScreen* screen = gtk_widget_get_screen(priv->_target); - if ( tracked_screen ) { - if ( priv->_monitor >= 0 && priv->_monitor < (static_cast(tracked_screen->profiles->len))) { - GByteArray* gba = static_cast(g_ptr_array_index(tracked_screen->profiles, priv->_monitor)); - if ( gba ) { + if (priv->_target) { + // GdkScreen* screen = gtk_widget_get_screen(priv->_target); + if (tracked_screen) { + if (priv->_monitor >= 0 && priv->_monitor < (static_cast(tracked_screen->profiles->len))) { + GByteArray *gba = + static_cast(g_ptr_array_index(tracked_screen->profiles, priv->_monitor)); + if (gba) { dataPos = gba->data; dataLen = gba->len; } @@ -248,26 +221,26 @@ void ege_color_prof_tracker_get_profile( EgeColorProfTracker const * tracker, gp } } } - if ( ptr ) { + if (ptr) { *ptr = dataPos; } - if ( len ) { + if (len) { *len = dataLen; } } -void ege_color_prof_tracker_get_profile_for( guint monitor, gpointer* ptr, guint* len ) +void ege_color_prof_tracker_get_profile_for(guint monitor, gpointer *ptr, guint *len) { gpointer dataPos = nullptr; guint dataLen = 0; GdkDisplay *display = gdk_display_get_default(); - GdkScreen *screen = gdk_display_get_default_screen(display); + GdkScreen *screen = gdk_display_get_default_screen(display); - if ( screen ) { - if ( tracked_screen ) { - if ( monitor < tracked_screen->profiles->len ) { - GByteArray* gba = (GByteArray*)g_ptr_array_index( tracked_screen->profiles, monitor ); - if ( gba ) { + if (screen) { + if (tracked_screen) { + if (monitor < tracked_screen->profiles->len) { + GByteArray *gba = (GByteArray *)g_ptr_array_index(tracked_screen->profiles, monitor); + if (gba) { dataPos = gba->data; dataLen = gba->len; } @@ -277,49 +250,49 @@ void ege_color_prof_tracker_get_profile_for( guint monitor, gpointer* ptr, guint } } - if ( ptr ) { + if (ptr) { *ptr = dataPos; } - if ( len ) { + if (len) { *len = dataLen; } } -void ege_color_prof_tracker_get_property( GObject* obj, guint propId, GValue* value, GParamSpec * pspec ) +void ege_color_prof_tracker_get_property(GObject *obj, guint propId, GValue *value, GParamSpec *pspec) { - EgeColorProfTracker* tracker = EGE_COLOR_PROF_TRACKER( obj ); + EgeColorProfTracker *tracker = EGE_COLOR_PROF_TRACKER(obj); (void)tracker; (void)value; - switch ( propId ) { + switch (propId) { default: - G_OBJECT_WARN_INVALID_PROPERTY_ID( obj, propId, pspec ); + G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, propId, pspec); } } -void ege_color_prof_tracker_set_property( GObject* obj, guint propId, const GValue *value, GParamSpec* pspec ) +void ege_color_prof_tracker_set_property(GObject *obj, guint propId, const GValue *value, GParamSpec *pspec) { - EgeColorProfTracker* tracker = EGE_COLOR_PROF_TRACKER( obj ); + EgeColorProfTracker *tracker = EGE_COLOR_PROF_TRACKER(obj); (void)tracker; (void)value; - switch ( propId ) { + switch (propId) { default: - G_OBJECT_WARN_INVALID_PROPERTY_ID( obj, propId, pspec ); + G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, propId, pspec); } } - -void track_screen( GdkScreen* screen, EgeColorProfTracker* tracker ) +void track_screen(GdkScreen *screen, EgeColorProfTracker *tracker) { - if ( tracked_screen ) { + if (tracked_screen) { /* We found the screen already being tracked */ - if ( std::find(tracked_screen->trackers->begin(),tracked_screen->trackers->end(),tracker)==tracked_screen->trackers->end() ) { + if (std::find(tracked_screen->trackers->begin(), tracked_screen->trackers->end(), tracker) == + tracked_screen->trackers->end()) { tracked_screen->trackers->push_back(tracker); } } else { tracked_screen = g_new(ScreenTrack, 1); - GdkDisplay* display = gdk_display_get_default(); + GdkDisplay *display = gdk_display_get_default(); int numMonitors = gdk_display_get_n_monitors(display); @@ -327,17 +300,17 @@ void track_screen( GdkScreen* screen, EgeColorProfTracker* tracker ) tracked_screen->zeroSeen = FALSE; tracked_screen->otherSeen = FALSE; #endif /* GDK_WINDOWING_X11 */ - tracked_screen->trackers= new std::vector; - tracked_screen->trackers->push_back(tracker ); + tracked_screen->trackers = new std::vector; + tracked_screen->trackers->push_back(tracker); tracked_screen->profiles = g_ptr_array_new(); - for ( int i = 0; i < numMonitors; i++ ) { - g_ptr_array_add( tracked_screen->profiles, nullptr ); + for (int i = 0; i < numMonitors; i++) { + g_ptr_array_add(tracked_screen->profiles, nullptr); } - g_signal_connect( G_OBJECT(screen), "size-changed", G_CALLBACK( screen_size_changed_cb ), tracker ); + g_signal_connect(G_OBJECT(screen), "size-changed", G_CALLBACK(screen_size_changed_cb), tracker); #ifdef GDK_WINDOWING_X11 - if (GDK_IS_X11_DISPLAY (display) ) { + if (GDK_IS_X11_DISPLAY(display)) { // printf( "track_screen: Display is using X11\n" ); add_x11_tracking_for_screen(screen); } else { @@ -347,13 +320,12 @@ void track_screen( GdkScreen* screen, EgeColorProfTracker* tracker ) } } - -void event_after_cb( GtkWidget* widget, GdkEvent* event, gpointer user_data ) +void event_after_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data) { - if ( event->type == GDK_CONFIGURE ) { - GdkWindow* window = gtk_widget_get_window (widget); - EgeColorProfTracker* tracker = (EgeColorProfTracker*)user_data; - auto priv = EGE_COLOR_PROF_TRACKER_GET_PRIVATE (tracker); + if (event->type == GDK_CONFIGURE) { + GdkWindow *window = gtk_widget_get_window(widget); + EgeColorProfTracker *tracker = (EgeColorProfTracker *)user_data; + auto priv = EGE_COLOR_PROF_TRACKER_GET_PRIVATE(tracker); // In Gtk+ >= 3.22, we need to figure out the screen ID auto display = gdk_display_get_default(); @@ -366,95 +338,95 @@ void event_after_cb( GtkWidget* widget, GdkEvent* event, gpointer user_data ) // Now loop through the set of monitors and figure out whether this monitor matches for (int i_monitor = 0; i_monitor < n_monitors; ++i_monitor) { auto monitor_at_index = gdk_display_get_monitor(display, i_monitor); - if(monitor_at_index == monitor) monitorNum = i_monitor; + if (monitor_at_index == monitor) + monitorNum = i_monitor; } - if ( monitorNum != priv->_monitor && monitorNum != -1 ) { + if (monitorNum != priv->_monitor && monitorNum != -1) { priv->_monitor = monitorNum; - g_signal_emit( G_OBJECT(tracker), signals[CHANGED], 0 ); + g_signal_emit(G_OBJECT(tracker), signals[CHANGED], 0); } } } -void target_hierarchy_changed_cb(GtkWidget* widget, GtkWidget* prev_top, gpointer user_data) +void target_hierarchy_changed_cb(GtkWidget *widget, GtkWidget *prev_top, gpointer user_data) { - if ( !prev_top && gtk_widget_get_toplevel(widget) ) { - GtkWidget* top = gtk_widget_get_toplevel(widget); - if ( gtk_widget_is_toplevel(top) ) { - GtkWindow* win = GTK_WINDOW(top); - g_signal_connect( G_OBJECT(win), "event-after", G_CALLBACK( event_after_cb ), user_data ); + if (!prev_top && gtk_widget_get_toplevel(widget)) { + GtkWidget *top = gtk_widget_get_toplevel(widget); + if (gtk_widget_is_toplevel(top)) { + GtkWindow *win = GTK_WINDOW(top); + g_signal_connect(G_OBJECT(win), "event-after", G_CALLBACK(event_after_cb), user_data); } } } -void target_screen_changed_cb(GtkWidget* widget, GdkScreen* prev_screen, gpointer user_data) +void target_screen_changed_cb(GtkWidget *widget, GdkScreen *prev_screen, gpointer user_data) { - GdkScreen* screen = gtk_widget_get_screen(widget); + GdkScreen *screen = gtk_widget_get_screen(widget); - if ( screen && (screen != prev_screen) ) { - track_screen( screen, EGE_COLOR_PROF_TRACKER(user_data) ); + if (screen && (screen != prev_screen)) { + track_screen(screen, EGE_COLOR_PROF_TRACKER(user_data)); } } -void screen_size_changed_cb(GdkScreen* screen, gpointer user_data) +void screen_size_changed_cb(GdkScreen *screen, gpointer user_data) { (void)user_data; -/* g_message("screen size changed to (%d, %d) with %d monitors for obj:%p", */ -/* gdk_screen_get_width(screen), gdk_screen_get_height(screen), */ -/* gdk_screen_get_n_monitors(screen), */ -/* user_data); */ - if ( tracked_screen ) { - GdkDisplay* display = gdk_display_get_default(); - - int numMonitors = gdk_display_get_n_monitors(display); - - if ( numMonitors > (gint)tracked_screen->profiles->len ) { - for ( guint i = tracked_screen->profiles->len; i < (guint)numMonitors; i++ ) { - g_ptr_array_add( tracked_screen->profiles, nullptr ); + /* g_message("screen size changed to (%d, %d) with %d monitors for obj:%p", */ + /* gdk_screen_get_width(screen), gdk_screen_get_height(screen), */ + /* gdk_screen_get_n_monitors(screen), */ + /* user_data); */ + if (tracked_screen) { + GdkDisplay *display = gdk_display_get_default(); + + int numMonitors = gdk_display_get_n_monitors(display); + + if (numMonitors > (gint)tracked_screen->profiles->len) { + for (guint i = tracked_screen->profiles->len; i < (guint)numMonitors; i++) { + g_ptr_array_add(tracked_screen->profiles, nullptr); #ifdef GDK_WINDOWING_X11 - if (GDK_IS_X11_DISPLAY (display) ) { - gchar* name = g_strdup_printf( "_ICC_PROFILE_%d", i ); - handle_property_change( screen, name ); + if (GDK_IS_X11_DISPLAY(display)) { + gchar *name = g_strdup_printf("_ICC_PROFILE_%d", i); + handle_property_change(screen, name); g_free(name); } #endif /* GDK_WINDOWING_X11 */ } - } else if ( numMonitors < (gint)tracked_screen->profiles->len ) { -/* g_message("The count of monitors decreased, remove some"); */ + } else if (numMonitors < (gint)tracked_screen->profiles->len) { + /* g_message("The count of monitors decreased, remove some"); */ } } } #ifdef GDK_WINDOWING_X11 -GdkFilterReturn x11_win_filter(GdkXEvent *xevent, - GdkEvent *event, - gpointer data) +GdkFilterReturn x11_win_filter(GdkXEvent *xevent, GdkEvent *event, gpointer data) { - XEvent* x11 = (XEvent*)xevent; + XEvent *x11 = (XEvent *)xevent; (void)event; (void)data; - if ( x11->type == PropertyNotify ) { - XPropertyEvent* note = (XPropertyEvent*)x11; + if (x11->type == PropertyNotify) { + XPropertyEvent *note = (XPropertyEvent *)x11; /*GdkAtom gatom = gdk_x11_xatom_to_atom(note->atom);*/ - const gchar* name = gdk_x11_get_xatom_name(note->atom); - if ( strncmp("_ICC_PROFILE", name, 12 ) == 0 ) { - XEvent* native = (XEvent*)xevent; + const gchar *name = gdk_x11_get_xatom_name(note->atom); + if (strncmp("_ICC_PROFILE", name, 12) == 0) { + XEvent *native = (XEvent *)xevent; XWindowAttributes tmp; - Status stat = XGetWindowAttributes( native->xproperty.display, native->xproperty.window, &tmp ); - if ( stat ) { - GdkDisplay* display = gdk_x11_lookup_xdisplay(native->xproperty.display); - if ( display ) { - GdkScreen* targetScreen = nullptr; - GdkScreen* sc = gdk_display_get_default_screen(display); - if ( tmp.screen == GDK_SCREEN_XSCREEN(sc) ) { + Status stat = XGetWindowAttributes(native->xproperty.display, native->xproperty.window, &tmp); + if (stat) { + GdkDisplay *display = gdk_x11_lookup_xdisplay(native->xproperty.display); + if (display) { + GdkScreen *targetScreen = nullptr; + GdkScreen *sc = gdk_display_get_default_screen(display); + if (tmp.screen == GDK_SCREEN_XSCREEN(sc)) { targetScreen = sc; } - handle_property_change( targetScreen, name ); + handle_property_change(targetScreen, name); } } else { -/* g_message("%d failed XGetWindowAttributes with %d", GPOINTER_TO_INT(data), stat); */ + /* g_message("%d failed XGetWindowAttributes with %d", GPOINTER_TO_INT(data), + * stat); */ } } } @@ -462,43 +434,42 @@ GdkFilterReturn x11_win_filter(GdkXEvent *xevent, return GDK_FILTER_CONTINUE; } -void handle_property_change(GdkScreen* screen, const gchar* name) +void handle_property_change(GdkScreen *screen, const gchar *name) { - Display* xdisplay = GDK_SCREEN_XDISPLAY(screen); + Display *xdisplay = GDK_SCREEN_XDISPLAY(screen); gint monitor = 0; Atom atom = XInternAtom(xdisplay, name, True); - if ( strncmp("_ICC_PROFILE_", name, 13 ) == 0 ) { + if (strncmp("_ICC_PROFILE_", name, 13) == 0) { gint64 tmp = g_ascii_strtoll(name + 13, nullptr, 10); - if ( tmp != 0 && tmp != G_MAXINT64 && tmp != G_MININT64 ) { + if (tmp != 0 && tmp != G_MAXINT64 && tmp != G_MININT64) { monitor = (gint)tmp; } } - if ( atom != None ) { + if (atom != None) { Atom actualType = None; int actualFormat = 0; unsigned long size = 128 * 1042; unsigned long nitems = 0; unsigned long bytesAfter = 0; - unsigned char* prop = nullptr; + unsigned char *prop = nullptr; - clear_profile( monitor ); + clear_profile(monitor); - if ( XGetWindowProperty( xdisplay, GDK_WINDOW_XID(gdk_screen_get_root_window(screen)), - atom, 0, size, False, AnyPropertyType, - &actualType, &actualFormat, &nitems, &bytesAfter, &prop ) == Success ) { - if ( (actualType != None) && (bytesAfter + nitems) ) { + if (XGetWindowProperty(xdisplay, GDK_WINDOW_XID(gdk_screen_get_root_window(screen)), atom, 0, size, False, + AnyPropertyType, &actualType, &actualFormat, &nitems, &bytesAfter, &prop) == Success) { + if ((actualType != None) && (bytesAfter + nitems)) { size = nitems + bytesAfter; bytesAfter = 0; nitems = 0; - if ( prop ) { + if (prop) { XFree(prop); prop = nullptr; } - if ( XGetWindowProperty( xdisplay, GDK_WINDOW_XID(gdk_screen_get_root_window(screen)), - atom, 0, size, False, AnyPropertyType, - &actualType, &actualFormat, &nitems, &bytesAfter, &prop ) == Success ) { - gpointer profile = g_memdup( prop, nitems ); - set_profile( monitor, (const guint8*)profile, nitems ); + if (XGetWindowProperty(xdisplay, GDK_WINDOW_XID(gdk_screen_get_root_window(screen)), atom, 0, size, + False, AnyPropertyType, &actualType, &actualFormat, &nitems, &bytesAfter, + &prop) == Success) { + gpointer profile = g_memdup(prop, nitems); + set_profile(monitor, (const guint8 *)profile, nitems); free(profile); XFree(prop); } else { @@ -506,7 +477,7 @@ void handle_property_change(GdkScreen* screen, const gchar* name) } } else { /* clear it */ - set_profile( monitor, nullptr, 0 ); + set_profile(monitor, nullptr, 0); } } else { g_warning("error loading profile property"); @@ -515,46 +486,46 @@ void handle_property_change(GdkScreen* screen, const gchar* name) fire(monitor); } -void add_x11_tracking_for_screen(GdkScreen* screen) +void add_x11_tracking_for_screen(GdkScreen *screen) { - Display* xdisplay = GDK_SCREEN_XDISPLAY(screen); - GdkWindow* root = gdk_screen_get_root_window(screen); - if ( root ) { + Display *xdisplay = GDK_SCREEN_XDISPLAY(screen); + GdkWindow *root = gdk_screen_get_root_window(screen); + if (root) { Window rootWin = GDK_WINDOW_XID(root); Atom baseAtom = XInternAtom(xdisplay, "_ICC_PROFILE", True); int numWinProps = 0; - Atom* propArray = XListProperties(xdisplay, rootWin, &numWinProps); + Atom *propArray = XListProperties(xdisplay, rootWin, &numWinProps); gint i; gdk_window_set_events(root, (GdkEventMask)(gdk_window_get_events(root) | GDK_PROPERTY_CHANGE_MASK)); gdk_window_add_filter(root, x11_win_filter, GINT_TO_POINTER(1)); /* Look for any profiles attached to this root window */ - if ( propArray ) { + if (propArray) { int j = 0; auto display = gdk_display_get_default(); int numMonitors = gdk_display_get_n_monitors(display); - if ( baseAtom != None ) { - for ( i = 0; i < numWinProps; i++ ) { - if ( baseAtom == propArray[i] ) { + if (baseAtom != None) { + for (i = 0; i < numWinProps; i++) { + if (baseAtom == propArray[i]) { tracked_screen->zeroSeen = TRUE; - handle_property_change( screen, "_ICC_PROFILE" ); + handle_property_change(screen, "_ICC_PROFILE"); } } } else { -/* g_message("Base atom not found"); */ + /* g_message("Base atom not found"); */ } - for ( i = 1; i < numMonitors; i++ ) { - gchar* name = g_strdup_printf("_ICC_PROFILE_%d", i); + for (i = 1; i < numMonitors; i++) { + gchar *name = g_strdup_printf("_ICC_PROFILE_%d", i); Atom atom = XInternAtom(xdisplay, name, True); - if ( atom != None ) { - for ( j = 0; j < numWinProps; j++ ) { - if ( atom == propArray[j] ) { + if (atom != None) { + for (j = 0; j < numWinProps; j++) { + if (atom == propArray[j]) { tracked_screen->otherSeen = TRUE; - handle_property_change( screen, name ); + handle_property_change(screen, name); } } } @@ -568,53 +539,53 @@ void add_x11_tracking_for_screen(GdkScreen* screen) void fire(gint monitor) { - if ( tracked_screen ) { - for (auto tracker:(*(tracked_screen->trackers))) { - auto priv = EGE_COLOR_PROF_TRACKER_GET_PRIVATE (tracker); - if ( (monitor == -1) || (priv->_monitor == monitor) ) { - g_signal_emit( G_OBJECT(tracker), signals[CHANGED], 0 ); + if (tracked_screen) { + for (auto tracker : (*(tracked_screen->trackers))) { + auto priv = EGE_COLOR_PROF_TRACKER_GET_PRIVATE(tracker); + if ((monitor == -1) || (priv->_monitor == monitor)) { + g_signal_emit(G_OBJECT(tracker), signals[CHANGED], 0); } } } } -static void clear_profile( guint monitor ) +static void clear_profile(guint monitor) { - if ( tracked_screen ) { - GByteArray* previous = nullptr; - for ( guint i = tracked_screen->profiles->len; i <= monitor; i++ ) { - g_ptr_array_add( tracked_screen->profiles, nullptr ); + if (tracked_screen) { + GByteArray *previous = nullptr; + for (guint i = tracked_screen->profiles->len; i <= monitor; i++) { + g_ptr_array_add(tracked_screen->profiles, nullptr); } - previous = (GByteArray*)g_ptr_array_index( tracked_screen->profiles, monitor ); - if ( previous ) { - g_byte_array_free( previous, TRUE ); + previous = (GByteArray *)g_ptr_array_index(tracked_screen->profiles, monitor); + if (previous) { + g_byte_array_free(previous, TRUE); } tracked_screen->profiles->pdata[monitor] = nullptr; } } -static void set_profile( guint monitor, const guint8* data, guint len ) +static void set_profile(guint monitor, const guint8 *data, guint len) { - if ( tracked_screen ) { - for ( guint i = tracked_screen->profiles->len; i <= monitor; i++ ) { - g_ptr_array_add( tracked_screen->profiles, nullptr ); + if (tracked_screen) { + for (guint i = tracked_screen->profiles->len; i <= monitor; i++) { + g_ptr_array_add(tracked_screen->profiles, nullptr); } - GByteArray *previous = (GByteArray*)g_ptr_array_index( tracked_screen->profiles, monitor ); - if ( previous ) { - g_byte_array_free( previous, TRUE ); + GByteArray *previous = (GByteArray *)g_ptr_array_index(tracked_screen->profiles, monitor); + if (previous) { + g_byte_array_free(previous, TRUE); } - if ( data && len ) { - GByteArray* newBytes = g_byte_array_sized_new( len ); - newBytes = g_byte_array_append( newBytes, data, len ); + if (data && len) { + GByteArray *newBytes = g_byte_array_sized_new(len); + newBytes = g_byte_array_append(newBytes, data, len); tracked_screen->profiles->pdata[monitor] = newBytes; } else { tracked_screen->profiles->pdata[monitor] = nullptr; } - for (auto i:abstract_trackers) { - g_signal_emit( G_OBJECT(i), signals[MODIFIED], 0, monitor ); + for (auto i : abstract_trackers) { + g_signal_emit(G_OBJECT(i), signals[MODIFIED], 0, monitor); } } } diff --git a/src/ege-color-prof-tracker.h b/src/ege-color-prof-tracker.h index 535e26e9d66aa2d2ff0eb69953d1d094baae7754..da138477bc4d67d9dccecac2830b9f6d1c1ec86f 100644 --- a/src/ege-color-prof-tracker.h +++ b/src/ege-color-prof-tracker.h @@ -52,8 +52,8 @@ typedef struct _GtkWidget GtkWidget; G_BEGIN_DECLS -#define EGE_TYPE_COLOR_PROF_TRACKER ege_color_prof_tracker_get_type () -G_DECLARE_DERIVABLE_TYPE (EgeColorProfTracker, ege_color_prof_tracker, EGE, COLOR_PROF_TRACKER, GObject) +#define EGE_TYPE_COLOR_PROF_TRACKER ege_color_prof_tracker_get_type() +G_DECLARE_DERIVABLE_TYPE(EgeColorProfTracker, ege_color_prof_tracker, EGE, COLOR_PROF_TRACKER, GObject) /** * Class structure of EgeColorProfTracker. @@ -63,16 +63,16 @@ struct _EgeColorProfTrackerClass /** Parent class structure. */ GObjectClass parent_class; - void (*changed) (EgeColorProfTracker* tracker); + void (*changed)(EgeColorProfTracker *tracker); }; /** * Creates a new EgeColorProfTracker instance. */ -EgeColorProfTracker* ege_color_prof_tracker_new( GtkWidget* target ); +EgeColorProfTracker *ege_color_prof_tracker_new(GtkWidget *target); -void ege_color_prof_tracker_get_profile( EgeColorProfTracker const * tracker, gpointer* ptr, guint* len ); -void ege_color_prof_tracker_get_profile_for( guint monitor, gpointer* ptr, guint* len ); +void ege_color_prof_tracker_get_profile(EgeColorProfTracker const *tracker, gpointer *ptr, guint *len); +void ege_color_prof_tracker_get_profile_for(guint monitor, gpointer *ptr, guint *len); G_END_DECLS diff --git a/src/enums.h b/src/enums.h index 6e0c76924633bfe91153a848e11a44b1b902efe8..6566ad9546a3070a020884fcb97aae89c7f43bf0 100644 --- a/src/enums.h +++ b/src/enums.h @@ -16,58 +16,62 @@ /* Anchor types (imported from Gtk) */ enum SPAnchorType { - SP_ANCHOR_CENTER, - SP_ANCHOR_NORTH, - SP_ANCHOR_NORTH_WEST, - SP_ANCHOR_NORTH_EAST, - SP_ANCHOR_SOUTH, - SP_ANCHOR_SOUTH_WEST, - SP_ANCHOR_SOUTH_EAST, - SP_ANCHOR_WEST, - SP_ANCHOR_EAST, - SP_ANCHOR_N = SP_ANCHOR_NORTH, - SP_ANCHOR_NW = SP_ANCHOR_NORTH_WEST, - SP_ANCHOR_NE = SP_ANCHOR_NORTH_EAST, - SP_ANCHOR_S = SP_ANCHOR_SOUTH, - SP_ANCHOR_SW = SP_ANCHOR_SOUTH_WEST, - SP_ANCHOR_SE = SP_ANCHOR_SOUTH_EAST, - SP_ANCHOR_W = SP_ANCHOR_WEST, - SP_ANCHOR_E = SP_ANCHOR_EAST + SP_ANCHOR_CENTER, + SP_ANCHOR_NORTH, + SP_ANCHOR_NORTH_WEST, + SP_ANCHOR_NORTH_EAST, + SP_ANCHOR_SOUTH, + SP_ANCHOR_SOUTH_WEST, + SP_ANCHOR_SOUTH_EAST, + SP_ANCHOR_WEST, + SP_ANCHOR_EAST, + SP_ANCHOR_N = SP_ANCHOR_NORTH, + SP_ANCHOR_NW = SP_ANCHOR_NORTH_WEST, + SP_ANCHOR_NE = SP_ANCHOR_NORTH_EAST, + SP_ANCHOR_S = SP_ANCHOR_SOUTH, + SP_ANCHOR_SW = SP_ANCHOR_SOUTH_WEST, + SP_ANCHOR_SE = SP_ANCHOR_SOUTH_EAST, + SP_ANCHOR_W = SP_ANCHOR_WEST, + SP_ANCHOR_E = SP_ANCHOR_EAST }; /* preserveAspectRatio */ -enum { - SP_ASPECT_NONE, - SP_ASPECT_XMIN_YMIN, - SP_ASPECT_XMID_YMIN, - SP_ASPECT_XMAX_YMIN, - SP_ASPECT_XMIN_YMID, - SP_ASPECT_XMID_YMID, - SP_ASPECT_XMAX_YMID, - SP_ASPECT_XMIN_YMAX, - SP_ASPECT_XMID_YMAX, - SP_ASPECT_XMAX_YMAX +enum +{ + SP_ASPECT_NONE, + SP_ASPECT_XMIN_YMIN, + SP_ASPECT_XMID_YMIN, + SP_ASPECT_XMAX_YMIN, + SP_ASPECT_XMIN_YMID, + SP_ASPECT_XMID_YMID, + SP_ASPECT_XMAX_YMID, + SP_ASPECT_XMIN_YMAX, + SP_ASPECT_XMID_YMAX, + SP_ASPECT_XMAX_YMAX }; -enum { - SP_ASPECT_MEET, - SP_ASPECT_SLICE +enum +{ + SP_ASPECT_MEET, + SP_ASPECT_SLICE }; /* maskUnits */ /* maskContentUnits */ -enum { - SP_CONTENT_UNITS_USERSPACEONUSE, - SP_CONTENT_UNITS_OBJECTBOUNDINGBOX +enum +{ + SP_CONTENT_UNITS_USERSPACEONUSE, + SP_CONTENT_UNITS_OBJECTBOUNDINGBOX }; /* markerUnits */ -enum { - SP_MARKER_UNITS_STROKEWIDTH, - SP_MARKER_UNITS_USERSPACEONUSE +enum +{ + SP_MARKER_UNITS_STROKEWIDTH, + SP_MARKER_UNITS_USERSPACEONUSE }; /* stroke-linejoin */ @@ -75,30 +79,34 @@ enum { /* markers */ -enum { - SP_MARKER_NONE, - SP_MARKER_TRIANGLE, - SP_MARKER_ARROW +enum +{ + SP_MARKER_NONE, + SP_MARKER_TRIANGLE, + SP_MARKER_ARROW }; /* fill-rule */ /* clip-rule */ -enum { - SP_CLONE_COMPENSATION_PARALLEL, - SP_CLONE_COMPENSATION_UNMOVED, - SP_CLONE_COMPENSATION_NONE +enum +{ + SP_CLONE_COMPENSATION_PARALLEL, + SP_CLONE_COMPENSATION_UNMOVED, + SP_CLONE_COMPENSATION_NONE }; -enum { - SP_CLONE_ORPHANS_UNLINK, - SP_CLONE_ORPHANS_DELETE, - SP_CLONE_ORPHANS_ASKME +enum +{ + SP_CLONE_ORPHANS_UNLINK, + SP_CLONE_ORPHANS_DELETE, + SP_CLONE_ORPHANS_ASKME }; /* "inlayer" preference values */ -enum PrefsSelectionContext { +enum PrefsSelectionContext +{ PREFS_SELECTION_ALL = 0, PREFS_SELECTION_LAYER = 1, PREFS_SELECTION_LAYER_RECURSIVE = 2, @@ -106,7 +114,8 @@ enum PrefsSelectionContext { /* clip/mask group enclosing behavior preference values */ -enum PrefsMaskobjectGrouping { +enum PrefsMaskobjectGrouping +{ PREFS_MASKOBJECT_GROUPING_NONE = 0, PREFS_MASKOBJECT_GROUPING_SEPARATE = 1, PREFS_MASKOBJECT_GROUPING_ALL = 2, @@ -114,7 +123,8 @@ enum PrefsMaskobjectGrouping { /* save window geometry preference values (/options/savewindowgeometry/value) */ -enum PrefsSaveWindowGeometry { +enum PrefsSaveWindowGeometry +{ PREFS_WINDOW_GEOMETRY_NONE = 0, PREFS_WINDOW_GEOMETRY_FILE = 1, PREFS_WINDOW_GEOMETRY_LAST = 2, @@ -122,7 +132,8 @@ enum PrefsSaveWindowGeometry { /* default window size preference values (/options/defaultwindowsize/value) */ -enum PrefsDefaultWindowSize { +enum PrefsDefaultWindowSize +{ PREFS_WINDOW_SIZE_NATURAL = -1, PREFS_WINDOW_SIZE_SMALL = 0, PREFS_WINDOW_SIZE_LARGE = 1, @@ -130,4 +141,3 @@ enum PrefsDefaultWindowSize { }; #endif - diff --git a/src/event-log.cpp b/src/event-log.cpp index ace74f83f9525c170f0f5bcb3b6213e8b3a5b1b1..708ed4c8b0aa2960a5188e3a834ef0e55f68e1ad 100644 --- a/src/event-log.cpp +++ b/src/event-log.cpp @@ -9,28 +9,26 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "util/signal-blocker.h" - #include "event-log.h" + #include #include "desktop.h" +#include "document.h" #include "inkscape.h" +#include "util/signal-blocker.h" #include "util/ucompose.hpp" -#include "document.h" -namespace -{ +namespace { class DialogConnection { public: - DialogConnection(Gtk::TreeView *event_list_view, Inkscape::EventLog::CallbackMap *callback_connections) : - _event_list_view(event_list_view), - _callback_connections(callback_connections), - _event_list_selection(_event_list_view->get_selection()) - { - } + DialogConnection(Gtk::TreeView *event_list_view, Inkscape::EventLog::CallbackMap *callback_connections) + : _event_list_view(event_list_view) + , _callback_connections(callback_connections) + , _event_list_selection(_event_list_view->get_selection()) + {} Gtk::TreeView *_event_list_view; @@ -43,14 +41,12 @@ public: class ConnectionMatcher { public: - ConnectionMatcher(Gtk::TreeView *view, - Inkscape::EventLog::CallbackMap *callbacks) : - _view(view), - _callbacks(callbacks) - { - } + ConnectionMatcher(Gtk::TreeView *view, Inkscape::EventLog::CallbackMap *callbacks) + : _view(view) + , _callbacks(callbacks) + {} - bool operator() (DialogConnection const &dlg) + bool operator()(DialogConnection const &dlg) { return (_view == dlg._event_list_view) && (_callbacks == dlg._callback_connections); } @@ -59,12 +55,11 @@ public: Inkscape::EventLog::CallbackMap *_callbacks; }; -void addBlocker(std::vector > &blockers, sigc::connection *connection) +void addBlocker(std::vector> &blockers, sigc::connection *connection) { blockers.emplace_back(new SignalBlocker(connection)); } - } // namespace namespace Inkscape { @@ -72,32 +67,25 @@ namespace Inkscape { class EventLogPrivate { public: - EventLogPrivate() : - _connections() - { - } + EventLogPrivate() + : _connections() + {} - bool isConnected() const - { - return !_connections.empty(); - } + bool isConnected() const { return !_connections.empty(); } - void addDialogConnection(Gtk::TreeView *event_list_view, - Inkscape::EventLog::CallbackMap *callback_connections, - Glib::RefPtr event_list_store, - Inkscape::EventLog::iterator &curr_event) + void addDialogConnection(Gtk::TreeView *event_list_view, Inkscape::EventLog::CallbackMap *callback_connections, + Glib::RefPtr event_list_store, Inkscape::EventLog::iterator &curr_event) { - if (std::find_if(_connections.begin(), _connections.end(), ConnectionMatcher(event_list_view, callback_connections)) != _connections.end()) { + if (std::find_if(_connections.begin(), _connections.end(), + ConnectionMatcher(event_list_view, callback_connections)) != _connections.end()) { // skipping - } - else - { + } else { DialogConnection dlg(event_list_view, callback_connections); dlg._event_list_selection->set_mode(Gtk::SELECTION_SINGLE); { - std::vector > blockers; + std::vector> blockers; addBlocker(blockers, &(*dlg._callback_connections)[Inkscape::EventLog::CALLB_SELECTION_CHANGE]); addBlocker(blockers, &(*dlg._callback_connections)[Inkscape::EventLog::CALLB_EXPAND]); @@ -110,7 +98,8 @@ public: void removeDialogConnection(Gtk::TreeView *event_list_view, Inkscape::EventLog::CallbackMap *callback_connections) { - std::vector::iterator it = std::find_if(_connections.begin(), _connections.end(), ConnectionMatcher(event_list_view, callback_connections)); + std::vector::iterator it = std::find_if( + _connections.begin(), _connections.end(), ConnectionMatcher(event_list_view, callback_connections)); if (it != _connections.end()) { _connections.erase(it); } @@ -118,30 +107,26 @@ public: void collapseRow(Gtk::TreeModel::Path const &path) { - std::vector > blockers; - for (auto & _connection : _connections) - { + std::vector> blockers; + for (auto &_connection : _connections) { addBlocker(blockers, &(*_connection._callback_connections)[Inkscape::EventLog::CALLB_SELECTION_CHANGE]); addBlocker(blockers, &(*_connection._callback_connections)[Inkscape::EventLog::CALLB_COLLAPSE]); } - for (auto & _connection : _connections) - { + for (auto &_connection : _connections) { _connection._event_list_view->collapse_row(path); } } void selectRow(Gtk::TreeModel::Path const &path) { - std::vector > blockers; - for (auto & _connection : _connections) - { + std::vector> blockers; + for (auto &_connection : _connections) { addBlocker(blockers, &(*_connection._callback_connections)[Inkscape::EventLog::CALLB_SELECTION_CHANGE]); addBlocker(blockers, &(*_connection._callback_connections)[Inkscape::EventLog::CALLB_EXPAND]); } - for (auto & _connection : _connections) - { + for (auto &_connection : _connections) { _connection._event_list_view->expand_to_path(path); _connection._event_list_selection->select(path); _connection._event_list_view->scroll_to_row(path); @@ -151,9 +136,8 @@ public: void clearEventList(Glib::RefPtr eventListStore) { if (eventListStore) { - std::vector > blockers; - for (auto & _connection : _connections) - { + std::vector> blockers; + for (auto &_connection : _connections) { addBlocker(blockers, &(*_connection._callback_connections)[Inkscape::EventLog::CALLB_SELECTION_CHANGE]); addBlocker(blockers, &(*_connection._callback_connections)[Inkscape::EventLog::CALLB_EXPAND]); } @@ -171,24 +155,25 @@ const EventLog::EventModelColumns &EventLog::getColumns() return columns; } -EventLog::EventLog(SPDocument* document) : - UndoStackObserver(), - _priv(new EventLogPrivate()), - _document (document), - _event_list_store (Gtk::TreeStore::create(getColumns())), - _curr_event_parent (nullptr), - _notifications_blocked (false) +EventLog::EventLog(SPDocument *document) + : UndoStackObserver() + , _priv(new EventLogPrivate()) + , _document(document) + , _event_list_store(Gtk::TreeStore::create(getColumns())) + , _curr_event_parent(nullptr) + , _notifications_blocked(false) { // add initial pseudo event Gtk::TreeRow curr_row = *(_event_list_store->append()); _curr_event = _last_saved = _last_event = curr_row; - + auto &_columns = getColumns(); curr_row[_columns.description] = _("[Unchanged]"); curr_row[_columns.type] = SP_VERB_FILE_NEW; } -EventLog::~EventLog() { +EventLog::~EventLog() +{ // avoid crash by clearing entries here (see bug #1071082) _priv->clearEventList(_event_list_store); @@ -196,27 +181,23 @@ EventLog::~EventLog() { _priv = nullptr; } -void -EventLog::notifyUndoEvent(Event* log) +void EventLog::notifyUndoEvent(Event *log) { - if ( !_notifications_blocked ) { + if (!_notifications_blocked) { auto &_columns = getColumns(); - + // make sure the supplied event matches the next undoable event - g_return_if_fail ( _getUndoEvent() && (*(_getUndoEvent()))[_columns.event] == log ); + g_return_if_fail(_getUndoEvent() && (*(_getUndoEvent()))[_columns.event] == log); // if we're on the first child event... - if ( _curr_event->parent() && - _curr_event == _curr_event->parent()->children().begin() ) - { + if (_curr_event->parent() && _curr_event == _curr_event->parent()->children().begin()) { // ...back up to the parent _curr_event = _curr_event->parent(); - _curr_event_parent = (iterator)nullptr; - - } else { + _curr_event_parent = (iterator) nullptr; + } else { // if we're about to leave a branch, collapse it - if ( !_curr_event->children().empty() ) { + if (!_curr_event->children().empty()) { _priv->collapseRow(_event_list_store->get_path(_curr_event)); } @@ -228,7 +209,7 @@ EventLog::notifyUndoEvent(Event* log) _curr_event = _curr_event->children().end(); --_curr_event; } - } + } checkForVirginity(); @@ -240,40 +221,33 @@ EventLog::notifyUndoEvent(Event* log) updateUndoVerbs(); } - } -void -EventLog::notifyRedoEvent(Event* log) +void EventLog::notifyRedoEvent(Event *log) { - if ( !_notifications_blocked ) { + if (!_notifications_blocked) { auto &_columns = getColumns(); // make sure the supplied event matches the next redoable event - g_return_if_fail ( _getRedoEvent() && (*(_getRedoEvent()))[_columns.event] == log ); + g_return_if_fail(_getRedoEvent() && (*(_getRedoEvent()))[_columns.event] == log); // if we're on a parent event... - if ( !_curr_event->children().empty() ) { - + if (!_curr_event->children().empty()) { // ...move to its first child _curr_event_parent = _curr_event; _curr_event = _curr_event->children().begin(); } else { - ++_curr_event; // if we are about to leave a branch... - if ( _curr_event->parent() && - _curr_event == _curr_event->parent()->children().end() ) - { - + if (_curr_event->parent() && _curr_event == _curr_event->parent()->children().end()) { // ...collapse it _priv->collapseRow(_event_list_store->get_path(_curr_event->parent())); // ...and move to the next event at parent level _curr_event = _curr_event->parent(); - _curr_event_parent = (iterator)nullptr; + _curr_event_parent = (iterator) nullptr; ++_curr_event; } @@ -289,11 +263,9 @@ EventLog::notifyRedoEvent(Event* log) updateUndoVerbs(); } - } -void -EventLog::notifyUndoCommitEvent(Event* log) +void EventLog::notifyUndoCommitEvent(Event *log) { _clearRedo(); @@ -303,8 +275,8 @@ EventLog::notifyUndoCommitEvent(Event* log) auto &_columns = getColumns(); // if the new event is of the same type as the previous then create a new branch - if ( event_type == (*_curr_event)[_columns.type] ) { - if ( !_curr_event_parent ) { + if (event_type == (*_curr_event)[_columns.type]) { + if (!_curr_event_parent) { _curr_event_parent = _curr_event; } curr_row = *(_event_list_store->append(_curr_event_parent->children())); @@ -321,7 +293,7 @@ EventLog::notifyUndoCommitEvent(Event* log) } _curr_event_parent = (iterator)(nullptr); - } + } _curr_event = _last_event = curr_row; @@ -340,21 +312,19 @@ EventLog::notifyUndoCommitEvent(Event* log) updateUndoVerbs(); } -void -EventLog::notifyClearUndoEvent() +void EventLog::notifyClearUndoEvent() { - _clearUndo(); + _clearUndo(); updateUndoVerbs(); } -void -EventLog::notifyClearRedoEvent() +void EventLog::notifyClearRedoEvent() { _clearRedo(); updateUndoVerbs(); } -void EventLog::addDialogConnection(Gtk::TreeView *event_list_view, CallbackMap *callback_connections) +void EventLog::addDialogConnection(Gtk::TreeView *event_list_view, CallbackMap *callback_connections) { _priv->addDialogConnection(event_list_view, callback_connections, _event_list_store, _curr_event); } @@ -364,99 +334,85 @@ void EventLog::removeDialogConnection(Gtk::TreeView *event_list_view, CallbackMa _priv->removeDialogConnection(event_list_view, callback_connections); } -void -EventLog::updateUndoVerbs() +void EventLog::updateUndoVerbs() { - if(_document) { + if (_document) { auto &_columns = getColumns(); - if(_getUndoEvent()) { + if (_getUndoEvent()) { Inkscape::Verb::get(SP_VERB_EDIT_UNDO)->sensitive(_document, true); - Inkscape::Verb::get(SP_VERB_EDIT_UNDO)->name(_document, String::ucompose("%1: %2", - Glib::ustring(_("_Undo")), - Glib::ustring((*_getUndoEvent())[_columns.description]))); + Inkscape::Verb::get(SP_VERB_EDIT_UNDO) + ->name(_document, String::ucompose("%1: %2", Glib::ustring(_("_Undo")), + Glib::ustring((*_getUndoEvent())[_columns.description]))); } else { Inkscape::Verb::get(SP_VERB_EDIT_UNDO)->name(_document, _("_Undo")); Inkscape::Verb::get(SP_VERB_EDIT_UNDO)->sensitive(_document, false); } - if(_getRedoEvent()) { + if (_getRedoEvent()) { Inkscape::Verb::get(SP_VERB_EDIT_REDO)->sensitive(_document, true); - Inkscape::Verb::get(SP_VERB_EDIT_REDO)->name(_document, String::ucompose("%1: %2", - Glib::ustring(_("_Redo")), - Glib::ustring((*_getRedoEvent())[_columns.description]))); + Inkscape::Verb::get(SP_VERB_EDIT_REDO) + ->name(_document, String::ucompose("%1: %2", Glib::ustring(_("_Redo")), + Glib::ustring((*_getRedoEvent())[_columns.description]))); } else { Inkscape::Verb::get(SP_VERB_EDIT_REDO)->name(_document, _("_Redo")); Inkscape::Verb::get(SP_VERB_EDIT_REDO)->sensitive(_document, false); } - } - } - -EventLog::const_iterator -EventLog::_getUndoEvent() const +EventLog::const_iterator EventLog::_getUndoEvent() const { - const_iterator undo_event = (const_iterator)nullptr; - if( _curr_event != _event_list_store->children().begin() ) + const_iterator undo_event = (const_iterator) nullptr; + if (_curr_event != _event_list_store->children().begin()) undo_event = _curr_event; return undo_event; } -EventLog::const_iterator -EventLog::_getRedoEvent() const +EventLog::const_iterator EventLog::_getRedoEvent() const { - const_iterator redo_event = (const_iterator)nullptr; - - if ( _curr_event != _last_event ) { + const_iterator redo_event = (const_iterator) nullptr; - if ( !_curr_event->children().empty() ) + if (_curr_event != _last_event) { + if (!_curr_event->children().empty()) redo_event = _curr_event->children().begin(); - else { + else { redo_event = _curr_event; ++redo_event; - if ( redo_event->parent() && - redo_event == redo_event->parent()->children().end() ) { - + if (redo_event->parent() && redo_event == redo_event->parent()->children().end()) { redo_event = redo_event->parent(); ++redo_event; - } } - } return redo_event; } -void -EventLog::_clearUndo() +void EventLog::_clearUndo() { // TODO: Implement when needed } -void -EventLog::_clearRedo() +void EventLog::_clearRedo() { - if ( _last_event != _curr_event ) { + if (_last_event != _curr_event) { auto &_columns = getColumns(); _last_event = _curr_event; - if ( !_last_event->children().empty() ) { + if (!_last_event->children().empty()) { _last_event = _last_event->children().begin(); } else { ++_last_event; } - while ( _last_event != _event_list_store->children().end() ) { - + while (_last_event != _event_list_store->children().end()) { if (_last_event->parent()) { - while ( _last_event != _last_event->parent()->children().end() ) { + while (_last_event != _last_event->parent()->children().end()) { _last_event = _event_list_store->erase(_last_event); } _last_event = _last_event->parent(); @@ -467,16 +423,14 @@ EventLog::_clearRedo() } else { _last_event = _event_list_store->erase(_last_event); } - } - } } /* mark document as untouched if we reach a state where the document was previously saved */ -void -EventLog::checkForVirginity() { - g_return_if_fail (_document); +void EventLog::checkForVirginity() +{ + g_return_if_fail(_document); if (_curr_event == _last_saved) { _document->setModifiedSinceSave(false); } @@ -484,7 +438,6 @@ EventLog::checkForVirginity() { } // namespace Inkscape - /* Local Variables: mode:c++ diff --git a/src/event-log.h b/src/event-log.h index 48dc31fc4ddc7e3fe2327ad06b7707077bbc239d..b6a86ef48d2c9be86b39b1704766b768f429ddd9 100644 --- a/src/event-log.h +++ b/src/event-log.h @@ -12,14 +12,14 @@ #ifndef INKSCAPE_EVENT_LOG_H #define INKSCAPE_EVENT_LOG_H -#include #include #include +#include #include #include -#include "undo-stack-observer.h" #include "event.h" +#include "undo-stack-observer.h" namespace Inkscape { @@ -38,14 +38,15 @@ class EventLogPrivate; * expanded/collapsed state will be updated as events are committed, undone and redone. Whenever * this happens, the event log will block the TreeView's callbacks to prevent circular updates. */ -class EventLog : public UndoStackObserver, public sigc::trackable +class EventLog + : public UndoStackObserver + , public sigc::trackable { - public: typedef Gtk::TreeModel::iterator iterator; typedef Gtk::TreeModel::const_iterator const_iterator; - EventLog(SPDocument* document); + EventLog(SPDocument *document); ~EventLog() override; /** @@ -59,8 +60,11 @@ public: Gtk::TreeModelColumn child_count; EventModelColumns() - { - add(event); add(type); add(description); add(child_count); + { + add(event); + add(type); + add(description); + add(child_count); } }; @@ -78,22 +82,23 @@ public: // Accessor functions Glib::RefPtr getEventListStore() const { return _event_list_store; } - static const EventModelColumns& getColumns(); - iterator getCurrEvent() const { return _curr_event; } - iterator getCurrEventParent() const { return _curr_event_parent; } + static const EventModelColumns &getColumns(); + iterator getCurrEvent() const { return _curr_event; } + iterator getCurrEventParent() const { return _curr_event_parent; } - void setCurrEvent(iterator event) { _curr_event = event; } - void setCurrEventParent(iterator event) { _curr_event_parent = event; } - void blockNotifications(bool status=true) { _notifications_blocked = status; } - void rememberFileSave() { _last_saved = _curr_event; } + void setCurrEvent(iterator event) { _curr_event = event; } + void setCurrEventParent(iterator event) { _curr_event_parent = event; } + void blockNotifications(bool status = true) { _notifications_blocked = status; } + void rememberFileSave() { _last_saved = _curr_event; } // Callback types for TreeView changes. - enum CallbackTypes { - CALLB_SELECTION_CHANGE, - CALLB_EXPAND, - CALLB_COLLAPSE, - CALLB_LAST + enum CallbackTypes + { + CALLB_SELECTION_CHANGE, + CALLB_EXPAND, + CALLB_COLLAPSE, + CALLB_LAST }; typedef std::map CallbackMap; @@ -117,15 +122,15 @@ public: private: EventLogPrivate *_priv; - SPDocument *_document; //< document that is logged + SPDocument *_document; //< document that is logged - Glib::RefPtr _event_list_store; + Glib::RefPtr _event_list_store; iterator _curr_event; //< current event in _event_list_store iterator _last_event; //< end position in _event_list_store iterator _curr_event_parent; //< parent to current event, if any - iterator _last_saved; //< position where last document save occurred + iterator _last_saved; //< position where last document save occurred bool _notifications_blocked; //< if notifications should be handled @@ -134,14 +139,14 @@ private: const_iterator _getUndoEvent() const; //< returns the current undoable event or NULL if none const_iterator _getRedoEvent() const; //< returns the current redoable event or NULL if none - void _clearUndo(); //< erase all previously committed events - void _clearRedo(); //< erase all previously undone events + void _clearUndo(); //< erase all previously committed events + void _clearRedo(); //< erase all previously undone events void checkForVirginity(); //< marks the document as untouched if undo/redo reaches a previously saved state // noncopyable, nonassignable EventLog(EventLog const &other) = delete; - EventLog& operator=(EventLog const &other) = delete; + EventLog &operator=(EventLog const &other) = delete; }; } // namespace Inkscape diff --git a/src/event.h b/src/event.h index 65a128da9fb1c33d3e6a8347fee0b07e8712879b..8db8f9a1da633fffb9cd794f7f5b6b72aa8f5c78 100644 --- a/src/event.h +++ b/src/event.h @@ -14,28 +14,29 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include - #include -#include "xml/event-fns.h" #include "verbs.h" +#include "xml/event-fns.h" namespace Inkscape { namespace XML { class Event; } -} +} // namespace Inkscape namespace Inkscape { -struct Event { - - Event(XML::Event *_event, unsigned int _type=SP_VERB_NONE, Glib::ustring _description="") - : event (_event), type (_type), description (std::move(_description)) { } +struct Event +{ + Event(XML::Event *_event, unsigned int _type = SP_VERB_NONE, Glib::ustring _description = "") + : event(_event) + , type(_type) + , description(std::move(_description)) + {} - virtual ~Event() { sp_repr_free_log (event); } + virtual ~Event() { sp_repr_free_log(event); } XML::Event *event; const unsigned int type; diff --git a/src/extension/db.cpp b/src/extension/db.cpp index 2c1ab953ec52dda2f58a3a9f726433b944cda1c2..ed0a44eac69ca476cf1b5a0e5212afe4d16a9d23 100644 --- a/src/extension/db.cpp +++ b/src/extension/db.cpp @@ -14,9 +14,10 @@ */ #include "db.h" + +#include "effect.h" #include "input.h" #include "output.h" -#include "effect.h" /* Globals */ @@ -30,281 +31,298 @@ DB db; /* Types */ -DB::DB (void) = default; - - -struct ModuleInputCmp { - bool operator()(Input* module1, Input* module2) const { - - // Ensure SVG files are at top - int n1 = 0; - int n2 = 0; - // 12345678901234567890123456789012 - if (strncmp(module1->get_id(),"org.inkscape.input.svg", 22) == 0) n1 = 1; - if (strncmp(module2->get_id(),"org.inkscape.input.svg", 22) == 0) n2 = 1; - if (strncmp(module1->get_id(),"org.inkscape.input.svgz", 23) == 0) n1 = 2; - if (strncmp(module2->get_id(),"org.inkscape.input.svgz", 23) == 0) n2 = 2; +DB::DB(void) = default; - if (n1 != 0 && n2 != 0) return (n1 < n2); - if (n1 != 0) return true; - if (n2 != 0) return false; - - // GDK filetypenames begin with lower case letters and thus are sorted at the end. - // Special case "sK1" which starts with a lower case letter to keep it out of GDK region. - if (strncmp(module1->get_id(),"org.inkscape.input.sk1", 22) == 0) { - return ( strcmp("SK1", module2->get_filetypename()) <= 0 ); - } - if (strncmp(module2->get_id(),"org.inkscape.input.sk1", 22) == 0) { - return ( strcmp(module1->get_filetypename(), "SK1" ) <= 0 ); +struct ModuleInputCmp +{ + bool operator()(Input *module1, Input *module2) const + { + // Ensure SVG files are at top + int n1 = 0; + int n2 = 0; + // 12345678901234567890123456789012 + if (strncmp(module1->get_id(), "org.inkscape.input.svg", 22) == 0) + n1 = 1; + if (strncmp(module2->get_id(), "org.inkscape.input.svg", 22) == 0) + n2 = 1; + if (strncmp(module1->get_id(), "org.inkscape.input.svgz", 23) == 0) + n1 = 2; + if (strncmp(module2->get_id(), "org.inkscape.input.svgz", 23) == 0) + n2 = 2; + + if (n1 != 0 && n2 != 0) + return (n1 < n2); + if (n1 != 0) + return true; + if (n2 != 0) + return false; + + // GDK filetypenames begin with lower case letters and thus are sorted at the end. + // Special case "sK1" which starts with a lower case letter to keep it out of GDK region. + if (strncmp(module1->get_id(), "org.inkscape.input.sk1", 22) == 0) { + return (strcmp("SK1", module2->get_filetypename()) <= 0); + } + if (strncmp(module2->get_id(), "org.inkscape.input.sk1", 22) == 0) { + return (strcmp(module1->get_filetypename(), "SK1") <= 0); + } + + return (strcmp(module1->get_filetypename(), module2->get_filetypename()) <= 0); } - - return ( strcmp(module1->get_filetypename(), module2->get_filetypename()) <= 0 ); - } }; - -struct ModuleOutputCmp { - bool operator()(Output* module1, Output* module2) const { - - // Ensure SVG files are at top - int n1 = 0; - int n2 = 0; - // 12345678901234567890123456789012 - if (strncmp(module1->get_id(),"org.inkscape.output.svg.inkscape", 32) == 0) n1 = 1; - if (strncmp(module2->get_id(),"org.inkscape.output.svg.inkscape", 32) == 0) n2 = 1; - if (strncmp(module1->get_id(),"org.inkscape.output.svg.plain", 29) == 0) n1 = 2; - if (strncmp(module2->get_id(),"org.inkscape.output.svg.plain", 29) == 0) n2 = 2; - if (strncmp(module1->get_id(),"org.inkscape.output.svgz.inkscape", 33) == 0) n1 = 3; - if (strncmp(module2->get_id(),"org.inkscape.output.svgz.inkscape", 33) == 0) n2 = 3; - if (strncmp(module1->get_id(),"org.inkscape.output.svgz.plain", 30) == 0) n1 = 4; - if (strncmp(module2->get_id(),"org.inkscape.output.svgz.plain", 30) == 0) n2 = 4; - if (strncmp(module1->get_id(),"org.inkscape.output.scour", 25) == 0) n1 = 5; - if (strncmp(module2->get_id(),"org.inkscape.output.scour", 25) == 0) n2 = 5; - if (strncmp(module1->get_id(),"org.inkscape.output.ZIP", 23) == 0) n1 = 6; - if (strncmp(module2->get_id(),"org.inkscape.output.ZIP", 23) == 0) n2 = 6; - if (strncmp(module1->get_id(),"org.inkscape.output.LAYERS", 26) == 0) n1 = 7; - if (strncmp(module2->get_id(),"org.inkscape.output.LAYERS", 26) == 0) n2 = 7; - - if (n1 != 0 && n2 != 0) return (n1 < n2); - if (n1 != 0) return true; - if (n2 != 0) return false; - - // Special case "sK1" which starts with a lower case letter. - if (strncmp(module1->get_id(),"org.inkscape.output.sk1", 23) == 0) { - return ( strcmp("SK1", module2->get_filetypename()) <= 0 ); - } - if (strncmp(module2->get_id(),"org.inkscape.output.sk1", 23) == 0) { - return ( strcmp(module1->get_filetypename(), "SK1" ) <= 0 ); +struct ModuleOutputCmp +{ + bool operator()(Output *module1, Output *module2) const + { + // Ensure SVG files are at top + int n1 = 0; + int n2 = 0; + // 12345678901234567890123456789012 + if (strncmp(module1->get_id(), "org.inkscape.output.svg.inkscape", 32) == 0) + n1 = 1; + if (strncmp(module2->get_id(), "org.inkscape.output.svg.inkscape", 32) == 0) + n2 = 1; + if (strncmp(module1->get_id(), "org.inkscape.output.svg.plain", 29) == 0) + n1 = 2; + if (strncmp(module2->get_id(), "org.inkscape.output.svg.plain", 29) == 0) + n2 = 2; + if (strncmp(module1->get_id(), "org.inkscape.output.svgz.inkscape", 33) == 0) + n1 = 3; + if (strncmp(module2->get_id(), "org.inkscape.output.svgz.inkscape", 33) == 0) + n2 = 3; + if (strncmp(module1->get_id(), "org.inkscape.output.svgz.plain", 30) == 0) + n1 = 4; + if (strncmp(module2->get_id(), "org.inkscape.output.svgz.plain", 30) == 0) + n2 = 4; + if (strncmp(module1->get_id(), "org.inkscape.output.scour", 25) == 0) + n1 = 5; + if (strncmp(module2->get_id(), "org.inkscape.output.scour", 25) == 0) + n2 = 5; + if (strncmp(module1->get_id(), "org.inkscape.output.ZIP", 23) == 0) + n1 = 6; + if (strncmp(module2->get_id(), "org.inkscape.output.ZIP", 23) == 0) + n2 = 6; + if (strncmp(module1->get_id(), "org.inkscape.output.LAYERS", 26) == 0) + n1 = 7; + if (strncmp(module2->get_id(), "org.inkscape.output.LAYERS", 26) == 0) + n2 = 7; + + if (n1 != 0 && n2 != 0) + return (n1 < n2); + if (n1 != 0) + return true; + if (n2 != 0) + return false; + + // Special case "sK1" which starts with a lower case letter. + if (strncmp(module1->get_id(), "org.inkscape.output.sk1", 23) == 0) { + return (strcmp("SK1", module2->get_filetypename()) <= 0); + } + if (strncmp(module2->get_id(), "org.inkscape.output.sk1", 23) == 0) { + return (strcmp(module1->get_filetypename(), "SK1") <= 0); + } + + return (strcmp(module1->get_filetypename(), module2->get_filetypename()) <= 0); } - - return ( strcmp(module1->get_filetypename(), module2->get_filetypename()) <= 0 ); - } }; - /** - \brief Add a module to the module database - \param module The module to be registered. + \brief Add a module to the module database + \param module The module to be registered. */ -void -DB::register_ext (Extension *module) +void DB::register_ext(Extension *module) { - g_return_if_fail(module != nullptr); - g_return_if_fail(module->get_id() != nullptr); - - // only add to list if it's a never-before-seen module - bool add_to_list = - ( moduledict.find(module->get_id()) == moduledict.end()); - - //printf("Registering: '%s' '%s' add:%d\n", module->get_id(), module->get_name(), add_to_list); - moduledict[module->get_id()] = module; - - if (add_to_list) { - modulelist.push_back( module ); - } + g_return_if_fail(module != nullptr); + g_return_if_fail(module->get_id() != nullptr); + + // only add to list if it's a never-before-seen module + bool add_to_list = (moduledict.find(module->get_id()) == moduledict.end()); + + // printf("Registering: '%s' '%s' add:%d\n", module->get_id(), module->get_name(), add_to_list); + moduledict[module->get_id()] = module; + + if (add_to_list) { + modulelist.push_back(module); + } } /** - \brief This function removes a module from the database - \param module The module to be removed. + \brief This function removes a module from the database + \param module The module to be removed. */ -void -DB::unregister_ext (Extension * module) +void DB::unregister_ext(Extension *module) { - g_return_if_fail(module != nullptr); - g_return_if_fail(module->get_id() != nullptr); - - // printf("Extension DB: removing %s\n", module->get_id()); - moduledict.erase(moduledict.find(module->get_id())); - // only remove if it's not there any more - if ( moduledict.find(module->get_id()) != moduledict.end()) - modulelist.remove(module); + g_return_if_fail(module != nullptr); + g_return_if_fail(module->get_id() != nullptr); + + // printf("Extension DB: removing %s\n", module->get_id()); + moduledict.erase(moduledict.find(module->get_id())); + // only remove if it's not there any more + if (moduledict.find(module->get_id()) != moduledict.end()) + modulelist.remove(module); } /** - \return A reference to the Inkscape::Extension::Extension specified by the input key. - \brief This function looks up a Inkscape::Extension::Extension by using its unique - id. It then returns a reference to that module. - \param key The unique ID of the module - - Retrieves a module by name; if non-NULL, it refs the returned - module; the caller is responsible for releasing that reference - when it is no longer needed. + \return A reference to the Inkscape::Extension::Extension specified by the input key. + \brief This function looks up a Inkscape::Extension::Extension by using its unique + id. It then returns a reference to that module. + \param key The unique ID of the module + + Retrieves a module by name; if non-NULL, it refs the returned + module; the caller is responsible for releasing that reference + when it is no longer needed. */ -Extension * -DB::get (const gchar *key) +Extension *DB::get(const gchar *key) { - if (key == nullptr) return nullptr; + if (key == nullptr) + return nullptr; - Extension *mod = moduledict[key]; - if ( !mod || mod->deactivated() ) - return nullptr; + Extension *mod = moduledict[key]; + if (!mod || mod->deactivated()) + return nullptr; - return mod; + return mod; } /** - \return none - \brief A function to execute another function with every entry - in the database as a parameter. - \param in_func The function to execute for every module - \param in_data A data pointer that is also passed to in_func - - Enumerates the modules currently in the database, calling a given - callback for each one. + \return none + \brief A function to execute another function with every entry + in the database as a parameter. + \param in_func The function to execute for every module + \param in_data A data pointer that is also passed to in_func + + Enumerates the modules currently in the database, calling a given + callback for each one. */ -void -DB::foreach (void (*in_func)(Extension * in_plug, gpointer in_data), gpointer in_data) +void DB::foreach (void (*in_func)(Extension *in_plug, gpointer in_data), gpointer in_data) { - std::list ::iterator cur; + std::list::iterator cur; - for (cur = modulelist.begin(); cur != modulelist.end(); ++cur) { - // printf("foreach: %s\n", (*cur)->get_id()); - in_func((*cur), in_data); - } + for (cur = modulelist.begin(); cur != modulelist.end(); ++cur) { + // printf("foreach: %s\n", (*cur)->get_id()); + in_func((*cur), in_data); + } } /** - \return none - \brief The function to look at each module and see if it is - an input module, then add it to the list. - \param in_plug Module to be examined - \param data The list to be attached to - - The first thing that is checked is if this module is an input - module. If it is, then it is added to the list which is passed - in through \c data. + \return none + \brief The function to look at each module and see if it is + an input module, then add it to the list. + \param in_plug Module to be examined + \param data The list to be attached to + + The first thing that is checked is if this module is an input + module. If it is, then it is added to the list which is passed + in through \c data. */ -void -DB::input_internal (Extension * in_plug, gpointer data) +void DB::input_internal(Extension *in_plug, gpointer data) { - if (dynamic_cast(in_plug)) { - InputList * ilist; - Input * imod; + if (dynamic_cast(in_plug)) { + InputList *ilist; + Input *imod; - imod = dynamic_cast(in_plug); - ilist = reinterpret_cast(data); + imod = dynamic_cast(in_plug); + ilist = reinterpret_cast(data); - ilist->push_back(imod); - // printf("Added to input list: %s\n", imod->get_id()); - } + ilist->push_back(imod); + // printf("Added to input list: %s\n", imod->get_id()); + } } /** - \return none - \brief The function to look at each module and see if it is - an output module, then add it to the list. - \param in_plug Module to be examined - \param data The list to be attached to - - The first thing that is checked is if this module is an output - module. If it is, then it is added to the list which is passed - in through \c data. + \return none + \brief The function to look at each module and see if it is + an output module, then add it to the list. + \param in_plug Module to be examined + \param data The list to be attached to + + The first thing that is checked is if this module is an output + module. If it is, then it is added to the list which is passed + in through \c data. */ -void -DB::output_internal (Extension * in_plug, gpointer data) +void DB::output_internal(Extension *in_plug, gpointer data) { - if (dynamic_cast(in_plug)) { - OutputList * olist; - Output * omod; + if (dynamic_cast(in_plug)) { + OutputList *olist; + Output *omod; - omod = dynamic_cast(in_plug); - olist = reinterpret_cast(data); + omod = dynamic_cast(in_plug); + olist = reinterpret_cast(data); - olist->push_back(omod); - // printf("Added to output list: %s\n", omod->get_id()); - } + olist->push_back(omod); + // printf("Added to output list: %s\n", omod->get_id()); + } - return; + return; } /** - \return none - \brief The function to look at each module and see if it is - an effect module, then add it to the list. - \param in_plug Module to be examined - \param data The list to be attached to - - The first thing that is checked is if this module is an effect - module. If it is, then it is added to the list which is passed - in through \c data. + \return none + \brief The function to look at each module and see if it is + an effect module, then add it to the list. + \param in_plug Module to be examined + \param data The list to be attached to + + The first thing that is checked is if this module is an effect + module. If it is, then it is added to the list which is passed + in through \c data. */ -void -DB::effect_internal (Extension * in_plug, gpointer data) +void DB::effect_internal(Extension *in_plug, gpointer data) { - if (dynamic_cast(in_plug)) { - EffectList * elist; - Effect * emod; + if (dynamic_cast(in_plug)) { + EffectList *elist; + Effect *emod; - emod = dynamic_cast(in_plug); - elist = reinterpret_cast(data); + emod = dynamic_cast(in_plug); + elist = reinterpret_cast(data); - elist->push_back(emod); - // printf("Added to effect list: %s\n", emod->get_id()); - } + elist->push_back(emod); + // printf("Added to effect list: %s\n", emod->get_id()); + } - return; + return; } /** - \brief Creates a list of all the Input extensions - \param ou_list The list that is used to put all the extensions in + \brief Creates a list of all the Input extensions + \param ou_list The list that is used to put all the extensions in - Calls the database \c foreach function with \c input_internal. + Calls the database \c foreach function with \c input_internal. */ -DB::InputList & -DB::get_input_list (DB::InputList &ou_list) +DB::InputList &DB::get_input_list(DB::InputList &ou_list) { - foreach(input_internal, (gpointer)&ou_list); - ou_list.sort( ModuleInputCmp() ); - return ou_list; + foreach (input_internal, (gpointer)&ou_list) + ; + ou_list.sort(ModuleInputCmp()); + return ou_list; } /** - \brief Creates a list of all the Output extensions - \param ou_list The list that is used to put all the extensions in + \brief Creates a list of all the Output extensions + \param ou_list The list that is used to put all the extensions in - Calls the database \c foreach function with \c output_internal. + Calls the database \c foreach function with \c output_internal. */ -DB::OutputList & -DB::get_output_list (DB::OutputList &ou_list) +DB::OutputList &DB::get_output_list(DB::OutputList &ou_list) { - foreach(output_internal, (gpointer)&ou_list); - ou_list.sort( ModuleOutputCmp() ); - return ou_list; + foreach (output_internal, (gpointer)&ou_list) + ; + ou_list.sort(ModuleOutputCmp()); + return ou_list; } /** - \brief Creates a list of all the Effect extensions - \param ou_list The list that is used to put all the extensions in + \brief Creates a list of all the Effect extensions + \param ou_list The list that is used to put all the extensions in - Calls the database \c foreach function with \c effect_internal. + Calls the database \c foreach function with \c effect_internal. */ -DB::EffectList & -DB::get_effect_list (DB::EffectList &ou_list) +DB::EffectList &DB::get_effect_list(DB::EffectList &ou_list) { - foreach(effect_internal, (gpointer)&ou_list); - return ou_list; + foreach (effect_internal, (gpointer)&ou_list) + ; + return ou_list; } -} } /* namespace Extension, Inkscape */ +} // namespace Extension +} // namespace Inkscape diff --git a/src/extension/db.h b/src/extension/db.h index 4efc74f8b39bf5e54d8e5649f37134a5b003364e..5dd9828e5787292c0a79eafeae1539993cdeb696 100644 --- a/src/extension/db.h +++ b/src/extension/db.h @@ -16,12 +16,10 @@ #ifndef SEEN_MODULES_DB_H #define SEEN_MODULES_DB_H -#include -#include #include - #include - +#include +#include namespace Inkscape { namespace Extension { @@ -31,13 +29,16 @@ class Output; class Effect; class Extension; -class DB { +class DB +{ private: /** A string comparison function to be used in the moduledict to find the different extensions in the hash map. */ - struct ltstr { - bool operator()(const char* s1, const char* s2) const { - if ( (s1 == nullptr) && (s2 != nullptr) ) { + struct ltstr + { + bool operator()(const char *s1, const char *s2) const + { + if ((s1 == nullptr) && (s2 != nullptr)) { return true; } else if (s1 == nullptr || s2 == nullptr) { return false; @@ -48,38 +49,39 @@ private: }; /** This is the actual database. It has all of the modules in it, indexed by their ids. It's a hash table for faster lookups */ - std::map moduledict; + std::map moduledict; /** Maintain an ordered list of modules for generating the extension lists via "foreach" */ - std::list modulelist; + std::list modulelist; - static void foreach_internal (gpointer in_key, gpointer in_value, gpointer in_data); + static void foreach_internal(gpointer in_key, gpointer in_value, gpointer in_data); public: - DB (); - Extension * get (const gchar *key); - void register_ext (Extension *module); - void unregister_ext (Extension *module); - void foreach (void (*in_func)(Extension * in_plug, gpointer in_data), gpointer in_data); + DB(); + Extension *get(const gchar *key); + void register_ext(Extension *module); + void unregister_ext(Extension *module); + void foreach (void (*in_func)(Extension *in_plug, gpointer in_data), gpointer in_data); private: - static void input_internal (Extension * in_plug, gpointer data); - static void output_internal (Extension * in_plug, gpointer data); - static void effect_internal (Extension * in_plug, gpointer data); + static void input_internal(Extension *in_plug, gpointer data); + static void output_internal(Extension *in_plug, gpointer data); + static void effect_internal(Extension *in_plug, gpointer data); public: typedef std::list OutputList; typedef std::list InputList; typedef std::list EffectList; - InputList &get_input_list (InputList &ou_list); - OutputList &get_output_list (OutputList &ou_list); - EffectList &get_effect_list (EffectList &ou_list); + InputList &get_input_list(InputList &ou_list); + OutputList &get_output_list(OutputList &ou_list); + EffectList &get_effect_list(EffectList &ou_list); }; /* class DB */ extern DB db; -} } /* namespace Extension, Inkscape */ +} // namespace Extension +} // namespace Inkscape #endif // SEEN_MODULES_DB_H diff --git a/src/extension/dbus/application-interface.cpp b/src/extension/dbus/application-interface.cpp index 1b4be697d399ba61ba04b7b59d6432650c4885ac..08bc7f65e93597ca2d403568c8c5b14729e6d5cb 100644 --- a/src/extension/dbus/application-interface.cpp +++ b/src/extension/dbus/application-interface.cpp @@ -17,38 +17,33 @@ */ #include "application-interface.h" + #include + #include "dbus-init.h" #include "file.h" #include "inkscape.h" G_DEFINE_TYPE(ApplicationInterface, application_interface, G_TYPE_OBJECT) -static void -application_interface_finalize (GObject *object) +static void application_interface_finalize(GObject *object) { - G_OBJECT_CLASS (application_interface_parent_class)->finalize (object); + G_OBJECT_CLASS(application_interface_parent_class)->finalize(object); } - -static void -application_interface_class_init (ApplicationInterfaceClass *klass) +static void application_interface_class_init(ApplicationInterfaceClass *klass) { - GObjectClass *object_class; - object_class = G_OBJECT_CLASS (klass); - object_class->finalize = application_interface_finalize; + GObjectClass *object_class; + object_class = G_OBJECT_CLASS(klass); + object_class->finalize = application_interface_finalize; } -static void -application_interface_init (ApplicationInterface *app_interface) +static void application_interface_init(ApplicationInterface *app_interface) { - dbus_g_error_domain_register (INKSCAPE_ERROR, - NULL, - INKSCAPE_TYPE_ERROR); + dbus_g_error_domain_register(INKSCAPE_ERROR, NULL, INKSCAPE_TYPE_ERROR); } -static bool -ensure_desktop_valid(GError **error) +static bool ensure_desktop_valid(GError **error) { if (!INKSCAPE.use_gui()) { g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OTHER, "Application interface action requires a GUI"); @@ -57,20 +52,19 @@ ensure_desktop_valid(GError **error) return true; } -static bool -ensure_desktop_not_present(GError **error) +static bool ensure_desktop_not_present(GError **error) { if (INKSCAPE.use_gui()) { - g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OTHER, "Application interface action requires non-GUI (command line) mode"); + g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OTHER, + "Application interface action requires non-GUI (command line) mode"); return false; } return true; } -ApplicationInterface * -application_interface_new (void) +ApplicationInterface *application_interface_new(void) { - return (ApplicationInterface*)g_object_new (TYPE_APPLICATION_INTERFACE, NULL); + return (ApplicationInterface *)g_object_new(TYPE_APPLICATION_INTERFACE, NULL); } /* @@ -78,32 +72,32 @@ application_interface_new (void) * * To add a new error type, edit here and in the .h InkscapeError enum. */ -GQuark -inkscape_error_quark (void) +GQuark inkscape_error_quark(void) { - static GQuark quark = 0; - if (!quark) - quark = g_quark_from_static_string ("inkscape_error"); + static GQuark quark = 0; + if (!quark) + quark = g_quark_from_static_string("inkscape_error"); - return quark; + return quark; } -#define ENUM_ENTRY(NAME, DESC) { NAME, "" #NAME "", DESC } +#define ENUM_ENTRY(NAME, DESC) \ + { \ + NAME, "" #NAME "", DESC \ + } GType inkscape_error_get_type(void) { static GType etype = 0; if (etype == 0) { - static const GEnumValue values[] = - { + static const GEnumValue values[] = { - ENUM_ENTRY(INKSCAPE_ERROR_SELECTION, "Incompatible_Selection"), - ENUM_ENTRY(INKSCAPE_ERROR_OBJECT, "Incompatible_Object"), - ENUM_ENTRY(INKSCAPE_ERROR_VERB, "Failed_Verb"), - ENUM_ENTRY(INKSCAPE_ERROR_OTHER, "Generic_Error"), - { 0, 0, 0 } - }; + ENUM_ENTRY(INKSCAPE_ERROR_SELECTION, "Incompatible_Selection"), + ENUM_ENTRY(INKSCAPE_ERROR_OBJECT, "Incompatible_Object"), + ENUM_ENTRY(INKSCAPE_ERROR_VERB, "Failed_Verb"), + ENUM_ENTRY(INKSCAPE_ERROR_OTHER, "Generic_Error"), + {0, 0, 0}}; etype = g_enum_register_static("InkscapeError", values); } @@ -115,44 +109,34 @@ GType inkscape_error_get_type(void) DESKTOP FUNCTIONS ****************************************************************************/ -gchar* -application_interface_desktop_new (ApplicationInterface *app_interface, - GError **error) +gchar *application_interface_desktop_new(ApplicationInterface *app_interface, GError **error) { g_return_val_if_fail(ensure_desktop_valid(error), NULL); - return (gchar*)Inkscape::Extension::Dbus::init_desktop(); + return (gchar *)Inkscape::Extension::Dbus::init_desktop(); } -gchar** -application_interface_get_desktop_list (ApplicationInterface *app_interface) +gchar **application_interface_get_desktop_list(ApplicationInterface *app_interface) { - return NULL; + return NULL; } -gchar* -application_interface_get_active_desktop (ApplicationInterface *app_interface, - GError **error) +gchar *application_interface_get_active_desktop(ApplicationInterface *app_interface, GError **error) { - return NULL; + return NULL; } -gboolean -application_interface_set_active_desktop (ApplicationInterface *app_interface, - gchar* document_name, - GError **error) +gboolean application_interface_set_active_desktop(ApplicationInterface *app_interface, gchar *document_name, + GError **error) { - return TRUE; + return TRUE; } -gboolean -application_interface_desktop_close_all (ApplicationInterface *app_interface, - GError **error) +gboolean application_interface_desktop_close_all(ApplicationInterface *app_interface, GError **error) { - return TRUE; + return TRUE; } -gboolean -application_interface_exit (ApplicationInterface *app_interface, GError **error) +gboolean application_interface_exit(ApplicationInterface *app_interface, GError **error) { sp_file_exit(); return TRUE; @@ -162,35 +146,29 @@ application_interface_exit (ApplicationInterface *app_interface, GError **error) DOCUMENT FUNCTIONS ****************************************************************************/ -gchar* application_interface_document_new (ApplicationInterface *app_interface, - GError **error) +gchar *application_interface_document_new(ApplicationInterface *app_interface, GError **error) { g_return_val_if_fail(ensure_desktop_not_present(error), NULL); - return (gchar*)Inkscape::Extension::Dbus::init_document(); + return (gchar *)Inkscape::Extension::Dbus::init_document(); } -gchar* -application_interface_get_active_document(ApplicationInterface *app_interface, - GError **error) +gchar *application_interface_get_active_document(ApplicationInterface *app_interface, GError **error) { - gchar *result = (gchar*)Inkscape::Extension::Dbus::init_active_document(); - if (!result) { - g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OTHER, "No active document"); - } - return result; + gchar *result = (gchar *)Inkscape::Extension::Dbus::init_active_document(); + if (!result) { + g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OTHER, "No active document"); + } + return result; } -gchar** -application_interface_get_document_list (ApplicationInterface *app_interface) +gchar **application_interface_get_document_list(ApplicationInterface *app_interface) { - return NULL; + return NULL; } -gboolean -application_interface_document_close_all (ApplicationInterface *app_interface, - GError **error) +gboolean application_interface_document_close_all(ApplicationInterface *app_interface, GError **error) { - return TRUE; + return TRUE; } /* INTERESTING FUNCTIONS @@ -203,4 +181,3 @@ application_interface_document_close_all (ApplicationInterface *app_interface, Inkscape::XML::Node *repr = doc->getReprRoot(); g_assert(repr != NULL); */ - diff --git a/src/extension/dbus/application-interface.h b/src/extension/dbus/application-interface.h index 9e975856188d954a80d59a89240193dd4bc3229f..390775378af836ad6643b0426105244df887b592 100644 --- a/src/extension/dbus/application-interface.h +++ b/src/extension/dbus/application-interface.h @@ -19,104 +19,87 @@ #ifndef INKSCAPE_EXTENSION_APPLICATION_INTERFACE_H_ #define INKSCAPE_EXTENSION_APPLICATION_INTERFACE_H_ -#include -#include #include #include +#include +#include + +#define DBUS_APPLICATION_INTERFACE_PATH "/org/inkscape/application" -#define DBUS_APPLICATION_INTERFACE_PATH "/org/inkscape/application" - -#define TYPE_APPLICATION_INTERFACE (application_interface_get_type ()) -#define APPLICATION_INTERFACE(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), TYPE_APPLICATION_INTERFACE, ApplicationInterface)) -#define APPLICATION_INTERFACE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), TYPE_APPLICATION_INTERFACE, ApplicationInterfaceClass)) -#define IS_APPLICATION_INTERFACE(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), TYPE_APPLICATION_INTERFACE)) -#define IS_APPLICATION_INTERFACE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), TYPE_APPLICATION_INTERFACE)) -#define APPLICATION_INTERFACE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), TYPE_APPLICATION_INTERFACE, ApplicationInterfaceClass)) +#define TYPE_APPLICATION_INTERFACE (application_interface_get_type()) +#define APPLICATION_INTERFACE(object) \ + (G_TYPE_CHECK_INSTANCE_CAST((object), TYPE_APPLICATION_INTERFACE, ApplicationInterface)) +#define APPLICATION_INTERFACE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass), TYPE_APPLICATION_INTERFACE, ApplicationInterfaceClass)) +#define IS_APPLICATION_INTERFACE(object) (G_TYPE_CHECK_INSTANCE_TYPE((object), TYPE_APPLICATION_INTERFACE)) +#define IS_APPLICATION_INTERFACE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), TYPE_APPLICATION_INTERFACE)) +#define APPLICATION_INTERFACE_GET_CLASS(obj) \ + (G_TYPE_INSTANCE_GET_CLASS((obj), TYPE_APPLICATION_INTERFACE, ApplicationInterfaceClass)) G_BEGIN_DECLS typedef struct _ApplicationInterface ApplicationInterface; typedef struct _ApplicationInterfaceClass ApplicationInterfaceClass; -struct _ApplicationInterface { - GObject parent; +struct _ApplicationInterface +{ + GObject parent; }; -struct _ApplicationInterfaceClass { - GObjectClass parent; +struct _ApplicationInterfaceClass +{ + GObjectClass parent; }; - enum InkscapeError { - INKSCAPE_ERROR_SELECTION, - INKSCAPE_ERROR_OBJECT, - INKSCAPE_ERROR_VERB, - INKSCAPE_ERROR_OTHER + INKSCAPE_ERROR_SELECTION, + INKSCAPE_ERROR_OBJECT, + INKSCAPE_ERROR_VERB, + INKSCAPE_ERROR_OTHER }; +#define INKSCAPE_ERROR (inkscape_error_quark()) +#define INKSCAPE_TYPE_ERROR (inkscape_error_get_type()) - -#define INKSCAPE_ERROR (inkscape_error_quark ()) -#define INKSCAPE_TYPE_ERROR (inkscape_error_get_type ()) - -GQuark inkscape_error_quark (void); -GType inkscape_error_get_type (void); +GQuark inkscape_error_quark(void); +GType inkscape_error_get_type(void); /**************************************************************************** DESKTOP FUNCTIONS ****************************************************************************/ -gchar* -application_interface_desktop_new (ApplicationInterface *app_interface, - GError **error); +gchar *application_interface_desktop_new(ApplicationInterface *app_interface, GError **error); -gchar** -application_interface_get_desktop_list (ApplicationInterface *app_interface); +gchar **application_interface_get_desktop_list(ApplicationInterface *app_interface); -gchar* -application_interface_get_active_desktop (ApplicationInterface *app_interface, - GError **error); +gchar *application_interface_get_active_desktop(ApplicationInterface *app_interface, GError **error); -gboolean -application_interface_set_active_desktop (ApplicationInterface *app_interface, - gchar* document_name, - GError **error); +gboolean application_interface_set_active_desktop(ApplicationInterface *app_interface, gchar *document_name, + GError **error); -gboolean -application_interface_desktop_close_all (ApplicationInterface *app_interface, - GError **error); +gboolean application_interface_desktop_close_all(ApplicationInterface *app_interface, GError **error); -gboolean -application_interface_exit (ApplicationInterface *app_interface, GError **error); +gboolean application_interface_exit(ApplicationInterface *app_interface, GError **error); /**************************************************************************** DOCUMENT FUNCTIONS ****************************************************************************/ -gchar* -application_interface_document_new (ApplicationInterface *app_interface, - GError **error); - -gchar* -application_interface_get_active_document(ApplicationInterface *app_interface, - GError **error); +gchar *application_interface_document_new(ApplicationInterface *app_interface, GError **error); -gchar** -application_interface_get_document_list (ApplicationInterface *app_interface); +gchar *application_interface_get_active_document(ApplicationInterface *app_interface, GError **error); -gboolean -application_interface_document_close_all (ApplicationInterface *app_interface, - GError **error); +gchar **application_interface_get_document_list(ApplicationInterface *app_interface); +gboolean application_interface_document_close_all(ApplicationInterface *app_interface, GError **error); /**************************************************************************** SETUP ****************************************************************************/ -ApplicationInterface *application_interface_new (void); -GType application_interface_get_type (void); - +ApplicationInterface *application_interface_new(void); +GType application_interface_get_type(void); G_END_DECLS diff --git a/src/extension/dbus/dbus-init.cpp b/src/extension/dbus/dbus-init.cpp index c83caacc1dac2d291209d2765fe2208700c70c78..df9c77b881e381472adf85f68bf94701ae66f681 100644 --- a/src/extension/dbus/dbus-init.cpp +++ b/src/extension/dbus/dbus-init.cpp @@ -17,73 +17,60 @@ #include // this is required so that giomm headers won't barf #undef DBUS_MESSAGE_TYPE_INVALID -#include "dbus-init.h" +#include +#include +#include #include "application-interface.h" #include "application-server-glue.h" - +#include "dbus-init.h" +#include "desktop.h" #include "document-interface.h" #include "document-server-glue.h" - -#include "inkscape.h" #include "document.h" -#include "desktop.h" #include "file.h" -#include "verbs.h" #include "helper/action.h" +#include "inkscape.h" +#include "verbs.h" -#include -#include -#include - - -namespace -{ - // This stores the bus name to use for this app instance. By default, it - // will be set to org.inkscape. However, users may provide other names by - // setting command-line parameters when starting Inkscape, so that more - // than one instance of Inkscape may be used by external scripts. - gchar *instance_bus_name = NULL; -} +namespace { +// This stores the bus name to use for this app instance. By default, it +// will be set to org.inkscape. However, users may provide other names by +// setting command-line parameters when starting Inkscape, so that more +// than one instance of Inkscape may be used by external scripts. +gchar *instance_bus_name = NULL; +} // namespace namespace Inkscape { namespace Extension { namespace Dbus { /* PRIVATE get a connection to the session bus */ -DBusGConnection * -dbus_get_connection() { - GError *error = NULL; - DBusGConnection *connection = dbus_g_bus_get (DBUS_BUS_SESSION, &error); - if (error) { - fprintf(stderr, "Failed to get connection"); - return NULL; - } - else - return connection; +DBusGConnection *dbus_get_connection() +{ + GError *error = NULL; + DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, &error); + if (error) { + fprintf(stderr, "Failed to get connection"); + return NULL; + } else + return connection; } /* PRIVATE create a proxy object for a bus.*/ -DBusGProxy * -dbus_get_proxy(DBusGConnection *connection) { - return dbus_g_proxy_new_for_name (connection, - DBUS_SERVICE_DBUS, - DBUS_PATH_DBUS, - DBUS_INTERFACE_DBUS); +DBusGProxy *dbus_get_proxy(DBusGConnection *connection) +{ + return dbus_g_proxy_new_for_name(connection, DBUS_SERVICE_DBUS, DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS); } /* PRIVATE register an object on a bus */ -static gpointer -dbus_register_object (DBusGConnection *connection, - DBusGProxy *proxy, - GType object_type, - const DBusGObjectInfo *info, - const gchar *path) +static gpointer dbus_register_object(DBusGConnection *connection, DBusGProxy *proxy, GType object_type, + const DBusGObjectInfo *info, const gchar *path) { - GObject *object = (GObject*)g_object_new (object_type, NULL); - dbus_g_object_type_install_info (object_type, info); - dbus_g_connection_register_g_object (connection, path, object); - return object; + GObject *object = (GObject *)g_object_new(object_type, NULL); + dbus_g_object_type_install_info(object_type, info); + dbus_g_connection_register_g_object(connection, path, object); + return object; } /* @@ -94,8 +81,7 @@ dbus_register_object (DBusGConnection *connection, * Desktop-associated DocumentInterfaces are named /org/inkscape/desktop_0, etc. * FIXME: This state of affairs probably needs tidying up at some point in the future. */ -static gchar * -dbus_register_document(Inkscape::ActionContext const & target) +static gchar *dbus_register_document(Inkscape::ActionContext const &target) { SPDocument *doc = target.getDocument(); g_assert(doc != NULL); @@ -105,18 +91,15 @@ dbus_register_document(Inkscape::ActionContext const & target) std::stringstream ss; ss << doc->serial(); name.append(ss.str()); - + DBusGConnection *connection = dbus_get_connection(); DBusGProxy *proxy = dbus_get_proxy(connection); // Has the document already been registered? if (!dbus_g_connection_lookup_g_object(connection, name.c_str())) { // No - register it - DocumentInterface *doc_interface = (DocumentInterface*) dbus_register_object (connection, - proxy, - TYPE_DOCUMENT_INTERFACE, - &dbus_glib_document_interface_object_info, - name.c_str()); + DocumentInterface *doc_interface = (DocumentInterface *)dbus_register_object( + connection, proxy, TYPE_DOCUMENT_INTERFACE, &dbus_glib_document_interface_object_info, name.c_str()); // Set the document info for this interface doc_interface->target = target; @@ -125,33 +108,26 @@ dbus_register_document(Inkscape::ActionContext const & target) } /* Initialize a Dbus service */ -void -init (void) +void init(void) { - if (instance_bus_name == NULL) { - // Set the bus name to the default - instance_bus_name = strdup("org.inkscape"); - } - - guint result; - GError *error = NULL; - DBusGConnection *connection; - DBusGProxy *proxy; - connection = dbus_get_connection(); - proxy = dbus_get_proxy(connection); - org_freedesktop_DBus_request_name (proxy, - instance_bus_name, - DBUS_NAME_FLAG_DO_NOT_QUEUE, &result, &error); - //create interface for application - dbus_register_object (connection, - proxy, - TYPE_APPLICATION_INTERFACE, - &dbus_glib_application_interface_object_info, - DBUS_APPLICATION_INTERFACE_PATH); + if (instance_bus_name == NULL) { + // Set the bus name to the default + instance_bus_name = strdup("org.inkscape"); + } + + guint result; + GError *error = NULL; + DBusGConnection *connection; + DBusGProxy *proxy; + connection = dbus_get_connection(); + proxy = dbus_get_proxy(connection); + org_freedesktop_DBus_request_name(proxy, instance_bus_name, DBUS_NAME_FLAG_DO_NOT_QUEUE, &result, &error); + // create interface for application + dbus_register_object(connection, proxy, TYPE_APPLICATION_INTERFACE, &dbus_glib_application_interface_object_info, + DBUS_APPLICATION_INTERFACE_PATH); } -gchar * -init_document (void) +gchar *init_document(void) { // This is for command-line use only g_assert(!INKSCAPE.use_gui()); @@ -162,74 +138,69 @@ init_document (void) return dbus_register_document(INKSCAPE.action_context_for_document(doc)); } -gchar * -init_active_document() +gchar *init_active_document() { SPDocument *doc = INKSCAPE.active_document(); if (!doc) { return NULL; } - + return dbus_register_document(INKSCAPE.active_action_context()); } -gchar * -dbus_init_desktop_interface (SPDesktop * dt) +gchar *dbus_init_desktop_interface(SPDesktop *dt) { DBusGConnection *connection; DBusGProxy *proxy; std::string name("/org/inkscape/desktop_"); - std::stringstream out; - out << dt->dkey; - name.append(out.str()); + std::stringstream out; + out << dt->dkey; + name.append(out.str()); - //printf("DKEY: %d\n, NUMBER %d\n NAME: %s\n", dt->dkey, dt->number, name.c_str()); + // printf("DKEY: %d\n, NUMBER %d\n NAME: %s\n", dt->dkey, dt->number, name.c_str()); connection = dbus_get_connection(); proxy = dbus_get_proxy(connection); if (!dbus_g_connection_lookup_g_object(connection, name.c_str())) { - DocumentInterface *doc_interface = (DocumentInterface*) dbus_register_object (connection, - proxy, - TYPE_DOCUMENT_INTERFACE, - &dbus_glib_document_interface_object_info, - name.c_str()); + DocumentInterface *doc_interface = (DocumentInterface *)dbus_register_object( + connection, proxy, TYPE_DOCUMENT_INTERFACE, &dbus_glib_document_interface_object_info, name.c_str()); // Set the document info for this interface doc_interface->target = Inkscape::ActionContext(dt); doc_interface->updates = TRUE; - dt->dbus_document_interface=doc_interface; + dt->dbus_document_interface = doc_interface; } return strdup(name.c_str()); } -gchar * -init_desktop (void) { - //this function will create a new desktop and call - //dbus_init_desktop_interface. - SPDesktop * dt = sp_file_new_default(); +gchar *init_desktop(void) +{ + // this function will create a new desktop and call + // dbus_init_desktop_interface. + SPDesktop *dt = sp_file_new_default(); std::string name("/org/inkscape/desktop_"); - std::stringstream out; - out << dt->dkey; - name.append(out.str()); + std::stringstream out; + out << dt->dkey; + name.append(out.str()); return strdup(name.c_str()); } -void -dbus_set_bus_name(gchar const * bus_name) +void dbus_set_bus_name(gchar const *bus_name) { g_assert(bus_name != NULL); g_assert(instance_bus_name == NULL); instance_bus_name = strdup(bus_name); } -gchar * -dbus_get_bus_name() +gchar *dbus_get_bus_name() { g_assert(instance_bus_name != NULL); return instance_bus_name; } -} } } /* namespace Inkscape::Extension::Dbus */ +} // namespace Dbus +} // namespace Extension +} // namespace Inkscape diff --git a/src/extension/dbus/dbus-init.h b/src/extension/dbus/dbus-init.h index 54a2819b151850cd3af57dacd7598d35d9c24a86..4f4c38b59f7a9a01c22b1fdb0fba3f201c3478b6 100644 --- a/src/extension/dbus/dbus-init.h +++ b/src/extension/dbus/dbus-init.h @@ -19,27 +19,29 @@ namespace Dbus { /** \brief Dbus stuff. For registering objects on the bus. */ -void init (void); +void init(void); -gchar * init_document (void); +gchar *init_document(void); -gchar * init_active_document (); +gchar *init_active_document(); -gchar * init_desktop (void); +gchar *init_desktop(void); -gchar * dbus_init_desktop_interface (SPDesktop * dt); +gchar *dbus_init_desktop_interface(SPDesktop *dt); /** Set the bus name to use. Default is "org.inkscape". This function should only be called once, before init(), if a non-default bus name is required. */ -void dbus_set_bus_name(gchar const * bus_name); +void dbus_set_bus_name(gchar const *bus_name); /** Get the bus name for this instance. Default is "org.inkscape". This function should only be called after init(). The returned gchar * is owned by this module and should not be freed. */ -gchar * dbus_get_bus_name(); +gchar *dbus_get_bus_name(); -} } } /* namespace Dbus, Extension, Inkscape */ +} // namespace Dbus +} // namespace Extension +} // namespace Inkscape #endif /* INKSCAPE_EXTENSION_DBUS_INIT_H__ */ diff --git a/src/extension/dbus/document-interface.cpp b/src/extension/dbus/document-interface.cpp index 06269a57b496aaacdda09a6ac914104227b0fdee..7482f27f7791bb2d5550f84e72a978918edf4fac 100644 --- a/src/extension/dbus/document-interface.cpp +++ b/src/extension/dbus/document-interface.cpp @@ -16,72 +16,61 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include #include #include -#include - //#include "2geom/svg-path-parser.h" //get_node_coordinates -#include "inkscape-application.h" // create_window() - #include "application-interface.h" #include "desktop-style.h" //sp_desktop_get_style #include "desktop.h" +#include "display/canvas-text.h" //text #include "document-interface.h" #include "document-undo.h" -#include "document.h" // getReprDoc() -#include "file.h" //IO -#include "inkscape.h" //inkscape_find_desktop_by_dkey, activate desktops -#include "layer-fns.h" //LPOS_BELOW -#include "layer-model.h" -#include "print.h" //IO -#include "selection-chemistry.h"// lots of selection functions -#include "selection.h" //selection struct -#include "style.h" //style_write -#include "text-editing.h" -#include "verbs.h" - -#include "helper/action-context.h" -#include "helper/action.h" //sp_action_perform - -#include "display/canvas-text.h" //text - +#include "document.h" // getReprDoc() #include "extension/output.h" //IO #include "extension/system.h" //IO - +#include "file.h" //IO +#include "helper/action-context.h" +#include "helper/action.h" //sp_action_perform +#include "inkscape-application.h" // create_window() +#include "inkscape.h" //inkscape_find_desktop_by_dkey, activate desktops +#include "layer-fns.h" //LPOS_BELOW +#include "layer-model.h" #include "live_effects/parameter/text.h" //text - #include "object/sp-ellipse.h" #include "object/sp-object.h" #include "object/sp-root.h" - -#include "util/units.h" - +#include "print.h" //IO +#include "selection-chemistry.h" // lots of selection functions +#include "selection.h" //selection struct +#include "style.h" //style_write +#include "text-editing.h" #include "ui/widget/canvas.h" // Disable drawing - +#include "util/units.h" +#include "verbs.h" #include "xml/repr.h" //sp_repr_document_new #if 0 -#include #include +#include #include #include #endif - - enum - { - OBJECT_MOVED_SIGNAL, - LAST_SIGNAL - }; - - static guint signals[LAST_SIGNAL] = { 0 }; +enum +{ + OBJECT_MOVED_SIGNAL, + LAST_SIGNAL +}; + +static guint signals[LAST_SIGNAL] = {0}; /**************************************************************************** HELPER / SHORTCUT FUNCTIONS ****************************************************************************/ -/* +/* * This function or the one below it translates the user input for an object * into Inkscapes internal representation. It is called by almost every * method so it should be as fast as possible. @@ -91,30 +80,26 @@ * If the internal representation changes (No more 'id' attributes) this is the * place to adjust things. */ -Inkscape::XML::Node * -get_repr_by_name (SPDocument *doc, gchar *name, GError **error) +Inkscape::XML::Node *get_repr_by_name(SPDocument *doc, gchar *name, GError **error) { /* ALTERNATIVE (is this faster if only repr is needed?) Inkscape::XML::Node *node = sp_repr_lookup_name((doc->root)->repr, name); */ - SPObject * obj = doc->getObjectById(name); - if (!obj) - { + SPObject *obj = doc->getObjectById(name); + if (!obj) { g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OBJECT, "Object '%s' not found in document.", name); return NULL; } - return obj->getRepr(); + return obj->getRepr(); } -/* +/* * See comment for get_repr_by_name, above. */ -SPObject * -get_object_by_name (SPDocument *doc, gchar *name, GError **error) +SPObject *get_object_by_name(SPDocument *doc, gchar *name, GError **error) { - SPObject * obj = doc->getObjectById(name); - if (!obj) - { + SPObject *obj = doc->getObjectById(name); + if (!obj) { g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OBJECT, "Object '%s' not found in document.", name); return NULL; } @@ -123,71 +108,67 @@ get_object_by_name (SPDocument *doc, gchar *name, GError **error) /* * Tests for NULL strings and throws an appropriate error. - * Every method that takes a string parameter (other than the + * Every method that takes a string parameter (other than the * name of an object, that's tested separately) should call this. */ -gboolean -dbus_check_string (gchar *string, GError ** error, const gchar * errorstr) +gboolean dbus_check_string(gchar *string, GError **error, const gchar *errorstr) { - if (string == NULL) - { + if (string == NULL) { g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OTHER, "%s", errorstr); return FALSE; } return TRUE; } -/* +/* * This is used to return object values to the user */ -const gchar * -get_name_from_object (SPObject * obj) +const gchar *get_name_from_object(SPObject *obj) { - return obj->getRepr()->attribute("id"); + return obj->getRepr()->attribute("id"); } /* * Some verbs (cut, paste) only work on the active layer. * This makes sure that the document that is about to receive a command is active. */ -void -desktop_ensure_active (SPDesktop* desk) { +void desktop_ensure_active(SPDesktop *desk) +{ if (desk != SP_ACTIVE_DESKTOP) - INKSCAPE.activate_desktop (desk); + INKSCAPE.activate_desktop(desk); return; } -gdouble -selection_get_center_x (Inkscape::Selection *sel){ +gdouble selection_get_center_x(Inkscape::Selection *sel) +{ Geom::OptRect box = sel->documentBounds(SPItem::GEOMETRIC_BBOX); return box ? box->midpoint()[Geom::X] : 0; } -gdouble -selection_get_center_y (Inkscape::Selection *sel){ +gdouble selection_get_center_y(Inkscape::Selection *sel) +{ Geom::OptRect box = sel->documentBounds(SPItem::GEOMETRIC_BBOX); return box ? box->midpoint()[Geom::Y] : 0; } -/* +/* * This function is used along with selection_restore to * take advantage of functionality provided by a selection * for a single object. * - * It saves the current selection and sets the selection to + * It saves the current selection and sets the selection to * the object specified. Any selection verb can be used on the - * object and then selection_restore is called, restoring the + * object and then selection_restore is called, restoring the * original selection. * * This should be mostly transparent to the user who need never * know we never bothered to implement it separately. Although * they might see the selection box flicker if used in a loop. */ -std::vector -selection_swap(Inkscape::Selection *sel, gchar *name, GError **error) +std::vector selection_swap(Inkscape::Selection *sel, gchar *name, GError **error) { - std::vector oldsel = std::vector(sel->objects().begin(), sel->objects().end()); - + std::vector oldsel = std::vector(sel->objects().begin(), sel->objects().end()); + sel->set(get_object_by_name(sel->layers()->getDocument(), name, error)); return oldsel; } @@ -195,8 +176,7 @@ selection_swap(Inkscape::Selection *sel, gchar *name, GError **error) /* * See selection_swap, above */ -void -selection_restore(Inkscape::Selection *sel, std::vector oldsel) +void selection_restore(Inkscape::Selection *sel, std::vector oldsel) { // ... setList used to work here sel->clear(); @@ -206,8 +186,7 @@ selection_restore(Inkscape::Selection *sel, std::vector oldsel) /* * Shortcut for creating a Node. */ -Inkscape::XML::Node * -dbus_create_node (SPDocument *doc, const gchar *type) +Inkscape::XML::Node *dbus_create_node(SPDocument *doc, const gchar *type) { Inkscape::XML::Document *xml_doc = doc->getReprDoc(); @@ -221,7 +200,8 @@ dbus_create_node (SPDocument *doc, const gchar *type) * There is probably a better way to do this (use the shape tools default styles) * but I'm not sure how. */ -gchar *finish_create_shape (DocumentInterface *doc_interface, GError ** /*error*/, Inkscape::XML::Node *newNode, gchar *desc) +gchar *finish_create_shape(DocumentInterface *doc_interface, GError ** /*error*/, Inkscape::XML::Node *newNode, + gchar *desc) { SPCSSAttr *style = NULL; if (doc_interface->target.getDesktop()) { @@ -231,16 +211,16 @@ gchar *finish_create_shape (DocumentInterface *doc_interface, GError ** /*error* Glib::ustring str; sp_repr_css_write_string(style, str); newNode->setAttributeOrRemoveIfEmpty("style", str); - } - else { - newNode->setAttribute("style", "fill:#0000ff;fill-opacity:1;stroke:#c900b9;stroke-width:0;stroke-miterlimit:0;stroke-opacity:1;stroke-dasharray:none"); + } else { + newNode->setAttribute("style", "fill:#0000ff;fill-opacity:1;stroke:#c900b9;stroke-width:0;stroke-miterlimit:0;" + "stroke-opacity:1;stroke-dasharray:none"); } doc_interface->target.getSelection()->layers()->currentLayer()->appendChildRepr(newNode); doc_interface->target.getSelection()->layers()->currentLayer()->updateRepr(); if (doc_interface->updates) { - Inkscape::DocumentUndo::done(doc_interface->target.getDocument(), 0, (gchar *)desc); + Inkscape::DocumentUndo::done(doc_interface->target.getDocument(), 0, (gchar *)desc); } return strdup(newNode->attribute("id")); @@ -254,18 +234,17 @@ gchar *finish_create_shape (DocumentInterface *doc_interface, GError ** /*error* * * document_interface_call_verb is similar but is called by the user. */ -gboolean -dbus_call_verb (DocumentInterface *doc_interface, int verbid, GError **error) -{ - SPDesktop *desk = doc_interface->target.getDesktop(); - if ( desk ) { - desktop_ensure_active (desk); +gboolean dbus_call_verb(DocumentInterface *doc_interface, int verbid, GError **error) +{ + SPDesktop *desk = doc_interface->target.getDesktop(); + if (desk) { + desktop_ensure_active(desk); } - Inkscape::Verb *verb = Inkscape::Verb::get( verbid ); - if ( verb ) { + Inkscape::Verb *verb = Inkscape::Verb::get(verbid); + if (verb) { SPAction *action = verb->get_action(doc_interface->target); - if ( action ) { - sp_action_perform( action, NULL ); + if (action) { + sp_action_perform(action, NULL); if (doc_interface->updates) Inkscape::DocumentUndo::done(doc_interface->target.getDocument(), verb->get_code(), verb->get_tip()); return TRUE; @@ -278,8 +257,7 @@ dbus_call_verb (DocumentInterface *doc_interface, int verbid, GError **error) /* * Check that the desktop is not NULL. If it is NULL, set the error to a useful message. */ -bool -ensure_desktop_valid(SPDesktop* desk, GError **error) +bool ensure_desktop_valid(SPDesktop *desk, GError **error) { if (desk) { return true; @@ -295,44 +273,30 @@ ensure_desktop_valid(SPDesktop* desk, GError **error) G_DEFINE_TYPE(DocumentInterface, document_interface, G_TYPE_OBJECT) -static void -document_interface_finalize (GObject *object) +static void document_interface_finalize(GObject *object) { - G_OBJECT_CLASS (document_interface_parent_class)->finalize (object); + G_OBJECT_CLASS(document_interface_parent_class)->finalize(object); } - -static void -document_interface_class_init (DocumentInterfaceClass *klass) +static void document_interface_class_init(DocumentInterfaceClass *klass) { - GObjectClass *object_class; - object_class = G_OBJECT_CLASS (klass); - object_class->finalize = document_interface_finalize; - signals[OBJECT_MOVED_SIGNAL] = - g_signal_new ("object_moved", - G_OBJECT_CLASS_TYPE (klass), - G_SIGNAL_RUN_LAST, - 0, - NULL, NULL, - g_cclosure_marshal_VOID__STRING, - G_TYPE_NONE, 1, G_TYPE_STRING); + GObjectClass *object_class; + object_class = G_OBJECT_CLASS(klass); + object_class->finalize = document_interface_finalize; + signals[OBJECT_MOVED_SIGNAL] = g_signal_new("object_moved", G_OBJECT_CLASS_TYPE(klass), G_SIGNAL_RUN_LAST, 0, NULL, + NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE, 1, G_TYPE_STRING); } -static void -document_interface_init (DocumentInterface *doc_interface) +static void document_interface_init(DocumentInterface *doc_interface) { doc_interface->target = Inkscape::ActionContext(); } - -DocumentInterface * -document_interface_new (void) +DocumentInterface *document_interface_new(void) { - return (DocumentInterface*)g_object_new (TYPE_DOCUMENT_INTERFACE, NULL); + return (DocumentInterface *)g_object_new(TYPE_DOCUMENT_INTERFACE, NULL); } - - /**************************************************************************** MISC FUNCTIONS ****************************************************************************/ @@ -343,18 +307,17 @@ gboolean document_interface_delete_all(DocumentInterface *doc_interface, GError return TRUE; } -gboolean -document_interface_call_verb (DocumentInterface *doc_interface, gchar *verbid, GError **error) +gboolean document_interface_call_verb(DocumentInterface *doc_interface, gchar *verbid, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); - if ( desk ) { - desktop_ensure_active (desk); + if (desk) { + desktop_ensure_active(desk); } - Inkscape::Verb *verb = Inkscape::Verb::getbyid( verbid ); - if ( verb ) { + Inkscape::Verb *verb = Inkscape::Verb::getbyid(verbid); + if (verb) { SPAction *action = verb->get_action(doc_interface->target); - if ( action ) { - sp_action_perform( action, NULL ); + if (action) { + sp_action_perform(action, NULL); if (doc_interface->updates) { Inkscape::DocumentUndo::done(doc_interface->target.getDocument(), verb->get_code(), verb->get_tip()); } @@ -365,28 +328,23 @@ document_interface_call_verb (DocumentInterface *doc_interface, gchar *verbid, G return FALSE; } - /**************************************************************************** CREATION FUNCTIONS ****************************************************************************/ -gchar* -document_interface_rectangle (DocumentInterface *doc_interface, int x, int y, - int width, int height, GError **error) +gchar *document_interface_rectangle(DocumentInterface *doc_interface, int x, int y, int width, int height, + GError **error) { - - Inkscape::XML::Node *newNode = dbus_create_node(doc_interface->target.getDocument(), "svg:rect"); - sp_repr_set_int(newNode, "x", x); //could also use newNode->setAttribute() + sp_repr_set_int(newNode, "x", x); // could also use newNode->setAttribute() sp_repr_set_int(newNode, "y", y); sp_repr_set_int(newNode, "width", width); sp_repr_set_int(newNode, "height", height); - return finish_create_shape (doc_interface, error, newNode, (gchar *)"create rectangle"); + return finish_create_shape(doc_interface, error, newNode, (gchar *)"create rectangle"); } -gchar* -document_interface_ellipse_center (DocumentInterface *doc_interface, int cx, int cy, - int rx, int ry, GError **error) +gchar *document_interface_ellipse_center(DocumentInterface *doc_interface, int cx, int cy, int rx, int ry, + GError **error) { Inkscape::XML::Node *newNode = dbus_create_node(doc_interface->target.getDocument(), "svg:path"); newNode->setAttribute("sodipodi:type", "arc"); @@ -394,13 +352,11 @@ document_interface_ellipse_center (DocumentInterface *doc_interface, int cx, int sp_repr_set_int(newNode, "sodipodi:cy", cy); sp_repr_set_int(newNode, "sodipodi:rx", rx); sp_repr_set_int(newNode, "sodipodi:ry", ry); - return finish_create_shape (doc_interface, error, newNode, (gchar *)"create circle"); + return finish_create_shape(doc_interface, error, newNode, (gchar *)"create circle"); } -gchar* -document_interface_polygon (DocumentInterface *doc_interface, int cx, int cy, - int radius, int rotation, int sides, - GError **error) +gchar *document_interface_polygon(DocumentInterface *doc_interface, int cx, int cy, int radius, int rotation, int sides, + GError **error) { gdouble rot = ((rotation / 180.0) * M_PI) - M_PI_2; Inkscape::XML::Node *newNode = dbus_create_node(doc_interface->target.getDocument(), "svg:path"); @@ -416,13 +372,11 @@ document_interface_polygon (DocumentInterface *doc_interface, int cx, int cy, sp_repr_set_svg_double(newNode, "sodipodi:arg2", rot); sp_repr_set_svg_double(newNode, "inkscape:rounded", 0); - return finish_create_shape (doc_interface, error, newNode, (gchar *)"create polygon"); + return finish_create_shape(doc_interface, error, newNode, (gchar *)"create polygon"); } -gchar* -document_interface_star (DocumentInterface *doc_interface, int cx, int cy, - int r1, int r2, int sides, gdouble rounded, - gdouble arg1, gdouble arg2, GError **error) +gchar *document_interface_star(DocumentInterface *doc_interface, int cx, int cy, int r1, int r2, int sides, + gdouble rounded, gdouble arg1, gdouble arg2, GError **error) { Inkscape::XML::Node *newNode = dbus_create_node(doc_interface->target.getDocument(), "svg:path"); newNode->setAttribute("inkscape:flatsided", "false"); @@ -437,33 +391,28 @@ document_interface_star (DocumentInterface *doc_interface, int cx, int cy, sp_repr_set_svg_double(newNode, "sodipodi:arg2", arg2); sp_repr_set_svg_double(newNode, "inkscape:rounded", rounded); - return finish_create_shape (doc_interface, error, newNode, (gchar *)"create star"); + return finish_create_shape(doc_interface, error, newNode, (gchar *)"create star"); } -gchar* -document_interface_ellipse (DocumentInterface *doc_interface, int x, int y, - int width, int height, GError **error) +gchar *document_interface_ellipse(DocumentInterface *doc_interface, int x, int y, int width, int height, GError **error) { - int rx = width/2; - int ry = height/2; - return document_interface_ellipse_center (doc_interface, x+rx, y+ry, rx, ry, error); + int rx = width / 2; + int ry = height / 2; + return document_interface_ellipse_center(doc_interface, x + rx, y + ry, rx, ry, error); } -gchar* -document_interface_line (DocumentInterface *doc_interface, int x, int y, - int x2, int y2, GError **error) +gchar *document_interface_line(DocumentInterface *doc_interface, int x, int y, int x2, int y2, GError **error) { Inkscape::XML::Node *newNode = dbus_create_node(doc_interface->target.getDocument(), "svg:path"); std::stringstream out; // Not sure why this works. - out << "m " << x << "," << y << " " << x2 - x << "," << y2 - y; + out << "m " << x << "," << y << " " << x2 - x << "," << y2 - y; newNode->setAttribute("d", out.str()); - return finish_create_shape (doc_interface, error, newNode, (gchar *)"create line"); + return finish_create_shape(doc_interface, error, newNode, (gchar *)"create line"); } -gchar* -document_interface_spiral (DocumentInterface *doc_interface, int cx, int cy, - int r, int revolutions, GError **error) +gchar *document_interface_spiral(DocumentInterface *doc_interface, int cx, int cy, int r, int revolutions, + GError **error) { Inkscape::XML::Node *newNode = dbus_create_node(doc_interface->target.getDocument(), "svg:path"); newNode->setAttribute("sodipodi:type", "spiral"); @@ -474,58 +423,55 @@ document_interface_spiral (DocumentInterface *doc_interface, int cx, int cy, sp_repr_set_int(newNode, "sodipodi:t0", 0); sp_repr_set_int(newNode, "sodipodi:argument", 0); sp_repr_set_int(newNode, "sodipodi:expansion", 1); - gchar * retval = finish_create_shape (doc_interface, error, newNode, (gchar *)"create spiral"); - //Makes sure there is no fill for spirals by default. - gchar* newString = g_strconcat(newNode->attribute("style"), ";fill:none", NULL); + gchar *retval = finish_create_shape(doc_interface, error, newNode, (gchar *)"create spiral"); + // Makes sure there is no fill for spirals by default. + gchar *newString = g_strconcat(newNode->attribute("style"), ";fill:none", NULL); newNode->setAttribute("style", newString); g_free(newString); return retval; } -gchar* -document_interface_text (DocumentInterface *doc_interface, int x, int y, gchar *text, GError **error) +gchar *document_interface_text(DocumentInterface *doc_interface, int x, int y, gchar *text, GError **error) { - - Inkscape::XML::Node *text_node = dbus_create_node(doc_interface->target.getDocument(), "svg:text"); + Inkscape::XML::Node *text_node = dbus_create_node(doc_interface->target.getDocument(), "svg:text"); sp_repr_set_int(text_node, "x", x); sp_repr_set_int(text_node, "y", y); - //just a workaround so i can get an spitem from the name - gchar *name = finish_create_shape (doc_interface, error, text_node, (gchar *)"create text"); - - SPItem* text_obj=(SPItem* )get_object_by_name(doc_interface->target.getDocument(), name, error); + // just a workaround so i can get an spitem from the name + gchar *name = finish_create_shape(doc_interface, error, text_node, (gchar *)"create text"); + + SPItem *text_obj = (SPItem *)get_object_by_name(doc_interface->target.getDocument(), name, error); sp_te_set_repr_text_multiline(text_obj, text); return name; } -gchar * -document_interface_image (DocumentInterface *doc_interface, int x, int y, gchar *filename, GError **error) +gchar *document_interface_image(DocumentInterface *doc_interface, int x, int y, gchar *filename, GError **error) { - gchar * uri = g_filename_to_uri (filename, FALSE, error); + gchar *uri = g_filename_to_uri(filename, FALSE, error); if (!uri) return FALSE; - + Inkscape::XML::Node *newNode = dbus_create_node(doc_interface->target.getDocument(), "svg:image"); sp_repr_set_int(newNode, "x", x); sp_repr_set_int(newNode, "y", y); newNode->setAttribute("xlink:href", uri); - + doc_interface->target.getSelection()->layers()->currentLayer()->appendChildRepr(newNode); doc_interface->target.getSelection()->layers()->currentLayer()->updateRepr(); if (doc_interface->updates) - Inkscape::DocumentUndo::done(doc_interface->target.getDocument(), 0, "Imported bitmap."); + Inkscape::DocumentUndo::done(doc_interface->target.getDocument(), 0, "Imported bitmap."); - //g_free(uri); + // g_free(uri); return strdup(newNode->attribute("id")); } gchar *document_interface_node(DocumentInterface *doc_interface, gchar *type, GError ** /*error*/) { - SPDocument * doc = doc_interface->target.getDocument(); + SPDocument *doc = doc_interface->target.getDocument(); Inkscape::XML::Document *xml_doc = doc->getReprDoc(); - Inkscape::XML::Node *newNode = xml_doc->createElement(type); + Inkscape::XML::Node *newNode = xml_doc->createElement(type); doc_interface->target.getSelection()->layers()->currentLayer()->appendChildRepr(newNode); doc_interface->target.getSelection()->layers()->currentLayer()->updateRepr(); @@ -540,105 +486,88 @@ gchar *document_interface_node(DocumentInterface *doc_interface, gchar *type, GE /**************************************************************************** ENVIRONMENT FUNCTIONS ****************************************************************************/ -gdouble -document_interface_document_get_width (DocumentInterface *doc_interface) +gdouble document_interface_document_get_width(DocumentInterface *doc_interface) { - return doc_interface->target.getDocument()->getWidth().value("px"); + return doc_interface->target.getDocument()->getWidth().value("px"); } -gdouble -document_interface_document_get_height (DocumentInterface *doc_interface) +gdouble document_interface_document_get_height(DocumentInterface *doc_interface) { - return doc_interface->target.getDocument()->getHeight().value("px"); + return doc_interface->target.getDocument()->getHeight().value("px"); } -gchar *document_interface_document_get_css(DocumentInterface *doc_interface, GError ** error) +gchar *document_interface_document_get_css(DocumentInterface *doc_interface, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); g_return_val_if_fail(ensure_desktop_valid(desk, error), NULL); SPCSSAttr *current = desk->current; Glib::ustring str; sp_repr_css_write_string(current, str); - return (str.empty() ? NULL : g_strdup (str.c_str())); + return (str.empty() ? NULL : g_strdup(str.c_str())); } -gboolean document_interface_document_merge_css(DocumentInterface *doc_interface, - gchar *stylestring, GError ** error) +gboolean document_interface_document_merge_css(DocumentInterface *doc_interface, gchar *stylestring, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); g_return_val_if_fail(ensure_desktop_valid(desk, error), FALSE); - SPCSSAttr * style = sp_repr_css_attr_new(); + SPCSSAttr *style = sp_repr_css_attr_new(); sp_repr_css_attr_add_from_string(style, stylestring); sp_desktop_set_style(desk, style); return TRUE; } -gboolean document_interface_document_set_css(DocumentInterface *doc_interface, - gchar *stylestring, GError ** error) +gboolean document_interface_document_set_css(DocumentInterface *doc_interface, gchar *stylestring, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); g_return_val_if_fail(ensure_desktop_valid(desk, error), FALSE); - SPCSSAttr * style = sp_repr_css_attr_new(); - sp_repr_css_attr_add_from_string (style, stylestring); - //Memory leak? + SPCSSAttr *style = sp_repr_css_attr_new(); + sp_repr_css_attr_add_from_string(style, stylestring); + // Memory leak? desk->current = style; return TRUE; } -gboolean -document_interface_document_resize_to_fit_selection (DocumentInterface *doc_interface, - GError **error) +gboolean document_interface_document_resize_to_fit_selection(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_FIT_CANVAS_TO_SELECTION, error); + return dbus_call_verb(doc_interface, SP_VERB_FIT_CANVAS_TO_SELECTION, error); } -gboolean -document_interface_document_set_display_area (DocumentInterface *doc_interface, - double x0, - double y0, - double x1, - double y1, - double border, - GError **error) +gboolean document_interface_document_set_display_area(DocumentInterface *doc_interface, double x0, double y0, double x1, + double y1, double border, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); g_return_val_if_fail(ensure_desktop_valid(desk, error), FALSE); - desk->set_display_area (Geom::Rect( Geom::Point(x0,y0), Geom::Point(x1,y1)), border, false ); + desk->set_display_area(Geom::Rect(Geom::Point(x0, y0), Geom::Point(x1, y1)), border, false); return TRUE; } - -GArray * -document_interface_document_get_display_area (DocumentInterface *doc_interface) +GArray *document_interface_document_get_display_area(DocumentInterface *doc_interface) { - SPDesktop *desk = doc_interface->target.getDesktop(); - if (!desk) { - return NULL; - } - Geom::Rect const d = desk->get_display_area().bounds(); - - GArray * dArr = g_array_new (TRUE, TRUE, sizeof(double)); + SPDesktop *desk = doc_interface->target.getDesktop(); + if (!desk) { + return NULL; + } + Geom::Rect const d = desk->get_display_area().bounds(); - double x0 = d.min()[Geom::X]; - double y0 = d.min()[Geom::Y]; - double x1 = d.max()[Geom::X]; - double y1 = d.max()[Geom::Y]; - g_array_append_val (dArr, x0); // - g_array_append_val (dArr, y0); - g_array_append_val (dArr, x1); - g_array_append_val (dArr, y1); - return dArr; + GArray *dArr = g_array_new(TRUE, TRUE, sizeof(double)); + double x0 = d.min()[Geom::X]; + double y0 = d.min()[Geom::Y]; + double x1 = d.max()[Geom::X]; + double y1 = d.max()[Geom::Y]; + g_array_append_val(dArr, x0); // + g_array_append_val(dArr, y0); + g_array_append_val(dArr, x1); + g_array_append_val(dArr, y1); + return dArr; } - /**************************************************************************** OBJECT FUNCTIONS ****************************************************************************/ -gboolean -document_interface_set_attribute (DocumentInterface *doc_interface, char *shape, - char *attribute, char *newval, GError **error) +gboolean document_interface_set_attribute(DocumentInterface *doc_interface, char *shape, char *attribute, char *newval, + GError **error) { Inkscape::XML::Node *newNode = get_repr_by_name(doc_interface->target.getDocument(), shape, error); @@ -647,63 +576,54 @@ document_interface_set_attribute (DocumentInterface *doc_interface, char *shape, */ if (!dbus_check_string(newval, error, "New value string was empty.")) return FALSE; - + if (!newNode) return FALSE; - + newNode->setAttribute(attribute, newval); return TRUE; } -gboolean -document_interface_set_int_attribute (DocumentInterface *doc_interface, - char *shape, char *attribute, - int newval, GError **error) +gboolean document_interface_set_int_attribute(DocumentInterface *doc_interface, char *shape, char *attribute, + int newval, GError **error) { - Inkscape::XML::Node *newNode = get_repr_by_name (doc_interface->target.getDocument(), shape, error); + Inkscape::XML::Node *newNode = get_repr_by_name(doc_interface->target.getDocument(), shape, error); if (!newNode) return FALSE; - - sp_repr_set_int (newNode, attribute, newval); + + sp_repr_set_int(newNode, attribute, newval); return TRUE; } - -gboolean -document_interface_set_double_attribute (DocumentInterface *doc_interface, - char *shape, char *attribute, - double newval, GError **error) +gboolean document_interface_set_double_attribute(DocumentInterface *doc_interface, char *shape, char *attribute, + double newval, GError **error) { - Inkscape::XML::Node *newNode = get_repr_by_name (doc_interface->target.getDocument(), shape, error); - - if (!dbus_check_string (attribute, error, "New value string was empty.")) + Inkscape::XML::Node *newNode = get_repr_by_name(doc_interface->target.getDocument(), shape, error); + + if (!dbus_check_string(attribute, error, "New value string was empty.")) return FALSE; if (!newNode) return FALSE; - - sp_repr_set_svg_double (newNode, attribute, newval); + + sp_repr_set_svg_double(newNode, attribute, newval); return TRUE; } -gchar * -document_interface_get_attribute (DocumentInterface *doc_interface, char *shape, - char *attribute, GError **error) +gchar *document_interface_get_attribute(DocumentInterface *doc_interface, char *shape, char *attribute, GError **error) { Inkscape::XML::Node *newNode = get_repr_by_name(doc_interface->target.getDocument(), shape, error); - if (!dbus_check_string (attribute, error, "Attribute name empty.")) + if (!dbus_check_string(attribute, error, "Attribute name empty.")) return NULL; if (!newNode) return NULL; - + return g_strdup(newNode->attribute(attribute)); } -gboolean -document_interface_move (DocumentInterface *doc_interface, gchar *name, gdouble x, - gdouble y, GError **error) +gboolean document_interface_move(DocumentInterface *doc_interface, gchar *name, gdouble x, gdouble y, GError **error) { - std::vector oldsel = selection_swap(doc_interface->target.getSelection(), name, error); + std::vector oldsel = selection_swap(doc_interface->target.getSelection(), name, error); if (oldsel.empty()) return FALSE; doc_interface->target.getSelection()->move(x, 0 - y); @@ -711,143 +631,129 @@ document_interface_move (DocumentInterface *doc_interface, gchar *name, gdouble return TRUE; } -gboolean -document_interface_move_to (DocumentInterface *doc_interface, gchar *name, gdouble x, - gdouble y, GError **error) +gboolean document_interface_move_to(DocumentInterface *doc_interface, gchar *name, gdouble x, gdouble y, GError **error) { - std::vector oldsel = selection_swap(doc_interface->target.getSelection(), name, error); + std::vector oldsel = selection_swap(doc_interface->target.getSelection(), name, error); if (oldsel.empty()) return FALSE; - Inkscape::Selection * sel = doc_interface->target.getSelection(); - doc_interface->target.getSelection()->move(x - selection_get_center_x(sel), - 0 - (y - selection_get_center_y(sel))); + Inkscape::Selection *sel = doc_interface->target.getSelection(); + doc_interface->target.getSelection()->move(x - selection_get_center_x(sel), 0 - (y - selection_get_center_y(sel))); selection_restore(doc_interface->target.getSelection(), oldsel); return TRUE; } -gboolean -document_interface_object_to_path (DocumentInterface *doc_interface, - char *shape, GError **error) +gboolean document_interface_object_to_path(DocumentInterface *doc_interface, char *shape, GError **error) { - std::vector oldsel = selection_swap(doc_interface->target.getSelection(), shape, error); + std::vector oldsel = selection_swap(doc_interface->target.getSelection(), shape, error); if (oldsel.empty()) return FALSE; - dbus_call_verb (doc_interface, SP_VERB_OBJECT_TO_CURVE, error); + dbus_call_verb(doc_interface, SP_VERB_OBJECT_TO_CURVE, error); selection_restore(doc_interface->target.getSelection(), oldsel); return TRUE; } -gchar * -document_interface_get_path (DocumentInterface *doc_interface, char *pathname, GError **error) +gchar *document_interface_get_path(DocumentInterface *doc_interface, char *pathname, GError **error) { Inkscape::XML::Node *node = get_repr_by_name(doc_interface->target.getDocument(), pathname, error); - + if (!node) return NULL; - - if (node->attribute("d") == NULL) - { + + if (node->attribute("d") == NULL) { g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OBJECT, "Object is not a path."); return NULL; } return strdup(node->attribute("d")); } -gboolean -document_interface_transform (DocumentInterface *doc_interface, gchar *shape, - gchar *transformstr, GError **error) +gboolean document_interface_transform(DocumentInterface *doc_interface, gchar *shape, gchar *transformstr, + GError **error) { - //FIXME: This should merge transformations. + // FIXME: This should merge transformations. gchar trans[] = "transform"; - document_interface_set_attribute (doc_interface, shape, trans, transformstr, error); + document_interface_set_attribute(doc_interface, shape, trans, transformstr, error); return TRUE; } -gchar * -document_interface_get_css (DocumentInterface *doc_interface, gchar *shape, - GError **error) +gchar *document_interface_get_css(DocumentInterface *doc_interface, gchar *shape, GError **error) { gchar style[] = "style"; - return document_interface_get_attribute (doc_interface, shape, style, error); + return document_interface_get_attribute(doc_interface, shape, style, error); } -gboolean -document_interface_modify_css (DocumentInterface *doc_interface, gchar *shape, - gchar *cssattrb, gchar *newval, GError **error) +gboolean document_interface_modify_css(DocumentInterface *doc_interface, gchar *shape, gchar *cssattrb, gchar *newval, + GError **error) { // Doesn't like non-variable strings for some reason. gchar style[] = "style"; Inkscape::XML::Node *node = get_repr_by_name(doc_interface->target.getDocument(), shape, error); - - if (!dbus_check_string (cssattrb, error, "Attribute string empty.")) + + if (!dbus_check_string(cssattrb, error, "Attribute string empty.")) return FALSE; if (!node) return FALSE; - - SPCSSAttr * oldstyle = sp_repr_css_attr (node, style); + + SPCSSAttr *oldstyle = sp_repr_css_attr(node, style); sp_repr_css_set_property(oldstyle, cssattrb, newval); Glib::ustring str; - sp_repr_css_write_string (oldstyle, str); - node->setAttributeOrRemoveIfEmpty (style, str); + sp_repr_css_write_string(oldstyle, str); + node->setAttributeOrRemoveIfEmpty(style, str); return TRUE; } -gboolean -document_interface_merge_css (DocumentInterface *doc_interface, gchar *shape, - gchar *stylestring, GError **error) +gboolean document_interface_merge_css(DocumentInterface *doc_interface, gchar *shape, gchar *stylestring, + GError **error) { gchar style[] = "style"; - + Inkscape::XML::Node *node = get_repr_by_name(doc_interface->target.getDocument(), shape, error); - - if (!dbus_check_string (stylestring, error, "Style string empty.")) + + if (!dbus_check_string(stylestring, error, "Style string empty.")) return FALSE; if (!node) return FALSE; - - SPCSSAttr * newstyle = sp_repr_css_attr_new(); - sp_repr_css_attr_add_from_string (newstyle, stylestring); - SPCSSAttr * oldstyle = sp_repr_css_attr (node, style); + SPCSSAttr *newstyle = sp_repr_css_attr_new(); + sp_repr_css_attr_add_from_string(newstyle, stylestring); + + SPCSSAttr *oldstyle = sp_repr_css_attr(node, style); sp_repr_css_merge(oldstyle, newstyle); Glib::ustring str; - sp_repr_css_write_string (oldstyle, str); - node->setAttributeOrRemoveIfEmpty (style, str); - + sp_repr_css_write_string(oldstyle, str); + node->setAttributeOrRemoveIfEmpty(style, str); + return TRUE; } -gboolean -document_interface_set_color (DocumentInterface *doc_interface, gchar *shape, - int r, int g, int b, gboolean fill, GError **error) +gboolean document_interface_set_color(DocumentInterface *doc_interface, gchar *shape, int r, int g, int b, + gboolean fill, GError **error) { gchar style[15]; - if (r<0 || r>255 || g<0 || g>255 || b<0 || b>255) - { - g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OTHER, "Given (%d,%d,%d). All values must be between 0-255 inclusive.", r, g, b); + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { + g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OTHER, + "Given (%d,%d,%d). All values must be between 0-255 inclusive.", r, g, b); return FALSE; } - + if (fill) snprintf(style, 15, "fill:#%.2x%.2x%.2x", r, g, b); else snprintf(style, 15, "stroke:#%.2x%.2x%.2x", r, g, b); - + if (strcmp(shape, "document") == 0) - return document_interface_document_merge_css (doc_interface, style, error); - - return document_interface_merge_css (doc_interface, shape, style, error); + return document_interface_document_merge_css(doc_interface, style, error); + + return document_interface_merge_css(doc_interface, shape, style, error); } -gboolean -document_interface_move_to_layer (DocumentInterface *doc_interface, gchar *shape, - gchar *layerstr, GError **error) +gboolean document_interface_move_to_layer(DocumentInterface *doc_interface, gchar *shape, gchar *layerstr, + GError **error) { - std::vector oldsel = selection_swap(doc_interface->target.getSelection(), shape, error); + std::vector oldsel = selection_swap(doc_interface->target.getSelection(), shape, error); if (oldsel.empty()) return FALSE; - + document_interface_selection_move_to_layer(doc_interface, layerstr, error); selection_restore(doc_interface->target.getSelection(), oldsel); return TRUE; @@ -855,81 +761,66 @@ document_interface_move_to_layer (DocumentInterface *doc_interface, gchar *shape GArray *document_interface_get_node_coordinates(DocumentInterface * /*doc_interface*/, gchar * /*shape*/) { - //FIXME: Needs lot's of work. -/* - Inkscape::XML::Node *shapenode = get_repr_by_name (doc_interface->target.getDocument(), shape, error); - if (shapenode == NULL || shapenode->attribute("d") == NULL) { - return FALSE; - } - char * path = strdup(shapenode->attribute("d")); - printf("PATH: %s\n", path); - - Geom::parse_svg_path (path); - return NULL; - */ + // FIXME: Needs lot's of work. + /* + Inkscape::XML::Node *shapenode = get_repr_by_name (doc_interface->target.getDocument(), shape, error); + if (shapenode == NULL || shapenode->attribute("d") == NULL) { + return FALSE; + } + char * path = strdup(shapenode->attribute("d")); + printf("PATH: %s\n", path); + + Geom::parse_svg_path (path); + return NULL; + */ return NULL; } - -gboolean -document_interface_set_text (DocumentInterface *doc_interface, gchar *name, gchar *text, GError **error) +gboolean document_interface_set_text(DocumentInterface *doc_interface, gchar *name, gchar *text, GError **error) { - - SPItem* text_obj=(SPItem* )get_object_by_name(doc_interface->target.getDocument(), name, error); - //TODO verify object type - if (!text_obj) - return FALSE; - sp_te_set_repr_text_multiline(text_obj, text); - return TRUE; - + SPItem *text_obj = (SPItem *)get_object_by_name(doc_interface->target.getDocument(), name, error); + // TODO verify object type + if (!text_obj) + return FALSE; + sp_te_set_repr_text_multiline(text_obj, text); + return TRUE; } - - -gboolean -document_interface_text_apply_style (DocumentInterface *doc_interface, gchar *name, - int start_pos, int end_pos, gchar *style, gchar *styleval, - GError **error) +gboolean document_interface_text_apply_style(DocumentInterface *doc_interface, gchar *name, int start_pos, int end_pos, + gchar *style, gchar *styleval, GError **error) { + SPItem *text_obj = (SPItem *)get_object_by_name(doc_interface->target.getDocument(), name, error); - SPItem* text_obj=(SPItem* )get_object_by_name(doc_interface->target.getDocument(), name, error); + // void sp_te_apply_style(SPItem *text, Inkscape::Text::Layout::iterator const &start, + // Inkscape::Text::Layout::iterator const &end, SPCSSAttr const *css) + // TODO verify object type + if (!text_obj) + return FALSE; + Inkscape::Text::Layout const *layout = te_get_layout(text_obj); + Inkscape::Text::Layout::iterator start = layout->charIndexToIterator(start_pos); + Inkscape::Text::Layout::iterator end = layout->charIndexToIterator(end_pos); - //void sp_te_apply_style(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPCSSAttr const *css) - //TODO verify object type - if (!text_obj) - return FALSE; - Inkscape::Text::Layout const *layout = te_get_layout(text_obj); - Inkscape::Text::Layout::iterator start = layout->charIndexToIterator (start_pos); - Inkscape::Text::Layout::iterator end = layout->charIndexToIterator (end_pos); - - SPCSSAttr *css = sp_repr_css_attr_new(); - sp_repr_css_set_property(css, style, styleval); - - sp_te_apply_style(text_obj, - start, - end, - css); - return TRUE; - -} + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, style, styleval); + sp_te_apply_style(text_obj, start, end, css); + return TRUE; +} /**************************************************************************** FILE I/O FUNCTIONS ****************************************************************************/ -gboolean -document_interface_save (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_save(DocumentInterface *doc_interface, GError **error) { - SPDocument * doc = doc_interface->target.getDocument(); + SPDocument *doc = doc_interface->target.getDocument(); printf("1: %s\n2: %s\n3: %s\n", doc->getDocumentURI(), doc->getDocumentBase(), doc->getDocumentName()); if (doc->getDocumentURI()) - return document_interface_save_as (doc_interface, doc->getDocumentURI(), error); + return document_interface_save_as(doc_interface, doc->getDocumentURI(), error); return FALSE; } -gboolean document_interface_load(DocumentInterface *doc_interface, - gchar *filename, GError ** /*error*/) +gboolean document_interface_load(DocumentInterface *doc_interface, gchar *filename, GError ** /*error*/) { if (!filename) { return false; @@ -942,46 +833,43 @@ gboolean document_interface_load(DocumentInterface *doc_interface, Glib::RefPtr file = Gio::File::create_for_path(filename); - ConcreteInkscapeApplication* app = &(ConcreteInkscapeApplication::get_instance()); + ConcreteInkscapeApplication *app = + &(ConcreteInkscapeApplication::get_instance()); app->create_window(file); if (doc_interface->updates) { - Inkscape::DocumentUndo::done(doc_interface->target.getDocument(), SP_VERB_FILE_OPEN, "Opened File"); + Inkscape::DocumentUndo::done(doc_interface->target.getDocument(), SP_VERB_FILE_OPEN, "Opened File"); } return TRUE; } -gchar * -document_interface_import (DocumentInterface *doc_interface, - gchar *filename, GError **error) +gchar *document_interface_import(DocumentInterface *doc_interface, gchar *filename, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); if (desk) { desktop_ensure_active(desk); } const Glib::ustring file(filename); - SPDocument * doc = doc_interface->target.getDocument(); + SPDocument *doc = doc_interface->target.getDocument(); SPObject *new_obj = NULL; new_obj = file_import(doc, file, NULL); return strdup(new_obj->getRepr()->attribute("id")); } -gboolean -document_interface_save_as (DocumentInterface *doc_interface, - const gchar *filename, GError **error) +gboolean document_interface_save_as(DocumentInterface *doc_interface, const gchar *filename, GError **error) { // FIXME: Isn't there a verb we can use for this instead? - SPDocument * doc = doc_interface->target.getDocument(); + SPDocument *doc = doc_interface->target.getDocument(); - if (!doc || strlen(filename)<1) { //Safety check + if (!doc || strlen(filename) < 1) { // Safety check return false; } try { - Inkscape::Extension::save(NULL, doc, filename, - false, false, true, Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS); + Inkscape::Extension::save(NULL, doc, filename, false, false, true, + Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS); } catch (...) { // FIXME: catch ... is not usually a great idea, why is it needed here? return false; @@ -992,7 +880,7 @@ document_interface_save_as (DocumentInterface *doc_interface, gboolean document_interface_mark_as_unmodified(DocumentInterface *doc_interface, GError ** /*error*/) { - SPDocument * doc = doc_interface->target.getDocument(); + SPDocument *doc = doc_interface->target.getDocument(); if (doc) { doc->setModifiedSinceSave(FALSE); } @@ -1000,12 +888,12 @@ gboolean document_interface_mark_as_unmodified(DocumentInterface *doc_interface, } /* -gboolean +gboolean document_interface_print_to_file (DocumentInterface *doc_interface, GError **error) { SPDocument * doc = doc_interface->target.getDocument(); sp_print_document_to_file (doc, g_strdup("/home/soren/test.pdf")); - + return TRUE; } */ @@ -1013,40 +901,34 @@ document_interface_print_to_file (DocumentInterface *doc_interface, GError **err PROGRAM CONTROL FUNCTIONS ****************************************************************************/ -gboolean -document_interface_close (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_close(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_FILE_CLOSE_VIEW, error); + return dbus_call_verb(doc_interface, SP_VERB_FILE_CLOSE_VIEW, error); } -gboolean -document_interface_exit (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_exit(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_FILE_QUIT, error); + return dbus_call_verb(doc_interface, SP_VERB_FILE_QUIT, error); } -gboolean -document_interface_undo (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_undo(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_EDIT_UNDO, error); + return dbus_call_verb(doc_interface, SP_VERB_EDIT_UNDO, error); } -gboolean -document_interface_redo (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_redo(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_EDIT_REDO, error); + return dbus_call_verb(doc_interface, SP_VERB_EDIT_REDO, error); } - - /**************************************************************************** - UPDATE FUNCTIONS + UPDATE FUNCTIONS FIXME: This would work better by adding a flag to SPDesktop to prevent updating but that would be very intrusive so for now there is a workaround. Need to make sure it plays well with verbs because they are used so much. ****************************************************************************/ -void document_interface_pause_updates(DocumentInterface *doc_interface, GError ** error) +void document_interface_pause_updates(DocumentInterface *doc_interface, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); g_return_if_fail(ensure_desktop_valid(desk, error)); @@ -1054,17 +936,17 @@ void document_interface_pause_updates(DocumentInterface *doc_interface, GError * desk->getCanvas()->set_drawing_disabled(true); } -void document_interface_resume_updates(DocumentInterface *doc_interface, GError ** error) +void document_interface_resume_updates(DocumentInterface *doc_interface, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); g_return_if_fail(ensure_desktop_valid(desk, error)); doc_interface->updates = TRUE; desk->getCanvas()->set_drawing_disabled(false); - //FIXME: use better verb than rect. - Inkscape::DocumentUndo::done(doc_interface->target.getDocument(), SP_VERB_CONTEXT_RECT, "Multiple actions"); + // FIXME: use better verb than rect. + Inkscape::DocumentUndo::done(doc_interface->target.getDocument(), SP_VERB_CONTEXT_RECT, "Multiple actions"); } -void document_interface_update(DocumentInterface *doc_interface, GError ** error) +void document_interface_update(DocumentInterface *doc_interface, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); g_return_if_fail(ensure_desktop_valid(desk, error)); @@ -1076,7 +958,7 @@ void document_interface_update(DocumentInterface *doc_interface, GError ** error desk->disableInteraction(); doc->getRoot()->uflags = FALSE; doc->getRoot()->mflags = FALSE; - //Inkscape::DocumentUndo::done(doc, SP_VERB_CONTEXT_RECT, "Multiple actions"); + // Inkscape::DocumentUndo::done(doc, SP_VERB_CONTEXT_RECT, "Multiple actions"); } /**************************************************************************** @@ -1085,12 +967,12 @@ void document_interface_update(DocumentInterface *doc_interface, GError ** error gboolean document_interface_selection_get(DocumentInterface *doc_interface, char ***out, GError ** /*error*/) { - Inkscape::Selection * sel = doc_interface->target.getSelection(); + Inkscape::Selection *sel = doc_interface->target.getSelection(); auto oldsel = sel->objects(); int size = oldsel.size(); - *out = g_new0 (char *, size + 1); + *out = g_new0(char *, size + 1); int i = 0; for (auto iter = oldsel.begin(); iter != oldsel.end(); ++iter) { @@ -1102,46 +984,41 @@ gboolean document_interface_selection_get(DocumentInterface *doc_interface, char return TRUE; } -gboolean -document_interface_selection_add (DocumentInterface *doc_interface, char *name, GError **error) +gboolean document_interface_selection_add(DocumentInterface *doc_interface, char *name, GError **error) { - SPObject * obj = get_object_by_name(doc_interface->target.getDocument(), name, error); + SPObject *obj = get_object_by_name(doc_interface->target.getDocument(), name, error); if (!obj) return FALSE; - + Inkscape::Selection *selection = doc_interface->target.getSelection(); selection->add(obj); return TRUE; } -gboolean -document_interface_selection_add_list (DocumentInterface *doc_interface, - char **names, GError **error) +gboolean document_interface_selection_add_list(DocumentInterface *doc_interface, char **names, GError **error) { int i; - for (i=0;names[i] != NULL;i++) { - document_interface_selection_add(doc_interface, names[i], error); + for (i = 0; names[i] != NULL; i++) { + document_interface_selection_add(doc_interface, names[i], error); } return TRUE; } gboolean document_interface_selection_set(DocumentInterface *doc_interface, char *name, GError ** /*error*/) { - SPDocument * doc = doc_interface->target.getDocument(); + SPDocument *doc = doc_interface->target.getDocument(); Inkscape::Selection *selection = doc_interface->target.getSelection(); selection->set(doc->getObjectById(name)); return TRUE; } -gboolean -document_interface_selection_set_list (DocumentInterface *doc_interface, - gchar **names, GError **error) +gboolean document_interface_selection_set_list(DocumentInterface *doc_interface, gchar **names, GError **error) { doc_interface->target.getSelection()->clear(); int i; - for (i=0;names[i] != NULL;i++) { - document_interface_selection_add(doc_interface, names[i], error); + for (i = 0; names[i] != NULL; i++) { + document_interface_selection_add(doc_interface, names[i], error); } return TRUE; } @@ -1153,10 +1030,9 @@ gboolean document_interface_selection_rotate(DocumentInterface *doc_interface, i return TRUE; } -gboolean -document_interface_selection_delete (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_selection_delete(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_EDIT_DELETE, error); + return dbus_call_verb(doc_interface, SP_VERB_EDIT_DELETE, error); } gboolean document_interface_selection_clear(DocumentInterface *doc_interface, GError ** /*error*/) @@ -1165,103 +1041,91 @@ gboolean document_interface_selection_clear(DocumentInterface *doc_interface, GE return TRUE; } -gboolean -document_interface_select_all (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_select_all(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_EDIT_SELECT_ALL, error); + return dbus_call_verb(doc_interface, SP_VERB_EDIT_SELECT_ALL, error); } -gboolean -document_interface_select_all_in_all_layers(DocumentInterface *doc_interface, - GError **error) +gboolean document_interface_select_all_in_all_layers(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_EDIT_SELECT_ALL_IN_ALL_LAYERS, error); + return dbus_call_verb(doc_interface, SP_VERB_EDIT_SELECT_ALL_IN_ALL_LAYERS, error); } -gboolean document_interface_selection_box(DocumentInterface * /*doc_interface*/, int /*x*/, int /*y*/, - int /*x2*/, int /*y2*/, gboolean /*replace*/, - GError ** /*error*/) +gboolean document_interface_selection_box(DocumentInterface * /*doc_interface*/, int /*x*/, int /*y*/, int /*x2*/, + int /*y2*/, gboolean /*replace*/, GError ** /*error*/) { - //FIXME: implement. + // FIXME: implement. return FALSE; } -gboolean -document_interface_selection_invert (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_selection_invert(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_EDIT_INVERT, error); + return dbus_call_verb(doc_interface, SP_VERB_EDIT_INVERT, error); } -gboolean -document_interface_selection_group (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_selection_group(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_SELECTION_GROUP, error); + return dbus_call_verb(doc_interface, SP_VERB_SELECTION_GROUP, error); } -gboolean -document_interface_selection_ungroup (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_selection_ungroup(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_SELECTION_UNGROUP, error); + return dbus_call_verb(doc_interface, SP_VERB_SELECTION_UNGROUP, error); } - -gboolean -document_interface_selection_cut (DocumentInterface *doc_interface, GError **error) + +gboolean document_interface_selection_cut(DocumentInterface *doc_interface, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); g_return_val_if_fail(ensure_desktop_valid(desk, error), FALSE); - return dbus_call_verb (doc_interface, SP_VERB_EDIT_CUT, error); + return dbus_call_verb(doc_interface, SP_VERB_EDIT_CUT, error); } -gboolean -document_interface_selection_copy (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_selection_copy(DocumentInterface *doc_interface, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); g_return_val_if_fail(ensure_desktop_valid(desk, error), FALSE); - return dbus_call_verb (doc_interface, SP_VERB_EDIT_COPY, error); + return dbus_call_verb(doc_interface, SP_VERB_EDIT_COPY, error); } -gboolean -document_interface_selection_paste (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_selection_paste(DocumentInterface *doc_interface, GError **error) { SPDesktop *desk = doc_interface->target.getDesktop(); g_return_val_if_fail(ensure_desktop_valid(desk, error), FALSE); - return dbus_call_verb (doc_interface, SP_VERB_EDIT_PASTE, error); + return dbus_call_verb(doc_interface, SP_VERB_EDIT_PASTE, error); } gboolean document_interface_selection_scale(DocumentInterface *doc_interface, gdouble grow, GError ** /*error*/) { Inkscape::Selection *selection = doc_interface->target.getSelection(); - if (!selection) - { + if (!selection) { return FALSE; - } + } selection->scale(grow); return TRUE; } gboolean document_interface_selection_move(DocumentInterface *doc_interface, gdouble x, gdouble y, GError ** /*error*/) { - doc_interface->target.getSelection()->move(x, 0 - y); //switching coordinate systems. + doc_interface->target.getSelection()->move(x, 0 - y); // switching coordinate systems. return TRUE; } -gboolean document_interface_selection_move_to(DocumentInterface *doc_interface, gdouble x, gdouble y, GError ** /*error*/) +gboolean document_interface_selection_move_to(DocumentInterface *doc_interface, gdouble x, gdouble y, + GError ** /*error*/) { - Inkscape::Selection * sel = doc_interface->target.getSelection(); + Inkscape::Selection *sel = doc_interface->target.getSelection(); Geom::OptRect sel_bbox = sel->visualBounds(); if (sel_bbox) { - Geom::Point m( x - selection_get_center_x(sel) , 0 - (y - selection_get_center_y(sel)) ); + Geom::Point m(x - selection_get_center_x(sel), 0 - (y - selection_get_center_y(sel))); sel->moveRelative(m, true); } return TRUE; } -//FIXME: does not paste in new layer. +// FIXME: does not paste in new layer. // This needs to use lower level cut_impl and paste_impl (messy) // See the built-in sp_selection_to_next_layer and duplicate. -gboolean -document_interface_selection_move_to_layer (DocumentInterface *doc_interface, - gchar *layerstr, GError **error) +gboolean document_interface_selection_move_to_layer(DocumentInterface *doc_interface, gchar *layerstr, GError **error) { SPDesktop *dt = doc_interface->target.getDesktop(); g_return_val_if_fail(ensure_desktop_valid(dt, error), FALSE); @@ -1273,81 +1137,73 @@ document_interface_selection_move_to_layer (DocumentInterface *doc_interface, return FALSE; SPObject *next = get_object_by_name(doc_interface->target.getDocument(), layerstr, error); - + if (!next) return FALSE; if (strcmp("layer", (next->getRepr())->attribute("inkscape:groupmode")) == 0) { - dt->selection->cut(); doc_interface->target.getSelection()->layers()->setCurrentLayer(next); sp_selection_paste(dt, TRUE); - } + } return TRUE; } -GArray * -document_interface_selection_get_center (DocumentInterface *doc_interface) +GArray *document_interface_selection_get_center(DocumentInterface *doc_interface) { - Inkscape::Selection * sel = doc_interface->target.getSelection(); + Inkscape::Selection *sel = doc_interface->target.getSelection(); - if (sel) - { + if (sel) { gdouble x = selection_get_center_x(sel); gdouble y = selection_get_center_y(sel); - GArray * intArr = g_array_new (TRUE, TRUE, sizeof(double)); + GArray *intArr = g_array_new(TRUE, TRUE, sizeof(double)); - g_array_append_val (intArr, x); - g_array_append_val (intArr, y); + g_array_append_val(intArr, x); + g_array_append_val(intArr, y); return intArr; } return NULL; } -gboolean -document_interface_selection_to_path (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_selection_to_path(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_OBJECT_TO_CURVE, error); + return dbus_call_verb(doc_interface, SP_VERB_OBJECT_TO_CURVE, error); } - -gboolean -document_interface_selection_combine (DocumentInterface *doc_interface, gchar *cmd, char ***newpaths, - GError **error) +gboolean document_interface_selection_combine(DocumentInterface *doc_interface, gchar *cmd, char ***newpaths, + GError **error) { if (strcmp(cmd, "union") == 0) - dbus_call_verb (doc_interface, SP_VERB_SELECTION_UNION, error); + dbus_call_verb(doc_interface, SP_VERB_SELECTION_UNION, error); else if (strcmp(cmd, "intersection") == 0) - dbus_call_verb (doc_interface, SP_VERB_SELECTION_INTERSECT, error); + dbus_call_verb(doc_interface, SP_VERB_SELECTION_INTERSECT, error); else if (strcmp(cmd, "difference") == 0) - dbus_call_verb (doc_interface, SP_VERB_SELECTION_DIFF, error); + dbus_call_verb(doc_interface, SP_VERB_SELECTION_DIFF, error); else if (strcmp(cmd, "exclusion") == 0) - dbus_call_verb (doc_interface, SP_VERB_SELECTION_SYMDIFF, error); + dbus_call_verb(doc_interface, SP_VERB_SELECTION_SYMDIFF, error); else if (strcmp(cmd, "division") == 0) - dbus_call_verb (doc_interface, SP_VERB_SELECTION_CUT, error); + dbus_call_verb(doc_interface, SP_VERB_SELECTION_CUT, error); else { g_set_error(error, INKSCAPE_ERROR, INKSCAPE_ERROR_OTHER, "Operation command not recognised"); return FALSE; } - return document_interface_selection_get (doc_interface, newpaths, error); + return document_interface_selection_get(doc_interface, newpaths, error); } -gboolean -document_interface_selection_change_level (DocumentInterface *doc_interface, gchar *cmd, - GError **error) +gboolean document_interface_selection_change_level(DocumentInterface *doc_interface, gchar *cmd, GError **error) { if (strcmp(cmd, "raise") == 0) - return dbus_call_verb (doc_interface, SP_VERB_SELECTION_RAISE, error); + return dbus_call_verb(doc_interface, SP_VERB_SELECTION_RAISE, error); if (strcmp(cmd, "lower") == 0) - return dbus_call_verb (doc_interface, SP_VERB_SELECTION_LOWER, error); + return dbus_call_verb(doc_interface, SP_VERB_SELECTION_LOWER, error); if ((strcmp(cmd, "to_top") == 0) || (strcmp(cmd, "to_front") == 0)) - return dbus_call_verb (doc_interface, SP_VERB_SELECTION_TO_FRONT, error); + return dbus_call_verb(doc_interface, SP_VERB_SELECTION_TO_FRONT, error); if ((strcmp(cmd, "to_bottom") == 0) || (strcmp(cmd, "to_back") == 0)) - return dbus_call_verb (doc_interface, SP_VERB_SELECTION_TO_BACK, error); + return dbus_call_verb(doc_interface, SP_VERB_SELECTION_TO_BACK, error); return TRUE; } @@ -1357,85 +1213,76 @@ document_interface_selection_change_level (DocumentInterface *doc_interface, gch gchar *document_interface_layer_new(DocumentInterface *doc_interface, GError ** /*error*/) { - Inkscape::LayerModel * layers = doc_interface->target.getSelection()->layers(); + Inkscape::LayerModel *layers = doc_interface->target.getSelection()->layers(); SPObject *new_layer = Inkscape::create_layer(layers->currentRoot(), layers->currentLayer(), Inkscape::LPOS_BELOW); layers->setCurrentLayer(new_layer); return g_strdup(get_name_from_object(new_layer)); } -gboolean -document_interface_layer_set (DocumentInterface *doc_interface, - gchar *layerstr, GError **error) +gboolean document_interface_layer_set(DocumentInterface *doc_interface, gchar *layerstr, GError **error) { - SPObject * obj = get_object_by_name (doc_interface->target.getDocument(), layerstr, error); - + SPObject *obj = get_object_by_name(doc_interface->target.getDocument(), layerstr, error); + if (!obj) return FALSE; - - doc_interface->target.getSelection()->layers()->setCurrentLayer (obj); + + doc_interface->target.getSelection()->layers()->setCurrentLayer(obj); return TRUE; } gchar **document_interface_layer_get_all(DocumentInterface * /*doc_interface*/) { - //FIXME: implement. + // FIXME: implement. return NULL; } -gboolean -document_interface_layer_change_level (DocumentInterface *doc_interface, - gchar *cmd, GError **error) +gboolean document_interface_layer_change_level(DocumentInterface *doc_interface, gchar *cmd, GError **error) { if (strcmp(cmd, "raise") == 0) - return dbus_call_verb (doc_interface, SP_VERB_LAYER_RAISE, error); + return dbus_call_verb(doc_interface, SP_VERB_LAYER_RAISE, error); if (strcmp(cmd, "lower") == 0) - return dbus_call_verb (doc_interface, SP_VERB_LAYER_LOWER, error); + return dbus_call_verb(doc_interface, SP_VERB_LAYER_LOWER, error); if ((strcmp(cmd, "to_top") == 0) || (strcmp(cmd, "to_front") == 0)) - return dbus_call_verb (doc_interface, SP_VERB_LAYER_TO_TOP, error); + return dbus_call_verb(doc_interface, SP_VERB_LAYER_TO_TOP, error); if ((strcmp(cmd, "to_bottom") == 0) || (strcmp(cmd, "to_back") == 0)) - return dbus_call_verb (doc_interface, SP_VERB_LAYER_TO_BOTTOM, error); + return dbus_call_verb(doc_interface, SP_VERB_LAYER_TO_BOTTOM, error); return TRUE; } -gboolean -document_interface_layer_next (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_layer_next(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_LAYER_NEXT, error); + return dbus_call_verb(doc_interface, SP_VERB_LAYER_NEXT, error); } -gboolean -document_interface_layer_previous (DocumentInterface *doc_interface, GError **error) +gboolean document_interface_layer_previous(DocumentInterface *doc_interface, GError **error) { - return dbus_call_verb (doc_interface, SP_VERB_LAYER_PREV, error); + return dbus_call_verb(doc_interface, SP_VERB_LAYER_PREV, error); } - //////////////signals - DocumentInterface *fugly; -gboolean dbus_send_ping (SPDesktop* desk, SPItem *item) +gboolean dbus_send_ping(SPDesktop *desk, SPItem *item) { - if (!item) return TRUE; - g_signal_emit (desk->dbus_document_interface, signals[OBJECT_MOVED_SIGNAL], 0, item->getId()); - return TRUE; + if (!item) + return TRUE; + g_signal_emit(desk->dbus_document_interface, signals[OBJECT_MOVED_SIGNAL], 0, item->getId()); + return TRUE; } //////////tree - -gboolean -document_interface_get_children (DocumentInterface *doc_interface, char *name, char ***out, GError **error) +gboolean document_interface_get_children(DocumentInterface *doc_interface, char *name, char ***out, GError **error) { - SPItem* parent=(SPItem* )get_object_by_name(doc_interface->target.getDocument(), name, error); - std::vector children = parent->childList(false); + SPItem *parent = (SPItem *)get_object_by_name(doc_interface->target.getDocument(), name, error); + std::vector children = parent->childList(false); int size = children.size(); - *out = g_new0 (char *, size + 1); + *out = g_new0(char *, size + 1); int i = 0; - for (std::vector::iterator iter = children.begin(), e = children.end(); iter != e; ++iter) { + for (std::vector::iterator iter = children.begin(), e = children.end(); iter != e; ++iter) { (*out)[i] = g_strdup((*iter)->getId()); i++; } @@ -1444,16 +1291,13 @@ document_interface_get_children (DocumentInterface *doc_interface, char *name, return TRUE; } - -gchar* -document_interface_get_parent (DocumentInterface *doc_interface, char *name, GError **error) +gchar *document_interface_get_parent(DocumentInterface *doc_interface, char *name, GError **error) { - SPItem*node=(SPItem* )get_object_by_name(doc_interface->target.getDocument(), name, error); - - SPObject* parent=node->parent; + SPItem *node = (SPItem *)get_object_by_name(doc_interface->target.getDocument(), name, error); - return g_strdup(parent->getRepr()->attribute("id")); + SPObject *parent = node->parent; + return g_strdup(parent->getRepr()->attribute("id")); } #if 0 diff --git a/src/extension/dbus/document-interface.h b/src/extension/dbus/document-interface.h index ed31513089fe07142bdc81bf37d9ec991dd5bb57..04b9e1ab6e16c6a81bf879f87fc1a366e8f39488 100644 --- a/src/extension/dbus/document-interface.h +++ b/src/extension/dbus/document-interface.h @@ -19,10 +19,10 @@ #ifndef INKSCAPE_EXTENSION_DOCUMENT_INTERFACE_H_ #define INKSCAPE_EXTENSION_DOCUMENT_INTERFACE_H_ -#include -#include #include #include +#include +#include // this is required so that giomm headers won't barf #undef DBUS_MESSAGE_TYPE_INVALID @@ -35,32 +35,36 @@ class SPDesktop; class SPItem; - -#define TYPE_DOCUMENT_INTERFACE (document_interface_get_type ()) -#define DOCUMENT_INTERFACE(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), TYPE_DOCUMENT_INTERFACE, DocumentInterface)) -#define DOCUMENT_INTERFACE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), TYPE_DOCUMENT_INTERFACE, DocumentInterfaceClass)) -#define IS_DOCUMENT_INTERFACE(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), TYPE_DOCUMENT_INTERFACE)) -#define IS_DOCUMENT_INTERFACE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), TYPE_DOCUMENT_INTERFACE)) -#define DOCUMENT_INTERFACE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), TYPE_DOCUMENT_INTERFACE, DocumentInterfaceClass)) + +#define TYPE_DOCUMENT_INTERFACE (document_interface_get_type()) +#define DOCUMENT_INTERFACE(object) (G_TYPE_CHECK_INSTANCE_CAST((object), TYPE_DOCUMENT_INTERFACE, DocumentInterface)) +#define DOCUMENT_INTERFACE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass), TYPE_DOCUMENT_INTERFACE, DocumentInterfaceClass)) +#define IS_DOCUMENT_INTERFACE(object) (G_TYPE_CHECK_INSTANCE_TYPE((object), TYPE_DOCUMENT_INTERFACE)) +#define IS_DOCUMENT_INTERFACE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), TYPE_DOCUMENT_INTERFACE)) +#define DOCUMENT_INTERFACE_GET_CLASS(obj) \ + (G_TYPE_INSTANCE_GET_CLASS((obj), TYPE_DOCUMENT_INTERFACE, DocumentInterfaceClass)) G_BEGIN_DECLS typedef struct _DocumentInterface DocumentInterface; typedef struct _DocumentInterfaceClass DocumentInterfaceClass; -struct _DocumentInterface { +struct _DocumentInterface +{ GObject parent; - Inkscape::ActionContext target; ///< stores information about which document, selection, desktop etc this interface is linked to + Inkscape::ActionContext target; ///< stores information about which document, selection, desktop etc this interface + ///< is linked to gboolean updates; }; -struct _DocumentInterfaceClass { - GObjectClass parent; +struct _DocumentInterfaceClass +{ + GObjectClass parent; }; - - -struct DBUSPoint { +struct DBUSPoint +{ int x; int y; }; @@ -68,183 +72,114 @@ struct DBUSPoint { MISC FUNCTIONS ****************************************************************************/ -gboolean -document_interface_delete_all (DocumentInterface *doc_interface, GError **error); +gboolean document_interface_delete_all(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_call_verb (DocumentInterface *doc_interface, - gchar *verbid, GError **error); +gboolean document_interface_call_verb(DocumentInterface *doc_interface, gchar *verbid, GError **error); /**************************************************************************** CREATION FUNCTIONS ****************************************************************************/ -gchar* -document_interface_rectangle (DocumentInterface *doc_interface, int x, int y, - int width, int height, GError **error); +gchar *document_interface_rectangle(DocumentInterface *doc_interface, int x, int y, int width, int height, + GError **error); -gchar* -document_interface_ellipse (DocumentInterface *doc_interface, int x, int y, - int width, int height, GError **error); - -gchar* -document_interface_polygon (DocumentInterface *doc_interface, int cx, int cy, - int radius, int rotation, int sides, - GError **error); +gchar *document_interface_ellipse(DocumentInterface *doc_interface, int x, int y, int width, int height, + GError **error); -gchar* -document_interface_star (DocumentInterface *doc_interface, int cx, int cy, - int r1, int r2, int sides, gdouble rounded, - gdouble arg1, gdouble arg2, GError **error); +gchar *document_interface_polygon(DocumentInterface *doc_interface, int cx, int cy, int radius, int rotation, int sides, + GError **error); -gchar* -document_interface_spiral (DocumentInterface *doc_interface, int cx, int cy, - int r, int revolutions, GError **error); +gchar *document_interface_star(DocumentInterface *doc_interface, int cx, int cy, int r1, int r2, int sides, + gdouble rounded, gdouble arg1, gdouble arg2, GError **error); -gchar* -document_interface_line (DocumentInterface *doc_interface, int x, int y, - int x2, int y2, GError **error); +gchar *document_interface_spiral(DocumentInterface *doc_interface, int cx, int cy, int r, int revolutions, + GError **error); -gchar* -document_interface_text (DocumentInterface *doc_interface, int x, int y, - gchar *text, GError **error); -gboolean -document_interface_set_text (DocumentInterface *doc_interface, gchar *name, - gchar *text, GError **error); -gboolean -document_interface_text_apply_style (DocumentInterface *doc_interface, gchar *name, - int start_pos, int end_pos, gchar *style, gchar *styleval, - GError **error); +gchar *document_interface_line(DocumentInterface *doc_interface, int x, int y, int x2, int y2, GError **error); -gchar * -document_interface_image (DocumentInterface *doc_interface, int x, int y, - gchar *filename, GError **error); +gchar *document_interface_text(DocumentInterface *doc_interface, int x, int y, gchar *text, GError **error); +gboolean document_interface_set_text(DocumentInterface *doc_interface, gchar *name, gchar *text, GError **error); +gboolean document_interface_text_apply_style(DocumentInterface *doc_interface, gchar *name, int start_pos, int end_pos, + gchar *style, gchar *styleval, GError **error); -gchar* -document_interface_node (DocumentInterface *doc_interface, gchar *svgtype, - GError **error); +gchar *document_interface_image(DocumentInterface *doc_interface, int x, int y, gchar *filename, GError **error); +gchar *document_interface_node(DocumentInterface *doc_interface, gchar *svgtype, GError **error); /**************************************************************************** ENVIRONMENT FUNCTIONS ****************************************************************************/ -gdouble -document_interface_document_get_width (DocumentInterface *doc_interface); +gdouble document_interface_document_get_width(DocumentInterface *doc_interface); -gdouble -document_interface_document_get_height (DocumentInterface *doc_interface); +gdouble document_interface_document_get_height(DocumentInterface *doc_interface); -gchar * -document_interface_document_get_css (DocumentInterface *doc_interface, GError **error); +gchar *document_interface_document_get_css(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_document_merge_css (DocumentInterface *doc_interface, - gchar *stylestring, GError **error); +gboolean document_interface_document_merge_css(DocumentInterface *doc_interface, gchar *stylestring, GError **error); -gboolean -document_interface_document_set_css (DocumentInterface *doc_interface, - gchar *stylestring, GError **error); +gboolean document_interface_document_set_css(DocumentInterface *doc_interface, gchar *stylestring, GError **error); -gboolean -document_interface_document_resize_to_fit_selection (DocumentInterface *doc_interface, - GError **error); -gboolean -document_interface_document_set_display_area (DocumentInterface *doc_interface, - double x0, - double y0, - double x1, - double y1, - double border, - GError **error); -GArray * -document_interface_document_get_display_area (DocumentInterface *doc_interface); +gboolean document_interface_document_resize_to_fit_selection(DocumentInterface *doc_interface, GError **error); +gboolean document_interface_document_set_display_area(DocumentInterface *doc_interface, double x0, double y0, double x1, + double y1, double border, GError **error); +GArray *document_interface_document_get_display_area(DocumentInterface *doc_interface); /**************************************************************************** OBJECT FUNCTIONS ****************************************************************************/ -gboolean -document_interface_set_attribute (DocumentInterface *doc_interface, - char *shape, char *attribute, - char *newval, GError **error); +gboolean document_interface_set_attribute(DocumentInterface *doc_interface, char *shape, char *attribute, char *newval, + GError **error); -gboolean -document_interface_set_int_attribute (DocumentInterface *doc_interface, - char *shape, char *attribute, - int newval, GError **error); - -gboolean -document_interface_set_double_attribute (DocumentInterface *doc_interface, - char *shape, char *attribute, - double newval, GError **error); +gboolean document_interface_set_int_attribute(DocumentInterface *doc_interface, char *shape, char *attribute, + int newval, GError **error); -gchar * -document_interface_get_attribute (DocumentInterface *doc_interface, - char *shape, char *attribute, GError **error); +gboolean document_interface_set_double_attribute(DocumentInterface *doc_interface, char *shape, char *attribute, + double newval, GError **error); -gboolean -document_interface_move (DocumentInterface *doc_interface, gchar *name, - gdouble x, gdouble y, GError **error); +gchar *document_interface_get_attribute(DocumentInterface *doc_interface, char *shape, char *attribute, GError **error); -gboolean -document_interface_move_to (DocumentInterface *doc_interface, gchar *name, - gdouble x, gdouble y, GError **error); +gboolean document_interface_move(DocumentInterface *doc_interface, gchar *name, gdouble x, gdouble y, GError **error); -gboolean -document_interface_object_to_path (DocumentInterface *doc_interface, - char *shape, GError **error); +gboolean document_interface_move_to(DocumentInterface *doc_interface, gchar *name, gdouble x, gdouble y, + GError **error); -gchar * -document_interface_get_path (DocumentInterface *doc_interface, - char *pathname, GError **error); +gboolean document_interface_object_to_path(DocumentInterface *doc_interface, char *shape, GError **error); -gboolean -document_interface_transform (DocumentInterface *doc_interface, gchar *shape, - gchar *transformstr, GError **error); +gchar *document_interface_get_path(DocumentInterface *doc_interface, char *pathname, GError **error); -gchar * -document_interface_get_css (DocumentInterface *doc_interface, gchar *shape, - GError **error); +gboolean document_interface_transform(DocumentInterface *doc_interface, gchar *shape, gchar *transformstr, + GError **error); -gboolean -document_interface_modify_css (DocumentInterface *doc_interface, gchar *shape, - gchar *cssattrb, gchar *newval, GError **error); +gchar *document_interface_get_css(DocumentInterface *doc_interface, gchar *shape, GError **error); -gboolean -document_interface_merge_css (DocumentInterface *doc_interface, gchar *shape, - gchar *stylestring, GError **error); +gboolean document_interface_modify_css(DocumentInterface *doc_interface, gchar *shape, gchar *cssattrb, gchar *newval, + GError **error); -gboolean -document_interface_set_color (DocumentInterface *doc_interface, gchar *shape, - int r, int g, int b, gboolean fill, GError **error); +gboolean document_interface_merge_css(DocumentInterface *doc_interface, gchar *shape, gchar *stylestring, + GError **error); -gboolean -document_interface_move_to_layer (DocumentInterface *doc_interface, gchar *shape, - gchar *layerstr, GError **error); +gboolean document_interface_set_color(DocumentInterface *doc_interface, gchar *shape, int r, int g, int b, + gboolean fill, GError **error); +gboolean document_interface_move_to_layer(DocumentInterface *doc_interface, gchar *shape, gchar *layerstr, + GError **error); -GArray * -document_interface_get_node_coordinates (DocumentInterface *doc_interface, gchar *shape); +GArray *document_interface_get_node_coordinates(DocumentInterface *doc_interface, gchar *shape); /**************************************************************************** FILE I/O FUNCTIONS ****************************************************************************/ -gboolean -document_interface_save (DocumentInterface *doc_interface, GError **error); +gboolean document_interface_save(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_load (DocumentInterface *doc_interface, - gchar *filename, GError **error); +gboolean document_interface_load(DocumentInterface *doc_interface, gchar *filename, GError **error); -gboolean -document_interface_save_as (DocumentInterface *doc_interface, - const gchar *filename, GError **error); +gboolean document_interface_save_as(DocumentInterface *doc_interface, const gchar *filename, GError **error); -gboolean -document_interface_mark_as_unmodified (DocumentInterface *doc_interface, GError **error); +gboolean document_interface_mark_as_unmodified(DocumentInterface *doc_interface, GError **error); /* -gboolean +gboolean document_interface_print_to_file (DocumentInterface *doc_interface, GError **error); */ @@ -252,169 +187,105 @@ document_interface_print_to_file (DocumentInterface *doc_interface, GError **err PROGRAM CONTROL FUNCTIONS ****************************************************************************/ -gboolean -document_interface_close (DocumentInterface *doc_interface, GError **error); +gboolean document_interface_close(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_exit (DocumentInterface *doc_interface, GError **error); - -gboolean -document_interface_undo (DocumentInterface *doc_interface, GError **error); +gboolean document_interface_exit(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_redo (DocumentInterface *doc_interface, GError **error); +gboolean document_interface_undo(DocumentInterface *doc_interface, GError **error); +gboolean document_interface_redo(DocumentInterface *doc_interface, GError **error); /**************************************************************************** UPDATE FUNCTIONS ****************************************************************************/ -void -document_interface_pause_updates (DocumentInterface *doc_interface, GError **error); +void document_interface_pause_updates(DocumentInterface *doc_interface, GError **error); -void -document_interface_resume_updates (DocumentInterface *doc_interface, GError **error); +void document_interface_resume_updates(DocumentInterface *doc_interface, GError **error); -void -document_interface_update (DocumentInterface *doc_interface, GError **error); +void document_interface_update(DocumentInterface *doc_interface, GError **error); /**************************************************************************** SELECTION FUNCTIONS ****************************************************************************/ -gboolean -document_interface_selection_get (DocumentInterface *doc_interface, char ***out, GError **error); +gboolean document_interface_selection_get(DocumentInterface *doc_interface, char ***out, GError **error); -gboolean -document_interface_selection_add (DocumentInterface *doc_interface, - char *name, GError **error); +gboolean document_interface_selection_add(DocumentInterface *doc_interface, char *name, GError **error); -gboolean -document_interface_selection_add_list (DocumentInterface *doc_interface, - char **names, GError **error); +gboolean document_interface_selection_add_list(DocumentInterface *doc_interface, char **names, GError **error); -gboolean -document_interface_selection_set (DocumentInterface *doc_interface, - char *name, GError **error); +gboolean document_interface_selection_set(DocumentInterface *doc_interface, char *name, GError **error); -gboolean -document_interface_selection_set_list (DocumentInterface *doc_interface, - gchar **names, GError **error); +gboolean document_interface_selection_set_list(DocumentInterface *doc_interface, gchar **names, GError **error); -gboolean -document_interface_selection_rotate (DocumentInterface *doc_interface, - int angle, GError **error); +gboolean document_interface_selection_rotate(DocumentInterface *doc_interface, int angle, GError **error); -gboolean -document_interface_selection_delete(DocumentInterface *doc_interface, GError **error); +gboolean document_interface_selection_delete(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_selection_clear(DocumentInterface *doc_interface, GError **error); +gboolean document_interface_selection_clear(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_select_all(DocumentInterface *doc_interface, GError **error); +gboolean document_interface_select_all(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_select_all_in_all_layers(DocumentInterface *doc_interface, - GError **error); +gboolean document_interface_select_all_in_all_layers(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_selection_box (DocumentInterface *doc_interface, int x, int y, - int x2, int y2, gboolean replace, - GError **error); +gboolean document_interface_selection_box(DocumentInterface *doc_interface, int x, int y, int x2, int y2, + gboolean replace, GError **error); -gboolean -document_interface_selection_invert (DocumentInterface *doc_interface, GError **error); +gboolean document_interface_selection_invert(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_selection_group(DocumentInterface *doc_interface, GError **error); +gboolean document_interface_selection_group(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_selection_ungroup(DocumentInterface *doc_interface, GError **error); +gboolean document_interface_selection_ungroup(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_selection_cut(DocumentInterface *doc_interface, GError **error); +gboolean document_interface_selection_cut(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_selection_copy(DocumentInterface *doc_interface, GError **error); +gboolean document_interface_selection_copy(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_selection_paste(DocumentInterface *doc_interface, GError **error); +gboolean document_interface_selection_paste(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_selection_scale (DocumentInterface *doc_interface, - gdouble grow, GError **error); +gboolean document_interface_selection_scale(DocumentInterface *doc_interface, gdouble grow, GError **error); -gboolean -document_interface_selection_move (DocumentInterface *doc_interface, gdouble x, - gdouble y, GError **error); +gboolean document_interface_selection_move(DocumentInterface *doc_interface, gdouble x, gdouble y, GError **error); -gboolean -document_interface_selection_move_to (DocumentInterface *doc_interface, gdouble x, - gdouble y, GError **error); +gboolean document_interface_selection_move_to(DocumentInterface *doc_interface, gdouble x, gdouble y, GError **error); -gboolean -document_interface_selection_move_to_layer (DocumentInterface *doc_interface, - gchar *layerstr, GError **error); +gboolean document_interface_selection_move_to_layer(DocumentInterface *doc_interface, gchar *layerstr, GError **error); -GArray * -document_interface_selection_get_center (DocumentInterface *doc_interface); +GArray *document_interface_selection_get_center(DocumentInterface *doc_interface); -gboolean -document_interface_selection_to_path (DocumentInterface *doc_interface, GError **error); +gboolean document_interface_selection_to_path(DocumentInterface *doc_interface, GError **error); -gboolean -document_interface_selection_combine (DocumentInterface *doc_interface, gchar *cmd, char ***newpaths, - GError **error); +gboolean document_interface_selection_combine(DocumentInterface *doc_interface, gchar *cmd, char ***newpaths, + GError **error); -gboolean -document_interface_selection_change_level (DocumentInterface *doc_interface, gchar *cmd, - GError **error); +gboolean document_interface_selection_change_level(DocumentInterface *doc_interface, gchar *cmd, GError **error); /**************************************************************************** LAYER FUNCTIONS ****************************************************************************/ -gchar * -document_interface_layer_new (DocumentInterface *doc_interface, GError **error); - -gboolean -document_interface_layer_set (DocumentInterface *doc_interface, - gchar *layerstr, GError **error); +gchar *document_interface_layer_new(DocumentInterface *doc_interface, GError **error); -gchar ** -document_interface_layer_get_all (DocumentInterface *doc_interface); +gboolean document_interface_layer_set(DocumentInterface *doc_interface, gchar *layerstr, GError **error); -gboolean -document_interface_layer_change_level (DocumentInterface *doc_interface, - gchar *cmd, GError **error); +gchar **document_interface_layer_get_all(DocumentInterface *doc_interface); -gboolean -document_interface_layer_next (DocumentInterface *doc_interface, GError **error); +gboolean document_interface_layer_change_level(DocumentInterface *doc_interface, gchar *cmd, GError **error); -gboolean -document_interface_layer_previous (DocumentInterface *doc_interface, GError **error); +gboolean document_interface_layer_next(DocumentInterface *doc_interface, GError **error); +gboolean document_interface_layer_previous(DocumentInterface *doc_interface, GError **error); - - - - - - -DocumentInterface *document_interface_new (void); -GType document_interface_get_type (void); +DocumentInterface *document_interface_new(void); +GType document_interface_get_type(void); extern DocumentInterface *fugly; -gboolean dbus_send_ping (SPDesktop* desk, SPItem *item); +gboolean dbus_send_ping(SPDesktop *desk, SPItem *item); -gboolean -document_interface_get_children (DocumentInterface *doc_interface, char *name, char ***out, GError **error); +gboolean document_interface_get_children(DocumentInterface *doc_interface, char *name, char ***out, GError **error); -gchar* -document_interface_get_parent (DocumentInterface *doc_interface, char *name, GError **error); +gchar *document_interface_get_parent(DocumentInterface *doc_interface, char *name, GError **error); -gchar* -document_interface_import (DocumentInterface *doc_interface, - gchar *filename, GError **error); +gchar *document_interface_import(DocumentInterface *doc_interface, gchar *filename, GError **error); G_END_DECLS diff --git a/src/extension/dbus/wrapper/inkscape-dbus-wrapper.c b/src/extension/dbus/wrapper/inkscape-dbus-wrapper.c index cc9399cda78a72c5cb5bf615c1a60c2c68b686c2..6754d6e8524317b67b26dd0e7d2f14b414c57f73 100644 --- a/src/extension/dbus/wrapper/inkscape-dbus-wrapper.c +++ b/src/extension/dbus/wrapper/inkscape-dbus-wrapper.c @@ -8,39 +8,34 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "inkscape-dbus-wrapper.h" -#include + +#include +#include #include #include - - +#include #include "document-client-glue.h" -#include -#include // (static.*(\n[^}]*)*(async)+.*(\n[^}]*)*})|typedef void .*; // http://www.josephkahn.com/music/index.xml /* PRIVATE get a connection to the session bus */ -DBusGConnection * -dbus_get_connection() { - GError *error = NULL; - DBusGConnection *connection = dbus_g_bus_get (DBUS_BUS_SESSION, &error); - if (error) { - fprintf(stderr, "Failed to get connection"); - return NULL; - } - else - return connection; +DBusGConnection *dbus_get_connection() +{ + GError *error = NULL; + DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, &error); + if (error) { + fprintf(stderr, "Failed to get connection"); + return NULL; + } else + return connection; } /* PRIVATE create a proxy object for a bus.*/ -DBusGProxy * -dbus_get_proxy(DBusGConnection *connection) { - return dbus_g_proxy_new_for_name (connection, - DBUS_SERVICE_DBUS, - DBUS_PATH_DBUS, - DBUS_INTERFACE_DBUS); +DBusGProxy *dbus_get_proxy(DBusGConnection *connection) +{ + return dbus_g_proxy_new_for_name(connection, DBUS_SERVICE_DBUS, DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS); } #if 0 @@ -63,725 +58,653 @@ dbus_register_object (DBusGConnection *connection, DOCUMENT INTERFACE CLASS STUFF ****************************************************************************/ -struct _DocumentInterface { - GObject parent; - DBusGProxy * proxy; +struct _DocumentInterface +{ + GObject parent; + DBusGProxy *proxy; }; G_DEFINE_TYPE(DocumentInterface, document_interface, G_TYPE_OBJECT) -static void -document_interface_finalize (GObject *object) +static void document_interface_finalize(GObject *object) { - G_OBJECT_CLASS (document_interface_parent_class)->finalize (object); + G_OBJECT_CLASS(document_interface_parent_class)->finalize(object); } - -static void -document_interface_class_init (DocumentInterfaceClass *klass) +static void document_interface_class_init(DocumentInterfaceClass *klass) { - GObjectClass *object_class; - object_class = G_OBJECT_CLASS (klass); - object_class->finalize = document_interface_finalize; + GObjectClass *object_class; + object_class = G_OBJECT_CLASS(klass); + object_class->finalize = document_interface_finalize; } -static void -document_interface_init (DocumentInterface *object) +static void document_interface_init(DocumentInterface *object) { - object->proxy = NULL; + object->proxy = NULL; } - -DocumentInterface * -document_interface_new (void) +DocumentInterface *document_interface_new(void) { - return (DocumentInterface*)g_object_new (TYPE_DOCUMENT_INTERFACE, NULL); + return (DocumentInterface *)g_object_new(TYPE_DOCUMENT_INTERFACE, NULL); } -DocumentInterface * -inkscape_desktop_init_dbus () +DocumentInterface *inkscape_desktop_init_dbus() { DBusGConnection *connection; GError *error; DBusGProxy *proxy; - -#if !GLIB_CHECK_VERSION(2,36,0) - g_type_init (); + +#if !GLIB_CHECK_VERSION(2, 36, 0) + g_type_init(); #endif error = NULL; - connection = dbus_g_bus_get (DBUS_BUS_SESSION, - &error); - if (connection == NULL) - { - g_printerr ("Failed to open connection to bus: %s\n", - error->message); - g_error_free (error); - exit (1); - } - - proxy = dbus_g_proxy_new_for_name (connection, - "org.inkscape", - "/org/inkscape/desktop_0", - "org.inkscape.document"); - - DocumentInterface * inkdesk = (DocumentInterface *)g_object_new (TYPE_DOCUMENT_INTERFACE, NULL); + connection = dbus_g_bus_get(DBUS_BUS_SESSION, &error); + if (connection == NULL) { + g_printerr("Failed to open connection to bus: %s\n", error->message); + g_error_free(error); + exit(1); + } + + proxy = dbus_g_proxy_new_for_name(connection, "org.inkscape", "/org/inkscape/desktop_0", "org.inkscape.document"); + + DocumentInterface *inkdesk = (DocumentInterface *)g_object_new(TYPE_DOCUMENT_INTERFACE, NULL); inkdesk->proxy = proxy; return inkdesk; } - -//static -gboolean -inkscape_delete_all (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_delete_all(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_delete_all (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_delete_all(proxy, error); } -//static -gboolean -inkscape_call_verb (DocumentInterface *doc, const char * IN_verbid, GError **error) +// static +gboolean inkscape_call_verb(DocumentInterface *doc, const char *IN_verbid, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_call_verb(proxy, IN_verbid, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_call_verb(proxy, IN_verbid, error); } - -//static -gchar * -inkscape_rectangle (DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_width, const gint IN_height, GError **error) +// static +gchar *inkscape_rectangle(DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_width, + const gint IN_height, GError **error) { - char * OUT_object_name; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_rectangle (proxy, IN_x, IN_y, IN_width, IN_height, &OUT_object_name, error); - return OUT_object_name; + char *OUT_object_name; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_rectangle(proxy, IN_x, IN_y, IN_width, IN_height, &OUT_object_name, error); + return OUT_object_name; } -//static -char * -inkscape_ellipse (DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_width, const gint IN_height, GError **error) +// static +char *inkscape_ellipse(DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_width, + const gint IN_height, GError **error) { - char * OUT_object_name; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_ellipse (proxy, IN_x, IN_y, IN_width, IN_height, &OUT_object_name, error); - return OUT_object_name; + char *OUT_object_name; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_ellipse(proxy, IN_x, IN_y, IN_width, IN_height, &OUT_object_name, error); + return OUT_object_name; } -//static -char * -inkscape_polygon (DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_radius, const gint IN_rotation, const gint IN_sides, GError **error) +// static +char *inkscape_polygon(DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_radius, + const gint IN_rotation, const gint IN_sides, GError **error) { - char * OUT_object_name; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_polygon (proxy, IN_cx, IN_cy, IN_radius, IN_rotation, IN_sides, &OUT_object_name, error); - return OUT_object_name; + char *OUT_object_name; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_polygon(proxy, IN_cx, IN_cy, IN_radius, IN_rotation, IN_sides, &OUT_object_name, error); + return OUT_object_name; } -//static -char * -inkscape_star (DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_r1, const gint IN_r2, const gdouble IN_arg1, const gdouble IN_arg2, const gint IN_sides, const gdouble IN_rounded, GError **error) +// static +char *inkscape_star(DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_r1, const gint IN_r2, + const gdouble IN_arg1, const gdouble IN_arg2, const gint IN_sides, const gdouble IN_rounded, + GError **error) { - char * OUT_object_name; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_star (proxy, IN_cx, IN_cy, IN_r1, IN_r2, IN_arg1, IN_arg2, IN_sides, IN_rounded, &OUT_object_name, error); - return OUT_object_name; + char *OUT_object_name; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_star(proxy, IN_cx, IN_cy, IN_r1, IN_r2, IN_arg1, IN_arg2, IN_sides, IN_rounded, + &OUT_object_name, error); + return OUT_object_name; } -//static -char * -inkscape_spiral (DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_r, const gint IN_revolutions, GError **error) +// static +char *inkscape_spiral(DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_r, + const gint IN_revolutions, GError **error) { - char * OUT_object_name; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_spiral (proxy, IN_cx, IN_cy, IN_r, IN_revolutions, &OUT_object_name, error); - return OUT_object_name; + char *OUT_object_name; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_spiral(proxy, IN_cx, IN_cy, IN_r, IN_revolutions, &OUT_object_name, error); + return OUT_object_name; } -//static -char * -inkscape_line (DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_x2, const gint IN_y2, GError **error) +// static +char *inkscape_line(DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_x2, const gint IN_y2, + GError **error) { - char * OUT_object_name; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_line (proxy, IN_x, IN_y, IN_x2, IN_y2, &OUT_object_name, error); - return OUT_object_name; + char *OUT_object_name; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_line(proxy, IN_x, IN_y, IN_x2, IN_y2, &OUT_object_name, error); + return OUT_object_name; } -//static -char * -inkscape_text (DocumentInterface *doc, const gint IN_x, const gint IN_y, const char * IN_text, GError **error) +// static +char *inkscape_text(DocumentInterface *doc, const gint IN_x, const gint IN_y, const char *IN_text, GError **error) { - char * OUT_object_name; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_text (proxy, IN_x, IN_y, IN_text, &OUT_object_name, error); - return OUT_object_name; + char *OUT_object_name; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_text(proxy, IN_x, IN_y, IN_text, &OUT_object_name, error); + return OUT_object_name; } -//static -char * -inkscape_image (DocumentInterface *doc, const gint IN_x, const gint IN_y, const char * IN_text, GError **error) +// static +char *inkscape_image(DocumentInterface *doc, const gint IN_x, const gint IN_y, const char *IN_text, GError **error) { - char * OUT_object_name; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_image (proxy, IN_x, IN_y, IN_text, &OUT_object_name, error); - return OUT_object_name; + char *OUT_object_name; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_image(proxy, IN_x, IN_y, IN_text, &OUT_object_name, error); + return OUT_object_name; } -//static -char * -inkscape_node (DocumentInterface *doc, const char * IN_svgtype, GError **error) +// static +char *inkscape_node(DocumentInterface *doc, const char *IN_svgtype, GError **error) { - char *OUT_node_name; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_node (proxy, IN_svgtype, &OUT_node_name, error); - return OUT_node_name; + char *OUT_node_name; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_node(proxy, IN_svgtype, &OUT_node_name, error); + return OUT_node_name; } -//static -gdouble -inkscape_document_get_width (DocumentInterface *doc, GError **error) +// static +gdouble inkscape_document_get_width(DocumentInterface *doc, GError **error) { - gdouble OUT_val; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_document_get_width (proxy, &OUT_val, error); - return OUT_val; + gdouble OUT_val; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_document_get_width(proxy, &OUT_val, error); + return OUT_val; } -//static -gdouble -inkscape_document_get_height (DocumentInterface *doc, GError **error) +// static +gdouble inkscape_document_get_height(DocumentInterface *doc, GError **error) { - gdouble OUT_val; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_document_get_height (proxy, &OUT_val, error); - return OUT_val; + gdouble OUT_val; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_document_get_height(proxy, &OUT_val, error); + return OUT_val; } -//static -char * -inkscape_document_get_css (DocumentInterface *doc, GError **error) +// static +char *inkscape_document_get_css(DocumentInterface *doc, GError **error) { - char * OUT_css; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_document_get_css (proxy, &OUT_css, error); - return OUT_css; + char *OUT_css; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_document_get_css(proxy, &OUT_css, error); + return OUT_css; } -//static -gboolean -inkscape_document_set_css (DocumentInterface *doc, const char * IN_stylestring, GError **error) +// static +gboolean inkscape_document_set_css(DocumentInterface *doc, const char *IN_stylestring, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_document_set_css (proxy, IN_stylestring, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_document_set_css(proxy, IN_stylestring, error); } -//static -gboolean -inkscape_document_merge_css (DocumentInterface *doc, const char * IN_stylestring, GError **error) +// static +gboolean inkscape_document_merge_css(DocumentInterface *doc, const char *IN_stylestring, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_document_merge_css (proxy, IN_stylestring, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_document_merge_css(proxy, IN_stylestring, error); } -//static -gboolean -inkscape_document_resize_to_fit_selection (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_document_resize_to_fit_selection(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_document_resize_to_fit_selection (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_document_resize_to_fit_selection(proxy, error); } -//static -gboolean -inkscape_set_attribute (DocumentInterface *doc, const char * IN_shape, const char * IN_attribute, const char * IN_newval, GError **error) +// static +gboolean inkscape_set_attribute(DocumentInterface *doc, const char *IN_shape, const char *IN_attribute, + const char *IN_newval, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_set_attribute (proxy, IN_shape, IN_attribute, IN_newval, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_set_attribute(proxy, IN_shape, IN_attribute, IN_newval, error); } -//static -gboolean -inkscape_set_int_attribute (DocumentInterface *doc, const char * IN_shape, const char * IN_attribute, const gint IN_newval, GError **error) +// static +gboolean inkscape_set_int_attribute(DocumentInterface *doc, const char *IN_shape, const char *IN_attribute, + const gint IN_newval, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_set_int_attribute (proxy, IN_shape, IN_attribute, IN_newval, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_set_int_attribute(proxy, IN_shape, IN_attribute, IN_newval, error); } -//static -gboolean -inkscape_set_double_attribute (DocumentInterface *doc, const char * IN_shape, const char * IN_attribute, const gdouble IN_newval, GError **error) +// static +gboolean inkscape_set_double_attribute(DocumentInterface *doc, const char *IN_shape, const char *IN_attribute, + const gdouble IN_newval, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_set_double_attribute (proxy, IN_shape, IN_attribute, IN_newval, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_set_double_attribute(proxy, IN_shape, IN_attribute, IN_newval, error); } -//static -char * -inkscape_get_attribute (DocumentInterface *doc, const char * IN_shape, const char * IN_attribute, GError **error) +// static +char *inkscape_get_attribute(DocumentInterface *doc, const char *IN_shape, const char *IN_attribute, GError **error) { - char * OUT_val; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_get_attribute (proxy, IN_shape, IN_attribute, &OUT_val, error); - return OUT_val; + char *OUT_val; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_get_attribute(proxy, IN_shape, IN_attribute, &OUT_val, error); + return OUT_val; } -//static -gboolean -inkscape_move (DocumentInterface *doc, const char * IN_shape, const gdouble IN_x, const gdouble IN_y, GError **error) +// static +gboolean inkscape_move(DocumentInterface *doc, const char *IN_shape, const gdouble IN_x, const gdouble IN_y, + GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_move (proxy, IN_shape, IN_x, IN_y, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_move(proxy, IN_shape, IN_x, IN_y, error); } -//static -gboolean -inkscape_move_to (DocumentInterface *doc, const char * IN_shape, const gdouble IN_x, const gdouble IN_y, GError **error) +// static +gboolean inkscape_move_to(DocumentInterface *doc, const char *IN_shape, const gdouble IN_x, const gdouble IN_y, + GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_move_to (proxy, IN_shape, IN_x, IN_y, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_move_to(proxy, IN_shape, IN_x, IN_y, error); } -//static -gboolean -inkscape_object_to_path (DocumentInterface *doc, const char * IN_objectname, GError **error) +// static +gboolean inkscape_object_to_path(DocumentInterface *doc, const char *IN_objectname, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_object_to_path (proxy, IN_objectname, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_object_to_path(proxy, IN_objectname, error); } -//static -char * -inkscape_get_path (DocumentInterface *doc, const char * IN_shape, GError **error) +// static +char *inkscape_get_path(DocumentInterface *doc, const char *IN_shape, GError **error) { - char * OUT_val; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_get_path (proxy, IN_shape, &OUT_val, error); - return OUT_val; + char *OUT_val; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_get_path(proxy, IN_shape, &OUT_val, error); + return OUT_val; } -//static -gboolean -inkscape_transform (DocumentInterface *doc, const char * IN_shape, const char * IN_transformstr, GError **error) +// static +gboolean inkscape_transform(DocumentInterface *doc, const char *IN_shape, const char *IN_transformstr, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_transform (proxy, IN_shape, IN_transformstr, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_transform(proxy, IN_shape, IN_transformstr, error); } -//static -char * -inkscape_get_css (DocumentInterface *doc, const char * IN_shape, GError **error) +// static +char *inkscape_get_css(DocumentInterface *doc, const char *IN_shape, GError **error) { - char * OUT_css; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_get_css (proxy, IN_shape, &OUT_css, error); - return OUT_css; + char *OUT_css; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_get_css(proxy, IN_shape, &OUT_css, error); + return OUT_css; } -//static -gboolean -inkscape_modify_css (DocumentInterface *doc, const char * IN_shape, const char * IN_cssattrib, const char * IN_newval, GError **error) +// static +gboolean inkscape_modify_css(DocumentInterface *doc, const char *IN_shape, const char *IN_cssattrib, + const char *IN_newval, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_modify_css (proxy, IN_shape, IN_cssattrib, IN_newval, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_modify_css(proxy, IN_shape, IN_cssattrib, IN_newval, error); } -//static -gboolean -inkscape_merge_css (DocumentInterface *doc, const char * IN_shape, const char * IN_stylestring, GError **error) +// static +gboolean inkscape_merge_css(DocumentInterface *doc, const char *IN_shape, const char *IN_stylestring, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_merge_css (proxy, IN_shape, IN_stylestring, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_merge_css(proxy, IN_shape, IN_stylestring, error); } -//static -gboolean -inkscape_set_color (DocumentInterface *doc, const char * IN_shape, const gint IN_red, const gint IN_green, const gint IN_blue, const gboolean IN_fill, GError **error) +// static +gboolean inkscape_set_color(DocumentInterface *doc, const char *IN_shape, const gint IN_red, const gint IN_green, + const gint IN_blue, const gboolean IN_fill, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_set_color (proxy, IN_shape, IN_red, IN_green, IN_blue, IN_fill, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_set_color(proxy, IN_shape, IN_red, IN_green, IN_blue, IN_fill, error); } -//static -gboolean -inkscape_move_to_layer (DocumentInterface *doc, const char * IN_objectname, const char * IN_layername, GError **error) +// static +gboolean inkscape_move_to_layer(DocumentInterface *doc, const char *IN_objectname, const char *IN_layername, + GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_move_to_layer (proxy, IN_objectname, IN_layername, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_move_to_layer(proxy, IN_objectname, IN_layername, error); } -//static -GArray* -inkscape_get_node_coordinates (DocumentInterface *doc, const char * IN_shape, GError **error) +// static +GArray *inkscape_get_node_coordinates(DocumentInterface *doc, const char *IN_shape, GError **error) { - GArray* OUT_points; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_get_node_coordinates (proxy, IN_shape, &OUT_points, error); - return OUT_points; + GArray *OUT_points; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_get_node_coordinates(proxy, IN_shape, &OUT_points, error); + return OUT_points; } -//static -gboolean -inkscape_save (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_save(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_save (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_save(proxy, error); } -//static -gboolean -inkscape_save_as (DocumentInterface *doc, const char * IN_pathname, GError **error) +// static +gboolean inkscape_save_as(DocumentInterface *doc, const char *IN_pathname, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_save_as (proxy, IN_pathname, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_save_as(proxy, IN_pathname, error); } -//static -gboolean -inkscape_load (DocumentInterface *doc, const char * IN_pathname, GError **error) +// static +gboolean inkscape_load(DocumentInterface *doc, const char *IN_pathname, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_load (proxy, IN_pathname, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_load(proxy, IN_pathname, error); } -//static -gboolean -inkscape_mark_as_unmodified (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_mark_as_unmodified(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_mark_as_unmodified (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_mark_as_unmodified(proxy, error); } -//static -gboolean -inkscape_close (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_close(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_close (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_close(proxy, error); } -//static -gboolean -inkscape_inkscape_exit (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_inkscape_exit(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_exit (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_exit(proxy, error); } -//static -gboolean -inkscape_undo (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_undo(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_undo (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_undo(proxy, error); } -//static -gboolean -inkscape_redo (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_redo(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_redo (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_redo(proxy, error); } -//static -gboolean -inkscape_pause_updates (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_pause_updates(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_pause_updates (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_pause_updates(proxy, error); } -//static -gboolean -inkscape_resume_updates (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_resume_updates(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_resume_updates (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_resume_updates(proxy, error); } -//static -gboolean -inkscape_update (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_update(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_update (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_update(proxy, error); } -//static -char ** -inkscape_selection_get (DocumentInterface *doc, GError **error) +// static +char **inkscape_selection_get(DocumentInterface *doc, GError **error) { - char ** OUT_listy; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_selection_get (proxy, &OUT_listy, error); - return OUT_listy; + char **OUT_listy; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_selection_get(proxy, &OUT_listy, error); + return OUT_listy; } -//static -gboolean -inkscape_selection_add (DocumentInterface *doc, const char * IN_name, GError **error) +// static +gboolean inkscape_selection_add(DocumentInterface *doc, const char *IN_name, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_add (proxy, IN_name, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_add(proxy, IN_name, error); } -//static -gboolean -inkscape_selection_add_list (DocumentInterface *doc, const char ** IN_name, GError **error) +// static +gboolean inkscape_selection_add_list(DocumentInterface *doc, const char **IN_name, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_add_list (proxy, IN_name, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_add_list(proxy, IN_name, error); } -//static -gboolean -inkscape_selection_set (DocumentInterface *doc, const char * IN_name, GError **error) +// static +gboolean inkscape_selection_set(DocumentInterface *doc, const char *IN_name, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_set (proxy, IN_name, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_set(proxy, IN_name, error); } -//static -gboolean -inkscape_selection_set_list (DocumentInterface *doc, const char ** IN_name, GError **error) +// static +gboolean inkscape_selection_set_list(DocumentInterface *doc, const char **IN_name, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_set_list (proxy, IN_name, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_set_list(proxy, IN_name, error); } -//static -gboolean -inkscape_selection_rotate (DocumentInterface *doc, const gint IN_angle, GError **error) +// static +gboolean inkscape_selection_rotate(DocumentInterface *doc, const gint IN_angle, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_rotate (proxy, IN_angle, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_rotate(proxy, IN_angle, error); } -//static -gboolean -inkscape_selection_delete (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_selection_delete(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_delete (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_delete(proxy, error); } -//static -gboolean -inkscape_selection_clear (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_selection_clear(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_clear (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_clear(proxy, error); } -//static -gboolean -inkscape_select_all (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_select_all(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_select_all (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_select_all(proxy, error); } -//static -gboolean -inkscape_select_all_in_all_layers (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_select_all_in_all_layers(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_select_all_in_all_layers (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_select_all_in_all_layers(proxy, error); } -//static -gboolean -inkscape_selection_box (DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_x2, const gint IN_y2, const gboolean IN_replace, GError **error) +// static +gboolean inkscape_selection_box(DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_x2, + const gint IN_y2, const gboolean IN_replace, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_box (proxy, IN_x, IN_y, IN_x2, IN_y2, IN_replace, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_box(proxy, IN_x, IN_y, IN_x2, IN_y2, IN_replace, error); } -//static -gboolean -inkscape_selection_invert (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_selection_invert(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_invert (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_invert(proxy, error); } -//static -gboolean -inkscape_selection_group (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_selection_group(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_group (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_group(proxy, error); } -//static -gboolean -inkscape_selection_ungroup (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_selection_ungroup(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_ungroup (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_ungroup(proxy, error); } -//static -gboolean -inkscape_selection_cut (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_selection_cut(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_cut (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_cut(proxy, error); } -//static -gboolean -inkscape_selection_copy (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_selection_copy(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_copy (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_copy(proxy, error); } -//static -gboolean -inkscape_selection_paste (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_selection_paste(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_paste (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_paste(proxy, error); } -//static -gboolean -inkscape_selection_scale (DocumentInterface *doc, const gdouble IN_grow, GError **error) +// static +gboolean inkscape_selection_scale(DocumentInterface *doc, const gdouble IN_grow, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_scale (proxy, IN_grow, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_scale(proxy, IN_grow, error); } -//static -gboolean -inkscape_selection_move (DocumentInterface *doc, const gdouble IN_x, const gdouble IN_y, GError **error) +// static +gboolean inkscape_selection_move(DocumentInterface *doc, const gdouble IN_x, const gdouble IN_y, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_move (proxy, IN_x, IN_y, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_move(proxy, IN_x, IN_y, error); } -//static -gboolean -inkscape_selection_move_to (DocumentInterface *doc, const gdouble IN_x, const gdouble IN_y, GError **error) +// static +gboolean inkscape_selection_move_to(DocumentInterface *doc, const gdouble IN_x, const gdouble IN_y, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_move_to (proxy, IN_x, IN_y, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_move_to(proxy, IN_x, IN_y, error); } -//static -gboolean -inkscape_selection_move_to_layer (DocumentInterface *doc, const char * IN_layer, GError **error) +// static +gboolean inkscape_selection_move_to_layer(DocumentInterface *doc, const char *IN_layer, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_move_to_layer (proxy, IN_layer, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_move_to_layer(proxy, IN_layer, error); } -//static -GArray * -inkscape_selection_get_center (DocumentInterface *doc, GError **error) +// static +GArray *inkscape_selection_get_center(DocumentInterface *doc, GError **error) { - GArray* OUT_centerpoint; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_selection_get_center (proxy, &OUT_centerpoint, error); - return OUT_centerpoint; + GArray *OUT_centerpoint; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_selection_get_center(proxy, &OUT_centerpoint, error); + return OUT_centerpoint; } -//static -gboolean -inkscape_selection_to_path (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_selection_to_path(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_selection_to_path (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_selection_to_path(proxy, error); } -//static -char ** -inkscape_selection_combine (DocumentInterface *doc, const char * IN_type, GError **error) +// static +char **inkscape_selection_combine(DocumentInterface *doc, const char *IN_type, GError **error) { - char ** OUT_newpaths; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_selection_combine (proxy, IN_type, &OUT_newpaths, error); - return OUT_newpaths; + char **OUT_newpaths; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_selection_combine(proxy, IN_type, &OUT_newpaths, error); + return OUT_newpaths; } -//static -gboolean -inkscape_selection_change_level (DocumentInterface *doc, const char * IN_command, GError **error) +// static +gboolean inkscape_selection_change_level(DocumentInterface *doc, const char *IN_command, GError **error) { - gboolean OUT_objectsmoved; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_selection_change_level (proxy, IN_command, &OUT_objectsmoved, error); - return OUT_objectsmoved; + gboolean OUT_objectsmoved; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_selection_change_level(proxy, IN_command, &OUT_objectsmoved, error); + return OUT_objectsmoved; } -//static -char * -inkscape_layer_new (DocumentInterface *doc, GError **error) +// static +char *inkscape_layer_new(DocumentInterface *doc, GError **error) { - char * OUT_layername; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_layer_new (proxy, &OUT_layername, error); - return OUT_layername; + char *OUT_layername; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_layer_new(proxy, &OUT_layername, error); + return OUT_layername; } -//static -gboolean -inkscape_layer_set (DocumentInterface *doc, const char * IN_layer, GError **error) +// static +gboolean inkscape_layer_set(DocumentInterface *doc, const char *IN_layer, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_layer_set (proxy, IN_layer, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_layer_set(proxy, IN_layer, error); } -//static -char ** -inkscape_layer_get_all (DocumentInterface *doc, GError **error) +// static +char **inkscape_layer_get_all(DocumentInterface *doc, GError **error) { - char ** OUT_layers; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_layer_get_all (proxy, &OUT_layers, error); - return OUT_layers; + char **OUT_layers; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_layer_get_all(proxy, &OUT_layers, error); + return OUT_layers; } -//static -gboolean -inkscape_layer_change_level (DocumentInterface *doc, const char * IN_command, GError **error) +// static +gboolean inkscape_layer_change_level(DocumentInterface *doc, const char *IN_command, GError **error) { - gboolean OUT_layermoved; - DBusGProxy *proxy = doc->proxy; - org_inkscape_document_layer_change_level (proxy, IN_command, &OUT_layermoved, error); - return OUT_layermoved; + gboolean OUT_layermoved; + DBusGProxy *proxy = doc->proxy; + org_inkscape_document_layer_change_level(proxy, IN_command, &OUT_layermoved, error); + return OUT_layermoved; } -//static -gboolean -inkscape_layer_next (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_layer_next(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_layer_next (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_layer_next(proxy, error); } -//static -gboolean -inkscape_layer_previous (DocumentInterface *doc, GError **error) +// static +gboolean inkscape_layer_previous(DocumentInterface *doc, GError **error) { - DBusGProxy *proxy = doc->proxy; - return org_inkscape_document_layer_previous (proxy, error); + DBusGProxy *proxy = doc->proxy; + return org_inkscape_document_layer_previous(proxy, error); } /* int -main (int argc, char** argv) +main (int argc, char** argv) { gchar * result; GError *error = NULL; DocumentInterface * doc = inkscape_desktop_init_dbus (); result = rectangle (doc->proxy, 10, 10, 100, 100, &error); printf("RESULT: %s\n", result); - - //dbus_g_proxy_call(doc->proxy, "rectangle", &error, G_TYPE_INT, 100, G_TYPE_INT, 100, G_TYPE_INT, 100, G_TYPE_INT, 100, G_TYPE_INVALID, G_TYPE_INVALID); - printf("yes\n"); + + //dbus_g_proxy_call(doc->proxy, "rectangle", &error, G_TYPE_INT, 100, G_TYPE_INT, 100, G_TYPE_INT, 100, G_TYPE_INT, +100, G_TYPE_INVALID, G_TYPE_INVALID); printf("yes\n"); } */ - diff --git a/src/extension/dbus/wrapper/inkscape-dbus-wrapper.h b/src/extension/dbus/wrapper/inkscape-dbus-wrapper.h index e2abd305e0708a2b222f1e55b84cb11b958c45d1..d641bbb071e5db7d79dece9ff8010df0f01ceee6 100644 --- a/src/extension/dbus/wrapper/inkscape-dbus-wrapper.h +++ b/src/extension/dbus/wrapper/inkscape-dbus-wrapper.h @@ -10,20 +10,22 @@ #ifndef INKSCAPE_EXTENSION_DOCUMENT_INTERFACE_H_ #define INKSCAPE_EXTENSION_DOCUMENT_INTERFACE_H_ -#include #include +#include //#include "document-client-glue-mod.h" //#include //#include - -#define TYPE_DOCUMENT_INTERFACE (document_interface_get_type ()) -#define DOCUMENT_INTERFACE(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), TYPE_DOCUMENT_INTERFACE, DocumentInterface)) -#define DOCUMENT_INTERFACE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), TYPE_DOCUMENT_INTERFACE, DocumentInterfaceClass)) -#define IS_DOCUMENT_INTERFACE(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), TYPE_DOCUMENT_INTERFACE)) -#define IS_DOCUMENT_INTERFACE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), TYPE_DOCUMENT_INTERFACE)) -#define DOCUMENT_INTERFACE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), TYPE_DOCUMENT_INTERFACE, DocumentInterfaceClass)) + +#define TYPE_DOCUMENT_INTERFACE (document_interface_get_type()) +#define DOCUMENT_INTERFACE(object) (G_TYPE_CHECK_INSTANCE_CAST((object), TYPE_DOCUMENT_INTERFACE, DocumentInterface)) +#define DOCUMENT_INTERFACE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass), TYPE_DOCUMENT_INTERFACE, DocumentInterfaceClass)) +#define IS_DOCUMENT_INTERFACE(object) (G_TYPE_CHECK_INSTANCE_TYPE((object), TYPE_DOCUMENT_INTERFACE)) +#define IS_DOCUMENT_INTERFACE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), TYPE_DOCUMENT_INTERFACE)) +#define DOCUMENT_INTERFACE_GET_CLASS(obj) \ + (G_TYPE_INSTANCE_GET_CLASS((obj), TYPE_DOCUMENT_INTERFACE, DocumentInterfaceClass)) G_BEGIN_DECLS @@ -32,315 +34,254 @@ typedef struct _DocumentInterfaceClass DocumentInterfaceClass; struct _DocumentInterface; -struct _DocumentInterfaceClass { - GObjectClass parent; +struct _DocumentInterfaceClass +{ + GObjectClass parent; }; +DocumentInterface *document_interface_new(void); +GType document_interface_get_type(void); -DocumentInterface *document_interface_new (void); -GType document_interface_get_type (void); - - - -DocumentInterface * -inkscape_desktop_init_dbus (); +DocumentInterface *inkscape_desktop_init_dbus(); -//static -gboolean -inkscape_delete_all (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_delete_all(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_call_verb (DocumentInterface *doc, const char * IN_verbid, GError **error); +// static +gboolean inkscape_call_verb(DocumentInterface *doc, const char *IN_verbid, GError **error); - -//static -gchar * -inkscape_rectangle (DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_width, const gint IN_height, GError **error); +// static +gchar *inkscape_rectangle(DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_width, + const gint IN_height, GError **error); -//static -char * -inkscape_ellipse (DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_width, const gint IN_height, GError **error); +// static +char *inkscape_ellipse(DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_width, + const gint IN_height, GError **error); -//static -char * -inkscape_polygon (DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_radius, const gint IN_rotation, const gint IN_sides, GError **error); +// static +char *inkscape_polygon(DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_radius, + const gint IN_rotation, const gint IN_sides, GError **error); -//static -char * -inkscape_star (DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_r1, const gint IN_r2, const gdouble IN_arg1, const gdouble IN_arg2, const gint IN_sides, const gdouble IN_rounded, GError **error); +// static +char *inkscape_star(DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_r1, const gint IN_r2, + const gdouble IN_arg1, const gdouble IN_arg2, const gint IN_sides, const gdouble IN_rounded, + GError **error); -//static -char * -inkscape_spiral (DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_r, const gint IN_revolutions, GError **error); +// static +char *inkscape_spiral(DocumentInterface *doc, const gint IN_cx, const gint IN_cy, const gint IN_r, + const gint IN_revolutions, GError **error); -//static -char * -inkscape_line (DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_x2, const gint IN_y2, GError **error); +// static +char *inkscape_line(DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_x2, const gint IN_y2, + GError **error); -//static -char * -inkscape_text (DocumentInterface *doc, const gint IN_x, const gint IN_y, const char * IN_text, GError **error); +// static +char *inkscape_text(DocumentInterface *doc, const gint IN_x, const gint IN_y, const char *IN_text, GError **error); -//static -char * -inkscape_image (DocumentInterface *doc, const gint IN_x, const gint IN_y, const char * IN_text, GError **error); +// static +char *inkscape_image(DocumentInterface *doc, const gint IN_x, const gint IN_y, const char *IN_text, GError **error); -//static -char * -inkscape_node (DocumentInterface *doc, const char * IN_svgtype, GError **error); +// static +char *inkscape_node(DocumentInterface *doc, const char *IN_svgtype, GError **error); -//static -gdouble -inkscape_document_get_width (DocumentInterface *doc, GError **error); +// static +gdouble inkscape_document_get_width(DocumentInterface *doc, GError **error); -//static -gdouble -inkscape_document_get_height (DocumentInterface *doc, GError **error); +// static +gdouble inkscape_document_get_height(DocumentInterface *doc, GError **error); -//static -char * -inkscape_document_get_css (DocumentInterface *doc, GError **error); +// static +char *inkscape_document_get_css(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_document_set_css (DocumentInterface *doc, const char * IN_stylestring, GError **error); +// static +gboolean inkscape_document_set_css(DocumentInterface *doc, const char *IN_stylestring, GError **error); -//static -gboolean -inkscape_document_merge_css (DocumentInterface *doc, const char * IN_stylestring, GError **error); +// static +gboolean inkscape_document_merge_css(DocumentInterface *doc, const char *IN_stylestring, GError **error); -//static -gboolean -inkscape_document_resize_to_fit_selection (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_document_resize_to_fit_selection(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_set_attribute (DocumentInterface *doc, const char * IN_shape, const char * IN_attribute, const char * IN_newval, GError **error); +// static +gboolean inkscape_set_attribute(DocumentInterface *doc, const char *IN_shape, const char *IN_attribute, + const char *IN_newval, GError **error); -//static -gboolean -inkscape_set_int_attribute (DocumentInterface *doc, const char * IN_shape, const char * IN_attribute, const gint IN_newval, GError **error); +// static +gboolean inkscape_set_int_attribute(DocumentInterface *doc, const char *IN_shape, const char *IN_attribute, + const gint IN_newval, GError **error); -//static -gboolean -inkscape_set_double_attribute (DocumentInterface *doc, const char * IN_shape, const char * IN_attribute, const gdouble IN_newval, GError **error); +// static +gboolean inkscape_set_double_attribute(DocumentInterface *doc, const char *IN_shape, const char *IN_attribute, + const gdouble IN_newval, GError **error); -//static -char * -inkscape_get_attribute (DocumentInterface *doc, const char * IN_shape, const char * IN_attribute, GError **error); +// static +char *inkscape_get_attribute(DocumentInterface *doc, const char *IN_shape, const char *IN_attribute, GError **error); -//static -gboolean -inkscape_move (DocumentInterface *doc, const char * IN_shape, const gdouble IN_x, const gdouble IN_y, GError **error); +// static +gboolean inkscape_move(DocumentInterface *doc, const char *IN_shape, const gdouble IN_x, const gdouble IN_y, + GError **error); -//static -gboolean -inkscape_move_to (DocumentInterface *doc, const char * IN_shape, const gdouble IN_x, const gdouble IN_y, GError **error); +// static +gboolean inkscape_move_to(DocumentInterface *doc, const char *IN_shape, const gdouble IN_x, const gdouble IN_y, + GError **error); -//static -gboolean -inkscape_object_to_path (DocumentInterface *doc, const char * IN_objectname, GError **error); +// static +gboolean inkscape_object_to_path(DocumentInterface *doc, const char *IN_objectname, GError **error); -//static -char * -inkscape_get_path (DocumentInterface *doc, const char * IN_shape, GError **error); +// static +char *inkscape_get_path(DocumentInterface *doc, const char *IN_shape, GError **error); -//static -gboolean -inkscape_transform (DocumentInterface *doc, const char * IN_shape, const char * IN_transformstr, GError **error); +// static +gboolean inkscape_transform(DocumentInterface *doc, const char *IN_shape, const char *IN_transformstr, GError **error); -//static -char * -inkscape_get_css (DocumentInterface *doc, const char * IN_shape, GError **error); +// static +char *inkscape_get_css(DocumentInterface *doc, const char *IN_shape, GError **error); -//static -gboolean -inkscape_modify_css (DocumentInterface *doc, const char * IN_shape, const char * IN_cssattrib, const char * IN_newval, GError **error); +// static +gboolean inkscape_modify_css(DocumentInterface *doc, const char *IN_shape, const char *IN_cssattrib, + const char *IN_newval, GError **error); -//static -gboolean -inkscape_inkscape_merge_css (DocumentInterface *doc, const char * IN_shape, const char * IN_stylestring, GError **error); +// static +gboolean inkscape_inkscape_merge_css(DocumentInterface *doc, const char *IN_shape, const char *IN_stylestring, + GError **error); -//static -gboolean -inkscape_set_color (DocumentInterface *doc, const char * IN_shape, const gint IN_red, const gint IN_green, const gint IN_blue, const gboolean IN_fill, GError **error); +// static +gboolean inkscape_set_color(DocumentInterface *doc, const char *IN_shape, const gint IN_red, const gint IN_green, + const gint IN_blue, const gboolean IN_fill, GError **error); -//static -gboolean -inkscape_move_to_layer (DocumentInterface *doc, const char * IN_objectname, const char * IN_layername, GError **error); +// static +gboolean inkscape_move_to_layer(DocumentInterface *doc, const char *IN_objectname, const char *IN_layername, + GError **error); -//static -GArray* -inkscape_get_node_coordinates (DocumentInterface *doc, const char * IN_shape, GError **error); +// static +GArray *inkscape_get_node_coordinates(DocumentInterface *doc, const char *IN_shape, GError **error); -//static -gboolean -inkscape_save (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_save(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_save_as (DocumentInterface *doc, const char * IN_pathname, GError **error); +// static +gboolean inkscape_save_as(DocumentInterface *doc, const char *IN_pathname, GError **error); -//static -gboolean -inkscape_load (DocumentInterface *doc, const char * IN_pathname, GError **error); +// static +gboolean inkscape_load(DocumentInterface *doc, const char *IN_pathname, GError **error); -//static -gboolean -inkscape_mark_as_unmodified (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_mark_as_unmodified(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_close (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_close(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_inkscape_exit (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_inkscape_exit(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_undo (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_undo(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_redo (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_redo(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_pause_updates (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_pause_updates(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_resume_updates (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_resume_updates(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_update (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_update(DocumentInterface *doc, GError **error); -//static -char ** -inkscape_selection_get (DocumentInterface *doc, GError **error); +// static +char **inkscape_selection_get(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_selection_add (DocumentInterface *doc, const char * IN_name, GError **error); +// static +gboolean inkscape_selection_add(DocumentInterface *doc, const char *IN_name, GError **error); -//static -gboolean -inkscape_selection_add_list (DocumentInterface *doc, const char ** IN_name, GError **error); +// static +gboolean inkscape_selection_add_list(DocumentInterface *doc, const char **IN_name, GError **error); -//static -gboolean -inkscape_selection_set (DocumentInterface *doc, const char * IN_name, GError **error); +// static +gboolean inkscape_selection_set(DocumentInterface *doc, const char *IN_name, GError **error); -//static -gboolean -inkscape_selection_set_list (DocumentInterface *doc, const char ** IN_name, GError **error); +// static +gboolean inkscape_selection_set_list(DocumentInterface *doc, const char **IN_name, GError **error); -//static -gboolean -inkscape_selection_rotate (DocumentInterface *doc, const gint IN_angle, GError **error); +// static +gboolean inkscape_selection_rotate(DocumentInterface *doc, const gint IN_angle, GError **error); -//static -gboolean -inkscape_selection_delete (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_selection_delete(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_selection_clear (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_selection_clear(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_select_all (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_select_all(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_select_all_in_all_layers (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_select_all_in_all_layers(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_selection_box (DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_x2, const gint IN_y2, const gboolean IN_replace, GError **error); +// static +gboolean inkscape_selection_box(DocumentInterface *doc, const gint IN_x, const gint IN_y, const gint IN_x2, + const gint IN_y2, const gboolean IN_replace, GError **error); -//static -gboolean -inkscape_selection_invert (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_selection_invert(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_selection_group (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_selection_group(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_selection_ungroup (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_selection_ungroup(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_selection_cut (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_selection_cut(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_selection_copy (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_selection_copy(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_selection_paste (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_selection_paste(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_selection_scale (DocumentInterface *doc, const gdouble IN_grow, GError **error); +// static +gboolean inkscape_selection_scale(DocumentInterface *doc, const gdouble IN_grow, GError **error); -//static -gboolean -inkscape_selection_move (DocumentInterface *doc, const gdouble IN_x, const gdouble IN_y, GError **error); +// static +gboolean inkscape_selection_move(DocumentInterface *doc, const gdouble IN_x, const gdouble IN_y, GError **error); -//static -gboolean -inkscape_selection_move_to (DocumentInterface *doc, const gdouble IN_x, const gdouble IN_y, GError **error); +// static +gboolean inkscape_selection_move_to(DocumentInterface *doc, const gdouble IN_x, const gdouble IN_y, GError **error); -//static -gboolean -inkscape_selection_move_to_layer (DocumentInterface *doc, const char * IN_layer, GError **error); +// static +gboolean inkscape_selection_move_to_layer(DocumentInterface *doc, const char *IN_layer, GError **error); -//static -GArray * -inkscape_selection_get_center (DocumentInterface *doc, GError **error); +// static +GArray *inkscape_selection_get_center(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_selection_to_path (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_selection_to_path(DocumentInterface *doc, GError **error); -//static -char ** -inkscape_selection_combine (DocumentInterface *doc, const char * IN_type, GError **error); +// static +char **inkscape_selection_combine(DocumentInterface *doc, const char *IN_type, GError **error); -//static -gboolean -inkscape_selection_change_level (DocumentInterface *doc, const char * IN_command, GError **error); +// static +gboolean inkscape_selection_change_level(DocumentInterface *doc, const char *IN_command, GError **error); -//static -char * -inkscape_layer_new (DocumentInterface *doc, GError **error); +// static +char *inkscape_layer_new(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_layer_set (DocumentInterface *doc, const char * IN_layer, GError **error); +// static +gboolean inkscape_layer_set(DocumentInterface *doc, const char *IN_layer, GError **error); -//static -char ** -inkscape_layer_get_all (DocumentInterface *doc, GError **error); +// static +char **inkscape_layer_get_all(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_layer_change_level (DocumentInterface *doc, const char * IN_command, GError **error); +// static +gboolean inkscape_layer_change_level(DocumentInterface *doc, const char *IN_command, GError **error); -//static -gboolean -inkscape_layer_next (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_layer_next(DocumentInterface *doc, GError **error); -//static -gboolean -inkscape_layer_previous (DocumentInterface *doc, GError **error); +// static +gboolean inkscape_layer_previous(DocumentInterface *doc, GError **error); G_END_DECLS diff --git a/src/extension/dependency.cpp b/src/extension/dependency.cpp index 3ecaa72b03c49c971cb7e1e82349805761fc5c84..dcd0acf91f46cb130c55f2c16b8462185db3016b 100644 --- a/src/extension/dependency.cpp +++ b/src/extension/dependency.cpp @@ -9,10 +9,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "dependency.h" + #include +#include #include -#include "dependency.h" + #include "db.h" #include "extension.h" #include "io/resource.h" @@ -22,7 +24,7 @@ namespace Extension { // These strings are for XML attribute comparisons and should not be translated; // make sure to keep in sync with enum defined in dependency.h -gchar const * Dependency::_type_str[] = { +gchar const *Dependency::_type_str[] = { "executable", "file", "extension", @@ -30,7 +32,7 @@ gchar const * Dependency::_type_str[] = { // These strings are for XML attribute comparisons and should not be translated // make sure to keep in sync with enum defined in dependency.h -gchar const * Dependency::_location_str[] = { +gchar const *Dependency::_location_str[] = { "path", "extensions", "inx", @@ -48,21 +50,21 @@ gchar const * Dependency::_location_str[] = { a little bit easier to use later. Also, a pointer to the core content is pulled out -- also to make things easier. */ -Dependency::Dependency (Inkscape::XML::Node * in_repr, const Extension *extension, type_t default_type) +Dependency::Dependency(Inkscape::XML::Node *in_repr, const Extension *extension, type_t default_type) : _repr(in_repr) , _extension(extension) , _type(default_type) { Inkscape::GC::anchor(_repr); - if (const gchar * location = _repr->attribute("location")) { + if (const gchar *location = _repr->attribute("location")) { for (int i = 0; i < LOCATION_CNT && location != nullptr; i++) { if (!strcmp(location, _location_str[i])) { _location = (location_t)i; break; } } - } else if (const gchar * location = _repr->attribute("reldir")) { // backwards-compatibility + } else if (const gchar *location = _repr->attribute("reldir")) { // backwards-compatibility for (int i = 0; i < LOCATION_CNT && location != nullptr; i++) { if (!strcmp(location, _location_str[i])) { _location = (location_t)i; @@ -71,7 +73,7 @@ Dependency::Dependency (Inkscape::XML::Node * in_repr, const Extension *extensio } } - const gchar * type = _repr->attribute("type"); + const gchar *type = _repr->attribute("type"); for (int i = 0; i < TYPE_CNT && type != nullptr; i++) { if (!strcmp(type, _type_str[i])) { _type = (type_t)i; @@ -93,7 +95,7 @@ Dependency::Dependency (Inkscape::XML::Node * in_repr, const Extension *extensio Unreference the XML structure. */ -Dependency::~Dependency () +Dependency::~Dependency() { Inkscape::GC::release(_repr); } @@ -128,7 +130,7 @@ Dependency::~Dependency () found then a TRUE is returned. If we get all the way through the path then a FALSE is returned, the command could not be found. */ -bool Dependency::check () +bool Dependency::check() { if (_string == nullptr) { return false; @@ -138,9 +140,11 @@ bool Dependency::check () switch (_type) { case TYPE_EXTENSION: { - Extension * myext = db.get(_string); - if (myext == nullptr) return false; - if (myext->deactivated()) return false; + Extension *myext = db.get(_string); + if (myext == nullptr) + return false; + if (myext->deactivated()) + return false; break; } case TYPE_EXECUTABLE: @@ -159,8 +163,7 @@ bool Dependency::check () // check interpreted scripts as "file" for backwards-compatibility, even if "executable" was requested static const std::vector interpreted = {".py", ".pl", ".rb"}; if (!extension.empty() && - std::find(interpreted.begin(), interpreted.end(), extension) != interpreted.end()) - { + std::find(interpreted.begin(), interpreted.end(), extension) != interpreted.end()) { _type = TYPE_FILE; } @@ -176,8 +179,8 @@ bool Dependency::check () switch (_location) { case LOCATION_EXTENSIONS: { // get_filename will warn if the resource isn't found, while returning an empty string. - std::string temploc = - Inkscape::IO::Resource::get_filename_string(Inkscape::IO::Resource::EXTENSIONS, location.c_str()); + std::string temploc = Inkscape::IO::Resource::get_filename_string( + Inkscape::IO::Resource::EXTENSIONS, location.c_str()); if (!temploc.empty()) { location = temploc; _absolute_location = temploc; @@ -185,8 +188,8 @@ bool Dependency::check () } /* Look for deprecated locations next */ auto deprloc = g_build_filename("inkex", "deprecated-simple", location.c_str(), NULL); - std::string tempdepr = - Inkscape::IO::Resource::get_filename_string(Inkscape::IO::Resource::EXTENSIONS, deprloc, false, true); + std::string tempdepr = Inkscape::IO::Resource::get_filename_string( + Inkscape::IO::Resource::EXTENSIONS, deprloc, false, true); g_free(deprloc); if (!tempdepr.empty()) { location = tempdepr; @@ -207,7 +210,8 @@ bool Dependency::check () std::string base_directory = _extension->get_base_directory(); if (base_directory.empty()) { g_warning("Dependency '%s' requests location relative to .inx file, " - "which is unknown for extension '%s'", _string, _extension->get_id()); + "which is unknown for extension '%s'", + _string, _extension->get_id()); } std::string absolute_location = Glib::build_filename(base_directory, location); if (!Glib::file_test(absolute_location, filetest)) { @@ -221,7 +225,7 @@ bool Dependency::check () default: { // TODO: we can likely use g_find_program_in_path (or its glibmm equivalent) for executable types - gchar * path = g_strdup(g_getenv("PATH")); + gchar *path = g_strdup(g_getenv("PATH")); if (path == nullptr) { /* There is no `PATH' in the environment. @@ -229,10 +233,10 @@ bool Dependency::check () path = g_strdup(G_SEARCHPATH_SEPARATOR_S); } - gchar * orig_path = path; + gchar *orig_path = path; for (; path != nullptr;) { - gchar * local_path; // to have the path after detection of the separator + gchar *local_path; // to have the path after detection of the separator std::string final_name; local_path = path; @@ -265,8 +269,7 @@ bool Dependency::check () if (_type == TYPE_EXECUTABLE) { static const std::vector extensions = {".exe", ".cmd", ".bat", ".com"}; if (extension.empty() || - std::find(extensions.begin(), extensions.end(), extension) == extensions.end()) - { + std::find(extensions.begin(), extensions.end(), extension) == extensions.end()) { for (auto extension : extensions) { if (Glib::file_test(final_name + extension, filetest)) { g_free(orig_path); @@ -299,7 +302,7 @@ bool Dependency::check () Returns the name of the dependency as found in the configuration file. */ -const gchar* Dependency::get_name() +const gchar *Dependency::get_name() { return _string; } @@ -331,11 +334,9 @@ std::string Dependency::get_path() */ Glib::ustring Dependency::info_string() { - Glib::ustring str = Glib::ustring::compose("%1:\n\t%2: %3\n\t%4: %5\n\t%6: %7", - _("Dependency"), - _("type"), _(_type_str[_type]), - _("location"), _(_location_str[_location]), - _("string"), _string); + Glib::ustring str = + Glib::ustring::compose("%1:\n\t%2: %3\n\t%4: %5\n\t%6: %7", _("Dependency"), _("type"), _(_type_str[_type]), + _("location"), _(_location_str[_location]), _("string"), _string); if (_description) { str += Glib::ustring::compose("\n\t%1: %2\n", _(" description: "), _(_description)); @@ -344,7 +345,8 @@ Glib::ustring Dependency::info_string() return str; } -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/dependency.h b/src/extension/dependency.h index e2c2791120e16863c9870185163506a4c386dce0..b1f33ced1dc60034e7e4bc6799957b0ce0603621 100644 --- a/src/extension/dependency.h +++ b/src/extension/dependency.h @@ -12,6 +12,7 @@ #define INKSCAPE_EXTENSION_DEPENDENCY_H__ #include + #include "xml/repr.h" namespace Inkscape { @@ -22,19 +23,21 @@ class Extension; /** \brief A class to represent a dependency for an extension. There are different things that can be done in a dependency, and this class takes care of all of them. */ -class Dependency { - +class Dependency +{ public: /** \brief All the possible types of dependencies. */ - enum type_t { + enum type_t + { TYPE_EXECUTABLE, /**< Look for an executable */ TYPE_FILE, /**< Look to make sure a file exists */ TYPE_EXTENSION, /**< Make sure a specific extension is loaded and functional */ TYPE_CNT /**< Number of types */ }; - + /** \brief All of the possible locations to look for the dependency. */ - enum location_t { + enum location_t + { LOCATION_PATH, /**< Look in the PATH for this dependency - historically this is the default (it's a bit odd for interpreted script files but makes sense for other executables) */ LOCATION_EXTENSIONS, /**< Look in the extensions directory @@ -43,18 +46,18 @@ public: LOCATION_ABSOLUTE, /**< This dependency is already defined in absolute terms */ LOCATION_CNT /**< Number of locations to look */ }; - + private: static constexpr const char *UNCHECKED = "---unchecked---"; - + /** \brief The XML representation of the dependency. */ - Inkscape::XML::Node * _repr; + Inkscape::XML::Node *_repr; /** \brief The string that is in the XML tags pulled out. */ - const gchar * _string = nullptr; + const gchar *_string = nullptr; /** \brief The description of the dependency for the users. */ - const gchar * _description = nullptr; + const gchar *_description = nullptr; /** \brief The absolute path to the dependency file determined while checking this dependency. */ - std::string _absolute_location = UNCHECKED; + std::string _absolute_location = UNCHECKED; /** \brief Storing the type of this particular dependency. */ type_t _type = TYPE_FILE; @@ -63,26 +66,26 @@ private: /** \brief Strings to represent the different enum values in \c type_t in the XML */ - static gchar const * _type_str[TYPE_CNT]; + static gchar const *_type_str[TYPE_CNT]; /** \brief Strings to represent the different enum values in \c location_t in the XML */ - static gchar const * _location_str[LOCATION_CNT]; + static gchar const *_location_str[LOCATION_CNT]; /** \brief Reference to the extension requesting this dependency. */ const Extension *_extension; public: - Dependency (Inkscape::XML::Node *in_repr, const Extension *extension, type_t type=TYPE_FILE); - virtual ~Dependency (); + Dependency(Inkscape::XML::Node *in_repr, const Extension *extension, type_t type = TYPE_FILE); + virtual ~Dependency(); bool check(); - const gchar* get_name(); + const gchar *get_name(); std::string get_path(); Glib::ustring info_string(); }; /* class Dependency */ - -} } /* namespace Extension, Inkscape */ +} // namespace Extension +} // namespace Inkscape #endif /* INKSCAPE_EXTENSION_DEPENDENCY_H__ */ diff --git a/src/extension/effect.cpp b/src/extension/effect.cpp index 1a39d4bbda0bc33e8e7ace23cf113434b930d6a8..321c1e6d7a54eba85e58b941b505682d678b68e8 100644 --- a/src/extension/effect.cpp +++ b/src/extension/effect.cpp @@ -12,38 +12,36 @@ #include "effect.h" #include "execution-env.h" -#include "inkscape.h" -#include "timer.h" - #include "helper/action.h" #include "implementation/implementation.h" +#include "inkscape.h" #include "prefdialog/prefdialog.h" +#include "timer.h" #include "ui/view/view.h" - - /* Inkscape::Extension::Effect */ namespace Inkscape { namespace Extension { -Effect * Effect::_last_effect = nullptr; -Inkscape::XML::Node * Effect::_effects_list = nullptr; -Inkscape::XML::Node * Effect::_filters_list = nullptr; +Effect *Effect::_last_effect = nullptr; +Inkscape::XML::Node *Effect::_effects_list = nullptr; +Inkscape::XML::Node *Effect::_filters_list = nullptr; -#define EFFECTS_LIST "effects-list" -#define FILTERS_LIST "filters-list" +#define EFFECTS_LIST "effects-list" +#define FILTERS_LIST "filters-list" -Effect::Effect (Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory) +Effect::Effect(Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory) : Extension(in_repr, in_imp, base_directory) , _id_noprefs(Glib::ustring(get_id()) + ".noprefs") , _name_noprefs(Glib::ustring(_(get_name())) + _(" (No preferences)")) , _verb(get_id(), get_name(), nullptr, nullptr, this, true) , _verb_nopref(_id_noprefs.c_str(), _name_noprefs.c_str(), nullptr, nullptr, this, false) - , _menu_node(nullptr), _workingDialog(true) + , _menu_node(nullptr) + , _workingDialog(true) , _prefDialog(nullptr) { - Inkscape::XML::Node * local_effects_menu = nullptr; + Inkscape::XML::Node *local_effects_menu = nullptr; // This is a weird hack if (!strcmp(this->get_id(), "org.inkscape.filter.dropshadow")) @@ -55,19 +53,21 @@ Effect::Effect (Inkscape::XML::Node *in_repr, Implementation::Implementation *in no_live_preview = false; if (repr != nullptr) { - for (Inkscape::XML::Node *child = repr->firstChild(); child != nullptr; child = child->next()) { if (!strcmp(child->name(), INKSCAPE_EXTENSION_NS "effect")) { if (child->attribute("needs-document") && !strcmp(child->attribute("needs-document"), "false")) { no_doc = true; } - if (child->attribute("needs-live-preview") && !strcmp(child->attribute("needs-live-preview"), "false")) { + if (child->attribute("needs-live-preview") && + !strcmp(child->attribute("needs-live-preview"), "false")) { no_live_preview = true; } - if (child->attribute("implements-custom-gui") && !strcmp(child->attribute("implements-custom-gui"), "true")) { + if (child->attribute("implements-custom-gui") && + !strcmp(child->attribute("implements-custom-gui"), "true")) { _workingDialog = false; } - for (Inkscape::XML::Node *effect_child = child->firstChild(); effect_child != nullptr; effect_child = effect_child->next()) { + for (Inkscape::XML::Node *effect_child = child->firstChild(); effect_child != nullptr; + effect_child = effect_child->next()) { if (!strcmp(effect_child->name(), INKSCAPE_EXTENSION_NS "effects-menu")) { // printf("Found local effects menu in %s\n", this->get_name()); local_effects_menu = effect_child->firstChild(); @@ -76,20 +76,20 @@ Effect::Effect (Inkscape::XML::Node *in_repr, Implementation::Implementation *in } } if (!strcmp(effect_child->name(), INKSCAPE_EXTENSION_NS "menu-name") || - !strcmp(effect_child->name(), INKSCAPE_EXTENSION_NS "_menu-name")) { + !strcmp(effect_child->name(), INKSCAPE_EXTENSION_NS "_menu-name")) { // printf("Found local effects menu in %s\n", this->get_name()); _verb.set_name(effect_child->firstChild()->content()); } if (!strcmp(effect_child->name(), INKSCAPE_EXTENSION_NS "menu-tip") || - !strcmp(effect_child->name(), INKSCAPE_EXTENSION_NS "_menu-tip")) { + !strcmp(effect_child->name(), INKSCAPE_EXTENSION_NS "_menu-tip")) { // printf("Found local effects menu in %s\n", this->get_name()); _verb.set_tip(effect_child->firstChild()->content()); } - } // children of "effect" + } // children of "effect" break; // there can only be one effect - } // find "effect" - } // children of "inkscape-extension" - } // if we have an XML file + } // find "effect" + } // children of "inkscape-extension" + } // if we have an XML file // \TODO this gets called from the Inkscape::Application constructor, where it initializes the menus. // But in the constructor, our object isn't quite there yet! @@ -107,9 +107,7 @@ Effect::Effect (Inkscape::XML::Node *in_repr, Implementation::Implementation *in _menu_node->setAttribute("verb-id", this->get_id()); if (!hidden) { - if (_filters_list && - local_effects_menu && - local_effects_menu->attribute("name") && + if (_filters_list && local_effects_menu && local_effects_menu->attribute("name") && !strcmp(local_effects_menu->attribute("name"), ("Filters"))) { merge_menu(_filters_list->parent(), _filters_list, local_effects_menu->firstChild(), _menu_node); } else if (_effects_list) { @@ -121,14 +119,12 @@ Effect::Effect (Inkscape::XML::Node *in_repr, Implementation::Implementation *in return; } -void -Effect::merge_menu (Inkscape::XML::Node * base, - Inkscape::XML::Node * start, - Inkscape::XML::Node * pattern, - Inkscape::XML::Node * merge) { +void Effect::merge_menu(Inkscape::XML::Node *base, Inkscape::XML::Node *start, Inkscape::XML::Node *pattern, + Inkscape::XML::Node *merge) +{ Glib::ustring mergename; - Inkscape::XML::Node * tomerge = nullptr; - Inkscape::XML::Node * submenu = nullptr; + Inkscape::XML::Node *tomerge = nullptr; + Inkscape::XML::Node *submenu = nullptr; if (pattern == nullptr) { // Merge the verb name @@ -136,8 +132,10 @@ Effect::merge_menu (Inkscape::XML::Node * base, mergename = get_translation(get_name()); } else { gchar const *menuname = pattern->attribute("name"); - if (menuname == nullptr) menuname = pattern->attribute("_name"); - if (menuname == nullptr) return; + if (menuname == nullptr) + menuname = pattern->attribute("_name"); + if (menuname == nullptr) + return; Inkscape::XML::Document *xml_doc; xml_doc = base->document(); @@ -155,14 +153,15 @@ Effect::merge_menu (Inkscape::XML::Node * base, int position = -1; if (start != nullptr) { - Inkscape::XML::Node * menupass; - for (menupass = start; menupass != nullptr && strcmp(menupass->name(), "separator"); menupass = menupass->next()) { - gchar const * compare_char = nullptr; + Inkscape::XML::Node *menupass; + for (menupass = start; menupass != nullptr && strcmp(menupass->name(), "separator"); + menupass = menupass->next()) { + gchar const *compare_char = nullptr; if (!strcmp(menupass->name(), "verb")) { - gchar const * verbid = menupass->attribute("verb-id"); - Inkscape::Verb * verb = Inkscape::Verb::getbyid(verbid); + gchar const *verbid = menupass->attribute("verb-id"); + Inkscape::Verb *verb = Inkscape::Verb::getbyid(verbid); if (verb == nullptr) { - g_warning("Unable to find verb '%s' which is referred to in the menus.", verbid); + g_warning("Unable to find verb '%s' which is referred to in the menus.", verbid); continue; } compare_char = verb->get_name(); @@ -193,7 +192,7 @@ Effect::merge_menu (Inkscape::XML::Node * base, break; } } // for menu items - } // start != NULL + } // start != NULL if (tomerge != nullptr) { if (position != -1) { @@ -213,7 +212,7 @@ Effect::merge_menu (Inkscape::XML::Node * base, return; } -Effect::~Effect () +Effect::~Effect() { if (get_last_effect() == this) set_last_effect(nullptr); @@ -222,8 +221,7 @@ Effect::~Effect () return; } -bool -Effect::check () +bool Effect::check() { if (!Extension::check()) { _verb.sensitive(nullptr, false); @@ -233,8 +231,7 @@ Effect::check () return true; } -bool -Effect::prefs (Inkscape::UI::View::View * doc) +bool Effect::prefs(Inkscape::UI::View::View *doc) { if (_prefDialog != nullptr) { _prefDialog->raise(); @@ -248,7 +245,8 @@ Effect::prefs (Inkscape::UI::View::View * doc) if (!loaded()) set_state(Extension::STATE_LOADED); - if (!loaded()) return false; + if (!loaded()) + return false; Glib::ustring name = get_translation(this->get_name()); _prefDialog = new PrefDialog(name, nullptr, this); @@ -267,13 +265,13 @@ Effect::prefs (Inkscape::UI::View::View * doc) executes a \c SPDocumentUndo::done to commit the changes to the undo stack. */ -void -Effect::effect (Inkscape::UI::View::View * doc) +void Effect::effect(Inkscape::UI::View::View *doc) { - //printf("Execute effect\n"); + // printf("Execute effect\n"); if (!loaded()) set_state(Extension::STATE_LOADED); - if (!loaded()) return; + if (!loaded()) + return; ExecutionEnv executionEnv(this, doc, nullptr, _workingDialog, true); execution_env = &executionEnv; timer->lock(); @@ -297,8 +295,7 @@ Effect::effect (Inkscape::UI::View::View * doc) If the \c in_effect variable is \c NULL then the last effect verb is made insesitive. */ -void -Effect::set_last_effect (Effect * in_effect) +void Effect::set_last_effect(Effect *in_effect) { if (in_effect == nullptr) { Inkscape::Verb::get(SP_VERB_EFFECT_LAST)->sensitive(nullptr, false); @@ -312,19 +309,17 @@ Effect::set_last_effect (Effect * in_effect) return; } -Inkscape::XML::Node * -Effect::find_menu (Inkscape::XML::Node * menustruct, const gchar *name) +Inkscape::XML::Node *Effect::find_menu(Inkscape::XML::Node *menustruct, const gchar *name) { - if (menustruct == nullptr) return nullptr; - for (Inkscape::XML::Node * child = menustruct; - child != nullptr; - child = child->next()) { + if (menustruct == nullptr) + return nullptr; + for (Inkscape::XML::Node *child = menustruct; child != nullptr; child = child->next()) { if (!strcmp(child->name(), name)) { return child; } - Inkscape::XML::Node * firstchild = child->firstChild(); + Inkscape::XML::Node *firstchild = child->firstChild(); if (firstchild != nullptr) { - Inkscape::XML::Node *found = find_menu (firstchild, name); + Inkscape::XML::Node *found = find_menu(firstchild, name); if (found) return found; } @@ -332,43 +327,38 @@ Effect::find_menu (Inkscape::XML::Node * menustruct, const gchar *name) return nullptr; } - -Gtk::VBox * -Effect::get_info_widget() +Gtk::VBox *Effect::get_info_widget() { return Extension::get_info_widget(); } -PrefDialog * -Effect::get_pref_dialog () +PrefDialog *Effect::get_pref_dialog() { return _prefDialog; } -void -Effect::set_pref_dialog (PrefDialog * prefdialog) +void Effect::set_pref_dialog(PrefDialog *prefdialog) { _prefDialog = prefdialog; return; } -SPAction * -Effect::EffectVerb::make_action (Inkscape::ActionContext const & context) +SPAction *Effect::EffectVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform, static_cast(this)); } /** \brief Decode the verb code and take appropriate action */ -void -Effect::EffectVerb::perform( SPAction *action, void * data ) +void Effect::EffectVerb::perform(SPAction *action, void *data) { g_return_if_fail(ensure_desktop_valid(action)); - Inkscape::UI::View::View * current_view = sp_action_get_view(action); + Inkscape::UI::View::View *current_view = sp_action_get_view(action); - Effect::EffectVerb * ev = reinterpret_cast(data); - Effect * effect = ev->_effect; + Effect::EffectVerb *ev = reinterpret_cast(data); + Effect *effect = ev->_effect; - if (effect == nullptr) return; + if (effect == nullptr) + return; if (ev->_showPrefs) { effect->prefs(current_view); @@ -379,7 +369,8 @@ Effect::EffectVerb::perform( SPAction *action, void * data ) return; } -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/effect.h b/src/extension/effect.h index 11b252cf4050401644fc19965d1f27ba1c4d708a..7153c0162949bb12189d3b4ebef0207e17b183f5 100644 --- a/src/extension/effect.h +++ b/src/extension/effect.h @@ -8,23 +8,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #ifndef INKSCAPE_EXTENSION_EFFECT_H__ #define INKSCAPE_EXTENSION_EFFECT_H__ #include -#include "verbs.h" + #include "extension.h" +#include "verbs.h" namespace Gtk { - class VBox; +class VBox; } class SPDocument; namespace Inkscape { - namespace Extension { class PrefDialog; @@ -32,59 +31,62 @@ class PrefDialog; to it in place. This class adds the extra functions required to make extensions effects. */ -class Effect : public Extension { +class Effect : public Extension +{ /** \brief This is the last effect that was used. This is used in a menu item to rapidly recall the same effect. */ - static Effect * _last_effect; + static Effect *_last_effect; /** \brief The location of the Extensions and Filters menus on the menu structure XML file. This is saved so it only has to be discovered once. */ - static Inkscape::XML::Node * _effects_list; - static Inkscape::XML::Node * _filters_list; - Inkscape::XML::Node *find_menu (Inkscape::XML::Node * menustruct, const gchar *name); - void merge_menu (Inkscape::XML::Node * base, Inkscape::XML::Node * start, Inkscape::XML::Node * pattern, Inkscape::XML::Node * merge); + static Inkscape::XML::Node *_effects_list; + static Inkscape::XML::Node *_filters_list; + Inkscape::XML::Node *find_menu(Inkscape::XML::Node *menustruct, const gchar *name); + void merge_menu(Inkscape::XML::Node *base, Inkscape::XML::Node *start, Inkscape::XML::Node *pattern, + Inkscape::XML::Node *merge); /** \brief This is the verb type that is used for all effect's verbs. It provides convenience functions and maintains a pointer back to the effect that created it. */ - class EffectVerb : public Inkscape::Verb { - private: - static void perform (SPAction * action, void * mydata); - - /** \brief The effect that this verb represents. */ - Effect * _effect; - /** \brief Whether or not to show preferences on display */ - bool _showPrefs; - /** \brief Name with ellipses if that makes sense */ - gchar * _elip_name; - protected: - SPAction * make_action (Inkscape::ActionContext const & context) override; - public: - /** \brief Use the Verb initializer with the same parameters. */ - EffectVerb(gchar const * id, - gchar const * name, - gchar const * tip, - gchar const * image, - Effect * effect, - bool showPrefs) : - Verb(id, _(name), _(tip), image, _("Extensions")), - _effect(effect), - _showPrefs(showPrefs), - _elip_name(nullptr) { - /* No clue why, but this is required */ - this->set_default_sensitive(true); - if (_showPrefs && effect != nullptr && effect->widget_visible_count() != 0) { - _elip_name = g_strdup_printf("%s...", _(name)); - set_name(_elip_name); - } + class EffectVerb : public Inkscape::Verb + { + private: + static void perform(SPAction *action, void *mydata); + + /** \brief The effect that this verb represents. */ + Effect *_effect; + /** \brief Whether or not to show preferences on display */ + bool _showPrefs; + /** \brief Name with ellipses if that makes sense */ + gchar *_elip_name; + + protected: + SPAction *make_action(Inkscape::ActionContext const &context) override; + + public: + /** \brief Use the Verb initializer with the same parameters. */ + EffectVerb(gchar const *id, gchar const *name, gchar const *tip, gchar const *image, Effect *effect, + bool showPrefs) + : Verb(id, _(name), _(tip), image, _("Extensions")) + , _effect(effect) + , _showPrefs(showPrefs) + , _elip_name(nullptr) + { + /* No clue why, but this is required */ + this->set_default_sensitive(true); + if (_showPrefs && effect != nullptr && effect->widget_visible_count() != 0) { + _elip_name = g_strdup_printf("%s...", _(name)); + set_name(_elip_name); } + } - /** \brief Destructor */ - ~EffectVerb() override { - if (_elip_name != nullptr) { - g_free(_elip_name); - } + /** \brief Destructor */ + ~EffectVerb() override + { + if (_elip_name != nullptr) { + g_free(_elip_name); } + } }; /** \brief ID used for the verb without preferences */ @@ -97,42 +99,46 @@ class Effect : public Extension { /** \brief The verb representing this effect. Without preferences. */ EffectVerb _verb_nopref; /** \brief Menu node created for this effect */ - Inkscape::XML::Node * _menu_node; + Inkscape::XML::Node *_menu_node; /** \brief Whether a working dialog should be shown */ bool _workingDialog; /** \brief The preference dialog if it is shown */ - PrefDialog * _prefDialog; + PrefDialog *_prefDialog; + public: Effect(Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory); - ~Effect () override; + ~Effect() override; bool check() override; - bool prefs (Inkscape::UI::View::View * doc); - void effect (Inkscape::UI::View::View * doc); + bool prefs(Inkscape::UI::View::View *doc); + void effect(Inkscape::UI::View::View *doc); /** \brief Accessor function for a pointer to the verb */ - Inkscape::Verb * get_verb () { return &_verb; }; + Inkscape::Verb *get_verb() { return &_verb; }; /** \brief Static function to get the last effect used */ - static Effect * get_last_effect () { return _last_effect; }; - static void set_last_effect (Effect * in_effect); + static Effect *get_last_effect() { return _last_effect; }; + static void set_last_effect(Effect *in_effect); - static void place_menus (); - void place_menu (Inkscape::XML::Node * menus); + static void place_menus(); + void place_menu(Inkscape::XML::Node *menus); - Gtk::VBox * get_info_widget(); + Gtk::VBox *get_info_widget(); - bool no_doc; // if true, the effect does not process SVG document at all, so no need to save, read, and watch for errors + bool no_doc; // if true, the effect does not process SVG document at all, so no need to save, read, and watch for + // errors bool no_live_preview; // if true, the effect does not need "live preview" checkbox in its dialog - PrefDialog *get_pref_dialog (); - void set_pref_dialog (PrefDialog * prefdialog); + PrefDialog *get_pref_dialog(); + void set_pref_dialog(PrefDialog *prefdialog); + private: - static gchar * remove_ (gchar * instr); + static gchar *remove_(gchar *instr); }; -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape #endif /* INKSCAPE_EXTENSION_EFFECT_H__ */ /* diff --git a/src/extension/error-file.cpp b/src/extension/error-file.cpp index ad65457b2df135cc80dac8215d2a503acd6bb49d..513af795c39ad6335f9e166cb09f309731329801 100644 --- a/src/extension/error-file.cpp +++ b/src/extension/error-file.cpp @@ -8,19 +8,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/dialog/extensions.h" +#include "error-file.h" #include -#include "inkscape.h" -#include "preferences.h" + #include "extension/extension.h" +#include "inkscape.h" #include "io/resource.h" - -#include "error-file.h" +#include "preferences.h" +#include "ui/dialog/extensions.h" /** The name and group of the preference to say whether the error dialog should be shown on startup. */ -#define PREFERENCE_ID "/dialogs/extension-error/show-on-startup" +#define PREFERENCE_ID "/dialogs/extension-error/show-on-startup" namespace Inkscape { namespace Extension { @@ -35,20 +35,22 @@ namespace Extension { it should always be checked if you can see the dialog, but it is probably good to check anyway). */ -ErrorFileNotice::ErrorFileNotice () : - Gtk::MessageDialog( - "", /* message */ - false, /* use markup */ - Gtk::MESSAGE_WARNING, /* dialog type */ - Gtk::BUTTONS_OK, /* buttons */ - true /* modal */ - ) +ErrorFileNotice::ErrorFileNotice() + : Gtk::MessageDialog("", /* message */ + false, /* use markup */ + Gtk::MESSAGE_WARNING, /* dialog type */ + Gtk::BUTTONS_OK, /* buttons */ + true /* modal */ + ) { // \FIXME change this /* This is some filler text, needs to change before release */ - Glib::ustring dialog_text(_("One or more extensions failed to load\n\nThe failed extensions have been skipped. Inkscape will continue to run normally but those extensions will be unavailable. For details to troubleshoot this problem, please refer to the error log located at: ")); - gchar * ext_error_file = Inkscape::IO::Resource::log_path(EXTENSION_ERROR_LOG_FILENAME); + Glib::ustring dialog_text( + _("One or more extensions failed to load\n\nThe failed extensions " + "have been skipped. Inkscape will continue to run normally but those extensions will be unavailable. For " + "details to troubleshoot this problem, please refer to the error log located at: ")); + gchar *ext_error_file = Inkscape::IO::Resource::log_path(EXTENSION_ERROR_LOG_FILENAME); dialog_text += ext_error_file; g_free(ext_error_file); set_message(dialog_text, true); @@ -66,17 +68,16 @@ ErrorFileNotice::ErrorFileNotice () : set_resizable(true); - Inkscape::UI::Dialogs::ExtensionsPanel* extens = new Inkscape::UI::Dialogs::ExtensionsPanel(); + Inkscape::UI::Dialogs::ExtensionsPanel *extens = new Inkscape::UI::Dialogs::ExtensionsPanel(); extens->set_full(false); - vbox->pack_start( *extens, true, true ); + vbox->pack_start(*extens, true, true); extens->show(); return; } /** \brief Sets the preferences based on the checkbox value */ -void -ErrorFileNotice::checkbox_toggle () +void ErrorFileNotice::checkbox_toggle() { // std::cout << "Toggle value" << std::endl; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -88,8 +89,7 @@ ErrorFileNotice::checkbox_toggle () This function only shows the dialog if the preferences say that the user wants to see the dialog, otherwise it just exits. */ -int -ErrorFileNotice::run () +int ErrorFileNotice::run() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (!prefs->getBool(PREFERENCE_ID, true)) @@ -97,7 +97,8 @@ ErrorFileNotice::run () return Gtk::Dialog::run(); } -}; }; /* namespace Inkscape, Extension */ +}; // namespace Extension +}; // namespace Inkscape /* Local Variables: diff --git a/src/extension/error-file.h b/src/extension/error-file.h index 442bc8f86ac600d4c1ffea89e0a67d3555d6496d..e9a047b44143ec47955b552fb4a5959d52671957 100644 --- a/src/extension/error-file.h +++ b/src/extension/error-file.h @@ -11,8 +11,8 @@ #ifndef INKSCAPE_EXTENSION_ERROR_FILE_H__ #define INKSCAPE_EXTENSION_ERROR_FILE_H__ -#include #include +#include namespace Inkscape { namespace Extension { @@ -20,17 +20,20 @@ namespace Extension { /** \brief A warning dialog to say that some extensions failed to load, will not run if the preference controlling running is turned off. */ -class ErrorFileNotice : public Gtk::MessageDialog { +class ErrorFileNotice : public Gtk::MessageDialog +{ /** The checkbutton, this is so we can figure out when it gets checked */ - Gtk::CheckButton * checkbutton; + Gtk::CheckButton *checkbutton; void checkbox_toggle(); + public: - ErrorFileNotice (); - int run (); + ErrorFileNotice(); + int run(); }; -}; }; /* namespace Inkscape, Extension */ +}; // namespace Extension +}; // namespace Inkscape #endif /* INKSCAPE_EXTENSION_ERROR_FILE_H__ */ diff --git a/src/extension/execution-env.cpp b/src/extension/execution-env.cpp index c931e7f0b3e21575c7999fd6bf0a979122d7f811..b0bda6f58495f41c2c0ea942ac34c5ec0e708ae2 100644 --- a/src/extension/execution-env.cpp +++ b/src/extension/execution-env.cpp @@ -9,23 +9,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "execution-env.h" + #include #include -#include "execution-env.h" -#include "prefdialog/prefdialog.h" -#include "implementation/implementation.h" - -#include "selection.h" -#include "effect.h" -#include "document.h" #include "desktop.h" -#include "inkscape.h" #include "document-undo.h" -#include "desktop.h" +#include "document.h" +#include "effect.h" +#include "implementation/implementation.h" +#include "inkscape.h" #include "object/sp-namedview.h" - -#include "ui/widget/canvas.h" // To get window (perverse!) +#include "prefdialog/prefdialog.h" +#include "selection.h" +#include "ui/widget/canvas.h" // To get window (perverse!) namespace Inkscape { namespace Extension { @@ -41,15 +39,16 @@ namespace Extension { Grabs the selection of the current document so that it can get restored. Will generate a document cache if one isn't provided. */ -ExecutionEnv::ExecutionEnv (Effect * effect, Inkscape::UI::View::View * doc, Implementation::ImplementationDocumentCache * docCache, bool show_working, bool show_errors) : - _state(ExecutionEnv::INIT), - _visibleDialog(nullptr), - _mainloop(nullptr), - _doc(doc), - _docCache(docCache), - _effect(effect), - _show_working(show_working), - _show_errors(show_errors) +ExecutionEnv::ExecutionEnv(Effect *effect, Inkscape::UI::View::View *doc, + Implementation::ImplementationDocumentCache *docCache, bool show_working, bool show_errors) + : _state(ExecutionEnv::INIT) + , _visibleDialog(nullptr) + , _mainloop(nullptr) + , _doc(doc) + , _docCache(docCache) + , _effect(effect) + , _show_working(show_working) + , _show_errors(show_errors) { genDocCache(); @@ -60,7 +59,8 @@ ExecutionEnv::ExecutionEnv (Effect * effect, Inkscape::UI::View::View * doc, Imp Destroys the dialog if created and the document cache. */ -ExecutionEnv::~ExecutionEnv () { +ExecutionEnv::~ExecutionEnv() +{ if (_visibleDialog != nullptr) { _visibleDialog->hide(); delete _visibleDialog; @@ -75,8 +75,8 @@ ExecutionEnv::~ExecutionEnv () { If there isn't one we create a new one from the implementation from the effect's implementation. */ -void -ExecutionEnv::genDocCache () { +void ExecutionEnv::genDocCache() +{ if (_docCache == nullptr) { // printf("Gen Doc Cache\n"); _docCache = _effect->get_imp()->newDocCache(_effect, _doc); @@ -88,8 +88,8 @@ ExecutionEnv::genDocCache () { Just delete it. */ -void -ExecutionEnv::killDocCache () { +void ExecutionEnv::killDocCache() +{ if (_docCache != nullptr) { // printf("Killed Doc Cache\n"); delete _docCache; @@ -103,8 +103,8 @@ ExecutionEnv::killDocCache () { Builds the dialog with a message saying that the effect is working. And make sure to connect to the cancel. */ -void -ExecutionEnv::createWorkingDialog () { +void ExecutionEnv::createWorkingDialog() +{ if (_visibleDialog != nullptr) { _visibleDialog->hide(); delete _visibleDialog; @@ -118,13 +118,11 @@ ExecutionEnv::createWorkingDialog () { return; } - gchar * dlgmessage = g_strdup_printf(_("'%s' working, please wait..."), _(_effect->get_name())); - _visibleDialog = new Gtk::MessageDialog(*window, - dlgmessage, - false, // use markup - Gtk::MESSAGE_INFO, - Gtk::BUTTONS_CANCEL, - true); // modal + gchar *dlgmessage = g_strdup_printf(_("'%s' working, please wait..."), _(_effect->get_name())); + _visibleDialog = new Gtk::MessageDialog(*window, dlgmessage, + false, // use markup + Gtk::MESSAGE_INFO, Gtk::BUTTONS_CANCEL, + true); // modal _visibleDialog->signal_response().connect(sigc::mem_fun(this, &ExecutionEnv::workingCanceled)); g_free(dlgmessage); @@ -141,29 +139,29 @@ ExecutionEnv::createWorkingDialog () { return; } -void -ExecutionEnv::workingCanceled( const int /*resp*/) { +void ExecutionEnv::workingCanceled(const int /*resp*/) +{ cancel(); undo(); return; } -void -ExecutionEnv::cancel () { +void ExecutionEnv::cancel() +{ SPDesktop *desktop = (SPDesktop *)_doc; desktop->clearWaitingCursor(); _effect->get_imp()->cancelProcessing(); return; } -void -ExecutionEnv::undo () { +void ExecutionEnv::undo() +{ DocumentUndo::cancel(_doc->doc()); return; } -void -ExecutionEnv::commit () { +void ExecutionEnv::commit() +{ DocumentUndo::done(_doc->doc(), SP_VERB_NONE, _(_effect->get_name())); Effect::set_last_effect(_effect); _effect->get_imp()->commitDocument(); @@ -171,10 +169,10 @@ ExecutionEnv::commit () { return; } -void -ExecutionEnv::reselect () { +void ExecutionEnv::reselect() +{ SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if(desktop) { + if (desktop) { Inkscape::Selection *selection = desktop->getSelection(); if (selection) { selection->restoreBackup(); @@ -183,8 +181,8 @@ ExecutionEnv::reselect () { return; } -void -ExecutionEnv::run () { +void ExecutionEnv::run() +{ _state = ExecutionEnv::RUNNING; if (_show_working) { createWorkingDialog(); @@ -201,13 +199,13 @@ ExecutionEnv::run () { return; } -void -ExecutionEnv::runComplete () { +void ExecutionEnv::runComplete() +{ _mainloop->quit(); } -bool -ExecutionEnv::wait () { +bool ExecutionEnv::wait() +{ if (_state != ExecutionEnv::COMPLETE) { if (_mainloop) { _mainloop = Glib::MainLoop::create(false); @@ -222,11 +220,8 @@ ExecutionEnv::wait () { return true; } - - -} } /* namespace Inkscape, Extension */ - - +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/execution-env.h b/src/extension/execution-env.h index 15d2cce353e63e6a622af36a547ab4fb2f37bfcc..2757adf29aecb941f15e394b208e045bde5f92e8 100644 --- a/src/extension/execution-env.h +++ b/src/extension/execution-env.h @@ -13,7 +13,6 @@ #include #include - #include namespace Inkscape { @@ -28,14 +27,15 @@ namespace Extension { class Effect; -namespace Implementation -{ +namespace Implementation { class ImplementationDocumentCache; } -class ExecutionEnv { +class ExecutionEnv +{ private: - enum state_t { + enum state_t + { INIT, //< The context has been initialized COMPLETE, //< We've completed atleast once RUNNING //< The effect is currently running @@ -45,26 +45,26 @@ private: /** \brief If there is a working dialog it'll be referenced right here. */ - Gtk::Dialog * _visibleDialog; + Gtk::Dialog *_visibleDialog; /** \brief Signal that the run is complete. */ sigc::signal _runComplete; /** \brief In some cases we need a mainLoop, when we do, this is a pointer to it. */ Glib::RefPtr _mainloop; /** \brief The document that we're working on. */ - Inkscape::UI::View::View * _doc; + Inkscape::UI::View::View *_doc; /** \brief A document cache if we were passed one. */ - Implementation::ImplementationDocumentCache * _docCache; + Implementation::ImplementationDocumentCache *_docCache; /** \brief The effect that we're executing in this context. */ - Effect * _effect; + Effect *_effect; /** \brief Show the working dialog when the effect is executing. */ bool _show_working; /** \brief Display errors if they occur. */ bool _show_errors; -public: +public: /** \brief Create a new context for execution of an effect \param effect The effect to execute \param doc The document to execute the effect on @@ -75,38 +75,37 @@ public: is working. Allows for user canceling. \param show_errors If the effect has an error, show it or not. */ - ExecutionEnv (Effect * effect, - Inkscape::UI::View::View * doc, - Implementation::ImplementationDocumentCache * docCache = nullptr, - bool show_working = true, - bool show_errors = true); - virtual ~ExecutionEnv (); + ExecutionEnv(Effect *effect, Inkscape::UI::View::View *doc, + Implementation::ImplementationDocumentCache *docCache = nullptr, bool show_working = true, + bool show_errors = true); + virtual ~ExecutionEnv(); /** \brief Starts the execution of the effect \return Returns whether the effect was executed to completion */ - void run (); + void run(); /** \brief Cancel the execution of the effect */ - void cancel (); + void cancel(); /** \brief Commit the changes to the document */ - void commit (); + void commit(); /** \brief Undoes what the effect completed. */ - void undo (); + void undo(); /** \brief Wait for the effect to complete if it hasn't. */ - bool wait (); - void reselect (); + bool wait(); + void reselect(); /** \brief Return reference to working dialog (if any) */ - Gtk::Dialog *get_working_dialog () { return _visibleDialog; }; + Gtk::Dialog *get_working_dialog() { return _visibleDialog; }; private: - void runComplete (); - void createWorkingDialog (); - void workingCanceled (const int resp); - void genDocCache (); - void killDocCache (); + void runComplete(); + void createWorkingDialog(); + void workingCanceled(const int resp); + void genDocCache(); + void killDocCache(); }; -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape #endif /* INKSCAPE_EXTENSION_EXECUTION_ENV_H__ */ /* diff --git a/src/extension/extension.cpp b/src/extension/extension.cpp index 6d182af0a2a3710cd3f02a531da9baf447a9b05d..5745436fa839d4f97cf23532cee79a543e876408 100644 --- a/src/extension/extension.cpp +++ b/src/extension/extension.cpp @@ -17,15 +17,12 @@ */ #include "extension.h" -#include "implementation/implementation.h" -#include -#include - -#include #include - +#include +#include #include +#include #include #include #include @@ -33,18 +30,15 @@ #include "db.h" #include "dependency.h" +#include "implementation/implementation.h" #include "inkscape.h" -#include "timer.h" - #include "io/resource.h" #include "io/sys.h" - #include "prefdialog/parameter.h" #include "prefdialog/widget.h" - +#include "timer.h" #include "xml/repr.h" - namespace Inkscape { namespace Extension { @@ -173,7 +167,7 @@ Extension::Extension(Inkscape::XML::Node *in_repr, Implementation::Implementatio #endif // finally register the extension if all checks passed - db.register_ext (this); + db.register_ext(this); } /** @@ -185,7 +179,7 @@ Extension::Extension(Inkscape::XML::Node *in_repr, Implementation::Implementatio than freeing it because it may (I wouldn't know why) be referenced in another place. */ -Extension::~Extension () +Extension::~Extension() { set_state(STATE_UNLOADED); @@ -203,7 +197,7 @@ Extension::~Extension () delete widget; } - for (auto & _dep : _deps) { + for (auto &_dep : _deps) { delete _dep; } _deps.clear(); @@ -220,10 +214,10 @@ Extension::~Extension () load or unload. Currently, there is no error checking in this function. There should be. */ -void -Extension::set_state (state_t in_state) +void Extension::set_state(state_t in_state) { - if (_state == STATE_DEACTIVATED) return; + if (_state == STATE_DEACTIVATED) + return; if (in_state != _state) { /** \todo Need some more error checking here! */ switch (in_state) { @@ -267,8 +261,7 @@ Extension::set_state (state_t in_state) \return The state the extension is in \brief A getter for the state variable. */ -Extension::state_t -Extension::get_state () +Extension::state_t Extension::get_state() { return _state; } @@ -277,8 +270,7 @@ Extension::get_state () \return Whether the extension is loaded or not \brief A quick function to test the state of the extension */ -bool -Extension::loaded () +bool Extension::loaded() { return get_state() == STATE_LOADED; } @@ -299,11 +291,10 @@ Extension::loaded () installations, and figure out what they need to get for the full functionality of Inkscape to be available. */ -bool -Extension::check () +bool Extension::check() { - const char * inx_failure = _(" This is caused by an improper .inx file for this extension." - " An improper .inx file could have been caused by a faulty installation of Inkscape."); + const char *inx_failure = _(" This is caused by an improper .inx file for this extension." + " An improper .inx file could have been caused by a faulty installation of Inkscape."); if (repr == nullptr) { printFailure(Glib::ustring(_("the XML description of it got lost.")) + inx_failure); @@ -337,8 +328,7 @@ Extension::check () Real simple, just put everything into \c error_file. */ -void -Extension::printFailure (Glib::ustring reason) +void Extension::printFailure(Glib::ustring reason) { _error_reason = Glib::ustring::compose(_("Extension \"%1\" failed to load because %2"), _name, reason); error_file_write(_error_reason); @@ -348,8 +338,7 @@ Extension::printFailure (Glib::ustring reason) \return The XML tree that is used to define the extension \brief A getter for the internal Repr, does not add a reference. */ -Inkscape::XML::Node * -Extension::get_repr () +Inkscape::XML::Node *Extension::get_repr() { return repr; } @@ -358,8 +347,7 @@ Extension::get_repr () \return The textual id of this extension \brief Get the ID of this extension - not a copy don't delete! */ -gchar * -Extension::get_id () const +gchar *Extension::get_id() const { return _id; } @@ -368,8 +356,7 @@ Extension::get_id () const \return The textual name of this extension \brief Get the name of this extension - not a copy don't delete! */ -gchar * -Extension::get_name () const +gchar *Extension::get_name() const { return _name; } @@ -389,8 +376,7 @@ Extension::get_name () const \warning It is important to note that there is no 'activate' function. Running this function is irreversable. */ -void -Extension::deactivate () +void Extension::deactivate() { set_state(STATE_DEACTIVATED); @@ -406,25 +392,24 @@ Extension::deactivate () \return Whether the extension has been deactivated \brief Find out the status of the extension */ -bool -Extension::deactivated () +bool Extension::deactivated() { return get_state() == STATE_DEACTIVATED; } /** Gets the location of the dependency file as an absolute path - * - * Iterates over all dependencies of this extension and finds the one with matching name, - * then returns the absolute path to this dependency file as determined previously. - * - * TODO: This function should not be necessary, but we parse script dependencies twice: - * - Once here in the Extension::Extension() constructor - * - A second time in Script::load() in "script.cpp" when determining the script location - * Theoretically we could return the wrong path if an extension depends on two files with the same name - * in different relative locations. In practice this risk should be close to zero, though. - * - * @return Absolute path of the dependency file - */ + * + * Iterates over all dependencies of this extension and finds the one with matching name, + * then returns the absolute path to this dependency file as determined previously. + * + * TODO: This function should not be necessary, but we parse script dependencies twice: + * - Once here in the Extension::Extension() constructor + * - A second time in Script::load() in "script.cpp" when determining the script location + * Theoretically we could return the wrong path if an extension depends on two files with the same name + * in different relative locations. In practice this risk should be close to zero, though. + * + * @return Absolute path of the dependency file + */ std::string Extension::get_dependency_location(const char *name) { for (auto dep : _deps) { @@ -437,7 +422,8 @@ std::string Extension::get_dependency_location(const char *name) } /** recursively searches directory for a file named filename; returns true if found */ -static bool _find_filename_recursive(std::string directory, std::string filename) { +static bool _find_filename_recursive(std::string directory, std::string filename) +{ Glib::Dir dir(directory); std::string name = dir.read_name(); @@ -459,18 +445,19 @@ static bool _find_filename_recursive(std::string directory, std::string filename } /** Searches for a gettext catalog matching the extension's translationdomain - * - * This function will attempt to find the correct gettext catalog for the translationdomain - * requested by the extension. - * - * For this the following three locations are recursively searched for "${translationdomain}.mo": - * - the 'locale' directory in the .inx file's folder - * - the 'locale' directory in the "extensions" folder containing the .inx - * - the system location for gettext catalogs, i.e. where Inkscape's own catalog is located - * - * If one matching file is found, the directory is assumed to be the correct location and registered with gettext - */ -void Extension::lookup_translation_catalog() { + * + * This function will attempt to find the correct gettext catalog for the translationdomain + * requested by the extension. + * + * For this the following three locations are recursively searched for "${translationdomain}.mo": + * - the 'locale' directory in the .inx file's folder + * - the 'locale' directory in the "extensions" folder containing the .inx + * - the system location for gettext catalogs, i.e. where Inkscape's own catalog is located + * + * If one matching file is found, the directory is assumed to be the correct location and registered with gettext + */ +void Extension::lookup_translation_catalog() +{ g_assert(!_base_directory.empty()); // get locale folder locations @@ -482,7 +469,7 @@ void Extension::lookup_translation_catalog() { size_t index = _base_directory.find_last_of("extensions"); if (index != std::string::npos) { - locale_dir_extensions = Glib::build_filename(_base_directory.substr(0, index+1), "locale"); + locale_dir_extensions = Glib::build_filename(_base_directory.substr(0, index + 1), "locale"); } locale_dir_system = bindtextdomain("inkscape", nullptr); @@ -526,16 +513,17 @@ void Extension::lookup_translation_catalog() { } /** Gets a translation within the context of the current extension - * - * Query gettext for the translated version of the input string, - * handling the preferred translation domain of the extension internally. - * - * @param msgid String to translate - * @param msgctxt Context for the translation - * - * @return Translated string (or original string if extension is not supposed to be translated) - */ -const char *Extension::get_translation(const char *msgid, const char *msgctxt) { + * + * Query gettext for the translated version of the input string, + * handling the preferred translation domain of the extension internally. + * + * @param msgid String to translate + * @param msgctxt Context for the translation + * + * @return Translated string (or original string if extension is not supposed to be translated) + */ +const char *Extension::get_translation(const char *msgid, const char *msgctxt) +{ if (!_translation_enabled) { return msgid; } @@ -553,11 +541,12 @@ const char *Extension::get_translation(const char *msgid, const char *msgctxt) { } /** Sets environment suitable for executing this Extension - * - * Currently sets the environment variables INKEX_GETTEXT_DOMAIN and INKEX_GETTEXT_DIRECTORY - * to make the "translationdomain" accessible to child processes spawned by this extension's Implementation. - */ -void Extension::set_environment() { + * + * Currently sets the environment variables INKEX_GETTEXT_DOMAIN and INKEX_GETTEXT_DIRECTORY + * to make the "translationdomain" accessible to child processes spawned by this extension's Implementation. + */ +void Extension::set_environment() +{ Glib::unsetenv("INKEX_GETTEXT_DOMAIN"); Glib::unsetenv("INKEX_GETTEXT_DIRECTORY"); @@ -574,8 +563,7 @@ void Extension::set_environment() { \return An array with all the parameters in it. */ -void -Extension::paramListString (std::list &retlist) +void Extension::paramListString(std::list &retlist) { // first collect all widgets in the current extension std::vector widget_list; @@ -633,7 +621,6 @@ InxParameter const *Extension::get_param(const gchar *name) const return const_cast(this)->get_param(name); } - /** \return The value of the parameter identified by the name \brief Gets a parameter identified by name with the bool placed in value. @@ -641,8 +628,7 @@ InxParameter const *Extension::get_param(const gchar *name) const Look up in the parameters list, const then execute the function on that found parameter. */ -bool -Extension::get_param_bool(const gchar *name) const +bool Extension::get_param_bool(const gchar *name) const { const InxParameter *param; param = get_param(name); @@ -656,8 +642,7 @@ Extension::get_param_bool(const gchar *name) const Look up in the parameters list, const then execute the function on that found parameter. */ -int -Extension::get_param_int(const gchar *name) const +int Extension::get_param_int(const gchar *name) const { const InxParameter *param; param = get_param(name); @@ -671,8 +656,7 @@ Extension::get_param_int(const gchar *name) const Look up in the parameters list, const then execute the function on that found parameter. */ -float -Extension::get_param_float(const gchar *name) const +float Extension::get_param_float(const gchar *name) const { const InxParameter *param; param = get_param(name); @@ -686,8 +670,7 @@ Extension::get_param_float(const gchar *name) const Look up in the parameters list, const then execute the function on that found parameter. */ -const char * -Extension::get_param_string(const gchar *name) const +const char *Extension::get_param_string(const gchar *name) const { const InxParameter *param; param = get_param(name); @@ -701,8 +684,7 @@ Extension::get_param_string(const gchar *name) const Look up in the parameters list, const then execute the function on that found parameter. */ -const char * -Extension::get_param_optiongroup(const gchar *name) const +const char *Extension::get_param_optiongroup(const gchar *name) const { const InxParameter *param; param = get_param(name); @@ -715,8 +697,7 @@ Extension::get_param_optiongroup(const gchar *name) const * @param name The name of the optiongroup parameter to get. * @return true if value exists, false if not */ -bool -Extension::get_param_optiongroup_contains(const gchar *name, const char *value) const +bool Extension::get_param_optiongroup_contains(const gchar *name, const char *value) const { const InxParameter *param; param = get_param(name); @@ -730,8 +711,7 @@ Extension::get_param_optiongroup_contains(const gchar *name, const char *value) Look up in the parameters list, const then execute the function on that found parameter. */ -guint32 -Extension::get_param_color(const gchar *name) const +guint32 Extension::get_param_color(const gchar *name) const { const InxParameter *param; param = get_param(name); @@ -746,8 +726,7 @@ Extension::get_param_color(const gchar *name) const Look up in the parameters list, const then execute the function on that found parameter. */ -bool -Extension::set_param_bool(const gchar *name, const bool value) +bool Extension::set_param_bool(const gchar *name, const bool value) { InxParameter *param; param = get_param(name); @@ -762,8 +741,7 @@ Extension::set_param_bool(const gchar *name, const bool value) Look up in the parameters list, const then execute the function on that found parameter. */ -int -Extension::set_param_int(const gchar *name, const int value) +int Extension::set_param_int(const gchar *name, const int value) { InxParameter *param; param = get_param(name); @@ -778,8 +756,7 @@ Extension::set_param_int(const gchar *name, const int value) Look up in the parameters list, const then execute the function on that found parameter. */ -float -Extension::set_param_float(const gchar *name, const float value) +float Extension::set_param_float(const gchar *name, const float value) { InxParameter *param; param = get_param(name); @@ -794,8 +771,7 @@ Extension::set_param_float(const gchar *name, const float value) Look up in the parameters list, const then execute the function on that found parameter. */ -const char * -Extension::set_param_string(const gchar *name, const char *value) +const char *Extension::set_param_string(const gchar *name, const char *value) { InxParameter *param; param = get_param(name); @@ -810,8 +786,7 @@ Extension::set_param_string(const gchar *name, const char *value) Look up in the parameters list, const then execute the function on that found parameter. */ -const char * -Extension::set_param_optiongroup(const gchar *name, const char *value) +const char *Extension::set_param_optiongroup(const gchar *name, const char *value) { InxParameter *param; param = get_param(name); @@ -826,18 +801,15 @@ Extension::set_param_optiongroup(const gchar *name, const char *value) Look up in the parameters list, const then execute the function on that found parameter. */ -guint32 -Extension::set_param_color(const gchar *name, const guint32 color) +guint32 Extension::set_param_color(const gchar *name, const guint32 color) { InxParameter *param; param = get_param(name); return param->set_color(color); } - /** \brief A function to open the error log file. */ -void -Extension::error_file_open () +void Extension::error_file_open() { gchar *ext_error_file = Inkscape::IO::Resource::log_path(EXTENSION_ERROR_LOG_FILENAME); error_file = Inkscape::IO::fopen_utf8name(ext_error_file, "w+"); @@ -848,8 +820,7 @@ Extension::error_file_open () }; /** \brief A function to close the error log file. */ -void -Extension::error_file_close () +void Extension::error_file_close() { if (error_file) { fclose(error_file); @@ -857,8 +828,7 @@ Extension::error_file_close () }; /** \brief A function to write to the error log file. */ -void -Extension::error_file_write (Glib::ustring text) +void Extension::error_file_write(Glib::ustring text) { if (error_file) { g_fprintf(error_file, "%s\n", text.c_str()); @@ -866,10 +836,12 @@ Extension::error_file_write (Glib::ustring text) }; /** \brief A widget to represent the inside of an AutoGUI widget */ -class AutoGUI : public Gtk::VBox { +class AutoGUI : public Gtk::VBox +{ public: /** \brief Create an AutoGUI object */ - AutoGUI () : Gtk::VBox() {}; + AutoGUI() + : Gtk::VBox(){}; /** * Adds a widget with a tool tip into the autogui. @@ -881,7 +853,8 @@ public: * @param widg Widget to add. * @param tooltip Tooltip for the widget. */ - void addWidget(Gtk::Widget *widg, gchar const *tooltip, int indent) { + void addWidget(Gtk::Widget *widg, gchar const *tooltip, int indent) + { if (widg) { widg->set_margin_start(indent * InxParameter::GUI_INDENTATION); this->pack_start(*widg, false, true, 0); // fill=true does not have an effect here, but allows the @@ -904,14 +877,13 @@ public: If there are no visible parameters, this function just returns NULL. */ -Gtk::Widget * -Extension::autogui (SPDocument *doc, Inkscape::XML::Node *node, sigc::signal *changeSignal) +Gtk::Widget *Extension::autogui(SPDocument *doc, Inkscape::XML::Node *node, sigc::signal *changeSignal) { if (!_gui || widget_visible_count() == 0) { return nullptr; } - AutoGUI * agui = Gtk::manage(new AutoGUI()); + AutoGUI *agui = Gtk::manage(new AutoGUI()); agui->set_border_width(InxParameter::GUI_BOX_MARGIN); agui->set_spacing(InxParameter::GUI_BOX_SPACING); @@ -934,13 +906,12 @@ Extension::autogui (SPDocument *doc, Inkscape::XML::Node *node, sigc::signalset_border_width(4); - Gtk::Frame * info = Gtk::manage(new Gtk::Frame("General Extension Information")); + Gtk::Frame *info = Gtk::manage(new Gtk::Frame("General Extension Information")); retval->pack_start(*info, true, true, 4); auto table = Gtk::manage(new Gtk::Grid()); @@ -952,16 +923,18 @@ Extension::get_info_widget() int row = 0; add_val(_("Name:"), get_translation(_name), table, &row); add_val(_("ID:"), _id, table, &row); - add_val(_("State:"), _state == STATE_LOADED ? _("Loaded") : _state == STATE_UNLOADED ? _("Unloaded") : _("Deactivated"), table, &row); + add_val(_("State:"), + _state == STATE_LOADED ? _("Loaded") : _state == STATE_UNLOADED ? _("Unloaded") : _("Deactivated"), table, + &row); retval->show_all(); return retval; } -void Extension::add_val(Glib::ustring labelstr, Glib::ustring valuestr, Gtk::Grid * table, int * row) +void Extension::add_val(Glib::ustring labelstr, Glib::ustring valuestr, Gtk::Grid *table, int *row) { - Gtk::Label * label; - Gtk::Label * value; + Gtk::Label *label; + Gtk::Label *value; (*row)++; label = Gtk::manage(new Gtk::Label(labelstr, Gtk::ALIGN_START)); @@ -976,18 +949,17 @@ void Extension::add_val(Glib::ustring labelstr, Glib::ustring valuestr, Gtk::Gri return; } -Gtk::VBox * -Extension::get_params_widget() +Gtk::VBox *Extension::get_params_widget() { - Gtk::VBox * retval = Gtk::manage(new Gtk::VBox()); - Gtk::Widget * content = Gtk::manage(new Gtk::Label("Params")); + Gtk::VBox *retval = Gtk::manage(new Gtk::VBox()); + Gtk::Widget *content = Gtk::manage(new Gtk::Label("Params")); retval->pack_start(*content, true, true, 4); content->show(); retval->show(); return retval; } -unsigned int Extension::widget_visible_count ( ) +unsigned int Extension::widget_visible_count() { unsigned int _visible_count = 0; for (auto widget : _widgets) { @@ -998,9 +970,8 @@ unsigned int Extension::widget_visible_count ( ) return _visible_count; } -} /* namespace Extension */ -} /* namespace Inkscape */ - +} /* namespace Extension */ +} /* namespace Inkscape */ /* Local Variables: diff --git a/src/extension/extension.h b/src/extension/extension.h index 476be37d599af0f098e0fb036387d380ca28b3de..5082b2777e85b9f287a57822d86b88c0fb66dbdd 100644 --- a/src/extension/extension.h +++ b/src/extension/extension.h @@ -16,21 +16,20 @@ */ #include -#include -#include - #include +#include #include +#include namespace Glib { - class ustring; +class ustring; } namespace Gtk { - class Grid; - class VBox; - class Widget; -} +class Grid; +class VBox; +class Widget; +} // namespace Gtk /** The key that is used to identify that the I/O should be autodetected */ #define SP_MODULE_KEY_AUTODETECT "autodetect" @@ -49,14 +48,14 @@ namespace Gtk { #define SP_MODULE_KEY_OUTPUT_DEFAULT SP_MODULE_KEY_AUTODETECT /** Defines the key for Postscript printing */ -#define SP_MODULE_KEY_PRINT_PS "org.inkscape.print.ps" -#define SP_MODULE_KEY_PRINT_CAIRO_PS "org.inkscape.print.ps.cairo" -#define SP_MODULE_KEY_PRINT_CAIRO_EPS "org.inkscape.print.eps.cairo" +#define SP_MODULE_KEY_PRINT_PS "org.inkscape.print.ps" +#define SP_MODULE_KEY_PRINT_CAIRO_PS "org.inkscape.print.ps.cairo" +#define SP_MODULE_KEY_PRINT_CAIRO_EPS "org.inkscape.print.eps.cairo" /** Defines the key for PDF printing */ -#define SP_MODULE_KEY_PRINT_PDF "org.inkscape.print.pdf" -#define SP_MODULE_KEY_PRINT_CAIRO_PDF "org.inkscape.print.pdf.cairo" +#define SP_MODULE_KEY_PRINT_PDF "org.inkscape.print.pdf" +#define SP_MODULE_KEY_PRINT_CAIRO_PDF "org.inkscape.print.pdf.cairo" /** Defines the key for LaTeX printing */ -#define SP_MODULE_KEY_PRINT_LATEX "org.inkscape.print.latex" +#define SP_MODULE_KEY_PRINT_LATEX "org.inkscape.print.latex" /** Defines the key for printing with GNOME Print */ #define SP_MODULE_KEY_PRINT_GNOME "org.inkscape.print.gnome" @@ -64,12 +63,11 @@ namespace Gtk { #define MIME_SVG "image/svg+xml" /** Name of the extension error file */ -#define EXTENSION_ERROR_LOG_FILENAME "extension-errors.log" +#define EXTENSION_ERROR_LOG_FILENAME "extension-errors.log" - -#define INKSCAPE_EXTENSION_URI "http://www.inkscape.org/namespace/inkscape/extension" +#define INKSCAPE_EXTENSION_URI "http://www.inkscape.org/namespace/inkscape/extension" #define INKSCAPE_EXTENSION_NS_NC "extension" -#define INKSCAPE_EXTENSION_NS "extension:" +#define INKSCAPE_EXTENSION_NS "extension:" class SPDocument; @@ -88,49 +86,49 @@ class ExpirationTimer; class InxParameter; class InxWidget; -namespace Implementation -{ +namespace Implementation { class Implementation; } - /** The object that is the basis for the Extension system. This object contains all of the information that all Extension have. The individual items are detailed within. This is the interface that those who want to _use_ the extensions system should use. This is most likely to be those who are inside the Inkscape program. */ -class Extension { +class Extension +{ public: /** An enumeration to identify if the Extension has been loaded or not. */ - enum state_t { - STATE_LOADED, /**< The extension has been loaded successfully */ - STATE_UNLOADED, /**< The extension has not been loaded */ - STATE_DEACTIVATED /**< The extension is missing something which makes it unusable */ + enum state_t + { + STATE_LOADED, /**< The extension has been loaded successfully */ + STATE_UNLOADED, /**< The extension has not been loaded */ + STATE_DEACTIVATED /**< The extension is missing something which makes it unusable */ }; private: - gchar *_id = nullptr; /**< The unique identifier for the Extension */ - gchar *_name = nullptr; /**< A user friendly name for the Extension */ - state_t _state = STATE_UNLOADED; /**< Which state the Extension is currently in */ - std::vector _deps; /**< Dependencies for this extension */ - static FILE *error_file; /**< This is the place where errors get reported */ + gchar *_id = nullptr; /**< The unique identifier for the Extension */ + gchar *_name = nullptr; /**< A user friendly name for the Extension */ + state_t _state = STATE_UNLOADED; /**< Which state the Extension is currently in */ + std::vector _deps; /**< Dependencies for this extension */ + static FILE *error_file; /**< This is the place where errors get reported */ bool _gui; - std::string _error_reason; /**< Short, textual explanation for the latest error */ + std::string _error_reason; /**< Short, textual explanation for the latest error */ protected: - Inkscape::XML::Node *repr; /**< The XML description of the Extension */ - Implementation::Implementation * imp; /**< An object that holds all the functions for making this work */ - ExecutionEnv * execution_env; /**< Execution environment of the extension - * (currently only used by Effects) */ - std::string _base_directory; /**< Directory containing the .inx file, - * relative paths in the extension should usually be relative to it */ - ExpirationTimer * timer = nullptr; /**< Timeout to unload after a given time */ - bool _translation_enabled = true; /**< Attempt translation of strings provided by the extension? */ + Inkscape::XML::Node *repr; /**< The XML description of the Extension */ + Implementation::Implementation *imp; /**< An object that holds all the functions for making this work */ + ExecutionEnv *execution_env; /**< Execution environment of the extension + * (currently only used by Effects) */ + std::string _base_directory; /**< Directory containing the .inx file, + * relative paths in the extension should usually be relative to it */ + ExpirationTimer *timer = nullptr; /**< Timeout to unload after a given time */ + bool _translation_enabled = true; /**< Attempt translation of strings provided by the extension? */ private: - const char *_translationdomain = nullptr; /**< Domainname of gettext textdomain that should - * be used for translation of the extension's strings */ - std::string _gettext_catalog_dir; /**< Directory containing the gettext catalog for _translationdomain */ + const char *_translationdomain = nullptr; /**< Domainname of gettext textdomain that should + * be used for translation of the extension's strings */ + std::string _gettext_catalog_dir; /**< Directory containing the gettext catalog for _translationdomain */ void lookup_translation_catalog(); @@ -138,55 +136,65 @@ public: Extension(Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory); virtual ~Extension(); - void set_state (state_t in_state); - state_t get_state (); - bool loaded (); - virtual bool check (); - Inkscape::XML::Node * get_repr (); - gchar * get_id () const; - gchar * get_name () const; - void deactivate (); - bool deactivated (); - void printFailure (Glib::ustring reason); + void set_state(state_t in_state); + state_t get_state(); + bool loaded(); + virtual bool check(); + Inkscape::XML::Node *get_repr(); + gchar *get_id() const; + gchar *get_name() const; + void deactivate(); + bool deactivated(); + void printFailure(Glib::ustring reason); std::string const &getErrorReason() { return _error_reason; }; - Implementation::Implementation * get_imp () { return imp; }; - void set_execution_env (ExecutionEnv * env) { execution_env = env; }; - ExecutionEnv *get_execution_env () { return execution_env; }; - std::string get_base_directory() const { return _base_directory; }; - void set_base_directory(std::string base_directory) { _base_directory = base_directory; }; - std::string get_dependency_location(const char *name); - const char *get_translation(const char* msgid, const char *msgctxt=nullptr); - void set_environment(); - -/* Parameter Stuff */ + Implementation::Implementation *get_imp() { return imp; }; + void set_execution_env(ExecutionEnv *env) { execution_env = env; }; + ExecutionEnv *get_execution_env() { return execution_env; }; + std::string get_base_directory() const { return _base_directory; }; + void set_base_directory(std::string base_directory) { _base_directory = base_directory; }; + std::string get_dependency_location(const char *name); + const char *get_translation(const char *msgid, const char *msgctxt = nullptr); + void set_environment(); + + /* Parameter Stuff */ private: std::vector _widgets; /**< A list of widgets for this extension. */ public: /** \brief A function to get the number of visible parameters of the extension. \return The number of visible parameters. */ - unsigned int widget_visible_count ( ); + unsigned int widget_visible_count(); public: /** An error class for when a parameter is looked for that just * simply doesn't exist */ - class param_not_exist {}; + class param_not_exist + { + }; /** no valid ID found while parsing XML representation */ - class extension_no_id{}; + class extension_no_id + { + }; /** no valid name found while parsing XML representation */ - class extension_no_name{}; + class extension_no_name + { + }; /** extension is not compatible with the current system and should not be loaded */ - class extension_not_compatible{}; + class extension_not_compatible + { + }; /** An error class for when a filename already exists, but the user * doesn't want to overwrite it */ - class no_overwrite {}; + class no_overwrite + { + }; private: - void make_param (Inkscape::XML::Node * paramrepr); + void make_param(Inkscape::XML::Node *paramrepr); /** * Looks up the parameter with the specified name. @@ -200,37 +208,36 @@ private: * @param name Name of the parameter to search for. * @return Parameter with matching name. */ - InxParameter *get_param(const gchar *name); + InxParameter *get_param(const gchar *name); - InxParameter const *get_param(const gchar *name) const; + InxParameter const *get_param(const gchar *name) const; public: - bool get_param_bool (const gchar *name) const; - int get_param_int (const gchar *name) const; - float get_param_float (const gchar *name) const; - const char *get_param_string (const gchar *name) const; - const char *get_param_optiongroup (const gchar *name) const; - guint32 get_param_color (const gchar *name) const; - - bool get_param_optiongroup_contains (const gchar *name, const char *value) const; - - bool set_param_bool (const gchar *name, const bool value); - int set_param_int (const gchar *name, const int value); - float set_param_float (const gchar *name, const float value); - const char *set_param_string (const gchar *name, const char *value); - const char *set_param_optiongroup (const gchar *name, const char *value); - guint32 set_param_color (const gchar *name, const guint32 color); - + bool get_param_bool(const gchar *name) const; + int get_param_int(const gchar *name) const; + float get_param_float(const gchar *name) const; + const char *get_param_string(const gchar *name) const; + const char *get_param_optiongroup(const gchar *name) const; + guint32 get_param_color(const gchar *name) const; + + bool get_param_optiongroup_contains(const gchar *name, const char *value) const; + + bool set_param_bool(const gchar *name, const bool value); + int set_param_int(const gchar *name, const int value); + float set_param_float(const gchar *name, const float value); + const char *set_param_string(const gchar *name, const char *value); + const char *set_param_optiongroup(const gchar *name, const char *value); + guint32 set_param_color(const gchar *name, const guint32 color); /* Error file handling */ public: - static void error_file_open (); - static void error_file_close (); - static void error_file_write (Glib::ustring text); + static void error_file_open(); + static void error_file_close(); + static void error_file_write(Glib::ustring text); public: - Gtk::Widget *autogui (SPDocument *doc, Inkscape::XML::Node *node, sigc::signal *changeSignal = nullptr); - void paramListString(std::list &retlist); + Gtk::Widget *autogui(SPDocument *doc, Inkscape::XML::Node *node, sigc::signal *changeSignal = nullptr); + void paramListString(std::list &retlist); void set_gui(bool s) { _gui = s; } bool get_gui() { return _gui; } @@ -238,12 +245,11 @@ public: public: Gtk::VBox *get_info_widget(); Gtk::VBox *get_params_widget(); + protected: - inline static void add_val(Glib::ustring labelstr, Glib::ustring valuestr, Gtk::Grid * table, int * row); + inline static void add_val(Glib::ustring labelstr, Glib::ustring valuestr, Gtk::Grid *table, int *row); }; - - /* This is a prototype for how collections should work. Whoever gets @@ -264,8 +270,8 @@ public: }; */ -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif // INK_EXTENSION_H diff --git a/src/extension/find_extension_by_mime.h b/src/extension/find_extension_by_mime.h index f58580e6f3ffc4d8ccc655915531b902fc70f990..8d3369afea3e2c76a1c69f689cbb3b03dd4d9352 100644 --- a/src/extension/find_extension_by_mime.h +++ b/src/extension/find_extension_by_mime.h @@ -26,7 +26,6 @@ namespace Inkscape { namespace Extension { static inline Inkscape::Extension::Extension *find_by_mime(const char *const mime) { - Inkscape::Extension::DB::InputList o; Inkscape::Extension::db.get_input_list(o); Inkscape::Extension::DB::InputList::const_iterator i = o.begin(); @@ -35,5 +34,5 @@ static inline Inkscape::Extension::Extension *find_by_mime(const char *const mim } return *i; } -} -} +} // namespace Extension +} // namespace Inkscape diff --git a/src/extension/implementation/implementation.cpp b/src/extension/implementation/implementation.cpp index 36cd299b7d79267bc1713029d7851b65f48fd1e7..4e1635ccff30ee7fb0ea75affd385d75d5a72df4 100644 --- a/src/extension/implementation/implementation.cpp +++ b/src/extension/implementation/implementation.cpp @@ -13,40 +13,40 @@ #include "implementation.h" -#include -#include #include +#include +#include -#include "selection.h" #include "desktop.h" - +#include "selection.h" namespace Inkscape { namespace Extension { namespace Implementation { -Gtk::Widget * -Implementation::prefs_input(Inkscape::Extension::Input *module, gchar const */*filename*/) { +Gtk::Widget *Implementation::prefs_input(Inkscape::Extension::Input *module, gchar const * /*filename*/) +{ return module->autogui(nullptr, nullptr); } -Gtk::Widget * -Implementation::prefs_output(Inkscape::Extension::Output *module) { +Gtk::Widget *Implementation::prefs_output(Inkscape::Extension::Output *module) +{ return module->autogui(nullptr, nullptr); } -Gtk::Widget *Implementation::prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View * view, sigc::signal * changeSignal, ImplementationDocumentCache * /*docCache*/) +Gtk::Widget *Implementation::prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *view, + sigc::signal *changeSignal, ImplementationDocumentCache * /*docCache*/) { if (module->widget_visible_count() == 0) { return nullptr; } - SPDocument * current_document = view->doc(); + SPDocument *current_document = view->doc(); - auto selected = ((SPDesktop *) view)->getSelection()->items(); - Inkscape::XML::Node const* first_select = nullptr; + auto selected = ((SPDesktop *)view)->getSelection()->items(); + Inkscape::XML::Node const *first_select = nullptr; if (!selected.empty()) { - const SPItem * item = selected.front(); + const SPItem *item = selected.front(); first_select = item->getRepr(); } @@ -54,9 +54,9 @@ Gtk::Widget *Implementation::prefs_effect(Inkscape::Extension::Effect *module, I return module->autogui(current_document, const_cast(first_select), changeSignal); } // Implementation::prefs_effect -} /* namespace Implementation */ -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Implementation */ +} /* namespace Extension */ +} /* namespace Inkscape */ /* Local Variables: diff --git a/src/extension/implementation/implementation.h b/src/extension/implementation/implementation.h index ba4f773b561f6c0e402be6a2d3541b3d00705cf3..f577c69eb8aba13f9bca070a63b4f1f294c2e658 100644 --- a/src/extension/implementation/implementation.h +++ b/src/extension/implementation/implementation.h @@ -13,13 +13,13 @@ #ifndef SEEN_INKSCAPE_EXTENSION_IMPLEMENTATION_H #define SEEN_INKSCAPE_EXTENSION_IMPLEMENTATION_H -#include -#include -#include #include <2geom/forward.h> +#include +#include +#include namespace Gtk { - class Widget; +class Widget; } class SPDocument; @@ -31,10 +31,10 @@ namespace UI { namespace View { class View; } -} +} // namespace UI namespace XML { - class Node; +class Node; } namespace Extension { @@ -50,17 +50,18 @@ namespace Implementation { /** * A cache for the document and this implementation. */ -class ImplementationDocumentCache { - +class ImplementationDocumentCache +{ /** - * The document that this instance is working on. - */ - Inkscape::UI::View::View * _view; + * The document that this instance is working on. + */ + Inkscape::UI::View::View *_view; + public: - ImplementationDocumentCache (Inkscape::UI::View::View * view) { return; }; + ImplementationDocumentCache(Inkscape::UI::View::View *view) { return; }; - virtual ~ImplementationDocumentCache ( ) { return; }; - Inkscape::UI::View::View const * view ( ) { return _view; }; + virtual ~ImplementationDocumentCache() { return; }; + Inkscape::UI::View::View const *view() { return _view; }; }; /** @@ -68,7 +69,8 @@ public: * having something like the scripting system, or they are implemented internally they all derive * from this class. */ -class Implementation { +class Implementation +{ public: // ----- Constructor / destructor ----- Implementation() = default; @@ -89,21 +91,23 @@ public: * @return A new document cache that is valid as long as the document * is not changed. */ - virtual ImplementationDocumentCache * newDocCache (Inkscape::Extension::Extension * /*ext*/, Inkscape::UI::View::View * /*doc*/) { return nullptr; } + virtual ImplementationDocumentCache *newDocCache(Inkscape::Extension::Extension * /*ext*/, + Inkscape::UI::View::View * /*doc*/) + { + return nullptr; + } /** Verify any dependencies. */ virtual bool check(Inkscape::Extension::Extension * /*module*/) { return true; } - virtual bool cancelProcessing () { return true; } - virtual void commitDocument () {} + virtual bool cancelProcessing() { return true; } + virtual void commitDocument() {} // ----- Input functions ----- /** Find out information about the file. */ - virtual Gtk::Widget *prefs_input(Inkscape::Extension::Input *module, - gchar const *filename); + virtual Gtk::Widget *prefs_input(Inkscape::Extension::Input *module, gchar const *filename); - virtual SPDocument *open(Inkscape::Extension::Input * /*module*/, - gchar const * /*filename*/) { return nullptr; } + virtual SPDocument *open(Inkscape::Extension::Input * /*module*/, gchar const * /*filename*/) { return nullptr; } // ----- Output functions ----- /** Find out information about the file. */ @@ -112,20 +116,17 @@ public: // ----- Effect functions ----- /** Find out information about the file. */ - virtual Gtk::Widget * prefs_effect(Inkscape::Extension::Effect *module, - Inkscape::UI::View::View *view, - sigc::signal *changeSignal, - ImplementationDocumentCache *docCache); - virtual void effect(Inkscape::Extension::Effect * /*module*/, - Inkscape::UI::View::View * /*document*/, - ImplementationDocumentCache * /*docCache*/) {} + virtual Gtk::Widget *prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *view, + sigc::signal *changeSignal, ImplementationDocumentCache *docCache); + virtual void effect(Inkscape::Extension::Effect * /*module*/, Inkscape::UI::View::View * /*document*/, + ImplementationDocumentCache * /*docCache*/) + {} // ----- Print functions ----- virtual unsigned setup(Inkscape::Extension::Print * /*module*/) { return 0; } virtual unsigned set_preview(Inkscape::Extension::Print * /*module*/) { return 0; } - virtual unsigned begin(Inkscape::Extension::Print * /*module*/, - SPDocument * /*doc*/) { return 0; } + virtual unsigned begin(Inkscape::Extension::Print * /*module*/, SPDocument * /*doc*/) { return 0; } virtual unsigned finish(Inkscape::Extension::Print * /*module*/) { return 0; } /** @@ -135,7 +136,7 @@ public: * \retval true Render the text as a path * \retval false Render text using the text function (above) */ - virtual bool textToPath(Inkscape::Extension::Print * /*ext*/) { return false; } + virtual bool textToPath(Inkscape::Extension::Print * /*ext*/) { return false; } /** * Get "fontEmbedded" param, i.e. tell the printing engine whether fonts should be embedded. @@ -144,40 +145,41 @@ public: * to install fonts to have the interpreter read the document correctly * \retval false Do not embed fonts */ - virtual bool fontEmbedded(Inkscape::Extension::Print * /*ext*/) { return false; } + virtual bool fontEmbedded(Inkscape::Extension::Print * /*ext*/) { return false; } // ----- Rendering methods ----- - virtual unsigned bind(Inkscape::Extension::Print * /*module*/, - Geom::Affine const & /*transform*/, - float /*opacity*/) { return 0; } + virtual unsigned bind(Inkscape::Extension::Print * /*module*/, Geom::Affine const & /*transform*/, + float /*opacity*/) + { + return 0; + } virtual unsigned release(Inkscape::Extension::Print * /*module*/) { return 0; } virtual unsigned comment(Inkscape::Extension::Print * /*module*/, char const * /*comment*/) { return 0; } - virtual unsigned fill(Inkscape::Extension::Print * /*module*/, - Geom::PathVector const & /*pathv*/, - Geom::Affine const & /*ctm*/, - SPStyle const * /*style*/, - Geom::OptRect const & /*pbox*/, - Geom::OptRect const & /*dbox*/, - Geom::OptRect const & /*bbox*/) { return 0; } - virtual unsigned stroke(Inkscape::Extension::Print * /*module*/, - Geom::PathVector const & /*pathv*/, - Geom::Affine const & /*transform*/, - SPStyle const * /*style*/, - Geom::OptRect const & /*pbox*/, - Geom::OptRect const & /*dbox*/, - Geom::OptRect const & /*bbox*/) { return 0; } - virtual unsigned image(Inkscape::Extension::Print * /*module*/, - unsigned char * /*px*/, - unsigned int /*w*/, - unsigned int /*h*/, - unsigned int /*rs*/, - Geom::Affine const & /*transform*/, - SPStyle const * /*style*/) { return 0; } - virtual unsigned text(Inkscape::Extension::Print * /*module*/, - char const * /*text*/, - Geom::Point const & /*p*/, - SPStyle const * /*style*/) { return 0; } - virtual void processPath(Inkscape::XML::Node * /*node*/) {} + virtual unsigned fill(Inkscape::Extension::Print * /*module*/, Geom::PathVector const & /*pathv*/, + Geom::Affine const & /*ctm*/, SPStyle const * /*style*/, Geom::OptRect const & /*pbox*/, + Geom::OptRect const & /*dbox*/, Geom::OptRect const & /*bbox*/) + { + return 0; + } + virtual unsigned stroke(Inkscape::Extension::Print * /*module*/, Geom::PathVector const & /*pathv*/, + Geom::Affine const & /*transform*/, SPStyle const * /*style*/, + Geom::OptRect const & /*pbox*/, Geom::OptRect const & /*dbox*/, + Geom::OptRect const & /*bbox*/) + { + return 0; + } + virtual unsigned image(Inkscape::Extension::Print * /*module*/, unsigned char * /*px*/, unsigned int /*w*/, + unsigned int /*h*/, unsigned int /*rs*/, Geom::Affine const & /*transform*/, + SPStyle const * /*style*/) + { + return 0; + } + virtual unsigned text(Inkscape::Extension::Print * /*module*/, char const * /*text*/, Geom::Point const & /*p*/, + SPStyle const * /*style*/) + { + return 0; + } + virtual void processPath(Inkscape::XML::Node * /*node*/) {} /** * If detach = true, when saving to a file, don't store URIs realtive to the filename @@ -185,10 +187,9 @@ public: virtual void setDetachBase(bool detach) {} }; - -} // namespace Implementation -} // namespace Extension -} // namespace Inkscape +} // namespace Implementation +} // namespace Extension +} // namespace Inkscape #endif // __INKSCAPE_EXTENSION_IMPLEMENTATION_H__ diff --git a/src/extension/implementation/script.cpp b/src/extension/implementation/script.cpp index 990aec1106366b1ec3f611cd2b073f28361d9cf3..51ae8614380d3dba46da8d7f70bf7cdb13833589 100644 --- a/src/extension/implementation/script.cpp +++ b/src/extension/implementation/script.cpp @@ -13,6 +13,8 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "script.h" + #include #include #include @@ -23,21 +25,19 @@ #include #include "desktop.h" -#include "inkscape.h" -#include "path-prefix.h" -#include "preferences.h" -#include "script.h" -#include "selection.h" - #include "extension/db.h" #include "extension/effect.h" #include "extension/execution-env.h" #include "extension/input.h" #include "extension/output.h" #include "extension/system.h" +#include "inkscape.h" #include "io/resource.h" #include "object/sp-namedview.h" #include "object/sp-path.h" +#include "path-prefix.h" +#include "preferences.h" +#include "selection.h" #include "ui/dialog-events.h" #include "ui/tool/control-point-selection.h" #include "ui/tool/multi-path-manipulator.h" @@ -57,14 +57,14 @@ namespace Implementation { This just keeps coming the events through so that we'll make the GUI update and look pretty. */ -void Script::pump_events () { - while ( Gtk::Main::events_pending() ) { +void Script::pump_events() +{ + while (Gtk::Main::events_pending()) { Gtk::Main::iteration(); } return; } - /** \brief A table of what interpreters to call for a given language This table is used to keep track of all the programs to execute a @@ -72,7 +72,7 @@ void Script::pump_events () { the given interpreter to a custom one per user. */ const std::map Script::interpreterTab = { - // clang-format off +// clang-format off #ifdef _WIN32 { "perl", {"perl-interpreter", {"wperl" }}}, { "python", {"python-interpreter", {"pythonw" }}}, @@ -89,8 +89,6 @@ const std::map Script::interpreterTab = { // clang-format on }; - - /** \brief Look up an interpreter name, and translate to something that is executable \param interpNameArg The name of the interpreter that we're looking @@ -113,11 +111,11 @@ std::string Script::resolveInterpreterExecutable(const Glib::ustring &interpName auto prefInterp = prefs->getString("/extensions/" + Glib::ustring(interp->second.prefstring)); if (!prefInterp.empty()) { - searchList.push_front(prefInterp); + searchList.push_front(prefInterp); } // 2. Search for things in the path if they're there or an absolute - for (const auto& binname : searchList) { + for (const auto &binname : searchList) { auto interpreter_path = Glib::filename_from_utf8(binname); if (!Glib::path_is_absolute(interpreter_path)) { @@ -131,7 +129,8 @@ std::string Script::resolveInterpreterExecutable(const Glib::ustring &interpName } // 3. Error - g_critical("Script::resolveInterpreterExecutable(): failed to locate script interpreter '%s'", interpNameArg.c_str()); + g_critical("Script::resolveInterpreterExecutable(): failed to locate script interpreter '%s'", + interpNameArg.c_str()); return ""; } @@ -147,15 +146,12 @@ Script::Script() : Implementation() , _canceled(false) , parent_window(nullptr) -{ -} +{} /** * \brief Destructor */ -Script::~Script() -= default; - +Script::~Script() = default; /** \return none @@ -218,7 +214,6 @@ bool Script::load(Inkscape::Extension::Extension *module) return true; } - /** \return None. \brief Unload this puppy! @@ -227,15 +222,12 @@ bool Script::load(Inkscape::Extension::Extension *module) This function just sets the module to unloaded. It free's the command if it has been allocated. */ -void Script::unload(Inkscape::Extension::Extension */*module*/) +void Script::unload(Inkscape::Extension::Extension * /*module*/) { command.clear(); helper_extension = ""; } - - - /** \return Whether the check passed or not \brief Check every dependency that was given to make sure we should keep this extension @@ -275,20 +267,23 @@ bool Script::check(Inkscape::Extension::Extension *module) return true; } -class ScriptDocCache : public ImplementationDocumentCache { +class ScriptDocCache : public ImplementationDocumentCache +{ friend class Script; + protected: std::string _filename; int _tempfd; + public: - ScriptDocCache (Inkscape::UI::View::View * view); - ~ScriptDocCache ( ) override; + ScriptDocCache(Inkscape::UI::View::View *view); + ~ScriptDocCache() override; }; -ScriptDocCache::ScriptDocCache (Inkscape::UI::View::View * view) : - ImplementationDocumentCache(view), - _filename(""), - _tempfd(0) +ScriptDocCache::ScriptDocCache(Inkscape::UI::View::View *view) + : ImplementationDocumentCache(view) + , _filename("") + , _tempfd(0) { try { _tempfd = Glib::file_open_tmp(_filename, "ink_ext_XXXXXX.svg"); @@ -297,29 +292,29 @@ ScriptDocCache::ScriptDocCache (Inkscape::UI::View::View * view) : return; } - SPDesktop *desktop = (SPDesktop *) view; + SPDesktop *desktop = (SPDesktop *)view; sp_namedview_document_from_window(desktop); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setBool("/options/svgoutput/disable_optimizations", true); - Inkscape::Extension::save( - Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_SVG_INKSCAPE), - view->doc(), _filename.c_str(), false, false, false, Inkscape::Extension::FILE_SAVE_METHOD_TEMPORARY); + Inkscape::Extension::save(Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_SVG_INKSCAPE), view->doc(), + _filename.c_str(), false, false, false, Inkscape::Extension::FILE_SAVE_METHOD_TEMPORARY); prefs->setBool("/options/svgoutput/disable_optimizations", false); return; } -ScriptDocCache::~ScriptDocCache ( ) +ScriptDocCache::~ScriptDocCache() { close(_tempfd); unlink(_filename.c_str()); } -ImplementationDocumentCache *Script::newDocCache( Inkscape::Extension::Extension * /*ext*/, Inkscape::UI::View::View * view ) { +ImplementationDocumentCache *Script::newDocCache(Inkscape::Extension::Extension * /*ext*/, + Inkscape::UI::View::View *view) +{ return new ScriptDocCache(view); } - /** \return A dialog for preferences \brief A stub function right now @@ -328,14 +323,11 @@ ImplementationDocumentCache *Script::newDocCache( Inkscape::Extension::Extension This function should really do something, right now it doesn't. */ -Gtk::Widget *Script::prefs_input(Inkscape::Extension::Input *module, - const gchar */*filename*/) +Gtk::Widget *Script::prefs_input(Inkscape::Extension::Input *module, const gchar * /*filename*/) { return module->autogui(nullptr, nullptr); } - - /** \return A dialog for preferences \brief A stub function right now @@ -369,8 +361,7 @@ Gtk::Widget *Script::prefs_output(Inkscape::Extension::Output *module) the incoming filename (so that it's not the temporary filename). That document is then returned from this function. */ -SPDocument *Script::open(Inkscape::Extension::Input *module, - const gchar *filenameArg) +SPDocument *Script::open(Inkscape::Extension::Input *module, const gchar *filenameArg) { std::list params; module->paramListString(params); @@ -391,16 +382,14 @@ SPDocument *Script::open(Inkscape::Extension::Input *module, int data_read = execute(command, params, lfilename, fileout); fileout.toFile(tempfilename_out); - SPDocument * mydoc = nullptr; + SPDocument *mydoc = nullptr; if (data_read > 10) { - if (helper_extension.size()==0) { - mydoc = Inkscape::Extension::open( - Inkscape::Extension::db.get(SP_MODULE_KEY_INPUT_SVG), - tempfilename_out.c_str()); + if (helper_extension.size() == 0) { + mydoc = Inkscape::Extension::open(Inkscape::Extension::db.get(SP_MODULE_KEY_INPUT_SVG), + tempfilename_out.c_str()); } else { - mydoc = Inkscape::Extension::open( - Inkscape::Extension::db.get(helper_extension.c_str()), - tempfilename_out.c_str()); + mydoc = Inkscape::Extension::open(Inkscape::Extension::db.get(helper_extension.c_str()), + tempfilename_out.c_str()); } } // data_read @@ -417,8 +406,6 @@ SPDocument *Script::open(Inkscape::Extension::Input *module, return mydoc; } // open - - /** \return none \brief This function uses an extension to save a document. It first @@ -444,9 +431,7 @@ SPDocument *Script::open(Inkscape::Extension::Input *module, put the output of the script into the final output file. We then delete the temporary file. */ -void Script::save(Inkscape::Extension::Output *module, - SPDocument *doc, - const gchar *filenameArg) +void Script::save(Inkscape::Extension::Output *module, SPDocument *doc, const gchar *filenameArg) { std::list params; module->paramListString(params); @@ -462,18 +447,14 @@ void Script::save(Inkscape::Extension::Output *module, } if (helper_extension.size() == 0) { - Inkscape::Extension::save( - Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_SVG_INKSCAPE), - doc, tempfilename_in.c_str(), false, false, false, - Inkscape::Extension::FILE_SAVE_METHOD_TEMPORARY); + Inkscape::Extension::save(Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_SVG_INKSCAPE), doc, + tempfilename_in.c_str(), false, false, false, + Inkscape::Extension::FILE_SAVE_METHOD_TEMPORARY); } else { - Inkscape::Extension::save( - Inkscape::Extension::db.get(helper_extension.c_str()), - doc, tempfilename_in.c_str(), false, false, false, - Inkscape::Extension::FILE_SAVE_METHOD_TEMPORARY); + Inkscape::Extension::save(Inkscape::Extension::db.get(helper_extension.c_str()), doc, tempfilename_in.c_str(), + false, false, false, Inkscape::Extension::FILE_SAVE_METHOD_TEMPORARY); } - file_listener fileout; int data_read = execute(command, params, tempfilename_in, fileout); @@ -496,8 +477,6 @@ void Script::save(Inkscape::Extension::Output *module, return; } - - /** \return none \brief This function uses an extension as an effect on a document. @@ -526,20 +505,18 @@ void Script::save(Inkscape::Extension::Output *module, exists at the time, the other is created by that script). At that point both should be full, and the second one is loaded. */ -void Script::effect(Inkscape::Extension::Effect *module, - Inkscape::UI::View::View *doc, - ImplementationDocumentCache * docCache) +void Script::effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *doc, + ImplementationDocumentCache *docCache) { if (docCache == nullptr) { docCache = newDocCache(module, doc); } - ScriptDocCache * dc = dynamic_cast(docCache); + ScriptDocCache *dc = dynamic_cast(docCache); if (dc == nullptr) { printf("TOO BAD TO LIVE!!!"); exit(1); } - if (doc == nullptr) - { + if (doc == nullptr) { g_warning("Script::effect: View not defined"); return; } @@ -574,7 +551,7 @@ void Script::effect(Inkscape::Extension::Effect *module, } if (desktop) { - Inkscape::Selection * selection = desktop->getSelection(); + Inkscape::Selection *selection = desktop->getSelection(); if (selection) { params = selection->params; module->paramListString(params); @@ -588,18 +565,16 @@ void Script::effect(Inkscape::Extension::Effect *module, pump_events(); - SPDocument * mydoc = nullptr; + SPDocument *mydoc = nullptr; if (data_read > 10) { try { - mydoc = Inkscape::Extension::open( - Inkscape::Extension::db.get(SP_MODULE_KEY_INPUT_SVG), - tempfilename_out.c_str()); + mydoc = Inkscape::Extension::open(Inkscape::Extension::db.get(SP_MODULE_KEY_INPUT_SVG), + tempfilename_out.c_str()); } catch (const Inkscape::Extension::Input::open_failed &e) { g_warning("Extension returned output that could not be parsed: %s", e.what()); - Gtk::MessageDialog warning( - _("The output from the extension could not be parsed."), - false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK, true); - warning.set_transient_for( parent_window ? *parent_window : *(INKSCAPE.active_desktop()->getToplevel()) ); + Gtk::MessageDialog warning(_("The output from the extension could not be parsed."), false, + Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK, true); + warning.set_transient_for(parent_window ? *parent_window : *(INKSCAPE.active_desktop()->getToplevel())); warning.run(); } } // data_read @@ -612,9 +587,8 @@ void Script::effect(Inkscape::Extension::Effect *module, g_unlink(tempfilename_out.c_str()); if (mydoc) { - SPDocument* vd=doc->doc(); - if (vd != nullptr) - { + SPDocument *vd = doc->doc(); + if (vd != nullptr) { mydoc->changeUriAndHrefs(vd->getDocumentURI()); vd->emitReconstructionStart(); @@ -624,15 +598,13 @@ void Script::effect(Inkscape::Extension::Effect *module, // Getting the named view from the document generated by the extension SPNamedView *nv = sp_document_namedview(mydoc, nullptr); - //Check if it has a default layer set up + // Check if it has a default layer set up SPObject *layer = nullptr; - if ( nv != nullptr) - { - if( nv->default_layer_id != 0 ) { + if (nv != nullptr) { + if (nv->default_layer_id != 0) { SPDocument *document = desktop->doc(); - //If so, get that layer - if (document != nullptr) - { + // If so, get that layer + if (document != nullptr) { layer = document->getObjectById(g_quark_to_string(nv->default_layer_id)); } } @@ -640,9 +612,9 @@ void Script::effect(Inkscape::Extension::Effect *module, } sp_namedview_update_layers_from_document(desktop); - //If that layer exists, + // If that layer exists, if (layer) { - //set the current layer + // set the current layer desktop->setCurrentLayer(layer); } } @@ -652,8 +624,6 @@ void Script::effect(Inkscape::Extension::Effect *module, return; } - - /** \brief A function to replace all the elements in an old document by those from a new document. @@ -673,10 +643,9 @@ void Script::effect(Inkscape::Extension::Effect *module, Finally, it copies the attributes in namedview. */ -void Script::copy_doc (Inkscape::XML::Node * oldroot, Inkscape::XML::Node * newroot) +void Script::copy_doc(Inkscape::XML::Node *oldroot, Inkscape::XML::Node *newroot) { - if ((oldroot == nullptr) ||(newroot == nullptr)) - { + if ((oldroot == nullptr) || (newroot == nullptr)) { g_warning("Error on copy_doc: NULL pointer input."); return; } @@ -714,13 +683,10 @@ void Script::copy_doc (Inkscape::XML::Node * oldroot, Inkscape::XML::Node * newr std::vector delete_list; // Make list - for (Inkscape::XML::Node * child = oldroot->firstChild(); - child != nullptr; - child = child->next()) { + for (Inkscape::XML::Node *child = oldroot->firstChild(); child != nullptr; child = child->next()) { if (!strcmp("sodipodi:namedview", child->name())) { - for (Inkscape::XML::Node * oldroot_namedview_child = child->firstChild(); - oldroot_namedview_child != nullptr; - oldroot_namedview_child = oldroot_namedview_child->next()) { + for (Inkscape::XML::Node *oldroot_namedview_child = child->firstChild(); oldroot_namedview_child != nullptr; + oldroot_namedview_child = oldroot_namedview_child->next()) { delete_list.push_back(oldroot_namedview_child); } break; @@ -728,7 +694,7 @@ void Script::copy_doc (Inkscape::XML::Node * oldroot, Inkscape::XML::Node * newr } // Unparent (delete) - for (auto & i : delete_list) { + for (auto &i : delete_list) { sp_repr_unparent(i); } attribs.clear(); @@ -739,9 +705,7 @@ void Script::copy_doc (Inkscape::XML::Node * oldroot, Inkscape::XML::Node * newr shows it in a warning dialog to the user \param filename Filename of the stderr file */ -void Script::checkStderr (const Glib::ustring &data, - Gtk::MessageType type, - const Glib::ustring &message) +void Script::checkStderr(const Glib::ustring &data, Gtk::MessageType type, const Glib::ustring &message) { Gtk::MessageDialog warning(message, false, type, Gtk::BUTTONS_OK, true); warning.set_resizable(true); @@ -755,14 +719,14 @@ void Script::checkStderr (const Glib::ustring &data, auto vbox = warning.get_content_area(); /* Gtk::TextView * textview = new Gtk::TextView(Gtk::TextBuffer::create()); */ - Gtk::TextView * textview = new Gtk::TextView(); + Gtk::TextView *textview = new Gtk::TextView(); textview->set_editable(false); textview->set_wrap_mode(Gtk::WRAP_WORD); textview->show(); textview->get_buffer()->set_text(data.c_str()); - Gtk::ScrolledWindow * scrollwindow = new Gtk::ScrolledWindow(); + 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); @@ -779,7 +743,8 @@ void Script::checkStderr (const Glib::ustring &data, return; } -bool Script::cancelProcessing () { +bool Script::cancelProcessing() +{ _canceled = true; _main_loop->quit(); Glib::spawn_close_pid(_pid); @@ -787,7 +752,6 @@ bool Script::cancelProcessing () { return true; } - /** \brief This is the core of the extension file as it actually does the execution of the extension. \param in_command The command to be executed @@ -815,10 +779,8 @@ bool Script::cancelProcessing () { At the very end (after the data has been copied) both of the files are closed, and we return to what we were doing. */ -int Script::execute (const std::list &in_command, - const std::list &in_params, - const Glib::ustring &filein, - file_listener &fileout) +int Script::execute(const std::list &in_command, const std::list &in_params, + const Glib::ustring &filein, file_listener &fileout) { g_return_val_if_fail(!in_command.empty(), 0); @@ -858,21 +820,22 @@ int Script::execute (const std::list &in_command, argv.push_back(filein_native); } - //for(int i=0;i(0), // no flags sigc::slot(), - &_pid, // Pid - nullptr, // STDIN - &stdout_pipe, // STDOUT - &stderr_pipe); // STDERR + &_pid, // Pid + nullptr, // STDIN + &stdout_pipe, // STDOUT + &stderr_pipe); // STDERR } catch (Glib::Error &e) { - g_critical("Script::execute(): failed to execute program '%s'.\n\tReason: %s", program.c_str(), e.what().data()); + g_critical("Script::execute(): failed to execute program '%s'.\n\tReason: %s", program.c_str(), + e.what().data()); return 0; } @@ -902,12 +865,11 @@ int Script::execute (const std::list &in_command, } Glib::ustring stderr_data = fileerr.string(); - if (stderr_data.length() != 0 && - INKSCAPE.use_gui() - ) { - checkStderr(stderr_data, Gtk::MESSAGE_INFO, - _("Inkscape has received additional data from the script executed. " - "The script did not return an error, but this may indicate the results will not be as expected.")); + if (stderr_data.length() != 0 && INKSCAPE.use_gui()) { + checkStderr( + stderr_data, Gtk::MESSAGE_INFO, + _("Inkscape has received additional data from the script executed. " + "The script did not return an error, but this may indicate the results will not be as expected.")); } Glib::ustring stdout_data = fileout.string(); @@ -919,17 +881,19 @@ int Script::execute (const std::list &in_command, return stdout_data.length(); } - -void Script::file_listener::init(int fd, Glib::RefPtr main) { +void Script::file_listener::init(int fd, Glib::RefPtr main) +{ _channel = Glib::IOChannel::create_from_fd(fd); _channel->set_encoding(); - _conn = main->get_context()->signal_io().connect(sigc::mem_fun(*this, &file_listener::read), _channel, Glib::IO_IN | Glib::IO_HUP | Glib::IO_ERR); + _conn = main->get_context()->signal_io().connect(sigc::mem_fun(*this, &file_listener::read), _channel, + Glib::IO_IN | Glib::IO_HUP | Glib::IO_ERR); _main_loop = main; return; } -bool Script::file_listener::read(Glib::IOCondition condition) { +bool Script::file_listener::read(Glib::IOCondition condition) +{ if (condition != Glib::IO_IN) { _main_loop->quit(); return false; @@ -949,11 +913,13 @@ bool Script::file_listener::read(Glib::IOCondition condition) { return true; } -bool Script::file_listener::toFile(const Glib::ustring &name) { +bool Script::file_listener::toFile(const Glib::ustring &name) +{ return toFile(Glib::filename_from_utf8(name)); } -bool Script::file_listener::toFile(const std::string &name) { +bool Script::file_listener::toFile(const std::string &name) +{ try { Glib::RefPtr stdout_file = Glib::IOChannel::create_from_file(name, "w"); stdout_file->set_encoding(); @@ -964,9 +930,9 @@ bool Script::file_listener::toFile(const std::string &name) { return true; } -} // namespace Implementation -} // namespace Extension -} // namespace Inkscape +} // namespace Implementation +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/implementation/script.h b/src/extension/implementation/script.h index 69dc1c889ddf8f7f10e762d228b8517a9992a1d8..174ffb3c0d5381c53a230e1bfd0c3a2647158c98 100644 --- a/src/extension/implementation/script.h +++ b/src/extension/implementation/script.h @@ -14,12 +14,13 @@ #ifndef INKSCAPE_EXTENSION_IMPEMENTATION_SCRIPT_H_SEEN #define INKSCAPE_EXTENSION_IMPEMENTATION_SCRIPT_H_SEEN -#include "implementation.h" -#include -#include +#include #include #include -#include +#include +#include + +#include "implementation.h" namespace Inkscape { namespace XML { @@ -32,23 +33,25 @@ namespace Implementation { /** * Utility class used for loading and launching script extensions */ -class Script : public Implementation { +class Script : public Implementation +{ public: - Script(); ~Script() override; bool load(Inkscape::Extension::Extension *module) override; void unload(Inkscape::Extension::Extension *module) override; bool check(Inkscape::Extension::Extension *module) override; - ImplementationDocumentCache * newDocCache(Inkscape::Extension::Extension * ext, Inkscape::UI::View::View * view) override; + ImplementationDocumentCache *newDocCache(Inkscape::Extension::Extension *ext, + Inkscape::UI::View::View *view) override; Gtk::Widget *prefs_input(Inkscape::Extension::Input *module, gchar const *filename) override; SPDocument *open(Inkscape::Extension::Input *module, gchar const *filename) override; Gtk::Widget *prefs_output(Inkscape::Extension::Output *module) override; void save(Inkscape::Extension::Output *module, SPDocument *doc, gchar const *filename) override; - void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *doc, ImplementationDocumentCache * docCache) override; - bool cancelProcessing () override; + void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *doc, + ImplementationDocumentCache *docCache) override; + bool cancelProcessing() override; private: bool _canceled; @@ -61,25 +64,26 @@ private: */ std::list command; - /** - * This is the extension that will be used - * as the helper to read in or write out the - * data - */ + /** + * This is the extension that will be used + * as the helper to read in or write out the + * data + */ Glib::ustring helper_extension; - /** - * The window which should be considered as "parent window" of the script execution, - * e.g. when showin warning messages - * - * If set to NULL the main window of the currently active document is used. - */ + /** + * The window which should be considered as "parent window" of the script execution, + * e.g. when showin warning messages + * + * If set to NULL the main window of the currently active document is used. + */ Gtk::Window *parent_window; - void copy_doc(Inkscape::XML::Node * olddoc, Inkscape::XML::Node * newdoc); - void checkStderr (Glib::ustring const& filename, Gtk::MessageType type, Glib::ustring const& message); + void copy_doc(Inkscape::XML::Node *olddoc, Inkscape::XML::Node *newdoc); + void checkStderr(Glib::ustring const &filename, Gtk::MessageType type, Glib::ustring const &message); - class file_listener { + class file_listener + { Glib::ustring _string; sigc::connection _conn; Glib::RefPtr _channel; @@ -87,40 +91,38 @@ private: bool _dead; public: - file_listener () : _dead(false) { }; - virtual ~file_listener () { - _conn.disconnect(); - }; + file_listener() + : _dead(false){}; + virtual ~file_listener() { _conn.disconnect(); }; - bool isDead () { return _dead; } + bool isDead() { return _dead; } void init(int fd, Glib::RefPtr main); bool read(Glib::IOCondition condition); - Glib::ustring string () { return _string; }; + Glib::ustring string() { return _string; }; bool toFile(const Glib::ustring &name); bool toFile(const std::string &name); }; - int execute (const std::list &in_command, - const std::list &in_params, - const Glib::ustring &filein, - file_listener &fileout); + int execute(const std::list &in_command, const std::list &in_params, + const Glib::ustring &filein, file_listener &fileout); void pump_events(); /** \brief A definition of an interpreter, which can be specified in the INX file, but we need to know what to call */ - struct interpreter_t { - std::string prefstring; /**< The preferences key that can override the default */ - std::vector defaultvals; /**< The default values to check if the preferences are wrong */ + struct interpreter_t + { + std::string prefstring; /**< The preferences key that can override the default */ + std::vector defaultvals; /**< The default values to check if the preferences are wrong */ }; static const std::map interpreterTab; std::string resolveInterpreterExecutable(const Glib::ustring &interpNameArg); }; // class Script -} // namespace Implementation -} // namespace Extension -} // namespace Inkscape +} // namespace Implementation +} // namespace Extension +} // namespace Inkscape #endif // INKSCAPE_EXTENSION_IMPEMENTATION_SCRIPT_H_SEEN diff --git a/src/extension/implementation/xslt.cpp b/src/extension/implementation/xslt.cpp index dced1dd3749e0768f69858f5f7b99c371d1a32c8..cd0e00faf1d6965b438805034597e73b61bd55c3 100644 --- a/src/extension/implementation/xslt.cpp +++ b/src/extension/implementation/xslt.cpp @@ -15,28 +15,23 @@ #include "xslt.h" -#include +#include #include - #include #include #include +#include #include "document.h" -#include "file.h" - #include "extension/extension.h" -#include "extension/output.h" #include "extension/input.h" - +#include "extension/output.h" +#include "file.h" #include "io/resource.h" - #include "xml/node.h" #include "xml/repr.h" -#include - -Inkscape::XML::Document * sp_repr_do_read (xmlDocPtr doc, const gchar * default_ns); +Inkscape::XML::Document *sp_repr_do_read(xmlDocPtr doc, const gchar *default_ns); /* Namespaces */ namespace Inkscape { @@ -50,13 +45,12 @@ namespace Implementation { variables. */ -XSLT::XSLT() : - Implementation(), - _filename(""), - _parsedDoc(nullptr), - _stylesheet(nullptr) -{ -} +XSLT::XSLT() + : Implementation() + , _filename("") + , _parsedDoc(nullptr) + , _stylesheet(nullptr) +{} bool XSLT::check(Inkscape::Extension::Extension *module) { @@ -70,7 +64,9 @@ bool XSLT::check(Inkscape::Extension::Extension *module) bool XSLT::load(Inkscape::Extension::Extension *module) { - if (module->loaded()) { return true; } + if (module->loaded()) { + return true; + } Inkscape::XML::Node *child_repr = module->get_repr()->firstChild(); while (child_repr != nullptr) { @@ -92,7 +88,9 @@ bool XSLT::load(Inkscape::Extension::Extension *module) } _parsedDoc = xmlParseFile(_filename.c_str()); - if (_parsedDoc == nullptr) { return false; } + if (_parsedDoc == nullptr) { + return false; + } _stylesheet = xsltParseStylesheetDoc(_parsedDoc); @@ -101,19 +99,22 @@ bool XSLT::load(Inkscape::Extension::Extension *module) void XSLT::unload(Inkscape::Extension::Extension *module) { - if (!module->loaded()) { return; } + if (!module->loaded()) { + return; + } xsltFreeStylesheet(_stylesheet); // No need to use xmlfreedoc(_parsedDoc), it's handled by xsltFreeStylesheet(_stylesheet); return; } -SPDocument * XSLT::open(Inkscape::Extension::Input */*module*/, - gchar const *filename) +SPDocument *XSLT::open(Inkscape::Extension::Input * /*module*/, gchar const *filename) { xmlDocPtr filein = xmlParseFile(filename); - if (filein == nullptr) { return nullptr; } + if (filein == nullptr) { + return nullptr; + } - const char * params[1]; + const char *params[1]; params[0] = nullptr; char *oldlocale = g_strdup(std::setlocale(LC_NUMERIC, nullptr)); std::setlocale(LC_NUMERIC, "C"); @@ -121,7 +122,7 @@ SPDocument * XSLT::open(Inkscape::Extension::Input */*module*/, xmlDocPtr result = xsltApplyStylesheet(_stylesheet, filein, params); xmlFreeDoc(filein); - Inkscape::XML::Document * rdoc = sp_repr_do_read( result, SP_SVG_NS_URI); + Inkscape::XML::Document *rdoc = sp_repr_do_read(result, SP_SVG_NS_URI); xmlFreeDoc(result); std::setlocale(LC_NUMERIC, oldlocale); g_free(oldlocale); @@ -134,9 +135,9 @@ SPDocument * XSLT::open(Inkscape::Extension::Input */*module*/, return nullptr; } - gchar * base = nullptr; - gchar * name = nullptr; - gchar * s = nullptr, * p = nullptr; + gchar *base = nullptr; + gchar *name = nullptr; + gchar *s = nullptr, *p = nullptr; s = g_strdup(filename); p = strrchr(s, '/'); if (p) { @@ -149,9 +150,10 @@ SPDocument * XSLT::open(Inkscape::Extension::Input */*module*/, } g_free(s); - SPDocument * doc = SPDocument::createDoc(rdoc, filename, base, name, true, nullptr); + SPDocument *doc = SPDocument::createDoc(rdoc, filename, base, name, true, nullptr); - g_free(base); g_free(name); + g_free(base); + g_free(name); return doc; } @@ -185,8 +187,8 @@ void XSLT::save(Inkscape::Extension::Output *module, SPDocument *doc, gchar cons return; } - if (!sp_repr_save_rebased_file(repr->document(), tempfilename_out.c_str(), SP_SVG_NS_URI, - doc->getDocumentBase(), filename)) { + if (!sp_repr_save_rebased_file(repr->document(), tempfilename_out.c_str(), SP_SVG_NS_URI, doc->getDocumentBase(), + filename)) { throw Inkscape::Extension::Output::save_failed(); } @@ -199,15 +201,15 @@ void XSLT::save(Inkscape::Extension::Output *module, SPDocument *doc, gchar cons std::list params; module->paramListString(params); const int max_parameters = params.size() * 2; - const char * xslt_params[max_parameters+1] ; + const char *xslt_params[max_parameters + 1]; int count = 0; - for(auto & param : params) { + for (auto ¶m : params) { std::size_t pos = param.find("="); std::ostringstream parameter; std::ostringstream value; - parameter << param.substr(2,pos-2); - value << param.substr(pos+1); + parameter << param.substr(2, pos - 2); + value << param.substr(pos + 1); xslt_params[count++] = g_strdup_printf("%s", parameter.str().c_str()); xslt_params[count++] = g_strdup_printf("'%s'", value.str().c_str()); } @@ -217,7 +219,7 @@ void XSLT::save(Inkscape::Extension::Output *module, SPDocument *doc, gchar cons char *oldlocale = g_strdup(std::setlocale(LC_NUMERIC, nullptr)); std::setlocale(LC_NUMERIC, "C"); xmlDocPtr newdoc = xsltApplyStylesheet(_stylesheet, svgdoc, xslt_params); - //xmlSaveFile(filename, newdoc); + // xmlSaveFile(filename, newdoc); int success = xsltSaveResultToFilename(filename, newdoc, _stylesheet, 0); std::setlocale(LC_NUMERIC, oldlocale); g_free(oldlocale); @@ -235,11 +237,9 @@ void XSLT::save(Inkscape::Extension::Output *module, SPDocument *doc, gchar cons return; } - -} /* Implementation */ -} /* module */ -} /* Inkscape */ - +} // namespace Implementation +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/implementation/xslt.h b/src/extension/implementation/xslt.h index 745d7f57aa458ccc32c1397e37732ec46088ac15..1278bc9b6e74d142114ae20022c6c083cd21fc68 100644 --- a/src/extension/implementation/xslt.h +++ b/src/extension/implementation/xslt.h @@ -14,7 +14,6 @@ #define __INKSCAPE_EXTENSION_IMPEMENTATION_XSLT_H__ #include "implementation.h" - #include "libxml/tree.h" #include "libxslt/xslt.h" #include "libxslt/xsltInternals.h" @@ -23,35 +22,34 @@ namespace Inkscape { namespace XML { class Node; } -} - +} // namespace Inkscape namespace Inkscape { namespace Extension { namespace Implementation { -class XSLT : public Implementation { +class XSLT : public Implementation +{ private: std::string _filename; xmlDocPtr _parsedDoc; xsltStylesheetPtr _stylesheet; public: - XSLT (); + XSLT(); bool load(Inkscape::Extension::Extension *module) override; void unload(Inkscape::Extension::Extension *module) override; bool check(Inkscape::Extension::Extension *module) override; - SPDocument *open(Inkscape::Extension::Input *module, - gchar const *filename) override; + SPDocument *open(Inkscape::Extension::Input *module, gchar const *filename) override; void save(Inkscape::Extension::Output *module, SPDocument *doc, gchar const *filename) override; }; -} /* Inkscape */ -} /* Extension */ -} /* Implementation */ +} // namespace Implementation +} // namespace Extension +} // namespace Inkscape #endif /* __INKSCAPE_EXTENSION_IMPEMENTATION_XSLT_H__ */ /* diff --git a/src/extension/init.cpp b/src/extension/init.cpp index 5a95fb8efa0cb01eb19863187cddc27ae41da701..6efd1b127605dc8f4b0ce3dcf0efb6406000374e 100644 --- a/src/extension/init.cpp +++ b/src/extension/init.cpp @@ -14,44 +14,41 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef HAVE_POPPLER -# include "internal/pdfinput/pdf-input.h" +#include "internal/pdfinput/pdf-input.h" #endif -#include "path-prefix.h" - -#include "inkscape.h" - +#include #include #include #include -#include "system.h" #include "db.h" +#include "inkscape.h" +#include "internal/emf-inout.h" +#include "internal/emf-print.h" #include "internal/svgz.h" -# include "internal/emf-inout.h" -# include "internal/emf-print.h" -# include "internal/wmf-inout.h" -# include "internal/wmf-print.h" - -#include +#include "internal/wmf-inout.h" +#include "internal/wmf-print.h" +#include "path-prefix.h" +#include "system.h" #ifdef CAIRO_HAS_PDF_SURFACE -# include "internal/cairo-renderer-pdf-out.h" +#include "internal/cairo-renderer-pdf-out.h" #endif #ifdef CAIRO_HAS_PS_SURFACE -# include "internal/cairo-ps-out.h" +#include "internal/cairo-ps-out.h" #endif -#include "internal/pov-out.h" -#include "internal/odf.h" -#include "internal/latex-pstricks-out.h" -#include "internal/latex-pstricks.h" -#include "internal/gdkpixbuf-input.h" #include "internal/bluredge.h" +#include "internal/gdkpixbuf-input.h" #include "internal/gimpgrad.h" #include "internal/grid.h" +#include "internal/latex-pstricks-out.h" +#include "internal/latex-pstricks.h" +#include "internal/odf.h" +#include "internal/pov-out.h" #ifdef WITH_LIBWPG #include "internal/wpg-input.h" #endif @@ -61,15 +58,16 @@ #ifdef WITH_LIBCDR #include "internal/cdr-input.h" #endif -#include "preferences.h" -#include "io/sys.h" #include "io/resource.h" +#include "io/sys.h" +#include "preferences.h" #ifdef WITH_DBUS #include "dbus/dbus-init.h" #endif #ifdef WITH_MAGICK #include + #include "internal/bitmap/adaptiveThreshold.h" #include "internal/bitmap/addNoise.h" #include "internal/bitmap/blur.h" @@ -107,9 +105,8 @@ #include "internal/bitmap/wave.h" #endif /* WITH_MAGICK */ -#include "internal/filter/filter.h" - #include "init.h" +#include "internal/filter/filter.h" using namespace Inkscape::IO::Resource; @@ -118,7 +115,7 @@ namespace Extension { /** This is the extension that all files are that are pulled from the extension directory and parsed */ -#define SP_MODULE_EXTENSION "inx" +#define SP_MODULE_EXTENSION "inx" static void check_extensions(); @@ -131,12 +128,10 @@ static void check_extensions(); * \param pref_default Default string to set * \param extension_family List of extensions to search */ -static void -update_pref(Glib::ustring const &pref_path, - gchar const *pref_default) +static void update_pref(Glib::ustring const &pref_path, gchar const *pref_default) { Glib::ustring pref = Inkscape::Preferences::get()->getString(pref_path); - if (!Inkscape::Extension::db.get( pref.data() ) /*missing*/) { + if (!Inkscape::Extension::db.get(pref.data()) /*missing*/) { Inkscape::Preferences::get()->setString(pref_path, pref_default); } } @@ -147,8 +142,7 @@ update_pref(Glib::ustring const &pref_path, * This should be a list of all the internal modules that need to initialized. This is just a * convenient place to put them. */ -void -init() +void init() { /* TODO: Change to Internal */ Internal::Svg::init(); @@ -227,14 +221,14 @@ init() Internal::Bitmap::Solarize::init(); Internal::Bitmap::Spread::init(); Internal::Bitmap::Swirl::init(); - //Internal::Bitmap::Threshold::init(); + // Internal::Bitmap::Threshold::init(); Internal::Bitmap::Unsharpmask::init(); Internal::Bitmap::Wave::init(); #endif /* WITH_MAGICK */ Internal::Filter::Filter::filters_all(); - for(auto &filename: get_filenames(EXTENSIONS, {SP_MODULE_EXTENSION})) { + for (auto &filename : get_filenames(EXTENSIONS, {SP_MODULE_EXTENSION})) { build_from_file(filename.c_str()); } @@ -250,20 +244,19 @@ init() /* This is a hack to deal with updating saved outdated module * names in the prefs... */ - update_pref("/dialogs/save_as/default", - SP_MODULE_KEY_OUTPUT_SVG_INKSCAPE + update_pref("/dialogs/save_as/default", SP_MODULE_KEY_OUTPUT_SVG_INKSCAPE // Inkscape::Extension::db.get_output_list() - ); + ); } -static void -check_extensions_internal(Extension *in_plug, gpointer in_data) +static void check_extensions_internal(Extension *in_plug, gpointer in_data) { int *count = (int *)in_data; - if (in_plug == nullptr) return; + if (in_plug == nullptr) + return; if (!in_plug->deactivated() && !in_plug->check()) { - in_plug->deactivate(); + in_plug->deactivate(); (*count)++; } } @@ -275,13 +268,13 @@ static void check_extensions() Inkscape::Extension::Extension::error_file_open(); while (count != 0) { count = 0; - db.foreach(check_extensions_internal, (gpointer)&count); + db.foreach (check_extensions_internal, (gpointer)&count); } Inkscape::Extension::Extension::error_file_close(); } -} } /* namespace Inkscape::Extension */ - +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/init.h b/src/extension/init.h index 328ee89d7859c834617adb1a8b59ead7bb8edebf..0e0524ee88f233c156d49f054f32bbc2d2248174 100644 --- a/src/extension/init.h +++ b/src/extension/init.h @@ -19,9 +19,10 @@ namespace Inkscape { namespace Extension { -void init (); +void init(); -} } /* namespace Inkscape::Extension */ +} +} // namespace Inkscape #endif /* INKSCAPE_EXTENSION_INIT_H__ */ diff --git a/src/extension/input.cpp b/src/extension/input.cpp index cf02c274d3149a3462bdff5634f2b20b892aaf78..b84040cbb5b6c4906a3601b91af144f61b0aae07 100644 --- a/src/extension/input.cpp +++ b/src/extension/input.cpp @@ -10,15 +10,11 @@ #include "input.h" -#include "timer.h" - #include "implementation/implementation.h" - #include "prefdialog/prefdialog.h" - +#include "timer.h" #include "xml/repr.h" - /* Inkscape::Extension::Input */ namespace Inkscape { @@ -40,7 +36,7 @@ namespace Extension { Overall, there are many levels of indentation, just to handle the levels of indentation in the XML file. */ -Input::Input (Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory) +Input::Input(Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory) : Extension(in_repr, in_imp, base_directory) { mimetype = nullptr; @@ -50,7 +46,7 @@ Input::Input (Inkscape::XML::Node *in_repr, Implementation::Implementation *in_i output_extension = nullptr; if (repr != nullptr) { - Inkscape::XML::Node * child_repr; + Inkscape::XML::Node *child_repr; child_repr = repr->firstChild(); @@ -58,30 +54,30 @@ Input::Input (Inkscape::XML::Node *in_repr, Implementation::Implementation *in_i if (!strcmp(child_repr->name(), INKSCAPE_EXTENSION_NS "input")) { child_repr = child_repr->firstChild(); while (child_repr != nullptr) { - char const * chname = child_repr->name(); - if (!strncmp(chname, INKSCAPE_EXTENSION_NS_NC, strlen(INKSCAPE_EXTENSION_NS_NC))) { - chname += strlen(INKSCAPE_EXTENSION_NS); - } + char const *chname = child_repr->name(); + if (!strncmp(chname, INKSCAPE_EXTENSION_NS_NC, strlen(INKSCAPE_EXTENSION_NS_NC))) { + chname += strlen(INKSCAPE_EXTENSION_NS); + } if (chname[0] == '_') /* Allow _ for translation of tags */ chname++; if (!strcmp(chname, "extension")) { - g_free (extension); + g_free(extension); extension = g_strdup(child_repr->firstChild()->content()); } if (!strcmp(chname, "mimetype")) { - g_free (mimetype); + g_free(mimetype); mimetype = g_strdup(child_repr->firstChild()->content()); } if (!strcmp(chname, "filetypename")) { - g_free (filetypename); + g_free(filetypename); filetypename = g_strdup(child_repr->firstChild()->content()); } if (!strcmp(chname, "filetypetooltip")) { - g_free (filetypetooltip); + g_free(filetypetooltip); filetypetooltip = g_strdup(child_repr->firstChild()->content()); } if (!strcmp(chname, "output_extension")) { - g_free (output_extension); + g_free(output_extension); output_extension = g_strdup(child_repr->firstChild()->content()); } @@ -93,7 +89,6 @@ Input::Input (Inkscape::XML::Node *in_repr, Implementation::Implementation *in_i child_repr = child_repr->next(); } - } return; @@ -103,7 +98,7 @@ Input::Input (Inkscape::XML::Node *in_repr, Implementation::Implementation *in_i \return None \brief Destroys an Input extension */ -Input::~Input () +Input::~Input() { g_free(mimetype); g_free(extension); @@ -121,8 +116,7 @@ Input::~Input () a filename extension and a MIME type. Then it calls the parent class' check function which also checks out the implementation. */ -bool -Input::check () +bool Input::check() { if (extension == nullptr) return FALSE; @@ -142,8 +136,7 @@ Input::check () file actually exists. If it doesn't, a NULL is returned. If the file exits, then it is opened using the implementation of this extension. */ -SPDocument * -Input::open (const gchar *uri) +SPDocument *Input::open(const gchar *uri) { if (!loaded()) { set_state(Extension::STATE_LOADED); @@ -162,8 +155,7 @@ Input::open (const gchar *uri) \return IETF mime-type for the extension \brief Get the mime-type that describes this extension */ -gchar * -Input::get_mimetype() +gchar *Input::get_mimetype() { return mimetype; } @@ -172,8 +164,7 @@ Input::get_mimetype() \return Filename extension for the extension \brief Get the filename extension for this extension */ -gchar * -Input::get_extension() +gchar *Input::get_extension() { return extension; } @@ -182,8 +173,7 @@ Input::get_extension() \return The name of the filetype supported \brief Get the name of the filetype supported */ -const char * -Input::get_filetypename(bool translated) +const char *Input::get_filetypename(bool translated) { const char *name; @@ -203,8 +193,7 @@ Input::get_filetypename(bool translated) \return Tooltip giving more information on the filetype \brief Get the tooltip for more information on the filetype */ -const char * -Input::get_filetypetooltip(bool translated) +const char *Input::get_filetypetooltip(bool translated) { if (filetypetooltip && translated) { return get_translation(filetypetooltip); @@ -219,8 +208,7 @@ Input::get_filetypetooltip(bool translated) Calls the implementation to get the preferences. */ -bool -Input::prefs (const gchar *uri) +bool Input::prefs(const gchar *uri) { if (!loaded()) { set_state(Extension::STATE_LOADED); @@ -229,7 +217,7 @@ Input::prefs (const gchar *uri) return false; } - Gtk::Widget * controls; + Gtk::Widget *controls; controls = imp->prefs_input(this, uri); if (controls == nullptr) { // std::cout << "No preferences for Input" << std::endl; @@ -246,7 +234,8 @@ Input::prefs (const gchar *uri) return (response == Gtk::RESPONSE_OK); } -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/input.h b/src/extension/input.h index 5952c3c0442f7facabcc6e67120b98a2675269e2..37fcb733e6a630f635ede6267a5712f0d887b881 100644 --- a/src/extension/input.h +++ b/src/extension/input.h @@ -8,12 +8,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #ifndef INKSCAPE_EXTENSION_INPUT_H__ #define INKSCAPE_EXTENSION_INPUT_H__ #include #include + #include "extension.h" class SPDocument; @@ -21,25 +21,29 @@ class SPDocument; namespace Inkscape { namespace Extension { -class Input : public Extension { - gchar *mimetype; /**< What is the mime type this inputs? */ - gchar *extension; /**< The extension of the input files */ - gchar *filetypename; /**< A userfriendly name for the file type */ - gchar *filetypetooltip; /**< A more detailed description of the filetype */ +class Input : public Extension +{ + gchar *mimetype; /**< What is the mime type this inputs? */ + gchar *extension; /**< The extension of the input files */ + gchar *filetypename; /**< A userfriendly name for the file type */ + gchar *filetypetooltip; /**< A more detailed description of the filetype */ -public: /* this is a hack for this release, this will be private shortly */ - gchar *output_extension; /**< Setting of what output extension should be used */ +public: /* this is a hack for this release, this will be private shortly */ + gchar *output_extension; /**< Setting of what output extension should be used */ public: - struct open_failed : public std::exception { + struct open_failed : public std::exception + { ~open_failed() noexcept override = default; const char *what() const noexcept override { return "Open failed"; } }; - struct no_extension_found : public std::exception { + struct no_extension_found : public std::exception + { ~no_extension_found() noexcept override = default; const char *what() const noexcept override { return "No suitable input extension found"; } }; - struct open_cancelled : public std::exception { + struct open_cancelled : public std::exception + { ~open_cancelled() noexcept override = default; const char *what() const noexcept override { return "Open was cancelled"; } }; @@ -49,15 +53,16 @@ public: bool check() override; - SPDocument * open (gchar const *uri); - gchar * get_mimetype (); - gchar * get_extension (); - const char * get_filetypename (bool translated=false); - const char * get_filetypetooltip (bool translated=false); - bool prefs (gchar const *uri); + SPDocument *open(gchar const *uri); + gchar *get_mimetype(); + gchar *get_extension(); + const char *get_filetypename(bool translated = false); + const char *get_filetypetooltip(bool translated = false); + bool prefs(gchar const *uri); }; -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape #endif /* INKSCAPE_EXTENSION_INPUT_H__ */ /* diff --git a/src/extension/internal/bitmap/adaptiveThreshold.cpp b/src/extension/internal/bitmap/adaptiveThreshold.cpp index 7c85d84ed1ec037dab0a6bc23d671bfb86734195..be8ffc13f360d5c0d78d6645d36d8af15e1db9ef 100644 --- a/src/extension/internal/bitmap/adaptiveThreshold.cpp +++ b/src/extension/internal/bitmap/adaptiveThreshold.cpp @@ -7,33 +7,33 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "adaptiveThreshold.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -AdaptiveThreshold::applyEffect(Magick::Image *image) { - image->adaptiveThreshold(_width, _height); + +void AdaptiveThreshold::applyEffect(Magick::Image *image) +{ + image->adaptiveThreshold(_width, _height); } -void -AdaptiveThreshold::refreshParameters(Inkscape::Extension::Effect *module) { - _width = module->get_param_int("width"); - _height = module->get_param_int("height"); - _offset = module->get_param_int("offset"); +void AdaptiveThreshold::refreshParameters(Inkscape::Extension::Effect *module) +{ + _width = module->get_param_int("width"); + _height = module->get_param_int("height"); + _offset = module->get_param_int("offset"); } #include "../clear-n_.h" -void -AdaptiveThreshold::init() +void AdaptiveThreshold::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/adaptiveThreshold.h b/src/extension/internal/bitmap/adaptiveThreshold.h index 066f13ba04f88bf441fd88e5ac489836a7ebadff..a9d68df4516cdad3301a6cb24b2389f601e5f7a6 100644 --- a/src/extension/internal/bitmap/adaptiveThreshold.h +++ b/src/extension/internal/bitmap/adaptiveThreshold.h @@ -17,13 +17,14 @@ namespace Bitmap { class AdaptiveThreshold : public ImageMagick { private: - unsigned int _width; - unsigned int _height; - unsigned _offset; + unsigned int _width; + unsigned int _height; + unsigned _offset; + public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init (); + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/addNoise.cpp b/src/extension/internal/bitmap/addNoise.cpp index 0bedb3cbf3bb2ae271b95b77cdad91c124cbe655..ce4d412191d4bd2d720f4daa6b240672d53e33e7 100644 --- a/src/extension/internal/bitmap/addNoise.cpp +++ b/src/extension/internal/bitmap/addNoise.cpp @@ -7,39 +7,45 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "addNoise.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -AddNoise::applyEffect(Magick::Image *image) { - Magick::NoiseType noiseType = Magick::UniformNoise; - if (!strcmp(_noiseTypeName, "Uniform Noise")) noiseType = Magick::UniformNoise; - else if (!strcmp(_noiseTypeName, "Gaussian Noise")) noiseType = Magick::GaussianNoise; - else if (!strcmp(_noiseTypeName, "Multiplicative Gaussian Noise")) noiseType = Magick::MultiplicativeGaussianNoise; - else if (!strcmp(_noiseTypeName, "Impulse Noise")) noiseType = Magick::ImpulseNoise; - else if (!strcmp(_noiseTypeName, "Laplacian Noise")) noiseType = Magick::LaplacianNoise; - else if (!strcmp(_noiseTypeName, "Poisson Noise")) noiseType = Magick::PoissonNoise; - - image->addNoise(noiseType); + +void AddNoise::applyEffect(Magick::Image *image) +{ + Magick::NoiseType noiseType = Magick::UniformNoise; + if (!strcmp(_noiseTypeName, "Uniform Noise")) + noiseType = Magick::UniformNoise; + else if (!strcmp(_noiseTypeName, "Gaussian Noise")) + noiseType = Magick::GaussianNoise; + else if (!strcmp(_noiseTypeName, "Multiplicative Gaussian Noise")) + noiseType = Magick::MultiplicativeGaussianNoise; + else if (!strcmp(_noiseTypeName, "Impulse Noise")) + noiseType = Magick::ImpulseNoise; + else if (!strcmp(_noiseTypeName, "Laplacian Noise")) + noiseType = Magick::LaplacianNoise; + else if (!strcmp(_noiseTypeName, "Poisson Noise")) + noiseType = Magick::PoissonNoise; + + image->addNoise(noiseType); } -void -AddNoise::refreshParameters(Inkscape::Extension::Effect *module) { - _noiseTypeName = module->get_param_optiongroup("noiseType"); +void AddNoise::refreshParameters(Inkscape::Extension::Effect *module) +{ + _noiseTypeName = module->get_param_optiongroup("noiseType"); } #include "../clear-n_.h" -void -AddNoise::init() +void AddNoise::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/addNoise.h b/src/extension/internal/bitmap/addNoise.h index 06ce8c397c875b02048b06e5ef3676bac4b931c4..7bb5584f8e47375e855b37ace7aa34a7b46354d9 100644 --- a/src/extension/internal/bitmap/addNoise.h +++ b/src/extension/internal/bitmap/addNoise.h @@ -17,11 +17,12 @@ namespace Bitmap { class AddNoise : public ImageMagick { private: - const gchar* _noiseTypeName; + const gchar *_noiseTypeName; + public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init (); + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/blur.cpp b/src/extension/internal/bitmap/blur.cpp index ba9d5237118ad1b99a22ba96435b140a6ee30cfc..95be77f8a9f3c91950440928081319edcc557b1a 100644 --- a/src/extension/internal/bitmap/blur.cpp +++ b/src/extension/internal/bitmap/blur.cpp @@ -7,32 +7,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "blur.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Blur::applyEffect(Magick::Image *image) { - image->blur(_radius, _sigma); + +void Blur::applyEffect(Magick::Image *image) +{ + image->blur(_radius, _sigma); } -void -Blur::refreshParameters(Inkscape::Extension::Effect *module) { - _radius = module->get_param_float("radius"); - _sigma = module->get_param_float("sigma"); +void Blur::refreshParameters(Inkscape::Extension::Effect *module) +{ + _radius = module->get_param_float("radius"); + _sigma = module->get_param_float("sigma"); } #include "../clear-n_.h" -void -Blur::init() +void Blur::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/blur.h b/src/extension/internal/bitmap/blur.h index da93a42fd6cf2423bd0402b6a029b859139fc4c4..98e14a869706c20e6ef7874613d64fa5e8a60b79 100644 --- a/src/extension/internal/bitmap/blur.h +++ b/src/extension/internal/bitmap/blur.h @@ -17,11 +17,12 @@ namespace Bitmap { class Blur : public ImageMagick { private: - float _radius; - float _sigma; + float _radius; + float _sigma; + public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; static void init(); }; diff --git a/src/extension/internal/bitmap/channel.cpp b/src/extension/internal/bitmap/channel.cpp index 38ba8f11feb6aa051093e6a287fb21955b3bc940..d493d9b961c1c9dae77ce41cd4554770a2e8a07c 100644 --- a/src/extension/internal/bitmap/channel.cpp +++ b/src/extension/internal/bitmap/channel.cpp @@ -7,42 +7,51 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "channel.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Channel::applyEffect(Magick::Image *image) { - Magick::ChannelType layer = Magick::UndefinedChannel; - if (!strcmp(_layerName, "Red Channel")) layer = Magick::RedChannel; - else if (!strcmp(_layerName, "Green Channel")) layer = Magick::GreenChannel; - else if (!strcmp(_layerName, "Blue Channel")) layer = Magick::BlueChannel; - else if (!strcmp(_layerName, "Cyan Channel")) layer = Magick::CyanChannel; - else if (!strcmp(_layerName, "Magenta Channel")) layer = Magick::MagentaChannel; - else if (!strcmp(_layerName, "Yellow Channel")) layer = Magick::YellowChannel; - else if (!strcmp(_layerName, "Black Channel")) layer = Magick::BlackChannel; - else if (!strcmp(_layerName, "Opacity Channel")) layer = Magick::OpacityChannel; - else if (!strcmp(_layerName, "Matte Channel")) layer = Magick::MatteChannel; - - image->channel(layer); + +void Channel::applyEffect(Magick::Image *image) +{ + Magick::ChannelType layer = Magick::UndefinedChannel; + if (!strcmp(_layerName, "Red Channel")) + layer = Magick::RedChannel; + else if (!strcmp(_layerName, "Green Channel")) + layer = Magick::GreenChannel; + else if (!strcmp(_layerName, "Blue Channel")) + layer = Magick::BlueChannel; + else if (!strcmp(_layerName, "Cyan Channel")) + layer = Magick::CyanChannel; + else if (!strcmp(_layerName, "Magenta Channel")) + layer = Magick::MagentaChannel; + else if (!strcmp(_layerName, "Yellow Channel")) + layer = Magick::YellowChannel; + else if (!strcmp(_layerName, "Black Channel")) + layer = Magick::BlackChannel; + else if (!strcmp(_layerName, "Opacity Channel")) + layer = Magick::OpacityChannel; + else if (!strcmp(_layerName, "Matte Channel")) + layer = Magick::MatteChannel; + + image->channel(layer); } -void -Channel::refreshParameters(Inkscape::Extension::Effect *module) { - _layerName = module->get_param_optiongroup("layer"); +void Channel::refreshParameters(Inkscape::Extension::Effect *module) +{ + _layerName = module->get_param_optiongroup("layer"); } #include "../clear-n_.h" -void -Channel::init() +void Channel::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/channel.h b/src/extension/internal/bitmap/channel.h index e215344f7566b009356aef55aca101f1764cec67..3963bd5151c0ff9b854da5dc4e439981084867be 100644 --- a/src/extension/internal/bitmap/channel.h +++ b/src/extension/internal/bitmap/channel.h @@ -14,16 +14,16 @@ namespace Extension { namespace Internal { namespace Bitmap { -class Channel : public ImageMagick { - +class Channel : public ImageMagick +{ private: - const gchar * _layerName; + const gchar *_layerName; public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init (); + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/charcoal.cpp b/src/extension/internal/bitmap/charcoal.cpp index 63433995ef4333f34ba8017e55ee2e7e2727a41a..45d5994b4eb56d3953c081728e645413db030d17 100644 --- a/src/extension/internal/bitmap/charcoal.cpp +++ b/src/extension/internal/bitmap/charcoal.cpp @@ -7,32 +7,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "charcoal.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Charcoal::applyEffect(Magick::Image* image) { - image->charcoal(_radius, _sigma); + +void Charcoal::applyEffect(Magick::Image *image) +{ + image->charcoal(_radius, _sigma); } -void -Charcoal::refreshParameters(Inkscape::Extension::Effect* module) { - _radius = module->get_param_float("radius"); - _sigma = module->get_param_float("sigma"); +void Charcoal::refreshParameters(Inkscape::Extension::Effect *module) +{ + _radius = module->get_param_float("radius"); + _sigma = module->get_param_float("sigma"); } #include "../clear-n_.h" -void -Charcoal::init() +void Charcoal::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/charcoal.h b/src/extension/internal/bitmap/charcoal.h index c22574689224e1d2c6ee7509b0dea4c8a834ab71..0ad71cbe881bba43c823fb2203633c317e6e597d 100644 --- a/src/extension/internal/bitmap/charcoal.h +++ b/src/extension/internal/bitmap/charcoal.h @@ -17,11 +17,12 @@ namespace Bitmap { class Charcoal : public ImageMagick { private: - float _radius; - float _sigma; + float _radius; + float _sigma; + public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; static void init(); }; diff --git a/src/extension/internal/bitmap/colorize.cpp b/src/extension/internal/bitmap/colorize.cpp index ea9d748a797824124ba609b7c8012bf6f34444b8..4e31ddfc41529889a2a16fcda2cf549cd49d879e 100644 --- a/src/extension/internal/bitmap/colorize.cpp +++ b/src/extension/internal/bitmap/colorize.cpp @@ -9,42 +9,40 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "colorize.h" -#include "color.h" - -#include #include +#include + +#include "color.h" +#include "extension/effect.h" +#include "extension/system.h" namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Colorize::applyEffect(Magick::Image *image) { - float r = ((_color >> 24) & 0xff) / 255.0F; - float g = ((_color >> 16) & 0xff) / 255.0F; - float b = ((_color >> 8) & 0xff) / 255.0F; - float a = ((_color ) & 0xff) / 255.0F; - - Magick::ColorRGB mc(r,g,b); - - image->colorize(a * 100, mc); + +void Colorize::applyEffect(Magick::Image *image) +{ + float r = ((_color >> 24) & 0xff) / 255.0F; + float g = ((_color >> 16) & 0xff) / 255.0F; + float b = ((_color >> 8) & 0xff) / 255.0F; + float a = ((_color)&0xff) / 255.0F; + + Magick::ColorRGB mc(r, g, b); + + image->colorize(a * 100, mc); } -void -Colorize::refreshParameters(Inkscape::Extension::Effect *module) { - _color = module->get_param_color("color"); +void Colorize::refreshParameters(Inkscape::Extension::Effect *module) +{ + _color = module->get_param_color("color"); } #include "../clear-n_.h" -void -Colorize::init() +void Colorize::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/colorize.h b/src/extension/internal/bitmap/colorize.h index 7c16ef5b609cb8f654be4f0ad4d7e2059c2d5190..23f5d02146f0c17629c16d5d1201dec77dc98cb3 100644 --- a/src/extension/internal/bitmap/colorize.h +++ b/src/extension/internal/bitmap/colorize.h @@ -16,16 +16,17 @@ namespace Extension { namespace Internal { namespace Bitmap { -class Colorize : public ImageMagick { +class Colorize : public ImageMagick +{ private: - unsigned int _opacity; - guint32 _color; + unsigned int _opacity; + guint32 _color; public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init (); + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/contrast.cpp b/src/extension/internal/bitmap/contrast.cpp index 2f439237ae9c0023f4b66c04e2349ae1a2d1f975..72591bfcc7049c79d1f5fcb0c169ec91ae2f69df 100644 --- a/src/extension/internal/bitmap/contrast.cpp +++ b/src/extension/internal/bitmap/contrast.cpp @@ -7,34 +7,34 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "contrast.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Contrast::applyEffect(Magick::Image *image) { - // the contrast method's argument seems to be binary, so we perform it multiple times - // to get the desired level of effect - for (unsigned int i = 0; i < _sharpen; i ++) - image->contrast(1); + +void Contrast::applyEffect(Magick::Image *image) +{ + // the contrast method's argument seems to be binary, so we perform it multiple times + // to get the desired level of effect + for (unsigned int i = 0; i < _sharpen; i++) + image->contrast(1); } -void -Contrast::refreshParameters(Inkscape::Extension::Effect *module) { - _sharpen = module->get_param_int("sharpen"); +void Contrast::refreshParameters(Inkscape::Extension::Effect *module) +{ + _sharpen = module->get_param_int("sharpen"); } #include "../clear-n_.h" -void -Contrast::init() +void Contrast::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/contrast.h b/src/extension/internal/bitmap/contrast.h index c0e95e4a20d624de76d53654cbf1276b97899d4c..91b4f75b3bac39c20c226bb41c973018539c13c5 100644 --- a/src/extension/internal/bitmap/contrast.h +++ b/src/extension/internal/bitmap/contrast.h @@ -17,10 +17,11 @@ namespace Bitmap { class Contrast : public ImageMagick { private: - unsigned int _sharpen; + unsigned int _sharpen; + public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; static void init(); }; diff --git a/src/extension/internal/bitmap/crop.cpp b/src/extension/internal/bitmap/crop.cpp index 785c32a13a292efd6c9477c423a968c3b01c2bab..4d7ca1cc6dc89e8181cb39aa02c17af999a04920 100644 --- a/src/extension/internal/bitmap/crop.cpp +++ b/src/extension/internal/bitmap/crop.cpp @@ -6,23 +6,24 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "crop.h" + +#include + #include "2geom/transforms.h" #include "extension/effect.h" #include "extension/system.h" - -#include "crop.h" -#include "selection-chemistry.h" -#include "object/sp-item.h" #include "object/sp-item-transform.h" -#include +#include "object/sp-item.h" +#include "selection-chemistry.h" namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { -void -Crop::applyEffect(Magick::Image *image) { +void Crop::applyEffect(Magick::Image *image) +{ int width = image->baseColumns() - (_left + _right); int height = image->baseRows() - (_top + _bottom); if (width > 0 and height > 0) { @@ -31,27 +32,26 @@ Crop::applyEffect(Magick::Image *image) { } } -void -Crop::postEffect(Magick::Image *image, SPItem *item) { - +void Crop::postEffect(Magick::Image *image, SPItem *item) +{ // Scale bbox - Geom::Scale scale (0,0); - scale = Geom::Scale(image->columns() / (double) image->baseColumns(), - image->rows() / (double) image->baseRows()); + Geom::Scale scale(0, 0); + scale = Geom::Scale(image->columns() / (double)image->baseColumns(), image->rows() / (double)image->baseRows()); item->scale_rel(scale); // Translate proportionaly to the image/bbox ratio Geom::OptRect bbox(item->desktopGeometricBounds()); - //g_warning("bbox. W:%f, H:%f, X:%f, Y:%f", bbox->dimensions()[Geom::X], bbox->dimensions()[Geom::Y], bbox->min()[Geom::X], bbox->min()[Geom::Y]); + // g_warning("bbox. W:%f, H:%f, X:%f, Y:%f", bbox->dimensions()[Geom::X], bbox->dimensions()[Geom::Y], + // bbox->min()[Geom::X], bbox->min()[Geom::Y]); - Geom::Translate translate (0,0); - translate = Geom::Translate(((_left - _right) / 2.0) * (bbox->dimensions()[Geom::X] / (double) image->columns()), - ((_bottom - _top) / 2.0) * (bbox->dimensions()[Geom::Y] / (double) image->rows())); + Geom::Translate translate(0, 0); + translate = Geom::Translate(((_left - _right) / 2.0) * (bbox->dimensions()[Geom::X] / (double)image->columns()), + ((_bottom - _top) / 2.0) * (bbox->dimensions()[Geom::Y] / (double)image->rows())); item->move_rel(translate); } -void -Crop::refreshParameters(Inkscape::Extension::Effect *module) { +void Crop::refreshParameters(Inkscape::Extension::Effect *module) +{ _top = module->get_param_int("top"); _bottom = module->get_param_int("bottom"); _left = module->get_param_int("left"); @@ -60,8 +60,7 @@ Crop::refreshParameters(Inkscape::Extension::Effect *module) { #include "../clear-n_.h" -void -Crop::init() +void Crop::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/crop.h b/src/extension/internal/bitmap/crop.h index da538789ce758f3c44de84a672f19730fbae06e0..9fb44d9eb85d130232e964369a2dc974a22b95af 100644 --- a/src/extension/internal/bitmap/crop.h +++ b/src/extension/internal/bitmap/crop.h @@ -22,11 +22,12 @@ private: int _bottom; int _left; int _right; + public: void applyEffect(Magick::Image *image) override; void postEffect(Magick::Image *image, SPItem *item) override; void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init (); + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/cycleColormap.cpp b/src/extension/internal/bitmap/cycleColormap.cpp index c28e5e6dcb24074afc3484221fca6382e0ef7c37..75b29e9364bebb89fecf35821604e986796b6ab5 100644 --- a/src/extension/internal/bitmap/cycleColormap.cpp +++ b/src/extension/internal/bitmap/cycleColormap.cpp @@ -7,31 +7,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "cycleColormap.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -CycleColormap::applyEffect(Magick::Image *image) { - image->cycleColormap(_amount); + +void CycleColormap::applyEffect(Magick::Image *image) +{ + image->cycleColormap(_amount); } -void -CycleColormap::refreshParameters(Inkscape::Extension::Effect *module) { - _amount = module->get_param_int("amount"); +void CycleColormap::refreshParameters(Inkscape::Extension::Effect *module) +{ + _amount = module->get_param_int("amount"); } #include "../clear-n_.h" -void -CycleColormap::init() +void CycleColormap::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/cycleColormap.h b/src/extension/internal/bitmap/cycleColormap.h index 0d66b15a78953428be6fe5d3fd507dc9ebbeedc4..dc7ee5935d47151740fbe8d69b82e68ef41037a5 100644 --- a/src/extension/internal/bitmap/cycleColormap.h +++ b/src/extension/internal/bitmap/cycleColormap.h @@ -14,13 +14,15 @@ namespace Extension { namespace Internal { namespace Bitmap { -class CycleColormap : public ImageMagick { +class CycleColormap : public ImageMagick +{ private: - int _amount; + int _amount; + public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init (); + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/despeckle.cpp b/src/extension/internal/bitmap/despeckle.cpp index 46a1baf1701e3140cc1e3e2a777964f3b7752453..168a45a90698d1c678b2699cfc04fae50ad7e56f 100644 --- a/src/extension/internal/bitmap/despeckle.cpp +++ b/src/extension/internal/bitmap/despeckle.cpp @@ -7,30 +7,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "despeckle.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Despeckle::applyEffect(Magick::Image *image) { - image->despeckle(); -} -void -Despeckle::refreshParameters(Inkscape::Extension::Effect */*module*/) { +void Despeckle::applyEffect(Magick::Image *image) +{ + image->despeckle(); } +void Despeckle::refreshParameters(Inkscape::Extension::Effect * /*module*/) {} + #include "../clear-n_.h" -void -Despeckle::init() +void Despeckle::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/despeckle.h b/src/extension/internal/bitmap/despeckle.h index 0c731ee43b1445ff31ee5fe6b327c1c2929f9da2..ac56beeef796522c3e0144c5bc3c51bd239c5b1b 100644 --- a/src/extension/internal/bitmap/despeckle.h +++ b/src/extension/internal/bitmap/despeckle.h @@ -14,11 +14,12 @@ namespace Extension { namespace Internal { namespace Bitmap { -class Despeckle : public ImageMagick { +class Despeckle : public ImageMagick +{ public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init (); + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/edge.cpp b/src/extension/internal/bitmap/edge.cpp index 93b7394b21163b5766ac29bb95b7c7fa890ead09..768cb3d3bdc18f71d6f3352955bd2c5937722001 100644 --- a/src/extension/internal/bitmap/edge.cpp +++ b/src/extension/internal/bitmap/edge.cpp @@ -7,31 +7,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "edge.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Edge::applyEffect(Magick::Image *image) { - image->edge(_radius); + +void Edge::applyEffect(Magick::Image *image) +{ + image->edge(_radius); } -void -Edge::refreshParameters(Inkscape::Extension::Effect *module) { - _radius = module->get_param_int("radius"); +void Edge::refreshParameters(Inkscape::Extension::Effect *module) +{ + _radius = module->get_param_int("radius"); } #include "../clear-n_.h" -void -Edge::init() +void Edge::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/edge.h b/src/extension/internal/bitmap/edge.h index 2c5fe1427bc6a01e17821cf453e37ed465989616..c385caa2fa66c1714edb88f59855fd204addfcff 100644 --- a/src/extension/internal/bitmap/edge.h +++ b/src/extension/internal/bitmap/edge.h @@ -14,13 +14,15 @@ namespace Extension { namespace Internal { namespace Bitmap { -class Edge : public ImageMagick { +class Edge : public ImageMagick +{ private: - unsigned int _radius; + unsigned int _radius; + public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init (); + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/emboss.cpp b/src/extension/internal/bitmap/emboss.cpp index 86988c9dff3f1c6b12d6aa2835fcc9d1b1f0509c..14a46defde0dc6ab6527890bebd97bba34e86193 100644 --- a/src/extension/internal/bitmap/emboss.cpp +++ b/src/extension/internal/bitmap/emboss.cpp @@ -7,32 +7,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "emboss.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Emboss::applyEffect(Magick::Image *image) { - image->emboss(_radius, _sigma); + +void Emboss::applyEffect(Magick::Image *image) +{ + image->emboss(_radius, _sigma); } -void -Emboss::refreshParameters(Inkscape::Extension::Effect *module) { - _radius = module->get_param_float("radius"); - _sigma = module->get_param_float("sigma"); +void Emboss::refreshParameters(Inkscape::Extension::Effect *module) +{ + _radius = module->get_param_float("radius"); + _sigma = module->get_param_float("sigma"); } #include "../clear-n_.h" -void -Emboss::init() +void Emboss::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/emboss.h b/src/extension/internal/bitmap/emboss.h index 18b91bb1adbc08aef86528418b8a5f0564628832..ae2c502b90cd30c65ef31d8c6cf89a654ea64962 100644 --- a/src/extension/internal/bitmap/emboss.h +++ b/src/extension/internal/bitmap/emboss.h @@ -17,12 +17,13 @@ namespace Bitmap { class Emboss : public ImageMagick { private: - float _radius; - float _sigma; + float _radius; + float _sigma; + public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init (); + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/enhance.cpp b/src/extension/internal/bitmap/enhance.cpp index 391d1f14fb2cb206b46829e92227fc94d631bbbe..a03fa47d4d07e4f2cf4a10767558d237f590a540 100644 --- a/src/extension/internal/bitmap/enhance.cpp +++ b/src/extension/internal/bitmap/enhance.cpp @@ -7,29 +7,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "enhance.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Enhance::applyEffect(Magick::Image *image) { - image->enhance(); + +void Enhance::applyEffect(Magick::Image *image) +{ + image->enhance(); } -void -Enhance::refreshParameters(Inkscape::Extension::Effect */*module*/) { } +void Enhance::refreshParameters(Inkscape::Extension::Effect * /*module*/) {} #include "../clear-n_.h" -void -Enhance::init() +void Enhance::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/enhance.h b/src/extension/internal/bitmap/enhance.h index dd3d9ff6a2714a1b7eb2caaf1e13f5ddfaca7bd4..56aff58da57312c8d4553005320c097151ef95a5 100644 --- a/src/extension/internal/bitmap/enhance.h +++ b/src/extension/internal/bitmap/enhance.h @@ -18,8 +18,8 @@ class Enhance : public ImageMagick { public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init (); + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/equalize.cpp b/src/extension/internal/bitmap/equalize.cpp index df0575ea1034c5f84a79af1df03a060f1eceee76..3246ec71bcec1bbc3f170fcddca9da36f8ed54cf 100644 --- a/src/extension/internal/bitmap/equalize.cpp +++ b/src/extension/internal/bitmap/equalize.cpp @@ -7,29 +7,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "equalize.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Equalize::applyEffect(Magick::Image *image) { - image->equalize(); + +void Equalize::applyEffect(Magick::Image *image) +{ + image->equalize(); } -void -Equalize::refreshParameters(Inkscape::Extension::Effect */*module*/) { } +void Equalize::refreshParameters(Inkscape::Extension::Effect * /*module*/) {} #include "../clear-n_.h" -void -Equalize::init() +void Equalize::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/equalize.h b/src/extension/internal/bitmap/equalize.h index 8259ffb78ee13dc93a3abbdf9de4672c213695b2..ecf25a218b2205980bdae19f96cea0dea6711e75 100644 --- a/src/extension/internal/bitmap/equalize.h +++ b/src/extension/internal/bitmap/equalize.h @@ -18,8 +18,8 @@ class Equalize : public ImageMagick { public: void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init (); + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/gaussianBlur.cpp b/src/extension/internal/bitmap/gaussianBlur.cpp index 1b8396b314261a29d564fa2a899c2468d65e8e3a..ef164f4de550b2b33e417f8f65ce45c29908d76a 100644 --- a/src/extension/internal/bitmap/gaussianBlur.cpp +++ b/src/extension/internal/bitmap/gaussianBlur.cpp @@ -7,32 +7,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "gaussianBlur.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -GaussianBlur::applyEffect(Magick::Image* image) { - image->gaussianBlur(_width, _sigma); + +void GaussianBlur::applyEffect(Magick::Image *image) +{ + image->gaussianBlur(_width, _sigma); } -void -GaussianBlur::refreshParameters(Inkscape::Extension::Effect* module) { - _width = module->get_param_float("width"); - _sigma = module->get_param_float("sigma"); +void GaussianBlur::refreshParameters(Inkscape::Extension::Effect *module) +{ + _width = module->get_param_float("width"); + _sigma = module->get_param_float("sigma"); } #include "../clear-n_.h" -void -GaussianBlur::init() +void GaussianBlur::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/gaussianBlur.h b/src/extension/internal/bitmap/gaussianBlur.h index 3cd3fb8717339fdcd80a5cd18acdf0738ac23c5e..8e153bdbbc811324ec7bc406b88c5e1e8578231d 100644 --- a/src/extension/internal/bitmap/gaussianBlur.h +++ b/src/extension/internal/bitmap/gaussianBlur.h @@ -17,12 +17,13 @@ namespace Bitmap { class GaussianBlur : public ImageMagick { private: - float _width; - float _sigma; + float _width; + float _sigma; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/imagemagick.cpp b/src/extension/internal/bitmap/imagemagick.cpp index 915d3b08f22c3edb9167aea77de70ea6a350711d..ad368332af5cfc4bc8183b71f1c026031a8e0300 100644 --- a/src/extension/internal/bitmap/imagemagick.cpp +++ b/src/extension/internal/bitmap/imagemagick.cpp @@ -9,81 +9,80 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "imagemagick.h" -#include +#include +#include #include +#include #include - -#include +#include #include "desktop.h" - -#include "selection.h" - #include "extension/effect.h" #include "extension/system.h" - -#include "imagemagick.h" -#include +#include "selection.h" namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { -class ImageMagickDocCache: public Inkscape::Extension::Implementation::ImplementationDocumentCache { +class ImageMagickDocCache : public Inkscape::Extension::Implementation::ImplementationDocumentCache +{ friend class ImageMagick; + private: void readImage(char const *xlink, char const *id, Magick::Image *image); + protected: - Inkscape::XML::Node** _nodes; - - Magick::Image** _images; + Inkscape::XML::Node **_nodes; + + Magick::Image **_images; int _imageCount; - char** _caches; - unsigned* _cacheLengths; - const char** _originals; - SPItem** _imageItems; + char **_caches; + unsigned *_cacheLengths; + const char **_originals; + SPItem **_imageItems; + public: - ImageMagickDocCache(Inkscape::UI::View::View * view); - ~ImageMagickDocCache ( ) override; + ImageMagickDocCache(Inkscape::UI::View::View *view); + ~ImageMagickDocCache() override; }; -ImageMagickDocCache::ImageMagickDocCache(Inkscape::UI::View::View * view) : - Inkscape::Extension::Implementation::ImplementationDocumentCache(view), - _nodes(NULL), - _images(NULL), - _imageCount(0), - _caches(NULL), - _cacheLengths(NULL), - _originals(NULL), - _imageItems(NULL) +ImageMagickDocCache::ImageMagickDocCache(Inkscape::UI::View::View *view) + : Inkscape::Extension::Implementation::ImplementationDocumentCache(view) + , _nodes(NULL) + , _images(NULL) + , _imageCount(0) + , _caches(NULL) + , _cacheLengths(NULL) + , _originals(NULL) + , _imageItems(NULL) { - SPDesktop *desktop = (SPDesktop*)view; + SPDesktop *desktop = (SPDesktop *)view; auto selectedItemList = desktop->selection->items(); - int selectCount = (int) boost::distance(selectedItemList); - + int selectCount = (int)boost::distance(selectedItemList); + // Init the data-holders - _nodes = new Inkscape::XML::Node*[selectCount]; - _originals = new const char*[selectCount]; - _caches = new char*[selectCount]; + _nodes = new Inkscape::XML::Node *[selectCount]; + _originals = new const char *[selectCount]; + _caches = new char *[selectCount]; _cacheLengths = new unsigned int[selectCount]; - _images = new Magick::Image*[selectCount]; + _images = new Magick::Image *[selectCount]; _imageCount = 0; - _imageItems = new SPItem*[selectCount]; + _imageItems = new SPItem *[selectCount]; // Loop through selected items for (auto i = selectedItemList.begin(); i != selectedItemList.end(); ++i) { SPItem *item = *i; Inkscape::XML::Node *node = reinterpret_cast(item->getRepr()); - if (!strcmp(node->name(), "image") || !strcmp(node->name(), "svg:image")) - { - _nodes[_imageCount] = node; + if (!strcmp(node->name(), "image") || !strcmp(node->name(), "svg:image")) { + _nodes[_imageCount] = node; char const *xlink = node->attribute("xlink:href"); char const *id = node->attribute("id"); _originals[_imageCount] = xlink; - _caches[_imageCount] = (char*)""; + _caches[_imageCount] = (char *)""; _cacheLengths[_imageCount] = 0; _images[_imageCount] = new Magick::Image(); readImage(xlink, id, _images[_imageCount]); @@ -93,7 +92,8 @@ ImageMagickDocCache::ImageMagickDocCache(Inkscape::UI::View::View * view) : } } -ImageMagickDocCache::~ImageMagickDocCache ( ) { +ImageMagickDocCache::~ImageMagickDocCache() +{ if (_nodes) delete _nodes; if (_originals) @@ -109,14 +109,13 @@ ImageMagickDocCache::~ImageMagickDocCache ( ) { return; } -void -ImageMagickDocCache::readImage(const char *xlink, const char *id, Magick::Image *image) +void ImageMagickDocCache::readImage(const char *xlink, const char *id, Magick::Image *image) { - // Find if the xlink:href is base64 data, i.e. if the image is embedded + // Find if the xlink:href is base64 data, i.e. if the image is embedded gchar *search = g_strndup(xlink, 30); - if (strstr(search, "base64") != (char*)NULL) { + if (strstr(search, "base64") != (char *)NULL) { // 7 = strlen("base64") + strlen(",") - const char* pureBase64 = strstr(xlink, "base64") + 7; + const char *pureBase64 = strstr(xlink, "base64") + 7; Magick::Blob blob; blob.base64(pureBase64); try { @@ -126,7 +125,7 @@ ImageMagickDocCache::readImage(const char *xlink, const char *id, Magick::Image } } else { gchar *path; - if (strncmp (xlink,"file:", 5) == 0) { + if (strncmp(xlink, "file:", 5) == 0) { path = g_filename_from_uri(xlink, NULL, NULL); } else { path = g_strdup(xlink); @@ -141,35 +140,33 @@ ImageMagickDocCache::readImage(const char *xlink, const char *id, Magick::Image g_free(search); } -bool -ImageMagick::load(Inkscape::Extension::Extension */*module*/) +bool ImageMagick::load(Inkscape::Extension::Extension * /*module*/) { return true; } Inkscape::Extension::Implementation::ImplementationDocumentCache * -ImageMagick::newDocCache (Inkscape::Extension::Extension * /*ext*/, Inkscape::UI::View::View * view) { +ImageMagick::newDocCache(Inkscape::Extension::Extension * /*ext*/, Inkscape::UI::View::View *view) +{ return new ImageMagickDocCache(view); } -void -ImageMagick::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, Inkscape::Extension::Implementation::ImplementationDocumentCache * docCache) +void ImageMagick::effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, + Inkscape::Extension::Implementation::ImplementationDocumentCache *docCache) { refreshParameters(module); if (docCache == NULL) { // should never happen docCache = newDocCache(module, document); } - ImageMagickDocCache * dc = dynamic_cast(docCache); + ImageMagickDocCache *dc = dynamic_cast(docCache); if (dc == NULL) { // should really never happen printf("AHHHHHHHHH!!!!!"); exit(1); } - for (int i = 0; i < dc->_imageCount; i++) - { - try - { + for (int i = 0; i < dc->_imageCount; i++) { + try { Magick::Image effectedImage = *dc->_images[i]; // make a copy applyEffect(&effectedImage); @@ -178,7 +175,7 @@ ImageMagick::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::Vi // e.g. resize the image element, after the effecti is applied postEffect(&effectedImage, dc->_imageItems[i]); -// dc->_nodes[i]->setAttribute("xlink:href", dc->_caches[i]); + // dc->_nodes[i]->setAttribute("xlink:href", dc->_caches[i]); Magick::Blob *blob = new Magick::Blob(); effectedImage.write(blob); @@ -195,35 +192,34 @@ ImageMagick::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::Vi char *formatted_i = dc->_caches[i]; const char *src; - for (src = "data:image/"; *src; ) + for (src = "data:image/"; *src;) *formatted_i++ = *src++; - for (src = effectedImage.magick().c_str(); *src ; ) + for (src = effectedImage.magick().c_str(); *src;) *formatted_i++ = *src++; - for (src = ";base64, \n" ; *src; ) + for (src = ";base64, \n"; *src;) *formatted_i++ = *src++; int col = 0; while (*raw_i) { - *formatted_i++ = *raw_i++; - if (col++ > 76) { - *formatted_i++ = '\n'; - col = 0; - } - } + *formatted_i++ = *raw_i++; + if (col++ > 76) { + *formatted_i++ = '\n'; + col = 0; + } + } if (col) { - *formatted_i++ = '\n'; + *formatted_i++ = '\n'; } *formatted_i = '\0'; dc->_nodes[i]->setAttribute("xlink:href", dc->_caches[i]); dc->_nodes[i]->removeAttribute("sodipodi:absref"); delete blob; - } - catch (Magick::Exception &error_) { + } catch (Magick::Exception &error_) { printf("Caught exception: %s \n", error_.what()); } - //while(Gtk::Main::events_pending()) { + // while(Gtk::Main::events_pending()) { // Gtk::Main::iteration(); //} } @@ -235,13 +231,14 @@ ImageMagick::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::Vi Uses AutoGUI for creating the GUI. */ -Gtk::Widget * -ImageMagick::prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View * view, sigc::signal * changeSignal, Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) +Gtk::Widget *ImageMagick::prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *view, + sigc::signal *changeSignal, + Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) { - SPDocument * current_document = view->doc(); + SPDocument *current_document = view->doc(); - auto selected = ((SPDesktop *) view)->getSelection()->items(); - Inkscape::XML::Node * first_select = NULL; + auto selected = ((SPDesktop *)view)->getSelection()->items(); + Inkscape::XML::Node *first_select = NULL; if (!selected.empty()) { first_select = (selected.front())->getRepr(); } diff --git a/src/extension/internal/bitmap/imagemagick.h b/src/extension/internal/bitmap/imagemagick.h index 754e1959efab64f7da2cac68a2a7a1ce2714130f..6173908945c70be95f553b086a6fe3f5743e7043 100644 --- a/src/extension/internal/bitmap/imagemagick.h +++ b/src/extension/internal/bitmap/imagemagick.h @@ -27,18 +27,23 @@ class Extension; namespace Internal { namespace Bitmap { -class ImageMagick : public Inkscape::Extension::Implementation::Implementation { +class ImageMagick : public Inkscape::Extension::Implementation::Implementation +{ public: /* Functions to be implemented by subclasses */ - virtual void applyEffect(Magick::Image */*image*/) { }; - virtual void refreshParameters(Inkscape::Extension::Effect */*module*/) { }; - virtual void postEffect(Magick::Image */*image*/, SPItem */*item*/) { }; + virtual void applyEffect(Magick::Image * /*image*/){}; + virtual void refreshParameters(Inkscape::Extension::Effect * /*module*/){}; + virtual void postEffect(Magick::Image * /*image*/, SPItem * /*item*/){}; /* Functions implemented from ::Implementation */ bool load(Inkscape::Extension::Extension *module) override; - Inkscape::Extension::Implementation::ImplementationDocumentCache * newDocCache (Inkscape::Extension::Extension * ext, Inkscape::UI::View::View * doc) override; - void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, Inkscape::Extension::Implementation::ImplementationDocumentCache * docCache) override; - Gtk::Widget* prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View * view, sigc::signal * changeSignal, Inkscape::Extension::Implementation::ImplementationDocumentCache * docCache) override; + Inkscape::Extension::Implementation::ImplementationDocumentCache * + newDocCache(Inkscape::Extension::Extension *ext, Inkscape::UI::View::View *doc) override; + void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, + Inkscape::Extension::Implementation::ImplementationDocumentCache *docCache) override; + Gtk::Widget *prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *view, + sigc::signal *changeSignal, + Inkscape::Extension::Implementation::ImplementationDocumentCache *docCache) override; }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/implode.cpp b/src/extension/internal/bitmap/implode.cpp index 4395e2a0fba5049e3c82bbd5684fead60b78bd61..d1e8a31ecbfba9715c3f9a872c66344ad4b87d01 100644 --- a/src/extension/internal/bitmap/implode.cpp +++ b/src/extension/internal/bitmap/implode.cpp @@ -7,31 +7,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "implode.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Implode::applyEffect(Magick::Image* image) { - image->implode(_factor); + +void Implode::applyEffect(Magick::Image *image) +{ + image->implode(_factor); } -void -Implode::refreshParameters(Inkscape::Extension::Effect* module) { - _factor = module->get_param_float("factor"); +void Implode::refreshParameters(Inkscape::Extension::Effect *module) +{ + _factor = module->get_param_float("factor"); } #include "../clear-n_.h" -void -Implode::init() +void Implode::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/implode.h b/src/extension/internal/bitmap/implode.h index d9c5adb1596c20ac3bd70d37913a0319eb097780..4ab030c862f7b1a932b8d0df785835cf3daf1a2c 100644 --- a/src/extension/internal/bitmap/implode.h +++ b/src/extension/internal/bitmap/implode.h @@ -17,11 +17,12 @@ namespace Bitmap { class Implode : public ImageMagick { private: - float _factor; + float _factor; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/level.cpp b/src/extension/internal/bitmap/level.cpp index cf317443097d593234bfd14b0d06e5ed804f54c0..23e78a80c060bc13fbe95190f11d74981c3b623c 100644 --- a/src/extension/internal/bitmap/level.cpp +++ b/src/extension/internal/bitmap/level.cpp @@ -7,35 +7,35 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "level.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Level::applyEffect(Magick::Image* image) { - Magick::Quantum black_point = Magick::Color::scaleDoubleToQuantum(_black_point / 100.0); - Magick::Quantum white_point = Magick::Color::scaleDoubleToQuantum(_white_point / 100.0); - image->level(black_point, white_point, _mid_point); + +void Level::applyEffect(Magick::Image *image) +{ + Magick::Quantum black_point = Magick::Color::scaleDoubleToQuantum(_black_point / 100.0); + Magick::Quantum white_point = Magick::Color::scaleDoubleToQuantum(_white_point / 100.0); + image->level(black_point, white_point, _mid_point); } -void -Level::refreshParameters(Inkscape::Extension::Effect* module) { - _black_point = module->get_param_float("blackPoint"); - _white_point = module->get_param_float("whitePoint"); - _mid_point = module->get_param_float("midPoint"); +void Level::refreshParameters(Inkscape::Extension::Effect *module) +{ + _black_point = module->get_param_float("blackPoint"); + _white_point = module->get_param_float("whitePoint"); + _mid_point = module->get_param_float("midPoint"); } #include "../clear-n_.h" -void -Level::init() +void Level::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/level.h b/src/extension/internal/bitmap/level.h index d3727453975353046392ef45956b9d0563378133..3c68106d4dd68b4609357136f521de8e0716e9b9 100644 --- a/src/extension/internal/bitmap/level.h +++ b/src/extension/internal/bitmap/level.h @@ -17,13 +17,14 @@ namespace Bitmap { class Level : public ImageMagick { private: - float _black_point; - float _white_point; - float _mid_point; + float _black_point; + float _white_point; + float _mid_point; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/levelChannel.cpp b/src/extension/internal/bitmap/levelChannel.cpp index 7280fb118a8949a99c828b60c9ef7b49f99249fd..aeb7e573608fe9abfcc56b047134bdbdcb2a7f57 100644 --- a/src/extension/internal/bitmap/levelChannel.cpp +++ b/src/extension/internal/bitmap/levelChannel.cpp @@ -7,46 +7,55 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "levelChannel.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -LevelChannel::applyEffect(Magick::Image* image) { - Magick::ChannelType channel = Magick::UndefinedChannel; - if (!strcmp(_channelName, "Red Channel")) channel = Magick::RedChannel; - else if (!strcmp(_channelName, "Green Channel")) channel = Magick::GreenChannel; - else if (!strcmp(_channelName, "Blue Channel")) channel = Magick::BlueChannel; - else if (!strcmp(_channelName, "Cyan Channel")) channel = Magick::CyanChannel; - else if (!strcmp(_channelName, "Magenta Channel")) channel = Magick::MagentaChannel; - else if (!strcmp(_channelName, "Yellow Channel")) channel = Magick::YellowChannel; - else if (!strcmp(_channelName, "Black Channel")) channel = Magick::BlackChannel; - else if (!strcmp(_channelName, "Opacity Channel")) channel = Magick::OpacityChannel; - else if (!strcmp(_channelName, "Matte Channel")) channel = Magick::MatteChannel; - Magick::Quantum black_point = Magick::Color::scaleDoubleToQuantum(_black_point / 100.0); - Magick::Quantum white_point = Magick::Color::scaleDoubleToQuantum(_white_point / 100.0); - image->levelChannel(channel, black_point, white_point, _mid_point); + +void LevelChannel::applyEffect(Magick::Image *image) +{ + Magick::ChannelType channel = Magick::UndefinedChannel; + if (!strcmp(_channelName, "Red Channel")) + channel = Magick::RedChannel; + else if (!strcmp(_channelName, "Green Channel")) + channel = Magick::GreenChannel; + else if (!strcmp(_channelName, "Blue Channel")) + channel = Magick::BlueChannel; + else if (!strcmp(_channelName, "Cyan Channel")) + channel = Magick::CyanChannel; + else if (!strcmp(_channelName, "Magenta Channel")) + channel = Magick::MagentaChannel; + else if (!strcmp(_channelName, "Yellow Channel")) + channel = Magick::YellowChannel; + else if (!strcmp(_channelName, "Black Channel")) + channel = Magick::BlackChannel; + else if (!strcmp(_channelName, "Opacity Channel")) + channel = Magick::OpacityChannel; + else if (!strcmp(_channelName, "Matte Channel")) + channel = Magick::MatteChannel; + Magick::Quantum black_point = Magick::Color::scaleDoubleToQuantum(_black_point / 100.0); + Magick::Quantum white_point = Magick::Color::scaleDoubleToQuantum(_white_point / 100.0); + image->levelChannel(channel, black_point, white_point, _mid_point); } -void -LevelChannel::refreshParameters(Inkscape::Extension::Effect* module) { - _channelName = module->get_param_optiongroup("channel"); - _black_point = module->get_param_float("blackPoint"); - _white_point = module->get_param_float("whitePoint"); - _mid_point = module->get_param_float("midPoint"); +void LevelChannel::refreshParameters(Inkscape::Extension::Effect *module) +{ + _channelName = module->get_param_optiongroup("channel"); + _black_point = module->get_param_float("blackPoint"); + _white_point = module->get_param_float("whitePoint"); + _mid_point = module->get_param_float("midPoint"); } #include "../clear-n_.h" -void -LevelChannel::init() +void LevelChannel::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/levelChannel.h b/src/extension/internal/bitmap/levelChannel.h index a619939f9053dbf1ad9b2570abf92a2f44b89849..2bdd1ce213590b18cb2283f398dd0e74ca09d932 100644 --- a/src/extension/internal/bitmap/levelChannel.h +++ b/src/extension/internal/bitmap/levelChannel.h @@ -17,14 +17,15 @@ namespace Bitmap { class LevelChannel : public ImageMagick { private: - float _black_point; - float _white_point; - float _mid_point; - const gchar * _channelName; + float _black_point; + float _white_point; + float _mid_point; + const gchar *_channelName; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/medianFilter.cpp b/src/extension/internal/bitmap/medianFilter.cpp index 80385ac08b984da0922dabed1d50aa74756ef7fc..c543c399a9d66415590f1285e765871524f0f2e6 100644 --- a/src/extension/internal/bitmap/medianFilter.cpp +++ b/src/extension/internal/bitmap/medianFilter.cpp @@ -7,31 +7,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "medianFilter.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -MedianFilter::applyEffect(Magick::Image* image) { - image->medianFilter(_radius); + +void MedianFilter::applyEffect(Magick::Image *image) +{ + image->medianFilter(_radius); } -void -MedianFilter::refreshParameters(Inkscape::Extension::Effect* module) { - _radius = module->get_param_float("radius"); +void MedianFilter::refreshParameters(Inkscape::Extension::Effect *module) +{ + _radius = module->get_param_float("radius"); } #include "../clear-n_.h" -void -MedianFilter::init() +void MedianFilter::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/medianFilter.h b/src/extension/internal/bitmap/medianFilter.h index 60ac31ae16747dd5532959301a7a674629cdb6d2..43118b1ac7c8f4597c6468b4f882e15dbc1aea66 100644 --- a/src/extension/internal/bitmap/medianFilter.h +++ b/src/extension/internal/bitmap/medianFilter.h @@ -17,11 +17,12 @@ namespace Bitmap { class MedianFilter : public ImageMagick { private: - float _radius; + float _radius; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/modulate.cpp b/src/extension/internal/bitmap/modulate.cpp index b1349b23fc5daadad52e0b9d98c482f12c516365..6a4847894a0fb1f904599d92045a68795f3be6b1 100644 --- a/src/extension/internal/bitmap/modulate.cpp +++ b/src/extension/internal/bitmap/modulate.cpp @@ -7,34 +7,34 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "modulate.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Modulate::applyEffect(Magick::Image* image) { - float hue = (_hue * 200 / 360.0) + 100; - image->modulate(_brightness, _saturation, hue); + +void Modulate::applyEffect(Magick::Image *image) +{ + float hue = (_hue * 200 / 360.0) + 100; + image->modulate(_brightness, _saturation, hue); } -void -Modulate::refreshParameters(Inkscape::Extension::Effect* module) { - _brightness = module->get_param_float("brightness"); - _saturation = module->get_param_float("saturation"); - _hue = module->get_param_float("hue"); +void Modulate::refreshParameters(Inkscape::Extension::Effect *module) +{ + _brightness = module->get_param_float("brightness"); + _saturation = module->get_param_float("saturation"); + _hue = module->get_param_float("hue"); } #include "../clear-n_.h" -void -Modulate::init() +void Modulate::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/modulate.h b/src/extension/internal/bitmap/modulate.h index f0aaf1b78a61b2dda4b3162f9b0603511c9497c8..53fbe0450d444b2c947d498cc4e651993019ca70 100644 --- a/src/extension/internal/bitmap/modulate.h +++ b/src/extension/internal/bitmap/modulate.h @@ -17,13 +17,14 @@ namespace Bitmap { class Modulate : public ImageMagick { private: - float _brightness; - float _saturation; - float _hue; + float _brightness; + float _saturation; + float _hue; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/negate.cpp b/src/extension/internal/bitmap/negate.cpp index 64705564a5ba0a65dd3cac62491d29cd6652fb9e..5a5a1b0475991c411983cd45b8b09cd25b5ac97c 100644 --- a/src/extension/internal/bitmap/negate.cpp +++ b/src/extension/internal/bitmap/negate.cpp @@ -7,30 +7,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "negate.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Negate::applyEffect(Magick::Image* image) { - image->negate(); -} -void -Negate::refreshParameters(Inkscape::Extension::Effect* /*module*/) { +void Negate::applyEffect(Magick::Image *image) +{ + image->negate(); } +void Negate::refreshParameters(Inkscape::Extension::Effect * /*module*/) {} + #include "../clear-n_.h" -void -Negate::init() +void Negate::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/negate.h b/src/extension/internal/bitmap/negate.h index 4cde402bcbbd7a43fd470148701574294de08f83..fe0b6555beabe7edfcd9838377d96e4c77bc8988 100644 --- a/src/extension/internal/bitmap/negate.h +++ b/src/extension/internal/bitmap/negate.h @@ -17,9 +17,9 @@ namespace Bitmap { class Negate : public ImageMagick { public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/normalize.cpp b/src/extension/internal/bitmap/normalize.cpp index 96cfe13c0d1e14f84e153ab1da86cc8ade2988d2..64c8fb1e75ac9709946997d3896864b42fc0af49 100644 --- a/src/extension/internal/bitmap/normalize.cpp +++ b/src/extension/internal/bitmap/normalize.cpp @@ -7,30 +7,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "normalize.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Normalize::applyEffect(Magick::Image* image) { - image->normalize(); -} -void -Normalize::refreshParameters(Inkscape::Extension::Effect* /*module*/) { +void Normalize::applyEffect(Magick::Image *image) +{ + image->normalize(); } +void Normalize::refreshParameters(Inkscape::Extension::Effect * /*module*/) {} + #include "../clear-n_.h" -void -Normalize::init() +void Normalize::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/normalize.h b/src/extension/internal/bitmap/normalize.h index 2d4a9c2f5bfad7a57c28ba212cafe679466450da..e335d75f6d1a7f5ce7cca8ced94eb3170644063e 100644 --- a/src/extension/internal/bitmap/normalize.h +++ b/src/extension/internal/bitmap/normalize.h @@ -17,9 +17,9 @@ namespace Bitmap { class Normalize : public ImageMagick { public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/oilPaint.cpp b/src/extension/internal/bitmap/oilPaint.cpp index ee17964925514a21f5b4175db2e9402d19c44853..2cd4b7296d2c4348d2aa52512a4edfad3c30003c 100644 --- a/src/extension/internal/bitmap/oilPaint.cpp +++ b/src/extension/internal/bitmap/oilPaint.cpp @@ -7,31 +7,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "oilPaint.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -OilPaint::applyEffect(Magick::Image* image) { - image->oilPaint(_radius); + +void OilPaint::applyEffect(Magick::Image *image) +{ + image->oilPaint(_radius); } -void -OilPaint::refreshParameters(Inkscape::Extension::Effect* module) { - _radius = module->get_param_int("radius"); +void OilPaint::refreshParameters(Inkscape::Extension::Effect *module) +{ + _radius = module->get_param_int("radius"); } #include "../clear-n_.h" -void -OilPaint::init() +void OilPaint::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/oilPaint.h b/src/extension/internal/bitmap/oilPaint.h index d3957bd6ff5a08aec7f3fecca78616dccc9bb40d..8c7005c707a747f50d57923e07888b66d1c3aa7f 100644 --- a/src/extension/internal/bitmap/oilPaint.h +++ b/src/extension/internal/bitmap/oilPaint.h @@ -17,11 +17,12 @@ namespace Bitmap { class OilPaint : public ImageMagick { private: - float _radius; + float _radius; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/opacity.cpp b/src/extension/internal/bitmap/opacity.cpp index 024dcb945c9fa1448d467d0c59f4082b68b1d82e..d0db275bd96e6f7bd39b331a38502ce7c6f80c73 100644 --- a/src/extension/internal/bitmap/opacity.cpp +++ b/src/extension/internal/bitmap/opacity.cpp @@ -7,32 +7,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "opacity.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Opacity::applyEffect(Magick::Image* image) { - Magick::Quantum opacity = Magick::Color::scaleDoubleToQuantum((100 - _opacity) / 100.0); - image->opacity(opacity); + +void Opacity::applyEffect(Magick::Image *image) +{ + Magick::Quantum opacity = Magick::Color::scaleDoubleToQuantum((100 - _opacity) / 100.0); + image->opacity(opacity); } -void -Opacity::refreshParameters(Inkscape::Extension::Effect* module) { - _opacity = module->get_param_float("opacity"); +void Opacity::refreshParameters(Inkscape::Extension::Effect *module) +{ + _opacity = module->get_param_float("opacity"); } #include "../clear-n_.h" -void -Opacity::init() +void Opacity::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/opacity.h b/src/extension/internal/bitmap/opacity.h index df6e6acdec91bd063c951812be5a05d2a17ec2ae..b6872f8108511319435198c1ce9d70c873f7315d 100644 --- a/src/extension/internal/bitmap/opacity.h +++ b/src/extension/internal/bitmap/opacity.h @@ -17,11 +17,12 @@ namespace Bitmap { class Opacity : public ImageMagick { private: - float _opacity; + float _opacity; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/raise.cpp b/src/extension/internal/bitmap/raise.cpp index e209f2debdf43f540384bfcea775acff2b7d727f..2e59b5fe5eb2be372b23bcb074dde27aed52bb09 100644 --- a/src/extension/internal/bitmap/raise.cpp +++ b/src/extension/internal/bitmap/raise.cpp @@ -7,34 +7,34 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "raise.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Raise::applyEffect(Magick::Image* image) { - Magick::Geometry geometry(_width, _height, 0, 0); - image->raise(geometry, _raisedFlag); + +void Raise::applyEffect(Magick::Image *image) +{ + Magick::Geometry geometry(_width, _height, 0, 0); + image->raise(geometry, _raisedFlag); } -void -Raise::refreshParameters(Inkscape::Extension::Effect* module) { - _width = module->get_param_int("width"); - _height = module->get_param_int("height"); - _raisedFlag = module->get_param_bool("raisedFlag"); +void Raise::refreshParameters(Inkscape::Extension::Effect *module) +{ + _width = module->get_param_int("width"); + _height = module->get_param_int("height"); + _raisedFlag = module->get_param_bool("raisedFlag"); } #include "../clear-n_.h" -void -Raise::init() +void Raise::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/raise.h b/src/extension/internal/bitmap/raise.h index 90023fb807ad4cdf3ae0cb8d3fe2fffa77b77e7b..705c488887ab2ffdcb9fa4fc83f0c2b21d427e99 100644 --- a/src/extension/internal/bitmap/raise.h +++ b/src/extension/internal/bitmap/raise.h @@ -17,13 +17,14 @@ namespace Bitmap { class Raise : public ImageMagick { private: - int _width; - int _height; - bool _raisedFlag; + int _width; + int _height; + bool _raisedFlag; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/reduceNoise.cpp b/src/extension/internal/bitmap/reduceNoise.cpp index e1e5e83bc9483d49fbe8f7ff7a2e023b63dd5f4f..71acc2a3138d4edddcda82a251e5ef00bf299c92 100644 --- a/src/extension/internal/bitmap/reduceNoise.cpp +++ b/src/extension/internal/bitmap/reduceNoise.cpp @@ -7,34 +7,34 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "reduceNoise.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -ReduceNoise::applyEffect(Magick::Image* image) { - if (_order > -1) - image->reduceNoise(_order); - else - image->reduceNoise(); + +void ReduceNoise::applyEffect(Magick::Image *image) +{ + if (_order > -1) + image->reduceNoise(_order); + else + image->reduceNoise(); } -void -ReduceNoise::refreshParameters(Inkscape::Extension::Effect* module) { - _order = module->get_param_int("order"); +void ReduceNoise::refreshParameters(Inkscape::Extension::Effect *module) +{ + _order = module->get_param_int("order"); } #include "../clear-n_.h" -void -ReduceNoise::init() +void ReduceNoise::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/reduceNoise.h b/src/extension/internal/bitmap/reduceNoise.h index 3c9d2d6c27e13e5e9c9f0f4953aeed4ef5944c5e..26c4d8fc57a0c395120b45d982adc3396c92f31e 100644 --- a/src/extension/internal/bitmap/reduceNoise.h +++ b/src/extension/internal/bitmap/reduceNoise.h @@ -17,11 +17,12 @@ namespace Bitmap { class ReduceNoise : public ImageMagick { private: - int _order; + int _order; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/sample.cpp b/src/extension/internal/bitmap/sample.cpp index 47b014723b16fdb04f4b098ac481466a409342d2..77dc96d4aa0baad6cbd1d9e7cb68e4bff4d6ea9d 100644 --- a/src/extension/internal/bitmap/sample.cpp +++ b/src/extension/internal/bitmap/sample.cpp @@ -7,33 +7,33 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "sample.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Sample::applyEffect(Magick::Image* image) { - Magick::Geometry geometry(_width, _height, 0, 0); - image->sample(geometry); + +void Sample::applyEffect(Magick::Image *image) +{ + Magick::Geometry geometry(_width, _height, 0, 0); + image->sample(geometry); } -void -Sample::refreshParameters(Inkscape::Extension::Effect* module) { - _width = module->get_param_int("width"); - _height = module->get_param_int("height"); +void Sample::refreshParameters(Inkscape::Extension::Effect *module) +{ + _width = module->get_param_int("width"); + _height = module->get_param_int("height"); } #include "../clear-n_.h" -void -Sample::init() +void Sample::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/sample.h b/src/extension/internal/bitmap/sample.h index c93ab0ac5fe388ef7776711671ed1a48cead02c6..bcbacf9dd4d16797c27fbb0c2585a1b76ad75b3d 100644 --- a/src/extension/internal/bitmap/sample.h +++ b/src/extension/internal/bitmap/sample.h @@ -17,12 +17,13 @@ namespace Bitmap { class Sample : public ImageMagick { private: - int _width; - int _height; + int _width; + int _height; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/shade.cpp b/src/extension/internal/bitmap/shade.cpp index 4a4f907dfe9e2c0687a5dba6be387df8cfb74fff..7efe49f5eda1eebd057429ee2281369aa34ac8ba 100644 --- a/src/extension/internal/bitmap/shade.cpp +++ b/src/extension/internal/bitmap/shade.cpp @@ -7,34 +7,34 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "shade.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Shade::applyEffect(Magick::Image* image) { - image->shade(_azimuth, _elevation, !_colorShading); - // I don't know why, but I have to invert colorShading here + +void Shade::applyEffect(Magick::Image *image) +{ + image->shade(_azimuth, _elevation, !_colorShading); + // I don't know why, but I have to invert colorShading here } -void -Shade::refreshParameters(Inkscape::Extension::Effect* module) { - _azimuth = module->get_param_float("azimuth"); - _elevation = module->get_param_float("elevation"); - _colorShading = module->get_param_bool("colorShading"); +void Shade::refreshParameters(Inkscape::Extension::Effect *module) +{ + _azimuth = module->get_param_float("azimuth"); + _elevation = module->get_param_float("elevation"); + _colorShading = module->get_param_bool("colorShading"); } #include "../clear-n_.h" -void -Shade::init() +void Shade::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/shade.h b/src/extension/internal/bitmap/shade.h index 71ed3db1e26dc2b52d1766e172070d6ae34bcb65..070ab4e8072159913d8e29936b50954fd55bfc94 100644 --- a/src/extension/internal/bitmap/shade.h +++ b/src/extension/internal/bitmap/shade.h @@ -17,13 +17,14 @@ namespace Bitmap { class Shade : public ImageMagick { private: - float _azimuth; - float _elevation; - bool _colorShading; + float _azimuth; + float _elevation; + bool _colorShading; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/sharpen.cpp b/src/extension/internal/bitmap/sharpen.cpp index 40e159ccce49fb7478ca930c4a642aacfa2562dd..54069c7026115c4d8e1c26cf87d51c82ae4ddf8a 100644 --- a/src/extension/internal/bitmap/sharpen.cpp +++ b/src/extension/internal/bitmap/sharpen.cpp @@ -7,32 +7,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "sharpen.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Sharpen::applyEffect(Magick::Image* image) { - image->sharpen(_radius, _sigma); + +void Sharpen::applyEffect(Magick::Image *image) +{ + image->sharpen(_radius, _sigma); } -void -Sharpen::refreshParameters(Inkscape::Extension::Effect* module) { - _radius = module->get_param_float("radius"); - _sigma = module->get_param_float("sigma"); +void Sharpen::refreshParameters(Inkscape::Extension::Effect *module) +{ + _radius = module->get_param_float("radius"); + _sigma = module->get_param_float("sigma"); } #include "../clear-n_.h" -void -Sharpen::init() +void Sharpen::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/sharpen.h b/src/extension/internal/bitmap/sharpen.h index 35067ed5e2633d145560fc85791e1db9e595e9c7..94640dc3a9e5920cc70ed6744cca7c85b44a111b 100644 --- a/src/extension/internal/bitmap/sharpen.h +++ b/src/extension/internal/bitmap/sharpen.h @@ -17,12 +17,13 @@ namespace Bitmap { class Sharpen : public ImageMagick { private: - float _radius; - float _sigma; + float _radius; + float _sigma; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/solarize.cpp b/src/extension/internal/bitmap/solarize.cpp index 41952d80f15d2a05df04a3374c4bebecdfcb0cc5..0ceb7030fc35ab6afc08e1b6ec476edfe14f531f 100644 --- a/src/extension/internal/bitmap/solarize.cpp +++ b/src/extension/internal/bitmap/solarize.cpp @@ -7,33 +7,33 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "solarize.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Solarize::applyEffect(Magick::Image* image) { + +void Solarize::applyEffect(Magick::Image *image) +{ // Image Magick Quantum depth = 16 // 655.35 = (2^16 - 1) / 100 - image->solarize(_factor * 655.35); + image->solarize(_factor * 655.35); } -void -Solarize::refreshParameters(Inkscape::Extension::Effect* module) { - _factor = module->get_param_float("factor"); +void Solarize::refreshParameters(Inkscape::Extension::Effect *module) +{ + _factor = module->get_param_float("factor"); } #include "../clear-n_.h" -void -Solarize::init() +void Solarize::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/solarize.h b/src/extension/internal/bitmap/solarize.h index 2e4a51b285ead58b7cc0ca6eaf9f61c40d2fde24..56fd08a8e5cda65a9fea50b9e111c96ecb05d3c2 100644 --- a/src/extension/internal/bitmap/solarize.h +++ b/src/extension/internal/bitmap/solarize.h @@ -17,11 +17,12 @@ namespace Bitmap { class Solarize : public ImageMagick { private: - float _factor; + float _factor; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/spread.cpp b/src/extension/internal/bitmap/spread.cpp index cb7aa5dfce44a2a5a76edeeb1fcbc8f21b81af96..4b2e15e1226641dd8b02ec212c46285952da8fa3 100644 --- a/src/extension/internal/bitmap/spread.cpp +++ b/src/extension/internal/bitmap/spread.cpp @@ -7,31 +7,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "spread.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Spread::applyEffect(Magick::Image* image) { - image->spread(_amount); + +void Spread::applyEffect(Magick::Image *image) +{ + image->spread(_amount); } -void -Spread::refreshParameters(Inkscape::Extension::Effect* module) { - _amount = module->get_param_int("amount"); +void Spread::refreshParameters(Inkscape::Extension::Effect *module) +{ + _amount = module->get_param_int("amount"); } #include "../clear-n_.h" -void -Spread::init() +void Spread::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/spread.h b/src/extension/internal/bitmap/spread.h index ad775440b0c96f09a5b4f4dc2984acc8973c1ef8..ea3323d6741dda9de0e5b75d0e31b09e6d1e4560 100644 --- a/src/extension/internal/bitmap/spread.h +++ b/src/extension/internal/bitmap/spread.h @@ -17,11 +17,12 @@ namespace Bitmap { class Spread : public ImageMagick { private: - int _amount; + int _amount; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/swirl.cpp b/src/extension/internal/bitmap/swirl.cpp index 50dc75d279d16f3b11a828d2278be31e28b810ea..4e950242233139adccd68bf27c7e50fc142f6ab6 100644 --- a/src/extension/internal/bitmap/swirl.cpp +++ b/src/extension/internal/bitmap/swirl.cpp @@ -7,31 +7,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "swirl.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Swirl::applyEffect(Magick::Image* image) { - image->swirl(_degrees); + +void Swirl::applyEffect(Magick::Image *image) +{ + image->swirl(_degrees); } -void -Swirl::refreshParameters(Inkscape::Extension::Effect* module) { - _degrees = module->get_param_int("degrees"); +void Swirl::refreshParameters(Inkscape::Extension::Effect *module) +{ + _degrees = module->get_param_int("degrees"); } #include "../clear-n_.h" -void -Swirl::init() +void Swirl::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/swirl.h b/src/extension/internal/bitmap/swirl.h index b9ca3484ec3d23f55445ba1a0c4c7eee5a241d8a..0d5715d0625b3b9f3d00363da8fdff79a12b3cd6 100644 --- a/src/extension/internal/bitmap/swirl.h +++ b/src/extension/internal/bitmap/swirl.h @@ -17,11 +17,12 @@ namespace Bitmap { class Swirl : public ImageMagick { private: - float _degrees; + float _degrees; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/threshold.cpp b/src/extension/internal/bitmap/threshold.cpp index 235cf48379481a61a4537dff6fbafa90df988d86..6f4e10b49d3154122a3c34b3b135967bc57e8086 100644 --- a/src/extension/internal/bitmap/threshold.cpp +++ b/src/extension/internal/bitmap/threshold.cpp @@ -7,31 +7,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "threshold.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Threshold::applyEffect(Magick::Image* image) { - image->threshold(_threshold); + +void Threshold::applyEffect(Magick::Image *image) +{ + image->threshold(_threshold); } -void -Threshold::refreshParameters(Inkscape::Extension::Effect* module) { - _threshold = module->get_param_float("threshold"); +void Threshold::refreshParameters(Inkscape::Extension::Effect *module) +{ + _threshold = module->get_param_float("threshold"); } #include "../clear-n_.h" -void -Threshold::init() +void Threshold::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/threshold.h b/src/extension/internal/bitmap/threshold.h index 93e15bcb6a2e69a6f49652f9b25c7a4446b23a93..dc95e323f0a0903bd31725d9ecd068c1fcee0a12 100644 --- a/src/extension/internal/bitmap/threshold.h +++ b/src/extension/internal/bitmap/threshold.h @@ -17,11 +17,12 @@ namespace Bitmap { class Threshold : public ImageMagick { private: - double _threshold; + double _threshold; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/unsharpmask.cpp b/src/extension/internal/bitmap/unsharpmask.cpp index cd8d64dc2e752dca0e8aa1597b04062aef202fbb..5400a7e04073f6b74cc998121b826f1980b4b6d5 100644 --- a/src/extension/internal/bitmap/unsharpmask.cpp +++ b/src/extension/internal/bitmap/unsharpmask.cpp @@ -7,35 +7,35 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "unsharpmask.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Unsharpmask::applyEffect(Magick::Image* image) { - float amount = _amount / 100.0; - image->unsharpmask(_radius, _sigma, amount, _threshold); + +void Unsharpmask::applyEffect(Magick::Image *image) +{ + float amount = _amount / 100.0; + image->unsharpmask(_radius, _sigma, amount, _threshold); } -void -Unsharpmask::refreshParameters(Inkscape::Extension::Effect* module) { - _radius = module->get_param_float("radius"); - _sigma = module->get_param_float("sigma"); - _amount = module->get_param_float("amount"); - _threshold = module->get_param_float("threshold"); +void Unsharpmask::refreshParameters(Inkscape::Extension::Effect *module) +{ + _radius = module->get_param_float("radius"); + _sigma = module->get_param_float("sigma"); + _amount = module->get_param_float("amount"); + _threshold = module->get_param_float("threshold"); } #include "../clear-n_.h" -void -Unsharpmask::init() +void Unsharpmask::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/unsharpmask.h b/src/extension/internal/bitmap/unsharpmask.h index 34fbfebc6afcb1d35363435ea652b6f137bb0ddf..83313ce43e7025cf9d03ff862a6abffc5076a34d 100644 --- a/src/extension/internal/bitmap/unsharpmask.h +++ b/src/extension/internal/bitmap/unsharpmask.h @@ -17,14 +17,15 @@ namespace Bitmap { class Unsharpmask : public ImageMagick { private: - float _radius; - float _sigma; - float _amount; - float _threshold; + float _radius; + float _sigma; + float _amount; + float _threshold; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bitmap/wave.cpp b/src/extension/internal/bitmap/wave.cpp index 80ae7681ce7553f4367454e56296ce6d5324771d..634feb1088ee254be323356d488a8e9033ceefde 100644 --- a/src/extension/internal/bitmap/wave.cpp +++ b/src/extension/internal/bitmap/wave.cpp @@ -7,32 +7,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/effect.h" -#include "extension/system.h" - #include "wave.h" + #include +#include "extension/effect.h" +#include "extension/system.h" + namespace Inkscape { namespace Extension { namespace Internal { namespace Bitmap { - -void -Wave::applyEffect(Magick::Image* image) { - image->wave(_amplitude, _wavelength); + +void Wave::applyEffect(Magick::Image *image) +{ + image->wave(_amplitude, _wavelength); } -void -Wave::refreshParameters(Inkscape::Extension::Effect* module) { - _amplitude = module->get_param_float("amplitude"); - _wavelength = module->get_param_float("wavelength"); +void Wave::refreshParameters(Inkscape::Extension::Effect *module) +{ + _amplitude = module->get_param_float("amplitude"); + _wavelength = module->get_param_float("wavelength"); } #include "../clear-n_.h" -void -Wave::init() +void Wave::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bitmap/wave.h b/src/extension/internal/bitmap/wave.h index f524c175f3439f383db34a1ea152c8d6c3a404fb..4e67e2bc460144feed4a64bd9ffb606ee209ee6a 100644 --- a/src/extension/internal/bitmap/wave.h +++ b/src/extension/internal/bitmap/wave.h @@ -17,12 +17,13 @@ namespace Bitmap { class Wave : public ImageMagick { private: - float _amplitude; - float _wavelength; + float _amplitude; + float _wavelength; + public: - void applyEffect(Magick::Image *image) override; - void refreshParameters(Inkscape::Extension::Effect *module) override; - static void init(); + void applyEffect(Magick::Image *image) override; + void refreshParameters(Inkscape::Extension::Effect *module) override; + static void init(); }; }; /* namespace Bitmap */ diff --git a/src/extension/internal/bluredge.cpp b/src/extension/internal/bluredge.cpp index 9e5aa4af9343ed3a0815aa09b0a4a18e9595fdd4..8856a37bbe05b01956f209d7912e16fdcb7999c8 100644 --- a/src/extension/internal/bluredge.cpp +++ b/src/extension/internal/bluredge.cpp @@ -13,34 +13,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "bluredge.h" + #include + #include "desktop.h" #include "document.h" -#include "selection.h" -#include "helper/action.h" -#include "helper/action-context.h" -#include "preferences.h" -#include "path-chemistry.h" -#include "object/sp-item.h" - #include "extension/effect.h" #include "extension/system.h" - - -#include "bluredge.h" +#include "helper/action-context.h" +#include "helper/action.h" +#include "object/sp-item.h" +#include "path-chemistry.h" +#include "preferences.h" +#include "selection.h" namespace Inkscape { namespace Extension { namespace Internal { - /** \brief A function to allocated anything -- just an example here \param module Unused \return Whether the load was successful */ -bool -BlurEdge::load (Inkscape::Extension::Extension */*module*/) +bool BlurEdge::load(Inkscape::Extension::Extension * /*module*/) { // std::cout << "Hey, I'm Blur Edge, I'm loading!" << std::endl; return TRUE; @@ -51,38 +48,37 @@ BlurEdge::load (Inkscape::Extension::Extension */*module*/) \param module The effect that was called (unused) \param desktop What should be edited. */ -void -BlurEdge::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::View *desktop, Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) +void BlurEdge::effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *desktop, + Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) { - Inkscape::Selection * selection = static_cast(desktop)->selection; + Inkscape::Selection *selection = static_cast(desktop)->selection; float width = module->get_param_float("blur-width"); - int steps = module->get_param_int("num-steps"); + int steps = module->get_param_int("num-steps"); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double old_offset = prefs->getDouble("/options/defaultoffsetwidth/value", 1.0, "px"); // TODO need to properly refcount the items, at least - std::vector items(selection->items().begin(), selection->items().end()); + std::vector items(selection->items().begin(), selection->items().end()); selection->clear(); - for(auto spitem : items) { + for (auto spitem : items) { std::vector new_items(steps); Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); - Inkscape::XML::Node * new_group = xml_doc->createElement("svg:g"); + Inkscape::XML::Node *new_group = xml_doc->createElement("svg:g"); spitem->getRepr()->parent()->appendChild(new_group); double orig_opacity = sp_repr_css_double_property(sp_repr_css_attr(spitem->getRepr(), "style"), "opacity", 1.0); char opacity_string[64]; - g_ascii_formatd(opacity_string, sizeof(opacity_string), "%f", - orig_opacity / (steps)); + g_ascii_formatd(opacity_string, sizeof(opacity_string), "%f", orig_opacity / (steps)); for (int i = 0; i < steps; i++) { double offset = (width / (float)(steps - 1) * (float)i) - (width / 2.0); new_items[i] = spitem->getRepr()->duplicate(xml_doc); - SPCSSAttr * css = sp_repr_css_attr(new_items[i], "style"); + SPCSSAttr *css = sp_repr_css_attr(new_items[i], "style"); sp_repr_css_set_property(css, "opacity", opacity_string); sp_repr_css_change(new_items[i], css, "style"); @@ -94,10 +90,14 @@ BlurEdge::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::View /* Doing an inset here folks */ offset *= -1.0; prefs->setDoubleUnit("/options/defaultoffsetwidth/value", offset, "px"); - sp_action_perform(Inkscape::Verb::get(SP_VERB_SELECTION_INSET)->get_action(Inkscape::ActionContext(desktop)), nullptr); + sp_action_perform( + Inkscape::Verb::get(SP_VERB_SELECTION_INSET)->get_action(Inkscape::ActionContext(desktop)), + nullptr); } else if (offset > 0.0) { prefs->setDoubleUnit("/options/defaultoffsetwidth/value", offset, "px"); - sp_action_perform(Inkscape::Verb::get(SP_VERB_SELECTION_OFFSET)->get_action(Inkscape::ActionContext(desktop)), nullptr); + sp_action_perform( + Inkscape::Verb::get(SP_VERB_SELECTION_OFFSET)->get_action(Inkscape::ActionContext(desktop)), + nullptr); } selection->clear(); @@ -114,16 +114,16 @@ BlurEdge::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::View return; } -Gtk::Widget * -BlurEdge::prefs_effect(Inkscape::Extension::Effect * module, Inkscape::UI::View::View * /*view*/, sigc::signal * changeSignal, Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) +Gtk::Widget *BlurEdge::prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View * /*view*/, + sigc::signal *changeSignal, + Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) { return module->autogui(nullptr, nullptr, changeSignal); } #include "clear-n_.h" -void -BlurEdge::init () +void BlurEdge::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/bluredge.h b/src/extension/internal/bluredge.h index b74b7535b2fecfef1b8799bf150787c1628cff44..a0dedd95411a9a67cb425c623868827ec2d033de 100644 --- a/src/extension/internal/bluredge.h +++ b/src/extension/internal/bluredge.h @@ -21,14 +21,17 @@ namespace Internal { /** \brief Implementation class of the GIMP gradient plugin. This mostly just creates a namespace for the GIMP gradient plugin today. */ -class BlurEdge : public Inkscape::Extension::Implementation::Implementation { - +class BlurEdge : public Inkscape::Extension::Implementation::Implementation +{ public: bool load(Inkscape::Extension::Extension *module) override; - void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, Inkscape::Extension::Implementation::ImplementationDocumentCache * docCache) override; - Gtk::Widget * prefs_effect(Inkscape::Extension::Effect * module, Inkscape::UI::View::View * view, sigc::signal * changeSignal, Inkscape::Extension::Implementation::ImplementationDocumentCache * docCache) override; + void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, + Inkscape::Extension::Implementation::ImplementationDocumentCache *docCache) override; + Gtk::Widget *prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *view, + sigc::signal *changeSignal, + Inkscape::Extension::Implementation::ImplementationDocumentCache *docCache) override; - static void init (); + static void init(); }; }; /* namespace Internal */ diff --git a/src/extension/internal/cairo-ps-out.cpp b/src/extension/internal/cairo-ps-out.cpp index 4d6e5674007fcd2b140066d973e3e68b571d1469..8759f228eaaa385969106277f672884222d68c6c 100644 --- a/src/extension/internal/cairo-ps-out.cpp +++ b/src/extension/internal/cairo-ps-out.cpp @@ -18,31 +18,29 @@ #include #ifdef CAIRO_HAS_PS_SURFACE -#include "cairo-ps.h" +#include + #include "cairo-ps-out.h" +#include "cairo-ps.h" #include "cairo-render-context.h" #include "cairo-renderer.h" -#include "latex-text-renderer.h" -#include -#include "extension/system.h" -#include "extension/print.h" +#include "display/curve.h" +#include "display/drawing.h" +#include "document.h" #include "extension/db.h" #include "extension/output.h" -#include "display/drawing.h" - -#include "display/curve.h" - +#include "extension/print.h" +#include "extension/system.h" +#include "io/sys.h" +#include "latex-text-renderer.h" #include "object/sp-item.h" #include "object/sp-root.h" -#include "io/sys.h" -#include "document.h" - namespace Inkscape { namespace Extension { namespace Internal { -bool CairoPsOutput::check (Inkscape::Extension::Extension * /*module*/) +bool CairoPsOutput::check(Inkscape::Extension::Extension * /*module*/) { if (nullptr == Inkscape::Extension::db.get(SP_MODULE_KEY_PRINT_CAIRO_PS)) { return FALSE; @@ -51,7 +49,7 @@ bool CairoPsOutput::check (Inkscape::Extension::Extension * /*module*/) } } -bool CairoEpsOutput::check (Inkscape::Extension::Extension * /*module*/) +bool CairoEpsOutput::check(Inkscape::Extension::Extension * /*module*/) { if (nullptr == Inkscape::Extension::db.get(SP_MODULE_KEY_PRINT_CAIRO_EPS)) { return FALSE; @@ -60,9 +58,9 @@ bool CairoEpsOutput::check (Inkscape::Extension::Extension * /*module*/) } } -static bool -ps_print_document_to_file(SPDocument *doc, gchar const *filename, unsigned int level, bool texttopath, bool omittext, - bool filtertobitmap, int resolution, const gchar * const exportId, bool exportDrawing, bool exportCanvas, float bleedmargin_px, bool eps = false) +static bool ps_print_document_to_file(SPDocument *doc, gchar const *filename, unsigned int level, bool texttopath, + bool omittext, bool filtertobitmap, int resolution, const gchar *const exportId, + bool exportDrawing, bool exportCanvas, float bleedmargin_px, bool eps = false) { doc->ensureUpToDate(); @@ -78,8 +76,7 @@ ps_print_document_to_file(SPDocument *doc, gchar const *filename, unsigned int l } root->cropToObject(base); // TODO: This is inconsistent in CLI (should only happen for --export-id-only) pageBoundingBox = exportCanvas; - } - else { + } else { // we want to export the entire document from root base = root; pageBoundingBox = !exportDrawing; @@ -103,7 +100,7 @@ ps_print_document_to_file(SPDocument *doc, gchar const *filename, unsigned int l ctx->setBitmapResolution(resolution); bool ret = ctx->setPsTarget(filename); - if(ret) { + if (ret) { /* Render document */ ret = renderer->setupDocument(ctx, doc, pageBoundingBox, bleedmargin_px, base); if (ret) { @@ -120,17 +117,15 @@ ps_print_document_to_file(SPDocument *doc, gchar const *filename, unsigned int l return ret; } - /** \brief This function calls the output module with the filename - \param mod unused - \param doc Document to be saved + \param mod unused + \param doc Document to be saved \param filename Filename to save to (probably will end in .ps) */ -void -CairoPsOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) +void CairoPsOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) { - Inkscape::Extension::Extension * ext; + Inkscape::Extension::Extension *ext; unsigned int ret; ext = Inkscape::Extension::db.get(SP_MODULE_KEY_PRINT_CAIRO_PS); @@ -140,59 +135,63 @@ CairoPsOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar con int level = CAIRO_PS_LEVEL_2; try { const gchar *new_level = mod->get_param_optiongroup("PSlevel"); - if((new_level != nullptr) && (g_ascii_strcasecmp("PS3", new_level) == 0)) { + if ((new_level != nullptr) && (g_ascii_strcasecmp("PS3", new_level) == 0)) { level = CAIRO_PS_LEVEL_3; } - } catch(...) {} + } catch (...) { + } - bool new_textToPath = FALSE; + bool new_textToPath = FALSE; try { new_textToPath = (strcmp(mod->get_param_optiongroup("textToPath"), "paths") == 0); - } catch(...) {} + } catch (...) { + } - bool new_textToLaTeX = FALSE; + bool new_textToLaTeX = FALSE; try { new_textToLaTeX = (strcmp(mod->get_param_optiongroup("textToPath"), "LaTeX") == 0); - } - catch(...) { + } catch (...) { g_warning("Parameter might not exist"); } - bool new_blurToBitmap = FALSE; + bool new_blurToBitmap = FALSE; try { - new_blurToBitmap = mod->get_param_bool("blurToBitmap"); - } catch(...) {} + new_blurToBitmap = mod->get_param_bool("blurToBitmap"); + } catch (...) { + } - int new_bitmapResolution = 72; + int new_bitmapResolution = 72; try { new_bitmapResolution = mod->get_param_int("resolution"); - } catch(...) {} + } catch (...) { + } - bool new_areaPage = true; + bool new_areaPage = true; try { new_areaPage = (strcmp(mod->get_param_optiongroup("area"), "page") == 0); - } catch(...) {} + } catch (...) { + } - bool new_areaDrawing = !new_areaPage; + bool new_areaDrawing = !new_areaPage; float bleedmargin_px = 0.; try { bleedmargin_px = mod->get_param_float("bleed"); - } catch(...) {} + } catch (...) { + } const gchar *new_exportId = nullptr; try { new_exportId = mod->get_param_string("exportId"); - } catch(...) {} + } catch (...) { + } // Create PS { - gchar * final_name; + gchar *final_name; final_name = g_strdup_printf("> %s", filename); - ret = ps_print_document_to_file(doc, final_name, level, new_textToPath, - new_textToLaTeX, new_blurToBitmap, - new_bitmapResolution, new_exportId, - new_areaDrawing, new_areaPage, + ret = ps_print_document_to_file(doc, final_name, level, new_textToPath, new_textToLaTeX, new_blurToBitmap, + new_bitmapResolution, new_exportId, new_areaDrawing, new_areaPage, bleedmargin_px); g_free(final_name); @@ -209,17 +208,15 @@ CairoPsOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar con } } - /** \brief This function calls the output module with the filename - \param mod unused - \param doc Document to be saved + \param mod unused + \param doc Document to be saved \param filename Filename to save to (probably will end in .ps) */ -void -CairoEpsOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) +void CairoEpsOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) { - Inkscape::Extension::Extension * ext; + Inkscape::Extension::Extension *ext; unsigned int ret; ext = Inkscape::Extension::db.get(SP_MODULE_KEY_PRINT_CAIRO_EPS); @@ -229,59 +226,63 @@ CairoEpsOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar co int level = CAIRO_PS_LEVEL_2; try { const gchar *new_level = mod->get_param_optiongroup("PSlevel"); - if((new_level != nullptr) && (g_ascii_strcasecmp("PS3", new_level) == 0)) { + if ((new_level != nullptr) && (g_ascii_strcasecmp("PS3", new_level) == 0)) { level = CAIRO_PS_LEVEL_3; } - } catch(...) {} + } catch (...) { + } - bool new_textToPath = FALSE; + bool new_textToPath = FALSE; try { new_textToPath = (strcmp(mod->get_param_optiongroup("textToPath"), "paths") == 0); - } catch(...) {} + } catch (...) { + } - bool new_textToLaTeX = FALSE; + bool new_textToLaTeX = FALSE; try { new_textToLaTeX = (strcmp(mod->get_param_optiongroup("textToPath"), "LaTeX") == 0); - } - catch(...) { + } catch (...) { g_warning("Parameter might not exist"); } - bool new_blurToBitmap = FALSE; + bool new_blurToBitmap = FALSE; try { - new_blurToBitmap = mod->get_param_bool("blurToBitmap"); - } catch(...) {} + new_blurToBitmap = mod->get_param_bool("blurToBitmap"); + } catch (...) { + } - int new_bitmapResolution = 72; + int new_bitmapResolution = 72; try { new_bitmapResolution = mod->get_param_int("resolution"); - } catch(...) {} + } catch (...) { + } - bool new_areaPage = true; + bool new_areaPage = true; try { new_areaPage = (strcmp(mod->get_param_optiongroup("area"), "page") == 0); - } catch(...) {} + } catch (...) { + } - bool new_areaDrawing = !new_areaPage; + bool new_areaDrawing = !new_areaPage; float bleedmargin_px = 0.; try { bleedmargin_px = mod->get_param_float("bleed"); - } catch(...) {} + } catch (...) { + } const gchar *new_exportId = nullptr; try { new_exportId = mod->get_param_string("exportId"); - } catch(...) {} + } catch (...) { + } // Create EPS { - gchar * final_name; + gchar *final_name; final_name = g_strdup_printf("> %s", filename); - ret = ps_print_document_to_file(doc, final_name, level, new_textToPath, - new_textToLaTeX, new_blurToBitmap, - new_bitmapResolution, new_exportId, - new_areaDrawing, new_areaPage, + ret = ps_print_document_to_file(doc, final_name, level, new_textToPath, new_textToLaTeX, new_blurToBitmap, + new_bitmapResolution, new_exportId, new_areaDrawing, new_areaPage, bleedmargin_px, true); g_free(final_name); @@ -298,15 +299,12 @@ CairoEpsOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar co } } - -bool -CairoPsOutput::textToPath(Inkscape::Extension::Print * ext) +bool CairoPsOutput::textToPath(Inkscape::Extension::Print *ext) { return ext->get_param_bool("textToPath"); } -bool -CairoEpsOutput::textToPath(Inkscape::Extension::Print * ext) +bool CairoEpsOutput::textToPath(Inkscape::Extension::Print *ext) { return ext->get_param_bool("textToPath"); } @@ -314,14 +312,13 @@ CairoEpsOutput::textToPath(Inkscape::Extension::Print * ext) #include "clear-n_.h" /** - \brief A function allocate a copy of this function. + \brief A function allocate a copy of this function. - This is the definition of Cairo PS out. This function just - calls the extension system with the memory allocated XML that - describes the data. + This is the definition of Cairo PS out. This function just + calls the extension system with the memory allocated XML that + describes the data. */ -void -CairoPsOutput::init () +void CairoPsOutput::init() { // clang-format off Inkscape::Extension::build_from_mem( @@ -358,14 +355,13 @@ CairoPsOutput::init () } /** - \brief A function allocate a copy of this function. + \brief A function allocate a copy of this function. - This is the definition of Cairo EPS out. This function just - calls the extension system with the memory allocated XML that - describes the data. + This is the definition of Cairo EPS out. This function just + calls the extension system with the memory allocated XML that + describes the data. */ -void -CairoEpsOutput::init () +void CairoEpsOutput::init() { // clang-format off Inkscape::Extension::build_from_mem( @@ -401,6 +397,8 @@ CairoEpsOutput::init () return; } -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* HAVE_CAIRO_PDF */ diff --git a/src/extension/internal/cairo-ps-out.h b/src/extension/internal/cairo-ps-out.h index ee58179c45f9b9a585f2741c09ed32d6aa8ee7f9..8c2d37d86e7c4f09e33fa5f5a3893a5b601d4b4d 100644 --- a/src/extension/internal/cairo-ps-out.h +++ b/src/extension/internal/cairo-ps-out.h @@ -23,31 +23,27 @@ namespace Inkscape { namespace Extension { namespace Internal { -class CairoPsOutput : Inkscape::Extension::Implementation::Implementation { - +class CairoPsOutput : Inkscape::Extension::Implementation::Implementation +{ public: bool check(Inkscape::Extension::Extension *module) override; - void save(Inkscape::Extension::Output *mod, - SPDocument *doc, - gchar const *filename) override; + void save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) override; static void init(); bool textToPath(Inkscape::Extension::Print *ext) override; - }; -class CairoEpsOutput : Inkscape::Extension::Implementation::Implementation { - +class CairoEpsOutput : Inkscape::Extension::Implementation::Implementation +{ public: bool check(Inkscape::Extension::Extension *module) override; - void save(Inkscape::Extension::Output *mod, - SPDocument *doc, - gchar const *uri) override; + void save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *uri) override; static void init(); bool textToPath(Inkscape::Extension::Print *ext) override; - }; -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* !EXTENSION_INTERNAL_CAIRO_PS_OUT_H */ diff --git a/src/extension/internal/cairo-render-context.cpp b/src/extension/internal/cairo-render-context.cpp index c9e51533ba57dc6d3dd408e544ed34440f757f5e..03c7bed345031d32d1a36689b80ec7b80fa2714d 100644 --- a/src/extension/internal/cairo-render-context.cpp +++ b/src/extension/internal/cairo-render-context.cpp @@ -14,7 +14,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifndef PANGO_ENABLE_BACKEND @@ -25,43 +25,37 @@ #define PANGO_ENABLE_ENGINE #endif -#include "cairo-render-context.h" - -#include -#include #include <2geom/pathvector.h> - +#include +#include #include #include -#include "display/drawing.h" -#include "display/curve.h" +#include "cairo-render-context.h" #include "display/cairo-utils.h" - -#include "object/sp-item.h" -#include "object/sp-item-group.h" +#include "display/curve.h" +#include "display/drawing.h" +#include "object/sp-clippath.h" #include "object/sp-hatch.h" +#include "object/sp-item-group.h" +#include "object/sp-item.h" #include "object/sp-linear-gradient.h" -#include "object/sp-radial-gradient.h" +#include "object/sp-mask.h" #include "object/sp-mesh-gradient.h" #include "object/sp-pattern.h" -#include "object/sp-mask.h" -#include "object/sp-clippath.h" - +#include "object/sp-radial-gradient.h" #include "util/units.h" #ifdef _WIN32 #include "libnrtype/FontFactory.h" // USE_PANGO_WIN32 #endif +#include + #include "cairo-renderer.h" #include "extension/system.h" - #include "io/sys.h" - #include "svg/stringstream.h" -#include - // include support for only the compiled-in surface types #ifdef CAIRO_HAS_PDF_SURFACE #include @@ -70,13 +64,12 @@ #include #endif - #ifdef CAIRO_HAS_FT_FONT #include #endif #ifdef CAIRO_HAS_WIN32_FONT -#include #include +#include #endif #include @@ -108,39 +101,43 @@ namespace Internal { static cairo_status_t _write_callback(void *closure, const unsigned char *data, unsigned int length); -CairoRenderContext::CairoRenderContext(CairoRenderer *parent) : - _dpi(72), - _pdf_level(1), - _ps_level(1), - _eps(false), - _is_texttopath(FALSE), - _is_omittext(FALSE), - _is_filtertobitmap(FALSE), - _bitmapresolution(72), - _stream(nullptr), - _is_valid(FALSE), - _vector_based_target(FALSE), - _cr(nullptr), // Cairo context - _surface(nullptr), - _target(CAIRO_SURFACE_TYPE_IMAGE), - _target_format(CAIRO_FORMAT_ARGB32), - _layout(nullptr), - _state(nullptr), - _renderer(parent), - _render_mode(RENDER_MODE_NORMAL), - _clip_mode(CLIP_MODE_MASK), - _omittext_state(EMPTY) -{ -} +CairoRenderContext::CairoRenderContext(CairoRenderer *parent) + : _dpi(72) + , _pdf_level(1) + , _ps_level(1) + , _eps(false) + , _is_texttopath(FALSE) + , _is_omittext(FALSE) + , _is_filtertobitmap(FALSE) + , _bitmapresolution(72) + , _stream(nullptr) + , _is_valid(FALSE) + , _vector_based_target(FALSE) + , _cr(nullptr) + , // Cairo context + _surface(nullptr) + , _target(CAIRO_SURFACE_TYPE_IMAGE) + , _target_format(CAIRO_FORMAT_ARGB32) + , _layout(nullptr) + , _state(nullptr) + , _renderer(parent) + , _render_mode(RENDER_MODE_NORMAL) + , _clip_mode(CLIP_MODE_MASK) + , _omittext_state(EMPTY) +{} CairoRenderContext::~CairoRenderContext() { - for (std::map::const_iterator iter = font_table.begin(); iter != font_table.end(); ++iter) + for (std::map::const_iterator iter = font_table.begin(); iter != font_table.end(); + ++iter) font_data_free(iter->second); - if (_cr) cairo_destroy(_cr); - if (_surface) cairo_surface_destroy(_surface); - if (_layout) g_object_unref(_layout); + if (_cr) + cairo_destroy(_cr); + if (_surface) + cairo_surface_destroy(_surface); + if (_layout) + g_object_unref(_layout); } void CairoRenderContext::font_data_free(gpointer data) { @@ -150,23 +147,23 @@ void CairoRenderContext::font_data_free(gpointer data) } } -CairoRenderer* CairoRenderContext::getRenderer() const +CairoRenderer *CairoRenderContext::getRenderer() const { return _renderer; } -CairoRenderState* CairoRenderContext::getCurrentState() const +CairoRenderState *CairoRenderContext::getCurrentState() const { return _state; } -CairoRenderState* CairoRenderContext::getParentState() const +CairoRenderState *CairoRenderContext::getParentState() const { // if this is the root node just return it if (_state_stack.size() == 1) { return _state; } else { - return _state_stack[_state_stack.size()-2]; + return _state_stack[_state_stack.size() - 2]; } } @@ -181,9 +178,7 @@ void CairoRenderContext::setStateForStyle(SPStyle const *style) _state->merge_opacity = FALSE; // disable rendering of opacity if there's a stroke on the fill - if (_state->merge_opacity - && !style->fill.isNone() - && !style->stroke.isNone()) + if (_state->merge_opacity && !style->fill.isNone() && !style->stroke.isNone()) _state->merge_opacity = FALSE; } @@ -193,11 +188,10 @@ void CairoRenderContext::setStateForStyle(SPStyle const *style) * \param width width of the surface to be created * \param height height of the surface to be created */ -CairoRenderContext* -CairoRenderContext::cloneMe(double width, double height) const +CairoRenderContext *CairoRenderContext::cloneMe(double width, double height) const { - g_assert( _is_valid ); - g_assert( width > 0.0 && height > 0.0 ); + g_assert(_is_valid); + g_assert(width > 0.0 && height > 0.0); CairoRenderContext *new_context = _renderer->createContext(); cairo_surface_t *surface = cairo_surface_create_similar(cairo_get_target(_cr), CAIRO_CONTENT_COLOR_ALPHA, @@ -211,9 +205,9 @@ CairoRenderContext::cloneMe(double width, double height) const return new_context; } -CairoRenderContext* CairoRenderContext::cloneMe() const +CairoRenderContext *CairoRenderContext::cloneMe() const { - g_assert( _is_valid ); + g_assert(_is_valid); return cloneMe(_width, _height); } @@ -255,54 +249,51 @@ bool CairoRenderContext::setPdfTarget(gchar const *utf8_fn) gsize bytesRead = 0; gsize bytesWritten = 0; GError *error = nullptr; - gchar *local_fn = g_filename_from_utf8(utf8_fn, - -1, &bytesRead, &bytesWritten, &error); + gchar *local_fn = g_filename_from_utf8(utf8_fn, -1, &bytesRead, &bytesWritten, &error); gchar const *fn = local_fn; /* TODO: Replace the below fprintf's with something that does the right thing whether in - * gui or batch mode (e.g. --print=blah). Consider throwing an exception: currently one of - * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the - * return code. - */ + * gui or batch mode (e.g. --print=blah). Consider throwing an exception: currently one of + * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the + * return code. + */ if (fn != nullptr) { if (*fn == '|') { fn += 1; - while (isspace(*fn)) fn += 1; + while (isspace(*fn)) + fn += 1; #ifndef _WIN32 osp = popen(fn, "w"); #else osp = _popen(fn, "w"); #endif if (!osp) { - fprintf(stderr, "inkscape: popen(%s): %s\n", - fn, strerror(errno)); + fprintf(stderr, "inkscape: popen(%s): %s\n", fn, strerror(errno)); return false; } _stream = osp; } else if (*fn == '>') { fn += 1; - while (isspace(*fn)) fn += 1; + while (isspace(*fn)) + fn += 1; Inkscape::IO::dump_fopen_call(fn, "K"); osf = Inkscape::IO::fopen_utf8name(fn, "w+"); if (!osf) { - fprintf(stderr, "inkscape: fopen(%s): %s\n", - fn, strerror(errno)); + fprintf(stderr, "inkscape: fopen(%s): %s\n", fn, strerror(errno)); return false; } _stream = osf; } else { /* put cwd stuff in here */ - gchar *qn = ( *fn - ? g_strdup_printf("lpr -P %s", fn) /* FIXME: quote fn */ - : g_strdup("lpr") ); + gchar *qn = (*fn ? g_strdup_printf("lpr -P %s", fn) /* FIXME: quote fn */ + : g_strdup("lpr")); #ifndef _WIN32 osp = popen(qn, "w"); #else osp = _popen(qn, "w"); #endif if (!osp) { - fprintf(stderr, "inkscape: popen(%s): %s\n", - qn, strerror(errno)); + fprintf(stderr, "inkscape: popen(%s): %s\n", qn, strerror(errno)); return false; } g_free(qn); @@ -315,7 +306,7 @@ bool CairoRenderContext::setPdfTarget(gchar const *utf8_fn) if (_stream) { /* fixme: this is kinda icky */ #if !defined(_WIN32) && !defined(__WIN32__) - (void) signal(SIGPIPE, SIG_IGN); + (void)signal(SIGPIPE, SIG_IGN); #endif } @@ -337,54 +328,51 @@ bool CairoRenderContext::setPsTarget(gchar const *utf8_fn) gsize bytesRead = 0; gsize bytesWritten = 0; GError *error = nullptr; - gchar *local_fn = g_filename_from_utf8(utf8_fn, - -1, &bytesRead, &bytesWritten, &error); + gchar *local_fn = g_filename_from_utf8(utf8_fn, -1, &bytesRead, &bytesWritten, &error); gchar const *fn = local_fn; /* TODO: Replace the below fprintf's with something that does the right thing whether in - * gui or batch mode (e.g. --print=blah). Consider throwing an exception: currently one of - * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the - * return code. - */ + * gui or batch mode (e.g. --print=blah). Consider throwing an exception: currently one of + * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the + * return code. + */ if (fn != nullptr) { if (*fn == '|') { fn += 1; - while (isspace(*fn)) fn += 1; + while (isspace(*fn)) + fn += 1; #ifndef _WIN32 osp = popen(fn, "w"); #else osp = _popen(fn, "w"); #endif if (!osp) { - fprintf(stderr, "inkscape: popen(%s): %s\n", - fn, strerror(errno)); + fprintf(stderr, "inkscape: popen(%s): %s\n", fn, strerror(errno)); return false; } _stream = osp; } else if (*fn == '>') { fn += 1; - while (isspace(*fn)) fn += 1; + while (isspace(*fn)) + fn += 1; Inkscape::IO::dump_fopen_call(fn, "K"); osf = Inkscape::IO::fopen_utf8name(fn, "w+"); if (!osf) { - fprintf(stderr, "inkscape: fopen(%s): %s\n", - fn, strerror(errno)); + fprintf(stderr, "inkscape: fopen(%s): %s\n", fn, strerror(errno)); return false; } _stream = osf; } else { /* put cwd stuff in here */ - gchar *qn = ( *fn - ? g_strdup_printf("lpr -P %s", fn) /* FIXME: quote fn */ - : g_strdup("lpr") ); + gchar *qn = (*fn ? g_strdup_printf("lpr -P %s", fn) /* FIXME: quote fn */ + : g_strdup("lpr")); #ifndef _WIN32 osp = popen(qn, "w"); #else osp = _popen(qn, "w"); #endif if (!osp) { - fprintf(stderr, "inkscape: popen(%s): %s\n", - qn, strerror(errno)); + fprintf(stderr, "inkscape: popen(%s): %s\n", qn, strerror(errno)); return false; } g_free(qn); @@ -397,7 +385,7 @@ bool CairoRenderContext::setPsTarget(gchar const *utf8_fn) if (_stream) { /* fixme: this is kinda icky */ #if !defined(_WIN32) && !defined(__WIN32__) - (void) signal(SIGPIPE, SIG_IGN); + (void)signal(SIGPIPE, SIG_IGN); #endif } @@ -459,16 +447,14 @@ int CairoRenderContext::getBitmapResolution() return _bitmapresolution; } -cairo_surface_t* -CairoRenderContext::getSurface() +cairo_surface_t *CairoRenderContext::getSurface() { - g_assert( _is_valid ); + g_assert(_is_valid); return _surface; } -bool -CairoRenderContext::saveAsPng(const char *file_name) +bool CairoRenderContext::saveAsPng(const char *file_name) { cairo_status_t status = cairo_surface_write_to_png(_surface, file_name); if (status) @@ -477,8 +463,7 @@ CairoRenderContext::saveAsPng(const char *file_name) return true; } -void -CairoRenderContext::setRenderMode(CairoRenderMode mode) +void CairoRenderContext::setRenderMode(CairoRenderMode mode) { switch (mode) { case RENDER_MODE_NORMAL: @@ -491,14 +476,12 @@ CairoRenderContext::setRenderMode(CairoRenderMode mode) } } -CairoRenderContext::CairoRenderMode -CairoRenderContext::getRenderMode() const +CairoRenderContext::CairoRenderMode CairoRenderContext::getRenderMode() const { return _render_mode; } -void -CairoRenderContext::setClipMode(CairoClipMode mode) +void CairoRenderContext::setClipMode(CairoClipMode mode) { switch (mode) { case CLIP_MODE_PATH: // Clip is rendered as a path for vector output @@ -511,16 +494,15 @@ CairoRenderContext::setClipMode(CairoClipMode mode) } } -CairoRenderContext::CairoClipMode -CairoRenderContext::getClipMode() const +CairoRenderContext::CairoClipMode CairoRenderContext::getClipMode() const { return _clip_mode; } -CairoRenderState* CairoRenderContext::_createState() +CairoRenderState *CairoRenderContext::_createState() { - CairoRenderState *state = static_cast(g_try_malloc(sizeof(CairoRenderState))); - g_assert( state != nullptr ); + CairoRenderState *state = static_cast(g_try_malloc(sizeof(CairoRenderState))); + g_assert(state != nullptr); state->has_filtereffect = FALSE; state->merge_opacity = TRUE; @@ -536,7 +518,7 @@ CairoRenderState* CairoRenderContext::_createState() void CairoRenderContext::pushLayer() { - g_assert( _is_valid ); + g_assert(_is_valid); TRACE(("--pushLayer\n")); cairo_push_group(_cr); @@ -550,10 +532,9 @@ void CairoRenderContext::pushLayer() } } -void -CairoRenderContext::popLayer(cairo_operator_t composite) +void CairoRenderContext::popLayer(cairo_operator_t composite) { - g_assert( _is_valid ); + g_assert(_is_valid); float opacity = _state->opacity; TRACE(("--popLayer w/ opacity %f\n", opacity)); @@ -576,7 +557,6 @@ CairoRenderContext::popLayer(cairo_operator_t composite) SPClipPath *clip_path = _state->clip_path; SPMask *mask = _state->mask; if (clip_path || mask) { - CairoRenderContext *clip_ctx = nullptr; cairo_surface_t *clip_mask = nullptr; @@ -584,7 +564,7 @@ CairoRenderContext::popLayer(cairo_operator_t composite) if (clip_path) { TRACE((" Applying clip\n")); if (_render_mode == RENDER_MODE_CLIP) - mask = nullptr; // disable mask when performing nested clipping + mask = nullptr; // disable mask when performing nested clipping if (_vector_based_target) { setClipMode(CLIP_MODE_PATH); // Vector @@ -600,11 +580,10 @@ CairoRenderContext::popLayer(cairo_operator_t composite) // the clipPath will be applied before masking } } else { - // setup a new rendering context clip_ctx = _renderer->createContext(); clip_ctx->setImageTarget(CAIRO_FORMAT_A8); - clip_ctx->setClipMode(CLIP_MODE_MASK); // Raster + clip_ctx->setClipMode(CLIP_MODE_MASK); // Raster // This code ties the clipping to the document coordinates. It doesn't allow // for a clipped object initially drawn off the page and then translated onto // the page. @@ -645,7 +624,7 @@ CairoRenderContext::popLayer(cairo_operator_t composite) if (!mask) { cairo_pop_group_to_source(_cr); - if (composite != CAIRO_OPERATOR_CLEAR){ + if (composite != CAIRO_OPERATOR_CLEAR) { cairo_set_operator(_cr, composite); } cairo_mask_surface(_cr, clip_mask, 0, 0); @@ -664,16 +643,16 @@ CairoRenderContext::popLayer(cairo_operator_t composite) // Cairo surface is expecting the mask to be 96 dpi. float surface_width = _width; float surface_height = _height; - if( _vector_based_target ) { - surface_width *= 4.0/3.0; - surface_height *= 4.0/3.0; + if (_vector_based_target) { + surface_width *= 4.0 / 3.0; + surface_height *= 4.0 / 3.0; } - if (!mask_ctx->setupSurface( surface_width, surface_height )) { + if (!mask_ctx->setupSurface(surface_width, surface_height)) { TRACE(("mask: setupSurface failed\n")); _renderer->destroyContext(mask_ctx); return; } - TRACE(("mask surface: %f x %f at %i dpi\n", surface_width, surface_height, _dpi )); + TRACE(("mask surface: %f x %f at %i dpi\n", surface_width, surface_height, _dpi)); // Mask should start black, but it is created white. cairo_set_source_rgba(mask_ctx->_cr, 0.0, 0.0, 0.0, 1.0); @@ -720,13 +699,12 @@ CairoRenderContext::popLayer(cairo_operator_t composite) const float coeff_r = 0.2125 / 255.0; const float coeff_g = 0.7154 / 255.0; const float coeff_b = 0.0721 / 255.0; - for (int row = 0 ; row < height; row++) { + for (int row = 0; row < height; row++) { unsigned char *row_data = pixels + (row * stride); - for (int i = 0 ; i < width; i++) { + for (int i = 0; i < width; i++) { guint32 *pixel = reinterpret_cast(row_data) + i; float lum_alpha = (((*pixel & 0x00ff0000) >> 16) * coeff_r + - ((*pixel & 0x0000ff00) >> 8) * coeff_g + - ((*pixel & 0x000000ff) ) * coeff_b ); + ((*pixel & 0x0000ff00) >> 8) * coeff_g + ((*pixel & 0x000000ff)) * coeff_b); // lum_alpha can be slightly greater than 1 due to rounding errors... // but this should be OK since it doesn't matter what the lower // six hexadecimal numbers of *pixel are. @@ -735,7 +713,7 @@ CairoRenderContext::popLayer(cairo_operator_t composite) } cairo_pop_group_to_source(_cr); - if (composite != CAIRO_OPERATOR_CLEAR){ + if (composite != CAIRO_OPERATOR_CLEAR) { cairo_set_operator(_cr, composite); } if (_clip_mode == CLIP_MODE_PATH) { @@ -749,7 +727,7 @@ CairoRenderContext::popLayer(cairo_operator_t composite) } else { // No clip path or mask cairo_pop_group_to_source(_cr); - if (composite != CAIRO_OPERATOR_CLEAR){ + if (composite != CAIRO_OPERATOR_CLEAR) { cairo_set_operator(_cr, composite); } if (opacity == 1.0) @@ -758,25 +736,25 @@ CairoRenderContext::popLayer(cairo_operator_t composite) cairo_paint_with_alpha(_cr, opacity); } } -void CairoRenderContext::tagBegin(const char* l){ +void CairoRenderContext::tagBegin(const char *l) +{ #if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 15, 4) - char* link = g_strdup_printf("uri='%s'", l); + char *link = g_strdup_printf("uri='%s'", l); cairo_tag_begin(_cr, CAIRO_TAG_LINK, link); g_free(link); #endif } -void CairoRenderContext::tagEnd(){ +void CairoRenderContext::tagEnd() +{ #if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 15, 4) cairo_tag_end(_cr, CAIRO_TAG_LINK); #endif } - -void -CairoRenderContext::addClipPath(Geom::PathVector const &pv, SPIEnum const *fill_rule) +void CairoRenderContext::addClipPath(Geom::PathVector const &pv, SPIEnum const *fill_rule) { - g_assert( _is_valid ); + g_assert(_is_valid); // here it should be checked whether the current clip winding changed // so we could switch back to masked clipping @@ -788,17 +766,15 @@ CairoRenderContext::addClipPath(Geom::PathVector const &pv, SPIEnum addPathVector(pv); } -void -CairoRenderContext::addClippingRect(double x, double y, double width, double height) +void CairoRenderContext::addClippingRect(double x, double y, double width, double height) { - g_assert( _is_valid ); + g_assert(_is_valid); cairo_rectangle(_cr, x, y, width, height); cairo_clip(_cr); } -bool -CairoRenderContext::setupSurface(double width, double height) +bool CairoRenderContext::setupSurface(double width, double height) { // Is the surface already set up? if (_is_valid) @@ -812,25 +788,27 @@ CairoRenderContext::setupSurface(double width, double height) cairo_surface_t *surface = nullptr; cairo_matrix_t ctm; - cairo_matrix_init_identity (&ctm); + cairo_matrix_init_identity(&ctm); switch (_target) { case CAIRO_SURFACE_TYPE_IMAGE: surface = cairo_image_surface_create(_target_format, (int)ceil(width), (int)ceil(height)); break; #ifdef CAIRO_HAS_PDF_SURFACE case CAIRO_SURFACE_TYPE_PDF: - surface = cairo_pdf_surface_create_for_stream(Inkscape::Extension::Internal::_write_callback, _stream, width, height); + surface = cairo_pdf_surface_create_for_stream(Inkscape::Extension::Internal::_write_callback, _stream, + width, height); cairo_pdf_surface_restrict_to_version(surface, (cairo_pdf_version_t)_pdf_level); break; #endif #ifdef CAIRO_HAS_PS_SURFACE case CAIRO_SURFACE_TYPE_PS: - surface = cairo_ps_surface_create_for_stream(Inkscape::Extension::Internal::_write_callback, _stream, width, height); - if(CAIRO_STATUS_SUCCESS != cairo_surface_status(surface)) { + surface = cairo_ps_surface_create_for_stream(Inkscape::Extension::Internal::_write_callback, _stream, width, + height); + if (CAIRO_STATUS_SUCCESS != cairo_surface_status(surface)) { return FALSE; } cairo_ps_surface_restrict_to_level(surface, (cairo_ps_level_t)_ps_level); - cairo_ps_surface_set_eps(surface, (cairo_bool_t) _eps); + cairo_ps_surface_set_eps(surface, (cairo_bool_t)_eps); break; #endif default: @@ -840,34 +818,32 @@ CairoRenderContext::setupSurface(double width, double height) _setSurfaceMetadata(surface); - return _finishSurfaceSetup (surface, &ctm); + return _finishSurfaceSetup(surface, &ctm); } -bool -CairoRenderContext::setSurfaceTarget(cairo_surface_t *surface, bool is_vector, cairo_matrix_t *ctm) +bool CairoRenderContext::setSurfaceTarget(cairo_surface_t *surface, bool is_vector, cairo_matrix_t *ctm) { if (_is_valid || !surface) return false; _vector_based_target = is_vector; - bool ret = _finishSurfaceSetup (surface, ctm); + bool ret = _finishSurfaceSetup(surface, ctm); if (ret) - cairo_surface_reference (surface); + cairo_surface_reference(surface); return ret; } -bool -CairoRenderContext::_finishSurfaceSetup(cairo_surface_t *surface, cairo_matrix_t *ctm) +bool CairoRenderContext::_finishSurfaceSetup(cairo_surface_t *surface, cairo_matrix_t *ctm) { - if(surface == nullptr) { + if (surface == nullptr) { return false; } - if(CAIRO_STATUS_SUCCESS != cairo_surface_status(surface)) { + if (CAIRO_STATUS_SUCCESS != cairo_surface_status(surface)) { return false; } _cr = cairo_create(surface); - if(CAIRO_STATUS_SUCCESS != cairo_status(_cr)) { + if (CAIRO_STATUS_SUCCESS != cairo_status(_cr)) { return false; } if (ctm) @@ -875,7 +851,8 @@ CairoRenderContext::_finishSurfaceSetup(cairo_surface_t *surface, cairo_matrix_t _surface = surface; if (_vector_based_target) { - cairo_scale(_cr, Inkscape::Util::Quantity::convert(1, "px", "pt"), Inkscape::Util::Quantity::convert(1, "px", "pt")); + cairo_scale(_cr, Inkscape::Util::Quantity::convert(1, "px", "pt"), + Inkscape::Util::Quantity::convert(1, "px", "pt")); } else if (cairo_surface_get_content(_surface) != CAIRO_CONTENT_ALPHA) { // set background color on non-alpha surfaces // TODO: bgcolor should be derived from SPDocument (see IconImpl) @@ -889,8 +866,7 @@ CairoRenderContext::_finishSurfaceSetup(cairo_surface_t *surface, cairo_matrix_t return true; } -void -CairoRenderContext::_setSurfaceMetadata(cairo_surface_t *surface) +void CairoRenderContext::_setSurfaceMetadata(cairo_surface_t *surface) { switch (_target) { #if defined CAIRO_HAS_PDF_SURFACE && CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 15, 4) @@ -933,10 +909,9 @@ CairoRenderContext::_setSurfaceMetadata(cairo_surface_t *surface) } } -bool -CairoRenderContext::finish(bool finish_surface) +bool CairoRenderContext::finish(bool finish_surface) { - g_assert( _is_valid ); + g_assert(_is_valid); if (_vector_based_target && finish_surface) cairo_show_page(_cr); @@ -961,7 +936,7 @@ CairoRenderContext::finish(bool finish_surface) if (_vector_based_target && _stream) { /* Flush stream to be sure. */ - (void) fflush(_stream); + (void)fflush(_stream); fclose(_stream); _stream = nullptr; @@ -973,10 +948,9 @@ CairoRenderContext::finish(bool finish_surface) return false; } -void -CairoRenderContext::transform(Geom::Affine const &transform) +void CairoRenderContext::transform(Geom::Affine const &transform) { - g_assert( _is_valid ); + g_assert(_is_valid); cairo_matrix_t matrix; _initCairoMatrix(&matrix, transform); @@ -986,10 +960,9 @@ CairoRenderContext::transform(Geom::Affine const &transform) _state->transform = getTransform(); } -void -CairoRenderContext::setTransform(Geom::Affine const &transform) +void CairoRenderContext::setTransform(Geom::Affine const &transform) { - g_assert( _is_valid ); + g_assert(_is_valid); cairo_matrix_t matrix; _initCairoMatrix(&matrix, transform); @@ -999,7 +972,7 @@ CairoRenderContext::setTransform(Geom::Affine const &transform) Geom::Affine CairoRenderContext::getTransform() const { - g_assert( _is_valid ); + g_assert(_is_valid); cairo_matrix_t ctm; cairo_get_matrix(_cr, &ctm); @@ -1015,7 +988,7 @@ Geom::Affine CairoRenderContext::getTransform() const Geom::Affine CairoRenderContext::getParentTransform() const { - g_assert( _is_valid ); + g_assert(_is_valid); CairoRenderState *parent_state = getParentState(); return parent_state->transform; @@ -1023,7 +996,7 @@ Geom::Affine CairoRenderContext::getParentTransform() const void CairoRenderContext::pushState() { - g_assert( _is_valid ); + g_assert(_is_valid); cairo_save(_cr); @@ -1036,33 +1009,33 @@ void CairoRenderContext::pushState() void CairoRenderContext::popState() { - g_assert( _is_valid ); + g_assert(_is_valid); cairo_restore(_cr); g_free(_state_stack.back()); _state_stack.pop_back(); - g_assert( !_state_stack.empty()); + g_assert(!_state_stack.empty()); _state = _state_stack.back(); } static bool pattern_hasItemChildren(SPPattern *pat) { - for (auto& child: pat->children) { - if (SP_IS_ITEM (&child)) { + for (auto &child : pat->children) { + if (SP_IS_ITEM(&child)) { return true; } } return false; } -cairo_pattern_t* -CairoRenderContext::_createPatternPainter(SPPaintServer const *const paintserver, Geom::OptRect const &pbox) +cairo_pattern_t *CairoRenderContext::_createPatternPainter(SPPaintServer const *const paintserver, + Geom::OptRect const &pbox) { - g_assert( SP_IS_PATTERN(paintserver) ); + g_assert(SP_IS_PATTERN(paintserver)); - SPPattern *pat = SP_PATTERN (paintserver); + SPPattern *pat = SP_PATTERN(paintserver); Geom::Affine ps2user, pcs2dev; ps2user = Geom::identity(); @@ -1092,7 +1065,7 @@ CairoRenderContext::_createPatternPainter(SPPaintServer const *const paintserver // apply pattern transformation Geom::Affine pattern_transform(pat->getTransform()); ps2user *= pattern_transform; - Geom::Point ori (ps2user[4], ps2user[5]); + Geom::Point ori(ps2user[4], ps2user[5]); // create pattern contents coordinate system if (pat->viewBox_set) { @@ -1104,7 +1077,7 @@ CairoRenderContext::_createPatternPainter(SPPaintServer const *const paintserver w = width * bbox_width_scaler; h = height * bbox_height_scaler; - //calculatePreserveAspectRatio(pat->aspect_align, pat->aspect_clip, view_width, view_height, &x, &y, &w, &h); + // calculatePreserveAspectRatio(pat->aspect_align, pat->aspect_clip, view_width, view_height, &x, &y, &w, &h); pcs2dev[0] = w / view_box.width(); pcs2dev[3] = h / view_box.height(); pcs2dev[4] = x - view_box.left() * pcs2dev[0]; @@ -1131,8 +1104,8 @@ CairoRenderContext::_createPatternPainter(SPPaintServer const *const paintserver double scale_height = surface_height / (bbox_height_scaler * height); if (scale_width != 1.0 || scale_height != 1.0 || _vector_based_target) { TRACE(("needed to scale with %f %f\n", scale_width, scale_height)); - pcs2dev *= Geom::Scale(SUBPIX_SCALE,SUBPIX_SCALE); - ps2user *= Geom::Scale(1.0/SUBPIX_SCALE,1.0/SUBPIX_SCALE); + pcs2dev *= Geom::Scale(SUBPIX_SCALE, SUBPIX_SCALE); + ps2user *= Geom::Scale(1.0 / SUBPIX_SCALE, 1.0 / SUBPIX_SCALE); } // despite scaling up/down by subpixel scaler, the origin point of the pattern must be the same @@ -1149,7 +1122,7 @@ CairoRenderContext::_createPatternPainter(SPPaintServer const *const paintserver // show items and render them for (SPPattern *pat_i = pat; pat_i != nullptr; pat_i = pat_i->ref ? pat_i->ref->getObject() : nullptr) { if (pat_i && SP_IS_OBJECT(pat_i) && pattern_hasItemChildren(pat_i)) { // find the first one with item children - for (auto& child: pat_i->children) { + for (auto &child : pat_i->children) { if (SP_IS_ITEM(&child)) { SP_ITEM(&child)->invoke_show(drawing, dkey, SP_ITEM_REFERENCE_FLAGS); _renderer->renderItem(pattern_ctx, SP_ITEM(&child)); @@ -1178,7 +1151,7 @@ CairoRenderContext::_createPatternPainter(SPPaintServer const *const paintserver // hide all items for (SPPattern *pat_i = pat; pat_i != nullptr; pat_i = pat_i->ref ? pat_i->ref->getObject() : nullptr) { if (pat_i && SP_IS_OBJECT(pat_i) && pattern_hasItemChildren(pat_i)) { // find the first one with item children - for (auto& child: pat_i->children) { + for (auto &child : pat_i->children) { if (SP_IS_ITEM(&child)) { SP_ITEM(&child)->invoke_hide(dkey); } @@ -1190,10 +1163,11 @@ CairoRenderContext::_createPatternPainter(SPPaintServer const *const paintserver return result; } -cairo_pattern_t* -CairoRenderContext::_createHatchPainter(SPPaintServer const *const paintserver, Geom::OptRect const &pbox) { +cairo_pattern_t *CairoRenderContext::_createHatchPainter(SPPaintServer const *const paintserver, + Geom::OptRect const &pbox) +{ SPHatch const *hatch = dynamic_cast(paintserver); - g_assert( hatch ); + g_assert(hatch); g_assert(hatch->pitch() > 0); @@ -1220,10 +1194,10 @@ CairoRenderContext::_createHatchPainter(SPPaintServer const *const paintserver, Geom::Affine child_transform = render_info.child_transform; child_transform *= drawing_transform; - //The rendering of hatch overflow is implemented by repeated drawing - //of hatch paths over one strip. Within each iteration paths are moved by pitch value. - //The movement progresses from right to left. This gives the same result - //as drawing whole strips in left-to-right order. + // The rendering of hatch overflow is implemented by repeated drawing + // of hatch paths over one strip. Within each iteration paths are moved by pitch value. + // The movement progresses from right to left. This gives the same result + // as drawing whole strips in left-to-right order. gdouble overflow_right_strip = 0.0; int overflow_steps = 1; Geom::Affine overflow_transform; @@ -1266,45 +1240,43 @@ CairoRenderContext::_createHatchPainter(SPPaintServer const *const paintserver, return result; } -cairo_pattern_t* -CairoRenderContext::_createPatternForPaintServer(SPPaintServer const *const paintserver, - Geom::OptRect const &pbox, float alpha) +cairo_pattern_t *CairoRenderContext::_createPatternForPaintServer(SPPaintServer const *const paintserver, + Geom::OptRect const &pbox, float alpha) { cairo_pattern_t *pattern = nullptr; bool apply_bbox2user = FALSE; - if (SP_IS_LINEARGRADIENT (paintserver)) { + if (SP_IS_LINEARGRADIENT(paintserver)) { + SPLinearGradient *lg = SP_LINEARGRADIENT(paintserver); - SPLinearGradient *lg=SP_LINEARGRADIENT(paintserver); + SP_GRADIENT(lg)->ensureVector(); // when exporting from commandline, vector is not built - SP_GRADIENT(lg)->ensureVector(); // when exporting from commandline, vector is not built - - Geom::Point p1 (lg->x1.computed, lg->y1.computed); - Geom::Point p2 (lg->x2.computed, lg->y2.computed); - if (pbox && SP_GRADIENT(lg)->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) { - // convert to userspace - Geom::Affine bbox2user(pbox->width(), 0, 0, pbox->height(), pbox->left(), pbox->top()); - p1 *= bbox2user; - p2 *= bbox2user; - } - - // create linear gradient pattern - pattern = cairo_pattern_create_linear(p1[Geom::X], p1[Geom::Y], p2[Geom::X], p2[Geom::Y]); + Geom::Point p1(lg->x1.computed, lg->y1.computed); + Geom::Point p2(lg->x2.computed, lg->y2.computed); + if (pbox && SP_GRADIENT(lg)->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) { + // convert to userspace + Geom::Affine bbox2user(pbox->width(), 0, 0, pbox->height(), pbox->left(), pbox->top()); + p1 *= bbox2user; + p2 *= bbox2user; + } - // add stops - for (gint i = 0; unsigned(i) < lg->vector.stops.size(); i++) { - float rgb[3]; - lg->vector.stops[i].color.get_rgb_floatv(rgb); - cairo_pattern_add_color_stop_rgba(pattern, lg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], lg->vector.stops[i].opacity * alpha); - } - } else if (SP_IS_RADIALGRADIENT (paintserver)) { + // create linear gradient pattern + pattern = cairo_pattern_create_linear(p1[Geom::X], p1[Geom::Y], p2[Geom::X], p2[Geom::Y]); - SPRadialGradient *rg=SP_RADIALGRADIENT(paintserver); + // add stops + for (gint i = 0; unsigned(i) < lg->vector.stops.size(); i++) { + float rgb[3]; + lg->vector.stops[i].color.get_rgb_floatv(rgb); + cairo_pattern_add_color_stop_rgba(pattern, lg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], + lg->vector.stops[i].opacity * alpha); + } + } else if (SP_IS_RADIALGRADIENT(paintserver)) { + SPRadialGradient *rg = SP_RADIALGRADIENT(paintserver); SP_GRADIENT(rg)->ensureVector(); // when exporting from commandline, vector is not built - Geom::Point c (rg->cx.computed, rg->cy.computed); - Geom::Point f (rg->fx.computed, rg->fy.computed); + Geom::Point c(rg->cx.computed, rg->cy.computed); + Geom::Point f(rg->fx.computed, rg->fy.computed); double r = rg->r.computed; double fr = rg->fr.computed; if (pbox && SP_GRADIENT(rg)->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) @@ -1317,15 +1289,16 @@ CairoRenderContext::_createPatternForPaintServer(SPPaintServer const *const pain for (gint i = 0; unsigned(i) < rg->vector.stops.size(); i++) { float rgb[3]; rg->vector.stops[i].color.get_rgb_floatv(rgb); - cairo_pattern_add_color_stop_rgba(pattern, rg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], rg->vector.stops[i].opacity * alpha); + cairo_pattern_add_color_stop_rgba(pattern, rg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], + rg->vector.stops[i].opacity * alpha); } - } else if (SP_IS_MESHGRADIENT (paintserver)) { + } else if (SP_IS_MESHGRADIENT(paintserver)) { SPMeshGradient *mg = SP_MESHGRADIENT(paintserver); pattern = mg->pattern_new(_cr, pbox, 1.0); - } else if (SP_IS_PATTERN (paintserver)) { + } else if (SP_IS_PATTERN(paintserver)) { pattern = _createPatternPainter(paintserver, pbox); - } else if ( dynamic_cast(paintserver) ) { + } else if (dynamic_cast(paintserver)) { pattern = _createHatchPainter(paintserver, pbox); } else { return nullptr; @@ -1341,11 +1314,11 @@ CairoRenderContext::_createPatternForPaintServer(SPPaintServer const *const pain cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT); break; } - case SP_GRADIENT_SPREAD_REFLECT: { // not supported by cairo-pdf yet + case SP_GRADIENT_SPREAD_REFLECT: { // not supported by cairo-pdf yet cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REFLECT); break; } - case SP_GRADIENT_SPREAD_PAD: { // not supported by cairo-pdf yet + case SP_GRADIENT_SPREAD_PAD: { // not supported by cairo-pdf yet cairo_pattern_set_extend(pattern, CAIRO_EXTEND_PAD); break; } @@ -1358,33 +1331,29 @@ CairoRenderContext::_createPatternForPaintServer(SPPaintServer const *const pain cairo_matrix_t pattern_matrix; if (g->gradientTransform_set) { // apply gradient transformation - cairo_matrix_init(&pattern_matrix, - g->gradientTransform[0], g->gradientTransform[1], - g->gradientTransform[2], g->gradientTransform[3], - g->gradientTransform[4], g->gradientTransform[5]); + cairo_matrix_init(&pattern_matrix, g->gradientTransform[0], g->gradientTransform[1], + g->gradientTransform[2], g->gradientTransform[3], g->gradientTransform[4], + g->gradientTransform[5]); } else { - cairo_matrix_init_identity (&pattern_matrix); + cairo_matrix_init_identity(&pattern_matrix); } if (apply_bbox2user) { // convert to userspace cairo_matrix_t bbox2user; - cairo_matrix_init (&bbox2user, pbox->width(), 0, 0, pbox->height(), pbox->left(), pbox->top()); - cairo_matrix_multiply (&pattern_matrix, &bbox2user, &pattern_matrix); + cairo_matrix_init(&bbox2user, pbox->width(), 0, 0, pbox->height(), pbox->left(), pbox->top()); + cairo_matrix_multiply(&pattern_matrix, &bbox2user, &pattern_matrix); } - cairo_matrix_invert(&pattern_matrix); // because Cairo expects a userspace->patternspace matrix + cairo_matrix_invert(&pattern_matrix); // because Cairo expects a userspace->patternspace matrix cairo_pattern_set_matrix(pattern, &pattern_matrix); } return pattern; } -void -CairoRenderContext::_setFillStyle(SPStyle const *const style, Geom::OptRect const &pbox) +void CairoRenderContext::_setFillStyle(SPStyle const *const style, Geom::OptRect const &pbox) { - g_return_if_fail( !style->fill.set - || style->fill.isColor() - || style->fill.isPaintserver() ); + g_return_if_fail(!style->fill.set || style->fill.isColor() || style->fill.isPaintserver()); float alpha = SP_SCALE24_TO_FLOAT(style->fill_opacity.value); if (_state->merge_opacity) { @@ -1394,10 +1363,8 @@ CairoRenderContext::_setFillStyle(SPStyle const *const style, Geom::OptRect cons SPPaintServer const *paint_server = style->getFillPaintServer(); if (paint_server && paint_server->isValid()) { - - g_assert(SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) - || SP_IS_PATTERN(SP_STYLE_FILL_SERVER(style)) - || dynamic_cast(SP_STYLE_FILL_SERVER(style))); + g_assert(SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) || SP_IS_PATTERN(SP_STYLE_FILL_SERVER(style)) || + dynamic_cast(SP_STYLE_FILL_SERVER(style))); cairo_pattern_t *pattern = _createPatternForPaintServer(paint_server, pbox, alpha); if (pattern) { @@ -1411,15 +1378,13 @@ CairoRenderContext::_setFillStyle(SPStyle const *const style, Geom::OptRect cons cairo_set_source_rgba(_cr, rgb[0], rgb[1], rgb[2], alpha); } else { // unset fill is black - g_assert(!style->fill.set - || (paint_server && !paint_server->isValid())); + g_assert(!style->fill.set || (paint_server && !paint_server->isValid())); cairo_set_source_rgba(_cr, 0, 0, 0, alpha); } } -void -CairoRenderContext::_setStrokeStyle(SPStyle const *style, Geom::OptRect const &pbox) +void CairoRenderContext::_setStrokeStyle(SPStyle const *style, Geom::OptRect const &pbox) { float alpha = SP_SCALE24_TO_FLOAT(style->stroke_opacity.value); if (_state->merge_opacity) @@ -1431,10 +1396,9 @@ CairoRenderContext::_setStrokeStyle(SPStyle const *style, Geom::OptRect const &p cairo_set_source_rgba(_cr, rgb[0], rgb[1], rgb[2], alpha); } else { - g_assert( style->stroke.isPaintserver() - || SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) - || SP_IS_PATTERN(SP_STYLE_STROKE_SERVER(style)) - || dynamic_cast(SP_STYLE_STROKE_SERVER(style))); + g_assert(style->stroke.isPaintserver() || SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) || + SP_IS_PATTERN(SP_STYLE_STROKE_SERVER(style)) || + dynamic_cast(SP_STYLE_STROKE_SERVER(style))); cairo_pattern_t *pattern = _createPatternForPaintServer(SP_STYLE_STROKE_SERVER(style), pbox, alpha); @@ -1444,17 +1408,16 @@ CairoRenderContext::_setStrokeStyle(SPStyle const *style, Geom::OptRect const &p } } - if (!style->stroke_dasharray.values.empty()) - { + if (!style->stroke_dasharray.values.empty()) { size_t ndashes = style->stroke_dasharray.values.size(); - double* dashes =(double*)malloc(ndashes*sizeof(double)); - for( unsigned i = 0; i < ndashes; ++i ) { + double *dashes = (double *)malloc(ndashes * sizeof(double)); + for (unsigned i = 0; i < ndashes; ++i) { dashes[i] = style->stroke_dasharray.values[i].value; } cairo_set_dash(_cr, dashes, ndashes, style->stroke_dashoffset.value); free(dashes); } else { - cairo_set_dash(_cr, nullptr, 0, 0.0); // disable dashing + cairo_set_dash(_cr, nullptr, 0, 0.0); // disable dashing } cairo_set_line_width(_cr, style->stroke_width.computed); @@ -1491,8 +1454,7 @@ CairoRenderContext::_setStrokeStyle(SPStyle const *style, Geom::OptRect const &p cairo_set_miter_limit(_cr, MAX(1, style->stroke_miterlimit.value)); } -void -CairoRenderContext::_prepareRenderGraphic() +void CairoRenderContext::_prepareRenderGraphic() { // Only PDFLaTeX supports importing a single page of a graphics file, // so only PDF backend gets interleaved text/graphics @@ -1513,11 +1475,11 @@ CairoRenderContext::_prepareRenderGraphic() // Somebody with a more intimate understanding of cairo and the renderer implementation might // be able to implement this in a cleaner way, though. int stack_size = _state_stack.size(); - for (int i = stack_size-1; i > 0; i--) { + for (int i = stack_size - 1; i > 0; i--) { if (_state_stack[i]->need_layer) popLayer(); cairo_restore(_cr); - _state = _state_stack[i-1]; + _state = _state_stack[i - 1]; } cairo_show_page(_cr); @@ -1534,8 +1496,7 @@ CairoRenderContext::_prepareRenderGraphic() } } -void -CairoRenderContext::_prepareRenderText() +void CairoRenderContext::_prepareRenderText() { // Only PDFLaTeX supports importing a single page of a graphics file, // so only PDF backend gets interleaved text/graphics @@ -1548,10 +1509,10 @@ CairoRenderContext::_prepareRenderText() /* We need CairoPaintOrder as markers are rendered in a separate step and may be rendered * in between fill and stroke. */ -bool -CairoRenderContext::renderPathVector(Geom::PathVector const & pathv, SPStyle const *style, Geom::OptRect const &pbox, CairoPaintOrder order) +bool CairoRenderContext::renderPathVector(Geom::PathVector const &pathv, SPStyle const *style, + Geom::OptRect const &pbox, CairoPaintOrder order) { - g_assert( _is_valid ); + g_assert(_is_valid); _prepareRenderGraphic(); @@ -1569,21 +1530,20 @@ CairoRenderContext::renderPathVector(Geom::PathVector const & pathv, SPStyle con cairo_set_operator(_cr, ink_css_blend_to_cairo_operator(style->mix_blend_mode.value)); } cairo_fill(_cr); - TEST(cairo_surface_write_to_png (_surface, "pathmask.png")); + TEST(cairo_surface_write_to_png(_surface, "pathmask.png")); } return true; } - bool no_fill = style->fill.isNone() || style->fill_opacity.value == 0 || - order == STROKE_ONLY; + bool no_fill = style->fill.isNone() || style->fill_opacity.value == 0 || order == STROKE_ONLY; bool no_stroke = style->stroke.isNone() || style->stroke_width.computed < 1e-9 || - style->stroke_opacity.value == 0 || order == FILL_ONLY; + style->stroke_opacity.value == 0 || order == FILL_ONLY; if (no_fill && no_stroke) return true; - bool need_layer = ( !_state->merge_opacity && !_state->need_layer && - ( _state->opacity != 1.0 || _state->clip_path != nullptr || _state->mask != nullptr ) ); + bool need_layer = (!_state->merge_opacity && !_state->need_layer && + (_state->opacity != 1.0 || _state->clip_path != nullptr || _state->mask != nullptr)); bool blend = false; if (style->mix_blend_mode.set && style->mix_blend_mode.value != SP_CSS_BLEND_NORMAL) { need_layer = true; @@ -1625,7 +1585,7 @@ CairoRenderContext::renderPathVector(Geom::PathVector const & pathv, SPStyle con if (!no_fill && order == FILL_OVER_STROKE) { _setFillStyle(style, pbox); - cairo_fill(_cr); + cairo_fill(_cr); } if (need_layer) { @@ -1641,10 +1601,9 @@ CairoRenderContext::renderPathVector(Geom::PathVector const & pathv, SPStyle con return true; } -bool CairoRenderContext::renderImage(Inkscape::Pixbuf *pb, - Geom::Affine const &image_transform, SPStyle const *style) +bool CairoRenderContext::renderImage(Inkscape::Pixbuf *pb, Geom::Affine const &image_transform, SPStyle const *style) { - g_assert( _is_valid ); + g_assert(_is_valid); if (_render_mode == RENDER_MODE_CLIP) { return true; @@ -1715,14 +1674,15 @@ bool CairoRenderContext::renderImage(Inkscape::Pixbuf *pb, #define GLYPH_ARRAY_SIZE 64 // TODO investigate why the font is being ignored: -unsigned int CairoRenderContext::_showGlyphs(cairo_t *cr, PangoFont * /*font*/, std::vector const &glyphtext, bool path) +unsigned int CairoRenderContext::_showGlyphs(cairo_t *cr, PangoFont * /*font*/, + std::vector const &glyphtext, bool path) { cairo_glyph_t glyph_array[GLYPH_ARRAY_SIZE]; cairo_glyph_t *glyphs = glyph_array; unsigned int num_glyphs = glyphtext.size(); if (num_glyphs > GLYPH_ARRAY_SIZE) { - glyphs = (cairo_glyph_t*)g_try_malloc(sizeof(cairo_glyph_t) * num_glyphs); - if(glyphs == nullptr) { + glyphs = (cairo_glyph_t *)g_try_malloc(sizeof(cairo_glyph_t) * num_glyphs); + if (glyphs == nullptr) { g_warning("CairorenderContext::_showGlyphs: can not allocate memory for %d glyphs.", num_glyphs); return 0; } @@ -1730,7 +1690,7 @@ unsigned int CairoRenderContext::_showGlyphs(cairo_t *cr, PangoFont * /*font*/, unsigned int num_invalid_glyphs = 0; unsigned int i = 0; // is a counter for indexing the glyphs array, only counts the valid glyphs - for (const auto & it_info : glyphtext) { + for (const auto &it_info : glyphtext) { // skip glyphs which are PANGO_GLYPH_EMPTY (0x0FFFFFFF) // or have the PANGO_GLYPH_UNKNOWN_FLAG (0x10000000) set if (it_info.index == 0x0FFFFFFF || it_info.index & 0x10000000) { @@ -1740,8 +1700,8 @@ unsigned int CairoRenderContext::_showGlyphs(cairo_t *cr, PangoFont * /*font*/, continue; } glyphs[i].index = it_info.index; - glyphs[i].x = it_info.x; - glyphs[i].y = it_info.y; + glyphs[i].x = it_info.x; + glyphs[i].y = it_info.y; i++; } @@ -1758,11 +1718,9 @@ unsigned int CairoRenderContext::_showGlyphs(cairo_t *cr, PangoFont * /*font*/, return num_glyphs - num_invalid_glyphs; } -bool -CairoRenderContext::renderGlyphtext(PangoFont *font, Geom::Affine const &font_matrix, - std::vector const &glyphtext, SPStyle const *style) +bool CairoRenderContext::renderGlyphtext(PangoFont *font, Geom::Affine const &font_matrix, + std::vector const &glyphtext, SPStyle const *style) { - _prepareRenderText(); if (_is_omittext) return true; @@ -1771,13 +1729,13 @@ CairoRenderContext::renderGlyphtext(PangoFont *font, Geom::Affine const &font_ma // double size = style->font_size.computed; /// \fixme why is this variable never used? gpointer fonthash = (gpointer)font; cairo_font_face_t *font_face = nullptr; - if(font_table.find(fonthash)!=font_table.end()) + if (font_table.find(fonthash) != font_table.end()) font_face = font_table[fonthash]; FcPattern *fc_pattern = nullptr; #ifdef USE_PANGO_WIN32 -# ifdef CAIRO_HAS_WIN32_FONT +#ifdef CAIRO_HAS_WIN32_FONT LOGFONTA *lfa = pango_win32_font_logfont(font); LOGFONTW lfw; @@ -1785,26 +1743,26 @@ CairoRenderContext::renderGlyphtext(PangoFont *font, Geom::Affine const &font_ma memcpy(&lfw, lfa, sizeof(LOGFONTA)); MultiByteToWideChar(CP_OEMCP, MB_PRECOMPOSED, lfa->lfFaceName, LF_FACESIZE, lfw.lfFaceName, LF_FACESIZE); - if(font_face == NULL) { + if (font_face == NULL) { font_face = cairo_win32_font_face_create_for_logfontw(&lfw); font_table[fonthash] = font_face; } -# endif +#endif #else -# ifdef CAIRO_HAS_FT_FONT +#ifdef CAIRO_HAS_FT_FONT PangoFcFont *fc_font = PANGO_FC_FONT(font); fc_pattern = fc_font->font_pattern; - if(font_face == nullptr) { + if (font_face == nullptr) { font_face = cairo_ft_font_face_create_for_pattern(fc_pattern); font_table[fonthash] = font_face; } -# endif +#endif #endif cairo_save(_cr); cairo_set_font_face(_cr, font_face); - //if (fc_pattern && FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &size) != FcResultMatch) + // if (fc_pattern && FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &size) != FcResultMatch) // size = 12.0; // set the given font matrix @@ -1825,7 +1783,6 @@ CairoRenderContext::renderGlyphtext(PangoFont *font, Geom::Affine const &font_ma _showGlyphs(_cr, font, glyphtext, TRUE); } } else { - bool fill = false; if (style->fill.isColor() || style->fill.isPaintserver()) { fill = true; @@ -1842,14 +1799,14 @@ CairoRenderContext::renderGlyphtext(PangoFont *font, Geom::Affine const &font_ma // Text never has markers bool stroke_over_fill = true; - if ( (style->paint_order.layer[0] == SP_CSS_PAINT_ORDER_STROKE && - style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_FILL) || + if ((style->paint_order.layer[0] == SP_CSS_PAINT_ORDER_STROKE && + style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_FILL) || - (style->paint_order.layer[0] == SP_CSS_PAINT_ORDER_STROKE && - style->paint_order.layer[2] == SP_CSS_PAINT_ORDER_FILL) || + (style->paint_order.layer[0] == SP_CSS_PAINT_ORDER_STROKE && + style->paint_order.layer[2] == SP_CSS_PAINT_ORDER_FILL) || - (style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_STROKE && - style->paint_order.layer[2] == SP_CSS_PAINT_ORDER_FILL) ) { + (style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_STROKE && + style->paint_order.layer[2] == SP_CSS_PAINT_ORDER_FILL)) { stroke_over_fill = false; } @@ -1894,34 +1851,30 @@ CairoRenderContext::renderGlyphtext(PangoFont *font, Geom::Affine const &font_ma _showGlyphs(_cr, font, glyphtext, false); } } - } cairo_restore(_cr); -// if (font_face) -// cairo_font_face_destroy(font_face); + // if (font_face) + // cairo_font_face_destroy(font_face); return true; } /* Helper functions */ -void -CairoRenderContext::setPathVector(Geom::PathVector const &pv) +void CairoRenderContext::setPathVector(Geom::PathVector const &pv) { cairo_new_path(_cr); addPathVector(pv); } -void -CairoRenderContext::addPathVector(Geom::PathVector const &pv) +void CairoRenderContext::addPathVector(Geom::PathVector const &pv) { feed_pathvector_to_cairo(_cr, pv); } -void -CairoRenderContext::_concatTransform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0) +void CairoRenderContext::_concatTransform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0) { cairo_matrix_t matrix; @@ -1929,8 +1882,7 @@ CairoRenderContext::_concatTransform(cairo_t *cr, double xx, double yx, double x cairo_transform(cr, &matrix); } -void -CairoRenderContext::_initCairoMatrix(cairo_matrix_t *matrix, Geom::Affine const &transform) +void CairoRenderContext::_initCairoMatrix(cairo_matrix_t *matrix, Geom::Affine const &transform) { matrix->xx = transform[0]; matrix->yx = transform[1]; @@ -1940,38 +1892,33 @@ CairoRenderContext::_initCairoMatrix(cairo_matrix_t *matrix, Geom::Affine const matrix->y0 = transform[5]; } -void -CairoRenderContext::_concatTransform(cairo_t *cr, Geom::Affine const &transform) +void CairoRenderContext::_concatTransform(cairo_t *cr, Geom::Affine const &transform) { - _concatTransform(cr, transform[0], transform[1], - transform[2], transform[3], - transform[4], transform[5]); + _concatTransform(cr, transform[0], transform[1], transform[2], transform[3], transform[4], transform[5]); } -static cairo_status_t -_write_callback(void *closure, const unsigned char *data, unsigned int length) +static cairo_status_t _write_callback(void *closure, const unsigned char *data, unsigned int length) { size_t written; - FILE *file = (FILE*)closure; + FILE *file = (FILE *)closure; - written = fwrite (data, 1, length, file); + written = fwrite(data, 1, length, file); if (written == length) - return CAIRO_STATUS_SUCCESS; + return CAIRO_STATUS_SUCCESS; else - return CAIRO_STATUS_WRITE_ERROR; + return CAIRO_STATUS_WRITE_ERROR; } #include "clear-n_.h" -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ #undef TRACE #undef TEST - /* Local Variables: mode:c++ diff --git a/src/extension/internal/cairo-render-context.h b/src/extension/internal/cairo-render-context.h index f91a3f9258505a07438638f3e76ae39eaed82212..e671278b1ce8a723cc6a2a42fbdc582e86018607 100644 --- a/src/extension/internal/cairo-render-context.h +++ b/src/extension/internal/cairo-render-context.h @@ -14,17 +14,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/extension.h" +#include <2geom/affine.h> +#include <2geom/forward.h> +#include #include #include -#include <2geom/forward.h> -#include <2geom/affine.h> - +#include "extension/extension.h" #include "style-internal.h" // SPIEnum -#include - class SPClipPath; class SPMask; @@ -43,29 +41,32 @@ struct CairoRenderState; struct CairoGlyphInfo; // Holds info for rendering a glyph -struct CairoGlyphInfo { +struct CairoGlyphInfo +{ unsigned long index; double x; double y; }; -struct CairoRenderState { - unsigned int merge_opacity : 1; // whether fill/stroke opacity can be mul'd with item opacity - unsigned int need_layer : 1; // whether object is masked, clipped, and/or has a non-zero opacity +struct CairoRenderState +{ + unsigned int merge_opacity : 1; // whether fill/stroke opacity can be mul'd with item opacity + unsigned int need_layer : 1; // whether object is masked, clipped, and/or has a non-zero opacity unsigned int has_overflow : 1; - unsigned int parent_has_userspace : 1; // whether the parent's ctm should be applied + unsigned int parent_has_userspace : 1; // whether the parent's ctm should be applied float opacity; bool has_filtereffect; - Geom::Affine item_transform; // this item's item->transform, for correct clipping + Geom::Affine item_transform; // this item's item->transform, for correct clipping SPClipPath *clip_path; - SPMask* mask; + SPMask *mask; - Geom::Affine transform; // the CTM + Geom::Affine transform; // the CTM }; // Metadata to set on the cairo surface (if the surface supports it) -struct CairoRenderContextMetadata { +struct CairoRenderContextMetadata +{ Glib::ustring title = ""; Glib::ustring author = ""; Glib::ustring subject = ""; @@ -76,8 +77,10 @@ struct CairoRenderContextMetadata { Glib::ustring mdate = ""; // currently unused }; -class CairoRenderContext { +class CairoRenderContext +{ friend class CairoRenderer; + public: CairoRenderContext *cloneMe() const; CairoRenderContext *cloneMe(double width, double height) const; @@ -86,12 +89,14 @@ public: CairoRenderer *getRenderer() const; cairo_t *getCairoContext() const; - enum CairoRenderMode { + enum CairoRenderMode + { RENDER_MODE_NORMAL, RENDER_MODE_CLIP }; - enum CairoClipMode { + enum CairoClipMode + { CLIP_MODE_PATH, CLIP_MODE_MASK }; @@ -100,7 +105,7 @@ public: bool setPdfTarget(gchar const *utf8_fn); bool setPsTarget(gchar const *utf8_fn); /** Set the cairo_surface_t from an external source */ - bool setSurfaceTarget(cairo_surface_t *surface, bool is_vector, cairo_matrix_t *ctm=nullptr); + bool setSurfaceTarget(cairo_surface_t *surface, bool is_vector, cairo_matrix_t *ctm = nullptr); void setPSLevel(unsigned int level); void setEPS(bool eps); @@ -140,7 +145,7 @@ public: void pushLayer(); void popLayer(cairo_operator_t composite = CAIRO_OPERATOR_CLEAR); - void tagBegin(const char* link); + void tagBegin(const char *link); void tagEnd(); /* Graphics state manipulation */ @@ -160,18 +165,19 @@ public: void addClippingRect(double x, double y, double width, double height); /* Rendering methods */ - enum CairoPaintOrder { + enum CairoPaintOrder + { STROKE_OVER_FILL, FILL_OVER_STROKE, FILL_ONLY, STROKE_ONLY }; - bool renderPathVector(Geom::PathVector const &pathv, SPStyle const *style, Geom::OptRect const &pbox, CairoPaintOrder order = STROKE_OVER_FILL); - bool renderImage(Inkscape::Pixbuf *pb, - Geom::Affine const &image_transform, SPStyle const *style); - bool renderGlyphtext(PangoFont *font, Geom::Affine const &font_matrix, - std::vector const &glyphtext, SPStyle const *style); + bool renderPathVector(Geom::PathVector const &pathv, SPStyle const *style, Geom::OptRect const &pbox, + CairoPaintOrder order = STROKE_OVER_FILL); + bool renderImage(Inkscape::Pixbuf *pb, Geom::Affine const &image_transform, SPStyle const *style); + bool renderGlyphtext(PangoFont *font, Geom::Affine const &font_matrix, std::vector const &glyphtext, + SPStyle const *style); /* More general rendering methods will have to be added (like fill, stroke) */ @@ -179,7 +185,8 @@ protected: CairoRenderContext(CairoRenderer *renderer); virtual ~CairoRenderContext(); - enum CairoOmitTextPageState { + enum CairoOmitTextPageState + { EMPTY, GRAPHIC_ON_TOP, NEW_PAGE_ON_GRAPHIC @@ -211,7 +218,7 @@ protected: unsigned int _clip_winding_failed : 1; std::vector _state_stack; - CairoRenderState *_state; // the current state + CairoRenderState *_state; // the current state CairoRenderer *_renderer; @@ -222,12 +229,13 @@ protected: CairoRenderContextMetadata _metadata; - cairo_pattern_t *_createPatternForPaintServer(SPPaintServer const *const paintserver, - Geom::OptRect const &pbox, float alpha); + cairo_pattern_t *_createPatternForPaintServer(SPPaintServer const *const paintserver, Geom::OptRect const &pbox, + float alpha); cairo_pattern_t *_createPatternPainter(SPPaintServer const *const paintserver, Geom::OptRect const &pbox); cairo_pattern_t *_createHatchPainter(SPPaintServer const *const paintserver, Geom::OptRect const &pbox); - unsigned int _showGlyphs(cairo_t *cr, PangoFont *font, std::vector const &glyphtext, bool is_stroke); + unsigned int _showGlyphs(cairo_t *cr, PangoFont *font, std::vector const &glyphtext, + bool is_stroke); bool _finishSurfaceSetup(cairo_surface_t *surface, cairo_matrix_t *ctm = nullptr); void _setSurfaceMetadata(cairo_surface_t *surface); @@ -248,9 +256,9 @@ protected: CairoRenderState *_createState(); }; -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* !EXTENSION_INTERNAL_CAIRO_RENDER_CONTEXT_H_SEEN */ diff --git a/src/extension/internal/cairo-renderer-pdf-out.cpp b/src/extension/internal/cairo-renderer-pdf-out.cpp index 05267d3492863bd969ea3f1347a605496a2b547c..3ecc8dc24d205a0003b115d936888d7133b7f007 100644 --- a/src/extension/internal/cairo-renderer-pdf-out.cpp +++ b/src/extension/internal/cairo-renderer-pdf-out.cpp @@ -18,25 +18,22 @@ #include #ifdef CAIRO_HAS_PDF_SURFACE -#include "cairo-renderer-pdf-out.h" +#include <2geom/affine.h> +#include + #include "cairo-render-context.h" +#include "cairo-renderer-pdf-out.h" #include "cairo-renderer.h" -#include "latex-text-renderer.h" -#include -#include "extension/system.h" -#include "extension/print.h" +#include "display/curve.h" +#include "display/drawing.h" +#include "document.h" #include "extension/db.h" #include "extension/output.h" - -#include "display/drawing.h" -#include "display/curve.h" - +#include "extension/print.h" +#include "extension/system.h" +#include "latex-text-renderer.h" #include "object/sp-item.h" #include "object/sp-root.h" - -#include <2geom/affine.h> -#include "document.h" - #include "util/units.h" namespace Inkscape { @@ -54,10 +51,9 @@ bool CairoRendererPdfOutput::check(Inkscape::Extension::Extension * /*module*/) return result; } -static bool -pdf_render_document_to_file(SPDocument *doc, gchar const *filename, unsigned int level, - bool texttopath, bool omittext, bool filtertobitmap, int resolution, - const gchar * const exportId, bool exportDrawing, bool exportCanvas, float bleedmargin_px) +static bool pdf_render_document_to_file(SPDocument *doc, gchar const *filename, unsigned int level, bool texttopath, + bool omittext, bool filtertobitmap, int resolution, const gchar *const exportId, + bool exportDrawing, bool exportCanvas, float bleedmargin_px) { doc->ensureUpToDate(); @@ -73,8 +69,7 @@ pdf_render_document_to_file(SPDocument *doc, gchar const *filename, unsigned int } root->cropToObject(base); // TODO: This is inconsistent in CLI (should only happen for --export-id-only) pageBoundingBox = exportCanvas; - } - else { + } else { // we want to export the entire document from root base = root; pageBoundingBox = !exportDrawing; @@ -83,7 +78,7 @@ pdf_render_document_to_file(SPDocument *doc, gchar const *filename, unsigned int if (!base) { return false; } - + /* Create new arena */ Inkscape::Drawing drawing; drawing.setExact(true); @@ -99,8 +94,8 @@ pdf_render_document_to_file(SPDocument *doc, gchar const *filename, unsigned int ctx->setFilterToBitmap(filtertobitmap); ctx->setBitmapResolution(resolution); - bool ret = ctx->setPdfTarget (filename); - if(ret) { + bool ret = ctx->setPdfTarget(filename); + if (ret) { /* Render document */ ret = renderer->setupDocument(ctx, doc, pageBoundingBox, bleedmargin_px, base); if (ret) { @@ -127,10 +122,9 @@ pdf_render_document_to_file(SPDocument *doc, gchar const *filename, unsigned int an '>' on the front of the filename. This is the syntax used to tell the printing system to save to file. */ -void -CairoRendererPdfOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) +void CairoRendererPdfOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) { - Inkscape::Extension::Extension * ext; + Inkscape::Extension::Extension *ext; unsigned int ret; ext = Inkscape::Extension::db.get("org.inkscape.output.pdf.cairorenderer"); @@ -140,77 +134,70 @@ CairoRendererPdfOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, int level = 0; try { const gchar *new_level = mod->get_param_optiongroup("PDFversion"); - if((new_level != nullptr) && (g_ascii_strcasecmp("PDF-1.5", new_level) == 0)) { + if ((new_level != nullptr) && (g_ascii_strcasecmp("PDF-1.5", new_level) == 0)) { level = 1; } - } - catch(...) { + } catch (...) { g_warning("Parameter might not exist"); } - bool new_textToPath = FALSE; + bool new_textToPath = FALSE; try { new_textToPath = (strcmp(mod->get_param_optiongroup("textToPath"), "paths") == 0); - } - catch(...) { + } catch (...) { g_warning("Parameter might not exist"); } - bool new_textToLaTeX = FALSE; + bool new_textToLaTeX = FALSE; try { new_textToLaTeX = (strcmp(mod->get_param_optiongroup("textToPath"), "LaTeX") == 0); - } - catch(...) { + } catch (...) { g_warning("Parameter might not exist"); } - bool new_blurToBitmap = FALSE; + bool new_blurToBitmap = FALSE; try { - new_blurToBitmap = mod->get_param_bool("blurToBitmap"); - } - catch(...) { + new_blurToBitmap = mod->get_param_bool("blurToBitmap"); + } catch (...) { g_warning("Parameter might not exist"); } - int new_bitmapResolution = 72; + int new_bitmapResolution = 72; try { new_bitmapResolution = mod->get_param_int("resolution"); - } - catch(...) { + } catch (...) { g_warning("Parameter might not exist"); } const gchar *new_exportId = nullptr; try { new_exportId = mod->get_param_string("exportId"); - } - catch(...) { + } catch (...) { g_warning("Parameter might not exist"); } - bool new_exportCanvas = true; + bool new_exportCanvas = true; try { new_exportCanvas = (strcmp(ext->get_param_optiongroup("area"), "page") == 0); - } catch(...) { + } catch (...) { g_warning("Parameter might not exist"); } - bool new_exportDrawing = !new_exportCanvas; + bool new_exportDrawing = !new_exportCanvas; float new_bleedmargin_px = 0.; try { new_bleedmargin_px = Inkscape::Util::Quantity::convert(mod->get_param_float("bleed"), "mm", "px"); - } - catch(...) { + } catch (...) { g_warning("Parameter might not exist"); } // Create PDF file { - gchar * final_name; + gchar *final_name; final_name = g_strdup_printf("> %s", filename); - ret = pdf_render_document_to_file(doc, final_name, level, - new_textToPath, new_textToLaTeX, new_blurToBitmap, new_bitmapResolution, - new_exportId, new_exportDrawing, new_exportCanvas, new_bleedmargin_px); + ret = pdf_render_document_to_file(doc, final_name, level, new_textToPath, new_textToLaTeX, new_blurToBitmap, + new_bitmapResolution, new_exportId, new_exportDrawing, new_exportCanvas, + new_bleedmargin_px); g_free(final_name); if (!ret) @@ -219,7 +206,8 @@ CairoRendererPdfOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, // Create LaTeX file (if requested) if (new_textToLaTeX) { - ret = latex_render_document_text_to_file(doc, filename, new_exportId, new_exportDrawing, new_exportCanvas, new_bleedmargin_px, true); + ret = latex_render_document_text_to_file(doc, filename, new_exportId, new_exportDrawing, new_exportCanvas, + new_bleedmargin_px, true); if (!ret) throw Inkscape::Extension::Output::save_failed(); @@ -235,8 +223,7 @@ CairoRendererPdfOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, calls the extension system with the memory allocated XML that describes the data. */ -void -CairoRendererPdfOutput::init () +void CairoRendererPdfOutput::init() { // clang-format off Inkscape::Extension::build_from_mem( @@ -272,6 +259,8 @@ CairoRendererPdfOutput::init () return; } -} } } /* namespace Inkscape, Extension, Internal */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* HAVE_CAIRO_PDF */ diff --git a/src/extension/internal/cairo-renderer-pdf-out.h b/src/extension/internal/cairo-renderer-pdf-out.h index 9f9901250ebbea2dccda178a56b594b78f919f11..4f4471b63efbc4da8fcb855a6ea562c099fdece9 100644 --- a/src/extension/internal/cairo-renderer-pdf-out.h +++ b/src/extension/internal/cairo-renderer-pdf-out.h @@ -21,17 +21,17 @@ namespace Inkscape { namespace Extension { namespace Internal { -class CairoRendererPdfOutput : Inkscape::Extension::Implementation::Implementation { - +class CairoRendererPdfOutput : Inkscape::Extension::Implementation::Implementation +{ public: bool check(Inkscape::Extension::Extension *module) override; - void save(Inkscape::Extension::Output *mod, - SPDocument *doc, - gchar const *filename) override; + void save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) override; static void init(); }; -} } } /* namespace Inkscape, Extension, Internal */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* !EXTENSION_INTERNAL_CAIRO_RENDERER_PDF_OUT_H */ diff --git a/src/extension/internal/cairo-renderer.cpp b/src/extension/internal/cairo-renderer.cpp index 8a215f4b67f90734e6da8a5f1f453828f6efe401..4e1f87177b6c960fc7ad27fde7abbb465896ad08 100644 --- a/src/extension/internal/cairo-renderer.cpp +++ b/src/extension/internal/cairo-renderer.cpp @@ -14,7 +14,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifndef PANGO_ENABLE_BACKEND @@ -25,14 +25,11 @@ #define PANGO_ENABLE_ENGINE #endif - -#include -#include - - -#include <2geom/transforms.h> #include <2geom/pathvector.h> +#include <2geom/transforms.h> #include +#include +#include #include #include @@ -46,24 +43,16 @@ #include "cairo-render-context.h" #include "cairo-renderer.h" -#include "document.h" -#include "inkscape-version.h" -#include "rdf.h" - #include "display/cairo-utils.h" #include "display/curve.h" - +#include "document.h" #include "extension/system.h" - #include "helper/pixbuf-ops.h" #include "helper/png-write.h" - -#include "io/sys.h" - #include "include/source_date_epoch.h" - +#include "inkscape-version.h" +#include "io/sys.h" #include "libnrtype/Layout-TNG.h" - #include "object/sp-anchor.h" #include "object/sp-clippath.h" #include "object/sp-flowtext.h" @@ -81,7 +70,7 @@ #include "object/sp-symbol.h" #include "object/sp-text.h" #include "object/sp-use.h" - +#include "rdf.h" #include "util/units.h" //#define TRACE(_args) g_printf _args @@ -93,24 +82,22 @@ namespace Inkscape { namespace Extension { namespace Internal { -CairoRenderer::CairoRenderer(void) -= default; +CairoRenderer::CairoRenderer(void) = default; CairoRenderer::~CairoRenderer() { /* restore default signal handling for SIGPIPE */ #if !defined(_WIN32) && !defined(__WIN32__) - (void) signal(SIGPIPE, SIG_DFL); + (void)signal(SIGPIPE, SIG_DFL); #endif return; } -CairoRenderContext* -CairoRenderer::createContext() +CairoRenderContext *CairoRenderer::createContext() { CairoRenderContext *new_context = new CairoRenderContext(this); - g_assert( new_context != nullptr ); + g_assert(new_context != nullptr); new_context->_state = nullptr; @@ -123,8 +110,7 @@ CairoRenderer::createContext() return new_context; } -void -CairoRenderer::destroyContext(CairoRenderContext *ctx) +void CairoRenderer::destroyContext(CairoRenderContext *ctx) { delete ctx; } @@ -147,7 +133,8 @@ static void sp_image_render(SPImage *image, CairoRenderContext *ctx); static void sp_symbol_render(SPSymbol *symbol, CairoRenderContext *ctx); static void sp_asbitmap_render(SPItem *item, CairoRenderContext *ctx); -static void sp_shape_render_invoke_marker_rendering(SPMarker* marker, Geom::Affine tr, SPStyle* style, CairoRenderContext *ctx) +static void sp_shape_render_invoke_marker_rendering(SPMarker *marker, Geom::Affine tr, SPStyle *style, + CairoRenderContext *ctx) { bool render = true; if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) { @@ -159,12 +146,12 @@ static void sp_shape_render_invoke_marker_rendering(SPMarker* marker, Geom::Affi } if (render) { - SPItem* marker_item = sp_item_first_item_child(marker); + SPItem *marker_item = sp_item_first_item_child(marker); if (marker_item) { tr = (Geom::Affine)marker_item->transform * (Geom::Affine)marker->c2p * tr; Geom::Affine old_tr = marker_item->transform; marker_item->transform = tr; - ctx->getRenderer()->renderItem (ctx, marker_item); + ctx->getRenderer()->renderItem(ctx, marker_item); marker_item->transform = old_tr; } } @@ -178,7 +165,7 @@ static void sp_shape_render(SPShape *shape, CairoRenderContext *ctx) Geom::OptRect pbox = shape->geometricBounds(); - SPStyle* style = shape->style; + SPStyle *style = shape->style; Geom::PathVector const &pathv = shape->curve()->get_pathvector(); if (pathv.empty()) { @@ -190,54 +177,58 @@ static void sp_shape_render(SPShape *shape, CairoRenderContext *ctx) style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_STROKE)) { ctx->renderPathVector(pathv, style, pbox, CairoRenderContext::STROKE_OVER_FILL); } else if (style->paint_order.layer[0] == SP_CSS_PAINT_ORDER_STROKE && - style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_FILL ) { + style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_FILL) { ctx->renderPathVector(pathv, style, pbox, CairoRenderContext::FILL_OVER_STROKE); } else if (style->paint_order.layer[0] == SP_CSS_PAINT_ORDER_STROKE && - style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_MARKER ) { + style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_MARKER) { ctx->renderPathVector(pathv, style, pbox, CairoRenderContext::STROKE_ONLY); } else if (style->paint_order.layer[0] == SP_CSS_PAINT_ORDER_FILL && - style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_MARKER ) { + style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_MARKER) { ctx->renderPathVector(pathv, style, pbox, CairoRenderContext::FILL_ONLY); } // START marker - for (int i = 0; i < 2; i++) { // SP_MARKER_LOC and SP_MARKER_LOC_START - if ( shape->_marker[i] ) { - SPMarker* marker = shape->_marker[i]; + for (int i = 0; i < 2; i++) { // SP_MARKER_LOC and SP_MARKER_LOC_START + if (shape->_marker[i]) { + SPMarker *marker = shape->_marker[i]; Geom::Affine tr; if (marker->orient_mode == MARKER_ORIENT_AUTO) { tr = sp_shape_marker_get_transform_at_start(pathv.begin()->front()); } else if (marker->orient_mode == MARKER_ORIENT_AUTO_START_REVERSE) { - tr = Geom::Rotate::from_degrees( 180.0 ) * sp_shape_marker_get_transform_at_start(pathv.begin()->front()); + tr = Geom::Rotate::from_degrees(180.0) * sp_shape_marker_get_transform_at_start(pathv.begin()->front()); } else { - tr = Geom::Rotate::from_degrees(marker->orient.computed) * Geom::Translate(pathv.begin()->front().pointAt(0)); + tr = Geom::Rotate::from_degrees(marker->orient.computed) * + Geom::Translate(pathv.begin()->front().pointAt(0)); } sp_shape_render_invoke_marker_rendering(marker, tr, style, ctx); } } // MID marker - for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID - if ( !shape->_marker[i] ) continue; - SPMarker* marker = shape->_marker[i]; - for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) { + for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID + if (!shape->_marker[i]) + continue; + SPMarker *marker = shape->_marker[i]; + for (Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) { // START position - if ( path_it != pathv.begin() - && ! ((path_it == (pathv.end()-1)) && (path_it->size_default() == 0)) ) // if this is the last path and it is a moveto-only, there is no mid marker there + if (path_it != pathv.begin() && + !((path_it == (pathv.end() - 1)) && (path_it->size_default() == 0))) // if this is the last path and it + // is a moveto-only, there is no + // mid marker there { Geom::Affine tr; if (marker->orient_mode != MARKER_ORIENT_ANGLE) { tr = sp_shape_marker_get_transform_at_start(path_it->front()); } else { - tr = Geom::Rotate::from_degrees(marker->orient.computed) * Geom::Translate(path_it->front().pointAt(0)); + tr = Geom::Rotate::from_degrees(marker->orient.computed) * + Geom::Translate(path_it->front().pointAt(0)); } sp_shape_render_invoke_marker_rendering(marker, tr, style, ctx); } // MID position if (path_it->size_default() > 1) { - Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve - Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve - while (curve_it2 != path_it->end_default()) - { + Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve + Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve + while (curve_it2 != path_it->end_default()) { /* Put marker between curve_it1 and curve_it2. * Loop to end_default (so including closing segment), because when a path is closed, * there should be a midpoint marker between last segment and closing straight line segment */ @@ -245,7 +236,8 @@ static void sp_shape_render(SPShape *shape, CairoRenderContext *ctx) if (marker->orient_mode != MARKER_ORIENT_ANGLE) { tr = sp_shape_marker_get_transform(*curve_it1, *curve_it2); } else { - tr = Geom::Rotate::from_degrees(marker->orient.computed) * Geom::Translate(curve_it1->pointAt(1)); + tr = Geom::Rotate::from_degrees(marker->orient.computed) * + Geom::Translate(curve_it1->pointAt(1)); } sp_shape_render_invoke_marker_rendering(marker, tr, style, ctx); @@ -255,7 +247,7 @@ static void sp_shape_render(SPShape *shape, CairoRenderContext *ctx) } } // END position - if ( path_it != (pathv.end()-1) && !path_it->empty()) { + if (path_it != (pathv.end() - 1) && !path_it->empty()) { Geom::Curve const &lastcurve = path_it->back_default(); Geom::Affine tr; if (marker->orient_mode != MARKER_ORIENT_ANGLE) { @@ -268,9 +260,9 @@ static void sp_shape_render(SPShape *shape, CairoRenderContext *ctx) } } // END marker - for (int i = 0; i < 4; i += 3) { // SP_MARKER_LOC and SP_MARKER_LOC_END - if ( shape->_marker[i] ) { - SPMarker* marker = shape->_marker[i]; + for (int i = 0; i < 4; i += 3) { // SP_MARKER_LOC and SP_MARKER_LOC_END + if (shape->_marker[i]) { + SPMarker *marker = shape->_marker[i]; /* Get reference to last curve in the path. * For moveto-only path, this returns the "closing line segment". */ @@ -296,25 +288,24 @@ static void sp_shape_render(SPShape *shape, CairoRenderContext *ctx) style->paint_order.layer[2] == SP_CSS_PAINT_ORDER_STROKE) { ctx->renderPathVector(pathv, style, pbox, CairoRenderContext::STROKE_OVER_FILL); } else if (style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_STROKE && - style->paint_order.layer[2] == SP_CSS_PAINT_ORDER_FILL ) { + style->paint_order.layer[2] == SP_CSS_PAINT_ORDER_FILL) { ctx->renderPathVector(pathv, style, pbox, CairoRenderContext::FILL_OVER_STROKE); } else if (style->paint_order.layer[2] == SP_CSS_PAINT_ORDER_STROKE && - style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_MARKER ) { + style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_MARKER) { ctx->renderPathVector(pathv, style, pbox, CairoRenderContext::STROKE_ONLY); } else if (style->paint_order.layer[2] == SP_CSS_PAINT_ORDER_FILL && - style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_MARKER ) { + style->paint_order.layer[1] == SP_CSS_PAINT_ORDER_MARKER) { ctx->renderPathVector(pathv, style, pbox, CairoRenderContext::FILL_ONLY); } - } static void sp_group_render(SPGroup *group, CairoRenderContext *ctx) { CairoRenderer *renderer = ctx->getRenderer(); - std::vector l(group->childList(false)); - for(auto x : l){ - SPItem *item = dynamic_cast(x); + std::vector l(group->childList(false)); + for (auto x : l) { + SPItem *item = dynamic_cast(x); if (item) { renderer->renderItem(ctx, item); } @@ -370,8 +361,8 @@ static void sp_image_render(SPImage *image, CairoRenderContext *ctx) double height = image->height.computed; if (image->aspect_align != SP_ASPECT_NONE) { - calculatePreserveAspectRatio (image->aspect_align, image->aspect_clip, (double)w, (double)h, - &x, &y, &width, &height); + calculatePreserveAspectRatio(image->aspect_align, image->aspect_clip, (double)w, (double)h, &x, &y, &width, + &height); } if (image->aspect_clip == SP_ASPECT_SLICE && !ctx->getCurrentState()->has_overflow) { @@ -389,11 +380,11 @@ static void sp_anchor_render(SPAnchor *a, CairoRenderContext *ctx) { CairoRenderer *renderer = ctx->getRenderer(); - std::vector l(a->childList(false)); + std::vector l(a->childList(false)); if (a->href) ctx->tagBegin(a->href); - for(auto x : l){ - SPItem *item = dynamic_cast(x); + for (auto x : l) { + SPItem *item = dynamic_cast(x); if (item) { renderer->renderItem(ctx, item); } @@ -425,8 +416,8 @@ static void sp_symbol_render(SPSymbol *symbol, CairoRenderContext *ctx) view_width = symbol->viewBox.width(); view_height = symbol->viewBox.height(); - calculatePreserveAspectRatio(symbol->aspect_align, symbol->aspect_clip, view_width, view_height, - &x, &y,&width, &height); + calculatePreserveAspectRatio(symbol->aspect_align, symbol->aspect_clip, view_width, view_height, &x, &y, &width, + &height); // [itemTransform *] translate(x, y) * scale(w/vw, h/vh) * translate(-vx, -vy); vb2user = Geom::identity(); @@ -462,18 +453,17 @@ static void sp_root_render(SPRoot *root, CairoRenderContext *ctx) */ static void sp_asbitmap_render(SPItem *item, CairoRenderContext *ctx) { - // The code was adapted from sp_selection_create_bitmap_copy in selection-chemistry.cpp // Calculate resolution double res; /** @TODO reimplement the resolution stuff (WHY?) - */ + */ res = ctx->getBitmapResolution(); - if(res == 0) { + if (res == 0) { res = Inkscape::Util::Quantity::convert(1, "in", "px"); } - TRACE(("sp_asbitmap_render: resolution: %f\n", res )); + TRACE(("sp_asbitmap_render: resolution: %f\n", res)); // Get the bounding box of the selection in desktop coordinates. Geom::OptRect bbox = item->documentVisualBounds(); @@ -492,10 +482,11 @@ static void sp_asbitmap_render(SPItem *item, CairoRenderContext *ctx) } // The width and height of the bitmap in pixels - unsigned width = ceil(bbox->width() * Inkscape::Util::Quantity::convert(res, "px", "in")); + unsigned width = ceil(bbox->width() * Inkscape::Util::Quantity::convert(res, "px", "in")); unsigned height = ceil(bbox->height() * Inkscape::Util::Quantity::convert(res, "px", "in")); - if (width == 0 || height == 0) return; + if (width == 0 || height == 0) + return; // Scale to exactly fit integer bitmap inside bounding box double scale_x = bbox->width() / width; @@ -507,36 +498,34 @@ static void sp_asbitmap_render(SPItem *item, CairoRenderContext *ctx) // For default 96 dpi, snap bitmap to pixel grid if (res == Inkscape::Util::Quantity::convert(1, "in", "px")) { - shift_x = round (shift_x); - shift_y = round (shift_y); + shift_x = round(shift_x); + shift_y = round(shift_y); } // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects // Matrix to put bitmap in correct place on document - Geom::Affine t_on_document = (Geom::Affine)(Geom::Scale (scale_x, scale_y)) * - (Geom::Affine)(Geom::Translate (shift_x, shift_y)); + Geom::Affine t_on_document = + (Geom::Affine)(Geom::Scale(scale_x, scale_y)) * (Geom::Affine)(Geom::Translate(shift_x, shift_y)); // ctx matrix already includes item transformation. We must substract. - Geom::Affine t_item = item->i2doc_affine(); + Geom::Affine t_item = item->i2doc_affine(); Geom::Affine t = t_on_document * t_item.inverse(); // Do the export SPDocument *document = item->document; std::unique_ptr pb( - sp_generate_internal_bitmap(document, nullptr, - bbox->min()[Geom::X], bbox->min()[Geom::Y], bbox->max()[Geom::X], bbox->max()[Geom::Y], - width, height, res, res, (guint32) 0xffffff00, item )); + sp_generate_internal_bitmap(document, nullptr, bbox->min()[Geom::X], bbox->min()[Geom::Y], bbox->max()[Geom::X], + bbox->max()[Geom::Y], width, height, res, res, (guint32)0xffffff00, item)); if (pb) { - //TEST(gdk_pixbuf_save( pb, "bitmap.png", "png", NULL, NULL )); + // TEST(gdk_pixbuf_save( pb, "bitmap.png", "png", NULL, NULL )); ctx->renderImage(pb.get(), t, item->style); } } - static void sp_item_invoke_render(SPItem *item, CairoRenderContext *ctx) { // Check item's visibility @@ -544,7 +533,7 @@ static void sp_item_invoke_render(SPItem *item, CairoRenderContext *ctx) return; } - if(ctx->getFilterToBitmap() && (item->style->filter.set != 0)) { + if (ctx->getFilterToBitmap() && (item->style->filter.set != 0)) { return sp_asbitmap_render(item, ctx); } @@ -604,22 +593,22 @@ static void sp_item_invoke_render(SPItem *item, CairoRenderContext *ctx) } } -void -CairoRenderer::setStateForItem(CairoRenderContext *ctx, SPItem const *item) +void CairoRenderer::setStateForItem(CairoRenderContext *ctx, SPItem const *item) { ctx->setStateForStyle(item->style); CairoRenderState *state = ctx->getCurrentState(); state->clip_path = item->getClipObject(); state->mask = item->getMaskObject(); - state->item_transform = Geom::Affine (item->transform); + state->item_transform = Geom::Affine(item->transform); // If parent_has_userspace is true the parent state's transform // has to be used for the mask's/clippath's context. // This is so because we use the image's/(flow)text's transform for positioning // instead of explicitly specifying it and letting the renderer do the // transformation before rendering the item. - if (dynamic_cast(item) || dynamic_cast(item) || dynamic_cast(item)) { + if (dynamic_cast(item) || dynamic_cast(item) || + dynamic_cast(item)) { state->parent_has_userspace = TRUE; } TRACE(("setStateForItem opacity: %f\n", state->opacity)); @@ -632,14 +621,14 @@ void CairoRenderer::renderItem(CairoRenderContext *ctx, SPItem *item) setStateForItem(ctx, item); CairoRenderState *state = ctx->getCurrentState(); - state->need_layer = ( state->mask || state->clip_path || state->opacity != 1.0 ); - SPStyle* style = item->style; - SPGroup * group = dynamic_cast(item); + state->need_layer = (state->mask || state->clip_path || state->opacity != 1.0); + SPStyle *style = item->style; + SPGroup *group = dynamic_cast(item); bool blend = false; if (group && style->mix_blend_mode.set && style->mix_blend_mode.value != SP_CSS_BLEND_NORMAL) { state->need_layer = true; blend = true; - } + } // Draw item on a temporary surface so a mask, clip-path, or opacity can be applied to it. if (state->need_layer) { state->merge_opacity = FALSE; @@ -650,7 +639,8 @@ void CairoRenderer::renderItem(CairoRenderContext *ctx, SPItem *item) if (state->need_layer) { if (blend) { - ctx->popLayer(ink_css_blend_to_cairo_operator(style->mix_blend_mode.value)); // This applies clipping/masking + ctx->popLayer(ink_css_blend_to_cairo_operator(style->mix_blend_mode.value)); // This applies + // clipping/masking } else { ctx->popLayer(); // This applies clipping/masking } @@ -658,13 +648,14 @@ void CairoRenderer::renderItem(CairoRenderContext *ctx, SPItem *item) ctx->popState(); } -void CairoRenderer::renderHatchPath(CairoRenderContext *ctx, SPHatchPath const &hatchPath, unsigned key) { +void CairoRenderer::renderHatchPath(CairoRenderContext *ctx, SPHatchPath const &hatchPath, unsigned key) +{ ctx->pushState(); ctx->setStateForStyle(hatchPath.style); ctx->transform(Geom::Translate(hatchPath.offset.computed, 0)); std::unique_ptr curve = hatchPath.calculateRenderCurve(key); - Geom::PathVector const & pathv =curve->get_pathvector(); + Geom::PathVector const &pathv = curve->get_pathvector(); if (!pathv.empty()) { ctx->renderPathVector(pathv, hatchPath.style, Geom::OptRect()); } @@ -672,7 +663,8 @@ void CairoRenderer::renderHatchPath(CairoRenderContext *ctx, SPHatchPath const & ctx->popState(); } -void CairoRenderer::setMetadata(CairoRenderContext *ctx, SPDocument *doc) { +void CairoRenderer::setMetadata(CairoRenderContext *ctx, SPDocument *doc) +{ // title const gchar *title = rdf_get_work_entity(doc, rdf_find_entity("title")); if (title) { @@ -704,8 +696,8 @@ void CairoRenderer::setMetadata(CairoRenderContext *ctx, SPDocument *doc) { } // creator - ctx->_metadata.creator = Glib::ustring::compose("Inkscape %1 (https://inkscape.org)", - Inkscape::version_string_without_revision); + ctx->_metadata.creator = + Glib::ustring::compose("Inkscape %1 (https://inkscape.org)", Inkscape::version_string_without_revision); // cdate (only used for for reproducible builds hack) Glib::ustring cdate = ReproducibleBuilds::now_iso_8601(); @@ -716,12 +708,13 @@ void CairoRenderer::setMetadata(CairoRenderContext *ctx, SPDocument *doc) { // mdate (currently unused) } -bool -CairoRenderer::setupDocument(CairoRenderContext *ctx, SPDocument *doc, bool pageBoundingBox, float bleedmargin_px, SPItem *base) +bool CairoRenderer::setupDocument(CairoRenderContext *ctx, SPDocument *doc, bool pageBoundingBox, float bleedmargin_px, + SPItem *base) { -// PLEASE note when making changes to the boundingbox and transform calculation, corresponding changes should be made to LaTeXTextRenderer::setupDocument !!! + // PLEASE note when making changes to the boundingbox and transform calculation, corresponding changes should be + // made to LaTeXTextRenderer::setupDocument !!! - g_assert( ctx != nullptr ); + g_assert(ctx != nullptr); if (!base) { base = doc->getRoot(); @@ -729,7 +722,7 @@ CairoRenderer::setupDocument(CairoRenderContext *ctx, SPDocument *doc, bool page Geom::Rect d; if (pageBoundingBox) { - d = Geom::Rect::from_xywh(Geom::Point(0,0), doc->getDimensions()); + d = Geom::Rect::from_xywh(Geom::Point(0, 0), doc->getDimensions()); } else { Geom::OptRect bbox = base->documentVisualBounds(); if (!bbox) { @@ -758,7 +751,7 @@ CairoRenderer::setupDocument(CairoRenderContext *ctx, SPDocument *doc, bool page if (ret) { if (pageBoundingBox) { // translate to set bleed/margin - Geom::Affine tp( Geom::Translate( bleedmargin_px, bleedmargin_px ) ); + Geom::Affine tp(Geom::Translate(bleedmargin_px, bleedmargin_px)); ctx->transform(tp); } else { // this transform translates the export drawing to a virtual page (0,0)-(width,height) @@ -771,10 +764,9 @@ CairoRenderer::setupDocument(CairoRenderContext *ctx, SPDocument *doc, bool page } // Apply an SVG clip path -void -CairoRenderer::applyClipPath(CairoRenderContext *ctx, SPClipPath const *cp) +void CairoRenderer::applyClipPath(CairoRenderContext *ctx, SPClipPath const *cp) { - g_assert( ctx != nullptr && ctx->_is_valid ); + g_assert(ctx != nullptr && ctx->_is_valid); if (cp == nullptr) return; @@ -796,10 +788,9 @@ CairoRenderer::applyClipPath(CairoRenderContext *ctx, SPClipPath const *cp) TRACE(("BEGIN clip\n")); SPObject const *co = cp; - for (auto& child: co->children) { + for (auto &child : co->children) { SPItem const *item = dynamic_cast(&child); if (item) { - // combine transform of the item in clippath and the item using clippath: Geom::Affine tempmat = item->transform * ctx->getCurrentState()->item_transform; @@ -815,8 +806,8 @@ CairoRenderer::applyClipPath(CairoRenderContext *ctx, SPClipPath const *cp) TRACE(("END clip\n")); // do clipping only if this was the first call to applyClipPath - if (ctx->getClipMode() == CairoRenderContext::CLIP_MODE_PATH - && saved_mode == CairoRenderContext::RENDER_MODE_NORMAL) + if (ctx->getClipMode() == CairoRenderContext::CLIP_MODE_PATH && + saved_mode == CairoRenderContext::RENDER_MODE_NORMAL) cairo_clip(ctx->_cr); if (cp->clipPathUnits == SP_CONTENT_UNITS_OBJECTBOUNDINGBOX) @@ -826,10 +817,9 @@ CairoRenderer::applyClipPath(CairoRenderContext *ctx, SPClipPath const *cp) } // Apply an SVG mask -void -CairoRenderer::applyMask(CairoRenderContext *ctx, SPMask const *mask) +void CairoRenderer::applyMask(CairoRenderContext *ctx, SPMask const *mask) { - g_assert( ctx != nullptr && ctx->_is_valid ); + g_assert(ctx != nullptr && ctx->_is_valid); if (mask == nullptr) return; @@ -854,11 +844,11 @@ CairoRenderer::applyMask(CairoRenderContext *ctx, SPMask const *mask) TRACE(("BEGIN mask\n")); SPObject const *co = mask; - for (auto& child: co->children) { + for (auto &child : co->children) { SPItem const *item = dynamic_cast(&child); if (item) { // TODO fix const correctness: - renderItem(ctx, const_cast(item)); + renderItem(ctx, const_cast(item)); } } TRACE(("END mask\n")); @@ -866,9 +856,8 @@ CairoRenderer::applyMask(CairoRenderContext *ctx, SPMask const *mask) ctx->popState(); } -void -calculatePreserveAspectRatio(unsigned int aspect_align, unsigned int aspect_clip, double vp_width, double vp_height, - double *x, double *y, double *width, double *height) +void calculatePreserveAspectRatio(unsigned int aspect_align, unsigned int aspect_clip, double vp_width, + double vp_height, double *x, double *y, double *width, double *height) { if (aspect_align == SP_ASPECT_NONE) return; @@ -921,13 +910,12 @@ calculatePreserveAspectRatio(unsigned int aspect_align, unsigned int aspect_clip #include "clear-n_.h" -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ #undef TRACE - /* Local Variables: mode:c++ diff --git a/src/extension/internal/cairo-renderer.h b/src/extension/internal/cairo-renderer.h index 26f2f414ac21afc7205038ff0b5a3540bbe69eca..6db9e65f59439004885938d0b3f7d16a36c25da7 100644 --- a/src/extension/internal/cairo-renderer.h +++ b/src/extension/internal/cairo-renderer.h @@ -15,10 +15,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/extension.h" #include #include +#include "extension/extension.h" + //#include "libnrtype/font-instance.h" #include @@ -34,7 +35,8 @@ namespace Internal { class CairoRenderer; class CairoRenderContext; -class CairoRenderer { +class CairoRenderer +{ public: CairoRenderer(); virtual ~CairoRenderer(); @@ -50,7 +52,8 @@ public: /** Initializes the CairoRenderContext according to the specified SPDocument. A set*Target function can only be called on the context before setupDocument. */ - bool setupDocument(CairoRenderContext *ctx, SPDocument *doc, bool pageBoundingBox, float bleedmargin_px, SPItem *base); + bool setupDocument(CairoRenderContext *ctx, SPDocument *doc, bool pageBoundingBox, float bleedmargin_px, + SPItem *base); /** Traverses the object tree and invokes the render methods. */ void renderItem(CairoRenderContext *ctx, SPItem *item); @@ -65,9 +68,9 @@ private: void calculatePreserveAspectRatio(unsigned int aspect_align, unsigned int aspect_clip, double vp_width, double vp_height, double *x, double *y, double *width, double *height); -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* !EXTENSION_INTERNAL_CAIRO_RENDERER_H_SEEN */ diff --git a/src/extension/internal/cdr-input.cpp b/src/extension/internal/cdr-input.cpp index b1bb33be044f70640ba495529fb341a01023a314..288bb69bc2b22e8b53192e2106f4a8b3286ca2f2 100644 --- a/src/extension/internal/cdr-input.cpp +++ b/src/extension/internal/cdr-input.cpp @@ -15,7 +15,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include @@ -24,79 +24,73 @@ #ifdef WITH_LIBCDR -#include #include - #include +#include // TODO: Drop this check when librevenge is widespread. #if WITH_LIBCDR01 - #include +#include - using librevenge::RVNGString; - using librevenge::RVNGFileStream; - using librevenge::RVNGStringVector; +using librevenge::RVNGFileStream; +using librevenge::RVNGString; +using librevenge::RVNGStringVector; #else - #include +#include - typedef WPXString RVNGString; - typedef WPXFileStream RVNGFileStream; - typedef libcdr::CDRStringVector RVNGStringVector; +typedef WPXString RVNGString; +typedef WPXFileStream RVNGFileStream; +typedef libcdr::CDRStringVector RVNGStringVector; #endif +#include #include #include -#include "extension/system.h" -#include "extension/input.h" - #include "document.h" +#include "extension/input.h" +#include "extension/system.h" #include "inkscape.h" - +#include "object/sp-root.h" #include "ui/dialog-events.h" -#include - #include "ui/view/svg-view-widget.h" - -#include "object/sp-root.h" - #include "util/units.h" namespace Inkscape { namespace Extension { namespace Internal { - -class CdrImportDialog : public Gtk::Dialog { +class CdrImportDialog : public Gtk::Dialog +{ public: - CdrImportDialog(const std::vector &vec); - ~CdrImportDialog() override; + CdrImportDialog(const std::vector &vec); + ~CdrImportDialog() override; - bool showDialog(); - unsigned getSelectedPage(); - void getImportSettings(Inkscape::XML::Node *prefs); + bool showDialog(); + unsigned getSelectedPage(); + void getImportSettings(Inkscape::XML::Node *prefs); private: - void _setPreviewPage(); - - // Signal handlers - void _onPageNumberChanged(); - void _onSpinButtonPress(GdkEventButton* button_event); - void _onSpinButtonRelease(GdkEventButton* button_event); - - class Gtk::VBox * vbox1; - class Inkscape::UI::View::SVGViewWidget * _previewArea; - class Gtk::Button * cancelbutton; - class Gtk::Button * okbutton; - - class Gtk::HBox * _page_selector_box; - class Gtk::Label * _labelSelect; - class Gtk::Label * _labelTotalPages; - class Gtk::SpinButton * _pageNumberSpin; - - const std::vector &_vec; // Document to be imported - unsigned _current_page; // Current selected page - bool _spinning; // whether SpinButton is pressed (i.e. we're "spinning") + void _setPreviewPage(); + + // Signal handlers + void _onPageNumberChanged(); + void _onSpinButtonPress(GdkEventButton *button_event); + void _onSpinButtonRelease(GdkEventButton *button_event); + + class Gtk::VBox *vbox1; + class Inkscape::UI::View::SVGViewWidget *_previewArea; + class Gtk::Button *cancelbutton; + class Gtk::Button *okbutton; + + class Gtk::HBox *_page_selector_box; + class Gtk::Label *_labelSelect; + class Gtk::Label *_labelTotalPages; + class Gtk::SpinButton *_pageNumberSpin; + + const std::vector &_vec; // Document to be imported + unsigned _current_page; // Current selected page + bool _spinning; // whether SpinButton is pressed (i.e. we're "spinning") }; CdrImportDialog::CdrImportDialog(const std::vector &vec) @@ -105,104 +99,106 @@ CdrImportDialog::CdrImportDialog(const std::vector &vec) , _current_page(1) , _spinning(false) { - int num_pages = _vec.size(); - if ( num_pages <= 1 ) - return; - - // Dialog settings - this->set_title(_("Page Selector")); - this->set_modal(true); - sp_transientize(GTK_WIDGET(this->gobj())); //Make transient - this->property_window_position().set_value(Gtk::WIN_POS_NONE); - this->set_resizable(true); - this->property_destroy_with_parent().set_value(false); - - // Preview area - vbox1 = Gtk::manage(new class Gtk::VBox()); - this->get_content_area()->pack_start(*vbox1); - - // CONTROLS - _page_selector_box = Gtk::manage(new Gtk::HBox()); - - // "Select page:" label - _labelSelect = Gtk::manage(new class Gtk::Label(_("Select page:"))); - _labelTotalPages = Gtk::manage(new class Gtk::Label()); - _labelSelect->set_line_wrap(false); - _labelSelect->set_use_markup(false); - _labelSelect->set_selectable(false); - _page_selector_box->pack_start(*_labelSelect, Gtk::PACK_SHRINK); - - // Adjustment + spinner - auto pageNumberSpin_adj = Gtk::Adjustment::create(1, 1, _vec.size(), 1, 10, 0); - _pageNumberSpin = Gtk::manage(new Gtk::SpinButton(pageNumberSpin_adj, 1, 0)); - _pageNumberSpin->set_can_focus(); - _pageNumberSpin->set_update_policy(Gtk::UPDATE_ALWAYS); - _pageNumberSpin->set_numeric(true); - _pageNumberSpin->set_wrap(false); - _page_selector_box->pack_start(*_pageNumberSpin, Gtk::PACK_SHRINK); - - _labelTotalPages->set_line_wrap(false); - _labelTotalPages->set_use_markup(false); - _labelTotalPages->set_selectable(false); - gchar *label_text = g_strdup_printf(_("out of %i"), num_pages); - _labelTotalPages->set_label(label_text); - g_free(label_text); - _page_selector_box->pack_start(*_labelTotalPages, Gtk::PACK_SHRINK); - - vbox1->pack_end(*_page_selector_box, Gtk::PACK_SHRINK); - - // Buttons - cancelbutton = Gtk::manage(new Gtk::Button(_("_Cancel"), true)); - okbutton = Gtk::manage(new Gtk::Button(_("_OK"), true)); - this->add_action_widget(*cancelbutton, Gtk::RESPONSE_CANCEL); - this->add_action_widget(*okbutton, Gtk::RESPONSE_OK); - - // Show all widgets in dialog - this->show_all(); - - // Connect signals - _pageNumberSpin->signal_value_changed().connect(sigc::mem_fun(*this, &CdrImportDialog::_onPageNumberChanged)); - _pageNumberSpin->signal_button_press_event().connect_notify(sigc::mem_fun(*this, &CdrImportDialog::_onSpinButtonPress)); - _pageNumberSpin->signal_button_release_event().connect_notify(sigc::mem_fun(*this, &CdrImportDialog::_onSpinButtonRelease)); - - _setPreviewPage(); + int num_pages = _vec.size(); + if (num_pages <= 1) + return; + + // Dialog settings + this->set_title(_("Page Selector")); + this->set_modal(true); + sp_transientize(GTK_WIDGET(this->gobj())); // Make transient + this->property_window_position().set_value(Gtk::WIN_POS_NONE); + this->set_resizable(true); + this->property_destroy_with_parent().set_value(false); + + // Preview area + vbox1 = Gtk::manage(new class Gtk::VBox()); + this->get_content_area()->pack_start(*vbox1); + + // CONTROLS + _page_selector_box = Gtk::manage(new Gtk::HBox()); + + // "Select page:" label + _labelSelect = Gtk::manage(new class Gtk::Label(_("Select page:"))); + _labelTotalPages = Gtk::manage(new class Gtk::Label()); + _labelSelect->set_line_wrap(false); + _labelSelect->set_use_markup(false); + _labelSelect->set_selectable(false); + _page_selector_box->pack_start(*_labelSelect, Gtk::PACK_SHRINK); + + // Adjustment + spinner + auto pageNumberSpin_adj = Gtk::Adjustment::create(1, 1, _vec.size(), 1, 10, 0); + _pageNumberSpin = Gtk::manage(new Gtk::SpinButton(pageNumberSpin_adj, 1, 0)); + _pageNumberSpin->set_can_focus(); + _pageNumberSpin->set_update_policy(Gtk::UPDATE_ALWAYS); + _pageNumberSpin->set_numeric(true); + _pageNumberSpin->set_wrap(false); + _page_selector_box->pack_start(*_pageNumberSpin, Gtk::PACK_SHRINK); + + _labelTotalPages->set_line_wrap(false); + _labelTotalPages->set_use_markup(false); + _labelTotalPages->set_selectable(false); + gchar *label_text = g_strdup_printf(_("out of %i"), num_pages); + _labelTotalPages->set_label(label_text); + g_free(label_text); + _page_selector_box->pack_start(*_labelTotalPages, Gtk::PACK_SHRINK); + + vbox1->pack_end(*_page_selector_box, Gtk::PACK_SHRINK); + + // Buttons + cancelbutton = Gtk::manage(new Gtk::Button(_("_Cancel"), true)); + okbutton = Gtk::manage(new Gtk::Button(_("_OK"), true)); + this->add_action_widget(*cancelbutton, Gtk::RESPONSE_CANCEL); + this->add_action_widget(*okbutton, Gtk::RESPONSE_OK); + + // Show all widgets in dialog + this->show_all(); + + // Connect signals + _pageNumberSpin->signal_value_changed().connect(sigc::mem_fun(*this, &CdrImportDialog::_onPageNumberChanged)); + _pageNumberSpin->signal_button_press_event().connect_notify( + sigc::mem_fun(*this, &CdrImportDialog::_onSpinButtonPress)); + _pageNumberSpin->signal_button_release_event().connect_notify( + sigc::mem_fun(*this, &CdrImportDialog::_onSpinButtonRelease)); + + _setPreviewPage(); } CdrImportDialog::~CdrImportDialog() = default; bool CdrImportDialog::showDialog() { - show(); - gint b = run(); - hide(); - if (b == Gtk::RESPONSE_OK || b == Gtk::RESPONSE_ACCEPT) { - return TRUE; - } else { - return FALSE; - } + show(); + gint b = run(); + hide(); + if (b == Gtk::RESPONSE_OK || b == Gtk::RESPONSE_ACCEPT) { + return TRUE; + } else { + return FALSE; + } } unsigned CdrImportDialog::getSelectedPage() { - return _current_page; + return _current_page; } void CdrImportDialog::_onPageNumberChanged() { - unsigned page = static_cast(_pageNumberSpin->get_value_as_int()); - _current_page = CLAMP(page, 1U, _vec.size()); - _setPreviewPage(); + unsigned page = static_cast(_pageNumberSpin->get_value_as_int()); + _current_page = CLAMP(page, 1U, _vec.size()); + _setPreviewPage(); } -void CdrImportDialog::_onSpinButtonPress(GdkEventButton* /*button_event*/) +void CdrImportDialog::_onSpinButtonPress(GdkEventButton * /*button_event*/) { - _spinning = true; + _spinning = true; } -void CdrImportDialog::_onSpinButtonRelease(GdkEventButton* /*button_event*/) +void CdrImportDialog::_onSpinButtonRelease(GdkEventButton * /*button_event*/) { - _spinning = false; - _setPreviewPage(); + _spinning = false; + _setPreviewPage(); } /** @@ -214,8 +210,9 @@ void CdrImportDialog::_setPreviewPage() return; } - SPDocument *doc = SPDocument::createNewDocFromMem(_vec[_current_page-1].cstr(), strlen(_vec[_current_page-1].cstr()), false); - if(!doc) { + SPDocument *doc = + SPDocument::createNewDocFromMem(_vec[_current_page - 1].cstr(), strlen(_vec[_current_page - 1].cstr()), false); + if (!doc) { g_warning("CDR import: Could not create preview for page %d", _current_page); gchar const *no_preview_template = R"A( @@ -224,7 +221,7 @@ void CdrImportDialog::_setPreviewPage() %s )A"; - gchar * no_preview = g_strdup_printf(no_preview_template, _("No preview")); + gchar *no_preview = g_strdup_printf(no_preview_template, _("No preview")); doc = SPDocument::createNewDocFromMem(no_preview, strlen(no_preview), false); g_free(no_preview); } @@ -245,75 +242,78 @@ void CdrImportDialog::_setPreviewPage() _previewArea->show_all(); } -SPDocument *CdrInput::open(Inkscape::Extension::Input * /*mod*/, const gchar * uri) +SPDocument *CdrInput::open(Inkscape::Extension::Input * /*mod*/, const gchar *uri) { - #ifdef _WIN32 - // RVNGFileStream uses fopen() internally which unfortunately only uses ANSI encoding on Windows - // therefore attempt to convert uri to the system codepage - // even if this is not possible the alternate short (8.3) file name will be used if available - gchar * converted_uri = g_win32_locale_filename_from_utf8(uri); - RVNGFileStream input(converted_uri); - g_free(converted_uri); - #else - RVNGFileStream input(uri); - #endif - - if (!libcdr::CDRDocument::isSupported(&input)) { - return nullptr; - } - - RVNGStringVector output; +#ifdef _WIN32 + // RVNGFileStream uses fopen() internally which unfortunately only uses ANSI encoding on Windows + // therefore attempt to convert uri to the system codepage + // even if this is not possible the alternate short (8.3) file name will be used if available + gchar *converted_uri = g_win32_locale_filename_from_utf8(uri); + RVNGFileStream input(converted_uri); + g_free(converted_uri); +#else + RVNGFileStream input(uri); +#endif + + if (!libcdr::CDRDocument::isSupported(&input)) { + return nullptr; + } + + RVNGStringVector output; #if WITH_LIBCDR01 - librevenge::RVNGSVGDrawingGenerator generator(output, "svg"); + librevenge::RVNGSVGDrawingGenerator generator(output, "svg"); - if (!libcdr::CDRDocument::parse(&input, &generator)) { + if (!libcdr::CDRDocument::parse(&input, &generator)) { #else - if (!libcdr::CDRDocument::generateSVG(&input, output)) { + if (!libcdr::CDRDocument::generateSVG(&input, output)) { #endif - return nullptr; - } - - if (output.empty()) { - return nullptr; - } - - std::vector tmpSVGOutput; - for (unsigned i=0; i\n\n"); - tmpString.append(output[i]); - tmpSVGOutput.push_back(tmpString); - } - - unsigned page_num = 1; - - // If only one page is present, import that one without bothering user - if (tmpSVGOutput.size() > 1) { - CdrImportDialog *dlg = nullptr; - if (INKSCAPE.use_gui()) { - dlg = new CdrImportDialog(tmpSVGOutput); - if (!dlg->showDialog()) { - delete dlg; - throw Input::open_cancelled(); - } - } - - // Get needed page - if (dlg) { - page_num = dlg->getSelectedPage(); - if (page_num < 1) - page_num = 1; - if (page_num > tmpSVGOutput.size()) - page_num = tmpSVGOutput.size(); - } - } - - SPDocument * doc = SPDocument::createNewDocFromMem(tmpSVGOutput[page_num-1].cstr(), strlen(tmpSVGOutput[page_num-1].cstr()), TRUE); - - // Set viewBox if it doesn't exist - if (doc && !doc->getRoot()->viewBox_set) { - doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), doc->getHeight().value(doc->getDisplayUnit()))); - } - return doc; + return nullptr; + } + + if (output.empty()) { + return nullptr; + } + + std::vector tmpSVGOutput; + for (unsigned i = 0; i < output.size(); ++i) { + RVNGString tmpString("\n\n"); + tmpString.append(output[i]); + tmpSVGOutput.push_back(tmpString); + } + + unsigned page_num = 1; + + // If only one page is present, import that one without bothering user + if (tmpSVGOutput.size() > 1) { + CdrImportDialog *dlg = nullptr; + if (INKSCAPE.use_gui()) { + dlg = new CdrImportDialog(tmpSVGOutput); + if (!dlg->showDialog()) { + delete dlg; + throw Input::open_cancelled(); + } + } + + // Get needed page + if (dlg) { + page_num = dlg->getSelectedPage(); + if (page_num < 1) + page_num = 1; + if (page_num > tmpSVGOutput.size()) + page_num = tmpSVGOutput.size(); + } + } + + SPDocument *doc = SPDocument::createNewDocFromMem(tmpSVGOutput[page_num - 1].cstr(), + strlen(tmpSVGOutput[page_num - 1].cstr()), TRUE); + + // Set viewBox if it doesn't exist + if (doc && !doc->getRoot()->viewBox_set) { + doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), + doc->getHeight().value(doc->getDisplayUnit()))); + } + return doc; } #include "clear-n_.h" @@ -374,11 +374,13 @@ void CdrInput::init() "", new CdrInput()); // clang-format on - return; + return; } // init -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* WITH_LIBCDR */ /* diff --git a/src/extension/internal/cdr-input.h b/src/extension/internal/cdr-input.h index 546151fac0b4e045a7c6586b1d768e098c3acfdb..08628f23245b2d53bfe74e9b8f91a0d98753858f 100644 --- a/src/extension/internal/cdr-input.h +++ b/src/extension/internal/cdr-input.h @@ -15,7 +15,7 @@ #define __EXTENSION_INTERNAL_CDROUTPUT_H__ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef WITH_LIBCDR @@ -28,21 +28,23 @@ namespace Inkscape { namespace Extension { namespace Internal { -class CdrInput : public Inkscape::Extension::Implementation::Implementation { - CdrInput () = default;; -public: - SPDocument *open( Inkscape::Extension::Input *mod, - const gchar *uri ) override; - static void init( ); +class CdrInput : public Inkscape::Extension::Implementation::Implementation +{ + CdrInput() = default; + ; +public: + SPDocument *open(Inkscape::Extension::Input *mod, const gchar *uri) override; + static void init(); }; -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* WITH_LIBCDR */ #endif /* __EXTENSION_INTERNAL_CDROUTPUT_H__ */ - /* Local Variables: mode:c++ diff --git a/src/extension/internal/emf-inout.cpp b/src/extension/internal/emf-inout.cpp index ecfe7dac6559a46b9c6fe2dae5bbcdb3e2c85b2c..aaae99dfe1d95f371cddaeb502b57020b36fb38b 100644 --- a/src/extension/internal/emf-inout.cpp +++ b/src/extension/internal/emf-inout.cpp @@ -23,17 +23,18 @@ * http://msdn.microsoft.com/library/en-us/gdi/metafile_5hkj.asp */ +#include "emf-inout.h" + +#include <3rdparty/libuemf/symbol_convert.h> +#include #include #include -#include -#include <3rdparty/libuemf/symbol_convert.h> - -#include "emf-inout.h" #include "clear-n_.h" #include "display/drawing-item.h" #include "display/drawing.h" #include "document.h" +#include "emf-print.h" #include "extension/db.h" #include "extension/input.h" #include "extension/output.h" @@ -47,45 +48,38 @@ #include "svg/svg.h" #include "util/units.h" -#include "emf-print.h" - #define PRINT_EMF "org.inkscape.print.emf" #ifndef U_PS_JOIN_MASK -#define U_PS_JOIN_MASK (U_PS_JOIN_BEVEL|U_PS_JOIN_MITER|U_PS_JOIN_ROUND) +#define U_PS_JOIN_MASK (U_PS_JOIN_BEVEL | U_PS_JOIN_MITER | U_PS_JOIN_ROUND) #endif namespace Inkscape { namespace Extension { namespace Internal { -static uint32_t ICMmode = 0; // not used yet, but code to read it from EMF implemented +static uint32_t ICMmode = 0; // not used yet, but code to read it from EMF implemented static uint32_t BLTmode = 0; -float faraway = 10000000; // used in "exclude" clips, hopefully well outside any real drawing! +float faraway = 10000000; // used in "exclude" clips, hopefully well outside any real drawing! -Emf::Emf () // The null constructor +Emf::Emf() // The null constructor { return; } - -Emf::~Emf () //The destructor +Emf::~Emf() // The destructor { return; } - -bool -Emf::check (Inkscape::Extension::Extension * /*module*/) +bool Emf::check(Inkscape::Extension::Extension * /*module*/) { if (nullptr == Inkscape::Extension::db.get(PRINT_EMF)) return FALSE; return TRUE; } - -void -Emf::print_document_to_file(SPDocument *doc, const gchar *filename) +void Emf::print_document_to_file(SPDocument *doc, const gchar *filename) { Inkscape::Extension::Print *mod; SPPrintContext context; @@ -100,7 +94,7 @@ Emf::print_document_to_file(SPDocument *doc, const gchar *filename) oldoutput = g_strdup(oldconst); mod->set_param_string("destination", filename); -/* Start */ + /* Start */ context.module = mod; /* fixme: This has to go into module constructor somehow */ /* Create new arena */ @@ -116,12 +110,12 @@ Emf::print_document_to_file(SPDocument *doc, const gchar *filename) throw Inkscape::Extension::Output::save_failed(); } mod->base->invoke_print(&context); - (void) mod->finish(); + (void)mod->finish(); /* Release arena */ mod->base->invoke_hide(mod->dkey); mod->base = nullptr; mod->root = nullptr; // deleted by invoke_hide -/* end */ + /* end */ mod->set_param_string("destination", oldoutput); g_free(oldoutput); @@ -129,38 +123,35 @@ Emf::print_document_to_file(SPDocument *doc, const gchar *filename) return; } - -void -Emf::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) +void Emf::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) { - Inkscape::Extension::Extension * ext; + Inkscape::Extension::Extension *ext; ext = Inkscape::Extension::db.get(PRINT_EMF); if (ext == nullptr) return; - bool new_val = mod->get_param_bool("textToPath"); - bool new_FixPPTCharPos = mod->get_param_bool("FixPPTCharPos"); // character position bug + bool new_val = mod->get_param_bool("textToPath"); + bool new_FixPPTCharPos = mod->get_param_bool("FixPPTCharPos"); // character position bug // reserve FixPPT2 for opacity bug. Currently EMF does not export opacity values - bool new_FixPPTDashLine = mod->get_param_bool("FixPPTDashLine"); // dashed line bug - bool new_FixPPTGrad2Polys = mod->get_param_bool("FixPPTGrad2Polys"); // gradient bug - bool new_FixPPTLinGrad = mod->get_param_bool("FixPPTLinGrad"); // allow native rectangular linear gradient - bool new_FixPPTPatternAsHatch = mod->get_param_bool("FixPPTPatternAsHatch"); // force all patterns as standard EMF hatch - bool new_FixImageRot = mod->get_param_bool("FixImageRot"); // remove rotations on images - - TableGen( //possibly regenerate the unicode-convert tables - mod->get_param_bool("TnrToSymbol"), - mod->get_param_bool("TnrToWingdings"), - mod->get_param_bool("TnrToZapfDingbats"), - mod->get_param_bool("UsePUA") - ); - - ext->set_param_bool("FixPPTCharPos",new_FixPPTCharPos); // Remember to add any new ones to PrintEmf::init or a mysterious failure will result! - ext->set_param_bool("FixPPTDashLine",new_FixPPTDashLine); - ext->set_param_bool("FixPPTGrad2Polys",new_FixPPTGrad2Polys); - ext->set_param_bool("FixPPTLinGrad",new_FixPPTLinGrad); - ext->set_param_bool("FixPPTPatternAsHatch",new_FixPPTPatternAsHatch); - ext->set_param_bool("FixImageRot",new_FixImageRot); + bool new_FixPPTDashLine = mod->get_param_bool("FixPPTDashLine"); // dashed line bug + bool new_FixPPTGrad2Polys = mod->get_param_bool("FixPPTGrad2Polys"); // gradient bug + bool new_FixPPTLinGrad = mod->get_param_bool("FixPPTLinGrad"); // allow native rectangular linear gradient + bool new_FixPPTPatternAsHatch = + mod->get_param_bool("FixPPTPatternAsHatch"); // force all patterns as standard EMF hatch + bool new_FixImageRot = mod->get_param_bool("FixImageRot"); // remove rotations on images + + TableGen( // possibly regenerate the unicode-convert tables + mod->get_param_bool("TnrToSymbol"), mod->get_param_bool("TnrToWingdings"), + mod->get_param_bool("TnrToZapfDingbats"), mod->get_param_bool("UsePUA")); + + ext->set_param_bool("FixPPTCharPos", new_FixPPTCharPos); // Remember to add any new ones to PrintEmf::init or a + // mysterious failure will result! + ext->set_param_bool("FixPPTDashLine", new_FixPPTDashLine); + ext->set_param_bool("FixPPTGrad2Polys", new_FixPPTGrad2Polys); + ext->set_param_bool("FixPPTLinGrad", new_FixPPTLinGrad); + ext->set_param_bool("FixPPTPatternAsHatch", new_FixPPTPatternAsHatch); + ext->set_param_bool("FixImageRot", new_FixImageRot); ext->set_param_bool("textToPath", new_val); // ensure usage of dot as decimal separator in scanf/printf functions (independently of current locale) @@ -176,73 +167,83 @@ Emf::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filena return; } - /* given the transformation matrix from worldTransform return the scale in the matrix part. Assumes that the matrix is not used to skew, invert, or make another distorting transformation. */ -double Emf::current_scale(PEMF_CALLBACK_DATA d){ - double scale = - d->dc[d->level].worldTransform.eM11 * d->dc[d->level].worldTransform.eM22 - - d->dc[d->level].worldTransform.eM12 * d->dc[d->level].worldTransform.eM21; - if(scale <= 0.0)scale=1.0; /* something is dreadfully wrong with the matrix, but do not crash over it */ - scale=sqrt(scale); - return(scale); +double Emf::current_scale(PEMF_CALLBACK_DATA d) +{ + double scale = d->dc[d->level].worldTransform.eM11 * d->dc[d->level].worldTransform.eM22 - + d->dc[d->level].worldTransform.eM12 * d->dc[d->level].worldTransform.eM21; + if (scale <= 0.0) + scale = 1.0; /* something is dreadfully wrong with the matrix, but do not crash over it */ + scale = sqrt(scale); + return (scale); } /* given the transformation matrix from worldTransform and the current x,y position in inkscape coordinates, - generate an SVG transform that gives the same amount of rotation, no scaling, and maps x,y back onto x,y. This is used for - rotating objects when the location of at least one point in that object is known. Returns: + generate an SVG transform that gives the same amount of rotation, no scaling, and maps x,y back onto x,y. This is + used for rotating objects when the location of at least one point in that object is known. Returns: "matrix(a,b,c,d,e,f)" (WITH the double quotes) */ -std::string Emf::current_matrix(PEMF_CALLBACK_DATA d, double x, double y, int useoffset){ +std::string Emf::current_matrix(PEMF_CALLBACK_DATA d, double x, double y, int useoffset) +{ SVGOStringStream cxform; double scale = current_scale(d); cxform << "\"matrix("; - cxform << d->dc[d->level].worldTransform.eM11/scale; cxform << ","; - cxform << d->dc[d->level].worldTransform.eM12/scale; cxform << ","; - cxform << d->dc[d->level].worldTransform.eM21/scale; cxform << ","; - cxform << d->dc[d->level].worldTransform.eM22/scale; cxform << ","; - if(useoffset){ + cxform << d->dc[d->level].worldTransform.eM11 / scale; + cxform << ","; + cxform << d->dc[d->level].worldTransform.eM12 / scale; + cxform << ","; + cxform << d->dc[d->level].worldTransform.eM21 / scale; + cxform << ","; + cxform << d->dc[d->level].worldTransform.eM22 / scale; + cxform << ","; + if (useoffset) { /* for the "new" coordinates drop the worldtransform translations, not used here */ - double newx = x * d->dc[d->level].worldTransform.eM11/scale + y * d->dc[d->level].worldTransform.eM21/scale; - double newy = x * d->dc[d->level].worldTransform.eM12/scale + y * d->dc[d->level].worldTransform.eM22/scale; - cxform << x - newx; cxform << ","; + double newx = x * d->dc[d->level].worldTransform.eM11 / scale + y * d->dc[d->level].worldTransform.eM21 / scale; + double newy = x * d->dc[d->level].worldTransform.eM12 / scale + y * d->dc[d->level].worldTransform.eM22 / scale; + cxform << x - newx; + cxform << ","; cxform << y - newy; - } - else { + } else { cxform << "0,0"; } cxform << ")\""; - return(cxform.str()); + return (cxform.str()); } /* given the transformation matrix from worldTransform return the rotation angle in radians. counter clockwise from the x axis. */ -double Emf::current_rotation(PEMF_CALLBACK_DATA d){ +double Emf::current_rotation(PEMF_CALLBACK_DATA d) +{ return -std::atan2(d->dc[d->level].worldTransform.eM12, d->dc[d->level].worldTransform.eM11); } /* Add another 100 blank slots to the hatches array. -*/ -void Emf::enlarge_hatches(PEMF_CALLBACK_DATA d){ + */ +void Emf::enlarge_hatches(PEMF_CALLBACK_DATA d) +{ d->hatches.size += 100; - d->hatches.strings = (char **) realloc(d->hatches.strings,d->hatches.size * sizeof(char *)); + d->hatches.strings = (char **)realloc(d->hatches.strings, d->hatches.size * sizeof(char *)); } /* See if the pattern name is already in the list. If it is return its position (1->n, not 1-n-1) -*/ -int Emf::in_hatches(PEMF_CALLBACK_DATA d, char *test){ + */ +int Emf::in_hatches(PEMF_CALLBACK_DATA d, char *test) +{ int i; - for(i=0; ihatches.count; i++){ - if(strcmp(test,d->hatches.strings[i])==0)return(i+1); + for (i = 0; i < d->hatches.count; i++) { + if (strcmp(test, d->hatches.strings[i]) == 0) + return (i + 1); } - return(0); + return (0); } /* (Conditionally) add a hatch. If a matching hatch already exists nothing happens. If one does not exist it is added to the hatches list and also entered into . This is also used to add the path part of the hatches, which they reference with a xlink:href */ -uint32_t Emf::add_hatch(PEMF_CALLBACK_DATA d, uint32_t hatchType, U_COLORREF hatchColor){ +uint32_t Emf::add_hatch(PEMF_CALLBACK_DATA d, uint32_t hatchType, U_COLORREF hatchColor) +{ char hatchname[64]; // big enough char hpathname[64]; // big enough char hbkname[64]; // big enough @@ -250,17 +251,17 @@ uint32_t Emf::add_hatch(PEMF_CALLBACK_DATA d, uint32_t hatchType, U_COLORREF hat char bkcolor[8]; uint32_t idx; - switch(hatchType){ + switch (hatchType) { case U_HS_SOLIDTEXTCLR: case U_HS_DITHEREDTEXTCLR: - sprintf(tmpcolor,"%6.6X",sethexcolor(d->dc[d->level].textColor)); + sprintf(tmpcolor, "%6.6X", sethexcolor(d->dc[d->level].textColor)); break; case U_HS_SOLIDBKCLR: case U_HS_DITHEREDBKCLR: - sprintf(tmpcolor,"%6.6X",sethexcolor(d->dc[d->level].bkColor)); + sprintf(tmpcolor, "%6.6X", sethexcolor(d->dc[d->level].bkColor)); break; default: - sprintf(tmpcolor,"%6.6X",sethexcolor(hatchColor)); + sprintf(tmpcolor, "%6.6X", sethexcolor(hatchColor)); break; } @@ -268,15 +269,17 @@ uint32_t Emf::add_hatch(PEMF_CALLBACK_DATA d, uint32_t hatchType, U_COLORREF hat This will be used late to compose, or recompose the transparent or opaque final hatch.*/ std::string refpath; // used to reference later the path pieces which are about to be created - sprintf(hpathname,"EMFhpath%d_%s",hatchType,tmpcolor); - idx = in_hatches(d,hpathname); - auto & defs = d->defs; - if(!idx){ // add path/color if not already present - if(d->hatches.count == d->hatches.size){ enlarge_hatches(d); } - d->hatches.strings[d->hatches.count++]=strdup(hpathname); + sprintf(hpathname, "EMFhpath%d_%s", hatchType, tmpcolor); + idx = in_hatches(d, hpathname); + auto &defs = d->defs; + if (!idx) { // add path/color if not already present + if (d->hatches.count == d->hatches.size) { + enlarge_hatches(d); + } + d->hatches.strings[d->hatches.count++] = strdup(hpathname); defs += "\n"; - switch(hatchType){ + switch (hatchType) { case U_HS_HORIZONTAL: defs += " \n"; - break; + break; case U_HS_DIAGCROSS: defs += " \n"; + refpath += " \n"; break; case U_HS_FDIAGONAL: case U_HS_BDIAGONAL: - refpath += " \n"; - refpath += " \n"; - refpath += " \n"; + refpath += " \n"; + refpath += " \n"; + refpath += " \n"; break; case U_HS_DIAGCROSS: - refpath += " \n"; - refpath += " \n"; - refpath += " \n"; - refpath += " \n"; - refpath += " \n"; - refpath += " \n"; - break; - } - - if(d->dc[d->level].bkMode == U_TRANSPARENT || hatchType >= U_HS_SOLIDCLR){ - sprintf(hatchname,"EMFhatch%d_%s",hatchType,tmpcolor); - sprintf(hpathname,"EMFhpath%d_%s",hatchType,tmpcolor); - idx = in_hatches(d,hatchname); - if(!idx){ // add it if not already present - if(d->hatches.count == d->hatches.size){ enlarge_hatches(d); } - d->hatches.strings[d->hatches.count++]=strdup(hatchname); + refpath += " \n"; + refpath += " \n"; + refpath += " \n"; + refpath += " \n"; + refpath += " \n"; + refpath += " \n"; + break; + } + + if (d->dc[d->level].bkMode == U_TRANSPARENT || hatchType >= U_HS_SOLIDCLR) { + sprintf(hatchname, "EMFhatch%d_%s", hatchType, tmpcolor); + sprintf(hpathname, "EMFhpath%d_%s", hatchType, tmpcolor); + idx = in_hatches(d, hatchname); + if (!idx) { // add it if not already present + if (d->hatches.count == d->hatches.size) { + enlarge_hatches(d); + } + d->hatches.strings[d->hatches.count++] = strdup(hatchname); defs += "\n"; defs += " hatches.count; } - } - else { // bkMode==U_OPAQUE + } else { // bkMode==U_OPAQUE /* Set up an object in the defs for this background, if there is not one already there */ - sprintf(bkcolor,"%6.6X",sethexcolor(d->dc[d->level].bkColor)); - sprintf(hbkname,"EMFhbkclr_%s",bkcolor); - idx = in_hatches(d,hbkname); - if(!idx){ // add path/color if not already present. Hatchtype is not needed in the name. - if(d->hatches.count == d->hatches.size){ enlarge_hatches(d); } - d->hatches.strings[d->hatches.count++]=strdup(hbkname); + sprintf(bkcolor, "%6.6X", sethexcolor(d->dc[d->level].bkColor)); + sprintf(hbkname, "EMFhbkclr_%s", bkcolor); + idx = in_hatches(d, hbkname); + if (!idx) { // add path/color if not already present. Hatchtype is not needed in the name. + if (d->hatches.count == d->hatches.size) { + enlarge_hatches(d); + } + d->hatches.strings[d->hatches.count++] = strdup(hbkname); defs += "\n"; defs += " hatches.count == d->hatches.size){ enlarge_hatches(d); } - d->hatches.strings[d->hatches.count++]=strdup(hatchname); + sprintf(hatchname, "EMFhatch%d_%s_%s", hatchType, tmpcolor, bkcolor); + idx = in_hatches(d, hatchname); + if (!idx) { // add it if not already present + if (d->hatches.count == d->hatches.size) { + enlarge_hatches(d); + } + d->hatches.strings[d->hatches.count++] = strdup(hatchname); defs += "\n"; defs += " hatches.count; } } - return(idx-1); + return (idx - 1); } /* Add another 100 blank slots to the images array. -*/ -void Emf::enlarge_images(PEMF_CALLBACK_DATA d){ + */ +void Emf::enlarge_images(PEMF_CALLBACK_DATA d) +{ d->images.size += 100; - d->images.strings = (char **) realloc(d->images.strings,d->images.size * sizeof(char *)); + d->images.strings = (char **)realloc(d->images.strings, d->images.size * sizeof(char *)); } /* See if the image string is already in the list. If it is return its position (1->n, not 1-n-1) -*/ -int Emf::in_images(PEMF_CALLBACK_DATA d, const char *test){ + */ +int Emf::in_images(PEMF_CALLBACK_DATA d, const char *test) +{ int i; - for(i=0; iimages.count; i++){ - if(strcmp(test,d->images.strings[i])==0)return(i+1); + for (i = 0; i < d->images.count; i++) { + if (strcmp(test, d->images.strings[i]) == 0) + return (i + 1); } - return(0); + return (0); } /* (Conditionally) add an image. If a matching image already exists nothing happens. If one @@ -468,84 +479,80 @@ int Emf::in_images(PEMF_CALLBACK_DATA d, const char *test){ U_EMRCREATEMONOBRUSH records only work when the bitmap is monochrome. If we hit one that isn't set idx to 2^32-1 and let the caller handle it. */ -uint32_t Emf::add_image(PEMF_CALLBACK_DATA d, void *pEmr, uint32_t cbBits, uint32_t cbBmi, - uint32_t iUsage, uint32_t offBits, uint32_t offBmi){ - +uint32_t Emf::add_image(PEMF_CALLBACK_DATA d, void *pEmr, uint32_t cbBits, uint32_t cbBmi, uint32_t iUsage, + uint32_t offBits, uint32_t offBmi) +{ uint32_t idx; - char imagename[64]; // big enough - char imrotname[64]; // big enough - char xywh[64]; // big enough - int dibparams = U_BI_UNKNOWN; // type of image not yet determined + char imagename[64]; // big enough + char imrotname[64]; // big enough + char xywh[64]; // big enough + int dibparams = U_BI_UNKNOWN; // type of image not yet determined MEMPNG mempng; // PNG in memory comes back in this mempng.buffer = nullptr; - char *rgba_px = nullptr; // RGBA pixels - const char *px = nullptr; // DIB pixels - const U_RGBQUAD *ct = nullptr; // DIB color table - U_RGBQUAD ct2[2]; + char *rgba_px = nullptr; // RGBA pixels + const char *px = nullptr; // DIB pixels + const U_RGBQUAD *ct = nullptr; // DIB color table + U_RGBQUAD ct2[2]; uint32_t width, height, colortype, numCt, invert; // if needed these values will be set in get_DIB_params - if(cbBits && cbBmi && (iUsage == U_DIB_RGB_COLORS)){ + if (cbBits && cbBmi && (iUsage == U_DIB_RGB_COLORS)) { // next call returns pointers and values, but allocates no memory - dibparams = get_DIB_params((const char *)pEmr, offBits, offBmi, &px, (const U_RGBQUAD **) &ct, - &numCt, &width, &height, &colortype, &invert); - if(dibparams ==U_BI_RGB){ + dibparams = get_DIB_params((const char *)pEmr, offBits, offBmi, &px, (const U_RGBQUAD **)&ct, &numCt, &width, + &height, &colortype, &invert); + if (dibparams == U_BI_RGB) { // U_EMRCREATEMONOBRUSH uses text/bk colors instead of what is in the color map. - if(((PU_EMR)pEmr)->iType == U_EMR_CREATEMONOBRUSH){ - if(numCt==2){ - ct2[0] = U_RGB2BGR(d->dc[d->level].textColor); - ct2[1] = U_RGB2BGR(d->dc[d->level].bkColor); - ct = &ct2[0]; - } - else { // This record is invalid, nothing more to do here, let caller handle it - return(U_EMR_INVALID); + if (((PU_EMR)pEmr)->iType == U_EMR_CREATEMONOBRUSH) { + if (numCt == 2) { + ct2[0] = U_RGB2BGR(d->dc[d->level].textColor); + ct2[1] = U_RGB2BGR(d->dc[d->level].bkColor); + ct = &ct2[0]; + } else { // This record is invalid, nothing more to do here, let caller handle it + return (U_EMR_INVALID); } } - if(!DIB_to_RGBA( - px, // DIB pixel array - ct, // DIB color table - numCt, // DIB color table number of entries - &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. - width, // Width of pixel array in record - height, // Height of pixel array in record - colortype, // DIB BitCount Enumeration - numCt, // Color table used if not 0 - invert // If DIB rows are in opposite order from RGBA rows - )){ - toPNG( // Get the image from the RGBA px into mempng - &mempng, - width, height, // of the SRC bitmap - rgba_px - ); + if (!DIB_to_RGBA(px, // DIB pixel array + ct, // DIB color table + numCt, // DIB color table number of entries + &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. + width, // Width of pixel array in record + height, // Height of pixel array in record + colortype, // DIB BitCount Enumeration + numCt, // Color table used if not 0 + invert // If DIB rows are in opposite order from RGBA rows + )) { + toPNG( // Get the image from the RGBA px into mempng + &mempng, width, height, // of the SRC bitmap + rgba_px); free(rgba_px); } } } - gchar *base64String=nullptr; - if(dibparams == U_BI_JPEG || dibparams==U_BI_PNG){ // image was binary png or jpg in source file - base64String = g_base64_encode((guchar*) px, numCt ); - } - else if(mempng.buffer){ // image was DIB in source file, converted to png in this routine - base64String = g_base64_encode((guchar*) mempng.buffer, mempng.size ); + gchar *base64String = nullptr; + if (dibparams == U_BI_JPEG || dibparams == U_BI_PNG) { // image was binary png or jpg in source file + base64String = g_base64_encode((guchar *)px, numCt); + } else if (mempng.buffer) { // image was DIB in source file, converted to png in this routine + base64String = g_base64_encode((guchar *)mempng.buffer, mempng.size); free(mempng.buffer); - } - else { // unknown or unsupported image type or failed conversion, insert the common bad image picture - width = 3; + } else { // unknown or unsupported image type or failed conversion, insert the common bad image picture + width = 3; height = 4; base64String = bad_image_png(); } - idx = in_images(d, (char *) base64String); - auto & defs = d->defs; - if(!idx){ // add it if not already present - we looked at the actual data for comparison - if(d->images.count == d->images.size){ enlarge_images(d); } + idx = in_images(d, (char *)base64String); + auto &defs = d->defs; + if (!idx) { // add it if not already present - we looked at the actual data for comparison + if (d->images.count == d->images.size) { + enlarge_images(d); + } idx = d->images.count; - d->images.strings[d->images.count++]=strdup(base64String); + d->images.strings[d->images.count++] = strdup(base64String); - sprintf(imagename,"EMFimage%d",idx++); - sprintf(xywh," x=\"0\" y=\"0\" width=\"%d\" height=\"%d\" ",width,height); // reuse this buffer + sprintf(imagename, "EMFimage%d", idx++); + sprintf(xywh, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\" ", width, height); // reuse this buffer defs += "\n"; defs += " = 0.00001 || current_rotation(d) <= -0.00001){ /* some rotation, allow a little rounding error around 0 degrees */ - int tangle = round(current_rotation(d)*1000000.0); - sprintf(imrotname,"EMFrotimage%d_%d",idx-1,tangle); - base64String = g_base64_encode((guchar*) imrotname, strlen(imrotname) ); - idx = in_images(d, (char *) base64String); // scan for this "image" - if(!idx){ - if(d->images.count == d->images.size){ enlarge_images(d); } + if (current_rotation(d) >= 0.00001 || + current_rotation(d) <= -0.00001) { /* some rotation, allow a little rounding error around 0 degrees */ + int tangle = round(current_rotation(d) * 1000000.0); + sprintf(imrotname, "EMFrotimage%d_%d", idx - 1, tangle); + base64String = g_base64_encode((guchar *)imrotname, strlen(imrotname)); + idx = in_images(d, (char *)base64String); // scan for this "image" + if (!idx) { + if (d->images.count == d->images.size) { + enlarge_images(d); + } idx = d->images.count; - d->images.strings[d->images.count++]=strdup(base64String); - sprintf(imrotname,"EMFimage%d",idx++); + d->images.strings[d->images.count++] = strdup(base64String); + sprintf(imrotname, "EMFimage%d", idx++); defs += "\n"; defs += " gradients.size += 100; - d->gradients.strings = (char **) realloc(d->gradients.strings,d->gradients.size * sizeof(char *)); + d->gradients.strings = (char **)realloc(d->gradients.strings, d->gradients.size * sizeof(char *)); } /* See if the gradient name is already in the list. If it is return its position (1->n, not 1-n-1) -*/ -int Emf::in_gradients(PEMF_CALLBACK_DATA d, const char *test){ + */ +int Emf::in_gradients(PEMF_CALLBACK_DATA d, const char *test) +{ int i; - for(i=0; igradients.count; i++){ - if(strcmp(test,d->gradients.strings[i])==0)return(i+1); + for (i = 0; i < d->gradients.count; i++) { + if (strcmp(test, d->gradients.strings[i]) == 0) + return (i + 1); } - return(0); + return (0); } -U_COLORREF trivertex_to_colorref(U_TRIVERTEX tv){ +U_COLORREF trivertex_to_colorref(U_TRIVERTEX tv) +{ U_COLORREF uc; - uc.Red = tv.Red >> 8; - uc.Green = tv.Green >> 8; - uc.Blue = tv.Blue >> 8; - uc.Reserved = tv.Alpha >> 8; // Not used - return(uc); + uc.Red = tv.Red >> 8; + uc.Green = tv.Green >> 8; + uc.Blue = tv.Blue >> 8; + uc.Reserved = tv.Alpha >> 8; // Not used + return (uc); } /* (Conditionally) add a gradient. If a matching gradient already exists nothing happens. If one does not exist it is added to the gradients list and also entered into . Only call this with H or V gradient, not a triangle. */ -uint32_t Emf::add_gradient(PEMF_CALLBACK_DATA d, uint32_t gradientType, U_TRIVERTEX tv1, U_TRIVERTEX tv2){ - char hgradname[64]; // big enough +uint32_t Emf::add_gradient(PEMF_CALLBACK_DATA d, uint32_t gradientType, U_TRIVERTEX tv1, U_TRIVERTEX tv2) +{ + char hgradname[64]; // big enough char tmpcolor1[8]; char tmpcolor2[8]; char gradc; uint32_t idx; - std::string x2,y2; - + std::string x2, y2; + U_COLORREF gradientColor1 = trivertex_to_colorref(tv1); U_COLORREF gradientColor2 = trivertex_to_colorref(tv2); - - sprintf(tmpcolor1,"%6.6X",sethexcolor(gradientColor1)); - sprintf(tmpcolor2,"%6.6X",sethexcolor(gradientColor2)); - switch(gradientType){ + sprintf(tmpcolor1, "%6.6X", sethexcolor(gradientColor1)); + sprintf(tmpcolor2, "%6.6X", sethexcolor(gradientColor2)); + switch (gradientType) { case U_GRADIENT_FILL_RECT_H: - gradc='H'; - x2="100"; - y2="0"; + gradc = 'H'; + x2 = "100"; + y2 = "0"; break; case U_GRADIENT_FILL_RECT_V: - gradc='V'; - x2="0"; - y2="100"; + gradc = 'V'; + x2 = "0"; + y2 = "100"; break; default: // this should never happen, but fill these in to avoid compiler warnings - gradc='!'; - x2="0"; - y2="0"; + gradc = '!'; + x2 = "0"; + y2 = "0"; break; } @@ -683,31 +699,32 @@ uint32_t Emf::add_gradient(PEMF_CALLBACK_DATA d, uint32_t gradientType, U_TRIVER be at some other alignment, and that needs gradienttransform. Set the name using the same sort of hack as for add_image. */ - int tangle = round(current_rotation(d)*1000000.0); - sprintf(hgradname,"LinGrd%c_%s_%s_%d",gradc,tmpcolor1,tmpcolor2,tangle); - - idx = in_gradients(d,hgradname); - if(!idx){ // gradient does not yet exist - if(d->gradients.count == d->gradients.size){ enlarge_gradients(d); } - d->gradients.strings[d->gradients.count++]=strdup(hgradname); + int tangle = round(current_rotation(d) * 1000000.0); + sprintf(hgradname, "LinGrd%c_%s_%s_%d", gradc, tmpcolor1, tmpcolor2, tangle); + + idx = in_gradients(d, hgradname); + if (!idx) { // gradient does not yet exist + if (d->gradients.count == d->gradients.size) { + enlarge_gradients(d); + } + d->gradients.strings[d->gradients.count++] = strdup(hgradname); idx = d->gradients.count; SVGOStringStream stmp; - stmp << " defs += stmp.str().c_str(); } - return(idx-1); + return (idx - 1); } /* Add another 100 blank slots to the clips array. -*/ -void Emf::enlarge_clips(PEMF_CALLBACK_DATA d){ + */ +void Emf::enlarge_clips(PEMF_CALLBACK_DATA d) +{ d->clips.size += 100; - d->clips.strings = (char **) realloc(d->clips.strings,d->clips.size * sizeof(char *)); + d->clips.strings = (char **)realloc(d->clips.strings, d->clips.size * sizeof(char *)); } /* See if the pattern name is already in the list. If it is return its position (1->n, not 1-n-1) -*/ -int Emf::in_clips(PEMF_CALLBACK_DATA d, const char *test){ + */ +int Emf::in_clips(PEMF_CALLBACK_DATA d, const char *test) +{ int i; - for(i=0; iclips.count; i++){ - if(strcmp(test,d->clips.strings[i])==0)return(i+1); + for (i = 0; i < d->clips.count; i++) { + if (strcmp(test, d->clips.strings[i]) == 0) + return (i + 1); } - return(0); + return (0); } -/* (Conditionally) add a clip. - If a matching clip already exists nothing happens +/* (Conditionally) add a clip. + If a matching clip already exists nothing happens If one does exist it is added to the clips list, entered into . */ -void Emf::add_clips(PEMF_CALLBACK_DATA d, const char *clippath, unsigned int logic){ +void Emf::add_clips(PEMF_CALLBACK_DATA d, const char *clippath, unsigned int logic) +{ int op = combine_ops_to_livarot(logic); Geom::PathVector combined_vect; char *combined = nullptr; @@ -754,18 +775,20 @@ void Emf::add_clips(PEMF_CALLBACK_DATA d, const char *clippath, unsigned int log unsigned int real_idx = d->dc[d->level].clip_id - 1; Geom::PathVector old_vect = sp_svg_read_pathv(d->clips.strings[real_idx]); Geom::PathVector new_vect = sp_svg_read_pathv(clippath); - combined_vect = sp_pathvector_boolop(new_vect, old_vect, (bool_op) op , (FillRule) fill_oddEven, (FillRule) fill_oddEven); + combined_vect = + sp_pathvector_boolop(new_vect, old_vect, (bool_op)op, (FillRule)fill_oddEven, (FillRule)fill_oddEven); combined = sp_svg_write_path(combined_vect); - } - else { - combined = strdup(clippath); // COPY operation, erases everything and starts a new one + } else { + combined = strdup(clippath); // COPY operation, erases everything and starts a new one } - uint32_t idx = in_clips(d, combined); - if(!idx){ // add clip if not already present - if(d->clips.count == d->clips.size){ enlarge_clips(d); } - d->clips.strings[d->clips.count++]=strdup(combined); - d->dc[d->level].clip_id = d->clips.count; // one more than the slot where it is actually stored + uint32_t idx = in_clips(d, combined); + if (!idx) { // add clip if not already present + if (d->clips.count == d->clips.size) { + enlarge_clips(d); + } + d->clips.strings[d->clips.count++] = strdup(combined); + d->dc[d->level].clip_id = d->clips.count; // one more than the slot where it is actually stored SVGOStringStream tmp_clippath; tmp_clippath << "\n"; tmp_clippath << "\n"; d->outdef += tmp_clippath.str().c_str(); - } - else { + } else { d->dc[d->level].clip_id = idx; } free(combined); } - - -void -Emf::output_style(PEMF_CALLBACK_DATA d, int iType) +void Emf::output_style(PEMF_CALLBACK_DATA d, int iType) { -// SVGOStringStream tmp_id; + // SVGOStringStream tmp_id; SVGOStringStream tmp_style; char tmp[1024] = {0}; @@ -800,8 +819,8 @@ Emf::output_style(PEMF_CALLBACK_DATA d, int iType) // for U_EMR_BITBLT with no image, try to approximate some of these operations/ // Assume src color is "white" - if(d->dwRop3){ - switch(d->dwRop3){ + if (d->dwRop3) { + switch (d->dwRop3) { case U_PATINVERT: // invert pattern fill_rgb[0] = 1.0 - fill_rgb[0]; fill_rgb[1] = 1.0 - fill_rgb[1]; @@ -812,14 +831,14 @@ Emf::output_style(PEMF_CALLBACK_DATA d, int iType) case U_BLACKNESS: case U_SRCERASE: case U_NOTSRCCOPY: - fill_rgb[0]=fill_rgb[1]=fill_rgb[2]=0.0; + fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 0.0; break; - case U_SRCCOPY: // treat all of these as white + case U_SRCCOPY: // treat all of these as white case U_NOTSRCERASE: case U_WHITENESS: - fill_rgb[0]=fill_rgb[1]=fill_rgb[2]=1.0; + fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 1.0; break; - case U_SRCPAINT: // use the existing color + case U_SRCPAINT: // use the existing color case U_SRCAND: case U_MERGECOPY: case U_MERGEPAINT: @@ -828,28 +847,28 @@ Emf::output_style(PEMF_CALLBACK_DATA d, int iType) default: break; } - d->dwRop3 = 0; // might as well reset it here, it must be set for each BITBLT + d->dwRop3 = 0; // might as well reset it here, it must be set for each BITBLT } // Implement some of these, the ones where the original screen color does not matter. // The options that merge screen and pen colors cannot be done correctly because we // have no way of knowing what color is already on the screen. For those just pass the // pen color through. - switch(d->dwRop2){ + switch (d->dwRop2) { case U_R2_BLACK: - fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 0.0; - stroke_rgb[0]= stroke_rgb[1]= stroke_rgb[2] = 0.0; + fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 0.0; + stroke_rgb[0] = stroke_rgb[1] = stroke_rgb[2] = 0.0; break; case U_R2_NOTMERGEPEN: case U_R2_MASKNOTPEN: break; case U_R2_NOTCOPYPEN: - fill_rgb[0] = 1.0 - fill_rgb[0]; - fill_rgb[1] = 1.0 - fill_rgb[1]; - fill_rgb[2] = 1.0 - fill_rgb[2]; - stroke_rgb[0] = 1.0 - stroke_rgb[0]; - stroke_rgb[1] = 1.0 - stroke_rgb[1]; - stroke_rgb[2] = 1.0 - stroke_rgb[2]; + fill_rgb[0] = 1.0 - fill_rgb[0]; + fill_rgb[1] = 1.0 - fill_rgb[1]; + fill_rgb[2] = 1.0 - fill_rgb[2]; + stroke_rgb[0] = 1.0 - stroke_rgb[0]; + stroke_rgb[1] = 1.0 - stroke_rgb[1]; + stroke_rgb[2] = 1.0 - stroke_rgb[2]; break; case U_R2_MASKPENNOT: case U_R2_NOT: @@ -864,66 +883,49 @@ Emf::output_style(PEMF_CALLBACK_DATA d, int iType) case U_R2_MERGEPEN: break; case U_R2_WHITE: - fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 1.0; - stroke_rgb[0]= stroke_rgb[1]= stroke_rgb[2] = 1.0; + fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 1.0; + stroke_rgb[0] = stroke_rgb[1] = stroke_rgb[2] = 1.0; break; default: break; } - -// tmp_id << "\n\tid=\"" << (d->id++) << "\""; -// d->outsvg += tmp_id.str().c_str(); + // tmp_id << "\n\tid=\"" << (d->id++) << "\""; + // d->outsvg += tmp_id.str().c_str(); d->outsvg += "\n\tstyle=\""; if (iType == U_EMR_STROKEPATH || !d->dc[d->level].fill_set) { tmp_style << "fill:none;"; } else { - switch(d->dc[d->level].fill_mode){ + switch (d->dc[d->level].fill_mode) { // both of these use the url(#) method case DRAW_PATTERN: - snprintf(tmp, 1023, "fill:url(#%s); ",d->hatches.strings[d->dc[d->level].fill_idx]); + snprintf(tmp, 1023, "fill:url(#%s); ", d->hatches.strings[d->dc[d->level].fill_idx]); tmp_style << tmp; break; - case DRAW_IMAGE: - snprintf(tmp, 1023, "fill:url(#EMFimage%d_ref); ",d->dc[d->level].fill_idx); + case DRAW_IMAGE: + snprintf(tmp, 1023, "fill:url(#EMFimage%d_ref); ", d->dc[d->level].fill_idx); tmp_style << tmp; break; case DRAW_LINEAR_GRADIENT: case DRAW_PAINT: - default: // <-- this should never happen, but just in case... - snprintf( - tmp, 1023, - "fill:#%02x%02x%02x;", - SP_COLOR_F_TO_U(fill_rgb[0]), - SP_COLOR_F_TO_U(fill_rgb[1]), - SP_COLOR_F_TO_U(fill_rgb[2]) - ); + default: // <-- this should never happen, but just in case... + snprintf(tmp, 1023, "fill:#%02x%02x%02x;", SP_COLOR_F_TO_U(fill_rgb[0]), SP_COLOR_F_TO_U(fill_rgb[1]), + SP_COLOR_F_TO_U(fill_rgb[2])); tmp_style << tmp; break; } - snprintf( - tmp, 1023, - "fill-rule:%s;", - (d->dc[d->level].style.fill_rule.value == SP_WIND_RULE_NONZERO ? "evenodd" : "nonzero") - ); + snprintf(tmp, 1023, "fill-rule:%s;", + (d->dc[d->level].style.fill_rule.value == SP_WIND_RULE_NONZERO ? "evenodd" : "nonzero")); tmp_style << tmp; tmp_style << "fill-opacity:1;"; - // if the stroke is the same as the fill, and the right size not to change the end size of the object, do not do it separately - if( - (d->dc[d->level].fill_set ) && - (d->dc[d->level].stroke_set ) && - (d->dc[d->level].style.stroke_width.value == 1 ) && - (d->dc[d->level].fill_mode == d->dc[d->level].stroke_mode) && - ( - (d->dc[d->level].fill_mode != DRAW_PAINT) || - ( - (fill_rgb[0]==stroke_rgb[0]) && - (fill_rgb[1]==stroke_rgb[1]) && - (fill_rgb[2]==stroke_rgb[2]) - ) - ) - ){ + // if the stroke is the same as the fill, and the right size not to change the end size of the object, do not do + // it separately + if ((d->dc[d->level].fill_set) && (d->dc[d->level].stroke_set) && + (d->dc[d->level].style.stroke_width.value == 1) && + (d->dc[d->level].fill_mode == d->dc[d->level].stroke_mode) && + ((d->dc[d->level].fill_mode != DRAW_PAINT) || + ((fill_rgb[0] == stroke_rgb[0]) && (fill_rgb[1] == stroke_rgb[1]) && (fill_rgb[2] == stroke_rgb[2])))) { d->dc[d->level].stroke_set = false; } } @@ -931,57 +933,51 @@ Emf::output_style(PEMF_CALLBACK_DATA d, int iType) if (iType == U_EMR_FILLPATH || !d->dc[d->level].stroke_set) { tmp_style << "stroke:none;"; } else { - switch(d->dc[d->level].stroke_mode){ + switch (d->dc[d->level].stroke_mode) { // both of these use the url(#) method case DRAW_PATTERN: - snprintf(tmp, 1023, "stroke:url(#%s); ",d->hatches.strings[d->dc[d->level].stroke_idx]); + snprintf(tmp, 1023, "stroke:url(#%s); ", d->hatches.strings[d->dc[d->level].stroke_idx]); tmp_style << tmp; break; case DRAW_IMAGE: - snprintf(tmp, 1023, "stroke:url(#EMFimage%d_ref); ",d->dc[d->level].stroke_idx); + snprintf(tmp, 1023, "stroke:url(#EMFimage%d_ref); ", d->dc[d->level].stroke_idx); tmp_style << tmp; break; case DRAW_LINEAR_GRADIENT: case DRAW_PAINT: - default: // <-- this should never happen, but just in case... - snprintf( - tmp, 1023, - "stroke:#%02x%02x%02x;", - SP_COLOR_F_TO_U(stroke_rgb[0]), - SP_COLOR_F_TO_U(stroke_rgb[1]), - SP_COLOR_F_TO_U(stroke_rgb[2]) - ); + default: // <-- this should never happen, but just in case... + snprintf(tmp, 1023, "stroke:#%02x%02x%02x;", SP_COLOR_F_TO_U(stroke_rgb[0]), + SP_COLOR_F_TO_U(stroke_rgb[1]), SP_COLOR_F_TO_U(stroke_rgb[2])); tmp_style << tmp; break; } - tmp_style << "stroke-width:" << - MAX( 0.001, d->dc[d->level].style.stroke_width.value ) << "px;"; - - tmp_style << "stroke-linecap:" << - ( - d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_BUTT ? "butt" : - d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_ROUND ? "round" : - d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_SQUARE ? "square" : - "unknown" - ) << ";"; - - tmp_style << "stroke-linejoin:" << - ( - d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_MITER ? "miter" : - d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_ROUND ? "round" : - d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_BEVEL ? "bevel" : - "unknown" - ) << ";"; + tmp_style << "stroke-width:" << MAX(0.001, d->dc[d->level].style.stroke_width.value) << "px;"; + + tmp_style << "stroke-linecap:" + << (d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_BUTT + ? "butt" + : d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_ROUND + ? "round" + : d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_SQUARE ? "square" + : "unknown") + << ";"; + + tmp_style << "stroke-linejoin:" + << (d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_MITER + ? "miter" + : d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_ROUND + ? "round" + : d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_BEVEL + ? "bevel" + : "unknown") + << ";"; // Set miter limit if known, even if it is not needed immediately (not miter) - tmp_style << "stroke-miterlimit:" << - MAX( 2.0, d->dc[d->level].style.stroke_miterlimit.value ) << ";"; + tmp_style << "stroke-miterlimit:" << MAX(2.0, d->dc[d->level].style.stroke_miterlimit.value) << ";"; - if (d->dc[d->level].style.stroke_dasharray.set && - !d->dc[d->level].style.stroke_dasharray.values.empty() ) - { + if (d->dc[d->level].style.stroke_dasharray.set && !d->dc[d->level].style.stroke_dasharray.values.empty()) { tmp_style << "stroke-dasharray:"; - for (unsigned i=0; idc[d->level].style.stroke_dasharray.values.size(); i++) { + for (unsigned i = 0; i < d->dc[d->level].style.stroke_dasharray.values.size(); i++) { if (i) tmp_style << ","; tmp_style << d->dc[d->level].style.stroke_dasharray.values[i].value; @@ -1000,63 +996,58 @@ Emf::output_style(PEMF_CALLBACK_DATA d, int iType) d->outsvg += tmp_style.str().c_str(); } - -double -Emf::_pix_x_to_point(PEMF_CALLBACK_DATA d, double px) +double Emf::_pix_x_to_point(PEMF_CALLBACK_DATA d, double px) { double scale = (d->dc[d->level].ScaleInX ? d->dc[d->level].ScaleInX : 1.0); double tmp; - tmp = ((((double) (px - d->dc[d->level].winorg.x))*scale) + d->dc[d->level].vieworg.x) * d->D2PscaleX; - tmp -= d->ulCornerOutX; //The EMF boundary rectangle can be anywhere, place its upper left corner in the Inkscape upper left corner - return(tmp); + tmp = ((((double)(px - d->dc[d->level].winorg.x)) * scale) + d->dc[d->level].vieworg.x) * d->D2PscaleX; + tmp -= d->ulCornerOutX; // The EMF boundary rectangle can be anywhere, place its upper left corner in the Inkscape + // upper left corner + return (tmp); } -double -Emf::_pix_y_to_point(PEMF_CALLBACK_DATA d, double py) +double Emf::_pix_y_to_point(PEMF_CALLBACK_DATA d, double py) { double scale = (d->dc[d->level].ScaleInY ? d->dc[d->level].ScaleInY : 1.0); double tmp; - tmp = ((((double) (py - d->dc[d->level].winorg.y))*scale) * d->E2IdirY + d->dc[d->level].vieworg.y) * d->D2PscaleY; - tmp -= d->ulCornerOutY; //The EMF boundary rectangle can be anywhere, place its upper left corner in the Inkscape upper left corner - return(tmp); + tmp = ((((double)(py - d->dc[d->level].winorg.y)) * scale) * d->E2IdirY + d->dc[d->level].vieworg.y) * d->D2PscaleY; + tmp -= d->ulCornerOutY; // The EMF boundary rectangle can be anywhere, place its upper left corner in the Inkscape + // upper left corner + return (tmp); } - -double -Emf::pix_to_x_point(PEMF_CALLBACK_DATA d, double px, double py) +double Emf::pix_to_x_point(PEMF_CALLBACK_DATA d, double px, double py) { - double wpx = px * d->dc[d->level].worldTransform.eM11 + py * d->dc[d->level].worldTransform.eM21 + d->dc[d->level].worldTransform.eDx; - double x = _pix_x_to_point(d, wpx); + double wpx = px * d->dc[d->level].worldTransform.eM11 + py * d->dc[d->level].worldTransform.eM21 + + d->dc[d->level].worldTransform.eDx; + double x = _pix_x_to_point(d, wpx); return x; } -double -Emf::pix_to_y_point(PEMF_CALLBACK_DATA d, double px, double py) +double Emf::pix_to_y_point(PEMF_CALLBACK_DATA d, double px, double py) { - - double wpy = px * d->dc[d->level].worldTransform.eM12 + py * d->dc[d->level].worldTransform.eM22 + d->dc[d->level].worldTransform.eDy; - double y = _pix_y_to_point(d, wpy); + double wpy = px * d->dc[d->level].worldTransform.eM12 + py * d->dc[d->level].worldTransform.eM22 + + d->dc[d->level].worldTransform.eDy; + double y = _pix_y_to_point(d, wpy); return y; - } -double -Emf::pix_to_abs_size(PEMF_CALLBACK_DATA d, double px) +double Emf::pix_to_abs_size(PEMF_CALLBACK_DATA d, double px) { - double ppx = fabs(px * (d->dc[d->level].ScaleInX ? d->dc[d->level].ScaleInX : 1.0) * d->D2PscaleX * current_scale(d)); + double ppx = + fabs(px * (d->dc[d->level].ScaleInX ? d->dc[d->level].ScaleInX : 1.0) * d->D2PscaleX * current_scale(d)); return ppx; } /* snaps coordinate pairs made up of values near +/-faraway, +/-faraway to exactly faraway. - This eliminates coordinate drift on repeated clipping cycles which use exclude. + This eliminates coordinate drift on repeated clipping cycles which use exclude. It should not affect internals of normal drawings because the value of faraway is so large. */ -void -Emf::snap_to_faraway_pair(double *x, double *y) +void Emf::snap_to_faraway_pair(double *x, double *y) { - if((std::abs(std::abs(*x) - faraway)/faraway <= 1e-4) && (std::abs(std::abs(*y) - faraway)/faraway <= 1e-4)){ + if ((std::abs(std::abs(*x) - faraway) / faraway <= 1e-4) && (std::abs(std::abs(*y) - faraway) / faraway <= 1e-4)) { *x = (*x > 0 ? faraway : -faraway); *y = (*y > 0 ? faraway : -faraway); } @@ -1065,52 +1056,52 @@ Emf::snap_to_faraway_pair(double *x, double *y) /* returns "x,y" (without the quotes) in inkscape coordinates for a pair of EMF x,y coordinates. Since exclude clip can go through here, it calls snap_to_faraway_pair for numerical stability. */ -std::string Emf::pix_to_xy(PEMF_CALLBACK_DATA d, double x, double y){ +std::string Emf::pix_to_xy(PEMF_CALLBACK_DATA d, double x, double y) +{ SVGOStringStream cxform; - double tx = pix_to_x_point(d,x,y); - double ty = pix_to_y_point(d,x,y); - snap_to_faraway_pair(&tx,&ty); + double tx = pix_to_x_point(d, x, y); + double ty = pix_to_y_point(d, x, y); + snap_to_faraway_pair(&tx, &ty); cxform << tx; cxform << ","; cxform << ty; - return(cxform.str()); + return (cxform.str()); } - -void -Emf::select_pen(PEMF_CALLBACK_DATA d, int index) +void Emf::select_pen(PEMF_CALLBACK_DATA d, int index) { PU_EMRCREATEPEN pEmr = nullptr; - if (index >= 0 && index < d->n_obj){ - pEmr = (PU_EMRCREATEPEN) d->emf_obj[index].lpEMFR; + if (index >= 0 && index < d->n_obj) { + pEmr = (PU_EMRCREATEPEN)d->emf_obj[index].lpEMFR; } - if (!pEmr){ return; } + if (!pEmr) { + return; + } switch (pEmr->lopn.lopnStyle & U_PS_STYLE_MASK) { case U_PS_DASH: case U_PS_DOT: case U_PS_DASHDOT: - case U_PS_DASHDOTDOT: - { + case U_PS_DASHDOTDOT: { SPILength spilength(1.f); int penstyle = (pEmr->lopn.lopnStyle & U_PS_STYLE_MASK); if (!d->dc[d->level].style.stroke_dasharray.values.empty() && (d->level == 0 || (d->level > 0 && d->dc[d->level].style.stroke_dasharray != d->dc[d->level - 1].style.stroke_dasharray))) d->dc[d->level].style.stroke_dasharray.values.clear(); - if (penstyle==U_PS_DASH || penstyle==U_PS_DASHDOT || penstyle==U_PS_DASHDOTDOT) { + if (penstyle == U_PS_DASH || penstyle == U_PS_DASHDOT || penstyle == U_PS_DASHDOTDOT) { spilength.setDouble(3); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); spilength.setDouble(1); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); } - if (penstyle==U_PS_DOT || penstyle==U_PS_DASHDOT || penstyle==U_PS_DASHDOTDOT) { + if (penstyle == U_PS_DOT || penstyle == U_PS_DASHDOT || penstyle == U_PS_DASHDOTDOT) { d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); } - if (penstyle==U_PS_DASHDOTDOT) { + if (penstyle == U_PS_DASHDOTDOT) { d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); } @@ -1120,25 +1111,42 @@ Emf::select_pen(PEMF_CALLBACK_DATA d, int index) } case U_PS_SOLID: - default: - { + default: { d->dc[d->level].style.stroke_dasharray.set = false; break; } } switch (pEmr->lopn.lopnStyle & U_PS_ENDCAP_MASK) { - case U_PS_ENDCAP_ROUND: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_ROUND; break; } - case U_PS_ENDCAP_SQUARE: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_SQUARE; break; } + case U_PS_ENDCAP_ROUND: { + d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_ROUND; + break; + } + case U_PS_ENDCAP_SQUARE: { + d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_SQUARE; + break; + } case U_PS_ENDCAP_FLAT: - default: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_BUTT; break; } + default: { + d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_BUTT; + break; + } } switch (pEmr->lopn.lopnStyle & U_PS_JOIN_MASK) { - case U_PS_JOIN_BEVEL: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_BEVEL; break; } - case U_PS_JOIN_MITER: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_MITER; break; } + case U_PS_JOIN_BEVEL: { + d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_BEVEL; + break; + } + case U_PS_JOIN_MITER: { + d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_MITER; + break; + } case U_PS_JOIN_ROUND: - default: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_ROUND; break; } + default: { + d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_ROUND; + break; + } } d->dc[d->level].stroke_set = true; @@ -1149,47 +1157,45 @@ Emf::select_pen(PEMF_CALLBACK_DATA d, int index) } else if (pEmr->lopn.lopnWidth.x) { int cur_level = d->level; d->level = d->emf_obj[index].level; - double pen_width = pix_to_abs_size( d, pEmr->lopn.lopnWidth.x ); + double pen_width = pix_to_abs_size(d, pEmr->lopn.lopnWidth.x); d->level = cur_level; d->dc[d->level].style.stroke_width.value = pen_width; - } else { // this stroke should always be rendered as 1 pixel wide, independent of zoom level (can that be done in SVG?) - //d->dc[d->level].style.stroke_width.value = 1.0; + } else { // this stroke should always be rendered as 1 pixel wide, independent of zoom level (can that be done in + // SVG?) + // d->dc[d->level].style.stroke_width.value = 1.0; int cur_level = d->level; d->level = d->emf_obj[index].level; - double pen_width = pix_to_abs_size( d, 1 ); + double pen_width = pix_to_abs_size(d, 1); d->level = cur_level; d->dc[d->level].style.stroke_width.value = pen_width; } double r, g, b; - r = SP_COLOR_U_TO_F( U_RGBAGetR(pEmr->lopn.lopnColor) ); - g = SP_COLOR_U_TO_F( U_RGBAGetG(pEmr->lopn.lopnColor) ); - b = SP_COLOR_U_TO_F( U_RGBAGetB(pEmr->lopn.lopnColor) ); - d->dc[d->level].style.stroke.value.color.set( r, g, b ); + r = SP_COLOR_U_TO_F(U_RGBAGetR(pEmr->lopn.lopnColor)); + g = SP_COLOR_U_TO_F(U_RGBAGetG(pEmr->lopn.lopnColor)); + b = SP_COLOR_U_TO_F(U_RGBAGetB(pEmr->lopn.lopnColor)); + d->dc[d->level].style.stroke.value.color.set(r, g, b); } - -void -Emf::select_extpen(PEMF_CALLBACK_DATA d, int index) +void Emf::select_extpen(PEMF_CALLBACK_DATA d, int index) { PU_EMREXTCREATEPEN pEmr = nullptr; if (index >= 0 && index < d->n_obj) - pEmr = (PU_EMREXTCREATEPEN) d->emf_obj[index].lpEMFR; + pEmr = (PU_EMREXTCREATEPEN)d->emf_obj[index].lpEMFR; if (!pEmr) return; switch (pEmr->elp.elpPenStyle & U_PS_STYLE_MASK) { - case U_PS_USERSTYLE: - { + case U_PS_USERSTYLE: { if (pEmr->elp.elpNumEntries) { if (!d->dc[d->level].style.stroke_dasharray.values.empty() && (d->level == 0 || (d->level > 0 && d->dc[d->level].style.stroke_dasharray != d->dc[d->level - 1].style.stroke_dasharray))) d->dc[d->level].style.stroke_dasharray.values.clear(); - for (unsigned int i=0; ielp.elpNumEntries; i++) { - double dash_length = pix_to_abs_size( d, pEmr->elp.elpStyleEntry[i] ); + for (unsigned int i = 0; i < pEmr->elp.elpNumEntries; i++) { + double dash_length = pix_to_abs_size(d, pEmr->elp.elpStyleEntry[i]); d->dc[d->level].style.stroke_dasharray.values.emplace_back(dash_length); } d->dc[d->level].style.stroke_dasharray.set = true; @@ -1202,27 +1208,26 @@ Emf::select_extpen(PEMF_CALLBACK_DATA d, int index) case U_PS_DASH: case U_PS_DOT: case U_PS_DASHDOT: - case U_PS_DASHDOTDOT: - { + case U_PS_DASHDOTDOT: { int penstyle = (pEmr->elp.elpPenStyle & U_PS_STYLE_MASK); if (!d->dc[d->level].style.stroke_dasharray.values.empty() && (d->level == 0 || (d->level > 0 && d->dc[d->level].style.stroke_dasharray != d->dc[d->level - 1].style.stroke_dasharray))) d->dc[d->level].style.stroke_dasharray.values.clear(); SPILength spilength; - if (penstyle==U_PS_DASH || penstyle==U_PS_DASHDOT || penstyle==U_PS_DASHDOTDOT) { + if (penstyle == U_PS_DASH || penstyle == U_PS_DASHDOT || penstyle == U_PS_DASHDOTDOT) { spilength.setDouble(3); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); spilength.setDouble(2); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); } - if (penstyle==U_PS_DOT || penstyle==U_PS_DASHDOT || penstyle==U_PS_DASHDOTDOT) { + if (penstyle == U_PS_DOT || penstyle == U_PS_DASHDOT || penstyle == U_PS_DASHDOTDOT) { spilength.setDouble(1); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); spilength.setDouble(2); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); } - if (penstyle==U_PS_DASHDOTDOT) { + if (penstyle == U_PS_DASHDOTDOT) { spilength.setDouble(1); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); spilength.setDouble(2); @@ -1233,52 +1238,45 @@ Emf::select_extpen(PEMF_CALLBACK_DATA d, int index) break; } case U_PS_SOLID: -/* includes these for now, some should maybe not be in here - case U_PS_NULL: - case U_PS_INSIDEFRAME: - case U_PS_ALTERNATE: - case U_PS_STYLE_MASK: -*/ - default: - { + /* includes these for now, some should maybe not be in here + case U_PS_NULL: + case U_PS_INSIDEFRAME: + case U_PS_ALTERNATE: + case U_PS_STYLE_MASK: + */ + default: { d->dc[d->level].style.stroke_dasharray.set = false; break; } } switch (pEmr->elp.elpPenStyle & U_PS_ENDCAP_MASK) { - case U_PS_ENDCAP_ROUND: - { + case U_PS_ENDCAP_ROUND: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_ROUND; break; } - case U_PS_ENDCAP_SQUARE: - { + case U_PS_ENDCAP_SQUARE: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_SQUARE; break; } case U_PS_ENDCAP_FLAT: - default: - { + default: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_BUTT; break; } } switch (pEmr->elp.elpPenStyle & U_PS_JOIN_MASK) { - case U_PS_JOIN_BEVEL: - { + case U_PS_JOIN_BEVEL: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_BEVEL; break; } - case U_PS_JOIN_MITER: - { + case U_PS_JOIN_MITER: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_MITER; break; } case U_PS_JOIN_ROUND: - default: - { + default: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_ROUND; break; } @@ -1288,102 +1286,97 @@ Emf::select_extpen(PEMF_CALLBACK_DATA d, int index) if (pEmr->elp.elpPenStyle == U_PS_NULL) { // draw nothing, but fill out all the values with something double r, g, b; - r = SP_COLOR_U_TO_F( U_RGBAGetR(d->dc[d->level].textColor)); - g = SP_COLOR_U_TO_F( U_RGBAGetG(d->dc[d->level].textColor)); - b = SP_COLOR_U_TO_F( U_RGBAGetB(d->dc[d->level].textColor)); - d->dc[d->level].style.stroke.value.color.set( r, g, b ); + r = SP_COLOR_U_TO_F(U_RGBAGetR(d->dc[d->level].textColor)); + g = SP_COLOR_U_TO_F(U_RGBAGetG(d->dc[d->level].textColor)); + b = SP_COLOR_U_TO_F(U_RGBAGetB(d->dc[d->level].textColor)); + d->dc[d->level].style.stroke.value.color.set(r, g, b); d->dc[d->level].style.stroke_width.value = 0; d->dc[d->level].stroke_set = false; d->dc[d->level].stroke_mode = DRAW_PAINT; - } - else { + } else { if (pEmr->elp.elpWidth) { int cur_level = d->level; d->level = d->emf_obj[index].level; - double pen_width = pix_to_abs_size( d, pEmr->elp.elpWidth ); + double pen_width = pix_to_abs_size(d, pEmr->elp.elpWidth); d->level = cur_level; d->dc[d->level].style.stroke_width.value = pen_width; - } else { // this stroke should always be rendered as 1 pixel wide, independent of zoom level (can that be done in SVG?) - //d->dc[d->level].style.stroke_width.value = 1.0; + } else { // this stroke should always be rendered as 1 pixel wide, independent of zoom level (can that be done + // in SVG?) + // d->dc[d->level].style.stroke_width.value = 1.0; int cur_level = d->level; d->level = d->emf_obj[index].level; - double pen_width = pix_to_abs_size( d, 1 ); + double pen_width = pix_to_abs_size(d, 1); d->level = cur_level; d->dc[d->level].style.stroke_width.value = pen_width; } - if( pEmr->elp.elpBrushStyle == U_BS_SOLID){ + if (pEmr->elp.elpBrushStyle == U_BS_SOLID) { double r, g, b; - r = SP_COLOR_U_TO_F( U_RGBAGetR(pEmr->elp.elpColor) ); - g = SP_COLOR_U_TO_F( U_RGBAGetG(pEmr->elp.elpColor) ); - b = SP_COLOR_U_TO_F( U_RGBAGetB(pEmr->elp.elpColor) ); - d->dc[d->level].style.stroke.value.color.set( r, g, b ); + r = SP_COLOR_U_TO_F(U_RGBAGetR(pEmr->elp.elpColor)); + g = SP_COLOR_U_TO_F(U_RGBAGetG(pEmr->elp.elpColor)); + b = SP_COLOR_U_TO_F(U_RGBAGetB(pEmr->elp.elpColor)); + d->dc[d->level].style.stroke.value.color.set(r, g, b); d->dc[d->level].stroke_mode = DRAW_PAINT; - d->dc[d->level].stroke_set = true; - } - else if(pEmr->elp.elpBrushStyle == U_BS_HATCHED){ - d->dc[d->level].stroke_idx = add_hatch(d, pEmr->elp.elpHatch, pEmr->elp.elpColor); - d->dc[d->level].stroke_recidx = index; // used if the hatch needs to be redone due to bkMode, textmode, etc. changes - d->dc[d->level].stroke_mode = DRAW_PATTERN; - d->dc[d->level].stroke_set = true; - } - else if(pEmr->elp.elpBrushStyle == U_BS_DIBPATTERN || pEmr->elp.elpBrushStyle == U_BS_DIBPATTERNPT){ - d->dc[d->level].stroke_idx = add_image(d, (void *)pEmr, pEmr->cbBits, pEmr->cbBmi, *(uint32_t *) &(pEmr->elp.elpColor), pEmr->offBits, pEmr->offBmi); + d->dc[d->level].stroke_set = true; + } else if (pEmr->elp.elpBrushStyle == U_BS_HATCHED) { + d->dc[d->level].stroke_idx = add_hatch(d, pEmr->elp.elpHatch, pEmr->elp.elpColor); + d->dc[d->level].stroke_recidx = + index; // used if the hatch needs to be redone due to bkMode, textmode, etc. changes + d->dc[d->level].stroke_mode = DRAW_PATTERN; + d->dc[d->level].stroke_set = true; + } else if (pEmr->elp.elpBrushStyle == U_BS_DIBPATTERN || pEmr->elp.elpBrushStyle == U_BS_DIBPATTERNPT) { + d->dc[d->level].stroke_idx = add_image(d, (void *)pEmr, pEmr->cbBits, pEmr->cbBmi, + *(uint32_t *)&(pEmr->elp.elpColor), pEmr->offBits, pEmr->offBmi); d->dc[d->level].stroke_mode = DRAW_IMAGE; - d->dc[d->level].stroke_set = true; - } - else { // U_BS_PATTERN and anything strange that falls in, stroke is solid textColor + d->dc[d->level].stroke_set = true; + } else { // U_BS_PATTERN and anything strange that falls in, stroke is solid textColor double r, g, b; - r = SP_COLOR_U_TO_F( U_RGBAGetR(d->dc[d->level].textColor)); - g = SP_COLOR_U_TO_F( U_RGBAGetG(d->dc[d->level].textColor)); - b = SP_COLOR_U_TO_F( U_RGBAGetB(d->dc[d->level].textColor)); - d->dc[d->level].style.stroke.value.color.set( r, g, b ); + r = SP_COLOR_U_TO_F(U_RGBAGetR(d->dc[d->level].textColor)); + g = SP_COLOR_U_TO_F(U_RGBAGetG(d->dc[d->level].textColor)); + b = SP_COLOR_U_TO_F(U_RGBAGetB(d->dc[d->level].textColor)); + d->dc[d->level].style.stroke.value.color.set(r, g, b); d->dc[d->level].stroke_mode = DRAW_PAINT; - d->dc[d->level].stroke_set = true; + d->dc[d->level].stroke_set = true; } } } - -void -Emf::select_brush(PEMF_CALLBACK_DATA d, int index) +void Emf::select_brush(PEMF_CALLBACK_DATA d, int index) { - uint32_t tidx; - uint32_t iType; - - if (index >= 0 && index < d->n_obj){ - iType = ((PU_EMR) (d->emf_obj[index].lpEMFR))->iType; - if(iType == U_EMR_CREATEBRUSHINDIRECT){ - PU_EMRCREATEBRUSHINDIRECT pEmr = (PU_EMRCREATEBRUSHINDIRECT) d->emf_obj[index].lpEMFR; - if( pEmr->lb.lbStyle == U_BS_SOLID){ + uint32_t tidx; + uint32_t iType; + + if (index >= 0 && index < d->n_obj) { + iType = ((PU_EMR)(d->emf_obj[index].lpEMFR))->iType; + if (iType == U_EMR_CREATEBRUSHINDIRECT) { + PU_EMRCREATEBRUSHINDIRECT pEmr = (PU_EMRCREATEBRUSHINDIRECT)d->emf_obj[index].lpEMFR; + if (pEmr->lb.lbStyle == U_BS_SOLID) { double r, g, b; - r = SP_COLOR_U_TO_F( U_RGBAGetR(pEmr->lb.lbColor) ); - g = SP_COLOR_U_TO_F( U_RGBAGetG(pEmr->lb.lbColor) ); - b = SP_COLOR_U_TO_F( U_RGBAGetB(pEmr->lb.lbColor) ); - d->dc[d->level].style.fill.value.color.set( r, g, b ); - d->dc[d->level].fill_mode = DRAW_PAINT; - d->dc[d->level].fill_set = true; - } - else if(pEmr->lb.lbStyle == U_BS_HATCHED){ - d->dc[d->level].fill_idx = add_hatch(d, pEmr->lb.lbHatch, pEmr->lb.lbColor); - d->dc[d->level].fill_recidx = index; // used if the hatch needs to be redone due to bkMode, textmode, etc. changes - d->dc[d->level].fill_mode = DRAW_PATTERN; - d->dc[d->level].fill_set = true; - } - } - else if(iType == U_EMR_CREATEDIBPATTERNBRUSHPT || iType == U_EMR_CREATEMONOBRUSH){ - PU_EMRCREATEDIBPATTERNBRUSHPT pEmr = (PU_EMRCREATEDIBPATTERNBRUSHPT) d->emf_obj[index].lpEMFR; - tidx = add_image(d, (void *) pEmr, pEmr->cbBits, pEmr->cbBmi, pEmr->iUsage, pEmr->offBits, pEmr->offBmi); - if(tidx == U_EMR_INVALID){ // This happens if createmonobrush has a DIB that isn't monochrome + r = SP_COLOR_U_TO_F(U_RGBAGetR(pEmr->lb.lbColor)); + g = SP_COLOR_U_TO_F(U_RGBAGetG(pEmr->lb.lbColor)); + b = SP_COLOR_U_TO_F(U_RGBAGetB(pEmr->lb.lbColor)); + d->dc[d->level].style.fill.value.color.set(r, g, b); + d->dc[d->level].fill_mode = DRAW_PAINT; + d->dc[d->level].fill_set = true; + } else if (pEmr->lb.lbStyle == U_BS_HATCHED) { + d->dc[d->level].fill_idx = add_hatch(d, pEmr->lb.lbHatch, pEmr->lb.lbColor); + d->dc[d->level].fill_recidx = + index; // used if the hatch needs to be redone due to bkMode, textmode, etc. changes + d->dc[d->level].fill_mode = DRAW_PATTERN; + d->dc[d->level].fill_set = true; + } + } else if (iType == U_EMR_CREATEDIBPATTERNBRUSHPT || iType == U_EMR_CREATEMONOBRUSH) { + PU_EMRCREATEDIBPATTERNBRUSHPT pEmr = (PU_EMRCREATEDIBPATTERNBRUSHPT)d->emf_obj[index].lpEMFR; + tidx = add_image(d, (void *)pEmr, pEmr->cbBits, pEmr->cbBmi, pEmr->iUsage, pEmr->offBits, pEmr->offBmi); + if (tidx == U_EMR_INVALID) { // This happens if createmonobrush has a DIB that isn't monochrome double r, g, b; - r = SP_COLOR_U_TO_F( U_RGBAGetR(d->dc[d->level].textColor)); - g = SP_COLOR_U_TO_F( U_RGBAGetG(d->dc[d->level].textColor)); - b = SP_COLOR_U_TO_F( U_RGBAGetB(d->dc[d->level].textColor)); - d->dc[d->level].style.fill.value.color.set( r, g, b ); + r = SP_COLOR_U_TO_F(U_RGBAGetR(d->dc[d->level].textColor)); + g = SP_COLOR_U_TO_F(U_RGBAGetG(d->dc[d->level].textColor)); + b = SP_COLOR_U_TO_F(U_RGBAGetB(d->dc[d->level].textColor)); + d->dc[d->level].style.fill.value.color.set(r, g, b); d->dc[d->level].fill_mode = DRAW_PAINT; - } - else { - d->dc[d->level].fill_idx = tidx; + } else { + d->dc[d->level].fill_idx = tidx; d->dc[d->level].fill_mode = DRAW_IMAGE; } d->dc[d->level].fill_set = true; @@ -1391,17 +1384,15 @@ Emf::select_brush(PEMF_CALLBACK_DATA d, int index) } } - -void -Emf::select_font(PEMF_CALLBACK_DATA d, int index) +void Emf::select_font(PEMF_CALLBACK_DATA d, int index) { PU_EMREXTCREATEFONTINDIRECTW pEmr = nullptr; if (index >= 0 && index < d->n_obj) - pEmr = (PU_EMREXTCREATEFONTINDIRECTW) d->emf_obj[index].lpEMFR; - - if (!pEmr)return; + pEmr = (PU_EMREXTCREATEFONTINDIRECTW)d->emf_obj[index].lpEMFR; + if (!pEmr) + return; /* The logfont information always starts with a U_LOGFONT structure but the U_EMREXTCREATEFONTINDIRECTW is defined as U_LOGFONT_PANOSE so it can handle one of those if that is actually present. Currently only logfont @@ -1409,106 +1400,128 @@ Emf::select_font(PEMF_CALLBACK_DATA d, int index) */ int cur_level = d->level; d->level = d->emf_obj[index].level; - double font_size = pix_to_abs_size( d, pEmr->elfw.elfLogFont.lfHeight ); + double font_size = pix_to_abs_size(d, pEmr->elfw.elfLogFont.lfHeight); /* snap the font_size to the nearest 1/32nd of a point. (The size is converted from Pixels to points, snapped, and converted back.) See the notes where d->D2Pscale[XY] are set for the reason why. Typically this will set the font to the desired exact size. If some peculiar size was intended this will, at worst, make it .03125 off, which is unlikely to be a problem. */ - font_size = round(20.0 * 0.8 * font_size)/(20.0 * 0.8); + font_size = round(20.0 * 0.8 * font_size) / (20.0 * 0.8); d->level = cur_level; d->dc[d->level].style.font_size.computed = font_size; d->dc[d->level].style.font_weight.value = - pEmr->elfw.elfLogFont.lfWeight == U_FW_THIN ? SP_CSS_FONT_WEIGHT_100 : - pEmr->elfw.elfLogFont.lfWeight == U_FW_EXTRALIGHT ? SP_CSS_FONT_WEIGHT_200 : - pEmr->elfw.elfLogFont.lfWeight == U_FW_LIGHT ? SP_CSS_FONT_WEIGHT_300 : - pEmr->elfw.elfLogFont.lfWeight == U_FW_NORMAL ? SP_CSS_FONT_WEIGHT_400 : - pEmr->elfw.elfLogFont.lfWeight == U_FW_MEDIUM ? SP_CSS_FONT_WEIGHT_500 : - pEmr->elfw.elfLogFont.lfWeight == U_FW_SEMIBOLD ? SP_CSS_FONT_WEIGHT_600 : - pEmr->elfw.elfLogFont.lfWeight == U_FW_BOLD ? SP_CSS_FONT_WEIGHT_700 : - pEmr->elfw.elfLogFont.lfWeight == U_FW_EXTRABOLD ? SP_CSS_FONT_WEIGHT_800 : - pEmr->elfw.elfLogFont.lfWeight == U_FW_HEAVY ? SP_CSS_FONT_WEIGHT_900 : - pEmr->elfw.elfLogFont.lfWeight == U_FW_NORMAL ? SP_CSS_FONT_WEIGHT_NORMAL : - pEmr->elfw.elfLogFont.lfWeight == U_FW_BOLD ? SP_CSS_FONT_WEIGHT_BOLD : - pEmr->elfw.elfLogFont.lfWeight == U_FW_EXTRALIGHT ? SP_CSS_FONT_WEIGHT_LIGHTER : - pEmr->elfw.elfLogFont.lfWeight == U_FW_EXTRABOLD ? SP_CSS_FONT_WEIGHT_BOLDER : - SP_CSS_FONT_WEIGHT_NORMAL; - d->dc[d->level].style.font_style.value = (pEmr->elfw.elfLogFont.lfItalic ? SP_CSS_FONT_STYLE_ITALIC : SP_CSS_FONT_STYLE_NORMAL); - d->dc[d->level].style.text_decoration_line.underline = pEmr->elfw.elfLogFont.lfUnderline; + pEmr->elfw.elfLogFont.lfWeight == U_FW_THIN + ? SP_CSS_FONT_WEIGHT_100 + : pEmr->elfw.elfLogFont.lfWeight == U_FW_EXTRALIGHT + ? SP_CSS_FONT_WEIGHT_200 + : pEmr->elfw.elfLogFont.lfWeight == U_FW_LIGHT + ? SP_CSS_FONT_WEIGHT_300 + : pEmr->elfw.elfLogFont.lfWeight == U_FW_NORMAL + ? SP_CSS_FONT_WEIGHT_400 + : pEmr->elfw.elfLogFont.lfWeight == U_FW_MEDIUM + ? SP_CSS_FONT_WEIGHT_500 + : pEmr->elfw.elfLogFont.lfWeight == U_FW_SEMIBOLD + ? SP_CSS_FONT_WEIGHT_600 + : pEmr->elfw.elfLogFont.lfWeight == U_FW_BOLD + ? SP_CSS_FONT_WEIGHT_700 + : pEmr->elfw.elfLogFont.lfWeight == U_FW_EXTRABOLD + ? SP_CSS_FONT_WEIGHT_800 + : pEmr->elfw.elfLogFont.lfWeight == U_FW_HEAVY + ? SP_CSS_FONT_WEIGHT_900 + : pEmr->elfw.elfLogFont.lfWeight == U_FW_NORMAL + ? SP_CSS_FONT_WEIGHT_NORMAL + : pEmr->elfw.elfLogFont.lfWeight == U_FW_BOLD + ? SP_CSS_FONT_WEIGHT_BOLD + : pEmr->elfw.elfLogFont.lfWeight == + U_FW_EXTRALIGHT + ? SP_CSS_FONT_WEIGHT_LIGHTER + : pEmr->elfw.elfLogFont.lfWeight == + U_FW_EXTRABOLD + ? SP_CSS_FONT_WEIGHT_BOLDER + : SP_CSS_FONT_WEIGHT_NORMAL; + d->dc[d->level].style.font_style.value = + (pEmr->elfw.elfLogFont.lfItalic ? SP_CSS_FONT_STYLE_ITALIC : SP_CSS_FONT_STYLE_NORMAL); + d->dc[d->level].style.text_decoration_line.underline = pEmr->elfw.elfLogFont.lfUnderline; d->dc[d->level].style.text_decoration_line.line_through = pEmr->elfw.elfLogFont.lfStrikeOut; - d->dc[d->level].style.text_decoration_line.set = true; - d->dc[d->level].style.text_decoration_line.inherit = false; + d->dc[d->level].style.text_decoration_line.set = true; + d->dc[d->level].style.text_decoration_line.inherit = false; // malformed EMF with empty filename may exist, ignore font change if encountered - char *ctmp = U_Utf16leToUtf8((uint16_t *) (pEmr->elfw.elfLogFont.lfFaceName), U_LF_FACESIZE, nullptr); - if(ctmp){ - if (d->dc[d->level].font_name){ free(d->dc[d->level].font_name); } - if(*ctmp){ - d->dc[d->level].font_name = ctmp; + char *ctmp = U_Utf16leToUtf8((uint16_t *)(pEmr->elfw.elfLogFont.lfFaceName), U_LF_FACESIZE, nullptr); + if (ctmp) { + if (d->dc[d->level].font_name) { + free(d->dc[d->level].font_name); } - else { // Malformed EMF might specify an empty font name + if (*ctmp) { + d->dc[d->level].font_name = ctmp; + } else { // Malformed EMF might specify an empty font name free(ctmp); - d->dc[d->level].font_name = strdup("Arial"); // Default font, EMF spec says device can pick whatever it wants + d->dc[d->level].font_name = + strdup("Arial"); // Default font, EMF spec says device can pick whatever it wants } } - d->dc[d->level].style.baseline_shift.value = round((double)((pEmr->elfw.elfLogFont.lfEscapement + 3600) % 3600)) / 10.0; // use baseline_shift instead of text_transform to avoid overflow + d->dc[d->level].style.baseline_shift.value = round((double)((pEmr->elfw.elfLogFont.lfEscapement + 3600) % 3600)) / + 10.0; // use baseline_shift instead of text_transform to avoid overflow } -void -Emf::delete_object(PEMF_CALLBACK_DATA d, int index) +void Emf::delete_object(PEMF_CALLBACK_DATA d, int index) { if (index >= 0 && index < d->n_obj) { d->emf_obj[index].type = 0; -// We are keeping a copy of the EMR rather than just a structure. Currently that is not necessary as the entire -// EMF is read in at once and is stored in a big malloc. However, in past versions it was handled -// record by record, and we might need to do that again at some point in the future if we start running into EMF -// files too big to fit into memory. + // We are keeping a copy of the EMR rather than just a structure. Currently that is not necessary as the entire + // EMF is read in at once and is stored in a big malloc. However, in past versions it was handled + // record by record, and we might need to do that again at some point in the future if we start running into EMF + // files too big to fit into memory. if (d->emf_obj[index].lpEMFR) free(d->emf_obj[index].lpEMFR); d->emf_obj[index].lpEMFR = nullptr; } } - -void -Emf::insert_object(PEMF_CALLBACK_DATA d, int index, int type, PU_ENHMETARECORD pObj) +void Emf::insert_object(PEMF_CALLBACK_DATA d, int index, int type, PU_ENHMETARECORD pObj) { if (index >= 0 && index < d->n_obj) { delete_object(d, index); d->emf_obj[index].type = type; d->emf_obj[index].level = d->level; - d->emf_obj[index].lpEMFR = emr_dup((char *) pObj); + d->emf_obj[index].lpEMFR = emr_dup((char *)pObj); } } /* Identify probable Adobe Illustrator produced EMF files, which do strange things with the scaling. The few so far observed all had this format. */ -int Emf::AI_hack(PU_EMRHEADER pEmr){ - int ret=0; - char *ptr; - ptr = (char *)pEmr; - PU_EMRSETMAPMODE nEmr = (PU_EMRSETMAPMODE) (ptr + pEmr->emr.nSize); - char *string = nullptr; - if(pEmr->nDescription)string = U_Utf16leToUtf8((uint16_t *)((char *) pEmr + pEmr->offDescription), pEmr->nDescription, nullptr); - if(string){ - if((pEmr->nDescription >= 13) && - (0==strcmp("Adobe Systems",string)) && - (nEmr->emr.iType == U_EMR_SETMAPMODE) && - (nEmr->iMode == U_MM_ANISOTROPIC)){ ret=1; } - free(string); - } - return(ret); +int Emf::AI_hack(PU_EMRHEADER pEmr) +{ + int ret = 0; + char *ptr; + ptr = (char *)pEmr; + PU_EMRSETMAPMODE nEmr = (PU_EMRSETMAPMODE)(ptr + pEmr->emr.nSize); + char *string = nullptr; + if (pEmr->nDescription) + string = U_Utf16leToUtf8((uint16_t *)((char *)pEmr + pEmr->offDescription), pEmr->nDescription, nullptr); + if (string) { + if ((pEmr->nDescription >= 13) && (0 == strcmp("Adobe Systems", string)) && + (nEmr->emr.iType == U_EMR_SETMAPMODE) && (nEmr->iMode == U_MM_ANISOTROPIC)) { + ret = 1; + } + free(string); + } + return (ret); } /** \fn create a UTF-32LE buffer and fill it with UNICODE unknown character \param count number of copies of the Unicode unknown character to fill with */ -uint32_t *Emf::unknown_chars(size_t count){ - uint32_t *res = (uint32_t *) malloc(sizeof(uint32_t) * (count + 1)); - if(!res)throw "Inkscape fatal memory allocation error - cannot continue"; - for(uint32_t i=0; idc[d->level].clip_id){ + if (d->dc[d->level].clip_id) { tmp_image << "\tclip-path=\"url(#clipEmfPath" << d->dc[d->level].clip_id << ")\"\n"; } - tmp_image << " y=\"" << dy << "\"\n x=\"" << dx <<"\"\n "; + tmp_image << " y=\"" << dy << "\"\n x=\"" << dx << "\"\n "; MEMPNG mempng; // PNG in memory comes back in this mempng.buffer = nullptr; - char *rgba_px = nullptr; // RGBA pixels - char *sub_px = nullptr; // RGBA pixels, subarray - const char *px = nullptr; // DIB pixels - const U_RGBQUAD *ct = nullptr; // DIB color table + char *rgba_px = nullptr; // RGBA pixels + char *sub_px = nullptr; // RGBA pixels, subarray + const char *px = nullptr; // DIB pixels + const U_RGBQUAD *ct = nullptr; // DIB color table uint32_t width, height, colortype, numCt, invert; // if needed these values will be set in get_DIB_params - if(cbBits && cbBmi && (iUsage == U_DIB_RGB_COLORS)){ + if (cbBits && cbBmi && (iUsage == U_DIB_RGB_COLORS)) { // next call returns pointers and values, but allocates no memory - dibparams = get_DIB_params((const char *)pEmr, offBits, offBmi, &px, (const U_RGBQUAD **) &ct, - &numCt, &width, &height, &colortype, &invert); - if(dibparams ==U_BI_RGB){ - if(sw == 0 || sh == 0){ + dibparams = get_DIB_params((const char *)pEmr, offBits, offBmi, &px, (const U_RGBQUAD **)&ct, &numCt, &width, + &height, &colortype, &invert); + if (dibparams == U_BI_RGB) { + if (sw == 0 || sh == 0) { sw = width; sh = height; } - if(!DIB_to_RGBA( - px, // DIB pixel array - ct, // DIB color table - numCt, // DIB color table number of entries - &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. - width, // Width of pixel array - height, // Height of pixel array - colortype, // DIB BitCount Enumeration - numCt, // Color table used if not 0 - invert // If DIB rows are in opposite order from RGBA rows - )){ - sub_px = RGBA_to_RGBA( // returns either a subset (side effect: frees rgba_px) or NULL (for subset == entire image) + if (!DIB_to_RGBA(px, // DIB pixel array + ct, // DIB color table + numCt, // DIB color table number of entries + &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. + width, // Width of pixel array + height, // Height of pixel array + colortype, // DIB BitCount Enumeration + numCt, // Color table used if not 0 + invert // If DIB rows are in opposite order from RGBA rows + )) { + sub_px = RGBA_to_RGBA( // returns either a subset (side effect: frees rgba_px) or NULL (for subset == + // entire image) rgba_px, // full pixel array from DIB width, // Width of pixel array height, // Height of pixel array - sx,sy, // starting point in pixel array - &sw,&sh // columns/rows to extract from the pixel array (output array size) + sx, sy, // starting point in pixel array + &sw, &sh // columns/rows to extract from the pixel array (output array size) ); - if(!sub_px)sub_px=rgba_px; - toPNG( // Get the image from the RGBA px into mempng - &mempng, - sw, sh, // size of the extracted pixel array - sub_px - ); + if (!sub_px) + sub_px = rgba_px; + toPNG( // Get the image from the RGBA px into mempng + &mempng, sw, sh, // size of the extracted pixel array + sub_px); free(sub_px); } } } - gchar *base64String=nullptr; - if(dibparams == U_BI_JPEG){ // image was binary jpg in source file + gchar *base64String = nullptr; + if (dibparams == U_BI_JPEG) { // image was binary jpg in source file tmp_image << " xlink:href=\"data:image/jpeg;base64,"; - base64String = g_base64_encode((guchar*) px, numCt ); - } - else if(dibparams==U_BI_PNG){ // image was binary png in source file + base64String = g_base64_encode((guchar *)px, numCt); + } else if (dibparams == U_BI_PNG) { // image was binary png in source file tmp_image << " xlink:href=\"data:image/png;base64,"; - base64String = g_base64_encode((guchar*) px, numCt ); - } - else if(mempng.buffer){ // image was DIB in source file, converted to png in this routine + base64String = g_base64_encode((guchar *)px, numCt); + } else if (mempng.buffer) { // image was DIB in source file, converted to png in this routine tmp_image << " xlink:href=\"data:image/png;base64,"; - base64String = g_base64_encode((guchar*) mempng.buffer, mempng.size ); + base64String = g_base64_encode((guchar *)mempng.buffer, mempng.size); free(mempng.buffer); - } - else { // unknown or unsupported image type or failed conversion, insert the common bad image picture + } else { // unknown or unsupported image type or failed conversion, insert the common bad image picture tmp_image << " xlink:href=\"data:image/png;base64,"; base64String = bad_image_png(); } @@ -1614,7 +1623,7 @@ void Emf::common_image_extraction(PEMF_CALLBACK_DATA d, void *pEmr, tmp_image << " transform=" << current_matrix(d, dx, dy, 1); // calculate appropriate offset tmp_image << " preserveAspectRatio=\"none\"\n"; - tmp_image << "/> \n"; + tmp_image << "/> \n"; d->outsvg += tmp_image.str().c_str(); d->path = ""; @@ -1626,1041 +1635,1038 @@ void Emf::common_image_extraction(PEMF_CALLBACK_DATA d, void *pEmr, \param length length in bytes of contents \param d Inkscape data structures returned by this call */ -//THis was a callback, just build it into a normal function +// THis was a callback, just build it into a normal function int Emf::myEnhMetaFileProc(char *contents, unsigned int length, PEMF_CALLBACK_DATA d) { - uint32_t off=0; - uint32_t emr_mask; - int OK =1; - int file_status=1; - uint32_t nSize; - uint32_t iType; - const char *blimit = contents + length; + uint32_t off = 0; + uint32_t emr_mask; + int OK = 1; + int file_status = 1; + uint32_t nSize; + uint32_t iType; + const char *blimit = contents + length; PU_ENHMETARECORD lpEMFR; - TCHUNK_SPECS tsp; - uint32_t tbkMode = U_TRANSPARENT; // holds proposed change to bkMode, if text is involved saving these to the DC must wait until the text is written - U_COLORREF tbkColor = U_RGB(255, 255, 255); // holds proposed change to bkColor + TCHUNK_SPECS tsp; + uint32_t tbkMode = U_TRANSPARENT; // holds proposed change to bkMode, if text is involved saving these to the DC + // must wait until the text is written + U_COLORREF tbkColor = U_RGB(255, 255, 255); // holds proposed change to bkColor // code for end user debugging - int eDbgRecord=0; - int eDbgComment=0; - int eDbgFinal=0; - char const* eDbgString = getenv( "INKSCAPE_DBG_EMF" ); - if ( eDbgString != nullptr ) { - if(strstr(eDbgString,"RECORD")){ eDbgRecord = 1; } - if(strstr(eDbgString,"COMMENT")){ eDbgComment = 1; } - if(strstr(eDbgString,"FINAL")){ eDbgFinal = 1; } + int eDbgRecord = 0; + int eDbgComment = 0; + int eDbgFinal = 0; + char const *eDbgString = getenv("INKSCAPE_DBG_EMF"); + if (eDbgString != nullptr) { + if (strstr(eDbgString, "RECORD")) { + eDbgRecord = 1; + } + if (strstr(eDbgString, "COMMENT")) { + eDbgComment = 1; + } + if (strstr(eDbgString, "FINAL")) { + eDbgFinal = 1; + } } /* initialize the tsp for text reassembly */ - tsp.string = nullptr; - tsp.ori = 0.0; /* degrees */ - tsp.fs = 12.0; /* font size */ - tsp.x = 0.0; - tsp.y = 0.0; - tsp.boff = 0.0; /* offset to baseline from LL corner of bounding rectangle, changes with fs and taln*/ - tsp.vadvance = 0.0; /* meaningful only when a complex contains two or more lines */ - tsp.taln = ALILEFT + ALIBASE; - tsp.ldir = LDIR_LR; - tsp.spaces = 0; // this field is only used for debugging - tsp.color.Red = 0; /* RGB Black */ - tsp.color.Green = 0; /* RGB Black */ - tsp.color.Blue = 0; /* RGB Black */ - tsp.color.Reserved = 0; /* not used */ - tsp.italics = 0; - tsp.weight = 80; + tsp.string = nullptr; + tsp.ori = 0.0; /* degrees */ + tsp.fs = 12.0; /* font size */ + tsp.x = 0.0; + tsp.y = 0.0; + tsp.boff = 0.0; /* offset to baseline from LL corner of bounding rectangle, changes with fs and taln*/ + tsp.vadvance = 0.0; /* meaningful only when a complex contains two or more lines */ + tsp.taln = ALILEFT + ALIBASE; + tsp.ldir = LDIR_LR; + tsp.spaces = 0; // this field is only used for debugging + tsp.color.Red = 0; /* RGB Black */ + tsp.color.Green = 0; /* RGB Black */ + tsp.color.Blue = 0; /* RGB Black */ + tsp.color.Reserved = 0; /* not used */ + tsp.italics = 0; + tsp.weight = 80; tsp.decoration = TXTDECOR_NONE; - tsp.condensed = 100; - tsp.co = 0; - tsp.fi_idx = -1; /* set to an invalid */ - - while(OK){ - if(off>=length)return(0); //normally should exit from while after EMREOF sets OK to false. - - // check record sizes and types thoroughly - int badrec = 0; - if (!U_emf_record_sizeok(contents + off, blimit, &nSize, &iType, 1) || - !U_emf_record_safe(contents + off)){ - badrec = 1; - } - else { - emr_mask = emr_properties(iType); - if (emr_mask == U_EMR_INVALID) { badrec = 1; } - } - if (badrec) { - file_status = 0; - break; - } - - lpEMFR = (PU_ENHMETARECORD)(contents + off); - -// At run time define environment variable INKSCAPE_DBG_EMF to include string RECORD. -// Users may employ this to track down toxic records - if(eDbgRecord){ - std::cout << "record type: " << iType << " name " << U_emr_names(iType) << " length: " << nSize << " offset: " << off <dirty:"<< d->tri->dirty << " emr_mask: " << std::hex << emr_mask << std::dec << std::endl; - - // incompatible change to text drawing detected (color or background change) forces out existing text - // OR - // next record is valid type and forces pending text to be drawn immediately - if ((d->dc[d->level].dirty & DIRTY_TEXT) || ((emr_mask != U_EMR_INVALID) && (emr_mask & U_DRAW_TEXT) && d->tri->dirty)){ - TR_layout_analyze(d->tri); - if (d->dc[d->level].clip_id){ - SVGOStringStream tmp_clip; - tmp_clip << "\ndc[d->level].clip_id << ")\"\n>"; - d->outsvg += tmp_clip.str().c_str(); + tsp.condensed = 100; + tsp.co = 0; + tsp.fi_idx = -1; /* set to an invalid */ + + while (OK) { + if (off >= length) + return (0); // normally should exit from while after EMREOF sets OK to false. + + // check record sizes and types thoroughly + int badrec = 0; + if (!U_emf_record_sizeok(contents + off, blimit, &nSize, &iType, 1) || !U_emf_record_safe(contents + off)) { + badrec = 1; + } else { + emr_mask = emr_properties(iType); + if (emr_mask == U_EMR_INVALID) { + badrec = 1; + } } - TR_layout_2_svg(d->tri); - SVGOStringStream ts; - ts << d->tri->out; - d->outsvg += ts.str().c_str(); - d->tri = trinfo_clear(d->tri); - if (d->dc[d->level].clip_id){ - d->outsvg += "\n\n"; - } - } - if(d->dc[d->level].dirty){ //Apply the delayed background changes, clear the flag - d->dc[d->level].bkMode = tbkMode; - memcpy(&(d->dc[d->level].bkColor),&tbkColor, sizeof(U_COLORREF)); - - if(d->dc[d->level].dirty & DIRTY_TEXT){ - // U_COLORREF and TRCOLORREF are exactly the same in memory, but the compiler needs some convincing... - if(tbkMode == U_TRANSPARENT){ (void) trinfo_load_bk(d->tri, BKCLR_NONE, *(TRCOLORREF *) &tbkColor); } - else { (void) trinfo_load_bk(d->tri, BKCLR_LINE, *(TRCOLORREF *) &tbkColor); } // Opaque + if (badrec) { + file_status = 0; + break; } - /* It is possible to have a series of EMF records that would result in - the following creating hash patterns which are never used. For instance, if - there were a series of records that changed the background color but did nothing - else. - */ - if((d->dc[d->level].stroke_mode == DRAW_PATTERN) && (d->dc[d->level].dirty & DIRTY_STROKE)){ - select_extpen(d, d->dc[d->level].stroke_recidx); - } - - if((d->dc[d->level].fill_mode == DRAW_PATTERN) && (d->dc[d->level].dirty & DIRTY_FILL)){ - select_brush(d, d->dc[d->level].fill_recidx); + lpEMFR = (PU_ENHMETARECORD)(contents + off); + + // At run time define environment variable INKSCAPE_DBG_EMF to include string RECORD. + // Users may employ this to track down toxic records + if (eDbgRecord) { + std::cout << "record type: " << iType << " name " << U_emr_names(iType) << " length: " << nSize + << " offset: " << off << std::endl; } - - d->dc[d->level].dirty = 0; - } + off += nSize; -// std::cout << "BEFORE DRAW logic d->mask: " << std::hex << d->mask << " emr_mask: " << emr_mask << std::dec << std::endl; -/* -std::cout << "BEFORE DRAW" - << " test0 " << ( d->mask & U_DRAW_VISIBLE) - << " test1 " << ( d->mask & U_DRAW_FORCE) - << " test2 " << (emr_mask & U_DRAW_ALTERS) - << " test3 " << (emr_mask & U_DRAW_VISIBLE) - << " test4 " << !(d->mask & U_DRAW_ONLYTO) - << " test5 " << ((d->mask & U_DRAW_ONLYTO) && !(emr_mask & U_DRAW_ONLYTO) ) - << std::endl; -*/ + SVGOStringStream tmp_outsvg; + SVGOStringStream tmp_path; + SVGOStringStream tmp_str; + SVGOStringStream dbg_str; - if( - (emr_mask != U_EMR_INVALID) && // next record is valid type - (d->mask & U_DRAW_VISIBLE) && // Current set of objects are drawable - ( - (d->mask & U_DRAW_FORCE) || // This draw is forced by STROKE/FILL/STROKEANDFILL PATH - (emr_mask & U_DRAW_ALTERS) || // Next record would alter the drawing environment in some way - ( - (emr_mask & U_DRAW_VISIBLE) && // Next record is visible... - ( - ( !(d->mask & U_DRAW_ONLYTO) ) || // Non *TO records cannot be followed by any Visible - ((d->mask & U_DRAW_ONLYTO) && !(emr_mask & U_DRAW_ONLYTO) )// *TO records can only be followed by other *TO records - ) - ) - ) - ){ -// std::cout << "PATH DRAW at TOP path" << *(d->path) << std::endl; - if(!(d->path.empty())){ - d->outsvg += " drawtype){ // explicit draw type EMR record - output_style(d, d->drawtype); - } - else if(d->mask & U_DRAW_CLOSED){ // implicit draw type - output_style(d, U_EMR_STROKEANDFILLPATH); - } - else { - output_style(d, U_EMR_STROKEPATH); - } - d->outsvg += "\n\t"; - d->outsvg += "\n\td=\""; // this is the ONLY place d=" should be used!!!! One exception, gradientfill. - d->outsvg += d->path; - d->outsvg += " \" /> \n"; - d->path = ""; + /* Uncomment the following to track down text problems */ + // std::cout << "tri->dirty:"<< d->tri->dirty << " emr_mask: " << std::hex << emr_mask << std::dec << std::endl; + + // incompatible change to text drawing detected (color or background change) forces out existing text + // OR + // next record is valid type and forces pending text to be drawn immediately + if ((d->dc[d->level].dirty & DIRTY_TEXT) || + ((emr_mask != U_EMR_INVALID) && (emr_mask & U_DRAW_TEXT) && d->tri->dirty)) { + TR_layout_analyze(d->tri); + if (d->dc[d->level].clip_id) { + SVGOStringStream tmp_clip; + tmp_clip << "\ndc[d->level].clip_id << ")\"\n>"; + d->outsvg += tmp_clip.str().c_str(); + } + TR_layout_2_svg(d->tri); + SVGOStringStream ts; + ts << d->tri->out; + d->outsvg += ts.str().c_str(); + d->tri = trinfo_clear(d->tri); + if (d->dc[d->level].clip_id) { + d->outsvg += "\n\n"; + } } - // reset the flags - d->mask = 0; - d->drawtype = 0; - } -// std::cout << "AFTER DRAW logic d->mask: " << std::hex << d->mask << " emr_mask: " << emr_mask << std::dec << std::endl; - - switch (iType) - { - case U_EMR_HEADER: - { - dbg_str << "\n"; - - d->outdef += "\n"; - - if (d->pDesc) { - d->outdef += "\n"; - } - - PU_EMRHEADER pEmr = (PU_EMRHEADER) lpEMFR; - SVGOStringStream tmp_outdef; - tmp_outdef << "MM100InX = pEmr->rclFrame.right - pEmr->rclFrame.left + 1; - d->MM100InY = pEmr->rclFrame.bottom - pEmr->rclFrame.top + 1; - d->PixelsInX = pEmr->rclBounds.right - pEmr->rclBounds.left + 1; - d->PixelsInY = pEmr->rclBounds.bottom - pEmr->rclBounds.top + 1; - - /* - calculate ratio of Inkscape dpi/EMF device dpi - This can cause problems later due to accuracy limits in the EMF. A high resolution - EMF might have a final D2Pscale[XY] of 0.074998, and adjusting the (integer) device size - by 1 will still not get it exactly to 0.075. Later when the font size is calculated it - can end up as 29.9992 or 22.4994 instead of the intended 30 or 22.5. This is handled by - snapping font sizes to the nearest .01. The best estimate is made by using both values. - */ - if ((pEmr->szlMillimeters.cx + pEmr->szlMillimeters.cy) && ( pEmr->szlDevice.cx + pEmr->szlDevice.cy)){ - d->E2IdirY = 1.0; // assume MM_TEXT, if not, this will be changed later - d->D2PscaleX = d->D2PscaleY = Inkscape::Util::Quantity::convert(1, "mm", "px") * - (double)(pEmr->szlMillimeters.cx + pEmr->szlMillimeters.cy)/ - (double)( pEmr->szlDevice.cx + pEmr->szlDevice.cy); + if (d->dc[d->level].dirty) { // Apply the delayed background changes, clear the flag + d->dc[d->level].bkMode = tbkMode; + memcpy(&(d->dc[d->level].bkColor), &tbkColor, sizeof(U_COLORREF)); + + if (d->dc[d->level].dirty & DIRTY_TEXT) { + // U_COLORREF and TRCOLORREF are exactly the same in memory, but the compiler needs some convincing... + if (tbkMode == U_TRANSPARENT) { + (void)trinfo_load_bk(d->tri, BKCLR_NONE, *(TRCOLORREF *)&tbkColor); + } else { + (void)trinfo_load_bk(d->tri, BKCLR_LINE, *(TRCOLORREF *)&tbkColor); + } // Opaque } - trinfo_load_qe(d->tri, d->D2PscaleX); /* quantization error that will affect text positions */ - /* Adobe Illustrator files set mapmode to MM_ANISOTROPIC and somehow or other this - converts the rclFrame values from MM_HIMETRIC to MM_HIENGLISH, with another factor of 3 thrown - in for good measure. Ours not to question why... + /* It is possible to have a series of EMF records that would result in + the following creating hash patterns which are never used. For instance, if + there were a series of records that changed the background color but did nothing + else. */ - if(AI_hack(pEmr)){ - d->MM100InX *= 25.4/(10.0*3.0); - d->MM100InY *= 25.4/(10.0*3.0); - d->D2PscaleX *= 25.4/(10.0*3.0); - d->D2PscaleY *= 25.4/(10.0*3.0); + if ((d->dc[d->level].stroke_mode == DRAW_PATTERN) && (d->dc[d->level].dirty & DIRTY_STROKE)) { + select_extpen(d, d->dc[d->level].stroke_recidx); } - d->MMX = d->MM100InX / 100.0; - d->MMY = d->MM100InY / 100.0; + if ((d->dc[d->level].fill_mode == DRAW_PATTERN) && (d->dc[d->level].dirty & DIRTY_FILL)) { + select_brush(d, d->dc[d->level].fill_recidx); + } - d->PixelsOutX = Inkscape::Util::Quantity::convert(d->MMX, "mm", "px"); - d->PixelsOutY = Inkscape::Util::Quantity::convert(d->MMY, "mm", "px"); + d->dc[d->level].dirty = 0; + } - // Upper left corner, from header rclBounds, in device units, usually both 0, but not always - d->ulCornerInX = pEmr->rclBounds.left; - d->ulCornerInY = pEmr->rclBounds.top; - d->ulCornerOutX = d->ulCornerInX * d->D2PscaleX; - d->ulCornerOutY = d->ulCornerInY * d->E2IdirY * d->D2PscaleY; + // std::cout << "BEFORE DRAW logic d->mask: " << std::hex << d->mask << " emr_mask: " << emr_mask << std::dec << + // std::endl; + /* + std::cout << "BEFORE DRAW" + << " test0 " << ( d->mask & U_DRAW_VISIBLE) + << " test1 " << ( d->mask & U_DRAW_FORCE) + << " test2 " << (emr_mask & U_DRAW_ALTERS) + << " test3 " << (emr_mask & U_DRAW_VISIBLE) + << " test4 " << !(d->mask & U_DRAW_ONLYTO) + << " test5 " << ((d->mask & U_DRAW_ONLYTO) && !(emr_mask & U_DRAW_ONLYTO) ) + << std::endl; + */ - tmp_outdef << - " width=\"" << d->MMX << "mm\"\n" << - " height=\"" << d->MMY << "mm\">\n"; - d->outdef += tmp_outdef.str().c_str(); - d->outdef += ""; // temporary end of header + if ((emr_mask != U_EMR_INVALID) && // next record is valid type + (d->mask & U_DRAW_VISIBLE) && // Current set of objects are drawable + ((d->mask & U_DRAW_FORCE) || // This draw is forced by STROKE/FILL/STROKEANDFILL PATH + (emr_mask & U_DRAW_ALTERS) || // Next record would alter the drawing environment in some way + ((emr_mask & U_DRAW_VISIBLE) && // Next record is visible... + ((!(d->mask & U_DRAW_ONLYTO)) || // Non *TO records cannot be followed by any Visible + ((d->mask & U_DRAW_ONLYTO) && !(emr_mask & U_DRAW_ONLYTO)) // *TO records can only be followed by other + // *TO records + )))) { + // std::cout << "PATH DRAW at TOP path" << *(d->path) << std::endl; + if (!(d->path.empty())) { + d->outsvg += + " drawtype) { // explicit draw type EMR record + output_style(d, d->drawtype); + } else if (d->mask & U_DRAW_CLOSED) { // implicit draw type + output_style(d, U_EMR_STROKEANDFILLPATH); + } else { + output_style(d, U_EMR_STROKEPATH); + } + d->outsvg += "\n\t"; + d->outsvg += "\n\td=\""; // this is the ONLY place d=" should be used!!!! One exception, gradientfill. + d->outsvg += d->path; + d->outsvg += " \" /> \n"; + d->path = ""; + } + // reset the flags + d->mask = 0; + d->drawtype = 0; + } + // std::cout << "AFTER DRAW logic d->mask: " << std::hex << d->mask << " emr_mask: " << emr_mask << std::dec << + // std::endl; - // d->defs holds any defines which are read in. + switch (iType) { + case U_EMR_HEADER: { + dbg_str << "\n"; - tmp_outsvg << "\n\n\n"; // start of main body + d->outdef += "\n"; - if (pEmr->nHandles) { - d->n_obj = pEmr->nHandles; - d->emf_obj = new EMF_OBJECT[d->n_obj]; + if (d->pDesc) { + d->outdef += "\n"; + } - // Init the new emf_obj list elements to null, provided the - // dynamic allocation succeeded. - if ( d->emf_obj != nullptr ) - { - for( int i=0; i < d->n_obj; ++i ) - d->emf_obj[i].lpEMFR = nullptr; - } //if + PU_EMRHEADER pEmr = (PU_EMRHEADER)lpEMFR; + SVGOStringStream tmp_outdef; + tmp_outdef << "MM100InX = pEmr->rclFrame.right - pEmr->rclFrame.left + 1; + d->MM100InY = pEmr->rclFrame.bottom - pEmr->rclFrame.top + 1; + d->PixelsInX = pEmr->rclBounds.right - pEmr->rclBounds.left + 1; + d->PixelsInY = pEmr->rclBounds.bottom - pEmr->rclBounds.top + 1; + + /* + calculate ratio of Inkscape dpi/EMF device dpi + This can cause problems later due to accuracy limits in the EMF. A high resolution + EMF might have a final D2Pscale[XY] of 0.074998, and adjusting the (integer) device size + by 1 will still not get it exactly to 0.075. Later when the font size is calculated it + can end up as 29.9992 or 22.4994 instead of the intended 30 or 22.5. This is handled by + snapping font sizes to the nearest .01. The best estimate is made by using both values. + */ + if ((pEmr->szlMillimeters.cx + pEmr->szlMillimeters.cy) && (pEmr->szlDevice.cx + pEmr->szlDevice.cy)) { + d->E2IdirY = 1.0; // assume MM_TEXT, if not, this will be changed later + d->D2PscaleX = d->D2PscaleY = Inkscape::Util::Quantity::convert(1, "mm", "px") * + (double)(pEmr->szlMillimeters.cx + pEmr->szlMillimeters.cy) / + (double)(pEmr->szlDevice.cx + pEmr->szlDevice.cy); + } + trinfo_load_qe(d->tri, d->D2PscaleX); /* quantization error that will affect text positions */ - } else { - d->emf_obj = nullptr; - } + /* Adobe Illustrator files set mapmode to MM_ANISOTROPIC and somehow or other this + converts the rclFrame values from MM_HIMETRIC to MM_HIENGLISH, with another factor of 3 thrown + in for good measure. Ours not to question why... + */ + if (AI_hack(pEmr)) { + d->MM100InX *= 25.4 / (10.0 * 3.0); + d->MM100InY *= 25.4 / (10.0 * 3.0); + d->D2PscaleX *= 25.4 / (10.0 * 3.0); + d->D2PscaleY *= 25.4 / (10.0 * 3.0); + } - break; - } - case U_EMR_POLYBEZIER: - { - dbg_str << "\n"; + d->MMX = d->MM100InX / 100.0; + d->MMY = d->MM100InY / 100.0; - PU_EMRPOLYBEZIER pEmr = (PU_EMRPOLYBEZIER) lpEMFR; - uint32_t i,j; + d->PixelsOutX = Inkscape::Util::Quantity::convert(d->MMX, "mm", "px"); + d->PixelsOutY = Inkscape::Util::Quantity::convert(d->MMY, "mm", "px"); - if (pEmr->cptl<4) - break; + // Upper left corner, from header rclBounds, in device units, usually both 0, but not always + d->ulCornerInX = pEmr->rclBounds.left; + d->ulCornerInY = pEmr->rclBounds.top; + d->ulCornerOutX = d->ulCornerInX * d->D2PscaleX; + d->ulCornerOutY = d->ulCornerInY * d->E2IdirY * d->D2PscaleY; - d->mask |= emr_mask; + tmp_outdef << " width=\"" << d->MMX << "mm\"\n" + << " height=\"" << d->MMY << "mm\">\n"; + d->outdef += tmp_outdef.str().c_str(); + d->outdef += ""; // temporary end of header - tmp_str << - "\n\tM " << - pix_to_xy( d, pEmr->aptl[0].x, pEmr->aptl[0].y) << " "; + // d->defs holds any defines which are read in. - for (i=1; icptl; ) { - tmp_str << "\n\tC "; - for (j=0; j<3 && icptl; j++,i++) { - tmp_str << pix_to_xy( d, pEmr->aptl[i].x, pEmr->aptl[i].y) << " "; + tmp_outsvg << "\n\n\n"; // start of main body + + if (pEmr->nHandles) { + d->n_obj = pEmr->nHandles; + d->emf_obj = new EMF_OBJECT[d->n_obj]; + + // Init the new emf_obj list elements to null, provided the + // dynamic allocation succeeded. + if (d->emf_obj != nullptr) { + for (int i = 0; i < d->n_obj; ++i) + d->emf_obj[i].lpEMFR = nullptr; + } // if + + } else { + d->emf_obj = nullptr; } + + break; } + case U_EMR_POLYBEZIER: { + dbg_str << "\n"; - tmp_path << tmp_str.str().c_str(); + PU_EMRPOLYBEZIER pEmr = (PU_EMRPOLYBEZIER)lpEMFR; + uint32_t i, j; - break; - } - case U_EMR_POLYGON: - { - dbg_str << "\n"; + if (pEmr->cptl < 4) + break; - PU_EMRPOLYGON pEmr = (PU_EMRPOLYGON) lpEMFR; - uint32_t i; + d->mask |= emr_mask; - if (pEmr->cptl < 2) - break; + tmp_str << "\n\tM " << pix_to_xy(d, pEmr->aptl[0].x, pEmr->aptl[0].y) << " "; - d->mask |= emr_mask; + for (i = 1; i < pEmr->cptl;) { + tmp_str << "\n\tC "; + for (j = 0; j < 3 && i < pEmr->cptl; j++, i++) { + tmp_str << pix_to_xy(d, pEmr->aptl[i].x, pEmr->aptl[i].y) << " "; + } + } - tmp_str << - "\n\tM " << - pix_to_xy( d, pEmr->aptl[0].x, pEmr->aptl[0].y ) << " "; + tmp_path << tmp_str.str().c_str(); - for (i=1; icptl; i++) { - tmp_str << - "\n\tL " << - pix_to_xy( d, pEmr->aptl[i].x, pEmr->aptl[i].y ) << " "; + break; } + case U_EMR_POLYGON: { + dbg_str << "\n"; - tmp_path << tmp_str.str().c_str(); - tmp_path << " z"; + PU_EMRPOLYGON pEmr = (PU_EMRPOLYGON)lpEMFR; + uint32_t i; - break; - } - case U_EMR_POLYLINE: - { - dbg_str << "\n"; + if (pEmr->cptl < 2) + break; - PU_EMRPOLYLINE pEmr = (PU_EMRPOLYLINE) lpEMFR; - uint32_t i; + d->mask |= emr_mask; - if (pEmr->cptl<2) - break; + tmp_str << "\n\tM " << pix_to_xy(d, pEmr->aptl[0].x, pEmr->aptl[0].y) << " "; - d->mask |= emr_mask; + for (i = 1; i < pEmr->cptl; i++) { + tmp_str << "\n\tL " << pix_to_xy(d, pEmr->aptl[i].x, pEmr->aptl[i].y) << " "; + } - tmp_str << - "\n\tM " << - pix_to_xy( d, pEmr->aptl[0].x, pEmr->aptl[0].y ) << " "; + tmp_path << tmp_str.str().c_str(); + tmp_path << " z"; - for (i=1; icptl; i++) { - tmp_str << - "\n\tL " << - pix_to_xy( d, pEmr->aptl[i].x, pEmr->aptl[i].y ) << " "; + break; } + case U_EMR_POLYLINE: { + dbg_str << "\n"; - tmp_path << tmp_str.str().c_str(); + PU_EMRPOLYLINE pEmr = (PU_EMRPOLYLINE)lpEMFR; + uint32_t i; - break; - } - case U_EMR_POLYBEZIERTO: - { - dbg_str << "\n"; + if (pEmr->cptl < 2) + break; - PU_EMRPOLYBEZIERTO pEmr = (PU_EMRPOLYBEZIERTO) lpEMFR; - uint32_t i,j; + d->mask |= emr_mask; - d->mask |= emr_mask; + tmp_str << "\n\tM " << pix_to_xy(d, pEmr->aptl[0].x, pEmr->aptl[0].y) << " "; - for (i=0; icptl;) { - tmp_path << "\n\tC "; - for (j=0; j<3 && icptl; j++,i++) { - tmp_path << - pix_to_xy( d, pEmr->aptl[i].x, pEmr->aptl[i].y ) << " "; + for (i = 1; i < pEmr->cptl; i++) { + tmp_str << "\n\tL " << pix_to_xy(d, pEmr->aptl[i].x, pEmr->aptl[i].y) << " "; } - } - - break; - } - case U_EMR_POLYLINETO: - { - dbg_str << "\n"; - PU_EMRPOLYLINETO pEmr = (PU_EMRPOLYLINETO) lpEMFR; - uint32_t i; + tmp_path << tmp_str.str().c_str(); - d->mask |= emr_mask; - - for (i=0; icptl;i++) { - tmp_path << - "\n\tL " << - pix_to_xy( d, pEmr->aptl[i].x, pEmr->aptl[i].y ) << " "; + break; } + case U_EMR_POLYBEZIERTO: { + dbg_str << "\n"; - break; - } - case U_EMR_POLYPOLYLINE: - case U_EMR_POLYPOLYGON: - { - if (lpEMFR->iType == U_EMR_POLYPOLYLINE) - dbg_str << "\n"; - if (lpEMFR->iType == U_EMR_POLYPOLYGON) - dbg_str << "\n"; + PU_EMRPOLYBEZIERTO pEmr = (PU_EMRPOLYBEZIERTO)lpEMFR; + uint32_t i, j; - PU_EMRPOLYPOLYGON pEmr = (PU_EMRPOLYPOLYGON) lpEMFR; - unsigned int n, i, j; + d->mask |= emr_mask; - d->mask |= emr_mask; + for (i = 0; i < pEmr->cptl;) { + tmp_path << "\n\tC "; + for (j = 0; j < 3 && i < pEmr->cptl; j++, i++) { + tmp_path << pix_to_xy(d, pEmr->aptl[i].x, pEmr->aptl[i].y) << " "; + } + } - U_POINTL *aptl = (PU_POINTL) &pEmr->aPolyCounts[pEmr->nPolys]; + break; + } + case U_EMR_POLYLINETO: { + dbg_str << "\n"; - i = 0; - for (n=0; nnPolys && icptl; n++) { - SVGOStringStream poly_path; + PU_EMRPOLYLINETO pEmr = (PU_EMRPOLYLINETO)lpEMFR; + uint32_t i; - poly_path << "\n\tM " << pix_to_xy( d, aptl[i].x, aptl[i].y) << " "; - i++; + d->mask |= emr_mask; - for (j=1; jaPolyCounts[n] && icptl; j++) { - poly_path << "\n\tL " << pix_to_xy( d, aptl[i].x, aptl[i].y) << " "; - i++; + for (i = 0; i < pEmr->cptl; i++) { + tmp_path << "\n\tL " << pix_to_xy(d, pEmr->aptl[i].x, pEmr->aptl[i].y) << " "; } - tmp_str << poly_path.str().c_str(); - if (lpEMFR->iType == U_EMR_POLYPOLYGON) - tmp_str << " z"; - tmp_str << " \n"; + break; } + case U_EMR_POLYPOLYLINE: + case U_EMR_POLYPOLYGON: { + if (lpEMFR->iType == U_EMR_POLYPOLYLINE) + dbg_str << "\n"; + if (lpEMFR->iType == U_EMR_POLYPOLYGON) + dbg_str << "\n"; - tmp_path << tmp_str.str().c_str(); + PU_EMRPOLYPOLYGON pEmr = (PU_EMRPOLYPOLYGON)lpEMFR; + unsigned int n, i, j; - break; - } - case U_EMR_SETWINDOWEXTEX: - { - dbg_str << "\n"; + d->mask |= emr_mask; - PU_EMRSETWINDOWEXTEX pEmr = (PU_EMRSETWINDOWEXTEX) lpEMFR; + U_POINTL *aptl = (PU_POINTL)&pEmr->aPolyCounts[pEmr->nPolys]; - d->dc[d->level].sizeWnd = pEmr->szlExtent; + i = 0; + for (n = 0; n < pEmr->nPolys && i < pEmr->cptl; n++) { + SVGOStringStream poly_path; - if (!d->dc[d->level].sizeWnd.cx || !d->dc[d->level].sizeWnd.cy) { - d->dc[d->level].sizeWnd = d->dc[d->level].sizeView; - if (!d->dc[d->level].sizeWnd.cx || !d->dc[d->level].sizeWnd.cy) { - d->dc[d->level].sizeWnd.cx = d->PixelsOutX; - d->dc[d->level].sizeWnd.cy = d->PixelsOutY; - } - } + poly_path << "\n\tM " << pix_to_xy(d, aptl[i].x, aptl[i].y) << " "; + i++; - if (!d->dc[d->level].sizeView.cx || !d->dc[d->level].sizeView.cy) { - d->dc[d->level].sizeView = d->dc[d->level].sizeWnd; - } + for (j = 1; j < pEmr->aPolyCounts[n] && i < pEmr->cptl; j++) { + poly_path << "\n\tL " << pix_to_xy(d, aptl[i].x, aptl[i].y) << " "; + i++; + } - /* scales logical to EMF pixels, transfer a negative sign on Y, if any */ - if (d->dc[d->level].sizeWnd.cx && d->dc[d->level].sizeWnd.cy) { - d->dc[d->level].ScaleInX = (double) d->dc[d->level].sizeView.cx / (double) d->dc[d->level].sizeWnd.cx; - d->dc[d->level].ScaleInY = (double) d->dc[d->level].sizeView.cy / (double) d->dc[d->level].sizeWnd.cy; - if(d->dc[d->level].ScaleInY < 0){ - d->dc[d->level].ScaleInY *= -1.0; - d->E2IdirY = -1.0; + tmp_str << poly_path.str().c_str(); + if (lpEMFR->iType == U_EMR_POLYPOLYGON) + tmp_str << " z"; + tmp_str << " \n"; } + + tmp_path << tmp_str.str().c_str(); + + break; } - else { - d->dc[d->level].ScaleInX = 1; - d->dc[d->level].ScaleInY = 1; - } - break; - } - case U_EMR_SETWINDOWORGEX: - { - dbg_str << "\n"; + case U_EMR_SETWINDOWEXTEX: { + dbg_str << "\n"; - PU_EMRSETWINDOWORGEX pEmr = (PU_EMRSETWINDOWORGEX) lpEMFR; - d->dc[d->level].winorg = pEmr->ptlOrigin; - break; - } - case U_EMR_SETVIEWPORTEXTEX: - { - dbg_str << "\n"; + PU_EMRSETWINDOWEXTEX pEmr = (PU_EMRSETWINDOWEXTEX)lpEMFR; - PU_EMRSETVIEWPORTEXTEX pEmr = (PU_EMRSETVIEWPORTEXTEX) lpEMFR; + d->dc[d->level].sizeWnd = pEmr->szlExtent; - d->dc[d->level].sizeView = pEmr->szlExtent; + if (!d->dc[d->level].sizeWnd.cx || !d->dc[d->level].sizeWnd.cy) { + d->dc[d->level].sizeWnd = d->dc[d->level].sizeView; + if (!d->dc[d->level].sizeWnd.cx || !d->dc[d->level].sizeWnd.cy) { + d->dc[d->level].sizeWnd.cx = d->PixelsOutX; + d->dc[d->level].sizeWnd.cy = d->PixelsOutY; + } + } - if (!d->dc[d->level].sizeView.cx || !d->dc[d->level].sizeView.cy) { - d->dc[d->level].sizeView = d->dc[d->level].sizeWnd; if (!d->dc[d->level].sizeView.cx || !d->dc[d->level].sizeView.cy) { - d->dc[d->level].sizeView.cx = d->PixelsOutX; - d->dc[d->level].sizeView.cy = d->PixelsOutY; + d->dc[d->level].sizeView = d->dc[d->level].sizeWnd; } - } - if (!d->dc[d->level].sizeWnd.cx || !d->dc[d->level].sizeWnd.cy) { - d->dc[d->level].sizeWnd = d->dc[d->level].sizeView; - } + /* scales logical to EMF pixels, transfer a negative sign on Y, if any */ + if (d->dc[d->level].sizeWnd.cx && d->dc[d->level].sizeWnd.cy) { + d->dc[d->level].ScaleInX = (double)d->dc[d->level].sizeView.cx / (double)d->dc[d->level].sizeWnd.cx; + d->dc[d->level].ScaleInY = (double)d->dc[d->level].sizeView.cy / (double)d->dc[d->level].sizeWnd.cy; + if (d->dc[d->level].ScaleInY < 0) { + d->dc[d->level].ScaleInY *= -1.0; + d->E2IdirY = -1.0; + } + } else { + d->dc[d->level].ScaleInX = 1; + d->dc[d->level].ScaleInY = 1; + } + break; + } + case U_EMR_SETWINDOWORGEX: { + dbg_str << "\n"; + + PU_EMRSETWINDOWORGEX pEmr = (PU_EMRSETWINDOWORGEX)lpEMFR; + d->dc[d->level].winorg = pEmr->ptlOrigin; + break; + } + case U_EMR_SETVIEWPORTEXTEX: { + dbg_str << "\n"; + + PU_EMRSETVIEWPORTEXTEX pEmr = (PU_EMRSETVIEWPORTEXTEX)lpEMFR; + + d->dc[d->level].sizeView = pEmr->szlExtent; + + if (!d->dc[d->level].sizeView.cx || !d->dc[d->level].sizeView.cy) { + d->dc[d->level].sizeView = d->dc[d->level].sizeWnd; + if (!d->dc[d->level].sizeView.cx || !d->dc[d->level].sizeView.cy) { + d->dc[d->level].sizeView.cx = d->PixelsOutX; + d->dc[d->level].sizeView.cy = d->PixelsOutY; + } + } + + if (!d->dc[d->level].sizeWnd.cx || !d->dc[d->level].sizeWnd.cy) { + d->dc[d->level].sizeWnd = d->dc[d->level].sizeView; + } - /* scales logical to EMF pixels, transfer a negative sign on Y, if any */ - if (d->dc[d->level].sizeWnd.cx && d->dc[d->level].sizeWnd.cy) { - d->dc[d->level].ScaleInX = (double) d->dc[d->level].sizeView.cx / (double) d->dc[d->level].sizeWnd.cx; - d->dc[d->level].ScaleInY = (double) d->dc[d->level].sizeView.cy / (double) d->dc[d->level].sizeWnd.cy; - if( d->dc[d->level].ScaleInY < 0){ - d->dc[d->level].ScaleInY *= -1.0; - d->E2IdirY = -1.0; + /* scales logical to EMF pixels, transfer a negative sign on Y, if any */ + if (d->dc[d->level].sizeWnd.cx && d->dc[d->level].sizeWnd.cy) { + d->dc[d->level].ScaleInX = (double)d->dc[d->level].sizeView.cx / (double)d->dc[d->level].sizeWnd.cx; + d->dc[d->level].ScaleInY = (double)d->dc[d->level].sizeView.cy / (double)d->dc[d->level].sizeWnd.cy; + if (d->dc[d->level].ScaleInY < 0) { + d->dc[d->level].ScaleInY *= -1.0; + d->E2IdirY = -1.0; + } + } else { + d->dc[d->level].ScaleInX = 1; + d->dc[d->level].ScaleInY = 1; } + break; } - else { - d->dc[d->level].ScaleInX = 1; - d->dc[d->level].ScaleInY = 1; + case U_EMR_SETVIEWPORTORGEX: { + dbg_str << "\n"; + + PU_EMRSETVIEWPORTORGEX pEmr = (PU_EMRSETVIEWPORTORGEX)lpEMFR; + d->dc[d->level].vieworg = pEmr->ptlOrigin; + break; } - break; - } - case U_EMR_SETVIEWPORTORGEX: - { - dbg_str << "\n"; + case U_EMR_SETBRUSHORGEX: + dbg_str << "\n"; + break; + case U_EMR_EOF: { + dbg_str << "\n"; - PU_EMRSETVIEWPORTORGEX pEmr = (PU_EMRSETVIEWPORTORGEX) lpEMFR; - d->dc[d->level].vieworg = pEmr->ptlOrigin; - break; - } - case U_EMR_SETBRUSHORGEX: dbg_str << "\n"; break; - case U_EMR_EOF: - { - dbg_str << "\n"; - - tmp_outsvg << "\n"; - d->outsvg = d->outdef + d->defs + d->outsvg; - OK=0; - break; - } - case U_EMR_SETPIXELV: dbg_str << "\n"; break; - case U_EMR_SETMAPPERFLAGS: dbg_str << "\n"; break; - case U_EMR_SETMAPMODE: - { - dbg_str << "\n"; - PU_EMRSETMAPMODE pEmr = (PU_EMRSETMAPMODE) lpEMFR; - switch (pEmr->iMode){ - case U_MM_TEXT: - default: - // Use all values from the header. - break; - /* For all of the following the indicated scale this will be encoded in WindowExtEx/ViewportExtex - and show up in ScaleIn[XY] - */ - case U_MM_LOMETRIC: // 1 LU = 0.1 mm, - case U_MM_HIMETRIC: // 1 LU = 0.01 mm - case U_MM_LOENGLISH: // 1 LU = 0.1 in - case U_MM_HIENGLISH: // 1 LU = 0.01 in - case U_MM_TWIPS: // 1 LU = 1/1440 in - d->E2IdirY = -1.0; - // Use d->D2Pscale[XY] values from the header. - break; - case U_MM_ISOTROPIC: // ScaleIn[XY] should be set elsewhere by SETVIEWPORTEXTEX and SETWINDOWEXTEX - case U_MM_ANISOTROPIC: - break; + tmp_outsvg << "\n"; + d->outsvg = d->outdef + d->defs + d->outsvg; + OK = 0; + break; } - break; - } - case U_EMR_SETBKMODE: - { - dbg_str << "\n"; - PU_EMRSETBKMODE pEmr = (PU_EMRSETBKMODE) lpEMFR; - tbkMode = pEmr->iMode; - if(tbkMode != d->dc[d->level].bkMode){ - d->dc[d->level].dirty |= DIRTY_TEXT; - if(tbkMode != d->dc[d->level].bkMode){ - if(d->dc[d->level].fill_mode == DRAW_PATTERN){ d->dc[d->level].dirty |= DIRTY_FILL; } - if(d->dc[d->level].stroke_mode == DRAW_PATTERN){ d->dc[d->level].dirty |= DIRTY_STROKE; } + case U_EMR_SETPIXELV: + dbg_str << "\n"; + break; + case U_EMR_SETMAPPERFLAGS: + dbg_str << "\n"; + break; + case U_EMR_SETMAPMODE: { + dbg_str << "\n"; + PU_EMRSETMAPMODE pEmr = (PU_EMRSETMAPMODE)lpEMFR; + switch (pEmr->iMode) { + case U_MM_TEXT: + default: + // Use all values from the header. + break; + /* For all of the following the indicated scale this will be encoded in WindowExtEx/ViewportExtex + and show up in ScaleIn[XY] + */ + case U_MM_LOMETRIC: // 1 LU = 0.1 mm, + case U_MM_HIMETRIC: // 1 LU = 0.01 mm + case U_MM_LOENGLISH: // 1 LU = 0.1 in + case U_MM_HIENGLISH: // 1 LU = 0.01 in + case U_MM_TWIPS: // 1 LU = 1/1440 in + d->E2IdirY = -1.0; + // Use d->D2Pscale[XY] values from the header. + break; + case U_MM_ISOTROPIC: // ScaleIn[XY] should be set elsewhere by SETVIEWPORTEXTEX and SETWINDOWEXTEX + case U_MM_ANISOTROPIC: + break; } - memcpy(&tbkColor,&(d->dc[d->level].bkColor),sizeof(U_COLORREF)); + break; } - break; - } - case U_EMR_SETPOLYFILLMODE: - { - dbg_str << "\n"; - - PU_EMRSETPOLYFILLMODE pEmr = (PU_EMRSETPOLYFILLMODE) lpEMFR; - d->dc[d->level].style.fill_rule.value = - (pEmr->iMode == U_ALTERNATE - ? SP_WIND_RULE_NONZERO - : (pEmr->iMode == U_WINDING ? SP_WIND_RULE_INTERSECT : SP_WIND_RULE_NONZERO)); - break; - } - case U_EMR_SETROP2: - { - dbg_str << "\n"; - PU_EMRSETROP2 pEmr = (PU_EMRSETROP2) lpEMFR; - d->dwRop2 = pEmr->iMode; - break; - } - case U_EMR_SETSTRETCHBLTMODE: - { - PU_EMRSETSTRETCHBLTMODE pEmr = (PU_EMRSETSTRETCHBLTMODE) lpEMFR; // from wingdi.h - BLTmode = pEmr->iMode; - dbg_str << "\n"; - break; - } - case U_EMR_SETTEXTALIGN: - { - dbg_str << "\n"; + case U_EMR_SETBKMODE: { + dbg_str << "\n"; + PU_EMRSETBKMODE pEmr = (PU_EMRSETBKMODE)lpEMFR; + tbkMode = pEmr->iMode; + if (tbkMode != d->dc[d->level].bkMode) { + d->dc[d->level].dirty |= DIRTY_TEXT; + if (tbkMode != d->dc[d->level].bkMode) { + if (d->dc[d->level].fill_mode == DRAW_PATTERN) { + d->dc[d->level].dirty |= DIRTY_FILL; + } + if (d->dc[d->level].stroke_mode == DRAW_PATTERN) { + d->dc[d->level].dirty |= DIRTY_STROKE; + } + } + memcpy(&tbkColor, &(d->dc[d->level].bkColor), sizeof(U_COLORREF)); + } + break; + } + case U_EMR_SETPOLYFILLMODE: { + dbg_str << "\n"; - PU_EMRSETTEXTALIGN pEmr = (PU_EMRSETTEXTALIGN) lpEMFR; - d->dc[d->level].textAlign = pEmr->iMode; - break; - } - case U_EMR_SETCOLORADJUSTMENT: - dbg_str << "\n"; - break; - case U_EMR_SETTEXTCOLOR: - { - dbg_str << "\n"; + PU_EMRSETPOLYFILLMODE pEmr = (PU_EMRSETPOLYFILLMODE)lpEMFR; + d->dc[d->level].style.fill_rule.value = + (pEmr->iMode == U_ALTERNATE + ? SP_WIND_RULE_NONZERO + : (pEmr->iMode == U_WINDING ? SP_WIND_RULE_INTERSECT : SP_WIND_RULE_NONZERO)); + break; + } + case U_EMR_SETROP2: { + dbg_str << "\n"; + PU_EMRSETROP2 pEmr = (PU_EMRSETROP2)lpEMFR; + d->dwRop2 = pEmr->iMode; + break; + } + case U_EMR_SETSTRETCHBLTMODE: { + PU_EMRSETSTRETCHBLTMODE pEmr = (PU_EMRSETSTRETCHBLTMODE)lpEMFR; // from wingdi.h + BLTmode = pEmr->iMode; + dbg_str << "\n"; + break; + } + case U_EMR_SETTEXTALIGN: { + dbg_str << "\n"; - PU_EMRSETTEXTCOLOR pEmr = (PU_EMRSETTEXTCOLOR) lpEMFR; - d->dc[d->level].textColor = pEmr->crColor; - if(tbkMode != d->dc[d->level].bkMode){ - if(d->dc[d->level].fill_mode == DRAW_PATTERN){ d->dc[d->level].dirty |= DIRTY_FILL; } - if(d->dc[d->level].stroke_mode == DRAW_PATTERN){ d->dc[d->level].dirty |= DIRTY_STROKE; } + PU_EMRSETTEXTALIGN pEmr = (PU_EMRSETTEXTALIGN)lpEMFR; + d->dc[d->level].textAlign = pEmr->iMode; + break; } - // not text_dirty, because multicolored complex text is supported in libTERE - break; - } - case U_EMR_SETBKCOLOR: - { - dbg_str << "\n"; - - PU_EMRSETBKCOLOR pEmr = (PU_EMRSETBKCOLOR) lpEMFR; - tbkColor = pEmr->crColor; - if(memcmp(&tbkColor, &(d->dc[d->level].bkColor), sizeof(U_COLORREF))){ - d->dc[d->level].dirty |= DIRTY_TEXT; - if(d->dc[d->level].fill_mode == DRAW_PATTERN){ d->dc[d->level].dirty |= DIRTY_FILL; } - if(d->dc[d->level].stroke_mode == DRAW_PATTERN){ d->dc[d->level].dirty |= DIRTY_STROKE; } - tbkMode = d->dc[d->level].bkMode; + case U_EMR_SETCOLORADJUSTMENT: + dbg_str << "\n"; + break; + case U_EMR_SETTEXTCOLOR: { + dbg_str << "\n"; + + PU_EMRSETTEXTCOLOR pEmr = (PU_EMRSETTEXTCOLOR)lpEMFR; + d->dc[d->level].textColor = pEmr->crColor; + if (tbkMode != d->dc[d->level].bkMode) { + if (d->dc[d->level].fill_mode == DRAW_PATTERN) { + d->dc[d->level].dirty |= DIRTY_FILL; + } + if (d->dc[d->level].stroke_mode == DRAW_PATTERN) { + d->dc[d->level].dirty |= DIRTY_STROKE; + } + } + // not text_dirty, because multicolored complex text is supported in libTERE + break; } - break; - } - case U_EMR_OFFSETCLIPRGN: - { - dbg_str << "\n"; - if (d->dc[d->level].clip_id) { // can only offsetan existing clipping path - PU_EMROFFSETCLIPRGN pEmr = (PU_EMROFFSETCLIPRGN) lpEMFR; - U_POINTL off = pEmr->ptlOffset; - unsigned int real_idx = d->dc[d->level].clip_id - 1; - Geom::PathVector tmp_vect = sp_svg_read_pathv(d->clips.strings[real_idx]); - double ox = pix_to_x_point(d, off.x, off.y) - pix_to_x_point(d, 0, 0); // take into account all active transforms - double oy = pix_to_y_point(d, off.x, off.y) - pix_to_y_point(d, 0, 0); - Geom::Affine tf = Geom::Translate(ox,oy); - tmp_vect *= tf; - char *tmp_path = sp_svg_write_path(tmp_vect); - add_clips(d, tmp_path, U_RGN_COPY); - free(tmp_path); + case U_EMR_SETBKCOLOR: { + dbg_str << "\n"; + + PU_EMRSETBKCOLOR pEmr = (PU_EMRSETBKCOLOR)lpEMFR; + tbkColor = pEmr->crColor; + if (memcmp(&tbkColor, &(d->dc[d->level].bkColor), sizeof(U_COLORREF))) { + d->dc[d->level].dirty |= DIRTY_TEXT; + if (d->dc[d->level].fill_mode == DRAW_PATTERN) { + d->dc[d->level].dirty |= DIRTY_FILL; + } + if (d->dc[d->level].stroke_mode == DRAW_PATTERN) { + d->dc[d->level].dirty |= DIRTY_STROKE; + } + tbkMode = d->dc[d->level].bkMode; + } + break; } - break; - } - case U_EMR_MOVETOEX: - { - dbg_str << "\n"; + case U_EMR_OFFSETCLIPRGN: { + dbg_str << "\n"; + if (d->dc[d->level].clip_id) { // can only offsetan existing clipping path + PU_EMROFFSETCLIPRGN pEmr = (PU_EMROFFSETCLIPRGN)lpEMFR; + U_POINTL off = pEmr->ptlOffset; + unsigned int real_idx = d->dc[d->level].clip_id - 1; + Geom::PathVector tmp_vect = sp_svg_read_pathv(d->clips.strings[real_idx]); + double ox = pix_to_x_point(d, off.x, off.y) - + pix_to_x_point(d, 0, 0); // take into account all active transforms + double oy = pix_to_y_point(d, off.x, off.y) - pix_to_y_point(d, 0, 0); + Geom::Affine tf = Geom::Translate(ox, oy); + tmp_vect *= tf; + char *tmp_path = sp_svg_write_path(tmp_vect); + add_clips(d, tmp_path, U_RGN_COPY); + free(tmp_path); + } + break; + } + case U_EMR_MOVETOEX: { + dbg_str << "\n"; - PU_EMRMOVETOEX pEmr = (PU_EMRMOVETOEX) lpEMFR; + PU_EMRMOVETOEX pEmr = (PU_EMRMOVETOEX)lpEMFR; - d->mask |= emr_mask; + d->mask |= emr_mask; - d->dc[d->level].cur = pEmr->ptl; + d->dc[d->level].cur = pEmr->ptl; - tmp_path << - "\n\tM " << pix_to_xy( d, pEmr->ptl.x, pEmr->ptl.y ) << " "; - break; - } - case U_EMR_SETMETARGN: dbg_str << "\n"; break; - case U_EMR_EXCLUDECLIPRECT: - { - dbg_str << "\n"; - - PU_EMREXCLUDECLIPRECT pEmr = (PU_EMREXCLUDECLIPRECT) lpEMFR; - U_RECTL rc = pEmr->rclClip; - - SVGOStringStream tmp_path; - //outer rect, clockwise - tmp_path << "M " << faraway << "," << faraway << " "; - tmp_path << "L " << faraway << "," << -faraway << " "; - tmp_path << "L " << -faraway << "," << -faraway << " "; - tmp_path << "L " << -faraway << "," << faraway << " "; - tmp_path << "z "; - //inner rect, counterclockwise (sign of Y is reversed) - tmp_path << "M " << pix_to_xy( d, rc.left , rc.top ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.right, rc.top ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.right, rc.bottom ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.left, rc.bottom ) << " "; - tmp_path << "z"; - - add_clips(d, tmp_path.str().c_str(), U_RGN_AND); - - d->path = ""; - d->drawtype = 0; - break; - } - case U_EMR_INTERSECTCLIPRECT: - { - dbg_str << "\n"; - - PU_EMRINTERSECTCLIPRECT pEmr = (PU_EMRINTERSECTCLIPRECT) lpEMFR; - U_RECTL rc = pEmr->rclClip; - - SVGOStringStream tmp_path; - tmp_path << "M " << pix_to_xy( d, rc.left , rc.top ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.right, rc.top ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.right, rc.bottom ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.left, rc.bottom ) << " "; - tmp_path << "z"; - - add_clips(d, tmp_path.str().c_str(), U_RGN_AND); - - d->path = ""; - d->drawtype = 0; - break; - } - case U_EMR_SCALEVIEWPORTEXTEX: dbg_str << "\n"; break; - case U_EMR_SCALEWINDOWEXTEX: dbg_str << "\n"; break; - case U_EMR_SAVEDC: - dbg_str << "\n"; - - if (d->level < EMF_MAX_DC) { - d->dc[d->level + 1] = d->dc[d->level]; - if(d->dc[d->level].font_name){ - d->dc[d->level + 1].font_name = strdup(d->dc[d->level].font_name); // or memory access problems because font name pointer duplicated - } - d->level = d->level + 1; + tmp_path << "\n\tM " << pix_to_xy(d, pEmr->ptl.x, pEmr->ptl.y) << " "; + break; } - break; - case U_EMR_RESTOREDC: - { - dbg_str << "\n"; - - PU_EMRRESTOREDC pEmr = (PU_EMRRESTOREDC) lpEMFR; - int old_level = d->level; - if (pEmr->iRelative >= 0) { - if (pEmr->iRelative < d->level) - d->level = pEmr->iRelative; - } - else { - if (d->level + pEmr->iRelative >= 0) - d->level = d->level + pEmr->iRelative; - } - while (old_level > d->level) { - if (!d->dc[old_level].style.stroke_dasharray.values.empty() && - (old_level == 0 || (old_level > 0 && d->dc[old_level].style.stroke_dasharray != - d->dc[old_level - 1].style.stroke_dasharray))) { - d->dc[old_level].style.stroke_dasharray.values.clear(); - } - if(d->dc[old_level].font_name){ - free(d->dc[old_level].font_name); // else memory leak - d->dc[old_level].font_name = nullptr; - } - old_level--; + case U_EMR_SETMETARGN: + dbg_str << "\n"; + break; + case U_EMR_EXCLUDECLIPRECT: { + dbg_str << "\n"; + + PU_EMREXCLUDECLIPRECT pEmr = (PU_EMREXCLUDECLIPRECT)lpEMFR; + U_RECTL rc = pEmr->rclClip; + + SVGOStringStream tmp_path; + // outer rect, clockwise + tmp_path << "M " << faraway << "," << faraway << " "; + tmp_path << "L " << faraway << "," << -faraway << " "; + tmp_path << "L " << -faraway << "," << -faraway << " "; + tmp_path << "L " << -faraway << "," << faraway << " "; + tmp_path << "z "; + // inner rect, counterclockwise (sign of Y is reversed) + tmp_path << "M " << pix_to_xy(d, rc.left, rc.top) << " "; + tmp_path << "L " << pix_to_xy(d, rc.right, rc.top) << " "; + tmp_path << "L " << pix_to_xy(d, rc.right, rc.bottom) << " "; + tmp_path << "L " << pix_to_xy(d, rc.left, rc.bottom) << " "; + tmp_path << "z"; + + add_clips(d, tmp_path.str().c_str(), U_RGN_AND); + + d->path = ""; + d->drawtype = 0; + break; } - break; - } - case U_EMR_SETWORLDTRANSFORM: - { - dbg_str << "\n"; + case U_EMR_INTERSECTCLIPRECT: { + dbg_str << "\n"; - PU_EMRSETWORLDTRANSFORM pEmr = (PU_EMRSETWORLDTRANSFORM) lpEMFR; - d->dc[d->level].worldTransform = pEmr->xform; - break; - } - case U_EMR_MODIFYWORLDTRANSFORM: - { - dbg_str << "\n"; - - PU_EMRMODIFYWORLDTRANSFORM pEmr = (PU_EMRMODIFYWORLDTRANSFORM) lpEMFR; - switch (pEmr->iMode) - { - case U_MWT_IDENTITY: - d->dc[d->level].worldTransform.eM11 = 1.0; - d->dc[d->level].worldTransform.eM12 = 0.0; - d->dc[d->level].worldTransform.eM21 = 0.0; - d->dc[d->level].worldTransform.eM22 = 1.0; - d->dc[d->level].worldTransform.eDx = 0.0; - d->dc[d->level].worldTransform.eDy = 0.0; - break; - case U_MWT_LEFTMULTIPLY: - { -// d->dc[d->level].worldTransform = pEmr->xform * worldTransform; - - float a11 = pEmr->xform.eM11; - float a12 = pEmr->xform.eM12; - float a13 = 0.0; - float a21 = pEmr->xform.eM21; - float a22 = pEmr->xform.eM22; - float a23 = 0.0; - float a31 = pEmr->xform.eDx; - float a32 = pEmr->xform.eDy; - float a33 = 1.0; - - float b11 = d->dc[d->level].worldTransform.eM11; - float b12 = d->dc[d->level].worldTransform.eM12; - //float b13 = 0.0; - float b21 = d->dc[d->level].worldTransform.eM21; - float b22 = d->dc[d->level].worldTransform.eM22; - //float b23 = 0.0; - float b31 = d->dc[d->level].worldTransform.eDx; - float b32 = d->dc[d->level].worldTransform.eDy; - //float b33 = 1.0; - - float c11 = a11*b11 + a12*b21 + a13*b31;; - float c12 = a11*b12 + a12*b22 + a13*b32;; - //float c13 = a11*b13 + a12*b23 + a13*b33;; - float c21 = a21*b11 + a22*b21 + a23*b31;; - float c22 = a21*b12 + a22*b22 + a23*b32;; - //float c23 = a21*b13 + a22*b23 + a23*b33;; - float c31 = a31*b11 + a32*b21 + a33*b31;; - float c32 = a31*b12 + a32*b22 + a33*b32;; - //float c33 = a31*b13 + a32*b23 + a33*b33;; - - d->dc[d->level].worldTransform.eM11 = c11;; - d->dc[d->level].worldTransform.eM12 = c12;; - d->dc[d->level].worldTransform.eM21 = c21;; - d->dc[d->level].worldTransform.eM22 = c22;; - d->dc[d->level].worldTransform.eDx = c31; - d->dc[d->level].worldTransform.eDy = c32; + PU_EMRINTERSECTCLIPRECT pEmr = (PU_EMRINTERSECTCLIPRECT)lpEMFR; + U_RECTL rc = pEmr->rclClip; - break; - } - case U_MWT_RIGHTMULTIPLY: - { -// d->dc[d->level].worldTransform = worldTransform * pEmr->xform; - - float a11 = d->dc[d->level].worldTransform.eM11; - float a12 = d->dc[d->level].worldTransform.eM12; - float a13 = 0.0; - float a21 = d->dc[d->level].worldTransform.eM21; - float a22 = d->dc[d->level].worldTransform.eM22; - float a23 = 0.0; - float a31 = d->dc[d->level].worldTransform.eDx; - float a32 = d->dc[d->level].worldTransform.eDy; - float a33 = 1.0; - - float b11 = pEmr->xform.eM11; - float b12 = pEmr->xform.eM12; - //float b13 = 0.0; - float b21 = pEmr->xform.eM21; - float b22 = pEmr->xform.eM22; - //float b23 = 0.0; - float b31 = pEmr->xform.eDx; - float b32 = pEmr->xform.eDy; - //float b33 = 1.0; - - float c11 = a11*b11 + a12*b21 + a13*b31;; - float c12 = a11*b12 + a12*b22 + a13*b32;; - //float c13 = a11*b13 + a12*b23 + a13*b33;; - float c21 = a21*b11 + a22*b21 + a23*b31;; - float c22 = a21*b12 + a22*b22 + a23*b32;; - //float c23 = a21*b13 + a22*b23 + a23*b33;; - float c31 = a31*b11 + a32*b21 + a33*b31;; - float c32 = a31*b12 + a32*b22 + a33*b32;; - //float c33 = a31*b13 + a32*b23 + a33*b33;; - - d->dc[d->level].worldTransform.eM11 = c11;; - d->dc[d->level].worldTransform.eM12 = c12;; - d->dc[d->level].worldTransform.eM21 = c21;; - d->dc[d->level].worldTransform.eM22 = c22;; - d->dc[d->level].worldTransform.eDx = c31; - d->dc[d->level].worldTransform.eDy = c32; + SVGOStringStream tmp_path; + tmp_path << "M " << pix_to_xy(d, rc.left, rc.top) << " "; + tmp_path << "L " << pix_to_xy(d, rc.right, rc.top) << " "; + tmp_path << "L " << pix_to_xy(d, rc.right, rc.bottom) << " "; + tmp_path << "L " << pix_to_xy(d, rc.left, rc.bottom) << " "; + tmp_path << "z"; - break; + add_clips(d, tmp_path.str().c_str(), U_RGN_AND); + + d->path = ""; + d->drawtype = 0; + break; + } + case U_EMR_SCALEVIEWPORTEXTEX: + dbg_str << "\n"; + break; + case U_EMR_SCALEWINDOWEXTEX: + dbg_str << "\n"; + break; + case U_EMR_SAVEDC: + dbg_str << "\n"; + + if (d->level < EMF_MAX_DC) { + d->dc[d->level + 1] = d->dc[d->level]; + if (d->dc[d->level].font_name) { + d->dc[d->level + 1].font_name = + strdup(d->dc[d->level].font_name); // or memory access problems because font name pointer + // duplicated + } + d->level = d->level + 1; } -// case MWT_SET: - default: - d->dc[d->level].worldTransform = pEmr->xform; - break; + break; + case U_EMR_RESTOREDC: { + dbg_str << "\n"; + + PU_EMRRESTOREDC pEmr = (PU_EMRRESTOREDC)lpEMFR; + int old_level = d->level; + if (pEmr->iRelative >= 0) { + if (pEmr->iRelative < d->level) + d->level = pEmr->iRelative; + } else { + if (d->level + pEmr->iRelative >= 0) + d->level = d->level + pEmr->iRelative; + } + while (old_level > d->level) { + if (!d->dc[old_level].style.stroke_dasharray.values.empty() && + (old_level == 0 || (old_level > 0 && d->dc[old_level].style.stroke_dasharray != + d->dc[old_level - 1].style.stroke_dasharray))) { + d->dc[old_level].style.stroke_dasharray.values.clear(); + } + if (d->dc[old_level].font_name) { + free(d->dc[old_level].font_name); // else memory leak + d->dc[old_level].font_name = nullptr; + } + old_level--; + } + break; } - break; - } - case U_EMR_SELECTOBJECT: - { - dbg_str << "\n"; - - PU_EMRSELECTOBJECT pEmr = (PU_EMRSELECTOBJECT) lpEMFR; - unsigned int index = pEmr->ihObject; - - if (index & U_STOCK_OBJECT) { - switch (index) { - case U_NULL_BRUSH: - d->dc[d->level].fill_mode = DRAW_PAINT; - d->dc[d->level].fill_set = false; + case U_EMR_SETWORLDTRANSFORM: { + dbg_str << "\n"; + + PU_EMRSETWORLDTRANSFORM pEmr = (PU_EMRSETWORLDTRANSFORM)lpEMFR; + d->dc[d->level].worldTransform = pEmr->xform; + break; + } + case U_EMR_MODIFYWORLDTRANSFORM: { + dbg_str << "\n"; + + PU_EMRMODIFYWORLDTRANSFORM pEmr = (PU_EMRMODIFYWORLDTRANSFORM)lpEMFR; + switch (pEmr->iMode) { + case U_MWT_IDENTITY: + d->dc[d->level].worldTransform.eM11 = 1.0; + d->dc[d->level].worldTransform.eM12 = 0.0; + d->dc[d->level].worldTransform.eM21 = 0.0; + d->dc[d->level].worldTransform.eM22 = 1.0; + d->dc[d->level].worldTransform.eDx = 0.0; + d->dc[d->level].worldTransform.eDy = 0.0; break; - case U_BLACK_BRUSH: - case U_DKGRAY_BRUSH: - case U_GRAY_BRUSH: - case U_LTGRAY_BRUSH: - case U_WHITE_BRUSH: - { - float val = 0; - switch (index) { - case U_BLACK_BRUSH: - val = 0.0 / 255.0; - break; - case U_DKGRAY_BRUSH: - val = 64.0 / 255.0; - break; - case U_GRAY_BRUSH: - val = 128.0 / 255.0; - break; - case U_LTGRAY_BRUSH: - val = 192.0 / 255.0; - break; - case U_WHITE_BRUSH: - val = 255.0 / 255.0; - break; - } - d->dc[d->level].style.fill.value.color.set( val, val, val ); + case U_MWT_LEFTMULTIPLY: { + // d->dc[d->level].worldTransform = pEmr->xform * worldTransform; + + float a11 = pEmr->xform.eM11; + float a12 = pEmr->xform.eM12; + float a13 = 0.0; + float a21 = pEmr->xform.eM21; + float a22 = pEmr->xform.eM22; + float a23 = 0.0; + float a31 = pEmr->xform.eDx; + float a32 = pEmr->xform.eDy; + float a33 = 1.0; + + float b11 = d->dc[d->level].worldTransform.eM11; + float b12 = d->dc[d->level].worldTransform.eM12; + // float b13 = 0.0; + float b21 = d->dc[d->level].worldTransform.eM21; + float b22 = d->dc[d->level].worldTransform.eM22; + // float b23 = 0.0; + float b31 = d->dc[d->level].worldTransform.eDx; + float b32 = d->dc[d->level].worldTransform.eDy; + // float b33 = 1.0; + + float c11 = a11 * b11 + a12 * b21 + a13 * b31; + ; + float c12 = a11 * b12 + a12 * b22 + a13 * b32; + ; + // float c13 = a11*b13 + a12*b23 + a13*b33;; + float c21 = a21 * b11 + a22 * b21 + a23 * b31; + ; + float c22 = a21 * b12 + a22 * b22 + a23 * b32; + ; + // float c23 = a21*b13 + a22*b23 + a23*b33;; + float c31 = a31 * b11 + a32 * b21 + a33 * b31; + ; + float c32 = a31 * b12 + a32 * b22 + a33 * b32; + ; + // float c33 = a31*b13 + a32*b23 + a33*b33;; + + d->dc[d->level].worldTransform.eM11 = c11; + ; + d->dc[d->level].worldTransform.eM12 = c12; + ; + d->dc[d->level].worldTransform.eM21 = c21; + ; + d->dc[d->level].worldTransform.eM22 = c22; + ; + d->dc[d->level].worldTransform.eDx = c31; + d->dc[d->level].worldTransform.eDy = c32; - d->dc[d->level].fill_mode = DRAW_PAINT; - d->dc[d->level].fill_set = true; break; } - case U_NULL_PEN: - d->dc[d->level].stroke_mode = DRAW_PAINT; - d->dc[d->level].stroke_set = false; - break; - case U_BLACK_PEN: - case U_WHITE_PEN: - { - float val = index == U_BLACK_PEN ? 0 : 1; - d->dc[d->level].style.stroke_dasharray.set = false; - d->dc[d->level].style.stroke_width.value = 1.0; - d->dc[d->level].style.stroke.value.color.set( val, val, val ); - - d->dc[d->level].stroke_mode = DRAW_PAINT; - d->dc[d->level].stroke_set = true; + case U_MWT_RIGHTMULTIPLY: { + // d->dc[d->level].worldTransform = worldTransform * pEmr->xform; + + float a11 = d->dc[d->level].worldTransform.eM11; + float a12 = d->dc[d->level].worldTransform.eM12; + float a13 = 0.0; + float a21 = d->dc[d->level].worldTransform.eM21; + float a22 = d->dc[d->level].worldTransform.eM22; + float a23 = 0.0; + float a31 = d->dc[d->level].worldTransform.eDx; + float a32 = d->dc[d->level].worldTransform.eDy; + float a33 = 1.0; + + float b11 = pEmr->xform.eM11; + float b12 = pEmr->xform.eM12; + // float b13 = 0.0; + float b21 = pEmr->xform.eM21; + float b22 = pEmr->xform.eM22; + // float b23 = 0.0; + float b31 = pEmr->xform.eDx; + float b32 = pEmr->xform.eDy; + // float b33 = 1.0; + + float c11 = a11 * b11 + a12 * b21 + a13 * b31; + ; + float c12 = a11 * b12 + a12 * b22 + a13 * b32; + ; + // float c13 = a11*b13 + a12*b23 + a13*b33;; + float c21 = a21 * b11 + a22 * b21 + a23 * b31; + ; + float c22 = a21 * b12 + a22 * b22 + a23 * b32; + ; + // float c23 = a21*b13 + a22*b23 + a23*b33;; + float c31 = a31 * b11 + a32 * b21 + a33 * b31; + ; + float c32 = a31 * b12 + a32 * b22 + a33 * b32; + ; + // float c33 = a31*b13 + a32*b23 + a33*b33;; + + d->dc[d->level].worldTransform.eM11 = c11; + ; + d->dc[d->level].worldTransform.eM12 = c12; + ; + d->dc[d->level].worldTransform.eM21 = c21; + ; + d->dc[d->level].worldTransform.eM22 = c22; + ; + d->dc[d->level].worldTransform.eDx = c31; + d->dc[d->level].worldTransform.eDy = c32; break; } + // case MWT_SET: + default: + d->dc[d->level].worldTransform = pEmr->xform; + break; } - } else { - if ( /*index >= 0 &&*/ index < (unsigned int) d->n_obj) { - switch (d->emf_obj[index].type) - { - case U_EMR_CREATEPEN: - select_pen(d, index); + break; + } + case U_EMR_SELECTOBJECT: { + dbg_str << "\n"; + + PU_EMRSELECTOBJECT pEmr = (PU_EMRSELECTOBJECT)lpEMFR; + unsigned int index = pEmr->ihObject; + + if (index & U_STOCK_OBJECT) { + switch (index) { + case U_NULL_BRUSH: + d->dc[d->level].fill_mode = DRAW_PAINT; + d->dc[d->level].fill_set = false; break; - case U_EMR_CREATEBRUSHINDIRECT: - case U_EMR_CREATEDIBPATTERNBRUSHPT: - case U_EMR_CREATEMONOBRUSH: - select_brush(d, index); + case U_BLACK_BRUSH: + case U_DKGRAY_BRUSH: + case U_GRAY_BRUSH: + case U_LTGRAY_BRUSH: + case U_WHITE_BRUSH: { + float val = 0; + switch (index) { + case U_BLACK_BRUSH: + val = 0.0 / 255.0; + break; + case U_DKGRAY_BRUSH: + val = 64.0 / 255.0; + break; + case U_GRAY_BRUSH: + val = 128.0 / 255.0; + break; + case U_LTGRAY_BRUSH: + val = 192.0 / 255.0; + break; + case U_WHITE_BRUSH: + val = 255.0 / 255.0; + break; + } + d->dc[d->level].style.fill.value.color.set(val, val, val); + + d->dc[d->level].fill_mode = DRAW_PAINT; + d->dc[d->level].fill_set = true; break; - case U_EMR_EXTCREATEPEN: - select_extpen(d, index); + } + case U_NULL_PEN: + d->dc[d->level].stroke_mode = DRAW_PAINT; + d->dc[d->level].stroke_set = false; break; - case U_EMR_EXTCREATEFONTINDIRECTW: - select_font(d, index); + case U_BLACK_PEN: + case U_WHITE_PEN: { + float val = index == U_BLACK_PEN ? 0 : 1; + d->dc[d->level].style.stroke_dasharray.set = false; + d->dc[d->level].style.stroke_width.value = 1.0; + d->dc[d->level].style.stroke.value.color.set(val, val, val); + + d->dc[d->level].stroke_mode = DRAW_PAINT; + d->dc[d->level].stroke_set = true; + break; + } + } + } else { + if (/*index >= 0 &&*/ index < (unsigned int)d->n_obj) { + switch (d->emf_obj[index].type) { + case U_EMR_CREATEPEN: + select_pen(d, index); + break; + case U_EMR_CREATEBRUSHINDIRECT: + case U_EMR_CREATEDIBPATTERNBRUSHPT: + case U_EMR_CREATEMONOBRUSH: + select_brush(d, index); + break; + case U_EMR_EXTCREATEPEN: + select_extpen(d, index); + break; + case U_EMR_EXTCREATEFONTINDIRECTW: + select_font(d, index); + break; + } } } + break; } - break; - } - case U_EMR_CREATEPEN: - { - dbg_str << "\n"; + case U_EMR_CREATEPEN: { + dbg_str << "\n"; - PU_EMRCREATEPEN pEmr = (PU_EMRCREATEPEN) lpEMFR; - insert_object(d, pEmr->ihPen, U_EMR_CREATEPEN, lpEMFR); - break; - } - case U_EMR_CREATEBRUSHINDIRECT: - { - dbg_str << "\n"; + PU_EMRCREATEPEN pEmr = (PU_EMRCREATEPEN)lpEMFR; + insert_object(d, pEmr->ihPen, U_EMR_CREATEPEN, lpEMFR); + break; + } + case U_EMR_CREATEBRUSHINDIRECT: { + dbg_str << "\n"; - PU_EMRCREATEBRUSHINDIRECT pEmr = (PU_EMRCREATEBRUSHINDIRECT) lpEMFR; - insert_object(d, pEmr->ihBrush, U_EMR_CREATEBRUSHINDIRECT, lpEMFR); - break; - } - case U_EMR_DELETEOBJECT: - dbg_str << "\n"; - // Objects here are not deleted until the draw completes, new ones may write over an existing one. - break; - case U_EMR_ANGLEARC: - dbg_str << "\n"; - break; - case U_EMR_ELLIPSE: - { - dbg_str << "\n"; - - PU_EMRELLIPSE pEmr = (PU_EMRELLIPSE) lpEMFR; - U_RECTL rclBox = pEmr->rclBox; - - double cx = pix_to_x_point( d, (rclBox.left + rclBox.right)/2.0, (rclBox.bottom + rclBox.top)/2.0 ); - double cy = pix_to_y_point( d, (rclBox.left + rclBox.right)/2.0, (rclBox.bottom + rclBox.top)/2.0 ); - double rx = pix_to_abs_size( d, std::abs(rclBox.right - rclBox.left )/2.0 ); - double ry = pix_to_abs_size( d, std::abs(rclBox.top - rclBox.bottom)/2.0 ); - - SVGOStringStream tmp_ellipse; - tmp_ellipse << "cx=\"" << cx << "\" "; - tmp_ellipse << "cy=\"" << cy << "\" "; - tmp_ellipse << "rx=\"" << rx << "\" "; - tmp_ellipse << "ry=\"" << ry << "\" "; - - d->mask |= emr_mask; - - d->outsvg += " iType); // - d->outsvg += "\n\t"; - d->outsvg += tmp_ellipse.str().c_str(); - d->outsvg += "/> \n"; - d->path = ""; - break; - } - case U_EMR_RECTANGLE: - { - dbg_str << "\n"; + PU_EMRCREATEBRUSHINDIRECT pEmr = (PU_EMRCREATEBRUSHINDIRECT)lpEMFR; + insert_object(d, pEmr->ihBrush, U_EMR_CREATEBRUSHINDIRECT, lpEMFR); + break; + } + case U_EMR_DELETEOBJECT: + dbg_str << "\n"; + // Objects here are not deleted until the draw completes, new ones may write over an existing one. + break; + case U_EMR_ANGLEARC: + dbg_str << "\n"; + break; + case U_EMR_ELLIPSE: { + dbg_str << "\n"; - PU_EMRRECTANGLE pEmr = (PU_EMRRECTANGLE) lpEMFR; - U_RECTL rc = pEmr->rclBox; + PU_EMRELLIPSE pEmr = (PU_EMRELLIPSE)lpEMFR; + U_RECTL rclBox = pEmr->rclBox; - SVGOStringStream tmp_rectangle; - tmp_rectangle << "\n\tM " << pix_to_xy( d, rc.left , rc.top ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, rc.right, rc.top ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, rc.right, rc.bottom ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, rc.left, rc.bottom ) << " "; - tmp_rectangle << "\n\tz"; + double cx = pix_to_x_point(d, (rclBox.left + rclBox.right) / 2.0, (rclBox.bottom + rclBox.top) / 2.0); + double cy = pix_to_y_point(d, (rclBox.left + rclBox.right) / 2.0, (rclBox.bottom + rclBox.top) / 2.0); + double rx = pix_to_abs_size(d, std::abs(rclBox.right - rclBox.left) / 2.0); + double ry = pix_to_abs_size(d, std::abs(rclBox.top - rclBox.bottom) / 2.0); - d->mask |= emr_mask; + SVGOStringStream tmp_ellipse; + tmp_ellipse << "cx=\"" << cx << "\" "; + tmp_ellipse << "cy=\"" << cy << "\" "; + tmp_ellipse << "rx=\"" << rx << "\" "; + tmp_ellipse << "ry=\"" << ry << "\" "; - tmp_path << tmp_rectangle.str().c_str(); - break; - } - case U_EMR_ROUNDRECT: - { - dbg_str << "\n"; - - PU_EMRROUNDRECT pEmr = (PU_EMRROUNDRECT) lpEMFR; - U_RECTL rc = pEmr->rclBox; - U_SIZEL corner = pEmr->szlCorner; - double f = 4.*(sqrt(2) - 1)/3; - double f1 = 1.0 - f; - double cnx = corner.cx/2; - double cny = corner.cy/2; - - // clang-format off + d->mask |= emr_mask; + + d->outsvg += " iType); // + d->outsvg += "\n\t"; + d->outsvg += tmp_ellipse.str().c_str(); + d->outsvg += "/> \n"; + d->path = ""; + break; + } + case U_EMR_RECTANGLE: { + dbg_str << "\n"; + + PU_EMRRECTANGLE pEmr = (PU_EMRRECTANGLE)lpEMFR; + U_RECTL rc = pEmr->rclBox; + + SVGOStringStream tmp_rectangle; + tmp_rectangle << "\n\tM " << pix_to_xy(d, rc.left, rc.top) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, rc.right, rc.top) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, rc.right, rc.bottom) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, rc.left, rc.bottom) << " "; + tmp_rectangle << "\n\tz"; + + d->mask |= emr_mask; + + tmp_path << tmp_rectangle.str().c_str(); + break; + } + case U_EMR_ROUNDRECT: { + dbg_str << "\n"; + + PU_EMRROUNDRECT pEmr = (PU_EMRROUNDRECT)lpEMFR; + U_RECTL rc = pEmr->rclBox; + U_SIZEL corner = pEmr->szlCorner; + double f = 4. * (sqrt(2) - 1) / 3; + double f1 = 1.0 - f; + double cnx = corner.cx / 2; + double cny = corner.cy / 2; + + // clang-format off SVGOStringStream tmp_rectangle; tmp_rectangle << "\n" << " M " @@ -2704,850 +2710,957 @@ std::cout << "BEFORE DRAW" << pix_to_xy(d, rc.left , rc.bottom - cny ) << "\n"; tmp_rectangle << " z\n"; - // clang-format on - - d->mask |= emr_mask; + // clang-format on - tmp_path << tmp_rectangle.str().c_str(); - break; - } - case U_EMR_ARC: - { - dbg_str << "\n"; - U_PAIRF center,start,end,size; - int f1; - int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); - int stat = emr_arc_points( lpEMFR, &f1, f2, ¢er, &start, &end, &size); - if(!stat){ - tmp_path << "\n\tM " << pix_to_xy(d, start.x, start.y); - tmp_path << " A " << pix_to_abs_size(d, size.x)/2.0 << "," << pix_to_abs_size(d, size.y)/2.0; - tmp_path << " "; - tmp_path << 180.0 * current_rotation(d)/M_PI; - tmp_path << " "; - tmp_path << " " << f1 << "," << f2 << " "; - tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; - d->mask |= emr_mask; - } - else { - dbg_str << "\n"; - } - break; - } - case U_EMR_CHORD: - { - dbg_str << "\n"; - U_PAIRF center,start,end,size; - int f1; - int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); - if(!emr_arc_points( lpEMFR, &f1, f2, ¢er, &start, &end, &size)){ - tmp_path << "\n\tM " << pix_to_xy(d, start.x, start.y); - tmp_path << " A " << pix_to_abs_size(d, size.x)/2.0 << "," << pix_to_abs_size(d, size.y)/2.0; - tmp_path << " "; - tmp_path << 180.0 * current_rotation(d)/M_PI; - tmp_path << " "; - tmp_path << " " << f1 << "," << f2 << " "; - tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; - tmp_path << " z "; d->mask |= emr_mask; + + tmp_path << tmp_rectangle.str().c_str(); + break; } - else { - dbg_str << "\n"; + case U_EMR_ARC: { + dbg_str << "\n"; + U_PAIRF center, start, end, size; + int f1; + int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); + int stat = emr_arc_points(lpEMFR, &f1, f2, ¢er, &start, &end, &size); + if (!stat) { + tmp_path << "\n\tM " << pix_to_xy(d, start.x, start.y); + tmp_path << " A " << pix_to_abs_size(d, size.x) / 2.0 << "," << pix_to_abs_size(d, size.y) / 2.0; + tmp_path << " "; + tmp_path << 180.0 * current_rotation(d) / M_PI; + tmp_path << " "; + tmp_path << " " << f1 << "," << f2 << " "; + tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; + d->mask |= emr_mask; + } else { + dbg_str << "\n"; + } + break; } - break; - } - case U_EMR_PIE: - { - dbg_str << "\n"; - U_PAIRF center,start,end,size; - int f1; - int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); - if(!emr_arc_points( lpEMFR, &f1, f2, ¢er, &start, &end, &size)){ - tmp_path << "\n\tM " << pix_to_xy(d, center.x, center.y); - tmp_path << "\n\tL " << pix_to_xy(d, start.x, start.y); - tmp_path << " A " << pix_to_abs_size(d, size.x)/2.0 << "," << pix_to_abs_size(d, size.y)/2.0; - tmp_path << " "; - tmp_path << 180.0 * current_rotation(d)/M_PI; - tmp_path << " "; - tmp_path << " " << f1 << "," << f2 << " "; - tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; - tmp_path << " z "; - d->mask |= emr_mask; + case U_EMR_CHORD: { + dbg_str << "\n"; + U_PAIRF center, start, end, size; + int f1; + int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); + if (!emr_arc_points(lpEMFR, &f1, f2, ¢er, &start, &end, &size)) { + tmp_path << "\n\tM " << pix_to_xy(d, start.x, start.y); + tmp_path << " A " << pix_to_abs_size(d, size.x) / 2.0 << "," << pix_to_abs_size(d, size.y) / 2.0; + tmp_path << " "; + tmp_path << 180.0 * current_rotation(d) / M_PI; + tmp_path << " "; + tmp_path << " " << f1 << "," << f2 << " "; + tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; + tmp_path << " z "; + d->mask |= emr_mask; + } else { + dbg_str << "\n"; + } + break; } - else { - dbg_str << "\n"; + case U_EMR_PIE: { + dbg_str << "\n"; + U_PAIRF center, start, end, size; + int f1; + int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); + if (!emr_arc_points(lpEMFR, &f1, f2, ¢er, &start, &end, &size)) { + tmp_path << "\n\tM " << pix_to_xy(d, center.x, center.y); + tmp_path << "\n\tL " << pix_to_xy(d, start.x, start.y); + tmp_path << " A " << pix_to_abs_size(d, size.x) / 2.0 << "," << pix_to_abs_size(d, size.y) / 2.0; + tmp_path << " "; + tmp_path << 180.0 * current_rotation(d) / M_PI; + tmp_path << " "; + tmp_path << " " << f1 << "," << f2 << " "; + tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; + tmp_path << " z "; + d->mask |= emr_mask; + } else { + dbg_str << "\n"; + } + break; } - break; - } - case U_EMR_SELECTPALETTE: dbg_str << "\n"; break; - case U_EMR_CREATEPALETTE: dbg_str << "\n"; break; - case U_EMR_SETPALETTEENTRIES: dbg_str << "\n"; break; - case U_EMR_RESIZEPALETTE: dbg_str << "\n"; break; - case U_EMR_REALIZEPALETTE: dbg_str << "\n"; break; - case U_EMR_EXTFLOODFILL: dbg_str << "\n"; break; - case U_EMR_LINETO: - { - dbg_str << "\n"; - - PU_EMRLINETO pEmr = (PU_EMRLINETO) lpEMFR; - - d->mask |= emr_mask; - - tmp_path << - "\n\tL " << pix_to_xy( d, pEmr->ptl.x, pEmr->ptl.y) << " "; - break; - } - case U_EMR_ARCTO: - { - dbg_str << "\n"; - U_PAIRF center,start,end,size; - int f1; - int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); - if(!emr_arc_points( lpEMFR, &f1, f2, ¢er, &start, &end, &size)){ - // draw a line from current position to start, arc from there - tmp_path << "\n\tL " << pix_to_xy(d, start.x, start.y); - tmp_path << " A " << pix_to_abs_size(d, size.x)/2.0 << "," << pix_to_abs_size(d, size.y)/2.0; - tmp_path << " "; - tmp_path << 180.0 * current_rotation(d)/M_PI; - tmp_path << " "; - tmp_path << " " << f1 << "," << f2 << " "; - tmp_path << pix_to_xy(d, end.x, end.y)<< " "; + case U_EMR_SELECTPALETTE: + dbg_str << "\n"; + break; + case U_EMR_CREATEPALETTE: + dbg_str << "\n"; + break; + case U_EMR_SETPALETTEENTRIES: + dbg_str << "\n"; + break; + case U_EMR_RESIZEPALETTE: + dbg_str << "\n"; + break; + case U_EMR_REALIZEPALETTE: + dbg_str << "\n"; + break; + case U_EMR_EXTFLOODFILL: + dbg_str << "\n"; + break; + case U_EMR_LINETO: { + dbg_str << "\n"; + + PU_EMRLINETO pEmr = (PU_EMRLINETO)lpEMFR; d->mask |= emr_mask; + + tmp_path << "\n\tL " << pix_to_xy(d, pEmr->ptl.x, pEmr->ptl.y) << " "; + break; } - else { - dbg_str << "\n"; + case U_EMR_ARCTO: { + dbg_str << "\n"; + U_PAIRF center, start, end, size; + int f1; + int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); + if (!emr_arc_points(lpEMFR, &f1, f2, ¢er, &start, &end, &size)) { + // draw a line from current position to start, arc from there + tmp_path << "\n\tL " << pix_to_xy(d, start.x, start.y); + tmp_path << " A " << pix_to_abs_size(d, size.x) / 2.0 << "," << pix_to_abs_size(d, size.y) / 2.0; + tmp_path << " "; + tmp_path << 180.0 * current_rotation(d) / M_PI; + tmp_path << " "; + tmp_path << " " << f1 << "," << f2 << " "; + tmp_path << pix_to_xy(d, end.x, end.y) << " "; + + d->mask |= emr_mask; + } else { + dbg_str << "\n"; + } + break; } - break; - } - case U_EMR_POLYDRAW: dbg_str << "\n"; break; - case U_EMR_SETARCDIRECTION: - { - dbg_str << "\n"; - PU_EMRSETARCDIRECTION pEmr = (PU_EMRSETARCDIRECTION) lpEMFR; - if(d->arcdir == U_AD_CLOCKWISE || d->arcdir == U_AD_COUNTERCLOCKWISE){ // EMF file could be corrupt - d->arcdir = pEmr->iArcDirection; - } - break; - } - case U_EMR_SETMITERLIMIT: - { - dbg_str << "\n"; + case U_EMR_POLYDRAW: + dbg_str << "\n"; + break; + case U_EMR_SETARCDIRECTION: { + dbg_str << "\n"; + PU_EMRSETARCDIRECTION pEmr = (PU_EMRSETARCDIRECTION)lpEMFR; + if (d->arcdir == U_AD_CLOCKWISE || d->arcdir == U_AD_COUNTERCLOCKWISE) { // EMF file could be corrupt + d->arcdir = pEmr->iArcDirection; + } + break; + } + case U_EMR_SETMITERLIMIT: { + dbg_str << "\n"; - PU_EMRSETMITERLIMIT pEmr = (PU_EMRSETMITERLIMIT) lpEMFR; + PU_EMRSETMITERLIMIT pEmr = (PU_EMRSETMITERLIMIT)lpEMFR; - //The function takes a float but saves a 32 bit int in the U_EMR_SETMITERLIMIT record. - float miterlimit = *((int32_t *) &(pEmr->eMiterLimit)); - d->dc[d->level].style.stroke_miterlimit.value = miterlimit; //ratio, not a pt size - if (d->dc[d->level].style.stroke_miterlimit.value < 2) - d->dc[d->level].style.stroke_miterlimit.value = 2.0; - break; - } - case U_EMR_BEGINPATH: - { - dbg_str << "\n"; - // The next line should never be needed, should have been handled before main switch - // qualifier added because EMF's encountered where moveto preceded beginpath followed by lineto - if(d->mask & U_DRAW_VISIBLE){ - d->path = ""; - } - d->mask |= emr_mask; - break; - } - case U_EMR_ENDPATH: - { - dbg_str << "\n"; - d->mask &= (0xFFFFFFFF - U_DRAW_ONLYTO); // clear the OnlyTo bit (it might not have been set), prevents any further path extension - break; - } - case U_EMR_CLOSEFIGURE: - { - dbg_str << "\n"; - // EMF may contain multiple closefigures on one path - tmp_path << "\n\tz"; - d->mask |= U_DRAW_CLOSED; - break; - } - case U_EMR_FILLPATH: - { - dbg_str << "\n"; - if(d->mask & U_DRAW_PATH){ // Operation only effects declared paths - if(!(d->mask & U_DRAW_CLOSED)){ // Close a path not explicitly closed by an EMRCLOSEFIGURE, otherwise fill makes no sense - tmp_path << "\n\tz"; - d->mask |= U_DRAW_CLOSED; - } - d->mask |= emr_mask; - d->drawtype = U_EMR_FILLPATH; + // The function takes a float but saves a 32 bit int in the U_EMR_SETMITERLIMIT record. + float miterlimit = *((int32_t *)&(pEmr->eMiterLimit)); + d->dc[d->level].style.stroke_miterlimit.value = miterlimit; // ratio, not a pt size + if (d->dc[d->level].style.stroke_miterlimit.value < 2) + d->dc[d->level].style.stroke_miterlimit.value = 2.0; + break; } - break; - } - case U_EMR_STROKEANDFILLPATH: - { - dbg_str << "\n"; - if(d->mask & U_DRAW_PATH){ // Operation only effects declared paths - if(!(d->mask & U_DRAW_CLOSED)){ // Close a path not explicitly closed by an EMRCLOSEFIGURE, otherwise fill makes no sense - tmp_path << "\n\tz"; - d->mask |= U_DRAW_CLOSED; + case U_EMR_BEGINPATH: { + dbg_str << "\n"; + // The next line should never be needed, should have been handled before main switch + // qualifier added because EMF's encountered where moveto preceded beginpath followed by lineto + if (d->mask & U_DRAW_VISIBLE) { + d->path = ""; } d->mask |= emr_mask; - d->drawtype = U_EMR_STROKEANDFILLPATH; + break; } - break; - } - case U_EMR_STROKEPATH: - { - dbg_str << "\n"; - if(d->mask & U_DRAW_PATH){ // Operation only effects declared paths - d->mask |= emr_mask; - d->drawtype = U_EMR_STROKEPATH; + case U_EMR_ENDPATH: { + dbg_str << "\n"; + d->mask &= (0xFFFFFFFF - U_DRAW_ONLYTO); // clear the OnlyTo bit (it might not have been set), prevents + // any further path extension + break; } - break; - } - case U_EMR_FLATTENPATH: dbg_str << "\n"; break; - case U_EMR_WIDENPATH: dbg_str << "\n"; break; - case U_EMR_SELECTCLIPPATH: - { - dbg_str << "\n"; - PU_EMRSELECTCLIPPATH pEmr = (PU_EMRSELECTCLIPPATH) lpEMFR; - int logic = pEmr->iMode; - - if ((logic < U_RGN_MIN) || (logic > U_RGN_MAX)){ break; } - add_clips(d, d->path.c_str(), logic); // finds an existing one or stores this, sets clip_id - d->path = ""; - d->drawtype = 0; - break; - } - case U_EMR_ABORTPATH: - { - dbg_str << "\n"; - d->path = ""; - d->drawtype = 0; - break; - } - case U_EMR_UNDEF69: dbg_str << "\n"; break; - case U_EMR_COMMENT: - { - dbg_str << "\n"; - - PU_EMRCOMMENT pEmr = (PU_EMRCOMMENT) lpEMFR; - - char *szTxt = (char *) pEmr->Data; - - for (uint32_t i = 0; i < pEmr->cbData; i++) { - if ( *szTxt) { - if ( *szTxt >= ' ' && *szTxt < 'z' && *szTxt != '<' && *szTxt != '>' ) { - tmp_str << *szTxt; + case U_EMR_CLOSEFIGURE: { + dbg_str << "\n"; + // EMF may contain multiple closefigures on one path + tmp_path << "\n\tz"; + d->mask |= U_DRAW_CLOSED; + break; + } + case U_EMR_FILLPATH: { + dbg_str << "\n"; + if (d->mask & U_DRAW_PATH) { // Operation only effects declared paths + if (!(d->mask & U_DRAW_CLOSED)) { // Close a path not explicitly closed by an EMRCLOSEFIGURE, + // otherwise fill makes no sense + tmp_path << "\n\tz"; + d->mask |= U_DRAW_CLOSED; } - szTxt++; + d->mask |= emr_mask; + d->drawtype = U_EMR_FILLPATH; } + break; } - - if (false && strlen(tmp_str.str().c_str())) { - tmp_outsvg << " \n"; + case U_EMR_STROKEANDFILLPATH: { + dbg_str << "\n"; + if (d->mask & U_DRAW_PATH) { // Operation only effects declared paths + if (!(d->mask & U_DRAW_CLOSED)) { // Close a path not explicitly closed by an EMRCLOSEFIGURE, + // otherwise fill makes no sense + tmp_path << "\n\tz"; + d->mask |= U_DRAW_CLOSED; + } + d->mask |= emr_mask; + d->drawtype = U_EMR_STROKEANDFILLPATH; + } + break; } - - break; - } - case U_EMR_FILLRGN: dbg_str << "\n"; break; - case U_EMR_FRAMERGN: dbg_str << "\n"; break; - case U_EMR_INVERTRGN: dbg_str << "\n"; break; - case U_EMR_PAINTRGN: dbg_str << "\n"; break; - case U_EMR_EXTSELECTCLIPRGN: - { - dbg_str << "\n"; - - PU_EMREXTSELECTCLIPRGN pEmr = (PU_EMREXTSELECTCLIPRGN) lpEMFR; - // the only mode we implement - this clears the clipping region - if (pEmr->iMode == U_RGN_COPY) { - d->dc[d->level].clip_id = 0; + case U_EMR_STROKEPATH: { + dbg_str << "\n"; + if (d->mask & U_DRAW_PATH) { // Operation only effects declared paths + d->mask |= emr_mask; + d->drawtype = U_EMR_STROKEPATH; + } + break; } - break; - } - case U_EMR_BITBLT: - { - dbg_str << "\n"; - - PU_EMRBITBLT pEmr = (PU_EMRBITBLT) lpEMFR; - // Treat all nonImage bitblts as a rectangular write. Definitely not correct, but at - // least it leaves objects where the operations should have been. - if (!pEmr->cbBmiSrc) { - // should be an application of a DIBPATTERNBRUSHPT, use a solid color instead - - if(pEmr->dwRop == U_NOOP)break; /* GDI applications apparently often end with this as a sort of flush(), nothing should be drawn */ - int32_t dx = pEmr->Dest.x; - int32_t dy = pEmr->Dest.y; - int32_t dw = pEmr->cDest.x; - int32_t dh = pEmr->cDest.y; - SVGOStringStream tmp_rectangle; - tmp_rectangle << "\n\tM " << pix_to_xy( d, dx, dy ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx + dw, dy ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx + dw, dy + dh ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx, dy + dh ) << " "; - tmp_rectangle << "\n\tz"; + case U_EMR_FLATTENPATH: + dbg_str << "\n"; + break; + case U_EMR_WIDENPATH: + dbg_str << "\n"; + break; + case U_EMR_SELECTCLIPPATH: { + dbg_str << "\n"; + PU_EMRSELECTCLIPPATH pEmr = (PU_EMRSELECTCLIPPATH)lpEMFR; + int logic = pEmr->iMode; - d->mask |= emr_mask; - d->dwRop3 = pEmr->dwRop; // we will try to approximate SOME of these - d->mask |= U_DRAW_CLOSED; // Bitblit is not really open or closed, but we need it to fill, and this is the flag for that - - tmp_path << tmp_rectangle.str().c_str(); - } - else { - double dx = pix_to_x_point( d, pEmr->Dest.x, pEmr->Dest.y); - double dy = pix_to_y_point( d, pEmr->Dest.x, pEmr->Dest.y); - double dw = pix_to_abs_size( d, pEmr->cDest.x); - double dh = pix_to_abs_size( d, pEmr->cDest.y); - //source position within the bitmap, in pixels - int sx = pEmr->Src.x + pEmr->xformSrc.eDx; - int sy = pEmr->Src.y + pEmr->xformSrc.eDy; - int sw = 0; // extract all of the image - int sh = 0; - if(sx<0)sx=0; - if(sy<0)sy=0; - common_image_extraction(d,pEmr,dx,dy,dw,dh,sx,sy,sw,sh, - pEmr->iUsageSrc, pEmr->offBitsSrc, pEmr->cbBitsSrc, pEmr->offBmiSrc, pEmr->cbBmiSrc); - } - break; - } - case U_EMR_STRETCHBLT: - { - dbg_str << "\n"; - PU_EMRSTRETCHBLT pEmr = (PU_EMRSTRETCHBLT) lpEMFR; - // Always grab image, ignore modes. - if (pEmr->cbBmiSrc) { - double dx = pix_to_x_point( d, pEmr->Dest.x, pEmr->Dest.y); - double dy = pix_to_y_point( d, pEmr->Dest.x, pEmr->Dest.y); - double dw = pix_to_abs_size( d, pEmr->cDest.x); - double dh = pix_to_abs_size( d, pEmr->cDest.y); - //source position within the bitmap, in pixels - int sx = pEmr->Src.x + pEmr->xformSrc.eDx; - int sy = pEmr->Src.y + pEmr->xformSrc.eDy; - int sw = pEmr->cSrc.x; // extract the specified amount of the image - int sh = pEmr->cSrc.y; - common_image_extraction(d,pEmr,dx,dy,dw,dh,sx,sy,sw,sh, - pEmr->iUsageSrc, pEmr->offBitsSrc, pEmr->cbBitsSrc, pEmr->offBmiSrc, pEmr->cbBmiSrc); + if ((logic < U_RGN_MIN) || (logic > U_RGN_MAX)) { + break; + } + add_clips(d, d->path.c_str(), logic); // finds an existing one or stores this, sets clip_id + d->path = ""; + d->drawtype = 0; + break; } - break; - } - case U_EMR_MASKBLT: - { - dbg_str << "\n"; - PU_EMRMASKBLT pEmr = (PU_EMRMASKBLT) lpEMFR; - // Always grab image, ignore masks and modes. - if (pEmr->cbBmiSrc) { - double dx = pix_to_x_point( d, pEmr->Dest.x, pEmr->Dest.y); - double dy = pix_to_y_point( d, pEmr->Dest.x, pEmr->Dest.y); - double dw = pix_to_abs_size( d, pEmr->cDest.x); - double dh = pix_to_abs_size( d, pEmr->cDest.y); - int sx = pEmr->Src.x + pEmr->xformSrc.eDx; //source position within the bitmap, in pixels - int sy = pEmr->Src.y + pEmr->xformSrc.eDy; - int sw = 0; // extract all of the image - int sh = 0; - common_image_extraction(d,pEmr,dx,dy,dw,dh,sx,sy,sw,sh, - pEmr->iUsageSrc, pEmr->offBitsSrc, pEmr->cbBitsSrc, pEmr->offBmiSrc, pEmr->cbBmiSrc); + case U_EMR_ABORTPATH: { + dbg_str << "\n"; + d->path = ""; + d->drawtype = 0; + break; } - break; - } - case U_EMR_PLGBLT: dbg_str << "\n"; break; - case U_EMR_SETDIBITSTODEVICE: dbg_str << "\n"; break; - case U_EMR_STRETCHDIBITS: - { - // Some applications use multiple EMF operations, including multiple STRETCHDIBITS to create - // images with transparent regions. PowerPoint does this with rotated images, for instance. - // Parsing all of that to derive a single resultant image object is left for a later version - // of this code. In the meantime, every STRETCHDIBITS goes directly to an image. The Inkscape - // user can sort out transparency later using Gimp, if need be. - - PU_EMRSTRETCHDIBITS pEmr = (PU_EMRSTRETCHDIBITS) lpEMFR; - double dx = pix_to_x_point( d, pEmr->Dest.x, pEmr->Dest.y ); - double dy = pix_to_y_point( d, pEmr->Dest.x, pEmr->Dest.y ); - double dw = pix_to_abs_size( d, pEmr->cDest.x); - double dh = pix_to_abs_size( d, pEmr->cDest.y); - int sx = pEmr->Src.x; //source position within the bitmap, in pixels - int sy = pEmr->Src.y; - int sw = pEmr->cSrc.x; // extract the specified amount of the image - int sh = pEmr->cSrc.y; - common_image_extraction(d,pEmr,dx,dy,dw,dh,sx,sy,sw,sh, - pEmr->iUsageSrc, pEmr->offBitsSrc, pEmr->cbBitsSrc, pEmr->offBmiSrc, pEmr->cbBmiSrc); - - dbg_str << "\n"; - break; - } - case U_EMR_EXTCREATEFONTINDIRECTW: - { - dbg_str << "\n"; - - PU_EMREXTCREATEFONTINDIRECTW pEmr = (PU_EMREXTCREATEFONTINDIRECTW) lpEMFR; - insert_object(d, pEmr->ihFont, U_EMR_EXTCREATEFONTINDIRECTW, lpEMFR); - break; - } - case U_EMR_EXTTEXTOUTA: - case U_EMR_EXTTEXTOUTW: - case U_EMR_SMALLTEXTOUT: - { - dbg_str << "\n"; + case U_EMR_UNDEF69: + dbg_str << "\n"; + break; + case U_EMR_COMMENT: { + dbg_str << "\n"; - PU_EMREXTTEXTOUTW pEmr = (PU_EMREXTTEXTOUTW) lpEMFR; - PU_EMRSMALLTEXTOUT pEmrS = (PU_EMRSMALLTEXTOUT) lpEMFR; + PU_EMRCOMMENT pEmr = (PU_EMRCOMMENT)lpEMFR; - double x1,y1; - int roff = sizeof(U_EMRSMALLTEXTOUT); //offset to the start of the variable fields, only used with U_EMR_SMALLTEXTOUT - int cChars; - if(lpEMFR->iType==U_EMR_SMALLTEXTOUT){ - x1 = pEmrS->Dest.x; - y1 = pEmrS->Dest.y; - cChars = pEmrS->cChars; - if(!(pEmrS->fuOptions & U_ETO_NO_RECT)){ roff += sizeof(U_RECTL); } - } - else { - x1 = pEmr->emrtext.ptlReference.x; - y1 = pEmr->emrtext.ptlReference.y; - cChars = 0; - } - uint32_t fOptions = pEmr->emrtext.fOptions; + char *szTxt = (char *)pEmr->Data; - if (d->dc[d->level].textAlign & U_TA_UPDATECP) { - x1 = d->dc[d->level].cur.x; - y1 = d->dc[d->level].cur.y; - } - - double x = pix_to_x_point(d, x1, y1); - double y = pix_to_y_point(d, x1, y1); + for (uint32_t i = 0; i < pEmr->cbData; i++) { + if (*szTxt) { + if (*szTxt >= ' ' && *szTxt < 'z' && *szTxt != '<' && *szTxt != '>') { + tmp_str << *szTxt; + } + szTxt++; + } + } - /* Rotation issues are handled entirely in libTERE now */ + if (false && strlen(tmp_str.str().c_str())) { + tmp_outsvg << " \n"; + } - uint32_t *dup_wt = nullptr; + break; + } + case U_EMR_FILLRGN: + dbg_str << "\n"; + break; + case U_EMR_FRAMERGN: + dbg_str << "\n"; + break; + case U_EMR_INVERTRGN: + dbg_str << "\n"; + break; + case U_EMR_PAINTRGN: + dbg_str << "\n"; + break; + case U_EMR_EXTSELECTCLIPRGN: { + dbg_str << "\n"; - if( lpEMFR->iType==U_EMR_EXTTEXTOUTA){ - /* These should be JUST ASCII, but they might not be... - If it holds Utf-8 or plain ASCII the first call will succeed. - If not, assume that it holds Latin1. - If that fails then something is really screwed up! - */ - dup_wt = U_Utf8ToUtf32le((char *) pEmr + pEmr->emrtext.offString, pEmr->emrtext.nChars, nullptr); - if(!dup_wt)dup_wt = U_Latin1ToUtf32le((char *) pEmr + pEmr->emrtext.offString, pEmr->emrtext.nChars, nullptr); - if(!dup_wt)dup_wt = unknown_chars(pEmr->emrtext.nChars); + PU_EMREXTSELECTCLIPRGN pEmr = (PU_EMREXTSELECTCLIPRGN)lpEMFR; + // the only mode we implement - this clears the clipping region + if (pEmr->iMode == U_RGN_COPY) { + d->dc[d->level].clip_id = 0; + } + break; } - else if( lpEMFR->iType==U_EMR_EXTTEXTOUTW){ - dup_wt = U_Utf16leToUtf32le((uint16_t *)((char *) pEmr + pEmr->emrtext.offString), pEmr->emrtext.nChars, nullptr); - if(!dup_wt)dup_wt = unknown_chars(pEmr->emrtext.nChars); + case U_EMR_BITBLT: { + dbg_str << "\n"; + + PU_EMRBITBLT pEmr = (PU_EMRBITBLT)lpEMFR; + // Treat all nonImage bitblts as a rectangular write. Definitely not correct, but at + // least it leaves objects where the operations should have been. + if (!pEmr->cbBmiSrc) { + // should be an application of a DIBPATTERNBRUSHPT, use a solid color instead + + if (pEmr->dwRop == U_NOOP) + break; /* GDI applications apparently often end with this as a sort of flush(), nothing should + be drawn */ + int32_t dx = pEmr->Dest.x; + int32_t dy = pEmr->Dest.y; + int32_t dw = pEmr->cDest.x; + int32_t dh = pEmr->cDest.y; + SVGOStringStream tmp_rectangle; + tmp_rectangle << "\n\tM " << pix_to_xy(d, dx, dy) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx + dw, dy) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx + dw, dy + dh) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx, dy + dh) << " "; + tmp_rectangle << "\n\tz"; + + d->mask |= emr_mask; + d->dwRop3 = pEmr->dwRop; // we will try to approximate SOME of these + d->mask |= U_DRAW_CLOSED; // Bitblit is not really open or closed, but we need it to fill, and this + // is the flag for that + + tmp_path << tmp_rectangle.str().c_str(); + } else { + double dx = pix_to_x_point(d, pEmr->Dest.x, pEmr->Dest.y); + double dy = pix_to_y_point(d, pEmr->Dest.x, pEmr->Dest.y); + double dw = pix_to_abs_size(d, pEmr->cDest.x); + double dh = pix_to_abs_size(d, pEmr->cDest.y); + // source position within the bitmap, in pixels + int sx = pEmr->Src.x + pEmr->xformSrc.eDx; + int sy = pEmr->Src.y + pEmr->xformSrc.eDy; + int sw = 0; // extract all of the image + int sh = 0; + if (sx < 0) + sx = 0; + if (sy < 0) + sy = 0; + common_image_extraction(d, pEmr, dx, dy, dw, dh, sx, sy, sw, sh, pEmr->iUsageSrc, pEmr->offBitsSrc, + pEmr->cbBitsSrc, pEmr->offBmiSrc, pEmr->cbBmiSrc); + } + break; } - else { // U_EMR_SMALLTEXTOUT - if(pEmrS->fuOptions & U_ETO_SMALL_CHARS){ - dup_wt = U_Utf8ToUtf32le((char *) pEmrS + roff, cChars, nullptr); + case U_EMR_STRETCHBLT: { + dbg_str << "\n"; + PU_EMRSTRETCHBLT pEmr = (PU_EMRSTRETCHBLT)lpEMFR; + // Always grab image, ignore modes. + if (pEmr->cbBmiSrc) { + double dx = pix_to_x_point(d, pEmr->Dest.x, pEmr->Dest.y); + double dy = pix_to_y_point(d, pEmr->Dest.x, pEmr->Dest.y); + double dw = pix_to_abs_size(d, pEmr->cDest.x); + double dh = pix_to_abs_size(d, pEmr->cDest.y); + // source position within the bitmap, in pixels + int sx = pEmr->Src.x + pEmr->xformSrc.eDx; + int sy = pEmr->Src.y + pEmr->xformSrc.eDy; + int sw = pEmr->cSrc.x; // extract the specified amount of the image + int sh = pEmr->cSrc.y; + common_image_extraction(d, pEmr, dx, dy, dw, dh, sx, sy, sw, sh, pEmr->iUsageSrc, pEmr->offBitsSrc, + pEmr->cbBitsSrc, pEmr->offBmiSrc, pEmr->cbBmiSrc); } - else { - dup_wt = U_Utf16leToUtf32le((uint16_t *)((char *) pEmrS + roff), cChars, nullptr); + break; + } + case U_EMR_MASKBLT: { + dbg_str << "\n"; + PU_EMRMASKBLT pEmr = (PU_EMRMASKBLT)lpEMFR; + // Always grab image, ignore masks and modes. + if (pEmr->cbBmiSrc) { + double dx = pix_to_x_point(d, pEmr->Dest.x, pEmr->Dest.y); + double dy = pix_to_y_point(d, pEmr->Dest.x, pEmr->Dest.y); + double dw = pix_to_abs_size(d, pEmr->cDest.x); + double dh = pix_to_abs_size(d, pEmr->cDest.y); + int sx = pEmr->Src.x + pEmr->xformSrc.eDx; // source position within the bitmap, in pixels + int sy = pEmr->Src.y + pEmr->xformSrc.eDy; + int sw = 0; // extract all of the image + int sh = 0; + common_image_extraction(d, pEmr, dx, dy, dw, dh, sx, sy, sw, sh, pEmr->iUsageSrc, pEmr->offBitsSrc, + pEmr->cbBitsSrc, pEmr->offBmiSrc, pEmr->cbBmiSrc); } - if(!dup_wt)dup_wt = unknown_chars(cChars); + break; } + case U_EMR_PLGBLT: + dbg_str << "\n"; + break; + case U_EMR_SETDIBITSTODEVICE: + dbg_str << "\n"; + break; + case U_EMR_STRETCHDIBITS: { + // Some applications use multiple EMF operations, including multiple STRETCHDIBITS to create + // images with transparent regions. PowerPoint does this with rotated images, for instance. + // Parsing all of that to derive a single resultant image object is left for a later version + // of this code. In the meantime, every STRETCHDIBITS goes directly to an image. The Inkscape + // user can sort out transparency later using Gimp, if need be. + + PU_EMRSTRETCHDIBITS pEmr = (PU_EMRSTRETCHDIBITS)lpEMFR; + double dx = pix_to_x_point(d, pEmr->Dest.x, pEmr->Dest.y); + double dy = pix_to_y_point(d, pEmr->Dest.x, pEmr->Dest.y); + double dw = pix_to_abs_size(d, pEmr->cDest.x); + double dh = pix_to_abs_size(d, pEmr->cDest.y); + int sx = pEmr->Src.x; // source position within the bitmap, in pixels + int sy = pEmr->Src.y; + int sw = pEmr->cSrc.x; // extract the specified amount of the image + int sh = pEmr->cSrc.y; + common_image_extraction(d, pEmr, dx, dy, dw, dh, sx, sy, sw, sh, pEmr->iUsageSrc, pEmr->offBitsSrc, + pEmr->cbBitsSrc, pEmr->offBmiSrc, pEmr->cbBmiSrc); - msdepua(dup_wt); //convert everything in Microsoft's private use area. For Symbol, Wingdings, Dingbats - - if(NonToUnicode(dup_wt, d->dc[d->level].font_name)){ - free(d->dc[d->level].font_name); - d->dc[d->level].font_name = strdup("Times New Roman"); + dbg_str << "\n"; + break; } + case U_EMR_EXTCREATEFONTINDIRECTW: { + dbg_str << "\n"; - char *ansi_text; - ansi_text = (char *) U_Utf32leToUtf8((uint32_t *)dup_wt, 0, nullptr); - free(dup_wt); - // Empty string or starts with an invalid escape/control sequence, which is bogus text. Throw it out before g_markup_escape_text can make things worse - if(*((uint8_t *)ansi_text) <= 0x1F){ - free(ansi_text); - ansi_text=nullptr; + PU_EMREXTCREATEFONTINDIRECTW pEmr = (PU_EMREXTCREATEFONTINDIRECTW)lpEMFR; + insert_object(d, pEmr->ihFont, U_EMR_EXTCREATEFONTINDIRECTW, lpEMFR); + break; } + case U_EMR_EXTTEXTOUTA: + case U_EMR_EXTTEXTOUTW: + case U_EMR_SMALLTEXTOUT: { + dbg_str << "\n"; + + PU_EMREXTTEXTOUTW pEmr = (PU_EMREXTTEXTOUTW)lpEMFR; + PU_EMRSMALLTEXTOUT pEmrS = (PU_EMRSMALLTEXTOUT)lpEMFR; + + double x1, y1; + int roff = sizeof(U_EMRSMALLTEXTOUT); // offset to the start of the variable fields, only used with + // U_EMR_SMALLTEXTOUT + int cChars; + if (lpEMFR->iType == U_EMR_SMALLTEXTOUT) { + x1 = pEmrS->Dest.x; + y1 = pEmrS->Dest.y; + cChars = pEmrS->cChars; + if (!(pEmrS->fuOptions & U_ETO_NO_RECT)) { + roff += sizeof(U_RECTL); + } + } else { + x1 = pEmr->emrtext.ptlReference.x; + y1 = pEmr->emrtext.ptlReference.y; + cChars = 0; + } + uint32_t fOptions = pEmr->emrtext.fOptions; - if (ansi_text) { + if (d->dc[d->level].textAlign & U_TA_UPDATECP) { + x1 = d->dc[d->level].cur.x; + y1 = d->dc[d->level].cur.y; + } - SVGOStringStream ts; + double x = pix_to_x_point(d, x1, y1); + double y = pix_to_y_point(d, x1, y1); + + /* Rotation issues are handled entirely in libTERE now */ + + uint32_t *dup_wt = nullptr; + + if (lpEMFR->iType == U_EMR_EXTTEXTOUTA) { + /* These should be JUST ASCII, but they might not be... + If it holds Utf-8 or plain ASCII the first call will succeed. + If not, assume that it holds Latin1. + If that fails then something is really screwed up! + */ + dup_wt = U_Utf8ToUtf32le((char *)pEmr + pEmr->emrtext.offString, pEmr->emrtext.nChars, nullptr); + if (!dup_wt) + dup_wt = + U_Latin1ToUtf32le((char *)pEmr + pEmr->emrtext.offString, pEmr->emrtext.nChars, nullptr); + if (!dup_wt) + dup_wt = unknown_chars(pEmr->emrtext.nChars); + } else if (lpEMFR->iType == U_EMR_EXTTEXTOUTW) { + dup_wt = U_Utf16leToUtf32le((uint16_t *)((char *)pEmr + pEmr->emrtext.offString), + pEmr->emrtext.nChars, nullptr); + if (!dup_wt) + dup_wt = unknown_chars(pEmr->emrtext.nChars); + } else { // U_EMR_SMALLTEXTOUT + if (pEmrS->fuOptions & U_ETO_SMALL_CHARS) { + dup_wt = U_Utf8ToUtf32le((char *)pEmrS + roff, cChars, nullptr); + } else { + dup_wt = U_Utf16leToUtf32le((uint16_t *)((char *)pEmrS + roff), cChars, nullptr); + } + if (!dup_wt) + dup_wt = unknown_chars(cChars); + } - gchar *escaped_text = g_markup_escape_text(ansi_text, -1); + msdepua(dup_wt); // convert everything in Microsoft's private use area. For Symbol, Wingdings, Dingbats - tsp.x = x*0.8; // TERE expects sizes in points. - tsp.y = y*0.8; - tsp.color.Red = d->dc[d->level].textColor.Red; - tsp.color.Green = d->dc[d->level].textColor.Green; - tsp.color.Blue = d->dc[d->level].textColor.Blue; - tsp.color.Reserved = 0; - switch(d->dc[d->level].style.font_style.value){ - case SP_CSS_FONT_STYLE_OBLIQUE: - tsp.italics = FC_SLANT_OBLIQUE; break; - case SP_CSS_FONT_STYLE_ITALIC: - tsp.italics = FC_SLANT_ITALIC; break; - default: - case SP_CSS_FONT_STYLE_NORMAL: - tsp.italics = FC_SLANT_ROMAN; break; - } - switch(d->dc[d->level].style.font_weight.value){ - case SP_CSS_FONT_WEIGHT_100: tsp.weight = FC_WEIGHT_THIN ; break; - case SP_CSS_FONT_WEIGHT_200: tsp.weight = FC_WEIGHT_EXTRALIGHT ; break; - case SP_CSS_FONT_WEIGHT_300: tsp.weight = FC_WEIGHT_LIGHT ; break; - case SP_CSS_FONT_WEIGHT_400: tsp.weight = FC_WEIGHT_NORMAL ; break; - case SP_CSS_FONT_WEIGHT_500: tsp.weight = FC_WEIGHT_MEDIUM ; break; - case SP_CSS_FONT_WEIGHT_600: tsp.weight = FC_WEIGHT_SEMIBOLD ; break; - case SP_CSS_FONT_WEIGHT_700: tsp.weight = FC_WEIGHT_BOLD ; break; - case SP_CSS_FONT_WEIGHT_800: tsp.weight = FC_WEIGHT_EXTRABOLD ; break; - case SP_CSS_FONT_WEIGHT_900: tsp.weight = FC_WEIGHT_HEAVY ; break; - case SP_CSS_FONT_WEIGHT_NORMAL: tsp.weight = FC_WEIGHT_NORMAL ; break; - case SP_CSS_FONT_WEIGHT_BOLD: tsp.weight = FC_WEIGHT_BOLD ; break; - case SP_CSS_FONT_WEIGHT_LIGHTER: tsp.weight = FC_WEIGHT_EXTRALIGHT ; break; - case SP_CSS_FONT_WEIGHT_BOLDER: tsp.weight = FC_WEIGHT_EXTRABOLD ; break; - default: tsp.weight = FC_WEIGHT_NORMAL ; break; + if (NonToUnicode(dup_wt, d->dc[d->level].font_name)) { + free(d->dc[d->level].font_name); + d->dc[d->level].font_name = strdup("Times New Roman"); } - // EMF only supports two types of text decoration - tsp.decoration = TXTDECOR_NONE; - if(d->dc[d->level].style.text_decoration_line.underline){ tsp.decoration |= TXTDECOR_UNDER; } - if(d->dc[d->level].style.text_decoration_line.line_through){ tsp.decoration |= TXTDECOR_STRIKE;} - - // EMF textalignment is a bit strange: 0x6 is center, 0x2 is right, 0x0 is left, the value 0x4 is also drawn left - tsp.taln = ((d->dc[d->level].textAlign & U_TA_CENTER) == U_TA_CENTER) ? ALICENTER : - (((d->dc[d->level].textAlign & U_TA_CENTER) == U_TA_LEFT) ? ALILEFT : - ALIRIGHT); - tsp.taln |= ((d->dc[d->level].textAlign & U_TA_BASEBIT) ? ALIBASE : - ((d->dc[d->level].textAlign & U_TA_BOTTOM) ? ALIBOT : - ALITOP)); - - // language direction can be encoded two ways, U_TA_RTLREADING is preferred - if( (fOptions & U_ETO_RTLREADING) || (d->dc[d->level].textAlign & U_TA_RTLREADING) ){ tsp.ldir = LDIR_RL; } - else{ tsp.ldir = LDIR_LR; } - - tsp.condensed = FC_WIDTH_NORMAL; // Not implemented well in libTERE (yet) - tsp.ori = d->dc[d->level].style.baseline_shift.value; // For now orientation is always the same as escapement - tsp.ori += 180.0 * current_rotation(d)/ M_PI; // radians to degrees - tsp.string = (uint8_t *) U_strdup(escaped_text); // this will be free'd much later at a trinfo_clear(). - tsp.fs = d->dc[d->level].style.font_size.computed * 0.8; // Font size in points - char *fontspec = TR_construct_fontspec(&tsp, d->dc[d->level].font_name); - tsp.fi_idx = ftinfo_load_fontname(d->tri->fti,fontspec); - free(fontspec); - // when font name includes narrow it may not be set to "condensed". Narrow fonts do not work well anyway though - // as the metrics from fontconfig may not match, or the font may not be present. - if(0<= TR_findcasesub(d->dc[d->level].font_name, (char *) "Narrow")){ tsp.co=1; } - else { tsp.co=0; } - - int status = trinfo_load_textrec(d->tri, &tsp, tsp.ori,TR_EMFBOT); // ori is actually escapement - if(status==-1){ // change of escapement, emit what we have and reset - TR_layout_analyze(d->tri); - if (d->dc[d->level].clip_id){ - SVGOStringStream tmp_clip; - tmp_clip << "\ndc[d->level].clip_id << ")\"\n>"; - d->outsvg += tmp_clip.str().c_str(); - } - TR_layout_2_svg(d->tri); - ts << d->tri->out; - d->outsvg += ts.str().c_str(); - d->tri = trinfo_clear(d->tri); - (void) trinfo_load_textrec(d->tri, &tsp, tsp.ori,TR_EMFBOT); // ignore return status, it must work - if (d->dc[d->level].clip_id){ - d->outsvg += "\n\n"; - } + + char *ansi_text; + ansi_text = (char *)U_Utf32leToUtf8((uint32_t *)dup_wt, 0, nullptr); + free(dup_wt); + // Empty string or starts with an invalid escape/control sequence, which is bogus text. Throw it out + // before g_markup_escape_text can make things worse + if (*((uint8_t *)ansi_text) <= 0x1F) { + free(ansi_text); + ansi_text = nullptr; } - g_free(escaped_text); - free(ansi_text); - } + if (ansi_text) { + SVGOStringStream ts; - break; - } - case U_EMR_POLYBEZIER16: - { - dbg_str << "\n"; + gchar *escaped_text = g_markup_escape_text(ansi_text, -1); - PU_EMRPOLYBEZIER16 pEmr = (PU_EMRPOLYBEZIER16) lpEMFR; - PU_POINT16 apts = (PU_POINT16) pEmr->apts; // Bug in MinGW wingdi.h ? - uint32_t i,j; + tsp.x = x * 0.8; // TERE expects sizes in points. + tsp.y = y * 0.8; + tsp.color.Red = d->dc[d->level].textColor.Red; + tsp.color.Green = d->dc[d->level].textColor.Green; + tsp.color.Blue = d->dc[d->level].textColor.Blue; + tsp.color.Reserved = 0; + switch (d->dc[d->level].style.font_style.value) { + case SP_CSS_FONT_STYLE_OBLIQUE: + tsp.italics = FC_SLANT_OBLIQUE; + break; + case SP_CSS_FONT_STYLE_ITALIC: + tsp.italics = FC_SLANT_ITALIC; + break; + default: + case SP_CSS_FONT_STYLE_NORMAL: + tsp.italics = FC_SLANT_ROMAN; + break; + } + switch (d->dc[d->level].style.font_weight.value) { + case SP_CSS_FONT_WEIGHT_100: + tsp.weight = FC_WEIGHT_THIN; + break; + case SP_CSS_FONT_WEIGHT_200: + tsp.weight = FC_WEIGHT_EXTRALIGHT; + break; + case SP_CSS_FONT_WEIGHT_300: + tsp.weight = FC_WEIGHT_LIGHT; + break; + case SP_CSS_FONT_WEIGHT_400: + tsp.weight = FC_WEIGHT_NORMAL; + break; + case SP_CSS_FONT_WEIGHT_500: + tsp.weight = FC_WEIGHT_MEDIUM; + break; + case SP_CSS_FONT_WEIGHT_600: + tsp.weight = FC_WEIGHT_SEMIBOLD; + break; + case SP_CSS_FONT_WEIGHT_700: + tsp.weight = FC_WEIGHT_BOLD; + break; + case SP_CSS_FONT_WEIGHT_800: + tsp.weight = FC_WEIGHT_EXTRABOLD; + break; + case SP_CSS_FONT_WEIGHT_900: + tsp.weight = FC_WEIGHT_HEAVY; + break; + case SP_CSS_FONT_WEIGHT_NORMAL: + tsp.weight = FC_WEIGHT_NORMAL; + break; + case SP_CSS_FONT_WEIGHT_BOLD: + tsp.weight = FC_WEIGHT_BOLD; + break; + case SP_CSS_FONT_WEIGHT_LIGHTER: + tsp.weight = FC_WEIGHT_EXTRALIGHT; + break; + case SP_CSS_FONT_WEIGHT_BOLDER: + tsp.weight = FC_WEIGHT_EXTRABOLD; + break; + default: + tsp.weight = FC_WEIGHT_NORMAL; + break; + } + // EMF only supports two types of text decoration + tsp.decoration = TXTDECOR_NONE; + if (d->dc[d->level].style.text_decoration_line.underline) { + tsp.decoration |= TXTDECOR_UNDER; + } + if (d->dc[d->level].style.text_decoration_line.line_through) { + tsp.decoration |= TXTDECOR_STRIKE; + } - if (pEmr->cpts<4) - break; + // EMF textalignment is a bit strange: 0x6 is center, 0x2 is right, 0x0 is left, the value 0x4 is + // also drawn left + tsp.taln = ((d->dc[d->level].textAlign & U_TA_CENTER) == U_TA_CENTER) + ? ALICENTER + : (((d->dc[d->level].textAlign & U_TA_CENTER) == U_TA_LEFT) ? ALILEFT : ALIRIGHT); + tsp.taln |= ((d->dc[d->level].textAlign & U_TA_BASEBIT) + ? ALIBASE + : ((d->dc[d->level].textAlign & U_TA_BOTTOM) ? ALIBOT : ALITOP)); + + // language direction can be encoded two ways, U_TA_RTLREADING is preferred + if ((fOptions & U_ETO_RTLREADING) || (d->dc[d->level].textAlign & U_TA_RTLREADING)) { + tsp.ldir = LDIR_RL; + } else { + tsp.ldir = LDIR_LR; + } - d->mask |= emr_mask; + tsp.condensed = FC_WIDTH_NORMAL; // Not implemented well in libTERE (yet) + tsp.ori = d->dc[d->level].style.baseline_shift.value; // For now orientation is always the same as + // escapement + tsp.ori += 180.0 * current_rotation(d) / M_PI; // radians to degrees + tsp.string = + (uint8_t *)U_strdup(escaped_text); // this will be free'd much later at a trinfo_clear(). + tsp.fs = d->dc[d->level].style.font_size.computed * 0.8; // Font size in points + char *fontspec = TR_construct_fontspec(&tsp, d->dc[d->level].font_name); + tsp.fi_idx = ftinfo_load_fontname(d->tri->fti, fontspec); + free(fontspec); + // when font name includes narrow it may not be set to "condensed". Narrow fonts do not work well + // anyway though as the metrics from fontconfig may not match, or the font may not be present. + if (0 <= TR_findcasesub(d->dc[d->level].font_name, (char *)"Narrow")) { + tsp.co = 1; + } else { + tsp.co = 0; + } - tmp_str << "\n\tM " << pix_to_xy( d, apts[0].x, apts[0].y ) << " "; + int status = trinfo_load_textrec(d->tri, &tsp, tsp.ori, TR_EMFBOT); // ori is actually escapement + if (status == -1) { // change of escapement, emit what we have and reset + TR_layout_analyze(d->tri); + if (d->dc[d->level].clip_id) { + SVGOStringStream tmp_clip; + tmp_clip << "\ndc[d->level].clip_id << ")\"\n>"; + d->outsvg += tmp_clip.str().c_str(); + } + TR_layout_2_svg(d->tri); + ts << d->tri->out; + d->outsvg += ts.str().c_str(); + d->tri = trinfo_clear(d->tri); + (void)trinfo_load_textrec(d->tri, &tsp, tsp.ori, + TR_EMFBOT); // ignore return status, it must work + if (d->dc[d->level].clip_id) { + d->outsvg += "\n\n"; + } + } - for (i=1; icpts; ) { - tmp_str << "\n\tC "; - for (j=0; j<3 && icpts; j++,i++) { - tmp_str << pix_to_xy( d, apts[i].x, apts[i].y ) << " "; + g_free(escaped_text); + free(ansi_text); } + + break; } + case U_EMR_POLYBEZIER16: { + dbg_str << "\n"; - tmp_path << tmp_str.str().c_str(); + PU_EMRPOLYBEZIER16 pEmr = (PU_EMRPOLYBEZIER16)lpEMFR; + PU_POINT16 apts = (PU_POINT16)pEmr->apts; // Bug in MinGW wingdi.h ? + uint32_t i, j; - break; - } - case U_EMR_POLYGON16: - { - dbg_str << "\n"; + if (pEmr->cpts < 4) + break; - PU_EMRPOLYGON16 pEmr = (PU_EMRPOLYGON16) lpEMFR; - PU_POINT16 apts = (PU_POINT16) pEmr->apts; // Bug in MinGW wingdi.h ? - SVGOStringStream tmp_poly; - unsigned int i; - unsigned int first = 0; + d->mask |= emr_mask; + + tmp_str << "\n\tM " << pix_to_xy(d, apts[0].x, apts[0].y) << " "; - d->mask |= emr_mask; + for (i = 1; i < pEmr->cpts;) { + tmp_str << "\n\tC "; + for (j = 0; j < 3 && i < pEmr->cpts; j++, i++) { + tmp_str << pix_to_xy(d, apts[i].x, apts[i].y) << " "; + } + } - // skip the first point? - tmp_poly << "\n\tM " << pix_to_xy( d, apts[first].x, apts[first].y ) << " "; + tmp_path << tmp_str.str().c_str(); - for (i=first+1; icpts; i++) { - tmp_poly << "\n\tL " << pix_to_xy( d, apts[i].x, apts[i].y ) << " "; + break; } + case U_EMR_POLYGON16: { + dbg_str << "\n"; - tmp_path << tmp_poly.str().c_str(); - tmp_path << "\n\tz"; - d->mask |= U_DRAW_CLOSED; - - break; - } - case U_EMR_POLYLINE16: - { - dbg_str << "\n"; + PU_EMRPOLYGON16 pEmr = (PU_EMRPOLYGON16)lpEMFR; + PU_POINT16 apts = (PU_POINT16)pEmr->apts; // Bug in MinGW wingdi.h ? + SVGOStringStream tmp_poly; + unsigned int i; + unsigned int first = 0; - PU_EMRPOLYLINE16 pEmr = (PU_EMRPOLYLINE16) lpEMFR; - PU_POINT16 apts = (PU_POINT16) pEmr->apts; // Bug in MinGW wingdi.h ? - uint32_t i; + d->mask |= emr_mask; - if (pEmr->cpts<2) - break; + // skip the first point? + tmp_poly << "\n\tM " << pix_to_xy(d, apts[first].x, apts[first].y) << " "; - d->mask |= emr_mask; + for (i = first + 1; i < pEmr->cpts; i++) { + tmp_poly << "\n\tL " << pix_to_xy(d, apts[i].x, apts[i].y) << " "; + } - tmp_str << "\n\tM " << pix_to_xy( d, apts[0].x, apts[0].y ) << " "; + tmp_path << tmp_poly.str().c_str(); + tmp_path << "\n\tz"; + d->mask |= U_DRAW_CLOSED; - for (i=1; icpts; i++) { - tmp_str << "\n\tL " << pix_to_xy( d, apts[i].x, apts[i].y ) << " "; + break; } + case U_EMR_POLYLINE16: { + dbg_str << "\n"; - tmp_path << tmp_str.str().c_str(); + PU_EMRPOLYLINE16 pEmr = (PU_EMRPOLYLINE16)lpEMFR; + PU_POINT16 apts = (PU_POINT16)pEmr->apts; // Bug in MinGW wingdi.h ? + uint32_t i; - break; - } - case U_EMR_POLYBEZIERTO16: - { - dbg_str << "\n"; + if (pEmr->cpts < 2) + break; - PU_EMRPOLYBEZIERTO16 pEmr = (PU_EMRPOLYBEZIERTO16) lpEMFR; - PU_POINT16 apts = (PU_POINT16) pEmr->apts; // Bug in MinGW wingdi.h ? - uint32_t i,j; + d->mask |= emr_mask; - d->mask |= emr_mask; + tmp_str << "\n\tM " << pix_to_xy(d, apts[0].x, apts[0].y) << " "; - for (i=0; icpts;) { - tmp_path << "\n\tC "; - for (j=0; j<3 && icpts; j++,i++) { - tmp_path << pix_to_xy( d, apts[i].x, apts[i].y) << " "; + for (i = 1; i < pEmr->cpts; i++) { + tmp_str << "\n\tL " << pix_to_xy(d, apts[i].x, apts[i].y) << " "; } + + tmp_path << tmp_str.str().c_str(); + + break; } + case U_EMR_POLYBEZIERTO16: { + dbg_str << "\n"; - break; - } - case U_EMR_POLYLINETO16: - { - dbg_str << "\n"; + PU_EMRPOLYBEZIERTO16 pEmr = (PU_EMRPOLYBEZIERTO16)lpEMFR; + PU_POINT16 apts = (PU_POINT16)pEmr->apts; // Bug in MinGW wingdi.h ? + uint32_t i, j; - PU_EMRPOLYLINETO16 pEmr = (PU_EMRPOLYLINETO16) lpEMFR; - PU_POINT16 apts = (PU_POINT16) pEmr->apts; // Bug in MinGW wingdi.h ? - uint32_t i; + d->mask |= emr_mask; - d->mask |= emr_mask; + for (i = 0; i < pEmr->cpts;) { + tmp_path << "\n\tC "; + for (j = 0; j < 3 && i < pEmr->cpts; j++, i++) { + tmp_path << pix_to_xy(d, apts[i].x, apts[i].y) << " "; + } + } - for (i=0; icpts;i++) { - tmp_path << "\n\tL " << pix_to_xy( d, apts[i].x, apts[i].y) << " "; + break; } + case U_EMR_POLYLINETO16: { + dbg_str << "\n"; - break; - } - case U_EMR_POLYPOLYLINE16: - case U_EMR_POLYPOLYGON16: - { - if (lpEMFR->iType == U_EMR_POLYPOLYLINE16) - dbg_str << "\n"; - if (lpEMFR->iType == U_EMR_POLYPOLYGON16) - dbg_str << "\n"; + PU_EMRPOLYLINETO16 pEmr = (PU_EMRPOLYLINETO16)lpEMFR; + PU_POINT16 apts = (PU_POINT16)pEmr->apts; // Bug in MinGW wingdi.h ? + uint32_t i; - PU_EMRPOLYPOLYGON16 pEmr = (PU_EMRPOLYPOLYGON16) lpEMFR; - unsigned int n, i, j; + d->mask |= emr_mask; - d->mask |= emr_mask; + for (i = 0; i < pEmr->cpts; i++) { + tmp_path << "\n\tL " << pix_to_xy(d, apts[i].x, apts[i].y) << " "; + } - PU_POINT16 apts = (PU_POINT16) &pEmr->aPolyCounts[pEmr->nPolys]; + break; + } + case U_EMR_POLYPOLYLINE16: + case U_EMR_POLYPOLYGON16: { + if (lpEMFR->iType == U_EMR_POLYPOLYLINE16) + dbg_str << "\n"; + if (lpEMFR->iType == U_EMR_POLYPOLYGON16) + dbg_str << "\n"; - i = 0; - for (n=0; nnPolys && icpts; n++) { - SVGOStringStream poly_path; + PU_EMRPOLYPOLYGON16 pEmr = (PU_EMRPOLYPOLYGON16)lpEMFR; + unsigned int n, i, j; - poly_path << "\n\tM " << pix_to_xy( d, apts[i].x, apts[i].y) << " "; - i++; + d->mask |= emr_mask; - for (j=1; jaPolyCounts[n] && icpts; j++) { - poly_path << "\n\tL " << pix_to_xy( d, apts[i].x, apts[i].y) << " "; + PU_POINT16 apts = (PU_POINT16)&pEmr->aPolyCounts[pEmr->nPolys]; + + i = 0; + for (n = 0; n < pEmr->nPolys && i < pEmr->cpts; n++) { + SVGOStringStream poly_path; + + poly_path << "\n\tM " << pix_to_xy(d, apts[i].x, apts[i].y) << " "; i++; + + for (j = 1; j < pEmr->aPolyCounts[n] && i < pEmr->cpts; j++) { + poly_path << "\n\tL " << pix_to_xy(d, apts[i].x, apts[i].y) << " "; + i++; + } + + tmp_str << poly_path.str().c_str(); + if (lpEMFR->iType == U_EMR_POLYPOLYGON16) + tmp_str << " z"; + tmp_str << " \n"; } - tmp_str << poly_path.str().c_str(); - if (lpEMFR->iType == U_EMR_POLYPOLYGON16) - tmp_str << " z"; - tmp_str << " \n"; + tmp_path << tmp_str.str().c_str(); + + break; } + case U_EMR_POLYDRAW16: + dbg_str << "\n"; + break; + case U_EMR_CREATEMONOBRUSH: { + dbg_str << "\n"; - tmp_path << tmp_str.str().c_str(); + PU_EMRCREATEMONOBRUSH pEmr = (PU_EMRCREATEMONOBRUSH)lpEMFR; + insert_object(d, pEmr->ihBrush, U_EMR_CREATEMONOBRUSH, lpEMFR); + break; + } + case U_EMR_CREATEDIBPATTERNBRUSHPT: { + dbg_str << "\n"; - break; - } - case U_EMR_POLYDRAW16: dbg_str << "\n"; break; - case U_EMR_CREATEMONOBRUSH: - { - dbg_str << "\n"; + PU_EMRCREATEDIBPATTERNBRUSHPT pEmr = (PU_EMRCREATEDIBPATTERNBRUSHPT)lpEMFR; + insert_object(d, pEmr->ihBrush, U_EMR_CREATEDIBPATTERNBRUSHPT, lpEMFR); + break; + } + case U_EMR_EXTCREATEPEN: { + dbg_str << "\n"; - PU_EMRCREATEMONOBRUSH pEmr = (PU_EMRCREATEMONOBRUSH) lpEMFR; - insert_object(d, pEmr->ihBrush, U_EMR_CREATEMONOBRUSH, lpEMFR); - break; - } - case U_EMR_CREATEDIBPATTERNBRUSHPT: - { - dbg_str << "\n"; + PU_EMREXTCREATEPEN pEmr = (PU_EMREXTCREATEPEN)lpEMFR; + insert_object(d, pEmr->ihPen, U_EMR_EXTCREATEPEN, lpEMFR); + break; + } + case U_EMR_POLYTEXTOUTA: + dbg_str << "\n"; + break; + case U_EMR_POLYTEXTOUTW: + dbg_str << "\n"; + break; + case U_EMR_SETICMMODE: { + dbg_str << "\n"; + PU_EMRSETICMMODE pEmr = (PU_EMRSETICMMODE)lpEMFR; + ICMmode = pEmr->iMode; + break; + } + case U_EMR_CREATECOLORSPACE: + dbg_str << "\n"; + break; + case U_EMR_SETCOLORSPACE: + dbg_str << "\n"; + break; + case U_EMR_DELETECOLORSPACE: + dbg_str << "\n"; + break; + case U_EMR_GLSRECORD: + dbg_str << "\n"; + break; + case U_EMR_GLSBOUNDEDRECORD: + dbg_str << "\n"; + break; + case U_EMR_PIXELFORMAT: + dbg_str << "\n"; + break; + case U_EMR_DRAWESCAPE: + dbg_str << "\n"; + break; + case U_EMR_EXTESCAPE: + dbg_str << "\n"; + break; + case U_EMR_UNDEF107: + dbg_str << "\n"; + break; + // U_EMR_SMALLTEXTOUT is handled with U_EMR_EXTTEXTOUTA/W above + case U_EMR_FORCEUFIMAPPING: + dbg_str << "\n"; + break; + case U_EMR_NAMEDESCAPE: + dbg_str << "\n"; + break; + case U_EMR_COLORCORRECTPALETTE: + dbg_str << "\n"; + break; + case U_EMR_SETICMPROFILEA: + dbg_str << "\n"; + break; + case U_EMR_SETICMPROFILEW: + dbg_str << "\n"; + break; + case U_EMR_ALPHABLEND: + dbg_str << "\n"; + break; + case U_EMR_SETLAYOUT: + dbg_str << "\n"; + break; + case U_EMR_TRANSPARENTBLT: + dbg_str << "\n"; + break; + case U_EMR_UNDEF117: + dbg_str << "\n"; + break; + case U_EMR_GRADIENTFILL: { + /* Gradient fill is doable for rectangles because those correspond to linear gradients. However, + the general case for the triangle fill, with a different color in each corner of the triangle, + has no SVG equivalent and cannot be easily emulated with SVG gradients. So the linear gradient + is implemented, and the triangle fill just paints with the color of the first corner. - PU_EMRCREATEDIBPATTERNBRUSHPT pEmr = (PU_EMRCREATEDIBPATTERNBRUSHPT) lpEMFR; - insert_object(d, pEmr->ihBrush, U_EMR_CREATEDIBPATTERNBRUSHPT, lpEMFR); - break; - } - case U_EMR_EXTCREATEPEN: - { - dbg_str << "\n"; + This record can hold a series of gradients so we are forced to add path elements directly here, + it cannot wait for the top of the main loop. Any existing path is erased. - PU_EMREXTCREATEPEN pEmr = (PU_EMREXTCREATEPEN) lpEMFR; - insert_object(d, pEmr->ihPen, U_EMR_EXTCREATEPEN, lpEMFR); - break; - } - case U_EMR_POLYTEXTOUTA: dbg_str << "\n"; break; - case U_EMR_POLYTEXTOUTW: dbg_str << "\n"; break; - case U_EMR_SETICMMODE: - { - dbg_str << "\n"; - PU_EMRSETICMMODE pEmr = (PU_EMRSETICMMODE) lpEMFR; - ICMmode= pEmr->iMode; - break; - } - case U_EMR_CREATECOLORSPACE: dbg_str << "\n"; break; - case U_EMR_SETCOLORSPACE: dbg_str << "\n"; break; - case U_EMR_DELETECOLORSPACE: dbg_str << "\n"; break; - case U_EMR_GLSRECORD: dbg_str << "\n"; break; - case U_EMR_GLSBOUNDEDRECORD: dbg_str << "\n"; break; - case U_EMR_PIXELFORMAT: dbg_str << "\n"; break; - case U_EMR_DRAWESCAPE: dbg_str << "\n"; break; - case U_EMR_EXTESCAPE: dbg_str << "\n"; break; - case U_EMR_UNDEF107: dbg_str << "\n"; break; - // U_EMR_SMALLTEXTOUT is handled with U_EMR_EXTTEXTOUTA/W above - case U_EMR_FORCEUFIMAPPING: dbg_str << "\n"; break; - case U_EMR_NAMEDESCAPE: dbg_str << "\n"; break; - case U_EMR_COLORCORRECTPALETTE: dbg_str << "\n"; break; - case U_EMR_SETICMPROFILEA: dbg_str << "\n"; break; - case U_EMR_SETICMPROFILEW: dbg_str << "\n"; break; - case U_EMR_ALPHABLEND: dbg_str << "\n"; break; - case U_EMR_SETLAYOUT: dbg_str << "\n"; break; - case U_EMR_TRANSPARENTBLT: dbg_str << "\n"; break; - case U_EMR_UNDEF117: dbg_str << "\n"; break; - case U_EMR_GRADIENTFILL: - { - /* Gradient fill is doable for rectangles because those correspond to linear gradients. However, - the general case for the triangle fill, with a different color in each corner of the triangle, - has no SVG equivalent and cannot be easily emulated with SVG gradients. So the linear gradient - is implemented, and the triangle fill just paints with the color of the first corner. - - This record can hold a series of gradients so we are forced to add path elements directly here, - it cannot wait for the top of the main loop. Any existing path is erased. - - */ - dbg_str << "\n"; - PU_EMRGRADIENTFILL pEmr = (PU_EMRGRADIENTFILL) lpEMFR; - int nV = pEmr->nTriVert; // Number of TriVertex objects - int nG = pEmr->nGradObj; // Number of gradient triangle/rectangle objects - U_TRIVERTEX *tv = (U_TRIVERTEX *)(((char *)lpEMFR) + sizeof(U_EMRGRADIENTFILL)); - if( pEmr->ulMode == U_GRADIENT_FILL_RECT_H || - pEmr->ulMode == U_GRADIENT_FILL_RECT_V - ){ - SVGOStringStream tmp_rectangle; - int i,fill_idx; - U_GRADIENT4 *rcs = (U_GRADIENT4 *)(((char *)lpEMFR) + sizeof(U_EMRGRADIENTFILL) + sizeof(U_TRIVERTEX)*nV); - for(i=0;iulMode, tv[rcs[i].UpperLeft], tv[rcs[i].LowerRight]); - tmp_rectangle << "\n\tM " << pix_to_xy( d, tv[rcs[i].UpperLeft ].x , tv[rcs[i].UpperLeft ].y ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, tv[rcs[i].LowerRight].x , tv[rcs[i].UpperLeft ].y ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, tv[rcs[i].LowerRight].x , tv[rcs[i].LowerRight].y ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, tv[rcs[i].UpperLeft ].x , tv[rcs[i].LowerRight].y ) << " "; - tmp_rectangle << "\n\tz\""; - tmp_rectangle << "\n\tstyle=\"stroke:none;fill:url(#"; - tmp_rectangle << d->gradients.strings[fill_idx]; - tmp_rectangle << ");\"\n"; - if (d->dc[d->level].clip_id){ - tmp_rectangle << "\tclip-path=\"url(#clipEmfPath" << d->dc[d->level].clip_id << ")\"\n"; - } - tmp_rectangle << "/>\n"; - } - d->outsvg += tmp_rectangle.str().c_str(); - } - else if(pEmr->ulMode == U_GRADIENT_FILL_TRIANGLE){ - SVGOStringStream tmp_triangle; - char tmpcolor[8]; - int i; - U_GRADIENT3 *tris = (U_GRADIENT3 *)(((char *)lpEMFR) + sizeof(U_EMRGRADIENTFILL) + sizeof(U_TRIVERTEX)*nV); - for(i=0;i\n"; - } - d->outsvg += tmp_triangle.str().c_str(); - } - d->path = ""; - // if it is anything else the record is bogus, so ignore it - break; + */ + dbg_str << "\n"; + PU_EMRGRADIENTFILL pEmr = (PU_EMRGRADIENTFILL)lpEMFR; + int nV = pEmr->nTriVert; // Number of TriVertex objects + int nG = pEmr->nGradObj; // Number of gradient triangle/rectangle objects + U_TRIVERTEX *tv = (U_TRIVERTEX *)(((char *)lpEMFR) + sizeof(U_EMRGRADIENTFILL)); + if (pEmr->ulMode == U_GRADIENT_FILL_RECT_H || pEmr->ulMode == U_GRADIENT_FILL_RECT_V) { + SVGOStringStream tmp_rectangle; + int i, fill_idx; + U_GRADIENT4 *rcs = + (U_GRADIENT4 *)(((char *)lpEMFR) + sizeof(U_EMRGRADIENTFILL) + sizeof(U_TRIVERTEX) * nV); + for (i = 0; i < nG; i++) { + tmp_rectangle << "\nulMode, tv[rcs[i].UpperLeft], tv[rcs[i].LowerRight]); + tmp_rectangle << "\n\tM " << pix_to_xy(d, tv[rcs[i].UpperLeft].x, tv[rcs[i].UpperLeft].y) + << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, tv[rcs[i].LowerRight].x, tv[rcs[i].UpperLeft].y) + << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, tv[rcs[i].LowerRight].x, tv[rcs[i].LowerRight].y) + << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, tv[rcs[i].UpperLeft].x, tv[rcs[i].LowerRight].y) + << " "; + tmp_rectangle << "\n\tz\""; + tmp_rectangle << "\n\tstyle=\"stroke:none;fill:url(#"; + tmp_rectangle << d->gradients.strings[fill_idx]; + tmp_rectangle << ");\"\n"; + if (d->dc[d->level].clip_id) { + tmp_rectangle << "\tclip-path=\"url(#clipEmfPath" << d->dc[d->level].clip_id << ")\"\n"; + } + tmp_rectangle << "/>\n"; + } + d->outsvg += tmp_rectangle.str().c_str(); + } else if (pEmr->ulMode == U_GRADIENT_FILL_TRIANGLE) { + SVGOStringStream tmp_triangle; + char tmpcolor[8]; + int i; + U_GRADIENT3 *tris = + (U_GRADIENT3 *)(((char *)lpEMFR) + sizeof(U_EMRGRADIENTFILL) + sizeof(U_TRIVERTEX) * nV); + for (i = 0; i < nG; i++) { + tmp_triangle << "\n\n"; + } + d->outsvg += tmp_triangle.str().c_str(); + } + d->path = ""; + // if it is anything else the record is bogus, so ignore it + break; + } + case U_EMR_SETLINKEDUFIS: + dbg_str << "\n"; + break; + case U_EMR_SETTEXTJUSTIFICATION: + dbg_str << "\n"; + break; + case U_EMR_COLORMATCHTOTARGETW: + dbg_str << "\n"; + break; + case U_EMR_CREATECOLORSPACEW: + dbg_str << "\n"; + break; + default: + dbg_str << "\n"; + break; + } // end of switch + // At run time define environment variable INKSCAPE_DBG_EMF to include string COMMENT. + // Users may employ this to to place a comment for each processed EMR record in the SVG + if (eDbgComment) { + d->outsvg += dbg_str.str().c_str(); } - case U_EMR_SETLINKEDUFIS: dbg_str << "\n"; break; - case U_EMR_SETTEXTJUSTIFICATION: dbg_str << "\n"; break; - case U_EMR_COLORMATCHTOTARGETW: dbg_str << "\n"; break; - case U_EMR_CREATECOLORSPACEW: dbg_str << "\n"; break; - default: - dbg_str << "\n"; - break; - } //end of switch -// At run time define environment variable INKSCAPE_DBG_EMF to include string COMMENT. -// Users may employ this to to place a comment for each processed EMR record in the SVG - if(eDbgComment){ - d->outsvg += dbg_str.str().c_str(); - } - d->outsvg += tmp_outsvg.str().c_str(); - d->path += tmp_path.str().c_str(); - - } //end of while -// At run time define environment variable INKSCAPE_DBG_EMF to include string FINAL -// Users may employ this to to show the final SVG derived from the EMF - if(eDbgFinal){ - std::cout << d->outsvg << std::endl; + d->outsvg += tmp_outsvg.str().c_str(); + d->path += tmp_path.str().c_str(); + + } // end of while + // At run time define environment variable INKSCAPE_DBG_EMF to include string FINAL + // Users may employ this to to show the final SVG derived from the EMF + if (eDbgFinal) { + std::cout << d->outsvg << std::endl; } - (void) emr_properties(U_EMR_INVALID); // force the release of the lookup table memory, returned value is irrelevant + (void)emr_properties(U_EMR_INVALID); // force the release of the lookup table memory, returned value is irrelevant - return(file_status); + return (file_status); } -void Emf::free_emf_strings(EMF_STRINGS name){ - if(name.count){ - for(int i=0; i< name.count; i++){ free(name.strings[i]); } +void Emf::free_emf_strings(EMF_STRINGS name) +{ + if (name.count) { + for (int i = 0; i < name.count; i++) { + free(name.strings[i]); + } free(name.strings); } name.count = 0; name.size = 0; } -SPDocument * -Emf::open( Inkscape::Extension::Input * /*mod*/, const gchar *uri ) +SPDocument *Emf::open(Inkscape::Extension::Input * /*mod*/, const gchar *uri) { if (uri == nullptr) { return nullptr; @@ -3559,11 +3672,13 @@ Emf::open( Inkscape::Extension::Input * /*mod*/, const gchar *uri ) EMF_CALLBACK_DATA d; - d.n_obj = 0; //these might not be set otherwise if the input file is corrupt - d.emf_obj = nullptr; - d.dc[0].font_name = strdup("Arial"); // Default font, set only on lowest level, it copies up from there EMF spec says device can pick whatever it wants + d.n_obj = 0; // these might not be set otherwise if the input file is corrupt + d.emf_obj = nullptr; + d.dc[0].font_name = strdup("Arial"); // Default font, set only on lowest level, it copies up from there EMF spec + // says device can pick whatever it wants - // set up the size default for patterns in defs. This might not be referenced if there are no patterns defined in the drawing. + // set up the size default for patterns in defs. This might not be referenced if there are no patterns defined in + // the drawing. d.defs += "\n"; d.defs += " \n"; d.defs += " \n"; - size_t length; char *contents; - if(emf_readdata(uri, &contents, &length))return(nullptr); + if (emf_readdata(uri, &contents, &length)) + return (nullptr); d.pDesc = nullptr; // set up the text reassembly system - if(!(d.tri = trinfo_init(nullptr)))return(nullptr); - (void) trinfo_load_ft_opts(d.tri, 1, - FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, - FT_KERNING_UNSCALED); + if (!(d.tri = trinfo_init(nullptr))) + return (nullptr); + (void)trinfo_load_ft_opts(d.tri, 1, FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, FT_KERNING_UNSCALED); - int good = myEnhMetaFileProc(contents,length, &d); + int good = myEnhMetaFileProc(contents, length, &d); free(contents); - if (d.pDesc){ free( d.pDesc ); } + if (d.pDesc) { + free(d.pDesc); + } -// std::cout << "SVG Output: " << std::endl << d.outsvg << std::endl; + // std::cout << "SVG Output: " << std::endl << d.outsvg << std::endl; SPDocument *doc = nullptr; if (good) { @@ -3606,15 +3722,16 @@ Emf::open( Inkscape::Extension::Input * /*mod*/, const gchar *uri ) if (d.emf_obj) { int i; - for (i=0; i -#include <3rdparty/libuemf/uemf_safe.h> #include <3rdparty/libuemf/uemf_endian.h> // for U_emf_record_sizeok() -#include "extension/internal/metafile-inout.h" // picks up PNG +#include <3rdparty/libuemf/uemf_safe.h> + #include "extension/implementation/implementation.h" +#include "extension/internal/metafile-inout.h" // picks up PNG #include "style.h" #include "text_reassemble.h" @@ -25,46 +26,59 @@ namespace Inkscape { namespace Extension { namespace Internal { -#define DIRTY_NONE 0x00 -#define DIRTY_TEXT 0x01 -#define DIRTY_FILL 0x02 +#define DIRTY_NONE 0x00 +#define DIRTY_TEXT 0x01 +#define DIRTY_FILL 0x02 #define DIRTY_STROKE 0x04 -struct EMF_OBJECT { +struct EMF_OBJECT +{ int type = 0; int level = 0; char *lpEMFR = nullptr; }; using PEMF_OBJECT = EMF_OBJECT *; -struct EMF_STRINGS { - int size = 0; // number of slots allocated in strings - int count = 0; // number of slots used in strings - char **strings = nullptr; // place to store strings +struct EMF_STRINGS +{ + int size = 0; // number of slots allocated in strings + int count = 0; // number of slots used in strings + char **strings = nullptr; // place to store strings }; using PEMF_STRINGS = EMF_STRINGS *; -struct EMF_DEVICE_CONTEXT { - EMF_DEVICE_CONTEXT() : - // SPStyle: class with constructor - font_name(nullptr), - clip_id(0), - stroke_set(false), stroke_mode(0), stroke_idx(0), stroke_recidx(0), - fill_set(false), fill_mode(0), fill_idx(0), fill_recidx(0), - dirty(0), +struct EMF_DEVICE_CONTEXT +{ + EMF_DEVICE_CONTEXT() + : // SPStyle: class with constructor + font_name(nullptr) + , clip_id(0) + , stroke_set(false) + , stroke_mode(0) + , stroke_idx(0) + , stroke_recidx(0) + , fill_set(false) + , fill_mode(0) + , fill_idx(0) + , fill_recidx(0) + , dirty(0) + , // sizeWnd, sizeView, winorg, vieworg, - ScaleInX(0), ScaleInY(0), - ScaleOutX(0), ScaleOutY(0), - bkMode(U_TRANSPARENT), + ScaleInX(0) + , ScaleInY(0) + , ScaleOutX(0) + , ScaleOutY(0) + , bkMode(U_TRANSPARENT) + , // bkColor, textColor textAlign(0) - // worldTransform, cur + // worldTransform, cur { font_name = nullptr; - sizeWnd = sizel_set( 0.0, 0.0 ); - sizeView = sizel_set( 0.0, 0.0 ); - winorg = point32_set( 0.0, 0.0 ); - vieworg = point32_set( 0.0, 0.0 ); + sizeWnd = sizel_set(0.0, 0.0); + sizeView = sizel_set(0.0, 0.0); + winorg = point32_set(0.0, 0.0); + vieworg = point32_set(0.0, 0.0); bkColor = U_RGB(255, 255, 255); // default foreground color (white) textColor = U_RGB(0, 0, 0); // default foreground color (black) worldTransform.eM11 = 1.0; @@ -73,168 +87,173 @@ struct EMF_DEVICE_CONTEXT { worldTransform.eM22 = 1.0; worldTransform.eDx = 0.0; worldTransform.eDy = 0.0; - cur = point32_set( 0, 0 ); - }; - SPStyle style; - char *font_name; - int clip_id; // 0 if none, else 1 + index into clips - bool stroke_set; - int stroke_mode; // enumeration from drawmode, not used if fill_set is not True - int stroke_idx; // used with DRAW_PATTERN and DRAW_IMAGE to return the appropriate fill - int stroke_recidx;// record used to regenerate hatch when it needs to be redone due to bkmode, textmode, etc. change - bool fill_set; - int fill_mode; // enumeration from drawmode, not used if fill_set is not True - int fill_idx; // used with DRAW_PATTERN and DRAW_IMAGE to return the appropriate fill - int fill_recidx; // record used to regenerate hatch when it needs to be redone due to bkmode, textmode, etc. change - int dirty; // holds the dirty bits for text, stroke, fill - U_SIZEL sizeWnd; - U_SIZEL sizeView; - U_POINTL winorg; - U_POINTL vieworg; - double ScaleInX, ScaleInY; - double ScaleOutX, ScaleOutY; - uint16_t bkMode; - U_COLORREF bkColor; - U_COLORREF textColor; - uint32_t textAlign; - U_XFORM worldTransform; - U_POINTL cur; + cur = point32_set(0, 0); + }; + SPStyle style; + char *font_name; + int clip_id; // 0 if none, else 1 + index into clips + bool stroke_set; + int stroke_mode; // enumeration from drawmode, not used if fill_set is not True + int stroke_idx; // used with DRAW_PATTERN and DRAW_IMAGE to return the appropriate fill + int stroke_recidx; // record used to regenerate hatch when it needs to be redone due to bkmode, textmode, etc. + // change + bool fill_set; + int fill_mode; // enumeration from drawmode, not used if fill_set is not True + int fill_idx; // used with DRAW_PATTERN and DRAW_IMAGE to return the appropriate fill + int fill_recidx; // record used to regenerate hatch when it needs to be redone due to bkmode, textmode, etc. change + int dirty; // holds the dirty bits for text, stroke, fill + U_SIZEL sizeWnd; + U_SIZEL sizeView; + U_POINTL winorg; + U_POINTL vieworg; + double ScaleInX, ScaleInY; + double ScaleOutX, ScaleOutY; + uint16_t bkMode; + U_COLORREF bkColor; + U_COLORREF textColor; + uint32_t textAlign; + U_XFORM worldTransform; + U_POINTL cur; }; using PEMF_DEVICE_CONTEXT = EMF_DEVICE_CONTEXT *; #define EMF_MAX_DC 128 -struct EMF_CALLBACK_DATA { - - EMF_CALLBACK_DATA() : - // dc: array, structure w/ constructor - level(0), - E2IdirY(1.0), - D2PscaleX(1.0), D2PscaleY(1.0), - MM100InX(0), MM100InY(0), - PixelsInX(0), PixelsInY(0), - PixelsOutX(0), PixelsOutY(0), - ulCornerInX(0), ulCornerInY(0), - ulCornerOutX(0), ulCornerOutY(0), - mask(0), - arcdir(U_AD_COUNTERCLOCKWISE), - dwRop2(U_R2_COPYPEN), dwRop3(0), - MMX(0),MMY(0), - drawtype(0), - pDesc(nullptr), +struct EMF_CALLBACK_DATA +{ + EMF_CALLBACK_DATA() + : // dc: array, structure w/ constructor + level(0) + , E2IdirY(1.0) + , D2PscaleX(1.0) + , D2PscaleY(1.0) + , MM100InX(0) + , MM100InY(0) + , PixelsInX(0) + , PixelsInY(0) + , PixelsOutX(0) + , PixelsOutY(0) + , ulCornerInX(0) + , ulCornerInY(0) + , ulCornerOutX(0) + , ulCornerOutY(0) + , mask(0) + , arcdir(U_AD_COUNTERCLOCKWISE) + , dwRop2(U_R2_COPYPEN) + , dwRop3(0) + , MMX(0) + , MMY(0) + , drawtype(0) + , pDesc(nullptr) + , // hatches, images, gradients, struct w/ constructor - tri(nullptr), - n_obj(0) + tri(nullptr) + , n_obj(0) // emf_obj; - {}; + {}; Glib::ustring outsvg; Glib::ustring path; Glib::ustring outdef; Glib::ustring defs; - EMF_DEVICE_CONTEXT dc[EMF_MAX_DC+1]; // FIXME: This should be dynamic.. + EMF_DEVICE_CONTEXT dc[EMF_MAX_DC + 1]; // FIXME: This should be dynamic.. int level; - - double E2IdirY; // EMF Y direction relative to Inkscape Y direction. Will be negative for MM_LOMETRIC etc. - double D2PscaleX,D2PscaleY; // EMF device to Inkscape Page scale. - float MM100InX, MM100InY; // size of the drawing in hundredths of a millimeter - float PixelsInX, PixelsInY; // size of the drawing, in EMF device pixels - float PixelsOutX, PixelsOutY; // size of the drawing, in Inkscape pixels - double ulCornerInX,ulCornerInY; // Upper left corner, from header rclBounds, in logical units - double ulCornerOutX,ulCornerOutY; // Upper left corner, in Inkscape pixels - uint32_t mask; // Draw properties - int arcdir; //U_AD_COUNTERCLOCKWISE 1 or U_AD_CLOCKWISE 2 - - uint32_t dwRop2; // Binary raster operation, 0 if none (use brush/pen unmolested) - uint32_t dwRop3; // Ternary raster operation, 0 if none (use brush/pen unmolested) + + double E2IdirY; // EMF Y direction relative to Inkscape Y direction. Will be negative for MM_LOMETRIC etc. + double D2PscaleX, D2PscaleY; // EMF device to Inkscape Page scale. + float MM100InX, MM100InY; // size of the drawing in hundredths of a millimeter + float PixelsInX, PixelsInY; // size of the drawing, in EMF device pixels + float PixelsOutX, PixelsOutY; // size of the drawing, in Inkscape pixels + double ulCornerInX, ulCornerInY; // Upper left corner, from header rclBounds, in logical units + double ulCornerOutX, ulCornerOutY; // Upper left corner, in Inkscape pixels + uint32_t mask; // Draw properties + int arcdir; // U_AD_COUNTERCLOCKWISE 1 or U_AD_CLOCKWISE 2 + + uint32_t dwRop2; // Binary raster operation, 0 if none (use brush/pen unmolested) + uint32_t dwRop3; // Ternary raster operation, 0 if none (use brush/pen unmolested) float MMX; float MMY; - unsigned int drawtype; // one of 0 or U_EMR_FILLPATH, U_EMR_STROKEPATH, U_EMR_STROKEANDFILLPATH + unsigned int drawtype; // one of 0 or U_EMR_FILLPATH, U_EMR_STROKEPATH, U_EMR_STROKEANDFILLPATH char *pDesc; - // both of these end up in under the names shown here. These structures allow duplicates to be avoided. - EMF_STRINGS hatches; // hold pattern names, all like EMFhatch#_$$$$$$ where # is the EMF hatch code and $$$$$$ is the color - EMF_STRINGS images; // hold images, all like Image#, where # is the slot the image lives. - EMF_STRINGS gradients; // hold gradient names, all like EMF[HV]_$$$$$$_$$$$$$ where $$$$$$ are the colors - EMF_STRINGS clips; // hold clipping paths, referred to be the slot where the clipping path lives - TR_INFO *tri; // Text Reassembly data structure - + // both of these end up in under the names shown here. These structures allow duplicates to be avoided. + EMF_STRINGS hatches; // hold pattern names, all like EMFhatch#_$$$$$$ where # is the EMF hatch code and $$$$$$ is + // the color + EMF_STRINGS images; // hold images, all like Image#, where # is the slot the image lives. + EMF_STRINGS gradients; // hold gradient names, all like EMF[HV]_$$$$$$_$$$$$$ where $$$$$$ are the colors + EMF_STRINGS clips; // hold clipping paths, referred to be the slot where the clipping path lives + TR_INFO *tri; // Text Reassembly data structure int n_obj; PEMF_OBJECT emf_obj; }; using PEMF_CALLBACK_DATA = EMF_CALLBACK_DATA *; -class Emf : public Metafile -{ - +class Emf : public Metafile +{ public: - Emf(); // Empty constructor - ~Emf() override;//Destructor + ~Emf() override; // Destructor - bool check(Inkscape::Extension::Extension *module) override; //Can this module load (always yes for now) + bool check(Inkscape::Extension::Extension *module) override; // Can this module load (always yes for now) void save(Inkscape::Extension::Output *mod, // Save the given document to the given filename - SPDocument *doc, - gchar const *filename) override; + SPDocument *doc, gchar const *filename) override; - SPDocument *open( Inkscape::Extension::Input *mod, - const gchar *uri ) override; + SPDocument *open(Inkscape::Extension::Input *mod, const gchar *uri) override; - static void init();//Initialize the class + static void init(); // Initialize the class private: - protected: - static void print_document_to_file(SPDocument *doc, const gchar *filename); - static double current_scale(PEMF_CALLBACK_DATA d); + static void print_document_to_file(SPDocument *doc, const gchar *filename); + static double current_scale(PEMF_CALLBACK_DATA d); static std::string current_matrix(PEMF_CALLBACK_DATA d, double x, double y, int useoffset); - static double current_rotation(PEMF_CALLBACK_DATA d); - static void enlarge_hatches(PEMF_CALLBACK_DATA d); - static int in_hatches(PEMF_CALLBACK_DATA d, char *test); - static uint32_t add_hatch(PEMF_CALLBACK_DATA d, uint32_t hatchType, U_COLORREF hatchColor); - static void enlarge_images(PEMF_CALLBACK_DATA d); - static int in_images(PEMF_CALLBACK_DATA d, const char *test); - static uint32_t add_image(PEMF_CALLBACK_DATA d, void *pEmr, uint32_t cbBits, uint32_t cbBmi, - uint32_t iUsage, uint32_t offBits, uint32_t offBmi); - static void enlarge_gradients(PEMF_CALLBACK_DATA d); - static int in_gradients(PEMF_CALLBACK_DATA d, const char *test); - static uint32_t add_gradient(PEMF_CALLBACK_DATA d, uint32_t gradientType, U_TRIVERTEX tv1, U_TRIVERTEX tv2); - - static void enlarge_clips(PEMF_CALLBACK_DATA d); - static int in_clips(PEMF_CALLBACK_DATA d, const char *test); - static void add_clips(PEMF_CALLBACK_DATA d, const char *clippath, unsigned int logic); - - static void output_style(PEMF_CALLBACK_DATA d, int iType); - static double _pix_x_to_point(PEMF_CALLBACK_DATA d, double px); - static double _pix_y_to_point(PEMF_CALLBACK_DATA d, double py); - static double pix_to_x_point(PEMF_CALLBACK_DATA d, double px, double py); - static double pix_to_y_point(PEMF_CALLBACK_DATA d, double px, double py); - static double pix_to_abs_size(PEMF_CALLBACK_DATA d, double px); - static void snap_to_faraway_pair(double *x, double *y); + static double current_rotation(PEMF_CALLBACK_DATA d); + static void enlarge_hatches(PEMF_CALLBACK_DATA d); + static int in_hatches(PEMF_CALLBACK_DATA d, char *test); + static uint32_t add_hatch(PEMF_CALLBACK_DATA d, uint32_t hatchType, U_COLORREF hatchColor); + static void enlarge_images(PEMF_CALLBACK_DATA d); + static int in_images(PEMF_CALLBACK_DATA d, const char *test); + static uint32_t add_image(PEMF_CALLBACK_DATA d, void *pEmr, uint32_t cbBits, uint32_t cbBmi, uint32_t iUsage, + uint32_t offBits, uint32_t offBmi); + static void enlarge_gradients(PEMF_CALLBACK_DATA d); + static int in_gradients(PEMF_CALLBACK_DATA d, const char *test); + static uint32_t add_gradient(PEMF_CALLBACK_DATA d, uint32_t gradientType, U_TRIVERTEX tv1, U_TRIVERTEX tv2); + + static void enlarge_clips(PEMF_CALLBACK_DATA d); + static int in_clips(PEMF_CALLBACK_DATA d, const char *test); + static void add_clips(PEMF_CALLBACK_DATA d, const char *clippath, unsigned int logic); + + static void output_style(PEMF_CALLBACK_DATA d, int iType); + static double _pix_x_to_point(PEMF_CALLBACK_DATA d, double px); + static double _pix_y_to_point(PEMF_CALLBACK_DATA d, double py); + static double pix_to_x_point(PEMF_CALLBACK_DATA d, double px, double py); + static double pix_to_y_point(PEMF_CALLBACK_DATA d, double px, double py); + static double pix_to_abs_size(PEMF_CALLBACK_DATA d, double px); + static void snap_to_faraway_pair(double *x, double *y); static std::string pix_to_xy(PEMF_CALLBACK_DATA d, double x, double y); - static void select_pen(PEMF_CALLBACK_DATA d, int index); - static void select_extpen(PEMF_CALLBACK_DATA d, int index); - static void select_brush(PEMF_CALLBACK_DATA d, int index); - static void select_font(PEMF_CALLBACK_DATA d, int index); - static void delete_object(PEMF_CALLBACK_DATA d, int index); - static void insert_object(PEMF_CALLBACK_DATA d, int index, int type, PU_ENHMETARECORD pObj); - static int AI_hack(PU_EMRHEADER pEmr); - static uint32_t *unknown_chars(size_t count); - static void common_image_extraction(PEMF_CALLBACK_DATA d, void *pEmr, - double dx, double dy, double dw, double dh, int sx, int sy, int sw, int sh, - uint32_t iUsage, uint32_t offBits, uint32_t cbBits, uint32_t offBmi, uint32_t cbBmi); - static int myEnhMetaFileProc(char *contents, unsigned int length, PEMF_CALLBACK_DATA d); - static void free_emf_strings(EMF_STRINGS name); - + static void select_pen(PEMF_CALLBACK_DATA d, int index); + static void select_extpen(PEMF_CALLBACK_DATA d, int index); + static void select_brush(PEMF_CALLBACK_DATA d, int index); + static void select_font(PEMF_CALLBACK_DATA d, int index); + static void delete_object(PEMF_CALLBACK_DATA d, int index); + static void insert_object(PEMF_CALLBACK_DATA d, int index, int type, PU_ENHMETARECORD pObj); + static int AI_hack(PU_EMRHEADER pEmr); + static uint32_t *unknown_chars(size_t count); + static void common_image_extraction(PEMF_CALLBACK_DATA d, void *pEmr, double dx, double dy, double dw, double dh, + int sx, int sy, int sw, int sh, uint32_t iUsage, uint32_t offBits, + uint32_t cbBits, uint32_t offBmi, uint32_t cbBmi); + static int myEnhMetaFileProc(char *contents, unsigned int length, PEMF_CALLBACK_DATA d); + static void free_emf_strings(EMF_STRINGS name); }; -} } } /* namespace Inkscape, Extension, Implementation */ - +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* EXTENSION_INTERNAL_EMF_H */ diff --git a/src/extension/internal/emf-print.cpp b/src/extension/internal/emf-print.cpp index 06af4aec50975540f77c0c2808b54c32cfab9266..8e1f6f3716526279db98ed88993496abf71968cc 100644 --- a/src/extension/internal/emf-print.cpp +++ b/src/extension/internal/emf-print.cpp @@ -25,44 +25,37 @@ #include "emf-print.h" -#include -#include -#include <3rdparty/libuemf/symbol_convert.h> -#include <2geom/sbasis-to-bezier.h> +#include <2geom/curves.h> #include <2geom/path.h> #include <2geom/pathvector.h> #include <2geom/rect.h> -#include <2geom/curves.h> +#include <2geom/sbasis-to-bezier.h> #include <2geom/svg-path-parser.h> // to get from SVG text to Geom::Path +#include <3rdparty/libuemf/symbol_convert.h> +#include +#include -#include "inkscape-version.h" - -#include "document.h" -#include "path-prefix.h" -#include "style.h" -#include "style-enums.h" // Fill rules - -#include "display/cairo-utils.h" // for Inkscape::Pixbuf::PF_CAIRO +#include "display/cairo-utils.h" // for Inkscape::Pixbuf::PF_CAIRO #include "display/curve.h" - -#include "extension/system.h" +#include "document.h" #include "extension/print.h" - -#include "helper/geom.h" +#include "extension/system.h" #include "helper/geom-curves.h" - -#include "object/sp-pattern.h" -#include "object/sp-image.h" +#include "helper/geom.h" +#include "inkscape-version.h" +#include "object/sp-clippath.h" #include "object/sp-gradient.h" -#include "object/sp-radial-gradient.h" -#include "object/sp-linear-gradient.h" +#include "object/sp-image.h" #include "object/sp-item.h" +#include "object/sp-linear-gradient.h" +#include "object/sp-pattern.h" +#include "object/sp-radial-gradient.h" #include "object/sp-root.h" #include "object/sp-shape.h" -#include "object/sp-clippath.h" - +#include "path-prefix.h" #include "path/path-boolop.h" - +#include "style-enums.h" // Fill rules +#include "style.h" #include "util/units.h" namespace Inkscape { @@ -72,38 +65,38 @@ namespace Internal { #define PXPERMETER 2835 /* globals */ -static double PX2WORLD; -static bool FixPPTCharPos, FixPPTDashLine, FixPPTGrad2Polys, FixPPTLinGrad, FixPPTPatternAsHatch, FixImageRot; -static EMFTRACK *et = nullptr; -static EMFHANDLES *eht = nullptr; +static double PX2WORLD; +static bool FixPPTCharPos, FixPPTDashLine, FixPPTGrad2Polys, FixPPTLinGrad, FixPPTPatternAsHatch, FixImageRot; +static EMFTRACK *et = nullptr; +static EMFHANDLES *eht = nullptr; void PrintEmf::smuggle_adxkyrtl_out(const char *string, uint32_t **adx, double *ky, int *rtl, int *ndx, float scale) { - float fdx; - int i; - uint32_t *ladx; + float fdx; + int i; + uint32_t *ladx; const char *cptr = &string[strlen(string) + 1]; // this works because of the first fake terminator *adx = nullptr; - *ky = 0.0; // set a default value + *ky = 0.0; // set a default value sscanf(cptr, "%7d", ndx); if (!*ndx) { - return; // this could happen with an empty string + return; // this could happen with an empty string } cptr += 7; - ladx = (uint32_t *) malloc(*ndx * sizeof(uint32_t)); + ladx = (uint32_t *)malloc(*ndx * sizeof(uint32_t)); if (!ladx) { g_message("Out of memory"); } *adx = ladx; for (i = 0; i < *ndx; i++, cptr += 7, ladx++) { sscanf(cptr, "%7f", &fdx); - *ladx = (uint32_t) round(fdx * scale); + *ladx = (uint32_t)round(fdx * scale); } cptr++; // skip 2nd fake terminator sscanf(cptr, "%7f", &fdx); *ky = fdx; - cptr += 7; // advance over ky and its space + cptr += 7; // advance over ky and its space sscanf(cptr, "%07d", rtl); } @@ -112,37 +105,34 @@ PrintEmf::PrintEmf() // all of the class variables are initialized elsewhere, many in PrintEmf::Begin, } - unsigned int PrintEmf::setup(Inkscape::Extension::Print * /*mod*/) { return TRUE; } - unsigned int PrintEmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) { - U_SIZEL szlDev, szlMm; - U_RECTL rclBounds, rclFrame; - char *rec; - gchar const *utf8_fn = mod->get_param_string("destination"); + U_SIZEL szlDev, szlMm; + U_RECTL rclBounds, rclFrame; + char *rec; + gchar const *utf8_fn = mod->get_param_string("destination"); // Typically PX2WORLD is 1200/90, using inkscape's default dpi - PX2WORLD = 1200.0 / Inkscape::Util::Quantity::convert(1.0, "in", "px"); - FixPPTCharPos = mod->get_param_bool("FixPPTCharPos"); - FixPPTDashLine = mod->get_param_bool("FixPPTDashLine"); - FixPPTGrad2Polys = mod->get_param_bool("FixPPTGrad2Polys"); - FixPPTLinGrad = mod->get_param_bool("FixPPTLinGrad"); + PX2WORLD = 1200.0 / Inkscape::Util::Quantity::convert(1.0, "in", "px"); + FixPPTCharPos = mod->get_param_bool("FixPPTCharPos"); + FixPPTDashLine = mod->get_param_bool("FixPPTDashLine"); + FixPPTGrad2Polys = mod->get_param_bool("FixPPTGrad2Polys"); + FixPPTLinGrad = mod->get_param_bool("FixPPTLinGrad"); FixPPTPatternAsHatch = mod->get_param_bool("FixPPTPatternAsHatch"); - FixImageRot = mod->get_param_bool("FixImageRot"); - - (void) emf_start(utf8_fn, 1000000, 250000, &et); // Initialize the et structure - (void) htable_create(128, 128, &eht); // Initialize the eht structure + FixImageRot = mod->get_param_bool("FixImageRot"); - char *ansi_uri = (char *) utf8_fn; + (void)emf_start(utf8_fn, 1000000, 250000, &et); // Initialize the et structure + (void)htable_create(128, 128, &eht); // Initialize the eht structure + char *ansi_uri = (char *)utf8_fn; // width and height in px - _width = doc->getWidth().value("px"); + _width = doc->getWidth().value("px"); _height = doc->getHeight().value("px"); _doc_unit_scale = doc->getDocumentScale()[Geom::X]; @@ -155,14 +145,14 @@ unsigned int PrintEmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) if (nv) { const char *p1 = nv->attribute("pagecolor"); char *p2; - uint32_t lc = strtoul(&p1[1], &p2, 16); // it looks like "#ABC123" + uint32_t lc = strtoul(&p1[1], &p2, 16); // it looks like "#ABC123" if (*p2) { lc = 0; } gv.bgc = _gethexcolor(lc); - gv.rgb[0] = (float) U_RGBAGetR(gv.bgc) / 255.0; - gv.rgb[1] = (float) U_RGBAGetG(gv.bgc) / 255.0; - gv.rgb[2] = (float) U_RGBAGetB(gv.bgc) / 255.0; + gv.rgb[0] = (float)U_RGBAGetR(gv.bgc) / 255.0; + gv.rgb[1] = (float)U_RGBAGetG(gv.bgc) / 255.0; + gv.rgb[2] = (float)U_RGBAGetB(gv.bgc) / 255.0; } bool pageBoundingBox; @@ -185,12 +175,13 @@ unsigned int PrintEmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) float dwInchesY = d.height(); // dwInchesX x dwInchesY in micrometer units, 1200 dpi/25.4 -> dpmm - (void) drawing_size((int) ceil(dwInchesX * 25.4), (int) ceil(dwInchesY * 25.4),1200.0/25.4, &rclBounds, &rclFrame); + (void)drawing_size((int)ceil(dwInchesX * 25.4), (int)ceil(dwInchesY * 25.4), 1200.0 / 25.4, &rclBounds, &rclFrame); - // set up the reference device as 100 X A4 horizontal, (1200 dpi/25.4 -> dpmm). Extra digits maintain dpi better in EMF + // set up the reference device as 100 X A4 horizontal, (1200 dpi/25.4 -> dpmm). Extra digits maintain dpi better in + // EMF int MMX = 216; int MMY = 279; - (void) device_size(MMX, MMY, 1200.0 / 25.4, &szlDev, &szlMm); + (void)device_size(MMX, MMY, 1200.0 / 25.4, &szlDev, &szlMm); int PixelsX = szlDev.cx; int PixelsY = szlDev.cy; @@ -207,24 +198,22 @@ unsigned int PrintEmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) } snprintf(buff, sizeof(buff) - 1, "Inkscape %s \1%s\1", Inkscape::version_string, p); uint16_t *Description = U_Utf8ToUtf16le(buff, 0, nullptr); - int cbDesc = 2 + wchar16len(Description); // also count the final terminator - (void) U_Utf16leEdit(Description, '\1', '\0'); // swap the temporary \1 characters for nulls + int cbDesc = 2 + wchar16len(Description); // also count the final terminator + (void)U_Utf16leEdit(Description, '\1', '\0'); // swap the temporary \1 characters for nulls // construct the EMRHEADER record and append it to the EMF in memory - rec = U_EMRHEADER_set(rclBounds, rclFrame, nullptr, cbDesc, Description, szlDev, szlMm, 0); + rec = U_EMRHEADER_set(rclBounds, rclFrame, nullptr, cbDesc, Description, szlDev, szlMm, 0); free(Description); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::begin at EMRHEADER"); } - // Simplest mapping mode, supply all coordinates in pixels rec = U_EMRSETMAPMODE_set(U_MM_TEXT); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::begin at EMRSETMAPMODE"); } - // In earlier versions this was used to scale from inkscape's dpi of 90 to // the files 1200 dpi, taking into account PX2WORLD which was 20. Now PX2WORLD // is set so that this matrix is unitary. The usual value of PX2WORLD is 1200/90, @@ -235,15 +224,14 @@ unsigned int PrintEmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) worldTransform.eM12 = 0.0; worldTransform.eM21 = 0.0; worldTransform.eM22 = 1.0; - worldTransform.eDx = 0; - worldTransform.eDy = 0; + worldTransform.eDx = 0; + worldTransform.eDy = 0; rec = U_EMRMODIFYWORLDTRANSFORM_set(worldTransform, U_MWT_LEFTMULTIPLY); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::begin at EMRMODIFYWORLDTRANSFORM"); } - if (true) { snprintf(buff, sizeof(buff) - 1, "Screen=%dx%dpx, %dx%dmm", PixelsX, PixelsY, MMX, MMY); rec = textcomment_set(buff); @@ -251,7 +239,9 @@ unsigned int PrintEmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) g_error("Fatal programming error in PrintEmf::begin at textcomment_set 1"); } - snprintf(buff, sizeof(buff) - 1, "Drawing=%.1fx%.1fpx, %.1fx%.1fmm", _width, _height, Inkscape::Util::Quantity::convert(dwInchesX, "in", "mm"), Inkscape::Util::Quantity::convert(dwInchesY, "in", "mm")); + snprintf(buff, sizeof(buff) - 1, "Drawing=%.1fx%.1fpx, %.1fx%.1fmm", _width, _height, + Inkscape::Util::Quantity::convert(dwInchesX, "in", "mm"), + Inkscape::Util::Quantity::convert(dwInchesY, "in", "mm")); rec = textcomment_set(buff); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::begin at textcomment_set 1"); @@ -297,33 +287,28 @@ unsigned int PrintEmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) return 0; } - unsigned int PrintEmf::finish(Inkscape::Extension::Print * /*mod*/) { - do_clip_if_present(nullptr); // Terminate any open clip. + do_clip_if_present(nullptr); // Terminate any open clip. char *rec; if (!et) { return 0; } - // earlier versions had flush of fill here, but it never executed and was removed rec = U_EMREOF_set(0, nullptr, et); // generate the EOF record if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::finish"); } - (void) emf_finish(et, eht); // Finalize and write out the EMF - emf_free(&et); // clean up - htable_free(&eht); // clean up + (void)emf_finish(et, eht); // Finalize and write out the EMF + emf_free(&et); // clean up + htable_free(&eht); // clean up return 0; } - -unsigned int PrintEmf::comment( - Inkscape::Extension::Print * /*module*/, - const char * /*comment*/) +unsigned int PrintEmf::comment(Inkscape::Extension::Print * /*module*/, const char * /*comment*/) { if (!et) { return 0; @@ -334,33 +319,32 @@ unsigned int PrintEmf::comment( return 0; } - // fcolor is defined when gradients are being expanded, it is the color of one stripe or ring. int PrintEmf::create_brush(SPStyle const *style, PU_COLORREF fcolor) { - float rgb[3]; - char *rec; - U_LOGBRUSH lb; - uint32_t brush, fmode; - MFDrawMode fill_mode; + float rgb[3]; + char *rec; + U_LOGBRUSH lb; + uint32_t brush, fmode; + MFDrawMode fill_mode; Inkscape::Pixbuf *pixbuf; - uint32_t brushStyle; - int hatchType; - U_COLORREF hatchColor; - U_COLORREF bkColor; - uint32_t width = 0; // quiets a harmless compiler warning, initialization not otherwise required. - uint32_t height = 0; + uint32_t brushStyle; + int hatchType; + U_COLORREF hatchColor; + U_COLORREF bkColor; + uint32_t width = 0; // quiets a harmless compiler warning, initialization not otherwise required. + uint32_t height = 0; if (!et) { return 0; } // set a default fill in case we can't figure out a better way to do it - fmode = U_ALTERNATE; - fill_mode = DRAW_PAINT; + fmode = U_ALTERNATE; + fill_mode = DRAW_PAINT; brushStyle = U_BS_SOLID; - hatchType = U_HS_SOLIDCLR; - bkColor = U_RGB(0, 0, 0); + hatchType = U_HS_SOLIDCLR; + bkColor = U_RGB(0, 0, 0); if (fcolor) { hatchColor = *fcolor; } else { @@ -380,13 +364,14 @@ int PrintEmf::create_brush(SPStyle const *style, PU_COLORREF fcolor) style->fill.value.color.get_rgb_floatv(rgb); hatchColor = U_RGB(255 * rgb[0], 255 * rgb[1], 255 * rgb[2]); - fmode = style->fill_rule.computed == 0 ? U_WINDING : (style->fill_rule.computed == 2 ? U_ALTERNATE : U_ALTERNATE); + fmode = style->fill_rule.computed == 0 ? U_WINDING + : (style->fill_rule.computed == 2 ? U_ALTERNATE : U_ALTERNATE); } else if (SP_IS_PATTERN(SP_STYLE_FILL_SERVER(style))) { // must be paint-server SPPaintServer *paintserver = style->fill.value.href->getObject(); SPPattern *pat = SP_PATTERN(paintserver); - double dwidth = pat->width(); + double dwidth = pat->width(); double dheight = pat->height(); - width = dwidth; + width = dwidth; height = dheight; brush_classify(pat, 0, &pixbuf, &hatchType, &hatchColor, &bkColor); if (pixbuf) { @@ -394,20 +379,21 @@ int PrintEmf::create_brush(SPStyle const *style, PU_COLORREF fcolor) } else { // pattern fill_mode = DRAW_PATTERN; if (hatchType == -1) { // Not a standard hatch, so force it to something - hatchType = U_HS_CROSS; + hatchType = U_HS_CROSS; hatchColor = U_RGB(0xFF, 0xC3, 0xC3); } } if (FixPPTPatternAsHatch) { if (hatchType == -1) { // image or unclassified - fill_mode = DRAW_PATTERN; - hatchType = U_HS_DIAGCROSS; + fill_mode = DRAW_PATTERN; + hatchType = U_HS_DIAGCROSS; hatchColor = U_RGB(0xFF, 0xC3, 0xC3); } } brushStyle = U_BS_HATCHED; } else if (SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style))) { // must be a gradient - // currently we do not do anything with gradients, the code below just sets the color to the average of the stops + // currently we do not do anything with gradients, the code below just sets the color to the average of the + // stops SPPaintServer *paintserver = style->fill.value.href->getObject(); SPLinearGradient *lg = nullptr; SPRadialGradient *rg = nullptr; @@ -442,55 +428,58 @@ int PrintEmf::create_brush(SPStyle const *style, PU_COLORREF fcolor) // default fill } - lb = logbrush_set(brushStyle, hatchColor, hatchType); + lb = logbrush_set(brushStyle, hatchColor, hatchType); switch (fill_mode) { - case DRAW_LINEAR_GRADIENT: // fill with average color unless gradients are converted to slices - case DRAW_RADIAL_GRADIENT: // ditto - case DRAW_PAINT: - case DRAW_PATTERN: - // SVG text has no background attribute, so OPAQUE mode ALWAYS cancels after the next draw, otherwise it would mess up future text output. - if (usebk) { - rec = U_EMRSETBKCOLOR_set(bkColor); + case DRAW_LINEAR_GRADIENT: // fill with average color unless gradients are converted to slices + case DRAW_RADIAL_GRADIENT: // ditto + case DRAW_PAINT: + case DRAW_PATTERN: + // SVG text has no background attribute, so OPAQUE mode ALWAYS cancels after the next draw, otherwise it + // would mess up future text output. + if (usebk) { + rec = U_EMRSETBKCOLOR_set(bkColor); + if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { + g_error("Fatal programming error in PrintEmf::create_brush at U_EMRSETBKCOLOR_set"); + } + rec = U_EMRSETBKMODE_set(U_OPAQUE); + if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { + g_error("Fatal programming error in PrintEmf::create_brush at U_EMRSETBKMODE_set"); + } + } + rec = createbrushindirect_set(&brush, eht, lb); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { - g_error("Fatal programming error in PrintEmf::create_brush at U_EMRSETBKCOLOR_set"); + g_error("Fatal programming error in PrintEmf::create_brush at createbrushindirect_set"); + } + break; + case DRAW_IMAGE: + char *px; + char *rgba_px; + uint32_t cbPx; + uint32_t colortype; + PU_RGBQUAD ct; + int numCt; + U_BITMAPINFOHEADER Bmih; + PU_BITMAPINFO Bmi; + rgba_px = (char *)pixbuf->pixels(); // Do NOT free this!!! + colortype = U_BCBM_COLOR32; + (void)RGBA_to_DIB(&px, &cbPx, &ct, &numCt, rgba_px, width, height, width * 4, colortype, 0, 1); + // pixbuf can be either PF_CAIRO or PF_GDK, and these have R and B bytes swapped + if (pixbuf->pixelFormat() == Inkscape::Pixbuf::PF_CAIRO) { + swapRBinRGBA(px, width * height); } - rec = U_EMRSETBKMODE_set(U_OPAQUE); + Bmih = bitmapinfoheader_set(width, height, 1, colortype, U_BI_RGB, 0, PXPERMETER, PXPERMETER, numCt, 0); + Bmi = bitmapinfo_set(Bmih, ct); + rec = createdibpatternbrushpt_set(&brush, eht, U_DIB_RGB_COLORS, Bmi, cbPx, px); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { - g_error("Fatal programming error in PrintEmf::create_brush at U_EMRSETBKMODE_set"); + g_error("Fatal programming error in PrintEmf::create_brush at createdibpatternbrushpt_set"); } - } - rec = createbrushindirect_set(&brush, eht, lb); - if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { - g_error("Fatal programming error in PrintEmf::create_brush at createbrushindirect_set"); - } - break; - case DRAW_IMAGE: - char *px; - char *rgba_px; - uint32_t cbPx; - uint32_t colortype; - PU_RGBQUAD ct; - int numCt; - U_BITMAPINFOHEADER Bmih; - PU_BITMAPINFO Bmi; - rgba_px = (char *) pixbuf->pixels(); // Do NOT free this!!! - colortype = U_BCBM_COLOR32; - (void) RGBA_to_DIB(&px, &cbPx, &ct, &numCt, rgba_px, width, height, width * 4, colortype, 0, 1); - // pixbuf can be either PF_CAIRO or PF_GDK, and these have R and B bytes swapped - if (pixbuf->pixelFormat() == Inkscape::Pixbuf::PF_CAIRO) { swapRBinRGBA(px, width * height); } - Bmih = bitmapinfoheader_set(width, height, 1, colortype, U_BI_RGB, 0, PXPERMETER, PXPERMETER, numCt, 0); - Bmi = bitmapinfo_set(Bmih, ct); - rec = createdibpatternbrushpt_set(&brush, eht, U_DIB_RGB_COLORS, Bmi, cbPx, px); - if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { - g_error("Fatal programming error in PrintEmf::create_brush at createdibpatternbrushpt_set"); - } - free(px); - free(Bmi); // ct will be NULL because of colortype - break; + free(px); + free(Bmi); // ct will be NULL because of colortype + break; } - hbrush = brush; // need this later for destroy_brush + hbrush = brush; // need this later for destroy_brush rec = selectobject_set(brush, eht); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::create_brush at selectobject_set"); @@ -507,13 +496,13 @@ int PrintEmf::create_brush(SPStyle const *style, PU_COLORREF fcolor) return 0; } - void PrintEmf::destroy_brush() { char *rec; // before an object may be safely deleted it must no longer be selected // select in a stock object to deselect this one, the stock object should - // never be used because we always select in a new one before drawing anythingrestore previous brush, necessary??? Would using a default stock object not work? + // never be used because we always select in a new one before drawing anythingrestore previous brush, necessary??? + // Would using a default stock object not work? rec = selectobject_set(U_NULL_BRUSH, eht); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::destroy_brush at selectobject_set"); @@ -527,31 +516,30 @@ void PrintEmf::destroy_brush() } } - int PrintEmf::create_pen(SPStyle const *style, const Geom::Affine &transform) { - U_EXTLOGPEN *elp; - U_NUM_STYLEENTRY n_dash = 0; - U_STYLEENTRY *dash = nullptr; - char *rec = nullptr; - int linestyle = U_PS_SOLID; - int linecap = 0; - int linejoin = 0; - uint32_t pen; - uint32_t brushStyle; - Inkscape::Pixbuf *pixbuf; - int hatchType; - U_COLORREF hatchColor; - U_COLORREF bkColor; - uint32_t width, height; - char *px = nullptr; - char *rgba_px; - uint32_t cbPx = 0; - uint32_t colortype; - PU_RGBQUAD ct = nullptr; - int numCt = 0; - U_BITMAPINFOHEADER Bmih; - PU_BITMAPINFO Bmi = nullptr; + U_EXTLOGPEN *elp; + U_NUM_STYLEENTRY n_dash = 0; + U_STYLEENTRY *dash = nullptr; + char *rec = nullptr; + int linestyle = U_PS_SOLID; + int linecap = 0; + int linejoin = 0; + uint32_t pen; + uint32_t brushStyle; + Inkscape::Pixbuf *pixbuf; + int hatchType; + U_COLORREF hatchColor; + U_COLORREF bkColor; + uint32_t width, height; + char *px = nullptr; + char *rgba_px; + uint32_t cbPx = 0; + uint32_t colortype; + PU_RGBQUAD ct = nullptr; + int numCt = 0; + U_BITMAPINFOHEADER Bmih; + PU_BITMAPINFO Bmi = nullptr; if (!et) { return 0; @@ -560,8 +548,8 @@ int PrintEmf::create_pen(SPStyle const *style, const Geom::Affine &transform) // set a default stroke in case we can't figure out a better way to do it brushStyle = U_BS_SOLID; hatchColor = U_RGB(0, 0, 0); - hatchType = U_HS_HORIZONTAL; - bkColor = U_RGB(0, 0, 0); + hatchType = U_HS_HORIZONTAL; + bkColor = U_RGB(0, 0, 0); if (style) { float rgb[3]; @@ -569,23 +557,26 @@ int PrintEmf::create_pen(SPStyle const *style, const Geom::Affine &transform) if (SP_IS_PATTERN(SP_STYLE_STROKE_SERVER(style))) { // must be paint-server SPPaintServer *paintserver = style->stroke.value.href->getObject(); SPPattern *pat = SP_PATTERN(paintserver); - double dwidth = pat->width(); + double dwidth = pat->width(); double dheight = pat->height(); - width = dwidth; + width = dwidth; height = dheight; brush_classify(pat, 0, &pixbuf, &hatchType, &hatchColor, &bkColor); if (pixbuf) { - brushStyle = U_BS_DIBPATTERN; - rgba_px = (char *) pixbuf->pixels(); // Do NOT free this!!! + brushStyle = U_BS_DIBPATTERN; + rgba_px = (char *)pixbuf->pixels(); // Do NOT free this!!! colortype = U_BCBM_COLOR32; - (void) RGBA_to_DIB(&px, &cbPx, &ct, &numCt, rgba_px, width, height, width * 4, colortype, 0, 1); + (void)RGBA_to_DIB(&px, &cbPx, &ct, &numCt, rgba_px, width, height, width * 4, colortype, 0, 1); // pixbuf can be either PF_CAIRO or PF_GDK, and these have R and B bytes swapped - if (pixbuf->pixelFormat() == Inkscape::Pixbuf::PF_CAIRO) { swapRBinRGBA(px, width * height); } + if (pixbuf->pixelFormat() == Inkscape::Pixbuf::PF_CAIRO) { + swapRBinRGBA(px, width * height); + } Bmih = bitmapinfoheader_set(width, height, 1, colortype, U_BI_RGB, 0, PXPERMETER, PXPERMETER, numCt, 0); Bmi = bitmapinfo_set(Bmih, ct); } else { // pattern - brushStyle = U_BS_HATCHED; - if (usebk) { // OPAQUE mode ALWAYS cancels after the next draw, otherwise it would mess up future text output. + brushStyle = U_BS_HATCHED; + if (usebk) { // OPAQUE mode ALWAYS cancels after the next draw, otherwise it would mess up future text + // output. rec = U_EMRSETBKCOLOR_set(bkColor); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::create_pen at U_EMRSETBKCOLOR_set"); @@ -596,15 +587,15 @@ int PrintEmf::create_pen(SPStyle const *style, const Geom::Affine &transform) } } if (hatchType == -1) { // Not a standard hatch, so force it to something - hatchType = U_HS_CROSS; + hatchType = U_HS_CROSS; hatchColor = U_RGB(0xFF, 0xC3, 0xC3); } } if (FixPPTPatternAsHatch) { if (hatchType == -1) { // image or unclassified - brushStyle = U_BS_HATCHED; - hatchType = U_HS_DIAGCROSS; - hatchColor = U_RGB(0xFF, 0xC3, 0xC3); + brushStyle = U_BS_HATCHED; + hatchType = U_HS_DIAGCROSS; + hatchColor = U_RGB(0xFF, 0xC3, 0xC3); } } } else if (SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style))) { // must be a gradient @@ -636,7 +627,7 @@ int PrintEmf::create_pen(SPStyle const *style, const Geom::Affine &transform) yhandle_point += c; xhandle_point += c; if (rg->gradientTransform_set) { - c = c * rg->gradientTransform; + c = c * rg->gradientTransform; yhandle_point = yhandle_point * rg->gradientTransform; xhandle_point = xhandle_point * rg->gradientTransform; } @@ -648,13 +639,11 @@ int PrintEmf::create_pen(SPStyle const *style, const Geom::Affine &transform) style->stroke.value.color.get_rgb_floatv(rgb); brushStyle = U_BS_SOLID; hatchColor = U_RGB(255 * rgb[0], 255 * rgb[1], 255 * rgb[2]); - hatchType = U_HS_SOLIDCLR; + hatchType = U_HS_SOLIDCLR; } else { // default fill } - - using Geom::X; using Geom::Y; @@ -667,9 +656,9 @@ int PrintEmf::create_pen(SPStyle const *style, const Geom::Affine &transform) double scale = sqrt((p[X] * p[X]) + (p[Y] * p[Y])) / sqrt(2); if (!style->stroke_width.computed) { - return 0; //if width is 0 do not (reset) the pen, it should already be NULL_PEN + return 0; // if width is 0 do not (reset) the pen, it should already be NULL_PEN } - uint32_t linewidth = MAX(1, (uint32_t) round(scale * style->stroke_width.computed * PX2WORLD)); + uint32_t linewidth = MAX(1, (uint32_t)round(scale * style->stroke_width.computed * PX2WORLD)); if (style->stroke_linecap.computed == 0) { linecap = U_PS_ENDCAP_FLAT; @@ -688,9 +677,10 @@ int PrintEmf::create_pen(SPStyle const *style, const Geom::Affine &transform) } if (!style->stroke_dasharray.values.empty()) { - if (FixPPTDashLine) { // will break up line into many smaller lines. Override gradient if that was set, cannot do both. + if (FixPPTDashLine) { // will break up line into many smaller lines. Override gradient if that was set, + // cannot do both. brushStyle = U_BS_SOLID; - hatchType = U_HS_HORIZONTAL; + hatchType = U_HS_HORIZONTAL; } else { unsigned i = 0; while ((linestyle != U_PS_USERSTYLE) && (i < style->stroke_dasharray.values.size())) { @@ -710,28 +700,15 @@ int PrintEmf::create_pen(SPStyle const *style, const Geom::Affine &transform) } } - elp = extlogpen_set( - U_PS_GEOMETRIC | linestyle | linecap | linejoin, - linewidth, - brushStyle, - hatchColor, - hatchType, - n_dash, - dash); + elp = extlogpen_set(U_PS_GEOMETRIC | linestyle | linecap | linejoin, linewidth, brushStyle, hatchColor, + hatchType, n_dash, dash); } else { // if (!style) linejoin = 0; - elp = extlogpen_set( - linestyle, - 1, - U_BS_SOLID, - U_RGB(0, 0, 0), - U_HS_HORIZONTAL, - 0, - nullptr); + elp = extlogpen_set(linestyle, 1, U_BS_SOLID, U_RGB(0, 0, 0), U_HS_HORIZONTAL, 0, nullptr); } - rec = extcreatepen_set(&pen, eht, Bmi, cbPx, px, elp); + rec = extcreatepen_set(&pen, eht, Bmi, cbPx, px, elp); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::create_pen at extcreatepen_set"); } @@ -740,23 +717,23 @@ int PrintEmf::create_pen(SPStyle const *style, const Geom::Affine &transform) free(Bmi); } if (px) { - free(px); // ct will always be NULL + free(px); // ct will always be NULL } rec = selectobject_set(pen, eht); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::create_pen at selectobject_set"); } - hpen = pen; // need this later for destroy_pen + hpen = pen; // need this later for destroy_pen if (linejoin == U_PS_JOIN_MITER) { - float miterlimit = style->stroke_miterlimit.value; // This is a ratio. + float miterlimit = style->stroke_miterlimit.value; // This is a ratio. if (miterlimit < 1) { miterlimit = 1; } - rec = U_EMRSETMITERLIMIT_set((uint32_t) miterlimit); + rec = U_EMRSETMITERLIMIT_set((uint32_t)miterlimit); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::create_pen at U_EMRSETMITERLIMIT_set"); } @@ -774,7 +751,8 @@ void PrintEmf::destroy_pen() char *rec = nullptr; // before an object may be safely deleted it must no longer be selected // select in a stock object to deselect this one, the stock object should - // never be used because we always select in a new one before drawing anythingrestore previous brush, necessary??? Would using a default stock object not work? + // never be used because we always select in a new one before drawing anythingrestore previous brush, necessary??? + // Would using a default stock object not work? rec = selectobject_set(U_NULL_PEN, eht); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::destroy_pen at selectobject_set"); @@ -790,61 +768,63 @@ void PrintEmf::destroy_pen() /* Return a Path consisting of just the corner points of the single path in a PathVector. If the PathVector has more than one path, or that one path is open, or any of its segments are curved, then the -returned PathVector is an empty path. If the input path is already just straight lines and vertices the output will be the -same as the sole path in the input. */ +returned PathVector is an empty path. If the input path is already just straight lines and vertices the output will be +the same as the sole path in the input. */ Geom::Path PrintEmf::pathv_to_simple_polygon(Geom::PathVector const &pathv, int *vertices) { Geom::Point P1_trail; Geom::Point P1; Geom::Point P1_lead; - Geom::Point v1,v2; + Geom::Point v1, v2; Geom::Path output; Geom::Path bad; Geom::PathVector pv = pathv_to_linear_and_cubic_beziers(pathv); - Geom::PathVector::const_iterator pit = pv.begin(); + Geom::PathVector::const_iterator pit = pv.begin(); Geom::PathVector::const_iterator pit2 = pv.begin(); - int first_seg=1; + int first_seg = 1; ++pit2; *vertices = 0; - if(pit->end_closed() != pit->end_default())return(bad); // path must be closed - if(pit2 != pv.end())return(bad); // there may only be one path + if (pit->end_closed() != pit->end_default()) + return (bad); // path must be closed + if (pit2 != pv.end()) + return (bad); // there may only be one path P1_trail = pit->finalPoint(); Geom::Path::const_iterator cit = pit->begin(); P1 = cit->initialPoint(); - for(;cit != pit->end_closed();++cit) { + for (; cit != pit->end_closed(); ++cit) { if (!is_straight_curve(*cit)) { *vertices = 0; - return(bad); + return (bad); } P1_lead = cit->finalPoint(); - if(Geom::are_near(P1_lead, P1, 1e-5))continue; // duplicate points at the same coordinate - v1 = unit_vector(P1 - P1_trail); - v2 = unit_vector(P1_lead - P1 ); - if(Geom::are_near(dot(v1,v2), 1.0, 1e-5)){ // P1 is within a straight line + if (Geom::are_near(P1_lead, P1, 1e-5)) + continue; // duplicate points at the same coordinate + v1 = unit_vector(P1 - P1_trail); + v2 = unit_vector(P1_lead - P1); + if (Geom::are_near(dot(v1, v2), 1.0, 1e-5)) { // P1 is within a straight line P1 = P1_lead; continue; } // P1 is the center point of a turn of some angle - if(!*vertices){ - output.start( P1 ); - output.close( pit->closed() ); - } - if(!Geom::are_near(P1, P1_trail, 1e-5)){ // possible for P1 to start on the end point - Geom::LineSegment ls(P1_trail, P1); - output.append(ls); - if(first_seg){ - *vertices += 2; - first_seg=0; - } - else { - *vertices += 1; - } + if (!*vertices) { + output.start(P1); + output.close(pit->closed()); + } + if (!Geom::are_near(P1, P1_trail, 1e-5)) { // possible for P1 to start on the end point + Geom::LineSegment ls(P1_trail, P1); + output.append(ls); + if (first_seg) { + *vertices += 2; + first_seg = 0; + } else { + *vertices += 1; + } } P1_trail = P1; P1 = P1_lead; } - return(output); + return (output); } /* Returns the simplified PathVector (no matter what). @@ -855,46 +835,50 @@ Geom::Path PrintEmf::pathv_to_rect(Geom::PathVector const &pathv, bool *is_rect, { Geom::Point P1_trail; Geom::Point P1; - Geom::Point v1,v2; + Geom::Point v1, v2; int vertices; Geom::Path pR = pathv_to_simple_polygon(pathv, &vertices); *is_rect = false; - if(vertices==4){ // or else it cannot be a rectangle - int vertex_count=0; + if (vertices == 4) { // or else it cannot be a rectangle + int vertex_count = 0; /* Get the ends of the LAST line segment. Find minimum rotation to align rectangle with X,Y axes. (Very degenerate if it is rotated 45 degrees.) */ - *angle = 10.0; /* must be > than the actual angle in radians. */ - for(Geom::Path::iterator cit = pR.begin();; ++cit){ + *angle = 10.0; /* must be > than the actual angle in radians. */ + for (Geom::Path::iterator cit = pR.begin();; ++cit) { P1_trail = cit->initialPoint(); - P1 = cit->finalPoint(); + P1 = cit->finalPoint(); v1 = unit_vector(P1 - P1_trail); - if(v1[Geom::X] > 0){ // only check the 1 or 2 points on vectors aimed the same direction as unit X - double ang = asin(v1[Geom::Y]); // because component is rotation by ang of {1,0| vector - if(fabs(ang) < fabs(*angle))*angle = -ang; // y increases down, flips sign on angle + if (v1[Geom::X] > 0) { // only check the 1 or 2 points on vectors aimed the same direction as unit X + double ang = asin(v1[Geom::Y]); // because component is rotation by ang of {1,0| vector + if (fabs(ang) < fabs(*angle)) + *angle = -ang; // y increases down, flips sign on angle } - if(cit == pR.end_open())break; + if (cit == pR.end_open()) + break; } /* For increased numerical stability, snap the angle to the nearest 1/100th of a degree. */ - double convert = 36000.0/ (2.0 * M_PI); - *angle = round(*angle * convert)/convert; + double convert = 36000.0 / (2.0 * M_PI); + *angle = round(*angle * convert) / convert; // at this stage v1 holds the last vector in the path, whichever direction it points. - for(Geom::Path::iterator cit = pR.begin(); ;++cit) { + for (Geom::Path::iterator cit = pR.begin();; ++cit) { v2 = v1; P1_trail = cit->initialPoint(); - P1 = cit->finalPoint(); - v1 = unit_vector(P1 - P1_trail); + P1 = cit->finalPoint(); + v1 = unit_vector(P1 - P1_trail); // P1 is center of a turn that is not 90 degrees. Limit comes from cos(89.9) = .001745 - if(!Geom::are_near(dot(v1,v2), 0.0, 2e-3))break; + if (!Geom::are_near(dot(v1, v2), 0.0, 2e-3)) + break; vertex_count++; - if(cit == pR.end_open())break; + if (cit == pR.end_open()) + break; } - if(vertex_count == 4){ - *is_rect=true; + if (vertex_count == 4) { + *is_rect = true; } } - return(pR); + return (pR); } /* Compare a vector with a rectangle's orientation (angle needed to rotate side(s) @@ -905,16 +889,24 @@ Geom::Path PrintEmf::pathv_to_rect(Geom::PathVector const &pathv, bool *is_rect, 3 antiparallel to horizontal 4 antiparallel to vertical */ -int PrintEmf::vector_rect_alignment(double angle, Geom::Point vtest){ +int PrintEmf::vector_rect_alignment(double angle, Geom::Point vtest) +{ int stat = 0; - Geom::Point v1 = Geom::unit_vector(vtest); // unit vector to test alignment - Geom::Point v2 = Geom::Point(1,0) * Geom::Rotate(-angle); // unit horizontal side (sign change because Y increases DOWN) - Geom::Point v3 = Geom::Point(0,1) * Geom::Rotate(-angle); // unit horizontal side (sign change because Y increases DOWN) - if( Geom::are_near(dot(v1,v2), 1.0, 1e-5)){ stat = 1; } - else if(Geom::are_near(dot(v1,v2),-1.0, 1e-5)){ stat = 2; } - else if(Geom::are_near(dot(v1,v3), 1.0, 1e-5)){ stat = 3; } - else if(Geom::are_near(dot(v1,v3),-1.0, 1e-5)){ stat = 4; } - return(stat); + Geom::Point v1 = Geom::unit_vector(vtest); // unit vector to test alignment + Geom::Point v2 = + Geom::Point(1, 0) * Geom::Rotate(-angle); // unit horizontal side (sign change because Y increases DOWN) + Geom::Point v3 = + Geom::Point(0, 1) * Geom::Rotate(-angle); // unit horizontal side (sign change because Y increases DOWN) + if (Geom::are_near(dot(v1, v2), 1.0, 1e-5)) { + stat = 1; + } else if (Geom::are_near(dot(v1, v2), -1.0, 1e-5)) { + stat = 2; + } else if (Geom::are_near(dot(v1, v3), 1.0, 1e-5)) { + stat = 3; + } else if (Geom::are_near(dot(v1, v3), -1.0, 1e-5)) { + stat = 4; + } + return (stat); } /* retrieve the point at the indicated corner: @@ -926,74 +918,81 @@ int PrintEmf::vector_rect_alignment(double angle, Geom::Point vtest){ clockwise or counterclockwise. This should work even if the corners of the rectangle are slightly displaced. */ -Geom::Point PrintEmf::get_pathrect_corner(Geom::Path pathRect, double angle, int corner){ - Geom::Point center(0,0); - for(Geom::Path::iterator cit = pathRect.begin(); ; ++cit) { - center += cit->initialPoint()/4.0; - if(cit == pathRect.end_open())break; +Geom::Point PrintEmf::get_pathrect_corner(Geom::Path pathRect, double angle, int corner) +{ + Geom::Point center(0, 0); + for (Geom::Path::iterator cit = pathRect.begin();; ++cit) { + center += cit->initialPoint() / 4.0; + if (cit == pathRect.end_open()) + break; } int LR; // 1 if Left, 0 if Right int UL; // 1 if Lower, 0 if Upper (as viewed on screen, y coordinates increase downwards) - switch(corner){ - case 1: //UR - LR = 0; - UL = 0; - break; - case 2: //LR - LR = 0; - UL = 1; - break; - case 3: //LL - LR = 1; - UL = 1; - break; - default: //UL - LR = 1; - UL = 0; - break; - } - - Geom::Point v1 = Geom::Point(1,0) * Geom::Rotate(-angle); // unit horizontal side (sign change because Y increases DOWN) - Geom::Point v2 = Geom::Point(0,1) * Geom::Rotate(-angle); // unit vertical side (sign change because Y increases DOWN) + switch (corner) { + case 1: // UR + LR = 0; + UL = 0; + break; + case 2: // LR + LR = 0; + UL = 1; + break; + case 3: // LL + LR = 1; + UL = 1; + break; + default: // UL + LR = 1; + UL = 0; + break; + } + + Geom::Point v1 = + Geom::Point(1, 0) * Geom::Rotate(-angle); // unit horizontal side (sign change because Y increases DOWN) + Geom::Point v2 = + Geom::Point(0, 1) * Geom::Rotate(-angle); // unit vertical side (sign change because Y increases DOWN) Geom::Point P1; - for(Geom::Path::iterator cit = pathRect.begin(); ; ++cit) { + for (Geom::Path::iterator cit = pathRect.begin();; ++cit) { P1 = cit->initialPoint(); - if ( ( LR == (dot(P1 - center,v1) > 0 ? 0 : 1) ) - && ( UL == (dot(P1 - center,v2) > 0 ? 1 : 0) ) ) break; - if(cit == pathRect.end_open())break; + if ((LR == (dot(P1 - center, v1) > 0 ? 0 : 1)) && (UL == (dot(P1 - center, v2) > 0 ? 1 : 0))) + break; + if (cit == pathRect.end_open()) + break; } - return(P1); + return (P1); } -U_TRIVERTEX PrintEmf::make_trivertex(Geom::Point Pt, U_COLORREF uc){ +U_TRIVERTEX PrintEmf::make_trivertex(Geom::Point Pt, U_COLORREF uc) +{ U_TRIVERTEX tv; using Geom::X; using Geom::Y; - tv.x = (int32_t) round(Pt[X]); - tv.y = (int32_t) round(Pt[Y]); - tv.Red = uc.Red << 8; - tv.Green = uc.Green << 8; - tv.Blue = uc.Blue << 8; - tv.Alpha = uc.Reserved << 8; // EMF will ignore this - return(tv); + tv.x = (int32_t)round(Pt[X]); + tv.y = (int32_t)round(Pt[Y]); + tv.Red = uc.Red << 8; + tv.Green = uc.Green << 8; + tv.Blue = uc.Blue << 8; + tv.Alpha = uc.Reserved << 8; // EMF will ignore this + return (tv); } /* Examine clip. If there is a (new) one then apply it. If there is one and it is the same as the preceding one, leave the preceding one active. If style is NULL terminate the current clip, if any, and return. */ -void PrintEmf::do_clip_if_present(SPStyle const *style){ +void PrintEmf::do_clip_if_present(SPStyle const *style) +{ char *rec; static SPClipPath *scpActive = nullptr; - if(!style){ - if(scpActive){ // clear the existing clip + if (!style) { + if (scpActive) { // clear the existing clip rec = U_EMRRESTOREDC_set(-1); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::fill at U_EMRRESTOREDC_set"); } - scpActive=nullptr; + scpActive = nullptr; } } else { /* The current implementation converts only one level of clipping. If there were more @@ -1006,15 +1005,17 @@ void PrintEmf::do_clip_if_present(SPStyle const *style){ /* find the first clip_ref at object or up the stack. There may not be one. */ SPClipPath *scp = nullptr; SPItem *item = SP_ITEM(style->object); - while(true) { + while (true) { scp = item->getClipObject(); - if(scp)break; + if (scp) + break; item = SP_ITEM(item->parent); - if(!item || SP_IS_ROOT(item))break; // this will never be a clipping path + if (!item || SP_IS_ROOT(item)) + break; // this will never be a clipping path } - if(scp != scpActive){ // change or remove the clipping - if(scpActive){ // clear the existing clip + if (scp != scpActive) { // change or remove the clipping + if (scpActive) { // clear the existing clip rec = U_EMRRESTOREDC_set(-1); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::fill at U_EMRRESTOREDC_set"); @@ -1022,81 +1023,87 @@ void PrintEmf::do_clip_if_present(SPStyle const *style){ scpActive = nullptr; } - if (scp) { // set the new clip + if (scp) { // set the new clip /* because of units and who knows what other transforms that might be applied above we need the full transform all the way to the root. */ Geom::Affine tf = item->transform; SPItem *scan_item = item; - while(true) { - scan_item = SP_ITEM(scan_item->parent); - if(!scan_item)break; - tf *= scan_item->transform; + while (true) { + scan_item = SP_ITEM(scan_item->parent); + if (!scan_item) + break; + tf *= scan_item->transform; } - tf *= Geom::Scale(_doc_unit_scale);; // Transform must be in PIXELS, no matter what the document unit is. + tf *= Geom::Scale(_doc_unit_scale); + ; // Transform must be in PIXELS, no matter what the document unit is. /* find the clipping path */ Geom::PathVector combined_pathvector; - Geom::Affine tfc; // clipping transform, generally not the same as item transform - for (auto& child: scp->children) { + Geom::Affine tfc; // clipping transform, generally not the same as item transform + for (auto &child : scp->children) { item = SP_ITEM(&child); if (!item) { break; } - if (SP_IS_GROUP(item)) { // not implemented + if (SP_IS_GROUP(item)) { // not implemented // return sp_group_render(item); combined_pathvector = merge_PathVector_with_group(combined_pathvector, item, tfc); } else if (SP_IS_SHAPE(item)) { combined_pathvector = merge_PathVector_with_shape(combined_pathvector, item, tfc); - } else { // not implemented + } else { // not implemented } } if (!combined_pathvector.empty()) { // if clipping path isn't empty, define EMF clipping record - scpActive = scp; // remember for next time + scpActive = scp; // remember for next time // the sole purpose of this SAVEDC is to let us clear the clipping region later. rec = U_EMRSAVEDC_set(); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::image at U_EMRSAVEDC_set"); } - (void) draw_pathv_to_EMF(combined_pathvector, tf); + (void)draw_pathv_to_EMF(combined_pathvector, tf); rec = U_EMRSELECTCLIPPATH_set(U_RGN_COPY); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::do_clip_if_present at U_EMRSELECTCLIPPATH_set"); } - } - else { + } else { scpActive = nullptr; // no valid path available to draw, so no DC was saved, so no signal to restore } } // change or remove clipping - } // scp exists - } // style exists + } // scp exists + } // style exists } -Geom::PathVector PrintEmf::merge_PathVector_with_group(Geom::PathVector const &combined_pathvector, SPItem const *item, const Geom::Affine &transform) +Geom::PathVector PrintEmf::merge_PathVector_with_group(Geom::PathVector const &combined_pathvector, SPItem const *item, + const Geom::Affine &transform) { Geom::PathVector new_combined_pathvector; - if(!SP_IS_GROUP(item))return(new_combined_pathvector); // sanity test, only a group should be passed in, return empty if something else happens + if (!SP_IS_GROUP(item)) + return (new_combined_pathvector); // sanity test, only a group should be passed in, return empty if something + // else happens new_combined_pathvector = combined_pathvector; SPGroup *group = SP_GROUP(item); Geom::Affine tfc = item->transform * transform; - for (auto& child: group->children) { + for (auto &child : group->children) { item = SP_ITEM(&child); if (!item) { break; } if (SP_IS_GROUP(item)) { - new_combined_pathvector = merge_PathVector_with_group(new_combined_pathvector, item, tfc); // could be endlessly recursive on a badly formed SVG + new_combined_pathvector = merge_PathVector_with_group( + new_combined_pathvector, item, tfc); // could be endlessly recursive on a badly formed SVG } else if (SP_IS_SHAPE(item)) { new_combined_pathvector = merge_PathVector_with_shape(new_combined_pathvector, item, tfc); - } else { // not implemented + } else { // not implemented } } return new_combined_pathvector; } -Geom::PathVector PrintEmf::merge_PathVector_with_shape(Geom::PathVector const &combined_pathvector, SPItem const *item, const Geom::Affine &transform) +Geom::PathVector PrintEmf::merge_PathVector_with_shape(Geom::PathVector const &combined_pathvector, SPItem const *item, + const Geom::Affine &transform) { Geom::PathVector new_combined_pathvector; auto shape = dynamic_cast(item); @@ -1108,51 +1115,53 @@ Geom::PathVector PrintEmf::merge_PathVector_with_shape(Geom::PathVector const &c Geom::Affine tfc = item->transform * transform; if (shape->curve()) { Geom::PathVector const &new_vect = shape->curve()->get_pathvector(); - if(combined_pathvector.empty()){ + if (combined_pathvector.empty()) { new_combined_pathvector = new_vect * tfc; - } - else { - new_combined_pathvector = sp_pathvector_boolop(new_vect * tfc, combined_pathvector, bool_op_union , (FillRule) fill_oddEven, (FillRule) fill_oddEven); + } else { + new_combined_pathvector = sp_pathvector_boolop(new_vect * tfc, combined_pathvector, bool_op_union, + (FillRule)fill_oddEven, (FillRule)fill_oddEven); } } return new_combined_pathvector; } -unsigned int PrintEmf::fill( - Inkscape::Extension::Print * /*mod*/, - Geom::PathVector const &pathv, Geom::Affine const & /*transform*/, SPStyle const *style, - Geom::OptRect const &/*pbox*/, Geom::OptRect const &/*dbox*/, Geom::OptRect const &/*bbox*/) +unsigned int PrintEmf::fill(Inkscape::Extension::Print * /*mod*/, Geom::PathVector const &pathv, + Geom::Affine const & /*transform*/, SPStyle const *style, Geom::OptRect const & /*pbox*/, + Geom::OptRect const & /*dbox*/, Geom::OptRect const & /*bbox*/) { char *rec; using Geom::X; using Geom::Y; Geom::Affine tf = m_tr_stack.top(); - do_clip_if_present(style); // If clipping is needed set it up + do_clip_if_present(style); // If clipping is needed set it up - use_fill = true; + use_fill = true; use_stroke = false; fill_transform = tf; int brush_stat = create_brush(style, nullptr); - /* native linear gradients are only used if the object is a rectangle AND the gradient is parallel to the sides of the object */ + /* native linear gradients are only used if the object is a rectangle AND the gradient is parallel to the sides of + * the object */ bool is_Rect = false; double angle; - int rectDir=0; + int rectDir = 0; Geom::Path pathRect; - if(FixPPTLinGrad && brush_stat && gv.mode == DRAW_LINEAR_GRADIENT){ + if (FixPPTLinGrad && brush_stat && gv.mode == DRAW_LINEAR_GRADIENT) { Geom::PathVector pvr = pathv * fill_transform; pathRect = pathv_to_rect(pvr, &is_Rect, &angle); - if(is_Rect){ + if (is_Rect) { /* Gradientfill records can only be used if the gradient is parallel to the sides of the rectangle. That must be checked here so that we can fall back to another form of gradient fill if it is not the case. */ rectDir = vector_rect_alignment(angle, (gv.p2 - gv.p1) * fill_transform); - if(!rectDir)is_Rect = false; + if (!rectDir) + is_Rect = false; } - if(!is_Rect && !FixPPTGrad2Polys)brush_stat=0; // fall all the way back to a solid fill + if (!is_Rect && !FixPPTGrad2Polys) + brush_stat = 0; // fall all the way back to a solid fill } if (brush_stat) { // only happens if the style is a gradient @@ -1160,43 +1169,44 @@ unsigned int PrintEmf::fill( Handle gradients. Uses modified livarot as 2geom boolops is currently broken. Can handle gradients with multiple stops. - The overlap is needed to avoid antialiasing artifacts when edges are not strictly aligned on pixel boundaries. - There is an inevitable loss of accuracy saving through an EMF file because of the integer coordinate system. - Keep the overlap quite large so that loss of accuracy does not remove an overlap. + The overlap is needed to avoid antialiasing artifacts when edges are not strictly aligned on pixel + boundaries. There is an inevitable loss of accuracy saving through an EMF file because of the integer + coordinate system. Keep the overlap quite large so that loss of accuracy does not remove an overlap. */ - destroy_pen(); //this sets the NULL_PEN, otherwise gradient slices may display with boundaries, see longer explanation below + destroy_pen(); // this sets the NULL_PEN, otherwise gradient slices may display with boundaries, see longer + // explanation below Geom::Path cutter; - float rgb[3]; + float rgb[3]; U_COLORREF wc, c1, c2; - FillRule frb = SPWR_to_LVFR((SPWindRule) style->fill_rule.computed); - double doff, doff_base, doff_range; - double divisions = 128.0; - int nstops; - int istop = 1; - float opa; // opacity at stop - - SPRadialGradient *tg = (SPRadialGradient *)(gv.grad); // linear/radial are the same here + FillRule frb = SPWR_to_LVFR((SPWindRule)style->fill_rule.computed); + double doff, doff_base, doff_range; + double divisions = 128.0; + int nstops; + int istop = 1; + float opa; // opacity at stop + + SPRadialGradient *tg = (SPRadialGradient *)(gv.grad); // linear/radial are the same here nstops = tg->vector.stops.size(); tg->vector.stops[0].color.get_rgb_floatv(rgb); - opa = tg->vector.stops[0].opacity; // first stop - c1 = U_RGBA(255 * rgb[0], 255 * rgb[1], 255 * rgb[2], 255 * opa); + opa = tg->vector.stops[0].opacity; // first stop + c1 = U_RGBA(255 * rgb[0], 255 * rgb[1], 255 * rgb[2], 255 * opa); tg->vector.stops[nstops - 1].color.get_rgb_floatv(rgb); - opa = tg->vector.stops[nstops - 1].opacity; // last stop - c2 = U_RGBA(255 * rgb[0], 255 * rgb[1], 255 * rgb[2], 255 * opa); + opa = tg->vector.stops[nstops - 1].opacity; // last stop + c2 = U_RGBA(255 * rgb[0], 255 * rgb[1], 255 * rgb[2], 255 * opa); - doff = 0.0; - doff_base = 0.0; - doff_range = tg->vector.stops[1].offset; // next or last stop + doff = 0.0; + doff_base = 0.0; + doff_range = tg->vector.stops[1].offset; // next or last stop if (gv.mode == DRAW_RADIAL_GRADIENT) { - Geom::Point xv = gv.p2 - gv.p1; // X' vector - Geom::Point yv = gv.p3 - gv.p1; // Y' vector - Geom::Point xuv = Geom::unit_vector(xv); // X' unit vector + Geom::Point xv = gv.p2 - gv.p1; // X' vector + Geom::Point yv = gv.p3 - gv.p1; // Y' vector + Geom::Point xuv = Geom::unit_vector(xv); // X' unit vector double rx = hypot(xv[X], xv[Y]); double ry = hypot(yv[X], yv[Y]); - double range = fmax(rx, ry); // length along the gradient - double step = range / divisions; // adequate approximation for gradient - double overlap = step / 4.0; // overlap slices slightly + double range = fmax(rx, ry); // length along the gradient + double step = range / divisions; // adequate approximation for gradient + double overlap = step / 4.0; // overlap slices slightly double start; double stop; Geom::PathVector pathvc, pathvr; @@ -1204,10 +1214,11 @@ unsigned int PrintEmf::fill( /* radial gradient might stop part way through the shape, fill with outer color from there to "infinity". Do this first so that outer colored ring will overlay it. */ - pathvc = center_elliptical_hole_as_SVG_PathV(gv.p1, rx * (1.0 - overlap / range), ry * (1.0 - overlap / range), asin(xuv[Y])); - pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule) fill_oddEven, frb); + pathvc = center_elliptical_hole_as_SVG_PathV(gv.p1, rx * (1.0 - overlap / range), + ry * (1.0 - overlap / range), asin(xuv[Y])); + pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule)fill_oddEven, frb); wc = weight_opacity(c2); - (void) create_brush(style, &wc); + (void)create_brush(style, &wc); print_pathv(pathvr, fill_transform); tg->vector.stops[istop].color.get_rgb_floatv(rgb); @@ -1220,21 +1231,22 @@ unsigned int PrintEmf::fill( stop = range; } wc = weight_colors(c1, c2, (doff - doff_base) / (doff_range - doff_base)); - (void) create_brush(style, &wc); + (void)create_brush(style, &wc); - pathvc = center_elliptical_ring_as_SVG_PathV(gv.p1, rx * start / range, ry * start / range, rx * stop / range, ry * stop / range, asin(xuv[Y])); + pathvc = center_elliptical_ring_as_SVG_PathV(gv.p1, rx * start / range, ry * start / range, + rx * stop / range, ry * stop / range, asin(xuv[Y])); - pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule) fill_nonZero, frb); - print_pathv(pathvr, fill_transform); // show the intersection + pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule)fill_nonZero, frb); + print_pathv(pathvr, fill_transform); // show the intersection if (doff >= doff_range) { istop++; if (istop >= nstops) { istop = nstops - 1; - continue; // could happen on a rounding error + continue; // could happen on a rounding error } - doff_base = doff_range; - doff_range = tg->vector.stops[istop].offset; // next or last stop + doff_base = doff_range; + doff_range = tg->vector.stops[istop].offset; // next or last stop c1 = c2; tg->vector.stops[istop].color.get_rgb_floatv(rgb); opa = tg->vector.stops[istop].opacity; @@ -1242,7 +1254,7 @@ unsigned int PrintEmf::fill( } } } else if (gv.mode == DRAW_LINEAR_GRADIENT) { - if(is_Rect){ + if (is_Rect) { int gMode; Geom::Point ul, ur, lr; Geom::Point outUL, outLR; // UL,LR corners of a stop rectangle, in OUTPUT coordinates @@ -1257,22 +1269,23 @@ unsigned int PrintEmf::fill( ul = get_pathrect_corner(pathRect, angle, 0) * PX2WORLD; ur = get_pathrect_corner(pathRect, angle, 1) * PX2WORLD; lr = get_pathrect_corner(pathRect, angle, 2) * PX2WORLD; - wRect = Geom::distance(ul,ur); - hRect = Geom::distance(ur,lr); + wRect = Geom::distance(ul, ur); + hRect = Geom::distance(ur, lr); /* The basic rectangle for all of these is placed with its UL corner at 0,0 with a size wRect,hRect. Apply a world transform to place/scale it into the appropriate position on the drawing. - Actual gradientfill records are either this entire rectangle or slices of it as defined by the stops. - This rectangle has already been transformed by tf (whatever rotation/scale) Inkscape had applied to it. + Actual gradientfill records are either this entire rectangle or slices of it as defined by the + stops. This rectangle has already been transformed by tf (whatever rotation/scale) Inkscape had + applied to it. */ - Geom::Affine tf2 = Geom::Rotate(-angle); // the rectangle may be drawn skewed to the coordinate system + Geom::Affine tf2 = Geom::Rotate(-angle); // the rectangle may be drawn skewed to the coordinate system tmpTransform.eM11 = tf2[0]; tmpTransform.eM12 = tf2[1]; tmpTransform.eM21 = tf2[2]; tmpTransform.eM22 = tf2[3]; - tmpTransform.eDx = round((ul)[Geom::X]); // use explicit round for better stability - tmpTransform.eDy = round((ul)[Geom::Y]); + tmpTransform.eDx = round((ul)[Geom::X]); // use explicit round for better stability + tmpTransform.eDy = round((ul)[Geom::Y]); rec = U_EMRSAVEDC_set(); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { @@ -1284,72 +1297,69 @@ unsigned int PrintEmf::fill( g_error("Fatal programming error in PrintEmf::image at EMRMODIFYWORLDTRANSFORM"); } - for(;istopvector.stops[istop].offset; // next or last stop - if(rectDir == 1 || rectDir == 2){ - outUL = Geom::Point(doff_base *wRect, 0 ); - outLR = Geom::Point(doff_range*wRect, hRect); - gMode = U_GRADIENT_FILL_RECT_H; - } - else { - outUL = Geom::Point(0, doff_base *hRect); - outLR = Geom::Point(wRect,doff_range*hRect); - gMode = U_GRADIENT_FILL_RECT_V; - } - - doff_base = doff_range; - rcb.left = round(outUL[X]); // use explicit round for better stability - rcb.top = round(outUL[Y]); - rcb.right = round(outLR[X]); - rcb.bottom = round(outLR[Y]); - tg->vector.stops[istop].color.get_rgb_floatv(rgb); - opa = tg->vector.stops[istop].opacity; - c2 = U_RGBA(255 * rgb[0], 255 * rgb[1], 255 * rgb[2], 255 * opa); - - if(rectDir == 2 || rectDir == 4){ // gradient is reversed, so swap colors - ut[0] = make_trivertex(outUL, c2); - ut[1] = make_trivertex(outLR, c1); - } - else { - ut[0] = make_trivertex(outUL, c1); - ut[1] = make_trivertex(outLR, c2); - } - c1 = c2; // for next stop - ug4.UpperLeft = 0; - ug4.LowerRight= 1; - rec = U_EMRGRADIENTFILL_set(rcb, 2, 1, gMode, ut, (uint32_t *) &ug4 ); - if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { - g_error("Fatal programming error in PrintEmf::fill at U_EMRGRADIENTFILL_set"); - } + for (; istop < nstops; istop++) { + doff_range = tg->vector.stops[istop].offset; // next or last stop + if (rectDir == 1 || rectDir == 2) { + outUL = Geom::Point(doff_base * wRect, 0); + outLR = Geom::Point(doff_range * wRect, hRect); + gMode = U_GRADIENT_FILL_RECT_H; + } else { + outUL = Geom::Point(0, doff_base * hRect); + outLR = Geom::Point(wRect, doff_range * hRect); + gMode = U_GRADIENT_FILL_RECT_V; + } + + doff_base = doff_range; + rcb.left = round(outUL[X]); // use explicit round for better stability + rcb.top = round(outUL[Y]); + rcb.right = round(outLR[X]); + rcb.bottom = round(outLR[Y]); + tg->vector.stops[istop].color.get_rgb_floatv(rgb); + opa = tg->vector.stops[istop].opacity; + c2 = U_RGBA(255 * rgb[0], 255 * rgb[1], 255 * rgb[2], 255 * opa); + + if (rectDir == 2 || rectDir == 4) { // gradient is reversed, so swap colors + ut[0] = make_trivertex(outUL, c2); + ut[1] = make_trivertex(outLR, c1); + } else { + ut[0] = make_trivertex(outUL, c1); + ut[1] = make_trivertex(outLR, c2); + } + c1 = c2; // for next stop + ug4.UpperLeft = 0; + ug4.LowerRight = 1; + rec = U_EMRGRADIENTFILL_set(rcb, 2, 1, gMode, ut, (uint32_t *)&ug4); + if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { + g_error("Fatal programming error in PrintEmf::fill at U_EMRGRADIENTFILL_set"); + } } rec = U_EMRRESTOREDC_set(-1); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::fill at U_EMRRESTOREDC_set"); } - } - else { - Geom::Point uv = Geom::unit_vector(gv.p2 - gv.p1); // unit vector - Geom::Point puv = uv.cw(); // perp. to unit vector - double range = Geom::distance(gv.p1, gv.p2); // length along the gradient - double step = range / divisions; // adequate approximation for gradient - double overlap = step / 4.0; // overlap slices slightly + } else { + Geom::Point uv = Geom::unit_vector(gv.p2 - gv.p1); // unit vector + Geom::Point puv = uv.cw(); // perp. to unit vector + double range = Geom::distance(gv.p1, gv.p2); // length along the gradient + double step = range / divisions; // adequate approximation for gradient + double overlap = step / 4.0; // overlap slices slightly double start; double stop; Geom::PathVector pathvc, pathvr; /* before lower end of gradient, overlap first slice position */ wc = weight_opacity(c1); - (void) create_brush(style, &wc); + (void)create_brush(style, &wc); pathvc = rect_cutter(gv.p1, uv * (overlap), uv * (-50000.0), puv * 50000.0); - pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule) fill_nonZero, frb); + pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule)fill_nonZero, frb); print_pathv(pathvr, fill_transform); /* after high end of gradient, overlap last slice position */ wc = weight_opacity(c2); - (void) create_brush(style, &wc); + (void)create_brush(style, &wc); pathvc = rect_cutter(gv.p2, uv * (-overlap), uv * (50000.0), puv * 50000.0); - pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule) fill_nonZero, frb); + pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule)fill_nonZero, frb); print_pathv(pathvr, fill_transform); tg->vector.stops[istop].color.get_rgb_floatv(rgb); @@ -1364,18 +1374,19 @@ unsigned int PrintEmf::fill( pathvc = rect_cutter(gv.p1, uv * start, uv * stop, puv * 50000.0); wc = weight_colors(c1, c2, (doff - doff_base) / (doff_range - doff_base)); - (void) create_brush(style, &wc); - Geom::PathVector pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule) fill_nonZero, frb); - print_pathv(pathvr, fill_transform); // show the intersection + (void)create_brush(style, &wc); + Geom::PathVector pathvr = + sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule)fill_nonZero, frb); + print_pathv(pathvr, fill_transform); // show the intersection if (doff >= doff_range) { istop++; if (istop >= nstops) { istop = nstops - 1; - continue; // could happen on a rounding error + continue; // could happen on a rounding error } - doff_base = doff_range; - doff_range = tg->vector.stops[istop].offset; // next or last stop + doff_base = doff_range; + doff_range = tg->vector.stops[istop].offset; // next or last stop c1 = c2; tg->vector.stops[istop].color.get_rgb_floatv(rgb); opa = tg->vector.stops[istop].opacity; @@ -1386,7 +1397,7 @@ unsigned int PrintEmf::fill( } else { g_error("Fatal programming error in PrintEmf::fill, invalid gradient type detected"); } - use_fill = false; // gradients handled, be sure stroke does not use stroke and fill + use_fill = false; // gradients handled, be sure stroke does not use stroke and fill } else { /* Inkscape was not calling create_pen for objects with no border. @@ -1396,26 +1407,23 @@ unsigned int PrintEmf::fill( To avoid this force the pen to NULL_PEN if we can determine that no pen will be needed after the fill. */ if (style->stroke.noneSet || style->stroke_width.computed == 0.0) { - destroy_pen(); //this sets the NULL_PEN + destroy_pen(); // this sets the NULL_PEN } /* postpone fill in case stroke also required AND all stroke paths closed Dashes converted to line segments will "open" a closed path. */ bool all_closed = true; - for (const auto & pit : pathv) { + for (const auto &pit : pathv) { for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_open(); ++cit) { if (pit.end_default() != pit.end_closed()) { all_closed = false; } } } - if ( - (style->stroke.isNone() || style->stroke.noneSet || style->stroke_width.computed == 0.0) || - (!style->stroke_dasharray.values.empty() && FixPPTDashLine) || - !all_closed - ) { - print_pathv(pathv, fill_transform); // do any fills. side effect: clears fill_pathv + if ((style->stroke.isNone() || style->stroke.noneSet || style->stroke_width.computed == 0.0) || + (!style->stroke_dasharray.values.empty() && FixPPTDashLine) || !all_closed) { + print_pathv(pathv, fill_transform); // do any fills. side effect: clears fill_pathv use_fill = false; } } @@ -1423,16 +1431,13 @@ unsigned int PrintEmf::fill( return 0; } - -unsigned int PrintEmf::stroke( - Inkscape::Extension::Print * /*mod*/, - Geom::PathVector const &pathv, const Geom::Affine &/*transform*/, const SPStyle *style, - Geom::OptRect const &/*pbox*/, Geom::OptRect const &/*dbox*/, Geom::OptRect const &/*bbox*/) +unsigned int PrintEmf::stroke(Inkscape::Extension::Print * /*mod*/, Geom::PathVector const &pathv, + const Geom::Affine & /*transform*/, const SPStyle *style, Geom::OptRect const & /*pbox*/, + Geom::OptRect const & /*dbox*/, Geom::OptRect const & /*bbox*/) { - char *rec = nullptr; Geom::Affine tf = m_tr_stack.top(); - do_clip_if_present(style); // If clipping is needed set it up + do_clip_if_present(style); // If clipping is needed set it up use_stroke = true; // use_fill was set in ::fill, if it is needed @@ -1441,18 +1446,18 @@ unsigned int PrintEmf::stroke( return 0; } - if (!style->stroke_dasharray.values.empty() && FixPPTDashLine) { + if (!style->stroke_dasharray.values.empty() && FixPPTDashLine) { // convert the path, gets its complete length, and then make a new path with parameter length instead of t - Geom::Piecewise > tmp_pathpw; // pathv-> sbasis - Geom::Piecewise > tmp_pathpw2; // sbasis using arc length parameter - Geom::Piecewise > tmp_pathpw3; // new (discontinuous) path, composed of dots/dashes - Geom::Piecewise > first_frag; // first fragment, will be appended at end + Geom::Piecewise> tmp_pathpw; // pathv-> sbasis + Geom::Piecewise> tmp_pathpw2; // sbasis using arc length parameter + Geom::Piecewise> tmp_pathpw3; // new (discontinuous) path, composed of dots/dashes + Geom::Piecewise> first_frag; // first fragment, will be appended at end int n_dash = style->stroke_dasharray.values.size(); - int i = 0; //dash index - double tlength; // length of tmp_pathpw - double slength = 0.0; // start of gragment - double elength; // end of gragment - for (const auto & i : pathv) { + int i = 0; // dash index + double tlength; // length of tmp_pathpw + double slength = 0.0; // start of gragment + double elength; // end of gragment + for (const auto &i : pathv) { tmp_pathpw.concat(i.toPwSb()); } tlength = length(tmp_pathpw, 0.1); @@ -1464,7 +1469,7 @@ unsigned int PrintEmf::stroke( if (elength > tlength) { elength = tlength; } - Geom::Piecewise > fragment(portion(tmp_pathpw2, slength, elength)); + Geom::Piecewise> fragment(portion(tmp_pathpw2, slength, elength)); if (slength) { tmp_pathpw3.concat(fragment); } else { @@ -1484,7 +1489,7 @@ unsigned int PrintEmf::stroke( } use_stroke = false; - use_fill = false; + use_fill = false; if (usebk) { // OPAQUE was set, revert to TRANSPARENT usebk = false; @@ -1497,22 +1502,20 @@ unsigned int PrintEmf::stroke( return 0; } - // Draws simple_shapes, those with closed EMR_* primitives, like polygons, rectangles and ellipses. // These use whatever the current pen/brush are and need not be followed by a FILLPATH or STROKEPATH. // For other paths it sets a few flags and returns. bool PrintEmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Affine &transform) { - Geom::PathVector pv = pathv_to_linear_and_cubic_beziers(pathv * transform); - int nodes = 0; - int moves = 0; - int lines = 0; + int nodes = 0; + int moves = 0; + int lines = 0; int curves = 0; - char *rec = nullptr; + char *rec = nullptr; - for (auto & pit : pv) { + for (auto &pit : pv) { moves++; nodes++; @@ -1537,7 +1540,7 @@ bool PrintEmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff /** * For all Subpaths in the */ - for (auto & pit : pv) { + for (auto &pit : pv) { using Geom::X; using Geom::Y; @@ -1546,8 +1549,8 @@ bool PrintEmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff p0[X] = (p0[X] * PX2WORLD); p0[Y] = (p0[Y] * PX2WORLD); - int32_t const x0 = (int32_t) round(p0[X]); - int32_t const y0 = (int32_t) round(p0[Y]); + int32_t const x0 = (int32_t)round(p0[X]); + int32_t const y0 = (int32_t)round(p0[Y]); lpPoints[i].x = x0; lpPoints[i].y = y0; @@ -1558,46 +1561,46 @@ bool PrintEmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff */ for (Geom::Path::iterator cit = pit.begin(); cit != pit.end_open(); ++cit) { if (is_straight_curve(*cit)) { - //Geom::Point p0 = cit->initialPoint(); + // Geom::Point p0 = cit->initialPoint(); Geom::Point p1 = cit->finalPoint(); - //p0[X] = (p0[X] * PX2WORLD); + // p0[X] = (p0[X] * PX2WORLD); p1[X] = (p1[X] * PX2WORLD); - //p0[Y] = (p0[Y] * PX2WORLD); + // p0[Y] = (p0[Y] * PX2WORLD); p1[Y] = (p1[Y] * PX2WORLD); - //int32_t const x0 = (int32_t) round(p0[X]); - //int32_t const y0 = (int32_t) round(p0[Y]); - int32_t const x1 = (int32_t) round(p1[X]); - int32_t const y1 = (int32_t) round(p1[Y]); + // int32_t const x0 = (int32_t) round(p0[X]); + // int32_t const y0 = (int32_t) round(p0[Y]); + int32_t const x1 = (int32_t)round(p1[X]); + int32_t const y1 = (int32_t)round(p1[Y]); lpPoints[i].x = x1; lpPoints[i].y = y1; i = i + 1; } else if (Geom::CubicBezier const *cubic = dynamic_cast(&*cit)) { std::vector points = cubic->controlPoints(); - //Geom::Point p0 = points[0]; + // Geom::Point p0 = points[0]; Geom::Point p1 = points[1]; Geom::Point p2 = points[2]; Geom::Point p3 = points[3]; - //p0[X] = (p0[X] * PX2WORLD); + // p0[X] = (p0[X] * PX2WORLD); p1[X] = (p1[X] * PX2WORLD); p2[X] = (p2[X] * PX2WORLD); p3[X] = (p3[X] * PX2WORLD); - //p0[Y] = (p0[Y] * PX2WORLD); + // p0[Y] = (p0[Y] * PX2WORLD); p1[Y] = (p1[Y] * PX2WORLD); p2[Y] = (p2[Y] * PX2WORLD); p3[Y] = (p3[Y] * PX2WORLD); - //int32_t const x0 = (int32_t) round(p0[X]); - //int32_t const y0 = (int32_t) round(p0[Y]); - int32_t const x1 = (int32_t) round(p1[X]); - int32_t const y1 = (int32_t) round(p1[Y]); - int32_t const x2 = (int32_t) round(p2[X]); - int32_t const y2 = (int32_t) round(p2[Y]); - int32_t const x3 = (int32_t) round(p3[X]); - int32_t const y3 = (int32_t) round(p3[Y]); + // int32_t const x0 = (int32_t) round(p0[X]); + // int32_t const y0 = (int32_t) round(p0[Y]); + int32_t const x1 = (int32_t)round(p1[X]); + int32_t const y1 = (int32_t)round(p1[Y]); + int32_t const x2 = (int32_t)round(p2[X]); + int32_t const y2 = (int32_t)round(p2[Y]); + int32_t const x3 = (int32_t)round(p3[X]); + int32_t const y3 = (int32_t)round(p3[Y]); lpPoints[i].x = x1; lpPoints[i].y = y1; @@ -1628,18 +1631,17 @@ bool PrintEmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff } else if (moves == 1 && nodes == 5 && moves + curves == nodes && closed) { // if (lpPoints[0].x == lpPoints[1].x && lpPoints[1].x == lpPoints[11].x && // lpPoints[5].x == lpPoints[6].x && lpPoints[6].x == lpPoints[7].x && - // lpPoints[2].x == lpPoints[10].x && lpPoints[3].x == lpPoints[9].x && lpPoints[4].x == lpPoints[8].x && - // lpPoints[2].y == lpPoints[3].y && lpPoints[3].y == lpPoints[4].y && - // lpPoints[8].y == lpPoints[9].y && lpPoints[9].y == lpPoints[10].y && - // lpPoints[5].y == lpPoints[1].y && lpPoints[6].y == lpPoints[0].y && lpPoints[7].y == lpPoints[11].y) + // lpPoints[2].x == lpPoints[10].x && lpPoints[3].x == lpPoints[9].x && lpPoints[4].x == + // lpPoints[8].x && lpPoints[2].y == lpPoints[3].y && lpPoints[3].y == lpPoints[4].y && lpPoints[8].y + // == lpPoints[9].y && lpPoints[9].y == lpPoints[10].y && lpPoints[5].y == lpPoints[1].y && + // lpPoints[6].y == lpPoints[0].y && lpPoints[7].y == lpPoints[11].y) // { // disable due to LP Bug 407394 // ellipse = true; // } } if (polygon || ellipse) { - - if (use_fill && !use_stroke) { // only fill + if (use_fill && !use_stroke) { // only fill rec = selectobject_set(U_NULL_PEN, eht); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::print_simple_shape at selectobject_set pen"); @@ -1653,21 +1655,14 @@ bool PrintEmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff if (polygon) { if (rectangle) { - U_RECTL rcl = rectl_set((U_POINTL) { - lpPoints[0].x, lpPoints[0].y - }, (U_POINTL) { - lpPoints[2].x, lpPoints[2].y - }); + U_RECTL rcl = + rectl_set((U_POINTL){lpPoints[0].x, lpPoints[0].y}, (U_POINTL){lpPoints[2].x, lpPoints[2].y}); rec = U_EMRRECTANGLE_set(rcl); } else { rec = U_EMRPOLYGON_set(U_RCL_DEF, nodes, lpPoints); } } else if (ellipse) { - U_RECTL rcl = rectl_set((U_POINTL) { - lpPoints[6].x, lpPoints[3].y - }, (U_POINTL) { - lpPoints[0].x, lpPoints[9].y - }); + U_RECTL rcl = rectl_set((U_POINTL){lpPoints[6].x, lpPoints[3].y}, (U_POINTL){lpPoints[0].x, lpPoints[9].y}); rec = U_EMRELLIPSE_set(rcl); } if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { @@ -1710,20 +1705,21 @@ bool PrintEmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff size of two bitmaps. */ -unsigned int PrintEmf::image( - Inkscape::Extension::Print * /* module */, /** not used */ - unsigned char *rgba_px, /** array of pixel values, Gdk::Pixbuf bitmap format */ - unsigned int w, /** width of bitmap */ - unsigned int h, /** height of bitmap */ - unsigned int rs, /** row stride (normally w*4) */ - Geom::Affine const &tf_rect, /** affine transform only used for defining location and size of rect, for all other transforms, use the one from m_tr_stack */ - SPStyle const *style) /** provides indirect link to image object */ +unsigned int PrintEmf::image(Inkscape::Extension::Print * /* module */, /** not used */ + unsigned char *rgba_px, /** array of pixel values, Gdk::Pixbuf bitmap format */ + unsigned int w, /** width of bitmap */ + unsigned int h, /** height of bitmap */ + unsigned int rs, /** row stride (normally w*4) */ + Geom::Affine const &tf_rect, /** affine transform only used for defining location and size + of rect, for all other transforms, use the one from + m_tr_stack */ + SPStyle const *style) /** provides indirect link to image object */ { double x1, y1, dw, dh; char *rec = nullptr; Geom::Affine tf = m_tr_stack.top(); - do_clip_if_present(style); // If clipping is needed set it up + do_clip_if_present(style); // If clipping is needed set it up rec = U_EMRSETSTRETCHBLTMODE_set(U_COLORONCOLOR); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { @@ -1732,41 +1728,42 @@ unsigned int PrintEmf::image( x1 = tf_rect[4]; y1 = tf_rect[5]; - dw = ((double) w) * tf_rect[0]; - dh = ((double) h) * tf_rect[3]; + dw = ((double)w) * tf_rect[0]; + dh = ((double)h) * tf_rect[3]; Geom::Point pLL(x1, y1); - Geom::Point pLL2 = pLL * tf; //location of LL corner in Inkscape coordinates - - char *px; - uint32_t cbPx; - uint32_t colortype; - PU_RGBQUAD ct; - int numCt; - U_BITMAPINFOHEADER Bmih; - PU_BITMAPINFO Bmi; + Geom::Point pLL2 = pLL * tf; // location of LL corner in Inkscape coordinates + + char *px; + uint32_t cbPx; + uint32_t colortype; + PU_RGBQUAD ct; + int numCt; + U_BITMAPINFOHEADER Bmih; + PU_BITMAPINFO Bmi; colortype = U_BCBM_COLOR32; - (void) RGBA_to_DIB(&px, &cbPx, &ct, &numCt, (char *) rgba_px, w, h, w * 4, colortype, 0, 1); + (void)RGBA_to_DIB(&px, &cbPx, &ct, &numCt, (char *)rgba_px, w, h, w * 4, colortype, 0, 1); Bmih = bitmapinfoheader_set(w, h, 1, colortype, U_BI_RGB, 0, PXPERMETER, PXPERMETER, numCt, 0); Bmi = bitmapinfo_set(Bmih, ct); - U_POINTL Dest = pointl_set(round(pLL2[Geom::X] * PX2WORLD), round(pLL2[Geom::Y] * PX2WORLD)); + U_POINTL Dest = pointl_set(round(pLL2[Geom::X] * PX2WORLD), round(pLL2[Geom::Y] * PX2WORLD)); U_POINTL cDest = pointl_set(round(dw * PX2WORLD), round(dh * PX2WORLD)); - U_POINTL Src = pointl_set(0, 0); - U_POINTL cSrc = pointl_set(w, h); - /* map the integer Dest coordinates back into pLL2, so that the rounded part does not destabilize the transform offset below */ + U_POINTL Src = pointl_set(0, 0); + U_POINTL cSrc = pointl_set(w, h); + /* map the integer Dest coordinates back into pLL2, so that the rounded part does not destabilize the transform + * offset below */ pLL2[Geom::X] = Dest.x; pLL2[Geom::Y] = Dest.y; pLL2 /= PX2WORLD; - if (!FixImageRot) { /* Rotate images - some programs cannot read them in correctly if they are rotated */ - tf[4] = tf[5] = 0.0; // get rid of the offset in the transform + if (!FixImageRot) { /* Rotate images - some programs cannot read them in correctly if they are rotated */ + tf[4] = tf[5] = 0.0; // get rid of the offset in the transform Geom::Point pLL2prime = pLL2 * tf; U_XFORM tmpTransform; - tmpTransform.eM11 = tf[0]; - tmpTransform.eM12 = tf[1]; - tmpTransform.eM21 = tf[2]; - tmpTransform.eM22 = tf[3]; - tmpTransform.eDx = (pLL2[Geom::X] - pLL2prime[Geom::X]) * PX2WORLD; - tmpTransform.eDy = (pLL2[Geom::Y] - pLL2prime[Geom::Y]) * PX2WORLD; + tmpTransform.eM11 = tf[0]; + tmpTransform.eM12 = tf[1]; + tmpTransform.eM21 = tf[2]; + tmpTransform.eM22 = tf[3]; + tmpTransform.eDx = (pLL2[Geom::X] - pLL2prime[Geom::X]) * PX2WORLD; + tmpTransform.eDy = (pLL2[Geom::Y] - pLL2prime[Geom::Y]) * PX2WORLD; rec = U_EMRSAVEDC_set(); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { @@ -1778,18 +1775,17 @@ unsigned int PrintEmf::image( g_error("Fatal programming error in PrintEmf::image at EMRMODIFYWORLDTRANSFORM"); } } - rec = U_EMRSTRETCHDIBITS_set( - U_RCL_DEF, //! Bounding rectangle in device units - Dest, //! Destination UL corner in logical units - cDest, //! Destination W & H in logical units - Src, //! Source UL corner in logical units - cSrc, //! Source W & H in logical units - U_DIB_RGB_COLORS, //! DIBColors Enumeration - U_SRCCOPY, //! RasterOPeration Enumeration - Bmi, //! (Optional) bitmapbuffer (U_BITMAPINFO section) - h * rs, //! size in bytes of px - px //! (Optional) bitmapbuffer (U_BITMAPINFO section) - ); + rec = U_EMRSTRETCHDIBITS_set(U_RCL_DEF, //! Bounding rectangle in device units + Dest, //! Destination UL corner in logical units + cDest, //! Destination W & H in logical units + Src, //! Source UL corner in logical units + cSrc, //! Source W & H in logical units + U_DIB_RGB_COLORS, //! DIBColors Enumeration + U_SRCCOPY, //! RasterOPeration Enumeration + Bmi, //! (Optional) bitmapbuffer (U_BITMAPINFO section) + h * rs, //! size in bytes of px + px //! (Optional) bitmapbuffer (U_BITMAPINFO section) + ); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::image at U_EMRSTRETCHDIBITS_set"); } @@ -1809,7 +1805,8 @@ unsigned int PrintEmf::image( return 0; } -unsigned int PrintEmf::draw_pathv_to_EMF(Geom::PathVector const &pathv, const Geom::Affine &transform) { +unsigned int PrintEmf::draw_pathv_to_EMF(Geom::PathVector const &pathv, const Geom::Affine &transform) +{ char *rec; /* inkscape to EMF scaling is done below, but NOT the rotation/translation transform, @@ -1826,17 +1823,16 @@ unsigned int PrintEmf::draw_pathv_to_EMF(Geom::PathVector const &pathv, const Ge /** * For all Subpaths in the */ - for (const auto & pit : pv) { + for (const auto &pit : pv) { using Geom::X; using Geom::Y; - Geom::Point p0 = pit.initialPoint(); p0[X] = (p0[X] * PX2WORLD); p0[Y] = (p0[Y] * PX2WORLD); - U_POINTL ptl = pointl_set((int32_t) round(p0[X]), (int32_t) round(p0[Y])); + U_POINTL ptl = pointl_set((int32_t)round(p0[X]), (int32_t)round(p0[Y])); rec = U_EMRMOVETOEX_set(ptl); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::print_pathv at U_EMRMOVETOEX_set"); @@ -1847,46 +1843,46 @@ unsigned int PrintEmf::draw_pathv_to_EMF(Geom::PathVector const &pathv, const Ge */ for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_open(); ++cit) { if (is_straight_curve(*cit)) { - //Geom::Point p0 = cit->initialPoint(); + // Geom::Point p0 = cit->initialPoint(); Geom::Point p1 = cit->finalPoint(); - //p0[X] = (p0[X] * PX2WORLD); + // p0[X] = (p0[X] * PX2WORLD); p1[X] = (p1[X] * PX2WORLD); - //p0[Y] = (p0[Y] * PX2WORLD); + // p0[Y] = (p0[Y] * PX2WORLD); p1[Y] = (p1[Y] * PX2WORLD); - //int32_t const x0 = (int32_t) round(p0[X]); - //int32_t const y0 = (int32_t) round(p0[Y]); + // int32_t const x0 = (int32_t) round(p0[X]); + // int32_t const y0 = (int32_t) round(p0[Y]); - ptl = pointl_set((int32_t) round(p1[X]), (int32_t) round(p1[Y])); + ptl = pointl_set((int32_t)round(p1[X]), (int32_t)round(p1[Y])); rec = U_EMRLINETO_set(ptl); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::print_pathv at U_EMRLINETO_set"); } } else if (Geom::CubicBezier const *cubic = dynamic_cast(&*cit)) { std::vector points = cubic->controlPoints(); - //Geom::Point p0 = points[0]; + // Geom::Point p0 = points[0]; Geom::Point p1 = points[1]; Geom::Point p2 = points[2]; Geom::Point p3 = points[3]; - //p0[X] = (p0[X] * PX2WORLD); + // p0[X] = (p0[X] * PX2WORLD); p1[X] = (p1[X] * PX2WORLD); p2[X] = (p2[X] * PX2WORLD); p3[X] = (p3[X] * PX2WORLD); - //p0[Y] = (p0[Y] * PX2WORLD); + // p0[Y] = (p0[Y] * PX2WORLD); p1[Y] = (p1[Y] * PX2WORLD); p2[Y] = (p2[Y] * PX2WORLD); p3[Y] = (p3[Y] * PX2WORLD); - //int32_t const x0 = (int32_t) round(p0[X]); - //int32_t const y0 = (int32_t) round(p0[Y]); - int32_t const x1 = (int32_t) round(p1[X]); - int32_t const y1 = (int32_t) round(p1[Y]); - int32_t const x2 = (int32_t) round(p2[X]); - int32_t const y2 = (int32_t) round(p2[Y]); - int32_t const x3 = (int32_t) round(p3[X]); - int32_t const y3 = (int32_t) round(p3[Y]); + // int32_t const x0 = (int32_t) round(p0[X]); + // int32_t const y0 = (int32_t) round(p0[Y]); + int32_t const x1 = (int32_t)round(p1[X]); + int32_t const y1 = (int32_t)round(p1[Y]); + int32_t const x2 = (int32_t)round(p2[X]); + int32_t const y2 = (int32_t)round(p2[Y]); + int32_t const x3 = (int32_t)round(p3[X]); + int32_t const y3 = (int32_t)round(p3[Y]); U_POINTL pt[3]; pt[0].x = x1; @@ -1905,20 +1901,19 @@ unsigned int PrintEmf::draw_pathv_to_EMF(Geom::PathVector const &pathv, const Ge } } - if (pit.end_default() == pit.end_closed()) { // there may be multiples of this on a single path + if (pit.end_default() == pit.end_closed()) { // there may be multiples of this on a single path rec = U_EMRCLOSEFIGURE_set(); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::print_pathv at U_EMRCLOSEFIGURE_set"); } } - } - rec = U_EMRENDPATH_set(); // there may be only be one of these on a single path + rec = U_EMRENDPATH_set(); // there may be only be one of these on a single path if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::print_pathv at U_EMRENDPATH_set"); } - return(0); + return (0); } // may also be called with a simple_shape or an empty path, whereupon it just returns without doing anything @@ -1930,7 +1925,7 @@ unsigned int PrintEmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af simple_shape = print_simple_shape(pathv, tf); if (simple_shape || pathv.empty()) { if (use_fill) { - destroy_brush(); // these must be cleared even if nothing is drawn or hbrush,hpen fill up + destroy_brush(); // these must be cleared even if nothing is drawn or hbrush,hpen fill up } if (use_stroke) { destroy_pen(); @@ -1938,7 +1933,7 @@ unsigned int PrintEmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af return TRUE; } - (void) draw_pathv_to_EMF(pathv, tf); + (void)draw_pathv_to_EMF(pathv, tf); // explicit FILL/STROKE commands are needed for each sub section of the path if (use_fill && !use_stroke) { @@ -1947,12 +1942,12 @@ unsigned int PrintEmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af g_error("Fatal programming error in PrintEmf::fill at U_EMRFILLPATH_set"); } } else if (use_fill && use_stroke) { - rec = U_EMRSTROKEANDFILLPATH_set(U_RCL_DEF); + rec = U_EMRSTROKEANDFILLPATH_set(U_RCL_DEF); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::stroke at U_EMRSTROKEANDFILLPATH_set"); } } else if (!use_fill && use_stroke) { - rec = U_EMRSTROKEPATH_set(U_RCL_DEF); + rec = U_EMRSTROKEPATH_set(U_RCL_DEF); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::stroke at U_EMRSTROKEPATH_set"); } @@ -1969,7 +1964,6 @@ unsigned int PrintEmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af return TRUE; } - unsigned int PrintEmf::text(Inkscape::Extension::Print * /*mod*/, char const *text, Geom::Point const &p, SPStyle const *const style) { @@ -1977,21 +1971,23 @@ unsigned int PrintEmf::text(Inkscape::Extension::Print * /*mod*/, char const *te return 0; } - do_clip_if_present(style); // If clipping is needed set it up + do_clip_if_present(style); // If clipping is needed set it up char *rec = nullptr; int ccount, newfont; int fix90n = 0; uint32_t hfont = 0; Geom::Affine tf = m_tr_stack.top(); double rot = -1800.0 * std::atan2(tf[1], tf[0]) / M_PI; // 0.1 degree rotation, - sign for MM_TEXT - double rotb = -std::atan2(tf[1], tf[0]); // rotation for baseline offset for superscript/subscript, used below + double rotb = -std::atan2(tf[1], tf[0]); // rotation for baseline offset for superscript/subscript, used below double dx, dy; double ky; - // the dx array is smuggled in like: textw1 w2 w3 ...wn, where the widths are floats 7 characters wide, including the space + // the dx array is smuggled in like: textw1 w2 w3 ...wn, where the widths are floats 7 characters + // wide, including the space int ndx, rtl; uint32_t *adx; - smuggle_adxkyrtl_out(text, &adx, &ky, &rtl, &ndx, PX2WORLD * std::min(tf.expansionX(), tf.expansionY())); // side effect: free() adx + smuggle_adxkyrtl_out(text, &adx, &ky, &rtl, &ndx, + PX2WORLD * std::min(tf.expansionX(), tf.expansionY())); // side effect: free() adx uint32_t textalignment; if (rtl > 0) { @@ -2007,40 +2003,39 @@ unsigned int PrintEmf::text(Inkscape::Extension::Print * /*mod*/, char const *te } } - char *text2 = strdup(text); // because U_Utf8ToUtf16le calls iconv which does not like a const char * + char *text2 = strdup(text); // because U_Utf8ToUtf16le calls iconv which does not like a const char * uint16_t *unicode_text = U_Utf8ToUtf16le(text2, 0, nullptr); free(text2); - //translates Unicode to NonUnicode, if possible. If any translate, all will, and all to - //the same font, because of code in Layout::print + // translates Unicode to NonUnicode, if possible. If any translate, all will, and all to + // the same font, because of code in Layout::print UnicodeToNon(unicode_text, &ccount, &newfont); - //PPT gets funky with text within +-1 degree of a multiple of 90, but only for SOME fonts.Snap those to the central value - //Some funky ones: Arial, Times New Roman - //Some not funky ones: Symbol and Verdana. - //Without a huge table we cannot catch them all, so just the most common problem ones. + // PPT gets funky with text within +-1 degree of a multiple of 90, but only for SOME fonts.Snap those to the central + // value Some funky ones: Arial, Times New Roman Some not funky ones: Symbol and Verdana. Without a huge table we + // cannot catch them all, so just the most common problem ones. FontfixParams params; if (FixPPTCharPos) { switch (newfont) { - case CVTSYM: - _lookup_ppt_fontfix("Convert To Symbol", params); - break; - case CVTZDG: - _lookup_ppt_fontfix("Convert To Zapf Dingbats", params); - break; - case CVTWDG: - _lookup_ppt_fontfix("Convert To Wingdings", params); - break; - default: //also CVTNON - _lookup_ppt_fontfix(style->font_family.value(), params); - break; + case CVTSYM: + _lookup_ppt_fontfix("Convert To Symbol", params); + break; + case CVTZDG: + _lookup_ppt_fontfix("Convert To Zapf Dingbats", params); + break; + case CVTWDG: + _lookup_ppt_fontfix("Convert To Wingdings", params); + break; + default: // also CVTNON + _lookup_ppt_fontfix(style->font_family.value(), params); + break; } if (params.f2 != 0 || params.f3 != 0) { - int irem = ((int) round(rot)) % 900 ; + int irem = ((int)round(rot)) % 900; if (irem <= 9 && irem >= -9) { - fix90n = 1; //assume vertical - rot = (double)(((int) round(rot)) - irem); - rotb = rot * M_PI / 1800.0; + fix90n = 1; // assume vertical + rot = (double)(((int)round(rot)) - irem); + rotb = rot * M_PI / 1800.0; if (std::abs(rot) == 900.0) { fix90n = 2; } @@ -2069,24 +2064,14 @@ unsigned int PrintEmf::text(Inkscape::Extension::Print * /*mod*/, char const *te // it was streteched asymmetrically.) Few applications support text from EMF which is scaled // differently by height/width, so leave lfWidth alone. - U_LOGFONT lf = logfont_set( - textheight, - 0, - round(rot), - round(rot), - _translate_weight(style->font_weight.computed), - (style->font_style.computed == SP_CSS_FONT_STYLE_ITALIC), - style->text_decoration_line.underline, - style->text_decoration_line.line_through, - U_DEFAULT_CHARSET, - U_OUT_DEFAULT_PRECIS, - U_CLIP_DEFAULT_PRECIS, - U_DEFAULT_QUALITY, - U_DEFAULT_PITCH | U_FF_DONTCARE, - wfacename); + U_LOGFONT lf = + logfont_set(textheight, 0, round(rot), round(rot), _translate_weight(style->font_weight.computed), + (style->font_style.computed == SP_CSS_FONT_STYLE_ITALIC), style->text_decoration_line.underline, + style->text_decoration_line.line_through, U_DEFAULT_CHARSET, U_OUT_DEFAULT_PRECIS, + U_CLIP_DEFAULT_PRECIS, U_DEFAULT_QUALITY, U_DEFAULT_PITCH | U_FF_DONTCARE, wfacename); free(wfacename); - rec = extcreatefontindirectw_set(&hfont, eht, (char *) &lf, nullptr); + rec = extcreatefontindirectw_set(&hfont, eht, (char *)&lf, nullptr); if (!rec || emf_append((PU_ENHMETARECORD)rec, et, U_REC_FREE)) { g_error("Fatal programming error in PrintEmf::text at extcreatefontindirectw_set"); } @@ -2110,7 +2095,7 @@ unsigned int PrintEmf::text(Inkscape::Extension::Print * /*mod*/, char const *te Geom::Point p2 = p * tf; - //Handle super/subscripts and vertical kerning + // Handle super/subscripts and vertical kerning /* Previously used this, but vertical kerning was not supported p2[Geom::X] -= style->baseline_shift.computed * std::sin( rotb ); p2[Geom::Y] -= style->baseline_shift.computed * std::cos( rotb ); @@ -2118,12 +2103,12 @@ unsigned int PrintEmf::text(Inkscape::Extension::Print * /*mod*/, char const *te p2[Geom::X] += ky * std::sin(rotb); p2[Geom::Y] += ky * std::cos(rotb); - //Conditionally handle compensation for PPT EMF import bug (affects PPT 2003-2010, at least) + // Conditionally handle compensation for PPT EMF import bug (affects PPT 2003-2010, at least) if (FixPPTCharPos) { - if (fix90n == 1) { //vertical + if (fix90n == 1) { // vertical dx = 0.0; dy = params.f3 * style->font_size.computed * std::cos(rotb); - } else if (fix90n == 2) { //horizontal + } else if (fix90n == 2) { // horizontal dx = params.f2 * style->font_size.computed * std::sin(rotb); dy = 0.0; } else { @@ -2137,9 +2122,8 @@ unsigned int PrintEmf::text(Inkscape::Extension::Print * /*mod*/, char const *te p2[Geom::X] = (p2[Geom::X] * PX2WORLD); p2[Geom::Y] = (p2[Geom::Y] * PX2WORLD); - int32_t const xpos = (int32_t) round(p2[Geom::X]); - int32_t const ypos = (int32_t) round(p2[Geom::Y]); - + int32_t const xpos = (int32_t)round(p2[Geom::X]); + int32_t const ypos = (int32_t)round(p2[Geom::Y]); // The number of characters in the string is a bit fuzzy. ndx, the number of entries in adx is // the number of VISIBLE characters, since some may combine from the UTF (8 originally, @@ -2151,13 +2135,9 @@ unsigned int PrintEmf::text(Inkscape::Extension::Print * /*mod*/, char const *te // uint32_t *adx = dx_set(textheight, U_FW_NORMAL, slen); // dx is needed, this makes one up char *rec2; if (rtl > 0) { - rec2 = emrtext_set((U_POINTL) { - xpos, ypos - }, ndx, 2, unicode_text, U_ETO_NONE, U_RCL_DEF, adx); + rec2 = emrtext_set((U_POINTL){xpos, ypos}, ndx, 2, unicode_text, U_ETO_NONE, U_RCL_DEF, adx); } else { // RTL text, U_TA_RTLREADING should be enough, but set this one too just in case - rec2 = emrtext_set((U_POINTL) { - xpos, ypos - }, ndx, 2, unicode_text, U_ETO_RTLREADING, U_RCL_DEF, adx); + rec2 = emrtext_set((U_POINTL){xpos, ypos}, ndx, 2, unicode_text, U_ETO_RTLREADING, U_RCL_DEF, adx); } free(unicode_text); free(adx); @@ -2207,10 +2187,9 @@ void PrintEmf::init() return; } -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ - +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ /* Local Variables: diff --git a/src/extension/internal/emf-print.h b/src/extension/internal/emf-print.h index 020c808ffe3967a00ce80add509bac004c29cc35..6d1ff544df42dff071770026354b80b17fa6cae7 100644 --- a/src/extension/internal/emf-print.h +++ b/src/extension/internal/emf-print.h @@ -14,6 +14,7 @@ #define SEEN_INKSCAPE_EXTENSION_INTERNAL_EMF_PRINT_H #include <3rdparty/libuemf/uemf.h> + #include "extension/internal/metafile-print.h" class SPItem; @@ -26,63 +27,56 @@ class PrintEmf : public PrintMetafile { uint32_t hbrush, hbrushOld, hpen; - unsigned int print_pathv (Geom::PathVector const &pathv, const Geom::Affine &transform); - bool print_simple_shape (Geom::PathVector const &pathv, const Geom::Affine &transform); + unsigned int print_pathv(Geom::PathVector const &pathv, const Geom::Affine &transform); + bool print_simple_shape(Geom::PathVector const &pathv, const Geom::Affine &transform); public: PrintEmf(); /* Print functions */ - unsigned int setup (Inkscape::Extension::Print * module) override; + unsigned int setup(Inkscape::Extension::Print *module) override; - unsigned int begin (Inkscape::Extension::Print * module, SPDocument *doc) override; - unsigned int finish (Inkscape::Extension::Print * module) override; + unsigned int begin(Inkscape::Extension::Print *module, SPDocument *doc) override; + unsigned int finish(Inkscape::Extension::Print *module) override; /* Rendering methods */ - unsigned int fill (Inkscape::Extension::Print *module, - Geom::PathVector const &pathv, - Geom::Affine const &ctm, SPStyle const *style, - Geom::OptRect const &pbox, Geom::OptRect const &dbox, - Geom::OptRect const &bbox) override; - unsigned int stroke (Inkscape::Extension::Print * module, - Geom::PathVector const &pathv, - Geom::Affine const &ctm, SPStyle const *style, - Geom::OptRect const &pbox, Geom::OptRect const &dbox, - Geom::OptRect const &bbox) override; - unsigned int image(Inkscape::Extension::Print *module, - unsigned char *px, - unsigned int w, - unsigned int h, - unsigned int rs, - Geom::Affine const &transform, - SPStyle const *style) override; - unsigned int comment(Inkscape::Extension::Print *module, const char * comment) override; - unsigned int text(Inkscape::Extension::Print *module, char const *text, - Geom::Point const &p, SPStyle const *style) override; - - static void init (); + unsigned int fill(Inkscape::Extension::Print *module, Geom::PathVector const &pathv, Geom::Affine const &ctm, + SPStyle const *style, Geom::OptRect const &pbox, Geom::OptRect const &dbox, + Geom::OptRect const &bbox) override; + unsigned int stroke(Inkscape::Extension::Print *module, Geom::PathVector const &pathv, Geom::Affine const &ctm, + SPStyle const *style, Geom::OptRect const &pbox, Geom::OptRect const &dbox, + Geom::OptRect const &bbox) override; + unsigned int image(Inkscape::Extension::Print *module, unsigned char *px, unsigned int w, unsigned int h, + unsigned int rs, Geom::Affine const &transform, SPStyle const *style) override; + unsigned int comment(Inkscape::Extension::Print *module, const char *comment) override; + unsigned int text(Inkscape::Extension::Print *module, char const *text, Geom::Point const &p, + SPStyle const *style) override; + + static void init(); + protected: - static void smuggle_adxkyrtl_out(const char *string, uint32_t **adx, double *ky, int *rtl, int *ndx, float scale); + static void smuggle_adxkyrtl_out(const char *string, uint32_t **adx, double *ky, int *rtl, int *ndx, float scale); - void do_clip_if_present(SPStyle const *style); - Geom::PathVector merge_PathVector_with_group(Geom::PathVector const &combined_pathvector, SPItem const *item, const Geom::Affine &transform); - Geom::PathVector merge_PathVector_with_shape(Geom::PathVector const &combined_pathvector, SPItem const *item, const Geom::Affine &transform); + void do_clip_if_present(SPStyle const *style); + Geom::PathVector merge_PathVector_with_group(Geom::PathVector const &combined_pathvector, SPItem const *item, + const Geom::Affine &transform); + Geom::PathVector merge_PathVector_with_shape(Geom::PathVector const &combined_pathvector, SPItem const *item, + const Geom::Affine &transform); unsigned int draw_pathv_to_EMF(Geom::PathVector const &pathv, const Geom::Affine &transform); - Geom::Path pathv_to_simple_polygon(Geom::PathVector const &pathv, int *vertices); - Geom::Path pathv_to_rect(Geom::PathVector const &pathv, bool *is_rect, double *angle); + Geom::Path pathv_to_simple_polygon(Geom::PathVector const &pathv, int *vertices); + Geom::Path pathv_to_rect(Geom::PathVector const &pathv, bool *is_rect, double *angle); Geom::Point get_pathrect_corner(Geom::Path pathRect, double angle, int corner); U_TRIVERTEX make_trivertex(Geom::Point Pt, U_COLORREF uc); - int vector_rect_alignment(double angle, Geom::Point vtest); - int create_brush(SPStyle const *style, PU_COLORREF fcolor) override; - void destroy_brush() override; - int create_pen(SPStyle const *style, const Geom::Affine &transform) override; - void destroy_pen() override; + int vector_rect_alignment(double angle, Geom::Point vtest); + int create_brush(SPStyle const *style, PU_COLORREF fcolor) override; + void destroy_brush() override; + int create_pen(SPStyle const *style, const Geom::Affine &transform) override; + void destroy_pen() override; }; -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ - +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* __INKSCAPE_EXTENSION_INTERNAL_PRINT_EMF_H__ */ diff --git a/src/extension/internal/filter/bevels.h b/src/extension/internal/filter/bevels.h index a8382ba4e5a79a9b49d8c71afae1705d46899f55..f91d4c56c81ecc2df6f956ac7d175a34577db66a 100644 --- a/src/extension/internal/filter/bevels.h +++ b/src/extension/internal/filter/bevels.h @@ -17,11 +17,10 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { @@ -30,7 +29,7 @@ namespace Filter { /** \brief Custom predefined Diffuse light filter. - + Basic diffuse bevel to use for building textures Filter's parameters: @@ -40,15 +39,23 @@ namespace Filter { * Lighting color (guint, default -1 [white]) -> diffuse (lighting-color) */ -class DiffuseLight : public Inkscape::Extension::Internal::Filter::Filter { +class DiffuseLight : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - DiffuseLight ( ) : Filter() { }; - ~DiffuseLight ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } - - static void init () { + DiffuseLight() + : Filter(){}; + ~DiffuseLight() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } + + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -70,13 +77,12 @@ public: "\n", new DiffuseLight()); // clang-format on }; - }; -gchar const * -DiffuseLight::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *DiffuseLight::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream smooth; std::ostringstream elevation; @@ -93,25 +99,30 @@ DiffuseLight::get_filter_text (Inkscape::Extension::Extension * ext) r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; - + _filter = g_strdup_printf( - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n", smooth.str().c_str(), r.str().c_str(), g.str().c_str(), b.str().c_str(), elevation.str().c_str(), azimuth.str().c_str(), a.str().c_str()); + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n", + smooth.str().c_str(), r.str().c_str(), g.str().c_str(), b.str().c_str(), elevation.str().c_str(), + azimuth.str().c_str(), a.str().c_str()); return _filter; }; /* DiffuseLight filter */ /** \brief Custom predefined Matte jelly filter. - + Bulging, matte jelly covering Filter's parameters: @@ -122,15 +133,23 @@ DiffuseLight::get_filter_text (Inkscape::Extension::Extension * ext) * Lighting color (guint, default -1 [white]) -> specular (lighting-color) */ -class MatteJelly : public Inkscape::Extension::Internal::Filter::Filter { +class MatteJelly : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - MatteJelly ( ) : Filter() { }; - ~MatteJelly ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } - - static void init () { + MatteJelly() + : Filter(){}; + ~MatteJelly() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } + + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -153,13 +172,12 @@ public: "\n", new MatteJelly()); // clang-format on }; - }; -gchar const * -MatteJelly::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *MatteJelly::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream smooth; std::ostringstream bright; @@ -178,26 +196,32 @@ MatteJelly::get_filter_text (Inkscape::Extension::Extension * ext) r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; - - _filter = g_strdup_printf( - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n", smooth.str().c_str(), bright.str().c_str(), r.str().c_str(), g.str().c_str(), b.str().c_str(), elevation.str().c_str(), azimuth.str().c_str(), a.str().c_str()); + + _filter = + g_strdup_printf("\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n", + smooth.str().c_str(), bright.str().c_str(), r.str().c_str(), g.str().c_str(), b.str().c_str(), + elevation.str().c_str(), azimuth.str().c_str(), a.str().c_str()); return _filter; }; /* MatteJelly filter */ /** \brief Custom predefined Specular light filter. - + Basic specular bevel to use for building textures Filter's parameters: @@ -208,15 +232,23 @@ MatteJelly::get_filter_text (Inkscape::Extension::Extension * ext) * Lighting color (guint, default -1 [white]) -> specular (lighting-color) */ -class SpecularLight : public Inkscape::Extension::Internal::Filter::Filter { +class SpecularLight : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - SpecularLight ( ) : Filter() { }; - ~SpecularLight ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } - - static void init () { + SpecularLight() + : Filter(){}; + ~SpecularLight() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } + + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -239,13 +271,12 @@ public: "\n", new SpecularLight()); // clang-format on }; - }; -gchar const * -SpecularLight::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *SpecularLight::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream smooth; std::ostringstream bright; @@ -264,18 +295,23 @@ SpecularLight::get_filter_text (Inkscape::Extension::Extension * ext) r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; - - _filter = g_strdup_printf( - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n", smooth.str().c_str(), bright.str().c_str(), r.str().c_str(), g.str().c_str(), b.str().c_str(), elevation.str().c_str(), azimuth.str().c_str(), a.str().c_str()); + + _filter = + g_strdup_printf("\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n", + smooth.str().c_str(), bright.str().c_str(), r.str().c_str(), g.str().c_str(), b.str().c_str(), + elevation.str().c_str(), azimuth.str().c_str(), a.str().c_str()); return _filter; }; /* SpecularLight filter */ diff --git a/src/extension/internal/filter/blurs.h b/src/extension/internal/filter/blurs.h index 85f99fdacf726abeb72f175b7777fac870ce356a..3bb27ed922b586ca31d068287f5e9cc0ebf941d2 100644 --- a/src/extension/internal/filter/blurs.h +++ b/src/extension/internal/filter/blurs.h @@ -19,11 +19,10 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { @@ -32,24 +31,32 @@ namespace Filter { /** \brief Custom predefined Blur filter. - + Simple horizontal and vertical blur Filter's parameters: * Horizontal blur (0.01->100., default 2) -> blur (stdDeviation) * Vertical blur (0.01->100., default 2) -> blur (stdDeviation) - * Blur content only (boolean, default false) -> + * Blur content only (boolean, default false) -> */ -class Blur : public Inkscape::Extension::Internal::Filter::Filter { +class Blur : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Blur ( ) : Filter() { }; - ~Blur ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Blur() + : Filter(){}; + ~Blur() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -70,13 +77,12 @@ public: "\n", new Blur()); // clang-format on }; - }; -gchar const * -Blur::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Blur::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream bbox; std::ostringstream hblur; @@ -91,11 +97,10 @@ Blur::get_filter_text (Inkscape::Extension::Extension * ext) content << "\n" << "\n"; } else { - bbox << "" ; - content << "" ; + bbox << ""; + content << ""; } - // clang-format off _filter = g_strdup_printf( "\n" @@ -109,22 +114,30 @@ Blur::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Clean edges filter. - + Removes or decreases glows and jaggeries around objects edges after applying some filters Filter's parameters: * Strength (0.01->2., default 0.4) -> blur (stdDeviation) */ -class CleanEdges : public Inkscape::Extension::Internal::Filter::Filter { +class CleanEdges : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - CleanEdges ( ) : Filter() { }; - ~CleanEdges ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + CleanEdges() + : Filter(){}; + ~CleanEdges() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -143,13 +156,12 @@ public: "\n", new CleanEdges()); // clang-format on }; - }; -gchar const * -CleanEdges::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *CleanEdges::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream blur; @@ -169,7 +181,7 @@ CleanEdges::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Cross blur filter. - + Combine vertical and horizontal blur Filter's parameters: @@ -180,15 +192,23 @@ CleanEdges::get_filter_text (Inkscape::Extension::Extension * ext) * Blend mode (enum, default Darken) -> blend (mode) */ -class CrossBlur : public Inkscape::Extension::Internal::Filter::Filter { +class CrossBlur : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - CrossBlur ( ) : Filter() { }; - ~CrossBlur ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + CrossBlur() + : Filter(){}; + ~CrossBlur() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -216,13 +236,12 @@ public: "\n", new CrossBlur()); // clang-format on }; - }; -gchar const * -CrossBlur::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *CrossBlur::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream bright; std::ostringstream fade; @@ -235,7 +254,7 @@ CrossBlur::get_filter_text (Inkscape::Extension::Extension * ext) hblur << ext->get_param_float("hblur"); vblur << ext->get_param_float("vblur"); blend << ext->get_param_optiongroup("blend"); - + // clang-format off _filter = g_strdup_printf( "\n" @@ -252,22 +271,30 @@ CrossBlur::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Feather filter. - + Blurred mask on the edge without altering the contents Filter's parameters: * Strength (0.01->100., default 5) -> blur (stdDeviation) */ -class Feather : public Inkscape::Extension::Internal::Filter::Filter { +class Feather : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Feather ( ) : Filter() { }; - ~Feather ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Feather() + : Filter(){}; + ~Feather() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -286,13 +313,12 @@ public: "\n", new Feather()); // clang-format on }; - }; -gchar const * -Feather::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Feather::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream blur; @@ -313,7 +339,7 @@ Feather::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Out of Focus filter. - + Blur eroded by white or transparency Filter's parameters: @@ -328,15 +354,23 @@ Feather::get_filter_text (Inkscape::Extension::Extension * ext) */ -class ImageBlur : public Inkscape::Extension::Internal::Filter::Filter { +class ImageBlur : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - ImageBlur ( ) : Filter() { }; - ~ImageBlur ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + ImageBlur() + : Filter(){}; + ~ImageBlur() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -374,13 +408,12 @@ public: "\n", new ImageBlur()); // clang-format on }; - }; -gchar const * -ImageBlur::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *ImageBlur::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream hblur; std::ostringstream vblur; @@ -403,14 +436,14 @@ ImageBlur::get_filter_text (Inkscape::Extension::Extension * ext) guint32 color = ext->get_param_color("color"); r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; blend << ext->get_param_optiongroup("blend"); if (ext->get_param_bool("background")) { - background << "BackgroundImage" ; + background << "BackgroundImage"; } else { - background << "flood" ; + background << "flood"; } // clang-format off diff --git a/src/extension/internal/filter/bumps.h b/src/extension/internal/filter/bumps.h index 7bb0338c62742d834a800da89edb188dd473a0c9..be1e04777194d1d643effe8c7bc68788fb41ef04 100644 --- a/src/extension/internal/filter/bumps.h +++ b/src/extension/internal/filter/bumps.h @@ -16,11 +16,10 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { @@ -29,7 +28,7 @@ namespace Filter { /** \brief Custom predefined Bump filter. - + All purpose bump filter Filter's parameters: @@ -40,11 +39,12 @@ namespace Filter { * Red (-50.->50., default 0.) -> colormatrix1 (values) * Green (-50.->50., default 0.) -> colormatrix1 (values) * Blue (-50.->50., default 0.) -> colormatrix1 (values) - * Bump from background (boolean, default false) -> colormatrix1 (false: in="SourceGraphic", true: in="BackgroundImage") - Lighting + * Bump from background (boolean, default false) -> colormatrix1 (false: in="SourceGraphic", true: + in="BackgroundImage") Lighting * Lighting type (enum, default specular) -> lighting block * Height (0.->50., default 5.) -> lighting (surfaceScale) - * Lightness (0.->5., default 1.) -> lighting [diffuselighting (diffuseConstant)|specularlighting (specularConstant)] + * Lightness (0.->5., default 1.) -> lighting [diffuselighting (diffuseConstant)|specularlighting + (specularConstant)] * Precision (1->128, default 15) -> lighting (specularExponent) * Color (guint, default -1 (RGB:255,255,255))-> lighting (lighting-color) Light source @@ -67,15 +67,23 @@ namespace Filter { * Color bump (boolean, default false) -> composite2 (false: in="diffuselighting", true in="flood") */ -class Bump : public Inkscape::Extension::Internal::Filter::Filter { +class Bump : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Bump ( ) : Filter() { }; - ~Bump ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Bump() + : Filter(){}; + ~Bump() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -149,13 +157,12 @@ public: "\n", new Bump()); // clang-format on }; - }; -gchar const * -Bump::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Bump::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream simplifyImage; std::ostringstream simplifyBump; @@ -165,18 +172,17 @@ Bump::get_filter_text (Inkscape::Extension::Extension * ext) std::ostringstream crop; std::ostringstream bumpSource; std::ostringstream blend; - + std::ostringstream lightStart; std::ostringstream lightOptions; std::ostringstream lightEnd; - + std::ostringstream floodRed; std::ostringstream floodGreen; std::ostringstream floodBlue; std::ostringstream floodAlpha; std::ostringstream colorize; - simplifyImage << ext->get_param_float("simplifyImage"); simplifyBump << ext->get_param_float("simplifyBump"); red << ext->get_param_float("red"); @@ -184,28 +190,28 @@ Bump::get_filter_text (Inkscape::Extension::Extension * ext) blue << ext->get_param_float("blue"); crop << ext->get_param_float("crop"); blend << ext->get_param_optiongroup("blend"); - + guint32 lightingColor = ext->get_param_color("lightingColor"); guint32 imageColor = ext->get_param_color("imageColor"); - + if (ext->get_param_bool("background")) { - bumpSource << "BackgroundImage" ; + bumpSource << "BackgroundImage"; } else { - bumpSource << "blur1" ; + bumpSource << "blur1"; } const gchar *lightType = ext->get_param_optiongroup("lightType"); if ((g_ascii_strcasecmp("specular", lightType) == 0)) { - // Specular + // Specular lightStart << "> 24) & 0xff) << "," - << ((lightingColor >> 16) & 0xff) << "," << ((lightingColor >> 8) & 0xff) << ")\" surfaceScale=\"" + << ((lightingColor >> 16) & 0xff) << "," << ((lightingColor >> 8) & 0xff) << ")\" surfaceScale=\"" << ext->get_param_float("height") << "\" specularConstant=\"" << ext->get_param_float("lightness") << "\" specularExponent=\"" << ext->get_param_int("precision") << "\" result=\"lighting\">"; lightEnd << ""; } else { - // Diffuse + // Diffuse lightStart << "> 24) & 0xff) << "," - << ((lightingColor >> 16) & 0xff) << "," << ((lightingColor >> 8) & 0xff) << ")\" surfaceScale=\"" + << ((lightingColor >> 16) & 0xff) << "," << ((lightingColor >> 8) & 0xff) << ")\" surfaceScale=\"" << ext->get_param_float("height") << "\" diffuseConstant=\"" << ext->get_param_float("lightness") << "\" result=\"lighting\">"; lightEnd << ""; @@ -213,34 +219,33 @@ Bump::get_filter_text (Inkscape::Extension::Extension * ext) const gchar *lightSource = ext->get_param_optiongroup("lightSource"); if ((g_ascii_strcasecmp("distant", lightSource) == 0)) { - // Distant + // Distant lightOptions << "get_param_int("distantAzimuth") << "\" elevation=\"" << ext->get_param_int("distantElevation") << "\" />"; } else if ((g_ascii_strcasecmp("point", lightSource) == 0)) { - // Point - lightOptions << "get_param_int("pointX") << "\" y=\"" << ext->get_param_int("pointY") - << "\" x=\"" << ext->get_param_int("pointZ") << "\" />"; + // Point + lightOptions << "get_param_int("pointX") << "\" y=\"" + << ext->get_param_int("pointY") << "\" x=\"" << ext->get_param_int("pointZ") << "\" />"; } else { - // Spot - lightOptions << "get_param_int("pointX") << "\" y=\"" << ext->get_param_int("pointY") - << "\" z=\"" << ext->get_param_int("pointZ") << "\" pointsAtX=\"" << ext->get_param_int("spotAtX") - << "\" pointsAtY=\"" << ext->get_param_int("spotAtY") << "\" pointsAtZ=\"" << ext->get_param_int("spotAtZ") - << "\" specularExponent=\"" << ext->get_param_int("spotExponent") - << "\" limitingConeAngle=\"" << ext->get_param_int("spotConeAngle") - << "\" />"; + // Spot + lightOptions << "get_param_int("pointX") << "\" y=\"" << ext->get_param_int("pointY") + << "\" z=\"" << ext->get_param_int("pointZ") << "\" pointsAtX=\"" << ext->get_param_int("spotAtX") + << "\" pointsAtY=\"" << ext->get_param_int("spotAtY") << "\" pointsAtZ=\"" + << ext->get_param_int("spotAtZ") << "\" specularExponent=\"" << ext->get_param_int("spotExponent") + << "\" limitingConeAngle=\"" << ext->get_param_int("spotConeAngle") << "\" />"; } floodRed << ((imageColor >> 24) & 0xff); floodGreen << ((imageColor >> 16) & 0xff); - floodBlue << ((imageColor >> 8) & 0xff); + floodBlue << ((imageColor >> 8) & 0xff); floodAlpha << (imageColor & 0xff) / 255.0F; - + if (ext->get_param_bool("colorize")) { - colorize << "flood" ; + colorize << "flood"; } else { - colorize << "blur1" ; + colorize << "blur1"; } - + // clang-format off _filter = g_strdup_printf( "\n" @@ -269,9 +274,9 @@ Bump::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Wax Bump filter. - + Turns an image to jelly - + Filter's parameters: Options * Image simplification (0.01->10., default 1.5) -> blur1 (stdDeviation) @@ -288,7 +293,8 @@ Bump::get_filter_text (Inkscape::Extension::Extension * ext) Lighting (specular, distant light) * Color (guint, default -1 (RGB:255,255,255))-> lighting (lighting-color) * Height (-50.->50., default 5.) -> lighting (surfaceScale) - * Lightness (0.->10., default 1.4) -> lighting [diffuselighting (diffuseConstant)|specularlighting (specularConstant)] + * Lightness (0.->10., default 1.4) -> lighting [diffuselighting (diffuseConstant)|specularlighting + (specularConstant)] * Precision (0->50, default 35) -> lighting (specularExponent) * Azimuth (0->360, default 225) -> lightsOptions (distantAzimuth) * Elevation (0->180, default 60) -> lightsOptions (distantElevation) @@ -300,15 +306,23 @@ Bump::get_filter_text (Inkscape::Extension::Extension * ext) * Revert bump (boolean, default false) -> composite1 (false: operator="out", true operator="in") */ -class WaxBump : public Inkscape::Extension::Internal::Filter::Filter { +class WaxBump : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - WaxBump ( ) : Filter() { }; - ~WaxBump ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + WaxBump() + : Filter(){}; + ~WaxBump() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -373,13 +387,12 @@ public: "\n", new WaxBump()); // clang-format on }; - }; -gchar const * -WaxBump::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *WaxBump::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream simplifyImage; std::ostringstream simplifyBump; @@ -391,13 +404,13 @@ WaxBump::get_filter_text (Inkscape::Extension::Extension * ext) std::ostringstream background; std::ostringstream bgopacity; - + std::ostringstream height; std::ostringstream lightness; std::ostringstream precision; std::ostringstream distantAzimuth; std::ostringstream distantElevation; - + std::ostringstream lightRed; std::ostringstream lightGreen; std::ostringstream lightBlue; @@ -432,18 +445,18 @@ WaxBump::get_filter_text (Inkscape::Extension::Extension * ext) guint32 lightingColor = ext->get_param_color("lightingColor"); lightRed << ((lightingColor >> 24) & 0xff); lightGreen << ((lightingColor >> 16) & 0xff); - lightBlue << ((lightingColor >> 8) & 0xff); + lightBlue << ((lightingColor >> 8) & 0xff); guint32 imageColor = ext->get_param_color("imageColor"); floodRed << ((imageColor >> 24) & 0xff); floodGreen << ((imageColor >> 16) & 0xff); - floodBlue << ((imageColor >> 8) & 0xff); + floodBlue << ((imageColor >> 8) & 0xff); floodAlpha << (imageColor & 0xff) / 255.0F; - + if (ext->get_param_bool("revert")) { - revert << "in" ; + revert << "in"; } else { - revert << "out" ; + revert << "out"; } lightingblend << ext->get_param_optiongroup("lightingblend"); diff --git a/src/extension/internal/filter/color.h b/src/extension/internal/filter/color.h index 57adeaa54442062266212a6ff7da3a67f14c3b60..17f33e5dda3a6b6241f6f69a6a55f743f522652d 100644 --- a/src/extension/internal/filter/color.h +++ b/src/extension/internal/filter/color.h @@ -33,11 +33,10 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { @@ -46,7 +45,7 @@ namespace Filter { /** \brief Custom predefined Brilliance filter. - + Brilliance filter. Filter's parameters: @@ -54,22 +53,30 @@ namespace Filter { * Over-saturation (0.->10., default 0.5) -> colorMatrix (6 other entries) * Lightness (-10.->10., default 0.) -> colorMatrix (last column) * Inverted (boolean, default false) -> colorMatrix - + Matrix: St Vi Vi 0 Li Vi St Vi 0 Li Vi Vi St 0 Li 0 0 0 1 0 */ -class Brilliance : public Inkscape::Extension::Internal::Filter::Filter { +class Brilliance : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Brilliance ( ) : Filter() { }; - ~Brilliance ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Brilliance() + : Filter(){}; + ~Brilliance() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -93,10 +100,10 @@ public: }; }; -gchar const * -Brilliance::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Brilliance::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream brightness; std::ostringstream sat; @@ -127,7 +134,7 @@ Brilliance::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Channel Painting filter. - + Channel Painting filter. Filter's parameters: @@ -138,22 +145,30 @@ Brilliance::get_filter_text (Inkscape::Extension::Extension * ext) * Alpha (-10.->10., default 1.) -> colormatrix2 (values) * Flood colors (guint, default 16777215) -> flood (flood-opacity, flood-color) * Inverted (boolean, default false) -> composite1 (operator, true='in', false='out') - + Matrix: 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 R G B A 0 */ -class ChannelPaint : public Inkscape::Extension::Internal::Filter::Filter { +class ChannelPaint : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - ChannelPaint ( ) : Filter() { }; - ~ChannelPaint ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } - - static void init () { + ChannelPaint() + : Filter(){}; + ~ChannelPaint() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } + + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -186,10 +201,10 @@ public: }; }; -gchar const * -ChannelPaint::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *ChannelPaint::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream saturation; std::ostringstream red; @@ -211,7 +226,7 @@ ChannelPaint::get_filter_text (Inkscape::Extension::Extension * ext) guint32 color = ext->get_param_color("color"); floodRed << ((color >> 24) & 0xff); floodGreen << ((color >> 16) & 0xff); - floodBlue << ((color >> 8) & 0xff); + floodBlue << ((color >> 8) & 0xff); floodAlpha << (color & 0xff) / 255.0F; if (ext->get_param_bool("invert")) { @@ -219,7 +234,7 @@ ChannelPaint::get_filter_text (Inkscape::Extension::Extension * ext) } else { invert << "out"; } - + // clang-format off _filter = g_strdup_printf( "\n" @@ -246,19 +261,27 @@ ChannelPaint::get_filter_text (Inkscape::Extension::Extension * ext) Color Blindness filter. Based on https://openclipart.org/detail/22299/Color%20Blindness%20filters - + Filter's parameters: * Blindness type (enum, default Achromatomaly) -> colormatrix */ -class ColorBlindness : public Inkscape::Extension::Internal::Filter::Filter { +class ColorBlindness : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - ColorBlindness ( ) : Filter() { }; - ~ColorBlindness ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } - - static void init () { + ColorBlindness() + : Filter(){}; + ~ColorBlindness() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } + + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -301,10 +324,10 @@ public: }; }; -gchar const * -ColorBlindness::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *ColorBlindness::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream type; type << ext->get_param_optiongroup("type"); @@ -321,7 +344,7 @@ ColorBlindness::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Color shift filter. - + Rotate and desaturate hue Filter's parameters: @@ -329,15 +352,23 @@ ColorBlindness::get_filter_text (Inkscape::Extension::Extension * ext) * Saturation (0.->1., default 0.6) -> color2 (values) */ -class ColorShift : public Inkscape::Extension::Internal::Filter::Filter { +class ColorShift : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - ColorShift ( ) : Filter() { }; - ~ColorShift ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + ColorShift() + : Filter(){}; + ~ColorShift() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -357,13 +388,12 @@ public: "\n", new ColorShift()); // clang-format on }; - }; -gchar const * -ColorShift::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *ColorShift::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream shift; std::ostringstream sat; @@ -384,7 +414,7 @@ ColorShift::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Colorize filter. - + Blend image or object with a flood color. Filter's parameters: @@ -396,15 +426,23 @@ ColorShift::get_filter_text (Inkscape::Extension::Extension * ext) * Blend mode 2 (enum, default Screen) -> blend2 (mode) */ -class Colorize : public Inkscape::Extension::Internal::Filter::Filter { +class Colorize : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Colorize ( ) : Filter() { }; - ~Colorize ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Colorize() + : Filter(){}; + ~Colorize() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -446,13 +484,12 @@ public: "\n", new Colorize()); // clang-format on }; - }; -gchar const * -Colorize::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Colorize::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream a; std::ostringstream r; @@ -467,7 +504,7 @@ Colorize::get_filter_text (Inkscape::Extension::Extension * ext) guint32 color = ext->get_param_color("color"); r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; hlight << ext->get_param_float("hlight"); @@ -479,7 +516,7 @@ Colorize::get_filter_text (Inkscape::Extension::Extension * ext) } else { duotone << "1"; } - + // clang-format off _filter = g_strdup_printf( "\n" @@ -500,22 +537,30 @@ Colorize::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined ComponentTransfer filter. - + Basic component transfer structure. Filter's parameters: * Type (enum, default identity) -> component function */ -class ComponentTransfer : public Inkscape::Extension::Internal::Filter::Filter { +class ComponentTransfer : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - ComponentTransfer ( ) : Filter() { }; - ~ComponentTransfer ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + ComponentTransfer() + : Filter(){}; + ~ComponentTransfer() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -542,35 +587,35 @@ public: }; }; -gchar const * -ComponentTransfer::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *ComponentTransfer::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream CTfunction; const gchar *type = ext->get_param_optiongroup("type"); if ((g_ascii_strcasecmp("identity", type) == 0)) { CTfunction << "\n" - << "\n" - << "\n" - << "\n"; + << "\n" + << "\n" + << "\n"; } else if ((g_ascii_strcasecmp("table", type) == 0)) { CTfunction << "\n" - << "\n" - << "\n"; + << "\n" + << "\n"; } else if ((g_ascii_strcasecmp("discrete", type) == 0)) { CTfunction << "\n" - << "\n" - << "\n"; + << "\n" + << "\n"; } else if ((g_ascii_strcasecmp("linear", type) == 0)) { CTfunction << "\n" - << "\n" - << "\n"; - } else { //Gamma + << "\n" + << "\n"; + } else { // Gamma CTfunction << "\n" - << "\n" - << "\n"; + << "\n" + << "\n"; } // clang-format off _filter = g_strdup_printf( @@ -586,7 +631,7 @@ ComponentTransfer::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Duochrome filter. - + Convert luminance values to a duochrome palette. Filter's parameters: @@ -596,15 +641,23 @@ ComponentTransfer::get_filter_text (Inkscape::Extension::Extension * ext) * Color 2 (guint, default -65281) -> flood2 (flood-opacity, flood-color) */ -class Duochrome : public Inkscape::Extension::Internal::Filter::Filter { +class Duochrome : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Duochrome ( ) : Filter() { }; - ~Duochrome ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Duochrome() + : Filter(){}; + ~Duochrome() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -639,13 +692,12 @@ public: "\n", new Duochrome()); // clang-format on }; - }; -gchar const * -Duochrome::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Duochrome::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream a1; std::ostringstream r1; @@ -665,10 +717,10 @@ Duochrome::get_filter_text (Inkscape::Extension::Extension * ext) r1 << ((color1 >> 24) & 0xff); g1 << ((color1 >> 16) & 0xff); - b1 << ((color1 >> 8) & 0xff); + b1 << ((color1 >> 8) & 0xff); r2 << ((color2 >> 24) & 0xff); g2 << ((color2 >> 16) & 0xff); - b2 << ((color2 >> 8) & 0xff); + b2 << ((color2 >> 8) & 0xff); fluo << fluorescence; if ((g_ascii_strcasecmp("full", swaptype) == 0)) { @@ -716,7 +768,7 @@ Duochrome::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Extract Channel filter. - + Extract color channel as a transparent image. Filter's parameters: @@ -725,15 +777,23 @@ Duochrome::get_filter_text (Inkscape::Extension::Extension * ext) * Channel to alpha (boolean, default false) -> colormatrix (values) */ -class ExtractChannel : public Inkscape::Extension::Internal::Filter::Filter { +class ExtractChannel : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - ExtractChannel ( ) : Filter() { }; - ~ExtractChannel ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + ExtractChannel() + : Filter(){}; + ~ExtractChannel() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -767,10 +827,10 @@ public: }; }; -gchar const * -ExtractChannel::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *ExtractChannel::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream blend; std::ostringstream colors; @@ -821,13 +881,13 @@ ExtractChannel::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Fade to Black or White filter. - + Fade to black or white. Filter's parameters: * Level (0.->1., default 1.) -> colorMatrix (RVB entries) * Fade to (enum [black|white], default black) -> colorMatrix (RVB entries) - + Matrix black white Lv 0 0 0 0 Lv 0 0 1-lv 0 @@ -835,15 +895,23 @@ ExtractChannel::get_filter_text (Inkscape::Extension::Extension * ext) 0 0 Lv 0 0 0 0 Lv 1-lv 0 0 0 0 1 0 0 0 0 1 0 */ -class FadeToBW : public Inkscape::Extension::Internal::Filter::Filter { +class FadeToBW : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - FadeToBW ( ) : Filter() { }; - ~FadeToBW ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + FadeToBW() + : Filter(){}; + ~FadeToBW() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -868,10 +936,10 @@ public: }; }; -gchar const * -FadeToBW::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *FadeToBW::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream level; std::ostringstream wlevel; @@ -880,10 +948,10 @@ FadeToBW::get_filter_text (Inkscape::Extension::Extension * ext) const gchar *fadeto = ext->get_param_optiongroup("fadeto"); if ((g_ascii_strcasecmp("white", fadeto) == 0)) { - // White + // White wlevel << (1 - ext->get_param_float("level")); } else { - // Black + // Black wlevel << "0"; } @@ -901,7 +969,7 @@ FadeToBW::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Greyscale filter. - + Customize greyscale components. Filter's parameters: @@ -910,23 +978,31 @@ FadeToBW::get_filter_text (Inkscape::Extension::Extension * ext) * Blue (-10.->10., default .072) -> colorMatrix (values) * Lightness (-10.->10., default 0.) -> colorMatrix (values) * Transparent (boolean, default false) -> matrix structure - + Matrix: normal transparency R G B St 0 0 0 0 0 0 R G B St 0 0 0 0 0 0 - R G B St 0 0 0 0 0 0 + R G B St 0 0 0 0 0 0 0 0 0 1 0 R G B 1-St 0 */ -class Greyscale : public Inkscape::Extension::Internal::Filter::Filter { +class Greyscale : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Greyscale ( ) : Filter() { }; - ~Greyscale ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Greyscale() + : Filter(){}; + ~Greyscale() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -951,10 +1027,10 @@ public: }; }; -gchar const * -Greyscale::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Greyscale::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream red; std::ostringstream green; @@ -966,25 +1042,27 @@ Greyscale::get_filter_text (Inkscape::Extension::Extension * ext) std::ostringstream strengtht; std::ostringstream transparency; std::ostringstream line; - + red << ext->get_param_float("red"); green << ext->get_param_float("green"); blue << ext->get_param_float("blue"); strength << ext->get_param_float("strength"); - - redt << - ext->get_param_float("red"); - greent << - ext->get_param_float("green"); - bluet << - ext->get_param_float("blue"); + + redt << -ext->get_param_float("red"); + greent << -ext->get_param_float("green"); + bluet << -ext->get_param_float("blue"); strengtht << 1 - ext->get_param_float("strength"); if (ext->get_param_bool("transparent")) { line << "0 0 0 0"; - transparency << redt.str().c_str() << " " << greent.str().c_str() << " " << bluet.str().c_str() << " " << strengtht.str().c_str(); + transparency << redt.str().c_str() << " " << greent.str().c_str() << " " << bluet.str().c_str() << " " + << strengtht.str().c_str(); } else { - line << red.str().c_str() << " " << green.str().c_str() << " " << blue.str().c_str() << " " << strength.str().c_str(); + line << red.str().c_str() << " " << green.str().c_str() << " " << blue.str().c_str() << " " + << strength.str().c_str(); transparency << "0 0 0 1"; } - + // clang-format off _filter = g_strdup_printf( "\n" @@ -997,27 +1075,36 @@ Greyscale::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Invert filter. - + Manage hue, lightness and transparency inversions Filter's parameters: * Invert hue (boolean, default false) -> color1 (values, true: 180, false: 0) * Invert lightness (boolean, default false) -> color1 (values, true: 180, false: 0; XOR with Invert hue), - color2 (values: from a00 to a22, if 1, set -1 and set 1 in ax4, if -1, set 1 and set 0 in ax4) + color2 (values: from a00 to a22, if 1, set -1 and set 1 in ax4, if + -1, set 1 and set 0 in ax4) * Invert transparency (boolean, default false) -> color2 (values: negate a30, a31 and a32, substract 1 from a33) * Invert channels (enum, default Red and blue) -> color2 (values -for R&B: swap ax0 and ax2 in the first 3 lines) * Light transparency (0.->1., default 0.) -> color2 (values: a33=a33-x) */ -class Invert : public Inkscape::Extension::Internal::Filter::Filter { +class Invert : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Invert ( ) : Filter() { }; - ~Invert ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Invert() + : Filter(){}; + ~Invert() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -1045,13 +1132,12 @@ public: "\n", new Invert()); // clang-format on }; - }; -gchar const * -Invert::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Invert::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream line1; std::ostringstream line2; @@ -1066,13 +1152,13 @@ Invert::get_filter_text (Inkscape::Extension::Extension * ext) } else { hue << ""; } - + if (ext->get_param_bool("transparency")) { transparency << "0.21 0.72 0.07 " << 1 - ext->get_param_float("opacify"); } else { - transparency << "-0.21 -0.72 -0.07 " << 2 - ext->get_param_float("opacify"); + transparency << "-0.21 -0.72 -0.07 " << 2 - ext->get_param_float("opacify"); } - + if (ext->get_param_bool("lightness")) { switch (atoi(ext->get_param_optiongroup("channels"))) { case 1: @@ -1140,7 +1226,7 @@ Invert::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Lighting filter. - + Modify lights and shadows separately. Filter's parameters: @@ -1148,15 +1234,23 @@ Invert::get_filter_text (Inkscape::Extension::Extension * ext) * Shadow (0.->20., default 1.) -> component (exponent) * Offset (-1.->1., default 0.) -> component (offset) */ -class Lighting : public Inkscape::Extension::Internal::Filter::Filter { +class Lighting : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Lighting ( ) : Filter() { }; - ~Lighting ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Lighting() + : Filter(){}; + ~Lighting() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -1179,10 +1273,10 @@ public: }; }; -gchar const * -Lighting::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Lighting::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream amplitude; std::ostringstream exponent; @@ -1210,28 +1304,36 @@ Lighting::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Lightness-Contrast filter. - + Modify lightness and contrast separately. Filter's parameters: * Lightness (0.->100., default 0.) -> colorMatrix * Contrast (0.->100., default 0.) -> colorMatrix - + Matrix: Co/10 0 0 1+(Co-1)*Li/2000 -(Co-1)/20 0 Co/10 0 1+(Co-1)*Li/2000 -(Co-1)/20 0 0 Co/10 1+(Co-1)*Li/2000 -(Co-1)/20 0 0 0 1 0 */ -class LightnessContrast : public Inkscape::Extension::Internal::Filter::Filter { +class LightnessContrast : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - LightnessContrast ( ) : Filter() { }; - ~LightnessContrast ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + LightnessContrast() + : Filter(){}; + ~LightnessContrast() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -1253,10 +1355,10 @@ public: }; }; -gchar const * -LightnessContrast::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *LightnessContrast::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream lightness; std::ostringstream contrast; @@ -1265,11 +1367,11 @@ LightnessContrast::get_filter_text (Inkscape::Extension::Extension * ext) gfloat c5; if (ext->get_param_float("contrast") > 0) { contrast << (1 + ext->get_param_float("contrast") / 10); - c5 = (- ext->get_param_float("contrast") / 20); + c5 = (-ext->get_param_float("contrast") / 20); } else { contrast << (1 + ext->get_param_float("contrast") / 100); - c5 =(- ext->get_param_float("contrast") / 200); - } + c5 = (-ext->get_param_float("contrast") / 200); + } contrast5 << c5; lightness << ((1 - c5) * ext->get_param_float("lightness") / 100); @@ -1288,7 +1390,7 @@ LightnessContrast::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Nudge RGB filter. - + Nudge RGB channels separately and blend them to different types of backgrounds Filter's parameters: @@ -1306,15 +1408,23 @@ LightnessContrast::get_filter_text (Inkscape::Extension::Extension * ext) * Background color (guint, default 255)-> flood (flood-color, flood-opacity) */ -class NudgeRGB : public Inkscape::Extension::Internal::Filter::Filter { +class NudgeRGB : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - NudgeRGB ( ) : Filter() { }; - ~NudgeRGB ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + NudgeRGB() + : Filter(){}; + ~NudgeRGB() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -1350,10 +1460,10 @@ public: }; }; -gchar const * -NudgeRGB::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *NudgeRGB::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream rx; std::ostringstream ry; @@ -1377,9 +1487,9 @@ NudgeRGB::get_filter_text (Inkscape::Extension::Extension * ext) guint32 color = ext->get_param_color("color"); r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; - + // clang-format off _filter = g_strdup_printf( "\n" @@ -1405,7 +1515,7 @@ NudgeRGB::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Nudge CMY filter. - + Nudge CMY channels separately and blend them to different types of backgrounds Filter's parameters: @@ -1422,15 +1532,23 @@ NudgeRGB::get_filter_text (Inkscape::Extension::Extension * ext) Color * Background color (guint, default -1)-> flood (flood-color, flood-opacity) */ -class NudgeCMY : public Inkscape::Extension::Internal::Filter::Filter { +class NudgeCMY : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - NudgeCMY ( ) : Filter() { }; - ~NudgeCMY ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + NudgeCMY() + : Filter(){}; + ~NudgeCMY() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -1466,10 +1584,10 @@ public: }; }; -gchar const * -NudgeCMY::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *NudgeCMY::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream cx; std::ostringstream cy; @@ -1493,9 +1611,9 @@ NudgeCMY::get_filter_text (Inkscape::Extension::Extension * ext) guint32 color = ext->get_param_color("color"); r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; - + // clang-format off _filter = g_strdup_printf( "\n" @@ -1521,7 +1639,7 @@ NudgeCMY::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Quadritone filter. - + Replace hue by two colors. Filter's parameters: @@ -1532,15 +1650,23 @@ NudgeCMY::get_filter_text (Inkscape::Extension::Extension * ext) * Blend mode 2 (enum, default Normal) -> blend2 (mode) */ -class Quadritone : public Inkscape::Extension::Internal::Filter::Filter { +class Quadritone : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Quadritone ( ) : Filter() { }; - ~Quadritone ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Quadritone() + : Filter(){}; + ~Quadritone() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -1573,13 +1699,12 @@ public: "\n", new Quadritone()); // clang-format on }; - }; -gchar const * -Quadritone::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Quadritone::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream dist; std::ostringstream colors; @@ -1609,25 +1734,32 @@ Quadritone::get_filter_text (Inkscape::Extension::Extension * ext) return _filter; }; /* Quadritone filter */ - /** \brief Custom predefined Simple blend filter. - + Simple blend filter. Filter's parameters: * Color (guint, default 16777215) -> flood1 (flood-opacity, flood-color) * Blend mode (enum, default Hue) -> blend1 (mode) */ -class SimpleBlend : public Inkscape::Extension::Internal::Filter::Filter { +class SimpleBlend : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - SimpleBlend ( ) : Filter() { }; - ~SimpleBlend ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } - - static void init () { + SimpleBlend() + : Filter(){}; + ~SimpleBlend() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } + + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -1665,10 +1797,10 @@ public: }; }; -gchar const * -SimpleBlend::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *SimpleBlend::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream a; std::ostringstream r; @@ -1679,7 +1811,7 @@ SimpleBlend::get_filter_text (Inkscape::Extension::Extension * ext) guint32 color = ext->get_param_color("color"); r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; blend << ext->get_param_optiongroup("blendmode"); @@ -1698,7 +1830,7 @@ SimpleBlend::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Solarize filter. - + Classic photographic solarization effect. Filter's parameters: @@ -1708,16 +1840,23 @@ SimpleBlend::get_filter_text (Inkscape::Extension::Extension * ext) * Hue rotation (0->360, default 0) -> colormatrix1 (values) */ - -class Solarize : public Inkscape::Extension::Internal::Filter::Filter { +class Solarize : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Solarize ( ) : Filter() { }; - ~Solarize ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Solarize() + : Filter(){}; + ~Solarize() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -1740,13 +1879,12 @@ public: "\n", new Solarize()); // clang-format on }; - }; -gchar const * -Solarize::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Solarize::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream rotate; std::ostringstream blend1; @@ -1755,11 +1893,11 @@ Solarize::get_filter_text (Inkscape::Extension::Extension * ext) rotate << ext->get_param_int("rotate"); const gchar *type = ext->get_param_optiongroup("type"); if ((g_ascii_strcasecmp("solarize", type) == 0)) { - // Solarize + // Solarize blend1 << "darken"; blend2 << "screen"; } else { - // Moonarize + // Moonarize blend1 << "lighten"; blend2 << "multiply"; } @@ -1781,7 +1919,7 @@ Solarize::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Tritone filter. - + Create a custom tritone palette with additional glow, blend modes and hue moving. Filter's parameters: @@ -1790,7 +1928,8 @@ Solarize::get_filter_text (Inkscape::Extension::Extension * ext) Enhance hue = Normal + composite2 (in="SourceGraphic") Phosphorescence = Normal + blend6 (in2="SourceGraphic") composite2 (in="blend6", in2="composite1") PhosphorescenceB = Normal + blend6 (in2="flood") composite1 (in2="SourceGraphic") - Hue to background = Normal + composite1 (in2="BackgroundImage") [a template with an activated background is needed, or colors become black] + Hue to background = Normal + composite1 (in2="BackgroundImage") [a template with an activated background is + needed, or colors become black] * Hue distribution (0->360, default 0) -> colormatrix1 (values) * Colors (guint, default -73203457) -> flood (flood-opacity, flood-color) * Global blend (enum, default Lighten) -> blend5 (mode) [Multiply, Screen, Darken, Lighten only!] @@ -1800,15 +1939,23 @@ Solarize::get_filter_text (Inkscape::Extension::Extension * ext) * Global light (0.->10., default 1) -> composite2 (k3) [k2 must be fixed to 1]. */ -class Tritone : public Inkscape::Extension::Internal::Filter::Filter { +class Tritone : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Tritone ( ) : Filter() { }; - ~Tritone ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Tritone() + : Filter(){}; + ~Tritone() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -1855,14 +2002,13 @@ public: "\n", new Tritone()); // clang-format on }; - }; -gchar const * -Tritone::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Tritone::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); - + if (_filter != nullptr) + g_free((void *)_filter); + std::ostringstream dist; std::ostringstream a; std::ostringstream r; @@ -1877,11 +2023,11 @@ Tritone::get_filter_text (Inkscape::Extension::Extension * ext) std::ostringstream c2in; std::ostringstream c2in2; std::ostringstream b6in2; - + guint32 color = ext->get_param_color("color"); r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; globalblend << ext->get_param_optiongroup("globalblend"); dist << ext->get_param_int("dist"); @@ -1889,40 +2035,40 @@ Tritone::get_filter_text (Inkscape::Extension::Extension * ext) glowblend << ext->get_param_optiongroup("glowblend"); llight << ext->get_param_float("llight"); glight << ext->get_param_float("glight"); - + const gchar *type = ext->get_param_optiongroup("type"); if ((g_ascii_strcasecmp("enhue", type) == 0)) { - // Enhance hue + // Enhance hue c1in2 << "flood"; c2in << "SourceGraphic"; c2in2 << "blend6"; b6in2 << "composite1"; } else if ((g_ascii_strcasecmp("phospho", type) == 0)) { - // Phosphorescence + // Phosphorescence c1in2 << "flood"; c2in << "blend6"; c2in2 << "composite1"; b6in2 << "SourceGraphic"; } else if ((g_ascii_strcasecmp("phosphoB", type) == 0)) { - // Phosphorescence B + // Phosphorescence B c1in2 << "SourceGraphic"; c2in << "blend6"; c2in2 << "composite1"; b6in2 << "flood"; } else if ((g_ascii_strcasecmp("htb", type) == 0)) { - // Hue to background + // Hue to background c1in2 << "BackgroundImage"; c2in << "blend2"; c2in2 << "blend6"; b6in2 << "composite1"; } else { - // Normal + // Normal c1in2 << "flood"; c2in << "blend2"; c2in2 << "blend6"; b6in2 << "composite"; } - + // clang-format off _filter = g_strdup_printf( "\n" diff --git a/src/extension/internal/filter/distort.h b/src/extension/internal/filter/distort.h index c27dba5a56efb2f553d1c5156cf322ab6a57a0b3..8c5a1db41a13d8d75bc77b3d9b586cbdb244f27d 100644 --- a/src/extension/internal/filter/distort.h +++ b/src/extension/internal/filter/distort.h @@ -16,11 +16,10 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { @@ -29,9 +28,9 @@ namespace Filter { /** \brief Custom predefined FeltFeather filter. - + Blur and displace edges of shapes and pictures - + Filter's parameters: * Type (enum, default "In") -> in = map (in="composite3") @@ -45,7 +44,7 @@ namespace Filter { Wide = composite4 (operator="over") Narrow = composite4 (operator="in") No fill = composite4 (operator="xor") - * Roughness (group) + * Roughness (group) * Turbulence type (enum, default fractalNoise else turbulence) -> turbulence (type) * Horizontal frequency (0.001->1., default 0.05) -> turbulence (baseFrequency [/100]) * Vertical frequency (0.001->1., default 0.05) -> turbulence (baseFrequency [/100]) @@ -54,15 +53,23 @@ namespace Filter { * Intensity (0.0->100., default 30) -> displacement (scale) */ -class FeltFeather : public Inkscape::Extension::Internal::Filter::Filter { +class FeltFeather : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - FeltFeather ( ) : Filter() { }; - ~FeltFeather ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + FeltFeather() + : Filter(){}; + ~FeltFeather() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -103,14 +110,12 @@ public: "\n", new FeltFeather()); // clang-format on }; - }; -gchar const * -FeltFeather::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *FeltFeather::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); - + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream hblur; std::ostringstream vblur; @@ -126,12 +131,12 @@ FeltFeather::get_filter_text (Inkscape::Extension::Extension * ext) std::ostringstream map; std::ostringstream stroke; - + hblur << ext->get_param_float("hblur"); vblur << ext->get_param_float("vblur"); dilat << ext->get_param_float("dilat"); erosion << -ext->get_param_float("erosion"); - + turbulence << ext->get_param_optiongroup("turbulence"); hfreq << ext->get_param_float("hfreq") / 100; vfreq << ext->get_param_float("vfreq") / 100; @@ -140,7 +145,7 @@ FeltFeather::get_filter_text (Inkscape::Extension::Extension * ext) intensity << ext->get_param_float("intensity"); stroke << ext->get_param_optiongroup("stroke"); - + const gchar *maptype = ext->get_param_optiongroup("type"); if (g_ascii_strcasecmp("in", maptype) == 0) { map << "composite3"; @@ -169,7 +174,7 @@ FeltFeather::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Roughen filter. - + Small-scale roughening to edges and content Filter's parameters: @@ -181,15 +186,23 @@ FeltFeather::get_filter_text (Inkscape::Extension::Extension * ext) * Intensity (0.0->50., default 6.6) -> displacement (scale) */ -class Roughen : public Inkscape::Extension::Internal::Filter::Filter { +class Roughen : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Roughen ( ) : Filter() { }; - ~Roughen ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Roughen() + : Filter(){}; + ~Roughen() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -216,21 +229,20 @@ public: "\n", new Roughen()); // clang-format on }; - }; -gchar const * -Roughen::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Roughen::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); - + if (_filter != nullptr) + g_free((void *)_filter); + std::ostringstream type; std::ostringstream hfreq; std::ostringstream vfreq; std::ostringstream complexity; std::ostringstream variation; std::ostringstream intensity; - + type << ext->get_param_optiongroup("type"); hfreq << ext->get_param_float("hfreq") / 100; vfreq << ext->get_param_float("vfreq") / 100; diff --git a/src/extension/internal/filter/filter-all.cpp b/src/extension/internal/filter/filter-all.cpp index 5aa3900b089e05edf15ca1771cfd7dc7991274c2..d1964095f2d008cbe30f3dcfa48804d489deec02 100644 --- a/src/extension/internal/filter/filter-all.cpp +++ b/src/extension/internal/filter/filter-all.cpp @@ -28,11 +28,9 @@ namespace Extension { namespace Internal { namespace Filter { - -void -Filter::filters_all ( ) +void Filter::filters_all() { - // Here come the filters which are coded in C++ in order to present a parameters dialog + // Here come the filters which are coded in C++ in order to present a parameters dialog /* Experimental custom predefined filters */ @@ -47,7 +45,7 @@ Filter::filters_all ( ) CrossBlur::init(); Feather::init(); ImageBlur::init(); - + // Bumps Bump::init(); WaxBump::init(); @@ -105,7 +103,7 @@ Filter::filters_all ( ) // Textures InkBlot::init(); - + // Fill and transparency Blend::init(); ChannelTransparency::init(); @@ -113,13 +111,13 @@ Filter::filters_all ( ) Opacity::init(); Silhouette::init(); - // Here come the rest of the filters that are read from SVG files in share/filters and - // .config/Inkscape/filters - /* This should always be last, don't put stuff below this - * line. */ - Filter::filters_all_files(); + // Here come the rest of the filters that are read from SVG files in share/filters and + // .config/Inkscape/filters + /* This should always be last, don't put stuff below this + * line. */ + Filter::filters_all_files(); - return; + return; } }; /* namespace Filter */ diff --git a/src/extension/internal/filter/filter-file.cpp b/src/extension/internal/filter/filter-file.cpp index 0776350f1531f802fd87df53a84acb2478826040..3e0f0cb053a23fcb4503fa24a976367ba28f4ed8 100644 --- a/src/extension/internal/filter/filter-file.cpp +++ b/src/extension/internal/filter/filter-file.cpp @@ -7,22 +7,21 @@ */ #include "filter.h" - -#include "io/sys.h" #include "io/resource.h" #include "io/stream/inkscapestream.h" +#include "io/sys.h" /* Directory includes */ -#include "path-prefix.h" #include "inkscape.h" +#include "path-prefix.h" /* Extension */ #include "extension/extension.h" #include "extension/system.h" /* System includes */ -#include #include +#include using namespace Inkscape::IO::Resource; @@ -31,76 +30,81 @@ namespace Extension { namespace Internal { namespace Filter { -void -filters_load_file (Glib::ustring filename, gchar * menuname) +void filters_load_file(Glib::ustring filename, gchar *menuname) { Inkscape::XML::Document *doc = sp_repr_read_file(filename.c_str(), INKSCAPE_EXTENSION_URI); - if (doc == nullptr) { - g_warning("File (%s) is not parseable as XML. Ignored.", filename.c_str()); - return; - } - - Inkscape::XML::Node * root = doc->root(); - if (strcmp(root->name(), "svg:svg")) { - Inkscape::GC::release(doc); - g_warning("File (%s) is not SVG. Ignored.", filename.c_str()); - return; - } - - for (Inkscape::XML::Node * child = root->firstChild(); - child != nullptr; child = child->next()) { - if (!strcmp(child->name(), "svg:defs")) { - for (Inkscape::XML::Node * defs = child->firstChild(); - defs != nullptr; defs = defs->next()) { - if (!strcmp(defs->name(), "svg:filter")) { - Filter::filters_load_node(defs, menuname); - } // oh! a filter - } //defs - } // is defs - } // children of root - - Inkscape::GC::release(doc); - return; + if (doc == nullptr) { + g_warning("File (%s) is not parseable as XML. Ignored.", filename.c_str()); + return; + } + + Inkscape::XML::Node *root = doc->root(); + if (strcmp(root->name(), "svg:svg")) { + Inkscape::GC::release(doc); + g_warning("File (%s) is not SVG. Ignored.", filename.c_str()); + return; + } + + for (Inkscape::XML::Node *child = root->firstChild(); child != nullptr; child = child->next()) { + if (!strcmp(child->name(), "svg:defs")) { + for (Inkscape::XML::Node *defs = child->firstChild(); defs != nullptr; defs = defs->next()) { + if (!strcmp(defs->name(), "svg:filter")) { + Filter::filters_load_node(defs, menuname); + } // oh! a filter + } // defs + } // is defs + } // children of root + + Inkscape::GC::release(doc); + return; } void Filter::filters_all_files() { - for(auto &filename: get_filenames(USER, FILTERS, {".svg"})) { + for (auto &filename : get_filenames(USER, FILTERS, {".svg"})) { filters_load_file(filename, _("Personal")); } - for(auto &filename: get_filenames(SYSTEM, FILTERS, {".svg"})) { + for (auto &filename : get_filenames(SYSTEM, FILTERS, {".svg"})) { filters_load_file(filename, _("Bundled")); } } - #include "extension/internal/clear-n_.h" -class mywriter : public Inkscape::IO::BasicWriter { - Glib::ustring _str; +class mywriter : public Inkscape::IO::BasicWriter +{ + Glib::ustring _str; + public: - void close() override; - void flush() override; - void put (char ch) override; - gchar const * c_str () { return _str.c_str(); } + void close() override; + void flush() override; + void put(char ch) override; + gchar const *c_str() { return _str.c_str(); } }; -void mywriter::close () { return; } -void mywriter::flush () { return; } -void mywriter::put (char ch) { _str += ch; } - +void mywriter::close() +{ + return; +} +void mywriter::flush() +{ + return; +} +void mywriter::put(char ch) +{ + _str += ch; +} -void -Filter::filters_load_node (Inkscape::XML::Node *node, gchar * menuname) +void Filter::filters_load_node(Inkscape::XML::Node *node, gchar *menuname) { - gchar const * label = node->attribute("inkscape:label"); - gchar const * menu = node->attribute("inkscape:menu"); - gchar const * menu_tooltip = node->attribute("inkscape:menu-tooltip"); - gchar const * id = node->attribute("id"); + gchar const *label = node->attribute("inkscape:label"); + gchar const *menu = node->attribute("inkscape:menu"); + gchar const *menu_tooltip = node->attribute("inkscape:menu-tooltip"); + gchar const *id = node->attribute("id"); - if (label == nullptr) { - label = id; - } + if (label == nullptr) { + label = id; + } // clang-format off gchar * xml_str = g_strdup_printf( @@ -119,16 +123,16 @@ Filter::filters_load_node (Inkscape::XML::Node *node, gchar * menuname) "\n", label, id, menu? menu : menuname, menu_tooltip? menu_tooltip : label); // clang-format on - // FIXME: Bad hack: since we pull out a single filter node out of SVG file and - // serialize it, it loses the namespace declarations from the root, so we must provide - // one right here for our inkscape attributes - node->setAttribute("xmlns:inkscape", SP_INKSCAPE_NS_URI); + // FIXME: Bad hack: since we pull out a single filter node out of SVG file and + // serialize it, it loses the namespace declarations from the root, so we must provide + // one right here for our inkscape attributes + node->setAttribute("xmlns:inkscape", SP_INKSCAPE_NS_URI); - mywriter writer; - sp_repr_write_stream(node, writer, 0, FALSE, g_quark_from_static_string("svg"), 0, 0); + mywriter writer; + sp_repr_write_stream(node, writer, 0, FALSE, g_quark_from_static_string("svg"), 0, 0); Inkscape::Extension::build_from_mem(xml_str, new Filter(g_strdup(writer.c_str()))); - g_free(xml_str); + g_free(xml_str); return; } @@ -136,4 +140,3 @@ Filter::filters_load_node (Inkscape::XML::Node *node, gchar * menuname) }; /* namespace Internal */ }; /* namespace Extension */ }; /* namespace Inkscape */ - diff --git a/src/extension/internal/filter/filter.cpp b/src/extension/internal/filter/filter.cpp index 3c5674d7bea6909c0c94606abd599441cf3daff9..464516c8a7ad60967a127a41dac8177fa72749eb 100644 --- a/src/extension/internal/filter/filter.cpp +++ b/src/extension/internal/filter/filter.cpp @@ -8,36 +8,39 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "filter.h" + #include "desktop.h" -#include "selection.h" -#include "extension/extension.h" #include "extension/effect.h" +#include "extension/extension.h" #include "extension/system.h" +#include "object/sp-defs.h" +#include "selection.h" +#include "xml/attribute-record.h" #include "xml/repr.h" #include "xml/simple-node.h" -#include "xml/attribute-record.h" -#include "object/sp-defs.h" - -#include "filter.h" namespace Inkscape { namespace Extension { namespace Internal { namespace Filter { -Filter::Filter() : - Inkscape::Extension::Implementation::Implementation(), - _filter(nullptr) { +Filter::Filter() + : Inkscape::Extension::Implementation::Implementation() + , _filter(nullptr) +{ return; } -Filter::Filter(gchar const * filter) : - Inkscape::Extension::Implementation::Implementation(), - _filter(filter) { +Filter::Filter(gchar const *filter) + : Inkscape::Extension::Implementation::Implementation() + , _filter(filter) +{ return; } -Filter::~Filter () { +Filter::~Filter() +{ if (_filter != nullptr) { _filter = nullptr; } @@ -50,8 +53,8 @@ bool Filter::load(Inkscape::Extension::Extension * /*module*/) return true; } -Inkscape::Extension::Implementation::ImplementationDocumentCache *Filter::newDocCache(Inkscape::Extension::Extension * /*ext*/, - Inkscape::UI::View::View * /*doc*/) +Inkscape::Extension::Implementation::ImplementationDocumentCache * +Filter::newDocCache(Inkscape::Extension::Extension * /*ext*/, Inkscape::UI::View::View * /*doc*/) { return nullptr; } @@ -61,25 +64,24 @@ gchar const *Filter::get_filter_text(Inkscape::Extension::Extension * /*ext*/) return _filter; } -Inkscape::XML::Document * -Filter::get_filter (Inkscape::Extension::Extension * ext) { - gchar const * filter = get_filter_text(ext); +Inkscape::XML::Document *Filter::get_filter(Inkscape::Extension::Extension *ext) +{ + gchar const *filter = get_filter_text(ext); return sp_repr_read_mem(filter, strlen(filter), nullptr); } -void -Filter::merge_filters( Inkscape::XML::Node * to, Inkscape::XML::Node * from, - Inkscape::XML::Document * doc, - gchar const * srcGraphic, gchar const * srcGraphicAlpha) +void Filter::merge_filters(Inkscape::XML::Node *to, Inkscape::XML::Node *from, Inkscape::XML::Document *doc, + gchar const *srcGraphic, gchar const *srcGraphicAlpha) { - if (from == nullptr) return; + if (from == nullptr) + return; // copy attributes - for ( Inkscape::Util::List iter = from->attributeList() ; - iter ; ++iter ) { - gchar const * attr = g_quark_to_string(iter->key); - //printf("Attribute List: %s\n", attr); - if (!strcmp(attr, "id")) continue; // nope, don't copy that one! + for (Inkscape::Util::List iter = from->attributeList(); iter; ++iter) { + gchar const *attr = g_quark_to_string(iter->key); + // printf("Attribute List: %s\n", attr); + if (!strcmp(attr, "id")) + continue; // nope, don't copy that one! to->setAttribute(attr, from->attribute(attr)); if (!strcmp(attr, "in") || !strcmp(attr, "in2") || !strcmp(attr, "in3")) { @@ -94,23 +96,23 @@ Filter::merge_filters( Inkscape::XML::Node * to, Inkscape::XML::Node * from, } // for each child call recursively - for (Inkscape::XML::Node * from_child = from->firstChild(); - from_child != nullptr ; from_child = from_child->next()) { + for (Inkscape::XML::Node *from_child = from->firstChild(); from_child != nullptr; from_child = from_child->next()) { Glib::ustring name = "svg:"; name += from_child->name(); - Inkscape::XML::Node * to_child = doc->createElement(name.c_str()); + Inkscape::XML::Node *to_child = doc->createElement(name.c_str()); to->appendChild(to_child); merge_filters(to_child, from_child, doc, srcGraphic, srcGraphicAlpha); - if (from_child == from->firstChild() && !strcmp("filter", from->name()) && srcGraphic != nullptr && to_child->attribute("in") == nullptr) { + if (from_child == from->firstChild() && !strcmp("filter", from->name()) && srcGraphic != nullptr && + to_child->attribute("in") == nullptr) { to_child->setAttribute("in", srcGraphic); } Inkscape::GC::release(to_child); } } -#define FILTER_SRC_GRAPHIC "fbSourceGraphic" +#define FILTER_SRC_GRAPHIC "fbSourceGraphic" #define FILTER_SRC_GRAPHIC_ALPHA "fbSourceGraphicAlpha" void Filter::effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, @@ -121,30 +123,30 @@ void Filter::effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::Vie return; // could not parse the XML source of the filter; typically parser will stderr a warning } - //printf("Calling filter effect\n"); - Inkscape::Selection * selection = ((SPDesktop *)document)->selection; + // printf("Calling filter effect\n"); + Inkscape::Selection *selection = ((SPDesktop *)document)->selection; // TODO need to properly refcount the items, at least - std::vector items(selection->items().begin(), selection->items().end()); + std::vector items(selection->items().begin(), selection->items().end()); - Inkscape::XML::Document * xmldoc = document->doc()->getReprDoc(); - Inkscape::XML::Node * defsrepr = document->doc()->getDefs()->getRepr(); + Inkscape::XML::Document *xmldoc = document->doc()->getReprDoc(); + Inkscape::XML::Node *defsrepr = document->doc()->getDefs()->getRepr(); - for(auto spitem : items) { + for (auto spitem : items) { Inkscape::XML::Node *node = spitem->getRepr(); - SPCSSAttr * css = sp_repr_css_attr(node, "style"); - gchar const * filter = sp_repr_css_property(css, "filter", nullptr); + SPCSSAttr *css = sp_repr_css_attr(node, "style"); + gchar const *filter = sp_repr_css_property(css, "filter", nullptr); if (filter == nullptr) { - - Inkscape::XML::Node * newfilterroot = xmldoc->createElement("svg:filter"); + Inkscape::XML::Node *newfilterroot = xmldoc->createElement("svg:filter"); merge_filters(newfilterroot, filterdoc->root(), xmldoc); defsrepr->appendChild(newfilterroot); document->doc()->resources_changed_signals[g_quark_from_string("filter")].emit(); - Glib::ustring url = "url(#"; url += newfilterroot->attribute("id"); url += ")"; - + Glib::ustring url = "url(#"; + url += newfilterroot->attribute("id"); + url += ")"; Inkscape::GC::release(newfilterroot); @@ -156,9 +158,9 @@ void Filter::effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::Vie continue; } - gchar * lfilter = g_strndup(filter + 5, strlen(filter) - 6); - Inkscape::XML::Node * filternode = nullptr; - for (Inkscape::XML::Node * child = defsrepr->firstChild(); child != nullptr; child = child->next()) { + gchar *lfilter = g_strndup(filter + 5, strlen(filter) - 6); + Inkscape::XML::Node *filternode = nullptr; + for (Inkscape::XML::Node *child = defsrepr->firstChild(); child != nullptr; child = child->next()) { if (!strcmp(lfilter, child->attribute("id"))) { filternode = child; break; @@ -178,7 +180,7 @@ void Filter::effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::Vie } else { // existing filter, we merge filternode->lastChild()->setAttribute("result", FILTER_SRC_GRAPHIC); - Inkscape::XML::Node * alpha = xmldoc->createElement("svg:feColorMatrix"); + Inkscape::XML::Node *alpha = xmldoc->createElement("svg:feColorMatrix"); alpha->setAttribute("result", FILTER_SRC_GRAPHIC_ALPHA); alpha->setAttribute("in", FILTER_SRC_GRAPHIC); // not required, but we're being explicit alpha->setAttribute("values", "0 0 0 -1 0 0 0 0 -1 0 0 0 0 -1 0 0 0 0 1 0"); @@ -197,8 +199,8 @@ void Filter::effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::Vie #include "extension/internal/clear-n_.h" -void -Filter::filter_init (gchar const * id, gchar const * name, gchar const * submenu, gchar const * tip, gchar const * filter) +void Filter::filter_init(gchar const *id, gchar const *name, gchar const *submenu, gchar const *tip, + gchar const *filter) { // clang-format off gchar * xml_str = g_strdup_printf( diff --git a/src/extension/internal/filter/filter.h b/src/extension/internal/filter/filter.h index cb3ed363b44d5d203c9820e14bedc7ecb935e911..4311896041e40d53e0efdf799508a659ed27a11a 100644 --- a/src/extension/internal/filter/filter.h +++ b/src/extension/internal/filter/filter.h @@ -16,7 +16,7 @@ namespace Inkscape { namespace XML { - struct Document; +struct Document; } namespace Extension { @@ -27,31 +27,35 @@ class Extension; namespace Internal { namespace Filter { -class Filter : public Inkscape::Extension::Implementation::Implementation { +class Filter : public Inkscape::Extension::Implementation::Implementation +{ protected: - gchar const * _filter; - virtual gchar const * get_filter_text (Inkscape::Extension::Extension * ext); + gchar const *_filter; + virtual gchar const *get_filter_text(Inkscape::Extension::Extension *ext); private: - Inkscape::XML::Document * get_filter (Inkscape::Extension::Extension * ext); - void merge_filters (Inkscape::XML::Node * to, Inkscape::XML::Node * from, Inkscape::XML::Document * doc, gchar const * srcGraphic = nullptr, gchar const * srcGraphicAlpha = nullptr); + Inkscape::XML::Document *get_filter(Inkscape::Extension::Extension *ext); + void merge_filters(Inkscape::XML::Node *to, Inkscape::XML::Node *from, Inkscape::XML::Document *doc, + gchar const *srcGraphic = nullptr, gchar const *srcGraphicAlpha = nullptr); public: - Filter(); - Filter(gchar const * filter); - ~Filter() override; - - bool load(Inkscape::Extension::Extension *module) override; - Inkscape::Extension::Implementation::ImplementationDocumentCache * newDocCache (Inkscape::Extension::Extension * ext, Inkscape::UI::View::View * doc) override; - void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, Inkscape::Extension::Implementation::ImplementationDocumentCache * docCache) override; - - static void filter_init(gchar const * id, gchar const * name, gchar const * submenu, gchar const * tip, gchar const * filter); - static void filters_all(); - - /* File loader related */ - static void filters_all_files(); - static void filters_load_node(Inkscape::XML::Node *node, gchar * menuname); - + Filter(); + Filter(gchar const *filter); + ~Filter() override; + + bool load(Inkscape::Extension::Extension *module) override; + Inkscape::Extension::Implementation::ImplementationDocumentCache * + newDocCache(Inkscape::Extension::Extension *ext, Inkscape::UI::View::View *doc) override; + void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, + Inkscape::Extension::Implementation::ImplementationDocumentCache *docCache) override; + + static void filter_init(gchar const *id, gchar const *name, gchar const *submenu, gchar const *tip, + gchar const *filter); + static void filters_all(); + + /* File loader related */ + static void filters_all_files(); + static void filters_load_node(Inkscape::XML::Node *node, gchar *menuname); }; }; /* namespace Filter */ diff --git a/src/extension/internal/filter/image.h b/src/extension/internal/filter/image.h index 8820122262b657eb60db691f63b112f2f4a82b86..01ea63d8e5b84364b61965e0ff7b4052b819476e 100644 --- a/src/extension/internal/filter/image.h +++ b/src/extension/internal/filter/image.h @@ -15,11 +15,10 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { @@ -28,7 +27,7 @@ namespace Filter { /** \brief Custom predefined Edge detect filter. - + Detect color edges in object. Filter's parameters: @@ -36,15 +35,23 @@ namespace Filter { * Level (0.01->10., default 1.) -> convolve (divisor) * Inverted (boolean, default false) -> convolve (bias) */ -class EdgeDetect : public Inkscape::Extension::Internal::Filter::Filter { +class EdgeDetect : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - EdgeDetect ( ) : Filter() { }; - ~EdgeDetect ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + EdgeDetect() + : Filter(){}; + ~EdgeDetect() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -69,22 +76,21 @@ public: "\n", new EdgeDetect()); // clang-format on }; - }; -gchar const * -EdgeDetect::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *EdgeDetect::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream matrix; std::ostringstream inverted; std::ostringstream level; - + const gchar *type = ext->get_param_optiongroup("type"); level << 1 / ext->get_param_float("level"); - + if ((g_ascii_strcasecmp("vertical", type) == 0)) { matrix << "0 0 0 1 -2 1 0 0 0"; } else if ((g_ascii_strcasecmp("horizontal", type) == 0)) { @@ -92,13 +98,13 @@ EdgeDetect::get_filter_text (Inkscape::Extension::Extension * ext) } else { matrix << "0 1 0 1 -4 1 0 1 0"; } - + if (ext->get_param_bool("inverted")) { inverted << "1"; } else { inverted << "0"; } - + // clang-format off _filter = g_strdup_printf( "\n" diff --git a/src/extension/internal/filter/morphology.h b/src/extension/internal/filter/morphology.h index 7057c8db9bc427fbf8b431b57e2fbfe0c1120b6b..2304358583fc33728ee2568c9dbbdbe559b149e6 100644 --- a/src/extension/internal/filter/morphology.h +++ b/src/extension/internal/filter/morphology.h @@ -16,11 +16,10 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { @@ -29,7 +28,7 @@ namespace Filter { /** \brief Custom predefined Cross-smooth filter. - + Smooth the outside of shapes and pictures. Filter's parameters: @@ -45,15 +44,23 @@ namespace Filter { * Blur content (boolean, default false) -> blend (true: in="colormatrix2", false: in="SourceGraphic") */ -class Crosssmooth : public Inkscape::Extension::Internal::Filter::Filter { +class Crosssmooth : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Crosssmooth ( ) : Filter() { }; - ~Crosssmooth ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Crosssmooth() + : Filter(){}; + ~Crosssmooth() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -83,13 +90,12 @@ public: "\n", new Crosssmooth()); // clang-format on }; - }; -gchar const * -Crosssmooth::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Crosssmooth::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream type; std::ostringstream width; @@ -133,7 +139,7 @@ Crosssmooth::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Outline filter. - + Adds a colorizable outline Filter's parameters: @@ -154,18 +160,26 @@ Crosssmooth::get_filter_text (Inkscape::Extension::Extension * ext) * Color (guint, default 0,0,0,255) -> flood (flood-color, flood-opacity) * Fill opacity (0.->1., default 1) -> composite5 (k2) * Stroke opacity (0.->1., default 1) -> composite5 (k3) - + */ -class Outline : public Inkscape::Extension::Internal::Filter::Filter { +class Outline : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Outline ( ) : Filter() { }; - ~Outline ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Outline() + : Filter(){}; + ~Outline() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -214,13 +228,12 @@ public: "\n", new Outline()); // clang-format on }; - }; -gchar const * -Outline::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Outline::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream width1; std::ostringstream dilat1; @@ -244,36 +257,35 @@ Outline::get_filter_text (Inkscape::Extension::Extension * ext) std::ostringstream c2op; std::ostringstream c4in; - width1 << ext->get_param_float("width1"); dilat1 << ext->get_param_float("dilat1"); - erosion1 << (- ext->get_param_float("erosion1")); + erosion1 << (-ext->get_param_float("erosion1")); width2 << ext->get_param_float("width2"); dilat2 << ext->get_param_float("dilat2"); - erosion2 << (- ext->get_param_float("erosion2")); + erosion2 << (-ext->get_param_float("erosion2")); antialias << ext->get_param_float("antialias"); guint32 color = ext->get_param_color("color"); r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; fopacity << ext->get_param_float("fopacity"); sopacity << ext->get_param_float("sopacity"); const gchar *position = ext->get_param_optiongroup("position"); - if((g_ascii_strcasecmp("inside", position) == 0)) { - // Indide + if ((g_ascii_strcasecmp("inside", position) == 0)) { + // Indide c1in << "SourceGraphic"; c1in2 << "blur1"; c1op << "out"; - } else if((g_ascii_strcasecmp("outside", position) == 0)) { - // Outside + } else if ((g_ascii_strcasecmp("outside", position) == 0)) { + // Outside c1in << "blur1"; c1in2 << "SourceGraphic"; c1op << "out"; } else { - // Overlayed + // Overlayed c1in << "blur1"; c1in2 << "SourceGraphic"; c1op << "xor"; @@ -286,7 +298,7 @@ Outline::get_filter_text (Inkscape::Extension::Extension * ext) } c2op << ext->get_param_optiongroup("type"); - + if (ext->get_param_bool("outline")) { c4in << "composite3"; } else { @@ -298,7 +310,7 @@ Outline::get_filter_text (Inkscape::Extension::Extension * ext) } else { smooth << "5 -1"; } - + // clang-format off _filter = g_strdup_printf( "\n" diff --git a/src/extension/internal/filter/overlays.h b/src/extension/internal/filter/overlays.h index 53bd31c11116eb1bee319de3b31685511972931e..b73b98812724af640f32efda79f8680e88096c61 100644 --- a/src/extension/internal/filter/overlays.h +++ b/src/extension/internal/filter/overlays.h @@ -15,11 +15,10 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { @@ -28,7 +27,7 @@ namespace Filter { /** \brief Custom predefined Noise fill filter. - + Basic noise fill and transparency texture Filter's parameters: @@ -43,15 +42,23 @@ namespace Filter { * Inverted (boolean, default false) -> composite1 (operator, true="in", false="out") */ -class NoiseFill : public Inkscape::Extension::Internal::Filter::Filter { +class NoiseFill : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - NoiseFill ( ) : Filter() { }; - ~NoiseFill ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } - - static void init () { + NoiseFill() + : Filter(){}; + ~NoiseFill() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } + + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -87,13 +94,12 @@ public: "\n", new NoiseFill()); // clang-format on }; - }; -gchar const * -NoiseFill::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *NoiseFill::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream type; std::ostringstream hfreq; @@ -114,11 +120,11 @@ NoiseFill::get_filter_text (Inkscape::Extension::Extension * ext) complexity << ext->get_param_int("complexity"); variation << ext->get_param_int("variation"); dilat << ext->get_param_float("dilat"); - erosion << (- ext->get_param_float("erosion")); + erosion << (-ext->get_param_float("erosion")); guint32 color = ext->get_param_color("color"); r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; if (ext->get_param_bool("inverted")) inverted << "out"; @@ -126,17 +132,21 @@ NoiseFill::get_filter_text (Inkscape::Extension::Extension * ext) inverted << "in"; _filter = g_strdup_printf( - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n" - "\n", type.str().c_str(), hfreq.str().c_str(), vfreq.str().c_str(), complexity.str().c_str(), variation.str().c_str(), inverted.str().c_str(), dilat.str().c_str(), erosion.str().c_str(), a.str().c_str(), r.str().c_str(), g.str().c_str(), b.str().c_str()); + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n", + type.str().c_str(), hfreq.str().c_str(), vfreq.str().c_str(), complexity.str().c_str(), variation.str().c_str(), + inverted.str().c_str(), dilat.str().c_str(), erosion.str().c_str(), a.str().c_str(), r.str().c_str(), + g.str().c_str(), b.str().c_str()); return _filter; }; /* NoiseFill filter */ diff --git a/src/extension/internal/filter/paint.h b/src/extension/internal/filter/paint.h index 920b275afe5f466dc7bf4defffbda4fbf2a19215..a73ade5de90ac7f2f0b8c4a86e4ab9256a995a5d 100644 --- a/src/extension/internal/filter/paint.h +++ b/src/extension/internal/filter/paint.h @@ -22,11 +22,10 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { @@ -35,12 +34,13 @@ namespace Filter { /** \brief Custom predefined Chromolitho filter. - + Chromo effect with customizable edge drawing and graininess Filter's parameters: * Drawing (boolean, default checked) -> Checked = blend1 (in="convolve1"), unchecked = blend1 (in="composite1") - * Transparent (boolean, default unchecked) -> Checked = colormatrix5 (in="colormatrix4"), Unchecked = colormatrix5 (in="component1") + * Transparent (boolean, default unchecked) -> Checked = colormatrix5 (in="colormatrix4"), Unchecked = colormatrix5 + (in="component1") * Invert (boolean, default false) -> component1 (tableValues) [adds a trailing 0] * Dented (boolean, default false) -> component1 (tableValues) [adds intermediate 0s] * Lightness (0.->10., default 0.) -> composite1 (k1) @@ -58,15 +58,23 @@ namespace Filter { * Grain color (boolean, default true) -> colormatrix2 (values) * Grain blend (enum, default Normal) -> blend2 (mode) */ -class Chromolitho : public Inkscape::Extension::Internal::Filter::Filter { +class Chromolitho : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Chromolitho ( ) : Filter() { }; - ~Chromolitho ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Chromolitho() + : Filter(){}; + ~Chromolitho() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -122,11 +130,11 @@ public: }; }; -gchar const * -Chromolitho::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Chromolitho::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); - + if (_filter != nullptr) + g_free((void *)_filter); + std::ostringstream b1in; std::ostringstream b2in; std::ostringstream col3in; @@ -212,7 +220,7 @@ Chromolitho::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Cross engraving filter. - + Convert image to an engraving made of vertical and horizontal lines Filter's parameters: @@ -223,15 +231,23 @@ Chromolitho::get_filter_text (Inkscape::Extension::Extension * ext) * Length (0.5->20, default 4) -> blur1 (stdDeviation x), blur2 (stdDeviation y) * Transparent (boolean, default false) -> composite 4 (in, true->composite3, false->blend) */ -class CrossEngraving : public Inkscape::Extension::Internal::Filter::Filter { +class CrossEngraving : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - CrossEngraving ( ) : Filter() { }; - ~CrossEngraving ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + CrossEngraving() + : Filter(){}; + ~CrossEngraving() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -257,10 +273,10 @@ public: }; }; -gchar const * -CrossEngraving::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *CrossEngraving::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream clean; std::ostringstream dilat; @@ -271,7 +287,7 @@ CrossEngraving::get_filter_text (Inkscape::Extension::Extension * ext) clean << (-1000 - ext->get_param_int("clean")); dilat << ext->get_param_float("dilat"); - erosion << (- ext->get_param_float("erosion")); + erosion << (-ext->get_param_float("erosion")); strength << ext->get_param_float("strength"); length << ext->get_param_float("length"); if (ext->get_param_bool("trans")) @@ -301,7 +317,7 @@ CrossEngraving::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Drawing filter. - + Convert images to duochrome drawings. Filter's parameters: @@ -326,15 +342,23 @@ CrossEngraving::get_filter_text (Inkscape::Extension::Extension * ext) */ -class Drawing : public Inkscape::Extension::Internal::Filter::Filter { +class Drawing : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Drawing ( ) : Filter() { }; - ~Drawing ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Drawing() + : Filter(){}; + ~Drawing() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -380,10 +404,10 @@ public: }; }; -gchar const * -Drawing::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Drawing::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream simply; std::ostringstream clean; @@ -412,21 +436,21 @@ Drawing::get_filter_text (Inkscape::Extension::Extension * ext) erase << (ext->get_param_float("erase") / 10); smooth << ext->get_param_float("smooth"); dilat << ext->get_param_float("dilat"); - erosion << (- ext->get_param_float("erosion")); + erosion << (-ext->get_param_float("erosion")); if (ext->get_param_bool("translucent")) translucent << "merge1"; else translucent << "color5"; offset << ext->get_param_int("offset"); - + blur << ext->get_param_float("blur"); bdilat << ext->get_param_float("bdilat"); - berosion << (- ext->get_param_float("berosion")); + berosion << (-ext->get_param_float("berosion")); guint32 fcolor = ext->get_param_color("fcolor"); fillr << ((fcolor >> 24) & 0xff); fillg << ((fcolor >> 16) & 0xff); - fillb << ((fcolor >> 8) & 0xff); + fillb << ((fcolor >> 8) & 0xff); filla << (fcolor & 0xff) / 255.0F; if (ext->get_param_bool("iof")) iof << "SourceGraphic"; @@ -436,13 +460,13 @@ Drawing::get_filter_text (Inkscape::Extension::Extension * ext) guint32 scolor = ext->get_param_color("scolor"); stroker << ((scolor >> 24) & 0xff); strokeg << ((scolor >> 16) & 0xff); - strokeb << ((scolor >> 8) & 0xff); + strokeb << ((scolor >> 8) & 0xff); strokea << (scolor & 0xff) / 255.0F; if (ext->get_param_bool("ios")) ios << "SourceGraphic"; else ios << "flood2"; - + // clang-format off _filter = g_strdup_printf( "\n" @@ -481,10 +505,9 @@ Drawing::get_filter_text (Inkscape::Extension::Extension * ext) return _filter; }; /* Drawing filter */ - /** \brief Custom predefined Electrize filter. - + Electro solarization effects. Filter's parameters: @@ -493,15 +516,23 @@ Drawing::get_filter_text (Inkscape::Extension::Extension * ext) * Level (0->10, default 3) -> component (tableValues) * Inverted (boolean, default false) -> component (tableValues) */ -class Electrize : public Inkscape::Extension::Internal::Filter::Filter { +class Electrize : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Electrize ( ) : Filter() { }; - ~Electrize ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Electrize() + : Filter(){}; + ~Electrize() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -528,10 +559,10 @@ public: }; }; -gchar const * -Electrize::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Electrize::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream blur; std::ostringstream type; @@ -547,16 +578,15 @@ Electrize::get_filter_text (Inkscape::Extension::Extension * ext) val = 1; } values << val; - for ( int step = 1 ; step <= levels ; step++ ) { + for (int step = 1; step <= levels; step++) { if (val == 1) { val = 0; - } - else { + } else { val = 1; } values << " " << val; } - + // clang-format off _filter = g_strdup_printf( "\n" @@ -574,7 +604,7 @@ Electrize::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Neon draw filter. - + Posterize and draw smooth lines around color shapes Filter's parameters: @@ -587,15 +617,23 @@ Electrize::get_filter_text (Inkscape::Extension::Extension * ext) * Blend (enum [normal, multiply, screen], default normal) -> blend (mode) * Dark mode (boolean, default false) -> composite2 (true: in2="component2") */ -class NeonDraw : public Inkscape::Extension::Internal::Filter::Filter { +class NeonDraw : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - NeonDraw ( ) : Filter() { }; - ~NeonDraw ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + NeonDraw() + : Filter(){}; + ~NeonDraw() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -627,10 +665,10 @@ public: }; }; -gchar const * -NeonDraw::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *NeonDraw::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream blend; std::ostringstream simply; @@ -672,7 +710,7 @@ NeonDraw::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Point engraving filter. - + Convert image to a transparent point engraving Filter's parameters: @@ -688,21 +726,29 @@ NeonDraw::get_filter_text (Inkscape::Extension::Extension * ext) * Grain lightness (0.->10., default 1.3) -> composite1 (k2) * Erase (0.00->1., default 0) -> composite1 (k4) * Blur (0.01->2., default 0.5) -> blur (stdDeviation) - + * Drawing color (guint32, default rgb(255,255,255)) -> flood1 (flood-color, flood-opacity) - + * Background color (guint32, default rgb(99,89,46)) -> flood2 (flood-color, flood-opacity) */ -class PointEngraving : public Inkscape::Extension::Internal::Filter::Filter { +class PointEngraving : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - PointEngraving ( ) : Filter() { }; - ~PointEngraving ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + PointEngraving() + : Filter(){}; + ~PointEngraving() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -752,14 +798,13 @@ public: "\n", new PointEngraving()); // clang-format on }; - }; -gchar const * -PointEngraving::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *PointEngraving::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); - + if (_filter != nullptr) + g_free((void *)_filter); + std::ostringstream type; std::ostringstream hfreq; std::ostringstream vfreq; @@ -793,18 +838,18 @@ PointEngraving::get_filter_text (Inkscape::Extension::Extension * ext) grain << ext->get_param_float("grain"); erase << ext->get_param_float("erase"); blur << ext->get_param_float("blur"); - + guint32 fcolor = ext->get_param_color("fcolor"); r << ((fcolor >> 24) & 0xff); g << ((fcolor >> 16) & 0xff); - b << ((fcolor >> 8) & 0xff); - a << (fcolor & 0xff) / 255.0F; - + b << ((fcolor >> 8) & 0xff); + a << (fcolor & 0xff) / 255.0F; + guint32 pcolor = ext->get_param_color("pcolor"); br << ((pcolor >> 24) & 0xff); bg << ((pcolor >> 16) & 0xff); - bb << ((pcolor >> 8) & 0xff); - ba << (pcolor & 0xff) / 255.0F; + bb << ((pcolor >> 8) & 0xff); + ba << (pcolor & 0xff) / 255.0F; if (ext->get_param_bool("iof")) iof << "SourceGraphic"; @@ -845,7 +890,7 @@ PointEngraving::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Poster paint filter. - + Poster and painting effects. Filter's parameters: @@ -861,15 +906,23 @@ PointEngraving::get_filter_text (Inkscape::Extension::Extension * ext) * Post-saturation (0.->1., default 1.) -> color2 (values) * Simulate antialiasing (boolean, default false) -> blur3 (true->stdDeviation=0.5, false->stdDeviation=0.01) */ -class Posterize : public Inkscape::Extension::Internal::Filter::Filter { +class Posterize : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Posterize ( ) : Filter() { }; - ~Posterize ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Posterize() + : Filter(){}; + ~Posterize() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -910,10 +963,10 @@ public: }; }; -gchar const * -Posterize::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Posterize::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream table; std::ostringstream blendmode; @@ -923,7 +976,7 @@ Posterize::get_filter_text (Inkscape::Extension::Extension * ext) std::ostringstream postsat; std::ostringstream transf; std::ostringstream antialias; - + table << ext->get_param_optiongroup("table"); blendmode << ext->get_param_optiongroup("blend"); blur1 << ext->get_param_float("blur1"); @@ -934,7 +987,7 @@ Posterize::get_filter_text (Inkscape::Extension::Extension * ext) // TransfertComponent table values are calculated based on the poster type. transf << "0"; int levels = ext->get_param_int("levels") + 1; - const gchar *effecttype = ext->get_param_optiongroup("type"); + const gchar *effecttype = ext->get_param_optiongroup("type"); if (levels == 1) { if ((g_ascii_strcasecmp("dented", effecttype) == 0)) { transf << " 1 0 1"; @@ -942,21 +995,21 @@ Posterize::get_filter_text (Inkscape::Extension::Extension * ext) transf << " 1"; } } else { - for ( int step = 1 ; step <= levels ; step++ ) { - float val = (float) step / levels; + for (int step = 1; step <= levels; step++) { + float val = (float)step / levels; transf << " " << val; if ((g_ascii_strcasecmp("dented", effecttype) == 0)) { - transf << " " << (val - ((float) 1 / (3 * levels))) << " " << (val + ((float) 1 / (2 * levels))); + transf << " " << (val - ((float)1 / (3 * levels))) << " " << (val + ((float)1 / (2 * levels))); } } } transf << " 1"; - + if (ext->get_param_bool("antialiasing")) antialias << "0.5"; else antialias << "0.01"; - + // clang-format off _filter = g_strdup_printf( "\n" @@ -981,22 +1034,30 @@ Posterize::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Posterize basic filter. - + Simple posterizing effect Filter's parameters: * Levels (0->20, default 5) -> component1 (tableValues) * Blur (0.01->20., default 4.) -> blur1 (stdDeviation) */ -class PosterizeBasic : public Inkscape::Extension::Internal::Filter::Filter { +class PosterizeBasic : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - PosterizeBasic ( ) : Filter() { }; - ~PosterizeBasic ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + PosterizeBasic() + : Filter(){}; + ~PosterizeBasic() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -1018,20 +1079,20 @@ public: }; }; -gchar const * -PosterizeBasic::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *PosterizeBasic::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream blur; std::ostringstream transf; - + blur << ext->get_param_float("blur"); transf << "0"; int levels = ext->get_param_int("levels") + 1; - for ( int step = 1 ; step <= levels ; step++ ) { - const float val = (float) step / levels; + for (int step = 1; step <= levels; step++) { + const float val = (float)step / levels; transf << " " << val; } transf << " 1"; diff --git a/src/extension/internal/filter/protrusions.h b/src/extension/internal/filter/protrusions.h index ccf54b4763d828eb9d0609a27025258a071390d7..bca80a5bdb9680e3af02b78cf023c5bdfa6bd5a8 100644 --- a/src/extension/internal/filter/protrusions.h +++ b/src/extension/internal/filter/protrusions.h @@ -17,34 +17,40 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { namespace Internal { namespace Filter { - /** \brief Custom predefined Snow filter. - + Snow has fallen on object. */ -class Snow : public Inkscape::Extension::Internal::Filter::Filter { +class Snow : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Snow ( ) : Filter() { }; - ~Snow ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Snow() + : Filter(){}; + ~Snow() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } public: - static void init () { - // clang-format off + static void init() + { + // clang-format off Inkscape::Extension::build_from_mem( "\n" "" N_("Snow Crest") "\n" @@ -60,20 +66,19 @@ public: "" N_("Snow has fallen on object") "\n" "\n" "\n", new Snow()); - // clang-format on - }; - + // clang-format on + }; }; -gchar const * -Snow::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Snow::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); - std::ostringstream drift; - drift << ext->get_param_float("drift"); + std::ostringstream drift; + drift << ext->get_param_float("drift"); - // clang-format off + // clang-format off _filter = g_strdup_printf( "\n" "\n" @@ -89,12 +94,11 @@ Snow::get_filter_text (Inkscape::Extension::Extension * ext) "\n" "\n" "\n", drift.str().c_str()); - // clang-format on + // clang-format on - return _filter; + return _filter; }; /* Snow filter */ - }; /* namespace Filter */ }; /* namespace Internal */ }; /* namespace Extension */ diff --git a/src/extension/internal/filter/shadows.h b/src/extension/internal/filter/shadows.h index 2616b25789f3d5d2e61046563fde23166b50435d..a1dee91e9a92d5739e5f810893100d98b118af15 100644 --- a/src/extension/internal/filter/shadows.h +++ b/src/extension/internal/filter/shadows.h @@ -15,11 +15,10 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { @@ -28,7 +27,7 @@ namespace Filter { /** \brief Custom predefined Drop shadow filter. - + Colorizable Drop shadow. Filter's parameters: @@ -44,15 +43,23 @@ namespace Filter { * Color (guint, default 0,0,0,127) -> flood (flood-opacity, flood-color) * Use object's color (boolean, default false) -> composite1 (in1, in2) */ -class ColorizableDropShadow : public Inkscape::Extension::Internal::Filter::Filter { +class ColorizableDropShadow : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - ColorizableDropShadow ( ) : Filter() { }; - ~ColorizableDropShadow ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + ColorizableDropShadow() + : Filter(){}; + ~ColorizableDropShadow() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -88,13 +95,12 @@ public: "\n", new ColorizableDropShadow()); // clang-format on }; - }; -gchar const * -ColorizableDropShadow::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *ColorizableDropShadow::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream blur; std::ostringstream a; @@ -109,7 +115,7 @@ ColorizableDropShadow::get_filter_text (Inkscape::Extension::Extension * ext) std::ostringstream comp2in1; std::ostringstream comp2in2; std::ostringstream comp2op; - + const gchar *type = ext->get_param_optiongroup("type"); guint32 color = ext->get_param_color("color"); @@ -119,7 +125,7 @@ ColorizableDropShadow::get_filter_text (Inkscape::Extension::Extension * ext) a << (color & 0xff) / 255.0F; r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); // Select object or user-defined color if ((g_ascii_strcasecmp("innercut", type) == 0)) { @@ -156,12 +162,12 @@ ColorizableDropShadow::get_filter_text (Inkscape::Extension::Extension * ext) comp2op << "out"; comp2in1 << "offset"; comp2in2 << "SourceGraphic"; - } else if ((g_ascii_strcasecmp("innercut", type) == 0)){ + } else if ((g_ascii_strcasecmp("innercut", type) == 0)) { comp1op << "out"; comp1in1 << "flood"; comp1in2 << "SourceGraphic"; comp2op << "in"; - } else { //shadow + } else { // shadow comp1op << "in"; comp2op << "atop"; comp2in1 << "offset"; diff --git a/src/extension/internal/filter/textures.h b/src/extension/internal/filter/textures.h index 66066aeb9cdd1222f67f8f51c8bbb9b9a8bdc250..a88d9ed27aa84fa9da250dd00c81e1f820d4ee19 100644 --- a/src/extension/internal/filter/textures.h +++ b/src/extension/internal/filter/textures.h @@ -15,23 +15,21 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { namespace Internal { namespace Filter { - /** \brief Custom predefined Ink Blot filter. - + Inkblot on tissue or rough paper. - + Filter's parameters: * Turbulence type (enum, default fractalNoise else turbulence) -> turbulence (type) @@ -48,16 +46,24 @@ namespace Filter { * k2 (-10.->10., default -0.25) * k3 (-10.->10., default 0.5) */ -class InkBlot : public Inkscape::Extension::Internal::Filter::Filter { +class InkBlot : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - InkBlot ( ) : Filter() { }; - ~InkBlot ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + InkBlot() + : Filter(){}; + ~InkBlot() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } public: - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -97,14 +103,13 @@ public: "\n" "\n", new InkBlot()); // clang-format on - }; - + }; }; -gchar const * -InkBlot::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *InkBlot::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream type; std::ostringstream freq; @@ -128,7 +133,8 @@ InkBlot::get_filter_text (Inkscape::Extension::Extension * ext) const gchar *ope = ext->get_param_optiongroup("stroke"); if (g_ascii_strcasecmp("arithmetic", ope) == 0) { - custom << "k1=\"" << ext->get_param_float("k1") << "\" k2=\"" << ext->get_param_float("k2") << "\" k3=\"" << ext->get_param_float("k3") << "\""; + custom << "k1=\"" << ext->get_param_float("k1") << "\" k2=\"" << ext->get_param_float("k2") << "\" k3=\"" + << ext->get_param_float("k3") << "\""; } else { custom << ""; } @@ -149,11 +155,10 @@ InkBlot::get_filter_text (Inkscape::Extension::Extension * ext) custom.str().c_str(), stroke.str().c_str() ); // clang-format on - return _filter; + return _filter; }; /* Ink Blot filter */ - }; /* namespace Filter */ }; /* namespace Internal */ }; /* namespace Extension */ diff --git a/src/extension/internal/filter/transparency.h b/src/extension/internal/filter/transparency.h index 39cd240bb4173ce9acbd457ff9675f548184f3e1..8827fe5005f7c78535e208234b7a0a7a85bca102 100644 --- a/src/extension/internal/filter/transparency.h +++ b/src/extension/internal/filter/transparency.h @@ -19,11 +19,10 @@ */ /* ^^^ Change the copyright to be you and your e-mail address ^^^ */ -#include "filter.h" - +#include "extension/extension.h" #include "extension/internal/clear-n_.h" #include "extension/system.h" -#include "extension/extension.h" +#include "filter.h" namespace Inkscape { namespace Extension { @@ -32,7 +31,7 @@ namespace Filter { /** \brief Custom predefined Blend filter. - + Blend objects with background images or with themselves Filter's parameters: @@ -40,15 +39,23 @@ namespace Filter { * Mode (enum, all blend modes, default Multiply) -> blend (mode) */ -class Blend : public Inkscape::Extension::Internal::Filter::Filter { +class Blend : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Blend ( ) : Filter() { }; - ~Blend ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Blend() + : Filter(){}; + ~Blend() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -77,13 +84,12 @@ public: "\n", new Blend()); // clang-format on }; - }; -gchar const * -Blend::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Blend::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream source; std::ostringstream mode; @@ -103,7 +109,7 @@ Blend::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Channel transparency filter. - + Channel transparency filter. Filter's parameters: @@ -114,22 +120,30 @@ Blend::get_filter_text (Inkscape::Extension::Extension * ext) * Alpha (-10.->10., default 1.) -> colormatrix2 (values) * Flood colors (guint, default 16777215) -> flood (flood-opacity, flood-color) * Inverted (boolean, default false) -> composite1 (operator, true='in', false='out') - + Matrix: 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 R G B A 0 */ -class ChannelTransparency : public Inkscape::Extension::Internal::Filter::Filter { +class ChannelTransparency : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - ChannelTransparency ( ) : Filter() { }; - ~ChannelTransparency ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } - - static void init () { + ChannelTransparency() + : Filter(){}; + ~ChannelTransparency() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } + + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -154,10 +168,10 @@ public: }; }; -gchar const * -ChannelTransparency::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *ChannelTransparency::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream red; std::ostringstream green; @@ -175,7 +189,7 @@ ChannelTransparency::get_filter_text (Inkscape::Extension::Extension * ext) } else { invert << "xor"; } - + // clang-format off _filter = g_strdup_printf( "\n" @@ -190,7 +204,7 @@ ChannelTransparency::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined LightEraser filter. - + Make the lightest parts of the object progressively transparent. Filter's parameters: @@ -198,17 +212,25 @@ ChannelTransparency::get_filter_text (Inkscape::Extension::Extension * ext) * Erosion (1.->1000., default 100) -> colormatrix (first 3 values, multiplicator) * Global opacity (0.->1., default 1.) -> composite (k2) * Inverted (boolean, default false) -> colormatrix (values, true: first 3 values positive, 4th negative) - + */ -class LightEraser : public Inkscape::Extension::Internal::Filter::Filter { +class LightEraser : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - LightEraser ( ) : Filter() { }; - ~LightEraser ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } - - static void init () { + LightEraser() + : Filter(){}; + ~LightEraser() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } + + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -232,10 +254,10 @@ public: }; }; -gchar const * -LightEraser::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *LightEraser::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream expand; std::ostringstream erode; @@ -244,13 +266,11 @@ LightEraser::get_filter_text (Inkscape::Extension::Extension * ext) opacity << ext->get_param_float("opacity"); if (ext->get_param_bool("invert")) { - expand << (ext->get_param_float("erode") * 0.2125) << " " - << (ext->get_param_float("erode") * 0.7154) << " " + expand << (ext->get_param_float("erode") * 0.2125) << " " << (ext->get_param_float("erode") * 0.7154) << " " << (ext->get_param_float("erode") * 0.0721); erode << (-ext->get_param_float("expand")); } else { - expand << (-ext->get_param_float("erode") * 0.2125) << " " - << (-ext->get_param_float("erode") * 0.7154) << " " + expand << (-ext->get_param_float("erode") * 0.2125) << " " << (-ext->get_param_float("erode") * 0.7154) << " " << (-ext->get_param_float("erode") * 0.0721); erode << ext->get_param_float("expand"); } @@ -266,27 +286,34 @@ LightEraser::get_filter_text (Inkscape::Extension::Extension * ext) return _filter; }; /* Light Eraser filter */ - /** \brief Custom predefined Opacity filter. - + Set opacity and strength of opacity boundaries. Filter's parameters: * Expansion (0.->1000., default 5) -> colormatrix (last-1th value) * Erosion (0.->1000., default 1) -> colormatrix (last value) * Global opacity (0.->1., default 1.) -> composite (k2) - + */ -class Opacity : public Inkscape::Extension::Internal::Filter::Filter { +class Opacity : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Opacity ( ) : Filter() { }; - ~Opacity ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } - - static void init () { + Opacity() + : Filter(){}; + ~Opacity() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } + + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -309,18 +336,17 @@ public: }; }; -gchar const * -Opacity::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Opacity::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream matrix; std::ostringstream opacity; opacity << ext->get_param_float("opacity"); - matrix << (ext->get_param_float("expand")) << " " - << (-ext->get_param_float("erode")); + matrix << (ext->get_param_float("expand")) << " " << (-ext->get_param_float("erode")); // clang-format off _filter = g_strdup_printf( @@ -335,7 +361,7 @@ Opacity::get_filter_text (Inkscape::Extension::Extension * ext) /** \brief Custom predefined Silhouette filter. - + Repaint anything visible monochrome Filter's parameters: @@ -344,15 +370,23 @@ Opacity::get_filter_text (Inkscape::Extension::Extension * ext) * Color (guint, default 0,0,0,255) -> flood (flood-color, flood-opacity) */ -class Silhouette : public Inkscape::Extension::Internal::Filter::Filter { +class Silhouette : public Inkscape::Extension::Internal::Filter::Filter +{ protected: - gchar const * get_filter_text (Inkscape::Extension::Extension * ext) override; + gchar const *get_filter_text(Inkscape::Extension::Extension *ext) override; public: - Silhouette ( ) : Filter() { }; - ~Silhouette ( ) override { if (_filter != nullptr) g_free((void *)_filter); return; } + Silhouette() + : Filter(){}; + ~Silhouette() override + { + if (_filter != nullptr) + g_free((void *)_filter); + return; + } - static void init () { + static void init() + { // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -373,13 +407,12 @@ public: "\n", new Silhouette()); // clang-format on }; - }; -gchar const * -Silhouette::get_filter_text (Inkscape::Extension::Extension * ext) +gchar const *Silhouette::get_filter_text(Inkscape::Extension::Extension *ext) { - if (_filter != nullptr) g_free((void *)_filter); + if (_filter != nullptr) + g_free((void *)_filter); std::ostringstream a; std::ostringstream r; @@ -391,7 +424,7 @@ Silhouette::get_filter_text (Inkscape::Extension::Extension * ext) guint32 color = ext->get_param_color("color"); r << ((color >> 24) & 0xff); g << ((color >> 16) & 0xff); - b << ((color >> 8) & 0xff); + b << ((color >> 8) & 0xff); a << (color & 0xff) / 255.0F; if (ext->get_param_bool("cutout")) cutout << "out"; diff --git a/src/extension/internal/gdkpixbuf-input.cpp b/src/extension/internal/gdkpixbuf-input.cpp index 054a6a7587f8742ae5fa7c2b71357d6c3adef89e..35513249b2a84eabc8fafae197ba6c43e48132a9 100644 --- a/src/extension/internal/gdkpixbuf-input.cpp +++ b/src/extension/internal/gdkpixbuf-input.cpp @@ -8,31 +8,26 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "gdkpixbuf-input.h" #include #include #include #include #include - -#include "document.h" -#include "document-undo.h" -#include "gdkpixbuf-input.h" -#include "image-resolution.h" -#include "preferences.h" -#include "selection-chemistry.h" +#include #include "display/cairo-utils.h" - +#include "document-undo.h" +#include "document.h" #include "extension/input.h" #include "extension/system.h" - +#include "image-resolution.h" #include "io/dir-util.h" - #include "object/sp-image.h" #include "object/sp-root.h" - +#include "preferences.h" +#include "selection-chemistry.h" #include "util/units.h" namespace Inkscape { @@ -40,31 +35,30 @@ namespace Inkscape { namespace Extension { namespace Internal { -SPDocument * -GdkpixbufInput::open(Inkscape::Extension::Input *mod, char const *uri) +SPDocument *GdkpixbufInput::open(Inkscape::Extension::Input *mod, char const *uri) { // Determine whether the image should be embedded Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool ask = prefs->getBool( "/dialogs/import/ask"); - bool forcexdpi = prefs->getBool( "/dialogs/import/forcexdpi"); - Glib::ustring link = prefs->getString("/dialogs/import/link"); + bool ask = prefs->getBool("/dialogs/import/ask"); + bool forcexdpi = prefs->getBool("/dialogs/import/forcexdpi"); + Glib::ustring link = prefs->getString("/dialogs/import/link"); Glib::ustring scale = prefs->getString("/dialogs/import/scale"); // If we asked about import preferences, get values and update preferences. if (ask) { - ask = !mod->get_param_bool("do_not_ask"); + ask = !mod->get_param_bool("do_not_ask"); forcexdpi = (strcmp(mod->get_param_optiongroup("dpi"), "from_default") == 0); - link = mod->get_param_optiongroup("link"); - scale = mod->get_param_optiongroup("scale"); + link = mod->get_param_optiongroup("link"); + scale = mod->get_param_optiongroup("scale"); - prefs->setBool( "/dialogs/import/ask", ask ); - prefs->setBool( "/dialogs/import/forcexdpi", forcexdpi); - prefs->setString("/dialogs/import/link", link ); - prefs->setString("/dialogs/import/scale", scale ); + prefs->setBool("/dialogs/import/ask", ask); + prefs->setBool("/dialogs/import/forcexdpi", forcexdpi); + prefs->setString("/dialogs/import/link", link); + prefs->setString("/dialogs/import/scale", scale); } bool embed = (link == "embed"); - + SPDocument *doc = nullptr; std::unique_ptr pb(Inkscape::Pixbuf::create_from_file(uri)); @@ -78,19 +72,19 @@ GdkpixbufInput::open(Inkscape::Extension::Input *mod, char const *uri) double width = pb->width(); double height = pb->height(); - double defaultxdpi = prefs->getDouble("/dialogs/import/defaultxdpi/value", Inkscape::Util::Quantity::convert(1, "in", "px")); + double defaultxdpi = + prefs->getDouble("/dialogs/import/defaultxdpi/value", Inkscape::Util::Quantity::convert(1, "in", "px")); ImageResolution *ir = nullptr; double xscale = 1; double yscale = 1; - if (!ir && !forcexdpi) { ir = new ImageResolution(uri); } if (ir && ir->ok()) { - xscale = 960.0 / round(10.*ir->x()); // round-off to 0.1 dpi - yscale = 960.0 / round(10.*ir->y()); + xscale = 960.0 / round(10. * ir->x()); // round-off to 0.1 dpi + yscale = 960.0 / round(10. * ir->y()); // prevent crash on image with too small dpi (bug 1479193) if (ir->x() <= .05) xscale = 960.0; @@ -116,19 +110,19 @@ GdkpixbufInput::open(Inkscape::Extension::Input *mod, char const *uri) image_node->setAttribute("preserveAspectRatio", "none"); // This is actually 'image-rendering'. - if( scale.compare( "auto" ) != 0 ) { + if (scale.compare("auto") != 0) { SPCSSAttr *css = sp_repr_css_attr_new(); sp_repr_css_set_property(css, "image-rendering", scale.c_str()); sp_repr_css_set(image_node, css, "style"); - sp_repr_css_attr_unref( css ); + sp_repr_css_attr_unref(css); } if (embed) { sp_embed_image(image_node, pb.get()); } else { // convert filename to uri - gchar* _uri = g_filename_to_uri(uri, nullptr, nullptr); - if(_uri) { + gchar *_uri = g_filename_to_uri(uri, nullptr, nullptr); + if (_uri) { image_node->setAttribute("xlink:href", _uri); g_free(_uri); } else { @@ -145,13 +139,14 @@ GdkpixbufInput::open(Inkscape::Extension::Input *mod, char const *uri) Inkscape::GC::release(image_node); Inkscape::GC::release(layer_node); fit_canvas_to_drawing(doc); - + // Set viewBox if it doesn't exist if (!doc->getRoot()->viewBox_set) { // std::cerr << "Viewbox not set, setting" << std::endl; - doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), doc->getHeight().value(doc->getDisplayUnit()))); + doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), + doc->getHeight().value(doc->getDisplayUnit()))); } - + // restore undo, as now this document may be shown to the user if a bitmap was opened DocumentUndo::setUndoSensitive(doc, saved); } else { @@ -163,34 +158,32 @@ GdkpixbufInput::open(Inkscape::Extension::Input *mod, char const *uri) #include "clear-n_.h" -void -GdkpixbufInput::init() +void GdkpixbufInput::init() { - static std::vector< Gdk::PixbufFormat > formatlist = Gdk::Pixbuf::get_formats(); - for (auto i: formatlist) { + static std::vector formatlist = Gdk::Pixbuf::get_formats(); + for (auto i : formatlist) { GdkPixbufFormat *pixformat = i.gobj(); - gchar *name = gdk_pixbuf_format_get_name(pixformat); + gchar *name = gdk_pixbuf_format_get_name(pixformat); gchar *description = gdk_pixbuf_format_get_description(pixformat); - gchar **extensions = gdk_pixbuf_format_get_extensions(pixformat); - gchar **mimetypes = gdk_pixbuf_format_get_mime_types(pixformat); + gchar **extensions = gdk_pixbuf_format_get_extensions(pixformat); + gchar **mimetypes = gdk_pixbuf_format_get_mime_types(pixformat); for (int i = 0; extensions[i] != nullptr; i++) { - for (int j = 0; mimetypes[j] != nullptr; j++) { - - /* thanks but no thanks, we'll handle SVG extensions... */ - if (strcmp(extensions[i], "svg") == 0) { - continue; - } - if (strcmp(extensions[i], "svgz") == 0) { - continue; - } - if (strcmp(extensions[i], "svg.gz") == 0) { - continue; - } - gchar *caption = g_strdup_printf(_("%s bitmap image import"), name); - - // clang-format off + for (int j = 0; mimetypes[j] != nullptr; j++) { + /* thanks but no thanks, we'll handle SVG extensions... */ + if (strcmp(extensions[i], "svg") == 0) { + continue; + } + if (strcmp(extensions[i], "svgz") == 0) { + continue; + } + if (strcmp(extensions[i], "svg.gz") == 0) { + continue; + } + gchar *caption = g_strdup_printf(_("%s bitmap image import"), name); + + // clang-format off gchar *xmlString = g_strdup_printf( "\n" "%s\n" diff --git a/src/extension/internal/gdkpixbuf-input.h b/src/extension/internal/gdkpixbuf-input.h index 19807002581a71c4c9fdfc28d30dc5fdbbec1c10..26b4b2df816a0176dcc29b082db4ada678ea8dff 100644 --- a/src/extension/internal/gdkpixbuf-input.h +++ b/src/extension/internal/gdkpixbuf-input.h @@ -16,15 +16,16 @@ namespace Inkscape { namespace Extension { namespace Internal { -class GdkpixbufInput : Inkscape::Extension::Implementation::Implementation { +class GdkpixbufInput : Inkscape::Extension::Implementation::Implementation +{ public: - SPDocument *open(Inkscape::Extension::Input *mod, - char const *uri) override; + SPDocument *open(Inkscape::Extension::Input *mod, char const *uri) override; static void init(); }; -} } } /* namespace Inkscape, Extension, Implementation */ - +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* INKSCAPE_EXTENSION_INTERNAL_GDKPIXBUF_INPUT_H */ diff --git a/src/extension/internal/gimpgrad.cpp b/src/extension/internal/gimpgrad.cpp index c22d49827f546f78eaaaa7c2672198bbb89b478f..4008f6381a55613ff739b83d785d75da022f2e43 100644 --- a/src/extension/internal/gimpgrad.cpp +++ b/src/extension/internal/gimpgrad.cpp @@ -13,17 +13,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "gimpgrad.h" + #include -#include "io/sys.h" -#include "extension/system.h" -#include "svg/css-ostringstream.h" -#include "svg/svg-color.h" -#include "gimpgrad.h" -#include "streq.h" -#include "strneq.h" #include "document.h" #include "extension/extension.h" +#include "extension/system.h" +#include "io/sys.h" +#include "streq.h" +#include "strneq.h" +#include "svg/css-ostringstream.h" +#include "svg/svg-color.h" namespace Inkscape { namespace Extension { @@ -34,7 +35,7 @@ namespace Internal { \param module Unused \return Whether the load was successful */ -bool GimpGrad::load (Inkscape::Extension::Extension */*module*/) +bool GimpGrad::load(Inkscape::Extension::Extension * /*module*/) { // std::cout << "Hey, I'm loading!\n" << std::endl; return TRUE; @@ -45,7 +46,7 @@ bool GimpGrad::load (Inkscape::Extension::Extension */*module*/) \param module Unused \return None */ -void GimpGrad::unload (Inkscape::Extension::Extension */*module*/) +void GimpGrad::unload(Inkscape::Extension::Extension * /*module*/) { // std::cout << "Nooo! I'm being unloaded!" << std::endl; return; @@ -125,8 +126,7 @@ static Glib::ustring stop_svg(ColorRGBA const in_color, double const location) document using the \c sp_document_from_mem. That is then returned to Inkscape. */ -SPDocument * -GimpGrad::open (Inkscape::Extension::Input */*module*/, gchar const *filename) +SPDocument *GimpGrad::open(Inkscape::Extension::Input * /*module*/, gchar const *filename) { Inkscape::IO::dump_fopen_call(filename, "I"); FILE *gradient = Inkscape::IO::fopen_utf8name(filename, "r"); @@ -167,8 +167,7 @@ GimpGrad::open (Inkscape::Extension::Input */*module*/, gchar const *filename) } char *endptr = nullptr; long const n_segs = strtol(tempstr, &endptr, 10); - if ((*endptr != '\n') - || n_segs < 1) { + if ((*endptr != '\n') || n_segs < 1) { /* SVG gradients are allowed to have zero stops (treated as `none'), but gimp 2.2 * requires at least one segment (i.e. at least two stops) (see gimp_gradient_load in * gimpgradient-load.c). We try to use the same error handling as gimp, so that @@ -183,7 +182,7 @@ GimpGrad::open (Inkscape::Extension::Input */*module*/, gchar const *filename) while (fgets(tempstr, 1024, gradient) != nullptr) { double dbls[3 + 4 + 4]; gchar *p = tempstr; - for (double & dbl : dbls) { + for (double &dbl : dbls) { gchar *end = nullptr; double const xi = g_ascii_strtod(p, &end); if (!end || end == p || !g_ascii_isspace(*end)) { @@ -219,7 +218,7 @@ GimpGrad::open (Inkscape::Extension::Input */*module*/, gchar const *filename) * sRGB space (or whatever the default in SVG is). See gimp/app/core/gimpgradient.c * for how gimp uses these. We could use gimp functions to sample at a few points, and * add some intermediate stops to convert to the linear/sRGB interpolation */ - int type; /* enum: linear, curved, sine, sphere increasing, sphere decreasing. */ + int type; /* enum: linear, curved, sine, sphere increasing, sphere decreasing. */ int color_interpolation; /* enum: rgb, hsv anticlockwise, hsv clockwise. */ if (sscanf(p, "%8d %8d", &type, &color_interpolation) != 2) { continue; @@ -262,7 +261,7 @@ error: #include "clear-n_.h" -void GimpGrad::init () +void GimpGrad::init() { // clang-format off Inkscape::Extension::build_from_mem( @@ -280,7 +279,9 @@ void GimpGrad::init () return; } -} } } /* namespace Internal; Extension; Inkscape */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/internal/gimpgrad.h b/src/extension/internal/gimpgrad.h index 8daadefeb9612524c57c101d6cad45bd21948dcf..3c8e3b6da7536a4edeb0e2b3d8b73200f10f1fb1 100644 --- a/src/extension/internal/gimpgrad.h +++ b/src/extension/internal/gimpgrad.h @@ -33,7 +33,6 @@ public: static void init(); }; - } // namespace Internal } // namespace Extension } // namespace Inkscape diff --git a/src/extension/internal/grid.cpp b/src/extension/internal/grid.cpp index 971290541c1183eed872213d8704c470714bd5de..a7d3460f416b9757c3f24301d1745a5df01087c1 100644 --- a/src/extension/internal/grid.cpp +++ b/src/extension/internal/grid.cpp @@ -12,25 +12,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "grid.h" + #include +#include #include +#include "2geom/geom.h" #include "desktop.h" - #include "document.h" -#include "selection.h" -#include "2geom/geom.h" - -#include "svg/path-string.h" - #include "extension/effect.h" #include "extension/system.h" - +#include "selection.h" +#include "svg/path-string.h" #include "util/units.h" -#include "grid.h" - namespace Inkscape { namespace Extension { namespace Internal { @@ -40,8 +36,7 @@ namespace Internal { \param module Unused \return Whether the load was successful */ -bool -Grid::load (Inkscape::Extension::Extension */*module*/) +bool Grid::load(Inkscape::Extension::Extension * /*module*/) { // std::cout << "Hey, I'm Grid, I'm loading!" << std::endl; return TRUE; @@ -49,24 +44,21 @@ Grid::load (Inkscape::Extension::Extension */*module*/) namespace { -Glib::ustring build_lines(Geom::Rect bounding_area, - Geom::Point const &offset, Geom::Point const &spacing) +Glib::ustring build_lines(Geom::Rect bounding_area, Geom::Point const &offset, Geom::Point const &spacing) { Geom::Point point_offset(0.0, 0.0); SVG::PathString path_data; - for ( int axis = Geom::X ; axis <= Geom::Y ; ++axis ) { + for (int axis = Geom::X; axis <= Geom::Y; ++axis) { point_offset[axis] = offset[axis]; for (Geom::Point start_point = bounding_area.min(); - start_point[axis] + offset[axis] <= (bounding_area.max())[axis]; - start_point[axis] += spacing[axis]) { + start_point[axis] + offset[axis] <= (bounding_area.max())[axis]; start_point[axis] += spacing[axis]) { Geom::Point end_point = start_point; - end_point[1-axis] = (bounding_area.max())[1-axis]; + end_point[1 - axis] = (bounding_area.max())[1 - axis]; - path_data.moveTo(start_point + point_offset) - .lineTo(end_point + point_offset); + path_data.moveTo(start_point + point_offset).lineTo(end_point + point_offset); } } // std::cout << "Path data:" << path_data.c_str() << std::endl; @@ -80,17 +72,17 @@ Glib::ustring build_lines(Geom::Rect bounding_area, \param module The effect that was called (unused) \param document What should be edited. */ -void -Grid::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) +void Grid::effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, + Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) { - Inkscape::Selection * selection = ((SPDesktop *)document)->selection; + Inkscape::Selection *selection = ((SPDesktop *)document)->selection; - Geom::Rect bounding_area = Geom::Rect(Geom::Point(0,0), Geom::Point(100,100)); + Geom::Rect bounding_area = Geom::Rect(Geom::Point(0, 0), Geom::Point(100, 100)); if (selection->isEmpty()) { /* get page size */ - SPDocument * doc = document->doc(); - bounding_area = Geom::Rect( Geom::Point(0,0), - Geom::Point(doc->getWidth().value("px"), doc->getHeight().value("px")) ); + SPDocument *doc = document->doc(); + bounding_area = + Geom::Rect(Geom::Point(0, 0), Geom::Point(doc->getWidth().value("px"), doc->getHeight().value("px"))); } else { Geom::OptRect bounds = selection->visualBounds(); if (bounds) { @@ -105,20 +97,18 @@ Grid::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::View *doc double scale = document->doc()->getDocumentScale().inverse()[Geom::X]; bounding_area *= Geom::Scale(scale); - Geom::Point spacings( scale * module->get_param_float("xspacing"), - scale * module->get_param_float("yspacing") ); + Geom::Point spacings(scale * module->get_param_float("xspacing"), scale * module->get_param_float("yspacing")); gdouble line_width = scale * module->get_param_float("lineWidth"); - Geom::Point offsets( scale * module->get_param_float("xoffset"), - scale * module->get_param_float("yoffset") ); + Geom::Point offsets(scale * module->get_param_float("xoffset"), scale * module->get_param_float("yoffset")); Glib::ustring path_data(""); path_data = build_lines(bounding_area, offsets, spacings); - Inkscape::XML::Document * xml_doc = document->doc()->getReprDoc(); + Inkscape::XML::Document *xml_doc = document->doc()->getReprDoc(); - //XML Tree being used directly here while it shouldn't be. - Inkscape::XML::Node * current_layer = static_cast(document)->currentLayer()->getRepr(); - Inkscape::XML::Node * path = xml_doc->createElement("svg:path"); + // XML Tree being used directly here while it shouldn't be. + Inkscape::XML::Node *current_layer = static_cast(document)->currentLayer()->getRepr(); + Inkscape::XML::Node *path = xml_doc->createElement("svg:path"); path->setAttribute("d", path_data); @@ -131,22 +121,27 @@ Grid::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::View *doc } /** \brief A class to make an adjustment that uses Extension params */ -class PrefAdjustment : public Gtk::Adjustment { +class PrefAdjustment : public Gtk::Adjustment +{ /** Extension that this relates to */ - Inkscape::Extension::Extension * _ext; + Inkscape::Extension::Extension *_ext; /** The string which represents the parameter */ - char * _pref; + char *_pref; + public: /** \brief Make the adjustment using an extension and the string describing the parameter. */ - PrefAdjustment(Inkscape::Extension::Extension * ext, char * pref) : - Gtk::Adjustment(0.0, 0.0, 10.0, 0.1), _ext(ext), _pref(pref) { + PrefAdjustment(Inkscape::Extension::Extension *ext, char *pref) + : Gtk::Adjustment(0.0, 0.0, 10.0, 0.1) + , _ext(ext) + , _pref(pref) + { this->set_value(_ext->get_param_float(_pref)); this->signal_value_changed().connect(sigc::mem_fun(this, &PrefAdjustment::val_changed)); return; }; - void val_changed (); + void val_changed(); }; /* class PrefAdjustment */ /** \brief A function to respond to the value_changed signal from the @@ -155,8 +150,7 @@ public: This function just grabs the value from the adjustment and writes it to the parameter. Very simple, but yet beautiful. */ -void -PrefAdjustment::val_changed () +void PrefAdjustment::val_changed() { // std::cout << "Value Changed to: " << this->get_value() << std::endl; _ext->set_param_float(_pref, this->get_value()); @@ -169,13 +163,14 @@ PrefAdjustment::val_changed () Uses AutoGUI for creating the GUI. */ -Gtk::Widget * -Grid::prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View * view, sigc::signal * changeSignal, Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) +Gtk::Widget *Grid::prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *view, + sigc::signal *changeSignal, + Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) { - SPDocument * current_document = view->doc(); + SPDocument *current_document = view->doc(); - auto selected = ((SPDesktop *) view)->getSelection()->items(); - Inkscape::XML::Node * first_select = nullptr; + auto selected = ((SPDesktop *)view)->getSelection()->items(); + Inkscape::XML::Node *first_select = nullptr; if (!selected.empty()) { first_select = selected.front()->getRepr(); } @@ -185,8 +180,7 @@ Grid::prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View #include "clear-n_.h" -void -Grid::init () +void Grid::init() { // clang-format off Inkscape::Extension::build_from_mem( diff --git a/src/extension/internal/grid.h b/src/extension/internal/grid.h index 16f4cd76ea7a591ca20a6a78ee8d16bb14c71410..5ef83ee4f5b98910f15a482a819ecb7371b69a45 100644 --- a/src/extension/internal/grid.h +++ b/src/extension/internal/grid.h @@ -21,14 +21,17 @@ namespace Internal { /** \brief Implementation class of the GIMP gradient plugin. This mostly just creates a namespace for the GIMP gradient plugin today. */ -class Grid : public Inkscape::Extension::Implementation::Implementation { - +class Grid : public Inkscape::Extension::Implementation::Implementation +{ public: bool load(Inkscape::Extension::Extension *module) override; - void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, Inkscape::Extension::Implementation::ImplementationDocumentCache * docCache) override; - Gtk::Widget * prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View * view, sigc::signal * changeSignal, Inkscape::Extension::Implementation::ImplementationDocumentCache * docCache) override; + void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, + Inkscape::Extension::Implementation::ImplementationDocumentCache *docCache) override; + Gtk::Widget *prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *view, + sigc::signal *changeSignal, + Inkscape::Extension::Implementation::ImplementationDocumentCache *docCache) override; - static void init (); + static void init(); }; }; /* namespace Internal */ diff --git a/src/extension/internal/image-resolution.cpp b/src/extension/internal/image-resolution.cpp index 3ca596c27d40c81c2c4e1b0661835903fb93ff33..929579f57042d2a696899eb2313f864b065ad5be 100644 --- a/src/extension/internal/image-resolution.cpp +++ b/src/extension/internal/image-resolution.cpp @@ -9,26 +9,26 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include "util/units.h" #include "image-resolution.h" +#include "util/units.h" #define IR_TRY_PNG 1 #include #ifdef HAVE_EXIF -#include #include +#include #endif #define IR_TRY_EXIV 0 #ifdef HAVE_JPEG #define IR_TRY_JFIF 1 -#include #include +#include #endif #ifdef WITH_MAGICK @@ -38,20 +38,22 @@ #define noIMAGE_RESOLUTION_DEBUG #ifdef IMAGE_RESOLUTION_DEBUG -# define debug(f, a...) { g_print("%s(%d) %s:", \ - __FILE__,__LINE__,__FUNCTION__); \ - g_print(f, ## a); \ - g_print("\n"); \ - } +#define debug(f, a...) \ + { \ + g_print("%s(%d) %s:", __FILE__, __LINE__, __FUNCTION__); \ + g_print(f, ##a); \ + g_print("\n"); \ + } #else -# define debug(f, a...) /* */ +#define debug(f, a...) /* */ #endif namespace Inkscape { namespace Extension { namespace Internal { -ImageResolution::ImageResolution(char const *fn) { +ImageResolution::ImageResolution(char const *fn) +{ ok_ = false; readpng(fn); @@ -69,30 +71,32 @@ ImageResolution::ImageResolution(char const *fn) { } } -bool ImageResolution::ok() const { +bool ImageResolution::ok() const +{ return ok_; } -double ImageResolution::x() const { +double ImageResolution::x() const +{ return x_; } -double ImageResolution::y() const { +double ImageResolution::y() const +{ return y_; } - - #if IR_TRY_PNG - -static bool haspngheader(FILE *fp) { + +static bool haspngheader(FILE *fp) +{ unsigned char header[8]; - if ( fread(header, 1, 8, fp) != 8 ) { + if (fread(header, 1, 8, fp) != 8) { return false; } fseek(fp, 0, SEEK_SET); - + if (png_sig_cmp(header, 0, 8)) { return false; } @@ -101,9 +105,10 @@ static bool haspngheader(FILE *fp) { } // Implementation using libpng -void ImageResolution::readpng(char const *fn) { +void ImageResolution::readpng(char const *fn) +{ FILE *fp = fopen(fn, "rb"); - if (!fp) + if (!fp) return; if (!haspngheader(fp)) { @@ -112,15 +117,15 @@ void ImageResolution::readpng(char const *fn) { } png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); - if (!png_ptr) + if (!png_ptr) return; - + png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, nullptr, nullptr); return; } - + if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); fclose(fp); @@ -137,8 +142,8 @@ void ImageResolution::readpng(char const *fn) { res_y = png_get_y_pixels_per_inch(png_ptr, info_ptr); if (res_x != 0 && res_y != 0) { ok_ = true; - x_ = res_x * 1.0; // FIXME: implicit conversion of png_uint_32 to double ok? - y_ = res_y * 1.0; // FIXME: implicit conversion of png_uint_32 to double ok? + x_ = res_x * 1.0; // FIXME: implicit conversion of png_uint_32 to double ok? + y_ = res_y * 1.0; // FIXME: implicit conversion of png_uint_32 to double ok? } #else debug("PNG_RESOLUTION_METER"); @@ -167,14 +172,14 @@ void ImageResolution::readpng(char const *fn) { #else // Dummy implementation -void ImageResolution::readpng(char const *) { -} +void ImageResolution::readpng(char const *) {} #endif #if IR_TRY_EXIF -static double exifDouble(ExifEntry *entry, ExifByteOrder byte_order) { +static double exifDouble(ExifEntry *entry, ExifByteOrder byte_order) +{ switch (entry->format) { case EXIF_FORMAT_BYTE: { return double(entry->data[0]); @@ -215,24 +220,25 @@ static double exifDouble(ExifEntry *entry, ExifByteOrder byte_order) { } // Implementation using libexif -void ImageResolution::readexif(char const *fn) { +void ImageResolution::readexif(char const *fn) +{ ExifData *ed; ed = exif_data_new_from_file(fn); if (!ed) return; - + ExifByteOrder byte_order = exif_data_get_byte_order(ed); - + ExifEntry *xres = exif_content_get_entry(ed->ifd[EXIF_IFD_0], EXIF_TAG_X_RESOLUTION); ExifEntry *yres = exif_content_get_entry(ed->ifd[EXIF_IFD_0], EXIF_TAG_Y_RESOLUTION); ExifEntry *unit = exif_content_get_entry(ed->ifd[EXIF_IFD_0], EXIF_TAG_RESOLUTION_UNIT); - - if ( xres && yres ) { + + if (xres && yres) { x_ = exifDouble(xres, byte_order); y_ = exifDouble(yres, byte_order); if (unit) { double u = exifDouble(unit, byte_order); - if ( u == 3 ) { + if (u == 3) { x_ *= 2.54; y_ *= 2.54; } @@ -240,7 +246,7 @@ void ImageResolution::readexif(char const *fn) { ok_ = true; } exif_data_free(ed); - + if (ok_) { debug("xdpi: %f", x_); debug("ydpi: %f", y_); @@ -252,14 +258,14 @@ void ImageResolution::readexif(char const *fn) { #else // Dummy implementation -void ImageResolution::readexif(char const *) { -} - +void ImageResolution::readexif(char const *) {} + #endif - + #if IR_TRY_EXIV -void ImageResolution::readexiv(char const *fn) { +void ImageResolution::readexiv(char const *fn) +{ Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(fn); if (!image.get()) return; @@ -277,27 +283,27 @@ void ImageResolution::readexiv(char const *fn) { for (Exiv2::ExifData::const_iterator i = exifData.begin(); i != end; ++i) { if (ok_) break; - if ( i->tag() == 0x011a ) { + if (i->tag() == 0x011a) { // X Resolution x_ = i->toFloat(); havex = true; - } else if ( i->tag() == 0x011b ) { + } else if (i->tag() == 0x011b) { // Y Resolution y_ = i->toFloat(); havey = true; - } else if ( i->tag() == 0x0128 ) { + } else if (i->tag() == 0x0128) { unit = i->toLong(); } ok_ = havex && havey && haveunit; } if (haveunit) { - if ( unit == 3 ) { + if (unit == 3) { x_ *= 2.54; y_ *= 2.54; } } ok_ = havex && havey; - + if (ok_) { debug("xdpi: %f", x_); debug("ydpi: %f", y_); @@ -309,30 +315,27 @@ void ImageResolution::readexiv(char const *fn) { #else // Dummy implementation -void ImageResolution::readexiv(char const *) { -} +void ImageResolution::readexiv(char const *) {} #endif #if IR_TRY_JFIF -static void irjfif_error_exit(j_common_ptr cinfo) { - longjmp(*(jmp_buf*)cinfo->client_data, 1); +static void irjfif_error_exit(j_common_ptr cinfo) +{ + longjmp(*(jmp_buf *)cinfo->client_data, 1); } -static void irjfif_emit_message(j_common_ptr, int) { -} +static void irjfif_emit_message(j_common_ptr, int) {} -static void irjfif_output_message(j_common_ptr) { -} +static void irjfif_output_message(j_common_ptr) {} -static void irjfif_format_message(j_common_ptr, char *) { -} +static void irjfif_format_message(j_common_ptr, char *) {} -static void irjfif_reset(j_common_ptr) { -} +static void irjfif_reset(j_common_ptr) {} -void ImageResolution::readjfif(char const *fn) { +void ImageResolution::readjfif(char const *fn) +{ FILE *ifd = fopen(fn, "rb"); if (!ifd) { return; @@ -347,7 +350,7 @@ void ImageResolution::readjfif(char const *fn) { jpeg_destroy_decompress(&cinfo); return; } - + cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jerr.error_exit = &irjfif_error_exit; @@ -355,18 +358,18 @@ void ImageResolution::readjfif(char const *fn) { jerr.output_message = &irjfif_output_message; jerr.format_message = &irjfif_format_message; jerr.reset_error_mgr = &irjfif_reset; - cinfo.client_data = (void*)&jbuf; + cinfo.client_data = (void *)&jbuf; jpeg_stdio_src(&cinfo, ifd); jpeg_read_header(&cinfo, TRUE); - + debug("cinfo.[XY]_density"); - if (cinfo.saw_JFIF_marker) { // JFIF APP0 marker was seen - if ( cinfo.density_unit == 1 ) { // dots/inch + if (cinfo.saw_JFIF_marker) { // JFIF APP0 marker was seen + if (cinfo.density_unit == 1) { // dots/inch x_ = cinfo.X_density; y_ = cinfo.Y_density; ok_ = true; - } else if ( cinfo.density_unit == 2 ) { // dots/cm + } else if (cinfo.density_unit == 2) { // dots/cm x_ = cinfo.X_density * 2.54; y_ = cinfo.Y_density * 2.54; ok_ = true; @@ -380,7 +383,7 @@ void ImageResolution::readjfif(char const *fn) { } jpeg_destroy_decompress(&cinfo); fclose(ifd); - + if (ok_) { debug("xdpi: %f", x_); debug("ydpi: %f", y_); @@ -392,21 +395,21 @@ void ImageResolution::readjfif(char const *fn) { #else // Dummy implementation -void ImageResolution::readjfif(char const *) { -} +void ImageResolution::readjfif(char const *) {} #endif #ifdef WITH_MAGICK -void ImageResolution::readmagick(char const *fn) { +void ImageResolution::readmagick(char const *fn) +{ Magick::Image image; debug("Trying image.read"); try { image.read(fn); - } catch (Magick::Error & err) { + } catch (Magick::Error &err) { debug("ImageMagick error: %s", err.what()); return; - } catch (std::exception & err) { + } catch (std::exception &err) { debug("ImageResolution::readmagick: %s", err.what()); return; } @@ -415,12 +418,12 @@ void ImageResolution::readmagick(char const *fn) { x_ = image.xResolution(); y_ = image.yResolution(); -// TODO: find out why the hell the following conversion is necessary + // TODO: find out why the hell the following conversion is necessary if (type == "BMP") { x_ = Inkscape::Util::Quantity::convert(x_, "in", "cm"); y_ = Inkscape::Util::Quantity::convert(y_, "in", "cm"); } - + if (x_ != 0 && y_ != 0) { ok_ = true; } @@ -437,11 +440,10 @@ void ImageResolution::readmagick(char const *fn) { #else // Dummy implementation -void ImageResolution::readmagick(char const *) { -} +void ImageResolution::readmagick(char const *) {} #endif /* WITH_MAGICK */ -} -} -} +} // namespace Internal +} // namespace Extension +} // namespace Inkscape diff --git a/src/extension/internal/image-resolution.h b/src/extension/internal/image-resolution.h index ad69df031b8f0fbf01a104ee5215d3e119624f22..bbcf4f9880c375a9b9dd1dada2bb3278b51d2753 100644 --- a/src/extension/internal/image-resolution.h +++ b/src/extension/internal/image-resolution.h @@ -8,7 +8,6 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #ifndef IMAGE_RESOLUTION_H #define IMAGE_RESOLUTION_H @@ -17,16 +16,19 @@ namespace Inkscape { namespace Extension { namespace Internal { -class ImageResolution { +class ImageResolution +{ public: ImageResolution(char const *fn); bool ok() const; double x() const; double y() const; + private: bool ok_; double x_; double y_; + private: void readpng(char const *fn); void readexif(char const *fn); @@ -35,8 +37,8 @@ private: void readmagick(char const *fn); }; -} -} -} +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif diff --git a/src/extension/internal/latex-pstricks-out.cpp b/src/extension/internal/latex-pstricks-out.cpp index 824f3825ab998038524152fe99c508490beec3b8..179daa3ea48115ec62f7f81ee865d7b989719b0d 100644 --- a/src/extension/internal/latex-pstricks-out.cpp +++ b/src/extension/internal/latex-pstricks-out.cpp @@ -11,27 +11,26 @@ */ #include "latex-pstricks-out.h" -#include -#include "extension/system.h" -#include "extension/print.h" -#include "extension/db.h" -#include "display/drawing.h" -#include "object/sp-root.h" +#include +#include "display/drawing.h" #include "document.h" - +#include "extension/db.h" +#include "extension/print.h" +#include "extension/system.h" +#include "object/sp-root.h" namespace Inkscape { namespace Extension { namespace Internal { -LatexOutput::LatexOutput () // The null constructor +LatexOutput::LatexOutput() // The null constructor { return; } -LatexOutput::~LatexOutput () //The destructor +LatexOutput::~LatexOutput() // The destructor { return; } @@ -42,15 +41,14 @@ bool LatexOutput::check(Inkscape::Extension::Extension * /*module*/) return result; } - void LatexOutput::save(Inkscape::Extension::Output * /*mod2*/, SPDocument *doc, gchar const *filename) { SPPrintContext context; doc->ensureUpToDate(); Inkscape::Extension::Print *mod = Inkscape::Extension::get_print(SP_MODULE_KEY_PRINT_LATEX); - const gchar * oldconst = mod->get_param_string("destination"); - gchar * oldoutput = g_strdup(oldconst); + const gchar *oldconst = mod->get_param_string("destination"); + gchar *oldoutput = g_strdup(oldconst); mod->set_param_string("destination", filename); // Start @@ -84,8 +82,7 @@ void LatexOutput::save(Inkscape::Extension::Output * /*mod2*/, SPDocument *doc, calls the extension system with the memory allocated XML that describes the data. */ -void -LatexOutput::init () +void LatexOutput::init() { // clang-format off Inkscape::Extension::build_from_mem( @@ -104,7 +101,9 @@ LatexOutput::init () return; } -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/internal/latex-pstricks-out.h b/src/extension/internal/latex-pstricks-out.h index 670904b1045567a135992c43b64bc3547c3e44b0..8d65934acb8665aa09323d3c0eea3e67031b585f 100644 --- a/src/extension/internal/latex-pstricks-out.h +++ b/src/extension/internal/latex-pstricks-out.h @@ -18,23 +18,25 @@ namespace Inkscape { namespace Extension { namespace Internal { -class LatexOutput : Inkscape::Extension::Implementation::Implementation { //This is a derived class - +class LatexOutput : Inkscape::Extension::Implementation::Implementation +{ // This is a derived class + public: LatexOutput(); // Empty constructor - ~LatexOutput() override;//Destructor + ~LatexOutput() override; // Destructor - bool check(Inkscape::Extension::Extension *module) override; //Can this module load (always yes for now) + bool check(Inkscape::Extension::Extension *module) override; // Can this module load (always yes for now) void save(Inkscape::Extension::Output *mod, // Save the given document to the given filename - SPDocument *doc, - gchar const *filename) override; + SPDocument *doc, gchar const *filename) override; - static void init();//Initialize the class + static void init(); // Initialize the class }; -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* EXTENSION_INTERNAL_LATEX_OUT_H */ diff --git a/src/extension/internal/latex-pstricks.cpp b/src/extension/internal/latex-pstricks.cpp index 0933fe450c6c56cff9cb2d698cee9227c0f4c0c3..3de1168a432260f43d78fc5d50dc2f9e707115c0 100644 --- a/src/extension/internal/latex-pstricks.cpp +++ b/src/extension/internal/latex-pstricks.cpp @@ -11,43 +11,44 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "latex-pstricks.h" + +#include <2geom/curves.h> #include <2geom/pathvector.h> #include <2geom/sbasis-to-bezier.h> -#include <2geom/curves.h> #include #include -#include "util/units.h" -#include "helper/geom-curves.h" +#include +#include "document.h" #include "extension/print.h" #include "extension/system.h" +#include "helper/geom-curves.h" #include "inkscape-version.h" #include "io/sys.h" -#include "latex-pstricks.h" #include "style.h" -#include "document.h" -#include +#include "util/units.h" namespace Inkscape { namespace Extension { namespace Internal { -PrintLatex::PrintLatex (): - _width(0), - _height(0), - _stream(nullptr) -{ -} +PrintLatex::PrintLatex() + : _width(0) + , _height(0) + , _stream(nullptr) +{} -PrintLatex::~PrintLatex () +PrintLatex::~PrintLatex() { - if (_stream) fclose(_stream); + if (_stream) + fclose(_stream); - /* restore default signal handling for SIGPIPE */ + /* restore default signal handling for SIGPIPE */ #if !defined(_WIN32) && !defined(__WIN32__) - (void) signal(SIGPIPE, SIG_DFL); + (void)signal(SIGPIPE, SIG_DFL); #endif - return; + return; } unsigned int PrintLatex::setup(Inkscape::Extension::Print * /*mod*/) @@ -55,20 +56,19 @@ unsigned int PrintLatex::setup(Inkscape::Extension::Print * /*mod*/) return TRUE; } -unsigned int PrintLatex::begin (Inkscape::Extension::Print *mod, SPDocument *doc) +unsigned int PrintLatex::begin(Inkscape::Extension::Print *mod, SPDocument *doc) { Inkscape::SVGOStringStream os; int res; FILE *osf = nullptr; - const gchar * fn = nullptr; + const gchar *fn = nullptr; gsize bytesRead = 0; gsize bytesWritten = 0; - GError* error = nullptr; + GError *error = nullptr; os.setf(std::ios::fixed); fn = mod->get_param_string("destination"); - gchar* local_fn = g_filename_from_utf8( fn, - -1, &bytesRead, &bytesWritten, &error); + gchar *local_fn = g_filename_from_utf8(fn, -1, &bytesRead, &bytesWritten, &error); fn = local_fn; /* TODO: Replace the below fprintf's with something that does the right thing whether in @@ -77,7 +77,8 @@ unsigned int PrintLatex::begin (Inkscape::Extension::Print *mod, SPDocument *doc * return code. */ if (fn != nullptr) { - while (isspace(*fn)) fn += 1; + while (isspace(*fn)) + fn += 1; Inkscape::IO::dump_fopen_call(fn, "K"); osf = Inkscape::IO::fopen_utf8name(fn, "w+"); if (!osf) { @@ -92,7 +93,7 @@ unsigned int PrintLatex::begin (Inkscape::Extension::Print *mod, SPDocument *doc /* fixme: this is kinda icky */ #if !defined(_WIN32) && !defined(__WIN32__) - (void) signal(SIGPIPE, SIG_IGN); + (void)signal(SIGPIPE, SIG_IGN); #endif res = fprintf(_stream, "%%LaTeX with PSTricks extensions\n"); @@ -100,8 +101,7 @@ unsigned int PrintLatex::begin (Inkscape::Extension::Print *mod, SPDocument *doc if (fflush(_stream)) { /*g_print("caught error in sp_module_print_plain_begin\n");*/ if (ferror(_stream)) { - g_print("Error %d on output stream: %s\n", errno, - g_strerror(errno)); + g_print("Error %d on output stream: %s\n", errno, g_strerror(errno)); } g_print("Printing failed\n"); /* fixme: should use pclose() for pipes */ @@ -116,7 +116,6 @@ unsigned int PrintLatex::begin (Inkscape::Extension::Print *mod, SPDocument *doc _height = doc->getHeight().value("pt"); if (res >= 0) { - os << "%%Creator: Inkscape " << Inkscape::version_string << "\n"; os << "%%Please note this file requires PSTricks extensions\n"; @@ -126,7 +125,8 @@ unsigned int PrintLatex::begin (Inkscape::Extension::Print *mod, SPDocument *doc os << "\\begin{pspicture}(" << doc->getWidth().value("px") << "," << doc->getHeight().value("px") << ")\n"; } - m_tr_stack.push( Geom::Scale(1, -1) * Geom::Translate(0, doc->getHeight().value("px"))); /// @fixme hardcoded doc2dt transform + m_tr_stack.push(Geom::Scale(1, -1) * Geom::Translate(0, doc->getHeight().value("px"))); /// @fixme hardcoded doc2dt + /// transform return fprintf(_stream, "%s", os.str().c_str()); } @@ -163,19 +163,18 @@ unsigned int PrintLatex::release(Inkscape::Extension::Print * /*mod*/) return 1; } -unsigned int PrintLatex::comment(Inkscape::Extension::Print * /*mod*/, - const char * comment) +unsigned int PrintLatex::comment(Inkscape::Extension::Print * /*mod*/, const char *comment) { if (!_stream) { return 0; // XXX: fixme, returning -1 as unsigned. } - return fprintf(_stream, "%%! %s\n",comment); + return fprintf(_stream, "%%! %s\n", comment); } -unsigned int PrintLatex::fill(Inkscape::Extension::Print * /*mod*/, - Geom::PathVector const &pathv, Geom::Affine const &transform, SPStyle const *style, - Geom::OptRect const & /*pbox*/, Geom::OptRect const & /*dbox*/, Geom::OptRect const & /*bbox*/) +unsigned int PrintLatex::fill(Inkscape::Extension::Print * /*mod*/, Geom::PathVector const &pathv, + Geom::Affine const &transform, SPStyle const *style, Geom::OptRect const & /*pbox*/, + Geom::OptRect const & /*dbox*/, Geom::OptRect const & /*bbox*/) { if (!_stream) { return 0; // XXX: fixme, returning -1 as unsigned. @@ -188,12 +187,12 @@ unsigned int PrintLatex::fill(Inkscape::Extension::Print * /*mod*/, os.setf(std::ios::fixed); - fill_opacity=SP_SCALE24_TO_FLOAT(style->fill_opacity.value); + fill_opacity = SP_SCALE24_TO_FLOAT(style->fill_opacity.value); style->fill.value.color.get_rgb_floatv(rgb); os << "{\n\\newrgbcolor{curcolor}{" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "}\n"; os << "\\pscustom[linestyle=none,fillstyle=solid,fillcolor=curcolor"; - if (fill_opacity!=1.0) { - os << ",opacity="<stroke_opacity.value); + stroke_opacity = SP_SCALE24_TO_FLOAT(style->stroke_opacity.value); style->stroke.value.color.get_rgb_floatv(rgb); os << "{\n\\newrgbcolor{curcolor}{" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "}\n"; - os << "\\pscustom[linewidth=" << style->stroke_width.computed*scale<< ",linecolor=curcolor"; + os << "\\pscustom[linewidth=" << style->stroke_width.computed * scale << ",linecolor=curcolor"; - if (stroke_opacity!=1.0) { - os<<",strokeopacity="<stroke_dasharray.values.size(); i++) { if ((i)) { @@ -244,7 +243,7 @@ unsigned int PrintLatex::stroke(Inkscape::Extension::Print * /*mod*/, } } - os <<"]\n{\n"; + os << "]\n{\n"; print_pathvector(os, pathv, transform); @@ -257,61 +256,54 @@ unsigned int PrintLatex::stroke(Inkscape::Extension::Print * /*mod*/, } // FIXME: why is 'transform' argument not used? -void -PrintLatex::print_pathvector(SVGOStringStream &os, Geom::PathVector const &pathv_in, const Geom::Affine & /*transform*/) +void PrintLatex::print_pathvector(SVGOStringStream &os, Geom::PathVector const &pathv_in, + const Geom::Affine & /*transform*/) { if (pathv_in.empty()) return; -// Geom::Affine tf=transform; // why was this here? - Geom::Affine tf_stack=m_tr_stack.top(); // and why is transform argument not used? - Geom::PathVector pathv = pathv_in * tf_stack; // generates new path, which is a bit slow, but this doesn't have to be performance optimized + // Geom::Affine tf=transform; // why was this here? + Geom::Affine tf_stack = m_tr_stack.top(); // and why is transform argument not used? + Geom::PathVector pathv = pathv_in * tf_stack; // generates new path, which is a bit slow, but this doesn't have to + // be performance optimized os << "\\newpath\n"; - for(const auto & it : pathv) { - + for (const auto &it : pathv) { os << "\\moveto(" << it.initialPoint()[Geom::X] << "," << it.initialPoint()[Geom::Y] << ")\n"; - for(Geom::Path::const_iterator cit = it.begin(); cit != it.end_open(); ++cit) { + for (Geom::Path::const_iterator cit = it.begin(); cit != it.end_open(); ++cit) { print_2geomcurve(os, *cit); } if (it.closed()) { os << "\\closepath\n"; } - } } -void -PrintLatex::print_2geomcurve(SVGOStringStream &os, Geom::Curve const &c) +void PrintLatex::print_2geomcurve(SVGOStringStream &os, Geom::Curve const &c) { using Geom::X; using Geom::Y; - if( is_straight_curve(c) ) - { + if (is_straight_curve(c)) { os << "\\lineto(" << c.finalPoint()[X] << "," << c.finalPoint()[Y] << ")\n"; - } - else if(Geom::CubicBezier const *cubic_bezier = dynamic_cast(&c)) { + } else if (Geom::CubicBezier const *cubic_bezier = dynamic_cast(&c)) { std::vector points = cubic_bezier->controlPoints(); - os << "\\curveto(" << points[1][X] << "," << points[1][Y] << ")(" - << points[2][X] << "," << points[2][Y] << ")(" - << points[3][X] << "," << points[3][Y] << ")\n"; - } - else { - //this case handles sbasis as well as all other curve types + os << "\\curveto(" << points[1][X] << "," << points[1][Y] << ")(" << points[2][X] << "," << points[2][Y] << ")(" + << points[3][X] << "," << points[3][Y] << ")\n"; + } else { + // this case handles sbasis as well as all other curve types Geom::Path sbasis_path = Geom::cubicbezierpath_from_sbasis(c.toSBasis(), 0.1); - for(const auto & iter : sbasis_path) { + for (const auto &iter : sbasis_path) { print_2geomcurve(os, iter); } } } -bool -PrintLatex::textToPath(Inkscape::Extension::Print * ext) +bool PrintLatex::textToPath(Inkscape::Extension::Print *ext) { return ext->get_param_bool("textToPath"); } @@ -333,9 +325,9 @@ void PrintLatex::init() // clang-format on } -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ /* Local Variables: @@ -347,4 +339,3 @@ void PrintLatex::init() End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - diff --git a/src/extension/internal/latex-pstricks.h b/src/extension/internal/latex-pstricks.h index 37d08b82137228f54566d93950f29a4f6063b327..1d48711d5d5dc70d87caa1514a1d6fd0bf7c4e70 100644 --- a/src/extension/internal/latex-pstricks.h +++ b/src/extension/internal/latex-pstricks.h @@ -15,57 +15,54 @@ #include -#include "extension/implementation/implementation.h" #include "extension/extension.h" - +#include "extension/implementation/implementation.h" #include "svg/stringstream.h" namespace Inkscape { namespace Extension { namespace Internal { -class PrintLatex : public Inkscape::Extension::Implementation::Implementation { +class PrintLatex : public Inkscape::Extension::Implementation::Implementation +{ + float _width; + float _height; + FILE *_stream; - float _width; - float _height; - FILE * _stream; - std::stack m_tr_stack; void print_pathvector(SVGOStringStream &os, Geom::PathVector const &pathv_in, const Geom::Affine & /*transform*/); - void print_2geomcurve(SVGOStringStream &os, Geom::Curve const & c ); + void print_2geomcurve(SVGOStringStream &os, Geom::Curve const &c); public: - PrintLatex (); - ~PrintLatex () override; - - /* Print functions */ - unsigned int setup (Inkscape::Extension::Print * module) override; - - unsigned int begin (Inkscape::Extension::Print * module, SPDocument *doc) override; - unsigned int finish (Inkscape::Extension::Print * module) override; - - /* Rendering methods */ - unsigned int bind(Inkscape::Extension::Print *module, Geom::Affine const &transform, float opacity) override; - unsigned int release(Inkscape::Extension::Print *module) override; - - unsigned int fill (Inkscape::Extension::Print *module, Geom::PathVector const &pathv, - Geom::Affine const &ctm, SPStyle const *style, - Geom::OptRect const &pbox, Geom::OptRect const &dbox, - Geom::OptRect const &bbox) override; - unsigned int stroke (Inkscape::Extension::Print *module, Geom::PathVector const &pathv, - Geom::Affine const &ctm, SPStyle const *style, - Geom::OptRect const &pbox, Geom::OptRect const &dbox, - Geom::OptRect const &bbox) override; - unsigned int comment(Inkscape::Extension::Print *module, const char * comment) override; - bool textToPath (Inkscape::Extension::Print * ext) override; - - static void init (); + PrintLatex(); + ~PrintLatex() override; + + /* Print functions */ + unsigned int setup(Inkscape::Extension::Print *module) override; + + unsigned int begin(Inkscape::Extension::Print *module, SPDocument *doc) override; + unsigned int finish(Inkscape::Extension::Print *module) override; + + /* Rendering methods */ + unsigned int bind(Inkscape::Extension::Print *module, Geom::Affine const &transform, float opacity) override; + unsigned int release(Inkscape::Extension::Print *module) override; + + unsigned int fill(Inkscape::Extension::Print *module, Geom::PathVector const &pathv, Geom::Affine const &ctm, + SPStyle const *style, Geom::OptRect const &pbox, Geom::OptRect const &dbox, + Geom::OptRect const &bbox) override; + unsigned int stroke(Inkscape::Extension::Print *module, Geom::PathVector const &pathv, Geom::Affine const &ctm, + SPStyle const *style, Geom::OptRect const &pbox, Geom::OptRect const &dbox, + Geom::OptRect const &bbox) override; + unsigned int comment(Inkscape::Extension::Print *module, const char *comment) override; + bool textToPath(Inkscape::Extension::Print *ext) override; + + static void init(); }; -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* __INKSCAPE_EXTENSION_INTERNAL_PRINT_LATEX */ diff --git a/src/extension/internal/latex-text-renderer.cpp b/src/extension/internal/latex-text-renderer.cpp index c8b2d7425c4f4e49e58d44332d2a2e37158e1ca7..8c9da8a4f3ca2eb133239ba913cbc0fd83a6eac2 100644 --- a/src/extension/internal/latex-text-renderer.cpp +++ b/src/extension/internal/latex-text-renderer.cpp @@ -18,48 +18,41 @@ #include "latex-text-renderer.h" -#include +#include <2geom/rect.h> +#include <2geom/transforms.h> #include - +#include #include #include +#include "document.h" +#include "extension/output.h" +#include "extension/system.h" +#include "inkscape-version.h" +#include "io/sys.h" #include "libnrtype/Layout-TNG.h" -#include <2geom/transforms.h> -#include <2geom/rect.h> - -#include "object/sp-item.h" +#include "object/sp-flowtext.h" #include "object/sp-item-group.h" +#include "object/sp-item.h" +#include "object/sp-rect.h" #include "object/sp-root.h" -#include "object/sp-use.h" #include "object/sp-text.h" -#include "object/sp-flowtext.h" -#include "object/sp-rect.h" +#include "object/sp-use.h" #include "style.h" - #include "text-editing.h" - #include "util/units.h" -#include "extension/output.h" -#include "extension/system.h" - -#include "inkscape-version.h" -#include "io/sys.h" -#include "document.h" - namespace Inkscape { namespace Extension { namespace Internal { /** * This method is called by the PDF, EPS and PS output extensions. - * @param filename This should be the filename without '_tex' extension to which the tex code should be written. Output goes to _tex, note the underscore instead of period. + * @param filename This should be the filename without '_tex' extension to which the tex code should be written. Output + * goes to _tex, note the underscore instead of period. */ -bool -latex_render_document_text_to_file( SPDocument *doc, gchar const *filename, - const gchar * const exportId, bool exportDrawing, bool exportCanvas, float bleedmargin_px, - bool pdflatex) +bool latex_render_document_text_to_file(SPDocument *doc, gchar const *filename, const gchar *const exportId, + bool exportDrawing, bool exportCanvas, float bleedmargin_px, bool pdflatex) { doc->ensureUpToDate(); @@ -75,8 +68,7 @@ latex_render_document_text_to_file( SPDocument *doc, gchar const *filename, } root->cropToObject(base); // TODO: This is inconsistent in CLI (should only happen for --export-id-only) pageBoundingBox = exportCanvas; - } - else { + } else { // we want to export the entire document from root base = root; pageBoundingBox = !exportDrawing; @@ -103,11 +95,11 @@ latex_render_document_text_to_file( SPDocument *doc, gchar const *filename, } LaTeXTextRenderer::LaTeXTextRenderer(bool pdflatex) - : _stream(nullptr), - _filename(nullptr), - _pdflatex(pdflatex), - _omittext_state(EMPTY), - _omittext_page(1) + : _stream(nullptr) + , _filename(nullptr) + , _pdflatex(pdflatex) + , _omittext_state(EMPTY) + , _omittext_page(1) { push_transform(Geom::identity()); } @@ -122,7 +114,7 @@ LaTeXTextRenderer::~LaTeXTextRenderer() /* restore default signal handling for SIGPIPE */ #if !defined(_WIN32) && !defined(__WIN32__) - (void) signal(SIGPIPE, SIG_DFL); + (void)signal(SIGPIPE, SIG_DFL); #endif if (_filename) { @@ -135,10 +127,11 @@ LaTeXTextRenderer::~LaTeXTextRenderer() /** This should create the output LaTeX file, and assign it to _stream. * @return Returns true when successful */ -bool -LaTeXTextRenderer::setTargetFile(gchar const *filename) { +bool LaTeXTextRenderer::setTargetFile(gchar const *filename) +{ if (filename != nullptr) { - while (isspace(*filename)) filename += 1; + while (isspace(*filename)) + filename += 1; _filename = g_path_get_basename(filename); @@ -156,7 +149,7 @@ LaTeXTextRenderer::setTargetFile(gchar const *filename) { /* fixme: this is kinda icky */ #if !defined(_WIN32) && !defined(__WIN32__) - (void) signal(SIGPIPE, SIG_IGN); + (void)signal(SIGPIPE, SIG_IGN); #endif fprintf(_stream, "%%%% Creator: Inkscape %s, www.inkscape.org\n", Inkscape::version_string); @@ -166,8 +159,7 @@ LaTeXTextRenderer::setTargetFile(gchar const *filename) { /* flush this to test output stream as early as possible */ if (fflush(_stream)) { if (ferror(_stream)) { - g_print("Error %d on LaTeX file output stream: %s\n", errno, - g_strerror(errno)); + g_print("Error %d on LaTeX file output stream: %s\n", errno, g_strerror(errno)); } g_print("Output to LaTeX file failed\n"); /* fixme: should use pclose() for pipes */ @@ -182,63 +174,61 @@ LaTeXTextRenderer::setTargetFile(gchar const *filename) { return true; } -static char const preamble[] = -"%% To include the image in your LaTeX document, write\n" -"%% \\input{.pdf_tex}\n" -"%% instead of\n" -"%% \\includegraphics{.pdf}\n" -"%% To scale the image, write\n" -"%% \\def\\svgwidth{}\n" -"%% \\input{.pdf_tex}\n" -"%% instead of\n" -"%% \\includegraphics[width=]{.pdf}\n" -"%%\n" -"%% Images with a different path to the parent latex file can\n" -"%% be accessed with the `import' package (which may need to be\n" -"%% installed) using\n" -"%% \\usepackage{import}\n" -"%% in the preamble, and then including the image with\n" -"%% \\import{}{.pdf_tex}\n" -"%% Alternatively, one can specify\n" -"%% \\graphicspath{{/}}\n" -"%% \n" -"%% For more information, please see info/svg-inkscape on CTAN:\n" -"%% http://tug.ctan.org/tex-archive/info/svg-inkscape\n" -"%%\n" -"\\begingroup%\n" -" \\makeatletter%\n" -" \\providecommand\\color[2][]{%\n" -" \\errmessage{(Inkscape) Color is used for the text in Inkscape, but the package \'color.sty\' is not loaded}%\n" -" \\renewcommand\\color[2][]{}%\n" -" }%\n" -" \\providecommand\\transparent[1]{%\n" -" \\errmessage{(Inkscape) Transparency is used (non-zero) for the text in Inkscape, but the package \'transparent.sty\' is not loaded}%\n" -" \\renewcommand\\transparent[1]{}%\n" -" }%\n" -" \\providecommand\\rotatebox[2]{#2}%\n" -" \\newcommand*\\fsize{\\dimexpr\\f@size pt\\relax}%\n" -" \\newcommand*\\lineheight[1]{\\fontsize{\\fsize}{#1\\fsize}\\selectfont}%\n"; - -static char const postamble[] = -" \\end{picture}%\n" -"\\endgroup%\n"; - -void -LaTeXTextRenderer::writePreamble() +static char const preamble[] = "%% To include the image in your LaTeX document, write\n" + "%% \\input{.pdf_tex}\n" + "%% instead of\n" + "%% \\includegraphics{.pdf}\n" + "%% To scale the image, write\n" + "%% \\def\\svgwidth{}\n" + "%% \\input{.pdf_tex}\n" + "%% instead of\n" + "%% \\includegraphics[width=]{.pdf}\n" + "%%\n" + "%% Images with a different path to the parent latex file can\n" + "%% be accessed with the `import' package (which may need to be\n" + "%% installed) using\n" + "%% \\usepackage{import}\n" + "%% in the preamble, and then including the image with\n" + "%% \\import{}{.pdf_tex}\n" + "%% Alternatively, one can specify\n" + "%% \\graphicspath{{/}}\n" + "%% \n" + "%% For more information, please see info/svg-inkscape on CTAN:\n" + "%% http://tug.ctan.org/tex-archive/info/svg-inkscape\n" + "%%\n" + "\\begingroup%\n" + " \\makeatletter%\n" + " \\providecommand\\color[2][]{%\n" + " \\errmessage{(Inkscape) Color is used for the text in Inkscape, but the package " + "\'color.sty\' is not loaded}%\n" + " \\renewcommand\\color[2][]{}%\n" + " }%\n" + " \\providecommand\\transparent[1]{%\n" + " \\errmessage{(Inkscape) Transparency is used (non-zero) for the text in Inkscape, " + "but the package \'transparent.sty\' is not loaded}%\n" + " \\renewcommand\\transparent[1]{}%\n" + " }%\n" + " \\providecommand\\rotatebox[2]{#2}%\n" + " \\newcommand*\\fsize{\\dimexpr\\f@size pt\\relax}%\n" + " \\newcommand*\\lineheight[1]{\\fontsize{\\fsize}{#1\\fsize}\\selectfont}%\n"; + +static char const postamble[] = " \\end{picture}%\n" + "\\endgroup%\n"; + +void LaTeXTextRenderer::writePreamble() { fprintf(_stream, "%s", preamble); } -void -LaTeXTextRenderer::writePostamble() +void LaTeXTextRenderer::writePostamble() { fprintf(_stream, "%s", postamble); } void LaTeXTextRenderer::sp_group_render(SPGroup *group) { - std::vector l = (group->childList(false)); - for(auto x : l){ - SPItem *item = dynamic_cast(x); + std::vector l = (group->childList(false)); + for (auto x : l) { + SPItem *item = dynamic_cast(x); if (item) { renderItem(item); } @@ -274,7 +264,7 @@ void LaTeXTextRenderer::sp_text_render(SPText *textobj) // Only PDFLaTeX supports importing a single page of a graphics file, // so only PDF backend gets interleaved text/graphics - if (_pdflatex && _omittext_state == GRAPHIC_ON_TOP) + if (_pdflatex && _omittext_state == GRAPHIC_ON_TOP) _omittext_state = NEW_PAGE_ON_GRAPHIC; SPStyle *style = textobj->style; @@ -285,19 +275,19 @@ void LaTeXTextRenderer::sp_text_render(SPText *textobj) gchar const *alignment = nullptr; gchar const *aligntabular = nullptr; switch (style->text_anchor.computed) { - case SP_CSS_TEXT_ANCHOR_START: - alignment = "[lt]"; - aligntabular = "{l}"; - break; - case SP_CSS_TEXT_ANCHOR_END: - alignment = "[rt]"; - aligntabular = "{r}"; - break; - case SP_CSS_TEXT_ANCHOR_MIDDLE: - default: - alignment = "[t]"; - aligntabular = "{c}"; - break; + case SP_CSS_TEXT_ANCHOR_START: + alignment = "[lt]"; + aligntabular = "{l}"; + break; + case SP_CSS_TEXT_ANCHOR_END: + alignment = "[rt]"; + aligntabular = "{r}"; + break; + case SP_CSS_TEXT_ANCHOR_MIDDLE: + default: + alignment = "[t]"; + aligntabular = "{c}"; + break; } Geom::Point anchor = textobj->attributes.firstXY() * transform(); Geom::Point pos(anchor); @@ -325,8 +315,8 @@ void LaTeXTextRenderer::sp_text_render(SPText *textobj) // get rotation Geom::Affine i2doc = textobj->i2doc_affine(); Geom::Affine wotransl = i2doc.withoutTranslation(); - double degrees = -180/M_PI * Geom::atan2(wotransl.xAxis()); - bool has_rotation = !Geom::are_near(degrees,0.); + double degrees = -180 / M_PI * Geom::atan2(wotransl.xAxis()); + bool has_rotation = !Geom::are_near(degrees, 0.); // get line-height float line_height; @@ -359,72 +349,75 @@ void LaTeXTextRenderer::sp_text_render(SPText *textobj) os << "\\smash{"; os << "\\begin{tabular}[t]" << aligntabular; - // Walk through all spans in the text object. - // Write span strings to LaTeX, associated with font weight and style. - Inkscape::Text::Layout const &layout = *(te_get_layout (textobj)); - for (Inkscape::Text::Layout::iterator li = layout.begin(), le = layout.end(); - li != le; li.nextStartOfSpan()) - { - Inkscape::Text::Layout::iterator ln = li; - ln.nextStartOfSpan(); - Glib::ustring uspanstr = sp_te_get_string_multiline (textobj, li, ln); - - // escape ampersands - uspanstr = Glib::Regex::create("&")->replace_literal(uspanstr, 0, "\\&", (Glib::RegexMatchFlags)0); - // escape percent - uspanstr = Glib::Regex::create("%")->replace_literal(uspanstr, 0, "\\%", (Glib::RegexMatchFlags)0); - - const gchar *spanstr = uspanstr.c_str(); - if (!spanstr) { - continue; - } + // Walk through all spans in the text object. + // Write span strings to LaTeX, associated with font weight and style. + Inkscape::Text::Layout const &layout = *(te_get_layout(textobj)); + for (Inkscape::Text::Layout::iterator li = layout.begin(), le = layout.end(); li != le; li.nextStartOfSpan()) { + Inkscape::Text::Layout::iterator ln = li; + ln.nextStartOfSpan(); + Glib::ustring uspanstr = sp_te_get_string_multiline(textobj, li, ln); + + // escape ampersands + uspanstr = Glib::Regex::create("&")->replace_literal(uspanstr, 0, "\\&", (Glib::RegexMatchFlags)0); + // escape percent + uspanstr = Glib::Regex::create("%")->replace_literal(uspanstr, 0, "\\%", (Glib::RegexMatchFlags)0); + + const gchar *spanstr = uspanstr.c_str(); + if (!spanstr) { + continue; + } - bool is_bold = false, is_italic = false, is_oblique = false; - - // newline character only -> don't attempt to add style (will break compilation in LaTeX) - if (g_strcmp0(spanstr, "\n")) { - SPStyle const &spanstyle = *(sp_te_style_at_position (textobj, li)); - if (spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_500 || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_600 || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_700 || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_800 || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_900 || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_BOLD || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_BOLDER) - { - is_bold = true; - os << "\\textbf{"; - } - if (spanstyle.font_style.computed == SP_CSS_FONT_STYLE_ITALIC) - { - is_italic = true; - os << "\\textit{"; - } - if (spanstyle.font_style.computed == SP_CSS_FONT_STYLE_OBLIQUE) - { - is_oblique = true; - os << "\\textsl{"; // this is an accurate choice if the LaTeX chosen font matches the font in Inkscape. Gives bad results when it is not so... - } - } + bool is_bold = false, is_italic = false, is_oblique = false; - // replace carriage return with double slash - gchar ** splitstr = g_strsplit(spanstr, "\n", 2); - os << splitstr[0]; - if (g_strv_length(splitstr) > 1) - { - os << "\\\\"; + // newline character only -> don't attempt to add style (will break compilation in LaTeX) + if (g_strcmp0(spanstr, "\n")) { + SPStyle const &spanstyle = *(sp_te_style_at_position(textobj, li)); + if (spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_500 || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_600 || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_700 || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_800 || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_900 || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_BOLD || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_BOLDER) { + is_bold = true; + os << "\\textbf{"; } - g_strfreev(splitstr); + if (spanstyle.font_style.computed == SP_CSS_FONT_STYLE_ITALIC) { + is_italic = true; + os << "\\textit{"; + } + if (spanstyle.font_style.computed == SP_CSS_FONT_STYLE_OBLIQUE) { + is_oblique = true; + os << "\\textsl{"; // this is an accurate choice if the LaTeX chosen font matches the font in Inkscape. + // Gives bad results when it is not so... + } + } - if (is_oblique) { os << "}"; } // oblique end - if (is_italic) { os << "}"; } // italic end - if (is_bold) { os << "}"; } // bold end + // replace carriage return with double slash + gchar **splitstr = g_strsplit(spanstr, "\n", 2); + os << splitstr[0]; + if (g_strv_length(splitstr) > 1) { + os << "\\\\"; } + g_strfreev(splitstr); + + if (is_oblique) { + os << "}"; + } // oblique end + if (is_italic) { + os << "}"; + } // italic end + if (is_bold) { + os << "}"; + } // bold end + } os << "\\end{tabular}"; // tabular end - os << "}"; // smash end - if (has_rotation) { os << "}"; } // rotatebox end - os << "}"; //makebox end + os << "}"; // smash end + if (has_rotation) { + os << "}"; + } // rotatebox end + os << "}"; // makebox end os << "}%\n"; // put end fprintf(_stream, "%s", os.str().c_str()); @@ -432,14 +425,14 @@ void LaTeXTextRenderer::sp_text_render(SPText *textobj) void LaTeXTextRenderer::sp_flowtext_render(SPFlowtext *flowtext) { -/* -Flowtext is possible by using a minipage! :) -Flowing in rectangle is possible, not in arb shape. -*/ + /* + Flowtext is possible by using a minipage! :) + Flowing in rectangle is possible, not in arb shape. + */ // Only PDFLaTeX supports importing a single page of a graphics file, // so only PDF backend gets interleaved text/graphics - if (_pdflatex && _omittext_state == GRAPHIC_ON_TOP) + if (_pdflatex && _omittext_state == GRAPHIC_ON_TOP) _omittext_state = NEW_PAGE_ON_GRAPHIC; SPStyle *style = flowtext->style; @@ -451,7 +444,7 @@ Flowing in rectangle is possible, not in arb shape. return; // don't know how to handle non-rect frames yet. is quite uncommon for latex users i think } - // We will transform the coordinates + // We will transform the coordinates Geom::Rect framebox = frame->getRect(); // get position and alignment @@ -459,23 +452,23 @@ Flowing in rectangle is possible, not in arb shape. gchar const *alignment = "[lt]"; gchar const *justification = ""; switch (flowtext->layout.paragraphAlignment(flowtext->layout.begin())) { - case Inkscape::Text::Layout::LEFT: - justification = "\\raggedright "; - break; - case Inkscape::Text::Layout::RIGHT: - justification = "\\raggedleft "; - break; - case Inkscape::Text::Layout::CENTER: - justification = "\\centering "; - case Inkscape::Text::Layout::FULL: - default: - // no need to add LaTeX code for standard justified output :) - break; - } - - // The topleft Corner was calculated after rotating the text which results in a wrong Coordinate. - // Now, the topleft Corner is rotated after calculating it - Geom::Point pos(framebox.corner(0) * transform()); //topleft corner + case Inkscape::Text::Layout::LEFT: + justification = "\\raggedright "; + break; + case Inkscape::Text::Layout::RIGHT: + justification = "\\raggedleft "; + break; + case Inkscape::Text::Layout::CENTER: + justification = "\\centering "; + case Inkscape::Text::Layout::FULL: + default: + // no need to add LaTeX code for standard justified output :) + break; + } + + // The topleft Corner was calculated after rotating the text which results in a wrong Coordinate. + // Now, the topleft Corner is rotated after calculating it + Geom::Point pos(framebox.corner(0) * transform()); // topleft corner // determine color and transparency (for now, use rgb color model as it is most native to Inkscape) bool has_color = false; // if the item has no color set, don't force black color @@ -500,8 +493,8 @@ Flowing in rectangle is possible, not in arb shape. // get rotation Geom::Affine i2doc = flowtext->i2doc_affine(); Geom::Affine wotransl = i2doc.withoutTranslation(); - double degrees = -180/M_PI * Geom::atan2(wotransl.xAxis()); - bool has_rotation = !Geom::are_near(degrees,0.); + double degrees = -180 / M_PI * Geom::atan2(wotransl.xAxis()); + bool has_rotation = !Geom::are_near(degrees, 0.); // write to LaTeX Inkscape::SVGOStringStream os; @@ -519,65 +512,67 @@ Flowing in rectangle is possible, not in arb shape. } os << "\\makebox(0,0)" << alignment << "{"; - // Scale the x width correctly + // Scale the x width correctly os << "\\begin{minipage}{" << framebox.width() * transform().expansionX() << "\\unitlength}"; os << justification; - // Walk through all spans in the text object. - // Write span strings to LaTeX, associated with font weight and style. - Inkscape::Text::Layout const &layout = *(te_get_layout(flowtext)); - for (Inkscape::Text::Layout::iterator li = layout.begin(), le = layout.end(); - li != le; li.nextStartOfSpan()) - { - SPStyle const &spanstyle = *(sp_te_style_at_position(flowtext, li)); - bool is_bold = false, is_italic = false, is_oblique = false; - - if (spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_500 || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_600 || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_700 || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_800 || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_900 || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_BOLD || - spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_BOLDER) - { - is_bold = true; - os << "\\textbf{"; - } - if (spanstyle.font_style.computed == SP_CSS_FONT_STYLE_ITALIC) - { - is_italic = true; - os << "\\textit{"; - } - if (spanstyle.font_style.computed == SP_CSS_FONT_STYLE_OBLIQUE) - { - is_oblique = true; - os << "\\textsl{"; // this is an accurate choice if the LaTeX chosen font matches the font in Inkscape. Gives bad results when it is not so... - } + // Walk through all spans in the text object. + // Write span strings to LaTeX, associated with font weight and style. + Inkscape::Text::Layout const &layout = *(te_get_layout(flowtext)); + for (Inkscape::Text::Layout::iterator li = layout.begin(), le = layout.end(); li != le; li.nextStartOfSpan()) { + SPStyle const &spanstyle = *(sp_te_style_at_position(flowtext, li)); + bool is_bold = false, is_italic = false, is_oblique = false; + + if (spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_500 || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_600 || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_700 || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_800 || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_900 || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_BOLD || + spanstyle.font_weight.computed == SP_CSS_FONT_WEIGHT_BOLDER) { + is_bold = true; + os << "\\textbf{"; + } + if (spanstyle.font_style.computed == SP_CSS_FONT_STYLE_ITALIC) { + is_italic = true; + os << "\\textit{"; + } + if (spanstyle.font_style.computed == SP_CSS_FONT_STYLE_OBLIQUE) { + is_oblique = true; + os << "\\textsl{"; // this is an accurate choice if the LaTeX chosen font matches the font in Inkscape. + // Gives bad results when it is not so... + } - Inkscape::Text::Layout::iterator ln = li; - ln.nextStartOfSpan(); - Glib::ustring uspanstr = sp_te_get_string_multiline(flowtext, li, ln); - const gchar *spanstr = uspanstr.c_str(); - if (!spanstr) { - continue; - } - // replace carriage return with double slash - gchar ** splitstr = g_strsplit(spanstr, "\n", -1); - gchar *spanstr_new = g_strjoinv("\\\\ ", splitstr); - os << spanstr_new; - g_strfreev(splitstr); - g_free(spanstr_new); - - if (is_oblique) { os << "}"; } // oblique end - if (is_italic) { os << "}"; } // italic end - if (is_bold) { os << "}"; } // bold end + Inkscape::Text::Layout::iterator ln = li; + ln.nextStartOfSpan(); + Glib::ustring uspanstr = sp_te_get_string_multiline(flowtext, li, ln); + const gchar *spanstr = uspanstr.c_str(); + if (!spanstr) { + continue; } + // replace carriage return with double slash + gchar **splitstr = g_strsplit(spanstr, "\n", -1); + gchar *spanstr_new = g_strjoinv("\\\\ ", splitstr); + os << spanstr_new; + g_strfreev(splitstr); + g_free(spanstr_new); + + if (is_oblique) { + os << "}"; + } // oblique end + if (is_italic) { + os << "}"; + } // italic end + if (is_bold) { + os << "}"; + } // bold end + } os << "\\end{minipage}"; if (has_rotation) { os << "}"; // rotatebox end } - os << "}"; //makebox end + os << "}"; // makebox end os << "}%\n"; // put end fprintf(_stream, "%s", os.str().c_str()); @@ -590,8 +585,7 @@ void LaTeXTextRenderer::sp_root_render(SPRoot *root) pop_transform(); } -void -LaTeXTextRenderer::sp_item_invoke_render(SPItem *item) +void LaTeXTextRenderer::sp_item_invoke_render(SPItem *item) { // Check item's visibility if (item->isHidden()) { @@ -626,32 +620,31 @@ LaTeXTextRenderer::sp_item_invoke_render(SPItem *item) _omittext_state = GRAPHIC_ON_TOP; } -void -LaTeXTextRenderer::renderItem(SPItem *item) +void LaTeXTextRenderer::renderItem(SPItem *item) { push_transform(item->transform); sp_item_invoke_render(item); pop_transform(); } -void -LaTeXTextRenderer::writeGraphicPage() { +void LaTeXTextRenderer::writeGraphicPage() +{ Inkscape::SVGOStringStream os; os.setf(std::ios::fixed); // no scientific notation // strip pathname, as it is probably desired. Having a specific path in the TeX file is not convenient. if (_pdflatex) - os << " \\put(0,0){\\includegraphics[width=\\unitlength,page=" << _omittext_page++ << "]{" << _filename << "}}%\n"; + os << " \\put(0,0){\\includegraphics[width=\\unitlength,page=" << _omittext_page++ << "]{" << _filename + << "}}%\n"; else os << " \\put(0,0){\\includegraphics[width=\\unitlength]{" << _filename << "}}%\n"; fprintf(_stream, "%s", os.str().c_str()); } -bool -LaTeXTextRenderer::setupDocument(SPDocument *doc, bool pageBoundingBox, float bleedmargin_px, SPItem *base) +bool LaTeXTextRenderer::setupDocument(SPDocument *doc, bool pageBoundingBox, float bleedmargin_px, SPItem *base) { -// The boundingbox calculation here should be exactly the same as the one by CairoRenderer::setupDocument ! + // The boundingbox calculation here should be exactly the same as the one by CairoRenderer::setupDocument ! if (!base) { base = doc->getRoot(); @@ -659,7 +652,7 @@ LaTeXTextRenderer::setupDocument(SPDocument *doc, bool pageBoundingBox, float bl Geom::Rect d; if (pageBoundingBox) { - d = Geom::Rect::from_xywh(Geom::Point(0,0), doc->getDimensions()); + d = Geom::Rect::from_xywh(Geom::Point(0, 0), doc->getDimensions()); } else { Geom::OptRect bbox = base->documentVisualBounds(); if (!bbox) { @@ -671,7 +664,7 @@ LaTeXTextRenderer::setupDocument(SPDocument *doc, bool pageBoundingBox, float bl d.expandBy(bleedmargin_px); // scale all coordinates, such that the width of the image is 1, this is convenient for scaling the image in LaTeX - double scale = 1/(d.width()); + double scale = 1 / (d.width()); double _width = d.width() * scale; double _height = d.height() * scale; push_transform(Geom::Translate(-d.corner(3)) * Geom::Scale(scale, -scale)); @@ -682,7 +675,8 @@ LaTeXTextRenderer::setupDocument(SPDocument *doc, bool pageBoundingBox, float bl // scaling of the image when including it in LaTeX os << " \\ifx\\svgwidth\\undefined%\n"; - os << " \\setlength{\\unitlength}{" << Inkscape::Util::Quantity::convert(d.width(), "px", "pt") << "bp}%\n"; // note: 'bp' is the Postscript pt unit in LaTeX, see LP bug #792384 + os << " \\setlength{\\unitlength}{" << Inkscape::Util::Quantity::convert(d.width(), "px", "pt") + << "bp}%\n"; // note: 'bp' is the Postscript pt unit in LaTeX, see LP bug #792384 os << " \\ifx\\svgscale\\undefined%\n"; os << " \\relax%\n"; os << " \\else%\n"; @@ -710,16 +704,14 @@ LaTeXTextRenderer::setupDocument(SPDocument *doc, bool pageBoundingBox, float bl return true; } -Geom::Affine const & -LaTeXTextRenderer::transform() +Geom::Affine const &LaTeXTextRenderer::transform() { return _transform_stack.top(); } -void -LaTeXTextRenderer::push_transform(Geom::Affine const &tr) +void LaTeXTextRenderer::push_transform(Geom::Affine const &tr) { - if(!_transform_stack.empty()){ + if (!_transform_stack.empty()) { Geom::Affine tr_top = _transform_stack.top(); _transform_stack.push(tr * tr_top); } else { @@ -727,15 +719,14 @@ LaTeXTextRenderer::push_transform(Geom::Affine const &tr) } } -void -LaTeXTextRenderer::pop_transform() +void LaTeXTextRenderer::pop_transform() { _transform_stack.pop(); } -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ /* Local Variables: diff --git a/src/extension/internal/latex-text-renderer.h b/src/extension/internal/latex-text-renderer.h index a96a2631a4e391fbf29163f439a4552a0ce7bd76..0bd8e20677f875d64fbb5bb3b599122085af5994 100644 --- a/src/extension/internal/latex-text-renderer.h +++ b/src/extension/internal/latex-text-renderer.h @@ -3,7 +3,7 @@ #define EXTENSION_INTERNAL_LATEX_TEXT_RENDERER_H_SEEN /** \file - * Declaration of LaTeXTextRenderer, used for rendering the accompanying LaTeX file when exporting to PDF/EPS/PS + LaTeX + * Declaration of LaTeXTextRenderer, used for rendering the accompanying LaTeX file when exporting to PDF/EPS/PS + LaTeX */ /* * Authors: @@ -14,10 +14,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "extension/extension.h" #include <2geom/affine.h> #include +#include "extension/extension.h" + class SPItem; class SPRoot; class SPGroup; @@ -29,11 +30,11 @@ namespace Inkscape { namespace Extension { namespace Internal { -bool latex_render_document_text_to_file(SPDocument *doc, gchar const *filename, - const gchar * const exportId, bool exportDrawing, bool exportCanvas, float bleedmargin_px, - bool pdflatex); +bool latex_render_document_text_to_file(SPDocument *doc, gchar const *filename, const gchar *const exportId, + bool exportDrawing, bool exportCanvas, float bleedmargin_px, bool pdflatex); -class LaTeXTextRenderer { +class LaTeXTextRenderer +{ public: LaTeXTextRenderer(bool pdflatex); virtual ~LaTeXTextRenderer(); @@ -48,14 +49,15 @@ public: void renderItem(SPItem *item); protected: - enum LaTeXOmitTextPageState { + enum LaTeXOmitTextPageState + { EMPTY, GRAPHIC_ON_TOP, NEW_PAGE_ON_GRAPHIC }; - FILE * _stream; - gchar * _filename; + FILE *_stream; + gchar *_filename; bool _pdflatex; /** true if outputting for pdfLaTeX*/ @@ -63,7 +65,7 @@ protected: gulong _omittext_page; void push_transform(Geom::Affine const &transform); - Geom::Affine const & transform(); + Geom::Affine const &transform(); void pop_transform(); std::stack _transform_stack; @@ -80,9 +82,9 @@ protected: void sp_flowtext_render(SPFlowtext *flowtext); }; -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* !EXTENSION_INTERNAL_LATEX_TEXT_RENDERER_H_SEEN */ diff --git a/src/extension/internal/metafile-inout.cpp b/src/extension/internal/metafile-inout.cpp index e657845e00ae6b857f5f31cde7611dd0be58208a..f51dca1d79a0465546eae09fdac31aa8e62ca4ef 100644 --- a/src/extension/internal/metafile-inout.cpp +++ b/src/extension/internal/metafile-inout.cpp @@ -9,25 +9,25 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "extension/internal/metafile-inout.h" // picks up PNG + #include #include #include #include #include "display/curve.h" -#include "extension/internal/metafile-inout.h" // picks up PNG -#include "extension/print.h" -#include "path-prefix.h" -#include "document.h" -#include "util/units.h" -#include "ui/shape-editor.h" #include "document-undo.h" +#include "document.h" +#include "extension/print.h" #include "inkscape.h" -#include "preferences.h" - -#include "object/sp-root.h" #include "object/sp-namedview.h" +#include "object/sp-root.h" +#include "path-prefix.h" +#include "preferences.h" #include "svg/stringstream.h" +#include "ui/shape-editor.h" +#include "util/units.h" namespace Inkscape { namespace Extension { @@ -51,106 +51,99 @@ gcc -Wall -o testpng testpng.c -lpng Originally here, but moved up #include +#include #include #include -#include */ - /* Given "bitmap", this returns the pixel of bitmap at the point ("x", "y"). */ -pixel_t * Metafile::pixel_at (bitmap_t * bitmap, int x, int y) +pixel_t *Metafile::pixel_at(bitmap_t *bitmap, int x, int y) { return bitmap->pixels + bitmap->width * y + x; } - /* Write "bitmap" to a PNG file specified by "path"; returns 0 on success, non-zero on error. */ -void -Metafile::my_png_write_data(png_structp png_ptr, png_bytep data, png_size_t length) +void Metafile::my_png_write_data(png_structp png_ptr, png_bytep data, png_size_t length) { - PMEMPNG p=(PMEMPNG)png_get_io_ptr(png_ptr); + PMEMPNG p = (PMEMPNG)png_get_io_ptr(png_ptr); size_t nsize = p->size + length; /* allocate or grow buffer */ - if(p->buffer){ p->buffer = (char *) realloc(p->buffer, nsize); } - else{ p->buffer = (char *) malloc(nsize); } + if (p->buffer) { + p->buffer = (char *)realloc(p->buffer, nsize); + } else { + p->buffer = (char *)malloc(nsize); + } - if(!p->buffer){ png_error(png_ptr, "Write Error"); } + if (!p->buffer) { + png_error(png_ptr, "Write Error"); + } /* copy new bytes to end of buffer */ memcpy(p->buffer + p->size, data, length); p->size += length; } -void Metafile::toPNG(PMEMPNG accum, int width, int height, const char *px){ +void Metafile::toPNG(PMEMPNG accum, int width, int height, const char *px) +{ bitmap_t bmStore; bitmap_t *bitmap = &bmStore; - accum->buffer=nullptr; // PNG constructed in memory will end up here, caller must free(). - accum->size=0; - bitmap->pixels=(pixel_t *)px; - bitmap->width = width; + accum->buffer = nullptr; // PNG constructed in memory will end up here, caller must free(). + accum->size = 0; + bitmap->pixels = (pixel_t *)px; + bitmap->width = width; bitmap->height = height; png_structp png_ptr = nullptr; png_infop info_ptr = nullptr; size_t x, y; - png_byte ** row_pointers = nullptr; + png_byte **row_pointers = nullptr; /* The following number is set by trial and error only. I cannot see where it it is documented in the libpng manual. */ int pixel_size = 3; int depth = 8; - png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); - if (png_ptr == nullptr){ - accum->buffer=nullptr; + png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); + if (png_ptr == nullptr) { + accum->buffer = nullptr; return; } - info_ptr = png_create_info_struct (png_ptr); - if (info_ptr == nullptr){ - png_destroy_write_struct (&png_ptr, &info_ptr); - accum->buffer=nullptr; + info_ptr = png_create_info_struct(png_ptr); + if (info_ptr == nullptr) { + png_destroy_write_struct(&png_ptr, &info_ptr); + accum->buffer = nullptr; return; } /* Set up error handling. */ - if (setjmp (png_jmpbuf (png_ptr))) { - png_destroy_write_struct (&png_ptr, &info_ptr); - accum->buffer=nullptr; + if (setjmp(png_jmpbuf(png_ptr))) { + png_destroy_write_struct(&png_ptr, &info_ptr); + accum->buffer = nullptr; return; } /* Set image attributes. */ - png_set_IHDR ( - png_ptr, - info_ptr, - bitmap->width, - bitmap->height, - depth, - PNG_COLOR_TYPE_RGB, - PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_DEFAULT, - PNG_FILTER_TYPE_DEFAULT - ); + png_set_IHDR(png_ptr, info_ptr, bitmap->width, bitmap->height, depth, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, + PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); /* Initialize rows of PNG. */ - row_pointers = (png_byte **) png_malloc (png_ptr, bitmap->height * sizeof (png_byte *)); + row_pointers = (png_byte **)png_malloc(png_ptr, bitmap->height * sizeof(png_byte *)); for (y = 0; y < bitmap->height; ++y) { - png_byte *row = - (png_byte *) png_malloc (png_ptr, sizeof (uint8_t) * bitmap->width * pixel_size); - row_pointers[bitmap->height - y - 1] = row; // Row order in EMF is reversed. + png_byte *row = (png_byte *)png_malloc(png_ptr, sizeof(uint8_t) * bitmap->width * pixel_size); + row_pointers[bitmap->height - y - 1] = row; // Row order in EMF is reversed. for (x = 0; x < bitmap->width; ++x) { - pixel_t * pixel = pixel_at (bitmap, x, y); - *row++ = pixel->red; // R & B channels were set correctly by DIB_to_RGB + pixel_t *pixel = pixel_at(bitmap, x, y); + *row++ = pixel->red; // R & B channels were set correctly by DIB_to_RGB *row++ = pixel->green; *row++ = pixel->blue; } @@ -158,34 +151,33 @@ void Metafile::toPNG(PMEMPNG accum, int width, int height, const char *px){ /* Write the image data to memory */ - png_set_rows (png_ptr, info_ptr, row_pointers); + png_set_rows(png_ptr, info_ptr, row_pointers); png_set_write_fn(png_ptr, accum, my_png_write_data, nullptr); - png_write_png (png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, nullptr); + png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, nullptr); for (y = 0; y < bitmap->height; y++) { - png_free (png_ptr, row_pointers[y]); + png_free(png_ptr, row_pointers[y]); } - png_free (png_ptr, row_pointers); + png_free(png_ptr, row_pointers); png_destroy_write_struct(&png_ptr, &info_ptr); - } -/* If the viewBox is missing, set one -*/ -void Metafile::setViewBoxIfMissing(SPDocument *doc) { - +/* If the viewBox is missing, set one + */ +void Metafile::setViewBoxIfMissing(SPDocument *doc) +{ if (doc && !doc->getRoot()->viewBox_set) { bool saved = Inkscape::DocumentUndo::getUndoSensitive(doc); Inkscape::DocumentUndo::setUndoSensitive(doc, false); - + doc->ensureUpToDate(); - + // Set document unit Inkscape::XML::Node *repr = sp_document_namedview(doc, nullptr)->getRepr(); Inkscape::SVGOStringStream os; - Inkscape::Util::Unit const* doc_unit = doc->getWidth().unit; + Inkscape::Util::Unit const *doc_unit = doc->getWidth().unit; os << doc_unit->abbr; repr->setAttribute("inkscape:document-units", os.str()); @@ -197,32 +189,31 @@ void Metafile::setViewBoxIfMissing(SPDocument *doc) { double scale = Inkscape::Util::Quantity::convert(1, "px", doc_unit); Inkscape::UI::ShapeEditor::blockSetItem(true); double dh; - if(SP_ACTIVE_DOCUMENT){ // for file menu open or import, or paste from clipboard + if (SP_ACTIVE_DOCUMENT) { // for file menu open or import, or paste from clipboard dh = SP_ACTIVE_DOCUMENT->getHeight().value("px"); - } - else { // for open via --file on command line + } else { // for open via --file on command line dh = doc->getHeight().value("px"); } // These should not affect input, but they do, so set them to a neutral state Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool transform_stroke = prefs->getBool("/options/transform/stroke", true); + 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); + 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); - + doc->getRoot()->scaleChildItemsRec(Geom::Scale(scale), Geom::Point(0, dh), true); Inkscape::UI::ShapeEditor::blockSetItem(false); // restore options - prefs->setBool("/options/transform/stroke", transform_stroke); + 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); + prefs->setBool("/options/transform/pattern", transform_pattern); + prefs->setBool("/options/transform/gradient", transform_gradient); Inkscape::DocumentUndo::setUndoSensitive(doc, saved); } @@ -235,49 +226,46 @@ void Metafile::setViewBoxIfMissing(SPDocument *doc) { */ int Metafile::combine_ops_to_livarot(const int op) { - int ret = -1; - switch(op) { + int ret = -1; + switch (op) { case U_RGN_AND: - ret = bool_op_inters; - break; + ret = bool_op_inters; + break; case U_RGN_OR: - ret = bool_op_union; - break; + ret = bool_op_union; + break; case U_RGN_XOR: - ret = bool_op_symdiff; - break; + ret = bool_op_symdiff; + break; case U_RGN_DIFF: - ret = bool_op_diff; - break; + ret = bool_op_diff; + break; } - return(ret); + return (ret); } - - /* convert an EMF RGB(A) color to 0RGB inverse of gethexcolor() in emf-print.cpp */ -uint32_t Metafile::sethexcolor(U_COLORREF color){ - +uint32_t Metafile::sethexcolor(U_COLORREF color) +{ uint32_t out; - out = (U_RGBAGetR(color) << 16) + - (U_RGBAGetG(color) << 8 ) + - (U_RGBAGetB(color) ); - return(out); + out = (U_RGBAGetR(color) << 16) + (U_RGBAGetG(color) << 8) + (U_RGBAGetB(color)); + return (out); } /* Return the base64 encoded png which is shown for all bad images. Currently a random 3x4 blotch. Caller must free. */ -gchar *Metafile::bad_image_png(){ - gchar *gstring = g_strdup("iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAIAAAA7ljmRAAAAA3NCSVQICAjb4U/gAAAALElEQVQImQXBQQ2AMAAAsUJQMSWI2H8qME1yMshojwrvGB8XcHKvR1XtOTc/8HENumHCsOMAAAAASUVORK5CYII="); - return(gstring); +gchar *Metafile::bad_image_png() +{ + gchar *gstring = + g_strdup("iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAIAAAA7ljmRAAAAA3NCSVQICAjb4U/" + "gAAAALElEQVQImQXBQQ2AMAAAsUJQMSWI2H8qME1yMshojwrvGB8XcHKvR1XtOTc/8HENumHCsOMAAAAASUVORK5CYII="); + return (gstring); } - - } // namespace Internal } // namespace Extension } // namespace Inkscape diff --git a/src/extension/internal/metafile-inout.h b/src/extension/internal/metafile-inout.h index c742a64dfc281a9ae800bc9b8790be7a31db525a..5781beb5186b58c0f4daf3a5cd9e155124ce9595 100644 --- a/src/extension/internal/metafile-inout.h +++ b/src/extension/internal/metafile-inout.h @@ -13,16 +13,16 @@ #define SEEN_INKSCAPE_EXTENSION_INTERNAL_METAFILE_INOUT_H #define PNG_SKIP_SETJMP_CHECK // else any further png.h include blows up in the compiler -#include +#include <2geom/affine.h> +#include <2geom/pathvector.h> +#include <3rdparty/libuemf/uemf.h> +#include #include #include -#include +#include #include +#include #include -#include -#include <3rdparty/libuemf/uemf.h> -#include <2geom/affine.h> -#include <2geom/pathvector.h> #include "extension/implementation/implementation.h" @@ -35,7 +35,8 @@ namespace Extension { namespace Internal { /* A coloured pixel. */ -struct pixel_t { +struct pixel_t +{ uint8_t red; uint8_t green; uint8_t blue; @@ -43,35 +44,35 @@ struct pixel_t { }; /* A picture. */ -struct bitmap_t { +struct bitmap_t +{ pixel_t *pixels; size_t width; size_t height; }; - + /* structure to store PNG image bytes */ -struct MEMPNG { - char *buffer; - size_t size; +struct MEMPNG +{ + char *buffer; + size_t size; }; using PMEMPNG = MEMPNG *; -class Metafile - : public Inkscape::Extension::Implementation::Implementation +class Metafile : public Inkscape::Extension::Implementation::Implementation { public: Metafile() = default; ~Metafile() override; protected: - static uint32_t sethexcolor(U_COLORREF color); - static pixel_t *pixel_at (bitmap_t * bitmap, int x, int y); - static void my_png_write_data(png_structp png_ptr, png_bytep data, png_size_t length); - static void toPNG(PMEMPNG accum, int width, int height, const char *px); - static gchar *bad_image_png(); - static void setViewBoxIfMissing(SPDocument *doc); - static int combine_ops_to_livarot(const int op); - + static uint32_t sethexcolor(U_COLORREF color); + static pixel_t *pixel_at(bitmap_t *bitmap, int x, int y); + static void my_png_write_data(png_structp png_ptr, png_bytep data, png_size_t length); + static void toPNG(PMEMPNG accum, int width, int height, const char *px); + static gchar *bad_image_png(); + static void setViewBoxIfMissing(SPDocument *doc); + static int combine_ops_to_livarot(const int op); private: }; diff --git a/src/extension/internal/metafile-print.cpp b/src/extension/internal/metafile-print.cpp index 917aec0d6ded98ccb9f13cf10d0e6f773b491ed1..21b0476ed6a8ba5e8835fd8b0b95d1ed4f2f496a 100644 --- a/src/extension/internal/metafile-print.cpp +++ b/src/extension/internal/metafile-print.cpp @@ -9,22 +9,23 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "extension/internal/metafile-print.h" + +#include <2geom/curves.h> +#include <2geom/rect.h> +#include <2geom/svg-path-parser.h> #include #include #include #include -#include <2geom/rect.h> -#include <2geom/curves.h> -#include <2geom/svg-path-parser.h> -#include "extension/internal/metafile-print.h" #include "extension/print.h" -#include "path-prefix.h" #include "object/sp-gradient.h" #include "object/sp-image.h" #include "object/sp-linear-gradient.h" #include "object/sp-pattern.h" #include "object/sp-radial-gradient.h" +#include "path-prefix.h" #include "style.h" namespace Inkscape { @@ -35,7 +36,7 @@ PrintMetafile::~PrintMetafile() { #ifndef G_OS_WIN32 // restore default signal handling for SIGPIPE - (void) signal(SIGPIPE, SIG_DFL); + (void)signal(SIGPIPE, SIG_DFL); #endif return; } @@ -91,7 +92,7 @@ unsigned int PrintMetafile::release(Inkscape::Extension::Print * /*mod*/) void PrintMetafile::_lookup_ppt_fontfix(Glib::ustring const &fontname, FontfixParams ¶ms) { auto it = _ppt_fixable_fonts.find(fontname); - if (it!=_ppt_fixable_fonts.end()) { + if (it != _ppt_fixable_fonts.end()) { params = it->second; } } @@ -99,11 +100,7 @@ void PrintMetafile::_lookup_ppt_fontfix(Glib::ustring const &fontname, FontfixPa U_COLORREF PrintMetafile::_gethexcolor(uint32_t color) { U_COLORREF out; - out = U_RGB( - (color >> 16) & 0xFF, - (color >> 8) & 0xFF, - (color >> 0) & 0xFF - ); + out = U_RGB((color >> 16) & 0xFF, (color >> 8) & 0xFF, (color >> 0) & 0xFF); return out; } @@ -112,16 +109,26 @@ uint32_t PrintMetafile::_translate_weight(unsigned inkweight) { switch (inkweight) { // 400 is tested first, as it is the most common case - case SP_CSS_FONT_WEIGHT_400: return U_FW_NORMAL; - case SP_CSS_FONT_WEIGHT_100: return U_FW_THIN; - case SP_CSS_FONT_WEIGHT_200: return U_FW_EXTRALIGHT; - case SP_CSS_FONT_WEIGHT_300: return U_FW_LIGHT; - case SP_CSS_FONT_WEIGHT_500: return U_FW_MEDIUM; - case SP_CSS_FONT_WEIGHT_600: return U_FW_SEMIBOLD; - case SP_CSS_FONT_WEIGHT_700: return U_FW_BOLD; - case SP_CSS_FONT_WEIGHT_800: return U_FW_EXTRABOLD; - case SP_CSS_FONT_WEIGHT_900: return U_FW_HEAVY; - default: return U_FW_NORMAL; + case SP_CSS_FONT_WEIGHT_400: + return U_FW_NORMAL; + case SP_CSS_FONT_WEIGHT_100: + return U_FW_THIN; + case SP_CSS_FONT_WEIGHT_200: + return U_FW_EXTRALIGHT; + case SP_CSS_FONT_WEIGHT_300: + return U_FW_LIGHT; + case SP_CSS_FONT_WEIGHT_500: + return U_FW_MEDIUM; + case SP_CSS_FONT_WEIGHT_600: + return U_FW_SEMIBOLD; + case SP_CSS_FONT_WEIGHT_700: + return U_FW_BOLD; + case SP_CSS_FONT_WEIGHT_800: + return U_FW_EXTRABOLD; + case SP_CSS_FONT_WEIGHT_900: + return U_FW_HEAVY; + default: + return U_FW_NORMAL; } } @@ -140,19 +147,18 @@ U_COLORREF PrintMetafile::avg_stop_color(SPGradient *gr) float rgbe[3]; float ops, ope; - ops = gr->vector.stops[0 ].opacity; + ops = gr->vector.stops[0].opacity; ope = gr->vector.stops[last].opacity; - gr->vector.stops[0 ].color.get_rgb_floatv(rgbs); + gr->vector.stops[0].color.get_rgb_floatv(rgbs); gr->vector.stops[last].color.get_rgb_floatv(rgbe); - /* Replace opacity at start & stop with that fraction background color, then average those two for final color. */ - cr = U_RGB( - 255 * ((opweight(rgbs[0], gv.rgb[0], ops) + opweight(rgbe[0], gv.rgb[0], ope)) / 2.0), - 255 * ((opweight(rgbs[1], gv.rgb[1], ops) + opweight(rgbe[1], gv.rgb[1], ope)) / 2.0), - 255 * ((opweight(rgbs[2], gv.rgb[2], ops) + opweight(rgbe[2], gv.rgb[2], ope)) / 2.0) - ); + /* Replace opacity at start & stop with that fraction background color, then average those two for final color. + */ + cr = U_RGB(255 * ((opweight(rgbs[0], gv.rgb[0], ops) + opweight(rgbe[0], gv.rgb[0], ope)) / 2.0), + 255 * ((opweight(rgbs[1], gv.rgb[1], ops) + opweight(rgbe[1], gv.rgb[1], ope)) / 2.0), + 255 * ((opweight(rgbs[2], gv.rgb[2], ops) + opweight(rgbe[2], gv.rgb[2], ope)) / 2.0)); } else { - cr = U_RGB(0, 0, 0); // The default fill + cr = U_RGB(0, 0, 0); // The default fill } return cr; } @@ -160,20 +166,18 @@ U_COLORREF PrintMetafile::avg_stop_color(SPGradient *gr) U_COLORREF PrintMetafile::weight_opacity(U_COLORREF c1) { float opa = c1.Reserved / 255.0; - U_COLORREF result = U_RGB( - 255 * opweight((float)c1.Red / 255.0, gv.rgb[0], opa), - 255 * opweight((float)c1.Green / 255.0, gv.rgb[1], opa), - 255 * opweight((float)c1.Blue / 255.0, gv.rgb[2], opa) - ); + U_COLORREF result = U_RGB(255 * opweight((float)c1.Red / 255.0, gv.rgb[0], opa), + 255 * opweight((float)c1.Green / 255.0, gv.rgb[1], opa), + 255 * opweight((float)c1.Blue / 255.0, gv.rgb[2], opa)); return result; } /* t between 0 and 1, values outside that range use the nearest limit */ U_COLORREF PrintMetafile::weight_colors(U_COLORREF c1, U_COLORREF c2, double t) { -#define clrweight(a,b,t) ((1-t)*((double) a) + (t)*((double) b)) +#define clrweight(a, b, t) ((1 - t) * ((double)a) + (t) * ((double)b)) U_COLORREF result; - t = ( t > 1.0 ? 1.0 : ( t < 0.0 ? 0.0 : t)); + t = (t > 1.0 ? 1.0 : (t < 0.0 ? 0.0 : t)); // clang-format off result.Red = clrweight(c1.Red, c2.Red, t); result.Green = clrweight(c1.Green, c2.Green, t); @@ -197,16 +201,16 @@ U_COLORREF PrintMetafile::weight_colors(U_COLORREF c1, U_COLORREF c2, double t) // void PrintMetafile::hatch_classify(char *name, int *hatchType, U_COLORREF *hatchColor, U_COLORREF *bkColor) { - int val; + int val; uint32_t hcolor = 0; uint32_t bcolor = 0; // name should be EMFhatch or WMFhatch but *MFhatch will be accepted if (0 != strncmp(&name[1], "MFhatch", 7)) { - return; // not anything we can parse + return; // not anything we can parse } name += 8; // EMFhatch already detected - val = 0; + val = 0; while (*name && isdigit(*name)) { val = 10 * val + *name - '0'; name++; @@ -218,16 +222,17 @@ void PrintMetafile::hatch_classify(char *name, int *hatchType, U_COLORREF *hatch name++; if (2 != sscanf(name, "%X_%X", &hcolor, &bcolor)) { // not a pattern with background if (1 != sscanf(name, "%X", &hcolor)) { - *hatchType = -1; // not a pattern, cannot classify + *hatchType = -1; // not a pattern, cannot classify } *hatchColor = _gethexcolor(hcolor); } else { *hatchColor = _gethexcolor(hcolor); - *bkColor = _gethexcolor(bcolor); - usebk = true; + *bkColor = _gethexcolor(bcolor); + usebk = true; } } - /* Everything > U_HS_SOLIDCLR is solid, just specify the color in the brush rather than messing around with background or textcolor */ + /* Everything > U_HS_SOLIDCLR is solid, just specify the color in the brush rather than messing around with + * background or textcolor */ if (*hatchType > U_HS_SOLIDCLR) { *hatchType = U_HS_SOLIDCLR; } @@ -240,32 +245,35 @@ void PrintMetafile::hatch_classify(char *name, int *hatchType, U_COLORREF *hatch // otherwise hatchType is set to -1 and hatchColor is not defined. // -void PrintMetafile::brush_classify(SPObject *parent, int depth, Inkscape::Pixbuf **epixbuf, int *hatchType, U_COLORREF *hatchColor, U_COLORREF *bkColor) +void PrintMetafile::brush_classify(SPObject *parent, int depth, Inkscape::Pixbuf **epixbuf, int *hatchType, + U_COLORREF *hatchColor, U_COLORREF *bkColor) { if (depth == 0) { - *epixbuf = nullptr; - *hatchType = -1; + *epixbuf = nullptr; + *hatchType = -1; *hatchColor = U_RGB(0, 0, 0); - *bkColor = U_RGB(255, 255, 255); + *bkColor = U_RGB(255, 255, 255); } depth++; // first look along the pattern chain, if there is one if (SP_IS_PATTERN(parent)) { - for (SPPattern *pat_i = SP_PATTERN(parent); pat_i != nullptr; pat_i = pat_i->ref ? pat_i->ref->getObject() : nullptr) { + for (SPPattern *pat_i = SP_PATTERN(parent); pat_i != nullptr; + pat_i = pat_i->ref ? pat_i->ref->getObject() : nullptr) { if (SP_IS_IMAGE(pat_i)) { *epixbuf = ((SPImage *)pat_i)->pixbuf; return; } - char temp[32]; // large enough - strncpy(temp, pat_i->getAttribute("id"), sizeof(temp)-1); // Some names may be longer than [EW]MFhatch#_###### - temp[sizeof(temp)-1] = '\0'; + char temp[32]; // large enough + strncpy(temp, pat_i->getAttribute("id"), + sizeof(temp) - 1); // Some names may be longer than [EW]MFhatch#_###### + temp[sizeof(temp) - 1] = '\0'; hatch_classify(temp, hatchType, hatchColor, bkColor); if (*hatchType != -1) { return; } // still looking? Look at this pattern's children, if there are any - for (auto& child: pat_i->children) { + for (auto &child : pat_i->children) { if (*epixbuf || *hatchType != -1) { break; } @@ -275,8 +283,9 @@ void PrintMetafile::brush_classify(SPObject *parent, int depth, Inkscape::Pixbuf } else if (SP_IS_IMAGE(parent)) { *epixbuf = ((SPImage *)parent)->pixbuf; return; - } else { // some inkscape rearrangements pass through nodes between pattern and image which are not classified as either. - for (auto& child: parent->children) { + } else { // some inkscape rearrangements pass through nodes between pattern and image which are not classified as + // either. + for (auto &child : parent->children) { if (*epixbuf || *hatchType != -1) { break; } @@ -285,7 +294,7 @@ void PrintMetafile::brush_classify(SPObject *parent, int depth, Inkscape::Pixbuf } } -//swap R/B in 4 byte pixel +// swap R/B in 4 byte pixel void PrintMetafile::swapRBinRGBA(char *px, int pixels) { char tmp; @@ -301,22 +310,22 @@ int PrintMetafile::hold_gradient(void *gr, int mode) gv.mode = mode; gv.grad = gr; if (mode == DRAW_RADIAL_GRADIENT) { - SPRadialGradient *rg = (SPRadialGradient *) gr; - gv.r = rg->r.computed; // radius, but of what??? - gv.p1 = Geom::Point(rg->cx.computed, rg->cy.computed); // center - gv.p2 = Geom::Point(gv.r, 0) + gv.p1; // xhandle - gv.p3 = Geom::Point(0, -gv.r) + gv.p1; // yhandle + SPRadialGradient *rg = (SPRadialGradient *)gr; + gv.r = rg->r.computed; // radius, but of what??? + gv.p1 = Geom::Point(rg->cx.computed, rg->cy.computed); // center + gv.p2 = Geom::Point(gv.r, 0) + gv.p1; // xhandle + gv.p3 = Geom::Point(0, -gv.r) + gv.p1; // yhandle if (rg->gradientTransform_set) { gv.p1 = gv.p1 * rg->gradientTransform; gv.p2 = gv.p2 * rg->gradientTransform; gv.p3 = gv.p3 * rg->gradientTransform; } } else if (mode == DRAW_LINEAR_GRADIENT) { - SPLinearGradient *lg = (SPLinearGradient *) gr; - gv.r = 0; // unused - gv.p1 = Geom::Point(lg->x1.computed, lg->y1.computed); // start - gv.p2 = Geom::Point(lg->x2.computed, lg->y2.computed); // end - gv.p3 = Geom::Point(0, 0); // unused + SPLinearGradient *lg = (SPLinearGradient *)gr; + gv.r = 0; // unused + gv.p1 = Geom::Point(lg->x1.computed, lg->y1.computed); // start + gv.p2 = Geom::Point(lg->x2.computed, lg->y2.computed); // end + gv.p3 = Geom::Point(0, 0); // unused if (lg->gradientTransform_set) { gv.p1 = gv.p1 * lg->gradientTransform; gv.p2 = gv.p2 * lg->gradientTransform; @@ -356,44 +365,46 @@ Geom::PathVector PrintMetafile::center_ellipse_as_SVG_PathV(Geom::Point ctr, dou double x1, y1, x2, y2; Geom::Path SVGep; - x1 = ctr[X] + cos(F) * rx * cos(0) + sin(-F) * ry * sin(0); - y1 = ctr[Y] + sin(F) * rx * cos(0) + cos(F) * ry * sin(0); - x2 = ctr[X] + cos(F) * rx * cos(M_PI) + sin(-F) * ry * sin(M_PI); - y2 = ctr[Y] + sin(F) * rx * cos(M_PI) + cos(F) * ry * sin(M_PI); + x1 = ctr[X] + cos(F) * rx * cos(0) + sin(-F) * ry * sin(0); + y1 = ctr[Y] + sin(F) * rx * cos(0) + cos(F) * ry * sin(0); + x2 = ctr[X] + cos(F) * rx * cos(M_PI) + sin(-F) * ry * sin(M_PI); + y2 = ctr[Y] + sin(F) * rx * cos(M_PI) + cos(F) * ry * sin(M_PI); char text[256]; - snprintf(text, 256, " M %f,%f A %f %f %f 0 0 %f %f A %f %f %f 0 0 %f %f z", - x1, y1, rx, ry, F * 360. / (2.*M_PI), x2, y2, rx, ry, F * 360. / (2.*M_PI), x1, y1); - Geom::PathVector outres = Geom::parse_svg_path(text); + snprintf(text, 256, " M %f,%f A %f %f %f 0 0 %f %f A %f %f %f 0 0 %f %f z", x1, y1, rx, ry, F * 360. / (2. * M_PI), + x2, y2, rx, ry, F * 360. / (2. * M_PI), x1, y1); + Geom::PathVector outres = Geom::parse_svg_path(text); return outres; } - /* rx2,ry2 must be larger than rx1,ry1! angle is in RADIANS */ -Geom::PathVector PrintMetafile::center_elliptical_ring_as_SVG_PathV(Geom::Point ctr, double rx1, double ry1, double rx2, double ry2, double F) +Geom::PathVector PrintMetafile::center_elliptical_ring_as_SVG_PathV(Geom::Point ctr, double rx1, double ry1, double rx2, + double ry2, double F) { using Geom::X; using Geom::Y; double x11, y11, x12, y12; double x21, y21, x22, y22; - double degrot = F * 360. / (2.*M_PI); + double degrot = F * 360. / (2. * M_PI); - x11 = ctr[X] + cos(F) * rx1 * cos(0) + sin(-F) * ry1 * sin(0); - y11 = ctr[Y] + sin(F) * rx1 * cos(0) + cos(F) * ry1 * sin(0); - x12 = ctr[X] + cos(F) * rx1 * cos(M_PI) + sin(-F) * ry1 * sin(M_PI); - y12 = ctr[Y] + sin(F) * rx1 * cos(M_PI) + cos(F) * ry1 * sin(M_PI); + x11 = ctr[X] + cos(F) * rx1 * cos(0) + sin(-F) * ry1 * sin(0); + y11 = ctr[Y] + sin(F) * rx1 * cos(0) + cos(F) * ry1 * sin(0); + x12 = ctr[X] + cos(F) * rx1 * cos(M_PI) + sin(-F) * ry1 * sin(M_PI); + y12 = ctr[Y] + sin(F) * rx1 * cos(M_PI) + cos(F) * ry1 * sin(M_PI); - x21 = ctr[X] + cos(F) * rx2 * cos(0) + sin(-F) * ry2 * sin(0); - y21 = ctr[Y] + sin(F) * rx2 * cos(0) + cos(F) * ry2 * sin(0); - x22 = ctr[X] + cos(F) * rx2 * cos(M_PI) + sin(-F) * ry2 * sin(M_PI); - y22 = ctr[Y] + sin(F) * rx2 * cos(M_PI) + cos(F) * ry2 * sin(M_PI); + x21 = ctr[X] + cos(F) * rx2 * cos(0) + sin(-F) * ry2 * sin(0); + y21 = ctr[Y] + sin(F) * rx2 * cos(0) + cos(F) * ry2 * sin(0); + x22 = ctr[X] + cos(F) * rx2 * cos(M_PI) + sin(-F) * ry2 * sin(M_PI); + y22 = ctr[Y] + sin(F) * rx2 * cos(M_PI) + cos(F) * ry2 * sin(M_PI); char text[512]; - snprintf(text, 512, " M %f,%f A %f %f %f 0 1 %f %f A %f %f %f 0 1 %f %f z M %f,%f A %f %f %f 0 0 %f %f A %f %f %f 0 0 %f %f z", - x11, y11, rx1, ry1, degrot, x12, y12, rx1, ry1, degrot, x11, y11, - x21, y21, rx2, ry2, degrot, x22, y22, rx2, ry2, degrot, x21, y21); + snprintf( + text, 512, + " M %f,%f A %f %f %f 0 1 %f %f A %f %f %f 0 1 %f %f z M %f,%f A %f %f %f 0 0 %f %f A %f %f %f 0 0 %f %f z", + x11, y11, rx1, ry1, degrot, x12, y12, rx1, ry1, degrot, x11, y11, x21, y21, rx2, ry2, degrot, x22, y22, rx2, + ry2, degrot, x21, y21); Geom::PathVector outres = Geom::parse_svg_path(text); return outres; @@ -407,15 +418,17 @@ Geom::PathVector PrintMetafile::center_elliptical_hole_as_SVG_PathV(Geom::Point double x1, y1, x2, y2; Geom::Path SVGep; - x1 = ctr[X] + cos(F) * rx * cos(0) + sin(-F) * ry * sin(0); - y1 = ctr[Y] + sin(F) * rx * cos(0) + cos(F) * ry * sin(0); - x2 = ctr[X] + cos(F) * rx * cos(M_PI) + sin(-F) * ry * sin(M_PI); - y2 = ctr[Y] + sin(F) * rx * cos(M_PI) + cos(F) * ry * sin(M_PI); + x1 = ctr[X] + cos(F) * rx * cos(0) + sin(-F) * ry * sin(0); + y1 = ctr[Y] + sin(F) * rx * cos(0) + cos(F) * ry * sin(0); + x2 = ctr[X] + cos(F) * rx * cos(M_PI) + sin(-F) * ry * sin(M_PI); + y2 = ctr[Y] + sin(F) * rx * cos(M_PI) + cos(F) * ry * sin(M_PI); char text[256]; - snprintf(text, 256, " M %f,%f A %f %f %f 0 0 %f %f A %f %f %f 0 0 %f %f z M 50000,50000 50000,-50000 -50000,-50000 -50000,50000 z", - x1, y1, rx, ry, F * 360. / (2.*M_PI), x2, y2, rx, ry, F * 360. / (2.*M_PI), x1, y1); - Geom::PathVector outres = Geom::parse_svg_path(text); + snprintf( + text, 256, + " M %f,%f A %f %f %f 0 0 %f %f A %f %f %f 0 0 %f %f z M 50000,50000 50000,-50000 -50000,-50000 -50000,50000 z", + x1, y1, rx, ry, F * 360. / (2. * M_PI), x2, y2, rx, ry, F * 360. / (2. * M_PI), x1, y1); + Geom::PathVector outres = Geom::parse_svg_path(text); return outres; } @@ -444,7 +457,7 @@ Geom::PathVector PrintMetafile::rect_cutter(Geom::Point ctr, Geom::Point pos, Ge FillRule PrintMetafile::SPWR_to_LVFR(SPWindRule wr) { FillRule fr; - if (wr == SP_WIND_RULE_EVENODD) { + if (wr == SP_WIND_RULE_EVENODD) { fr = fill_oddEven; } else { fr = fill_nonZero; diff --git a/src/extension/internal/metafile-print.h b/src/extension/internal/metafile-print.h index d828f9fda48d12f9144e615ec03001d1e4fe7d09..8aadf215ba13bfd5b90a122779936828a9e5a8d5 100644 --- a/src/extension/internal/metafile-print.h +++ b/src/extension/internal/metafile-print.h @@ -12,18 +12,16 @@ #ifndef SEEN_INKSCAPE_EXTENSION_INTERNAL_METAFILE_PRINT_H #define SEEN_INKSCAPE_EXTENSION_INTERNAL_METAFILE_PRINT_H -#include -#include - -#include -#include <3rdparty/libuemf/uemf.h> #include <2geom/affine.h> #include <2geom/pathvector.h> +#include <3rdparty/libuemf/uemf.h> +#include +#include +#include #include "extension/implementation/implementation.h" - -#include "style-enums.h" // Fill rule -#include "livarot/LivarotDefs.h" // FillRule +#include "livarot/LivarotDefs.h" // FillRule +#include "style-enums.h" // Fill rule class SPGradient; class SPObject; @@ -34,46 +32,54 @@ class Pixbuf; namespace Extension { namespace Internal { -enum MFDrawMode {DRAW_PAINT, DRAW_PATTERN, DRAW_IMAGE, DRAW_LINEAR_GRADIENT, DRAW_RADIAL_GRADIENT}; +enum MFDrawMode +{ + DRAW_PAINT, + DRAW_PATTERN, + DRAW_IMAGE, + DRAW_LINEAR_GRADIENT, + DRAW_RADIAL_GRADIENT +}; -struct FontfixParams { - double f1; //Vertical (rotating) offset factor (* font height) - double f2; //Vertical (nonrotating) offset factor (* font height) - double f3; //Horizontal (nonrotating) offset factor (* font height) +struct FontfixParams +{ + double f1; // Vertical (rotating) offset factor (* font height) + double f2; // Vertical (nonrotating) offset factor (* font height) + double f3; // Horizontal (nonrotating) offset factor (* font height) }; -class PrintMetafile - : public Inkscape::Extension::Implementation::Implementation +class PrintMetafile : public Inkscape::Extension::Implementation::Implementation { public: PrintMetafile() = default; ~PrintMetafile() override; - bool textToPath (Inkscape::Extension::Print * ext) override; + bool textToPath(Inkscape::Extension::Print *ext) override; unsigned int bind(Inkscape::Extension::Print *module, Geom::Affine const &transform, float opacity) override; unsigned int release(Inkscape::Extension::Print *module) override; protected: - struct GRADVALUES { - Geom::Point p1; // center or start - Geom::Point p2; // xhandle or end - Geom::Point p3; // yhandle or unused - double r; // radius or unused - void *grad; // to access the stops information - int mode; // DRAW_LINEAR_GRADIENT or DRAW_RADIAL_GRADIENT, if GRADVALUES is valid, else any value - U_COLORREF bgc; // document background color, this is as good a place as any to keep it - float rgb[3]; // also background color, but as 0-1 float. + struct GRADVALUES + { + Geom::Point p1; // center or start + Geom::Point p2; // xhandle or end + Geom::Point p3; // yhandle or unused + double r; // radius or unused + void *grad; // to access the stops information + int mode; // DRAW_LINEAR_GRADIENT or DRAW_RADIAL_GRADIENT, if GRADVALUES is valid, else any value + U_COLORREF bgc; // document background color, this is as good a place as any to keep it + float rgb[3]; // also background color, but as 0-1 float. }; - double _width; - double _height; - double _doc_unit_scale; // to pixels, regardless of the document units - - U_RECTL rc; + double _width; + double _height; + double _doc_unit_scale; // to pixels, regardless of the document units + + U_RECTL rc; uint32_t htextalignment; - uint32_t hpolyfillmode; // used to minimize redundant records that set this - float htextcolor_rgb[3]; // used to minimize redundant records that set this + uint32_t hpolyfillmode; // used to minimize redundant records that set this + float htextcolor_rgb[3]; // used to minimize redundant records that set this std::stack m_tr_stack; Geom::PathVector fill_pathv; @@ -93,21 +99,23 @@ protected: U_COLORREF weight_opacity(U_COLORREF c1); U_COLORREF weight_colors(U_COLORREF c1, U_COLORREF c2, double t); - void hatch_classify(char *name, int *hatchType, U_COLORREF *hatchColor, U_COLORREF *bkColor); - void brush_classify(SPObject *parent, int depth, Inkscape::Pixbuf **epixbuf, int *hatchType, U_COLORREF *hatchColor, U_COLORREF *bkColor); + void hatch_classify(char *name, int *hatchType, U_COLORREF *hatchColor, U_COLORREF *bkColor); + void brush_classify(SPObject *parent, int depth, Inkscape::Pixbuf **epixbuf, int *hatchType, U_COLORREF *hatchColor, + U_COLORREF *bkColor); static void swapRBinRGBA(char *px, int pixels); - int hold_gradient(void *gr, int mode); - static int snprintf_dots(char * s, size_t n, const char * format, ...); + int hold_gradient(void *gr, int mode); + static int snprintf_dots(char *s, size_t n, const char *format, ...); static Geom::PathVector center_ellipse_as_SVG_PathV(Geom::Point ctr, double rx, double ry, double F); - static Geom::PathVector center_elliptical_ring_as_SVG_PathV(Geom::Point ctr, double rx1, double ry1, double rx2, double ry2, double F); + static Geom::PathVector center_elliptical_ring_as_SVG_PathV(Geom::Point ctr, double rx1, double ry1, double rx2, + double ry2, double F); static Geom::PathVector center_elliptical_hole_as_SVG_PathV(Geom::Point ctr, double rx, double ry, double F); static Geom::PathVector rect_cutter(Geom::Point ctr, Geom::Point pos, Geom::Point neg, Geom::Point width); - static FillRule SPWR_to_LVFR(SPWindRule wr); + static FillRule SPWR_to_LVFR(SPWindRule wr); - virtual int create_brush(SPStyle const *style, PU_COLORREF fcolor) = 0; + virtual int create_brush(SPStyle const *style, PU_COLORREF fcolor) = 0; virtual void destroy_brush() = 0; - virtual int create_pen(SPStyle const *style, const Geom::Affine &transform) = 0; + virtual int create_pen(SPStyle const *style, const Geom::Affine &transform) = 0; virtual void destroy_pen() = 0; }; diff --git a/src/extension/internal/odf.cpp b/src/extension/internal/odf.cpp index bca3c965ef6ffe36b3b759c952f826722ee31608..f5df101e5551c55a567a0555c184383e99e6de35 100644 --- a/src/extension/internal/odf.cpp +++ b/src/extension/internal/odf.cpp @@ -27,62 +27,54 @@ #include "odf.h" //# System includes +#include #include #include #include -#include //# Inkscape includes -#include "clear-n_.h" -#include "inkscape.h" -#include "display/curve.h" -#include <2geom/pathvector.h> #include <2geom/curves.h> +#include <2geom/pathvector.h> #include <2geom/transforms.h> #include -#include "helper/geom-curves.h" -#include "extension/system.h" +#include +#include -#include "xml/repr.h" -#include "xml/attribute-record.h" -#include "object/sp-image.h" +#include "clear-n_.h" +#include "display/curve.h" +#include "document.h" +#include "extension/extension.h" +#include "extension/system.h" +#include "helper/geom-curves.h" +#include "inkscape-version.h" +#include "inkscape.h" +#include "io/stream/bufferstream.h" +#include "io/stream/stringstream.h" +#include "io/sys.h" +#include "object/sp-flowtext.h" #include "object/sp-gradient.h" -#include "object/sp-stop.h" +#include "object/sp-image.h" #include "object/sp-linear-gradient.h" +#include "object/sp-path.h" #include "object/sp-radial-gradient.h" #include "object/sp-root.h" -#include "object/sp-path.h" +#include "object/sp-stop.h" #include "object/sp-text.h" -#include "object/sp-flowtext.h" #include "object/uri.h" #include "style.h" - #include "svg/svg.h" #include "text-editing.h" #include "util/units.h" - - -#include "inkscape-version.h" -#include "document.h" -#include "extension/extension.h" - -#include "io/stream/bufferstream.h" -#include "io/stream/stringstream.h" -#include "io/sys.h" -#include -#include -namespace Inkscape -{ -namespace Extension -{ -namespace Internal -{ +#include "xml/attribute-record.h" +#include "xml/repr.h" +namespace Inkscape { +namespace Extension { +namespace Internal { //# Shorthand notation typedef Inkscape::IO::BufferOutputStream BufferOutputStream; typedef Inkscape::IO::OutputStreamWriter OutputStreamWriter; typedef Inkscape::IO::StringOutputStream StringOutputStream; - //######################################################################## //# C L A S S SingularValueDecomposition //######################################################################## @@ -91,140 +83,118 @@ typedef Inkscape::IO::StringOutputStream StringOutputStream; class SVDMatrix { public: - - SVDMatrix() - { - init(); - } + SVDMatrix() { init(); } SVDMatrix(unsigned int rowSize, unsigned int colSize) - { + { init(); rows = rowSize; cols = colSize; size = rows * cols; - d = new double[size]; - for (unsigned int i=0 ; i= rows || col >= cols) - return badval; - return d[cols*row + col]; - } - - double operator() (unsigned int row, unsigned int col) const - { - if (row >= rows || col >= cols) - return badval; - return d[cols*row + col]; - } - - unsigned int getRows() - { - return rows; - } - - unsigned int getCols() - { - return cols; - } - - SVDMatrix multiply(const SVDMatrix &other) - { - if (cols != other.rows) - { - SVDMatrix dummy; - return dummy; - } - SVDMatrix result(rows, other.cols); - for (unsigned int i=0 ; i= rows || col >= cols) + return badval; + return d[cols * row + col]; + } -private: + double operator()(unsigned int row, unsigned int col) const + { + if (row >= rows || col >= cols) + return badval; + return d[cols * row + col]; + } + + unsigned int getRows() { return rows; } + unsigned int getCols() { return cols; } + + SVDMatrix multiply(const SVDMatrix &other) + { + if (cols != other.rows) { + SVDMatrix dummy; + return dummy; + } + SVDMatrix result(rows, other.cols); + for (unsigned int i = 0; i < rows; i++) { + for (unsigned int j = 0; j < other.cols; j++) { + double sum = 0.0; + for (unsigned int k = 0; k < cols; k++) { + // sum += a[i][k] * b[k][j]; + sum += d[i * cols + k] * other(k, j); + } + result(i, j) = sum; + } + } + return result; + } + SVDMatrix transpose() + { + SVDMatrix result(cols, rows); + for (unsigned int i = 0; i < rows; i++) { + for (unsigned int j = 0; j < cols; j++) { + result(j, i) = d[i * cols + j]; + } + } + return result; + } + +private: virtual void init() - { + { badval = 0.0; - d = nullptr; - rows = 0; - cols = 0; - size = 0; - } + d = nullptr; + rows = 0; + cols = 0; + size = 0; + } - void assign(const SVDMatrix &other) - { - if (d) - { + void assign(const SVDMatrix &other) + { + if (d) { delete[] d; d = nullptr; - } + } rows = other.rows; cols = other.cols; size = other.size; badval = other.badval; d = new double[size]; - for (unsigned int i=0 ; i fabs(b)) - { - r = b/a; - r = fabs(a) * sqrt(1+r*r); - } - else if (b != 0) - { - r = a/b; - r = fabs(b) * sqrt(1+r*r); - } - else - { + if (fabs(a) > fabs(b)) { + r = b / a; + r = fabs(a) * sqrt(1 + r * r); + } else if (b != 0) { + r = a / b; + r = fabs(b) * sqrt(1 + r * r); + } else { r = 0.0; - } + } return r; } - - void SingularValueDecomposition::calculate() { - // Initialize. - int m = A.getRows(); - int n = A.getCols(); - - int nu = (m > n) ? m : n; - s_size = (m+1 < n) ? m+1 : n; - s = new double[s_size]; - U = SVDMatrix(m, nu); - V = SVDMatrix(n, n); - double *e = new double[n]; - double *work = new double[m]; - bool wantu = true; - bool wantv = true; - - // Reduce A to bidiagonal form, storing the diagonal elements - // in s and the super-diagonal elements in e. - - int nct = (m-10) ? nrtx : 0; - for (int k = 0; k < 2; k++) { - if (k < nct) { - + // Initialize. + int m = A.getRows(); + int n = A.getCols(); + + int nu = (m > n) ? m : n; + s_size = (m + 1 < n) ? m + 1 : n; + s = new double[s_size]; + U = SVDMatrix(m, nu); + V = SVDMatrix(n, n); + double *e = new double[n]; + double *work = new double[m]; + bool wantu = true; + bool wantv = true; + + // Reduce A to bidiagonal form, storing the diagonal elements + // in s and the super-diagonal elements in e. + + int nct = (m - 1 < n) ? m - 1 : n; + int nrtx = (n - 2 < m) ? n - 2 : m; + int nrt = (nrtx > 0) ? nrtx : 0; + for (int k = 0; k < 2; k++) { + if (k < nct) { // Compute the transformation for the k-th column and // place the k-th diagonal in s[k]. // Compute 2-norm of k-th column without under/overflow. s[k] = 0; for (int i = k; i < m; i++) { - s[k] = svd_hypot(s[k],A(i, k)); + s[k] = svd_hypot(s[k], A(i, k)); } if (s[k] != 0.0) { - if (A(k, k) < 0.0) { - s[k] = -s[k]; - } - for (int i = k; i < m; i++) { - A(i, k) /= s[k]; - } - A(k, k) += 1.0; + if (A(k, k) < 0.0) { + s[k] = -s[k]; + } + for (int i = k; i < m; i++) { + A(i, k) /= s[k]; + } + A(k, k) += 1.0; } s[k] = -s[k]; - } - for (int j = k+1; j < n; j++) { - if ((k < nct) & (s[k] != 0.0)) { - - // Apply the transformation. - - double t = 0; - for (int i = k; i < m; i++) { - t += A(i, k) * A(i, j); - } - t = -t/A(k, k); - for (int i = k; i < m; i++) { - A(i, j) += t*A(i, k); - } + } + for (int j = k + 1; j < n; j++) { + if ((k < nct) & (s[k] != 0.0)) { + // Apply the transformation. + + double t = 0; + for (int i = k; i < m; i++) { + t += A(i, k) * A(i, j); + } + t = -t / A(k, k); + for (int i = k; i < m; i++) { + A(i, j) += t * A(i, k); + } } // Place the k-th row of A into e for the // subsequent calculation of the row transformation. e[j] = A(k, j); - } - if (wantu & (k < nct)) { - + } + if (wantu & (k < nct)) { // Place the transformation in U for subsequent back // multiplication. for (int i = k; i < m; i++) { - U(i, k) = A(i, k); + U(i, k) = A(i, k); } - } - if (k < nrt) { - + } + if (k < nrt) { // Compute the k-th row transformation and place the // k-th super-diagonal in e[k]. // Compute 2-norm without under/overflow. e[k] = 0; - for (int i = k+1; i < n; i++) { - e[k] = svd_hypot(e[k],e[i]); + for (int i = k + 1; i < n; i++) { + e[k] = svd_hypot(e[k], e[i]); } if (e[k] != 0.0) { - if (e[k+1] < 0.0) { - e[k] = -e[k]; - } - for (int i = k+1; i < n; i++) { - e[i] /= e[k]; - } - e[k+1] += 1.0; + if (e[k + 1] < 0.0) { + e[k] = -e[k]; + } + for (int i = k + 1; i < n; i++) { + e[i] /= e[k]; + } + e[k + 1] += 1.0; } e[k] = -e[k]; - if ((k+1 < m) & (e[k] != 0.0)) { - - // Apply the transformation. - - for (int i = k+1; i < m; i++) { - work[i] = 0.0; - } - for (int j = k+1; j < n; j++) { - for (int i = k+1; i < m; i++) { - work[i] += e[j]*A(i, j); - } - } - for (int j = k+1; j < n; j++) { - double t = -e[j]/e[k+1]; - for (int i = k+1; i < m; i++) { - A(i, j) += t*work[i]; - } - } + if ((k + 1 < m) & (e[k] != 0.0)) { + // Apply the transformation. + + for (int i = k + 1; i < m; i++) { + work[i] = 0.0; + } + for (int j = k + 1; j < n; j++) { + for (int i = k + 1; i < m; i++) { + work[i] += e[j] * A(i, j); + } + } + for (int j = k + 1; j < n; j++) { + double t = -e[j] / e[k + 1]; + for (int i = k + 1; i < m; i++) { + A(i, j) += t * work[i]; + } + } } if (wantv) { + // Place the transformation in V for subsequent + // back multiplication. - // Place the transformation in V for subsequent - // back multiplication. - - for (int i = k+1; i < n; i++) { - V(i, k) = e[i]; - } + for (int i = k + 1; i < n; i++) { + V(i, k) = e[i]; + } } - } - } - - // Set up the final bidiagonal matrix or order p. - - int p = (n < m+1) ? n : m+1; - if (nct < n) { - s[nct] = A(nct, nct); - } - if (m < p) { - s[p-1] = 0.0; - } - if (nrt+1 < p) { - e[nrt] = A(nrt, p-1); - } - e[p-1] = 0.0; - - // If required, generate U. - - if (wantu) { - for (int j = nct; j < nu; j++) { + } + } + + // Set up the final bidiagonal matrix or order p. + + int p = (n < m + 1) ? n : m + 1; + if (nct < n) { + s[nct] = A(nct, nct); + } + if (m < p) { + s[p - 1] = 0.0; + } + if (nrt + 1 < p) { + e[nrt] = A(nrt, p - 1); + } + e[p - 1] = 0.0; + + // If required, generate U. + + if (wantu) { + for (int j = nct; j < nu; j++) { for (int i = 0; i < m; i++) { - U(i, j) = 0.0; + U(i, j) = 0.0; } U(j, j) = 1.0; - } - for (int k = nct-1; k >= 0; k--) { + } + for (int k = nct - 1; k >= 0; k--) { if (s[k] != 0.0) { - for (int j = k+1; j < nu; j++) { - double t = 0; - for (int i = k; i < m; i++) { - t += U(i, k)*U(i, j); - } - t = -t/U(k, k); - for (int i = k; i < m; i++) { - U(i, j) += t*U(i, k); - } - } - for (int i = k; i < m; i++ ) { - U(i, k) = -U(i, k); - } - U(k, k) = 1.0 + U(k, k); - for (int i = 0; i < k-1; i++) { - U(i, k) = 0.0; - } + for (int j = k + 1; j < nu; j++) { + double t = 0; + for (int i = k; i < m; i++) { + t += U(i, k) * U(i, j); + } + t = -t / U(k, k); + for (int i = k; i < m; i++) { + U(i, j) += t * U(i, k); + } + } + for (int i = k; i < m; i++) { + U(i, k) = -U(i, k); + } + U(k, k) = 1.0 + U(k, k); + for (int i = 0; i < k - 1; i++) { + U(i, k) = 0.0; + } } else { - for (int i = 0; i < m; i++) { - U(i, k) = 0.0; - } - U(k, k) = 1.0; + for (int i = 0; i < m; i++) { + U(i, k) = 0.0; + } + U(k, k) = 1.0; } - } - } + } + } - // If required, generate V. + // If required, generate V. - if (wantv) { - for (int k = n-1; k >= 0; k--) { + if (wantv) { + for (int k = n - 1; k >= 0; k--) { if ((k < nrt) & (e[k] != 0.0)) { - for (int j = k+1; j < nu; j++) { - double t = 0; - for (int i = k+1; i < n; i++) { - t += V(i, k)*V(i, j); - } - t = -t/V(k+1, k); - for (int i = k+1; i < n; i++) { - V(i, j) += t*V(i, k); - } - } + for (int j = k + 1; j < nu; j++) { + double t = 0; + for (int i = k + 1; i < n; i++) { + t += V(i, k) * V(i, j); + } + t = -t / V(k + 1, k); + for (int i = k + 1; i < n; i++) { + V(i, j) += t * V(i, k); + } + } } for (int i = 0; i < n; i++) { - V(i, k) = 0.0; + V(i, k) = 0.0; } V(k, k) = 1.0; - } - } - - // Main iteration loop for the singular values. - - int pp = p-1; - //double eps = pow(2.0,-52.0); - //double tiny = pow(2.0,-966.0); - //let's just calculate these now - //a double can be e ± 308.25, so this is safe - double eps = 2.22e-16; - double tiny = 1.6e-291; - while (p > 0) { - int k,kase; - - // Here is where a test for too many iterations would go. - - // This section of the program inspects for - // negligible elements in the s and e arrays. On - // completion the variables kase and k are set as follows. - - // kase = 1 if s(p) and e[k-1] are negligible and k

= -1; k--) { + } + } + + // Main iteration loop for the singular values. + + int pp = p - 1; + // double eps = pow(2.0,-52.0); + // double tiny = pow(2.0,-966.0); + // let's just calculate these now + // a double can be e ± 308.25, so this is safe + double eps = 2.22e-16; + double tiny = 1.6e-291; + while (p > 0) { + int k, kase; + + // Here is where a test for too many iterations would go. + + // This section of the program inspects for + // negligible elements in the s and e arrays. On + // completion the variables kase and k are set as follows. + + // kase = 1 if s(p) and e[k-1] are negligible and k

= -1; k--) { if (k == -1) { - break; + break; } - if (fabs(e[k]) <= - tiny + eps*(fabs(s[k]) + fabs(s[k+1]))) { - e[k] = 0.0; - break; + if (fabs(e[k]) <= tiny + eps * (fabs(s[k]) + fabs(s[k + 1]))) { + e[k] = 0.0; + break; } - } - if (k == p-2) { + } + if (k == p - 2) { kase = 4; - } else { + } else { int ks; - for (ks = p-1; ks >= k; ks--) { - if (ks == k) { - break; - } - double t = (ks != p ? fabs(e[ks]) : 0.) + - (ks != k+1 ? fabs(e[ks-1]) : 0.); - if (fabs(s[ks]) <= tiny + eps*t) { - s[ks] = 0.0; - break; - } + for (ks = p - 1; ks >= k; ks--) { + if (ks == k) { + break; + } + double t = (ks != p ? fabs(e[ks]) : 0.) + (ks != k + 1 ? fabs(e[ks - 1]) : 0.); + if (fabs(s[ks]) <= tiny + eps * t) { + s[ks] = 0.0; + break; + } } if (ks == k) { - kase = 3; - } else if (ks == p-1) { - kase = 1; + kase = 3; + } else if (ks == p - 1) { + kase = 1; } else { - kase = 2; - k = ks; + kase = 2; + k = ks; } - } - k++; - - // Perform the task indicated by kase. + } + k++; - switch (kase) { + // Perform the task indicated by kase. - // Deflate negligible s(p). + switch (kase) { + // Deflate negligible s(p). case 1: { - double f = e[p-2]; - e[p-2] = 0.0; - for (int j = p-2; j >= k; j--) { - double t = svd_hypot(s[j],f); - double cs = s[j]/t; - double sn = f/t; - s[j] = t; - if (j != k) { - f = -sn*e[j-1]; - e[j-1] = cs*e[j-1]; - } - if (wantv) { - for (int i = 0; i < n; i++) { - t = cs*V(i, j) + sn*V(i, p-1); - V(i, p-1) = -sn*V(i, j) + cs*V(i, p-1); - V(i, j) = t; - } - } - } - } - break; + double f = e[p - 2]; + e[p - 2] = 0.0; + for (int j = p - 2; j >= k; j--) { + double t = svd_hypot(s[j], f); + double cs = s[j] / t; + double sn = f / t; + s[j] = t; + if (j != k) { + f = -sn * e[j - 1]; + e[j - 1] = cs * e[j - 1]; + } + if (wantv) { + for (int i = 0; i < n; i++) { + t = cs * V(i, j) + sn * V(i, p - 1); + V(i, p - 1) = -sn * V(i, j) + cs * V(i, p - 1); + V(i, j) = t; + } + } + } + } break; - // Split at negligible s(k). + // Split at negligible s(k). case 2: { - double f = e[k-1]; - e[k-1] = 0.0; - for (int j = k; j < p; j++) { - double t = svd_hypot(s[j],f); - double cs = s[j]/t; - double sn = f/t; - s[j] = t; - f = -sn*e[j]; - e[j] = cs*e[j]; - if (wantu) { - for (int i = 0; i < m; i++) { - t = cs*U(i, j) + sn*U(i, k-1); - U(i, k-1) = -sn*U(i, j) + cs*U(i, k-1); - U(i, j) = t; - } - } - } - } - break; + double f = e[k - 1]; + e[k - 1] = 0.0; + for (int j = k; j < p; j++) { + double t = svd_hypot(s[j], f); + double cs = s[j] / t; + double sn = f / t; + s[j] = t; + f = -sn * e[j]; + e[j] = cs * e[j]; + if (wantu) { + for (int i = 0; i < m; i++) { + t = cs * U(i, j) + sn * U(i, k - 1); + U(i, k - 1) = -sn * U(i, j) + cs * U(i, k - 1); + U(i, j) = t; + } + } + } + } break; - // Perform one qr step. + // Perform one qr step. case 3: { + // Calculate the shift. + + double scale = fabs(s[p - 1]); + double d = fabs(s[p - 2]); + if (d > scale) + scale = d; + d = fabs(e[p - 2]); + if (d > scale) + scale = d; + d = fabs(s[k]); + if (d > scale) + scale = d; + d = fabs(e[k]); + if (d > scale) + scale = d; + double sp = s[p - 1] / scale; + double spm1 = s[p - 2] / scale; + double epm1 = e[p - 2] / scale; + double sk = s[k] / scale; + double ek = e[k] / scale; + double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0; + double c = (sp * epm1) * (sp * epm1); + double shift = 0.0; + if ((b != 0.0) | (c != 0.0)) { + shift = sqrt(b * b + c); + if (b < 0.0) { + shift = -shift; + } + shift = c / (b + shift); + } + double f = (sk + sp) * (sk - sp) + shift; + double g = sk * ek; - // Calculate the shift. - - double scale = fabs(s[p-1]); - double d = fabs(s[p-2]); - if (d>scale) scale=d; - d = fabs(e[p-2]); - if (d>scale) scale=d; - d = fabs(s[k]); - if (d>scale) scale=d; - d = fabs(e[k]); - if (d>scale) scale=d; - double sp = s[p-1]/scale; - double spm1 = s[p-2]/scale; - double epm1 = e[p-2]/scale; - double sk = s[k]/scale; - double ek = e[k]/scale; - double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0; - double c = (sp*epm1)*(sp*epm1); - double shift = 0.0; - if ((b != 0.0) | (c != 0.0)) { - shift = sqrt(b*b + c); - if (b < 0.0) { - shift = -shift; - } - shift = c/(b + shift); - } - double f = (sk + sp)*(sk - sp) + shift; - double g = sk*ek; - - // Chase zeros. - - for (int j = k; j < p-1; j++) { - double t = svd_hypot(f,g); - double cs = f/t; - double sn = g/t; - if (j != k) { - e[j-1] = t; - } - f = cs*s[j] + sn*e[j]; - e[j] = cs*e[j] - sn*s[j]; - g = sn*s[j+1]; - s[j+1] = cs*s[j+1]; - if (wantv) { - for (int i = 0; i < n; i++) { - t = cs*V(i, j) + sn*V(i, j+1); - V(i, j+1) = -sn*V(i, j) + cs*V(i, j+1); - V(i, j) = t; - } - } - t = svd_hypot(f,g); - cs = f/t; - sn = g/t; - s[j] = t; - f = cs*e[j] + sn*s[j+1]; - s[j+1] = -sn*e[j] + cs*s[j+1]; - g = sn*e[j+1]; - e[j+1] = cs*e[j+1]; - if (wantu && (j < m-1)) { - for (int i = 0; i < m; i++) { - t = cs*U(i, j) + sn*U(i, j+1); - U(i, j+1) = -sn*U(i, j) + cs*U(i, j+1); - U(i, j) = t; - } - } - } - e[p-2] = f; - } - break; + // Chase zeros. - // Convergence. + for (int j = k; j < p - 1; j++) { + double t = svd_hypot(f, g); + double cs = f / t; + double sn = g / t; + if (j != k) { + e[j - 1] = t; + } + f = cs * s[j] + sn * e[j]; + e[j] = cs * e[j] - sn * s[j]; + g = sn * s[j + 1]; + s[j + 1] = cs * s[j + 1]; + if (wantv) { + for (int i = 0; i < n; i++) { + t = cs * V(i, j) + sn * V(i, j + 1); + V(i, j + 1) = -sn * V(i, j) + cs * V(i, j + 1); + V(i, j) = t; + } + } + t = svd_hypot(f, g); + cs = f / t; + sn = g / t; + s[j] = t; + f = cs * e[j] + sn * s[j + 1]; + s[j + 1] = -sn * e[j] + cs * s[j + 1]; + g = sn * e[j + 1]; + e[j + 1] = cs * e[j + 1]; + if (wantu && (j < m - 1)) { + for (int i = 0; i < m; i++) { + t = cs * U(i, j) + sn * U(i, j + 1); + U(i, j + 1) = -sn * U(i, j) + cs * U(i, j + 1); + U(i, j) = t; + } + } + } + e[p - 2] = f; + } break; + + // Convergence. case 4: { + // Make the singular values positive. + + if (s[k] <= 0.0) { + s[k] = (s[k] < 0.0 ? -s[k] : 0.0); + if (wantv) { + for (int i = 0; i <= pp; i++) { + V(i, k) = -V(i, k); + } + } + } - // Make the singular values positive. - - if (s[k] <= 0.0) { - s[k] = (s[k] < 0.0 ? -s[k] : 0.0); - if (wantv) { - for (int i = 0; i <= pp; i++) { - V(i, k) = -V(i, k); - } - } - } - - // Order the singular values. - - while (k < pp) { - if (s[k] >= s[k+1]) { - break; - } - double t = s[k]; - s[k] = s[k+1]; - s[k+1] = t; - if (wantv && (k < n-1)) { - for (int i = 0; i < n; i++) { - t = V(i, k+1); V(i, k+1) = V(i, k); V(i, k) = t; - } - } - if (wantu && (k < m-1)) { - for (int i = 0; i < m; i++) { - t = U(i, k+1); U(i, k+1) = U(i, k); U(i, k) = t; - } - } - k++; - } - p--; - } - break; - } - } + // Order the singular values. - delete [] e; - delete [] work; + while (k < pp) { + if (s[k] >= s[k + 1]) { + break; + } + double t = s[k]; + s[k] = s[k + 1]; + s[k + 1] = t; + if (wantv && (k < n - 1)) { + for (int i = 0; i < n; i++) { + t = V(i, k + 1); + V(i, k + 1) = V(i, k); + V(i, k) = t; + } + } + if (wantu && (k < m - 1)) { + for (int i = 0; i < m; i++) { + t = U(i, k + 1); + U(i, k + 1) = U(i, k); + U(i, k) = t; + } + } + k++; + } + p--; + } break; + } + } + delete[] e; + delete[] work; } - /** * Return the left singular vectors * @return U @@ -830,7 +776,7 @@ double SingularValueDecomposition::norm2() double SingularValueDecomposition::cond() { - return s[0]/s[2]; + return s[0] / s[2]; } /** @@ -839,14 +785,13 @@ double SingularValueDecomposition::cond() */ int SingularValueDecomposition::rank() { - double eps = pow(2.0,-52.0); - double tol = 3.0*s[0]*eps; + double eps = pow(2.0, -52.0); + double tol = 3.0 * s[0] * eps; int r = 0; - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { if (s[i] > tol) r++; - } + } return r; } @@ -854,13 +799,8 @@ int SingularValueDecomposition::rank() //# E N D C L A S S SingularValueDecomposition //######################################################################## - - - - //#define pxToCm 0.0275 -#define pxToCm 0.03 - +#define pxToCm 0.03 //######################################################################## //# O U T P U T @@ -869,7 +809,7 @@ int SingularValueDecomposition::rank() /** * Get the value of a node/attribute pair */ -static Glib::ustring getAttribute( Inkscape::XML::Node *node, char const *attrName) +static Glib::ustring getAttribute(Inkscape::XML::Node *node, char const *attrName) { Glib::ustring val; char const *valstr = node->attribute(attrName); @@ -878,22 +818,18 @@ static Glib::ustring getAttribute( Inkscape::XML::Node *node, char const *attrNa return val; } - static Glib::ustring formatTransform(Geom::Affine &tf) { Glib::ustring str; - if (!tf.isIdentity()) - { + if (!tf.isIdentity()) { StringOutputStream outs; OutputStreamWriter out(outs); - out.printf("matrix(%.3f %.3f %.3f %.3f %.3f %.3f)", - tf[0], tf[1], tf[2], tf[3], tf[4], tf[5]); + out.printf("matrix(%.3f %.3f %.3f %.3f %.3f %.3f)", tf[0], tf[1], tf[2], tf[3], tf[4], tf[5]); str = outs.getString(); - } + } return str; } - /** * Get the general transform from SVG pixels to * ODF cm @@ -901,12 +837,11 @@ static Glib::ustring formatTransform(Geom::Affine &tf) static Geom::Affine getODFTransform(const SPItem *item) { //### Get SVG-to-ODF transform - Geom::Affine tf (item->i2doc_affine()); - tf = tf * Geom::Affine(Geom::Scale(pxToCm)); + Geom::Affine tf(item->i2doc_affine()); + tf = tf * Geom::Affine(Geom::Scale(pxToCm)); return tf; } - /** * Get the bounding box of an item, as mapped onto * an ODF document, in cm. @@ -921,25 +856,21 @@ static Geom::OptRect getODFBoundingBox(const SPItem *item) return bbox; } - /** * Get the transform for an item, including parents, but without * root viewBox transformation. */ static Geom::Affine getODFItemTransform(const SPItem *item) { - Geom::Affine itemTransform (item->i2doc_affine() * - SP_ACTIVE_DOCUMENT->getRoot()->c2p.inverse()); + Geom::Affine itemTransform(item->i2doc_affine() * SP_ACTIVE_DOCUMENT->getRoot()->c2p.inverse()); return itemTransform; } - /** * Get some fun facts from the transform */ -static void analyzeTransform(Geom::Affine &tf, - double &rotate, double &/*xskew*/, double &/*yskew*/, - double &xscale, double &yscale) +static void analyzeTransform(Geom::Affine &tf, double &rotate, double & /*xskew*/, double & /*yskew*/, double &xscale, + double &yscale) { SVDMatrix mat(2, 2); mat(0, 0) = tf[0]; @@ -957,27 +888,22 @@ static void analyzeTransform(Geom::Affine &tf, double s1 = svd.getS(1); xscale = s0; yscale = s1; - rotate = UVt(0,0); + rotate = UVt(0, 0); } static void gatherText(Inkscape::XML::Node *node, Glib::ustring &buf) { - if (node->type() == Inkscape::XML::TEXT_NODE) - { + if (node->type() == Inkscape::XML::TEXT_NODE) { char *s = (char *)node->content(); if (s) buf.append(s); - } + } - for (Inkscape::XML::Node *child = node->firstChild() ; - child != nullptr; child = child->next()) - { + for (Inkscape::XML::Node *child = node->firstChild(); child != nullptr; child = child->next()) { gatherText(child, buf); - } - + } } - /** * FIRST PASS. * Method descends into the repr tree, converting image, style, and gradient info @@ -986,37 +912,32 @@ static void gatherText(Inkscape::XML::Node *node, Glib::ustring &buf) void OdfOutput::preprocess(ZipFile &zf, Inkscape::XML::Node *node) { Glib::ustring nodeName = node->name(); - Glib::ustring id = getAttribute(node, "id"); + Glib::ustring id = getAttribute(node, "id"); //### First, check for metadata - if (nodeName == "metadata" || nodeName == "svg:metadata") - { - Inkscape::XML::Node *mchild = node->firstChild() ; + if (nodeName == "metadata" || nodeName == "svg:metadata") { + Inkscape::XML::Node *mchild = node->firstChild(); if (!mchild || strcmp(mchild->name(), "rdf:RDF")) return; - Inkscape::XML::Node *rchild = mchild->firstChild() ; + Inkscape::XML::Node *rchild = mchild->firstChild(); if (!rchild || strcmp(rchild->name(), "cc:Work")) return; - for (Inkscape::XML::Node *cchild = rchild->firstChild() ; - cchild ; cchild = cchild->next()) - { + for (Inkscape::XML::Node *cchild = rchild->firstChild(); cchild; cchild = cchild->next()) { Glib::ustring ccName = cchild->name(); Glib::ustring ccVal; gatherText(cchild, ccVal); - //g_message("ccName: %s ccVal:%s", ccName.c_str(), ccVal.c_str()); + // g_message("ccName: %s ccVal:%s", ccName.c_str(), ccVal.c_str()); metadata[ccName] = ccVal; - } - return; } + return; + } - //Now consider items. + // Now consider items. SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(node); - if (!reprobj) - { + if (!reprobj) { return; } - if (!SP_IS_ITEM(reprobj)) - { + if (!SP_IS_ITEM(reprobj)) { return; } @@ -1045,12 +966,10 @@ void OdfOutput::preprocess(ZipFile &zf, Inkscape::XML::Node *node) } } - for (Inkscape::XML::Node *child = node->firstChild() ; - child ; child = child->next()) + for (Inkscape::XML::Node *child = node->firstChild(); child; child = child->next()) preprocess(zf, child); } - /** * Writes the manifest. Currently it only changes according to the * file names of images packed into the zip file. @@ -1064,27 +983,29 @@ bool OdfOutput::writeManifest(ZipFile &zf) time(&tim); outs.writeString("\n"); - outs.writeString("\n"); + outs.writeString( + "\n"); outs.writeString("\n"); outs.writeString("\n"); outs.writeString("\n"); outs.writeString("\n"); outs.writeString("\n"); outs.writeString("\n"); - outs.writeString(" \n"); - outs.writeString(" \n"); + outs.writeString(" \n"); + outs.writeString( + " \n"); outs.writeString(" \n"); outs.writeString(" \n"); outs.writeString(" \n"); std::map::iterator iter; - for (iter = imageTable.begin() ; iter!=imageTable.end() ; ++iter) - { + for (iter = imageTable.begin(); iter != imageTable.end(); ++iter) { Glib::ustring newName = iter->second; // note: mime subtype was added as file extension in OdfOutput::preprocess @@ -1096,12 +1017,12 @@ bool OdfOutput::writeManifest(ZipFile &zf) outs.printf("\" manifest:full-path=\""); outs.writeString(newName.c_str()); outs.printf("\"/>\n"); - } + } outs.printf("\n"); outs.close(); - //Make our entry + // Make our entry ZipEntry *ze = zf.newEntry("META-INF/manifest.xml", "ODF file manifest"); ze->setUncompressedData(bouts.getBuffer()); ze->finish(); @@ -1109,7 +1030,6 @@ bool OdfOutput::writeManifest(ZipFile &zf) return true; } - /** * This writes the document meta information to meta.xml */ @@ -1125,28 +1045,24 @@ bool OdfOutput::writeMeta(ZipFile &zf) Glib::ustring InkscapeVersion = Glib::ustring("Inkscape.org - ") + Inkscape::version_string; Glib::ustring creator = InkscapeVersion; iter = metadata.find("dc:creator"); - if (iter != metadata.end()) - { + if (iter != metadata.end()) { creator = iter->second; } - + Glib::ustring date; Glib::ustring moddate; - char buf [80]; + char buf[80]; time_t rawtime; - struct tm * timeinfo; - time (&rawtime); - timeinfo = localtime (&rawtime); - strftime (buf,80,"%Y-%m-%d %H:%M:%S",timeinfo); + struct tm *timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + strftime(buf, 80, "%Y-%m-%d %H:%M:%S", timeinfo); moddate = Glib::ustring(buf); - + iter = metadata.find("dc:date"); - if (iter != metadata.end()) - { + if (iter != metadata.end()) { date = iter->second; - } - else - { + } else { date = moddate; } @@ -1155,7 +1071,7 @@ bool OdfOutput::writeMeta(ZipFile &zf) outs.writeString("\n"); @@ -1176,12 +1092,10 @@ bool OdfOutput::writeMeta(ZipFile &zf) tmp += Glib::ustring::compose(" %1\n", date); tmp += Glib::ustring::compose(" %1\n", moddate); outs.writeUString(tmp); - for (iter = metadata.begin() ; iter != metadata.end() ; ++iter) - { - Glib::ustring name = iter->first; + for (iter = metadata.begin(); iter != metadata.end(); ++iter) { + Glib::ustring name = iter->first; Glib::ustring value = iter->second; - if (!name.empty() && !value.empty()) - { + if (!name.empty() && !value.empty()) { tmp = Glib::ustring::compose(" <%1>%2\n", name, value, name); outs.writeUString(tmp); } @@ -1197,7 +1111,7 @@ bool OdfOutput::writeMeta(ZipFile &zf) outs.writeString("\n"); outs.close(); - //Make our entry + // Make our entry ZipEntry *ze = zf.newEntry("meta.xml", "ODF info file"); ze->setUncompressedData(bouts.getBuffer()); ze->finish(); @@ -1205,140 +1119,127 @@ bool OdfOutput::writeMeta(ZipFile &zf) return true; } - /** * Writes an SVG path as an ODF and returns the number of points written */ -static int -writePath(Writer &outs, Geom::PathVector const &pathv, - Geom::Affine const &tf, double xoff, double yoff) +static int writePath(Writer &outs, Geom::PathVector const &pathv, Geom::Affine const &tf, double xoff, double yoff) { using Geom::X; using Geom::Y; - int nrPoints = 0; + int nrPoints = 0; // convert the path to only lineto's and cubic curveto's: - Geom::PathVector pv = pathv_to_linear_and_cubic_beziers(pathv * tf * Geom::Translate(xoff, yoff) * Geom::Scale(1000.)); - - for (const auto & pit : pv) { - - double destx = pit.initialPoint()[X]; - double desty = pit.initialPoint()[Y]; - if (fabs(destx)<1.0) destx = 0.0; // Why is this needed? Shouldn't we just round all numbers then? - if (fabs(desty)<1.0) desty = 0.0; - outs.printf("M %.3f %.3f ", destx, desty); - nrPoints++; - - for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_closed(); ++cit) { - - if( is_straight_curve(*cit) ) - { - double destx = cit->finalPoint()[X]; - double desty = cit->finalPoint()[Y]; - if (fabs(destx)<1.0) destx = 0.0; // Why is this needed? Shouldn't we just round all numbers then? - if (fabs(desty)<1.0) desty = 0.0; - outs.printf("L %.3f %.3f ", destx, desty); - } - else if(Geom::CubicBezier const *cubic = dynamic_cast(&*cit)) { - std::vector points = cubic->controlPoints(); - for (unsigned i = 1; i <= 3; i++) { - if (fabs(points[i][X])<1.0) points[i][X] = 0.0; // Why is this needed? Shouldn't we just round all numbers then? - if (fabs(points[i][Y])<1.0) points[i][Y] = 0.0; - } - outs.printf("C %.3f %.3f %.3f %.3f %.3f %.3f ", points[1][X],points[1][Y], points[2][X],points[2][Y], points[3][X],points[3][Y]); + Geom::PathVector pv = + pathv_to_linear_and_cubic_beziers(pathv * tf * Geom::Translate(xoff, yoff) * Geom::Scale(1000.)); + + for (const auto &pit : pv) { + double destx = pit.initialPoint()[X]; + double desty = pit.initialPoint()[Y]; + if (fabs(destx) < 1.0) + destx = 0.0; // Why is this needed? Shouldn't we just round all numbers then? + if (fabs(desty) < 1.0) + desty = 0.0; + outs.printf("M %.3f %.3f ", destx, desty); + nrPoints++; + + for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_closed(); ++cit) { + if (is_straight_curve(*cit)) { + double destx = cit->finalPoint()[X]; + double desty = cit->finalPoint()[Y]; + if (fabs(destx) < 1.0) + destx = 0.0; // Why is this needed? Shouldn't we just round all numbers then? + if (fabs(desty) < 1.0) + desty = 0.0; + outs.printf("L %.3f %.3f ", destx, desty); + } else if (Geom::CubicBezier const *cubic = dynamic_cast(&*cit)) { + std::vector points = cubic->controlPoints(); + for (unsigned i = 1; i <= 3; i++) { + if (fabs(points[i][X]) < 1.0) + points[i][X] = 0.0; // Why is this needed? Shouldn't we just round all numbers then? + if (fabs(points[i][Y]) < 1.0) + points[i][Y] = 0.0; } - else { - g_error ("logical error, because pathv_to_linear_and_cubic_beziers was used"); - } - - nrPoints++; + outs.printf("C %.3f %.3f %.3f %.3f %.3f %.3f ", points[1][X], points[1][Y], points[2][X], points[2][Y], + points[3][X], points[3][Y]); + } else { + g_error("logical error, because pathv_to_linear_and_cubic_beziers was used"); } - if (pit.closed()) { - outs.printf("Z"); - } + nrPoints++; } + if (pit.closed()) { + outs.printf("Z"); + } + } + return nrPoints; } -bool OdfOutput::processStyle(SPItem *item, const Glib::ustring &id, const Glib::ustring &gradientNameFill, const Glib::ustring &gradientNameStroke, Glib::ustring& output) +bool OdfOutput::processStyle(SPItem *item, const Glib::ustring &id, const Glib::ustring &gradientNameFill, + const Glib::ustring &gradientNameStroke, Glib::ustring &output) { output.clear(); - if (!item) - { + if (!item) { return false; } - + SPStyle *style = item->style; - if (!style) - { + if (!style) { return false; } - + StyleInfo si; // FILL - if (style->fill.isColor()) - { - guint32 fillCol = style->fill.value.color.toRGBA32( 0 ); + if (style->fill.isColor()) { + guint32 fillCol = style->fill.value.color.toRGBA32(0); char buf[16]; int r = (fillCol >> 24) & 0xff; int g = (fillCol >> 16) & 0xff; - int b = (fillCol >> 8) & 0xff; + int b = (fillCol >> 8) & 0xff; snprintf(buf, 15, "#%02x%02x%02x", r, g, b); si.fillColor = buf; - si.fill = "solid"; - double opacityPercent = 100.0 * - (SP_SCALE24_TO_FLOAT(style->fill_opacity.value)); + si.fill = "solid"; + double opacityPercent = 100.0 * (SP_SCALE24_TO_FLOAT(style->fill_opacity.value)); snprintf(buf, 15, "%.3f%%", opacityPercent); si.fillOpacity = buf; - } - else if (style->fill.isPaintserver()) - { + } else if (style->fill.isPaintserver()) { SPGradient *gradient = SP_GRADIENT(SP_STYLE_FILL_SERVER(style)); - if (gradient) - { + if (gradient) { si.fill = "gradient"; } } // STROKE - if (style->stroke.isColor()) - { - guint32 strokeCol = style->stroke.value.color.toRGBA32( 0 ); + if (style->stroke.isColor()) { + guint32 strokeCol = style->stroke.value.color.toRGBA32(0); char buf[16]; int r = (strokeCol >> 24) & 0xff; int g = (strokeCol >> 16) & 0xff; - int b = (strokeCol >> 8) & 0xff; + int b = (strokeCol >> 8) & 0xff; snprintf(buf, 15, "#%02x%02x%02x", r, g, b); si.strokeColor = buf; snprintf(buf, 15, "%.3fpt", style->stroke_width.value); si.strokeWidth = buf; - si.stroke = "solid"; - double opacityPercent = 100.0 * - (SP_SCALE24_TO_FLOAT(style->stroke_opacity.value)); + si.stroke = "solid"; + double opacityPercent = 100.0 * (SP_SCALE24_TO_FLOAT(style->stroke_opacity.value)); snprintf(buf, 15, "%.3f%%", opacityPercent); si.strokeOpacity = buf; - } - else if (style->stroke.isPaintserver()) - { + } else if (style->stroke.isPaintserver()) { SPGradient *gradient = SP_GRADIENT(SP_STYLE_STROKE_SERVER(style)); - if (gradient) - { + if (gradient) { si.stroke = "gradient"; } } - //Look for existing identical style; + // Look for existing identical style; bool styleMatch = false; std::vector::iterator iter; - for (iter=styleTable.begin() ; iter!=styleTable.end() ; ++iter) - { - if (si.equals(*iter)) - { - //map to existing styleTable entry + for (iter = styleTable.begin(); iter != styleTable.end(); ++iter) { + if (si.equals(*iter)) { + // map to existing styleTable entry Glib::ustring styleName = iter->name; styleLookupTable[id] = styleName; styleMatch = true; @@ -1347,8 +1248,7 @@ bool OdfOutput::processStyle(SPItem *item, const Glib::ustring &id, const Glib:: } // Don't need a new style - if (styleMatch) - { + if (styleMatch) { return false; } @@ -1357,31 +1257,26 @@ bool OdfOutput::processStyle(SPItem *item, const Glib::ustring &id, const Glib:: styleTable.push_back(si); styleLookupTable[id] = styleName; - output = Glib::ustring::compose ("\n", si.name); + output = Glib::ustring::compose( + "\n", si.name); output += "style; - if (!style) - { + if (!style) { return false; } - if ((checkFillGradient? (!style->fill.isPaintserver()) : (!style->stroke.isPaintserver()))) - { + if ((checkFillGradient ? (!style->fill.isPaintserver()) : (!style->stroke.isPaintserver()))) { return false; } //## Gradient - SPGradient *gradient = SP_GRADIENT((checkFillGradient?(SP_STYLE_FILL_SERVER(style)) :(SP_STYLE_STROKE_SERVER(style)))); + SPGradient *gradient = + SP_GRADIENT((checkFillGradient ? (SP_STYLE_FILL_SERVER(style)) : (SP_STYLE_STROKE_SERVER(style)))); - if (gradient == nullptr) - { + if (gradient == nullptr) { return false; } GradientInfo gi; SPGradient *grvec = gradient->getVector(FALSE); - for (SPStop *stop = grvec->getFirstStop(); - stop ; stop = stop->getNextStop()) - { + for (SPStop *stop = grvec->getFirstStop(); stop; stop = stop->getNextStop()) { unsigned long rgba = stop->get_rgba32(); - unsigned long rgb = (rgba >> 8) & 0xffffff; - double opacity = (static_cast(rgba & 0xff)) / 256.0; + unsigned long rgb = (rgba >> 8) & 0xffffff; + double opacity = (static_cast(rgba & 0xff)) / 256.0; GradientStop gs(rgb, opacity); gi.stops.push_back(gs); } Glib::ustring gradientName2; - if (SP_IS_LINEARGRADIENT(gradient)) - { + if (SP_IS_LINEARGRADIENT(gradient)) { gi.style = "linear"; SPLinearGradient *linGrad = SP_LINEARGRADIENT(gradient); gi.x1 = linGrad->x1.value; @@ -1439,30 +1327,24 @@ bool OdfOutput::processGradient(SPItem *item, gi.x2 = linGrad->x2.value; gi.y2 = linGrad->y2.value; gradientName2 = Glib::ustring::compose("ImportedLinearGradient%1", gradientTable.size()); - } - else if (SP_IS_RADIALGRADIENT(gradient)) - { + } else if (SP_IS_RADIALGRADIENT(gradient)) { gi.style = "radial"; SPRadialGradient *radGrad = SP_RADIALGRADIENT(gradient); Geom::OptRect bbox = item->documentVisualBounds(); - gi.cx = (radGrad->cx.value-bbox->left())/bbox->width(); - gi.cy = (radGrad->cy.value-bbox->top())/bbox->height(); + gi.cx = (radGrad->cx.value - bbox->left()) / bbox->width(); + gi.cy = (radGrad->cy.value - bbox->top()) / bbox->height(); gradientName2 = Glib::ustring::compose("ImportedRadialGradient%1", gradientTable.size()); - } - else - { + } else { g_warning("not a supported gradient type"); return false; } - //Look for existing identical style; + // Look for existing identical style; bool gradientMatch = false; std::vector::iterator iter; - for (iter=gradientTable.begin() ; iter!=gradientTable.end() ; ++iter) - { - if (gi.equals(*iter)) - { - //map to existing gradientTable entry + for (iter = gradientTable.begin(); iter != gradientTable.end(); ++iter) { + if (gi.equals(*iter)) { + // map to existing gradientTable entry gradientName = iter->name; gradientLookupTable[id] = gradientName; gradientMatch = true; @@ -1470,8 +1352,7 @@ bool OdfOutput::processGradient(SPItem *item, } } - if (gradientMatch) - { + if (gradientMatch) { return true; } @@ -1483,8 +1364,7 @@ bool OdfOutput::processGradient(SPItem *item, // int gradientCount = gradientTable.size(); char buf[128]; - if (gi.style == "linear") - { + if (gi.style == "linear") { /* =================================================================== LINEAR gradient. We need something that looks like this: @@ -1496,8 +1376,7 @@ bool OdfOutput::processGradient(SPItem *item, draw:angle="150" draw:border="0%"/> =================================================================== */ - if (gi.stops.size() < 2) - { + if (gi.stops.size() < 2) { g_warning("Need at least 2 stops for a linear gradient"); return false; } @@ -1506,16 +1385,16 @@ bool OdfOutput::processGradient(SPItem *item, output += " draw:style=\"linear\""; snprintf(buf, 127, " draw:start-color=\"#%06lx\" draw:end-color=\"#%06lx\"", gi.stops[0].rgb, gi.stops[1].rgb); output += buf; - //TODO: apply maths, to define begin of gradient, taking gradient begin and end, as well as object boundary into account - double angle = (gi.y2-gi.y1); - angle = (angle != 0.) ? (atan((gi.x2-gi.x1)/(gi.y2-gi.y1))* 180. / M_PI) : 90; - angle = (angle < 0)?(180+angle):angle; - angle = angle * 10; //why do we need this: precision????????????? + // TODO: apply maths, to define begin of gradient, taking gradient begin and end, as well as object boundary + // into account + double angle = (gi.y2 - gi.y1); + angle = (angle != 0.) ? (atan((gi.x2 - gi.x1) / (gi.y2 - gi.y1)) * 180. / M_PI) : 90; + angle = (angle < 0) ? (180 + angle) : angle; + angle = angle * 10; // why do we need this: precision????????????? output += Glib::ustring::compose(" draw:start-intensity=\"%1\" draw:end-intensity=\"%2\" draw:angle=\"%3\"/>\n", - gi.stops[0].opacity * 100.0, gi.stops[1].opacity * 100.0, angle);// draw:border=\"0%%\" - } - else if (gi.style == "radial") - { + gi.stops[0].opacity * 100.0, gi.stops[1].opacity * 100.0, + angle); // draw:border=\"0%%\" + } else if (gi.style == "radial") { /* =================================================================== RADIAL gradient. We need something that looks like this: @@ -1528,60 +1407,54 @@ bool OdfOutput::processGradient(SPItem *item, draw:border="0%"/> =================================================================== */ - if (gi.stops.size() < 2) - { + if (gi.stops.size() < 2) { g_warning("Need at least 2 stops for a radial gradient"); return false; } output += Glib::ustring::compose("getObjectByRepr(node); - if (!reprobj) - { + if (!reprobj) { return true; } - if (!SP_IS_ITEM(reprobj)) - { + if (!SP_IS_ITEM(reprobj)) { return true; } SPItem *item = SP_ITEM(reprobj); Glib::ustring nodeName = node->name(); - Glib::ustring id = getAttribute(node, "id"); - Geom::Affine tf = getODFTransform(item);//Get SVG-to-ODF transform - Geom::OptRect bbox = getODFBoundingBox(item);//Get ODF bounding box params for item + Glib::ustring id = getAttribute(node, "id"); + Geom::Affine tf = getODFTransform(item); // Get SVG-to-ODF transform + Geom::OptRect bbox = getODFBoundingBox(item); // Get ODF bounding box params for item if (!bbox) { return true; } - double bbox_x = bbox->min()[Geom::X]; - double bbox_y = bbox->min()[Geom::Y]; - double bbox_width = (*bbox)[Geom::X].extent(); - double bbox_height = (*bbox)[Geom::Y].extent(); + double bbox_x = bbox->min()[Geom::X]; + double bbox_y = bbox->min()[Geom::Y]; + double bbox_width = (*bbox)[Geom::X].extent(); + double bbox_height = (*bbox)[Geom::Y].extent(); double rotate; double xskew; @@ -1592,44 +1465,29 @@ bool OdfOutput::writeTree(Writer &couts, Writer &souts, //# Do our stuff - if (nodeName == "svg" || nodeName == "svg:svg") - { + if (nodeName == "svg" || nodeName == "svg:svg") { //# Iterate through the children - for (Inkscape::XML::Node *child = node->firstChild() ; - child ; child = child->next()) - { - if (!writeTree(couts, souts, child)) - { + for (Inkscape::XML::Node *child = node->firstChild(); child; child = child->next()) { + if (!writeTree(couts, souts, child)) { return false; } } return true; - } - else if (nodeName == "g" || nodeName == "svg:g") - { - if (!id.empty()) - { + } else if (nodeName == "g" || nodeName == "svg:g") { + if (!id.empty()) { couts.printf("\n", id.c_str()); - } - else - { + } else { couts.printf("\n"); } //# Iterate through the children - for (Inkscape::XML::Node *child = node->firstChild() ; - child ; child = child->next()) - { - if (!writeTree(couts, souts, child)) - { + for (Inkscape::XML::Node *child = node->firstChild(); child; child = child->next()) { + if (!writeTree(couts, souts, child)) { return false; } } - if (!id.empty()) - { + if (!id.empty()) { couts.printf(" \n", id.c_str()); - } - else - { + } else { couts.printf("\n"); } return true; @@ -1641,35 +1499,33 @@ bool OdfOutput::writeTree(Writer &couts, Writer &souts, Glib::ustring outputFill; Glib::ustring outputStroke; Glib::ustring outputStyle; - + processGradient(item, id, tf, gradientNameFill, outputFill, true); processGradient(item, id, tf, gradientNameStroke, outputStroke, false); souts.writeUString(outputFill); souts.writeUString(outputStroke); - + //# STYLE processStyle(item, id, gradientNameFill, gradientNameStroke, outputStyle); souts.writeUString(outputStyle); //# ITEM DATA - if (nodeName == "image" || nodeName == "svg:image") - { - if (!SP_IS_IMAGE(item)) - { + if (nodeName == "image" || nodeName == "svg:image") { + if (!SP_IS_IMAGE(item)) { g_warning(" is not an SPImage."); return false; } - SPImage *img = SP_IMAGE(item); - double ix = img->x.value; - double iy = img->y.value; - double iwidth = img->width.value; + SPImage *img = SP_IMAGE(item); + double ix = img->x.value; + double iy = img->y.value; + double iwidth = img->width.value; double iheight = img->height.value; Geom::Point ibbox_min = Geom::Point(ix, iy) * tf; - ix = ibbox_min.x(); - iy = ibbox_min.y(); - iwidth = xscale * iwidth; + ix = ibbox_min.x(); + iy = ibbox_min.y(); + iwidth = xscale * iwidth; iheight = yscale * iheight; Geom::Affine itemTransform = getODFItemTransform(item); @@ -1678,35 +1534,27 @@ bool OdfOutput::writeTree(Writer &couts, Writer &souts, Glib::ustring href = getAttribute(node, "xlink:href"); std::map::iterator iter = imageTable.find(href); - if (iter == imageTable.end()) - { + if (iter == imageTable.end()) { g_warning("image '%s' not in table", href.c_str()); return false; } Glib::ustring newName = iter->second; couts.printf("\n"); - couts.printf(" \n"); couts.writeString(" \n"); couts.writeString(" \n"); @@ -1722,33 +1570,26 @@ bool OdfOutput::writeTree(Writer &couts, Writer &souts, curve = te_get_layout(item)->convertToCurves(); } - if (curve) - { + if (curve) { //### Default output couts.writeString("::iterator siter; siter = styleLookupTable.find(id); - if (siter != styleLookupTable.end()) - { + if (siter != styleLookupTable.end()) { Glib::ustring styleName = siter->second; couts.printf("draw:style-name=\"%s\" ", styleName.c_str()); } - couts.printf("draw:layer=\"layout\" svg:x=\"%.3fcm\" svg:y=\"%.3fcm\" ", - bbox_x, bbox_y); - couts.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ", - bbox_width, bbox_height); - couts.printf("svg:viewBox=\"0.0 0.0 %.3f %.3f\"", - bbox_width * 1000.0, bbox_height * 1000.0); + couts.printf("draw:layer=\"layout\" svg:x=\"%.3fcm\" svg:y=\"%.3fcm\" ", bbox_x, bbox_y); + couts.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ", bbox_width, bbox_height); + couts.printf("svg:viewBox=\"0.0 0.0 %.3f %.3f\"", bbox_width * 1000.0, bbox_height * 1000.0); couts.printf(" svg:d=\""); - int nrPoints = writePath(couts, curve->get_pathvector(), - tf, bbox_x, bbox_y); + int nrPoints = writePath(couts, curve->get_pathvector(), tf, bbox_x, bbox_y); couts.writeString("\""); couts.writeString(">\n"); @@ -1759,7 +1600,6 @@ bool OdfOutput::writeTree(Writer &couts, Writer &souts, return true; } - /** * Write the header for the content.xml file */ @@ -1773,7 +1613,7 @@ bool OdfOutput::writeStyleHeader(Writer &outs) outs.writeString("\n"); @@ -1822,7 +1662,6 @@ bool OdfOutput::writeStyleHeader(Writer &outs) return true; } - /** * Write the footer for the style.xml file */ @@ -1835,11 +1674,12 @@ bool OdfOutput::writeStyleFooter(Writer &outs) outs.writeString("\n"); outs.writeString("\n"); outs.writeString("\n"); - -///TODO: add default document style here - + + /// TODO: add default document style here + outs.writeString("\n"); - outs.writeString("\n"); + outs.writeString( + "\n"); outs.writeString(" + outs.printf(" Generated by Inkscape: %s", ctime(&tim)); // ctime has its own outs.writeString(" http://www.inkscape.org\n"); outs.writeString("*************************************************************************\n"); outs.writeString("-->\n"); @@ -1937,7 +1776,6 @@ bool OdfOutput::writeContentHeader(Writer &outs) return true; } - /** * Write the footer for the content.xml file */ @@ -1954,48 +1792,43 @@ bool OdfOutput::writeContentFooter(Writer &outs) return true; } - /** * Write the content.xml file. Writes the namesspace headers, then * calls writeTree(). */ bool OdfOutput::writeContent(ZipFile &zf, Inkscape::XML::Node *node) { - //Content.xml stream + // Content.xml stream BufferOutputStream cbouts; OutputStreamWriter couts(cbouts); - if (!writeContentHeader(couts)) - { + if (!writeContentHeader(couts)) { return false; } - //Style.xml stream + // Style.xml stream BufferOutputStream sbouts; OutputStreamWriter souts(sbouts); - if (!writeStyleHeader(souts)) - { + if (!writeStyleHeader(souts)) { return false; } //# Descend into the tree, doing all of our conversions //# to both files at the same time - char *oldlocale = g_strdup (setlocale (LC_NUMERIC, nullptr)); - setlocale (LC_NUMERIC, "C"); - if (!writeTree(couts, souts, node)) - { + char *oldlocale = g_strdup(setlocale(LC_NUMERIC, nullptr)); + setlocale(LC_NUMERIC, "C"); + if (!writeTree(couts, souts, node)) { g_warning("Failed to convert SVG tree"); - setlocale (LC_NUMERIC, oldlocale); - g_free (oldlocale); + setlocale(LC_NUMERIC, oldlocale); + g_free(oldlocale); return false; } - setlocale (LC_NUMERIC, oldlocale); - g_free (oldlocale); + setlocale(LC_NUMERIC, oldlocale); + g_free(oldlocale); //# Finish content file - if (!writeContentFooter(couts)) - { + if (!writeContentFooter(couts)) { return false; } @@ -2004,8 +1837,7 @@ bool OdfOutput::writeContent(ZipFile &zf, Inkscape::XML::Node *node) ze->finish(); //# Finish style file - if (!writeStyleFooter(souts)) - { + if (!writeStyleFooter(souts)) { return false; } @@ -2016,7 +1848,6 @@ bool OdfOutput::writeContent(ZipFile &zf, Inkscape::XML::Node *node) return true; } - /** * Resets class to its pristine condition, ready to use again */ @@ -2030,11 +1861,10 @@ void OdfOutput::reset() imageTable.clear(); } - /** * Descends into the SVG tree, mapping things to ODF when appropriate */ -void OdfOutput::save(Inkscape::Extension::Output */*mod*/, SPDocument *doc, gchar const *filename) +void OdfOutput::save(Inkscape::Extension::Output * /*mod*/, SPDocument *doc, gchar const *filename) { if (doc != SP_ACTIVE_DOCUMENT) { g_warning("OdfOutput can only save the active document"); @@ -2048,36 +1878,31 @@ void OdfOutput::save(Inkscape::Extension::Output */*mod*/, SPDocument *doc, gcha ZipFile zf; preprocess(zf, doc->getReprRoot()); - if (!writeManifest(zf)) - { + if (!writeManifest(zf)) { g_warning("Failed to write manifest"); return; - } + } - if (!writeContent(zf, doc->getReprRoot())) - { + if (!writeContent(zf, doc->getReprRoot())) { g_warning("Failed to write content"); return; - } + } - if (!writeMeta(zf)) - { + if (!writeMeta(zf)) { g_warning("Failed to write metafile"); return; - } + } - if (!zf.writeFile(filename)) - { + if (!zf.writeFile(filename)) { return; - } + } } - /** * This is the definition of PovRay output. This function just * calls the extension system with the memory allocated XML that * describes the data. -*/ + */ void OdfOutput::init() { // clang-format off @@ -2099,7 +1924,7 @@ void OdfOutput::init() /** * Make sure that we are in the database */ -bool OdfOutput::check (Inkscape::Extension::Extension */*module*/) +bool OdfOutput::check(Inkscape::Extension::Extension * /*module*/) { /* We don't need a Key if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV)) @@ -2109,10 +1934,9 @@ bool OdfOutput::check (Inkscape::Extension::Extension */*module*/) return TRUE; } -} //namespace Internal -} //namespace Extension -} //namespace Inkscape - +} // namespace Internal +} // namespace Extension +} // namespace Inkscape //######################################################################## //# E N D O F F I L E diff --git a/src/extension/internal/odf.h b/src/extension/internal/odf.h index 94cd360b69eb6e7ce947c33cf1b744448b7b5dee..4bab3a513978fd7314cfcfda798cf25172aa81a0 100644 --- a/src/extension/internal/odf.h +++ b/src/extension/internal/odf.h @@ -13,90 +13,71 @@ #ifndef EXTENSION_INTERNAL_ODG_OUT_H #define EXTENSION_INTERNAL_ODG_OUT_H +#include +#include #include - -#include "extension/implementation/implementation.h" - #include -#include -#include +#include "extension/implementation/implementation.h" #include "object/uri.h" class SPItem; #include -namespace Inkscape -{ -namespace Extension -{ -namespace Internal -{ +namespace Inkscape { +namespace Extension { +namespace Internal { typedef Inkscape::IO::Writer Writer; class StyleInfo { public: + StyleInfo() { init(); } - StyleInfo() - { - init(); - } - - StyleInfo(const StyleInfo &other) - { - assign(other); - } + StyleInfo(const StyleInfo &other) { assign(other); } StyleInfo &operator=(const StyleInfo &other) - { + { assign(other); return *this; - } + } void assign(const StyleInfo &other) - { - name = other.name; - stroke = other.stroke; - strokeColor = other.strokeColor; - strokeWidth = other.strokeWidth; + { + name = other.name; + stroke = other.stroke; + strokeColor = other.strokeColor; + strokeWidth = other.strokeWidth; strokeOpacity = other.strokeOpacity; - fill = other.fill; - fillColor = other.fillColor; - fillOpacity = other.fillOpacity; - } + fill = other.fill; + fillColor = other.fillColor; + fillOpacity = other.fillOpacity; + } void init() - { - name = "none"; - stroke = "none"; - strokeColor = "none"; - strokeWidth = "none"; + { + name = "none"; + stroke = "none"; + strokeColor = "none"; + strokeWidth = "none"; strokeOpacity = "none"; - fill = "none"; - fillColor = "none"; - fillOpacity = "none"; - } + fill = "none"; + fillColor = "none"; + fillOpacity = "none"; + } - virtual ~StyleInfo() - = default; + virtual ~StyleInfo() = default; - //used for eliminating duplicates in the styleTable + // used for eliminating duplicates in the styleTable bool equals(const StyleInfo &other) - { - if ( - stroke != other.stroke || - strokeColor != other.strokeColor || - strokeWidth != other.strokeWidth || - strokeOpacity != other.strokeOpacity || - fill != other.fill || - fillColor != other.fillColor || - fillOpacity != other.fillOpacity - ) + { + if (stroke != other.stroke || strokeColor != other.strokeColor || strokeWidth != other.strokeWidth || + strokeOpacity != other.strokeOpacity || fill != other.fill || fillColor != other.fillColor || + fillOpacity != other.fillOpacity) return false; return true; - } + } Glib::ustring name; Glib::ustring stroke; @@ -106,121 +87,101 @@ public: Glib::ustring fill; Glib::ustring fillColor; Glib::ustring fillOpacity; - }; - - - class GradientStop { public: - GradientStop() : rgb(0), opacity(0) - {} + GradientStop() + : rgb(0) + , opacity(0) + {} GradientStop(unsigned long rgbArg, double opacityArg) - { rgb = rgbArg; opacity = opacityArg; } - virtual ~GradientStop() - = default; - GradientStop(const GradientStop &other) - { assign(other); } - virtual GradientStop& operator=(const GradientStop &other) - { assign(other); return *this; } + { + rgb = rgbArg; + opacity = opacityArg; + } + virtual ~GradientStop() = default; + GradientStop(const GradientStop &other) { assign(other); } + virtual GradientStop &operator=(const GradientStop &other) + { + assign(other); + return *this; + } void assign(const GradientStop &other) - { + { rgb = other.rgb; opacity = other.opacity; - } + } unsigned long rgb; double opacity; }; - - class GradientInfo { public: + GradientInfo() { init(); } - GradientInfo() - { - init(); - } - - GradientInfo(const GradientInfo &other) - { - assign(other); - } + GradientInfo(const GradientInfo &other) { assign(other); } GradientInfo &operator=(const GradientInfo &other) - { + { assign(other); return *this; - } + } void assign(const GradientInfo &other) - { - name = other.name; - style = other.style; - cx = other.cx; - cy = other.cy; - fx = other.fx; - fy = other.fy; - r = other.r; - x1 = other.x1; - y1 = other.y1; - x2 = other.x2; - y2 = other.y2; - stops = other.stops; - } + { + name = other.name; + style = other.style; + cx = other.cx; + cy = other.cy; + fx = other.fx; + fy = other.fy; + r = other.r; + x1 = other.x1; + y1 = other.y1; + x2 = other.x2; + y2 = other.y2; + stops = other.stops; + } void init() - { - name = "none"; - style = "none"; - cx = 0.0; - cy = 0.0; - fx = 0.0; - fy = 0.0; - r = 0.0; - x1 = 0.0; - y1 = 0.0; - x2 = 0.0; - y2 = 0.0; + { + name = "none"; + style = "none"; + cx = 0.0; + cy = 0.0; + fx = 0.0; + fy = 0.0; + r = 0.0; + x1 = 0.0; + y1 = 0.0; + x2 = 0.0; + y2 = 0.0; stops.clear(); - } + } - virtual ~GradientInfo() - = default; + virtual ~GradientInfo() = default; - //used for eliminating duplicates in the styleTable + // used for eliminating duplicates in the styleTable bool equals(const GradientInfo &other) - { - if ( - name != other.name || - style != other.style || - cx != other.cx || - cy != other.cy || - fx != other.fx || - fy != other.fy || - r != other.r || - x1 != other.x1 || - y1 != other.y1 || - x2 != other.x2 || - y2 != other.y2 - ) + { + if (name != other.name || style != other.style || cx != other.cx || cy != other.cy || fx != other.fx || + fy != other.fy || r != other.r || x1 != other.x1 || y1 != other.y1 || x2 != other.x2 || y2 != other.y2) return false; if (stops.size() != other.stops.size()) return false; - for (unsigned int i=0 ; i stops; - }; - - /** * OpenDocument input and output * @@ -252,24 +210,19 @@ public: */ class OdfOutput : public Inkscape::Extension::Implementation::Implementation { - public: + bool check(Inkscape::Extension::Extension *module) override; - bool check (Inkscape::Extension::Extension * module) override; - - void save (Inkscape::Extension::Output *mod, - SPDocument *doc, - gchar const *filename) override; + void save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) override; - static void init (); + static void init(); private: - std::string docBaseUri; void reset(); - //cc or dc metadata name/value pairs + // cc or dc metadata name/value pairs std::map metadata; /* Style table @@ -278,17 +231,17 @@ private: StyleInfo si = styleTable[styleLookupTable[id]]; but check for errors, of course */ - //element id -> style entry name + // element id -> style entry name std::map styleLookupTable; - //style entry name -> style info + // style entry name -> style info std::vector styleTable; - //element id -> gradient entry name + // element id -> gradient entry name std::map gradientLookupTable; - //gradient entry name -> gradient info + // gradient entry name -> gradient info std::vector gradientTable; - //for renaming image file names + // for renaming image file names std::map imageTable; void preprocess(ZipFile &zf, Inkscape::XML::Node *node); @@ -299,10 +252,11 @@ private: bool writeStyle(ZipFile &zf); - bool processStyle(SPItem *item, const Glib::ustring &id, const Glib::ustring &gradientNameFill, const Glib::ustring &gradientNameStroke, Glib::ustring& output); + bool processStyle(SPItem *item, const Glib::ustring &id, const Glib::ustring &gradientNameFill, + const Glib::ustring &gradientNameStroke, Glib::ustring &output); - bool processGradient(SPItem *item, - const Glib::ustring &id, Geom::Affine &tf, Glib::ustring& gradientName, Glib::ustring& output, bool checkFillGradient = true); + bool processGradient(SPItem *item, const Glib::ustring &id, Geom::Affine &tf, Glib::ustring &gradientName, + Glib::ustring &output, bool checkFillGradient = true); bool writeStyleHeader(Writer &outs); @@ -315,15 +269,10 @@ private: bool writeTree(Writer &couts, Writer &souts, Inkscape::XML::Node *node); bool writeContent(ZipFile &zf, Inkscape::XML::Node *node); - }; - -} //namespace Internal -} //namespace Extension -} //namespace Inkscape - - +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* EXTENSION_INTERNAL_ODG_OUT_H */ - diff --git a/src/extension/internal/pdfinput/pdf-input.cpp b/src/extension/internal/pdfinput/pdf-input.cpp index 28616966dcd2b65533ea87e4827fe6e984ee772d..08a381a69084c19adb4b92ab6719ea1403164198 100644 --- a/src/extension/internal/pdfinput/pdf-input.cpp +++ b/src/extension/internal/pdfinput/pdf-input.cpp @@ -13,23 +13,23 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include "pdf-input.h" #ifdef HAVE_POPPLER -#include +#include #include #include #include #include -#include +#include #ifdef HAVE_POPPLER_CAIRO -#include #include #include +#include #endif #include @@ -57,21 +57,18 @@ #include "ui/widget/spinbutton.h" #include "util/units.h" - - namespace { -void sanitize_page_number(int &page_num, const int num_pages) { +void sanitize_page_number(int &page_num, const int num_pages) +{ if (page_num < 1 || page_num > num_pages) { - std::cerr << "Inkscape::Extension::Internal::PdfInput::open: Bad page number " - << page_num - << ". Import first page instead." - << std::endl; + std::cerr << "Inkscape::Extension::Internal::PdfInput::open: Bad page number " << page_num + << ". Import first page instead." << std::endl; page_num = 1; } } -} +} // namespace namespace Inkscape { namespace Extension { @@ -82,17 +79,12 @@ namespace Internal { * FIXME: Probably this should be placed into src/ui/dialog */ -static const gchar * crop_setting_choices[] = { - //TRANSLATORS: The following are document crop settings for PDF import - // more info: http://www.acrobatusers.com/tech_corners/javascript_corner/tips/2006/page_bounds/ - N_("media box"), - N_("crop box"), - N_("trim box"), - N_("bleed box"), - N_("art box") -}; - -PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar */*uri*/) +static const gchar *crop_setting_choices[] = { + // TRANSLATORS: The following are document crop settings for PDF import + // more info: http://www.acrobatusers.com/tech_corners/javascript_corner/tips/2006/page_bounds/ + N_("media box"), N_("crop box"), N_("trim box"), N_("bleed box"), N_("art box")}; + +PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar * /*uri*/) : _pdf_doc(std::move(doc)) { assert(_pdf_doc); @@ -100,7 +92,7 @@ PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar */*uri _poppler_doc = NULL; #endif // HAVE_POPPLER_CAIRO cancelbutton = Gtk::manage(new Gtk::Button(_("_Cancel"), true)); - okbutton = Gtk::manage(new Gtk::Button(_("_OK"), true)); + okbutton = Gtk::manage(new Gtk::Button(_("_OK"), true)); _labelSelect = Gtk::manage(new class Gtk::Label(_("Select page:"))); // Page number @@ -110,7 +102,7 @@ PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar */*uri hbox2 = Gtk::manage(new class Gtk::HBox(false, 0)); // Disable the page selector when there's only one page int num_pages = _pdf_doc->getCatalog()->getNumPages(); - if ( num_pages == 1 ) { + if (num_pages == 1) { _pageNumberSpin->set_sensitive(false); } else { // Display total number of pages @@ -123,7 +115,7 @@ PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar */*uri _cropCheck = Gtk::manage(new class Gtk::CheckButton(_("Clip to:"))); _cropTypeCombo = Gtk::manage(new class Gtk::ComboBoxText()); int num_crop_choices = sizeof(crop_setting_choices) / sizeof(crop_setting_choices[0]); - for ( int i = 0 ; i < num_crop_choices ; i++ ) { + for (int i = 0; i < num_crop_choices; i++) { _cropTypeCombo->append(_(crop_setting_choices[i])); } _cropTypeCombo->set_active_text(_(crop_setting_choices[0])); @@ -133,16 +125,21 @@ PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar */*uri vbox2 = Gtk::manage(new class Gtk::VBox(false, 4)); _pageSettingsFrame = Gtk::manage(new class Inkscape::UI::Widget::Frame(_("Page settings"))); _labelPrecision = Gtk::manage(new class Gtk::Label(_("Precision of approximating gradient meshes:"))); - _labelPrecisionWarning = Gtk::manage(new class Gtk::Label(_("Note: setting the precision too high may result in a large SVG file and slow performance."))); + _labelPrecisionWarning = Gtk::manage(new class Gtk::Label( + _("Note: setting the precision too high may result in a large SVG file and slow performance."))); _labelPrecisionWarning->set_max_width_chars(50); #ifdef HAVE_POPPLER_CAIRO Gtk::RadioButton::Group group; - _importViaPoppler = Gtk::manage(new class Gtk::RadioButton(group,_("Poppler/Cairo import"))); - _labelViaPoppler = Gtk::manage(new class Gtk::Label(_("Import via external library. Text consists of groups containing cloned glyphs where each glyph is a path. Images are stored internally. Meshes cause entire document to be rendered as a raster image."))); + _importViaPoppler = Gtk::manage(new class Gtk::RadioButton(group, _("Poppler/Cairo import"))); + _labelViaPoppler = Gtk::manage(new class Gtk::Label( + _("Import via external library. Text consists of groups containing cloned glyphs where each glyph is a path. " + "Images are stored internally. Meshes cause entire document to be rendered as a raster image."))); _labelViaPoppler->set_max_width_chars(50); - _importViaInternal = Gtk::manage(new class Gtk::RadioButton(group,_("Internal import"))); - _labelViaInternal = Gtk::manage(new class Gtk::Label(_("Import via internal (Poppler derived) library. Text is stored as text but white space is missing. Meshes are converted to tiles, the number depends on the precision set below."))); + _importViaInternal = Gtk::manage(new class Gtk::RadioButton(group, _("Internal import"))); + _labelViaInternal = Gtk::manage(new class Gtk::Label( + _("Import via internal (Poppler derived) library. Text is stored as text but white space is missing. Meshes " + "are converted to tiles, the number depends on the precision set below."))); _labelViaInternal->set_max_width_chars(50); #endif @@ -248,13 +245,13 @@ PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar */*uri _labelViaInternal->set_xalign(0); #endif - _fallbackPrecisionSlider->set_size_request(180,-1); + _fallbackPrecisionSlider->set_size_request(180, -1); _fallbackPrecisionSlider->set_can_focus(); _fallbackPrecisionSlider->set_inverted(false); _fallbackPrecisionSlider->set_digits(1); _fallbackPrecisionSlider->set_draw_value(true); _fallbackPrecisionSlider->set_value_pos(Gtk::POS_TOP); - _labelPrecisionComment->set_size_request(90,-1); + _labelPrecisionComment->set_size_request(90, -1); _labelPrecisionComment->set_justify(Gtk::JUSTIFY_LEFT); _labelPrecisionComment->set_line_wrap(false); _labelPrecisionComment->set_use_markup(false); @@ -278,11 +275,11 @@ PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar */*uri _embedImagesCheck->set_mode(true); _embedImagesCheck->set_active(true); #ifdef HAVE_POPPLER_CAIRO - vbox3->pack_start(*_importViaPoppler, Gtk::PACK_SHRINK, 0); - vbox3->pack_start(*_labelViaPoppler, Gtk::PACK_SHRINK, 0); + vbox3->pack_start(*_importViaPoppler, Gtk::PACK_SHRINK, 0); + vbox3->pack_start(*_labelViaPoppler, Gtk::PACK_SHRINK, 0); vbox3->pack_start(*_importViaInternal, Gtk::PACK_SHRINK, 0); vbox3->pack_start(*_labelViaInternal, Gtk::PACK_SHRINK, 0); -#endif +#endif vbox3->pack_start(*_localFontsCheck, Gtk::PACK_SHRINK, 0); vbox3->pack_start(*_embedImagesCheck, Gtk::PACK_SHRINK, 0); vbox3->pack_start(*_labelPrecision, Gtk::PACK_SHRINK, 0); @@ -302,7 +299,7 @@ PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar */*uri this->set_title(_("PDF Import Settings")); this->set_modal(true); - sp_transientize(GTK_WIDGET(this->gobj())); //Make transient + sp_transientize(GTK_WIDGET(this->gobj())); // Make transient this->property_window_position().set_value(Gtk::WIN_POS_NONE); this->set_resizable(true); this->property_destroy_with_parent().set_value(false); @@ -310,12 +307,13 @@ PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar */*uri this->add_action_widget(*okbutton, -5); this->show_all(); - + // Connect signals _previewArea->signal_draw().connect(sigc::mem_fun(*this, &PdfImportDialog::_onDraw)); _pageNumberSpin_adj->signal_value_changed().connect(sigc::mem_fun(*this, &PdfImportDialog::_onPageNumberChanged)); _cropCheck->signal_toggled().connect(sigc::mem_fun(*this, &PdfImportDialog::_onToggleCropping)); - _fallbackPrecisionSlider_adj->signal_value_changed().connect(sigc::mem_fun(*this, &PdfImportDialog::_onPrecisionChanged)); + _fallbackPrecisionSlider_adj->signal_value_changed().connect( + sigc::mem_fun(*this, &PdfImportDialog::_onPrecisionChanged)); #ifdef HAVE_POPPLER_CAIRO _importViaPoppler->signal_toggled().connect(sigc::mem_fun(*this, &PdfImportDialog::_onToggleImport)); #endif @@ -328,10 +326,10 @@ PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar */*uri // Create PopplerDocument std::string filename = _pdf_doc->getFileName()->getCString(); if (!Glib::path_is_absolute(filename)) { - filename = Glib::build_filename(Glib::get_current_dir(),filename); + filename = Glib::build_filename(Glib::get_current_dir(), filename); } Glib::ustring full_uri = Glib::filename_to_uri(filename); - + if (!full_uri.empty()) { _poppler_doc = poppler_document_new_from_file(full_uri.c_str(), NULL, NULL); } @@ -350,11 +348,12 @@ PdfImportDialog::PdfImportDialog(std::shared_ptr doc, const gchar */*uri _current_page = 1; _setPreviewPage(_current_page); - set_default (*okbutton); - set_focus (*okbutton); + set_default(*okbutton); + set_focus(*okbutton); } -PdfImportDialog::~PdfImportDialog() { +PdfImportDialog::~PdfImportDialog() +{ #ifdef HAVE_POPPLER_CAIRO if (_cairo_surface) { cairo_surface_destroy(_cairo_surface); @@ -364,26 +363,29 @@ PdfImportDialog::~PdfImportDialog() { } #endif if (_thumb_data) { - gfree(_thumb_data); + gfree(_thumb_data); } } -bool PdfImportDialog::showDialog() { +bool PdfImportDialog::showDialog() +{ show(); gint b = run(); hide(); - if ( b == Gtk::RESPONSE_OK ) { + if (b == Gtk::RESPONSE_OK) { return TRUE; } else { return FALSE; } } -int PdfImportDialog::getSelectedPage() { +int PdfImportDialog::getSelectedPage() +{ return _current_page; } -bool PdfImportDialog::getImportMethod() { +bool PdfImportDialog::getImportMethod() +{ #ifdef HAVE_POPPLER_CAIRO return _importViaPoppler->get_active(); #else @@ -395,14 +397,15 @@ bool PdfImportDialog::getImportMethod() { * \brief Retrieves the current settings into a repr which SvgBuilder will use * for determining the behaviour desired by the user */ -void PdfImportDialog::getImportSettings(Inkscape::XML::Node *prefs) { +void PdfImportDialog::getImportSettings(Inkscape::XML::Node *prefs) +{ sp_repr_set_svg_double(prefs, "selectedPage", (double)_current_page); if (_cropCheck->get_active()) { Glib::ustring current_choice = _cropTypeCombo->get_active_text(); int num_crop_choices = sizeof(crop_setting_choices) / sizeof(crop_setting_choices[0]); int i = 0; - for ( ; i < num_crop_choices ; i++ ) { - if ( current_choice == _(crop_setting_choices[i]) ) { + for (; i < num_crop_choices; i++) { + if (current_choice == _(crop_setting_choices[i])) { break; } } @@ -410,8 +413,7 @@ void PdfImportDialog::getImportSettings(Inkscape::XML::Node *prefs) { } else { sp_repr_set_svg_double(prefs, "cropTo", -1.0); } - sp_repr_set_svg_double(prefs, "approximationPrecision", - _fallbackPrecisionSlider->get_value()); + sp_repr_set_svg_double(prefs, "approximationPrecision", _fallbackPrecisionSlider->get_value()); if (_localFontsCheck->get_active()) { prefs->setAttribute("localFonts", "1"); } else { @@ -435,37 +437,37 @@ void PdfImportDialog::getImportSettings(Inkscape::XML::Node *prefs) { * \brief Redisplay the comment on the current approximation precision setting * Evenly divides the interval of possible values between the available labels. */ -void PdfImportDialog::_onPrecisionChanged() { - +void PdfImportDialog::_onPrecisionChanged() +{ static Glib::ustring precision_comments[] = { - Glib::ustring(C_("PDF input precision", "rough")), - Glib::ustring(C_("PDF input precision", "medium")), - Glib::ustring(C_("PDF input precision", "fine")), - Glib::ustring(C_("PDF input precision", "very fine")) - }; + Glib::ustring(C_("PDF input precision", "rough")), Glib::ustring(C_("PDF input precision", "medium")), + Glib::ustring(C_("PDF input precision", "fine")), Glib::ustring(C_("PDF input precision", "very fine"))}; double min = _fallbackPrecisionSlider_adj->get_lower(); double max = _fallbackPrecisionSlider_adj->get_upper(); int num_intervals = sizeof(precision_comments) / sizeof(precision_comments[0]); - double interval_len = ( max - min ) / (double)num_intervals; + double interval_len = (max - min) / (double)num_intervals; double value = _fallbackPrecisionSlider_adj->get_value(); - int comment_idx = (int)floor( ( value - min ) / interval_len ); + int comment_idx = (int)floor((value - min) / interval_len); _labelPrecisionComment->set_label(precision_comments[comment_idx]); } -void PdfImportDialog::_onToggleCropping() { +void PdfImportDialog::_onToggleCropping() +{ _cropTypeCombo->set_sensitive(_cropCheck->get_active()); } -void PdfImportDialog::_onPageNumberChanged() { +void PdfImportDialog::_onPageNumberChanged() +{ int page = _pageNumberSpin->get_value_as_int(); _current_page = CLAMP(page, 1, _pdf_doc->getCatalog()->getNumPages()); _setPreviewPage(_current_page); } #ifdef HAVE_POPPLER_CAIRO -void PdfImportDialog::_onToggleImport() { - if( _importViaPoppler->get_active() ) { +void PdfImportDialog::_onToggleImport() +{ + if (_importViaPoppler->get_active()) { hbox3->set_sensitive(false); _localFontsCheck->set_sensitive(false); _embedImagesCheck->set_sensitive(false); @@ -479,7 +481,6 @@ void PdfImportDialog::_onToggleImport() { } #endif - #ifdef HAVE_POPPLER_CAIRO /** * \brief Copies image data from a Cairo surface to a pixbuf @@ -488,9 +489,7 @@ void PdfImportDialog::_onToggleImport() { * Copyright (C) 2005, Red Hat, Inc. * */ -static void copy_cairo_surface_to_pixbuf (cairo_surface_t *surface, - unsigned char *data, - GdkPixbuf *pixbuf) +static void copy_cairo_surface_to_pixbuf(cairo_surface_t *surface, unsigned char *data, GdkPixbuf *pixbuf) { int cairo_width, cairo_height, cairo_rowstride; unsigned char *pixbuf_data, *dst, *cairo_data; @@ -498,25 +497,23 @@ static void copy_cairo_surface_to_pixbuf (cairo_surface_t *surface, unsigned int *src; int x, y; - cairo_width = cairo_image_surface_get_width (surface); - cairo_height = cairo_image_surface_get_height (surface); + cairo_width = cairo_image_surface_get_width(surface); + cairo_height = cairo_image_surface_get_height(surface); cairo_rowstride = cairo_width * 4; cairo_data = data; - pixbuf_data = gdk_pixbuf_get_pixels (pixbuf); - pixbuf_rowstride = gdk_pixbuf_get_rowstride (pixbuf); - pixbuf_n_channels = gdk_pixbuf_get_n_channels (pixbuf); + pixbuf_data = gdk_pixbuf_get_pixels(pixbuf); + pixbuf_rowstride = gdk_pixbuf_get_rowstride(pixbuf); + pixbuf_n_channels = gdk_pixbuf_get_n_channels(pixbuf); - if (cairo_width > gdk_pixbuf_get_width (pixbuf)) - cairo_width = gdk_pixbuf_get_width (pixbuf); - if (cairo_height > gdk_pixbuf_get_height (pixbuf)) - cairo_height = gdk_pixbuf_get_height (pixbuf); - for (y = 0; y < cairo_height; y++) - { + if (cairo_width > gdk_pixbuf_get_width(pixbuf)) + cairo_width = gdk_pixbuf_get_width(pixbuf); + if (cairo_height > gdk_pixbuf_get_height(pixbuf)) + cairo_height = gdk_pixbuf_get_height(pixbuf); + for (y = 0; y < cairo_height; y++) { src = reinterpret_cast(cairo_data + y * cairo_rowstride); dst = pixbuf_data + y * pixbuf_rowstride; - for (x = 0; x < cairo_width; x++) - { + for (x = 0; x < cairo_width; x++) { dst[0] = (*src >> 16) & 0xff; dst[1] = (*src >> 8) & 0xff; dst[2] = (*src >> 0) & 0xff; @@ -530,7 +527,8 @@ static void copy_cairo_surface_to_pixbuf (cairo_surface_t *surface, #endif -bool PdfImportDialog::_onDraw(const Cairo::RefPtr& cr) { +bool PdfImportDialog::_onDraw(const Cairo::RefPtr &cr) +{ // Check if we have a thumbnail at all if (!_thumb_data) { return true; @@ -540,11 +538,10 @@ bool PdfImportDialog::_onDraw(const Cairo::RefPtr& cr) { Glib::RefPtr thumb; if (_render_thumb) { - thumb = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, true, - 8, _thumb_width, _thumb_height); + thumb = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, true, 8, _thumb_width, _thumb_height); } else { - thumb = Gdk::Pixbuf::create_from_data(_thumb_data, Gdk::COLORSPACE_RGB, - false, 8, _thumb_width, _thumb_height, _thumb_rowstride); + thumb = Gdk::Pixbuf::create_from_data(_thumb_data, Gdk::COLORSPACE_RGB, false, 8, _thumb_width, _thumb_height, + _thumb_rowstride); } if (!thumb) { return true; @@ -553,8 +550,8 @@ bool PdfImportDialog::_onDraw(const Cairo::RefPtr& cr) { // Set background to white if (_render_thumb) { thumb->fill(0xffffffff); - Gdk::Cairo::set_source_pixbuf(cr, thumb, 0, 0); - cr->paint(); + Gdk::Cairo::set_source_pixbuf(cr, thumb, 0, 0); + cr->paint(); } #ifdef HAVE_POPPLER_CAIRO // Copy the thumbnail image from the Cairo surface @@ -571,8 +568,8 @@ bool PdfImportDialog::_onDraw(const Cairo::RefPtr& cr) { /** * \brief Renders the given page's thumbnail using Cairo */ -void PdfImportDialog::_setPreviewPage(int page) { - +void PdfImportDialog::_setPreviewPage(int page) +{ _previewed_page = _pdf_doc->getCatalog()->getPage(page); g_return_if_fail(_previewed_page); // Try to get a thumbnail from the PDF if possible @@ -581,8 +578,7 @@ void PdfImportDialog::_setPreviewPage(int page) { gfree(_thumb_data); _thumb_data = nullptr; } - if (!_previewed_page->loadThumb(&_thumb_data, - &_thumb_width, &_thumb_height, &_thumb_rowstride)) { + if (!_previewed_page->loadThumb(&_thumb_data, &_thumb_width, &_thumb_height, &_thumb_rowstride)) { return; } // Redraw preview area @@ -594,7 +590,7 @@ void PdfImportDialog::_setPreviewPage(int page) { // Get page size by accounting for rotation double width, height; int rotate = _previewed_page->getRotate(); - if ( rotate == 90 || rotate == 270 ) { + if (rotate == 90 || rotate == 270) { height = _previewed_page->getCropWidth(); width = _previewed_page->getCropHeight(); } else { @@ -604,10 +600,10 @@ void PdfImportDialog::_setPreviewPage(int page) { // Calculate the needed scaling for the page double scale_x = (double)_preview_width / width; double scale_y = (double)_preview_height / height; - double scale_factor = ( scale_x > scale_y ) ? scale_y : scale_x; + double scale_factor = (scale_x > scale_y) ? scale_y : scale_x; // Create new Cairo surface - _thumb_width = (int)ceil( width * scale_factor ); - _thumb_height = (int)ceil( height * scale_factor ); + _thumb_width = (int)ceil(width * scale_factor); + _thumb_height = (int)ceil(height * scale_factor); _thumb_rowstride = _thumb_width * 4; if (_thumb_data) { gfree(_thumb_data); @@ -616,15 +612,15 @@ void PdfImportDialog::_setPreviewPage(int page) { if (_cairo_surface) { cairo_surface_destroy(_cairo_surface); } - _cairo_surface = cairo_image_surface_create_for_data(_thumb_data, - CAIRO_FORMAT_ARGB32, _thumb_width, _thumb_height, _thumb_rowstride); + _cairo_surface = cairo_image_surface_create_for_data(_thumb_data, CAIRO_FORMAT_ARGB32, _thumb_width, _thumb_height, + _thumb_rowstride); cairo_t *cr = cairo_create(_cairo_surface); - cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 1.0); // Set fill color to white - cairo_paint(cr); // Clear it - cairo_scale(cr, scale_factor, scale_factor); // Use Cairo for resizing the image + cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 1.0); // Set fill color to white + cairo_paint(cr); // Clear it + cairo_scale(cr, scale_factor, scale_factor); // Use Cairo for resizing the image // Render page if (_poppler_doc != NULL) { - PopplerPage *poppler_page = poppler_document_get_page(_poppler_doc, page-1); + PopplerPage *poppler_page = poppler_document_get_page(_poppler_doc, page - 1); poppler_page_render(poppler_page, cr); g_object_unref(G_OBJECT(poppler_page)); } @@ -640,11 +636,10 @@ void PdfImportDialog::_setPreviewPage(int page) { #ifdef HAVE_POPPLER_CAIRO /// helper method -static cairo_status_t - _write_ustring_cb(void *closure, const unsigned char *data, unsigned int length) +static cairo_status_t _write_ustring_cb(void *closure, const unsigned char *data, unsigned int length) { - Glib::ustring* stream = static_cast(closure); - stream->append(reinterpret_cast(data), length); + Glib::ustring *stream = static_cast(closure); + stream->append(reinterpret_cast(data), length); return CAIRO_STATUS_SUCCESS; } @@ -653,15 +648,13 @@ static cairo_status_t /** * Parses the selected page of the given PDF document using PdfParser. */ -SPDocument * -PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) { - +SPDocument *PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar *uri) +{ // Initialize the globalParams variable for poppler if (!globalParams) { globalParams = _POPPLER_NEW_GLOBAL_PARAMS(); } - // Open the file using poppler // PDFDoc is from poppler. PDFDoc is used for preview and for native import. std::shared_ptr pdf_doc; @@ -670,17 +663,18 @@ PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) { // poppler does not use glib g_open. So on win32 we must use unicode call. code was copied from // glib gstdio.c GooString *filename_goo = new GooString(uri); - pdf_doc = std::make_shared(filename_goo, nullptr, nullptr, nullptr); // TODO: Could ask for password - //delete filename_goo; + pdf_doc = std::make_shared(filename_goo, nullptr, nullptr, nullptr); // TODO: Could ask for password + // delete filename_goo; #else - wchar_t *wfilename = reinterpret_cast(g_utf8_to_utf16 (uri, -1, NULL, NULL, NULL)); + wchar_t *wfilename = reinterpret_cast(g_utf8_to_utf16(uri, -1, NULL, NULL, NULL)); if (wfilename == NULL) { - return NULL; + return NULL; } - pdf_doc = std::make_shared(wfilename, wcslen(wfilename), nullptr, nullptr, nullptr); // TODO: Could ask for password - g_free (wfilename); + pdf_doc = std::make_shared(wfilename, wcslen(wfilename), nullptr, nullptr, + nullptr); // TODO: Could ask for password + g_free(wfilename); #endif if (!pdf_doc->isOk()) { @@ -712,7 +706,6 @@ PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) { return nullptr; } - std::unique_ptr dlg; if (INKSCAPE.use_gui()) { dlg = std::make_unique(pdf_doc, uri); @@ -740,8 +733,7 @@ PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) { // Create Inkscape document from file SPDocument *doc = nullptr; bool saved = false; - if(!is_importvia_poppler) - { + if (!is_importvia_poppler) { // native importer // Check page exists @@ -777,7 +769,7 @@ PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) { double crop_setting = -1.0; sp_repr_get_double(prefs, "cropTo", &crop_setting); - if ( crop_setting >= 0.0 ) { // Do page clipping + if (crop_setting >= 0.0) { // Do page clipping int crop_choice = (int)crop_setting; switch (crop_choice) { case 0: // Media box @@ -801,18 +793,18 @@ PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) { } // Create parser (extension/internal/pdfinput/pdf-parser.h) - PdfParser *pdf_parser = new PdfParser(pdf_doc->getXRef(), builder, page_num-1, page->getRotate(), + PdfParser *pdf_parser = new PdfParser(pdf_doc->getXRef(), builder, page_num - 1, page->getRotate(), page->getResourceDict(), page->getCropBox(), clipToBox); // Set up approximation precision for parser. Used for converting Mesh Gradients into tiles. double color_delta = 2.0; sp_repr_get_double(prefs, "approximationPrecision", &color_delta); - if ( color_delta <= 0.0 ) { + if (color_delta <= 0.0) { color_delta = 1.0 / 2.0; } else { color_delta = 1.0 / color_delta; } - for ( int i = 1 ; i <= pdfNumShadingTypes ; i++ ) { + for (int i = 1; i <= pdfNumShadingTypes; i++) { pdf_parser->setApproximationPrecision(i, color_delta, 6); } @@ -834,27 +826,25 @@ PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) { delete pdf_parser; delete builder; g_free(docname); - } - else - { + } else { #ifdef HAVE_POPPLER_CAIRO // the poppler import std::string full_path = uri; if (!Glib::path_is_absolute(uri)) { - full_path = Glib::build_filename(Glib::get_current_dir(),uri); + full_path = Glib::build_filename(Glib::get_current_dir(), uri); } Glib::ustring full_uri = Glib::filename_to_uri(full_path); GError *error = NULL; /// @todo handle password /// @todo check if win32 unicode needs special attention - PopplerDocument* document = poppler_document_new_from_file(full_uri.c_str(), NULL, &error); - PopplerPage* page = nullptr; + PopplerDocument *document = poppler_document_new_from_file(full_uri.c_str(), NULL, &error); + PopplerPage *page = nullptr; - if(error != NULL) { + if (error != NULL) { std::cerr << "PDFInput::open: error opening document: " << full_uri << std::endl; - g_error_free (error); + g_error_free(error); } if (document) { @@ -868,16 +858,16 @@ PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) { poppler_page_get_size(page, &width, &height); Glib::ustring output; - cairo_surface_t* surface = cairo_svg_surface_create_for_stream(Inkscape::Extension::Internal::_write_ustring_cb, - &output, width, height); + cairo_surface_t *surface = cairo_svg_surface_create_for_stream( + Inkscape::Extension::Internal::_write_ustring_cb, &output, width, height); // This magical function results in more fine-grain fallbacks. In particular, a mesh // gradient won't necessarily result in the whole PDF being rasterized. Of course, SVG // 1.2 never made it as a standard, but hey, we'll take what we can get. This trick was // found by examining the 'pdftocairo' code. - cairo_svg_surface_restrict_to_version( surface, CAIRO_SVG_VERSION_1_2 ); + cairo_svg_surface_restrict_to_version(surface, CAIRO_SVG_VERSION_1_2); - cairo_t* cr = cairo_create(surface); + cairo_t *cr = cairo_create(surface); poppler_page_render_for_printing(page, cr); cairo_show_page(cr); @@ -909,7 +899,8 @@ PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) { // Set viewBox if it doesn't exist if (!doc->getRoot()->viewBox_set) { - doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), doc->getHeight().value(doc->getDisplayUnit()))); + doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), + doc->getHeight().value(doc->getDisplayUnit()))); } // Restore undo @@ -920,7 +911,8 @@ PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) { #include "../clear-n_.h" -void PdfInput::init() { +void PdfInput::init() +{ /* PDF in */ // clang-format off Inkscape::Extension::build_from_mem( @@ -952,7 +944,9 @@ void PdfInput::init() { // clang-format on } // init -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* HAVE_POPPLER */ diff --git a/src/extension/internal/pdfinput/pdf-input.h b/src/extension/internal/pdfinput/pdf-input.h index 66f750d6617ac044d68e11d38a421ff21584e4e0..7cebb9da3dcef91eb9e144f923f3786b88b5f466 100644 --- a/src/extension/internal/pdfinput/pdf-input.h +++ b/src/extension/internal/pdfinput/pdf-input.h @@ -12,19 +12,18 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef HAVE_POPPLER -#include "poppler-transition-api.h" - #include #include "../../implementation/implementation.h" +#include "poppler-transition-api.h" #ifdef HAVE_POPPLER_CAIRO struct _PopplerDocument; -typedef struct _PopplerDocument PopplerDocument; +typedef struct _PopplerDocument PopplerDocument; #endif struct _GdkEventExpose; @@ -34,26 +33,26 @@ class Page; class PDFDoc; namespace Gtk { - class Button; - class CheckButton; - class ComboBoxText; - class DrawingArea; - class Frame; - class HBox; - class Scale; - class RadioButton; - class VBox; - class Label; -} +class Button; +class CheckButton; +class ComboBoxText; +class DrawingArea; +class Frame; +class HBox; +class Scale; +class RadioButton; +class VBox; +class Label; +} // namespace Gtk namespace Inkscape { namespace UI { namespace Widget { - class SpinButton; - class Frame; -} -} +class SpinButton; +class Frame; +} // namespace Widget +} // namespace UI namespace Extension { namespace Internal { @@ -76,74 +75,75 @@ private: void _setPreviewPage(int page); // Signal handlers - bool _onDraw(const Cairo::RefPtr& cr); + bool _onDraw(const Cairo::RefPtr &cr); void _onPageNumberChanged(); void _onToggleCropping(); void _onPrecisionChanged(); #ifdef HAVE_POPPLER_CAIRO void _onToggleImport(); #endif - - class Gtk::Button * cancelbutton; - class Gtk::Button * okbutton; - class Gtk::Label * _labelSelect; - class Inkscape::UI::Widget::SpinButton * _pageNumberSpin; - class Gtk::Label * _labelTotalPages; - class Gtk::HBox * hbox2; - class Gtk::CheckButton * _cropCheck; - class Gtk::ComboBoxText * _cropTypeCombo; - class Gtk::HBox * hbox3; - class Gtk::VBox * vbox2; - class Inkscape::UI::Widget::Frame * _pageSettingsFrame; - class Gtk::Label * _labelPrecision; - class Gtk::Label * _labelPrecisionWarning; + + class Gtk::Button *cancelbutton; + class Gtk::Button *okbutton; + class Gtk::Label *_labelSelect; + class Inkscape::UI::Widget::SpinButton *_pageNumberSpin; + class Gtk::Label *_labelTotalPages; + class Gtk::HBox *hbox2; + class Gtk::CheckButton *_cropCheck; + class Gtk::ComboBoxText *_cropTypeCombo; + class Gtk::HBox *hbox3; + class Gtk::VBox *vbox2; + class Inkscape::UI::Widget::Frame *_pageSettingsFrame; + class Gtk::Label *_labelPrecision; + class Gtk::Label *_labelPrecisionWarning; #ifdef HAVE_POPPLER_CAIRO - class Gtk::RadioButton * _importViaPoppler; // Use poppler_cairo importing - class Gtk::Label * _labelViaPoppler; - class Gtk::RadioButton * _importViaInternal; // Use native (poppler based) importing - class Gtk::Label * _labelViaInternal; + class Gtk::RadioButton *_importViaPoppler; // Use poppler_cairo importing + class Gtk::Label *_labelViaPoppler; + class Gtk::RadioButton *_importViaInternal; // Use native (poppler based) importing + class Gtk::Label *_labelViaInternal; #endif - Gtk::Scale * _fallbackPrecisionSlider; + Gtk::Scale *_fallbackPrecisionSlider; Glib::RefPtr _fallbackPrecisionSlider_adj; - class Gtk::Label * _labelPrecisionComment; - class Gtk::HBox * hbox6; + class Gtk::Label *_labelPrecisionComment; + class Gtk::HBox *hbox6; #if 0 class Gtk::Label * _labelText; class Gtk::ComboBoxText * _textHandlingCombo; class Gtk::HBox * hbox5; #endif - class Gtk::CheckButton * _localFontsCheck; - class Gtk::CheckButton * _embedImagesCheck; - class Gtk::VBox * vbox3; - class Inkscape::UI::Widget::Frame * _importSettingsFrame; - class Gtk::VBox * vbox1; - class Gtk::DrawingArea * _previewArea; - class Gtk::HBox * hbox1; - - std::shared_ptr _pdf_doc; // Document to be imported - int _current_page; // Current selected page - Page *_previewed_page; // Currently previewed page - unsigned char *_thumb_data; // Thumbnail image data - int _thumb_width, _thumb_height; // Thumbnail size + class Gtk::CheckButton *_localFontsCheck; + class Gtk::CheckButton *_embedImagesCheck; + class Gtk::VBox *vbox3; + class Inkscape::UI::Widget::Frame *_importSettingsFrame; + class Gtk::VBox *vbox1; + class Gtk::DrawingArea *_previewArea; + class Gtk::HBox *hbox1; + + std::shared_ptr _pdf_doc; // Document to be imported + int _current_page; // Current selected page + Page *_previewed_page; // Currently previewed page + unsigned char *_thumb_data; // Thumbnail image data + int _thumb_width, _thumb_height; // Thumbnail size int _thumb_rowstride; - int _preview_width, _preview_height; // Size of the preview area - bool _render_thumb; // Whether we can/shall render thumbnails + int _preview_width, _preview_height; // Size of the preview area + bool _render_thumb; // Whether we can/shall render thumbnails #ifdef HAVE_POPPLER_CAIRO cairo_surface_t *_cairo_surface; PopplerDocument *_poppler_doc; #endif }; - -class PdfInput: public Inkscape::Extension::Implementation::Implementation { - PdfInput () = default;; +class PdfInput : public Inkscape::Extension::Implementation::Implementation +{ + PdfInput() = default; + ; + public: - SPDocument *open( Inkscape::Extension::Input *mod, - const gchar *uri ) override; - static void init( ); + SPDocument *open(Inkscape::Extension::Input *mod, const gchar *uri) override; + static void init(); }; -} // namespace Implementation +} // namespace Internal } // namespace Extension } // namespace Inkscape diff --git a/src/extension/internal/pdfinput/pdf-parser.cpp b/src/extension/internal/pdfinput/pdf-parser.cpp index 1bc5742409ed5b3d2089843b9983c26ac43fe3f3..6e95352e27a7e4daad2e559dd3e5227e54e3cc8b 100644 --- a/src/extension/internal/pdfinput/pdf-parser.cpp +++ b/src/extension/internal/pdfinput/pdf-parser.cpp @@ -11,7 +11,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef HAVE_POPPLER @@ -20,34 +20,33 @@ #pragma implementation #endif -#include -#include +#include #include +#include +#include #include -#include - -#include "svg-builder.h" -#include "Gfx.h" -#include "pdf-parser.h" -#include "util/units.h" -#include "glib/poppler-features.h" -#include "goo/gmem.h" -#include "goo/GooString.h" -#include "GlobalParams.h" -#include "CharTypes.h" -#include "Object.h" +#include "Annot.h" #include "Array.h" +#include "CharTypes.h" #include "Dict.h" -#include "Stream.h" -#include "Lexer.h" -#include "Parser.h" +#include "Error.h" +#include "Gfx.h" #include "GfxFont.h" #include "GfxState.h" +#include "GlobalParams.h" +#include "Lexer.h" +#include "Object.h" #include "OutputDev.h" #include "Page.h" -#include "Annot.h" -#include "Error.h" +#include "Parser.h" +#include "Stream.h" +#include "glib/poppler-features.h" +#include "goo/GooString.h" +#include "goo/gmem.h" +#include "pdf-parser.h" +#include "svg-builder.h" +#include "util/units.h" // the MSVC math.h doesn't define this #ifndef M_PI @@ -59,7 +58,7 @@ //------------------------------------------------------------------------ // Default max delta allowed in any color component for a shading fill. -#define defaultShadingColorDelta (dblToCol( 1 / 2.0 )) +#define defaultShadingColorDelta (dblToCol(1 / 2.0)) // Default max recursive depth for a shading fill. #define defaultShadingMaxDepth 6 @@ -72,173 +71,93 @@ //------------------------------------------------------------------------ PdfOperator PdfParser::opTab[] = { - {"\"", 3, {tchkNum, tchkNum, tchkString}, - &PdfParser::opMoveSetShowText}, - {"'", 1, {tchkString}, - &PdfParser::opMoveShowText}, - {"B", 0, {tchkNone}, - &PdfParser::opFillStroke}, - {"B*", 0, {tchkNone}, - &PdfParser::opEOFillStroke}, - {"BDC", 2, {tchkName, tchkProps}, - &PdfParser::opBeginMarkedContent}, - {"BI", 0, {tchkNone}, - &PdfParser::opBeginImage}, - {"BMC", 1, {tchkName}, - &PdfParser::opBeginMarkedContent}, - {"BT", 0, {tchkNone}, - &PdfParser::opBeginText}, - {"BX", 0, {tchkNone}, - &PdfParser::opBeginIgnoreUndef}, - {"CS", 1, {tchkName}, - &PdfParser::opSetStrokeColorSpace}, - {"DP", 2, {tchkName, tchkProps}, - &PdfParser::opMarkPoint}, - {"Do", 1, {tchkName}, - &PdfParser::opXObject}, - {"EI", 0, {tchkNone}, - &PdfParser::opEndImage}, - {"EMC", 0, {tchkNone}, - &PdfParser::opEndMarkedContent}, - {"ET", 0, {tchkNone}, - &PdfParser::opEndText}, - {"EX", 0, {tchkNone}, - &PdfParser::opEndIgnoreUndef}, - {"F", 0, {tchkNone}, - &PdfParser::opFill}, - {"G", 1, {tchkNum}, - &PdfParser::opSetStrokeGray}, - {"ID", 0, {tchkNone}, - &PdfParser::opImageData}, - {"J", 1, {tchkInt}, - &PdfParser::opSetLineCap}, - {"K", 4, {tchkNum, tchkNum, tchkNum, tchkNum}, - &PdfParser::opSetStrokeCMYKColor}, - {"M", 1, {tchkNum}, - &PdfParser::opSetMiterLimit}, - {"MP", 1, {tchkName}, - &PdfParser::opMarkPoint}, - {"Q", 0, {tchkNone}, - &PdfParser::opRestore}, - {"RG", 3, {tchkNum, tchkNum, tchkNum}, - &PdfParser::opSetStrokeRGBColor}, - {"S", 0, {tchkNone}, - &PdfParser::opStroke}, - {"SC", -4, {tchkNum, tchkNum, tchkNum, tchkNum}, - &PdfParser::opSetStrokeColor}, - {"SCN", -33, {tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN,}, - &PdfParser::opSetStrokeColorN}, - {"T*", 0, {tchkNone}, - &PdfParser::opTextNextLine}, - {"TD", 2, {tchkNum, tchkNum}, - &PdfParser::opTextMoveSet}, - {"TJ", 1, {tchkArray}, - &PdfParser::opShowSpaceText}, - {"TL", 1, {tchkNum}, - &PdfParser::opSetTextLeading}, - {"Tc", 1, {tchkNum}, - &PdfParser::opSetCharSpacing}, - {"Td", 2, {tchkNum, tchkNum}, - &PdfParser::opTextMove}, - {"Tf", 2, {tchkName, tchkNum}, - &PdfParser::opSetFont}, - {"Tj", 1, {tchkString}, - &PdfParser::opShowText}, - {"Tm", 6, {tchkNum, tchkNum, tchkNum, tchkNum, - tchkNum, tchkNum}, - &PdfParser::opSetTextMatrix}, - {"Tr", 1, {tchkInt}, - &PdfParser::opSetTextRender}, - {"Ts", 1, {tchkNum}, - &PdfParser::opSetTextRise}, - {"Tw", 1, {tchkNum}, - &PdfParser::opSetWordSpacing}, - {"Tz", 1, {tchkNum}, - &PdfParser::opSetHorizScaling}, - {"W", 0, {tchkNone}, - &PdfParser::opClip}, - {"W*", 0, {tchkNone}, - &PdfParser::opEOClip}, - {"b", 0, {tchkNone}, - &PdfParser::opCloseFillStroke}, - {"b*", 0, {tchkNone}, - &PdfParser::opCloseEOFillStroke}, - {"c", 6, {tchkNum, tchkNum, tchkNum, tchkNum, - tchkNum, tchkNum}, - &PdfParser::opCurveTo}, - {"cm", 6, {tchkNum, tchkNum, tchkNum, tchkNum, - tchkNum, tchkNum}, - &PdfParser::opConcat}, - {"cs", 1, {tchkName}, - &PdfParser::opSetFillColorSpace}, - {"d", 2, {tchkArray, tchkNum}, - &PdfParser::opSetDash}, - {"d0", 2, {tchkNum, tchkNum}, - &PdfParser::opSetCharWidth}, - {"d1", 6, {tchkNum, tchkNum, tchkNum, tchkNum, - tchkNum, tchkNum}, - &PdfParser::opSetCacheDevice}, - {"f", 0, {tchkNone}, - &PdfParser::opFill}, - {"f*", 0, {tchkNone}, - &PdfParser::opEOFill}, - {"g", 1, {tchkNum}, - &PdfParser::opSetFillGray}, - {"gs", 1, {tchkName}, - &PdfParser::opSetExtGState}, - {"h", 0, {tchkNone}, - &PdfParser::opClosePath}, - {"i", 1, {tchkNum}, - &PdfParser::opSetFlat}, - {"j", 1, {tchkInt}, - &PdfParser::opSetLineJoin}, - {"k", 4, {tchkNum, tchkNum, tchkNum, tchkNum}, - &PdfParser::opSetFillCMYKColor}, - {"l", 2, {tchkNum, tchkNum}, - &PdfParser::opLineTo}, - {"m", 2, {tchkNum, tchkNum}, - &PdfParser::opMoveTo}, - {"n", 0, {tchkNone}, - &PdfParser::opEndPath}, - {"q", 0, {tchkNone}, - &PdfParser::opSave}, - {"re", 4, {tchkNum, tchkNum, tchkNum, tchkNum}, - &PdfParser::opRectangle}, - {"rg", 3, {tchkNum, tchkNum, tchkNum}, - &PdfParser::opSetFillRGBColor}, - {"ri", 1, {tchkName}, - &PdfParser::opSetRenderingIntent}, - {"s", 0, {tchkNone}, - &PdfParser::opCloseStroke}, - {"sc", -4, {tchkNum, tchkNum, tchkNum, tchkNum}, - &PdfParser::opSetFillColor}, - {"scn", -33, {tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN, tchkSCN, tchkSCN, tchkSCN, - tchkSCN,}, - &PdfParser::opSetFillColorN}, - {"sh", 1, {tchkName}, - &PdfParser::opShFill}, - {"v", 4, {tchkNum, tchkNum, tchkNum, tchkNum}, - &PdfParser::opCurveTo1}, - {"w", 1, {tchkNum}, - &PdfParser::opSetLineWidth}, - {"y", 4, {tchkNum, tchkNum, tchkNum, tchkNum}, - &PdfParser::opCurveTo2} -}; + {"\"", 3, {tchkNum, tchkNum, tchkString}, &PdfParser::opMoveSetShowText}, + {"'", 1, {tchkString}, &PdfParser::opMoveShowText}, + {"B", 0, {tchkNone}, &PdfParser::opFillStroke}, + {"B*", 0, {tchkNone}, &PdfParser::opEOFillStroke}, + {"BDC", 2, {tchkName, tchkProps}, &PdfParser::opBeginMarkedContent}, + {"BI", 0, {tchkNone}, &PdfParser::opBeginImage}, + {"BMC", 1, {tchkName}, &PdfParser::opBeginMarkedContent}, + {"BT", 0, {tchkNone}, &PdfParser::opBeginText}, + {"BX", 0, {tchkNone}, &PdfParser::opBeginIgnoreUndef}, + {"CS", 1, {tchkName}, &PdfParser::opSetStrokeColorSpace}, + {"DP", 2, {tchkName, tchkProps}, &PdfParser::opMarkPoint}, + {"Do", 1, {tchkName}, &PdfParser::opXObject}, + {"EI", 0, {tchkNone}, &PdfParser::opEndImage}, + {"EMC", 0, {tchkNone}, &PdfParser::opEndMarkedContent}, + {"ET", 0, {tchkNone}, &PdfParser::opEndText}, + {"EX", 0, {tchkNone}, &PdfParser::opEndIgnoreUndef}, + {"F", 0, {tchkNone}, &PdfParser::opFill}, + {"G", 1, {tchkNum}, &PdfParser::opSetStrokeGray}, + {"ID", 0, {tchkNone}, &PdfParser::opImageData}, + {"J", 1, {tchkInt}, &PdfParser::opSetLineCap}, + {"K", 4, {tchkNum, tchkNum, tchkNum, tchkNum}, &PdfParser::opSetStrokeCMYKColor}, + {"M", 1, {tchkNum}, &PdfParser::opSetMiterLimit}, + {"MP", 1, {tchkName}, &PdfParser::opMarkPoint}, + {"Q", 0, {tchkNone}, &PdfParser::opRestore}, + {"RG", 3, {tchkNum, tchkNum, tchkNum}, &PdfParser::opSetStrokeRGBColor}, + {"S", 0, {tchkNone}, &PdfParser::opStroke}, + {"SC", -4, {tchkNum, tchkNum, tchkNum, tchkNum}, &PdfParser::opSetStrokeColor}, + {"SCN", + -33, + { + tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, + tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, + tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, + }, + &PdfParser::opSetStrokeColorN}, + {"T*", 0, {tchkNone}, &PdfParser::opTextNextLine}, + {"TD", 2, {tchkNum, tchkNum}, &PdfParser::opTextMoveSet}, + {"TJ", 1, {tchkArray}, &PdfParser::opShowSpaceText}, + {"TL", 1, {tchkNum}, &PdfParser::opSetTextLeading}, + {"Tc", 1, {tchkNum}, &PdfParser::opSetCharSpacing}, + {"Td", 2, {tchkNum, tchkNum}, &PdfParser::opTextMove}, + {"Tf", 2, {tchkName, tchkNum}, &PdfParser::opSetFont}, + {"Tj", 1, {tchkString}, &PdfParser::opShowText}, + {"Tm", 6, {tchkNum, tchkNum, tchkNum, tchkNum, tchkNum, tchkNum}, &PdfParser::opSetTextMatrix}, + {"Tr", 1, {tchkInt}, &PdfParser::opSetTextRender}, + {"Ts", 1, {tchkNum}, &PdfParser::opSetTextRise}, + {"Tw", 1, {tchkNum}, &PdfParser::opSetWordSpacing}, + {"Tz", 1, {tchkNum}, &PdfParser::opSetHorizScaling}, + {"W", 0, {tchkNone}, &PdfParser::opClip}, + {"W*", 0, {tchkNone}, &PdfParser::opEOClip}, + {"b", 0, {tchkNone}, &PdfParser::opCloseFillStroke}, + {"b*", 0, {tchkNone}, &PdfParser::opCloseEOFillStroke}, + {"c", 6, {tchkNum, tchkNum, tchkNum, tchkNum, tchkNum, tchkNum}, &PdfParser::opCurveTo}, + {"cm", 6, {tchkNum, tchkNum, tchkNum, tchkNum, tchkNum, tchkNum}, &PdfParser::opConcat}, + {"cs", 1, {tchkName}, &PdfParser::opSetFillColorSpace}, + {"d", 2, {tchkArray, tchkNum}, &PdfParser::opSetDash}, + {"d0", 2, {tchkNum, tchkNum}, &PdfParser::opSetCharWidth}, + {"d1", 6, {tchkNum, tchkNum, tchkNum, tchkNum, tchkNum, tchkNum}, &PdfParser::opSetCacheDevice}, + {"f", 0, {tchkNone}, &PdfParser::opFill}, + {"f*", 0, {tchkNone}, &PdfParser::opEOFill}, + {"g", 1, {tchkNum}, &PdfParser::opSetFillGray}, + {"gs", 1, {tchkName}, &PdfParser::opSetExtGState}, + {"h", 0, {tchkNone}, &PdfParser::opClosePath}, + {"i", 1, {tchkNum}, &PdfParser::opSetFlat}, + {"j", 1, {tchkInt}, &PdfParser::opSetLineJoin}, + {"k", 4, {tchkNum, tchkNum, tchkNum, tchkNum}, &PdfParser::opSetFillCMYKColor}, + {"l", 2, {tchkNum, tchkNum}, &PdfParser::opLineTo}, + {"m", 2, {tchkNum, tchkNum}, &PdfParser::opMoveTo}, + {"n", 0, {tchkNone}, &PdfParser::opEndPath}, + {"q", 0, {tchkNone}, &PdfParser::opSave}, + {"re", 4, {tchkNum, tchkNum, tchkNum, tchkNum}, &PdfParser::opRectangle}, + {"rg", 3, {tchkNum, tchkNum, tchkNum}, &PdfParser::opSetFillRGBColor}, + {"ri", 1, {tchkName}, &PdfParser::opSetRenderingIntent}, + {"s", 0, {tchkNone}, &PdfParser::opCloseStroke}, + {"sc", -4, {tchkNum, tchkNum, tchkNum, tchkNum}, &PdfParser::opSetFillColor}, + {"scn", + -33, + { + tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, + tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, + tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, + }, + &PdfParser::opSetFillColorN}, + {"sh", 1, {tchkName}, &PdfParser::opShFill}, + {"v", 4, {tchkNum, tchkNum, tchkNum, tchkNum}, &PdfParser::opCurveTo1}, + {"w", 1, {tchkNum}, &PdfParser::opSetLineWidth}, + {"y", 4, {tchkNum, tchkNum, tchkNum, tchkNum}, &PdfParser::opCurveTo2}}; #define numOps (sizeof(opTab) / sizeof(PdfOperator)) @@ -257,9 +176,9 @@ GfxPatch blankPatch() // ClipHistoryEntry //------------------------------------------------------------------------ -class ClipHistoryEntry { +class ClipHistoryEntry +{ public: - ClipHistoryEntry(GfxPath *clipPath = nullptr, GfxClipType clipType = clipNormal); virtual ~ClipHistoryEntry(); @@ -272,10 +191,9 @@ public: GfxClipType getClipType() { return clipType; } private: + ClipHistoryEntry *saved; // next clip path on stack - ClipHistoryEntry *saved; // next clip path on stack - - GfxPath *clipPath; // used as the path to be filled for an 'sh' operator + GfxPath *clipPath; // used as the path to be filled for an 'sh' operator GfxClipType clipType; ClipHistoryEntry(ClipHistoryEntry *other); @@ -285,218 +203,213 @@ private: // PdfParser //------------------------------------------------------------------------ -PdfParser::PdfParser(XRef *xrefA, - Inkscape::Extension::Internal::SvgBuilder *builderA, - int /*pageNum*/, - int rotate, - Dict *resDict, - _POPPLER_CONST PDFRectangle *box, - _POPPLER_CONST PDFRectangle *cropBox) : - xref(xrefA), - builder(builderA), - subPage(gFalse), - printCommands(false), - res(new GfxResources(xref, resDict, nullptr)), // start the resource stack - state(new GfxState(72.0, 72.0, box, rotate, gTrue)), - fontChanged(gFalse), - clip(clipNone), - ignoreUndef(0), - baseMatrix(), - formDepth(0), - parser(nullptr), - colorDeltas(), - maxDepths(), - clipHistory(new ClipHistoryEntry()), - operatorHistory(nullptr) -{ - setDefaultApproximationPrecision(); - builder->setDocumentSize(Inkscape::Util::Quantity::convert(state->getPageWidth(), "pt", "px"), - Inkscape::Util::Quantity::convert(state->getPageHeight(), "pt", "px")); - - const double *ctm = state->getCTM(); - double scaledCTM[6]; - for (int i = 0; i < 6; ++i) { - baseMatrix[i] = ctm[i]; - scaledCTM[i] = Inkscape::Util::Quantity::convert(ctm[i], "pt", "px"); - } - saveState(); - builder->setTransform((double*)&scaledCTM); - formDepth = 0; - - // set crop box - if (cropBox) { - if (printCommands) - printf("cropBox: %f %f %f %f\n", cropBox->x1, cropBox->y1, cropBox->x2, cropBox->y2); - // do not clip if it's not needed - if (cropBox->x1 != 0.0 || cropBox->y1 != 0.0 || - cropBox->x2 != state->getPageWidth() || cropBox->y2 != state->getPageHeight()) { - - state->moveTo(cropBox->x1, cropBox->y1); - state->lineTo(cropBox->x2, cropBox->y1); - state->lineTo(cropBox->x2, cropBox->y2); - state->lineTo(cropBox->x1, cropBox->y2); - state->closePath(); - state->clip(); - clipHistory->setClip(state->getPath(), clipNormal); - builder->setClipPath(state); - state->clearPath(); +PdfParser::PdfParser(XRef *xrefA, Inkscape::Extension::Internal::SvgBuilder *builderA, int /*pageNum*/, int rotate, + Dict *resDict, _POPPLER_CONST PDFRectangle *box, _POPPLER_CONST PDFRectangle *cropBox) + : xref(xrefA) + , builder(builderA) + , subPage(gFalse) + , printCommands(false) + , res(new GfxResources(xref, resDict, nullptr)) + , // start the resource stack + state(new GfxState(72.0, 72.0, box, rotate, gTrue)) + , fontChanged(gFalse) + , clip(clipNone) + , ignoreUndef(0) + , baseMatrix() + , formDepth(0) + , parser(nullptr) + , colorDeltas() + , maxDepths() + , clipHistory(new ClipHistoryEntry()) + , operatorHistory(nullptr) +{ + setDefaultApproximationPrecision(); + builder->setDocumentSize(Inkscape::Util::Quantity::convert(state->getPageWidth(), "pt", "px"), + Inkscape::Util::Quantity::convert(state->getPageHeight(), "pt", "px")); + + const double *ctm = state->getCTM(); + double scaledCTM[6]; + for (int i = 0; i < 6; ++i) { + baseMatrix[i] = ctm[i]; + scaledCTM[i] = Inkscape::Util::Quantity::convert(ctm[i], "pt", "px"); } - } - pushOperator("startPage"); -} - -PdfParser::PdfParser(XRef *xrefA, - Inkscape::Extension::Internal::SvgBuilder *builderA, - Dict *resDict, - _POPPLER_CONST PDFRectangle *box) : - xref(xrefA), - builder(builderA), - subPage(gTrue), - printCommands(false), - res(new GfxResources(xref, resDict, nullptr)), // start the resource stack - state(new GfxState(72, 72, box, 0, gFalse)), - fontChanged(gFalse), - clip(clipNone), - ignoreUndef(0), - baseMatrix(), - formDepth(0), - parser(nullptr), - colorDeltas(), - maxDepths(), - clipHistory(new ClipHistoryEntry()), - operatorHistory(nullptr) -{ - setDefaultApproximationPrecision(); - - for (int i = 0; i < 6; ++i) { - baseMatrix[i] = state->getCTM()[i]; - } - formDepth = 0; -} - -PdfParser::~PdfParser() { - while(operatorHistory) { - OpHistoryEntry *tmp = operatorHistory->next; - delete operatorHistory; - operatorHistory = tmp; - } - - while (state && state->hasSaves()) { - restoreState(); - } + saveState(); + builder->setTransform((double *)&scaledCTM); + formDepth = 0; + + // set crop box + if (cropBox) { + if (printCommands) + printf("cropBox: %f %f %f %f\n", cropBox->x1, cropBox->y1, cropBox->x2, cropBox->y2); + // do not clip if it's not needed + if (cropBox->x1 != 0.0 || cropBox->y1 != 0.0 || cropBox->x2 != state->getPageWidth() || + cropBox->y2 != state->getPageHeight()) { + state->moveTo(cropBox->x1, cropBox->y1); + state->lineTo(cropBox->x2, cropBox->y1); + state->lineTo(cropBox->x2, cropBox->y2); + state->lineTo(cropBox->x1, cropBox->y2); + state->closePath(); + state->clip(); + clipHistory->setClip(state->getPath(), clipNormal); + builder->setClipPath(state); + state->clearPath(); + } + } + pushOperator("startPage"); +} + +PdfParser::PdfParser(XRef *xrefA, Inkscape::Extension::Internal::SvgBuilder *builderA, Dict *resDict, + _POPPLER_CONST PDFRectangle *box) + : xref(xrefA) + , builder(builderA) + , subPage(gTrue) + , printCommands(false) + , res(new GfxResources(xref, resDict, nullptr)) + , // start the resource stack + state(new GfxState(72, 72, box, 0, gFalse)) + , fontChanged(gFalse) + , clip(clipNone) + , ignoreUndef(0) + , baseMatrix() + , formDepth(0) + , parser(nullptr) + , colorDeltas() + , maxDepths() + , clipHistory(new ClipHistoryEntry()) + , operatorHistory(nullptr) +{ + setDefaultApproximationPrecision(); - if (!subPage) { - //out->endPage(); - } + for (int i = 0; i < 6; ++i) { + baseMatrix[i] = state->getCTM()[i]; + } + formDepth = 0; +} - while (res) { - popResources(); - } - - if (state) { - delete state; - state = nullptr; - } - - if (clipHistory) { - delete clipHistory; - clipHistory = nullptr; - } -} - -void PdfParser::parse(Object *obj, GBool topLevel) { - Object obj2; - - if (obj->isArray()) { - for (int i = 0; i < obj->arrayGetLength(); ++i) { - _POPPLER_CALL_ARGS(obj2, obj->arrayGet, i); - if (!obj2.isStream()) { - error(errInternal, -1, "Weird page contents"); - _POPPLER_FREE(obj2); - return; - } - _POPPLER_FREE(obj2); - } - } else if (!obj->isStream()) { - error(errInternal, -1, "Weird page contents"); - return; - } - parser = new _POPPLER_NEW_PARSER(xref, obj); - go(topLevel); - delete parser; - parser = nullptr; +PdfParser::~PdfParser() +{ + while (operatorHistory) { + OpHistoryEntry *tmp = operatorHistory->next; + delete operatorHistory; + operatorHistory = tmp; + } + + while (state && state->hasSaves()) { + restoreState(); + } + + if (!subPage) { + // out->endPage(); + } + + while (res) { + popResources(); + } + + if (state) { + delete state; + state = nullptr; + } + + if (clipHistory) { + delete clipHistory; + clipHistory = nullptr; + } +} + +void PdfParser::parse(Object *obj, GBool topLevel) +{ + Object obj2; + + if (obj->isArray()) { + for (int i = 0; i < obj->arrayGetLength(); ++i) { + _POPPLER_CALL_ARGS(obj2, obj->arrayGet, i); + if (!obj2.isStream()) { + error(errInternal, -1, "Weird page contents"); + _POPPLER_FREE(obj2); + return; + } + _POPPLER_FREE(obj2); + } + } else if (!obj->isStream()) { + error(errInternal, -1, "Weird page contents"); + return; + } + parser = new _POPPLER_NEW_PARSER(xref, obj); + go(topLevel); + delete parser; + parser = nullptr; } void PdfParser::go(GBool /*topLevel*/) { - Object obj; - Object args[maxArgs]; - - // scan a sequence of objects - int numArgs = 0; - _POPPLER_CALL(obj, parser->getObj); - while (!obj.isEOF()) { - - // got a command - execute it - if (obj.isCmd()) { - if (printCommands) { - obj.print(stdout); - for (int i = 0; i < numArgs; ++i) { - printf(" "); - args[i].print(stdout); - } - printf("\n"); - fflush(stdout); - } - - // Run the operation - execOp(&obj, args, numArgs); + Object obj; + Object args[maxArgs]; + + // scan a sequence of objects + int numArgs = 0; + _POPPLER_CALL(obj, parser->getObj); + while (!obj.isEOF()) { + // got a command - execute it + if (obj.isCmd()) { + if (printCommands) { + obj.print(stdout); + for (int i = 0; i < numArgs; ++i) { + printf(" "); + args[i].print(stdout); + } + printf("\n"); + fflush(stdout); + } + + // Run the operation + execOp(&obj, args, numArgs); #if !defined(POPPLER_NEW_OBJECT_API) - _POPPLER_FREE(obj); - for (int i = 0; i < numArgs; ++i) - _POPPLER_FREE(args[i]); + _POPPLER_FREE(obj); + for (int i = 0; i < numArgs; ++i) + _POPPLER_FREE(args[i]); #endif - numArgs = 0; + numArgs = 0; - // got an argument - save it - } else if (numArgs < maxArgs) { - args[numArgs++] = std::move(obj); + // got an argument - save it + } else if (numArgs < maxArgs) { + args[numArgs++] = std::move(obj); - // too many arguments - something is wrong - } else { - error(errSyntaxError, getPos(), "Too many args in content stream"); - if (printCommands) { - printf("throwing away arg: "); - obj.print(stdout); - printf("\n"); - fflush(stdout); - } - _POPPLER_FREE(obj); - } - - // grab the next object - _POPPLER_CALL(obj, parser->getObj); - } - _POPPLER_FREE(obj); + // too many arguments - something is wrong + } else { + error(errSyntaxError, getPos(), "Too many args in content stream"); + if (printCommands) { + printf("throwing away arg: "); + obj.print(stdout); + printf("\n"); + fflush(stdout); + } + _POPPLER_FREE(obj); + } - // args at end with no command - if (numArgs > 0) { - error(errSyntaxError, getPos(), "Leftover args in content stream"); - if (printCommands) { - printf("%d leftovers:", numArgs); - for (int i = 0; i < numArgs; ++i) { - printf(" "); - args[i].print(stdout); - } - printf("\n"); - fflush(stdout); + // grab the next object + _POPPLER_CALL(obj, parser->getObj); } + _POPPLER_FREE(obj); + + // args at end with no command + if (numArgs > 0) { + error(errSyntaxError, getPos(), "Leftover args in content stream"); + if (printCommands) { + printf("%d leftovers:", numArgs); + for (int i = 0; i < numArgs; ++i) { + printf(" "); + args[i].print(stdout); + } + printf("\n"); + fflush(stdout); + } #if !defined(POPPLER_NEW_OBJECT_API) - for (int i = 0; i < numArgs; ++i) - _POPPLER_FREE(args[i]); + for (int i = 0; i < numArgs; ++i) + _POPPLER_FREE(args[i]); #endif - } + } } void PdfParser::pushOperator(const char *name) @@ -504,7 +417,7 @@ void PdfParser::pushOperator(const char *name) OpHistoryEntry *newEntry = new OpHistoryEntry; newEntry->name = name; newEntry->state = nullptr; - newEntry->depth = (operatorHistory != nullptr ? (operatorHistory->depth+1) : 0); + newEntry->depth = (operatorHistory != nullptr ? (operatorHistory->depth + 1) : 0); newEntry->next = operatorHistory; operatorHistory = newEntry; @@ -526,7 +439,8 @@ void PdfParser::pushOperator(const char *name) } } -const char *PdfParser::getPreviousOperator(unsigned int look_back) { +const char *PdfParser::getPreviousOperator(unsigned int look_back) +{ OpHistoryEntry *prev = nullptr; if (operatorHistory != nullptr && look_back > 0) { prev = operatorHistory->next; @@ -541,93 +455,105 @@ const char *PdfParser::getPreviousOperator(unsigned int look_back) { } } -void PdfParser::execOp(Object *cmd, Object args[], int numArgs) { - PdfOperator *op; - const char *name; - Object *argPtr; - int i; - - // find operator - name = cmd->getCmd(); - if (!(op = findOp(name))) { - if (ignoreUndef == 0) - error(errSyntaxError, getPos(), "Unknown operator '{0:s}'", name); - return; - } +void PdfParser::execOp(Object *cmd, Object args[], int numArgs) +{ + PdfOperator *op; + const char *name; + Object *argPtr; + int i; - // type check args - argPtr = args; - if (op->numArgs >= 0) { - if (numArgs < op->numArgs) { - error(errSyntaxError, getPos(), "Too few ({0:d}) args to '{1:d}' operator", numArgs, name); - return; + // find operator + name = cmd->getCmd(); + if (!(op = findOp(name))) { + if (ignoreUndef == 0) + error(errSyntaxError, getPos(), "Unknown operator '{0:s}'", name); + return; } - if (numArgs > op->numArgs) { + + // type check args + argPtr = args; + if (op->numArgs >= 0) { + if (numArgs < op->numArgs) { + error(errSyntaxError, getPos(), "Too few ({0:d}) args to '{1:d}' operator", numArgs, name); + return; + } + if (numArgs > op->numArgs) { #if 0 error(errSyntaxError, getPos(), "Too many ({0:d}) args to '{1:s}' operator", numArgs, name); #endif - argPtr += numArgs - op->numArgs; - numArgs = op->numArgs; - } - } else { - if (numArgs > -op->numArgs) { - error(errSyntaxError, getPos(), "Too many ({0:d}) args to '{1:s}' operator", - numArgs, name); - return; - } - } - for (i = 0; i < numArgs; ++i) { - if (!checkArg(&argPtr[i], op->tchk[i])) { - error(errSyntaxError, getPos(), "Arg #{0:d} to '{1:s}' operator is wrong type ({2:s})", - i, name, argPtr[i].getTypeName()); - return; - } - } - - // add to history - pushOperator((char*)&op->name); - - // do it - (this->*op->func)(argPtr, numArgs); -} - -PdfOperator* PdfParser::findOp(const char *name) { - int a = -1; - int b = numOps; - int cmp = -1; - // invariant: opTab[a] < name < opTab[b] - while (b - a > 1) { - const int m = (a + b) / 2; - cmp = strcmp(opTab[m].name, name); - if (cmp < 0) - a = m; - else if (cmp > 0) - b = m; - else - a = b = m; - } - if (cmp != 0) - return nullptr; - return &opTab[a]; + argPtr += numArgs - op->numArgs; + numArgs = op->numArgs; + } + } else { + if (numArgs > -op->numArgs) { + error(errSyntaxError, getPos(), "Too many ({0:d}) args to '{1:s}' operator", numArgs, name); + return; + } + } + for (i = 0; i < numArgs; ++i) { + if (!checkArg(&argPtr[i], op->tchk[i])) { + error(errSyntaxError, getPos(), "Arg #{0:d} to '{1:s}' operator is wrong type ({2:s})", i, name, + argPtr[i].getTypeName()); + return; + } + } + + // add to history + pushOperator((char *)&op->name); + + // do it + (this->*op->func)(argPtr, numArgs); } -GBool PdfParser::checkArg(Object *arg, TchkType type) { - switch (type) { - case tchkBool: return arg->isBool(); - case tchkInt: return arg->isInt(); - case tchkNum: return arg->isNum(); - case tchkString: return arg->isString(); - case tchkName: return arg->isName(); - case tchkArray: return arg->isArray(); - case tchkProps: return arg->isDict() || arg->isName(); - case tchkSCN: return arg->isNum() || arg->isName(); - case tchkNone: return gFalse; - } - return gFalse; +PdfOperator *PdfParser::findOp(const char *name) +{ + int a = -1; + int b = numOps; + int cmp = -1; + // invariant: opTab[a] < name < opTab[b] + while (b - a > 1) { + const int m = (a + b) / 2; + cmp = strcmp(opTab[m].name, name); + if (cmp < 0) + a = m; + else if (cmp > 0) + b = m; + else + a = b = m; + } + if (cmp != 0) + return nullptr; + return &opTab[a]; } -int PdfParser::getPos() { - return parser ? parser->getPos() : -1; +GBool PdfParser::checkArg(Object *arg, TchkType type) +{ + switch (type) { + case tchkBool: + return arg->isBool(); + case tchkInt: + return arg->isInt(); + case tchkNum: + return arg->isNum(); + case tchkString: + return arg->isString(); + case tchkName: + return arg->isName(); + case tchkArray: + return arg->isArray(); + case tchkProps: + return arg->isDict() || arg->isName(); + case tchkSCN: + return arg->isNum() || arg->isName(); + case tchkNone: + return gFalse; + } + return gFalse; +} + +int PdfParser::getPos() +{ + return parser ? parser->getPos() : -1; } //------------------------------------------------------------------------ @@ -636,363 +562,358 @@ int PdfParser::getPos() { void PdfParser::opSave(Object /*args*/[], int /*numArgs*/) { - saveState(); + saveState(); } void PdfParser::opRestore(Object /*args*/[], int /*numArgs*/) { - restoreState(); + restoreState(); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opConcat(Object args[], int /*numArgs*/) { - state->concatCTM(args[0].getNum(), args[1].getNum(), - args[2].getNum(), args[3].getNum(), - args[4].getNum(), args[5].getNum()); - const char *prevOp = getPreviousOperator(); - double a0 = args[0].getNum(); - double a1 = args[1].getNum(); - double a2 = args[2].getNum(); - double a3 = args[3].getNum(); - double a4 = args[4].getNum(); - double a5 = args[5].getNum(); - if (!strcmp(prevOp, "q")) { - builder->setTransform(a0, a1, a2, a3, a4, a5); - } else if (!strcmp(prevOp, "cm") || !strcmp(prevOp, "startPage")) { - // multiply it with the previous transform - double otherMatrix[6]; - if (!builder->getTransform(otherMatrix)) { // invalid transform - // construct identity matrix - otherMatrix[0] = otherMatrix[3] = 1.0; - otherMatrix[1] = otherMatrix[2] = otherMatrix[4] = otherMatrix[5] = 0.0; - } - double c0 = a0*otherMatrix[0] + a1*otherMatrix[2]; - double c1 = a0*otherMatrix[1] + a1*otherMatrix[3]; - double c2 = a2*otherMatrix[0] + a3*otherMatrix[2]; - double c3 = a2*otherMatrix[1] + a3*otherMatrix[3]; - double c4 = a4*otherMatrix[0] + a5*otherMatrix[2] + otherMatrix[4]; - double c5 = a4*otherMatrix[1] + a5*otherMatrix[3] + otherMatrix[5]; - builder->setTransform(c0, c1, c2, c3, c4, c5); - } else { - builder->pushGroup(); - builder->setTransform(a0, a1, a2, a3, a4, a5); - } - fontChanged = gTrue; + state->concatCTM(args[0].getNum(), args[1].getNum(), args[2].getNum(), args[3].getNum(), args[4].getNum(), + args[5].getNum()); + const char *prevOp = getPreviousOperator(); + double a0 = args[0].getNum(); + double a1 = args[1].getNum(); + double a2 = args[2].getNum(); + double a3 = args[3].getNum(); + double a4 = args[4].getNum(); + double a5 = args[5].getNum(); + if (!strcmp(prevOp, "q")) { + builder->setTransform(a0, a1, a2, a3, a4, a5); + } else if (!strcmp(prevOp, "cm") || !strcmp(prevOp, "startPage")) { + // multiply it with the previous transform + double otherMatrix[6]; + if (!builder->getTransform(otherMatrix)) { // invalid transform + // construct identity matrix + otherMatrix[0] = otherMatrix[3] = 1.0; + otherMatrix[1] = otherMatrix[2] = otherMatrix[4] = otherMatrix[5] = 0.0; + } + double c0 = a0 * otherMatrix[0] + a1 * otherMatrix[2]; + double c1 = a0 * otherMatrix[1] + a1 * otherMatrix[3]; + double c2 = a2 * otherMatrix[0] + a3 * otherMatrix[2]; + double c3 = a2 * otherMatrix[1] + a3 * otherMatrix[3]; + double c4 = a4 * otherMatrix[0] + a5 * otherMatrix[2] + otherMatrix[4]; + double c5 = a4 * otherMatrix[1] + a5 * otherMatrix[3] + otherMatrix[5]; + builder->setTransform(c0, c1, c2, c3, c4, c5); + } else { + builder->pushGroup(); + builder->setTransform(a0, a1, a2, a3, a4, a5); + } + fontChanged = gTrue; } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetDash(Object args[], int /*numArgs*/) { - double *dash = nullptr; + double *dash = nullptr; - Array *a = args[0].getArray(); - int length = a->getLength(); - if (length != 0) { - dash = (double *)gmallocn(length, sizeof(double)); - for (int i = 0; i < length; ++i) { - Object obj; - dash[i] = _POPPLER_CALL_ARGS_DEREF(obj, a->get, i).getNum(); - _POPPLER_FREE(obj); + Array *a = args[0].getArray(); + int length = a->getLength(); + if (length != 0) { + dash = (double *)gmallocn(length, sizeof(double)); + for (int i = 0; i < length; ++i) { + Object obj; + dash[i] = _POPPLER_CALL_ARGS_DEREF(obj, a->get, i).getNum(); + _POPPLER_FREE(obj); + } } - } - state->setLineDash(dash, length, args[1].getNum()); - builder->updateStyle(state); + state->setLineDash(dash, length, args[1].getNum()); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetFlat(Object args[], int /*numArgs*/) { - state->setFlatness((int)args[0].getNum()); + state->setFlatness((int)args[0].getNum()); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetLineJoin(Object args[], int /*numArgs*/) { - state->setLineJoin(args[0].getInt()); - builder->updateStyle(state); + state->setLineJoin(args[0].getInt()); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetLineCap(Object args[], int /*numArgs*/) { - state->setLineCap(args[0].getInt()); - builder->updateStyle(state); + state->setLineCap(args[0].getInt()); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetMiterLimit(Object args[], int /*numArgs*/) { - state->setMiterLimit(args[0].getNum()); - builder->updateStyle(state); + state->setMiterLimit(args[0].getNum()); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetLineWidth(Object args[], int /*numArgs*/) { - state->setLineWidth(args[0].getNum()); - builder->updateStyle(state); + state->setLineWidth(args[0].getNum()); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetExtGState(Object args[], int /*numArgs*/) { - Object obj1, obj2, obj3, obj4, obj5; - Function *funcs[4] = {nullptr, nullptr, nullptr, nullptr}; - GfxColor backdropColor; - GBool haveBackdropColor = gFalse; - GBool alpha = gFalse; + Object obj1, obj2, obj3, obj4, obj5; + Function *funcs[4] = {nullptr, nullptr, nullptr, nullptr}; + GfxColor backdropColor; + GBool haveBackdropColor = gFalse; + GBool alpha = gFalse; - _POPPLER_CALL_ARGS(obj1, res->lookupGState, args[0].getName()); - if (obj1.isNull()) { - return; - } - if (!obj1.isDict()) { - error(errSyntaxError, getPos(), "ExtGState '{0:s}' is wrong type"), args[0].getName(); - _POPPLER_FREE(obj1); - return; - } - if (printCommands) { - printf(" gfx state dict: "); - obj1.print(); - printf("\n"); - } - - // transparency support: blend mode, fill/stroke opacity - if (!_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "BM").isNull()) { - GfxBlendMode mode = gfxBlendNormal; - if (state->parseBlendMode(&obj2, &mode)) { - state->setBlendMode(mode); - } else { - error(errSyntaxError, getPos(), "Invalid blend mode in ExtGState"); - } - } - _POPPLER_FREE(obj2); - if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "ca").isNum()) { - state->setFillOpacity(obj2.getNum()); - } - _POPPLER_FREE(obj2); - if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "CA").isNum()) { - state->setStrokeOpacity(obj2.getNum()); - } - _POPPLER_FREE(obj2); - - // fill/stroke overprint - GBool haveFillOP = gFalse; - if ((haveFillOP = _POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "op").isBool())) { - state->setFillOverprint(obj2.getBool()); - } - _POPPLER_FREE(obj2); - if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "OP").isBool()) { - state->setStrokeOverprint(obj2.getBool()); - if (!haveFillOP) { - state->setFillOverprint(obj2.getBool()); - } - } - _POPPLER_FREE(obj2); - - // stroke adjust - if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "SA").isBool()) { - state->setStrokeAdjust(obj2.getBool()); - } - _POPPLER_FREE(obj2); - - // transfer function - if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "TR2").isNull()) { + _POPPLER_CALL_ARGS(obj1, res->lookupGState, args[0].getName()); + if (obj1.isNull()) { + return; + } + if (!obj1.isDict()) { + error(errSyntaxError, getPos(), "ExtGState '{0:s}' is wrong type"), args[0].getName(); + _POPPLER_FREE(obj1); + return; + } + if (printCommands) { + printf(" gfx state dict: "); + obj1.print(); + printf("\n"); + } + + // transparency support: blend mode, fill/stroke opacity + if (!_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "BM").isNull()) { + GfxBlendMode mode = gfxBlendNormal; + if (state->parseBlendMode(&obj2, &mode)) { + state->setBlendMode(mode); + } else { + error(errSyntaxError, getPos(), "Invalid blend mode in ExtGState"); + } + } _POPPLER_FREE(obj2); - _POPPLER_CALL_ARGS(obj2, obj1.dictLookup, "TR"); - } - if (obj2.isName(const_cast("Default")) || - obj2.isName(const_cast("Identity"))) { - funcs[0] = funcs[1] = funcs[2] = funcs[3] = nullptr; - state->setTransfer(funcs); - } else if (obj2.isArray() && obj2.arrayGetLength() == 4) { - int pos = 4; - for (int i = 0; i < 4; ++i) { - _POPPLER_CALL_ARGS(obj3, obj2.arrayGet, i); - funcs[i] = Function::parse(&obj3); - _POPPLER_FREE(obj3); - if (!funcs[i]) { - pos = i; - break; - } - } - if (pos == 4) { - state->setTransfer(funcs); - } - } else if (obj2.isName() || obj2.isDict() || obj2.isStream()) { - if ((funcs[0] = Function::parse(&obj2))) { - funcs[1] = funcs[2] = funcs[3] = nullptr; - state->setTransfer(funcs); - } - } else if (!obj2.isNull()) { - error(errSyntaxError, getPos(), "Invalid transfer function in ExtGState"); - } - _POPPLER_FREE(obj2); - - // soft mask - if (!_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "SMask").isNull()) { - if (obj2.isName(const_cast("None"))) { - builder->clearSoftMask(state); - } else if (obj2.isDict()) { - if (_POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "S").isName("Alpha")) { - alpha = gTrue; - } else { // "Luminosity" - alpha = gFalse; - } - _POPPLER_FREE(obj3); - funcs[0] = nullptr; - if (!_POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "TR").isNull()) { - funcs[0] = Function::parse(&obj3); - if (funcs[0]->getInputSize() != 1 || - funcs[0]->getOutputSize() != 1) { - error(errSyntaxError, getPos(), "Invalid transfer function in soft mask in ExtGState"); - delete funcs[0]; - funcs[0] = nullptr; - } - } - _POPPLER_FREE(obj3); - if ((haveBackdropColor = _POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "BC").isArray())) { - for (int & i : backdropColor.c) { - i = 0; - } - for (int i = 0; i < obj3.arrayGetLength() && i < gfxColorMaxComps; ++i) { - _POPPLER_CALL_ARGS(obj4, obj3.arrayGet, i); - if (obj4.isNum()) { - backdropColor.c[i] = dblToCol(obj4.getNum()); - } - _POPPLER_FREE(obj4); - } - } - _POPPLER_FREE(obj3); - if (_POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "G").isStream()) { - if (_POPPLER_CALL_ARGS_DEREF(obj4, obj3.streamGetDict()->lookup, "Group").isDict()) { - GfxColorSpace *blendingColorSpace = nullptr; - GBool isolated = gFalse; - GBool knockout = gFalse; - if (!_POPPLER_CALL_ARGS_DEREF(obj5, obj4.dictLookup, "CS").isNull()) { + if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "ca").isNum()) { + state->setFillOpacity(obj2.getNum()); + } + _POPPLER_FREE(obj2); + if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "CA").isNum()) { + state->setStrokeOpacity(obj2.getNum()); + } + _POPPLER_FREE(obj2); + + // fill/stroke overprint + GBool haveFillOP = gFalse; + if ((haveFillOP = _POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "op").isBool())) { + state->setFillOverprint(obj2.getBool()); + } + _POPPLER_FREE(obj2); + if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "OP").isBool()) { + state->setStrokeOverprint(obj2.getBool()); + if (!haveFillOP) { + state->setFillOverprint(obj2.getBool()); + } + } + _POPPLER_FREE(obj2); + + // stroke adjust + if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "SA").isBool()) { + state->setStrokeAdjust(obj2.getBool()); + } + _POPPLER_FREE(obj2); + + // transfer function + if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "TR2").isNull()) { + _POPPLER_FREE(obj2); + _POPPLER_CALL_ARGS(obj2, obj1.dictLookup, "TR"); + } + if (obj2.isName(const_cast("Default")) || obj2.isName(const_cast("Identity"))) { + funcs[0] = funcs[1] = funcs[2] = funcs[3] = nullptr; + state->setTransfer(funcs); + } else if (obj2.isArray() && obj2.arrayGetLength() == 4) { + int pos = 4; + for (int i = 0; i < 4; ++i) { + _POPPLER_CALL_ARGS(obj3, obj2.arrayGet, i); + funcs[i] = Function::parse(&obj3); + _POPPLER_FREE(obj3); + if (!funcs[i]) { + pos = i; + break; + } + } + if (pos == 4) { + state->setTransfer(funcs); + } + } else if (obj2.isName() || obj2.isDict() || obj2.isStream()) { + if ((funcs[0] = Function::parse(&obj2))) { + funcs[1] = funcs[2] = funcs[3] = nullptr; + state->setTransfer(funcs); + } + } else if (!obj2.isNull()) { + error(errSyntaxError, getPos(), "Invalid transfer function in ExtGState"); + } + _POPPLER_FREE(obj2); + + // soft mask + if (!_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "SMask").isNull()) { + if (obj2.isName(const_cast("None"))) { + builder->clearSoftMask(state); + } else if (obj2.isDict()) { + if (_POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "S").isName("Alpha")) { + alpha = gTrue; + } else { // "Luminosity" + alpha = gFalse; + } + _POPPLER_FREE(obj3); + funcs[0] = nullptr; + if (!_POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "TR").isNull()) { + funcs[0] = Function::parse(&obj3); + if (funcs[0]->getInputSize() != 1 || funcs[0]->getOutputSize() != 1) { + error(errSyntaxError, getPos(), "Invalid transfer function in soft mask in ExtGState"); + delete funcs[0]; + funcs[0] = nullptr; + } + } + _POPPLER_FREE(obj3); + if ((haveBackdropColor = _POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "BC").isArray())) { + for (int &i : backdropColor.c) { + i = 0; + } + for (int i = 0; i < obj3.arrayGetLength() && i < gfxColorMaxComps; ++i) { + _POPPLER_CALL_ARGS(obj4, obj3.arrayGet, i); + if (obj4.isNum()) { + backdropColor.c[i] = dblToCol(obj4.getNum()); + } + _POPPLER_FREE(obj4); + } + } + _POPPLER_FREE(obj3); + if (_POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "G").isStream()) { + if (_POPPLER_CALL_ARGS_DEREF(obj4, obj3.streamGetDict()->lookup, "Group").isDict()) { + GfxColorSpace *blendingColorSpace = nullptr; + GBool isolated = gFalse; + GBool knockout = gFalse; + if (!_POPPLER_CALL_ARGS_DEREF(obj5, obj4.dictLookup, "CS").isNull()) { #if defined(POPPLER_EVEN_NEWER_NEW_COLOR_SPACE_API) - blendingColorSpace = GfxColorSpace::parse(nullptr, &obj5, nullptr, nullptr); + blendingColorSpace = GfxColorSpace::parse(nullptr, &obj5, nullptr, nullptr); #elif defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API) - blendingColorSpace = GfxColorSpace::parse(&obj5, NULL, NULL); + blendingColorSpace = GfxColorSpace::parse(&obj5, NULL, NULL); #else - blendingColorSpace = GfxColorSpace::parse(&obj5, NULL); + blendingColorSpace = GfxColorSpace::parse(&obj5, NULL); #endif - } - _POPPLER_FREE(obj5); - if (_POPPLER_CALL_ARGS_DEREF(obj5, obj4.dictLookup, "I").isBool()) { - isolated = obj5.getBool(); - } - _POPPLER_FREE(obj5); - if (_POPPLER_CALL_ARGS_DEREF(obj5, obj4.dictLookup, "K").isBool()) { - knockout = obj5.getBool(); - } - _POPPLER_FREE(obj5); - if (!haveBackdropColor) { - if (blendingColorSpace) { - blendingColorSpace->getDefaultColor(&backdropColor); - } else { - //~ need to get the parent or default color space (?) - for (int & i : backdropColor.c) { - i = 0; - } - } - } - doSoftMask(&obj3, alpha, blendingColorSpace, - isolated, knockout, funcs[0], &backdropColor); - if (funcs[0]) { - delete funcs[0]; - } - } else { - error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState - missing group"); - } - _POPPLER_FREE(obj4); - } else { - error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState - missing group"); - } - _POPPLER_FREE(obj3); - } else if (!obj2.isNull()) { - error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState"); + } + _POPPLER_FREE(obj5); + if (_POPPLER_CALL_ARGS_DEREF(obj5, obj4.dictLookup, "I").isBool()) { + isolated = obj5.getBool(); + } + _POPPLER_FREE(obj5); + if (_POPPLER_CALL_ARGS_DEREF(obj5, obj4.dictLookup, "K").isBool()) { + knockout = obj5.getBool(); + } + _POPPLER_FREE(obj5); + if (!haveBackdropColor) { + if (blendingColorSpace) { + blendingColorSpace->getDefaultColor(&backdropColor); + } else { + //~ need to get the parent or default color space (?) + for (int &i : backdropColor.c) { + i = 0; + } + } + } + doSoftMask(&obj3, alpha, blendingColorSpace, isolated, knockout, funcs[0], &backdropColor); + if (funcs[0]) { + delete funcs[0]; + } + } else { + error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState - missing group"); + } + _POPPLER_FREE(obj4); + } else { + error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState - missing group"); + } + _POPPLER_FREE(obj3); + } else if (!obj2.isNull()) { + error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState"); + } } - } - _POPPLER_FREE(obj2); + _POPPLER_FREE(obj2); - _POPPLER_FREE(obj1); + _POPPLER_FREE(obj1); } -void PdfParser::doSoftMask(Object *str, GBool alpha, - GfxColorSpace *blendingColorSpace, - GBool isolated, GBool knockout, - Function *transferFunc, GfxColor *backdropColor) { - Dict *dict, *resDict; - double m[6], bbox[4]; - Object obj1, obj2; - int i; +void PdfParser::doSoftMask(Object *str, GBool alpha, GfxColorSpace *blendingColorSpace, GBool isolated, GBool knockout, + Function *transferFunc, GfxColor *backdropColor) +{ + Dict *dict, *resDict; + double m[6], bbox[4]; + Object obj1, obj2; + int i; - // check for excessive recursion - if (formDepth > 20) { - return; - } + // check for excessive recursion + if (formDepth > 20) { + return; + } - // get stream dict - dict = str->streamGetDict(); + // get stream dict + dict = str->streamGetDict(); - // check form type - _POPPLER_CALL_ARGS(obj1, dict->lookup, "FormType"); - if (!(obj1.isNull() || (obj1.isInt() && obj1.getInt() == 1))) { - error(errSyntaxError, getPos(), "Unknown form type"); - } - _POPPLER_FREE(obj1); + // check form type + _POPPLER_CALL_ARGS(obj1, dict->lookup, "FormType"); + if (!(obj1.isNull() || (obj1.isInt() && obj1.getInt() == 1))) { + error(errSyntaxError, getPos(), "Unknown form type"); + } + _POPPLER_FREE(obj1); - // get bounding box - _POPPLER_CALL_ARGS(obj1, dict->lookup, "BBox"); - if (!obj1.isArray()) { + // get bounding box + _POPPLER_CALL_ARGS(obj1, dict->lookup, "BBox"); + if (!obj1.isArray()) { + _POPPLER_FREE(obj1); + error(errSyntaxError, getPos(), "Bad form bounding box"); + return; + } + for (i = 0; i < 4; ++i) { + _POPPLER_CALL_ARGS(obj2, obj1.arrayGet, i); + bbox[i] = obj2.getNum(); + _POPPLER_FREE(obj2); + } _POPPLER_FREE(obj1); - error(errSyntaxError, getPos(), "Bad form bounding box"); - return; - } - for (i = 0; i < 4; ++i) { - _POPPLER_CALL_ARGS(obj2, obj1.arrayGet, i); - bbox[i] = obj2.getNum(); - _POPPLER_FREE(obj2); - } - _POPPLER_FREE(obj1); - // get matrix - _POPPLER_CALL_ARGS(obj1, dict->lookup, "Matrix"); - if (obj1.isArray()) { - for (i = 0; i < 6; ++i) { - _POPPLER_CALL_ARGS(obj2, obj1.arrayGet, i); - m[i] = obj2.getNum(); - _POPPLER_FREE(obj2); + // get matrix + _POPPLER_CALL_ARGS(obj1, dict->lookup, "Matrix"); + if (obj1.isArray()) { + for (i = 0; i < 6; ++i) { + _POPPLER_CALL_ARGS(obj2, obj1.arrayGet, i); + m[i] = obj2.getNum(); + _POPPLER_FREE(obj2); + } + } else { + m[0] = 1; + m[1] = 0; + m[2] = 0; + m[3] = 1; + m[4] = 0; + m[5] = 0; } - } else { - m[0] = 1; m[1] = 0; - m[2] = 0; m[3] = 1; - m[4] = 0; m[5] = 0; - } - _POPPLER_FREE(obj1); + _POPPLER_FREE(obj1); - // get resources - _POPPLER_CALL_ARGS(obj1, dict->lookup, "Resources"); - resDict = obj1.isDict() ? obj1.getDict() : (Dict *)nullptr; + // get resources + _POPPLER_CALL_ARGS(obj1, dict->lookup, "Resources"); + resDict = obj1.isDict() ? obj1.getDict() : (Dict *)nullptr; - // draw it - ++formDepth; - doForm1(str, resDict, m, bbox, gTrue, gTrue, - blendingColorSpace, isolated, knockout, - alpha, transferFunc, backdropColor); - --formDepth; + // draw it + ++formDepth; + doForm1(str, resDict, m, bbox, gTrue, gTrue, blendingColorSpace, isolated, knockout, alpha, transferFunc, + backdropColor); + --formDepth; - if (blendingColorSpace) { - delete blendingColorSpace; - } - _POPPLER_FREE(obj1); + if (blendingColorSpace) { + delete blendingColorSpace; + } + _POPPLER_FREE(obj1); } -void PdfParser::opSetRenderingIntent(Object /*args*/[], int /*numArgs*/) -{ -} +void PdfParser::opSetRenderingIntent(Object /*args*/[], int /*numArgs*/) {} //------------------------------------------------------------------------ // color operators @@ -1001,295 +922,295 @@ void PdfParser::opSetRenderingIntent(Object /*args*/[], int /*numArgs*/) // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetFillGray(Object args[], int /*numArgs*/) { - GfxColor color; + GfxColor color; - state->setFillPattern(nullptr); - state->setFillColorSpace(new GfxDeviceGrayColorSpace()); - color.c[0] = dblToCol(args[0].getNum()); - state->setFillColor(&color); - builder->updateStyle(state); + state->setFillPattern(nullptr); + state->setFillColorSpace(new GfxDeviceGrayColorSpace()); + color.c[0] = dblToCol(args[0].getNum()); + state->setFillColor(&color); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetStrokeGray(Object args[], int /*numArgs*/) { - GfxColor color; + GfxColor color; - state->setStrokePattern(nullptr); - state->setStrokeColorSpace(new GfxDeviceGrayColorSpace()); - color.c[0] = dblToCol(args[0].getNum()); - state->setStrokeColor(&color); - builder->updateStyle(state); + state->setStrokePattern(nullptr); + state->setStrokeColorSpace(new GfxDeviceGrayColorSpace()); + color.c[0] = dblToCol(args[0].getNum()); + state->setStrokeColor(&color); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetFillCMYKColor(Object args[], int /*numArgs*/) { - GfxColor color; - int i; + GfxColor color; + int i; - state->setFillPattern(nullptr); - state->setFillColorSpace(new GfxDeviceCMYKColorSpace()); - for (i = 0; i < 4; ++i) { - color.c[i] = dblToCol(args[i].getNum()); - } - state->setFillColor(&color); - builder->updateStyle(state); + state->setFillPattern(nullptr); + state->setFillColorSpace(new GfxDeviceCMYKColorSpace()); + for (i = 0; i < 4; ++i) { + color.c[i] = dblToCol(args[i].getNum()); + } + state->setFillColor(&color); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetStrokeCMYKColor(Object args[], int /*numArgs*/) { - GfxColor color; + GfxColor color; - state->setStrokePattern(nullptr); - state->setStrokeColorSpace(new GfxDeviceCMYKColorSpace()); - for (int i = 0; i < 4; ++i) { - color.c[i] = dblToCol(args[i].getNum()); - } - state->setStrokeColor(&color); - builder->updateStyle(state); + state->setStrokePattern(nullptr); + state->setStrokeColorSpace(new GfxDeviceCMYKColorSpace()); + for (int i = 0; i < 4; ++i) { + color.c[i] = dblToCol(args[i].getNum()); + } + state->setStrokeColor(&color); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetFillRGBColor(Object args[], int /*numArgs*/) { - GfxColor color; + GfxColor color; - state->setFillPattern(nullptr); - state->setFillColorSpace(new GfxDeviceRGBColorSpace()); - for (int i = 0; i < 3; ++i) { - color.c[i] = dblToCol(args[i].getNum()); - } - state->setFillColor(&color); - builder->updateStyle(state); + state->setFillPattern(nullptr); + state->setFillColorSpace(new GfxDeviceRGBColorSpace()); + for (int i = 0; i < 3; ++i) { + color.c[i] = dblToCol(args[i].getNum()); + } + state->setFillColor(&color); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: -void PdfParser::opSetStrokeRGBColor(Object args[], int /*numArgs*/) { - GfxColor color; +void PdfParser::opSetStrokeRGBColor(Object args[], int /*numArgs*/) +{ + GfxColor color; - state->setStrokePattern(nullptr); - state->setStrokeColorSpace(new GfxDeviceRGBColorSpace()); - for (int i = 0; i < 3; ++i) { - color.c[i] = dblToCol(args[i].getNum()); - } - state->setStrokeColor(&color); - builder->updateStyle(state); + state->setStrokePattern(nullptr); + state->setStrokeColorSpace(new GfxDeviceRGBColorSpace()); + for (int i = 0; i < 3; ++i) { + color.c[i] = dblToCol(args[i].getNum()); + } + state->setStrokeColor(&color); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetFillColorSpace(Object args[], int /*numArgs*/) { - Object obj; + Object obj; - state->setFillPattern(nullptr); - _POPPLER_CALL_ARGS(obj, res->lookupColorSpace, args[0].getName()); + state->setFillPattern(nullptr); + _POPPLER_CALL_ARGS(obj, res->lookupColorSpace, args[0].getName()); - GfxColorSpace *colorSpace = nullptr; + GfxColorSpace *colorSpace = nullptr; #if defined(POPPLER_EVEN_NEWER_NEW_COLOR_SPACE_API) - if (obj.isNull()) { - colorSpace = GfxColorSpace::parse(nullptr, &args[0], nullptr, nullptr); - } else { - colorSpace = GfxColorSpace::parse(nullptr, &obj, nullptr, nullptr); - } + if (obj.isNull()) { + colorSpace = GfxColorSpace::parse(nullptr, &args[0], nullptr, nullptr); + } else { + colorSpace = GfxColorSpace::parse(nullptr, &obj, nullptr, nullptr); + } #elif defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API) - if (obj.isNull()) { - colorSpace = GfxColorSpace::parse(&args[0], NULL, NULL); - } else { - colorSpace = GfxColorSpace::parse(&obj, NULL, NULL); - } + if (obj.isNull()) { + colorSpace = GfxColorSpace::parse(&args[0], NULL, NULL); + } else { + colorSpace = GfxColorSpace::parse(&obj, NULL, NULL); + } #else - if (obj.isNull()) { - colorSpace = GfxColorSpace::parse(&args[0], NULL); - } else { - colorSpace = GfxColorSpace::parse(&obj, NULL); - } + if (obj.isNull()) { + colorSpace = GfxColorSpace::parse(&args[0], NULL); + } else { + colorSpace = GfxColorSpace::parse(&obj, NULL); + } #endif - _POPPLER_FREE(obj); - if (colorSpace) { - GfxColor color; - state->setFillColorSpace(colorSpace); - colorSpace->getDefaultColor(&color); - state->setFillColor(&color); - builder->updateStyle(state); - } else { - error(errSyntaxError, getPos(), "Bad color space (fill)"); - } + _POPPLER_FREE(obj); + if (colorSpace) { + GfxColor color; + state->setFillColorSpace(colorSpace); + colorSpace->getDefaultColor(&color); + state->setFillColor(&color); + builder->updateStyle(state); + } else { + error(errSyntaxError, getPos(), "Bad color space (fill)"); + } } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetStrokeColorSpace(Object args[], int /*numArgs*/) { - Object obj; - GfxColorSpace *colorSpace = nullptr; + Object obj; + GfxColorSpace *colorSpace = nullptr; - state->setStrokePattern(nullptr); - _POPPLER_CALL_ARGS(obj, res->lookupColorSpace, args[0].getName()); + state->setStrokePattern(nullptr); + _POPPLER_CALL_ARGS(obj, res->lookupColorSpace, args[0].getName()); #if defined(POPPLER_EVEN_NEWER_NEW_COLOR_SPACE_API) - if (obj.isNull()) { - colorSpace = GfxColorSpace::parse(nullptr, &args[0], nullptr, nullptr); - } else { - colorSpace = GfxColorSpace::parse(nullptr, &obj, nullptr, nullptr); - } + if (obj.isNull()) { + colorSpace = GfxColorSpace::parse(nullptr, &args[0], nullptr, nullptr); + } else { + colorSpace = GfxColorSpace::parse(nullptr, &obj, nullptr, nullptr); + } #elif defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API) - if (obj.isNull()) { - colorSpace = GfxColorSpace::parse(&args[0], NULL, NULL); - } else { - colorSpace = GfxColorSpace::parse(&obj, NULL, NULL); - } + if (obj.isNull()) { + colorSpace = GfxColorSpace::parse(&args[0], NULL, NULL); + } else { + colorSpace = GfxColorSpace::parse(&obj, NULL, NULL); + } #else - if (obj.isNull()) { - colorSpace = GfxColorSpace::parse(&args[0], NULL); - } else { - colorSpace = GfxColorSpace::parse(&obj, NULL); - } + if (obj.isNull()) { + colorSpace = GfxColorSpace::parse(&args[0], NULL); + } else { + colorSpace = GfxColorSpace::parse(&obj, NULL); + } #endif - _POPPLER_FREE(obj); - if (colorSpace) { - GfxColor color; - state->setStrokeColorSpace(colorSpace); - colorSpace->getDefaultColor(&color); - state->setStrokeColor(&color); - builder->updateStyle(state); - } else { - error(errSyntaxError, getPos(), "Bad color space (stroke)"); - } + _POPPLER_FREE(obj); + if (colorSpace) { + GfxColor color; + state->setStrokeColorSpace(colorSpace); + colorSpace->getDefaultColor(&color); + state->setStrokeColor(&color); + builder->updateStyle(state); + } else { + error(errSyntaxError, getPos(), "Bad color space (stroke)"); + } } -void PdfParser::opSetFillColor(Object args[], int numArgs) { - GfxColor color; - int i; +void PdfParser::opSetFillColor(Object args[], int numArgs) +{ + GfxColor color; + int i; - if (numArgs != state->getFillColorSpace()->getNComps()) { - error(errSyntaxError, getPos(), "Incorrect number of arguments in 'sc' command"); - return; - } - state->setFillPattern(nullptr); - for (i = 0; i < numArgs; ++i) { - color.c[i] = dblToCol(args[i].getNum()); - } - state->setFillColor(&color); - builder->updateStyle(state); + if (numArgs != state->getFillColorSpace()->getNComps()) { + error(errSyntaxError, getPos(), "Incorrect number of arguments in 'sc' command"); + return; + } + state->setFillPattern(nullptr); + for (i = 0; i < numArgs; ++i) { + color.c[i] = dblToCol(args[i].getNum()); + } + state->setFillColor(&color); + builder->updateStyle(state); } -void PdfParser::opSetStrokeColor(Object args[], int numArgs) { - GfxColor color; - int i; +void PdfParser::opSetStrokeColor(Object args[], int numArgs) +{ + GfxColor color; + int i; - if (numArgs != state->getStrokeColorSpace()->getNComps()) { - error(errSyntaxError, getPos(), "Incorrect number of arguments in 'SC' command"); - return; - } - state->setStrokePattern(nullptr); - for (i = 0; i < numArgs; ++i) { - color.c[i] = dblToCol(args[i].getNum()); - } - state->setStrokeColor(&color); - builder->updateStyle(state); -} - -void PdfParser::opSetFillColorN(Object args[], int numArgs) { - GfxColor color; - int i; - - if (state->getFillColorSpace()->getMode() == csPattern) { - if (numArgs > 1) { - if (!((GfxPatternColorSpace *)state->getFillColorSpace())->getUnder() || - numArgs - 1 != ((GfxPatternColorSpace *)state->getFillColorSpace()) - ->getUnder()->getNComps()) { - error(errSyntaxError, getPos(), "Incorrect number of arguments in 'scn' command"); - return; - } - for (i = 0; i < numArgs - 1 && i < gfxColorMaxComps; ++i) { - if (args[i].isNum()) { - color.c[i] = dblToCol(args[i].getNum()); - } - } - state->setFillColor(&color); - builder->updateStyle(state); + if (numArgs != state->getStrokeColorSpace()->getNComps()) { + error(errSyntaxError, getPos(), "Incorrect number of arguments in 'SC' command"); + return; } - GfxPattern *pattern; -#if defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API) - if (args[numArgs-1].isName() && - (pattern = res->lookupPattern(args[numArgs-1].getName(), nullptr, nullptr))) { - state->setFillPattern(pattern); - builder->updateStyle(state); + state->setStrokePattern(nullptr); + for (i = 0; i < numArgs; ++i) { + color.c[i] = dblToCol(args[i].getNum()); } + state->setStrokeColor(&color); + builder->updateStyle(state); +} + +void PdfParser::opSetFillColorN(Object args[], int numArgs) +{ + GfxColor color; + int i; + + if (state->getFillColorSpace()->getMode() == csPattern) { + if (numArgs > 1) { + if (!((GfxPatternColorSpace *)state->getFillColorSpace())->getUnder() || + numArgs - 1 != ((GfxPatternColorSpace *)state->getFillColorSpace())->getUnder()->getNComps()) { + error(errSyntaxError, getPos(), "Incorrect number of arguments in 'scn' command"); + return; + } + for (i = 0; i < numArgs - 1 && i < gfxColorMaxComps; ++i) { + if (args[i].isNum()) { + color.c[i] = dblToCol(args[i].getNum()); + } + } + state->setFillColor(&color); + builder->updateStyle(state); + } + GfxPattern *pattern; +#if defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API) + if (args[numArgs - 1].isName() && + (pattern = res->lookupPattern(args[numArgs - 1].getName(), nullptr, nullptr))) { + state->setFillPattern(pattern); + builder->updateStyle(state); + } #else - if (args[numArgs-1].isName() && - (pattern = res->lookupPattern(args[numArgs-1].getName(), NULL))) { - state->setFillPattern(pattern); - builder->updateStyle(state); - } + if (args[numArgs - 1].isName() && (pattern = res->lookupPattern(args[numArgs - 1].getName(), NULL))) { + state->setFillPattern(pattern); + builder->updateStyle(state); + } #endif - } else { - if (numArgs != state->getFillColorSpace()->getNComps()) { - error(errSyntaxError, getPos(), "Incorrect number of arguments in 'scn' command"); - return; - } - state->setFillPattern(nullptr); - for (i = 0; i < numArgs && i < gfxColorMaxComps; ++i) { - if (args[i].isNum()) { - color.c[i] = dblToCol(args[i].getNum()); - } - } - state->setFillColor(&color); - builder->updateStyle(state); - } -} - -void PdfParser::opSetStrokeColorN(Object args[], int numArgs) { - GfxColor color; - int i; - - if (state->getStrokeColorSpace()->getMode() == csPattern) { - if (numArgs > 1) { - if (!((GfxPatternColorSpace *)state->getStrokeColorSpace()) - ->getUnder() || - numArgs - 1 != ((GfxPatternColorSpace *)state->getStrokeColorSpace()) - ->getUnder()->getNComps()) { - error(errSyntaxError, getPos(), "Incorrect number of arguments in 'SCN' command"); - return; - } - for (i = 0; i < numArgs - 1 && i < gfxColorMaxComps; ++i) { - if (args[i].isNum()) { - color.c[i] = dblToCol(args[i].getNum()); - } - } - state->setStrokeColor(&color); - builder->updateStyle(state); + } else { + if (numArgs != state->getFillColorSpace()->getNComps()) { + error(errSyntaxError, getPos(), "Incorrect number of arguments in 'scn' command"); + return; + } + state->setFillPattern(nullptr); + for (i = 0; i < numArgs && i < gfxColorMaxComps; ++i) { + if (args[i].isNum()) { + color.c[i] = dblToCol(args[i].getNum()); + } + } + state->setFillColor(&color); + builder->updateStyle(state); } - GfxPattern *pattern; +} + +void PdfParser::opSetStrokeColorN(Object args[], int numArgs) +{ + GfxColor color; + int i; + + if (state->getStrokeColorSpace()->getMode() == csPattern) { + if (numArgs > 1) { + if (!((GfxPatternColorSpace *)state->getStrokeColorSpace())->getUnder() || + numArgs - 1 != ((GfxPatternColorSpace *)state->getStrokeColorSpace())->getUnder()->getNComps()) { + error(errSyntaxError, getPos(), "Incorrect number of arguments in 'SCN' command"); + return; + } + for (i = 0; i < numArgs - 1 && i < gfxColorMaxComps; ++i) { + if (args[i].isNum()) { + color.c[i] = dblToCol(args[i].getNum()); + } + } + state->setStrokeColor(&color); + builder->updateStyle(state); + } + GfxPattern *pattern; #if defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API) - if (args[numArgs-1].isName() && - (pattern = res->lookupPattern(args[numArgs-1].getName(), nullptr, nullptr))) { - state->setStrokePattern(pattern); - builder->updateStyle(state); - } + if (args[numArgs - 1].isName() && + (pattern = res->lookupPattern(args[numArgs - 1].getName(), nullptr, nullptr))) { + state->setStrokePattern(pattern); + builder->updateStyle(state); + } #else - if (args[numArgs-1].isName() && - (pattern = res->lookupPattern(args[numArgs-1].getName(), NULL))) { - state->setStrokePattern(pattern); - builder->updateStyle(state); - } + if (args[numArgs - 1].isName() && (pattern = res->lookupPattern(args[numArgs - 1].getName(), NULL))) { + state->setStrokePattern(pattern); + builder->updateStyle(state); + } #endif - } else { - if (numArgs != state->getStrokeColorSpace()->getNComps()) { - error(errSyntaxError, getPos(), "Incorrect number of arguments in 'SCN' command"); - return; - } - state->setStrokePattern(nullptr); - for (i = 0; i < numArgs && i < gfxColorMaxComps; ++i) { - if (args[i].isNum()) { - color.c[i] = dblToCol(args[i].getNum()); - } + } else { + if (numArgs != state->getStrokeColorSpace()->getNComps()) { + error(errSyntaxError, getPos(), "Incorrect number of arguments in 'SCN' command"); + return; + } + state->setStrokePattern(nullptr); + for (i = 0; i < numArgs && i < gfxColorMaxComps; ++i) { + if (args[i].isNum()) { + color.c[i] = dblToCol(args[i].getNum()); + } + } + state->setStrokeColor(&color); + builder->updateStyle(state); } - state->setStrokeColor(&color); - builder->updateStyle(state); - } } //------------------------------------------------------------------------ @@ -1299,88 +1220,88 @@ void PdfParser::opSetStrokeColorN(Object args[], int numArgs) { // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opMoveTo(Object args[], int /*numArgs*/) { - state->moveTo(args[0].getNum(), args[1].getNum()); + state->moveTo(args[0].getNum(), args[1].getNum()); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opLineTo(Object args[], int /*numArgs*/) { - if (!state->isCurPt()) { - error(errSyntaxError, getPos(), "No current point in lineto"); - return; - } - state->lineTo(args[0].getNum(), args[1].getNum()); + if (!state->isCurPt()) { + error(errSyntaxError, getPos(), "No current point in lineto"); + return; + } + state->lineTo(args[0].getNum(), args[1].getNum()); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opCurveTo(Object args[], int /*numArgs*/) { - if (!state->isCurPt()) { - error(errSyntaxError, getPos(), "No current point in curveto"); - return; - } - double x1 = args[0].getNum(); - double y1 = args[1].getNum(); - double x2 = args[2].getNum(); - double y2 = args[3].getNum(); - double x3 = args[4].getNum(); - double y3 = args[5].getNum(); - state->curveTo(x1, y1, x2, y2, x3, y3); + if (!state->isCurPt()) { + error(errSyntaxError, getPos(), "No current point in curveto"); + return; + } + double x1 = args[0].getNum(); + double y1 = args[1].getNum(); + double x2 = args[2].getNum(); + double y2 = args[3].getNum(); + double x3 = args[4].getNum(); + double y3 = args[5].getNum(); + state->curveTo(x1, y1, x2, y2, x3, y3); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opCurveTo1(Object args[], int /*numArgs*/) { - if (!state->isCurPt()) { - error(errSyntaxError, getPos(), "No current point in curveto1"); - return; - } - double x1 = state->getCurX(); - double y1 = state->getCurY(); - double x2 = args[0].getNum(); - double y2 = args[1].getNum(); - double x3 = args[2].getNum(); - double y3 = args[3].getNum(); - state->curveTo(x1, y1, x2, y2, x3, y3); + if (!state->isCurPt()) { + error(errSyntaxError, getPos(), "No current point in curveto1"); + return; + } + double x1 = state->getCurX(); + double y1 = state->getCurY(); + double x2 = args[0].getNum(); + double y2 = args[1].getNum(); + double x3 = args[2].getNum(); + double y3 = args[3].getNum(); + state->curveTo(x1, y1, x2, y2, x3, y3); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opCurveTo2(Object args[], int /*numArgs*/) { - if (!state->isCurPt()) { - error(errSyntaxError, getPos(), "No current point in curveto2"); - return; - } - double x1 = args[0].getNum(); - double y1 = args[1].getNum(); - double x2 = args[2].getNum(); - double y2 = args[3].getNum(); - double x3 = x2; - double y3 = y2; - state->curveTo(x1, y1, x2, y2, x3, y3); + if (!state->isCurPt()) { + error(errSyntaxError, getPos(), "No current point in curveto2"); + return; + } + double x1 = args[0].getNum(); + double y1 = args[1].getNum(); + double x2 = args[2].getNum(); + double y2 = args[3].getNum(); + double x3 = x2; + double y3 = y2; + state->curveTo(x1, y1, x2, y2, x3, y3); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opRectangle(Object args[], int /*numArgs*/) { - double x = args[0].getNum(); - double y = args[1].getNum(); - double w = args[2].getNum(); - double h = args[3].getNum(); - state->moveTo(x, y); - state->lineTo(x + w, y); - state->lineTo(x + w, y + h); - state->lineTo(x, y + h); - state->closePath(); + double x = args[0].getNum(); + double y = args[1].getNum(); + double w = args[2].getNum(); + double h = args[3].getNum(); + state->moveTo(x, y); + state->lineTo(x + w, y); + state->lineTo(x + w, y + h); + state->lineTo(x, y + h); + state->closePath(); } void PdfParser::opClosePath(Object /*args*/[], int /*numArgs*/) { - if (!state->isCurPt()) { - error(errSyntaxError, getPos(), "No current point in closepath"); - return; - } - state->closePath(); + if (!state->isCurPt()) { + error(errSyntaxError, getPos(), "No current point in closepath"); + return; + } + state->closePath(); } //------------------------------------------------------------------------ @@ -1389,130 +1310,132 @@ void PdfParser::opClosePath(Object /*args*/[], int /*numArgs*/) void PdfParser::opEndPath(Object /*args*/[], int /*numArgs*/) { - doEndPath(); + doEndPath(); } void PdfParser::opStroke(Object /*args*/[], int /*numArgs*/) { - if (!state->isCurPt()) { - //error(getPos(), const_cast("No path in stroke")); - return; - } - if (state->isPath()) { - if (state->getStrokeColorSpace()->getMode() == csPattern && - !builder->isPatternTypeSupported(state->getStrokePattern())) { - doPatternStrokeFallback(); - } else { - builder->addPath(state, false, true); + if (!state->isCurPt()) { + // error(getPos(), const_cast("No path in stroke")); + return; + } + if (state->isPath()) { + if (state->getStrokeColorSpace()->getMode() == csPattern && + !builder->isPatternTypeSupported(state->getStrokePattern())) { + doPatternStrokeFallback(); + } else { + builder->addPath(state, false, true); + } } - } - doEndPath(); + doEndPath(); } -void PdfParser::opCloseStroke(Object * /*args[]*/, int /*numArgs*/) { - if (!state->isCurPt()) { - //error(getPos(), const_cast("No path in closepath/stroke")); - return; - } - state->closePath(); - if (state->isPath()) { - if (state->getStrokeColorSpace()->getMode() == csPattern && - !builder->isPatternTypeSupported(state->getStrokePattern())) { - doPatternStrokeFallback(); - } else { - builder->addPath(state, false, true); +void PdfParser::opCloseStroke(Object * /*args[]*/, int /*numArgs*/) +{ + if (!state->isCurPt()) { + // error(getPos(), const_cast("No path in closepath/stroke")); + return; } - } - doEndPath(); + state->closePath(); + if (state->isPath()) { + if (state->getStrokeColorSpace()->getMode() == csPattern && + !builder->isPatternTypeSupported(state->getStrokePattern())) { + doPatternStrokeFallback(); + } else { + builder->addPath(state, false, true); + } + } + doEndPath(); } void PdfParser::opFill(Object /*args*/[], int /*numArgs*/) { - if (!state->isCurPt()) { - //error(getPos(), const_cast("No path in fill")); - return; - } - if (state->isPath()) { - if (state->getFillColorSpace()->getMode() == csPattern && - !builder->isPatternTypeSupported(state->getFillPattern())) { - doPatternFillFallback(gFalse); - } else { - builder->addPath(state, true, false); + if (!state->isCurPt()) { + // error(getPos(), const_cast("No path in fill")); + return; + } + if (state->isPath()) { + if (state->getFillColorSpace()->getMode() == csPattern && + !builder->isPatternTypeSupported(state->getFillPattern())) { + doPatternFillFallback(gFalse); + } else { + builder->addPath(state, true, false); + } } - } - doEndPath(); + doEndPath(); } void PdfParser::opEOFill(Object /*args*/[], int /*numArgs*/) { - if (!state->isCurPt()) { - //error(getPos(), const_cast("No path in eofill")); - return; - } - if (state->isPath()) { - if (state->getFillColorSpace()->getMode() == csPattern && - !builder->isPatternTypeSupported(state->getFillPattern())) { - doPatternFillFallback(gTrue); - } else { - builder->addPath(state, true, false, true); + if (!state->isCurPt()) { + // error(getPos(), const_cast("No path in eofill")); + return; + } + if (state->isPath()) { + if (state->getFillColorSpace()->getMode() == csPattern && + !builder->isPatternTypeSupported(state->getFillPattern())) { + doPatternFillFallback(gTrue); + } else { + builder->addPath(state, true, false, true); + } } - } - doEndPath(); + doEndPath(); } void PdfParser::opFillStroke(Object /*args*/[], int /*numArgs*/) { - if (!state->isCurPt()) { - //error(getPos(), const_cast("No path in fill/stroke")); - return; - } - if (state->isPath()) { - doFillAndStroke(gFalse); - } else { - builder->addPath(state, true, true); - } - doEndPath(); + if (!state->isCurPt()) { + // error(getPos(), const_cast("No path in fill/stroke")); + return; + } + if (state->isPath()) { + doFillAndStroke(gFalse); + } else { + builder->addPath(state, true, true); + } + doEndPath(); } void PdfParser::opCloseFillStroke(Object /*args*/[], int /*numArgs*/) { - if (!state->isCurPt()) { - //error(getPos(), const_cast("No path in closepath/fill/stroke")); - return; - } - if (state->isPath()) { - state->closePath(); - doFillAndStroke(gFalse); - } - doEndPath(); + if (!state->isCurPt()) { + // error(getPos(), const_cast("No path in closepath/fill/stroke")); + return; + } + if (state->isPath()) { + state->closePath(); + doFillAndStroke(gFalse); + } + doEndPath(); } void PdfParser::opEOFillStroke(Object /*args*/[], int /*numArgs*/) { - if (!state->isCurPt()) { - //error(getPos(), const_cast("No path in eofill/stroke")); - return; - } - if (state->isPath()) { - doFillAndStroke(gTrue); - } - doEndPath(); + if (!state->isCurPt()) { + // error(getPos(), const_cast("No path in eofill/stroke")); + return; + } + if (state->isPath()) { + doFillAndStroke(gTrue); + } + doEndPath(); } void PdfParser::opCloseEOFillStroke(Object /*args*/[], int /*numArgs*/) { - if (!state->isCurPt()) { - //error(getPos(), const_cast("No path in closepath/eofill/stroke")); - return; - } - if (state->isPath()) { - state->closePath(); - doFillAndStroke(gTrue); - } - doEndPath(); + if (!state->isCurPt()) { + // error(getPos(), const_cast("No path in closepath/eofill/stroke")); + return; + } + if (state->isPath()) { + state->closePath(); + doFillAndStroke(gTrue); + } + doEndPath(); } -void PdfParser::doFillAndStroke(GBool eoFill) { +void PdfParser::doFillAndStroke(GBool eoFill) +{ GBool fillOk = gTrue, strokeOk = gTrue; if (state->getFillColorSpace()->getMode() == csPattern && !builder->isPatternTypeSupported(state->getFillPattern())) { @@ -1530,619 +1453,591 @@ void PdfParser::doFillAndStroke(GBool eoFill) { } } -void PdfParser::doPatternFillFallback(GBool eoFill) { - GfxPattern *pattern; +void PdfParser::doPatternFillFallback(GBool eoFill) +{ + GfxPattern *pattern; - if (!(pattern = state->getFillPattern())) { - return; - } - switch (pattern->getType()) { - case 1: - break; - case 2: - doShadingPatternFillFallback(static_cast(pattern), gFalse, eoFill); - break; - default: - error(errUnimplemented, getPos(), "Unimplemented pattern type (%d) in fill", - pattern->getType()); - break; - } -} - -void PdfParser::doPatternStrokeFallback() { - GfxPattern *pattern; - - if (!(pattern = state->getStrokePattern())) { - return; - } - switch (pattern->getType()) { - case 1: - break; - case 2: - doShadingPatternFillFallback(static_cast(pattern), gTrue, gFalse); - break; - default: - error(errUnimplemented, getPos(), "Unimplemented pattern type ({0:d}) in stroke", - pattern->getType()); - break; - } -} - -void PdfParser::doShadingPatternFillFallback(GfxShadingPattern *sPat, - GBool stroke, GBool eoFill) { - GfxShading *shading; - GfxPath *savedPath; - const double *ctm, *btm, *ptm; - double m[6], ictm[6], m1[6]; - double xMin, yMin, xMax, yMax; - double det; - - shading = sPat->getShading(); - - // save current graphics state - savedPath = state->getPath()->copy(); - saveState(); - - // clip to bbox - if (false ){//shading->getHasBBox()) { - shading->getBBox(&xMin, &yMin, &xMax, &yMax); - state->moveTo(xMin, yMin); - state->lineTo(xMax, yMin); - state->lineTo(xMax, yMax); - state->lineTo(xMin, yMax); - state->closePath(); - state->clip(); - //builder->clip(state); - state->setPath(savedPath->copy()); - } - - // clip to current path - if (stroke) { - state->clipToStrokePath(); - //out->clipToStrokePath(state); - } else { - state->clip(); - if (eoFill) { - builder->setClipPath(state, true); + if (!(pattern = state->getFillPattern())) { + return; + } + switch (pattern->getType()) { + case 1: + break; + case 2: + doShadingPatternFillFallback(static_cast(pattern), gFalse, eoFill); + break; + default: + error(errUnimplemented, getPos(), "Unimplemented pattern type (%d) in fill", pattern->getType()); + break; + } +} + +void PdfParser::doPatternStrokeFallback() +{ + GfxPattern *pattern; + + if (!(pattern = state->getStrokePattern())) { + return; + } + switch (pattern->getType()) { + case 1: + break; + case 2: + doShadingPatternFillFallback(static_cast(pattern), gTrue, gFalse); + break; + default: + error(errUnimplemented, getPos(), "Unimplemented pattern type ({0:d}) in stroke", pattern->getType()); + break; + } +} + +void PdfParser::doShadingPatternFillFallback(GfxShadingPattern *sPat, GBool stroke, GBool eoFill) +{ + GfxShading *shading; + GfxPath *savedPath; + const double *ctm, *btm, *ptm; + double m[6], ictm[6], m1[6]; + double xMin, yMin, xMax, yMax; + double det; + + shading = sPat->getShading(); + + // save current graphics state + savedPath = state->getPath()->copy(); + saveState(); + + // clip to bbox + if (false) { // shading->getHasBBox()) { + shading->getBBox(&xMin, &yMin, &xMax, &yMax); + state->moveTo(xMin, yMin); + state->lineTo(xMax, yMin); + state->lineTo(xMax, yMax); + state->lineTo(xMin, yMax); + state->closePath(); + state->clip(); + // builder->clip(state); + state->setPath(savedPath->copy()); + } + + // clip to current path + if (stroke) { + state->clipToStrokePath(); + // out->clipToStrokePath(state); } else { - builder->setClipPath(state); - } - } - - // set the color space - state->setFillColorSpace(shading->getColorSpace()->copy()); - - // background color fill - if (shading->getHasBackground()) { - state->setFillColor(shading->getBackground()); - builder->addPath(state, true, false); - } - state->clearPath(); - - // construct a (pattern space) -> (current space) transform matrix - ctm = state->getCTM(); - btm = baseMatrix; - ptm = sPat->getMatrix(); - // iCTM = invert CTM - det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]); - ictm[0] = ctm[3] * det; - ictm[1] = -ctm[1] * det; - ictm[2] = -ctm[2] * det; - ictm[3] = ctm[0] * det; - ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det; - ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det; - // m1 = PTM * BTM = PTM * base transform matrix - m1[0] = ptm[0] * btm[0] + ptm[1] * btm[2]; - m1[1] = ptm[0] * btm[1] + ptm[1] * btm[3]; - m1[2] = ptm[2] * btm[0] + ptm[3] * btm[2]; - m1[3] = ptm[2] * btm[1] + ptm[3] * btm[3]; - m1[4] = ptm[4] * btm[0] + ptm[5] * btm[2] + btm[4]; - m1[5] = ptm[4] * btm[1] + ptm[5] * btm[3] + btm[5]; - // m = m1 * iCTM = (PTM * BTM) * (iCTM) - m[0] = m1[0] * ictm[0] + m1[1] * ictm[2]; - m[1] = m1[0] * ictm[1] + m1[1] * ictm[3]; - m[2] = m1[2] * ictm[0] + m1[3] * ictm[2]; - m[3] = m1[2] * ictm[1] + m1[3] * ictm[3]; - m[4] = m1[4] * ictm[0] + m1[5] * ictm[2] + ictm[4]; - m[5] = m1[4] * ictm[1] + m1[5] * ictm[3] + ictm[5]; - - // set the new matrix - state->concatCTM(m[0], m[1], m[2], m[3], m[4], m[5]); - builder->setTransform(m[0], m[1], m[2], m[3], m[4], m[5]); - - // do shading type-specific operations - switch (shading->getType()) { - case 1: - doFunctionShFill(static_cast(shading)); - break; - case 2: - case 3: - // no need to implement these - break; - case 4: - case 5: - doGouraudTriangleShFill(static_cast(shading)); - break; - case 6: - case 7: - doPatchMeshShFill(static_cast(shading)); - break; - } - - // restore graphics state - restoreState(); - state->setPath(savedPath); + state->clip(); + if (eoFill) { + builder->setClipPath(state, true); + } else { + builder->setClipPath(state); + } + } + + // set the color space + state->setFillColorSpace(shading->getColorSpace()->copy()); + + // background color fill + if (shading->getHasBackground()) { + state->setFillColor(shading->getBackground()); + builder->addPath(state, true, false); + } + state->clearPath(); + + // construct a (pattern space) -> (current space) transform matrix + ctm = state->getCTM(); + btm = baseMatrix; + ptm = sPat->getMatrix(); + // iCTM = invert CTM + det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]); + ictm[0] = ctm[3] * det; + ictm[1] = -ctm[1] * det; + ictm[2] = -ctm[2] * det; + ictm[3] = ctm[0] * det; + ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det; + ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det; + // m1 = PTM * BTM = PTM * base transform matrix + m1[0] = ptm[0] * btm[0] + ptm[1] * btm[2]; + m1[1] = ptm[0] * btm[1] + ptm[1] * btm[3]; + m1[2] = ptm[2] * btm[0] + ptm[3] * btm[2]; + m1[3] = ptm[2] * btm[1] + ptm[3] * btm[3]; + m1[4] = ptm[4] * btm[0] + ptm[5] * btm[2] + btm[4]; + m1[5] = ptm[4] * btm[1] + ptm[5] * btm[3] + btm[5]; + // m = m1 * iCTM = (PTM * BTM) * (iCTM) + m[0] = m1[0] * ictm[0] + m1[1] * ictm[2]; + m[1] = m1[0] * ictm[1] + m1[1] * ictm[3]; + m[2] = m1[2] * ictm[0] + m1[3] * ictm[2]; + m[3] = m1[2] * ictm[1] + m1[3] * ictm[3]; + m[4] = m1[4] * ictm[0] + m1[5] * ictm[2] + ictm[4]; + m[5] = m1[4] * ictm[1] + m1[5] * ictm[3] + ictm[5]; + + // set the new matrix + state->concatCTM(m[0], m[1], m[2], m[3], m[4], m[5]); + builder->setTransform(m[0], m[1], m[2], m[3], m[4], m[5]); + + // do shading type-specific operations + switch (shading->getType()) { + case 1: + doFunctionShFill(static_cast(shading)); + break; + case 2: + case 3: + // no need to implement these + break; + case 4: + case 5: + doGouraudTriangleShFill(static_cast(shading)); + break; + case 6: + case 7: + doPatchMeshShFill(static_cast(shading)); + break; + } + + // restore graphics state + restoreState(); + state->setPath(savedPath); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opShFill(Object args[], int /*numArgs*/) { - GfxShading *shading = nullptr; - GfxPath *savedPath = nullptr; - double xMin, yMin, xMax, yMax; - double xTemp, yTemp; - double gradientTransform[6]; - double *matrix = nullptr; - GBool savedState = gFalse; + GfxShading *shading = nullptr; + GfxPath *savedPath = nullptr; + double xMin, yMin, xMax, yMax; + double xTemp, yTemp; + double gradientTransform[6]; + double *matrix = nullptr; + GBool savedState = gFalse; #if defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API) - if (!(shading = res->lookupShading(args[0].getName(), nullptr, nullptr))) { - return; - } + if (!(shading = res->lookupShading(args[0].getName(), nullptr, nullptr))) { + return; + } #else - if (!(shading = res->lookupShading(args[0].getName(), NULL))) { - return; - } + if (!(shading = res->lookupShading(args[0].getName(), NULL))) { + return; + } #endif - // save current graphics state - if (shading->getType() != 2 && shading->getType() != 3) { - savedPath = state->getPath()->copy(); - saveState(); - savedState = gTrue; - } else { // get gradient transform if possible - // check proper operator sequence - // first there should be one W(*) and then one 'cm' somewhere before 'sh' - GBool seenClip, seenConcat; - seenClip = (clipHistory->getClipPath() != nullptr); - seenConcat = gFalse; - int i = 1; - while (i <= maxOperatorHistoryDepth) { - const char *opName = getPreviousOperator(i); - if (!strcmp(opName, "cm")) { - if (seenConcat) { // more than one 'cm' + // save current graphics state + if (shading->getType() != 2 && shading->getType() != 3) { + savedPath = state->getPath()->copy(); + saveState(); + savedState = gTrue; + } else { // get gradient transform if possible + // check proper operator sequence + // first there should be one W(*) and then one 'cm' somewhere before 'sh' + GBool seenClip, seenConcat; + seenClip = (clipHistory->getClipPath() != nullptr); + seenConcat = gFalse; + int i = 1; + while (i <= maxOperatorHistoryDepth) { + const char *opName = getPreviousOperator(i); + if (!strcmp(opName, "cm")) { + if (seenConcat) { // more than one 'cm' + break; + } else { + seenConcat = gTrue; + } + } + i++; + } + + if (seenConcat && seenClip) { + if (builder->getTransform(gradientTransform)) { + matrix = (double *)&gradientTransform; + builder->setTransform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); // remove transform + } + } + } + + // clip to bbox + if (shading->getHasBBox()) { + shading->getBBox(&xMin, &yMin, &xMax, &yMax); + if (matrix != nullptr) { + xTemp = matrix[0] * xMin + matrix[2] * yMin + matrix[4]; + yTemp = matrix[1] * xMin + matrix[3] * yMin + matrix[5]; + state->moveTo(xTemp, yTemp); + xTemp = matrix[0] * xMax + matrix[2] * yMin + matrix[4]; + yTemp = matrix[1] * xMax + matrix[3] * yMin + matrix[5]; + state->lineTo(xTemp, yTemp); + xTemp = matrix[0] * xMax + matrix[2] * yMax + matrix[4]; + yTemp = matrix[1] * xMax + matrix[3] * yMax + matrix[5]; + state->lineTo(xTemp, yTemp); + xTemp = matrix[0] * xMin + matrix[2] * yMax + matrix[4]; + yTemp = matrix[1] * xMin + matrix[3] * yMax + matrix[5]; + state->lineTo(xTemp, yTemp); + } else { + state->moveTo(xMin, yMin); + state->lineTo(xMax, yMin); + state->lineTo(xMax, yMax); + state->lineTo(xMin, yMax); + } + state->closePath(); + state->clip(); + if (savedState) + builder->setClipPath(state); + else + builder->clip(state); + state->clearPath(); + } + + // set the color space + if (savedState) + state->setFillColorSpace(shading->getColorSpace()->copy()); + + // do shading type-specific operations + switch (shading->getType()) { + case 1: + doFunctionShFill(static_cast(shading)); break; - } else { - seenConcat = gTrue; - } - } - i++; - } - - if (seenConcat && seenClip) { - if (builder->getTransform(gradientTransform)) { - matrix = (double*)&gradientTransform; - builder->setTransform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); // remove transform - } - } - } - - // clip to bbox - if (shading->getHasBBox()) { - shading->getBBox(&xMin, &yMin, &xMax, &yMax); - if (matrix != nullptr) { - xTemp = matrix[0]*xMin + matrix[2]*yMin + matrix[4]; - yTemp = matrix[1]*xMin + matrix[3]*yMin + matrix[5]; - state->moveTo(xTemp, yTemp); - xTemp = matrix[0]*xMax + matrix[2]*yMin + matrix[4]; - yTemp = matrix[1]*xMax + matrix[3]*yMin + matrix[5]; - state->lineTo(xTemp, yTemp); - xTemp = matrix[0]*xMax + matrix[2]*yMax + matrix[4]; - yTemp = matrix[1]*xMax + matrix[3]*yMax + matrix[5]; - state->lineTo(xTemp, yTemp); - xTemp = matrix[0]*xMin + matrix[2]*yMax + matrix[4]; - yTemp = matrix[1]*xMin + matrix[3]*yMax + matrix[5]; - state->lineTo(xTemp, yTemp); - } - else { - state->moveTo(xMin, yMin); - state->lineTo(xMax, yMin); - state->lineTo(xMax, yMax); - state->lineTo(xMin, yMax); + case 2: + case 3: + if (clipHistory->getClipPath()) { + builder->addShadedFill(shading, matrix, clipHistory->getClipPath(), + clipHistory->getClipType() == clipEO ? true : false); + } + break; + case 4: + case 5: + doGouraudTriangleShFill(static_cast(shading)); + break; + case 6: + case 7: + doPatchMeshShFill(static_cast(shading)); + break; + } + + // restore graphics state + if (savedState) { + restoreState(); + state->setPath(savedPath); + } + + delete shading; +} + +void PdfParser::doFunctionShFill(GfxFunctionShading *shading) +{ + double x0, y0, x1, y1; + GfxColor colors[4]; + + shading->getDomain(&x0, &y0, &x1, &y1); + shading->getColor(x0, y0, &colors[0]); + shading->getColor(x0, y1, &colors[1]); + shading->getColor(x1, y0, &colors[2]); + shading->getColor(x1, y1, &colors[3]); + doFunctionShFill1(shading, x0, y0, x1, y1, colors, 0); +} + +void PdfParser::doFunctionShFill1(GfxFunctionShading *shading, double x0, double y0, double x1, double y1, + GfxColor *colors, int depth) +{ + GfxColor fillColor; + GfxColor color0M, color1M, colorM0, colorM1, colorMM; + GfxColor colors2[4]; + double functionColorDelta = colorDeltas[pdfFunctionShading - 1]; + const double *matrix; + double xM, yM; + int nComps, i, j; + + nComps = shading->getColorSpace()->getNComps(); + matrix = shading->getMatrix(); + + // compare the four corner colors + for (i = 0; i < 4; ++i) { + for (j = 0; j < nComps; ++j) { + if (abs(colors[i].c[j] - colors[(i + 1) & 3].c[j]) > functionColorDelta) { + break; + } + } + if (j < nComps) { + break; + } + } + + // center of the rectangle + xM = 0.5 * (x0 + x1); + yM = 0.5 * (y0 + y1); + + // the four corner colors are close (or we hit the recursive limit) + // -- fill the rectangle; but require at least one subdivision + // (depth==0) to avoid problems when the four outer corners of the + // shaded region are the same color + if ((i == 4 && depth > 0) || depth == maxDepths[pdfFunctionShading - 1]) { + // use the center color + shading->getColor(xM, yM, &fillColor); + state->setFillColor(&fillColor); + + // fill the rectangle + state->moveTo(x0 * matrix[0] + y0 * matrix[2] + matrix[4], x0 * matrix[1] + y0 * matrix[3] + matrix[5]); + state->lineTo(x1 * matrix[0] + y0 * matrix[2] + matrix[4], x1 * matrix[1] + y0 * matrix[3] + matrix[5]); + state->lineTo(x1 * matrix[0] + y1 * matrix[2] + matrix[4], x1 * matrix[1] + y1 * matrix[3] + matrix[5]); + state->lineTo(x0 * matrix[0] + y1 * matrix[2] + matrix[4], x0 * matrix[1] + y1 * matrix[3] + matrix[5]); + state->closePath(); + builder->addPath(state, true, false); + state->clearPath(); + + // the four corner colors are not close enough -- subdivide the + // rectangle + } else { + // colors[0] colorM0 colors[2] + // (x0,y0) (xM,y0) (x1,y0) + // +----------+----------+ + // | | | + // | UL | UR | + // color0M | colorMM | color1M + // (x0,yM) +----------+----------+ (x1,yM) + // | (xM,yM) | + // | LL | LR | + // | | | + // +----------+----------+ + // colors[1] colorM1 colors[3] + // (x0,y1) (xM,y1) (x1,y1) + + shading->getColor(x0, yM, &color0M); + shading->getColor(x1, yM, &color1M); + shading->getColor(xM, y0, &colorM0); + shading->getColor(xM, y1, &colorM1); + shading->getColor(xM, yM, &colorMM); + + // upper-left sub-rectangle + colors2[0] = colors[0]; + colors2[1] = color0M; + colors2[2] = colorM0; + colors2[3] = colorMM; + doFunctionShFill1(shading, x0, y0, xM, yM, colors2, depth + 1); + + // lower-left sub-rectangle + colors2[0] = color0M; + colors2[1] = colors[1]; + colors2[2] = colorMM; + colors2[3] = colorM1; + doFunctionShFill1(shading, x0, yM, xM, y1, colors2, depth + 1); + + // upper-right sub-rectangle + colors2[0] = colorM0; + colors2[1] = colorMM; + colors2[2] = colors[2]; + colors2[3] = color1M; + doFunctionShFill1(shading, xM, y0, x1, yM, colors2, depth + 1); + + // lower-right sub-rectangle + colors2[0] = colorMM; + colors2[1] = colorM1; + colors2[2] = color1M; + colors2[3] = colors[3]; + doFunctionShFill1(shading, xM, yM, x1, y1, colors2, depth + 1); + } +} + +void PdfParser::doGouraudTriangleShFill(GfxGouraudTriangleShading *shading) +{ + double x0, y0, x1, y1, x2, y2; + GfxColor color0, color1, color2; + int i; + + for (i = 0; i < shading->getNTriangles(); ++i) { + shading->getTriangle(i, &x0, &y0, &color0, &x1, &y1, &color1, &x2, &y2, &color2); + gouraudFillTriangle(x0, y0, &color0, x1, y1, &color1, x2, y2, &color2, shading->getColorSpace()->getNComps(), + 0); + } +} + +void PdfParser::gouraudFillTriangle(double x0, double y0, GfxColor *color0, double x1, double y1, GfxColor *color1, + double x2, double y2, GfxColor *color2, int nComps, int depth) +{ + double x01, y01, x12, y12, x20, y20; + double gouraudColorDelta = colorDeltas[pdfGouraudTriangleShading - 1]; + GfxColor color01, color12, color20; + int i; + + for (i = 0; i < nComps; ++i) { + if (abs(color0->c[i] - color1->c[i]) > gouraudColorDelta || + abs(color1->c[i] - color2->c[i]) > gouraudColorDelta) { + break; + } + } + if (i == nComps || depth == maxDepths[pdfGouraudTriangleShading - 1]) { + state->setFillColor(color0); + state->moveTo(x0, y0); + state->lineTo(x1, y1); + state->lineTo(x2, y2); + state->closePath(); + builder->addPath(state, true, false); + state->clearPath(); + } else { + x01 = 0.5 * (x0 + x1); + y01 = 0.5 * (y0 + y1); + x12 = 0.5 * (x1 + x2); + y12 = 0.5 * (y1 + y2); + x20 = 0.5 * (x2 + x0); + y20 = 0.5 * (y2 + y0); + //~ if the shading has a Function, this should interpolate on the + //~ function parameter, not on the color components + for (i = 0; i < nComps; ++i) { + color01.c[i] = (color0->c[i] + color1->c[i]) / 2; + color12.c[i] = (color1->c[i] + color2->c[i]) / 2; + color20.c[i] = (color2->c[i] + color0->c[i]) / 2; + } + gouraudFillTriangle(x0, y0, color0, x01, y01, &color01, x20, y20, &color20, nComps, depth + 1); + gouraudFillTriangle(x01, y01, &color01, x1, y1, color1, x12, y12, &color12, nComps, depth + 1); + gouraudFillTriangle(x01, y01, &color01, x12, y12, &color12, x20, y20, &color20, nComps, depth + 1); + gouraudFillTriangle(x20, y20, &color20, x12, y12, &color12, x2, y2, color2, nComps, depth + 1); + } +} + +void PdfParser::doPatchMeshShFill(GfxPatchMeshShading *shading) +{ + int start, i; + + if (shading->getNPatches() > 128) { + start = 3; + } else if (shading->getNPatches() > 64) { + start = 2; + } else if (shading->getNPatches() > 16) { + start = 1; + } else { + start = 0; } - state->closePath(); - state->clip(); - if (savedState) - builder->setClipPath(state); - else - builder->clip(state); - state->clearPath(); - } + for (i = 0; i < shading->getNPatches(); ++i) { + fillPatch(shading->getPatch(i), shading->getColorSpace()->getNComps(), start); + } +} - // set the color space - if (savedState) - state->setFillColorSpace(shading->getColorSpace()->copy()); +void PdfParser::fillPatch(_POPPLER_CONST GfxPatch *patch, int nComps, int depth) +{ + GfxPatch patch00 = blankPatch(); + GfxPatch patch01 = blankPatch(); + GfxPatch patch10 = blankPatch(); + GfxPatch patch11 = blankPatch(); + GfxColor color = {{0}}; + double xx[4][8]; + double yy[4][8]; + double xxm; + double yym; + double patchColorDelta = colorDeltas[pdfPatchMeshShading - 1]; - // do shading type-specific operations - switch (shading->getType()) { - case 1: - doFunctionShFill(static_cast(shading)); - break; - case 2: - case 3: - if (clipHistory->getClipPath()) { - builder->addShadedFill(shading, matrix, clipHistory->getClipPath(), - clipHistory->getClipType() == clipEO ? true : false); - } - break; - case 4: - case 5: - doGouraudTriangleShFill(static_cast(shading)); - break; - case 6: - case 7: - doPatchMeshShFill(static_cast(shading)); - break; - } - - // restore graphics state - if (savedState) { - restoreState(); - state->setPath(savedPath); - } - - delete shading; -} - -void PdfParser::doFunctionShFill(GfxFunctionShading *shading) { - double x0, y0, x1, y1; - GfxColor colors[4]; - - shading->getDomain(&x0, &y0, &x1, &y1); - shading->getColor(x0, y0, &colors[0]); - shading->getColor(x0, y1, &colors[1]); - shading->getColor(x1, y0, &colors[2]); - shading->getColor(x1, y1, &colors[3]); - doFunctionShFill1(shading, x0, y0, x1, y1, colors, 0); -} - -void PdfParser::doFunctionShFill1(GfxFunctionShading *shading, - double x0, double y0, - double x1, double y1, - GfxColor *colors, int depth) { - GfxColor fillColor; - GfxColor color0M, color1M, colorM0, colorM1, colorMM; - GfxColor colors2[4]; - double functionColorDelta = colorDeltas[pdfFunctionShading-1]; - const double *matrix; - double xM, yM; - int nComps, i, j; - - nComps = shading->getColorSpace()->getNComps(); - matrix = shading->getMatrix(); - - // compare the four corner colors - for (i = 0; i < 4; ++i) { - for (j = 0; j < nComps; ++j) { - if (abs(colors[i].c[j] - colors[(i+1)&3].c[j]) > functionColorDelta) { - break; - } - } - if (j < nComps) { - break; - } - } - - // center of the rectangle - xM = 0.5 * (x0 + x1); - yM = 0.5 * (y0 + y1); - - // the four corner colors are close (or we hit the recursive limit) - // -- fill the rectangle; but require at least one subdivision - // (depth==0) to avoid problems when the four outer corners of the - // shaded region are the same color - if ((i == 4 && depth > 0) || depth == maxDepths[pdfFunctionShading-1]) { - - // use the center color - shading->getColor(xM, yM, &fillColor); - state->setFillColor(&fillColor); - - // fill the rectangle - state->moveTo(x0 * matrix[0] + y0 * matrix[2] + matrix[4], - x0 * matrix[1] + y0 * matrix[3] + matrix[5]); - state->lineTo(x1 * matrix[0] + y0 * matrix[2] + matrix[4], - x1 * matrix[1] + y0 * matrix[3] + matrix[5]); - state->lineTo(x1 * matrix[0] + y1 * matrix[2] + matrix[4], - x1 * matrix[1] + y1 * matrix[3] + matrix[5]); - state->lineTo(x0 * matrix[0] + y1 * matrix[2] + matrix[4], - x0 * matrix[1] + y1 * matrix[3] + matrix[5]); - state->closePath(); - builder->addPath(state, true, false); - state->clearPath(); + int i; - // the four corner colors are not close enough -- subdivide the - // rectangle - } else { - - // colors[0] colorM0 colors[2] - // (x0,y0) (xM,y0) (x1,y0) - // +----------+----------+ - // | | | - // | UL | UR | - // color0M | colorMM | color1M - // (x0,yM) +----------+----------+ (x1,yM) - // | (xM,yM) | - // | LL | LR | - // | | | - // +----------+----------+ - // colors[1] colorM1 colors[3] - // (x0,y1) (xM,y1) (x1,y1) - - shading->getColor(x0, yM, &color0M); - shading->getColor(x1, yM, &color1M); - shading->getColor(xM, y0, &colorM0); - shading->getColor(xM, y1, &colorM1); - shading->getColor(xM, yM, &colorMM); - - // upper-left sub-rectangle - colors2[0] = colors[0]; - colors2[1] = color0M; - colors2[2] = colorM0; - colors2[3] = colorMM; - doFunctionShFill1(shading, x0, y0, xM, yM, colors2, depth + 1); - - // lower-left sub-rectangle - colors2[0] = color0M; - colors2[1] = colors[1]; - colors2[2] = colorMM; - colors2[3] = colorM1; - doFunctionShFill1(shading, x0, yM, xM, y1, colors2, depth + 1); - - // upper-right sub-rectangle - colors2[0] = colorM0; - colors2[1] = colorMM; - colors2[2] = colors[2]; - colors2[3] = color1M; - doFunctionShFill1(shading, xM, y0, x1, yM, colors2, depth + 1); - - // lower-right sub-rectangle - colors2[0] = colorMM; - colors2[1] = colorM1; - colors2[2] = color1M; - colors2[3] = colors[3]; - doFunctionShFill1(shading, xM, yM, x1, y1, colors2, depth + 1); - } -} - -void PdfParser::doGouraudTriangleShFill(GfxGouraudTriangleShading *shading) { - double x0, y0, x1, y1, x2, y2; - GfxColor color0, color1, color2; - int i; - - for (i = 0; i < shading->getNTriangles(); ++i) { - shading->getTriangle(i, &x0, &y0, &color0, - &x1, &y1, &color1, - &x2, &y2, &color2); - gouraudFillTriangle(x0, y0, &color0, x1, y1, &color1, x2, y2, &color2, - shading->getColorSpace()->getNComps(), 0); - } -} - -void PdfParser::gouraudFillTriangle(double x0, double y0, GfxColor *color0, - double x1, double y1, GfxColor *color1, - double x2, double y2, GfxColor *color2, - int nComps, int depth) { - double x01, y01, x12, y12, x20, y20; - double gouraudColorDelta = colorDeltas[pdfGouraudTriangleShading-1]; - GfxColor color01, color12, color20; - int i; - - for (i = 0; i < nComps; ++i) { - if (abs(color0->c[i] - color1->c[i]) > gouraudColorDelta || - abs(color1->c[i] - color2->c[i]) > gouraudColorDelta) { - break; - } - } - if (i == nComps || depth == maxDepths[pdfGouraudTriangleShading-1]) { - state->setFillColor(color0); - state->moveTo(x0, y0); - state->lineTo(x1, y1); - state->lineTo(x2, y2); - state->closePath(); - builder->addPath(state, true, false); - state->clearPath(); - } else { - x01 = 0.5 * (x0 + x1); - y01 = 0.5 * (y0 + y1); - x12 = 0.5 * (x1 + x2); - y12 = 0.5 * (y1 + y2); - x20 = 0.5 * (x2 + x0); - y20 = 0.5 * (y2 + y0); - //~ if the shading has a Function, this should interpolate on the - //~ function parameter, not on the color components - for (i = 0; i < nComps; ++i) { - color01.c[i] = (color0->c[i] + color1->c[i]) / 2; - color12.c[i] = (color1->c[i] + color2->c[i]) / 2; - color20.c[i] = (color2->c[i] + color0->c[i]) / 2; - } - gouraudFillTriangle(x0, y0, color0, x01, y01, &color01, - x20, y20, &color20, nComps, depth + 1); - gouraudFillTriangle(x01, y01, &color01, x1, y1, color1, - x12, y12, &color12, nComps, depth + 1); - gouraudFillTriangle(x01, y01, &color01, x12, y12, &color12, - x20, y20, &color20, nComps, depth + 1); - gouraudFillTriangle(x20, y20, &color20, x12, y12, &color12, - x2, y2, color2, nComps, depth + 1); - } -} - -void PdfParser::doPatchMeshShFill(GfxPatchMeshShading *shading) { - int start, i; - - if (shading->getNPatches() > 128) { - start = 3; - } else if (shading->getNPatches() > 64) { - start = 2; - } else if (shading->getNPatches() > 16) { - start = 1; - } else { - start = 0; - } - for (i = 0; i < shading->getNPatches(); ++i) { - fillPatch(shading->getPatch(i), shading->getColorSpace()->getNComps(), - start); - } -} - -void PdfParser::fillPatch(_POPPLER_CONST GfxPatch *patch, int nComps, int depth) { - GfxPatch patch00 = blankPatch(); - GfxPatch patch01 = blankPatch(); - GfxPatch patch10 = blankPatch(); - GfxPatch patch11 = blankPatch(); - GfxColor color = {{0}}; - double xx[4][8]; - double yy[4][8]; - double xxm; - double yym; - double patchColorDelta = colorDeltas[pdfPatchMeshShading - 1]; - - int i; - - for (i = 0; i < nComps; ++i) { - if (std::abs(patch->color[0][0].c[i] - patch->color[0][1].c[i]) - > patchColorDelta || - std::abs(patch->color[0][1].c[i] - patch->color[1][1].c[i]) - > patchColorDelta || - std::abs(patch->color[1][1].c[i] - patch->color[1][0].c[i]) - > patchColorDelta || - std::abs(patch->color[1][0].c[i] - patch->color[0][0].c[i]) - > patchColorDelta) { - break; - } - color.c[i] = GfxColorComp(patch->color[0][0].c[i]); - } - if (i == nComps || depth == maxDepths[pdfPatchMeshShading-1]) { - state->setFillColor(&color); - state->moveTo(patch->x[0][0], patch->y[0][0]); - state->curveTo(patch->x[0][1], patch->y[0][1], - patch->x[0][2], patch->y[0][2], - patch->x[0][3], patch->y[0][3]); - state->curveTo(patch->x[1][3], patch->y[1][3], - patch->x[2][3], patch->y[2][3], - patch->x[3][3], patch->y[3][3]); - state->curveTo(patch->x[3][2], patch->y[3][2], - patch->x[3][1], patch->y[3][1], - patch->x[3][0], patch->y[3][0]); - state->curveTo(patch->x[2][0], patch->y[2][0], - patch->x[1][0], patch->y[1][0], - patch->x[0][0], patch->y[0][0]); - state->closePath(); - builder->addPath(state, true, false); - state->clearPath(); - } else { - for (i = 0; i < 4; ++i) { - xx[i][0] = patch->x[i][0]; - yy[i][0] = patch->y[i][0]; - xx[i][1] = 0.5 * (patch->x[i][0] + patch->x[i][1]); - yy[i][1] = 0.5 * (patch->y[i][0] + patch->y[i][1]); - xxm = 0.5 * (patch->x[i][1] + patch->x[i][2]); - yym = 0.5 * (patch->y[i][1] + patch->y[i][2]); - xx[i][6] = 0.5 * (patch->x[i][2] + patch->x[i][3]); - yy[i][6] = 0.5 * (patch->y[i][2] + patch->y[i][3]); - xx[i][2] = 0.5 * (xx[i][1] + xxm); - yy[i][2] = 0.5 * (yy[i][1] + yym); - xx[i][5] = 0.5 * (xxm + xx[i][6]); - yy[i][5] = 0.5 * (yym + yy[i][6]); - xx[i][3] = xx[i][4] = 0.5 * (xx[i][2] + xx[i][5]); - yy[i][3] = yy[i][4] = 0.5 * (yy[i][2] + yy[i][5]); - xx[i][7] = patch->x[i][3]; - yy[i][7] = patch->y[i][3]; - } - for (i = 0; i < 4; ++i) { - patch00.x[0][i] = xx[0][i]; - patch00.y[0][i] = yy[0][i]; - patch00.x[1][i] = 0.5 * (xx[0][i] + xx[1][i]); - patch00.y[1][i] = 0.5 * (yy[0][i] + yy[1][i]); - xxm = 0.5 * (xx[1][i] + xx[2][i]); - yym = 0.5 * (yy[1][i] + yy[2][i]); - patch10.x[2][i] = 0.5 * (xx[2][i] + xx[3][i]); - patch10.y[2][i] = 0.5 * (yy[2][i] + yy[3][i]); - patch00.x[2][i] = 0.5 * (patch00.x[1][i] + xxm); - patch00.y[2][i] = 0.5 * (patch00.y[1][i] + yym); - patch10.x[1][i] = 0.5 * (xxm + patch10.x[2][i]); - patch10.y[1][i] = 0.5 * (yym + patch10.y[2][i]); - patch00.x[3][i] = 0.5 * (patch00.x[2][i] + patch10.x[1][i]); - patch00.y[3][i] = 0.5 * (patch00.y[2][i] + patch10.y[1][i]); - patch10.x[0][i] = patch00.x[3][i]; - patch10.y[0][i] = patch00.y[3][i]; - patch10.x[3][i] = xx[3][i]; - patch10.y[3][i] = yy[3][i]; - } - for (i = 4; i < 8; ++i) { - patch01.x[0][i-4] = xx[0][i]; - patch01.y[0][i-4] = yy[0][i]; - patch01.x[1][i-4] = 0.5 * (xx[0][i] + xx[1][i]); - patch01.y[1][i-4] = 0.5 * (yy[0][i] + yy[1][i]); - xxm = 0.5 * (xx[1][i] + xx[2][i]); - yym = 0.5 * (yy[1][i] + yy[2][i]); - patch11.x[2][i-4] = 0.5 * (xx[2][i] + xx[3][i]); - patch11.y[2][i-4] = 0.5 * (yy[2][i] + yy[3][i]); - patch01.x[2][i-4] = 0.5 * (patch01.x[1][i-4] + xxm); - patch01.y[2][i-4] = 0.5 * (patch01.y[1][i-4] + yym); - patch11.x[1][i-4] = 0.5 * (xxm + patch11.x[2][i-4]); - patch11.y[1][i-4] = 0.5 * (yym + patch11.y[2][i-4]); - patch01.x[3][i-4] = 0.5 * (patch01.x[2][i-4] + patch11.x[1][i-4]); - patch01.y[3][i-4] = 0.5 * (patch01.y[2][i-4] + patch11.y[1][i-4]); - patch11.x[0][i-4] = patch01.x[3][i-4]; - patch11.y[0][i-4] = patch01.y[3][i-4]; - patch11.x[3][i-4] = xx[3][i]; - patch11.y[3][i-4] = yy[3][i]; - } - //~ if the shading has a Function, this should interpolate on the - //~ function parameter, not on the color components for (i = 0; i < nComps; ++i) { - patch00.color[0][0].c[i] = patch->color[0][0].c[i]; - patch00.color[0][1].c[i] = (patch->color[0][0].c[i] + - patch->color[0][1].c[i]) / 2; - patch01.color[0][0].c[i] = patch00.color[0][1].c[i]; - patch01.color[0][1].c[i] = patch->color[0][1].c[i]; - patch01.color[1][1].c[i] = (patch->color[0][1].c[i] + - patch->color[1][1].c[i]) / 2; - patch11.color[0][1].c[i] = patch01.color[1][1].c[i]; - patch11.color[1][1].c[i] = patch->color[1][1].c[i]; - patch11.color[1][0].c[i] = (patch->color[1][1].c[i] + - patch->color[1][0].c[i]) / 2; - patch10.color[1][1].c[i] = patch11.color[1][0].c[i]; - patch10.color[1][0].c[i] = patch->color[1][0].c[i]; - patch10.color[0][0].c[i] = (patch->color[1][0].c[i] + - patch->color[0][0].c[i]) / 2; - patch00.color[1][0].c[i] = patch10.color[0][0].c[i]; - patch00.color[1][1].c[i] = (patch00.color[1][0].c[i] + - patch01.color[1][1].c[i]) / 2; - patch01.color[1][0].c[i] = patch00.color[1][1].c[i]; - patch11.color[0][0].c[i] = patch00.color[1][1].c[i]; - patch10.color[0][1].c[i] = patch00.color[1][1].c[i]; - } - fillPatch(&patch00, nComps, depth + 1); - fillPatch(&patch10, nComps, depth + 1); - fillPatch(&patch01, nComps, depth + 1); - fillPatch(&patch11, nComps, depth + 1); - } -} - -void PdfParser::doEndPath() { - if (state->isCurPt() && clip != clipNone) { - state->clip(); - if (clip == clipNormal) { - clipHistory->setClip(state->getPath(), clipNormal); - builder->clip(state); + if (std::abs(patch->color[0][0].c[i] - patch->color[0][1].c[i]) > patchColorDelta || + std::abs(patch->color[0][1].c[i] - patch->color[1][1].c[i]) > patchColorDelta || + std::abs(patch->color[1][1].c[i] - patch->color[1][0].c[i]) > patchColorDelta || + std::abs(patch->color[1][0].c[i] - patch->color[0][0].c[i]) > patchColorDelta) { + break; + } + color.c[i] = GfxColorComp(patch->color[0][0].c[i]); + } + if (i == nComps || depth == maxDepths[pdfPatchMeshShading - 1]) { + state->setFillColor(&color); + state->moveTo(patch->x[0][0], patch->y[0][0]); + state->curveTo(patch->x[0][1], patch->y[0][1], patch->x[0][2], patch->y[0][2], patch->x[0][3], patch->y[0][3]); + state->curveTo(patch->x[1][3], patch->y[1][3], patch->x[2][3], patch->y[2][3], patch->x[3][3], patch->y[3][3]); + state->curveTo(patch->x[3][2], patch->y[3][2], patch->x[3][1], patch->y[3][1], patch->x[3][0], patch->y[3][0]); + state->curveTo(patch->x[2][0], patch->y[2][0], patch->x[1][0], patch->y[1][0], patch->x[0][0], patch->y[0][0]); + state->closePath(); + builder->addPath(state, true, false); + state->clearPath(); } else { - clipHistory->setClip(state->getPath(), clipEO); - builder->clip(state, true); + for (i = 0; i < 4; ++i) { + xx[i][0] = patch->x[i][0]; + yy[i][0] = patch->y[i][0]; + xx[i][1] = 0.5 * (patch->x[i][0] + patch->x[i][1]); + yy[i][1] = 0.5 * (patch->y[i][0] + patch->y[i][1]); + xxm = 0.5 * (patch->x[i][1] + patch->x[i][2]); + yym = 0.5 * (patch->y[i][1] + patch->y[i][2]); + xx[i][6] = 0.5 * (patch->x[i][2] + patch->x[i][3]); + yy[i][6] = 0.5 * (patch->y[i][2] + patch->y[i][3]); + xx[i][2] = 0.5 * (xx[i][1] + xxm); + yy[i][2] = 0.5 * (yy[i][1] + yym); + xx[i][5] = 0.5 * (xxm + xx[i][6]); + yy[i][5] = 0.5 * (yym + yy[i][6]); + xx[i][3] = xx[i][4] = 0.5 * (xx[i][2] + xx[i][5]); + yy[i][3] = yy[i][4] = 0.5 * (yy[i][2] + yy[i][5]); + xx[i][7] = patch->x[i][3]; + yy[i][7] = patch->y[i][3]; + } + for (i = 0; i < 4; ++i) { + patch00.x[0][i] = xx[0][i]; + patch00.y[0][i] = yy[0][i]; + patch00.x[1][i] = 0.5 * (xx[0][i] + xx[1][i]); + patch00.y[1][i] = 0.5 * (yy[0][i] + yy[1][i]); + xxm = 0.5 * (xx[1][i] + xx[2][i]); + yym = 0.5 * (yy[1][i] + yy[2][i]); + patch10.x[2][i] = 0.5 * (xx[2][i] + xx[3][i]); + patch10.y[2][i] = 0.5 * (yy[2][i] + yy[3][i]); + patch00.x[2][i] = 0.5 * (patch00.x[1][i] + xxm); + patch00.y[2][i] = 0.5 * (patch00.y[1][i] + yym); + patch10.x[1][i] = 0.5 * (xxm + patch10.x[2][i]); + patch10.y[1][i] = 0.5 * (yym + patch10.y[2][i]); + patch00.x[3][i] = 0.5 * (patch00.x[2][i] + patch10.x[1][i]); + patch00.y[3][i] = 0.5 * (patch00.y[2][i] + patch10.y[1][i]); + patch10.x[0][i] = patch00.x[3][i]; + patch10.y[0][i] = patch00.y[3][i]; + patch10.x[3][i] = xx[3][i]; + patch10.y[3][i] = yy[3][i]; + } + for (i = 4; i < 8; ++i) { + patch01.x[0][i - 4] = xx[0][i]; + patch01.y[0][i - 4] = yy[0][i]; + patch01.x[1][i - 4] = 0.5 * (xx[0][i] + xx[1][i]); + patch01.y[1][i - 4] = 0.5 * (yy[0][i] + yy[1][i]); + xxm = 0.5 * (xx[1][i] + xx[2][i]); + yym = 0.5 * (yy[1][i] + yy[2][i]); + patch11.x[2][i - 4] = 0.5 * (xx[2][i] + xx[3][i]); + patch11.y[2][i - 4] = 0.5 * (yy[2][i] + yy[3][i]); + patch01.x[2][i - 4] = 0.5 * (patch01.x[1][i - 4] + xxm); + patch01.y[2][i - 4] = 0.5 * (patch01.y[1][i - 4] + yym); + patch11.x[1][i - 4] = 0.5 * (xxm + patch11.x[2][i - 4]); + patch11.y[1][i - 4] = 0.5 * (yym + patch11.y[2][i - 4]); + patch01.x[3][i - 4] = 0.5 * (patch01.x[2][i - 4] + patch11.x[1][i - 4]); + patch01.y[3][i - 4] = 0.5 * (patch01.y[2][i - 4] + patch11.y[1][i - 4]); + patch11.x[0][i - 4] = patch01.x[3][i - 4]; + patch11.y[0][i - 4] = patch01.y[3][i - 4]; + patch11.x[3][i - 4] = xx[3][i]; + patch11.y[3][i - 4] = yy[3][i]; + } + //~ if the shading has a Function, this should interpolate on the + //~ function parameter, not on the color components + for (i = 0; i < nComps; ++i) { + patch00.color[0][0].c[i] = patch->color[0][0].c[i]; + patch00.color[0][1].c[i] = (patch->color[0][0].c[i] + patch->color[0][1].c[i]) / 2; + patch01.color[0][0].c[i] = patch00.color[0][1].c[i]; + patch01.color[0][1].c[i] = patch->color[0][1].c[i]; + patch01.color[1][1].c[i] = (patch->color[0][1].c[i] + patch->color[1][1].c[i]) / 2; + patch11.color[0][1].c[i] = patch01.color[1][1].c[i]; + patch11.color[1][1].c[i] = patch->color[1][1].c[i]; + patch11.color[1][0].c[i] = (patch->color[1][1].c[i] + patch->color[1][0].c[i]) / 2; + patch10.color[1][1].c[i] = patch11.color[1][0].c[i]; + patch10.color[1][0].c[i] = patch->color[1][0].c[i]; + patch10.color[0][0].c[i] = (patch->color[1][0].c[i] + patch->color[0][0].c[i]) / 2; + patch00.color[1][0].c[i] = patch10.color[0][0].c[i]; + patch00.color[1][1].c[i] = (patch00.color[1][0].c[i] + patch01.color[1][1].c[i]) / 2; + patch01.color[1][0].c[i] = patch00.color[1][1].c[i]; + patch11.color[0][0].c[i] = patch00.color[1][1].c[i]; + patch10.color[0][1].c[i] = patch00.color[1][1].c[i]; + } + fillPatch(&patch00, nComps, depth + 1); + fillPatch(&patch10, nComps, depth + 1); + fillPatch(&patch01, nComps, depth + 1); + fillPatch(&patch11, nComps, depth + 1); + } +} + +void PdfParser::doEndPath() +{ + if (state->isCurPt() && clip != clipNone) { + state->clip(); + if (clip == clipNormal) { + clipHistory->setClip(state->getPath(), clipNormal); + builder->clip(state); + } else { + clipHistory->setClip(state->getPath(), clipEO); + builder->clip(state, true); + } } - } - clip = clipNone; - state->clearPath(); + clip = clipNone; + state->clearPath(); } //------------------------------------------------------------------------ @@ -2151,12 +2046,12 @@ void PdfParser::doEndPath() { void PdfParser::opClip(Object /*args*/[], int /*numArgs*/) { - clip = clipNormal; + clip = clipNormal; } void PdfParser::opEOClip(Object /*args*/[], int /*numArgs*/) { - clip = clipEO; + clip = clipEO; } //------------------------------------------------------------------------ @@ -2165,16 +2060,16 @@ void PdfParser::opEOClip(Object /*args*/[], int /*numArgs*/) void PdfParser::opBeginText(Object /*args*/[], int /*numArgs*/) { - state->setTextMat(1, 0, 0, 1, 0, 0); - state->textMoveTo(0, 0); - builder->updateTextPosition(0.0, 0.0); - fontChanged = gTrue; - builder->beginTextObject(state); + state->setTextMat(1, 0, 0, 1, 0, 0); + state->textMoveTo(0, 0); + builder->updateTextPosition(0.0, 0.0); + fontChanged = gTrue; + builder->beginTextObject(state); } void PdfParser::opEndText(Object /*args*/[], int /*numArgs*/) { - builder->endTextObject(state); + builder->endTextObject(state); } //------------------------------------------------------------------------ @@ -2184,65 +2079,63 @@ void PdfParser::opEndText(Object /*args*/[], int /*numArgs*/) // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetCharSpacing(Object args[], int /*numArgs*/) { - state->setCharSpace(args[0].getNum()); + state->setCharSpace(args[0].getNum()); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetFont(Object args[], int /*numArgs*/) { - GfxFont *font = res->lookupFont(args[0].getName()); + GfxFont *font = res->lookupFont(args[0].getName()); - if (!font) { - // unsetting the font (drawing no text) is better than using the - // previous one and drawing random glyphs from it - state->setFont(nullptr, args[1].getNum()); - fontChanged = gTrue; - return; - } - if (printCommands) { - printf(" font: tag=%s name='%s' %g\n", - font->getTag()->getCString(), - font->getName() ? font->getName()->getCString() : "???", - args[1].getNum()); - fflush(stdout); - } + if (!font) { + // unsetting the font (drawing no text) is better than using the + // previous one and drawing random glyphs from it + state->setFont(nullptr, args[1].getNum()); + fontChanged = gTrue; + return; + } + if (printCommands) { + printf(" font: tag=%s name='%s' %g\n", font->getTag()->getCString(), + font->getName() ? font->getName()->getCString() : "???", args[1].getNum()); + fflush(stdout); + } - font->incRefCnt(); - state->setFont(font, args[1].getNum()); - fontChanged = gTrue; + font->incRefCnt(); + state->setFont(font, args[1].getNum()); + fontChanged = gTrue; } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetTextLeading(Object args[], int /*numArgs*/) { - state->setLeading(args[0].getNum()); + state->setLeading(args[0].getNum()); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetTextRender(Object args[], int /*numArgs*/) { - state->setRender(args[0].getInt()); - builder->updateStyle(state); + state->setRender(args[0].getInt()); + builder->updateStyle(state); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetTextRise(Object args[], int /*numArgs*/) { - state->setRise(args[0].getNum()); + state->setRise(args[0].getNum()); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetWordSpacing(Object args[], int /*numArgs*/) { - state->setWordSpace(args[0].getNum()); + state->setWordSpace(args[0].getNum()); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetHorizScaling(Object args[], int /*numArgs*/) { - state->setHorizScaling(args[0].getNum()); - builder->updateTextMatrix(state); - fontChanged = gTrue; + state->setHorizScaling(args[0].getNum()); + builder->updateTextMatrix(state); + fontChanged = gTrue; } //------------------------------------------------------------------------ @@ -2252,47 +2145,46 @@ void PdfParser::opSetHorizScaling(Object args[], int /*numArgs*/) // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opTextMove(Object args[], int /*numArgs*/) { - double tx, ty; + double tx, ty; - tx = state->getLineX() + args[0].getNum(); - ty = state->getLineY() + args[1].getNum(); - state->textMoveTo(tx, ty); - builder->updateTextPosition(tx, ty); + tx = state->getLineX() + args[0].getNum(); + ty = state->getLineY() + args[1].getNum(); + state->textMoveTo(tx, ty); + builder->updateTextPosition(tx, ty); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opTextMoveSet(Object args[], int /*numArgs*/) { - double tx, ty; + double tx, ty; - tx = state->getLineX() + args[0].getNum(); - ty = args[1].getNum(); - state->setLeading(-ty); - ty += state->getLineY(); - state->textMoveTo(tx, ty); - builder->updateTextPosition(tx, ty); + tx = state->getLineX() + args[0].getNum(); + ty = args[1].getNum(); + state->setLeading(-ty); + ty += state->getLineY(); + state->textMoveTo(tx, ty); + builder->updateTextPosition(tx, ty); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opSetTextMatrix(Object args[], int /*numArgs*/) { - state->setTextMat(args[0].getNum(), args[1].getNum(), - args[2].getNum(), args[3].getNum(), - args[4].getNum(), args[5].getNum()); - state->textMoveTo(0, 0); - builder->updateTextMatrix(state); - builder->updateTextPosition(0.0, 0.0); - fontChanged = gTrue; + state->setTextMat(args[0].getNum(), args[1].getNum(), args[2].getNum(), args[3].getNum(), args[4].getNum(), + args[5].getNum()); + state->textMoveTo(0, 0); + builder->updateTextMatrix(state); + builder->updateTextPosition(0.0, 0.0); + fontChanged = gTrue; } void PdfParser::opTextNextLine(Object /*args*/[], int /*numArgs*/) { - double tx, ty; + double tx, ty; - tx = state->getLineX(); - ty = state->getLineY() - state->getLeading(); - state->textMoveTo(tx, ty); - builder->updateTextPosition(tx, ty); + tx = state->getLineX(); + ty = state->getLineY() - state->getLeading(); + state->textMoveTo(tx, ty); + builder->updateTextPosition(tx, ty); } //------------------------------------------------------------------------ @@ -2302,243 +2194,240 @@ void PdfParser::opTextNextLine(Object /*args*/[], int /*numArgs*/) // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opShowText(Object args[], int /*numArgs*/) { - if (!state->getFont()) { - error(errSyntaxError, getPos(), "No font in show"); - return; - } - if (fontChanged) { - builder->updateFont(state); - fontChanged = gFalse; - } - doShowText(args[0].getString()); + if (!state->getFont()) { + error(errSyntaxError, getPos(), "No font in show"); + return; + } + if (fontChanged) { + builder->updateFont(state); + fontChanged = gFalse; + } + doShowText(args[0].getString()); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opMoveShowText(Object args[], int /*numArgs*/) { - double tx = 0; - double ty = 0; + double tx = 0; + double ty = 0; - if (!state->getFont()) { - error(errSyntaxError, getPos(), "No font in move/show"); - return; - } - if (fontChanged) { - builder->updateFont(state); - fontChanged = gFalse; - } - tx = state->getLineX(); - ty = state->getLineY() - state->getLeading(); - state->textMoveTo(tx, ty); - builder->updateTextPosition(tx, ty); - doShowText(args[0].getString()); + if (!state->getFont()) { + error(errSyntaxError, getPos(), "No font in move/show"); + return; + } + if (fontChanged) { + builder->updateFont(state); + fontChanged = gFalse; + } + tx = state->getLineX(); + ty = state->getLineY() - state->getLeading(); + state->textMoveTo(tx, ty); + builder->updateTextPosition(tx, ty); + doShowText(args[0].getString()); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opMoveSetShowText(Object args[], int /*numArgs*/) { - double tx = 0; - double ty = 0; + double tx = 0; + double ty = 0; - if (!state->getFont()) { - error(errSyntaxError, getPos(), "No font in move/set/show"); - return; - } - if (fontChanged) { - builder->updateFont(state); - fontChanged = gFalse; - } - state->setWordSpace(args[0].getNum()); - state->setCharSpace(args[1].getNum()); - tx = state->getLineX(); - ty = state->getLineY() - state->getLeading(); - state->textMoveTo(tx, ty); - builder->updateTextPosition(tx, ty); - doShowText(args[2].getString()); + if (!state->getFont()) { + error(errSyntaxError, getPos(), "No font in move/set/show"); + return; + } + if (fontChanged) { + builder->updateFont(state); + fontChanged = gFalse; + } + state->setWordSpace(args[0].getNum()); + state->setCharSpace(args[1].getNum()); + tx = state->getLineX(); + ty = state->getLineY() - state->getLeading(); + state->textMoveTo(tx, ty); + builder->updateTextPosition(tx, ty); + doShowText(args[2].getString()); } // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opShowSpaceText(Object args[], int /*numArgs*/) { - Array *a = nullptr; - Object obj; - int wMode = 0; - - if (!state->getFont()) { - error(errSyntaxError, getPos(), "No font in show/space"); - return; - } - if (fontChanged) { - builder->updateFont(state); - fontChanged = gFalse; - } - wMode = state->getFont()->getWMode(); - a = args[0].getArray(); - for (int i = 0; i < a->getLength(); ++i) { - _POPPLER_CALL_ARGS(obj, a->get, i); - if (obj.isNum()) { - // this uses the absolute value of the font size to match - // Acrobat's behavior - if (wMode) { - state->textShift(0, -obj.getNum() * 0.001 * - fabs(state->getFontSize())); - } else { - state->textShift(-obj.getNum() * 0.001 * - fabs(state->getFontSize()), 0); - } - builder->updateTextShift(state, obj.getNum()); - } else if (obj.isString()) { - doShowText(obj.getString()); - } else { - error(errSyntaxError, getPos(), "Element of show/space array must be number or string"); + Array *a = nullptr; + Object obj; + int wMode = 0; + + if (!state->getFont()) { + error(errSyntaxError, getPos(), "No font in show/space"); + return; + } + if (fontChanged) { + builder->updateFont(state); + fontChanged = gFalse; + } + wMode = state->getFont()->getWMode(); + a = args[0].getArray(); + for (int i = 0; i < a->getLength(); ++i) { + _POPPLER_CALL_ARGS(obj, a->get, i); + if (obj.isNum()) { + // this uses the absolute value of the font size to match + // Acrobat's behavior + if (wMode) { + state->textShift(0, -obj.getNum() * 0.001 * fabs(state->getFontSize())); + } else { + state->textShift(-obj.getNum() * 0.001 * fabs(state->getFontSize()), 0); + } + builder->updateTextShift(state, obj.getNum()); + } else if (obj.isString()) { + doShowText(obj.getString()); + } else { + error(errSyntaxError, getPos(), "Element of show/space array must be number or string"); + } + _POPPLER_FREE(obj); } - _POPPLER_FREE(obj); - } } -#if POPPLER_CHECK_VERSION(0,64,0) -void PdfParser::doShowText(const GooString *s) { +#if POPPLER_CHECK_VERSION(0, 64, 0) +void PdfParser::doShowText(const GooString *s) +{ #else -void PdfParser::doShowText(GooString *s) { +void PdfParser::doShowText(GooString *s) +{ #endif - GfxFont *font; - int wMode; - double riseX, riseY; - CharCode code; - Unicode _POPPLER_CONST_82 *u = nullptr; - double x, y, dx, dy, tdx, tdy; - double originX, originY, tOriginX, tOriginY; - double oldCTM[6], newCTM[6]; - const double *mat; - Object charProc; - Dict *resDict; - Parser *oldParser; -#if POPPLER_CHECK_VERSION(0,64,0) - const char *p; + GfxFont *font; + int wMode; + double riseX, riseY; + CharCode code; + Unicode _POPPLER_CONST_82 *u = nullptr; + double x, y, dx, dy, tdx, tdy; + double originX, originY, tOriginX, tOriginY; + double oldCTM[6], newCTM[6]; + const double *mat; + Object charProc; + Dict *resDict; + Parser *oldParser; +#if POPPLER_CHECK_VERSION(0, 64, 0) + const char *p; #else - char *p; + char *p; #endif - int len, n, uLen; + int len, n, uLen; - font = state->getFont(); - wMode = font->getWMode(); + font = state->getFont(); + wMode = font->getWMode(); - builder->beginString(state); + builder->beginString(state); - // handle a Type 3 char - if (font->getType() == fontType3 && false) {//out->interpretType3Chars()) { - mat = state->getCTM(); - for (int i = 0; i < 6; ++i) { - oldCTM[i] = mat[i]; - } - mat = state->getTextMat(); - newCTM[0] = mat[0] * oldCTM[0] + mat[1] * oldCTM[2]; - newCTM[1] = mat[0] * oldCTM[1] + mat[1] * oldCTM[3]; - newCTM[2] = mat[2] * oldCTM[0] + mat[3] * oldCTM[2]; - newCTM[3] = mat[2] * oldCTM[1] + mat[3] * oldCTM[3]; - mat = font->getFontMatrix(); - newCTM[0] = mat[0] * newCTM[0] + mat[1] * newCTM[2]; - newCTM[1] = mat[0] * newCTM[1] + mat[1] * newCTM[3]; - newCTM[2] = mat[2] * newCTM[0] + mat[3] * newCTM[2]; - newCTM[3] = mat[2] * newCTM[1] + mat[3] * newCTM[3]; - newCTM[0] *= state->getFontSize(); - newCTM[1] *= state->getFontSize(); - newCTM[2] *= state->getFontSize(); - newCTM[3] *= state->getFontSize(); - newCTM[0] *= state->getHorizScaling(); - newCTM[2] *= state->getHorizScaling(); - state->textTransformDelta(0, state->getRise(), &riseX, &riseY); - double curX = state->getCurX(); - double curY = state->getCurY(); - double lineX = state->getLineX(); - double lineY = state->getLineY(); - oldParser = parser; - p = s->getCString(); - len = s->getLength(); - while (len > 0) { - n = font->getNextChar(p, len, &code, - &u, &uLen, /* TODO: This looks like a memory leak for u. */ - &dx, &dy, &originX, &originY); - dx = dx * state->getFontSize() + state->getCharSpace(); - if (n == 1 && *p == ' ') { - dx += state->getWordSpace(); - } - dx *= state->getHorizScaling(); - dy *= state->getFontSize(); - state->textTransformDelta(dx, dy, &tdx, &tdy); - state->transform(curX + riseX, curY + riseY, &x, &y); - saveState(); - state->setCTM(newCTM[0], newCTM[1], newCTM[2], newCTM[3], x, y); - //~ the CTM concat values here are wrong (but never used) - //out->updateCTM(state, 1, 0, 0, 1, 0, 0); - if (false){ /*!out->beginType3Char(state, curX + riseX, curY + riseY, tdx, tdy, - code, u, uLen)) {*/ - _POPPLER_CALL_ARGS(charProc, ((Gfx8BitFont *)font)->getCharProc, code); - if ((resDict = ((Gfx8BitFont *)font)->getResources())) { - pushResources(resDict); - } - if (charProc.isStream()) { - //parse(&charProc, gFalse); // TODO: parse into SVG font - } else { - error(errSyntaxError, getPos(), "Missing or bad Type3 CharProc entry"); - } - //out->endType3Char(state); - if (resDict) { - popResources(); - } - _POPPLER_FREE(charProc); - } - restoreState(); - // GfxState::restore() does *not* restore the current position, - // so we deal with it here using (curX, curY) and (lineX, lineY) - curX += tdx; - curY += tdy; - state->moveTo(curX, curY); - state->textSetPos(lineX, lineY); - p += n; - len -= n; + // handle a Type 3 char + if (font->getType() == fontType3 && false) { // out->interpretType3Chars()) { + mat = state->getCTM(); + for (int i = 0; i < 6; ++i) { + oldCTM[i] = mat[i]; + } + mat = state->getTextMat(); + newCTM[0] = mat[0] * oldCTM[0] + mat[1] * oldCTM[2]; + newCTM[1] = mat[0] * oldCTM[1] + mat[1] * oldCTM[3]; + newCTM[2] = mat[2] * oldCTM[0] + mat[3] * oldCTM[2]; + newCTM[3] = mat[2] * oldCTM[1] + mat[3] * oldCTM[3]; + mat = font->getFontMatrix(); + newCTM[0] = mat[0] * newCTM[0] + mat[1] * newCTM[2]; + newCTM[1] = mat[0] * newCTM[1] + mat[1] * newCTM[3]; + newCTM[2] = mat[2] * newCTM[0] + mat[3] * newCTM[2]; + newCTM[3] = mat[2] * newCTM[1] + mat[3] * newCTM[3]; + newCTM[0] *= state->getFontSize(); + newCTM[1] *= state->getFontSize(); + newCTM[2] *= state->getFontSize(); + newCTM[3] *= state->getFontSize(); + newCTM[0] *= state->getHorizScaling(); + newCTM[2] *= state->getHorizScaling(); + state->textTransformDelta(0, state->getRise(), &riseX, &riseY); + double curX = state->getCurX(); + double curY = state->getCurY(); + double lineX = state->getLineX(); + double lineY = state->getLineY(); + oldParser = parser; + p = s->getCString(); + len = s->getLength(); + while (len > 0) { + n = font->getNextChar(p, len, &code, &u, &uLen, /* TODO: This looks like a memory leak for u. */ + &dx, &dy, &originX, &originY); + dx = dx * state->getFontSize() + state->getCharSpace(); + if (n == 1 && *p == ' ') { + dx += state->getWordSpace(); + } + dx *= state->getHorizScaling(); + dy *= state->getFontSize(); + state->textTransformDelta(dx, dy, &tdx, &tdy); + state->transform(curX + riseX, curY + riseY, &x, &y); + saveState(); + state->setCTM(newCTM[0], newCTM[1], newCTM[2], newCTM[3], x, y); + //~ the CTM concat values here are wrong (but never used) + // out->updateCTM(state, 1, 0, 0, 1, 0, 0); + if (false) { /*!out->beginType3Char(state, curX + riseX, curY + riseY, tdx, tdy, + code, u, uLen)) {*/ + _POPPLER_CALL_ARGS(charProc, ((Gfx8BitFont *)font)->getCharProc, code); + if ((resDict = ((Gfx8BitFont *)font)->getResources())) { + pushResources(resDict); + } + if (charProc.isStream()) { + // parse(&charProc, gFalse); // TODO: parse into SVG font + } else { + error(errSyntaxError, getPos(), "Missing or bad Type3 CharProc entry"); + } + // out->endType3Char(state); + if (resDict) { + popResources(); + } + _POPPLER_FREE(charProc); + } + restoreState(); + // GfxState::restore() does *not* restore the current position, + // so we deal with it here using (curX, curY) and (lineX, lineY) + curX += tdx; + curY += tdy; + state->moveTo(curX, curY); + state->textSetPos(lineX, lineY); + p += n; + len -= n; + } + parser = oldParser; + + } else { + state->textTransformDelta(0, state->getRise(), &riseX, &riseY); + p = s->getCString(); + len = s->getLength(); + while (len > 0) { + n = font->getNextChar(p, len, &code, &u, &uLen, /* TODO: This looks like a memory leak for u. */ + &dx, &dy, &originX, &originY); + + if (wMode) { + dx *= state->getFontSize(); + dy = dy * state->getFontSize() + state->getCharSpace(); + if (n == 1 && *p == ' ') { + dy += state->getWordSpace(); + } + } else { + dx = dx * state->getFontSize() + state->getCharSpace(); + if (n == 1 && *p == ' ') { + dx += state->getWordSpace(); + } + dx *= state->getHorizScaling(); + dy *= state->getFontSize(); + } + state->textTransformDelta(dx, dy, &tdx, &tdy); + originX *= state->getFontSize(); + originY *= state->getFontSize(); + state->textTransformDelta(originX, originY, &tOriginX, &tOriginY); + builder->addChar(state, state->getCurX() + riseX, state->getCurY() + riseY, dx, dy, tOriginX, tOriginY, + code, n, u, uLen); + state->shift(tdx, tdy); + p += n; + len -= n; + } } - parser = oldParser; - } else { - state->textTransformDelta(0, state->getRise(), &riseX, &riseY); - p = s->getCString(); - len = s->getLength(); - while (len > 0) { - n = font->getNextChar(p, len, &code, - &u, &uLen, /* TODO: This looks like a memory leak for u. */ - &dx, &dy, &originX, &originY); - - if (wMode) { - dx *= state->getFontSize(); - dy = dy * state->getFontSize() + state->getCharSpace(); - if (n == 1 && *p == ' ') { - dy += state->getWordSpace(); - } - } else { - dx = dx * state->getFontSize() + state->getCharSpace(); - if (n == 1 && *p == ' ') { - dx += state->getWordSpace(); - } - dx *= state->getHorizScaling(); - dy *= state->getFontSize(); - } - state->textTransformDelta(dx, dy, &tdx, &tdy); - originX *= state->getFontSize(); - originY *= state->getFontSize(); - state->textTransformDelta(originX, originY, &tOriginX, &tOriginY); - builder->addChar(state, state->getCurX() + riseX, state->getCurY() + riseY, - dx, dy, tOriginX, tOriginY, code, n, u, uLen); - state->shift(tdx, tdy); - p += n; - len -= n; - } - } - - builder->endString(state); + builder->endString(state); } - //------------------------------------------------------------------------ // XObject operators //------------------------------------------------------------------------ @@ -2546,40 +2435,40 @@ void PdfParser::doShowText(GooString *s) { // TODO not good that numArgs is ignored but args[] is used: void PdfParser::opXObject(Object args[], int /*numArgs*/) { - Object obj1, obj2, obj3, refObj; + Object obj1, obj2, obj3, refObj; -#if POPPLER_CHECK_VERSION(0,64,0) - const char *name = args[0].getName(); +#if POPPLER_CHECK_VERSION(0, 64, 0) + const char *name = args[0].getName(); #else - char *name = args[0].getName(); + char *name = args[0].getName(); #endif - _POPPLER_CALL_ARGS(obj1, res->lookupXObject, name); - if (obj1.isNull()) { - return; - } - if (!obj1.isStream()) { - error(errSyntaxError, getPos(), "XObject '{0:s}' is wrong type", name); + _POPPLER_CALL_ARGS(obj1, res->lookupXObject, name); + if (obj1.isNull()) { + return; + } + if (!obj1.isStream()) { + error(errSyntaxError, getPos(), "XObject '{0:s}' is wrong type", name); + _POPPLER_FREE(obj1); + return; + } + _POPPLER_CALL_ARGS(obj2, obj1.streamGetDict()->lookup, "Subtype"); + if (obj2.isName(const_cast("Image"))) { + _POPPLER_CALL_ARGS(refObj, res->lookupXObjectNF, name); + doImage(&refObj, obj1.getStream(), gFalse); + _POPPLER_FREE(refObj); + } else if (obj2.isName(const_cast("Form"))) { + doForm(&obj1); + } else if (obj2.isName(const_cast("PS"))) { + _POPPLER_CALL_ARGS(obj3, obj1.streamGetDict()->lookup, "Level1"); + /* out->psXObject(obj1.getStream(), + obj3.isStream() ? obj3.getStream() : (Stream *)NULL);*/ + } else if (obj2.isName()) { + error(errSyntaxError, getPos(), "Unknown XObject subtype '{0:s}'", obj2.getName()); + } else { + error(errSyntaxError, getPos(), "XObject subtype is missing or wrong type"); + } + _POPPLER_FREE(obj2); _POPPLER_FREE(obj1); - return; - } - _POPPLER_CALL_ARGS(obj2, obj1.streamGetDict()->lookup, "Subtype"); - if (obj2.isName(const_cast("Image"))) { - _POPPLER_CALL_ARGS(refObj, res->lookupXObjectNF, name); - doImage(&refObj, obj1.getStream(), gFalse); - _POPPLER_FREE(refObj); - } else if (obj2.isName(const_cast("Form"))) { - doForm(&obj1); - } else if (obj2.isName(const_cast("PS"))) { - _POPPLER_CALL_ARGS(obj3, obj1.streamGetDict()->lookup, "Level1"); -/* out->psXObject(obj1.getStream(), - obj3.isStream() ? obj3.getStream() : (Stream *)NULL);*/ - } else if (obj2.isName()) { - error(errSyntaxError, getPos(), "Unknown XObject subtype '{0:s}'", obj2.getName()); - } else { - error(errSyntaxError, getPos(), "XObject subtype is missing or wrong type"); - } - _POPPLER_FREE(obj2); - _POPPLER_FREE(obj1); } void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) @@ -2596,28 +2485,26 @@ void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) GBool maskInvert; GBool maskInterpolate; Object obj1, obj2; - + // get info from the stream bits = 0; csMode = streamCSNone; str->getImageParams(&bits, &csMode); - + // get stream dict dict = str->getDict(); - + // get size _POPPLER_CALL_ARGS(obj1, dict->lookup, "Width"); if (obj1.isNull()) { _POPPLER_FREE(obj1); _POPPLER_CALL_ARGS(obj1, dict->lookup, "W"); } - if (obj1.isInt()){ + if (obj1.isInt()) { width = obj1.getInt(); - } - else if (obj1.isReal()) { + } else if (obj1.isReal()) { width = (int)obj1.getReal(); - } - else { + } else { goto err2; } _POPPLER_FREE(obj1); @@ -2628,25 +2515,23 @@ void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) } if (obj1.isInt()) { height = obj1.getInt(); - } - else if (obj1.isReal()){ + } else if (obj1.isReal()) { height = static_cast(obj1.getReal()); - } - else { + } else { goto err2; } _POPPLER_FREE(obj1); - + // image interpolation _POPPLER_CALL_ARGS(obj1, dict->lookup, "Interpolate"); if (obj1.isNull()) { - _POPPLER_FREE(obj1); - _POPPLER_CALL_ARGS(obj1, dict->lookup, "I"); + _POPPLER_FREE(obj1); + _POPPLER_CALL_ARGS(obj1, dict->lookup, "I"); } if (obj1.isBool()) - interpolate = obj1.getBool(); + interpolate = obj1.getBool(); else - interpolate = gFalse; + interpolate = gFalse; _POPPLER_FREE(obj1); maskInterpolate = gFalse; @@ -2659,12 +2544,11 @@ void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) mask = gFalse; if (obj1.isBool()) { mask = obj1.getBool(); - } - else if (!obj1.isNull()) { + } else if (!obj1.isNull()) { goto err2; } _POPPLER_FREE(obj1); - + // bit depth if (bits == 0) { _POPPLER_CALL_ARGS(obj1, dict->lookup, "BitsPerComponent"); @@ -2681,7 +2565,7 @@ void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) } _POPPLER_FREE(obj1); } - + // display a mask if (mask) { // check for inverted mask @@ -2704,10 +2588,10 @@ void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) goto err2; } _POPPLER_FREE(obj1); - + // draw it builder->addImageMask(state, str, width, height, invert, interpolate); - + } else { // get color space and color map GfxColorSpace *colorSpace; @@ -2719,10 +2603,10 @@ void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) if (obj1.isName()) { _POPPLER_CALL_ARGS(obj2, res->lookupColorSpace, obj1.getName()); if (!obj2.isNull()) { - _POPPLER_FREE(obj1); - obj1 = std::move(obj2); + _POPPLER_FREE(obj1); + obj1 = std::move(obj2); } else { - _POPPLER_FREE(obj2); + _POPPLER_FREE(obj2); } } if (!obj1.isNull()) { @@ -2757,9 +2641,9 @@ void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) delete colorMap; goto err1; } - + // get the mask - int maskColors[2*gfxColorMaxComps]; + int maskColors[2 * gfxColorMaxComps]; haveColorKeyMask = haveExplicitMask = haveSoftMask = gFalse; Stream *maskStr = nullptr; int maskWidth = 0; @@ -2768,67 +2652,67 @@ void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) GfxImageColorMap *maskColorMap = nullptr; _POPPLER_CALL_ARGS(maskObj, dict->lookup, "Mask"); _POPPLER_CALL_ARGS(smaskObj, dict->lookup, "SMask"); - Dict* maskDict; + Dict *maskDict; if (smaskObj.isStream()) { // soft mask if (inlineImg) { - goto err1; + goto err1; } maskStr = smaskObj.getStream(); maskDict = smaskObj.streamGetDict(); _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Width"); if (obj1.isNull()) { - _POPPLER_FREE(obj1); - _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "W"); + _POPPLER_FREE(obj1); + _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "W"); } if (!obj1.isInt()) { - goto err2; + goto err2; } maskWidth = obj1.getInt(); _POPPLER_FREE(obj1); _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Height"); if (obj1.isNull()) { - _POPPLER_FREE(obj1); - _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "H"); + _POPPLER_FREE(obj1); + _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "H"); } if (!obj1.isInt()) { - goto err2; + goto err2; } maskHeight = obj1.getInt(); _POPPLER_FREE(obj1); _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "BitsPerComponent"); if (obj1.isNull()) { - _POPPLER_FREE(obj1); - _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "BPC"); + _POPPLER_FREE(obj1); + _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "BPC"); } if (!obj1.isInt()) { - goto err2; + goto err2; } int maskBits = obj1.getInt(); _POPPLER_FREE(obj1); _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Interpolate"); - if (obj1.isNull()) { - _POPPLER_FREE(obj1); - _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "I"); - } - if (obj1.isBool()) - maskInterpolate = obj1.getBool(); - else - maskInterpolate = gFalse; - _POPPLER_FREE(obj1); + if (obj1.isNull()) { + _POPPLER_FREE(obj1); + _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "I"); + } + if (obj1.isBool()) + maskInterpolate = obj1.getBool(); + else + maskInterpolate = gFalse; + _POPPLER_FREE(obj1); _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "ColorSpace"); if (obj1.isNull()) { - _POPPLER_FREE(obj1); - _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "CS"); + _POPPLER_FREE(obj1); + _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "CS"); } if (obj1.isName()) { - _POPPLER_CALL_ARGS(obj2, res->lookupColorSpace, obj1.getName()); - if (!obj2.isNull()) { - _POPPLER_FREE(obj1); - obj1 = std::move(obj2); - } else { - _POPPLER_FREE(obj2); - } + _POPPLER_CALL_ARGS(obj2, res->lookupColorSpace, obj1.getName()); + if (!obj2.isNull()) { + _POPPLER_FREE(obj1); + obj1 = std::move(obj2); + } else { + _POPPLER_FREE(obj2); + } } #if defined(POPPLER_EVEN_NEWER_NEW_COLOR_SPACE_API) GfxColorSpace *maskColorSpace = GfxColorSpace::parse(nullptr, &obj1, nullptr, nullptr); @@ -2857,12 +2741,12 @@ void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) } else if (maskObj.isArray()) { // color key mask int i; - for (i = 0; i < maskObj.arrayGetLength() && i < 2*gfxColorMaxComps; ++i) { + for (i = 0; i < maskObj.arrayGetLength() && i < 2 * gfxColorMaxComps; ++i) { _POPPLER_CALL_ARGS(obj1, maskObj.arrayGet, i); maskColors[i] = obj1.getInt(); _POPPLER_FREE(obj1); } - haveColorKeyMask = gTrue; + haveColorKeyMask = gTrue; } else if (maskObj.isStream()) { // explicit mask if (inlineImg) { @@ -2900,15 +2784,15 @@ void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) } _POPPLER_FREE(obj1); _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Interpolate"); - if (obj1.isNull()) { - _POPPLER_FREE(obj1); - _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "I"); - } - if (obj1.isBool()) - maskInterpolate = obj1.getBool(); - else - maskInterpolate = gFalse; - _POPPLER_FREE(obj1); + if (obj1.isNull()) { + _POPPLER_FREE(obj1); + _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "I"); + } + if (obj1.isBool()) + maskInterpolate = obj1.getBool(); + else + maskInterpolate = gFalse; + _POPPLER_FREE(obj1); maskInvert = gFalse; _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Decode"); if (obj1.isNull()) { @@ -2927,225 +2811,223 @@ void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg) _POPPLER_FREE(obj1); haveExplicitMask = gTrue; } - + // draw it if (haveSoftMask) { - builder->addSoftMaskedImage(state, str, width, height, colorMap, interpolate, - maskStr, maskWidth, maskHeight, maskColorMap, maskInterpolate); + builder->addSoftMaskedImage(state, str, width, height, colorMap, interpolate, maskStr, maskWidth, + maskHeight, maskColorMap, maskInterpolate); delete maskColorMap; } else if (haveExplicitMask) { - builder->addMaskedImage(state, str, width, height, colorMap, interpolate, - maskStr, maskWidth, maskHeight, maskInvert, maskInterpolate); + builder->addMaskedImage(state, str, width, height, colorMap, interpolate, maskStr, maskWidth, maskHeight, + maskInvert, maskInterpolate); } else { - builder->addImage(state, str, width, height, colorMap, interpolate, - haveColorKeyMask ? maskColors : static_cast(nullptr)); + builder->addImage(state, str, width, height, colorMap, interpolate, + haveColorKeyMask ? maskColors : static_cast(nullptr)); } delete colorMap; - + _POPPLER_FREE(maskObj); _POPPLER_FREE(smaskObj); } return; - err2: +err2: _POPPLER_FREE(obj1); - err1: +err1: error(errSyntaxError, getPos(), "Bad image parameters"); } -void PdfParser::doForm(Object *str) { - Dict *dict; - GBool transpGroup, isolated, knockout; - GfxColorSpace *blendingColorSpace; - Object matrixObj, bboxObj; - double m[6], bbox[4]; - Object resObj; - Dict *resDict; - Object obj1, obj2, obj3; - int i; +void PdfParser::doForm(Object *str) +{ + Dict *dict; + GBool transpGroup, isolated, knockout; + GfxColorSpace *blendingColorSpace; + Object matrixObj, bboxObj; + double m[6], bbox[4]; + Object resObj; + Dict *resDict; + Object obj1, obj2, obj3; + int i; - // check for excessive recursion - if (formDepth > 20) { - return; - } + // check for excessive recursion + if (formDepth > 20) { + return; + } - // get stream dict - dict = str->streamGetDict(); + // get stream dict + dict = str->streamGetDict(); - // check form type - _POPPLER_CALL_ARGS(obj1, dict->lookup, "FormType"); - if (!(obj1.isNull() || (obj1.isInt() && obj1.getInt() == 1))) { - error(errSyntaxError, getPos(), "Unknown form type"); - } - _POPPLER_FREE(obj1); + // check form type + _POPPLER_CALL_ARGS(obj1, dict->lookup, "FormType"); + if (!(obj1.isNull() || (obj1.isInt() && obj1.getInt() == 1))) { + error(errSyntaxError, getPos(), "Unknown form type"); + } + _POPPLER_FREE(obj1); - // get bounding box - _POPPLER_CALL_ARGS(bboxObj, dict->lookup, "BBox"); - if (!bboxObj.isArray()) { + // get bounding box + _POPPLER_CALL_ARGS(bboxObj, dict->lookup, "BBox"); + if (!bboxObj.isArray()) { + _POPPLER_FREE(bboxObj); + error(errSyntaxError, getPos(), "Bad form bounding box"); + return; + } + for (i = 0; i < 4; ++i) { + _POPPLER_CALL_ARGS(obj1, bboxObj.arrayGet, i); + bbox[i] = obj1.getNum(); + _POPPLER_FREE(obj1); + } _POPPLER_FREE(bboxObj); - error(errSyntaxError, getPos(), "Bad form bounding box"); - return; - } - for (i = 0; i < 4; ++i) { - _POPPLER_CALL_ARGS(obj1, bboxObj.arrayGet, i); - bbox[i] = obj1.getNum(); - _POPPLER_FREE(obj1); - } - _POPPLER_FREE(bboxObj); - // get matrix - _POPPLER_CALL_ARGS(matrixObj, dict->lookup, "Matrix"); - if (matrixObj.isArray()) { - for (i = 0; i < 6; ++i) { - _POPPLER_CALL_ARGS(obj1, matrixObj.arrayGet, i); - m[i] = obj1.getNum(); - _POPPLER_FREE(obj1); - } - } else { - m[0] = 1; m[1] = 0; - m[2] = 0; m[3] = 1; - m[4] = 0; m[5] = 0; - } - _POPPLER_FREE(matrixObj); - - // get resources - _POPPLER_CALL_ARGS(resObj, dict->lookup, "Resources"); - resDict = resObj.isDict() ? resObj.getDict() : (Dict *)nullptr; - - // check for a transparency group - transpGroup = isolated = knockout = gFalse; - blendingColorSpace = nullptr; - if (_POPPLER_CALL_ARGS_DEREF(obj1, dict->lookup, "Group").isDict()) { - if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "S").isName("Transparency")) { - transpGroup = gTrue; - if (!_POPPLER_CALL_ARGS_DEREF(obj3, obj1.dictLookup, "CS").isNull()) { + // get matrix + _POPPLER_CALL_ARGS(matrixObj, dict->lookup, "Matrix"); + if (matrixObj.isArray()) { + for (i = 0; i < 6; ++i) { + _POPPLER_CALL_ARGS(obj1, matrixObj.arrayGet, i); + m[i] = obj1.getNum(); + _POPPLER_FREE(obj1); + } + } else { + m[0] = 1; + m[1] = 0; + m[2] = 0; + m[3] = 1; + m[4] = 0; + m[5] = 0; + } + _POPPLER_FREE(matrixObj); + + // get resources + _POPPLER_CALL_ARGS(resObj, dict->lookup, "Resources"); + resDict = resObj.isDict() ? resObj.getDict() : (Dict *)nullptr; + + // check for a transparency group + transpGroup = isolated = knockout = gFalse; + blendingColorSpace = nullptr; + if (_POPPLER_CALL_ARGS_DEREF(obj1, dict->lookup, "Group").isDict()) { + if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "S").isName("Transparency")) { + transpGroup = gTrue; + if (!_POPPLER_CALL_ARGS_DEREF(obj3, obj1.dictLookup, "CS").isNull()) { #if defined(POPPLER_EVEN_NEWER_NEW_COLOR_SPACE_API) - blendingColorSpace = GfxColorSpace::parse(nullptr, &obj3, nullptr, nullptr); + blendingColorSpace = GfxColorSpace::parse(nullptr, &obj3, nullptr, nullptr); #elif defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API) - blendingColorSpace = GfxColorSpace::parse(&obj3, NULL, NULL); + blendingColorSpace = GfxColorSpace::parse(&obj3, NULL, NULL); #else - blendingColorSpace = GfxColorSpace::parse(&obj3, NULL); + blendingColorSpace = GfxColorSpace::parse(&obj3, NULL); #endif - } - _POPPLER_FREE(obj3); - if (_POPPLER_CALL_ARGS_DEREF(obj3, obj1.dictLookup, "I").isBool()) { - isolated = obj3.getBool(); - } - _POPPLER_FREE(obj3); - if (_POPPLER_CALL_ARGS_DEREF(obj3, obj1.dictLookup, "K").isBool()) { - knockout = obj3.getBool(); - } - _POPPLER_FREE(obj3); + } + _POPPLER_FREE(obj3); + if (_POPPLER_CALL_ARGS_DEREF(obj3, obj1.dictLookup, "I").isBool()) { + isolated = obj3.getBool(); + } + _POPPLER_FREE(obj3); + if (_POPPLER_CALL_ARGS_DEREF(obj3, obj1.dictLookup, "K").isBool()) { + knockout = obj3.getBool(); + } + _POPPLER_FREE(obj3); + } + _POPPLER_FREE(obj2); } - _POPPLER_FREE(obj2); - } - _POPPLER_FREE(obj1); - - // draw it - ++formDepth; - doForm1(str, resDict, m, bbox, - transpGroup, gFalse, blendingColorSpace, isolated, knockout); - --formDepth; - - if (blendingColorSpace) { - delete blendingColorSpace; - } - _POPPLER_FREE(resObj); -} - -void PdfParser::doForm1(Object *str, Dict *resDict, double *matrix, double *bbox, - GBool transpGroup, GBool softMask, - GfxColorSpace *blendingColorSpace, - GBool isolated, GBool knockout, - GBool alpha, Function *transferFunc, - GfxColor *backdropColor) { - Parser *oldParser; - double oldBaseMatrix[6]; - int i; - - // push new resources on stack - pushResources(resDict); - - // save current graphics state - saveState(); - - // kill any pre-existing path - state->clearPath(); - - if (softMask || transpGroup) { - builder->clearSoftMask(state); - builder->pushTransparencyGroup(state, bbox, blendingColorSpace, - isolated, knockout, softMask); - } - - // save current parser - oldParser = parser; - - // set form transformation matrix - state->concatCTM(matrix[0], matrix[1], matrix[2], - matrix[3], matrix[4], matrix[5]); - builder->setTransform(matrix[0], matrix[1], matrix[2], - matrix[3], matrix[4], matrix[5]); - - // set form bounding box - state->moveTo(bbox[0], bbox[1]); - state->lineTo(bbox[2], bbox[1]); - state->lineTo(bbox[2], bbox[3]); - state->lineTo(bbox[0], bbox[3]); - state->closePath(); - state->clip(); - clipHistory->setClip(state->getPath()); - builder->clip(state); - state->clearPath(); - - if (softMask || transpGroup) { - if (state->getBlendMode() != gfxBlendNormal) { - state->setBlendMode(gfxBlendNormal); - } - if (state->getFillOpacity() != 1) { - builder->setGroupOpacity(state->getFillOpacity()); - state->setFillOpacity(1); - } - if (state->getStrokeOpacity() != 1) { - state->setStrokeOpacity(1); - } - } - - // set new base matrix - for (i = 0; i < 6; ++i) { - oldBaseMatrix[i] = baseMatrix[i]; - baseMatrix[i] = state->getCTM()[i]; - } - - // draw the form - parse(str, gFalse); - - // restore base matrix - for (i = 0; i < 6; ++i) { - baseMatrix[i] = oldBaseMatrix[i]; - } - - // restore parser - parser = oldParser; - - if (softMask || transpGroup) { - builder->popTransparencyGroup(state); - } - - // restore graphics state - restoreState(); - - // pop resource stack - popResources(); - - if (softMask) { - builder->setSoftMask(state, bbox, alpha, transferFunc, backdropColor); - } else if (transpGroup) { - builder->paintTransparencyGroup(state, bbox); - } - - return; + _POPPLER_FREE(obj1); + + // draw it + ++formDepth; + doForm1(str, resDict, m, bbox, transpGroup, gFalse, blendingColorSpace, isolated, knockout); + --formDepth; + + if (blendingColorSpace) { + delete blendingColorSpace; + } + _POPPLER_FREE(resObj); +} + +void PdfParser::doForm1(Object *str, Dict *resDict, double *matrix, double *bbox, GBool transpGroup, GBool softMask, + GfxColorSpace *blendingColorSpace, GBool isolated, GBool knockout, GBool alpha, + Function *transferFunc, GfxColor *backdropColor) +{ + Parser *oldParser; + double oldBaseMatrix[6]; + int i; + + // push new resources on stack + pushResources(resDict); + + // save current graphics state + saveState(); + + // kill any pre-existing path + state->clearPath(); + + if (softMask || transpGroup) { + builder->clearSoftMask(state); + builder->pushTransparencyGroup(state, bbox, blendingColorSpace, isolated, knockout, softMask); + } + + // save current parser + oldParser = parser; + + // set form transformation matrix + state->concatCTM(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); + builder->setTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); + + // set form bounding box + state->moveTo(bbox[0], bbox[1]); + state->lineTo(bbox[2], bbox[1]); + state->lineTo(bbox[2], bbox[3]); + state->lineTo(bbox[0], bbox[3]); + state->closePath(); + state->clip(); + clipHistory->setClip(state->getPath()); + builder->clip(state); + state->clearPath(); + + if (softMask || transpGroup) { + if (state->getBlendMode() != gfxBlendNormal) { + state->setBlendMode(gfxBlendNormal); + } + if (state->getFillOpacity() != 1) { + builder->setGroupOpacity(state->getFillOpacity()); + state->setFillOpacity(1); + } + if (state->getStrokeOpacity() != 1) { + state->setStrokeOpacity(1); + } + } + + // set new base matrix + for (i = 0; i < 6; ++i) { + oldBaseMatrix[i] = baseMatrix[i]; + baseMatrix[i] = state->getCTM()[i]; + } + + // draw the form + parse(str, gFalse); + + // restore base matrix + for (i = 0; i < 6; ++i) { + baseMatrix[i] = oldBaseMatrix[i]; + } + + // restore parser + parser = oldParser; + + if (softMask || transpGroup) { + builder->popTransparencyGroup(state); + } + + // restore graphics state + restoreState(); + + // pop resource stack + popResources(); + + if (softMask) { + builder->setSoftMask(state, bbox, alpha, transferFunc, backdropColor); + } else if (transpGroup) { + builder->paintTransparencyGroup(state, bbox); + } + + return; } //------------------------------------------------------------------------ @@ -3154,94 +3036,91 @@ void PdfParser::doForm1(Object *str, Dict *resDict, double *matrix, double *bbox void PdfParser::opBeginImage(Object /*args*/[], int /*numArgs*/) { - // build dict/stream - Stream *str = buildImageStream(); + // build dict/stream + Stream *str = buildImageStream(); - // display the image - if (str) { - doImage(nullptr, str, gTrue); - - // skip 'EI' tag - int c1 = str->getUndecodedStream()->getChar(); - int c2 = str->getUndecodedStream()->getChar(); - while (!(c1 == 'E' && c2 == 'I') && c2 != EOF) { - c1 = c2; - c2 = str->getUndecodedStream()->getChar(); + // display the image + if (str) { + doImage(nullptr, str, gTrue); + + // skip 'EI' tag + int c1 = str->getUndecodedStream()->getChar(); + int c2 = str->getUndecodedStream()->getChar(); + while (!(c1 == 'E' && c2 == 'I') && c2 != EOF) { + c1 = c2; + c2 = str->getUndecodedStream()->getChar(); + } + delete str; } - delete str; - } } -Stream *PdfParser::buildImageStream() { - Object dict; - Object obj; - Stream *str; +Stream *PdfParser::buildImageStream() +{ + Object dict; + Object obj; + Stream *str; - // build dictionary + // build dictionary #if defined(POPPLER_NEW_OBJECT_API) - dict = Object(new Dict(xref)); + dict = Object(new Dict(xref)); #else - dict.initDict(xref); + dict.initDict(xref); #endif - _POPPLER_CALL(obj, parser->getObj); - while (!obj.isCmd(const_cast("ID")) && !obj.isEOF()) { - if (!obj.isName()) { - error(errSyntaxError, getPos(), "Inline image dictionary key must be a name object"); - _POPPLER_FREE(obj); - } else { - Object obj2; - _POPPLER_CALL(obj2, parser->getObj); - if (obj2.isEOF() || obj2.isError()) { + _POPPLER_CALL(obj, parser->getObj); + while (!obj.isCmd(const_cast("ID")) && !obj.isEOF()) { + if (!obj.isName()) { + error(errSyntaxError, getPos(), "Inline image dictionary key must be a name object"); + _POPPLER_FREE(obj); + } else { + Object obj2; + _POPPLER_CALL(obj2, parser->getObj); + if (obj2.isEOF() || obj2.isError()) { + _POPPLER_FREE(obj); + break; + } + _POPPLER_DICTADD(dict, obj.getName(), obj2); + _POPPLER_FREE(obj); + _POPPLER_FREE(obj2); + } + _POPPLER_CALL(obj, parser->getObj); + } + if (obj.isEOF()) { + error(errSyntaxError, getPos(), "End of file in inline image"); _POPPLER_FREE(obj); - break; - } - _POPPLER_DICTADD(dict, obj.getName(), obj2); - _POPPLER_FREE(obj); - _POPPLER_FREE(obj2); + _POPPLER_FREE(dict); + return nullptr; } - _POPPLER_CALL(obj, parser->getObj); - } - if (obj.isEOF()) { - error(errSyntaxError, getPos(), "End of file in inline image"); _POPPLER_FREE(obj); - _POPPLER_FREE(dict); - return nullptr; - } - _POPPLER_FREE(obj); - // make stream + // make stream #if defined(POPPLER_NEW_OBJECT_API) - str = new EmbedStream(parser->getStream(), dict.copy(), gFalse, 0); - str = str->addFilters(dict.getDict()); + str = new EmbedStream(parser->getStream(), dict.copy(), gFalse, 0); + str = str->addFilters(dict.getDict()); #else - str = new EmbedStream(parser->getStream(), &dict, gFalse, 0); - str = str->addFilters(&dict); + str = new EmbedStream(parser->getStream(), &dict, gFalse, 0); + str = str->addFilters(&dict); #endif - return str; + return str; } void PdfParser::opImageData(Object /*args*/[], int /*numArgs*/) { - error(errInternal, getPos(), "Internal: got 'ID' operator"); + error(errInternal, getPos(), "Internal: got 'ID' operator"); } void PdfParser::opEndImage(Object /*args*/[], int /*numArgs*/) { - error(errInternal, getPos(), "Internal: got 'EI' operator"); + error(errInternal, getPos(), "Internal: got 'EI' operator"); } //------------------------------------------------------------------------ // type 3 font operators //------------------------------------------------------------------------ -void PdfParser::opSetCharWidth(Object /*args*/[], int /*numArgs*/) -{ -} +void PdfParser::opSetCharWidth(Object /*args*/[], int /*numArgs*/) {} -void PdfParser::opSetCacheDevice(Object /*args*/[], int /*numArgs*/) -{ -} +void PdfParser::opSetCacheDevice(Object /*args*/[], int /*numArgs*/) {} //------------------------------------------------------------------------ // compatibility operators @@ -3249,135 +3128,140 @@ void PdfParser::opSetCacheDevice(Object /*args*/[], int /*numArgs*/) void PdfParser::opBeginIgnoreUndef(Object /*args*/[], int /*numArgs*/) { - ++ignoreUndef; + ++ignoreUndef; } void PdfParser::opEndIgnoreUndef(Object /*args*/[], int /*numArgs*/) { - if (ignoreUndef > 0) - --ignoreUndef; + if (ignoreUndef > 0) + --ignoreUndef; } //------------------------------------------------------------------------ // marked content operators //------------------------------------------------------------------------ -void PdfParser::opBeginMarkedContent(Object args[], int numArgs) { - if (printCommands) { - printf(" marked content: %s ", args[0].getName()); - if (numArgs == 2) - args[2].print(stdout); - printf("\n"); - fflush(stdout); - } +void PdfParser::opBeginMarkedContent(Object args[], int numArgs) +{ + if (printCommands) { + printf(" marked content: %s ", args[0].getName()); + if (numArgs == 2) + args[2].print(stdout); + printf("\n"); + fflush(stdout); + } - if(numArgs == 2) { - //out->beginMarkedContent(args[0].getName(),args[1].getDict()); - } else { - //out->beginMarkedContent(args[0].getName()); - } + if (numArgs == 2) { + // out->beginMarkedContent(args[0].getName(),args[1].getDict()); + } else { + // out->beginMarkedContent(args[0].getName()); + } } void PdfParser::opEndMarkedContent(Object /*args*/[], int /*numArgs*/) { - //out->endMarkedContent(); + // out->endMarkedContent(); } -void PdfParser::opMarkPoint(Object args[], int numArgs) { - if (printCommands) { - printf(" mark point: %s ", args[0].getName()); - if (numArgs == 2) - args[2].print(stdout); - printf("\n"); - fflush(stdout); - } - - if(numArgs == 2) { - //out->markPoint(args[0].getName(),args[1].getDict()); - } else { - //out->markPoint(args[0].getName()); - } +void PdfParser::opMarkPoint(Object args[], int numArgs) +{ + if (printCommands) { + printf(" mark point: %s ", args[0].getName()); + if (numArgs == 2) + args[2].print(stdout); + printf("\n"); + fflush(stdout); + } + if (numArgs == 2) { + // out->markPoint(args[0].getName(),args[1].getDict()); + } else { + // out->markPoint(args[0].getName()); + } } //------------------------------------------------------------------------ // misc //------------------------------------------------------------------------ -void PdfParser::saveState() { - bool is_radial = false; +void PdfParser::saveState() +{ + bool is_radial = false; - GfxPattern *pattern = state->getFillPattern(); - if (pattern != nullptr) - if (pattern->getType() == 2 ) { - GfxShadingPattern *shading_pattern = static_cast(pattern); - GfxShading *shading = shading_pattern->getShading(); - if (shading->getType() == 3) - is_radial = true; - } + GfxPattern *pattern = state->getFillPattern(); + if (pattern != nullptr) + if (pattern->getType() == 2) { + GfxShadingPattern *shading_pattern = static_cast(pattern); + GfxShading *shading = shading_pattern->getShading(); + if (shading->getType() == 3) + is_radial = true; + } - builder->saveState(); - if (is_radial) - state->save(); // nasty hack to prevent GfxRadialShading from getting corrupted during copy operation - else - state = state->save(); // see LP Bug 919176 comment 8 - clipHistory = clipHistory->save(); + builder->saveState(); + if (is_radial) + state->save(); // nasty hack to prevent GfxRadialShading from getting corrupted during copy operation + else + state = state->save(); // see LP Bug 919176 comment 8 + clipHistory = clipHistory->save(); } -void PdfParser::restoreState() { - clipHistory = clipHistory->restore(); - state = state->restore(); - builder->restoreState(); +void PdfParser::restoreState() +{ + clipHistory = clipHistory->restore(); + state = state->restore(); + builder->restoreState(); } -void PdfParser::pushResources(Dict *resDict) { - res = new GfxResources(xref, resDict, res); +void PdfParser::pushResources(Dict *resDict) +{ + res = new GfxResources(xref, resDict, res); } -void PdfParser::popResources() { - GfxResources *resPtr; +void PdfParser::popResources() +{ + GfxResources *resPtr; - resPtr = res->getNext(); - delete res; - res = resPtr; + resPtr = res->getNext(); + delete res; + res = resPtr; } -void PdfParser::setDefaultApproximationPrecision() { - for (int i = 1; i <= pdfNumShadingTypes; ++i) { - setApproximationPrecision(i, defaultShadingColorDelta, defaultShadingMaxDepth); - } +void PdfParser::setDefaultApproximationPrecision() +{ + for (int i = 1; i <= pdfNumShadingTypes; ++i) { + setApproximationPrecision(i, defaultShadingColorDelta, defaultShadingMaxDepth); + } } -void PdfParser::setApproximationPrecision(int shadingType, double colorDelta, - int maxDepth) { - - if (shadingType > pdfNumShadingTypes || shadingType < 1) { - return; - } - colorDeltas[shadingType-1] = dblToCol(colorDelta); - maxDepths[shadingType-1] = maxDepth; +void PdfParser::setApproximationPrecision(int shadingType, double colorDelta, int maxDepth) +{ + if (shadingType > pdfNumShadingTypes || shadingType < 1) { + return; + } + colorDeltas[shadingType - 1] = dblToCol(colorDelta); + maxDepths[shadingType - 1] = maxDepth; } //------------------------------------------------------------------------ // ClipHistoryEntry //------------------------------------------------------------------------ -ClipHistoryEntry::ClipHistoryEntry(GfxPath *clipPathA, GfxClipType clipTypeA) : - saved(nullptr), - clipPath((clipPathA) ? clipPathA->copy() : nullptr), - clipType(clipTypeA) -{ -} +ClipHistoryEntry::ClipHistoryEntry(GfxPath *clipPathA, GfxClipType clipTypeA) + : saved(nullptr) + , clipPath((clipPathA) ? clipPathA->copy() : nullptr) + , clipType(clipTypeA) +{} ClipHistoryEntry::~ClipHistoryEntry() { if (clipPath) { delete clipPath; - clipPath = nullptr; + clipPath = nullptr; } } -void ClipHistoryEntry::setClip(_POPPLER_CONST_83 GfxPath *clipPathA, GfxClipType clipTypeA) { +void ClipHistoryEntry::setClip(_POPPLER_CONST_83 GfxPath *clipPathA, GfxClipType clipTypeA) +{ // Free previous clip path if (clipPath) { delete clipPath; @@ -3387,18 +3271,20 @@ void ClipHistoryEntry::setClip(_POPPLER_CONST_83 GfxPath *clipPathA, GfxClipType clipType = clipTypeA; } else { clipPath = nullptr; - clipType = clipNormal; + clipType = clipNormal; } } -ClipHistoryEntry *ClipHistoryEntry::save() { +ClipHistoryEntry *ClipHistoryEntry::save() +{ ClipHistoryEntry *newEntry = new ClipHistoryEntry(this); newEntry->saved = this; return newEntry; } -ClipHistoryEntry *ClipHistoryEntry::restore() { +ClipHistoryEntry *ClipHistoryEntry::restore() +{ ClipHistoryEntry *oldEntry; if (saved) { @@ -3412,13 +3298,14 @@ ClipHistoryEntry *ClipHistoryEntry::restore() { return oldEntry; } -ClipHistoryEntry::ClipHistoryEntry(ClipHistoryEntry *other) { +ClipHistoryEntry::ClipHistoryEntry(ClipHistoryEntry *other) +{ if (other->clipPath) { this->clipPath = other->clipPath->copy(); this->clipType = other->clipType; } else { this->clipPath = nullptr; - this->clipType = clipNormal; + this->clipType = clipNormal; } saved = nullptr; } diff --git a/src/extension/internal/pdfinput/pdf-parser.h b/src/extension/internal/pdfinput/pdf-parser.h index 31c84d51bb8b5db9e48606cefd648131662a04d5..cabb1b0ec68573d980baa5d56ee28d7ee0f3ca71 100644 --- a/src/extension/internal/pdfinput/pdf-parser.h +++ b/src/extension/internal/pdfinput/pdf-parser.h @@ -15,7 +15,7 @@ #define PDF_PARSER_H #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef HAVE_POPPLER @@ -26,18 +26,18 @@ #endif namespace Inkscape { - namespace Extension { - namespace Internal { - class SvgBuilder; - } - } +namespace Extension { +namespace Internal { +class SvgBuilder; } +} // namespace Extension +} // namespace Inkscape // TODO clean up and remove using: using Inkscape::Extension::Internal::SvgBuilder; -#include "glib/poppler-features.h" #include "Object.h" +#include "glib/poppler-features.h" class GooString; class XRef; @@ -74,28 +74,31 @@ class ClipHistoryEntry; //------------------------------------------------------------------------ #ifndef GFX_H -enum GfxClipType { +enum GfxClipType +{ clipNone, clipNormal, clipEO }; -enum TchkType { - tchkBool, // boolean - tchkInt, // integer - tchkNum, // number (integer or real) - tchkString, // string - tchkName, // name - tchkArray, // array - tchkProps, // properties (dictionary or name) - tchkSCN, // scn/SCN args (number of name) - tchkNone // used to avoid empty initializer lists +enum TchkType +{ + tchkBool, // boolean + tchkInt, // integer + tchkNum, // number (integer or real) + tchkString, // string + tchkName, // name + tchkArray, // array + tchkProps, // properties (dictionary or name) + tchkSCN, // scn/SCN args (number of name) + tchkNone // used to avoid empty initializer lists }; #endif /* GFX_H */ #define maxOperatorArgs 33 -struct PdfOperator { +struct PdfOperator +{ char name[4]; int numArgs; TchkType tchk[maxOperatorArgs]; @@ -104,13 +107,14 @@ struct PdfOperator { #undef maxOperatorArgs -struct OpHistoryEntry { - const char *name; // operator's name - GfxState *state; // saved state, NULL if none - GBool executed; // whether the operator has been executed +struct OpHistoryEntry +{ + const char *name; // operator's name + GfxState *state; // saved state, NULL if none + GBool executed; // whether the operator has been executed - OpHistoryEntry *next; // next entry on stack - unsigned depth; // total number of entries descending from this + OpHistoryEntry *next; // next entry on stack + unsigned depth; // total number of entries descending from this }; //------------------------------------------------------------------------ @@ -121,225 +125,209 @@ struct OpHistoryEntry { // constants //------------------------------------------------------------------------ -#define pdfFunctionShading 1 -#define pdfAxialShading 2 -#define pdfRadialShading 3 -#define pdfGouraudTriangleShading 4 +#define pdfFunctionShading 1 +#define pdfAxialShading 2 +#define pdfRadialShading 3 +#define pdfGouraudTriangleShading 4 #define pdfPatchMeshShading 5 #define pdfNumShadingTypes 5 - - /** * PDF parsing module using libpoppler's facilities. */ -class PdfParser { +class PdfParser +{ public: + // Constructor for regular output. + PdfParser(XRef *xrefA, SvgBuilder *builderA, int pageNum, int rotate, Dict *resDict, + _POPPLER_CONST PDFRectangle *box, _POPPLER_CONST PDFRectangle *cropBox); - // Constructor for regular output. - PdfParser(XRef *xrefA, SvgBuilder *builderA, int pageNum, int rotate, - Dict *resDict, - _POPPLER_CONST PDFRectangle *box, - _POPPLER_CONST PDFRectangle *cropBox); + // Constructor for a sub-page object. + PdfParser(XRef *xrefA, Inkscape::Extension::Internal::SvgBuilder *builderA, Dict *resDict, + _POPPLER_CONST PDFRectangle *box); - // Constructor for a sub-page object. - PdfParser(XRef *xrefA, Inkscape::Extension::Internal::SvgBuilder *builderA, - Dict *resDict, - _POPPLER_CONST PDFRectangle *box); + virtual ~PdfParser(); - virtual ~PdfParser(); + // Interpret a stream or array of streams. + void parse(Object *obj, GBool topLevel = gTrue); - // Interpret a stream or array of streams. - void parse(Object *obj, GBool topLevel = gTrue); + // Save graphics state. + void saveState(); - // Save graphics state. - void saveState(); + // Restore graphics state. + void restoreState(); - // Restore graphics state. - void restoreState(); + // Get the current graphics state object. + GfxState *getState() { return state; } - // Get the current graphics state object. - GfxState *getState() { return state; } - - // Set the precision of approximation for specific shading fills. - void setApproximationPrecision(int shadingType, double colorDelta, int maxDepth); + // Set the precision of approximation for specific shading fills. + void setApproximationPrecision(int shadingType, double colorDelta, int maxDepth); private: - - XRef *xref; // the xref table for this PDF file - SvgBuilder *builder; // SVG generator - GBool subPage; // is this a sub-page object? - GBool printCommands; // print the drawing commands (for debugging) - GfxResources *res; // resource stack - - GfxState *state; // current graphics state - GBool fontChanged; // set if font or text matrix has changed - GfxClipType clip; // do a clip? - int ignoreUndef; // current BX/EX nesting level - double baseMatrix[6]; // default matrix for most recent - // page/form/pattern - int formDepth; - - Parser *parser; // parser for page content stream(s) - - static PdfOperator opTab[]; // table of operators - - int colorDeltas[pdfNumShadingTypes]; - // max deltas allowed in any color component - // for the approximation of shading fills - int maxDepths[pdfNumShadingTypes]; // max recursive depths - - ClipHistoryEntry *clipHistory; // clip path stack - OpHistoryEntry *operatorHistory; // list containing the last N operators - - void setDefaultApproximationPrecision(); // init color deltas - void pushOperator(const char *name); - OpHistoryEntry *popOperator(); - const char *getPreviousOperator(unsigned int look_back=1); // returns the nth previous operator's name - - void go(GBool topLevel); - void execOp(Object *cmd, Object args[], int numArgs); - PdfOperator *findOp(const char *name); - GBool checkArg(Object *arg, TchkType type); - int getPos(); - - // graphics state operators - void opSave(Object args[], int numArgs); - void opRestore(Object args[], int numArgs); - void opConcat(Object args[], int numArgs); - void opSetDash(Object args[], int numArgs); - void opSetFlat(Object args[], int numArgs); - void opSetLineJoin(Object args[], int numArgs); - void opSetLineCap(Object args[], int numArgs); - void opSetMiterLimit(Object args[], int numArgs); - void opSetLineWidth(Object args[], int numArgs); - void opSetExtGState(Object args[], int numArgs); - void doSoftMask(Object *str, GBool alpha, - GfxColorSpace *blendingColorSpace, - GBool isolated, GBool knockout, - Function *transferFunc, GfxColor *backdropColor); - void opSetRenderingIntent(Object args[], int numArgs); - - // color operators - void opSetFillGray(Object args[], int numArgs); - void opSetStrokeGray(Object args[], int numArgs); - void opSetFillCMYKColor(Object args[], int numArgs); - void opSetStrokeCMYKColor(Object args[], int numArgs); - void opSetFillRGBColor(Object args[], int numArgs); - void opSetStrokeRGBColor(Object args[], int numArgs); - void opSetFillColorSpace(Object args[], int numArgs); - void opSetStrokeColorSpace(Object args[], int numArgs); - void opSetFillColor(Object args[], int numArgs); - void opSetStrokeColor(Object args[], int numArgs); - void opSetFillColorN(Object args[], int numArgs); - void opSetStrokeColorN(Object args[], int numArgs); - - // path segment operators - void opMoveTo(Object args[], int numArgs); - void opLineTo(Object args[], int numArgs); - void opCurveTo(Object args[], int numArgs); - void opCurveTo1(Object args[], int numArgs); - void opCurveTo2(Object args[], int numArgs); - void opRectangle(Object args[], int numArgs); - void opClosePath(Object args[], int numArgs); - - // path painting operators - void opEndPath(Object args[], int numArgs); - void opStroke(Object args[], int numArgs); - void opCloseStroke(Object args[], int numArgs); - void opFill(Object args[], int numArgs); - void opEOFill(Object args[], int numArgs); - void opFillStroke(Object args[], int numArgs); - void opCloseFillStroke(Object args[], int numArgs); - void opEOFillStroke(Object args[], int numArgs); - void opCloseEOFillStroke(Object args[], int numArgs); - void doFillAndStroke(GBool eoFill); - void doPatternFillFallback(GBool eoFill); - void doPatternStrokeFallback(); - void doShadingPatternFillFallback(GfxShadingPattern *sPat, - GBool stroke, GBool eoFill); - void opShFill(Object args[], int numArgs); - void doFunctionShFill(GfxFunctionShading *shading); - void doFunctionShFill1(GfxFunctionShading *shading, - double x0, double y0, - double x1, double y1, - GfxColor *colors, int depth); - void doGouraudTriangleShFill(GfxGouraudTriangleShading *shading); - void gouraudFillTriangle(double x0, double y0, GfxColor *color0, - double x1, double y1, GfxColor *color1, - double x2, double y2, GfxColor *color2, - int nComps, int depth); - void doPatchMeshShFill(GfxPatchMeshShading *shading); - void fillPatch(_POPPLER_CONST GfxPatch *patch, int nComps, int depth); - void doEndPath(); - - // path clipping operators - void opClip(Object args[], int numArgs); - void opEOClip(Object args[], int numArgs); - - // text object operators - void opBeginText(Object args[], int numArgs); - void opEndText(Object args[], int numArgs); - - // text state operators - void opSetCharSpacing(Object args[], int numArgs); - void opSetFont(Object args[], int numArgs); - void opSetTextLeading(Object args[], int numArgs); - void opSetTextRender(Object args[], int numArgs); - void opSetTextRise(Object args[], int numArgs); - void opSetWordSpacing(Object args[], int numArgs); - void opSetHorizScaling(Object args[], int numArgs); - - // text positioning operators - void opTextMove(Object args[], int numArgs); - void opTextMoveSet(Object args[], int numArgs); - void opSetTextMatrix(Object args[], int numArgs); - void opTextNextLine(Object args[], int numArgs); - - // text string operators - void opShowText(Object args[], int numArgs); - void opMoveShowText(Object args[], int numArgs); - void opMoveSetShowText(Object args[], int numArgs); - void opShowSpaceText(Object args[], int numArgs); -#if POPPLER_CHECK_VERSION(0,64,0) - void doShowText(const GooString *s); + XRef *xref; // the xref table for this PDF file + SvgBuilder *builder; // SVG generator + GBool subPage; // is this a sub-page object? + GBool printCommands; // print the drawing commands (for debugging) + GfxResources *res; // resource stack + + GfxState *state; // current graphics state + GBool fontChanged; // set if font or text matrix has changed + GfxClipType clip; // do a clip? + int ignoreUndef; // current BX/EX nesting level + double baseMatrix[6]; // default matrix for most recent + // page/form/pattern + int formDepth; + + Parser *parser; // parser for page content stream(s) + + static PdfOperator opTab[]; // table of operators + + int colorDeltas[pdfNumShadingTypes]; + // max deltas allowed in any color component + // for the approximation of shading fills + int maxDepths[pdfNumShadingTypes]; // max recursive depths + + ClipHistoryEntry *clipHistory; // clip path stack + OpHistoryEntry *operatorHistory; // list containing the last N operators + + void setDefaultApproximationPrecision(); // init color deltas + void pushOperator(const char *name); + OpHistoryEntry *popOperator(); + const char *getPreviousOperator(unsigned int look_back = 1); // returns the nth previous operator's name + + void go(GBool topLevel); + void execOp(Object *cmd, Object args[], int numArgs); + PdfOperator *findOp(const char *name); + GBool checkArg(Object *arg, TchkType type); + int getPos(); + + // graphics state operators + void opSave(Object args[], int numArgs); + void opRestore(Object args[], int numArgs); + void opConcat(Object args[], int numArgs); + void opSetDash(Object args[], int numArgs); + void opSetFlat(Object args[], int numArgs); + void opSetLineJoin(Object args[], int numArgs); + void opSetLineCap(Object args[], int numArgs); + void opSetMiterLimit(Object args[], int numArgs); + void opSetLineWidth(Object args[], int numArgs); + void opSetExtGState(Object args[], int numArgs); + void doSoftMask(Object *str, GBool alpha, GfxColorSpace *blendingColorSpace, GBool isolated, GBool knockout, + Function *transferFunc, GfxColor *backdropColor); + void opSetRenderingIntent(Object args[], int numArgs); + + // color operators + void opSetFillGray(Object args[], int numArgs); + void opSetStrokeGray(Object args[], int numArgs); + void opSetFillCMYKColor(Object args[], int numArgs); + void opSetStrokeCMYKColor(Object args[], int numArgs); + void opSetFillRGBColor(Object args[], int numArgs); + void opSetStrokeRGBColor(Object args[], int numArgs); + void opSetFillColorSpace(Object args[], int numArgs); + void opSetStrokeColorSpace(Object args[], int numArgs); + void opSetFillColor(Object args[], int numArgs); + void opSetStrokeColor(Object args[], int numArgs); + void opSetFillColorN(Object args[], int numArgs); + void opSetStrokeColorN(Object args[], int numArgs); + + // path segment operators + void opMoveTo(Object args[], int numArgs); + void opLineTo(Object args[], int numArgs); + void opCurveTo(Object args[], int numArgs); + void opCurveTo1(Object args[], int numArgs); + void opCurveTo2(Object args[], int numArgs); + void opRectangle(Object args[], int numArgs); + void opClosePath(Object args[], int numArgs); + + // path painting operators + void opEndPath(Object args[], int numArgs); + void opStroke(Object args[], int numArgs); + void opCloseStroke(Object args[], int numArgs); + void opFill(Object args[], int numArgs); + void opEOFill(Object args[], int numArgs); + void opFillStroke(Object args[], int numArgs); + void opCloseFillStroke(Object args[], int numArgs); + void opEOFillStroke(Object args[], int numArgs); + void opCloseEOFillStroke(Object args[], int numArgs); + void doFillAndStroke(GBool eoFill); + void doPatternFillFallback(GBool eoFill); + void doPatternStrokeFallback(); + void doShadingPatternFillFallback(GfxShadingPattern *sPat, GBool stroke, GBool eoFill); + void opShFill(Object args[], int numArgs); + void doFunctionShFill(GfxFunctionShading *shading); + void doFunctionShFill1(GfxFunctionShading *shading, double x0, double y0, double x1, double y1, GfxColor *colors, + int depth); + void doGouraudTriangleShFill(GfxGouraudTriangleShading *shading); + void gouraudFillTriangle(double x0, double y0, GfxColor *color0, double x1, double y1, GfxColor *color1, double x2, + double y2, GfxColor *color2, int nComps, int depth); + void doPatchMeshShFill(GfxPatchMeshShading *shading); + void fillPatch(_POPPLER_CONST GfxPatch *patch, int nComps, int depth); + void doEndPath(); + + // path clipping operators + void opClip(Object args[], int numArgs); + void opEOClip(Object args[], int numArgs); + + // text object operators + void opBeginText(Object args[], int numArgs); + void opEndText(Object args[], int numArgs); + + // text state operators + void opSetCharSpacing(Object args[], int numArgs); + void opSetFont(Object args[], int numArgs); + void opSetTextLeading(Object args[], int numArgs); + void opSetTextRender(Object args[], int numArgs); + void opSetTextRise(Object args[], int numArgs); + void opSetWordSpacing(Object args[], int numArgs); + void opSetHorizScaling(Object args[], int numArgs); + + // text positioning operators + void opTextMove(Object args[], int numArgs); + void opTextMoveSet(Object args[], int numArgs); + void opSetTextMatrix(Object args[], int numArgs); + void opTextNextLine(Object args[], int numArgs); + + // text string operators + void opShowText(Object args[], int numArgs); + void opMoveShowText(Object args[], int numArgs); + void opMoveSetShowText(Object args[], int numArgs); + void opShowSpaceText(Object args[], int numArgs); +#if POPPLER_CHECK_VERSION(0, 64, 0) + void doShowText(const GooString *s); #else - void doShowText(GooString *s); + void doShowText(GooString *s); #endif - - - // XObject operators - void opXObject(Object args[], int numArgs); - void doImage(Object *ref, Stream *str, GBool inlineImg); - void doForm(Object *str); - void doForm1(Object *str, Dict *resDict, double *matrix, double *bbox, - GBool transpGroup = gFalse, GBool softMask = gFalse, - GfxColorSpace *blendingColorSpace = nullptr, - GBool isolated = gFalse, GBool knockout = gFalse, - GBool alpha = gFalse, Function *transferFunc = nullptr, - GfxColor *backdropColor = nullptr); - - // in-line image operators - void opBeginImage(Object args[], int numArgs); - Stream *buildImageStream(); - void opImageData(Object args[], int numArgs); - void opEndImage(Object args[], int numArgs); - - // type 3 font operators - void opSetCharWidth(Object args[], int numArgs); - void opSetCacheDevice(Object args[], int numArgs); - - // compatibility operators - void opBeginIgnoreUndef(Object args[], int numArgs); - void opEndIgnoreUndef(Object args[], int numArgs); - - // marked content operators - void opBeginMarkedContent(Object args[], int numArgs); - void opEndMarkedContent(Object args[], int numArgs); - void opMarkPoint(Object args[], int numArgs); - - void pushResources(Dict *resDict); - void popResources(); + + // XObject operators + void opXObject(Object args[], int numArgs); + void doImage(Object *ref, Stream *str, GBool inlineImg); + void doForm(Object *str); + void doForm1(Object *str, Dict *resDict, double *matrix, double *bbox, GBool transpGroup = gFalse, + GBool softMask = gFalse, GfxColorSpace *blendingColorSpace = nullptr, GBool isolated = gFalse, + GBool knockout = gFalse, GBool alpha = gFalse, Function *transferFunc = nullptr, + GfxColor *backdropColor = nullptr); + + // in-line image operators + void opBeginImage(Object args[], int numArgs); + Stream *buildImageStream(); + void opImageData(Object args[], int numArgs); + void opEndImage(Object args[], int numArgs); + + // type 3 font operators + void opSetCharWidth(Object args[], int numArgs); + void opSetCacheDevice(Object args[], int numArgs); + + // compatibility operators + void opBeginIgnoreUndef(Object args[], int numArgs); + void opEndIgnoreUndef(Object args[], int numArgs); + + // marked content operators + void opBeginMarkedContent(Object args[], int numArgs); + void opEndMarkedContent(Object args[], int numArgs); + void opMarkPoint(Object args[], int numArgs); + + void pushResources(Dict *resDict); + void popResources(); }; #endif /* HAVE_POPPLER */ diff --git a/src/extension/internal/pdfinput/poppler-transition-api.h b/src/extension/internal/pdfinput/poppler-transition-api.h index 96718118db947de5580d2ecbccbd94fe351c3c7a..8bffbecc12f76232ec7285725a6c15e5cc32ab45 100644 --- a/src/extension/internal/pdfinput/poppler-transition-api.h +++ b/src/extension/internal/pdfinput/poppler-transition-api.h @@ -38,32 +38,31 @@ #define _POPPLER_NEW_GLOBAL_PARAMS(args...) new GlobalParams(args) #endif - #if POPPLER_CHECK_VERSION(0, 72, 0) #define getCString c_str #endif -#if POPPLER_CHECK_VERSION(0,71,0) +#if POPPLER_CHECK_VERSION(0, 71, 0) typedef bool GBool; #define gTrue true #define gFalse false #endif -#if POPPLER_CHECK_VERSION(0,70,0) +#if POPPLER_CHECK_VERSION(0, 70, 0) #define _POPPLER_CONST const #else #define _POPPLER_CONST #endif -#if POPPLER_CHECK_VERSION(0,69,0) +#if POPPLER_CHECK_VERSION(0, 69, 0) #define _POPPLER_DICTADD(dict, key, obj) (dict).dictAdd(key, std::move(obj)) -#elif POPPLER_CHECK_VERSION(0,58,0) +#elif POPPLER_CHECK_VERSION(0, 58, 0) #define _POPPLER_DICTADD(dict, key, obj) (dict).dictAdd(copyString(key), std::move(obj)) #else #define _POPPLER_DICTADD(dict, key, obj) (dict).dictAdd(copyString(key), &obj) #endif -#if POPPLER_CHECK_VERSION(0,58,0) +#if POPPLER_CHECK_VERSION(0, 58, 0) #define POPPLER_NEW_OBJECT_API #define _POPPLER_FREE(obj) #define _POPPLER_CALL(ret, func) (ret = func()) diff --git a/src/extension/internal/pdfinput/svg-builder.cpp b/src/extension/internal/pdfinput/svg-builder.cpp index 1abe590fd22519a076e6df71caa6ac5614e27168..2127f1b86128212b3ef64779b8f91864cd9d1493 100644 --- a/src/extension/internal/pdfinput/svg-builder.cpp +++ b/src/extension/internal/pdfinput/svg-builder.cpp @@ -13,39 +13,36 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include +#include #ifdef HAVE_POPPLER -#include "svg-builder.h" -#include "pdf-parser.h" - +#include "Function.h" +#include "GfxFont.h" +#include "GfxState.h" +#include "GlobalParams.h" +#include "Page.h" +#include "Stream.h" +#include "UnicodeMap.h" +#include "color.h" +#include "display/nr-filter-utils.h" #include "document.h" +#include "libnrtype/font-instance.h" +#include "object/sp-defs.h" +#include "pdf-parser.h" #include "png.h" - -#include "xml/document.h" -#include "xml/node.h" -#include "xml/repr.h" -#include "svg/svg.h" -#include "svg/path-string.h" +#include "svg-builder.h" #include "svg/css-ostringstream.h" +#include "svg/path-string.h" #include "svg/svg-color.h" -#include "color.h" +#include "svg/svg.h" #include "util/units.h" -#include "display/nr-filter-utils.h" -#include "libnrtype/font-instance.h" -#include "object/sp-defs.h" - -#include "Function.h" -#include "GfxState.h" -#include "GfxFont.h" -#include "Stream.h" -#include "Page.h" -#include "UnicodeMap.h" -#include "GlobalParams.h" +#include "xml/document.h" +#include "xml/node.h" +#include "xml/repr.h" namespace Inkscape { namespace Extension { @@ -60,7 +57,8 @@ namespace Internal { * \struct SvgTransparencyGroup * \brief Holds information about a PDF transparency group */ -struct SvgTransparencyGroup { +struct SvgTransparencyGroup +{ double bbox[6]; // TODO should this be 4? Inkscape::XML::Node *container; @@ -73,7 +71,7 @@ struct SvgTransparencyGroup { /** * \class SvgBuilder - * + * */ SvgBuilder::SvgBuilder(SPDocument *document, gchar *docname, XRef *xref) @@ -93,7 +91,8 @@ SvgBuilder::SvgBuilder(SPDocument *document, gchar *docname, XRef *xref) _preferences->setAttribute("localFonts", "1"); } -SvgBuilder::SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root) { +SvgBuilder::SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root) +{ _is_top_level = false; _doc = parent->_doc; _docname = parent->_docname; @@ -106,7 +105,8 @@ SvgBuilder::SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root) { SvgBuilder::~SvgBuilder() = default; -void SvgBuilder::_init() { +void SvgBuilder::_init() +{ _font_style = nullptr; _current_font = nullptr; _font_specification = nullptr; @@ -121,7 +121,7 @@ void SvgBuilder::_init() { // Fill _availableFontNames (Bug LP #179589) (code cfr. FontLister) std::vector families; font_factory::Default()->GetUIFamilies(families); - for (auto & familie : families) { + for (auto &familie : families) { _availableFontNames.emplace_back(pango_font_family_get_name(familie)); } @@ -132,11 +132,17 @@ void SvgBuilder::_init() { _state_stack.push_back(initial_state); _node_stack.push_back(_container); - _ttm[0] = 1; _ttm[1] = 0; _ttm[2] = 0; _ttm[3] = 1; _ttm[4] = 0; _ttm[5] = 0; + _ttm[0] = 1; + _ttm[1] = 0; + _ttm[2] = 0; + _ttm[3] = 1; + _ttm[4] = 0; + _ttm[5] = 0; _ttm_is_set = false; } -void SvgBuilder::setDocumentSize(double width, double height) { +void SvgBuilder::setDocumentSize(double width, double height) +{ sp_repr_set_svg_double(_root, "width", width); sp_repr_set_svg_double(_root, "height", height); this->_width = width; @@ -146,7 +152,8 @@ void SvgBuilder::setDocumentSize(double width, double height) { /** * \brief Sets groupmode of the current container to 'layer' and sets its label if given */ -void SvgBuilder::setAsLayer(char *layer_name) { +void SvgBuilder::setAsLayer(char *layer_name) +{ _container->setAttribute("inkscape:groupmode", "layer"); if (layer_name) { _container->setAttribute("inkscape:label", layer_name); @@ -156,11 +163,13 @@ void SvgBuilder::setAsLayer(char *layer_name) { /** * \brief Sets the current container's opacity */ -void SvgBuilder::setGroupOpacity(double opacity) { +void SvgBuilder::setGroupOpacity(double opacity) +{ sp_repr_set_svg_double(_container, "opacity", CLAMP(opacity, 0.0, 1.0)); } -void SvgBuilder::saveState() { +void SvgBuilder::saveState() +{ SvgGraphicsState new_state; new_state.group_depth = 0; new_state.softmask = _state_stack.back().softmask; @@ -168,26 +177,29 @@ void SvgBuilder::saveState() { pushGroup(); } -void SvgBuilder::restoreState() { - while( _state_stack.back().group_depth > 0 ) { +void SvgBuilder::restoreState() +{ + while (_state_stack.back().group_depth > 0) { popGroup(); } _state_stack.pop_back(); } -Inkscape::XML::Node *SvgBuilder::pushNode(const char *name) { +Inkscape::XML::Node *SvgBuilder::pushNode(const char *name) +{ Inkscape::XML::Node *node = _xml_doc->createElement(name); _node_stack.push_back(node); _container = node; return node; } -Inkscape::XML::Node *SvgBuilder::popNode() { +Inkscape::XML::Node *SvgBuilder::popNode() +{ Inkscape::XML::Node *node = nullptr; - if ( _node_stack.size() > 1 ) { + if (_node_stack.size() > 1) { node = _node_stack.back(); _node_stack.pop_back(); - _container = _node_stack.back(); // Re-set container + _container = _node_stack.back(); // Re-set container } else { TRACE(("popNode() called when stack is empty\n")); node = _root; @@ -195,16 +207,17 @@ Inkscape::XML::Node *SvgBuilder::popNode() { return node; } -Inkscape::XML::Node *SvgBuilder::pushGroup() { +Inkscape::XML::Node *SvgBuilder::pushGroup() +{ Inkscape::XML::Node *saved_container = _container; Inkscape::XML::Node *node = pushNode("svg:g"); saved_container->appendChild(node); Inkscape::GC::release(node); _state_stack.back().group_depth++; // Set as a layer if this is a top-level group - if ( _container->parent() == _root && _is_top_level ) { + if (_container->parent() == _root && _is_top_level) { static int layer_count = 1; - if ( layer_count > 1 ) { + if (layer_count > 1) { gchar *layer_name = g_strdup_printf("%s%d", _docname, layer_count); setAsLayer(layer_name); g_free(layer_name); @@ -213,15 +226,16 @@ Inkscape::XML::Node *SvgBuilder::pushGroup() { } } if (_container->parent()->attribute("inkscape:groupmode") != nullptr) { - _ttm[0] = _ttm[3] = 1.0; // clear ttm if parent is a layer + _ttm[0] = _ttm[3] = 1.0; // clear ttm if parent is a layer _ttm[1] = _ttm[2] = _ttm[4] = _ttm[5] = 0.0; _ttm_is_set = false; } return _container; } -Inkscape::XML::Node *SvgBuilder::popGroup() { - if (_container != _root) { // Pop if the current container isn't root +Inkscape::XML::Node *SvgBuilder::popGroup() +{ + if (_container != _root) { // Pop if the current container isn't root popNode(); _state_stack.back().group_depth--; } @@ -229,30 +243,30 @@ Inkscape::XML::Node *SvgBuilder::popGroup() { return _container; } -Inkscape::XML::Node *SvgBuilder::getContainer() { +Inkscape::XML::Node *SvgBuilder::getContainer() +{ return _container; } -static gchar *svgConvertRGBToText(double r, double g, double b) { +static gchar *svgConvertRGBToText(double r, double g, double b) +{ using Inkscape::Filters::clamp; static gchar tmp[1023] = {0}; - snprintf(tmp, 1023, - "#%02x%02x%02x", - clamp(SP_COLOR_F_TO_U(r)), - clamp(SP_COLOR_F_TO_U(g)), + snprintf(tmp, 1023, "#%02x%02x%02x", clamp(SP_COLOR_F_TO_U(r)), clamp(SP_COLOR_F_TO_U(g)), clamp(SP_COLOR_F_TO_U(b))); return (gchar *)&tmp; } -static gchar *svgConvertGfxRGB(GfxRGB *color) { +static gchar *svgConvertGfxRGB(GfxRGB *color) +{ double r = (double)color->r / 65535.0; double g = (double)color->g / 65535.0; double b = (double)color->b / 65535.0; return svgConvertRGBToText(r, g, b); } -static void svgSetTransform(Inkscape::XML::Node *node, double c0, double c1, - double c2, double c3, double c4, double c5) { +static void svgSetTransform(Inkscape::XML::Node *node, double c0, double c1, double c2, double c3, double c4, double c5) +{ Geom::Affine matrix(c0, c1, c2, c3, c4, c5); gchar *transform_text = sp_svg_transform_write(matrix); node->setAttribute("transform", transform_text); @@ -262,18 +276,18 @@ static void svgSetTransform(Inkscape::XML::Node *node, double c0, double c1, /** * \brief Generates a SVG path string from poppler's data structure */ -static gchar *svgInterpretPath(_POPPLER_CONST_83 GfxPath *path) { +static gchar *svgInterpretPath(_POPPLER_CONST_83 GfxPath *path) +{ Inkscape::SVG::PathString pathString; - for (int i = 0 ; i < path->getNumSubpaths() ; ++i ) { + for (int i = 0; i < path->getNumSubpaths(); ++i) { _POPPLER_CONST_83 GfxSubpath *subpath = path->getSubpath(i); if (subpath->getNumPoints() > 0) { pathString.moveTo(subpath->getX(0), subpath->getY(0)); int j = 1; while (j < subpath->getNumPoints()) { if (subpath->getCurve(j)) { - pathString.curveTo(subpath->getX(j), subpath->getY(j), - subpath->getX(j+1), subpath->getY(j+1), - subpath->getX(j+2), subpath->getY(j+2)); + pathString.curveTo(subpath->getX(j), subpath->getY(j), subpath->getX(j + 1), subpath->getY(j + 1), + subpath->getX(j + 2), subpath->getY(j + 2)); j += 3; } else { @@ -294,9 +308,10 @@ static gchar *svgInterpretPath(_POPPLER_CONST_83 GfxPath *path) { * \brief Sets stroke style from poppler's GfxState data structure * Uses the given SPCSSAttr for storing the style properties */ -void SvgBuilder::_setStrokeStyle(SPCSSAttr *css, GfxState *state) { +void SvgBuilder::_setStrokeStyle(SPCSSAttr *css, GfxState *state) +{ // Stroke color/pattern - if ( state->getStrokeColorSpace()->getMode() == csPattern ) { + if (state->getStrokeColorSpace()->getMode() == csPattern) { gchar *urltext = _createPattern(state->getStrokePattern(), state, true); sp_repr_css_set_property(css, "stroke", urltext); if (urltext) { @@ -361,9 +376,9 @@ void SvgBuilder::_setStrokeStyle(SPCSSAttr *css, GfxState *state) { int dash_length; double dash_start; state->getLineDash(&dash_pattern, &dash_length, &dash_start); - if ( dash_length > 0 ) { + if (dash_length > 0) { Inkscape::CSSOStringStream os_array; - for ( int i = 0 ; i < dash_length ; i++ ) { + for (int i = 0; i < dash_length; i++) { os_array << dash_pattern[i]; if (i < (dash_length - 1)) { os_array << ","; @@ -384,10 +399,10 @@ void SvgBuilder::_setStrokeStyle(SPCSSAttr *css, GfxState *state) { * \brief Sets fill style from poppler's GfxState data structure * Uses the given SPCSSAttr for storing the style properties. */ -void SvgBuilder::_setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd) { - +void SvgBuilder::_setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd) +{ // Fill color/pattern - if ( state->getFillColorSpace()->getMode() == csPattern ) { + if (state->getFillColorSpace()->getMode() == csPattern) { gchar *urltext = _createPattern(state->getFillPattern(), state); sp_repr_css_set_property(css, "fill", urltext); if (urltext) { @@ -403,7 +418,7 @@ void SvgBuilder::_setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd) { Inkscape::CSSOStringStream os_opacity; os_opacity << state->getFillOpacity(); sp_repr_css_set_property(css, "fill-opacity", os_opacity.str().c_str()); - + // Fill rule sp_repr_css_set_property(css, "fill-rule", even_odd ? "evenodd" : "nonzero"); } @@ -428,14 +443,15 @@ void SvgBuilder::_setBlendMode(Inkscape::XML::Node *node, GfxState *state) * \brief Sets style properties from poppler's GfxState data structure * \return SPCSSAttr with all the relevant properties set */ -SPCSSAttr *SvgBuilder::_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd) { +SPCSSAttr *SvgBuilder::_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd) +{ SPCSSAttr *css = sp_repr_css_attr_new(); if (fill) { _setFillStyle(css, state, even_odd); } else { sp_repr_css_set_property(css, "fill", "none"); } - + if (stroke) { _setStrokeStyle(css, state); } else { @@ -453,7 +469,8 @@ SPCSSAttr *SvgBuilder::_setStyle(GfxState *state, bool fill, bool stroke, bool e * \param stroke whether the path should be stroked * \param even_odd whether the even-odd rule should be used when filling the path */ -void SvgBuilder::addPath(GfxState *state, bool fill, bool stroke, bool even_odd) { +void SvgBuilder::addPath(GfxState *state, bool fill, bool stroke, bool even_odd) +{ Inkscape::XML::Node *path = _xml_doc->createElement("svg:path"); gchar *pathtext = svgInterpretPath(state->getPath()); path->setAttribute("d", pathtext); @@ -472,9 +489,8 @@ void SvgBuilder::addPath(GfxState *state, bool fill, bool stroke, bool even_odd) * \brief Emits the current path in poppler's GfxState data structure * The path is set to be filled with the given shading. */ -void SvgBuilder::addShadedFill(GfxShading *shading, double *matrix, GfxPath *path, - bool even_odd) { - +void SvgBuilder::addShadedFill(GfxShading *shading, double *matrix, GfxPath *path, bool even_odd) +{ Inkscape::XML::Node *path_node = _xml_doc->createElement("svg:path"); gchar *pathtext = svgInterpretPath(path); path_node->setAttribute("d", pathtext); @@ -484,7 +500,7 @@ void SvgBuilder::addShadedFill(GfxShading *shading, double *matrix, GfxPath *pat SPCSSAttr *css = sp_repr_css_attr_new(); gchar *id = _createGradient(shading, matrix, true); if (id) { - gchar *urltext = g_strdup_printf ("url(#%s)", id); + gchar *urltext = g_strdup_printf("url(#%s)", id); sp_repr_css_set_property(css, "fill", urltext); g_free(urltext); g_free(id); @@ -506,13 +522,13 @@ void SvgBuilder::addShadedFill(GfxShading *shading, double *matrix, GfxPath *pat // Remove the clipping path emitted before the 'sh' operator int up_walk = 0; Inkscape::XML::Node *node = _container->parent(); - while( node && node->childCount() == 1 && up_walk < 3 ) { + while (node && node->childCount() == 1 && up_walk < 3) { gchar const *clip_path_url = node->attribute("clip-path"); if (clip_path_url) { // Obtain clipping path's id from the URL gchar clip_path_id[32]; strncpy(clip_path_id, clip_path_url + 5, strlen(clip_path_url) - 6); - clip_path_id[sizeof (clip_path_id) - 1] = '\0'; + clip_path_id[sizeof(clip_path_id) - 1] = '\0'; SPObject *clip_obj = _doc->getObjectById(clip_path_id); if (clip_obj) { clip_obj->deleteObject(); @@ -531,12 +547,14 @@ void SvgBuilder::addShadedFill(GfxShading *shading, double *matrix, GfxPath *pat * \param state poppler's data structure * \param even_odd whether the even-odd rule should be applied */ -void SvgBuilder::clip(GfxState *state, bool even_odd) { +void SvgBuilder::clip(GfxState *state, bool even_odd) +{ pushGroup(); setClipPath(state, even_odd); } -void SvgBuilder::setClipPath(GfxState *state, bool even_odd) { +void SvgBuilder::setClipPath(GfxState *state, bool even_odd) +{ // Create the clipPath repr Inkscape::XML::Node *clip_path = _xml_doc->createElement("svg:clipPath"); clip_path->setAttribute("clipPathUnits", "userSpaceOnUse"); @@ -552,7 +570,7 @@ void SvgBuilder::setClipPath(GfxState *state, bool even_odd) { Inkscape::GC::release(path); // Append clipPath to defs and get id _doc->getDefs()->getRepr()->appendChild(clip_path); - gchar *urltext = g_strdup_printf ("url(#%s)", clip_path->attribute("id")); + gchar *urltext = g_strdup_printf("url(#%s)", clip_path->attribute("id")); Inkscape::GC::release(clip_path); _container->setAttribute("clip-path", urltext); g_free(urltext); @@ -563,12 +581,13 @@ void SvgBuilder::setClipPath(GfxState *state, bool even_odd) { * \param transform array of doubles to be filled * \return true on success; false on invalid transformation */ -bool SvgBuilder::getTransform(double *transform) { +bool SvgBuilder::getTransform(double *transform) +{ Geom::Affine svd; gchar const *tr = _container->attribute("transform"); bool valid = sp_svg_transform_read(tr, &svd); if (valid) { - for ( int i = 0 ; i < 6 ; i++ ) { + for (int i = 0; i < 6; i++) { transform[i] = svd[i]; } return true; @@ -580,8 +599,8 @@ bool SvgBuilder::getTransform(double *transform) { /** * \brief Sets the transformation matrix of the current container */ -void SvgBuilder::setTransform(double c0, double c1, double c2, double c3, - double c4, double c5) { +void SvgBuilder::setTransform(double c0, double c1, double c2, double c3, double c4, double c5) +{ // do not remember the group which is a layer if ((_container->attribute("inkscape:groupmode") == nullptr) && !_ttm_is_set) { _ttm[0] = c0; @@ -594,33 +613,34 @@ void SvgBuilder::setTransform(double c0, double c1, double c2, double c3, } // Avoid transforming a group with an already set clip-path - if ( _container->attribute("clip-path") != nullptr ) { + if (_container->attribute("clip-path") != nullptr) { pushGroup(); } TRACE(("setTransform: %f %f %f %f %f %f\n", c0, c1, c2, c3, c4, c5)); svgSetTransform(_container, c0, c1, c2, c3, c4, c5); } -void SvgBuilder::setTransform(double const *transform) { - setTransform(transform[0], transform[1], transform[2], transform[3], - transform[4], transform[5]); +void SvgBuilder::setTransform(double const *transform) +{ + setTransform(transform[0], transform[1], transform[2], transform[3], transform[4], transform[5]); } /** * \brief Checks whether the given pattern type can be represented in SVG * Used by PdfParser to decide when to do fallback operations. */ -bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) { - if ( pattern != nullptr ) { - if ( pattern->getType() == 2 ) { // shading pattern +bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) +{ + if (pattern != nullptr) { + if (pattern->getType() == 2) { // shading pattern GfxShading *shading = (static_cast(pattern))->getShading(); int shadingType = shading->getType(); - if ( shadingType == 2 || // axial shading - shadingType == 3 ) { // radial shading + if (shadingType == 2 || // axial shading + shadingType == 3) { // radial shading return true; } return false; - } else if ( pattern->getType() == 1 ) { // tiling pattern + } else if (pattern->getType() == 1) { // tiling pattern return true; } } @@ -634,10 +654,11 @@ bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) { * build a tiling pattern. * \return a url pointing to the created pattern */ -gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_stroke) { +gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_stroke) +{ gchar *id = nullptr; - if ( pattern != nullptr ) { - if ( pattern->getType() == 2 ) { // Shading pattern + if (pattern != nullptr) { + if (pattern->getType() == 2) { // Shading pattern GfxShadingPattern *shading_pattern = static_cast(pattern); const double *ptm; double m[6] = {1, 0, 0, 1, 0, 0}; @@ -648,11 +669,11 @@ gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_ ptm = shading_pattern->getMatrix(); det = _ttm[0] * _ttm[3] - _ttm[1] * _ttm[2]; if (det) { - double ittm[6]; // invert ttm - ittm[0] = _ttm[3] / det; + double ittm[6]; // invert ttm + ittm[0] = _ttm[3] / det; ittm[1] = -_ttm[1] / det; ittm[2] = -_ttm[2] / det; - ittm[3] = _ttm[0] / det; + ittm[3] = _ttm[0] / det; ittm[4] = (_ttm[2] * _ttm[5] - _ttm[3] * _ttm[4]) / det; ittm[5] = (_ttm[1] * _ttm[4] - _ttm[0] * _ttm[5]) / det; m[0] = ptm[0] * ittm[0] + ptm[1] * ittm[2]; @@ -662,16 +683,14 @@ gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_ m[4] = ptm[4] * ittm[0] + ptm[5] * ittm[2] + ittm[4]; m[5] = ptm[4] * ittm[1] + ptm[5] * ittm[3] + ittm[5]; } - id = _createGradient(shading_pattern->getShading(), - m, - !is_stroke); - } else if ( pattern->getType() == 1 ) { // Tiling pattern - id = _createTilingPattern(static_cast(pattern), state, is_stroke); + id = _createGradient(shading_pattern->getShading(), m, !is_stroke); + } else if (pattern->getType() == 1) { // Tiling pattern + id = _createTilingPattern(static_cast(pattern), state, is_stroke); } } else { return nullptr; } - gchar *urltext = g_strdup_printf ("url(#%s)", id); + gchar *urltext = g_strdup_printf("url(#%s)", id); g_free(id); return urltext; } @@ -681,21 +700,20 @@ gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_ * Creates a sub-page PdfParser and uses it to parse the pattern's content stream. * \return id of the created pattern */ -gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern, - GfxState *state, bool is_stroke) { - +gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern, GfxState *state, bool is_stroke) +{ Inkscape::XML::Node *pattern_node = _xml_doc->createElement("svg:pattern"); // Set pattern transform matrix const double *p2u = tiling_pattern->getMatrix(); double m[6] = {1, 0, 0, 1, 0, 0}; double det; - det = _ttm[0] * _ttm[3] - _ttm[1] * _ttm[2]; // see LP Bug 1168908 + det = _ttm[0] * _ttm[3] - _ttm[1] * _ttm[2]; // see LP Bug 1168908 if (det) { - double ittm[6]; // invert ttm - ittm[0] = _ttm[3] / det; + double ittm[6]; // invert ttm + ittm[0] = _ttm[3] / det; ittm[1] = -_ttm[1] / det; ittm[2] = -_ttm[2] / det; - ittm[3] = _ttm[0] / det; + ittm[3] = _ttm[0] / det; ittm[4] = (_ttm[2] * _ttm[5] - _ttm[3] * _ttm[4]) / det; ittm[5] = (_ttm[1] * _ttm[4] - _ttm[0] * _ttm[5]) / det; m[0] = p2u[0] * ittm[0] + p2u[1] * ittm[2]; @@ -726,14 +744,13 @@ gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern, box.y2 = bbox[3]; // Create new SvgBuilder and sub-page PdfParser SvgBuilder *pattern_builder = new SvgBuilder(this, pattern_node); - PdfParser *pdf_parser = new PdfParser(_xref, pattern_builder, tiling_pattern->getResDict(), - &box); + PdfParser *pdf_parser = new PdfParser(_xref, pattern_builder, tiling_pattern->getResDict(), &box); // Get pattern color space - GfxPatternColorSpace *pat_cs = (GfxPatternColorSpace *)( is_stroke ? state->getStrokeColorSpace() - : state->getFillColorSpace() ); + GfxPatternColorSpace *pat_cs = + (GfxPatternColorSpace *)(is_stroke ? state->getStrokeColorSpace() : state->getFillColorSpace()); // Set fill/stroke colors if this is an uncolored tiling pattern GfxColorSpace *cs = nullptr; - if ( tiling_pattern->getPaintType() == 2 && ( cs = pat_cs->getUnder() ) ) { + if (tiling_pattern->getPaintType() == 2 && (cs = pat_cs->getUnder())) { GfxState *pattern_state = pdf_parser->getState(); pattern_state->setFillColorSpace(cs->copy()); pattern_state->setFillColor(state->getFillColor()); @@ -763,15 +780,16 @@ gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern, * \param for_shading true if we're creating this for a shading operator; false otherwise * \return id of the created object */ -gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for_shading) { +gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for_shading) +{ Inkscape::XML::Node *gradient; _POPPLER_CONST Function *func; int num_funcs; bool extend0, extend1; - if ( shading->getType() == 2 ) { // Axial shading + if (shading->getType() == 2) { // Axial shading gradient = _xml_doc->createElement("svg:linearGradient"); - GfxAxialShading *axial_shading = static_cast(shading); + GfxAxialShading *axial_shading = static_cast(shading); double x1, y1, x2, y2; axial_shading->getCoords(&x1, &y1, &x2, &y2); sp_repr_set_svg_double(gradient, "x1", x1); @@ -782,9 +800,9 @@ gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for extend1 = axial_shading->getExtend1(); num_funcs = axial_shading->getNFuncs(); func = axial_shading->getFunc(0); - } else if (shading->getType() == 3) { // Radial shading + } else if (shading->getType() == 3) { // Radial shading gradient = _xml_doc->createElement("svg:radialGradient"); - GfxRadialShading *radial_shading = static_cast(shading); + GfxRadialShading *radial_shading = static_cast(shading); double x1, y1, r1, x2, y2, r2; radial_shading->getCoords(&x1, &y1, &r1, &x2, &y2, &r2); // FIXME: the inner circle's radius is ignored here @@ -797,15 +815,14 @@ gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for extend1 = radial_shading->getExtend1(); num_funcs = radial_shading->getNFuncs(); func = radial_shading->getFunc(0); - } else { // Unsupported shading type + } else { // Unsupported shading type return nullptr; } gradient->setAttribute("gradientUnits", "userSpaceOnUse"); // If needed, flip the gradient transform around the y axis if (matrix) { - Geom::Affine pat_matrix(matrix[0], matrix[1], matrix[2], matrix[3], - matrix[4], matrix[5]); - if ( !for_shading && _is_top_level ) { + Geom::Affine pat_matrix(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); + if (!for_shading && _is_top_level) { Geom::Affine flip(1.0, 0.0, 0.0, -1.0, 0.0, Inkscape::Util::Quantity::convert(_height, "px", "pt")); pat_matrix *= flip; } @@ -814,11 +831,11 @@ gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for g_free(transform_text); } - if ( extend0 && extend1 ) { + if (extend0 && extend1) { gradient->setAttribute("spreadMethod", "pad"); } - if ( num_funcs > 1 || !_addGradientStops(gradient, shading, func) ) { + if (num_funcs > 1 || !_addGradientStops(gradient, shading, func)) { Inkscape::GC::release(gradient); return nullptr; } @@ -835,17 +852,17 @@ gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for /** * \brief Adds a stop with the given properties to the gradient's representation */ -void SvgBuilder::_addStopToGradient(Inkscape::XML::Node *gradient, double offset, - GfxRGB *color, double opacity) { +void SvgBuilder::_addStopToGradient(Inkscape::XML::Node *gradient, double offset, GfxRGB *color, double opacity) +{ Inkscape::XML::Node *stop = _xml_doc->createElement("svg:stop"); SPCSSAttr *css = sp_repr_css_attr_new(); Inkscape::CSSOStringStream os_opacity; gchar *color_text = nullptr; - if ( _transp_group_stack != nullptr && _transp_group_stack->for_softmask ) { + if (_transp_group_stack != nullptr && _transp_group_stack->for_softmask) { double gray = (double)color->r / 65535.0; gray = CLAMP(gray, 0.0, 1.0); os_opacity << gray; - color_text = (char*) "#ffffff"; + color_text = (char *)"#ffffff"; } else { os_opacity << opacity; color_text = svgConvertGfxRGB(color); @@ -861,13 +878,14 @@ void SvgBuilder::_addStopToGradient(Inkscape::XML::Node *gradient, double offset Inkscape::GC::release(stop); } -static bool svgGetShadingColorRGB(GfxShading *shading, double offset, GfxRGB *result) { +static bool svgGetShadingColorRGB(GfxShading *shading, double offset, GfxRGB *result) +{ GfxColorSpace *color_space = shading->getColorSpace(); GfxColor temp; - if ( shading->getType() == 2 ) { // Axial shading - (static_cast(shading))->getColor(offset, &temp); - } else if ( shading->getType() == 3 ) { // Radial shading - (static_cast(shading))->getColor(offset, &temp); + if (shading->getType() == 2) { // Axial shading + (static_cast(shading))->getColor(offset, &temp); + } else if (shading->getType() == 3) { // Radial shading + (static_cast(shading))->getColor(offset, &temp); } else { return false; } @@ -878,20 +896,19 @@ static bool svgGetShadingColorRGB(GfxShading *shading, double offset, GfxRGB *re } #define INT_EPSILON 8 -bool SvgBuilder::_addGradientStops(Inkscape::XML::Node *gradient, GfxShading *shading, - _POPPLER_CONST Function *func) { +bool SvgBuilder::_addGradientStops(Inkscape::XML::Node *gradient, GfxShading *shading, _POPPLER_CONST Function *func) +{ int type = func->getType(); - if ( type == 0 || type == 2 ) { // Sampled or exponential function + if (type == 0 || type == 2) { // Sampled or exponential function GfxRGB stop1, stop2; - if ( !svgGetShadingColorRGB(shading, 0.0, &stop1) || - !svgGetShadingColorRGB(shading, 1.0, &stop2) ) { + if (!svgGetShadingColorRGB(shading, 0.0, &stop1) || !svgGetShadingColorRGB(shading, 1.0, &stop2)) { return false; } else { _addStopToGradient(gradient, 0.0, &stop1, 1.0); _addStopToGradient(gradient, 1.0, &stop2, 1.0); } - } else if ( type == 3 ) { // Stitching - auto stitchingFunc = static_cast<_POPPLER_CONST StitchingFunction*>(func); + } else if (type == 3) { // Stitching + auto stitchingFunc = static_cast<_POPPLER_CONST StitchingFunction *>(func); const double *bounds = stitchingFunc->getBounds(); const double *encode = stitchingFunc->getEncode(); int num_funcs = stitchingFunc->getNumFuncs(); @@ -900,16 +917,17 @@ bool SvgBuilder::_addGradientStops(Inkscape::XML::Node *gradient, GfxShading *sh GfxRGB prev_color, color; svgGetShadingColorRGB(shading, bounds[0], &prev_color); _addStopToGradient(gradient, bounds[0], &prev_color, 1.0); - for ( int i = 0 ; i < num_funcs ; i++ ) { + for (int i = 0; i < num_funcs; i++) { svgGetShadingColorRGB(shading, bounds[i + 1], &color); // Add stops - if (stitchingFunc->getFunc(i)->getType() == 2) { // process exponential fxn - double expE = (static_cast<_POPPLER_CONST ExponentialFunction*>(stitchingFunc->getFunc(i)))->getE(); + if (stitchingFunc->getFunc(i)->getType() == 2) { // process exponential fxn + double expE = (static_cast<_POPPLER_CONST ExponentialFunction *>(stitchingFunc->getFunc(i)))->getE(); if (expE > 1.0) { - expE = (bounds[i + 1] - bounds[i])/expE; // approximate exponential as a single straight line at x=1 - if (encode[2*i] == 0) { // normal sequence + expE = + (bounds[i + 1] - bounds[i]) / expE; // approximate exponential as a single straight line at x=1 + if (encode[2 * i] == 0) { // normal sequence _addStopToGradient(gradient, bounds[i + 1] - expE, &prev_color, 1.0); - } else { // reflected sequence + } else { // reflected sequence _addStopToGradient(gradient, bounds[i] + expE, &color, 1.0); } } @@ -928,7 +946,8 @@ bool SvgBuilder::_addGradientStops(Inkscape::XML::Node *gradient, GfxShading *sh * \brief Sets _invalidated_style to true to indicate that styles have to be updated * Used for text output when glyphs are buffered till a font change */ -void SvgBuilder::updateStyle(GfxState *state) { +void SvgBuilder::updateStyle(GfxState *state) +{ if (_in_text_object) { _invalidated_style = true; _current_state = state; @@ -937,7 +956,7 @@ void SvgBuilder::updateStyle(GfxState *state) { /* MatchingChars - Count for how many characters s1 matches sp taking into account + Count for how many characters s1 matches sp taking into account that a space in sp may be removed or replaced by some other tokens specified in the code. (Bug LP #179589) */ @@ -946,9 +965,10 @@ static size_t MatchingChars(std::string s1, std::string sp) size_t is = 0; size_t ip = 0; - while(is < s1.length() && ip < sp.length()) { + while (is < s1.length() && ip < sp.length()) { if (s1[is] == sp[ip]) { - is++; ip++; + is++; + ip++; } else if (sp[ip] == ' ') { ip++; if (s1[is] == '_') { // Valid matches to spaces in sp. @@ -970,14 +990,14 @@ std::string SvgBuilder::_BestMatchingFont(std::string PDFname) { double bestMatch = 0; std::string bestFontname = "Arial"; - + for (auto fontname : _availableFontNames) { // At least the first word of the font name should match. size_t minMatch = fontname.find(" "); if (minMatch == std::string::npos) { - minMatch = fontname.length(); + minMatch = fontname.length(); } - + size_t Match = MatchingChars(PDFname, fontname); if (Match >= minMatch) { double relMatch = (float)Match / (fontname.length() + PDFname.length()); @@ -1021,14 +1041,14 @@ static char *font_weight_translator[][2] = { /** * \brief Updates _font_style according to the font set in parameter state */ -void SvgBuilder::updateFont(GfxState *state) { - +void SvgBuilder::updateFont(GfxState *state) +{ TRACE(("updateFont()\n")); _need_font_update = false; - updateTextMatrix(state); // Ensure that we have a text matrix built + updateTextMatrix(state); // Ensure that we have a text matrix built if (_font_style) { - //sp_repr_css_attr_unref(_font_style); + // sp_repr_css_attr_unref(_font_style); } _font_style = sp_repr_css_attr_new(); GfxFont *font = state->getFont(); @@ -1052,8 +1072,7 @@ void SvgBuilder::updateFont(GfxState *state) { font_family = g_strdup(_font_specification); } char *style_delim = nullptr; - if ( ( style_delim = g_strrstr(font_family, "-") ) || - ( style_delim = g_strrstr(font_family, ",") ) ) { + if ((style_delim = g_strrstr(font_family, "-")) || (style_delim = g_strrstr(font_family, ","))) { font_style = style_delim + 1; font_style_lowercase = g_ascii_strdown(font_style, -1); style_delim[0] = 0; @@ -1062,7 +1081,7 @@ void SvgBuilder::updateFont(GfxState *state) { // Font family if (font->getFamily()) { // if font family is explicitly given use it. sp_repr_css_set_property(_font_style, "font-family", font->getFamily()->getCString()); - } else { + } else { int attr_value = 1; sp_repr_get_int(_preferences, "localFonts", &attr_value); if (attr_value != 0) { @@ -1077,8 +1096,7 @@ void SvgBuilder::updateFont(GfxState *state) { if (font->isItalic()) { sp_repr_css_set_property(_font_style, "font-style", "italic"); } else if (font_style) { - if ( strstr(font_style_lowercase, "italic") || - strstr(font_style_lowercase, "slanted") ) { + if (strstr(font_style_lowercase, "italic") || strstr(font_style_lowercase, "slanted")) { sp_repr_css_set_property(_font_style, "font-style", "italic"); } else if (strstr(font_style_lowercase, "oblique")) { sp_repr_css_set_property(_font_style, "font-style", "oblique"); @@ -1091,26 +1109,26 @@ void SvgBuilder::updateFont(GfxState *state) { // Font weight GfxFont::Weight font_weight = font->getWeight(); char *css_font_weight = nullptr; - if ( font_weight != GfxFont::WeightNotDefined ) { - if ( font_weight == GfxFont::W400 ) { - css_font_weight = (char*) "normal"; - } else if ( font_weight == GfxFont::W700 ) { - css_font_weight = (char*) "bold"; + if (font_weight != GfxFont::WeightNotDefined) { + if (font_weight == GfxFont::W400) { + css_font_weight = (char *)"normal"; + } else if (font_weight == GfxFont::W700) { + css_font_weight = (char *)"bold"; } else { gchar weight_num[4] = "100"; - weight_num[0] = (gchar)( '1' + (font_weight - GfxFont::W100) ); + weight_num[0] = (gchar)('1' + (font_weight - GfxFont::W100)); sp_repr_css_set_property(_font_style, "font-weight", (gchar *)&weight_num); } } else if (font_style) { // Apply the font weight translations - int num_translations = sizeof(font_weight_translator) / ( 2 * sizeof(char *) ); - for ( int i = 0 ; i < num_translations ; i++ ) { + int num_translations = sizeof(font_weight_translator) / (2 * sizeof(char *)); + for (int i = 0; i < num_translations; i++) { if (strstr(font_style_lowercase, font_weight_translator[i][0])) { css_font_weight = font_weight_translator[i][1]; } } } else { - css_font_weight = (char*) "normal"; + css_font_weight = (char *)"normal"; } if (css_font_weight) { sp_repr_css_set_property(_font_style, "font-weight", css_font_weight); @@ -1125,45 +1143,45 @@ void SvgBuilder::updateFont(GfxState *state) { gchar *stretch_value = nullptr; switch (font_stretch) { case GfxFont::UltraCondensed: - stretch_value = (char*) "ultra-condensed"; + stretch_value = (char *)"ultra-condensed"; break; case GfxFont::ExtraCondensed: - stretch_value = (char*) "extra-condensed"; + stretch_value = (char *)"extra-condensed"; break; case GfxFont::Condensed: - stretch_value = (char*) "condensed"; + stretch_value = (char *)"condensed"; break; case GfxFont::SemiCondensed: - stretch_value = (char*) "semi-condensed"; + stretch_value = (char *)"semi-condensed"; break; case GfxFont::Normal: - stretch_value = (char*) "normal"; + stretch_value = (char *)"normal"; break; case GfxFont::SemiExpanded: - stretch_value = (char*) "semi-expanded"; + stretch_value = (char *)"semi-expanded"; break; case GfxFont::Expanded: - stretch_value = (char*) "expanded"; + stretch_value = (char *)"expanded"; break; case GfxFont::ExtraExpanded: - stretch_value = (char*) "extra-expanded"; + stretch_value = (char *)"extra-expanded"; break; case GfxFont::UltraExpanded: - stretch_value = (char*) "ultra-expanded"; + stretch_value = (char *)"ultra-expanded"; break; default: break; } - if ( stretch_value != nullptr ) { + if (stretch_value != nullptr) { sp_repr_css_set_property(_font_style, "font-stretch", stretch_value); } // Font size Inkscape::CSSOStringStream os_font_size; double css_font_size = _font_scaling * state->getFontSize(); - if ( font->getType() == fontType3 ) { + if (font->getType() == fontType3) { const double *font_matrix = font->getFontMatrix(); - if ( font_matrix[0] != 0.0 ) { + if (font_matrix[0] != 0.0) { css_font_size *= font_matrix[3] / font_matrix[0]; } } @@ -1171,7 +1189,7 @@ void SvgBuilder::updateFont(GfxState *state) { sp_repr_css_set_property(_font_style, "font-size", os_font_size.str().c_str()); // Writing mode - if ( font->getWMode() == 0 ) { + if (font->getWMode() == 0) { sp_repr_css_set_property(_font_style, "writing-mode", "lr"); } else { sp_repr_css_set_property(_font_style, "writing-mode", "tb"); @@ -1184,7 +1202,8 @@ void SvgBuilder::updateFont(GfxState *state) { /** * \brief Shifts the current text position by the given amount (specified in text space) */ -void SvgBuilder::updateTextShift(GfxState *state, double shift) { +void SvgBuilder::updateTextShift(GfxState *state, double shift) +{ double shift_value = -shift * 0.001 * fabs(state->getFontSize()); if (state->getFont()->getWMode()) { _text_position[1] += shift_value; @@ -1196,7 +1215,8 @@ void SvgBuilder::updateTextShift(GfxState *state, double shift) { /** * \brief Updates current text position */ -void SvgBuilder::updateTextPosition(double tx, double ty) { +void SvgBuilder::updateTextPosition(double tx, double ty) +{ Geom::Point new_position(tx, ty); _text_position = new_position; } @@ -1204,27 +1224,26 @@ void SvgBuilder::updateTextPosition(double tx, double ty) { /** * \brief Flushes the buffered characters */ -void SvgBuilder::updateTextMatrix(GfxState *state) { +void SvgBuilder::updateTextMatrix(GfxState *state) +{ _flushText(); // Update text matrix const double *text_matrix = state->getTextMat(); - double w_scale = sqrt( text_matrix[0] * text_matrix[0] + text_matrix[2] * text_matrix[2] ); - double h_scale = sqrt( text_matrix[1] * text_matrix[1] + text_matrix[3] * text_matrix[3] ); + double w_scale = sqrt(text_matrix[0] * text_matrix[0] + text_matrix[2] * text_matrix[2]); + double h_scale = sqrt(text_matrix[1] * text_matrix[1] + text_matrix[3] * text_matrix[3]); double max_scale; - if ( w_scale > h_scale ) { + if (w_scale > h_scale) { max_scale = w_scale; } else { max_scale = h_scale; } // Calculate new text matrix - Geom::Affine new_text_matrix(text_matrix[0] * state->getHorizScaling(), - text_matrix[1] * state->getHorizScaling(), - -text_matrix[2], -text_matrix[3], - 0.0, 0.0); + Geom::Affine new_text_matrix(text_matrix[0] * state->getHorizScaling(), text_matrix[1] * state->getHorizScaling(), + -text_matrix[2], -text_matrix[3], 0.0, 0.0); - if ( fabs( max_scale - 1.0 ) > EPSILON ) { + if (fabs(max_scale - 1.0) > EPSILON) { // Cancel out scaling by font size in text matrix - for ( int i = 0 ; i < 4 ; i++ ) { + for (int i = 0; i < 4; i++) { new_text_matrix[i] /= max_scale; } } @@ -1235,17 +1254,18 @@ void SvgBuilder::updateTextMatrix(GfxState *state) { /** * \brief Writes the buffered characters to the SVG document */ -void SvgBuilder::_flushText() { +void SvgBuilder::_flushText() +{ // Ignore empty strings - if ( _glyphs.empty()) { + if (_glyphs.empty()) { _glyphs.clear(); return; } std::vector::iterator i = _glyphs.begin(); - const SvgGlyph& first_glyph = (*i); + const SvgGlyph &first_glyph = (*i); int render_mode = first_glyph.render_mode; // Ignore invisible characters - if ( render_mode == 3 ) { + if (render_mode == 3) { _glyphs.clear(); return; } @@ -1270,37 +1290,35 @@ void SvgBuilder::_flushText() { // Output all buffered glyphs while (true) { - const SvgGlyph& glyph = (*i); + const SvgGlyph &glyph = (*i); std::vector::iterator prev_iterator = i - 1; // Check if we need to make a new tspan if (glyph.style_changed) { new_tspan = true; - } else if ( i != _glyphs.begin() ) { - const SvgGlyph& prev_glyph = (*prev_iterator); - if ( !( ( glyph.dy == 0.0 && prev_glyph.dy == 0.0 && - glyph.text_position[1] == prev_glyph.text_position[1] ) || - ( glyph.dx == 0.0 && prev_glyph.dx == 0.0 && - glyph.text_position[0] == prev_glyph.text_position[0] ) ) ) { + } else if (i != _glyphs.begin()) { + const SvgGlyph &prev_glyph = (*prev_iterator); + if (!((glyph.dy == 0.0 && prev_glyph.dy == 0.0 && glyph.text_position[1] == prev_glyph.text_position[1]) || + (glyph.dx == 0.0 && prev_glyph.dx == 0.0 && glyph.text_position[0] == prev_glyph.text_position[0]))) { new_tspan = true; } } // Create tspan node if needed - if ( new_tspan || i == _glyphs.end() ) { + if (new_tspan || i == _glyphs.end()) { if (tspan_node) { // Set the x and y coordinate arrays - if ( same_coords[0] ) { + if (same_coords[0]) { sp_repr_set_svg_double(tspan_node, "x", last_delta_pos[0]); } else { tspan_node->setAttributeOrRemoveIfEmpty("x", x_coords); } - if ( same_coords[1] ) { + if (same_coords[1]) { sp_repr_set_svg_double(tspan_node, "y", last_delta_pos[1]); } else { tspan_node->setAttributeOrRemoveIfEmpty("y", y_coords); } TRACE(("tspan content: %s\n", text_buffer.c_str())); - if ( glyphs_in_a_row > 1 ) { + if (glyphs_in_a_row > 1) { tspan_node->setAttribute("sodipodi:role", "line"); } // Add text content node to tspan @@ -1315,12 +1333,12 @@ void SvgBuilder::_flushText() { Inkscape::GC::release(tspan_node); glyphs_in_a_row = 0; } - if ( i == _glyphs.end() ) { + if (i == _glyphs.end()) { sp_repr_css_attr_unref((*prev_iterator).style); break; } else { tspan_node = _xml_doc->createElement("svg:tspan"); - + /////// // Create a font specification string and save the attribute in the style PangoFontDescription *descr = pango_font_description_from_string(glyph.font_specification); @@ -1331,27 +1349,27 @@ void SvgBuilder::_flushText() { // Set style and unref SPCSSAttr if it won't be needed anymore // assume all nodes in a node share the same style sp_repr_css_change(text_node, glyph.style, "style"); - if ( glyph.style_changed && i != _glyphs.begin() ) { // Free previous style + if (glyph.style_changed && i != _glyphs.begin()) { // Free previous style sp_repr_css_attr_unref((*prev_iterator).style); } } new_tspan = false; } - if ( glyphs_in_a_row > 0 ) { + if (glyphs_in_a_row > 0) { x_coords.append(" "); y_coords.append(" "); // Check if we have the same coordinates - const SvgGlyph& prev_glyph = (*prev_iterator); - for ( int p = 0 ; p < 2 ; p++ ) { - if ( glyph.text_position[p] != prev_glyph.text_position[p] ) { + const SvgGlyph &prev_glyph = (*prev_iterator); + for (int p = 0; p < 2; p++) { + if (glyph.text_position[p] != prev_glyph.text_position[p]) { same_coords[p] = false; } } } // Append the coordinates to their respective strings - Geom::Point delta_pos( glyph.text_position - first_glyph.text_position ); + Geom::Point delta_pos(glyph.text_position - first_glyph.text_position); delta_pos[1] += glyph.rise; - delta_pos[1] *= -1.0; // flip it + delta_pos[1] *= -1.0; // flip it delta_pos *= _font_scaling; Inkscape::CSSOStringStream os_x; os_x << delta_pos[0]; @@ -1362,9 +1380,9 @@ void SvgBuilder::_flushText() { last_delta_pos = delta_pos; // Append the character to the text buffer - if ( !glyph.code.empty() ) { + if (!glyph.code.empty()) { text_buffer.append(1, glyph.code[0]); - } + } glyphs_in_a_row++; ++i; @@ -1375,14 +1393,15 @@ void SvgBuilder::_flushText() { _glyphs.clear(); } -void SvgBuilder::beginString(GfxState *state) { +void SvgBuilder::beginString(GfxState *state) +{ if (_need_font_update) { updateFont(state); } IFTRACE(double *m = state->getTextMat()); - TRACE(("tm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5])); + TRACE(("tm: %f %f %f %f %f %f\n", m[0], m[1], m[2], m[3], m[4], m[5])); IFTRACE(m = state->getCTM()); - TRACE(("ctm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5])); + TRACE(("ctm: %f %f %f %f %f %f\n", m[0], m[1], m[2], m[3], m[4], m[5])); } /** @@ -1390,11 +1409,9 @@ void SvgBuilder::beginString(GfxState *state) { * Takes care of converting it to UTF-8 and generates a new style repr if style * has changed since the last call. */ -void SvgBuilder::addChar(GfxState *state, double x, double y, - double dx, double dy, - double originX, double originY, - CharCode /*code*/, int /*nBytes*/, Unicode const *u, int uLen) { - +void SvgBuilder::addChar(GfxState *state, double x, double y, double dx, double dy, double originX, double originY, + CharCode /*code*/, int /*nBytes*/, Unicode const *u, int uLen) +{ // Skip control characters, found in LaTeX generated PDFs // https://gitlab.com/inkscape/inkscape/-/issues/1369 if (uLen > 0 && u[0] < 0x80 && g_ascii_iscntrl(u[0]) && !g_ascii_isspace(u[0])) { @@ -1403,16 +1420,15 @@ void SvgBuilder::addChar(GfxState *state, double x, double y, return; } - bool is_space = ( uLen == 1 && u[0] == 32 ); + bool is_space = (uLen == 1 && u[0] == 32); // Skip beginning space - if ( is_space && _glyphs.empty()) { + if (is_space && _glyphs.empty()) { Geom::Point delta(dx, dy); - _text_position += delta; - return; + _text_position += delta; + return; } // Allow only one space in a row - if ( is_space && (_glyphs[_glyphs.size() - 1].code.size() == 1) && - (_glyphs[_glyphs.size() - 1].code[0] == 32) ) { + if (is_space && (_glyphs[_glyphs.size() - 1].code.size() == 1) && (_glyphs[_glyphs.size() - 1].code[0] == 32)) { Geom::Point delta(dx, dy); _text_position += delta; return; @@ -1420,7 +1436,7 @@ void SvgBuilder::addChar(GfxState *state, double x, double y, SvgGlyph new_glyph; new_glyph.is_space = is_space; - new_glyph.position = Geom::Point( x - originX, y - originY ); + new_glyph.position = Geom::Point(x - originX, y - originY); new_glyph.text_position = _text_position; new_glyph.dx = dx; new_glyph.dy = dy; @@ -1436,7 +1452,7 @@ void SvgBuilder::addChar(GfxState *state, double x, double y, } gchar *tmp = g_utf16_to_utf8(uu, uLen, nullptr, nullptr, nullptr); - if ( tmp && *tmp ) { + if (tmp && *tmp) { new_glyph.code = tmp; } else { new_glyph.code.clear(); @@ -1449,8 +1465,8 @@ void SvgBuilder::addChar(GfxState *state, double x, double y, new_glyph.style_changed = true; int render_mode = state->getRender(); // Set style - bool has_fill = !( render_mode & 1 ); - bool has_stroke = ( render_mode & 3 ) == 1 || ( render_mode & 3 ) == 2; + bool has_fill = !(render_mode & 1); + bool has_stroke = (render_mode & 3) == 1 || (render_mode & 3) == 2; new_glyph.style = _setStyle(state, has_fill, has_stroke); // Find a way to handle blend modes on text /* GfxBlendMode blendmode = state->getBlendMode(); @@ -1463,7 +1479,7 @@ void SvgBuilder::addChar(GfxState *state, double x, double y, } else { new_glyph.style_changed = false; // Point to previous glyph's style information - const SvgGlyph& prev_glyph = _glyphs.back(); + const SvgGlyph &prev_glyph = _glyphs.back(); new_glyph.style = prev_glyph.style; /* GfxBlendMode blendmode = state->getBlendMode(); if (blendmode) { @@ -1477,16 +1493,17 @@ void SvgBuilder::addChar(GfxState *state, double x, double y, _glyphs.push_back(new_glyph); } -void SvgBuilder::endString(GfxState * /*state*/) { -} +void SvgBuilder::endString(GfxState * /*state*/) {} -void SvgBuilder::beginTextObject(GfxState *state) { +void SvgBuilder::beginTextObject(GfxState *state) +{ _in_text_object = true; - _invalidated_style = true; // Force copying of current state + _invalidated_style = true; // Force copying of current state _current_state = state; } -void SvgBuilder::endTextObject(GfxState * /*state*/) { +void SvgBuilder::endTextObject(GfxState * /*state*/) +{ _flushText(); // TODO: clip if render_mode >= 4 _in_text_object = false; @@ -1498,7 +1515,7 @@ void SvgBuilder::endTextObject(GfxState * /*state*/) { void png_write_vector(png_structp png_ptr, png_bytep data, png_size_t length) { auto *v_ptr = reinterpret_cast *>(png_get_io_ptr(png_ptr)); // Get pointer to stream - for ( unsigned i = 0 ; i < length ; i++ ) { + for (unsigned i = 0; i < length; i++) { v_ptr->push_back(data[i]); } } @@ -1507,19 +1524,17 @@ void png_write_vector(png_structp png_ptr, png_bytep data, png_size_t length) * \brief Creates an element containing the given ImageStream as a PNG * */ -Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height, - GfxImageColorMap *color_map, bool interpolate, - int *mask_colors, bool alpha_only, - bool invert_alpha) { - +Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height, GfxImageColorMap *color_map, + bool interpolate, int *mask_colors, bool alpha_only, bool invert_alpha) +{ // Create PNG write struct png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); - if ( png_ptr == nullptr ) { + if (png_ptr == nullptr) { return nullptr; } // Create PNG info struct png_infop info_ptr = png_create_info_struct(png_ptr); - if ( info_ptr == nullptr ) { + if (info_ptr == nullptr) { png_destroy_write_struct(&png_ptr, nullptr); return nullptr; } @@ -1531,7 +1546,7 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height // Decide whether we should embed this image int attr_value = 1; sp_repr_get_int(_preferences, "embedImages", &attr_value); - bool embed_image = ( attr_value != 0 ); + bool embed_image = (attr_value != 0); // Set read/write functions std::vector png_buffer; FILE *fp = nullptr; @@ -1542,7 +1557,7 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height static int counter = 0; file_name = g_strdup_printf("%s_img%d.png", _docname, counter++); fp = fopen(file_name, "wb"); - if ( fp == nullptr ) { + if (fp == nullptr) { png_destroy_write_struct(&png_ptr, &info_ptr); g_free(file_name); return nullptr; @@ -1551,33 +1566,21 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height } // Set header data - if ( !invert_alpha && !alpha_only ) { + if (!invert_alpha && !alpha_only) { png_set_invert_alpha(png_ptr); } png_color_8 sig_bit; if (alpha_only) { - png_set_IHDR(png_ptr, info_ptr, - width, - height, - 8, /* bit_depth */ - PNG_COLOR_TYPE_GRAY, - PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_BASE, - PNG_FILTER_TYPE_BASE); + png_set_IHDR(png_ptr, info_ptr, width, height, 8, /* bit_depth */ + PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); sig_bit.red = 0; sig_bit.green = 0; sig_bit.blue = 0; sig_bit.gray = 8; sig_bit.alpha = 0; } else { - png_set_IHDR(png_ptr, info_ptr, - width, - height, - 8, /* bit_depth */ - PNG_COLOR_TYPE_RGB_ALPHA, - PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_BASE, - PNG_FILTER_TYPE_BASE); + png_set_IHDR(png_ptr, info_ptr, width, height, 8, /* bit_depth */ + PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); sig_bit.red = 8; sig_bit.green = 8; sig_bit.blue = 8; @@ -1592,8 +1595,7 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height ImageStream *image_stream; if (alpha_only) { if (color_map) { - image_stream = new ImageStream(str, width, color_map->getNumPixelComps(), - color_map->getBits()); + image_stream = new ImageStream(str, width, color_map->getNumPixelComps(), color_map->getBits()); } else { image_stream = new ImageStream(str, width, 1, 1); } @@ -1602,14 +1604,14 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height // Convert grayscale values unsigned char *buffer = new unsigned char[width]; int invert_bit = invert_alpha ? 1 : 0; - for ( int y = 0 ; y < height ; y++ ) { + for (int y = 0; y < height; y++) { unsigned char *row = image_stream->getLine(); if (color_map) { color_map->getGrayLine(row, buffer, width); } else { unsigned char *buf_ptr = buffer; - for ( int x = 0 ; x < width ; x++ ) { - if ( row[x] ^ invert_bit ) { + for (int x = 0; x < width; x++) { + if (row[x] ^ invert_bit) { *buf_ptr++ = 0; } else { *buf_ptr++ = 255; @@ -1618,26 +1620,23 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height } png_write_row(png_ptr, (png_bytep)buffer); } - delete [] buffer; + delete[] buffer; } else if (color_map) { - image_stream = new ImageStream(str, width, - color_map->getNumPixelComps(), - color_map->getBits()); + image_stream = new ImageStream(str, width, color_map->getNumPixelComps(), color_map->getBits()); image_stream->reset(); // Convert RGB values unsigned int *buffer = new unsigned int[width]; if (mask_colors) { - for ( int y = 0 ; y < height ; y++ ) { + for (int y = 0; y < height; y++) { unsigned char *row = image_stream->getLine(); color_map->getRGBLine(row, buffer, width); unsigned int *dest = buffer; - for ( int x = 0 ; x < width ; x++ ) { + for (int x = 0; x < width; x++) { // Check each color component against the mask - for ( int i = 0; i < color_map->getNumPixelComps() ; i++) { - if ( row[i] < mask_colors[2*i] * 255 || - row[i] > mask_colors[2*i + 1] * 255 ) { + for (int i = 0; i < color_map->getNumPixelComps(); i++) { + if (row[i] < mask_colors[2 * i] * 255 || row[i] > mask_colors[2 * i + 1] * 255) { *dest = *dest | 0xff000000; break; } @@ -1650,16 +1649,16 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height png_write_row(png_ptr, (png_bytep)buffer); } } else { - for ( int i = 0 ; i < height ; i++ ) { + for (int i = 0; i < height; i++) { unsigned char *row = image_stream->getLine(); - memset((void*)buffer, 0xff, sizeof(int) * width); + memset((void *)buffer, 0xff, sizeof(int) * width); color_map->getRGBLine(row, buffer, width); png_write_row(png_ptr, (png_bytep)buffer); } } - delete [] buffer; + delete[] buffer; - } else { // A colormap must be provided, so quit + } else { // A colormap must be provided, so quit png_destroy_write_struct(&png_ptr, &info_ptr); if (!embed_image) { fclose(fp); @@ -1677,7 +1676,7 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height Inkscape::XML::Node *image_node = _xml_doc->createElement("svg:image"); sp_repr_set_svg_double(image_node, "width", 1); sp_repr_set_svg_double(image_node, "height", 1); - if( !interpolate ) { + if (!interpolate) { SPCSSAttr *css = sp_repr_css_attr_new(); // This should be changed after CSS4 Images widely supported. sp_repr_css_set_property(css, "image-rendering", "optimizeSpeed"); @@ -1690,7 +1689,7 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height // Set transformation - svgSetTransform(image_node, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0); + svgSetTransform(image_node, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0); // Create href if (embed_image) { @@ -1713,7 +1712,8 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height * If we're not the top-level SvgBuilder, creates a too and adds the mask to it. * \return the created XML node */ -Inkscape::XML::Node *SvgBuilder::_createMask(double width, double height) { +Inkscape::XML::Node *SvgBuilder::_createMask(double width, double height) +{ Inkscape::XML::Node *mask_node = _xml_doc->createElement("svg:mask"); mask_node->setAttribute("maskUnits", "userSpaceOnUse"); sp_repr_set_svg_double(mask_node, "x", 0.0); @@ -1725,10 +1725,10 @@ Inkscape::XML::Node *SvgBuilder::_createMask(double width, double height) { _doc->getDefs()->getRepr()->appendChild(mask_node); Inkscape::GC::release(mask_node); return _doc->getDefs()->getRepr()->lastChild(); - } else { // Work around for renderer bug when mask isn't defined in pattern + } else { // Work around for renderer bug when mask isn't defined in pattern static int mask_count = 0; Inkscape::XML::Node *defs = _root->firstChild(); - if ( !( defs && !strcmp(defs->name(), "svg:defs") ) ) { + if (!(defs && !strcmp(defs->name(), "svg:defs"))) { // Create node defs = _xml_doc->createElement("svg:defs"); _root->addChild(defs, nullptr); @@ -1747,7 +1747,6 @@ Inkscape::XML::Node *SvgBuilder::_createMask(double width, double height) { void SvgBuilder::addImage(GfxState *state, Stream *str, int width, int height, GfxImageColorMap *color_map, bool interpolate, int *mask_colors) { - Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, interpolate, mask_colors); if (image_node) { _setBlendMode(image_node, state); @@ -1756,9 +1755,8 @@ void SvgBuilder::addImage(GfxState *state, Stream *str, int width, int height, G } } -void SvgBuilder::addImageMask(GfxState *state, Stream *str, int width, int height, - bool invert, bool interpolate) { - +void SvgBuilder::addImageMask(GfxState *state, Stream *str, int width, int height, bool invert, bool interpolate) +{ // Create a rectangle Inkscape::XML::Node *rect = _xml_doc->createElement("svg:rect"); sp_repr_set_svg_double(rect, "x", 0.0); @@ -1774,7 +1772,7 @@ void SvgBuilder::addImageMask(GfxState *state, Stream *str, int width, int heigh _setBlendMode(rect, state); // Scaling 1x1 surfaces might not work so skip setting a mask with this size - if ( width > 1 || height > 1 ) { + if (width > 1 || height > 1) { Inkscape::XML::Node *mask_image_node = _createImage(str, width, height, nullptr, interpolate, nullptr, true, invert); if (mask_image_node) { @@ -1799,11 +1797,10 @@ void SvgBuilder::addMaskedImage(GfxState *state, Stream *str, int width, int hei bool interpolate, Stream *mask_str, int mask_width, int mask_height, bool invert_mask, bool mask_interpolate) { - - Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height, - nullptr, mask_interpolate, nullptr, true, invert_mask); + Inkscape::XML::Node *mask_image_node = + _createImage(mask_str, mask_width, mask_height, nullptr, mask_interpolate, nullptr, true, invert_mask); Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, interpolate, nullptr); - if ( mask_image_node && image_node ) { + if (mask_image_node && image_node) { // Create mask for the image Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0); // Remove unnecessary transformation from the mask image @@ -1833,11 +1830,10 @@ void SvgBuilder::addSoftMaskedImage(GfxState *state, Stream *str, int width, int bool interpolate, Stream *mask_str, int mask_width, int mask_height, GfxImageColorMap *mask_color_map, bool mask_interpolate) { - - Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height, - mask_color_map, mask_interpolate, nullptr, true); + Inkscape::XML::Node *mask_image_node = + _createImage(mask_str, mask_width, mask_height, mask_color_map, mask_interpolate, nullptr, true); Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, interpolate, nullptr); - if ( mask_image_node && image_node ) { + if (mask_image_node && image_node) { // Create mask for the image Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0); // Remove unnecessary transformation from the mask image @@ -1861,18 +1857,16 @@ void SvgBuilder::addSoftMaskedImage(GfxState *state, Stream *str, int width, int /** * \brief Starts building a new transparency group */ -void SvgBuilder::pushTransparencyGroup(GfxState * /*state*/, double *bbox, - GfxColorSpace * /*blending_color_space*/, - bool isolated, bool knockout, - bool for_softmask) { - +void SvgBuilder::pushTransparencyGroup(GfxState * /*state*/, double *bbox, GfxColorSpace * /*blending_color_space*/, + bool isolated, bool knockout, bool for_softmask) +{ // Push node stack pushNode("svg:g"); // Setup new transparency group SvgTransparencyGroup *transpGroup = new SvgTransparencyGroup; for (size_t i = 0; i < 4; i++) { - transpGroup->bbox[i] = bbox[i]; + transpGroup->bbox[i] = bbox[i]; } transpGroup->isolated = isolated; transpGroup->knockout = knockout; @@ -1884,7 +1878,8 @@ void SvgBuilder::pushTransparencyGroup(GfxState * /*state*/, double *bbox, _transp_group_stack = transpGroup; } -void SvgBuilder::popTransparencyGroup(GfxState * /*state*/) { +void SvgBuilder::popTransparencyGroup(GfxState * /*state*/) +{ // Restore node stack popNode(); } @@ -1892,7 +1887,8 @@ void SvgBuilder::popTransparencyGroup(GfxState * /*state*/) { /** * \brief Places the current transparency group into the current container */ -void SvgBuilder::paintTransparencyGroup(GfxState * /*state*/, double * /*bbox*/) { +void SvgBuilder::paintTransparencyGroup(GfxState * /*state*/, double * /*bbox*/) +{ SvgTransparencyGroup *transpGroup = _transp_group_stack; _container->appendChild(transpGroup->container); Inkscape::GC::release(transpGroup->container); @@ -1904,9 +1900,9 @@ void SvgBuilder::paintTransparencyGroup(GfxState * /*state*/, double * /*bbox*/) /** * \brief Creates a mask using the current transparency group as its content */ -void SvgBuilder::setSoftMask(GfxState * /*state*/, double * /*bbox*/, bool /*alpha*/, - Function * /*transfer_func*/, GfxColor * /*backdrop_color*/) { - +void SvgBuilder::setSoftMask(GfxState * /*state*/, double * /*bbox*/, bool /*alpha*/, Function * /*transfer_func*/, + GfxColor * /*backdrop_color*/) +{ // Create mask Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0); // Add the softmask content to it @@ -1924,14 +1920,17 @@ void SvgBuilder::setSoftMask(GfxState * /*state*/, double * /*bbox*/, bool /*alp delete transpGroup; } -void SvgBuilder::clearSoftMask(GfxState * /*state*/) { +void SvgBuilder::clearSoftMask(GfxState * /*state*/) +{ if (_state_stack.back().softmask) { _state_stack.back().softmask = nullptr; popGroup(); } } -} } } /* namespace Inkscape, Extension, Internal */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* HAVE_POPPLER */ diff --git a/src/extension/internal/pdfinput/svg-builder.h b/src/extension/internal/pdfinput/svg-builder.h index 050465d4bf9c00b7f72d2be3139f8be505e3354d..ac954df36d3f286baa602ce8078e40ab49469dda 100644 --- a/src/extension/internal/pdfinput/svg-builder.h +++ b/src/extension/internal/pdfinput/svg-builder.h @@ -12,7 +12,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef HAVE_POPPLER @@ -20,14 +20,14 @@ class SPDocument; namespace Inkscape { - namespace XML { - struct Document; - class Node; - } -} +namespace XML { +struct Document; +class Node; +} // namespace XML +} // namespace Inkscape -#include <2geom/point.h> #include <2geom/affine.h> +#include <2geom/point.h> #include #include "CharTypes.h" @@ -47,8 +47,8 @@ class XRef; class SPCSSAttr; -#include #include +#include namespace Inkscape { namespace Extension { @@ -61,87 +61,80 @@ struct SvgTransparencyGroup; * Could be later used to store other graphics state parameters so that we could * emit only the differences in style settings from the parent state. */ -struct SvgGraphicsState { +struct SvgGraphicsState +{ Inkscape::XML::Node *softmask; // Points to current softmask node - int group_depth; // Depth of nesting groups at this level + int group_depth; // Depth of nesting groups at this level }; /** * Holds information about glyphs added by PdfParser which haven't been added * to the document yet. */ -struct SvgGlyph { - Geom::Point position; // Absolute glyph coords +struct SvgGlyph +{ + Geom::Point position; // Absolute glyph coords Geom::Point text_position; // Absolute glyph coords in text space - double dx; // X advance value - double dy; // Y advance value - double rise; // Text rise parameter - Glib::ustring code; // UTF-8 coded character + double dx; // X advance value + double dy; // Y advance value + double rise; // Text rise parameter + Glib::ustring code; // UTF-8 coded character bool is_space; - bool style_changed; // Set to true if style has to be reset + bool style_changed; // Set to true if style has to be reset SPCSSAttr *style; - int render_mode; // Text render mode - const char *font_specification; // Pointer to current font specification + int render_mode; // Text render mode + const char *font_specification; // Pointer to current font specification }; /** * Builds the inner SVG representation using libpoppler from the calls of PdfParser. */ -class SvgBuilder { +class SvgBuilder +{ public: SvgBuilder(SPDocument *document, gchar *docname, XRef *xref); SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root); virtual ~SvgBuilder(); // Property setting - void setDocumentSize(double width, double height); // Document size in px - void setAsLayer(char *layer_name=nullptr); + void setDocumentSize(double width, double height); // Document size in px + void setAsLayer(char *layer_name = nullptr); void setGroupOpacity(double opacity); - Inkscape::XML::Node *getPreferences() { - return _preferences; - } + Inkscape::XML::Node *getPreferences() { return _preferences; } // Handling the node stack Inkscape::XML::Node *pushGroup(); Inkscape::XML::Node *popGroup(); - Inkscape::XML::Node *getContainer(); // Returns current group node + Inkscape::XML::Node *getContainer(); // Returns current group node // Path adding - void addPath(GfxState *state, bool fill, bool stroke, bool even_odd=false); - void addShadedFill(GfxShading *shading, double *matrix, GfxPath *path, bool even_odd=false); + void addPath(GfxState *state, bool fill, bool stroke, bool even_odd = false); + void addShadedFill(GfxShading *shading, double *matrix, GfxPath *path, bool even_odd = false); // Image handling - void addImage(GfxState *state, Stream *str, int width, int height, - GfxImageColorMap *color_map, bool interpolate, int *mask_colors); - void addImageMask(GfxState *state, Stream *str, int width, int height, - bool invert, bool interpolate); - void addMaskedImage(GfxState *state, Stream *str, int width, int height, - GfxImageColorMap *color_map, bool interpolate, - Stream *mask_str, int mask_width, int mask_height, - bool invert_mask, bool mask_interpolate); - void addSoftMaskedImage(GfxState *state, Stream *str, int width, int height, - GfxImageColorMap *color_map, bool interpolate, - Stream *mask_str, int mask_width, int mask_height, + void addImage(GfxState *state, Stream *str, int width, int height, GfxImageColorMap *color_map, bool interpolate, + int *mask_colors); + void addImageMask(GfxState *state, Stream *str, int width, int height, bool invert, bool interpolate); + void addMaskedImage(GfxState *state, Stream *str, int width, int height, GfxImageColorMap *color_map, + bool interpolate, Stream *mask_str, int mask_width, int mask_height, bool invert_mask, + bool mask_interpolate); + void addSoftMaskedImage(GfxState *state, Stream *str, int width, int height, GfxImageColorMap *color_map, + bool interpolate, Stream *mask_str, int mask_width, int mask_height, GfxImageColorMap *mask_color_map, bool mask_interpolate); // Transparency group and soft mask handling - void pushTransparencyGroup(GfxState *state, double *bbox, - GfxColorSpace *blending_color_space, - bool isolated, bool knockout, - bool for_softmask); + void pushTransparencyGroup(GfxState *state, double *bbox, GfxColorSpace *blending_color_space, bool isolated, + bool knockout, bool for_softmask); void popTransparencyGroup(GfxState *state); void paintTransparencyGroup(GfxState *state, double *bbox); - void setSoftMask(GfxState *state, double *bbox, bool alpha, - Function *transfer_func, GfxColor *backdrop_color); + void setSoftMask(GfxState *state, double *bbox, bool alpha, Function *transfer_func, GfxColor *backdrop_color); void clearSoftMask(GfxState *state); // Text handling void beginString(GfxState *state); void endString(GfxState *state); - void addChar(GfxState *state, double x, double y, - double dx, double dy, - double originX, double originY, + void addChar(GfxState *state, double x, double y, double dx, double dy, double originX, double originY, CharCode code, int nBytes, Unicode const *u, int uLen); void beginTextObject(GfxState *state); void endTextObject(GfxState *state); @@ -158,12 +151,11 @@ public: void updateTextMatrix(GfxState *state); // Clipping - void clip(GfxState *state, bool even_odd=false); - void setClipPath(GfxState *state, bool even_odd=false); + void clip(GfxState *state, bool even_odd = false); + void setClipPath(GfxState *state, bool even_odd = false); // Transforming - void setTransform(double c0, double c1, double c2, double c3, double c4, - double c5); + void setTransform(double c0, double c1, double c2, double c3, double c4, double c5); void setTransform(double const *transform); bool getTransform(double *transform); @@ -171,65 +163,59 @@ private: void _init(); // Pattern creation - gchar *_createPattern(GfxPattern *pattern, GfxState *state, bool is_stroke=false); - gchar *_createGradient(GfxShading *shading, double *matrix, bool for_shading=false); - void _addStopToGradient(Inkscape::XML::Node *gradient, double offset, - GfxRGB *color, double opacity); - bool _addGradientStops(Inkscape::XML::Node *gradient, GfxShading *shading, - _POPPLER_CONST Function *func); - gchar *_createTilingPattern(GfxTilingPattern *tiling_pattern, GfxState *state, - bool is_stroke=false); + gchar *_createPattern(GfxPattern *pattern, GfxState *state, bool is_stroke = false); + gchar *_createGradient(GfxShading *shading, double *matrix, bool for_shading = false); + void _addStopToGradient(Inkscape::XML::Node *gradient, double offset, GfxRGB *color, double opacity); + bool _addGradientStops(Inkscape::XML::Node *gradient, GfxShading *shading, _POPPLER_CONST Function *func); + gchar *_createTilingPattern(GfxTilingPattern *tiling_pattern, GfxState *state, bool is_stroke = false); // Image/mask creation - Inkscape::XML::Node *_createImage(Stream *str, int width, int height, - GfxImageColorMap *color_map, bool interpolate, - int *mask_colors, bool alpha_only=false, - bool invert_alpha=false); + Inkscape::XML::Node *_createImage(Stream *str, int width, int height, GfxImageColorMap *color_map, bool interpolate, + int *mask_colors, bool alpha_only = false, bool invert_alpha = false); Inkscape::XML::Node *_createMask(double width, double height); // Style setting - SPCSSAttr *_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd=false); + SPCSSAttr *_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd = false); void _setStrokeStyle(SPCSSAttr *css, GfxState *state); void _setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd); void _setBlendMode(Inkscape::XML::Node *node, GfxState *state); - void _flushText(); // Write buffered text into doc + void _flushText(); // Write buffered text into doc std::string _BestMatchingFont(std::string PDFname); // Handling of node stack - Inkscape::XML::Node *pushNode(const char* name); + Inkscape::XML::Node *pushNode(const char *name); Inkscape::XML::Node *popNode(); std::vector _node_stack; - std::vector _group_depth; // Depth of nesting groups - SvgTransparencyGroup *_transp_group_stack; // Transparency group stack + std::vector _group_depth; // Depth of nesting groups + SvgTransparencyGroup *_transp_group_stack; // Transparency group stack std::vector _state_stack; - SPCSSAttr *_font_style; // Current font style + SPCSSAttr *_font_style; // Current font style GfxFont *_current_font; const char *_font_specification; double _font_scaling; bool _need_font_update; Geom::Affine _text_matrix; Geom::Point _text_position; - std::vector _glyphs; // Added characters - bool _in_text_object; // Whether we are inside a text object + std::vector _glyphs; // Added characters + bool _in_text_object; // Whether we are inside a text object bool _invalidated_style; GfxState *_current_state; std::vector _availableFontNames; // Full names, used for matching font names (Bug LP #179589). - bool _is_top_level; // Whether this SvgBuilder is the top-level one + bool _is_top_level; // Whether this SvgBuilder is the top-level one SPDocument *_doc; - gchar *_docname; // Basename of the URI from which this document is created - XRef *_xref; // Cross-reference table from the PDF doc we're converting from + gchar *_docname; // Basename of the URI from which this document is created + XRef *_xref; // Cross-reference table from the PDF doc we're converting from Inkscape::XML::Document *_xml_doc; - Inkscape::XML::Node *_root; // Root node from the point of view of this SvgBuilder - Inkscape::XML::Node *_container; // Current container (group/pattern/mask) - Inkscape::XML::Node *_preferences; // Preferences container node - double _width; // Document size in px - double _height; // Document size in px - double _ttm[6]; ///< temporary transform matrix + Inkscape::XML::Node *_root; // Root node from the point of view of this SvgBuilder + Inkscape::XML::Node *_container; // Current container (group/pattern/mask) + Inkscape::XML::Node *_preferences; // Preferences container node + double _width; // Document size in px + double _height; // Document size in px + double _ttm[6]; ///< temporary transform matrix bool _ttm_is_set; }; - } // namespace Internal } // namespace Extension } // namespace Inkscape diff --git a/src/extension/internal/pov-out.cpp b/src/extension/internal/pov-out.cpp index 96daafb034478840057acb8fbea2048989fe1b5c..37026695bc23daf6c328007c601b1cb2eb3ac836 100644 --- a/src/extension/internal/pov-out.cpp +++ b/src/extension/internal/pov-out.cpp @@ -19,35 +19,30 @@ */ #include "pov-out.h" -#include -#include -#include -#include + +#include <2geom/curves.h> #include <2geom/pathvector.h> #include <2geom/rect.h> -#include <2geom/curves.h> -#include "helper/geom.h" -#include "helper/geom-curves.h" +#include +#include +#include +#include +#include +#include #include - -#include "object/sp-root.h" -#include "object/sp-path.h" -#include "style.h" - #include -#include -#include + #include "document.h" #include "extension/extension.h" +#include "helper/geom-curves.h" +#include "helper/geom.h" +#include "object/sp-path.h" +#include "object/sp-root.h" +#include "style.h" - -namespace Inkscape -{ -namespace Extension -{ -namespace Internal -{ - +namespace Inkscape { +namespace Extension { +namespace Internal { //######################################################################## //# M E S S A G E S @@ -56,22 +51,17 @@ namespace Internal static void err(const char *fmt, ...) { va_list args; - g_log(nullptr, G_LOG_LEVEL_WARNING, "Pov-out err: "); + g_log(nullptr, G_LOG_LEVEL_WARNING, "Pov-out err: "); va_start(args, fmt); g_logv(nullptr, G_LOG_LEVEL_WARNING, fmt, args); va_end(args); - g_log(nullptr, G_LOG_LEVEL_WARNING, "\n"); + g_log(nullptr, G_LOG_LEVEL_WARNING, "\n"); } - - - //######################################################################## //# U T I L I T Y //######################################################################## - - static double effective_opacity(SPItem const *item) { // TODO investigate this. The early return seems that it would abort early. @@ -84,42 +74,35 @@ static double effective_opacity(SPItem const *item) return ret; } - - - - //######################################################################## //# OUTPUT FORMATTING //######################################################################## -PovOutput::PovOutput() : - outbuf (), - nrNodes (0), - nrSegments (0), - nrShapes (0), - idIndex (0), - minx (0), - miny (0), - maxx (0), - maxy (0) -{ -} +PovOutput::PovOutput() + : outbuf() + , nrNodes(0) + , nrSegments(0) + , nrShapes(0) + , idIndex(0) + , minx(0) + , miny(0) + , maxx(0) + , maxy(0) +{} /** * We want to control floating output format */ static PovOutput::String dstr(double d) { - char dbuf[G_ASCII_DTOSTR_BUF_SIZE+1]; - g_ascii_formatd(dbuf, G_ASCII_DTOSTR_BUF_SIZE, - "%.8f", (gdouble)d); + char dbuf[G_ASCII_DTOSTR_BUF_SIZE + 1]; + g_ascii_formatd(dbuf, G_ASCII_DTOSTR_BUF_SIZE, "%.8f", (gdouble)d); PovOutput::String s = dbuf; return s; } #define DSTR(d) (dstr(d).c_str()) - /** * Output data to the buffer, printf()-style */ @@ -133,10 +116,6 @@ void PovOutput::out(const char *fmt, ...) g_free(output); } - - - - /** * Output a 2d vector */ @@ -145,8 +124,6 @@ void PovOutput::vec2(double a, double b) out("<%s, %s>", DSTR(a), DSTR(b)); } - - /** * Output a 3d vector */ @@ -155,8 +132,6 @@ void PovOutput::vec3(double a, double b, double c) out("<%s, %s, %s>", DSTR(a), DSTR(b), DSTR(c)); } - - /** * Output a v4d ector */ @@ -165,8 +140,6 @@ void PovOutput::vec4(double a, double b, double c, double d) out("<%s, %s, %s, %s>", DSTR(a), DSTR(b), DSTR(c), DSTR(d)); } - - /** * Output an rgbf color vector */ @@ -177,32 +150,23 @@ void PovOutput::rgbf(double r, double g, double b, double f) vec4(r, g, b, f); } - - /** * Output one bezier's start, start-control, end-control, and end nodes */ -void PovOutput::segment(int segNr, - double startX, double startY, - double startCtrlX, double startCtrlY, - double endCtrlX, double endCtrlY, - double endX, double endY) +void PovOutput::segment(int segNr, double startX, double startY, double startCtrlX, double startCtrlY, double endCtrlX, + double endCtrlY, double endX, double endY) { //" /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>" out(" /*%4d*/ ", segNr); - vec2(startX, startY); + vec2(startX, startY); out(", "); vec2(startCtrlX, startCtrlY); out(", "); - vec2(endCtrlX, endCtrlY); + vec2(endCtrlX, endCtrlY); out(", "); - vec2(endX, endY); + vec2(endX, endY); } - - - - /** * Output the file header */ @@ -212,7 +176,7 @@ bool PovOutput::doHeader() out("/*###################################################################\n"); out("### This PovRay document was generated by Inkscape\n"); out("### http://www.inkscape.org\n"); - out("### Created: %s", ctime(&tim)); + out("### Created: %s", ctime(&tim)); out("### Version: %s\n", Inkscape::version_string); out("#####################################################################\n"); out("### NOTES:\n"); @@ -245,8 +209,6 @@ bool PovOutput::doHeader() return true; } - - /** * Output the file footer */ @@ -260,8 +222,6 @@ bool PovOutput::doTail() return true; } - - /** * Output the curve data to buffer */ @@ -271,7 +231,7 @@ bool PovOutput::doCurve(SPItem *item, const String &id) using Geom::Y; //### Get the Shape - if (!SP_IS_SHAPE(item))//Bulia's suggestion. Allow all shapes + if (!SP_IS_SHAPE(item)) // Bulia's suggestion. Allow all shapes return true; SPShape *shape = SP_SHAPE(item); @@ -282,34 +242,35 @@ bool PovOutput::doCurve(SPItem *item, const String &id) nrShapes++; PovShapeInfo shapeInfo; - shapeInfo.id = id; + shapeInfo.id = id; shapeInfo.color = ""; - //Try to get the fill color of the shape + // Try to get the fill color of the shape SPStyle *style = shape->style; /* fixme: Handle other fill types, even if this means translating gradients to a single flat colour. */ - if (style) - { - if (style->fill.isColor()) - { + if (style) { + if (style->fill.isColor()) { // see color.h for how to parse SPColor float rgb[3]; style->fill.value.color.get_rgb_floatv(rgb); - double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value) - * effective_opacity(shape) ); - //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>", + double const dopacity = (SP_SCALE24_TO_FLOAT(style->fill_opacity.value) * effective_opacity(shape)); + // gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>", // rgb[0], rgb[1], rgb[2], 1.0 - dopacity); String rgbf = "rgbf <"; - rgbf.append(dstr(rgb[0])); rgbf.append(", "); - rgbf.append(dstr(rgb[1])); rgbf.append(", "); - rgbf.append(dstr(rgb[2])); rgbf.append(", "); - rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">"); + rgbf.append(dstr(rgb[0])); + rgbf.append(", "); + rgbf.append(dstr(rgb[1])); + rgbf.append(", "); + rgbf.append(dstr(rgb[2])); + rgbf.append(", "); + rgbf.append(dstr(1.0 - dopacity)); + rgbf.append(">"); shapeInfo.color += rgbf; - } } + } - povShapes.push_back(shapeInfo); //passed all tests. save the info + povShapes.push_back(shapeInfo); // passed all tests. save the info // convert the path to only lineto's and cubic curveto's: Geom::Affine tf = item->i2dt_affine(); @@ -325,16 +286,14 @@ bool PovOutput::doCurve(SPItem *item, const String &id) /** * For all Subpaths in the */ - for (const auto & pit : pathv) - { + for (const auto &pit : pathv) { /** * For all segments in the subpath, including extra closing segment defined by 2geom */ - for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_closed(); ++cit) - { - + for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_closed(); ++cit) { // Skip zero length segments. - if( !cit->isDegenerate() ) ++segmentCount; + if (!cit->isDegenerate()) + ++segmentCount; } } @@ -354,66 +313,52 @@ bool PovOutput::doCurve(SPItem *item, const String &id) /** * at moment of writing, 2geom lacks proper initialization of empty intervals in rect... */ - Geom::Rect cminmax( pathv.front().initialPoint(), pathv.front().initialPoint() ); - + Geom::Rect cminmax(pathv.front().initialPoint(), pathv.front().initialPoint()); /** * For all Subpaths in the */ - for (const auto & pit : pathv) - { - + for (const auto &pit : pathv) { cminmax.expandTo(pit.initialPoint()); /** * For all segments in the subpath, including extra closing segment defined by 2geom */ - for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_closed(); ++cit) - { - + for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_closed(); ++cit) { // Skip zero length segments - if( cit->isDegenerate() ) + if (cit->isDegenerate()) continue; - if( is_straight_curve(*cit) ) - { + if (is_straight_curve(*cit)) { Geom::Point p0 = cit->initialPoint(); Geom::Point p1 = cit->finalPoint(); - segment(segmentNr++, - p0[X], p0[Y], p0[X], p0[Y], p1[X], p1[Y], p1[X], p1[Y] ); + segment(segmentNr++, p0[X], p0[Y], p0[X], p0[Y], p1[X], p1[Y], p1[X], p1[Y]); nrNodes += 8; - } - else if(Geom::CubicBezier const *cubic = dynamic_cast(&*cit)) - { + } else if (Geom::CubicBezier const *cubic = dynamic_cast(&*cit)) { std::vector points = cubic->controlPoints(); Geom::Point p0 = points[0]; Geom::Point p1 = points[1]; Geom::Point p2 = points[2]; Geom::Point p3 = points[3]; - segment(segmentNr++, - p0[X],p0[Y], p1[X],p1[Y], p2[X],p2[Y], p3[X],p3[Y]); + segment(segmentNr++, p0[X], p0[Y], p1[X], p1[Y], p2[X], p2[Y], p3[X], p3[Y]); nrNodes += 8; - } - else - { + } else { err("logical error, because pathv_to_linear_and_cubic_beziers was used"); return false; - } + } if (segmentNr < segmentCount) out(",\n"); else out("\n"); - if (segmentNr > segmentCount) - { + if (segmentNr > segmentCount) { err("Too many segments"); return false; - } + } cminmax.expandTo(cit->finalPoint()); - - } } + } out("}\n"); @@ -423,16 +368,15 @@ bool PovOutput::doCurve(SPItem *item, const String &id) double cmaxy = cminmax.max()[Y]; out("#declare %s_MIN_X = %s;\n", id.c_str(), DSTR(cminx)); - out("#declare %s_CENTER_X = %s;\n", id.c_str(), DSTR((cmaxx+cminx)/2.0)); + out("#declare %s_CENTER_X = %s;\n", id.c_str(), DSTR((cmaxx + cminx) / 2.0)); out("#declare %s_MAX_X = %s;\n", id.c_str(), DSTR(cmaxx)); - out("#declare %s_WIDTH = %s;\n", id.c_str(), DSTR(cmaxx-cminx)); + out("#declare %s_WIDTH = %s;\n", id.c_str(), DSTR(cmaxx - cminx)); out("#declare %s_MIN_Y = %s;\n", id.c_str(), DSTR(cminy)); - out("#declare %s_CENTER_Y = %s;\n", id.c_str(), DSTR((cmaxy+cminy)/2.0)); + out("#declare %s_CENTER_Y = %s;\n", id.c_str(), DSTR((cmaxy + cminy) / 2.0)); out("#declare %s_MAX_Y = %s;\n", id.c_str(), DSTR(cmaxy)); - out("#declare %s_HEIGHT = %s;\n", id.c_str(), DSTR(cmaxy-cminy)); - if (shapeInfo.color.length()>0) - out("#declare %s_COLOR = %s;\n", - id.c_str(), shapeInfo.color.c_str()); + out("#declare %s_HEIGHT = %s;\n", id.c_str(), DSTR(cmaxy - cminy)); + if (shapeInfo.color.length() > 0) + out("#declare %s_COLOR = %s;\n", id.c_str(), shapeInfo.color.c_str()); out("/*###################################################\n"); out("### end %s\n", id.c_str()); out("###################################################*/\n\n\n\n"); @@ -454,34 +398,28 @@ bool PovOutput::doCurve(SPItem *item, const String &id) */ bool PovOutput::doTreeRecursive(SPDocument *doc, SPObject *obj) { - String id; - if (!obj->getId()) - { + if (!obj->getId()) { char buf[16]; sprintf(buf, "id%d", idIndex++); id = buf; - } - else - { - id = obj->getId(); - } + } else { + id = obj->getId(); + } - if (SP_IS_ITEM(obj)) - { + if (SP_IS_ITEM(obj)) { SPItem *item = SP_ITEM(obj); if (!doCurve(item, id)) return false; - } + } /** * Descend into children */ - for (auto &child: obj->children) - { - if (!doTreeRecursive(doc, &child)) - return false; - } + for (auto &child : obj->children) { + if (!doTreeRecursive(doc, &child)) + return false; + } return true; } @@ -492,17 +430,16 @@ bool PovOutput::doTreeRecursive(SPDocument *doc, SPObject *obj) bool PovOutput::doTree(SPDocument *doc) { double bignum = 1000000.0; - minx = bignum; - maxx = -bignum; - miny = bignum; - maxy = -bignum; + minx = bignum; + maxx = -bignum; + miny = bignum; + maxy = -bignum; if (!doTreeRecursive(doc, doc->getRoot())) return false; //## Let's make a union of all of the Shapes - if (!povShapes.empty()) - { + if (!povShapes.empty()) { String id = "AllShapes"; char *pfx = (char *)id.c_str(); out("/*###################################################\n"); @@ -522,22 +459,20 @@ bool PovOutput::doTree(SPDocument *doc) out("#end\n"); out("\n\n"); out("#declare %s = union {\n", id.c_str()); - for (auto & povShape : povShapes) - { + for (auto &povShape : povShapes) { out(" object { %s\n", povShape.id.c_str()); out(" texture { \n"); - if (povShape.color.length()>0) + if (povShape.color.length() > 0) out(" pigment { %s }\n", povShape.color.c_str()); else out(" pigment { rgb <0,0,0> }\n"); out(" finish { %s_Finish }\n", pfx); out(" } \n"); out(" } \n"); - } + } out("}\n\n\n\n"); - - double zinc = 0.2 / (double)povShapes.size(); + double zinc = 0.2 / (double)povShapes.size(); out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n"); out("\n\n"); out("/**\n"); @@ -551,11 +486,10 @@ bool PovOutput::doTree(SPDocument *doc) out("\n\n"); out("#declare %s_Z = union {\n", pfx); - for (auto & povShape : povShapes) - { + for (auto &povShape : povShapes) { out(" object { %s\n", povShape.id.c_str()); out(" texture { \n"); - if (povShape.color.length()>0) + if (povShape.color.length() > 0) out(" pigment { %s }\n", povShape.color.c_str()); else out(" pigment { rgb <0,0,0> }\n"); @@ -563,51 +497,45 @@ bool PovOutput::doTree(SPDocument *doc) out(" } \n"); out(" scale <1, %s_Z_Scale, 1>\n", pfx); out(" } \n"); - out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n", - pfx, pfx, pfx); - } + out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n", pfx, pfx, pfx); + } out("}\n"); out("#declare %s_MIN_X = %s;\n", pfx, DSTR(minx)); - out("#declare %s_CENTER_X = %s;\n", pfx, DSTR((maxx+minx)/2.0)); + out("#declare %s_CENTER_X = %s;\n", pfx, DSTR((maxx + minx) / 2.0)); out("#declare %s_MAX_X = %s;\n", pfx, DSTR(maxx)); - out("#declare %s_WIDTH = %s;\n", pfx, DSTR(maxx-minx)); + out("#declare %s_WIDTH = %s;\n", pfx, DSTR(maxx - minx)); out("#declare %s_MIN_Y = %s;\n", pfx, DSTR(miny)); - out("#declare %s_CENTER_Y = %s;\n", pfx, DSTR((maxy+miny)/2.0)); + out("#declare %s_CENTER_Y = %s;\n", pfx, DSTR((maxy + miny) / 2.0)); out("#declare %s_MAX_Y = %s;\n", pfx, DSTR(maxy)); - out("#declare %s_HEIGHT = %s;\n", pfx, DSTR(maxy-miny)); + out("#declare %s_HEIGHT = %s;\n", pfx, DSTR(maxy - miny)); out("/*##############################################\n"); out("### end %s\n", id.c_str()); out("##############################################*/\n"); out("\n\n"); - } + } return true; } - //######################################################################## //# M A I N O U T P U T //######################################################################## - - /** * Set values back to initial state */ void PovOutput::reset() { - nrNodes = 0; + nrNodes = 0; nrSegments = 0; - nrShapes = 0; - idIndex = 0; + nrShapes = 0; + idIndex = 0; outbuf.clear(); povShapes.clear(); } - - /** * Saves the Shapes of an Inkscape SVG file as PovRay spline definitions */ @@ -617,31 +545,25 @@ void PovOutput::saveDocument(SPDocument *doc, gchar const *filename_utf8) //###### SAVE IN POV FORMAT TO BUFFER //# Lets do the curves first, to get the stats - if (!doTree(doc)) - { + if (!doTree(doc)) { err("Could not output curves for %s", filename_utf8); return; - } + } String curveBuf = outbuf; outbuf.clear(); - if (!doHeader()) - { + if (!doHeader()) { err("Could not write header for %s", filename_utf8); return; - } + } outbuf.append(curveBuf); - if (!doTail()) - { + if (!doTail()) { err("Could not write footer for %s", filename_utf8); return; - } - - - + } //###### WRITE TO FILE Inkscape::IO::dump_fopen_call(filename_utf8, "L"); @@ -649,45 +571,33 @@ void PovOutput::saveDocument(SPDocument *doc, gchar const *filename_utf8) if (!f) return; - for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); ++iter) - { + for (String::iterator iter = outbuf.begin(); iter != outbuf.end(); ++iter) { int ch = *iter; fputc(ch, f); - } + } fclose(f); } - - - //######################################################################## //# EXTENSION API //######################################################################## - - #include "clear-n_.h" - - /** * API call to save document -*/ -void -PovOutput::save(Inkscape::Extension::Output */*mod*/, - SPDocument *doc, gchar const *filename_utf8) + */ +void PovOutput::save(Inkscape::Extension::Output * /*mod*/, SPDocument *doc, gchar const *filename_utf8) { /* See comments in JavaFSOutput::save re the name `filename_utf8'. */ saveDocument(doc, filename_utf8); } - - /** * Make sure that we are in the database */ -bool PovOutput::check (Inkscape::Extension::Extension */*module*/) +bool PovOutput::check(Inkscape::Extension::Extension * /*module*/) { /* We don't need a Key if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV)) @@ -697,15 +607,12 @@ bool PovOutput::check (Inkscape::Extension::Extension */*module*/) return true; } - - /** * This is the definition of PovRay output. This function just * calls the extension system with the memory allocated XML that * describes the data. -*/ -void -PovOutput::init() + */ +void PovOutput::init() { // clang-format off Inkscape::Extension::build_from_mem( @@ -723,14 +630,9 @@ PovOutput::init() // clang-format on } - - - - -} // namespace Internal -} // namespace Extension -} // namespace Inkscape - +} // namespace Internal +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/internal/pov-out.h b/src/extension/internal/pov-out.h index 3dee88be8cf9cdd2b0d96dfc0ff5e41cb9066be3..9f94447b6ab66edbd124af95a2c956ff3c106966 100644 --- a/src/extension/internal/pov-out.h +++ b/src/extension/internal/pov-out.h @@ -18,67 +18,57 @@ #define EXTENSION_INTERNAL_POV_OUT_H #include + #include "extension/implementation/implementation.h" class SPObject; class SPItem; -namespace Inkscape -{ -namespace Extension -{ -namespace Internal -{ - - +namespace Inkscape { +namespace Extension { +namespace Internal { /** * Output bezier splines in POVRay format. - * - * For information, @see: - * http://www.povray.org - */ + * + * For information, @see: + * http://www.povray.org + */ class PovOutput : public Inkscape::Extension::Implementation::Implementation { - - public: - PovOutput(); - + /** * Our internal String definition */ typedef Glib::ustring String; - /** * Check whether we can actually output using this module */ - bool check (Inkscape::Extension::Extension * module) override; + bool check(Inkscape::Extension::Extension *module) override; /** * API call to perform the output to a file */ - void save(Inkscape::Extension::Output *mod, - SPDocument *doc, gchar const *filename) override; + void save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) override; /** * Inkscape runtime startup call. */ - static void init(); - + static void init(); + /** * Reset variables to initial state */ - void reset(); - -private: + void reset(); - /** - * Format text to our output buffer - */ - void out(const char *fmt, ...) G_GNUC_PRINTF(2,3); +private: + /** + * Format text to our output buffer + */ + void out(const char *fmt, ...) G_GNUC_PRINTF(2, 3); /** * Output a 2d vector @@ -101,14 +91,10 @@ private: void rgbf(double r, double g, double b, double f); /** - * Output one bezier's start, start-control, + * Output one bezier's start, start-control, * end-control, and end nodes */ - void segment(int segNr, double a0, double a1, - double b0, double b1, - double c0, double c1, - double d0, double d1); - + void segment(int segNr, double a0, double a1, double b0, double b1, double c0, double c1, double d0, double d1); /** * Output the file header @@ -132,59 +118,51 @@ private: */ void saveDocument(SPDocument *doc, gchar const *filename); - /** * used for saving information about shapes */ class PovShapeInfo { public: - PovShapeInfo() - = default; - PovShapeInfo(const PovShapeInfo &other) - { assign(other); } - PovShapeInfo& operator=(const PovShapeInfo &other) - { assign(other); return *this; } - virtual ~PovShapeInfo() - = default; + PovShapeInfo() = default; + PovShapeInfo(const PovShapeInfo &other) { assign(other); } + PovShapeInfo &operator=(const PovShapeInfo &other) + { + assign(other); + return *this; + } + virtual ~PovShapeInfo() = default; String id; String color; private: void assign(const PovShapeInfo &other) - { - id = other.id; + { + id = other.id; color = other.color; - } + } }; - //A list for saving information about the shapes + // A list for saving information about the shapes std::vector povShapes; - - //For formatted output - String outbuf; - //For statistics + // For formatted output + String outbuf; + + // For statistics int nrNodes; int nrSegments; int nrShapes; int idIndex; - + double minx; double miny; double maxx; double maxy; - }; - - - -} // namespace Internal -} // namespace Extension -} // namespace Inkscape - - +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* EXTENSION_INTERNAL_POV_OUT_H */ - diff --git a/src/extension/internal/svg.cpp b/src/extension/internal/svg.cpp index 39da17687561b20eb7281196e5b04e7216363650..43918dbde20abb56dfcd12698e725e226dff53bf 100644 --- a/src/extension/internal/svg.cpp +++ b/src/extension/internal/svg.cpp @@ -15,32 +15,26 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "svg.h" #include -#include +#include +#include "display/cairo-utils.h" #include "document.h" -#include "inkscape.h" -#include "preferences.h" -#include "extension/output.h" #include "extension/input.h" +#include "extension/output.h" #include "extension/system.h" #include "file.h" -#include "svg.h" -#include "file.h" -#include "display/cairo-utils.h" -#include "extension/system.h" -#include "extension/output.h" -#include "xml/attribute-record.h" -#include "xml/simple-document.h" - +#include "inkscape.h" #include "object/sp-image.h" #include "object/sp-root.h" #include "object/sp-text.h" - -#include "util/units.h" +#include "preferences.h" #include "selection-chemistry.h" +#include "util/units.h" +#include "xml/attribute-record.h" +#include "xml/simple-document.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -51,7 +45,6 @@ namespace Internal { #include "clear-n_.h" - using Inkscape::Util::List; using Inkscape::XML::AttributeRecord; using Inkscape::XML::Node; @@ -60,32 +53,32 @@ using Inkscape::XML::Node; * Removes all sodipodi and inkscape elements and attributes from an xml tree. * used to make plain svg output. */ -static void pruneExtendedNamespaces( Inkscape::XML::Node *repr ) +static void pruneExtendedNamespaces(Inkscape::XML::Node *repr) { if (repr) { - if ( repr->type() == Inkscape::XML::ELEMENT_NODE ) { - std::vector attrsRemoved; - for ( List it = repr->attributeList(); it; ++it ) { - const gchar* attrName = g_quark_to_string(it->key); + if (repr->type() == Inkscape::XML::ELEMENT_NODE) { + std::vector attrsRemoved; + for (List it = repr->attributeList(); it; ++it) { + const gchar *attrName = g_quark_to_string(it->key); if ((strncmp("inkscape:", attrName, 9) == 0) || (strncmp("sodipodi:", attrName, 9) == 0)) { attrsRemoved.push_back(attrName); } } // Can't change the set we're iterating over while we are iterating. - for (auto & it : attrsRemoved) { + for (auto &it : attrsRemoved) { repr->removeAttribute(it); } } std::vector nodesRemoved; - for ( Node *child = repr->firstChild(); child; child = child->next() ) { - if((strncmp("inkscape:", child->name(), 9) == 0) || strncmp("sodipodi:", child->name(), 9) == 0) { + for (Node *child = repr->firstChild(); child; child = child->next()) { + if ((strncmp("inkscape:", child->name(), 9) == 0) || strncmp("sodipodi:", child->name(), 9) == 0) { nodesRemoved.push_back(child); } else { pruneExtendedNamespaces(child); } } - for (auto & it : nodesRemoved) { + for (auto &it : nodesRemoved) { repr->removeChild(it); } } @@ -96,19 +89,20 @@ static void pruneExtendedNamespaces( Inkscape::XML::Node *repr ) * to remove problematic elements (for example Adobe's i:pgf tag) only removes * known garbage tags. */ -static void pruneProprietaryGarbage( Inkscape::XML::Node *repr ) +static void pruneProprietaryGarbage(Inkscape::XML::Node *repr) { if (repr) { std::vector nodesRemoved; - for ( Node *child = repr->firstChild(); child; child = child->next() ) { - if((strncmp("i:pgf", child->name(), 5) == 0)) { + for (Node *child = repr->firstChild(); child; child = child->next()) { + if ((strncmp("i:pgf", child->name(), 5) == 0)) { nodesRemoved.push_back(child); - g_warning( "An Adobe proprietary tag was found which is known to cause issues. It was removed before saving."); + g_warning( + "An Adobe proprietary tag was found which is known to cause issues. It was removed before saving."); } else { pruneProprietaryGarbage(child); } } - for (auto & it : nodesRemoved) { + for (auto &it : nodesRemoved) { repr->removeChild(it); } } @@ -126,42 +120,34 @@ static void pruneProprietaryGarbage( Inkscape::XML::Node *repr ) * \param property Which property to check, either 'marker' or 'marker-start'. * */ -static void remove_marker_auto_start_reverse(Inkscape::XML::Node *repr, - Inkscape::XML::Node *defs, - SPCSSAttr *css, +static void remove_marker_auto_start_reverse(Inkscape::XML::Node *repr, Inkscape::XML::Node *defs, SPCSSAttr *css, Glib::ustring const &property) { - Glib::ustring value = sp_repr_css_property (css, property.c_str(), ""); + Glib::ustring value = sp_repr_css_property(css, property.c_str(), ""); if (!value.empty()) { - // Find reference static Glib::RefPtr regex = Glib::Regex::create("url\\(#([A-z0-9#]*)\\)"); Glib::MatchInfo matchInfo; regex->match(value, matchInfo); if (matchInfo.matches()) { - auto marker_name = matchInfo.fetch(1).raw(); - Inkscape::XML::Node *marker = sp_repr_lookup_child (defs, "id", marker_name.c_str()); + Inkscape::XML::Node *marker = sp_repr_lookup_child(defs, "id", marker_name.c_str()); if (marker) { - // Does marker use "auto-start-reverse"? - if (strncmp(marker->attribute("orient"), "auto-start-reverse", 17)==0) { - + if (strncmp(marker->attribute("orient"), "auto-start-reverse", 17) == 0) { // See if a reversed marker already exists. auto marker_name_reversed = marker_name + "_reversed"; Inkscape::XML::Node *marker_reversed = - sp_repr_lookup_child (defs, "id", marker_name_reversed.c_str()); + sp_repr_lookup_child(defs, "id", marker_name_reversed.c_str()); if (!marker_reversed) { - // No reversed marker, need to create! marker_reversed = repr->document()->createElement("svg:marker"); // Copy attributes - for (List iter = marker->attributeList(); - iter ; ++iter) { + for (List iter = marker->attributeList(); iter; ++iter) { marker_reversed->setAttribute(g_quark_to_string(iter->key), iter->value); } @@ -170,8 +156,8 @@ static void remove_marker_auto_start_reverse(Inkscape::XML::Node *repr, marker_reversed->setAttribute("orient", "auto"); // Find transform - const char* refX = marker_reversed->attribute("refX"); - const char* refY = marker_reversed->attribute("refY"); + const char *refX = marker_reversed->attribute("refX"); + const char *refY = marker_reversed->attribute("refY"); std::string transform = "rotate(180"; if (refX) { transform += ","; @@ -195,7 +181,7 @@ static void remove_marker_auto_start_reverse(Inkscape::XML::Node *repr, marker_reversed->addChild(group, nullptr); // Copy all marker content to group. - for (auto child = marker->firstChild() ; child != nullptr ; child = child->next() ) { + for (auto child = marker->firstChild(); child != nullptr; child = child->next()) { auto new_child = child->duplicate(repr->document()); group->addChild(new_child, nullptr); new_child->release(); @@ -204,7 +190,7 @@ static void remove_marker_auto_start_reverse(Inkscape::XML::Node *repr, // Add new marker to . defs->addChild(marker_reversed, marker); marker_reversed->release(); - } + } // Change url to reference reversed marker. std::string marker_url("url(#" + marker_name_reversed + ")"); @@ -227,9 +213,7 @@ static void remove_marker_auto_start_reverse(Inkscape::XML::Node *repr, } // Called by remove_marker_context_paint() for each property value ("marker", "marker-start", ...). -static void remove_marker_context_paint (Inkscape::XML::Node *repr, - Inkscape::XML::Node *defs, - Glib::ustring property) +static void remove_marker_context_paint(Inkscape::XML::Node *repr, Inkscape::XML::Node *defs, Glib::ustring property) { // Value of 'marker', 'marker-start', ... property. std::string value("url(#"); @@ -237,15 +221,13 @@ static void remove_marker_context_paint (Inkscape::XML::Node *repr, value += ")"; // Generate a list of elements that reference this marker. - std::vector to_fix_fill_stroke = - sp_repr_lookup_property_many(repr->root(), property, value); - - for (auto it: to_fix_fill_stroke) { + std::vector to_fix_fill_stroke = sp_repr_lookup_property_many(repr->root(), property, value); + for (auto it : to_fix_fill_stroke) { // Figure out value of fill... could be inherited. - SPCSSAttr* css = sp_repr_css_attr_inherited (it, "style"); - Glib::ustring fill = sp_repr_css_property (css, "fill", ""); - Glib::ustring stroke = sp_repr_css_property (css, "stroke", ""); + SPCSSAttr *css = sp_repr_css_attr_inherited(it, "style"); + Glib::ustring fill = sp_repr_css_property(css, "fill", ""); + Glib::ustring stroke = sp_repr_css_property(css, "stroke", ""); // Name of new marker. Glib::ustring marker_fixed_id = repr->attribute("id"); @@ -258,34 +240,33 @@ static void remove_marker_context_paint (Inkscape::XML::Node *repr, // See if a fixed marker already exists. // Could be more robust, assumes markers are direct children of . - Inkscape::XML::Node* marker_fixed = sp_repr_lookup_child(defs, "id", marker_fixed_id.c_str()); + Inkscape::XML::Node *marker_fixed = sp_repr_lookup_child(defs, "id", marker_fixed_id.c_str()); if (!marker_fixed) { - // Need to create new marker. marker_fixed = repr->duplicate(repr->document()); marker_fixed->setAttribute("id", marker_fixed_id); // This needs to be turned into a function that fixes all descendents. - for (auto child = marker_fixed->firstChild() ; child != nullptr ; child = child->next()) { + for (auto child = marker_fixed->firstChild(); child != nullptr; child = child->next()) { // Find style. - SPCSSAttr* css = sp_repr_css_attr ( child, "style" ); + SPCSSAttr *css = sp_repr_css_attr(child, "style"); - Glib::ustring fill2 = sp_repr_css_property (css, "fill", ""); - if (fill2 == "context-fill" ) { - sp_repr_css_set_property (css, "fill", fill.c_str()); + Glib::ustring fill2 = sp_repr_css_property(css, "fill", ""); + if (fill2 == "context-fill") { + sp_repr_css_set_property(css, "fill", fill.c_str()); } - if (fill2 == "context-stroke" ) { - sp_repr_css_set_property (css, "fill", stroke.c_str()); + if (fill2 == "context-stroke") { + sp_repr_css_set_property(css, "fill", stroke.c_str()); } - Glib::ustring stroke2 = sp_repr_css_property (css, "stroke", ""); - if (stroke2 == "context-fill" ) { - sp_repr_css_set_property (css, "stroke", fill.c_str()); + Glib::ustring stroke2 = sp_repr_css_property(css, "stroke", ""); + if (stroke2 == "context-fill") { + sp_repr_css_set_property(css, "stroke", fill.c_str()); } - if (stroke2 == "context-stroke" ) { - sp_repr_css_set_property (css, "stroke", stroke.c_str()); + if (stroke2 == "context-stroke") { + sp_repr_css_set_property(css, "stroke", stroke.c_str()); } sp_repr_css_set(child, css, "style"); @@ -297,37 +278,30 @@ static void remove_marker_context_paint (Inkscape::XML::Node *repr, } Glib::ustring marker_value = "url(#" + marker_fixed_id + ")"; - sp_repr_css_set_property (css, property.c_str(), marker_value.c_str()); - sp_repr_css_set (it, css, "style"); + sp_repr_css_set_property(css, property.c_str(), marker_value.c_str()); + sp_repr_css_set(it, css, "style"); sp_repr_css_attr_unref(css); } } -static void remove_marker_context_paint (Inkscape::XML::Node *repr, - Inkscape::XML::Node *defs) +static void remove_marker_context_paint(Inkscape::XML::Node *repr, Inkscape::XML::Node *defs) { if (strncmp("svg:marker", repr->name(), 10) == 0) { - if (!repr->attribute("id")) { - std::cerr << "remove_marker_context_paint: without 'id'!" << std::endl; } else { - // First see if we need to do anything. bool need_to_fix = false; // This needs to be turned into a function that searches all descendents. - for (auto child = repr->firstChild() ; child != nullptr ; child = child->next()) { - + for (auto child = repr->firstChild(); child != nullptr; child = child->next()) { // Find style. - SPCSSAttr* css = sp_repr_css_attr ( child, "style" ); - Glib::ustring fill = sp_repr_css_property (css, "fill", ""); - Glib::ustring stroke = sp_repr_css_property (css, "stroke", ""); - if (fill == "context-fill" || - fill == "context-stroke" || - stroke == "context-fill" || - stroke == "context-stroke" ) { + SPCSSAttr *css = sp_repr_css_attr(child, "style"); + Glib::ustring fill = sp_repr_css_property(css, "fill", ""); + Glib::ustring stroke = sp_repr_css_property(css, "stroke", ""); + if (fill == "context-fill" || fill == "context-stroke" || stroke == "context-fill" || + stroke == "context-stroke") { need_to_fix = true; break; } @@ -335,12 +309,11 @@ static void remove_marker_context_paint (Inkscape::XML::Node *repr, } if (need_to_fix) { - // Now we need to search document for all elements that use this marker. - remove_marker_context_paint (repr, defs, "marker"); - remove_marker_context_paint (repr, defs, "marker-start"); - remove_marker_context_paint (repr, defs, "marker-mid"); - remove_marker_context_paint (repr, defs, "marker-end"); + remove_marker_context_paint(repr, defs, "marker"); + remove_marker_context_paint(repr, defs, "marker-start"); + remove_marker_context_paint(repr, defs, "marker-mid"); + remove_marker_context_paint(repr, defs, "marker-end"); } } } @@ -351,24 +324,22 @@ static void remove_marker_context_paint (Inkscape::XML::Node *repr, * Notes: * Text must have been layed out. Access via old document. */ -static void insert_text_fallback( Inkscape::XML::Node *repr, SPDocument *original_doc, Inkscape::XML::Node *defs = nullptr ) +static void insert_text_fallback(Inkscape::XML::Node *repr, SPDocument *original_doc, + Inkscape::XML::Node *defs = nullptr) { if (repr) { - if (strncmp("svg:text", repr->name(), 8) == 0) { - auto id = repr->attribute("id"); // std::cout << "insert_text_fallback: found text! id: " << (id?id:"null") << std::endl; // We need to get original SPText object to access layout. - SPText* text = static_cast(original_doc->getObjectById( id )); + SPText *text = static_cast(original_doc->getObjectById(id)); if (text == nullptr) { std::cerr << "insert_text_fallback: bad cast" << std::endl; return; } - if (!text->has_inline_size() && - !text->has_shape_inside()) { + if (!text->has_inline_size() && !text->has_shape_inside()) { // No SVG 2 text, nothing to do. return; } @@ -378,7 +349,7 @@ static void insert_text_fallback( Inkscape::XML::Node *repr, SPDocument *origina // For text in a shape, We need to unset 'text-anchor' or SVG 1.1 fallback won't work. // Note 'text' here refers to original document while 'repr' refers to new document copy. if (text->has_shape_inside()) { - SPCSSAttr *css = sp_repr_css_attr(repr, "style" ); + SPCSSAttr *css = sp_repr_css_attr(repr, "style"); sp_repr_css_unset_property(css, "text-anchor"); sp_repr_css_set(repr, css, "style"); sp_repr_css_attr_unref(css); @@ -386,8 +357,7 @@ static void insert_text_fallback( Inkscape::XML::Node *repr, SPDocument *origina // We need to put trailing white space into it's own tspan for inline size so // it is excluded during calculation of line position in SVG 1.1 renderers. - bool trim = text->has_inline_size() && - !(text->style->text_anchor.computed == SP_CSS_TEXT_ANCHOR_START); + bool trim = text->has_inline_size() && !(text->style->text_anchor.computed == SP_CSS_TEXT_ANCHOR_START); // Make a list of children to delete at end: std::vector old_children; @@ -405,8 +375,7 @@ static void insert_text_fallback( Inkscape::XML::Node *repr, SPDocument *origina // std::cout << "text_x: " << text_x << " text_y: " << text_y << std::endl; // Loop over all lines in layout. - for (auto it = text->layout.begin() ; it != text->layout.end() ; ) { - + for (auto it = text->layout.begin(); it != text->layout.end();) { // Create a with 'x' and 'y' for each line. Inkscape::XML::Node *line_tspan = repr->document()->createElement("svg:tspan"); @@ -432,16 +401,19 @@ static void insert_text_fallback( Inkscape::XML::Node *repr, SPDocument *origina // std::cout << " horizontal: " << text_x << " " << line_anchor_point[Geom::Y] << std::endl; if (text->has_inline_size()) { // We use text_x as this is the reference for 'text-anchor' - // (line_x is the start of the line which gives wrong position when 'text-anchor' not start). + // (line_x is the start of the line which gives wrong position when 'text-anchor' not + // start). sp_repr_set_svg_double(line_tspan, "x", text_x); } else { // shape-inside (we don't have to worry about 'text-anchor'). sp_repr_set_svg_double(line_tspan, "x", line_x); } - sp_repr_set_svg_double(line_tspan, "y", line_y); // FIXME: this will pick up the wrong end of counter-directional runs + sp_repr_set_svg_double(line_tspan, "y", line_y); // FIXME: this will pick up the wrong end of + // counter-directional runs } else { // std::cout << " vertical: " << line_anchor_point[Geom::X] << " " << text_y << std::endl; - sp_repr_set_svg_double(line_tspan, "x", line_x); // FIXME: this will pick up the wrong end of counter-directional runs + sp_repr_set_svg_double(line_tspan, "x", line_x); // FIXME: this will pick up the wrong end of + // counter-directional runs if (text->has_inline_size()) { sp_repr_set_svg_double(line_tspan, "y", text_y); } else { @@ -450,8 +422,8 @@ static void insert_text_fallback( Inkscape::XML::Node *repr, SPDocument *origina } } - // Inside line , create s for each change of style or shift. (No shifts in SVG 2 flowed text.) - // For simple lines, this creates an unneeded but so be it. + // Inside line , create s for each change of style or shift. (No shifts in SVG 2 flowed + // text.) For simple lines, this creates an unneeded but so be it. Inkscape::Text::Layout::iterator it_line_end = it; it_line_end.nextStartOfLine(); @@ -464,7 +436,6 @@ static void insert_text_fallback( Inkscape::XML::Node *repr, SPDocument *origina // Loop over chunks in line while (it != it_line_end) { - Inkscape::XML::Node *span_tspan = repr->document()->createElement("svg:tspan"); // use kerning to simulate justification and whatnot @@ -483,7 +454,9 @@ static void insert_text_fallback( Inkscape::XML::Node *repr, SPDocument *origina text->layout.getSourceOfCharacter(it, &source_obj, &span_text_start_iter); // Set tspan style - Glib::ustring style_text = (dynamic_cast(source_obj) ? source_obj->parent : source_obj)->style->write( SP_STYLE_FLAG_IFDIFF, SP_STYLE_SRC_UNSET, text->style); + Glib::ustring style_text = + (dynamic_cast(source_obj) ? source_obj->parent : source_obj) + ->style->write(SP_STYLE_FLAG_IFDIFF, SP_STYLE_SRC_UNSET, text->style); if (!style_text.empty()) { span_tspan->setAttributeOrRemoveIfEmpty("style", style_text); } @@ -498,22 +471,25 @@ static void insert_text_fallback( Inkscape::XML::Node *repr, SPDocument *origina if (span_end_obj != source_obj) { if (it_span_end == text->layout.end()) { span_text_end_iter = span_text_start_iter; - for (int i = text->layout.iteratorToCharIndex(it_span_end) - text->layout.iteratorToCharIndex(it) ; i ; --i) + for (int i = text->layout.iteratorToCharIndex(it_span_end) - + text->layout.iteratorToCharIndex(it); + i; --i) ++span_text_end_iter; } else - span_text_end_iter = string->end(); // spans will never straddle a source boundary + span_text_end_iter = string->end(); // spans will never straddle a source boundary } if (span_text_start_iter != span_text_end_iter) { Glib::ustring new_string; while (span_text_start_iter != span_text_end_iter) - new_string += *span_text_start_iter++; // grr. no substr() with iterators + new_string += *span_text_start_iter++; // grr. no substr() with iterators if (it == it_last_span && trim) { // Found last span in line - const auto s = new_string.find_last_not_of(" \t"); // Any other white space characters needed? - trailing_whitespace = new_string.substr(s+1, new_string.length()); - new_string.erase(s+1); + const auto s = + new_string.find_last_not_of(" \t"); // Any other white space characters needed? + trailing_whitespace = new_string.substr(s + 1, new_string.length()); + new_string.erase(s + 1); } Inkscape::XML::Node *new_text = repr->document()->createTextNode(new_string.c_str()); @@ -537,7 +513,6 @@ static void insert_text_fallback( Inkscape::XML::Node *repr, SPDocument *origina // into a separate tspan (alignment is done by "text chunk" and spaces at ends of // line will mess this up). if (trim && trailing_whitespace.length() != 0) { - Inkscape::XML::Node *space_tspan = repr->document()->createElement("svg:tspan"); // Set either 'x' or 'y' to force a new text chunk. To do: this really should // be positioned at the end of the line (overhanging). @@ -552,28 +527,25 @@ static void insert_text_fallback( Inkscape::XML::Node *repr, SPDocument *origina line_tspan->appendChild(space_tspan); Inkscape::GC::release(space_tspan); } - } - for (auto i: old_children) { - repr->removeChild (i); + for (auto i : old_children) { + repr->removeChild(i); } return; // No need to look at children of } - for ( Node *child = repr->firstChild(); child; child = child->next() ) { - insert_text_fallback (child, original_doc, defs); + for (Node *child = repr->firstChild(); child; child = child->next()) { + insert_text_fallback(child, original_doc, defs); } } } - -static void insert_mesh_polyfill( Inkscape::XML::Node *repr ) +static void insert_mesh_polyfill(Inkscape::XML::Node *repr) { if (repr) { - - Inkscape::XML::Node *defs = sp_repr_lookup_name (repr, "svg:defs"); + Inkscape::XML::Node *defs = sp_repr_lookup_name(repr, "svg:defs"); if (defs == nullptr) { // We always put meshes in , no defs -> no mesh. @@ -581,26 +553,25 @@ static void insert_mesh_polyfill( Inkscape::XML::Node *repr ) } bool has_mesh = false; - for ( Node *child = defs->firstChild(); child; child = child->next() ) { + for (Node *child = defs->firstChild(); child; child = child->next()) { if (strncmp("svg:meshgradient", child->name(), 16) == 0) { has_mesh = true; break; } } - Inkscape::XML::Node *script = sp_repr_lookup_child (repr, "id", "mesh_polyfill"); + Inkscape::XML::Node *script = sp_repr_lookup_child(repr, "id", "mesh_polyfill"); if (has_mesh && script == nullptr) { - script = repr->document()->createElement("svg:script"); - script->setAttribute ("id", "mesh_polyfill"); - script->setAttribute ("type", "text/javascript"); + script->setAttribute("id", "mesh_polyfill"); + script->setAttribute("type", "text/javascript"); repr->root()->appendChild(script); // Must be last // Insert JavaScript via raw string literal. Glib::ustring js = #include "polyfill/mesh_compressed.include" -; + ; Inkscape::XML::Node *script_text = repr->document()->createTextNode(js.c_str()); script->appendChild(script_text); @@ -608,12 +579,10 @@ static void insert_mesh_polyfill( Inkscape::XML::Node *repr ) } } - -static void insert_hatch_polyfill( Inkscape::XML::Node *repr ) +static void insert_hatch_polyfill(Inkscape::XML::Node *repr) { if (repr) { - - Inkscape::XML::Node *defs = sp_repr_lookup_name (repr, "svg:defs"); + Inkscape::XML::Node *defs = sp_repr_lookup_name(repr, "svg:defs"); if (defs == nullptr) { // We always put meshes in , no defs -> no mesh. @@ -621,26 +590,25 @@ static void insert_hatch_polyfill( Inkscape::XML::Node *repr ) } bool has_hatch = false; - for ( Node *child = defs->firstChild(); child; child = child->next() ) { + for (Node *child = defs->firstChild(); child; child = child->next()) { if (strncmp("svg:hatch", child->name(), 16) == 0) { has_hatch = true; break; } } - Inkscape::XML::Node *script = sp_repr_lookup_child (repr, "id", "hatch_polyfill"); + Inkscape::XML::Node *script = sp_repr_lookup_child(repr, "id", "hatch_polyfill"); if (has_hatch && script == nullptr) { - script = repr->document()->createElement("svg:script"); - script->setAttribute ("id", "hatch_polyfill"); - script->setAttribute ("type", "text/javascript"); + script->setAttribute("id", "hatch_polyfill"); + script->setAttribute("type", "text/javascript"); repr->root()->appendChild(script); // Must be last // Insert JavaScript via raw string literal. Glib::ustring js = #include "polyfill/hatch_compressed.include" -; + ; Inkscape::XML::Node *script_text = repr->document()->createTextNode(js.c_str()); script->appendChild(script_text); @@ -651,17 +619,16 @@ static void insert_hatch_polyfill( Inkscape::XML::Node *repr ) /* * Recursively transform SVG 2 to SVG 1.1, if possible. */ -static void transform_2_to_1( Inkscape::XML::Node *repr, Inkscape::XML::Node *defs = nullptr ) +static void transform_2_to_1(Inkscape::XML::Node *repr, Inkscape::XML::Node *defs = nullptr) { if (repr) { - // std::cout << "transform_2_to_1: " << repr->name() << std::endl; // Things we do once per node. ----------------------- // Find defs, if does not exist, create. if (defs == nullptr) { - defs = sp_repr_lookup_name (repr, "svg:defs"); + defs = sp_repr_lookup_name(repr, "svg:defs"); } if (defs == nullptr) { defs = repr->document()->createElement("svg:defs"); @@ -669,21 +636,21 @@ static void transform_2_to_1( Inkscape::XML::Node *repr, Inkscape::XML::Node *de } // Find style. - SPCSSAttr* css = sp_repr_css_attr ( repr, "style" ); + SPCSSAttr *css = sp_repr_css_attr(repr, "style"); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); // Individual items ---------------------------------- // SVG 2 marker attribute orient:auto-start-reverse: - if ( prefs->getBool("/options/svgexport/marker_autostartreverse", false) ) { + if (prefs->getBool("/options/svgexport/marker_autostartreverse", false)) { // Do "marker-start" first for efficiency reasons. remove_marker_auto_start_reverse(repr, defs, css, "marker-start"); remove_marker_auto_start_reverse(repr, defs, css, "marker"); } // SVG 2 paint values 'context-fill', 'context-stroke': - if ( prefs->getBool("/options/svgexport/marker_contextpaint", false) ) { + if (prefs->getBool("/options/svgexport/marker_contextpaint", false)) { remove_marker_context_paint(repr, defs); } @@ -693,17 +660,14 @@ static void transform_2_to_1( Inkscape::XML::Node *repr, Inkscape::XML::Node *de // Meshes // Hatches - for ( Node *child = repr->firstChild(); child; child = child->next() ) { - transform_2_to_1 (child, defs); + for (Node *child = repr->firstChild(); child; child = child->next()) { + transform_2_to_1(child, defs); } sp_repr_css_attr_unref(css); } } - - - /** \return None \brief What would an SVG editor be without loading/saving SVG @@ -716,8 +680,7 @@ static void transform_2_to_1( Inkscape::XML::Node *repr, Inkscape::XML::Node *de have is the key function for the operation. And that is linked at the end of each call. */ -void -Svg::init() +void Svg::init() { // clang-format off /* SVG in */ @@ -766,7 +729,6 @@ Svg::init() return; } - /** \return A new document just for you! \brief This function takes in a filename of a SVG document and @@ -780,8 +742,7 @@ Svg::init() Most of the import code was copied from gdkpixpuf-input.cpp. */ -SPDocument * -Svg::open (Inkscape::Extension::Input *mod, const gchar *uri) +SPDocument *Svg::open(Inkscape::Extension::Input *mod, const gchar *uri) { // This is only used at the end... but it should go here once uri stuff is fixed. auto file = Gio::File::create_for_commandline_arg(uri); @@ -803,20 +764,20 @@ Svg::open (Inkscape::Extension::Input *mod, const gchar *uri) Inkscape::Preferences *prefs = Inkscape::Preferences::get(); // Get import preferences. - bool ask_svg = prefs->getBool( "/dialogs/import/ask_svg"); - Glib::ustring import_mode_svg = prefs->getString("/dialogs/import/import_mode_svg"); - Glib::ustring scale = prefs->getString("/dialogs/import/scale"); + bool ask_svg = prefs->getBool("/dialogs/import/ask_svg"); + Glib::ustring import_mode_svg = prefs->getString("/dialogs/import/import_mode_svg"); + Glib::ustring scale = prefs->getString("/dialogs/import/scale"); // If we popped up a window asking about import preferences, get values from // there and update preferences. - if(mod->get_gui() && ask_svg) { - ask_svg = !mod->get_param_bool("do_not_ask"); - import_mode_svg = mod->get_param_optiongroup("import_mode_svg"); - scale = mod->get_param_optiongroup("scale"); - - prefs->setBool( "/dialogs/import/ask_svg", ask_svg); - prefs->setString("/dialogs/import/import_mode_svg", import_mode_svg ); - prefs->setString("/dialogs/import/scale", scale ); + if (mod->get_gui() && ask_svg) { + ask_svg = !mod->get_param_bool("do_not_ask"); + import_mode_svg = mod->get_param_optiongroup("import_mode_svg"); + scale = mod->get_param_optiongroup("scale"); + + prefs->setBool("/dialogs/import/ask_svg", ask_svg); + prefs->setString("/dialogs/import/import_mode_svg", import_mode_svg); + prefs->setString("/dialogs/import/scale", scale); } // Do we "import" as ? @@ -824,11 +785,11 @@ Svg::open (Inkscape::Extension::Input *mod, const gchar *uri) // We import! // New wrapper document. - SPDocument * doc = SPDocument::createNewDoc (nullptr, true, true); + SPDocument *doc = SPDocument::createNewDoc(nullptr, true, true); // Imported document // SPDocument * ret = SPDocument::createNewDoc(file->get_uri().c_str(), true); - SPDocument * ret = SPDocument::createNewDoc(uri, true); + SPDocument *ret = SPDocument::createNewDoc(uri, true); // What is display unit doing here? Glib::ustring display_unit = doc->getDisplayUnit()->abbr; @@ -853,23 +814,23 @@ Svg::open (Inkscape::Extension::Input *mod, const gchar *uri) // This is actually "image-rendering" Glib::ustring scale = prefs->getString("/dialogs/import/scale"); - if( scale != "auto") { + if (scale != "auto") { SPCSSAttr *css = sp_repr_css_attr_new(); sp_repr_css_set_property(css, "image-rendering", scale.c_str()); sp_repr_css_set(image_node, css, "style"); - sp_repr_css_attr_unref( css ); + sp_repr_css_attr_unref(css); } // Do we embed or link? if (import_mode_svg == "embed") { std::unique_ptr pb(Inkscape::Pixbuf::create_from_file(uri, svgdpi)); - if(pb) { + if (pb) { sp_embed_svg(image_node, uri); } } else { // Convert filename to uri (why do we need to do this, we claimed it was already a uri). - gchar* _uri = g_filename_to_uri(uri, nullptr, nullptr); - if(_uri) { + gchar *_uri = g_filename_to_uri(uri, nullptr, nullptr); + if (_uri) { // if (strcmp(_uri, uri) != 0) { // std::cout << "Svg::open: _uri != uri! " << _uri << ":" << uri << std::endl; // } @@ -892,7 +853,8 @@ Svg::open (Inkscape::Extension::Input *mod, const gchar *uri) // Set viewBox if it doesn't exist. What is display unit doing here? if (!doc->getRoot()->viewBox_set) { - doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), doc->getHeight().value(doc->getDisplayUnit()))); + doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), + doc->getHeight().value(doc->getDisplayUnit()))); } return doc; } @@ -946,41 +908,30 @@ Svg::open (Inkscape::Extension::Input *mod, const gchar *uri) This really needs to be fleshed out more, but I don't quite understand all of this code. I just stole it. */ -void -Svg::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) +void Svg::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) { g_return_if_fail(doc != nullptr); g_return_if_fail(filename != nullptr); Inkscape::XML::Document *rdoc = doc->getReprDoc(); - bool const exportExtensions = ( !mod->get_id() - || !strcmp (mod->get_id(), SP_MODULE_KEY_OUTPUT_SVG_INKSCAPE) - || !strcmp (mod->get_id(), SP_MODULE_KEY_OUTPUT_SVGZ_INKSCAPE)); + bool const exportExtensions = (!mod->get_id() || !strcmp(mod->get_id(), SP_MODULE_KEY_OUTPUT_SVG_INKSCAPE) || + !strcmp(mod->get_id(), SP_MODULE_KEY_OUTPUT_SVGZ_INKSCAPE)); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool const transform_2_to_1_flag = - prefs->getBool("/dialogs/save_as/enable_svgexport", false); - - bool const insert_text_fallback_flag = - prefs->getBool("/options/svgexport/text_insertfallback", true); - bool const insert_mesh_polyfill_flag = - prefs->getBool("/options/svgexport/mesh_insertpolyfill", true); - bool const insert_hatch_polyfill_flag = - prefs->getBool("/options/svgexport/hatch_insertpolyfill", true); - - bool createNewDoc = - !exportExtensions || - transform_2_to_1_flag || - insert_text_fallback_flag || - insert_mesh_polyfill_flag || - insert_hatch_polyfill_flag; + bool const transform_2_to_1_flag = prefs->getBool("/dialogs/save_as/enable_svgexport", false); + + bool const insert_text_fallback_flag = prefs->getBool("/options/svgexport/text_insertfallback", true); + bool const insert_mesh_polyfill_flag = prefs->getBool("/options/svgexport/mesh_insertpolyfill", true); + bool const insert_hatch_polyfill_flag = prefs->getBool("/options/svgexport/hatch_insertpolyfill", true); + + bool createNewDoc = !exportExtensions || transform_2_to_1_flag || insert_text_fallback_flag || + insert_mesh_polyfill_flag || insert_hatch_polyfill_flag; // We prune the in-use document and deliberately loose data, because there // is no known use for this data at the present time. pruneProprietaryGarbage(rdoc->root()); if (createNewDoc) { - // We make a duplicate document so we don't prune the in-use document // and loose data. Perhaps the user intends to save as inkscape-svg next. Inkscape::XML::Document *new_rdoc = new Inkscape::XML::SimpleDocument(); @@ -1002,20 +953,20 @@ Svg::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filena } if (transform_2_to_1_flag) { - transform_2_to_1 (root); + transform_2_to_1(root); new_rdoc->setAttribute("version", "1.1"); } if (insert_text_fallback_flag) { - insert_text_fallback (root, doc); + insert_text_fallback(root, doc); } if (insert_mesh_polyfill_flag) { - insert_mesh_polyfill (root); + insert_mesh_polyfill(root); } if (insert_hatch_polyfill_flag) { - insert_hatch_polyfill (root); + insert_hatch_polyfill(root); } rdoc = new_rdoc; @@ -1034,7 +985,9 @@ Svg::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filena return; } -} } } /* namespace inkscape, module, implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/internal/svg.h b/src/extension/internal/svg.h index cbfd22171b1bfd1018213d5a22799eae840ed67f..8a69f494d1f48d51546030d1d1bfe2875e2d602d 100644 --- a/src/extension/internal/svg.h +++ b/src/extension/internal/svg.h @@ -34,27 +34,25 @@ "false\n" // clang-format on - namespace Inkscape { namespace Extension { namespace Internal { -class Svg : public Inkscape::Extension::Implementation::Implementation { +class Svg : public Inkscape::Extension::Implementation::Implementation +{ bool m_detachbase = false; public: - void setDetachBase(bool detach) override { m_detachbase = detach; } - - void save( Inkscape::Extension::Output *mod, - SPDocument *doc, - gchar const *filename ) override; - SPDocument *open( Inkscape::Extension::Input *mod, - const gchar *uri ) override; - static void init( ); + void setDetachBase(bool detach) override { m_detachbase = detach; } + void save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) override; + SPDocument *open(Inkscape::Extension::Input *mod, const gchar *uri) override; + static void init(); }; -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* __SVG_H__ */ /* diff --git a/src/extension/internal/svgz.cpp b/src/extension/internal/svgz.cpp index 63d0058d53c132cb6d99cc0704f55456b87bacf9..b871300785d26ec6a729103dbf6444e852623a08 100644 --- a/src/extension/internal/svgz.cpp +++ b/src/extension/internal/svgz.cpp @@ -14,6 +14,7 @@ */ #include "svgz.h" + #include "extension/extension.h" #include "extension/system.h" @@ -35,8 +36,7 @@ namespace Internal { have is the key function for the operation. And that is linked at the end of each call. */ -void -Svgz::init() +void Svgz::init() { // clang-format off /* SVGZ in */ @@ -86,8 +86,9 @@ Svgz::init() return; } - -} } } // namespace inkscape, module, implementation +} // namespace Internal +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/internal/svgz.h b/src/extension/internal/svgz.h index e923c4ce1eb147a20bbf0b3f4cc45e0e4f066fc6..c7e324076728a01084d4fcb99e045cbcb239a799 100644 --- a/src/extension/internal/svgz.h +++ b/src/extension/internal/svgz.h @@ -22,12 +22,15 @@ namespace Inkscape { namespace Extension { namespace Internal { -class Svgz : public Svg { +class Svgz : public Svg +{ public: - static void init( ); + static void init(); }; -} } } // namespace Inkscape, Extension, Implementation +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif // SEEN_SVGZ_H /* diff --git a/src/extension/internal/text_reassemble.c b/src/extension/internal/text_reassemble.c index 543106f3e0400fcb8b2ca1856b35500a3388b1b0..792171345b864bfc37a86fa5c23d48354f98172d 100644 --- a/src/extension/internal/text_reassemble.c +++ b/src/extension/internal/text_reassemble.c @@ -9,7 +9,6 @@ * Released under GNU GPL v2.0+, read the file 'COPYING' for more information. */ - /** @file text_reassemble.c @@ -58,7 +57,8 @@ On Windows use: On Linux use: - gcc -Wall -DTEST -DDBG_TR_PARA -DDBG_TR_INPUT -I. -I/usr/include/freetype2 -o text_reassemble text_reassemble.c uemf_utf.c -lfreetype -lfontconfig -lm + gcc -Wall -DTEST -DDBG_TR_PARA -DDBG_TR_INPUT -I. -I/usr/include/freetype2 -o text_reassemble text_reassemble.c +uemf_utf.c -lfreetype -lfontconfig -lm Compilation of object file only (Windows): @@ -67,7 +67,7 @@ Compilation of object file only (Windows): text_reassemble.c Compilation of object file only (Linux): - gcc -Wall -c -I. -I/usr/include/freetype2 text_reassemble.c + gcc -Wall -c -I. -I/usr/include/freetype2 text_reassemble.c Optional compiler switches for development: @@ -91,20 +91,22 @@ extern "C" { #endif #include "text_reassemble.h" -#include <3rdparty/libuemf/uemf_utf.h> /* For a couple of text functions. Exact copy from libUEMF. */ -#include + +#include <3rdparty/libuemf/uemf_utf.h> /* For a couple of text functions. Exact copy from libUEMF. */ #include +#include /* Code generated by make_ucd_mn_table.c using: cat mnlist.txt | ./make_ucd_mn_table >generated.c */ #include -int is_mn_unicode(int test){ +int is_mn_unicode(int test) +{ #define MN_TEST_LIMIT 921600 -#define N_SPAGES 225 -#define N_CPAGES 192 -#define N_CPDATA 344 -#define C_PER_S 16 +#define N_SPAGES 225 +#define N_CPAGES 192 +#define N_CPDATA 344 +#define C_PER_S 16 // clang-format off uint8_t superpages[N_SPAGES]={ @@ -184,47 +186,47 @@ int is_mn_unicode(int test){ 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0000FFFF}; // clang-format on - int result=0; + int result = 0; - int spage_idx; - int cpage_row, cpage_column, cpage_idx; - int cd_row, cd_column, cd_idx, cd_bit; + int spage_idx; + int cpage_row, cpage_column, cpage_idx; + int cd_row, cd_column, cd_idx, cd_bit; - if(test> 12; - cpage_row = superpages[spage_idx]; - cpage_column = (test>>8) & 15; - cpage_idx = C_PER_S*cpage_row + cpage_column; - cd_row = cpages[cpage_idx]; - cd_column = test>>5 & 7; - cd_idx = 8*cd_row + cd_column; - cd_bit = test & 31; - result = cpage_data[cd_idx] & (1 << cd_bit); - } - return(result); + if (test < MN_TEST_LIMIT) { + spage_idx = test >> 12; + cpage_row = superpages[spage_idx]; + cpage_column = (test >> 8) & 15; + cpage_idx = C_PER_S * cpage_row + cpage_column; + cd_row = cpages[cpage_idx]; + cd_column = test >> 5 & 7; + cd_idx = 8 * cd_row + cd_column; + cd_bit = test & 31; + result = cpage_data[cd_idx] & (1 << cd_bit); + } + return (result); } - - /** \brief Find a (sub)string in a caseinvariant manner, used for locating "Narrow" in font name \return Returns -1 if no match, else returns the position (numbered from 0) of the first character of the match. \param string Text to search \param sub Text to find */ -int TR_findcasesub(const char *string, const char *sub){ - int i,j; - int match=0; - for(i=0; string[i]; i++){ - for(match=1,j=0; sub[j] && string[i+j]; j++){ - if(toupper(sub[j]) != toupper(string[i+j])){ - match=0; - break; - } - } - if(match && !sub[j])break; /* matched over the entire substring */ - } - return((match ? i : -1)); +int TR_findcasesub(const char *string, const char *sub) +{ + int i, j; + int match = 0; + for (i = 0; string[i]; i++) { + for (match = 1, j = 0; sub[j] && string[i + j]; j++) { + if (toupper(sub[j]) != toupper(string[i + j])) { + match = 0; + break; + } + } + if (match && !sub[j]) + break; /* matched over the entire substring */ + } + return ((match ? i : -1)); } /** @@ -233,110 +235,118 @@ int TR_findcasesub(const char *string, const char *sub){ \param tsp pointer to TCHUNK_SPECS to use for information \param fontname Fontname to use in the new fontspec */ - /* construct a font name */ -char *TR_construct_fontspec(const TCHUNK_SPECS *tsp, const char *fontname){ - int newlen = 128 + strlen(fontname); /* too big, but not by much */ - char *newfs = NULL; - newfs = (char *) malloc(newlen); - sprintf(newfs,"%s:slant=%d:weight=%d:size=%f:width=%d",fontname,tsp->italics,tsp->weight,tsp->fs,(tsp->co ? 75 : tsp->condensed)); - return(newfs); +/* construct a font name */ +char *TR_construct_fontspec(const TCHUNK_SPECS *tsp, const char *fontname) +{ + int newlen = 128 + strlen(fontname); /* too big, but not by much */ + char *newfs = NULL; + newfs = (char *)malloc(newlen); + sprintf(newfs, "%s:slant=%d:weight=%d:size=%f:width=%d", fontname, tsp->italics, tsp->weight, tsp->fs, + (tsp->co ? 75 : tsp->condensed)); + return (newfs); } - /** \brief Reconstrouct a fontspec by substituting a font name into an existing spec \return Returns NULL on error, new fontspec on success \param fontspec Original fontspec, only the name will be changed \param fontname Fontname to substitute into the new fontspec */ - /* construct a font name */ -char *TR_reconstruct_fontspec(const char *fontspec, const char *fontname){ - int colon; - int newlen = strlen(fontspec) + strlen(fontname) + 1; /* too big, but not by much */ - char *newfs = NULL; - newfs = (char *) malloc(newlen); - colon = strcspn(fontspec,":"); - if(colon){ sprintf(newfs,"%s%s",fontname,&fontspec[colon]); } - return(newfs); +/* construct a font name */ +char *TR_reconstruct_fontspec(const char *fontspec, const char *fontname) +{ + int colon; + int newlen = strlen(fontspec) + strlen(fontname) + 1; /* too big, but not by much */ + char *newfs = NULL; + newfs = (char *)malloc(newlen); + colon = strcspn(fontspec, ":"); + if (colon) { + sprintf(newfs, "%s%s", fontname, &fontspec[colon]); + } + return (newfs); } /** \brief Find a font in the list that has a glyph for this character, change alternate to match \return Returns 0 if no match or an error, else returns the glyph index in the new alternate font \param fti pointer to the FT_INFO structure, may be modified if alternate font is added - \param efsp Pointer to a Pointer to the original FNT_SPECS struct. On return contains the FNT_SPECS corresponding to the glyph_index.. - \param wc Current character (32 bit int) -*/ -int TR_find_alternate_font(FT_INFO *fti, FNT_SPECS **efsp, uint32_t wc){ - int glyph_index=0; /* this is the unknown character glyph */ - uint32_t i; - FcCharSet *cs; - FcResult result = FcResultMatch; - FcPattern *pattern, *fpat; - char *filename; - char *fontname; - char *newfontspec; - int fi_idx; - FNT_SPECS *fsp,*fsp2; - if(!fti || !efsp || !*efsp)return(0); - fsp = *efsp; - for(i=0;iused;i++){ /* first check in alts */ - fsp2 = &fti->fonts[fsp->alts[i].fi_idx]; /* these are in order of descending previous usage */ - glyph_index = FT_Get_Char_Index( fsp2->face, wc); /* we have the face, might as well check that directly */ - if (glyph_index){ /* found a glyph for the character in this font */ - (void) fsp_alts_weight(fsp, i); - *efsp = fsp2; - return(glyph_index); - } - } - - /* it was not in alts, now go through fontset and see if it is in there */ - for(i=1; i< (unsigned int) fsp->fontset->nfont;i++){ /* already know the primary does not have this character */ - result = FcPatternGetCharSet(fsp->fontset->fonts[i], FC_CHARSET, 0, &cs); - if(result != FcResultMatch) return(0); /* some terrible problem, this should never happen */ - if (FcCharSetHasChar(cs, wc)){ /* found a glyph for the character in this font */ - glyph_index = i; - - /* Do a lot of work to find the filename corresponding to the fontset entry. - None of these should ever fail, but if one does, return 0 - */ - if( - !(pattern = FcNameParse((const FcChar8 *)&(fsp->fontspec))) || - !FcConfigSubstitute(NULL, pattern, FcMatchPattern) - )return(0); - FcDefaultSubstitute(pattern); - if( - !(fpat = FcFontRenderPrepare(NULL, pattern, fsp->fontset->fonts[i])) || - (FcPatternGetString( fpat, FC_FILE, 0, (FcChar8 **)&filename) != FcResultMatch) || - (FcPatternGetString( fsp->fontset->fonts[i], FC_FULLNAME, 0, (FcChar8 **)&fontname) != FcResultMatch) - )return(0); - - /* find the font (added from an unrelated fontset, for instance) or insert it as new */ - fi_idx = ftinfo_find_loaded_by_src(fti, (uint8_t *) filename); - if(fi_idx < 0){ - newfontspec = TR_reconstruct_fontspec((char *) fsp->fontspec, fontname); - fi_idx = ftinfo_load_fontname(fti, newfontspec); - free(newfontspec); - if(fi_idx < 0)return(0); /* This could happen if we run out of memory*/ - } - - /* add the new font index to the alts list on the (current) fsp. */ - (void) fsp_alts_insert(fsp, fi_idx); - - /* release FC's own memory related to this call that does not need to be kept around so that face will work */ - FcPatternDestroy(pattern); - - *efsp = &(fti->fonts[fi_idx]); - return(glyph_index); - } - } - - return(0); + \param efsp Pointer to a Pointer to the original FNT_SPECS struct. On return contains the FNT_SPECS + corresponding to the glyph_index.. \param wc Current character (32 bit int) +*/ +int TR_find_alternate_font(FT_INFO *fti, FNT_SPECS **efsp, uint32_t wc) +{ + int glyph_index = 0; /* this is the unknown character glyph */ + uint32_t i; + FcCharSet *cs; + FcResult result = FcResultMatch; + FcPattern *pattern, *fpat; + char *filename; + char *fontname; + char *newfontspec; + int fi_idx; + FNT_SPECS *fsp, *fsp2; + if (!fti || !efsp || !*efsp) + return (0); + fsp = *efsp; + for (i = 0; i < fsp->used; i++) { /* first check in alts */ + fsp2 = &fti->fonts[fsp->alts[i].fi_idx]; /* these are in order of descending previous usage */ + glyph_index = FT_Get_Char_Index(fsp2->face, wc); /* we have the face, might as well check that directly */ + if (glyph_index) { /* found a glyph for the character in this font */ + (void)fsp_alts_weight(fsp, i); + *efsp = fsp2; + return (glyph_index); + } + } + + /* it was not in alts, now go through fontset and see if it is in there */ + for (i = 1; i < (unsigned int)fsp->fontset->nfont; + i++) { /* already know the primary does not have this character */ + result = FcPatternGetCharSet(fsp->fontset->fonts[i], FC_CHARSET, 0, &cs); + if (result != FcResultMatch) + return (0); /* some terrible problem, this should never happen */ + if (FcCharSetHasChar(cs, wc)) { /* found a glyph for the character in this font */ + glyph_index = i; + + /* Do a lot of work to find the filename corresponding to the fontset entry. + None of these should ever fail, but if one does, return 0 + */ + if (!(pattern = FcNameParse((const FcChar8 *)&(fsp->fontspec))) || + !FcConfigSubstitute(NULL, pattern, FcMatchPattern)) + return (0); + FcDefaultSubstitute(pattern); + if (!(fpat = FcFontRenderPrepare(NULL, pattern, fsp->fontset->fonts[i])) || + (FcPatternGetString(fpat, FC_FILE, 0, (FcChar8 **)&filename) != FcResultMatch) || + (FcPatternGetString(fsp->fontset->fonts[i], FC_FULLNAME, 0, (FcChar8 **)&fontname) != FcResultMatch)) + return (0); + + /* find the font (added from an unrelated fontset, for instance) or insert it as new */ + fi_idx = ftinfo_find_loaded_by_src(fti, (uint8_t *)filename); + if (fi_idx < 0) { + newfontspec = TR_reconstruct_fontspec((char *)fsp->fontspec, fontname); + fi_idx = ftinfo_load_fontname(fti, newfontspec); + free(newfontspec); + if (fi_idx < 0) + return (0); /* This could happen if we run out of memory*/ + } + + /* add the new font index to the alts list on the (current) fsp. */ + (void)fsp_alts_insert(fsp, fi_idx); + + /* release FC's own memory related to this call that does not need to be kept around so that face will work + */ + FcPatternDestroy(pattern); + + *efsp = &(fti->fonts[fi_idx]); + return (glyph_index); + } + } + + return (0); } /** \brief Get the advance for the 32 bit character - + \return Returns -1 on error, or advance in units of 1/64th of a Point. \param fti pointer to the FT_INFO structure, may be modified if alternate font is required \param fsp Pointer to FNT_SPECS struct. @@ -345,37 +355,44 @@ int TR_find_alternate_font(FT_INFO *fti, FNT_SPECS **efsp, uint32_t wc){ \param load_flags Controls internal advance: FT_LOAD_NO_SCALE, internal advance is in 1/64th of a point. (kerning values are still scaled) FT_LOAD_TARGET_NORMAL internal advance is in 1/64th of a point. The scale - factor seems to be (Font Size in points)*(DPI)/(32.0 pnts)*(72 dpi). - \param kern_mode FT_KERNING_DEFAULT, FT_KERNING_UNFITTED, or FT_KERNING_UNSCALED. Set to match calling application. - \param ymin If the pointer is defined, the value is adjusted if ymin of wc character is less than the current value. - \param ymax If the pointer is defined, the value is adjusted if ymin of wc character is more than the current value. -*/ -int TR_getadvance(FT_INFO *fti, FNT_SPECS *fsp, uint32_t wc, uint32_t pc, int load_flags, int kern_mode, int *ymin, int *ymax){ - FT_Glyph glyph; - int glyph_index; - int advance=-1; - FT_BBox bbox; - - if(is_mn_unicode(wc))return(0); /* no advance on Unicode Mn characters */ - - glyph_index = FT_Get_Char_Index( fsp->face, wc); - if(!glyph_index){ /* not in primary font, check alternates */ - glyph_index = TR_find_alternate_font(fti, &fsp, wc); - } - if(glyph_index){ - if (!FT_Load_Glyph( fsp->face, glyph_index, load_flags )){ - if ( !FT_Get_Glyph( fsp->face->glyph, &glyph ) ) { - advance = fsp->face->glyph->advance.x; - FT_Glyph_Get_CBox( glyph, FT_GLYPH_BBOX_UNSCALED, &bbox ); - if(ymin && (bbox.yMin < *ymin))*ymin=bbox.yMin; - if(ymax && (bbox.yMax > *ymax))*ymax=bbox.yMax; - if(pc)advance += TR_getkern2(fsp, wc, pc, kern_mode); - FT_Done_Glyph(glyph); - } - } - } - /* If there was no way to determine the width, this returns the error value */ - return(advance); + factor seems to be (Font Size in points)*(DPI)/(32.0 pnts)*(72 dpi). + \param kern_mode FT_KERNING_DEFAULT, FT_KERNING_UNFITTED, or FT_KERNING_UNSCALED. Set to match calling + application. \param ymin If the pointer is defined, the value is adjusted if ymin of wc character is less than the + current value. \param ymax If the pointer is defined, the value is adjusted if ymin of wc character is more than the + current value. +*/ +int TR_getadvance(FT_INFO *fti, FNT_SPECS *fsp, uint32_t wc, uint32_t pc, int load_flags, int kern_mode, int *ymin, + int *ymax) +{ + FT_Glyph glyph; + int glyph_index; + int advance = -1; + FT_BBox bbox; + + if (is_mn_unicode(wc)) + return (0); /* no advance on Unicode Mn characters */ + + glyph_index = FT_Get_Char_Index(fsp->face, wc); + if (!glyph_index) { /* not in primary font, check alternates */ + glyph_index = TR_find_alternate_font(fti, &fsp, wc); + } + if (glyph_index) { + if (!FT_Load_Glyph(fsp->face, glyph_index, load_flags)) { + if (!FT_Get_Glyph(fsp->face->glyph, &glyph)) { + advance = fsp->face->glyph->advance.x; + FT_Glyph_Get_CBox(glyph, FT_GLYPH_BBOX_UNSCALED, &bbox); + if (ymin && (bbox.yMin < *ymin)) + *ymin = bbox.yMin; + if (ymax && (bbox.yMax > *ymax)) + *ymax = bbox.yMax; + if (pc) + advance += TR_getkern2(fsp, wc, pc, kern_mode); + FT_Done_Glyph(glyph); + } + } + } + /* If there was no way to determine the width, this returns the error value */ + return (advance); } /** @@ -384,61 +401,61 @@ int TR_getadvance(FT_INFO *fti, FNT_SPECS *fsp, uint32_t wc, uint32_t pc, int lo \param fsp Pointer to FNT_SPECS struct. \param wc Current character (32 bit int) \param pc Previous character - \param kern_mode FT_KERNING_DEFAULT, FT_KERNING_UNFITTED, or FT_KERNING_UNSCALED. Set to match calling application. + \param kern_mode FT_KERNING_DEFAULT, FT_KERNING_UNFITTED, or FT_KERNING_UNSCALED. Set to match calling + application. */ -int TR_getkern2(FNT_SPECS *fsp, uint32_t wc, uint32_t pc, int kern_mode){ - int this_glyph_index; - int prev_glyph_index; - int kern=0; - FT_Vector akerning; - - this_glyph_index = FT_Get_Char_Index( fsp->face, wc); - prev_glyph_index = FT_Get_Char_Index( fsp->face, pc); - if(!FT_Get_Kerning( fsp->face, - prev_glyph_index, - this_glyph_index, - kern_mode, - &akerning )){ - kern = akerning.x; /* Is sign correct? */ - } - return(kern); +int TR_getkern2(FNT_SPECS *fsp, uint32_t wc, uint32_t pc, int kern_mode) +{ + int this_glyph_index; + int prev_glyph_index; + int kern = 0; + FT_Vector akerning; + + this_glyph_index = FT_Get_Char_Index(fsp->face, wc); + prev_glyph_index = FT_Get_Char_Index(fsp->face, pc); + if (!FT_Get_Kerning(fsp->face, prev_glyph_index, this_glyph_index, kern_mode, &akerning)) { + kern = akerning.x; /* Is sign correct? */ + } + return (kern); } /** - \brief Get the kerning for a pair of 32 bit characters, where one is the last character in the previous text block, and the other is the first in the current text block. - \return Returns 0 on error, or kerning value (which may be 0) for the pair in units of 1/64th of a point. - \param fsp Pointer to FNT_SPECS struct. - \param tsp current text object + \brief Get the kerning for a pair of 32 bit characters, where one is the last character in the previous text block, + and the other is the first in the current text block. \return Returns 0 on error, or kerning value (which may be 0) + for the pair in units of 1/64th of a point. \param fsp Pointer to FNT_SPECS struct. \param tsp current text object \param ptsp previous text object - \param kern_mode FT_KERNING_DEFAULT, FT_KERNING_UNFITTED, or FT_KERNING_UNSCALED. Set to match calling application. -*/ -int TR_kern_gap(FNT_SPECS *fsp, TCHUNK_SPECS *tsp, TCHUNK_SPECS *ptsp, int kern_mode){ - int kern=0; - uint32_t *text32=NULL; - uint32_t *ptxt32=NULL; - size_t tlen,plen; - while(ptsp && tsp){ - text32 = U_Utf8ToUtf32le((char *) tsp->string, 0, &tlen); - if(!text32){ // LATIN1 encoded >128 are generally not valid UTF, so the first will fail - text32 = U_Latin1ToUtf32le((char *) tsp->string,0, &tlen); - if(!text32)break; - } - ptxt32 = U_Utf8ToUtf32le((char *) ptsp->string,0,&plen); - if(!ptxt32){ // LATIN1 encoded >128 are generally not valid UTF, so the first will fail - ptxt32 = U_Latin1ToUtf32le((char *) ptsp->string,0, &plen); - if(!ptxt32)break; - } - kern = TR_getkern2(fsp, *text32, ptxt32[plen-1], kern_mode); - break; - } - if(text32)free(text32); - if(ptxt32)free(ptxt32); - return(kern); + \param kern_mode FT_KERNING_DEFAULT, FT_KERNING_UNFITTED, or FT_KERNING_UNSCALED. Set to match calling + application. +*/ +int TR_kern_gap(FNT_SPECS *fsp, TCHUNK_SPECS *tsp, TCHUNK_SPECS *ptsp, int kern_mode) +{ + int kern = 0; + uint32_t *text32 = NULL; + uint32_t *ptxt32 = NULL; + size_t tlen, plen; + while (ptsp && tsp) { + text32 = U_Utf8ToUtf32le((char *)tsp->string, 0, &tlen); + if (!text32) { // LATIN1 encoded >128 are generally not valid UTF, so the first will fail + text32 = U_Latin1ToUtf32le((char *)tsp->string, 0, &tlen); + if (!text32) + break; + } + ptxt32 = U_Utf8ToUtf32le((char *)ptsp->string, 0, &plen); + if (!ptxt32) { // LATIN1 encoded >128 are generally not valid UTF, so the first will fail + ptxt32 = U_Latin1ToUtf32le((char *)ptsp->string, 0, &plen); + if (!ptxt32) + break; + } + kern = TR_getkern2(fsp, *text32, ptxt32[plen - 1], kern_mode); + break; + } + if (text32) + free(text32); + if (ptxt32) + free(ptxt32); + return (kern); } - - - /** \brief Find baseline on Y axis of a complex. If the complex is a TR_TEXT or TR_LINE find its baseline. @@ -450,67 +467,70 @@ int TR_kern_gap(FNT_SPECS *fsp, TCHUNK_SPECS *tsp, TCHUNK_SPECS *ptsp, int kern_ \return Returns 0 if it cannot determine a baseline, else returns the baseline Y coordinate. \param tri pointer to the TR_INFO structure holding all TR data \param src index of the current complex - \param ymax If the pointer is defined, the value is adjusted if ymax of current complex is more than the current value. - \param ymin If the pointer is defined, the value is adjusted if ymin of current complex is less than the current value. -*/ -double TR_baseline(TR_INFO *tri, int src, double *ymax, double *ymin){ - double baseline=0; - double tmp=0.0; - double yheight; - int last; - int i; - int trec; - CX_INFO *cxi=tri->cxi; - BR_INFO *bri=tri->bri; - TP_INFO *tpi=tri->tpi; - FT_INFO *fti=tri->fti; - FNT_SPECS *fsp; - last = cxi->cx[src].kids.used - 1; - switch (cxi->cx[src].type){ - case TR_TEXT: - trec = cxi->cx[src].kids.members[0]; /* for this complex type there is only ever one member */ - baseline = bri->rects[trec].yll - tpi->chunks[trec].boff; - fsp = &(fti->fonts[tpi->chunks[trec].fi_idx]); - yheight = fsp->face->bbox.yMax - fsp->face->bbox.yMin; - if(ymax){ - tmp = tpi->chunks[trec].fs * ((double)fsp->face->bbox.yMax/yheight); - if(*ymax <= tmp)*ymax = tmp; - } - else if(ymin){ - tmp = tpi->chunks[trec].fs * ((double)-fsp->face->bbox.yMin/yheight); /* yMin in face is negative */ - if(*ymin <= tmp)*ymin = tmp; - } - break; - case TR_LINE: - for(i=last;i>=0;i--){ /* here last is the count of text objects in the complex */ - trec = cxi->cx[src].kids.members[i]; - fsp = &(fti->fonts[tpi->chunks[trec].fi_idx]); - yheight = fsp->face->bbox.yMax - fsp->face->bbox.yMin; - if(ymax){ - tmp = tpi->chunks[trec].fs * (((double)fsp->face->bbox.yMax)/yheight); - if(*ymax <= tmp){ - *ymax = tmp; - baseline = bri->rects[trec].yll - tpi->chunks[trec].boff; - } - } - else if(ymin){ - tmp = tpi->chunks[trec].fs * (((double)-fsp->face->bbox.yMin)/yheight); /* yMin in face is negative */ - if(*ymin <= tmp){ - *ymin = tmp; - baseline = bri->rects[trec].yll - tpi->chunks[trec].boff; + \param ymax If the pointer is defined, the value is adjusted if ymax of current complex is more than the current + value. \param ymin If the pointer is defined, the value is adjusted if ymin of current complex is less than the + current value. +*/ +double TR_baseline(TR_INFO *tri, int src, double *ymax, double *ymin) +{ + double baseline = 0; + double tmp = 0.0; + double yheight; + int last; + int i; + int trec; + CX_INFO *cxi = tri->cxi; + BR_INFO *bri = tri->bri; + TP_INFO *tpi = tri->tpi; + FT_INFO *fti = tri->fti; + FNT_SPECS *fsp; + last = cxi->cx[src].kids.used - 1; + switch (cxi->cx[src].type) { + case TR_TEXT: + trec = cxi->cx[src].kids.members[0]; /* for this complex type there is only ever one member */ + baseline = bri->rects[trec].yll - tpi->chunks[trec].boff; + fsp = &(fti->fonts[tpi->chunks[trec].fi_idx]); + yheight = fsp->face->bbox.yMax - fsp->face->bbox.yMin; + if (ymax) { + tmp = tpi->chunks[trec].fs * ((double)fsp->face->bbox.yMax / yheight); + if (*ymax <= tmp) + *ymax = tmp; + } else if (ymin) { + tmp = tpi->chunks[trec].fs * ((double)-fsp->face->bbox.yMin / yheight); /* yMin in face is negative */ + if (*ymin <= tmp) + *ymin = tmp; + } + break; + case TR_LINE: + for (i = last; i >= 0; i--) { /* here last is the count of text objects in the complex */ + trec = cxi->cx[src].kids.members[i]; + fsp = &(fti->fonts[tpi->chunks[trec].fi_idx]); + yheight = fsp->face->bbox.yMax - fsp->face->bbox.yMin; + if (ymax) { + tmp = tpi->chunks[trec].fs * (((double)fsp->face->bbox.yMax) / yheight); + if (*ymax <= tmp) { + *ymax = tmp; + baseline = bri->rects[trec].yll - tpi->chunks[trec].boff; + } + } else if (ymin) { + tmp = tpi->chunks[trec].fs * + (((double)-fsp->face->bbox.yMin) / yheight); /* yMin in face is negative */ + if (*ymin <= tmp) { + *ymin = tmp; + baseline = bri->rects[trec].yll - tpi->chunks[trec].boff; + } } - } - } - break; - case TR_PARA_UJ: - case TR_PARA_LJ: - case TR_PARA_CJ: - case TR_PARA_RJ: - trec = cxi->cx[src].kids.members[last]; - baseline = TR_baseline(tri, trec, ymax, ymin); - break; - } - return(baseline); + } + break; + case TR_PARA_UJ: + case TR_PARA_LJ: + case TR_PARA_CJ: + case TR_PARA_RJ: + trec = cxi->cx[src].kids.members[last]; + baseline = TR_baseline(tri, trec, ymax, ymin); + break; + } + return (baseline); } /** @@ -522,7 +542,7 @@ double TR_baseline(TR_INFO *tri, int src, double *ymax, double *ymin){ If an existing vadvance does not match the one which would be required to fit the next complex to add to the growing one, it terminates a growing complex. (Ie, starts a new paragraph.) Find baseline on Y axis of a complex. - If the complex is a TR_TEXT or TR_LINE find its baseline. + If the complex is a TR_TEXT or TR_LINE find its baseline. If the complex is TR_PARA+* find the baseline of the last line. If there are multiple text elements in a TR_LINE, the baseline is that of the element that uses the largest font. This will definitely give the wrong @@ -536,73 +556,72 @@ double TR_baseline(TR_INFO *tri, int src, double *ymax, double *ymin){ since there can be some noise introduced when lines have different maximum font sizes. \param lines index of the first text block that was added to the growing complex. */ -int TR_check_set_vadvance(TR_INFO *tri, int src, int lines){ - int status = 0; - CX_INFO *cxi = tri->cxi; - TP_INFO *tpi = tri->tpi; - double ymax = DBL_MIN; - double ymin = DBL_MIN; - double prevbase; - double thisbase; - double weight; - int trec; - double newV; - int dst; - - dst = cxi->used-1; /* complex being grown */ - - prevbase = TR_baseline(tri, dst, NULL, &ymin); - thisbase = TR_baseline(tri, src, &ymax, NULL); - newV = (thisbase - prevbase)/(ymax + ymin); - trec = cxi->cx[dst].kids.members[0]; /* complex whose first text record holds vadvance for this complex */ - trec = cxi->cx[trec].kids.members[0]; /* text record that halds vadvance for this complex */ - if(tpi->chunks[trec].vadvance){ - /* already set on the first text (only place it is stored.) - See if the line to be added is compatible. - All text fields in a complex have the same advance, so just set/check the first one. - vadvance must be within 1% or do not add a new line */ - if(fabs(1.0 - (tpi->chunks[trec].vadvance/newV)) > 0.01){ - status = 1; - } - else { /* recalculate the weighted vadvance */ - weight = (1.0 / (double) (src - lines)); - tpi->chunks[trec].vadvance = tpi->chunks[trec].vadvance*(1.0-weight) + newV*weight; - } - } - else { /* only happens when src = lines + 1*/ - tpi->chunks[trec].vadvance = newV; - } - return(status); +int TR_check_set_vadvance(TR_INFO *tri, int src, int lines) +{ + int status = 0; + CX_INFO *cxi = tri->cxi; + TP_INFO *tpi = tri->tpi; + double ymax = DBL_MIN; + double ymin = DBL_MIN; + double prevbase; + double thisbase; + double weight; + int trec; + double newV; + int dst; + + dst = cxi->used - 1; /* complex being grown */ + + prevbase = TR_baseline(tri, dst, NULL, &ymin); + thisbase = TR_baseline(tri, src, &ymax, NULL); + newV = (thisbase - prevbase) / (ymax + ymin); + trec = cxi->cx[dst].kids.members[0]; /* complex whose first text record holds vadvance for this complex */ + trec = cxi->cx[trec].kids.members[0]; /* text record that halds vadvance for this complex */ + if (tpi->chunks[trec].vadvance) { + /* already set on the first text (only place it is stored.) + See if the line to be added is compatible. + All text fields in a complex have the same advance, so just set/check the first one. + vadvance must be within 1% or do not add a new line */ + if (fabs(1.0 - (tpi->chunks[trec].vadvance / newV)) > 0.01) { + status = 1; + } else { /* recalculate the weighted vadvance */ + weight = (1.0 / (double)(src - lines)); + tpi->chunks[trec].vadvance = tpi->chunks[trec].vadvance * (1.0 - weight) + newV * weight; + } + } else { /* only happens when src = lines + 1*/ + tpi->chunks[trec].vadvance = newV; + } + return (status); } - /** \brief Initialize an FT_INFO structure. Sets up a freetype library to use in this context. \returns a pointer to the FT_INFO structure created, or NULL on error. */ -FT_INFO *ftinfo_init(void){ - FT_INFO *fti = NULL; - if(FcInit()){ - fti = (FT_INFO *)calloc(1,sizeof(FT_INFO)); - if(fti){ - if(!FT_Init_FreeType( &(fti->library))){ - fti->space=0; - fti->used=0; - - if(ftinfo_make_insertable(fti)){ - FT_Done_FreeType(fti->library); - free(fti); - fti=NULL; +FT_INFO *ftinfo_init(void) +{ + FT_INFO *fti = NULL; + if (FcInit()) { + fti = (FT_INFO *)calloc(1, sizeof(FT_INFO)); + if (fti) { + if (!FT_Init_FreeType(&(fti->library))) { + fti->space = 0; + fti->used = 0; + + if (ftinfo_make_insertable(fti)) { + FT_Done_FreeType(fti->library); + free(fti); + fti = NULL; + } + } else { + free(fti); + fti = NULL; } - } - else { - free(fti); - fti=NULL; - } - } - if(!fti)FcFini(); - } - return(fti); + } + if (!fti) + FcFini(); + } + return (fti); } /** @@ -610,57 +629,58 @@ FT_INFO *ftinfo_init(void){ \param fti pointer to the FT_INFO structure \returns 0 on success, !0 on error. */ -int ftinfo_make_insertable(FT_INFO *fti){ - int status=0; - FNT_SPECS *tmp; - if(!fti)return(2); - if(fti->used >= fti->space){ - fti->space += ALLOCINFO_CHUNK; - tmp = (FNT_SPECS *) realloc(fti->fonts, fti->space * sizeof(FNT_SPECS) ); - if(tmp){ - fti->fonts = tmp; - memset(&fti->fonts[fti->used],0,(fti->space - fti->used)*sizeof(FNT_SPECS)); - } - else { - status=1; - } - } - return(status); +int ftinfo_make_insertable(FT_INFO *fti) +{ + int status = 0; + FNT_SPECS *tmp; + if (!fti) + return (2); + if (fti->used >= fti->space) { + fti->space += ALLOCINFO_CHUNK; + tmp = (FNT_SPECS *)realloc(fti->fonts, fti->space * sizeof(FNT_SPECS)); + if (tmp) { + fti->fonts = tmp; + memset(&fti->fonts[fti->used], 0, (fti->space - fti->used) * sizeof(FNT_SPECS)); + } else { + status = 1; + } + } + return (status); } - /** \brief Insert a copy of a FNT_SPECS structure into the FT_INFO structure. \param fti pointer to the FT_INFO structure. \param fsp pointer to the FNT_SPECS structure. \returns 0 on success, !0 on error. */ -int ftinfo_insert(FT_INFO *fti, FNT_SPECS *fsp){ - int status=1; - if(!fti)return(2); - if(!fsp)return(3); - if(!(status = ftinfo_make_insertable(fti))){ - memcpy(&(fti->fonts[fti->used]),fsp,sizeof(FNT_SPECS)); - fti->used++; - } - return(status); +int ftinfo_insert(FT_INFO *fti, FNT_SPECS *fsp) +{ + int status = 1; + if (!fti) + return (2); + if (!fsp) + return (3); + if (!(status = ftinfo_make_insertable(fti))) { + memcpy(&(fti->fonts[fti->used]), fsp, sizeof(FNT_SPECS)); + fti->used++; + } + return (status); } - - /** \brief Release an FT_INFO structure. Release all associated memory. Use like: fi_ptr = ftinfo_release(fi_ptr) \param fti pointer to the FT_INFO structure. \returns NULL. */ -FT_INFO *ftinfo_release(FT_INFO *fti){ - (void) ftinfo_clear(fti); - FcFini(); /* shut down FontConfig, release memory, patterns must have already been released or boom! */ - return NULL; +FT_INFO *ftinfo_release(FT_INFO *fti) +{ + (void)ftinfo_clear(fti); + FcFini(); /* shut down FontConfig, release memory, patterns must have already been released or boom! */ + return NULL; } - /** \brief Clear an FT_INFO structure. Release all Freetype memory but does not release Fontconfig. This would be called in preference to ftinfo_release() if some other part of the program needed @@ -669,27 +689,29 @@ FT_INFO *ftinfo_release(FT_INFO *fti){ \param fti pointer to the FT_INFO structure. \returns NULL. */ -FT_INFO *ftinfo_clear(FT_INFO *fti){ - uint32_t i; - FNT_SPECS *fsp; - if(fti){ - for(i=0;iused;i++){ - fsp = &(fti->fonts[i]); - FT_Done_Face(fsp->face); /* release memory for face controlled by FreeType */ - free(fsp->file); /* release memory holding copies of paths */ - free(fsp->fontspec); /* release memory holding copies of font names */ - FcPatternDestroy(fsp->fpat); /* release memory for FontConfig fpats */ - FcFontSetDestroy(fsp->fontset); - if(fsp->alts){ free(fsp->alts); } - } - free(fti->fonts); - FT_Done_FreeType(fti->library); /* release all other FreeType memory */ - free(fti); - } - return NULL; +FT_INFO *ftinfo_clear(FT_INFO *fti) +{ + uint32_t i; + FNT_SPECS *fsp; + if (fti) { + for (i = 0; i < fti->used; i++) { + fsp = &(fti->fonts[i]); + FT_Done_Face(fsp->face); /* release memory for face controlled by FreeType */ + free(fsp->file); /* release memory holding copies of paths */ + free(fsp->fontspec); /* release memory holding copies of font names */ + FcPatternDestroy(fsp->fpat); /* release memory for FontConfig fpats */ + FcFontSetDestroy(fsp->fontset); + if (fsp->alts) { + free(fsp->alts); + } + } + free(fti->fonts); + FT_Done_FreeType(fti->library); /* release all other FreeType memory */ + free(fti); + } + return NULL; } - /** \brief Find the loaded font matching fontspec \returns index of font on success, -1 if not found @@ -697,17 +719,18 @@ FT_INFO *ftinfo_clear(FT_INFO *fti){ \param fontspec UTF-8 description of the font, as constructed in trinfo_load_fontname */ -int ftinfo_find_loaded_by_spec(const FT_INFO *fti, const uint8_t *fontspec){ - uint32_t i; - int status = -1; - /* If it is already loaded, do not load it again */ - for(i=0;iused;i++){ - if(0==strcmp((char *) fti->fonts[i].fontspec, (char *)fontspec)){ - status=i; - break; - } - } - return(status); +int ftinfo_find_loaded_by_spec(const FT_INFO *fti, const uint8_t *fontspec) +{ + uint32_t i; + int status = -1; + /* If it is already loaded, do not load it again */ + for (i = 0; i < fti->used; i++) { + if (0 == strcmp((char *)fti->fonts[i].fontspec, (char *)fontspec)) { + status = i; + break; + } + } + return (status); } /** @@ -717,20 +740,20 @@ int ftinfo_find_loaded_by_spec(const FT_INFO *fti, const uint8_t *fontspec){ \param filename UTF-8 file name for the font */ -int ftinfo_find_loaded_by_src(const FT_INFO *fti, const uint8_t *filename){ - uint32_t i; - int status = -1; - /* If it is already loaded, do not load it again */ - for(i=0;iused;i++){ - if(0==strcmp((char *) fti->fonts[i].file, (char *) filename)){ - status=i; - break; - } - } - return(status); +int ftinfo_find_loaded_by_src(const FT_INFO *fti, const uint8_t *filename) +{ + uint32_t i; + int status = -1; + /* If it is already loaded, do not load it again */ + for (i = 0; i < fti->used; i++) { + if (0 == strcmp((char *)fti->fonts[i].file, (char *)filename)) { + status = i; + break; + } + } + return (status); } - /** \brief Load a (new) font by name into a TR_INFO structure or find it if it is already loaded \returns fi_idx of inserted (or found) font on success, <0 on error. @@ -739,159 +762,196 @@ int ftinfo_find_loaded_by_src(const FT_INFO *fti, const uint8_t *filename){ \param fontspec UTF-8 font specification used for query string. */ -int ftinfo_load_fontname(FT_INFO *fti, const char *fontspec){ - FcPattern *pattern = NULL; - FcPattern *fpat = NULL; - FcFontSet *fontset = NULL; - FcResult result = FcResultMatch; - char *filename; - double fd; - FNT_SPECS *fsp; - int status; - int fi_idx; - - if(!fti)return(-1); - - /* If it is already loaded, do not load it again */ - status = ftinfo_find_loaded_by_spec(fti, (uint8_t *) fontspec); - if(status >= 0){ return(status); } - status = 0; /* was -1, reset to 0 */ - - ftinfo_make_insertable(fti); - fi_idx = fti->used; - - pattern = FcNameParse((const FcChar8 *)fontspec); - while(1) { /* this is NOT a loop, it uses breaks to avoid gotos and deep nesting */ - if(!(pattern)){ status = -2; break; } - if(!FcConfigSubstitute(NULL, pattern, FcMatchPattern)){ status = -3; break; }; - FcDefaultSubstitute(pattern); - /* get a fontset, trimmed to only those with new glyphs as needed, so that missing glyph's may be handled */ - if(!(fontset = FcFontSort (NULL,pattern, FcTrue, NULL, &result)) || (result != FcResultMatch)){ status = -4; break; } - if(!(fpat = FcFontRenderPrepare(NULL, pattern, fontset->fonts[0]))){ status = -405; break; } - if(FcPatternGetString( fpat, FC_FILE, 0, (FcChar8 **)&filename) != FcResultMatch){ status = -5; break; } - if(FcPatternGetDouble( fpat, FC_SIZE, 0, &fd) != FcResultMatch){ status = -6; break; } - - /* copy these into memory for external use */ - fsp = &(fti->fonts[fti->used]); - fsp->fontset = fontset; - fsp->alts = NULL; /* Initially no links to alternate fonts */ - fsp->space = 0; - fsp->file = (uint8_t *) U_strdup((char *) filename); - fsp->fontspec = (uint8_t *) U_strdup((char *) fontspec); - fsp->fpat = fpat; - fsp->fsize = fd; - break; - } - /* release FC's own memory related to this call that does not need to be kept around so that face will work */ - if(pattern)FcPatternDestroy(pattern); /* done with this memory */ - if(status<0){ - if(fontset)FcFontSetDestroy(fontset); - if(fpat)FcPatternDestroy(fpat); - return(status); - } - - /* get the current face */ - if(FT_New_Face( fti->library, (const char *) fsp->file, 0, &(fsp->face) )){ return(-8); } - - if(FT_Set_Char_Size( - fsp->face, /* handle to face object */ - 0, /* char_width in 1/64th of points */ - fd*64, /* char_height in 1/64th of points */ - 72, /* horizontal device resolution, DPI */ - 72) /* vebrical device resolution, DPI */ - ){ return(-9); } - - /* The space advance is needed in various places. Get it now, and get it in the font units, - so that it can be scaled later with the text size */ - status = TR_getadvance(fti, fsp,' ',0,FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, FT_KERNING_UNSCALED, NULL, NULL); - if(status < 0)return(-7); - fsp->spcadv = ((double) status)/(64.0); - - fti->used++; - -/* - char *fs; - int fb; - if(FcPatternGetBool( fpat, FC_OUTLINE, 0, &fb)== FcResultMatch){ printf("outline: %d\n",fb);fflush(stdout); } - if(FcPatternGetBool( fpat, FC_SCALABLE, 0, &fb)== FcResultMatch){ printf("scalable: %d\n",fb);fflush(stdout); } - if(FcPatternGetDouble( fpat, FC_DPI, 0, &fd)== FcResultMatch){ printf("DPI: %f\n",fd);fflush(stdout); } - if(FcPatternGetInteger( fpat, FC_FONTVERSION, 0, &fb)== FcResultMatch){ printf("fontversion: %d\n",fb);fflush(stdout); } - if(FcPatternGetString( fpat, FC_FULLNAME , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("FULLNAME : %s\n",fs);fflush(stdout); } - if(FcPatternGetString( fpat, FC_FAMILY , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("FAMILY : %s\n",fs);fflush(stdout); } - if(FcPatternGetString( fpat, FC_STYLE , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("STYLE : %s\n",fs);fflush(stdout); } - if(FcPatternGetString( fpat, FC_FOUNDRY , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("FOUNDRY : %s\n",fs);fflush(stdout); } - if(FcPatternGetString( fpat, FC_FAMILYLANG , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("FAMILYLANG : %s\n",fs);fflush(stdout); } - if(FcPatternGetString( fpat, FC_STYLELANG , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("STYLELANG : %s\n",fs);fflush(stdout); } - if(FcPatternGetString( fpat, FC_FULLNAMELANG, 0, (FcChar8 **)&fs)== FcResultMatch){ printf("FULLNAMELANG: %s\n",fs);fflush(stdout); } - if(FcPatternGetString( fpat, FC_CAPABILITY , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("CAPABILITY : %s\n",fs);fflush(stdout); } - if(FcPatternGetString( fpat, FC_FONTFORMAT , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("FONTFORMAT : %s\n",fs);fflush(stdout); } -*/ - - return(fi_idx); +int ftinfo_load_fontname(FT_INFO *fti, const char *fontspec) +{ + FcPattern *pattern = NULL; + FcPattern *fpat = NULL; + FcFontSet *fontset = NULL; + FcResult result = FcResultMatch; + char *filename; + double fd; + FNT_SPECS *fsp; + int status; + int fi_idx; + + if (!fti) + return (-1); + + /* If it is already loaded, do not load it again */ + status = ftinfo_find_loaded_by_spec(fti, (uint8_t *)fontspec); + if (status >= 0) { + return (status); + } + status = 0; /* was -1, reset to 0 */ + + ftinfo_make_insertable(fti); + fi_idx = fti->used; + + pattern = FcNameParse((const FcChar8 *)fontspec); + while (1) { /* this is NOT a loop, it uses breaks to avoid gotos and deep nesting */ + if (!(pattern)) { + status = -2; + break; + } + if (!FcConfigSubstitute(NULL, pattern, FcMatchPattern)) { + status = -3; + break; + }; + FcDefaultSubstitute(pattern); + /* get a fontset, trimmed to only those with new glyphs as needed, so that missing glyph's may be handled */ + if (!(fontset = FcFontSort(NULL, pattern, FcTrue, NULL, &result)) || (result != FcResultMatch)) { + status = -4; + break; + } + if (!(fpat = FcFontRenderPrepare(NULL, pattern, fontset->fonts[0]))) { + status = -405; + break; + } + if (FcPatternGetString(fpat, FC_FILE, 0, (FcChar8 **)&filename) != FcResultMatch) { + status = -5; + break; + } + if (FcPatternGetDouble(fpat, FC_SIZE, 0, &fd) != FcResultMatch) { + status = -6; + break; + } + + /* copy these into memory for external use */ + fsp = &(fti->fonts[fti->used]); + fsp->fontset = fontset; + fsp->alts = NULL; /* Initially no links to alternate fonts */ + fsp->space = 0; + fsp->file = (uint8_t *)U_strdup((char *)filename); + fsp->fontspec = (uint8_t *)U_strdup((char *)fontspec); + fsp->fpat = fpat; + fsp->fsize = fd; + break; + } + /* release FC's own memory related to this call that does not need to be kept around so that face will work */ + if (pattern) + FcPatternDestroy(pattern); /* done with this memory */ + if (status < 0) { + if (fontset) + FcFontSetDestroy(fontset); + if (fpat) + FcPatternDestroy(fpat); + return (status); + } + + /* get the current face */ + if (FT_New_Face(fti->library, (const char *)fsp->file, 0, &(fsp->face))) { + return (-8); + } + + if (FT_Set_Char_Size(fsp->face, /* handle to face object */ + 0, /* char_width in 1/64th of points */ + fd * 64, /* char_height in 1/64th of points */ + 72, /* horizontal device resolution, DPI */ + 72) /* vebrical device resolution, DPI */ + ) { + return (-9); + } + + /* The space advance is needed in various places. Get it now, and get it in the font units, + so that it can be scaled later with the text size */ + status = TR_getadvance(fti, fsp, ' ', 0, FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, + FT_KERNING_UNSCALED, NULL, NULL); + if (status < 0) + return (-7); + fsp->spcadv = ((double)status) / (64.0); + + fti->used++; + + /* + char *fs; + int fb; + if(FcPatternGetBool( fpat, FC_OUTLINE, 0, &fb)== FcResultMatch){ printf("outline: + %d\n",fb);fflush(stdout); } if(FcPatternGetBool( fpat, FC_SCALABLE, 0, &fb)== FcResultMatch){ + printf("scalable: %d\n",fb);fflush(stdout); } if(FcPatternGetDouble( fpat, FC_DPI, 0, &fd)== + FcResultMatch){ printf("DPI: %f\n",fd);fflush(stdout); } if(FcPatternGetInteger( fpat, FC_FONTVERSION, + 0, &fb)== FcResultMatch){ printf("fontversion: %d\n",fb);fflush(stdout); } if(FcPatternGetString( fpat, + FC_FULLNAME , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("FULLNAME : %s\n",fs);fflush(stdout); } + if(FcPatternGetString( fpat, FC_FAMILY , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("FAMILY : + %s\n",fs);fflush(stdout); } if(FcPatternGetString( fpat, FC_STYLE , 0, (FcChar8 **)&fs)== + FcResultMatch){ printf("STYLE : %s\n",fs);fflush(stdout); } if(FcPatternGetString( fpat, FC_FOUNDRY , + 0, (FcChar8 **)&fs)== FcResultMatch){ printf("FOUNDRY : %s\n",fs);fflush(stdout); } + if(FcPatternGetString( fpat, FC_FAMILYLANG , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("FAMILYLANG : + %s\n",fs);fflush(stdout); } if(FcPatternGetString( fpat, FC_STYLELANG , 0, (FcChar8 **)&fs)== + FcResultMatch){ printf("STYLELANG : %s\n",fs);fflush(stdout); } if(FcPatternGetString( fpat, + FC_FULLNAMELANG, 0, (FcChar8 **)&fs)== FcResultMatch){ printf("FULLNAMELANG: %s\n",fs);fflush(stdout); } + if(FcPatternGetString( fpat, FC_CAPABILITY , 0, (FcChar8 **)&fs)== FcResultMatch){ printf("CAPABILITY : + %s\n",fs);fflush(stdout); } if(FcPatternGetString( fpat, FC_FONTFORMAT , 0, (FcChar8 **)&fs)== + FcResultMatch){ printf("FONTFORMAT : %s\n",fs);fflush(stdout); } + */ + + return (fi_idx); } /** \brief Dump the contents of the TR_INFO structure to stdout. For debugging purposes,not used in production code. \param tri pointer to the TR_INFO structure. */ -void ftinfo_dump(const FT_INFO *fti){ - uint32_t i,j; - FNT_SPECS *fsp; - printf("fti space: %d\n",fti->space); - printf("fti used: %d\n",fti->used); - for(i=0; i< fti->used; i++){ - fsp = &(fti->fonts[i]); - printf("fti font: %6d space: %6d used: %6d spcadv %8f fsize %8f \n",i,fsp->space,fsp->used,fsp->spcadv,fsp->fsize); - printf(" file: %s\n",fsp->file); - printf(" fspc: %s\n",fsp->fontspec); - for(j=0;jused;j++){ - printf(" alts: %6d fi_idx: %6d wgt: %6d\n",j,fsp->alts[j].fi_idx,fsp->alts[j].weight); - } - } - -} - +void ftinfo_dump(const FT_INFO *fti) +{ + uint32_t i, j; + FNT_SPECS *fsp; + printf("fti space: %d\n", fti->space); + printf("fti used: %d\n", fti->used); + for (i = 0; i < fti->used; i++) { + fsp = &(fti->fonts[i]); + printf("fti font: %6d space: %6d used: %6d spcadv %8f fsize %8f \n", i, fsp->space, fsp->used, fsp->spcadv, + fsp->fsize); + printf(" file: %s\n", fsp->file); + printf(" fspc: %s\n", fsp->fontspec); + for (j = 0; j < fsp->used; j++) { + printf(" alts: %6d fi_idx: %6d wgt: %6d\n", j, fsp->alts[j].fi_idx, fsp->alts[j].weight); + } + } +} + /** \brief Make the FNT_SPECS alts structure insertable. Adds storage as needed. \param fti pointer to the FT_INFO structure \returns 0 on success, !0 on error. */ -int fsp_alts_make_insertable(FNT_SPECS *fsp){ - int status=0; - ALT_SPECS *tmp; - if(!fsp)return(2); - if(fsp->used >= fsp->space){ - fsp->space += ALLOCINFO_CHUNK; - tmp = (ALT_SPECS *) realloc(fsp->alts, fsp->space * sizeof(ALT_SPECS) ); - if(tmp){ - fsp->alts = tmp; - memset(&fsp->alts[fsp->used],0,(fsp->space - fsp->used)*sizeof(ALT_SPECS)); - } - else { - status=1; - } - } - return(status); +int fsp_alts_make_insertable(FNT_SPECS *fsp) +{ + int status = 0; + ALT_SPECS *tmp; + if (!fsp) + return (2); + if (fsp->used >= fsp->space) { + fsp->space += ALLOCINFO_CHUNK; + tmp = (ALT_SPECS *)realloc(fsp->alts, fsp->space * sizeof(ALT_SPECS)); + if (tmp) { + fsp->alts = tmp; + memset(&fsp->alts[fsp->used], 0, (fsp->space - fsp->used) * sizeof(ALT_SPECS)); + } else { + status = 1; + } + } + return (status); } - /** \brief Insert a new ALT_SPECS into the FNT_SPECS alts list. \param fsp pointer to the FNT_SPECS structure. \param fi_idx font index to add to the alts list \returns 0 on success, !0 on error. */ -int fsp_alts_insert(FNT_SPECS *fsp, uint32_t fi_idx){ - int status=1; - ALT_SPECS alt; - if(!fsp)return(3); - alt.fi_idx = fi_idx; - alt.weight = 1; /* new ones start with this weight, it can only go up */ - if(!(status = fsp_alts_make_insertable(fsp))){ - fsp->alts[fsp->used] = alt; - fsp->used++; - } - return(status); +int fsp_alts_insert(FNT_SPECS *fsp, uint32_t fi_idx) +{ + int status = 1; + ALT_SPECS alt; + if (!fsp) + return (3); + alt.fi_idx = fi_idx; + alt.weight = 1; /* new ones start with this weight, it can only go up */ + if (!(status = fsp_alts_make_insertable(fsp))) { + fsp->alts[fsp->used] = alt; + fsp->used++; + } + return (status); } /** @@ -900,49 +960,55 @@ int fsp_alts_insert(FNT_SPECS *fsp, uint32_t fi_idx){ \param idx index of the alts entry to increment \returns 0 on success, !0 on error. */ -int fsp_alts_weight(FNT_SPECS *fsp, uint32_t a_idx){ - uint32_t i; - ALT_SPECS alt; - if(!fsp)return(1); - if(!fsp->used)return(2); - if(a_idx >= fsp->used)return(3); - /* If a counter hits the limit divide all counts in half. */ - if(fsp->alts[a_idx].weight == UINT32_MAX){ - for(i=0; iused; i++){ fsp->alts[i].weight /= 2; } - } - fsp->alts[a_idx].weight++; - for(i=a_idx; i>0; i--){ - if(fsp->alts[i-1].weight >= fsp->alts[a_idx].weight)break; - alt = fsp->alts[i-1]; - fsp->alts[i-1] = fsp->alts[a_idx]; - fsp->alts[a_idx] = alt; - } - return(0); +int fsp_alts_weight(FNT_SPECS *fsp, uint32_t a_idx) +{ + uint32_t i; + ALT_SPECS alt; + if (!fsp) + return (1); + if (!fsp->used) + return (2); + if (a_idx >= fsp->used) + return (3); + /* If a counter hits the limit divide all counts in half. */ + if (fsp->alts[a_idx].weight == UINT32_MAX) { + for (i = 0; i < fsp->used; i++) { + fsp->alts[i].weight /= 2; + } + } + fsp->alts[a_idx].weight++; + for (i = a_idx; i > 0; i--) { + if (fsp->alts[i - 1].weight >= fsp->alts[a_idx].weight) + break; + alt = fsp->alts[i - 1]; + fsp->alts[i - 1] = fsp->alts[a_idx]; + fsp->alts[a_idx] = alt; + } + return (0); } - - /** \brief Make a CHILD_SPECS structure insertable. Adds storage as needed. \param csp pointer to the CHILD_SPECS structure \returns 0 on success, !0 on error. */ -int csp_make_insertable(CHILD_SPECS *csp){ - int status=0; - int *tmp; - if(!csp)return(2); - if(csp->used >= csp->space){ - csp->space += ALLOCINFO_CHUNK; - tmp = (int *) realloc(csp->members, csp->space * sizeof(int) ); - if(tmp){ - csp->members = tmp; - memset(&csp->members[csp->used],0,(csp->space - csp->used)*sizeof(int)); - } - else { - status=1; - } - } - return(status); +int csp_make_insertable(CHILD_SPECS *csp) +{ + int status = 0; + int *tmp; + if (!csp) + return (2); + if (csp->used >= csp->space) { + csp->space += ALLOCINFO_CHUNK; + tmp = (int *)realloc(csp->members, csp->space * sizeof(int)); + if (tmp) { + csp->members = tmp; + memset(&csp->members[csp->used], 0, (csp->space - csp->used) * sizeof(int)); + } else { + status = 1; + } + } + return (status); } /** @@ -951,34 +1017,40 @@ int csp_make_insertable(CHILD_SPECS *csp){ \param src index of the member. \returns 0 on success, !0 on error. */ -int csp_insert(CHILD_SPECS *dst, int src){ - int status=1; - if(!dst)return(2); - if(!(status=csp_make_insertable(dst))){ - dst->members[dst->used]=src; - dst->used++; - } - return(status); +int csp_insert(CHILD_SPECS *dst, int src) +{ + int status = 1; + if (!dst) + return (2); + if (!(status = csp_make_insertable(dst))) { + dst->members[dst->used] = src; + dst->used++; + } + return (status); } /** - \brief Append all the members of one CHILD_SPECS structure to another CHILD_SPECS structure. + \brief Append all the members of one CHILD_SPECS structure to another CHILD_SPECS structure. Member is an index for either a text object or a complex. The donor is not modified. \param dst pointer to the recipient CHILD_SPECS structure. \param src pointer to the donor CHILD_SPECS structure. \returns 0 on success, !0 on error. */ -int csp_merge(CHILD_SPECS *dst, CHILD_SPECS *src){ - uint32_t i; - int status=1; - if(!dst)return(2); - if(!src)return(3); - for(i=0;iused;i++){ - status = csp_insert(dst, src->members[i]); - if(status)break; - } - return(status); +int csp_merge(CHILD_SPECS *dst, CHILD_SPECS *src) +{ + uint32_t i; + int status = 1; + if (!dst) + return (2); + if (!src) + return (3); + for (i = 0; i < src->used; i++) { + status = csp_insert(dst, src->members[i]); + if (status) + break; + } + return (status); } /** @@ -986,12 +1058,13 @@ int csp_merge(CHILD_SPECS *dst, CHILD_SPECS *src){ \param csp pointer to the CHILD_SPECS structure. \returns NULL. */ -void csp_release(CHILD_SPECS *csp){ - if(csp){ - free(csp->members); - csp->space = 0; - csp->used = 0; - } +void csp_release(CHILD_SPECS *csp) +{ + if (csp) { + free(csp->members); + csp->space = 0; + csp->used = 0; + } } /** @@ -999,25 +1072,26 @@ void csp_release(CHILD_SPECS *csp){ \param csp pointer to the CHILD_SPECS structure. \returns NULL. */ -void csp_clear(CHILD_SPECS *csp){ - csp->used = 0; +void csp_clear(CHILD_SPECS *csp) +{ + csp->used = 0; } - /** \brief Initialize an CX_INFO structure. Holds complexes (multiple text objects in known positions and order.) \returns a pointer to the CX_INFO structure created, or NULL on error. */ -CX_INFO *cxinfo_init(void){ - CX_INFO *cxi = NULL; - cxi = (CX_INFO *)calloc(1,sizeof(CX_INFO)); - if(cxi){ - if(cxinfo_make_insertable(cxi)){ - free(cxi); - cxi=NULL; - } - } - return(cxi); +CX_INFO *cxinfo_init(void) +{ + CX_INFO *cxi = NULL; + cxi = (CX_INFO *)calloc(1, sizeof(CX_INFO)); + if (cxi) { + if (cxinfo_make_insertable(cxi)) { + free(cxi); + cxi = NULL; + } + } + return (cxi); } /** @@ -1025,21 +1099,21 @@ CX_INFO *cxinfo_init(void){ \returns 0 on success, !0 on error. \param cxi pointer to the CX_INFO structure */ -int cxinfo_make_insertable(CX_INFO *cxi){ - int status=0; - CX_SPECS *tmp; - if(cxi->used >= cxi->space){ - cxi->space += ALLOCINFO_CHUNK; - tmp = (CX_SPECS *) realloc(cxi->cx, cxi->space * sizeof(CX_SPECS) ); - if(tmp){ - cxi->cx = tmp; - memset(&cxi->cx[cxi->used],0,(cxi->space - cxi->used)*sizeof(CX_SPECS)); - } - else { - status=1; - } - } - return(status); +int cxinfo_make_insertable(CX_INFO *cxi) +{ + int status = 0; + CX_SPECS *tmp; + if (cxi->used >= cxi->space) { + cxi->space += ALLOCINFO_CHUNK; + tmp = (CX_SPECS *)realloc(cxi->cx, cxi->space * sizeof(CX_SPECS)); + if (tmp) { + cxi->cx = tmp; + memset(&cxi->cx[cxi->used], 0, (cxi->space - cxi->used) * sizeof(CX_SPECS)); + } else { + status = 1; + } + } + return (status); } /** @@ -1050,16 +1124,18 @@ int cxinfo_make_insertable(CX_INFO *cxi){ \param src_rt_tidx index of the bounding rectangle \param type TR_TEXT (index is for tpi->chunks[]) or TR_LINE (index is for cxi->kids[]) */ -int cxinfo_insert(CX_INFO *cxi, int src, int src_rt_tidx, enum tr_classes type){ - int status=1; - if(!cxi)return(2); - if(!(status=cxinfo_make_insertable(cxi))){ - cxi->cx[cxi->used].rt_cidx = src_rt_tidx; - cxi->cx[cxi->used].type = type; - status = csp_insert(&(cxi->cx[cxi->used].kids), src); - cxi->used++; - } - return(status); +int cxinfo_insert(CX_INFO *cxi, int src, int src_rt_tidx, enum tr_classes type) +{ + int status = 1; + if (!cxi) + return (2); + if (!(status = cxinfo_make_insertable(cxi))) { + cxi->cx[cxi->used].rt_cidx = src_rt_tidx; + cxi->cx[cxi->used].type = type; + status = csp_insert(&(cxi->cx[cxi->used].kids), src); + cxi->used++; + } + return (status); } /** @@ -1069,17 +1145,18 @@ int cxinfo_insert(CX_INFO *cxi, int src, int src_rt_tidx, enum tr_classes type){ \param type TR_LINE (src is an index for tpi->chunks[]) or TR_PARA (src is an index for cxi->kids[]). \returns 0 on success, !0 on error. */ -int cxinfo_append(CX_INFO *cxi, int src, enum tr_classes type){ - int status=1; - if(!cxi)return(2); - if(!(status=cxinfo_make_insertable(cxi))){ - cxi->cx[cxi->used-1].type = type; - status = csp_insert(&(cxi->cx[cxi->used-1].kids), src); - } - return(status); +int cxinfo_append(CX_INFO *cxi, int src, enum tr_classes type) +{ + int status = 1; + if (!cxi) + return (2); + if (!(status = cxinfo_make_insertable(cxi))) { + cxi->cx[cxi->used - 1].type = type; + status = csp_insert(&(cxi->cx[cxi->used - 1].kids), src); + } + return (status); } - /** \brief Merge a complex dst with N members (N>=1) by adding a second complex src, and change the type. \param cxi pointer to the CX_INFO structure (complexes). @@ -1088,15 +1165,20 @@ int cxinfo_append(CX_INFO *cxi, int src, enum tr_classes type){ \param type TR_LINE (src is an index for tpi->chunks[]) or TR_PARA (src is an index for cxi->kids[]). \returns 0 on success, !0 on error. */ -int cxinfo_merge(CX_INFO *cxi, int dst, int src, enum tr_classes type){ - int status =1; - if(!cxi)return(2); - if(!cxi->used)return(3); - if(dst < 0 || dst >= (int) cxi->used)return(4); - if(src < 0)return(5); - cxi->cx[dst].type = type; - status = csp_merge(&(cxi->cx[dst].kids), &(cxi->cx[src].kids)); - return(status); +int cxinfo_merge(CX_INFO *cxi, int dst, int src, enum tr_classes type) +{ + int status = 1; + if (!cxi) + return (2); + if (!cxi->used) + return (3); + if (dst < 0 || dst >= (int)cxi->used) + return (4); + if (src < 0) + return (5); + cxi->cx[dst].type = type; + status = csp_merge(&(cxi->cx[dst].kids), &(cxi->cx[src].kids)); + return (status); } /** @@ -1104,60 +1186,62 @@ int cxinfo_merge(CX_INFO *cxi, int dst, int src, enum tr_classes type){ \param cxi pointer to the CX_INFO structure (complexes). \returns 0 on success, !0 on error. */ -int cxinfo_trim(CX_INFO *cxi){ - int status = 0; - int last ; - if(!cxi)return(1); - if(!cxi->used)return(2); - last = cxi->used - 1; - csp_clear(&(cxi->cx[last].kids)); - cxi->used--; - return(status); +int cxinfo_trim(CX_INFO *cxi) +{ + int status = 0; + int last; + if (!cxi) + return (1); + if (!cxi->used) + return (2); + last = cxi->used - 1; + csp_clear(&(cxi->cx[last].kids)); + cxi->used--; + return (status); } - /** \brief Dump the contents of the TR_INFO structure to stdout. For debugging purposes,not used in production code. \param tri pointer to the TR_INFO structure. */ -void cxinfo_dump(const TR_INFO *tri){ - uint32_t i,j,k; - CX_INFO *cxi = tri->cxi; - BR_INFO *bri = tri->bri; - TP_INFO *tpi = tri->tpi; - BRECT_SPECS *bsp; - CX_SPECS *csp; - if(cxi){ - printf("cxi space: %d\n",cxi->space); - printf("cxi used: %d\n",cxi->used); - printf("cxi phase1: %d\n",cxi->phase1); - printf("cxi lines: %d\n",cxi->lines); - printf("cxi paras: %d\n",cxi->paras); - printf("cxi xy: %f , %f\n",tri->x,tri->y); - - for(i=0;iused;i++){ - csp = &(cxi->cx[i]); - bsp = &(bri->rects[csp->rt_cidx]); - printf("cxi cx[%d] type:%d rt_tidx:%d kids_used:%d kids_space:%d\n",i, csp->type, csp->rt_cidx, csp->kids.used, csp->kids.space); - printf("cxi cx[%d] br (LL,UR) (%f,%f),(%f,%f)\n",i,bsp->xll,bsp->yll,bsp->xur,bsp->yur); - for(j=0;jkids.used;j++){ - k = csp->kids.members[j]; - bsp = &(bri->rects[k]); - if(csp->type == TR_TEXT || csp->type == TR_LINE){ - printf("cxi cx[%d] member:%3d tp_idx:%3d ldir:%d rt_tidx:%3d br (LL,UR) (%8.3f,%8.3f),(%8.3f,%8.3f) xy (%8.3f,%8.3f) kern (%8.3f,%8.3f) text:<%s> decor:%5.5x\n", - i, j, k, tpi->chunks[k].ldir, tpi->chunks[k].rt_tidx, - bsp->xll,bsp->yll,bsp->xur,bsp->yur, - tpi->chunks[k].x, tpi->chunks[k].y, - tpi->chunks[k].xkern, tpi->chunks[k].ykern, - tpi->chunks[k].string, tpi->chunks[k].decoration ); - } - else { /* TR_PARA_* */ - printf("cxi cx[%d] member:%d cx_idx:%d\n",i, j, k); +void cxinfo_dump(const TR_INFO *tri) +{ + uint32_t i, j, k; + CX_INFO *cxi = tri->cxi; + BR_INFO *bri = tri->bri; + TP_INFO *tpi = tri->tpi; + BRECT_SPECS *bsp; + CX_SPECS *csp; + if (cxi) { + printf("cxi space: %d\n", cxi->space); + printf("cxi used: %d\n", cxi->used); + printf("cxi phase1: %d\n", cxi->phase1); + printf("cxi lines: %d\n", cxi->lines); + printf("cxi paras: %d\n", cxi->paras); + printf("cxi xy: %f , %f\n", tri->x, tri->y); + + for (i = 0; i < cxi->used; i++) { + csp = &(cxi->cx[i]); + bsp = &(bri->rects[csp->rt_cidx]); + printf("cxi cx[%d] type:%d rt_tidx:%d kids_used:%d kids_space:%d\n", i, csp->type, csp->rt_cidx, + csp->kids.used, csp->kids.space); + printf("cxi cx[%d] br (LL,UR) (%f,%f),(%f,%f)\n", i, bsp->xll, bsp->yll, bsp->xur, bsp->yur); + for (j = 0; j < csp->kids.used; j++) { + k = csp->kids.members[j]; + bsp = &(bri->rects[k]); + if (csp->type == TR_TEXT || csp->type == TR_LINE) { + printf("cxi cx[%d] member:%3d tp_idx:%3d ldir:%d rt_tidx:%3d br (LL,UR) " + "(%8.3f,%8.3f),(%8.3f,%8.3f) xy (%8.3f,%8.3f) kern (%8.3f,%8.3f) text:<%s> decor:%5.5x\n", + i, j, k, tpi->chunks[k].ldir, tpi->chunks[k].rt_tidx, bsp->xll, bsp->yll, bsp->xur, bsp->yur, + tpi->chunks[k].x, tpi->chunks[k].y, tpi->chunks[k].xkern, tpi->chunks[k].ykern, + tpi->chunks[k].string, tpi->chunks[k].decoration); + } else { /* TR_PARA_* */ + printf("cxi cx[%d] member:%d cx_idx:%d\n", i, j, k); + } } - } - } - } - return; + } + } + return; } /** @@ -1166,54 +1250,56 @@ void cxinfo_dump(const TR_INFO *tri){ \param cxi pointer to the CX_INFO structure. \returns NULL. */ -CX_INFO *cxinfo_release(CX_INFO *cxi){ - uint32_t i; - if(cxi){ - for(i=0;iused;i++){ csp_release(&cxi->cx[i].kids); } - free(cxi->cx); - free(cxi); /* release the overall cxinfo structure */ - } - return NULL; +CX_INFO *cxinfo_release(CX_INFO *cxi) +{ + uint32_t i; + if (cxi) { + for (i = 0; i < cxi->used; i++) { + csp_release(&cxi->cx[i].kids); + } + free(cxi->cx); + free(cxi); /* release the overall cxinfo structure */ + } + return NULL; } - /** \brief Initialize an TP_INFO structure. Holds text objects from which complexes are built. \returns a pointer to the TP_INFO structure created, or NULL on error. */ -TP_INFO *tpinfo_init(void){ - TP_INFO *tpi = NULL; - tpi = (TP_INFO *)calloc(1,sizeof(TP_INFO)); - if(tpi){ - if(tpinfo_make_insertable(tpi)){ - free(tpi); - tpi=NULL; - } - } - return(tpi); +TP_INFO *tpinfo_init(void) +{ + TP_INFO *tpi = NULL; + tpi = (TP_INFO *)calloc(1, sizeof(TP_INFO)); + if (tpi) { + if (tpinfo_make_insertable(tpi)) { + free(tpi); + tpi = NULL; + } + } + return (tpi); } - /** \brief Make a TP_INFO structure insertable. Adds storage as needed. \returns 0 on success, !0 on error. \param tpi pointer to the TP_INFO structure */ -int tpinfo_make_insertable(TP_INFO *tpi){ - int status=0; - TCHUNK_SPECS *tmp; - if(tpi->used >= tpi->space){ - tpi->space += ALLOCINFO_CHUNK; - tmp = (TCHUNK_SPECS *) realloc(tpi->chunks, tpi->space * sizeof(TCHUNK_SPECS) ); - if(tmp){ - tpi->chunks = tmp; - memset(&tpi->chunks[tpi->used],0,(tpi->space - tpi->used)*sizeof(TCHUNK_SPECS)); - } - else { - status=1; - } - } - return(status); +int tpinfo_make_insertable(TP_INFO *tpi) +{ + int status = 0; + TCHUNK_SPECS *tmp; + if (tpi->used >= tpi->space) { + tpi->space += ALLOCINFO_CHUNK; + tmp = (TCHUNK_SPECS *)realloc(tpi->chunks, tpi->space * sizeof(TCHUNK_SPECS)); + if (tmp) { + tpi->chunks = tmp; + memset(&tpi->chunks[tpi->used], 0, (tpi->space - tpi->used) * sizeof(TCHUNK_SPECS)); + } else { + status = 1; + } + } + return (status); } /** @@ -1222,19 +1308,23 @@ int tpinfo_make_insertable(TP_INFO *tpi){ \param tpi pointer to the TP_INFO structure \param tsp pointer to the TCHUNK_SPECS structure */ -int tpinfo_insert(TP_INFO *tpi, const TCHUNK_SPECS *tsp){ - int status=1; - TCHUNK_SPECS *ltsp; - if(!tpi)return(2); - if(!tsp)return(3); - if(!(status = tpinfo_make_insertable(tpi))){ - ltsp = &(tpi->chunks[tpi->used]); - memcpy(ltsp,tsp,sizeof(TCHUNK_SPECS)); - if(tsp->co)ltsp->condensed = 75; /* Narrow was set in the font name */ - ltsp->xkern = ltsp->ykern = 0.0; /* kerning will be calculated from the derived layout */ - tpi->used++; - } - return(status); +int tpinfo_insert(TP_INFO *tpi, const TCHUNK_SPECS *tsp) +{ + int status = 1; + TCHUNK_SPECS *ltsp; + if (!tpi) + return (2); + if (!tsp) + return (3); + if (!(status = tpinfo_make_insertable(tpi))) { + ltsp = &(tpi->chunks[tpi->used]); + memcpy(ltsp, tsp, sizeof(TCHUNK_SPECS)); + if (tsp->co) + ltsp->condensed = 75; /* Narrow was set in the font name */ + ltsp->xkern = ltsp->ykern = 0.0; /* kerning will be calculated from the derived layout */ + tpi->used++; + } + return (status); } /** @@ -1243,31 +1333,34 @@ int tpinfo_insert(TP_INFO *tpi, const TCHUNK_SPECS *tsp){ \returns NULL. \param tpi pointer to the TP_INFO structure. */ -TP_INFO *tpinfo_release(TP_INFO *tpi){ - uint32_t i; - if(tpi){ - for(i=0;iused;i++){ - free(tpi->chunks[i].string); } - free(tpi->chunks); /* release the array */ - free(tpi); /* release the overall tpinfo structure */ - } - return NULL; +TP_INFO *tpinfo_release(TP_INFO *tpi) +{ + uint32_t i; + if (tpi) { + for (i = 0; i < tpi->used; i++) { + free(tpi->chunks[i].string); + } + free(tpi->chunks); /* release the array */ + free(tpi); /* release the overall tpinfo structure */ + } + return NULL; } /** \brief Initialize an BR_INFO structure. Holds bounding rectangles, for both text objects and complexes. \returns a pointer to the BR_INFO structure created, or NULL on error. */ -BR_INFO *brinfo_init(void){ - BR_INFO *bri = NULL; - bri = (BR_INFO *)calloc(1,sizeof(BR_INFO)); - if(bri){ - if(brinfo_make_insertable(bri)){ - free(bri); - bri=NULL; - } - } - return(bri); +BR_INFO *brinfo_init(void) +{ + BR_INFO *bri = NULL; + bri = (BR_INFO *)calloc(1, sizeof(BR_INFO)); + if (bri) { + if (brinfo_make_insertable(bri)) { + free(bri); + bri = NULL; + } + } + return (bri); } /** @@ -1275,17 +1368,22 @@ BR_INFO *brinfo_init(void){ \returns 0 on success, !0 on error. \param bri pointer to the BR_INFO structure */ -int brinfo_make_insertable(BR_INFO *bri){ - int status=0; - BRECT_SPECS *tmp; - if(!bri)return(2); - if(bri->used >= bri->space){ - bri->space += ALLOCINFO_CHUNK; - tmp = (BRECT_SPECS *) realloc(bri->rects, bri->space * sizeof(BRECT_SPECS) ); - if(tmp){ bri->rects = tmp; } - else { status = 1;} - } - return(status); +int brinfo_make_insertable(BR_INFO *bri) +{ + int status = 0; + BRECT_SPECS *tmp; + if (!bri) + return (2); + if (bri->used >= bri->space) { + bri->space += ALLOCINFO_CHUNK; + tmp = (BRECT_SPECS *)realloc(bri->rects, bri->space * sizeof(BRECT_SPECS)); + if (tmp) { + bri->rects = tmp; + } else { + status = 1; + } + } + return (status); } /** @@ -1294,44 +1392,49 @@ int brinfo_make_insertable(BR_INFO *bri){ \param bri pointer to the BR_INFO structure \param element pointer to the BRECT_SPECS structure */ -int brinfo_insert(BR_INFO *bri, const BRECT_SPECS *element){ - int status=1; - if(!bri)return(2); - if(!(status=brinfo_make_insertable(bri))){ - memcpy(&(bri->rects[bri->used]),element,sizeof(BRECT_SPECS)); - bri->used++; - } - return(status); +int brinfo_insert(BR_INFO *bri, const BRECT_SPECS *element) +{ + int status = 1; + if (!bri) + return (2); + if (!(status = brinfo_make_insertable(bri))) { + memcpy(&(bri->rects[bri->used]), element, sizeof(BRECT_SPECS)); + bri->used++; + } + return (status); } /** - \brief Merge BRECT_SPEC element src into/with BRECT_SPEC element dst. src is unchanged. (Merge two bounding rectangles.) - \returns 0 on success, !0 on error. - \param bri pointer to the BR_INFO structure - \param dst index of the destination bounding rectangle. - \param src index of the source bounding rectangle. -*/ -int brinfo_merge(BR_INFO *bri, int dst, int src){ - if(!bri)return(1); - if(!bri->used)return(2); - if(dst<0 || dst >= (int) bri->used)return(3); - if(src<0 || src >= (int) bri->used)return(4); - bri->rects[dst].xll = TEREMIN(bri->rects[dst].xll, bri->rects[src].xll); - bri->rects[dst].yll = TEREMAX(bri->rects[dst].yll, bri->rects[src].yll); /* MAX because Y is positive DOWN */ - bri->rects[dst].xur = TEREMAX(bri->rects[dst].xur, bri->rects[src].xur); - bri->rects[dst].yur = TEREMIN(bri->rects[dst].yur, bri->rects[src].yur); /* MIN because Y is positive DOWN */ -/* -printf("bri_Merge into rect:%d (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n",dst, -(bri->rects[dst].xll), -(bri->rects[dst].yll), -(bri->rects[dst].xur), -(bri->rects[dst].yur), -(bri->rects[src].xll), -(bri->rects[src].yll), -(bri->rects[src].xur), -(bri->rects[src].yur)); -*/ - return(0); + \brief Merge BRECT_SPEC element src into/with BRECT_SPEC element dst. src is unchanged. (Merge two bounding + rectangles.) \returns 0 on success, !0 on error. \param bri pointer to the BR_INFO structure \param dst index of the + destination bounding rectangle. \param src index of the source bounding rectangle. +*/ +int brinfo_merge(BR_INFO *bri, int dst, int src) +{ + if (!bri) + return (1); + if (!bri->used) + return (2); + if (dst < 0 || dst >= (int)bri->used) + return (3); + if (src < 0 || src >= (int)bri->used) + return (4); + bri->rects[dst].xll = TEREMIN(bri->rects[dst].xll, bri->rects[src].xll); + bri->rects[dst].yll = TEREMAX(bri->rects[dst].yll, bri->rects[src].yll); /* MAX because Y is positive DOWN */ + bri->rects[dst].xur = TEREMAX(bri->rects[dst].xur, bri->rects[src].xur); + bri->rects[dst].yur = TEREMIN(bri->rects[dst].yur, bri->rects[src].yur); /* MIN because Y is positive DOWN */ + /* + printf("bri_Merge into rect:%d (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n",dst, + (bri->rects[dst].xll), + (bri->rects[dst].yll), + (bri->rects[dst].xur), + (bri->rects[dst].yur), + (bri->rects[src].xll), + (bri->rects[src].yll), + (bri->rects[src].xur), + (bri->rects[src].yur)); + */ + return (0); } /** @@ -1339,7 +1442,7 @@ printf("bri_Merge into rect:%d (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n Allowable overlap is any area overlap of src and dst bounding rectangles, after they have been expanded (padded) by allowed edge expansions. (For instance, if missing spaces must be accounted for.) - The method works backwards: look for all reasons they might not overlap, + The method works backwards: look for all reasons they might not overlap, if none are found, then the rectangles do overlap. An overlap here does not count just a line or a point - area must be involved. \returns 0 on success (overlap detected), 1 on no overlap, anything else is an error. @@ -1349,109 +1452,118 @@ printf("bri_Merge into rect:%d (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n \param rp_dst Pointer to edge padding values for dst. \param rp_src Pointer to edge padding values for src. */ -int brinfo_overlap(const BR_INFO *bri, int dst, int src, RT_PAD *rp_dst, RT_PAD *rp_src){ - int status; - BRECT_SPECS *br_dst; - BRECT_SPECS *br_src; - if(!bri || !rp_dst || !rp_src)return(2); - if(!bri->used)return(3); - if(dst<0 || dst>= (int) bri->used)return(4); - if(src<0 || src>= (int) bri->used)return(5); - br_dst=&bri->rects[dst]; - br_src=&bri->rects[src]; - if( /* Test all conditions that exclude overlap, if any are true, then no overlap */ - ((br_dst->xur + rp_dst->right) < (br_src->xll - rp_src->left) ) || /* dst fully to the left */ - ((br_dst->xll - rp_dst->left) > (br_src->xur + rp_src->right) ) || /* dst fully to the right */ - ((br_dst->yur - rp_dst->up) > (br_src->yll + rp_src->down) ) || /* dst fully below (Y is positive DOWN) */ - ((br_dst->yll + rp_dst->down) < (br_src->yur - rp_src->up) ) /* dst fully above (Y is positive DOWN) */ - ){ - status = 1; - } - else { - /* overlap not excluded, so it must occur. - Only accept overlaps that are mostly at one end or the other, not mostly top or bottom. - If the following condition is true then there is no more than a tiny bit of horizontal overlap of src - within dist, which suggests that the two pieces of text may be considered part of one line. - (For a vertical alphabet the same method could be used for up/down.) */ - if( - (br_src->xll >= br_dst->xur - rp_dst->right) || /* src overlaps just a little on the right (L->R language) */ - (br_src->xur <= br_dst->xll + rp_dst->left) /* src overlaps just a little on the left (R->L language) */ - ){ - status = 0; - } - else { /* Too much overlap, reject the overlap */ - status = 1; - } - } -/* -printf("Overlap status:%d\nOverlap trects (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n", -status, -(br_dst->xll - rp_dst->left ), -(br_dst->yll - rp_dst->down ), -(br_dst->xur + rp_dst->right), -(br_dst->yur + rp_dst->up ), -(br_src->xll - rp_src->left ), -(br_src->yll - rp_src->down ), -(br_src->xur + rp_src->right), -(br_src->yur + rp_src->up )); -printf("Overlap brects (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n", -(br_dst->xll), -(br_dst->yll), -(br_dst->xur), -(br_dst->yur), -(br_src->xll), -(br_src->yll), -(br_src->xur), -(br_src->yur)); -printf("Overlap rprect (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n", -(rp_dst->left), -(rp_dst->down), -(rp_dst->right), -(rp_dst->up), -(rp_src->left), -(rp_src->down), -(rp_src->right), -(rp_src->up)); -*/ - return(status); +int brinfo_overlap(const BR_INFO *bri, int dst, int src, RT_PAD *rp_dst, RT_PAD *rp_src) +{ + int status; + BRECT_SPECS *br_dst; + BRECT_SPECS *br_src; + if (!bri || !rp_dst || !rp_src) + return (2); + if (!bri->used) + return (3); + if (dst < 0 || dst >= (int)bri->used) + return (4); + if (src < 0 || src >= (int)bri->used) + return (5); + br_dst = &bri->rects[dst]; + br_src = &bri->rects[src]; + if (/* Test all conditions that exclude overlap, if any are true, then no overlap */ + ((br_dst->xur + rp_dst->right) < (br_src->xll - rp_src->left)) || /* dst fully to the left */ + ((br_dst->xll - rp_dst->left) > (br_src->xur + rp_src->right)) || /* dst fully to the right */ + ((br_dst->yur - rp_dst->up) > (br_src->yll + rp_src->down)) || /* dst fully below (Y is positive DOWN) */ + ((br_dst->yll + rp_dst->down) < (br_src->yur - rp_src->up)) /* dst fully above (Y is positive DOWN) */ + ) { + status = 1; + } else { + /* overlap not excluded, so it must occur. + Only accept overlaps that are mostly at one end or the other, not mostly top or bottom. + If the following condition is true then there is no more than a tiny bit of horizontal overlap of src + within dist, which suggests that the two pieces of text may be considered part of one line. + (For a vertical alphabet the same method could be used for up/down.) */ + if ((br_src->xll >= br_dst->xur - rp_dst->right) || /* src overlaps just a little on the right (L->R language) + */ + (br_src->xur <= br_dst->xll + rp_dst->left) /* src overlaps just a little on the left (R->L language) */ + ) { + status = 0; + } else { /* Too much overlap, reject the overlap */ + status = 1; + } + } + /* + printf("Overlap status:%d\nOverlap trects (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n", + status, + (br_dst->xll - rp_dst->left ), + (br_dst->yll - rp_dst->down ), + (br_dst->xur + rp_dst->right), + (br_dst->yur + rp_dst->up ), + (br_src->xll - rp_src->left ), + (br_src->yll - rp_src->down ), + (br_src->xur + rp_src->right), + (br_src->yur + rp_src->up )); + printf("Overlap brects (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n", + (br_dst->xll), + (br_dst->yll), + (br_dst->xur), + (br_dst->yur), + (br_src->xll), + (br_src->yll), + (br_src->xur), + (br_src->yur)); + printf("Overlap rprect (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n", + (rp_dst->left), + (rp_dst->down), + (rp_dst->right), + (rp_dst->up), + (rp_src->left), + (rp_src->down), + (rp_src->right), + (rp_src->up)); + */ + return (status); } /** - \brief Check for various sorts of invalid text elements upstream (language dir changes, draw order backwards from language direction) - \returns 0 on success (not upstream), 1 if upstream, anything else is an error. - \param bri pointer to the BR_INFO structure - \param dst index of the destination bounding rectangle. - \param src index of the source bounding rectangle. - \param ddir direction of dst - \param sdir direction of src -*/ - -int brinfo_upstream(BR_INFO *bri, int dst, int src, int ddir, int sdir){ - int status=0; - BRECT_SPECS *br_dst; - BRECT_SPECS *br_src; - if(!bri)return(2); - if(!bri->used)return(3); - if(dst<0 || dst>= (int) bri->used)return(4); - if(src<0 || src>= (int) bri->used)return(5); - br_dst=&bri->rects[dst]; - br_src=&bri->rects[src]; - if( ddir == LDIR_RL && sdir == LDIR_LR){ - if(br_dst->xur <= (br_src->xll + br_src->xur)/2.0){ status = 1; } - } - else if( ddir == LDIR_LR && sdir == LDIR_RL){ - if((br_src->xll + br_src->xur)/2.0 <= br_dst->xll ){ status = 1; } - } - else if( ddir == LDIR_RL && sdir == LDIR_RL){ - if(br_dst->xur <= (br_src->xll + br_src->xur)/2.0){ status = 1; } - } - else if( ddir == LDIR_LR && sdir == LDIR_LR){ - if((br_src->xll + br_src->xur)/2.0 <= br_dst->xll ){ status = 1; } - } - return(status); + \brief Check for various sorts of invalid text elements upstream (language dir changes, draw order backwards from + language direction) \returns 0 on success (not upstream), 1 if upstream, anything else is an error. \param bri + pointer to the BR_INFO structure \param dst index of the destination bounding rectangle. \param src index of the + source bounding rectangle. \param ddir direction of dst \param sdir direction of src +*/ + +int brinfo_upstream(BR_INFO *bri, int dst, int src, int ddir, int sdir) +{ + int status = 0; + BRECT_SPECS *br_dst; + BRECT_SPECS *br_src; + if (!bri) + return (2); + if (!bri->used) + return (3); + if (dst < 0 || dst >= (int)bri->used) + return (4); + if (src < 0 || src >= (int)bri->used) + return (5); + br_dst = &bri->rects[dst]; + br_src = &bri->rects[src]; + if (ddir == LDIR_RL && sdir == LDIR_LR) { + if (br_dst->xur <= (br_src->xll + br_src->xur) / 2.0) { + status = 1; + } + } else if (ddir == LDIR_LR && sdir == LDIR_RL) { + if ((br_src->xll + br_src->xur) / 2.0 <= br_dst->xll) { + status = 1; + } + } else if (ddir == LDIR_RL && sdir == LDIR_RL) { + if (br_dst->xur <= (br_src->xll + br_src->xur) / 2.0) { + status = 1; + } + } else if (ddir == LDIR_LR && sdir == LDIR_LR) { + if ((br_src->xll + br_src->xur) / 2.0 <= br_dst->xll) { + status = 1; + } + } + return (status); } - /** \brief Try to deduce justification of a paragraph from the bounding rectangles for two successive lines. \returns one of TR_PARA_ UJ (unknown justified), LJ, CJ, or RJ (left, center, or right justified). @@ -1462,47 +1574,44 @@ int brinfo_upstream(BR_INFO *bri, int dst, int src, int ddir, int sdir){ \param type Preexisting justification for dst, if any. Justification of dst and src must match this or TR_PARA_UJ is returned even if dst and src have some (other) alignment. */ -enum tr_classes brinfo_pp_alignment(const BR_INFO *bri, int dst, int src, double slop, enum tr_classes type){ - enum tr_classes newtype; - BRECT_SPECS *br_dst = & bri->rects[dst]; - BRECT_SPECS *br_src = & bri->rects[src]; - if((br_dst->yur >= br_src->yur) || (br_dst->yll >= br_src->yll)){ /* Y is positive DOWN */ - /* lines in the wrong vertical order, no paragraph possible (Y is positive down) */ - newtype = TR_PARA_UJ; - } - else if(fabs(br_dst->xll - br_src->xll) < slop){ - /* LJ (might also be CJ but LJ takes precedence) */ - newtype = TR_PARA_LJ; - } - else if(fabs(br_dst->xur - br_src->xur) < slop){ - /* RJ */ - newtype = TR_PARA_RJ; - } - else if(fabs( (br_dst->xur + br_dst->xll)/2.0 - (br_src->xur + br_src->xll)/2.0 ) < slop){ - /* CJ */ - newtype = TR_PARA_CJ; - } - else { - /* not aligned */ - newtype = TR_PARA_UJ; - } - /* within a paragraph type can change from unknown to known, but not from one known type to another*/ - if((type != TR_PARA_UJ) && (newtype != type)){ - newtype = TR_PARA_UJ; - } -/* -printf("pp_align newtype:%d brects (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n", -newtype, -(br_dst->xll), -(br_dst->yll), -(br_dst->xur), -(br_dst->yur), -(br_src->xll), -(br_src->yll), -(br_src->xur), -(br_src->yur)); -*/ - return(newtype); +enum tr_classes brinfo_pp_alignment(const BR_INFO *bri, int dst, int src, double slop, enum tr_classes type) +{ + enum tr_classes newtype; + BRECT_SPECS *br_dst = &bri->rects[dst]; + BRECT_SPECS *br_src = &bri->rects[src]; + if ((br_dst->yur >= br_src->yur) || (br_dst->yll >= br_src->yll)) { /* Y is positive DOWN */ + /* lines in the wrong vertical order, no paragraph possible (Y is positive down) */ + newtype = TR_PARA_UJ; + } else if (fabs(br_dst->xll - br_src->xll) < slop) { + /* LJ (might also be CJ but LJ takes precedence) */ + newtype = TR_PARA_LJ; + } else if (fabs(br_dst->xur - br_src->xur) < slop) { + /* RJ */ + newtype = TR_PARA_RJ; + } else if (fabs((br_dst->xur + br_dst->xll) / 2.0 - (br_src->xur + br_src->xll) / 2.0) < slop) { + /* CJ */ + newtype = TR_PARA_CJ; + } else { + /* not aligned */ + newtype = TR_PARA_UJ; + } + /* within a paragraph type can change from unknown to known, but not from one known type to another*/ + if ((type != TR_PARA_UJ) && (newtype != type)) { + newtype = TR_PARA_UJ; + } + /* + printf("pp_align newtype:%d brects (LL,UR) dst:(%f,%f),(%f,%f) src:(%f,%f),(%f,%f)\n", + newtype, + (br_dst->xll), + (br_dst->yll), + (br_dst->xur), + (br_dst->yur), + (br_src->xll), + (br_src->yll), + (br_src->xur), + (br_src->yur)); + */ + return (newtype); } /** @@ -1511,42 +1620,41 @@ newtype, \param bri pointer to the BR_INFO structure. \returns NULL. */ -BR_INFO *brinfo_release(BR_INFO *bri){ - if(bri){ - free(bri->rects); - free(bri); /* release the overall brinfo structure */ - } - return NULL; +BR_INFO *brinfo_release(BR_INFO *bri) +{ + if (bri) { + free(bri->rects); + free(bri); /* release the overall brinfo structure */ + } + return NULL; } - - /** \brief Initialize an TR_INFO structure. Holds all data for text reassembly. \returns a pointer to the TR_INFO structure created, or NULL on error. */ -TR_INFO *trinfo_init(TR_INFO *tri){ - if(tri)return(tri); /* tri is already set, double initialization is not allowed */ - if(!(tri = (TR_INFO *)calloc(1,sizeof(TR_INFO))) || - !(tri->fti = ftinfo_init()) || - !(tri->tpi = tpinfo_init()) || - !(tri->bri = brinfo_init()) || - !(tri->cxi = cxinfo_init()) - ){ tri = trinfo_release(tri); } - tri->out = NULL; /* This will allocate as needed, it might not ever be needed. */ - tri->qe = 0.0; - tri->esc = 0.0; - tri->x = DBL_MAX; - tri->y = DBL_MAX; - tri->dirty = 0; - tri->use_kern = 1; - tri->load_flags = FT_LOAD_NO_SCALE; - tri->kern_mode = FT_KERNING_UNSCALED; - tri->outspace = 0; - tri->outused = 0; - tri->usebk = BKCLR_NONE; - memset(&(tri->bkcolor),0,sizeof(TRCOLORREF)); - return(tri); +TR_INFO *trinfo_init(TR_INFO *tri) +{ + if (tri) + return (tri); /* tri is already set, double initialization is not allowed */ + if (!(tri = (TR_INFO *)calloc(1, sizeof(TR_INFO))) || !(tri->fti = ftinfo_init()) || !(tri->tpi = tpinfo_init()) || + !(tri->bri = brinfo_init()) || !(tri->cxi = cxinfo_init())) { + tri = trinfo_release(tri); + } + tri->out = NULL; /* This will allocate as needed, it might not ever be needed. */ + tri->qe = 0.0; + tri->esc = 0.0; + tri->x = DBL_MAX; + tri->y = DBL_MAX; + tri->dirty = 0; + tri->use_kern = 1; + tri->load_flags = FT_LOAD_NO_SCALE; + tri->kern_mode = FT_KERNING_UNSCALED; + tri->outspace = 0; + tri->outused = 0; + tri->usebk = BKCLR_NONE; + memset(&(tri->bkcolor), 0, sizeof(TRCOLORREF)); + return (tri); } /** @@ -1557,20 +1665,28 @@ TR_INFO *trinfo_init(TR_INFO *tri){ \param tri pointer to the TR_INFO structure. \returns NULL. */ -TR_INFO *trinfo_release(TR_INFO *tri){ - if(tri){ - if(tri->bri)tri->bri=brinfo_release(tri->bri); - if(tri->tpi)tri->tpi=tpinfo_release(tri->tpi); - if(tri->fti)tri->fti=ftinfo_release(tri->fti); - if(tri->cxi)tri->cxi=cxinfo_release(tri->cxi); - if(tri->out){ free(tri->out); tri->out=NULL; }; - free(tri); - } - return(NULL); +TR_INFO *trinfo_release(TR_INFO *tri) +{ + if (tri) { + if (tri->bri) + tri->bri = brinfo_release(tri->bri); + if (tri->tpi) + tri->tpi = tpinfo_release(tri->tpi); + if (tri->fti) + tri->fti = ftinfo_release(tri->fti); + if (tri->cxi) + tri->cxi = cxinfo_release(tri->cxi); + if (tri->out) { + free(tri->out); + tri->out = NULL; + }; + free(tri); + } + return (NULL); } /** - \brief Release a TR_INFO structure mostly. + \brief Release a TR_INFO structure mostly. Release all associated memory EXCEPT Fontconfig. Fontconfig may still be needed elsewhere in a program and there is no way to figure that out here. See also trinfo_clear() and trinfo_release(). @@ -1578,16 +1694,24 @@ TR_INFO *trinfo_release(TR_INFO *tri){ \param tri pointer to the TR_INFO structure. \returns NULL. */ -TR_INFO *trinfo_release_except_FC(TR_INFO *tri){ - if(tri){ - if(tri->bri)tri->bri=brinfo_release(tri->bri); - if(tri->tpi)tri->tpi=tpinfo_release(tri->tpi); - if(tri->fti)tri->fti=ftinfo_clear(tri->fti); - if(tri->cxi)tri->cxi=cxinfo_release(tri->cxi); - if(tri->out){ free(tri->out); tri->out=NULL; }; - free(tri); - } - return(NULL); +TR_INFO *trinfo_release_except_FC(TR_INFO *tri) +{ + if (tri) { + if (tri->bri) + tri->bri = brinfo_release(tri->bri); + if (tri->tpi) + tri->tpi = tpinfo_release(tri->tpi); + if (tri->fti) + tri->fti = ftinfo_clear(tri->fti); + if (tri->cxi) + tri->cxi = cxinfo_release(tri->cxi); + if (tri->out) { + free(tri->out); + tri->out = NULL; + }; + free(tri); + } + return (NULL); } /** @@ -1599,34 +1723,35 @@ TR_INFO *trinfo_release_except_FC(TR_INFO *tri){ \param tri pointer to the TR_INFO structure. \returns NULL. */ -TR_INFO *trinfo_clear(TR_INFO *tri){ - if(tri){ - - if(tri->bri)tri->bri=brinfo_release(tri->bri); - if(tri->tpi)tri->tpi=tpinfo_release(tri->tpi); - if(tri->cxi)tri->cxi=cxinfo_release(tri->cxi); - if(tri->out){ - free(tri->out); - tri->out = NULL; - tri->outused = 0; - tri->outspace = 0; - }; - /* Do NOT modify: qe, use_kern, usebk, load_flags, kern_mode, or bkcolor. Set the rest back to their defaults */ - tri->esc = 0.0; - tri->x = DBL_MAX; - tri->y = DBL_MAX; - tri->dirty = 0; - if(!(tri->tpi = tpinfo_init()) || /* re-init the pieces just released */ - !(tri->bri = brinfo_init()) || - !(tri->cxi = cxinfo_init()) - ){ - tri = trinfo_release(tri); /* something horrible happened, clean out tri and return NULL */ - } - } - return(tri); +TR_INFO *trinfo_clear(TR_INFO *tri) +{ + if (tri) { + if (tri->bri) + tri->bri = brinfo_release(tri->bri); + if (tri->tpi) + tri->tpi = tpinfo_release(tri->tpi); + if (tri->cxi) + tri->cxi = cxinfo_release(tri->cxi); + if (tri->out) { + free(tri->out); + tri->out = NULL; + tri->outused = 0; + tri->outspace = 0; + }; + /* Do NOT modify: qe, use_kern, usebk, load_flags, kern_mode, or bkcolor. Set the rest back to their defaults + */ + tri->esc = 0.0; + tri->x = DBL_MAX; + tri->y = DBL_MAX; + tri->dirty = 0; + if (!(tri->tpi = tpinfo_init()) || /* re-init the pieces just released */ + !(tri->bri = brinfo_init()) || !(tri->cxi = cxinfo_init())) { + tri = trinfo_release(tri); /* something horrible happened, clean out tri and return NULL */ + } + } + return (tri); } - /** \brief Set the quantization error value for a TR_INFO structure. If coordinates have passed through an integer form limits @@ -1639,11 +1764,14 @@ TR_INFO *trinfo_clear(TR_INFO *tri){ \param tri pointer to TR_INFO structure \param qe quantization error. */ -int trinfo_load_qe(TR_INFO *tri, double qe){ - if(!tri)return(1); - if(qe<0.0)return(2); - tri->qe=qe; - return(0); +int trinfo_load_qe(TR_INFO *tri, double qe) +{ + if (!tri) + return (1); + if (qe < 0.0) + return (2); + tri->qe = qe; + return (0); } /** @@ -1655,18 +1783,21 @@ int trinfo_load_qe(TR_INFO *tri, double qe){ \param usebk 0 for no background, anything else uses background color \param bkcolor background color to use */ -int trinfo_load_bk(TR_INFO *tri, int usebk, TRCOLORREF bkcolor){ - int status=0; - if(!tri){ status = 1; } - else { - if((usebk < BKCLR_NONE) || (usebk > BKCLR_ALL)){ status = 2; } - else { - status = trinfo_check_bk(tri, usebk, bkcolor); - tri->usebk = usebk; - tri->bkcolor = bkcolor; - } - } - return(status); +int trinfo_load_bk(TR_INFO *tri, int usebk, TRCOLORREF bkcolor) +{ + int status = 0; + if (!tri) { + status = 1; + } else { + if ((usebk < BKCLR_NONE) || (usebk > BKCLR_ALL)) { + status = 2; + } else { + status = trinfo_check_bk(tri, usebk, bkcolor); + tri->usebk = usebk; + tri->bkcolor = bkcolor; + } + } + return (status); } /** @@ -1676,10 +1807,13 @@ int trinfo_load_bk(TR_INFO *tri, int usebk, TRCOLORREF bkcolor){ \param usebk 0 for no background, anything else uses background color \param bkcolor background color to use */ -int trinfo_check_bk(TR_INFO *tri, int usebk, TRCOLORREF bkcolor){ - int status = 0; - if( (tri->usebk != usebk) || memcmp(&tri->bkcolor,&bkcolor,sizeof(TRCOLORREF))){ status = -1; } - return(status); +int trinfo_check_bk(TR_INFO *tri, int usebk, TRCOLORREF bkcolor) +{ + int status = 0; + if ((tri->usebk != usebk) || memcmp(&tri->bkcolor, &bkcolor, sizeof(TRCOLORREF))) { + status = -1; + } + return (status); } /** @@ -1690,15 +1824,17 @@ int trinfo_check_bk(TR_INFO *tri, int usebk, TRCOLORREF bkcolor){ \param load_flags Controls internal advance: FT_LOAD_NO_SCALE, internal advance is in 1/64th of a point. (kerning values are still scaled) FT_LOAD_TARGET_NORMAL internal advance is in 1/64th of a point. The scale - factor seems to be (Font Size in points)*(DPI)/(32.0 pnts)*(72 dpi). + factor seems to be (Font Size in points)*(DPI)/(32.0 pnts)*(72 dpi). \param kern_mode FT_KERNING_DEFAULT, FT_KERNING_UNFITTED, or FT_KERNING_UNSCALED. Set to match calling application. */ -int trinfo_load_ft_opts(TR_INFO *tri, int use_kern, int load_flags, int kern_mode){ - if(!tri)return(1); - tri->use_kern = use_kern; - tri->load_flags = load_flags; - tri->kern_mode = kern_mode; - return(0); +int trinfo_load_ft_opts(TR_INFO *tri, int use_kern, int load_flags, int kern_mode) +{ + if (!tri) + return (1); + tri->use_kern = use_kern; + tri->load_flags = load_flags; + tri->kern_mode = kern_mode; + return (0); } /** @@ -1707,23 +1843,27 @@ int trinfo_load_ft_opts(TR_INFO *tri, int use_kern, int load_flags, int kern_mod \param tri pointer to a TR_INFO structure \param src Pointer to a text string. */ -int trinfo_append_out(TR_INFO *tri, const char *src){ - size_t slen; - uint8_t *tmp; - if(!src)return(-1); - slen = strlen(src); - if(tri->outused + (int) slen + 1 >= tri->outspace){ - tri->outspace += TEREMAX(ALLOCOUT_CHUNK,slen+1); - tmp = realloc(tri->out, tri->outspace * sizeof(uint8_t) ); - if(tmp){ tri->out = tmp; } - else { return(-1); } - } - memcpy(tri->out + tri->outused, src, slen+1); /* copy the terminator */ - tri->outused += slen; /* do not count the terminator in the length */ - return(0); +int trinfo_append_out(TR_INFO *tri, const char *src) +{ + size_t slen; + uint8_t *tmp; + if (!src) + return (-1); + slen = strlen(src); + if (tri->outused + (int)slen + 1 >= tri->outspace) { + tri->outspace += TEREMAX(ALLOCOUT_CHUNK, slen + 1); + tmp = realloc(tri->out, tri->outspace * sizeof(uint8_t)); + if (tmp) { + tri->out = tmp; + } else { + return (-1); + } + } + memcpy(tri->out + tri->outused, src, slen + 1); /* copy the terminator */ + tri->outused += slen; /* do not count the terminator in the length */ + return (0); } - /** \brief Load a text object into a TR_INFO struct. \returns 0 on success, !0 on error. -1 means that the escapement is different from the objects already loaded. @@ -1733,173 +1873,196 @@ int trinfo_append_out(TR_INFO *tri, const char *src){ \param flags special processing flags: TR_EMFBOT calculate Y coordinates of ALIBOT object compatible with EMF files TA_BOTTOM alignment. */ -int trinfo_load_textrec(TR_INFO *tri, const TCHUNK_SPECS *tsp, double escapement, int flags){ - - int status; - double x,y,xe; - double asc,dsc; /* these are the ascender/descender for the actual text */ - int ymin,ymax; - double fasc,fdsc; /* these are the ascender/descender for the font as a whole (text independent) */ - TP_INFO *tpi; - FT_INFO *fti; - BR_INFO *bri; - int current,idx,taln; - uint32_t prev; - uint32_t *text32,*tptr; - FNT_SPECS *fsp; - BRECT_SPECS bsp; - - /* check incoming parameters */ - if(!tri)return(1); - if(!tsp)return(2); - if(!tsp->string)return(3); - fti = tri->fti; - tpi = tri->tpi; - bri = tri->bri; - idx = tsp->fi_idx; - taln = tsp->taln; - if(!fti->used)return(4); - if(idx <0 || idx >= (int) fti->used)return(5); - fsp = &(fti->fonts[idx]); - - if(!tri->dirty){ - tri->x = tsp->x; - tri->y = tsp->y; - tri->esc = escapement; - tri->dirty = 1; - } - else { - if(tri->esc != escapement)return(-1); - } - - - tpinfo_insert(tpi,tsp); - current=tpi->used-1; - ymin = 64000; - ymax = -64000; - - /* The geometry model has origin Y at the top of screen, positive Y is down, maximum positive - Y is at the bottom of the screen. That makes "top" (by positive Y) actually the bottom - (as viewed on the screen.) */ - - escapement *= 2.0 * M_PI / 360.0; /* degrees to radians */ - x = tpi->chunks[current].x - tri->x; /* convert to internal orientation */ - y = tpi->chunks[current].y - tri->y; - tpi->chunks[current].x = x * cos(escapement) - y * sin(escapement); /* coordinate transformation */ - tpi->chunks[current].y = x * sin(escapement) + y * cos(escapement); - -/* Careful! face bbox does NOT scale with FT_Set_Char_Size -printf("Face idx:%d bbox: xMax/Min:%ld,%ld yMax/Min:%ld,%ld UpEM:%d asc/des:%d,%d height:%d size:%f\n", - idx, - fsp->face->bbox.xMax,fsp->face->bbox.xMin, - fsp->face->bbox.yMax,fsp->face->bbox.yMin, - fsp->face->units_per_EM,fsp->face->ascender,fsp->face->descender,fsp->face->height,fsp->fsize); -*/ - - text32 = U_Utf8ToUtf32le((char *) tsp->string,0,NULL); - if(!text32){ // LATIN1 encoded >128 are generally not valid UTF, so the first will fail - text32 = U_Latin1ToUtf32le((char *) tsp->string,0,NULL); - if(!text32)return(5); - } - /* baseline advance is independent of character orientation */ - for(xe=0.0, prev=0, tptr=text32; *tptr; tptr++){ - status = TR_getadvance(fti, fsp, *tptr, (tri->use_kern ? prev: 0), tri->load_flags, tri->kern_mode, &ymin, &ymax); - if(status>=0){ - xe += ((double) status)/64.0; - } - else { return(6); } - prev=*tptr; - } - - /* Some glyphs in fonts have no vertical extent, for instance, Hebrew glyphs in Century Schoolbook L. - Use the 3/4 of the font size as a (very bad) approximation for the actual values. */ - if(ymin==0 && ymax==0){ - ymax = 0.75 * fsp->fsize * 64.0; - } - - asc = ((double) (ymax))/64.0; - dsc = ((double) (ymin))/64.0; /* This is negative */ -/* This did not work very well because the ascender/descender went well beyond the actual characters, causing - overlaps on lines that did not actually overlap (vertically). - asc = ((double) (fsp->face->ascender) )/64.0; - dsc = ((double) (fsp->face->descender))/64.0; -*/ - - free(text32); - - /* find the font ascender descender (general one, not specific for current text) */ - fasc = ((double) (fsp->face->ascender) )/64.0; - fdsc = ((double) (fsp->face->descender))/64.0; - - /* originally the denominator was just 32.0, but it broke when units_per_EM wasn't 2048 */ - double fixscale = tsp->fs/(((double) fsp->face->units_per_EM)/64.0); - if(tri->load_flags & FT_LOAD_NO_SCALE) xe *= fixscale; - - /* now place the rectangle using ALN information */ - if( taln & ALIHORI & ALILEFT ){ - bsp.xll = tpi->chunks[current].x; - bsp.xur = tpi->chunks[current].x + xe; - } - else if( taln & ALIHORI & ALICENTER){ - bsp.xll = tpi->chunks[current].x - xe/2.0; - bsp.xur = tpi->chunks[current].x + xe/2.0; - } - else{ /* taln & ALIHORI & ALIRIGHT */ - bsp.xll = tpi->chunks[current].x - xe; - bsp.xur = tpi->chunks[current].x; - } - tpi->chunks[current].ldir = tsp->ldir; - - if(tri->load_flags & FT_LOAD_NO_SCALE){ - asc *= fixscale; - dsc *= fixscale; - fasc *= fixscale; - fdsc *= fixscale; - } - - - /* From this point forward y is on the baseline, so need to correct it in chunks. The asc/dsc are the general - ones for the font, else the text content will muck around with the baseline in BAD ways. */ - if( taln & ALIVERT & ALITOP ){ tpi->chunks[current].y += fasc; } - else if( taln & ALIVERT & ALIBASE){ } /* no correction required */ - else{ /* taln & ALIVERT & ALIBOT */ - if(flags & TR_EMFBOT){ tpi->chunks[current].y -= 0.35 * tsp->fs; } /* compatible with EMF implementations */ - else { tpi->chunks[current].y += fdsc; } - } - tpi->chunks[current].boff = -dsc; - - /* since y is always on the baseline, the lower left and upper right are easy. These use asc/dsc for the particular text, - so that the bounding box will fit it tightly. */ - bsp.yll = tpi->chunks[current].y - dsc; - bsp.yur = tpi->chunks[current].y - asc; - brinfo_insert(bri,&bsp); - tpi->chunks[current].rt_tidx = bri->used - 1; /* index of rectangle that contains it */ - - return(0); +int trinfo_load_textrec(TR_INFO *tri, const TCHUNK_SPECS *tsp, double escapement, int flags) +{ + int status; + double x, y, xe; + double asc, dsc; /* these are the ascender/descender for the actual text */ + int ymin, ymax; + double fasc, fdsc; /* these are the ascender/descender for the font as a whole (text independent) */ + TP_INFO *tpi; + FT_INFO *fti; + BR_INFO *bri; + int current, idx, taln; + uint32_t prev; + uint32_t *text32, *tptr; + FNT_SPECS *fsp; + BRECT_SPECS bsp; + + /* check incoming parameters */ + if (!tri) + return (1); + if (!tsp) + return (2); + if (!tsp->string) + return (3); + fti = tri->fti; + tpi = tri->tpi; + bri = tri->bri; + idx = tsp->fi_idx; + taln = tsp->taln; + if (!fti->used) + return (4); + if (idx < 0 || idx >= (int)fti->used) + return (5); + fsp = &(fti->fonts[idx]); + + if (!tri->dirty) { + tri->x = tsp->x; + tri->y = tsp->y; + tri->esc = escapement; + tri->dirty = 1; + } else { + if (tri->esc != escapement) + return (-1); + } + + tpinfo_insert(tpi, tsp); + current = tpi->used - 1; + ymin = 64000; + ymax = -64000; + + /* The geometry model has origin Y at the top of screen, positive Y is down, maximum positive + Y is at the bottom of the screen. That makes "top" (by positive Y) actually the bottom + (as viewed on the screen.) */ + + escapement *= 2.0 * M_PI / 360.0; /* degrees to radians */ + x = tpi->chunks[current].x - tri->x; /* convert to internal orientation */ + y = tpi->chunks[current].y - tri->y; + tpi->chunks[current].x = x * cos(escapement) - y * sin(escapement); /* coordinate transformation */ + tpi->chunks[current].y = x * sin(escapement) + y * cos(escapement); + + /* Careful! face bbox does NOT scale with FT_Set_Char_Size + printf("Face idx:%d bbox: xMax/Min:%ld,%ld yMax/Min:%ld,%ld UpEM:%d asc/des:%d,%d height:%d size:%f\n", + idx, + fsp->face->bbox.xMax,fsp->face->bbox.xMin, + fsp->face->bbox.yMax,fsp->face->bbox.yMin, + fsp->face->units_per_EM,fsp->face->ascender,fsp->face->descender,fsp->face->height,fsp->fsize); + */ + + text32 = U_Utf8ToUtf32le((char *)tsp->string, 0, NULL); + if (!text32) { // LATIN1 encoded >128 are generally not valid UTF, so the first will fail + text32 = U_Latin1ToUtf32le((char *)tsp->string, 0, NULL); + if (!text32) + return (5); + } + /* baseline advance is independent of character orientation */ + for (xe = 0.0, prev = 0, tptr = text32; *tptr; tptr++) { + status = + TR_getadvance(fti, fsp, *tptr, (tri->use_kern ? prev : 0), tri->load_flags, tri->kern_mode, &ymin, &ymax); + if (status >= 0) { + xe += ((double)status) / 64.0; + } else { + return (6); + } + prev = *tptr; + } + + /* Some glyphs in fonts have no vertical extent, for instance, Hebrew glyphs in Century Schoolbook L. + Use the 3/4 of the font size as a (very bad) approximation for the actual values. */ + if (ymin == 0 && ymax == 0) { + ymax = 0.75 * fsp->fsize * 64.0; + } + + asc = ((double)(ymax)) / 64.0; + dsc = ((double)(ymin)) / 64.0; /* This is negative */ + /* This did not work very well because the ascender/descender went well beyond the actual characters, causing + overlaps on lines that did not actually overlap (vertically). + asc = ((double) (fsp->face->ascender) )/64.0; + dsc = ((double) (fsp->face->descender))/64.0; + */ + + free(text32); + + /* find the font ascender descender (general one, not specific for current text) */ + fasc = ((double)(fsp->face->ascender)) / 64.0; + fdsc = ((double)(fsp->face->descender)) / 64.0; + + /* originally the denominator was just 32.0, but it broke when units_per_EM wasn't 2048 */ + double fixscale = tsp->fs / (((double)fsp->face->units_per_EM) / 64.0); + if (tri->load_flags & FT_LOAD_NO_SCALE) + xe *= fixscale; + + /* now place the rectangle using ALN information */ + if (taln & ALIHORI & ALILEFT) { + bsp.xll = tpi->chunks[current].x; + bsp.xur = tpi->chunks[current].x + xe; + } else if (taln & ALIHORI & ALICENTER) { + bsp.xll = tpi->chunks[current].x - xe / 2.0; + bsp.xur = tpi->chunks[current].x + xe / 2.0; + } else { /* taln & ALIHORI & ALIRIGHT */ + bsp.xll = tpi->chunks[current].x - xe; + bsp.xur = tpi->chunks[current].x; + } + tpi->chunks[current].ldir = tsp->ldir; + + if (tri->load_flags & FT_LOAD_NO_SCALE) { + asc *= fixscale; + dsc *= fixscale; + fasc *= fixscale; + fdsc *= fixscale; + } + + /* From this point forward y is on the baseline, so need to correct it in chunks. The asc/dsc are the general + ones for the font, else the text content will muck around with the baseline in BAD ways. */ + if (taln & ALIVERT & ALITOP) { + tpi->chunks[current].y += fasc; + } else if (taln & ALIVERT & ALIBASE) { + } /* no correction required */ + else { /* taln & ALIVERT & ALIBOT */ + if (flags & TR_EMFBOT) { + tpi->chunks[current].y -= 0.35 * tsp->fs; + } /* compatible with EMF implementations */ + else { + tpi->chunks[current].y += fdsc; + } + } + tpi->chunks[current].boff = -dsc; + + /* since y is always on the baseline, the lower left and upper right are easy. These use asc/dsc for the particular + text, so that the bounding box will fit it tightly. */ + bsp.yll = tpi->chunks[current].y - dsc; + bsp.yur = tpi->chunks[current].y - asc; + brinfo_insert(bri, &bsp); + tpi->chunks[current].rt_tidx = bri->used - 1; /* index of rectangle that contains it */ + + return (0); } /** \brief Fontweight conversion. Fontconfig units to SVG units. - Anything not recognized becomes "normal" == 400. + Anything not recognized becomes "normal" == 400. There is no interpolation because a value that mapped to 775, for instance, most likely would not display properly because it is intermediate between 700 and 800, and only those need be supported in SVG viewers. \returns SVG font weight \param weight Fontconfig font weight. */ -int TR_weight_FC_to_SVG(int weight){ - int ret=400; - if( weight == 0){ ret = 100; } - else if(weight == 40){ ret = 200; } - else if(weight == 50){ ret = 300; } - else if(weight == 80){ ret = 400; } - else if(weight == 100){ ret = 500; } - else if(weight == 180){ ret = 600; } - else if(weight == 200){ ret = 700; } - else if(weight == 205){ ret = 800; } - else if(weight == 210){ ret = 900; } - else { ret = 400; } - return(ret); +int TR_weight_FC_to_SVG(int weight) +{ + int ret = 400; + if (weight == 0) { + ret = 100; + } else if (weight == 40) { + ret = 200; + } else if (weight == 50) { + ret = 300; + } else if (weight == 80) { + ret = 400; + } else if (weight == 100) { + ret = 500; + } else if (weight == 180) { + ret = 600; + } else if (weight == 200) { + ret = 700; + } else if (weight == 205) { + ret = 800; + } else if (weight == 210) { + ret = 900; + } else { + ret = 400; + } + return (ret); } /** @@ -1911,351 +2074,430 @@ int TR_weight_FC_to_SVG(int weight){ \param left padding for the left of a bounding rectangle. \param right padding for the right of a bounding rectangle. */ -void TR_rt_pad_set(RT_PAD *rt_pad, double up, double down, double left, double right){ - rt_pad->up = up; - rt_pad->down = down; - rt_pad->left = left; - rt_pad->right = right; -} +void TR_rt_pad_set(RT_PAD *rt_pad, double up, double down, double left, double right) +{ + rt_pad->up = up; + rt_pad->down = down; + rt_pad->left = left; + rt_pad->right = right; +} /** \brief Convert from analyzed complexes to SVG format. \returns void \param tri pointer to a TR_INFO struct which will be analyzed. Result is stored in its "out" buffer. */ -void TR_layout_2_svg(TR_INFO *tri){ - double x = tri->x; - double y = tri->y; - double dx,dy; - double esc; - double recenter; /* horizontal offset to set things up correctly for CJ and RJ text, is 0 for LJ*/ - double lineheight=1.25; - int cutat; - FT_INFO *fti=tri->fti; /* Font info storage */ - TP_INFO *tpi=tri->tpi; /* Text Info/Position Info storage */ - BR_INFO *bri=tri->bri; /* bounding Rectangle Info storage */ - CX_INFO *cxi=tri->cxi; /* Complexes deduced for this text */ - TCHUNK_SPECS *tsp; /* current text object */ - CX_SPECS *csp; - CX_SPECS *cline_sp; - unsigned int i,j,k,jdx,kdx; - int ldir; - char obuf[1024]; /* big enough for style and so forth */ - char cbuf[16]; /* big enough for one hex color */ - - char stransform[128]; - double newx,newy,tmpx; - uint32_t utmp; - - /* copy the current numeric locale, make a copy because setlocale may stomp on - the memory it points to. Then change it because SVG needs decimal points, - not commas, in floats. Restore on exit from this routine. - */ - char *prev_locale = setlocale(LC_NUMERIC,NULL); - char *hold_locale = malloc(sizeof(char) * (strlen(prev_locale) + 1)); - strcpy(hold_locale,prev_locale); - (void) setlocale(LC_NUMERIC,"POSIX"); - -/* -#define DBG_TR_PARA 0 -#define DBG_TR_INPUT 1 -*/ +void TR_layout_2_svg(TR_INFO *tri) +{ + double x = tri->x; + double y = tri->y; + double dx, dy; + double esc; + double recenter; /* horizontal offset to set things up correctly for CJ and RJ text, is 0 for LJ*/ + double lineheight = 1.25; + int cutat; + FT_INFO *fti = tri->fti; /* Font info storage */ + TP_INFO *tpi = tri->tpi; /* Text Info/Position Info storage */ + BR_INFO *bri = tri->bri; /* bounding Rectangle Info storage */ + CX_INFO *cxi = tri->cxi; /* Complexes deduced for this text */ + TCHUNK_SPECS *tsp; /* current text object */ + CX_SPECS *csp; + CX_SPECS *cline_sp; + unsigned int i, j, k, jdx, kdx; + int ldir; + char obuf[1024]; /* big enough for style and so forth */ + char cbuf[16]; /* big enough for one hex color */ + + char stransform[128]; + double newx, newy, tmpx; + uint32_t utmp; + + /* copy the current numeric locale, make a copy because setlocale may stomp on + the memory it points to. Then change it because SVG needs decimal points, + not commas, in floats. Restore on exit from this routine. + */ + char *prev_locale = setlocale(LC_NUMERIC, NULL); + char *hold_locale = malloc(sizeof(char) * (strlen(prev_locale) + 1)); + strcpy(hold_locale, prev_locale); + (void)setlocale(LC_NUMERIC, "POSIX"); + + /* + #define DBG_TR_PARA 0 + #define DBG_TR_INPUT 1 + */ /* The debug section below is difficult to see if usebk is anything other than BKCLR_NONE */ -#if DBG_TR_PARA || DBG_TR_INPUT /* enable debugging code, writes extra information into SVG */ +#if DBG_TR_PARA || DBG_TR_INPUT /* enable debugging code, writes extra information into SVG */ /* put rectangles down for each text string - debugging!!! This will not work properly for any Narrow fonts */ - esc = tri->esc; - esc *= 2.0 * M_PI / 360.0; /* degrees to radians and change direction of rotation */ - sprintf(stransform,"transform=\"matrix(%f,%f,%f,%f,%f,%f)\"\n",cos(esc),-sin(esc),sin(esc),cos(esc), 1.25*x,1.25*y); - for(i=cxi->phase1; iused;i++){ /* over all complex members from phase2 == TR_PARA_* complexes */ - csp = &(cxi->cx[i]); - for(j=0; jkids.used; j++){ /* over all members of these complexes, which are phase1 complexes */ - jdx = csp->kids.members[j]; /* index of phase1 complex (all are TR_TEXT or TR_LINE) */ - for(k=0; kcx[jdx].kids.used; k++){ /* over all members of the phase1 complex */ - kdx = cxi->cx[jdx].kids.members[k]; /* index for text objects in tpi */ - tsp = &tpi->chunks[kdx]; - ldir = tsp->ldir; - if(!j && !k){ + esc = tri->esc; + esc *= 2.0 * M_PI / 360.0; /* degrees to radians and change direction of rotation */ + sprintf(stransform, "transform=\"matrix(%f,%f,%f,%f,%f,%f)\"\n", cos(esc), -sin(esc), sin(esc), cos(esc), 1.25 * x, + 1.25 * y); + for (i = cxi->phase1; i < cxi->used; i++) { /* over all complex members from phase2 == TR_PARA_* complexes */ + csp = &(cxi->cx[i]); + for (j = 0; j < csp->kids.used; j++) { /* over all members of these complexes, which are phase1 complexes */ + jdx = csp->kids.members[j]; /* index of phase1 complex (all are TR_TEXT or TR_LINE) */ + for (k = 0; k < cxi->cx[jdx].kids.used; k++) { /* over all members of the phase1 complex */ + kdx = cxi->cx[jdx].kids.members[k]; /* index for text objects in tpi */ + tsp = &tpi->chunks[kdx]; + ldir = tsp->ldir; + if (!j && !k) { #if DBG_TR_PARA - TRPRINT(tri, "rects[csp->rt_cidx].xur - bri->rects[csp->rt_cidx].xll)); - TRPRINT(tri, obuf); - sprintf(obuf,"height=\"%f\"\n",1.25*(bri->rects[csp->rt_cidx].yll - bri->rects[csp->rt_cidx].yur)); - TRPRINT(tri, obuf); - sprintf(obuf,"x=\"%f\" y=\"%f\"\n",1.25*(bri->rects[csp->rt_cidx].xll),1.25*(bri->rects[csp->rt_cidx].yur)); - TRPRINT(tri, obuf); - TRPRINT(tri, stransform); - TRPRINT(tri, "/>\n"); -#endif /* DBG_TR_PARA */ - } -#if DBG_TR_INPUT /* debugging code, this section writes the original text objects */ - newx = 1.25*(ldir == LDIR_RL ? bri->rects[tsp->rt_tidx].xur : bri->rects[tsp->rt_tidx].xll); - newy = 1.25*(bri->rects[tsp->rt_tidx].yur); - TRPRINT(tri, "rects[tsp->rt_tidx].xur - bri->rects[tsp->rt_tidx].xll)); - TRPRINT(tri, obuf); - sprintf(obuf,"height=\"%f\"\n",1.25*(bri->rects[tsp->rt_tidx].yll - bri->rects[tsp->rt_tidx].yur)); - TRPRINT(tri, obuf); - sprintf(obuf,"x=\"%f\" y=\"%f\"\n",1.25*(bri->rects[tsp->rt_tidx].xll),newy); - TRPRINT(tri, obuf); - TRPRINT(tri, stransform); - TRPRINT(tri, "/>\n"); - - newy = 1.25*(bri->rects[tsp->rt_tidx].yll - tsp->boff); - sprintf(obuf,"fs*1.25); /*IMPORTANT, if the FS is given in pt it looks like crap in browsers. As if px != 1.25 pt, maybe 96 dpi not 90?*/ - TRPRINT(tri, obuf); - sprintf(obuf,"font-style:%s;",(tsp->italics ? "italic" : "normal")); - TRPRINT(tri, obuf); - TRPRINT(tri, "font-variant:normal;"); - sprintf(obuf,"font-weight:%d;",TR_weight_FC_to_SVG(tsp->weight)); - TRPRINT(tri, obuf); - sprintf(obuf,"font-stretch:%s;",(tsp->condensed==100 ? "Normal" : "Condensed")); - TRPRINT(tri, obuf); - sprintf(obuf,"text-anchor:%s;",(tsp->ldir == LDIR_RL ? "end" : "start")); - TRPRINT(tri, obuf); - cutat=strcspn((char *)fti->fonts[tsp->fi_idx].fontspec,":"); - sprintf(obuf,"font-family:%.*s;",cutat,fti->fonts[tsp->fi_idx].fontspec); - TRPRINT(tri, obuf); - sprintf(obuf,"\n\">%s\n",&tsp->string[tsp->spaces]); - TRPRINT(tri, obuf); + TRPRINT(tri, "rects[csp->rt_cidx].xur - bri->rects[csp->rt_cidx].xll)); + TRPRINT(tri, obuf); + sprintf(obuf, "height=\"%f\"\n", + 1.25 * (bri->rects[csp->rt_cidx].yll - bri->rects[csp->rt_cidx].yur)); + TRPRINT(tri, obuf); + sprintf(obuf, "x=\"%f\" y=\"%f\"\n", 1.25 * (bri->rects[csp->rt_cidx].xll), + 1.25 * (bri->rects[csp->rt_cidx].yur)); + TRPRINT(tri, obuf); + TRPRINT(tri, stransform); + TRPRINT(tri, "/>\n"); +#endif /* DBG_TR_PARA */ + } +#if DBG_TR_INPUT /* debugging code, this section writes the original text objects */ + newx = 1.25 * (ldir == LDIR_RL ? bri->rects[tsp->rt_tidx].xur : bri->rects[tsp->rt_tidx].xll); + newy = 1.25 * (bri->rects[tsp->rt_tidx].yur); + TRPRINT(tri, "rects[tsp->rt_tidx].xur - bri->rects[tsp->rt_tidx].xll)); + TRPRINT(tri, obuf); + sprintf(obuf, "height=\"%f\"\n", 1.25 * (bri->rects[tsp->rt_tidx].yll - bri->rects[tsp->rt_tidx].yur)); + TRPRINT(tri, obuf); + sprintf(obuf, "x=\"%f\" y=\"%f\"\n", 1.25 * (bri->rects[tsp->rt_tidx].xll), newy); + TRPRINT(tri, obuf); + TRPRINT(tri, stransform); + TRPRINT(tri, "/>\n"); + + newy = 1.25 * (bri->rects[tsp->rt_tidx].yll - tsp->boff); + sprintf(obuf, "fs * 1.25); /*IMPORTANT, if the FS is given in pt it looks like crap in browsers. As if px + != 1.25 pt, maybe 96 dpi not 90?*/ + TRPRINT(tri, obuf); + sprintf(obuf, "font-style:%s;", (tsp->italics ? "italic" : "normal")); + TRPRINT(tri, obuf); + TRPRINT(tri, "font-variant:normal;"); + sprintf(obuf, "font-weight:%d;", TR_weight_FC_to_SVG(tsp->weight)); + TRPRINT(tri, obuf); + sprintf(obuf, "font-stretch:%s;", (tsp->condensed == 100 ? "Normal" : "Condensed")); + TRPRINT(tri, obuf); + sprintf(obuf, "text-anchor:%s;", (tsp->ldir == LDIR_RL ? "end" : "start")); + TRPRINT(tri, obuf); + cutat = strcspn((char *)fti->fonts[tsp->fi_idx].fontspec, ":"); + sprintf(obuf, "font-family:%.*s;", cutat, fti->fonts[tsp->fi_idx].fontspec); + TRPRINT(tri, obuf); + sprintf(obuf, "\n\">%s\n", &tsp->string[tsp->spaces]); + TRPRINT(tri, obuf); #endif /* DBG_TR_INPUT debugging code, original text objects */ - } - } - } + } + } + } #endif /* DBG_TR_PARA and/or DBG_TR_INPUT */ - - if(tri->usebk){ - esc = tri->esc; - esc *= 2.0 * M_PI / 360.0; /* degrees to radians and change direction of rotation */ - sprintf(stransform,"transform=\"matrix(%f,%f,%f,%f,%f,%f)\"\n",cos(esc),-sin(esc),sin(esc),cos(esc), 1.25*x,1.25*y); - - for(i=cxi->phase1; iused;i++){ /* over all complex members from phase2 == TR_PARA_* complexes */ - TRPRINT(tri, "\n"); /* group backgrounds for each object in the SVG */ - csp = &(cxi->cx[i]); - for(j=0; jkids.used; j++){ /* over all members of these complexes, which are phase1 complexes */ - jdx = csp->kids.members[j]; /* index of phase1 complex (all are TR_TEXT or TR_LINE) */ - cline_sp = &(cxi->cx[jdx]); - if(tri->usebk == BKCLR_LINE){ - TRPRINT(tri, "bkcolor.Red,tri->bkcolor.Green,tri->bkcolor.Blue); - TRPRINT(tri, obuf); - sprintf(obuf,"width=\"%f\"\n", 1.25*(bri->rects[cline_sp->rt_cidx].xur - bri->rects[cline_sp->rt_cidx].xll)); - TRPRINT(tri, obuf); - sprintf(obuf,"height=\"%f\"\n",1.25*(bri->rects[cline_sp->rt_cidx].yll - bri->rects[cline_sp->rt_cidx].yur)); - TRPRINT(tri, obuf); - sprintf(obuf,"x=\"%f\" y=\"%f\"\n",1.25*(bri->rects[cline_sp->rt_cidx].xll),1.25*(bri->rects[cline_sp->rt_cidx].yur)); - TRPRINT(tri, obuf); - TRPRINT(tri, stransform); - TRPRINT(tri, "/>\n"); - } - - for(k=0; kcx[jdx].kids.used; k++){ /* over all members of the phase1 complex */ - kdx = cxi->cx[jdx].kids.members[k]; /* index for text objects in tpi */ - tsp = &tpi->chunks[kdx]; - ldir = tsp->ldir; - if(!j && !k){ - if(tri->usebk == BKCLR_ALL){ + if (tri->usebk) { + esc = tri->esc; + esc *= 2.0 * M_PI / 360.0; /* degrees to radians and change direction of rotation */ + sprintf(stransform, "transform=\"matrix(%f,%f,%f,%f,%f,%f)\"\n", cos(esc), -sin(esc), sin(esc), cos(esc), + 1.25 * x, 1.25 * y); + + for (i = cxi->phase1; i < cxi->used; i++) { /* over all complex members from phase2 == TR_PARA_* complexes */ + TRPRINT(tri, "\n"); /* group backgrounds for each object in the SVG */ + csp = &(cxi->cx[i]); + for (j = 0; j < csp->kids.used; + j++) { /* over all members of these complexes, which are phase1 complexes */ + jdx = csp->kids.members[j]; /* index of phase1 complex (all are TR_TEXT or TR_LINE) */ + cline_sp = &(cxi->cx[jdx]); + if (tri->usebk == BKCLR_LINE) { TRPRINT(tri, "bkcolor.Red,tri->bkcolor.Green,tri->bkcolor.Blue); - TRPRINT(tri, obuf); - sprintf(obuf,"width=\"%f\"\n", 1.25*(bri->rects[csp->rt_cidx].xur - bri->rects[csp->rt_cidx].xll)); - TRPRINT(tri, obuf); - sprintf(obuf,"height=\"%f\"\n",1.25*(bri->rects[csp->rt_cidx].yll - bri->rects[csp->rt_cidx].yur)); - TRPRINT(tri, obuf); - sprintf(obuf,"x=\"%f\" y=\"%f\"\n",1.25*(bri->rects[csp->rt_cidx].xll),1.25*(bri->rects[csp->rt_cidx].yur)); - TRPRINT(tri, obuf); - TRPRINT(tri, stransform); - TRPRINT(tri, "/>\n"); - } - } - if(tri->usebk == BKCLR_FRAG){ - newx = 1.25*(ldir == LDIR_RL ? bri->rects[tsp->rt_tidx].xur : bri->rects[tsp->rt_tidx].xll); - newy = 1.25*(bri->rects[tsp->rt_tidx].yur); - TRPRINT(tri, "bkcolor.Red,tri->bkcolor.Green,tri->bkcolor.Blue); - TRPRINT(tri, obuf); - sprintf(obuf,"width=\"%f\"\n", 1.25*(bri->rects[tsp->rt_tidx].xur - bri->rects[tsp->rt_tidx].xll)); - TRPRINT(tri, obuf); - sprintf(obuf,"height=\"%f\"\n",1.25*(bri->rects[tsp->rt_tidx].yll - bri->rects[tsp->rt_tidx].yur)); - TRPRINT(tri, obuf); - sprintf(obuf,"x=\"%f\" y=\"%f\"\n",newx,newy); - TRPRINT(tri, obuf); - TRPRINT(tri, stransform); - TRPRINT(tri, "/>\n"); - } + sprintf(obuf, + "style=\"color-interpolation:sRGB;color-interpolation-filters:linearRGB;fill:#%2.2X%2.2X%2." + "2X;;stroke:none;;stroke-dasharray:none;marker:none;visibility:visible;display:inline;" + "overflow:visible;enable-background:accumulate;clip-rule:nonzero\"\n", + tri->bkcolor.Red, tri->bkcolor.Green, tri->bkcolor.Blue); + TRPRINT(tri, obuf); + sprintf(obuf, "width=\"%f\"\n", + 1.25 * (bri->rects[cline_sp->rt_cidx].xur - bri->rects[cline_sp->rt_cidx].xll)); + TRPRINT(tri, obuf); + sprintf(obuf, "height=\"%f\"\n", + 1.25 * (bri->rects[cline_sp->rt_cidx].yll - bri->rects[cline_sp->rt_cidx].yur)); + TRPRINT(tri, obuf); + sprintf(obuf, "x=\"%f\" y=\"%f\"\n", 1.25 * (bri->rects[cline_sp->rt_cidx].xll), + 1.25 * (bri->rects[cline_sp->rt_cidx].yur)); + TRPRINT(tri, obuf); + TRPRINT(tri, stransform); + TRPRINT(tri, "/>\n"); + } + + for (k = 0; k < cxi->cx[jdx].kids.used; k++) { /* over all members of the phase1 complex */ + kdx = cxi->cx[jdx].kids.members[k]; /* index for text objects in tpi */ + tsp = &tpi->chunks[kdx]; + ldir = tsp->ldir; + if (!j && !k) { + if (tri->usebk == BKCLR_ALL) { + TRPRINT(tri, "bkcolor.Red, tri->bkcolor.Green, tri->bkcolor.Blue); + TRPRINT(tri, obuf); + sprintf(obuf, "width=\"%f\"\n", + 1.25 * (bri->rects[csp->rt_cidx].xur - bri->rects[csp->rt_cidx].xll)); + TRPRINT(tri, obuf); + sprintf(obuf, "height=\"%f\"\n", + 1.25 * (bri->rects[csp->rt_cidx].yll - bri->rects[csp->rt_cidx].yur)); + TRPRINT(tri, obuf); + sprintf(obuf, "x=\"%f\" y=\"%f\"\n", 1.25 * (bri->rects[csp->rt_cidx].xll), + 1.25 * (bri->rects[csp->rt_cidx].yur)); + TRPRINT(tri, obuf); + TRPRINT(tri, stransform); + TRPRINT(tri, "/>\n"); + } + } + if (tri->usebk == BKCLR_FRAG) { + newx = 1.25 * (ldir == LDIR_RL ? bri->rects[tsp->rt_tidx].xur : bri->rects[tsp->rt_tidx].xll); + newy = 1.25 * (bri->rects[tsp->rt_tidx].yur); + TRPRINT(tri, "bkcolor.Red, tri->bkcolor.Green, tri->bkcolor.Blue); + TRPRINT(tri, obuf); + sprintf(obuf, "width=\"%f\"\n", + 1.25 * (bri->rects[tsp->rt_tidx].xur - bri->rects[tsp->rt_tidx].xll)); + TRPRINT(tri, obuf); + sprintf(obuf, "height=\"%f\"\n", + 1.25 * (bri->rects[tsp->rt_tidx].yll - bri->rects[tsp->rt_tidx].yur)); + TRPRINT(tri, obuf); + sprintf(obuf, "x=\"%f\" y=\"%f\"\n", newx, newy); + TRPRINT(tri, obuf); + TRPRINT(tri, stransform); + TRPRINT(tri, "/>\n"); + } + } } - } - TRPRINT(tri, "\n"); /* end of grouping for backgrounds for each object in the SVG */ - } - } - - - /* over all complex members from phase2. Paragraphs == TR_PARA_* */ - for(i=cxi->phase1; iused;i++){ - csp = &(cxi->cx[i]); - esc = tri->esc; - esc *= 2.0 * M_PI / 360.0; /* degrees to radians and change direction of rotation */ - - /* over all members of the present Paragraph. Each of these is a line and a phase 1 complex. - It may be either TR_TEXT or TR_LINE */ - for(j=0; jkids.used; j++){ - if(j){ - sprintf(obuf,""); - TRPRINT(tri, obuf); - } - jdx = csp->kids.members[j]; /* index of phase1 complex (all are TR_TEXT or TR_LINE) */ - recenter = 0; /* mostly to quiet a compiler warning, should always be set below */ - - - /* over all members of the present Line. These are the original text objects which were reassembled. - There will be one for TR_TEXT, more than one for TR_LINE */ - for(k=0; kcx[jdx].kids.used; k++){ - kdx = cxi->cx[jdx].kids.members[k]; /* index for text objects in tpi, for this k */ - tsp = &tpi->chunks[kdx]; /* text chunk for this k */ - ldir = tsp->ldir; /* language direction for this k */ - if(!k){ /* first iteration */ - switch(csp->type){ /* set up the alignment, if there is one */ - case TR_TEXT: - case TR_LINE: - /* these should never occur, this section quiets a compiler warning */ - break; - case TR_PARA_UJ: - case TR_PARA_LJ: - if(ldir == LDIR_RL){ recenter = -(bri->rects[cxi->cx[jdx].rt_cidx].xur - bri->rects[cxi->cx[jdx].rt_cidx].xll); } - else { recenter = 0.0; } - break; - case TR_PARA_CJ: - if(ldir == LDIR_RL){ recenter = -(bri->rects[cxi->cx[jdx].rt_cidx].xur - bri->rects[cxi->cx[jdx].rt_cidx].xll)/2.0; } - else { recenter = +(bri->rects[cxi->cx[jdx].rt_cidx].xur - bri->rects[cxi->cx[jdx].rt_cidx].xll)/2.0; } - break; - case TR_PARA_RJ: - if(ldir == LDIR_RL){ recenter = 0.0; } - else { recenter = +(bri->rects[cxi->cx[jdx].rt_cidx].xur - bri->rects[cxi->cx[jdx].rt_cidx].xll); } - break; - } - if(!j){ - TRPRINT(tri, "fs*1.25); /*IMPORTANT, if the FS is given in pt it looks like crap in browsers. As if px != 1.25 pt, maybe 96 dpi not 90?*/ - TRPRINT(tri, obuf); - sprintf(obuf,"font-style:%s;",(tsp->italics ? "italic" : "normal")); - TRPRINT(tri, obuf); - TRPRINT(tri, "font-variant:normal;"); - sprintf(obuf,"font-weight:%d;",TR_weight_FC_to_SVG(tsp->weight)); - TRPRINT(tri, obuf); - sprintf(obuf,"font-stretch:%s;",(tsp->condensed==100 ? "Normal" : "Condensed")); - TRPRINT(tri, obuf); - if(tsp->vadvance){ lineheight = tsp->vadvance *100.0; } - else { lineheight = 125.0; } - sprintf(obuf,"line-height:%f%%;",lineheight); - TRPRINT(tri, obuf); - TRPRINT(tri, "letter-spacing:0px;"); - TRPRINT(tri, "word-spacing:0px;"); - TRPRINT(tri, "fill:#000000;"); - TRPRINT(tri, "fill-opacity:1;"); - TRPRINT(tri, "stroke:none;"); - cutat=strcspn((char *)fti->fonts[tsp->fi_idx].fontspec,":"); - sprintf(obuf,"font-family:%.*s;",cutat,fti->fonts[tsp->fi_idx].fontspec); - TRPRINT(tri, obuf); - switch(csp->type){ /* set up the alignment, if there is one */ - case TR_TEXT: - case TR_LINE: - /* these should never occur, this section quiets a compiler warning */ - break; - case TR_PARA_UJ: - case TR_PARA_LJ: - sprintf(obuf,"text-align:start;text-anchor:start;"); - break; - case TR_PARA_CJ: - sprintf(obuf,"text-align:center;text-anchor:middle;"); - break; - case TR_PARA_RJ: - sprintf(obuf,"text-align:end;text-anchor:end;"); - break; - } - TRPRINT(tri, obuf); - TRPRINT(tri, "\"\n"); /* End of style specification */ - sprintf(obuf,"transform=\"matrix(%f,%f,%f,%f,%f,%f)\"\n",cos(esc),-sin(esc),sin(esc),cos(esc),1.25*x,1.25*y); - TRPRINT(tri, obuf); - tmpx = 1.25*((ldir == LDIR_RL ? bri->rects[kdx].xur : bri->rects[kdx].xll) + recenter); - sprintf(obuf,"x=\"%f\" y=\"%f\"\n>",tmpx,1.25*(bri->rects[kdx].yll - tsp->boff)); - TRPRINT(tri, obuf); - } - tmpx = 1.25*((ldir == LDIR_RL ? bri->rects[kdx].xur : bri->rects[kdx].xll) + recenter); - sprintf(obuf,"",tmpx,1.25*(bri->rects[kdx].yll - tsp->boff)); - TRPRINT(tri, obuf); + TRPRINT(tri, "\n"); /* end of grouping for backgrounds for each object in the SVG */ + } + } + + /* over all complex members from phase2. Paragraphs == TR_PARA_* */ + for (i = cxi->phase1; i < cxi->used; i++) { + csp = &(cxi->cx[i]); + esc = tri->esc; + esc *= 2.0 * M_PI / 360.0; /* degrees to radians and change direction of rotation */ + + /* over all members of the present Paragraph. Each of these is a line and a phase 1 complex. + It may be either TR_TEXT or TR_LINE */ + for (j = 0; j < csp->kids.used; j++) { + if (j) { + sprintf(obuf, ""); + TRPRINT(tri, obuf); } - TRPRINT(tri, "xkern; - dy = 1.25 * tsp->ykern; - - sprintf(obuf,"dx=\"%f\" dy=\"%f\" ",dx, dy); - TRPRINT(tri, obuf); - sprintf(obuf,"style=\"fill:#%2.2X%2.2X%2.2X;",tsp->color.Red,tsp->color.Green,tsp->color.Blue); - TRPRINT(tri, obuf); - sprintf(obuf,"font-size:%fpx;",tsp->fs*1.25); /*IMPORTANT, if the FS is given in pt it looks like crap in browsers. As if px != 1.25 pt, maybe 96 dpi not 90?*/ - TRPRINT(tri, obuf); - sprintf(obuf,"font-style:%s;",(tsp->italics ? "italic" : "normal")); - TRPRINT(tri, obuf); - if(tsp->decoration & TXTDECOR_TMASK){ - sprintf(obuf,"text-decoration:"); - /* multiple text decoration styles may be set */ - utmp = tsp->decoration & TXTDECOR_TMASK; - if(utmp & TXTDECOR_UNDER ){ strcat(obuf," underline"); } - if(utmp & TXTDECOR_OVER ){ strcat(obuf," overline"); } - if(utmp & TXTDECOR_BLINK ){ strcat(obuf," blink"); } - if(utmp & TXTDECOR_STRIKE){ strcat(obuf," line-through");} - if(*obuf){ - /* only a single text decoration line type may be set */ - switch(tsp->decoration & TXTDECOR_LMASK){ - case TXTDECOR_SOLID: break; // "solid" is the CSS 3 default, omitting it remains CSS 2 compatible - case TXTDECOR_DOUBLE: strcat(obuf," double"); break; // these are all CSS3 - case TXTDECOR_DOTTED: strcat(obuf," dotted"); break; - case TXTDECOR_DASHED: strcat(obuf," dashed"); break; - case TXTDECOR_WAVY: strcat(obuf," wavy" ); break; - default: break; - } - if((tsp->decoration & TXTDECOR_CLRSET) && memcmp(&(tsp->decColor),&(tsp->color),sizeof(TRCOLORREF))){ - /* CSS 3, CSS 2 implementations may choke on it. If the specified color matches text color omit, for better CSS 2 compatitiblity. */ - sprintf(cbuf," #%2.2X%2.2X%2.2X",tsp->decColor.Red,tsp->decColor.Green,tsp->decColor.Blue); - strcat(obuf,cbuf); - } + jdx = csp->kids.members[j]; /* index of phase1 complex (all are TR_TEXT or TR_LINE) */ + recenter = 0; /* mostly to quiet a compiler warning, should always be set below */ + + /* over all members of the present Line. These are the original text objects which were reassembled. + There will be one for TR_TEXT, more than one for TR_LINE */ + for (k = 0; k < cxi->cx[jdx].kids.used; k++) { + kdx = cxi->cx[jdx].kids.members[k]; /* index for text objects in tpi, for this k */ + tsp = &tpi->chunks[kdx]; /* text chunk for this k */ + ldir = tsp->ldir; /* language direction for this k */ + if (!k) { /* first iteration */ + switch (csp->type) { /* set up the alignment, if there is one */ + case TR_TEXT: + case TR_LINE: + /* these should never occur, this section quiets a compiler warning */ + break; + case TR_PARA_UJ: + case TR_PARA_LJ: + if (ldir == LDIR_RL) { + recenter = + -(bri->rects[cxi->cx[jdx].rt_cidx].xur - bri->rects[cxi->cx[jdx].rt_cidx].xll); + } else { + recenter = 0.0; + } + break; + case TR_PARA_CJ: + if (ldir == LDIR_RL) { + recenter = + -(bri->rects[cxi->cx[jdx].rt_cidx].xur - bri->rects[cxi->cx[jdx].rt_cidx].xll) / + 2.0; + } else { + recenter = + +(bri->rects[cxi->cx[jdx].rt_cidx].xur - bri->rects[cxi->cx[jdx].rt_cidx].xll) / + 2.0; + } + break; + case TR_PARA_RJ: + if (ldir == LDIR_RL) { + recenter = 0.0; + } else { + recenter = + +(bri->rects[cxi->cx[jdx].rt_cidx].xur - bri->rects[cxi->cx[jdx].rt_cidx].xll); + } + break; + } + if (!j) { + TRPRINT(tri, "fs * 1.25); /*IMPORTANT, if the FS is given in pt it looks like crap in browsers. + As if px != 1.25 pt, maybe 96 dpi not 90?*/ + TRPRINT(tri, obuf); + sprintf(obuf, "font-style:%s;", (tsp->italics ? "italic" : "normal")); + TRPRINT(tri, obuf); + TRPRINT(tri, "font-variant:normal;"); + sprintf(obuf, "font-weight:%d;", TR_weight_FC_to_SVG(tsp->weight)); + TRPRINT(tri, obuf); + sprintf(obuf, "font-stretch:%s;", (tsp->condensed == 100 ? "Normal" : "Condensed")); + TRPRINT(tri, obuf); + if (tsp->vadvance) { + lineheight = tsp->vadvance * 100.0; + } else { + lineheight = 125.0; + } + sprintf(obuf, "line-height:%f%%;", lineheight); + TRPRINT(tri, obuf); + TRPRINT(tri, "letter-spacing:0px;"); + TRPRINT(tri, "word-spacing:0px;"); + TRPRINT(tri, "fill:#000000;"); + TRPRINT(tri, "fill-opacity:1;"); + TRPRINT(tri, "stroke:none;"); + cutat = strcspn((char *)fti->fonts[tsp->fi_idx].fontspec, ":"); + sprintf(obuf, "font-family:%.*s;", cutat, fti->fonts[tsp->fi_idx].fontspec); + TRPRINT(tri, obuf); + switch (csp->type) { /* set up the alignment, if there is one */ + case TR_TEXT: + case TR_LINE: + /* these should never occur, this section quiets a compiler warning */ + break; + case TR_PARA_UJ: + case TR_PARA_LJ: + sprintf(obuf, "text-align:start;text-anchor:start;"); + break; + case TR_PARA_CJ: + sprintf(obuf, "text-align:center;text-anchor:middle;"); + break; + case TR_PARA_RJ: + sprintf(obuf, "text-align:end;text-anchor:end;"); + break; + } + TRPRINT(tri, obuf); + TRPRINT(tri, "\"\n"); /* End of style specification */ + sprintf(obuf, "transform=\"matrix(%f,%f,%f,%f,%f,%f)\"\n", cos(esc), -sin(esc), sin(esc), + cos(esc), 1.25 * x, 1.25 * y); + TRPRINT(tri, obuf); + tmpx = 1.25 * ((ldir == LDIR_RL ? bri->rects[kdx].xur : bri->rects[kdx].xll) + recenter); + sprintf(obuf, "x=\"%f\" y=\"%f\"\n>", tmpx, 1.25 * (bri->rects[kdx].yll - tsp->boff)); + TRPRINT(tri, obuf); + } + tmpx = 1.25 * ((ldir == LDIR_RL ? bri->rects[kdx].xur : bri->rects[kdx].xll) + recenter); + sprintf(obuf, "", tmpx, + 1.25 * (bri->rects[kdx].yll - tsp->boff)); + TRPRINT(tri, obuf); } - strcat(obuf,";"); - TRPRINT(tri,obuf); - } - TRPRINT(tri, "font-variant:normal;"); - sprintf(obuf,"font-weight:%d;",TR_weight_FC_to_SVG(tsp->weight)); - TRPRINT(tri, obuf); - sprintf(obuf,"font-stretch:%s;",(tsp->condensed==100 ? "Normal" : "Condensed")); - TRPRINT(tri, obuf); - cutat=strcspn((char *)fti->fonts[tsp->fi_idx].fontspec,":"); - sprintf(obuf,"font-family:%.*s;\"",cutat,fti->fonts[tsp->fi_idx].fontspec); - TRPRINT(tri, obuf); - TRPRINT(tri, "\n>"); - TRPRINT(tri, (char *) tsp->string); - TRPRINT(tri, ""); - } /* end of k loop */ - } /* end of j loop */ - TRPRINT(tri,"\n"); - } /* end of i loop */ - - /* restore locale and free memory. */ - (void) setlocale(LC_NUMERIC,hold_locale); - free(hold_locale); + TRPRINT(tri, "xkern; + dy = 1.25 * tsp->ykern; + + sprintf(obuf, "dx=\"%f\" dy=\"%f\" ", dx, dy); + TRPRINT(tri, obuf); + sprintf(obuf, "style=\"fill:#%2.2X%2.2X%2.2X;", tsp->color.Red, tsp->color.Green, tsp->color.Blue); + TRPRINT(tri, obuf); + sprintf(obuf, "font-size:%fpx;", + tsp->fs * 1.25); /*IMPORTANT, if the FS is given in pt it looks like crap in browsers. As if px + != 1.25 pt, maybe 96 dpi not 90?*/ + TRPRINT(tri, obuf); + sprintf(obuf, "font-style:%s;", (tsp->italics ? "italic" : "normal")); + TRPRINT(tri, obuf); + if (tsp->decoration & TXTDECOR_TMASK) { + sprintf(obuf, "text-decoration:"); + /* multiple text decoration styles may be set */ + utmp = tsp->decoration & TXTDECOR_TMASK; + if (utmp & TXTDECOR_UNDER) { + strcat(obuf, " underline"); + } + if (utmp & TXTDECOR_OVER) { + strcat(obuf, " overline"); + } + if (utmp & TXTDECOR_BLINK) { + strcat(obuf, " blink"); + } + if (utmp & TXTDECOR_STRIKE) { + strcat(obuf, " line-through"); + } + if (*obuf) { + /* only a single text decoration line type may be set */ + switch (tsp->decoration & TXTDECOR_LMASK) { + case TXTDECOR_SOLID: + break; // "solid" is the CSS 3 default, omitting it remains CSS 2 compatible + case TXTDECOR_DOUBLE: + strcat(obuf, " double"); + break; // these are all CSS3 + case TXTDECOR_DOTTED: + strcat(obuf, " dotted"); + break; + case TXTDECOR_DASHED: + strcat(obuf, " dashed"); + break; + case TXTDECOR_WAVY: + strcat(obuf, " wavy"); + break; + default: + break; + } + if ((tsp->decoration & TXTDECOR_CLRSET) && + memcmp(&(tsp->decColor), &(tsp->color), sizeof(TRCOLORREF))) { + /* CSS 3, CSS 2 implementations may choke on it. If the specified color matches text color + * omit, for better CSS 2 compatitiblity. */ + sprintf(cbuf, " #%2.2X%2.2X%2.2X", tsp->decColor.Red, tsp->decColor.Green, + tsp->decColor.Blue); + strcat(obuf, cbuf); + } + } + strcat(obuf, ";"); + TRPRINT(tri, obuf); + } + TRPRINT(tri, "font-variant:normal;"); + sprintf(obuf, "font-weight:%d;", TR_weight_FC_to_SVG(tsp->weight)); + TRPRINT(tri, obuf); + sprintf(obuf, "font-stretch:%s;", (tsp->condensed == 100 ? "Normal" : "Condensed")); + TRPRINT(tri, obuf); + cutat = strcspn((char *)fti->fonts[tsp->fi_idx].fontspec, ":"); + sprintf(obuf, "font-family:%.*s;\"", cutat, fti->fonts[tsp->fi_idx].fontspec); + TRPRINT(tri, obuf); + TRPRINT(tri, "\n>"); + TRPRINT(tri, (char *)tsp->string); + TRPRINT(tri, ""); + } /* end of k loop */ + } /* end of j loop */ + TRPRINT(tri, "\n"); + } /* end of i loop */ + + /* restore locale and free memory. */ + (void)setlocale(LC_NUMERIC, hold_locale); + free(hold_locale); } /** @@ -2266,705 +2508,824 @@ void TR_layout_2_svg(TR_INFO *tri){ are TR_LINEs, therwise they are TR_TEXT. 2. Group sequential complexes (TR_LINE or TR_TEXT) into TR_PARA_UJ (paragraphs,by smooth progression in vertical position down page). - 3. Analyze the paragraphs to classify them as Left/Center/Right justified (possibly with indentation.) If + 3. Analyze the paragraphs to classify them as Left/Center/Right justified (possibly with indentation.) If they do not fall into any of these categories break that one back down into TR_LINE/TR_TEXT. 4. Return the number of complex text objects. \returns Number of complexes. (>=1, <= number of text objects.) <0 is an error. \param tri pointer to the TR_INFO structure holding the data, which will also hold the results. */ -int TR_layout_analyze(TR_INFO *tri){ - unsigned int i,j,k; - int ok; - int cxidx; - int src_rt; - int dst_rt; - TP_INFO *tpi; - BR_INFO *bri; - CX_INFO *cxi; - FT_INFO *fti; - BRECT_SPECS bsp; - RT_PAD rt_pad_i; - RT_PAD rt_pad_j; - double ratio; - double qsp,dx,dy; - double spcadv; - enum tr_classes type; - TCHUNK_SPECS *tspi; - TCHUNK_SPECS *tspj; - TCHUNK_SPECS *tspRevEnd=NULL; - TCHUNK_SPECS *tspRevStart=NULL; - CX_SPECS *csp; - CHILD_SPECS *kidp; /* used with preceding complex (see below) */ - CHILD_SPECS *kidc; /* used with current complex (see below) */ - int lastldir,ldir,rev; - - if(!tri)return(-1); - if(!tri->cxi)return(-2); - if(!tri->tpi)return(-3); - if(!tri->bri)return(-4); - if(!tri->fti)return(-5); - tpi=tri->tpi; - cxi=tri->cxi; - bri=tri->bri; - fti=tri->fti; - cxi->lines = 0; - cxi->paras = 0; - cxi->phase1 = 0; - -/* When debugging - ftinfo_dump(fti); -*/ - /* Phase 1. Working sequentially, insert text. Initially as TR_TEXT and then try to extend to TR_LINE by checking - overlaps. When done the complexes will contain a mix of TR_LINE and TR_TEXT. */ - - for(i=0; iused; i++){ - tspi = &(tpi->chunks[i]); - memcpy(&bsp,&(bri->rects[tspi->rt_tidx]),sizeof(BRECT_SPECS)); /* Must make a copy as next call may reallocate rects! */ - (void) brinfo_insert(bri,&bsp); - dst_rt = bri->used-1; - (void) cxinfo_insert(cxi, i, dst_rt, TR_TEXT); - cxidx = cxi->used-1; - - spcadv = fti->fonts[tspi->fi_idx].spcadv * tspi->fs/32.0; /* spcadv was always FT_LOAD_NO_SCALE */ - /* for the leading text: pad with no leading and two trailing spaces, leading and trailing depend on direction */ - if(tspi->ldir == LDIR_RL){ TR_rt_pad_set(&rt_pad_i,tri->qe, tri->qe, tri->qe + 2.0 * spcadv, 0.0); } - else { TR_rt_pad_set(&rt_pad_i,tri->qe, tri->qe, 0.0, tri->qe + 2.0 * spcadv); } - - for(j=i+1; jused; j++){ - tspj = &(tpi->chunks[j]); - /* Reject font size changes of greater than 50%, these are almost certainly not continuous text. These happen - in math formulas, for instance, where a sum or integral is much larger than the other symbols. */ - ratio = (double)(tspj->fs)/(double)(tspi->fs); - if(ratio >2.0 || ratio <0.5)break; - - spcadv = fti->fonts[tspj->fi_idx].spcadv * tspj->fs/32.0; /* spcadv was always FT_LOAD_NO_SCALE */ - /* for the trailing text: pad with one leading and trailing spaces (so it should work L->R and R->L) */ - TR_rt_pad_set(&rt_pad_j,tri->qe, tri->qe, spcadv, spcadv); - src_rt = tspj->rt_tidx; - - /* Reject direction changes like [1 <- Hebrew][2 -> English], that is where the direction changes AND the - next logical piece of text is "upstream" positionally of its logical predecessor. The meaning of such - a construct is at best ambiguous. The test is only applied with respect to the first text chunk. This sort - of construct may appear when a valid initial construct like [1->English][2<-Hebrew][3->English] is edited - and the leading chunk of text removed. - - Also reject reversed order text as in (English) (draw order) arranged as . This happens - if the language direction field is incorrect, perhaps due to a corrupt or malformed input file. +int TR_layout_analyze(TR_INFO *tri) +{ + unsigned int i, j, k; + int ok; + int cxidx; + int src_rt; + int dst_rt; + TP_INFO *tpi; + BR_INFO *bri; + CX_INFO *cxi; + FT_INFO *fti; + BRECT_SPECS bsp; + RT_PAD rt_pad_i; + RT_PAD rt_pad_j; + double ratio; + double qsp, dx, dy; + double spcadv; + enum tr_classes type; + TCHUNK_SPECS *tspi; + TCHUNK_SPECS *tspj; + TCHUNK_SPECS *tspRevEnd = NULL; + TCHUNK_SPECS *tspRevStart = NULL; + CX_SPECS *csp; + CHILD_SPECS *kidp; /* used with preceding complex (see below) */ + CHILD_SPECS *kidc; /* used with current complex (see below) */ + int lastldir, ldir, rev; + + if (!tri) + return (-1); + if (!tri->cxi) + return (-2); + if (!tri->tpi) + return (-3); + if (!tri->bri) + return (-4); + if (!tri->fti) + return (-5); + tpi = tri->tpi; + cxi = tri->cxi; + bri = tri->bri; + fti = tri->fti; + cxi->lines = 0; + cxi->paras = 0; + cxi->phase1 = 0; + + /* When debugging + ftinfo_dump(fti); + */ + /* Phase 1. Working sequentially, insert text. Initially as TR_TEXT and then try to extend to TR_LINE by checking + overlaps. When done the complexes will contain a mix of TR_LINE and TR_TEXT. */ + + for (i = 0; i < tpi->used; i++) { + tspi = &(tpi->chunks[i]); + memcpy(&bsp, &(bri->rects[tspi->rt_tidx]), + sizeof(BRECT_SPECS)); /* Must make a copy as next call may reallocate rects! */ + (void)brinfo_insert(bri, &bsp); + dst_rt = bri->used - 1; + (void)cxinfo_insert(cxi, i, dst_rt, TR_TEXT); + cxidx = cxi->used - 1; + + spcadv = fti->fonts[tspi->fi_idx].spcadv * tspi->fs / 32.0; /* spcadv was always FT_LOAD_NO_SCALE */ + /* for the leading text: pad with no leading and two trailing spaces, leading and trailing depend on direction */ - if(brinfo_upstream(bri, - dst_rt, /* index into bri for dst */ - src_rt, /* index into bri for src */ - tspi->ldir,tspj->ldir))break; - - if(!brinfo_overlap(bri, - dst_rt, /* index into bri for dst */ - src_rt, /* index into bri for src */ - &rt_pad_i,&rt_pad_j)){ - (void) cxinfo_append(cxi,j,TR_LINE); - (void) brinfo_merge(bri,dst_rt,src_rt); - /* for the leading text: pad with two leading and trailing spaces (so it should work L->R and R->L */ - spcadv = fti->fonts[tspj->fi_idx].spcadv * tspj->fs/32.0; /* spcadv was always FT_LOAD_NO_SCALE */ - TR_rt_pad_set(&rt_pad_i, tri->qe, tri->qe, - tri->qe + 2.0 * spcadv, tri->qe + 2.0 * spcadv); - } - else { /* either alignment ge*/ - break; - } - } - - /* Bidirectional text will cause complexes to not assemble in one pass. - This happens whenever a change of direction occurs with 2 or more sequential elements in - the opposite direction, - - Let + = LR and - = RL. - - Reading left to right, this happens with +-- or -++. - For instance, the sequence ++-+ ---+ would break into the two complexes shown. - Not until the last element in the second complex is added will the bounding rectangles for the complexes overlap. - - Check for this effect now if there is a preceding complex and the first element of the current complex is - reversed from the last in the preceding. */ - if(cxidx >= 1){ - kidp = &(cxi->cx[cxidx-1].kids); - kidc = &(cxi->cx[cxidx ].kids); - tspi = &(tpi->chunks[ kidp->members[kidp->used - 1] ]); /* here, the last text element in preceding complex */ - tspj = &(tpi->chunks[ kidc->members[0 ] ]); /* here, tge first text element in current complex */ - if(tspi->ldir != tspj->ldir){ - spcadv = fti->fonts[tspi->fi_idx].spcadv * tspi->fs/32.0; - if(tspi->ldir == LDIR_RL){ TR_rt_pad_set(&rt_pad_i,tri->qe, tri->qe, tri->qe + 2.0 * spcadv, 0.0); } - else { TR_rt_pad_set(&rt_pad_i,tri->qe, tri->qe, 0.0, tri->qe + 2.0 * spcadv); } - spcadv = fti->fonts[tspj->fi_idx].spcadv * tspj->fs/32.0; - TR_rt_pad_set(&rt_pad_j,tri->qe, tri->qe, spcadv, spcadv); - if(!brinfo_overlap(bri, - cxi->cx[cxidx-1].rt_cidx, /* index into rt for dst cx */ - cxi->cx[cxidx].rt_cidx, /* index into rt for src cx */ - &rt_pad_i,&rt_pad_j)){ - /* Merge the current complex into the preceding one*/ - (void) cxinfo_merge(cxi, cxidx-1, cxidx, TR_LINE); - (void) brinfo_merge(bri,cxi->cx[cxidx-1].rt_cidx,cxi->cx[cxidx].rt_cidx); /* merge the bounding boxes*/ - (void) cxinfo_trim(cxi); - cxi->lines--; /* else the normal line count value is one too high */ - /* remove the current complex */ + if (tspi->ldir == LDIR_RL) { + TR_rt_pad_set(&rt_pad_i, tri->qe, tri->qe, tri->qe + 2.0 * spcadv, 0.0); + } else { + TR_rt_pad_set(&rt_pad_i, tri->qe, tri->qe, 0.0, tri->qe + 2.0 * spcadv); + } + + for (j = i + 1; j < tpi->used; j++) { + tspj = &(tpi->chunks[j]); + /* Reject font size changes of greater than 50%, these are almost certainly not continuous text. These + happen in math formulas, for instance, where a sum or integral is much larger than the other symbols. */ + ratio = (double)(tspj->fs) / (double)(tspi->fs); + if (ratio > 2.0 || ratio < 0.5) + break; + + spcadv = fti->fonts[tspj->fi_idx].spcadv * tspj->fs / 32.0; /* spcadv was always FT_LOAD_NO_SCALE */ + /* for the trailing text: pad with one leading and trailing spaces (so it should work L->R and R->L) */ + TR_rt_pad_set(&rt_pad_j, tri->qe, tri->qe, spcadv, spcadv); + src_rt = tspj->rt_tidx; + + /* Reject direction changes like [1 <- Hebrew][2 -> English], that is where the direction changes AND the + next logical piece of text is "upstream" positionally of its logical predecessor. The meaning of such + a construct is at best ambiguous. The test is only applied with respect to the first text chunk. This sort + of construct may appear when a valid initial construct like [1->English][2<-Hebrew][3->English] is edited + and the leading chunk of text removed. + + Also reject reversed order text as in (English) (draw order) arranged as . This happens + if the language direction field is incorrect, perhaps due to a corrupt or malformed input file. + */ + if (brinfo_upstream(bri, dst_rt, /* index into bri for dst */ + src_rt, /* index into bri for src */ + tspi->ldir, tspj->ldir)) + break; + + if (!brinfo_overlap(bri, dst_rt, /* index into bri for dst */ + src_rt, /* index into bri for src */ + &rt_pad_i, &rt_pad_j)) { + (void)cxinfo_append(cxi, j, TR_LINE); + (void)brinfo_merge(bri, dst_rt, src_rt); + /* for the leading text: pad with two leading and trailing spaces (so it should work L->R and R->L */ + spcadv = fti->fonts[tspj->fi_idx].spcadv * tspj->fs / 32.0; /* spcadv was always FT_LOAD_NO_SCALE */ + TR_rt_pad_set(&rt_pad_i, tri->qe, tri->qe, tri->qe + 2.0 * spcadv, tri->qe + 2.0 * spcadv); + } else { /* either alignment ge*/ + break; } - } - } - - if(cxi->cx[cxidx].type == TR_LINE)cxi->lines++; - i=j-1; /* start up after the last merged entry (there may not be any) */ - } - cxi->phase1 = cxi->used; /* total complexes defined in this phase, all TR_LINE or TR_TEXT */ - - /* phase 1.5, calculate kerning. This is as good a place to do it as any. At this point all kern values - are zero. Each of these pieces is strictly unidirectional, but each piece can have a different direction. - The direction of the line is set by the first text element. The ends of runs of elements which are - reversed with respect to the line direction are special, everything else is simple: - Let: + == L->R, - == R->L, $ == end of text, the rules for kerning on B are: - A B others xkern - [+|$] + + [+|$] Bll - Aur - [-|$] - - [-|$] All - Bur (chs) - + - + [-|$] Bll - Aur (chs) - - + - [+|$] All - Bur - + - -...[-=C] [+|$] All - Cur (chs) - - + +...[+=C] [-|$] Cll - Aur - - chs = change sign, because dx is an absolute direction, and direction of text on RTL is in -x. - - Kerning calculations currently seems unstable for R->L if the kerning extends to the end of the line. If - the first and last characters are back in sync there are no issues. When things go south R->L left justified - text is not justified when read in. - */ - - for(i=0; i < cxi->phase1; i++){ /* over all lines */ - csp = &(cxi->cx[i]); - if(csp->kids.used < 2)continue; /* no kerning possible */ - tspi = &tpi->chunks[csp->kids.members[0]]; /* used here as last tsp. no kerning is applied to the first element */ - lastldir = ldir = tspi->ldir; - rev = 0; /* the first ldir defines forward and reverse */ - for(j=1; jkids.used; j++){ - tspj = &tpi->chunks[csp->kids.members[j]]; - ldir = tspj->ldir; - if(ldir != lastldir){ /* direction change */ - rev = !rev; /* reverse direction tracker */ - if(!rev){ /* back in original orientation */ - if(ldir == LDIR_RL){ tspj->xkern = bri->rects[tspj->rt_tidx].xur - bri->rects[tspRevStart->rt_tidx].xll; } - else { tspj->xkern = bri->rects[tspj->rt_tidx].xll - bri->rects[tspRevStart->rt_tidx].xur; } - tspj->ykern = (bri->rects[tspj->rt_tidx].yll - tspj->boff) - - (bri->rects[tspRevStart->rt_tidx].yll - tspRevStart->boff); + } + + /* Bidirectional text will cause complexes to not assemble in one pass. + This happens whenever a change of direction occurs with 2 or more sequential elements in + the opposite direction, + + Let + = LR and - = RL. + + Reading left to right, this happens with +-- or -++. + For instance, the sequence ++-+ ---+ would break into the two complexes shown. + Not until the last element in the second complex is added will the bounding rectangles for the complexes + overlap. + + Check for this effect now if there is a preceding complex and the first element of the current complex is + reversed from the last in the preceding. */ + if (cxidx >= 1) { + kidp = &(cxi->cx[cxidx - 1].kids); + kidc = &(cxi->cx[cxidx].kids); + tspi = + &(tpi->chunks[kidp->members[kidp->used - 1]]); /* here, the last text element in preceding complex */ + tspj = &(tpi->chunks[kidc->members[0]]); /* here, tge first text element in current complex */ + if (tspi->ldir != tspj->ldir) { + spcadv = fti->fonts[tspi->fi_idx].spcadv * tspi->fs / 32.0; + if (tspi->ldir == LDIR_RL) { + TR_rt_pad_set(&rt_pad_i, tri->qe, tri->qe, tri->qe + 2.0 * spcadv, 0.0); + } else { + TR_rt_pad_set(&rt_pad_i, tri->qe, tri->qe, 0.0, tri->qe + 2.0 * spcadv); + } + spcadv = fti->fonts[tspj->fi_idx].spcadv * tspj->fs / 32.0; + TR_rt_pad_set(&rt_pad_j, tri->qe, tri->qe, spcadv, spcadv); + if (!brinfo_overlap(bri, cxi->cx[cxidx - 1].rt_cidx, /* index into rt for dst cx */ + cxi->cx[cxidx].rt_cidx, /* index into rt for src cx */ + &rt_pad_i, &rt_pad_j)) { + /* Merge the current complex into the preceding one*/ + (void)cxinfo_merge(cxi, cxidx - 1, cxidx, TR_LINE); + (void)brinfo_merge(bri, cxi->cx[cxidx - 1].rt_cidx, + cxi->cx[cxidx].rt_cidx); /* merge the bounding boxes*/ + (void)cxinfo_trim(cxi); + cxi->lines--; /* else the normal line count value is one too high */ + /* remove the current complex */ + } } - else { /* now in reversed orientation */ - tspRevStart = tspj; /* Save the beginning of this run (length >=1 ) */ - /* scan forward for the last text object in this orientation, include the first */ - for(k=j; k kids.used; k++){ - if(tpi->chunks[csp->kids.members[k]].ldir == ldir){ tspRevEnd = &tpi->chunks[csp->kids.members[k]]; } - else { break; } - } - if(lastldir == LDIR_RL){ tspj->xkern = bri->rects[tspRevEnd->rt_tidx].xur - bri->rects[tspi->rt_tidx].xll; } - else { tspj->xkern = bri->rects[tspRevEnd->rt_tidx].xll - bri->rects[tspi->rt_tidx].xur; } - tspj->ykern = (bri->rects[tspRevEnd->rt_tidx].yll - tspRevEnd->boff) - - (bri->rects[ tspi->rt_tidx].yll - tspi->boff ); + } + + if (cxi->cx[cxidx].type == TR_LINE) + cxi->lines++; + i = j - 1; /* start up after the last merged entry (there may not be any) */ + } + cxi->phase1 = cxi->used; /* total complexes defined in this phase, all TR_LINE or TR_TEXT */ + + /* phase 1.5, calculate kerning. This is as good a place to do it as any. At this point all kern values + are zero. Each of these pieces is strictly unidirectional, but each piece can have a different direction. + The direction of the line is set by the first text element. The ends of runs of elements which are + reversed with respect to the line direction are special, everything else is simple: + Let: + == L->R, - == R->L, $ == end of text, the rules for kerning on B are: + A B others xkern + [+|$] + + [+|$] Bll - Aur + [-|$] - - [-|$] All - Bur (chs) + + - + [-|$] Bll - Aur (chs) + - + - [+|$] All - Bur + + - -...[-=C] [+|$] All - Cur (chs) + - + +...[+=C] [-|$] Cll - Aur + + chs = change sign, because dx is an absolute direction, and direction of text on RTL is in -x. + + Kerning calculations currently seems unstable for R->L if the kerning extends to the end of the line. If + the first and last characters are back in sync there are no issues. When things go south R->L left justified + text is not justified when read in. + */ + + for (i = 0; i < cxi->phase1; i++) { /* over all lines */ + csp = &(cxi->cx[i]); + if (csp->kids.used < 2) + continue; /* no kerning possible */ + tspi = + &tpi->chunks[csp->kids.members[0]]; /* used here as last tsp. no kerning is applied to the first element */ + lastldir = ldir = tspi->ldir; + rev = 0; /* the first ldir defines forward and reverse */ + for (j = 1; j < csp->kids.used; j++) { + tspj = &tpi->chunks[csp->kids.members[j]]; + ldir = tspj->ldir; + if (ldir != lastldir) { /* direction change */ + rev = !rev; /* reverse direction tracker */ + if (!rev) { /* back in original orientation */ + if (ldir == LDIR_RL) { + tspj->xkern = bri->rects[tspj->rt_tidx].xur - bri->rects[tspRevStart->rt_tidx].xll; + } else { + tspj->xkern = bri->rects[tspj->rt_tidx].xll - bri->rects[tspRevStart->rt_tidx].xur; + } + tspj->ykern = (bri->rects[tspj->rt_tidx].yll - tspj->boff) - + (bri->rects[tspRevStart->rt_tidx].yll - tspRevStart->boff); + } else { /* now in reversed orientation */ + tspRevStart = tspj; /* Save the beginning of this run (length >=1 ) */ + /* scan forward for the last text object in this orientation, include the first */ + for (k = j; k < csp->kids.used; k++) { + if (tpi->chunks[csp->kids.members[k]].ldir == ldir) { + tspRevEnd = &tpi->chunks[csp->kids.members[k]]; + } else { + break; + } + } + if (lastldir == LDIR_RL) { + tspj->xkern = bri->rects[tspRevEnd->rt_tidx].xur - bri->rects[tspi->rt_tidx].xll; + } else { + tspj->xkern = bri->rects[tspRevEnd->rt_tidx].xll - bri->rects[tspi->rt_tidx].xur; + } + tspj->ykern = (bri->rects[tspRevEnd->rt_tidx].yll - tspRevEnd->boff) - + (bri->rects[tspi->rt_tidx].yll - tspi->boff); + } + } else { + if (ldir == LDIR_RL) { + tspj->xkern = bri->rects[tspj->rt_tidx].xur - bri->rects[tspi->rt_tidx].xll; + } else { + tspj->xkern = bri->rects[tspj->rt_tidx].xll - bri->rects[tspi->rt_tidx].xur; + } + tspj->ykern = + (bri->rects[tspj->rt_tidx].yll - tspj->boff) - (bri->rects[tspi->rt_tidx].yll - tspi->boff); } - } - else { - if(ldir == LDIR_RL){ tspj->xkern = bri->rects[tspj->rt_tidx].xur - bri->rects[tspi->rt_tidx].xll; } - else { tspj->xkern = bri->rects[tspj->rt_tidx].xll - bri->rects[tspi->rt_tidx].xur; } - tspj->ykern = (bri->rects[tspj->rt_tidx].yll - tspj->boff) - - (bri->rects[tspi->rt_tidx].yll - tspi->boff); - } - - - /* - Sometimes a font substitution was absolutely terrible, for instance, for Arial Narrow on (most) Linux systems, - The resulting advance (xkern) may be much too large so that it overruns the next text chunk. Since - overlapping text on the same line is almost never encountered, this may be used to detect the bad - substitution so that a more appropriate offset can be used. - Detect this situation as a negative dx < 1/2 a space character's width while |dy| < an entire space width. - The y constraints allow super and subscripts, which overlap in x but are shifted above/below in y. - */ - spcadv = fti->fonts[tspj->fi_idx].spcadv * tspj->fs/32.0; - qsp = 0.25 * spcadv; - dx = tspj->xkern; - dy = tspj->ykern; - if(dy <=qsp && dy >= -qsp){ - if(ldir==LDIR_RL){ - if(dx > 2*qsp)tspj->xkern = 0.0; + + /* + Sometimes a font substitution was absolutely terrible, for instance, for Arial Narrow on (most) Linux + systems, The resulting advance (xkern) may be much too large so that it overruns the next text chunk. + Since overlapping text on the same line is almost never encountered, this may be used to detect the bad + substitution so that a more appropriate offset can be used. + Detect this situation as a negative dx < 1/2 a space character's width while |dy| < an entire space width. + The y constraints allow super and subscripts, which overlap in x but are shifted above/below in y. + */ + spcadv = fti->fonts[tspj->fi_idx].spcadv * tspj->fs / 32.0; + qsp = 0.25 * spcadv; + dx = tspj->xkern; + dy = tspj->ykern; + if (dy <= qsp && dy >= -qsp) { + if (ldir == LDIR_RL) { + if (dx > 2 * qsp) + tspj->xkern = 0.0; + } else { + if (dx < -2 * qsp) + tspj->xkern = 0.0; + } } - else { - if(dx < -2*qsp)tspj->xkern = 0.0; + + /* if x or y kern is less than twice the quantization error it is probably noise, set it to zero */ + if (fabs(tspj->xkern) <= 2.0 * tri->qe) + tspj->xkern = 0.0; + if (fabs(tspj->ykern) <= 2.0 * tri->qe) + tspj->ykern = 0.0; + + /* reintroduce spaces on the leading edge of text "j" if the kerning can be in part or in whole replaced + with 1 or 2 spaces */ + if (tspj->ykern == 0.0) { + double spaces = tspj->xkern / spcadv; /* negative on RL language, positive on LR */ + if ((ldir == LDIR_RL && (spaces <= -0.9 && spaces >= -2.1)) || + (ldir == LDIR_LR && (spaces >= 0.9 && spaces <= 2.1))) { + int ispaces = lround(spaces); + tspj->xkern -= ((double)ispaces * spcadv); + if (ispaces < 0) + ispaces = -ispaces; + size_t slen = strlen((char *)tspj->string); + uint8_t *newstring = malloc(1 + ispaces + slen); + sprintf((char *)newstring, + " "); /* start with two spaces, possibly overwrite one in the next line */ + memcpy(newstring + ispaces, tspj->string, slen + 1); /* copy existing string to proper position */ + free(tspj->string); + tspj->string = newstring; + tspj->spaces = ispaces; // only needed to fix optional debugging SVG output later + } } - } - - /* if x or y kern is less than twice the quantization error it is probably noise, set it to zero */ - if(fabs(tspj->xkern) <= 2.0*tri->qe)tspj->xkern = 0.0; - if(fabs(tspj->ykern) <= 2.0*tri->qe)tspj->ykern = 0.0; - - /* reintroduce spaces on the leading edge of text "j" if the kerning can be in part or in whole replaced - with 1 or 2 spaces */ - if(tspj->ykern == 0.0){ - double spaces = tspj->xkern/spcadv; /* negative on RL language, positive on LR */ - if((ldir == LDIR_RL && (spaces <= -0.9 && spaces >= -2.1)) || - (ldir == LDIR_LR && (spaces >= 0.9 && spaces <= 2.1)) ){ - int ispaces = lround(spaces); - tspj->xkern -= ((double)ispaces*spcadv); - if(ispaces<0)ispaces=-ispaces; - size_t slen = strlen((char *)tspj->string); - uint8_t *newstring = malloc(1 + ispaces + slen); - sprintf((char *)newstring," "); /* start with two spaces, possibly overwrite one in the next line */ - memcpy(newstring+ispaces,tspj->string,slen+1); /* copy existing string to proper position */ - free(tspj->string); - tspj->string = newstring; - tspj->spaces = ispaces; // only needed to fix optional debugging SVG output later + + tspi = tspj; + lastldir = ldir; + } + } + + /* Phase 2, try to group sequential lines. There may be "lines" that are still TR_TEXT, as in: + + ... this is a sentence that wraps by one + word. + + And some paragrahs might be single word lines (+ = bullet in the following) + + +verbs + +nouns + +adjectives + + Everything starts out as TR_PARA_UJ and if the next one can be lined up, the type changes to + an aligned paragraph and complexes are appended to the existing one. + */ + + for (i = 0; i < cxi->phase1; i++) { + type = TR_PARA_UJ; /* any paragraph alignment will be acceptable */ + /* Must make a copy as next call may reallocate rects, so if we just passed a pointer to something in the + structure it would vaporize part way through the call. */ + memcpy(&bsp, &(bri->rects[cxi->cx[i].rt_cidx]), sizeof(BRECT_SPECS)); + (void)brinfo_insert(bri, &bsp); + dst_rt = bri->used - 1; + (void)cxinfo_insert(cxi, i, dst_rt, type); + + cxi->paras++; + ok = 1; + for (j = i + 1; ok && (j < cxi->phase1); j++) { + type = brinfo_pp_alignment(bri, cxi->cx[i].rt_cidx, cxi->cx[j].rt_cidx, 3 * tri->qe, type); + switch (type) { + case TR_PARA_UJ: /* paragraph type was set and j line does not fit, or no paragraph alignment matched */ + ok = 0; /* force exit from j loop */ + j--; /* this will increment at loop bottom */ + break; + case TR_PARA_LJ: + case TR_PARA_CJ: + case TR_PARA_RJ: + /* two successive lines have been identified (possible following others already in the paragraph */ + if (TR_check_set_vadvance(tri, j, i)) { /* check for compatibility with vadvance if set, set it if + it isn't. */ + ok = 0; /* force exit from j loop */ + j--; /* this will increment at loop bottom */ + } else { + src_rt = cxi->cx[j].rt_cidx; + (void)cxinfo_append(cxi, j, type); + (void)brinfo_merge(bri, dst_rt, src_rt); + } + break; + default: + return (-6); /* programming error */ } - } - - tspi = tspj; - lastldir = ldir; - } - } - - - /* Phase 2, try to group sequential lines. There may be "lines" that are still TR_TEXT, as in: - - ... this is a sentence that wraps by one - word. - - And some paragrahs might be single word lines (+ = bullet in the following) - - +verbs - +nouns - +adjectives - - Everything starts out as TR_PARA_UJ and if the next one can be lined up, the type changes to - an aligned paragraph and complexes are appended to the existing one. - */ - - for(i=0; i < cxi->phase1; i++){ - type = TR_PARA_UJ; /* any paragraph alignment will be acceptable */ - /* Must make a copy as next call may reallocate rects, so if we just passed a pointer to something in the structure - it would vaporize part way through the call. */ - memcpy(&bsp,&(bri->rects[cxi->cx[i].rt_cidx]),sizeof(BRECT_SPECS)); - (void) brinfo_insert(bri,&bsp); - dst_rt = bri->used-1; - (void) cxinfo_insert(cxi, i, dst_rt, type); - - cxi->paras++; - ok = 1; - for(j=i+1; ok && (j < cxi->phase1); j++){ - type = brinfo_pp_alignment(bri, cxi->cx[i].rt_cidx, cxi->cx[j].rt_cidx, 3*tri->qe, type); - switch (type){ - case TR_PARA_UJ: /* paragraph type was set and j line does not fit, or no paragraph alignment matched */ - ok = 0; /* force exit from j loop */ - j--; /* this will increment at loop bottom */ - break; - case TR_PARA_LJ: - case TR_PARA_CJ: - case TR_PARA_RJ: - /* two successive lines have been identified (possible following others already in the paragraph */ - if(TR_check_set_vadvance(tri,j,i)){ /* check for compatibility with vadvance if set, set it if it isn't. */ - ok = 0; /* force exit from j loop */ - j--; /* this will increment at loop bottom */ - } - else { - src_rt = cxi->cx[j].rt_cidx; - (void) cxinfo_append(cxi, j, type); - (void) brinfo_merge(bri, dst_rt, src_rt); - } - break; - default: - return(-6); /* programming error */ - } - } - if(j>=cxi->phase1)break; - i=j-1; - } - - -/* When debugging - cxinfo_dump(tri); -*/ + } + if (j >= cxi->phase1) + break; + i = j - 1; + } - return(cxi->used); -} + /* When debugging + cxinfo_dump(tri); + */ + return (cxi->used); +} /* no doxygen documentation below this point, these pieces are for the text program, not the library. */ #if TEST -#define MAXLINE 2048 /* big enough for testing */ -enum OP_TYPES {OPCOM,OPOOPS,OPFONT,OPESC,OPORI,OPXY,OPFS,OPTEXT,OPALN,OPLDIR,OPMUL,OPITA,OPWGT,OPDEC,OPCND,OPBKG,OPCLR,OPDCLR,OPBCLR,OPFLAGS,OPEMIT,OPDONE}; - -int parseit(char *buffer,char **data){ - int pre; - pre = strcspn(buffer,":"); - if(!pre)return(OPOOPS); - *data=&buffer[pre+1]; - buffer[pre]='\0'; - if(*buffer=='#' )return(OPCOM ); - if(0==strcmp("FONT",buffer))return(OPFONT); - if(0==strcmp("ESC" ,buffer))return(OPESC ); - if(0==strcmp("ORI", buffer))return(OPORI ); - if(0==strcmp("XY", buffer))return(OPXY ); - if(0==strcmp("FS", buffer))return(OPFS ); - if(0==strcmp("TEXT",buffer))return(OPTEXT); - if(0==strcmp("ALN", buffer))return(OPALN ); - if(0==strcmp("LDIR",buffer))return(OPLDIR); - if(0==strcmp("MUL", buffer))return(OPMUL ); - if(0==strcmp("ITA", buffer))return(OPITA ); - if(0==strcmp("WGT", buffer))return(OPWGT ); - if(0==strcmp("DEC", buffer))return(OPDEC ); - if(0==strcmp("CND", buffer))return(OPCND ); - if(0==strcmp("BKG", buffer))return(OPBKG ); - if(0==strcmp("CLR", buffer))return(OPCLR ); - if(0==strcmp("DCLR", buffer))return(OPDCLR ); - if(0==strcmp("BCLR",buffer))return(OPBCLR ); - if(0==strcmp("FLAG",buffer))return(OPFLAGS); - if(0==strcmp("EMIT",buffer))return(OPEMIT); - if(0==strcmp("DONE",buffer))return(OPDONE); - return(OPOOPS); -} - -void boom(char *string,int lineno){ - fprintf(stderr,"Fatal error at line %d %s\n",lineno,string); - exit(EXIT_FAILURE); -} - - -void init_as_svg(TR_INFO *tri){ - TRPRINT(tri,"\n"); - TRPRINT(tri,"\n"); - TRPRINT(tri,"\n"); - TRPRINT(tri,"\n"); - TRPRINT(tri," \n"); - TRPRINT(tri," \n"); - TRPRINT(tri," \n"); - TRPRINT(tri," \n"); - TRPRINT(tri," \n"); - TRPRINT(tri," image/svg+xml\n"); - TRPRINT(tri," \n"); - TRPRINT(tri," \n"); - TRPRINT(tri," \n"); - TRPRINT(tri," \n"); - TRPRINT(tri," \n"); - TRPRINT(tri," \n"); - TRPRINT(tri,"\n"); -} - - -void flush_as_svg(TR_INFO *tri, FILE *fp){ - fwrite(tri->out,tri->outused,1,fp); -} - -FILE *close_as_svg(TR_INFO *tri, FILE *fp){ - TRPRINT(tri, " \n"); - TRPRINT(tri, "\n"); - flush_as_svg(tri,fp); - fclose(fp); - return(NULL); -} - - -int main(int argc, char *argv[]){ - char *data; - char inbuf[MAXLINE]; - FILE *fpi = NULL; - FILE *fpo = NULL; - int op; - double fact = 1.0; /* input units to points */ - double escapement = 0.0; /* degrees */ - int lineno = 0; - int ok = 1; - int status; - TCHUNK_SPECS tsp; - TR_INFO *tri=NULL; - int flags=0; - char *infile; - uint32_t utmp32; - TRCOLORREF bkcolor; - int bkmode; - char *fontspec; - - infile=malloc(strlen(argv[1])+1); - strcpy(infile,argv[1]); - - if(argc < 2 || !(fpi = fopen(infile,"r"))){ - printf("Usage: text_reassemble input_file\n"); - printf(" Test program reads an input file containing lines like:\n"); - printf(" FONT:(font for next text)\n"); - printf(" ESC:(escapement angle degrees of text line, up from X axis)\n"); - printf(" ORI:(angle degrees of character orientation, up from X axis)\n"); - printf(" FS:(font size, units)\n"); - printf(" XY:(x,y) X 0 is at left, N is at right, Y 0 is at top, N is at bottom, as page is viewed.\n"); - printf(" TEXT:(UTF8 text)\n"); - printf(" ALN:combination of {LCR}{BLT} = Text is placed on {X,Y} at Left/Center/Right of text, at Bottom,baseLine,Top of text.\n"); - printf(" LDIR:{LR|RL|TB) Left to Right, Right to Left, and Top to Bottom \n"); - printf(" MUL:(float, multiplicative factor to convert FS,XY units to points).\n"); - printf(" ITA:(Italics, 0=normal, 100=italics, 110=oblique).\n"); - printf(" WGT:(Weight, 0-215: 80=normal, 200=bold, 215=ultrablack, 0=thin)).\n"); - printf(" DEC:(this is a bit field. For color see DCLR\n"); - printf(" style: 000 none, 001 underline,002 overline, 004 blink, 008 strike-through\n"); - printf(" line: 000 solid, 010 double, 020 dotted, 040 dashed, 080 wavy)\n"); - printf(" CND:(Condensed 50-200: 100=normal, 50=ultracondensed, 75=condensed, 200=expanded).\n"); - printf(" BKG:(Background color: 0 none, 1 by input fragment, 2 by assembled line, 3 by entire assembly. Use BCLR, THEN BKG) \n"); - printf(" CLR:(Text RGB color, as 6 HEX digits, like: FF0000 (red) or 0000FF (blue)) \n"); - printf(" DCLR:(Decoration color, specify like CLR, except 1000000 or higher disables.)\n"); - printf(" BCLR:(Background RGB color, specify like CLR.) \n"); - printf(" FLAG: Special processing options. 1 EMF compatible text alignment.\n"); - printf(" EMIT:(Process everything up to this point, then start clean for remaining input).\n"); - printf(" DONE:(no more input, process it).\n"); - printf(" # comment\n"); - printf("\n"); - printf(" The output is a summary of how the pieces are to be assembled into complex text.\n"); - printf("\n"); - printf(" egrep pattern: '^LOAD:|^FONT:|^ESC:|^ORI:|^FS:|^XY:|^TEXT:|^ALN:|^LDIR:|^MUL:|^ITA:|^WGT:|^DEC:|^CND:|^BKG:|^CLR:|^BCLR:|^DCLR:|^FLAG:|^EMIT:^DONE:'\n"); - exit(EXIT_FAILURE); - } - - tri = trinfo_init(tri); /* If it loops the trinfo_clear at the end will reset tri to the proper state, do NOT call trinfo_init twice! */ +#define MAXLINE 2048 /* big enough for testing */ +enum OP_TYPES +{ + OPCOM, + OPOOPS, + OPFONT, + OPESC, + OPORI, + OPXY, + OPFS, + OPTEXT, + OPALN, + OPLDIR, + OPMUL, + OPITA, + OPWGT, + OPDEC, + OPCND, + OPBKG, + OPCLR, + OPDCLR, + OPBCLR, + OPFLAGS, + OPEMIT, + OPDONE +}; + +int parseit(char *buffer, char **data) +{ + int pre; + pre = strcspn(buffer, ":"); + if (!pre) + return (OPOOPS); + *data = &buffer[pre + 1]; + buffer[pre] = '\0'; + if (*buffer == '#') + return (OPCOM); + if (0 == strcmp("FONT", buffer)) + return (OPFONT); + if (0 == strcmp("ESC", buffer)) + return (OPESC); + if (0 == strcmp("ORI", buffer)) + return (OPORI); + if (0 == strcmp("XY", buffer)) + return (OPXY); + if (0 == strcmp("FS", buffer)) + return (OPFS); + if (0 == strcmp("TEXT", buffer)) + return (OPTEXT); + if (0 == strcmp("ALN", buffer)) + return (OPALN); + if (0 == strcmp("LDIR", buffer)) + return (OPLDIR); + if (0 == strcmp("MUL", buffer)) + return (OPMUL); + if (0 == strcmp("ITA", buffer)) + return (OPITA); + if (0 == strcmp("WGT", buffer)) + return (OPWGT); + if (0 == strcmp("DEC", buffer)) + return (OPDEC); + if (0 == strcmp("CND", buffer)) + return (OPCND); + if (0 == strcmp("BKG", buffer)) + return (OPBKG); + if (0 == strcmp("CLR", buffer)) + return (OPCLR); + if (0 == strcmp("DCLR", buffer)) + return (OPDCLR); + if (0 == strcmp("BCLR", buffer)) + return (OPBCLR); + if (0 == strcmp("FLAG", buffer)) + return (OPFLAGS); + if (0 == strcmp("EMIT", buffer)) + return (OPEMIT); + if (0 == strcmp("DONE", buffer)) + return (OPDONE); + return (OPOOPS); +} + +void boom(char *string, int lineno) +{ + fprintf(stderr, "Fatal error at line %d %s\n", lineno, string); + exit(EXIT_FAILURE); +} + +void init_as_svg(TR_INFO *tri) +{ + TRPRINT(tri, "\n"); + TRPRINT(tri, "\n"); + TRPRINT(tri, "\n"); + TRPRINT(tri, "\n"); + TRPRINT(tri, " \n"); + TRPRINT(tri, " \n"); + TRPRINT(tri, " \n"); + TRPRINT(tri, " \n"); + TRPRINT(tri, " \n"); + TRPRINT(tri, " image/svg+xml\n"); + TRPRINT(tri, " \n"); + TRPRINT(tri, " \n"); + TRPRINT(tri, " \n"); + TRPRINT(tri, " \n"); + TRPRINT(tri, " \n"); + TRPRINT(tri, " \n"); + TRPRINT(tri, "\n"); +} + +void flush_as_svg(TR_INFO *tri, FILE *fp) +{ + fwrite(tri->out, tri->outused, 1, fp); +} + +FILE *close_as_svg(TR_INFO *tri, FILE *fp) +{ + TRPRINT(tri, " \n"); + TRPRINT(tri, "\n"); + flush_as_svg(tri, fp); + fclose(fp); + return (NULL); +} + +int main(int argc, char *argv[]) +{ + char *data; + char inbuf[MAXLINE]; + FILE *fpi = NULL; + FILE *fpo = NULL; + int op; + double fact = 1.0; /* input units to points */ + double escapement = 0.0; /* degrees */ + int lineno = 0; + int ok = 1; + int status; + TCHUNK_SPECS tsp; + TR_INFO *tri = NULL; + int flags = 0; + char *infile; + uint32_t utmp32; + TRCOLORREF bkcolor; + int bkmode; + char *fontspec; + + infile = malloc(strlen(argv[1]) + 1); + strcpy(infile, argv[1]); + + if (argc < 2 || !(fpi = fopen(infile, "r"))) { + printf("Usage: text_reassemble input_file\n"); + printf(" Test program reads an input file containing lines like:\n"); + printf(" FONT:(font for next text)\n"); + printf(" ESC:(escapement angle degrees of text line, up from X axis)\n"); + printf(" ORI:(angle degrees of character orientation, up from X axis)\n"); + printf(" FS:(font size, units)\n"); + printf(" XY:(x,y) X 0 is at left, N is at right, Y 0 is at top, N is at bottom, as page is viewed.\n"); + printf(" TEXT:(UTF8 text)\n"); + printf(" ALN:combination of {LCR}{BLT} = Text is placed on {X,Y} at Left/Center/Right of text, at " + "Bottom,baseLine,Top of text.\n"); + printf(" LDIR:{LR|RL|TB) Left to Right, Right to Left, and Top to Bottom \n"); + printf(" MUL:(float, multiplicative factor to convert FS,XY units to points).\n"); + printf(" ITA:(Italics, 0=normal, 100=italics, 110=oblique).\n"); + printf(" WGT:(Weight, 0-215: 80=normal, 200=bold, 215=ultrablack, 0=thin)).\n"); + printf(" DEC:(this is a bit field. For color see DCLR\n"); + printf(" style: 000 none, 001 underline,002 overline, 004 blink, 008 strike-through\n"); + printf(" line: 000 solid, 010 double, 020 dotted, 040 dashed, 080 wavy)\n"); + printf(" CND:(Condensed 50-200: 100=normal, 50=ultracondensed, 75=condensed, 200=expanded).\n"); + printf(" BKG:(Background color: 0 none, 1 by input fragment, 2 by assembled line, 3 by entire assembly. Use " + "BCLR, THEN BKG) \n"); + printf(" CLR:(Text RGB color, as 6 HEX digits, like: FF0000 (red) or 0000FF (blue)) \n"); + printf(" DCLR:(Decoration color, specify like CLR, except 1000000 or higher disables.)\n"); + printf(" BCLR:(Background RGB color, specify like CLR.) \n"); + printf(" FLAG: Special processing options. 1 EMF compatible text alignment.\n"); + printf(" EMIT:(Process everything up to this point, then start clean for remaining input).\n"); + printf(" DONE:(no more input, process it).\n"); + printf(" # comment\n"); + printf("\n"); + printf(" The output is a summary of how the pieces are to be assembled into complex text.\n"); + printf("\n"); + printf(" egrep pattern: " + "'^LOAD:|^FONT:|^ESC:|^ORI:|^FS:|^XY:|^TEXT:|^ALN:|^LDIR:|^MUL:|^ITA:|^WGT:|^DEC:|^CND:|^BKG:|^CLR:|^" + "BCLR:|^DCLR:|^FLAG:|^EMIT:^DONE:'\n"); + exit(EXIT_FAILURE); + } + + tri = trinfo_init(tri); /* If it loops the trinfo_clear at the end will reset tri to the proper state, do NOT call + trinfo_init twice! */ #ifdef DBG_LOOP - int ldx; - for(ldx=0;ldx<5;ldx++){ - if(fpi)fclose(fpi); - fpi = fopen(infile,"r"); + int ldx; + for (ldx = 0; ldx < 5; ldx++) { + if (fpi) + fclose(fpi); + fpi = fopen(infile, "r"); #endif - tsp.string = NULL; - tsp.ori = 0.0; /* degrees */ - tsp.fs = 12.0; /* font size */ - tsp.x = 0.0; - tsp.y = 0.0; - tsp.boff = 0.0; /* offset to baseline from LL corner of bounding rectangle, changes with fs and taln*/ - tsp.vadvance = 0.0; /* meaningful only when a complex contains two or more lines */ - tsp.taln = ALILEFT + ALIBASE; - tsp.ldir = LDIR_LR; - tsp.color.Red = tsp.decColor.Red = 0; /* RGBA Black */ - tsp.color.Green = tsp.decColor.Green = 0; /* RGBA Black */ - tsp.color.Blue = tsp.decColor.Blue = 0; /* RGBA Black */ - tsp.color.Reserved = tsp.decColor.Reserved = 0; /* unused */ - tsp.italics = 0; - tsp.weight = 80; - tsp.condensed = 100; - tsp.decoration = 0; /* none */ - tsp.spaces = 0; /* none */ - tsp.fi_idx = -1; /* set to an invalid */ - tsp.rt_tidx = -1; /* set to an invalid */ - tsp.xkern = tsp.ykern = 0.0; - /* no need to set rt_tidx */ - - - - if(!tri){ - fprintf(stderr,"Fatal error, could not initialize data structures\n"); - exit(EXIT_FAILURE); - } - (void) trinfo_load_ft_opts(tri, 1, - FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, - FT_KERNING_UNSCALED); - - fpo=fopen("dump.svg","wb"); - init_as_svg(tri); - - while(ok){ - lineno++; - if(!fgets(inbuf,MAXLINE,fpi))boom("Unexpected end of file - no DONE:",lineno); - inbuf[strlen(inbuf)-1]='\0'; /* step on the EOL character */ - op = parseit(inbuf,&data); - switch(op){ - case OPCOM: /* ignore comments*/ - break; - case OPFONT: - /* If the font name includes "Narrow" condensed may not have been set */ - if(0<= TR_findcasesub(data, "Narrow")){ - tsp.co=1; - } - else { - tsp.co=0; - } - fontspec = TR_construct_fontspec(&tsp, data); - if((tsp.fi_idx = ftinfo_load_fontname(tri->fti, fontspec)) < 0 )boom("Font load failed",lineno); - free(fontspec); - break; - case OPESC: - if(1 != sscanf(data,"%lf",&escapement))boom("Invalid ESC:",lineno); - break; - case OPORI: - if(1 != sscanf(data,"%lf",&tsp.ori))boom("Invalid ORI:",lineno); - break; - case OPFS: - if(1 != sscanf(data,"%lf",&tsp.fs) || tsp.fs <= 0.0)boom("Invalid FS:",lineno); - tsp.fs *= fact; - break; - case OPXY: - if(2 != sscanf(data,"%lf,%lf",&tsp.x,&tsp.y) )boom("Invalid XY:",lineno); - tsp.x *= fact; - tsp.y *= fact; - break; - case OPTEXT: - tsp.string = (uint8_t *) U_strdup(data); - /* FreeType parameters match inkscape*/ - status = trinfo_load_textrec(tri, &tsp, escapement,flags); - if(status==-1){ // change of escapement, emit what we have and reset - TR_layout_analyze(tri); - TR_layout_2_svg(tri); - flush_as_svg(tri, fpo); - tri = trinfo_clear(tri); - if(trinfo_load_textrec(tri, &tsp, escapement,flags)){ boom("Text load failed",lineno); } - } - else if(status){ boom("Text load failed",lineno); } - break; - case OPALN: - tsp.taln=0; - switch (*data++){ - case 'L': tsp.taln |= ALILEFT; break; - case 'C': tsp.taln |= ALICENTER; break; - case 'R': tsp.taln |= ALIRIGHT; break; - default: boom("Invalid ALN:",lineno); - } - switch (*data++){ - case 'T': tsp.taln |= ALITOP; break; - case 'L': tsp.taln |= ALIBASE; break; - case 'B': tsp.taln |= ALIBOT; break; - default: boom("Invalid ALN:",lineno); - } - break; - case OPLDIR: - tsp.ldir=0; - if(0==strcmp("LR",data)){ tsp.ldir=LDIR_LR; break;} - if(0==strcmp("RL",data)){ tsp.ldir=LDIR_RL; break;} - if(0==strcmp("TB",data)){ tsp.ldir=LDIR_TB; break;} - boom("Invalid LDIR:",lineno); - break; - case OPMUL: - if(1 != sscanf(data,"%lf",&fact) || fact <= 0.0)boom("Invalid MUL:",lineno); - (void) trinfo_load_qe(tri,fact); - break; - case OPITA: - if(1 != sscanf(data,"%d",&tsp.italics) || tsp.italics < 0 || tsp.italics>110)boom("Invalid ITA:",lineno); - break; - case OPWGT: - if(1 != sscanf(data,"%d",&tsp.weight) || tsp.weight < 0 || tsp.weight > 215)boom("Invalid WGT:",lineno); - break; - case OPDEC: - if(1 != sscanf(data,"%X",(unsigned int *) &tsp.decoration))boom("Invalid DEC:",lineno); - break; - case OPCND: - if(1 != sscanf(data,"%d",&tsp.condensed) || tsp.condensed < 50 || tsp.condensed > 200)boom("Invalid CND:",lineno); - break; - case OPBKG: - if(1 != sscanf(data,"%d",&bkmode) )boom("Invalid BKG:",lineno); - (void) trinfo_load_bk(tri,bkmode,bkcolor); - break; - case OPCLR: - if(1 != sscanf(data,"%x",&utmp32) )boom("Invalid CLR:",lineno); - tsp.color.Red = (utmp32 >> 16) & 0xFF; - tsp.color.Green = (utmp32 >> 8) & 0xFF; - tsp.color.Blue = (utmp32 >> 0) & 0xFF; - tsp.color.Reserved = 0; - break; - case OPDCLR: - if(1 != sscanf(data,"%x",&utmp32) )boom("Invalid DCLR:",lineno); - if(utmp32 >= 0x1000000){ - tsp.decColor.Red = tsp.decColor.Green = tsp.decColor.Blue = tsp.decColor.Reserved = 0; - tsp.decoration &= ~TXTDECOR_CLRSET; - } - else { - tsp.decColor.Red = (utmp32 >> 16) & 0xFF; - tsp.decColor.Green = (utmp32 >> 8) & 0xFF; - tsp.decColor.Blue = (utmp32 >> 0) & 0xFF; - tsp.decColor.Reserved = 0; - tsp.decoration |= TXTDECOR_CLRSET; + tsp.string = NULL; + tsp.ori = 0.0; /* degrees */ + tsp.fs = 12.0; /* font size */ + tsp.x = 0.0; + tsp.y = 0.0; + tsp.boff = 0.0; /* offset to baseline from LL corner of bounding rectangle, changes with fs and taln*/ + tsp.vadvance = 0.0; /* meaningful only when a complex contains two or more lines */ + tsp.taln = ALILEFT + ALIBASE; + tsp.ldir = LDIR_LR; + tsp.color.Red = tsp.decColor.Red = 0; /* RGBA Black */ + tsp.color.Green = tsp.decColor.Green = 0; /* RGBA Black */ + tsp.color.Blue = tsp.decColor.Blue = 0; /* RGBA Black */ + tsp.color.Reserved = tsp.decColor.Reserved = 0; /* unused */ + tsp.italics = 0; + tsp.weight = 80; + tsp.condensed = 100; + tsp.decoration = 0; /* none */ + tsp.spaces = 0; /* none */ + tsp.fi_idx = -1; /* set to an invalid */ + tsp.rt_tidx = -1; /* set to an invalid */ + tsp.xkern = tsp.ykern = 0.0; + /* no need to set rt_tidx */ + + if (!tri) { + fprintf(stderr, "Fatal error, could not initialize data structures\n"); + exit(EXIT_FAILURE); + } + (void)trinfo_load_ft_opts(tri, 1, FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, + FT_KERNING_UNSCALED); + + fpo = fopen("dump.svg", "wb"); + init_as_svg(tri); + + while (ok) { + lineno++; + if (!fgets(inbuf, MAXLINE, fpi)) + boom("Unexpected end of file - no DONE:", lineno); + inbuf[strlen(inbuf) - 1] = '\0'; /* step on the EOL character */ + op = parseit(inbuf, &data); + switch (op) { + case OPCOM: /* ignore comments*/ + break; + case OPFONT: + /* If the font name includes "Narrow" condensed may not have been set */ + if (0 <= TR_findcasesub(data, "Narrow")) { + tsp.co = 1; + } else { + tsp.co = 0; + } + fontspec = TR_construct_fontspec(&tsp, data); + if ((tsp.fi_idx = ftinfo_load_fontname(tri->fti, fontspec)) < 0) + boom("Font load failed", lineno); + free(fontspec); + break; + case OPESC: + if (1 != sscanf(data, "%lf", &escapement)) + boom("Invalid ESC:", lineno); + break; + case OPORI: + if (1 != sscanf(data, "%lf", &tsp.ori)) + boom("Invalid ORI:", lineno); + break; + case OPFS: + if (1 != sscanf(data, "%lf", &tsp.fs) || tsp.fs <= 0.0) + boom("Invalid FS:", lineno); + tsp.fs *= fact; + break; + case OPXY: + if (2 != sscanf(data, "%lf,%lf", &tsp.x, &tsp.y)) + boom("Invalid XY:", lineno); + tsp.x *= fact; + tsp.y *= fact; + break; + case OPTEXT: + tsp.string = (uint8_t *)U_strdup(data); + /* FreeType parameters match inkscape*/ + status = trinfo_load_textrec(tri, &tsp, escapement, flags); + if (status == -1) { // change of escapement, emit what we have and reset + TR_layout_analyze(tri); + TR_layout_2_svg(tri); + flush_as_svg(tri, fpo); + tri = trinfo_clear(tri); + if (trinfo_load_textrec(tri, &tsp, escapement, flags)) { + boom("Text load failed", lineno); + } + } else if (status) { + boom("Text load failed", lineno); + } + break; + case OPALN: + tsp.taln = 0; + switch (*data++) { + case 'L': + tsp.taln |= ALILEFT; + break; + case 'C': + tsp.taln |= ALICENTER; + break; + case 'R': + tsp.taln |= ALIRIGHT; + break; + default: + boom("Invalid ALN:", lineno); + } + switch (*data++) { + case 'T': + tsp.taln |= ALITOP; + break; + case 'L': + tsp.taln |= ALIBASE; + break; + case 'B': + tsp.taln |= ALIBOT; + break; + default: + boom("Invalid ALN:", lineno); + } + break; + case OPLDIR: + tsp.ldir = 0; + if (0 == strcmp("LR", data)) { + tsp.ldir = LDIR_LR; + break; + } + if (0 == strcmp("RL", data)) { + tsp.ldir = LDIR_RL; + break; + } + if (0 == strcmp("TB", data)) { + tsp.ldir = LDIR_TB; + break; + } + boom("Invalid LDIR:", lineno); + break; + case OPMUL: + if (1 != sscanf(data, "%lf", &fact) || fact <= 0.0) + boom("Invalid MUL:", lineno); + (void)trinfo_load_qe(tri, fact); + break; + case OPITA: + if (1 != sscanf(data, "%d", &tsp.italics) || tsp.italics < 0 || tsp.italics > 110) + boom("Invalid ITA:", lineno); + break; + case OPWGT: + if (1 != sscanf(data, "%d", &tsp.weight) || tsp.weight < 0 || tsp.weight > 215) + boom("Invalid WGT:", lineno); + break; + case OPDEC: + if (1 != sscanf(data, "%X", (unsigned int *)&tsp.decoration)) + boom("Invalid DEC:", lineno); + break; + case OPCND: + if (1 != sscanf(data, "%d", &tsp.condensed) || tsp.condensed < 50 || tsp.condensed > 200) + boom("Invalid CND:", lineno); + break; + case OPBKG: + if (1 != sscanf(data, "%d", &bkmode)) + boom("Invalid BKG:", lineno); + (void)trinfo_load_bk(tri, bkmode, bkcolor); + break; + case OPCLR: + if (1 != sscanf(data, "%x", &utmp32)) + boom("Invalid CLR:", lineno); + tsp.color.Red = (utmp32 >> 16) & 0xFF; + tsp.color.Green = (utmp32 >> 8) & 0xFF; + tsp.color.Blue = (utmp32 >> 0) & 0xFF; + tsp.color.Reserved = 0; + break; + case OPDCLR: + if (1 != sscanf(data, "%x", &utmp32)) + boom("Invalid DCLR:", lineno); + if (utmp32 >= 0x1000000) { + tsp.decColor.Red = tsp.decColor.Green = tsp.decColor.Blue = tsp.decColor.Reserved = 0; + tsp.decoration &= ~TXTDECOR_CLRSET; + } else { + tsp.decColor.Red = (utmp32 >> 16) & 0xFF; + tsp.decColor.Green = (utmp32 >> 8) & 0xFF; + tsp.decColor.Blue = (utmp32 >> 0) & 0xFF; + tsp.decColor.Reserved = 0; + tsp.decoration |= TXTDECOR_CLRSET; + } + break; + case OPBCLR: + if (1 != sscanf(data, "%x", &utmp32)) + boom("Invalid BCLR:", lineno); + bkcolor.Red = (utmp32 >> 16) & 0xFF; + bkcolor.Green = (utmp32 >> 8) & 0xFF; + bkcolor.Blue = (utmp32 >> 0) & 0xFF; + bkcolor.Reserved = 0; + break; + case OPFLAGS: + if (1 != sscanf(data, "%d", &flags)) + boom("Invalid FLAG:", lineno); + break; + case OPEMIT: + TR_layout_analyze(tri); + TR_layout_2_svg(tri); + flush_as_svg(tri, fpo); + tri = trinfo_clear(tri); + break; + case OPDONE: + TR_layout_analyze(tri); + TR_layout_2_svg(tri); + flush_as_svg(tri, fpo); + tri = trinfo_clear(tri); + ok = 0; + break; + case OPOOPS: + default: + boom("Input line cannot be parsed", lineno); + break; } - break; - case OPBCLR: - if(1 != sscanf(data,"%x",&utmp32) )boom("Invalid BCLR:",lineno); - bkcolor.Red = (utmp32 >> 16) & 0xFF; - bkcolor.Green = (utmp32 >> 8) & 0xFF; - bkcolor.Blue = (utmp32 >> 0) & 0xFF; - bkcolor.Reserved = 0; - break; - case OPFLAGS: - if(1 != sscanf(data,"%d",&flags) )boom("Invalid FLAG:",lineno); - break; - case OPEMIT: - TR_layout_analyze(tri); - TR_layout_2_svg(tri); - flush_as_svg(tri, fpo); - tri = trinfo_clear(tri); - break; - case OPDONE: - TR_layout_analyze(tri); - TR_layout_2_svg(tri); - flush_as_svg(tri, fpo); - tri = trinfo_clear(tri); - ok = 0; - break; - case OPOOPS: - default: - boom("Input line cannot be parsed",lineno); - break; - } - - } - - if(fpo){ - fpo=close_as_svg(tri, fpo); - } + } + if (fpo) { + fpo = close_as_svg(tri, fpo); + } #ifdef DBG_LOOP - tri = trinfo_clear(tri); - ok = 1; - } + tri = trinfo_clear(tri); + ok = 1; + } #endif /* DBG_LOOP */ - fclose(fpi); - tri = trinfo_release(tri); - free(infile); + fclose(fpi); + tri = trinfo_release(tri); + free(infile); - exit(EXIT_SUCCESS); + exit(EXIT_SUCCESS); } #endif /* TEST */ diff --git a/src/extension/internal/text_reassemble.h b/src/extension/internal/text_reassemble.h index 25b556abb92852a42fd79f0c667e59472bb996e9..c544d4fe2215f9f29970687a79a5a89e83ad7533 100644 --- a/src/extension/internal/text_reassemble.h +++ b/src/extension/internal/text_reassemble.h @@ -28,280 +28,291 @@ Copyright: 2014 David Mathog and California Institute of Technology (Caltech) extern "C" { #endif - -#include //NOLINT -#include //NOLINT -#include //NOLINT -#include //NOLINT -#include //NOLINT +#include //NOLINT #include #include #include +#include //NOLINT +#include //NOLINT +#include //NOLINT +#include //NOLINT #include FT_FREETYPE_H #include FT_GLYPH_H /** \cond */ -#define TEREMIN(A,B) (A < B ? A : B) -#define TEREMAX(A,B) (A > B ? A : B) +#define TEREMIN(A, B) (A < B ? A : B) +#define TEREMAX(A, B) (A > B ? A : B) #ifndef M_PI -# define M_PI 3.14159265358979323846 /* pi */ -#endif +#define M_PI 3.14159265358979323846 /* pi */ +#endif #define ALLOCINFO_CHUNK 32 -#define ALLOCOUT_CHUNK 8192 +#define ALLOCOUT_CHUNK 8192 #define TRPRINT trinfo_append_out /** \endcond */ /** \defgroup color background options - Text is underwritten with the background color not at all, + Text is underwritten with the background color not at all, by reassembled line, or by full assembly . @{ */ -#define BKCLR_NONE 0x00 /**< text is not underwritten with background color (default) */ -#define BKCLR_FRAG 0x01 /**< each fragment of text is underwritten with background color */ -#define BKCLR_LINE 0x02 /**< each line of text is underwritten with background color */ -#define BKCLR_ALL 0x03 /**< entire assembly is underwritten with background color */ +#define BKCLR_NONE 0x00 /**< text is not underwritten with background color (default) */ +#define BKCLR_FRAG 0x01 /**< each fragment of text is underwritten with background color */ +#define BKCLR_LINE 0x02 /**< each line of text is underwritten with background color */ +#define BKCLR_ALL 0x03 /**< entire assembly is underwritten with background color */ /** @} */ /** \defgroup decoration options - One of these values may be present in the decoration field. + One of these values may be present in the decoration field. Unused bits may be used by end user code. These values are SVG specific. Other applications could use the text decoration field for a different set of bits, so long as it provided its own output function. @{ */ -#define TXTDECOR_NONE 0x000 /**< text is not decorated (default) */ -#define TXTDECOR_UNDER 0x001 /**< underlined */ -#define TXTDECOR_OVER 0x002 /**< overlined */ -#define TXTDECOR_BLINK 0x004 /**< blinking text */ -#define TXTDECOR_STRIKE 0x008 /**< strike through */ -#define TXTDECOR_TMASK 0x00F /**< Mask for selecting bits above */ - -#define TXTDECOR_SOLID 0x000 /**< draw as single solid line */ -#define TXTDECOR_DOUBLE 0x010 /**< draw as double solid line */ -#define TXTDECOR_DOTTED 0x020 /**< draw as single dotted line */ -#define TXTDECOR_DASHED 0x040 /**< draw as single dashed line */ -#define TXTDECOR_WAVY 0x080 /**< draw as single wavy line */ -#define TXTDECOR_LMASK 0x0F0 /**< Mask for selecting these bits */ - -#define TXTDECOR_CLRSET 0x100 /**< decoration has its own color */ +#define TXTDECOR_NONE 0x000 /**< text is not decorated (default) */ +#define TXTDECOR_UNDER 0x001 /**< underlined */ +#define TXTDECOR_OVER 0x002 /**< overlined */ +#define TXTDECOR_BLINK 0x004 /**< blinking text */ +#define TXTDECOR_STRIKE 0x008 /**< strike through */ +#define TXTDECOR_TMASK 0x00F /**< Mask for selecting bits above */ + +#define TXTDECOR_SOLID 0x000 /**< draw as single solid line */ +#define TXTDECOR_DOUBLE 0x010 /**< draw as double solid line */ +#define TXTDECOR_DOTTED 0x020 /**< draw as single dotted line */ +#define TXTDECOR_DASHED 0x040 /**< draw as single dashed line */ +#define TXTDECOR_WAVY 0x080 /**< draw as single wavy line */ +#define TXTDECOR_LMASK 0x0F0 /**< Mask for selecting these bits */ + +#define TXTDECOR_CLRSET 0x100 /**< decoration has its own color */ /** @} */ - - - - /** \defgroup text alignment types Location of text's {X,Y} coordinate on bounding rectangle. Values are compatible with Fontconfig. @{ */ -#define ALILEFT 0x01 /**< text object horizontal alignment = left */ -#define ALICENTER 0x02 /**< text object horizontal alignment = center */ -#define ALIRIGHT 0x04 /**< text object horizontal alignment = right */ -#define ALIHORI 0x07 /**< text object horizontal alignment mask */ -#define ALITOP 0x08 /**< text object vertical alignment = top */ -#define ALIBASE 0x10 /**< text object vertical alignment = baseline */ -#define ALIBOT 0x20 /**< text object vertical alignment = bottom */ -#define ALIVERT 0x38 /**< text object vertical alignment mask */ +#define ALILEFT 0x01 /**< text object horizontal alignment = left */ +#define ALICENTER 0x02 /**< text object horizontal alignment = center */ +#define ALIRIGHT 0x04 /**< text object horizontal alignment = right */ +#define ALIHORI 0x07 /**< text object horizontal alignment mask */ +#define ALITOP 0x08 /**< text object vertical alignment = top */ +#define ALIBASE 0x10 /**< text object vertical alignment = baseline */ +#define ALIBOT 0x20 /**< text object vertical alignment = bottom */ +#define ALIVERT 0x38 /**< text object vertical alignment mask */ /** @} */ /** \defgroup language direction types @{ */ -#define LDIR_LR 0x00 /**< left to right */ -#define LDIR_RL 0x01 /**< right to left */ -#define LDIR_TB 0x02 /**< top to bottom */ +#define LDIR_LR 0x00 /**< left to right */ +#define LDIR_RL 0x01 /**< right to left */ +#define LDIR_TB 0x02 /**< top to bottom */ /** @} */ /** \defgroup special processing flags @{ */ -#define TR_EMFBOT 0x01 /**< use an approximation compatible with EMF file's "BOTTOM" text orientation, which is not the "bottom" for Freetype fonts */ +#define TR_EMFBOT \ + 0x01 /**< use an approximation compatible with EMF file's "BOTTOM" text orientation, which is not the "bottom" for \ + Freetype fonts */ /** @} */ /** \enum tr_classes classification of complexes @{ */ -enum tr_classes { - TR_TEXT, /**< simple text object */ - TR_LINE, /**< linear assembly of TR_TEXTs */ - TR_PARA_UJ, /**< sequential assembly of TR_LINEs and TR_TEXTs into a paragraph - - unknown justification properties */ - TR_PARA_LJ, /**< ditto, left justified */ - TR_PARA_CJ, /**< ditto, center justified */ - TR_PARA_RJ /**< ditto, right justified */ - }; +enum tr_classes +{ + TR_TEXT, /**< simple text object */ + TR_LINE, /**< linear assembly of TR_TEXTs */ + TR_PARA_UJ, /**< sequential assembly of TR_LINEs and TR_TEXTs into a paragraph - + unknown justification properties */ + TR_PARA_LJ, /**< ditto, left justified */ + TR_PARA_CJ, /**< ditto, center justified */ + TR_PARA_RJ /**< ditto, right justified */ +}; /** @} */ /** \brief alt font entries. */ -typedef struct { - uint32_t fi_idx; /**< index into FT_INFO fonts, for fonts added for missing glyphs */ - uint32_t weight; /**< integer weight for alt fonts, kept sorted into descending order */ +typedef struct +{ + uint32_t fi_idx; /**< index into FT_INFO fonts, for fonts added for missing glyphs */ + uint32_t weight; /**< integer weight for alt fonts, kept sorted into descending order */ } ALT_SPECS; /** \brief Information for a font instance. */ -typedef struct { - FcFontSet *fontset; /**< all matching fonts (for fallback on missing glyphs) */ - ALT_SPECS *alts; /**< index into FT_INFO fonts, for fonts added for missing glyphs */ - uint32_t space; /**< alts storage slots allocated */ - uint32_t used; /**< alts storage slots in use */ - FT_Face face; /**< font face structures (FT_FACE is a pointer!) */ - uint8_t *file; /**< pointer to font paths to files */ - uint8_t *fontspec; /**< pointer to a font specification (name:italics, etc.) */ - FcPattern *fpat; /**< current font, must hang onto this or faces operations break */ - double spcadv; /**< advance equal to a space, in points at font's face size */ - double fsize; /**< font's face size in points */ +typedef struct +{ + FcFontSet *fontset; /**< all matching fonts (for fallback on missing glyphs) */ + ALT_SPECS *alts; /**< index into FT_INFO fonts, for fonts added for missing glyphs */ + uint32_t space; /**< alts storage slots allocated */ + uint32_t used; /**< alts storage slots in use */ + FT_Face face; /**< font face structures (FT_FACE is a pointer!) */ + uint8_t *file; /**< pointer to font paths to files */ + uint8_t *fontspec; /**< pointer to a font specification (name:italics, etc.) */ + FcPattern *fpat; /**< current font, must hang onto this or faces operations break */ + double spcadv; /**< advance equal to a space, in points at font's face size */ + double fsize; /**< font's face size in points */ } FNT_SPECS; /** \brief Information for all font instances. */ -typedef struct { - FT_Library library; /**< Fontconfig handle */ - FNT_SPECS *fonts; /**< Array of fontinfo structures */ - uint32_t space; /**< storage slots allocated */ - uint32_t used; /**< storage slots in use */ +typedef struct +{ + FT_Library library; /**< Fontconfig handle */ + FNT_SPECS *fonts; /**< Array of fontinfo structures */ + uint32_t space; /**< storage slots allocated */ + uint32_t used; /**< storage slots in use */ } FT_INFO; -typedef struct { - uint8_t Red; //!< Red color (0-255) - uint8_t Green; //!< Green color (0-255) - uint8_t Blue; //!< Blue color (0-255) - uint8_t Reserved; //!< Not used +typedef struct +{ + uint8_t Red; //!< Red color (0-255) + uint8_t Green; //!< Green color (0-255) + uint8_t Blue; //!< Blue color (0-255) + uint8_t Reserved; //!< Not used } TRCOLORREF; /** \brief Information for a single text object */ -typedef struct { - uint8_t *string; /**< UTF-8 text */ - double ori; /**< Orientation, angle of characters with respect to baseline in degrees */ - double fs; /**< font size of text */ - double x; /**< x coordinate, relative to TR_INFO x,y, in points */ - double y; /**< y coordinate, relative to TR_INFO x,y, in points */ - double xkern; /**< x kern relative to preceding text chunk in complex (if any) */ - double ykern; /**< y kern relative to preceding text chunk in complex (if any) */ - double boff; /**< Y LL corner - boff finds baseline */ - double vadvance; /**< Line spacing typically 1.25 or 1.2, only set on the first text - element in a complex */ - TRCOLORREF color; /**< RGB */ - int taln; /**< text alignment with respect to x,y */ - int ldir; /**< language direction LDIR_* */ - int italics; /**< italics, as in FontConfig */ - int weight; /**< weight, as in FontConfig */ - int condensed; /**< condensed, as in FontConfig */ - int decoration; /**< text decorations, ignored during assembly, used during output */ - int spaces; /**< count of spaces converted from wide kerning (1 or 2) */ - TRCOLORREF decColor; /**< text decoration color, ignored during assembly, used during output */ - int co; /**< condensed override, if set Font name included narrow */ - int rt_tidx; /**< index of rectangle that contains it */ - int fi_idx; /**< index of the font it uses */ +typedef struct +{ + uint8_t *string; /**< UTF-8 text */ + double ori; /**< Orientation, angle of characters with respect to baseline in degrees */ + double fs; /**< font size of text */ + double x; /**< x coordinate, relative to TR_INFO x,y, in points */ + double y; /**< y coordinate, relative to TR_INFO x,y, in points */ + double xkern; /**< x kern relative to preceding text chunk in complex (if any) */ + double ykern; /**< y kern relative to preceding text chunk in complex (if any) */ + double boff; /**< Y LL corner - boff finds baseline */ + double vadvance; /**< Line spacing typically 1.25 or 1.2, only set on the first text + element in a complex */ + TRCOLORREF color; /**< RGB */ + int taln; /**< text alignment with respect to x,y */ + int ldir; /**< language direction LDIR_* */ + int italics; /**< italics, as in FontConfig */ + int weight; /**< weight, as in FontConfig */ + int condensed; /**< condensed, as in FontConfig */ + int decoration; /**< text decorations, ignored during assembly, used during output */ + int spaces; /**< count of spaces converted from wide kerning (1 or 2) */ + TRCOLORREF decColor; /**< text decoration color, ignored during assembly, used during output */ + int co; /**< condensed override, if set Font name included narrow */ + int rt_tidx; /**< index of rectangle that contains it */ + int fi_idx; /**< index of the font it uses */ } TCHUNK_SPECS; /** \brief Information for all text objects. Coordinates here are INTERNAL, after offset/rotate using values in TR_INFO. */ -typedef struct { - TCHUNK_SPECS *chunks; /**< text chunks */ - uint32_t space; /**< storage slots allocated */ - uint32_t used; /**< storage slots in use */ +typedef struct +{ + TCHUNK_SPECS *chunks; /**< text chunks */ + uint32_t space; /**< storage slots allocated */ + uint32_t used; /**< storage slots in use */ } TP_INFO; /** \brief Information for a single bounding rectangle. Coordinates here are INTERNAL, after offset/rotate using values in TR_INFO. */ -typedef struct { - double xll; /**< x rectangle lower left corner */ - double yll; /**< y " */ - double xur; /**< x upper right corner */ - double yur; /**< y " */ - double xbearing; /**< x bearing of the leftmost character */ +typedef struct +{ + double xll; /**< x rectangle lower left corner */ + double yll; /**< y " */ + double xur; /**< x upper right corner */ + double yur; /**< y " */ + double xbearing; /**< x bearing of the leftmost character */ } BRECT_SPECS; /** \brief Information for all bounding rectangles. */ -typedef struct { - BRECT_SPECS *rects; /**< bounding rectangles */ - uint32_t space; /**< storage slots allocated */ - uint32_t used; /**< storage slots in use */ +typedef struct +{ + BRECT_SPECS *rects; /**< bounding rectangles */ + uint32_t space; /**< storage slots allocated */ + uint32_t used; /**< storage slots in use */ } BR_INFO; /** \brief List of all members of a single complex. */ -typedef struct { - int *members; /**< array of immediate children (for TR_PARA_* these are indices - for TR_TEXT or TR_LINE complexes also in cxi. For TR_TEXT - and TR_LINE these are indices to the actual text in tpi.) */ - uint32_t space; /**< storage slots allocated */ - uint32_t used; /**< storage slots in use */ +typedef struct +{ + int *members; /**< array of immediate children (for TR_PARA_* these are indices + for TR_TEXT or TR_LINE complexes also in cxi. For TR_TEXT + and TR_LINE these are indices to the actual text in tpi.) */ + uint32_t space; /**< storage slots allocated */ + uint32_t used; /**< storage slots in use */ } CHILD_SPECS; /** - \brief Information for a single complex. + \brief Information for a single complex. */ -typedef struct { - int rt_cidx; /**< index of rectangle that contains all members */ - enum tr_classes type; /**< classification of the complex */ - CHILD_SPECS kids; /**< immediate child nodes of this complex, for type TR_TEXT the - idx refers to the tpi data. otherwise, cxi data */ +typedef struct +{ + int rt_cidx; /**< index of rectangle that contains all members */ + enum tr_classes type; /**< classification of the complex */ + CHILD_SPECS kids; /**< immediate child nodes of this complex, for type TR_TEXT the + idx refers to the tpi data. otherwise, cxi data */ } CX_SPECS; /** \brief Information for all complexes. */ -typedef struct { - CX_SPECS *cx; /**< complexes */ - uint32_t space; /**< storage slots allocated */ - uint32_t used; /**< storage slots in use */ - uint32_t phase1; /**< Number of complexes (lines + text fragments) entered in phase 1 */ - uint32_t lines; /**< Number of lines in phase 1 */ - uint32_t paras; /**< Number of complexes (paras) entered in phase 2 */ +typedef struct +{ + CX_SPECS *cx; /**< complexes */ + uint32_t space; /**< storage slots allocated */ + uint32_t used; /**< storage slots in use */ + uint32_t phase1; /**< Number of complexes (lines + text fragments) entered in phase 1 */ + uint32_t lines; /**< Number of lines in phase 1 */ + uint32_t paras; /**< Number of complexes (paras) entered in phase 2 */ } CX_INFO; /** \brief Information for the entire text reassembly system. */ -typedef struct { - FT_INFO *fti; /**< Font info storage */ - TP_INFO *tpi; /**< Text Info/Position Info storage */ - BR_INFO *bri; /**< Bounding Rectangle Info storage */ - CX_INFO *cxi; /**< Complex Info storage */ - uint8_t *out; /**< buffer to hold formatted output */ - double qe; /**< quantization error in points. */ - double esc; /**< escapement angle in DEGREES */ - double x; /**< x coordinate of first text object, in points */ - double y; /**< y coordinate of first text object, in points */ - int dirty; /**< 1 if text records are loaded */ - int use_kern; /**< 1 if kerning is used, 0 if not */ - int load_flags; /**< FT_LOAD_NO_SCALE or FT_LOAD_TARGET_NORMAL */ - int kern_mode; /**< FT_KERNING_DEFAULT, FT_KERNING_UNFITTED, or FT_KERNING_UNSCALED */ - uint32_t outspace; /**< storage in output buffer allocated */ - uint32_t outused; /**< storage in output buffer in use */ - int usebk; /**< On output write the background color under the text */ - TRCOLORREF bkcolor; /**< RGB background color */ +typedef struct +{ + FT_INFO *fti; /**< Font info storage */ + TP_INFO *tpi; /**< Text Info/Position Info storage */ + BR_INFO *bri; /**< Bounding Rectangle Info storage */ + CX_INFO *cxi; /**< Complex Info storage */ + uint8_t *out; /**< buffer to hold formatted output */ + double qe; /**< quantization error in points. */ + double esc; /**< escapement angle in DEGREES */ + double x; /**< x coordinate of first text object, in points */ + double y; /**< y coordinate of first text object, in points */ + int dirty; /**< 1 if text records are loaded */ + int use_kern; /**< 1 if kerning is used, 0 if not */ + int load_flags; /**< FT_LOAD_NO_SCALE or FT_LOAD_TARGET_NORMAL */ + int kern_mode; /**< FT_KERNING_DEFAULT, FT_KERNING_UNFITTED, or FT_KERNING_UNSCALED */ + uint32_t outspace; /**< storage in output buffer allocated */ + uint32_t outused; /**< storage in output buffer in use */ + int usebk; /**< On output write the background color under the text */ + TRCOLORREF bkcolor; /**< RGB background color */ } TR_INFO; /* padding added to rectangles before overlap test */ /** \brief Information for one padding record. (Padding is added to bounding rectangles before overlap tests.) */ -typedef struct { - double up; /**< to top */ - double down; /**< to bottom */ - double left; /**< to left */ - double right; /**< to right */ +typedef struct +{ + double up; /**< to top */ + double down; /**< to bottom */ + double left; /**< to left */ + double right; /**< to right */ } RT_PAD; /** \cond */ @@ -313,83 +324,82 @@ typedef struct { */ #ifdef SOL8 #define ICONV_CAST (const char **) -#endif //SOL8 +#endif // SOL8 #if !defined(ICONV_CAST) #define ICONV_CAST (char **) -#endif //ICONV_CAST +#endif // ICONV_CAST /** \endcond */ /* Prototypes */ -int TR_findcasesub(const char *string, const char *sub); -char *TR_construct_fontspec(const TCHUNK_SPECS *tsp, const char *fontname); -char *TR_reconstruct_fontspec(const char *fontspec, const char *fontname); -int TR_find_alternate_font(FT_INFO *fti, FNT_SPECS **efsp, uint32_t wc); -int TR_getadvance(FT_INFO *fti, FNT_SPECS *fsp, uint32_t wc, uint32_t pc, int load_flags, int kern_mode, int *ymin, int *ymax); -int TR_getkern2(FNT_SPECS *fsp, uint32_t wc, uint32_t pc, int kern_mode); -int TR_kern_gap(FNT_SPECS *fsp, TCHUNK_SPECS *tsp, TCHUNK_SPECS *ptsp, int kern_mode); -void TR_rt_pad_set(RT_PAD *rt_pad, double up, double down, double left, double right); -double TR_baseline(TR_INFO *tri, int src, double *AscMax, double *DscMax); -int TR_check_set_vadvance(TR_INFO *tri, int src, int lines); -int TR_layout_analyze(TR_INFO *tri); -void TR_layout_2_svg(TR_INFO *tri); -int TR_weight_FC_to_SVG(int weight); - -FT_INFO *ftinfo_init(void); -int ftinfo_make_insertable(FT_INFO *fti); -int ftinfo_insert(FT_INFO *fti, FNT_SPECS *fsp); -FT_INFO *ftinfo_release(FT_INFO *fti); -FT_INFO *ftinfo_clear(FT_INFO *fti); -int ftinfo_find_loaded_by_spec(const FT_INFO *fti, const uint8_t *fname); -int ftinfo_find_loaded_by_src(const FT_INFO *fti, const uint8_t *filename); -int ftinfo_load_fontname(FT_INFO *fti, const char *fontspec); -void ftinfo_dump(const FT_INFO *fti); - -int fsp_alts_make_insertable(FNT_SPECS *fsp); -int fsp_alts_insert(FNT_SPECS *fsp, uint32_t fi_idx); -int fsp_alts_weight(FNT_SPECS *fsp, uint32_t a_idx); - -int csp_make_insertable(CHILD_SPECS *csp); -int csp_insert(CHILD_SPECS *csp, int src); -int csp_merge(CHILD_SPECS *dst, CHILD_SPECS *src); -void csp_release(CHILD_SPECS *csp); -void csp_clear(CHILD_SPECS *csp); - -CX_INFO *cxinfo_init(void); -int cxinfo_make_insertable(CX_INFO *cxi); -int cxinfo_insert(CX_INFO *cxi, int src, int src_rt_idx, enum tr_classes type); -int cxinfo_append(CX_INFO *cxi, int src, enum tr_classes type); -int cxinfo_merge(CX_INFO *cxi, int dst, int src, enum tr_classes type); -int cxinfo_trim(CX_INFO *cxi); -CX_INFO *cxinfo_release(CX_INFO *cxi); -void cxinfo_dump(const TR_INFO *tri); - -TP_INFO *tpinfo_init(void); -int tpinfo_make_insertable(TP_INFO *tpi); -int tpinfo_insert(TP_INFO *tpi, const TCHUNK_SPECS *tsp); -TP_INFO *tpinfo_release(TP_INFO *tpi); - -BR_INFO *brinfo_init(void); -int brinfo_make_insertable(BR_INFO *bri); -int brinfo_insert(BR_INFO *bri, const BRECT_SPECS *element); -int brinfo_merge(BR_INFO *bri, int dst, int src); -enum tr_classes - brinfo_pp_alignment(const BR_INFO *bri, int dst, int src, double slop, enum tr_classes type); -int brinfo_overlap(const BR_INFO *bri, int dst, int src, RT_PAD *rp_dst, RT_PAD *rp_src); -BR_INFO *brinfo_release(BR_INFO *bri); - -TR_INFO *trinfo_init(TR_INFO *tri); -TR_INFO *trinfo_release(TR_INFO *tri); -TR_INFO *trinfo_release_except_FC(TR_INFO *tri); -TR_INFO *trinfo_clear(TR_INFO *tri); -int trinfo_load_qe(TR_INFO *tri, double qe); -int trinfo_load_bk(TR_INFO *tri, int usebk, TRCOLORREF bkcolor); -int trinfo_load_ft_opts(TR_INFO *tri, int use_kern, int load_flags, int kern_mode); -int trinfo_load_textrec(TR_INFO *tri, const TCHUNK_SPECS *tsp, double escapement, int flags); -int trinfo_check_bk(TR_INFO *tri, int usebk, TRCOLORREF bkcolor); -int trinfo_append_out(TR_INFO *tri, const char *src); - -int is_mn_unicode(int test); - +int TR_findcasesub(const char *string, const char *sub); +char *TR_construct_fontspec(const TCHUNK_SPECS *tsp, const char *fontname); +char *TR_reconstruct_fontspec(const char *fontspec, const char *fontname); +int TR_find_alternate_font(FT_INFO *fti, FNT_SPECS **efsp, uint32_t wc); +int TR_getadvance(FT_INFO *fti, FNT_SPECS *fsp, uint32_t wc, uint32_t pc, int load_flags, int kern_mode, int *ymin, + int *ymax); +int TR_getkern2(FNT_SPECS *fsp, uint32_t wc, uint32_t pc, int kern_mode); +int TR_kern_gap(FNT_SPECS *fsp, TCHUNK_SPECS *tsp, TCHUNK_SPECS *ptsp, int kern_mode); +void TR_rt_pad_set(RT_PAD *rt_pad, double up, double down, double left, double right); +double TR_baseline(TR_INFO *tri, int src, double *AscMax, double *DscMax); +int TR_check_set_vadvance(TR_INFO *tri, int src, int lines); +int TR_layout_analyze(TR_INFO *tri); +void TR_layout_2_svg(TR_INFO *tri); +int TR_weight_FC_to_SVG(int weight); + +FT_INFO *ftinfo_init(void); +int ftinfo_make_insertable(FT_INFO *fti); +int ftinfo_insert(FT_INFO *fti, FNT_SPECS *fsp); +FT_INFO *ftinfo_release(FT_INFO *fti); +FT_INFO *ftinfo_clear(FT_INFO *fti); +int ftinfo_find_loaded_by_spec(const FT_INFO *fti, const uint8_t *fname); +int ftinfo_find_loaded_by_src(const FT_INFO *fti, const uint8_t *filename); +int ftinfo_load_fontname(FT_INFO *fti, const char *fontspec); +void ftinfo_dump(const FT_INFO *fti); + +int fsp_alts_make_insertable(FNT_SPECS *fsp); +int fsp_alts_insert(FNT_SPECS *fsp, uint32_t fi_idx); +int fsp_alts_weight(FNT_SPECS *fsp, uint32_t a_idx); + +int csp_make_insertable(CHILD_SPECS *csp); +int csp_insert(CHILD_SPECS *csp, int src); +int csp_merge(CHILD_SPECS *dst, CHILD_SPECS *src); +void csp_release(CHILD_SPECS *csp); +void csp_clear(CHILD_SPECS *csp); + +CX_INFO *cxinfo_init(void); +int cxinfo_make_insertable(CX_INFO *cxi); +int cxinfo_insert(CX_INFO *cxi, int src, int src_rt_idx, enum tr_classes type); +int cxinfo_append(CX_INFO *cxi, int src, enum tr_classes type); +int cxinfo_merge(CX_INFO *cxi, int dst, int src, enum tr_classes type); +int cxinfo_trim(CX_INFO *cxi); +CX_INFO *cxinfo_release(CX_INFO *cxi); +void cxinfo_dump(const TR_INFO *tri); + +TP_INFO *tpinfo_init(void); +int tpinfo_make_insertable(TP_INFO *tpi); +int tpinfo_insert(TP_INFO *tpi, const TCHUNK_SPECS *tsp); +TP_INFO *tpinfo_release(TP_INFO *tpi); + +BR_INFO *brinfo_init(void); +int brinfo_make_insertable(BR_INFO *bri); +int brinfo_insert(BR_INFO *bri, const BRECT_SPECS *element); +int brinfo_merge(BR_INFO *bri, int dst, int src); +enum tr_classes brinfo_pp_alignment(const BR_INFO *bri, int dst, int src, double slop, enum tr_classes type); +int brinfo_overlap(const BR_INFO *bri, int dst, int src, RT_PAD *rp_dst, RT_PAD *rp_src); +BR_INFO *brinfo_release(BR_INFO *bri); + +TR_INFO *trinfo_init(TR_INFO *tri); +TR_INFO *trinfo_release(TR_INFO *tri); +TR_INFO *trinfo_release_except_FC(TR_INFO *tri); +TR_INFO *trinfo_clear(TR_INFO *tri); +int trinfo_load_qe(TR_INFO *tri, double qe); +int trinfo_load_bk(TR_INFO *tri, int usebk, TRCOLORREF bkcolor); +int trinfo_load_ft_opts(TR_INFO *tri, int use_kern, int load_flags, int kern_mode); +int trinfo_load_textrec(TR_INFO *tri, const TCHUNK_SPECS *tsp, double escapement, int flags); +int trinfo_check_bk(TR_INFO *tri, int usebk, TRCOLORREF bkcolor); +int trinfo_append_out(TR_INFO *tri, const char *src); + +int is_mn_unicode(int test); #ifdef __cplusplus } diff --git a/src/extension/internal/vsd-input.cpp b/src/extension/internal/vsd-input.cpp index 4679ccef8a0f571b9b193a8229d173710ff20684..568f6ff0e772f292f692462870a907d24704caa8 100644 --- a/src/extension/internal/vsd-input.cpp +++ b/src/extension/internal/vsd-input.cpp @@ -15,7 +15,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include @@ -24,78 +24,72 @@ #ifdef WITH_LIBVISIO -#include #include - #include +#include // TODO: Drop this check when librevenge is widespread. #if WITH_LIBVISIO01 - #include +#include - using librevenge::RVNGString; - using librevenge::RVNGFileStream; - using librevenge::RVNGStringVector; +using librevenge::RVNGFileStream; +using librevenge::RVNGString; +using librevenge::RVNGStringVector; #else - #include +#include - typedef WPXString RVNGString; - typedef WPXFileStream RVNGFileStream; - typedef libvisio::VSDStringVector RVNGStringVector; +typedef WPXString RVNGString; +typedef WPXFileStream RVNGFileStream; +typedef libvisio::VSDStringVector RVNGStringVector; #endif +#include #include -#include "extension/system.h" -#include "extension/input.h" - #include "document.h" +#include "extension/input.h" +#include "extension/system.h" #include "inkscape.h" - +#include "object/sp-root.h" #include "ui/dialog-events.h" -#include - #include "ui/view/svg-view-widget.h" - -#include "object/sp-root.h" - #include "util/units.h" namespace Inkscape { namespace Extension { namespace Internal { - -class VsdImportDialog : public Gtk::Dialog { +class VsdImportDialog : public Gtk::Dialog +{ public: - VsdImportDialog(const std::vector &vec); - ~VsdImportDialog() override; + VsdImportDialog(const std::vector &vec); + ~VsdImportDialog() override; - bool showDialog(); - unsigned getSelectedPage(); - void getImportSettings(Inkscape::XML::Node *prefs); + bool showDialog(); + unsigned getSelectedPage(); + void getImportSettings(Inkscape::XML::Node *prefs); private: - void _setPreviewPage(); - - // Signal handlers - void _onPageNumberChanged(); - void _onSpinButtonPress(GdkEventButton* button_event); - void _onSpinButtonRelease(GdkEventButton* button_event); - - class Gtk::VBox * vbox1; - class Inkscape::UI::View::SVGViewWidget * _previewArea; - class Gtk::Button * cancelbutton; - class Gtk::Button * okbutton; - - class Gtk::HBox * _page_selector_box; - class Gtk::Label * _labelSelect; - class Gtk::Label * _labelTotalPages; - class Gtk::SpinButton * _pageNumberSpin; - - const std::vector &_vec; // Document to be imported - unsigned _current_page; // Current selected page - bool _spinning; // whether SpinButton is pressed (i.e. we're "spinning") + void _setPreviewPage(); + + // Signal handlers + void _onPageNumberChanged(); + void _onSpinButtonPress(GdkEventButton *button_event); + void _onSpinButtonRelease(GdkEventButton *button_event); + + class Gtk::VBox *vbox1; + class Inkscape::UI::View::SVGViewWidget *_previewArea; + class Gtk::Button *cancelbutton; + class Gtk::Button *okbutton; + + class Gtk::HBox *_page_selector_box; + class Gtk::Label *_labelSelect; + class Gtk::Label *_labelTotalPages; + class Gtk::SpinButton *_pageNumberSpin; + + const std::vector &_vec; // Document to be imported + unsigned _current_page; // Current selected page + bool _spinning; // whether SpinButton is pressed (i.e. we're "spinning") }; VsdImportDialog::VsdImportDialog(const std::vector &vec) @@ -104,105 +98,106 @@ VsdImportDialog::VsdImportDialog(const std::vector &vec) , _current_page(1) , _spinning(false) { - int num_pages = _vec.size(); - if ( num_pages <= 1 ) - return; - - - // Dialog settings - this->set_title(_("Page Selector")); - this->set_modal(true); - sp_transientize(GTK_WIDGET(this->gobj())); //Make transient - this->property_window_position().set_value(Gtk::WIN_POS_NONE); - this->set_resizable(true); - this->property_destroy_with_parent().set_value(false); - - // Preview area - vbox1 = Gtk::manage(new class Gtk::VBox()); - this->get_content_area()->pack_start(*vbox1); - - // CONTROLS - _page_selector_box = Gtk::manage(new Gtk::HBox()); - - // Labels - _labelSelect = Gtk::manage(new class Gtk::Label(_("Select page:"))); - _labelTotalPages = Gtk::manage(new class Gtk::Label()); - _labelSelect->set_line_wrap(false); - _labelSelect->set_use_markup(false); - _labelSelect->set_selectable(false); - _page_selector_box->pack_start(*_labelSelect, Gtk::PACK_SHRINK); - - // Adjustment + spinner - auto _pageNumberSpin_adj = Gtk::Adjustment::create(1, 1, _vec.size(), 1, 10, 0); - _pageNumberSpin = Gtk::manage(new Gtk::SpinButton(_pageNumberSpin_adj, 1, 0)); - _pageNumberSpin->set_can_focus(); - _pageNumberSpin->set_update_policy(Gtk::UPDATE_ALWAYS); - _pageNumberSpin->set_numeric(true); - _pageNumberSpin->set_wrap(false); - _page_selector_box->pack_start(*_pageNumberSpin, Gtk::PACK_SHRINK); - - _labelTotalPages->set_line_wrap(false); - _labelTotalPages->set_use_markup(false); - _labelTotalPages->set_selectable(false); - gchar *label_text = g_strdup_printf(_("out of %i"), num_pages); - _labelTotalPages->set_label(label_text); - g_free(label_text); - _page_selector_box->pack_start(*_labelTotalPages, Gtk::PACK_SHRINK); - - vbox1->pack_end(*_page_selector_box, Gtk::PACK_SHRINK); - - // Buttons - cancelbutton = Gtk::manage(new Gtk::Button(_("_Cancel"), true)); - okbutton = Gtk::manage(new Gtk::Button(_("_OK"), true)); - this->add_action_widget(*cancelbutton, Gtk::RESPONSE_CANCEL); - this->add_action_widget(*okbutton, Gtk::RESPONSE_OK); - - // Show all widgets in dialog - this->show_all(); - - // Connect signals - _pageNumberSpin->signal_value_changed().connect(sigc::mem_fun(*this, &VsdImportDialog::_onPageNumberChanged)); - _pageNumberSpin->signal_button_press_event().connect_notify(sigc::mem_fun(*this, &VsdImportDialog::_onSpinButtonPress)); - _pageNumberSpin->signal_button_release_event().connect_notify(sigc::mem_fun(*this, &VsdImportDialog::_onSpinButtonRelease)); - - _setPreviewPage(); + int num_pages = _vec.size(); + if (num_pages <= 1) + return; + + // Dialog settings + this->set_title(_("Page Selector")); + this->set_modal(true); + sp_transientize(GTK_WIDGET(this->gobj())); // Make transient + this->property_window_position().set_value(Gtk::WIN_POS_NONE); + this->set_resizable(true); + this->property_destroy_with_parent().set_value(false); + + // Preview area + vbox1 = Gtk::manage(new class Gtk::VBox()); + this->get_content_area()->pack_start(*vbox1); + + // CONTROLS + _page_selector_box = Gtk::manage(new Gtk::HBox()); + + // Labels + _labelSelect = Gtk::manage(new class Gtk::Label(_("Select page:"))); + _labelTotalPages = Gtk::manage(new class Gtk::Label()); + _labelSelect->set_line_wrap(false); + _labelSelect->set_use_markup(false); + _labelSelect->set_selectable(false); + _page_selector_box->pack_start(*_labelSelect, Gtk::PACK_SHRINK); + + // Adjustment + spinner + auto _pageNumberSpin_adj = Gtk::Adjustment::create(1, 1, _vec.size(), 1, 10, 0); + _pageNumberSpin = Gtk::manage(new Gtk::SpinButton(_pageNumberSpin_adj, 1, 0)); + _pageNumberSpin->set_can_focus(); + _pageNumberSpin->set_update_policy(Gtk::UPDATE_ALWAYS); + _pageNumberSpin->set_numeric(true); + _pageNumberSpin->set_wrap(false); + _page_selector_box->pack_start(*_pageNumberSpin, Gtk::PACK_SHRINK); + + _labelTotalPages->set_line_wrap(false); + _labelTotalPages->set_use_markup(false); + _labelTotalPages->set_selectable(false); + gchar *label_text = g_strdup_printf(_("out of %i"), num_pages); + _labelTotalPages->set_label(label_text); + g_free(label_text); + _page_selector_box->pack_start(*_labelTotalPages, Gtk::PACK_SHRINK); + + vbox1->pack_end(*_page_selector_box, Gtk::PACK_SHRINK); + + // Buttons + cancelbutton = Gtk::manage(new Gtk::Button(_("_Cancel"), true)); + okbutton = Gtk::manage(new Gtk::Button(_("_OK"), true)); + this->add_action_widget(*cancelbutton, Gtk::RESPONSE_CANCEL); + this->add_action_widget(*okbutton, Gtk::RESPONSE_OK); + + // Show all widgets in dialog + this->show_all(); + + // Connect signals + _pageNumberSpin->signal_value_changed().connect(sigc::mem_fun(*this, &VsdImportDialog::_onPageNumberChanged)); + _pageNumberSpin->signal_button_press_event().connect_notify( + sigc::mem_fun(*this, &VsdImportDialog::_onSpinButtonPress)); + _pageNumberSpin->signal_button_release_event().connect_notify( + sigc::mem_fun(*this, &VsdImportDialog::_onSpinButtonRelease)); + + _setPreviewPage(); } VsdImportDialog::~VsdImportDialog() = default; bool VsdImportDialog::showDialog() { - show(); - gint b = run(); - hide(); - if (b == Gtk::RESPONSE_OK || b == Gtk::RESPONSE_ACCEPT) { - return TRUE; - } else { - return FALSE; - } + show(); + gint b = run(); + hide(); + if (b == Gtk::RESPONSE_OK || b == Gtk::RESPONSE_ACCEPT) { + return TRUE; + } else { + return FALSE; + } } unsigned VsdImportDialog::getSelectedPage() { - return _current_page; + return _current_page; } void VsdImportDialog::_onPageNumberChanged() { - unsigned page = static_cast(_pageNumberSpin->get_value_as_int()); - _current_page = CLAMP(page, 1U, _vec.size()); - _setPreviewPage(); + unsigned page = static_cast(_pageNumberSpin->get_value_as_int()); + _current_page = CLAMP(page, 1U, _vec.size()); + _setPreviewPage(); } -void VsdImportDialog::_onSpinButtonPress(GdkEventButton* /*button_event*/) +void VsdImportDialog::_onSpinButtonPress(GdkEventButton * /*button_event*/) { - _spinning = true; + _spinning = true; } -void VsdImportDialog::_onSpinButtonRelease(GdkEventButton* /*button_event*/) +void VsdImportDialog::_onSpinButtonRelease(GdkEventButton * /*button_event*/) { - _spinning = false; - _setPreviewPage(); + _spinning = false; + _setPreviewPage(); } /** @@ -214,8 +209,9 @@ void VsdImportDialog::_setPreviewPage() return; } - SPDocument *doc = SPDocument::createNewDocFromMem(_vec[_current_page-1].cstr(), strlen(_vec[_current_page-1].cstr()), false); - if(!doc) { + SPDocument *doc = + SPDocument::createNewDocFromMem(_vec[_current_page - 1].cstr(), strlen(_vec[_current_page - 1].cstr()), false); + if (!doc) { g_warning("VSD import: Could not create preview for page %d", _current_page); gchar const *no_preview_template = R"A( @@ -224,7 +220,7 @@ void VsdImportDialog::_setPreviewPage() %s )A"; - gchar * no_preview = g_strdup_printf(no_preview_template, _("No preview")); + gchar *no_preview = g_strdup_printf(no_preview_template, _("No preview")); doc = SPDocument::createNewDocFromMem(no_preview, strlen(no_preview), false); g_free(no_preview); } @@ -245,75 +241,78 @@ void VsdImportDialog::_setPreviewPage() _previewArea->show_all(); } -SPDocument *VsdInput::open(Inkscape::Extension::Input * /*mod*/, const gchar * uri) +SPDocument *VsdInput::open(Inkscape::Extension::Input * /*mod*/, const gchar *uri) { - #ifdef _WIN32 - // RVNGFileStream uses fopen() internally which unfortunately only uses ANSI encoding on Windows - // therefore attempt to convert uri to the system codepage - // even if this is not possible the alternate short (8.3) file name will be used if available - gchar * converted_uri = g_win32_locale_filename_from_utf8(uri); - RVNGFileStream input(converted_uri); - g_free(converted_uri); - #else - RVNGFileStream input(uri); - #endif - - if (!libvisio::VisioDocument::isSupported(&input)) { - return nullptr; - } - - RVNGStringVector output; +#ifdef _WIN32 + // RVNGFileStream uses fopen() internally which unfortunately only uses ANSI encoding on Windows + // therefore attempt to convert uri to the system codepage + // even if this is not possible the alternate short (8.3) file name will be used if available + gchar *converted_uri = g_win32_locale_filename_from_utf8(uri); + RVNGFileStream input(converted_uri); + g_free(converted_uri); +#else + RVNGFileStream input(uri); +#endif + + if (!libvisio::VisioDocument::isSupported(&input)) { + return nullptr; + } + + RVNGStringVector output; #if WITH_LIBVISIO01 - librevenge::RVNGSVGDrawingGenerator generator(output, "svg"); + librevenge::RVNGSVGDrawingGenerator generator(output, "svg"); - if (!libvisio::VisioDocument::parse(&input, &generator)) { + if (!libvisio::VisioDocument::parse(&input, &generator)) { #else - if (!libvisio::VisioDocument::generateSVG(&input, output)) { + if (!libvisio::VisioDocument::generateSVG(&input, output)) { #endif - return nullptr; - } - - if (output.empty()) { - return nullptr; - } - - std::vector tmpSVGOutput; - for (unsigned i=0; i\n\n"); - tmpString.append(output[i]); - tmpSVGOutput.push_back(tmpString); - } - - unsigned page_num = 1; - - // If only one page is present, import that one without bothering user - if (tmpSVGOutput.size() > 1) { - VsdImportDialog *dlg = nullptr; - if (INKSCAPE.use_gui()) { - dlg = new VsdImportDialog(tmpSVGOutput); - if (!dlg->showDialog()) { - delete dlg; - throw Input::open_cancelled(); - } - } - - // Get needed page - if (dlg) { - page_num = dlg->getSelectedPage(); - if (page_num < 1) - page_num = 1; - if (page_num > tmpSVGOutput.size()) - page_num = tmpSVGOutput.size(); - } - } - - SPDocument * doc = SPDocument::createNewDocFromMem(tmpSVGOutput[page_num-1].cstr(), strlen(tmpSVGOutput[page_num-1].cstr()), TRUE); - - // Set viewBox if it doesn't exist - if (doc && !doc->getRoot()->viewBox_set) { - doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), doc->getHeight().value(doc->getDisplayUnit()))); - } - return doc; + return nullptr; + } + + if (output.empty()) { + return nullptr; + } + + std::vector tmpSVGOutput; + for (unsigned i = 0; i < output.size(); ++i) { + RVNGString tmpString("\n\n"); + tmpString.append(output[i]); + tmpSVGOutput.push_back(tmpString); + } + + unsigned page_num = 1; + + // If only one page is present, import that one without bothering user + if (tmpSVGOutput.size() > 1) { + VsdImportDialog *dlg = nullptr; + if (INKSCAPE.use_gui()) { + dlg = new VsdImportDialog(tmpSVGOutput); + if (!dlg->showDialog()) { + delete dlg; + throw Input::open_cancelled(); + } + } + + // Get needed page + if (dlg) { + page_num = dlg->getSelectedPage(); + if (page_num < 1) + page_num = 1; + if (page_num > tmpSVGOutput.size()) + page_num = tmpSVGOutput.size(); + } + } + + SPDocument *doc = SPDocument::createNewDocFromMem(tmpSVGOutput[page_num - 1].cstr(), + strlen(tmpSVGOutput[page_num - 1].cstr()), TRUE); + + // Set viewBox if it doesn't exist + if (doc && !doc->getRoot()->viewBox_set) { + doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), + doc->getHeight().value(doc->getDisplayUnit()))); + } + return doc; } #include "clear-n_.h" @@ -374,11 +373,13 @@ void VsdInput::init() "", new VsdInput()); // clang-format on - return; + return; } // init -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* WITH_LIBVISIO */ /* diff --git a/src/extension/internal/vsd-input.h b/src/extension/internal/vsd-input.h index f30c905f6790300e5e93ed5c05116534ed6ae8ac..8fb871d03fe864e0ea5f413d6e870283cfa682f3 100644 --- a/src/extension/internal/vsd-input.h +++ b/src/extension/internal/vsd-input.h @@ -15,7 +15,7 @@ #define __EXTENSION_INTERNAL_VSDOUTPUT_H__ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef WITH_LIBVISIO @@ -28,21 +28,23 @@ namespace Inkscape { namespace Extension { namespace Internal { -class VsdInput : public Inkscape::Extension::Implementation::Implementation { - VsdInput () = default;; -public: - SPDocument *open( Inkscape::Extension::Input *mod, - const gchar *uri ) override; - static void init( ); +class VsdInput : public Inkscape::Extension::Implementation::Implementation +{ + VsdInput() = default; + ; +public: + SPDocument *open(Inkscape::Extension::Input *mod, const gchar *uri) override; + static void init(); }; -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* WITH_LIBVISIO */ #endif /* __EXTENSION_INTERNAL_VSDOUTPUT_H__ */ - /* Local Variables: mode:c++ diff --git a/src/extension/internal/wmf-inout.cpp b/src/extension/internal/wmf-inout.cpp index 3b68c3abd9f1a4dee2479b3bf630ab6527567ea2..cec80f6488e68c1636a7d59032f06aad53ca41ea 100644 --- a/src/extension/internal/wmf-inout.cpp +++ b/src/extension/internal/wmf-inout.cpp @@ -24,69 +24,62 @@ */ //#include //This must precede text_reassemble.h or it blows up in pngconf.h when compiling +#include "wmf-inout.h" + +#include <3rdparty/libuemf/symbol_convert.h> +#include #include #include -#include -#include <3rdparty/libuemf/symbol_convert.h> +#include "clear-n_.h" +#include "display/drawing-item.h" +#include "display/drawing.h" #include "document.h" -#include "object/sp-root.h" // even though it is included indirectly by wmf-inout.h -#include "object/sp-path.h" -#include "print.h" -#include "extension/system.h" -#include "extension/print.h" #include "extension/db.h" #include "extension/input.h" #include "extension/output.h" -#include "display/drawing.h" -#include "display/drawing-item.h" -#include "clear-n_.h" +#include "extension/print.h" +#include "extension/system.h" +#include "inkscape.h" // even though it is included indirectly by wmf-inout.h +#include "object/sp-path.h" +#include "object/sp-root.h" // even though it is included indirectly by wmf-inout.h #include "path/path-boolop.h" +#include "print.h" #include "svg/svg.h" #include "util/units.h" // even though it is included indirectly by wmf-inout.h -#include "inkscape.h" // even though it is included indirectly by wmf-inout.h - - -#include "wmf-inout.h" #include "wmf-print.h" #define PRINT_WMF "org.inkscape.print.wmf" #ifndef U_PS_JOIN_MASK -#define U_PS_JOIN_MASK (U_PS_JOIN_BEVEL|U_PS_JOIN_MITER|U_PS_JOIN_ROUND) +#define U_PS_JOIN_MASK (U_PS_JOIN_BEVEL | U_PS_JOIN_MITER | U_PS_JOIN_ROUND) #endif namespace Inkscape { namespace Extension { namespace Internal { - static bool clipset = false; -static uint32_t BLTmode=0; +static uint32_t BLTmode = 0; -Wmf::Wmf () // The null constructor +Wmf::Wmf() // The null constructor { return; } - -Wmf::~Wmf () //The destructor +Wmf::~Wmf() // The destructor { return; } - -bool -Wmf::check (Inkscape::Extension::Extension * /*module*/) +bool Wmf::check(Inkscape::Extension::Extension * /*module*/) { if (nullptr == Inkscape::Extension::db.get(PRINT_WMF)) return FALSE; return TRUE; } - -void -Wmf::print_document_to_file(SPDocument *doc, const gchar *filename) +void Wmf::print_document_to_file(SPDocument *doc, const gchar *filename) { Inkscape::Extension::Print *mod; SPPrintContext context; @@ -100,7 +93,7 @@ Wmf::print_document_to_file(SPDocument *doc, const gchar *filename) oldoutput = g_strdup(oldconst); mod->set_param_string("destination", filename); -/* Start */ + /* Start */ context.module = mod; /* fixme: This has to go into module constructor somehow */ /* Create new arena */ @@ -123,7 +116,7 @@ Wmf::print_document_to_file(SPDocument *doc, const gchar *filename) mod->base->invoke_hide(mod->dkey); mod->base = nullptr; mod->root = nullptr; // deleted by invoke_hide -/* end */ + /* end */ mod->set_param_string("destination", oldoutput); g_free(oldoutput); @@ -131,34 +124,31 @@ Wmf::print_document_to_file(SPDocument *doc, const gchar *filename) return; } - -void -Wmf::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) +void Wmf::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) { - Inkscape::Extension::Extension * ext; + Inkscape::Extension::Extension *ext; ext = Inkscape::Extension::db.get(PRINT_WMF); if (ext == nullptr) return; - bool new_val = mod->get_param_bool("textToPath"); - bool new_FixPPTCharPos = mod->get_param_bool("FixPPTCharPos"); // character position bug + bool new_val = mod->get_param_bool("textToPath"); + bool new_FixPPTCharPos = mod->get_param_bool("FixPPTCharPos"); // character position bug // reserve FixPPT2 for opacity bug. Currently WMF does not export opacity values - bool new_FixPPTDashLine = mod->get_param_bool("FixPPTDashLine"); // dashed line bug - bool new_FixPPTGrad2Polys = mod->get_param_bool("FixPPTGrad2Polys"); // gradient bug - bool new_FixPPTPatternAsHatch = mod->get_param_bool("FixPPTPatternAsHatch"); // force all patterns as standard WMF hatch - - TableGen( //possibly regenerate the unicode-convert tables - mod->get_param_bool("TnrToSymbol"), - mod->get_param_bool("TnrToWingdings"), - mod->get_param_bool("TnrToZapfDingbats"), - mod->get_param_bool("UsePUA") - ); - - ext->set_param_bool("FixPPTCharPos",new_FixPPTCharPos); // Remember to add any new ones to PrintWmf::init or a mysterious failure will result! - ext->set_param_bool("FixPPTDashLine",new_FixPPTDashLine); - ext->set_param_bool("FixPPTGrad2Polys",new_FixPPTGrad2Polys); - ext->set_param_bool("FixPPTPatternAsHatch",new_FixPPTPatternAsHatch); + bool new_FixPPTDashLine = mod->get_param_bool("FixPPTDashLine"); // dashed line bug + bool new_FixPPTGrad2Polys = mod->get_param_bool("FixPPTGrad2Polys"); // gradient bug + bool new_FixPPTPatternAsHatch = + mod->get_param_bool("FixPPTPatternAsHatch"); // force all patterns as standard WMF hatch + + TableGen( // possibly regenerate the unicode-convert tables + mod->get_param_bool("TnrToSymbol"), mod->get_param_bool("TnrToWingdings"), + mod->get_param_bool("TnrToZapfDingbats"), mod->get_param_bool("UsePUA")); + + ext->set_param_bool("FixPPTCharPos", new_FixPPTCharPos); // Remember to add any new ones to PrintWmf::init or a + // mysterious failure will result! + ext->set_param_bool("FixPPTDashLine", new_FixPPTDashLine); + ext->set_param_bool("FixPPTGrad2Polys", new_FixPPTGrad2Polys); + ext->set_param_bool("FixPPTPatternAsHatch", new_FixPPTPatternAsHatch); ext->set_param_bool("textToPath", new_val); // ensure usage of dot as decimal separator in scanf/printf functions (independently of current locale) @@ -174,57 +164,71 @@ Wmf::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filena return; } - /* WMF has no worldTransform, so this always returns 1.0. Retain it to keep WMF and WMF in sync as much as possible.*/ -double Wmf::current_scale(PWMF_CALLBACK_DATA /*d*/){ +double Wmf::current_scale(PWMF_CALLBACK_DATA /*d*/) +{ return 1.0; } /* WMF has no worldTransform, so this always returns an Identity rotation matrix, but the offsets may have values.*/ -std::string Wmf::current_matrix(PWMF_CALLBACK_DATA d, double x, double y, int useoffset){ +std::string Wmf::current_matrix(PWMF_CALLBACK_DATA d, double x, double y, int useoffset) +{ SVGOStringStream cxform; double scale = current_scale(d); cxform << "\"matrix("; - cxform << 1.0/scale; cxform << ","; - cxform << 0.0; cxform << ","; - cxform << 0.0; cxform << ","; - cxform << 1.0/scale; cxform << ","; - if(useoffset){ cxform << x; cxform << ","; cxform << y; } - else { cxform << "0,0"; } + cxform << 1.0 / scale; + cxform << ","; + cxform << 0.0; + cxform << ","; + cxform << 0.0; + cxform << ","; + cxform << 1.0 / scale; + cxform << ","; + if (useoffset) { + cxform << x; + cxform << ","; + cxform << y; + } else { + cxform << "0,0"; + } cxform << ")\""; - return(cxform.str()); + return (cxform.str()); } /* WMF has no worldTransform, so this always returns 0. Retain it to keep WMF and WMF in sync as much as possible.*/ -double Wmf::current_rotation(PWMF_CALLBACK_DATA /*d*/){ +double Wmf::current_rotation(PWMF_CALLBACK_DATA /*d*/) +{ return 0.0; } /* Add another 100 blank slots to the hatches array. -*/ -void Wmf::enlarge_hatches(PWMF_CALLBACK_DATA d){ + */ +void Wmf::enlarge_hatches(PWMF_CALLBACK_DATA d) +{ d->hatches.size += 100; - d->hatches.strings = (char **) realloc(d->hatches.strings,d->hatches.size * sizeof(char *)); + d->hatches.strings = (char **)realloc(d->hatches.strings, d->hatches.size * sizeof(char *)); } /* See if the pattern name is already in the list. If it is return its position (1->n, not 1-n-1) -*/ -int Wmf::in_hatches(PWMF_CALLBACK_DATA d, char *test){ + */ +int Wmf::in_hatches(PWMF_CALLBACK_DATA d, char *test) +{ int i; - for(i=0; ihatches.count; i++){ - if(strcmp(test,d->hatches.strings[i])==0)return(i+1); + for (i = 0; i < d->hatches.count; i++) { + if (strcmp(test, d->hatches.strings[i]) == 0) + return (i + 1); } - return(0); + return (0); } class TagEmitter { public: - TagEmitter(Glib::ustring & p_defs, char * p_tmpcolor, char * p_hpathname): - defs(p_defs), tmpcolor(p_tmpcolor), hpathname(p_hpathname) - { - }; - void append(const char *prefix, const char * inner) + TagEmitter(Glib::ustring &p_defs, char *p_tmpcolor, char *p_hpathname) + : defs(p_defs) + , tmpcolor(p_tmpcolor) + , hpathname(p_hpathname){}; + void append(const char *prefix, const char *inner) { defs += " "; defs += prefix; @@ -235,15 +239,16 @@ public: } protected: - Glib::ustring & defs; - char * tmpcolor, * hpathname; + Glib::ustring &defs; + char *tmpcolor, *hpathname; }; /* (Conditionally) add a hatch. If a matching hatch already exists nothing happens. If one does not exist it is added to the hatches list and also entered into . This is also used to add the path part of the hatches, which they reference with a xlink:href */ -uint32_t Wmf::add_hatch(PWMF_CALLBACK_DATA d, uint32_t hatchType, U_COLORREF hatchColor){ +uint32_t Wmf::add_hatch(PWMF_CALLBACK_DATA d, uint32_t hatchType, U_COLORREF hatchColor) +{ char hatchname[64]; // big enough char hpathname[64]; // big enough char hbkname[64]; // big enough @@ -251,59 +256,54 @@ uint32_t Wmf::add_hatch(PWMF_CALLBACK_DATA d, uint32_t hatchType, U_COLORREF hat char bkcolor[8]; uint32_t idx; - switch(hatchType){ + switch (hatchType) { case U_HS_SOLIDTEXTCLR: case U_HS_DITHEREDTEXTCLR: - sprintf(tmpcolor,"%6.6X",sethexcolor(d->dc[d->level].textColor)); + sprintf(tmpcolor, "%6.6X", sethexcolor(d->dc[d->level].textColor)); break; case U_HS_SOLIDBKCLR: case U_HS_DITHEREDBKCLR: - sprintf(tmpcolor,"%6.6X",sethexcolor(d->dc[d->level].bkColor)); + sprintf(tmpcolor, "%6.6X", sethexcolor(d->dc[d->level].bkColor)); break; default: - sprintf(tmpcolor,"%6.6X",sethexcolor(hatchColor)); + sprintf(tmpcolor, "%6.6X", sethexcolor(hatchColor)); break; } - auto & defs = d->defs; + auto &defs = d->defs; TagEmitter a(defs, tmpcolor, hpathname); /* For both bkMode types set the PATH + FOREGROUND COLOR for the indicated standard hatch. This will be used late to compose, or recompose the transparent or opaque final hatch.*/ std::string refpath; // used to reference later the path pieces which are about to be created - sprintf(hpathname,"WMFhpath%d_%s",hatchType,tmpcolor); - idx = in_hatches(d,hpathname); - if(!idx){ // add path/color if not already present - if(d->hatches.count == d->hatches.size){ enlarge_hatches(d); } - d->hatches.strings[d->hatches.count++]=strdup(hpathname); + sprintf(hpathname, "WMFhpath%d_%s", hatchType, tmpcolor); + idx = in_hatches(d, hpathname); + if (!idx) { // add path/color if not already present + if (d->hatches.count == d->hatches.size) { + enlarge_hatches(d); + } + d->hatches.strings[d->hatches.count++] = strdup(hpathname); defs += "\n"; - switch(hatchType){ + switch (hatchType) { case U_HS_HORIZONTAL: - a.append("\n"; + refpath += " \n"; break; case U_HS_FDIAGONAL: case U_HS_BDIAGONAL: - refpath += " \n"; - refpath += " \n"; - refpath += " \n"; + refpath += " \n"; + refpath += " \n"; + refpath += " \n"; break; case U_HS_DIAGCROSS: - refpath += " \n"; - refpath += " \n"; - refpath += " \n"; - refpath += " \n"; - refpath += " \n"; - refpath += " \n"; - break; - } - - if(d->dc[d->level].bkMode == U_TRANSPARENT || hatchType >= U_HS_SOLIDCLR){ - sprintf(hatchname,"WMFhatch%d_%s",hatchType,tmpcolor); - sprintf(hpathname,"WMFhpath%d_%s",hatchType,tmpcolor); - idx = in_hatches(d,hatchname); - if(!idx){ // add it if not already present - if(d->hatches.count == d->hatches.size){ enlarge_hatches(d); } - d->hatches.strings[d->hatches.count++]=strdup(hatchname); + refpath += " \n"; + refpath += " \n"; + refpath += " \n"; + refpath += " \n"; + refpath += " \n"; + refpath += " \n"; + break; + } + + if (d->dc[d->level].bkMode == U_TRANSPARENT || hatchType >= U_HS_SOLIDCLR) { + sprintf(hatchname, "WMFhatch%d_%s", hatchType, tmpcolor); + sprintf(hpathname, "WMFhpath%d_%s", hatchType, tmpcolor); + idx = in_hatches(d, hatchname); + if (!idx) { // add it if not already present + if (d->hatches.count == d->hatches.size) { + enlarge_hatches(d); + } + d->hatches.strings[d->hatches.count++] = strdup(hatchname); defs += "\n"; defs += " hatches.count; } - } - else { // bkMode==U_OPAQUE + } else { // bkMode==U_OPAQUE /* Set up an object in the defs for this background, if there is not one already there */ - sprintf(bkcolor,"%6.6X",sethexcolor(d->dc[d->level].bkColor)); - sprintf(hbkname,"WMFhbkclr_%s",bkcolor); - idx = in_hatches(d,hbkname); - if(!idx){ // add path/color if not already present. Hatchtype is not needed in the name. - if(d->hatches.count == d->hatches.size){ enlarge_hatches(d); } - d->hatches.strings[d->hatches.count++]=strdup(hbkname); + sprintf(bkcolor, "%6.6X", sethexcolor(d->dc[d->level].bkColor)); + sprintf(hbkname, "WMFhbkclr_%s", bkcolor); + idx = in_hatches(d, hbkname); + if (!idx) { // add path/color if not already present. Hatchtype is not needed in the name. + if (d->hatches.count == d->hatches.size) { + enlarge_hatches(d); + } + d->hatches.strings[d->hatches.count++] = strdup(hbkname); defs += "\n"; defs += " hatches.count == d->hatches.size){ enlarge_hatches(d); } - d->hatches.strings[d->hatches.count++]=strdup(hatchname); + sprintf(hatchname, "WMFhatch%d_%s_%s", hatchType, tmpcolor, bkcolor); + idx = in_hatches(d, hatchname); + if (!idx) { // add it if not already present + if (d->hatches.count == d->hatches.size) { + enlarge_hatches(d); + } + d->hatches.strings[d->hatches.count++] = strdup(hatchname); defs += "\n"; defs += " hatches.count; } } - return(idx-1); + return (idx - 1); } /* Add another 100 blank slots to the images array. -*/ -void Wmf::enlarge_images(PWMF_CALLBACK_DATA d){ + */ +void Wmf::enlarge_images(PWMF_CALLBACK_DATA d) +{ d->images.size += 100; - d->images.strings = (char **) realloc(d->images.strings,d->images.size * sizeof(char *)); + d->images.strings = (char **)realloc(d->images.strings, d->images.size * sizeof(char *)); } /* See if the image string is already in the list. If it is return its position (1->n, not 1-n-1) -*/ -int Wmf::in_images(PWMF_CALLBACK_DATA d, char *test){ + */ +int Wmf::in_images(PWMF_CALLBACK_DATA d, char *test) +{ int i; - for(i=0; iimages.count; i++){ - if(strcmp(test,d->images.strings[i])==0)return(i+1); + for (i = 0; i < d->images.count; i++) { + if (strcmp(test, d->images.strings[i]) == 0) + return (i + 1); } - return(0); + return (0); } /* (Conditionally) add an image from a DIB. If a matching image already exists nothing happens. If one does not exist it is added to the images list and also entered into . */ -uint32_t Wmf::add_dib_image(PWMF_CALLBACK_DATA d, const char *dib, uint32_t iUsage){ - +uint32_t Wmf::add_dib_image(PWMF_CALLBACK_DATA d, const char *dib, uint32_t iUsage) +{ uint32_t idx; - char imagename[64]; // big enough - char xywh[64]; // big enough - int dibparams = U_BI_UNKNOWN; // type of image not yet determined + char imagename[64]; // big enough + char xywh[64]; // big enough + int dibparams = U_BI_UNKNOWN; // type of image not yet determined MEMPNG mempng; // PNG in memory comes back in this mempng.buffer = nullptr; - char *rgba_px = nullptr; // RGBA pixels - const char *px = nullptr; // DIB pixels - const U_RGBQUAD *ct = nullptr; // DIB color table + char *rgba_px = nullptr; // RGBA pixels + const char *px = nullptr; // DIB pixels + const U_RGBQUAD *ct = nullptr; // DIB color table uint32_t numCt; - int32_t width, height, colortype, invert; // if needed these values will be set by wget_DIB_params - if(iUsage == U_DIB_RGB_COLORS){ + int32_t width, height, colortype, invert; // if needed these values will be set by wget_DIB_params + if (iUsage == U_DIB_RGB_COLORS) { // next call returns pointers and values, but allocates no memory dibparams = wget_DIB_params(dib, &px, &ct, &numCt, &width, &height, &colortype, &invert); - if(dibparams == U_BI_RGB){ - if(!DIB_to_RGBA( - px, // DIB pixel array - ct, // DIB color table - numCt, // DIB color table number of entries - &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. - width, // Width of pixel array in record - height, // Height of pixel array in record - colortype, // DIB BitCount Enumeration - numCt, // Color table used if not 0 - invert // If DIB rows are in opposite order from RGBA rows - )){ - toPNG( // Get the image from the RGBA px into mempng - &mempng, - width, height, // of the SRC bitmap - rgba_px - ); + if (dibparams == U_BI_RGB) { + if (!DIB_to_RGBA(px, // DIB pixel array + ct, // DIB color table + numCt, // DIB color table number of entries + &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. + width, // Width of pixel array in record + height, // Height of pixel array in record + colortype, // DIB BitCount Enumeration + numCt, // Color table used if not 0 + invert // If DIB rows are in opposite order from RGBA rows + )) { + toPNG( // Get the image from the RGBA px into mempng + &mempng, width, height, // of the SRC bitmap + rgba_px); free(rgba_px); } } } - gchar *base64String=nullptr; - if(dibparams == U_BI_JPEG || dibparams==U_BI_PNG){ // image was binary png or jpg in source file - base64String = g_base64_encode((guchar*) px, numCt ); - } - else if(mempng.buffer){ // image was DIB in source file, converted to png in this routine - base64String = g_base64_encode((guchar*) mempng.buffer, mempng.size ); + gchar *base64String = nullptr; + if (dibparams == U_BI_JPEG || dibparams == U_BI_PNG) { // image was binary png or jpg in source file + base64String = g_base64_encode((guchar *)px, numCt); + } else if (mempng.buffer) { // image was DIB in source file, converted to png in this routine + base64String = g_base64_encode((guchar *)mempng.buffer, mempng.size); free(mempng.buffer); - } - else { // failed conversion, insert the common bad image picture - width = 3; + } else { // failed conversion, insert the common bad image picture + width = 3; height = 4; base64String = bad_image_png(); } - idx = in_images(d, (char *) base64String); - auto & defs = d->defs; - if(!idx){ // add it if not already present - we looked at the actual data for comparison - if(d->images.count == d->images.size){ enlarge_images(d); } + idx = in_images(d, (char *)base64String); + auto &defs = d->defs; + if (!idx) { // add it if not already present - we looked at the actual data for comparison + if (d->images.count == d->images.size) { + enlarge_images(d); + } idx = d->images.count; - d->images.strings[d->images.count++]=strdup(base64String); + d->images.strings[d->images.count++] = strdup(base64String); - sprintf(imagename,"WMFimage%d",idx++); - sprintf(xywh," x=\"0\" y=\"0\" width=\"%d\" height=\"%d\" ",width,height); // reuse this buffer + sprintf(imagename, "WMFimage%d", idx++); + sprintf(xywh, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\" ", width, height); // reuse this buffer defs += "\n"; defs += " . */ -uint32_t Wmf::add_bm16_image(PWMF_CALLBACK_DATA d, U_BITMAP16 Bm16, const char *px){ - +uint32_t Wmf::add_bm16_image(PWMF_CALLBACK_DATA d, U_BITMAP16 Bm16, const char *px) +{ uint32_t idx; char imagename[64]; // big enough - char xywh[64]; // big enough + char xywh[64]; // big enough MEMPNG mempng; // PNG in memory comes back in this mempng.buffer = nullptr; - char *rgba_px = nullptr; // RGBA pixels - const U_RGBQUAD *ct = nullptr; // color table, always NULL here - int32_t width, height, colortype, numCt, invert; - numCt = 0; - width = Bm16.Width; // bitmap width in pixels. - height = Bm16.Height; // bitmap height in scan lines. - colortype = Bm16.BitsPixel; // seems to be BitCount Enumeration - invert = 0; - if(colortype < 16)return(U_WMR_INVALID); // these would need a colortable if they were a dib, no idea what bm16 is supposed to do instead. - - if(!DIB_to_RGBA(// This is not really a dib, but close enough so that it still works. - px, // DIB pixel array - ct, // DIB color table (always NULL here) - numCt, // DIB color table number of entries (always 0) - &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. - width, // Width of pixel array - height, // Height of pixel array - colortype, // DIB BitCount Enumeration - numCt, // Color table used if not 0 - invert // If DIB rows are in opposite order from RGBA rows - )){ - toPNG( // Get the image from the RGBA px into mempng - &mempng, - width, height, // of the SRC bitmap - rgba_px - ); + char *rgba_px = nullptr; // RGBA pixels + const U_RGBQUAD *ct = nullptr; // color table, always NULL here + int32_t width, height, colortype, numCt, invert; + numCt = 0; + width = Bm16.Width; // bitmap width in pixels. + height = Bm16.Height; // bitmap height in scan lines. + colortype = Bm16.BitsPixel; // seems to be BitCount Enumeration + invert = 0; + if (colortype < 16) + return (U_WMR_INVALID); // these would need a colortable if they were a dib, no idea what bm16 is supposed to do + // instead. + + if (!DIB_to_RGBA( // This is not really a dib, but close enough so that it still works. + px, // DIB pixel array + ct, // DIB color table (always NULL here) + numCt, // DIB color table number of entries (always 0) + &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. + width, // Width of pixel array + height, // Height of pixel array + colortype, // DIB BitCount Enumeration + numCt, // Color table used if not 0 + invert // If DIB rows are in opposite order from RGBA rows + )) { + toPNG( // Get the image from the RGBA px into mempng + &mempng, width, height, // of the SRC bitmap + rgba_px); free(rgba_px); } - gchar *base64String=nullptr; - if(mempng.buffer){ // image was Bm16 in source file, converted to png in this routine - base64String = g_base64_encode((guchar*) mempng.buffer, mempng.size ); + gchar *base64String = nullptr; + if (mempng.buffer) { // image was Bm16 in source file, converted to png in this routine + base64String = g_base64_encode((guchar *)mempng.buffer, mempng.size); free(mempng.buffer); - } - else { // failed conversion, insert the common bad image picture - width = 3; + } else { // failed conversion, insert the common bad image picture + width = 3; height = 4; base64String = bad_image_png(); } - idx = in_images(d, (char *) base64String); - auto & defs = d->defs; - if(!idx){ // add it if not already present - we looked at the actual data for comparison - if(d->images.count == d->images.size){ enlarge_images(d); } + idx = in_images(d, (char *)base64String); + auto &defs = d->defs; + if (!idx) { // add it if not already present - we looked at the actual data for comparison + if (d->images.count == d->images.size) { + enlarge_images(d); + } idx = d->images.count; - d->images.strings[d->images.count++]=g_strdup(base64String); + d->images.strings[d->images.count++] = g_strdup(base64String); - sprintf(imagename,"WMFimage%d",idx++); - sprintf(xywh," x=\"0\" y=\"0\" width=\"%d\" height=\"%d\" ",width,height); // reuse this buffer + sprintf(imagename, "WMFimage%d", idx++); + sprintf(xywh, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\" ", width, height); // reuse this buffer defs += "\n"; defs += " \n"; defs += " \n"; } - g_free(base64String); //wait until this point to free because it might be a duplicate image - return(idx-1); + g_free(base64String); // wait until this point to free because it might be a duplicate image + return (idx - 1); } /* Add another 100 blank slots to the clips array. -*/ -void Wmf::enlarge_clips(PWMF_CALLBACK_DATA d){ + */ +void Wmf::enlarge_clips(PWMF_CALLBACK_DATA d) +{ d->clips.size += 100; - d->clips.strings = (char **) realloc(d->clips.strings,d->clips.size * sizeof(char *)); + d->clips.strings = (char **)realloc(d->clips.strings, d->clips.size * sizeof(char *)); } /* See if the pattern name is already in the list. If it is return its position (1->n, not 1-n-1) -*/ -int Wmf::in_clips(PWMF_CALLBACK_DATA d, const char *test){ + */ +int Wmf::in_clips(PWMF_CALLBACK_DATA d, const char *test) +{ int i; - for(i=0; iclips.count; i++){ - if(strcmp(test,d->clips.strings[i])==0)return(i+1); + for (i = 0; i < d->clips.count; i++) { + if (strcmp(test, d->clips.strings[i]) == 0) + return (i + 1); } - return(0); + return (0); } -/* (Conditionally) add a clip. - If a matching clip already exists nothing happens +/* (Conditionally) add a clip. + If a matching clip already exists nothing happens If one does exist it is added to the clips list, entered into . */ -void Wmf::add_clips(PWMF_CALLBACK_DATA d, const char *clippath, unsigned int logic){ +void Wmf::add_clips(PWMF_CALLBACK_DATA d, const char *clippath, unsigned int logic) +{ int op = combine_ops_to_livarot(logic); Geom::PathVector combined_vect; char *combined = nullptr; @@ -664,18 +674,20 @@ void Wmf::add_clips(PWMF_CALLBACK_DATA d, const char *clippath, unsigned int log unsigned int real_idx = d->dc[d->level].clip_id - 1; Geom::PathVector old_vect = sp_svg_read_pathv(d->clips.strings[real_idx]); Geom::PathVector new_vect = sp_svg_read_pathv(clippath); - combined_vect = sp_pathvector_boolop(new_vect, old_vect, (bool_op) op , (FillRule) fill_oddEven, (FillRule) fill_oddEven); + combined_vect = + sp_pathvector_boolop(new_vect, old_vect, (bool_op)op, (FillRule)fill_oddEven, (FillRule)fill_oddEven); combined = sp_svg_write_path(combined_vect); - } - else { - combined = strdup(clippath); // COPY operation, erases everything and starts a new one + } else { + combined = strdup(clippath); // COPY operation, erases everything and starts a new one } - uint32_t idx = in_clips(d, combined); - if(!idx){ // add clip if not already present - if(d->clips.count == d->clips.size){ enlarge_clips(d); } - d->clips.strings[d->clips.count++]=strdup(combined); - d->dc[d->level].clip_id = d->clips.count; // one more than the slot where it is actually stored + uint32_t idx = in_clips(d, combined); + if (!idx) { // add clip if not already present + if (d->clips.count == d->clips.size) { + enlarge_clips(d); + } + d->clips.strings[d->clips.count++] = strdup(combined); + d->dc[d->level].clip_id = d->clips.count; // one more than the slot where it is actually stored SVGOStringStream tmp_clippath; tmp_clippath << "\n"; tmp_clippath << "\n"; d->outdef += tmp_clippath.str().c_str(); - } - else { + } else { d->dc[d->level].clip_id = idx; } free(combined); } - - -void -Wmf::output_style(PWMF_CALLBACK_DATA d) +void Wmf::output_style(PWMF_CALLBACK_DATA d) { -// SVGOStringStream tmp_id; + // SVGOStringStream tmp_id; SVGOStringStream tmp_style; char tmp[1024] = {0}; @@ -710,23 +718,23 @@ Wmf::output_style(PWMF_CALLBACK_DATA d) // for U_WMR_BITBLT with no image, try to approximate some of these operations/ // Assume src color is "white" - if(d->dwRop3){ - switch(d->dwRop3){ + if (d->dwRop3) { + switch (d->dwRop3) { case U_PATINVERT: // treat all of these as black case U_SRCINVERT: case U_DSTINVERT: case U_BLACKNESS: case U_SRCERASE: case U_NOTSRCCOPY: - fill_rgb[0]=fill_rgb[1]=fill_rgb[2]=0.0; + fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 0.0; break; - case U_SRCCOPY: // treat all of these as white + case U_SRCCOPY: // treat all of these as white case U_NOTSRCERASE: case U_PATCOPY: case U_WHITENESS: - fill_rgb[0]=fill_rgb[1]=fill_rgb[2]=1.0; + fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 1.0; break; - case U_SRCPAINT: // use the existing color + case U_SRCPAINT: // use the existing color case U_SRCAND: case U_MERGECOPY: case U_MERGEPAINT: @@ -734,28 +742,28 @@ Wmf::output_style(PWMF_CALLBACK_DATA d) default: break; } - d->dwRop3 = 0; // might as well reset it here, it must be set for each BITBLT + d->dwRop3 = 0; // might as well reset it here, it must be set for each BITBLT } // Implement some of these, the ones where the original screen color does not matter. // The options that merge screen and pen colors cannot be done correctly because we // have no way of knowing what color is already on the screen. For those just pass the // pen color through. - switch(d->dwRop2){ + switch (d->dwRop2) { case U_R2_BLACK: - fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 0.0; - stroke_rgb[0]= stroke_rgb[1]= stroke_rgb[2] = 0.0; + fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 0.0; + stroke_rgb[0] = stroke_rgb[1] = stroke_rgb[2] = 0.0; break; case U_R2_NOTMERGEPEN: case U_R2_MASKNOTPEN: break; case U_R2_NOTCOPYPEN: - fill_rgb[0] = 1.0 - fill_rgb[0]; - fill_rgb[1] = 1.0 - fill_rgb[1]; - fill_rgb[2] = 1.0 - fill_rgb[2]; - stroke_rgb[0] = 1.0 - stroke_rgb[0]; - stroke_rgb[1] = 1.0 - stroke_rgb[1]; - stroke_rgb[2] = 1.0 - stroke_rgb[2]; + fill_rgb[0] = 1.0 - fill_rgb[0]; + fill_rgb[1] = 1.0 - fill_rgb[1]; + fill_rgb[2] = 1.0 - fill_rgb[2]; + stroke_rgb[0] = 1.0 - stroke_rgb[0]; + stroke_rgb[1] = 1.0 - stroke_rgb[1]; + stroke_rgb[2] = 1.0 - stroke_rgb[2]; break; case U_R2_MASKPENNOT: case U_R2_NOT: @@ -770,65 +778,48 @@ Wmf::output_style(PWMF_CALLBACK_DATA d) case U_R2_MERGEPEN: break; case U_R2_WHITE: - fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 1.0; - stroke_rgb[0]= stroke_rgb[1]= stroke_rgb[2] = 1.0; + fill_rgb[0] = fill_rgb[1] = fill_rgb[2] = 1.0; + stroke_rgb[0] = stroke_rgb[1] = stroke_rgb[2] = 1.0; break; default: break; } - -// tmp_id << "\n\tid=\"" << (d->id++) << "\""; -// d->outsvg += tmp_id.str().c_str(); + // tmp_id << "\n\tid=\"" << (d->id++) << "\""; + // d->outsvg += tmp_id.str().c_str(); d->outsvg += "\n\tstyle=\""; - if (!d->dc[d->level].fill_set || ( d->mask & U_DRAW_NOFILL)) { // nofill are lines and arcs + if (!d->dc[d->level].fill_set || (d->mask & U_DRAW_NOFILL)) { // nofill are lines and arcs tmp_style << "fill:none;"; } else { - switch(d->dc[d->level].fill_mode){ + switch (d->dc[d->level].fill_mode) { // both of these use the url(#) method case DRAW_PATTERN: - snprintf(tmp, 1023, "fill:url(#%s); ",d->hatches.strings[d->dc[d->level].fill_idx]); + snprintf(tmp, 1023, "fill:url(#%s); ", d->hatches.strings[d->dc[d->level].fill_idx]); tmp_style << tmp; break; case DRAW_IMAGE: - snprintf(tmp, 1023, "fill:url(#WMFimage%d_ref); ",d->dc[d->level].fill_idx); + snprintf(tmp, 1023, "fill:url(#WMFimage%d_ref); ", d->dc[d->level].fill_idx); tmp_style << tmp; break; case DRAW_PAINT: - default: // <-- this should never happen, but just in case... - snprintf( - tmp, 1023, - "fill:#%02x%02x%02x;", - SP_COLOR_F_TO_U(fill_rgb[0]), - SP_COLOR_F_TO_U(fill_rgb[1]), - SP_COLOR_F_TO_U(fill_rgb[2]) - ); + default: // <-- this should never happen, but just in case... + snprintf(tmp, 1023, "fill:#%02x%02x%02x;", SP_COLOR_F_TO_U(fill_rgb[0]), SP_COLOR_F_TO_U(fill_rgb[1]), + SP_COLOR_F_TO_U(fill_rgb[2])); tmp_style << tmp; break; } - snprintf( - tmp, 1023, - "fill-rule:%s;", - (d->dc[d->level].style.fill_rule.value == SP_WIND_RULE_NONZERO ? "evenodd" : "nonzero") - ); + snprintf(tmp, 1023, "fill-rule:%s;", + (d->dc[d->level].style.fill_rule.value == SP_WIND_RULE_NONZERO ? "evenodd" : "nonzero")); tmp_style << tmp; tmp_style << "fill-opacity:1;"; - // if the stroke is the same as the fill, and the right size not to change the end size of the object, do not do it separately - if( - (d->dc[d->level].fill_set ) && - (d->dc[d->level].stroke_set ) && - (d->dc[d->level].style.stroke_width.value == 1 ) && - (d->dc[d->level].fill_mode == d->dc[d->level].stroke_mode) && - ( - (d->dc[d->level].fill_mode != DRAW_PAINT) || - ( - (fill_rgb[0]==stroke_rgb[0]) && - (fill_rgb[1]==stroke_rgb[1]) && - (fill_rgb[2]==stroke_rgb[2]) - ) - ) - ){ + // if the stroke is the same as the fill, and the right size not to change the end size of the object, do not do + // it separately + if ((d->dc[d->level].fill_set) && (d->dc[d->level].stroke_set) && + (d->dc[d->level].style.stroke_width.value == 1) && + (d->dc[d->level].fill_mode == d->dc[d->level].stroke_mode) && + ((d->dc[d->level].fill_mode != DRAW_PAINT) || + ((fill_rgb[0] == stroke_rgb[0]) && (fill_rgb[1] == stroke_rgb[1]) && (fill_rgb[2] == stroke_rgb[2])))) { d->dc[d->level].stroke_set = false; } } @@ -836,61 +827,54 @@ Wmf::output_style(PWMF_CALLBACK_DATA d) if (!d->dc[d->level].stroke_set) { tmp_style << "stroke:none;"; } else { - switch(d->dc[d->level].stroke_mode){ + switch (d->dc[d->level].stroke_mode) { // both of these use the url(#) method case DRAW_PATTERN: - snprintf(tmp, 1023, "stroke:url(#%s); ",d->hatches.strings[d->dc[d->level].stroke_idx]); + snprintf(tmp, 1023, "stroke:url(#%s); ", d->hatches.strings[d->dc[d->level].stroke_idx]); tmp_style << tmp; break; case DRAW_IMAGE: - snprintf(tmp, 1023, "stroke:url(#WMFimage%d_ref); ",d->dc[d->level].stroke_idx); + snprintf(tmp, 1023, "stroke:url(#WMFimage%d_ref); ", d->dc[d->level].stroke_idx); tmp_style << tmp; break; case DRAW_PAINT: - default: // <-- this should never happen, but just in case... - snprintf( - tmp, 1023, - "stroke:#%02x%02x%02x;", - SP_COLOR_F_TO_U(stroke_rgb[0]), - SP_COLOR_F_TO_U(stroke_rgb[1]), - SP_COLOR_F_TO_U(stroke_rgb[2]) - ); + default: // <-- this should never happen, but just in case... + snprintf(tmp, 1023, "stroke:#%02x%02x%02x;", SP_COLOR_F_TO_U(stroke_rgb[0]), + SP_COLOR_F_TO_U(stroke_rgb[1]), SP_COLOR_F_TO_U(stroke_rgb[2])); tmp_style << tmp; break; } - if(d->dc[d->level].style.stroke_width.value){ - tmp_style << "stroke-width:" << - MAX( 0.001, d->dc[d->level].style.stroke_width.value ) << "px;"; - } - else { // In a WMF a 0 width pixel means "1 pixel" - tmp_style << "stroke-width:" << pix_to_abs_size( d, 1 ) << "px;"; - } - - tmp_style << "stroke-linecap:" << - ( - d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_BUTT ? "butt" : - d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_ROUND ? "round" : - d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_SQUARE ? "square" : - "unknown" - ) << ";"; - - tmp_style << "stroke-linejoin:" << - ( - d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_MITER ? "miter" : - d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_ROUND ? "round" : - d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_BEVEL ? "bevel" : - "unknown" - ) << ";"; + if (d->dc[d->level].style.stroke_width.value) { + tmp_style << "stroke-width:" << MAX(0.001, d->dc[d->level].style.stroke_width.value) << "px;"; + } else { // In a WMF a 0 width pixel means "1 pixel" + tmp_style << "stroke-width:" << pix_to_abs_size(d, 1) << "px;"; + } + + tmp_style << "stroke-linecap:" + << (d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_BUTT + ? "butt" + : d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_ROUND + ? "round" + : d->dc[d->level].style.stroke_linecap.computed == SP_STROKE_LINECAP_SQUARE ? "square" + : "unknown") + << ";"; + + tmp_style << "stroke-linejoin:" + << (d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_MITER + ? "miter" + : d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_ROUND + ? "round" + : d->dc[d->level].style.stroke_linejoin.computed == SP_STROKE_LINEJOIN_BEVEL + ? "bevel" + : "unknown") + << ";"; // Set miter limit if known, even if it is not needed immediately (not miter) - tmp_style << "stroke-miterlimit:" << - MAX( 2.0, d->dc[d->level].style.stroke_miterlimit.value ) << ";"; + tmp_style << "stroke-miterlimit:" << MAX(2.0, d->dc[d->level].style.stroke_miterlimit.value) << ";"; - if (d->dc[d->level].style.stroke_dasharray.set && - !d->dc[d->level].style.stroke_dasharray.values.empty()) - { + if (d->dc[d->level].style.stroke_dasharray.set && !d->dc[d->level].style.stroke_dasharray.values.empty()) { tmp_style << "stroke-dasharray:"; - for (unsigned i=0; idc[d->level].style.stroke_dasharray.values.size(); i++) { + for (unsigned i = 0; i < d->dc[d->level].style.stroke_dasharray.values.size(); i++) { if (i) tmp_style << ","; tmp_style << d->dc[d->level].style.stroke_dasharray.values[i].value; @@ -909,99 +893,96 @@ Wmf::output_style(PWMF_CALLBACK_DATA d) d->outsvg += tmp_style.str().c_str(); } - -double -Wmf::_pix_x_to_point(PWMF_CALLBACK_DATA d, double px) +double Wmf::_pix_x_to_point(PWMF_CALLBACK_DATA d, double px) { double scale = (d->dc[d->level].ScaleInX ? d->dc[d->level].ScaleInX : 1.0); double tmp; - tmp = ((((double) (px - d->dc[d->level].winorg.x))*scale) + d->dc[d->level].vieworg.x) * d->D2PscaleX; - tmp -= d->ulCornerOutX; //The WMF boundary rectangle can be anywhere, place its upper left corner in the Inkscape upper left corner - return(tmp); + tmp = ((((double)(px - d->dc[d->level].winorg.x)) * scale) + d->dc[d->level].vieworg.x) * d->D2PscaleX; + tmp -= d->ulCornerOutX; // The WMF boundary rectangle can be anywhere, place its upper left corner in the Inkscape + // upper left corner + return (tmp); } -double -Wmf::_pix_y_to_point(PWMF_CALLBACK_DATA d, double py) +double Wmf::_pix_y_to_point(PWMF_CALLBACK_DATA d, double py) { double scale = (d->dc[d->level].ScaleInY ? d->dc[d->level].ScaleInY : 1.0); double tmp; - tmp = ((((double) (py - d->dc[d->level].winorg.y))*scale) * d->E2IdirY + d->dc[d->level].vieworg.y) * d->D2PscaleY; - tmp -= d->ulCornerOutY; //The WMF boundary rectangle can be anywhere, place its upper left corner in the Inkscape upper left corner - return(tmp); + tmp = ((((double)(py - d->dc[d->level].winorg.y)) * scale) * d->E2IdirY + d->dc[d->level].vieworg.y) * d->D2PscaleY; + tmp -= d->ulCornerOutY; // The WMF boundary rectangle can be anywhere, place its upper left corner in the Inkscape + // upper left corner + return (tmp); } - -double -Wmf::pix_to_x_point(PWMF_CALLBACK_DATA d, double px, double /*py*/) +double Wmf::pix_to_x_point(PWMF_CALLBACK_DATA d, double px, double /*py*/) { - double x = _pix_x_to_point(d, px); + double x = _pix_x_to_point(d, px); return x; } -double -Wmf::pix_to_y_point(PWMF_CALLBACK_DATA d, double /*px*/, double py) +double Wmf::pix_to_y_point(PWMF_CALLBACK_DATA d, double /*px*/, double py) { - double y = _pix_y_to_point(d, py); + double y = _pix_y_to_point(d, py); return y; - } -double -Wmf::pix_to_abs_size(PWMF_CALLBACK_DATA d, double px) +double Wmf::pix_to_abs_size(PWMF_CALLBACK_DATA d, double px) { - double ppx = fabs(px * (d->dc[d->level].ScaleInX ? d->dc[d->level].ScaleInX : 1.0) * d->D2PscaleX * current_scale(d)); + double ppx = + fabs(px * (d->dc[d->level].ScaleInX ? d->dc[d->level].ScaleInX : 1.0) * d->D2PscaleX * current_scale(d)); return ppx; } /* returns "x,y" (without the quotes) in inkscape coordinates for a pair of WMF x,y coordinates -*/ -std::string Wmf::pix_to_xy(PWMF_CALLBACK_DATA d, double x, double y){ + */ +std::string Wmf::pix_to_xy(PWMF_CALLBACK_DATA d, double x, double y) +{ SVGOStringStream cxform; - cxform << pix_to_x_point(d,x,y); + cxform << pix_to_x_point(d, x, y); cxform << ","; - cxform << pix_to_y_point(d,x,y); - return(cxform.str()); + cxform << pix_to_y_point(d, x, y); + return (cxform.str()); } - -void -Wmf::select_pen(PWMF_CALLBACK_DATA d, int index) +void Wmf::select_pen(PWMF_CALLBACK_DATA d, int index) { int width; char *record = nullptr; U_PEN up; - if (index < 0 && index >= d->n_obj){ return; } + if (index < 0 && index >= d->n_obj) { + return; + } record = d->wmf_obj[index].record; - if(!record){ return; } + if (!record) { + return; + } d->dc[d->level].active_pen = index; - (void) U_WMRCREATEPENINDIRECT_get(record, &up); - width = up.Widthw[0]; // width is stored in the first 16 bits of the 32. + (void)U_WMRCREATEPENINDIRECT_get(record, &up); + width = up.Widthw[0]; // width is stored in the first 16 bits of the 32. switch (up.Style & U_PS_STYLE_MASK) { case U_PS_DASH: case U_PS_DOT: case U_PS_DASHDOT: - case U_PS_DASHDOTDOT: - { + case U_PS_DASHDOTDOT: { int penstyle = (up.Style & U_PS_STYLE_MASK); SPILength spilength(1.f); if (!d->dc[d->level].style.stroke_dasharray.values.empty() && (d->level == 0 || (d->level > 0 && d->dc[d->level].style.stroke_dasharray != d->dc[d->level - 1].style.stroke_dasharray))) d->dc[d->level].style.stroke_dasharray.values.clear(); - if (penstyle==U_PS_DASH || penstyle==U_PS_DASHDOT || penstyle==U_PS_DASHDOTDOT) { + if (penstyle == U_PS_DASH || penstyle == U_PS_DASHDOT || penstyle == U_PS_DASHDOTDOT) { spilength.setDouble(3); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); spilength.setDouble(1); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); } - if (penstyle==U_PS_DOT || penstyle==U_PS_DASHDOT || penstyle==U_PS_DASHDOTDOT) { + if (penstyle == U_PS_DOT || penstyle == U_PS_DASHDOT || penstyle == U_PS_DASHDOTDOT) { d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); } - if (penstyle==U_PS_DASHDOTDOT) { + if (penstyle == U_PS_DASHDOTDOT) { d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); d->dc[d->level].style.stroke_dasharray.values.push_back(spilength); } @@ -1011,143 +992,156 @@ Wmf::select_pen(PWMF_CALLBACK_DATA d, int index) } case U_PS_SOLID: - default: - { + default: { d->dc[d->level].style.stroke_dasharray.set = false; break; } } switch (up.Style & U_PS_ENDCAP_MASK) { - case U_PS_ENDCAP_ROUND: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_ROUND; break; } - case U_PS_ENDCAP_SQUARE: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_SQUARE; break; } + case U_PS_ENDCAP_ROUND: { + d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_ROUND; + break; + } + case U_PS_ENDCAP_SQUARE: { + d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_SQUARE; + break; + } case U_PS_ENDCAP_FLAT: - default: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_BUTT; break; } + default: { + d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_BUTT; + break; + } } switch (up.Style & U_PS_JOIN_MASK) { - case U_PS_JOIN_BEVEL: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_BEVEL; break; } - case U_PS_JOIN_MITER: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_MITER; break; } + case U_PS_JOIN_BEVEL: { + d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_BEVEL; + break; + } + case U_PS_JOIN_MITER: { + d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_MITER; + break; + } case U_PS_JOIN_ROUND: - default: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_ROUND; break; } + default: { + d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_ROUND; + break; + } } - double pen_width; if (up.Style == U_PS_NULL) { d->dc[d->level].stroke_set = false; - pen_width =0.0; + pen_width = 0.0; } else if (width) { d->dc[d->level].stroke_set = true; int cur_level = d->level; - d->level = d->wmf_obj[index].level; // this object may have been defined in some other DC. - pen_width = pix_to_abs_size( d, width ); + d->level = d->wmf_obj[index].level; // this object may have been defined in some other DC. + pen_width = pix_to_abs_size(d, width); d->level = cur_level; - } else { // this stroke should always be rendered as 1 pixel wide, independent of zoom level (can that be done in SVG?) + } else { // this stroke should always be rendered as 1 pixel wide, independent of zoom level (can that be done in + // SVG?) d->dc[d->level].stroke_set = true; int cur_level = d->level; - d->level = d->wmf_obj[index].level; // this object may have been defined in some other DC. - pen_width = pix_to_abs_size( d, 1 ); + d->level = d->wmf_obj[index].level; // this object may have been defined in some other DC. + pen_width = pix_to_abs_size(d, 1); d->level = cur_level; } d->dc[d->level].style.stroke_width.value = pen_width; double r, g, b; - r = SP_COLOR_U_TO_F( U_RGBAGetR(up.Color) ); - g = SP_COLOR_U_TO_F( U_RGBAGetG(up.Color) ); - b = SP_COLOR_U_TO_F( U_RGBAGetB(up.Color) ); - d->dc[d->level].style.stroke.value.color.set( r, g, b ); + r = SP_COLOR_U_TO_F(U_RGBAGetR(up.Color)); + g = SP_COLOR_U_TO_F(U_RGBAGetG(up.Color)); + b = SP_COLOR_U_TO_F(U_RGBAGetB(up.Color)); + d->dc[d->level].style.stroke.value.color.set(r, g, b); } - -void -Wmf::select_brush(PWMF_CALLBACK_DATA d, int index) +void Wmf::select_brush(PWMF_CALLBACK_DATA d, int index) { - uint8_t iType; - char *record; - const char *membrush; + uint8_t iType; + char *record; + const char *membrush; - if (index < 0 || index >= d->n_obj)return; + if (index < 0 || index >= d->n_obj) + return; record = d->wmf_obj[index].record; - if(!record)return; + if (!record) + return; d->dc[d->level].active_brush = index; - iType = *(uint8_t *)(record + offsetof(U_METARECORD, iType ) ); - if(iType == U_WMR_CREATEBRUSHINDIRECT){ - U_WLOGBRUSH lb; - (void) U_WMRCREATEBRUSHINDIRECT_get(record, &membrush); + iType = *(uint8_t *)(record + offsetof(U_METARECORD, iType)); + if (iType == U_WMR_CREATEBRUSHINDIRECT) { + U_WLOGBRUSH lb; + (void)U_WMRCREATEBRUSHINDIRECT_get(record, &membrush); memcpy(&lb, membrush, U_SIZE_WLOGBRUSH); - if(lb.Style == U_BS_SOLID){ + if (lb.Style == U_BS_SOLID) { double r, g, b; - r = SP_COLOR_U_TO_F( U_RGBAGetR(lb.Color) ); - g = SP_COLOR_U_TO_F( U_RGBAGetG(lb.Color) ); - b = SP_COLOR_U_TO_F( U_RGBAGetB(lb.Color) ); - d->dc[d->level].style.fill.value.color.set( r, g, b ); - d->dc[d->level].fill_mode = DRAW_PAINT; - d->dc[d->level].fill_set = true; - } - else if(lb.Style == U_BS_HATCHED){ - d->dc[d->level].fill_idx = add_hatch(d, lb.Hatch, lb.Color); - d->dc[d->level].fill_recidx = index; // used if the hatch needs to be redone due to bkMode, textmode, etc. changes - d->dc[d->level].fill_mode = DRAW_PATTERN; - d->dc[d->level].fill_set = true; - } - else if(lb.Style == U_BS_NULL){ - d->dc[d->level].fill_mode = DRAW_PAINT; // set it to something - d->dc[d->level].fill_set = false; - } - } - else if(iType == U_WMR_DIBCREATEPATTERNBRUSH){ - uint32_t tidx; - uint16_t Style; - uint16_t cUsage; - const char *Bm16h = nullptr; // Pointer to Bitmap16 header (px follows) - const char *dib = nullptr; // Pointer to DIB - (void) U_WMRDIBCREATEPATTERNBRUSH_get(record, &Style, &cUsage, &Bm16h, &dib); - if(dib || Bm16h){ - if(dib){ tidx = add_dib_image(d, dib, cUsage); } - else { - U_BITMAP16 Bm16; + r = SP_COLOR_U_TO_F(U_RGBAGetR(lb.Color)); + g = SP_COLOR_U_TO_F(U_RGBAGetG(lb.Color)); + b = SP_COLOR_U_TO_F(U_RGBAGetB(lb.Color)); + d->dc[d->level].style.fill.value.color.set(r, g, b); + d->dc[d->level].fill_mode = DRAW_PAINT; + d->dc[d->level].fill_set = true; + } else if (lb.Style == U_BS_HATCHED) { + d->dc[d->level].fill_idx = add_hatch(d, lb.Hatch, lb.Color); + d->dc[d->level].fill_recidx = + index; // used if the hatch needs to be redone due to bkMode, textmode, etc. changes + d->dc[d->level].fill_mode = DRAW_PATTERN; + d->dc[d->level].fill_set = true; + } else if (lb.Style == U_BS_NULL) { + d->dc[d->level].fill_mode = DRAW_PAINT; // set it to something + d->dc[d->level].fill_set = false; + } + } else if (iType == U_WMR_DIBCREATEPATTERNBRUSH) { + uint32_t tidx; + uint16_t Style; + uint16_t cUsage; + const char *Bm16h = nullptr; // Pointer to Bitmap16 header (px follows) + const char *dib = nullptr; // Pointer to DIB + (void)U_WMRDIBCREATEPATTERNBRUSH_get(record, &Style, &cUsage, &Bm16h, &dib); + if (dib || Bm16h) { + if (dib) { + tidx = add_dib_image(d, dib, cUsage); + } else { + U_BITMAP16 Bm16; const char *px; memcpy(&Bm16, Bm16h, U_SIZE_BITMAP16); px = Bm16h + U_SIZE_BITMAP16; tidx = add_bm16_image(d, Bm16, px); } - if(tidx == U_WMR_INVALID){ // Problem with the image, for instance, an unsupported bitmap16 type + if (tidx == U_WMR_INVALID) { // Problem with the image, for instance, an unsupported bitmap16 type double r, g, b; - r = SP_COLOR_U_TO_F( U_RGBAGetR(d->dc[d->level].textColor)); - g = SP_COLOR_U_TO_F( U_RGBAGetG(d->dc[d->level].textColor)); - b = SP_COLOR_U_TO_F( U_RGBAGetB(d->dc[d->level].textColor)); - d->dc[d->level].style.fill.value.color.set( r, g, b ); + r = SP_COLOR_U_TO_F(U_RGBAGetR(d->dc[d->level].textColor)); + g = SP_COLOR_U_TO_F(U_RGBAGetG(d->dc[d->level].textColor)); + b = SP_COLOR_U_TO_F(U_RGBAGetB(d->dc[d->level].textColor)); + d->dc[d->level].style.fill.value.color.set(r, g, b); d->dc[d->level].fill_mode = DRAW_PAINT; - } - else { - d->dc[d->level].fill_idx = tidx; + } else { + d->dc[d->level].fill_idx = tidx; d->dc[d->level].fill_mode = DRAW_IMAGE; } d->dc[d->level].fill_set = true; + } else { + g_message("Please send WMF file to developers - select_brush U_WMR_DIBCREATEPATTERNBRUSH not bm16 or dib, " + "not handled"); } - else { - g_message("Please send WMF file to developers - select_brush U_WMR_DIBCREATEPATTERNBRUSH not bm16 or dib, not handled"); - } - } - else if(iType == U_WMR_CREATEPATTERNBRUSH){ - uint32_t tidx; - int cbPx; - U_BITMAP16 Bm16h; + } else if (iType == U_WMR_CREATEPATTERNBRUSH) { + uint32_t tidx; + int cbPx; + U_BITMAP16 Bm16h; const char *px; - if(U_WMRCREATEPATTERNBRUSH_get(record, &Bm16h, &cbPx, &px)){ + if (U_WMRCREATEPATTERNBRUSH_get(record, &Bm16h, &cbPx, &px)) { tidx = add_bm16_image(d, Bm16h, px); - if(tidx == 0xFFFFFFFF){ // Problem with the image, for instance, an unsupported bitmap16 type + if (tidx == 0xFFFFFFFF) { // Problem with the image, for instance, an unsupported bitmap16 type double r, g, b; - r = SP_COLOR_U_TO_F( U_RGBAGetR(d->dc[d->level].textColor)); - g = SP_COLOR_U_TO_F( U_RGBAGetG(d->dc[d->level].textColor)); - b = SP_COLOR_U_TO_F( U_RGBAGetB(d->dc[d->level].textColor)); - d->dc[d->level].style.fill.value.color.set( r, g, b ); + r = SP_COLOR_U_TO_F(U_RGBAGetR(d->dc[d->level].textColor)); + g = SP_COLOR_U_TO_F(U_RGBAGetG(d->dc[d->level].textColor)); + b = SP_COLOR_U_TO_F(U_RGBAGetB(d->dc[d->level].textColor)); + d->dc[d->level].style.fill.value.color.set(r, g, b); d->dc[d->level].fill_mode = DRAW_PAINT; - } - else { - d->dc[d->level].fill_idx = tidx; + } else { + d->dc[d->level].fill_idx = tidx; d->dc[d->level].fill_mode = DRAW_IMAGE; } d->dc[d->level].fill_set = true; @@ -1155,23 +1149,22 @@ Wmf::select_brush(PWMF_CALLBACK_DATA d, int index) } } - -void -Wmf::select_font(PWMF_CALLBACK_DATA d, int index) +void Wmf::select_font(PWMF_CALLBACK_DATA d, int index) { - char *record = nullptr; - const char *memfont; - const char *facename; - U_FONT font; + char *record = nullptr; + const char *memfont; + const char *facename; + U_FONT font; - if (index < 0 || index >= d->n_obj)return; + if (index < 0 || index >= d->n_obj) + return; record = d->wmf_obj[index].record; - if (!record)return; + if (!record) + return; d->dc[d->level].active_font = index; - - (void) U_WMRCREATEFONTINDIRECT_get(record, &memfont); - memcpy(&font,memfont,U_SIZE_FONT_CORE); //make sure it is in a properly aligned structure before touching it + (void)U_WMRCREATEFONTINDIRECT_get(record, &memfont); + memcpy(&font, memfont, U_SIZE_FONT_CORE); // make sure it is in a properly aligned structure before touching it facename = memfont + U_SIZE_FONT_CORE; /* The logfont information always starts with a U_LOGFONT structure but the U_WMRCREATEFONTINDIRECT @@ -1180,45 +1173,60 @@ Wmf::select_font(PWMF_CALLBACK_DATA d, int index) */ int cur_level = d->level; d->level = d->wmf_obj[index].level; - double font_size = pix_to_abs_size( d, font.Height ); + double font_size = pix_to_abs_size(d, font.Height); /* snap the font_size to the nearest 1/32nd of a point. (The size is converted from Pixels to points, snapped, and converted back.) See the notes where d->D2Pscale[XY] are set for the reason why. Typically this will set the font to the desired exact size. If some peculiar size was intended this will, at worst, make it .03125 off, which is unlikely to be a problem. */ - font_size = round(20.0 * 0.8 * font_size)/(20.0 * 0.8); + font_size = round(20.0 * 0.8 * font_size) / (20.0 * 0.8); d->level = cur_level; d->dc[d->level].style.font_size.computed = font_size; d->dc[d->level].style.font_weight.value = - font.Weight == U_FW_THIN ? SP_CSS_FONT_WEIGHT_100 : - font.Weight == U_FW_EXTRALIGHT ? SP_CSS_FONT_WEIGHT_200 : - font.Weight == U_FW_LIGHT ? SP_CSS_FONT_WEIGHT_300 : - font.Weight == U_FW_NORMAL ? SP_CSS_FONT_WEIGHT_400 : - font.Weight == U_FW_MEDIUM ? SP_CSS_FONT_WEIGHT_500 : - font.Weight == U_FW_SEMIBOLD ? SP_CSS_FONT_WEIGHT_600 : - font.Weight == U_FW_BOLD ? SP_CSS_FONT_WEIGHT_700 : - font.Weight == U_FW_EXTRABOLD ? SP_CSS_FONT_WEIGHT_800 : - font.Weight == U_FW_HEAVY ? SP_CSS_FONT_WEIGHT_900 : - font.Weight == U_FW_NORMAL ? SP_CSS_FONT_WEIGHT_NORMAL : - font.Weight == U_FW_BOLD ? SP_CSS_FONT_WEIGHT_BOLD : - font.Weight == U_FW_EXTRALIGHT ? SP_CSS_FONT_WEIGHT_LIGHTER : - font.Weight == U_FW_EXTRABOLD ? SP_CSS_FONT_WEIGHT_BOLDER : - SP_CSS_FONT_WEIGHT_NORMAL; + font.Weight == U_FW_THIN + ? SP_CSS_FONT_WEIGHT_100 + : font.Weight == U_FW_EXTRALIGHT + ? SP_CSS_FONT_WEIGHT_200 + : font.Weight == U_FW_LIGHT + ? SP_CSS_FONT_WEIGHT_300 + : font.Weight == U_FW_NORMAL + ? SP_CSS_FONT_WEIGHT_400 + : font.Weight == U_FW_MEDIUM + ? SP_CSS_FONT_WEIGHT_500 + : font.Weight == U_FW_SEMIBOLD + ? SP_CSS_FONT_WEIGHT_600 + : font.Weight == U_FW_BOLD + ? SP_CSS_FONT_WEIGHT_700 + : font.Weight == U_FW_EXTRABOLD + ? SP_CSS_FONT_WEIGHT_800 + : font.Weight == U_FW_HEAVY + ? SP_CSS_FONT_WEIGHT_900 + : font.Weight == U_FW_NORMAL + ? SP_CSS_FONT_WEIGHT_NORMAL + : font.Weight == U_FW_BOLD + ? SP_CSS_FONT_WEIGHT_BOLD + : font.Weight == U_FW_EXTRALIGHT + ? SP_CSS_FONT_WEIGHT_LIGHTER + : font.Weight == U_FW_EXTRABOLD + ? SP_CSS_FONT_WEIGHT_BOLDER + : SP_CSS_FONT_WEIGHT_NORMAL; d->dc[d->level].style.font_style.value = (font.Italic ? SP_CSS_FONT_STYLE_ITALIC : SP_CSS_FONT_STYLE_NORMAL); - d->dc[d->level].style.text_decoration_line.underline = font.Underline; + d->dc[d->level].style.text_decoration_line.underline = font.Underline; d->dc[d->level].style.text_decoration_line.line_through = font.StrikeOut; - d->dc[d->level].style.text_decoration_line.set = true; - d->dc[d->level].style.text_decoration_line.inherit = false; + d->dc[d->level].style.text_decoration_line.set = true; + d->dc[d->level].style.text_decoration_line.inherit = false; // malformed WMF with empty filename may exist, ignore font change if encountered - if(d->dc[d->level].font_name)free(d->dc[d->level].font_name); - if(*facename){ + if (d->dc[d->level].font_name) + free(d->dc[d->level].font_name); + if (*facename) { d->dc[d->level].font_name = strdup(facename); + } else { // Malformed WMF might specify an empty font name + d->dc[d->level].font_name = strdup("Arial"); // Default font, WMF spec says device can pick whatever it wants } - else { // Malformed WMF might specify an empty font name - d->dc[d->level].font_name = strdup("Arial"); // Default font, WMF spec says device can pick whatever it wants - } - d->dc[d->level].style.baseline_shift.value = round((double)((font.Escapement + 3600) % 3600) / 10.0); // use baseline_shift instead of text_transform to avoid overflow + d->dc[d->level].style.baseline_shift.value = + round((double)((font.Escapement + 3600) % 3600) / 10.0); // use baseline_shift instead of text_transform to + // avoid overflow } /* Find the first free hole where an object may be stored. @@ -1226,79 +1234,84 @@ Wmf::select_font(PWMF_CALLBACK_DATA d, int index) */ int Wmf::insertable_object(PWMF_CALLBACK_DATA d) { - int index = d->low_water; // Start looking from here, it may already have been filled - while(index < d->n_obj && d->wmf_obj[index].record != nullptr){ index++; } - if(index >= d->n_obj)return(-1); // this is a big problem, percolate it back up so the program can get out of this gracefully + int index = d->low_water; // Start looking from here, it may already have been filled + while (index < d->n_obj && d->wmf_obj[index].record != nullptr) { + index++; + } + if (index >= d->n_obj) + return (-1); // this is a big problem, percolate it back up so the program can get out of this gracefully d->low_water = index; // Could probably be index+1 - return(index); + return (index); } -void -Wmf::delete_object(PWMF_CALLBACK_DATA d, int index) +void Wmf::delete_object(PWMF_CALLBACK_DATA d, int index) { if (index >= 0 && index < d->n_obj) { // If the active object is deleted set default draw values - if(index == d->dc[d->level].active_pen){ // Use default pen: solid, black, 1 pixel wide - d->dc[d->level].active_pen = -1; - d->dc[d->level].style.stroke_dasharray.set = false; - d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_SQUARE; // U_PS_ENDCAP_SQUARE + if (index == d->dc[d->level].active_pen) { // Use default pen: solid, black, 1 pixel wide + d->dc[d->level].active_pen = -1; + d->dc[d->level].style.stroke_dasharray.set = false; + d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_SQUARE; // U_PS_ENDCAP_SQUARE d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_MITER; // U_PS_JOIN_MITER; - d->dc[d->level].stroke_set = true; - d->dc[d->level].style.stroke_width.value = 1.0; - d->dc[d->level].style.stroke.value.color.set( 0, 0, 0 ); - } - else if(index == d->dc[d->level].active_brush){ - d->dc[d->level].active_brush = -1; - d->dc[d->level].fill_set = false; - } - else if(index == d->dc[d->level].active_font){ - d->dc[d->level].active_font = -1; - if(d->dc[d->level].font_name){ free(d->dc[d->level].font_name);} - d->dc[d->level].font_name = strdup("Arial"); // Default font, WMF spec says device can pick whatever it wants - d->dc[d->level].style.font_size.computed = 16.0; - d->dc[d->level].style.font_weight.value = SP_CSS_FONT_WEIGHT_400; - d->dc[d->level].style.font_style.value = SP_CSS_FONT_STYLE_NORMAL; - d->dc[d->level].style.text_decoration_line.underline = false; + d->dc[d->level].stroke_set = true; + d->dc[d->level].style.stroke_width.value = 1.0; + d->dc[d->level].style.stroke.value.color.set(0, 0, 0); + } else if (index == d->dc[d->level].active_brush) { + d->dc[d->level].active_brush = -1; + d->dc[d->level].fill_set = false; + } else if (index == d->dc[d->level].active_font) { + d->dc[d->level].active_font = -1; + if (d->dc[d->level].font_name) { + free(d->dc[d->level].font_name); + } + d->dc[d->level].font_name = + strdup("Arial"); // Default font, WMF spec says device can pick whatever it wants + d->dc[d->level].style.font_size.computed = 16.0; + d->dc[d->level].style.font_weight.value = SP_CSS_FONT_WEIGHT_400; + d->dc[d->level].style.font_style.value = SP_CSS_FONT_STYLE_NORMAL; + d->dc[d->level].style.text_decoration_line.underline = false; d->dc[d->level].style.text_decoration_line.line_through = false; - d->dc[d->level].style.baseline_shift.value = 0; + d->dc[d->level].style.baseline_shift.value = 0; } - d->wmf_obj[index].type = 0; -// We are keeping a copy of the WMR rather than just a structure. Currently that is not necessary as the entire -// WMF is read in at once and is stored in a big malloc. However, in past versions it was handled -// record by record, and we might need to do that again at some point in the future if we start running into WMF -// files too big to fit into memory. + // We are keeping a copy of the WMR rather than just a structure. Currently that is not necessary as the entire + // WMF is read in at once and is stored in a big malloc. However, in past versions it was handled + // record by record, and we might need to do that again at some point in the future if we start running into WMF + // files too big to fit into memory. if (d->wmf_obj[index].record) free(d->wmf_obj[index].record); d->wmf_obj[index].record = nullptr; - if(index < d->low_water)d->low_water = index; + if (index < d->low_water) + d->low_water = index; } } - // returns the new index, or -1 on error. int Wmf::insert_object(PWMF_CALLBACK_DATA d, int type, const char *record) { int index = insertable_object(d); - if(index>=0){ + if (index >= 0) { d->wmf_obj[index].type = type; d->wmf_obj[index].level = d->level; d->wmf_obj[index].record = wmr_dup(record); } - return(index); + return (index); } - /** \fn create a UTF-32LE buffer and fill it with UNICODE unknown character \param count number of copies of the Unicode unknown character to fill with */ -uint32_t *Wmf::unknown_chars(size_t count){ - uint32_t *res = (uint32_t *) malloc(sizeof(uint32_t) * (count + 1)); - if(!res)throw "Inkscape fatal memory allocation error - cannot continue"; - for(uint32_t i=0; idc[d->level].clip_id){ + if (d->dc[d->level].clip_id) { tmp_image << "\tclip-path=\"url(#clipWmfPath" << d->dc[d->level].clip_id << ")\"\n"; } - tmp_image << " y=\"" << dy << "\"\n x=\"" << dx <<"\"\n "; + tmp_image << " y=\"" << dy << "\"\n x=\"" << dx << "\"\n "; MEMPNG mempng; // PNG in memory comes back in this mempng.buffer = nullptr; - char *rgba_px = nullptr; // RGBA pixels - char *sub_px = nullptr; // RGBA pixels, subarray - const char *px = nullptr; // DIB pixels - const U_RGBQUAD *ct = nullptr; // color table + char *rgba_px = nullptr; // RGBA pixels + char *sub_px = nullptr; // RGBA pixels, subarray + const char *px = nullptr; // DIB pixels + const U_RGBQUAD *ct = nullptr; // color table uint32_t numCt; - int32_t width, height, colortype, invert; // if needed these values will be set in wget_DIB_params - if(iUsage == U_DIB_RGB_COLORS){ + int32_t width, height, colortype, invert; // if needed these values will be set in wget_DIB_params + if (iUsage == U_DIB_RGB_COLORS) { // next call returns pointers and values, but allocates no memory dibparams = wget_DIB_params(dib, &px, &ct, &numCt, &width, &height, &colortype, &invert); - if(dibparams == U_BI_RGB){ - if(sw == 0 || sh == 0){ + if (dibparams == U_BI_RGB) { + if (sw == 0 || sh == 0) { sw = width; sh = height; } - if(!DIB_to_RGBA( - px, // DIB pixel array - ct, // DIB color table - numCt, // DIB color table number of entries - &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. - width, // Width of pixel array - height, // Height of pixel array - colortype, // DIB BitCount Enumeration - numCt, // Color table used if not 0 - invert // If DIB rows are in opposite order from RGBA rows - )){ - sub_px = RGBA_to_RGBA( // returns either a subset (side effect: frees rgba_px) or NULL (for subset == entire image) + if (!DIB_to_RGBA(px, // DIB pixel array + ct, // DIB color table + numCt, // DIB color table number of entries + &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. + width, // Width of pixel array + height, // Height of pixel array + colortype, // DIB BitCount Enumeration + numCt, // Color table used if not 0 + invert // If DIB rows are in opposite order from RGBA rows + )) { + sub_px = RGBA_to_RGBA( // returns either a subset (side effect: frees rgba_px) or NULL (for subset == + // entire image) rgba_px, // full pixel array from DIB width, // Width of pixel array height, // Height of pixel array - sx,sy, // starting point in pixel array - &sw,&sh // columns/rows to extract from the pixel array (output array size) + sx, sy, // starting point in pixel array + &sw, &sh // columns/rows to extract from the pixel array (output array size) ); - if(!sub_px)sub_px=rgba_px; - toPNG( // Get the image from the RGBA px into mempng - &mempng, - sw, sh, // size of the extracted pixel array - sub_px - ); + if (!sub_px) + sub_px = rgba_px; + toPNG( // Get the image from the RGBA px into mempng + &mempng, sw, sh, // size of the extracted pixel array + sub_px); free(sub_px); } } } - gchar *base64String=nullptr; - if(dibparams == U_BI_JPEG){ // image was binary jpg in source file + gchar *base64String = nullptr; + if (dibparams == U_BI_JPEG) { // image was binary jpg in source file tmp_image << " xlink:href=\"data:image/jpeg;base64,"; - base64String = g_base64_encode((guchar*) px, numCt ); - } - else if(dibparams==U_BI_PNG){ // image was binary png in source file + base64String = g_base64_encode((guchar *)px, numCt); + } else if (dibparams == U_BI_PNG) { // image was binary png in source file tmp_image << " xlink:href=\"data:image/png;base64,"; - base64String = g_base64_encode((guchar*) px, numCt ); - } - else if(mempng.buffer){ // image was DIB in source file, converted to png in this routine + base64String = g_base64_encode((guchar *)px, numCt); + } else if (mempng.buffer) { // image was DIB in source file, converted to png in this routine tmp_image << " xlink:href=\"data:image/png;base64,"; - base64String = g_base64_encode((guchar*) mempng.buffer, mempng.size ); + base64String = g_base64_encode((guchar *)mempng.buffer, mempng.size); free(mempng.buffer); - } - else { // unknown or unsupported image type or failed conversion, insert the common bad image picture + } else { // unknown or unsupported image type or failed conversion, insert the common bad image picture tmp_image << " xlink:href=\"data:image/png;base64,"; base64String = bad_image_png(); } @@ -1416,73 +1425,73 @@ void Wmf::common_dib_to_image(PWMF_CALLBACK_DATA d, const char *dib, \param sy (int) source y in src image pixels \param iUsage */ -void Wmf::common_bm16_to_image(PWMF_CALLBACK_DATA d, U_BITMAP16 Bm16, const char *px, - double dx, double dy, double dw, double dh, int sx, int sy, int sw, int sh){ - +void Wmf::common_bm16_to_image(PWMF_CALLBACK_DATA d, U_BITMAP16 Bm16, const char *px, double dx, double dy, double dw, + double dh, int sx, int sy, int sw, int sh) +{ SVGOStringStream tmp_image; tmp_image << "\n\t dc[d->level].clip_id){ + if (d->dc[d->level].clip_id) { tmp_image << "\tclip-path=\"url(#clipWmfPath" << d->dc[d->level].clip_id << ")\"\n"; } - tmp_image << " y=\"" << dy << "\"\n x=\"" << dx <<"\"\n "; + tmp_image << " y=\"" << dy << "\"\n x=\"" << dx << "\"\n "; MEMPNG mempng; // PNG in memory comes back in this mempng.buffer = nullptr; - char *rgba_px = nullptr; // RGBA pixels - char *sub_px = nullptr; // RGBA pixels, subarray - const U_RGBQUAD *ct = nullptr; // color table + char *rgba_px = nullptr; // RGBA pixels + char *sub_px = nullptr; // RGBA pixels, subarray + const U_RGBQUAD *ct = nullptr; // color table int32_t width, height, colortype, numCt, invert; - numCt = 0; - width = Bm16.Width; // bitmap width in pixels. - height = Bm16.Height; // bitmap height in scan lines. - colortype = Bm16.BitsPixel; // seems to be BitCount Enumeration - invert = 0; + numCt = 0; + width = Bm16.Width; // bitmap width in pixels. + height = Bm16.Height; // bitmap height in scan lines. + colortype = Bm16.BitsPixel; // seems to be BitCount Enumeration + invert = 0; - if(sw == 0 || sh == 0){ + if (sw == 0 || sh == 0) { sw = width; sh = height; } - if(colortype < 16)return; // these would need a colortable if they were a dib, no idea what bm16 is supposed to do instead. - - if(!DIB_to_RGBA(// This is not really a dib, but close enough so that it still works. - px, // DIB pixel array - ct, // DIB color table (always NULL here) - numCt, // DIB color table number of entries (always 0) - &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. - width, // Width of pixel array - height, // Height of pixel array - colortype, // DIB BitCount Enumeration - numCt, // Color table used if not 0 - invert // If DIB rows are in opposite order from RGBA rows - )){ - sub_px = RGBA_to_RGBA( // returns either a subset (side effect: frees rgba_px) or NULL (for subset == entire image) - rgba_px, // full pixel array from DIB - width, // Width of pixel array - height, // Height of pixel array - sx,sy, // starting point in pixel array - &sw,&sh // columns/rows to extract from the pixel array (output array size) - ); - - if(!sub_px)sub_px=rgba_px; - toPNG( // Get the image from the RGBA px into mempng - &mempng, - sw, sh, // size of the extracted pixel array - sub_px - ); + if (colortype < 16) + return; // these would need a colortable if they were a dib, no idea what bm16 is supposed to do instead. + + if (!DIB_to_RGBA( // This is not really a dib, but close enough so that it still works. + px, // DIB pixel array + ct, // DIB color table (always NULL here) + numCt, // DIB color table number of entries (always 0) + &rgba_px, // U_RGBA pixel array (32 bits), created by this routine, caller must free. + width, // Width of pixel array + height, // Height of pixel array + colortype, // DIB BitCount Enumeration + numCt, // Color table used if not 0 + invert // If DIB rows are in opposite order from RGBA rows + )) { + sub_px = + RGBA_to_RGBA( // returns either a subset (side effect: frees rgba_px) or NULL (for subset == entire image) + rgba_px, // full pixel array from DIB + width, // Width of pixel array + height, // Height of pixel array + sx, sy, // starting point in pixel array + &sw, &sh // columns/rows to extract from the pixel array (output array size) + ); + + if (!sub_px) + sub_px = rgba_px; + toPNG( // Get the image from the RGBA px into mempng + &mempng, sw, sh, // size of the extracted pixel array + sub_px); free(sub_px); } - gchar *base64String=nullptr; - if(mempng.buffer){ // image was Bm16 in source file, converted to png in this routine + gchar *base64String = nullptr; + if (mempng.buffer) { // image was Bm16 in source file, converted to png in this routine tmp_image << " xlink:href=\"data:image/png;base64,"; - base64String = g_base64_encode((guchar*) mempng.buffer, mempng.size ); + base64String = g_base64_encode((guchar *)mempng.buffer, mempng.size); free(mempng.buffer); - } - else { // unknown or unsupported image type or failed conversion, insert the common bad image picture + } else { // unknown or unsupported image type or failed conversion, insert the common bad image picture tmp_image << " xlink:href=\"data:image/png;base64,"; base64String = bad_image_png(); } @@ -1505,144 +1514,151 @@ void Wmf::common_bm16_to_image(PWMF_CALLBACK_DATA d, U_BITMAP16 Bm16, const char \param length length in bytes of contents \param d Inkscape data structures returned by this call */ -//THis was a callback, just build it into a normal function +// THis was a callback, just build it into a normal function int Wmf::myMetaFileProc(const char *contents, unsigned int length, PWMF_CALLBACK_DATA d) { - uint32_t off=0; - uint32_t wmr_mask; - int OK =1; - int file_status=1; - TCHUNK_SPECS tsp; - uint8_t iType; - int nSize; // size of the current record, in bytes, or an error value if <=0 - const char *blimit = contents + length; // 1 byte past the end of the last record + uint32_t off = 0; + uint32_t wmr_mask; + int OK = 1; + int file_status = 1; + TCHUNK_SPECS tsp; + uint8_t iType; + int nSize; // size of the current record, in bytes, or an error value if <=0 + const char *blimit = contents + length; // 1 byte past the end of the last record /* variables used to retrieve data from WMF records */ - uint16_t utmp16; - U_POINT16 pt16; // any point - U_RECT16 rc; // any rectangle, usually a bounding rectangle - U_POINT16 Dst; // Destination coordinates - U_POINT16 cDst; // Destination w,h, if different from Src - U_POINT16 Src; // Source coordinates - U_POINT16 cSrc; // Source w,h, if different from Dst - U_POINT16 cwh; // w,h, if Src and Dst use the same values - uint16_t cUsage; // colorusage enumeration - uint32_t dwRop3; // raster operations, these are only barely supported here - const char *dib; // DIB style image structure - U_BITMAP16 Bm16; // Bitmap16 style image structure - const char *px; // Image for Bm16 - uint16_t cPts; // number of points in the next variable - const char *points; // any list of U_POINT16, may not be aligned - int16_t tlen; // length of returned text, in bytes - const char *text; // returned text, Latin1 encoded - uint16_t Opts; - const int16_t *dx; // character spacing for one text mode, inkscape ignores this - double left, right, top, bottom; // values used, because a bounding rect can have values reversed L<->R, T<->B - - uint16_t tbkMode = U_TRANSPARENT; // holds proposed change to bkMode, if text is involved saving these to the DC must wait until the text is written - U_COLORREF tbkColor = U_RGB(255, 255, 255); // holds proposed change to bkColor + uint16_t utmp16; + U_POINT16 pt16; // any point + U_RECT16 rc; // any rectangle, usually a bounding rectangle + U_POINT16 Dst; // Destination coordinates + U_POINT16 cDst; // Destination w,h, if different from Src + U_POINT16 Src; // Source coordinates + U_POINT16 cSrc; // Source w,h, if different from Dst + U_POINT16 cwh; // w,h, if Src and Dst use the same values + uint16_t cUsage; // colorusage enumeration + uint32_t dwRop3; // raster operations, these are only barely supported here + const char *dib; // DIB style image structure + U_BITMAP16 Bm16; // Bitmap16 style image structure + const char *px; // Image for Bm16 + uint16_t cPts; // number of points in the next variable + const char *points; // any list of U_POINT16, may not be aligned + int16_t tlen; // length of returned text, in bytes + const char *text; // returned text, Latin1 encoded + uint16_t Opts; + const int16_t *dx; // character spacing for one text mode, inkscape ignores this + double left, right, top, bottom; // values used, because a bounding rect can have values reversed L<->R, T<->B + + uint16_t tbkMode = U_TRANSPARENT; // holds proposed change to bkMode, if text is involved saving these to the DC + // must wait until the text is written + U_COLORREF tbkColor = U_RGB(255, 255, 255); // holds proposed change to bkColor // code for end user debugging - int wDbgRecord=0; - int wDbgComment=0; - int wDbgFinal=0; - char const* wDbgString = getenv( "INKSCAPE_DBG_WMF" ); - if ( wDbgString != nullptr ) { - if(strstr(wDbgString,"RECORD")){ wDbgRecord = 1; } - if(strstr(wDbgString,"COMMENT")){ wDbgComment = 1; } - if(strstr(wDbgString,"FINAL")){ wDbgFinal = 1; } + int wDbgRecord = 0; + int wDbgComment = 0; + int wDbgFinal = 0; + char const *wDbgString = getenv("INKSCAPE_DBG_WMF"); + if (wDbgString != nullptr) { + if (strstr(wDbgString, "RECORD")) { + wDbgRecord = 1; + } + if (strstr(wDbgString, "COMMENT")) { + wDbgComment = 1; + } + if (strstr(wDbgString, "FINAL")) { + wDbgFinal = 1; + } } /* initialize the tsp for text reassembly */ - tsp.string = nullptr; - tsp.ori = 0.0; /* degrees */ - tsp.fs = 12.0; /* font size */ - tsp.x = 0.0; - tsp.y = 0.0; - tsp.boff = 0.0; /* offset to baseline from LL corner of bounding rectangle, changes with fs and taln*/ - tsp.vadvance = 0.0; /* meaningful only when a complex contains two or more lines */ - tsp.taln = ALILEFT + ALIBASE; - tsp.ldir = LDIR_LR; - tsp.spaces = 0; // this field is only used for debugging - tsp.color.Red = 0; /* RGB Black */ - tsp.color.Green = 0; /* RGB Black */ - tsp.color.Blue = 0; /* RGB Black */ - tsp.color.Reserved = 0; /* not used */ - tsp.italics = 0; - tsp.weight = 80; + tsp.string = nullptr; + tsp.ori = 0.0; /* degrees */ + tsp.fs = 12.0; /* font size */ + tsp.x = 0.0; + tsp.y = 0.0; + tsp.boff = 0.0; /* offset to baseline from LL corner of bounding rectangle, changes with fs and taln*/ + tsp.vadvance = 0.0; /* meaningful only when a complex contains two or more lines */ + tsp.taln = ALILEFT + ALIBASE; + tsp.ldir = LDIR_LR; + tsp.spaces = 0; // this field is only used for debugging + tsp.color.Red = 0; /* RGB Black */ + tsp.color.Green = 0; /* RGB Black */ + tsp.color.Blue = 0; /* RGB Black */ + tsp.color.Reserved = 0; /* not used */ + tsp.italics = 0; + tsp.weight = 80; tsp.decoration = TXTDECOR_NONE; - tsp.condensed = 100; - tsp.co = 0; - tsp.fi_idx = -1; /* set to an invalid */ - tsp.rt_tidx = -1; /* set to an invalid */ + tsp.condensed = 100; + tsp.co = 0; + tsp.fi_idx = -1; /* set to an invalid */ + tsp.rt_tidx = -1; /* set to an invalid */ SVGOStringStream dbg_str; - /* There is very little information in WMF headers, get what is there. In many cases pretty much everything will have to - default. If there is no placeable header we know pretty much nothing about the size of the page, in which case - assume that it is 1440 WMF pixels/inch and make the page A4 landscape. That is almost certainly the wrong page size + /* There is very little information in WMF headers, get what is there. In many cases pretty much everything will + have to default. If there is no placeable header we know pretty much nothing about the size of the page, in + which case assume that it is 1440 WMF pixels/inch and make the page A4 landscape. That is almost certainly the + wrong page size but it has to be set to something, and nothing horrible happens if the drawing goes off the page. */ { - U_WMRPLACEABLE Placeable; U_WMRHEADER Header; off = 0; nSize = wmfheader_get(contents, blimit, &Placeable, &Header); if (!nSize) { - return(0); + return (0); } - if(!Header.nObjects){ Header.nObjects = 256; }// there _may_ be WMF files with no objects, more likely it is corrupt. Try to use it anyway. - d->n_obj = Header.nObjects; - d->wmf_obj = new WMF_OBJECT[d->n_obj]; - d->low_water = 0; // completely empty at this point, so start searches at 0 + if (!Header.nObjects) { + Header.nObjects = 256; + } // there _may_ be WMF files with no objects, more likely it is corrupt. Try to use it anyway. + d->n_obj = Header.nObjects; + d->wmf_obj = new WMF_OBJECT[d->n_obj]; + d->low_water = 0; // completely empty at this point, so start searches at 0 // Init the new wmf_obj list elements to null, provided the // dynamic allocation succeeded. - if ( d->wmf_obj != nullptr ) - { - for( int i=0; i < d->n_obj; ++i ) + if (d->wmf_obj != nullptr) { + for (int i = 0; i < d->n_obj; ++i) d->wmf_obj[i].record = nullptr; - } //if + } // if - if(!Placeable.Inch){ Placeable.Inch= 1440; } - if(!Placeable.Dst.right && !Placeable.Dst.left){ // no page size has been supplied + if (!Placeable.Inch) { + Placeable.Inch = 1440; + } + if (!Placeable.Dst.right && !Placeable.Dst.left) { // no page size has been supplied // This is gross, scan forward looking for a SETWINDOWEXT record, use the first one found to // define the page size int hold_nSize = off = nSize; - Placeable.Dst.left = 0; - Placeable.Dst.top = 0; - while(OK){ + Placeable.Dst.left = 0; + Placeable.Dst.top = 0; + while (OK) { nSize = U_WMRRECSAFE_get(contents + off, blimit); - if(nSize){ - iType = *(uint8_t *)(contents + off + offsetof(U_METARECORD, iType ) ); - if(iType == U_WMR_SETWINDOWEXT){ - OK=0; - (void) U_WMRSETWINDOWEXT_get(contents + off, &Dst); - Placeable.Dst.right = Dst.x; + if (nSize) { + iType = *(uint8_t *)(contents + off + offsetof(U_METARECORD, iType)); + if (iType == U_WMR_SETWINDOWEXT) { + OK = 0; + (void)U_WMRSETWINDOWEXT_get(contents + off, &Dst); + Placeable.Dst.right = Dst.x; Placeable.Dst.bottom = Dst.y; - } - else if(iType == U_WMR_EOF){ - OK=0; + } else if (iType == U_WMR_EOF) { + OK = 0; // Really messed up WMF, have to set the page to something, make it A4 horizontal - Placeable.Dst.right = round(((double) Placeable.Inch) * 297.0/25.4); - Placeable.Dst.bottom = round(((double) Placeable.Inch) * 210.0/25.4); - } - else { + Placeable.Dst.right = round(((double)Placeable.Inch) * 297.0 / 25.4); + Placeable.Dst.bottom = round(((double)Placeable.Inch) * 210.0 / 25.4); + } else { off += nSize; } - } - else { - return(0); + } else { + return (0); } } - off=0; + off = 0; nSize = hold_nSize; - OK=1; + OK = 1; } // drawing size in WMF pixels - d->PixelsInX = Placeable.Dst.right - Placeable.Dst.left + 1; - d->PixelsInY = Placeable.Dst.bottom - Placeable.Dst.top + 1; + d->PixelsInX = Placeable.Dst.right - Placeable.Dst.left + 1; + d->PixelsInY = Placeable.Dst.bottom - Placeable.Dst.top + 1; /* Set values for Window and ViewPort extents to 0 - not defined yet. @@ -1654,22 +1670,23 @@ int Wmf::myMetaFileProc(const char *contents, unsigned int length, PWMF_CALLBACK If a placeable header is used, and later a windoworg/windowext are found, then the placeable information will be ignored. */ - d->ulCornerInX = Placeable.Dst.left; - d->ulCornerInY = Placeable.Dst.top; + d->ulCornerInX = Placeable.Dst.left; + d->ulCornerInY = Placeable.Dst.top; - d->E2IdirY = 1.0; // assume MM_ANISOTROPIC, if not, this will be changed later - d->D2PscaleX = d->D2PscaleY = Inkscape::Util::Quantity::convert(1, "in", "px")/(double) Placeable.Inch; - trinfo_load_qe(d->tri, d->D2PscaleX); /* quantization error that will affect text positions */ + d->E2IdirY = 1.0; // assume MM_ANISOTROPIC, if not, this will be changed later + d->D2PscaleX = d->D2PscaleY = Inkscape::Util::Quantity::convert(1, "in", "px") / (double)Placeable.Inch; + trinfo_load_qe(d->tri, d->D2PscaleX); /* quantization error that will affect text positions */ // drawing size in Inkscape pixels d->PixelsOutX = d->PixelsInX * d->D2PscaleX; d->PixelsOutY = d->PixelsInY * d->D2PscaleY; // Upper left corner in Inkscape units - d->ulCornerOutX = d->ulCornerInX * d->D2PscaleX; + d->ulCornerOutX = d->ulCornerInX * d->D2PscaleX; d->ulCornerOutY = d->ulCornerInY * d->E2IdirY * d->D2PscaleY; - d->dc[0].style.stroke_width.value = pix_to_abs_size( d, 1 ); // This could not be set until the size of the WMF was known + d->dc[0].style.stroke_width.value = + pix_to_abs_size(d, 1); // This could not be set until the size of the WMF was known dbg_str << "\n"; d->outdef += "\n"; @@ -1679,1438 +1696,1490 @@ int Wmf::myMetaFileProc(const char *contents, unsigned int length, PWMF_CALLBACK tmp_outdef << " xmlns:svg=\"http://www.w3.org/2000/svg\"\n"; tmp_outdef << " xmlns=\"http://www.w3.org/2000/svg\"\n"; tmp_outdef << " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"; - tmp_outdef << " xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"\n"; // needed for sodipodi:role + tmp_outdef << " xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"\n"; // needed for + // sodipodi:role tmp_outdef << " version=\"1.0\"\n"; - tmp_outdef << - " width=\"" << Inkscape::Util::Quantity::convert(d->PixelsOutX, "px", "mm") << "mm\"\n" << - " height=\"" << Inkscape::Util::Quantity::convert(d->PixelsOutY, "px", "mm") << "mm\">\n"; + tmp_outdef << " width=\"" << Inkscape::Util::Quantity::convert(d->PixelsOutX, "px", "mm") << "mm\"\n" + << " height=\"" << Inkscape::Util::Quantity::convert(d->PixelsOutY, "px", "mm") << "mm\">\n"; d->outdef += tmp_outdef.str().c_str(); - d->outdef += ""; // temporary end of header + d->outdef += ""; // temporary end of header // d->defs holds any defines which are read in. - - } + while (OK) { + if (off >= length) { + return (0); // normally should exit from while after WMREOF sets OK to false. + } + contents += nSize; // pointer to the start of the next record + off += nSize; // offset from beginning of buffer to the start of the next record + /* Currently this is a weaker check than for EMF, it only checks the size of the constant part + of the record */ + nSize = U_WMRRECSAFE_get(contents, blimit); + if (!nSize) { + file_status = 0; + break; + } - while(OK){ - if (off>=length) { - return(0); //normally should exit from while after WMREOF sets OK to false. - } - contents += nSize; // pointer to the start of the next record - off += nSize; // offset from beginning of buffer to the start of the next record - - /* Currently this is a weaker check than for EMF, it only checks the size of the constant part - of the record */ - nSize = U_WMRRECSAFE_get(contents, blimit); - if(!nSize) { - file_status = 0; - break; - } - - iType = *(uint8_t *)(contents + offsetof(U_METARECORD, iType ) ); - - wmr_mask = U_wmr_properties(iType); - if (wmr_mask == U_WMR_INVALID) { - file_status = 0; - break; - } -// At run time define environment variable INKSCAPE_DBG_WMF to include string RECORD. -// Users may employ this to track down toxic records - if(wDbgRecord){ - std::cout << "record type: " << iType << " name " << U_wmr_names(iType) << " length: " << nSize << " offset: " << off <dirty:"<< d->tri->dirty << " wmr_mask: " << std::hex << wmr_mask << std::dec << std::endl; - - // incompatible change to text drawing detected (color or background change) forces out existing text - // OR - // next record is valid type and forces pending text to be drawn immediately - if ((d->dc[d->level].dirty & DIRTY_TEXT) || ((wmr_mask != U_WMR_INVALID) && (wmr_mask & U_DRAW_TEXT) && d->tri->dirty)){ - TR_layout_analyze(d->tri); - if (d->dc[d->level].clip_id){ - SVGOStringStream tmp_clip; - tmp_clip << "\ndc[d->level].clip_id << ")\"\n>"; - d->outsvg += tmp_clip.str().c_str(); - } - TR_layout_2_svg(d->tri); - SVGOStringStream ts; - ts << d->tri->out; - d->outsvg += ts.str().c_str(); - d->tri = trinfo_clear(d->tri); - if (d->dc[d->level].clip_id){ - d->outsvg += "\n\n"; - } - } - if(d->dc[d->level].dirty){ //Apply the delayed background changes, clear the flag - d->dc[d->level].bkMode = tbkMode; - memcpy(&(d->dc[d->level].bkColor),&tbkColor, sizeof(U_COLORREF)); - - if(d->dc[d->level].dirty & DIRTY_TEXT){ - // U_COLORREF and TRCOLORREF are exactly the same in memory, but the compiler needs some convincing... - if(tbkMode == U_TRANSPARENT){ (void) trinfo_load_bk(d->tri, BKCLR_NONE, *(TRCOLORREF *) &tbkColor); } - else { (void) trinfo_load_bk(d->tri, BKCLR_LINE, *(TRCOLORREF *) &tbkColor); } // Opaque + wmr_mask = U_wmr_properties(iType); + if (wmr_mask == U_WMR_INVALID) { + file_status = 0; + break; } - - /* It is possible to have a series of EMF records that would result in - the following creating hash patterns which are never used. For instance, if - there were a series of records that changed the background color but did nothing - else. - */ - if((d->dc[d->level].fill_mode == DRAW_PATTERN) && (d->dc[d->level].dirty & DIRTY_FILL)){ - select_brush(d, d->dc[d->level].fill_recidx); + // At run time define environment variable INKSCAPE_DBG_WMF to include string RECORD. + // Users may employ this to track down toxic records + if (wDbgRecord) { + std::cout << "record type: " << iType << " name " << U_wmr_names(iType) << " length: " << nSize + << " offset: " << off << std::endl; } - - d->dc[d->level].dirty = 0; - } -//std::cout << "BEFORE DRAW logic d->mask: " << std::hex << d->mask << " wmr_mask: " << wmr_mask << std::dec << std::endl; -/* -std::cout << "BEFORE DRAW" - << " test0 " << ( d->mask & U_DRAW_VISIBLE) - << " test1 " << ( d->mask & U_DRAW_FORCE) - << " test2 " << (wmr_mask & U_DRAW_ALTERS) - << " test2.5 " << ((d->mask & U_DRAW_NOFILL) != (wmr_mask & U_DRAW_NOFILL) ) - << " test3 " << (wmr_mask & U_DRAW_VISIBLE) - << " test4 " << !(d->mask & U_DRAW_ONLYTO) - << " test5 " << ((d->mask & U_DRAW_ONLYTO) && !(wmr_mask & U_DRAW_ONLYTO) ) - << std::endl; -*/ - /* spurious moveto records should not affect the drawing. However, they set the NOFILL - bit and that messes up the logic about when to emit a path. So prune out any - stray moveto records. That is those which were never followed by a lineto. - */ - if((d->mask & U_DRAW_NOFILL) && !(d->mask & U_DRAW_VISIBLE) && - !(wmr_mask & U_DRAW_ONLYTO) && (wmr_mask & U_DRAW_VISIBLE)){ - d->mask ^= U_DRAW_NOFILL; - } + SVGOStringStream tmp_path; + SVGOStringStream tmp_str; - if( - (wmr_mask != U_WMR_INVALID) && // next record is valid type - (d->mask & U_DRAW_VISIBLE) && // This record is drawable - ( - (d->mask & U_DRAW_FORCE) || // This draw is forced by STROKE/FILL/STROKEANDFILL PATH - (wmr_mask & U_DRAW_ALTERS) || // Next record would alter the drawing environment in some way - ((d->mask & U_DRAW_NOFILL) != (wmr_mask & U_DRAW_NOFILL)) || // Fill<->!Fill requires a draw between - ( (wmr_mask & U_DRAW_VISIBLE) && // Next record is visible... - ( - ( !(d->mask & U_DRAW_ONLYTO) ) || // Non *TO records cannot be followed by any Visible - ((d->mask & U_DRAW_ONLYTO) && !(wmr_mask & U_DRAW_ONLYTO) )// *TO records can only be followed by other *TO records - ) - ) - ) - ){ -// std::cout << "PATH DRAW at TOP <<+++++++++++++++++++++++++++++++++++++" << std::endl; - if(!(d->path.empty())){ - d->outsvg += " outsvg += "\n\t"; - d->outsvg += "\n\td=\""; // this is the ONLY place d=" should be used!!!! - d->outsvg += d->path; - d->outsvg += " \" /> \n"; - d->path = ""; //reset the path - } - // reset the flags - d->mask = 0; - d->drawtype = 0; - } -// std::cout << "AFTER DRAW logic d->mask: " << std::hex << d->mask << " wmr_mask: " << wmr_mask << std::dec << std::endl; - switch (iType) - { - case U_WMR_EOF: - { - dbg_str << "\n"; + /* Uncomment the following to track down text problems */ + // std::cout << "tri->dirty:"<< d->tri->dirty << " wmr_mask: " << std::hex << wmr_mask << std::dec << std::endl; - d->outsvg = d->outdef + d->defs + "\n\n\n" + d->outsvg + "\n"; - OK=0; - break; - } - case U_WMR_SETBKCOLOR: - { - dbg_str << "\n"; - nSize = U_WMRSETBKCOLOR_get(contents, &tbkColor); - if(memcmp(&tbkColor, &(d->dc[d->level].bkColor), sizeof(U_COLORREF))){ - d->dc[d->level].dirty |= DIRTY_TEXT; - if(d->dc[d->level].fill_mode == DRAW_PATTERN){ d->dc[d->level].dirty |= DIRTY_FILL; } - tbkMode = d->dc[d->level].bkMode; + // incompatible change to text drawing detected (color or background change) forces out existing text + // OR + // next record is valid type and forces pending text to be drawn immediately + if ((d->dc[d->level].dirty & DIRTY_TEXT) || + ((wmr_mask != U_WMR_INVALID) && (wmr_mask & U_DRAW_TEXT) && d->tri->dirty)) { + TR_layout_analyze(d->tri); + if (d->dc[d->level].clip_id) { + SVGOStringStream tmp_clip; + tmp_clip << "\ndc[d->level].clip_id << ")\"\n>"; + d->outsvg += tmp_clip.str().c_str(); } - break; - } - case U_WMR_SETBKMODE:{ - dbg_str << "\n"; - nSize = U_WMRSETBKMODE_get(contents, &tbkMode); - if(tbkMode != d->dc[d->level].bkMode){ - d->dc[d->level].dirty |= DIRTY_TEXT; - if(tbkMode != d->dc[d->level].bkMode){ - if(d->dc[d->level].fill_mode == DRAW_PATTERN){ d->dc[d->level].dirty |= DIRTY_FILL; } - } - memcpy(&tbkColor,&(d->dc[d->level].bkColor),sizeof(U_COLORREF)); + TR_layout_2_svg(d->tri); + SVGOStringStream ts; + ts << d->tri->out; + d->outsvg += ts.str().c_str(); + d->tri = trinfo_clear(d->tri); + if (d->dc[d->level].clip_id) { + d->outsvg += "\n\n"; } - break; } - case U_WMR_SETMAPMODE: - { - dbg_str << "\n"; - nSize = U_WMRSETMAPMODE_get(contents, &utmp16); - switch (utmp16){ - case U_MM_TEXT: - default: - // Use all values from the header. - break; - /* For all of the following the indicated scale this will be encoded in WindowExtEx/ViewportExtex - and show up in ScaleIn[XY] - */ - case U_MM_LOMETRIC: // 1 LU = 0.1 mm, - case U_MM_HIMETRIC: // 1 LU = 0.01 mm - case U_MM_LOENGLISH: // 1 LU = 0.1 in - case U_MM_HIENGLISH: // 1 LU = 0.01 in - case U_MM_TWIPS: // 1 LU = 1/1440 in - d->E2IdirY = -1.0; - // Use d->D2Pscale[XY] values from the header. - break; - case U_MM_ISOTROPIC: // ScaleIn[XY] should be set elsewhere by SETVIEWPORTEXTEX and SETWINDOWEXTEX - case U_MM_ANISOTROPIC: - break; + if (d->dc[d->level].dirty) { // Apply the delayed background changes, clear the flag + d->dc[d->level].bkMode = tbkMode; + memcpy(&(d->dc[d->level].bkColor), &tbkColor, sizeof(U_COLORREF)); + + if (d->dc[d->level].dirty & DIRTY_TEXT) { + // U_COLORREF and TRCOLORREF are exactly the same in memory, but the compiler needs some convincing... + if (tbkMode == U_TRANSPARENT) { + (void)trinfo_load_bk(d->tri, BKCLR_NONE, *(TRCOLORREF *)&tbkColor); + } else { + (void)trinfo_load_bk(d->tri, BKCLR_LINE, *(TRCOLORREF *)&tbkColor); + } // Opaque } - break; - } - case U_WMR_SETROP2: - { - dbg_str << "\n"; - nSize = U_WMRSETROP2_get(contents, &utmp16); - d->dwRop2 = utmp16; - break; - } - case U_WMR_SETRELABS: dbg_str << "\n"; break; - case U_WMR_SETPOLYFILLMODE: - { - dbg_str << "\n"; - nSize = U_WMRSETPOLYFILLMODE_get(contents, &utmp16); - d->dc[d->level].style.fill_rule.value = - (utmp16 == U_ALTERNATE ? SP_WIND_RULE_NONZERO - : utmp16 == U_WINDING ? SP_WIND_RULE_INTERSECT : SP_WIND_RULE_NONZERO); - break; - } - case U_WMR_SETSTRETCHBLTMODE: - { - dbg_str << "\n"; - nSize = U_WMRSETSTRETCHBLTMODE_get(contents, &utmp16); - BLTmode = utmp16; - break; - } - case U_WMR_SETTEXTCHAREXTRA: dbg_str << "\n"; break; - case U_WMR_SETTEXTCOLOR: - { - dbg_str << "\n"; - nSize = U_WMRSETTEXTCOLOR_get(contents, &(d->dc[d->level].textColor)); - if(tbkMode != d->dc[d->level].bkMode){ - if(d->dc[d->level].fill_mode == DRAW_PATTERN){ d->dc[d->level].dirty |= DIRTY_FILL; } - } - // not text_dirty, because multicolored complex text is supported in libTERE - break; - } - case U_WMR_SETTEXTJUSTIFICATION: dbg_str << "\n"; break; - case U_WMR_SETWINDOWORG: - { - dbg_str << "\n"; - nSize = U_WMRSETWINDOWORG_get(contents, &d->dc[d->level].winorg); - d->ulCornerOutX = 0.0; // In the examples seen to date if this record is used with a placeable header, that header is ignored - d->ulCornerOutY = 0.0; - break; - } - case U_WMR_SETWINDOWEXT: - { - dbg_str << "\n"; - nSize = U_WMRSETWINDOWEXT_get(contents, &d->dc[d->level].sizeWnd); - - if (!d->dc[d->level].sizeWnd.x || !d->dc[d->level].sizeWnd.y) { - d->dc[d->level].sizeWnd = d->dc[d->level].sizeView; - if (!d->dc[d->level].sizeWnd.x || !d->dc[d->level].sizeWnd.y) { - d->dc[d->level].sizeWnd.x = d->PixelsOutX; - d->dc[d->level].sizeWnd.y = d->PixelsOutY; - } - } - else { - /* There are a lot WMF files in circulation with the x,y values in the setwindowext reversed. If this is detected, swap them. - There is a remote possibility that the strange scaling this implies was intended, and those will be rendered incorrectly */ - double Ox = d->PixelsOutX; - double Oy = d->PixelsOutY; - double Wx = d->dc[d->level].sizeWnd.x; - double Wy = d->dc[d->level].sizeWnd.y; - if(Wx != Wy && Geom::are_near(Ox/Wy, Oy/Wx, 1.01/MIN(Wx,Wy)) ){ - int tmp; - tmp = d->dc[d->level].sizeWnd.x; - d->dc[d->level].sizeWnd.x = d->dc[d->level].sizeWnd.y; - d->dc[d->level].sizeWnd.y = tmp; - } + /* It is possible to have a series of EMF records that would result in + the following creating hash patterns which are never used. For instance, if + there were a series of records that changed the background color but did nothing + else. + */ + if ((d->dc[d->level].fill_mode == DRAW_PATTERN) && (d->dc[d->level].dirty & DIRTY_FILL)) { + select_brush(d, d->dc[d->level].fill_recidx); } - if (!d->dc[d->level].sizeView.x || !d->dc[d->level].sizeView.y) { - /* Previously it used sizeWnd, but that always resulted in scale = 1 if no viewport ever appeared, and in most files, it did not */ - d->dc[d->level].sizeView.x = d->PixelsInX - 1; - d->dc[d->level].sizeView.y = d->PixelsInY - 1; - } + d->dc[d->level].dirty = 0; + } - /* scales logical to WMF pixels, transfer a negative sign on Y, if any */ - if (d->dc[d->level].sizeWnd.x && d->dc[d->level].sizeWnd.y) { - d->dc[d->level].ScaleInX = (double) d->dc[d->level].sizeView.x / (double) d->dc[d->level].sizeWnd.x; - d->dc[d->level].ScaleInY = (double) d->dc[d->level].sizeView.y / (double) d->dc[d->level].sizeWnd.y; - if(d->dc[d->level].ScaleInY < 0){ - d->dc[d->level].ScaleInY *= -1.0; - d->E2IdirY = -1.0; - } - } - else { - d->dc[d->level].ScaleInX = 1; - d->dc[d->level].ScaleInY = 1; + // std::cout << "BEFORE DRAW logic d->mask: " << std::hex << d->mask << " wmr_mask: " << wmr_mask << std::dec << + // std::endl; + /* + std::cout << "BEFORE DRAW" + << " test0 " << ( d->mask & U_DRAW_VISIBLE) + << " test1 " << ( d->mask & U_DRAW_FORCE) + << " test2 " << (wmr_mask & U_DRAW_ALTERS) + << " test2.5 " << ((d->mask & U_DRAW_NOFILL) != (wmr_mask & U_DRAW_NOFILL) ) + << " test3 " << (wmr_mask & U_DRAW_VISIBLE) + << " test4 " << !(d->mask & U_DRAW_ONLYTO) + << " test5 " << ((d->mask & U_DRAW_ONLYTO) && !(wmr_mask & U_DRAW_ONLYTO) ) + << std::endl; + */ + /* spurious moveto records should not affect the drawing. However, they set the NOFILL + bit and that messes up the logic about when to emit a path. So prune out any + stray moveto records. That is those which were never followed by a lineto. + */ + if ((d->mask & U_DRAW_NOFILL) && !(d->mask & U_DRAW_VISIBLE) && !(wmr_mask & U_DRAW_ONLYTO) && + (wmr_mask & U_DRAW_VISIBLE)) { + d->mask ^= U_DRAW_NOFILL; + } + + if ((wmr_mask != U_WMR_INVALID) && // next record is valid type + (d->mask & U_DRAW_VISIBLE) && // This record is drawable + ((d->mask & U_DRAW_FORCE) || // This draw is forced by STROKE/FILL/STROKEANDFILL PATH + (wmr_mask & U_DRAW_ALTERS) || // Next record would alter the drawing environment in some way + ((d->mask & U_DRAW_NOFILL) != (wmr_mask & U_DRAW_NOFILL)) || // Fill<->!Fill requires a draw between + ((wmr_mask & U_DRAW_VISIBLE) && // Next record is visible... + ((!(d->mask & U_DRAW_ONLYTO)) || // Non *TO records cannot be followed by any Visible + ((d->mask & U_DRAW_ONLYTO) && !(wmr_mask & U_DRAW_ONLYTO)) // *TO records can only be followed by other + // *TO records + )))) { + // std::cout << "PATH DRAW at TOP <<+++++++++++++++++++++++++++++++++++++" << std::endl; + if (!(d->path.empty())) { + d->outsvg += " outsvg += "\n\t"; + d->outsvg += "\n\td=\""; // this is the ONLY place d=" should be used!!!! + d->outsvg += d->path; + d->outsvg += " \" /> \n"; + d->path = ""; // reset the path } - break; - } - case U_WMR_SETVIEWPORTORG: - { - dbg_str << "\n"; - nSize = U_WMRSETVIEWPORTORG_get(contents, &d->dc[d->level].vieworg); - break; + // reset the flags + d->mask = 0; + d->drawtype = 0; } - case U_WMR_SETVIEWPORTEXT: - { - dbg_str << "\n"; + // std::cout << "AFTER DRAW logic d->mask: " << std::hex << d->mask << " wmr_mask: " << wmr_mask << std::dec << + // std::endl; + switch (iType) { + case U_WMR_EOF: { + dbg_str << "\n"; - nSize = U_WMRSETVIEWPORTEXT_get(contents, &d->dc[d->level].sizeView); - - if (!d->dc[d->level].sizeView.x || !d->dc[d->level].sizeView.y) { - d->dc[d->level].sizeView = d->dc[d->level].sizeWnd; - if (!d->dc[d->level].sizeView.x || !d->dc[d->level].sizeView.y) { - d->dc[d->level].sizeView.x = d->PixelsOutX; - d->dc[d->level].sizeView.y = d->PixelsOutY; + d->outsvg = d->outdef + d->defs + "\n\n\n" + d->outsvg + "\n"; + OK = 0; + break; + } + case U_WMR_SETBKCOLOR: { + dbg_str << "\n"; + nSize = U_WMRSETBKCOLOR_get(contents, &tbkColor); + if (memcmp(&tbkColor, &(d->dc[d->level].bkColor), sizeof(U_COLORREF))) { + d->dc[d->level].dirty |= DIRTY_TEXT; + if (d->dc[d->level].fill_mode == DRAW_PATTERN) { + d->dc[d->level].dirty |= DIRTY_FILL; + } + tbkMode = d->dc[d->level].bkMode; } + break; } - - if (!d->dc[d->level].sizeWnd.x || !d->dc[d->level].sizeWnd.y) { - d->dc[d->level].sizeWnd = d->dc[d->level].sizeView; + case U_WMR_SETBKMODE: { + dbg_str << "\n"; + nSize = U_WMRSETBKMODE_get(contents, &tbkMode); + if (tbkMode != d->dc[d->level].bkMode) { + d->dc[d->level].dirty |= DIRTY_TEXT; + if (tbkMode != d->dc[d->level].bkMode) { + if (d->dc[d->level].fill_mode == DRAW_PATTERN) { + d->dc[d->level].dirty |= DIRTY_FILL; + } + } + memcpy(&tbkColor, &(d->dc[d->level].bkColor), sizeof(U_COLORREF)); + } + break; } - - /* scales logical to WMF pixels, transfer a negative sign on Y, if any */ - if (d->dc[d->level].sizeWnd.x && d->dc[d->level].sizeWnd.y) { - d->dc[d->level].ScaleInX = (double) d->dc[d->level].sizeView.x / (double) d->dc[d->level].sizeWnd.x; - d->dc[d->level].ScaleInY = (double) d->dc[d->level].sizeView.y / (double) d->dc[d->level].sizeWnd.y; - if(d->dc[d->level].ScaleInY < 0){ - d->dc[d->level].ScaleInY *= -1.0; - d->E2IdirY = -1.0; + case U_WMR_SETMAPMODE: { + dbg_str << "\n"; + nSize = U_WMRSETMAPMODE_get(contents, &utmp16); + switch (utmp16) { + case U_MM_TEXT: + default: + // Use all values from the header. + break; + /* For all of the following the indicated scale this will be encoded in WindowExtEx/ViewportExtex + and show up in ScaleIn[XY] + */ + case U_MM_LOMETRIC: // 1 LU = 0.1 mm, + case U_MM_HIMETRIC: // 1 LU = 0.01 mm + case U_MM_LOENGLISH: // 1 LU = 0.1 in + case U_MM_HIENGLISH: // 1 LU = 0.01 in + case U_MM_TWIPS: // 1 LU = 1/1440 in + d->E2IdirY = -1.0; + // Use d->D2Pscale[XY] values from the header. + break; + case U_MM_ISOTROPIC: // ScaleIn[XY] should be set elsewhere by SETVIEWPORTEXTEX and SETWINDOWEXTEX + case U_MM_ANISOTROPIC: + break; } + break; } - else { - d->dc[d->level].ScaleInX = 1; - d->dc[d->level].ScaleInY = 1; + case U_WMR_SETROP2: { + dbg_str << "\n"; + nSize = U_WMRSETROP2_get(contents, &utmp16); + d->dwRop2 = utmp16; + break; } - break; - } - case U_WMR_OFFSETWINDOWORG: dbg_str << "\n"; break; - case U_WMR_SCALEWINDOWEXT: dbg_str << "\n"; break; - case U_WMR_OFFSETVIEWPORTORG: dbg_str << "\n"; break; - case U_WMR_SCALEVIEWPORTEXT: dbg_str << "\n"; break; - case U_WMR_LINETO: - { - dbg_str << "\n"; - - nSize = U_WMRLINETO_get(contents, &pt16); - - d->mask |= wmr_mask; + case U_WMR_SETRELABS: + dbg_str << "\n"; + break; + case U_WMR_SETPOLYFILLMODE: { + dbg_str << "\n"; + nSize = U_WMRSETPOLYFILLMODE_get(contents, &utmp16); + d->dc[d->level].style.fill_rule.value = + (utmp16 == U_ALTERNATE ? SP_WIND_RULE_NONZERO + : utmp16 == U_WINDING ? SP_WIND_RULE_INTERSECT : SP_WIND_RULE_NONZERO); + break; + } + case U_WMR_SETSTRETCHBLTMODE: { + dbg_str << "\n"; + nSize = U_WMRSETSTRETCHBLTMODE_get(contents, &utmp16); + BLTmode = utmp16; + break; + } + case U_WMR_SETTEXTCHAREXTRA: + dbg_str << "\n"; + break; + case U_WMR_SETTEXTCOLOR: { + dbg_str << "\n"; + nSize = U_WMRSETTEXTCOLOR_get(contents, &(d->dc[d->level].textColor)); + if (tbkMode != d->dc[d->level].bkMode) { + if (d->dc[d->level].fill_mode == DRAW_PATTERN) { + d->dc[d->level].dirty |= DIRTY_FILL; + } + } + // not text_dirty, because multicolored complex text is supported in libTERE + break; + } + case U_WMR_SETTEXTJUSTIFICATION: + dbg_str << "\n"; + break; + case U_WMR_SETWINDOWORG: { + dbg_str << "\n"; + nSize = U_WMRSETWINDOWORG_get(contents, &d->dc[d->level].winorg); + d->ulCornerOutX = 0.0; // In the examples seen to date if this record is used with a placeable header, + // that header is ignored + d->ulCornerOutY = 0.0; + break; + } + case U_WMR_SETWINDOWEXT: { + dbg_str << "\n"; - tmp_path << "\n\tL " << pix_to_xy( d, pt16.x, pt16.y) << " "; - break; - } - case U_WMR_MOVETO: - { - dbg_str << "\n"; + nSize = U_WMRSETWINDOWEXT_get(contents, &d->dc[d->level].sizeWnd); + + if (!d->dc[d->level].sizeWnd.x || !d->dc[d->level].sizeWnd.y) { + d->dc[d->level].sizeWnd = d->dc[d->level].sizeView; + if (!d->dc[d->level].sizeWnd.x || !d->dc[d->level].sizeWnd.y) { + d->dc[d->level].sizeWnd.x = d->PixelsOutX; + d->dc[d->level].sizeWnd.y = d->PixelsOutY; + } + } else { + /* There are a lot WMF files in circulation with the x,y values in the setwindowext reversed. If + this is detected, swap them. There is a remote possibility that the strange scaling this implies + was intended, and those will be rendered incorrectly */ + double Ox = d->PixelsOutX; + double Oy = d->PixelsOutY; + double Wx = d->dc[d->level].sizeWnd.x; + double Wy = d->dc[d->level].sizeWnd.y; + if (Wx != Wy && Geom::are_near(Ox / Wy, Oy / Wx, 1.01 / MIN(Wx, Wy))) { + int tmp; + tmp = d->dc[d->level].sizeWnd.x; + d->dc[d->level].sizeWnd.x = d->dc[d->level].sizeWnd.y; + d->dc[d->level].sizeWnd.y = tmp; + } + } - nSize = U_WMRLINETO_get(contents, &pt16); + if (!d->dc[d->level].sizeView.x || !d->dc[d->level].sizeView.y) { + /* Previously it used sizeWnd, but that always resulted in scale = 1 if no viewport ever appeared, + * and in most files, it did not */ + d->dc[d->level].sizeView.x = d->PixelsInX - 1; + d->dc[d->level].sizeView.y = d->PixelsInY - 1; + } - d->mask |= wmr_mask; + /* scales logical to WMF pixels, transfer a negative sign on Y, if any */ + if (d->dc[d->level].sizeWnd.x && d->dc[d->level].sizeWnd.y) { + d->dc[d->level].ScaleInX = (double)d->dc[d->level].sizeView.x / (double)d->dc[d->level].sizeWnd.x; + d->dc[d->level].ScaleInY = (double)d->dc[d->level].sizeView.y / (double)d->dc[d->level].sizeWnd.y; + if (d->dc[d->level].ScaleInY < 0) { + d->dc[d->level].ScaleInY *= -1.0; + d->E2IdirY = -1.0; + } + } else { + d->dc[d->level].ScaleInX = 1; + d->dc[d->level].ScaleInY = 1; + } + break; + } + case U_WMR_SETVIEWPORTORG: { + dbg_str << "\n"; + nSize = U_WMRSETVIEWPORTORG_get(contents, &d->dc[d->level].vieworg); + break; + } + case U_WMR_SETVIEWPORTEXT: { + dbg_str << "\n"; - d->dc[d->level].cur = pt16; + nSize = U_WMRSETVIEWPORTEXT_get(contents, &d->dc[d->level].sizeView); - tmp_path << - "\n\tM " << pix_to_xy( d, pt16.x, pt16.y ) << " "; - break; - } - case U_WMR_EXCLUDECLIPRECT: - { - dbg_str << "\n"; - - U_RECT16 rc; - nSize = U_WMREXCLUDECLIPRECT_get(contents, &rc); - - SVGOStringStream tmp_path; - float faraway = 10000000; // hopefully well outside any real drawing! - //outer rect, clockwise - tmp_path << "M " << faraway << "," << faraway << " "; - tmp_path << "L " << faraway << "," << -faraway << " "; - tmp_path << "L " << -faraway << "," << -faraway << " "; - tmp_path << "L " << -faraway << "," << faraway << " "; - tmp_path << "z "; - //inner rect, counterclockwise (sign of Y is reversed) - tmp_path << "M " << pix_to_xy( d, rc.left , rc.top ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.right, rc.top ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.right, rc.bottom ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.left, rc.bottom ) << " "; - tmp_path << "z"; - - add_clips(d, tmp_path.str().c_str(), U_RGN_AND); - - d->path = ""; - d->drawtype = 0; - break; - } - case U_WMR_INTERSECTCLIPRECT: - { - dbg_str << "\n"; - - nSize = U_WMRINTERSECTCLIPRECT_get(contents, &rc); - - SVGOStringStream tmp_path; - tmp_path << "M " << pix_to_xy( d, rc.left , rc.top ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.right, rc.top ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.right, rc.bottom ) << " "; - tmp_path << "L " << pix_to_xy( d, rc.left, rc.bottom ) << " "; - tmp_path << "z"; - - add_clips(d, tmp_path.str().c_str(), U_RGN_AND); - - d->path = ""; - d->drawtype = 0; - break; - } - case U_WMR_ARC: - { - dbg_str << "\n"; - U_POINT16 ArcStart, ArcEnd; - nSize = U_WMRARC_get(contents, &ArcStart, &ArcEnd, &rc); - - U_PAIRF center,start,end,size; - int f1; - int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); - int stat = wmr_arc_points(rc, ArcStart, ArcEnd,&f1, f2, ¢er, &start, &end, &size); - if(!stat){ - tmp_path << "\n\tM " << pix_to_xy(d, start.x, start.y); - tmp_path << " A " << pix_to_abs_size(d, size.x)/2.0 << "," << pix_to_abs_size(d, size.y)/2.0; - tmp_path << " "; - tmp_path << 180.0 * current_rotation(d)/M_PI; - tmp_path << " "; - tmp_path << " " << f1 << "," << f2 << " "; - tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; - d->mask |= wmr_mask; + if (!d->dc[d->level].sizeView.x || !d->dc[d->level].sizeView.y) { + d->dc[d->level].sizeView = d->dc[d->level].sizeWnd; + if (!d->dc[d->level].sizeView.x || !d->dc[d->level].sizeView.y) { + d->dc[d->level].sizeView.x = d->PixelsOutX; + d->dc[d->level].sizeView.y = d->PixelsOutY; + } + } + + if (!d->dc[d->level].sizeWnd.x || !d->dc[d->level].sizeWnd.y) { + d->dc[d->level].sizeWnd = d->dc[d->level].sizeView; + } + + /* scales logical to WMF pixels, transfer a negative sign on Y, if any */ + if (d->dc[d->level].sizeWnd.x && d->dc[d->level].sizeWnd.y) { + d->dc[d->level].ScaleInX = (double)d->dc[d->level].sizeView.x / (double)d->dc[d->level].sizeWnd.x; + d->dc[d->level].ScaleInY = (double)d->dc[d->level].sizeView.y / (double)d->dc[d->level].sizeWnd.y; + if (d->dc[d->level].ScaleInY < 0) { + d->dc[d->level].ScaleInY *= -1.0; + d->E2IdirY = -1.0; + } + } else { + d->dc[d->level].ScaleInX = 1; + d->dc[d->level].ScaleInY = 1; + } + break; } - else { - dbg_str << "\n"; + case U_WMR_OFFSETWINDOWORG: + dbg_str << "\n"; + break; + case U_WMR_SCALEWINDOWEXT: + dbg_str << "\n"; + break; + case U_WMR_OFFSETVIEWPORTORG: + dbg_str << "\n"; + break; + case U_WMR_SCALEVIEWPORTEXT: + dbg_str << "\n"; + break; + case U_WMR_LINETO: { + dbg_str << "\n"; + + nSize = U_WMRLINETO_get(contents, &pt16); + + d->mask |= wmr_mask; + + tmp_path << "\n\tL " << pix_to_xy(d, pt16.x, pt16.y) << " "; + break; } - break; - } - case U_WMR_ELLIPSE: - { - dbg_str << "\n"; - - nSize = U_WMRELLIPSE_get(contents, &rc); - - double cx = pix_to_x_point( d, (rc.left + rc.right)/2.0, (rc.bottom + rc.top)/2.0 ); - double cy = pix_to_y_point( d, (rc.left + rc.right)/2.0, (rc.bottom + rc.top)/2.0 ); - double rx = pix_to_abs_size( d, std::abs(rc.right - rc.left )/2.0 ); - double ry = pix_to_abs_size( d, std::abs(rc.top - rc.bottom)/2.0 ); - - SVGOStringStream tmp_ellipse; - tmp_ellipse << "cx=\"" << cx << "\" "; - tmp_ellipse << "cy=\"" << cy << "\" "; - tmp_ellipse << "rx=\"" << rx << "\" "; - tmp_ellipse << "ry=\"" << ry << "\" "; - - d->mask |= wmr_mask; - - d->outsvg += " outsvg += "\n\t"; - d->outsvg += tmp_ellipse.str().c_str(); - d->outsvg += "/> \n"; - d->path = ""; - break; - } - case U_WMR_FLOODFILL: dbg_str << "\n"; break; - case U_WMR_PIE: - { - dbg_str << "\n"; - U_POINT16 ArcStart, ArcEnd; - nSize = U_WMRPIE_get(contents, &ArcStart, &ArcEnd, &rc); - U_PAIRF center,start,end,size; - int f1; - int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); - if(!wmr_arc_points(rc, ArcStart, ArcEnd, &f1, f2, ¢er, &start, &end, &size)){ - tmp_path << "\n\tM " << pix_to_xy(d, center.x, center.y); - tmp_path << "\n\tL " << pix_to_xy(d, start.x, start.y); - tmp_path << " A " << pix_to_abs_size(d, size.x)/2.0 << "," << pix_to_abs_size(d, size.y)/2.0; - tmp_path << " "; - tmp_path << 180.0 * current_rotation(d)/M_PI; - tmp_path << " "; - tmp_path << " " << f1 << "," << f2 << " "; - tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; - tmp_path << " z "; + case U_WMR_MOVETO: { + dbg_str << "\n"; + + nSize = U_WMRLINETO_get(contents, &pt16); + d->mask |= wmr_mask; + + d->dc[d->level].cur = pt16; + + tmp_path << "\n\tM " << pix_to_xy(d, pt16.x, pt16.y) << " "; + break; } - else { - dbg_str << "\n"; + case U_WMR_EXCLUDECLIPRECT: { + dbg_str << "\n"; + + U_RECT16 rc; + nSize = U_WMREXCLUDECLIPRECT_get(contents, &rc); + + SVGOStringStream tmp_path; + float faraway = 10000000; // hopefully well outside any real drawing! + // outer rect, clockwise + tmp_path << "M " << faraway << "," << faraway << " "; + tmp_path << "L " << faraway << "," << -faraway << " "; + tmp_path << "L " << -faraway << "," << -faraway << " "; + tmp_path << "L " << -faraway << "," << faraway << " "; + tmp_path << "z "; + // inner rect, counterclockwise (sign of Y is reversed) + tmp_path << "M " << pix_to_xy(d, rc.left, rc.top) << " "; + tmp_path << "L " << pix_to_xy(d, rc.right, rc.top) << " "; + tmp_path << "L " << pix_to_xy(d, rc.right, rc.bottom) << " "; + tmp_path << "L " << pix_to_xy(d, rc.left, rc.bottom) << " "; + tmp_path << "z"; + + add_clips(d, tmp_path.str().c_str(), U_RGN_AND); + + d->path = ""; + d->drawtype = 0; + break; } - break; - } - case U_WMR_RECTANGLE: - { - dbg_str << "\n"; + case U_WMR_INTERSECTCLIPRECT: { + dbg_str << "\n"; - nSize = U_WMRRECTANGLE_get(contents, &rc); - U_sanerect16(rc, &left, &top, &right, &bottom); + nSize = U_WMRINTERSECTCLIPRECT_get(contents, &rc); - SVGOStringStream tmp_rectangle; - tmp_rectangle << "\n\tM " << pix_to_xy( d, left , top ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, right, top ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, right, bottom ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, left, bottom ) << " "; - tmp_rectangle << "\n\tz"; + SVGOStringStream tmp_path; + tmp_path << "M " << pix_to_xy(d, rc.left, rc.top) << " "; + tmp_path << "L " << pix_to_xy(d, rc.right, rc.top) << " "; + tmp_path << "L " << pix_to_xy(d, rc.right, rc.bottom) << " "; + tmp_path << "L " << pix_to_xy(d, rc.left, rc.bottom) << " "; + tmp_path << "z"; - d->mask |= wmr_mask; + add_clips(d, tmp_path.str().c_str(), U_RGN_AND); - tmp_path << tmp_rectangle.str().c_str(); - break; - } - case U_WMR_ROUNDRECT: - { - dbg_str << "\n"; - - int16_t Height,Width; - nSize = U_WMRROUNDRECT_get(contents, &Width, &Height, &rc); - U_sanerect16(rc, &left, &top, &right, &bottom); - double f = 4.*(sqrt(2) - 1)/3; - double f1 = 1.0 - f; - double cnx = Width/2; - double cny = Height/2; - - - SVGOStringStream tmp_rectangle; - tmp_rectangle << "\n" - << " M " - << pix_to_xy(d, left , top + cny ) - << "\n"; - tmp_rectangle << " C " - << pix_to_xy(d, left , top + cny*f1 ) - << " " - << pix_to_xy(d, left + cnx*f1 , top ) - << " " - << pix_to_xy(d, left + cnx , top ) - << "\n"; - tmp_rectangle << " L " - << pix_to_xy(d, right - cnx , top ) - << "\n"; - tmp_rectangle << " C " - << pix_to_xy(d, right - cnx*f1 , top ) - << " " - << pix_to_xy(d, right , top + cny*f1 ) - << " " - << pix_to_xy(d, right , top + cny ) - << "\n"; - tmp_rectangle << " L " - << pix_to_xy(d, right , bottom - cny ) - << "\n"; - tmp_rectangle << " C " - << pix_to_xy(d, right , bottom - cny*f1 ) - << " " - << pix_to_xy(d, right - cnx*f1 , bottom ) - << " " - << pix_to_xy(d, right - cnx , bottom ) - << "\n"; - tmp_rectangle << " L " - << pix_to_xy(d, left + cnx , bottom ) - << "\n"; - tmp_rectangle << " C " - << pix_to_xy(d, left + cnx*f1 , bottom ) - << " " - << pix_to_xy(d, left , bottom - cny*f1 ) - << " " - << pix_to_xy(d, left , bottom - cny ) - << "\n"; - tmp_rectangle << " z\n"; - - - d->mask |= wmr_mask; - - tmp_path << tmp_rectangle.str().c_str(); - break; - } - case U_WMR_PATBLT: - { - dbg_str << "\n"; - // Treat this like any other rectangle, ie, ignore the dwRop3 - nSize = U_WMRPATBLT_get(contents, &Dst, &cwh, &dwRop3); - SVGOStringStream tmp_rectangle; - tmp_rectangle << "\n\tM " << pix_to_xy( d, Dst.x , Dst.y ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, Dst.x + cwh.x, Dst.y ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, Dst.x + cwh.x, Dst.y + cwh.y ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, Dst.x, Dst.y + cwh.y ) << " "; - tmp_rectangle << "\n\tz"; - - d->mask |= wmr_mask; - - tmp_path << tmp_rectangle.str().c_str(); - break; - } - case U_WMR_SAVEDC: - { - dbg_str << "\n"; - - if (d->level < WMF_MAX_DC) { - d->dc[d->level + 1] = d->dc[d->level]; - if(d->dc[d->level].font_name){ - d->dc[d->level + 1].font_name = strdup(d->dc[d->level].font_name); // or memory access problems because font name pointer duplicated - } - d->level = d->level + 1; + d->path = ""; + d->drawtype = 0; + break; } - break; - } - case U_WMR_SETPIXEL: dbg_str << "\n"; break; - case U_WMR_OFFSETCLIPRGN: - { - dbg_str << "\n"; - U_POINT16 off; - nSize = U_WMROFFSETCLIPRGN_get(contents,&off); - if (d->dc[d->level].clip_id) { // can only offset an existing clipping path - unsigned int real_idx = d->dc[d->level].clip_id - 1; - Geom::PathVector tmp_vect = sp_svg_read_pathv(d->clips.strings[real_idx]); - double ox = pix_to_x_point(d, off.x, off.y) - pix_to_x_point(d, 0, 0); // take into account all active transforms - double oy = pix_to_y_point(d, off.x, off.y) - pix_to_y_point(d, 0, 0); - Geom::Affine tf = Geom::Translate(ox,oy); - tmp_vect *= tf; - char *tmp_path = sp_svg_write_path(tmp_vect); - add_clips(d, tmp_path, U_RGN_COPY); - free(tmp_path); + case U_WMR_ARC: { + dbg_str << "\n"; + U_POINT16 ArcStart, ArcEnd; + nSize = U_WMRARC_get(contents, &ArcStart, &ArcEnd, &rc); + + U_PAIRF center, start, end, size; + int f1; + int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); + int stat = wmr_arc_points(rc, ArcStart, ArcEnd, &f1, f2, ¢er, &start, &end, &size); + if (!stat) { + tmp_path << "\n\tM " << pix_to_xy(d, start.x, start.y); + tmp_path << " A " << pix_to_abs_size(d, size.x) / 2.0 << "," << pix_to_abs_size(d, size.y) / 2.0; + tmp_path << " "; + tmp_path << 180.0 * current_rotation(d) / M_PI; + tmp_path << " "; + tmp_path << " " << f1 << "," << f2 << " "; + tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; + d->mask |= wmr_mask; + } else { + dbg_str << "\n"; + } + break; } - break; - } - // U_WMR_TEXTOUT should be here, but has been moved down to merge with U_WMR_EXTTEXTOUT - case U_WMR_BITBLT: - { - dbg_str << "\n"; - nSize = U_WMRBITBLT_get(contents,&Dst,&cwh,&Src,&dwRop3,&Bm16,&px); - if(!px){ - if(dwRop3 == U_NOOP)break; /* GDI applications apparently often end with this as a sort of flush(), nothing should be drawn */ - int32_t dx = Dst.x; - int32_t dy = Dst.y; - int32_t dw = cwh.x; - int32_t dh = cwh.y; - SVGOStringStream tmp_rectangle; - tmp_rectangle << "\n\tM " << pix_to_xy( d, dx, dy ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx + dw, dy ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx + dw, dy + dh ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx, dy + dh ) << " "; - tmp_rectangle << "\n\tz"; + case U_WMR_ELLIPSE: { + dbg_str << "\n"; + + nSize = U_WMRELLIPSE_get(contents, &rc); + + double cx = pix_to_x_point(d, (rc.left + rc.right) / 2.0, (rc.bottom + rc.top) / 2.0); + double cy = pix_to_y_point(d, (rc.left + rc.right) / 2.0, (rc.bottom + rc.top) / 2.0); + double rx = pix_to_abs_size(d, std::abs(rc.right - rc.left) / 2.0); + double ry = pix_to_abs_size(d, std::abs(rc.top - rc.bottom) / 2.0); + + SVGOStringStream tmp_ellipse; + tmp_ellipse << "cx=\"" << cx << "\" "; + tmp_ellipse << "cy=\"" << cy << "\" "; + tmp_ellipse << "rx=\"" << rx << "\" "; + tmp_ellipse << "ry=\"" << ry << "\" "; d->mask |= wmr_mask; - d->dwRop3 = dwRop3; // we will try to approximate SOME of these - d->mask |= U_DRAW_CLOSED; // Bitblit is not really open or closed, but we need it to fill, and this is the flag for that - - tmp_path << tmp_rectangle.str().c_str(); - } - else { /* Not done yet, Bm16 image present */ } - double dx = pix_to_x_point( d, Dst.x, Dst.y); - double dy = pix_to_y_point( d, Dst.x, Dst.y); - double dw = pix_to_abs_size( d, cwh.x); - double dh = pix_to_abs_size( d, cwh.y); - //source position within the bitmap, in pixels - int sx = Src.x; - int sy = Src.y; - int sw = 0; // extract all of the image - int sh = 0; - if(sx<0)sx=0; - if(sy<0)sy=0; - common_bm16_to_image(d,Bm16,px,dx,dy,dw,dh,sx,sy,sw,sh); - break; - } - case U_WMR_STRETCHBLT: - { - dbg_str << "\n"; - nSize = U_WMRSTRETCHBLT_get(contents,&Dst,&cDst,&Src,&cSrc,&dwRop3,&Bm16,&px); - if(!px){ - if(dwRop3 == U_NOOP)break; /* GDI applications apparently often end with this as a sort of flush(), nothing should be drawn */ - int32_t dx = Dst.x; - int32_t dy = Dst.y; - int32_t dw = cDst.x; - int32_t dh = cDst.y; + + d->outsvg += " outsvg += "\n\t"; + d->outsvg += tmp_ellipse.str().c_str(); + d->outsvg += "/> \n"; + d->path = ""; + break; + } + case U_WMR_FLOODFILL: + dbg_str << "\n"; + break; + case U_WMR_PIE: { + dbg_str << "\n"; + U_POINT16 ArcStart, ArcEnd; + nSize = U_WMRPIE_get(contents, &ArcStart, &ArcEnd, &rc); + U_PAIRF center, start, end, size; + int f1; + int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); + if (!wmr_arc_points(rc, ArcStart, ArcEnd, &f1, f2, ¢er, &start, &end, &size)) { + tmp_path << "\n\tM " << pix_to_xy(d, center.x, center.y); + tmp_path << "\n\tL " << pix_to_xy(d, start.x, start.y); + tmp_path << " A " << pix_to_abs_size(d, size.x) / 2.0 << "," << pix_to_abs_size(d, size.y) / 2.0; + tmp_path << " "; + tmp_path << 180.0 * current_rotation(d) / M_PI; + tmp_path << " "; + tmp_path << " " << f1 << "," << f2 << " "; + tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; + tmp_path << " z "; + d->mask |= wmr_mask; + } else { + dbg_str << "\n"; + } + break; + } + case U_WMR_RECTANGLE: { + dbg_str << "\n"; + + nSize = U_WMRRECTANGLE_get(contents, &rc); + U_sanerect16(rc, &left, &top, &right, &bottom); + SVGOStringStream tmp_rectangle; - tmp_rectangle << "\n\tM " << pix_to_xy( d, dx, dy ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx + dw, dy ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx + dw, dy + dh ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx, dy + dh ) << " "; + tmp_rectangle << "\n\tM " << pix_to_xy(d, left, top) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, right, top) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, right, bottom) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, left, bottom) << " "; tmp_rectangle << "\n\tz"; d->mask |= wmr_mask; - d->dwRop3 = dwRop3; // we will try to approximate SOME of these - d->mask |= U_DRAW_CLOSED; // Bitblit is not really open or closed, but we need it to fill, and this is the flag for that - - tmp_path << tmp_rectangle.str().c_str(); - } - else { /* Not done yet, Bm16 image present */ } - double dx = pix_to_x_point( d, Dst.x, Dst.y); - double dy = pix_to_y_point( d, Dst.x, Dst.y); - double dw = pix_to_abs_size( d, cDst.x); - double dh = pix_to_abs_size( d, cDst.y); - //source position within the bitmap, in pixels - int sx = Src.x; - int sy = Src.y; - int sw = cSrc.x; // extract the specified amount of the image - int sh = cSrc.y; - if(sx<0)sx=0; - if(sy<0)sy=0; - common_bm16_to_image(d,Bm16,px,dx,dy,dw,dh,sx,sy,sw,sh); - break; - } - case U_WMR_POLYGON: - case U_WMR_POLYLINE: - { - dbg_str << "\n"; - nSize = U_WMRPOLYGON_get(contents, &cPts, &points); - uint32_t i; - if (cPts < 2)break; + tmp_path << tmp_rectangle.str().c_str(); + break; + } + case U_WMR_ROUNDRECT: { + dbg_str << "\n"; + + int16_t Height, Width; + nSize = U_WMRROUNDRECT_get(contents, &Width, &Height, &rc); + U_sanerect16(rc, &left, &top, &right, &bottom); + double f = 4. * (sqrt(2) - 1) / 3; + double f1 = 1.0 - f; + double cnx = Width / 2; + double cny = Height / 2; - d->mask |= wmr_mask; - memcpy(&pt16,points,U_SIZE_POINT16); points += U_SIZE_POINT16; + SVGOStringStream tmp_rectangle; + tmp_rectangle << "\n" + << " M " << pix_to_xy(d, left, top + cny) << "\n"; + tmp_rectangle << " C " << pix_to_xy(d, left, top + cny * f1) << " " + << pix_to_xy(d, left + cnx * f1, top) << " " << pix_to_xy(d, left + cnx, top) << "\n"; + tmp_rectangle << " L " << pix_to_xy(d, right - cnx, top) << "\n"; + tmp_rectangle << " C " << pix_to_xy(d, right - cnx * f1, top) << " " + << pix_to_xy(d, right, top + cny * f1) << " " << pix_to_xy(d, right, top + cny) << "\n"; + tmp_rectangle << " L " << pix_to_xy(d, right, bottom - cny) << "\n"; + tmp_rectangle << " C " << pix_to_xy(d, right, bottom - cny * f1) << " " + << pix_to_xy(d, right - cnx * f1, bottom) << " " << pix_to_xy(d, right - cnx, bottom) + << "\n"; + tmp_rectangle << " L " << pix_to_xy(d, left + cnx, bottom) << "\n"; + tmp_rectangle << " C " << pix_to_xy(d, left + cnx * f1, bottom) << " " + << pix_to_xy(d, left, bottom - cny * f1) << " " << pix_to_xy(d, left, bottom - cny) + << "\n"; + tmp_rectangle << " z\n"; - tmp_str << "\n\tM " << pix_to_xy( d, pt16.x, pt16.y) << " "; + d->mask |= wmr_mask; - for (i=1; i\n"; + // Treat this like any other rectangle, ie, ignore the dwRop3 + nSize = U_WMRPATBLT_get(contents, &Dst, &cwh, &dwRop3); + SVGOStringStream tmp_rectangle; + tmp_rectangle << "\n\tM " << pix_to_xy(d, Dst.x, Dst.y) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, Dst.x + cwh.x, Dst.y) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, Dst.x + cwh.x, Dst.y + cwh.y) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, Dst.x, Dst.y + cwh.y) << " "; + tmp_rectangle << "\n\tz"; - tmp_path << tmp_str.str().c_str(); - if(iType==U_WMR_POLYGON){ tmp_path << " z"; } + d->mask |= wmr_mask; - break; - } - case U_WMR_ESCAPE: // only 3 types of escape are implemented - { - dbg_str << "\n"; - uint16_t Escape, elen; - nSize = U_WMRESCAPE_get(contents, &Escape, &elen, &text); - if(elen>=4){ - uint32_t utmp4; - memcpy(&utmp4, text ,4); - if(Escape == U_MFE_SETLINECAP){ - switch (utmp4 & U_PS_ENDCAP_MASK) { - case U_PS_ENDCAP_ROUND: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_ROUND; break; } - case U_PS_ENDCAP_SQUARE: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_SQUARE; break; } - case U_PS_ENDCAP_FLAT: - default: { d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_BUTT; break; } + tmp_path << tmp_rectangle.str().c_str(); + break; + } + case U_WMR_SAVEDC: { + dbg_str << "\n"; + + if (d->level < WMF_MAX_DC) { + d->dc[d->level + 1] = d->dc[d->level]; + if (d->dc[d->level].font_name) { + d->dc[d->level + 1].font_name = + strdup(d->dc[d->level].font_name); // or memory access problems because font name pointer + // duplicated } + d->level = d->level + 1; } - else if(Escape == U_MFE_SETLINEJOIN){ - switch (utmp4 & U_PS_JOIN_MASK) { - case U_PS_JOIN_BEVEL: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_BEVEL; break; } - case U_PS_JOIN_MITER: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_MITER; break; } - case U_PS_JOIN_ROUND: - default: { d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_ROUND; break; } - } + break; + } + case U_WMR_SETPIXEL: + dbg_str << "\n"; + break; + case U_WMR_OFFSETCLIPRGN: { + dbg_str << "\n"; + U_POINT16 off; + nSize = U_WMROFFSETCLIPRGN_get(contents, &off); + if (d->dc[d->level].clip_id) { // can only offset an existing clipping path + unsigned int real_idx = d->dc[d->level].clip_id - 1; + Geom::PathVector tmp_vect = sp_svg_read_pathv(d->clips.strings[real_idx]); + double ox = pix_to_x_point(d, off.x, off.y) - + pix_to_x_point(d, 0, 0); // take into account all active transforms + double oy = pix_to_y_point(d, off.x, off.y) - pix_to_y_point(d, 0, 0); + Geom::Affine tf = Geom::Translate(ox, oy); + tmp_vect *= tf; + char *tmp_path = sp_svg_write_path(tmp_vect); + add_clips(d, tmp_path, U_RGN_COPY); + free(tmp_path); } - else if(Escape == U_MFE_SETMITERLIMIT){ - //The function takes a float but uses a 32 bit int in the record. - float miterlimit = utmp4; - d->dc[d->level].style.stroke_miterlimit.value = miterlimit; //ratio, not a pt size - if (d->dc[d->level].style.stroke_miterlimit.value < 2) - d->dc[d->level].style.stroke_miterlimit.value = 2.0; + break; + } + // U_WMR_TEXTOUT should be here, but has been moved down to merge with U_WMR_EXTTEXTOUT + case U_WMR_BITBLT: { + dbg_str << "\n"; + nSize = U_WMRBITBLT_get(contents, &Dst, &cwh, &Src, &dwRop3, &Bm16, &px); + if (!px) { + if (dwRop3 == U_NOOP) + break; /* GDI applications apparently often end with this as a sort of flush(), nothing should + be drawn */ + int32_t dx = Dst.x; + int32_t dy = Dst.y; + int32_t dw = cwh.x; + int32_t dh = cwh.y; + SVGOStringStream tmp_rectangle; + tmp_rectangle << "\n\tM " << pix_to_xy(d, dx, dy) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx + dw, dy) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx + dw, dy + dh) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx, dy + dh) << " "; + tmp_rectangle << "\n\tz"; + + d->mask |= wmr_mask; + d->dwRop3 = dwRop3; // we will try to approximate SOME of these + d->mask |= U_DRAW_CLOSED; // Bitblit is not really open or closed, but we need it to fill, and this + // is the flag for that + + tmp_path << tmp_rectangle.str().c_str(); + } else { /* Not done yet, Bm16 image present */ } + double dx = pix_to_x_point(d, Dst.x, Dst.y); + double dy = pix_to_y_point(d, Dst.x, Dst.y); + double dw = pix_to_abs_size(d, cwh.x); + double dh = pix_to_abs_size(d, cwh.y); + // source position within the bitmap, in pixels + int sx = Src.x; + int sy = Src.y; + int sw = 0; // extract all of the image + int sh = 0; + if (sx < 0) + sx = 0; + if (sy < 0) + sy = 0; + common_bm16_to_image(d, Bm16, px, dx, dy, dw, dh, sx, sy, sw, sh); + break; } - break; - } - case U_WMR_RESTOREDC: - { - dbg_str << "\n"; - - int16_t DC; - nSize = U_WMRRESTOREDC_get(contents, &DC); - int old_level = d->level; - if (DC >= 0) { - if (DC < d->level) - d->level = DC; - } - else { - if (d->level + DC >= 0) - d->level = d->level + DC; - } - while (old_level > d->level) { - if (!d->dc[old_level].style.stroke_dasharray.values.empty() && - (old_level == 0 || (old_level > 0 && d->dc[old_level].style.stroke_dasharray != - d->dc[old_level - 1].style.stroke_dasharray))) { - d->dc[old_level].style.stroke_dasharray.values.clear(); + case U_WMR_STRETCHBLT: { + dbg_str << "\n"; + nSize = U_WMRSTRETCHBLT_get(contents, &Dst, &cDst, &Src, &cSrc, &dwRop3, &Bm16, &px); + if (!px) { + if (dwRop3 == U_NOOP) + break; /* GDI applications apparently often end with this as a sort of flush(), nothing should + be drawn */ + int32_t dx = Dst.x; + int32_t dy = Dst.y; + int32_t dw = cDst.x; + int32_t dh = cDst.y; + SVGOStringStream tmp_rectangle; + tmp_rectangle << "\n\tM " << pix_to_xy(d, dx, dy) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx + dw, dy) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx + dw, dy + dh) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx, dy + dh) << " "; + tmp_rectangle << "\n\tz"; + + d->mask |= wmr_mask; + d->dwRop3 = dwRop3; // we will try to approximate SOME of these + d->mask |= U_DRAW_CLOSED; // Bitblit is not really open or closed, but we need it to fill, and this + // is the flag for that + + tmp_path << tmp_rectangle.str().c_str(); + } else { /* Not done yet, Bm16 image present */ } - if(d->dc[old_level].font_name){ - free(d->dc[old_level].font_name); // else memory leak - d->dc[old_level].font_name = nullptr; + double dx = pix_to_x_point(d, Dst.x, Dst.y); + double dy = pix_to_y_point(d, Dst.x, Dst.y); + double dw = pix_to_abs_size(d, cDst.x); + double dh = pix_to_abs_size(d, cDst.y); + // source position within the bitmap, in pixels + int sx = Src.x; + int sy = Src.y; + int sw = cSrc.x; // extract the specified amount of the image + int sh = cSrc.y; + if (sx < 0) + sx = 0; + if (sy < 0) + sy = 0; + common_bm16_to_image(d, Bm16, px, dx, dy, dw, dh, sx, sy, sw, sh); + break; + } + case U_WMR_POLYGON: + case U_WMR_POLYLINE: { + dbg_str << "\n"; + nSize = U_WMRPOLYGON_get(contents, &cPts, &points); + uint32_t i; + + if (cPts < 2) + break; + + d->mask |= wmr_mask; + memcpy(&pt16, points, U_SIZE_POINT16); + points += U_SIZE_POINT16; + + tmp_str << "\n\tM " << pix_to_xy(d, pt16.x, pt16.y) << " "; + + for (i = 1; i < cPts; i++) { + memcpy(&pt16, points, U_SIZE_POINT16); + points += U_SIZE_POINT16; + tmp_str << "\n\tL " << pix_to_xy(d, pt16.x, pt16.y) << " "; } - old_level--; + + tmp_path << tmp_str.str().c_str(); + if (iType == U_WMR_POLYGON) { + tmp_path << " z"; + } + + break; } - break; - } - case U_WMR_FILLREGION: dbg_str << "\n"; break; - case U_WMR_FRAMEREGION: dbg_str << "\n"; break; - case U_WMR_INVERTREGION: dbg_str << "\n"; break; - case U_WMR_PAINTREGION: dbg_str << "\n"; break; - case U_WMR_SELECTCLIPREGION: - { - dbg_str << "\n"; - nSize = U_WMRSELECTCLIPREGION_get(contents, &utmp16); - if (utmp16 == U_RGN_COPY) - clipset = false; - break; - } - case U_WMR_SELECTOBJECT: - { - dbg_str << "\n"; - - nSize = U_WMRSELECTOBJECT_get(contents, &utmp16); - unsigned int index = utmp16; - - // WMF has no stock objects - if ( /*index >= 0 &&*/ index < (unsigned int) d->n_obj) { - switch (d->wmf_obj[index].type) - { - case U_WMR_CREATEPENINDIRECT: - select_pen(d, index); - break; - case U_WMR_CREATEBRUSHINDIRECT: - case U_WMR_DIBCREATEPATTERNBRUSH: - case U_WMR_CREATEPATTERNBRUSH: // <- this one did not display properly on XP, DIBCREATEPATTERNBRUSH works - select_brush(d, index); - break; - case U_WMR_CREATEFONTINDIRECT: - select_font(d, index); - break; - case U_WMR_CREATEPALETTE: - case U_WMR_CREATEBITMAPINDIRECT: - case U_WMR_CREATEBITMAP: - case U_WMR_CREATEREGION: - /* these do not do anything, but their objects must be kept in the count */ - break; + case U_WMR_ESCAPE: // only 3 types of escape are implemented + { + dbg_str << "\n"; + uint16_t Escape, elen; + nSize = U_WMRESCAPE_get(contents, &Escape, &elen, &text); + if (elen >= 4) { + uint32_t utmp4; + memcpy(&utmp4, text, 4); + if (Escape == U_MFE_SETLINECAP) { + switch (utmp4 & U_PS_ENDCAP_MASK) { + case U_PS_ENDCAP_ROUND: { + d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_ROUND; + break; + } + case U_PS_ENDCAP_SQUARE: { + d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_SQUARE; + break; + } + case U_PS_ENDCAP_FLAT: + default: { + d->dc[d->level].style.stroke_linecap.computed = SP_STROKE_LINECAP_BUTT; + break; + } + } + } else if (Escape == U_MFE_SETLINEJOIN) { + switch (utmp4 & U_PS_JOIN_MASK) { + case U_PS_JOIN_BEVEL: { + d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_BEVEL; + break; + } + case U_PS_JOIN_MITER: { + d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_MITER; + break; + } + case U_PS_JOIN_ROUND: + default: { + d->dc[d->level].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_ROUND; + break; + } + } + } else if (Escape == U_MFE_SETMITERLIMIT) { + // The function takes a float but uses a 32 bit int in the record. + float miterlimit = utmp4; + d->dc[d->level].style.stroke_miterlimit.value = miterlimit; // ratio, not a pt size + if (d->dc[d->level].style.stroke_miterlimit.value < 2) + d->dc[d->level].style.stroke_miterlimit.value = 2.0; + } } + break; } - break; - } - case U_WMR_SETTEXTALIGN: - { - dbg_str << "\n"; - nSize = U_WMRSETTEXTALIGN_get(contents, &(d->dc[d->level].textAlign)); - break; - } - case U_WMR_DRAWTEXT: dbg_str << "\n"; break; - case U_WMR_CHORD: - { - dbg_str << "\n"; - U_POINT16 ArcStart, ArcEnd; - nSize = U_WMRCHORD_get(contents, &ArcStart, &ArcEnd, &rc); - U_PAIRF center,start,end,size; - int f1; - int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); - if(!wmr_arc_points(rc, ArcStart, ArcEnd, &f1, f2, ¢er, &start, &end, &size)){ - tmp_path << "\n\tM " << pix_to_xy(d, start.x, start.y); - tmp_path << " A " << pix_to_abs_size(d, size.x)/2.0 << "," << pix_to_abs_size(d, size.y)/2.0 ; - tmp_path << " "; - tmp_path << 180.0 * current_rotation(d)/M_PI; - tmp_path << " "; - tmp_path << " " << f1 << "," << f2 << " "; - tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; - tmp_path << " z "; - d->mask |= wmr_mask; + case U_WMR_RESTOREDC: { + dbg_str << "\n"; + + int16_t DC; + nSize = U_WMRRESTOREDC_get(contents, &DC); + int old_level = d->level; + if (DC >= 0) { + if (DC < d->level) + d->level = DC; + } else { + if (d->level + DC >= 0) + d->level = d->level + DC; + } + while (old_level > d->level) { + if (!d->dc[old_level].style.stroke_dasharray.values.empty() && + (old_level == 0 || (old_level > 0 && d->dc[old_level].style.stroke_dasharray != + d->dc[old_level - 1].style.stroke_dasharray))) { + d->dc[old_level].style.stroke_dasharray.values.clear(); + } + if (d->dc[old_level].font_name) { + free(d->dc[old_level].font_name); // else memory leak + d->dc[old_level].font_name = nullptr; + } + old_level--; + } + break; } - else { - dbg_str << "\n"; + case U_WMR_FILLREGION: + dbg_str << "\n"; + break; + case U_WMR_FRAMEREGION: + dbg_str << "\n"; + break; + case U_WMR_INVERTREGION: + dbg_str << "\n"; + break; + case U_WMR_PAINTREGION: + dbg_str << "\n"; + break; + case U_WMR_SELECTCLIPREGION: { + dbg_str << "\n"; + nSize = U_WMRSELECTCLIPREGION_get(contents, &utmp16); + if (utmp16 == U_RGN_COPY) + clipset = false; + break; } - break; - } - case U_WMR_SETMAPPERFLAGS: dbg_str << "\n"; break; - case U_WMR_TEXTOUT: - case U_WMR_EXTTEXTOUT: - { - if(iType == U_WMR_TEXTOUT){ - dbg_str << "\n"; - nSize = U_WMRTEXTOUT_get(contents, &Dst, &tlen, &text); - Opts=0; - } - else { - dbg_str << "\n"; - nSize = U_WMREXTTEXTOUT_get(contents, &Dst, &tlen, &Opts, &text, &dx, &rc ); + case U_WMR_SELECTOBJECT: { + dbg_str << "\n"; + + nSize = U_WMRSELECTOBJECT_get(contents, &utmp16); + unsigned int index = utmp16; + + // WMF has no stock objects + if (/*index >= 0 &&*/ index < (unsigned int)d->n_obj) { + switch (d->wmf_obj[index].type) { + case U_WMR_CREATEPENINDIRECT: + select_pen(d, index); + break; + case U_WMR_CREATEBRUSHINDIRECT: + case U_WMR_DIBCREATEPATTERNBRUSH: + case U_WMR_CREATEPATTERNBRUSH: // <- this one did not display properly on XP, + // DIBCREATEPATTERNBRUSH works + select_brush(d, index); + break; + case U_WMR_CREATEFONTINDIRECT: + select_font(d, index); + break; + case U_WMR_CREATEPALETTE: + case U_WMR_CREATEBITMAPINDIRECT: + case U_WMR_CREATEBITMAP: + case U_WMR_CREATEREGION: + /* these do not do anything, but their objects must be kept in the count */ + break; + } + } + break; } - uint32_t fOptions = Opts; + case U_WMR_SETTEXTALIGN: { + dbg_str << "\n"; + nSize = U_WMRSETTEXTALIGN_get(contents, &(d->dc[d->level].textAlign)); + break; + } + case U_WMR_DRAWTEXT: + dbg_str << "\n"; + break; + case U_WMR_CHORD: { + dbg_str << "\n"; + U_POINT16 ArcStart, ArcEnd; + nSize = U_WMRCHORD_get(contents, &ArcStart, &ArcEnd, &rc); + U_PAIRF center, start, end, size; + int f1; + int f2 = (d->arcdir == U_AD_COUNTERCLOCKWISE ? 0 : 1); + if (!wmr_arc_points(rc, ArcStart, ArcEnd, &f1, f2, ¢er, &start, &end, &size)) { + tmp_path << "\n\tM " << pix_to_xy(d, start.x, start.y); + tmp_path << " A " << pix_to_abs_size(d, size.x) / 2.0 << "," << pix_to_abs_size(d, size.y) / 2.0; + tmp_path << " "; + tmp_path << 180.0 * current_rotation(d) / M_PI; + tmp_path << " "; + tmp_path << " " << f1 << "," << f2 << " "; + tmp_path << pix_to_xy(d, end.x, end.y) << " \n"; + tmp_path << " z "; + d->mask |= wmr_mask; + } else { + dbg_str << "\n"; + } + break; + } + case U_WMR_SETMAPPERFLAGS: + dbg_str << "\n"; + break; + case U_WMR_TEXTOUT: + case U_WMR_EXTTEXTOUT: { + if (iType == U_WMR_TEXTOUT) { + dbg_str << "\n"; + nSize = U_WMRTEXTOUT_get(contents, &Dst, &tlen, &text); + Opts = 0; + } else { + dbg_str << "\n"; + nSize = U_WMREXTTEXTOUT_get(contents, &Dst, &tlen, &Opts, &text, &dx, &rc); + } + uint32_t fOptions = Opts; - double x1,y1; - int cChars; - x1 = Dst.x; - y1 = Dst.y; - cChars = tlen; + double x1, y1; + int cChars; + x1 = Dst.x; + y1 = Dst.y; + cChars = tlen; - if (d->dc[d->level].textAlign & U_TA_UPDATECP) { - x1 = d->dc[d->level].cur.x; - y1 = d->dc[d->level].cur.y; - } + if (d->dc[d->level].textAlign & U_TA_UPDATECP) { + x1 = d->dc[d->level].cur.x; + y1 = d->dc[d->level].cur.y; + } - double x = pix_to_x_point(d, x1, y1); - double y = pix_to_y_point(d, x1, y1); + double x = pix_to_x_point(d, x1, y1); + double y = pix_to_y_point(d, x1, y1); - /* Rotation issues are handled entirely in libTERE now */ + /* Rotation issues are handled entirely in libTERE now */ - uint32_t *dup_wt = nullptr; + uint32_t *dup_wt = nullptr; - dup_wt = U_Latin1ToUtf32le(text, cChars, nullptr); - if(!dup_wt)dup_wt = unknown_chars(cChars); + dup_wt = U_Latin1ToUtf32le(text, cChars, nullptr); + if (!dup_wt) + dup_wt = unknown_chars(cChars); - msdepua(dup_wt); //convert everything in Microsoft's private use area. For Symbol, Wingdings, Dingbats + msdepua(dup_wt); // convert everything in Microsoft's private use area. For Symbol, Wingdings, Dingbats - if(NonToUnicode(dup_wt, d->dc[d->level].font_name)){ - free(d->dc[d->level].font_name); - d->dc[d->level].font_name = strdup("Times New Roman"); - } - - char *ansi_text; - ansi_text = (char *) U_Utf32leToUtf8((uint32_t *)dup_wt, 0, nullptr); - free(dup_wt); - // Empty text or starts with an invalid escape/control sequence, which is bogus text. Throw it out before g_markup_escape_text can make things worse - if(*((uint8_t *)ansi_text) <= 0x1F){ - free(ansi_text); - ansi_text=nullptr; - } - - if (ansi_text) { - - SVGOStringStream ts; - - gchar *escaped_text = g_markup_escape_text(ansi_text, -1); - - tsp.x = x*0.8; // TERE expects sizes in points - tsp.y = y*0.8; - tsp.color.Red = d->dc[d->level].textColor.Red; - tsp.color.Green = d->dc[d->level].textColor.Green; - tsp.color.Blue = d->dc[d->level].textColor.Blue; - tsp.color.Reserved = 0; - switch(d->dc[d->level].style.font_style.value){ - case SP_CSS_FONT_STYLE_OBLIQUE: - tsp.italics = FC_SLANT_OBLIQUE; break; - case SP_CSS_FONT_STYLE_ITALIC: - tsp.italics = FC_SLANT_ITALIC; break; - default: - case SP_CSS_FONT_STYLE_NORMAL: - tsp.italics = FC_SLANT_ROMAN; break; + if (NonToUnicode(dup_wt, d->dc[d->level].font_name)) { + free(d->dc[d->level].font_name); + d->dc[d->level].font_name = strdup("Times New Roman"); } - switch(d->dc[d->level].style.font_weight.value){ - case SP_CSS_FONT_WEIGHT_100: tsp.weight = FC_WEIGHT_THIN ; break; - case SP_CSS_FONT_WEIGHT_200: tsp.weight = FC_WEIGHT_EXTRALIGHT ; break; - case SP_CSS_FONT_WEIGHT_300: tsp.weight = FC_WEIGHT_LIGHT ; break; - case SP_CSS_FONT_WEIGHT_400: tsp.weight = FC_WEIGHT_NORMAL ; break; - case SP_CSS_FONT_WEIGHT_500: tsp.weight = FC_WEIGHT_MEDIUM ; break; - case SP_CSS_FONT_WEIGHT_600: tsp.weight = FC_WEIGHT_SEMIBOLD ; break; - case SP_CSS_FONT_WEIGHT_700: tsp.weight = FC_WEIGHT_BOLD ; break; - case SP_CSS_FONT_WEIGHT_800: tsp.weight = FC_WEIGHT_EXTRABOLD ; break; - case SP_CSS_FONT_WEIGHT_900: tsp.weight = FC_WEIGHT_HEAVY ; break; - case SP_CSS_FONT_WEIGHT_NORMAL: tsp.weight = FC_WEIGHT_NORMAL ; break; - case SP_CSS_FONT_WEIGHT_BOLD: tsp.weight = FC_WEIGHT_BOLD ; break; - case SP_CSS_FONT_WEIGHT_LIGHTER: tsp.weight = FC_WEIGHT_EXTRALIGHT ; break; - case SP_CSS_FONT_WEIGHT_BOLDER: tsp.weight = FC_WEIGHT_EXTRABOLD ; break; - default: tsp.weight = FC_WEIGHT_NORMAL ; break; + + char *ansi_text; + ansi_text = (char *)U_Utf32leToUtf8((uint32_t *)dup_wt, 0, nullptr); + free(dup_wt); + // Empty text or starts with an invalid escape/control sequence, which is bogus text. Throw it out + // before g_markup_escape_text can make things worse + if (*((uint8_t *)ansi_text) <= 0x1F) { + free(ansi_text); + ansi_text = nullptr; } - // WMF only supports two types of text decoration - tsp.decoration = TXTDECOR_NONE; - if(d->dc[d->level].style.text_decoration_line.underline){ tsp.decoration |= TXTDECOR_UNDER; } - if(d->dc[d->level].style.text_decoration_line.line_through){ tsp.decoration |= TXTDECOR_STRIKE;} - - // WMF textalignment is a bit strange: 0x6 is center, 0x2 is right, 0x0 is left, the value 0x4 is also drawn left - tsp.taln = ((d->dc[d->level].textAlign & U_TA_CENTER) == U_TA_CENTER) ? ALICENTER : - (((d->dc[d->level].textAlign & U_TA_CENTER) == U_TA_LEFT) ? ALILEFT : - ALIRIGHT); - tsp.taln |= ((d->dc[d->level].textAlign & U_TA_BASEBIT) ? ALIBASE : - ((d->dc[d->level].textAlign & U_TA_BOTTOM) ? ALIBOT : - ALITOP)); - - // language direction can be encoded two ways, U_TA_RTLREADING is preferred - if( (fOptions & U_ETO_RTLREADING) || (d->dc[d->level].textAlign & U_TA_RTLREADING) ){ tsp.ldir = LDIR_RL; } - else{ tsp.ldir = LDIR_LR; } - - tsp.condensed = FC_WIDTH_NORMAL; // Not implemented well in libTERE (yet) - tsp.ori = d->dc[d->level].style.baseline_shift.value; // For now orientation is always the same as escapement - // There is no world transform, so ori need not be further rotated - tsp.string = (uint8_t *) U_strdup(escaped_text); // this will be free'd much later at a trinfo_clear(). - tsp.fs = d->dc[d->level].style.font_size.computed * 0.8; // Font size in points - char *fontspec = TR_construct_fontspec(&tsp, d->dc[d->level].font_name); - tsp.fi_idx = ftinfo_load_fontname(d->tri->fti,fontspec); - free(fontspec); - // when font name includes narrow it may not be set to "condensed". Narrow fonts do not work well anyway though - // as the metrics from fontconfig may not match, or the font may not be present. - if(0<= TR_findcasesub(d->dc[d->level].font_name, (char *) "Narrow")){ tsp.co=1; } - else { tsp.co=0; } - - int status; - - status = trinfo_load_textrec(d->tri, &tsp, tsp.ori,TR_EMFBOT); // ori is actually escapement - if(status==-1){ // change of escapement, emit what we have and reset - TR_layout_analyze(d->tri); - if (d->dc[d->level].clip_id){ - SVGOStringStream tmp_clip; - tmp_clip << "\ndc[d->level].clip_id << ")\"\n>"; - d->outsvg += tmp_clip.str().c_str(); + + if (ansi_text) { + SVGOStringStream ts; + + gchar *escaped_text = g_markup_escape_text(ansi_text, -1); + + tsp.x = x * 0.8; // TERE expects sizes in points + tsp.y = y * 0.8; + tsp.color.Red = d->dc[d->level].textColor.Red; + tsp.color.Green = d->dc[d->level].textColor.Green; + tsp.color.Blue = d->dc[d->level].textColor.Blue; + tsp.color.Reserved = 0; + switch (d->dc[d->level].style.font_style.value) { + case SP_CSS_FONT_STYLE_OBLIQUE: + tsp.italics = FC_SLANT_OBLIQUE; + break; + case SP_CSS_FONT_STYLE_ITALIC: + tsp.italics = FC_SLANT_ITALIC; + break; + default: + case SP_CSS_FONT_STYLE_NORMAL: + tsp.italics = FC_SLANT_ROMAN; + break; + } + switch (d->dc[d->level].style.font_weight.value) { + case SP_CSS_FONT_WEIGHT_100: + tsp.weight = FC_WEIGHT_THIN; + break; + case SP_CSS_FONT_WEIGHT_200: + tsp.weight = FC_WEIGHT_EXTRALIGHT; + break; + case SP_CSS_FONT_WEIGHT_300: + tsp.weight = FC_WEIGHT_LIGHT; + break; + case SP_CSS_FONT_WEIGHT_400: + tsp.weight = FC_WEIGHT_NORMAL; + break; + case SP_CSS_FONT_WEIGHT_500: + tsp.weight = FC_WEIGHT_MEDIUM; + break; + case SP_CSS_FONT_WEIGHT_600: + tsp.weight = FC_WEIGHT_SEMIBOLD; + break; + case SP_CSS_FONT_WEIGHT_700: + tsp.weight = FC_WEIGHT_BOLD; + break; + case SP_CSS_FONT_WEIGHT_800: + tsp.weight = FC_WEIGHT_EXTRABOLD; + break; + case SP_CSS_FONT_WEIGHT_900: + tsp.weight = FC_WEIGHT_HEAVY; + break; + case SP_CSS_FONT_WEIGHT_NORMAL: + tsp.weight = FC_WEIGHT_NORMAL; + break; + case SP_CSS_FONT_WEIGHT_BOLD: + tsp.weight = FC_WEIGHT_BOLD; + break; + case SP_CSS_FONT_WEIGHT_LIGHTER: + tsp.weight = FC_WEIGHT_EXTRALIGHT; + break; + case SP_CSS_FONT_WEIGHT_BOLDER: + tsp.weight = FC_WEIGHT_EXTRABOLD; + break; + default: + tsp.weight = FC_WEIGHT_NORMAL; + break; + } + // WMF only supports two types of text decoration + tsp.decoration = TXTDECOR_NONE; + if (d->dc[d->level].style.text_decoration_line.underline) { + tsp.decoration |= TXTDECOR_UNDER; } - TR_layout_2_svg(d->tri); - ts << d->tri->out; - d->outsvg += ts.str().c_str(); - d->tri = trinfo_clear(d->tri); - (void) trinfo_load_textrec(d->tri, &tsp, tsp.ori,TR_EMFBOT); // ignore return status, it must work - if (d->dc[d->level].clip_id){ - d->outsvg += "\n\n"; - } + if (d->dc[d->level].style.text_decoration_line.line_through) { + tsp.decoration |= TXTDECOR_STRIKE; + } + + // WMF textalignment is a bit strange: 0x6 is center, 0x2 is right, 0x0 is left, the value 0x4 is + // also drawn left + tsp.taln = ((d->dc[d->level].textAlign & U_TA_CENTER) == U_TA_CENTER) + ? ALICENTER + : (((d->dc[d->level].textAlign & U_TA_CENTER) == U_TA_LEFT) ? ALILEFT : ALIRIGHT); + tsp.taln |= ((d->dc[d->level].textAlign & U_TA_BASEBIT) + ? ALIBASE + : ((d->dc[d->level].textAlign & U_TA_BOTTOM) ? ALIBOT : ALITOP)); + + // language direction can be encoded two ways, U_TA_RTLREADING is preferred + if ((fOptions & U_ETO_RTLREADING) || (d->dc[d->level].textAlign & U_TA_RTLREADING)) { + tsp.ldir = LDIR_RL; + } else { + tsp.ldir = LDIR_LR; + } + + tsp.condensed = FC_WIDTH_NORMAL; // Not implemented well in libTERE (yet) + tsp.ori = d->dc[d->level].style.baseline_shift.value; // For now orientation is always the same as + // escapement + // There is no world transform, so ori need not be further rotated + tsp.string = + (uint8_t *)U_strdup(escaped_text); // this will be free'd much later at a trinfo_clear(). + tsp.fs = d->dc[d->level].style.font_size.computed * 0.8; // Font size in points + char *fontspec = TR_construct_fontspec(&tsp, d->dc[d->level].font_name); + tsp.fi_idx = ftinfo_load_fontname(d->tri->fti, fontspec); + free(fontspec); + // when font name includes narrow it may not be set to "condensed". Narrow fonts do not work well + // anyway though as the metrics from fontconfig may not match, or the font may not be present. + if (0 <= TR_findcasesub(d->dc[d->level].font_name, (char *)"Narrow")) { + tsp.co = 1; + } else { + tsp.co = 0; + } + + int status; + + status = trinfo_load_textrec(d->tri, &tsp, tsp.ori, TR_EMFBOT); // ori is actually escapement + if (status == -1) { // change of escapement, emit what we have and reset + TR_layout_analyze(d->tri); + if (d->dc[d->level].clip_id) { + SVGOStringStream tmp_clip; + tmp_clip << "\ndc[d->level].clip_id << ")\"\n>"; + d->outsvg += tmp_clip.str().c_str(); + } + TR_layout_2_svg(d->tri); + ts << d->tri->out; + d->outsvg += ts.str().c_str(); + d->tri = trinfo_clear(d->tri); + (void)trinfo_load_textrec(d->tri, &tsp, tsp.ori, + TR_EMFBOT); // ignore return status, it must work + if (d->dc[d->level].clip_id) { + d->outsvg += "\n\n"; + } + } + + g_free(escaped_text); + free(ansi_text); } - g_free(escaped_text); - free(ansi_text); + break; } + case U_WMR_SETDIBTODEV: + dbg_str << "\n"; + break; + case U_WMR_SELECTPALETTE: + dbg_str << "\n"; + break; + case U_WMR_REALIZEPALETTE: + dbg_str << "\n"; + break; + case U_WMR_ANIMATEPALETTE: + dbg_str << "\n"; + break; + case U_WMR_SETPALENTRIES: + dbg_str << "\n"; + break; + case U_WMR_POLYPOLYGON: { + dbg_str << "\n"; + uint16_t nPolys; + const uint16_t *aPolyCounts; + const char *Points; + int cpts; /* total number of points in Points*/ + nSize = U_WMRPOLYPOLYGON_get(contents, &nPolys, &aPolyCounts, &Points); + int n, i, j; + + d->mask |= wmr_mask; + + U_POINT16 apt; + for (n = cpts = 0; n < nPolys; n++) { + cpts += aPolyCounts[n]; + } + i = 0; // offset in BYTES + cpts *= U_SIZE_POINT16; // limit for offset i, in BYTES + + for (n = 0; n < nPolys && i < cpts; n++) { + SVGOStringStream poly_path; - break; - } - case U_WMR_SETDIBTODEV: dbg_str << "\n"; break; - case U_WMR_SELECTPALETTE: dbg_str << "\n"; break; - case U_WMR_REALIZEPALETTE: dbg_str << "\n"; break; - case U_WMR_ANIMATEPALETTE: dbg_str << "\n"; break; - case U_WMR_SETPALENTRIES: dbg_str << "\n"; break; - case U_WMR_POLYPOLYGON: - { - dbg_str << "\n"; - uint16_t nPolys; - const uint16_t *aPolyCounts; - const char *Points; - int cpts; /* total number of points in Points*/ - nSize = U_WMRPOLYPOLYGON_get(contents, &nPolys, &aPolyCounts, &Points); - int n, i, j; - - d->mask |= wmr_mask; - - U_POINT16 apt; - for (n=cpts=0; n < nPolys; n++) { cpts += aPolyCounts[n]; } - i = 0; // offset in BYTES - cpts *= U_SIZE_POINT16; // limit for offset i, in BYTES - - for (n=0; n < nPolys && i\n"; break; - case U_WMR_3A: - case U_WMR_3B: - case U_WMR_3C: - case U_WMR_3D: - case U_WMR_3E: - case U_WMR_3F: - { - dbg_str << "\n"; - break; - } - case U_WMR_DIBBITBLT: - { - dbg_str << "\n"; - nSize = U_WMRDIBBITBLT_get(contents, &Dst, &cwh, &Src, &dwRop3, &dib); - - // Treat all nonImage bitblts as a rectangular write. Definitely not correct, but at - // least it leaves objects where the operations should have been. - if (!dib) { - // should be an application of a DIBPATTERNBRUSHPT, use a solid color instead - - if(dwRop3 == U_NOOP)break; /* GDI applications apparently often end with this as a sort of flush(), nothing should be drawn */ - int32_t dx = Dst.x; - int32_t dy = Dst.y; - int32_t dw = cwh.x; - int32_t dh = cwh.y; - SVGOStringStream tmp_rectangle; - tmp_rectangle << "\n\tM " << pix_to_xy( d, dx, dy ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx + dw, dy ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx + dw, dy + dh ) << " "; - tmp_rectangle << "\n\tL " << pix_to_xy( d, dx, dy + dh ) << " "; - tmp_rectangle << "\n\tz"; + tmp_path << tmp_str.str().c_str(); - d->mask |= wmr_mask; - d->dwRop3 = dwRop3; // we will try to approximate SOME of these - d->mask |= U_DRAW_CLOSED; // Bitblit is not really open or closed, but we need it to fill, and this is the flag for that - - tmp_path << tmp_rectangle.str().c_str(); - } - else { - double dx = pix_to_x_point( d, Dst.x, Dst.y); - double dy = pix_to_y_point( d, Dst.x, Dst.y); - double dw = pix_to_abs_size( d, cDst.x); - double dh = pix_to_abs_size( d, cDst.y); - //source position within the bitmap, in pixels - int sx = Src.x; - int sy = Src.y; - int sw = 0; // extract all of the image - int sh = 0; - if(sx<0)sx=0; - if(sy<0)sy=0; - // usageSrc not defined, implicitly it must be U_DIB_RGB_COLORS - common_dib_to_image(d,dib,dx,dy,dw,dh,sx,sy,sw,sh,U_DIB_RGB_COLORS); + break; } - break; - } - case U_WMR_DIBSTRETCHBLT: - { - dbg_str << "\n"; - nSize = U_WMRDIBSTRETCHBLT_get(contents, &Dst, &cDst, &Src, &cSrc, &dwRop3, &dib); - // Always grab image, ignore modes. - if (dib) { - double dx = pix_to_x_point( d, Dst.x, Dst.y); - double dy = pix_to_y_point( d, Dst.x, Dst.y); - double dw = pix_to_abs_size( d, cDst.x); - double dh = pix_to_abs_size( d, cDst.y); - //source position within the bitmap, in pixels - int sx = Src.x; + case U_WMR_RESIZEPALETTE: + dbg_str << "\n"; + break; + case U_WMR_3A: + case U_WMR_3B: + case U_WMR_3C: + case U_WMR_3D: + case U_WMR_3E: + case U_WMR_3F: { + dbg_str << "\n"; + break; + } + case U_WMR_DIBBITBLT: { + dbg_str << "\n"; + nSize = U_WMRDIBBITBLT_get(contents, &Dst, &cwh, &Src, &dwRop3, &dib); + + // Treat all nonImage bitblts as a rectangular write. Definitely not correct, but at + // least it leaves objects where the operations should have been. + if (!dib) { + // should be an application of a DIBPATTERNBRUSHPT, use a solid color instead + + if (dwRop3 == U_NOOP) + break; /* GDI applications apparently often end with this as a sort of flush(), nothing should + be drawn */ + int32_t dx = Dst.x; + int32_t dy = Dst.y; + int32_t dw = cwh.x; + int32_t dh = cwh.y; + SVGOStringStream tmp_rectangle; + tmp_rectangle << "\n\tM " << pix_to_xy(d, dx, dy) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx + dw, dy) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx + dw, dy + dh) << " "; + tmp_rectangle << "\n\tL " << pix_to_xy(d, dx, dy + dh) << " "; + tmp_rectangle << "\n\tz"; + + d->mask |= wmr_mask; + d->dwRop3 = dwRop3; // we will try to approximate SOME of these + d->mask |= U_DRAW_CLOSED; // Bitblit is not really open or closed, but we need it to fill, and this + // is the flag for that + + tmp_path << tmp_rectangle.str().c_str(); + } else { + double dx = pix_to_x_point(d, Dst.x, Dst.y); + double dy = pix_to_y_point(d, Dst.x, Dst.y); + double dw = pix_to_abs_size(d, cDst.x); + double dh = pix_to_abs_size(d, cDst.y); + // source position within the bitmap, in pixels + int sx = Src.x; + int sy = Src.y; + int sw = 0; // extract all of the image + int sh = 0; + if (sx < 0) + sx = 0; + if (sy < 0) + sy = 0; + // usageSrc not defined, implicitly it must be U_DIB_RGB_COLORS + common_dib_to_image(d, dib, dx, dy, dw, dh, sx, sy, sw, sh, U_DIB_RGB_COLORS); + } + break; + } + case U_WMR_DIBSTRETCHBLT: { + dbg_str << "\n"; + nSize = U_WMRDIBSTRETCHBLT_get(contents, &Dst, &cDst, &Src, &cSrc, &dwRop3, &dib); + // Always grab image, ignore modes. + if (dib) { + double dx = pix_to_x_point(d, Dst.x, Dst.y); + double dy = pix_to_y_point(d, Dst.x, Dst.y); + double dw = pix_to_abs_size(d, cDst.x); + double dh = pix_to_abs_size(d, cDst.y); + // source position within the bitmap, in pixels + int sx = Src.x; + int sy = Src.y; + int sw = cSrc.x; // extract the specified amount of the image + int sh = cSrc.y; + // usageSrc not defined, implicitly it must be U_DIB_RGB_COLORS + common_dib_to_image(d, dib, dx, dy, dw, dh, sx, sy, sw, sh, U_DIB_RGB_COLORS); + } + break; + } + case U_WMR_DIBCREATEPATTERNBRUSH: { + dbg_str << "\n"; + insert_object(d, U_WMR_DIBCREATEPATTERNBRUSH, contents); + break; + } + case U_WMR_STRETCHDIB: { + dbg_str << "\n"; + nSize = U_WMRSTRETCHDIB_get(contents, &Dst, &cDst, &Src, &cSrc, &cUsage, &dwRop3, &dib); + double dx = pix_to_x_point(d, Dst.x, Dst.y); + double dy = pix_to_y_point(d, Dst.x, Dst.y); + double dw = pix_to_abs_size(d, cDst.x); + double dh = pix_to_abs_size(d, cDst.y); + int sx = Src.x; // source position within the bitmap, in pixels int sy = Src.y; int sw = cSrc.x; // extract the specified amount of the image int sh = cSrc.y; - // usageSrc not defined, implicitly it must be U_DIB_RGB_COLORS - common_dib_to_image(d,dib,dx,dy,dw,dh,sx,sy,sw,sh, U_DIB_RGB_COLORS); + uint32_t iUsageSrc; + iUsageSrc = cUsage; + common_dib_to_image(d, dib, dx, dy, dw, dh, sx, sy, sw, sh, iUsageSrc); + + break; } - break; + case U_WMR_44: + case U_WMR_45: + case U_WMR_46: + case U_WMR_47: { + dbg_str << "\n"; + break; + } + case U_WMR_EXTFLOODFILL: + dbg_str << "\n"; + break; + case U_WMR_49: + case U_WMR_4A: + case U_WMR_4B: + case U_WMR_4C: + case U_WMR_4D: + case U_WMR_4E: + case U_WMR_4F: + case U_WMR_50: + case U_WMR_51: + case U_WMR_52: + case U_WMR_53: + case U_WMR_54: + case U_WMR_55: + case U_WMR_56: + case U_WMR_57: + case U_WMR_58: + case U_WMR_59: + case U_WMR_5A: + case U_WMR_5B: + case U_WMR_5C: + case U_WMR_5D: + case U_WMR_5E: + case U_WMR_5F: + case U_WMR_60: + case U_WMR_61: + case U_WMR_62: + case U_WMR_63: + case U_WMR_64: + case U_WMR_65: + case U_WMR_66: + case U_WMR_67: + case U_WMR_68: + case U_WMR_69: + case U_WMR_6A: + case U_WMR_6B: + case U_WMR_6C: + case U_WMR_6D: + case U_WMR_6E: + case U_WMR_6F: + case U_WMR_70: + case U_WMR_71: + case U_WMR_72: + case U_WMR_73: + case U_WMR_74: + case U_WMR_75: + case U_WMR_76: + case U_WMR_77: + case U_WMR_78: + case U_WMR_79: + case U_WMR_7A: + case U_WMR_7B: + case U_WMR_7C: + case U_WMR_7D: + case U_WMR_7E: + case U_WMR_7F: + case U_WMR_80: + case U_WMR_81: + case U_WMR_82: + case U_WMR_83: + case U_WMR_84: + case U_WMR_85: + case U_WMR_86: + case U_WMR_87: + case U_WMR_88: + case U_WMR_89: + case U_WMR_8A: + case U_WMR_8B: + case U_WMR_8C: + case U_WMR_8D: + case U_WMR_8E: + case U_WMR_8F: + case U_WMR_90: + case U_WMR_91: + case U_WMR_92: + case U_WMR_93: + case U_WMR_94: + case U_WMR_95: + case U_WMR_96: + case U_WMR_97: + case U_WMR_98: + case U_WMR_99: + case U_WMR_9A: + case U_WMR_9B: + case U_WMR_9C: + case U_WMR_9D: + case U_WMR_9E: + case U_WMR_9F: + case U_WMR_A0: + case U_WMR_A1: + case U_WMR_A2: + case U_WMR_A3: + case U_WMR_A4: + case U_WMR_A5: + case U_WMR_A6: + case U_WMR_A7: + case U_WMR_A8: + case U_WMR_A9: + case U_WMR_AA: + case U_WMR_AB: + case U_WMR_AC: + case U_WMR_AD: + case U_WMR_AE: + case U_WMR_AF: + case U_WMR_B0: + case U_WMR_B1: + case U_WMR_B2: + case U_WMR_B3: + case U_WMR_B4: + case U_WMR_B5: + case U_WMR_B6: + case U_WMR_B7: + case U_WMR_B8: + case U_WMR_B9: + case U_WMR_BA: + case U_WMR_BB: + case U_WMR_BC: + case U_WMR_BD: + case U_WMR_BE: + case U_WMR_BF: + case U_WMR_C0: + case U_WMR_C1: + case U_WMR_C2: + case U_WMR_C3: + case U_WMR_C4: + case U_WMR_C5: + case U_WMR_C6: + case U_WMR_C7: + case U_WMR_C8: + case U_WMR_C9: + case U_WMR_CA: + case U_WMR_CB: + case U_WMR_CC: + case U_WMR_CD: + case U_WMR_CE: + case U_WMR_CF: + case U_WMR_D0: + case U_WMR_D1: + case U_WMR_D2: + case U_WMR_D3: + case U_WMR_D4: + case U_WMR_D5: + case U_WMR_D6: + case U_WMR_D7: + case U_WMR_D8: + case U_WMR_D9: + case U_WMR_DA: + case U_WMR_DB: + case U_WMR_DC: + case U_WMR_DD: + case U_WMR_DE: + case U_WMR_DF: + case U_WMR_E0: + case U_WMR_E1: + case U_WMR_E2: + case U_WMR_E3: + case U_WMR_E4: + case U_WMR_E5: + case U_WMR_E6: + case U_WMR_E7: + case U_WMR_E8: + case U_WMR_E9: + case U_WMR_EA: + case U_WMR_EB: + case U_WMR_EC: + case U_WMR_ED: + case U_WMR_EE: + case U_WMR_EF: { + dbg_str << "\n"; + break; + } + case U_WMR_DELETEOBJECT: { + dbg_str << "\n"; + nSize = U_WMRDELETEOBJECT_get(contents, &utmp16); + delete_object(d, utmp16); + break; + } + case U_WMR_F1: + case U_WMR_F2: + case U_WMR_F3: + case U_WMR_F4: + case U_WMR_F5: + case U_WMR_F6: { + dbg_str << "\n"; + break; + } + case U_WMR_CREATEPALETTE: { + dbg_str << "\n"; + insert_object(d, U_WMR_CREATEPALETTE, contents); + break; + } + case U_WMR_F8: + dbg_str << "\n"; + break; + case U_WMR_CREATEPATTERNBRUSH: { + dbg_str << "\n"; + insert_object(d, U_WMR_CREATEPATTERNBRUSH, contents); + break; + } + case U_WMR_CREATEPENINDIRECT: { + dbg_str << "\n"; + insert_object(d, U_WMR_CREATEPENINDIRECT, contents); + break; + } + case U_WMR_CREATEFONTINDIRECT: { + dbg_str << "\n"; + insert_object(d, U_WMR_CREATEFONTINDIRECT, contents); + break; + } + case U_WMR_CREATEBRUSHINDIRECT: { + dbg_str << "\n"; + insert_object(d, U_WMR_CREATEBRUSHINDIRECT, contents); + break; + } + case U_WMR_CREATEBITMAPINDIRECT: { + dbg_str << "\n"; + insert_object(d, U_WMR_CREATEBITMAPINDIRECT, contents); + break; + } + case U_WMR_CREATEBITMAP: { + dbg_str << "\n"; + insert_object(d, U_WMR_CREATEBITMAP, contents); + break; + } + case U_WMR_CREATEREGION: { + dbg_str << "\n"; + insert_object(d, U_WMR_CREATEREGION, contents); + break; + } + default: + dbg_str << "\n"; + break; + } // end of switch + // At run time define environment variable INKSCAPE_DBG_WMF to include string COMMENT. + // Users may employ this to to place a comment for each processed WMR record in the SVG + if (wDbgComment) { + d->outsvg += dbg_str.str().c_str(); } - case U_WMR_DIBCREATEPATTERNBRUSH: - { - dbg_str << "\n"; - insert_object(d, U_WMR_DIBCREATEPATTERNBRUSH, contents); + d->path += tmp_path.str().c_str(); + if (!nSize) { // There was some problem with the processing of this record, it is not safe to continue + file_status = 0; break; } - case U_WMR_STRETCHDIB: - { - dbg_str << "\n"; - nSize = U_WMRSTRETCHDIB_get(contents, &Dst, &cDst, &Src, &cSrc, &cUsage, &dwRop3, &dib); - double dx = pix_to_x_point( d, Dst.x, Dst.y ); - double dy = pix_to_y_point( d, Dst.x, Dst.y ); - double dw = pix_to_abs_size( d, cDst.x); - double dh = pix_to_abs_size( d, cDst.y); - int sx = Src.x; //source position within the bitmap, in pixels - int sy = Src.y; - int sw = cSrc.x; // extract the specified amount of the image - int sh = cSrc.y; - uint32_t iUsageSrc; - iUsageSrc = cUsage; - common_dib_to_image(d,dib,dx,dy,dw,dh,sx,sy,sw,sh,iUsageSrc); - break; - } - case U_WMR_44: - case U_WMR_45: - case U_WMR_46: - case U_WMR_47: - { - dbg_str << "\n"; - break; - } - case U_WMR_EXTFLOODFILL: dbg_str << "\n"; break; - case U_WMR_49: - case U_WMR_4A: - case U_WMR_4B: - case U_WMR_4C: - case U_WMR_4D: - case U_WMR_4E: - case U_WMR_4F: - case U_WMR_50: - case U_WMR_51: - case U_WMR_52: - case U_WMR_53: - case U_WMR_54: - case U_WMR_55: - case U_WMR_56: - case U_WMR_57: - case U_WMR_58: - case U_WMR_59: - case U_WMR_5A: - case U_WMR_5B: - case U_WMR_5C: - case U_WMR_5D: - case U_WMR_5E: - case U_WMR_5F: - case U_WMR_60: - case U_WMR_61: - case U_WMR_62: - case U_WMR_63: - case U_WMR_64: - case U_WMR_65: - case U_WMR_66: - case U_WMR_67: - case U_WMR_68: - case U_WMR_69: - case U_WMR_6A: - case U_WMR_6B: - case U_WMR_6C: - case U_WMR_6D: - case U_WMR_6E: - case U_WMR_6F: - case U_WMR_70: - case U_WMR_71: - case U_WMR_72: - case U_WMR_73: - case U_WMR_74: - case U_WMR_75: - case U_WMR_76: - case U_WMR_77: - case U_WMR_78: - case U_WMR_79: - case U_WMR_7A: - case U_WMR_7B: - case U_WMR_7C: - case U_WMR_7D: - case U_WMR_7E: - case U_WMR_7F: - case U_WMR_80: - case U_WMR_81: - case U_WMR_82: - case U_WMR_83: - case U_WMR_84: - case U_WMR_85: - case U_WMR_86: - case U_WMR_87: - case U_WMR_88: - case U_WMR_89: - case U_WMR_8A: - case U_WMR_8B: - case U_WMR_8C: - case U_WMR_8D: - case U_WMR_8E: - case U_WMR_8F: - case U_WMR_90: - case U_WMR_91: - case U_WMR_92: - case U_WMR_93: - case U_WMR_94: - case U_WMR_95: - case U_WMR_96: - case U_WMR_97: - case U_WMR_98: - case U_WMR_99: - case U_WMR_9A: - case U_WMR_9B: - case U_WMR_9C: - case U_WMR_9D: - case U_WMR_9E: - case U_WMR_9F: - case U_WMR_A0: - case U_WMR_A1: - case U_WMR_A2: - case U_WMR_A3: - case U_WMR_A4: - case U_WMR_A5: - case U_WMR_A6: - case U_WMR_A7: - case U_WMR_A8: - case U_WMR_A9: - case U_WMR_AA: - case U_WMR_AB: - case U_WMR_AC: - case U_WMR_AD: - case U_WMR_AE: - case U_WMR_AF: - case U_WMR_B0: - case U_WMR_B1: - case U_WMR_B2: - case U_WMR_B3: - case U_WMR_B4: - case U_WMR_B5: - case U_WMR_B6: - case U_WMR_B7: - case U_WMR_B8: - case U_WMR_B9: - case U_WMR_BA: - case U_WMR_BB: - case U_WMR_BC: - case U_WMR_BD: - case U_WMR_BE: - case U_WMR_BF: - case U_WMR_C0: - case U_WMR_C1: - case U_WMR_C2: - case U_WMR_C3: - case U_WMR_C4: - case U_WMR_C5: - case U_WMR_C6: - case U_WMR_C7: - case U_WMR_C8: - case U_WMR_C9: - case U_WMR_CA: - case U_WMR_CB: - case U_WMR_CC: - case U_WMR_CD: - case U_WMR_CE: - case U_WMR_CF: - case U_WMR_D0: - case U_WMR_D1: - case U_WMR_D2: - case U_WMR_D3: - case U_WMR_D4: - case U_WMR_D5: - case U_WMR_D6: - case U_WMR_D7: - case U_WMR_D8: - case U_WMR_D9: - case U_WMR_DA: - case U_WMR_DB: - case U_WMR_DC: - case U_WMR_DD: - case U_WMR_DE: - case U_WMR_DF: - case U_WMR_E0: - case U_WMR_E1: - case U_WMR_E2: - case U_WMR_E3: - case U_WMR_E4: - case U_WMR_E5: - case U_WMR_E6: - case U_WMR_E7: - case U_WMR_E8: - case U_WMR_E9: - case U_WMR_EA: - case U_WMR_EB: - case U_WMR_EC: - case U_WMR_ED: - case U_WMR_EE: - case U_WMR_EF: - { - dbg_str << "\n"; - break; - } - case U_WMR_DELETEOBJECT: - { - dbg_str << "\n"; - nSize = U_WMRDELETEOBJECT_get(contents, &utmp16); - delete_object(d, utmp16); - break; - } - case U_WMR_F1: - case U_WMR_F2: - case U_WMR_F3: - case U_WMR_F4: - case U_WMR_F5: - case U_WMR_F6: - { - dbg_str << "\n"; - break; - } - case U_WMR_CREATEPALETTE: - { - dbg_str << "\n"; - insert_object(d, U_WMR_CREATEPALETTE, contents); - break; - } - case U_WMR_F8: dbg_str << "\n"; break; - case U_WMR_CREATEPATTERNBRUSH: - { - dbg_str << "\n"; - insert_object(d, U_WMR_CREATEPATTERNBRUSH, contents); - break; - } - case U_WMR_CREATEPENINDIRECT: - { - dbg_str << "\n"; - insert_object(d, U_WMR_CREATEPENINDIRECT, contents); - break; - } - case U_WMR_CREATEFONTINDIRECT: - { - dbg_str << "\n"; - insert_object(d, U_WMR_CREATEFONTINDIRECT, contents); - break; - } - case U_WMR_CREATEBRUSHINDIRECT: - { - dbg_str << "\n"; - insert_object(d, U_WMR_CREATEBRUSHINDIRECT, contents); - break; - } - case U_WMR_CREATEBITMAPINDIRECT: - { - dbg_str << "\n"; - insert_object(d, U_WMR_CREATEBITMAPINDIRECT, contents); - break; - } - case U_WMR_CREATEBITMAP: - { - dbg_str << "\n"; - insert_object(d, U_WMR_CREATEBITMAP, contents); - break; - } - case U_WMR_CREATEREGION: - { - dbg_str << "\n"; - insert_object(d, U_WMR_CREATEREGION, contents); - break; - } - default: - dbg_str << "\n"; - break; - } //end of switch -// At run time define environment variable INKSCAPE_DBG_WMF to include string COMMENT. -// Users may employ this to to place a comment for each processed WMR record in the SVG - if(wDbgComment){ - d->outsvg += dbg_str.str().c_str(); - } - d->path += tmp_path.str().c_str(); - if(!nSize){ // There was some problem with the processing of this record, it is not safe to continue - file_status = 0; - break; - } - - } //end of while on OK -// At run time define environment variable INKSCAPE_DBG_WMF to include string FINAL -// Users may employ this to to show the final SVG derived from the WMF - if(wDbgFinal){ - std::cout << d->outsvg << std::endl; + } // end of while on OK + // At run time define environment variable INKSCAPE_DBG_WMF to include string FINAL + // Users may employ this to to show the final SVG derived from the WMF + if (wDbgFinal) { + std::cout << d->outsvg << std::endl; } - (void) U_wmr_properties(U_WMR_INVALID); // force the release of the lookup table memory, returned value is irrelevant + (void)U_wmr_properties(U_WMR_INVALID); // force the release of the lookup table memory, returned value is irrelevant - return(file_status); + return (file_status); } -void Wmf::free_wmf_strings(WMF_STRINGS name){ - if(name.count){ - for(int i=0; i< name.count; i++){ free(name.strings[i]); } +void Wmf::free_wmf_strings(WMF_STRINGS name) +{ + if (name.count) { + for (int i = 0; i < name.count; i++) { + free(name.strings[i]); + } free(name.strings); } name.count = 0; name.size = 0; } -SPDocument * -Wmf::open( Inkscape::Extension::Input * /*mod*/, const gchar *uri ) +SPDocument *Wmf::open(Inkscape::Extension::Input * /*mod*/, const gchar *uri) { - if (uri == nullptr) { return nullptr; } @@ -3120,33 +3189,35 @@ Wmf::open( Inkscape::Extension::Input * /*mod*/, const gchar *uri ) setlocale(LC_NUMERIC, "C"); WMF_CALLBACK_DATA d; - - d.n_obj = 0; //these might not be set otherwise if the input file is corrupt - d.wmf_obj=nullptr; - // Default font, WMF spec says device can pick whatever it wants. + d.n_obj = 0; // these might not be set otherwise if the input file is corrupt + d.wmf_obj = nullptr; + + // Default font, WMF spec says device can pick whatever it wants. // WMF files that do not specify a font are unlikely to look very good! - d.dc[0].style.font_size.computed = 16.0; - d.dc[0].style.font_weight.value = SP_CSS_FONT_WEIGHT_400; - d.dc[0].style.font_style.value = SP_CSS_FONT_STYLE_NORMAL; - d.dc[0].style.text_decoration_line.underline = false; + d.dc[0].style.font_size.computed = 16.0; + d.dc[0].style.font_weight.value = SP_CSS_FONT_WEIGHT_400; + d.dc[0].style.font_style.value = SP_CSS_FONT_STYLE_NORMAL; + d.dc[0].style.text_decoration_line.underline = false; d.dc[0].style.text_decoration_line.line_through = false; - d.dc[0].style.baseline_shift.value = 0; + d.dc[0].style.baseline_shift.value = 0; // Default pen, WMF files that do not specify a pen are unlikely to look very good! - d.dc[0].style.stroke_dasharray.set = false; - d.dc[0].style.stroke_linecap.computed = SP_STROKE_LINECAP_SQUARE; // U_PS_ENDCAP_SQUARE; - d.dc[0].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_MITER; // U_PS_JOIN_MITER; - d.dc[0].style.stroke_width.value = 1.0; // will be reset to something reasonable once WMF drawing size is known - d.dc[0].style.stroke.value.color.set( 0, 0, 0 ); - d.dc[0].stroke_set = true; + d.dc[0].style.stroke_dasharray.set = false; + d.dc[0].style.stroke_linecap.computed = SP_STROKE_LINECAP_SQUARE; // U_PS_ENDCAP_SQUARE; + d.dc[0].style.stroke_linejoin.computed = SP_STROKE_LINEJOIN_MITER; // U_PS_JOIN_MITER; + d.dc[0].style.stroke_width.value = 1.0; // will be reset to something reasonable once WMF drawing size is known + d.dc[0].style.stroke.value.color.set(0, 0, 0); + d.dc[0].stroke_set = true; // Default brush is none - no fill. WMF files that do not specify a brush are unlikely to look very good! - d.dc[0].fill_set = false; + d.dc[0].fill_set = false; - d.dc[0].font_name = strdup("Arial"); // Default font, set only on lowest level, it copies up from there WMF spec says device can pick whatever it wants + d.dc[0].font_name = strdup("Arial"); // Default font, set only on lowest level, it copies up from there WMF spec + // says device can pick whatever it wants - // set up the size default for patterns in defs. This might not be referenced if there are no patterns defined in the drawing. + // set up the size default for patterns in defs. This might not be referenced if there are no patterns defined in + // the drawing. d.defs += "\n"; d.defs += " \n"; d.defs += " \n"; - size_t length; char *contents; - if(wmf_readdata(uri, &contents, &length))return(nullptr); + if (wmf_readdata(uri, &contents, &length)) + return (nullptr); // set up the text reassembly system - if(!(d.tri = trinfo_init(nullptr)))return(nullptr); - (void) trinfo_load_ft_opts(d.tri, 1, - FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, - FT_KERNING_UNSCALED); + if (!(d.tri = trinfo_init(nullptr))) + return (nullptr); + (void)trinfo_load_ft_opts(d.tri, 1, FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, FT_KERNING_UNSCALED); - int good = myMetaFileProc(contents,length, &d); + int good = myMetaFileProc(contents, length, &d); free(contents); -// std::cout << "SVG Output: " << std::endl << d.outsvg << std::endl; + // std::cout << "SVG Output: " << std::endl << d.outsvg << std::endl; SPDocument *doc = nullptr; if (good) { @@ -3184,15 +3254,16 @@ Wmf::open( Inkscape::Extension::Input * /*mod*/, const gchar *uri ) if (d.wmf_obj) { int i; - for (i=0; i -#include "extension/internal/metafile-inout.h" // picks up PNG + #include "extension/implementation/implementation.h" +#include "extension/internal/metafile-inout.h" // picks up PNG #include "style.h" #include "text_reassemble.h" @@ -22,207 +23,228 @@ namespace Inkscape { namespace Extension { namespace Internal { -#define DIRTY_NONE 0x00 -#define DIRTY_TEXT 0x01 -#define DIRTY_FILL 0x02 +#define DIRTY_NONE 0x00 +#define DIRTY_TEXT 0x01 +#define DIRTY_FILL 0x02 #define DIRTY_STROKE 0x04 // not used currently -struct WMF_OBJECT { +struct WMF_OBJECT +{ int type = 0; int level = 0; char *record = nullptr; }; using PWMF_OBJECT = WMF_OBJECT *; -struct WMF_STRINGS { - int size = 0; // number of slots allocated in strings - int count = 0; // number of slots used in strings - char **strings = nullptr; // place to store strings +struct WMF_STRINGS +{ + int size = 0; // number of slots allocated in strings + int count = 0; // number of slots used in strings + char **strings = nullptr; // place to store strings }; using PWMF_STRINGS = WMF_STRINGS *; -struct WMF_DEVICE_CONTEXT { - WMF_DEVICE_CONTEXT() : - // SPStyle: class with constructor - font_name(nullptr), - clip_id(0), - stroke_set(false), stroke_mode(0), stroke_idx(0), stroke_recidx(0), - fill_set(false), fill_mode(0), fill_idx(0), fill_recidx(0), - dirty(0), - active_pen(-1), active_brush(-1), active_font(-1), // -1 when the default is used +struct WMF_DEVICE_CONTEXT +{ + WMF_DEVICE_CONTEXT() + : // SPStyle: class with constructor + font_name(nullptr) + , clip_id(0) + , stroke_set(false) + , stroke_mode(0) + , stroke_idx(0) + , stroke_recidx(0) + , fill_set(false) + , fill_mode(0) + , fill_idx(0) + , fill_recidx(0) + , dirty(0) + , active_pen(-1) + , active_brush(-1) + , active_font(-1) + , // -1 when the default is used // sizeWnd, sizeView, winorg, vieworg, - ScaleInX(0), ScaleInY(0), - ScaleOutX(0), ScaleOutY(0), - bkMode(U_TRANSPARENT), + ScaleInX(0) + , ScaleInY(0) + , ScaleOutX(0) + , ScaleOutY(0) + , bkMode(U_TRANSPARENT) + , // bkColor, textColor textAlign(0) - // worldTransform, cur + // worldTransform, cur { font_name = nullptr; - sizeWnd = point16_set( 0.0, 0.0 ); - sizeView = point16_set( 0.0, 0.0 ); - winorg = point16_set( 0.0, 0.0 ); - vieworg = point16_set( 0.0, 0.0 ); + sizeWnd = point16_set(0.0, 0.0); + sizeView = point16_set(0.0, 0.0); + winorg = point16_set(0.0, 0.0); + vieworg = point16_set(0.0, 0.0); bkColor = U_RGB(255, 255, 255); // default foreground color (white) textColor = U_RGB(0, 0, 0); // default foreground color (black) - cur = point16_set( 0.0, 0.0 ); + cur = point16_set(0.0, 0.0); }; - SPStyle style; - char *font_name; - int clip_id; // 0 if none, else 1 + index into clips - bool stroke_set; - int stroke_mode; // enumeration from drawmode, not used if fill_set is not True - int stroke_idx; // used with DRAW_PATTERN and DRAW_IMAGE to return the appropriate fill - int stroke_recidx;// record used to regenerate hatch when it needs to be redone due to bkmode, textmode, etc. change - bool fill_set; - int fill_mode; // enumeration from drawmode, not used if fill_set is not True - int fill_idx; // used with DRAW_PATTERN and DRAW_IMAGE to return the appropriate fill - int fill_recidx; // record used to regenerate hatch when it needs to be redone due to bkmode, textmode, etc. change - int dirty; // holds the dirty bits for text, stroke, fill - int active_pen; // used when the active object is deleted to set the default values, -1 is none active - int active_brush; // ditto - int active_font; // ditto. also used to hold object number in case font needs to be remade due to textcolor change. - U_POINT16 sizeWnd; - U_POINT16 sizeView; - U_POINT16 winorg; - U_POINT16 vieworg; - double ScaleInX, ScaleInY; - double ScaleOutX, ScaleOutY; - uint16_t bkMode; - U_COLORREF bkColor; - U_COLORREF textColor; - uint16_t textAlign; - U_POINT16 cur; + SPStyle style; + char *font_name; + int clip_id; // 0 if none, else 1 + index into clips + bool stroke_set; + int stroke_mode; // enumeration from drawmode, not used if fill_set is not True + int stroke_idx; // used with DRAW_PATTERN and DRAW_IMAGE to return the appropriate fill + int stroke_recidx; // record used to regenerate hatch when it needs to be redone due to bkmode, textmode, etc. + // change + bool fill_set; + int fill_mode; // enumeration from drawmode, not used if fill_set is not True + int fill_idx; // used with DRAW_PATTERN and DRAW_IMAGE to return the appropriate fill + int fill_recidx; // record used to regenerate hatch when it needs to be redone due to bkmode, textmode, etc. change + int dirty; // holds the dirty bits for text, stroke, fill + int active_pen; // used when the active object is deleted to set the default values, -1 is none active + int active_brush; // ditto + int active_font; // ditto. also used to hold object number in case font needs to be remade due to textcolor change. + U_POINT16 sizeWnd; + U_POINT16 sizeView; + U_POINT16 winorg; + U_POINT16 vieworg; + double ScaleInX, ScaleInY; + double ScaleOutX, ScaleOutY; + uint16_t bkMode; + U_COLORREF bkColor; + U_COLORREF textColor; + uint16_t textAlign; + U_POINT16 cur; }; using PWMF_DEVICE_CONTEXT = WMF_DEVICE_CONTEXT *; #define WMF_MAX_DC 128 - // like this causes a mysterious crash on the return from Wmf::open -//typedef struct emf_callback_data { +// typedef struct emf_callback_data { // this fixes it, so some confusion between this struct and the one in emf-inout??? -//typedef struct wmf_callback_data { +// typedef struct wmf_callback_data { // as does this -struct WMF_CALLBACK_DATA { - - WMF_CALLBACK_DATA() : - // dc: array, structure w/ constructor - level(0), - E2IdirY(1.0), - D2PscaleX(1.0), D2PscaleY(1.0), - PixelsInX(0), PixelsInY(0), - PixelsOutX(0), PixelsOutY(0), - ulCornerInX(0), ulCornerInY(0), - ulCornerOutX(0), ulCornerOutY(0), - mask(0), - arcdir(U_AD_COUNTERCLOCKWISE), - dwRop2(U_R2_COPYPEN), dwRop3(0), - id(0), drawtype(0), +struct WMF_CALLBACK_DATA +{ + WMF_CALLBACK_DATA() + : // dc: array, structure w/ constructor + level(0) + , E2IdirY(1.0) + , D2PscaleX(1.0) + , D2PscaleY(1.0) + , PixelsInX(0) + , PixelsInY(0) + , PixelsOutX(0) + , PixelsOutY(0) + , ulCornerInX(0) + , ulCornerInY(0) + , ulCornerOutX(0) + , ulCornerOutY(0) + , mask(0) + , arcdir(U_AD_COUNTERCLOCKWISE) + , dwRop2(U_R2_COPYPEN) + , dwRop3(0) + , id(0) + , drawtype(0) + , // hatches, images, gradients, struct w/ constructor - tri(nullptr), - n_obj(0), - low_water(0) - //wmf_obj - {}; + tri(nullptr) + , n_obj(0) + , low_water(0) + // wmf_obj + {}; Glib::ustring outsvg; Glib::ustring path; Glib::ustring outdef; Glib::ustring defs; - WMF_DEVICE_CONTEXT dc[WMF_MAX_DC+1]; // FIXME: This should be dynamic.. + WMF_DEVICE_CONTEXT dc[WMF_MAX_DC + 1]; // FIXME: This should be dynamic.. int level; - - double E2IdirY; // WMF Y direction relative to Inkscape Y direction. Will be negative for MM_LOMETRIC etc. - double D2PscaleX,D2PscaleY; // WMF device to Inkscape Page scale. - float PixelsInX, PixelsInY; // size of the drawing, in WMF device pixels - float PixelsOutX, PixelsOutY; // size of the drawing, in Inkscape pixels - double ulCornerInX,ulCornerInY; // Upper left corner, from header rclBounds, in logical units - double ulCornerOutX,ulCornerOutY; // Upper left corner, in Inkscape pixels - uint32_t mask; // Draw properties - int arcdir; // U_AD_COUNTERCLOCKWISE 1 or U_AD_CLOCKWISE 2 - - uint32_t dwRop2; // Binary raster operation, 0 if none (use brush/pen unmolested) - uint32_t dwRop3; // Ternary raster operation, 0 if none (use brush/pen unmolested) - unsigned int id; - unsigned int drawtype; // one of 0 or U_WMR_FILLPATH, U_WMR_STROKEPATH, U_WMR_STROKEANDFILLPATH - // both of these end up in under the names shown here. These structures allow duplicates to be avoided. - WMF_STRINGS hatches; // hold pattern names, all like WMFhatch#_$$$$$$ where # is the WMF hatch code and $$$$$$ is the color - WMF_STRINGS images; // hold images, all like Image#, where # is the slot the image lives. - WMF_STRINGS clips; // hold clipping paths, referred to be the slot where the clipping path lives - TR_INFO *tri; // Text Reassembly data structure + double E2IdirY; // WMF Y direction relative to Inkscape Y direction. Will be negative for MM_LOMETRIC etc. + double D2PscaleX, D2PscaleY; // WMF device to Inkscape Page scale. + float PixelsInX, PixelsInY; // size of the drawing, in WMF device pixels + float PixelsOutX, PixelsOutY; // size of the drawing, in Inkscape pixels + double ulCornerInX, ulCornerInY; // Upper left corner, from header rclBounds, in logical units + double ulCornerOutX, ulCornerOutY; // Upper left corner, in Inkscape pixels + uint32_t mask; // Draw properties + int arcdir; // U_AD_COUNTERCLOCKWISE 1 or U_AD_CLOCKWISE 2 + + uint32_t dwRop2; // Binary raster operation, 0 if none (use brush/pen unmolested) + uint32_t dwRop3; // Ternary raster operation, 0 if none (use brush/pen unmolested) + unsigned int id; + unsigned int drawtype; // one of 0 or U_WMR_FILLPATH, U_WMR_STROKEPATH, U_WMR_STROKEANDFILLPATH + // both of these end up in under the names shown here. These structures allow + // duplicates to be avoided. + WMF_STRINGS hatches; // hold pattern names, all like WMFhatch#_$$$$$$ where # is the WMF hatch code and $$$$$$ is + // the color + WMF_STRINGS images; // hold images, all like Image#, where # is the slot the image lives. + WMF_STRINGS clips; // hold clipping paths, referred to be the slot where the clipping path lives + TR_INFO *tri; // Text Reassembly data structure int n_obj; - int low_water; // first object slot which _might_ be unoccupied. Everything below is filled. + int low_water; // first object slot which _might_ be unoccupied. Everything below is filled. PWMF_OBJECT wmf_obj; }; using PWMF_CALLBACK_DATA = WMF_CALLBACK_DATA *; class Wmf : public Metafile { - public: Wmf(); // Empty constructor - ~Wmf() override;//Destructor + ~Wmf() override; // Destructor - bool check(Inkscape::Extension::Extension *module) override; //Can this module load (always yes for now) + bool check(Inkscape::Extension::Extension *module) override; // Can this module load (always yes for now) void save(Inkscape::Extension::Output *mod, // Save the given document to the given filename - SPDocument *doc, - gchar const *filename) override; + SPDocument *doc, gchar const *filename) override; - SPDocument *open( Inkscape::Extension::Input *mod, - const gchar *uri ) override; + SPDocument *open(Inkscape::Extension::Input *mod, const gchar *uri) override; - static void init();//Initialize the class + static void init(); // Initialize the class private: protected: - static void print_document_to_file(SPDocument *doc, const gchar *filename); - static double current_scale(PWMF_CALLBACK_DATA d); - static std::string current_matrix(PWMF_CALLBACK_DATA d, double x, double y, int useoffset); - static double current_rotation(PWMF_CALLBACK_DATA d); - static void enlarge_hatches(PWMF_CALLBACK_DATA d); - static int in_hatches(PWMF_CALLBACK_DATA d, char *test); - static uint32_t add_hatch(PWMF_CALLBACK_DATA d, uint32_t hatchType, U_COLORREF hatchColor); - static void enlarge_images(PWMF_CALLBACK_DATA d); - static int in_images(PWMF_CALLBACK_DATA d, char *test); - static uint32_t add_dib_image(PWMF_CALLBACK_DATA d, const char *dib, uint32_t iUsage); - static uint32_t add_bm16_image(PWMF_CALLBACK_DATA d, U_BITMAP16 Bm16, const char *px); - - static void enlarge_clips(PWMF_CALLBACK_DATA d); - static int in_clips(PWMF_CALLBACK_DATA d, const char *test); - static void add_clips(PWMF_CALLBACK_DATA d, const char *clippath, unsigned int logic); - - static void output_style(PWMF_CALLBACK_DATA d); - static double _pix_x_to_point(PWMF_CALLBACK_DATA d, double px); - static double _pix_y_to_point(PWMF_CALLBACK_DATA d, double py); - static double pix_to_x_point(PWMF_CALLBACK_DATA d, double px, double py); - static double pix_to_y_point(PWMF_CALLBACK_DATA d, double px, double py); - static double pix_to_abs_size(PWMF_CALLBACK_DATA d, double px); - static std::string pix_to_xy(PWMF_CALLBACK_DATA d, double x, double y); - static void select_brush(PWMF_CALLBACK_DATA d, int index); - static void select_font(PWMF_CALLBACK_DATA d, int index); - static void select_pen(PWMF_CALLBACK_DATA d, int index); - static int insertable_object(PWMF_CALLBACK_DATA d); - static void delete_object(PWMF_CALLBACK_DATA d, int index); - static int insert_object(PWMF_CALLBACK_DATA d, int type, const char *record); - static uint32_t *unknown_chars(size_t count); - static void common_dib_to_image(PWMF_CALLBACK_DATA d, const char *dib, - double dx, double dy, double dw, double dh, int sx, int sy, int sw, int sh, uint32_t iUsage); - static void common_bm16_to_image(PWMF_CALLBACK_DATA d, U_BITMAP16 Bm16, const char *px, - double dx, double dy, double dw, double dh, int sx, int sy, int sw, int sh); - static int myMetaFileProc(const char *contents, unsigned int length, PWMF_CALLBACK_DATA d); - static void free_wmf_strings(WMF_STRINGS name); + static void print_document_to_file(SPDocument *doc, const gchar *filename); + static double current_scale(PWMF_CALLBACK_DATA d); + static std::string current_matrix(PWMF_CALLBACK_DATA d, double x, double y, int useoffset); + static double current_rotation(PWMF_CALLBACK_DATA d); + static void enlarge_hatches(PWMF_CALLBACK_DATA d); + static int in_hatches(PWMF_CALLBACK_DATA d, char *test); + static uint32_t add_hatch(PWMF_CALLBACK_DATA d, uint32_t hatchType, U_COLORREF hatchColor); + static void enlarge_images(PWMF_CALLBACK_DATA d); + static int in_images(PWMF_CALLBACK_DATA d, char *test); + static uint32_t add_dib_image(PWMF_CALLBACK_DATA d, const char *dib, uint32_t iUsage); + static uint32_t add_bm16_image(PWMF_CALLBACK_DATA d, U_BITMAP16 Bm16, const char *px); -}; + static void enlarge_clips(PWMF_CALLBACK_DATA d); + static int in_clips(PWMF_CALLBACK_DATA d, const char *test); + static void add_clips(PWMF_CALLBACK_DATA d, const char *clippath, unsigned int logic); -} } } /* namespace Inkscape, Extension, Implementation */ + static void output_style(PWMF_CALLBACK_DATA d); + static double _pix_x_to_point(PWMF_CALLBACK_DATA d, double px); + static double _pix_y_to_point(PWMF_CALLBACK_DATA d, double py); + static double pix_to_x_point(PWMF_CALLBACK_DATA d, double px, double py); + static double pix_to_y_point(PWMF_CALLBACK_DATA d, double px, double py); + static double pix_to_abs_size(PWMF_CALLBACK_DATA d, double px); + static std::string pix_to_xy(PWMF_CALLBACK_DATA d, double x, double y); + static void select_brush(PWMF_CALLBACK_DATA d, int index); + static void select_font(PWMF_CALLBACK_DATA d, int index); + static void select_pen(PWMF_CALLBACK_DATA d, int index); + static int insertable_object(PWMF_CALLBACK_DATA d); + static void delete_object(PWMF_CALLBACK_DATA d, int index); + static int insert_object(PWMF_CALLBACK_DATA d, int type, const char *record); + static uint32_t *unknown_chars(size_t count); + static void common_dib_to_image(PWMF_CALLBACK_DATA d, const char *dib, double dx, double dy, double dw, double dh, + int sx, int sy, int sw, int sh, uint32_t iUsage); + static void common_bm16_to_image(PWMF_CALLBACK_DATA d, U_BITMAP16 Bm16, const char *px, double dx, double dy, + double dw, double dh, int sx, int sy, int sw, int sh); + static int myMetaFileProc(const char *contents, unsigned int length, PWMF_CALLBACK_DATA d); + static void free_wmf_strings(WMF_STRINGS name); +}; +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* EXTENSION_INTERNAL_WMF_H */ diff --git a/src/extension/internal/wmf-print.cpp b/src/extension/internal/wmf-print.cpp index 855da88c4217385ed36d2bcaefbc69796d5dba1f..ffef36d7f65ae518784079584716ea26d890c604 100644 --- a/src/extension/internal/wmf-print.cpp +++ b/src/extension/internal/wmf-print.cpp @@ -24,85 +24,78 @@ * http://msdn.microsoft.com/library/en-us/gdi/metafile_5hkj.asp */ -#include <2geom/sbasis-to-bezier.h> -#include <2geom/elliptical-arc.h> +#include "wmf-print.h" +#include <2geom/curves.h> +#include <2geom/elliptical-arc.h> #include <2geom/path.h> #include <2geom/pathvector.h> #include <2geom/rect.h> -#include <2geom/curves.h> -#include "helper/geom.h" -#include "helper/geom-curves.h" - -#include "inkscape-version.h" - -#include "util/units.h" +#include <2geom/sbasis-to-bezier.h> +#include <2geom/svg-path-parser.h> // to get from SVG text to Geom::Path +#include <3rdparty/libuemf/symbol_convert.h> +#include -#include "extension/system.h" -#include "extension/print.h" +#include "display/cairo-utils.h" // for Inkscape::Pixbuf::PF_CAIRO #include "document.h" -#include "path-prefix.h" - -#include "object/sp-pattern.h" -#include "object/sp-image.h" +#include "extension/print.h" +#include "extension/system.h" +#include "helper/geom-curves.h" +#include "helper/geom.h" +#include "inkscape-version.h" #include "object/sp-gradient.h" -#include "object/sp-radial-gradient.h" +#include "object/sp-image.h" +#include "object/sp-item.h" #include "object/sp-linear-gradient.h" +#include "object/sp-pattern.h" +#include "object/sp-radial-gradient.h" #include "object/sp-root.h" -#include "object/sp-item.h" - +#include "path-prefix.h" #include "path/path-boolop.h" - -#include <2geom/svg-path-parser.h> // to get from SVG text to Geom::Path - -#include "display/cairo-utils.h" // for Inkscape::Pixbuf::PF_CAIRO - -#include "wmf-print.h" - -#include -#include <3rdparty/libuemf/symbol_convert.h> +#include "util/units.h" namespace Inkscape { namespace Extension { namespace Internal { #define PXPERMETER 2835 -#define MAXDISP 2.0 // This should be set in the output dialog. This is ok for experimenting, no more than 2 pixel deviation. Not actually used at present - +#define MAXDISP \ + 2.0 // This should be set in the output dialog. This is ok for experimenting, no more than 2 pixel deviation. Not + // actually used at present /* globals */ -static double PX2WORLD; // value set in begin() -static bool FixPPTCharPos, FixPPTDashLine, FixPPTGrad2Polys, FixPPTPatternAsHatch; -static WMFTRACK *wt = nullptr; -static WMFHANDLES *wht = nullptr; +static double PX2WORLD; // value set in begin() +static bool FixPPTCharPos, FixPPTDashLine, FixPPTGrad2Polys, FixPPTPatternAsHatch; +static WMFTRACK *wt = nullptr; +static WMFHANDLES *wht = nullptr; void PrintWmf::smuggle_adxky_out(const char *string, int16_t **adx, double *ky, int *rtl, int *ndx, float scale) { - float fdx; - int i; - int16_t *ladx; + float fdx; + int i; + int16_t *ladx; const char *cptr = &string[strlen(string) + 1]; // this works because of the first fake terminator *adx = nullptr; - *ky = 0.0; // set a default value + *ky = 0.0; // set a default value sscanf(cptr, "%7d", ndx); if (!*ndx) { - return; // this could happen with an empty string + return; // this could happen with an empty string } cptr += 7; - ladx = (int16_t *) malloc(*ndx * sizeof(int16_t)); + ladx = (int16_t *)malloc(*ndx * sizeof(int16_t)); if (!ladx) { g_error("Out of memory"); } *adx = ladx; for (i = 0; i < *ndx; i++, cptr += 7, ladx++) { sscanf(cptr, "%7f", &fdx); - *ladx = (int16_t) round(fdx * scale); + *ladx = (int16_t)round(fdx * scale); } cptr++; // skip 2nd fake terminator sscanf(cptr, "%7f", &fdx); *ky = fdx; - cptr += 7; // advance over ky and its space + cptr += 7; // advance over ky and its space sscanf(cptr, "%07d", rtl); } @@ -111,31 +104,29 @@ PrintWmf::PrintWmf() // all of the class variables are initialized elsewhere, many in PrintWmf::Begin, } - unsigned int PrintWmf::setup(Inkscape::Extension::Print * /*mod*/) { return TRUE; } - unsigned int PrintWmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) { - char *rec; - gchar const *utf8_fn = mod->get_param_string("destination"); + char *rec; + gchar const *utf8_fn = mod->get_param_string("destination"); // Typically PX2WORLD is 1200/90, using inkscape's default dpi PX2WORLD = 1200.0 / Inkscape::Util::Quantity::convert(1.0, "in", "px"); - FixPPTCharPos = mod->get_param_bool("FixPPTCharPos"); - FixPPTDashLine = mod->get_param_bool("FixPPTDashLine"); - FixPPTGrad2Polys = mod->get_param_bool("FixPPTGrad2Polys"); + FixPPTCharPos = mod->get_param_bool("FixPPTCharPos"); + FixPPTDashLine = mod->get_param_bool("FixPPTDashLine"); + FixPPTGrad2Polys = mod->get_param_bool("FixPPTGrad2Polys"); FixPPTPatternAsHatch = mod->get_param_bool("FixPPTPatternAsHatch"); - (void) wmf_start(utf8_fn, 1000000, 250000, &wt); // Initialize the wt structure - (void) wmf_htable_create(128, 128, &wht); // Initialize the wht structure + (void)wmf_start(utf8_fn, 1000000, 250000, &wt); // Initialize the wt structure + (void)wmf_htable_create(128, 128, &wht); // Initialize the wht structure // WMF header the only things that can be set are the page size in inches (w,h) and the dpi // width and height in px - _width = doc->getWidth().value("px"); + _width = doc->getWidth().value("px"); _height = doc->getHeight().value("px"); // initialize a few global variables @@ -147,14 +138,14 @@ unsigned int PrintWmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) if (nv) { const char *p1 = nv->attribute("pagecolor"); char *p2; - uint32_t lc = strtoul(&p1[1], &p2, 16); // it looks like "#ABC123" + uint32_t lc = strtoul(&p1[1], &p2, 16); // it looks like "#ABC123" if (*p2) { lc = 0; } gv.bgc = _gethexcolor(lc); - gv.rgb[0] = (float) U_RGBAGetR(gv.bgc) / 255.0; - gv.rgb[1] = (float) U_RGBAGetG(gv.bgc) / 255.0; - gv.rgb[2] = (float) U_RGBAGetB(gv.bgc) / 255.0; + gv.rgb[0] = (float)U_RGBAGetR(gv.bgc) / 255.0; + gv.rgb[1] = (float)U_RGBAGetG(gv.bgc) / 255.0; + gv.rgb[2] = (float)U_RGBAGetB(gv.bgc) / 255.0; } bool pageBoundingBox; @@ -171,13 +162,14 @@ unsigned int PrintWmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) } } - d *= Geom::Scale(Inkscape::Util::Quantity::convert(1, "px", "in")); // 90 dpi inside inkscape, wmf file will be 1200 dpi + d *= Geom::Scale(Inkscape::Util::Quantity::convert(1, "px", "in")); // 90 dpi inside inkscape, wmf file will be 1200 + // dpi /* -1/1200 in next two lines so that WMF read in will write out again at exactly the same size */ - float dwInchesX = d.width() - 1.0 / 1200.0; + float dwInchesX = d.width() - 1.0 / 1200.0; float dwInchesY = d.height() - 1.0 / 1200.0; - int dwPxX = round(dwInchesX * 1200.0); - int dwPxY = round(dwInchesY * 1200.0); + int dwPxX = round(dwInchesX * 1200.0); + int dwPxY = round(dwInchesY * 1200.0); #if 0 float dwInchesX = d.width(); float dwInchesY = d.height(); @@ -192,7 +184,7 @@ unsigned int PrintWmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) g_warning("Failed in PrintWmf::begin at WMRHEADER"); return -1; } - (void) wmf_header_append((U_METARECORD *)rec, wt, 1); + (void)wmf_header_append((U_METARECORD *)rec, wt, 1); rec = U_WMRSETWINDOWEXT_set(point16_set(dwPxX, dwPxY)); if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { @@ -257,10 +249,10 @@ unsigned int PrintWmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) return -1; } - - // create a pen as object 0. We never use it (except by mistake). Its purpose it to make all of the other object indices >=1 + // create a pen as object 0. We never use it (except by mistake). Its purpose it to make all of the other object + // indices >=1 U_PEN up = U_PEN_set(U_PS_SOLID, 1, colorref_set(0, 0, 0)); - uint32_t Pen; + uint32_t Pen; rec = wcreatepenindirect_set(&Pen, wht, up); if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { g_warning("Failed in PrintWmf::begin at wcreatepenindirect_set"); @@ -288,7 +280,6 @@ unsigned int PrintWmf::begin(Inkscape::Extension::Print *mod, SPDocument *doc) return 0; } - unsigned int PrintWmf::finish(Inkscape::Extension::Print * /*mod*/) { char *rec; @@ -315,18 +306,17 @@ unsigned int PrintWmf::finish(Inkscape::Extension::Print * /*mod*/) g_error("Fatal programming error in PrintWmf::finish at wdeleteobject_set filler object"); } - rec = U_WMREOF_set(); // generate the EOF record + rec = U_WMREOF_set(); // generate the EOF record if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { g_error("Fatal programming error in PrintWmf::finish"); } - (void) wmf_finish(wt); // Finalize and write out the WMF - uwmf_free(&wt); // clean up - wmf_htable_free(&wht); // clean up + (void)wmf_finish(wt); // Finalize and write out the WMF + uwmf_free(&wt); // clean up + wmf_htable_free(&wht); // clean up return 0; } - unsigned int PrintWmf::comment(Inkscape::Extension::Print * /*module*/, const char * /*comment*/) { if (!wt) { @@ -338,33 +328,32 @@ unsigned int PrintWmf::comment(Inkscape::Extension::Print * /*module*/, const ch return 0; } - // fcolor is defined when gradients are being expanded, it is the color of one stripe or ring. int PrintWmf::create_brush(SPStyle const *style, U_COLORREF *fcolor) { - float rgb[3]; - char *rec; - U_WLOGBRUSH lb; - uint32_t brush, fmode; - MFDrawMode fill_mode; + float rgb[3]; + char *rec; + U_WLOGBRUSH lb; + uint32_t brush, fmode; + MFDrawMode fill_mode; Inkscape::Pixbuf *pixbuf; - uint32_t brushStyle; - int hatchType; - U_COLORREF hatchColor; - U_COLORREF bkColor; - uint32_t width = 0; // quiets a harmless compiler warning, initialization not otherwise required. - uint32_t height = 0; + uint32_t brushStyle; + int hatchType; + U_COLORREF hatchColor; + U_COLORREF bkColor; + uint32_t width = 0; // quiets a harmless compiler warning, initialization not otherwise required. + uint32_t height = 0; if (!wt) { return 0; } // set a default fill in case we can't figure out a better way to do it - fmode = U_ALTERNATE; - fill_mode = DRAW_PAINT; + fmode = U_ALTERNATE; + fill_mode = DRAW_PAINT; brushStyle = U_BS_SOLID; - hatchType = U_HS_SOLIDCLR; - bkColor = U_RGB(0, 0, 0); + hatchType = U_HS_SOLIDCLR; + bkColor = U_RGB(0, 0, 0); if (fcolor) { hatchColor = *fcolor; } else { @@ -383,13 +372,14 @@ int PrintWmf::create_brush(SPStyle const *style, U_COLORREF *fcolor) style->fill.value.color.get_rgb_floatv(rgb); hatchColor = U_RGB(255 * rgb[0], 255 * rgb[1], 255 * rgb[2]); - fmode = style->fill_rule.computed == 0 ? U_WINDING : (style->fill_rule.computed == 2 ? U_ALTERNATE : U_ALTERNATE); + fmode = style->fill_rule.computed == 0 ? U_WINDING + : (style->fill_rule.computed == 2 ? U_ALTERNATE : U_ALTERNATE); } else if (SP_IS_PATTERN(SP_STYLE_FILL_SERVER(style))) { // must be paint-server SPPaintServer *paintserver = style->fill.value.href->getObject(); SPPattern *pat = SP_PATTERN(paintserver); - double dwidth = pat->width(); + double dwidth = pat->width(); double dheight = pat->height(); - width = dwidth; + width = dwidth; height = dheight; brush_classify(pat, 0, &pixbuf, &hatchType, &hatchColor, &bkColor); if (pixbuf) { @@ -397,20 +387,21 @@ int PrintWmf::create_brush(SPStyle const *style, U_COLORREF *fcolor) } else { // pattern fill_mode = DRAW_PATTERN; if (hatchType == -1) { // Not a standard hatch, so force it to something - hatchType = U_HS_CROSS; + hatchType = U_HS_CROSS; hatchColor = U_RGB(0xFF, 0xC3, 0xC3); } } if (FixPPTPatternAsHatch) { if (hatchType == -1) { // image or unclassified - fill_mode = DRAW_PATTERN; - hatchType = U_HS_DIAGCROSS; + fill_mode = DRAW_PATTERN; + hatchType = U_HS_DIAGCROSS; hatchColor = U_RGB(0xFF, 0xC3, 0xC3); } } brushStyle = U_BS_HATCHED; } else if (SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style))) { // must be a gradient - // currently we do not do anything with gradients, the code below just sets the color to the average of the stops + // currently we do not do anything with gradients, the code below just sets the color to the average of the + // stops SPPaintServer *paintserver = style->fill.value.href->getObject(); SPLinearGradient *lg = nullptr; SPRadialGradient *rg = nullptr; @@ -446,53 +437,56 @@ int PrintWmf::create_brush(SPStyle const *style, U_COLORREF *fcolor) } switch (fill_mode) { - case DRAW_LINEAR_GRADIENT: // fill with average color unless gradients are converted to slices - case DRAW_RADIAL_GRADIENT: // ditto - case DRAW_PAINT: - case DRAW_PATTERN: - // SVG text has no background attribute, so OPAQUE mode ALWAYS cancels after the next draw, otherwise it would mess up future text output. - if (usebk) { - rec = U_WMRSETBKCOLOR_set(bkColor); + case DRAW_LINEAR_GRADIENT: // fill with average color unless gradients are converted to slices + case DRAW_RADIAL_GRADIENT: // ditto + case DRAW_PAINT: + case DRAW_PATTERN: + // SVG text has no background attribute, so OPAQUE mode ALWAYS cancels after the next draw, otherwise it + // would mess up future text output. + if (usebk) { + rec = U_WMRSETBKCOLOR_set(bkColor); + if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { + g_error("Fatal programming error in PrintWmf::create_brush at U_WMRSETBKCOLOR_set"); + } + rec = U_WMRSETBKMODE_set(U_OPAQUE); + if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { + g_error("Fatal programming error in PrintWmf::create_brush at U_WMRSETBKMODE_set"); + } + } + lb = U_WLOGBRUSH_set(brushStyle, hatchColor, hatchType); + rec = wcreatebrushindirect_set(&brush, wht, lb); if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { - g_error("Fatal programming error in PrintWmf::create_brush at U_WMRSETBKCOLOR_set"); + g_error("Fatal programming error in PrintWmf::create_brush at createbrushindirect_set"); + } + break; + case DRAW_IMAGE: + char *px; + char *rgba_px; + uint32_t cbPx; + uint32_t colortype; + U_RGBQUAD *ct; + int numCt; + U_BITMAPINFOHEADER Bmih; + U_BITMAPINFO *Bmi; + rgba_px = (char *)pixbuf->pixels(); // Do NOT free this!!! + colortype = U_BCBM_COLOR32; + (void)RGBA_to_DIB(&px, &cbPx, &ct, &numCt, rgba_px, width, height, width * 4, colortype, 0, 1); + // pixbuf can be either PF_CAIRO or PF_GDK, and these have R and B bytes swapped + if (pixbuf->pixelFormat() == Inkscape::Pixbuf::PF_CAIRO) { + swapRBinRGBA(px, width * height); } - rec = U_WMRSETBKMODE_set(U_OPAQUE); + Bmih = bitmapinfoheader_set(width, height, 1, colortype, U_BI_RGB, 0, PXPERMETER, PXPERMETER, numCt, 0); + Bmi = bitmapinfo_set(Bmih, ct); + rec = wcreatedibpatternbrush_srcdib_set(&brush, wht, U_DIB_RGB_COLORS, Bmi, cbPx, px); if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { - g_error("Fatal programming error in PrintWmf::create_brush at U_WMRSETBKMODE_set"); + g_error("Fatal programming error in PrintWmf::create_brush at createdibpatternbrushpt_set"); } - } - lb = U_WLOGBRUSH_set(brushStyle, hatchColor, hatchType); - rec = wcreatebrushindirect_set(&brush, wht, lb); - if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { - g_error("Fatal programming error in PrintWmf::create_brush at createbrushindirect_set"); - } - break; - case DRAW_IMAGE: - char *px; - char *rgba_px; - uint32_t cbPx; - uint32_t colortype; - U_RGBQUAD *ct; - int numCt; - U_BITMAPINFOHEADER Bmih; - U_BITMAPINFO *Bmi; - rgba_px = (char *) pixbuf->pixels(); // Do NOT free this!!! - colortype = U_BCBM_COLOR32; - (void) RGBA_to_DIB(&px, &cbPx, &ct, &numCt, rgba_px, width, height, width * 4, colortype, 0, 1); - // pixbuf can be either PF_CAIRO or PF_GDK, and these have R and B bytes swapped - if (pixbuf->pixelFormat() == Inkscape::Pixbuf::PF_CAIRO) { swapRBinRGBA(px, width * height); } - Bmih = bitmapinfoheader_set(width, height, 1, colortype, U_BI_RGB, 0, PXPERMETER, PXPERMETER, numCt, 0); - Bmi = bitmapinfo_set(Bmih, ct); - rec = wcreatedibpatternbrush_srcdib_set(&brush, wht, U_DIB_RGB_COLORS, Bmi, cbPx, px); - if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { - g_error("Fatal programming error in PrintWmf::create_brush at createdibpatternbrushpt_set"); - } - free(px); - free(Bmi); // ct will be NULL because of colortype - break; + free(px); + free(Bmi); // ct will be NULL because of colortype + break; } - hbrush = brush; // need this later for destroy_brush + hbrush = brush; // need this later for destroy_brush rec = wselectobject_set(brush, wht); if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { g_error("Fatal programming error in PrintWmf::create_brush at wselectobject_set"); @@ -509,7 +503,6 @@ int PrintWmf::create_brush(SPStyle const *style, U_COLORREF *fcolor) return 0; } - void PrintWmf::destroy_brush() { char *rec; @@ -530,15 +523,14 @@ void PrintWmf::destroy_brush() } } - int PrintWmf::create_pen(SPStyle const *style, const Geom::Affine &transform) { - char *rec = nullptr; - uint32_t pen; - uint32_t penstyle; - U_COLORREF penColor; - U_PEN up; - int modstyle; + char *rec = nullptr; + uint32_t pen; + uint32_t penstyle; + U_COLORREF penColor; + U_PEN up; + int modstyle; if (!wt) { return 0; @@ -550,7 +542,7 @@ int PrintWmf::create_pen(SPStyle const *style, const Geom::Affine &transform) penColor = U_RGB(0, 0, 0); uint32_t linewidth = 1; - if (style) { // override some or all of the preceding + if (style) { // override some or all of the preceding float rgb[3]; // WMF does not support hatched, bitmap, or gradient pens, just set the color. @@ -569,11 +561,12 @@ int PrintWmf::create_pen(SPStyle const *style, const Geom::Affine &transform) double scale = sqrt((p[X] * p[X]) + (p[Y] * p[Y])) / sqrt(2); if (!style->stroke_width.computed) { - return 0; //if width is 0 do not (reset) the pen, it should already be NULL_PEN + return 0; // if width is 0 do not (reset) the pen, it should already be NULL_PEN } - linewidth = MAX(1, (uint32_t) round(scale * style->stroke_width.computed * PX2WORLD)); + linewidth = MAX(1, (uint32_t)round(scale * style->stroke_width.computed * PX2WORLD)); - // most WMF readers will ignore linecap and linejoin, but set them anyway. Inkscape itself can read them back in. + // most WMF readers will ignore linecap and linejoin, but set them anyway. Inkscape itself can read them back + // in. if (style->stroke_linecap.computed == 0) { modstyle |= U_PS_ENDCAP_FLAT; @@ -584,7 +577,7 @@ int PrintWmf::create_pen(SPStyle const *style, const Geom::Affine &transform) } if (style->stroke_linejoin.computed == 0) { - float miterlimit = style->stroke_miterlimit.value; // This is a ratio. + float miterlimit = style->stroke_miterlimit.value; // This is a ratio. if (miterlimit < 1) { miterlimit = 1; } @@ -592,7 +585,7 @@ int PrintWmf::create_pen(SPStyle const *style, const Geom::Affine &transform) // most WMF readers will ignore miterlimit, but set it anyway. Inkscape itself can read it back in if ((uint32_t)miterlimit != hmiterlimit) { hmiterlimit = (uint32_t)miterlimit; - rec = wmiterlimit_set((uint32_t) miterlimit); + rec = wmiterlimit_set((uint32_t)miterlimit); if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { g_error("Fatal programming error in PrintWmf::create_pen at wmiterlimit_set"); } @@ -608,10 +601,10 @@ int PrintWmf::create_pen(SPStyle const *style, const Geom::Affine &transform) if (!FixPPTDashLine) { // if this is set code elsewhere will break dots/dashes into many smaller lines. int n_dash = style->stroke_dasharray.values.size(); /* options are dash, dot, dashdot and dashdotdot. Try to pick the closest one. */ - int mark_short=INT_MAX; - int mark_long =0; + int mark_short = INT_MAX; + int mark_long = 0; int i; - for (i=0;istroke_dasharray.values[i].value; if (mark > mark_long) { mark_long = mark; @@ -620,24 +613,20 @@ int PrintWmf::create_pen(SPStyle const *style, const Geom::Affine &transform) mark_short = mark; } } - if(mark_long == mark_short){ // only one mark size - penstyle = U_PS_DOT; - } - else if (n_dash==2) { - penstyle = U_PS_DASH; - } - else if (n_dash==4) { - penstyle = U_PS_DASHDOT; - } - else { - penstyle = U_PS_DASHDOTDOT; + if (mark_long == mark_short) { // only one mark size + penstyle = U_PS_DOT; + } else if (n_dash == 2) { + penstyle = U_PS_DASH; + } else if (n_dash == 4) { + penstyle = U_PS_DASHDOT; + } else { + penstyle = U_PS_DASHDOTDOT; } } } - } - up = U_PEN_set(penstyle | modstyle, linewidth, penColor); + up = U_PEN_set(penstyle | modstyle, linewidth, penColor); rec = wcreatepenindirect_set(&pen, wht, up); if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { g_error("Fatal programming error in PrintWmf::create_pen at wcreatepenindirect_set"); @@ -647,7 +636,7 @@ int PrintWmf::create_pen(SPStyle const *style, const Geom::Affine &transform) if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { g_error("Fatal programming error in PrintWmf::create_pen at wselectobject_set"); } - hpen = pen; // need this later for destroy_pen + hpen = pen; // need this later for destroy_pen return 0; } @@ -673,18 +662,16 @@ void PrintWmf::destroy_pen() } } - -unsigned int PrintWmf::fill( - Inkscape::Extension::Print * /*mod*/, - Geom::PathVector const &pathv, Geom::Affine const & /*transform*/, SPStyle const *style, - Geom::OptRect const &/*pbox*/, Geom::OptRect const &/*dbox*/, Geom::OptRect const &/*bbox*/) +unsigned int PrintWmf::fill(Inkscape::Extension::Print * /*mod*/, Geom::PathVector const &pathv, + Geom::Affine const & /*transform*/, SPStyle const *style, Geom::OptRect const & /*pbox*/, + Geom::OptRect const & /*dbox*/, Geom::OptRect const & /*bbox*/) { using Geom::X; using Geom::Y; Geom::Affine tf = m_tr_stack.top(); - use_fill = true; + use_fill = true; use_stroke = false; fill_transform = tf; @@ -694,43 +681,44 @@ unsigned int PrintWmf::fill( Handle gradients. Uses modified livarot as 2geom boolops is currently broken. Can handle gradients with multiple stops. - The overlap is needed to avoid antialiasing artifacts when edges are not strictly aligned on pixel boundaries. - There is an inevitable loss of accuracy saving through an WMF file because of the integer coordinate system. - Keep the overlap quite large so that loss of accuracy does not remove an overlap. + The overlap is needed to avoid antialiasing artifacts when edges are not strictly aligned on pixel + boundaries. There is an inevitable loss of accuracy saving through an WMF file because of the integer + coordinate system. Keep the overlap quite large so that loss of accuracy does not remove an overlap. */ - destroy_pen(); //this sets the NULL_PEN, otherwise gradient slices may display with boundaries, see longer explanation below + destroy_pen(); // this sets the NULL_PEN, otherwise gradient slices may display with boundaries, see longer + // explanation below Geom::Path cutter; - float rgb[3]; + float rgb[3]; U_COLORREF wc, c1, c2; - FillRule frb = SPWR_to_LVFR((SPWindRule) style->fill_rule.computed); - double doff, doff_base, doff_range; - double divisions = 128.0; - int nstops; - int istop = 1; - float opa; // opacity at stop - - SPRadialGradient *tg = (SPRadialGradient *)(gv.grad); // linear/radial are the same here + FillRule frb = SPWR_to_LVFR((SPWindRule)style->fill_rule.computed); + double doff, doff_base, doff_range; + double divisions = 128.0; + int nstops; + int istop = 1; + float opa; // opacity at stop + + SPRadialGradient *tg = (SPRadialGradient *)(gv.grad); // linear/radial are the same here nstops = tg->vector.stops.size(); tg->vector.stops[0].color.get_rgb_floatv(rgb); - opa = tg->vector.stops[0].opacity; - c1 = U_RGBA(255 * rgb[0], 255 * rgb[1], 255 * rgb[2], 255 * opa); + opa = tg->vector.stops[0].opacity; + c1 = U_RGBA(255 * rgb[0], 255 * rgb[1], 255 * rgb[2], 255 * opa); tg->vector.stops[nstops - 1].color.get_rgb_floatv(rgb); - opa = tg->vector.stops[nstops - 1].opacity; - c2 = U_RGBA(255 * rgb[0], 255 * rgb[1], 255 * rgb[2], 255 * opa); + opa = tg->vector.stops[nstops - 1].opacity; + c2 = U_RGBA(255 * rgb[0], 255 * rgb[1], 255 * rgb[2], 255 * opa); - doff = 0.0; - doff_base = 0.0; - doff_range = tg->vector.stops[1].offset; // next or last stop + doff = 0.0; + doff_base = 0.0; + doff_range = tg->vector.stops[1].offset; // next or last stop if (gv.mode == DRAW_RADIAL_GRADIENT) { - Geom::Point xv = gv.p2 - gv.p1; // X' vector - Geom::Point yv = gv.p3 - gv.p1; // Y' vector - Geom::Point xuv = Geom::unit_vector(xv); // X' unit vector + Geom::Point xv = gv.p2 - gv.p1; // X' vector + Geom::Point yv = gv.p3 - gv.p1; // Y' vector + Geom::Point xuv = Geom::unit_vector(xv); // X' unit vector double rx = hypot(xv[X], xv[Y]); double ry = hypot(yv[X], yv[Y]); - double range = fmax(rx, ry); // length along the gradient - double step = range / divisions; // adequate approximation for gradient - double overlap = step / 4.0; // overlap slices slightly + double range = fmax(rx, ry); // length along the gradient + double step = range / divisions; // adequate approximation for gradient + double overlap = step / 4.0; // overlap slices slightly double start; double stop; Geom::PathVector pathvc, pathvr; @@ -738,10 +726,11 @@ unsigned int PrintWmf::fill( /* radial gradient might stop part way through the shape, fill with outer color from there to "infinity". Do this first so that outer colored ring will overlay it. */ - pathvc = center_elliptical_hole_as_SVG_PathV(gv.p1, rx * (1.0 - overlap / range), ry * (1.0 - overlap / range), asin(xuv[Y])); - pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule) fill_oddEven, frb); + pathvc = center_elliptical_hole_as_SVG_PathV(gv.p1, rx * (1.0 - overlap / range), + ry * (1.0 - overlap / range), asin(xuv[Y])); + pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule)fill_oddEven, frb); wc = weight_opacity(c2); - (void) create_brush(style, &wc); + (void)create_brush(style, &wc); print_pathv(pathvr, fill_transform); tg->vector.stops[istop].color.get_rgb_floatv(rgb); @@ -754,20 +743,21 @@ unsigned int PrintWmf::fill( stop = range; } wc = weight_colors(c1, c2, (doff - doff_base) / (doff_range - doff_base)); - (void) create_brush(style, &wc); + (void)create_brush(style, &wc); - pathvc = center_elliptical_ring_as_SVG_PathV(gv.p1, rx * start / range, ry * start / range, rx * stop / range, ry * stop / range, asin(xuv[Y])); + pathvc = center_elliptical_ring_as_SVG_PathV(gv.p1, rx * start / range, ry * start / range, + rx * stop / range, ry * stop / range, asin(xuv[Y])); - pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule) fill_nonZero, frb); - print_pathv(pathvr, fill_transform); // show the intersection + pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule)fill_nonZero, frb); + print_pathv(pathvr, fill_transform); // show the intersection if (doff >= doff_range - doff_base) { istop++; if (istop >= nstops) { - continue; // could happen on a rounding error + continue; // could happen on a rounding error } - doff_base = doff_range; - doff_range = tg->vector.stops[istop].offset; // next or last stop + doff_base = doff_range; + doff_range = tg->vector.stops[istop].offset; // next or last stop c1 = c2; tg->vector.stops[istop].color.get_rgb_floatv(rgb); opa = tg->vector.stops[istop].opacity; @@ -775,27 +765,27 @@ unsigned int PrintWmf::fill( } } } else if (gv.mode == DRAW_LINEAR_GRADIENT) { - Geom::Point uv = Geom::unit_vector(gv.p2 - gv.p1); // unit vector - Geom::Point puv = uv.cw(); // perp. to unit vector - double range = Geom::distance(gv.p1, gv.p2); // length along the gradient - double step = range / divisions; // adequate approximation for gradient - double overlap = step / 4.0; // overlap slices slightly + Geom::Point uv = Geom::unit_vector(gv.p2 - gv.p1); // unit vector + Geom::Point puv = uv.cw(); // perp. to unit vector + double range = Geom::distance(gv.p1, gv.p2); // length along the gradient + double step = range / divisions; // adequate approximation for gradient + double overlap = step / 4.0; // overlap slices slightly double start; double stop; Geom::PathVector pathvc, pathvr; /* before lower end of gradient, overlap first slice position */ wc = weight_opacity(c1); - (void) create_brush(style, &wc); + (void)create_brush(style, &wc); pathvc = rect_cutter(gv.p1, uv * (overlap), uv * (-50000.0), puv * 50000.0); - pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule) fill_nonZero, frb); + pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule)fill_nonZero, frb); print_pathv(pathvr, fill_transform); /* after high end of gradient, overlap last slice position */ wc = weight_opacity(c2); - (void) create_brush(style, &wc); + (void)create_brush(style, &wc); pathvc = rect_cutter(gv.p2, uv * (-overlap), uv * (50000.0), puv * 50000.0); - pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule) fill_nonZero, frb); + pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule)fill_nonZero, frb); print_pathv(pathvr, fill_transform); tg->vector.stops[istop].color.get_rgb_floatv(rgb); @@ -810,17 +800,18 @@ unsigned int PrintWmf::fill( pathvc = rect_cutter(gv.p1, uv * start, uv * stop, puv * 50000.0); wc = weight_colors(c1, c2, (doff - doff_base) / (doff_range - doff_base)); - (void) create_brush(style, &wc); - Geom::PathVector pathvr = sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule) fill_nonZero, frb); - print_pathv(pathvr, fill_transform); // show the intersection + (void)create_brush(style, &wc); + Geom::PathVector pathvr = + sp_pathvector_boolop(pathvc, pathv, bool_op_inters, (FillRule)fill_nonZero, frb); + print_pathv(pathvr, fill_transform); // show the intersection if (doff >= doff_range - doff_base) { istop++; if (istop >= nstops) { - continue; // could happen on a rounding error + continue; // could happen on a rounding error } - doff_base = doff_range; - doff_range = tg->vector.stops[istop].offset; // next or last stop + doff_base = doff_range; + doff_range = tg->vector.stops[istop].offset; // next or last stop c1 = c2; tg->vector.stops[istop].color.get_rgb_floatv(rgb); opa = tg->vector.stops[istop].opacity; @@ -830,7 +821,7 @@ unsigned int PrintWmf::fill( } else { g_error("Fatal programming error in PrintWmf::fill, invalid gradient type detected"); } - use_fill = false; // gradients handled, be sure stroke does not use stroke and fill + use_fill = false; // gradients handled, be sure stroke does not use stroke and fill } else { /* Inkscape was not calling create_pen for objects with no border. @@ -840,26 +831,23 @@ unsigned int PrintWmf::fill( To avoid this force the pen to NULL_PEN if we can determine that no pen will be needed after the fill. */ if (style->stroke.noneSet || style->stroke_width.computed == 0.0) { - destroy_pen(); //this sets the NULL_PEN + destroy_pen(); // this sets the NULL_PEN } /* postpone fill in case stroke also required AND all stroke paths closed Dashes converted to line segments will "open" a closed path. */ bool all_closed = true; - for (const auto & pit : pathv) { + for (const auto &pit : pathv) { for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_open(); ++cit) { if (pit.end_default() != pit.end_closed()) { all_closed = false; } } } - if ( - (style->stroke.isNone() || style->stroke.noneSet || style->stroke_width.computed == 0.0) || - (!style->stroke_dasharray.values.empty() && FixPPTDashLine) || - !all_closed - ) { - print_pathv(pathv, fill_transform); // do any fills. side effect: clears fill_pathv + if ((style->stroke.isNone() || style->stroke.noneSet || style->stroke_width.computed == 0.0) || + (!style->stroke_dasharray.values.empty() && FixPPTDashLine) || !all_closed) { + print_pathv(pathv, fill_transform); // do any fills. side effect: clears fill_pathv use_fill = false; } } @@ -867,13 +855,10 @@ unsigned int PrintWmf::fill( return 0; } - -unsigned int PrintWmf::stroke( - Inkscape::Extension::Print * /*mod*/, - Geom::PathVector const &pathv, const Geom::Affine &/*transform*/, const SPStyle *style, - Geom::OptRect const &/*pbox*/, Geom::OptRect const &/*dbox*/, Geom::OptRect const &/*bbox*/) +unsigned int PrintWmf::stroke(Inkscape::Extension::Print * /*mod*/, Geom::PathVector const &pathv, + const Geom::Affine & /*transform*/, const SPStyle *style, Geom::OptRect const & /*pbox*/, + Geom::OptRect const & /*dbox*/, Geom::OptRect const & /*bbox*/) { - char *rec = nullptr; Geom::Affine tf = m_tr_stack.top(); @@ -884,18 +869,18 @@ unsigned int PrintWmf::stroke( return 0; } - if (!style->stroke_dasharray.values.empty() && FixPPTDashLine) { + if (!style->stroke_dasharray.values.empty() && FixPPTDashLine) { // convert the path, gets its complete length, and then make a new path with parameter length instead of t - Geom::Piecewise > tmp_pathpw; // pathv-> sbasis - Geom::Piecewise > tmp_pathpw2; // sbasis using arc length parameter - Geom::Piecewise > tmp_pathpw3; // new (discontinuous) path, composed of dots/dashes - Geom::Piecewise > first_frag; // first fragment, will be appended at end + Geom::Piecewise> tmp_pathpw; // pathv-> sbasis + Geom::Piecewise> tmp_pathpw2; // sbasis using arc length parameter + Geom::Piecewise> tmp_pathpw3; // new (discontinuous) path, composed of dots/dashes + Geom::Piecewise> first_frag; // first fragment, will be appended at end int n_dash = style->stroke_dasharray.values.size(); - int i = 0; //dash index - double tlength; // length of tmp_pathpw - double slength = 0.0; // start of gragment - double elength; // end of gragment - for (const auto & i : pathv) { + int i = 0; // dash index + double tlength; // length of tmp_pathpw + double slength = 0.0; // start of gragment + double elength; // end of gragment + for (const auto &i : pathv) { tmp_pathpw.concat(i.toPwSb()); } tlength = length(tmp_pathpw, 0.1); @@ -907,7 +892,7 @@ unsigned int PrintWmf::stroke( if (elength > tlength) { elength = tlength; } - Geom::Piecewise > fragment(portion(tmp_pathpw2, slength, elength)); + Geom::Piecewise> fragment(portion(tmp_pathpw2, slength, elength)); if (slength) { tmp_pathpw3.concat(fragment); } else { @@ -927,7 +912,7 @@ unsigned int PrintWmf::stroke( } use_stroke = false; - use_fill = false; + use_fill = false; if (usebk) { // OPAQUE was set, revert to TRANSPARENT usebk = false; @@ -940,22 +925,20 @@ unsigned int PrintWmf::stroke( return 0; } - // Draws simple_shapes, those with closed WMR_* primitives, like polygons, rectangles and ellipses. // These use whatever the current pen/brush are and need not be followed by a FILLPATH or STROKEPATH. // For other paths it sets a few flags and returns. bool PrintWmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Affine &transform) { - Geom::PathVector pv = pathv_to_linear(pathv * transform, MAXDISP); - int nodes = 0; - int moves = 0; - int lines = 0; + int nodes = 0; + int moves = 0; + int lines = 0; int curves = 0; - char *rec = nullptr; + char *rec = nullptr; - for (const auto & pit : pv) { + for (const auto &pit : pv) { moves++; nodes++; @@ -979,7 +962,7 @@ bool PrintWmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff /** For all Subpaths in the */ - for (const auto & pit : pv) { + for (const auto &pit : pv) { using Geom::X; using Geom::Y; @@ -988,8 +971,8 @@ bool PrintWmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff p0[X] = (p0[X] * PX2WORLD); p0[Y] = (p0[Y] * PX2WORLD); - int32_t const x0 = (int32_t) round(p0[X]); - int32_t const y0 = (int32_t) round(p0[Y]); + int32_t const x0 = (int32_t)round(p0[X]); + int32_t const y0 = (int32_t)round(p0[Y]); lpPoints[i].x = x0; lpPoints[i].y = y0; @@ -999,46 +982,46 @@ bool PrintWmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_open(); ++cit) { if (is_straight_curve(*cit)) { - //Geom::Point p0 = cit->initialPoint(); + // Geom::Point p0 = cit->initialPoint(); Geom::Point p1 = cit->finalPoint(); - //p0[X] = (p0[X] * PX2WORLD); + // p0[X] = (p0[X] * PX2WORLD); p1[X] = (p1[X] * PX2WORLD); - //p0[Y] = (p0[Y] * PX2WORLD); + // p0[Y] = (p0[Y] * PX2WORLD); p1[Y] = (p1[Y] * PX2WORLD); - //int32_t const x0 = (int32_t) round(p0[X]); - //int32_t const y0 = (int32_t) round(p0[Y]); - int32_t const x1 = (int32_t) round(p1[X]); - int32_t const y1 = (int32_t) round(p1[Y]); + // int32_t const x0 = (int32_t) round(p0[X]); + // int32_t const y0 = (int32_t) round(p0[Y]); + int32_t const x1 = (int32_t)round(p1[X]); + int32_t const y1 = (int32_t)round(p1[Y]); lpPoints[i].x = x1; lpPoints[i].y = y1; i = i + 1; } else if (Geom::CubicBezier const *cubic = dynamic_cast(&*cit)) { std::vector points = cubic->controlPoints(); - //Geom::Point p0 = points[0]; + // Geom::Point p0 = points[0]; Geom::Point p1 = points[1]; Geom::Point p2 = points[2]; Geom::Point p3 = points[3]; - //p0[X] = (p0[X] * PX2WORLD); + // p0[X] = (p0[X] * PX2WORLD); p1[X] = (p1[X] * PX2WORLD); p2[X] = (p2[X] * PX2WORLD); p3[X] = (p3[X] * PX2WORLD); - //p0[Y] = (p0[Y] * PX2WORLD); + // p0[Y] = (p0[Y] * PX2WORLD); p1[Y] = (p1[Y] * PX2WORLD); p2[Y] = (p2[Y] * PX2WORLD); p3[Y] = (p3[Y] * PX2WORLD); - //int32_t const x0 = (int32_t) round(p0[X]); - //int32_t const y0 = (int32_t) round(p0[Y]); - int32_t const x1 = (int32_t) round(p1[X]); - int32_t const y1 = (int32_t) round(p1[Y]); - int32_t const x2 = (int32_t) round(p2[X]); - int32_t const y2 = (int32_t) round(p2[Y]); - int32_t const x3 = (int32_t) round(p3[X]); - int32_t const y3 = (int32_t) round(p3[Y]); + // int32_t const x0 = (int32_t) round(p0[X]); + // int32_t const y0 = (int32_t) round(p0[Y]); + int32_t const x1 = (int32_t)round(p1[X]); + int32_t const y1 = (int32_t)round(p1[Y]); + int32_t const x2 = (int32_t)round(p2[X]); + int32_t const y2 = (int32_t)round(p2[Y]); + int32_t const x3 = (int32_t)round(p3[X]); + int32_t const y3 = (int32_t)round(p3[Y]); lpPoints[i].x = x1; lpPoints[i].y = y1; @@ -1069,10 +1052,10 @@ bool PrintWmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff } else if (moves == 1 && nodes == 5 && moves + curves == nodes && closed) { // if (lpPoints[0].x == lpPoints[1].x && lpPoints[1].x == lpPoints[11].x && // lpPoints[5].x == lpPoints[6].x && lpPoints[6].x == lpPoints[7].x && - // lpPoints[2].x == lpPoints[10].x && lpPoints[3].x == lpPoints[9].x && lpPoints[4].x == lpPoints[8].x && - // lpPoints[2].y == lpPoints[3].y && lpPoints[3].y == lpPoints[4].y && - // lpPoints[8].y == lpPoints[9].y && lpPoints[9].y == lpPoints[10].y && - // lpPoints[5].y == lpPoints[1].y && lpPoints[6].y == lpPoints[0].y && lpPoints[7].y == lpPoints[11].y) + // lpPoints[2].x == lpPoints[10].x && lpPoints[3].x == lpPoints[9].x && lpPoints[4].x == + // lpPoints[8].x && lpPoints[2].y == lpPoints[3].y && lpPoints[3].y == lpPoints[4].y && lpPoints[8].y + // == lpPoints[9].y && lpPoints[9].y == lpPoints[10].y && lpPoints[5].y == lpPoints[1].y && + // lpPoints[6].y == lpPoints[0].y && lpPoints[7].y == lpPoints[11].y) // { // disable due to LP Bug 407394 // ellipse = true; // } @@ -1083,21 +1066,15 @@ bool PrintWmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff if (polygon) { if (rectangle) { - U_RECT16 rcl = U_RECT16_set((U_POINT16) { - lpPoints[0].x, lpPoints[0].y - }, (U_POINT16) { - lpPoints[2].x, lpPoints[2].y - }); + U_RECT16 rcl = + U_RECT16_set((U_POINT16){lpPoints[0].x, lpPoints[0].y}, (U_POINT16){lpPoints[2].x, lpPoints[2].y}); rec = U_WMRRECTANGLE_set(rcl); } else { rec = U_WMRPOLYGON_set(nodes, lpPoints); } } else if (ellipse) { - U_RECT16 rcl = U_RECT16_set((U_POINT16) { - lpPoints[6].x, lpPoints[3].y - }, (U_POINT16) { - lpPoints[0].x, lpPoints[9].y - }); + U_RECT16 rcl = + U_RECT16_set((U_POINT16){lpPoints[6].x, lpPoints[3].y}, (U_POINT16){lpPoints[0].x, lpPoints[9].y}); rec = U_WMRELLIPSE_set(rcl); } if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { @@ -1105,7 +1082,6 @@ bool PrintWmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff } done = true; - } delete[] lpPoints; @@ -1129,14 +1105,15 @@ bool PrintWmf::print_simple_shape(Geom::PathVector const &pathv, const Geom::Aff size of two bitmaps. */ -unsigned int PrintWmf::image( - Inkscape::Extension::Print * /* module */, /** not used */ - unsigned char *rgba_px, /** array of pixel values, Gdk::Pixbuf bitmap format */ - unsigned int w, /** width of bitmap */ - unsigned int h, /** height of bitmap */ - unsigned int rs, /** row stride (normally w*4) */ - Geom::Affine const &tf_rect, /** affine transform only used for defining location and size of rect, for all other transforms, use the one from m_tr_stack */ - SPStyle const * /*style*/) /** provides indirect link to image object */ +unsigned int PrintWmf::image(Inkscape::Extension::Print * /* module */, /** not used */ + unsigned char *rgba_px, /** array of pixel values, Gdk::Pixbuf bitmap format */ + unsigned int w, /** width of bitmap */ + unsigned int h, /** height of bitmap */ + unsigned int rs, /** row stride (normally w*4) */ + Geom::Affine const &tf_rect, /** affine transform only used for defining location and size + of rect, for all other transforms, use the one from + m_tr_stack */ + SPStyle const * /*style*/) /** provides indirect link to image object */ { double x1, y1, dw, dh; char *rec = nullptr; @@ -1149,10 +1126,10 @@ unsigned int PrintWmf::image( x1 = tf_rect[4]; y1 = tf_rect[5]; - dw = ((double) w) * tf_rect[0]; - dh = ((double) h) * tf_rect[3]; + dw = ((double)w) * tf_rect[0]; + dh = ((double)h) * tf_rect[3]; Geom::Point pLL(x1, y1); - Geom::Point pLL2 = pLL * tf; //location of LL corner in Inkscape coordinates + Geom::Point pLL2 = pLL * tf; // location of LL corner in Inkscape coordinates /* adjust scale of w and h. This works properly when there is no rotation. The values are a bit strange when there is rotation, but since WMF cannot handle rotation in any case, all @@ -1161,33 +1138,32 @@ unsigned int PrintWmf::image( Geom::Point pWH(dw, dh); Geom::Point pWH2 = pWH * tf.withoutTranslation(); - char *px; - uint32_t cbPx; - uint32_t colortype; - U_RGBQUAD *ct; - int numCt; - U_BITMAPINFOHEADER Bmih; - U_BITMAPINFO *Bmi; + char *px; + uint32_t cbPx; + uint32_t colortype; + U_RGBQUAD *ct; + int numCt; + U_BITMAPINFOHEADER Bmih; + U_BITMAPINFO *Bmi; colortype = U_BCBM_COLOR32; - (void) RGBA_to_DIB(&px, &cbPx, &ct, &numCt, (char *) rgba_px, w, h, w * 4, colortype, 0, 1); + (void)RGBA_to_DIB(&px, &cbPx, &ct, &numCt, (char *)rgba_px, w, h, w * 4, colortype, 0, 1); Bmih = bitmapinfoheader_set(w, h, 1, colortype, U_BI_RGB, 0, PXPERMETER, PXPERMETER, numCt, 0); Bmi = bitmapinfo_set(Bmih, ct); - U_POINT16 Dest = point16_set(round(pLL2[Geom::X] * PX2WORLD), round(pLL2[Geom::Y] * PX2WORLD)); + U_POINT16 Dest = point16_set(round(pLL2[Geom::X] * PX2WORLD), round(pLL2[Geom::Y] * PX2WORLD)); U_POINT16 cDest = point16_set(round(pWH2[Geom::X] * PX2WORLD), round(pWH2[Geom::Y] * PX2WORLD)); - U_POINT16 Src = point16_set(0, 0); - U_POINT16 cSrc = point16_set(w, h); - rec = U_WMRSTRETCHDIB_set( - Dest, //! Destination UL corner in logical units - cDest, //! Destination W & H in logical units - Src, //! Source UL corner in logical units - cSrc, //! Source W & H in logical units - U_DIB_RGB_COLORS, //! DIBColors Enumeration - U_SRCCOPY, //! RasterOPeration Enumeration - Bmi, //! (Optional) bitmapbuffer (U_BITMAPINFO section) - h * rs, //! size in bytes of px - px //! (Optional) bitmapbuffer (U_BITMAPINFO section) - ); + U_POINT16 Src = point16_set(0, 0); + U_POINT16 cSrc = point16_set(w, h); + rec = U_WMRSTRETCHDIB_set(Dest, //! Destination UL corner in logical units + cDest, //! Destination W & H in logical units + Src, //! Source UL corner in logical units + cSrc, //! Source W & H in logical units + U_DIB_RGB_COLORS, //! DIBColors Enumeration + U_SRCCOPY, //! RasterOPeration Enumeration + Bmi, //! (Optional) bitmapbuffer (U_BITMAPINFO section) + h * rs, //! size in bytes of px + px //! (Optional) bitmapbuffer (U_BITMAPINFO section) + ); if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { g_error("Fatal programming error in PrintWmf::image at U_WMRSTRETCHDIB_set"); } @@ -1202,10 +1178,10 @@ unsigned int PrintWmf::image( // may also be called with a simple_shape or an empty path, whereupon it just returns without doing anything unsigned int PrintWmf::print_pathv(Geom::PathVector const &pathv, const Geom::Affine &transform) { - char *rec = nullptr; - U_POINT16 *pt16hold, *pt16ptr; - uint16_t *n16hold; - uint16_t *n16ptr; + char *rec = nullptr; + U_POINT16 *pt16hold, *pt16ptr; + uint16_t *n16hold; + uint16_t *n16ptr; simple_shape = print_simple_shape(pathv, transform); if (!simple_shape && !pathv.empty()) { @@ -1226,8 +1202,9 @@ unsigned int PrintWmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af a closed path as an open one. */ int nPolys = 0; int totPoints = 0; - for (const auto & pit : pv) { - totPoints += 1 + pit.size_default(); // big array, will hold all points, for all polygons. Size_default ignores first point in each path. + for (const auto &pit : pv) { + totPoints += 1 + pit.size_default(); // big array, will hold all points, for all polygons. Size_default + // ignores first point in each path. if (pit.end_default() == pit.end_closed()) { nPolys++; } else { @@ -1237,23 +1214,22 @@ unsigned int PrintWmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af } if (nPolys > 1) { // a single polypolygon, a single polygon falls through to the else - pt16hold = pt16ptr = (U_POINT16 *) malloc(totPoints * sizeof(U_POINT16)); + pt16hold = pt16ptr = (U_POINT16 *)malloc(totPoints * sizeof(U_POINT16)); if (!pt16ptr) { - return(false); + return (false); } - n16hold = n16ptr = (uint16_t *) malloc(nPolys * sizeof(uint16_t)); + n16hold = n16ptr = (uint16_t *)malloc(nPolys * sizeof(uint16_t)); if (!n16ptr) { free(pt16hold); - return(false); + return (false); } - for (const auto & pit : pv) { + for (const auto &pit : pv) { using Geom::X; using Geom::Y; - - *n16ptr++ = pit.size_default(); // points in the subpath + *n16ptr++ = pit.size_default(); // points in the subpath /** For each segment in the subpath */ @@ -1261,16 +1237,15 @@ unsigned int PrintWmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af p1[X] = (p1[X] * PX2WORLD); p1[Y] = (p1[Y] * PX2WORLD); - *pt16ptr++ = point16_set((int32_t) round(p1[X]), (int32_t) round(p1[Y])); + *pt16ptr++ = point16_set((int32_t)round(p1[X]), (int32_t)round(p1[Y])); for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_open(); ++cit) { Geom::Point p1 = cit->finalPoint(); p1[X] = (p1[X] * PX2WORLD); p1[Y] = (p1[Y] * PX2WORLD); - *pt16ptr++ = point16_set((int32_t) round(p1[X]), (int32_t) round(p1[Y])); + *pt16ptr++ = point16_set((int32_t)round(p1[X]), (int32_t)round(p1[Y])); } - } rec = U_WMRPOLYPOLYGON_set(nPolys, n16hold, pt16hold); if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { @@ -1279,7 +1254,7 @@ unsigned int PrintWmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af free(pt16hold); free(n16hold); } else { // one or more polyline or polygons (but not all polygons, that would be the preceding case) - for (const auto & pit : pv) { + for (const auto &pit : pv) { using Geom::X; using Geom::Y; @@ -1294,7 +1269,7 @@ unsigned int PrintWmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af */ int nPoints = 1 + pit.size_default(); - pt16hold = pt16ptr = (U_POINT16 *) malloc(nPoints * sizeof(U_POINT16)); + pt16hold = pt16ptr = (U_POINT16 *)malloc(nPoints * sizeof(U_POINT16)); if (!pt16ptr) { break; } @@ -1305,7 +1280,7 @@ unsigned int PrintWmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af p1[X] = (p1[X] * PX2WORLD); p1[Y] = (p1[Y] * PX2WORLD); - *pt16ptr++ = point16_set((int32_t) round(p1[X]), (int32_t) round(p1[Y])); + *pt16ptr++ = point16_set((int32_t)round(p1[X]), (int32_t)round(p1[Y])); nPoints = 1; for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_default(); ++cit, nPoints++) { @@ -1313,11 +1288,11 @@ unsigned int PrintWmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af p1[X] = (p1[X] * PX2WORLD); p1[Y] = (p1[Y] * PX2WORLD); - *pt16ptr++ = point16_set((int32_t) round(p1[X]), (int32_t) round(p1[Y])); + *pt16ptr++ = point16_set((int32_t)round(p1[X]), (int32_t)round(p1[Y])); } if (pit.end_default() == pit.end_closed()) { - rec = U_WMRPOLYGON_set(nPoints, pt16hold); + rec = U_WMRPOLYGON_set(nPoints, pt16hold); if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { g_error("Fatal programming error in PrintWmf::print_pathv at U_WMRPOLYGON_set"); } @@ -1354,7 +1329,6 @@ unsigned int PrintWmf::print_pathv(Geom::PathVector const &pathv, const Geom::Af return TRUE; } - unsigned int PrintWmf::text(Inkscape::Extension::Print * /*mod*/, char const *text, Geom::Point const &p, SPStyle const *const style) { @@ -1368,15 +1342,17 @@ unsigned int PrintWmf::text(Inkscape::Extension::Print * /*mod*/, char const *te uint32_t hfont = 0; Geom::Affine tf = m_tr_stack.top(); double rot = -1800.0 * std::atan2(tf[1], tf[0]) / M_PI; // 0.1 degree rotation, - sign for MM_TEXT - double rotb = -std::atan2(tf[1], tf[0]); // rotation for baseline offset for superscript/subscript, used below + double rotb = -std::atan2(tf[1], tf[0]); // rotation for baseline offset for superscript/subscript, used below double dx, dy; double ky; - // the dx array is smuggled in like: textw1 w2 w3 ...wn, where the widths are floats 7 characters wide, including the space + // the dx array is smuggled in like: textw1 w2 w3 ...wn, where the widths are floats 7 characters + // wide, including the space int ndx = 0; int rtl = 0; int16_t *adx; - smuggle_adxky_out(text, &adx, &ky, &rtl, &ndx, PX2WORLD * std::min(tf.expansionX(), tf.expansionY())); // side effect: free() adx + smuggle_adxky_out(text, &adx, &ky, &rtl, &ndx, + PX2WORLD * std::min(tf.expansionX(), tf.expansionY())); // side effect: free() adx uint32_t textalignment; if (rtl > 0) { @@ -1392,11 +1368,11 @@ unsigned int PrintWmf::text(Inkscape::Extension::Print * /*mod*/, char const *te } } - char *text2 = strdup(text); // because U_Utf8ToUtf16le calls iconv which does not like a const char * + char *text2 = strdup(text); // because U_Utf8ToUtf16le calls iconv which does not like a const char * uint16_t *unicode_text = U_Utf8ToUtf16le(text2, 0, nullptr); free(text2); - //translates Unicode as Utf16le to NonUnicode, if possible. If any translate, all will, and all to - //the same font, because of code in Layout::print + // translates Unicode as Utf16le to NonUnicode, if possible. If any translate, all will, and all to + // the same font, because of code in Layout::print UnicodeToNon(unicode_text, &ccount, &newfont); // The preceding hopefully handled conversions to symbol, wingdings or zapf dingbats. Now slam everything // else down into latin1, which is all WMF can handle. If the language isn't English expect terrible results. @@ -1404,35 +1380,37 @@ unsigned int PrintWmf::text(Inkscape::Extension::Print * /*mod*/, char const *te free(unicode_text); // in some cases a UTF string may reduce to NO latin1 characters, which returns NULL - if(!latin1_text){free(adx); return 0; } + if (!latin1_text) { + free(adx); + return 0; + } - //PPT gets funky with text within +-1 degree of a multiple of 90, but only for SOME fonts.Snap those to the central value - //Some funky ones: Arial, Times New Roman - //Some not funky ones: Symbol and Verdana. - //Without a huge table we cannot catch them all, so just the most common problem ones. + // PPT gets funky with text within +-1 degree of a multiple of 90, but only for SOME fonts.Snap those to the central + // value Some funky ones: Arial, Times New Roman Some not funky ones: Symbol and Verdana. Without a huge table we + // cannot catch them all, so just the most common problem ones. FontfixParams params; if (FixPPTCharPos) { switch (newfont) { - case CVTSYM: - _lookup_ppt_fontfix("Convert To Symbol", params); - break; - case CVTZDG: - _lookup_ppt_fontfix("Convert To Zapf Dingbats", params); - break; - case CVTWDG: - _lookup_ppt_fontfix("Convert To Wingdings", params); - break; - default: //also CVTNON - _lookup_ppt_fontfix(style->font_family.value(), params); - break; + case CVTSYM: + _lookup_ppt_fontfix("Convert To Symbol", params); + break; + case CVTZDG: + _lookup_ppt_fontfix("Convert To Zapf Dingbats", params); + break; + case CVTWDG: + _lookup_ppt_fontfix("Convert To Wingdings", params); + break; + default: // also CVTNON + _lookup_ppt_fontfix(style->font_family.value(), params); + break; } if (params.f2 != 0 || params.f3 != 0) { - int irem = ((int) round(rot)) % 900 ; + int irem = ((int)round(rot)) % 900; if (irem <= 9 && irem >= -9) { - fix90n = 1; //assume vertical - rot = (double)(((int) round(rot)) - irem); - rotb = rot * M_PI / 1800.0; + fix90n = 1; // assume vertical + rot = (double)(((int)round(rot)) - irem); + rotb = rot * M_PI / 1800.0; if (std::abs(rot) == 900.0) { fix90n = 2; } @@ -1448,7 +1426,6 @@ unsigned int PrintWmf::text(Inkscape::Extension::Print * /*mod*/, char const *te */ int textheight = round(-style->font_size.computed * PX2WORLD * std::min(tf.expansionX(), tf.expansionY())); if (!hfont) { - // Get font face name. Use changed font name if unicode mapped to one // of the special fonts. char *facename; @@ -1462,24 +1439,14 @@ unsigned int PrintWmf::text(Inkscape::Extension::Print * /*mod*/, char const *te // it was streteched asymmetrically.) Few applications support text from WMF which is scaled // differently by height/width, so leave lfWidth alone. - U_FONT *puf = U_FONT_set( - textheight, - 0, - round(rot), - round(rot), - _translate_weight(style->font_weight.computed), - (style->font_style.computed == SP_CSS_FONT_STYLE_ITALIC), - style->text_decoration_line.underline, - style->text_decoration_line.line_through, - U_DEFAULT_CHARSET, - U_OUT_DEFAULT_PRECIS, - U_CLIP_DEFAULT_PRECIS, - U_DEFAULT_QUALITY, - U_DEFAULT_PITCH | U_FF_DONTCARE, - facename); + U_FONT *puf = + U_FONT_set(textheight, 0, round(rot), round(rot), _translate_weight(style->font_weight.computed), + (style->font_style.computed == SP_CSS_FONT_STYLE_ITALIC), style->text_decoration_line.underline, + style->text_decoration_line.line_through, U_DEFAULT_CHARSET, U_OUT_DEFAULT_PRECIS, + U_CLIP_DEFAULT_PRECIS, U_DEFAULT_QUALITY, U_DEFAULT_PITCH | U_FF_DONTCARE, facename); free(facename); - rec = wcreatefontindirect_set(&hfont, wht, puf); + rec = wcreatefontindirect_set(&hfont, wht, puf); if (!rec || wmf_append((U_METARECORD *)rec, wt, U_REC_FREE)) { g_error("Fatal programming error in PrintWmf::text at wcreatefontindirect_set"); } @@ -1502,7 +1469,6 @@ unsigned int PrintWmf::text(Inkscape::Extension::Print * /*mod*/, char const *te } } - // Text alignment: // - (x,y) coordinates received by this filter are those of the point where the text // actually starts, and already takes into account the text object's alignment; @@ -1513,7 +1479,7 @@ unsigned int PrintWmf::text(Inkscape::Extension::Print * /*mod*/, char const *te Geom::Point p2 = p * tf; - //Handle super/subscripts and vertical kerning + // Handle super/subscripts and vertical kerning /* Previously used this, but vertical kerning was not supported p2[Geom::X] -= style->baseline_shift.computed * std::sin( rotb ); p2[Geom::Y] -= style->baseline_shift.computed * std::cos( rotb ); @@ -1521,12 +1487,12 @@ unsigned int PrintWmf::text(Inkscape::Extension::Print * /*mod*/, char const *te p2[Geom::X] += ky * std::sin(rotb); p2[Geom::Y] += ky * std::cos(rotb); - //Conditionally handle compensation for PPT WMF import bug (affects PPT 2003-2010, at least) + // Conditionally handle compensation for PPT WMF import bug (affects PPT 2003-2010, at least) if (FixPPTCharPos) { - if (fix90n == 1) { //vertical + if (fix90n == 1) { // vertical dx = 0.0; dy = params.f3 * style->font_size.computed * std::cos(rotb); - } else if (fix90n == 2) { //horizontal + } else if (fix90n == 2) { // horizontal dx = params.f2 * style->font_size.computed * std::sin(rotb); dy = 0.0; } else { @@ -1540,8 +1506,8 @@ unsigned int PrintWmf::text(Inkscape::Extension::Print * /*mod*/, char const *te p2[Geom::X] = (p2[Geom::X] * PX2WORLD); p2[Geom::Y] = (p2[Geom::Y] * PX2WORLD); - int32_t const xpos = (int32_t) round(p2[Geom::X]); - int32_t const ypos = (int32_t) round(p2[Geom::Y]); + int32_t const xpos = (int32_t)round(p2[Geom::X]); + int32_t const ypos = (int32_t)round(p2[Geom::Y]); // The number of characters in the string is a bit fuzzy. ndx, the number of entries in adx is // the number of VISIBLE characters, since some may combine from the UTF (8 originally, @@ -1552,15 +1518,11 @@ unsigned int PrintWmf::text(Inkscape::Extension::Print * /*mod*/, char const *te // MUCH better than the fallback hack below // uint32_t *adx = dx_set(textheight, U_FW_NORMAL, slen); // dx is needed, this makes one up if (rtl > 0) { - rec = U_WMREXTTEXTOUT_set((U_POINT16) { - (int16_t) xpos, (int16_t) ypos - }, - ndx, U_ETO_NONE, latin1_text, adx, U_RCL16_DEF); + rec = U_WMREXTTEXTOUT_set((U_POINT16){(int16_t)xpos, (int16_t)ypos}, ndx, U_ETO_NONE, latin1_text, adx, + U_RCL16_DEF); } else { // RTL text, U_TA_RTLREADING should be enough, but set this one too just in case - rec = U_WMREXTTEXTOUT_set((U_POINT16) { - (int16_t) xpos, (int16_t) ypos - }, - ndx, U_ETO_RTLREADING, latin1_text, adx, U_RCL16_DEF); + rec = U_WMREXTTEXTOUT_set((U_POINT16){(int16_t)xpos, (int16_t)ypos}, ndx, U_ETO_RTLREADING, latin1_text, adx, + U_RCL16_DEF); } free(latin1_text); free(adx); @@ -1598,10 +1560,9 @@ void PrintWmf::init() return; } -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ - +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ /* Local Variables: diff --git a/src/extension/internal/wmf-print.h b/src/extension/internal/wmf-print.h index e4aaba55000ddaadadd8fdcdb636fb641a8280a8..794f1a86f1b2b3068cc61443176f05066329a864 100644 --- a/src/extension/internal/wmf-print.h +++ b/src/extension/internal/wmf-print.h @@ -13,6 +13,7 @@ #define SEEN_INKSCAPE_EXTENSION_INTERNAL_WMF_PRINT_H #include <3rdparty/libuemf/uwmf.h> + #include "extension/internal/metafile-print.h" namespace Inkscape { @@ -22,45 +23,37 @@ namespace Internal { class PrintWmf : public PrintMetafile { uint32_t hbrush, hpen, hbrush_null, hpen_null; - uint32_t hmiterlimit; // used to minimize redundant records that set this + uint32_t hmiterlimit; // used to minimize redundant records that set this - unsigned int print_pathv (Geom::PathVector const &pathv, const Geom::Affine &transform); - bool print_simple_shape (Geom::PathVector const &pathv, const Geom::Affine &transform); + unsigned int print_pathv(Geom::PathVector const &pathv, const Geom::Affine &transform); + bool print_simple_shape(Geom::PathVector const &pathv, const Geom::Affine &transform); public: PrintWmf(); /* Print functions */ - unsigned int setup (Inkscape::Extension::Print * module) override; + unsigned int setup(Inkscape::Extension::Print *module) override; - unsigned int begin (Inkscape::Extension::Print * module, SPDocument *doc) override; - unsigned int finish (Inkscape::Extension::Print * module) override; + unsigned int begin(Inkscape::Extension::Print *module, SPDocument *doc) override; + unsigned int finish(Inkscape::Extension::Print *module) override; /* Rendering methods */ - unsigned int fill (Inkscape::Extension::Print *module, - Geom::PathVector const &pathv, - Geom::Affine const &ctm, SPStyle const *style, - Geom::OptRect const &pbox, Geom::OptRect const &dbox, - Geom::OptRect const &bbox) override; - unsigned int stroke (Inkscape::Extension::Print * module, - Geom::PathVector const &pathv, - Geom::Affine const &ctm, SPStyle const *style, - Geom::OptRect const &pbox, Geom::OptRect const &dbox, - Geom::OptRect const &bbox) override; - unsigned int image(Inkscape::Extension::Print *module, - unsigned char *px, - unsigned int w, - unsigned int h, - unsigned int rs, - Geom::Affine const &transform, - SPStyle const *style) override; - unsigned int comment(Inkscape::Extension::Print *module, const char * comment) override; - unsigned int text(Inkscape::Extension::Print *module, char const *text, - Geom::Point const &p, SPStyle const *style) override; + unsigned int fill(Inkscape::Extension::Print *module, Geom::PathVector const &pathv, Geom::Affine const &ctm, + SPStyle const *style, Geom::OptRect const &pbox, Geom::OptRect const &dbox, + Geom::OptRect const &bbox) override; + unsigned int stroke(Inkscape::Extension::Print *module, Geom::PathVector const &pathv, Geom::Affine const &ctm, + SPStyle const *style, Geom::OptRect const &pbox, Geom::OptRect const &dbox, + Geom::OptRect const &bbox) override; + unsigned int image(Inkscape::Extension::Print *module, unsigned char *px, unsigned int w, unsigned int h, + unsigned int rs, Geom::Affine const &transform, SPStyle const *style) override; + unsigned int comment(Inkscape::Extension::Print *module, const char *comment) override; + unsigned int text(Inkscape::Extension::Print *module, char const *text, Geom::Point const &p, + SPStyle const *style) override; + + static void init(); - static void init (); protected: - static void smuggle_adxky_out(const char *string, int16_t **adx, double *ky, int *rtl, int *ndx, float scale); + static void smuggle_adxky_out(const char *string, int16_t **adx, double *ky, int *rtl, int *ndx, float scale); int create_brush(SPStyle const *style, PU_COLORREF fcolor) override; void destroy_brush() override; @@ -68,10 +61,9 @@ protected: void destroy_pen() override; }; -} /* namespace Internal */ -} /* namespace Extension */ -} /* namespace Inkscape */ - +} /* namespace Internal */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* __INKSCAPE_EXTENSION_INTERNAL_PRINT_WMF_H__ */ diff --git a/src/extension/internal/wpg-input.cpp b/src/extension/internal/wpg-input.cpp index 7145eefb98d2ecd048d54951a34882a7960b98ed..6449b8de254554be7f98168505e70eb010b6fbf7 100644 --- a/src/extension/internal/wpg-input.cpp +++ b/src/extension/internal/wpg-input.cpp @@ -41,20 +41,21 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include #ifdef WITH_LIBWPG -#include "wpg-input.h" -#include "extension/system.h" -#include "extension/input.h" +#include + #include "document.h" +#include "extension/input.h" +#include "extension/system.h" #include "object/sp-root.h" #include "util/units.h" -#include +#include "wpg-input.h" // Take a guess and fallback to 0.2.x if no configure has run #if !defined(WITH_LIBWPG03) && !defined(WITH_LIBWPG02) @@ -63,17 +64,17 @@ #include "libwpg/libwpg.h" #if WITH_LIBWPG03 - #include +#include - using librevenge::RVNGString; - using librevenge::RVNGFileStream; - using librevenge::RVNGInputStream; +using librevenge::RVNGFileStream; +using librevenge::RVNGInputStream; +using librevenge::RVNGString; #else - #include "libwpd-stream/libwpd-stream.h" +#include "libwpd-stream/libwpd-stream.h" - typedef WPXString RVNGString; - typedef WPXFileStream RVNGFileStream; - typedef WPXInputStream RVNGInputStream; +typedef WPXString RVNGString; +typedef WPXFileStream RVNGFileStream; +typedef WPXInputStream RVNGInputStream; #endif using namespace libwpg; @@ -82,26 +83,25 @@ namespace Inkscape { namespace Extension { namespace Internal { - -SPDocument *WpgInput::open(Inkscape::Extension::Input * /*mod*/, const gchar * uri) +SPDocument *WpgInput::open(Inkscape::Extension::Input * /*mod*/, const gchar *uri) { - #ifdef _WIN32 - // RVNGFileStream uses fopen() internally which unfortunately only uses ANSI encoding on Windows - // therefore attempt to convert uri to the system codepage - // even if this is not possible the alternate short (8.3) file name will be used if available - gchar * converted_uri = g_win32_locale_filename_from_utf8(uri); - RVNGInputStream* input = new RVNGFileStream(converted_uri); - g_free(converted_uri); - #else - RVNGInputStream* input = new RVNGFileStream(uri); - #endif +#ifdef _WIN32 + // RVNGFileStream uses fopen() internally which unfortunately only uses ANSI encoding on Windows + // therefore attempt to convert uri to the system codepage + // even if this is not possible the alternate short (8.3) file name will be used if available + gchar *converted_uri = g_win32_locale_filename_from_utf8(uri); + RVNGInputStream *input = new RVNGFileStream(converted_uri); + g_free(converted_uri); +#else + RVNGInputStream *input = new RVNGFileStream(uri); +#endif #if WITH_LIBWPG03 if (input->isStructured()) { - RVNGInputStream* olestream = input->getSubStreamByName("PerfectOffice_MAIN"); + RVNGInputStream *olestream = input->getSubStreamByName("PerfectOffice_MAIN"); #else if (input->isOLEStream()) { - RVNGInputStream* olestream = input->getDocumentOLEStream("PerfectOffice_MAIN"); + RVNGInputStream *olestream = input->getDocumentOLEStream("PerfectOffice_MAIN"); #endif if (olestream) { @@ -127,7 +127,8 @@ SPDocument *WpgInput::open(Inkscape::Extension::Input * /*mod*/, const gchar * u return nullptr; } - RVNGString output("\n\n"); + RVNGString output("\n\n"); output.append(vec[0]); #else RVNGString output; @@ -137,22 +138,24 @@ SPDocument *WpgInput::open(Inkscape::Extension::Input * /*mod*/, const gchar * u } #endif - //printf("I've got a doc: \n%s", painter.document.c_str()); + // printf("I've got a doc: \n%s", painter.document.c_str()); + + SPDocument *doc = SPDocument::createNewDocFromMem(output.cstr(), strlen(output.cstr()), TRUE); - SPDocument * doc = SPDocument::createNewDocFromMem(output.cstr(), strlen(output.cstr()), TRUE); - // Set viewBox if it doesn't exist if (doc && !doc->getRoot()->viewBox_set) { - doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), doc->getHeight().value(doc->getDisplayUnit()))); + doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), + doc->getHeight().value(doc->getDisplayUnit()))); } - + delete input; return doc; } #include "clear-n_.h" -void WpgInput::init() { +void WpgInput::init() +{ // clang-format off Inkscape::Extension::build_from_mem( "\n" @@ -168,7 +171,9 @@ void WpgInput::init() { // clang-format on } // init -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* WITH_LIBWPG */ /* diff --git a/src/extension/internal/wpg-input.h b/src/extension/internal/wpg-input.h index 67e4d9185ee093c397ec4f050be034b3f6a82332..a1a0e7f7970f4a5bc0ca9233cf6b3d382f7f114a 100644 --- a/src/extension/internal/wpg-input.h +++ b/src/extension/internal/wpg-input.h @@ -15,7 +15,7 @@ #define __EXTENSION_INTERNAL_WPGOUTPUT_H__ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef WITH_LIBWPG @@ -26,21 +26,23 @@ namespace Inkscape { namespace Extension { namespace Internal { -class WpgInput : public Inkscape::Extension::Implementation::Implementation { - WpgInput () = default;; -public: - SPDocument *open( Inkscape::Extension::Input *mod, - const gchar *uri ) override; - static void init( ); +class WpgInput : public Inkscape::Extension::Implementation::Implementation +{ + WpgInput() = default; + ; +public: + SPDocument *open(Inkscape::Extension::Input *mod, const gchar *uri) override; + static void init(); }; -} } } /* namespace Inkscape, Extension, Implementation */ +} // namespace Internal +} // namespace Extension +} // namespace Inkscape #endif /* WITH_LIBWPG */ #endif /* __EXTENSION_INTERNAL_WPGOUTPUT_H__ */ - /* Local Variables: mode:c++ diff --git a/src/extension/loader.cpp b/src/extension/loader.cpp index d409d09baf0572273ad29b2296fb510d992341d6..bf75878fab6420b3b886887df9e2377b38eb8438 100644 --- a/src/extension/loader.cpp +++ b/src/extension/loader.cpp @@ -12,12 +12,12 @@ #include "loader.h" +#include #include -#include "system.h" -#include #include "dependency.h" #include "inkscape-version.h" +#include "system.h" namespace Inkscape { namespace Extension { @@ -43,44 +43,43 @@ bool Loader::load_dependency(Dependency *dep) Implementation::Implementation *Loader::load_implementation(Inkscape::XML::Document *doc) { try { - Inkscape::XML::Node *repr = doc->root(); Inkscape::XML::Node *child_repr = repr->firstChild(); - + // Iterate over the xml content while (child_repr != nullptr) { char const *chname = child_repr->name(); if (!strncmp(chname, INKSCAPE_EXTENSION_NS_NC, strlen(INKSCAPE_EXTENSION_NS_NC))) { chname += strlen(INKSCAPE_EXTENSION_NS); } - + // Deal with dependencies if we have them if (!strcmp(chname, "dependency")) { Dependency dep = Dependency(child_repr, nullptr); // TODO: Why is "this" not an extension? // try to load it bool success = load_dependency(&dep); - if( !success ){ + if (!success) { // Could not load dependency, we abort const char *res = g_module_error(); - g_warning("Unable to load dependency %s of plugin %s.\nDetails: %s\n", dep.get_name(), "", res); + g_warning("Unable to load dependency %s of plugin %s.\nDetails: %s\n", dep.get_name(), "", + res); return nullptr; } - } + } // Found a plugin to load if (!strcmp(chname, "plugin")) { - // The name of the plugin is actually the library file we want to load if (const gchar *name = child_repr->attribute("name")) { GModule *module = nullptr; _getImplementation GetImplementation = nullptr; _getInkscapeVersion GetInkscapeVersion = nullptr; - + // build the path where to look for the plugin - gchar *path = g_build_filename(_baseDirectory.c_str(), name, (char *) nullptr); + gchar *path = g_build_filename(_baseDirectory.c_str(), name, (char *)nullptr); module = g_module_open(path, G_MODULE_BIND_LOCAL); g_free(path); - + if (module == nullptr) { // we were not able to load the plugin, write warning and abort const char *res = g_module_error(); @@ -89,33 +88,34 @@ Implementation::Implementation *Loader::load_implementation(Inkscape::XML::Docum } // Get a handle to the version function of the module - if (g_module_symbol(module, "GetInkscapeVersion", (gpointer *) &GetInkscapeVersion) == FALSE) { + if (g_module_symbol(module, "GetInkscapeVersion", (gpointer *)&GetInkscapeVersion) == FALSE) { // This didn't work, write warning and abort const char *res = g_module_error(); g_warning("Unable to load extension %s.\nDetails: %s\n", name, res); return nullptr; } - + // Get a handle to the function that delivers the implementation - if (g_module_symbol(module, "GetImplementation", (gpointer *) &GetImplementation) == FALSE) { + if (g_module_symbol(module, "GetImplementation", (gpointer *)&GetImplementation) == FALSE) { // This didn't work, write warning and abort const char *res = g_module_error(); g_warning("Unable to load extension %s.\nDetails: %s\n", name, res); return nullptr; } - + // Get version and test against this version - const gchar* version = GetInkscapeVersion(); - if( strcmp(version, version_string) != 0) { + const gchar *version = GetInkscapeVersion(); + if (strcmp(version, version_string) != 0) { // The versions are different, display warning. - g_warning("Plugin was built against Inkscape version %s, this is %s. The plugin might not be compatible.", version, version_string); + g_warning("Plugin was built against Inkscape version %s, this is %s. The plugin might not be " + "compatible.", + version, version_string); } - - + Implementation::Implementation *i = GetImplementation(); return i; } - } + } child_repr = child_repr->next(); } diff --git a/src/extension/loader.h b/src/extension/loader.h index c6adbe2ec41e1ced6d565a3694bcb0f4f5f104b5..04e79bf1ed7934f4290118f6c31da43dae0fb9c8 100644 --- a/src/extension/loader.h +++ b/src/extension/loader.h @@ -16,7 +16,6 @@ #include "extension.h" - namespace Inkscape { namespace XML { @@ -26,18 +25,16 @@ class Document; namespace Extension { /** This class contains the mechanism to load c++ plugins dynamically. -*/ -class Loader { - + */ +class Loader +{ public: /** * Sets a base directory where to look for the actual plugin to load. * * @param dir is the path where the plugin should be loaded from. */ - void set_base_directory(std::string dir) { - _baseDirectory = dir; - } + void set_base_directory(std::string dir) { _baseDirectory = dir; } /** * Loads plugin dependencies which are needed for the plugin to load. @@ -56,8 +53,6 @@ public: private: std::string _baseDirectory; /**< The base directory to load a plugin from */ - - }; } // namespace Extension diff --git a/src/extension/output.cpp b/src/extension/output.cpp index 07c1120e75ce9efbf4b0b8181c1748f764565c05..8342ee950d9b6d7ba888fc8202dc8c19cef76d6a 100644 --- a/src/extension/output.cpp +++ b/src/extension/output.cpp @@ -12,14 +12,10 @@ #include "output.h" #include "document.h" - #include "implementation/implementation.h" - #include "prefdialog/prefdialog.h" - #include "xml/repr.h" - /* Inkscape::Extension::Output */ namespace Inkscape { @@ -41,17 +37,17 @@ namespace Extension { Overall, there are many levels of indentation, just to handle the levels of indentation in the XML file. */ -Output::Output (Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory) +Output::Output(Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory) : Extension(in_repr, in_imp, base_directory) { mimetype = nullptr; extension = nullptr; filetypename = nullptr; filetypetooltip = nullptr; - dataloss = TRUE; + dataloss = TRUE; if (repr != nullptr) { - Inkscape::XML::Node * child_repr; + Inkscape::XML::Node *child_repr; child_repr = repr->firstChild(); @@ -59,33 +55,33 @@ Output::Output (Inkscape::XML::Node *in_repr, Implementation::Implementation *in if (!strcmp(child_repr->name(), INKSCAPE_EXTENSION_NS "output")) { child_repr = child_repr->firstChild(); while (child_repr != nullptr) { - char const * chname = child_repr->name(); - if (!strncmp(chname, INKSCAPE_EXTENSION_NS_NC, strlen(INKSCAPE_EXTENSION_NS_NC))) { - chname += strlen(INKSCAPE_EXTENSION_NS); - } + char const *chname = child_repr->name(); + if (!strncmp(chname, INKSCAPE_EXTENSION_NS_NC, strlen(INKSCAPE_EXTENSION_NS_NC))) { + chname += strlen(INKSCAPE_EXTENSION_NS); + } if (chname[0] == '_') /* Allow _ for translation of tags */ chname++; if (!strcmp(chname, "extension")) { - g_free (extension); + g_free(extension); extension = g_strdup(child_repr->firstChild()->content()); } if (!strcmp(chname, "mimetype")) { - g_free (mimetype); + g_free(mimetype); mimetype = g_strdup(child_repr->firstChild()->content()); } if (!strcmp(chname, "filetypename")) { - g_free (filetypename); + g_free(filetypename); filetypename = g_strdup(child_repr->firstChild()->content()); } if (!strcmp(chname, "filetypetooltip")) { - g_free (filetypetooltip); + g_free(filetypetooltip); filetypetooltip = g_strdup(child_repr->firstChild()->content()); } if (!strcmp(chname, "dataloss")) { if (!strcmp(child_repr->firstChild()->content(), "false")) { - dataloss = FALSE; - } - } + dataloss = FALSE; + } + } child_repr = child_repr->next(); } @@ -95,14 +91,13 @@ Output::Output (Inkscape::XML::Node *in_repr, Implementation::Implementation *in child_repr = child_repr->next(); } - } } /** \brief Destroy an output extension */ -Output::~Output () +Output::~Output() { g_free(mimetype); g_free(extension); @@ -113,49 +108,45 @@ Output::~Output () /** \return Whether this extension checks out - \brief Validate this extension + \brief Validate this extension - This function checks to make sure that the output extension has - a filename extension and a MIME type. Then it calls the parent - class' check function which also checks out the implementation. + This function checks to make sure that the output extension has + a filename extension and a MIME type. Then it calls the parent + class' check function which also checks out the implementation. */ -bool -Output::check () +bool Output::check() { - if (extension == nullptr) - return FALSE; - if (mimetype == nullptr) - return FALSE; + if (extension == nullptr) + return FALSE; + if (mimetype == nullptr) + return FALSE; - return Extension::check(); + return Extension::check(); } /** \return IETF mime-type for the extension - \brief Get the mime-type that describes this extension + \brief Get the mime-type that describes this extension */ -gchar * -Output::get_mimetype() +gchar *Output::get_mimetype() { return mimetype; } /** \return Filename extension for the extension - \brief Get the filename extension for this extension + \brief Get the filename extension for this extension */ -gchar * -Output::get_extension() +gchar *Output::get_extension() { return extension; } /** \return The name of the filetype supported - \brief Get the name of the filetype supported + \brief Get the name of the filetype supported */ -const char * -Output::get_filetypename(bool translated) +const char *Output::get_filetypename(bool translated) { const char *name; @@ -173,10 +164,9 @@ Output::get_filetypename(bool translated) /** \return Tooltip giving more information on the filetype - \brief Get the tooltip for more information on the filetype + \brief Get the tooltip for more information on the filetype */ -const char * -Output::get_filetypetooltip(bool translated) +const char *Output::get_filetypetooltip(bool translated) { if (filetypetooltip && translated) { return get_translation(filetypetooltip); @@ -187,18 +177,18 @@ Output::get_filetypetooltip(bool translated) /** \return A dialog to get settings for this extension - \brief Create a dialog for preference for this extension + \brief Create a dialog for preference for this extension - Calls the implementation to get the preferences. + Calls the implementation to get the preferences. */ -bool -Output::prefs () +bool Output::prefs() { if (!loaded()) set_state(Extension::STATE_LOADED); - if (!loaded()) return false; + if (!loaded()) + return false; - Gtk::Widget * controls; + Gtk::Widget *controls; controls = imp->prefs_output(this); if (controls == nullptr) { // std::cout << "No preferences for Output" << std::endl; @@ -217,29 +207,29 @@ Output::prefs () /** \return None - \brief Save a document as a file - \param doc Document to save - \param filename File to save the document as - - This function does a little of the dirty work involved in saving - a document so that the implementation only has to worry about getting - bits on the disk. - - The big thing that it does is remove and read the fields that are - only used at runtime and shouldn't be saved. One that may surprise - people is the output extension. This is not saved so that the IDs - could be changed, and old files will still work properly. + \brief Save a document as a file + \param doc Document to save + \param filename File to save the document as + + This function does a little of the dirty work involved in saving + a document so that the implementation only has to worry about getting + bits on the disk. + + The big thing that it does is remove and read the fields that are + only used at runtime and shouldn't be saved. One that may surprise + people is the output extension. This is not saved so that the IDs + could be changed, and old files will still work properly. */ -void -Output::save(SPDocument *doc, gchar const *filename, bool detachbase) +void Output::save(SPDocument *doc, gchar const *filename, bool detachbase) { imp->setDetachBase(detachbase); imp->save(this, doc, filename); - return; + return; } -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/output.h b/src/extension/output.h index 8210858ea69c1121df7dd7bb107029a69b5242e7..9c15c1be86d7b2169435fadfc0c9761ae1369c6d 100644 --- a/src/extension/output.h +++ b/src/extension/output.h @@ -9,8 +9,6 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - - #ifndef INKSCAPE_EXTENSION_OUTPUT_H__ #define INKSCAPE_EXTENSION_OUTPUT_H__ @@ -20,41 +18,51 @@ class SPDocument; namespace Inkscape { namespace Extension { -class Output : public Extension { - gchar *mimetype; /**< What is the mime type this inputs? */ - gchar *extension; /**< The extension of the input files */ - gchar *filetypename; /**< A userfriendly name for the file type */ - gchar *filetypetooltip; /**< A more detailed description of the filetype */ - bool dataloss; /**< The extension causes data loss on save */ +class Output : public Extension +{ + gchar *mimetype; /**< What is the mime type this inputs? */ + gchar *extension; /**< The extension of the input files */ + gchar *filetypename; /**< A userfriendly name for the file type */ + gchar *filetypetooltip; /**< A more detailed description of the filetype */ + bool dataloss; /**< The extension causes data loss on save */ public: - class save_failed {}; /**< Generic failure for an undescribed reason */ - class save_cancelled {}; /**< Saving was cancelled */ - class no_extension_found {}; /**< Failed because we couldn't find an extension to match the filename */ - class file_read_only {}; /**< The existing file can not be opened for writing */ - class export_id_not_found { /**< The object ID requested for export could not be found in the document */ - public: - const gchar * const id; - export_id_not_found(const gchar * const id = nullptr) : id{id} {}; + class save_failed + { + }; /**< Generic failure for an undescribed reason */ + class save_cancelled + { + }; /**< Saving was cancelled */ + class no_extension_found + { + }; /**< Failed because we couldn't find an extension to match the filename */ + class file_read_only + { + }; /**< The existing file can not be opened for writing */ + class export_id_not_found + { /**< The object ID requested for export could not be found in the document */ + public: + const gchar *const id; + export_id_not_found(const gchar *const id = nullptr) + : id{id} {}; }; Output(Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory); - ~Output () override; + ~Output() override; bool check() override; - void save (SPDocument *doc, - gchar const *filename, - bool detachbase = false); - bool prefs (); - gchar * get_mimetype(); - gchar * get_extension(); - const char * get_filetypename(bool translated=false); - const char * get_filetypetooltip(bool translated=false); - bool causes_dataloss() { return dataloss; }; + void save(SPDocument *doc, gchar const *filename, bool detachbase = false); + bool prefs(); + gchar *get_mimetype(); + gchar *get_extension(); + const char *get_filetypename(bool translated = false); + const char *get_filetypetooltip(bool translated = false); + bool causes_dataloss() { return dataloss; }; }; -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape #endif /* INKSCAPE_EXTENSION_OUTPUT_H__ */ /* diff --git a/src/extension/patheffect.cpp b/src/extension/patheffect.cpp index 3ed53e74e0997e6eb63d3fba896374865a124436..649acd41a9fea30e0564a068c95e01a3fe5658e3 100644 --- a/src/extension/patheffect.cpp +++ b/src/extension/patheffect.cpp @@ -8,64 +8,51 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "patheffect.h" #include "db.h" - #include "object/sp-defs.h" - #include "xml/repr.h" - namespace Inkscape { namespace Extension { -PathEffect::PathEffect (Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory) +PathEffect::PathEffect(Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, + std::string *base_directory) : Extension(in_repr, in_imp, base_directory) -{ +{} -} +PathEffect::~PathEffect(void) = default; -PathEffect::~PathEffect (void) -= default; +void PathEffect::processPath(SPDocument * /*doc*/, Inkscape::XML::Node * /*path*/, Inkscape::XML::Node * /*def*/) {} -void -PathEffect::processPath (SPDocument * /*doc*/, Inkscape::XML::Node * /*path*/, Inkscape::XML::Node * /*def*/) +void PathEffect::processPathEffects(SPDocument *doc, Inkscape::XML::Node *path) { - - -} - -void -PathEffect::processPathEffects (SPDocument * doc, Inkscape::XML::Node * path) -{ - gchar const * patheffectlist = path->attribute("inkscape:path-effects"); + gchar const *patheffectlist = path->attribute("inkscape:path-effects"); if (patheffectlist == nullptr) return; - gchar ** patheffects = g_strsplit(patheffectlist, ";", 128); - Inkscape::XML::Node * defs = doc->getDefs()->getRepr(); + gchar **patheffects = g_strsplit(patheffectlist, ";", 128); + Inkscape::XML::Node *defs = doc->getDefs()->getRepr(); for (int i = 0; (i < 128) && (patheffects[i] != nullptr); i++) { - gchar * patheffect = patheffects[i]; + gchar *patheffect = patheffects[i]; // This is weird, they should all be references... but anyway - if (patheffect[0] != '#') continue; + if (patheffect[0] != '#') + continue; - Inkscape::XML::Node * prefs = sp_repr_lookup_child(defs, "id", &(patheffect[1])); + Inkscape::XML::Node *prefs = sp_repr_lookup_child(defs, "id", &(patheffect[1])); if (prefs == nullptr) { - continue; } - gchar const * ext_id = prefs->attribute("extension"); + gchar const *ext_id = prefs->attribute("extension"); if (ext_id == nullptr) { - continue; } - Inkscape::Extension::PathEffect * peffect; + Inkscape::Extension::PathEffect *peffect; peffect = dynamic_cast(Inkscape::Extension::db.get(ext_id)); if (peffect != nullptr) { peffect->processPath(doc, path, prefs); @@ -76,8 +63,8 @@ PathEffect::processPathEffects (SPDocument * doc, Inkscape::XML::Node * path) return; } - -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/patheffect.h b/src/extension/patheffect.h index b2dd7a029c2ccdc7cd7e1ef9fe13a138f885d442..0bd61398cb87a11ee56dae09e44e0a6bb8567d28 100644 --- a/src/extension/patheffect.h +++ b/src/extension/patheffect.h @@ -17,21 +17,18 @@ namespace Inkscape { namespace Extension { -class PathEffect : public Extension { - +class PathEffect : public Extension +{ public: PathEffect(Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory); ~PathEffect() override; - void processPath (SPDocument * doc, - Inkscape::XML::Node * path, - Inkscape::XML::Node * def); - static void processPathEffects (SPDocument * doc, - Inkscape::XML::Node * path); + void processPath(SPDocument *doc, Inkscape::XML::Node *path, Inkscape::XML::Node *def); + static void processPathEffects(SPDocument *doc, Inkscape::XML::Node *path); }; /* PathEffect */ - -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape #endif /* INKSCAPE_EXTENSION_PATHEFFECT_H__ */ /* diff --git a/src/extension/plugins/grid2/grid.cpp b/src/extension/plugins/grid2/grid.cpp index 53dcecd6a070747aef8d09afdcfd1a6429c49791..b5fa1b2277567c02aeca215938368b3c0b21f0c5 100644 --- a/src/extension/plugins/grid2/grid.cpp +++ b/src/extension/plugins/grid2/grid.cpp @@ -12,27 +12,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "grid.h" + #include +#include #include +#include "2geom/geom.h" #include "desktop.h" - #include "document.h" -#include "selection.h" -#include "2geom/geom.h" - -#include "object/sp-object.h" - -#include "svg/path-string.h" - #include "extension/effect.h" #include "extension/system.h" - +#include "object/sp-object.h" +#include "selection.h" +#include "svg/path-string.h" #include "util/units.h" -#include "grid.h" - namespace Inkscape { namespace Extension { namespace Internal { @@ -42,8 +37,7 @@ namespace Internal { \param module Unused \return Whether the load was successful */ -bool -Grid::load (Inkscape::Extension::Extension */*module*/) +bool Grid::load(Inkscape::Extension::Extension * /*module*/) { // std::cout << "Hey, I'm Grid, I'm loading!" << std::endl; return TRUE; @@ -51,27 +45,23 @@ Grid::load (Inkscape::Extension::Extension */*module*/) namespace { -Glib::ustring build_lines(Geom::Rect bounding_area, - Geom::Point const &offset, Geom::Point const &spacing) +Glib::ustring build_lines(Geom::Rect bounding_area, Geom::Point const &offset, Geom::Point const &spacing) { - std::cout << "Building lines" << std::endl; Geom::Point point_offset(0.0, 0.0); SVG::PathString path_data; - for ( int axis = Geom::X ; axis <= Geom::Y ; ++axis ) { + for (int axis = Geom::X; axis <= Geom::Y; ++axis) { point_offset[axis] = offset[axis]; for (Geom::Point start_point = bounding_area.min(); - start_point[axis] + offset[axis] <= (bounding_area.max())[axis]; - start_point[axis] += spacing[axis]) { + start_point[axis] + offset[axis] <= (bounding_area.max())[axis]; start_point[axis] += spacing[axis]) { Geom::Point end_point = start_point; - end_point[1-axis] = (bounding_area.max())[1-axis]; + end_point[1 - axis] = (bounding_area.max())[1 - axis]; - path_data.moveTo(start_point + point_offset) - .lineTo(end_point + point_offset); + path_data.moveTo(start_point + point_offset).lineTo(end_point + point_offset); } } std::cout << "Path data:" << path_data.c_str() << std::endl; @@ -85,29 +75,29 @@ Glib::ustring build_lines(Geom::Rect bounding_area, \param module The effect that was called (unused) \param document What should be edited. */ -void -Grid::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) +void Grid::effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, + Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) { - std::cout << "Executing effect" << std::endl; - Inkscape::Selection * selection = ((SPDesktop *)document)->selection; + Inkscape::Selection *selection = ((SPDesktop *)document)->selection; - Geom::Rect bounding_area = Geom::Rect(Geom::Point(0,0), Geom::Point(100,100)); + Geom::Rect bounding_area = Geom::Rect(Geom::Point(0, 0), Geom::Point(100, 100)); if (selection->isEmpty()) { /* get page size */ - SPDocument * doc = document->doc(); - bounding_area = Geom::Rect( Geom::Point(0,0), - Geom::Point(doc->getWidth().value("px"), doc->getHeight().value("px")) ); + SPDocument *doc = document->doc(); + bounding_area = + Geom::Rect(Geom::Point(0, 0), Geom::Point(doc->getWidth().value("px"), doc->getHeight().value("px"))); } else { Geom::OptRect bounds = selection->visualBounds(); if (bounds) { bounding_area = *bounds; } - gdouble doc_height = (document->doc())->getHeight().value("px"); - Geom::Rect temprec = Geom::Rect(Geom::Point(bounding_area.min()[Geom::X], doc_height - bounding_area.min()[Geom::Y]), - Geom::Point(bounding_area.max()[Geom::X], doc_height - bounding_area.max()[Geom::Y])); + gdouble doc_height = (document->doc())->getHeight().value("px"); + Geom::Rect temprec = + Geom::Rect(Geom::Point(bounding_area.min()[Geom::X], doc_height - bounding_area.min()[Geom::Y]), + Geom::Point(bounding_area.max()[Geom::X], doc_height - bounding_area.max()[Geom::Y])); bounding_area = temprec; } @@ -115,20 +105,18 @@ Grid::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::View *doc double scale = document->doc()->getDocumentScale().inverse()[Geom::X]; bounding_area *= Geom::Scale(scale); - Geom::Point spacings( scale * module->get_param_float("xspacing"), - scale * module->get_param_float("yspacing") ); + Geom::Point spacings(scale * module->get_param_float("xspacing"), scale * module->get_param_float("yspacing")); gdouble line_width = scale * module->get_param_float("lineWidth"); - Geom::Point offsets( scale * module->get_param_float("xoffset"), - scale * module->get_param_float("yoffset") ); + Geom::Point offsets(scale * module->get_param_float("xoffset"), scale * module->get_param_float("yoffset")); Glib::ustring path_data(""); path_data = build_lines(bounding_area, offsets, spacings); - Inkscape::XML::Document * xml_doc = document->doc()->getReprDoc(); + Inkscape::XML::Document *xml_doc = document->doc()->getReprDoc(); - //XML Tree being used directly here while it shouldn't be. - Inkscape::XML::Node * current_layer = static_cast(document)->currentLayer()->getRepr(); - Inkscape::XML::Node * path = xml_doc->createElement("svg:path"); + // XML Tree being used directly here while it shouldn't be. + Inkscape::XML::Node *current_layer = static_cast(document)->currentLayer()->getRepr(); + Inkscape::XML::Node *path = xml_doc->createElement("svg:path"); path->setAttribute("d", path_data); @@ -141,22 +129,27 @@ Grid::effect (Inkscape::Extension::Effect *module, Inkscape::UI::View::View *doc } /** \brief A class to make an adjustment that uses Extension params */ -class PrefAdjustment : public Gtk::Adjustment { +class PrefAdjustment : public Gtk::Adjustment +{ /** Extension that this relates to */ - Inkscape::Extension::Extension * _ext; + Inkscape::Extension::Extension *_ext; /** The string which represents the parameter */ - char * _pref; + char *_pref; + public: /** \brief Make the adjustment using an extension and the string describing the parameter. */ - PrefAdjustment(Inkscape::Extension::Extension * ext, char * pref) : - Gtk::Adjustment(0.0, 0.0, 10.0, 0.1), _ext(ext), _pref(pref) { + PrefAdjustment(Inkscape::Extension::Extension *ext, char *pref) + : Gtk::Adjustment(0.0, 0.0, 10.0, 0.1) + , _ext(ext) + , _pref(pref) + { this->set_value(_ext->get_param_float(_pref)); this->signal_value_changed().connect(sigc::mem_fun(this, &PrefAdjustment::val_changed)); return; }; - void val_changed (); + void val_changed(); }; /* class PrefAdjustment */ /** \brief A function to respond to the value_changed signal from the @@ -165,8 +158,7 @@ public: This function just grabs the value from the adjustment and writes it to the parameter. Very simple, but yet beautiful. */ -void -PrefAdjustment::val_changed () +void PrefAdjustment::val_changed() { // std::cout << "Value Changed to: " << this->get_value() << std::endl; _ext->set_param_float(_pref, this->get_value()); @@ -179,13 +171,14 @@ PrefAdjustment::val_changed () Uses AutoGUI for creating the GUI. */ -Gtk::Widget * -Grid::prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View * view, sigc::signal * changeSignal, Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) +Gtk::Widget *Grid::prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *view, + sigc::signal *changeSignal, + Inkscape::Extension::Implementation::ImplementationDocumentCache * /*docCache*/) { - SPDocument * current_document = view->doc(); + SPDocument *current_document = view->doc(); - auto selected = ((SPDesktop *) view)->getSelection()->items(); - Inkscape::XML::Node * first_select = nullptr; + auto selected = ((SPDesktop *)view)->getSelection()->items(); + Inkscape::XML::Node *first_select = nullptr; if (!selected.empty()) { first_select = selected.front()->getRepr(); } @@ -193,14 +186,10 @@ Grid::prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View return module->autogui(current_document, first_select, changeSignal); } - - - }; /* namespace Internal */ }; /* namespace Extension */ }; /* namespace Inkscape */ - /* Local Variables: mode:c++ diff --git a/src/extension/plugins/grid2/grid.h b/src/extension/plugins/grid2/grid.h index f6d7d57c4d639e3f1d4927f7d920bd5da254d2ab..40b3259b3997ebbeb3f781afbf620fce7eb2317b 100644 --- a/src/extension/plugins/grid2/grid.h +++ b/src/extension/plugins/grid2/grid.h @@ -10,14 +10,11 @@ #ifndef __GRID_H -#include "extension/implementation/implementation.h" - - #include #include -#include "inkscape-version.cpp" - +#include "extension/implementation/implementation.h" +#include "inkscape-version.cpp" namespace Inkscape { namespace Extension { @@ -30,21 +27,29 @@ namespace Internal { /** \brief Implementation class of the GIMP gradient plugin. This mostly just creates a namespace for the GIMP gradient plugin today. */ -class Grid : public Inkscape::Extension::Implementation::Implementation { - +class Grid : public Inkscape::Extension::Implementation::Implementation +{ public: bool load(Inkscape::Extension::Extension *module) override; - void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, Inkscape::Extension::Implementation::ImplementationDocumentCache * docCache) override; - Gtk::Widget * prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View * view, sigc::signal * changeSignal, Inkscape::Extension::Implementation::ImplementationDocumentCache * docCache) override; - + void effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *document, + Inkscape::Extension::Implementation::ImplementationDocumentCache *docCache) override; + Gtk::Widget *prefs_effect(Inkscape::Extension::Effect *module, Inkscape::UI::View::View *view, + sigc::signal *changeSignal, + Inkscape::Extension::Implementation::ImplementationDocumentCache *docCache) override; }; }; /* namespace Internal */ }; /* namespace Extension */ }; /* namespace Inkscape */ -extern "C" G_MODULE_EXPORT Inkscape::Extension::Implementation::Implementation* GetImplementation() { return new Inkscape::Extension::Internal::Grid(); } -extern "C" G_MODULE_EXPORT const gchar* GetInkscapeVersion() { return Inkscape::version_string; } +extern "C" G_MODULE_EXPORT Inkscape::Extension::Implementation::Implementation *GetImplementation() +{ + return new Inkscape::Extension::Internal::Grid(); +} +extern "C" G_MODULE_EXPORT const gchar *GetInkscapeVersion() +{ + return Inkscape::version_string; +} #endif /* diff --git a/src/extension/prefdialog/parameter-bool.cpp b/src/extension/prefdialog/parameter-bool.cpp index 609e7277434b5c17565c6392838e0bbf54178a9b..8ea309a726c7a5a8500c67bcccce22d2643d1c49 100644 --- a/src/extension/prefdialog/parameter-bool.cpp +++ b/src/extension/prefdialog/parameter-bool.cpp @@ -12,9 +12,9 @@ #include #include -#include "xml/node.h" #include "extension/extension.h" #include "preferences.h" +#include "xml/node.h" namespace Inkscape { namespace Extension { @@ -31,8 +31,8 @@ ParamBool::ParamBool(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *e } else if (!strcmp(value, "false")) { _value = false; } else { - g_warning("Invalid default value ('%s') for parameter '%s' in extension '%s'", - value, _name, _extension->get_id()); + g_warning("Invalid default value ('%s') for parameter '%s' in extension '%s'", value, _name, + _extension->get_id()); } } } @@ -61,7 +61,8 @@ bool ParamBool::get() const * parameter to change it's value as the check button changes * value. */ -class ParamBoolCheckButton : public Gtk::CheckButton { +class ParamBoolCheckButton : public Gtk::CheckButton +{ public: /** * Initialize the check button. @@ -73,7 +74,8 @@ public: ParamBoolCheckButton(ParamBool *param, char *label, sigc::signal *changeSignal) : Gtk::CheckButton(label) , _pref(param) - , _changeSignal(changeSignal) { + , _changeSignal(changeSignal) + { this->set_active(_pref->get()); this->signal_toggled().connect(sigc::mem_fun(this, &ParamBoolCheckButton::on_toggle)); return; @@ -83,7 +85,7 @@ public: * A function to respond to the check box changing. * Adjusts the value of the preference to match that in the check box. */ - void on_toggle (); + void on_toggle(); private: /** Param to change. */ @@ -117,7 +119,7 @@ Gtk::Widget *ParamBool::get_widget(sigc::signal *changeSignal) auto hbox = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, GUI_PARAM_WIDGETS_SPACING)); hbox->set_homogeneous(false); - ParamBoolCheckButton * checkbox = Gtk::manage(new ParamBoolCheckButton(this, _text, changeSignal)); + ParamBoolCheckButton *checkbox = Gtk::manage(new ParamBoolCheckButton(this, _text, changeSignal)); checkbox->show(); hbox->pack_start(*checkbox, false, false); @@ -126,8 +128,8 @@ Gtk::Widget *ParamBool::get_widget(sigc::signal *changeSignal) return dynamic_cast(hbox); } -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ /* Local Variables: diff --git a/src/extension/prefdialog/parameter-bool.h b/src/extension/prefdialog/parameter-bool.h index 52fe06a7369e5ff81a9934d88d080304f8f10458..eb0a6c08a5477bd0f0b65293d63efa40be192cad 100644 --- a/src/extension/prefdialog/parameter-bool.h +++ b/src/extension/prefdialog/parameter-bool.h @@ -25,7 +25,8 @@ namespace Extension { /** * A boolean parameter. */ -class ParamBool : public InxParameter { +class ParamBool : public InxParameter +{ public: ParamBool(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); @@ -60,8 +61,8 @@ private: bool _value = true; }; -} // namespace Extension -} // namespace Inkscape +} // namespace Extension +} // namespace Inkscape #endif // SEEN_INK_EXTENSION_PARAMBOOL_H diff --git a/src/extension/prefdialog/parameter-color.cpp b/src/extension/prefdialog/parameter-color.cpp index a17ca1bbd81bc5635655efa71deca460b906302e..99ea9930822e97107b436006d5704f89deb06d29 100644 --- a/src/extension/prefdialog/parameter-color.cpp +++ b/src/extension/prefdialog/parameter-color.cpp @@ -10,23 +10,18 @@ #include "parameter-color.h" -#include -#include - #include #include #include +#include +#include #include "color.h" -#include "preferences.h" - #include "extension/extension.h" - +#include "preferences.h" #include "ui/widget/color-notebook.h" - #include "xml/node.h" - namespace Inkscape { namespace Extension { @@ -56,8 +51,8 @@ ParamColor::ParamColor(Inkscape::XML::Node *xml, Inkscape::Extension::Extension if (!strcmp(_appearance, "colorbutton")) { _mode = COLOR_BUTTON; } else { - g_warning("Invalid value ('%s') for appearance of parameter '%s' in extension '%s'", - _appearance, _name, _extension->get_id()); + g_warning("Invalid value ('%s') for appearance of parameter '%s' in extension '%s'", _appearance, _name, + _extension->get_id()); } } } @@ -92,10 +87,10 @@ Gtk::Widget *ParamColor::get_widget(sigc::signal *changeSignal) hbox->pack_start(*label, true, true); Gdk::RGBA rgba; - rgba.set_red_u (((_color.value() >> 24) & 255) << 8); + rgba.set_red_u(((_color.value() >> 24) & 255) << 8); rgba.set_green_u(((_color.value() >> 16) & 255) << 8); - rgba.set_blue_u (((_color.value() >> 8) & 255) << 8); - rgba.set_alpha_u(((_color.value() >> 0) & 255) << 8); + rgba.set_blue_u(((_color.value() >> 8) & 255) << 8); + rgba.set_alpha_u(((_color.value() >> 0) & 255) << 8); // TODO: It would be nicer to have a custom Gtk::ColorButton() implementation here, // that wraps an Inkscape::UI::Widget::ColorNotebook into a new dialog @@ -113,7 +108,6 @@ Gtk::Widget *ParamColor::get_widget(sigc::signal *changeSignal) } hbox->show(); return hbox; - } void ParamColor::_onColorChanged() @@ -128,10 +122,8 @@ void ParamColor::_onColorChanged() void ParamColor::_onColorButtonChanged() { Gdk::RGBA rgba = _color_button->get_rgba(); - unsigned int value = ((rgba.get_red_u() >> 8) << 24) + - ((rgba.get_green_u() >> 8) << 16) + - ((rgba.get_blue_u() >> 8) << 8) + - ((rgba.get_alpha_u() >> 8) << 0); + unsigned int value = ((rgba.get_red_u() >> 8) << 24) + ((rgba.get_green_u() >> 8) << 16) + + ((rgba.get_blue_u() >> 8) << 8) + ((rgba.get_alpha_u() >> 8) << 0); set(value); } @@ -142,5 +134,5 @@ std::string ParamColor::value_to_string() const return value_string; } -}; /* namespace Extension */ -}; /* namespace Inkscape */ +}; /* namespace Extension */ +}; /* namespace Inkscape */ diff --git a/src/extension/prefdialog/parameter-color.h b/src/extension/prefdialog/parameter-color.h index 4fef4b66bb21a5d5f0ff1d3e339ca2f72a4946d0..5b68740f549f74f5ec590ec0fbe7dfd0293765a8 100644 --- a/src/extension/prefdialog/parameter-color.h +++ b/src/extension/prefdialog/parameter-color.h @@ -15,7 +15,7 @@ namespace Gtk { class Widget; class ColorButton; -} +} // namespace Gtk namespace Inkscape { namespace XML { @@ -24,10 +24,13 @@ class Node; namespace Extension { -class ParamColor : public InxParameter { +class ParamColor : public InxParameter +{ public: - enum AppearanceMode { - DEFAULT, COLOR_BUTTON + enum AppearanceMode + { + DEFAULT, + COLOR_BUTTON }; ParamColor(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); @@ -60,8 +63,8 @@ private: AppearanceMode _mode = DEFAULT; }; // class ParamColor -} // namespace Extension -} // namespace Inkscape +} // namespace Extension +} // namespace Inkscape #endif // SEEN_INK_EXTENSION_PARAMCOLOR_H__ diff --git a/src/extension/prefdialog/parameter-float.cpp b/src/extension/prefdialog/parameter-float.cpp index ad8dc945de65915fcac5b51691e76ef9a502253e..35471107c84472b8af6d343d1dce8719a37bc1d0 100644 --- a/src/extension/prefdialog/parameter-float.cpp +++ b/src/extension/prefdialog/parameter-float.cpp @@ -12,16 +12,12 @@ #include #include -#include "preferences.h" - #include "extension/extension.h" - +#include "preferences.h" #include "ui/widget/spin-scale.h" #include "ui/widget/spinbutton.h" - #include "xml/node.h" - namespace Inkscape { namespace Extension { @@ -64,14 +60,13 @@ ParamFloat::ParamFloat(Inkscape::XML::Node *xml, Inkscape::Extension::Extension _precision = strtol(precision, nullptr, 0); } - // parse appearance if (_appearance) { if (!strcmp(_appearance, "full")) { _mode = FULL; } else { - g_warning("Invalid value ('%s') for appearance of parameter '%s' in extension '%s'", - _appearance, _name, _extension->get_id()); + g_warning("Invalid value ('%s') for appearance of parameter '%s' in extension '%s'", _appearance, _name, + _extension->get_id()); } } } @@ -111,23 +106,26 @@ std::string ParamFloat::value_to_string() const } /** A class to make an adjustment that uses Extension params. */ -class ParamFloatAdjustment : public Gtk::Adjustment { +class ParamFloatAdjustment : public Gtk::Adjustment +{ /** The parameter to adjust. */ ParamFloat *_pref; sigc::signal *_changeSignal; + public: /** Make the adjustment using an extension and the string describing the parameter. */ ParamFloatAdjustment(ParamFloat *param, sigc::signal *changeSignal) : Gtk::Adjustment(0.0, param->min(), param->max(), 0.1, 1.0, 0) , _pref(param) - , _changeSignal(changeSignal) { + , _changeSignal(changeSignal) + { this->set_value(_pref->get()); this->signal_value_changed().connect(sigc::mem_fun(this, &ParamFloatAdjustment::val_changed)); return; }; - void val_changed (); + void val_changed(); }; /* class ParamFloatAdjustment */ /** @@ -162,7 +160,6 @@ Gtk::Widget *ParamFloat::get_widget(sigc::signal *changeSignal) Glib::RefPtr fadjust(pfa); if (_mode == FULL) { - Glib::ustring text; if (_text != nullptr) text = _text; @@ -171,14 +168,12 @@ Gtk::Widget *ParamFloat::get_widget(sigc::signal *changeSignal) scale->show(); hbox->pack_start(*scale, true, true); - } - else if (_mode == DEFAULT) { - + } else if (_mode == DEFAULT) { Gtk::Label *label = Gtk::manage(new Gtk::Label(_text, Gtk::ALIGN_START)); label->show(); hbox->pack_start(*label, true, true); - auto spin = Gtk::manage(new Inkscape::UI::Widget::SpinButton(fadjust, 0.1, _precision)); + auto spin = Gtk::manage(new Inkscape::UI::Widget::SpinButton(fadjust, 0.1, _precision)); spin->show(); hbox->pack_start(*spin, false, false); } @@ -188,6 +183,5 @@ Gtk::Widget *ParamFloat::get_widget(sigc::signal *changeSignal) return dynamic_cast(hbox); } - -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ diff --git a/src/extension/prefdialog/parameter-float.h b/src/extension/prefdialog/parameter-float.h index 4c28cb54e66160f889b9a6d540b9ddb76c39bc05..131b6ed77bb7e82435dbddd3a3b34d7c1c9cf832 100644 --- a/src/extension/prefdialog/parameter-float.h +++ b/src/extension/prefdialog/parameter-float.h @@ -23,10 +23,13 @@ class Node; namespace Extension { -class ParamFloat : public InxParameter { +class ParamFloat : public InxParameter +{ public: - enum AppearanceMode { - DEFAULT, FULL + enum AppearanceMode + { + DEFAULT, + FULL }; ParamFloat(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); @@ -36,11 +39,11 @@ public: float set(float in); - float max () { return _max; } + float max() { return _max; } - float min () { return _min; } + float min() { return _min; } - float precision () { return _precision; } + float precision() { return _precision; } Gtk::Widget *get_widget(sigc::signal *changeSignal) override; @@ -62,8 +65,8 @@ private: AppearanceMode _mode = DEFAULT; }; -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* INK_EXTENSION_PARAMFLOAT_H_SEEN */ diff --git a/src/extension/prefdialog/parameter-int.cpp b/src/extension/prefdialog/parameter-int.cpp index 8a8e49ec979441c6ce6d940a33d8726a594dd1d8..4c017ce1f5cc2296fec92cb736ac423f52172544 100644 --- a/src/extension/prefdialog/parameter-int.cpp +++ b/src/extension/prefdialog/parameter-int.cpp @@ -12,20 +12,15 @@ #include #include -#include "preferences.h" - #include "extension/extension.h" - -#include "ui/widget/spinbutton.h" +#include "preferences.h" #include "ui/widget/spin-scale.h" - +#include "ui/widget/spinbutton.h" #include "xml/node.h" - namespace Inkscape { namespace Extension { - ParamInt::ParamInt(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext) : InxParameter(xml, ext) { @@ -64,8 +59,8 @@ ParamInt::ParamInt(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext if (!strcmp(_appearance, "full")) { _mode = FULL; } else { - g_warning("Invalid value ('%s') for appearance of parameter '%s' in extension '%s'", - _appearance, _name, _extension->get_id()); + g_warning("Invalid value ('%s') for appearance of parameter '%s' in extension '%s'", _appearance, _name, + _extension->get_id()); } } } @@ -94,10 +89,12 @@ int ParamInt::set(int in) } /** A class to make an adjustment that uses Extension params. */ -class ParamIntAdjustment : public Gtk::Adjustment { +class ParamIntAdjustment : public Gtk::Adjustment +{ /** The parameter to adjust. */ ParamInt *_pref; sigc::signal *_changeSignal; + public: /** Make the adjustment using an extension and the string describing the parameter. */ ParamIntAdjustment(ParamInt *param, sigc::signal *changeSignal) @@ -109,7 +106,7 @@ public: this->signal_value_changed().connect(sigc::mem_fun(this, &ParamIntAdjustment::val_changed)); }; - void val_changed (); + void val_changed(); }; /* class ParamIntAdjustment */ /** @@ -131,8 +128,7 @@ void ParamIntAdjustment::val_changed() * * Builds a hbox with a label and a int adjustment in it. */ -Gtk::Widget * -ParamInt::get_widget(sigc::signal *changeSignal) +Gtk::Widget *ParamInt::get_widget(sigc::signal *changeSignal) { if (_hidden) { return nullptr; @@ -144,7 +140,6 @@ ParamInt::get_widget(sigc::signal *changeSignal) Glib::RefPtr fadjust(pia); if (_mode == FULL) { - Glib::ustring text; if (_text != nullptr) text = _text; @@ -174,8 +169,8 @@ std::string ParamInt::value_to_string() const return value_string; } -} // namespace Extension -} // namespace Inkscape +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/prefdialog/parameter-int.h b/src/extension/prefdialog/parameter-int.h index da43eb75fcee4879cf9741e3fb16701454a52ff4..4d3dcff9c885fd341595f03f83943e9d4700a90a 100644 --- a/src/extension/prefdialog/parameter-int.h +++ b/src/extension/prefdialog/parameter-int.h @@ -23,10 +23,13 @@ class Node; namespace Extension { -class ParamInt : public InxParameter { +class ParamInt : public InxParameter +{ public: - enum AppearanceMode { - DEFAULT, FULL + enum AppearanceMode + { + DEFAULT, + FULL }; ParamInt(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); @@ -36,9 +39,9 @@ public: int set(int in); - int max () { return _max; } + int max() { return _max; } - int min () { return _min; } + int min() { return _min; } Gtk::Widget *get_widget(sigc::signal *changeSignal) override; @@ -57,8 +60,8 @@ private: AppearanceMode _mode = DEFAULT; }; -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* INK_EXTENSION_PARAMINT_H_SEEN */ diff --git a/src/extension/prefdialog/parameter-notebook.cpp b/src/extension/prefdialog/parameter-notebook.cpp index 0a7ae44892c20fc78d1a3ed6c5d6951c8c28fba5..951f25b57fc439ba13ea1a76cbc43f99ba81c72c 100644 --- a/src/extension/prefdialog/parameter-notebook.cpp +++ b/src/extension/prefdialog/parameter-notebook.cpp @@ -15,21 +15,17 @@ #include "parameter-notebook.h" -#include - #include #include - -#include "preferences.h" +#include #include "extension/extension.h" - +#include "preferences.h" #include "xml/node.h" namespace Inkscape { namespace Extension { - ParamNotebook::ParamNotebookPage::ParamNotebookPage(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext) : InxParameter(xml, ext) { @@ -51,9 +47,9 @@ ParamNotebook::ParamNotebookPage::ParamNotebookPage(Inkscape::XML::Node *xml, In _children.push_back(widget); } } else if (child_repr->type() == XML::ELEMENT_NODE) { - g_warning("Invalid child element ('%s') in notebook page in extension '%s'.", - chname, _extension->get_id()); - } else if (child_repr->type() != XML::COMMENT_NODE){ + g_warning("Invalid child element ('%s') in notebook page in extension '%s'.", chname, + _extension->get_id()); + } else if (child_repr->type() != XML::COMMENT_NODE) { g_warning("Invalid child element found in notebook page in extension '%s'.", _extension->get_id()); } @@ -62,7 +58,6 @@ ParamNotebook::ParamNotebookPage::ParamNotebookPage(Inkscape::XML::Node *xml, In } } - /** * Creates a notebookpage widget for a notebook. * @@ -74,7 +69,7 @@ Gtk::Widget *ParamNotebook::ParamNotebookPage::get_widget(sigc::signal *ch return nullptr; } - Gtk::VBox * vbox = Gtk::manage(new Gtk::VBox); + Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox); vbox->set_border_width(GUI_BOX_MARGIN); vbox->set_spacing(GUI_BOX_SPACING); @@ -83,7 +78,7 @@ Gtk::Widget *ParamNotebook::ParamNotebookPage::get_widget(sigc::signal *ch Gtk::Widget *child_widget = child->get_widget(changeSignal); if (child_widget) { int indent = child->get_indent(); - child_widget->set_margin_start(indent *GUI_INDENTATION); + child_widget->set_margin_start(indent * GUI_INDENTATION); vbox->pack_start(*child_widget, false, true, 0); // fill=true does not have an effect here, but allows the // child to choose to expand by setting hexpand/vexpand @@ -101,8 +96,6 @@ Gtk::Widget *ParamNotebook::ParamNotebookPage::get_widget(sigc::signal *ch /** End ParamNotebookPage **/ - - /** ParamNotebook **/ ParamNotebook::ParamNotebook(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext) @@ -113,8 +106,8 @@ ParamNotebook::ParamNotebook(Inkscape::XML::Node *xml, Inkscape::Extension::Exte Inkscape::XML::Node *child_repr = xml->firstChild(); while (child_repr) { const char *chname = child_repr->name(); - if (chname && (!strcmp(chname, INKSCAPE_EXTENSION_NS "page") || - !strcmp(chname, INKSCAPE_EXTENSION_NS "_page") )) { + if (chname && + (!strcmp(chname, INKSCAPE_EXTENSION_NS "page") || !strcmp(chname, INKSCAPE_EXTENSION_NS "_page"))) { ParamNotebookPage *page; page = new ParamNotebookPage(child_repr, ext); @@ -122,11 +115,11 @@ ParamNotebook::ParamNotebook(Inkscape::XML::Node *xml, Inkscape::Extension::Exte _children.push_back(page); } } else if (child_repr->type() == XML::ELEMENT_NODE) { - g_warning("Invalid child element ('%s') for parameter '%s' in extension '%s'. Expected 'page'.", - chname, _name, _extension->get_id()); - } else if (child_repr->type() != XML::COMMENT_NODE){ - g_warning("Invalid child element found in parameter '%s' in extension '%s'. Expected 'page'.", + g_warning("Invalid child element ('%s') for parameter '%s' in extension '%s'. Expected 'page'.", chname, _name, _extension->get_id()); + } else if (child_repr->type() != XML::COMMENT_NODE) { + g_warning("Invalid child element found in parameter '%s' in extension '%s'. Expected 'page'.", _name, + _extension->get_id()); } child_repr = child_repr->next(); } @@ -141,8 +134,8 @@ ParamNotebook::ParamNotebook(Inkscape::XML::Node *xml, Inkscape::Extension::Exte ParamNotebookPage *page = static_cast(child); auto ret = names.emplace(page->_name); if (!ret.second) { - g_warning("Duplicate page name ('%s') for parameter '%s' in extension '%s'.", - page->_name, _name, _extension->get_id()); + g_warning("Duplicate page name ('%s') for parameter '%s' in extension '%s'.", page->_name, _name, + _extension->get_id()); } } @@ -158,7 +151,6 @@ ParamNotebook::ParamNotebook(Inkscape::XML::Node *xml, Inkscape::Extension::Exte } } - /** * A function to set the \c _value. * @@ -167,9 +159,9 @@ ParamNotebook::ParamNotebook(Inkscape::XML::Node *xml, Inkscape::Extension::Exte * * @param in The number of the page to set as new value. */ -const Glib::ustring& ParamNotebook::set(const int in) +const Glib::ustring &ParamNotebook::set(const int in) { - int i = in < _children.size() ? in : _children.size()-1; + int i = in < _children.size() ? in : _children.size() - 1; ParamNotebookPage *page = dynamic_cast(_children[i]); if (page) { @@ -187,11 +179,12 @@ std::string ParamNotebook::value_to_string() const return _value.raw(); } - /** A special category of Gtk::Notebook to handle notebook parameters. */ -class NotebookWidget : public Gtk::Notebook { +class NotebookWidget : public Gtk::Notebook +{ private: ParamNotebook *_pref; + public: /** * Build a notebookpage preference for the given parameter. @@ -269,9 +262,8 @@ Gtk::Widget *ParamNotebook::get_widget(sigc::signal *changeSignal) return static_cast(notebook); } - -} // namespace Extension -} // namespace Inkscape +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/prefdialog/parameter-notebook.h b/src/extension/prefdialog/parameter-notebook.h index b64e5c62a0cfcc034ff1119ee38dd929b300082d..7c445bdd4a38f6b082bfbbb66cf7cc988d6dcb1b 100644 --- a/src/extension/prefdialog/parameter-notebook.h +++ b/src/extension/prefdialog/parameter-notebook.h @@ -16,26 +16,23 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "parameter.h" - -#include - #include +#include +#include "parameter.h" namespace Gtk { class Widget; } - namespace Inkscape { namespace Extension { class Extension; - /** A class to represent a notebook parameter of an extension. */ -class ParamNotebook : public InxParameter { +class ParamNotebook : public InxParameter +{ private: /** Internal value. */ Glib::ustring _value; @@ -43,8 +40,10 @@ private: /** * A class to represent the pages of a notebook parameter of an extension. */ - class ParamNotebookPage : public InxParameter { + class ParamNotebookPage : public InxParameter + { friend class ParamNotebook; + public: ParamNotebookPage(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); @@ -61,16 +60,12 @@ public: std::string value_to_string() const override; - const Glib::ustring& get() { return _value; } - const Glib::ustring& set(const int in); + const Glib::ustring &get() { return _value; } + const Glib::ustring &set(const int in); }; /* class ParamNotebook */ - - - - -} // namespace Extension -} // namespace Inkscape +} // namespace Extension +} // namespace Inkscape #endif /* INK_EXTENSION_PARAMNOTEBOOK_H_SEEN */ diff --git a/src/extension/prefdialog/parameter-optiongroup.cpp b/src/extension/prefdialog/parameter-optiongroup.cpp index c40c24b8505b8f20e1fb98713e3100cee28fcbcb..252aa882b7ead3ad7ebd618b22eae0204b279fbb 100644 --- a/src/extension/prefdialog/parameter-optiongroup.cpp +++ b/src/extension/prefdialog/parameter-optiongroup.cpp @@ -17,16 +17,14 @@ #include "parameter-optiongroup.h" -#include - #include #include #include +#include -#include "xml/node.h" #include "extension/extension.h" #include "preferences.h" - +#include "xml/node.h" namespace Inkscape { namespace Extension { @@ -42,20 +40,19 @@ ParamOptionGroup::ParamOptionGroup(Inkscape::XML::Node *xml, Inkscape::Extension Inkscape::XML::Node *child_repr = xml->firstChild(); while (child_repr) { const char *chname = child_repr->name(); - if (chname && (!strcmp(chname, INKSCAPE_EXTENSION_NS "option") || - !strcmp(chname, INKSCAPE_EXTENSION_NS "_option") || - !strcmp(chname, INKSCAPE_EXTENSION_NS "item") || - !strcmp(chname, INKSCAPE_EXTENSION_NS "_item")) ) { - child_repr->setAttribute("name", "option"); // TODO: hack to allow options to be parameters + if (chname && + (!strcmp(chname, INKSCAPE_EXTENSION_NS "option") || !strcmp(chname, INKSCAPE_EXTENSION_NS "_option") || + !strcmp(chname, INKSCAPE_EXTENSION_NS "item") || !strcmp(chname, INKSCAPE_EXTENSION_NS "_item"))) { + child_repr->setAttribute("name", "option"); // TODO: hack to allow options to be parameters child_repr->setAttribute("gui-text", "option"); // TODO: hack to allow options to be parameters ParamOptionGroupOption *param = new ParamOptionGroupOption(child_repr, ext, this); choices.push_back(param); } else if (child_repr->type() == XML::ELEMENT_NODE) { g_warning("Invalid child element ('%s') for parameter '%s' in extension '%s'. Expected 'option'.", chname, _name, _extension->get_id()); - } else if (child_repr->type() != XML::COMMENT_NODE){ - g_warning("Invalid child element found in parameter '%s' in extension '%s'. Expected 'option'.", - _name, _extension->get_id()); + } else if (child_repr->type() != XML::COMMENT_NODE) { + g_warning("Invalid child element found in parameter '%s' in extension '%s'. Expected 'option'.", _name, + _extension->get_id()); } child_repr = child_repr->next(); } @@ -70,13 +67,13 @@ ParamOptionGroup::ParamOptionGroup(Inkscape::XML::Node *xml, Inkscape::Extension for (auto choice : choices) { auto ret1 = texts.emplace(choice->_text.raw()); if (!ret1.second) { - g_warning("Duplicate option text ('%s') for parameter '%s' in extension '%s'.", - choice->_text.c_str(), _name, _extension->get_id()); + g_warning("Duplicate option text ('%s') for parameter '%s' in extension '%s'.", choice->_text.c_str(), + _name, _extension->get_id()); } auto ret2 = values.emplace(choice->_value.raw()); if (!ret2.second) { - g_warning("Duplicate option value ('%s') for parameter '%s' in extension '%s'.", - choice->_value.c_str(), _name, _extension->get_id()); + g_warning("Duplicate option value ('%s') for parameter '%s' in extension '%s'.", choice->_value.c_str(), + _name, _extension->get_id()); } } @@ -98,13 +95,13 @@ ParamOptionGroup::ParamOptionGroup(Inkscape::XML::Node *xml, Inkscape::Extension } else if (!strcmp(_appearance, "radio")) { _mode = RADIOBUTTON; } else { - g_warning("Invalid value ('%s') for appearance of parameter '%s' in extension '%s'", - _appearance, _name, _extension->get_id()); + g_warning("Invalid value ('%s') for appearance of parameter '%s' in extension '%s'", _appearance, _name, + _extension->get_id()); } } } -ParamOptionGroup::~ParamOptionGroup () +ParamOptionGroup::~ParamOptionGroup() { // destroy choice strings for (auto choice : choices) { @@ -112,7 +109,6 @@ ParamOptionGroup::~ParamOptionGroup () } } - /** * A function to set the \c _value. * @@ -121,15 +117,15 @@ ParamOptionGroup::~ParamOptionGroup () * * @param in The value to set. */ -const Glib::ustring& ParamOptionGroup::set(Glib::ustring in) +const Glib::ustring &ParamOptionGroup::set(Glib::ustring in) { if (contains(in)) { _value = in; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setString(pref_name(), _value.c_str()); } else { - g_warning("Could not set value ('%s') for parameter '%s' in extension '%s'. Not a valid choice.", - in.c_str(), _name, _extension->get_id()); + g_warning("Could not set value ('%s') for parameter '%s' in extension '%s'. Not a valid choice.", in.c_str(), + _name, _extension->get_id()); } return _value; @@ -168,16 +164,16 @@ Glib::ustring ParamOptionGroup::value_from_label(const Glib::ustring label) return value; } - - /** A special RadioButton class to use in ParamOptionGroup. */ -class RadioWidget : public Gtk::RadioButton { +class RadioWidget : public Gtk::RadioButton +{ private: ParamOptionGroup *_pref; sigc::signal *_changeSignal; + public: - RadioWidget(Gtk::RadioButtonGroup& group, const Glib::ustring& label, - ParamOptionGroup *pref, sigc::signal *changeSignal) + RadioWidget(Gtk::RadioButtonGroup &group, const Glib::ustring &label, ParamOptionGroup *pref, + sigc::signal *changeSignal) : Gtk::RadioButton(group, label) , _pref(pref) , _changeSignal(changeSignal) @@ -185,9 +181,7 @@ public: add_changesignal(); }; - void add_changesignal() { - this->signal_toggled().connect(sigc::mem_fun(this, &RadioWidget::changed)); - }; + void add_changesignal() { this->signal_toggled().connect(sigc::mem_fun(this, &RadioWidget::changed)); }; void changed(); }; @@ -210,9 +204,9 @@ void RadioWidget::changed() } } - /** A special ComboBoxText class to use in ParamOptionGroup. */ -class ComboWidget : public Gtk::ComboBoxText { +class ComboWidget : public Gtk::ComboBoxText +{ private: ParamOptionGroup *_pref; sigc::signal *_changeSignal; @@ -242,8 +236,6 @@ void ComboWidget::changed() } } - - /** * Creates the widget for the optiongroup parameter. */ @@ -294,8 +286,8 @@ Gtk::Widget *ParamOptionGroup::get_widget(sigc::signal *changeSignal) return static_cast(hbox); } - -ParamOptionGroup::ParamOptionGroupOption::ParamOptionGroupOption(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext, +ParamOptionGroup::ParamOptionGroupOption::ParamOptionGroupOption(Inkscape::XML::Node *xml, + Inkscape::Extension::Extension *ext, const Inkscape::Extension::ParamOptionGroup *parent) : InxParameter(xml, ext) { @@ -311,8 +303,8 @@ ParamOptionGroup::ParamOptionGroupOption::ParamOptionGroupOption(Inkscape::XML:: _text = text; } } else { - g_warning("Missing content in option of parameter '%s' in extension '%s'.", - parent->_name, _extension->get_id()); + g_warning("Missing content in option of parameter '%s' in extension '%s'.", parent->_name, + _extension->get_id()); } // get string value of option @@ -328,16 +320,14 @@ ParamOptionGroup::ParamOptionGroupOption::ParamOptionGroupOption(Inkscape::XML:: _value = _text; // use translated UI text as value } } else { - g_warning("Missing value for option '%s' of parameter '%s' in extension '%s'.", - _text.c_str(), parent->_name, _extension->get_id()); + g_warning("Missing value for option '%s' of parameter '%s' in extension '%s'.", _text.c_str(), + parent->_name, _extension->get_id()); } } } - - -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ /* Local Variables: diff --git a/src/extension/prefdialog/parameter-optiongroup.h b/src/extension/prefdialog/parameter-optiongroup.h index 533b13170cac5b16a82d40d22396c2a507345f36..ccb7aa87e684f4d4b57e210b0ac23e988bbdfbed 100644 --- a/src/extension/prefdialog/parameter-optiongroup.h +++ b/src/extension/prefdialog/parameter-optiongroup.h @@ -18,11 +18,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "parameter.h" - +#include #include -#include +#include "parameter.h" namespace Gtk { class Widget; @@ -33,13 +32,14 @@ namespace Extension { class Extension; - - // \brief A class to represent an optiongroup (option with multiple predefined value choices) parameter of an extension -class ParamOptionGroup : public InxParameter { +class ParamOptionGroup : public InxParameter +{ public: - enum AppearanceMode { - RADIOBUTTON, COMBOBOX + enum AppearanceMode + { + RADIOBUTTON, + COMBOBOX }; ParamOptionGroup(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); @@ -51,9 +51,9 @@ public: Glib::ustring value_from_label(const Glib::ustring label); - const Glib::ustring& get() const { return _value; } + const Glib::ustring &get() const { return _value; } - const Glib::ustring& set(const Glib::ustring in); + const Glib::ustring &set(const Glib::ustring in); /** * @returns true if text is a valid choice for this option group @@ -69,25 +69,24 @@ private: AppearanceMode _mode = RADIOBUTTON; /* For internal use only. */ - class ParamOptionGroupOption : public InxParameter { + class ParamOptionGroupOption : public InxParameter + { friend class ParamOptionGroup; + public: ParamOptionGroupOption(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext, const Inkscape::Extension::ParamOptionGroup *parent); + private: Glib::ustring _value; Glib::ustring _text; }; std::vector choices; /**< List of available options for the option group */ -}; /* class ParamOptionGroup */ - - - - +}; /* class ParamOptionGroup */ -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /*INK_EXTENSION_PARAMOPTIONGROUP_H_SEEN */ diff --git a/src/extension/prefdialog/parameter-path.cpp b/src/extension/prefdialog/parameter-path.cpp index 5ad3cf196e67fe0c0cc40f47894d5e9c031d36c3..d611b101372a2e75f7047625abd442946d85e87d 100644 --- a/src/extension/prefdialog/parameter-path.cpp +++ b/src/extension/prefdialog/parameter-path.cpp @@ -14,21 +14,19 @@ #include #include - -#include #include +#include #include #include - #include #include #include #include #include -#include "xml/node.h" #include "extension/extension.h" #include "preferences.h" +#include "xml/node.h" namespace Inkscape { namespace Extension { @@ -66,15 +64,15 @@ ParamPath::ParamPath(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *e } else if (!strcmp(mode, "folder_new")) { _mode = FOLDER_NEW; } else { - g_warning("Invalid value ('%s') for mode of parameter '%s' in extension '%s'", - mode, _name, _extension->get_id()); + g_warning("Invalid value ('%s') for mode of parameter '%s' in extension '%s'", mode, _name, + _extension->get_id()); } } // parse filetypes const char *filetypes = xml->attribute("filetypes"); if (filetypes) { - _filetypes = Glib::Regex::split_simple("," , filetypes); + _filetypes = Glib::Regex::split_simple(",", filetypes); } } @@ -86,7 +84,7 @@ ParamPath::ParamPath(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *e * * @param in The value to set to. */ -const std::string& ParamPath::set(const std::string in) +const std::string &ParamPath::set(const std::string in) { _value = in; @@ -105,12 +103,13 @@ std::string ParamPath::value_to_string() const } } - /** A special type of Gtk::Entry to handle path parameters. */ -class ParamPathEntry : public Gtk::Entry { +class ParamPathEntry : public Gtk::Entry +{ private: ParamPath *_pref; sigc::signal *_changeSignal; + public: /** * Build a string preference for the given parameter. @@ -128,7 +127,6 @@ public: void changed_text(); }; - /** * Respond to the text box changing. * @@ -166,7 +164,7 @@ Gtk::Widget *ParamPath::get_widget(sigc::signal *changeSignal) _entry = textbox; Gtk::Button *button = Gtk::manage(new Gtk::Button("…")); - button->show(); + button->show(); hbox->pack_end(*button, false, false); button->signal_clicked().connect(sigc::mem_fun(*this, &ParamPath::on_button_clicked)); @@ -245,7 +243,7 @@ void ParamPath::on_button_clicked() file_chooser->set_current_folder(dirname); } - if(_mode == FILE_NEW || _mode == FOLDER_NEW) { + if (_mode == FILE_NEW || _mode == FOLDER_NEW) { file_chooser->set_current_name(Glib::path_get_basename(first_filename)); } else { if (Glib::file_test(first_filename, Glib::FILE_TEST_EXISTS)) { @@ -264,5 +262,5 @@ void ParamPath::on_button_clicked() } } -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ diff --git a/src/extension/prefdialog/parameter-path.h b/src/extension/prefdialog/parameter-path.h index 2de231190fa02a19bc09b98aca79dfdb6b34bb80..1da8dc6daeca12868ce3611c2aab99286fe89847 100644 --- a/src/extension/prefdialog/parameter-path.h +++ b/src/extension/prefdialog/parameter-path.h @@ -15,27 +15,31 @@ #include "parameter.h" - namespace Inkscape { namespace Extension { class ParamPathEntry; -class ParamPath : public InxParameter { +class ParamPath : public InxParameter +{ public: ParamPath(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); /** \brief Returns \c _value, with a \i const to protect it. */ - const std::string& get() const { return _value; } - const std::string& set(const std::string in); + const std::string &get() const { return _value; } + const std::string &set(const std::string in); Gtk::Widget *get_widget(sigc::signal *changeSignal) override; std::string value_to_string() const override; private: - enum Mode { - FILE, FOLDER, FILE_NEW, FOLDER_NEW + enum Mode + { + FILE, + FOLDER, + FILE_NEW, + FOLDER_NEW }; /** \brief Internal value. */ @@ -51,15 +55,14 @@ private: std::vector _filetypes; /** pointer to the parameters text entry - * keep this around, so we can update the value accordingly in \a on_button_clicked() */ + * keep this around, so we can update the value accordingly in \a on_button_clicked() */ ParamPathEntry *_entry; void on_button_clicked(); }; - -} // namespace Extension -} // namespace Inkscape +} // namespace Extension +} // namespace Inkscape #endif /* INK_EXTENSION_PARAM_PATH_H_SEEN */ diff --git a/src/extension/prefdialog/parameter-string.cpp b/src/extension/prefdialog/parameter-string.cpp index 708731a950cb931cebadf8d31c319c3605b373a7..90a10e58382cc0f2435ee591e6590b8cdf32e597 100644 --- a/src/extension/prefdialog/parameter-string.cpp +++ b/src/extension/prefdialog/parameter-string.cpp @@ -9,15 +9,15 @@ #include "parameter-string.h" +#include #include #include #include #include -#include -#include "xml/node.h" #include "extension/extension.h" #include "preferences.h" +#include "xml/node.h" namespace Inkscape { namespace Extension { @@ -59,8 +59,8 @@ ParamString::ParamString(Inkscape::XML::Node *xml, Inkscape::Extension::Extensio if (!strcmp(_appearance, "multiline")) { _mode = MULTILINE; } else { - g_warning("Invalid value ('%s') for appearance of parameter '%s' in extension '%s'", - _appearance, _name, _extension->get_id()); + g_warning("Invalid value ('%s') for appearance of parameter '%s' in extension '%s'", _appearance, _name, + _extension->get_id()); } } } @@ -77,7 +77,7 @@ ParamString::ParamString(Inkscape::XML::Node *xml, Inkscape::Extension::Extensio * * @param in The value to set to. */ -const Glib::ustring& ParamString::set(const Glib::ustring in) +const Glib::ustring &ParamString::set(const Glib::ustring in) { _value = in; @@ -92,13 +92,13 @@ std::string ParamString::value_to_string() const return _value.raw(); } - - /** A special type of Gtk::Entry to handle string parameters. */ -class ParamStringEntry : public Gtk::Entry { +class ParamStringEntry : public Gtk::Entry +{ private: ParamString *_pref; sigc::signal *_changeSignal; + public: /** * Build a string preference for the given parameter. @@ -111,13 +111,12 @@ public: , _changeSignal(changeSignal) { this->set_text(_pref->get()); - this->set_max_length(_pref->getMaxLength()); //Set the max length - default zero means no maximum + this->set_max_length(_pref->getMaxLength()); // Set the max length - default zero means no maximum this->signal_changed().connect(sigc::mem_fun(this, &ParamStringEntry::changed_text)); }; void changed_text(); }; - /** * Respond to the text box changing. * @@ -133,13 +132,13 @@ void ParamStringEntry::changed_text() } } - - /** A special type of Gtk::TextView to handle multiline string parameters. */ -class ParamMultilineStringEntry : public Gtk::TextView { +class ParamMultilineStringEntry : public Gtk::TextView +{ private: ParamString *_pref; sigc::signal *_changeSignal; + public: /** * Build a string preference for the given parameter. @@ -152,7 +151,8 @@ public: , _changeSignal(changeSignal) { // replace literal '\n' with actual newlines for multiline strings - Glib::ustring value = Glib::Regex::create("\\\\n")->replace_literal(_pref->get(), 0, "\n", (Glib::RegexMatchFlags)0); + Glib::ustring value = + Glib::Regex::create("\\\\n")->replace_literal(_pref->get(), 0, "\n", (Glib::RegexMatchFlags)0); this->get_buffer()->set_text(value); this->get_buffer()->signal_changed().connect(sigc::mem_fun(this, &ParamMultilineStringEntry::changed_text)); @@ -179,8 +179,6 @@ void ParamMultilineStringEntry::changed_text() } } - - /** * Creates a text box for the string parameter. * @@ -224,5 +222,5 @@ Gtk::Widget *ParamString::get_widget(sigc::signal *changeSignal) return dynamic_cast(box); } -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ diff --git a/src/extension/prefdialog/parameter-string.h b/src/extension/prefdialog/parameter-string.h index 3af83111dee7ebc7e8f2dac35c1f1aeb6ac2ebca..20c798dee0af7d86517f1dd8baeeaaf03eba2b06 100644 --- a/src/extension/prefdialog/parameter-string.h +++ b/src/extension/prefdialog/parameter-string.h @@ -10,25 +10,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "parameter.h" - #include +#include "parameter.h" namespace Inkscape { namespace Extension { -class ParamString : public InxParameter { +class ParamString : public InxParameter +{ public: - enum AppearanceMode { - DEFAULT, MULTILINE + enum AppearanceMode + { + DEFAULT, + MULTILINE }; ParamString(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); /** \brief Returns \c _value, with a \i const to protect it. */ - const Glib::ustring& get() const { return _value; } - const Glib::ustring& set(const Glib::ustring in); + const Glib::ustring &get() const { return _value; } + const Glib::ustring &set(const Glib::ustring in); Gtk::Widget *get_widget(sigc::signal *changeSignal) override; @@ -48,9 +50,8 @@ private: int _max_length = 0; }; - -} // namespace Extension -} // namespace Inkscape +} // namespace Extension +} // namespace Inkscape #endif /* INK_EXTENSION_PARAMSTRING_H_SEEN */ diff --git a/src/extension/prefdialog/parameter.cpp b/src/extension/prefdialog/parameter.cpp index 14ccfc39477a9fdbea0add3d13157b0d4d4e650d..11f31a7e1172e9befe875d72cb8ece05ac716889 100644 --- a/src/extension/prefdialog/parameter.cpp +++ b/src/extension/prefdialog/parameter.cpp @@ -12,13 +12,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include +#include "parameter.h" +#include #include +#include #include -#include "parameter.h" +#include "extension/extension.h" +#include "object/sp-defs.h" #include "parameter-bool.h" #include "parameter-color.h" #include "parameter-float.h" @@ -27,25 +29,20 @@ #include "parameter-optiongroup.h" #include "parameter-path.h" #include "parameter-string.h" -#include "widget.h" -#include "widget-label.h" - -#include "extension/extension.h" - -#include "object/sp-defs.h" - #include "ui/widget/color-notebook.h" - +#include "widget-label.h" +#include "widget.h" #include "xml/node.h" - namespace Inkscape { namespace Extension { - // Re-implement ParamDescription for backwards-compatibility, deriving from both, WidgetLabel and InxParameter. // TODO: Should go away eventually... -class ParamDescription : public virtual WidgetLabel, public virtual InxParameter { +class ParamDescription + : public virtual WidgetLabel + , public virtual InxParameter +{ public: ParamDescription(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext) : WidgetLabel(xml, ext) @@ -61,8 +58,6 @@ public: std::string value_to_string() const override { return ""; } }; - - InxParameter *InxParameter::make(Inkscape::XML::Node *in_repr, Inkscape::Extension::Extension *in_ext) { InxParameter *param = nullptr; @@ -72,7 +67,7 @@ InxParameter *InxParameter::make(Inkscape::XML::Node *in_repr, Inkscape::Extensi if (!type) { // we can't create a parameter without type g_warning("Parameter without type in extension '%s'.", in_ext->get_id()); - } else if(!strcmp(type, "bool") || !strcmp(type, "boolean")) { // support "boolean" for backwards-compatibility + } else if (!strcmp(type, "bool") || !strcmp(type, "boolean")) { // support "boolean" for backwards-compatibility param = new ParamBool(in_repr, in_ext); } else if (!strcmp(type, "int")) { param = new ParamInt(in_repr, in_ext); @@ -99,8 +94,8 @@ InxParameter *InxParameter::make(Inkscape::XML::Node *in_repr, Inkscape::Extensi } else { g_warning("Unknown parameter type ('%s') in extension '%s'", type, in_ext->get_id()); } - } catch (const param_no_name&) { - } catch (const param_no_text&) { + } catch (const param_no_name &) { + } catch (const param_no_text &) { } // Note: param could equal nullptr @@ -172,7 +167,7 @@ unsigned int InxParameter::get_color() const bool InxParameter::set_bool(bool in) { - ParamBool * boolpntr = dynamic_cast(this); + ParamBool *boolpntr = dynamic_cast(this); if (boolpntr == nullptr) throw param_not_bool_param(); return boolpntr->set(in); @@ -188,7 +183,7 @@ int InxParameter::set_int(int in) float InxParameter::set_float(float in) { - ParamFloat * floatpntr; + ParamFloat *floatpntr; floatpntr = dynamic_cast(this); if (floatpntr == nullptr) throw param_not_float_param(); @@ -197,7 +192,7 @@ float InxParameter::set_float(float in) const char *InxParameter::set_string(const char *in) { - ParamString * stringpntr = dynamic_cast(this); + ParamString *stringpntr = dynamic_cast(this); if (stringpntr == nullptr) throw param_not_string_param(); return stringpntr->set(in).c_str(); @@ -214,13 +209,12 @@ const char *InxParameter::set_optiongroup(const char *in) unsigned int InxParameter::set_color(unsigned int in) { - ParamColor*param = dynamic_cast(this); + ParamColor *param = dynamic_cast(this); if (param == nullptr) throw param_not_color_param(); return param->set(in); } - InxParameter::InxParameter(Inkscape::XML::Node *in_repr, Inkscape::Extension::Extension *ext) : InxWidget(in_repr, ext) { @@ -246,8 +240,8 @@ InxParameter::InxParameter(Inkscape::XML::Node *in_repr, Inkscape::Extension::Ex _text = g_strdup(gui_text); } if (!_text && !_hidden) { - g_warning("Parameter '%s' in extension '%s' is visible but does not have a 'gui-text'.", - _name, _extension->get_id()); + g_warning("Parameter '%s' in extension '%s' is visible but does not have a 'gui-text'.", _name, + _extension->get_id()); throw param_no_text(); } @@ -284,13 +278,14 @@ Glib::ustring InxParameter::pref_name() const std::string InxParameter::value_to_string() const { // if we end up here we're missing a definition of ::string() in one of the subclasses - g_critical("InxParameter::value_to_string called from parameter '%s' in extension '%s'", _name, _extension->get_id()); + g_critical("InxParameter::value_to_string called from parameter '%s' in extension '%s'", _name, + _extension->get_id()); g_assert_not_reached(); return ""; } -} // namespace Extension -} // namespace Inkscape +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/prefdialog/parameter.h b/src/extension/prefdialog/parameter.h index 7776851dc9492adb240b673b37b7bef9617ac7a0..6cc5b3a14325b4b9a0d4957ed830c21495c0ef3d 100644 --- a/src/extension/prefdialog/parameter.h +++ b/src/extension/prefdialog/parameter.h @@ -16,12 +16,10 @@ #include "widget.h" - namespace Glib { class ustring; } - namespace Inkscape { namespace Extension { @@ -33,10 +31,10 @@ namespace Extension { * around. There is also a few functions that are used by all the * different parameters. */ -class InxParameter : public InxWidget { +class InxParameter : public InxWidget +{ public: - InxParameter(Inkscape::XML::Node *in_repr, - Inkscape::Extension::Extension *ext); + InxParameter(Inkscape::XML::Node *in_repr, Inkscape::Extension::Extension *ext); ~InxParameter() override; @@ -63,7 +61,7 @@ public: bool set_bool(bool in); /** Wrapper to cast to the object and use it's function. */ - int set_int(int in); + int set_int(int in); /** Wrapper to cast to the object and use it's function. */ float set_float(float in); @@ -109,17 +107,31 @@ public: /** Recommended spacing between the widgets making up a single Parameter (e.g. label and input) (in px) */ const static int GUI_PARAM_WIDGETS_SPACING = 4; - /** An error class for when a parameter is called on a type it is not */ - class param_no_name {}; - class param_no_text {}; - class param_not_bool_param {}; - class param_not_color_param {}; - class param_not_float_param {}; - class param_not_int_param {}; - class param_not_optiongroup_param {}; - class param_not_string_param {}; - + class param_no_name + { + }; + class param_no_text + { + }; + class param_not_bool_param + { + }; + class param_not_color_param + { + }; + class param_not_float_param + { + }; + class param_not_int_param + { + }; + class param_not_optiongroup_param + { + }; + class param_not_string_param + { + }; protected: /** The name of this parameter. */ @@ -131,7 +143,6 @@ protected: /** Extended description of the parameter (currently shown as tooltip on hover). */ char *_description = nullptr; - /* **** member functions **** */ /** @@ -145,8 +156,8 @@ protected: Glib::ustring pref_name() const; }; -} // namespace Extension -} // namespace Inkscape +} // namespace Extension +} // namespace Inkscape #endif // SEEN_INK_EXTENSION_PARAM_H__ diff --git a/src/extension/prefdialog/prefdialog.cpp b/src/extension/prefdialog/prefdialog.cpp index a94a6d9c74b4b33178b2377b745b30b09da4164c..1499d53eebe99d9954461783b6128813e43c841f 100644 --- a/src/extension/prefdialog/prefdialog.cpp +++ b/src/extension/prefdialog/prefdialog.cpp @@ -10,29 +10,25 @@ #include "prefdialog.h" +#include #include #include -#include #include "ui/dialog-events.h" #include "xml/repr.h" // Used to get SP_ACTIVE_DESKTOP -#include "inkscape.h" -#include "document.h" #include "document-undo.h" - +#include "document.h" #include "extension/effect.h" #include "extension/execution-env.h" #include "extension/implementation/implementation.h" - +#include "inkscape.h" #include "parameter.h" - namespace Inkscape { namespace Extension { - /** \brief Creates a new preference dialog for extension preferences \param name Name of the Extension whose dialog this is (should already be translated) \param controls The extension specific widgets in the dialog @@ -41,17 +37,17 @@ namespace Extension { in the title. It adds a few buttons and sets up handlers for them. It also places the passed-in widgets into the dialog. */ -PrefDialog::PrefDialog (Glib::ustring name, Gtk::Widget * controls, Effect * effect) : - Gtk::Dialog(name, true), - _name(name), - _button_ok(nullptr), - _button_cancel(nullptr), - _button_preview(nullptr), - _param_preview(nullptr), - _effect(effect), - _exEnv(nullptr) +PrefDialog::PrefDialog(Glib::ustring name, Gtk::Widget *controls, Effect *effect) + : Gtk::Dialog(name, true) + , _name(name) + , _button_ok(nullptr) + , _button_cancel(nullptr) + , _button_preview(nullptr) + , _param_preview(nullptr) + , _effect(effect) + , _exEnv(nullptr) { - this->set_default_size(0,0); // we want the window to be as small as possible instead of clobbering up space + this->set_default_size(0, 0); // we want the window to be as small as possible instead of clobbering up space Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox()); if (controls == nullptr) { @@ -69,13 +65,13 @@ PrefDialog::PrefDialog (Glib::ustring name, Gtk::Widget * controls, Effect * eff this->get_content_area()->pack_start(*hbox, true, true, 0); _button_cancel = add_button(_effect == nullptr ? _("_Cancel") : _("_Close"), Gtk::RESPONSE_CANCEL); - _button_ok = add_button(_effect == nullptr ? _("_OK") : _("_Apply"), Gtk::RESPONSE_OK); + _button_ok = add_button(_effect == nullptr ? _("_OK") : _("_Apply"), Gtk::RESPONSE_OK); set_default_response(Gtk::RESPONSE_OK); _button_ok->grab_focus(); if (_effect != nullptr && !_effect->no_live_preview) { if (_param_preview == nullptr) { - XML::Document * doc = sp_repr_read_mem(live_param_xml, strlen(live_param_xml), nullptr); + XML::Document *doc = sp_repr_read_mem(live_param_xml, strlen(live_param_xml), nullptr); if (doc == nullptr) { std::cout << "Error encountered loading live parameter XML !!!" << std::endl; return; @@ -117,7 +113,7 @@ PrefDialog::PrefDialog (Glib::ustring name, Gtk::Widget * controls, Effect * eff return; } -PrefDialog::~PrefDialog ( ) +PrefDialog::~PrefDialog() { if (_param_preview != nullptr) { delete _param_preview; @@ -138,11 +134,11 @@ PrefDialog::~PrefDialog ( ) return; } -void -PrefDialog::preview_toggle () { +void PrefDialog::preview_toggle() +{ SPDocument *document = SP_ACTIVE_DOCUMENT; bool modified = document->isModifiedSinceSave(); - if(_param_preview->get_bool()) { + if (_param_preview->get_bool()) { if (_exEnv == nullptr) { set_modal(true); _exEnv = new ExecutionEnv(_effect, SP_ACTIVE_DESKTOP, nullptr, false, false); @@ -163,23 +159,22 @@ PrefDialog::preview_toggle () { document->setModifiedSinceSave(modified); } -void -PrefDialog::param_change () { +void PrefDialog::param_change() +{ if (_exEnv != nullptr) { if (!_effect->loaded()) { _effect->set_state(Extension::STATE_LOADED); } _timersig.disconnect(); - _timersig = Glib::signal_timeout().connect(sigc::mem_fun(this, &PrefDialog::param_timer_expire), - 250, /* ms */ + _timersig = Glib::signal_timeout().connect(sigc::mem_fun(this, &PrefDialog::param_timer_expire), 250, /* ms */ Glib::PRIORITY_DEFAULT_IDLE); } return; } -bool -PrefDialog::param_timer_expire () { +bool PrefDialog::param_timer_expire() +{ if (_exEnv != nullptr) { _exEnv->cancel(); _exEnv->undo(); @@ -190,16 +185,16 @@ PrefDialog::param_timer_expire () { return false; } -void -PrefDialog::on_response (int signal) { +void PrefDialog::on_response(int signal) +{ if (signal == Gtk::RESPONSE_OK) { if (_exEnv == nullptr) { - if (_effect != nullptr) { - _effect->effect(SP_ACTIVE_DESKTOP); - } else { - // Shutdown run() - return; - } + if (_effect != nullptr) { + _effect->effect(SP_ACTIVE_DESKTOP); + } else { + // Shutdown run() + return; + } } else { if (_exEnv->wait()) { _exEnv->commit(); @@ -225,9 +220,11 @@ PrefDialog::on_response (int signal) { #include "extension/internal/clear-n_.h" -const char * PrefDialog::live_param_xml = "false"; +const char *PrefDialog::live_param_xml = "false"; -}; }; /* namespace Inkscape, Extension */ +}; // namespace Extension +}; // namespace Inkscape /* Local Variables: diff --git a/src/extension/prefdialog/prefdialog.h b/src/extension/prefdialog/prefdialog.h index 9fe8acda888624b7a6ec1f32e2cdf9e247c1e639..f8fb6c585c4e571f06cf066261f63276891dda02 100644 --- a/src/extension/prefdialog/prefdialog.h +++ b/src/extension/prefdialog/prefdialog.h @@ -11,9 +11,9 @@ #ifndef INKSCAPE_EXTENSION_DIALOG_H__ #define INKSCAPE_EXTENSION_DIALOG_H__ -#include -#include #include +#include +#include namespace Gtk { class CheckButton; @@ -26,7 +26,8 @@ class ExecutionEnv; class InxParameter; /** \brief A class to represent the preferences for an extension */ -class PrefDialog : public Gtk::Dialog { +class PrefDialog : public Gtk::Dialog +{ /** \brief Name of the extension */ Glib::ustring _name; @@ -44,7 +45,7 @@ class PrefDialog : public Gtk::Dialog { InxParameter *_param_preview; /** \brief XML to define the live effects parameter on the dialog */ - static const char * live_param_xml; + static const char *live_param_xml; /** \brief Signal that the user is changing the live effect state */ sigc::signal _signal_preview; @@ -65,17 +66,15 @@ class PrefDialog : public Gtk::Dialog { void preview_toggle(); void param_change(); bool param_timer_expire(); - void on_response (int signal) override; + void on_response(int signal) override; public: - PrefDialog (Glib::ustring name, - Gtk::Widget * controls = nullptr, - Effect * effect = nullptr); - ~PrefDialog () override; + PrefDialog(Glib::ustring name, Gtk::Widget *controls = nullptr, Effect *effect = nullptr); + ~PrefDialog() override; }; - -};}; /* namespace Inkscape, Extension */ +}; // namespace Extension +}; // namespace Inkscape #endif /* INKSCAPE_EXTENSION_DIALOG_H__ */ diff --git a/src/extension/prefdialog/widget-box.cpp b/src/extension/prefdialog/widget-box.cpp index 9fd75e19a9f3933c342ba44e645e686b2f140ca9..4c7244dd790e2d9772ae475dca9475fb9e966821 100644 --- a/src/extension/prefdialog/widget-box.cpp +++ b/src/extension/prefdialog/widget-box.cpp @@ -14,13 +14,12 @@ #include -#include "xml/node.h" #include "extension/extension.h" +#include "xml/node.h" namespace Inkscape { namespace Extension { - WidgetBox::WidgetBox(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext) : InxWidget(xml, ext) { @@ -55,9 +54,9 @@ WidgetBox::WidgetBox(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *e _children.push_back(widget); } } else if (child_repr->type() == XML::ELEMENT_NODE) { - g_warning("Invalid child element ('%s') in box widget in extension '%s'.", - chname, _extension->get_id()); - } else if (child_repr->type() != XML::COMMENT_NODE){ + g_warning("Invalid child element ('%s') in box widget in extension '%s'.", chname, + _extension->get_id()); + } else if (child_repr->type() != XML::COMMENT_NODE) { g_warning("Invalid child element found in box widget in extension '%s'.", _extension->get_id()); } @@ -81,7 +80,7 @@ Gtk::Widget *WidgetBox::get_widget(sigc::signal *changeSignal) Gtk::Box *box = Gtk::manage(new Gtk::Box(orientation)); // box->set_border_width(GUI_BOX_MARGIN); // leave at zero for now, so box is purely for layouting (not grouping) - // revisit this later, possibly implementing GtkFrame or similar + // revisit this later, possibly implementing GtkFrame or similar box->set_spacing(GUI_BOX_SPACING); if (_orientation == HORIZONTAL) { @@ -111,5 +110,5 @@ Gtk::Widget *WidgetBox::get_widget(sigc::signal *changeSignal) return dynamic_cast(box); } -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ diff --git a/src/extension/prefdialog/widget-box.h b/src/extension/prefdialog/widget-box.h index 6fd7b900c0eb295743e93cdfabf96b58e621882f..734b98ab24f765aacd0777afe99cc598349807cd 100644 --- a/src/extension/prefdialog/widget-box.h +++ b/src/extension/prefdialog/widget-box.h @@ -13,38 +13,42 @@ #ifndef SEEN_INK_EXTENSION_WIDGET_BOX_H #define SEEN_INK_EXTENSION_WIDGET_BOX_H -#include "widget.h" - #include +#include "widget.h" + namespace Gtk { - class Widget; +class Widget; } namespace Inkscape { namespace Xml { - class Node; +class Node; } namespace Extension { /** \brief A box widget */ -class WidgetBox : public InxWidget { +class WidgetBox : public InxWidget +{ public: WidgetBox(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); Gtk::Widget *get_widget(sigc::signal *changeSignal) override; + private: - enum Orientation { - HORIZONTAL, VERTICAL + enum Orientation + { + HORIZONTAL, + VERTICAL }; /** Layout orientation of the box (default is vertical) **/ Orientation _orientation = VERTICAL; }; -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* SEEN_INK_EXTENSION_WIDGET_BOX_H */ diff --git a/src/extension/prefdialog/widget-image.cpp b/src/extension/prefdialog/widget-image.cpp index 4f5e11dec20b8aa57a62d32a27bb1686bfdc7e99..4fc5e953ab0ad6c16dae372868a1f7e67e9a5ebd 100644 --- a/src/extension/prefdialog/widget-image.cpp +++ b/src/extension/prefdialog/widget-image.cpp @@ -16,13 +16,12 @@ #include #include -#include "xml/node.h" #include "extension/extension.h" +#include "xml/node.h" namespace Inkscape { namespace Extension { - WidgetImage::WidgetImage(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext) : InxWidget(xml, ext) { @@ -49,8 +48,8 @@ WidgetImage::WidgetImage(Inkscape::XML::Node *xml, Inkscape::Extension::Extensio if (Glib::file_test(image_path, Glib::FILE_TEST_IS_REGULAR)) { _image_path = image_path; } else { - g_warning("Image file ('%s') not found for image widget in extension '%s'.", - image_path.c_str(), _extension->get_id()); + g_warning("Image file ('%s') not found for image widget in extension '%s'.", image_path.c_str(), + _extension->get_id()); } // parse width/height attributes @@ -83,5 +82,5 @@ Gtk::Widget *WidgetImage::get_widget(sigc::signal * /*changeSignal*/) return dynamic_cast(image); } -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ diff --git a/src/extension/prefdialog/widget-image.h b/src/extension/prefdialog/widget-image.h index 95dd4d5d151819304f1e4618cbca5eb323052fe8..2cd88440c6d72837635207e111a734de8d9f132d 100644 --- a/src/extension/prefdialog/widget-image.h +++ b/src/extension/prefdialog/widget-image.h @@ -13,27 +13,29 @@ #ifndef SEEN_INK_EXTENSION_WIDGET_IMAGE_H #define SEEN_INK_EXTENSION_WIDGET_IMAGE_H -#include "widget.h" - #include +#include "widget.h" + namespace Gtk { - class Widget; +class Widget; } namespace Inkscape { namespace Xml { - class Node; +class Node; } namespace Extension { /** \brief A label widget */ -class WidgetImage : public InxWidget { +class WidgetImage : public InxWidget +{ public: WidgetImage(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); Gtk::Widget *get_widget(sigc::signal *changeSignal) override; + private: /** \brief Path to image file (relative paths are relative to the .inx file location). */ std::string _image_path; @@ -44,8 +46,8 @@ private: unsigned int _height = 0; }; -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* SEEN_INK_EXTENSION_WIDGET_IMAGE_H */ diff --git a/src/extension/prefdialog/widget-label.cpp b/src/extension/prefdialog/widget-label.cpp index ec4f558afd4ef3b801a9234f9e56f50d56a14e4b..c731aab03cbc0869cf201f6073920ad5a70c4005 100644 --- a/src/extension/prefdialog/widget-label.cpp +++ b/src/extension/prefdialog/widget-label.cpp @@ -14,24 +14,23 @@ #include "widget-label.h" -#include -#include #include #include +#include +#include -#include "xml/node.h" #include "extension/extension.h" +#include "xml/node.h" namespace Inkscape { namespace Extension { - WidgetLabel::WidgetLabel(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext) : InxWidget(xml, ext) { // construct the text content by concatenating all (non-empty) text nodes, // removing all other nodes (e.g. comment nodes) and replacing elements with "
" - Inkscape::XML::Node * cur_child = xml->firstChild(); + Inkscape::XML::Node *cur_child = xml->firstChild(); while (cur_child != nullptr) { if (cur_child->type() == XML::TEXT_NODE && cur_child->content() != nullptr) { _value += cur_child->content(); @@ -68,8 +67,8 @@ WidgetLabel::WidgetLabel(Inkscape::XML::Node *xml, Inkscape::Extension::Extensio } else if (!strcmp(_appearance, "url")) { _mode = URL; } else { - g_warning("Invalid value ('%s') for appearance of label widget in extension '%s'", - _appearance, _extension->get_id()); + g_warning("Invalid value ('%s') for appearance of label widget in extension '%s'", _appearance, + _extension->get_id()); } } } @@ -117,5 +116,5 @@ Gtk::Widget *WidgetLabel::get_widget(sigc::signal * /*changeSignal*/) return hbox; } -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ diff --git a/src/extension/prefdialog/widget-label.h b/src/extension/prefdialog/widget-label.h index 1c165500680b656d17a385f61834cb2d2b267db9..5f3072526f9deaa860030261e3215523d9eb099b 100644 --- a/src/extension/prefdialog/widget-label.h +++ b/src/extension/prefdialog/widget-label.h @@ -15,31 +15,36 @@ #ifndef SEEN_INK_EXTENSION_WIDGET_LABEL_H #define SEEN_INK_EXTENSION_WIDGET_LABEL_H -#include "widget.h" - #include +#include "widget.h" + namespace Gtk { - class Widget; +class Widget; } namespace Inkscape { namespace Xml { - class Node; +class Node; } namespace Extension { /** \brief A label widget */ -class WidgetLabel : public InxWidget { +class WidgetLabel : public InxWidget +{ public: - enum AppearanceMode { - DEFAULT, HEADER, URL + enum AppearanceMode + { + DEFAULT, + HEADER, + URL }; WidgetLabel(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); Gtk::Widget *get_widget(sigc::signal *changeSignal) override; + private: /** \brief Internal value. */ Glib::ustring _value; @@ -48,8 +53,8 @@ private: AppearanceMode _mode = DEFAULT; }; -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* SEEN_INK_EXTENSION_WIDGET_LABEL_H */ diff --git a/src/extension/prefdialog/widget-separator.cpp b/src/extension/prefdialog/widget-separator.cpp index d78894b6224736bce697b9222173ab807d51404b..470b303b1b47184a009ccef8d171f3581fab6842 100644 --- a/src/extension/prefdialog/widget-separator.cpp +++ b/src/extension/prefdialog/widget-separator.cpp @@ -14,17 +14,15 @@ #include -#include "xml/node.h" #include "extension/extension.h" +#include "xml/node.h" namespace Inkscape { namespace Extension { - WidgetSeparator::WidgetSeparator(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext) : InxWidget(xml, ext) -{ -} +{} /** \brief Create a label for the description */ Gtk::Widget *WidgetSeparator::get_widget(sigc::signal *changeSignal) @@ -39,5 +37,5 @@ Gtk::Widget *WidgetSeparator::get_widget(sigc::signal *changeSignal) return dynamic_cast(separator); } -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ diff --git a/src/extension/prefdialog/widget-separator.h b/src/extension/prefdialog/widget-separator.h index 9533aba61b24a2b6b01ea5d5827fc6aa5d4393f4..d7cb1dcbf37def86fd2adefd60a307ad27d89c55 100644 --- a/src/extension/prefdialog/widget-separator.h +++ b/src/extension/prefdialog/widget-separator.h @@ -13,31 +13,32 @@ #ifndef SEEN_INK_EXTENSION_WIDGET_SEPARATOR_H #define SEEN_INK_EXTENSION_WIDGET_SEPARATOR_H -#include "widget.h" - #include +#include "widget.h" + namespace Gtk { - class Widget; +class Widget; } namespace Inkscape { namespace Xml { - class Node; +class Node; } namespace Extension { /** \brief A separator widget */ -class WidgetSeparator : public InxWidget { +class WidgetSeparator : public InxWidget +{ public: WidgetSeparator(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); Gtk::Widget *get_widget(sigc::signal *changeSignal) override; }; -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* SEEN_INK_EXTENSION_WIDGET_SEPARATOR_H */ diff --git a/src/extension/prefdialog/widget-spacer.cpp b/src/extension/prefdialog/widget-spacer.cpp index 8ffa6ac1efc7db48a0da0c28edcdd8e0dd81a96a..22293d4fa89e3ff9218939639e8320c367a9848f 100644 --- a/src/extension/prefdialog/widget-spacer.cpp +++ b/src/extension/prefdialog/widget-spacer.cpp @@ -14,13 +14,12 @@ #include -#include "xml/node.h" #include "extension/extension.h" +#include "xml/node.h" namespace Inkscape { namespace Extension { - WidgetSpacer::WidgetSpacer(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext) : InxWidget(xml, ext) { @@ -46,7 +45,7 @@ Gtk::Widget *WidgetSpacer::get_widget(sigc::signal *changeSignal) } Gtk::Box *spacer = Gtk::manage(new Gtk::Box()); - spacer->set_border_width(_size/2); + spacer->set_border_width(_size / 2); if (_expand) { spacer->set_hexpand(); @@ -58,5 +57,5 @@ Gtk::Widget *WidgetSpacer::get_widget(sigc::signal *changeSignal) return dynamic_cast(spacer); } -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ diff --git a/src/extension/prefdialog/widget-spacer.h b/src/extension/prefdialog/widget-spacer.h index 467b5f95b3d63bda9e1d13806b62a0ec05e406bc..bf4ad62f578f13d362561dd9645b08f15d78ae65 100644 --- a/src/extension/prefdialog/widget-spacer.h +++ b/src/extension/prefdialog/widget-spacer.h @@ -13,23 +13,24 @@ #ifndef SEEN_INK_EXTENSION_WIDGET_SPACER_H #define SEEN_INK_EXTENSION_WIDGET_SPACER_H -#include "widget.h" - #include +#include "widget.h" + namespace Gtk { - class Widget; +class Widget; } namespace Inkscape { namespace Xml { - class Node; +class Node; } namespace Extension { /** \brief A separator widget */ -class WidgetSpacer : public InxWidget { +class WidgetSpacer : public InxWidget +{ public: WidgetSpacer(Inkscape::XML::Node *xml, Inkscape::Extension::Extension *ext); @@ -43,8 +44,8 @@ private: bool _expand = false; }; -} /* namespace Extension */ -} /* namespace Inkscape */ +} /* namespace Extension */ +} /* namespace Inkscape */ #endif /* SEEN_INK_EXTENSION_WIDGET_SPACER_H */ diff --git a/src/extension/prefdialog/widget.cpp b/src/extension/prefdialog/widget.cpp index 18639c58c41cd09a0ecaf658fcaea5daf5f40bbf..0637dadc0dca8201e7aae2e63fc28c8c90900c69 100644 --- a/src/extension/prefdialog/widget.cpp +++ b/src/extension/prefdialog/widget.cpp @@ -10,24 +10,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "parameter.h" #include "widget.h" -#include "widget-box.h" -#include "widget-image.h" -#include "widget-label.h" -#include "widget-separator.h" -#include "widget-spacer.h" #include #include - #include #include "extension/extension.h" - +#include "parameter.h" +#include "widget-box.h" +#include "widget-image.h" +#include "widget-label.h" +#include "widget-separator.h" +#include "widget-spacer.h" #include "xml/node.h" - namespace Inkscape { namespace Extension { @@ -71,8 +68,8 @@ InxWidget *InxWidget::make(Inkscape::XML::Node *in_repr, Inkscape::Extension::Ex bool InxWidget::is_valid_widget_name(const char *name) { // keep in sync with names supported in InxWidget::make() above - static const std::vector valid_names = - {"hbox", "vbox", "image", "label", "separator", "spacer", "param"}; + static const std::vector valid_names = {"hbox", "vbox", "image", "label", + "separator", "spacer", "param"}; if (std::find(valid_names.begin(), valid_names.end(), name) != valid_names.end()) { return true; @@ -81,7 +78,6 @@ bool InxWidget::is_valid_widget_name(const char *name) } } - InxWidget::InxWidget(Inkscape::XML::Node *in_repr, Inkscape::Extension::Extension *ext) : _extension(ext) { @@ -90,11 +86,11 @@ InxWidget::InxWidget(Inkscape::XML::Node *in_repr, Inkscape::Extension::Extensio if (translatable) { if (!strcmp(translatable, "yes")) { _translatable = YES; - } else if (!strcmp(translatable, "no")) { + } else if (!strcmp(translatable, "no")) { _translatable = NO; } else { - g_warning("Invalid value ('%s') for translatable attribute of widget '%s' in extension '%s'", - translatable, in_repr->name(), _extension->get_id()); + g_warning("Invalid value ('%s') for translatable attribute of widget '%s' in extension '%s'", translatable, + in_repr->name(), _extension->get_id()); } } @@ -141,17 +137,17 @@ InxWidget::~InxWidget() _appearance = nullptr; } -Gtk::Widget * -InxWidget::get_widget(sigc::signal * /*changeSignal*/) +Gtk::Widget *InxWidget::get_widget(sigc::signal * /*changeSignal*/) { // if we end up here we're missing a definition of ::get_widget() in one of the subclasses - g_critical("InxWidget::get_widget called from widget of type '%s' in extension '%s'", - typeid(this).name(), _extension->get_id()); + g_critical("InxWidget::get_widget called from widget of type '%s' in extension '%s'", typeid(this).name(), + _extension->get_id()); g_assert_not_reached(); return nullptr; } -const char *InxWidget::get_translation(const char* msgid) { +const char *InxWidget::get_translation(const char *msgid) +{ return _extension->get_translation(msgid, _context); } @@ -163,8 +159,8 @@ void InxWidget::get_widgets(std::vector &list) } } -} // namespace Extension -} // namespace Inkscape +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/prefdialog/widget.h b/src/extension/prefdialog/widget.h index 843655c6e0ad2632b83ea6c7c29582cba3242d56..c4a6f69145e545d2cc41b07b772ec7c912622a42 100644 --- a/src/extension/prefdialog/widget.h +++ b/src/extension/prefdialog/widget.h @@ -13,11 +13,10 @@ #ifndef SEEN_INK_EXTENSION_WIDGET_H #define SEEN_INK_EXTENSION_WIDGET_H +#include #include #include -#include - namespace Gtk { class Widget; } @@ -31,11 +30,11 @@ namespace Extension { class Extension; - /** * Base class to represent all widgets of an extension (including parameters) */ -class InxWidget { +class InxWidget +{ public: InxWidget(Inkscape::XML::Node *in_repr, Inkscape::Extension::Extension *in_ext); @@ -59,12 +58,12 @@ public: static bool is_valid_widget_name(const char *name); /** Return the instance's GTK::Widget representation for usage in a GUI - * - * @param changeSignal Can be used to subscribe to parameter changes. - * Will be emitted whenever a parameter value changes. - * - * @teturn A Gtk::Widget for the \a InxWidget. \c nullptr if the widget is hidden. - */ + * + * @param changeSignal Can be used to subscribe to parameter changes. + * Will be emitted whenever a parameter value changes. + * + * @teturn A Gtk::Widget for the \a InxWidget. \c nullptr if the widget is hidden. + */ virtual Gtk::Widget *get_widget(sigc::signal *changeSignal); virtual const char *get_tooltip() const { return nullptr; } // tool-tips are exclusive to InxParameters for now @@ -75,7 +74,6 @@ public: /** Indentation level of the widget */ int get_indent() const { return _indent; } - /** * Recursively construct a list containing the current widget and all of it's child widgets (if it has any) * @@ -83,7 +81,6 @@ public: */ virtual void get_widgets(std::vector &list); - /** Recommended margin of boxes containing multiple widgets (in px) */ const static int GUI_BOX_MARGIN = 10; /** Recommended spacing between multiple widgets packed into a box (in px) */ @@ -94,8 +91,11 @@ public: const static int GUI_MAX_LINE_LENGTH = 60; protected: - enum Translatable { - UNSET, YES, NO + enum Translatable + { + UNSET, + YES, + NO }; /** Which extension is this Widget attached to. */ @@ -119,21 +119,20 @@ protected: /** context for translation of translatable strings. */ char *_context = nullptr; - /* **** member functions **** */ /** gets the gettext translation for msgid - * - * Handles translation domain of the extension and message context of the widget internally - * - * @param msgid String to translate - * @return Translated string - */ - const char *get_translation(const char* msgid); + * + * Handles translation domain of the extension and message context of the widget internally + * + * @param msgid String to translate + * @return Translated string + */ + const char *get_translation(const char *msgid); }; -} // namespace Extension -} // namespace Inkscape +} // namespace Extension +} // namespace Inkscape #endif // SEEN_INK_EXTENSION_WIDGET_H diff --git a/src/extension/print.cpp b/src/extension/print.cpp index d9f7406ae7c6e70bbe648bb303a8cfef2193c55f..14bb659113b4a5a76df474e348704b0170959c32 100644 --- a/src/extension/print.cpp +++ b/src/extension/print.cpp @@ -8,115 +8,101 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "implementation/implementation.h" #include "print.h" +#include "implementation/implementation.h" + /* Inkscape::Extension::Print */ namespace Inkscape { namespace Extension { -Print::Print (Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory) +Print::Print(Inkscape::XML::Node *in_repr, Implementation::Implementation *in_imp, std::string *base_directory) : Extension(in_repr, in_imp, base_directory) , base(nullptr) , drawing(nullptr) , root(nullptr) , dkey(0) -{ -} +{} -Print::~Print () -= default; +Print::~Print() = default; -bool -Print::check () +bool Print::check() { return Extension::check(); } -unsigned int -Print::setup () +unsigned int Print::setup() { return imp->setup(this); } -unsigned int -Print::set_preview () +unsigned int Print::set_preview() { return imp->set_preview(this); } -unsigned int -Print::begin (SPDocument *doc) +unsigned int Print::begin(SPDocument *doc) { return imp->begin(this, doc); } -unsigned int -Print::finish () +unsigned int Print::finish() { return imp->finish(this); } -unsigned int -Print::bind (const Geom::Affine &transform, float opacity) +unsigned int Print::bind(const Geom::Affine &transform, float opacity) { - return imp->bind (this, transform, opacity); + return imp->bind(this, transform, opacity); } -unsigned int -Print::release () +unsigned int Print::release() { return imp->release(this); } -unsigned int -Print::comment (char const *comment) +unsigned int Print::comment(char const *comment) { return imp->comment(this, comment); } -unsigned int -Print::fill (Geom::PathVector const &pathv, Geom::Affine const &ctm, SPStyle const *style, - Geom::OptRect const &pbox, Geom::OptRect const &dbox, Geom::OptRect const &bbox) +unsigned int Print::fill(Geom::PathVector const &pathv, Geom::Affine const &ctm, SPStyle const *style, + Geom::OptRect const &pbox, Geom::OptRect const &dbox, Geom::OptRect const &bbox) { - return imp->fill (this, pathv, ctm, style, pbox, dbox, bbox); + return imp->fill(this, pathv, ctm, style, pbox, dbox, bbox); } -unsigned int -Print::stroke (Geom::PathVector const &pathv, Geom::Affine const &ctm, SPStyle const *style, - Geom::OptRect const &pbox, Geom::OptRect const &dbox, Geom::OptRect const &bbox) +unsigned int Print::stroke(Geom::PathVector const &pathv, Geom::Affine const &ctm, SPStyle const *style, + Geom::OptRect const &pbox, Geom::OptRect const &dbox, Geom::OptRect const &bbox) { - return imp->stroke (this, pathv, ctm, style, pbox, dbox, bbox); + return imp->stroke(this, pathv, ctm, style, pbox, dbox, bbox); } -unsigned int -Print::image (unsigned char *px, unsigned int w, unsigned int h, unsigned int rs, - const Geom::Affine &transform, const SPStyle *style) +unsigned int Print::image(unsigned char *px, unsigned int w, unsigned int h, unsigned int rs, + const Geom::Affine &transform, const SPStyle *style) { - return imp->image (this, px, w, h, rs, transform, style); + return imp->image(this, px, w, h, rs, transform, style); } -unsigned int -Print::text (char const *text, Geom::Point const &p, SPStyle const *style) +unsigned int Print::text(char const *text, Geom::Point const &p, SPStyle const *style) { - return imp->text (this, text, p, style); + return imp->text(this, text, p, style); } -bool -Print::textToPath () +bool Print::textToPath() { return imp->textToPath(this); } -//whether embed font in print output (EPS especially) -bool -Print::fontEmbedded () +// whether embed font in print output (EPS especially) +bool Print::fontEmbedded() { return imp->fontEmbedded(this); } -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/print.h b/src/extension/print.h index c4bc267bdd5d210a287c784ca45eff0b207d95b3..db2b89ab72ac56cb3d23f83daae892235d22bbb2 100644 --- a/src/extension/print.h +++ b/src/extension/print.h @@ -16,6 +16,7 @@ #include <2geom/generic-rect.h> #include <2geom/pathvector.h> #include <2geom/point.h> + #include "extension.h" class SPItem; @@ -28,8 +29,8 @@ class DrawingItem; namespace Extension { -class Print : public Extension { - +class Print : public Extension +{ public: /* TODO: These are public for the short term, but this should be fixed */ SPItem *base; Inkscape::Drawing *drawing; @@ -43,43 +44,29 @@ public: bool check() override; /* FALSE means user hit cancel */ - unsigned int setup (); - unsigned int set_preview (); + unsigned int setup(); + unsigned int set_preview(); - unsigned int begin (SPDocument *doc); - unsigned int finish (); + unsigned int begin(SPDocument *doc); + unsigned int finish(); /* Rendering methods */ - unsigned int bind (Geom::Affine const &transform, - float opacity); - unsigned int release (); - unsigned int comment (const char * comment); - unsigned int fill (Geom::PathVector const &pathv, - Geom::Affine const &ctm, - SPStyle const *style, - Geom::OptRect const &pbox, - Geom::OptRect const &dbox, - Geom::OptRect const &bbox); - unsigned int stroke (Geom::PathVector const &pathv, - Geom::Affine const &transform, - SPStyle const *style, - Geom::OptRect const &pbox, - Geom::OptRect const &dbox, - Geom::OptRect const &bbox); - unsigned int image (unsigned char *px, - unsigned int w, - unsigned int h, - unsigned int rs, - Geom::Affine const &transform, - SPStyle const *style); - unsigned int text (char const *text, - Geom::Point const &p, - SPStyle const *style); - bool textToPath (); - bool fontEmbedded (); + unsigned int bind(Geom::Affine const &transform, float opacity); + unsigned int release(); + unsigned int comment(const char *comment); + unsigned int fill(Geom::PathVector const &pathv, Geom::Affine const &ctm, SPStyle const *style, + Geom::OptRect const &pbox, Geom::OptRect const &dbox, Geom::OptRect const &bbox); + unsigned int stroke(Geom::PathVector const &pathv, Geom::Affine const &transform, SPStyle const *style, + Geom::OptRect const &pbox, Geom::OptRect const &dbox, Geom::OptRect const &bbox); + unsigned int image(unsigned char *px, unsigned int w, unsigned int h, unsigned int rs, + Geom::Affine const &transform, SPStyle const *style); + unsigned int text(char const *text, Geom::Point const &p, SPStyle const *style); + bool textToPath(); + bool fontEmbedded(); }; -} } /* namespace Inkscape, Extension */ +} // namespace Extension +} // namespace Inkscape #endif /* INKSCAPE_EXTENSION_PRINT_H__ */ /* diff --git a/src/extension/system.cpp b/src/extension/system.cpp index 08de0b47a879d9c8b93890421e334d9b7d741188..00b0c823c2e6d0876e0aeaa1e4c2852086cad03e 100644 --- a/src/extension/system.cpp +++ b/src/extension/system.cpp @@ -17,26 +17,26 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/interface.h" - #include "system.h" -#include "preferences.h" -#include "extension.h" + +#include + #include "db.h" -#include "input.h" -#include "output.h" +#include "document-undo.h" #include "effect.h" -#include "patheffect.h" -#include "print.h" +#include "extension.h" #include "implementation/script.h" #include "implementation/xslt.h" -#include "xml/rebase-hrefs.h" -#include "io/sys.h" #include "inkscape.h" -#include "document-undo.h" +#include "input.h" +#include "io/sys.h" #include "loader.h" - -#include +#include "output.h" +#include "patheffect.h" +#include "preferences.h" +#include "print.h" +#include "ui/interface.h" +#include "xml/rebase-hrefs.h" namespace Inkscape { namespace Extension { @@ -72,7 +72,7 @@ SPDocument *open(Extension *key, gchar const *filename) gpointer parray[2]; parray[0] = (gpointer)filename; parray[1] = (gpointer)&imod; - db.foreach(open_internal, (gpointer)&parray); + db.foreach (open_internal, (gpointer)&parray); } else { imod = dynamic_cast(key); } @@ -88,7 +88,7 @@ SPDocument *open(Extension *key, gchar const *filename) } // Hide pixbuf extensions depending on user preferences. - //g_warning("Extension: %s", imod->get_id()); + // g_warning("Extension: %s", imod->get_id()); bool show = true; if (strlen(imod->get_id()) > 21) { @@ -104,9 +104,9 @@ SPDocument *open(Extension *key, gchar const *filename) show = false; imod->set_gui(false); } - } else if(strlen(imod->get_id()) > 27) { + } else if (strlen(imod->get_id()) > 27) { id = Glib::ustring(imod->get_id(), 28); - if (!ask && id.compare( "org.inkscape.input.gdkpixbuf") == 0) { + if (!ask && id.compare("org.inkscape.input.gdkpixbuf") == 0) { show = false; imod->set_gui(false); } @@ -129,7 +129,7 @@ SPDocument *open(Extension *key, gchar const *filename) } if (last_chance_svg) { - if ( INKSCAPE.use_gui() ) { + if (INKSCAPE.use_gui()) { sp_ui_error_dialog(_("Format autodetect failed. The file is being opened as SVG.")); } else { g_warning("%s", _("Format autodetect failed. The file is being opened as SVG.")); @@ -163,8 +163,7 @@ SPDocument *open(Extension *key, gchar const *filename) * of the filename (for the length of the extension), and the extension itself. If this passes * then the pointer passed in is set to the current module. */ -static void -open_internal(Extension *in_plug, gpointer in_data) +static void open_internal(Extension *in_plug, gpointer in_data) { if (!in_plug->deactivated() && dynamic_cast(in_plug)) { gpointer *parray = (gpointer *)in_data; @@ -214,9 +213,8 @@ open_internal(Extension *in_plug, gpointer in_data) * * Lastly, the save function is called in the module itself. */ -void -save(Extension *key, SPDocument *doc, gchar const *filename, bool setextension, bool check_overwrite, bool official, - Inkscape::Extension::FileSaveMethod save_method) +void save(Extension *key, SPDocument *doc, gchar const *filename, bool setextension, bool check_overwrite, + bool official, Inkscape::Extension::FileSaveMethod save_method) { Output *omod; if (key == nullptr) { @@ -224,7 +222,7 @@ save(Extension *key, SPDocument *doc, gchar const *filename, bool setextension, parray[0] = (gpointer)filename; parray[1] = (gpointer)&omod; omod = nullptr; - db.foreach(save_internal, (gpointer)&parray); + db.foreach (save_internal, (gpointer)&parray); /* This is a nasty hack, but it is required to ensure that autodetect will always save with the Inkscape extensions @@ -234,7 +232,8 @@ save(Extension *key, SPDocument *doc, gchar const *filename, bool setextension, } /* If autodetect fails, save as Inkscape SVG */ if (omod == nullptr) { - // omod = dynamic_cast(db.get(SP_MODULE_KEY_OUTPUT_SVG_INKSCAPE)); use exception and let user choose + // omod = dynamic_cast(db.get(SP_MODULE_KEY_OUTPUT_SVG_INKSCAPE)); use exception and let user + // choose } } else { omod = dynamic_cast(key); @@ -285,7 +284,6 @@ save(Extension *key, SPDocument *doc, gchar const *filename, bool setextension, Inkscape::XML::Node *repr = doc->getReprRoot(); - // remember attributes in case this is an unofficial save and/or overwrite fails gchar *saved_uri = g_strdup(doc->getDocumentURI()); gchar *saved_output_extension = nullptr; @@ -303,7 +301,7 @@ save(Extension *key, SPDocument *doc, gchar const *filename, bool setextension, { DocumentUndo::ScopedInsensitive _no_undo(doc); // also save the extension for next use - store_file_extension_in_prefs (omod->get_id(), save_method); + store_file_extension_in_prefs(omod->get_id(), save_method); // set the "dataloss" attribute if the chosen extension is lossy repr->removeAttribute("inkscape:dataloss"); if (omod->causes_dataloss()) { @@ -315,13 +313,12 @@ save(Extension *key, SPDocument *doc, gchar const *filename, bool setextension, try { omod->save(doc, fileName); - } - catch(...) { + } catch (...) { // revert attributes in case of official and overwrite - if(check_overwrite && official) { + if (check_overwrite && official) { { DocumentUndo::ScopedInsensitive _no_undo(doc); - store_file_extension_in_prefs (saved_output_extension, save_method); + store_file_extension_in_prefs(saved_output_extension, save_method); repr->setAttribute("inkscape:dataloss", saved_dataloss); } doc->changeUriAndHrefs(saved_uri); @@ -338,10 +335,10 @@ save(Extension *key, SPDocument *doc, gchar const *filename, bool setextension, } // If it is an unofficial save, set the modified attributes back to what they were. - if ( !official) { + if (!official) { { DocumentUndo::ScopedInsensitive _no_undo(doc); - store_file_extension_in_prefs (saved_output_extension, save_method); + store_file_extension_in_prefs(saved_output_extension, save_method); repr->setAttribute("inkscape:dataloss", saved_dataloss); } doc->setModifiedSinceSave(saved_modified); @@ -373,8 +370,7 @@ save(Extension *key, SPDocument *doc, gchar const *filename, bool setextension, * of the filename (for the length of the extension), and the extension itself. If this passes * then the pointer passed in is set to the current module. */ -static void -save_internal(Extension *in_plug, gpointer in_data) +static void save_internal(Extension *in_plug, gpointer in_data) { if (!in_plug->deactivated() && dynamic_cast(in_plug)) { gpointer *parray = (gpointer *)in_data; @@ -401,8 +397,7 @@ save_internal(Extension *in_plug, gpointer in_data) return; } -Print * -get_print(gchar const *key) +Print *get_print(gchar const *key) { return dynamic_cast(db.get(key)); } @@ -424,16 +419,17 @@ get_print(gchar const *key) * get the load and unload functions. If there is no implementation then these are not set. This * case could apply to modules that are built in (like the SVG load/save functions). */ -bool -build_from_reprdoc(Inkscape::XML::Document *doc, Implementation::Implementation *in_imp, std::string* baseDir) +bool build_from_reprdoc(Inkscape::XML::Document *doc, Implementation::Implementation *in_imp, std::string *baseDir) { - enum { + enum + { MODULE_EXTENSION, MODULE_XSLT, MODULE_PLUGIN, MODULE_UNKNOWN_IMP } module_implementation_type = MODULE_UNKNOWN_IMP; - enum { + enum + { MODULE_INPUT, MODULE_OUTPUT, MODULE_FILTER, @@ -447,7 +443,10 @@ build_from_reprdoc(Inkscape::XML::Document *doc, Implementation::Implementation Inkscape::XML::Node *repr = doc->root(); if (strcmp(repr->name(), INKSCAPE_EXTENSION_NS "inkscape-extension")) { - g_warning("Extension definition started with <%s> instead of <" INKSCAPE_EXTENSION_NS "inkscape-extension>. Extension will not be created. See http://wiki.inkscape.org/wiki/index.php/Extensions for reference.\n", repr->name()); + g_warning("Extension definition started with <%s> instead of <" INKSCAPE_EXTENSION_NS + "inkscape-extension>. Extension will not be created. See " + "http://wiki.inkscape.org/wiki/index.php/Extensions for reference.\n", + repr->name()); return false; } @@ -469,13 +468,13 @@ build_from_reprdoc(Inkscape::XML::Document *doc, Implementation::Implementation module_implementation_type = MODULE_EXTENSION; } else if (!strcmp(element_name, INKSCAPE_EXTENSION_NS "xslt")) { module_implementation_type = MODULE_XSLT; - } else if (!strcmp(element_name, INKSCAPE_EXTENSION_NS "plugin")) { + } else if (!strcmp(element_name, INKSCAPE_EXTENSION_NS "plugin")) { module_implementation_type = MODULE_PLUGIN; } - //Inkscape::XML::Node *old_repr = child_repr; + // Inkscape::XML::Node *old_repr = child_repr; child_repr = child_repr->next(); - //Inkscape::GC::release(old_repr); + // Inkscape::GC::release(old_repr); } Implementation::Implementation *imp; @@ -493,8 +492,8 @@ build_from_reprdoc(Inkscape::XML::Document *doc, Implementation::Implementation } case MODULE_PLUGIN: { Inkscape::Extension::Loader loader = Inkscape::Extension::Loader(); - if( baseDir != nullptr){ - loader.set_base_directory ( *baseDir ); + if (baseDir != nullptr) { + loader.set_base_directory(*baseDir); } imp = loader.load_implementation(doc); break; @@ -537,11 +536,11 @@ build_from_reprdoc(Inkscape::XML::Document *doc, Implementation::Implementation break; } } - } catch (const Extension::extension_no_id& e) { + } catch (const Extension::extension_no_id &e) { g_warning("Building extension failed. Extension does not have a valid ID"); - } catch (const Extension::extension_no_name& e) { + } catch (const Extension::extension_no_name &e) { g_warning("Building extension failed. Extension does not have a valid name"); - } catch (const Extension::extension_not_compatible& e) { + } catch (const Extension::extension_not_compatible &e) { return true; // This is not an actual error; just silently ignore the extension } @@ -559,8 +558,7 @@ build_from_reprdoc(Inkscape::XML::Document *doc, Implementation::Implementation * * This function calls build_from_reprdoc with using sp_repr_read_file to create the reprdoc. */ -void -build_from_file(gchar const *filename) +void build_from_file(gchar const *filename) { std::string dir = Glib::path_get_dirname(filename); @@ -585,8 +583,7 @@ build_from_file(gchar const *filename) * This function calls build_from_reprdoc with using sp_repr_read_mem to create the reprdoc. It * finds the length of the buffer using strlen. */ -void -build_from_mem(gchar const *buffer, Implementation::Implementation *in_imp) +void build_from_mem(gchar const *buffer, Implementation::Implementation *in_imp) { Inkscape::XML::Document *doc = sp_repr_read_mem(buffer, strlen(buffer), INKSCAPE_EXTENSION_URI); if (!doc) { @@ -605,8 +602,8 @@ build_from_mem(gchar const *buffer, Implementation::Implementation *in_imp) * TODO: Is it guaranteed that the returned extension is valid? If so, we can remove the check for * filename_extension in sp_file_save_dialog(). */ -Glib::ustring -get_file_save_extension (Inkscape::Extension::FileSaveMethod method) { +Glib::ustring get_file_save_extension(Inkscape::Extension::FileSaveMethod method) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring extension; switch (method) { @@ -625,21 +622,20 @@ get_file_save_extension (Inkscape::Extension::FileSaveMethod method) { break; } - if(extension.empty()) { + if (extension.empty()) { extension = SP_MODULE_KEY_OUTPUT_SVG_INKSCAPE; } return extension; } -Glib::ustring -get_file_save_path (SPDocument *doc, FileSaveMethod method) { +Glib::ustring get_file_save_path(SPDocument *doc, FileSaveMethod method) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring path; bool use_current_dir = true; switch (method) { - case FILE_SAVE_METHOD_SAVE_AS: - { + case FILE_SAVE_METHOD_SAVE_AS: { use_current_dir = prefs->getBool("/dialogs/save_as/use_current_dir", true); if (doc->getDocumentURI() && use_current_dir) { path = Glib::path_get_dirname(doc->getDocumentURI()); @@ -652,7 +648,8 @@ get_file_save_path (SPDocument *doc, FileSaveMethod method) { path = prefs->getString("/dialogs/save_as/path"); break; case FILE_SAVE_METHOD_SAVE_COPY: - use_current_dir = prefs->getBool("/dialogs/save_copy/use_current_dir", prefs->getBool("/dialogs/save_as/use_current_dir", true)); + use_current_dir = prefs->getBool("/dialogs/save_copy/use_current_dir", + prefs->getBool("/dialogs/save_as/use_current_dir", true)); if (doc->getDocumentURI() && use_current_dir) { path = Glib::path_get_dirname(doc->getDocumentURI()); } else { @@ -674,7 +671,7 @@ get_file_save_path (SPDocument *doc, FileSaveMethod method) { break; } - if(path.empty()) { + if (path.empty()) { path = g_get_home_dir(); // Is this the most sensible solution? Note that we should avoid // g_get_current_dir because this leads to problems on OS X where // Inkscape opens the dialog inside application bundle when it is @@ -684,8 +681,8 @@ get_file_save_path (SPDocument *doc, FileSaveMethod method) { return path; } -void -store_file_extension_in_prefs (Glib::ustring extension, FileSaveMethod method) { +void store_file_extension_in_prefs(Glib::ustring extension, FileSaveMethod method) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); switch (method) { case FILE_SAVE_METHOD_SAVE_AS: @@ -702,8 +699,8 @@ store_file_extension_in_prefs (Glib::ustring extension, FileSaveMethod method) { } } -void -store_save_path_in_prefs (Glib::ustring path, FileSaveMethod method) { +void store_save_path_in_prefs(Glib::ustring path, FileSaveMethod method) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); switch (method) { case FILE_SAVE_METHOD_SAVE_AS: @@ -720,7 +717,8 @@ store_save_path_in_prefs (Glib::ustring path, FileSaveMethod method) { } } -} } /* namespace Inkscape::Extension */ +} // namespace Extension +} // namespace Inkscape /* Local Variables: diff --git a/src/extension/system.h b/src/extension/system.h index ea70a0f4f1e2371dfcedf001239f56e03f133940..84b87047dba6efe0216f314515b6508321f85f46 100644 --- a/src/extension/system.h +++ b/src/extension/system.h @@ -34,7 +34,8 @@ class Implementation; * Used to distinguish between the various invocations of the save dialogs (and thus to determine * the file type and save path offered in the dialog) */ -enum FileSaveMethod { +enum FileSaveMethod +{ FILE_SAVE_METHOD_SAVE_AS, FILE_SAVE_METHOD_SAVE_COPY, FILE_SAVE_METHOD_EXPORT, @@ -46,9 +47,8 @@ enum FileSaveMethod { }; SPDocument *open(Extension *key, gchar const *filename); -void save(Extension *key, SPDocument *doc, gchar const *filename, - bool setextension, bool check_overwrite, bool official, - Inkscape::Extension::FileSaveMethod save_method); +void save(Extension *key, SPDocument *doc, gchar const *filename, bool setextension, bool check_overwrite, + bool official, Inkscape::Extension::FileSaveMethod save_method); Print *get_print(gchar const *key); void build_from_file(gchar const *filename); void build_from_mem(gchar const *buffer, Implementation::Implementation *in_imp); @@ -60,7 +60,7 @@ void build_from_mem(gchar const *buffer, Implementation::Implementation *in_imp) * @param method the file save method of the dialog * @return the corresponding default file extension */ -Glib::ustring get_file_save_extension (FileSaveMethod method); +Glib::ustring get_file_save_extension(FileSaveMethod method); /** * Determine the desired default save path depending on the given FileSaveMethod. @@ -70,7 +70,7 @@ Glib::ustring get_file_save_extension (FileSaveMethod method); * @param doc the file's document * @return the corresponding default save path */ -Glib::ustring get_file_save_path (SPDocument *doc, FileSaveMethod method); +Glib::ustring get_file_save_path(SPDocument *doc, FileSaveMethod method); /** * Write the given file extension back to prefs so that it can be used later on. @@ -78,7 +78,7 @@ Glib::ustring get_file_save_path (SPDocument *doc, FileSaveMethod method); * @param extension the file extension which should be written to prefs * @param method the file save method of the dialog */ -void store_file_extension_in_prefs (Glib::ustring extension, FileSaveMethod method); +void store_file_extension_in_prefs(Glib::ustring extension, FileSaveMethod method); /** * Write the given path back to prefs so that it can be used later on. @@ -86,9 +86,10 @@ void store_file_extension_in_prefs (Glib::ustring extension, FileSaveMethod meth * @param path the path which should be written to prefs * @param method the file save method of the dialog */ -void store_save_path_in_prefs (Glib::ustring path, FileSaveMethod method); +void store_save_path_in_prefs(Glib::ustring path, FileSaveMethod method); -} } /* namespace Inkscape::Extension */ +} // namespace Extension +} // namespace Inkscape #endif /* INKSCAPE_EXTENSION_SYSTEM_H__ */ diff --git a/src/extension/timer.cpp b/src/extension/timer.cpp index 4533b0d85b0713e14ef840f58d61bee348f28097..68dd25dcdb1dd6147b040dbf8937bb4d9931f6b6 100644 --- a/src/extension/timer.cpp +++ b/src/extension/timer.cpp @@ -11,18 +11,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "timer.h" + #include #include "extension.h" -#include "timer.h" namespace Inkscape { namespace Extension { -#define TIMER_SCALE_VALUE 20 +#define TIMER_SCALE_VALUE 20 -ExpirationTimer * ExpirationTimer::timer_list = nullptr; -ExpirationTimer * ExpirationTimer::idle_start = nullptr; +ExpirationTimer *ExpirationTimer::timer_list = nullptr; +ExpirationTimer *ExpirationTimer::idle_start = nullptr; long ExpirationTimer::timeout = 240; bool ExpirationTimer::timer_started = false; @@ -34,9 +35,9 @@ bool ExpirationTimer::timer_started = false; the first timer extension, the timer is kicked off. This function also sets up the circularly linked list of all the timers. */ -ExpirationTimer::ExpirationTimer (Extension * in_extension): - locked(0), - extension(in_extension) +ExpirationTimer::ExpirationTimer(Extension *in_extension) + : locked(0) + , extension(in_extension) { /* Fix Me! */ if (timer_list == nullptr) { @@ -48,7 +49,7 @@ ExpirationTimer::ExpirationTimer (Extension * in_extension): } expiration = Glib::DateTime::create_now_utc().add_seconds(timeout); - + if (!timer_started) { Glib::signal_timeout().connect(sigc::ptr_fun(&timer_func), timeout * 1000 / TIMER_SCALE_VALUE); timer_started = true; @@ -58,7 +59,7 @@ ExpirationTimer::ExpirationTimer (Extension * in_extension): } /** \brief Deletes a \c ExpirationTimer - + The most complex thing that this function does is remove the timer from the circularly linked list. If this is the only entry in the list that is easy, otherwise all the entries must be found, and this @@ -69,10 +70,9 @@ ExpirationTimer::~ExpirationTimer() if (this != next) { /* This will remove this entry from the circularly linked list. */ - ExpirationTimer * prev; - for (prev = timer_list; - prev->next != this; - prev = prev->next){}; + ExpirationTimer *prev; + for (prev = timer_list; prev->next != this; prev = prev->next) { + }; prev->next = next; if (idle_start == this) @@ -102,13 +102,13 @@ ExpirationTimer::~ExpirationTimer() Extensions that are only used once will expire at a standard rate set by \c timeout. */ -void -ExpirationTimer::touch () +void ExpirationTimer::touch() { auto const current = Glib::DateTime::create_now_utc(); auto time_left = expiration.difference(current); - if (time_left < 0) time_left = 0; + if (time_left < 0) + time_left = 0; time_left /= 2; expiration = current.add(time_left).add_seconds(timeout); @@ -119,10 +119,10 @@ ExpirationTimer::touch () Checks the time against the current time. */ -bool -ExpirationTimer::expired () const +bool ExpirationTimer::expired() const { - if (locked > 0) return false; + if (locked > 0) + return false; auto const current = Glib::DateTime::create_now_utc(); return expiration.difference(current) < 0; @@ -142,9 +142,8 @@ ExpirationTimer::expired () const a timer is added. If there is entries left, but the next one is where this function started, then the timer is set up. The timer will then re-add the idle loop function when it runs. -*/ -bool -ExpirationTimer::idle_func () +*/ +bool ExpirationTimer::idle_func() { // std::cout << "Idle func pass: " << idle_cnt++ << " timer list: " << timer_list << std::endl; @@ -187,8 +186,7 @@ ExpirationTimer::idle_func () This function sets up the idle loop when it runs. The idle loop is the one that unloads all the extensions. */ -bool -ExpirationTimer::timer_func () +bool ExpirationTimer::timer_func() { // std::cout << "Timer func" << std::endl; idle_start = timer_list; @@ -197,7 +195,8 @@ ExpirationTimer::timer_func () return false; } -}; }; /* namespace Inkscape, Extension */ +}; // namespace Extension +}; // namespace Inkscape /* Local Variables: diff --git a/src/extension/timer.h b/src/extension/timer.h index ce9c495571e9c61c8e54dbdde1b9a0ef8bb3c27c..1d150fdd400d8b84db404497686b406fa43acdb2 100644 --- a/src/extension/timer.h +++ b/src/extension/timer.h @@ -15,19 +15,20 @@ #define INKSCAPE_EXTENSION_TIMER_H__ #include -#include #include +#include namespace Inkscape { namespace Extension { class Extension; -class ExpirationTimer { +class ExpirationTimer +{ /** \brief Circularly linked list of all timers */ - static ExpirationTimer * timer_list; + static ExpirationTimer *timer_list; /** \brief Which timer was on top when we started the idle loop */ - static ExpirationTimer * idle_start; + static ExpirationTimer *idle_start; /** \brief What the current timeout is (in seconds) */ static long timeout; /** \brief Has the timer been started? */ @@ -36,30 +37,31 @@ class ExpirationTimer { /** \brief Is this extension locked from being unloaded? */ int locked; /** \brief Next entry in the list */ - ExpirationTimer * next; + ExpirationTimer *next; /** \brief When this timer expires */ Glib::DateTime expiration; /** \brief What extension this function relates to */ - Extension * extension; + Extension *extension; bool expired() const; - static bool idle_func (); - static bool timer_func (); + static bool idle_func(); + static bool timer_func(); public: - ExpirationTimer(Extension * in_extension); + ExpirationTimer(Extension *in_extension); virtual ~ExpirationTimer(); - void touch (); - void lock () { locked++; }; - void unlock () { locked--; }; + void touch(); + void lock() { locked++; }; + void unlock() { locked--; }; /** \brief Set the timeout variable */ - static void set_timeout (long in_seconds) { timeout = in_seconds; }; + static void set_timeout(long in_seconds) { timeout = in_seconds; }; }; -}; }; /* namespace Inkscape, Extension */ +}; // namespace Extension +}; // namespace Inkscape #endif /* INKSCAPE_EXTENSION_TIMER_H__ */ diff --git a/src/extract-uri.cpp b/src/extract-uri.cpp index 65401df6e0d0febaec85ef4145611fc0905c90b1..8a4974f6dc422f14f5dbef8dbcf60c2c6c503685 100644 --- a/src/extract-uri.cpp +++ b/src/extract-uri.cpp @@ -7,11 +7,11 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "extract-uri.h" + #include #include -#include "extract-uri.h" - // FIXME: kill this ugliness when we have a proper CSS parser // Functions as per 4.3.4 of CSS 2.1 @@ -24,34 +24,30 @@ std::string extract_uri(char const *s, char const **endptr) return result; gchar const *sb = s; - if ( strlen(sb) < 4 || strncmp(sb, "url", 3) != 0 ) { + if (strlen(sb) < 4 || strncmp(sb, "url", 3) != 0) { return result; } sb += 3; - if ( endptr ) { + if (endptr) { *endptr = nullptr; } // This first whitespace technically is not allowed. // Just left in for now for legacy behavior. - while ( ( *sb == ' ' ) || - ( *sb == '\t' ) ) - { + while ((*sb == ' ') || (*sb == '\t')) { sb++; } - if ( *sb == '(' ) { + if (*sb == '(') { sb++; - while ( ( *sb == ' ' ) || - ( *sb == '\t' ) ) - { + while ((*sb == ' ') || (*sb == '\t')) { sb++; } gchar delim = ')'; - if ( (*sb == '\'' || *sb == '"') ) { + if ((*sb == '\'' || *sb == '"')) { delim = *sb; sb++; } @@ -60,34 +56,31 @@ std::string extract_uri(char const *s, char const **endptr) return result; } - gchar const* se = sb; - while ( *se && (*se != delim) ) { + gchar const *se = sb; + while (*se && (*se != delim)) { se++; } // we found the delimiter - if ( *se ) { - if ( delim == ')' ) { - if ( endptr ) { + if (*se) { + if (delim == ')') { + if (endptr) { *endptr = se + 1; } // back up for any trailing whitespace - while (se > sb && g_ascii_isspace(se[-1])) - { + while (se > sb && g_ascii_isspace(se[-1])) { se--; } result = std::string(sb, se); } else { - gchar const* tail = se + 1; - while ( ( *tail == ' ' ) || - ( *tail == '\t' ) ) - { + gchar const *tail = se + 1; + while ((*tail == ' ') || (*tail == '\t')) { tail++; } - if ( *tail == ')' ) { - if ( endptr ) { + if (*tail == ')') { + if (endptr) { *endptr = tail + 1; } result = std::string(sb, se); diff --git a/src/extract-uri.h b/src/extract-uri.h index ee773f4585df1ec9454d23e10d38cab942f7b22a..dece3ef052ee444fb5cda3e2f7ef05dd0b9ef7d6 100644 --- a/src/extract-uri.h +++ b/src/extract-uri.h @@ -36,7 +36,6 @@ */ std::string extract_uri(char const *s, char const **endptr = nullptr); - #endif /* !SEEN_EXTRACT_URI_H */ /* diff --git a/src/file-update.cpp b/src/file-update.cpp index 81b5f473d67990dd9c622cef846f80badaff7f7a..5af58941cc370728731d02dfd7b3f6c3dadb61f4 100644 --- a/src/file-update.cpp +++ b/src/file-update.cpp @@ -18,36 +18,25 @@ * su_v */ #include +#include #include #include -#include - #include "desktop.h" +#include "display/canvas-grid.h" #include "document-undo.h" #include "document.h" -#include "file.h" -#include "inkscape.h" -#include "message-stack.h" -#include "message.h" -#include "preferences.h" -#include "print.h" -#include "proj_pt.h" -#include "selection-chemistry.h" -#include "text-editing.h" -#include "verbs.h" - -#include "display/canvas-grid.h" - -#include "extension/effect.h" #include "extension/db.h" +#include "extension/effect.h" #include "extension/input.h" #include "extension/output.h" #include "extension/system.h" - +#include "file.h" +#include "inkscape.h" #include "io/dir-util.h" #include "io/sys.h" - +#include "message-stack.h" +#include "message.h" #include "object/persp3d.h" #include "object/sp-defs.h" #include "object/sp-flowdiv.h" @@ -59,11 +48,15 @@ #include "object/sp-root.h" #include "object/sp-text.h" #include "object/sp-tspan.h" +#include "preferences.h" +#include "print.h" +#include "proj_pt.h" +#include "selection-chemistry.h" #include "style.h" - +#include "text-editing.h" #include "ui/shape-editor.h" +#include "verbs.h" - using Inkscape::DocumentUndo; int sp_file_convert_dpi_method_commandline = -1; // Unset @@ -75,7 +68,6 @@ bool is_line(SPObject *i) return !strcmp(i->getAttribute("sodipodi:role"), "line"); } - void fix_blank_line(SPObject *o) { if (SP_IS_TEXT(o)) @@ -91,8 +83,11 @@ void fix_blank_line(SPObject *o) SPObject *i = *ci; if ((SP_IS_TSPAN(i) && is_line(i)) || SP_IS_FLOWPARA(i) || SP_IS_FLOWDIV(i)) { if (sp_text_get_length((SPItem *)i) <= 1) { // empty line - Inkscape::Text::Layout::iterator pos = te_get_layout((SPItem*)(o))->charIndexToIterator( - ((SP_IS_FLOWPARA(i) || SP_IS_FLOWDIV(i))?0:((ci==cl.begin())?0:1)) + sp_text_get_length_upto(o,i) ); + Inkscape::Text::Layout::iterator pos = + te_get_layout((SPItem *)(o)) + ->charIndexToIterator( + ((SP_IS_FLOWPARA(i) || SP_IS_FLOWDIV(i)) ? 0 : ((ci == cl.begin()) ? 0 : 1)) + + sp_text_get_length_upto(o, i)); sp_te_insert((SPItem *)o, pos, "\u00a0"); //"\u00a0" gchar *l = g_strdup_printf("%f", lineheight.value); gchar *f = g_strdup_printf("%f", fontsize.value); @@ -149,7 +144,6 @@ void fix_font_name(SPObject *o) o->style->font_family.read("monospace"); } - void fix_font_size(SPObject *o) { SPIFontSize fontsize = o->style->font_size; @@ -171,17 +165,15 @@ void fix_font_size(SPObject *o) o->style->font_size.clear(); } - void fix_osb(SPObject *i) { - if (auto a = i->getAttribute("osb:paint") ){ + if (auto a = i->getAttribute("osb:paint")) { i->setAttribute("inkscape:swatch", a); i->setAttribute("osb:paint", nullptr); i->updateRepr(); } } - // helper function void sp_file_text_run_recursive(void (*f)(SPObject *), SPObject *o) { @@ -194,7 +186,8 @@ void sp_file_text_run_recursive(void (*f)(SPObject *), SPObject *o) } } -void fix_update(SPObject *o) { +void fix_update(SPObject *o) +{ o->style->write(); o->updateRepr(); } @@ -202,7 +195,7 @@ void fix_update(SPObject *o) { void sp_file_convert_text_baseline_spacing(SPDocument *doc) { char *oldlocale = g_strdup(setlocale(LC_NUMERIC, nullptr)); - setlocale(LC_NUMERIC,"C"); + setlocale(LC_NUMERIC, "C"); sp_file_text_run_recursive(fix_blank_line, doc->getRoot()); sp_file_text_run_recursive(fix_line_spacing, doc->getRoot()); sp_file_text_run_recursive(fix_font_size, doc->getRoot()); @@ -220,7 +213,6 @@ void sp_file_fix_osb(SPObject *o) sp_file_fix_osb(ci); } - /** * Implements a fix for https://gitlab.com/inkscape/inkscape/-/issues/45 * Line spacing for empty lines was handled differently before 1.0 @@ -257,30 +249,25 @@ void _fix_pre_v1_empty_lines(SPObject *o) } } - - void sp_file_fix_empty_lines(SPDocument *doc) { sp_file_text_run_recursive(_fix_pre_v1_empty_lines, doc->getRoot()); sp_file_text_run_recursive(fix_update, doc->getRoot()); } - - void sp_file_convert_font_name(SPDocument *doc) { sp_file_text_run_recursive(fix_font_name, doc->getRoot()); sp_file_text_run_recursive(fix_update, doc->getRoot()); } - // Quick and dirty internal backup function -bool sp_file_save_backup( Glib::ustring uri ) { - +bool sp_file_save_backup(Glib::ustring uri) +{ Glib::ustring out = uri; - out.insert(out.find(".svg"),"_backup"); + out.insert(out.find(".svg"), "_backup"); - FILE *filein = Inkscape::IO::fopen_utf8name(uri.c_str(), "rb"); + FILE *filein = Inkscape::IO::fopen_utf8name(uri.c_str(), "rb"); if (!filein) { std::cerr << "sp_file_save_backup: failed to open: " << uri << std::endl; return false; @@ -289,7 +276,7 @@ bool sp_file_save_backup( Glib::ustring uri ) { FILE *fileout = Inkscape::IO::fopen_utf8name(out.c_str(), "wb"); if (!fileout) { std::cerr << "sp_file_save_backup: failed to open: " << out << std::endl; - fclose( filein ); + fclose(filein); return false; } @@ -311,7 +298,6 @@ bool sp_file_save_backup( Glib::ustring uri ) { return return_value; } - void sp_file_convert_dpi(SPDocument *doc) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -320,18 +306,18 @@ void sp_file_convert_dpi(SPDocument *doc) // See if we need to offer the user a fix for the 90->96 px per inch change. // std::cout << "SPFileOpen:" << std::endl; // std::cout << " Version: " << sp_version_to_string(root->version.inkscape) << std::endl; - // std::cout << " SVG file from old Inkscape version detected: " - // << sp_version_to_string(root->version.inkscape) << std::endl; - static const double ratio = 90.0/96.0; + // std::cout << " SVG file from old Inkscape version detected: " + // << sp_version_to_string(root->version.inkscape) << std::endl; + static const double ratio = 90.0 / 96.0; bool need_fix_viewbox = false; - bool need_fix_units = false; - bool need_fix_guides = false; + bool need_fix_units = false; + bool need_fix_guides = false; bool need_fix_grid_mm = false; - bool need_fix_box3d = false; - bool did_scaling = false; + bool need_fix_box3d = false; + bool did_scaling = false; - // Check if potentially need viewbox or unit fix + // Check if potentially need viewbox or unit fix switch (root->width.unit) { case SVGLength::PC: case SVGLength::PT: @@ -347,7 +333,7 @@ void sp_file_convert_dpi(SPDocument *doc) case SVGLength::EM: case SVGLength::EX: case SVGLength::PERCENT: - // OK + // OK break; default: std::cerr << "sp_file_convert_dpi: Unhandled width unit!" << std::endl; @@ -368,7 +354,7 @@ void sp_file_convert_dpi(SPDocument *doc) case SVGLength::EM: case SVGLength::EX: case SVGLength::PERCENT: - // OK + // OK break; default: std::cerr << "sp_file_convert_dpi: Unhandled height unit!" << std::endl; @@ -382,8 +368,8 @@ void sp_file_convert_dpi(SPDocument *doc) need_fix_units = false; } - // std::cout << "Absolute SVG units in root? " << (need_fix_viewbox?"true":"false") << std::endl; - // std::cout << "User units in root? " << (need_fix_units ?"true":"false") << std::endl; + // std::cout << "Absolute SVG units in root? " << (need_fix_viewbox?"true":"false") << std::endl; + // std::cout << "User units in root? " << (need_fix_units ?"true":"false") << std::endl; if ((!root->viewBox_set && need_fix_viewbox) || need_fix_units) { int response = FILE_DPI_UNCHANGED; // default @@ -392,7 +378,7 @@ void sp_file_convert_dpi(SPDocument *doc) bool backup = prefs->getBool("/options/dpifixbackup", true); if (INKSCAPE.use_gui() && sp_file_convert_dpi_method_commandline == -1) { Gtk::Dialog scale_dialog(_("Convert legacy Inkscape file")); - scale_dialog.set_transient_for( *(INKSCAPE.active_desktop()->getToplevel()) ); + scale_dialog.set_transient_for(*(INKSCAPE.active_desktop()->getToplevel())); scale_dialog.set_border_width(10); scale_dialog.set_resizable(false); Gtk::Label explanation; @@ -400,7 +386,7 @@ void sp_file_convert_dpi(SPDocument *doc) _("was created in an older version of Inkscape (90 DPI) and we need " "to make it compatible with newer versions (96 DPI). Tell us about this file:\n")); explanation.set_line_wrap(true); - explanation.set_size_request(600,-1); + explanation.set_size_request(600, -1); Gtk::RadioButton::Group c1, c2; Gtk::Label choice1_label; @@ -423,19 +409,19 @@ void sp_file_convert_dpi(SPDocument *doc) // TRANSLATORS: Please don't translate link unless the page exists in your language. Add your language // code to the link this way: https://inkscape.org/[lang]/learn/faq#dpi_change _("We've updated Inkscape to follow the CSS standard of 96 DPI for " - "better browser compatibility; we used to use 90 DPI. Digital artwork for screen\n" - "display will be converted to 96 DPI without scaling and should be unaffected.\n" - "Artwork drawn at 90 DPI for a specific physical size will be too small if " - "converted to 96 DPI without any scaling. There are two scaling methods:\n\n" - "Scaling the whole document: The least error-prone method, this preserves " - "the appearance of the artwork, including filters and the position of masks, etc. \n" - "The scale of the artwork relative to the document size may not be accurate.\n\n" - "Scaling individual elements in the artwork: This method is less reliable " - "and can result in a changed appearance, \nbut is better for physical output that " - "relies on accurate sizes and positions (for example, for 3D printing.)\n\n" - "More information about this change are available in the
Inkscape FAQ" - "")); + "better browser compatibility; we used to use 90 DPI. Digital artwork for screen\n" + "display will be converted to 96 DPI without scaling and should be unaffected.\n" + "Artwork drawn at 90 DPI for a specific physical size will be too small if " + "converted to 96 DPI without any scaling. There are two scaling methods:\n\n" + "Scaling the whole document: The least error-prone method, this preserves " + "the appearance of the artwork, including filters and the position of masks, etc. \n" + "The scale of the artwork relative to the document size may not be accurate.\n\n" + "Scaling individual elements in the artwork: This method is less reliable " + "and can result in a changed appearance, \nbut is better for physical output that " + "relies on accurate sizes and positions (for example, for 3D printing.)\n\n" + "More information about this change are available in the Inkscape FAQ" + "")); moreinfo_text.set_line_wrap(true); moreinfo_text.set_margin_bottom(20); moreinfo_text.set_margin_top(20); @@ -444,7 +430,7 @@ void sp_file_convert_dpi(SPDocument *doc) Gtk::Box b; b.set_border_width(0); - + b.pack_start(choice2_1, false, false, 4); b.pack_start(choice2_2, false, false, 4); choice2_1.show(); @@ -459,12 +445,12 @@ void sp_file_convert_dpi(SPDocument *doc) Gtk::Box *content = scale_dialog.get_content_area(); Gtk::Button *ok_button = scale_dialog.add_button(_("OK"), GTK_RESPONSE_ACCEPT); backup_button.set_active(backup); - content->pack_start(explanation, false, false, 5); - content->pack_start(choice1, false, false, 5); - content->pack_start(choice2, false, false, 5); - content->pack_start(b, false, false, 5); + content->pack_start(explanation, false, false, 5); + content->pack_start(choice1, false, false, 5); + content->pack_start(choice2, false, false, 5); + content->pack_start(b, false, false, 5); content->pack_start(backup_button, false, false, 5); - content->pack_start(moreinfo, false, false, 5); + content->pack_start(moreinfo, false, false, 5); moreinfo.add(moreinfo_text); scale_dialog.show_all_children(); b.hide(); @@ -472,19 +458,21 @@ void sp_file_convert_dpi(SPDocument *doc) choice2.signal_clicked().connect(sigc::mem_fun(b, &Gtk::Box::show)); response = prefs->getInt("/options/dpiupdatemethod", FILE_DPI_UNCHANGED); - if ( response != FILE_DPI_UNCHANGED ) { + if (response != FILE_DPI_UNCHANGED) { choice2.set_active(); b.show(); - if ( response == FILE_DPI_DOCUMENT_SCALED) + if (response == FILE_DPI_DOCUMENT_SCALED) choice2_2.set_active(); } ok_button->grab_focus(); int status = scale_dialog.run(); - if ( status == GTK_RESPONSE_ACCEPT ) { + if (status == GTK_RESPONSE_ACCEPT) { backup = backup_button.get_active(); prefs->setBool("/options/dpifixbackup", backup); - response = choice1.get_active() ? FILE_DPI_UNCHANGED : choice2_1.get_active() ? FILE_DPI_VIEWBOX_SCALED : FILE_DPI_DOCUMENT_SCALED; + response = choice1.get_active() + ? FILE_DPI_UNCHANGED + : choice2_1.get_active() ? FILE_DPI_VIEWBOX_SCALED : FILE_DPI_DOCUMENT_SCALED; prefs->setInt("/options/dpiupdatemethod", response); } else if (sp_file_convert_dpi_method_commandline != -1) { response = sp_file_convert_dpi_method_commandline; @@ -496,7 +484,7 @@ void sp_file_convert_dpi(SPDocument *doc) } if (backup && (response != FILE_DPI_UNCHANGED)) { - const char* uri = doc->getDocumentURI(); + const char *uri = doc->getDocumentURI(); if (uri) { sp_file_save_backup(Glib::ustring(uri)); } @@ -518,8 +506,7 @@ void sp_file_convert_dpi(SPDocument *doc) if (need_fix_units) doc->setWidthAndHeight(width, height, false); - } else if (response == FILE_DPI_DOCUMENT_SCALED) { - + } else if (response == FILE_DPI_DOCUMENT_SCALED) { Inkscape::Util::Quantity width = // maybe set it to mm ? Inkscape::Util::Quantity(doc->getWidth().value("px") / ratio, "px"); Inkscape::Util::Quantity height = Inkscape::Util::Quantity(doc->getHeight().value("px") / ratio, "px"); @@ -646,8 +633,6 @@ void sp_file_convert_dpi(SPDocument *doc) DocumentUndo::done(doc, SP_VERB_NONE, _("Update Document")); } - - /* Local Variables: mode:c++ diff --git a/src/file.cpp b/src/file.cpp index acce7e5391a5fb8797e6676234f11f24049b5a42..f96d9d0cc6e58885280b40089b983ab393d08c66 100644 --- a/src/file.cpp +++ b/src/file.cpp @@ -29,51 +29,44 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include -#include "file.h" -#include "inkscape-application.h" -#include "inkscape-window.h" - #include "desktop.h" #include "document-undo.h" #include "event-log.h" -#include "id-clash.h" -#include "inkscape-version.h" -#include "inkscape.h" -#include "message-stack.h" -#include "path-prefix.h" -#include "print.h" -#include "rdf.h" -#include "selection-chemistry.h" -#include "verbs.h" - #include "extension/db.h" #include "extension/effect.h" #include "extension/input.h" #include "extension/output.h" - +#include "file.h" #include "helper/png-write.h" - +#include "id-clash.h" +#include "inkscape-application.h" +#include "inkscape-version.h" +#include "inkscape-window.h" +#include "inkscape.h" #include "io/file.h" -#include "io/resource.h" #include "io/resource-manager.h" +#include "io/resource.h" #include "io/sys.h" - +#include "message-stack.h" #include "object/sp-defs.h" #include "object/sp-namedview.h" #include "object/sp-root.h" +#include "path-prefix.h" +#include "print.h" +#include "rdf.h" +#include "selection-chemistry.h" #include "style.h" - -#include "ui/dialog/font-substitution.h" #include "ui/dialog/filedialog.h" +#include "ui/dialog/font-substitution.h" #include "ui/interface.h" #include "ui/tools/tool-base.h" +#include "verbs.h" #include "widgets/desktop-widget.h" - #include "xml/rebase-hrefs.h" #include "xml/sp-css-attr.h" @@ -98,7 +91,6 @@ using Inkscape::IO::Resource::USER; void dump_str(gchar const *str, gchar const *prefix); void dump_ustr(Glib::ustring const &ustr); - /*###################### ## N E W ######################*/ @@ -109,15 +101,16 @@ void dump_ustr(Glib::ustring const &ustr); */ SPDesktop *sp_file_new(const std::string &templ) { - ConcreteInkscapeApplication* app = &(ConcreteInkscapeApplication::get_instance()); + ConcreteInkscapeApplication *app = + &(ConcreteInkscapeApplication::get_instance()); - SPDocument* doc = app->document_new (templ); + SPDocument *doc = app->document_new(templ); if (!doc) { std::cerr << "sp_file_new: failed to open document: " << templ << std::endl; } - InkscapeWindow* win = app->window_open (doc); + InkscapeWindow *win = app->window_open(doc); - SPDesktop* desktop = win->get_desktop(); + SPDesktop *desktop = win->get_desktop(); #ifdef WITH_DBUS Inkscape::Extension::Dbus::dbus_init_desktop_interface(desktop); @@ -131,15 +124,14 @@ std::string sp_file_default_template_uri() return Inkscape::IO::Resource::get_filename_string(TEMPLATES, "default.svg", true); } -SPDesktop* sp_file_new_default() +SPDesktop *sp_file_new_default() { - SPDesktop* desk = sp_file_new(sp_file_default_template_uri()); - //rdf_add_from_preferences( SP_ACTIVE_DOCUMENT ); + SPDesktop *desk = sp_file_new(sp_file_default_template_uri()); + // rdf_add_from_preferences( SP_ACTIVE_DOCUMENT ); return desk; } - /*###################### ## D E L E T E ######################*/ @@ -160,13 +152,12 @@ void sp_file_exit() } } - /** * Handle prompting user for "do you want to revert"? Revert on "OK" */ void sp_file_revert_dialog() { - SPDesktop *desktop = SP_ACTIVE_DESKTOP; + SPDesktop *desktop = SP_ACTIVE_DESKTOP; g_assert(desktop != nullptr); SPDocument *doc = desktop->getDocument(); @@ -183,8 +174,9 @@ void sp_file_revert_dialog() bool do_revert = true; if (doc->isModifiedSinceSave()) { - Glib::ustring tmpString = Glib::ustring::compose(_("Changes will be lost! Are you sure you want to reload document %1?"), uri); - bool response = desktop->warnDialog (tmpString); + Glib::ustring tmpString = + Glib::ustring::compose(_("Changes will be lost! Are you sure you want to reload document %1?"), uri); + bool response = desktop->warnDialog(tmpString); if (!response) { do_revert = false; } @@ -192,8 +184,9 @@ void sp_file_revert_dialog() bool reverted = false; if (do_revert) { - ConcreteInkscapeApplication* app = &(ConcreteInkscapeApplication::get_instance()); - reverted = app->document_revert (doc); + ConcreteInkscapeApplication *app = + &(ConcreteInkscapeApplication::get_instance()); + reverted = app->document_revert(doc); } if (reverted) { @@ -227,10 +220,10 @@ void dump_ustr(Glib::ustring const &ustr) Glib::ustring::size_type const dataLen = ustr.length(); Glib::ustring::size_type const cstrLen = strlen(cstr); - g_message(" size: %lu\n length: %lu\n bytes: %lu\n clen: %lu", - gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) ); - g_message( " ASCII? %s", (ustr.is_ascii() ? "yes":"no") ); - g_message( " UTF-8? %s", (ustr.validate() ? "yes":"no") ); + g_message(" size: %lu\n length: %lu\n bytes: %lu\n clen: %lu", gulong(ustr.size()), gulong(dataLen), + gulong(byteLen), gulong(cstrLen)); + g_message(" ASCII? %s", (ustr.is_ascii() ? "yes" : "no")); + g_message(" UTF-8? %s", (ustr.validate() ? "yes" : "no")); try { Glib::ustring tmp; @@ -238,9 +231,9 @@ void dump_ustr(Glib::ustring const &ustr) tmp = " "; if (i < dataLen) { Glib::ustring::value_type val = ustr.at(i); - gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? " %02x" : "%04x"), val ); + gchar *tmp2 = g_strdup_printf((((val & 0xff00) == 0) ? " %02x" : "%04x"), val); tmp += tmp2; - g_free( tmp2 ); + g_free(tmp2); } else { tmp += " "; } @@ -249,11 +242,11 @@ void dump_ustr(Glib::ustring const &ustr) int val = (0x0ff & data[i]); gchar *tmp2 = g_strdup_printf(" %02x", val); tmp += tmp2; - g_free( tmp2 ); - if ( val > 32 && val < 127 ) { - tmp2 = g_strdup_printf( " '%c'", (gchar)val ); + g_free(tmp2); + if (val > 32 && val < 127) { + tmp2 = g_strdup_printf(" '%c'", (gchar)val); tmp += tmp2; - g_free( tmp2 ); + g_free(tmp2); } else { tmp += " . "; } @@ -261,15 +254,15 @@ void dump_ustr(Glib::ustring const &ustr) tmp += " "; } - if ( i < cstrLen ) { + if (i < cstrLen) { int val = (0x0ff & cstr[i]); - gchar* tmp2 = g_strdup_printf(" %02x", val); + gchar *tmp2 = g_strdup_printf(" %02x", val); tmp += tmp2; g_free(tmp2); - if ( val > 32 && val < 127 ) { - tmp2 = g_strdup_printf(" '%c'", (gchar) val); + if (val > 32 && val < 127) { + tmp2 = g_strdup_printf(" '%c'", (gchar)val); tmp += tmp2; - g_free( tmp2 ); + g_free(tmp2); } else { tmp += " . "; } @@ -277,10 +270,10 @@ void dump_ustr(Glib::ustring const &ustr) tmp += " "; } - g_message( "%s", tmp.c_str() ); + g_message("%s", tmp.c_str()); } } catch (...) { - g_message("XXXXXXXXXXXXXXXXXX Exception" ); + g_message("XXXXXXXXXXXXXXXXXX Exception"); } g_message("---------------"); } @@ -289,46 +282,37 @@ void dump_ustr(Glib::ustring const &ustr) * Display an file Open selector. Open a document if OK is pressed. * Can select single or multiple files for opening. */ -void -sp_file_open_dialog(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/) +void sp_file_open_dialog(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/) { //# Get the current directory for finding files static Glib::ustring open_path; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if(open_path.empty()) - { + if (open_path.empty()) { Glib::ustring attr = prefs->getString("/dialogs/open/path"); - if (!attr.empty()) open_path = attr; + 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))) + if (!Inkscape::IO::file_test(open_path.c_str(), (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) open_path = ""; #ifdef _WIN32 //# If no open path, default to our win32 documents folder - if (open_path.empty()) - { + if (open_path.empty()) { // The path to the My Documents folder is read from the // value "HKEY_CURRENT_USER\Software\Windows\CurrentVersion\Explorer\Shell Folders\Personal" HKEY key = NULL; - if(RegOpenKeyExA(HKEY_CURRENT_USER, - "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", - 0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) - { + if (RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", 0, + KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) { WCHAR utf16path[_MAX_PATH]; DWORD value_type; DWORD data_size = sizeof(utf16path); - if(RegQueryValueExW(key, L"Personal", NULL, &value_type, - (BYTE*)utf16path, &data_size) == ERROR_SUCCESS) - { + if (RegQueryValueExW(key, L"Personal", NULL, &value_type, (BYTE *)utf16path, &data_size) == ERROR_SUCCESS) { g_assert(value_type == REG_SZ); - gchar *utf8path = g_utf16_to_utf8( - (const gunichar2*)utf16path, -1, NULL, NULL, NULL); - if(utf8path) - { + gchar *utf8path = g_utf16_to_utf8((const gunichar2 *)utf16path, -1, NULL, NULL, NULL); + if (utf8path) { open_path = Glib::ustring(utf8path); g_free(utf8path); } @@ -338,18 +322,14 @@ sp_file_open_dialog(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*d #endif //# If no open path, default to our home directory - if (open_path.empty()) - { + if (open_path.empty()) { open_path = g_get_home_dir(); open_path.append(G_DIR_SEPARATOR_S); } //# Create a dialog - Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance = - Inkscape::UI::Dialog::FileOpenDialog::create( - parentWindow, open_path, - Inkscape::UI::Dialog::SVG_TYPES, - _("Select file to open")); + Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance = Inkscape::UI::Dialog::FileOpenDialog::create( + parentWindow, open_path, Inkscape::UI::Dialog::SVG_TYPES, _("Select file to open")); //# Show the dialog bool const success = openDialogInstance->show(); @@ -357,8 +337,7 @@ sp_file_open_dialog(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*d //# Save the folder the user selected for later open_path = openDialogInstance->getCurrentDirectory(); - if (!success) - { + if (!success) { delete openDialogInstance; return; } @@ -378,54 +357,50 @@ sp_file_open_dialog(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*d delete openDialogInstance; openDialogInstance = nullptr; - ConcreteInkscapeApplication* app = &(ConcreteInkscapeApplication::get_instance()); + ConcreteInkscapeApplication *app = + &(ConcreteInkscapeApplication::get_instance()); //# Iterate through filenames if more than 1 - if (flist.size() > 1) - { - for (const auto & i : flist) - { + if (flist.size() > 1) { + for (const auto &i : flist) { fileName = i; Glib::ustring newFileName = Glib::filename_to_utf8(fileName); - if ( newFileName.size() > 0 ) + if (newFileName.size() > 0) fileName = newFileName; else - g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" ); + g_warning("ERROR CONVERTING OPEN FILENAME TO UTF-8"); #ifdef INK_DUMP_FILENAME_CONV g_message("Opening File %s\n", fileName.c_str()); #endif Glib::RefPtr file = Gio::File::create_for_path(fileName); - app->create_window (file); + app->create_window(file); } return; } - - if (!fileName.empty()) - { + if (!fileName.empty()) { Glib::ustring newFileName = Glib::filename_to_utf8(fileName); - if ( newFileName.size() > 0) + if (newFileName.size() > 0) fileName = newFileName; else - g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" ); + g_warning("ERROR CONVERTING OPEN FILENAME TO UTF-8"); - open_path = Glib::path_get_dirname (fileName); + open_path = Glib::path_get_dirname(fileName); open_path.append(G_DIR_SEPARATOR_S); prefs->setString("/dialogs/open/path", open_path); Glib::RefPtr file = Gio::File::create_for_path(fileName); - app->create_window (file); + app->create_window(file); } return; } - /*###################### ## V A C U U M ######################*/ @@ -437,26 +412,22 @@ void sp_file_vacuum(SPDocument *doc) { unsigned int diff = doc->vacuumDocument(); - DocumentUndo::done(doc, SP_VERB_FILE_VACUUM, - _("Clean up document")); + DocumentUndo::done(doc, SP_VERB_FILE_VACUUM, _("Clean up document")); SPDesktop *dt = SP_ACTIVE_DESKTOP; if (dt != nullptr) { // Show status messages when in GUI mode if (diff > 0) { dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE, - ngettext("Removed %i unused definition in <defs>.", - "Removed %i unused definitions in <defs>.", - diff), - diff); + ngettext("Removed %i unused definition in <defs>.", + "Removed %i unused definitions in <defs>.", diff), + diff); } else { - dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("No unused definitions in <defs>.")); + dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("No unused definitions in <defs>.")); } } } - - /*###################### ## S A V E ######################*/ @@ -467,39 +438,38 @@ void sp_file_vacuum(SPDocument *doc) * \param official whether to set :output_module and :modified in the * document; is true for normal save, false for temporary saves */ -static bool -file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri, - Inkscape::Extension::Extension *key, bool checkoverwrite, bool official, - Inkscape::Extension::FileSaveMethod save_method) +static bool file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri, + Inkscape::Extension::Extension *key, bool checkoverwrite, bool official, + Inkscape::Extension::FileSaveMethod save_method) { - if (!doc || uri.size()<1) //Safety check + if (!doc || uri.size() < 1) // Safety check return false; Inkscape::Version save = doc->getRoot()->version.inkscape; doc->getReprRoot()->setAttribute("inkscape:version", Inkscape::version_string); try { - Inkscape::Extension::save(key, doc, uri.c_str(), - false, - checkoverwrite, official, - save_method); + Inkscape::Extension::save(key, doc, uri.c_str(), false, checkoverwrite, official, save_method); } catch (Inkscape::Extension::Output::no_extension_found &e) { gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str()); - gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s). This may have been caused by an unknown filename extension."), safeUri); + gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s). This may have been caused " + "by an unknown filename extension."), + safeUri); SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved.")); sp_ui_error_dialog(text); g_free(text); g_free(safeUri); // Restore Inkscape version - doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string( save )); + doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string(save)); return false; } catch (Inkscape::Extension::Output::file_read_only &e) { gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str()); - gchar *text = g_strdup_printf(_("File %s is write protected. Please remove write protection and try again."), safeUri); + gchar *text = + g_strdup_printf(_("File %s is write protected. Please remove write protection and try again."), safeUri); SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved.")); sp_ui_error_dialog(text); g_free(text); g_free(safeUri); - doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string( save )); + doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string(save)); return false; } catch (Inkscape::Extension::Output::save_failed &e) { gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str()); @@ -508,18 +478,18 @@ file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri, sp_ui_error_dialog(text); g_free(text); g_free(safeUri); - doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string( save )); + doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string(save)); return false; } catch (Inkscape::Extension::Output::save_cancelled &e) { SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved.")); - doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string( save )); + doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string(save)); return false; } catch (Inkscape::Extension::Output::export_id_not_found &e) { gchar *text = g_strdup_printf(_("File could not be saved:\nNo object with ID '%s' found."), e.id); SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved.")); sp_ui_error_dialog(text); g_free(text); - doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string( save )); + doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string(save)); return false; } catch (Inkscape::Extension::Output::no_overwrite &e) { return sp_file_save_dialog(parentWindow, doc, save_method); @@ -527,12 +497,13 @@ file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri, gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str()); gchar *text = g_strdup_printf(_("File %s could not be saved.\n\n" "The following additional information was returned by the output extension:\n" - "'%s'"), safeUri, e.what()); + "'%s'"), + safeUri, e.what()); SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved.")); sp_ui_error_dialog(text); g_free(text); g_free(safeUri); - doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string( save )); + doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string(save)); return false; } catch (...) { g_critical("Extension '%s' threw an unspecified exception.", key->get_id()); @@ -542,15 +513,15 @@ file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri, sp_ui_error_dialog(text); g_free(text); g_free(safeUri); - doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string( save )); + doc->getReprRoot()->setAttribute("inkscape:version", sp_version_to_string(save)); return false; } if (SP_ACTIVE_DESKTOP) { - if (! SP_ACTIVE_DESKTOP->event_log) { + if (!SP_ACTIVE_DESKTOP->event_log) { g_message("file_save: ->event_log == NULL. please report to bug #967416"); } - if (! SP_ACTIVE_DESKTOP->messageStack()) { + if (!SP_ACTIVE_DESKTOP->messageStack()) { g_message("file_save: ->messageStack() == NULL. please report to bug #967416"); } } else { @@ -568,15 +539,14 @@ file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri, return true; } - /** * Check if a string ends with another string. * \todo Find a better code file to put this general purpose method */ -static bool hasEnding (Glib::ustring const &fullString, Glib::ustring const &ending) +static bool hasEnding(Glib::ustring const &fullString, Glib::ustring const &ending) { if (fullString.length() > ending.length()) { - return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending)); + return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending)); } else { return false; } @@ -585,8 +555,7 @@ static bool hasEnding (Glib::ustring const &fullString, Glib::ustring const &end /** * Display a SaveAs dialog. Save the document if OK pressed. */ -bool -sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, Inkscape::Extension::FileSaveMethod save_method) +bool sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, Inkscape::Extension::FileSaveMethod save_method) { Inkscape::Extension::Output *extension = nullptr; bool is_copy = (save_method == Inkscape::Extension::FILE_SAVE_METHOD_SAVE_COPY); @@ -596,19 +565,17 @@ sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, Inkscape::Extens Glib::ustring default_extension; Glib::ustring filename_extension = ".svg"; - default_extension= Inkscape::Extension::get_file_save_extension(save_method); - //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension); + default_extension = Inkscape::Extension::get_file_save_extension(save_method); + // g_message("%s: extension name: '%s'", __FUNCTION__, default_extension); - extension = dynamic_cast - (Inkscape::Extension::db.get(default_extension.c_str())); + extension = dynamic_cast(Inkscape::Extension::db.get(default_extension.c_str())); if (extension) filename_extension = extension->get_extension(); Glib::ustring save_path = Inkscape::Extension::get_file_save_path(doc, save_method); - if (!Inkscape::IO::file_test(save_path.c_str(), - (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) + if (!Inkscape::IO::file_test(save_path.c_str(), (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) save_path.clear(); if (save_path.empty()) @@ -618,7 +585,7 @@ sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, Inkscape::Extens save_loc.append(G_DIR_SEPARATOR_S); int i = 1; - if ( !doc->getDocumentURI() ) { + if (!doc->getDocumentURI()) { // We are saving for the first time; create a unique default filename save_loc = save_loc + _("drawing") + filename_extension; @@ -640,30 +607,24 @@ sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, Inkscape::Extens save_loc = save_loc_local; //# Show the SaveAs dialog - char const * dialog_title; + char const *dialog_title; if (is_copy) { - dialog_title = (char const *) _("Select file to save a copy to"); + dialog_title = (char const *)_("Select file to save a copy to"); } else { - dialog_title = (char const *) _("Select file to save to"); + dialog_title = (char const *)_("Select file to save to"); } - gchar* doc_title = doc->getRoot()->title(); - Inkscape::UI::Dialog::FileSaveDialog *saveDialog = - Inkscape::UI::Dialog::FileSaveDialog::create( - parentWindow, - save_loc, - Inkscape::UI::Dialog::SVG_TYPES, - dialog_title, - default_extension, - doc_title ? doc_title : "", - save_method - ); + gchar *doc_title = doc->getRoot()->title(); + Inkscape::UI::Dialog::FileSaveDialog *saveDialog = Inkscape::UI::Dialog::FileSaveDialog::create( + parentWindow, save_loc, Inkscape::UI::Dialog::SVG_TYPES, dialog_title, default_extension, + doc_title ? doc_title : "", save_method); saveDialog->setSelectionType(extension); bool success = saveDialog->show(); if (!success) { delete saveDialog; - if(doc_title) g_free(doc_title); + if (doc_title) + g_free(doc_title); return success; } @@ -675,7 +636,8 @@ sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, Inkscape::Extens delete saveDialog; saveDialog = nullptr; - if(doc_title) g_free(doc_title); + if (doc_title) + g_free(doc_title); if (!fileName.empty()) { Glib::ustring newFileName = Glib::filename_to_utf8(fileName); @@ -683,12 +645,12 @@ sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, Inkscape::Extens if (!newFileName.empty()) fileName = newFileName; else - g_warning( "Error converting filename for saving to UTF-8." ); + g_warning("Error converting filename for saving to UTF-8."); Inkscape::Extension::Output *omod = dynamic_cast(selectionType); if (omod) { Glib::ustring save_extension = (omod->get_extension()) ? (omod->get_extension()) : ""; - if ( !hasEnding(fileName, save_extension) ) { + if (!hasEnding(fileName, save_extension)) { fileName += save_extension; } } @@ -711,28 +673,25 @@ sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, Inkscape::Extens return success; } - return false; } - /** * Save a document, displaying a SaveAs dialog if necessary. */ -bool -sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc) +bool sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc) { bool success = true; if (doc->isModifiedSinceSave()) { - if ( doc->getDocumentURI() == nullptr ) - { + if (doc->getDocumentURI() == nullptr) { // Hier sollte in Argument mitgegeben werden, das anzeigt, da� das Dokument das erste // Mal gespeichert wird, so da� als default .svg ausgew�hlt wird und nicht die zuletzt // benutzte "Save as ..."-Endung return sp_file_save_dialog(parentWindow, doc, Inkscape::Extension::FILE_SAVE_METHOD_INKSCAPE_SVG); } else { - Glib::ustring extension = Inkscape::Extension::get_file_save_extension(Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS); + Glib::ustring extension = + Inkscape::Extension::get_file_save_extension(Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS); Glib::ustring fn = g_strdup(doc->getDocumentURI()); // Try to determine the extension from the uri; this may not lead to a valid extension, // but this case is caught in the file_save method below (or rather in Extension::save() @@ -742,9 +701,10 @@ sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc) if (pos != Glib::ustring::npos) { // FIXME: this could/should be more sophisticated (see FileSaveDialog::appendExtension()), // but hopefully it's a reasonable workaround for now - ext = fn.substr( pos ); + ext = fn.substr(pos); } - success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext.c_str()), FALSE, TRUE, Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS); + success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext.c_str()), FALSE, TRUE, + Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS); if (success == false) { // give the user the chance to change filename or extension return sp_file_save_dialog(parentWindow, doc, Inkscape::Extension::FILE_SAVE_METHOD_INKSCAPE_SVG); @@ -752,8 +712,7 @@ sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc) } } else { Glib::ustring msg; - if ( doc->getDocumentURI() == nullptr ) - { + if (doc->getDocumentURI() == nullptr) { msg = Glib::ustring::format(_("No changes need to be saved.")); } else { msg = Glib::ustring::format(_("No changes need to be saved."), " ", doc->getDocumentURI()); @@ -765,12 +724,10 @@ sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc) return success; } - /** * Save a document. */ -bool -sp_file_save(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/) +bool sp_file_save(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/) { if (!SP_ACTIVE_DOCUMENT) return false; @@ -781,12 +738,10 @@ sp_file_save(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/) return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT); } - /** * Save a document, always displaying the SaveAs dialog. */ -bool -sp_file_save_as(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/) +bool sp_file_save_as(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/) { if (!SP_ACTIVE_DOCUMENT) return false; @@ -794,13 +749,10 @@ sp_file_save_as(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data* return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS); } - - /** * Save a copy of a document, always displaying a sort of SaveAs dialog. */ -bool -sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/) +bool sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/) { if (!SP_ACTIVE_DOCUMENT) return false; @@ -811,10 +763,8 @@ sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*d /** * Save a copy of a document as template. */ -bool -sp_file_save_template(Gtk::Window &parentWindow, Glib::ustring name, - Glib::ustring author, Glib::ustring description, Glib::ustring keywords, - bool isDefault) +bool sp_file_save_template(Gtk::Window &parentWindow, Glib::ustring name, Glib::ustring author, + Glib::ustring description, Glib::ustring keywords, bool isDefault) { if (!SP_ACTIVE_DOCUMENT || name.length() == 0) return true; @@ -836,7 +786,6 @@ sp_file_save_template(Gtk::Window &parentWindow, Glib::ustring name, templateinfo_node->appendChild(element_node); if (author.length() != 0) { - element_node = xml_doc->createElement("inkscape:author"); Inkscape::GC::release(element_node); @@ -845,30 +794,25 @@ sp_file_save_template(Gtk::Window &parentWindow, Glib::ustring name, } if (description.length() != 0) { - element_node = xml_doc->createElement("inkscape:shortdesc"); Inkscape::GC::release(element_node); element_node->appendChild(xml_doc->createTextNode(description.c_str())); templateinfo_node->appendChild(element_node); - } element_node = xml_doc->createElement("inkscape:date"); Inkscape::GC::release(element_node); - element_node->appendChild(xml_doc->createTextNode( - Glib::DateTime::create_now_local().format("%F").c_str())); + element_node->appendChild(xml_doc->createTextNode(Glib::DateTime::create_now_local().format("%F").c_str())); templateinfo_node->appendChild(element_node); if (keywords.length() != 0) { - element_node = xml_doc->createElement("inkscape:keywords"); Inkscape::GC::release(element_node); element_node->appendChild(xml_doc->createTextNode(keywords.c_str())); templateinfo_node->appendChild(element_node); - } root->appendChild(templateinfo_node); @@ -883,10 +827,8 @@ sp_file_save_template(Gtk::Window &parentWindow, Glib::ustring name, auto operation_confirmed = sp_ui_overwrite_file(filename.c_str()); if (operation_confirmed) { - - file_save(parentWindow, document, filename, - Inkscape::Extension::db.get(".svg"), false, false, - Inkscape::Extension::FILE_SAVE_METHOD_INKSCAPE_SVG); + file_save(parentWindow, document, filename, Inkscape::Extension::db.get(".svg"), false, false, + Inkscape::Extension::FILE_SAVE_METHOD_INKSCAPE_SVG); if (isDefault) { // save as "default.svg" by default (so it works independently of UI language), unless @@ -898,12 +840,11 @@ sp_file_save_template(Gtk::Window &parentWindow, Glib::ustring name, filename = Inkscape::IO::Resource::get_path_ustring(USER, TEMPLATES, "default.svg"); } - file_save(parentWindow, document, filename, - Inkscape::Extension::db.get(".svg"), false, false, - Inkscape::Extension::FILE_SAVE_METHOD_INKSCAPE_SVG); + file_save(parentWindow, document, filename, Inkscape::Extension::db.get(".svg"), false, false, + Inkscape::Extension::FILE_SAVE_METHOD_INKSCAPE_SVG); } } - + // remove this node from current document after saving it as template root->removeChild(templateinfo_node); @@ -912,8 +853,6 @@ sp_file_save_template(Gtk::Window &parentWindow, Glib::ustring name, return operation_confirmed; } - - /*###################### ## I M P O R T ######################*/ @@ -926,7 +865,7 @@ sp_file_save_template(Gtk::Window &parentWindow, Glib::ustring name, */ void sp_import_document(SPDesktop *desktop, SPDocument *clipdoc, bool in_place) { - //TODO: merge with file_import() + // TODO: merge with file_import() SPDocument *target_document = desktop->getDocument(); Inkscape::XML::Node *root = clipdoc->getReprRoot(); @@ -935,10 +874,10 @@ void sp_import_document(SPDesktop *desktop, SPDocument *clipdoc, bool in_place) // copy definitions desktop->doc()->importDefs(clipdoc); - Inkscape::XML::Node* clipboard = nullptr; + Inkscape::XML::Node *clipboard = nullptr; // copy objects - std::vector pasted_objects; - for (Inkscape::XML::Node *obj = root->firstChild() ; obj ; obj = obj->next()) { + std::vector pasted_objects; + for (Inkscape::XML::Node *obj = root->firstChild(); obj; obj = obj->next()) { // Don't copy metadata, defs, named views and internal clipboard contents to the document if (!strcmp(obj->name(), "svg:defs")) { continue; @@ -961,26 +900,28 @@ void sp_import_document(SPDesktop *desktop, SPDocument *clipdoc, bool in_place) // if we are pasting a clone to an already existing object, its // transform is wrong (see ui/clipboard.cpp) - if(obj_copy->attribute("transform-with-parent") && target_document->getObjectById(obj->attribute("xlink:href")+1) ){ - obj_copy->setAttribute("transform",obj_copy->attribute("transform-with-parent")); + if (obj_copy->attribute("transform-with-parent") && + target_document->getObjectById(obj->attribute("xlink:href") + 1)) { + obj_copy->setAttribute("transform", obj_copy->attribute("transform-with-parent")); } - if(obj_copy->attribute("transform-with-parent")) + if (obj_copy->attribute("transform-with-parent")) obj_copy->removeAttribute("transform-with-parent"); } - std::vector pasted_objects_not; - if(clipboard) //???? Removed dead code can cause any bug, need to reimplement undead - for (Inkscape::XML::Node *obj = clipboard->firstChild() ; obj ; obj = obj->next()) { - if(target_document->getObjectById(obj->attribute("id"))) continue; - Inkscape::XML::Node *obj_copy = obj->duplicate(target_document->getReprDoc()); - SPObject * pasted = desktop->currentLayer()->appendChildRepr(obj_copy); - Inkscape::GC::release(obj_copy); - SPLPEItem * pasted_lpe_item = dynamic_cast(pasted); - if (pasted_lpe_item){ - pasted_lpe_item->forkPathEffectsIfNecessary(1); + std::vector pasted_objects_not; + if (clipboard) //???? Removed dead code can cause any bug, need to reimplement undead + for (Inkscape::XML::Node *obj = clipboard->firstChild(); obj; obj = obj->next()) { + if (target_document->getObjectById(obj->attribute("id"))) + continue; + Inkscape::XML::Node *obj_copy = obj->duplicate(target_document->getReprDoc()); + SPObject *pasted = desktop->currentLayer()->appendChildRepr(obj_copy); + Inkscape::GC::release(obj_copy); + SPLPEItem *pasted_lpe_item = dynamic_cast(pasted); + if (pasted_lpe_item) { + pasted_lpe_item->forkPathEffectsIfNecessary(1); + } + pasted_objects_not.push_back(obj_copy); } - pasted_objects_not.push_back(obj_copy); - } Inkscape::Selection *selection = desktop->getSelection(); selection->setReprList(pasted_objects_not); Geom::Affine doc2parent = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); @@ -998,8 +939,6 @@ void sp_import_document(SPDesktop *desktop, SPDocument *clipdoc, bool in_place) // Apply inverse of parent transform selection->applyAffine(desktop->dt2doc() * doc2parent * desktop->doc2dt(), true, false, false); - - // Update (among other things) all curves in paths, for bounds() to work target_document->ensureUpToDate(); @@ -1033,13 +972,10 @@ void sp_import_document(SPDesktop *desktop, SPDocument *clipdoc, bool in_place) target_document->emitReconstructionFinish(); } - /** * Import a resource. Called by sp_file_import() */ -SPObject * -file_import(SPDocument *in_doc, const Glib::ustring &uri, - Inkscape::Extension::Extension *key) +SPObject *file_import(SPDocument *in_doc, const Glib::ustring &uri, Inkscape::Extension::Extension *key) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; bool cancelled = false; @@ -1047,7 +983,7 @@ file_import(SPDocument *in_doc, const Glib::ustring &uri, // store mouse pointer location before opening any dialogs, so we can drop the item where initially intended auto pointer_location = desktop->point(); - //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key ); + // DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key ); SPDocument *doc; try { doc = Inkscape::Extension::open(key, uri.c_str()); @@ -1071,20 +1007,20 @@ file_import(SPDocument *in_doc, const Glib::ustring &uri, // Count the number of top-level items in the imported document. guint items_count = 0; SPObject *o = nullptr; - for (auto& child: doc->getRoot()->children) { + for (auto &child : doc->getRoot()->children) { if (SP_IS_ITEM(&child)) { items_count++; o = &child; } } - //ungroup if necessary + // ungroup if necessary bool did_ungroup = false; - while(items_count==1 && o && SP_IS_GROUP(o) && o->children.size()==1){ - std::vectorv; - sp_item_group_ungroup(SP_GROUP(o),v,false); + while (items_count == 1 && o && SP_IS_GROUP(o) && o->children.size() == 1) { + std::vector v; + sp_item_group_ungroup(SP_GROUP(o), v, false); o = v.empty() ? nullptr : v[0]; - did_ungroup=true; + did_ungroup = true; } // Create a new group if necessary. @@ -1111,9 +1047,10 @@ file_import(SPDocument *in_doc, const Glib::ustring &uri, // Construct a new object representing the imported image, // and insert it into the current document. SPObject *new_obj = nullptr; - for (auto& child: doc->getRoot()->children) { + for (auto &child : doc->getRoot()->children) { if (SP_IS_ITEM(&child)) { - Inkscape::XML::Node *newitem = did_ungroup ? o->getRepr()->duplicate(xml_in_doc) : child.getRepr()->duplicate(xml_in_doc); + Inkscape::XML::Node *newitem = + did_ungroup ? o->getRepr()->duplicate(xml_in_doc) : child.getRepr()->duplicate(xml_in_doc); // convert layers to groups, and make sure they are unlocked // FIXME: add "preserve layers" mode where each layer from @@ -1121,8 +1058,10 @@ file_import(SPDocument *in_doc, const Glib::ustring &uri, newitem->removeAttribute("inkscape:groupmode"); newitem->removeAttribute("sodipodi:insensitive"); - if (newgroup) newgroup->appendChild(newitem); - else new_obj = place_to_insert->appendChildRepr(newitem); + if (newgroup) + newgroup->appendChild(newitem); + else + new_obj = place_to_insert->appendChildRepr(newitem); } // don't lose top-level defs or style elements @@ -1134,11 +1073,14 @@ file_import(SPDocument *in_doc, const Glib::ustring &uri, } } in_doc->emitReconstructionFinish(); - if (newgroup) new_obj = place_to_insert->appendChildRepr(newgroup); + if (newgroup) + new_obj = place_to_insert->appendChildRepr(newgroup); // release some stuff - if (newgroup) Inkscape::GC::release(newgroup); - if (style) sp_repr_css_attr_unref(style); + if (newgroup) + Inkscape::GC::release(newgroup); + if (style) + sp_repr_css_attr_unref(style); // select and move the imported item if (new_obj && SP_IS_ITEM(new_obj)) { @@ -1156,14 +1098,13 @@ file_import(SPDocument *in_doc, const Glib::ustring &uri, desktop->getDocument()->ensureUpToDate(); Geom::OptRect sel_bbox = selection->visualBounds(); if (sel_bbox) { - Geom::Point m( pointer_location - sel_bbox->midpoint() ); + Geom::Point m(pointer_location - sel_bbox->midpoint()); selection->moveRelative(m, false); } } } - DocumentUndo::done(in_doc, SP_VERB_FILE_IMPORT, - _("Import")); + DocumentUndo::done(in_doc, SP_VERB_FILE_IMPORT, _("Import")); return new_obj; } else if (!cancelled) { gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str()); @@ -1174,12 +1115,10 @@ file_import(SPDocument *in_doc, const Glib::ustring &uri, return nullptr; } - /** * Display an Open dialog, import a resource if OK pressed. */ -void -sp_file_import(Gtk::Window &parentWindow) +void sp_file_import(Gtk::Window &parentWindow) { static Glib::ustring import_path; @@ -1189,31 +1128,25 @@ sp_file_import(Gtk::Window &parentWindow) Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if(import_path.empty()) - { + if (import_path.empty()) { Glib::ustring attr = prefs->getString("/dialogs/import/path"); - if (!attr.empty()) import_path = attr; + if (!attr.empty()) + import_path = attr; } //# Test if the import_path directory exists - if (!Inkscape::IO::file_test(import_path.c_str(), - (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) + if (!Inkscape::IO::file_test(import_path.c_str(), (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) import_path = ""; //# If no open path, default to our home directory - if (import_path.empty()) - { + if (import_path.empty()) { import_path = g_get_home_dir(); import_path.append(G_DIR_SEPARATOR_S); } // Create new dialog (don't use an old one, because parentWindow has probably changed) - Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = - Inkscape::UI::Dialog::FileOpenDialog::create( - parentWindow, - import_path, - Inkscape::UI::Dialog::IMPORT_TYPES, - (char const *)_("Select file to import")); + Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = Inkscape::UI::Dialog::FileOpenDialog::create( + parentWindow, import_path, Inkscape::UI::Dialog::IMPORT_TYPES, (char const *)_("Select file to import")); bool success = importDialogInstance->show(); if (!success) { @@ -1232,10 +1165,8 @@ sp_file_import(Gtk::Window &parentWindow) importDialogInstance = nullptr; //# Iterate through filenames if more than 1 - if (flist.size() > 1) - { - for (const auto & i : flist) - { + if (flist.size() > 1) { + for (const auto &i : flist) { fileName = i; Glib::ustring newFileName = Glib::filename_to_utf8(fileName); @@ -1253,9 +1184,7 @@ sp_file_import(Gtk::Window &parentWindow) return; } - if (!fileName.empty()) { - Glib::ustring newFileName = Glib::filename_to_utf8(fileName); if (!newFileName.empty()) @@ -1277,19 +1206,16 @@ sp_file_import(Gtk::Window &parentWindow) ## P R I N T ######################*/ - /** * Print the current document, if any. */ -void -sp_file_print(Gtk::Window& parentWindow) +void sp_file_print(Gtk::Window &parentWindow) { SPDocument *doc = SP_ACTIVE_DOCUMENT; if (doc) sp_print_document(parentWindow, doc); } - /* Local Variables: mode:c++ diff --git a/src/file.h b/src/file.h index bbc09491d77c4ec02e59aae7a8b79340fda380e2..f6fccda8cfc1f1aad50d4ae2ac5e03fb96a1024f 100644 --- a/src/file.h +++ b/src/file.h @@ -18,6 +18,7 @@ #include #include + #include "extension/system.h" class SPDesktop; @@ -25,10 +26,10 @@ class SPDocument; class SPObject; namespace Inkscape { - namespace Extension { - class Extension; - } +namespace Extension { +class Extension; } +} // namespace Inkscape namespace Gtk { class Window; @@ -45,8 +46,8 @@ std::string sp_file_default_template_uri(); * Creates a new Inkscape document and window. * Return value is a pointer to the newly created desktop. */ -SPDesktop* sp_file_new (const std::string &templ); -SPDesktop* sp_file_new_default (); +SPDesktop *sp_file_new(const std::string &templ); +SPDesktop *sp_file_new_default(); /*###################### ## D E L E T E @@ -55,7 +56,7 @@ SPDesktop* sp_file_new_default (); /** * Close the document/view */ -void sp_file_exit (); +void sp_file_exit(); /*###################### ## O P E N @@ -65,12 +66,12 @@ void sp_file_exit (); * Displays a file open dialog. Calls sp_file_open on * an OK. */ -void sp_file_open_dialog (Gtk::Window &parentWindow, void* object, void* data); +void sp_file_open_dialog(Gtk::Window &parentWindow, void *object, void *data); /** * Reverts file to disk-copy on "YES" */ -void sp_file_revert_dialog (); +void sp_file_revert_dialog(); /*###################### ## S A V E @@ -79,37 +80,34 @@ void sp_file_revert_dialog (); /** * */ -bool sp_file_save (Gtk::Window &parentWindow, void* object, void* data); +bool sp_file_save(Gtk::Window &parentWindow, void *object, void *data); /** * Saves the given document. Displays a file select dialog * to choose the new name. */ -bool sp_file_save_as (Gtk::Window &parentWindow, void* object, void* data); +bool sp_file_save_as(Gtk::Window &parentWindow, void *object, void *data); /** * Saves a copy of the given document. Displays a file select dialog * to choose a name for the copy. */ -bool sp_file_save_a_copy (Gtk::Window &parentWindow, void* object, void* data); +bool sp_file_save_a_copy(Gtk::Window &parentWindow, void *object, void *data); /** * Save a copy of a document as template. */ -bool -sp_file_save_template(Gtk::Window &parentWindow, Glib::ustring name, - Glib::ustring author, Glib::ustring description, Glib::ustring keywords, - bool isDefault); +bool sp_file_save_template(Gtk::Window &parentWindow, Glib::ustring name, Glib::ustring author, + Glib::ustring description, Glib::ustring keywords, bool isDefault); /** * Saves the given document. Displays a file select dialog * if needed. */ -bool sp_file_save_document (Gtk::Window &parentWindow, SPDocument *document); +bool sp_file_save_document(Gtk::Window &parentWindow, SPDocument *document); /* Do the saveas dialog with a document as the parameter */ -bool sp_file_save_dialog (Gtk::Window &parentWindow, SPDocument *doc, Inkscape::Extension::FileSaveMethod save_method); - +bool sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, Inkscape::Extension::FileSaveMethod save_method); /*###################### ## I M P O R T @@ -121,13 +119,12 @@ void sp_import_document(SPDesktop *desktop, SPDocument *clipdoc, bool in_place); * Displays a file selector dialog, to allow the * user to import data into the current document. */ -void sp_file_import (Gtk::Window &parentWindow); +void sp_file_import(Gtk::Window &parentWindow); /** * Imports a resource */ -SPObject* file_import(SPDocument *in_doc, const Glib::ustring &uri, - Inkscape::Extension::Extension *key); +SPObject *file_import(SPDocument *in_doc, const Glib::ustring &uri, Inkscape::Extension::Extension *key); /*###################### ## E X P O R T @@ -138,8 +135,7 @@ SPObject* file_import(SPDocument *in_doc, const Glib::ustring &uri, * additional type selection, to allow the user to export * the a document as a given type. */ -//bool sp_file_export_dialog (Gtk::Window &parentWindow); - +// bool sp_file_export_dialog (Gtk::Window &parentWindow); /*###################### ## P R I N T @@ -152,7 +148,7 @@ would be useful as instance methods /** * */ -void sp_file_print (Gtk::Window& parentWindow); +void sp_file_print(Gtk::Window &parentWindow); /*##################### ## U T I L I T Y @@ -161,18 +157,22 @@ void sp_file_print (Gtk::Window& parentWindow); /** * clean unused defs out of file */ -void sp_file_vacuum (SPDocument *doc); +void sp_file_vacuum(SPDocument *doc); void sp_file_convert_text_baseline_spacing(SPDocument *doc); void sp_file_convert_font_name(SPDocument *doc); void sp_file_convert_dpi(SPDocument *doc); void sp_file_fix_empty_lines(SPDocument *doc); void sp_file_fix_osb(SPObject *doc); -enum File_DPI_Fix { FILE_DPI_UNCHANGED = 0, FILE_DPI_VIEWBOX_SCALED, FILE_DPI_DOCUMENT_SCALED }; +enum File_DPI_Fix +{ + FILE_DPI_UNCHANGED = 0, + FILE_DPI_VIEWBOX_SCALED, + FILE_DPI_DOCUMENT_SCALED +}; extern int sp_file_convert_dpi_method_commandline; #endif // SEEN_SP_FILE_H - /* Local Variables: mode:c++ diff --git a/src/fill-or-stroke.h b/src/fill-or-stroke.h index 43849b379b1f77e885d7073a5a60f5eb1307bafb..27c6f633ce3394028b5166bd62162c8adabd54b2 100644 --- a/src/fill-or-stroke.h +++ b/src/fill-or-stroke.h @@ -12,6 +12,10 @@ #define SEEN_FILL_OR_STROKE_H /** \post STROKE == 0, FILL != 0. */ -enum FillOrStroke { STROKE = 0, FILL = 1 }; +enum FillOrStroke +{ + STROKE = 0, + FILL = 1 +}; #endif // !SEEN_FILL_OR_STROKE_H diff --git a/src/filter-chemistry.cpp b/src/filter-chemistry.cpp index 29fb37d57a3ad507ef85d8b21fe084da8223c7e5..3cc5679c70e44c60c6e02daf76f314feea110cc7 100644 --- a/src/filter-chemistry.cpp +++ b/src/filter-chemistry.cpp @@ -22,13 +22,11 @@ #include "desktop-style.h" #include "document.h" #include "filter-enums.h" -#include "style.h" - -#include "object/sp-defs.h" -#include "object/sp-item.h" - #include "object/filters/blend.h" #include "object/filters/gaussian-blur.h" +#include "object/sp-defs.h" +#include "object/sp-item.h" +#include "style.h" /** * Count how many times the filter is used by the styles of o and its @@ -42,14 +40,11 @@ static guint count_filter_hrefs(SPObject *o, SPFilter *filter) guint i = 0; SPStyle *style = o->style; - if (style - && style->filter.set - && style->getFilter() == filter) - { - i ++; + if (style && style->filter.set && style->getFilter() == filter) { + i++; } - for (auto& child: o->children) { + for (auto &child : o->children) { i += count_filter_hrefs(&child, filter); } @@ -60,8 +55,7 @@ static guint count_filter_hrefs(SPObject *o, SPFilter *filter) * Sets a suitable filter effects area according to given blur radius, * expansion and object size. */ -static void set_filter_area(Inkscape::XML::Node *repr, gdouble radius, - double expansion, double expansionX, +static void set_filter_area(Inkscape::XML::Node *repr, gdouble radius, double expansion, double expansionX, double expansionY, double width, double height) { // TODO: make this more generic, now assumed, that only the blur @@ -73,7 +67,7 @@ static void set_filter_area(Inkscape::XML::Node *repr, gdouble radius, if (width != 0 && height != 0) { // If not within the default 10% margin (see // http://www.w3.org/TR/SVG11/filters.html#FilterEffectsRegion), specify margins - // The 2.4 is an empirical coefficient: at that distance the cutoff is practically invisible + // The 2.4 is an empirical coefficient: at that distance the cutoff is practically invisible // (the opacity at 2.4*radius is about 3e-3) double xmargin = 2.4 * (rx) / width; double ymargin = 2.4 * (ry) / height; @@ -112,26 +106,24 @@ SPFilter *new_filter(SPDocument *document) Inkscape::GC::release(repr); // get corresponding object - SPFilter *f = SP_FILTER( document->getObjectByRepr(repr) ); - - + SPFilter *f = SP_FILTER(document->getObjectByRepr(repr)); + g_assert(f != nullptr); g_assert(SP_IS_FILTER(f)); return f; } -SPFilterPrimitive * -filter_add_primitive(SPFilter *filter, const Inkscape::Filters::FilterPrimitiveType type) +SPFilterPrimitive *filter_add_primitive(SPFilter *filter, const Inkscape::Filters::FilterPrimitiveType type) { Inkscape::XML::Document *xml_doc = filter->document->getReprDoc(); - //create filter primitive node + // create filter primitive node Inkscape::XML::Node *repr; repr = xml_doc->createElement(FPConverter.get_key(type).c_str()); // set default values - switch(type) { + switch (type) { case Inkscape::Filters::NR_FILTER_BLEND: repr->setAttribute("mode", "normal"); break; @@ -174,14 +166,14 @@ filter_add_primitive(SPFilter *filter, const Inkscape::Filters::FilterPrimitiveT break; } - //set primitive as child of filter node + // set primitive as child of filter node // XML tree being used directly while/where it shouldn't be... filter->appendChild(repr); Inkscape::GC::release(repr); - + // get corresponding object - SPFilterPrimitive *prim = SP_FILTER_PRIMITIVE( filter->document->getObjectByRepr(repr) ); - + SPFilterPrimitive *prim = SP_FILTER_PRIMITIVE(filter->document->getObjectByRepr(repr)); + g_assert(prim != nullptr); g_assert(SP_IS_FILTER_PRIMITIVE(prim)); @@ -189,10 +181,11 @@ filter_add_primitive(SPFilter *filter, const Inkscape::Filters::FilterPrimitiveT } /** - * Creates a filter with blur primitive of specified radius for an item with the given matrix expansion, width and height + * Creates a filter with blur primitive of specified radius for an item with the given matrix expansion, width and + * height */ -SPFilter * -new_filter_gaussian_blur (SPDocument *document, gdouble radius, double expansion, double expansionX, double expansionY, double width, double height) +SPFilter *new_filter_gaussian_blur(SPDocument *document, gdouble radius, double expansion, double expansionX, + double expansionY, double width, double height) { g_return_val_if_fail(document != nullptr, NULL); @@ -203,44 +196,43 @@ new_filter_gaussian_blur (SPDocument *document, gdouble radius, double expansion // create a new filter Inkscape::XML::Node *repr; repr = xml_doc->createElement("svg:filter"); - //repr->setAttribute("inkscape:collect", "always"); + // repr->setAttribute("inkscape:collect", "always"); - set_filter_area(repr, radius, expansion, expansionX, expansionY, - width, height); + set_filter_area(repr, radius, expansion, expansionX, expansionY, width, height); - /* Inkscape now supports both sRGB and linear color-interpolation-filters. + /* Inkscape now supports both sRGB and linear color-interpolation-filters. * But, for the moment, keep sRGB as default value for new filters. * historically set to sRGB and doesn't require conversion between * filter cairo surfaces and other types of cairo surfaces. lp:1127103 */ - SPCSSAttr *css = sp_repr_css_attr_new(); - sp_repr_css_set_property(css, "color-interpolation-filters", "sRGB"); - sp_repr_css_change(repr, css, "style"); + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "color-interpolation-filters", "sRGB"); + sp_repr_css_change(repr, css, "style"); sp_repr_css_attr_unref(css); - //create feGaussianBlur node + // create feGaussianBlur node Inkscape::XML::Node *b_repr; b_repr = xml_doc->createElement("svg:feGaussianBlur"); - //b_repr->setAttribute("inkscape:collect", "always"); - + // b_repr->setAttribute("inkscape:collect", "always"); + double stdDeviation = radius; if (expansion != 0) stdDeviation /= expansion; - //set stdDeviation attribute + // set stdDeviation attribute sp_repr_set_svg_double(b_repr, "stdDeviation", stdDeviation); - - //set feGaussianBlur as child of filter node + + // set feGaussianBlur as child of filter node repr->appendChild(b_repr); Inkscape::GC::release(b_repr); - + // Append the new filter node to defs defs->appendChild(repr); Inkscape::GC::release(repr); // get corresponding object - SPFilter *f = SP_FILTER( document->getObjectByRepr(repr) ); - SPGaussianBlur *b = SP_GAUSSIANBLUR( document->getObjectByRepr(b_repr) ); - + SPFilter *f = SP_FILTER(document->getObjectByRepr(repr)); + SPGaussianBlur *b = SP_GAUSSIANBLUR(document->getObjectByRepr(b_repr)); + g_assert(f != nullptr); g_assert(SP_IS_FILTER(f)); g_assert(b != nullptr); @@ -249,14 +241,13 @@ new_filter_gaussian_blur (SPDocument *document, gdouble radius, double expansion return f; } - /** * Creates a simple filter with a blend primitive and a blur primitive of specified radius for * an item with the given matrix expansion, width and height */ -static SPFilter * -new_filter_blend_gaussian_blur (SPDocument *document, const char *blendmode, gdouble radius, double expansion, - double expansionX, double expansionY, double width, double height) +static SPFilter *new_filter_blend_gaussian_blur(SPDocument *document, const char *blendmode, gdouble radius, + double expansion, double expansionX, double expansionY, double width, + double height) { g_return_val_if_fail(document != nullptr, NULL); @@ -269,46 +260,46 @@ new_filter_blend_gaussian_blur (SPDocument *document, const char *blendmode, gdo repr = xml_doc->createElement("svg:filter"); repr->setAttribute("inkscape:collect", "always"); - /* Inkscape now supports both sRGB and linear color-interpolation-filters. - * But, for the moment, keep sRGB as default value for new filters. + /* Inkscape now supports both sRGB and linear color-interpolation-filters. + * But, for the moment, keep sRGB as default value for new filters. * historically set to sRGB and doesn't require conversion between * filter cairo surfaces and other types of cairo surfaces. lp:1127103 */ - SPCSSAttr *css = sp_repr_css_attr_new(); - sp_repr_css_set_property(css, "color-interpolation-filters", "sRGB"); - sp_repr_css_change(repr, css, "style"); + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "color-interpolation-filters", "sRGB"); + sp_repr_css_change(repr, css, "style"); sp_repr_css_attr_unref(css); // Append the new filter node to defs defs->appendChild(repr); Inkscape::GC::release(repr); - + // get corresponding object - SPFilter *f = SP_FILTER( document->getObjectByRepr(repr) ); + SPFilter *f = SP_FILTER(document->getObjectByRepr(repr)); // Gaussian blur primitive - if(radius != 0) { + if (radius != 0) { set_filter_area(repr, radius, expansion, expansionX, expansionY, width, height); - //create feGaussianBlur node + // create feGaussianBlur node Inkscape::XML::Node *b_repr; b_repr = xml_doc->createElement("svg:feGaussianBlur"); b_repr->setAttribute("inkscape:collect", "always"); - + double stdDeviation = radius; if (expansion != 0) stdDeviation /= expansion; - - //set stdDeviation attribute + + // set stdDeviation attribute sp_repr_set_svg_double(b_repr, "stdDeviation", stdDeviation); - - //set feGaussianBlur as child of filter node + + // set feGaussianBlur as child of filter node repr->appendChild(b_repr); Inkscape::GC::release(b_repr); - SPGaussianBlur *b = SP_GAUSSIANBLUR( document->getObjectByRepr(b_repr) ); + SPGaussianBlur *b = SP_GAUSSIANBLUR(document->getObjectByRepr(b_repr)); g_assert(b != nullptr); g_assert(SP_IS_GAUSSIANBLUR(b)); } // Blend primitive - if(strcmp(blendmode, "normal")) { + if (strcmp(blendmode, "normal")) { Inkscape::XML::Node *b_repr; b_repr = xml_doc->createElement("svg:feBlend"); b_repr->setAttribute("inkscape:collect", "always"); @@ -329,10 +320,10 @@ new_filter_blend_gaussian_blur (SPDocument *document, const char *blendmode, gdo g_assert(b != nullptr); g_assert(SP_IS_FEBLEND(b)); } - + g_assert(f != nullptr); g_assert(SP_IS_FILTER(f)); - + return f; } @@ -340,8 +331,7 @@ new_filter_blend_gaussian_blur (SPDocument *document, const char *blendmode, gdo * Creates a simple filter for the given item with blend and blur primitives, using the * specified mode and radius, respectively */ -SPFilter * -new_filter_simple_from_item (SPDocument *document, SPItem *item, const char *mode, gdouble radius) +SPFilter *new_filter_simple_from_item(SPDocument *document, SPItem *item, const char *mode, gdouble radius) { Geom::OptRect const r = item->desktopGeometricBounds(); @@ -349,14 +339,15 @@ new_filter_simple_from_item (SPDocument *document, SPItem *item, const char *mod double height; if (r) { width = r->dimensions()[Geom::X]; - height= r->dimensions()[Geom::Y]; + height = r->dimensions()[Geom::Y]; } else { width = height = 0; } - Geom::Affine i2dt (item->i2dt_affine () ); + Geom::Affine i2dt(item->i2dt_affine()); - return (new_filter_blend_gaussian_blur (document, mode, radius, i2dt.descrim(), i2dt.expansionX(), i2dt.expansionY(), width, height)); + return (new_filter_blend_gaussian_blur(document, mode, radius, i2dt.descrim(), i2dt.expansionX(), i2dt.expansionY(), + width, height)); } /** @@ -368,8 +359,7 @@ new_filter_simple_from_item (SPDocument *document, SPItem *item, const char *mod * duplicated, so that other elements referring that filter are not modified. */ /* TODO: this should be made more generic, not just for blurs */ -SPFilter *modify_filter_gaussian_blur_from_item(SPDocument *document, SPItem *item, - gdouble radius) +SPFilter *modify_filter_gaussian_blur_from_item(SPDocument *document, SPItem *item, gdouble radius) { if (!item->style || !item->style->filter.set) { return new_filter_simple_from_item(document, item, "normal", radius); @@ -389,12 +379,12 @@ SPFilter *modify_filter_gaussian_blur_from_item(SPDocument *document, SPItem *it SPDefs *defs = document->getDefs(); defs->appendChild(repr); - filter = SP_FILTER( document->getObjectByRepr(repr) ); + filter = SP_FILTER(document->getObjectByRepr(repr)); Inkscape::GC::release(repr); } // Determine the required standard deviation value - Geom::Affine i2d (item->i2dt_affine ()); + Geom::Affine i2d(item->i2dt_affine()); double expansion = i2d.descrim(); double stdDeviation = radius; if (expansion != 0) @@ -406,23 +396,21 @@ SPFilter *modify_filter_gaussian_blur_from_item(SPDocument *document, SPItem *it double height; if (r) { width = r->dimensions()[Geom::X]; - height= r->dimensions()[Geom::Y]; + height = r->dimensions()[Geom::Y]; } else { width = height = 0; } // Set the filter effects area Inkscape::XML::Node *repr = item->style->getFilter()->getRepr(); - set_filter_area(repr, radius, expansion, i2d.expansionX(), - i2d.expansionY(), width, height); + set_filter_area(repr, radius, expansion, i2d.expansionX(), i2d.expansionY(), width, height); // Search for gaussian blur primitives. If found, set the stdDeviation // of the first one and return. Inkscape::XML::Node *primitive = repr->firstChild(); while (primitive) { if (strcmp("svg:feGaussianBlur", primitive->name()) == 0) { - sp_repr_set_svg_double(primitive, "stdDeviation", - stdDeviation); + sp_repr_set_svg_double(primitive, "stdDeviation", stdDeviation); return filter; } primitive = primitive->next(); @@ -430,22 +418,22 @@ SPFilter *modify_filter_gaussian_blur_from_item(SPDocument *document, SPItem *it // If there were no gaussian blur primitives, create a new one - //create feGaussianBlur node + // create feGaussianBlur node Inkscape::XML::Node *b_repr; b_repr = xml_doc->createElement("svg:feGaussianBlur"); - //b_repr->setAttribute("inkscape:collect", "always"); - - //set stdDeviation attribute + // b_repr->setAttribute("inkscape:collect", "always"); + + // set stdDeviation attribute sp_repr_set_svg_double(b_repr, "stdDeviation", stdDeviation); - - //set feGaussianBlur as child of filter node + + // set feGaussianBlur as child of filter node filter->getRepr()->appendChild(b_repr); Inkscape::GC::release(b_repr); return filter; } -void remove_filter (SPObject *item, bool recursive) +void remove_filter(SPObject *item, bool recursive) { SPCSSAttr *css = sp_repr_css_attr_new(); sp_repr_css_unset_property(css, "filter"); @@ -464,7 +452,7 @@ void remove_filter (SPObject *item, bool recursive) /* TODO: the removed filter primitive may had had a named result image, so * after removing, the filter may be in erroneous state, this situation should * be handled gracefully */ -void remove_filter_gaussian_blur (SPObject *item) +void remove_filter_gaussian_blur(SPObject *item) { if (item->style && item->style->filter.set && item->style->getFilter()) { // Search for the first blur primitive and remove it. (if found) @@ -505,7 +493,7 @@ void remove_filter_legacy_blend(SPObject *item) size_t total = 0; // determine whether filter is simple (blend and/or blur) or complex SPFeBlend *blend = nullptr; - for (auto &primitive_obj:item->style->getFilter()->children) { + for (auto &primitive_obj : item->style->getFilter()->children) { SPFilterPrimitive *primitive = dynamic_cast(&primitive_obj); if (primitive) { if (dynamic_cast(primitive)) { @@ -528,7 +516,7 @@ void remove_filter_legacy_blend(SPObject *item) } /** - * Get if the filter have a < 1.0 blending filter + * Get if the filter have a < 1.0 blending filter * @params: the item to get filtered blend */ SPBlendMode filter_get_legacy_blend(SPObject *item) @@ -543,7 +531,7 @@ SPBlendMode filter_get_legacy_blend(SPObject *item) size_t blendcount = 0; size_t total = 0; // determine whether filter is simple (blend and/or blur) or complex - for (auto &primitive_obj:item->style->getFilter()->children) { + for (auto &primitive_obj : item->style->getFilter()->children) { SPFilterPrimitive *primitive = dynamic_cast(&primitive_obj); if (primitive) { SPFeBlend *spblend = dynamic_cast(primitive); @@ -567,15 +555,12 @@ SPBlendMode filter_get_legacy_blend(SPObject *item) bool filter_is_single_gaussian_blur(SPFilter *filter) { - return (filter->children.size() == 1 && - SP_IS_GAUSSIANBLUR(&filter->children.front())); + return (filter->children.size() == 1 && SP_IS_GAUSSIANBLUR(&filter->children.front())); } double get_single_gaussian_blur_radius(SPFilter *filter) { - if (filter->children.size() == 1 && - SP_IS_GAUSSIANBLUR(&filter->children.front())) { - + if (filter->children.size() == 1 && SP_IS_GAUSSIANBLUR(&filter->children.front())) { SPGaussianBlur *gb = SP_GAUSSIANBLUR(filter->firstChild()); double x = gb->stdDeviation.getNumber(); double y = gb->stdDeviation.getOptNumber(); @@ -587,8 +572,6 @@ double get_single_gaussian_blur_radius(SPFilter *filter) return 0.0; } - - /* Local Variables: mode:c++ diff --git a/src/filter-chemistry.h b/src/filter-chemistry.h index de25cb640033cf547371b0a1e54245b4be434227..0b874a58159f3d31dee4193793deffc1b9be0bf8 100644 --- a/src/filter-chemistry.h +++ b/src/filter-chemistry.h @@ -25,12 +25,13 @@ class SPItem; class SPObject; SPFilterPrimitive *filter_add_primitive(SPFilter *filter, Inkscape::Filters::FilterPrimitiveType); -SPFilter *new_filter (SPDocument *document); -SPFilter *new_filter_gaussian_blur (SPDocument *document, double stdDeviation, double expansion, double expansionX, double expansionY, double width, double height); -SPFilter *new_filter_simple_from_item (SPDocument *document, SPItem *item, const char *mode, double stdDeviation); -SPFilter *modify_filter_gaussian_blur_from_item (SPDocument *document, SPItem *item, double stdDeviation); -void remove_filter (SPObject *item, bool recursive); -void remove_filter_gaussian_blur (SPObject *item); +SPFilter *new_filter(SPDocument *document); +SPFilter *new_filter_gaussian_blur(SPDocument *document, double stdDeviation, double expansion, double expansionX, + double expansionY, double width, double height); +SPFilter *new_filter_simple_from_item(SPDocument *document, SPItem *item, const char *mode, double stdDeviation); +SPFilter *modify_filter_gaussian_blur_from_item(SPDocument *document, SPItem *item, double stdDeviation); +void remove_filter(SPObject *item, bool recursive); +void remove_filter_gaussian_blur(SPObject *item); void remove_filter_legacy_blend(SPObject *item); SPBlendMode filter_get_legacy_blend(SPObject *item); bool filter_is_single_gaussian_blur(SPFilter *filter); diff --git a/src/filter-enums.cpp b/src/filter-enums.cpp index 41e26b4f5ba5af83a6f4821f7e312f50c3908a85..765a7811e9ebcccd095678e9d375d5e365387fad 100644 --- a/src/filter-enums.cpp +++ b/src/filter-enums.cpp @@ -10,11 +10,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "filter-enums.h" + #include #include -#include "filter-enums.h" - using Inkscape::Util::EnumData; using Inkscape::Util::EnumDataConverter; @@ -38,7 +38,8 @@ const EnumData FPData[Inkscape::Filters: {Inkscape::Filters::NR_FILTER_TURBULENCE, _("Turbulence"), "svg:feTurbulence"} // clang-format on }; -const EnumDataConverter FPConverter(FPData, Inkscape::Filters::NR_FILTER_ENDPRIMITIVETYPE); +const EnumDataConverter + FPConverter(FPData, Inkscape::Filters::NR_FILTER_ENDPRIMITIVETYPE); const EnumData FPInputData[FPINPUT_END] = { // clang-format off @@ -60,7 +61,8 @@ const EnumData ColorMatrixTypeData[Ink {Inkscape::Filters::COLORMATRIX_LUMINANCETOALPHA, _("Luminance to Alpha"), "luminanceToAlpha"} // clang-format on }; -const EnumDataConverter ColorMatrixTypeConverter(ColorMatrixTypeData, Inkscape::Filters::COLORMATRIX_ENDTYPE); +const EnumDataConverter + ColorMatrixTypeConverter(ColorMatrixTypeData, Inkscape::Filters::COLORMATRIX_ENDTYPE); // feComposite const EnumData CompositeOperatorData[COMPOSITE_ENDOPERATOR] = { @@ -88,26 +90,30 @@ const EnumData CompositeOperatorData[COMPOSITE_ENDOPERATOR] const EnumDataConverter CompositeOperatorConverter(CompositeOperatorData, COMPOSITE_ENDOPERATOR); // feComponentTransfer -const EnumData ComponentTransferTypeData[Inkscape::Filters::COMPONENTTRANSFER_TYPE_ERROR] = { - // clang-format off +const EnumData + ComponentTransferTypeData[Inkscape::Filters::COMPONENTTRANSFER_TYPE_ERROR] = { + // clang-format off {Inkscape::Filters::COMPONENTTRANSFER_TYPE_IDENTITY, _("Identity"), "identity"}, {Inkscape::Filters::COMPONENTTRANSFER_TYPE_TABLE, _("Table"), "table"}, {Inkscape::Filters::COMPONENTTRANSFER_TYPE_DISCRETE, _("Discrete"), "discrete"}, {Inkscape::Filters::COMPONENTTRANSFER_TYPE_LINEAR, _("Linear"), "linear"}, {Inkscape::Filters::COMPONENTTRANSFER_TYPE_GAMMA, _("Gamma"), "gamma"}, - // clang-format on + // clang-format on }; -const EnumDataConverter ComponentTransferTypeConverter(ComponentTransferTypeData, Inkscape::Filters::COMPONENTTRANSFER_TYPE_ERROR); +const EnumDataConverter + ComponentTransferTypeConverter(ComponentTransferTypeData, Inkscape::Filters::COMPONENTTRANSFER_TYPE_ERROR); // feConvolveMatrix -const EnumData ConvolveMatrixEdgeModeData[Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_ENDTYPE] = { - // clang-format off +const EnumData + ConvolveMatrixEdgeModeData[Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_ENDTYPE] = { + // clang-format off {Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_DUPLICATE, _("Duplicate"), "duplicate"}, {Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_WRAP, _("Wrap"), "wrap"}, {Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_NONE, C_("Convolve matrix, edge mode", "None"), "none"} - // clang-format on + // clang-format on }; -const EnumDataConverter ConvolveMatrixEdgeModeConverter(ConvolveMatrixEdgeModeData, Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_ENDTYPE); +const EnumDataConverter + ConvolveMatrixEdgeModeConverter(ConvolveMatrixEdgeModeData, Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_ENDTYPE); // feDisplacementMap const EnumData DisplacementMapChannelData[DISPLACEMENTMAP_CHANNEL_ENDTYPE] = { @@ -118,16 +124,19 @@ const EnumData DisplacementMapChannelData[ {DISPLACEMENTMAP_CHANNEL_ALPHA, _("Alpha"), "A"} // clang-format on }; -const EnumDataConverter DisplacementMapChannelConverter(DisplacementMapChannelData, DISPLACEMENTMAP_CHANNEL_ENDTYPE); +const EnumDataConverter + DisplacementMapChannelConverter(DisplacementMapChannelData, DISPLACEMENTMAP_CHANNEL_ENDTYPE); // feMorphology -const EnumData MorphologyOperatorData[Inkscape::Filters::MORPHOLOGY_OPERATOR_END] = { - // clang-format off +const EnumData + MorphologyOperatorData[Inkscape::Filters::MORPHOLOGY_OPERATOR_END] = { + // clang-format off {Inkscape::Filters::MORPHOLOGY_OPERATOR_ERODE, _("Erode"), "erode"}, {Inkscape::Filters::MORPHOLOGY_OPERATOR_DILATE, _("Dilate"), "dilate"} - // clang-format on + // clang-format on }; -const EnumDataConverter MorphologyOperatorConverter(MorphologyOperatorData, Inkscape::Filters::MORPHOLOGY_OPERATOR_END); +const EnumDataConverter + MorphologyOperatorConverter(MorphologyOperatorData, Inkscape::Filters::MORPHOLOGY_OPERATOR_END); // feTurbulence const EnumData TurbulenceTypeData[Inkscape::Filters::TURBULENCE_ENDTYPE] = { @@ -136,7 +145,8 @@ const EnumData TurbulenceTypeData[Inksc {Inkscape::Filters::TURBULENCE_TURBULENCE, _("Turbulence"), "turbulence"} // clang-format on }; -const EnumDataConverter TurbulenceTypeConverter(TurbulenceTypeData, Inkscape::Filters::TURBULENCE_ENDTYPE); +const EnumDataConverter + TurbulenceTypeConverter(TurbulenceTypeData, Inkscape::Filters::TURBULENCE_ENDTYPE); // Light source const EnumData LightSourceData[LIGHT_ENDSOURCE] = { diff --git a/src/filter-enums.h b/src/filter-enums.h index 613634615abed47fa98cb06cd27b29f44c08fd0f..10015458c3efc16028ab9bea25f97389557aa98f 100644 --- a/src/filter-enums.h +++ b/src/filter-enums.h @@ -25,10 +25,12 @@ #include "util/enums.h" // Filter primitives -extern const Inkscape::Util::EnumData FPData[Inkscape::Filters::NR_FILTER_ENDPRIMITIVETYPE]; +extern const Inkscape::Util::EnumData + FPData[Inkscape::Filters::NR_FILTER_ENDPRIMITIVETYPE]; extern const Inkscape::Util::EnumDataConverter FPConverter; -enum FilterPrimitiveInput { +enum FilterPrimitiveInput +{ FPINPUT_SOURCEGRAPHIC, FPINPUT_SOURCEALPHA, FPINPUT_BACKGROUNDIMAGE, @@ -42,28 +44,36 @@ extern const Inkscape::Util::EnumData FPInputData[FPINPUT_ extern const Inkscape::Util::EnumDataConverter FPInputConverter; // ColorMatrix type -extern const Inkscape::Util::EnumData ColorMatrixTypeData[Inkscape::Filters::COLORMATRIX_ENDTYPE]; +extern const Inkscape::Util::EnumData + ColorMatrixTypeData[Inkscape::Filters::COLORMATRIX_ENDTYPE]; extern const Inkscape::Util::EnumDataConverter ColorMatrixTypeConverter; // ComponentTransfer type -extern const Inkscape::Util::EnumData ComponentTransferTypeData[Inkscape::Filters::COMPONENTTRANSFER_TYPE_ERROR]; -extern const Inkscape::Util::EnumDataConverter ComponentTransferTypeConverter; +extern const Inkscape::Util::EnumData + ComponentTransferTypeData[Inkscape::Filters::COMPONENTTRANSFER_TYPE_ERROR]; +extern const Inkscape::Util::EnumDataConverter + ComponentTransferTypeConverter; // Composite operator extern const Inkscape::Util::EnumData CompositeOperatorData[COMPOSITE_ENDOPERATOR]; extern const Inkscape::Util::EnumDataConverter CompositeOperatorConverter; // ConvolveMatrix edgeMode -extern const Inkscape::Util::EnumData ConvolveMatrixEdgeModeData[Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_ENDTYPE]; -extern const Inkscape::Util::EnumDataConverter ConvolveMatrixEdgeModeConverter; +extern const Inkscape::Util::EnumData + ConvolveMatrixEdgeModeData[Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_ENDTYPE]; +extern const Inkscape::Util::EnumDataConverter + ConvolveMatrixEdgeModeConverter; // DisplacementMap channel extern const Inkscape::Util::EnumData DisplacementMapChannelData[4]; extern const Inkscape::Util::EnumDataConverter DisplacementMapChannelConverter; // Morphology operator -extern const Inkscape::Util::EnumData MorphologyOperatorData[Inkscape::Filters::MORPHOLOGY_OPERATOR_END]; +extern const Inkscape::Util::EnumData + MorphologyOperatorData[Inkscape::Filters::MORPHOLOGY_OPERATOR_END]; extern const Inkscape::Util::EnumDataConverter MorphologyOperatorConverter; // Turbulence type -extern const Inkscape::Util::EnumData TurbulenceTypeData[Inkscape::Filters::TURBULENCE_ENDTYPE]; +extern const Inkscape::Util::EnumData + TurbulenceTypeData[Inkscape::Filters::TURBULENCE_ENDTYPE]; extern const Inkscape::Util::EnumDataConverter TurbulenceTypeConverter; // Lighting -enum LightSource { +enum LightSource +{ LIGHT_DISTANT, LIGHT_POINT, LIGHT_SPOT, diff --git a/src/gc-anchored.cpp b/src/gc-anchored.cpp index 12eaa831938cbad9074f0b65dffe42c7c83c7cbe..c4d40a49eb0bdb80b47414aed9e9af7f391fb97f 100644 --- a/src/gc-anchored.cpp +++ b/src/gc-anchored.cpp @@ -10,11 +10,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "gc-anchored.h" + +#include + +#include "debug/demangle.h" #include "debug/event-tracker.h" #include "debug/simple-event.h" -#include "debug/demangle.h" #include "util/format.h" namespace Inkscape { @@ -25,11 +27,11 @@ namespace { typedef Debug::SimpleEvent RefCountEvent; -class BaseAnchorEvent : public RefCountEvent { +class BaseAnchorEvent : public RefCountEvent +{ public: - BaseAnchorEvent(Anchored const *object, int bias, - char const *name) - : RefCountEvent(name) + BaseAnchorEvent(Anchored const *object, int bias, char const *name) + : RefCountEvent(name) { _addProperty("base", Util::format("%p", Core::base(const_cast(object))).pointer()); _addProperty("pointer", Util::format("%p", object).pointer()); @@ -38,31 +40,36 @@ public: } }; -class AnchorEvent : public BaseAnchorEvent { +class AnchorEvent : public BaseAnchorEvent +{ public: AnchorEvent(Anchored const *object) - : BaseAnchorEvent(object, 1, "gc-anchor") + : BaseAnchorEvent(object, 1, "gc-anchor") {} }; -class ReleaseEvent : public BaseAnchorEvent { +class ReleaseEvent : public BaseAnchorEvent +{ public: ReleaseEvent(Anchored const *object) - : BaseAnchorEvent(object, -1, "gc-release") + : BaseAnchorEvent(object, -1, "gc-release") {} }; -} +} // namespace -Anchored::Anchor *Anchored::_new_anchor() const { +Anchored::Anchor *Anchored::_new_anchor() const +{ return new Anchor(this); } -void Anchored::_free_anchor(Anchored::Anchor *anchor) const { +void Anchored::_free_anchor(Anchored::Anchor *anchor) const +{ delete anchor; } -void Anchored::anchor() const { +void Anchored::anchor() const +{ Debug::EventTracker tracker(this); if (!_anchor) { _anchor = _new_anchor(); @@ -70,7 +77,8 @@ void Anchored::anchor() const { _anchor->refcount++; } -void Anchored::release() const { +void Anchored::release() const +{ Debug::EventTracker tracker(this); g_return_if_fail(_anchor); if (!--_anchor->refcount) { @@ -79,9 +87,9 @@ void Anchored::release() const { } } -} +} // namespace GC -} +} // namespace Inkscape /* Local Variables: diff --git a/src/gc-anchored.h b/src/gc-anchored.h index 8a7b2d765c45eeddf847aa0baabd239faabc25b2..8e20f6745b0b08f3c0eccf7c6e58ef0350c9547c 100644 --- a/src/gc-anchored.h +++ b/src/gc-anchored.h @@ -17,9 +17,9 @@ namespace Inkscape { namespace GC { /** - * A base class for anchored objects. + * A base class for anchored objects. * - * Objects are managed by our mark-and-sweep collector, but are anchored + * Objects are managed by our mark-and-sweep collector, but are anchored * against garbage collection so long as their reference count is nonzero. * * Object and member destructors will not be called on destruction @@ -45,27 +45,36 @@ namespace GC { * @see Inkscape::GC::release */ -class Anchored { +class Anchored +{ public: void anchor() const; void release() const; // for debugging - unsigned _anchored_refcount() const { - return ( _anchor ? _anchor->refcount : 0 ); - } + unsigned _anchored_refcount() const { return (_anchor ? _anchor->refcount : 0); } - Anchored(Anchored const &) = delete; // no copy + Anchored(Anchored const &) = delete; // no copy void operator=(Anchored const &) = delete; // no assign protected: - Anchored() : _anchor(nullptr) { anchor(); } // initial refcount of one + Anchored() + : _anchor(nullptr) + { + anchor(); + } // initial refcount of one virtual ~Anchored() = default; private: - struct Anchor : public Managed { - Anchor() : refcount(0),base(nullptr) {} - Anchor(Anchored const *obj) : refcount(0) { + struct Anchor : public Managed + { + Anchor() + : refcount(0) + , base(nullptr) + {} + Anchor(Anchored const *obj) + : refcount(0) + { base = Core::base(const_cast(obj)); } int refcount; @@ -91,7 +100,8 @@ private: * @return the reference to the object */ template -static R &anchor(R &r) { +static R &anchor(R &r) +{ static_cast(const_cast(r)).anchor(); return r; } @@ -109,7 +119,8 @@ static R &anchor(R &r) { * @return the pointer to the object */ template -static R *anchor(R *r) { +static R *anchor(R *r) +{ static_cast(const_cast(r))->anchor(); return r; } @@ -132,7 +143,8 @@ static R *anchor(R *r) { * @return the reference to the object */ template -static R &release(R &r) { +static R &release(R &r) +{ static_cast(const_cast(r)).release(); return r; } @@ -155,14 +167,15 @@ static R &release(R &r) { * @return the pointer to the object */ template -static R *release(R *r) { +static R *release(R *r) +{ static_cast(const_cast(r))->release(); return r; } -} +} // namespace GC -} +} // namespace Inkscape #endif /* diff --git a/src/gc-finalized.cpp b/src/gc-finalized.cpp index 8bba510d29767cae98b01a696313b1a3dbc5be0b..3ef0e190fb2d3d4116783b9d8709dea74c178529 100644 --- a/src/gc-finalized.cpp +++ b/src/gc-finalized.cpp @@ -22,11 +22,13 @@ * */ +#include "gc-finalized.h" + #include -#include "debug/simple-event.h" + #include "debug/event-tracker.h" +#include "debug/simple-event.h" #include "util/format.h" -#include "gc-finalized.h" namespace Inkscape { @@ -37,10 +39,11 @@ namespace { // workaround for g++ 4.0.2 typedef Debug::SimpleEvent BaseEvent; -class FinalizerEvent : public BaseEvent { +class FinalizerEvent : public BaseEvent +{ public: FinalizerEvent(Finalized *object) - : BaseEvent("gc-finalizer") + : BaseEvent("gc-finalizer") { _addProperty("base", Util::format("%p", Core::base(object)).pointer()); _addProperty("pointer", Util::format("%p", object).pointer()); @@ -48,17 +51,18 @@ public: } }; -} +} // namespace -void Finalized::_invoke_dtor(void *base, void *offset) { - Finalized *object=_unoffset(base, offset); +void Finalized::_invoke_dtor(void *base, void *offset) +{ + Finalized *object = _unoffset(base, offset); Debug::EventTracker tracker(object); object->~Finalized(); } -} +} // namespace GC -} +} // namespace Inkscape /* Local Variables: diff --git a/src/gc-finalized.h b/src/gc-finalized.h index 6bd702cf82fc678b6e552dd20ceb07d77fb70558..21f91c8910f48f919bed6593fcbee5fa32d609fa 100644 --- a/src/gc-finalized.h +++ b/src/gc-finalized.h @@ -14,8 +14,9 @@ #ifndef SEEN_INKSCAPE_GC_FINALIZED_H #define SEEN_INKSCAPE_GC_FINALIZED_H -#include #include +#include + #include "inkgc/gc-core.h" namespace Inkscape { @@ -28,7 +29,7 @@ namespace GC { * Normally, the garbage collector does not call destructors before destroying * an object. On construction, this "mix-in" will register a finalizer * function to call destructors before derived objects are destroyed. - * + * * This works pretty well, with the following caveats: * * 1. The garbage collector uses strictly topologically-ordered @@ -61,10 +62,12 @@ namespace GC { * collected, unless you register the finalizer yourself (by "member" * we mean an actual by-value member, not a reference or a pointer). */ -class Finalized { +class Finalized +{ public: - Finalized() { - void *base=Core::base(this); + Finalized() + { + void *base = Core::base(this); if (base) { // only if we are managed by the collector CleanupFunc old_cleanup; void *old_data; @@ -74,9 +77,7 @@ public: // ourselves would pin us forever and prevent us from being // finalized; instead we use an offset-from-base-address - Core::register_finalizer_ignore_self(base, _invoke_dtor, - _offset(base, this), - &old_cleanup, &old_data); + Core::register_finalizer_ignore_self(base, _invoke_dtor, _offset(base, this), &old_cleanup, &old_data); if (old_cleanup) { // If there was already a finalizer registered for our @@ -93,19 +94,17 @@ public: // It's also possible that a member's constructor was called // after ours (e.g. via placement new). Don't do that. - if ( old_cleanup != _invoke_dtor ) { - Core::register_finalizer_ignore_self(base, - old_cleanup, old_data, - nullptr, nullptr); + if (old_cleanup != _invoke_dtor) { + Core::register_finalizer_ignore_self(base, old_cleanup, old_data, nullptr, nullptr); } } } } - virtual ~Finalized() { + virtual ~Finalized() + { // make sure the destructor won't get invoked twice - Core::register_finalizer_ignore_self(Core::base(this), - nullptr, nullptr, nullptr, nullptr); + Core::register_finalizer_ignore_self(Core::base(this), nullptr, nullptr, nullptr, nullptr); } private: @@ -113,23 +112,20 @@ private: static void _invoke_dtor(void *base, void *offset); /// turn 'this' pointer into an offset-from-base-address (stored as void *) - static void *_offset(void *base, Finalized *self) { - return reinterpret_cast( - reinterpret_cast(self) - reinterpret_cast(base) - ); + static void *_offset(void *base, Finalized *self) + { + return reinterpret_cast(reinterpret_cast(self) - reinterpret_cast(base)); } /// reconstitute 'this' given an offset-from-base-address in a void * - static Finalized *_unoffset(void *base, void *offset) { - return reinterpret_cast( - reinterpret_cast(base) + - reinterpret_cast(offset) - ); + static Finalized *_unoffset(void *base, void *offset) + { + return reinterpret_cast(reinterpret_cast(base) + reinterpret_cast(offset)); } }; -} +} // namespace GC -} +} // namespace Inkscape #endif /* diff --git a/src/gradient-chemistry.cpp b/src/gradient-chemistry.cpp index f568e3a17e6cce440ab0e6a7999dcbca85caf680..1a710f3f08b8c0c9d48c693e721fe49fb740f836 100644 --- a/src/gradient-chemistry.cpp +++ b/src/gradient-chemistry.cpp @@ -19,21 +19,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "gradient-chemistry.h" -#include <2geom/transforms.h> #include <2geom/bezier-curve.h> #include <2geom/crossing.h> #include <2geom/line.h> +#include <2geom/transforms.h> +#include #include "desktop-style.h" #include "desktop.h" #include "document-undo.h" -#include "gradient-chemistry.h" #include "gradient-drag.h" -#include "selection.h" -#include "verbs.h" - #include "object/sp-defs.h" #include "object/sp-gradient-reference.h" #include "object/sp-linear-gradient.h" @@ -42,15 +39,14 @@ #include "object/sp-stop.h" #include "object/sp-text.h" #include "object/sp-tspan.h" +#include "selection.h" #include "style.h" - -#include "svg/svg.h" -#include "svg/svg-color.h" #include "svg/css-ostringstream.h" - +#include "svg/svg-color.h" +#include "svg/svg.h" #include "ui/tools/tool-base.h" - #include "ui/widget/gradient-vector-selector.h" +#include "verbs.h" #define noSP_GR_VERBOSE @@ -60,7 +56,8 @@ namespace { Inkscape::PaintTarget paintTargetItems[] = {Inkscape::FOR_FILL, Inkscape::FOR_STROKE}; -std::vector vectorOfPaintTargets(paintTargetItems, paintTargetItems + (sizeof(paintTargetItems) / sizeof(paintTargetItems[0]))); +std::vector + vectorOfPaintTargets(paintTargetItems, paintTargetItems + (sizeof(paintTargetItems) / sizeof(paintTargetItems[0]))); } // namespace @@ -99,24 +96,26 @@ SPGradient *sp_gradient_ensure_vector_normalized(SPGradient *gr) g_return_val_if_fail(!SP_IS_MESHGRADIENT(gr), NULL); /* If we are already normalized vector, just return */ - if (gr->state == SP_GRADIENT_STATE_VECTOR) return gr; + if (gr->state == SP_GRADIENT_STATE_VECTOR) + return gr; /* Fail, if we have wrong state set */ if (gr->state != SP_GRADIENT_STATE_UNKNOWN) { - g_warning("file %s: line %d: Cannot normalize private gradient to vector (%s)", __FILE__, __LINE__, gr->getId()); + g_warning("file %s: line %d: Cannot normalize private gradient to vector (%s)", __FILE__, __LINE__, + gr->getId()); return nullptr; } /* First make sure we have vector directly defined (i.e. gr has its own stops) */ - if ( !gr->hasStops() ) { + if (!gr->hasStops()) { /* We do not have stops ourselves, so flatten stops as well */ gr->ensureVector(); g_assert(gr->vector.built); // this adds stops from gr->vector as children to gr - gr->repr_write_vector (); + gr->repr_write_vector(); } /* If gr hrefs some other gradient, remove the href */ - if (gr->ref){ + if (gr->ref) { if (gr->ref->getObject()) { // We are hrefing someone, so require flattening gr->updateRepr(SP_OBJECT_WRITE_EXT | SP_OBJECT_WRITE_ALL); @@ -151,7 +150,7 @@ static SPGradient *sp_gradient_get_private_normalized(SPDocument *document, SPGr Inkscape::XML::Node *repr; if (type == SP_GRADIENT_TYPE_LINEAR) { repr = xml_doc->createElement("svg:linearGradient"); - } else if(type == SP_GRADIENT_TYPE_RADIAL) { + } else if (type == SP_GRADIENT_TYPE_RADIAL) { repr = xml_doc->createElement("svg:radialGradient"); } else { repr = xml_doc->createElement("svg:meshgradient"); @@ -186,34 +185,27 @@ static guint count_gradient_hrefs(SPObject *o, SPGradient *gr) guint i = 0; SPStyle *style = o->style; - if (style - && style->fill.isPaintserver() - && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) - && SP_GRADIENT(SP_STYLE_FILL_SERVER(style)) == gr) - { - i ++; + if (style && style->fill.isPaintserver() && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) && + SP_GRADIENT(SP_STYLE_FILL_SERVER(style)) == gr) { + i++; } - if (style - && style->stroke.isPaintserver() - && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) - && SP_GRADIENT(SP_STYLE_STROKE_SERVER(style)) == gr) - { - i ++; + if (style && style->stroke.isPaintserver() && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) && + SP_GRADIENT(SP_STYLE_STROKE_SERVER(style)) == gr) { + i++; } - for (auto& child: o->children) { + for (auto &child : o->children) { i += count_gradient_hrefs(&child, gr); } return i; } - /** * If gr has other users, create a new shared; also check if gr links to shared, relink if not */ -static SPGradient *sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradient *shared, - SPGradientType type, SPObject *o) +static SPGradient *sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradient *shared, SPGradientType type, + SPObject *o) { #ifdef SP_GR_VERBOSE g_message("sp_gradient_fork_private_if_necessary(%p, %p, %d, %p)", gr, shared, type, o); @@ -223,7 +215,7 @@ static SPGradient *sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradi // Orphaned gradient, no shared with stops or patches at the end of the line; this used to be // an assert - if ( !shared || !(shared->hasStops() || shared->hasPatches()) ) { + if (!shared || !(shared->hasStops() || shared->hasPatches())) { std::cerr << "sp_gradient_fork_private_if_necessary: Orphaned gradient" << std::endl; return (gr); } @@ -240,7 +232,7 @@ static SPGradient *sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradi // if we are private and there are no other users, if (!shared->isSwatch() && (gr->hrefcount <= count_gradient_hrefs(user, gr))) { // check shared - if ( gr != shared && gr->ref->getObject() != shared ) { + if (gr != shared && gr->ref->getObject() != shared) { /* our href is not the shared, and shared is different from gr; relink */ sp_gradient_repr_set_link(gr->getRepr(), shared); } @@ -250,12 +242,8 @@ static SPGradient *sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradi SPDocument *doc = gr->document; SPObject *defs = doc->getDefs(); - if ((gr->hasStops()) || - (gr->hasPatches()) || - (gr->state != SP_GRADIENT_STATE_UNKNOWN) || - (gr->parent != SP_OBJECT(defs)) || - (gr->hrefcount > 1)) { - + if ((gr->hasStops()) || (gr->hasPatches()) || (gr->state != SP_GRADIENT_STATE_UNKNOWN) || + (gr->parent != SP_OBJECT(defs)) || (gr->hrefcount > 1)) { // we have to clone a fresh new private gradient for the given shared // create an empty one @@ -271,7 +259,7 @@ static SPGradient *sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradi repr_new->setAttribute("cy", repr->attribute("cy")); repr_new->setAttribute("fx", repr->attribute("fx")); repr_new->setAttribute("fy", repr->attribute("fy")); - repr_new->setAttribute("r", repr->attribute("r" )); + repr_new->setAttribute("r", repr->attribute("r")); repr_new->setAttribute("fr", repr->attribute("fr")); repr_new->setAttribute("spreadMethod", repr->attribute("spreadMethod")); } else if (SP_IS_LINEARGRADIENT(gr)) { @@ -287,10 +275,10 @@ static SPGradient *sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradi // We probably want a completely separate mesh gradient so // copy the children and unset the link to the shared. - for ( Inkscape::XML::Node *child = repr->firstChild() ; child ; child = child->next() ) { + for (Inkscape::XML::Node *child = repr->firstChild(); child; child = child->next()) { Inkscape::XML::Node *copy = child->duplicate(doc->getReprDoc()); - repr_new->appendChild( copy ); - Inkscape::GC::release( copy ); + repr_new->appendChild(copy); + Inkscape::GC::release(copy); } sp_gradient_repr_set_link(repr_new, nullptr); } @@ -317,7 +305,7 @@ SPGradient *sp_gradient_fork_vector_if_necessary(SPGradient *gr) Inkscape::XML::Node *repr = gr->getRepr()->duplicate(xml_doc); doc->getDefs()->getRepr()->addChild(repr, nullptr); SPGradient *gr_new = static_cast(doc->getObjectByRepr(repr)); - gr_new = sp_gradient_ensure_vector_normalized (gr_new); + gr_new = sp_gradient_ensure_vector_normalized(gr_new); Inkscape::GC::release(repr); return gr_new; } @@ -325,7 +313,8 @@ SPGradient *sp_gradient_fork_vector_if_necessary(SPGradient *gr) } /** - * Obtain the vector from the gradient. A forked vector will be created and linked to this gradient if another gradient uses it. + * Obtain the vector from the gradient. A forked vector will be created and linked to this gradient if another gradient + * uses it. */ SPGradient *sp_gradient_get_forked_vector_if_necessary(SPGradient *gradient, bool force_vector) { @@ -333,14 +322,13 @@ SPGradient *sp_gradient_get_forked_vector_if_necessary(SPGradient *gradient, boo g_message("sp_gradient_get_forked_vector_if_necessary(%p, %d)", gradient, force_vector); #endif SPGradient *vector = gradient->getVector(force_vector); - vector = sp_gradient_fork_vector_if_necessary (vector); - if ( gradient != vector && gradient->ref->getObject() != vector ) { + vector = sp_gradient_fork_vector_if_necessary(vector); + if (gradient != vector && gradient->ref->getObject() != vector) { sp_gradient_repr_set_link(gradient->getRepr(), vector); } return vector; } - /** * Convert an item's gradient to userspace _without_ preserving coords, setting them to defaults * instead. No forking or reapplying is done because this is only called for newly created privates. @@ -370,31 +358,27 @@ SPGradient *sp_gradient_reset_to_userspace(SPGradient *gr, SPItem *item) sp_repr_set_svg_double(repr, "cy", center[Geom::Y]); sp_repr_set_svg_double(repr, "fx", center[Geom::X]); sp_repr_set_svg_double(repr, "fy", center[Geom::Y]); - sp_repr_set_svg_double(repr, "r", width/2); + sp_repr_set_svg_double(repr, "r", width / 2); // we want it to be elliptic, not circular - Geom::Affine squeeze = Geom::Translate (-center) * - Geom::Scale(1, height/width) * - Geom::Translate (center); + Geom::Affine squeeze = Geom::Translate(-center) * Geom::Scale(1, height / width) * Geom::Translate(center); gr->gradientTransform = squeeze; { - gchar *c=sp_svg_transform_write(gr->gradientTransform); + gchar *c = sp_svg_transform_write(gr->gradientTransform); gr->setAttribute("gradientTransform", c); g_free(c); } } else if (SP_IS_LINEARGRADIENT(gr)) { - // Assume horizontal gradient by default (as per SVG 1.1) - Geom::Point pStart = center - Geom::Point(width/2, 0); - Geom::Point pEnd = center + Geom::Point(width/2, 0); + Geom::Point pStart = center - Geom::Point(width / 2, 0); + Geom::Point pEnd = center + Geom::Point(width / 2, 0); // Get the preferred gradient angle from prefs Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double angle = prefs->getDouble("/dialogs/gradienteditor/angle", 0.0); if (angle != 0.0) { - Geom::Line grl(center, Geom::rad_from_deg(angle)); Geom::LineSegment bbl1(bbox->corner(0), bbox->corner(1)); Geom::LineSegment bbl2(bbox->corner(1), bbox->corner(2)); @@ -415,7 +399,6 @@ SPGradient *sp_gradient_reset_to_userspace(SPGradient *gr, SPItem *item) std::swap(pStart, pEnd); } } - } sp_repr_set_svg_double(repr, "x1", pStart[Geom::X]); @@ -427,12 +410,12 @@ SPGradient *sp_gradient_reset_to_userspace(SPGradient *gr, SPItem *item) // Mesh // THIS IS BEING CALLED TWICE WHENEVER A NEW GRADIENT IS CREATED, WRITING HERE CAUSES PROBLEMS // IN SPMeshNodeArray::create() - //sp_repr_set_svg_double(repr, "x", bbox->min()[Geom::X]); - //sp_repr_set_svg_double(repr, "y", bbox->min()[Geom::Y]); + // sp_repr_set_svg_double(repr, "x", bbox->min()[Geom::X]); + // sp_repr_set_svg_double(repr, "y", bbox->min()[Geom::Y]); // We don't create a shared array gradient. - SPMeshGradient* mg = SP_MESHGRADIENT( gr ); - mg->array.create( mg, item, bbox ); + SPMeshGradient *mg = SP_MESHGRADIENT(gr); + mg->array.create(mg, item, bbox); } // set the gradientUnits @@ -452,7 +435,7 @@ SPGradient *sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, gchar #endif g_return_val_if_fail(SP_IS_GRADIENT(gr), NULL); - if ( gr && gr->isSolid() ) { + if (gr && gr->isSolid()) { return gr; } @@ -462,21 +445,19 @@ SPGradient *sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, gchar } else if (SP_IS_RADIALGRADIENT(gr)) { gr = sp_gradient_fork_private_if_necessary(gr, gr->getVector(), SP_GRADIENT_TYPE_RADIAL, item); } else { - gr = sp_gradient_fork_private_if_necessary(gr, gr->getArray(), SP_GRADIENT_TYPE_MESH, item); + gr = sp_gradient_fork_private_if_necessary(gr, gr->getArray(), SP_GRADIENT_TYPE_MESH, item); } if (gr->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) { - Inkscape::XML::Node *repr = gr->getRepr(); // calculate the bbox of the item item->document->ensureUpToDate(); Geom::Affine bbox2user; Geom::OptRect bbox = item->visualBounds(); // we need "true" bbox without item_i2d_affine - if ( bbox ) { - bbox2user = Geom::Affine(bbox->dimensions()[Geom::X], 0, - 0, bbox->dimensions()[Geom::Y], - bbox->min()[Geom::X], bbox->min()[Geom::Y]); + if (bbox) { + bbox2user = Geom::Affine(bbox->dimensions()[Geom::X], 0, 0, bbox->dimensions()[Geom::Y], + bbox->min()[Geom::X], bbox->min()[Geom::Y]); } else { // would be degenerate otherwise bbox2user = Geom::identity(); @@ -508,7 +489,7 @@ SPGradient *sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, gchar // apply skew to the gradient gr->gradientTransform = skew; { - gchar *c=sp_svg_transform_write(gr->gradientTransform); + gchar *c = sp_svg_transform_write(gr->gradientTransform); gr->setAttribute("gradientTransform", c); g_free(c); } @@ -557,7 +538,8 @@ SPGradient *sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, gchar repr->setAttribute("gradientUnits", "userSpaceOnUse"); } else { - std::cerr << "sp_gradient_convert_to_userspace: Conversion of mesh to userspace not implemented" << std::endl; + std::cerr << "sp_gradient_convert_to_userspace: Conversion of mesh to userspace not implemented" + << std::endl; } } @@ -587,7 +569,7 @@ void sp_gradient_transform_multiply(SPGradient *gradient, Geom::Affine postmul, } gradient->gradientTransform_set = TRUE; - gchar *c=sp_svg_transform_write(gradient->gradientTransform); + gchar *c = sp_svg_transform_write(gradient->gradientTransform); gradient->setAttribute("gradientTransform", c); g_free(c); } @@ -597,12 +579,11 @@ SPGradient *getGradient(SPItem *item, Inkscape::PaintTarget fill_or_stroke) SPStyle *style = item->style; SPGradient *gradient = nullptr; - switch (fill_or_stroke) - { + switch (fill_or_stroke) { case Inkscape::FOR_FILL: if (style && (style->fill.isPaintserver())) { SPPaintServer *server = item->style->getFillPaintServer(); - if ( SP_IS_GRADIENT(server) ) { + if (SP_IS_GRADIENT(server)) { gradient = SP_GRADIENT(server); } } @@ -610,14 +591,14 @@ SPGradient *getGradient(SPItem *item, Inkscape::PaintTarget fill_or_stroke) case Inkscape::FOR_STROKE: if (style && (style->stroke.isPaintserver())) { SPPaintServer *server = item->style->getStrokePaintServer(); - if ( SP_IS_GRADIENT(server) ) { + if (SP_IS_GRADIENT(server)) { gradient = SP_GRADIENT(server); } } break; } - return gradient; + return gradient; } SPStop *sp_last_stop(SPGradient *gradient) @@ -639,11 +620,10 @@ SPStop *sp_get_stop_i(SPGradient *gradient, guint stop_i) // if this is valid but weird gradient without an offset-zero stop element, // inkscape has created a handle for the start of gradient anyway, // so when it asks for stop N that corresponds to stop element N-1 - if (stop->offset != 0) - { + if (stop->offset != 0) { stop_i--; } - + for (guint i = 0; i < stop_i; i++) { if (!stop) { return nullptr; @@ -656,15 +636,15 @@ SPStop *sp_get_stop_i(SPGradient *gradient, guint stop_i) guint32 average_color(guint32 c1, guint32 c2, gdouble p) { - guint32 r = static_cast(SP_RGBA32_R_U (c1) * (1 - p) + SP_RGBA32_R_U (c2) * p); - guint32 g = static_cast(SP_RGBA32_G_U (c1) * (1 - p) + SP_RGBA32_G_U (c2) * p); - guint32 b = static_cast(SP_RGBA32_B_U (c1) * (1 - p) + SP_RGBA32_B_U (c2) * p); - guint32 a = static_cast(SP_RGBA32_A_U (c1) * (1 - p) + SP_RGBA32_A_U (c2) * p); + guint32 r = static_cast(SP_RGBA32_R_U(c1) * (1 - p) + SP_RGBA32_R_U(c2) * p); + guint32 g = static_cast(SP_RGBA32_G_U(c1) * (1 - p) + SP_RGBA32_G_U(c2) * p); + guint32 b = static_cast(SP_RGBA32_B_U(c1) * (1 - p) + SP_RGBA32_B_U(c2) * p); + guint32 a = static_cast(SP_RGBA32_A_U(c1) * (1 - p) + SP_RGBA32_A_U(c2) * p); return SP_RGBA32_U_COMPOSE(r, g, b, a); } -SPStop *sp_vector_add_stop(SPGradient *vector, SPStop* prev_stop, SPStop* next_stop, gfloat offset) +SPStop *sp_vector_add_stop(SPGradient *vector, SPStop *prev_stop, SPStop *next_stop, gfloat offset) { #ifdef SP_GR_VERBOSE g_message("sp_vector_add_stop(%p, %p, %p, %f)", vector, prev_stop, next_stop, offset); @@ -676,22 +656,23 @@ SPStop *sp_vector_add_stop(SPGradient *vector, SPStop* prev_stop, SPStop* next_s SPStop *newstop = reinterpret_cast(vector->document->getObjectByRepr(new_stop_repr)); newstop->offset = offset; - sp_repr_set_css_double( newstop->getRepr(), "offset", (double)offset); + sp_repr_set_css_double(newstop->getRepr(), "offset", (double)offset); guint32 const c1 = prev_stop->get_rgba32(); guint32 const c2 = next_stop->get_rgba32(); - guint32 cnew = average_color (c1, c2, (offset - prev_stop->offset) / (next_stop->offset - prev_stop->offset)); + guint32 cnew = average_color(c1, c2, (offset - prev_stop->offset) / (next_stop->offset - prev_stop->offset)); Inkscape::CSSOStringStream os; gchar c[64]; - sp_svg_write_color (c, sizeof(c), cnew); - gdouble opacity = (gdouble) SP_RGBA32_A_F (cnew); - os << "stop-color:" << c << ";stop-opacity:" << opacity <<";"; + sp_svg_write_color(c, sizeof(c), cnew); + gdouble opacity = (gdouble)SP_RGBA32_A_F(cnew); + os << "stop-color:" << c << ";stop-opacity:" << opacity << ";"; newstop->setAttributeOrRemoveIfEmpty("style", os.str()); Inkscape::GC::release(new_stop_repr); return newstop; } -guint32 sp_item_gradient_stop_query_style(SPItem *item, GrPointType point_type, guint point_i, Inkscape::PaintTarget fill_or_stroke) +guint32 sp_item_gradient_stop_query_style(SPItem *item, GrPointType point_type, guint point_i, + Inkscape::PaintTarget fill_or_stroke) { SPGradient *gradient = getGradient(item, fill_or_stroke); @@ -699,54 +680,46 @@ guint32 sp_item_gradient_stop_query_style(SPItem *item, GrPointType point_type, return 0; } - if (SP_IS_LINEARGRADIENT(gradient) || SP_IS_RADIALGRADIENT(gradient) ) { - + if (SP_IS_LINEARGRADIENT(gradient) || SP_IS_RADIALGRADIENT(gradient)) { SPGradient *vector = gradient->getVector(); - if (!vector) // orphan! + if (!vector) // orphan! return 0; // what else to do? switch (point_type) { case POINT_LG_BEGIN: case POINT_RG_CENTER: - case POINT_RG_FOCUS: - { + case POINT_RG_FOCUS: { SPStop *first = vector->getFirstStop(); if (first) { return first->get_rgba32(); } - } - break; + } break; case POINT_LG_END: case POINT_RG_R1: - case POINT_RG_R2: - { - SPStop *last = sp_last_stop (vector); + case POINT_RG_R2: { + SPStop *last = sp_last_stop(vector); if (last) { return last->get_rgba32(); } - } - break; + } break; case POINT_LG_MID: case POINT_RG_MID1: - case POINT_RG_MID2: - { - SPStop *stopi = sp_get_stop_i (vector, point_i); + case POINT_RG_MID2: { + SPStop *stopi = sp_get_stop_i(vector, point_i); if (stopi) { return stopi->get_rgba32(); } - } - break; + } break; default: - g_warning( "Bad linear/radial gradient handle type" ); + g_warning("Bad linear/radial gradient handle type"); break; } return 0; } else if (SP_IS_MESHGRADIENT(gradient)) { - // Mesh gradient SPMeshGradient *mg = SP_MESHGRADIENT(gradient); @@ -755,12 +728,12 @@ guint32 sp_item_gradient_stop_query_style(SPItem *item, GrPointType point_type, if (point_i >= mg->array.corners.size()) { return 0; } - SPMeshNode const* cornerpoint = mg->array.corners[ point_i ]; + SPMeshNode const *cornerpoint = mg->array.corners[point_i]; if (cornerpoint) { - SPColor color = cornerpoint->color; + SPColor color = cornerpoint->color; double opacity = cornerpoint->opacity; - return color.toRGBA32( opacity ); + return color.toRGBA32(opacity); } else { return 0; } @@ -768,14 +741,13 @@ guint32 sp_item_gradient_stop_query_style(SPItem *item, GrPointType point_type, } case POINT_MG_HANDLE: - case POINT_MG_TENSOR: - { + case POINT_MG_TENSOR: { // Do nothing. Handles and tensors don't have color break; } default: - g_warning( "Bad mesh handle type" ); + g_warning("Bad mesh handle type"); } return 0; } @@ -783,7 +755,8 @@ guint32 sp_item_gradient_stop_query_style(SPItem *item, GrPointType point_type, return 0; } -void sp_item_gradient_stop_set_style(SPItem *item, GrPointType point_type, guint point_i, Inkscape::PaintTarget fill_or_stroke, SPCSSAttr *stop) +void sp_item_gradient_stop_set_style(SPItem *item, GrPointType point_type, guint point_i, + Inkscape::PaintTarget fill_or_stroke, SPCSSAttr *stop) { #ifdef SP_GR_VERBOSE g_message("sp_item_gradient_stop_set_style(%p, %d, %d, %d, %p)", item, point_type, point_i, fill_or_stroke, stop); @@ -793,88 +766,79 @@ void sp_item_gradient_stop_set_style(SPItem *item, GrPointType point_type, guint if (!gradient || !SP_IS_GRADIENT(gradient)) return; - if (SP_IS_LINEARGRADIENT(gradient) || SP_IS_RADIALGRADIENT(gradient) ) { - + if (SP_IS_LINEARGRADIENT(gradient) || SP_IS_RADIALGRADIENT(gradient)) { SPGradient *vector = gradient->getVector(); if (!vector) // orphan! return; - vector = sp_gradient_fork_vector_if_necessary (vector); - if ( gradient != vector && gradient->ref->getObject() != vector ) { + vector = sp_gradient_fork_vector_if_necessary(vector); + if (gradient != vector && gradient->ref->getObject() != vector) { sp_gradient_repr_set_link(gradient->getRepr(), vector); } switch (point_type) { case POINT_LG_BEGIN: case POINT_RG_CENTER: - case POINT_RG_FOCUS: - { + case POINT_RG_FOCUS: { SPStop *first = vector->getFirstStop(); if (first) { sp_repr_css_change(first->getRepr(), stop, "style"); } - } - break; + } break; case POINT_LG_END: case POINT_RG_R1: - case POINT_RG_R2: - { - SPStop *last = sp_last_stop (vector); + case POINT_RG_R2: { + SPStop *last = sp_last_stop(vector); if (last) { sp_repr_css_change(last->getRepr(), stop, "style"); } - } - break; + } break; case POINT_LG_MID: case POINT_RG_MID1: - case POINT_RG_MID2: - { - SPStop *stopi = sp_get_stop_i (vector, point_i); + case POINT_RG_MID2: { + SPStop *stopi = sp_get_stop_i(vector, point_i); if (stopi) { sp_repr_css_change(stopi->getRepr(), stop, "style"); } - } - break; + } break; default: - g_warning( "Bad linear/radial gradient handle type" ); + g_warning("Bad linear/radial gradient handle type"); break; } } else { - // Mesh gradient SPMeshGradient *mg = SP_MESHGRADIENT(gradient); bool changed = false; switch (point_type) { case POINT_MG_CORNER: { - // Update mesh array (which is not updated automatically when stop is changed?) - gchar const* color_str = sp_repr_css_property( stop, "stop-color", nullptr ); - if( color_str ) { - SPColor color( 0 ); + gchar const *color_str = sp_repr_css_property(stop, "stop-color", nullptr); + if (color_str) { + SPColor color(0); SPIPaint paint; - paint.read( color_str ); - if( paint.isColor() ) { + paint.read(color_str); + if (paint.isColor()) { color = paint.value.color; } - mg->array.corners[ point_i ]->color = color; + mg->array.corners[point_i]->color = color; changed = true; } - gchar const* opacity_str = sp_repr_css_property( stop, "stop-opacity", nullptr ); - if( opacity_str ) { - std::stringstream os( opacity_str ); + gchar const *opacity_str = sp_repr_css_property(stop, "stop-opacity", nullptr); + if (opacity_str) { + std::stringstream os(opacity_str); double opacity = 1.0; os >> opacity; - mg->array.corners[ point_i ]->opacity = opacity; + mg->array.corners[point_i]->opacity = opacity; changed = true; } // Update stop - if( changed ) { - SPStop *stopi = mg->array.corners[ point_i ]->stop; + if (changed) { + SPStop *stopi = mg->array.corners[point_i]->stop; if (stopi) { sp_repr_css_change(stopi->getRepr(), stop, "style"); } else { @@ -885,14 +849,13 @@ void sp_item_gradient_stop_set_style(SPItem *item, GrPointType point_type, guint } case POINT_MG_HANDLE: - case POINT_MG_TENSOR: - { + case POINT_MG_TENSOR: { // Do nothing. Handles and tensors don't have colors. break; } default: - g_warning( "Bad mesh handle type" ); + g_warning("Bad mesh handle type"); } } } @@ -910,38 +873,37 @@ void sp_item_gradient_reverse_vector(SPItem *item, Inkscape::PaintTarget fill_or if (!vector) // orphan! return; - vector = sp_gradient_fork_vector_if_necessary (vector); - if ( gradient != vector && gradient->ref->getObject() != vector ) { + vector = sp_gradient_fork_vector_if_necessary(vector); + if (gradient != vector && gradient->ref->getObject() != vector) { sp_gradient_repr_set_link(gradient->getRepr(), vector); } std::vector child_objects; - std::vectorchild_reprs; + std::vector child_reprs; std::vector offsets; double offset; - for (auto& child: vector->children) { + for (auto &child : vector->children) { child_reprs.push_back(child.getRepr()); child_objects.push_back(&child); - offset=0; + offset = 0; sp_repr_get_double(child.getRepr(), "offset", &offset); offsets.push_back(offset); } std::vector child_copies; - for (auto repr:child_reprs) { + for (auto repr : child_reprs) { Inkscape::XML::Document *xml_doc = vector->getRepr()->document(); child_copies.push_back(repr->duplicate(xml_doc)); } - - for (auto i:child_objects) { + for (auto i : child_objects) { i->deleteObject(); } std::vector::reverse_iterator o_it = offsets.rbegin(); for (auto c_it = child_copies.rbegin(); c_it != child_copies.rend(); ++c_it, ++o_it) { vector->appendChildRepr(*c_it); - sp_repr_set_svg_double (*c_it, "offset", 1 - *o_it); + sp_repr_set_svg_double(*c_it, "offset", 1 - *o_it); Inkscape::GC::release(*c_it); } } @@ -959,28 +921,23 @@ void sp_item_gradient_invert_vector_color(SPItem *item, Inkscape::PaintTarget fi if (!vector) // orphan! return; - vector = sp_gradient_fork_vector_if_necessary (vector); - if ( gradient != vector && gradient->ref->getObject() != vector ) { + vector = sp_gradient_fork_vector_if_necessary(vector); + if (gradient != vector && gradient->ref->getObject() != vector) { sp_gradient_repr_set_link(gradient->getRepr(), vector); } - for (auto& child: vector->children) { + for (auto &child : vector->children) { if (SP_IS_STOP(&child)) { - guint32 color = SP_STOP(&child)->get_rgba32(); - //g_message("Stop color %d", color); + guint32 color = SP_STOP(&child)->get_rgba32(); + // g_message("Stop color %d", color); gchar c[64]; - sp_svg_write_color (c, sizeof(c), - SP_RGBA32_U_COMPOSE( - (255 - SP_RGBA32_R_U(color)), - (255 - SP_RGBA32_G_U(color)), - (255 - SP_RGBA32_B_U(color)), - SP_RGBA32_A_U(color) - ) - ); - SPCSSAttr *css = sp_repr_css_attr_new (); - sp_repr_css_set_property (css, "stop-color", c); + sp_svg_write_color(c, sizeof(c), + SP_RGBA32_U_COMPOSE((255 - SP_RGBA32_R_U(color)), (255 - SP_RGBA32_G_U(color)), + (255 - SP_RGBA32_B_U(color)), SP_RGBA32_A_U(color))); + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "stop-color", c); sp_repr_css_change(child.getRepr(), css, "style"); - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); } } } @@ -989,10 +946,12 @@ void sp_item_gradient_invert_vector_color(SPItem *item, Inkscape::PaintTarget fi Set the position of point point_type of the gradient applied to item (either fill_or_stroke) to p_w (in desktop coordinates). Write_repr if you want the change to become permanent. */ -void sp_item_gradient_set_coords(SPItem *item, GrPointType point_type, guint point_i, Geom::Point p_w, Inkscape::PaintTarget fill_or_stroke, bool write_repr, bool scale) +void sp_item_gradient_set_coords(SPItem *item, GrPointType point_type, guint point_i, Geom::Point p_w, + Inkscape::PaintTarget fill_or_stroke, bool write_repr, bool scale) { #ifdef SP_GR_VERBOSE - g_message("sp_item_gradient_set_coords(%p, %d, %d, (%f, %f), ...)", item, point_type, point_i, p_w[Geom::X], p_w[Geom::Y] ); + g_message("sp_item_gradient_set_coords(%p, %d, %d, (%f, %f), ...)", item, point_type, point_i, p_w[Geom::X], + p_w[Geom::Y]); #endif SPGradient *gradient = getGradient(item, fill_or_stroke); @@ -1000,9 +959,10 @@ void sp_item_gradient_set_coords(SPItem *item, GrPointType point_type, guint poi return; // Needed only if units are set to SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX - gradient = sp_gradient_convert_to_userspace(gradient, item, (fill_or_stroke == Inkscape::FOR_FILL) ? "fill" : "stroke"); + gradient = + sp_gradient_convert_to_userspace(gradient, item, (fill_or_stroke == Inkscape::FOR_FILL) ? "fill" : "stroke"); - Geom::Affine i2d (item->i2dt_affine ()); + Geom::Affine i2d(item->i2dt_affine()); Geom::Point p = p_w * i2d.inverse(); p *= (gradient->gradientTransform).inverse(); // now p is in gradient's original coordinates @@ -1048,33 +1008,32 @@ void sp_item_gradient_set_coords(SPItem *item, GrPointType point_type, guint poi gradient->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; - case POINT_LG_MID: - { - // using X-coordinates only to determine the offset, assuming p has been snapped to the vector from begin to end. + case POINT_LG_MID: { + // using X-coordinates only to determine the offset, assuming p has been snapped to the vector from + // begin to end. Geom::Point begin(lg->x1.computed, lg->y1.computed); Geom::Point end(lg->x2.computed, lg->y2.computed); double offset = Geom::LineSegment(begin, end).nearestTime(p); - SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (lg, false); + SPGradient *vector = sp_gradient_get_forked_vector_if_necessary(lg, false); lg->ensureVector(); lg->vector.stops.at(point_i).offset = offset; - SPStop* stopi = sp_get_stop_i(vector, point_i); + SPStop *stopi = sp_get_stop_i(vector, point_i); stopi->offset = offset; if (write_repr) { sp_repr_set_css_double(stopi->getRepr(), "offset", stopi->offset); } else { stopi->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); } - } - break; + } break; default: - g_warning( "Bad linear gradient handle type" ); + g_warning("Bad linear gradient handle type"); break; } } else if (SP_IS_RADIALGRADIENT(gradient)) { SPRadialGradient *rg = SP_RADIALGRADIENT(gradient); - Geom::Point c (rg->cx.computed, rg->cy.computed); + Geom::Point c(rg->cx.computed, rg->cy.computed); Geom::Point c_w = c * gradient->gradientTransform * i2d; // now in desktop coords - if ((point_type == POINT_RG_R1 || point_type == POINT_RG_R2) && Geom::L2 (p_w - c_w) < 1e-3) { + if ((point_type == POINT_RG_R1 || point_type == POINT_RG_R2) && Geom::L2(p_w - c_w) < 1e-3) { // prevent setting a radius too close to the center return; } @@ -1106,53 +1065,46 @@ void sp_item_gradient_set_coords(SPItem *item, GrPointType point_type, guint poi gradient->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; - case POINT_RG_R1: - { + case POINT_RG_R1: { Geom::Point r1_w = (c + Geom::Point(rg->r.computed, 0)) * gradient->gradientTransform * i2d; double r1_angle = Geom::atan2(r1_w - c_w); double move_angle = Geom::atan2(p_w - c_w) - r1_angle; double move_stretch = Geom::L2(p_w - c_w) / Geom::L2(r1_w - c_w); - Geom::Affine move = Geom::Affine (Geom::Translate (-c_w)) * - Geom::Affine (Geom::Rotate(-r1_angle)) * - Geom::Affine (Geom::Scale(move_stretch, scale? move_stretch : 1)) * - Geom::Affine (Geom::Rotate(r1_angle)) * - Geom::Affine (Geom::Rotate(move_angle)) * - Geom::Affine (Geom::Translate (c_w)); + Geom::Affine move = Geom::Affine(Geom::Translate(-c_w)) * Geom::Affine(Geom::Rotate(-r1_angle)) * + Geom::Affine(Geom::Scale(move_stretch, scale ? move_stretch : 1)) * + Geom::Affine(Geom::Rotate(r1_angle)) * Geom::Affine(Geom::Rotate(move_angle)) * + Geom::Affine(Geom::Translate(c_w)); new_transform = gradient->gradientTransform * i2d * move * i2d.inverse(); transform_set = true; break; } - case POINT_RG_R2: - { + case POINT_RG_R2: { Geom::Point r2_w = (c + Geom::Point(0, -rg->r.computed)) * gradient->gradientTransform * i2d; double r2_angle = Geom::atan2(r2_w - c_w); double move_angle = Geom::atan2(p_w - c_w) - r2_angle; double move_stretch = Geom::L2(p_w - c_w) / Geom::L2(r2_w - c_w); - Geom::Affine move = Geom::Affine (Geom::Translate (-c_w)) * - Geom::Affine (Geom::Rotate(-r2_angle)) * - Geom::Affine (Geom::Scale(move_stretch, scale? move_stretch : 1)) * - Geom::Affine (Geom::Rotate(r2_angle)) * - Geom::Affine (Geom::Rotate(move_angle)) * - Geom::Affine (Geom::Translate (c_w)); + Geom::Affine move = Geom::Affine(Geom::Translate(-c_w)) * Geom::Affine(Geom::Rotate(-r2_angle)) * + Geom::Affine(Geom::Scale(move_stretch, scale ? move_stretch : 1)) * + Geom::Affine(Geom::Rotate(r2_angle)) * Geom::Affine(Geom::Rotate(move_angle)) * + Geom::Affine(Geom::Translate(c_w)); new_transform = gradient->gradientTransform * i2d * move * i2d.inverse(); transform_set = true; break; } - case POINT_RG_MID1: - { - Geom::Point start = Geom::Point (rg->cx.computed, rg->cy.computed); - Geom::Point end = Geom::Point (rg->cx.computed + rg->r.computed, rg->cy.computed); + case POINT_RG_MID1: { + Geom::Point start = Geom::Point(rg->cx.computed, rg->cy.computed); + Geom::Point end = Geom::Point(rg->cx.computed + rg->r.computed, rg->cy.computed); double offset = Geom::LineSegment(start, end).nearestTime(p); - SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (rg, false); + SPGradient *vector = sp_gradient_get_forked_vector_if_necessary(rg, false); rg->ensureVector(); rg->vector.stops.at(point_i).offset = offset; - SPStop* stopi = sp_get_stop_i(vector, point_i); + SPStop *stopi = sp_get_stop_i(vector, point_i); stopi->offset = offset; if (write_repr) { sp_repr_set_css_double(stopi->getRepr(), "offset", stopi->offset); @@ -1161,15 +1113,14 @@ void sp_item_gradient_set_coords(SPItem *item, GrPointType point_type, guint poi } break; } - case POINT_RG_MID2: - { - Geom::Point start = Geom::Point (rg->cx.computed, rg->cy.computed); - Geom::Point end = Geom::Point (rg->cx.computed, rg->cy.computed - rg->r.computed); + case POINT_RG_MID2: { + Geom::Point start = Geom::Point(rg->cx.computed, rg->cy.computed); + Geom::Point end = Geom::Point(rg->cx.computed, rg->cy.computed - rg->r.computed); double offset = Geom::LineSegment(start, end).nearestTime(p); SPGradient *vector = sp_gradient_get_forked_vector_if_necessary(rg, false); rg->ensureVector(); rg->vector.stops.at(point_i).offset = offset; - SPStop* stopi = sp_get_stop_i(vector, point_i); + SPStop *stopi = sp_get_stop_i(vector, point_i); stopi->offset = offset; if (write_repr) { sp_repr_set_css_double(stopi->getRepr(), "offset", stopi->offset); @@ -1179,7 +1130,7 @@ void sp_item_gradient_set_coords(SPItem *item, GrPointType point_type, guint poi break; } default: - g_warning( "Bad radial gradient handle type" ); + g_warning("Bad radial gradient handle type"); break; } @@ -1187,7 +1138,7 @@ void sp_item_gradient_set_coords(SPItem *item, GrPointType point_type, guint poi gradient->gradientTransform = new_transform; gradient->gradientTransform_set = TRUE; if (write_repr) { - gchar *s=sp_svg_transform_write(gradient->gradientTransform); + gchar *s = sp_svg_transform_write(gradient->gradientTransform); gradient->setAttribute("gradientTransform", s); g_free(s); } else { @@ -1196,39 +1147,37 @@ void sp_item_gradient_set_coords(SPItem *item, GrPointType point_type, guint poi } } else if (SP_IS_MESHGRADIENT(gradient)) { SPMeshGradient *mg = SP_MESHGRADIENT(gradient); - //Geom::Affine new_transform; - //bool transform_set = false; + // Geom::Affine new_transform; + // bool transform_set = false; switch (point_type) { - case POINT_MG_CORNER: - { - mg->array.corners[ point_i ]->p = p; + case POINT_MG_CORNER: { + mg->array.corners[point_i]->p = p; // Handles are moved in gradient-drag.cpp gradient->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } case POINT_MG_HANDLE: { - mg->array.handles[ point_i ]->p = p; + mg->array.handles[point_i]->p = p; gradient->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } case POINT_MG_TENSOR: { - mg->array.tensors[ point_i ]->p = p; + mg->array.tensors[point_i]->p = p; gradient->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } default: - g_warning( "Bad mesh handle type" ); + g_warning("Bad mesh handle type"); } - if( write_repr ) { - //std::cout << "Write mesh repr" << std::endl; - mg->array.write( mg ); + if (write_repr) { + // std::cout << "Write mesh repr" << std::endl; + mg->array.write(mg); } } - } SPGradient *sp_item_gradient_get_vector(SPItem *item, Inkscape::PaintTarget fill_or_stroke) @@ -1252,7 +1201,6 @@ SPGradientSpread sp_item_gradient_get_spread(SPItem *item, Inkscape::PaintTarget return spread; } - /** Returns the position of point point_type of the gradient applied to item (either fill_or_stroke), in desktop coordinates. @@ -1264,7 +1212,7 @@ Geom::Point getGradientCoords(SPItem *item, GrPointType point_type, guint point_ g_message("getGradientCoords(%p, %d, %d, %d, %p)", item, point_type, point_i, fill_or_stroke, gradient); #endif - Geom::Point p (0, 0); + Geom::Point p(0, 0); if (!gradient) return p; @@ -1273,95 +1221,89 @@ Geom::Point getGradientCoords(SPItem *item, GrPointType point_type, guint point_ SPLinearGradient *lg = SP_LINEARGRADIENT(gradient); switch (point_type) { case POINT_LG_BEGIN: - p = Geom::Point (lg->x1.computed, lg->y1.computed); + p = Geom::Point(lg->x1.computed, lg->y1.computed); break; case POINT_LG_END: - p = Geom::Point (lg->x2.computed, lg->y2.computed); + p = Geom::Point(lg->x2.computed, lg->y2.computed); break; - case POINT_LG_MID: - { - if (lg->vector.stops.size() < point_i) { - g_message("POINT_LG_MID bug trigger, see LP bug #453067"); - break; - } - gdouble offset = lg->vector.stops.at(point_i).offset; - p = (1-offset) * Geom::Point(lg->x1.computed, lg->y1.computed) + offset * Geom::Point(lg->x2.computed, lg->y2.computed); + case POINT_LG_MID: { + if (lg->vector.stops.size() < point_i) { + g_message("POINT_LG_MID bug trigger, see LP bug #453067"); + break; } - break; + gdouble offset = lg->vector.stops.at(point_i).offset; + p = (1 - offset) * Geom::Point(lg->x1.computed, lg->y1.computed) + + offset * Geom::Point(lg->x2.computed, lg->y2.computed); + } break; default: - g_warning( "Bad linear gradient handle type" ); + g_warning("Bad linear gradient handle type"); break; } - } else if (SP_IS_RADIALGRADIENT(gradient)) { + } else if (SP_IS_RADIALGRADIENT(gradient)) { SPRadialGradient *rg = SP_RADIALGRADIENT(gradient); switch (point_type) { case POINT_RG_CENTER: - p = Geom::Point (rg->cx.computed, rg->cy.computed); + p = Geom::Point(rg->cx.computed, rg->cy.computed); break; case POINT_RG_FOCUS: - p = Geom::Point (rg->fx.computed, rg->fy.computed); + p = Geom::Point(rg->fx.computed, rg->fy.computed); break; case POINT_RG_R1: - p = Geom::Point (rg->cx.computed + rg->r.computed, rg->cy.computed); + p = Geom::Point(rg->cx.computed + rg->r.computed, rg->cy.computed); break; case POINT_RG_R2: - p = Geom::Point (rg->cx.computed, rg->cy.computed - rg->r.computed); + p = Geom::Point(rg->cx.computed, rg->cy.computed - rg->r.computed); break; - case POINT_RG_MID1: - { - if (rg->vector.stops.size() < point_i) { - g_message("POINT_RG_MID1 bug trigger, see LP bug #453067"); - break; - } - gdouble offset = rg->vector.stops.at(point_i).offset; - p = (1-offset) * Geom::Point (rg->cx.computed, rg->cy.computed) + offset * Geom::Point(rg->cx.computed + rg->r.computed, rg->cy.computed); + case POINT_RG_MID1: { + if (rg->vector.stops.size() < point_i) { + g_message("POINT_RG_MID1 bug trigger, see LP bug #453067"); + break; } - break; - case POINT_RG_MID2: - { - if (rg->vector.stops.size() < point_i) { - g_message("POINT_RG_MID2 bug trigger, see LP bug #453067"); - break; - } - gdouble offset = rg->vector.stops.at(point_i).offset; - p = (1-offset) * Geom::Point (rg->cx.computed, rg->cy.computed) + offset * Geom::Point(rg->cx.computed, rg->cy.computed - rg->r.computed); + gdouble offset = rg->vector.stops.at(point_i).offset; + p = (1 - offset) * Geom::Point(rg->cx.computed, rg->cy.computed) + + offset * Geom::Point(rg->cx.computed + rg->r.computed, rg->cy.computed); + } break; + case POINT_RG_MID2: { + if (rg->vector.stops.size() < point_i) { + g_message("POINT_RG_MID2 bug trigger, see LP bug #453067"); + break; } - break; + gdouble offset = rg->vector.stops.at(point_i).offset; + p = (1 - offset) * Geom::Point(rg->cx.computed, rg->cy.computed) + + offset * Geom::Point(rg->cx.computed, rg->cy.computed - rg->r.computed); + } break; default: - g_warning( "Bad radial gradient handle type" ); + g_warning("Bad radial gradient handle type"); break; } - } else if (SP_IS_MESHGRADIENT(gradient)) { + } else if (SP_IS_MESHGRADIENT(gradient)) { SPMeshGradient *mg = SP_MESHGRADIENT(gradient); switch (point_type) { - case POINT_MG_CORNER: - p = mg->array.corners[ point_i ]->p; + p = mg->array.corners[point_i]->p; break; case POINT_MG_HANDLE: { - p = mg->array.handles[ point_i ]->p; + p = mg->array.handles[point_i]->p; break; } case POINT_MG_TENSOR: { - p = mg->array.tensors[ point_i ]->p; + p = mg->array.tensors[point_i]->p; break; } default: - g_warning( "Bad mesh handle type" ); + g_warning("Bad mesh handle type"); } } - if (SP_GRADIENT(gradient)->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) { item->document->ensureUpToDate(); Geom::OptRect bbox = item->visualBounds(); // we need "true" bbox without item_i2d_affine if (bbox) { - p *= Geom::Affine(bbox->dimensions()[Geom::X], 0, - 0, bbox->dimensions()[Geom::Y], - bbox->min()[Geom::X], bbox->min()[Geom::Y]); + p *= Geom::Affine(bbox->dimensions()[Geom::X], 0, 0, bbox->dimensions()[Geom::Y], bbox->min()[Geom::X], + bbox->min()[Geom::Y]); } } p *= Geom::Affine(gradient->gradientTransform) * (Geom::Affine)item->i2dt_affine(); @@ -1374,7 +1316,8 @@ Geom::Point getGradientCoords(SPItem *item, GrPointType point_type, guint point_ * gr has to be a normalized vector. */ -SPGradient *sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType type, Inkscape::PaintTarget fill_or_stroke) +SPGradient *sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType type, + Inkscape::PaintTarget fill_or_stroke) { #ifdef SP_GR_VERBOSE g_message("sp_item_set_gradient(%p, %p, %d, %d)", item, gr, type, fill_or_stroke); @@ -1393,24 +1336,19 @@ SPGradient *sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType ty ps = (fill_or_stroke == Inkscape::FOR_FILL) ? SP_STYLE_FILL_SERVER(style) : SP_STYLE_STROKE_SERVER(style); } - if (ps - && ( (type == SP_GRADIENT_TYPE_LINEAR && SP_IS_LINEARGRADIENT(ps)) || - (type == SP_GRADIENT_TYPE_RADIAL && SP_IS_RADIALGRADIENT(ps)) ) ) - { - + if (ps && ((type == SP_GRADIENT_TYPE_LINEAR && SP_IS_LINEARGRADIENT(ps)) || + (type == SP_GRADIENT_TYPE_RADIAL && SP_IS_RADIALGRADIENT(ps)))) { /* Current fill style is the gradient of the required type */ SPGradient *current = SP_GRADIENT(ps); - //g_message("hrefcount %d count %d\n", current->hrefcount, count_gradient_hrefs(item, current)); - - if (!current->isSwatch() - && (current->hrefcount == 1 || - current->hrefcount == count_gradient_hrefs(item, current))) { + // g_message("hrefcount %d count %d\n", current->hrefcount, count_gradient_hrefs(item, current)); + if (!current->isSwatch() && + (current->hrefcount == 1 || current->hrefcount == count_gradient_hrefs(item, current))) { // current is private and it's either used once, or all its uses are by children of item; // so just change its href to vector - if ( current != gr && current->getVector() != gr ) { + if (current != gr && current->getVector() != gr) { // href is not the vector sp_gradient_repr_set_link(current->getRepr(), gr); } @@ -1418,7 +1356,6 @@ SPGradient *sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType ty return current; } else { - // the gradient is not private, or it is shared with someone else; // normalize it (this includes creating new private if necessary) SPGradient *normalized = sp_gradient_fork_private_if_necessary(current, gr, type, item); @@ -1426,10 +1363,10 @@ SPGradient *sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType ty g_return_val_if_fail(normalized != nullptr, NULL); if (normalized != current) { - /* We have to change object style here; recursive because this is used from * fill&stroke and must work for groups etc. */ - sp_style_set_property_url(item, (fill_or_stroke == Inkscape::FOR_FILL) ? "fill" : "stroke", normalized, true); + sp_style_set_property_url(item, (fill_or_stroke == Inkscape::FOR_FILL) ? "fill" : "stroke", normalized, + true); } item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); return normalized; @@ -1441,9 +1378,9 @@ SPGradient *sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType ty g_assert(SP_IS_GRADIENT(gr)); // TEMP SPGradient *constructed = sp_gradient_get_private_normalized(item->document, gr, type); constructed = sp_gradient_reset_to_userspace(constructed, item); - sp_style_set_property_url(item, ( (fill_or_stroke == Inkscape::FOR_FILL) ? "fill" : "stroke" ), constructed, true); - item->requestDisplayUpdate(( SP_OBJECT_MODIFIED_FLAG | - SP_OBJECT_STYLE_MODIFIED_FLAG )); + sp_style_set_property_url(item, ((fill_or_stroke == Inkscape::FOR_FILL) ? "fill" : "stroke"), constructed, + true); + item->requestDisplayUpdate((SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG)); return constructed; } } @@ -1467,20 +1404,19 @@ static void sp_gradient_repr_set_link(Inkscape::XML::Node *repr, SPGradient *lin } } - -static void addStop( Inkscape::XML::Node *parent, Glib::ustring const &color, gint opacity, gchar const *offset ) +static void addStop(Inkscape::XML::Node *parent, Glib::ustring const &color, gint opacity, gchar const *offset) { #ifdef SP_GR_VERBOSE g_message("addStop(%p, %s, %d, %s)", parent, color.c_str(), opacity, offset); #endif Inkscape::XML::Node *stop = parent->document()->createElement("svg:stop"); { - gchar *tmp = g_strdup_printf( "stop-color:%s;stop-opacity:%d;", color.c_str(), opacity ); - stop->setAttribute( "style", tmp ); + gchar *tmp = g_strdup_printf("stop-color:%s;stop-opacity:%d;", color.c_str(), opacity); + stop->setAttribute("style", tmp); g_free(tmp); } - stop->setAttribute( "offset", offset ); + stop->setAttribute("offset", offset); parent->appendChild(stop); Inkscape::GC::release(stop); @@ -1489,14 +1425,14 @@ static void addStop( Inkscape::XML::Node *parent, Glib::ustring const &color, gi /* * Get default normalized gradient vector of document, create if there is none */ -SPGradient *sp_document_default_gradient_vector( SPDocument *document, SPColor const &color, bool singleStop ) +SPGradient *sp_document_default_gradient_vector(SPDocument *document, SPColor const &color, bool singleStop) { SPDefs *defs = document->getDefs(); Inkscape::XML::Document *xml_doc = document->getReprDoc(); Inkscape::XML::Node *repr = xml_doc->createElement("svg:linearGradient"); - if ( !singleStop ) { + if (!singleStop) { repr->setAttribute("inkscape:collect", "always"); // set here, but removed when it's edited in the gradient editor // to further reduce clutter, we could @@ -1505,9 +1441,9 @@ SPGradient *sp_document_default_gradient_vector( SPDocument *document, SPColor c } Glib::ustring colorStr = color.toString(); - addStop( repr, colorStr, 1, "0" ); - if ( !singleStop ) { - addStop( repr, colorStr, 0, "1" ); + addStop(repr, colorStr, 1, "0"); + if (!singleStop) { + addStop(repr, colorStr, 0, "1"); } defs->getRepr()->addChild(repr, nullptr); @@ -1523,19 +1459,20 @@ SPGradient *sp_document_default_gradient_vector( SPDocument *document, SPColor c return gr; } -SPGradient *sp_gradient_vector_for_object( SPDocument *const doc, SPDesktop *const desktop, - SPObject *const o, Inkscape::PaintTarget const fill_or_stroke, bool singleStop ) +SPGradient *sp_gradient_vector_for_object(SPDocument *const doc, SPDesktop *const desktop, SPObject *const o, + Inkscape::PaintTarget const fill_or_stroke, bool singleStop) { SPColor color; - if ( (o == nullptr) || (o->style == nullptr) ) { + if ((o == nullptr) || (o->style == nullptr)) { color = sp_desktop_get_color(desktop, (fill_or_stroke == Inkscape::FOR_FILL)); } else { // take the color of the object SPStyle const &style = *(o->style); SPIPaint const &paint = *style.getFillOrStroke(fill_or_stroke == Inkscape::FOR_FILL); if (paint.isPaintserver()) { - SPObject *server = (fill_or_stroke == Inkscape::FOR_FILL) ? o->style->getFillPaintServer() : o->style->getStrokePaintServer(); - if ( SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server) ) { + SPObject *server = (fill_or_stroke == Inkscape::FOR_FILL) ? o->style->getFillPaintServer() + : o->style->getStrokePaintServer(); + if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server)) { return SP_GRADIENT(server)->getVector(true); } else { color = sp_desktop_get_color(desktop, (fill_or_stroke == Inkscape::FOR_FILL)); @@ -1548,21 +1485,20 @@ SPGradient *sp_gradient_vector_for_object( SPDocument *const doc, SPDesktop *con } } - return sp_document_default_gradient_vector( doc, color, singleStop ); + return sp_document_default_gradient_vector(doc, color, singleStop); } void sp_gradient_invert_selected_gradients(SPDesktop *desktop, Inkscape::PaintTarget fill_or_stroke) { Inkscape::Selection *selection = desktop->getSelection(); - auto list= selection->items(); + auto list = selection->items(); for (auto i = list.begin(); i != list.end(); ++i) { sp_item_gradient_invert_vector_color(*i, fill_or_stroke); } // we did an undoable action - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, - _("Invert gradient colors")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, _("Invert gradient colors")); } void sp_gradient_reverse_selected_gradients(SPDesktop *desktop) @@ -1580,7 +1516,7 @@ void sp_gradient_reverse_selected_gradients(SPDesktop *desktop) if (drag && !drag->selected.empty()) { drag->selected_reverse_vector(); } else { // If no drag or no dragger selected, act on selection (both fill and stroke gradients) - auto list= selection->items(); + auto list = selection->items(); for (auto i = list.begin(); i != list.end(); ++i) { sp_item_gradient_reverse_vector(*i, Inkscape::FOR_FILL); sp_item_gradient_reverse_vector(*i, Inkscape::FOR_STROKE); @@ -1588,8 +1524,7 @@ void sp_gradient_reverse_selected_gradients(SPDesktop *desktop) } // we did an undoable action - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, - _("Reverse gradient")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, _("Reverse gradient")); } void sp_gradient_unset_swatch(SPDesktop *desktop, std::string id) @@ -1599,11 +1534,10 @@ void sp_gradient_unset_swatch(SPDesktop *desktop, std::string id) if (doc) { const std::vector gradients = doc->getResourceList("gradient"); for (auto gradient : gradients) { - SPGradient* grad = SP_GRADIENT(gradient); - if ( id == grad->getId() ) { + SPGradient *grad = SP_GRADIENT(gradient); + if (id == grad->getId()) { grad->setSwatch(false); - DocumentUndo::done(doc, SP_VERB_CONTEXT_GRADIENT, - _("Delete swatch")); + DocumentUndo::done(doc, SP_VERB_CONTEXT_GRADIENT, _("Delete swatch")); break; } } diff --git a/src/gradient-chemistry.h b/src/gradient-chemistry.h index 90a63f389555c8b12b1962b4a3d605781a159e7a..ea45a30574c9b544daf45984b2442ff21601dfcd 100644 --- a/src/gradient-chemistry.h +++ b/src/gradient-chemistry.h @@ -26,7 +26,6 @@ class SPItem; class SPGradient; class SPDesktop; - /** * Either normalizes given gradient to vector, or returns fresh normalized * vector - in latter case, original gradient is flattened and stops cleared. @@ -35,43 +34,43 @@ class SPDesktop; */ SPGradient *sp_gradient_ensure_vector_normalized(SPGradient *gradient); - /** * Sets item fill or stroke to the gradient of the specified type with given vector, creating * new private gradient, if needed. * gr has to be a normalized vector. */ -SPGradient *sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType type, Inkscape::PaintTarget fill_or_stroke); +SPGradient *sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType type, + Inkscape::PaintTarget fill_or_stroke); /* * Get default normalized gradient vector of document, create if there is none */ -SPGradient *sp_document_default_gradient_vector( SPDocument *document, SPColor const &color, bool singleStop ); +SPGradient *sp_document_default_gradient_vector(SPDocument *document, SPColor const &color, bool singleStop); /** * Return the preferred vector for \a o, made from (in order of preference) its current vector, * current fill or stroke color, or from desktop style if \a o is NULL or doesn't have style. */ -SPGradient *sp_gradient_vector_for_object( SPDocument *doc, SPDesktop *desktop, SPObject *o, Inkscape::PaintTarget fill_or_stroke, bool singleStop = false ); +SPGradient *sp_gradient_vector_for_object(SPDocument *doc, SPDesktop *desktop, SPObject *o, + Inkscape::PaintTarget fill_or_stroke, bool singleStop = false); -void sp_object_ensure_fill_gradient_normalized (SPObject *object); -void sp_object_ensure_stroke_gradient_normalized (SPObject *object); +void sp_object_ensure_fill_gradient_normalized(SPObject *object); +void sp_object_ensure_stroke_gradient_normalized(SPObject *object); -SPGradient *sp_gradient_convert_to_userspace (SPGradient *gr, SPItem *item, const char *property); -SPGradient *sp_gradient_reset_to_userspace (SPGradient *gr, SPItem *item); +SPGradient *sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, const char *property); +SPGradient *sp_gradient_reset_to_userspace(SPGradient *gr, SPItem *item); -SPGradient *sp_gradient_fork_vector_if_necessary (SPGradient *gr); +SPGradient *sp_gradient_fork_vector_if_necessary(SPGradient *gr); SPGradient *sp_gradient_get_forked_vector_if_necessary(SPGradient *gradient, bool force_vector); - -SPStop* sp_last_stop(SPGradient *gradient); -SPStop* sp_get_stop_i(SPGradient *gradient, unsigned int i); +SPStop *sp_last_stop(SPGradient *gradient); +SPStop *sp_get_stop_i(SPGradient *gradient, unsigned int i); unsigned int sp_number_of_stops(SPGradient const *gradient); unsigned int sp_number_of_stops_before_stop(SPGradient const *gradient, SPStop *target); guint32 average_color(guint32 c1, guint32 c2, double p = 0.5); -SPStop *sp_vector_add_stop(SPGradient *vector, SPStop* prev_stop, SPStop* next_stop, gfloat offset); +SPStop *sp_vector_add_stop(SPGradient *vector, SPStop *prev_stop, SPStop *next_stop, gfloat offset); void sp_gradient_transform_multiply(SPGradient *gradient, Geom::Affine postmul, bool set); @@ -89,20 +88,23 @@ void sp_gradient_unset_swatch(SPDesktop *desktop, std::string id); */ SPGradient *getGradient(SPItem *item, Inkscape::PaintTarget fill_or_stroke); - -void sp_item_gradient_set_coords(SPItem *item, GrPointType point_type, unsigned int point_i, Geom::Point p_desk, Inkscape::PaintTarget fill_or_stroke, bool write_repr, bool scale); +void sp_item_gradient_set_coords(SPItem *item, GrPointType point_type, unsigned int point_i, Geom::Point p_desk, + Inkscape::PaintTarget fill_or_stroke, bool write_repr, bool scale); /** * Returns the position of point point_type of the gradient applied to item (either fill_or_stroke), * in desktop coordinates. -*/ -Geom::Point getGradientCoords(SPItem *item, GrPointType point_type, unsigned int point_i, Inkscape::PaintTarget fill_or_stroke); + */ +Geom::Point getGradientCoords(SPItem *item, GrPointType point_type, unsigned int point_i, + Inkscape::PaintTarget fill_or_stroke); SPGradient *sp_item_gradient_get_vector(SPItem *item, Inkscape::PaintTarget fill_or_stroke); SPGradientSpread sp_item_gradient_get_spread(SPItem *item, Inkscape::PaintTarget fill_or_stroke); -void sp_item_gradient_stop_set_style(SPItem *item, GrPointType point_type, unsigned int point_i, Inkscape::PaintTarget fill_or_stroke, SPCSSAttr *stop); -guint32 sp_item_gradient_stop_query_style(SPItem *item, GrPointType point_type, unsigned int point_i, Inkscape::PaintTarget fill_or_stroke); +void sp_item_gradient_stop_set_style(SPItem *item, GrPointType point_type, unsigned int point_i, + Inkscape::PaintTarget fill_or_stroke, SPCSSAttr *stop); +guint32 sp_item_gradient_stop_query_style(SPItem *item, GrPointType point_type, unsigned int point_i, + Inkscape::PaintTarget fill_or_stroke); void sp_item_gradient_reverse_vector(SPItem *item, Inkscape::PaintTarget fill_or_stroke); void sp_item_gradient_invert_vector_color(SPItem *item, Inkscape::PaintTarget fill_or_stroke); diff --git a/src/gradient-drag.cpp b/src/gradient-drag.cpp index 8bec3ae5a72f10b3f95ca6fbedb1aea9e6ba8a0b..9bcc0e1265532dadb5a662e159d022f67812c504 100644 --- a/src/gradient-drag.cpp +++ b/src/gradient-drag.cpp @@ -15,112 +15,99 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include +#include "gradient-drag.h" +#include #include +#include #include "desktop-style.h" #include "desktop.h" +#include "display/sp-canvas-util.h" +#include "display/sp-ctrlcurve.h" +#include "display/sp-ctrlline.h" #include "document-undo.h" #include "document.h" #include "gradient-chemistry.h" -#include "gradient-drag.h" #include "include/macros.h" #include "inkscape.h" #include "knot.h" -#include "selection-chemistry.h" -#include "selection.h" -#include "snap.h" -#include "verbs.h" - -#include "display/sp-canvas-util.h" -#include "display/sp-ctrlcurve.h" -#include "display/sp-ctrlline.h" - #include "object/sp-linear-gradient.h" #include "object/sp-mesh-gradient.h" #include "object/sp-namedview.h" #include "object/sp-radial-gradient.h" #include "object/sp-stop.h" +#include "selection-chemistry.h" +#include "selection.h" +#include "snap.h" #include "style.h" - #include "svg/css-ostringstream.h" #include "svg/svg.h" - #include "ui/control-manager.h" #include "ui/tools/tool-base.h" #include "ui/widget/canvas.h" // Forced redraws - +#include "verbs.h" #include "xml/sp-css-attr.h" -using Inkscape::ControlManager; -using Inkscape::CtrlLineType; -using Inkscape::DocumentUndo; using Inkscape::allPaintTargets; +using Inkscape::ControlManager; using Inkscape::CTLINE_PRIMARY; using Inkscape::CTLINE_SECONDARY; +using Inkscape::CtrlLineType; +using Inkscape::DocumentUndo; -guint32 const GR_KNOT_COLOR_NORMAL = 0xffffff00; -guint32 const GR_KNOT_COLOR_MOUSEOVER = 0xff000000; -guint32 const GR_KNOT_COLOR_SELECTED = 0x0000ff00; -guint32 const GR_KNOT_COLOR_HIGHLIGHT = 0xffffff00; +guint32 const GR_KNOT_COLOR_NORMAL = 0xffffff00; +guint32 const GR_KNOT_COLOR_MOUSEOVER = 0xff000000; +guint32 const GR_KNOT_COLOR_SELECTED = 0x0000ff00; +guint32 const GR_KNOT_COLOR_HIGHLIGHT = 0xffffff00; guint32 const GR_KNOT_COLOR_MESHCORNER = 0xbfbfbf00; // absolute distance between gradient points for them to become a single dragger when the drag is created: #define MERGE_DIST 0.1 // knot shapes corresponding to GrPointType enum (in sp-gradient.h) -SPKnotShapeType gr_knot_shapes [] = { - SP_KNOT_SHAPE_SQUARE, // POINT_LG_BEGIN - SP_KNOT_SHAPE_CIRCLE, // POINT_LG_END - SP_KNOT_SHAPE_DIAMOND, // POINT_LG_MID - SP_KNOT_SHAPE_SQUARE, // POINT_RG_CENTER - SP_KNOT_SHAPE_CIRCLE, // POINT_RG_R1 - SP_KNOT_SHAPE_CIRCLE, // POINT_RG_R2 - SP_KNOT_SHAPE_CROSS, // POINT_RG_FOCUS - SP_KNOT_SHAPE_DIAMOND, // POINT_RG_MID1 - SP_KNOT_SHAPE_DIAMOND, // POINT_RG_MID2 - SP_KNOT_SHAPE_DIAMOND, // POINT_MG_CORNER - SP_KNOT_SHAPE_CIRCLE, // POINT_MG_HANDLE - SP_KNOT_SHAPE_SQUARE // POINT_MG_TENSOR +SPKnotShapeType gr_knot_shapes[] = { + SP_KNOT_SHAPE_SQUARE, // POINT_LG_BEGIN + SP_KNOT_SHAPE_CIRCLE, // POINT_LG_END + SP_KNOT_SHAPE_DIAMOND, // POINT_LG_MID + SP_KNOT_SHAPE_SQUARE, // POINT_RG_CENTER + SP_KNOT_SHAPE_CIRCLE, // POINT_RG_R1 + SP_KNOT_SHAPE_CIRCLE, // POINT_RG_R2 + SP_KNOT_SHAPE_CROSS, // POINT_RG_FOCUS + SP_KNOT_SHAPE_DIAMOND, // POINT_RG_MID1 + SP_KNOT_SHAPE_DIAMOND, // POINT_RG_MID2 + SP_KNOT_SHAPE_DIAMOND, // POINT_MG_CORNER + SP_KNOT_SHAPE_CIRCLE, // POINT_MG_HANDLE + SP_KNOT_SHAPE_SQUARE // POINT_MG_TENSOR }; -const gchar *gr_knot_descr [] = { - N_("Linear gradient start"), //POINT_LG_BEGIN - N_("Linear gradient end"), - N_("Linear gradient mid stop"), - N_("Radial gradient center"), - N_("Radial gradient radius"), - N_("Radial gradient radius"), +const gchar *gr_knot_descr[] = { + N_("Linear gradient start"), // POINT_LG_BEGIN + N_("Linear gradient end"), N_("Linear gradient mid stop"), N_("Radial gradient center"), + N_("Radial gradient radius"), N_("Radial gradient radius"), N_("Radial gradient focus"), // POINT_RG_FOCUS - N_("Radial gradient mid stop"), - N_("Radial gradient mid stop"), - N_("Mesh gradient corner"), - N_("Mesh gradient handle"), - N_("Mesh gradient tensor") -}; + N_("Radial gradient mid stop"), N_("Radial gradient mid stop"), N_("Mesh gradient corner"), + N_("Mesh gradient handle"), N_("Mesh gradient tensor")}; -static void -gr_drag_sel_changed(Inkscape::Selection */*selection*/, gpointer data) +static void gr_drag_sel_changed(Inkscape::Selection * /*selection*/, gpointer data) { - GrDrag *drag = (GrDrag *) data; - drag->updateDraggers (); - drag->updateLines (); - drag->updateLevels (); + GrDrag *drag = (GrDrag *)data; + drag->updateDraggers(); + drag->updateLines(); + drag->updateLevels(); } -static void gr_drag_sel_modified(Inkscape::Selection */*selection*/, guint /*flags*/, gpointer data) +static void gr_drag_sel_modified(Inkscape::Selection * /*selection*/, guint /*flags*/, gpointer data) { - GrDrag *drag = (GrDrag *) data; + GrDrag *drag = (GrDrag *)data; if (drag->local_change) { - drag->refreshDraggers (); // Needed to move mesh handles and toggle visibility + drag->refreshDraggers(); // Needed to move mesh handles and toggle visibility drag->local_change = false; } else { - drag->updateDraggers (); + drag->updateDraggers(); } - drag->updateLines (); - drag->updateLevels (); + drag->updateLines(); + drag->updateLevels(); } /** @@ -130,9 +117,10 @@ static void gr_drag_sel_modified(Inkscape::Selection */*selection*/, guint /*fla */ static int gr_drag_style_query(SPStyle *style, int property, gpointer data) { - GrDrag *drag = (GrDrag *) data; + GrDrag *drag = (GrDrag *)data; - if (property != QUERY_STYLE_PROPERTY_FILL && property != QUERY_STYLE_PROPERTY_STROKE && property != QUERY_STYLE_PROPERTY_MASTEROPACITY) { + if (property != QUERY_STYLE_PROPERTY_FILL && property != QUERY_STYLE_PROPERTY_STROKE && + property != QUERY_STYLE_PROPERTY_MASTEROPACITY) { return QUERY_STYLE_NOTHING; } @@ -145,21 +133,22 @@ static int gr_drag_style_query(SPStyle *style, int property, gpointer data) cf[0] = cf[1] = cf[2] = cf[3] = 0; int count = 0; - for(auto d : drag->selected) { //for all selected draggers - for(auto draggable : d->draggables) { //for all draggables of dragger + for (auto d : drag->selected) { // for all selected draggers + for (auto draggable : d->draggables) { // for all draggables of dragger if (ret == QUERY_STYLE_NOTHING) { ret = QUERY_STYLE_SINGLE; } else if (ret == QUERY_STYLE_SINGLE) { ret = QUERY_STYLE_MULTIPLE_AVERAGED; } - guint32 c = sp_item_gradient_stop_query_style (draggable->item, draggable->point_type, draggable->point_i, draggable->fill_or_stroke); - cf[0] += SP_RGBA32_R_F (c); - cf[1] += SP_RGBA32_G_F (c); - cf[2] += SP_RGBA32_B_F (c); - cf[3] += SP_RGBA32_A_F (c); + guint32 c = sp_item_gradient_stop_query_style(draggable->item, draggable->point_type, + draggable->point_i, draggable->fill_or_stroke); + cf[0] += SP_RGBA32_R_F(c); + cf[1] += SP_RGBA32_G_F(c); + cf[2] += SP_RGBA32_B_F(c); + cf[3] += SP_RGBA32_A_F(c); - count ++; + count++; } } @@ -171,18 +160,18 @@ static int gr_drag_style_query(SPStyle *style, int property, gpointer data) // set both fill and stroke with our stop-color and stop-opacity style->fill.clear(); - style->fill.setColor( cf[0], cf[1], cf[2] ); + style->fill.setColor(cf[0], cf[1], cf[2]); style->fill.set = TRUE; style->stroke.clear(); - style->stroke.setColor( cf[0], cf[1], cf[2] ); + style->stroke.setColor(cf[0], cf[1], cf[2]); style->stroke.set = TRUE; - style->fill_opacity.value = SP_SCALE24_FROM_FLOAT (cf[3]); + style->fill_opacity.value = SP_SCALE24_FROM_FLOAT(cf[3]); style->fill_opacity.set = TRUE; - style->stroke_opacity.value = SP_SCALE24_FROM_FLOAT (cf[3]); + style->stroke_opacity.value = SP_SCALE24_FROM_FLOAT(cf[3]); style->stroke_opacity.set = TRUE; - style->opacity.value = SP_SCALE24_FROM_FLOAT (cf[3]); + style->opacity.value = SP_SCALE24_FROM_FLOAT(cf[3]); style->opacity.set = TRUE; } @@ -190,24 +179,24 @@ static int gr_drag_style_query(SPStyle *style, int property, gpointer data) } } -Glib::ustring GrDrag::makeStopSafeColor( gchar const *str, bool &isNull ) +Glib::ustring GrDrag::makeStopSafeColor(gchar const *str, bool &isNull) { Glib::ustring colorStr; - if ( str ) { + if (str) { isNull = false; colorStr = str; Glib::ustring::size_type pos = colorStr.find("url(#"); - if ( pos != Glib::ustring::npos ) { + if (pos != Glib::ustring::npos) { Glib::ustring targetName = colorStr.substr(pos + 5, colorStr.length() - 6); std::vector gradients = desktop->doc()->getResourceList("gradient"); for (auto gradient : gradients) { - SPGradient* grad = SP_GRADIENT(gradient); - if ( targetName == grad->getId() ) { + SPGradient *grad = SP_GRADIENT(gradient); + if (targetName == grad->getId()) { SPGradient *vect = grad->getVector(); SPStop *firstStop = (vect) ? vect->getFirstStop() : grad->getFirstStop(); if (firstStop) { Glib::ustring stopColorStr = firstStop->getColor().toString(); - if ( !stopColorStr.empty() ) { + if (!stopColorStr.empty()) { colorStr = stopColorStr; } } @@ -222,7 +211,7 @@ Glib::ustring GrDrag::makeStopSafeColor( gchar const *str, bool &isNull ) return colorStr; } -bool GrDrag::styleSet( const SPCSSAttr *css ) +bool GrDrag::styleSet(const SPCSSAttr *css) { if (selected.empty()) { return false; @@ -235,42 +224,41 @@ bool GrDrag::styleSet( const SPCSSAttr *css ) // any of color properties, in order of increasing priority: if (css->attribute("flood-color")) { - sp_repr_css_set_property (stop, "stop-color", css->attribute("flood-color")); + sp_repr_css_set_property(stop, "stop-color", css->attribute("flood-color")); } if (css->attribute("lighting-color")) { - sp_repr_css_set_property (stop, "stop-color", css->attribute("lighting-color")); + sp_repr_css_set_property(stop, "stop-color", css->attribute("lighting-color")); } if (css->attribute("color")) { - sp_repr_css_set_property (stop, "stop-color", css->attribute("color")); + sp_repr_css_set_property(stop, "stop-color", css->attribute("color")); } if (css->attribute("stroke") && strcmp(css->attribute("stroke"), "none")) { - sp_repr_css_set_property (stop, "stop-color", css->attribute("stroke")); + sp_repr_css_set_property(stop, "stop-color", css->attribute("stroke")); } if (css->attribute("fill") && strcmp(css->attribute("fill"), "none")) { - sp_repr_css_set_property (stop, "stop-color", css->attribute("fill")); + sp_repr_css_set_property(stop, "stop-color", css->attribute("fill")); } if (css->attribute("stop-color")) { - sp_repr_css_set_property (stop, "stop-color", css->attribute("stop-color")); + sp_repr_css_set_property(stop, "stop-color", css->attribute("stop-color")); } // Make sure the style is allowed for gradient stops. - if ( !sp_repr_css_property_is_unset( stop, "stop-color") ) { + if (!sp_repr_css_property_is_unset(stop, "stop-color")) { bool stopIsNull = false; - Glib::ustring tmp = makeStopSafeColor( sp_repr_css_property( stop, "stop-color", "" ), stopIsNull ); - if ( !stopIsNull && !tmp.empty() ) { - sp_repr_css_set_property( stop, "stop-color", tmp.c_str() ); + Glib::ustring tmp = makeStopSafeColor(sp_repr_css_property(stop, "stop-color", ""), stopIsNull); + if (!stopIsNull && !tmp.empty()) { + sp_repr_css_set_property(stop, "stop-color", tmp.c_str()); } } - if (css->attribute("stop-opacity")) { // direct setting of stop-opacity has priority sp_repr_css_set_property(stop, "stop-opacity", css->attribute("stop-opacity")); - } else { // multiply all opacity properties: + } else { // multiply all opacity properties: gdouble accumulated = 1.0; accumulated *= sp_svg_read_percentage(css->attribute("flood-opacity"), 1.0); accumulated *= sp_svg_read_percentage(css->attribute("opacity"), 1.0); @@ -283,7 +271,8 @@ bool GrDrag::styleSet( const SPCSSAttr *css ) if ((css->attribute("fill") && !css->attribute("stroke") && !strcmp(css->attribute("fill"), "none")) || (css->attribute("stroke") && !css->attribute("fill") && !strcmp(css->attribute("stroke"), "none"))) { - sp_repr_css_set_property(stop, "stop-opacity", "0"); // if a single fill/stroke property is set to none, don't change color, set opacity to 0 + sp_repr_css_set_property(stop, "stop-opacity", "0"); // if a single fill/stroke property is set to none, + // don't change color, set opacity to 0 } } @@ -292,36 +281,39 @@ bool GrDrag::styleSet( const SPCSSAttr *css ) return false; } - for(auto d : selected) { //for all selected draggers - for(auto draggable : d->draggables) { //for all draggables of dragger + for (auto d : selected) { // for all selected draggers + for (auto draggable : d->draggables) { // for all draggables of dragger local_change = true; - sp_item_gradient_stop_set_style(draggable->item, draggable->point_type, draggable->point_i, draggable->fill_or_stroke, stop); + sp_item_gradient_stop_set_style(draggable->item, draggable->point_type, draggable->point_i, + draggable->fill_or_stroke, stop); } } - //sp_repr_css_print(stop); + // sp_repr_css_print(stop); sp_repr_css_attr_unref(stop); return true; } guint32 GrDrag::getColor() { - if (selected.empty()) return 0; + if (selected.empty()) + return 0; float cf[4]; cf[0] = cf[1] = cf[2] = cf[3] = 0; int count = 0; - for(auto d : selected) { //for all selected draggers - for(auto draggable : d->draggables) { //for all draggables of dragger - guint32 c = sp_item_gradient_stop_query_style (draggable->item, draggable->point_type, draggable->point_i, draggable->fill_or_stroke); - cf[0] += SP_RGBA32_R_F (c); - cf[1] += SP_RGBA32_G_F (c); - cf[2] += SP_RGBA32_B_F (c); - cf[3] += SP_RGBA32_A_F (c); + for (auto d : selected) { // for all selected draggers + for (auto draggable : d->draggables) { // for all draggables of dragger + guint32 c = sp_item_gradient_stop_query_style(draggable->item, draggable->point_type, draggable->point_i, + draggable->fill_or_stroke); + cf[0] += SP_RGBA32_R_F(c); + cf[1] += SP_RGBA32_G_F(c); + cf[2] += SP_RGBA32_B_F(c); + cf[3] += SP_RGBA32_A_F(c); - count ++; + count++; } } @@ -340,7 +332,7 @@ SPStop *GrDrag::addStopNearPoint(SPItem *item, Geom::Point mouse_p, double toler { gfloat new_stop_offset = 0; // type of SPStop.offset = gfloat SPGradient *gradient = nullptr; - //bool r1_knot = false; + // bool r1_knot = false; // For Mesh int divide_row = -1; @@ -349,18 +341,18 @@ SPStop *GrDrag::addStopNearPoint(SPItem *item, Geom::Point mouse_p, double toler bool addknot = false; - for (std::vector::const_iterator it = allPaintTargets().begin(); (it != allPaintTargets().end()) && !addknot; ++it) - { + for (std::vector::const_iterator it = allPaintTargets().begin(); + (it != allPaintTargets().end()) && !addknot; ++it) { Inkscape::PaintTarget fill_or_stroke = *it; gradient = getGradient(item, fill_or_stroke); if (SP_IS_LINEARGRADIENT(gradient)) { - Geom::Point begin = getGradientCoords(item, POINT_LG_BEGIN, 0, fill_or_stroke); - Geom::Point end = getGradientCoords(item, POINT_LG_END, 0, fill_or_stroke); + Geom::Point begin = getGradientCoords(item, POINT_LG_BEGIN, 0, fill_or_stroke); + Geom::Point end = getGradientCoords(item, POINT_LG_END, 0, fill_or_stroke); Geom::LineSegment ls(begin, end); double offset = ls.nearestTime(mouse_p); Geom::Point nearest = ls.pointAt(offset); double dist_screen = Geom::distance(mouse_p, nearest); - if ( dist_screen < tolerance ) { + if (dist_screen < tolerance) { // calculate the new stop offset new_stop_offset = distance(begin, nearest) / distance(begin, end); // add the knot @@ -368,33 +360,32 @@ SPStop *GrDrag::addStopNearPoint(SPItem *item, Geom::Point mouse_p, double toler } } else if (SP_IS_RADIALGRADIENT(gradient)) { Geom::Point begin = getGradientCoords(item, POINT_RG_CENTER, 0, fill_or_stroke); - Geom::Point end = getGradientCoords(item, POINT_RG_R1, 0, fill_or_stroke); + Geom::Point end = getGradientCoords(item, POINT_RG_R1, 0, fill_or_stroke); Geom::LineSegment ls(begin, end); double offset = ls.nearestTime(mouse_p); Geom::Point nearest = ls.pointAt(offset); double dist_screen = Geom::distance(mouse_p, nearest); - if ( dist_screen < tolerance ) { + if (dist_screen < tolerance) { // calculate the new stop offset new_stop_offset = distance(begin, nearest) / distance(begin, end); // add the knot addknot = true; - //r1_knot = true; + // r1_knot = true; } else { end = getGradientCoords(item, POINT_RG_R2, 0, fill_or_stroke); ls = Geom::LineSegment(begin, end); offset = ls.nearestTime(mouse_p); nearest = ls.pointAt(offset); dist_screen = Geom::distance(mouse_p, nearest); - if ( dist_screen < tolerance ) { + if (dist_screen < tolerance) { // calculate the new stop offset new_stop_offset = distance(begin, nearest) / distance(begin, end); // add the knot addknot = true; - //r1_knot = false; + // r1_knot = false; } } } else if (SP_IS_MESHGRADIENT(gradient)) { - // add_stop_near_point() // Find out which curve pointer is over and use that curve to determine // which row or column will be divided. @@ -402,29 +393,28 @@ SPStop *GrDrag::addStopNearPoint(SPItem *item, Geom::Point mouse_p, double toler // but that information is not saved (sp_gradient_context_is_over_line). SPMeshGradient *mg = SP_MESHGRADIENT(gradient); - Geom::Affine transform = Geom::Affine(mg->gradientTransform)*(Geom::Affine)item->i2dt_affine(); + Geom::Affine transform = Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); - guint rows = mg->array.patch_rows(); + guint rows = mg->array.patch_rows(); guint columns = mg->array.patch_columns(); double closest = 1e10; - for( guint i = 0; i < rows; ++i ) { - for( guint j = 0; j < columns; ++j ) { - - SPMeshPatchI patch( &(mg->array.nodes), i, j ); + for (guint i = 0; i < rows; ++i) { + for (guint j = 0; j < columns; ++j) { + SPMeshPatchI patch(&(mg->array.nodes), i, j); Geom::Point p[4]; // Top line { - p[0] = patch.getPoint( 0, 0 ) * transform; - p[1] = patch.getPoint( 0, 1 ) * transform; - p[2] = patch.getPoint( 0, 2 ) * transform; - p[3] = patch.getPoint( 0, 3 ) * transform; - Geom::BezierCurveN<3> b( p[0], p[1], p[2], p[3] ); - Geom::Coord coord = b.nearestTime( mouse_p ); - Geom::Point nearest = b( coord ); - double dist_screen = Geom::L2 ( mouse_p - nearest ); - if ( dist_screen < closest ) { + p[0] = patch.getPoint(0, 0) * transform; + p[1] = patch.getPoint(0, 1) * transform; + p[2] = patch.getPoint(0, 2) * transform; + p[3] = patch.getPoint(0, 3) * transform; + Geom::BezierCurveN<3> b(p[0], p[1], p[2], p[3]); + Geom::Coord coord = b.nearestTime(mouse_p); + Geom::Point nearest = b(coord); + double dist_screen = Geom::L2(mouse_p - nearest); + if (dist_screen < closest) { closest = dist_screen; divide_row = -1; divide_column = j; @@ -433,16 +423,16 @@ SPStop *GrDrag::addStopNearPoint(SPItem *item, Geom::Point mouse_p, double toler } // Right line (only for last column) - if( j == columns - 1 ) { - p[0] = patch.getPoint( 1, 0 ) * transform; - p[1] = patch.getPoint( 1, 1 ) * transform; - p[2] = patch.getPoint( 1, 2 ) * transform; - p[3] = patch.getPoint( 1, 3 ) * transform; - Geom::BezierCurveN<3> b( p[0], p[1], p[2], p[3] ); - Geom::Coord coord = b.nearestTime( mouse_p ); - Geom::Point nearest = b( coord ); - double dist_screen = Geom::L2 ( mouse_p - nearest ); - if ( dist_screen < closest ) { + if (j == columns - 1) { + p[0] = patch.getPoint(1, 0) * transform; + p[1] = patch.getPoint(1, 1) * transform; + p[2] = patch.getPoint(1, 2) * transform; + p[3] = patch.getPoint(1, 3) * transform; + Geom::BezierCurveN<3> b(p[0], p[1], p[2], p[3]); + Geom::Coord coord = b.nearestTime(mouse_p); + Geom::Point nearest = b(coord); + double dist_screen = Geom::L2(mouse_p - nearest); + if (dist_screen < closest) { closest = dist_screen; divide_row = i; divide_column = -1; @@ -451,16 +441,16 @@ SPStop *GrDrag::addStopNearPoint(SPItem *item, Geom::Point mouse_p, double toler } // Bottom line (only for last row) - if( i == rows - 1 ) { - p[0] = patch.getPoint( 2, 0 ) * transform; - p[1] = patch.getPoint( 2, 1 ) * transform; - p[2] = patch.getPoint( 2, 2 ) * transform; - p[3] = patch.getPoint( 2, 3 ) * transform; - Geom::BezierCurveN<3> b( p[0], p[1], p[2], p[3] ); - Geom::Coord coord = b.nearestTime( mouse_p ); - Geom::Point nearest = b( coord ); - double dist_screen = Geom::L2 ( mouse_p - nearest ); - if ( dist_screen < closest ) { + if (i == rows - 1) { + p[0] = patch.getPoint(2, 0) * transform; + p[1] = patch.getPoint(2, 1) * transform; + p[2] = patch.getPoint(2, 2) * transform; + p[3] = patch.getPoint(2, 3) * transform; + Geom::BezierCurveN<3> b(p[0], p[1], p[2], p[3]); + Geom::Coord coord = b.nearestTime(mouse_p); + Geom::Point nearest = b(coord); + double dist_screen = Geom::L2(mouse_p - nearest); + if (dist_screen < closest) { closest = dist_screen; divide_row = -1; divide_column = j; @@ -470,15 +460,15 @@ SPStop *GrDrag::addStopNearPoint(SPItem *item, Geom::Point mouse_p, double toler // Left line { - p[0] = patch.getPoint( 3, 0 ) * transform; - p[1] = patch.getPoint( 3, 1 ) * transform; - p[2] = patch.getPoint( 3, 2 ) * transform; - p[3] = patch.getPoint( 3, 3 ) * transform; - Geom::BezierCurveN<3> b( p[0], p[1], p[2], p[3] ); - Geom::Coord coord = b.nearestTime( mouse_p ); - Geom::Point nearest = b( coord ); - double dist_screen = Geom::L2 ( mouse_p - nearest ); - if ( dist_screen < closest ) { + p[0] = patch.getPoint(3, 0) * transform; + p[1] = patch.getPoint(3, 1) * transform; + p[2] = patch.getPoint(3, 2) * transform; + p[3] = patch.getPoint(3, 3) * transform; + Geom::BezierCurveN<3> b(p[0], p[1], p[2], p[3]); + Geom::Coord coord = b.nearestTime(mouse_p); + Geom::Point nearest = b(coord); + double dist_screen = Geom::L2(mouse_p - nearest); + if (dist_screen < closest) { closest = dist_screen; divide_row = i; divide_column = -1; @@ -487,24 +477,22 @@ SPStop *GrDrag::addStopNearPoint(SPItem *item, Geom::Point mouse_p, double toler } } // End loop over columns - } // End loop rows + } // End loop rows - if( closest < tolerance ) { + if (closest < tolerance) { addknot = true; } } // End if mesh - } if (addknot) { - - if( SP_IS_LINEARGRADIENT(gradient) || SP_IS_RADIALGRADIENT( gradient ) ) { - SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (gradient, false); - SPStop* prev_stop = vector->getFirstStop(); - SPStop* next_stop = prev_stop->getNextStop(); + if (SP_IS_LINEARGRADIENT(gradient) || SP_IS_RADIALGRADIENT(gradient)) { + SPGradient *vector = sp_gradient_get_forked_vector_if_necessary(gradient, false); + SPStop *prev_stop = vector->getFirstStop(); + SPStop *next_stop = prev_stop->getNextStop(); guint i = 1; - while ( (next_stop) && (next_stop->offset < new_stop_offset) ) { + while ((next_stop) && (next_stop->offset < new_stop_offset)) { prev_stop = next_stop; next_stop = next_stop->getNextStop(); i++; @@ -514,8 +502,7 @@ SPStop *GrDrag::addStopNearPoint(SPItem *item, Geom::Point mouse_p, double toler return nullptr; } - - SPStop *newstop = sp_vector_add_stop (vector, prev_stop, next_stop, new_stop_offset); + SPStop *newstop = sp_vector_add_stop(vector, prev_stop, next_stop, new_stop_offset); gradient->ensureVector(); updateDraggers(); @@ -528,22 +515,20 @@ SPStop *GrDrag::addStopNearPoint(SPItem *item, Geom::Point mouse_p, double toler return newstop; } else { - SPMeshGradient *mg = SP_MESHGRADIENT(gradient); - if( divide_row > -1 ) { - mg->array.split_row( divide_row, divide_coord ); + if (divide_row > -1) { + mg->array.split_row(divide_row, divide_coord); } else { - mg->array.split_column( divide_column, divide_coord ); + mg->array.split_column(divide_column, divide_coord); } // Update repr - mg->array.write( mg ); + mg->array.write(mg); mg->array.built = false; mg->ensureArray(); // How do we do this? - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MESH, - _("Added patch row or column")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MESH, _("Added patch row or column")); } // Mesh } @@ -551,25 +536,25 @@ SPStop *GrDrag::addStopNearPoint(SPItem *item, Geom::Point mouse_p, double toler return nullptr; } - -bool GrDrag::dropColor(SPItem */*item*/, gchar const *c, Geom::Point p) +bool GrDrag::dropColor(SPItem * /*item*/, gchar const *c, Geom::Point p) { // Note: not sure if a null pointer can come in for the style, but handle that just in case bool stopIsNull = false; - Glib::ustring toUse = makeStopSafeColor( c, stopIsNull ); + Glib::ustring toUse = makeStopSafeColor(c, stopIsNull); // first, see if we can drop onto one of the existing draggers - for(auto d : draggers) { //for all draggers - if (Geom::L2(p - d->point)*desktop->current_zoom() < 5) { - SPCSSAttr *stop = sp_repr_css_attr_new (); - sp_repr_css_set_property( stop, "stop-color", stopIsNull ? nullptr : toUse.c_str() ); - sp_repr_css_set_property( stop, "stop-opacity", "1" ); - for(auto draggable : d->draggables) { //for all draggables of dragger - local_change = true; - sp_item_gradient_stop_set_style (draggable->item, draggable->point_type, draggable->point_i, draggable->fill_or_stroke, stop); - } - sp_repr_css_attr_unref(stop); - return true; + for (auto d : draggers) { // for all draggers + if (Geom::L2(p - d->point) * desktop->current_zoom() < 5) { + SPCSSAttr *stop = sp_repr_css_attr_new(); + sp_repr_css_set_property(stop, "stop-color", stopIsNull ? nullptr : toUse.c_str()); + sp_repr_css_set_property(stop, "stop-opacity", "1"); + for (auto draggable : d->draggables) { // for all draggables of dragger + local_change = true; + sp_item_gradient_stop_set_style(draggable->item, draggable->point_type, draggable->point_i, + draggable->fill_or_stroke, stop); + } + sp_repr_css_attr_unref(stop); + return true; } } @@ -582,11 +567,11 @@ bool GrDrag::dropColor(SPItem */*item*/, gchar const *c, Geom::Point p) Geom::Point nearest = ls.pointAt(ls.nearestTime(p)); double dist_screen = Geom::L2(p - nearest) * desktop->current_zoom(); if (line->item && dist_screen < 5) { - SPStop *stop = addStopNearPoint(line->item, p, 5/desktop->current_zoom()); + SPStop *stop = addStopNearPoint(line->item, p, 5 / desktop->current_zoom()); if (stop) { SPCSSAttr *css = sp_repr_css_attr_new(); - sp_repr_css_set_property( css, "stop-color", stopIsNull ? nullptr : toUse.c_str() ); - sp_repr_css_set_property( css, "stop-opacity", "1" ); + sp_repr_css_set_property(css, "stop-color", stopIsNull ? nullptr : toUse.c_str()); + sp_repr_css_set_property(css, "stop-opacity", "1"); sp_repr_css_change(stop->getRepr(), css, "style"); return true; } @@ -597,47 +582,39 @@ bool GrDrag::dropColor(SPItem */*item*/, gchar const *c, Geom::Point p) return false; } - -GrDrag::GrDrag(SPDesktop *desktop) : - keep_selection(false), - local_change(false), - desktop(desktop), - hor_levels(), - vert_levels(), - draggers(0), - lines(0), - selection(desktop->getSelection()), - sel_changed_connection(), - sel_modified_connection(), - style_set_connection(), - style_query_connection() +GrDrag::GrDrag(SPDesktop *desktop) + : keep_selection(false) + , local_change(false) + , desktop(desktop) + , hor_levels() + , vert_levels() + , draggers(0) + , lines(0) + , selection(desktop->getSelection()) + , sel_changed_connection() + , sel_modified_connection() + , style_set_connection() + , style_query_connection() { - sel_changed_connection = selection->connectChangedFirst( - sigc::bind( - sigc::ptr_fun(&gr_drag_sel_changed), - (gpointer)this ) + sel_changed_connection = + selection->connectChangedFirst(sigc::bind(sigc::ptr_fun(&gr_drag_sel_changed), (gpointer)this) ); - sel_modified_connection = selection->connectModifiedFirst( - sigc::bind( - sigc::ptr_fun(&gr_drag_sel_modified), - (gpointer)this ) - ); + sel_modified_connection = + selection->connectModifiedFirst(sigc::bind(sigc::ptr_fun(&gr_drag_sel_modified), (gpointer)this)); - style_set_connection = desktop->connectSetStyle( sigc::mem_fun(*this, &GrDrag::styleSet) ); + style_set_connection = desktop->connectSetStyle(sigc::mem_fun(*this, &GrDrag::styleSet)); - style_query_connection = desktop->connectQueryStyle( - sigc::bind( - sigc::ptr_fun(&gr_drag_style_query), - (gpointer)this ) - ); + style_query_connection = + desktop->connectQueryStyle(sigc::bind(sigc::ptr_fun(&gr_drag_style_query), (gpointer)this)); updateDraggers(); updateLines(); updateLevels(); if (desktop->gr_item) { - GrDragger *dragger = getDraggerFor(desktop->gr_item, desktop->gr_point_type, desktop->gr_point_i, desktop->gr_fill_or_stroke); + GrDragger *dragger = + getDraggerFor(desktop->gr_item, desktop->gr_point_type, desktop->gr_point_i, desktop->gr_fill_or_stroke); if (dragger) { setSelected(dragger); } @@ -651,7 +628,7 @@ GrDrag::~GrDrag() this->style_set_connection.disconnect(); this->style_query_connection.disconnect(); - if (! this->selected.empty()) { + if (!this->selected.empty()) { GrDraggable *draggable = (*(this->selected.begin()))->draggables[0]; desktop->gr_item = draggable->item; desktop->gr_point_type = draggable->point_type; @@ -677,23 +654,22 @@ GrDrag::~GrDrag() this->lines.clear(); } -GrDraggable::GrDraggable(SPItem *item, GrPointType point_type, guint point_i, Inkscape::PaintTarget fill_or_stroke) : - item(item), - point_type(point_type), - point_i(point_i), - fill_or_stroke(fill_or_stroke) +GrDraggable::GrDraggable(SPItem *item, GrPointType point_type, guint point_i, Inkscape::PaintTarget fill_or_stroke) + : item(item) + , point_type(point_type) + , point_i(point_i) + , fill_or_stroke(fill_or_stroke) { - //g_object_ref(G_OBJECT(item)); - sp_object_ref(item); + // g_object_ref(G_OBJECT(item)); + sp_object_ref(item); } GrDraggable::~GrDraggable() { - //g_object_unref (G_OBJECT (this->item)); - sp_object_unref(this->item); + // g_object_unref (G_OBJECT (this->item)); + sp_object_unref(this->item); } - SPObject *GrDraggable::getServer() { SPObject *server = nullptr; @@ -713,11 +689,12 @@ SPObject *GrDraggable::getServer() static void gr_knot_moved_handler(SPKnot *knot, Geom::Point const &ppointer, guint state, gpointer data) { - GrDragger *dragger = (GrDragger *) data; + GrDragger *dragger = (GrDragger *)data; // Dragger must have at least one draggable - GrDraggable *draggable = (GrDraggable *) dragger->draggables[0]; - if (!draggable) return; + GrDraggable *draggable = (GrDraggable *)dragger->draggables[0]; + if (!draggable) + return; // Find mesh corner that corresponds to dragger (only checks first draggable) and highlight it. GrDragger *dragger_corner = dragger->getMgCorner(); @@ -734,18 +711,18 @@ static void gr_knot_moved_handler(SPKnot *knot, Geom::Point const &ppointer, gui if (state & GDK_SHIFT_MASK) { // with Shift; unsnap if we carry more than one draggable - if (dragger->draggables.size()>1) { + if (dragger->draggables.size() > 1) { // create a new dragger - GrDragger *dr_new = new GrDragger (dragger->parent, dragger->point, nullptr); + GrDragger *dr_new = new GrDragger(dragger->parent, dragger->point, nullptr); dragger->parent->draggers.insert(dragger->parent->draggers.begin(), dr_new); // relink to it all but the first draggable in the list std::vector::const_iterator i = dragger->draggables.begin(); - for ( ++i ; i != dragger->draggables.end(); ++i ) { - GrDraggable *draggable = *i; - dr_new->addDraggable (draggable); + for (++i; i != dragger->draggables.end(); ++i) { + GrDraggable *draggable = *i; + dr_new->addDraggable(draggable); } dr_new->updateKnotShape(); - if(dragger->draggables.size()>1){ + if (dragger->draggables.size() > 1) { GrDraggable *tmp = dragger->draggables[0]; dragger->draggables.clear(); dragger->draggables.push_back(tmp); @@ -755,34 +732,40 @@ static void gr_knot_moved_handler(SPKnot *knot, Geom::Point const &ppointer, gui } } else if (!(state & GDK_CONTROL_MASK)) { // without Shift or Ctrl; see if we need to snap to another dragger - for (std::vector::const_iterator di = dragger->parent->draggers.begin(); di != dragger->parent->draggers.end() ; ++di) { - GrDragger *d_new = *di; - if (dragger->mayMerge(d_new) && Geom::L2 (d_new->point - p) < snap_dist) { - + for (std::vector::const_iterator di = dragger->parent->draggers.begin(); + di != dragger->parent->draggers.end(); ++di) { + GrDragger *d_new = *di; + if (dragger->mayMerge(d_new) && Geom::L2(d_new->point - p) < snap_dist) { // Merge draggers: for (auto draggable : dragger->draggables) { // copy draggable to d_new: - GrDraggable *da_new = new GrDraggable (draggable->item, draggable->point_type, draggable->point_i, draggable->fill_or_stroke); - d_new->addDraggable (da_new); + GrDraggable *da_new = new GrDraggable(draggable->item, draggable->point_type, draggable->point_i, + draggable->fill_or_stroke); + d_new->addDraggable(da_new); } // unlink and delete this dragger - dragger->parent->draggers.erase(std::remove(dragger->parent->draggers.begin(),dragger->parent->draggers.end(), dragger),dragger->parent->draggers.end()); - d_new->parent->draggers.erase(std::remove(d_new->parent->draggers.begin(),d_new->parent->draggers.end(), dragger),d_new->parent->draggers.end()); + dragger->parent->draggers.erase( + std::remove(dragger->parent->draggers.begin(), dragger->parent->draggers.end(), dragger), + dragger->parent->draggers.end()); + d_new->parent->draggers.erase( + std::remove(d_new->parent->draggers.begin(), d_new->parent->draggers.end(), dragger), + d_new->parent->draggers.end()); d_new->parent->selected.erase(dragger); delete dragger; - // throw out delayed snap context + // throw out delayed snap context Inkscape::UI::Tools::sp_event_context_discard_delayed_snap_event(desktop->event_context); // update the new merged dragger d_new->fireDraggables(true, false, true); d_new->parent->updateLines(); - d_new->parent->setSelected (d_new); - d_new->updateKnotShape (); - d_new->updateTip (); + d_new->parent->setSelected(d_new); + d_new->updateKnotShape(); + d_new->updateTip(); d_new->updateDependencies(true); - DocumentUndo::done(d_new->parent->desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, _("Merge gradient handles")); + DocumentUndo::done(d_new->parent->desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, + _("Merge gradient handles")); return; } } @@ -803,23 +786,25 @@ static void gr_knot_moved_handler(SPKnot *knot, Geom::Point const &ppointer, gui unsigned snaps = abs(prefs->getInt("/options/rotationsnapsperpi/value", 12)); /* 0 means no snapping. */ - for (std::vector::const_iterator i = dragger->draggables.begin(); i != dragger->draggables.end(); ++i) { - GrDraggable *draggable = *i; + for (std::vector::const_iterator i = dragger->draggables.begin(); i != dragger->draggables.end(); + ++i) { + GrDraggable *draggable = *i; Geom::Point dr_snap(Geom::infinity(), Geom::infinity()); if (draggable->point_type == POINT_LG_BEGIN || draggable->point_type == POINT_LG_END) { - for (std::vector::const_iterator di = dragger->parent->draggers.begin() ; di != dragger->parent->draggers.end() ; ++di) { + for (std::vector::const_iterator di = dragger->parent->draggers.begin(); + di != dragger->parent->draggers.end(); ++di) { GrDragger *d_new = *di; if (d_new == dragger) continue; - if (d_new->isA (draggable->item, - draggable->point_type == POINT_LG_BEGIN? POINT_LG_END : POINT_LG_BEGIN, - draggable->fill_or_stroke)) { + if (d_new->isA(draggable->item, + draggable->point_type == POINT_LG_BEGIN ? POINT_LG_END : POINT_LG_BEGIN, + draggable->fill_or_stroke)) { // found the other end of the linear gradient; if (state & GDK_SHIFT_MASK) { // moving linear around center - Geom::Point center = Geom::Point (0.5*(d_new->point + dragger->point)); + Geom::Point center = Geom::Point(0.5 * (d_new->point + dragger->point)); dr_snap = center; } else { // moving linear around the other end @@ -827,14 +812,14 @@ static void gr_knot_moved_handler(SPKnot *knot, Geom::Point const &ppointer, gui } } } - } else if (draggable->point_type == POINT_RG_R1 || draggable->point_type == POINT_RG_R2 || draggable->point_type == POINT_RG_FOCUS) { - for (std::vector::const_iterator di = dragger->parent->draggers.begin(); di != dragger->parent->draggers.end(); ++di) { - GrDragger *d_new = *di; + } else if (draggable->point_type == POINT_RG_R1 || draggable->point_type == POINT_RG_R2 || + draggable->point_type == POINT_RG_FOCUS) { + for (std::vector::const_iterator di = dragger->parent->draggers.begin(); + di != dragger->parent->draggers.end(); ++di) { + GrDragger *d_new = *di; if (d_new == dragger) continue; - if (d_new->isA (draggable->item, - POINT_RG_CENTER, - draggable->fill_or_stroke)) { + if (d_new->isA(draggable->item, POINT_RG_CENTER, draggable->fill_or_stroke)) { // found the center of the radial gradient; dr_snap = d_new->point; } @@ -842,13 +827,13 @@ static void gr_knot_moved_handler(SPKnot *knot, Geom::Point const &ppointer, gui } else if (draggable->point_type == POINT_RG_CENTER) { // radial center snaps to hor/vert relative to its original position dr_snap = dragger->point_original; - } else if (draggable->point_type == POINT_MG_CORNER || - draggable->point_type == POINT_MG_HANDLE || - draggable->point_type == POINT_MG_TENSOR ) { + } else if (draggable->point_type == POINT_MG_CORNER || draggable->point_type == POINT_MG_HANDLE || + draggable->point_type == POINT_MG_TENSOR) { // std::cout << " gr_knot_moved_handler: Got mesh point!" << std::endl; } - // dr_snap contains the origin of the gradient, whereas p will be the new endpoint which we will try to snap now + // dr_snap contains the origin of the gradient, whereas p will be the new endpoint which we will try to snap + // now Inkscape::SnappedPoint sp; if (dr_snap.isFinite()) { m.setup(desktop); @@ -877,31 +862,30 @@ static void gr_knot_moved_handler(SPKnot *knot, Geom::Point const &ppointer, gui } } } - //p = isr.points.front().getPoint(); + // p = isr.points.front().getPoint(); p = bsp.getPoint(); knot->moveto(p); } - GrDrag *drag = dragger->parent; // There is just one GrDrag. - drag->keep_selection = (drag->selected.find(dragger)!=drag->selected.end()); + GrDrag *drag = dragger->parent; // There is just one GrDrag. + drag->keep_selection = (drag->selected.find(dragger) != drag->selected.end()); bool scale_radial = (state & GDK_CONTROL_MASK) && (state & GDK_SHIFT_MASK); if (drag->keep_selection) { Geom::Point diff = p - dragger->point; - drag->selected_move_nowrite (diff[Geom::X], diff[Geom::Y], scale_radial); + drag->selected_move_nowrite(diff[Geom::X], diff[Geom::Y], scale_radial); } else { Geom::Point p_old = dragger->point; dragger->point = p; - dragger->fireDraggables (false, scale_radial); + dragger->fireDraggables(false, scale_radial); dragger->updateDependencies(false); - dragger->moveMeshHandles( p_old, MG_NODE_NO_SCALE ); + dragger->moveMeshHandles(p_old, MG_NODE_NO_SCALE); } } - -static void gr_midpoint_limits(GrDragger *dragger, SPObject *server, Geom::Point *begin, Geom::Point *end, Geom::Point *low_lim, Geom::Point *high_lim, std::vector &moving) +static void gr_midpoint_limits(GrDragger *dragger, SPObject *server, Geom::Point *begin, Geom::Point *end, + Geom::Point *low_lim, Geom::Point *high_lim, std::vector &moving) { - GrDrag *drag = dragger->parent; // a midpoint dragger can (logically) only contain one GrDraggable GrDraggable *draggable = dragger->draggables[0]; @@ -915,23 +899,23 @@ static void gr_midpoint_limits(GrDragger *dragger, SPObject *server, Geom::Point GrDragger *lowest_dragger = dragger; GrDragger *highest_dragger = dragger; if (dragger->isSelected()) { - GrDragger* d_add; - while ( true ) - { - d_add = drag->getDraggerFor(draggable->item, draggable->point_type, lowest_i - 1, draggable->fill_or_stroke); - if ( d_add && drag->selected.find(d_add)!=drag->selected.end() ) { + GrDragger *d_add; + while (true) { + d_add = + drag->getDraggerFor(draggable->item, draggable->point_type, lowest_i - 1, draggable->fill_or_stroke); + if (d_add && drag->selected.find(d_add) != drag->selected.end()) { lowest_i = lowest_i - 1; - moving.insert(moving.begin(),d_add); + moving.insert(moving.begin(), d_add); lowest_dragger = d_add; } else { break; } } - while ( true ) - { - d_add = drag->getDraggerFor(draggable->item, draggable->point_type, highest_i + 1, draggable->fill_or_stroke); - if ( d_add && drag->selected.find(d_add)!=drag->selected.end() ) { + while (true) { + d_add = + drag->getDraggerFor(draggable->item, draggable->point_type, highest_i + 1, draggable->fill_or_stroke); + if (d_add && drag->selected.find(d_add) != drag->selected.end()) { highest_i = highest_i + 1; moving.push_back(d_add); highest_dragger = d_add; @@ -941,52 +925,55 @@ static void gr_midpoint_limits(GrDragger *dragger, SPObject *server, Geom::Point } } - if ( SP_IS_LINEARGRADIENT(server) ) { + if (SP_IS_LINEARGRADIENT(server)) { guint num = SP_LINEARGRADIENT(server)->vector.stops.size(); GrDragger *d_temp; if (lowest_i == 1) { - d_temp = drag->getDraggerFor (draggable->item, POINT_LG_BEGIN, 0, draggable->fill_or_stroke); + d_temp = drag->getDraggerFor(draggable->item, POINT_LG_BEGIN, 0, draggable->fill_or_stroke); } else { - d_temp = drag->getDraggerFor (draggable->item, POINT_LG_MID, lowest_i - 1, draggable->fill_or_stroke); + d_temp = drag->getDraggerFor(draggable->item, POINT_LG_MID, lowest_i - 1, draggable->fill_or_stroke); } if (d_temp) *begin = d_temp->point; - d_temp = drag->getDraggerFor (draggable->item, POINT_LG_MID, highest_i + 1, draggable->fill_or_stroke); + d_temp = drag->getDraggerFor(draggable->item, POINT_LG_MID, highest_i + 1, draggable->fill_or_stroke); if (d_temp == nullptr) { - d_temp = drag->getDraggerFor (draggable->item, POINT_LG_END, num-1, draggable->fill_or_stroke); + d_temp = drag->getDraggerFor(draggable->item, POINT_LG_END, num - 1, draggable->fill_or_stroke); } if (d_temp) *end = d_temp->point; - } else if ( SP_IS_RADIALGRADIENT(server) ) { + } else if (SP_IS_RADIALGRADIENT(server)) { guint num = SP_RADIALGRADIENT(server)->vector.stops.size(); GrDragger *d_temp; if (lowest_i == 1) { - d_temp = drag->getDraggerFor (draggable->item, POINT_RG_CENTER, 0, draggable->fill_or_stroke); + d_temp = drag->getDraggerFor(draggable->item, POINT_RG_CENTER, 0, draggable->fill_or_stroke); } else { - d_temp = drag->getDraggerFor (draggable->item, draggable->point_type, lowest_i - 1, draggable->fill_or_stroke); + d_temp = + drag->getDraggerFor(draggable->item, draggable->point_type, lowest_i - 1, draggable->fill_or_stroke); } if (d_temp) *begin = d_temp->point; - d_temp = drag->getDraggerFor (draggable->item, draggable->point_type, highest_i + 1, draggable->fill_or_stroke); + d_temp = drag->getDraggerFor(draggable->item, draggable->point_type, highest_i + 1, draggable->fill_or_stroke); if (d_temp == nullptr) { - d_temp = drag->getDraggerFor (draggable->item, (draggable->point_type==POINT_RG_MID1) ? POINT_RG_R1 : POINT_RG_R2, num-1, draggable->fill_or_stroke); + d_temp = drag->getDraggerFor(draggable->item, + (draggable->point_type == POINT_RG_MID1) ? POINT_RG_R1 : POINT_RG_R2, num - 1, + draggable->fill_or_stroke); } if (d_temp) *end = d_temp->point; } - *low_lim = dragger->point - (lowest_dragger->point - *begin); + *low_lim = dragger->point - (lowest_dragger->point - *begin); *high_lim = dragger->point - (highest_dragger->point - *end); } /** * Called when a midpoint knot is dragged. */ -static void gr_knot_moved_midpoint_handler(SPKnot */*knot*/, Geom::Point const &ppointer, guint state, gpointer data) +static void gr_knot_moved_midpoint_handler(SPKnot * /*knot*/, Geom::Point const &ppointer, guint state, gpointer data) { - GrDragger *dragger = (GrDragger *) data; + GrDragger *dragger = (GrDragger *)data; GrDrag *drag = dragger->parent; // a midpoint dragger can (logically) only contain one GrDraggable GrDraggable *draggable = dragger->draggables[0]; @@ -995,8 +982,8 @@ static void gr_knot_moved_midpoint_handler(SPKnot */*knot*/, Geom::Point const & double snap_fraction = 0.1; Geom::Point p = ppointer; - Geom::Point begin(0,0), end(0,0); - Geom::Point low_lim(0,0), high_lim(0,0); + Geom::Point begin(0, 0), end(0, 0); + Geom::Point low_lim(0, 0), high_lim(0, 0); SPObject *server = draggable->getServer(); @@ -1026,32 +1013,31 @@ static void gr_knot_moved_midpoint_handler(SPKnot */*knot*/, Geom::Point const & if (state & GDK_MOD1_MASK) { // FIXME: unify all these profiles (here, in nodepath, in tweak) in one place double alpha = 1.0; - if (Geom::L2(drg->point - dragger->point) + Geom::L2(drg->point - begin) - 1e-3 > Geom::L2(dragger->point - begin)) { // drg is on the end side from dragger - double x = Geom::L2(drg->point - dragger->point)/Geom::L2(end - dragger->point); - this_move = (0.5 * cos (M_PI * (pow(x, alpha))) + 0.5) * this_move; + if (Geom::L2(drg->point - dragger->point) + Geom::L2(drg->point - begin) - 1e-3 > + Geom::L2(dragger->point - begin)) { // drg is on the end side from dragger + double x = Geom::L2(drg->point - dragger->point) / Geom::L2(end - dragger->point); + this_move = (0.5 * cos(M_PI * (pow(x, alpha))) + 0.5) * this_move; } else { // drg is on the begin side from dragger - double x = Geom::L2(drg->point - dragger->point)/Geom::L2(begin - dragger->point); - this_move = (0.5 * cos (M_PI * (pow(x, alpha))) + 0.5) * this_move; + double x = Geom::L2(drg->point - dragger->point) / Geom::L2(begin - dragger->point); + this_move = (0.5 * cos(M_PI * (pow(x, alpha))) + 0.5) * this_move; } } drg->point += this_move; drgknot->moveto(drg->point); - drg->fireDraggables (false); + drg->fireDraggables(false); drg->updateDependencies(false); } drag->keep_selection = dragger->isSelected(); } - - -static void gr_knot_mousedown_handler(SPKnot */*knot*/, unsigned int /*state*/, gpointer data) +static void gr_knot_mousedown_handler(SPKnot * /*knot*/, unsigned int /*state*/, gpointer data) { - GrDragger *dragger = (GrDragger *) data; + GrDragger *dragger = (GrDragger *)data; GrDrag *drag = dragger->parent; // Turn off all mesh handle highlighting - for(auto d : drag->draggers) { //for all selected draggers + for (auto d : drag->draggers) { // for all selected draggers d->highlightCorner(false); } @@ -1069,28 +1055,29 @@ static void gr_knot_mousedown_handler(SPKnot */*knot*/, unsigned int /*state*/, */ static void gr_knot_ungrabbed_handler(SPKnot *knot, unsigned int state, gpointer data) { - GrDragger *dragger = (GrDragger *) data; + GrDragger *dragger = (GrDragger *)data; dragger->parent->desktop->getCanvas()->forced_redraws_stop(); dragger->point_original = dragger->point = knot->pos; if ((state & GDK_CONTROL_MASK) && (state & GDK_SHIFT_MASK)) { - dragger->fireDraggables (true, true); + dragger->fireDraggables(true, true); } else { - dragger->fireDraggables (true); + dragger->fireDraggables(true); } - dragger->moveMeshHandles( dragger->point_original, MG_NODE_NO_SCALE ); - - for (std::set::const_iterator it = dragger->parent->selected.begin(); it != dragger->parent->selected.end() ; ++it ) { + dragger->moveMeshHandles(dragger->point_original, MG_NODE_NO_SCALE); + + for (std::set::const_iterator it = dragger->parent->selected.begin(); + it != dragger->parent->selected.end(); ++it) { if (*it == dragger) continue; - (*it)->fireDraggables (true); + (*it)->fireDraggables(true); } // make this dragger selected if (!dragger->parent->keep_selection) { - dragger->parent->setSelected (dragger); + dragger->parent->setSelected(dragger); } dragger->parent->keep_selection = false; @@ -1104,19 +1091,20 @@ static void gr_knot_ungrabbed_handler(SPKnot *knot, unsigned int state, gpointer * Called when a dragger knot is clicked; selects the dragger or deletes it depending on the * state of the keyboard keys. */ -static void gr_knot_clicked_handler(SPKnot */*knot*/, guint state, gpointer data) +static void gr_knot_clicked_handler(SPKnot * /*knot*/, guint state, gpointer data) { - GrDragger *dragger = (GrDragger *) data; + GrDragger *dragger = (GrDragger *)data; GrDraggable *draggable = dragger->draggables[0]; - if (!draggable) return; + if (!draggable) + return; - if ( (state & GDK_CONTROL_MASK) && (state & GDK_MOD1_MASK ) ) { - // delete this knot from vector + if ((state & GDK_CONTROL_MASK) && (state & GDK_MOD1_MASK)) { + // delete this knot from vector SPGradient *gradient = getGradient(draggable->item, draggable->fill_or_stroke); gradient = gradient->getVector(); if (gradient->vector.stops.size() > 2) { // 2 is the minimum SPStop *stop = nullptr; - switch (draggable->point_type) { // if we delete first or last stop, move the next/previous to the edge + switch (draggable->point_type) { // if we delete first or last stop, move the next/previous to the edge case POINT_LG_BEGIN: case POINT_RG_CENTER: @@ -1151,22 +1139,20 @@ static void gr_knot_clicked_handler(SPKnot */*knot*/, guint state, gpointer data default: return; - } gradient->getRepr()->removeChild(stop->getRepr()); - DocumentUndo::done(gradient->document, SP_VERB_CONTEXT_GRADIENT, - _("Delete gradient stop")); + DocumentUndo::done(gradient->document, SP_VERB_CONTEXT_GRADIENT, _("Delete gradient stop")); } } else { - // select the dragger + // select the dragger dragger->point_original = dragger->point; - if ( state & GDK_SHIFT_MASK ) { - dragger->parent->setSelected (dragger, true, false); + if (state & GDK_SHIFT_MASK) { + dragger->parent->setSelected(dragger, true, false); } else { - dragger->parent->setSelected (dragger); + dragger->parent->setSelected(dragger); } } } @@ -1174,9 +1160,9 @@ static void gr_knot_clicked_handler(SPKnot */*knot*/, guint state, gpointer data /** * Called when a dragger knot is doubleclicked; */ -static void gr_knot_doubleclicked_handler(SPKnot */*knot*/, guint /*state*/, gpointer data) +static void gr_knot_doubleclicked_handler(SPKnot * /*knot*/, guint /*state*/, gpointer data) { - GrDragger *dragger = (GrDragger *) data; + GrDragger *dragger = (GrDragger *)data; dragger->point_original = dragger->point; @@ -1196,24 +1182,25 @@ void GrDragger::fireDraggables(bool write_repr, bool scale_radial, bool merging_ // change gradient, optionally writing to repr; prevent focus from moving if it's snapped // to the center, unless it's the first update upon merge when we must snap it to the point if (merging_focus || - !(draggable->point_type == POINT_RG_FOCUS && this->isA(draggable->item, POINT_RG_CENTER, draggable->point_i, draggable->fill_or_stroke))) - { - sp_item_gradient_set_coords (draggable->item, draggable->point_type, draggable->point_i, this->point, draggable->fill_or_stroke, write_repr, scale_radial); + !(draggable->point_type == POINT_RG_FOCUS && + this->isA(draggable->item, POINT_RG_CENTER, draggable->point_i, draggable->fill_or_stroke))) { + sp_item_gradient_set_coords(draggable->item, draggable->point_type, draggable->point_i, this->point, + draggable->fill_or_stroke, write_repr, scale_radial); } } } -void GrDragger::updateControlSizesOverload(SPKnot * knot) +void GrDragger::updateControlSizesOverload(SPKnot *knot) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int sizes[] = {4, 6, 8, 10, 12, 14, 16}; std::vector sizeTable = std::vector(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); int size = prefs->getIntLimited("/options/grabsize/value", 3, 1, 7); int knot_size = sizeTable[size - 1]; - if(knot->shape == SP_KNOT_SHAPE_TRIANGLE){ + if (knot->shape == SP_KNOT_SHAPE_TRIANGLE) { knot_size *= 2.2; knot_size = floor(knot_size); - if ( knot_size % 2 == 0 ){ + if (knot_size % 2 == 0) { knot_size += 1; } } @@ -1246,7 +1233,8 @@ bool GrDragger::isA(GrPointType point_type) bool GrDragger::isA(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke) { for (auto draggable : this->draggables) { - if ( (draggable->point_type == point_type) && (draggable->point_i == point_i) && (draggable->item == item) && (draggable->fill_or_stroke == fill_or_stroke) ) { + if ((draggable->point_type == point_type) && (draggable->point_i == point_i) && (draggable->item == item) && + (draggable->fill_or_stroke == fill_or_stroke)) { return true; } } @@ -1259,7 +1247,8 @@ bool GrDragger::isA(SPItem *item, GrPointType point_type, gint point_i, Inkscape bool GrDragger::isA(SPItem *item, GrPointType point_type, Inkscape::PaintTarget fill_or_stroke) { for (auto draggable : this->draggables) { - if ( (draggable->point_type == point_type) && (draggable->item == item) && (draggable->fill_or_stroke == fill_or_stroke) ) { + if ((draggable->point_type == point_type) && (draggable->item == item) && + (draggable->fill_or_stroke == fill_or_stroke)) { return true; } } @@ -1277,9 +1266,9 @@ bool GrDraggable::mayMerge(GrDraggable *da2) } } // disable merging of midpoints. - if ( (this->point_type == POINT_LG_MID) || (da2->point_type == POINT_LG_MID) - || (this->point_type == POINT_RG_MID1) || (da2->point_type == POINT_RG_MID1) - || (this->point_type == POINT_RG_MID2) || (da2->point_type == POINT_RG_MID2) ) + if ((this->point_type == POINT_LG_MID) || (da2->point_type == POINT_LG_MID) || + (this->point_type == POINT_RG_MID1) || (da2->point_type == POINT_RG_MID1) || + (this->point_type == POINT_RG_MID2) || (da2->point_type == POINT_RG_MID2)) return false; return true; @@ -1319,8 +1308,7 @@ bool GrDragger::mayMerge(GrDraggable *da2) * * Ooops, needs to be reimplemented. */ -void -GrDragger::moveMeshHandles ( Geom::Point pc_old, MeshNodeOperation op ) +void GrDragger::moveMeshHandles(Geom::Point pc_old, MeshNodeOperation op) { // This routine might more properly be in mesh-context.cpp but moving knots is // handled here rather than there. @@ -1334,12 +1322,13 @@ GrDragger::moveMeshHandles ( Geom::Point pc_old, MeshNodeOperation op ) // sharing the same dragger (overkill, perhaps?). // If no corner point in GrDragger then do nothing. - if( !isA (POINT_MG_CORNER ) ) return; + if (!isA(POINT_MG_CORNER)) + return; GrDrag *drag = this->parent; // We need a list of selected corners per mesh if scaling. - std::map > selected_corners; + std::map> selected_corners; // scaling was disabled so #if 0'ing out for now. #if 0 const bool scale = false; @@ -1366,62 +1355,60 @@ GrDragger::moveMeshHandles ( Geom::Point pc_old, MeshNodeOperation op ) // Now we do the handle moves. // Loop over all draggables in moved corner - std::map > dragger_corners; + std::map> dragger_corners; for (auto draggable : draggables) { - SPItem *item = draggable->item; - gint point_type = draggable->point_type; - gint point_i = draggable->point_i; - Inkscape::PaintTarget - fill_or_stroke = draggable->fill_or_stroke; + SPItem *item = draggable->item; + gint point_type = draggable->point_type; + gint point_i = draggable->point_i; + Inkscape::PaintTarget fill_or_stroke = draggable->fill_or_stroke; // Check draggable is of type POINT_MG_CORNER (don't allow selection of POINT_MG_HANDLE) - if( point_type != POINT_MG_CORNER ) continue; + if (point_type != POINT_MG_CORNER) + continue; // Must be a mesh gradient SPGradient *gradient = getGradient(item, fill_or_stroke); - if ( !SP_IS_MESHGRADIENT( gradient ) ) continue; - SPMeshGradient *mg = SP_MESHGRADIENT( gradient ); + if (!SP_IS_MESHGRADIENT(gradient)) + continue; + SPMeshGradient *mg = SP_MESHGRADIENT(gradient); // pc_old is the old corner position in desktop coordinates, we need it in gradient coordinate. - gradient = sp_gradient_convert_to_userspace (gradient, item, (fill_or_stroke == Inkscape::FOR_FILL) ? "fill" : "stroke"); - Geom::Affine i2d ( item->i2dt_affine() ); + gradient = sp_gradient_convert_to_userspace(gradient, item, + (fill_or_stroke == Inkscape::FOR_FILL) ? "fill" : "stroke"); + Geom::Affine i2d(item->i2dt_affine()); Geom::Point pcg_old = pc_old * i2d.inverse(); pcg_old *= (gradient->gradientTransform).inverse(); - mg->array.update_handles( point_i, selected_corners[ gradient ], pcg_old, op ); - mg->array.write( mg ); + mg->array.update_handles(point_i, selected_corners[gradient], pcg_old, op); + mg->array.write(mg); // Move on-screen knots - for( guint i = 0; i < mg->array.handles.size(); ++i ) { - GrDragger *handle = drag->getDraggerFor( item, POINT_MG_HANDLE, i, fill_or_stroke ); + for (guint i = 0; i < mg->array.handles.size(); ++i) { + GrDragger *handle = drag->getDraggerFor(item, POINT_MG_HANDLE, i, fill_or_stroke); SPKnot *knot = handle->knot; - Geom::Point pk = getGradientCoords( item, POINT_MG_HANDLE, i, fill_or_stroke ); + Geom::Point pk = getGradientCoords(item, POINT_MG_HANDLE, i, fill_or_stroke); knot->moveto(pk); - } - for( guint i = 0; i < mg->array.tensors.size(); ++i ) { - - GrDragger *handle = drag->getDraggerFor( item, POINT_MG_TENSOR, i, fill_or_stroke ); + for (guint i = 0; i < mg->array.tensors.size(); ++i) { + GrDragger *handle = drag->getDraggerFor(item, POINT_MG_TENSOR, i, fill_or_stroke); SPKnot *knot = handle->knot; - Geom::Point pk = getGradientCoords( item, POINT_MG_TENSOR, i, fill_or_stroke ); + Geom::Point pk = getGradientCoords(item, POINT_MG_TENSOR, i, fill_or_stroke); knot->moveto(pk); - } } // Loop over draggables. } - /** * Updates the statusbar tip of the dragger knot, based on its draggables. */ void GrDragger::updateTip() { g_return_if_fail(this->knot != nullptr); - + if (this->knot && this->knot->tip) { - g_free (this->knot->tip); + g_free(this->knot->tip); this->knot->tip = nullptr; } @@ -1432,38 +1419,39 @@ void GrDragger::updateTip() case POINT_LG_MID: case POINT_RG_MID1: case POINT_RG_MID2: - this->knot->tip = g_strdup_printf (_("%s %d for: %s%s; drag with Ctrl to snap offset; click with Ctrl+Alt to delete stop"), - _(gr_knot_descr[draggable->point_type]), - draggable->point_i, - item_desc, - (draggable->fill_or_stroke == Inkscape::FOR_STROKE) ? _(" (stroke)") : ""); + this->knot->tip = + g_strdup_printf(_("%s %d for: %s%s; drag with Ctrl to snap offset; click with " + "Ctrl+Alt to delete stop"), + _(gr_knot_descr[draggable->point_type]), draggable->point_i, item_desc, + (draggable->fill_or_stroke == Inkscape::FOR_STROKE) ? _(" (stroke)") : ""); break; case POINT_MG_CORNER: case POINT_MG_HANDLE: case POINT_MG_TENSOR: - this->knot->tip = g_strdup_printf (_("%s for: %s%s"), - _(gr_knot_descr[draggable->point_type]), - item_desc, - (draggable->fill_or_stroke == Inkscape::FOR_STROKE) ? _(" (stroke)") : ""); + this->knot->tip = + g_strdup_printf(_("%s for: %s%s"), _(gr_knot_descr[draggable->point_type]), item_desc, + (draggable->fill_or_stroke == Inkscape::FOR_STROKE) ? _(" (stroke)") : ""); break; default: - this->knot->tip = g_strdup_printf (_("%s for: %s%s; drag with Ctrl to snap angle, with Ctrl+Alt to preserve angle, with Ctrl+Shift to scale around center"), - _(gr_knot_descr[draggable->point_type]), - item_desc, - (draggable->fill_or_stroke == Inkscape::FOR_STROKE) ? _(" (stroke)") : ""); + this->knot->tip = + g_strdup_printf(_("%s for: %s%s; drag with Ctrl to snap angle, with Ctrl+Alt to " + "preserve angle, with Ctrl+Shift to scale around center"), + _(gr_knot_descr[draggable->point_type]), item_desc, + (draggable->fill_or_stroke == Inkscape::FOR_STROKE) ? _(" (stroke)") : ""); break; } g_free(item_desc); - } else if (draggables.size() == 2 && isA (POINT_RG_CENTER) && isA (POINT_RG_FOCUS)) { - this->knot->tip = g_strdup_printf ("%s", _("Radial gradient center and focus; drag with Shift to separate focus")); + } else if (draggables.size() == 2 && isA(POINT_RG_CENTER) && isA(POINT_RG_FOCUS)) { + this->knot->tip = g_strdup_printf( + "%s", _("Radial gradient center and focus; drag with Shift to separate focus")); } else { int length = this->draggables.size(); - this->knot->tip = g_strdup_printf (ngettext("Gradient point shared by %d gradient; drag with Shift to separate", - "Gradient point shared by %d gradients; drag with Shift to separate", - length), - length); + this->knot->tip = g_strdup_printf( + ngettext("Gradient point shared by %d gradient; drag with Shift to separate", + "Gradient point shared by %d gradients; drag with Shift to separate", length), + length); } } @@ -1476,13 +1464,14 @@ void GrDragger::updateKnotShape() return; GrDraggable *last = draggables.back(); - g_object_set (G_OBJECT (this->knot->item), "shape", gr_knot_shapes[last->point_type], NULL); + g_object_set(G_OBJECT(this->knot->item), "shape", gr_knot_shapes[last->point_type], NULL); // For highlighting mesh handles corresponding to selected corner if (this->knot->shape == SP_KNOT_SHAPE_TRIANGLE) { - this->knot->setFill(GR_KNOT_COLOR_HIGHLIGHT, GR_KNOT_COLOR_MOUSEOVER, GR_KNOT_COLOR_MOUSEOVER, GR_KNOT_COLOR_MOUSEOVER); + this->knot->setFill(GR_KNOT_COLOR_HIGHLIGHT, GR_KNOT_COLOR_MOUSEOVER, GR_KNOT_COLOR_MOUSEOVER, + GR_KNOT_COLOR_MOUSEOVER); if (gr_knot_shapes[last->point_type] == SP_KNOT_SHAPE_CIRCLE) { - g_object_set (G_OBJECT (this->knot->item), "shape", SP_KNOT_SHAPE_TRIANGLE, NULL); + g_object_set(G_OBJECT(this->knot->item), "shape", SP_KNOT_SHAPE_TRIANGLE, NULL); } } } @@ -1497,11 +1486,11 @@ void GrDragger::addDraggable(GrDraggable *draggable) this->updateTip(); } - /** * Moves this dragger to the point of the given draggable, acting upon all other draggables. */ -void GrDragger::moveThisToDraggable(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke, bool write_repr) +void GrDragger::moveThisToDraggable(SPItem *item, GrPointType point_type, gint point_i, + Inkscape::PaintTarget fill_or_stroke, bool write_repr) { if (draggables.empty()) return; @@ -1514,19 +1503,18 @@ void GrDragger::moveThisToDraggable(SPItem *item, GrPointType point_type, gint p this->knot->moveto(this->point); for (auto da : draggables) { - if ( (da->item == item) && - (da->point_type == point_type) && - (point_i == -1 || da->point_i == point_i) && - (da->fill_or_stroke == fill_or_stroke) ) { + if ((da->item == item) && (da->point_type == point_type) && (point_i == -1 || da->point_i == point_i) && + (da->fill_or_stroke == fill_or_stroke)) { // Don't move initial draggable continue; } - sp_item_gradient_set_coords(da->item, da->point_type, da->point_i, this->point, da->fill_or_stroke, write_repr, false); + sp_item_gradient_set_coords(da->item, da->point_type, da->point_i, this->point, da->fill_or_stroke, write_repr, + false); } - // FIXME: here we should also call this->updateDependencies(write_repr); to propagate updating, but how to prevent loops? + // FIXME: here we should also call this->updateDependencies(write_repr); to propagate updating, but how to prevent + // loops? } - /** * Moves all midstop draggables that depend on this one. */ @@ -1536,21 +1524,21 @@ void GrDragger::updateMidstopDependencies(GrDraggable *draggable, bool write_rep if (!server) return; guint num = SP_GRADIENT(server)->vector.stops.size(); - if (num <= 2) return; + if (num <= 2) + return; - if ( SP_IS_LINEARGRADIENT(server) ) { - for ( guint i = 1; i < num - 1; i++ ) { - this->moveOtherToDraggable (draggable->item, POINT_LG_MID, i, draggable->fill_or_stroke, write_repr); + if (SP_IS_LINEARGRADIENT(server)) { + for (guint i = 1; i < num - 1; i++) { + this->moveOtherToDraggable(draggable->item, POINT_LG_MID, i, draggable->fill_or_stroke, write_repr); } - } else if ( SP_IS_RADIALGRADIENT(server) ) { - for ( guint i = 1; i < num - 1; i++ ) { - this->moveOtherToDraggable (draggable->item, POINT_RG_MID1, i, draggable->fill_or_stroke, write_repr); - this->moveOtherToDraggable (draggable->item, POINT_RG_MID2, i, draggable->fill_or_stroke, write_repr); + } else if (SP_IS_RADIALGRADIENT(server)) { + for (guint i = 1; i < num - 1; i++) { + this->moveOtherToDraggable(draggable->item, POINT_RG_MID1, i, draggable->fill_or_stroke, write_repr); + this->moveOtherToDraggable(draggable->item, POINT_RG_MID2, i, draggable->fill_or_stroke, write_repr); } } } - /** * Moves all draggables that depend on this one. */ @@ -1558,49 +1546,47 @@ void GrDragger::updateDependencies(bool write_repr) { for (auto draggable : draggables) { switch (draggable->point_type) { - case POINT_LG_BEGIN: - { - // the end point is dependent only when dragging with ctrl+shift - this->moveOtherToDraggable (draggable->item, POINT_LG_END, -1, draggable->fill_or_stroke, write_repr); - - this->updateMidstopDependencies (draggable, write_repr); - } - break; - case POINT_LG_END: - { - // the begin point is dependent only when dragging with ctrl+shift - this->moveOtherToDraggable (draggable->item, POINT_LG_BEGIN, 0, draggable->fill_or_stroke, write_repr); - - this->updateMidstopDependencies (draggable, write_repr); - } - break; + case POINT_LG_BEGIN: { + // the end point is dependent only when dragging with ctrl+shift + this->moveOtherToDraggable(draggable->item, POINT_LG_END, -1, draggable->fill_or_stroke, write_repr); + + this->updateMidstopDependencies(draggable, write_repr); + } break; + case POINT_LG_END: { + // the begin point is dependent only when dragging with ctrl+shift + this->moveOtherToDraggable(draggable->item, POINT_LG_BEGIN, 0, draggable->fill_or_stroke, write_repr); + + this->updateMidstopDependencies(draggable, write_repr); + } break; case POINT_LG_MID: // no other nodes depend on mid points. break; case POINT_RG_R2: - this->moveOtherToDraggable (draggable->item, POINT_RG_R1, -1, draggable->fill_or_stroke, write_repr); - this->moveOtherToDraggable (draggable->item, POINT_RG_FOCUS, -1, draggable->fill_or_stroke, write_repr); - this->updateMidstopDependencies (draggable, write_repr); + this->moveOtherToDraggable(draggable->item, POINT_RG_R1, -1, draggable->fill_or_stroke, write_repr); + this->moveOtherToDraggable(draggable->item, POINT_RG_FOCUS, -1, draggable->fill_or_stroke, write_repr); + this->updateMidstopDependencies(draggable, write_repr); break; case POINT_RG_R1: - this->moveOtherToDraggable (draggable->item, POINT_RG_R2, -1, draggable->fill_or_stroke, write_repr); - this->moveOtherToDraggable (draggable->item, POINT_RG_FOCUS, -1, draggable->fill_or_stroke, write_repr); - this->updateMidstopDependencies (draggable, write_repr); + this->moveOtherToDraggable(draggable->item, POINT_RG_R2, -1, draggable->fill_or_stroke, write_repr); + this->moveOtherToDraggable(draggable->item, POINT_RG_FOCUS, -1, draggable->fill_or_stroke, write_repr); + this->updateMidstopDependencies(draggable, write_repr); break; case POINT_RG_CENTER: - this->moveOtherToDraggable (draggable->item, POINT_RG_R1, -1, draggable->fill_or_stroke, write_repr); - this->moveOtherToDraggable (draggable->item, POINT_RG_R2, -1, draggable->fill_or_stroke, write_repr); - this->moveOtherToDraggable (draggable->item, POINT_RG_FOCUS, -1, draggable->fill_or_stroke, write_repr); - this->updateMidstopDependencies (draggable, write_repr); + this->moveOtherToDraggable(draggable->item, POINT_RG_R1, -1, draggable->fill_or_stroke, write_repr); + this->moveOtherToDraggable(draggable->item, POINT_RG_R2, -1, draggable->fill_or_stroke, write_repr); + this->moveOtherToDraggable(draggable->item, POINT_RG_FOCUS, -1, draggable->fill_or_stroke, write_repr); + this->updateMidstopDependencies(draggable, write_repr); break; case POINT_RG_FOCUS: // nothing can depend on that break; case POINT_RG_MID1: - this->moveOtherToDraggable (draggable->item, POINT_RG_MID2, draggable->point_i, draggable->fill_or_stroke, write_repr); + this->moveOtherToDraggable(draggable->item, POINT_RG_MID2, draggable->point_i, + draggable->fill_or_stroke, write_repr); break; case POINT_RG_MID2: - this->moveOtherToDraggable (draggable->item, POINT_RG_MID1, draggable->point_i, draggable->fill_or_stroke, write_repr); + this->moveOtherToDraggable(draggable->item, POINT_RG_MID1, draggable->point_i, + draggable->fill_or_stroke, write_repr); break; default: break; @@ -1608,11 +1594,9 @@ void GrDragger::updateDependencies(bool write_repr) } } - - GrDragger::GrDragger(GrDrag *parent, Geom::Point p, GrDraggable *draggable) - : point(p), - point_original(p) + : point(p) + , point_original(p) { this->draggables.clear(); @@ -1635,26 +1619,31 @@ GrDragger::GrDragger(GrDrag *parent, Geom::Point p, GrDraggable *draggable) this->knot->show(); // connect knot's signals - if ( (draggable) // it can be NULL if a node in unsnapped (eg. focus point unsnapped from center) - // luckily, midstops never snap to other nodes so are never unsnapped... - && ( (draggable->point_type == POINT_LG_MID) - || (draggable->point_type == POINT_RG_MID1) - || (draggable->point_type == POINT_RG_MID2) ) ) - { - this->_moved_connection = this->knot->moved_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_moved_midpoint_handler), this)); + if ((draggable) // it can be NULL if a node in unsnapped (eg. focus point unsnapped from center) + // luckily, midstops never snap to other nodes so are never unsnapped... + && ((draggable->point_type == POINT_LG_MID) || (draggable->point_type == POINT_RG_MID1) || + (draggable->point_type == POINT_RG_MID2))) { + this->_moved_connection = + this->knot->moved_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_moved_midpoint_handler), this)); } else { - this->_moved_connection = this->knot->moved_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_moved_handler), this)); + this->_moved_connection = + this->knot->moved_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_moved_handler), this)); } - this->sizeUpdatedConn = ControlManager::getManager().connectCtrlSizeChanged(sigc::mem_fun(*this, &GrDragger::updateControlSizes)); - this->_clicked_connection = this->knot->click_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_clicked_handler), this)); - this->_doubleclicked_connection = this->knot->doubleclicked_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_doubleclicked_handler), this)); - this->_mousedown_connection = this->knot->mousedown_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_mousedown_handler), this)); - this->_ungrabbed_connection = this->knot->ungrabbed_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_ungrabbed_handler), this)); + this->sizeUpdatedConn = + ControlManager::getManager().connectCtrlSizeChanged(sigc::mem_fun(*this, &GrDragger::updateControlSizes)); + this->_clicked_connection = + this->knot->click_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_clicked_handler), this)); + this->_doubleclicked_connection = + this->knot->doubleclicked_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_doubleclicked_handler), this)); + this->_mousedown_connection = + this->knot->mousedown_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_mousedown_handler), this)); + this->_ungrabbed_connection = + this->knot->ungrabbed_signal.connect(sigc::bind(sigc::ptr_fun(gr_knot_ungrabbed_handler), this)); // add the initial draggable if (draggable) { - this->addDraggable (draggable); + this->addDraggable(draggable); } updateKnotShape(); @@ -1666,7 +1655,7 @@ GrDragger::~GrDragger() // Hmm, this causes a race condition as it triggers a call to gradient_selection_changed which // can be executed while a list of draggers is being deleted. It doesn't actually seem to be // necessary. - //this->parent->setDeselected(this); + // this->parent->setDeselected(this); // disconnect signals this->sizeUpdatedConn.disconnect(); @@ -1689,9 +1678,11 @@ GrDragger::~GrDragger() /** * Select the dragger which has the given draggable. */ -GrDragger *GrDrag::getDraggerFor(GrDraggable *d) { +GrDragger *GrDrag::getDraggerFor(GrDraggable *d) +{ for (auto dragger : this->draggers) { - for (std::vector::const_iterator j = dragger->draggables.begin(); j != dragger->draggables.end(); ++j ) { + for (std::vector::const_iterator j = dragger->draggables.begin(); j != dragger->draggables.end(); + ++j) { if (d == *j) { return dragger; } @@ -1703,15 +1694,16 @@ GrDragger *GrDrag::getDraggerFor(GrDraggable *d) { /** * Select the dragger which has the given draggable. */ -GrDragger *GrDrag::getDraggerFor(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke) +GrDragger *GrDrag::getDraggerFor(SPItem *item, GrPointType point_type, gint point_i, + Inkscape::PaintTarget fill_or_stroke) { for (auto dragger : this->draggers) { - for (std::vector::const_iterator j = dragger->draggables.begin(); j != dragger->draggables.end(); ++j ) { - GrDraggable *da2 = *j; - if ( (da2->item == item) && - (da2->point_type == point_type) && - (point_i == -1 || da2->point_i == point_i) && // -1 means this does not matter - (da2->fill_or_stroke == fill_or_stroke)) { + for (std::vector::const_iterator j = dragger->draggables.begin(); j != dragger->draggables.end(); + ++j) { + GrDraggable *da2 = *j; + if ((da2->item == item) && (da2->point_type == point_type) && + (point_i == -1 || da2->point_i == point_i) && // -1 means this does not matter + (da2->fill_or_stroke == fill_or_stroke)) { return (dragger); } } @@ -1719,11 +1711,11 @@ GrDragger *GrDrag::getDraggerFor(SPItem *item, GrPointType point_type, gint poin return nullptr; } - -void GrDragger::moveOtherToDraggable(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke, bool write_repr) +void GrDragger::moveOtherToDraggable(SPItem *item, GrPointType point_type, gint point_i, + Inkscape::PaintTarget fill_or_stroke, bool write_repr) { GrDragger *d = this->parent->getDraggerFor(item, point_type, point_i, fill_or_stroke); - if (d && d != this) { + if (d && d != this) { d->moveThisToDraggable(item, point_type, point_i, fill_or_stroke, write_repr); } } @@ -1731,10 +1723,10 @@ void GrDragger::moveOtherToDraggable(SPItem *item, GrPointType point_type, gint /** * Find mesh corner corresponding to given dragger. */ -GrDragger* GrDragger::getMgCorner(){ - GrDraggable *draggable = (GrDraggable *) this->draggables[0]; +GrDragger *GrDragger::getMgCorner() +{ + GrDraggable *draggable = (GrDraggable *)this->draggables[0]; if (draggable) { - // If corner, we already found it! if (draggable->point_type == POINT_MG_CORNER) { return this; @@ -1744,26 +1736,37 @@ GrDragger* GrDragger::getMgCorner(){ SPGradient *gradient = getGradient(draggable->item, draggable->fill_or_stroke); SPMeshGradient *mg = dynamic_cast(gradient); if (mg) { - std::vector< std::vector< SPMeshNode* > > nodes = mg->array.nodes; + std::vector> nodes = mg->array.nodes; for (guint i = 0; i < nodes.size(); ++i) { for (guint j = 0; j < nodes[i].size(); ++j) { if (nodes[i][j]->set && nodes[i][j]->node_type == MG_NODE_TYPE_HANDLE) { if (draggable->point_i == (gint)nodes[i][j]->draggable) { - - if (nodes.size() > i+1 && nodes[i+1].size() > j && nodes[i+1][j]->node_type == MG_NODE_TYPE_CORNER) { - return this->parent->getDraggerFor(draggable->item, POINT_MG_CORNER, nodes[i+1][j]->draggable, draggable->fill_or_stroke); + if (nodes.size() > i + 1 && nodes[i + 1].size() > j && + nodes[i + 1][j]->node_type == MG_NODE_TYPE_CORNER) { + return this->parent->getDraggerFor(draggable->item, POINT_MG_CORNER, + nodes[i + 1][j]->draggable, + draggable->fill_or_stroke); } - if (j != 0 && nodes.size() > i && nodes[i].size() > j-1 && nodes[i][j-1]->node_type == MG_NODE_TYPE_CORNER) { - return this->parent->getDraggerFor(draggable->item, POINT_MG_CORNER, nodes[i][j-1]->draggable, draggable->fill_or_stroke); + if (j != 0 && nodes.size() > i && nodes[i].size() > j - 1 && + nodes[i][j - 1]->node_type == MG_NODE_TYPE_CORNER) { + return this->parent->getDraggerFor(draggable->item, POINT_MG_CORNER, + nodes[i][j - 1]->draggable, + draggable->fill_or_stroke); } - if (i != 0 && nodes.size() > i-1 && nodes[i-1].size() > j && nodes[i-1][j]->node_type == MG_NODE_TYPE_CORNER) { - return this->parent->getDraggerFor(draggable->item, POINT_MG_CORNER, nodes[i-1][j]->draggable, draggable->fill_or_stroke); + if (i != 0 && nodes.size() > i - 1 && nodes[i - 1].size() > j && + nodes[i - 1][j]->node_type == MG_NODE_TYPE_CORNER) { + return this->parent->getDraggerFor(draggable->item, POINT_MG_CORNER, + nodes[i - 1][j]->draggable, + draggable->fill_or_stroke); } - if (nodes.size() > i && nodes[i].size() > j+1 && nodes[i][j+1]->node_type == MG_NODE_TYPE_CORNER) { - return this->parent->getDraggerFor(draggable->item, POINT_MG_CORNER, nodes[i][j+1]->draggable, draggable->fill_or_stroke); + if (nodes.size() > i && nodes[i].size() > j + 1 && + nodes[i][j + 1]->node_type == MG_NODE_TYPE_CORNER) { + return this->parent->getDraggerFor(draggable->item, POINT_MG_CORNER, + nodes[i][j + 1]->draggable, + draggable->fill_or_stroke); } } } @@ -1784,7 +1787,7 @@ void GrDragger::highlightNode(SPMeshNode *node, bool highlight, Geom::Point corn type = POINT_MG_HANDLE; } - GrDraggable *draggable = (GrDraggable *) this->draggables[0]; + GrDraggable *draggable = (GrDraggable *)this->draggables[0]; GrDragger *d = this->parent->getDraggerFor(draggable->item, type, node->draggable, draggable->fill_or_stroke); if (d && node->draggable < G_MAXUINT) { Geom::Point end = d->knot->pos; @@ -1796,15 +1799,18 @@ void GrDragger::highlightNode(SPMeshNode *node, bool highlight, Geom::Point corn } double angl = ray.angle(); - if (highlight && knot->fill[SP_KNOT_VISIBLE] == GR_KNOT_COLOR_HIGHLIGHT && abs(angl - knot->angle) > Geom::rad_from_deg(10.0)){ + if (highlight && knot->fill[SP_KNOT_VISIBLE] == GR_KNOT_COLOR_HIGHLIGHT && + abs(angl - knot->angle) > Geom::rad_from_deg(10.0)) { return; } SPKnot *knot = d->knot; if (highlight) { - knot->setFill(GR_KNOT_COLOR_HIGHLIGHT, GR_KNOT_COLOR_MOUSEOVER, GR_KNOT_COLOR_MOUSEOVER, GR_KNOT_COLOR_MOUSEOVER); + knot->setFill(GR_KNOT_COLOR_HIGHLIGHT, GR_KNOT_COLOR_MOUSEOVER, GR_KNOT_COLOR_MOUSEOVER, + GR_KNOT_COLOR_MOUSEOVER); } else { - knot->setFill(GR_KNOT_COLOR_NORMAL, GR_KNOT_COLOR_MOUSEOVER, GR_KNOT_COLOR_MOUSEOVER, GR_KNOT_COLOR_MOUSEOVER); + knot->setFill(GR_KNOT_COLOR_NORMAL, GR_KNOT_COLOR_MOUSEOVER, GR_KNOT_COLOR_MOUSEOVER, + GR_KNOT_COLOR_MOUSEOVER); } if (type == POINT_MG_HANDLE) { @@ -1814,7 +1820,7 @@ void GrDragger::highlightNode(SPMeshNode *node, bool highlight, Geom::Point corn knot->setShape(SP_KNOT_SHAPE_CIRCLE); } } else { - //Code for tensors + // Code for tensors return; } @@ -1828,18 +1834,18 @@ void GrDragger::highlightNode(SPMeshNode *node, bool highlight, Geom::Point corn /** * Highlight handles for mesh corner corresponding to this dragger. */ -void GrDragger::highlightCorner(bool highlight) +void GrDragger::highlightCorner(bool highlight) { // Must be a mesh gradient - GrDraggable *draggable = (GrDraggable *) this->draggables[0]; - if (draggable && draggable->point_type == POINT_MG_CORNER) { + GrDraggable *draggable = (GrDraggable *)this->draggables[0]; + if (draggable && draggable->point_type == POINT_MG_CORNER) { SPGradient *gradient = getGradient(draggable->item, draggable->fill_or_stroke); - if (SP_IS_MESHGRADIENT( gradient )) { + if (SP_IS_MESHGRADIENT(gradient)) { Geom::Point corner_point = this->point; gint corner = draggable->point_i; - SPMeshGradient *mg = SP_MESHGRADIENT( gradient ); + SPMeshGradient *mg = SP_MESHGRADIENT(gradient); SPMeshNodeArray mg_arr = mg->array; - std::vector< std::vector< SPMeshNode* > > nodes = mg_arr.nodes; + std::vector> nodes = mg_arr.nodes; // Find number of patch rows and columns guint mrow = mg_arr.patch_rows(); guint mcol = mg_arr.patch_columns(); @@ -1849,19 +1855,23 @@ void GrDragger::highlightCorner(bool highlight) guint crow = corner / ncorners; guint ccol = corner % ncorners; // Find node row/column - guint nrow = crow * 3; - guint ncol = ccol * 3; + guint nrow = crow * 3; + guint ncol = ccol * 3; bool patch[4]; patch[0] = patch[1] = patch[2] = patch[3] = false; - if (ccol > 0 && crow > 0 ) patch[0] = true; - if (ccol < mcol && crow > 0 ) patch[1] = true; - if (ccol < mcol && crow < mrow ) patch[2] = true; - if (ccol > 0 && crow < mrow ) patch[3] = true; + if (ccol > 0 && crow > 0) + patch[0] = true; + if (ccol < mcol && crow > 0) + patch[1] = true; + if (ccol < mcol && crow < mrow) + patch[2] = true; + if (ccol > 0 && crow < mrow) + patch[3] = true; if (patch[0] || patch[1]) { highlightNode(nodes[nrow - 1][ncol], highlight, corner_point, 0); } - if (patch[1] || patch[2]) { + if (patch[1] || patch[2]) { highlightNode(nodes[nrow][ncol + 1], highlight, corner_point, 1); } if (patch[2] || patch[3]) { @@ -1886,8 +1896,8 @@ void GrDragger::highlightCorner(bool highlight) */ void GrDragger::select() { - this->knot->fill [SP_KNOT_STATE_NORMAL] = GR_KNOT_COLOR_SELECTED; - g_object_set (G_OBJECT (this->knot->item), "fill_color", GR_KNOT_COLOR_SELECTED, NULL); + this->knot->fill[SP_KNOT_STATE_NORMAL] = GR_KNOT_COLOR_SELECTED; + g_object_set(G_OBJECT(this->knot->item), "fill_color", GR_KNOT_COLOR_SELECTED, NULL); highlightCorner(true); } @@ -1897,13 +1907,12 @@ void GrDragger::select() void GrDragger::deselect() { guint32 fill_color = isA(POINT_MG_CORNER) ? GR_KNOT_COLOR_MESHCORNER : GR_KNOT_COLOR_NORMAL; - this->knot->fill [SP_KNOT_STATE_NORMAL] = fill_color; - g_object_set (G_OBJECT (this->knot->item), "fill_color", fill_color, NULL); + this->knot->fill[SP_KNOT_STATE_NORMAL] = fill_color; + g_object_set(G_OBJECT(this->knot->item), "fill_color", fill_color, NULL); highlightCorner(false); } -bool -GrDragger::isSelected() +bool GrDragger::isSelected() { return parent->selected.find(this) != parent->selected.end(); } @@ -1933,7 +1942,7 @@ void GrDrag::deselectAll() void GrDrag::selectAll() { for (auto d : this->draggers) { - setSelected (d, true, true); + setSelected(d, true, true); } } @@ -1944,8 +1953,8 @@ void GrDrag::selectByCoords(std::vector coords) { for (auto d : this->draggers) { for (auto coord : coords) { - if (Geom::L2 (d->point - coord) < 1e-4) { - setSelected (d, true, true); + if (Geom::L2(d->point - coord) < 1e-4) { + setSelected(d, true, true); } } } @@ -1954,12 +1963,11 @@ void GrDrag::selectByCoords(std::vector coords) /** * Select draggers by stop */ -void GrDrag::selectByStop(SPStop *stop, bool add_to_selection, bool override ) +void GrDrag::selectByStop(SPStop *stop, bool add_to_selection, bool override) { for (auto dragger : this->draggers) { - - for (std::vector::const_iterator j = dragger->draggables.begin(); j != dragger->draggables.end(); ++j) { - + for (std::vector::const_iterator j = dragger->draggables.begin(); j != dragger->draggables.end(); + ++j) { GrDraggable *d = *j; SPGradient *gradient = getGradient(d->item, d->fill_or_stroke); SPGradient *vector = gradient->getVector(false); @@ -1978,7 +1986,7 @@ void GrDrag::selectRect(Geom::Rect const &r) { for (auto d : this->draggers) { if (r.contains(d->point)) { - setSelected (d, true, true); + setSelected(d, true, true); } } } @@ -1988,23 +1996,25 @@ void GrDrag::selectRect(Geom::Rect const &r) * @param dragger The dragger to select. * @param add_to_selection If true, add to selection, otherwise deselect others. * @param override If true, always select this node, otherwise toggle selected status. -*/ + */ void GrDrag::setSelected(GrDragger *dragger, bool add_to_selection, bool override) { GrDragger *seldragger = nullptr; // Don't allow selecting a mesh handle or mesh tensor. // We might want to rethink since a dragger can have draggables of different types. - if ( dragger->isA( POINT_MG_HANDLE ) || dragger->isA( POINT_MG_TENSOR ) ) return; + if (dragger->isA(POINT_MG_HANDLE) || dragger->isA(POINT_MG_TENSOR)) + return; if (add_to_selection) { - if (!dragger) return; + if (!dragger) + return; if (override) { - selected.insert(dragger); + selected.insert(dragger); dragger->select(); seldragger = dragger; } else { // toggle - if(selected.find(dragger)!=selected.end()) { + if (selected.find(dragger) != selected.end()) { selected.erase(dragger); dragger->deselect(); if (!selected.empty()) { @@ -2025,7 +2035,7 @@ void GrDrag::setSelected(GrDragger *dragger, bool add_to_selection, bool overrid } } if (seldragger) { - this->desktop->emitToolSubselectionChanged((gpointer) seldragger); + this->desktop->emitToolSubselectionChanged((gpointer)seldragger); } } @@ -2039,11 +2049,9 @@ void GrDrag::setDeselected(GrDragger *dragger) selected.erase(dragger); dragger->deselect(); } - this->desktop->emitToolSubselectionChanged((gpointer) (selected.empty() ? NULL :*(selected.begin()))); + this->desktop->emitToolSubselectionChanged((gpointer)(selected.empty() ? NULL : *(selected.begin()))); } - - /** * Create a line from p1 to p2 and add it to the lines list. */ @@ -2059,57 +2067,56 @@ void GrDrag::addLine(SPItem *item, Geom::Point p1, Geom::Point p2, Inkscape::Pai this->lines.push_back(line); } - - /** * Create a curve from p0 to p3 and add it to the lines list. Used for mesh sides. */ -void GrDrag::addCurve(SPItem *item, Geom::Point p0, Geom::Point p1, Geom::Point p2, Geom::Point p3, - int corner0, int corner1, int handle0, int handle1, Inkscape::PaintTarget fill_or_stroke) +void GrDrag::addCurve(SPItem *item, Geom::Point p0, Geom::Point p1, Geom::Point p2, Geom::Point p3, int corner0, + int corner1, int handle0, int handle1, Inkscape::PaintTarget fill_or_stroke) { // Highlight curve if one of its draggers has a mouse over it. bool highlight = false; - GrDragger* dragger0 = getDraggerFor(item, POINT_MG_CORNER, corner0, fill_or_stroke); - GrDragger* dragger1 = getDraggerFor(item, POINT_MG_CORNER, corner1, fill_or_stroke); - GrDragger* dragger2 = getDraggerFor(item, POINT_MG_HANDLE, handle0, fill_or_stroke); - GrDragger* dragger3 = getDraggerFor(item, POINT_MG_HANDLE, handle1, fill_or_stroke); + GrDragger *dragger0 = getDraggerFor(item, POINT_MG_CORNER, corner0, fill_or_stroke); + GrDragger *dragger1 = getDraggerFor(item, POINT_MG_CORNER, corner1, fill_or_stroke); + GrDragger *dragger2 = getDraggerFor(item, POINT_MG_HANDLE, handle0, fill_or_stroke); + GrDragger *dragger3 = getDraggerFor(item, POINT_MG_HANDLE, handle1, fill_or_stroke); if ((dragger0->knot && (dragger0->knot->flags & SP_KNOT_MOUSEOVER)) || (dragger1->knot && (dragger1->knot->flags & SP_KNOT_MOUSEOVER)) || (dragger2->knot && (dragger2->knot->flags & SP_KNOT_MOUSEOVER)) || - (dragger3->knot && (dragger3->knot->flags & SP_KNOT_MOUSEOVER)) ) { + (dragger3->knot && (dragger3->knot->flags & SP_KNOT_MOUSEOVER))) { highlight = true; } // CtrlLineType only sets color CtrlLineType type = (fill_or_stroke == Inkscape::FOR_FILL) ? CTLINE_PRIMARY : CTLINE_SECONDARY; if (highlight) { - type = (fill_or_stroke == Inkscape::FOR_FILL) ? CTLINE_SECONDARY : CTLINE_PRIMARY; + type = (fill_or_stroke == Inkscape::FOR_FILL) ? CTLINE_SECONDARY : CTLINE_PRIMARY; } - SPCtrlCurve *line = ControlManager::getManager().createControlCurve(this->desktop->getControls(), p0, p1, p2, p3, type); + SPCtrlCurve *line = + ControlManager::getManager().createControlCurve(this->desktop->getControls(), p0, p1, p2, p3, type); line->corner0 = corner0; line->corner1 = corner1; sp_canvas_item_move_to_z(line, 0); line->item = item; line->is_fill = (fill_or_stroke == Inkscape::FOR_FILL); - sp_canvas_item_show (line); + sp_canvas_item_show(line); this->lines.push_back(line); } - /** * If there already exists a dragger within MERGE_DIST of p, add the draggable to it; otherwise create * new dragger and add it to draggers list. */ -GrDragger* GrDrag::addDragger(GrDraggable *draggable) +GrDragger *GrDrag::addDragger(GrDraggable *draggable) { - Geom::Point p = getGradientCoords(draggable->item, draggable->point_type, draggable->point_i, draggable->fill_or_stroke); + Geom::Point p = + getGradientCoords(draggable->item, draggable->point_type, draggable->point_i, draggable->fill_or_stroke); for (auto dragger : this->draggers) { - if (dragger->mayMerge (draggable) && Geom::L2 (dragger->point - p) < MERGE_DIST) { + if (dragger->mayMerge(draggable) && Geom::L2(dragger->point - p) < MERGE_DIST) { // distance is small, merge this draggable into dragger, no need to create new dragger - dragger->addDraggable (draggable); + dragger->addDraggable(draggable); dragger->updateKnotShape(); return dragger; } @@ -2127,21 +2134,21 @@ GrDragger* GrDrag::addDragger(GrDraggable *draggable) void GrDrag::addDraggersRadial(SPRadialGradient *rg, SPItem *item, Inkscape::PaintTarget fill_or_stroke) { rg->ensureVector(); - addDragger (new GrDraggable (item, POINT_RG_CENTER, 0, fill_or_stroke)); + addDragger(new GrDraggable(item, POINT_RG_CENTER, 0, fill_or_stroke)); guint num = rg->vector.stops.size(); if (num > 2) { - for ( guint i = 1; i < num - 1; i++ ) { - addDragger (new GrDraggable (item, POINT_RG_MID1, i, fill_or_stroke)); + for (guint i = 1; i < num - 1; i++) { + addDragger(new GrDraggable(item, POINT_RG_MID1, i, fill_or_stroke)); } } - addDragger (new GrDraggable (item, POINT_RG_R1, num-1, fill_or_stroke)); + addDragger(new GrDraggable(item, POINT_RG_R1, num - 1, fill_or_stroke)); if (num > 2) { - for ( guint i = 1; i < num - 1; i++ ) { - addDragger (new GrDraggable (item, POINT_RG_MID2, i, fill_or_stroke)); + for (guint i = 1; i < num - 1; i++) { + addDragger(new GrDraggable(item, POINT_RG_MID2, i, fill_or_stroke)); } } - addDragger (new GrDraggable (item, POINT_RG_R2, num - 1, fill_or_stroke)); - addDragger (new GrDraggable (item, POINT_RG_FOCUS, 0, fill_or_stroke)); + addDragger(new GrDraggable(item, POINT_RG_R2, num - 1, fill_or_stroke)); + addDragger(new GrDraggable(item, POINT_RG_FOCUS, 0, fill_or_stroke)); } /** @@ -2150,14 +2157,14 @@ void GrDrag::addDraggersRadial(SPRadialGradient *rg, SPItem *item, Inkscape::Pai void GrDrag::addDraggersLinear(SPLinearGradient *lg, SPItem *item, Inkscape::PaintTarget fill_or_stroke) { lg->ensureVector(); - addDragger(new GrDraggable (item, POINT_LG_BEGIN, 0, fill_or_stroke)); + addDragger(new GrDraggable(item, POINT_LG_BEGIN, 0, fill_or_stroke)); guint num = lg->vector.stops.size(); if (num > 2) { - for ( guint i = 1; i < num - 1; i++ ) { - addDragger(new GrDraggable (item, POINT_LG_MID, i, fill_or_stroke)); + for (guint i = 1; i < num - 1; i++) { + addDragger(new GrDraggable(item, POINT_LG_MID, i, fill_or_stroke)); } } - addDragger(new GrDraggable (item, POINT_LG_END, num - 1, fill_or_stroke)); + addDragger(new GrDraggable(item, POINT_LG_END, num - 1, fill_or_stroke)); } /** @@ -2166,18 +2173,17 @@ void GrDrag::addDraggersLinear(SPLinearGradient *lg, SPItem *item, Inkscape::Pai void GrDrag::addDraggersMesh(SPMeshGradient *mg, SPItem *item, Inkscape::PaintTarget fill_or_stroke) { mg->ensureArray(); - std::vector< std::vector< SPMeshNode* > > nodes = mg->array.nodes; + std::vector> nodes = mg->array.nodes; // Show/hide mesh on fill/stroke. This doesn't work at the moment... and prevents node color updating. - + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool show_handles = (prefs->getBool("/tools/mesh/show_handles", true)); - bool edit_fill = (prefs->getBool("/tools/mesh/edit_fill", true)); - bool edit_stroke = (prefs->getBool("/tools/mesh/edit_stroke", true)); + bool edit_fill = (prefs->getBool("/tools/mesh/edit_fill", true)); + bool edit_stroke = (prefs->getBool("/tools/mesh/edit_stroke", true)); // Make sure we have at least one patch defined. - if( mg->array.patch_rows() == 0 || mg->array.patch_columns() == 0 ) { - + if (mg->array.patch_rows() == 0 || mg->array.patch_columns() == 0) { std::cerr << "Empty Mesh, No Draggers to Add" << std::endl; return; } @@ -2189,34 +2195,30 @@ void GrDrag::addDraggersMesh(SPMeshGradient *mg, SPItem *item, Inkscape::PaintTa mg->array.handles.clear(); mg->array.tensors.clear(); - if( (fill_or_stroke == Inkscape::FOR_FILL && !edit_fill) || - (fill_or_stroke == Inkscape::FOR_STROKE && !edit_stroke) ) { + if ((fill_or_stroke == Inkscape::FOR_FILL && !edit_fill) || + (fill_or_stroke == Inkscape::FOR_STROKE && !edit_stroke)) { return; } - for(auto & node : nodes) { - for(auto & j : node) { - + for (auto &node : nodes) { + for (auto &j : node) { // std::cout << " Draggers: " << i << " " << j << " " << nodes[i][j]->node_type << std::endl; - switch ( j->node_type ) { - - case MG_NODE_TYPE_CORNER: - { - mg->array.corners.push_back( j ); - GrDraggable *corner = new GrDraggable (item, POINT_MG_CORNER, icorner, fill_or_stroke); - addDragger ( corner ); + switch (j->node_type) { + case MG_NODE_TYPE_CORNER: { + mg->array.corners.push_back(j); + GrDraggable *corner = new GrDraggable(item, POINT_MG_CORNER, icorner, fill_or_stroke); + addDragger(corner); j->draggable = icorner; ++icorner; break; } - case MG_NODE_TYPE_HANDLE: - { - mg->array.handles.push_back( j ); - GrDraggable *handle = new GrDraggable (item, POINT_MG_HANDLE, ihandle, fill_or_stroke); - GrDragger* dragger = addDragger ( handle ); + case MG_NODE_TYPE_HANDLE: { + mg->array.handles.push_back(j); + GrDraggable *handle = new GrDraggable(item, POINT_MG_HANDLE, ihandle, fill_or_stroke); + GrDragger *dragger = addDragger(handle); - if( !show_handles || !j->set ) { + if (!show_handles || !j->set) { dragger->knot->hide(); } j->draggable = ihandle; @@ -2224,12 +2226,11 @@ void GrDrag::addDraggersMesh(SPMeshGradient *mg, SPItem *item, Inkscape::PaintTa break; } - case MG_NODE_TYPE_TENSOR: - { - mg->array.tensors.push_back( j ); - GrDraggable *tensor = new GrDraggable (item, POINT_MG_TENSOR, itensor, fill_or_stroke); - GrDragger* dragger = addDragger ( tensor ); - if( !show_handles || !j->set ) { + case MG_NODE_TYPE_TENSOR: { + mg->array.tensors.push_back(j); + GrDraggable *tensor = new GrDraggable(item, POINT_MG_TENSOR, itensor, fill_or_stroke); + GrDragger *dragger = addDragger(tensor); + if (!show_handles || !j->set) { dragger->knot->hide(); } j->draggable = itensor; @@ -2254,14 +2255,13 @@ void GrDrag::addDraggersMesh(SPMeshGradient *mg, SPItem *item, Inkscape::PaintTa void GrDrag::refreshDraggersMesh(SPMeshGradient *mg, SPItem *item, Inkscape::PaintTarget fill_or_stroke) { mg->ensureArray(); - std::vector< std::vector< SPMeshNode* > > nodes = mg->array.nodes; + std::vector> nodes = mg->array.nodes; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool show_handles = (prefs->getBool("/tools/mesh/show_handles", true)); // Make sure we have at least one patch defined. - if( mg->array.patch_rows() == 0 || mg->array.patch_columns() == 0 ) { - + if (mg->array.patch_rows() == 0 || mg->array.patch_columns() == 0) { std::cerr << "GrDrag::refreshDraggersMesh: Empty Mesh, No Draggers to refresh!" << std::endl; return; } @@ -2269,24 +2269,21 @@ void GrDrag::refreshDraggersMesh(SPMeshGradient *mg, SPItem *item, Inkscape::Pai guint ihandle = 0; guint itensor = 0; - for(auto & node : nodes) { - for(auto & j : node) { - + for (auto &node : nodes) { + for (auto &j : node) { // std::cout << " Draggers: " << i << " " << j << " " << nodes[i][j]->node_type << std::endl; - switch ( j->node_type ) { - + switch (j->node_type) { case MG_NODE_TYPE_CORNER: // Do nothing, corners are always shown. break; - case MG_NODE_TYPE_HANDLE: - { - GrDragger* dragger = getDraggerFor(item, POINT_MG_HANDLE, ihandle, fill_or_stroke); + case MG_NODE_TYPE_HANDLE: { + GrDragger *dragger = getDraggerFor(item, POINT_MG_HANDLE, ihandle, fill_or_stroke); if (dragger) { - Geom::Point pk = getGradientCoords( item, POINT_MG_HANDLE, ihandle, fill_or_stroke); + Geom::Point pk = getGradientCoords(item, POINT_MG_HANDLE, ihandle, fill_or_stroke); dragger->knot->moveto(pk); - if( !show_handles || !j->set ) { + if (!show_handles || !j->set) { dragger->knot->hide(); } else { dragger->knot->show(); @@ -2299,13 +2296,12 @@ void GrDrag::refreshDraggersMesh(SPMeshGradient *mg, SPItem *item, Inkscape::Pai break; } - case MG_NODE_TYPE_TENSOR: - { - GrDragger* dragger = getDraggerFor(item, POINT_MG_TENSOR, itensor, fill_or_stroke); + case MG_NODE_TYPE_TENSOR: { + GrDragger *dragger = getDraggerFor(item, POINT_MG_TENSOR, itensor, fill_or_stroke); if (dragger) { - Geom::Point pk = getGradientCoords( item, POINT_MG_TENSOR, itensor, fill_or_stroke); + Geom::Point pk = getGradientCoords(item, POINT_MG_TENSOR, itensor, fill_or_stroke); dragger->knot->moveto(pk); - if( !show_handles || !j->set ) { + if (!show_handles || !j->set) { dragger->knot->hide(); } else { dragger->knot->show(); @@ -2341,7 +2337,8 @@ void GrDrag::grabKnot(GrDragger *dragger, gint x, gint y, guint32 etime) * Artificially grab the knot of the dragger with this draggable; used by the gradient context. * This allows setting the final point from the end of the drag when creating a new gradient. */ -void GrDrag::grabKnot(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke, gint x, gint y, guint32 etime) +void GrDrag::grabKnot(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke, gint x, + gint y, guint32 etime) { GrDragger *dragger = getDraggerFor(item, point_type, point_i, fill_or_stroke); if (dragger) { @@ -2370,39 +2367,38 @@ void GrDrag::updateDraggers() if (style && (style->fill.isPaintserver())) { SPPaintServer *server = style->getFillPaintServer(); - if ( server && SP_IS_GRADIENT( server ) ) { - if ( server->isSolid() - || (SP_GRADIENT(server)->getVector() && SP_GRADIENT(server)->getVector()->isSolid())) { + if (server && SP_IS_GRADIENT(server)) { + if (server->isSolid() || + (SP_GRADIENT(server)->getVector() && SP_GRADIENT(server)->getVector()->isSolid())) { // Suppress "gradientness" of solid paint - } else if ( SP_IS_LINEARGRADIENT(server) ) { - addDraggersLinear( SP_LINEARGRADIENT(server), item, Inkscape::FOR_FILL ); - } else if ( SP_IS_RADIALGRADIENT(server) ) { - addDraggersRadial( SP_RADIALGRADIENT(server), item, Inkscape::FOR_FILL ); - } else if ( SP_IS_MESHGRADIENT(server) ) { - addDraggersMesh( SP_MESHGRADIENT(server), item, Inkscape::FOR_FILL ); + } else if (SP_IS_LINEARGRADIENT(server)) { + addDraggersLinear(SP_LINEARGRADIENT(server), item, Inkscape::FOR_FILL); + } else if (SP_IS_RADIALGRADIENT(server)) { + addDraggersRadial(SP_RADIALGRADIENT(server), item, Inkscape::FOR_FILL); + } else if (SP_IS_MESHGRADIENT(server)) { + addDraggersMesh(SP_MESHGRADIENT(server), item, Inkscape::FOR_FILL); } } } if (style && (style->stroke.isPaintserver())) { SPPaintServer *server = style->getStrokePaintServer(); - if ( server && SP_IS_GRADIENT( server ) ) { - if ( server->isSolid() - || (SP_GRADIENT(server)->getVector() && SP_GRADIENT(server)->getVector()->isSolid())) { + if (server && SP_IS_GRADIENT(server)) { + if (server->isSolid() || + (SP_GRADIENT(server)->getVector() && SP_GRADIENT(server)->getVector()->isSolid())) { // Suppress "gradientness" of solid paint - } else if ( SP_IS_LINEARGRADIENT(server) ) { - addDraggersLinear( SP_LINEARGRADIENT(server), item, Inkscape::FOR_STROKE ); - } else if ( SP_IS_RADIALGRADIENT(server) ) { - addDraggersRadial( SP_RADIALGRADIENT(server), item, Inkscape::FOR_STROKE ); - } else if ( SP_IS_MESHGRADIENT(server) ) { - addDraggersMesh( SP_MESHGRADIENT(server), item, Inkscape::FOR_STROKE ); + } else if (SP_IS_LINEARGRADIENT(server)) { + addDraggersLinear(SP_LINEARGRADIENT(server), item, Inkscape::FOR_STROKE); + } else if (SP_IS_RADIALGRADIENT(server)) { + addDraggersRadial(SP_RADIALGRADIENT(server), item, Inkscape::FOR_STROKE); + } else if (SP_IS_MESHGRADIENT(server)) { + addDraggersMesh(SP_MESHGRADIENT(server), item, Inkscape::FOR_STROKE); } } } } } - /** * Refresh draggers, moving and toggling visibility as necessary. * Does not regenerate draggers (as does updateDraggers()). @@ -2410,7 +2406,6 @@ void GrDrag::updateDraggers() */ void GrDrag::refreshDraggers() { - g_return_if_fail(this->selection != nullptr); auto list = this->selection->items(); for (auto i = list.begin(); i != list.end(); ++i) { @@ -2419,25 +2414,24 @@ void GrDrag::refreshDraggers() if (style && (style->fill.isPaintserver())) { SPPaintServer *server = style->getFillPaintServer(); - if ( server && SP_IS_GRADIENT( server ) ) { - if ( SP_IS_MESHGRADIENT(server) ) { - refreshDraggersMesh( SP_MESHGRADIENT(server), item, Inkscape::FOR_FILL ); + if (server && SP_IS_GRADIENT(server)) { + if (SP_IS_MESHGRADIENT(server)) { + refreshDraggersMesh(SP_MESHGRADIENT(server), item, Inkscape::FOR_FILL); } } } if (style && (style->stroke.isPaintserver())) { SPPaintServer *server = style->getStrokePaintServer(); - if ( server && SP_IS_GRADIENT( server ) ) { - if ( SP_IS_MESHGRADIENT(server) ) { - refreshDraggersMesh( SP_MESHGRADIENT(server), item, Inkscape::FOR_STROKE ); + if (server && SP_IS_GRADIENT(server)) { + if (SP_IS_MESHGRADIENT(server)) { + refreshDraggersMesh(SP_MESHGRADIENT(server), item, Inkscape::FOR_STROKE); } } } } } - /** * Returns true if at least one of the draggers' knots has the mouse hovering above it. */ @@ -2452,7 +2446,7 @@ bool GrDrag::mouseOver() return true; } } - if(mouse_out == true){ + if (mouse_out == true) { updateLines(); mouse_out = false; } @@ -2481,166 +2475,175 @@ void GrDrag::updateLines() if (style && (style->fill.isPaintserver())) { SPPaintServer *server = item->style->getFillPaintServer(); - if ( server && SP_IS_GRADIENT( server ) ) { - if ( server->isSolid() - || (SP_GRADIENT(server)->getVector() && SP_GRADIENT(server)->getVector()->isSolid())) { + if (server && SP_IS_GRADIENT(server)) { + if (server->isSolid() || + (SP_GRADIENT(server)->getVector() && SP_GRADIENT(server)->getVector()->isSolid())) { // Suppress "gradientness" of solid paint - } else if ( SP_IS_LINEARGRADIENT(server) ) { - addLine(item, getGradientCoords(item, POINT_LG_BEGIN, 0, Inkscape::FOR_FILL), getGradientCoords(item, POINT_LG_END, 0, Inkscape::FOR_FILL), Inkscape::FOR_FILL); - } else if ( SP_IS_RADIALGRADIENT(server) ) { + } else if (SP_IS_LINEARGRADIENT(server)) { + addLine(item, getGradientCoords(item, POINT_LG_BEGIN, 0, Inkscape::FOR_FILL), + getGradientCoords(item, POINT_LG_END, 0, Inkscape::FOR_FILL), Inkscape::FOR_FILL); + } else if (SP_IS_RADIALGRADIENT(server)) { Geom::Point center = getGradientCoords(item, POINT_RG_CENTER, 0, Inkscape::FOR_FILL); - addLine(item, center, getGradientCoords(item, POINT_RG_R1, 0, Inkscape::FOR_FILL), Inkscape::FOR_FILL); - addLine(item, center, getGradientCoords(item, POINT_RG_R2, 0, Inkscape::FOR_FILL), Inkscape::FOR_FILL); - } else if ( SP_IS_MESHGRADIENT(server) ) { - + addLine(item, center, getGradientCoords(item, POINT_RG_R1, 0, Inkscape::FOR_FILL), + Inkscape::FOR_FILL); + addLine(item, center, getGradientCoords(item, POINT_RG_R2, 0, Inkscape::FOR_FILL), + Inkscape::FOR_FILL); + } else if (SP_IS_MESHGRADIENT(server)) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool edit_fill = (prefs->getBool("/tools/mesh/edit_fill", true)); + bool edit_fill = (prefs->getBool("/tools/mesh/edit_fill", true)); SPMeshGradient *mg = SP_MESHGRADIENT(server); if (edit_fill) { - guint rows = mg->array.patch_rows(); - guint columns = mg->array.patch_columns(); - for ( guint i = 0; i < rows; ++i ) { - for ( guint j = 0; j < columns; ++j ) { - - std::vector h; - - SPMeshPatchI patch( &(mg->array.nodes), i, j ); - - // clockwise around patch, used to find corner dragger - int corner0 = i * (columns + 1) + j; - int corner1 = corner0 + 1; - int corner2 = corner1 + columns + 1; - int corner3 = corner2 - 1; - // clockwise around patch, used to find handle dragger - int handle0 = 2*j + i*(2+4*columns); - int handle1 = handle0 + 1; - int handle2 = j + i*(2+4*columns) + 2*columns + 1; - int handle3 = j + i*(2+4*columns) + 3*columns + 2; - int handle4 = handle1 + (2+4*columns); - int handle5 = handle0 + (2+4*columns); - int handle6 = handle3 - 1; - int handle7 = handle2 - 1; - - // Top line - h = patch.getPointsForSide( 0 ); - for( guint p = 0; p < 4; ++p ) { - h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); - } - addCurve (item, h[0], h[1], h[2], h[3], corner0, corner1, handle0, handle1, Inkscape::FOR_FILL ); - - // Right line - if( j == columns - 1 ) { - h = patch.getPointsForSide( 1 ); - for( guint p = 0; p < 4; ++p ) { + guint rows = mg->array.patch_rows(); + guint columns = mg->array.patch_columns(); + for (guint i = 0; i < rows; ++i) { + for (guint j = 0; j < columns; ++j) { + std::vector h; + + SPMeshPatchI patch(&(mg->array.nodes), i, j); + + // clockwise around patch, used to find corner dragger + int corner0 = i * (columns + 1) + j; + int corner1 = corner0 + 1; + int corner2 = corner1 + columns + 1; + int corner3 = corner2 - 1; + // clockwise around patch, used to find handle dragger + int handle0 = 2 * j + i * (2 + 4 * columns); + int handle1 = handle0 + 1; + int handle2 = j + i * (2 + 4 * columns) + 2 * columns + 1; + int handle3 = j + i * (2 + 4 * columns) + 3 * columns + 2; + int handle4 = handle1 + (2 + 4 * columns); + int handle5 = handle0 + (2 + 4 * columns); + int handle6 = handle3 - 1; + int handle7 = handle2 - 1; + + // Top line + h = patch.getPointsForSide(0); + for (guint p = 0; p < 4; ++p) { h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); } - addCurve (item, h[0], h[1], h[2], h[3], corner1, corner2, handle2, handle3, Inkscape::FOR_FILL ); - } + addCurve(item, h[0], h[1], h[2], h[3], corner0, corner1, handle0, handle1, + Inkscape::FOR_FILL); + + // Right line + if (j == columns - 1) { + h = patch.getPointsForSide(1); + for (guint p = 0; p < 4; ++p) { + h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); + } + addCurve(item, h[0], h[1], h[2], h[3], corner1, corner2, handle2, handle3, + Inkscape::FOR_FILL); + } - // Bottom line - if( i == rows - 1 ) { - h = patch.getPointsForSide( 2 ); - for( guint p = 0; p < 4; ++p ) { - h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); + // Bottom line + if (i == rows - 1) { + h = patch.getPointsForSide(2); + for (guint p = 0; p < 4; ++p) { + h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); + } + addCurve(item, h[0], h[1], h[2], h[3], corner2, corner3, handle4, handle5, + Inkscape::FOR_FILL); } - addCurve (item, h[0], h[1], h[2], h[3], corner2, corner3, handle4, handle5, Inkscape::FOR_FILL ); - } - // Left line - h = patch.getPointsForSide( 3 ); - for( guint p = 0; p < 4; ++p ) { - h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); + // Left line + h = patch.getPointsForSide(3); + for (guint p = 0; p < 4; ++p) { + h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); + } + addCurve(item, h[0], h[1], h[2], h[3], corner3, corner0, handle6, handle7, + Inkscape::FOR_FILL); } - addCurve (item, h[0], h[1], h[2], h[3], corner3, corner0, handle6, handle7, Inkscape::FOR_FILL ); } } - } - } + } } } if (style && (style->stroke.isPaintserver())) { SPPaintServer *server = item->style->getStrokePaintServer(); - if ( server && SP_IS_GRADIENT( server ) ) { - if ( server->isSolid() - || (SP_GRADIENT(server)->getVector() && SP_GRADIENT(server)->getVector()->isSolid())) { + if (server && SP_IS_GRADIENT(server)) { + if (server->isSolid() || + (SP_GRADIENT(server)->getVector() && SP_GRADIENT(server)->getVector()->isSolid())) { // Suppress "gradientness" of solid paint - } else if ( SP_IS_LINEARGRADIENT(server) ) { - addLine(item, getGradientCoords(item, POINT_LG_BEGIN, 0, Inkscape::FOR_STROKE), getGradientCoords(item, POINT_LG_END, 0, Inkscape::FOR_STROKE), Inkscape::FOR_STROKE); - } else if ( SP_IS_RADIALGRADIENT(server) ) { + } else if (SP_IS_LINEARGRADIENT(server)) { + addLine(item, getGradientCoords(item, POINT_LG_BEGIN, 0, Inkscape::FOR_STROKE), + getGradientCoords(item, POINT_LG_END, 0, Inkscape::FOR_STROKE), Inkscape::FOR_STROKE); + } else if (SP_IS_RADIALGRADIENT(server)) { Geom::Point center = getGradientCoords(item, POINT_RG_CENTER, 0, Inkscape::FOR_STROKE); - addLine(item, center, getGradientCoords(item, POINT_RG_R1, 0, Inkscape::FOR_STROKE), Inkscape::FOR_STROKE); - addLine(item, center, getGradientCoords(item, POINT_RG_R2, 0, Inkscape::FOR_STROKE), Inkscape::FOR_STROKE); - } else if ( SP_IS_MESHGRADIENT(server) ) { - + addLine(item, center, getGradientCoords(item, POINT_RG_R1, 0, Inkscape::FOR_STROKE), + Inkscape::FOR_STROKE); + addLine(item, center, getGradientCoords(item, POINT_RG_R2, 0, Inkscape::FOR_STROKE), + Inkscape::FOR_STROKE); + } else if (SP_IS_MESHGRADIENT(server)) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool edit_stroke = (prefs->getBool("/tools/mesh/edit_stroke", true)); + bool edit_stroke = (prefs->getBool("/tools/mesh/edit_stroke", true)); if (edit_stroke) { - - // MESH FIXME: TURN ROUTINE INTO FUNCTION AND CALL FOR BOTH FILL AND STROKE. - SPMeshGradient *mg = SP_MESHGRADIENT(server); - - guint rows = mg->array.patch_rows(); - guint columns = mg->array.patch_columns(); - for ( guint i = 0; i < rows; ++i ) { - for ( guint j = 0; j < columns; ++j ) { - - std::vector h; - - SPMeshPatchI patch( &(mg->array.nodes), i, j ); - - // clockwise around patch, used to find corner dragger - int corner0 = i * (columns + 1) + j; - int corner1 = corner0 + 1; - int corner2 = corner1 + columns + 1; - int corner3 = corner2 - 1; - // clockwise around patch, used to find handle dragger - int handle0 = 2*j + i*(2+4*columns); - int handle1 = handle0 + 1; - int handle2 = j + i*(2+4*columns) + 2*columns + 1; - int handle3 = j + i*(2+4*columns) + 3*columns + 2; - int handle4 = handle1 + (2+4*columns); - int handle5 = handle0 + (2+4*columns); - int handle6 = handle3 - 1; - int handle7 = handle2 - 1; - - // Top line - h = patch.getPointsForSide( 0 ); - for( guint p = 0; p < 4; ++p ) { - h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); - } - addCurve (item, h[0], h[1], h[2], h[3], corner0, corner1, handle0, handle1, Inkscape::FOR_STROKE); - - // Right line - if( j == columns - 1 ) { - h = patch.getPointsForSide( 1 ); - for( guint p = 0; p < 4; ++p ) { + // MESH FIXME: TURN ROUTINE INTO FUNCTION AND CALL FOR BOTH FILL AND STROKE. + SPMeshGradient *mg = SP_MESHGRADIENT(server); + + guint rows = mg->array.patch_rows(); + guint columns = mg->array.patch_columns(); + for (guint i = 0; i < rows; ++i) { + for (guint j = 0; j < columns; ++j) { + std::vector h; + + SPMeshPatchI patch(&(mg->array.nodes), i, j); + + // clockwise around patch, used to find corner dragger + int corner0 = i * (columns + 1) + j; + int corner1 = corner0 + 1; + int corner2 = corner1 + columns + 1; + int corner3 = corner2 - 1; + // clockwise around patch, used to find handle dragger + int handle0 = 2 * j + i * (2 + 4 * columns); + int handle1 = handle0 + 1; + int handle2 = j + i * (2 + 4 * columns) + 2 * columns + 1; + int handle3 = j + i * (2 + 4 * columns) + 3 * columns + 2; + int handle4 = handle1 + (2 + 4 * columns); + int handle5 = handle0 + (2 + 4 * columns); + int handle6 = handle3 - 1; + int handle7 = handle2 - 1; + + // Top line + h = patch.getPointsForSide(0); + for (guint p = 0; p < 4; ++p) { h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); } - addCurve (item, h[0], h[1], h[2], h[3], corner1, corner2, handle2, handle3, Inkscape::FOR_STROKE); - } + addCurve(item, h[0], h[1], h[2], h[3], corner0, corner1, handle0, handle1, + Inkscape::FOR_STROKE); + + // Right line + if (j == columns - 1) { + h = patch.getPointsForSide(1); + for (guint p = 0; p < 4; ++p) { + h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); + } + addCurve(item, h[0], h[1], h[2], h[3], corner1, corner2, handle2, handle3, + Inkscape::FOR_STROKE); + } - // Bottom line - if( i == rows - 1 ) { - h = patch.getPointsForSide( 2 ); - for( guint p = 0; p < 4; ++p ) { - h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); + // Bottom line + if (i == rows - 1) { + h = patch.getPointsForSide(2); + for (guint p = 0; p < 4; ++p) { + h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); + } + addCurve(item, h[0], h[1], h[2], h[3], corner2, corner3, handle4, handle5, + Inkscape::FOR_STROKE); } - addCurve (item, h[0], h[1], h[2], h[3], corner2, corner3, handle4, handle5, Inkscape::FOR_STROKE); - } - // Left line - h = patch.getPointsForSide( 3 ); - for( guint p = 0; p < 4; ++p ) { - h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); + // Left line + h = patch.getPointsForSide(3); + for (guint p = 0; p < 4; ++p) { + h[p] *= Geom::Affine(mg->gradientTransform) * (Geom::Affine)item->i2dt_affine(); + } + addCurve(item, h[0], h[1], h[2], h[3], corner3, corner0, handle6, handle7, + Inkscape::FOR_STROKE); } - addCurve (item, h[0], h[1], h[2], h[3], corner3, corner0, handle6, handle7,Inkscape::FOR_STROKE); } } - } } } } @@ -2656,7 +2659,7 @@ void GrDrag::updateLevels() hor_levels.clear(); vert_levels.clear(); - g_return_if_fail (this->selection != nullptr); + g_return_if_fail(this->selection != nullptr); auto list = this->selection->items(); for (auto i = list.begin(); i != list.end(); ++i) { @@ -2679,14 +2682,14 @@ void GrDrag::selected_reverse_vector() if (selected.empty()) return; - for(auto draggable : (*(selected.begin()))->draggables) { - sp_item_gradient_reverse_vector (draggable->item, draggable->fill_or_stroke); + for (auto draggable : (*(selected.begin()))->draggables) { + sp_item_gradient_reverse_vector(draggable->item, draggable->fill_or_stroke); } } void GrDrag::selected_move_nowrite(double x, double y, bool scale_radial) { - selected_move (x, y, false, scale_radial); + selected_move(x, y, false, scale_radial); } void GrDrag::selected_move(double x, double y, bool write_repr, bool scale_radial) @@ -2696,21 +2699,17 @@ void GrDrag::selected_move(double x, double y, bool write_repr, bool scale_radia bool did = false; - for(auto d : selected) { + for (auto d : selected) { if (!d->isA(POINT_LG_MID) && !d->isA(POINT_RG_MID1) && !d->isA(POINT_RG_MID2)) { // if this is an endpoint, // Moving an rg center moves its focus and radii as well. // therefore, if this is a focus or radius and if selection // contains the center as well, do not move this one - if (d->isA(POINT_RG_R1) || d->isA(POINT_RG_R2) || - (d->isA(POINT_RG_FOCUS) && !d->isA(POINT_RG_CENTER))) { + if (d->isA(POINT_RG_R1) || d->isA(POINT_RG_R2) || (d->isA(POINT_RG_FOCUS) && !d->isA(POINT_RG_CENTER))) { bool skip_radius_with_center = false; - for(auto d_new : selected) { - if (d_new->isA (( d->draggables[0])->item, - POINT_RG_CENTER, - 0, - (d->draggables[0])->fill_or_stroke)) { + for (auto d_new : selected) { + if (d_new->isA((d->draggables[0])->item, POINT_RG_CENTER, 0, (d->draggables[0])->fill_or_stroke)) { // FIXME: here we take into account only the first draggable! skip_radius_with_center = true; } @@ -2721,12 +2720,12 @@ void GrDrag::selected_move(double x, double y, bool write_repr, bool scale_radia did = true; Geom::Point p_old = d->point; - d->point += Geom::Point (x, y); + d->point += Geom::Point(x, y); d->point_original = d->point; d->knot->moveto(d->point); - d->fireDraggables (write_repr, scale_radial); - d->moveMeshHandles( p_old, MG_NODE_NO_SCALE ); + d->fireDraggables(write_repr, scale_radial); + d->moveMeshHandles(p_old, MG_NODE_NO_SCALE); d->updateDependencies(write_repr); } } @@ -2744,22 +2743,22 @@ void GrDrag::selected_move(double x, double y, bool write_repr, bool scale_radia // a midpoint dragger can (logically) only contain one GrDraggable GrDraggable *draggable = dragger->draggables[0]; - Geom::Point begin(0,0), end(0,0); - Geom::Point low_lim(0,0), high_lim(0,0); + Geom::Point begin(0, 0), end(0, 0); + Geom::Point low_lim(0, 0), high_lim(0, 0); SPObject *server = draggable->getServer(); std::vector moving; gr_midpoint_limits(dragger, server, &begin, &end, &low_lim, &high_lim, moving); Geom::LineSegment ls(low_lim, high_lim); - Geom::Point p = ls.pointAt(ls.nearestTime(dragger->point + Geom::Point(x,y))); + Geom::Point p = ls.pointAt(ls.nearestTime(dragger->point + Geom::Point(x, y))); Geom::Point displacement = p - dragger->point; - for(auto drg : moving) { + for (auto drg : moving) { SPKnot *drgknot = drg->knot; drg->point += displacement; drgknot->moveto(drg->point); - drg->fireDraggables (true); + drg->fireDraggables(true); drg->updateDependencies(true); did = true; } @@ -2778,7 +2777,7 @@ void GrDrag::selected_move_screen(double x, double y) gdouble zx = x / zoom; gdouble zy = y / zoom; - selected_move (zx, zy); + selected_move(zx, zy); } /** @@ -2852,14 +2851,14 @@ bool GrDrag::key_press_handler(GdkEvent *event) GrDragger *GrDrag::select_next() { GrDragger *d = nullptr; - if (selected.empty() || (++find(draggers.begin(),draggers.end(),*(selected.begin())))==draggers.end()) { + if (selected.empty() || (++find(draggers.begin(), draggers.end(), *(selected.begin()))) == draggers.end()) { if (!draggers.empty()) d = draggers[0]; } else { - d = *(++find(draggers.begin(),draggers.end(),*(selected.begin()))); + d = *(++find(draggers.begin(), draggers.end(), *(selected.begin()))); } if (d) - setSelected (d); + setSelected(d); return d; } @@ -2871,260 +2870,247 @@ GrDragger *GrDrag::select_prev() GrDragger *d = nullptr; if (selected.empty() || draggers[0] == (*(selected.begin()))) { if (!draggers.empty()) - d = draggers[draggers.size()-1]; + d = draggers[draggers.size() - 1]; } else { - d = *(--find(draggers.begin(),draggers.end(),*(selected.begin()))); + d = *(--find(draggers.begin(), draggers.end(), *(selected.begin()))); } if (d) - setSelected (d); + setSelected(d); return d; } - // FIXME: i.m.o. an ugly function that I just made to work, but... aargh! (Johan) void GrDrag::deleteSelected(bool just_one) { - if (selected.empty()) return; + if (selected.empty()) + return; SPDocument *document = nullptr; - struct StructStopInfo { - SPStop * spstop; - GrDraggable * draggable; - SPGradient * gradient; - SPGradient * vector; + struct StructStopInfo + { + SPStop *spstop; + GrDraggable *draggable; + SPGradient *gradient; + SPGradient *vector; }; - std::vector midstoplist;// list of stops that must be deleted (will be deleted first) - std::vector endstoplist;// list of stops that must be deleted + std::vector midstoplist; // list of stops that must be deleted (will be deleted first) + std::vector endstoplist; // list of stops that must be deleted while (!selected.empty()) { GrDragger *dragger = *(selected.begin()); - for(auto draggable : dragger->draggables) { + for (auto draggable : dragger->draggables) { SPGradient *gradient = getGradient(draggable->item, draggable->fill_or_stroke); - SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (gradient, false); + SPGradient *vector = sp_gradient_get_forked_vector_if_necessary(gradient, false); switch (draggable->point_type) { case POINT_LG_MID: case POINT_RG_MID1: - case POINT_RG_MID2: - { - SPStop *stop = sp_get_stop_i(vector, draggable->point_i); - // check if already present in list. (e.g. when both RG_MID1 and RG_MID2 were selected) - bool present = false; - for (auto i:midstoplist) { - if ( i == stop ) { - present = true; - break; // no need to search further. - } + case POINT_RG_MID2: { + SPStop *stop = sp_get_stop_i(vector, draggable->point_i); + // check if already present in list. (e.g. when both RG_MID1 and RG_MID2 were selected) + bool present = false; + for (auto i : midstoplist) { + if (i == stop) { + present = true; + break; // no need to search further. } - if (!present) - midstoplist.push_back(stop); } - break; + if (!present) + midstoplist.push_back(stop); + } break; case POINT_LG_BEGIN: case POINT_LG_END: case POINT_RG_CENTER: case POINT_RG_R1: - case POINT_RG_R2: - { - SPStop *stop = nullptr; - if ( (draggable->point_type == POINT_LG_BEGIN) || (draggable->point_type == POINT_RG_CENTER) ) { - stop = vector->getFirstStop(); - } else { - stop = sp_last_stop(vector); - } - if (stop) { - StructStopInfo *stopinfo = new StructStopInfo; - stopinfo->spstop = stop; - stopinfo->draggable = draggable; - stopinfo->gradient = gradient; - stopinfo->vector = vector; - // check if already present in list. (e.g. when both R1 and R2 were selected) - bool present = false; - for (auto i : endstoplist) { - if ( i->spstop == stopinfo->spstop ) { - present = true; - break; // no need to search further. - } + case POINT_RG_R2: { + SPStop *stop = nullptr; + if ((draggable->point_type == POINT_LG_BEGIN) || (draggable->point_type == POINT_RG_CENTER)) { + stop = vector->getFirstStop(); + } else { + stop = sp_last_stop(vector); + } + if (stop) { + StructStopInfo *stopinfo = new StructStopInfo; + stopinfo->spstop = stop; + stopinfo->draggable = draggable; + stopinfo->gradient = gradient; + stopinfo->vector = vector; + // check if already present in list. (e.g. when both R1 and R2 were selected) + bool present = false; + for (auto i : endstoplist) { + if (i->spstop == stopinfo->spstop) { + present = true; + break; // no need to search further. } - if (!present) - endstoplist.push_back(stopinfo); - else - delete stopinfo; } + if (!present) + endstoplist.push_back(stopinfo); + else + delete stopinfo; } - break; + } break; default: break; } } selected.erase(dragger); - if ( just_one ) break; // iterate once if just_one is set. + if (just_one) + break; // iterate once if just_one is set. } - for (auto stop:midstoplist) { + for (auto stop : midstoplist) { document = stop->document; - Inkscape::XML::Node * parent = stop->getRepr()->parent(); + Inkscape::XML::Node *parent = stop->getRepr()->parent(); parent->removeChild(stop->getRepr()); } - for (auto stopinfo:endstoplist) { + for (auto stopinfo : endstoplist) { document = stopinfo->spstop->document; // 2 is the minimum, cannot delete more than that without deleting the whole vector // cannot use vector->vector.stops.size() because the vector might be invalidated by deletion of a midstop // manually count the children, don't know if there already exists a function for this... int len = 0; - for (auto& child: stopinfo->vector->children) - { - if ( SP_IS_STOP(&child) ) { - len ++; + for (auto &child : stopinfo->vector->children) { + if (SP_IS_STOP(&child)) { + len++; } } - if (len > 2) - { + if (len > 2) { switch (stopinfo->draggable->point_type) { - case POINT_LG_BEGIN: - { - stopinfo->vector->getRepr()->removeChild(stopinfo->spstop->getRepr()); - - SPLinearGradient *lg = SP_LINEARGRADIENT(stopinfo->gradient); - Geom::Point oldbegin = Geom::Point (lg->x1.computed, lg->y1.computed); - Geom::Point end = Geom::Point (lg->x2.computed, lg->y2.computed); - SPStop *stop = stopinfo->vector->getFirstStop(); - gdouble offset = stop->offset; - Geom::Point newbegin = oldbegin + offset * (end - oldbegin); - lg->x1.computed = newbegin[Geom::X]; - lg->y1.computed = newbegin[Geom::Y]; - - Inkscape::XML::Node *repr = stopinfo->gradient->getRepr(); - sp_repr_set_svg_double(repr, "x1", lg->x1.computed); - sp_repr_set_svg_double(repr, "y1", lg->y1.computed); - stop->offset = 0; - sp_repr_set_css_double(stop->getRepr(), "offset", 0); - - // iterate through midstops to set new offset values such that they won't move on canvas. - SPStop *laststop = sp_last_stop(stopinfo->vector); + case POINT_LG_BEGIN: { + stopinfo->vector->getRepr()->removeChild(stopinfo->spstop->getRepr()); + + SPLinearGradient *lg = SP_LINEARGRADIENT(stopinfo->gradient); + Geom::Point oldbegin = Geom::Point(lg->x1.computed, lg->y1.computed); + Geom::Point end = Geom::Point(lg->x2.computed, lg->y2.computed); + SPStop *stop = stopinfo->vector->getFirstStop(); + gdouble offset = stop->offset; + Geom::Point newbegin = oldbegin + offset * (end - oldbegin); + lg->x1.computed = newbegin[Geom::X]; + lg->y1.computed = newbegin[Geom::Y]; + + Inkscape::XML::Node *repr = stopinfo->gradient->getRepr(); + sp_repr_set_svg_double(repr, "x1", lg->x1.computed); + sp_repr_set_svg_double(repr, "y1", lg->y1.computed); + stop->offset = 0; + sp_repr_set_css_double(stop->getRepr(), "offset", 0); + + // iterate through midstops to set new offset values such that they won't move on canvas. + SPStop *laststop = sp_last_stop(stopinfo->vector); + stop = stop->getNextStop(); + while (stop != laststop) { + stop->offset = (stop->offset - offset) / (1 - offset); + sp_repr_set_css_double(stop->getRepr(), "offset", stop->offset); stop = stop->getNextStop(); - while ( stop != laststop ) { - stop->offset = (stop->offset - offset)/(1 - offset); - sp_repr_set_css_double(stop->getRepr(), "offset", stop->offset); - stop = stop->getNextStop(); - } } - break; - case POINT_LG_END: - { - stopinfo->vector->getRepr()->removeChild(stopinfo->spstop->getRepr()); - - SPLinearGradient *lg = SP_LINEARGRADIENT(stopinfo->gradient); - Geom::Point begin = Geom::Point (lg->x1.computed, lg->y1.computed); - Geom::Point oldend = Geom::Point (lg->x2.computed, lg->y2.computed); - SPStop *laststop = sp_last_stop(stopinfo->vector); - gdouble offset = laststop->offset; - Geom::Point newend = begin + offset * (oldend - begin); - lg->x2.computed = newend[Geom::X]; - lg->y2.computed = newend[Geom::Y]; - - Inkscape::XML::Node *repr = stopinfo->gradient->getRepr(); - sp_repr_set_svg_double(repr, "x2", lg->x2.computed); - sp_repr_set_svg_double(repr, "y2", lg->y2.computed); - laststop->offset = 1; - sp_repr_set_css_double(laststop->getRepr(), "offset", 1); - - // iterate through midstops to set new offset values such that they won't move on canvas. - SPStop *stop = stopinfo->vector->getFirstStop(); + } break; + case POINT_LG_END: { + stopinfo->vector->getRepr()->removeChild(stopinfo->spstop->getRepr()); + + SPLinearGradient *lg = SP_LINEARGRADIENT(stopinfo->gradient); + Geom::Point begin = Geom::Point(lg->x1.computed, lg->y1.computed); + Geom::Point oldend = Geom::Point(lg->x2.computed, lg->y2.computed); + SPStop *laststop = sp_last_stop(stopinfo->vector); + gdouble offset = laststop->offset; + Geom::Point newend = begin + offset * (oldend - begin); + lg->x2.computed = newend[Geom::X]; + lg->y2.computed = newend[Geom::Y]; + + Inkscape::XML::Node *repr = stopinfo->gradient->getRepr(); + sp_repr_set_svg_double(repr, "x2", lg->x2.computed); + sp_repr_set_svg_double(repr, "y2", lg->y2.computed); + laststop->offset = 1; + sp_repr_set_css_double(laststop->getRepr(), "offset", 1); + + // iterate through midstops to set new offset values such that they won't move on canvas. + SPStop *stop = stopinfo->vector->getFirstStop(); + stop = stop->getNextStop(); + while (stop != laststop) { + stop->offset = stop->offset / offset; + sp_repr_set_css_double(stop->getRepr(), "offset", stop->offset); stop = stop->getNextStop(); - while ( stop != laststop ) { - stop->offset = stop->offset / offset; - sp_repr_set_css_double(stop->getRepr(), "offset", stop->offset); - stop = stop->getNextStop(); - } } - break; - case POINT_RG_CENTER: - { - SPStop *newfirst = stopinfo->spstop->getNextStop(); - if (newfirst) { - newfirst->offset = 0; - sp_repr_set_css_double(newfirst->getRepr(), "offset", 0); - } - stopinfo->vector->getRepr()->removeChild(stopinfo->spstop->getRepr()); + } break; + case POINT_RG_CENTER: { + SPStop *newfirst = stopinfo->spstop->getNextStop(); + if (newfirst) { + newfirst->offset = 0; + sp_repr_set_css_double(newfirst->getRepr(), "offset", 0); } - break; + stopinfo->vector->getRepr()->removeChild(stopinfo->spstop->getRepr()); + } break; case POINT_RG_R1: - case POINT_RG_R2: - { - stopinfo->vector->getRepr()->removeChild(stopinfo->spstop->getRepr()); - - SPRadialGradient *rg = SP_RADIALGRADIENT(stopinfo->gradient); - double oldradius = rg->r.computed; - SPStop *laststop = sp_last_stop(stopinfo->vector); - gdouble offset = laststop->offset; - double newradius = offset * oldradius; - rg->r.computed = newradius; - - Inkscape::XML::Node *repr = rg->getRepr(); - sp_repr_set_svg_double(repr, "r", rg->r.computed); - laststop->offset = 1; - sp_repr_set_css_double(laststop->getRepr(), "offset", 1); - - // iterate through midstops to set new offset values such that they won't move on canvas. - SPStop *stop = stopinfo->vector->getFirstStop(); + case POINT_RG_R2: { + stopinfo->vector->getRepr()->removeChild(stopinfo->spstop->getRepr()); + + SPRadialGradient *rg = SP_RADIALGRADIENT(stopinfo->gradient); + double oldradius = rg->r.computed; + SPStop *laststop = sp_last_stop(stopinfo->vector); + gdouble offset = laststop->offset; + double newradius = offset * oldradius; + rg->r.computed = newradius; + + Inkscape::XML::Node *repr = rg->getRepr(); + sp_repr_set_svg_double(repr, "r", rg->r.computed); + laststop->offset = 1; + sp_repr_set_css_double(laststop->getRepr(), "offset", 1); + + // iterate through midstops to set new offset values such that they won't move on canvas. + SPStop *stop = stopinfo->vector->getFirstStop(); + stop = stop->getNextStop(); + while (stop != laststop) { + stop->offset = stop->offset / offset; + sp_repr_set_css_double(stop->getRepr(), "offset", stop->offset); stop = stop->getNextStop(); - while ( stop != laststop ) { - stop->offset = stop->offset / offset; - sp_repr_set_css_double(stop->getRepr(), "offset", stop->offset); - stop = stop->getNextStop(); - } } - break; + } break; default: break; } - } - else - { // delete the gradient from the object. set fill to unset FIXME: set to fill of unselected node? - SPCSSAttr *css = sp_repr_css_attr_new (); + } else { // delete the gradient from the object. set fill to unset FIXME: set to fill of unselected node? + SPCSSAttr *css = sp_repr_css_attr_new(); // stopinfo->spstop is the selected stop Inkscape::XML::Node *unselectedrepr = stopinfo->vector->getRepr()->firstChild(); - if (unselectedrepr == stopinfo->spstop->getRepr() ) { + if (unselectedrepr == stopinfo->spstop->getRepr()) { unselectedrepr = unselectedrepr->next(); } if (unselectedrepr == nullptr) { if (stopinfo->draggable->fill_or_stroke == Inkscape::FOR_FILL) { - sp_repr_css_unset_property (css, "fill"); + sp_repr_css_unset_property(css, "fill"); } else { - sp_repr_css_unset_property (css, "stroke"); + sp_repr_css_unset_property(css, "stroke"); } } else { SPCSSAttr *stopcss = sp_repr_css_attr(unselectedrepr, "style"); if (stopinfo->draggable->fill_or_stroke == Inkscape::FOR_FILL) { - sp_repr_css_set_property(css, "fill", sp_repr_css_property(stopcss, "stop-color", "inkscape:unset")); + sp_repr_css_set_property(css, "fill", + sp_repr_css_property(stopcss, "stop-color", "inkscape:unset")); sp_repr_css_set_property(css, "fill-opacity", sp_repr_css_property(stopcss, "stop-opacity", "1")); } else { - sp_repr_css_set_property(css, "stroke", sp_repr_css_property(stopcss, "stop-color", "inkscape:unset")); + sp_repr_css_set_property(css, "stroke", + sp_repr_css_property(stopcss, "stop-color", "inkscape:unset")); sp_repr_css_set_property(css, "stroke-opacity", sp_repr_css_property(stopcss, "stop-opacity", "1")); } - sp_repr_css_attr_unref (stopcss); + sp_repr_css_attr_unref(stopcss); } sp_repr_css_change(stopinfo->draggable->item->getRepr(), css, "style"); - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); } delete stopinfo; } if (document) { - DocumentUndo::done( document, SP_VERB_CONTEXT_GRADIENT, _("Delete gradient stop(s)") ); + DocumentUndo::done(document, SP_VERB_CONTEXT_GRADIENT, _("Delete gradient stop(s)")); } } - /* Local Variables: mode:c++ diff --git a/src/gradient-drag.h b/src/gradient-drag.h index e50615941bd4a24c2596212e56e53719c3f5da4a..5f240faf08e313338e149d8ea8ad92588d54aec8 100644 --- a/src/gradient-drag.h +++ b/src/gradient-drag.h @@ -18,15 +18,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <2geom/point.h> #include -#include -#include -#include #include #include #include - -#include <2geom/point.h> +#include +#include +#include #include "object/sp-gradient.h" // TODO refactor enums to external .h file #include "object/sp-mesh-array.h" @@ -51,21 +50,24 @@ This class represents a single draggable point of a gradient. It remembers the i which has the gradient, whether it's fill or stroke, the point type (from the GrPointType enum), and the point number (needed if more than 2 stops are present). */ -struct GrDraggable { +struct GrDraggable +{ GrDraggable(SPItem *item, GrPointType point_type, guint point_i, Inkscape::PaintTarget fill_or_stroke); virtual ~GrDraggable(); SPItem *item; GrPointType point_type; - gint point_i; // the stop number of this point ( = 0 POINT_LG_BEGIN and POINT_RG_CENTER) + gint point_i; // the stop number of this point ( = 0 POINT_LG_BEGIN and POINT_RG_CENTER) Inkscape::PaintTarget fill_or_stroke; SPObject *getServer(); bool mayMerge(GrDraggable *da2); - inline int equals(GrDraggable *other) { - return ((item == other->item) && (point_type == other->point_type) && (point_i == other->point_i) && (fill_or_stroke == other->fill_or_stroke)); + inline int equals(GrDraggable *other) + { + return ((item == other->item) && (point_type == other->point_type) && (point_i == other->point_i) && + (fill_or_stroke == other->fill_or_stroke)); } }; @@ -76,7 +78,8 @@ This class holds together a visible on-canvas knot and a list of draggables that be moved when the knot moves. Normally there's one draggable in the list, but there may be more when draggers are snapped together. */ -struct GrDragger { +struct GrDragger +{ GrDragger(GrDrag *parent, Geom::Point p, GrDraggable *draggable); virtual ~GrDragger(); @@ -101,13 +104,15 @@ struct GrDragger { bool isSelected(); /* Given one GrDraggable, these all update other draggables belonging to same GrDragger */ - void moveThisToDraggable(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke, bool write_repr); - void moveOtherToDraggable(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke, bool write_repr); + void moveThisToDraggable(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke, + bool write_repr); + void moveOtherToDraggable(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke, + bool write_repr); void updateMidstopDependencies(GrDraggable *draggable, bool write_repr); void updateDependencies(bool write_repr); /* Update handles/tensors when mesh corner moved */ - void moveMeshHandles( Geom::Point pc_old, MeshNodeOperation op ); + void moveMeshHandles(Geom::Point pc_old, MeshNodeOperation op); /* Following are for highlighting mesh handles when corner node is selected. */ GrDragger *getMgCorner(); @@ -124,7 +129,7 @@ struct GrDragger { void fireDraggables(bool write_repr, bool scale_radial = false, bool merging_focus = false); protected: - void updateControlSizesOverload(SPKnot * knot); + void updateControlSizesOverload(SPKnot *knot); void updateControlSizes(); sigc::connection sizeUpdatedConn; @@ -141,23 +146,25 @@ struct SPCtrlLine; This is the root class of the gradient dragging machinery. It holds lists of GrDraggers and of lines (simple canvas items). It also remembers one of the draggers as selected. */ -class GrDrag { +class GrDrag +{ public: // FIXME: make more of this private! - GrDrag(SPDesktop *desktop); virtual ~GrDrag(); - bool isNonEmpty() {return !draggers.empty();} - bool hasSelection() {return !selected.empty();} - guint numSelected() {return selected.size();} - guint numDraggers() {return draggers.size();} + bool isNonEmpty() { return !draggers.empty(); } + bool hasSelection() { return !selected.empty(); } + guint numSelected() { return selected.size(); } + guint numDraggers() { return draggers.size(); } - guint singleSelectedDraggerNumDraggables() { - return (selected.empty()? 0 : (*(selected.begin()))->draggables.size() ); + guint singleSelectedDraggerNumDraggables() + { + return (selected.empty() ? 0 : (*(selected.begin()))->draggables.size()); } - guint singleSelectedDraggerSingleDraggableType() { - return (selected.empty() ? 0 : ((*(selected.begin()))->draggables[0]->point_type)); + guint singleSelectedDraggerSingleDraggableType() + { + return (selected.empty() ? 0 : ((*(selected.begin()))->draggables[0]->point_type)); } // especially the selection must be private, fix gradient-context to remove direct access to it @@ -167,7 +174,7 @@ public: // FIXME: make more of this private! void deselectAll(); void selectAll(); void selectByCoords(std::vector coords); - void selectByStop(SPStop *stop, bool add_to_selection = true, bool override = true); + void selectByStop(SPStop *stop, bool add_to_selection = true, bool override = true); void selectRect(Geom::Rect const &r); bool dropColor(SPItem *item, gchar const *c, Geom::Point p); @@ -184,7 +191,8 @@ public: // FIXME: make more of this private! GrDragger *getDraggerFor(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke); void grabKnot(GrDragger *dragger, gint x, gint y, guint32 etime); - void grabKnot(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke, gint x, gint y, guint32 etime); + void grabKnot(SPItem *item, GrPointType point_type, gint point_i, Inkscape::PaintTarget fill_or_stroke, gint x, + gint y, guint32 etime); bool local_change; @@ -218,20 +226,20 @@ public: // FIXME: make more of this private! private: void deselect_all(); - void addLine( SPItem *item, Geom::Point p1, Geom::Point p2, Inkscape::PaintTarget fill_or_stroke); - void addCurve(SPItem *item, Geom::Point p0, Geom::Point p1, Geom::Point p2, Geom::Point p3, - int corner0, int corner1, int handle0, int handle1, Inkscape::PaintTarget fill_or_stroke); + void addLine(SPItem *item, Geom::Point p1, Geom::Point p2, Inkscape::PaintTarget fill_or_stroke); + void addCurve(SPItem *item, Geom::Point p0, Geom::Point p1, Geom::Point p2, Geom::Point p3, int corner0, + int corner1, int handle0, int handle1, Inkscape::PaintTarget fill_or_stroke); GrDragger *addDragger(GrDraggable *draggable); void addDraggersRadial(SPRadialGradient *rg, SPItem *item, Inkscape::PaintTarget fill_or_stroke); void addDraggersLinear(SPLinearGradient *lg, SPItem *item, Inkscape::PaintTarget fill_or_stroke); - void addDraggersMesh( SPMeshGradient *mg, SPItem *item, Inkscape::PaintTarget fill_or_stroke); + void addDraggersMesh(SPMeshGradient *mg, SPItem *item, Inkscape::PaintTarget fill_or_stroke); void refreshDraggersMesh(SPMeshGradient *mg, SPItem *item, Inkscape::PaintTarget fill_or_stroke); - bool styleSet( const SPCSSAttr *css ); + bool styleSet(const SPCSSAttr *css); - Glib::ustring makeStopSafeColor( gchar const *str, bool &isNull ); + Glib::ustring makeStopSafeColor(gchar const *str, bool &isNull); Inkscape::Selection *selection; sigc::connection sel_changed_connection; diff --git a/src/graphlayout.cpp b/src/graphlayout.cpp index 82de08a3a483cc79f089b5098ad15f6a03e20e06..5e0e946404b44654294a5065caad882484f7f2b5 100644 --- a/src/graphlayout.cpp +++ b/src/graphlayout.cpp @@ -13,6 +13,9 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "graphlayout.h" + +#include <2geom/transforms.h> #include #include #include @@ -22,18 +25,12 @@ #include #include -#include <2geom/transforms.h> - -#include "conn-avoid-ref.h" -#include "desktop.h" -#include "graphlayout.h" -#include "inkscape.h" - #include "3rdparty/adaptagrams/libavoid/router.h" - #include "3rdparty/adaptagrams/libcola/cola.h" #include "3rdparty/adaptagrams/libcola/connected_components.h" - +#include "conn-avoid-ref.h" +#include "desktop.h" +#include "inkscape.h" #include "object/sp-item-transform.h" #include "object/sp-namedview.h" #include "object/sp-path.h" @@ -45,23 +42,26 @@ using namespace vpsc; /** * Returns true if item is a connector */ -bool isConnector(SPItem const * const item) { - SPPath * path = nullptr; +bool isConnector(SPItem const *const item) +{ + SPPath *path = nullptr; if (SP_IS_PATH(item)) { path = SP_PATH(item); } return path && path->connEndPair.isAutoRoutingConn(); } -struct CheckProgress: TestConvergence { - CheckProgress(double d, unsigned i, std::list & selected, Rectangles & rs, - std::map & nodelookup) +struct CheckProgress : TestConvergence +{ + CheckProgress(double d, unsigned i, std::list &selected, Rectangles &rs, + std::map &nodelookup) : TestConvergence(d, i) , selected(selected) , rs(rs) , nodelookup(nodelookup) {} - bool operator()(const double new_stress, std::valarray & X, std::valarray & Y) override { + bool operator()(const double new_stress, std::valarray &X, std::valarray &Y) override + { /* This is where, if we wanted to animate the layout, we would need to update * the positions of all objects and redraw the canvas and maybe sleep a bit cout << "stress="< & selected; - Rectangles & rs; - std::map & nodelookup; + std::list &selected; + Rectangles &rs; + std::map &nodelookup; }; /** * Scans the items list and places those items that are * not connectors in filtered */ -void filterConnectors(std::vector const & items, std::list & filtered) { - for (SPItem * item: items) { +void filterConnectors(std::vector const &items, std::list &filtered) +{ + for (SPItem *item : items) { if (!isConnector(item)) { filtered.push_back(item); } @@ -104,60 +105,64 @@ void filterConnectors(std::vector const & items, std::list & f * connectors between them, and uses graph layout techniques to find * a nice layout */ -void graphlayout(std::vector const & items) { - if (items.empty()) return; +void graphlayout(std::vector const &items) +{ + if (items.empty()) + return; - std::list selected; + std::list selected; filterConnectors(items, selected); - if (selected.size() < 2) return; + if (selected.size() < 2) + return; // add the connector spacing to the size of node bounding boxes // so that connectors can always be routed between shapes - SPDesktop * desktop = SP_ACTIVE_DESKTOP; + SPDesktop *desktop = SP_ACTIVE_DESKTOP; double spacing = 0; - if (desktop) spacing = desktop->namedview->connector_spacing + 0.1; + if (desktop) + spacing = desktop->namedview->connector_spacing + 0.1; std::map nodelookup; Rectangles rs; std::vector es; - for (SPItem * item: selected) { + for (SPItem *item : selected) { Geom::OptRect const item_box = item->desktopVisualBounds(); if (item_box) { Geom::Point ll(item_box->min()); Geom::Point ur(item_box->max()); nodelookup[item->getId()] = rs.size(); - rs.push_back(new Rectangle(ll[0] - spacing, ur[0] + spacing, - ll[1] - spacing, ur[1] + spacing)); + rs.push_back(new Rectangle(ll[0] - spacing, ur[0] + spacing, ll[1] - spacing, ur[1] + spacing)); } else { // I'm not actually sure if it's possible for something with a // NULL item-box to be attached to a connector in which case we // should never get to here... but if such a null box can occur it's // probably pretty safe to simply ignore - //fprintf(stderr, "NULL item_box found in graphlayout, ignoring!\n"); + // fprintf(stderr, "NULL item_box found in graphlayout, ignoring!\n"); } } - Inkscape::Preferences * prefs = Inkscape::Preferences::get(); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); CompoundConstraints constraints; double ideal_connector_length = prefs->getDouble("/tools/connector/length", 100.0); double directed_edge_height_modifier = 1.0; - bool directed = prefs->getBool("/tools/connector/directedlayout"); + bool directed = prefs->getBool("/tools/connector/directedlayout"); bool avoid_overlaps = prefs->getBool("/tools/connector/avoidoverlaplayout"); - for (SPItem * item: selected) { - std::map::iterator i_iter=nodelookup.find(item->getId()); - if (i_iter == nodelookup.end()) continue; + for (SPItem *item : selected) { + std::map::iterator i_iter = nodelookup.find(item->getId()); + if (i_iter == nodelookup.end()) + continue; unsigned u = i_iter->second; - std::vector nlist = item->getAvoidRef().getAttachedConnectors(Avoid::runningFrom); - std::list connectors; + std::vector nlist = item->getAvoidRef().getAttachedConnectors(Avoid::runningFrom); + std::list connectors; connectors.insert(connectors.end(), nlist.begin(), nlist.end()); - for (SPItem * conn: connectors) { - SPItem * iv; - SPItem * items[2]; + for (SPItem *conn : connectors) { + SPItem *iv; + SPItem *items[2]; assert(isConnector(conn)); SP_PATH(conn)->connEndPair.getAttachedItems(items); if (items[0] == item) { @@ -177,48 +182,50 @@ void graphlayout(std::vector const & items) { std::map::iterator v_pair = nodelookup.find(iv->getId()); if (v_pair != nodelookup.end()) { unsigned v = v_pair->second; - //cout << "Edge: (" << u <<","<style->marker_end.set) { if (directed && strcmp(conn->style->marker_end.value(), "none")) { - constraints.push_back(new SeparationConstraint(YDIM, v, u, - ideal_connector_length * directed_edge_height_modifier)); + constraints.push_back(new SeparationConstraint( + YDIM, v, u, ideal_connector_length * directed_edge_height_modifier)); } } } } } EdgeLengths elengths(es.size(), 1); - std::vector cs; + std::vector cs; connectedComponents(rs, es, cs); - for (Component * c: cs) { - if (c->edges.size() < 2) continue; + for (Component *c : cs) { + if (c->edges.size() < 2) + continue; CheckProgress test(0.0001, 100, selected, rs, nodelookup); ConstrainedMajorizationLayout alg(c->rects, c->edges, nullptr, ideal_connector_length, elengths, &test); - if (avoid_overlaps) alg.setAvoidOverlaps(); + if (avoid_overlaps) + alg.setAvoidOverlaps(); alg.setConstraints(&constraints); alg.run(); } separateComponents(cs); - for (SPItem * item: selected) { + for (SPItem *item : selected) { if (!isConnector(item)) { std::map::iterator i = nodelookup.find(item->getId()); if (i != nodelookup.end()) { - Rectangle * r = rs[i->second]; + Rectangle *r = rs[i->second]; Geom::OptRect item_box = item->desktopVisualBounds(); if (item_box) { Geom::Point const curr(item_box->midpoint()); - Geom::Point const dest(r->getCentreX(),r->getCentreY()); + Geom::Point const dest(r->getCentreX(), r->getCentreY()); item->move_rel(Geom::Translate(dest - curr)); } } } } - for (CompoundConstraint * c: constraints) { + for (CompoundConstraint *c : constraints) { delete c; } - for (Rectangle * r: rs) { + for (Rectangle *r : rs) { delete r; } } diff --git a/src/graphlayout.h b/src/graphlayout.h index 6c6b601f59c137bdaa2ec11632822a5b98e38481..978d934a612f75aee2871d6826bfade482100cb8 100644 --- a/src/graphlayout.h +++ b/src/graphlayout.h @@ -20,10 +20,10 @@ class SPItem; -void graphlayout(std::vector const &items); +void graphlayout(std::vector const &items); bool isConnector(SPItem const *const item); -void filterConnectors(std::vector const &items, std::list &filtered); +void filterConnectors(std::vector const &items, std::list &filtered); #endif // SEEN_GRAPHLAYOUT_H diff --git a/src/guide-snapper.cpp b/src/guide-snapper.cpp index 7278cd0e89970b0548a56fb36a0c7d3f454c1011..05c0e5baae4371d4585bf25c7271c0e3b144a3e3 100644 --- a/src/guide-snapper.cpp +++ b/src/guide-snapper.cpp @@ -13,14 +13,12 @@ */ #include "desktop.h" - #include "object/sp-guide.h" #include "object/sp-namedview.h" -Inkscape::GuideSnapper::GuideSnapper(SnapManager *sm, Geom::Coord const d) : LineSnapper(sm, d) -{ - -} +Inkscape::GuideSnapper::GuideSnapper(SnapManager *sm, Geom::Coord const d) + : LineSnapper(sm, d) +{} /** * \return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen pixels @@ -28,26 +26,27 @@ Inkscape::GuideSnapper::GuideSnapper(SnapManager *sm, Geom::Coord const d) : Lin Geom::Coord Inkscape::GuideSnapper::getSnapperTolerance() const { SPDesktop const *dt = _snapmanager->getDesktop(); - double const zoom = dt ? dt->current_zoom() : 1; + double const zoom = dt ? dt->current_zoom() : 1; return _snapmanager->snapprefs.getGuideTolerance() / zoom; } bool Inkscape::GuideSnapper::getSnapperAlwaysSnap() const { - return _snapmanager->snapprefs.getGuideTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp + return _snapmanager->snapprefs.getGuideTolerance() == + 10000; // TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp } -Inkscape::GuideSnapper::LineList Inkscape::GuideSnapper::_getSnapLines(Geom::Point const &/*p*/) const +Inkscape::GuideSnapper::LineList Inkscape::GuideSnapper::_getSnapLines(Geom::Point const & /*p*/) const { LineList s; - if ( nullptr == _snapmanager->getNamedView() || ThisSnapperMightSnap() == false) { + if (nullptr == _snapmanager->getNamedView() || ThisSnapperMightSnap() == false) { return s; } SPGuide const *guide_to_ignore = _snapmanager->getGuideToIgnore(); std::vector guides = _snapmanager->getNamedView()->guides; - for(auto guide : guides) { + for (auto guide : guides) { if (guide != guide_to_ignore) { s.push_back(std::pair(guide->getNormal(), guide->getPoint())); } @@ -65,30 +64,46 @@ bool Inkscape::GuideSnapper::ThisSnapperMightSnap() const return false; } - return (_snap_enabled && _snapmanager->snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_GUIDE) && _snapmanager->getNamedView()->showguides); + return (_snap_enabled && _snapmanager->snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_GUIDE) && + _snapmanager->getNamedView()->showguides); } -void Inkscape::GuideSnapper::_addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, Geom::Point const &normal_to_line, Geom::Point const &point_on_line) const +void Inkscape::GuideSnapper::_addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, Geom::Point const &normal_to_line, + Geom::Point const &point_on_line) const { - SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, source, source_num, Inkscape::SNAPTARGET_GUIDE, getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line); + SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, source, source_num, Inkscape::SNAPTARGET_GUIDE, + getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line); isr.guide_lines.push_back(dummy); } -void Inkscape::GuideSnapper::_addSnappedLinesOrigin(IntermSnapResults &isr, Geom::Point const &origin, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const +void Inkscape::GuideSnapper::_addSnappedLinesOrigin(IntermSnapResults &isr, Geom::Point const &origin, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, bool constrained_snap) const { - SnappedPoint dummy = SnappedPoint(origin, source, source_num, Inkscape::SNAPTARGET_GUIDE_ORIGIN, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); + SnappedPoint dummy = SnappedPoint(origin, source, source_num, Inkscape::SNAPTARGET_GUIDE_ORIGIN, snapped_distance, + getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); isr.points.push_back(dummy); } -void Inkscape::GuideSnapper::_addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const +void Inkscape::GuideSnapper::_addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, + bool constrained_snap) const { - SnappedPoint dummy = SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GUIDE_PERPENDICULAR, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); + SnappedPoint dummy = + SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GUIDE_PERPENDICULAR, snapped_distance, + getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); isr.points.push_back(dummy); } -void Inkscape::GuideSnapper::_addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const +void Inkscape::GuideSnapper::_addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, bool constrained_snap) const { - SnappedPoint dummy = SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GUIDE, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); + SnappedPoint dummy = SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GUIDE, snapped_distance, + getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true); isr.points.push_back(dummy); } diff --git a/src/guide-snapper.h b/src/guide-snapper.h index 94863fa4d7897fd5c80599f798a099a3ce767d68..95d7b464054f25c1ef447f2ad811cdfca8b9958d 100644 --- a/src/guide-snapper.h +++ b/src/guide-snapper.h @@ -16,8 +16,7 @@ class SPNamedView; -namespace Inkscape -{ +namespace Inkscape { /** * Snap to guides. @@ -28,23 +27,29 @@ public: GuideSnapper(SnapManager *sm, Geom::Coord const d); bool ThisSnapperMightSnap() const override; - Geom::Coord getSnapperTolerance() const override; //returns the tolerance of the snapper in screen pixels (i.e. independent of zoom) - bool getSnapperAlwaysSnap() const override; //if true, then the snapper will always snap, regardless of its tolerance + Geom::Coord getSnapperTolerance() const override; // returns the tolerance of the snapper in screen pixels (i.e. + // independent of zoom) + bool getSnapperAlwaysSnap() const override; // if true, then the snapper will always snap, regardless of its + // tolerance private: LineList _getSnapLines(Geom::Point const &p) const override; - void _addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, Geom::Point const &normal_to_line, Geom::Point const &point_on_line) const override; - void _addSnappedLinesOrigin(IntermSnapResults &isr, Geom::Point const &origin, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const override; - void _addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const override; - void _addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const override; + void _addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, Geom::Point const &normal_to_line, + Geom::Point const &point_on_line) const override; + void _addSnappedLinesOrigin(IntermSnapResults &isr, Geom::Point const &origin, Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, bool constrained_snap) const override; + void _addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, bool constrained_snap) const override; + void _addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, bool constrained_snap) const override; }; -} +} // namespace Inkscape #endif - - /* Local Variables: mode:c++ diff --git a/src/help.cpp b/src/help.cpp index 7123127b817803ddf9b7e614d786f538489f0a3f..282ffcbdd371e98f5879811e4a9b3d04d8e2da51 100644 --- a/src/help.cpp +++ b/src/help.cpp @@ -19,10 +19,9 @@ #include #include "inkscape-application.h" - #include "io/resource.h" -#include "ui/interface.h" // sp_ui_error_dialog #include "ui/dialog/about.h" +#include "ui/interface.h" // sp_ui_error_dialog using namespace Inkscape::IO::Resource; @@ -55,7 +54,8 @@ void sp_help_open_tutorial(Glib::ustring name) filename = Inkscape::IO::Resource::get_filename(Inkscape::IO::Resource::TUTORIALS, filename.c_str(), true); if (!filename.empty()) { Glib::RefPtr file = Gio::File::create_for_path(filename); - ConcreteInkscapeApplication* app = &(ConcreteInkscapeApplication::get_instance()); + ConcreteInkscapeApplication *app = + &(ConcreteInkscapeApplication::get_instance()); app->create_window(file, false, false); } else { // TRANSLATORS: Please don't translate link unless the page exists in your language. Add your language code to diff --git a/src/helper-fns.h b/src/helper-fns.h index 27dfc7315151c968b4eba75d80b170123bb0a164..6afa4a8075a8e6d7dee57befe01704a70eb597ad 100644 --- a/src/helper-fns.h +++ b/src/helper-fns.h @@ -12,8 +12,8 @@ */ #include -#include #include +#include // calling helperfns_read_number(string, false), it's not obvious, what // that false stands for. helperfns_read_number(string, HELPERFNS_NO_WARNING) @@ -29,7 +29,8 @@ * this function. This can be useful in places, where the input type * is not known beforehand. For example, see sp_feColorMatrix_set in * sp-fecolormatrix.cpp */ -inline double helperfns_read_number(gchar const *value, bool warning = true) { +inline double helperfns_read_number(gchar const *value, bool warning = true) +{ if (!value) { g_warning("Called helperfns_read_number with value==null_ptr, this can lead to unexpected behaviour."); return 0; @@ -47,14 +48,18 @@ inline double helperfns_read_number(gchar const *value, bool warning = true) { return ret; } -inline bool helperfns_read_bool(gchar const *value, bool default_value){ - if (!value) return default_value; - switch(value[0]){ +inline bool helperfns_read_bool(gchar const *value, bool default_value) +{ + if (!value) + return default_value; + switch (value[0]) { case 't': - if (strncmp(value, "true", 4) == 0) return true; + if (strncmp(value, "true", 4) == 0) + return true; break; case 'f': - if (strncmp(value, "false", 5) == 0) return false; + if (strncmp(value, "false", 5) == 0) + return false; break; } return default_value; @@ -66,28 +71,30 @@ inline bool helperfns_read_bool(gchar const *value, bool default_value){ * @param value ascii representation of the number * @return the vector of the converted numbers */ -inline std::vector helperfns_read_vector(const gchar* value){ - std::vector v; - - gchar const* beg = value; - while(isspace(*beg) || (*beg == ',')) beg++; - while(*beg) - { - char *end; - double ret = g_ascii_strtod(beg, &end); - if (end==beg){ - g_warning("helper-fns::helperfns_read_vector() Unable to convert \"%s\" to number", beg); - // We could leave this out, too. If strtod can't convert - // anything, it will return zero. - // ret = 0; - break; - } - v.push_back(ret); +inline std::vector helperfns_read_vector(const gchar *value) +{ + std::vector v; - beg = end; - while(isspace(*beg) || (*beg == ',')) beg++; + gchar const *beg = value; + while (isspace(*beg) || (*beg == ',')) + beg++; + while (*beg) { + char *end; + double ret = g_ascii_strtod(beg, &end); + if (end == beg) { + g_warning("helper-fns::helperfns_read_vector() Unable to convert \"%s\" to number", beg); + // We could leave this out, too. If strtod can't convert + // anything, it will return zero. + // ret = 0; + break; } - return v; + v.push_back(ret); + + beg = end; + while (isspace(*beg) || (*beg == ',')) + beg++; + } + return v; } #endif /* !SEEN_HELPER_FNS_H */ diff --git a/src/helper/action-context.cpp b/src/helper/action-context.cpp index 36b6914d6fef5eb0b137f7d88475b108fcc0350f..2e8ff78bdc8473f68eeb2ea8b9b930044ee5615f 100644 --- a/src/helper/action-context.cpp +++ b/src/helper/action-context.cpp @@ -10,29 +10,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "helper/action-context.h" + #include "desktop.h" #include "document.h" #include "layer-model.h" #include "selection.h" -#include "helper/action-context.h" namespace Inkscape { ActionContext::ActionContext() - : _selection(nullptr) - , _view(nullptr) -{ -} + : _selection(nullptr) + , _view(nullptr) +{} ActionContext::ActionContext(Selection *selection) - : _selection(selection) - , _view(nullptr) -{ -} + : _selection(selection) + , _view(nullptr) +{} ActionContext::ActionContext(UI::View::View *view) - : _selection(nullptr) - , _view(view) + : _selection(nullptr) + , _view(view) { SPDesktop *desktop = static_cast(view); if (desktop) { diff --git a/src/helper/action-context.h b/src/helper/action-context.h index d3468ea3ee48e51a574311bf7d86264bdc13f9c4..2d354cc655fc3a64abbb84dc0d514da977942761 100644 --- a/src/helper/action-context.h +++ b/src/helper/action-context.h @@ -38,13 +38,15 @@ class View; always seemed to cast straight to an SPDesktop* - so shouldn't we actually be storing an SPDesktop*? Is there a case where a non-SPDesktop UI::View::View is used by the actions? YES: Command-line wihtout GUI. - + ActionContext is designed to be copyable, so it may be used with stack storage if required. */ -class ActionContext { +class ActionContext +{ // NB: Only one of these is typically set - selection model if in console mode, view if in GUI mode - Selection *_selection; /**< The selection model to which this action applies, if running in console mode. May be NULL. */ - UI::View::View *_view; /**< The view to which this action applies. May be NULL (e.g. if running in console mode). */ + Selection *_selection; /**< The selection model to which this action applies, if running in console mode. May be + NULL. */ + UI::View::View *_view; /**< The view to which this action applies. May be NULL (e.g. if running in console mode). */ public: /** Construct without any document or GUI */ @@ -53,7 +55,7 @@ public: /** Construct an action context for when the app is being run without any GUI, i.e. in console mode */ ActionContext(Selection *selection); - + /** Construct an action context for when the app is being run in GUI mode */ ActionContext(UI::View::View *view); @@ -61,7 +63,7 @@ public: function to getView()->doc() if the action doesn't require a GUI. */ SPDocument *getDocument() const; - /** Get the selection for the action context. May be NULL. Should be + /** Get the selection for the action context. May be NULL. Should be non-NULL if getDocument() is non-NULL. */ Selection *getSelection() const; diff --git a/src/helper/action.cpp b/src/helper/action.cpp index 6b09a91405da6a828aded7136f750c3ffb87a809..702463abb47deec8a182ce8ca9d599b7056a7835 100644 --- a/src/helper/action.cpp +++ b/src/helper/action.cpp @@ -11,45 +11,43 @@ */ #include "helper/action.h" -#include "ui/icon-loader.h" #include +#include "debug/event-tracker.h" #include "debug/logger.h" -#include "debug/timestamp.h" #include "debug/simple-event.h" -#include "debug/event-tracker.h" -#include "ui/view/view.h" +#include "debug/timestamp.h" #include "desktop.h" #include "document.h" +#include "ui/icon-loader.h" +#include "ui/view/view.h" #include "verbs.h" -static void sp_action_finalize (GObject *object); +static void sp_action_finalize(GObject *object); G_DEFINE_TYPE(SPAction, sp_action, G_TYPE_OBJECT); /** * SPAction vtable initialization. */ -static void -sp_action_class_init (SPActionClass *klass) +static void sp_action_class_init(SPActionClass *klass) { - GObjectClass *object_class = (GObjectClass *) klass; + GObjectClass *object_class = (GObjectClass *)klass; object_class->finalize = sp_action_finalize; } /** * Callback for SPAction object initialization. */ -static void -sp_action_init (SPAction *action) +static void sp_action_init(SPAction *action) { action->sensitive = 0; action->active = 0; action->context = Inkscape::ActionContext(); action->id = action->name = action->tip = nullptr; action->image = nullptr; - + new (&action->signal_perform) sigc::signal(); new (&action->signal_set_sensitive) sigc::signal(); new (&action->signal_set_active) sigc::signal(); @@ -59,43 +57,37 @@ sp_action_init (SPAction *action) /** * Called before SPAction object destruction. */ -static void -sp_action_finalize (GObject *object) +static void sp_action_finalize(GObject *object) { SPAction *action = SP_ACTION(object); - g_free (action->image); - g_free (action->tip); - g_free (action->name); - g_free (action->id); + g_free(action->image); + g_free(action->tip); + g_free(action->name); + g_free(action->id); action->signal_perform.~signal(); action->signal_set_sensitive.~signal(); action->signal_set_active.~signal(); action->signal_set_name.~signal(); - G_OBJECT_CLASS(sp_action_parent_class)->finalize (object); + G_OBJECT_CLASS(sp_action_parent_class)->finalize(object); } /** * Create new SPAction object and set its properties. */ -SPAction * -sp_action_new(Inkscape::ActionContext const &context, - const gchar *id, - const gchar *name, - const gchar *tip, - const gchar *image, - Inkscape::Verb * verb) +SPAction *sp_action_new(Inkscape::ActionContext const &context, const gchar *id, const gchar *name, const gchar *tip, + const gchar *image, Inkscape::Verb *verb) { SPAction *action = (SPAction *)g_object_new(SP_TYPE_ACTION, nullptr); action->context = context; action->sensitive = TRUE; - action->id = g_strdup (id); - action->name = g_strdup (name); - action->tip = g_strdup (tip); - action->image = g_strdup (image); + action->id = g_strdup(id); + action->name = g_strdup(name); + action->tip = g_strdup(tip); + action->image = g_strdup(image); action->verb = verb; return action; @@ -103,16 +95,17 @@ sp_action_new(Inkscape::ActionContext const &context, namespace { -using Inkscape::Debug::SimpleEvent; using Inkscape::Debug::Event; +using Inkscape::Debug::SimpleEvent; using Inkscape::Debug::timestamp; typedef SimpleEvent ActionEventBase; -class ActionEvent : public ActionEventBase { +class ActionEvent : public ActionEventBase +{ public: ActionEvent(SPAction const *action) - : ActionEventBase("action") + : ActionEventBase("action") { _addProperty("timestamp", timestamp()); SPDocument *document = action->context.getDocument(); @@ -123,7 +116,7 @@ public: } }; -} +} // namespace /** * Executes an action. @@ -132,8 +125,8 @@ public: */ void sp_action_perform(SPAction *action, void * /*data*/) { - g_return_if_fail (action != nullptr); - g_return_if_fail (SP_IS_ACTION (action)); + g_return_if_fail(action != nullptr); + g_return_if_fail(SP_IS_ACTION(action)); Inkscape::Debug::EventTracker tracker(action); action->signal_perform.emit(); @@ -142,11 +135,10 @@ void sp_action_perform(SPAction *action, void * /*data*/) /** * Change activation in all actions that can be taken with the action. */ -void -sp_action_set_active (SPAction *action, unsigned int active) +void sp_action_set_active(SPAction *action, unsigned int active) { - g_return_if_fail (action != nullptr); - g_return_if_fail (SP_IS_ACTION (action)); + g_return_if_fail(action != nullptr); + g_return_if_fail(SP_IS_ACTION(action)); action->signal_set_active.emit(active); } @@ -154,20 +146,18 @@ sp_action_set_active (SPAction *action, unsigned int active) /** * Change sensitivity in all actions that can be taken with the action. */ -void -sp_action_set_sensitive (SPAction *action, unsigned int sensitive) +void sp_action_set_sensitive(SPAction *action, unsigned int sensitive) { - g_return_if_fail (action != nullptr); - g_return_if_fail (SP_IS_ACTION (action)); + g_return_if_fail(action != nullptr); + g_return_if_fail(SP_IS_ACTION(action)); action->signal_set_sensitive.emit(sensitive); } -void -sp_action_set_name (SPAction *action, Glib::ustring const &name) +void sp_action_set_name(SPAction *action, Glib::ustring const &name) { - g_return_if_fail (action != nullptr); - g_return_if_fail (SP_IS_ACTION (action)); + g_return_if_fail(action != nullptr); + g_return_if_fail(SP_IS_ACTION(action)); g_free(action->name); action->name = g_strdup(name.data()); @@ -177,45 +167,41 @@ sp_action_set_name (SPAction *action, Glib::ustring const &name) /** * Return Document associated with the action. */ -SPDocument * -sp_action_get_document (SPAction *action) +SPDocument *sp_action_get_document(SPAction *action) { - g_return_val_if_fail (SP_IS_ACTION (action), NULL); + g_return_val_if_fail(SP_IS_ACTION(action), NULL); return action->context.getDocument(); } /** * Return Selection associated with the action */ -Inkscape::Selection * -sp_action_get_selection (SPAction *action) +Inkscape::Selection *sp_action_get_selection(SPAction *action) { - g_return_val_if_fail (SP_IS_ACTION (action), NULL); + g_return_val_if_fail(SP_IS_ACTION(action), NULL); return action->context.getSelection(); } /** * Return View associated with the action, if any. */ -Inkscape::UI::View::View * -sp_action_get_view (SPAction *action) +Inkscape::UI::View::View *sp_action_get_view(SPAction *action) { - g_return_val_if_fail (SP_IS_ACTION (action), NULL); + g_return_val_if_fail(SP_IS_ACTION(action), NULL); return action->context.getView(); } /** * Return Desktop associated with the action, if any. */ -SPDesktop * -sp_action_get_desktop (SPAction *action) +SPDesktop *sp_action_get_desktop(SPAction *action) { - // TODO: this slightly horrible storage of a UI::View::View*, and + // TODO: this slightly horrible storage of a UI::View::View*, and // casting to an SPDesktop*, is only done because that's what was // already the norm in the Inkscape codebase. This seems wrong. Surely // we should store an SPDesktop* in the first place? Is there a case // of actions being carried out on a View that is not an SPDesktop? - return static_cast(sp_action_get_view(action)); + return static_cast(sp_action_get_view(action)); } /** @@ -227,9 +213,7 @@ sp_action_get_desktop (SPAction *action) * hooking up the "clicked" signal. This should probably wait until we've * migrated to Gtk::Application */ -Gtk::ToolButton * -SPAction::create_toolbutton_for_verb(unsigned int verb_code, - Inkscape::ActionContext &context) +Gtk::ToolButton *SPAction::create_toolbutton_for_verb(unsigned int verb_code, Inkscape::ActionContext &context) { // Get display properties for the verb auto verb = Inkscape::Verb::get(verb_code); @@ -243,8 +227,7 @@ SPAction::create_toolbutton_for_verb(unsigned int verb_code, button->set_tooltip_text(verb->get_tip()); // Hook up signal handler - auto button_clicked_cb = sigc::bind(sigc::ptr_fun(&sp_action_perform), - target_action, nullptr); + auto button_clicked_cb = sigc::bind(sigc::ptr_fun(&sp_action_perform), target_action, nullptr); button->signal_clicked().connect(button_clicked_cb); return button; diff --git a/src/helper/action.h b/src/helper/action.h index 1f871dbaae33c1e87eaad53ce03c7c09c4d54421..05df88ca83fef15306626d36142de74e3b679caa 100644 --- a/src/helper/action.h +++ b/src/helper/action.h @@ -14,10 +14,10 @@ #define SEEN_INKSCAPE_SP_ACTION_H #include +#include +#include #include "helper/action-context.h" -#include -#include #define SP_TYPE_ACTION (sp_action_get_type()) #define SP_ACTION(o) (G_TYPE_CHECK_INSTANCE_CAST((o), SP_TYPE_ACTION, SPAction)) @@ -40,43 +40,40 @@ namespace View { class View; } // namespace View } // namespace UI -} +} // namespace Inkscape /** All the data that is required to be an action. This structure identifies the action and has the data to - create menus and toolbars for the action */ -struct SPAction : public GObject { - unsigned sensitive : 1; /**< Value to track whether the action is sensitive */ - unsigned active : 1; /**< Value to track whether the action is active */ - Inkscape::ActionContext context; /**< The context (doc/view) to which this action is attached */ - gchar *id; /**< The identifier for the action */ - gchar *name; /**< Full text name of the action */ - gchar *tip; /**< A tooltip to describe the action */ - gchar *image; /**< An image to visually identify the action */ - Inkscape::Verb *verb; /**< The verb that produced this action */ - + create menus and toolbars for the action */ +struct SPAction : public GObject +{ + unsigned sensitive : 1; /**< Value to track whether the action is sensitive */ + unsigned active : 1; /**< Value to track whether the action is active */ + Inkscape::ActionContext context; /**< The context (doc/view) to which this action is attached */ + gchar *id; /**< The identifier for the action */ + gchar *name; /**< Full text name of the action */ + gchar *tip; /**< A tooltip to describe the action */ + gchar *image; /**< An image to visually identify the action */ + Inkscape::Verb *verb; /**< The verb that produced this action */ + sigc::signal signal_perform; sigc::signal signal_set_sensitive; sigc::signal signal_set_active; sigc::signal signal_set_name; - static Gtk::ToolButton * create_toolbutton_for_verb(unsigned int verb_code, - Inkscape::ActionContext &context); + static Gtk::ToolButton *create_toolbutton_for_verb(unsigned int verb_code, Inkscape::ActionContext &context); }; /** The action class is the same as its parent. */ -struct SPActionClass { +struct SPActionClass +{ GObjectClass parent_class; /**< Parent Class */ }; GType sp_action_get_type(); -SPAction *sp_action_new(Inkscape::ActionContext const &context, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image, - Inkscape::Verb *verb); +SPAction *sp_action_new(Inkscape::ActionContext const &context, gchar const *id, gchar const *name, gchar const *tip, + gchar const *image, Inkscape::Verb *verb); void sp_action_perform(SPAction *action, void *data); void sp_action_set_active(SPAction *action, unsigned active); diff --git a/src/helper/geom-curves.h b/src/helper/geom-curves.h index 08403e2ae14f18385058b2c9fed4af1dd1c3225c..1bf92d38c71533b20eef66625db223674edce5e9 100644 --- a/src/helper/geom-curves.h +++ b/src/helper/geom-curves.h @@ -15,14 +15,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <2geom/line.h> #include <2geom/bezier-curve.h> +#include <2geom/line.h> /// \todo un-inline this function -inline bool is_straight_curve(Geom::Curve const & c) +inline bool is_straight_curve(Geom::Curve const &c) { - if( dynamic_cast(&c) ) - { + if (dynamic_cast(&c)) { return true; } // the curve can be a quad/cubic bezier, but could still be a perfect straight line @@ -41,7 +40,7 @@ inline bool is_straight_curve(Geom::Curve const & c) return false; } -#endif // INKSCAPE_HELPER_GEOM_CURVES_H +#endif // INKSCAPE_HELPER_GEOM_CURVES_H /* Local Variables: diff --git a/src/helper/geom-nodetype.cpp b/src/helper/geom-nodetype.cpp index e04b08dbd0f5c8be7262f9a58c64ab059fe86103..9f1ffc944c782437cac69165e4064f33e6d0cdd6 100644 --- a/src/helper/geom-nodetype.cpp +++ b/src/helper/geom-nodetype.cpp @@ -19,13 +19,13 @@ namespace Geom { /* * NOTE: THIS METHOD NEVER RETURNS "NODE_SYMM". * Returns the nodetype between c_incoming and c_outgoing. Location of the node is - * at c_incoming.pointAt(1) == c_outgoing.pointAt(0). If these two are unequal, + * at c_incoming.pointAt(1) == c_outgoing.pointAt(0). If these two are unequal, * the returned type is NODE_NONE. * Comparison is based on the unitTangent, does not work for NODE_SYMM! */ NodeType get_nodetype(Curve const &c_incoming, Curve const &c_outgoing) { - if ( !are_near(c_incoming.pointAt(1), c_outgoing.pointAt(0)) ) + if (!are_near(c_incoming.pointAt(1), c_outgoing.pointAt(0))) return NODE_NONE; Geom::Curve *crv = c_incoming.reverse(); @@ -35,10 +35,7 @@ NodeType get_nodetype(Curve const &c_incoming, Curve const &c_outgoing) double this_angle_L2 = Geom::L2(deriv_1); double next_angle_L2 = Geom::L2(deriv_2); double both_angles_L2 = Geom::L2(deriv_1 + deriv_2); - if ( (this_angle_L2 > 1e-6) && - (next_angle_L2 > 1e-6) && - ((this_angle_L2 + next_angle_L2 - both_angles_L2) < 1e-3) ) - { + if ((this_angle_L2 > 1e-6) && (next_angle_L2 > 1e-6) && ((this_angle_L2 + next_angle_L2 - both_angles_L2) < 1e-3)) { return NODE_SMOOTH; } diff --git a/src/helper/geom-nodetype.h b/src/helper/geom-nodetype.h index d7d4d4c0232a0a8266b3ee4fad9120b2d18fb14b..6f6bb57c46bceacd93f17535c39e443aa0cd12db 100644 --- a/src/helper/geom-nodetype.h +++ b/src/helper/geom-nodetype.h @@ -26,24 +26,23 @@ namespace Geom { * derivate is connected. (Thus 2 means that the node is continuous * to the second derivative, i.e. has matching endpoints and tangents) */ -enum NodeType { -/** Discontinuous node, usually either start or endpoint of a path */ +enum NodeType +{ + /** Discontinuous node, usually either start or endpoint of a path */ NODE_NONE, -/** This node continuously joins two segments, but the unit tangent is discontinuous.*/ + /** This node continuously joins two segments, but the unit tangent is discontinuous.*/ NODE_CUSP, -/** This node continuously joins two segments, with continuous *unit* tangent. */ + /** This node continuously joins two segments, with continuous *unit* tangent. */ NODE_SMOOTH, -/** This node is symmetric. I.e. continuously joins two segments with continuous derivative */ + /** This node is symmetric. I.e. continuously joins two segments with continuous derivative */ NODE_SYMM }; - NodeType get_nodetype(Curve const &c_incoming, Curve const &c_outgoing); - } // namespace Geom -#endif // INKSCAPE_HELPER_GEOM_NODETYPE_H +#endif // INKSCAPE_HELPER_GEOM_NODETYPE_H /* Local Variables: diff --git a/src/helper/geom-pathstroke.cpp b/src/helper/geom-pathstroke.cpp index 181c45715a38a4b0bcc2b68b3c49df7018abd049..714f8bb2c809279ca291b630a844c284cf33a63f 100644 --- a/src/helper/geom-pathstroke.cpp +++ b/src/helper/geom-pathstroke.cpp @@ -9,71 +9,69 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "helper/geom-pathstroke.h" + +#include <2geom/circle.h> +#include <2geom/path-intersection.h> #include <2geom/path-sink.h> #include <2geom/sbasis-to-bezier.h> // cubicbezierpath_from_sbasis -#include <2geom/path-intersection.h> -#include <2geom/circle.h> - -#include "helper/geom-pathstroke.h" +#include namespace Geom { static Point intersection_point(Point origin_a, Point vector_a, Point origin_b, Point vector_b) { Coord denom = cross(vector_a, vector_b); - if (!are_near(denom,0.)) { + if (!are_near(denom, 0.)) { Coord t = (cross(vector_b, origin_a) + cross(origin_b, vector_b)) / denom; - return origin_a + vector_a*t; + return origin_a + vector_a * t; } return Point(infinity(), infinity()); } /** -* Find circle that touches inside of the curve, with radius matching the curvature, at time value \c t. -* Because this method internally uses unitTangentAt, t should be smaller than 1.0 (see unitTangentAt). -*/ -static Circle touching_circle( D2 const &curve, double t, double tol=0.01 ) + * Find circle that touches inside of the curve, with radius matching the curvature, at time value \c t. + * Because this method internally uses unitTangentAt, t should be smaller than 1.0 (see unitTangentAt). + */ +static Circle touching_circle(D2 const &curve, double t, double tol = 0.01) { - D2 dM=derivative(curve); - if ( are_near(L2sq(dM(t)), tol) ) { - dM=derivative(dM); + D2 dM = derivative(curve); + if (are_near(L2sq(dM(t)), tol)) { + dM = derivative(dM); } - if ( are_near(L2sq(dM(t)), tol) ) { // try second time - dM=derivative(dM); + if (are_near(L2sq(dM(t)), tol)) { // try second time + dM = derivative(dM); } - Piecewise > unitv = unitVector(dM,tol); - Piecewise dMlength = dot(Piecewise >(dM),unitv); - Piecewise k = cross(derivative(unitv),unitv); - k = divide(k,dMlength,tol,3); + Piecewise> unitv = unitVector(dM, tol); + Piecewise dMlength = dot(Piecewise>(dM), unitv); + Piecewise k = cross(derivative(unitv), unitv); + k = divide(k, dMlength, tol, 3); double curv = k(t); // note that this value is signed Geom::Point normal = unitTangentAt(curve, t).cw(); - double radius = 1/curv; - Geom::Point center = curve(t) + radius*normal; + double radius = 1 / curv; + Geom::Point center = curve(t) + radius * normal; return Geom::Circle(center, fabs(radius)); } - // Area of triangle given three corner points -static double area( Geom::Point a, Geom::Point b, Geom::Point c ) { - +static double area(Geom::Point a, Geom::Point b, Geom::Point c) +{ using Geom::X; using Geom::Y; - return( 0.5 * fabs( ( a[X]*(b[Y]-c[Y]) + b[X]*(c[Y]-a[Y]) + c[X]*(a[Y]-b[Y]) ) ) ); + return (0.5 * fabs((a[X] * (b[Y] - c[Y]) + b[X] * (c[Y] - a[Y]) + c[X] * (a[Y] - b[Y])))); } // Alternative touching circle routine directly using Beziers. Works only at end points. -static Circle touching_circle( CubicBezier const &curve, bool start ) { - +static Circle touching_circle(CubicBezier const &curve, bool start) +{ double k = 0; Geom::Point p; Geom::Point normal; - if ( start ) { - double distance = Geom::distance( curve[1], curve[0] ); - k = 4.0/3.0 * area( curve[0], curve[1], curve[2] ) / - (distance * distance * distance); - if( Geom::cross(curve[0]-curve[1], curve[1]-curve[2]) < 0 ) { + if (start) { + double distance = Geom::distance(curve[1], curve[0]); + k = 4.0 / 3.0 * area(curve[0], curve[1], curve[2]) / (distance * distance * distance); + if (Geom::cross(curve[0] - curve[1], curve[1] - curve[2]) < 0) { k = -k; } p = curve[0]; @@ -81,10 +79,9 @@ static Circle touching_circle( CubicBezier const &curve, bool start ) { normal.normalize(); // std::cout << "Start k: " << k << " d: " << distance << " normal: " << normal << std::endl; } else { - double distance = Geom::distance( curve[3], curve[2] ); - k = 4.0/3.0 * area( curve[1], curve[2], curve[3] ) / - (distance * distance * distance); - if( Geom::cross(curve[1]-curve[2], curve[2]-curve[3]) < 0 ) { + double distance = Geom::distance(curve[3], curve[2]); + k = 4.0 / 3.0 * area(curve[1], curve[2], curve[3]) / (distance * distance * distance); + if (Geom::cross(curve[1] - curve[2], curve[2] - curve[3]) < 0) { k = -k; } p = curve[3]; @@ -92,30 +89,37 @@ static Circle touching_circle( CubicBezier const &curve, bool start ) { normal.normalize(); // std::cout << "End k: " << k << " d: " << distance << " normal: " << normal << std::endl; } - if( k == 0 ) { - return Geom::Circle( Geom::Point(0,std::numeric_limits::infinity()), - std::numeric_limits::infinity()); + if (k == 0) { + return Geom::Circle(Geom::Point(0, std::numeric_limits::infinity()), + std::numeric_limits::infinity()); } else { - double radius = 1/k; + double radius = 1 / k; Geom::Point center = p + normal * radius; - return Geom::Circle( center, fabs(radius) ); + return Geom::Circle(center, fabs(radius)); } } -} +} // namespace Geom namespace { // Internal data structure -struct join_data { - join_data(Geom::Path &_res, Geom::Path const&_outgoing, Geom::Point _in_tang, Geom::Point _out_tang, double _miter, double _width) - : res(_res), outgoing(_outgoing), in_tang(_in_tang), out_tang(_out_tang), miter(_miter), width(_width) {}; +struct join_data +{ + join_data(Geom::Path &_res, Geom::Path const &_outgoing, Geom::Point _in_tang, Geom::Point _out_tang, double _miter, + double _width) + : res(_res) + , outgoing(_outgoing) + , in_tang(_in_tang) + , out_tang(_out_tang) + , miter(_miter) + , width(_width){}; // contains the current path that is being built on Geom::Path &res; // contains the next curve to append - Geom::Path const& outgoing; + Geom::Path const &outgoing; // input tangents Geom::Point in_tang; @@ -146,8 +150,8 @@ void miter_join_internal(join_data jd, bool clip) { using namespace Geom; - Curve const& incoming = jd.res.back(); - Curve const& outgoing = jd.outgoing.front(); + Curve const &incoming = jd.res.back(); + Curve const &outgoing = jd.outgoing.front(); Path &res = jd.res; double width = jd.width, miter = jd.miter; @@ -160,10 +164,10 @@ void miter_join_internal(join_data jd, bool clip) if (p.isFinite()) { // check size of miter - Point point_on_path = incoming.finalPoint() + rot90(tang1)*width; + Point point_on_path = incoming.finalPoint() + rot90(tang1) * width; // SVG defines miter length as distance between inner intersection and outer intersection, // which is twice the distance from p to point_on_path but width is half stroke width. - satisfied = distance(p, point_on_path) <= miter * width; + satisfied = distance(p, point_on_path) <= miter * width; if (satisfied) { // miter OK, check to see if we can do a relocation if (inc_ls) { @@ -206,36 +210,44 @@ void miter_join_internal(join_data jd, bool clip) res.insert(res.end(), ++jd.outgoing.begin(), jd.outgoing.end()); } -void miter_join(join_data jd) { miter_join_internal(jd, false); } -void miter_clip_join(join_data jd) { miter_join_internal(jd, true); } +void miter_join(join_data jd) +{ + miter_join_internal(jd, false); +} +void miter_clip_join(join_data jd) +{ + miter_join_internal(jd, true); +} Geom::Point pick_solution(std::vector points, Geom::Point tang2, Geom::Point endPt) { assert(points.size() == 2); Geom::Point sol; - if ( dot(tang2, points[0].point() - endPt) > 0 ) { + if (dot(tang2, points[0].point() - endPt) > 0) { // points[0] is bad, choose points[1] sol = points[1]; - } else if ( dot(tang2, points[1].point() - endPt) > 0 ) { // points[0] could be good, now check points[1] + } else if (dot(tang2, points[1].point() - endPt) > 0) { // points[0] could be good, now check points[1] // points[1] is bad, choose points[0] sol = points[0]; } else { // both points are good, choose nearest - sol = ( distanceSq(endPt, points[0].point()) < distanceSq(endPt, points[1].point()) ) - ? points[0].point() : points[1].point(); + sol = (distanceSq(endPt, points[0].point()) < distanceSq(endPt, points[1].point())) ? points[0].point() + : points[1].point(); } return sol; } // Arcs line join. If two circles don't intersect, expand inner circle. -Geom::Point expand_circle( Geom::Circle &inner_circle, Geom::Circle const &outer_circle, Geom::Point const &start_pt, Geom::Point const &start_tangent ) { +Geom::Point expand_circle(Geom::Circle &inner_circle, Geom::Circle const &outer_circle, Geom::Point const &start_pt, + Geom::Point const &start_tangent) +{ // std::cout << "expand_circle:" << std::endl; - // std::cout << " outer_circle: radius: " << outer_circle.radius() << " center: " << outer_circle.center() << std::endl; - // std::cout << " start: point: " << start_pt << " tangent: " << start_tangent << std::endl; + // std::cout << " outer_circle: radius: " << outer_circle.radius() << " center: " << outer_circle.center() << + // std::endl; std::cout << " start: point: " << start_pt << " tangent: " << start_tangent << std::endl; - if( !(outer_circle.contains(start_pt) ) ) { + if (!(outer_circle.contains(start_pt))) { // std::cout << " WARNING: Outer circle does not contain starting point!" << std::endl; - return Geom::Point(0,0); + return Geom::Point(0, 0); } Geom::Line secant1(start_pt, start_pt + start_tangent); @@ -243,25 +255,25 @@ Geom::Point expand_circle( Geom::Circle &inner_circle, Geom::Circle const &outer // std::cout << " chord1: " << chord1_pts[0].point() << ", " << chord1_pts[1].point() << std::endl; Geom::LineSegment chord1(chord1_pts[0].point(), chord1_pts[1].point()); - Geom::Line bisector = make_bisector_line( chord1 ); + Geom::Line bisector = make_bisector_line(chord1); std::vector chord2_pts = outer_circle.intersect(bisector); // std::cout << " chord2: " << chord2_pts[0].point() << ", " << chord2_pts[1].point() << std::endl; Geom::LineSegment chord2(chord2_pts[0].point(), chord2_pts[1].point()); // Find D, point on chord2 and on circle closest to start point - Geom::Coord d0 = Geom::distance(chord2_pts[0].point(),start_pt); - Geom::Coord d1 = Geom::distance(chord2_pts[1].point(),start_pt); + Geom::Coord d0 = Geom::distance(chord2_pts[0].point(), start_pt); + Geom::Coord d1 = Geom::distance(chord2_pts[1].point(), start_pt); // std::cout << " d0: " << d0 << " d1: " << d1 << std::endl; Geom::Point d = (d0 < d1) ? chord2_pts[0].point() : chord2_pts[1].point(); - Geom::Line da(d,start_pt); + Geom::Line da(d, start_pt); // Chord through start point and point D - std::vector chord3_pts = outer_circle.intersect(da); + std::vector chord3_pts = outer_circle.intersect(da); // std::cout << " chord3: " << chord3_pts[0].point() << ", " << chord3_pts[1].point() << std::endl; // Find farthest point on chord3 and on circle (could be more robust) - Geom::Coord d2 = Geom::distance(chord3_pts[0].point(),d); - Geom::Coord d3 = Geom::distance(chord3_pts[1].point(),d); + Geom::Coord d2 = Geom::distance(chord3_pts[0].point(), d); + Geom::Coord d3 = Geom::distance(chord3_pts[1].point(), d); // std::cout << " d2: " << d2 << " d3: " << d3 << std::endl; // Find point P, the intersection of outer circle and new inner circle @@ -270,23 +282,25 @@ Geom::Point expand_circle( Geom::Circle &inner_circle, Geom::Circle const &outer // Find center of new circle: it is at the intersection of the bisector // of the chord defined by the start point and point P and a line through // the start point and parallel to the first bisector. - Geom::LineSegment chord4(start_pt,p); - Geom::Line bisector2 = make_bisector_line( chord4 ); - Geom::Line diameter = make_parallel_line( start_pt, bisector ); - std::vector center_new = bisector2.intersect( diameter ); + Geom::LineSegment chord4(start_pt, p); + Geom::Line bisector2 = make_bisector_line(chord4); + Geom::Line diameter = make_parallel_line(start_pt, bisector); + std::vector center_new = bisector2.intersect(diameter); // std::cout << " center_new: " << center_new[0].point() << std::endl; - Geom::Coord r_new = Geom::distance( center_new[0].point(), start_pt ); + Geom::Coord r_new = Geom::distance(center_new[0].point(), start_pt); // std::cout << " r_new: " << r_new << std::endl; - inner_circle.setCenter( center_new[0].point() ); - inner_circle.setRadius( r_new ); + inner_circle.setCenter(center_new[0].point()); + inner_circle.setRadius(r_new); return p; } // Arcs line join. If two circles don't intersect, adjust both circles so they just touch. -// Increase (decrease) the radius of circle 1 and decrease (increase) of circle 2 by the same amount keeping the given points and tangents fixed. -Geom::Point adjust_circles( Geom::Circle &circle1, Geom::Circle &circle2, Geom::Point const &point1, Geom::Point const &point2, Geom::Point const &tan1, Geom::Point const &tan2 ) { - +// Increase (decrease) the radius of circle 1 and decrease (increase) of circle 2 by the same amount keeping the given +// points and tangents fixed. +Geom::Point adjust_circles(Geom::Circle &circle1, Geom::Circle &circle2, Geom::Point const &point1, + Geom::Point const &point2, Geom::Point const &tan1, Geom::Point const &tan2) +{ Geom::Point n1 = (circle1.center() - point1).normalized(); // Always points towards center Geom::Point n2 = (circle2.center() - point2).normalized(); Geom::Point sum_n = n1 + n2; @@ -306,44 +320,44 @@ Geom::Point adjust_circles( Geom::Circle &circle1, Geom::Circle &circle2, Geom:: // Quadratic equation double A = 4 - sum_n.length() * sum_n.length(); - double B = 4.0 * delta_r - 2.0 * Geom::dot( delta_c, sum_n ); + double B = 4.0 * delta_r - 2.0 * Geom::dot(delta_c, sum_n); double C = delta_r * delta_r - delta_c.length() * delta_c.length(); double s1 = 0; double s2 = 0; - if( fabs(A) < 0.01 ) { + if (fabs(A) < 0.01) { // std::cout << " A near zero! $$$$$$$$$$$$$$$$$$" << std::endl; - if( B != 0 ) { - s1 = -C/B; + if (B != 0) { + s1 = -C / B; s2 = -s1; } } else { - s1 = (-B + sqrt(B*B - 4*A*C))/(2*A); - s2 = (-B - sqrt(B*B - 4*A*C))/(2*A); + s1 = (-B + sqrt(B * B - 4 * A * C)) / (2 * A); + s2 = (-B - sqrt(B * B - 4 * A * C)) / (2 * A); } - double dr = (fabs(s1)<=fabs(s2)?s1:s2); + double dr = (fabs(s1) <= fabs(s2) ? s1 : s2); // std::cout << " A: " << A << std::endl; // std::cout << " B: " << B << std::endl; // std::cout << " C: " << C << std::endl; // std::cout << " s1: " << s1 << " s2: " << s2 << " dr: " << dr << std::endl; - circle1 = Geom::Circle( c1 - dr*n1, r1-dr ); - circle2 = Geom::Circle( c2 + dr*n2, r2+dr ); + circle1 = Geom::Circle(c1 - dr * n1, r1 - dr); + circle2 = Geom::Circle(c2 + dr * n2, r2 + dr); // std::cout << " C1: " << circle1 << std::endl; // std::cout << " C2: " << circle2 << std::endl; // std::cout << " d': " << Geom::Point( circle1.center() - circle2.center() ).length() << std::endl; - Geom::Line bisector( circle1.center(), circle2.center() ); - std::vector points = circle1.intersect( bisector ); + Geom::Line bisector(circle1.center(), circle2.center()); + std::vector points = circle1.intersect(bisector); Geom::Point p0 = points[0].point(); Geom::Point p1 = points[1].point(); // std::cout << " points: " << p0 << "; " << p1 << std::endl; - if( std::abs( Geom::distance( p0, circle2.center() ) - circle2.radius() ) < - std::abs( Geom::distance( p1, circle2.center() ) - circle2.radius() ) ) { + if (std::abs(Geom::distance(p0, circle2.center()) - circle2.radius()) < + std::abs(Geom::distance(p1, circle2.center()) - circle2.radius())) { return p0; } else { return p1; @@ -356,8 +370,8 @@ void extrapolate_join_internal(join_data jd, int alternative) using namespace Geom; Geom::Path &res = jd.res; - Geom::Curve const& incoming = res.back(); - Geom::Curve const& outgoing = jd.outgoing.front(); + Geom::Curve const &incoming = res.back(); + Geom::Curve const &outgoing = jd.outgoing.front(); Geom::Point startPt = incoming.finalPoint(); Geom::Point endPt = outgoing.initialPoint(); Geom::Point tang1 = jd.in_tang; @@ -375,16 +389,16 @@ void extrapolate_join_internal(join_data jd, int alternative) Geom::Circle circle2 = touching_circle(outgoing.toSBasis(), 0); // std::cout << " circle1: " << circle1 << std::endl; // std::cout << " circle2: " << circle2 << std::endl; - if( Geom::CubicBezier const * in_bezier = dynamic_cast(&incoming) ) { + if (Geom::CubicBezier const *in_bezier = dynamic_cast(&incoming)) { Geom::Circle circle_test1 = touching_circle(*in_bezier, false); - if( !Geom::are_near( circle1, circle_test1, 0.01 ) ) { + if (!Geom::are_near(circle1, circle_test1, 0.01)) { // std::cout << " Circle 1 error!!!!!!!!!!!!!!!!!" << std::endl; // std::cout << " " << circle_test1 << std::endl; } } - if( Geom::CubicBezier const * out_bezier = dynamic_cast(&outgoing) ) { + if (Geom::CubicBezier const *out_bezier = dynamic_cast(&outgoing)) { Geom::Circle circle_test2 = touching_circle(*out_bezier, true); - if( !Geom::are_near( circle2, circle_test2, 0.01 ) ) { + if (!Geom::are_near(circle2, circle_test2, 0.01)) { // std::cout << " Circle 2 error!!!!!!!!!!!!!!!!!" << std::endl; // std::cout << " " << circle_test2 << std::endl; } @@ -392,7 +406,8 @@ void extrapolate_join_internal(join_data jd, int alternative) // END TESTING Geom::Point center1 = circle1.center(); - double side1 = tang1[Geom::X]*(startPt[Geom::Y]-center1[Geom::Y]) - tang1[Geom::Y]*(startPt[Geom::X]-center1[Geom::X]); + double side1 = + tang1[Geom::X] * (startPt[Geom::Y] - center1[Geom::Y]) - tang1[Geom::Y] * (startPt[Geom::X] - center1[Geom::X]); // std::cout << " side1: " << side1 << std::endl; bool inc_ls = !circle1.center().isFinite(); @@ -412,14 +427,14 @@ void extrapolate_join_internal(join_data jd, int alternative) // std::cout << " two circles" << std::endl; // See if tangent is backwards (radius < width/2 and circle is inside stroke). - Geom::Point node_on_path = startPt + Geom::rot90(tang1)*width; + Geom::Point node_on_path = startPt + Geom::rot90(tang1) * width; // std::cout << " node_on_path: " << node_on_path << " -------------- " << std::endl; bool b1 = false; bool b2 = false; - if (circle1.radius() < width && distance( circle1.center(), node_on_path ) < width) { + if (circle1.radius() < width && distance(circle1.center(), node_on_path) < width) { b1 = true; } - if (circle2.radius() < width && distance( circle2.center(), node_on_path ) < width) { + if (circle2.radius() < width && distance(circle2.center(), node_on_path) < width) { b2 = true; } // std::cout << " b1: " << (b1?"true":"false") @@ -431,68 +446,63 @@ void extrapolate_join_internal(join_data jd, int alternative) if (points.size() != 2) { // std::cout << " Circles do not intersect, do backup" << std::endl; switch (alternative) { - case 1: - { + case 1: { // Fallback to round if one path has radius smaller than half line width. - if(b1 || b2) { + if (b1 || b2) { // std::cout << "At one least path has radius smaller than half line width." << std::endl; - return( round_join(jd) ); + return (round_join(jd)); } Point p; - if( circle2.contains( startPt ) && !circle1.contains( endPt ) ) { + if (circle2.contains(startPt) && !circle1.contains(endPt)) { // std::cout << "Expand circle1" << std::endl; - p = expand_circle( circle1, circle2, startPt, tang1 ); - points.emplace_back( 0, 0, p ); - points.emplace_back( 0, 0, p ); - } else if( circle1.contains( endPt ) && !circle2.contains( startPt ) ) { + p = expand_circle(circle1, circle2, startPt, tang1); + points.emplace_back(0, 0, p); + points.emplace_back(0, 0, p); + } else if (circle1.contains(endPt) && !circle2.contains(startPt)) { // std::cout << "Expand circle2" << std::endl; - p = expand_circle( circle2, circle1, endPt, tang2 ); - points.emplace_back( 0, 0, p ); - points.emplace_back( 0, 0, p ); + p = expand_circle(circle2, circle1, endPt, tang2); + points.emplace_back(0, 0, p); + points.emplace_back(0, 0, p); } else { // std::cout << "Either both points inside or both outside" << std::endl; - return( miter_clip_join(jd) ); + return (miter_clip_join(jd)); } break; - } - case 2: - { + case 2: { // Fallback to round if one path has radius smaller than half line width. - if(b1 || b2) { + if (b1 || b2) { // std::cout << "At one least path has radius smaller than half line width." << std::endl; - return( round_join(jd) ); + return (round_join(jd)); } - if( ( circle2.contains( startPt ) && !circle1.contains( endPt ) ) || - ( circle1.contains( endPt ) && !circle2.contains( startPt ) ) ) { - - Geom::Point apex = adjust_circles( circle1, circle2, startPt, endPt, tang1, tang2 ); - points.emplace_back( 0, 0, apex ); - points.emplace_back( 0, 0, apex ); + if ((circle2.contains(startPt) && !circle1.contains(endPt)) || + (circle1.contains(endPt) && !circle2.contains(startPt))) { + Geom::Point apex = adjust_circles(circle1, circle2, startPt, endPt, tang1, tang2); + points.emplace_back(0, 0, apex); + points.emplace_back(0, 0, apex); } else { // std::cout << "Either both points inside or both outside" << std::endl; - return( miter_clip_join(jd) ); + return (miter_clip_join(jd)); } - + break; } case 3: - if( side1 > 0 ) { + if (side1 > 0) { Geom::Line secant(startPt, startPt + tang1); points = circle2.intersect(secant); circle1.setRadius(std::numeric_limits::infinity()); - circle1.setCenter(Geom::Point(0,std::numeric_limits::infinity())); + circle1.setCenter(Geom::Point(0, std::numeric_limits::infinity())); } else { Geom::Line secant(endPt, endPt + tang2); points = circle1.intersect(secant); circle2.setRadius(std::numeric_limits::infinity()); - circle2.setCenter(Geom::Point(0,std::numeric_limits::infinity())); + circle2.setCenter(Geom::Point(0, std::numeric_limits::infinity())); } break; - case 0: default: // Do nothing @@ -502,13 +512,13 @@ void extrapolate_join_internal(join_data jd, int alternative) if (points.size() == 2) { sol = pick_solution(points, tang2, endPt); - if( circle1.radius() != std::numeric_limits::infinity() ) { - arc1 = circle1.arc(startPt, 0.5*(startPt+sol), sol); + if (circle1.radius() != std::numeric_limits::infinity()) { + arc1 = circle1.arc(startPt, 0.5 * (startPt + sol), sol); } else { seg1 = new Geom::LineSegment(startPt, sol); } - if( circle2.radius() != std::numeric_limits::infinity() ) { - arc2 = circle2.arc(sol, 0.5*(sol+endPt), endPt); + if (circle2.radius() != std::numeric_limits::infinity()) { + arc2 = circle2.arc(sol, 0.5 * (sol + endPt), endPt); } else { seg2 = new Geom::LineSegment(sol, endPt); } @@ -519,7 +529,7 @@ void extrapolate_join_internal(join_data jd, int alternative) points = circle2.intersect(Line(incoming.initialPoint(), incoming.finalPoint())); if (points.size() == 2) { sol = pick_solution(points, tang2, endPt); - arc2 = circle2.arc(sol, 0.5*(sol+endPt), endPt); + arc2 = circle2.arc(sol, 0.5 * (sol + endPt), endPt); } } else if (!inc_ls && out_ls) { // Circle and line @@ -527,7 +537,7 @@ void extrapolate_join_internal(join_data jd, int alternative) points = circle1.intersect(Line(outgoing.initialPoint(), outgoing.finalPoint())); if (points.size() == 2) { sol = pick_solution(points, tang2, endPt); - arc1 = circle1.arc(startPt, 0.5*(sol+startPt), sol); + arc1 = circle1.arc(startPt, 0.5 * (sol + startPt), sol); } } if (points.size() != 2) { @@ -538,19 +548,19 @@ void extrapolate_join_internal(join_data jd, int alternative) // We have a solution, thus sol is defined. p1 = sol; - + // See if we need to clip. Miter length is measured along a circular arc that is tangent to the // bisector of the incoming and out going angles and passes through the end point (sol) of the // line join. // Center of circle is intersection of a line orthogonal to bisector and a line bisecting // a chord connecting the path end point (point_on_path) and the join end point (sol). - Geom::Point point_on_path = startPt + Geom::rot90(tang1)*width; + Geom::Point point_on_path = startPt + Geom::rot90(tang1) * width; Geom::Line bisector = make_angle_bisector_line(startPt, point_on_path, endPt); - Geom::Line ortho = make_orthogonal_line(point_on_path, bisector); + Geom::Line ortho = make_orthogonal_line(point_on_path, bisector); Geom::LineSegment chord(point_on_path, sol); - Geom::Line bisector_chord = make_bisector_line(chord); + Geom::Line bisector_chord = make_bisector_line(chord); Geom::Line limit_line; double miter_limit = width * miter; @@ -561,13 +571,12 @@ void extrapolate_join_internal(join_data jd, int alternative) if (Geom::distance(point_on_path, sol) > miter_limit) { clipped = true; Geom::Point temp = bisector.versor(); - Geom::Point limit_point = point_on_path + miter_limit * temp; - limit_line = make_parallel_line( limit_point, ortho ); + Geom::Point limit_point = point_on_path + miter_limit * temp; + limit_line = make_parallel_line(limit_point, ortho); } } else { - Geom::Point center = - Geom::intersection_point( bisector_chord.pointAt(0), bisector_chord.versor(), - ortho.pointAt(0), ortho.versor() ); + Geom::Point center = Geom::intersection_point(bisector_chord.pointAt(0), bisector_chord.versor(), + ortho.pointAt(0), ortho.versor()); Geom::Coord radius = distance(center, point_on_path); Geom::Circle circle_center(center, radius); @@ -583,7 +592,7 @@ void extrapolate_join_internal(join_data jd, int alternative) limit_line.setAngle(start_ray.angle() + limit_angle); } - Geom::EllipticalArc *arc_center = circle_center.arc(point_on_path, 0.5*(point_on_path + sol), sol); + Geom::EllipticalArc *arc_center = circle_center.arc(point_on_path, 0.5 * (point_on_path + sol), sol); if (arc_center && arc_center->sweepAngle() > limit_angle) { // We need to clip clipped = true; @@ -594,7 +603,7 @@ void extrapolate_join_internal(join_data jd, int alternative) if (points.size() == 2) { p1 = pick_solution(points, tang2, endPt); delete arc1; - arc1 = circle1.arc(startPt, 0.5*(p1+startPt), p1); + arc1 = circle1.arc(startPt, 0.5 * (p1 + startPt), p1); } } else { p1 = Geom::intersection_point(startPt, tang1, limit_line.pointAt(0), limit_line.versor()); @@ -606,18 +615,18 @@ void extrapolate_join_internal(join_data jd, int alternative) if (points.size() == 2) { p2 = pick_solution(points, tang1, endPt); delete arc2; - arc2 = circle2.arc(p2, 0.5*(p2+endPt), endPt); + arc2 = circle2.arc(p2, 0.5 * (p2 + endPt), endPt); } } else { p2 = Geom::intersection_point(endPt, tang2, limit_line.pointAt(0), limit_line.versor()); } } - } + } // Add initial if (arc1) { res.append(*arc1); - } else if (seg1 ) { + } else if (seg1) { res.append(*seg1); } else { // Straight line segment: move last point @@ -632,7 +641,7 @@ void extrapolate_join_internal(join_data jd, int alternative) if (arc2) { res.append(*arc2); res.append(outgoing); - } else if (seg2 ) { + } else if (seg2) { res.append(*seg2); res.append(outgoing); } else { @@ -649,13 +658,24 @@ void extrapolate_join_internal(join_data jd, int alternative) delete seg2; } -void extrapolate_join( join_data jd) { extrapolate_join_internal(jd, 0); } -void extrapolate_join_alt1(join_data jd) { extrapolate_join_internal(jd, 1); } -void extrapolate_join_alt2(join_data jd) { extrapolate_join_internal(jd, 2); } -void extrapolate_join_alt3(join_data jd) { extrapolate_join_internal(jd, 3); } - +void extrapolate_join(join_data jd) +{ + extrapolate_join_internal(jd, 0); +} +void extrapolate_join_alt1(join_data jd) +{ + extrapolate_join_internal(jd, 1); +} +void extrapolate_join_alt2(join_data jd) +{ + extrapolate_join_internal(jd, 2); +} +void extrapolate_join_alt3(join_data jd) +{ + extrapolate_join_internal(jd, 3); +} -void tangents(Geom::Point tang[2], Geom::Curve const& incoming, Geom::Curve const& outgoing) +void tangents(Geom::Point tang[2], Geom::Curve const &incoming, Geom::Curve const &outgoing) { Geom::Point tang1 = Geom::unitTangentAt(reverse(incoming.toSBasis()), 0.); Geom::Point tang2 = outgoing.unitTangentAt(0.); @@ -663,25 +683,25 @@ void tangents(Geom::Point tang[2], Geom::Curve const& incoming, Geom::Curve cons } // Offsetting a line segment is mathematically stable and quick to do -Geom::LineSegment offset_line(Geom::LineSegment const& l, double width) +Geom::LineSegment offset_line(Geom::LineSegment const &l, double width) { Geom::Point tang1 = Geom::rot90(l.unitTangentAt(0)); Geom::Point tang2 = Geom::rot90(unitTangentAt(reverse(l.toSBasis()), 0.)); Geom::Point start = l.initialPoint() + tang1 * width; Geom::Point end = l.finalPoint() - tang2 * width; - + return Geom::LineSegment(start, end); } -void get_cubic_data(Geom::CubicBezier const& bez, double time, double& len, double& rad) +void get_cubic_data(Geom::CubicBezier const &bez, double time, double &len, double &rad) { // get derivatives std::vector derivs = bez.pointAndDerivatives(time, 3); Geom::Point der1 = derivs[1]; // first deriv (tangent vector) Geom::Point der2 = derivs[2]; // second deriv (tangent's tangent) - double l = Geom::L2(der1); // length + double l = Geom::L2(der1); // length len = rad = 0; @@ -696,7 +716,7 @@ void get_cubic_data(Geom::CubicBezier const& bez, double time, double& len, doub if (Geom::are_near(l, 0)) { return; // this isn't a segment... } - rad = 1e8; + rad = 1e8; } else { rad = -l * (Geom::dot(der2, der2) / Geom::cross(der2, der3)); } @@ -706,19 +726,11 @@ void get_cubic_data(Geom::CubicBezier const& bez, double time, double& len, doub len = l; } -double _offset_cubic_stable_sub( - Geom::CubicBezier const& bez, - Geom::CubicBezier& c, - const Geom::Point& start_normal, - const Geom::Point& end_normal, - const Geom::Point& start_new, - const Geom::Point& end_new, - const double start_rad, - const double end_rad, - const double start_len, - const double end_len, - const double width, - const double width_correction) { +double _offset_cubic_stable_sub(Geom::CubicBezier const &bez, Geom::CubicBezier &c, const Geom::Point &start_normal, + const Geom::Point &end_normal, const Geom::Point &start_new, const Geom::Point &end_new, + const double start_rad, const double end_rad, const double start_len, + const double end_len, const double width, const double width_correction) +{ using Geom::X; using Geom::Y; @@ -740,10 +752,10 @@ double _offset_cubic_stable_sub( end_off *= end_len; // -------- - Geom::Point mid1_new = start_normal.ccw()*start_off; - mid1_new = Geom::Point(start_new[X] + mid1_new[X]/3., start_new[Y] + mid1_new[Y]/3.); - Geom::Point mid2_new = end_normal.ccw()*end_off; - mid2_new = Geom::Point(end_new[X] - mid2_new[X]/3., end_new[Y] - mid2_new[Y]/3.); + Geom::Point mid1_new = start_normal.ccw() * start_off; + mid1_new = Geom::Point(start_new[X] + mid1_new[X] / 3., start_new[Y] + mid1_new[Y] / 3.); + Geom::Point mid2_new = end_normal.ccw() * end_off; + mid2_new = Geom::Point(end_new[X] - mid2_new[X] / 3., end_new[Y] - mid2_new[Y] / 3.); // create the estimate curve c = Geom::CubicBezier(start_new, mid1_new, mid2_new, end_new); @@ -751,11 +763,11 @@ double _offset_cubic_stable_sub( // check the tolerance for our estimate to be a parallel curve double worst_residual = 0; - for (size_t ii = 3; ii <= 7; ii+=2) { + for (size_t ii = 3; ii <= 7; ii += 2) { const double t = static_cast(ii) / 10; const Geom::Point req = bez.pointAt(t); const Geom::Point chk = c.pointAt(c.nearestTime(req)); - const double current_residual = (chk-req).length() - std::abs(width); + const double current_residual = (chk - req).length() - std::abs(width); if (std::abs(current_residual) > std::abs(worst_residual)) { worst_residual = current_residual; } @@ -763,7 +775,7 @@ double _offset_cubic_stable_sub( return worst_residual; } -void offset_cubic(Geom::Path& p, Geom::CubicBezier const& bez, double width, double tol, size_t levels) +void offset_cubic(Geom::Path &p, Geom::CubicBezier const &bez, double width, double tol, size_t levels) { using Geom::X; using Geom::Y; @@ -775,8 +787,8 @@ void offset_cubic(Geom::Path& p, Geom::CubicBezier const& bez, double width, dou const Geom::Point end_normal = -Geom::rot90(Geom::unitTangentAt(Geom::reverse(bez.toSBasis()), 0.)); // offset the start and end control points out by the width - const Geom::Point start_new = start_pos + start_normal*width; - const Geom::Point end_new = end_pos + end_normal*width; + const Geom::Point start_new = start_pos + start_normal * width; + const Geom::Point end_new = end_pos + end_normal * width; // -------- double start_rad, end_rad; @@ -784,18 +796,12 @@ void offset_cubic(Geom::Path& p, Geom::CubicBezier const& bez, double width, dou get_cubic_data(bez, 0, start_len, start_rad); get_cubic_data(bez, 1, end_len, end_rad); - Geom::CubicBezier c; double best_width_correction = 0; - double best_residual = _offset_cubic_stable_sub( - bez, c, - start_normal, end_normal, - start_new, end_new, - start_rad, end_rad, - start_len, end_len, - width, best_width_correction); - double stepsize = std::abs(width)/2; + double best_residual = _offset_cubic_stable_sub(bez, c, start_normal, end_normal, start_new, end_new, start_rad, + end_rad, start_len, end_len, width, best_width_correction); + double stepsize = std::abs(width) / 2; bool seen_success = false; double stepsize_threshold = 0; // std::cout << "Residual from " << best_residual << " "; @@ -804,19 +810,15 @@ void offset_cubic(Geom::Path& p, Geom::CubicBezier const& bez, double width, dou bool success = false; const double width_correction = best_width_correction - (best_residual > 0 ? 1 : -1) * stepsize; Geom::CubicBezier current_curve; - const double residual = _offset_cubic_stable_sub( - bez, current_curve, - start_normal, end_normal, - start_new, end_new, - start_rad, end_rad, - start_len, end_len, - width, width_correction); + const double residual = + _offset_cubic_stable_sub(bez, current_curve, start_normal, end_normal, start_new, end_new, start_rad, + end_rad, start_len, end_len, width, width_correction); if (std::abs(residual) < std::abs(best_residual)) { best_residual = residual; best_width_correction = width_correction; c = current_curve; success = true; - if (std::abs(best_residual) < tol/4) { + if (std::abs(best_residual) < tol / 4) { break; } } @@ -824,15 +826,14 @@ void offset_cubic(Geom::Path& p, Geom::CubicBezier const& bez, double width, dou if (success) { if (!seen_success) { seen_success = true; - //std::cout << "Stepsize factor: " << std::abs(width) / stepsize << std::endl; + // std::cout << "Stepsize factor: " << std::abs(width) / stepsize << std::endl; stepsize_threshold = stepsize / 1000; } - } - else { + } else { stepsize /= 2; } - if (std::abs(best_width_correction) >= std::abs(width)/2) { - //break; // Seems to prevent some numerical instabilities, not clear if useful + if (std::abs(best_width_correction) >= std::abs(width) / 2) { + // break; // Seems to prevent some numerical instabilities, not clear if useful } } @@ -841,12 +842,10 @@ void offset_cubic(Geom::Path& p, Geom::CubicBezier const& bez, double width, dou if (levels == 0) { try { p.append(c); - } - catch (...) { + } catch (...) { if ((p.finalPoint() - c.initialPoint()).length() < 1e-6) { c.setInitial(p.finalPoint()); - } - else { + } else { auto line = Geom::LineSegment(p.finalPoint(), c.initialPoint()); p.append(line); } @@ -892,84 +891,86 @@ void offset_cubic(Geom::Path& p, Geom::CubicBezier const& bez, double width, dou } } -void offset_quadratic(Geom::Path& p, Geom::QuadraticBezier const& bez, double width, double tol, size_t levels) +void offset_quadratic(Geom::Path &p, Geom::QuadraticBezier const &bez, double width, double tol, size_t levels) { // cheat // it's faster // seriously std::vector points = bez.controlPoints(); - Geom::Point b1 = points[0] + (2./3) * (points[1] - points[0]); - Geom::Point b2 = b1 + (1./3) * (points[2] - points[0]); + Geom::Point b1 = points[0] + (2. / 3) * (points[1] - points[0]); + Geom::Point b2 = b1 + (1. / 3) * (points[2] - points[0]); Geom::CubicBezier cub = Geom::CubicBezier(points[0], b1, b2, points[2]); offset_cubic(p, cub, width, tol, levels); } -void offset_curve(Geom::Path& res, Geom::Curve const* current, double width, double tolerance) +void offset_curve(Geom::Path &res, Geom::Curve const *current, double width, double tolerance) { size_t levels = 8; - if (current->isDegenerate()) return; // don't do anything + if (current->isDegenerate()) + return; // don't do anything // TODO: we can handle SVGEllipticalArc here as well, do that! - if (Geom::BezierCurve const *b = dynamic_cast(current)) { + if (Geom::BezierCurve const *b = dynamic_cast(current)) { size_t order = b->order(); switch (order) { case 1: - res.append(offset_line(static_cast(*current), width)); + res.append(offset_line(static_cast(*current), width)); break; case 2: { - Geom::QuadraticBezier const& q = static_cast(*current); + Geom::QuadraticBezier const &q = static_cast(*current); offset_quadratic(res, q, width, tolerance, levels); break; } case 3: { - Geom::CubicBezier const& cb = static_cast(*current); + Geom::CubicBezier const &cb = static_cast(*current); offset_cubic(res, cb, width, tolerance, levels); break; } default: { Geom::Path sbasis_path = Geom::cubicbezierpath_from_sbasis(current->toSBasis(), tolerance); - for (const auto & i : sbasis_path) + for (const auto &i : sbasis_path) offset_curve(res, &i, width, tolerance); break; } } } else { Geom::Path sbasis_path = Geom::cubicbezierpath_from_sbasis(current->toSBasis(), 0.1); - for (const auto & i : sbasis_path) + for (const auto &i : sbasis_path) offset_curve(res, &i, width, tolerance); } } -typedef void cap_func(Geom::PathBuilder& res, Geom::Path const& with_dir, Geom::Path const& against_dir, double width); +typedef void cap_func(Geom::PathBuilder &res, Geom::Path const &with_dir, Geom::Path const &against_dir, double width); -void flat_cap(Geom::PathBuilder& res, Geom::Path const&, Geom::Path const& against_dir, double) +void flat_cap(Geom::PathBuilder &res, Geom::Path const &, Geom::Path const &against_dir, double) { res.lineTo(against_dir.initialPoint()); } -void round_cap(Geom::PathBuilder& res, Geom::Path const&, Geom::Path const& against_dir, double width) +void round_cap(Geom::PathBuilder &res, Geom::Path const &, Geom::Path const &against_dir, double width) { res.arcTo(width / 2., width / 2., 0., true, false, against_dir.initialPoint()); } -void square_cap(Geom::PathBuilder& res, Geom::Path const& with_dir, Geom::Path const& against_dir, double width) +void square_cap(Geom::PathBuilder &res, Geom::Path const &with_dir, Geom::Path const &against_dir, double width) { width /= 2.; Geom::Point normal_1 = -Geom::unitTangentAt(Geom::reverse(with_dir.back().toSBasis()), 0.); Geom::Point normal_2 = -against_dir[0].unitTangentAt(0.); - res.lineTo(with_dir.finalPoint() + normal_1*width); - res.lineTo(against_dir.initialPoint() + normal_2*width); + res.lineTo(with_dir.finalPoint() + normal_1 * width); + res.lineTo(against_dir.initialPoint() + normal_2 * width); res.lineTo(against_dir.initialPoint()); } -void peak_cap(Geom::PathBuilder& res, Geom::Path const& with_dir, Geom::Path const& against_dir, double width) +void peak_cap(Geom::PathBuilder &res, Geom::Path const &with_dir, Geom::Path const &against_dir, double width) { width /= 2.; Geom::Point normal_1 = -Geom::unitTangentAt(Geom::reverse(with_dir.back().toSBasis()), 0.); Geom::Point normal_2 = -against_dir[0].unitTangentAt(0.); - Geom::Point midpoint = ((with_dir.finalPoint() + normal_1*width) + (against_dir.initialPoint() + normal_2*width)) * 0.5; + Geom::Point midpoint = + ((with_dir.finalPoint() + normal_1 * width) + (against_dir.initialPoint() + normal_2 * width)) * 0.5; res.lineTo(midpoint); res.lineTo(against_dir.initialPoint()); } @@ -978,19 +979,15 @@ void peak_cap(Geom::PathBuilder& res, Geom::Path const& with_dir, Geom::Path con namespace Inkscape { -Geom::PathVector outline( - Geom::Path const& input, - double width, - double miter, - LineJoinType join, - LineCapType butt, - double tolerance) +Geom::PathVector outline(Geom::Path const &input, double width, double miter, LineJoinType join, LineCapType butt, + double tolerance) { - if (input.size() == 0) return Geom::PathVector(); // nope, don't even try + if (input.size() == 0) + return Geom::PathVector(); // nope, don't even try Geom::PathBuilder res; - Geom::Path with_dir = half_outline(input, width/2., miter, join, tolerance); - Geom::Path against_dir = half_outline(input.reversed(), width/2., miter, join, tolerance); + Geom::Path with_dir = half_outline(input, width / 2., miter, join, tolerance); + Geom::Path against_dir = half_outline(input.reversed(), width / 2., miter, join, tolerance); res.moveTo(with_dir[0].initialPoint()); res.append(with_dir); @@ -1028,23 +1025,18 @@ Geom::PathVector outline( return res.peek(); } -Geom::Path half_outline( - Geom::Path const& input, - double width, - double miter, - LineJoinType join, - double tolerance) +Geom::Path half_outline(Geom::Path const &input, double width, double miter, LineJoinType join, double tolerance) { if (tolerance <= 0) { if (std::abs(width) > 0) { - tolerance = 5.0 * (std::abs(width)/100); - } - else { + tolerance = 5.0 * (std::abs(width) / 100); + } else { tolerance = 1e-4; } } Geom::Path res; - if (input.size() == 0) return res; + if (input.size() == 0) + return res; Geom::Point tang1 = input[0].unitTangentAt(0); Geom::Point start = input.initialPoint() + tang1 * width; @@ -1058,9 +1050,10 @@ Geom::Path half_outline( // Do two curves at a time for efficiency, since the join function needs to know the outgoing curve as well const Geom::Curve &closingline = input.back_closed(); - const size_t k = (are_near(closingline.initialPoint(), closingline.finalPoint()) && input.closed() ) - ?input.size_open():input.size_default(); - + const size_t k = (are_near(closingline.initialPoint(), closingline.finalPoint()) && input.closed()) + ? input.size_open() + : input.size_default(); + for (size_t u = 0; u < k; u += 2) { temp.clear(); @@ -1070,15 +1063,15 @@ Geom::Path half_outline( if (u == 0) { res.append(temp); } else { - tangents(tang, input[u-1], input[u]); + tangents(tang, input[u - 1], input[u]); outline_join(res, temp, tang[0], tang[1], width, miter, join); } // odd number of paths if (u < k - 1) { temp.clear(); - offset_curve(temp, &input[u+1], width, tolerance); - tangents(tang, input[u], input[u+1]); + offset_curve(temp, &input[u + 1], width, tolerance); + tangents(tang, input[u], input[u + 1]); outline_join(res, temp, tang[0], tang[1], width, miter, join); } } @@ -1099,11 +1092,12 @@ Geom::Path half_outline( return res; } -void outline_join(Geom::Path &res, Geom::Path const& temp, Geom::Point in_tang, Geom::Point out_tang, double width, double miter, Inkscape::LineJoinType join) +void outline_join(Geom::Path &res, Geom::Path const &temp, Geom::Point in_tang, Geom::Point out_tang, double width, + double miter, Inkscape::LineJoinType join) { if (res.size() == 0 || temp.size() == 0) return; - Geom::Curve const& outgoing = temp.front(); + Geom::Curve const &outgoing = temp.front(); if (Geom::are_near(res.finalPoint(), outgoing.initialPoint(), 0.01)) { // if the points are /that/ close, just ignore this one res.setFinal(temp.initialPoint()); @@ -1142,7 +1136,7 @@ void outline_join(Geom::Path &res, Geom::Path const& temp, Geom::Point in_tang, jf = &miter_join; } jf(jd); - } +} } // namespace Inkscape diff --git a/src/helper/geom-pathstroke.h b/src/helper/geom-pathstroke.h index 73d35b40253e1d425918f3e5914901a6eba801f2..00818721900b618d36d5121a51e178dc98ba4693 100644 --- a/src/helper/geom-pathstroke.h +++ b/src/helper/geom-pathstroke.h @@ -16,7 +16,8 @@ namespace Inkscape { -enum LineJoinType { +enum LineJoinType +{ JOIN_BEVEL, JOIN_ROUND, JOIN_MITER, @@ -27,7 +28,8 @@ enum LineJoinType { JOIN_EXTRAPOLATE3, }; -enum LineCapType { +enum LineCapType +{ BUTT_FLAT, BUTT_ROUND, BUTT_SQUARE, @@ -49,13 +51,8 @@ enum LineCapType { * If the input path is closed, the resultant vector will contain two paths. * Otherwise, there should be only one in the output. */ -Geom::PathVector outline( - Geom::Path const& input, - double width, - double miter, - LineJoinType join = JOIN_BEVEL, - LineCapType cap = BUTT_FLAT, - double tolerance = -1); +Geom::PathVector outline(Geom::Path const &input, double width, double miter, LineJoinType join = JOIN_BEVEL, + LineCapType cap = BUTT_FLAT, double tolerance = -1); /** * Offset the input path by @a width. @@ -69,18 +66,14 @@ Geom::PathVector outline( * * @return Offsetted output. */ -Geom::Path half_outline( - Geom::Path const& input, - double width, - double miter, - LineJoinType join = JOIN_BEVEL, - double tolerance = -1); +Geom::Path half_outline(Geom::Path const &input, double width, double miter, LineJoinType join = JOIN_BEVEL, + double tolerance = -1); /** * Builds a join on the provided path. * Joins may behave oddly if the width is negative. * - * @param[inout] res The path to build the join on. + * @param[inout] res The path to build the join on. * The outgoing path (or a portion thereof) will be appended after the join is created. * Previous segments may be modified as an optimization, beware! * @@ -91,7 +84,8 @@ Geom::Path half_outline( * @param[in] miter * @param[in] join */ -void outline_join(Geom::Path &res, Geom::Path const& outgoing, Geom::Point in_tang, Geom::Point out_tang, double width, double miter, LineJoinType join); +void outline_join(Geom::Path &res, Geom::Path const &outgoing, Geom::Point in_tang, Geom::Point out_tang, double width, + double miter, LineJoinType join); } // namespace Inkscape diff --git a/src/helper/geom-pathvectorsatellites.cpp b/src/helper/geom-pathvectorsatellites.cpp index 0e7c4f1384690ffaa289d7a50679d39f0826daa5..2e4f18a6f3569b4491bf423060e89bf0e34140ca 100644 --- a/src/helper/geom-pathvectorsatellites.cpp +++ b/src/helper/geom-pathvectorsatellites.cpp @@ -17,8 +17,9 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include +#include + #include "util/units.h" Geom::PathVector PathVectorSatellites::getPathVector() const @@ -44,7 +45,7 @@ void PathVectorSatellites::setSatellites(Satellites satellites) size_t PathVectorSatellites::getTotalSatellites() { size_t counter = 0; - for (auto & _satellite : _satellites) { + for (auto &_satellite : _satellites) { counter += _satellite.size(); } return counter; @@ -56,20 +57,20 @@ std::pair PathVectorSatellites::getIndexData(size_t index) for (size_t i = 0; i < _satellites.size(); ++i) { for (size_t j = 0; j < _satellites[i].size(); ++j) { if (index == counter) { - return std::make_pair(i,j); + return std::make_pair(i, j); } counter++; } } - return std::make_pair(0,0); + return std::make_pair(0, 0); } void PathVectorSatellites::setSelected(std::vector selected) { size_t counter = 0; - for (auto & _satellite : _satellites) { - for (auto & j : _satellite) { - if (find (selected.begin(), selected.end(), counter) != selected.end()) { + for (auto &_satellite : _satellites) { + for (auto &j : _satellite) { + if (find(selected.begin(), selected.end(), counter) != selected.end()) { j.setSelected(true); } else { j.setSelected(false); @@ -81,11 +82,9 @@ void PathVectorSatellites::setSelected(std::vector selected) void PathVectorSatellites::updateSteps(size_t steps, bool apply_no_radius, bool apply_with_radius, bool only_selected) { - for (auto & _satellite : _satellites) { - for (auto & j : _satellite) { - if ((!apply_no_radius && j.amount == 0) || - (!apply_with_radius && j.amount != 0)) - { + for (auto &_satellite : _satellites) { + for (auto &j : _satellite) { + if ((!apply_no_radius && j.amount == 0) || (!apply_with_radius && j.amount != 0)) { continue; } if (only_selected) { @@ -99,8 +98,8 @@ void PathVectorSatellites::updateSteps(size_t steps, bool apply_no_radius, bool } } -void PathVectorSatellites::updateAmount(double radius, bool apply_no_radius, bool apply_with_radius, bool only_selected, - bool use_knot_distance, bool flexible) +void PathVectorSatellites::updateAmount(double radius, bool apply_no_radius, bool apply_with_radius, bool only_selected, + bool use_knot_distance, bool flexible) { double power = 0; if (!flexible) { @@ -124,15 +123,15 @@ void PathVectorSatellites::updateAmount(double radius, bool apply_no_radius, boo continue; } if ((!apply_no_radius && _satellites[i][j].amount == 0) || - (!apply_with_radius && _satellites[i][j].amount != 0)) - { + (!apply_with_radius && _satellites[i][j].amount != 0)) { continue; } - + if (_satellites[i][j].selected || !only_selected) { if (!use_knot_distance && !flexible) { if (previous_index) { - _satellites[i][j].amount = _satellites[i][j].radToLen(power, _pathvector[i][*previous_index], _pathvector[i][j]); + _satellites[i][j].amount = + _satellites[i][j].radToLen(power, _pathvector[i][*previous_index], _pathvector[i][j]); if (power && !_satellites[i][j].amount) { g_warning("Seems a too high radius value"); } @@ -159,23 +158,22 @@ void PathVectorSatellites::convertUnit(Glib::ustring in, Glib::ustring to, bool continue; } if ((!apply_no_radius && _satellites[i][j].amount == 0) || - (!apply_with_radius && _satellites[i][j].amount != 0)) - { + (!apply_with_radius && _satellites[i][j].amount != 0)) { continue; } - _satellites[i][j].amount = Inkscape::Util::Quantity::convert(_satellites[i][j].amount, in.c_str(), to.c_str()); + _satellites[i][j].amount = + Inkscape::Util::Quantity::convert(_satellites[i][j].amount, in.c_str(), to.c_str()); } } } -void PathVectorSatellites::updateSatelliteType(SatelliteType satellitetype, bool apply_no_radius, bool apply_with_radius, - bool only_selected) +void PathVectorSatellites::updateSatelliteType(SatelliteType satellitetype, bool apply_no_radius, + bool apply_with_radius, bool only_selected) { for (size_t i = 0; i < _satellites.size(); ++i) { for (size_t j = 0; j < _satellites[i].size(); ++j) { if ((!apply_no_radius && _satellites[i][j].amount == 0) || - (!apply_with_radius && _satellites[i][j].amount != 0)) - { + (!apply_with_radius && _satellites[i][j].amount != 0)) { continue; } if (count_path_nodes(_pathvector[i]) == j) { @@ -203,10 +201,10 @@ void PathVectorSatellites::recalculateForNewPathVector(Geom::PathVector const pa // * _pathvector and satellites (old data) are paired Satellites satellites; bool found = false; - //TODO evaluate fix on nodes at same position + // TODO evaluate fix on nodes at same position // size_t number_nodes = count_pathvector_nodes(pathv); // size_t previous_number_nodes = getTotalSatellites(); - for (const auto & i : pathv) { + for (const auto &i : pathv) { std::vector path_satellites; size_t count = count_path_nodes(i); for (size_t j = 0; j < count; j++) { @@ -214,7 +212,7 @@ void PathVectorSatellites::recalculateForNewPathVector(Geom::PathVector const pa for (size_t k = 0; k < _pathvector.size(); k++) { size_t count2 = count_path_nodes(_pathvector[k]); for (size_t l = 0; l < count2; l++) { - if (Geom::are_near(_pathvector[k][l].initialPoint(), i[j].initialPoint())) { + if (Geom::are_near(_pathvector[k][l].initialPoint(), i[j].initialPoint())) { path_satellites.push_back(_satellites[k][l]); found = true; break; diff --git a/src/helper/geom-pathvectorsatellites.h b/src/helper/geom-pathvectorsatellites.h index 3009081bbe854b0120a75703c5c130249d74a19d..11ddcc28c52a467e9afc8fa4718f521bc3aee385 100644 --- a/src/helper/geom-pathvectorsatellites.h +++ b/src/helper/geom-pathvectorsatellites.h @@ -16,17 +16,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #ifndef SEEN_PATHVECTORSATELLITES_H #define SEEN_PATHVECTORSATELLITES_H -#include #include <2geom/path.h> #include <2geom/pathvector.h> +#include -typedef std::vector > Satellites; +typedef std::vector> Satellites; ///@brief PathVectorSatellites a class to manage satellites in a pathvector -class PathVectorSatellites { +class PathVectorSatellites +{ public: Geom::PathVector getPathVector() const; void setPathVector(Geom::PathVector pathv); @@ -35,18 +35,20 @@ public: size_t getTotalSatellites(); void setSelected(std::vector selected); void updateSteps(size_t steps, bool apply_no_radius, bool apply_with_radius, bool only_selected); - void updateAmount(double radius, bool apply_no_radius, bool apply_with_radius, bool only_selected, + void updateAmount(double radius, bool apply_no_radius, bool apply_with_radius, bool only_selected, bool use_knot_distance, bool flexible); void convertUnit(Glib::ustring in, Glib::ustring to, bool apply_no_radius, bool apply_with_radius); - void updateSatelliteType(SatelliteType satellitetype, bool apply_no_radius, bool apply_with_radius, bool only_selected); + void updateSatelliteType(SatelliteType satellitetype, bool apply_no_radius, bool apply_with_radius, + bool only_selected); std::pair getIndexData(size_t index); void recalculateForNewPathVector(Geom::PathVector const pathv, Satellite const S); + private: Geom::PathVector _pathvector; Satellites _satellites; }; -#endif //SEEN_PATHVECTORSATELLITES_H +#endif // SEEN_PATHVECTORSATELLITES_H /* Local Variables: mode:c++ diff --git a/src/helper/geom-satellite.cpp b/src/helper/geom-satellite.cpp index 0d8ca832ce23a84471e3858892131b097f9b470c..2ca339589b09f565326039b36cd6f7efaa1802f7 100644 --- a/src/helper/geom-satellite.cpp +++ b/src/helper/geom-satellite.cpp @@ -10,43 +10,42 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include <2geom/curve.h> #include <2geom/nearest-time.h> #include <2geom/path-intersection.h> -#include <2geom/sbasis-to-bezier.h> #include <2geom/ray.h> +#include <2geom/sbasis-to-bezier.h> #include +#include // log cache #ifdef _WIN32 #include #else -#include #include +#include #endif ///@brief Satellite a per node holder of data. Satellite::Satellite() = default; - Satellite::Satellite(SatelliteType satellite_type) - : satellite_type(satellite_type), - is_time(false), - selected(false), - has_mirror(false), - hidden(true), - amount(0.0), - angle(0.0), - steps(0) + : satellite_type(satellite_type) + , is_time(false) + , selected(false) + , has_mirror(false) + , hidden(true) + , amount(0.0) + , angle(0.0) + , steps(0) {} Satellite::~Satellite() = default; -///Calculate the time in curve_in with a size of A -//TODO: find a better place to it +/// Calculate the time in curve_in with a size of A +// TODO: find a better place to it double timeAtArcLength(double const A, Geom::Curve const &curve_in) { - if ( A == 0 || curve_in.isDegenerate()) { + if (A == 0 || curve_in.isDegenerate()) { return 0; } @@ -66,11 +65,11 @@ double timeAtArcLength(double const A, Geom::Curve const &curve_in) return t; } -///Calculate the size in curve_in with a point at A -//TODO: find a better place to it +/// Calculate the size in curve_in with a point at A +// TODO: find a better place to it double arcLengthAt(double const A, Geom::Curve const &curve_in) { - if ( A == 0 || curve_in.isDegenerate()) { + if (A == 0 || curve_in.isDegenerate()) { return 0; } @@ -86,20 +85,17 @@ double arcLengthAt(double const A, Geom::Curve const &curve_in) return s; } -///Convert a arc radius of a fillet/chamfer to his satellite length -point position where fillet/chamfer knot be on original curve -double Satellite::radToLen( - double const A, Geom::Curve const &curve_in, - Geom::Curve const &curve_out) const +/// Convert a arc radius of a fillet/chamfer to his satellite length -point position where fillet/chamfer knot be on +/// original curve +double Satellite::radToLen(double const A, Geom::Curve const &curve_in, Geom::Curve const &curve_out) const { double len = 0; Geom::D2 d2_in = curve_in.toSBasis(); Geom::D2 d2_out = curve_out.toSBasis(); - Geom::Piecewise > offset_curve0 = - Geom::Piecewise >(d2_in) + - rot90(unitVector(derivative(d2_in))) * (A); - Geom::Piecewise > offset_curve1 = - Geom::Piecewise >(d2_out) + - rot90(unitVector(derivative(d2_out))) * (A); + Geom::Piecewise> offset_curve0 = + Geom::Piecewise>(d2_in) + rot90(unitVector(derivative(d2_in))) * (A); + Geom::Piecewise> offset_curve1 = + Geom::Piecewise>(d2_out) + rot90(unitVector(derivative(d2_out))) * (A); offset_curve0[0][0].normalize(); offset_curve0[0][1].normalize(); Geom::Path p0 = path_from_piecewise(offset_curve0, 0.1)[0]; @@ -119,11 +115,10 @@ double Satellite::radToLen( return len; } -///Convert a satellite length -point position where fillet/chamfer knot be on original curve- to a arc radius of fillet/chamfer -double Satellite::lenToRad( - double const A, Geom::Curve const &curve_in, - Geom::Curve const &curve_out, - Satellite const previousSatellite) const +/// Convert a satellite length -point position where fillet/chamfer knot be on original curve- to a arc radius of +/// fillet/chamfer +double Satellite::lenToRad(double const A, Geom::Curve const &curve_in, Geom::Curve const &curve_out, + Satellite const previousSatellite) const { double time_in = (previousSatellite).time(A, true, curve_in); double time_out = timeAtArcLength(A, curve_out); @@ -141,10 +136,8 @@ double Satellite::lenToRad( if (cubic2) { ray2.setPoints(end_arc_point, (*cubic2)[1]); } - bool ccw_toggle = cross(curve_in.pointAt(1) - start_arc_point, - end_arc_point - start_arc_point) < 0; - double distance_arc = - Geom::distance(start_arc_point, middle_point(start_arc_point, end_arc_point)); + bool ccw_toggle = cross(curve_in.pointAt(1) - start_arc_point, end_arc_point - start_arc_point) < 0; + double distance_arc = Geom::distance(start_arc_point, middle_point(start_arc_point, end_arc_point)); double angle = angle_between(ray1, ray2, ccw_toggle); double divisor = std::sin(angle / 2.0); if (divisor > 0) { @@ -153,14 +146,14 @@ double Satellite::lenToRad( return 0; } -///Get the time position of the satellite in curve_in +/// Get the time position of the satellite in curve_in double Satellite::time(Geom::Curve const &curve_in, bool inverse) const { double t = amount; if (!is_time) { t = time(t, inverse, curve_in); } else if (inverse) { - t = 1-t; + t = 1 - t; } if (t > 1) { t = 1; @@ -168,9 +161,8 @@ double Satellite::time(Geom::Curve const &curve_in, bool inverse) const return t; } -///Get the time from a length A in other curve, a boolean inverse given to reverse time -double Satellite::time(double A, bool inverse, - Geom::Curve const &curve_in) const +/// Get the time from a length A in other curve, a boolean inverse given to reverse time +double Satellite::time(double A, bool inverse, Geom::Curve const &curve_in) const { if (A == 0 && inverse) { return 1; @@ -186,7 +178,7 @@ double Satellite::time(double A, bool inverse, return timeAtArcLength(A, curve_in); } -///Get the length of the satellite in curve_in +/// Get the length of the satellite in curve_in double Satellite::arcDistance(Geom::Curve const &curve_in) const { double s = amount; @@ -196,17 +188,17 @@ double Satellite::arcDistance(Geom::Curve const &curve_in) const return s; } -///Get the point position of the satellite +/// Get the point position of the satellite Geom::Point Satellite::getPosition(Geom::Curve const &curve_in, bool inverse) const { double t = time(curve_in, inverse); return curve_in.pointAt(t); } -///Set the position of the satellite from a given point P +/// Set the position of the satellite from a given point P void Satellite::setPosition(Geom::Point const p, Geom::Curve const &curve_in, bool inverse) { - Geom::Curve * curve = const_cast(&curve_in); + Geom::Curve *curve = const_cast(&curve_in); if (inverse) { curve = curve->reverse(); } @@ -217,23 +209,22 @@ void Satellite::setPosition(Geom::Point const p, Geom::Curve const &curve_in, bo amount = A; } - -///Map a satellite type with gchar +/// Map a satellite type with gchar void Satellite::setSatelliteType(gchar const *A) { - std::map gchar_map_to_satellite_type = - boost::assign::map_list_of("F", FILLET)("IF", INVERSE_FILLET)("C", CHAMFER)("IC", INVERSE_CHAMFER)("KO", INVALID_SATELLITE); + std::map gchar_map_to_satellite_type = boost::assign::map_list_of("F", FILLET)( + "IF", INVERSE_FILLET)("C", CHAMFER)("IC", INVERSE_CHAMFER)("KO", INVALID_SATELLITE); std::map::iterator it = gchar_map_to_satellite_type.find(std::string(A)); if (it != gchar_map_to_satellite_type.end()) { satellite_type = it->second; } } -///Map a gchar with satelliteType +/// Map a gchar with satelliteType gchar const *Satellite::getSatelliteTypeGchar() const { - std::map satellite_type_to_gchar_map = - boost::assign::map_list_of(FILLET, "F")(INVERSE_FILLET, "IF")(CHAMFER, "C")(INVERSE_CHAMFER, "IC")(INVALID_SATELLITE, "KO"); + std::map satellite_type_to_gchar_map = boost::assign::map_list_of(FILLET, "F")( + INVERSE_FILLET, "IF")(CHAMFER, "C")(INVERSE_CHAMFER, "IC")(INVALID_SATELLITE, "KO"); return satellite_type_to_gchar_map.at(satellite_type); } diff --git a/src/helper/geom-satellite.h b/src/helper/geom-satellite.h index 5fbcae159ecb6670925df1c50d26162a1f638890..badd6d256dd84ae97c4ebf58d71642851b49a23d 100644 --- a/src/helper/geom-satellite.h +++ b/src/helper/geom-satellite.h @@ -13,63 +13,41 @@ #ifndef SEEN_SATELLITE_H #define SEEN_SATELLITE_H -#include -#include #include <2geom/sbasis-geometric.h> -#include "util/enums.h" +#include +#include +#include "util/enums.h" -enum SatelliteType { - FILLET = 0, //Fillet - INVERSE_FILLET, //Inverse Fillet - CHAMFER, //Chamfer - INVERSE_CHAMFER, //Inverse Chamfer - INVALID_SATELLITE // Invalid Satellite +enum SatelliteType +{ + FILLET = 0, // Fillet + INVERSE_FILLET, // Inverse Fillet + CHAMFER, // Chamfer + INVERSE_CHAMFER, // Inverse Chamfer + INVALID_SATELLITE // Invalid Satellite }; /** * @brief Satellite a per node holder of data. */ -class Satellite { +class Satellite +{ public: - Satellite(); Satellite(SatelliteType satellite_type); virtual ~Satellite(); - void setIsTime(bool set_is_time) - { - is_time = set_is_time; - } - void setSelected(bool set_selected) - { - selected = set_selected; - } - void setHasMirror(bool set_has_mirror) - { - has_mirror = set_has_mirror; - } - void setHidden(bool set_hidden) - { - hidden = set_hidden; - } - void setAmount(double set_amount) - { - amount = set_amount; - } - void setAngle(double set_angle) - { - angle = set_angle; - } - void setSteps(size_t set_steps) - { - steps = set_steps; - } - double lenToRad(double const A, Geom::Curve const &curve_in, - Geom::Curve const &curve_out, + void setIsTime(bool set_is_time) { is_time = set_is_time; } + void setSelected(bool set_selected) { selected = set_selected; } + void setHasMirror(bool set_has_mirror) { has_mirror = set_has_mirror; } + void setHidden(bool set_hidden) { hidden = set_hidden; } + void setAmount(double set_amount) { amount = set_amount; } + void setAngle(double set_angle) { angle = set_angle; } + void setSteps(size_t set_steps) { steps = set_steps; } + double lenToRad(double const A, Geom::Curve const &curve_in, Geom::Curve const &curve_out, Satellite const previousSatellite) const; - double radToLen(double const A, Geom::Curve const &curve_in, - Geom::Curve const &curve_out) const; + double radToLen(double const A, Geom::Curve const &curve_in, Geom::Curve const &curve_out) const; double time(Geom::Curve const &curve_in, bool inverse = false) const; double time(double A, bool inverse, Geom::Curve const &curve_in) const; @@ -81,13 +59,13 @@ public: void setSatelliteType(gchar const *A); gchar const *getSatelliteTypeGchar() const; SatelliteType satellite_type; - //The value stored could be a time value of the satellite in the curve or a length of distance to the node from the satellite - //"is_time" tells us if it's a time or length value + // The value stored could be a time value of the satellite in the curve or a length of distance to the node from the + // satellite "is_time" tells us if it's a time or length value bool is_time; bool selected; bool has_mirror; bool hidden; - //in "amount" we store the time or distance used in the satellite + // in "amount" we store the time or distance used in the satellite double amount; double angle; size_t steps; diff --git a/src/helper/geom.cpp b/src/helper/geom.cpp index 5e8e763f5dc415d71769d08e7d024f3ee66c43d5..3069dbc17b0d74b2838cd6e9a58bbbcf48deabc1 100644 --- a/src/helper/geom.cpp +++ b/src/helper/geom.cpp @@ -10,11 +10,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "helper/geom.h" -#include "helper/geom-curves.h" + #include <2geom/curves.h> #include <2geom/sbasis-to-bezier.h> +#include + +#include "helper/geom-curves.h" using Geom::X; using Geom::Y; @@ -24,8 +26,8 @@ using Geom::Y; /* Fast bbox calculation */ /* Thanks to Nathan Hurst for suggesting it */ -static void -cubic_bbox (Geom::Coord x000, Geom::Coord y000, Geom::Coord x001, Geom::Coord y001, Geom::Coord x011, Geom::Coord y011, Geom::Coord x111, Geom::Coord y111, Geom::Rect &bbox) +static void cubic_bbox(Geom::Coord x000, Geom::Coord y000, Geom::Coord x001, Geom::Coord y001, Geom::Coord x011, + Geom::Coord y011, Geom::Coord x111, Geom::Coord y111, Geom::Rect &bbox) { Geom::Coord a, b, c, D; @@ -40,20 +42,16 @@ cubic_bbox (Geom::Coord x000, Geom::Coord y000, Geom::Coord x001, Geom::Coord y0 bool containsYrange = bbox[1].contains(y001) && bbox[1].contains(y011); /* - * xttt = s * (s * (s * x000 + t * x001) + t * (s * x001 + t * x011)) + t * (s * (s * x001 + t * x011) + t * (s * x011 + t * x111)) - * xttt = s * (s2 * x000 + s * t * x001 + t * s * x001 + t2 * x011) + t * (s2 * x001 + s * t * x011 + t * s * x011 + t2 * x111) - * xttt = s * (s2 * x000 + 2 * st * x001 + t2 * x011) + t * (s2 * x001 + 2 * st * x011 + t2 * x111) - * xttt = s3 * x000 + 2 * s2t * x001 + st2 * x011 + s2t * x001 + 2st2 * x011 + t3 * x111 - * xttt = s3 * x000 + 3s2t * x001 + 3st2 * x011 + t3 * x111 - * xttt = s3 * x000 + (1 - s) 3s2 * x001 + (1 - s) * (1 - s) * 3s * x011 + (1 - s) * (1 - s) * (1 - s) * x111 - * xttt = s3 * x000 + (3s2 - 3s3) * x001 + (3s - 6s2 + 3s3) * x011 + (1 - 2s + s2 - s + 2s2 - s3) * x111 - * xttt = (x000 - 3 * x001 + 3 * x011 - x111) * s3 + - * ( 3 * x001 - 6 * x011 + 3 * x111) * s2 + - * ( 3 * x011 - 3 * x111) * s + - * ( x111) - * xttt' = (3 * x000 - 9 * x001 + 9 * x011 - 3 * x111) * s2 + - * ( 6 * x001 - 12 * x011 + 6 * x111) * s + - * ( 3 * x011 - 3 * x111) + * xttt = s * (s * (s * x000 + t * x001) + t * (s * x001 + t * x011)) + t * (s * (s * x001 + t * x011) + t * (s * + * x011 + t * x111)) xttt = s * (s2 * x000 + s * t * x001 + t * s * x001 + t2 * x011) + t * (s2 * x001 + s * t * + * x011 + t * s * x011 + t2 * x111) xttt = s * (s2 * x000 + 2 * st * x001 + t2 * x011) + t * (s2 * x001 + 2 * st * + * x011 + t2 * x111) xttt = s3 * x000 + 2 * s2t * x001 + st2 * x011 + s2t * x001 + 2st2 * x011 + t3 * x111 xttt = s3 + * * x000 + 3s2t * x001 + 3st2 * x011 + t3 * x111 xttt = s3 * x000 + (1 - s) 3s2 * x001 + (1 - s) * (1 - s) * 3s * + * x011 + (1 - s) * (1 - s) * (1 - s) * x111 xttt = s3 * x000 + (3s2 - 3s3) * x001 + (3s - 6s2 + 3s3) * x011 + (1 - + * 2s + s2 - s + 2s2 - s3) * x111 xttt = (x000 - 3 * x001 + 3 * x011 - x111) * s3 + ( 3 * x001 - 6 * x011 + * + 3 * x111) * s2 + ( 3 * x011 - 3 * x111) * s + ( x111) xttt' = + * (3 * x000 - 9 * x001 + 9 * x011 - 3 * x111) * s2 + ( 6 * x001 - 12 * x011 + 6 * x111) * s + ( 3 * + * x011 - 3 * x111) */ if (!containsXrange) { @@ -62,11 +60,11 @@ cubic_bbox (Geom::Coord x000, Geom::Coord y000, Geom::Coord x001, Geom::Coord y0 c = 3 * x011 - 3 * x111; /* - * s = (-b +/- sqrt (b * b - 4 * a * c)) / 2 * a; - */ - if (fabs (a) < Geom::EPSILON) { + * s = (-b +/- sqrt (b * b - 4 * a * c)) / 2 * a; + */ + if (fabs(a) < Geom::EPSILON) { /* s = -c / b */ - if (fabs (b) > Geom::EPSILON) { + if (fabs(b) > Geom::EPSILON) { double s; s = -c / b; if ((s > 0.0) && (s < 1.0)) { @@ -81,7 +79,7 @@ cubic_bbox (Geom::Coord x000, Geom::Coord y000, Geom::Coord x001, Geom::Coord y0 if (D >= 0.0) { Geom::Coord d, s, t, xttt; /* Have solution */ - d = sqrt (D); + d = sqrt(D); s = (-b + d) / (2 * a); if ((s > 0.0) && (s < 1.0)) { t = 1.0 - s; @@ -103,9 +101,9 @@ cubic_bbox (Geom::Coord x000, Geom::Coord y000, Geom::Coord x001, Geom::Coord y0 b = 6 * y001 - 12 * y011 + 6 * y111; c = 3 * y011 - 3 * y111; - if (fabs (a) < Geom::EPSILON) { + if (fabs(a) < Geom::EPSILON) { /* s = -c / b */ - if (fabs (b) > Geom::EPSILON) { + if (fabs(b) > Geom::EPSILON) { double s; s = -c / b; if ((s > 0.0) && (s < 1.0)) { @@ -120,7 +118,7 @@ cubic_bbox (Geom::Coord x000, Geom::Coord y000, Geom::Coord x001, Geom::Coord y0 if (D >= 0.0) { Geom::Coord d, s, t, yttt; /* Have solution */ - d = sqrt (D); + d = sqrt(D); s = (-b + d) / (2 * a); if ((s > 0.0) && (s < 1.0)) { t = 1.0 - s; @@ -138,23 +136,21 @@ cubic_bbox (Geom::Coord x000, Geom::Coord y000, Geom::Coord x001, Geom::Coord y0 } } -Geom::OptRect -bounds_fast_transformed(Geom::PathVector const & pv, Geom::Affine const & t) +Geom::OptRect bounds_fast_transformed(Geom::PathVector const &pv, Geom::Affine const &t) { - return bounds_exact_transformed(pv, t); //use this as it is faster for now! :) -// return Geom::bounds_fast(pv * t); + return bounds_exact_transformed(pv, t); // use this as it is faster for now! :) + // return Geom::bounds_fast(pv * t); } -Geom::OptRect -bounds_exact_transformed(Geom::PathVector const & pv, Geom::Affine const & t) +Geom::OptRect bounds_exact_transformed(Geom::PathVector const &pv, Geom::Affine const &t) { if (pv.empty()) return Geom::OptRect(); Geom::Point initial = pv.front().initialPoint() * t; - Geom::Rect bbox(initial, initial); // obtain well defined bbox as starting point to unionWith + Geom::Rect bbox(initial, initial); // obtain well defined bbox as starting point to unionWith - for (const auto & it : pv) { + for (const auto &it : pv) { bbox.expandTo(it.initialPoint() * t); // don't loop including closing segment, since that segment can never increase the bbox @@ -162,18 +158,18 @@ bounds_exact_transformed(Geom::PathVector const & pv, Geom::Affine const & t) Geom::Curve const &c = *cit; unsigned order = 0; - if (Geom::BezierCurve const* b = dynamic_cast(&c)) { + if (Geom::BezierCurve const *b = dynamic_cast(&c)) { order = b->order(); } if (order == 1) { // line segment bbox.expandTo(c.finalPoint() * t); - // TODO: we can make the case for quadratics faster by degree elevating them to - // cubic and then taking the bbox of that. + // TODO: we can make the case for quadratics faster by degree elevating them to + // cubic and then taking the bbox of that. } else if (order == 3) { // cubic bezier - Geom::CubicBezier const &cubic_bezier = static_cast(c); + Geom::CubicBezier const &cubic_bezier = static_cast(c); Geom::Point c0 = cubic_bezier[0] * t; Geom::Point c1 = cubic_bezier[1] * t; Geom::Point c2 = cubic_bezier[2] * t; @@ -182,19 +178,17 @@ bounds_exact_transformed(Geom::PathVector const & pv, Geom::Affine const & t) } else { // should handle all not-so-easy curves: Geom::Curve *ctemp = cit->transformed(t); - bbox.unionWith( ctemp->boundsExact()); + bbox.unionWith(ctemp->boundsExact()); delete ctemp; } } } - //return Geom::bounds_exact(pv * t); + // return Geom::bounds_exact(pv * t); return bbox; } - - -static void -geom_line_wind_distance (Geom::Coord x0, Geom::Coord y0, Geom::Coord x1, Geom::Coord y1, Geom::Point const &pt, int *wind, Geom::Coord *best) +static void geom_line_wind_distance(Geom::Coord x0, Geom::Coord y0, Geom::Coord x1, Geom::Coord y1, + Geom::Point const &pt, int *wind, Geom::Coord *best) { Geom::Coord Ax, Ay, Bx, By, Dx, Dy, s; Geom::Coord dist2; @@ -222,21 +216,28 @@ geom_line_wind_distance (Geom::Coord x0, Geom::Coord y0, Geom::Coord x1, Geom::C dist2 = (Px - Qx) * (Px - Qx) + (Py - Qy) * (Py - Qy); } - if (dist2 < (*best * *best)) *best = sqrt (dist2); + if (dist2 < (*best * *best)) + *best = sqrt(dist2); } if (wind) { /* Find wind */ - if ((Ax >= Px) && (Bx >= Px)) return; - if ((Ay >= Py) && (By >= Py)) return; - if ((Ay < Py) && (By < Py)) return; - if (Ay == By) return; + if ((Ax >= Px) && (Bx >= Px)) + return; + if ((Ay >= Py) && (By >= Py)) + return; + if ((Ay < Py) && (By < Py)) + return; + if (Ay == By) + return; /* Ctach upper y bound */ if (Ay == Py) { - if (Ax < Px) *wind -= 1; + if (Ax < Px) + *wind -= 1; return; } else if (By == Py) { - if (Bx < Px) *wind += 1; + if (Bx < Px) + *wind += 1; return; } else { Geom::Coord Qx; @@ -249,14 +250,10 @@ geom_line_wind_distance (Geom::Coord x0, Geom::Coord y0, Geom::Coord x1, Geom::C } } -static void -geom_cubic_bbox_wind_distance (Geom::Coord x000, Geom::Coord y000, - Geom::Coord x001, Geom::Coord y001, - Geom::Coord x011, Geom::Coord y011, - Geom::Coord x111, Geom::Coord y111, - Geom::Point const &pt, - Geom::Rect *bbox, int *wind, Geom::Coord *best, - Geom::Coord tolerance) +static void geom_cubic_bbox_wind_distance(Geom::Coord x000, Geom::Coord y000, Geom::Coord x001, Geom::Coord y001, + Geom::Coord x011, Geom::Coord y011, Geom::Coord x111, Geom::Coord y111, + Geom::Point const &pt, Geom::Rect *bbox, int *wind, Geom::Coord *best, + Geom::Coord tolerance) { Geom::Coord x0, y0, x1, y1, len2; int needdist, needwind; @@ -267,27 +264,30 @@ geom_cubic_bbox_wind_distance (Geom::Coord x000, Geom::Coord y000, needdist = 0; needwind = 0; - if (bbox) cubic_bbox (x000, y000, x001, y001, x011, y011, x111, y111, *bbox); - - x0 = std::min (x000, x001); - x0 = std::min (x0, x011); - x0 = std::min (x0, x111); - y0 = std::min (y000, y001); - y0 = std::min (y0, y011); - y0 = std::min (y0, y111); - x1 = std::max (x000, x001); - x1 = std::max (x1, x011); - x1 = std::max (x1, x111); - y1 = std::max (y000, y001); - y1 = std::max (y1, y011); - y1 = std::max (y1, y111); + if (bbox) + cubic_bbox(x000, y000, x001, y001, x011, y011, x111, y111, *bbox); + + x0 = std::min(x000, x001); + x0 = std::min(x0, x011); + x0 = std::min(x0, x111); + y0 = std::min(y000, y001); + y0 = std::min(y0, y011); + y0 = std::min(y0, y111); + x1 = std::max(x000, x001); + x1 = std::max(x1, x011); + x1 = std::max(x1, x111); + y1 = std::max(y000, y001); + y1 = std::max(y1, y011); + y1 = std::max(y1, y111); if (best) { /* Quickly adjust to endpoints */ len2 = (x000 - Px) * (x000 - Px) + (y000 - Py) * (y000 - Py); - if (len2 < (*best * *best)) *best = (Geom::Coord) sqrt (len2); + if (len2 < (*best * *best)) + *best = (Geom::Coord)sqrt(len2); len2 = (x111 - Px) * (x111 - Px) + (y111 - Py) * (y111 - Py); - if (len2 < (*best * *best)) *best = (Geom::Coord) sqrt (len2); + if (len2 < (*best * *best)) + *best = (Geom::Coord)sqrt(len2); if (((x0 - Px) < *best) && ((y0 - Py) < *best) && ((Px - x1) < *best) && ((Py - y1) < *best)) { /* Point is inside sloppy bbox */ @@ -331,22 +331,23 @@ geom_cubic_bbox_wind_distance (Geom::Coord x000, Geom::Coord y000, y1tt = s * y01t + t * y11t; yttt = s * y0tt + t * y1tt; - geom_cubic_bbox_wind_distance (x000, y000, x00t, y00t, x0tt, y0tt, xttt, yttt, pt, nullptr, wind, best, tolerance); - geom_cubic_bbox_wind_distance (xttt, yttt, x1tt, y1tt, x11t, y11t, x111, y111, pt, nullptr, wind, best, tolerance); + geom_cubic_bbox_wind_distance(x000, y000, x00t, y00t, x0tt, y0tt, xttt, yttt, pt, nullptr, wind, best, + tolerance); + geom_cubic_bbox_wind_distance(xttt, yttt, x1tt, y1tt, x11t, y11t, x111, y111, pt, nullptr, wind, best, + tolerance); } else { - geom_line_wind_distance (x000, y000, x111, y111, pt, wind, best); + geom_line_wind_distance(x000, y000, x111, y111, pt, wind, best); } } -static void -geom_curve_bbox_wind_distance(Geom::Curve const & c, Geom::Affine const &m, - Geom::Point const &pt, - Geom::Rect *bbox, int *wind, Geom::Coord *dist, - Geom::Coord tolerance, Geom::Rect const *viewbox, - Geom::Point &p0) // pass p0 through as it represents the last endpoint added (the finalPoint of last curve) +static void geom_curve_bbox_wind_distance(Geom::Curve const &c, Geom::Affine const &m, Geom::Point const &pt, + Geom::Rect *bbox, int *wind, Geom::Coord *dist, Geom::Coord tolerance, + Geom::Rect const *viewbox, + Geom::Point &p0) // pass p0 through as it represents the last endpoint added + // (the finalPoint of last curve) { unsigned order = 0; - if (Geom::BezierCurve const* b = dynamic_cast(&c)) { + if (Geom::BezierCurve const *b = dynamic_cast(&c)) { order = b->order(); } if (order == 1) { @@ -356,17 +357,16 @@ geom_curve_bbox_wind_distance(Geom::Curve const & c, Geom::Affine const &m, } if (dist || wind) { if (wind) { // we need to pick fill, so do what we're told - geom_line_wind_distance (p0[X], p0[Y], pe[X], pe[Y], pt, wind, dist); + geom_line_wind_distance(p0[X], p0[Y], pe[X], pe[Y], pt, wind, dist); } else { // only stroke is being picked; skip this segment if it's totally outside the viewbox Geom::Rect swept(p0, pe); if (!viewbox || swept.intersects(*viewbox)) - geom_line_wind_distance (p0[X], p0[Y], pe[X], pe[Y], pt, wind, dist); + geom_line_wind_distance(p0[X], p0[Y], pe[X], pe[Y], pt, wind, dist); } } p0 = pe; - } - else if (order == 3) { - Geom::CubicBezier const& cubic_bezier = static_cast(c); + } else if (order == 3) { + Geom::CubicBezier const &cubic_bezier = static_cast(c); Geom::Point p1 = cubic_bezier[1] * m; Geom::Point p2 = cubic_bezier[2] * m; Geom::Point p3 = cubic_bezier[3] * m; @@ -377,25 +377,21 @@ geom_curve_bbox_wind_distance(Geom::Curve const & c, Geom::Affine const &m, swept.expandTo(p2); if (!viewbox || swept.intersects(*viewbox)) { // we see this segment, so do full processing - geom_cubic_bbox_wind_distance ( p0[X], p0[Y], - p1[X], p1[Y], - p2[X], p2[Y], - p3[X], p3[Y], - pt, - bbox, wind, dist, tolerance); + geom_cubic_bbox_wind_distance(p0[X], p0[Y], p1[X], p1[Y], p2[X], p2[Y], p3[X], p3[Y], pt, bbox, wind, dist, + tolerance); } else { if (wind) { // if we need fill, we can just pretend it's a straight line - geom_line_wind_distance (p0[X], p0[Y], p3[X], p3[Y], pt, wind, dist); + geom_line_wind_distance(p0[X], p0[Y], p3[X], p3[Y], pt, wind, dist); } else { // otherwise, skip it completely } } p0 = p3; - } else { - //this case handles sbasis as well as all other curve types + } else { + // this case handles sbasis as well as all other curve types Geom::Path sbasis_path = Geom::cubicbezierpath_from_sbasis(c.toSBasis(), 0.1); - //recurse to convert the new path resulting from the sbasis to svgd - for (const auto & iter : sbasis_path) { + // recurse to convert the new path resulting from the sbasis to svgd + for (const auto &iter : sbasis_path) { geom_curve_bbox_wind_distance(iter, m, pt, bbox, wind, dist, tolerance, viewbox, p0); } } @@ -405,29 +401,29 @@ geom_curve_bbox_wind_distance(Geom::Curve const & c, Geom::Affine const &m, and returns ... in *wind and the distance to ... in *dist. Returns bounding box in *bbox if bbox!=NULL. */ -void -pathv_matrix_point_bbox_wind_distance (Geom::PathVector const & pathv, Geom::Affine const &m, Geom::Point const &pt, - Geom::Rect *bbox, int *wind, Geom::Coord *dist, - Geom::Coord tolerance, Geom::Rect const *viewbox) +void pathv_matrix_point_bbox_wind_distance(Geom::PathVector const &pathv, Geom::Affine const &m, Geom::Point const &pt, + Geom::Rect *bbox, int *wind, Geom::Coord *dist, Geom::Coord tolerance, + Geom::Rect const *viewbox) { if (pathv.empty()) { - if (wind) *wind = 0; - if (dist) *dist = Geom::infinity(); + if (wind) + *wind = 0; + if (dist) + *dist = Geom::infinity(); return; } // remember last point of last curve - Geom::Point p0(0,0); + Geom::Point p0(0, 0); // remembering the start of subpath - Geom::Point p_start(0,0); + Geom::Point p_start(0, 0); bool start_set = false; - for (const auto & it : pathv) { - - if (start_set) { // this is a new subpath + for (const auto &it : pathv) { + if (start_set) { // this is a new subpath if (wind && (p0 != p_start)) // for correct fill picking, each subpath must be closed - geom_line_wind_distance (p0[X], p0[Y], p_start[X], p_start[Y], pt, wind, dist); + geom_line_wind_distance(p0[X], p0[Y], p_start[X], p_start[Y], pt, wind, dist); } p0 = it.initialPoint() * m; p_start = p0; @@ -442,9 +438,9 @@ pathv_matrix_point_bbox_wind_distance (Geom::PathVector const & pathv, Geom::Aff } } - if (start_set) { + if (start_set) { if (wind && (p0 != p_start)) // for correct picking, each subpath must be closed - geom_line_wind_distance (p0[X], p0[Y], p_start[X], p_start[Y], pt, wind, dist); + geom_line_wind_distance(p0[X], p0[Y], p_start[X], p_start[Y], pt, wind, dist); } } @@ -454,15 +450,14 @@ pathv_matrix_point_bbox_wind_distance (Geom::PathVector const & pathv, Geom::Aff * Converts all segments in all paths to Geom::LineSegment or Geom::HLineSegment or * Geom::VLineSegment or Geom::CubicBezier. */ -Geom::PathVector -pathv_to_linear_and_cubic_beziers( Geom::PathVector const &pathv ) +Geom::PathVector pathv_to_linear_and_cubic_beziers(Geom::PathVector const &pathv) { Geom::PathVector output; - for (const auto & pit : pathv) { - output.push_back( Geom::Path() ); + for (const auto &pit : pathv) { + output.push_back(Geom::Path()); output.back().setStitching(true); - output.back().start( pit.initialPoint() ); + output.back().start(pit.initialPoint()); for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_open(); ++cit) { if (is_straight_curve(*cit)) { @@ -481,10 +476,10 @@ pathv_to_linear_and_cubic_beziers( Geom::PathVector const &pathv ) } } } - - output.back().close( pit.closed() ); + + output.back().close(pit.closed()); } - + return output; } @@ -496,25 +491,23 @@ pathv_to_linear_and_cubic_beziers( Geom::PathVector const &pathv ) * This is NOT a terribly fast method, but it should give a solution close to the one with the * fewest points. */ -Geom::PathVector -pathv_to_linear( Geom::PathVector const &pathv, double /*maxdisp*/) +Geom::PathVector pathv_to_linear(Geom::PathVector const &pathv, double /*maxdisp*/) { Geom::PathVector output; Geom::PathVector tmppath = pathv_to_linear_and_cubic_beziers(pathv); - + // Now all path segments are either already lines, or they are beziers. - for (const auto & pit : tmppath) { - output.push_back( Geom::Path() ); - output.back().start( pit.initialPoint() ); - output.back().close( pit.closed() ); + for (const auto &pit : tmppath) { + output.push_back(Geom::Path()); + output.back().start(pit.initialPoint()); + output.back().close(pit.closed()); for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_open(); ++cit) { if (is_straight_curve(*cit)) { Geom::LineSegment ls(cit->initialPoint(), cit->finalPoint()); output.back().append(ls); - } - else { /* all others must be Bezier curves */ + } else { /* all others must be Bezier curves */ Geom::BezierCurve const *curve = dynamic_cast(&*cit); std::vector bzrpoints = curve->controlPoints(); Geom::Point A = bzrpoints[0]; @@ -523,26 +516,20 @@ pathv_to_linear( Geom::PathVector const &pathv, double /*maxdisp*/) Geom::Point D = bzrpoints[3]; std::vector pointlist; pointlist.push_back(A); - recursive_bezier4( - A[X], A[Y], - B[X], B[Y], - C[X], C[Y], - D[X], D[Y], - pointlist, - 0); + recursive_bezier4(A[X], A[Y], B[X], B[Y], C[X], C[Y], D[X], D[Y], pointlist, 0); pointlist.push_back(D); Geom::Point r1 = pointlist[0]; - for (unsigned int i=1; i( pitCubic.initialPoint() ); + pitCubic.appendNew(pitCubic.initialPoint()); pitCubic.close(true); } for (Geom::Path::iterator cit = pitCubic.begin(); cit != pitCubic.end_open(); ++cit) { if (is_straight_curve(*cit)) { - Geom::CubicBezier b(cit->initialPoint(), cit->pointAt(0.3334) + Geom::Point(cubicGap,cubicGap), cit->finalPoint(), cit->finalPoint()); + Geom::CubicBezier b(cit->initialPoint(), cit->pointAt(0.3334) + Geom::Point(cubicGap, cubicGap), + cit->finalPoint(), cit->finalPoint()); output.back().append(b); } else { Geom::BezierCurve const *curve = dynamic_cast(&*cit); @@ -598,9 +585,9 @@ pathv_to_cubicbezier( Geom::PathVector const &pathv) return output; } -//Study move to 2Geom -size_t -count_pathvector_nodes(Geom::PathVector const &pathv) { +// Study move to 2Geom +size_t count_pathvector_nodes(Geom::PathVector const &pathv) +{ size_t tot = 0; for (auto subpath : pathv) { tot += count_path_nodes(subpath); @@ -633,119 +620,109 @@ size_t count_path_nodes(Geom::Path const &path) // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://antigrain.com -// +// // AGG 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. -// +// // AGG 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 AGG; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA. //---------------------------------------------------------------------------- -void -recursive_bezier4(const double x1, const double y1, - const double x2, const double y2, - const double x3, const double y3, - const double x4, const double y4, - std::vector &m_points, - int level) +void recursive_bezier4(const double x1, const double y1, const double x2, const double y2, const double x3, + const double y3, const double x4, const double y4, std::vector &m_points, int level) +{ + // some of these should be parameters, but do it this way for now. + const double curve_collinearity_epsilon = 1e-30; + const double curve_angle_tolerance_epsilon = 0.01; + double m_cusp_limit = 0.0; + double m_angle_tolerance = 0.0; + double m_approximation_scale = 1.0; + double m_distance_tolerance_square = 0.5 / m_approximation_scale; + m_distance_tolerance_square *= m_distance_tolerance_square; + enum curve_recursion_limit_e { - // some of these should be parameters, but do it this way for now. - const double curve_collinearity_epsilon = 1e-30; - const double curve_angle_tolerance_epsilon = 0.01; - double m_cusp_limit = 0.0; - double m_angle_tolerance = 0.0; - double m_approximation_scale = 1.0; - double m_distance_tolerance_square = 0.5 / m_approximation_scale; - m_distance_tolerance_square *= m_distance_tolerance_square; - enum curve_recursion_limit_e { curve_recursion_limit = 32 }; -#define calc_sq_distance(A,B,C,D) ((A-C)*(A-C) + (B-D)*(B-D)) - - if(level > curve_recursion_limit) - { - return; - } + curve_recursion_limit = 32 + }; +#define calc_sq_distance(A, B, C, D) ((A - C) * (A - C) + (B - D) * (B - D)) + if (level > curve_recursion_limit) { + return; + } - // Calculate all the mid-points of the line segments - //---------------------- - double x12 = (x1 + x2) / 2; - double y12 = (y1 + y2) / 2; - double x23 = (x2 + x3) / 2; - double y23 = (y2 + y3) / 2; - double x34 = (x3 + x4) / 2; - double y34 = (y3 + y4) / 2; - double x123 = (x12 + x23) / 2; - double y123 = (y12 + y23) / 2; - double x234 = (x23 + x34) / 2; - double y234 = (y23 + y34) / 2; - double x1234 = (x123 + x234) / 2; - double y1234 = (y123 + y234) / 2; - - - // Try to approximate the full cubic curve by a single straight line - //------------------ - double dx = x4-x1; - double dy = y4-y1; - - double d2 = fabs(((x2 - x4) * dy - (y2 - y4) * dx)); - double d3 = fabs(((x3 - x4) * dy - (y3 - y4) * dx)); - double da1, da2, k; - - switch((int(d2 > curve_collinearity_epsilon) << 1) + - int(d3 > curve_collinearity_epsilon)) - { + // Calculate all the mid-points of the line segments + //---------------------- + double x12 = (x1 + x2) / 2; + double y12 = (y1 + y2) / 2; + double x23 = (x2 + x3) / 2; + double y23 = (y2 + y3) / 2; + double x34 = (x3 + x4) / 2; + double y34 = (y3 + y4) / 2; + double x123 = (x12 + x23) / 2; + double y123 = (y12 + y23) / 2; + double x234 = (x23 + x34) / 2; + double y234 = (y23 + y34) / 2; + double x1234 = (x123 + x234) / 2; + double y1234 = (y123 + y234) / 2; + + // Try to approximate the full cubic curve by a single straight line + //------------------ + double dx = x4 - x1; + double dy = y4 - y1; + + double d2 = fabs(((x2 - x4) * dy - (y2 - y4) * dx)); + double d3 = fabs(((x3 - x4) * dy - (y3 - y4) * dx)); + double da1, da2, k; + + switch ((int(d2 > curve_collinearity_epsilon) << 1) + int(d3 > curve_collinearity_epsilon)) { case 0: // All collinear OR p1==p4 //---------------------- - k = dx*dx + dy*dy; - if(k == 0) - { + k = dx * dx + dy * dy; + if (k == 0) { d2 = calc_sq_distance(x1, y1, x2, y2); d3 = calc_sq_distance(x4, y4, x3, y3); - } - else - { - k = 1 / k; + } else { + k = 1 / k; da1 = x2 - x1; da2 = y2 - y1; - d2 = k * (da1*dx + da2*dy); + d2 = k * (da1 * dx + da2 * dy); da1 = x3 - x1; da2 = y3 - y1; - d3 = k * (da1*dx + da2*dy); - if(d2 > 0 && d2 < 1 && d3 > 0 && d3 < 1) - { + d3 = k * (da1 * dx + da2 * dy); + if (d2 > 0 && d2 < 1 && d3 > 0 && d3 < 1) { // Simple collinear case, 1---2---3---4 // We can leave just two endpoints return; } - if(d2 <= 0) d2 = calc_sq_distance(x2, y2, x1, y1); - else if(d2 >= 1) d2 = calc_sq_distance(x2, y2, x4, y4); - else d2 = calc_sq_distance(x2, y2, x1 + d2*dx, y1 + d2*dy); - - if(d3 <= 0) d3 = calc_sq_distance(x3, y3, x1, y1); - else if(d3 >= 1) d3 = calc_sq_distance(x3, y3, x4, y4); - else d3 = calc_sq_distance(x3, y3, x1 + d3*dx, y1 + d3*dy); + if (d2 <= 0) + d2 = calc_sq_distance(x2, y2, x1, y1); + else if (d2 >= 1) + d2 = calc_sq_distance(x2, y2, x4, y4); + else + d2 = calc_sq_distance(x2, y2, x1 + d2 * dx, y1 + d2 * dy); + + if (d3 <= 0) + d3 = calc_sq_distance(x3, y3, x1, y1); + else if (d3 >= 1) + d3 = calc_sq_distance(x3, y3, x4, y4); + else + d3 = calc_sq_distance(x3, y3, x1 + d3 * dx, y1 + d3 * dy); } - if(d2 > d3) - { - if(d2 < m_distance_tolerance_square) - { + if (d2 > d3) { + if (d2 < m_distance_tolerance_square) { m_points.emplace_back(x2, y2); return; } - } - else - { - if(d3 < m_distance_tolerance_square) - { + } else { + if (d3 < m_distance_tolerance_square) { m_points.emplace_back(x3, y3); return; } @@ -755,10 +732,8 @@ recursive_bezier4(const double x1, const double y1, case 1: // p1,p2,p4 are collinear, p3 is significant //---------------------- - if(d3 * d3 <= m_distance_tolerance_square * (dx*dx + dy*dy)) - { - if(m_angle_tolerance < curve_angle_tolerance_epsilon) - { + if (d3 * d3 <= m_distance_tolerance_square * (dx * dx + dy * dy)) { + if (m_angle_tolerance < curve_angle_tolerance_epsilon) { m_points.emplace_back(x23, y23); return; } @@ -766,19 +741,17 @@ recursive_bezier4(const double x1, const double y1, // Angle Condition //---------------------- da1 = fabs(atan2(y4 - y3, x4 - x3) - atan2(y3 - y2, x3 - x2)); - if(da1 >= M_PI) da1 = 2*M_PI - da1; + if (da1 >= M_PI) + da1 = 2 * M_PI - da1; - if(da1 < m_angle_tolerance) - { + if (da1 < m_angle_tolerance) { m_points.emplace_back(x2, y2); m_points.emplace_back(x3, y3); return; } - if(m_cusp_limit != 0.0) - { - if(da1 > m_cusp_limit) - { + if (m_cusp_limit != 0.0) { + if (da1 > m_cusp_limit) { m_points.emplace_back(x3, y3); return; } @@ -789,10 +762,8 @@ recursive_bezier4(const double x1, const double y1, case 2: // p1,p3,p4 are collinear, p2 is significant //---------------------- - if(d2 * d2 <= m_distance_tolerance_square * (dx*dx + dy*dy)) - { - if(m_angle_tolerance < curve_angle_tolerance_epsilon) - { + if (d2 * d2 <= m_distance_tolerance_square * (dx * dx + dy * dy)) { + if (m_angle_tolerance < curve_angle_tolerance_epsilon) { m_points.emplace_back(x23, y23); return; } @@ -800,19 +771,17 @@ recursive_bezier4(const double x1, const double y1, // Angle Condition //---------------------- da1 = fabs(atan2(y3 - y2, x3 - x2) - atan2(y2 - y1, x2 - x1)); - if(da1 >= M_PI) da1 = 2*M_PI - da1; + if (da1 >= M_PI) + da1 = 2 * M_PI - da1; - if(da1 < m_angle_tolerance) - { + if (da1 < m_angle_tolerance) { m_points.emplace_back(x2, y2); m_points.emplace_back(x3, y3); return; } - if(m_cusp_limit != 0.0) - { - if(da1 > m_cusp_limit) - { + if (m_cusp_limit != 0.0) { + if (da1 > m_cusp_limit) { m_points.emplace_back(x2, y2); return; } @@ -820,62 +789,58 @@ recursive_bezier4(const double x1, const double y1, } break; - case 3: + case 3: // Regular case //----------------- - if((d2 + d3)*(d2 + d3) <= m_distance_tolerance_square * (dx*dx + dy*dy)) - { + if ((d2 + d3) * (d2 + d3) <= m_distance_tolerance_square * (dx * dx + dy * dy)) { // If the curvature doesn't exceed the distance_tolerance value // we tend to finish subdivisions. //---------------------- - if(m_angle_tolerance < curve_angle_tolerance_epsilon) - { + if (m_angle_tolerance < curve_angle_tolerance_epsilon) { m_points.emplace_back(x23, y23); return; } // Angle & Cusp Condition //---------------------- - k = atan2(y3 - y2, x3 - x2); + k = atan2(y3 - y2, x3 - x2); da1 = fabs(k - atan2(y2 - y1, x2 - x1)); da2 = fabs(atan2(y4 - y3, x4 - x3) - k); - if(da1 >= M_PI) da1 = 2*M_PI - da1; - if(da2 >= M_PI) da2 = 2*M_PI - da2; + if (da1 >= M_PI) + da1 = 2 * M_PI - da1; + if (da2 >= M_PI) + da2 = 2 * M_PI - da2; - if(da1 + da2 < m_angle_tolerance) - { + if (da1 + da2 < m_angle_tolerance) { // Finally we can stop the recursion //---------------------- m_points.emplace_back(x23, y23); return; } - if(m_cusp_limit != 0.0) - { - if(da1 > m_cusp_limit) - { + if (m_cusp_limit != 0.0) { + if (da1 > m_cusp_limit) { m_points.emplace_back(x2, y2); return; } - if(da2 > m_cusp_limit) - { + if (da2 > m_cusp_limit) { m_points.emplace_back(x3, y3); return; } } } break; - } + } - // Continue subdivision - //---------------------- - recursive_bezier4(x1, y1, x12, y12, x123, y123, x1234, y1234, m_points, level + 1); - recursive_bezier4(x1234, y1234, x234, y234, x34, y34, x4, y4, m_points, level + 1); + // Continue subdivision + //---------------------- + recursive_bezier4(x1, y1, x12, y12, x123, y123, x1234, y1234, m_points, level + 1); + recursive_bezier4(x1234, y1234, x234, y234, x34, y34, x4, y4, m_points, level + 1); } -void -swap(Geom::Point &A, Geom::Point &B){ +void swap(Geom::Point &A, Geom::Point &B) +{ Geom::Point tmp = A; A = B; B = tmp; diff --git a/src/helper/geom.h b/src/helper/geom.h index 58f323efee45eb133d8512d2c2b530dac77e04ec..bbf11c95b97d94ee0f614ce986ce5cc01c6d48a7 100644 --- a/src/helper/geom.h +++ b/src/helper/geom.h @@ -15,28 +15,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <2geom/affine.h> #include <2geom/forward.h> #include <2geom/rect.h> -#include <2geom/affine.h> -Geom::OptRect bounds_fast_transformed(Geom::PathVector const & pv, Geom::Affine const & t); -Geom::OptRect bounds_exact_transformed(Geom::PathVector const & pv, Geom::Affine const & t); +Geom::OptRect bounds_fast_transformed(Geom::PathVector const &pv, Geom::Affine const &t); +Geom::OptRect bounds_exact_transformed(Geom::PathVector const &pv, Geom::Affine const &t); -void pathv_matrix_point_bbox_wind_distance ( Geom::PathVector const & pathv, Geom::Affine const &m, Geom::Point const &pt, - Geom::Rect *bbox, int *wind, Geom::Coord *dist, - Geom::Coord tolerance, Geom::Rect const *viewbox); +void pathv_matrix_point_bbox_wind_distance(Geom::PathVector const &pathv, Geom::Affine const &m, Geom::Point const &pt, + Geom::Rect *bbox, int *wind, Geom::Coord *dist, Geom::Coord tolerance, + Geom::Rect const *viewbox); -size_t count_pathvector_nodes(Geom::PathVector const &pathv ); +size_t count_pathvector_nodes(Geom::PathVector const &pathv); size_t count_path_nodes(Geom::Path const &path); -Geom::PathVector pathv_to_linear_and_cubic_beziers( Geom::PathVector const &pathv ); -Geom::PathVector pathv_to_linear( Geom::PathVector const &pathv, double maxdisp ); -Geom::PathVector pathv_to_cubicbezier( Geom::PathVector const &pathv); -void recursive_bezier4(const double x1, const double y1, const double x2, const double y2, - const double x3, const double y3, const double x4, const double y4, - std::vector &pointlist, +Geom::PathVector pathv_to_linear_and_cubic_beziers(Geom::PathVector const &pathv); +Geom::PathVector pathv_to_linear(Geom::PathVector const &pathv, double maxdisp); +Geom::PathVector pathv_to_cubicbezier(Geom::PathVector const &pathv); +void recursive_bezier4(const double x1, const double y1, const double x2, const double y2, const double x3, + const double y3, const double x4, const double y4, std::vector &pointlist, int level); void swap(Geom::Point &A, Geom::Point &B); -#endif // INKSCAPE_HELPER_GEOM_H +#endif // INKSCAPE_HELPER_GEOM_H /* Local Variables: diff --git a/src/helper/gettext.cpp b/src/helper/gettext.cpp index d3f8cc23bd2082093f0361a2f8fd16bf54458af5..380edce91ffea5a2dee2654f7bcf521a3544ef48 100644 --- a/src/helper/gettext.cpp +++ b/src/helper/gettext.cpp @@ -11,23 +11,24 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef _WIN32 #include #endif -#include "path-prefix.h" - -#include #include #include +#include + +#include "path-prefix.h" namespace Inkscape { /** does all required gettext initialization and takes care of the respective locale directory paths */ -void initialize_gettext() { +void initialize_gettext() +{ auto localepath = Glib::getenv("INKSCAPE_LOCALEDIR"); if (localepath.empty()) { @@ -53,7 +54,8 @@ void initialize_gettext() { } /** set gettext codeset to UTF8 */ -void bind_textdomain_codeset_utf8() { +void bind_textdomain_codeset_utf8() +{ bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8"); } @@ -64,7 +66,8 @@ void bind_textdomain_codeset_utf8() { * as we have no easy way of determining console encoding from inkscape/inkview.exe process; * for now do something even easier - switch console encoding to UTF8 and be done with it! * this also works nicely on MSYS consoles where UTF8 encoding is used by default, too */ -void bind_textdomain_codeset_console() { +void bind_textdomain_codeset_console() +{ #ifdef _WIN32 bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8"); #else @@ -74,8 +77,7 @@ void bind_textdomain_codeset_console() { #endif } -} - +} // namespace Inkscape /* Local Variables: diff --git a/src/helper/gettext.h b/src/helper/gettext.h index e5745ee0df900458d65539e83ca1356678f7eeda..6b65cdaa90186185ca81a8912ce33e451ef861eb 100644 --- a/src/helper/gettext.h +++ b/src/helper/gettext.h @@ -14,10 +14,10 @@ #define SEEN_GETTEXT_HELPER_H namespace Inkscape { - void initialize_gettext(); - void bind_textdomain_codeset_utf8(); - void bind_textdomain_codeset_console(); -} +void initialize_gettext(); +void bind_textdomain_codeset_utf8(); +void bind_textdomain_codeset_console(); +} // namespace Inkscape #endif // SEEN_GETTEXT_HELPER_H diff --git a/src/helper/mathfns.h b/src/helper/mathfns.h index 3fa51a09b885357699640a43973186fdeae7d135..cf425610f0ac65a7b5b8903b93ac468df9abb6a0 100644 --- a/src/helper/mathfns.h +++ b/src/helper/mathfns.h @@ -22,12 +22,11 @@ namespace Util { /** * Returns area in triangle given by points; may be negative. */ -inline double -triangle_area (Geom::Point p1, Geom::Point p2, Geom::Point p3) +inline double triangle_area(Geom::Point p1, Geom::Point p2, Geom::Point p3) { using Geom::X; using Geom::Y; - return (p1[X]*p2[Y] + p1[Y]*p3[X] + p2[X]*p3[Y] - p2[Y]*p3[X] - p1[Y]*p2[X] - p1[X]*p3[Y]); + return (p1[X] * p2[Y] + p1[Y] * p3[X] + p2[X] * p3[Y] - p2[Y] * p3[X] - p1[Y] * p2[X] - p1[X] * p3[Y]); } /** @@ -66,9 +65,9 @@ inline double round_to_upper_multiple_plus(double x, double const c1, double con return ceil((x - c0) / c1) * c1 + c0; } -} +} // namespace Util -} +} // namespace Inkscape #endif /* diff --git a/src/helper/pixbuf-ops.cpp b/src/helper/pixbuf-ops.cpp index 4c5b9693cb99a12488e8dcfd5c2fcebd0db4290b..39cc35eaa0111514249ce52605b4a9d610ec7fb9 100644 --- a/src/helper/pixbuf-ops.cpp +++ b/src/helper/pixbuf-ops.cpp @@ -12,22 +12,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "helper/pixbuf-ops.h" + #include <2geom/transforms.h> +#include -#include "helper/png-write.h" #include "display/cairo-utils.h" -#include "display/drawing.h" #include "display/drawing-context.h" +#include "display/drawing.h" #include "document.h" -#include "object/sp-root.h" +#include "helper/png-write.h" +#include "inkscape.h" #include "object/sp-defs.h" +#include "object/sp-root.h" #include "object/sp-use.h" #include "util/units.h" -#include "inkscape.h" - -#include "helper/pixbuf-ops.h" - -#include // TODO look for copy-n-paste duplication of this function: /** @@ -36,46 +35,37 @@ static void hide_other_items_recursively(SPObject *o, SPItem *i, unsigned dkey) { SPItem *item = dynamic_cast(o); - if ( item - && !dynamic_cast(item) - && !dynamic_cast(item) - && !dynamic_cast(item) - && !dynamic_cast(item) - && (i != o) ) - { + if (item && !dynamic_cast(item) && !dynamic_cast(item) && !dynamic_cast(item) && + !dynamic_cast(item) && (i != o)) { item->invoke_hide(dkey); } // recurse if (i != o) { - for (auto& child: o->children) { + for (auto &child : o->children) { hide_other_items_recursively(&child, i, dkey); } } } - // The following is a mutation of the flood fill code, the marker preview, and random other samplings. // The dpi settings don't do anything yet, but I want them to, and was wanting to keep reasonably close // to the call for the interface to the png writing. -bool sp_export_jpg_file(SPDocument *doc, gchar const *filename, - double x0, double y0, double x1, double y1, - unsigned width, unsigned height, double xdpi, double ydpi, - unsigned long bgcolor, double quality, SPItem* item) +bool sp_export_jpg_file(SPDocument *doc, gchar const *filename, double x0, double y0, double x1, double y1, + unsigned width, unsigned height, double xdpi, double ydpi, unsigned long bgcolor, + double quality, SPItem *item) { std::unique_ptr pixbuf( - sp_generate_internal_bitmap(doc, filename, x0, y0, x1, y1, - width, height, xdpi, ydpi, bgcolor, item)); + sp_generate_internal_bitmap(doc, filename, x0, y0, x1, y1, width, height, xdpi, ydpi, bgcolor, item)); gchar c[32]; g_snprintf(c, 32, "%f", quality); gboolean saved = gdk_pixbuf_save(pixbuf->getPixbufRaw(), filename, "jpeg", nullptr, "quality", c, NULL); - + return saved; } - /** generates a bitmap from given items the bitmap is stored in RAM and not written to file @@ -89,14 +79,13 @@ bool sp_export_jpg_file(SPDocument *doc, gchar const *filename, @param ydpi @return the created GdkPixbuf structure or NULL if no memory is allocable */ -Inkscape::Pixbuf *sp_generate_internal_bitmap(SPDocument *doc, gchar const */*filename*/, - double x0, double y0, double x1, double y1, - unsigned width, unsigned height, double xdpi, double ydpi, - unsigned long /*bgcolor*/, - SPItem *item_only) +Inkscape::Pixbuf *sp_generate_internal_bitmap(SPDocument *doc, gchar const * /*filename*/, double x0, double y0, + double x1, double y1, unsigned width, unsigned height, double xdpi, + double ydpi, unsigned long /*bgcolor*/, SPItem *item_only) { - if (width == 0 || height == 0) return nullptr; + if (width == 0 || height == 0) + return nullptr; Inkscape::Pixbuf *inkpb = nullptr; /* Create new drawing for offscreen rendering*/ @@ -106,15 +95,16 @@ Inkscape::Pixbuf *sp_generate_internal_bitmap(SPDocument *doc, gchar const */*fi doc->ensureUpToDate(); - Geom::Rect screen=Geom::Rect(Geom::Point(x0,y0), Geom::Point(x1, y1)); + Geom::Rect screen = Geom::Rect(Geom::Point(x0, y0), Geom::Point(x1, y1)); Geom::Point origin = screen.min(); - Geom::Scale scale(Inkscape::Util::Quantity::convert(xdpi, "px", "in"), Inkscape::Util::Quantity::convert(ydpi, "px", "in")); + Geom::Scale scale(Inkscape::Util::Quantity::convert(xdpi, "px", "in"), + Inkscape::Util::Quantity::convert(ydpi, "px", "in")); Geom::Affine affine = scale * Geom::Translate(-origin * scale); /* Create ArenaItems and set transform */ - Inkscape::DrawingItem *root = doc->getRoot()->invoke_show( drawing, dkey, SP_ITEM_SHOW_DISPLAY); + Inkscape::DrawingItem *root = doc->getRoot()->invoke_show(drawing, dkey, SP_ITEM_SHOW_DISPLAY); root->setTransform(affine); drawing.setRoot(root); @@ -123,7 +113,7 @@ Inkscape::Pixbuf *sp_generate_internal_bitmap(SPDocument *doc, gchar const */*fi if (item_only) { hide_other_items_recursively(doc->getRoot(), item_only, dkey); // TODO: The following line forces 100% opacity as required by sp_asbitmap_render() in cairo-renderer.cpp - // Make it conditional if 'item_only' is ever used by other callers which need to retain opacity + // Make it conditional if 'item_only' is ever used by other callers which need to retain opacity item_only->get_arenaitem(dkey)->setOpacity(1.0); } @@ -133,22 +123,20 @@ Inkscape::Pixbuf *sp_generate_internal_bitmap(SPDocument *doc, gchar const */*fi cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); if (cairo_surface_status(surface) == CAIRO_STATUS_SUCCESS) { - Inkscape::DrawingContext dc(surface, Geom::Point(0,0)); + Inkscape::DrawingContext dc(surface, Geom::Point(0, 0)); // render items drawing.render(dc, final_bbox, Inkscape::DrawingItem::RENDER_BYPASS_CACHE); inkpb = new Inkscape::Pixbuf(surface); - } - else - { - long long size = (long long) height * (long long) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width); + } else { + long long size = (long long)height * (long long)cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width); g_warning("sp_generate_internal_bitmap: not enough memory to create pixel buffer. Need %lld.", size); cairo_surface_destroy(surface); } doc->getRoot()->invoke_hide(dkey); -// gdk_pixbuf_save (pixbuf, "C:\\temp\\internal.jpg", "jpeg", NULL, "quality","100", NULL); + // gdk_pixbuf_save (pixbuf, "C:\\temp\\internal.jpg", "jpeg", NULL, "quality","100", NULL); return inkpb; } diff --git a/src/helper/pixbuf-ops.h b/src/helper/pixbuf-ops.h index 549e8554eb88b848aa47e0dac63383c98aea81c4..241e806a7f66c309a720cc285a3529c78bb15f41 100644 --- a/src/helper/pixbuf-ops.h +++ b/src/helper/pixbuf-ops.h @@ -17,14 +17,16 @@ class SPDocument; class SPItem; -namespace Inkscape { class Pixbuf; } +namespace Inkscape { +class Pixbuf; +} - bool sp_export_jpg_file (SPDocument *doc, gchar const *filename, double x0, double y0, double x1, double y1, - unsigned int width, unsigned int height, double xdpi, double ydpi, unsigned long bgcolor, double quality, SPItem *item_only = nullptr); +bool sp_export_jpg_file(SPDocument *doc, gchar const *filename, double x0, double y0, double x1, double y1, + unsigned int width, unsigned int height, double xdpi, double ydpi, unsigned long bgcolor, + double quality, SPItem *item_only = nullptr); -Inkscape::Pixbuf *sp_generate_internal_bitmap(SPDocument *doc, gchar const *filename, - double x0, double y0, double x1, double y1, - unsigned width, unsigned height, double xdpi, double ydpi, - unsigned long bgcolor, SPItem *item_only = nullptr); +Inkscape::Pixbuf *sp_generate_internal_bitmap(SPDocument *doc, gchar const *filename, double x0, double y0, double x1, + double y1, unsigned width, unsigned height, double xdpi, double ydpi, + unsigned long bgcolor, SPItem *item_only = nullptr); #endif diff --git a/src/helper/png-write.cpp b/src/helper/png-write.cpp index ba726bfb93b74221df4f2bf6b1b6a96efdb3ef8c..a36c4734bcb677375b5a6e61c972209a50666492 100644 --- a/src/helper/png-write.cpp +++ b/src/helper/png-write.cpp @@ -14,28 +14,23 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "png-write.h" #include <2geom/rect.h> #include <2geom/transforms.h> - #include -#include "document.h" -#include "inkscape.h" -#include "png-write.h" -#include "preferences.h" -#include "rdf.h" - #include "display/cairo-utils.h" #include "display/drawing-context.h" #include "display/drawing.h" - +#include "document.h" +#include "inkscape.h" #include "io/sys.h" - #include "object/sp-defs.h" #include "object/sp-item.h" #include "object/sp-root.h" - +#include "preferences.h" +#include "rdf.h" #include "ui/interface.h" #include "util/units.h" @@ -51,7 +46,8 @@ * working PNG reader/writer, see pngtest.c, included in this distribution. */ -struct SPEBP { +struct SPEBP +{ unsigned long int width, height, sheight; guint32 background; Inkscape::Drawing *drawing; // it is assumed that all unneeded items are hidden @@ -62,7 +58,8 @@ struct SPEBP { /* write a png file */ -struct SPPNGBD { +struct SPPNGBD +{ guchar const *px; int rowstride; }; @@ -70,21 +67,26 @@ struct SPPNGBD { /** * A simple wrapper to list png_text. */ -class PngTextList { +class PngTextList +{ public: - PngTextList() : count(0), textItems(nullptr) {} + PngTextList() + : count(0) + , textItems(nullptr) + {} ~PngTextList(); - void add(gchar const* key, gchar const* text); - gint getCount() {return count;} - png_text* getPtext() {return textItems;} + void add(gchar const *key, gchar const *text); + gint getCount() { return count; } + png_text *getPtext() { return textItems; } private: gint count; - png_text* textItems; + png_text *textItems; }; -PngTextList::~PngTextList() { +PngTextList::~PngTextList() +{ for (gint i = 0; i < count; i++) { if (textItems[i].key) { g_free(textItems[i].key); @@ -95,18 +97,18 @@ PngTextList::~PngTextList() { } } -void PngTextList::add(gchar const* key, gchar const* text) +void PngTextList::add(gchar const *key, gchar const *text) { if (count < 0) { count = 0; textItems = nullptr; } - png_text* tmp = (count > 0) ? g_try_renew(png_text, textItems, count + 1): g_try_new(png_text, 1); + png_text *tmp = (count > 0) ? g_try_renew(png_text, textItems, count + 1) : g_try_new(png_text, 1); if (tmp) { textItems = tmp; count++; - png_text* item = &(textItems[count - 1]); + png_text *item = &(textItems[count - 1]); item->compression = PNG_TEXT_COMPRESSION_NONE; item->key = g_strdup(key); item->text = g_strdup(text); @@ -123,16 +125,17 @@ void PngTextList::add(gchar const* key, gchar const* text) } } -static bool -sp_png_write_rgba_striped(SPDocument *doc, - gchar const *filename, unsigned long int width, unsigned long int height, double xdpi, double ydpi, - int (* get_rows)(guchar const **rows, void **to_free, int row, int num_rows, void *data, int color_type, int bit_depth, int antialias), - void *data, bool interlace, int color_type, int bit_depth, int zlib, int antialiasing) +static bool sp_png_write_rgba_striped(SPDocument *doc, gchar const *filename, unsigned long int width, + unsigned long int height, double xdpi, double ydpi, + int (*get_rows)(guchar const **rows, void **to_free, int row, int num_rows, + void *data, int color_type, int bit_depth, int antialias), + void *data, bool interlace, int color_type, int bit_depth, int zlib, + int antialiasing) { g_return_val_if_fail(filename != nullptr, false); g_return_val_if_fail(data != nullptr, false); - struct SPEBP *ebp = (struct SPEBP *) data; + struct SPEBP *ebp = (struct SPEBP *)data; FILE *fp; png_structp png_ptr; png_infop info_ptr; @@ -143,7 +146,8 @@ sp_png_write_rgba_striped(SPDocument *doc, Inkscape::IO::dump_fopen_call(filename, "M"); fp = Inkscape::IO::fopen_utf8name(filename, "wb"); - if(fp == nullptr) return false; + if (fp == nullptr) + return false; /* Create and initialize the png_struct with the desired error handler * functions. If you want to use the default stderr and longjump method, @@ -190,22 +194,16 @@ sp_png_write_rgba_striped(SPDocument *doc, png_set_compression_level(png_ptr, zlib); - png_set_IHDR(png_ptr, info_ptr, - width, - height, - bit_depth, - color_type, - interlace ? PNG_INTERLACE_ADAM7 : PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_BASE, - PNG_FILTER_TYPE_BASE); + png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type, + interlace ? PNG_INTERLACE_ADAM7 : PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); - if ((color_type&2) && bit_depth == 16) { + if ((color_type & 2) && bit_depth == 16) { // otherwise, if we are dealing with a color image then sig_bit.red = 8; sig_bit.green = 8; sig_bit.blue = 8; // if the image has an alpha channel then - if (color_type&4) + if (color_type & 4) sig_bit.alpha = 8; png_set_sBIT(png_ptr, info_ptr, &sig_bit); } @@ -214,20 +212,19 @@ sp_png_write_rgba_striped(SPDocument *doc, textList.add("Software", "www.inkscape.org"); // Made by Inkscape comment { - const gchar* pngToDc[] = {"Title", "title", - "Author", "creator", - "Description", "description", - //"Copyright", "", - "Creation Time", "date", - //"Disclaimer", "", - //"Warning", "", - "Source", "source" - //"Comment", "" + const gchar *pngToDc[] = { + "Title", "title", "Author", "creator", "Description", "description", + //"Copyright", "", + "Creation Time", "date", + //"Disclaimer", "", + //"Warning", "", + "Source", "source" + //"Comment", "" }; for (size_t i = 0; i < G_N_ELEMENTS(pngToDc); i += 2) { - struct rdf_work_entity_t * entity = rdf_find_entity ( pngToDc[i + 1] ); + struct rdf_work_entity_t *entity = rdf_find_entity(pngToDc[i + 1]); if (entity) { - gchar const* data = rdf_get_work_entity(doc, entity); + gchar const *data = rdf_get_work_entity(doc, entity); if (data && *data) { textList.add(pngToDc[i], data); } @@ -236,11 +233,10 @@ sp_png_write_rgba_striped(SPDocument *doc, } } - - struct rdf_license_t *license = rdf_get_license(doc); + struct rdf_license_t *license = rdf_get_license(doc); if (license) { if (license->name && license->uri) { - gchar* tmp = g_strdup_printf("%s %s", license->name, license->uri); + gchar *tmp = g_strdup_printf("%s %s", license->name, license->uri); textList.add("Copyright", tmp); g_free(tmp); } else if (license->name) { @@ -257,10 +253,12 @@ sp_png_write_rgba_striped(SPDocument *doc, /* other optional chunks like cHRM, bKGD, tRNS, tIME, oFFs, pHYs, */ /* note that if sRGB is present the cHRM chunk must be ignored * on read and must be written in accordance with the sRGB profile */ - if(xdpi < 0.0254 ) xdpi = 0.0255; - if(ydpi < 0.0254 ) ydpi = 0.0255; + if (xdpi < 0.0254) + xdpi = 0.0255; + if (ydpi < 0.0254) + ydpi = 0.0255; - png_set_pHYs(png_ptr, info_ptr, unsigned(xdpi / 0.0254 ), unsigned(ydpi / 0.0254 ), PNG_RESOLUTION_METER); + png_set_pHYs(png_ptr, info_ptr, unsigned(xdpi / 0.0254), unsigned(ydpi / 0.0254), PNG_RESOLUTION_METER); /* Write the file header information. REQUIRED */ png_write_info(png_ptr, info_ptr); @@ -282,15 +280,17 @@ sp_png_write_rgba_striped(SPDocument *doc, * use the first method if you aren't handling interlacing yourself. */ - png_bytep* row_pointers = new png_bytep[ebp->sheight]; + png_bytep *row_pointers = new png_bytep[ebp->sheight]; int number_of_passes = interlace ? png_set_interlace_handling(png_ptr) : 1; - for(int i=0;i(height)) { void *to_free; - int n = get_rows((unsigned char const **) row_pointers, &to_free, r, height-r, data, color_type, bit_depth, antialiasing); - if (!n) break; + int n = get_rows((unsigned char const **)row_pointers, &to_free, r, height - r, data, color_type, bit_depth, + antialiasing); + if (!n) + break; png_write_rows(png_ptr, row_pointers, n); g_free(to_free); r += n; @@ -318,17 +318,17 @@ sp_png_write_rgba_striped(SPDocument *doc, return true; } - /** * */ -static int -sp_export_get_rows(guchar const **rows, void **to_free, int row, int num_rows, void *data, int color_type, int bit_depth, int antialiasing) +static int sp_export_get_rows(guchar const **rows, void **to_free, int row, int num_rows, void *data, int color_type, + int bit_depth, int antialiasing) { - struct SPEBP *ebp = (struct SPEBP *) data; + struct SPEBP *ebp = (struct SPEBP *)data; if (ebp->status) { - if (!ebp->status((float) row / ebp->height, ebp->data)) return 0; + if (!ebp->status((float)row / ebp->height, ebp->data)) + return 0; } num_rows = MIN(num_rows, static_cast(ebp->sheight)); @@ -346,8 +346,7 @@ sp_export_get_rows(guchar const **rows, void **to_free, int row, int num_rows, v int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, ebp->width); unsigned char *px = g_new(guchar, num_rows * stride); - cairo_surface_t *s = cairo_image_surface_create_for_data( - px, CAIRO_FORMAT_ARGB32, ebp->width, num_rows, stride); + cairo_surface_t *s = cairo_image_surface_create_for_data(px, CAIRO_FORMAT_ARGB32, ebp->width, num_rows, stride); Inkscape::DrawingContext dc(s, bbox.min()); dc.setSource(ebp->background); dc.setOperator(CAIRO_OPERATOR_SOURCE); @@ -361,10 +360,10 @@ sp_export_get_rows(guchar const **rows, void **to_free, int row, int num_rows, v // PNG stores data as unpremultiplied big-endian RGBA, which means // it's identical to the GdkPixbuf format. convert_pixels_argb32_to_pixbuf(px, ebp->width, num_rows, stride); - + // If a custom bit depth or color type is asked, then convert rgb to grayscale, etc. - const guchar* new_data = pixbuf_to_png(rows, px, num_rows, ebp->width, stride, color_type, bit_depth); - *to_free = (void*) new_data; + const guchar *new_data = pixbuf_to_png(rows, px, num_rows, ebp->width, stride, color_type, bit_depth); + *to_free = (void *)new_data; free(px); return num_rows; @@ -373,36 +372,30 @@ sp_export_get_rows(guchar const **rows, void **to_free, int row, int num_rows, v /** * Hide all items that are not listed in list, recursively, skipping groups and defs. */ -static void hide_other_items_recursively(SPObject *o, const std::vector &list, unsigned dkey) +static void hide_other_items_recursively(SPObject *o, const std::vector &list, unsigned dkey) { - if ( SP_IS_ITEM(o) - && !SP_IS_DEFS(o) - && !SP_IS_ROOT(o) - && !SP_IS_GROUP(o) - && list.end()==find(list.begin(),list.end(),o)) - { + if (SP_IS_ITEM(o) && !SP_IS_DEFS(o) && !SP_IS_ROOT(o) && !SP_IS_GROUP(o) && + list.end() == find(list.begin(), list.end(), o)) { SP_ITEM(o)->invoke_hide(dkey); } // recurse - if (list.end()==find(list.begin(),list.end(),o)) { - for (auto& child: o->children) { + if (list.end() == find(list.begin(), list.end(), o)) { + for (auto &child : o->children) { hide_other_items_recursively(&child, list, dkey); } } } - -ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, - double x0, double y0, double x1, double y1, +ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, double x0, double y0, double x1, double y1, unsigned long int width, unsigned long int height, double xdpi, double ydpi, - unsigned long bgcolor, - unsigned int (*status) (float, void *), - void *data, bool force_overwrite, - const std::vector &items_only, bool interlace, int color_type, int bit_depth, int zlib, int antialiasing) + unsigned long bgcolor, unsigned int (*status)(float, void *), void *data, + bool force_overwrite, const std::vector &items_only, bool interlace, + int color_type, int bit_depth, int zlib, int antialiasing) { - return sp_export_png_file(doc, filename, Geom::Rect(Geom::Point(x0,y0),Geom::Point(x1,y1)), - width, height, xdpi, ydpi, bgcolor, status, data, force_overwrite, items_only, interlace, color_type, bit_depth, zlib, antialiasing); + return sp_export_png_file(doc, filename, Geom::Rect(Geom::Point(x0, y0), Geom::Point(x1, y1)), width, height, xdpi, + ydpi, bgcolor, status, data, force_overwrite, items_only, interlace, color_type, + bit_depth, zlib, antialiasing); } /** @@ -410,13 +403,11 @@ ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, * * @param area Area in document coordinates */ -ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, - Geom::Rect const &area, - unsigned long width, unsigned long height, double xdpi, double ydpi, - unsigned long bgcolor, - unsigned (*status)(float, void *), - void *data, bool force_overwrite, - const std::vector &items_only, bool interlace, int color_type, int bit_depth, int zlib, int antialiasing) +ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, Geom::Rect const &area, unsigned long width, + unsigned long height, double xdpi, double ydpi, unsigned long bgcolor, + unsigned (*status)(float, void *), void *data, bool force_overwrite, + const std::vector &items_only, bool interlace, int color_type, int bit_depth, + int zlib, int antialiasing) { g_return_val_if_fail(doc != nullptr, EXPORT_ERROR); g_return_val_if_fail(filename != nullptr, EXPORT_ERROR); @@ -424,10 +415,9 @@ ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, g_return_val_if_fail(height >= 1, EXPORT_ERROR); g_return_val_if_fail(!area.hasZeroArea(), EXPORT_ERROR); - if (!force_overwrite && !sp_ui_overwrite_file(filename)) { // aborted overwrite - return EXPORT_ABORTED; + return EXPORT_ABORTED; } doc->ensureUpToDate(); @@ -451,12 +441,10 @@ ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, * (2) a[5] = -a[3] * y1 */ - Geom::Affine const affine(Geom::Translate(translation) - * Geom::Scale(width / area.width(), - height / area.height())); + Geom::Affine const affine(Geom::Translate(translation) * Geom::Scale(width / area.width(), height / area.height())); struct SPEBP ebp; - ebp.width = width; + ebp.width = width; ebp.height = height; ebp.background = bgcolor; @@ -477,15 +465,17 @@ ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, } ebp.status = status; - ebp.data = data; + ebp.data = data; - bool write_status = false;; + bool write_status = false; + ; ebp.sheight = 64; ebp.px = g_try_new(guchar, 4 * ebp.sheight * width); if (ebp.px) { - write_status = sp_png_write_rgba_striped(doc, filename, width, height, xdpi, ydpi, sp_export_get_rows, &ebp, interlace, color_type, bit_depth, zlib, antialiasing); + write_status = sp_png_write_rgba_striped(doc, filename, width, height, xdpi, ydpi, sp_export_get_rows, &ebp, + interlace, color_type, bit_depth, zlib, antialiasing); g_free(ebp.px); } @@ -495,7 +485,6 @@ ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, return write_status ? EXPORT_OK : EXPORT_ERROR; } - /* Local Variables: mode:c++ diff --git a/src/helper/png-write.h b/src/helper/png-write.h index 6c79d20e40ab16d4133fb4201594f1d497fc688e..ffd8ad0ef839b3ea6dffd4909b1047dc64ec907f 100644 --- a/src/helper/png-write.h +++ b/src/helper/png-write.h @@ -15,15 +15,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <2geom/forward.h> #include // Only for gchar. #include -#include <2geom/forward.h> - class SPDocument; class SPItem; -enum ExportResult { +enum ExportResult +{ EXPORT_ERROR = 0, EXPORT_OK, EXPORT_ABORTED @@ -34,18 +34,19 @@ enum ExportResult { * * @return EXPORT_OK if succeeded, EXPORT_ABORTED if no action was taken, EXPORT_ERROR (false) if an error occurred. */ -ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, - double x0, double y0, double x1, double y1, - unsigned long int width, unsigned long int height, double xdpi, double ydpi, - unsigned long bgcolor, - unsigned int (*status) (float, void *), void *data, bool force_overwrite = false, const std::vector &items_only = std::vector(), - bool interlace = false, int color_type = 6, int bit_depth = 8, int zlib = 6, int antialiasing = 2); - -ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, - Geom::Rect const &area, - unsigned long int width, unsigned long int height, double xdpi, double ydpi, - unsigned long bgcolor, - unsigned int (*status) (float, void *), void *data, bool force_overwrite = false, const std::vector &items_only = std::vector(), - bool interlace = false, int color_type = 6, int bit_depth = 8, int zlib = 6, int antialiasing = 2); +ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, double x0, double y0, double x1, double y1, + unsigned long int width, unsigned long int height, double xdpi, double ydpi, + unsigned long bgcolor, unsigned int (*status)(float, void *), void *data, + bool force_overwrite = false, + const std::vector &items_only = std::vector(), + bool interlace = false, int color_type = 6, int bit_depth = 8, int zlib = 6, + int antialiasing = 2); + +ExportResult sp_export_png_file(SPDocument *doc, gchar const *filename, Geom::Rect const &area, unsigned long int width, + unsigned long int height, double xdpi, double ydpi, unsigned long bgcolor, + unsigned int (*status)(float, void *), void *data, bool force_overwrite = false, + const std::vector &items_only = std::vector(), + bool interlace = false, int color_type = 6, int bit_depth = 8, int zlib = 6, + int antialiasing = 2); #endif // SEEN_SP_PNG_WRITE_H diff --git a/src/helper/stock-items.cpp b/src/helper/stock-items.cpp index fbdf11cf48badde2e166a75afae834e91f8bb1bc..37340b7e8b33183b9489201b9bef2de495ada844 100644 --- a/src/helper/stock-items.cpp +++ b/src/helper/stock-items.cpp @@ -17,22 +17,20 @@ #define noSP_SS_VERBOSE +#include "stock-items.h" + #include #include - -#include "path-prefix.h" - #include -#include "inkscape.h" -#include "io/sys.h" +#include "inkscape.h" #include "io/resource.h" -#include "stock-items.h" - +#include "io/sys.h" +#include "object/sp-defs.h" #include "object/sp-gradient.h" -#include "object/sp-pattern.h" #include "object/sp-marker.h" -#include "object/sp-defs.h" +#include "object/sp-pattern.h" +#include "path-prefix.h" static SPDocument *load_paint_doc(char const *basename, Inkscape::IO::Resource::Type type = Inkscape::IO::Resource::PAINT) @@ -58,7 +56,7 @@ static SPDocument *load_paint_doc(char const *basename, // take the dir to look in, and the file to check for, and cache // against that, rather than the existing copy/paste code seen here. -static SPObject * sp_marker_load_from_svg(gchar const *name, SPDocument *current_doc) +static SPObject *sp_marker_load_from_svg(gchar const *name, SPDocument *current_doc) { if (!current_doc) { return nullptr; @@ -82,9 +80,7 @@ static SPObject * sp_marker_load_from_svg(gchar const *name, SPDocument *current return nullptr; } - -static SPObject * -sp_pattern_load_from_svg(gchar const *name, SPDocument *current_doc) +static SPObject *sp_pattern_load_from_svg(gchar const *name, SPDocument *current_doc) { if (!current_doc) { return nullptr; @@ -107,9 +103,7 @@ sp_pattern_load_from_svg(gchar const *name, SPDocument *current_doc) return nullptr; } - -static SPObject * -sp_gradient_load_from_svg(gchar const *name, SPDocument *current_doc) +static SPObject *sp_gradient_load_from_svg(gchar const *name, SPDocument *current_doc) { if (!current_doc) { return nullptr; @@ -141,22 +135,21 @@ SPObject *get_stock_item(gchar const *urn, gboolean stock) g_assert(urn != nullptr); /* check its an inkscape URN */ - if (!strncmp (urn, "urn:inkscape:", 13)) { - + if (!strncmp(urn, "urn:inkscape:", 13)) { gchar const *e = urn + 13; int a = 0; - gchar * name = g_strdup(e); + gchar *name = g_strdup(e); gchar *name_p = name; - while (*name_p != ':' && *name_p != '\0'){ + while (*name_p != ':' && *name_p != '\0') { name_p++; a++; } - if (*name_p ==':') { + if (*name_p == ':') { name_p++; } - gchar * base = g_strndup(e, a); + gchar *base = g_strndup(e, a); SPDocument *doc = SP_ACTIVE_DOCUMENT; SPDefs *defs = doc->getDefs(); @@ -166,48 +159,34 @@ SPObject *get_stock_item(gchar const *urn, gboolean stock) } SPObject *object = nullptr; if (!strcmp(base, "marker") && !stock) { - for (auto& child: defs->children) - { + for (auto &child : defs->children) { if (child.getRepr()->attribute("inkscape:stockid") && - !strcmp(name_p, child.getRepr()->attribute("inkscape:stockid")) && - SP_IS_MARKER(&child)) - { + !strcmp(name_p, child.getRepr()->attribute("inkscape:stockid")) && SP_IS_MARKER(&child)) { object = &child; } } - } - else if (!strcmp(base,"pattern") && !stock) { - for (auto& child: defs->children) - { + } else if (!strcmp(base, "pattern") && !stock) { + for (auto &child : defs->children) { if (child.getRepr()->attribute("inkscape:stockid") && - !strcmp(name_p, child.getRepr()->attribute("inkscape:stockid")) && - SP_IS_PATTERN(&child)) - { + !strcmp(name_p, child.getRepr()->attribute("inkscape:stockid")) && SP_IS_PATTERN(&child)) { object = &child; } } - } - else if (!strcmp(base,"gradient") && !stock) { - for (auto& child: defs->children) - { + } else if (!strcmp(base, "gradient") && !stock) { + for (auto &child : defs->children) { if (child.getRepr()->attribute("inkscape:stockid") && - !strcmp(name_p, child.getRepr()->attribute("inkscape:stockid")) && - SP_IS_GRADIENT(&child)) - { + !strcmp(name_p, child.getRepr()->attribute("inkscape:stockid")) && SP_IS_GRADIENT(&child)) { object = &child; } } } if (object == nullptr) { - - if (!strcmp(base, "marker")) { + if (!strcmp(base, "marker")) { object = sp_marker_load_from_svg(name_p, doc); - } - else if (!strcmp(base, "pattern")) { + } else if (!strcmp(base, "pattern")) { object = sp_pattern_load_from_svg(name_p, doc); - } - else if (!strcmp(base, "gradient")) { + } else if (!strcmp(base, "gradient")) { object = sp_gradient_load_from_svg(name_p, doc); } } @@ -223,7 +202,6 @@ SPObject *get_stock_item(gchar const *urn, gboolean stock) } else { - SPDocument *doc = SP_ACTIVE_DOCUMENT; SPObject *object = doc->getObjectById(urn); diff --git a/src/helper/stock-items.h b/src/helper/stock-items.h index 0d1bb20fc975957d8c32db02a1367d9a31151727..fd18b18ed2c5319c09fc392ad3f1cb20e26321d9 100644 --- a/src/helper/stock-items.h +++ b/src/helper/stock-items.h @@ -16,6 +16,6 @@ class SPObject; -SPObject *get_stock_item(gchar const *urn, gboolean stock=FALSE); +SPObject *get_stock_item(gchar const *urn, gboolean stock = FALSE); #endif // SEEN_INK_STOCK_ITEMS_H diff --git a/src/helper/verb-action.cpp b/src/helper/verb-action.cpp index 1a724902d593d225265c7bbe35a00ec695500847..b123c3ba1ce463d3b94a8fbf856cb063a41e1895 100644 --- a/src/helper/verb-action.cpp +++ b/src/helper/verb-action.cpp @@ -29,24 +29,27 @@ #include "verb-action.h" -#include - #include #include +#include -#include "shortcuts.h" -#include "verbs.h" #include "helper/action.h" +#include "shortcuts.h" #include "ui/widget/button.h" +#include "verbs.h" #include "widgets/toolbox.h" -static GtkToolItem * sp_toolbox_button_item_new_from_verb_with_doubleclick( GtkWidget *t, GtkIconSize size, Inkscape::UI::Widget::ButtonType type, - Inkscape::Verb *verb, Inkscape::Verb *doubleclick_verb, - Inkscape::UI::View::View *view); - -GtkToolItem * sp_toolbox_button_item_new_from_verb_with_doubleclick(GtkWidget *t, GtkIconSize size, Inkscape::UI::Widget::ButtonType type, - Inkscape::Verb *verb, Inkscape::Verb *doubleclick_verb, - Inkscape::UI::View::View *view) +static GtkToolItem *sp_toolbox_button_item_new_from_verb_with_doubleclick(GtkWidget *t, GtkIconSize size, + Inkscape::UI::Widget::ButtonType type, + Inkscape::Verb *verb, + Inkscape::Verb *doubleclick_verb, + Inkscape::UI::View::View *view); + +GtkToolItem *sp_toolbox_button_item_new_from_verb_with_doubleclick(GtkWidget *t, GtkIconSize size, + Inkscape::UI::Widget::ButtonType type, + Inkscape::Verb *verb, + Inkscape::Verb *doubleclick_verb, + Inkscape::UI::View::View *view) { SPAction *action = verb->get_action(Inkscape::ActionContext(view)); if (!action) { @@ -70,15 +73,15 @@ GtkToolItem * sp_toolbox_button_item_new_from_verb_with_doubleclick(GtkWidget *t unsigned int shortcut = sp_shortcut_get_primary(verb); if (shortcut != GDK_KEY_VoidSymbol) { gchar *key = sp_shortcut_get_label(shortcut); - gchar *tip = g_strdup_printf ("%s (%s)", action->tip, key); - if ( t ) { - gtk_toolbar_insert(GTK_TOOLBAR(t), b_toolitem->gobj(), -1); - b->set_tooltip_text(tip); + gchar *tip = g_strdup_printf("%s (%s)", action->tip, key); + if (t) { + gtk_toolbar_insert(GTK_TOOLBAR(t), b_toolitem->gobj(), -1); + b->set_tooltip_text(tip); } g_free(tip); g_free(key); } else { - if ( t ) { + if (t) { gtk_toolbar_insert(GTK_TOOLBAR(t), b_toolitem->gobj(), -1); b->set_tooltip_text(action->tip); } @@ -87,77 +90,74 @@ GtkToolItem * sp_toolbox_button_item_new_from_verb_with_doubleclick(GtkWidget *t return GTK_TOOL_ITEM(b_toolitem->gobj()); } -Glib::RefPtr VerbAction::create(Inkscape::Verb* verb, Inkscape::Verb* verb2, Inkscape::UI::View::View *view) +Glib::RefPtr VerbAction::create(Inkscape::Verb *verb, Inkscape::Verb *verb2, Inkscape::UI::View::View *view) { Glib::RefPtr result; SPAction *action = verb->get_action(Inkscape::ActionContext(view)); - if ( action ) { - //SPAction* action2 = verb2 ? verb2->get_action(Inkscape::ActionContext(view)) : 0; + if (action) { + // SPAction* action2 = verb2 ? verb2->get_action(Inkscape::ActionContext(view)) : 0; result = Glib::RefPtr(new VerbAction(verb, verb2, view)); } return result; } -VerbAction::VerbAction(Inkscape::Verb* verb, Inkscape::Verb* verb2, Inkscape::UI::View::View *view) : - Gtk::Action(Glib::ustring(verb->get_id()), verb->get_image(), Glib::ustring(g_dpgettext2(nullptr, "ContextVerb", verb->get_name())), Glib::ustring(_(verb->get_tip()))), - verb(verb), - verb2(verb2), - view(view), - active(false) -{ -} +VerbAction::VerbAction(Inkscape::Verb *verb, Inkscape::Verb *verb2, Inkscape::UI::View::View *view) + : Gtk::Action(Glib::ustring(verb->get_id()), verb->get_image(), + Glib::ustring(g_dpgettext2(nullptr, "ContextVerb", verb->get_name())), + Glib::ustring(_(verb->get_tip()))) + , verb(verb) + , verb2(verb2) + , view(view) + , active(false) +{} -VerbAction::~VerbAction() -= default; +VerbAction::~VerbAction() = default; -Gtk::Widget* VerbAction::create_menu_item_vfunc() +Gtk::Widget *VerbAction::create_menu_item_vfunc() { - Gtk::Widget* widg = Gtk::Action::create_menu_item_vfunc(); -// g_message("create_menu_item_vfunc() = %p for '%s'", widg, verb->get_id()); + Gtk::Widget *widg = Gtk::Action::create_menu_item_vfunc(); + // g_message("create_menu_item_vfunc() = %p for '%s'", widg, verb->get_id()); return widg; } -Gtk::Widget* VerbAction::create_tool_item_vfunc() +Gtk::Widget *VerbAction::create_tool_item_vfunc() { -// Gtk::Widget* widg = Gtk::Action::create_tool_item_vfunc(); + // Gtk::Widget* widg = Gtk::Action::create_tool_item_vfunc(); GtkIconSize toolboxSize = Inkscape::UI::ToolboxFactory::prefToSize("/toolbox/tools/small"); - GtkWidget* toolbox = nullptr; - auto holder = Glib::wrap(sp_toolbox_button_item_new_from_verb_with_doubleclick( toolbox, toolboxSize, - Inkscape::UI::Widget::BUTTON_TYPE_TOGGLE, - verb, - verb2, - view )); + GtkWidget *toolbox = nullptr; + auto holder = Glib::wrap(sp_toolbox_button_item_new_from_verb_with_doubleclick( + toolbox, toolboxSize, Inkscape::UI::Widget::BUTTON_TYPE_TOGGLE, verb, verb2, view)); auto button_widget = static_cast(holder->get_child()); - if ( active ) { + if (active) { button_widget->toggle_set_down(active); } button_widget->show_all(); -// g_message("create_tool_item_vfunc() = %p for '%s'", holder, verb->get_id()); + // g_message("create_tool_item_vfunc() = %p for '%s'", holder, verb->get_id()); return holder; } -void VerbAction::connect_proxy_vfunc(Gtk::Widget* proxy) +void VerbAction::connect_proxy_vfunc(Gtk::Widget *proxy) { -// g_message("connect_proxy_vfunc(%p) for '%s'", proxy, verb->get_id()); + // g_message("connect_proxy_vfunc(%p) for '%s'", proxy, verb->get_id()); Gtk::Action::connect_proxy_vfunc(proxy); } -void VerbAction::disconnect_proxy_vfunc(Gtk::Widget* proxy) +void VerbAction::disconnect_proxy_vfunc(Gtk::Widget *proxy) { -// g_message("disconnect_proxy_vfunc(%p) for '%s'", proxy, verb->get_id()); + // g_message("disconnect_proxy_vfunc(%p) for '%s'", proxy, verb->get_id()); Gtk::Action::disconnect_proxy_vfunc(proxy); } void VerbAction::set_active(bool active) { this->active = active; - std::vector proxies = get_proxies(); + std::vector proxies = get_proxies(); for (auto proxie : proxies) { - Gtk::ToolItem* ti = dynamic_cast(proxie); + Gtk::ToolItem *ti = dynamic_cast(proxie); if (ti) { // *should* have one child that is the Inkscape::UI::Widget::Button auto child = dynamic_cast(ti->get_child()); @@ -170,12 +170,10 @@ void VerbAction::set_active(bool active) void VerbAction::on_activate() { - if ( verb ) { + if (verb) { SPAction *action = verb->get_action(Inkscape::ActionContext(view)); - if ( action ) { + if (action) { sp_action_perform(action, nullptr); } } } - - diff --git a/src/helper/verb-action.h b/src/helper/verb-action.h index 1c0171f212647ca538768a9677ccace54d3e1b77..e0db74a4819fff2e3fc653c24330e79172f424a4 100644 --- a/src/helper/verb-action.h +++ b/src/helper/verb-action.h @@ -40,37 +40,38 @@ namespace UI { namespace View { class View; } -} -} +} // namespace UI +} // namespace Inkscape /** * \brief A deprecated Gtk::Action that provides a widget for an Inkscape Verb * * \deprecated In new code, you should create a Gtk::ToolItem instead of using this */ -class VerbAction : public Gtk::Action { +class VerbAction : public Gtk::Action +{ public: - static Glib::RefPtr create(Inkscape::Verb* verb, Inkscape::Verb* verb2, Inkscape::UI::View::View *view); + static Glib::RefPtr create(Inkscape::Verb *verb, Inkscape::Verb *verb2, Inkscape::UI::View::View *view); ~VerbAction() override; virtual void set_active(bool active = true); protected: - Gtk::Widget* create_menu_item_vfunc() override; - Gtk::Widget* create_tool_item_vfunc() override; + Gtk::Widget *create_menu_item_vfunc() override; + Gtk::Widget *create_tool_item_vfunc() override; - void connect_proxy_vfunc(Gtk::Widget* proxy) override; - void disconnect_proxy_vfunc(Gtk::Widget* proxy) override; + void connect_proxy_vfunc(Gtk::Widget *proxy) override; + void disconnect_proxy_vfunc(Gtk::Widget *proxy) override; void on_activate() override; private: - Inkscape::Verb* verb; - Inkscape::Verb* verb2; + Inkscape::Verb *verb; + Inkscape::Verb *verb2; Inkscape::UI::View::View *view; bool active; - VerbAction(Inkscape::Verb* verb, Inkscape::Verb* verb2, Inkscape::UI::View::View *view); + VerbAction(Inkscape::Verb *verb, Inkscape::Verb *verb2, Inkscape::UI::View::View *view); }; #endif diff --git a/src/id-clash.cpp b/src/id-clash.cpp index 9c70d3dace5c6636ea9bb3d2c8adf2bb028a44c5..4e3190bf7307d8ef0cbbdfc5f3f95b590f733a5f 100644 --- a/src/id-clash.cpp +++ b/src/id-clash.cpp @@ -12,6 +12,8 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "id-clash.h" + #include #include #include @@ -20,8 +22,6 @@ #include #include "extract-uri.h" -#include "id-clash.h" - #include "live_effects/lpeobject.h" #include "object/sp-gradient.h" #include "object/sp-object.h" @@ -29,17 +29,25 @@ #include "object/sp-root.h" #include "style.h" -enum ID_REF_TYPE { REF_HREF, REF_STYLE, REF_SHAPES, REF_URL, REF_CLIPBOARD }; +enum ID_REF_TYPE +{ + REF_HREF, + REF_STYLE, + REF_SHAPES, + REF_URL, + REF_CLIPBOARD +}; -struct IdReference { +struct IdReference +{ ID_REF_TYPE type; SPObject *elem; - const char *attr; // property or href-like attribute + const char *attr; // property or href-like attribute }; -typedef std::map > refmap_type; +typedef std::map> refmap_type; -typedef std::pair id_changeitem_type; +typedef std::pair id_changeitem_type; typedef std::list id_changelist_type; const char *href_like_attributes[] = { @@ -55,19 +63,19 @@ const char *href_like_attributes[] = { }; #define NUM_HREF_LIKE_ATTRIBUTES (sizeof(href_like_attributes) / sizeof(*href_like_attributes)) -const SPIPaint SPStyle::* SPIPaint_members[] = { +const SPIPaint SPStyle::*SPIPaint_members[] = { //&SPStyle::color, reinterpret_cast(&SPStyle::fill), reinterpret_cast(&SPStyle::stroke), }; -const char* SPIPaint_properties[] = { +const char *SPIPaint_properties[] = { //"color", "fill", "stroke", }; #define NUM_SPIPAINT_PROPERTIES (sizeof(SPIPaint_properties) / sizeof(*SPIPaint_properties)) -const SPIShapes SPStyle::* SPIShapes_members[] = { +const SPIShapes SPStyle::*SPIShapes_members[] = { reinterpret_cast(&SPStyle::shape_inside), reinterpret_cast(&SPStyle::shape_subtract), }; @@ -77,33 +85,21 @@ const char *SPIShapes_properties[] = { }; #define NUM_SPISHAPES_PROPERTIES (sizeof(SPIShapes_properties) / sizeof(*SPIShapes_properties)) -const char* other_url_properties[] = { - "clip-path", - "color-profile", - "cursor", - "marker-end", - "marker-mid", - "marker-start", - "mask", +const char *other_url_properties[] = { + "clip-path", "color-profile", "cursor", "marker-end", "marker-mid", "marker-start", "mask", }; #define NUM_OTHER_URL_PROPERTIES (sizeof(other_url_properties) / sizeof(*other_url_properties)) -const char* clipboard_properties[] = { +const char *clipboard_properties[] = { //"color", - "fill", - "filter", - "stroke", - "marker-end", - "marker-mid", - "marker-start" -}; + "fill", "filter", "stroke", "marker-end", "marker-mid", "marker-start"}; #define NUM_CLIPBOARD_PROPERTIES (sizeof(clipboard_properties) / sizeof(*clipboard_properties)) /** * Given an reference (idref), make it point to to_obj instead */ -static void -fix_ref(IdReference const &idref, SPObject *to_obj, const char *old_id) { +static void fix_ref(IdReference const &idref, SPObject *to_obj, const char *old_id) +{ switch (idref.type) { case REF_HREF: { gchar *new_uri = g_strdup_printf("#%s", to_obj->getId()); @@ -116,15 +112,17 @@ fix_ref(IdReference const &idref, SPObject *to_obj, const char *old_id) { break; } case REF_SHAPES: { - SPCSSAttr* css = sp_repr_css_attr (idref.elem->getRepr(), "style"); - std::string prop = sp_repr_css_property (css, idref.attr, nullptr); - std::string oid; oid.append("url(#").append(old_id).append(")"); + SPCSSAttr *css = sp_repr_css_attr(idref.elem->getRepr(), "style"); + std::string prop = sp_repr_css_property(css, idref.attr, nullptr); + std::string oid; + oid.append("url(#").append(old_id).append(")"); auto pos = prop.find(oid); if (pos != std::string::npos) { - std::string nid; nid.append("url(#").append(to_obj->getId()).append(")"); + std::string nid; + nid.append("url(#").append(to_obj->getId()).append(")"); prop.replace(pos, oid.size(), nid); - sp_repr_css_set_property (css, idref.attr, prop.c_str()); - sp_repr_css_set (idref.elem->getRepr(), css, "style"); + sp_repr_css_set_property(css, idref.attr, prop.c_str()); + sp_repr_css_set(idref.elem->getRepr(), css, "style"); } else { std::cerr << "Failed to switch id -- shouldn't happen" << std::endl; } @@ -154,13 +152,15 @@ fix_ref(IdReference const &idref, SPObject *to_obj, const char *old_id) { * FIXME: There are some types of references not yet dealt with here * (e.g., ID selectors in CSS stylesheets, and references in scripts). */ -static void -find_references(SPObject *elem, refmap_type &refmap) +static void find_references(SPObject *elem, refmap_type &refmap) { - if (elem->cloned) return; + if (elem->cloned) + return; Inkscape::XML::Node *repr_elem = elem->getRepr(); - if (!repr_elem) return; - if (repr_elem->type() != Inkscape::XML::ELEMENT_NODE) return; + if (!repr_elem) + return; + if (repr_elem->type() != Inkscape::XML::ELEMENT_NODE) + return; /* check for references in inkscape:clipboard elements */ if (!std::strcmp(repr_elem->name(), "inkscape:clipboard")) { @@ -171,12 +171,11 @@ find_references(SPObject *elem, refmap_type &refmap) if (value) { auto uri = extract_uri(value); if (uri[0] == '#') { - IdReference idref = { REF_CLIPBOARD, elem, attr }; + IdReference idref = {REF_CLIPBOARD, elem, attr}; refmap[uri.c_str() + 1].push_back(idref); } } } - } return; // nothing more to do for inkscape:clipboard elements } @@ -185,8 +184,8 @@ find_references(SPObject *elem, refmap_type &refmap) for (auto attr : href_like_attributes) { const gchar *val = repr_elem->attribute(attr); if (val && val[0] == '#') { - std::string id(val+1); - IdReference idref = { REF_HREF, elem, attr }; + std::string id(val + 1); + IdReference idref = {REF_HREF, elem, attr}; refmap[id].push_back(idref); } } @@ -201,7 +200,7 @@ find_references(SPObject *elem, refmap_type &refmap) const SPObject *obj = paint->value.href->getObject(); if (obj) { const gchar *id = obj->getId(); - IdReference idref = { REF_STYLE, elem, SPIPaint_properties[i] }; + IdReference idref = {REF_STYLE, elem, SPIPaint_properties[i]}; refmap[id].push_back(idref); } } @@ -216,7 +215,7 @@ find_references(SPObject *elem, refmap_type &refmap) if (!obj) continue; auto shape_id = obj->getId(); - IdReference idref = { REF_SHAPES, elem, SPIShapes_properties[i] }; + IdReference idref = {REF_SHAPES, elem, SPIShapes_properties[i]}; refmap[shape_id].push_back(idref); } } @@ -227,19 +226,19 @@ find_references(SPObject *elem, refmap_type &refmap) const SPObject *obj = filter->href->getObject(); if (obj) { const gchar *id = obj->getId(); - IdReference idref = { REF_STYLE, elem, "filter" }; + IdReference idref = {REF_STYLE, elem, "filter"}; refmap[id].push_back(idref); } } /* check for url(#...) references in markers */ - const gchar *markers[4] = { "", "marker-start", "marker-mid", "marker-end" }; + const gchar *markers[4] = {"", "marker-start", "marker-mid", "marker-end"}; for (unsigned i = SP_MARKER_LOC_START; i < SP_MARKER_LOC_QTY; i++) { const gchar *value = style->marker_ptrs[i]->value(); if (value) { auto uri = extract_uri(value); if (uri[0] == '#') { - IdReference idref = { REF_STYLE, elem, markers[i] }; + IdReference idref = {REF_STYLE, elem, markers[i]}; refmap[uri.c_str() + 1].push_back(idref); } } @@ -251,15 +250,14 @@ find_references(SPObject *elem, refmap_type &refmap) if (value) { auto uri = extract_uri(value); if (uri[0] == '#') { - IdReference idref = { REF_URL, elem, attr }; + IdReference idref = {REF_URL, elem, attr}; refmap[uri.c_str() + 1].push_back(idref); } } } // recurse - for (auto& child: elem->children) - { + for (auto &child : elem->children) { find_references(&child, refmap); } } @@ -268,10 +266,8 @@ find_references(SPObject *elem, refmap_type &refmap) * Change any IDs that clash with IDs in the current document, and make * a list of those changes that will require fixing up references. */ -static void -change_clashing_ids(SPDocument *imported_doc, SPDocument *current_doc, - SPObject *elem, refmap_type const &refmap, - id_changelist_type *id_changes) +static void change_clashing_ids(SPDocument *imported_doc, SPDocument *current_doc, SPObject *elem, + refmap_type const &refmap, id_changelist_type *id_changes) { const gchar *id = elem->getId(); bool fix_clashing_ids = true; @@ -283,14 +279,14 @@ change_clashing_ids(SPDocument *imported_doc, SPDocument *current_doc, // and one or more digits. if (SP_IS_GRADIENT(elem)) { - SPObject *cd_obj = current_doc->getObjectById(id); + SPObject *cd_obj = current_doc->getObjectById(id); if (cd_obj && SP_IS_GRADIENT(cd_obj)) { SPGradient *cd_gr = SP_GRADIENT(cd_obj); - if ( cd_gr->isEquivalent(SP_GRADIENT(elem))) { + if (cd_gr->isEquivalent(SP_GRADIENT(elem))) { fix_clashing_ids = false; - } - } + } + } } LivePathEffectObject *lpeobj = dynamic_cast(elem); @@ -308,22 +304,20 @@ change_clashing_ids(SPDocument *imported_doc, SPDocument *current_doc, for (;;) { new_id += "0123456789"[std::rand() % 10]; const char *str = new_id.c_str(); - if (current_doc->getObjectById(str) == nullptr && - imported_doc->getObjectById(str) == nullptr) break; + if (current_doc->getObjectById(str) == nullptr && imported_doc->getObjectById(str) == nullptr) + break; } // Change to the new ID elem->setAttribute("id", new_id); - // Make a note of this change, if we need to fix up refs to it + // Make a note of this change, if we need to fix up refs to it if (refmap.find(old_id) != refmap.end()) id_changes->push_back(id_changeitem_type(elem, old_id)); } } - // recurse - for (auto& child: elem->children) - { + for (auto &child : elem->children) { change_clashing_ids(imported_doc, current_doc, &child, refmap, id_changes); } } @@ -331,8 +325,7 @@ change_clashing_ids(SPDocument *imported_doc, SPDocument *current_doc, /** * Fix up references to changed IDs. */ -static void -fix_up_refs(refmap_type const &refmap, const id_changelist_type &id_changes) +static void fix_up_refs(refmap_type const &refmap, const id_changelist_type &id_changes) { id_changelist_type::const_iterator pp; const id_changelist_type::const_iterator pp_end = id_changes.end(); @@ -353,24 +346,21 @@ fix_up_refs(refmap_type const &refmap, const id_changelist_type &id_changes) * clash with IDs in the existing document are changed, and references to * those IDs are updated accordingly. */ -void -prevent_id_clashes(SPDocument *imported_doc, SPDocument *current_doc) +void prevent_id_clashes(SPDocument *imported_doc, SPDocument *current_doc) { refmap_type refmap; id_changelist_type id_changes; SPObject *imported_root = imported_doc->getRoot(); find_references(imported_root, refmap); - change_clashing_ids(imported_doc, current_doc, imported_root, refmap, - &id_changes); + change_clashing_ids(imported_doc, current_doc, imported_root, refmap, &id_changes); fix_up_refs(refmap, id_changes); } /* * Change any references of svg:def from_obj into to_obj */ -void -change_def_references(SPObject *from_obj, SPObject *to_obj) +void change_def_references(SPObject *from_obj, SPObject *to_obj) { refmap_type refmap; SPDocument *current_doc = from_obj->document; @@ -394,16 +384,16 @@ change_def_references(SPObject *from_obj, SPObject *to_obj) */ void rename_id(SPObject *elem, Glib::ustring const &new_name) { - if (new_name.empty()){ + if (new_name.empty()) { g_message("Invalid Id, will not change."); return; } - gchar *id = g_strdup(new_name.c_str()); //id is not empty here as new_name is check to be not empty - g_strcanon (id, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.:", '_'); - Glib::ustring new_name2 = id; //will not fail as id can not be NULL, see length check on new_name - if (!isalnum (new_name2[0])) { + gchar *id = g_strdup(new_name.c_str()); // id is not empty here as new_name is check to be not empty + g_strcanon(id, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.:", '_'); + Glib::ustring new_name2 = id; // will not fail as id can not be NULL, see length check on new_name + if (!isalnum(new_name2[0])) { g_message("Invalid Id, will not change."); - g_free (id); + g_free(id); return; } @@ -424,7 +414,7 @@ void rename_id(SPObject *elem, Glib::ustring const &new_name) break; } } - g_free (id); + g_free(id); // Change to the new ID elem->setAttribute("id", new_name2); // Make a note of this change, if we need to fix up refs to it diff --git a/src/include/glibmm_version.h b/src/include/glibmm_version.h index 39bf2c655c4a71ed607a52f33fd318740c6d106e..8df16182cebb85f91431404c57419b14c3c17c75 100644 --- a/src/include/glibmm_version.h +++ b/src/include/glibmm_version.h @@ -17,7 +17,7 @@ #ifndef GLIBMM_CHECK_VERSION #if !defined(GLIBMM_MAJOR_VERSION) || !defined(GLIBMM_MINOR_VERSION) || !defined(GLIBMM_MICRO_VERSION) - #error "Missing defines for glibmm version (GLIBMM_MAJOR_VERSION / GLIBMM_MINOR_VERSION / GLIBMM_MICRO_VERSION)" +#error "Missing defines for glibmm version (GLIBMM_MAJOR_VERSION / GLIBMM_MINOR_VERSION / GLIBMM_MICRO_VERSION)" #endif /** @@ -34,11 +34,9 @@ * * Returns: %TRUE if glibmm headers are new enough */ -#define GLIBMM_CHECK_VERSION(major,minor,micro) \ - (GLIBMM_MAJOR_VERSION > (major) || \ - (GLIBMM_MAJOR_VERSION == (major) && GLIBMM_MINOR_VERSION > (minor)) || \ - (GLIBMM_MAJOR_VERSION == (major) && GLIBMM_MINOR_VERSION == (minor) && \ - GLIBMM_MICRO_VERSION >= (micro))) +#define GLIBMM_CHECK_VERSION(major, minor, micro) \ + (GLIBMM_MAJOR_VERSION > (major) || (GLIBMM_MAJOR_VERSION == (major) && GLIBMM_MINOR_VERSION > (minor)) || \ + (GLIBMM_MAJOR_VERSION == (major) && GLIBMM_MINOR_VERSION == (minor) && GLIBMM_MICRO_VERSION >= (micro))) #endif // #ifndef GLIBMM_CHECK_VERSION diff --git a/src/include/gtkmm_version.h b/src/include/gtkmm_version.h index a23223cc46ac431dd94119eecc1cf69c68fd3722..31c19f252a84db7401edc26f22585239f5c7b03a 100644 --- a/src/include/gtkmm_version.h +++ b/src/include/gtkmm_version.h @@ -17,7 +17,7 @@ #ifndef GTKMM_CHECK_VERSION #if !defined(GTKMM_MAJOR_VERSION) || !defined(GTKMM_MINOR_VERSION) || !defined(GTKMM_MICRO_VERSION) - #error "Missing defines for gtkmm version (GTKMM_MAJOR_VERSION / GTKMM_MINOR_VERSION / GTKMM_MICRO_VERSION)" +#error "Missing defines for gtkmm version (GTKMM_MAJOR_VERSION / GTKMM_MINOR_VERSION / GTKMM_MICRO_VERSION)" #endif /** @@ -34,11 +34,9 @@ * * Returns: %TRUE if GTK+ headers are new enough */ -#define GTKMM_CHECK_VERSION(major,minor,micro) \ - (GTKMM_MAJOR_VERSION > (major) || \ - (GTKMM_MAJOR_VERSION == (major) && GTKMM_MINOR_VERSION > (minor)) || \ - (GTKMM_MAJOR_VERSION == (major) && GTKMM_MINOR_VERSION == (minor) && \ - GTKMM_MICRO_VERSION >= (micro))) +#define GTKMM_CHECK_VERSION(major, minor, micro) \ + (GTKMM_MAJOR_VERSION > (major) || (GTKMM_MAJOR_VERSION == (major) && GTKMM_MINOR_VERSION > (minor)) || \ + (GTKMM_MAJOR_VERSION == (major) && GTKMM_MINOR_VERSION == (minor) && GTKMM_MICRO_VERSION >= (micro))) #endif // #ifndef GTKMM_CHECK_VERSION diff --git a/src/include/macros.h b/src/include/macros.h index aa1719d2f95539987750fca9c9e6e3fe4ad23e68..8a362570f7293a458d3991a559c6b69af56b69e1 100644 --- a/src/include/macros.h +++ b/src/include/macros.h @@ -16,7 +16,7 @@ // I'm of the opinion that this file should be removed, so I will in the future take the necessary steps to wipe it out. // Macros are not in general bad, but these particular ones are rather ugly. --Liam -#define sp_signal_disconnect_by_data(o,d) g_signal_handlers_disconnect_matched(o, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, d) +#define sp_signal_disconnect_by_data(o, d) g_signal_handlers_disconnect_matched(o, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, d) // "primary" modifier: Ctrl on Linux/Windows and Cmd on macOS. // note: Could query this at runtime with @@ -38,7 +38,7 @@ #define MOD__CTRL_ONLY(event) (((event)->key.state & INK_GDK_MODIFIER_MASK) == INK_GDK_PRIMARY_MASK) #define MOD__ALT_ONLY(event) (((event)->key.state & INK_GDK_MODIFIER_MASK) == GDK_MOD1_MASK) -#endif // SEEN_MACROS_H +#endif // SEEN_MACROS_H /* Local Variables: diff --git a/src/include/source_date_epoch.h b/src/include/source_date_epoch.h index 9080526f796dbc961e21e8ae3cd0a40286000946..c55137b66593159077989846d21a38efacf9416d 100644 --- a/src/include/source_date_epoch.h +++ b/src/include/source_date_epoch.h @@ -13,10 +13,10 @@ #ifndef SEEN_SOURCE_DATE_EPOCH #define SEEN_SOURCE_DATE_EPOCH -#include -#include #include #include +#include +#include namespace ReproducibleBuilds { diff --git a/src/inkgc/gc-alloc.h b/src/inkgc/gc-alloc.h index 8935c1220ae66dce3e740fd3fedb1a82d585310c..8e411c955752d1e3a39e361f3cbf9ffdd9e4f232 100644 --- a/src/inkgc/gc-alloc.h +++ b/src/inkgc/gc-alloc.h @@ -13,8 +13,9 @@ #ifndef SEEN_INKSCAPE_GC_ALLOC_H #define SEEN_INKSCAPE_GC_ALLOC_H -#include #include +#include + #include "inkgc/gc-core.h" namespace Inkscape { @@ -22,7 +23,8 @@ namespace Inkscape { namespace GC { template -class Alloc { +class Alloc +{ public: typedef T value_type; typedef T *pointer; @@ -33,25 +35,27 @@ public: typedef std::ptrdiff_t difference_type; template - struct rebind { typedef Alloc other; }; + struct rebind + { + typedef Alloc other; + }; Alloc() = default; - template Alloc(Alloc const &) {} + template + Alloc(Alloc const &) + {} pointer address(reference r) { return &r; } const_pointer address(const_reference r) { return &r; } - size_type max_size() const { - return std::numeric_limits::max() / sizeof(T); - } + size_type max_size() const { return std::numeric_limits::max() / sizeof(T); } - pointer allocate(size_type count, void const * =nullptr) { + pointer allocate(size_type count, void const * = nullptr) + { return static_cast(::operator new(count * sizeof(T), SCANNED, collect)); } - void construct(pointer p, const_reference value) { - new (static_cast(p)) T(value); - } + void construct(pointer p, const_reference value) { new (static_cast(p)) T(value); } void destroy(pointer p) { p->~T(); } void deallocate(pointer p, size_type) { ::operator delete(p, GC); } @@ -59,21 +63,21 @@ public: // allocators with the same collection policy are interchangeable -template -bool operator==(Alloc const &, Alloc const &) { +template +bool operator==(Alloc const &, Alloc const &) +{ return collect1 == collect2; } -template -bool operator!=(Alloc const &, Alloc const &) { +template +bool operator!=(Alloc const &, Alloc const &) +{ return collect1 != collect2; } -} +} // namespace GC -} +} // namespace Inkscape #endif /* diff --git a/src/inkgc/gc-core.h b/src/inkgc/gc-core.h index cbd4b7ef4c40d803285bcb318407e046a572cfa5..0586849303bbbe60de5b6ce023e13afbf7a36444 100644 --- a/src/inkgc/gc-core.h +++ b/src/inkgc/gc-core.h @@ -13,43 +13,43 @@ #ifndef SEEN_INKSCAPE_GC_CORE_H #define SEEN_INKSCAPE_GC_CORE_H -#include #include - -# include +#include +#include namespace Inkscape { namespace GC { -enum ScanPolicy { +enum ScanPolicy +{ SCANNED, ATOMIC }; -enum CollectionPolicy { +enum CollectionPolicy +{ AUTO, MANUAL }; -enum Delete { +enum Delete +{ GC }; typedef void (*CleanupFunc)(void *mem, void *data); -struct Ops { +struct Ops +{ void (*do_init)(); void *(*malloc)(std::size_t size); void *(*malloc_atomic)(std::size_t size); void *(*malloc_uncollectable)(std::size_t size); void *(*malloc_atomic_uncollectable)(std::size_t size); void *(*base)(void *ptr); - void (*register_finalizer_ignore_self)(void *base, - CleanupFunc func, void *data, - CleanupFunc *old_func, + void (*register_finalizer_ignore_self)(void *base, CleanupFunc func, void *data, CleanupFunc *old_func, void **old_data); - int (*general_register_disappearing_link)(void **p_ptr, - void const *base); + int (*general_register_disappearing_link)(void **p_ptr, void const *base); int (*unregister_disappearing_link)(void **p_ptr); std::size_t (*get_heap_size)(); std::size_t (*get_free_bytes)(); @@ -59,89 +59,60 @@ struct Ops { void (*free)(void *ptr); }; -struct Core { +struct Core +{ public: static void init(); - static inline void *malloc(std::size_t size) { - return _ops.malloc(size); - } - static inline void *malloc_atomic(std::size_t size) { - return _ops.malloc_atomic(size); - } - static inline void *malloc_uncollectable(std::size_t size) { - return _ops.malloc_uncollectable(size); - } - static inline void *malloc_atomic_uncollectable(std::size_t size) { - return _ops.malloc_atomic_uncollectable(size); - } - static inline void *base(void *ptr) { - return _ops.base(ptr); - } - static inline void register_finalizer_ignore_self(void *base, - CleanupFunc func, - void *data, - CleanupFunc *old_func, + static inline void *malloc(std::size_t size) { return _ops.malloc(size); } + static inline void *malloc_atomic(std::size_t size) { return _ops.malloc_atomic(size); } + static inline void *malloc_uncollectable(std::size_t size) { return _ops.malloc_uncollectable(size); } + static inline void *malloc_atomic_uncollectable(std::size_t size) { return _ops.malloc_atomic_uncollectable(size); } + static inline void *base(void *ptr) { return _ops.base(ptr); } + static inline void register_finalizer_ignore_self(void *base, CleanupFunc func, void *data, CleanupFunc *old_func, void **old_data) { - return _ops.register_finalizer_ignore_self(base, func, data, - old_func, old_data); + return _ops.register_finalizer_ignore_self(base, func, data, old_func, old_data); } - static inline int general_register_disappearing_link(void **p_ptr, - void *base) + static inline int general_register_disappearing_link(void **p_ptr, void *base) { return _ops.general_register_disappearing_link(p_ptr, base); } - static inline int unregister_disappearing_link(void **p_ptr) { - return _ops.unregister_disappearing_link(p_ptr); - } - static inline std::size_t get_heap_size() { - return _ops.get_heap_size(); - } - static inline std::size_t get_free_bytes() { - return _ops.get_free_bytes(); - } - static inline void gcollect() { - _ops.gcollect(); - } - static inline void enable() { - _ops.enable(); - } - static inline void disable() { - _ops.disable(); - } - static inline void free(void *ptr) { - return _ops.free(ptr); - } + static inline int unregister_disappearing_link(void **p_ptr) { return _ops.unregister_disappearing_link(p_ptr); } + static inline std::size_t get_heap_size() { return _ops.get_heap_size(); } + static inline std::size_t get_free_bytes() { return _ops.get_free_bytes(); } + static inline void gcollect() { _ops.gcollect(); } + static inline void enable() { _ops.enable(); } + static inline void disable() { _ops.disable(); } + static inline void free(void *ptr) { return _ops.free(ptr); } + private: static Ops _ops; }; -inline void init() { +inline void init() +{ Core::init(); } void request_early_collection(); -} -} +} // namespace GC +} // namespace Inkscape -inline void *operator new(std::size_t size, - Inkscape::GC::ScanPolicy scan, - Inkscape::GC::CollectionPolicy collect, - Inkscape::GC::CleanupFunc cleanup=nullptr, - void *data=nullptr) +inline void *operator new(std::size_t size, Inkscape::GC::ScanPolicy scan, Inkscape::GC::CollectionPolicy collect, + Inkscape::GC::CleanupFunc cleanup = nullptr, void *data = nullptr) { using namespace Inkscape::GC; void *mem; - if ( collect == AUTO ) { - if ( scan == SCANNED ) { + if (collect == AUTO) { + if (scan == SCANNED) { mem = Core::malloc(size); } else { mem = Core::malloc_atomic(size); } } else { - if ( scan == SCANNED ) { + if (scan == SCANNED) { mem = Core::malloc_uncollectable(size); } else { mem = Core::malloc_atomic_uncollectable(size); @@ -156,36 +127,31 @@ inline void *operator new(std::size_t size, return mem; } -inline void *operator new(std::size_t size, - Inkscape::GC::ScanPolicy scan, - Inkscape::GC::CleanupFunc cleanup=nullptr, - void *data=nullptr) +inline void *operator new(std::size_t size, Inkscape::GC::ScanPolicy scan, Inkscape::GC::CleanupFunc cleanup = nullptr, + void *data = nullptr) { return operator new(size, scan, Inkscape::GC::AUTO, cleanup, data); } -inline void *operator new[](std::size_t size, - Inkscape::GC::ScanPolicy scan, - Inkscape::GC::CollectionPolicy collect, - Inkscape::GC::CleanupFunc cleanup=nullptr, - void *data=nullptr) +inline void *operator new[](std::size_t size, Inkscape::GC::ScanPolicy scan, Inkscape::GC::CollectionPolicy collect, + Inkscape::GC::CleanupFunc cleanup = nullptr, void *data = nullptr) { return operator new(size, scan, collect, cleanup, data); } -inline void *operator new[](std::size_t size, - Inkscape::GC::ScanPolicy scan, - Inkscape::GC::CleanupFunc cleanup=nullptr, - void *data=nullptr) +inline void *operator new[](std::size_t size, Inkscape::GC::ScanPolicy scan, + Inkscape::GC::CleanupFunc cleanup = nullptr, void *data = nullptr) { return operator new[](size, scan, Inkscape::GC::AUTO, cleanup, data); } -inline void operator delete(void *mem, Inkscape::GC::Delete) { +inline void operator delete(void *mem, Inkscape::GC::Delete) +{ Inkscape::GC::Core::free(mem); } -inline void operator delete[](void *mem, Inkscape::GC::Delete) { +inline void operator delete[](void *mem, Inkscape::GC::Delete) +{ operator delete(mem, Inkscape::GC::GC); } diff --git a/src/inkgc/gc-managed.h b/src/inkgc/gc-managed.h index 2c2ef7ccc64b406e5307418dc3606348655c65c3..718c0d8f9cef35b0b55fc831acd474ba6a7160ec 100644 --- a/src/inkgc/gc-managed.h +++ b/src/inkgc/gc-managed.h @@ -20,22 +20,18 @@ namespace Inkscape { namespace GC { /** @brief A base class for objects for whom the normal new and delete - * operators should use the garbage-collected allocator - */ -template -class Managed { + * operators should use the garbage-collected allocator + */ +template +class Managed +{ public: - void *operator new(std::size_t size, - ScanPolicy scan=default_scan, - CollectionPolicy collect=default_collect) + void *operator new(std::size_t size, ScanPolicy scan = default_scan, CollectionPolicy collect = default_collect) { return ::operator new(size, scan, collect); } - void *operator new[](std::size_t size, - ScanPolicy scan=default_scan, - CollectionPolicy collect=default_collect) + void *operator new[](std::size_t size, ScanPolicy scan = default_scan, CollectionPolicy collect = default_collect) { return ::operator new[](size, scan, collect); } @@ -43,9 +39,9 @@ public: void operator delete(void *p) { return ::operator delete(p, GC); } }; -} +} // namespace GC -} +} // namespace Inkscape #endif /* diff --git a/src/inkgc/gc-soft-ptr.h b/src/inkgc/gc-soft-ptr.h index b245d81738c89112c6133463084ceac8ae181134..59b1c86aff9415366933cb718369578587720af7 100644 --- a/src/inkgc/gc-soft-ptr.h +++ b/src/inkgc/gc-soft-ptr.h @@ -24,18 +24,22 @@ namespace GC { * finalization cycles. */ template -class soft_ptr { +class soft_ptr +{ public: - soft_ptr(T *pointer=nullptr) : _pointer(pointer) { + soft_ptr(T *pointer = nullptr) + : _pointer(pointer) + { _register(); } operator T *() const { return static_cast(_pointer); } T &operator*() const { return *static_cast(_pointer); } - T *operator->() const { return static_cast(_pointer); } + T *operator->() const { return static_cast(_pointer); } T &operator[](int i) const { return static_cast(_pointer)[i]; } - soft_ptr &operator=(T *pointer) { + soft_ptr &operator=(T *pointer) + { _pointer = pointer; return *this; } @@ -43,8 +47,9 @@ public: // default copy private: - void _register() { - void *base=Core::base(this); + void _register() + { + void *base = Core::base(this); if (base) { Core::general_register_disappearing_link(&_pointer, base); } @@ -53,9 +58,9 @@ private: void *_pointer; }; -} +} // namespace GC -} +} // namespace Inkscape #endif /* diff --git a/src/inkgc/gc.cpp b/src/inkgc/gc.cpp index a290423062fb159b4d45503e1d9c4e0942144565..f0f3ef01f5a97e0a4965ed0993a9ff403cf9ed84 100644 --- a/src/inkgc/gc.cpp +++ b/src/inkgc/gc.cpp @@ -10,25 +10,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "inkgc/gc-core.h" -#include +#include #include -#include #include -#include #include -#include +#include +#include +#include + +#include "inkgc/gc-core.h" namespace Inkscape { namespace GC { namespace { -void display_warning(char *msg, GC_word arg) { +void display_warning(char *msg, GC_word arg) +{ g_warning(msg, arg); } -void do_init() { +void do_init() +{ GC_set_no_dls(1); GC_set_all_interior_pointers(1); GC_set_finalize_on_demand(0); @@ -38,40 +41,48 @@ void do_init() { GC_set_warn_proc(&display_warning); } -void *debug_malloc(std::size_t size) { +void *debug_malloc(std::size_t size) +{ return GC_debug_malloc(size, GC_EXTRAS); } -void *debug_malloc_atomic(std::size_t size) { +void *debug_malloc_atomic(std::size_t size) +{ return GC_debug_malloc_atomic(size, GC_EXTRAS); } -void *debug_malloc_uncollectable(std::size_t size) { +void *debug_malloc_uncollectable(std::size_t size) +{ return GC_debug_malloc_uncollectable(size, GC_EXTRAS); } -void *debug_malloc_atomic_uncollectable(std::size_t size) { +void *debug_malloc_atomic_uncollectable(std::size_t size) +{ return GC_debug_malloc_uncollectable(size, GC_EXTRAS); } -std::ptrdiff_t compute_debug_base_fixup() { - char *base=reinterpret_cast(GC_debug_malloc(1, GC_EXTRAS)); - char *real_base=reinterpret_cast(GC_base(base)); +std::ptrdiff_t compute_debug_base_fixup() +{ + char *base = reinterpret_cast(GC_debug_malloc(1, GC_EXTRAS)); + char *real_base = reinterpret_cast(GC_base(base)); GC_debug_free(base); return base - real_base; } -inline std::ptrdiff_t const &debug_base_fixup() { - static std::ptrdiff_t fixup=compute_debug_base_fixup(); +inline std::ptrdiff_t const &debug_base_fixup() +{ + static std::ptrdiff_t fixup = compute_debug_base_fixup(); return fixup; } -void *debug_base(void *ptr) { - char *base=reinterpret_cast(GC_base(ptr)); +void *debug_base(void *ptr) +{ + char *base = reinterpret_cast(GC_base(ptr)); return base + debug_base_fixup(); } -int debug_general_register_disappearing_link(void **p_ptr, void const *base) { +int debug_general_register_disappearing_link(void **p_ptr, void const *base) +{ char const *real_base = reinterpret_cast(base) - debug_base_fixup(); #if (GC_MAJOR_VERSION >= 7 && GC_MINOR_VERSION >= 4) return GC_general_register_disappearing_link(p_ptr, real_base); @@ -82,10 +93,12 @@ int debug_general_register_disappearing_link(void **p_ptr, void const *base) { void dummy_do_init() {} -void *dummy_base(void *) { return nullptr; } +void *dummy_base(void *) +{ + return nullptr; +} -void dummy_register_finalizer(void *, CleanupFunc, void *, - CleanupFunc *old_func, void **old_data) +void dummy_register_finalizer(void *, CleanupFunc, void *, CleanupFunc *old_func, void **old_data) { if (old_func) { *old_func = nullptr; @@ -95,13 +108,25 @@ void dummy_register_finalizer(void *, CleanupFunc, void *, } } -int dummy_general_register_disappearing_link(void **, void const *) { return false; } +int dummy_general_register_disappearing_link(void **, void const *) +{ + return false; +} -int dummy_unregister_disappearing_link(void **/*link*/) { return false; } +int dummy_unregister_disappearing_link(void ** /*link*/) +{ + return false; +} -std::size_t dummy_get_heap_size() { return 0; } +std::size_t dummy_get_heap_size() +{ + return 0; +} -std::size_t dummy_get_free_bytes() { return 0; } +std::size_t dummy_get_free_bytes() +{ + return 0; +} void dummy_gcollect() {} @@ -109,73 +134,69 @@ void dummy_enable() {} void dummy_disable() {} -Ops enabled_ops = { - &do_init, - &GC_malloc, - &GC_malloc_atomic, - &GC_malloc_uncollectable, - &GC_malloc_atomic_uncollectable, - &GC_base, - &GC_register_finalizer_ignore_self, +Ops enabled_ops = {&do_init, + &GC_malloc, + &GC_malloc_atomic, + &GC_malloc_uncollectable, + &GC_malloc_atomic_uncollectable, + &GC_base, + &GC_register_finalizer_ignore_self, #if (GC_MAJOR_VERSION >= 7 && GC_MINOR_VERSION >= 4) - &GC_general_register_disappearing_link, + &GC_general_register_disappearing_link, #else // compatibility with older Boehm GC versions - (int (*)(void**, const void*))(&GC_general_register_disappearing_link), + (int (*)(void **, const void *))(&GC_general_register_disappearing_link), #endif - &GC_unregister_disappearing_link, - &GC_get_heap_size, - &GC_get_free_bytes, - &GC_gcollect, - &GC_enable, - &GC_disable, - &GC_free -}; - -Ops debug_ops = { - &do_init, - &debug_malloc, - &debug_malloc_atomic, - &debug_malloc_uncollectable, - &debug_malloc_atomic_uncollectable, - &debug_base, - &GC_debug_register_finalizer_ignore_self, - &debug_general_register_disappearing_link, - &GC_unregister_disappearing_link, - &GC_get_heap_size, - &GC_get_free_bytes, - &GC_gcollect, - &GC_enable, - &GC_disable, - &GC_debug_free -}; - -Ops disabled_ops = { - &dummy_do_init, - &std::malloc, - &std::malloc, - &std::malloc, - &std::malloc, - &dummy_base, - &dummy_register_finalizer, - &dummy_general_register_disappearing_link, - &dummy_unregister_disappearing_link, - &dummy_get_heap_size, - &dummy_get_free_bytes, - &dummy_gcollect, - &dummy_enable, - &dummy_disable, - &std::free -}; - -class InvalidGCModeError : public std::runtime_error { + &GC_unregister_disappearing_link, + &GC_get_heap_size, + &GC_get_free_bytes, + &GC_gcollect, + &GC_enable, + &GC_disable, + &GC_free}; + +Ops debug_ops = {&do_init, + &debug_malloc, + &debug_malloc_atomic, + &debug_malloc_uncollectable, + &debug_malloc_atomic_uncollectable, + &debug_base, + &GC_debug_register_finalizer_ignore_self, + &debug_general_register_disappearing_link, + &GC_unregister_disappearing_link, + &GC_get_heap_size, + &GC_get_free_bytes, + &GC_gcollect, + &GC_enable, + &GC_disable, + &GC_debug_free}; + +Ops disabled_ops = {&dummy_do_init, + &std::malloc, + &std::malloc, + &std::malloc, + &std::malloc, + &dummy_base, + &dummy_register_finalizer, + &dummy_general_register_disappearing_link, + &dummy_unregister_disappearing_link, + &dummy_get_heap_size, + &dummy_get_free_bytes, + &dummy_gcollect, + &dummy_enable, + &dummy_disable, + &std::free}; + +class InvalidGCModeError : public std::runtime_error +{ public: InvalidGCModeError(const char *mode) - : runtime_error(std::string("Unknown GC mode \"") + mode + "\"") + : runtime_error(std::string("Unknown GC mode \"") + mode + "\"") {} }; -Ops const &get_ops() { - char *mode_string=std::getenv("_INKSCAPE_GC"); +Ops const &get_ops() +{ + char *mode_string = std::getenv("_INKSCAPE_GC"); if (mode_string) { if (!std::strcmp(mode_string, "enable")) { return enabled_ops; @@ -191,83 +212,92 @@ Ops const &get_ops() { } } -void die_because_not_initialized() { +void die_because_not_initialized() +{ g_error("Attempt to use GC allocator before call to Inkscape::GC::init()"); } -void *stub_malloc(std::size_t) { +void *stub_malloc(std::size_t) +{ die_because_not_initialized(); return nullptr; } -void *stub_base(void *) { +void *stub_base(void *) +{ die_because_not_initialized(); return nullptr; } -void stub_register_finalizer_ignore_self(void *, CleanupFunc, void *, - CleanupFunc *, void **) +void stub_register_finalizer_ignore_self(void *, CleanupFunc, void *, CleanupFunc *, void **) { die_because_not_initialized(); } -int stub_general_register_disappearing_link(void **, void const *) { +int stub_general_register_disappearing_link(void **, void const *) +{ die_because_not_initialized(); return 0; } -int stub_unregister_disappearing_link(void **) { +int stub_unregister_disappearing_link(void **) +{ die_because_not_initialized(); return 0; } -std::size_t stub_get_heap_size() { +std::size_t stub_get_heap_size() +{ die_because_not_initialized(); return 0; } -std::size_t stub_get_free_bytes() { +std::size_t stub_get_free_bytes() +{ die_because_not_initialized(); return 0; } -void stub_gcollect() { +void stub_gcollect() +{ die_because_not_initialized(); } -void stub_enable() { +void stub_enable() +{ die_because_not_initialized(); } -void stub_disable() { +void stub_disable() +{ die_because_not_initialized(); } -void stub_free(void *) { +void stub_free(void *) +{ die_because_not_initialized(); } -} - -Ops Core::_ops = { - nullptr, - &stub_malloc, - &stub_malloc, - &stub_malloc, - &stub_malloc, - &stub_base, - &stub_register_finalizer_ignore_self, - &stub_general_register_disappearing_link, - &stub_unregister_disappearing_link, - &stub_get_heap_size, - &stub_get_free_bytes, - &stub_gcollect, - &stub_enable, - &stub_disable, - &stub_free -}; - -void Core::init() { +} // namespace + +Ops Core::_ops = {nullptr, + &stub_malloc, + &stub_malloc, + &stub_malloc, + &stub_malloc, + &stub_base, + &stub_register_finalizer_ignore_self, + &stub_general_register_disappearing_link, + &stub_unregister_disappearing_link, + &stub_get_heap_size, + &stub_get_free_bytes, + &stub_gcollect, + &stub_enable, + &stub_disable, + &stub_free}; + +void Core::init() +{ try { _ops = get_ops(); } catch (InvalidGCModeError &e) { @@ -278,28 +308,29 @@ void Core::init() { _ops.do_init(); } - namespace { -bool collection_requested=false; -bool collection_task() { +bool collection_requested = false; +bool collection_task() +{ Core::gcollect(); Core::gcollect(); - collection_requested=false; + collection_requested = false; return false; } -} +} // namespace -void request_early_collection() { +void request_early_collection() +{ if (!collection_requested) { - collection_requested=true; + collection_requested = true; Glib::signal_idle().connect(sigc::ptr_fun(&collection_task)); } } -} -} +} // namespace GC +} // namespace Inkscape /* Local Variables: diff --git a/src/inkscape-application.cpp b/src/inkscape-application.cpp index 48b7a1d575462a54ddfe9b947f66863a8510b9c6..de6627ae003dd98c8f49a4749490f816331bfd4e 100644 --- a/src/inkscape-application.cpp +++ b/src/inkscape-application.cpp @@ -8,42 +8,15 @@ * */ -#include +#include // Internationalization #include +#include #include -#include // Internationalization - #ifdef HAVE_CONFIG_H -# include "config.h" // Defines ENABLE_NLS +#include "config.h" // Defines ENABLE_NLS #endif -#include "inkscape-application.h" -#include "inkscape-window.h" - -#include "auto-save.h" // Auto-save -#include "desktop.h" // Access to window -#include "file.h" // sp_file_convert_dpi -#include "inkscape.h" // Inkscape::Application - -#include "include/glibmm_version.h" - -#include "inkgc/gc-core.h" // Garbage Collecting init -#include "debug/logger.h" // INKSCAPE_DEBUG_LOG support - -#include "io/file.h" // File open (command line). -#include "io/resource.h" // TEMPLATE -#include "io/resource-manager.h" // Fix up references. - -#include "object/sp-root.h" // Inkscape version. - -#include "ui/interface.h" // sp_ui_error_dialog -#include "ui/dialog/font-substitution.h" // Warn user about font substitution. -#include "ui/widget/panel.h" // Panel prep -#include "widgets/desktop-widget.h" // Close without saving dialog - -#include "util/units.h" // Redimension window - #include "actions/actions-base.h" // Actions #include "actions/actions-file.h" // Actions #include "actions/actions-object.h" // Actions @@ -51,23 +24,41 @@ #include "actions/actions-selection.h" // Actions #include "actions/actions-transform.h" // Actions #include "actions/actions-window.h" // Actions +#include "auto-save.h" // Auto-save +#include "debug/logger.h" // INKSCAPE_DEBUG_LOG support +#include "desktop.h" // Access to window +#include "file.h" // sp_file_convert_dpi +#include "include/glibmm_version.h" +#include "inkgc/gc-core.h" // Garbage Collecting init +#include "inkscape-application.h" +#include "inkscape-window.h" +#include "inkscape.h" // Inkscape::Application +#include "io/file.h" // File open (command line). +#include "io/resource-manager.h" // Fix up references. +#include "io/resource.h" // TEMPLATE +#include "object/sp-root.h" // Inkscape version. +#include "ui/dialog/font-substitution.h" // Warn user about font substitution. +#include "ui/interface.h" // sp_ui_error_dialog +#include "ui/widget/panel.h" // Panel prep +#include "util/units.h" // Redimension window +#include "widgets/desktop-widget.h" // Close without saving dialog #ifdef GDK_WINDOWING_QUARTZ #include #endif #ifdef WITH_DBUS -# include "extension/dbus/dbus-init.h" +#include "extension/dbus/dbus-init.h" #endif #ifdef ENABLE_NLS // Native Language Support - shouldn't this always be used? -#include "helper/gettext.h" // gettext init -#endif // ENABLE_NLS +#include "helper/gettext.h" // gettext init +#endif // ENABLE_NLS #ifdef WITH_GNU_READLINE -#include #include +#include #endif #include "io/resource.h" @@ -79,13 +70,12 @@ using Inkscape::IO::Resource::UIS; // after calling on_handle_local_options() are assumed to be filenames. // Add document to app. -void -InkscapeApplication::document_add(SPDocument* document) +void InkscapeApplication::document_add(SPDocument *document) { if (document) { auto it = _documents.find(document); if (it == _documents.end()) { - _documents[document] = std::vector(); + _documents[document] = std::vector(); } else { // Should never happen. std::cerr << "InkscapeApplication::add_document: Document already opened!" << std::endl; @@ -97,8 +87,7 @@ InkscapeApplication::document_add(SPDocument* document) } // New document, add it to app. TODO: This should really be open_document with option to strip template data. -SPDocument* -InkscapeApplication::document_new(const std::string &Template) +SPDocument *InkscapeApplication::document_new(const std::string &Template) { // Open file SPDocument *document = ink_file_new(Template); @@ -117,10 +106,8 @@ InkscapeApplication::document_new(const std::string &Template) return document; } - // Open a document, add it to app. -SPDocument* -InkscapeApplication::document_open(const Glib::RefPtr& file, bool *cancelled) +SPDocument *InkscapeApplication::document_open(const Glib::RefPtr &file, bool *cancelled) { // Open file SPDocument *document = ink_file_open(file, cancelled); @@ -128,7 +115,7 @@ InkscapeApplication::document_open(const Glib::RefPtr& file, bool *ca if (document) { document->setVirgin(false); // Prevents replacing document in same window during file open. - document_add (document); + document_add(document); } else if (cancelled == nullptr || !(*cancelled)) { std::cerr << "InkscapeApplication::document_open: Failed to open: " << file->get_parse_name() << std::endl; } @@ -136,10 +123,8 @@ InkscapeApplication::document_open(const Glib::RefPtr& file, bool *ca return document; } - // Open a document, add it to app. -SPDocument* -InkscapeApplication::document_open(const std::string& data) +SPDocument *InkscapeApplication::document_open(const std::string &data) { // Open file SPDocument *document = ink_file_open(data); @@ -147,7 +132,7 @@ InkscapeApplication::document_open(const std::string& data) if (document) { document->setVirgin(false); // Prevents replacing document in same window during file open. - document_add (document); + document_add(document); } else { std::cerr << "InkscapeApplication::document_open: Failed to open memory document." << std::endl; } @@ -155,20 +140,18 @@ InkscapeApplication::document_open(const std::string& data) return document; } - /** Swap out one document for another in a window... maybe this should disappear. * Does not delete old document! */ -bool -InkscapeApplication::document_swap(InkscapeWindow* window, SPDocument* document) +bool InkscapeApplication::document_swap(InkscapeWindow *window, SPDocument *document) { if (!document || !window) { std::cerr << "InkscapeAppliation::swap_document: Missing window or document!" << std::endl; return false; } - SPDesktop* desktop = window->get_desktop(); - SPDocument* old_document = window->get_document(); + SPDesktop *desktop = window->get_desktop(); + SPDocument *old_document = window->get_document(); desktop->change_document(document); document->emitResizedSignal(document->getWidth().value("px"), document->getHeight().value("px")); @@ -177,7 +160,6 @@ InkscapeApplication::document_swap(InkscapeWindow* window, SPDocument* document) // Find old document auto it = _documents.find(old_document); if (it != _documents.end()) { - // Remove window from document map. auto it2 = std::find(it->second.begin(), it->second.end(), window); if (it2 != it->second.end()) { @@ -204,17 +186,16 @@ InkscapeApplication::document_swap(InkscapeWindow* window, SPDocument* document) // ActionContext should be removed once verbs are gone but we use it for now. Inkscape::ActionContext context = INKSCAPE.action_context_for_document(document); - _active_document = document; + _active_document = document; _active_selection = context.getSelection(); - _active_view = context.getView(); - _active_window = window; + _active_view = context.getView(); + _active_window = window; return true; } /** Revert document: open saved document and swap it for each window. */ -bool -InkscapeApplication::document_revert(SPDocument* document) +bool InkscapeApplication::document_revert(SPDocument *document) { // Find saved document. gchar const *path = document->getDocumentURI(); @@ -225,7 +206,7 @@ InkscapeApplication::document_revert(SPDocument* document) // Open saved document. Glib::RefPtr file = Gio::File::create_for_path(document->getDocumentURI()); - SPDocument* new_document = document_open (file); + SPDocument *new_document = document_open(file); if (!new_document) { std::cerr << "InkscapeApplication::revert_document: Cannot open saved document!" << std::endl; return false; @@ -236,26 +217,24 @@ InkscapeApplication::document_revert(SPDocument* document) auto it = _documents.find(document); if (it != _documents.end()) { - // Swap reverted document in all windows. for (auto it2 : it->second) { - - SPDesktop* desktop = it2->get_desktop(); + SPDesktop *desktop = it2->get_desktop(); // Remember current zoom and view. double zoom = desktop->current_zoom(); Geom::Point c = desktop->current_center(); - bool reverted = document_swap (it2, new_document); + bool reverted = document_swap(it2, new_document); if (reverted) { - desktop->zoom_absolute_center_point (c, zoom); + desktop->zoom_absolute_center_point(c, zoom); } else { std::cerr << "InkscapeApplication::revert_document: Revert failed!" << std::endl; } } - document_close (document); + document_close(document); } else { std::cerr << "InkscapeApplication::revert_document: Document not found!" << std::endl; return false; @@ -263,15 +242,11 @@ InkscapeApplication::document_revert(SPDocument* document) return true; } - - /** Close a document, remove from app. No checking is done on modified status, etc. */ -void -InkscapeApplication::document_close(SPDocument* document) +void InkscapeApplication::document_close(SPDocument *document) { if (document) { - auto it = _documents.find(document); if (it != _documents.end()) { if (it->second.size() != 0) { @@ -289,11 +264,9 @@ InkscapeApplication::document_close(SPDocument* document) } } - /** Return number of windows with document. */ -unsigned -InkscapeApplication::document_window_count(SPDocument* document) +unsigned InkscapeApplication::document_window_count(SPDocument *document) { unsigned count = 0; @@ -309,27 +282,25 @@ InkscapeApplication::document_window_count(SPDocument* document) /** Fix up a document if necessary (Only fixes that require GUI). */ -void -InkscapeApplication::document_fix(InkscapeWindow* window) +void InkscapeApplication::document_fix(InkscapeWindow *window) { // Most fixes are handled when document is opened in SPDocument::createDoc(). // But some require the GUI to be present. These are handled here. if (_with_gui) { - - SPDocument* document = window->get_document(); + SPDocument *document = window->get_document(); // Perform a fixup pass for hrefs. - if ( Inkscape::ResourceManager::getManager().fixupBrokenLinks(document) ) { + if (Inkscape::ResourceManager::getManager().fixupBrokenLinks(document)) { Glib::ustring msg = _("Broken links have been changed to point to existing files."); - SPDesktop* desktop = window->get_desktop(); + SPDesktop *desktop = window->get_desktop(); if (desktop != nullptr) { desktop->showInfoDialog(msg); } } // Fix dpi (pre-92 files). - if ( sp_version_inside_range( document->getRoot()->version.inkscape, 0, 1, 0, 92 ) ) { + if (sp_version_inside_range(document->getRoot()->version.inkscape, 0, 1, 0, 92)) { sp_file_convert_dpi(document); } @@ -338,24 +309,19 @@ InkscapeApplication::document_fix(InkscapeWindow* window) } } - /** Get a list of open documents (from document map). */ -std::vector -InkscapeApplication::get_documents() +std::vector InkscapeApplication::get_documents() { - std::vector documents; + std::vector documents; for (auto &i : _documents) { documents.push_back(i.first); } return documents; } - - // Take an already open document and create a new window, adding window to document map. -InkscapeWindow* -InkscapeApplication::window_open(SPDocument* document) +InkscapeWindow *InkscapeApplication::window_open(SPDocument *document) { // Once we've removed Inkscape::Application (separating GUI from non-GUI stuff) // it will be more easy to start up the GUI after-the-fact. Until then, prevent @@ -365,7 +331,7 @@ InkscapeApplication::window_open(SPDocument* document) return nullptr; } - InkscapeWindow* window = new InkscapeWindow(document); + InkscapeWindow *window = new InkscapeWindow(document); // TODO Add window to application. (Instead of in InkscapeWindow constructor.) // To be removed (add once per window)! @@ -374,9 +340,9 @@ InkscapeApplication::window_open(SPDocument* document) // ActionContext should be removed once verbs are gone but we use it for now. Inkscape::ActionContext context = INKSCAPE.action_context_for_document(document); _active_selection = context.getSelection(); - _active_view = context.getView(); - _active_document = document; - _active_window = window; + _active_view = context.getView(); + _active_document = document; + _active_window = window; auto it = _documents.find(document); if (it != _documents.end()) { @@ -390,26 +356,22 @@ InkscapeApplication::window_open(SPDocument* document) return window; } - // Close a window. Does not delete document. -void -InkscapeApplication::window_close(InkscapeWindow* window) +void InkscapeApplication::window_close(InkscapeWindow *window) { // std::cout << "InkscapeApplication::close_window" << std::endl; // dump(); if (window) { - - SPDocument* document = window->get_document(); + SPDocument *document = window->get_document(); if (document) { - // To be removed (remove once per window)! /* bool last = */ INKSCAPE.remove_document(document); // Leave active document alone (maybe should find new active window and reset variables). _active_selection = nullptr; - _active_view = nullptr; - _active_window = nullptr; + _active_view = nullptr; + _active_window = nullptr; // Remove window from document map. auto it = _documents.find(document); @@ -435,31 +397,27 @@ InkscapeApplication::window_close(InkscapeWindow* window) // dump(); } - // Closes active window (useful for scripting). -void -InkscapeApplication::window_close_active() +void InkscapeApplication::window_close_active() { if (_active_window) { - window_close (_active_window); + window_close(_active_window); } else { std::cerr << "InkscapeApplication::window_close_active: no active window!" << std::endl; } } - /** Update windows in response to: * - New active window * - Document change * - Selection change */ -void -InkscapeApplication::windows_update(SPDocument* document) +void InkscapeApplication::windows_update(SPDocument *document) { // Find windows: - auto it = _documents.find( document ); + auto it = _documents.find(document); if (it != _documents.end()) { - std::vector windows = it->second; + std::vector windows = it->second; // std::cout << "InkscapeApplication::update_windows: windows size: " << windows.size() << std::endl; // Loop over InkscapeWindows. // Loop over DialogWindows. TBD @@ -470,31 +428,28 @@ InkscapeApplication::windows_update(SPDocument* document) /** Debug function */ -void -InkscapeApplication::dump() +void InkscapeApplication::dump() { std::cout << "InkscapeApplication::dump()" << std::endl; std::cout << " Documents: " << _documents.size() << std::endl; for (auto i : _documents) { - std::cout << " Document: " << (i.first->getDocumentName()?i.first->getDocumentName():"unnamed") << std::endl; + std::cout << " Document: " << (i.first->getDocumentName() ? i.first->getDocumentName() : "unnamed") + << std::endl; for (auto j : i.second) { std::cout << " Window: " << j->get_title() << std::endl; } } } - -template -ConcreteInkscapeApplication& -ConcreteInkscapeApplication::get_instance() +template +ConcreteInkscapeApplication &ConcreteInkscapeApplication::get_instance() { static ConcreteInkscapeApplication instance; return instance; } -template -void -ConcreteInkscapeApplication::_start_main_option_section(const Glib::ustring& section_name) +template +void ConcreteInkscapeApplication::_start_main_option_section(const Glib::ustring §ion_name) { #ifndef _WIN32 // Avoid outputting control characters to non-tty destinations. @@ -524,14 +479,13 @@ ConcreteInkscapeApplication::_start_main_option_section(const Glib::ustring& // "g_application_set_application_id: assertion '!application->priv->is_registered' failed". // It also require generating new id's for each separate Inkscape instance required. -template +template ConcreteInkscapeApplication::ConcreteInkscapeApplication() : T("org.inkscape.Inkscape", - Gio::APPLICATION_HANDLES_OPEN | // Use default file opening. - Gio::APPLICATION_NON_UNIQUE ) + Gio::APPLICATION_HANDLES_OPEN | // Use default file opening. + Gio::APPLICATION_NON_UNIQUE) , InkscapeApplication() { - // ==================== Initializations ===================== // Garbage Collector Inkscape::GC::init(); @@ -567,17 +521,20 @@ ConcreteInkscapeApplication::ConcreteInkscapeApplication() // Will automatically handle character conversions. // Note: OPTION_TYPE_FILENAME => std::string, OPTION_TYPE_STRING => Glib::ustring. -#if GLIBMM_CHECK_VERSION(2,56,0) +#if GLIBMM_CHECK_VERSION(2, 56, 0) // Additional informational strings for --help output // TODO: Claims to be translated automatically, but seems broken, so pass already translated strings this->set_option_context_parameter_string(_("file1 [file2 [fileN]]")); this->set_option_context_summary(_("Process (or open) one or more files.")); - this->set_option_context_description(Glib::ustring("\n") + _("Examples:") + '\n' - + " " + Glib::ustring::compose(_("Export input SVG (%1) to PDF (%2) format:"), "in.svg", "out.pdf") + '\n' - + '\t' + "inkscape --export-filename=out.pdf in.svg\n" - + " " + Glib::ustring::compose(_("Export input files (%1) to PNG format keeping original name (%2):"), "in1.svg, in2.svg", "in1.png, in2.png") + '\n' - + '\t' + "inkscape --export-type=png in1.svg in2.svg\n" - + " " + Glib::ustring::compose(_("See %1 and %2 for more details."), "'man inkscape'", "http://wiki.inkscape.org/wiki/index.php/Using_the_Command_Line")); + this->set_option_context_description( + Glib::ustring("\n") + _("Examples:") + '\n' + " " + + Glib::ustring::compose(_("Export input SVG (%1) to PDF (%2) format:"), "in.svg", "out.pdf") + '\n' + '\t' + + "inkscape --export-filename=out.pdf in.svg\n" + " " + + Glib::ustring::compose(_("Export input files (%1) to PNG format keeping original name (%2):"), + "in1.svg, in2.svg", "in1.png, in2.png") + + '\n' + '\t' + "inkscape --export-type=png in1.svg in2.svg\n" + " " + + Glib::ustring::compose(_("See %1 and %2 for more details."), "'man inkscape'", + "http://wiki.inkscape.org/wiki/index.php/Using_the_Command_Line")); #endif // clang-format off @@ -663,7 +620,8 @@ ConcreteInkscapeApplication::ConcreteInkscapeApplication() #endif // WITH_DBUS // clang-format on - Gio::Application::signal_handle_local_options().connect(sigc::mem_fun(*this, &InkscapeApplication::on_handle_local_options)); + Gio::Application::signal_handle_local_options().connect( + sigc::mem_fun(*this, &InkscapeApplication::on_handle_local_options)); // This is normally called for us... but after the "handle_local_options" signal is emitted. If // we want to rely on actions for handling options, we need to call it here. This appears to @@ -671,18 +629,16 @@ ConcreteInkscapeApplication::ConcreteInkscapeApplication() T::register_application(); } -template -void -ConcreteInkscapeApplication::on_startup() +template +void ConcreteInkscapeApplication::on_startup() { T::on_startup(); } // Here are things that should be in on_startup() but cannot be as we don't set _with_gui until // on_handle_local_options() is called. -template<> -void -ConcreteInkscapeApplication::on_startup2() +template <> +void ConcreteInkscapeApplication::on_startup2() { Inkscape::Application::create(false); } @@ -693,9 +649,8 @@ static gboolean osx_openfile_callback(GtkosxApplication *, gchar const *, static gboolean osx_quit_callback(GtkosxApplication *, ConcreteInkscapeApplication *); #endif -template<> -void -ConcreteInkscapeApplication::on_startup2() +template <> +void ConcreteInkscapeApplication::on_startup2() { // This should be completely rewritten. Inkscape::Application::create(_with_gui); @@ -705,8 +660,8 @@ ConcreteInkscapeApplication::on_startup2() } // ======================= Actions (GUI) ====================== - add_action("new", sigc::mem_fun(*this, &InkscapeApplication::on_new )); - add_action("quit", sigc::mem_fun(*this, &InkscapeApplication::on_quit )); + add_action("new", sigc::mem_fun(*this, &InkscapeApplication::on_new)); + add_action("quit", sigc::mem_fun(*this, &InkscapeApplication::on_quit)); // ========================= GUI Init ========================= Gtk::Window::set_default_icon_name("org.inkscape.Inkscape"); @@ -719,12 +674,9 @@ ConcreteInkscapeApplication::on_startup2() Glib::ustring app_builder_file = get_filename(UIS, "inkscape-application.glade"); - try - { + try { _builder->add_from_file(app_builder_file); - } - catch (const Glib::Error& ex) - { + } catch (const Glib::Error &ex) { std::cerr << "InkscapeApplication: " << app_builder_file << " file not read! " << ex.what() << std::endl; } @@ -745,9 +697,8 @@ ConcreteInkscapeApplication::on_startup2() /** We should not create a window if T is Gio::Applicaton. */ -template -InkscapeWindow* -ConcreteInkscapeApplication::create_window(SPDocument *document, bool replace) +template +InkscapeWindow *ConcreteInkscapeApplication::create_window(SPDocument *document, bool replace) { std::cerr << "ConcreteInkscapeApplication::create_window: Should not be called!" << std::endl; return nullptr; @@ -755,78 +706,70 @@ ConcreteInkscapeApplication::create_window(SPDocument *document, bool replace /** Create a window given a document. This is used internally in InkscapeApplication. */ -template<> -InkscapeWindow* -ConcreteInkscapeApplication::create_window(SPDocument *document, bool replace) +template <> +InkscapeWindow *ConcreteInkscapeApplication::create_window(SPDocument *document, bool replace) { SPDocument *old_document = _active_document; - InkscapeWindow* window = InkscapeApplication::get_active_window(); + InkscapeWindow *window = InkscapeApplication::get_active_window(); if (replace && old_document && window) { - document_swap (window, document); + document_swap(window, document); // Delete old document if no longer attached to any window. - auto it = _documents.find (old_document); + auto it = _documents.find(old_document); if (it != _documents.end()) { if (it->second.size() == 0) { - document_close (old_document); + document_close(old_document); } } document->emitResizedSignal(document->getWidth().value("px"), document->getHeight().value("px")); } else { - window = window_open (document); + window = window_open(document); } window->show(); return window; } - /** We should not create a window if T is Gio::Applicaton. -*/ -template -void -ConcreteInkscapeApplication::create_window(const Glib::RefPtr& file, - bool add_to_recent, - bool replace_empty) + */ +template +void ConcreteInkscapeApplication::create_window(const Glib::RefPtr &file, bool add_to_recent, + bool replace_empty) { std::cerr << "ConcreteInkscapeApplication::create_window: Should not be called!" << std::endl; } - /** Create a window given a Gio::File. This is what most external functions should call. The booleans are only false when opening a help file. */ -template<> -void -ConcreteInkscapeApplication::create_window(const Glib::RefPtr& file, - bool add_to_recent, - bool replace_empty) +template <> +void ConcreteInkscapeApplication::create_window(const Glib::RefPtr &file, + bool add_to_recent, bool replace_empty) { - SPDocument* document = nullptr; - InkscapeWindow* window = nullptr; + SPDocument *document = nullptr; + InkscapeWindow *window = nullptr; bool cancelled = false; if (file) { document = document_open(file, &cancelled); if (document) { - if (add_to_recent) { auto recentmanager = Gtk::RecentManager::get_default(); - recentmanager->add_item (file->get_uri()); + recentmanager->add_item(file->get_uri()); } - SPDocument* old_document = _active_document; + SPDocument *old_document = _active_document; bool replace = replace_empty && old_document && old_document->getVirgin(); // virgin == true => an empty document (template). - window = create_window (document, replace); + window = create_window(document, replace); } else if (!cancelled) { - std::cerr << "ConcreteInkscapeApplication::create_window: Failed to load: " - << file->get_parse_name() << std::endl; + std::cerr << "ConcreteInkscapeApplication::create_window: Failed to load: " << file->get_parse_name() + << std::endl; gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), file->get_parse_name().c_str()); sp_ui_error_dialog(text); @@ -836,20 +779,21 @@ ConcreteInkscapeApplication::create_window(const Glib::RefPtr< } else { std::string Template = Inkscape::IO::Resource::get_filename(Inkscape::IO::Resource::TEMPLATES, "default.svg", true); - document = document_new (Template); + document = document_new(Template); if (document) { - window = window_open (document); + window = window_open(document); } else { - std::cerr << "ConcreteInkscapeApplication::create_window: Failed to open default template! " << Template << std::endl; + std::cerr << "ConcreteInkscapeApplication::create_window: Failed to open default template! " << Template + << std::endl; } } _active_document = document; - _active_window = window; + _active_window = window; #ifdef WITH_DBUS if (window) { - SPDesktop* desktop = window->get_desktop(); + SPDesktop *desktop = window->get_desktop(); if (desktop) { Inkscape::Extension::Dbus::dbus_init_desktop_interface(desktop); } else { @@ -861,9 +805,8 @@ ConcreteInkscapeApplication::create_window(const Glib::RefPtr< /** No need to destroy window if T is Gio::Application. */ -template -bool -ConcreteInkscapeApplication::destroy_window(InkscapeWindow* window) +template +bool ConcreteInkscapeApplication::destroy_window(InkscapeWindow *window) { std::cerr << "ConcreteInkscapeApplication::destroy_window: Should not be called!"; return false; @@ -872,17 +815,15 @@ ConcreteInkscapeApplication::destroy_window(InkscapeWindow* window) /** Destroy a window. Aborts if document needs saving. * Returns true if window destroyed. */ -template<> -bool -ConcreteInkscapeApplication::destroy_window(InkscapeWindow* window) +template <> +bool ConcreteInkscapeApplication::destroy_window(InkscapeWindow *window) { - SPDocument* document = window->get_document(); + SPDocument *document = window->get_document(); // Remove document if no windows left. if (document) { auto it = _documents.find(document); if (it != _documents.end()) { - // If only one window for document: if (it->second.size() == 1) { // Check if document needs saving. @@ -895,11 +836,12 @@ ConcreteInkscapeApplication::destroy_window(InkscapeWindow* wi window_close(window); if (it->second.size() == 0) { - document_close (document); + document_close(document); } } else { - std::cerr << "ConcreteInkscapeApplication::destroy_window: Could not find document!" << std::endl; + std::cerr << "ConcreteInkscapeApplication::destroy_window: Could not find document!" + << std::endl; } } @@ -911,32 +853,30 @@ ConcreteInkscapeApplication::destroy_window(InkscapeWindow* wi } /* Close all windows and exit. -**/ -template -void -ConcreteInkscapeApplication::destroy_all() + **/ +template +void ConcreteInkscapeApplication::destroy_all() { std::cerr << "ConcreteInkscapeApplication::destroy_all: Should not be called!"; } -template<> -void -ConcreteInkscapeApplication::destroy_all() +template <> +void ConcreteInkscapeApplication::destroy_all() { while (_documents.size() != 0) { auto it = _documents.begin(); if (!it->second.empty()) { auto it2 = it->second.begin(); - if (!destroy_window (*it2)) return; // If destroy aborted, we need to stop exit. + if (!destroy_window(*it2)) + return; // If destroy aborted, we need to stop exit. } } } /** Common processing for documents */ -template -void -ConcreteInkscapeApplication::process_document(SPDocument* document, std::string output_path) +template +void ConcreteInkscapeApplication::process_document(SPDocument *document, std::string output_path) { // Add to Inkscape::Application... INKSCAPE.add_document(document); @@ -951,18 +891,19 @@ ConcreteInkscapeApplication::process_document(SPDocument* document, std::stri // ActionContext should be removed once verbs are gone but we use it for now. Inkscape::ActionContext context = INKSCAPE.action_context_for_document(document); - _active_document = document; + _active_document = document; _active_selection = context.getSelection(); - _active_view = context.getView(); + _active_view = context.getView(); document->ensureUpToDate(); // Or queries don't work! // process_file - for (auto action: _command_line_actions) { + for (auto action : _command_line_actions) { if (!Gio::Application::has_action(action.first)) { - std::cerr << "ConcreteInkscapeApplication::process_document: Unknown action name: " << action.first << std::endl; + std::cerr << "ConcreteInkscapeApplication::process_document: Unknown action name: " << action.first + << std::endl; } - Gio::Application::activate_action( action.first, action.second ); + Gio::Application::activate_action(action.first, action.second); } if (_use_shell) { @@ -976,11 +917,9 @@ ConcreteInkscapeApplication::process_document(SPDocument* document, std::stri } } - // Open document window with default document or pipe. Either this or on_open() is called. -template -void -ConcreteInkscapeApplication::on_activate() +template +void ConcreteInkscapeApplication::on_activate() { on_startup2(); @@ -990,19 +929,17 @@ ConcreteInkscapeApplication::on_activate() SPDocument *document = nullptr; if (_use_pipe) { - // Create document from pipe in. std::istreambuf_iterator begin(std::cin), end; std::string s(begin, end); - document = document_open (s); + document = document_open(s); output = "-"; } else { - // Create a blank document from template std::string Template = Inkscape::IO::Resource::get_filename(Inkscape::IO::Resource::TEMPLATES, "default.svg", true); - document = document_new (Template); + document = document_new(Template); } if (!document) { @@ -1011,19 +948,18 @@ ConcreteInkscapeApplication::on_activate() } // Process document (command line actions, shell, create window) - process_document (document, output); + process_document(document, output); } // Open document window for each file. Either this or on_activate() is called. // type_vec_files == std::vector > -template -void -ConcreteInkscapeApplication::on_open(const Gio::Application::type_vec_files& files, const Glib::ustring& hint) +template +void ConcreteInkscapeApplication::on_open(const Gio::Application::type_vec_files &files, const Glib::ustring &hint) { on_startup2(); - if(_pdf_poppler) + if (_pdf_poppler) INKSCAPE.set_pdf_poppler(_pdf_poppler); - if(_pdf_page) + if (_pdf_page) INKSCAPE.set_pdf_page(_pdf_page); if (files.size() > 1 && !_file_export.export_filename.empty()) { @@ -1036,16 +972,15 @@ ConcreteInkscapeApplication::on_open(const Gio::Application::type_vec_files& } for (auto file : files) { - // Open file - SPDocument *document = document_open (file); + SPDocument *document = document_open(file); if (!document) { std::cerr << "ConcreteInkscapeApplication::on_open: failed to create document!" << std::endl; continue; } // Process document (command line actions, shell, create window) - process_document (document, file->get_path()); + process_document(document, file->get_path()); } if (_batch_process) { @@ -1054,9 +989,8 @@ ConcreteInkscapeApplication::on_open(const Gio::Application::type_vec_files& } } -template -void -ConcreteInkscapeApplication::parse_actions(const Glib::ustring& input, action_vector_t& action_vector) +template +void ConcreteInkscapeApplication::parse_actions(const Glib::ustring &input, action_vector_t &action_vector) { const auto re_colon = Glib::Regex::create("\\s*:\\s*"); @@ -1064,7 +998,7 @@ ConcreteInkscapeApplication::parse_actions(const Glib::ustring& input, action std::vector tokens = Glib::Regex::split_simple("\\s*;\\s*", input); for (auto token : tokens) { // Note: split into 2 tokens max ("param:value"); allows value to contain colon (e.g. abs. paths on Windows) - std::vector tokens2 = re_colon->split(token, 0, static_cast(0), 2); + std::vector tokens2 = re_colon->split(token, 0, static_cast(0), 2); std::string action; std::string value; if (tokens2.size() > 0) { @@ -1077,7 +1011,7 @@ ConcreteInkscapeApplication::parse_actions(const Glib::ustring& input, action Glib::RefPtr action_ptr = Gio::Application::lookup_action(action); if (action_ptr) { // Doesn't seem to be a way to test this using the C++ binding without Glib-CRITICAL errors. - const GVariantType* gtype = g_action_get_parameter_type(action_ptr->gobj()); + const GVariantType *gtype = g_action_get_parameter_type(action_ptr->gobj()); if (gtype) { // With value. Glib::VariantType type = action_ptr->get_parameter_type(); @@ -1088,33 +1022,29 @@ ConcreteInkscapeApplication::parse_actions(const Glib::ustring& input, action } else if (value == "0" || value == "false") { b = false; } else { - std::cerr << "InkscapeApplication::parse_actions: Invalid boolean value: " << action << ":" << value << std::endl; + std::cerr << "InkscapeApplication::parse_actions: Invalid boolean value: " << action << ":" + << value << std::endl; } - action_vector.push_back( - std::make_pair( action, Glib::Variant::create(b))); + action_vector.push_back(std::make_pair(action, Glib::Variant::create(b))); } else if (type.get_string() == "i") { - action_vector.push_back( - std::make_pair( action, Glib::Variant::create(std::stoi(value)))); + action_vector.push_back(std::make_pair(action, Glib::Variant::create(std::stoi(value)))); } else if (type.get_string() == "d") { - action_vector.push_back( - std::make_pair( action, Glib::Variant::create(std::stod(value)))); + action_vector.push_back(std::make_pair(action, Glib::Variant::create(std::stod(value)))); } else if (type.get_string() == "s") { - action_vector.push_back( - std::make_pair( action, Glib::Variant::create(value) )); + action_vector.push_back(std::make_pair(action, Glib::Variant::create(value))); } else { - std::cerr << "InkscapeApplication::parse_actions: unhandled action value: " - << action << ": " << type.get_string() << std::endl; + std::cerr << "InkscapeApplication::parse_actions: unhandled action value: " << action << ": " + << type.get_string() << std::endl; } } else { // Stateless (i.e. no value). - action_vector.push_back( std::make_pair( action, Glib::VariantBase() ) ); + action_vector.push_back(std::make_pair(action, Glib::VariantBase())); } } else { // Assume a verb // std::cerr << "InkscapeApplication::parse_actions: '" // << action << "' is not a valid action! Assuming verb!" << std::endl; - action_vector.push_back( - std::make_pair("verb", Glib::Variant::create(action))); + action_vector.push_back(std::make_pair("verb", Glib::Variant::create(action))); } } } @@ -1122,13 +1052,14 @@ ConcreteInkscapeApplication::parse_actions(const Glib::ustring& input, action #ifdef WITH_GNU_READLINE // For use in shell mode. Command completion of action names. -char* readline_generator (const char* text, int state) +char *readline_generator(const char *text, int state) { static std::vector actions; // Fill the vector of action names. if (actions.size() == 0) { - ConcreteInkscapeApplication* app = &(ConcreteInkscapeApplication::get_instance()); + ConcreteInkscapeApplication *app = + &(ConcreteInkscapeApplication::get_instance()); actions = app->list_actions(); std::sort(actions.begin(), actions.end()); } @@ -1141,26 +1072,26 @@ char* readline_generator (const char* text, int state) len = strlen(text); } - const char* name = nullptr; + const char *name = nullptr; while (list_index < actions.size()) { name = actions[list_index].c_str(); list_index++; - if (strncmp (name, text, len) == 0) { + if (strncmp(name, text, len) == 0) { return (strdup(name)); } } - return ((char*)nullptr); + return ((char *)nullptr); } -char** readline_completion(const char* text, int start, int end) +char **readline_completion(const char *text, int start, int end) { - char **matches = (char**)nullptr; + char **matches = (char **)nullptr; // Match actions names, but only at start of line. // It would be nice to also match action names after a ';' but it's not possible as text won't include ';'. if (start == 0) { - matches = rl_completion_matches (text, readline_generator); + matches = rl_completion_matches(text, readline_generator); } return (matches); @@ -1173,11 +1104,9 @@ void readline_init() } #endif // WITH_GNU_READLINE - // Once we don't need to create a window just to process verbs! -template -void -ConcreteInkscapeApplication::shell() +template +void ConcreteInkscapeApplication::shell() { std::cout << "Inkscape interactive shell mode. Type 'action-list' to list all actions. " << "Type 'quit' to quit." << std::endl; @@ -1222,14 +1151,15 @@ ConcreteInkscapeApplication::shell() action_vector_t action_vector; parse_actions(input, action_vector); - for (auto action: action_vector) { - Gio::Application::activate_action( action.first, action.second ); + for (auto action : action_vector) { + Gio::Application::activate_action(action.first, action.second); } // This would allow displaying the results of actions on the fly... but it needs to be well // vetted first. Glib::RefPtr context = Glib::MainContext::get_default(); - while (context->iteration(false)) {}; + while (context->iteration(false)) { + }; } if (_with_gui) { @@ -1237,7 +1167,6 @@ ConcreteInkscapeApplication::shell() } } - // ========================= Callbacks ========================== /* @@ -1248,9 +1177,8 @@ ConcreteInkscapeApplication::shell() * For each file without GUI: Open -> Query -> Process -> Export * More flexible processing can be done via actions. */ -template -int -ConcreteInkscapeApplication::on_handle_local_options(const Glib::RefPtr& options) +template +int ConcreteInkscapeApplication::on_handle_local_options(const Glib::RefPtr &options) { if (!options) { std::cerr << "InkscapeApplication::on_handle_local_options: options is null!" << std::endl; @@ -1291,68 +1219,45 @@ ConcreteInkscapeApplication::on_handle_local_options(const Glib::RefPtrcontains("pipe") || - - options->contains("export-filename") || - options->contains("export-overwrite") || - options->contains("export-type") || - - options->contains("export-area-page") || - options->contains("export-area-drawing") || - options->contains("export-area") || - options->contains("export-area-snap") || - options->contains("export-dpi") || - options->contains("export-width") || - options->contains("export-height") || - options->contains("export-margin") || - options->contains("export-height") || - - options->contains("export-id") || - options->contains("export-id-only") || - options->contains("export-plain-svg") || - options->contains("export-ps-level") || - options->contains("export-pdf-version") || - options->contains("export-text-to_path") || - options->contains("export-latex") || - options->contains("export-ignore-filters") || - options->contains("export-use-hints") || - options->contains("export-background") || - options->contains("export-background-opacity") || - options->contains("export-text-to_path") || - - options->contains("query-id") || - options->contains("query-x") || - options->contains("query-all") || - options->contains("query-y") || - options->contains("query-width") || - options->contains("query-height") || - - options->contains("vacuum-defs") || - options->contains("select") || - options->contains("actions") || - options->contains("verb") || - options->contains("shell") - ) { + if (options->contains("pipe") || + + options->contains("export-filename") || options->contains("export-overwrite") || + options->contains("export-type") || + + options->contains("export-area-page") || options->contains("export-area-drawing") || + options->contains("export-area") || options->contains("export-area-snap") || options->contains("export-dpi") || + options->contains("export-width") || options->contains("export-height") || options->contains("export-margin") || + options->contains("export-height") || + + options->contains("export-id") || options->contains("export-id-only") || + options->contains("export-plain-svg") || options->contains("export-ps-level") || + options->contains("export-pdf-version") || options->contains("export-text-to_path") || + options->contains("export-latex") || options->contains("export-ignore-filters") || + options->contains("export-use-hints") || options->contains("export-background") || + options->contains("export-background-opacity") || options->contains("export-text-to_path") || + + options->contains("query-id") || options->contains("query-x") || options->contains("query-all") || + options->contains("query-y") || options->contains("query-width") || options->contains("query-height") || + + options->contains("vacuum-defs") || options->contains("select") || options->contains("actions") || + options->contains("verb") || options->contains("shell")) { _with_gui = false; } - if (options->contains("with-gui") || - options->contains("batch-process") - ) { + if (options->contains("with-gui") || options->contains("batch-process")) { _with_gui = true; // Override turning GUI off } - if (options->contains("batch-process")) _batch_process = true; - if (options->contains("shell")) _use_shell = true; - if (options->contains("pipe")) _use_pipe = true; - + if (options->contains("batch-process")) + _batch_process = true; + if (options->contains("shell")) + _use_shell = true; + if (options->contains("pipe")) + _use_pipe = true; // Enable auto-export - if (options->contains("export-filename") || - options->contains("export-type") || - options->contains("export-overwrite") || - options->contains("export-use-hints") - ) { + if (options->contains("export-filename") || options->contains("export-type") || + options->contains("export-overwrite") || options->contains("export-use-hints")) { _auto_export = true; } @@ -1365,13 +1270,12 @@ ConcreteInkscapeApplication::on_handle_local_options(const Glib::RefPtrcontains("pdf-poppler")) { _pdf_poppler = true; } - if (options->contains("pdf-page")) { // Maybe useful for other file types? + if (options->contains("pdf-page")) { // Maybe useful for other file types? int page = 0; options->lookup_value("pdf-page", page); _pdf_page = page; @@ -1386,8 +1290,8 @@ ConcreteInkscapeApplication::on_handle_local_options(const Glib::RefPtrcontains("no-convert-text-baseline-spacing")) _command_line_actions.push_back(std::make_pair("no-convert-baseline", base)); - + if (options->contains("no-convert-text-baseline-spacing")) + _command_line_actions.push_back(std::make_pair("no-convert-baseline", base)); // ===================== QUERY ===================== @@ -1401,25 +1305,29 @@ ConcreteInkscapeApplication::on_handle_local_options(const Glib::RefPtrcontains("query-all")) _command_line_actions.push_back(std::make_pair("query-all", base)); - if (options->contains("query-x")) _command_line_actions.push_back(std::make_pair("query-x", base)); - if (options->contains("query-y")) _command_line_actions.push_back(std::make_pair("query-y", base)); - if (options->contains("query-width")) _command_line_actions.push_back(std::make_pair("query-width", base)); - if (options->contains("query-height")) _command_line_actions.push_back(std::make_pair("query-height",base)); - + if (options->contains("query-all")) + _command_line_actions.push_back(std::make_pair("query-all", base)); + if (options->contains("query-x")) + _command_line_actions.push_back(std::make_pair("query-x", base)); + if (options->contains("query-y")) + _command_line_actions.push_back(std::make_pair("query-y", base)); + if (options->contains("query-width")) + _command_line_actions.push_back(std::make_pair("query-width", base)); + if (options->contains("query-height")) + _command_line_actions.push_back(std::make_pair("query-height", base)); // =================== PROCESS ===================== // Note: this won't work with --verb="FileSave,FileClose" unless some additional verb changes the file. FIXME // One can use --verb="FileVacuum,FileSave,FileClose". - if (options->contains("vacuum-defs")) _command_line_actions.push_back(std::make_pair("vacuum-defs", base)); + if (options->contains("vacuum-defs")) + _command_line_actions.push_back(std::make_pair("vacuum-defs", base)); if (options->contains("select")) { Glib::ustring select; options->lookup_value("select", select); if (!select.empty()) { - _command_line_actions.push_back( - std::make_pair("select", Glib::Variant::create(select))); + _command_line_actions.push_back(std::make_pair("select", Glib::Variant::create(select))); } } @@ -1427,80 +1335,87 @@ ConcreteInkscapeApplication::on_handle_local_options(const Glib::RefPtrlookup_value("verb", verb); if (!verb.empty()) { - _command_line_actions.push_back( - std::make_pair("verb", Glib::Variant::create(verb))); + _command_line_actions.push_back(std::make_pair("verb", Glib::Variant::create(verb))); } } - // ==================== EXPORT ===================== if (options->contains("export-filename")) { - options->lookup_value("export-filename", _file_export.export_filename); + options->lookup_value("export-filename", _file_export.export_filename); } if (options->contains("export-type")) { - options->lookup_value("export-type", _file_export.export_type); + options->lookup_value("export-type", _file_export.export_type); } - if (options->contains("export-overwrite")) _file_export.export_overwrite = true; + if (options->contains("export-overwrite")) + _file_export.export_overwrite = true; // Export - Geometry if (options->contains("export-area")) { - options->lookup_value("export-area", _file_export.export_area); + options->lookup_value("export-area", _file_export.export_area); } - if (options->contains("export-area-drawing")) _file_export.export_area_drawing = true; - if (options->contains("export-area-page")) _file_export.export_area_page = true; + if (options->contains("export-area-drawing")) + _file_export.export_area_drawing = true; + if (options->contains("export-area-page")) + _file_export.export_area_page = true; if (options->contains("export-margin")) { - options->lookup_value("export-margin", _file_export.export_margin); + options->lookup_value("export-margin", _file_export.export_margin); } - if (options->contains("export-area-snap")) _file_export.export_area_snap = true; + if (options->contains("export-area-snap")) + _file_export.export_area_snap = true; if (options->contains("export-width")) { - options->lookup_value("export-width", _file_export.export_width); + options->lookup_value("export-width", _file_export.export_width); } if (options->contains("export-height")) { - options->lookup_value("export-height", _file_export.export_height); + options->lookup_value("export-height", _file_export.export_height); } // Export - Options if (options->contains("export-id")) { - options->lookup_value("export-id", _file_export.export_id); + options->lookup_value("export-id", _file_export.export_id); } - if (options->contains("export-id-only")) _file_export.export_id_only = true; - if (options->contains("export-plain-svg")) _file_export.export_plain_svg = true; + if (options->contains("export-id-only")) + _file_export.export_id_only = true; + if (options->contains("export-plain-svg")) + _file_export.export_plain_svg = true; if (options->contains("export-dpi")) { - options->lookup_value("export-dpi", _file_export.export_dpi); + options->lookup_value("export-dpi", _file_export.export_dpi); } - if (options->contains("export-ignore-filters")) _file_export.export_ignore_filters = true; - if (options->contains("export-text-to-path")) _file_export.export_text_to_path = true; + if (options->contains("export-ignore-filters")) + _file_export.export_ignore_filters = true; + if (options->contains("export-text-to-path")) + _file_export.export_text_to_path = true; if (options->contains("export-ps-level")) { - options->lookup_value("export-ps-level", _file_export.export_ps_level); + options->lookup_value("export-ps-level", _file_export.export_ps_level); } if (options->contains("export-pdf-version")) { options->lookup_value("export-pdf-version", _file_export.export_pdf_level); } - if (options->contains("export-latex")) _file_export.export_latex = true; - if (options->contains("export-use-hints")) _file_export.export_use_hints = true; + if (options->contains("export-latex")) + _file_export.export_latex = true; + if (options->contains("export-use-hints")) + _file_export.export_use_hints = true; if (options->contains("export-background")) { - options->lookup_value("export-background",_file_export.export_background); + options->lookup_value("export-background", _file_export.export_background); } if (options->contains("export-background-opacity")) { options->lookup_value("export-background-opacity", _file_export.export_background_opacity); } - // ==================== D-BUS ====================== #ifdef WITH_DBUS @@ -1519,18 +1434,20 @@ ConcreteInkscapeApplication::on_handle_local_options(const Glib::RefPtr -void -ConcreteInkscapeApplication::on_new() +template +void ConcreteInkscapeApplication::on_new() { create_window(); } -template void ConcreteInkscapeApplication::on_quit(){ T::quit(); } +template +void ConcreteInkscapeApplication::on_quit() +{ + T::quit(); +} -template<> -void -ConcreteInkscapeApplication::on_quit() +template <> +void ConcreteInkscapeApplication::on_quit() { // Delete all windows (quit() doesn't do this). /* @@ -1542,16 +1459,15 @@ ConcreteInkscapeApplication::on_quit() quit(); } -template -void -ConcreteInkscapeApplication::print_action_list() +template +void ConcreteInkscapeApplication::print_action_list() { std::vector actions = T::list_actions(); std::sort(actions.begin(), actions.end()); for (auto action : actions) { Glib::ustring fullname("app." + action); - std::cout << std::left << std::setw(20) << action - << ": " << _action_extra_data.get_tooltip_for_action(fullname) << std::endl; + std::cout << std::left << std::setw(20) << action << ": " + << _action_extra_data.get_tooltip_for_action(fullname) << std::endl; } } diff --git a/src/inkscape-application.h b/src/inkscape-application.h index 7087987503a94dcd229f94941f048a860d45e8c5..3611b4733fe81fd1014899c31caae4579572d38c 100644 --- a/src/inkscape-application.h +++ b/src/inkscape-application.h @@ -22,14 +22,13 @@ #include -#include "document.h" -#include "selection.h" - #include "actions/actions-extra-data.h" +#include "document.h" #include "helper/action.h" -#include "io/file-export-cmd.h" // File export (non-verb) +#include "io/file-export-cmd.h" // File export (non-verb) +#include "selection.h" -typedef std::vector > action_vector_t; +typedef std::vector> action_vector_t; class InkscapeWindow; class SPDocument; @@ -40,63 +39,61 @@ class InkscapeApplication public: virtual void on_startup() = 0; virtual void on_startup2() = 0; - virtual InkFileExportCmd* file_export() = 0; - virtual int on_handle_local_options(const Glib::RefPtr& options) = 0; + virtual InkFileExportCmd *file_export() = 0; + virtual int on_handle_local_options(const Glib::RefPtr &options) = 0; virtual void on_new() = 0; virtual void on_quit() = 0; // Gio::Actions need to know what document, selection, view to work on. // In headless mode, these are set for each file processed. // With GUI, these are set everytime the cursor enters an InkscapeWindow. - SPDocument* get_active_document() { return _active_document; }; - void set_active_document(SPDocument* document) { _active_document = document; }; + SPDocument *get_active_document() { return _active_document; }; + void set_active_document(SPDocument *document) { _active_document = document; }; - Inkscape::Selection* get_active_selection() { return _active_selection; } - void set_active_selection(Inkscape::Selection* selection) - {_active_selection = selection;}; + Inkscape::Selection *get_active_selection() { return _active_selection; } + void set_active_selection(Inkscape::Selection *selection) { _active_selection = selection; }; // A view should track selection and canvas to document transform matrix. This is partially // redundant with the selection functions above. Maybe we should get rid of view altogether. // Canvas to document transform matrix should be stored in InkscapeWindow. - Inkscape::UI::View::View* get_active_view() { return _active_view; } - void set_active_view(Inkscape::UI::View::View* view) { _active_view = view; } + Inkscape::UI::View::View *get_active_view() { return _active_view; } + void set_active_view(Inkscape::UI::View::View *view) { _active_view = view; } // The currently focused window (nominally corresponding to _active_document). // A window must have a document but a document may have zero, one, or more windows. // This will replace _active_view. - InkscapeWindow* get_active_window() { return _active_window; } - void set_active_window(InkscapeWindow* window) { _active_window = window; } + InkscapeWindow *get_active_window() { return _active_window; } + void set_active_window(InkscapeWindow *window) { _active_window = window; } /****** Document ******/ /* Except for document_fix(), these should not require a GUI! */ - void document_add(SPDocument* document); + void document_add(SPDocument *document); - SPDocument* document_new(const std::string &Template); - SPDocument* document_open(const Glib::RefPtr& file, bool *cancelled = nullptr); - SPDocument* document_open(const std::string& data); - bool document_swap(InkscapeWindow* window, SPDocument* document); - bool document_revert(SPDocument* document); - void document_close(SPDocument* document); - unsigned document_window_count(SPDocument* document); + SPDocument *document_new(const std::string &Template); + SPDocument *document_open(const Glib::RefPtr &file, bool *cancelled = nullptr); + SPDocument *document_open(const std::string &data); + bool document_swap(InkscapeWindow *window, SPDocument *document); + bool document_revert(SPDocument *document); + void document_close(SPDocument *document); + unsigned document_window_count(SPDocument *document); - void document_fix(InkscapeWindow* window); + void document_fix(InkscapeWindow *window); std::vector get_documents(); /******* Window *******/ - InkscapeWindow* window_open(SPDocument* document); - void window_close(InkscapeWindow* window); - void window_close_active(); + InkscapeWindow *window_open(SPDocument *document); + void window_close(InkscapeWindow *window); + void window_close_active(); // Update all windows connected to a document. - void windows_update(SPDocument* document); - + void windows_update(SPDocument *document); /****** Actions *******/ - InkActionExtraData& get_action_extra_data() { return _action_extra_data; } + InkActionExtraData &get_action_extra_data() { return _action_extra_data; } /******* Debug ********/ - void dump(); + void dump(); // These are needed to cast Glib::RefPtr to Glib::RefPtr, // Presumably, Gtk/Gio::Application takes care of ref counting in ConcreteInkscapeApplication @@ -105,24 +102,24 @@ public: // void unreference() { /*printf("unreference()\n");*/ } protected: - bool _with_gui = true; + bool _with_gui = true; bool _batch_process = false; // Temp - bool _use_shell = false; - bool _use_pipe = false; + bool _use_shell = false; + bool _use_pipe = false; bool _auto_export = false; - int _pdf_page = 1; - int _pdf_poppler = false; + int _pdf_page = 1; + int _pdf_poppler = false; InkscapeApplication() = default; // Documents are owned by the application which is responsible for opening/saving/exporting. WIP // std::vector _documents; For a true headless version - std::map > _documents; + std::map> _documents; // We keep track of these things so we don't need a window to find them (for headless operation). - SPDocument* _active_document = nullptr; - Inkscape::Selection* _active_selection = nullptr; - Inkscape::UI::View::View* _active_view = nullptr; - InkscapeWindow* _active_window = nullptr; + SPDocument *_active_document = nullptr; + Inkscape::Selection *_active_selection = nullptr; + Inkscape::UI::View::View *_active_view = nullptr; + InkscapeWindow *_active_window = nullptr; InkFileExportCmd _file_export; @@ -137,34 +134,37 @@ protected: // Gio::Application (window server is not present, required for CI testing) or // Gtk::Application (window server is present). // With Gtk::Application, one can still run "headless" by not creating any windows. -template class ConcreteInkscapeApplication : public T, public InkscapeApplication +template +class ConcreteInkscapeApplication + : public T + , public InkscapeApplication { public: - static ConcreteInkscapeApplication& get_instance(); + static ConcreteInkscapeApplication &get_instance(); private: ConcreteInkscapeApplication(); public: - InkFileExportCmd* file_export() override { return &_file_export; } - InkscapeWindow* create_window(SPDocument *document, bool replace); - void create_window(const Glib::RefPtr& file = Glib::RefPtr(), - bool add_to_recent = true, bool replace_empty = true); - bool destroy_window(InkscapeWindow* window); - void destroy_all(); - void print_action_list(); + InkFileExportCmd *file_export() override { return &_file_export; } + InkscapeWindow *create_window(SPDocument *document, bool replace); + void create_window(const Glib::RefPtr &file = Glib::RefPtr(), bool add_to_recent = true, + bool replace_empty = true); + bool destroy_window(InkscapeWindow *window); + void destroy_all(); + void print_action_list(); protected: - void on_startup() override; + void on_startup() override; void on_startup2() override; void on_activate() override; - void on_open(const Gio::Application::type_vec_files& files, const Glib::ustring& hint) override; - void process_document(SPDocument* document, std::string output_path); - void parse_actions(const Glib::ustring& input, action_vector_t& action_vector); + void on_open(const Gio::Application::type_vec_files &files, const Glib::ustring &hint) override; + void process_document(SPDocument *document, std::string output_path); + void parse_actions(const Glib::ustring &input, action_vector_t &action_vector); private: // Callbacks - int on_handle_local_options(const Glib::RefPtr& options) override; + int on_handle_local_options(const Glib::RefPtr &options) override; // Actions void on_new() override; @@ -173,10 +173,9 @@ private: void shell(); - void _start_main_option_section(const Glib::ustring& section_name = ""); + void _start_main_option_section(const Glib::ustring §ion_name = ""); Glib::RefPtr _builder; - }; #endif // INKSCAPE_APPLICATION_H diff --git a/src/inkscape-main.cpp b/src/inkscape-main.cpp index 68e93830dd68b57d8761e33e4e1c32313fdae663..b6646b71b1d7e82afb48dbef94ef880f10667963 100644 --- a/src/inkscape-main.cpp +++ b/src/inkscape-main.cpp @@ -11,14 +11,13 @@ */ #ifdef _WIN32 +#include // _O_BINARY #include // SetDllDirectoryW, SetConsoleOutputCP -#include // _O_BINARY #endif #include "inkscape-application.h" -#include "path-prefix.h" - #include "io/resource.h" +#include "path-prefix.h" static void set_extensions_env() { @@ -66,10 +65,10 @@ static void set_macos_app_bundle_env(gchar const *program_dir) // https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/MacOSXDirectories/MacOSXDirectories.html auto app_support_dir = Glib::getenv("HOME") + "/Library/Application Support/org.inkscape.Inkscape"; - auto bundle_resources_dir = Glib::path_get_dirname(get_inkscape_datadir()); - auto bundle_resources_etc_dir = bundle_resources_dir + "/etc"; - auto bundle_resources_bin_dir = bundle_resources_dir + "/bin"; - auto bundle_resources_lib_dir = bundle_resources_dir + "/lib"; + auto bundle_resources_dir = Glib::path_get_dirname(get_inkscape_datadir()); + auto bundle_resources_etc_dir = bundle_resources_dir + "/etc"; + auto bundle_resources_bin_dir = bundle_resources_dir + "/bin"; + auto bundle_resources_lib_dir = bundle_resources_dir + "/lib"; auto bundle_resources_share_dir = bundle_resources_dir + "/share"; // failsafe: Check if the expected content is really there, using GIO modules @@ -86,15 +85,15 @@ static void set_macos_app_bundle_env(gchar const *program_dir) // XDG // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html - Glib::setenv("XDG_DATA_HOME", app_support_dir + "/share"); - Glib::setenv("XDG_DATA_DIRS", bundle_resources_share_dir); + Glib::setenv("XDG_DATA_HOME", app_support_dir + "/share"); + Glib::setenv("XDG_DATA_DIRS", bundle_resources_share_dir); Glib::setenv("XDG_CONFIG_HOME", app_support_dir + "/config"); Glib::setenv("XDG_CONFIG_DIRS", bundle_resources_etc_dir + "/xdg"); - Glib::setenv("XDG_CACHE_HOME", app_support_dir + "/cache"); + Glib::setenv("XDG_CACHE_HOME", app_support_dir + "/cache"); // GTK // https://developer.gnome.org/gtk3/stable/gtk-running.html - Glib::setenv("GTK_EXE_PREFIX", bundle_resources_dir); + Glib::setenv("GTK_EXE_PREFIX", bundle_resources_dir); Glib::setenv("GTK_DATA_PREFIX", bundle_resources_dir); // GDK @@ -115,8 +114,8 @@ static void set_macos_app_bundle_env(gchar const *program_dir) // DYLD_LIBRARY_PATH // This is required to make Python GTK bindings work as they use dlopen() // to load libraries. - Glib::setenv("DYLD_LIBRARY_PATH", bundle_resources_lib_dir + ":" - + bundle_resources_lib_dir + "/gdk-pixbuf-2.0/2.10.0/loaders"); + Glib::setenv("DYLD_LIBRARY_PATH", + bundle_resources_lib_dir + ":" + bundle_resources_lib_dir + "/gdk-pixbuf-2.0/2.10.0/loaders"); } #endif @@ -144,7 +143,7 @@ static void convert_legacy_options(int &argc, char **&argv) bool found_legacy_export = false; - for (char const *type : { "png", "pdf", "ps", "eps", "emf", "wmf", "plain-svg" }) { + for (char const *type : {"png", "pdf", "ps", "eps", "emf", "wmf", "plain-svg"}) { auto s = std::string("--export-").append(type).append("="); if (g_str_has_prefix(argv[i], s.c_str())) { std::cerr << "Warning: Option " << s << " is deprecated" << std::endl; @@ -182,12 +181,11 @@ int main(int argc, char *argv[]) convert_legacy_options(argc, argv); #ifdef __APPLE__ - { // Check if we're inside an application bundle and adjust environment + { // Check if we're inside an application bundle and adjust environment // accordingly. char const *program_dir = get_program_dir(); if (g_str_has_suffix(program_dir, "Contents/MacOS")) { - // Step 1 // Remove macOS session identifier from command line arguments. // Code adopted from GIMP's app/main.c @@ -220,7 +218,7 @@ int main(int argc, char *argv[]) // as everything else is a mess and it seems to work just fine const unsigned int initial_cp = GetConsoleOutputCP(); SetConsoleOutputCP(CP_UTF8); - fflush(stdout); // empty buffer, just to be safe (see warning in documentation for _setmode) + fflush(stdout); // empty buffer, just to be safe (see warning in documentation for _setmode) _setmode(_fileno(stdout), _O_BINARY); // binary mode seems required for this to work properly #endif diff --git a/src/inkscape-version.h b/src/inkscape-version.h index 7d1b44f27bccba2c883712b0eede26f8b841c147..699c7b029094e7719cc03e5a8e9bf06bbc16e5e6 100644 --- a/src/inkscape-version.h +++ b/src/inkscape-version.h @@ -17,7 +17,7 @@ namespace Inkscape { -extern char const *version_string; ///< full version string +extern char const *version_string; ///< full version string extern char const *version_string_without_revision; ///< version string excluding revision and date } // namespace Inkscape diff --git a/src/inkscape-window.cpp b/src/inkscape-window.cpp index d2100d59f05c48d65d70ceb9b0e71c87445e340d..9810e6af2f47749e1cceea64e15a1346fe521658 100644 --- a/src/inkscape-window.cpp +++ b/src/inkscape-window.cpp @@ -14,29 +14,22 @@ * */ - #include "inkscape-window.h" -#include "inkscape.h" // SP_ACTIVE_DESKTOP -#include "enums.h" // PREFS_WINDOW_GEOMETRY_NONE -#include "shortcuts.h" -#include "inkscape-application.h" #include "actions/actions-canvas-transform.h" - -#include "object/sp-namedview.h" // TODO Remove need for this! - -#include "ui/drag-and-drop.h" // Move to canvas? -#include "ui/interface.h" // main menu, sp_ui_close_view() - -#include "ui/monitor.h" // get_monitor_geometry_at_point() - +#include "enums.h" // PREFS_WINDOW_GEOMETRY_NONE +#include "inkscape-application.h" +#include "inkscape.h" // SP_ACTIVE_DESKTOP +#include "object/sp-namedview.h" // TODO Remove need for this! +#include "shortcuts.h" #include "ui/desktop/menubar.h" - +#include "ui/drag-and-drop.h" // Move to canvas? #include "ui/drag-and-drop.h" - +#include "ui/interface.h" // main menu, sp_ui_close_view() +#include "ui/monitor.h" // get_monitor_geometry_at_point() #include "widgets/desktop-widget.h" -InkscapeWindow::InkscapeWindow(SPDocument* document) +InkscapeWindow::InkscapeWindow(SPDocument *document) : _document(document) , _app(nullptr) { @@ -51,7 +44,7 @@ InkscapeWindow::InkscapeWindow(SPDocument* document) set_resizable(true); // =================== Actions =================== - add_actions_canvas_transform(this); // Actions to transform canvas view. + add_actions_canvas_transform(this); // Actions to transform canvas view. insert_action_group("doc", document->getActionGroup()); @@ -84,18 +77,16 @@ InkscapeWindow::InkscapeWindow(SPDocument* document) _mainbox->pack_start(*Gtk::manage(_desktop_widget), true, true); // ================== Callbacks ================== - signal_delete_event().connect( sigc::mem_fun(*_desktop, &SPDesktop::onDeleteUI)); + signal_delete_event().connect(sigc::mem_fun(*_desktop, &SPDesktop::onDeleteUI)); signal_window_state_event().connect(sigc::mem_fun(*_desktop, &SPDesktop::onWindowStateEvent)); - signal_focus_in_event().connect( sigc::mem_fun(*_desktop_widget, &SPDesktopWidget::onFocusInEvent)); - + signal_focus_in_event().connect(sigc::mem_fun(*_desktop_widget, &SPDesktopWidget::onFocusInEvent)); // ================ Window Options ============== setup_view(); } // Change a document, leaving desktop/view the same. (Eventually move all code here.) -void -InkscapeWindow::change_document(SPDocument* document) +void InkscapeWindow::change_document(SPDocument *document) { if (!_app) { std::cerr << "Inkscapewindow::change_document: app is nullptr!" << std::endl; @@ -109,8 +100,7 @@ InkscapeWindow::change_document(SPDocument* document) } // Sets up the window and view according to user preferences and of the just loaded document -void -InkscapeWindow::setup_view() +void InkscapeWindow::setup_view() { // Make sure the GdkWindow is fully initialized before resizing/moving // (ensures the monitor it'll be shown on is known) @@ -148,8 +138,7 @@ inline bool is_Cmd_Q(GdkEventKey *event) #endif } -bool -InkscapeWindow::on_key_press_event(GdkEventKey* event) +bool InkscapeWindow::on_key_press_event(GdkEventKey *event) { // Need to call base class method first or text tool won't work! // Intercept Cmd-Q on macOS to not bypass confirmation dialog @@ -159,11 +148,10 @@ InkscapeWindow::on_key_press_event(GdkEventKey* event) } unsigned shortcut = sp_shortcut_get_for_event(event); - return sp_shortcut_invoke (shortcut, _desktop); + return sp_shortcut_invoke(shortcut, _desktop); } -bool -InkscapeWindow::on_focus_in_event(GdkEventFocus* event) +bool InkscapeWindow::on_focus_in_event(GdkEventFocus *event) { if (_app) { _app->set_active_window(this); @@ -179,8 +167,7 @@ InkscapeWindow::on_focus_in_event(GdkEventFocus* event) } // Called when a window is closed via the 'X' in the window bar. -bool -InkscapeWindow::on_delete_event(GdkEventAny* event) +bool InkscapeWindow::on_delete_event(GdkEventAny *event) { if (_app) { _app->destroy_window(this); diff --git a/src/inkscape-window.h b/src/inkscape-window.h index 96fcfa95145a639564cb7ae53dd5f78f47a25cd2..3ae2faee6308e83224900a326e318ebabfe8ac50 100644 --- a/src/inkscape-window.h +++ b/src/inkscape-window.h @@ -30,37 +30,36 @@ namespace UI { namespace View { // class SVGViewWidget; } -} -} - - -class InkscapeWindow : public Gtk::ApplicationWindow { +} // namespace UI +} // namespace Inkscape +class InkscapeWindow : public Gtk::ApplicationWindow +{ public: - InkscapeWindow(SPDocument* document); + InkscapeWindow(SPDocument *document); - SPDocument* get_document() { return _document; } - SPDesktop* get_desktop() { return _desktop; } - SPDesktopWidget* get_desktop_widget() { return _desktop_widget; } + SPDocument *get_document() { return _document; } + SPDesktop *get_desktop() { return _desktop; } + SPDesktopWidget *get_desktop_widget() { return _desktop_widget; } - void change_document(SPDocument* document); + void change_document(SPDocument *document); private: - ConcreteInkscapeApplication* _app; + ConcreteInkscapeApplication *_app; - SPDocument* _document; - SPDesktop* _desktop; - SPDesktopWidget* _desktop_widget; + SPDocument *_document; + SPDesktop *_desktop; + SPDesktopWidget *_desktop_widget; - Gtk::Box* _mainbox; - Gtk::MenuBar* _menubar; + Gtk::Box *_mainbox; + Gtk::MenuBar *_menubar; void setup_view(); // Callbacks - bool on_key_press_event(GdkEventKey* event) override; - bool on_focus_in_event(GdkEventFocus* event) override; - bool on_delete_event(GdkEventAny* event) override; + bool on_key_press_event(GdkEventKey *event) override; + bool on_focus_in_event(GdkEventFocus *event) override; + bool on_delete_event(GdkEventAny *event) override; }; #endif // INKSCAPE_WINDOW_H diff --git a/src/inkscape.cpp b/src/inkscape.cpp index 1598dc8f702e143109bd6c95175fde358eff75ef..8a3b7fff330eebd36634759524c08d2433426440 100644 --- a/src/inkscape.cpp +++ b/src/inkscape.cpp @@ -15,73 +15,60 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include - -#include +#include "inkscape.h" +#include +#include +#include #include +#include +#include #include - #include #include +#include +#include -#include -#include -#include -#include - +#include "debug/event-tracker.h" +#include "debug/simple-event.h" #include "desktop.h" #include "device-manager.h" #include "document.h" -#include "inkscape.h" -#include "message-stack.h" -#include "path-prefix.h" - -#include "debug/simple-event.h" -#include "debug/event-tracker.h" - #include "extension/db.h" #include "extension/init.h" #include "extension/output.h" #include "extension/system.h" - #include "helper/action-context.h" - -#include "io/resource.h" #include "io/resource-manager.h" +#include "io/resource.h" #include "io/sys.h" - #include "libnrtype/FontFactory.h" - +#include "message-stack.h" #include "object/sp-root.h" #include "object/sp-style-elem.h" - +#include "path-prefix.h" #include "svg/svg-color.h" - -#include "object/sp-root.h" -#include "object/sp-style-elem.h" - #include "ui/dialog/debug.h" #include "ui/tools/tool-base.h" /* Backbones of configuration xml data */ -#include "menus-skeleton.h" - #include +#include "menus-skeleton.h" + // Inkscape::Application static members -Inkscape::Application * Inkscape::Application::_S_inst = nullptr; +Inkscape::Application *Inkscape::Application::_S_inst = nullptr; bool Inkscape::Application::_crashIsHappening = false; -#define DESKTOP_IS_ACTIVE(d) (INKSCAPE._desktops != nullptr && !INKSCAPE._desktops->empty() && ((d) == INKSCAPE._desktops->front())) +#define DESKTOP_IS_ACTIVE(d) \ + (INKSCAPE._desktops != nullptr && !INKSCAPE._desktops->empty() && ((d) == INKSCAPE._desktops->front())) -static void (* segv_handler) (int) = SIG_DFL; -static void (* abrt_handler) (int) = SIG_DFL; -static void (* fpe_handler) (int) = SIG_DFL; -static void (* ill_handler) (int) = SIG_DFL; +static void (*segv_handler)(int) = SIG_DFL; +static void (*abrt_handler)(int) = SIG_DFL; +static void (*fpe_handler)(int) = SIG_DFL; +static void (*ill_handler)(int) = SIG_DFL; #ifndef _WIN32 -static void (* bus_handler) (int) = SIG_DFL; +static void (*bus_handler)(int) = SIG_DFL; #endif #define MENUS_FILE "menus.xml" @@ -90,23 +77,25 @@ static void (* bus_handler) (int) = SIG_DFL; /** C++ification TODO list * - _S_inst should NOT need to be assigned inside the constructor, but if it isn't the Filters+Extensions menus break. - * - Application::_deskops has to be a pointer because of a signal bug somewhere else. Basically, it will attempt to access a deleted object in sp_ui_close_all(), - * but if it's a pointer we can stop and return NULL in Application::active_desktop() + * - Application::_deskops has to be a pointer because of a signal bug somewhere else. Basically, it will attempt to + * access a deleted object in sp_ui_close_all(), but if it's a pointer we can stop and return NULL in + * Application::active_desktop() * - These functions are calling Application::create for no good reason I can determine: * * Inkscape::UI::Dialog::SVGPreview::SVGPreview() * src/ui/dialog/filedialogimpl-gtkmm.cpp:542:9 */ - -class InkErrorHandler : public Inkscape::ErrorReporter { +class InkErrorHandler : public Inkscape::ErrorReporter +{ public: - InkErrorHandler(bool useGui) : Inkscape::ErrorReporter(), - _useGui(useGui) + InkErrorHandler(bool useGui) + : Inkscape::ErrorReporter() + , _useGui(useGui) {} ~InkErrorHandler() override = default; - void handleError( Glib::ustring const& primary, Glib::ustring const& secondary ) const override + void handleError(Glib::ustring const &primary, Glib::ustring const &secondary) const override { if (_useGui) { Gtk::MessageDialog err(primary, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK, true); @@ -122,12 +111,12 @@ private: bool _useGui; }; -void inkscape_ref(Inkscape::Application & in) +void inkscape_ref(Inkscape::Application &in) { in.refCount++; } -void inkscape_unref(Inkscape::Application & in) +void inkscape_unref(Inkscape::Application &in) { in.refCount--; @@ -136,8 +125,9 @@ void inkscape_unref(Inkscape::Application & in) delete Inkscape::Application::_S_inst; } } else { - g_error("Attempt to unref an Application (=%p) not the current instance (=%p) (maybe it's already been destroyed?)", - &in, Inkscape::Application::_S_inst); + g_error( + "Attempt to unref an Application (=%p) not the current instance (=%p) (maybe it's already been destroyed?)", + &in, Inkscape::Application::_S_inst); } } @@ -147,30 +137,26 @@ namespace Inkscape { * Defined only for debugging purposes. If we are certain the bugs are gone we can remove this * and the references in inkscape_ref and inkscape_unref. */ -Application* -Application::operator &() const +Application *Application::operator&() const { - return const_cast(this); + return const_cast(this); } /** * Creates a new Inkscape::Application global object. */ -void -Application::create(bool use_gui) +void Application::create(bool use_gui) { - if (!Application::exists()) { + if (!Application::exists()) { new Application(use_gui); } else { - // g_assert_not_reached(); Can happen with InkscapeApplication + // g_assert_not_reached(); Can happen with InkscapeApplication } } - /** * Checks whether the current Inkscape::Application global object exists. */ -bool -Application::exists() +bool Application::exists() { return Application::_S_inst != nullptr; } @@ -179,11 +165,10 @@ Application::exists() * Returns the current Inkscape::Application global object. * \pre Application::_S_inst != NULL */ -Application& -Application::instance() +Application &Application::instance() { if (!exists()) { - g_error("Inkscape::Application does not yet exist."); + g_error("Inkscape::Application does not yet exist."); } return *Application::_S_inst; } @@ -194,18 +179,18 @@ Application::instance() * \pre Application::_S_inst == NULL */ -Application::Application(bool use_gui) : - _use_gui(use_gui) +Application::Application(bool use_gui) + : _use_gui(use_gui) { using namespace Inkscape::IO::Resource; /* fixme: load application defaults */ - segv_handler = signal (SIGSEGV, Application::crash_handler); - abrt_handler = signal (SIGABRT, Application::crash_handler); - fpe_handler = signal (SIGFPE, Application::crash_handler); - ill_handler = signal (SIGILL, Application::crash_handler); + segv_handler = signal(SIGSEGV, Application::crash_handler); + abrt_handler = signal(SIGABRT, Application::crash_handler); + fpe_handler = signal(SIGFPE, Application::crash_handler); + ill_handler = signal(SIGILL, Application::crash_handler); #ifndef _WIN32 - bus_handler = signal (SIGBUS, Application::crash_handler); + bus_handler = signal(SIGBUS, Application::crash_handler); #endif // \TODO: this belongs to Application::init but if it isn't here @@ -213,12 +198,12 @@ Application::Application(bool use_gui) : _S_inst = this; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - InkErrorHandler* handler = new InkErrorHandler(use_gui); + InkErrorHandler *handler = new InkErrorHandler(use_gui); prefs->setErrorHandler(handler); { Glib::ustring msg; Glib::ustring secondary; - if (prefs->getLastError( msg, secondary )) { + if (prefs->getLastError(msg, secondary)) { handler->handleError(msg, secondary); } } @@ -238,8 +223,7 @@ Application::Application(bool use_gui) : /* set language for user interface according setting in preferences */ Glib::ustring ui_language = prefs->getString("/ui/language"); - if(!ui_language.empty()) - { + if (!ui_language.empty()) { setenv("LANGUAGE", ui_language, true); } @@ -252,13 +236,11 @@ Application::Application(bool use_gui) : #define DEFAULT_LOG_REDIRECT false #endif - if (use_gui && prefs->getBool("/dialogs/debug/redirect", DEFAULT_LOG_REDIRECT)) - { + if (use_gui && prefs->getBool("/dialogs/debug/redirect", DEFAULT_LOG_REDIRECT)) { Inkscape::UI::Dialog::DebugDialog::getInstance()->captureLogMessages(); } - if (use_gui) - { + if (use_gui) { Inkscape::UI::Tools::init_latin_keys_group(); /* Check for global remapping of Alt key */ mapalt(guint(prefs->getInt("/options/mapalt/value", 0))); @@ -304,7 +286,6 @@ Application::~Application() // gtk_main_quit (); } - Glib::ustring Application::get_symbolic_colors() { Glib::ustring css_str; @@ -396,7 +377,6 @@ void Application::add_gtk_css(bool only_providers) } else { prefs->setString("/theme/iconTheme", Glib::ustring(gtkIconThemeName)); } - } g_free(gtkThemeName); @@ -459,19 +439,18 @@ void Application::add_gtk_css(bool only_providers) */ void Application::mapalt(guint maskvalue) { - if ( maskvalue < 2 || maskvalue > 5 ) { // MOD5 is the highest defined in gdktypes.h + if (maskvalue < 2 || maskvalue > 5) { // MOD5 is the highest defined in gdktypes.h _mapalt = 0; } else { - _mapalt = (GDK_MOD1_MASK << (maskvalue-1)); + _mapalt = (GDK_MOD1_MASK << (maskvalue - 1)); } } -void -Application::crash_handler (int /*signum*/) +void Application::crash_handler(int /*signum*/) { - using Inkscape::Debug::SimpleEvent; using Inkscape::Debug::EventTracker; using Inkscape::Debug::Logger; + using Inkscape::Debug::SimpleEvent; static bool recursion = false; @@ -479,29 +458,29 @@ Application::crash_handler (int /*signum*/) * reset all signal handlers: any further crashes should just be allowed * to crash normally. * */ - signal (SIGSEGV, segv_handler ); - signal (SIGABRT, abrt_handler ); - signal (SIGFPE, fpe_handler ); - signal (SIGILL, ill_handler ); + signal(SIGSEGV, segv_handler); + signal(SIGABRT, abrt_handler); + signal(SIGFPE, fpe_handler); + signal(SIGILL, ill_handler); #ifndef _WIN32 - signal (SIGBUS, bus_handler ); + signal(SIGBUS, bus_handler); #endif /* Stop bizarre loops */ if (recursion) { - abort (); + abort(); } recursion = true; _crashIsHappening = true; - EventTracker > tracker("crash"); - tracker.set >("emergency-save"); + EventTracker> tracker("crash"); + tracker.set>("emergency-save"); fprintf(stderr, "\nEmergency save activated!\n"); - time_t sptime = time (nullptr); - struct tm *sptm = localtime (&sptime); + time_t sptime = time(nullptr); + struct tm *sptm = localtime(&sptime); gchar sptstr[256]; strftime(sptstr, 256, "%Y_%m_%d_%H_%M_%S", sptm); @@ -509,9 +488,8 @@ Application::crash_handler (int /*signum*/) gchar *curdir = g_get_current_dir(); // This one needs to be freed explicitly std::vector savednames; std::vector failednames; - for (std::map::iterator iter = INKSCAPE._document_set.begin(), e = INKSCAPE._document_set.end(); - iter != e; - ++iter) { + for (std::map::iterator iter = INKSCAPE._document_set.begin(), e = INKSCAPE._document_set.end(); + iter != e; ++iter) { SPDocument *doc = iter->first; Inkscape::XML::Node *repr; repr = doc->getReprRoot(); @@ -524,54 +502,59 @@ Application::crash_handler (int /*signum*/) docname = doc->getDocumentName(); if (docname) { /* Removes an emergency save suffix if present: /(.*)\.[0-9_]*\.[0-9_]*\.[~\.]*$/\1/ */ - const char* d0 = strrchr ((char*)docname, '.'); + const char *d0 = strrchr((char *)docname, '.'); if (d0 && (d0 > docname)) { - const char* d = d0; + const char *d = d0; unsigned int dots = 0; - while ((isdigit (*d) || *d=='_' || *d=='.') && d>docname && dots<2) { + while ((isdigit(*d) || *d == '_' || *d == '.') && d > docname && dots < 2) { d -= 1; - if (*d=='.') dots++; + if (*d == '.') + dots++; } - if (*d=='.' && d>docname && dots==2) { - size_t len = MIN (d - docname, 63); - memcpy (n, docname, len); + if (*d == '.' && d > docname && dots == 2) { + size_t len = MIN(d - docname, 63); + memcpy(n, docname, len); n[len] = '\0'; docname = n; } } } - if (!docname || !*docname) docname = "emergency"; + if (!docname || !*docname) + docname = "emergency"; // Emergency filename char c[1024]; - g_snprintf (c, 1024, "%.256s.%s.%d.svg", docname, sptstr, count); + g_snprintf(c, 1024, "%.256s.%s.%d.svg", docname, sptstr, count); // Find a location - const char* locations[] = { + const char *locations[] = { doc->getDocumentBase(), g_get_home_dir(), g_get_tmp_dir(), curdir, }; FILE *file = nullptr; - for(auto & location : locations) { - if (!location) continue; // It seems to be okay, but just in case - gchar * filename = g_build_filename(location, c, NULL); + for (auto &location : locations) { + if (!location) + continue; // It seems to be okay, but just in case + gchar *filename = g_build_filename(location, c, NULL); Inkscape::IO::dump_fopen_call(filename, "E"); file = Inkscape::IO::fopen_utf8name(filename, "w"); if (file) { - g_snprintf (c, 1024, "%s", filename); // we want the complete path to be stored in c (for reporting purposes) + g_snprintf(c, 1024, "%s", + filename); // we want the complete path to be stored in c (for reporting purposes) break; } } // Save if (file) { - sp_repr_save_stream (repr->document(), file, SP_SVG_NS_URI); - savednames.push_back(g_strdup (c)); - fclose (file); + sp_repr_save_stream(repr->document(), file, SP_SVG_NS_URI); + savednames.push_back(g_strdup(c)); + fclose(file); } else { - failednames.push_back((doc->getDocumentName()) ? g_strdup(doc->getDocumentName()) : g_strdup (_("Untitled document"))); + failednames.push_back((doc->getDocumentName()) ? g_strdup(doc->getDocumentName()) + : g_strdup(_("Untitled document"))); } count++; } @@ -579,84 +562,83 @@ Application::crash_handler (int /*signum*/) g_free(curdir); if (!savednames.empty()) { - fprintf (stderr, "\nEmergency save document locations:\n"); - for (auto i:savednames) { - fprintf (stderr, " %s\n", i); + fprintf(stderr, "\nEmergency save document locations:\n"); + for (auto i : savednames) { + fprintf(stderr, " %s\n", i); } } if (!failednames.empty()) { - fprintf (stderr, "\nFailed to do emergency save for documents:\n"); - for (auto i:failednames) { - fprintf (stderr, " %s\n", i); + fprintf(stderr, "\nFailed to do emergency save for documents:\n"); + for (auto i : failednames) { + fprintf(stderr, " %s\n", i); } } // do not save the preferences since they can be in a corrupted state Inkscape::Preferences::unload(false); - fprintf (stderr, "Emergency save completed. Inkscape will close now.\n"); - fprintf (stderr, "If you can reproduce this crash, please file a bug at https://inkscape.org/report\n"); - fprintf (stderr, "with a detailed description of the steps leading to the crash, so we can fix it.\n"); + fprintf(stderr, "Emergency save completed. Inkscape will close now.\n"); + fprintf(stderr, "If you can reproduce this crash, please file a bug at https://inkscape.org/report\n"); + fprintf(stderr, "with a detailed description of the steps leading to the crash, so we can fix it.\n"); /* Show nice dialog box */ char const *istr = _("Inkscape encountered an internal error and will close now.\n"); char const *sstr = _("Automatic backups of unsaved documents were done to the following locations:\n"); char const *fstr = _("Automatic backup of the following documents failed:\n"); - gint nllen = strlen ("\n"); - gint len = strlen (istr) + strlen (sstr) + strlen (fstr); - for (auto i:savednames) { - len = len + SP_INDENT + strlen (i) + nllen; + gint nllen = strlen("\n"); + gint len = strlen(istr) + strlen(sstr) + strlen(fstr); + for (auto i : savednames) { + len = len + SP_INDENT + strlen(i) + nllen; } - for (auto i:failednames) { - len = len + SP_INDENT + strlen (i) + nllen; + for (auto i : failednames) { + len = len + SP_INDENT + strlen(i) + nllen; } len += 1; - gchar *b = g_new (gchar, len); + gchar *b = g_new(gchar, len); gint pos = 0; - len = strlen (istr); - memcpy (b + pos, istr, len); + len = strlen(istr); + memcpy(b + pos, istr, len); pos += len; if (!savednames.empty()) { - len = strlen (sstr); - memcpy (b + pos, sstr, len); + len = strlen(sstr); + memcpy(b + pos, sstr, len); pos += len; - for (auto i:savednames) { - memset (b + pos, ' ', SP_INDENT); + for (auto i : savednames) { + memset(b + pos, ' ', SP_INDENT); pos += SP_INDENT; len = strlen(i); - memcpy (b + pos, i, len); + memcpy(b + pos, i, len); pos += len; - memcpy (b + pos, "\n", nllen); + memcpy(b + pos, "\n", nllen); pos += nllen; } } if (!failednames.empty()) { - len = strlen (fstr); - memcpy (b + pos, fstr, len); + len = strlen(fstr); + memcpy(b + pos, fstr, len); pos += len; - for (auto i:failednames) { - memset (b + pos, ' ', SP_INDENT); + for (auto i : failednames) { + memset(b + pos, ' ', SP_INDENT); pos += SP_INDENT; len = strlen(i); - memcpy (b + pos, i, len); + memcpy(b + pos, i, len); pos += len; - memcpy (b + pos, "\n", nllen); + memcpy(b + pos, "\n", nllen); pos += nllen; } } *(b + pos) = '\0'; - if ( exists() && instance().use_gui() ) { - GtkWidget *msgbox = gtk_message_dialog_new (nullptr, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", b); - gtk_dialog_run (GTK_DIALOG (msgbox)); - gtk_widget_destroy (msgbox); - } - else - { - g_message( "Error: %s", b ); + if (exists() && instance().use_gui()) { + GtkWidget *msgbox = + gtk_message_dialog_new(nullptr, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", b); + gtk_dialog_run(GTK_DIALOG(msgbox)); + gtk_widget_destroy(msgbox); + } else { + g_message("Error: %s", b); } - g_free (b); + g_free(b); tracker.clear(); Logger::shutdown(); @@ -676,74 +658,63 @@ bool Application::load_menus() Glib::ustring filename = get_filename(UIS, MENUS_FILE); _menus = sp_repr_read_file(filename.c_str(), nullptr); - if ( !_menus ) { + if (!_menus) { _menus = sp_repr_read_mem(menus_skeleton, MENUS_SKELETON_SIZE, nullptr); } return (_menus != nullptr); } - -void -Application::selection_modified (Inkscape::Selection *selection, guint flags) +void Application::selection_modified(Inkscape::Selection *selection, guint flags) { - g_return_if_fail (selection != nullptr); + g_return_if_fail(selection != nullptr); - if (DESKTOP_IS_ACTIVE (selection->desktop())) { + if (DESKTOP_IS_ACTIVE(selection->desktop())) { signal_selection_modified.emit(selection, flags); } } - -void -Application::selection_changed (Inkscape::Selection * selection) +void Application::selection_changed(Inkscape::Selection *selection) { - g_return_if_fail (selection != nullptr); + g_return_if_fail(selection != nullptr); - if (DESKTOP_IS_ACTIVE (selection->desktop())) { + if (DESKTOP_IS_ACTIVE(selection->desktop())) { signal_selection_changed.emit(selection); } } -void -Application::subselection_changed (SPDesktop *desktop) +void Application::subselection_changed(SPDesktop *desktop) { - g_return_if_fail (desktop != nullptr); + g_return_if_fail(desktop != nullptr); - if (DESKTOP_IS_ACTIVE (desktop)) { + if (DESKTOP_IS_ACTIVE(desktop)) { signal_subselection_changed.emit(desktop); } } - -void -Application::selection_set (Inkscape::Selection * selection) +void Application::selection_set(Inkscape::Selection *selection) { - g_return_if_fail (selection != nullptr); + g_return_if_fail(selection != nullptr); - if (DESKTOP_IS_ACTIVE (selection->desktop())) { + if (DESKTOP_IS_ACTIVE(selection->desktop())) { signal_selection_set.emit(selection); signal_selection_changed.emit(selection); } } - -void -Application::eventcontext_set (Inkscape::UI::Tools::ToolBase * eventcontext) +void Application::eventcontext_set(Inkscape::UI::Tools::ToolBase *eventcontext) { - g_return_if_fail (eventcontext != nullptr); + g_return_if_fail(eventcontext != nullptr); - if (DESKTOP_IS_ACTIVE (eventcontext->getDesktop())) { + if (DESKTOP_IS_ACTIVE(eventcontext->getDesktop())) { signal_eventcontext_set.emit(eventcontext); } } - -void -Application::add_desktop (SPDesktop * desktop) +void Application::add_desktop(SPDesktop *desktop) { - g_return_if_fail (desktop != nullptr); + g_return_if_fail(desktop != nullptr); if (_desktops == nullptr) { - _desktops = new std::vector; + _desktops = new std::vector; } if (std::find(_desktops->begin(), _desktops->end(), desktop) != _desktops->end()) { @@ -758,23 +729,20 @@ Application::add_desktop (SPDesktop * desktop) signal_selection_changed.emit(desktop->getSelection()); } - - -void -Application::remove_desktop (SPDesktop * desktop) +void Application::remove_desktop(SPDesktop *desktop) { - g_return_if_fail (desktop != nullptr); + g_return_if_fail(desktop != nullptr); - if (std::find (_desktops->begin(), _desktops->end(), desktop) == _desktops->end() ) { + if (std::find(_desktops->begin(), _desktops->end(), desktop) == _desktops->end()) { g_error("Attempted to remove desktop not in list."); } desktop->setEventContext(""); - if (DESKTOP_IS_ACTIVE (desktop)) { + if (DESKTOP_IS_ACTIVE(desktop)) { signal_deactivate_desktop.emit(desktop); if (_desktops->size() > 1) { - SPDesktop * new_desktop = *(++_desktops->begin()); + SPDesktop *new_desktop = *(++_desktops->begin()); _desktops->erase(std::find(_desktops->begin(), _desktops->end(), new_desktop)); _desktops->insert(_desktops->begin(), new_desktop); @@ -799,20 +767,17 @@ Application::remove_desktop (SPDesktop * desktop) } } - - -void -Application::activate_desktop (SPDesktop * desktop) +void Application::activate_desktop(SPDesktop *desktop) { - g_return_if_fail (desktop != nullptr); + g_return_if_fail(desktop != nullptr); - if (DESKTOP_IS_ACTIVE (desktop)) { + if (DESKTOP_IS_ACTIVE(desktop)) { return; } - std::vector::iterator i; + std::vector::iterator i; - if ((i = std::find (_desktops->begin(), _desktops->end(), desktop)) == _desktops->end()) { + if ((i = std::find(_desktops->begin(), _desktops->end(), desktop)) == _desktops->end()) { g_error("Tried to activate desktop not added to list."); } @@ -820,8 +785,8 @@ Application::activate_desktop (SPDesktop * desktop) signal_deactivate_desktop.emit(current); - _desktops->erase (i); - _desktops->insert (_desktops->begin(), desktop); + _desktops->erase(i); + _desktops->insert(_desktops->begin(), desktop); signal_activate_desktop.emit(desktop); signal_eventcontext_set.emit(desktop->getEventContext()); @@ -829,51 +794,42 @@ Application::activate_desktop (SPDesktop * desktop) signal_selection_changed(desktop->getSelection()); } - /** - * Resends ACTIVATE_DESKTOP for current desktop; needed when a new desktop has got its window that dialogs will transientize to + * Resends ACTIVATE_DESKTOP for current desktop; needed when a new desktop has got its window that dialogs will + * transientize to */ -void -Application::reactivate_desktop (SPDesktop * desktop) +void Application::reactivate_desktop(SPDesktop *desktop) { - g_return_if_fail (desktop != nullptr); + g_return_if_fail(desktop != nullptr); - if (DESKTOP_IS_ACTIVE (desktop)) { + if (DESKTOP_IS_ACTIVE(desktop)) { signal_activate_desktop.emit(desktop); } } - - -SPDesktop * -Application::find_desktop_by_dkey (unsigned int dkey) +SPDesktop *Application::find_desktop_by_dkey(unsigned int dkey) { - for (auto & _desktop : *_desktops) { - if (_desktop->dkey == dkey){ + for (auto &_desktop : *_desktops) { + if (_desktop->dkey == dkey) { return _desktop; } } return nullptr; } - -unsigned int -Application::maximum_dkey() +unsigned int Application::maximum_dkey() { unsigned int dkey = 0; - for (auto & _desktop : *_desktops) { - if (_desktop->dkey > dkey){ + for (auto &_desktop : *_desktops) { + if (_desktop->dkey > dkey) { dkey = _desktop->dkey; } } return dkey; } - - -SPDesktop * -Application::next_desktop () +SPDesktop *Application::next_desktop() { SPDesktop *d = nullptr; unsigned int dkey_current = (_desktops->front())->dkey; @@ -881,7 +837,7 @@ Application::next_desktop () if (dkey_current < maximum_dkey()) { // find next existing for (unsigned int i = dkey_current + 1; i <= maximum_dkey(); ++i) { - d = find_desktop_by_dkey (i); + d = find_desktop_by_dkey(i); if (d) { break; } @@ -889,21 +845,18 @@ Application::next_desktop () } else { // find first existing for (unsigned int i = 0; i <= maximum_dkey(); ++i) { - d = find_desktop_by_dkey (i); + d = find_desktop_by_dkey(i); if (d) { break; } } } - g_assert (d); + g_assert(d); return d; } - - -SPDesktop * -Application::prev_desktop () +SPDesktop *Application::prev_desktop() { SPDesktop *d = nullptr; unsigned int dkey_current = (_desktops->front())->dkey; @@ -911,7 +864,7 @@ Application::prev_desktop () if (dkey_current > 0) { // find prev existing for (signed int i = dkey_current - 1; i >= 0; --i) { - d = find_desktop_by_dkey (i); + d = find_desktop_by_dkey(i); if (d) { break; } @@ -919,29 +872,24 @@ Application::prev_desktop () } if (!d) { // find last existing - d = find_desktop_by_dkey (maximum_dkey()); + d = find_desktop_by_dkey(maximum_dkey()); } - g_assert (d); + g_assert(d); return d; } - - -void -Application::switch_desktops_next () +void Application::switch_desktops_next() { next_desktop()->presentWindow(); } -void -Application::switch_desktops_prev() +void Application::switch_desktops_prev() { prev_desktop()->presentWindow(); } -void -Application::external_change() +void Application::external_change() { signal_external_change.emit(); } @@ -949,20 +897,19 @@ Application::external_change() /** * fixme: These need probably signals too */ -void -Application::add_document (SPDocument *document) +void Application::add_document(SPDocument *document) { - g_return_if_fail (document != nullptr); + g_return_if_fail(document != nullptr); // try to insert the pair into the list if (!(_document_set.insert(std::make_pair(document, 1)).second)) { - //insert failed, this key (document) is already in the list - for (auto & iter : _document_set) { + // insert failed, this key (document) is already in the list + for (auto &iter : _document_set) { if (iter.first == document) { // found this document in list, increase its count - iter.second ++; + iter.second++; } - } + } } else { // insert succeeded, this document is new. @@ -976,22 +923,18 @@ Application::add_document (SPDocument *document) } } - // returns true if this was last reference to this document, so you can delete it -bool -Application::remove_document (SPDocument *document) +bool Application::remove_document(SPDocument *document) { - g_return_val_if_fail (document != nullptr, false); + g_return_val_if_fail(document != nullptr, false); - for (std::map::iterator iter = _document_set.begin(); - iter != _document_set.end(); - ++iter) { + for (std::map::iterator iter = _document_set.begin(); iter != _document_set.end(); ++iter) { if (iter->first == document) { // found this document in list, decrease its count - iter->second --; + iter->second--; if (iter->second < 1) { // this was the last one, remove the pair from list - _document_set.erase (iter); + _document_set.erase(iter); // also remove the selection model std::map::iterator sel_iter = _selection_models.find(document); @@ -1009,8 +952,7 @@ Application::remove_document (SPDocument *document) return false; } -SPDesktop * -Application::active_desktop() +SPDesktop *Application::active_desktop() { if (!_desktops || _desktops->empty()) { return nullptr; @@ -1019,8 +961,7 @@ Application::active_desktop() return _desktops->front(); } -SPDocument * -Application::active_document() +SPDocument *Application::active_document() { if (SP_ACTIVE_DESKTOP) { return SP_ACTIVE_DESKTOP->getDocument(); @@ -1033,23 +974,22 @@ Application::active_document() return nullptr; } -bool -Application::sole_desktop_for_document(SPDesktop const &desktop) { - SPDocument const* document = desktop.doc(); +bool Application::sole_desktop_for_document(SPDesktop const &desktop) +{ + SPDocument const *document = desktop.doc(); if (!document) { return false; } for (auto other_desktop : *_desktops) { SPDocument *other_document = other_desktop->doc(); - if ( other_document == document && other_desktop != &desktop ) { + if (other_document == document && other_desktop != &desktop) { return false; } } return true; } -Inkscape::UI::Tools::ToolBase * -Application::active_event_context () +Inkscape::UI::Tools::ToolBase *Application::active_event_context() { if (SP_ACTIVE_DESKTOP) { return SP_ACTIVE_DESKTOP->getEventContext(); @@ -1058,8 +998,7 @@ Application::active_event_context () return nullptr; } -Inkscape::ActionContext -Application::active_action_context() +Inkscape::ActionContext Application::active_action_context() { if (SP_ACTIVE_DESKTOP) { return Inkscape::ActionContext(SP_ACTIVE_DESKTOP); @@ -1073,8 +1012,7 @@ Application::active_action_context() return action_context_for_document(doc); } -Inkscape::ActionContext -Application::action_context_for_document(SPDocument *doc) +Inkscape::ActionContext Application::action_context_for_document(SPDocument *doc) { // If there are desktops, check them first to see if the document is bound to one of them if (_desktops != nullptr) { @@ -1094,47 +1032,38 @@ Application::action_context_for_document(SPDocument *doc) return Inkscape::ActionContext(sel_iter->second->getSelection()); } - /*##################### # HELPERS #####################*/ -void -Application::refresh_display () +void Application::refresh_display() { - for (auto & _desktop : *_desktops) { + for (auto &_desktop : *_desktops) { _desktop->requestRedraw(); } } - /** * Handler for Inkscape's Exit verb. This emits the shutdown signal, * saves the preferences if appropriate, and quits. */ -void -Application::exit () +void Application::exit() { - //emit shutdown signal so that dialogs could remember layout + // emit shutdown signal so that dialogs could remember layout signal_shut_down.emit(); Inkscape::Preferences::unload(); - //gtk_main_quit (); + // gtk_main_quit (); } - - - -Inkscape::XML::Node * -Application::get_menus() +Inkscape::XML::Node *Application::get_menus() { Inkscape::XML::Node *repr = _menus->root(); - g_assert (!(strcmp (repr->name(), "inkscape"))); + g_assert(!(strcmp(repr->name(), "inkscape"))); return repr->firstChild(); } -void -Application::get_all_desktops(std::list< SPDesktop* >& listbuf) +void Application::get_all_desktops(std::list &listbuf) { listbuf.insert(listbuf.end(), _desktops->begin(), _desktops->end()); } diff --git a/src/inkscape.h b/src/inkscape.h index 8e6b705f5d8e7a35cdc4463dad48366c39efd4b9..2cef69902a03d8d86bdaf5a262934f8f930800af 100644 --- a/src/inkscape.h +++ b/src/inkscape.h @@ -14,8 +14,6 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "layer-model.h" -#include "selection.h" #include #include #include @@ -23,6 +21,9 @@ #include #include +#include "layer-model.h" +#include "selection.h" + class SPDesktop; class SPDocument; struct SPColor; @@ -47,20 +48,22 @@ struct Document; } // namespace Inkscape -void inkscape_ref (Inkscape::Application & in); -void inkscape_unref(Inkscape::Application & in); +void inkscape_ref(Inkscape::Application &in); +void inkscape_unref(Inkscape::Application &in); #define INKSCAPE (Inkscape::Application::instance()) #define SP_ACTIVE_EVENTCONTEXT (INKSCAPE.active_event_context()) #define SP_ACTIVE_DOCUMENT (INKSCAPE.active_document()) #define SP_ACTIVE_DESKTOP (INKSCAPE.active_desktop()) -class AppSelectionModel { +class AppSelectionModel +{ Inkscape::LayerModel _layer_model; Inkscape::Selection *_selection; public: - AppSelectionModel(SPDocument *doc) { + AppSelectionModel(SPDocument *doc) + { _layer_model.setDocument(doc); // TODO: is this really how we should manage the lifetime of the selection? // I just copied this from the initialization of the Selection in SPDesktop. @@ -73,19 +76,20 @@ public: namespace Inkscape { -class Application { +class Application +{ public: - static Application& instance(); + static Application &instance(); static bool exists(); static void create(bool use_gui); - + // returns the mask of the keyboard modifier to map to Alt, zero if no mapping // Needs to be a guint because gdktypes.h does not define a 'no-modifier' value guint mapalt() const { return _mapalt; } - - // Sets the keyboard modifier to map to Alt. Zero switches off mapping, as does '1', which is the default + + // Sets the keyboard modifier to map to Alt. Zero switches off mapping, as does '1', which is the default void mapalt(guint maskvalue); - + guint trackalt() const { return _trackalt; } void trackalt(guint trackvalue) { _trackalt = trackvalue; } @@ -96,67 +100,67 @@ public: static bool isCrashing() { return _crashIsHappening; } // useful functions - void application_init (gboolean use_gui); - void load_config (const gchar *filename, Inkscape::XML::Document *config, const gchar *skeleton, - unsigned int skel_size, const gchar *e_notreg, const gchar *e_notxml, - const gchar *e_notsp, const gchar *warn); + void application_init(gboolean use_gui); + void load_config(const gchar *filename, Inkscape::XML::Document *config, const gchar *skeleton, + unsigned int skel_size, const gchar *e_notreg, const gchar *e_notxml, const gchar *e_notsp, + const gchar *warn); bool load_menus(); bool save_menus(); - Inkscape::XML::Node * get_menus(); - - Inkscape::UI::Tools::ToolBase * active_event_context(); - SPDocument * active_document(); - SPDesktop * active_desktop(); + Inkscape::XML::Node *get_menus(); + + Inkscape::UI::Tools::ToolBase *active_event_context(); + SPDocument *active_document(); + SPDesktop *active_desktop(); Glib::RefPtr styleprovider; Glib::RefPtr themeprovider; Glib::RefPtr colorizeprovider; // Use this function to get selection model etc for a document Inkscape::ActionContext action_context_for_document(SPDocument *doc); Inkscape::ActionContext active_action_context(); - + bool sole_desktop_for_document(SPDesktop const &desktop); - + // Inkscape desktop stuff - void add_desktop(SPDesktop * desktop); - void remove_desktop(SPDesktop* desktop); - void activate_desktop (SPDesktop * desktop); - void switch_desktops_next (); - void switch_desktops_prev (); - void get_all_desktops (std::list< SPDesktop* >& listbuf); - void reactivate_desktop (SPDesktop * desktop); - SPDesktop * find_desktop_by_dkey (unsigned int dkey); + void add_desktop(SPDesktop *desktop); + void remove_desktop(SPDesktop *desktop); + void activate_desktop(SPDesktop *desktop); + void switch_desktops_next(); + void switch_desktops_prev(); + void get_all_desktops(std::list &listbuf); + void reactivate_desktop(SPDesktop *desktop); + SPDesktop *find_desktop_by_dkey(unsigned int dkey); unsigned int maximum_dkey(); - SPDesktop * next_desktop (); - SPDesktop * prev_desktop (); - - void external_change (); - void selection_modified (Inkscape::Selection *selection, guint flags); - void selection_changed (Inkscape::Selection * selection); - void subselection_changed (SPDesktop *desktop); - void selection_set (Inkscape::Selection * selection); + SPDesktop *next_desktop(); + SPDesktop *prev_desktop(); + + void external_change(); + void selection_modified(Inkscape::Selection *selection, guint flags); + void selection_changed(Inkscape::Selection *selection); + void subselection_changed(SPDesktop *desktop); + void selection_set(Inkscape::Selection *selection); Glib::ustring get_symbolic_colors(); - void eventcontext_set (Inkscape::UI::Tools::ToolBase * eventcontext); - + void eventcontext_set(Inkscape::UI::Tools::ToolBase *eventcontext); + // Moved document add/remove functions into public inkscape.h as they are used // (rightly or wrongly) by console-mode functions - void add_document (SPDocument *document); - bool remove_document (SPDocument *document); - + void add_document(SPDocument *document); + bool remove_document(SPDocument *document); + // fixme: This has to be rethought - void refresh_display (); - + void refresh_display(); + // fixme: This also - void exit (); - + void exit(); + static void crash_handler(int signum); // nobody should be accessing our reference count, so it's made private. - friend void ::inkscape_ref (Application & in); - friend void ::inkscape_unref(Application & in); + friend void ::inkscape_ref(Application &in); + friend void ::inkscape_unref(Application &in); // signals - + // one of selections changed sigc::signal signal_selection_changed; // one of subselections (text selection, gradient handle, etc) changed @@ -176,38 +180,30 @@ public: // these are orphaned signals (nothing emits them and nothing connects to them) sigc::signal signal_destroy_document; sigc::signal signal_color_set; - + // inkscape is quitting sigc::signal signal_shut_down; // a document was changed by some external means (undo or XML editor); this // may not be reflected by a selection change and thus needs a separate signal sigc::signal signal_external_change; - void set_pdf_poppler(bool p) { - _pdf_poppler = p; - } - bool get_pdf_poppler() { - return _pdf_poppler; - } - void set_pdf_page(gint page) { - _pdf_page = page; - } - gint get_pdf_page() { - return _pdf_page; - } + void set_pdf_poppler(bool p) { _pdf_poppler = p; } + bool get_pdf_poppler() { return _pdf_poppler; } + void set_pdf_page(gint page) { _pdf_page = page; } + gint get_pdf_page() { return _pdf_page; } void add_gtk_css(bool only_providers); void add_icon_theme(); - private: - static Inkscape::Application * _S_inst; +private: + static Inkscape::Application *_S_inst; Application(bool use_gui); ~Application(); - Application(Application const&); // no copy - Application& operator=(Application const&); // no assign - Application* operator&() const; // no pointer access + Application(Application const &); // no copy + Application &operator=(Application const &); // no assign + Application *operator&() const; // no pointer access Inkscape::XML::Document *_menus = nullptr; std::map _document_set; diff --git a/src/inkview-application.cpp b/src/inkview-application.cpp index 032dae3faa6ed5de765f86a34bbd0ff1bab7f356..7aec2c161afcee7fbc0b19abd33ce2f88f8123d6 100644 --- a/src/inkview-application.cpp +++ b/src/inkview-application.cpp @@ -15,27 +15,24 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // Defines ENABLE_NLS +#include "config.h" // Defines ENABLE_NLS #endif -#include - -#include // Internationalization - +#include // Internationalization #include +#include -#include "inkview-application.h" - -#include "inkscape.h" // Inkscape::Application -#include "inkscape-version.h" // Inkscape version #include "include/glibmm_version.h" -#include "inkgc/gc-core.h" // Garbage Collecting init +#include "inkgc/gc-core.h" // Garbage Collecting init +#include "inkscape-version.h" // Inkscape version +#include "inkscape.h" // Inkscape::Application +#include "inkview-application.h" #include "inkview-window.h" #ifdef ENABLE_NLS // Native Language Support - shouldn't this always be used? -#include "helper/gettext.h" // gettext init -#endif // ENABLE_NLS +#include "helper/gettext.h" // gettext init +#endif // ENABLE_NLS // This is a bit confusing as there are two ways to handle command line arguments and files // depending on if the Gio::APPLICATION_HANDLES_OPEN and/or Gio::APPLICATION_HANDLES_COMMAND_LINE @@ -44,8 +41,8 @@ InkviewApplication::InkviewApplication() : Gtk::Application("org.inkscape.Inkview", - Gio::APPLICATION_HANDLES_OPEN | // Use default file opening. - Gio::APPLICATION_NON_UNIQUE ) // Allows different instances of Inkview to run at same time. + Gio::APPLICATION_HANDLES_OPEN | // Use default file opening. + Gio::APPLICATION_NON_UNIQUE) // Allows different instances of Inkview to run at same time. , fullscreen(false) , recursive(false) , timer(0) @@ -61,9 +58,9 @@ InkviewApplication::InkviewApplication() Inkscape::initialize_gettext(); #endif - Glib::set_application_name(N_("Inkview - An SVG File Viewer")); // After gettext() init. + Glib::set_application_name(N_("Inkview - An SVG File Viewer")); // After gettext() init. -#if GLIBMM_CHECK_VERSION(2,56,0) +#if GLIBMM_CHECK_VERSION(2, 56, 0) // Additional informational strings for --help output // TODO: Claims to be translated automatically, but seems broken, so pass already translated strings set_option_context_parameter_string(_("path1 [path2 [pathN]]")); @@ -95,8 +92,7 @@ Glib::RefPtr InkviewApplication::create() return Glib::RefPtr(new InkviewApplication()); } -void -InkviewApplication::on_startup() +void InkviewApplication::on_startup() { Gtk::Application::on_startup(); @@ -104,10 +100,8 @@ InkviewApplication::on_startup() Inkscape::Application::create(true); } - // Open document window with default document. Either this or on_open() is called. -void -InkviewApplication::on_activate() +void InkviewApplication::on_activate() { // show file chooser dialog if no files/folders are given on the command line // TODO: A FileChooserNative would be preferential, but offers no easy way to allow files AND folders @@ -132,12 +126,11 @@ InkviewApplication::on_activate() } // Open document window for each file. Either this or on_activate() is called. -void -InkviewApplication::on_open(const Gio::Application::type_vec_files& files, const Glib::ustring& hint) +void InkviewApplication::on_open(const Gio::Application::type_vec_files &files, const Glib::ustring &hint) { try { window = new InkviewWindow(files, fullscreen, recursive, timer, scale, preload); - } catch (const InkviewWindow::NoValidFilesException&) { + } catch (const InkviewWindow::NoValidFilesException &) { std::cerr << _("Error") << ": " << _("No (valid) files to open.") << std::endl; exit(1); } @@ -146,14 +139,12 @@ InkviewApplication::on_open(const Gio::Application::type_vec_files& files, const add_window(*window); } - // ========================= Callbacks ========================== /* * Handle command line options callback. */ -int -InkviewApplication::on_handle_local_options(const Glib::RefPtr& options) +int InkviewApplication::on_handle_local_options(const Glib::RefPtr &options) { if (!options) { std::cerr << "InkviewApplication::on_handle_local_options: options is null!" << std::endl; diff --git a/src/inkview-application.h b/src/inkview-application.h index d22ea7c89a67cbde7aa890cf7f8038424357624c..e6f0890fbd6b5e591492770fc6958629b692f1dc 100644 --- a/src/inkview-application.h +++ b/src/inkview-application.h @@ -14,7 +14,6 @@ * */ - #ifndef INKVIEW_APPLICATION_H #define INKVIEW_APPLICATION_H @@ -31,22 +30,22 @@ public: static Glib::RefPtr create(); protected: - void on_startup() override; + void on_startup() override; void on_activate() override; - void on_open(const Gio::Application::type_vec_files& files, const Glib::ustring& hint) override; + void on_open(const Gio::Application::type_vec_files &files, const Glib::ustring &hint) override; private: // Callbacks - int on_handle_local_options(const Glib::RefPtr& options); + int on_handle_local_options(const Glib::RefPtr &options); // Command line options - bool fullscreen; - bool recursive; - int timer; + bool fullscreen; + bool recursive; + int timer; double scale; - bool preload; + bool preload; - InkviewWindow* window; + InkviewWindow *window; }; #endif // INKVIEW_APPLICATION_H diff --git a/src/inkview-main.cpp b/src/inkview-main.cpp index 5d60945f857ca5591c04c10e19b687f350aa7a6a..761bd8f29a431ba293e95c3632ffd3ca60317c88 100644 --- a/src/inkview-main.cpp +++ b/src/inkview-main.cpp @@ -15,8 +15,8 @@ */ #ifdef _WIN32 +#include // _O_BINARY #include // SetConsoleOutputCP -#include // _O_BINARY #endif #include "inkview-application.h" @@ -28,7 +28,7 @@ int main(int argc, char *argv[]) // as everything else is a mess and it seems to work just fine const unsigned int initial_cp = GetConsoleOutputCP(); SetConsoleOutputCP(CP_UTF8); - fflush(stdout); // empty buffer, just to be safe (see warning in documentation for _setmode) + fflush(stdout); // empty buffer, just to be safe (see warning in documentation for _setmode) _setmode(_fileno(stdout), _O_BINARY); // binary mode seems required for this to work properly #endif diff --git a/src/inkview-window.cpp b/src/inkview-window.cpp index 57e7f4727e404049302232450a241dad226608e7..e6afa069d81aad28b3618b8eefcf2ec2fd5a77e9 100644 --- a/src/inkview-window.cpp +++ b/src/inkview-window.cpp @@ -14,25 +14,17 @@ * */ - #include "inkview-window.h" #include #include "document.h" - #include "ui/monitor.h" #include "ui/view/svg-view-widget.h" - #include "util/units.h" -InkviewWindow::InkviewWindow(const Gio::Application::type_vec_files files, - bool fullscreen, - bool recursive, - int timer, - double scale, - bool preload - ) +InkviewWindow::InkviewWindow(const Gio::Application::type_vec_files files, bool fullscreen, bool recursive, int timer, + double scale, bool preload) : _files(files) , _fullscreen(fullscreen) , _recursive(recursive) @@ -53,7 +45,7 @@ InkviewWindow::InkviewWindow(const Gio::Application::type_vec_files files, throw NoValidFilesException(); } - _documents.resize( _files.size(), nullptr); // We keep _documents and _files in sync. + _documents.resize(_files.size(), nullptr); // We keep _documents and _files in sync. // Callbacks signal_key_press_event().connect(sigc::mem_fun(*this, &InkviewWindow::key_press), false); @@ -63,10 +55,10 @@ InkviewWindow::InkviewWindow(const Gio::Application::type_vec_files files, } // Actions - add_action( "show_first", sigc::mem_fun(*this, &InkviewWindow::show_first) ); - add_action( "show_prev", sigc::mem_fun(*this, &InkviewWindow::show_prev) ); - add_action( "show_next", sigc::mem_fun(*this, &InkviewWindow::show_next) ); - add_action( "show_last", sigc::mem_fun(*this, &InkviewWindow::show_last) ); + add_action("show_first", sigc::mem_fun(*this, &InkviewWindow::show_first)); + add_action("show_prev", sigc::mem_fun(*this, &InkviewWindow::show_prev)); + add_action("show_next", sigc::mem_fun(*this, &InkviewWindow::show_next)); + add_action("show_last", sigc::mem_fun(*this, &InkviewWindow::show_last)); // ToDo: Add Pause, Resume. @@ -75,13 +67,12 @@ InkviewWindow::InkviewWindow(const Gio::Application::type_vec_files files, } // Show first file - activate_action( "show_first" ); + activate_action("show_first"); } -std::vector > -InkviewWindow::create_file_list(const std::vector >& files) +std::vector> InkviewWindow::create_file_list(const std::vector> &files) { - std::vector > valid_files; + std::vector> valid_files; static bool first = true; @@ -89,12 +80,10 @@ InkviewWindow::create_file_list(const std::vector >& fi Gio::FileType type = file->query_file_type(); switch (type) { case Gio::FILE_TYPE_NOT_KNOWN: - std::cerr << "InkviewWindow: File or directory does not exist: " - << file->get_basename() << std::endl; + std::cerr << "InkviewWindow: File or directory does not exist: " << file->get_basename() << std::endl; break; - case Gio::FILE_TYPE_REGULAR: - { + case Gio::FILE_TYPE_REGULAR: { // Only look at SVG and SVGZ files. std::string basename = file->get_basename(); std::string extension = basename.substr(basename.find_last_of(".") + 1); @@ -104,13 +93,12 @@ InkviewWindow::create_file_list(const std::vector >& fi break; } - case Gio::FILE_TYPE_DIRECTORY: - { + case Gio::FILE_TYPE_DIRECTORY: { if (_recursive || first) { // No easy way to get children of directory! Glib::RefPtr children = file->enumerate_children(); Glib::RefPtr info; - std::vector > input; + std::vector> input; while ((info = children->next_file())) { input.push_back(children->get_child(info)); } @@ -128,35 +116,33 @@ InkviewWindow::create_file_list(const std::vector >& fi return valid_files; } -void -InkviewWindow::update_title() +void InkviewWindow::update_title() { Glib::ustring title(_documents[_index]->getDocumentName()); if (_documents.size() > 1) { - title += Glib::ustring::compose(" (%1/%2)", _index+1, _documents.size()); + title += Glib::ustring::compose(" (%1/%2)", _index + 1, _documents.size()); } set_title(title); } // Returns true if successfully shows document. -bool -InkviewWindow::show_document(SPDocument* document) +bool InkviewWindow::show_document(SPDocument *document) { - document->ensureUpToDate(); // Crashes on some documents if this isn't called! + document->ensureUpToDate(); // Crashes on some documents if this isn't called! // Resize window: (Might be better to use get_monitor_geometry_at_window(this)) Gdk::Rectangle monitor_geometry = Inkscape::UI::get_monitor_geometry_primary(); - int width = MIN((int)document->getWidth().value("px") * _scale, monitor_geometry.get_width()); - int height = MIN((int)document->getHeight().value("px") * _scale, monitor_geometry.get_height()); - resize (width, height); + int width = MIN((int)document->getWidth().value("px") * _scale, monitor_geometry.get_width()); + int height = MIN((int)document->getHeight().value("px") * _scale, monitor_geometry.get_height()); + resize(width, height); if (_view) { _view->setDocument(document); } else { _view = Gtk::manage(new Inkscape::UI::View::SVGViewWidget(document)); - add (*_view); + add(*_view); } update_title(); @@ -164,16 +150,14 @@ InkviewWindow::show_document(SPDocument* document) return true; } - // Load document, if fail, remove entry from lists. -SPDocument* -InkviewWindow::load_document() +SPDocument *InkviewWindow::load_document() { - SPDocument* document = _documents[_index]; + SPDocument *document = _documents[_index]; if (!document) { // We need to load document. ToDo: Pass Gio::File. Is get_base_name() better? - document = SPDocument::createNewDoc (_files[_index]->get_parse_name().c_str(), true, false); + document = SPDocument::createNewDoc(_files[_index]->get_parse_name().c_str(), true, false); if (document) { // We've successfully loaded it! _documents[_index] = document; @@ -183,21 +167,16 @@ InkviewWindow::load_document() if (!document) { // Failed to load document, remove from vectors. _documents.erase(std::next(_documents.begin(), _index)); - _files.erase( std::next( _files.begin(), _index)); + _files.erase(std::next(_files.begin(), _index)); } return document; } - - -void -InkviewWindow::preload_documents() +void InkviewWindow::preload_documents() { - for (auto it =_files.begin(); it != _files.end(); ) { - - SPDocument* document = - SPDocument::createNewDoc ((*it)->get_parse_name().c_str(), true, false); + for (auto it = _files.begin(); it != _files.end();) { + SPDocument *document = SPDocument::createNewDoc((*it)->get_parse_name().c_str(), true, false); if (document) { _documents.push_back(document); ++it; @@ -266,23 +245,17 @@ static std::string window_markup = R"( )"; -void -InkviewWindow::show_control() +void InkviewWindow::show_control() { if (!_controlwindow) { - auto builder = Gtk::Builder::create(); - try - { + try { builder->add_from_string(window_markup); - } - catch (const Glib::Error& err) - { + } catch (const Glib::Error &err) { std::cerr << "InkviewWindow::show_control: builder failed: " << err.what() << std::endl; return; } - builder->get_widget("ControlWindow", _controlwindow); if (!_controlwindow) { std::cerr << "InkviewWindow::show_control: Control Window not found!" << std::endl; @@ -297,15 +270,15 @@ InkviewWindow::show_control() // Gtk::Button not derived from Gtk::Actionable due to ABI issues. Must use Gtk. // Fixed in Gtk4. In Gtk4 this can be replaced by setting the action in the interface. - Gtk::Button* button; + Gtk::Button *button; builder->get_widget("show-first", button); - gtk_actionable_set_action_name( GTK_ACTIONABLE(button->gobj()), "viewer.show_first"); + gtk_actionable_set_action_name(GTK_ACTIONABLE(button->gobj()), "viewer.show_first"); builder->get_widget("show-prev", button); - gtk_actionable_set_action_name( GTK_ACTIONABLE(button->gobj()), "viewer.show_prev"); + gtk_actionable_set_action_name(GTK_ACTIONABLE(button->gobj()), "viewer.show_prev"); builder->get_widget("show-next", button); - gtk_actionable_set_action_name( GTK_ACTIONABLE(button->gobj()), "viewer.show_next"); + gtk_actionable_set_action_name(GTK_ACTIONABLE(button->gobj()), "viewer.show_next"); builder->get_widget("show-last", button); - gtk_actionable_set_action_name( GTK_ACTIONABLE(button->gobj()), "viewer.show_last"); + gtk_actionable_set_action_name(GTK_ACTIONABLE(button->gobj()), "viewer.show_last"); _controlwindow->set_resizable(false); _controlwindow->set_transient_for(*this); @@ -317,12 +290,11 @@ InkviewWindow::show_control() } // Next document -void -InkviewWindow::show_next() +void InkviewWindow::show_next() { ++_index; - SPDocument* document = nullptr; + SPDocument *document = nullptr; while (_index < _documents.size() && !document) { document = load_document(); @@ -338,10 +310,9 @@ InkviewWindow::show_next() } // Previous document -void -InkviewWindow::show_prev() +void InkviewWindow::show_prev() { - SPDocument* document = nullptr; + SPDocument *document = nullptr; int old_index = _index; while (_index > 0 && !document) { @@ -359,23 +330,20 @@ InkviewWindow::show_prev() } // Show first document -void -InkviewWindow::show_first() +void InkviewWindow::show_first() { _index = -1; show_next(); } // Show last document -void -InkviewWindow::show_last() +void InkviewWindow::show_last() { _index = _documents.size(); show_prev(); } -bool -InkviewWindow::key_press(GdkEventKey* event) +bool InkviewWindow::key_press(GdkEventKey *event) { switch (event->keyval) { case GDK_KEY_Up: @@ -428,8 +396,7 @@ InkviewWindow::key_press(GdkEventKey* event) return false; } -bool -InkviewWindow::on_timer() +bool InkviewWindow::on_timer() { show_next(); diff --git a/src/inkview-window.h b/src/inkview-window.h index 8cf6915fba771a9a90e08366eec63942d36ebb96..3ee5731b9422328c0c2aebb3283dc374bd6d61fb 100644 --- a/src/inkview-window.h +++ b/src/inkview-window.h @@ -24,40 +24,40 @@ class SPDocument; namespace Inkscape { namespace UI { namespace View { - class SVGViewWidget; +class SVGViewWidget; } -} -} - - -class InkviewWindow : public Gtk::ApplicationWindow { +} // namespace UI +} // namespace Inkscape +class InkviewWindow : public Gtk::ApplicationWindow +{ public: - InkviewWindow(const Gio::Application::type_vec_files files, - bool fullscreen, bool recursive, int timer, double scale, bool preload); + InkviewWindow(const Gio::Application::type_vec_files files, bool fullscreen, bool recursive, int timer, + double scale, bool preload); - class NoValidFilesException : public std::exception {}; + class NoValidFilesException : public std::exception + { + }; private: - std::vector > - create_file_list(const std::vector >& files); + std::vector> create_file_list(const std::vector> &files); void update_title(); - bool show_document(SPDocument* document); - SPDocument* load_document(); + bool show_document(SPDocument *document); + SPDocument *load_document(); void preload_documents(); - Gio::Application::type_vec_files _files; - bool _fullscreen; - bool _recursive; - int _timer; + Gio::Application::type_vec_files _files; + bool _fullscreen; + bool _recursive; + int _timer; double _scale; - bool _preload; + bool _preload; int _index; - std::vector _documents; + std::vector _documents; - Inkscape::UI::View::SVGViewWidget* _view; - Gtk::Window* _controlwindow; + Inkscape::UI::View::SVGViewWidget *_view; + Gtk::Window *_controlwindow; // Callbacks void show_control(); @@ -66,7 +66,7 @@ private: void show_first(); void show_last(); - bool key_press(GdkEventKey* event); + bool key_press(GdkEventKey *event); bool on_timer(); }; diff --git a/src/io/dir-util.cpp b/src/io/dir-util.cpp index 69a01f1fb3775904e34e02de14bd8dfd8eeaf0c0..2c54a13b40139c14147bf546cc9339f82c5fb0c0 100644 --- a/src/io/dir-util.cpp +++ b/src/io/dir-util.cpp @@ -12,37 +12,33 @@ * Utility functions for filenames. */ +#include "dir-util.h" + #include -#include #include #include -#include "dir-util.h" +#include -std::string sp_relative_path_from_path( std::string const &path, std::string const &base) +std::string sp_relative_path_from_path(std::string const &path, std::string const &base) { std::string result; - if ( !base.empty() && !path.empty() ) { + if (!base.empty() && !path.empty()) { size_t base_len = base.length(); - while (base_len != 0 - && (base[base_len - 1] == G_DIR_SEPARATOR)) - { + while (base_len != 0 && (base[base_len - 1] == G_DIR_SEPARATOR)) { --base_len; } - if ( (path.substr(0, base_len) == base.substr(0, base_len)) - && (path[base_len] == G_DIR_SEPARATOR)) - { + if ((path.substr(0, base_len) == base.substr(0, base_len)) && (path[base_len] == G_DIR_SEPARATOR)) { size_t retPos = base_len + 1; - while ( (retPos < path.length()) && (path[retPos] == G_DIR_SEPARATOR) ) { + while ((retPos < path.length()) && (path[retPos] == G_DIR_SEPARATOR)) { retPos++; } - if ( (retPos + 1) < path.length() ) { + if ((retPos + 1) < path.length()) { result = path.substr(retPos); } } - } - if ( result.empty() ) { + if (result.empty()) { result = path; } return result; @@ -50,21 +46,23 @@ std::string sp_relative_path_from_path( std::string const &path, std::string con char const *sp_extension_from_path(char const *const path) { - if (path == nullptr) { - return nullptr; - } + if (path == nullptr) { + return nullptr; + } - char const *p = path; - while (*p != '\0') p++; + char const *p = path; + while (*p != '\0') + p++; - while ((p >= path) && (*p != G_DIR_SEPARATOR) && (*p != '.')) p--; - if (* p != '.') return nullptr; - p++; + while ((p >= path) && (*p != G_DIR_SEPARATOR) && (*p != '.')) + p--; + if (*p != '.') + return nullptr; + p++; - return p; + return p; } - /* current == "./", parent == "../" */ static char const dots[] = {'.', '.', G_DIR_SEPARATOR, '\0'}; static char const *const parent = dots; @@ -72,88 +70,75 @@ static char const *const current = dots + 1; char *inkscape_rel2abs(const char *path, const char *base, char *result, const size_t size) { - const char *pp, *bp; - /* endp points the last position which is safe in the result buffer. */ - const char *endp = result + size - 1; - char *rp; - int length; - if (*path == G_DIR_SEPARATOR) - { - if (strlen (path) >= size) - goto erange; - strcpy (result, path); - goto finish; - } - else if (*base != G_DIR_SEPARATOR || !size) - { - errno = EINVAL; - return (nullptr); - } - else if (size == 1) - goto erange; - if (!strcmp (path, ".") || !strcmp (path, current)) - { - if (strlen (base) >= size) - goto erange; - strcpy (result, base); - /* rp points the last char. */ - rp = result + strlen (base) - 1; - if (*rp == G_DIR_SEPARATOR) - *rp = 0; - else - rp++; - /* rp point NULL char */ - if (*++path == G_DIR_SEPARATOR) - { - /* Append G_DIR_SEPARATOR to the tail of path name. */ - *rp++ = G_DIR_SEPARATOR; - if (rp > endp) - goto erange; - *rp = 0; - } - goto finish; + const char *pp, *bp; + /* endp points the last position which is safe in the result buffer. */ + const char *endp = result + size - 1; + char *rp; + int length; + if (*path == G_DIR_SEPARATOR) { + if (strlen(path) >= size) + goto erange; + strcpy(result, path); + goto finish; + } else if (*base != G_DIR_SEPARATOR || !size) { + errno = EINVAL; + return (nullptr); + } else if (size == 1) + goto erange; + if (!strcmp(path, ".") || !strcmp(path, current)) { + if (strlen(base) >= size) + goto erange; + strcpy(result, base); + /* rp points the last char. */ + rp = result + strlen(base) - 1; + if (*rp == G_DIR_SEPARATOR) + *rp = 0; + else + rp++; + /* rp point NULL char */ + if (*++path == G_DIR_SEPARATOR) { + /* Append G_DIR_SEPARATOR to the tail of path name. */ + *rp++ = G_DIR_SEPARATOR; + if (rp > endp) + goto erange; + *rp = 0; + } + goto finish; } - bp = base + strlen (base); - if (*(bp - 1) == G_DIR_SEPARATOR) - --bp; - /* up to root. */ - for (pp = path; *pp && *pp == '.';) - { - if (!strncmp (pp, parent, 3)) - { - pp += 3; - while (bp > base && *--bp != G_DIR_SEPARATOR) - ; - } - else if (!strncmp (pp, current, 2)) - { - pp += 2; - } - else if (!strncmp (pp, "..\0", 3)) - { - pp += 2; - while (bp > base && *--bp != G_DIR_SEPARATOR) - ; - } - else - break; + bp = base + strlen(base); + if (*(bp - 1) == G_DIR_SEPARATOR) + --bp; + /* up to root. */ + for (pp = path; *pp && *pp == '.';) { + if (!strncmp(pp, parent, 3)) { + pp += 3; + while (bp > base && *--bp != G_DIR_SEPARATOR) + ; + } else if (!strncmp(pp, current, 2)) { + pp += 2; + } else if (!strncmp(pp, "..\0", 3)) { + pp += 2; + while (bp > base && *--bp != G_DIR_SEPARATOR) + ; + } else + break; } - /* down to leaf. */ - length = bp - base; - if (length >= static_cast(size)) - goto erange; - strncpy (result, base, length); - rp = result + length; - if (*pp || *(pp - 1) == G_DIR_SEPARATOR || length == 0) - *rp++ = G_DIR_SEPARATOR; - if (rp + strlen (pp) > endp) - goto erange; - strcpy (rp, pp); + /* down to leaf. */ + length = bp - base; + if (length >= static_cast(size)) + goto erange; + strncpy(result, base, length); + rp = result + length; + if (*pp || *(pp - 1) == G_DIR_SEPARATOR || length == 0) + *rp++ = G_DIR_SEPARATOR; + if (rp + strlen(pp) > endp) + goto erange; + strcpy(rp, pp); finish: - return result; + return result; erange: - errno = ERANGE; - return (nullptr); + errno = ERANGE; + return (nullptr); } char *inkscape_abs2rel(const char *path, const char *base, char *result, const size_t size) @@ -163,19 +148,15 @@ char *inkscape_abs2rel(const char *path, const char *base, char *result, const s const char *endp = result + size - 1; char *rp; - if (*path != G_DIR_SEPARATOR) - { - if (strlen (path) >= size) + if (*path != G_DIR_SEPARATOR) { + if (strlen(path) >= size) goto erange; - strcpy (result, path); + strcpy(result, path); goto finish; - } - else if (*base != G_DIR_SEPARATOR || !size) - { + } else if (*base != G_DIR_SEPARATOR || !size) { errno = EINVAL; return (nullptr); - } - else if (size == 1) + } else if (size == 1) goto erange; /* seek to branched point. */ branch = path; @@ -183,8 +164,7 @@ char *inkscape_abs2rel(const char *path, const char *base, char *result, const s if (*pp == G_DIR_SEPARATOR) branch = pp; if (((*pp == 0) || ((*pp == G_DIR_SEPARATOR) && (*(pp + 1) == 0))) && - ((*bp == 0) || ((*bp == G_DIR_SEPARATOR) && (*(bp + 1) == 0)))) - { + ((*bp == 0) || ((*bp == G_DIR_SEPARATOR) && (*(bp + 1) == 0)))) { rp = result; *rp++ = '.'; if (*pp == G_DIR_SEPARATOR || *(pp - 1) == G_DIR_SEPARATOR) @@ -199,8 +179,7 @@ char *inkscape_abs2rel(const char *path, const char *base, char *result, const s /* up to root. */ rp = result; for (bp = base + (branch - path); *bp; bp++) - if (*bp == G_DIR_SEPARATOR && *(bp + 1) != 0) - { + if (*bp == G_DIR_SEPARATOR && *(bp + 1) != 0) { if (rp + 3 > endp) goto erange; *rp++ = '.'; @@ -211,13 +190,11 @@ char *inkscape_abs2rel(const char *path, const char *base, char *result, const s goto erange; *rp = 0; /* down to leaf. */ - if (*branch) - { - if (rp + strlen (branch + 1) > endp) + if (*branch) { + if (rp + strlen(branch + 1) > endp) goto erange; - strcpy (rp, branch + 1); - } - else + strcpy(rp, branch + 1); + } else *--rp = 0; finish: return result; @@ -228,27 +205,23 @@ erange: char *prepend_current_dir_if_relative(gchar const *uri) { - if (!uri) { - return nullptr; - } + if (!uri) { + return nullptr; + } - gchar *full_path = (gchar *) g_malloc (1001); - gchar *cwd = g_get_current_dir(); + gchar *full_path = (gchar *)g_malloc(1001); + gchar *cwd = g_get_current_dir(); - gsize bytesRead = 0; - gsize bytesWritten = 0; - GError* error = nullptr; - gchar* cwd_utf8 = g_filename_to_utf8 ( cwd, - -1, - &bytesRead, - &bytesWritten, - &error); + gsize bytesRead = 0; + gsize bytesWritten = 0; + GError *error = nullptr; + gchar *cwd_utf8 = g_filename_to_utf8(cwd, -1, &bytesRead, &bytesWritten, &error); - inkscape_rel2abs (uri, cwd_utf8, full_path, 1000); - gchar *ret = g_strdup (full_path); - g_free (full_path); - g_free (cwd); - return ret; + inkscape_rel2abs(uri, cwd_utf8, full_path, 1000); + gchar *ret = g_strdup(full_path); + g_free(full_path); + g_free(cwd); + return ret; } /* diff --git a/src/io/dir-util.h b/src/io/dir-util.h index 91f07c882c0c400e327919be1e784d52e43601f0..c73d1aa5f03bb20e40619c9c04507203194d4ff4 100644 --- a/src/io/dir-util.h +++ b/src/io/dir-util.h @@ -32,7 +32,7 @@ * * @see inkscape_abs2rel for a more sophisticated version. * @see prepend_current_dir_if_relative. -*/ + */ std::string sp_relative_path_from_path(std::string const &path, std::string const &base); char const *sp_extension_from_path(char const *path); @@ -60,7 +60,6 @@ char *inkscape_abs2rel(char const *path, char const *base, char *result, size_t char *prepend_current_dir_if_relative(char const *filename); - #endif // !SEEN_DIR_UTIL_H /* diff --git a/src/io/file-export-cmd.cpp b/src/io/file-export-cmd.cpp index 1230f26e70dd3d25dc965d1c3ba64c217684c93b..d5ad46ab2c8e92001967d8b6e8b6e29eca519b37 100644 --- a/src/io/file-export-cmd.cpp +++ b/src/io/file-export-cmd.cpp @@ -18,25 +18,23 @@ #include // PNG export #include "document.h" +#include "extension/db.h" +#include "extension/extension.h" +#include "extension/init.h" +#include "extension/output.h" +#include "extension/system.h" +#include "helper/png-write.h" // PNG Export #include "object/object-set.h" -#include "object/sp-item.h" -#include "object/sp-root.h" -#include "object/sp-text.h" #include "object/sp-flowtext.h" +#include "object/sp-item.h" #include "object/sp-namedview.h" #include "object/sp-object-group.h" -#include "object/object-set.h" -#include "path-chemistry.h" // sp_item_list_to_curves -#include "text-editing.h" // te_update_layout_now_recursive +#include "object/sp-root.h" +#include "object/sp-text.h" +#include "path-chemistry.h" // sp_item_list_to_curves #include "selection-chemistry.h" // fit_canvas_to_drawing -#include "svg/svg-color.h" // Background color -#include "helper/png-write.h" // PNG Export - -#include "extension/extension.h" -#include "extension/system.h" -#include "extension/db.h" -#include "extension/output.h" -#include "extension/init.h" +#include "svg/svg-color.h" // Background color +#include "text-editing.h" // te_update_layout_now_recursive InkFileExportCmd::InkFileExportCmd() : export_overwrite(false) @@ -56,11 +54,9 @@ InkFileExportCmd::InkFileExportCmd() , export_id_only(false) , export_background_opacity(-1) // default is unset != actively set to 0 , export_plain_svg(false) -{ -} +{} -void -InkFileExportCmd::do_export(SPDocument* doc, std::string filename_in) +void InkFileExportCmd::do_export(SPDocument *doc, std::string filename_in) { std::string export_type_filename; std::vector export_type_list; @@ -78,7 +74,7 @@ InkFileExportCmd::do_export(SPDocument* doc, std::string filename_in) // no extension is fine if --export-type is given } } else { - export_type_filename = export_filename.substr(extension_pos+1); + export_type_filename = export_filename.substr(extension_pos + 1); export_filename.erase(extension_pos); } } @@ -102,7 +98,8 @@ InkFileExportCmd::do_export(SPDocument* doc, std::string filename_in) << "Ignoring --export-type=" << export_type << "." << std::endl; } if (!export_filename.empty()) { - std::cerr << "InkFileExportCmd::do_export: --export-filename is ignored when using --export-use-hints!" << std::endl; + std::cerr << "InkFileExportCmd::do_export: --export-filename is ignored when using --export-use-hints!" + << std::endl; } export_type_list.clear(); export_type_list.emplace_back("png"); @@ -114,7 +111,7 @@ InkFileExportCmd::do_export(SPDocument* doc, std::string filename_in) } } - for (auto const& type: export_type_list) { + for (auto const &type : export_type_list) { g_info("exporting '%s' to type '%s'", filename_in.c_str(), type.c_str()); export_type_current = type; @@ -149,10 +146,9 @@ InkFileExportCmd::do_export(SPDocument* doc, std::string filename_in) } } - -// File names use std::string. HTML5 and presumably SVG 2 allows UTF-8 characters. Do we need to convert "object_id" here? -std::string -InkFileExportCmd::get_filename_out(std::string filename_in, std::string object_id) +// File names use std::string. HTML5 and presumably SVG 2 allows UTF-8 characters. Do we need to convert "object_id" +// here? +std::string InkFileExportCmd::get_filename_out(std::string filename_in, std::string object_id) { // Pipe out if (export_filename == "-") { @@ -174,11 +170,12 @@ InkFileExportCmd::get_filename_out(std::string filename_in, std::string object_i // Construct output filename from input filename and export_type. auto extension_pos = filename_in.find_last_of('.'); if (extension_pos == std::string::npos) { - std::cerr << "InkFileExportCmd::get_filename_out: cannot determine input file type from filename extension: " << filename_in << std::endl; + std::cerr << "InkFileExportCmd::get_filename_out: cannot determine input file type from filename extension: " + << filename_in << std::endl; return (std::string()); } - std::string extension = filename_in.substr(extension_pos+1); + std::string extension = filename_in.substr(extension_pos + 1); if (export_overwrite && export_type_current_native == extension) { return filename_in; } else { @@ -204,8 +201,8 @@ InkFileExportCmd::get_filename_out(std::string filename_in, std::string object_i // // Check if directory exists. // std::string directory = Glib::path_get_dirname(filename_out); // if (!Glib::file_test(directory, Glib::FILE_TEST_IS_DIR)) { - // std::cerr << "InkFileExportCmd::do_export: File path includes directory that does not exist! " << directory << std::endl; - // return (std::string()); + // std::cerr << "InkFileExportCmd::do_export: File path includes directory that does not exist! " << + // directory << std::endl; return (std::string()); // } // } } @@ -215,17 +212,16 @@ InkFileExportCmd::get_filename_out(std::string filename_in, std::string object_i * * \param doc Document to export. */ -int -InkFileExportCmd::do_export_svg(SPDocument* doc, std::string filename_in) +int InkFileExportCmd::do_export_svg(SPDocument *doc, std::string filename_in) { // Start with options that are once per document. if (export_text_to_path) { - std::vector items; + std::vector items; SPRoot *root = doc->getRoot(); doc->ensureUpToDate(); - for (auto& iter: root->children) { - SPItem* item = (SPItem*) &iter; - if (! (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item) || SP_IS_GROUP(item))) { + for (auto &iter : root->children) { + SPItem *item = (SPItem *)&iter; + if (!(SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item) || SP_IS_GROUP(item))) { continue; } @@ -233,8 +229,8 @@ InkFileExportCmd::do_export_svg(SPDocument* doc, std::string filename_in) items.push_back(item); } - std::vector selected; // Not used - std::vector to_select; // Not used + std::vector selected; // Not used + std::vector to_select; // Not used sp_item_list_to_curves(items, selected, to_select); } @@ -254,34 +250,34 @@ InkFileExportCmd::do_export_svg(SPDocument* doc, std::string filename_in) if (export_area_drawing) { fit_canvas_to_drawing(doc, export_margin != 0 ? true : false); - } else if (export_area_page || export_id.empty() ) { + } else if (export_area_page || export_id.empty()) { if (export_margin) { doc->ensureUpToDate(); doc->fitToRect(*(doc->preferredBounds()), true); } } - - // Export each object in list (or root if empty). Use ';' so in future it could be possible to selected multiple objects to export together. + // Export each object in list (or root if empty). Use ';' so in future it could be possible to selected multiple + // objects to export together. std::vector objects = Glib::Regex::split_simple("\\s*;\\s*", export_id); if (objects.empty()) { objects.emplace_back(); // So we do loop at least once for root. } for (auto object : objects) { - std::string filename_out = get_filename_out(filename_in, Glib::filename_from_utf8(object)); if (filename_out.empty()) { return 1; } - if(!object.empty()) { + if (!object.empty()) { doc->ensureUpToDate(); // "crop" the document to the specified object, cleaning as we go. SPObject *obj = doc->getObjectById(object); if (obj == nullptr) { - std::cerr << "InkFileExportCmd::do_export_svg: Object " << object << " not found in document, nothing to export." << std::endl; + std::cerr << "InkFileExportCmd::do_export_svg: Object " << object + << " not found in document, nothing to export." << std::endl; return 1; } if (export_id_only) { @@ -296,23 +292,24 @@ InkFileExportCmd::do_export_svg(SPDocument* doc, std::string filename_in) } if (export_plain_svg) { - try { - Inkscape::Extension::save(Inkscape::Extension::db.get("org.inkscape.output.svg.plain"), doc, filename_out.c_str(), false, - false, false, Inkscape::Extension::FILE_SAVE_METHOD_SAVE_COPY); + Inkscape::Extension::save(Inkscape::Extension::db.get("org.inkscape.output.svg.plain"), doc, + filename_out.c_str(), false, false, false, + Inkscape::Extension::FILE_SAVE_METHOD_SAVE_COPY); } catch (Inkscape::Extension::Output::save_failed &e) { std::cerr << "InkFileExportCmd::do_export_svg: Failed to save SVG to: " << filename_out << std::endl; return 1; } } else { - // Export as inkscape SVG. try { - Inkscape::Extension::save(Inkscape::Extension::db.get("org.inkscape.output.svg.inkscape"), doc, filename_out.c_str(), false, - false, false, Inkscape::Extension::FILE_SAVE_METHOD_INKSCAPE_SVG); + Inkscape::Extension::save(Inkscape::Extension::db.get("org.inkscape.output.svg.inkscape"), doc, + filename_out.c_str(), false, false, false, + Inkscape::Extension::FILE_SAVE_METHOD_INKSCAPE_SVG); } catch (Inkscape::Extension::Output::save_failed &e) { - std::cerr << "InkFileExportCmd::do_export_svg: Failed to save Inkscape SVG to: " << filename_out << std::endl; + std::cerr << "InkFileExportCmd::do_export_svg: Failed to save Inkscape SVG to: " << filename_out + << std::endl; return 1; } } @@ -320,36 +317,37 @@ InkFileExportCmd::do_export_svg(SPDocument* doc, std::string filename_in) return 0; } -guint32 InkFileExportCmd::get_bgcolor(SPDocument *doc) { +guint32 InkFileExportCmd::get_bgcolor(SPDocument *doc) +{ guint32 bgcolor = 0x00000000; if (!export_background.empty()) { // override the page color bgcolor = sp_svg_read_color(export_background.c_str(), 0xffffff00); // default is opaque if a color is given on commandline - if (export_background_opacity < -.5 ) { + if (export_background_opacity < -.5) { export_background_opacity = 255; } } else { // read from namedview Inkscape::XML::Node *nv = doc->getReprNamedView(); - if (nv && nv->attribute("pagecolor")){ + if (nv && nv->attribute("pagecolor")) { bgcolor = sp_svg_read_color(nv->attribute("pagecolor"), 0xffffff00); } } if (export_background_opacity > -.5) { // if the value is manually set if (export_background_opacity > 1.0) { - float value = CLAMP (export_background_opacity, 1.0f, 255.0f); - bgcolor |= (guint32) floor(value); + float value = CLAMP(export_background_opacity, 1.0f, 255.0f); + bgcolor |= (guint32)floor(value); } else { - float value = CLAMP (export_background_opacity, 0.0f, 1.0f); + float value = CLAMP(export_background_opacity, 0.0f, 1.0f); bgcolor |= SP_COLOR_F_TO_U(value); } } else { Inkscape::XML::Node *nv = doc->getReprNamedView(); - if (nv && nv->attribute("inkscape:pageopacity")){ + if (nv && nv->attribute("inkscape:pageopacity")) { double opacity = 1.0; - sp_repr_get_double (nv, "inkscape:pageopacity", &opacity); + sp_repr_get_double(nv, "inkscape:pageopacity", &opacity); bgcolor |= SP_COLOR_F_TO_U(opacity); } // else it's transparent } @@ -361,24 +359,23 @@ guint32 InkFileExportCmd::get_bgcolor(SPDocument *doc) { * * \param doc Document to export. */ -int -InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) +int InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) { bool filename_from_hint = false; gdouble dpi = 0.0; guint32 bgcolor = get_bgcolor(doc); - // Export each object in list (or root if empty). Use ';' so in future it could be possible to selected multiple objects to export together. + // Export each object in list (or root if empty). Use ';' so in future it could be possible to selected multiple + // objects to export together. std::vector objects = Glib::Regex::split_simple("\\s*;\\s*", export_id); if (objects.empty()) { objects.emplace_back(); // So we do loop at least once for root. } for (auto object_id : objects) { - std::string filename_out = get_filename_out(filename_in, Glib::filename_from_utf8(object_id)); - std::vector items; + std::vector items; // Find export object. (Either root or object with specified id.) SPObject *object = doc->getRoot(); @@ -388,28 +385,25 @@ InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) if (!object) { std::cerr << "InkFileExport::do_export_png: " - << "Object with id=\"" << object_id - << "\" was not found in the document. Skipping." << std::endl; + << "Object with id=\"" << object_id << "\" was not found in the document. Skipping." << std::endl; continue; } - if (!SP_IS_ITEM (object)) { + if (!SP_IS_ITEM(object)) { std::cerr << "InkFileExportCmd::do_export_png: " - << "Object with id=\"" << object_id - << "\" is not a visible item. Skipping." << std::endl; + << "Object with id=\"" << object_id << "\" is not a visible item. Skipping." << std::endl; continue; } items.push_back(SP_ITEM(object)); // There is only one item, why do this? if (export_id_only) { - std::cerr << "Exporting only object with id=\"" - << object_id << "\"; all other objects hidden." << std::endl; + std::cerr << "Exporting only object with id=\"" << object_id << "\"; all other objects hidden." + << std::endl; } // Find file name and dpi from hints. if (export_use_hints) { - // Retrieve export filename hint. const gchar *fn_hint = object->getRepr()->attribute("inkscape:export-filename"); if (fn_hint) { @@ -448,7 +442,7 @@ InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) } if (filename_from_hint) { - //Make relative paths go from the document location, if possible: + // Make relative paths go from the document location, if possible: if (!Glib::path_is_absolute(filename_out) && doc->getDocumentURI()) { std::string dirname = Glib::path_get_dirname(doc->getDocumentURI()); if (!dirname.empty()) { @@ -460,7 +454,8 @@ InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) // Check if directory exists std::string directory = Glib::path_get_dirname(filename_out); if (!Glib::file_test(directory, Glib::FILE_TEST_IS_DIR)) { - std::cerr << "File path " << filename_out << " includes directory that doesn't exist. Skipping." << std::endl; + std::cerr << "File path " << filename_out << " includes directory that doesn't exist. Skipping." + << std::endl; continue; } @@ -470,8 +465,7 @@ InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) dpi = export_dpi; if ((dpi < 0.1) || (dpi > 10000.0)) { std::cerr << "InkFileExport::do_export_png: " - << "DPI value " << export_dpi - << " out of range [0.1 - 10000.0]. Skipping."; + << "DPI value " << export_dpi << " out of range [0.1 - 10000.0]. Skipping."; continue; } } @@ -488,25 +482,22 @@ InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) // Three choices: 1. Command-line export_area 2. Page area 3. Drawing area if (!export_area.empty()) { - // Export area command-line /* Try to parse area (given in SVG pixels) */ - gdouble x0,y0,x1,y1; + gdouble x0, y0, x1, y1; if (sscanf(export_area.c_str(), "%lg:%lg:%lg:%lg", &x0, &y0, &x1, &y1) != 4) { g_warning("Cannot parse export area '%s'; use 'x0:y0:x1:y1'. Nothing exported.", export_area.c_str()); return 1; // If it fails once, it will fail for all objects. } - area = Geom::Rect(Geom::Interval(x0,x1), Geom::Interval(y0,y1)); + area = Geom::Rect(Geom::Interval(x0, x1), Geom::Interval(y0, y1)); } else if (export_area_page || (!export_area_drawing && object_id.empty())) { - // Export area page (explicit or if no object is given). Geom::Point origin(doc->getRoot()->x.computed, doc->getRoot()->y.computed); area = Geom::Rect(origin, origin + doc->getDimensions()); } else { - // Export area drawing (explicit or if object is given). Geom::OptRect areaMaybe = static_cast(object)->documentVisualBounds(); if (areaMaybe) { @@ -534,7 +525,8 @@ InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) height = export_height; if ((height < 1) || (height > PNG_UINT_31_MAX)) { std::cerr << "InkFileExport::do_export_png: " - << "Export height " << height << " out of range (1 to " << PNG_UINT_31_MAX << ")" << std::endl; + << "Export height " << height << " out of range (1 to " << PNG_UINT_31_MAX << ")" + << std::endl; continue; } ydpi = Inkscape::Util::Quantity::convert(height, "in", "px") / area.height(); @@ -555,15 +547,16 @@ InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) } if (width == 0) { - width = (unsigned long int) (Inkscape::Util::Quantity::convert(area.width(), "px", "in") * dpi + 0.5); + width = (unsigned long int)(Inkscape::Util::Quantity::convert(area.width(), "px", "in") * dpi + 0.5); } if (height == 0) { - height = (unsigned long int) (Inkscape::Util::Quantity::convert(area.height(), "px", "in") * dpi + 0.5); + height = (unsigned long int)(Inkscape::Util::Quantity::convert(area.height(), "px", "in") * dpi + 0.5); } if ((width < 1) || (height < 1) || (width > PNG_UINT_31_MAX) || (height > PNG_UINT_31_MAX)) { - std::cerr << "InkFileExport::do_export_png: Dimensions " << width << "x" << height << " are out of range (1 to " << PNG_UINT_31_MAX << ")." << std::endl; + std::cerr << "InkFileExport::do_export_png: Dimensions " << width << "x" << height + << " are out of range (1 to " << PNG_UINT_31_MAX << ")." << std::endl; continue; } @@ -571,15 +564,14 @@ InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) // Do we really need to print this? std::cerr << "Background RRGGBBAA: " << std::hex << bgcolor << std::dec << std::endl; - std::cerr << "Area " - << area[Geom::X][0] << ":" << area[Geom::Y][0] << ":" - << area[Geom::X][1] << ":" << area[Geom::Y][1] << " exported to " - << width << " x " << height << " pixels (" << dpi << " dpi)" << std::endl; + std::cerr << "Area " << area[Geom::X][0] << ":" << area[Geom::Y][0] << ":" << area[Geom::X][1] << ":" + << area[Geom::Y][1] << " exported to " << width << " x " << height << " pixels (" << dpi << " dpi)" + << std::endl; - reverse(items.begin(),items.end()); // But there was only one item! + reverse(items.begin(), items.end()); // But there was only one item! - if( sp_export_png_file(doc, filename_out.c_str(), area, width, height, xdpi, ydpi, - bgcolor, nullptr, nullptr, true, export_id_only ? items : std::vector()) == 1 ) { + if (sp_export_png_file(doc, filename_out.c_str(), area, width, height, xdpi, ydpi, bgcolor, nullptr, nullptr, + true, export_id_only ? items : std::vector()) == 1) { } else { std::cerr << "InkFileExport::do_export_png: Failed to export to " << filename_out << std::endl; continue; @@ -589,7 +581,6 @@ InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) return 0; } - /** * Perform a PDF/PS/EPS export * @@ -597,19 +588,19 @@ InkFileExportCmd::do_export_png(SPDocument *doc, std::string filename_in) * \param filename File to write to. * \param mime MIME type to export as. */ -int -InkFileExportCmd::do_export_ps_pdf(SPDocument* doc, std::string filename_in, std::string mime_type) +int InkFileExportCmd::do_export_ps_pdf(SPDocument *doc, std::string filename_in, std::string mime_type) { // Check if we support mime type. Inkscape::Extension::DB::OutputList o; Inkscape::Extension::db.get_output_list(o); Inkscape::Extension::DB::OutputList::const_iterator i = o.begin(); - while (i != o.end() && strcmp( (*i)->get_mimetype(), mime_type.c_str() ) != 0) { + while (i != o.end() && strcmp((*i)->get_mimetype(), mime_type.c_str()) != 0) { ++i; } if (i == o.end()) { - std::cerr << "InkFileExportCmd::do_export_ps_pdf: Could not find an extension to export to MIME type: " << mime_type << std::endl; + std::cerr << "InkFileExportCmd::do_export_ps_pdf: Could not find an extension to export to MIME type: " + << mime_type << std::endl; return 1; } @@ -638,7 +629,7 @@ InkFileExportCmd::do_export_ps_pdf(SPDocument* doc, std::string filename_in, std } } - (*i)->set_param_int("resolution", (int) dpi); + (*i)->set_param_int("resolution", (int)dpi); } (*i)->set_param_float("bleed", export_margin); @@ -656,7 +647,8 @@ InkFileExportCmd::do_export_ps_pdf(SPDocument* doc, std::string filename_in, std (*i)->set_param_optiongroup(pdfver_param_name, version_gui_string.c_str()); set_export_pdf_version_fail = false; } else { - g_warning("Desired PDF export version \"%s\" not supported! Hint: input one of the versions found in the pdf export dialog e.g. \"1.4\".", + g_warning("Desired PDF export version \"%s\" not supported! Hint: input one of the versions found " + "in the pdf export dialog e.g. \"1.4\".", export_pdf_level.c_str()); } } catch (...) { @@ -668,13 +660,13 @@ InkFileExportCmd::do_export_ps_pdf(SPDocument* doc, std::string filename_in, std } // set default pdf export version to 1.4, also if something went wrong - if(set_export_pdf_version_fail) { + if (set_export_pdf_version_fail) { (*i)->set_param_optiongroup(pdfver_param_name, "PDF-1.4"); } } if (mime_type == "image/x-postscript" || mime_type == "image/x-e-postscript") { - if ( export_ps_level < 2 || export_ps_level > 3 ) { + if (export_ps_level < 2 || export_ps_level > 3) { g_warning("Only supported PostScript levels are 2 and 3." " Defaulting to 2."); export_ps_level = 2; @@ -683,15 +675,14 @@ InkFileExportCmd::do_export_ps_pdf(SPDocument* doc, std::string filename_in, std (*i)->set_param_optiongroup("PSlevel", (export_ps_level == 3) ? "PS3" : "PS2"); } - - // Export each object in list (or root if empty). Use ';' so in future it could be possible to selected multiple objects to export together. + // Export each object in list (or root if empty). Use ';' so in future it could be possible to selected multiple + // objects to export together. std::vector objects = Glib::Regex::split_simple("\\s*;\\s*", export_id); if (objects.empty()) { objects.emplace_back(); // So we do loop at least once for root. } for (auto object : objects) { - std::string filename_out = get_filename_out(filename_in, Glib::filename_from_utf8(object)); if (filename_out.empty()) { return 1; @@ -701,35 +692,42 @@ InkFileExportCmd::do_export_ps_pdf(SPDocument* doc, std::string filename_in, std if (!object.empty()) { SPObject *o = doc->getObjectById(object); if (o == nullptr) { - std::cerr << "InkFileExportCmd::do_export_ps_pdf: Object " << object << " not found in document, nothing to export." << std::endl; + std::cerr << "InkFileExportCmd::do_export_ps_pdf: Object " << object + << " not found in document, nothing to export." << std::endl; return 1; } - (*i)->set_param_string ("exportId", object.c_str()); + (*i)->set_param_string("exportId", object.c_str()); } else { - (*i)->set_param_string ("exportId", ""); + (*i)->set_param_string("exportId", ""); } // Set export area. if (export_area_page && export_area_drawing) { - std::cerr << "You cannot use --export-area-page and --export-area-drawing at the same time; only the former will take effect." << std::endl;; + std::cerr << "You cannot use --export-area-page and --export-area-drawing at the same time; only the " + "former will take effect." + << std::endl; + ; export_area_drawing = false; } if (export_area_drawing) { - (*i)->set_param_optiongroup ("area", "drawing"); + (*i)->set_param_optiongroup("area", "drawing"); } if (export_area_page) { if (export_type == "eps") { - std::cerr << "EPS cannot have its bounding box extend beyond its content, so if your drawing is smaller than the page, --export-area-page will clip it to drawing." << std::endl; + std::cerr << "EPS cannot have its bounding box extend beyond its content, so if your drawing is " + "smaller than the page, --export-area-page will clip it to drawing." + << std::endl; } - (*i)->set_param_optiongroup ("area", "page"); + (*i)->set_param_optiongroup("area", "page"); } if (!export_area_drawing && !export_area_page) { // Neither is set. if (export_type == "eps" || !object.empty()) { - // Default to drawing for EPS or if object is specified (latter matches behavior for other export types). + // Default to drawing for EPS or if object is specified (latter matches behavior for other export + // types). (*i)->set_param_optiongroup("area", "drawing"); } else { (*i)->set_param_optiongroup("area", "page"); @@ -738,7 +736,7 @@ InkFileExportCmd::do_export_ps_pdf(SPDocument* doc, std::string filename_in, std try { (*i)->save(doc, filename_out.c_str()); - } catch(...) { + } catch (...) { std::cerr << "Failed to save PS/EPS/PDF to: " << filename_out << std::endl; return 1; } @@ -754,8 +752,7 @@ InkFileExportCmd::do_export_ps_pdf(SPDocument* doc, std::string filename_in, std * \param filename to export to. * \param mime MIME type to export as (should be "image/x-emf" or "image/x-wmf") */ -int -InkFileExportCmd::do_export_win_metafile(SPDocument* doc, std::string filename_in, std::string mime_type) +int InkFileExportCmd::do_export_win_metafile(SPDocument *doc, std::string filename_in, std::string mime_type) { std::string filename_out = get_filename_out(filename_in); @@ -763,13 +760,14 @@ InkFileExportCmd::do_export_win_metafile(SPDocument* doc, std::string filename_i Inkscape::Extension::DB::OutputList o; Inkscape::Extension::db.get_output_list(o); Inkscape::Extension::DB::OutputList::const_iterator i = o.begin(); - while (i != o.end() && strcmp( (*i)->get_mimetype(), mime_type.c_str() ) != 0) { + while (i != o.end() && strcmp((*i)->get_mimetype(), mime_type.c_str()) != 0) { ++i; } - if (i == o.end()) - { - std::cerr << "InkFileExportCmd::do_export_win_metafile_common: Could not find an extension to export to MIME type: " << mime_type << std::endl; + if (i == o.end()) { + std::cerr + << "InkFileExportCmd::do_export_win_metafile_common: Could not find an extension to export to MIME type: " + << mime_type << std::endl; return 1; } diff --git a/src/io/file-export-cmd.h b/src/io/file-export-cmd.h index 50d0bac6fa4a7e83ae512596e7ab1017209c88e3..4edd686de20c7f56b86d80574c0cbf0d17ff6aaf 100644 --- a/src/io/file-export-cmd.h +++ b/src/io/file-export-cmd.h @@ -12,26 +12,25 @@ #ifndef INK_FILE_EXPORT_CMD_H #define INK_FILE_EXPORT_CMD_H -#include #include +#include class SPDocument; -class InkFileExportCmd { - +class InkFileExportCmd +{ public: InkFileExportCmd(); - void do_export(SPDocument* doc, std::string filename_in=""); + void do_export(SPDocument *doc, std::string filename_in = ""); private: - guint32 get_bgcolor(SPDocument *doc); - std::string get_filename_out(std::string filename_in="", std::string object_id=""); - int do_export_svg( SPDocument* doc, std::string filename_in); - int do_export_png( SPDocument* doc, std::string filename_in); - int do_export_ps_pdf(SPDocument* doc, std::string filename_in, std::string mime_type); - int do_export_win_metafile(SPDocument* doc, std::string filename_in, std::string mime_type); + std::string get_filename_out(std::string filename_in = "", std::string object_id = ""); + int do_export_svg(SPDocument *doc, std::string filename_in); + int do_export_png(SPDocument *doc, std::string filename_in); + int do_export_ps_pdf(SPDocument *doc, std::string filename_in, std::string mime_type); + int do_export_win_metafile(SPDocument *doc, std::string filename_in, std::string mime_type); Glib::ustring export_type_current; @@ -39,31 +38,31 @@ public: // Should be private, but this is just temporary code (I hope!). // One-to-one correspondence with command line options - std::string export_filename; // Only if one file is processed! + std::string export_filename; // Only if one file is processed! Glib::ustring export_type; - bool export_overwrite; + bool export_overwrite; Glib::ustring export_area; - bool export_area_drawing; - bool export_area_page; - int export_margin; - bool export_area_snap; - int export_width; - int export_height; - - double export_dpi; - bool export_ignore_filters; - bool export_text_to_path; - int export_ps_level; + bool export_area_drawing; + bool export_area_page; + int export_margin; + bool export_area_snap; + int export_width; + int export_height; + + double export_dpi; + bool export_ignore_filters; + bool export_text_to_path; + int export_ps_level; Glib::ustring export_pdf_level; - bool export_latex; + bool export_latex; Glib::ustring export_id; - bool export_id_only; - bool export_use_hints; + bool export_id_only; + bool export_use_hints; Glib::ustring export_background; - double export_background_opacity; - bool export_plain_svg; + double export_background_opacity; + bool export_plain_svg; }; #endif // INK_FILE_EXPORT_CMD_H diff --git a/src/io/file.cpp b/src/io/file.cpp index a3e4645e9a5247e7ef6cc3cc4ba4acbd0d70c02e..d934d0cb6fa526fc5fef7bd312bb69284acf37bd 100644 --- a/src/io/file.cpp +++ b/src/io/file.cpp @@ -10,31 +10,26 @@ #include "file.h" -#include #include +#include -#include "document.h" #include "document-undo.h" - -#include "extension/system.h" // Extension::open() -#include "extension/extension.h" +#include "document.h" #include "extension/db.h" -#include "extension/output.h" +#include "extension/extension.h" #include "extension/input.h" - +#include "extension/output.h" +#include "extension/system.h" // Extension::open() #include "object/sp-root.h" - #include "xml/repr.h" - /** * Create a blank document, remove any template data. * Input: Empty string or template file name. */ -SPDocument* -ink_file_new(const std::string &Template) +SPDocument *ink_file_new(const std::string &Template) { - SPDocument *doc = SPDocument::createNewDoc ((Template.empty() ? nullptr : Template.c_str()), true, true ); + SPDocument *doc = SPDocument::createNewDoc((Template.empty() ? nullptr : Template.c_str()), true, true); if (doc) { // Remove all the template info from xml tree @@ -63,19 +58,17 @@ ink_file_new(const std::string &Template) /** * Open a document from memory. */ -SPDocument* -ink_file_open(const Glib::ustring& data) +SPDocument *ink_file_open(const Glib::ustring &data) { - SPDocument *doc = SPDocument::createNewDocFromMem (data.c_str(), data.length(), true); + SPDocument *doc = SPDocument::createNewDocFromMem(data.c_str(), data.length(), true); if (doc == nullptr) { std::cerr << "ink_file_open: cannot open file in memory (pipe?)" << std::endl; } else { - // This is the only place original values should be set. SPRoot *root = doc->getRoot(); root->original.inkscape = root->version.inkscape; - root->original.svg = root->version.svg; + root->original.svg = root->version.svg; } return doc; @@ -84,8 +77,7 @@ ink_file_open(const Glib::ustring& data) /** * Open a document. */ -SPDocument* -ink_file_open(const Glib::RefPtr& file, bool *cancelled_param) +SPDocument *ink_file_open(const Glib::RefPtr &file, bool *cancelled_param) { bool cancelled = false; @@ -125,7 +117,7 @@ ink_file_open(const Glib::RefPtr& file, bool *cancelled_param) // This is the only place original values should be set. SPRoot *root = doc->getRoot(); root->original.inkscape = root->version.inkscape; - root->original.svg = root->version.svg; + root->original.svg = root->version.svg; } else if (!cancelled) { std::cerr << "ink_file_open: '" << path << "' cannot be opened!" << std::endl; } diff --git a/src/io/file.h b/src/io/file.h index 5d2ec6d86d03b5ebea8f21f596815c6a7f91bcac..8adacf66c101eb0c955aed7a011f6e681f3121fa 100644 --- a/src/io/file.h +++ b/src/io/file.h @@ -22,19 +22,17 @@ class ustring; template class RefPtr; -} +} // namespace Glib class SPDocument; -SPDocument* ink_file_new(const std::string &Template = nullptr); -SPDocument* ink_file_open(const Glib::ustring &data); -SPDocument* ink_file_open(const Glib::RefPtr& file, bool *cancelled = nullptr); +SPDocument *ink_file_new(const std::string &Template = nullptr); +SPDocument *ink_file_open(const Glib::ustring &data); +SPDocument *ink_file_open(const Glib::RefPtr &file, bool *cancelled = nullptr); // To do: // ink_file_save() // ink_file_export() // ink_file_import() - - #endif // INK_FILE_IO_H diff --git a/src/io/http.cpp b/src/io/http.cpp index 6f28db7e4bbaae5b0bf85ca9c3b93353cd8d2294..7299909c1dc5ff35686473d33cba3fff10a99e53 100644 --- a/src/io/http.cpp +++ b/src/io/http.cpp @@ -16,18 +16,20 @@ * g_warning("HTTP request saved to %s", filename.c_str()); * } * uint timeout = 20 * 60 * 60; // 20 hours - * Glib::ustring filename = Inkscape::IO::HTTP::get_file("https://media.inkscape.org/media/messages.xml", timeout, _async_test_call); + * Glib::ustring filename = Inkscape::IO::HTTP::get_file("https://media.inkscape.org/media/messages.xml", timeout, + * _async_test_call); * */ +#include "io/http.h" + +#include #include #include #include -#include -#include "io/sys.h" -#include "io/http.h" #include "io/resource.h" +#include "io/sys.h" typedef std::function callback; @@ -37,7 +39,8 @@ namespace Inkscape { namespace IO { namespace HTTP { -void _save_data_as_file(Glib::ustring filename, const char *result) { +void _save_data_as_file(Glib::ustring filename, const char *result) +{ FILE *fileout = Inkscape::IO::fopen_utf8name(filename.c_str(), "wb"); if (!fileout) { g_warning("HTTP Cache: Can't open %s for write.", filename.c_str()); @@ -53,8 +56,9 @@ void _save_data_as_file(Glib::ustring filename, const char *result) { fclose(fileout); } -void _get_file_callback(SoupSession *session, SoupMessage *msg, gpointer user_data) { - auto data = static_cast*>(user_data); +void _get_file_callback(SoupSession *session, SoupMessage *msg, gpointer user_data) +{ + auto data = static_cast *>(user_data); data->first(data->second); delete data; } @@ -75,14 +79,14 @@ void _get_file_callback(SoupSession *session, SoupMessage *msg, gpointer user_da * your func will be called in a blocking way BEFORE this function returns. * */ -Glib::ustring get_file(Glib::ustring uri, unsigned int timeout, callback func) { - +Glib::ustring get_file(Glib::ustring uri, unsigned int timeout, callback func) +{ SoupURI *s_uri = soup_uri_new(uri.c_str()); std::string path = std::string(soup_uri_decode(soup_uri_get_path(s_uri))); std::string filepart; // Parse the url into a filename suitable for caching. - if(path.back() == '/') { + if (path.back() == '/') { filepart = path.replace(path.begin(), path.end(), '/', '_'); filepart += ".url"; } else { @@ -93,14 +97,14 @@ Glib::ustring get_file(Glib::ustring uri, unsigned int timeout, callback func) { Glib::ustring filename = Glib::ustring(ret); // We test first if the cache already exists - if(file_test(filename.c_str(), G_FILE_TEST_EXISTS) && timeout > 0) { + if (file_test(filename.c_str(), G_FILE_TEST_EXISTS) && timeout > 0) { GStatBuf st; - if(g_stat(filename.c_str(), &st) != -1) { - time_t changed = st.st_mtime; - time_t now = time(nullptr); + if (g_stat(filename.c_str(), &st) != -1) { + time_t changed = st.st_mtime; + time_t now = time(nullptr); // The cache hasn't timed out, so return the filename. - if(now - changed < timeout) { - if(func) { + if (now - changed < timeout) { + if (func) { // Non-async func callback return, may block. func(filename); } @@ -117,16 +121,16 @@ Glib::ustring get_file(Glib::ustring uri, unsigned int timeout, callback func) { #ifdef DEBUG_HTTP SoupLogger *logger; logger = soup_logger_new(SOUP_LOGGER_LOG_BODY, -1); - soup_session_add_feature(session, SOUP_SESSION_FEATURE (logger)); - g_object_unref (logger); + soup_session_add_feature(session, SOUP_SESSION_FEATURE(logger)); + g_object_unref(logger); #endif - if(func) { + if (func) { auto *user_data = new std::pair(func, filename); soup_session_queue_message(session, msg, _get_file_callback, user_data); } else { - guint status = soup_session_send_message (session, msg); - if(status == SOUP_STATUS_OK) { + guint status = soup_session_send_message(session, msg); + if (status == SOUP_STATUS_OK) { g_debug("HTTP Cache saved to: %s", filename.c_str()); _save_data_as_file(filename, msg->response_body->data); } else { @@ -136,10 +140,9 @@ Glib::ustring get_file(Glib::ustring uri, unsigned int timeout, callback func) { return filename; } - -} -} -} +} // namespace HTTP +} // namespace IO +} // namespace Inkscape /* Local Variables: diff --git a/src/io/http.h b/src/io/http.h index 398d699b1ee3cb069028f234b952c946ead826c4..ee00b364016f636ee07bf6e3638368610d78bcc5 100644 --- a/src/io/http.h +++ b/src/io/http.h @@ -22,11 +22,10 @@ namespace Inkscape { namespace IO { namespace HTTP { - Glib::ustring get_file(Glib::ustring uri, unsigned int timeout=0, std::function func=nullptr); - -} -} +Glib::ustring get_file(Glib::ustring uri, unsigned int timeout = 0, std::function func = nullptr); } +} // namespace IO +} // namespace Inkscape #endif /* diff --git a/src/io/resource-manager.cpp b/src/io/resource-manager.cpp index e0a3ac95ebe9f9c3cea4fc806af54f2de7c76a6c..67e0234a7401a389c872f80f9662c7af38dfb491 100644 --- a/src/io/resource-manager.cpp +++ b/src/io/resource-manager.cpp @@ -7,45 +7,42 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include -#include -#include +#include "resource-manager.h" -#include +#include +#include +#include #include #include -#include #include -#include - -#include "resource-manager.h" +#include +#include +#include +#include -#include "document.h" #include "document-undo.h" -#include "verbs.h" - +#include "document.h" #include "object/sp-object.h" - +#include "verbs.h" #include "xml/node.h" namespace Inkscape { -static std::vector splitPath( std::string const &path ) +static std::vector splitPath(std::string const &path) { std::vector parts; std::string prior; std::string tmp = path; - while ( !tmp.empty() && (tmp != prior) ) { + while (!tmp.empty() && (tmp != prior)) { prior = tmp; - parts.push_back( Glib::path_get_basename(tmp) ); + parts.push_back(Glib::path_get_basename(tmp)); tmp = Glib::path_get_dirname(tmp); } - if ( !parts.empty() ) { + if (!parts.empty()) { std::reverse(parts.begin(), parts.end()); - if ( (parts[0] == ".") && (path[0] != '.') ) { + if ((parts[0] == ".") && (path[0] != '.')) { parts.erase(parts.begin()); } } @@ -53,50 +50,50 @@ static std::vector splitPath( std::string const &path ) return parts; } -static std::string convertPathToRelative( std::string const &path, std::string const &docbase ) +static std::string convertPathToRelative(std::string const &path, std::string const &docbase) { std::string result = path; - if ( !path.empty() && Glib::path_is_absolute(path) ) { + if (!path.empty() && Glib::path_is_absolute(path)) { // Whack the parts into pieces std::vector parts = splitPath(path); std::vector baseParts = splitPath(docbase); // TODO debug g_message("+++++++++++++++++++++++++"); - for ( std::vector::iterator it = parts.begin(); it != parts.end(); ++it ) { + for (std::vector::iterator it = parts.begin(); it != parts.end(); ++it) { // TODO debug g_message(" [%s]", it->c_str()); } // TODO debug g_message(" - - - - - - - - - - - - - - - "); - for ( std::vector::iterator it = baseParts.begin(); it != baseParts.end(); ++it ) { + for (std::vector::iterator it = baseParts.begin(); it != baseParts.end(); ++it) { // TODO debug g_message(" [%s]", it->c_str()); } // TODO debug g_message("+++++++++++++++++++++++++"); - if ( !parts.empty() && !baseParts.empty() && (parts[0] == baseParts[0]) ) { + if (!parts.empty() && !baseParts.empty() && (parts[0] == baseParts[0])) { // Both paths have the same root. We can proceed. - while ( !parts.empty() && !baseParts.empty() && (parts[0] == baseParts[0]) ) { - parts.erase( parts.begin() ); - baseParts.erase( baseParts.begin() ); + while (!parts.empty() && !baseParts.empty() && (parts[0] == baseParts[0])) { + parts.erase(parts.begin()); + baseParts.erase(baseParts.begin()); } // TODO debug g_message("+++++++++++++++++++++++++"); - for ( std::vector::iterator it = parts.begin(); it != parts.end(); ++it ) { + for (std::vector::iterator it = parts.begin(); it != parts.end(); ++it) { // TODO debug g_message(" [%s]", it->c_str()); } // TODO debug g_message(" - - - - - - - - - - - - - - - "); - for ( std::vector::iterator it = baseParts.begin(); it != baseParts.end(); ++it ) { + for (std::vector::iterator it = baseParts.begin(); it != baseParts.end(); ++it) { // TODO debug g_message(" [%s]", it->c_str()); } // TODO debug g_message("+++++++++++++++++++++++++"); - if ( !parts.empty() ) { + if (!parts.empty()) { result.clear(); - for ( size_t i = 0; i < baseParts.size(); ++i ) { + for (size_t i = 0; i < baseParts.size(); ++i) { parts.insert(parts.begin(), ".."); } - result = Glib::build_filename( parts ); + result = Glib::build_filename(parts); // TODO debug g_message("----> [%s]", result.c_str()); } } @@ -105,14 +102,13 @@ static std::string convertPathToRelative( std::string const &path, std::string c return result; } - -class ResourceManagerImpl : public ResourceManager { +class ResourceManagerImpl : public ResourceManager +{ public: ResourceManagerImpl(); ~ResourceManagerImpl() override; bool fixupBrokenLinks(SPDocument *doc) override; - /** * Walk all links in a document and create a listing of unique broken links. @@ -129,8 +125,8 @@ public: * * @return a map of found links. */ - std::map locateLinks(Glib::ustring const & docbase, std::vector const & brokenLinks); - + std::map locateLinks(Glib::ustring const &docbase, + std::vector const &brokenLinks); /** * Try to parse href into a local filename using standard methods. @@ -147,37 +143,34 @@ public: */ bool reconstructFilepath(Glib::ustring const &href, std::string &filename); - bool searchUpwards( std::string const &base, std::string const &subpath, std::string &dest ); + bool searchUpwards(std::string const &base, std::string const &subpath, std::string &dest); protected: }; - ResourceManagerImpl::ResourceManagerImpl() : ResourceManager() -{ -} +{} -ResourceManagerImpl::~ResourceManagerImpl() -= default; +ResourceManagerImpl::~ResourceManagerImpl() = default; bool ResourceManagerImpl::extractFilepath(Glib::ustring const &href, std::string &filename) -{ +{ bool isFile = false; filename.clear(); auto scheme = Glib::uri_parse_scheme(href.raw()); - if ( !scheme.empty() ) { + if (!scheme.empty()) { // TODO debug g_message("Scheme is now [%s]", scheme.c_str()); - if ( scheme == "file" ) { + if (scheme == "file") { // TODO debug g_message("--- is a file URI [%s]", href.c_str()); // throws Glib::ConvertError: try { filename = Glib::filename_from_uri(href); isFile = true; - } catch(Glib::ConvertError e) { + } catch (Glib::ConvertError e) { g_warning("%s", e.what().c_str()); } } @@ -192,14 +185,14 @@ bool ResourceManagerImpl::extractFilepath(Glib::ustring const &href, std::string } bool ResourceManagerImpl::reconstructFilepath(Glib::ustring const &href, std::string &filename) -{ +{ bool isFile = false; filename.clear(); auto scheme = Glib::uri_parse_scheme(href.raw()); - if ( !scheme.empty() ) { - if ( scheme == "file" ) { + if (!scheme.empty()) { + if (scheme == "file") { // try to build a relative filename for URIs like "file:image.png" // they're not standard conformant but not uncommon Glib::ustring href_new = Glib::ustring(href, 5); @@ -210,19 +203,18 @@ bool ResourceManagerImpl::reconstructFilepath(Glib::ustring const &href, std::st return isFile; } - -std::vector ResourceManagerImpl::findBrokenLinks( SPDocument *doc ) +std::vector ResourceManagerImpl::findBrokenLinks(SPDocument *doc) { std::vector result; std::set uniques; - if ( doc ) { + if (doc) { std::vector images = doc->getResourceList("image"); for (auto image : images) { Inkscape::XML::Node *ir = image->getRepr(); gchar const *href = ir->attribute("xlink:href"); - if ( href && ( uniques.find(href) == uniques.end() ) ) { + if (href && (uniques.find(href) == uniques.end())) { std::string filename; if (extractFilepath(href, filename)) { if (Glib::path_is_absolute(filename)) { @@ -232,7 +224,7 @@ std::vector ResourceManagerImpl::findBrokenLinks( SPDocument *doc } } else { std::string combined = Glib::build_filename(doc->getDocumentBase(), filename); - if ( !Glib::file_test(combined, Glib::FILE_TEST_EXISTS) ) { + if (!Glib::file_test(combined, Glib::FILE_TEST_EXISTS)) { result.emplace_back(href); uniques.insert(href); } @@ -242,31 +234,30 @@ std::vector ResourceManagerImpl::findBrokenLinks( SPDocument *doc uniques.insert(href); } } - } + } } return result; } - -std::map ResourceManagerImpl::locateLinks(Glib::ustring const & docbase, std::vector const & brokenLinks) +std::map ResourceManagerImpl::locateLinks(Glib::ustring const &docbase, + std::vector const &brokenLinks) { std::map result; - // Note: we use a vector because we want them to stay in order: std::vector priorLocations; Glib::RefPtr recentMgr = Gtk::RecentManager::get_default(); - std::vector< Glib::RefPtr > recentItems = recentMgr->get_items(); - for (auto & recentItem : recentItems) { + std::vector> recentItems = recentMgr->get_items(); + for (auto &recentItem : recentItems) { Glib::ustring uri = recentItem->get_uri(); auto scheme = Glib::uri_parse_scheme(uri.raw()); - if ( scheme == "file" ) { + if (scheme == "file") { try { std::string path = Glib::filename_from_uri(uri); path = Glib::path_get_dirname(path); - if ( std::find(priorLocations.begin(), priorLocations.end(), path) == priorLocations.end() ) { + if (std::find(priorLocations.begin(), priorLocations.end(), path) == priorLocations.end()) { // TODO debug g_message(" ==>[%s]", path.c_str()); priorLocations.push_back(path); } @@ -277,7 +268,7 @@ std::map ResourceManagerImpl::locateLinks(Glib::us } // At the moment we expect this list to contain file:// references, or simple relative or absolute paths. - for (const auto & brokenLink : brokenLinks) { + for (const auto &brokenLink : brokenLinks) { // TODO debug g_message("========{%s}", it->c_str()); std::string filename; @@ -299,15 +290,16 @@ std::map ResourceManagerImpl::locateLinks(Glib::us } // Check if the MRU bases point us to it. - if ( !exists ) { - if ( !Glib::path_is_absolute(origPath) ) { - for ( std::vector::iterator it = priorLocations.begin(); !exists && (it != priorLocations.end()); ++it ) { + if (!exists) { + if (!Glib::path_is_absolute(origPath)) { + for (std::vector::iterator it = priorLocations.begin(); + !exists && (it != priorLocations.end()); ++it) { exists = searchUpwards(*it, origPath, filename); } } } - if ( exists ) { + if (exists) { if (Glib::path_is_absolute(filename)) { filename = convertPathToRelative(filename, docbase_native); } @@ -326,14 +318,14 @@ std::map ResourceManagerImpl::locateLinks(Glib::us bool ResourceManagerImpl::fixupBrokenLinks(SPDocument *doc) { bool changed = false; - if ( doc ) { + if (doc) { // TODO debug g_message("FIXUP FIXUP FIXUP FIXUP FIXUP FIXUP FIXUP FIXUP FIXUP FIXUP"); // TODO debug g_message(" base is [%s]", doc->getDocumentBase()); std::vector brokenHrefs = findBrokenLinks(doc); - if ( !brokenHrefs.empty() ) { + if (!brokenHrefs.empty()) { // TODO debug g_message(" FOUND SOME LINKS %d", static_cast(brokenHrefs.size())); - for ( std::vector::iterator it = brokenHrefs.begin(); it != brokenHrefs.end(); ++it ) { + for (std::vector::iterator it = brokenHrefs.begin(); it != brokenHrefs.end(); ++it) { // TODO debug g_message(" [%s]", it->c_str()); } } @@ -344,27 +336,26 @@ bool ResourceManagerImpl::fixupBrokenLinks(SPDocument *doc) } std::map mapping = locateLinks(base, brokenHrefs); - for ( std::map::iterator it = mapping.begin(); it != mapping.end(); ++it ) - { + for (std::map::iterator it = mapping.begin(); it != mapping.end(); ++it) { // TODO debug g_message(" [%s] ==> {%s}", it->first.c_str(), it->second.c_str()); } bool savedUndoState = DocumentUndo::getUndoSensitive(doc); DocumentUndo::setUndoSensitive(doc, true); - + std::vector images = doc->getResourceList("image"); for (auto image : images) { Inkscape::XML::Node *ir = image->getRepr(); gchar const *href = ir->attribute("xlink:href"); - if ( href ) { + if (href) { // TODO debug g_message(" consider [%s]", href); - - if ( mapping.find(href) != mapping.end() ) { + + if (mapping.find(href) != mapping.end()) { // TODO debug g_message(" Found a replacement"); - ir->setAttributeOrRemoveIfEmpty( "xlink:href", mapping[href] ); - if ( ir->attribute( "sodipodi:absref" ) ) { + ir->setAttributeOrRemoveIfEmpty("xlink:href", mapping[href]); + if (ir->attribute("sodipodi:absref")) { ir->removeAttribute("sodipodi:absref"); // Remove this attribute } @@ -378,8 +369,8 @@ bool ResourceManagerImpl::fixupBrokenLinks(SPDocument *doc) } } } - if ( changed ) { - DocumentUndo::done( doc, SP_VERB_DIALOG_XML_EDITOR, _("Fixup broken links") ); + if (changed) { + DocumentUndo::done(doc, SP_VERB_DIALOG_XML_EDITOR, _("Fixup broken links")); } DocumentUndo::setUndoSensitive(doc, savedUndoState); } @@ -387,8 +378,7 @@ bool ResourceManagerImpl::fixupBrokenLinks(SPDocument *doc) return changed; } - -bool ResourceManagerImpl::searchUpwards( std::string const &base, std::string const &subpath, std::string &dest ) +bool ResourceManagerImpl::searchUpwards(std::string const &base, std::string const &subpath, std::string &dest) { bool exists = false; // TODO debug g_message("............"); @@ -396,21 +386,21 @@ bool ResourceManagerImpl::searchUpwards( std::string const &base, std::string co std::vector parts = splitPath(subpath); std::vector baseParts = splitPath(base); - while ( !exists && !baseParts.empty() ) { + while (!exists && !baseParts.empty()) { std::vector current; current.insert(current.begin(), parts.begin(), parts.end()); // TODO debug g_message(" ---{%s}", Glib::build_filename( baseParts ).c_str()); - while ( !exists && !current.empty() ) { + while (!exists && !current.empty()) { std::vector combined; - combined.insert( combined.end(), baseParts.begin(), baseParts.end() ); - combined.insert( combined.end(), current.begin(), current.end() ); - std::string filepath = Glib::build_filename( combined ); + combined.insert(combined.end(), baseParts.begin(), baseParts.end()); + combined.insert(combined.end(), current.begin(), current.end()); + std::string filepath = Glib::build_filename(combined); exists = Glib::file_test(filepath, Glib::FILE_TEST_EXISTS); // TODO debug g_message(" ...[%s] %s", filepath.c_str(), (exists ? "XXX" : "")); - if ( exists ) { + if (exists) { dest = filepath; } - current.erase( current.begin() ); + current.erase(current.begin()); } baseParts.pop_back(); } @@ -418,23 +408,21 @@ bool ResourceManagerImpl::searchUpwards( std::string const &base, std::string co return exists; } +static ResourceManagerImpl *theInstance = nullptr; -static ResourceManagerImpl* theInstance = nullptr; - -ResourceManager::ResourceManager() -= default; +ResourceManager::ResourceManager() = default; ResourceManager::~ResourceManager() = default; -ResourceManager& ResourceManager::getManager() { - if ( !theInstance ) { +ResourceManager &ResourceManager::getManager() +{ + if (!theInstance) { theInstance = new ResourceManagerImpl(); } return *theInstance; } - } // namespace Inkscape /* diff --git a/src/io/resource-manager.h b/src/io/resource-manager.h index 7c1e242d4ff89a61162c4f949bf8c7c660e5a019..79030097641ede7beae57f24a40d0b5b458ae0f3 100644 --- a/src/io/resource-manager.h +++ b/src/io/resource-manager.h @@ -14,10 +14,10 @@ class SPDocument; namespace Inkscape { -class ResourceManager { - +class ResourceManager +{ public: - static ResourceManager& getManager(); + static ResourceManager &getManager(); virtual bool fixupBrokenLinks(SPDocument *doc) = 0; @@ -27,11 +27,9 @@ protected: private: ResourceManager(ResourceManager const &) = delete; // no copy - void operator=(ResourceManager const &) = delete; // no assign + void operator=(ResourceManager const &) = delete; // no assign }; - - } // namespace Inkscape #endif // SEEN_INKSCAPE_RESOURCE_MANAGER_H diff --git a/src/io/resource.cpp b/src/io/resource.cpp index ea73135ed128f3520ae898504b98c174d8ae4a8e..05c3f25a81e0184925beed43ba9bd0af1a9bf027 100644 --- a/src/io/resource.cpp +++ b/src/io/resource.cpp @@ -11,7 +11,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef _WIN32 @@ -19,14 +19,14 @@ #endif #include +#include #include #include #include -#include -#include "path-prefix.h" -#include "io/sys.h" #include "io/resource.h" +#include "io/sys.h" +#include "path-prefix.h" using Inkscape::IO::file_test; @@ -49,14 +49,14 @@ gchar *_get_path(Domain domain, Type type, char const *filename) { if (domain == USER) { switch (type) { - case ATTRIBUTES: - case EXAMPLES: - case DOCS: - case SCREENS: - case TUTORIALS: - // Happens for example with `get_filename_string(SCREENS, ...)` - // but we don't want a user configurable about screen. - return nullptr; + case ATTRIBUTES: + case EXAMPLES: + case DOCS: + case SCREENS: + case TUTORIALS: + // Happens for example with `get_filename_string(SCREENS, ...)` + // but we don't want a user configurable about screen. + return nullptr; } } @@ -67,9 +67,14 @@ gchar *_get_path(Domain domain, Type type, char const *filename) case CREATE: { sysdir = "create"; switch (type) { - case PAINT: name = "paint"; break; - case PALETTES: name = "swatches"; break; - default: return nullptr; + case PAINT: + name = "paint"; + break; + case PALETTES: + name = "swatches"; + break; + default: + return nullptr; } } break; case CACHE: { @@ -81,26 +86,63 @@ gchar *_get_path(Domain domain, Type type, char const *filename) sysdir = "inkscape"; case USER: { switch (type) { - case ATTRIBUTES: name = "attributes"; break; - case DOCS: name = "doc"; break; - case EXAMPLES: name = "examples"; break; - case EXTENSIONS: name = "extensions"; break; - case FILTERS: name = "filters"; break; - case FONTS: name = "fonts"; break; - case ICONS: name = "icons"; break; - case KEYS: name = "keys"; break; - case MARKERS: name = "markers"; break; - case PAINT: name = "paint"; break; - case PALETTES: name = "palettes"; break; - case SCREENS: name = "screens"; break; - case SYMBOLS: name = "symbols"; break; - case TEMPLATES: name = "templates"; break; - case THEMES: name = "themes"; break; - case TUTORIALS: name = "tutorials"; break; - case UIS: name = "ui"; break; - case PIXMAPS: name = "pixmaps"; break; - default: g_assert_not_reached(); - return nullptr; + case ATTRIBUTES: + name = "attributes"; + break; + case DOCS: + name = "doc"; + break; + case EXAMPLES: + name = "examples"; + break; + case EXTENSIONS: + name = "extensions"; + break; + case FILTERS: + name = "filters"; + break; + case FONTS: + name = "fonts"; + break; + case ICONS: + name = "icons"; + break; + case KEYS: + name = "keys"; + break; + case MARKERS: + name = "markers"; + break; + case PAINT: + name = "paint"; + break; + case PALETTES: + name = "palettes"; + break; + case SCREENS: + name = "screens"; + break; + case SYMBOLS: + name = "symbols"; + break; + case TEMPLATES: + name = "templates"; + break; + case THEMES: + name = "themes"; + break; + case TUTORIALS: + name = "tutorials"; + break; + case UIS: + name = "ui"; + break; + case PIXMAPS: + name = "pixmaps"; + break; + default: + g_assert_not_reached(); + return nullptr; } } break; } @@ -116,12 +158,10 @@ gchar *_get_path(Domain domain, Type type, char const *filename) } } - - Util::ptr_shared get_path(Domain domain, Type type, char const *filename) { char *path = _get_path(domain, type, filename); - Util::ptr_shared result=Util::share_string(path); + Util::ptr_shared result = Util::share_string(path); g_free(path); return result; } @@ -129,9 +169,9 @@ Glib::ustring get_path_ustring(Domain domain, Type type, char const *filename) { Glib::ustring result; char *path = _get_path(domain, type, filename); - if(path) { - result = Glib::ustring(path); - g_free(path); + if (path) { + result = Glib::ustring(path); + g_free(path); } return result; } @@ -155,7 +195,7 @@ std::string get_path_string(Domain domain, Type type, char const *filename) * localized - Prefer a localized version of the file, i.e. default.de.svg instead of default.svg. * (will use gettext to determine the preferred language of the user) * silent - do not warn if file doesnt exist - * + * */ Glib::ustring get_filename(Type type, char const *filename, bool localized, bool silent) { @@ -202,11 +242,11 @@ std::string get_filename_string(Type type, char const *filename, bool localized, g_info("Found resource file '%s' in system directory:\n\t%s", filename, result.c_str()); } else if (!silent) { if (localized) { - g_warning("Failed to find resource file '%s'. Looked in:\n\t%s\n\t%s\n\t%s\n\t%s", - filename, user_filename_localized, user_filename, sys_filename_localized, sys_filename); + g_warning("Failed to find resource file '%s'. Looked in:\n\t%s\n\t%s\n\t%s\n\t%s", filename, + user_filename_localized, user_filename, sys_filename_localized, sys_filename); } else { - g_warning("Failed to find resource file '%s'. Looked in:\n\t%s\n\t%s", - filename, user_filename, sys_filename); + g_warning("Failed to find resource file '%s'. Looked in:\n\t%s\n\t%s", filename, user_filename, + sys_filename); } } @@ -230,7 +270,7 @@ Glib::ustring get_filename(Glib::ustring path, Glib::ustring filename) Glib::filename_from_utf8(filename)); } -std::string get_filename(std::string const& path, std::string const& filename) +std::string get_filename(std::string const &path, std::string const &filename) { // Test if it's a filename and get the parent directory instead if (Glib::file_test(path, Glib::FILE_TEST_IS_REGULAR)) { @@ -259,7 +299,8 @@ std::string get_filename(std::string const& path, std::string const& filename) * extensions - A list of extensions to return, e.g. xml, svg * exclusions - A list of names to exclude e.g. default.xml */ -std::vector get_filenames(Type type, std::vector extensions, std::vector exclusions) +std::vector get_filenames(Type type, std::vector extensions, + std::vector exclusions) { std::vector ret; get_filenames_from_path(ret, get_path_string(USER, type), extensions, exclusions); @@ -268,13 +309,15 @@ std::vector get_filenames(Type type, std::vector ex return ret; } -std::vector get_filenames(Domain domain, Type type, std::vector extensions, std::vector exclusions) +std::vector get_filenames(Domain domain, Type type, std::vector extensions, + std::vector exclusions) { std::vector ret; get_filenames_from_path(ret, get_path_string(domain, type), extensions, exclusions); return ret; } -std::vector get_filenames(Glib::ustring path, std::vector extensions, std::vector exclusions) +std::vector get_filenames(Glib::ustring path, std::vector extensions, + std::vector exclusions) { std::vector ret; get_filenames_from_path(ret, Glib::filename_from_utf8(path), extensions, exclusions); @@ -311,7 +354,6 @@ std::vector get_foldernames(Glib::ustring path, std::vector get_foldernames(Glib::ustring path, std::vector &files, std::string const &path, std::vector const &extensions, std::vector const &exclusions) { - if(!Glib::file_test(path, Glib::FILE_TEST_IS_DIR)) { + if (!Glib::file_test(path, Glib::FILE_TEST_IS_DIR)) { return; } Glib::Dir dir(path); std::string file = dir.read_name(); - while (!file.empty()){ + while (!file.empty()) { // If not extensions are specified, don't reject ANY files. bool reject = !extensions.empty(); // Unreject any file which has one of the extensions. - for (auto &ext: extensions) { - reject ^= Glib::str_has_suffix(file, ext); + for (auto &ext : extensions) { + reject ^= Glib::str_has_suffix(file, ext); } // Reject any file which matches the exclusions. - for (auto &exc: exclusions) { - reject |= Glib::str_has_prefix(file, exc); + for (auto &exc : exclusions) { + reject |= Glib::str_has_prefix(file, exc); } // Reject any filename which isn't a regular file auto filename = Glib::build_filename(path, file); - if(Glib::file_test(filename, Glib::FILE_TEST_IS_DIR)) { + if (Glib::file_test(filename, Glib::FILE_TEST_IS_DIR)) { get_filenames_from_path(files, filename, extensions, exclusions); - } else if(Glib::file_test(filename, Glib::FILE_TEST_IS_REGULAR) && !reject) { + } else if (Glib::file_test(filename, Glib::FILE_TEST_IS_REGULAR) && !reject) { files.push_back(Glib::filename_to_utf8(filename)); } file = dir.read_name(); @@ -396,7 +438,6 @@ void get_foldernames_from_path(std::vector &folders, std::string } } - /** * Get, or guess, or decide the location where the preferences.xml * file should be located. This also indicates where all other inkscape @@ -424,22 +465,22 @@ char const *profile_path() // should we migrate to AppData\Local? Then we can simply use the portable g_get_user_config_dir() if (!prefdir) { ITEMIDLIST *pidl = 0; - if ( SHGetFolderLocation( NULL, CSIDL_APPDATA, NULL, 0, &pidl ) == S_OK ) { - gchar * utf8Path = NULL; + if (SHGetFolderLocation(NULL, CSIDL_APPDATA, NULL, 0, &pidl) == S_OK) { + gchar *utf8Path = NULL; { - wchar_t pathBuf[MAX_PATH+1]; + wchar_t pathBuf[MAX_PATH + 1]; g_assert(sizeof(wchar_t) == sizeof(gunichar2)); - if ( SHGetPathFromIDListW( pidl, pathBuf ) ) { - utf8Path = g_utf16_to_utf8( (gunichar2*)(&pathBuf[0]), -1, NULL, NULL, NULL ); + if (SHGetPathFromIDListW(pidl, pathBuf)) { + utf8Path = g_utf16_to_utf8((gunichar2 *)(&pathBuf[0]), -1, NULL, NULL, NULL); } } - if ( utf8Path ) { + if (utf8Path) { if (!g_utf8_validate(utf8Path, -1, NULL)) { - g_warning( "SHGetPathFromIDListW() resulted in invalid UTF-8"); - g_free( utf8Path ); + g_warning("SHGetPathFromIDListW() resulted in invalid UTF-8"); + g_free(utf8Path); utf8Path = 0; } else { prefdir = utf8Path; @@ -467,13 +508,13 @@ char const *profile_path() #ifdef S_IXOTH mode |= S_IXOTH; #endif - if ( g_mkdir_with_parents(prefdir, mode) == -1 ) { + if (g_mkdir_with_parents(prefdir, mode) == -1) { int problem = errno; g_warning("Unable to create profile directory (%s) (%d)", g_strerror(problem), problem); } else { - gchar const *userDirs[] = { "keys", "templates", "icons", "extensions", "ui", - "symbols", "paint", "themes", "palettes", nullptr }; - for (gchar const** name = userDirs; *name; ++name) { + gchar const *userDirs[] = {"keys", "templates", "icons", "extensions", "ui", + "symbols", "paint", "themes", "palettes", nullptr}; + for (gchar const **name = userDirs; *name; ++name) { gchar *dir = g_build_filename(prefdir, *name, NULL); g_mkdir_with_parents(dir, mode); g_free(dir); @@ -501,11 +542,11 @@ char *homedir_path(const char *filename) return g_build_filename(homedir, filename, NULL); } -} +} // namespace Resource -} +} // namespace IO -} +} // namespace Inkscape /* Local Variables: diff --git a/src/io/resource.h b/src/io/resource.h index 454ab1a7152a2a4d20671b141f114ded2f50623a..a426ad8fdf9943e184ed2891a2166c6c0ebee102 100644 --- a/src/io/resource.h +++ b/src/io/resource.h @@ -13,8 +13,9 @@ #ifndef SEEN_INKSCAPE_IO_RESOURCE_H #define SEEN_INKSCAPE_IO_RESOURCE_H -#include #include +#include + #include "util/share.h" namespace Inkscape { @@ -26,7 +27,8 @@ namespace IO { */ namespace Resource { -enum Type { +enum Type +{ ATTRIBUTES, EXAMPLES, EXTENSIONS, @@ -48,41 +50,37 @@ enum Type { DOCS }; -enum Domain { +enum Domain +{ SYSTEM, CREATE, CACHE, USER }; -Util::ptr_shared get_path(Domain domain, Type type, - char const *filename=nullptr); +Util::ptr_shared get_path(Domain domain, Type type, char const *filename = nullptr); -Glib::ustring get_path_ustring(Domain domain, Type type, - char const *filename=nullptr); +Glib::ustring get_path_ustring(Domain domain, Type type, char const *filename = nullptr); std::string get_path_string(Domain domain, Type type, char const *filename = nullptr); std::string get_filename_string(Type type, char const *filename, bool localized = false, bool silent = false); Glib::ustring get_filename(Type type, char const *filename, bool localized = false, bool silent = false); // TODO consolidate with Glib::StdStringView Glib::ustring get_filename(Glib::ustring path, Glib::ustring filename); -std::string get_filename(std::string const& path, std::string const& filename); +std::string get_filename(std::string const &path, std::string const &filename); inline std::string get_filename(const char *path, const char *filename) { return get_filename(std::string(path), std::string(filename)); } -std::vector get_filenames(Type type, - std::vector extensions={}, - std::vector exclusions={}); +std::vector get_filenames(Type type, std::vector extensions = {}, + std::vector exclusions = {}); -std::vector get_filenames(Domain domain, Type type, - std::vector extensions={}, - std::vector exclusions={}); +std::vector get_filenames(Domain domain, Type type, std::vector extensions = {}, + std::vector exclusions = {}); -std::vector get_filenames(Glib::ustring path, - std::vector extensions={}, - std::vector exclusions={}); +std::vector get_filenames(Glib::ustring path, std::vector extensions = {}, + std::vector exclusions = {}); std::vector get_foldernames(Type type, std::vector exclusions = {}); @@ -93,17 +91,16 @@ std::vector get_foldernames(Glib::ustring path, std::vector &files, Glib::ustring path, std::vector exclusions = {}); - char const *profile_path(); char *profile_path(const char *filename); char *homedir_path(const char *filename); char *log_path(const char *filename); -} +} // namespace Resource -} +} // namespace IO -} +} // namespace Inkscape #endif /* diff --git a/src/io/stream/bufferstream.cpp b/src/io/stream/bufferstream.cpp index 1723ee1ff232963f371ee4c2ab9354184eb01d72..b764f79823e96c5f31036b5d79f033656e11d83e 100644 --- a/src/io/stream/bufferstream.cpp +++ b/src/io/stream/bufferstream.cpp @@ -23,10 +23,8 @@ #include "bufferstream.h" -namespace Inkscape -{ -namespace IO -{ +namespace Inkscape { +namespace IO { //######################################################################### //# B U F F E R I N P U T S T R E A M @@ -34,9 +32,8 @@ namespace IO /** * */ -BufferInputStream::BufferInputStream( - const std::vector &sourceBuffer) - : buffer(sourceBuffer) +BufferInputStream::BufferInputStream(const std::vector &sourceBuffer) + : buffer(sourceBuffer) { position = 0; closed = false; @@ -45,8 +42,7 @@ BufferInputStream::BufferInputStream( /** * */ -BufferInputStream::~BufferInputStream() -= default; +BufferInputStream::~BufferInputStream() = default; /** * Returns the number of bytes that can be read (or skipped over) from @@ -60,7 +56,6 @@ int BufferInputStream::available() return buffer.size() - position; } - /** * Closes this input stream and releases any system resources * associated with the stream. @@ -79,13 +74,10 @@ int BufferInputStream::get() return -1; if (position >= (int)buffer.size()) return -1; - int ch = (int) buffer[position++]; + int ch = (int)buffer[position++]; return ch; } - - - //######################################################################### //# B U F F E R O U T P U T S T R E A M //######################################################################### @@ -101,8 +93,7 @@ BufferOutputStream::BufferOutputStream() /** * */ -BufferOutputStream::~BufferOutputStream() -= default; +BufferOutputStream::~BufferOutputStream() = default; /** * Closes this output stream and releases any system resources @@ -119,7 +110,7 @@ void BufferOutputStream::close() */ void BufferOutputStream::flush() { - //nothing to do + // nothing to do } /** @@ -133,11 +124,8 @@ int BufferOutputStream::put(char ch) return 1; } - - - -} //namespace IO -} //namespace Inkscape +} // namespace IO +} // namespace Inkscape //######################################################################### //# E N D O F F I L E diff --git a/src/io/stream/bufferstream.h b/src/io/stream/bufferstream.h index 811ab0d574e2fdd469981bf95d5360ee74f327f8..b87aa099b508c91bab54794880bad275a52b75b8 100644 --- a/src/io/stream/bufferstream.h +++ b/src/io/stream/bufferstream.h @@ -19,15 +19,12 @@ #ifndef SEEN_BUFFERSTREAM_H #define SEEN_BUFFERSTREAM_H - #include -#include "inkscapestream.h" +#include "inkscapestream.h" -namespace Inkscape -{ -namespace IO -{ +namespace Inkscape { +namespace IO { //######################################################################### //# S T R I N G I N P U T S T R E A M @@ -39,9 +36,7 @@ namespace IO */ class BufferInputStream : public InputStream { - public: - BufferInputStream(const std::vector &sourceBuffer); ~BufferInputStream() override; int available() override; @@ -55,9 +50,6 @@ private: }; // class BufferInputStream - - - //######################################################################### //# B U F F E R O U T P U T S T R E A M //######################################################################### @@ -68,19 +60,15 @@ private: */ class BufferOutputStream : public OutputStream { - public: - BufferOutputStream(); ~BufferOutputStream() override; void close() override; void flush() override; int put(char ch) override; - virtual std::vector &getBuffer() - { return buffer; } + virtual std::vector &getBuffer() { return buffer; } - virtual void clear() - { buffer.clear(); } + virtual void clear() { buffer.clear(); } private: std::vector buffer; @@ -88,11 +76,7 @@ private: }; // class BufferOutputStream - - -} //namespace IO -} //namespace Inkscape - - +} // namespace IO +} // namespace Inkscape #endif // SEEN_BUFFERSTREAM_H diff --git a/src/io/stream/gzipstream.cpp b/src/io/stream/gzipstream.cpp index 03960b004ae34cecbc33b489b522cd667eb5ca62..1a39f57c0bcab331b6ad97719dca6a7eb51e895c 100644 --- a/src/io/stream/gzipstream.cpp +++ b/src/io/stream/gzipstream.cpp @@ -17,15 +17,14 @@ */ #include "gzipstream.h" + #include #include #include #include -namespace Inkscape -{ -namespace IO -{ +namespace Inkscape { +namespace IO { //######################################################################### //# G Z I P I N P U T S T R E A M @@ -35,36 +34,36 @@ namespace IO /** * - */ + */ GzipInputStream::GzipInputStream(InputStream &sourceStream) - : BasicInputStream(sourceStream), - loaded(false), - totalIn(0), - totalOut(0), - outputBuf(nullptr), - srcBuf(nullptr), - crc(0), - srcCrc(0), - srcSiz(0), - srcConsumed(0), - srcLen(0), - outputBufPos(0), - outputBufLen(0) + : BasicInputStream(sourceStream) + , loaded(false) + , totalIn(0) + , totalOut(0) + , outputBuf(nullptr) + , srcBuf(nullptr) + , crc(0) + , srcCrc(0) + , srcSiz(0) + , srcConsumed(0) + , srcLen(0) + , outputBufPos(0) + , outputBufLen(0) { - memset( &d_stream, 0, sizeof(d_stream) ); + memset(&d_stream, 0, sizeof(d_stream)); } /** * - */ + */ GzipInputStream::~GzipInputStream() { close(); - if ( srcBuf ) { - delete[] srcBuf; - srcBuf = nullptr; + if (srcBuf) { + delete[] srcBuf; + srcBuf = nullptr; } - if ( outputBuf ) { + if (outputBuf) { delete[] outputBuf; outputBuf = nullptr; } @@ -74,7 +73,7 @@ GzipInputStream::~GzipInputStream() * Returns the number of bytes that can be read (or skipped over) from * this input stream without blocking by the next caller of a method for * this input stream. - */ + */ int GzipInputStream::available() { if (closed || !outputBuf) @@ -82,11 +81,10 @@ int GzipInputStream::available() return outputBufLen - outputBufPos; } - /** * Closes this input stream and releases any system resources * associated with the stream. - */ + */ void GzipInputStream::close() { if (closed) @@ -97,37 +95,36 @@ void GzipInputStream::close() printf("inflateEnd: Some kind of problem: %d\n", zerr); } - if ( srcBuf ) { - delete[] srcBuf; - srcBuf = nullptr; + if (srcBuf) { + delete[] srcBuf; + srcBuf = nullptr; } - if ( outputBuf ) { + if (outputBuf) { delete[] outputBuf; outputBuf = nullptr; } closed = true; } - + /** * Reads the next byte of data from the input stream. -1 if EOF - */ + */ int GzipInputStream::get() { int ch = -1; if (closed) { // leave return value -1 - } - else if (!loaded && !load()) { - closed=true; + } else if (!loaded && !load()) { + closed = true; } else { loaded = true; - if ( outputBufPos >= outputBufLen ) { + if (outputBufPos >= outputBufLen) { // time to read more, if we can fetchMore(); } - if ( outputBufPos < outputBufLen ) { + if (outputBufPos < outputBufLen) { ch = (int)outputBuf[outputBufPos++]; } } @@ -144,30 +141,29 @@ int GzipInputStream::get() bool GzipInputStream::load() { crc = crc32(0L, Z_NULL, 0); - + std::vector inputBuf; - while (true) - { + while (true) { int ch = source.get(); - if (ch<0) + if (ch < 0) break; inputBuf.push_back(static_cast(ch & 0xff)); - } + } long inputBufLen = inputBuf.size(); - - if (inputBufLen < 19) //header + tail + 1 - { + + if (inputBufLen < 19) // header + tail + 1 + { return false; - } + } srcLen = inputBuf.size(); - srcBuf = new (std::nothrow) Byte [srcLen]; + srcBuf = new (std::nothrow) Byte[srcLen]; if (!srcBuf) { return false; } - outputBuf = new (std::nothrow) unsigned char [OUT_SIZE]; - if ( !outputBuf ) { + outputBuf = new (std::nothrow) unsigned char[OUT_SIZE]; + if (!outputBuf) { delete[] srcBuf; srcBuf = nullptr; return false; @@ -176,110 +172,100 @@ bool GzipInputStream::load() std::vector::iterator iter; Bytef *p = srcBuf; - for (iter=inputBuf.begin() ; iter != inputBuf.end() ; ++iter) - { + for (iter = inputBuf.begin(); iter != inputBuf.end(); ++iter) { *p++ = *iter; - } + } int headerLen = 10; - //Magic - //int val = (int)srcBuf[0]; + // Magic + // int val = (int)srcBuf[0]; ////printf("val:%x\n", val); - //val = (int)srcBuf[1]; + // val = (int)srcBuf[1]; ////printf("val:%x\n", val); ////Method - //val = (int)srcBuf[2]; + // val = (int)srcBuf[2]; ////printf("val:%x\n", val); - //flags + // flags int flags = static_cast(srcBuf[3]); ////time - //val = (int)srcBuf[4]; - //val = (int)srcBuf[5]; - //val = (int)srcBuf[6]; - //val = (int)srcBuf[7]; + // val = (int)srcBuf[4]; + // val = (int)srcBuf[5]; + // val = (int)srcBuf[6]; + // val = (int)srcBuf[7]; ////xflags - //val = (int)srcBuf[8]; + // val = (int)srcBuf[8]; ////OS - //val = (int)srcBuf[9]; - -// if ( flags & FEXTRA ) { -// headerLen += 2; -// int xlen = -// TODO deal with optional header parts -// } - if ( flags & FNAME ) { + // val = (int)srcBuf[9]; + + // if ( flags & FEXTRA ) { + // headerLen += 2; + // int xlen = + // TODO deal with optional header parts + // } + if (flags & FNAME) { int cur = 10; - while ( srcBuf[cur] ) - { + while (srcBuf[cur]) { cur++; headerLen++; } headerLen++; } + srcCrc = ((0x0ff & srcBuf[srcLen - 5]) << 24) | ((0x0ff & srcBuf[srcLen - 6]) << 16) | + ((0x0ff & srcBuf[srcLen - 7]) << 8) | ((0x0ff & srcBuf[srcLen - 8]) << 0); + // printf("srcCrc:%lx\n", srcCrc); + + srcSiz = ((0x0ff & srcBuf[srcLen - 1]) << 24) | ((0x0ff & srcBuf[srcLen - 2]) << 16) | + ((0x0ff & srcBuf[srcLen - 3]) << 8) | ((0x0ff & srcBuf[srcLen - 4]) << 0); + // printf("srcSiz:%lx/%ld\n", srcSiz, srcSiz); + + // outputBufLen = srcSiz + srcSiz/100 + 14; - srcCrc = ((0x0ff & srcBuf[srcLen - 5]) << 24) - | ((0x0ff & srcBuf[srcLen - 6]) << 16) - | ((0x0ff & srcBuf[srcLen - 7]) << 8) - | ((0x0ff & srcBuf[srcLen - 8]) << 0); - //printf("srcCrc:%lx\n", srcCrc); - - srcSiz = ((0x0ff & srcBuf[srcLen - 1]) << 24) - | ((0x0ff & srcBuf[srcLen - 2]) << 16) - | ((0x0ff & srcBuf[srcLen - 3]) << 8) - | ((0x0ff & srcBuf[srcLen - 4]) << 0); - //printf("srcSiz:%lx/%ld\n", srcSiz, srcSiz); - - //outputBufLen = srcSiz + srcSiz/100 + 14; - unsigned char *data = srcBuf + headerLen; unsigned long dataLen = srcLen - (headerLen + 8); - //printf("%x %x\n", data[0], data[dataLen-1]); - - d_stream.zalloc = (alloc_func)nullptr; - d_stream.zfree = (free_func)nullptr; - d_stream.opaque = (voidpf)nullptr; - d_stream.next_in = data; - d_stream.avail_in = dataLen; - d_stream.next_out = outputBuf; + // printf("%x %x\n", data[0], data[dataLen-1]); + + d_stream.zalloc = (alloc_func) nullptr; + d_stream.zfree = (free_func) nullptr; + d_stream.opaque = (voidpf) nullptr; + d_stream.next_in = data; + d_stream.avail_in = dataLen; + d_stream.next_out = outputBuf; d_stream.avail_out = OUT_SIZE; - + int zerr = inflateInit2(&d_stream, -MAX_WBITS); - if ( zerr == Z_OK ) - { + if (zerr == Z_OK) { zerr = fetchMore(); } else { printf("inflateInit2: Some kind of problem: %d\n", zerr); } - return (zerr == Z_OK) || (zerr == Z_STREAM_END); } - int GzipInputStream::fetchMore() { // TODO assumes we aren't called till the buffer is empty - d_stream.next_out = outputBuf; + d_stream.next_out = outputBuf; d_stream.avail_out = OUT_SIZE; outputBufLen = 0; outputBufPos = 0; - int zerr = inflate( &d_stream, Z_SYNC_FLUSH ); - if ( zerr == Z_OK || zerr == Z_STREAM_END ) { + int zerr = inflate(&d_stream, Z_SYNC_FLUSH); + if (zerr == Z_OK || zerr == Z_STREAM_END) { outputBufLen = OUT_SIZE - d_stream.avail_out; - if ( outputBufLen ) { + if (outputBufLen) { crc = crc32(crc, const_cast(outputBuf), outputBufLen); } - //printf("crc:%lx\n", crc); -// } else if ( zerr != Z_STREAM_END ) { -// // TODO check to be sure this won't happen for partial end reads -// printf("inflate: Some kind of problem: %d\n", zerr); + // printf("crc:%lx\n", crc); + // } else if ( zerr != Z_STREAM_END ) { + // // TODO check to be sure this won't happen for partial end reads + // printf("inflate: Some kind of problem: %d\n", zerr); } return zerr; @@ -291,44 +277,42 @@ int GzipInputStream::fetchMore() /** * - */ + */ GzipOutputStream::GzipOutputStream(OutputStream &destinationStream) - : BasicOutputStream(destinationStream) + : BasicOutputStream(destinationStream) { + totalIn = 0; + totalOut = 0; + crc = crc32(0L, Z_NULL, 0); - totalIn = 0; - totalOut = 0; - crc = crc32(0L, Z_NULL, 0); - - //Gzip header + // Gzip header destination.put(0x1f); destination.put(0x8b); - //Say it is compressed + // Say it is compressed destination.put(Z_DEFLATED); - //flags + // flags destination.put(0); - //time + // time destination.put(0); destination.put(0); destination.put(0); destination.put(0); - //xflags + // xflags destination.put(0); - //OS code - from zutil.h - //destination.put(OS_CODE); - //apparently, we should not explicitly include zutil.h + // OS code - from zutil.h + // destination.put(OS_CODE); + // apparently, we should not explicitly include zutil.h destination.put(0); - } /** * - */ + */ GzipOutputStream::~GzipOutputStream() { close(); @@ -337,7 +321,7 @@ GzipOutputStream::~GzipOutputStream() /** * Closes this output stream and releases any system resources * associated with this stream. - */ + */ void GzipOutputStream::close() { if (closed) @@ -347,69 +331,62 @@ void GzipOutputStream::close() //# Send the CRC uLong outlong = crc; - for (int n = 0; n < 4; n++) - { + for (int n = 0; n < 4; n++) { destination.put(static_cast(outlong & 0xff)); outlong >>= 8; - } + } //# send the file length outlong = totalIn & 0xffffffffL; - for (int n = 0; n < 4; n++) - { + for (int n = 0; n < 4; n++) { destination.put(static_cast(outlong & 0xff)); outlong >>= 8; - } + } destination.close(); closed = true; } - + /** * Flushes this output stream and forces any buffered output * bytes to be written out. - */ + */ void GzipOutputStream::flush() { - if (closed || inputBuf.empty()) - { + if (closed || inputBuf.empty()) { return; } - + uLong srclen = inputBuf.size(); - Bytef *srcbuf = new (std::nothrow) Bytef [srclen]; - if (!srcbuf) - { + Bytef *srcbuf = new (std::nothrow) Bytef[srclen]; + if (!srcbuf) { return; - } - + } + uLong destlen = srclen; - Bytef *destbuf = new (std::nothrow) Bytef [(destlen + (srclen/100) + 13)]; - if (!destbuf) - { + Bytef *destbuf = new (std::nothrow) Bytef[(destlen + (srclen / 100) + 13)]; + if (!destbuf) { delete[] srcbuf; return; - } - + } + std::vector::iterator iter; Bytef *p = srcbuf; - for (iter=inputBuf.begin() ; iter != inputBuf.end() ; ++iter) + for (iter = inputBuf.begin(); iter != inputBuf.end(); ++iter) *p++ = *iter; - + crc = crc32(crc, const_cast(srcbuf), srclen); - + int zerr = compress(destbuf, static_cast(&destlen), srcbuf, srclen); - if (zerr != Z_OK) - { + if (zerr != Z_OK) { printf("Some kind of problem\n"); - } + } totalOut += destlen; - //skip the redundant zlib header and checksum - for (uLong i=2; i -#include "inkscapestream.h" #include -namespace Inkscape -{ -namespace IO -{ +#include "inkscapestream.h" + +namespace Inkscape { +namespace IO { //######################################################################### //# G Z I P I N P U T S T R E A M @@ -37,26 +36,23 @@ namespace IO */ class GzipInputStream : public BasicInputStream { - public: - GzipInputStream(InputStream &sourceStream); - + ~GzipInputStream() override; - + int available() override; - + void close() override; - + int get() override; - -private: +private: bool load(); int fetchMore(); bool loaded; - + long totalIn; long totalOut; @@ -74,9 +70,6 @@ private: z_stream d_stream; }; // class GzipInputStream - - - //######################################################################### //# G Z I P O U T P U T S T R E A M //######################################################################### @@ -88,21 +81,18 @@ private: */ class GzipOutputStream : public BasicOutputStream { - public: - GzipOutputStream(OutputStream &destinationStream); - + ~GzipOutputStream() override; - + void close() override; - + void flush() override; - + int put(char ch) override; private: - std::vector inputBuf; long totalIn; @@ -111,14 +101,7 @@ private: }; // class GzipOutputStream - - - - - - } // namespace IO } // namespace Inkscape - #endif /* __INKSCAPE_IO_GZIPSTREAM_H__ */ diff --git a/src/io/stream/inkscapestream.cpp b/src/io/stream/inkscapestream.cpp index bc6dc1d7fe83288ddd2c07de728deb9ecf0aa1ff..0a3c1ecea2b918ca8a1b11876ffac575d6c4e293 100644 --- a/src/io/stream/inkscapestream.cpp +++ b/src/io/stream/inkscapestream.cpp @@ -12,13 +12,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "inkscapestream.h" -namespace Inkscape -{ -namespace IO -{ +#include + +namespace Inkscape { +namespace IO { //######################################################################### //# U T I L I T Y @@ -26,13 +25,12 @@ namespace IO void pipeStream(InputStream &source, OutputStream &dest) { - for (;;) - { + for (;;) { int ch = source.get(); - if (ch<0) + if (ch < 0) break; dest.put(ch); - } + } dest.flush(); } @@ -40,12 +38,11 @@ void pipeStream(InputStream &source, OutputStream &dest) //# B A S I C I N P U T S T R E A M //######################################################################### - /** * - */ + */ BasicInputStream::BasicInputStream(InputStream &sourceStream) - : source(sourceStream) + : source(sourceStream) { closed = false; } @@ -54,7 +51,7 @@ BasicInputStream::BasicInputStream(InputStream &sourceStream) * Returns the number of bytes that can be read (or skipped over) from * this input stream without blocking by the next caller of a method for * this input stream. - */ + */ int BasicInputStream::available() { if (closed) @@ -62,11 +59,10 @@ int BasicInputStream::available() return source.available(); } - /** * Closes this input stream and releases any system resources * associated with the stream. - */ + */ void BasicInputStream::close() { if (closed) @@ -74,18 +70,16 @@ void BasicInputStream::close() source.close(); closed = true; } - + /** * Reads the next byte of data from the input stream. -1 if EOF - */ + */ int BasicInputStream::get() { if (closed) return -1; return source.get(); } - - //######################################################################### //# B A S I C O U T P U T S T R E A M @@ -93,9 +87,9 @@ int BasicInputStream::get() /** * - */ + */ BasicOutputStream::BasicOutputStream(OutputStream &destinationStream) - : destination(destinationStream) + : destination(destinationStream) { closed = false; } @@ -103,7 +97,7 @@ BasicOutputStream::BasicOutputStream(OutputStream &destinationStream) /** * Closes this output stream and releases any system resources * associated with this stream. - */ + */ void BasicOutputStream::close() { if (closed) @@ -111,21 +105,21 @@ void BasicOutputStream::close() destination.close(); closed = true; } - + /** * Flushes this output stream and forces any buffered output * bytes to be written out. - */ + */ void BasicOutputStream::flush() { if (closed) return; destination.flush(); } - + /** * Writes the specified byte to this output stream. - */ + */ int BasicOutputStream::put(char ch) { if (closed) @@ -134,14 +128,12 @@ int BasicOutputStream::put(char ch) return 1; } - - //######################################################################### //# B A S I C R E A D E R //######################################################################### /** * - */ + */ BasicReader::BasicReader(Reader &sourceReader) { source = &sourceReader; @@ -151,7 +143,7 @@ BasicReader::BasicReader(Reader &sourceReader) * Returns the number of bytes that can be read (or skipped over) from * this reader without blocking by the next caller of a method for * this reader. - */ + */ int BasicReader::available() { if (source) @@ -160,20 +152,19 @@ int BasicReader::available() return 0; } - /** * Closes this reader and releases any system resources * associated with the reader. - */ + */ void BasicReader::close() { if (source) source->close(); } - + /** * Reads the next byte of data from the reader. - */ + */ char BasicReader::get() { if (source) @@ -181,40 +172,36 @@ char BasicReader::get() else return (char)-1; } - /** * Reads a line of data from the reader. - */ + */ Glib::ustring BasicReader::readLine() { Glib::ustring str; - while (available() > 0) - { + while (available() > 0) { char ch = get(); if (ch == '\n') break; str.push_back(ch); - } + } return str; } - + /** * Reads a line of data from the reader. - */ + */ Glib::ustring BasicReader::readWord() { Glib::ustring str; - while (available() > 0) - { + while (available() > 0) { char ch = get(); if (!std::isprint(ch)) break; str.push_back(ch); - } + } return str; } - static bool getLong(Glib::ustring &str, long *val) { @@ -249,9 +236,7 @@ static bool getDouble(Glib::ustring &str, double *val) return true; } - - -const Reader &BasicReader::readBool (bool& val ) +const Reader &BasicReader::readBool(bool &val) { Glib::ustring buf = readWord(); if (buf == "true") @@ -261,43 +246,43 @@ const Reader &BasicReader::readBool (bool& val ) return *this; } -const Reader &BasicReader::readShort (short& val ) +const Reader &BasicReader::readShort(short &val) { Glib::ustring buf = readWord(); long ival; if (getLong(buf, &ival)) - val = (short) ival; + val = (short)ival; return *this; } -const Reader &BasicReader::readUnsignedShort (unsigned short& val ) +const Reader &BasicReader::readUnsignedShort(unsigned short &val) { Glib::ustring buf = readWord(); unsigned long ival; if (getULong(buf, &ival)) - val = (unsigned short) ival; + val = (unsigned short)ival; return *this; } -const Reader &BasicReader::readInt (int& val ) +const Reader &BasicReader::readInt(int &val) { Glib::ustring buf = readWord(); long ival; if (getLong(buf, &ival)) - val = (int) ival; + val = (int)ival; return *this; } -const Reader &BasicReader::readUnsignedInt (unsigned int& val ) +const Reader &BasicReader::readUnsignedInt(unsigned int &val) { Glib::ustring buf = readWord(); unsigned long ival; if (getULong(buf, &ival)) - val = (unsigned int) ival; + val = (unsigned int)ival; return *this; } -const Reader &BasicReader::readLong (long& val ) +const Reader &BasicReader::readLong(long &val) { Glib::ustring buf = readWord(); long ival; @@ -306,7 +291,7 @@ const Reader &BasicReader::readLong (long& val ) return *this; } -const Reader &BasicReader::readUnsignedLong (unsigned long& val ) +const Reader &BasicReader::readUnsignedLong(unsigned long &val) { Glib::ustring buf = readWord(); unsigned long ival; @@ -315,7 +300,7 @@ const Reader &BasicReader::readUnsignedLong (unsigned long& val ) return *this; } -const Reader &BasicReader::readFloat (float& val ) +const Reader &BasicReader::readFloat(float &val) { Glib::ustring buf = readWord(); double ival; @@ -324,7 +309,7 @@ const Reader &BasicReader::readFloat (float& val ) return *this; } -const Reader &BasicReader::readDouble (double& val ) +const Reader &BasicReader::readDouble(double &val) { Glib::ustring buf = readWord(); double ival; @@ -333,19 +318,13 @@ const Reader &BasicReader::readDouble (double& val ) return *this; } - - //######################################################################### //# I N P U T S T R E A M R E A D E R //######################################################################### - InputStreamReader::InputStreamReader(InputStream &inputStreamSource) - : inputStream(inputStreamSource) -{ -} - - + : inputStream(inputStreamSource) +{} /** * Close the underlying OutputStream @@ -354,7 +333,7 @@ void InputStreamReader::close() { inputStream.close(); } - + /** * Flush the underlying OutputStream */ @@ -362,7 +341,7 @@ int InputStreamReader::available() { return inputStream.available(); } - + /** * Overloaded to receive its bytes from an InputStream * rather than a Reader @@ -373,13 +352,10 @@ char InputStreamReader::get() return ch; } - - //######################################################################### //# S T D R E A D E R //######################################################################### - /** * */ @@ -396,8 +372,6 @@ StdReader::~StdReader() delete inputStream; } - - /** * Close the underlying OutputStream */ @@ -405,7 +379,7 @@ void StdReader::close() { inputStream->close(); } - + /** * Flush the underlying OutputStream */ @@ -413,7 +387,7 @@ int StdReader::available() { return inputStream->available(); } - + /** * Overloaded to receive its bytes from an InputStream * rather than a Reader @@ -424,17 +398,13 @@ char StdReader::get() return ch; } - - - - //######################################################################### //# B A S I C W R I T E R //######################################################################### /** * - */ + */ BasicWriter::BasicWriter(Writer &destinationWriter) { destination = &destinationWriter; @@ -443,26 +413,26 @@ BasicWriter::BasicWriter(Writer &destinationWriter) /** * Closes this writer and releases any system resources * associated with this writer. - */ + */ void BasicWriter::close() { if (destination) destination->close(); } - + /** * Flushes this output stream and forces any buffered output * bytes to be written out. - */ + */ void BasicWriter::flush() { if (destination) destination->flush(); } - + /** * Writes the specified byte to this output writer. - */ + */ void BasicWriter::put(char ch) { if (destination) @@ -471,7 +441,7 @@ void BasicWriter::put(char ch) /** * Provide printf()-like formatting - */ + */ Writer &BasicWriter::printf(char const *fmt, ...) { va_list args; @@ -486,17 +456,16 @@ Writer &BasicWriter::printf(char const *fmt, ...) } /** * Writes the specified character to this output writer. - */ + */ Writer &BasicWriter::writeChar(char ch) { put(ch); return *this; } - /** * Writes the specified unicode string to this output writer. - */ + */ Writer &BasicWriter::writeUString(const Glib::ustring &str) { writeStdString(str.raw()); @@ -505,7 +474,7 @@ Writer &BasicWriter::writeUString(const Glib::ustring &str) /** * Writes the specified standard string to this output writer. - */ + */ Writer &BasicWriter::writeStdString(const std::string &str) { for (char it : str) { @@ -516,7 +485,7 @@ Writer &BasicWriter::writeStdString(const std::string &str) /** * Writes the specified character string to this output writer. - */ + */ Writer &BasicWriter::writeString(const char *str) { std::string tmp; @@ -528,13 +497,10 @@ Writer &BasicWriter::writeString(const char *str) return *this; } - - - /** * */ -Writer &BasicWriter::writeBool (bool val ) +Writer &BasicWriter::writeBool(bool val) { if (val) writeString("true"); @@ -543,26 +509,23 @@ Writer &BasicWriter::writeBool (bool val ) return *this; } - /** * */ -Writer &BasicWriter::writeShort (short val ) +Writer &BasicWriter::writeShort(short val) { gchar *buf = g_strdup_printf("%d", val); if (buf) { writeString(buf); g_free(buf); } - return *this; + return *this; } - - /** * */ -Writer &BasicWriter::writeUnsignedShort (unsigned short val ) +Writer &BasicWriter::writeUnsignedShort(unsigned short val) { gchar *buf = g_strdup_printf("%u", val); if (buf) { @@ -575,7 +538,7 @@ Writer &BasicWriter::writeUnsignedShort (unsigned short val ) /** * */ -Writer &BasicWriter::writeInt (int val) +Writer &BasicWriter::writeInt(int val) { gchar *buf = g_strdup_printf("%d", val); if (buf) { @@ -588,7 +551,7 @@ Writer &BasicWriter::writeInt (int val) /** * */ -Writer &BasicWriter::writeUnsignedInt (unsigned int val) +Writer &BasicWriter::writeUnsignedInt(unsigned int val) { gchar *buf = g_strdup_printf("%u", val); if (buf) { @@ -601,7 +564,7 @@ Writer &BasicWriter::writeUnsignedInt (unsigned int val) /** * */ -Writer &BasicWriter::writeLong (long val) +Writer &BasicWriter::writeLong(long val) { gchar *buf = g_strdup_printf("%ld", val); if (buf) { @@ -660,59 +623,78 @@ Writer &BasicWriter::writeDouble(double val) return *this; } +Writer &operator<<(Writer &writer, char val) +{ + return writer.writeChar(val); +} -Writer& operator<< (Writer &writer, char val) - { return writer.writeChar(val); } - -Writer& operator<< (Writer &writer, Glib::ustring &val) - { return writer.writeUString(val); } - -Writer& operator<< (Writer &writer, std::string &val) - { return writer.writeStdString(val); } - -Writer& operator<< (Writer &writer, char const *val) - { return writer.writeString(val); } +Writer &operator<<(Writer &writer, Glib::ustring &val) +{ + return writer.writeUString(val); +} -Writer& operator<< (Writer &writer, bool val) - { return writer.writeBool(val); } +Writer &operator<<(Writer &writer, std::string &val) +{ + return writer.writeStdString(val); +} -Writer& operator<< (Writer &writer, short val) - { return writer.writeShort(val); } +Writer &operator<<(Writer &writer, char const *val) +{ + return writer.writeString(val); +} -Writer& operator<< (Writer &writer, unsigned short val) - { return writer.writeUnsignedShort(val); } +Writer &operator<<(Writer &writer, bool val) +{ + return writer.writeBool(val); +} -Writer& operator<< (Writer &writer, int val) - { return writer.writeInt(val); } +Writer &operator<<(Writer &writer, short val) +{ + return writer.writeShort(val); +} -Writer& operator<< (Writer &writer, unsigned int val) - { return writer.writeUnsignedInt(val); } +Writer &operator<<(Writer &writer, unsigned short val) +{ + return writer.writeUnsignedShort(val); +} -Writer& operator<< (Writer &writer, long val) - { return writer.writeLong(val); } +Writer &operator<<(Writer &writer, int val) +{ + return writer.writeInt(val); +} -Writer& operator<< (Writer &writer, unsigned long val) - { return writer.writeUnsignedLong(val); } +Writer &operator<<(Writer &writer, unsigned int val) +{ + return writer.writeUnsignedInt(val); +} -Writer& operator<< (Writer &writer, float val) - { return writer.writeFloat(val); } +Writer &operator<<(Writer &writer, long val) +{ + return writer.writeLong(val); +} -Writer& operator<< (Writer &writer, double val) - { return writer.writeDouble(val); } +Writer &operator<<(Writer &writer, unsigned long val) +{ + return writer.writeUnsignedLong(val); +} +Writer &operator<<(Writer &writer, float val) +{ + return writer.writeFloat(val); +} +Writer &operator<<(Writer &writer, double val) +{ + return writer.writeDouble(val); +} //######################################################################### //# O U T P U T S T R E A M W R I T E R //######################################################################### - OutputStreamWriter::OutputStreamWriter(OutputStream &outputStreamDest) - : outputStream(outputStreamDest) -{ -} - - + : outputStream(outputStreamDest) +{} /** * Close the underlying OutputStream @@ -722,15 +704,15 @@ void OutputStreamWriter::close() flush(); outputStream.close(); } - + /** * Flush the underlying OutputStream */ void OutputStreamWriter::flush() { - outputStream.flush(); + outputStream.flush(); } - + /** * Overloaded to redirect the output chars from the next Writer * in the chain to an OutputStream instead. @@ -744,26 +726,22 @@ void OutputStreamWriter::put(char ch) //# S T D W R I T E R //######################################################################### - /** - * + * */ StdWriter::StdWriter() { outputStream = new StdOutputStream(); } - /** - * + * */ StdWriter::~StdWriter() { delete outputStream; } - - /** * Close the underlying OutputStream */ @@ -772,15 +750,15 @@ void StdWriter::close() flush(); outputStream->close(); } - + /** * Flush the underlying OutputStream */ void StdWriter::flush() { - outputStream->flush(); + outputStream->flush(); } - + /** * Overloaded to redirect the output chars from the next Writer * in the chain to an OutputStream instead. @@ -790,11 +768,9 @@ void StdWriter::put(char ch) outputStream->put(ch); } - } // namespace IO } // namespace Inkscape - //######################################################################### //# E N D O F F I L E //######################################################################### diff --git a/src/io/stream/inkscapestream.h b/src/io/stream/inkscapestream.h index b835a7f041e4362155e025bff49f9a875ad7d139..13125e4b6a601f8767930952fd7fc96542b4a6b1 100644 --- a/src/io/stream/inkscapestream.h +++ b/src/io/stream/inkscapestream.h @@ -13,10 +13,8 @@ #include #include -namespace Inkscape -{ -namespace IO -{ +namespace Inkscape { +namespace IO { class StreamException : public std::exception { @@ -24,14 +22,11 @@ public: StreamException(Glib::ustring theReason) noexcept : reason(std::move(theReason)) {} - ~StreamException() noexcept override - = default; - char const *what() const noexcept override - { return reason.c_str(); } - + ~StreamException() noexcept override = default; + char const *what() const noexcept override { return reason.c_str(); } + private: Glib::ustring reason; - }; //######################################################################### @@ -47,9 +42,7 @@ private: */ class InputStream { - public: - /** * Constructor. */ @@ -65,14 +58,14 @@ public: * to be read */ virtual int available() = 0; - + /** * Do whatever it takes to 'close' this input stream * The most likely implementation of this method will be * for endpoints that use a resource for their data. */ virtual void close() = 0; - + /** * Read one byte from this input stream. This is a blocking * call. If no data is currently available, this call will @@ -83,11 +76,8 @@ public: * This call returns -1 on end-of-file. */ virtual int get() = 0; - -}; // class InputStream - - +}; // class InputStream /** * This is the class that most users should inherit, to provide @@ -96,55 +86,40 @@ public: */ class BasicInputStream : public InputStream { - public: - BasicInputStream(InputStream &sourceStream); - + ~BasicInputStream() override = default; - + int available() override; - + void close() override; - + int get() override; - -protected: +protected: bool closed; InputStream &source; - -private: - +private: }; // class BasicInputStream - - /** * Convenience class for reading from standard input */ class StdInputStream : public InputStream { public: + int available() override { return 0; } - int available() override - { return 0; } - void close() override - { /* do nothing */ } - - int get() override - { return getchar(); } + { /* do nothing */ + } + int get() override { return getchar(); } }; - - - - - //######################################################################### //# O U T P U T S T R E A M //######################################################################### @@ -157,9 +132,7 @@ public: */ class OutputStream { - public: - /** * Constructor. */ @@ -177,88 +150,69 @@ public: * 3. close the destination stream */ virtual void close() = 0; - + /** * This call should push any pending data it might have to * the destination stream. It should NOT call flush() on * the destination stream. */ virtual void flush() = 0; - + /** * Send one byte to the destination stream. */ virtual int put(char ch) = 0; - }; // class OutputStream - /** * This is the class that most users should inherit, to provide * their own output streams. */ class BasicOutputStream : public OutputStream { - public: - BasicOutputStream(OutputStream &destinationStream); - + ~BasicOutputStream() override = default; void close() override; - + void flush() override; - + int put(char ch) override; protected: - bool closed; OutputStream &destination; - }; // class BasicOutputStream - - /** * Convenience class for writing to standard output */ class StdOutputStream : public OutputStream { public: + void close() override {} - void close() override - { } - - void flush() override - { } - - int put(char ch) override - {return putchar(ch); } + void flush() override {} + int put(char ch) override { return putchar(ch); } }; - - - //######################################################################### //# R E A D E R //######################################################################### - /** * This interface and its descendants are for unicode character-oriented input * */ class Reader { - public: - /** * Constructor. */ @@ -269,48 +223,45 @@ public: */ virtual ~Reader() = default; - virtual int available() = 0; - + virtual void close() = 0; - + virtual char get() = 0; - + virtual Glib::ustring readLine() = 0; - + virtual Glib::ustring readWord() = 0; - + /* Input formatting */ - virtual const Reader& readBool (bool& val ) = 0; - virtual const Reader& operator>> (bool& val ) = 0; - - virtual const Reader& readShort (short &val) = 0; - virtual const Reader& operator>> (short &val) = 0; - - virtual const Reader& readUnsignedShort (unsigned short &val) = 0; - virtual const Reader& operator>> (unsigned short &val) = 0; - - virtual const Reader& readInt (int &val) = 0; - virtual const Reader& operator>> (int &val) = 0; - - virtual const Reader& readUnsignedInt (unsigned int &val) = 0; - virtual const Reader& operator>> (unsigned int &val) = 0; - - virtual const Reader& readLong (long &val) = 0; - virtual const Reader& operator>> (long &val) = 0; - - virtual const Reader& readUnsignedLong (unsigned long &val) = 0; - virtual const Reader& operator>> (unsigned long &val) = 0; - - virtual const Reader& readFloat (float &val) = 0; - virtual const Reader& operator>> (float &val) = 0; - - virtual const Reader& readDouble (double &val) = 0; - virtual const Reader& operator>> (double &val) = 0; + virtual const Reader &readBool(bool &val) = 0; + virtual const Reader &operator>>(bool &val) = 0; -}; // interface Reader + virtual const Reader &readShort(short &val) = 0; + virtual const Reader &operator>>(short &val) = 0; + + virtual const Reader &readUnsignedShort(unsigned short &val) = 0; + virtual const Reader &operator>>(unsigned short &val) = 0; + + virtual const Reader &readInt(int &val) = 0; + virtual const Reader &operator>>(int &val) = 0; + + virtual const Reader &readUnsignedInt(unsigned int &val) = 0; + virtual const Reader &operator>>(unsigned int &val) = 0; + + virtual const Reader &readLong(long &val) = 0; + virtual const Reader &operator>>(long &val) = 0; + virtual const Reader &readUnsignedLong(unsigned long &val) = 0; + virtual const Reader &operator>>(unsigned long &val) = 0; + virtual const Reader &readFloat(float &val) = 0; + virtual const Reader &operator>>(float &val) = 0; + + virtual const Reader &readDouble(double &val) = 0; + virtual const Reader &operator>>(double &val) = 0; + +}; // interface Reader /** * This class and its descendants are for unicode character-oriented input @@ -318,73 +269,56 @@ public: */ class BasicReader : public Reader { - public: - BasicReader(Reader &sourceStream); - + ~BasicReader() override = default; int available() override; - + void close() override; - + char get() override; - + Glib::ustring readLine() override; - + Glib::ustring readWord() override; - + /* Input formatting */ - const Reader& readBool (bool& val ) override; - const Reader& operator>> (bool& val ) override - { return readBool(val); } - - const Reader& readShort (short &val) override; - const Reader& operator>> (short &val) override - { return readShort(val); } - - const Reader& readUnsignedShort (unsigned short &val) override; - const Reader& operator>> (unsigned short &val) override - { return readUnsignedShort(val); } - - const Reader& readInt (int &val) override; - const Reader& operator>> (int &val) override - { return readInt(val); } - - const Reader& readUnsignedInt (unsigned int &val) override; - const Reader& operator>> (unsigned int &val) override - { return readUnsignedInt(val); } - - const Reader& readLong (long &val) override; - const Reader& operator>> (long &val) override - { return readLong(val); } - - const Reader& readUnsignedLong (unsigned long &val) override; - const Reader& operator>> (unsigned long &val) override - { return readUnsignedLong(val); } - - const Reader& readFloat (float &val) override; - const Reader& operator>> (float &val) override - { return readFloat(val); } - - const Reader& readDouble (double &val) override; - const Reader& operator>> (double &val) override - { return readDouble(val); } - + const Reader &readBool(bool &val) override; + const Reader &operator>>(bool &val) override { return readBool(val); } -protected: + const Reader &readShort(short &val) override; + const Reader &operator>>(short &val) override { return readShort(val); } - Reader *source; + const Reader &readUnsignedShort(unsigned short &val) override; + const Reader &operator>>(unsigned short &val) override { return readUnsignedShort(val); } - BasicReader() - { source = nullptr; } + const Reader &readInt(int &val) override; + const Reader &operator>>(int &val) override { return readInt(val); } -private: + const Reader &readUnsignedInt(unsigned int &val) override; + const Reader &operator>>(unsigned int &val) override { return readUnsignedInt(val); } -}; // class BasicReader + const Reader &readLong(long &val) override; + const Reader &operator>>(long &val) override { return readLong(val); } + + const Reader &readUnsignedLong(unsigned long &val) override; + const Reader &operator>>(unsigned long &val) override { return readUnsignedLong(val); } + + const Reader &readFloat(float &val) override; + const Reader &operator>>(float &val) override { return readFloat(val); } + const Reader &readDouble(double &val) override; + const Reader &operator>>(double &val) override { return readDouble(val); } +protected: + Reader *source; + + BasicReader() { source = nullptr; } + +private: +}; // class BasicReader /** * Class for placing a Reader on an open InputStream @@ -393,22 +327,17 @@ private: class InputStreamReader : public BasicReader { public: - InputStreamReader(InputStream &inputStreamSource); - + /*Overload these 3 for your implementation*/ int available() override; - + void close() override; - - char get() override; + char get() override; private: - InputStream &inputStream; - - }; /** @@ -418,30 +347,21 @@ private: class StdReader : public BasicReader { public: - StdReader(); ~StdReader() override; - + /*Overload these 3 for your implementation*/ int available() override; - + void close() override; - - char get() override; + char get() override; private: - InputStream *inputStream; - - }; - - - - //######################################################################### //# W R I T E R //######################################################################### @@ -452,9 +372,7 @@ private: */ class Writer { - public: - /** * Constructor. */ @@ -466,138 +384,122 @@ public: virtual ~Writer() = default; virtual void close() = 0; - + virtual void flush() = 0; - + virtual void put(char ch) = 0; - - /* Formatted output */ - virtual Writer& printf(char const *fmt, ...) G_GNUC_PRINTF(2,3) = 0; - virtual Writer& writeChar(char val) = 0; + /* Formatted output */ + virtual Writer &printf(char const *fmt, ...) G_GNUC_PRINTF(2, 3) = 0; - virtual Writer& writeUString(const Glib::ustring &val) = 0; + virtual Writer &writeChar(char val) = 0; - virtual Writer& writeStdString(const std::string &val) = 0; + virtual Writer &writeUString(const Glib::ustring &val) = 0; - virtual Writer& writeString(const char *str) = 0; + virtual Writer &writeStdString(const std::string &val) = 0; - virtual Writer& writeBool (bool val ) = 0; + virtual Writer &writeString(const char *str) = 0; - virtual Writer& writeShort (short val ) = 0; + virtual Writer &writeBool(bool val) = 0; - virtual Writer& writeUnsignedShort (unsigned short val ) = 0; + virtual Writer &writeShort(short val) = 0; - virtual Writer& writeInt (int val ) = 0; + virtual Writer &writeUnsignedShort(unsigned short val) = 0; - virtual Writer& writeUnsignedInt (unsigned int val ) = 0; + virtual Writer &writeInt(int val) = 0; - virtual Writer& writeLong (long val ) = 0; + virtual Writer &writeUnsignedInt(unsigned int val) = 0; - virtual Writer& writeUnsignedLong (unsigned long val ) = 0; + virtual Writer &writeLong(long val) = 0; - virtual Writer& writeFloat (float val ) = 0; + virtual Writer &writeUnsignedLong(unsigned long val) = 0; - virtual Writer& writeDouble (double val ) = 0; + virtual Writer &writeFloat(float val) = 0; - + virtual Writer &writeDouble(double val) = 0; }; // interface Writer - /** * This class and its descendants are for unicode character-oriented output * */ class BasicWriter : public Writer { - public: - BasicWriter(Writer &destinationWriter); ~BasicWriter() override = default; /*Overload these 3 for your implementation*/ void close() override; - + void flush() override; - + void put(char ch) override; - - - + /* Formatted output */ - Writer &printf(char const *fmt, ...) override G_GNUC_PRINTF(2,3); + Writer &printf(char const *fmt, ...) override G_GNUC_PRINTF(2, 3); - Writer& writeChar(char val) override; + Writer &writeChar(char val) override; - Writer& writeUString(const Glib::ustring &val) override; + Writer &writeUString(const Glib::ustring &val) override; - Writer& writeStdString(const std::string &val) override; + Writer &writeStdString(const std::string &val) override; - Writer& writeString(const char *str) override; + Writer &writeString(const char *str) override; - Writer& writeBool (bool val ) override; + Writer &writeBool(bool val) override; - Writer& writeShort (short val ) override; + Writer &writeShort(short val) override; - Writer& writeUnsignedShort (unsigned short val ) override; + Writer &writeUnsignedShort(unsigned short val) override; - Writer& writeInt (int val ) override; + Writer &writeInt(int val) override; - Writer& writeUnsignedInt (unsigned int val ) override; + Writer &writeUnsignedInt(unsigned int val) override; - Writer& writeLong (long val ) override; + Writer &writeLong(long val) override; - Writer& writeUnsignedLong (unsigned long val ) override; + Writer &writeUnsignedLong(unsigned long val) override; - Writer& writeFloat (float val ) override; + Writer &writeFloat(float val) override; - Writer& writeDouble (double val ) override; + Writer &writeDouble(double val) override; - protected: - Writer *destination; - BasicWriter() - { destination = nullptr; } - -private: + BasicWriter() { destination = nullptr; } +private: }; // class BasicWriter +Writer &operator<<(Writer &writer, char val); +Writer &operator<<(Writer &writer, Glib::ustring &val); -Writer& operator<< (Writer &writer, char val); - -Writer& operator<< (Writer &writer, Glib::ustring &val); - -Writer& operator<< (Writer &writer, std::string &val); - -Writer& operator<< (Writer &writer, char const *val); - -Writer& operator<< (Writer &writer, bool val); +Writer &operator<<(Writer &writer, std::string &val); -Writer& operator<< (Writer &writer, short val); +Writer &operator<<(Writer &writer, char const *val); -Writer& operator<< (Writer &writer, unsigned short val); +Writer &operator<<(Writer &writer, bool val); -Writer& operator<< (Writer &writer, int val); +Writer &operator<<(Writer &writer, short val); -Writer& operator<< (Writer &writer, unsigned int val); +Writer &operator<<(Writer &writer, unsigned short val); -Writer& operator<< (Writer &writer, long val); +Writer &operator<<(Writer &writer, int val); -Writer& operator<< (Writer &writer, unsigned long val); +Writer &operator<<(Writer &writer, unsigned int val); -Writer& operator<< (Writer &writer, float val); - -Writer& operator<< (Writer &writer, double val); +Writer &operator<<(Writer &writer, long val); +Writer &operator<<(Writer &writer, unsigned long val); +Writer &operator<<(Writer &writer, float val); +Writer &operator<<(Writer &writer, double val); /** * Class for placing a Writer on an open OutputStream @@ -606,25 +508,19 @@ Writer& operator<< (Writer &writer, double val); class OutputStreamWriter : public BasicWriter { public: - OutputStreamWriter(OutputStream &outputStreamDest); - + /*Overload these 3 for your implementation*/ void close() override; - + void flush() override; - - void put(char ch) override; + void put(char ch) override; private: - OutputStream &outputStream; - - }; - /** * Convenience class for writing to standard output */ @@ -635,20 +531,14 @@ public: ~StdWriter() override; - void close() override; - void flush() override; - void put(char ch) override; - private: - OutputStream *outputStream; - }; //######################################################################### @@ -657,10 +547,7 @@ private: void pipeStream(InputStream &source, OutputStream &dest); - - } // namespace IO } // namespace Inkscape - #endif // SEEN_INKSCAPE_IO_INKSCAPESTREAM_H diff --git a/src/io/stream/streamtest.cpp b/src/io/stream/streamtest.cpp index 5d270580b8c87dcd31d099a6f91b8f2746161935..a681d20cf0e6298eaa1706f3edeeaf543d4e6f7b 100644 --- a/src/io/stream/streamtest.cpp +++ b/src/io/stream/streamtest.cpp @@ -8,16 +8,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - -#include #include // realpath +#include #include // mkdtemp, realpath -#include // chdir #include // strlen, strncpy, strrchr +#include // chdir -#include "inkscapestream.h" #include "base64stream.h" #include "gzipstream.h" +#include "inkscapestream.h" #include "stringstream.h" #include "uristream.h" #include "xsltstream.h" @@ -35,12 +34,12 @@ bool testUriStream() { printf("######### UriStream copy ############\n"); Inkscape::URI inUri(myself); - Inkscape::IO::UriInputStream ins(inUri); + Inkscape::IO::UriInputStream ins(inUri); Inkscape::URI outUri("streamtest.copy"); Inkscape::IO::UriOutputStream outs(outUri); - + pipeStream(ins, outs); - + ins.close(); outs.close(); @@ -52,7 +51,7 @@ bool testWriter() printf("######### OutputStreamWriter ############\n"); Inkscape::IO::StdOutputStream outs; Inkscape::IO::OutputStreamWriter writer(outs); - + writer << "Hello, world! " << 123.45 << " times\n"; writer.printf("There are %f quick brown foxes in %d states\n", 123.45, 88); @@ -64,7 +63,7 @@ bool testStdWriter() { printf("######### StdWriter ############\n"); Inkscape::IO::StdWriter writer; - + writer << "Hello, world! " << 123.45 << " times\n"; writer.printf("There are %f quick brown foxes in %d states\n", 123.45, 88); @@ -107,31 +106,30 @@ bool testXslt() { printf("######### XSLT Sheet ############\n"); Inkscape::URI xsltSheetUri(xslpath); - Inkscape::IO::UriInputStream xsltSheetIns(xsltSheetUri); + Inkscape::IO::UriInputStream xsltSheetIns(xsltSheetUri); Inkscape::IO::XsltStyleSheet stylesheet(xsltSheetIns); xsltSheetIns.close(); - + Inkscape::URI sourceUri(xmlpath); - Inkscape::IO::UriInputStream xmlIns(sourceUri); + Inkscape::IO::UriInputStream xmlIns(sourceUri); printf("######### XSLT Input ############\n"); Inkscape::URI destUri("test.html"); Inkscape::IO::UriOutputStream xmlOuts(destUri); - - Inkscape::IO::XsltInputStream xsltIns(xmlIns, stylesheet); + + Inkscape::IO::XsltInputStream xsltIns(xmlIns, stylesheet); pipeStream(xsltIns, xmlOuts); xsltIns.close(); xmlOuts.close(); - printf("######### XSLT Output ############\n"); - Inkscape::IO::UriInputStream xmlIns2(sourceUri); + Inkscape::IO::UriInputStream xmlIns2(sourceUri); Inkscape::URI destUri2("test2.html"); Inkscape::IO::UriOutputStream xmlOuts2(destUri2); - - Inkscape::IO::XsltOutputStream xsltOuts(xmlOuts2, stylesheet); + + Inkscape::IO::XsltOutputStream xsltOuts(xmlOuts2, stylesheet); pipeStream(xmlIns2, xsltOuts); xmlIns2.close(); xsltOuts.close(); @@ -141,12 +139,11 @@ bool testXslt() bool testGzip() { - printf("######### Gzip Output ############\n"); Inkscape::URI gzUri("test.gz"); Inkscape::URI sourceUri(xmlpath); - Inkscape::IO::UriInputStream sourceIns(sourceUri); - Inkscape::IO::UriOutputStream gzOuts(gzUri); + Inkscape::IO::UriInputStream sourceIns(sourceUri); + Inkscape::IO::UriOutputStream gzOuts(gzUri); Inkscape::IO::GzipOutputStream gzipOuts(gzOuts); pipeStream(sourceIns, gzipOuts); @@ -155,7 +152,7 @@ bool testGzip() printf("######### Gzip Input ############\n"); - Inkscape::IO::UriInputStream gzIns(gzUri); + Inkscape::IO::UriInputStream gzIns(gzUri); Inkscape::URI destUri("crystalegg2.xml"); Inkscape::IO::UriOutputStream destOuts(destUri); @@ -169,88 +166,73 @@ bool testGzip() bool doTest() { - if (!testUriStream()) - { + if (!testUriStream()) { return false; - } - if (!testWriter()) - { + } + if (!testWriter()) { return false; - } - if (!testStdWriter()) - { + } + if (!testStdWriter()) { return false; - } - if (!testBase64()) - { + } + if (!testBase64()) { return false; - } - if (!testXslt()) - { + } + if (!testXslt()) { return false; - } - if (!testGzip()) - { + } + if (!testGzip()) { return false; - } + } return true; } void path_init(char *path, char *name) { - if (strlen(name)>PATH_MAX-strlen(myself)) - { - printf("merging paths would be too long\n"); - exit(1); + if (strlen(name) > PATH_MAX - strlen(myself)) { + printf("merging paths would be too long\n"); + exit(1); } - strncpy(path,myself,PATH_MAX); - char * ptr = strrchr(path,'/'); - if (!ptr) - { - printf("path '%s' is missing any slashes\n",path); - exit(1); + strncpy(path, myself, PATH_MAX); + char *ptr = strrchr(path, '/'); + if (!ptr) { + printf("path '%s' is missing any slashes\n", path); + exit(1); } - strncpy(ptr+1,name,strlen(name)+1); - path[PATH_MAX-1] = '\0'; - printf("'%s'\n",path); + strncpy(ptr + 1, name, strlen(name) + 1); + path[PATH_MAX - 1] = '\0'; + printf("'%s'\n", path); } - int main(int argc, char **argv) { - if (!realpath(argv[0],myself)) - { - perror("realpath"); - return 1; + if (!realpath(argv[0], myself)) { + perror("realpath"); + return 1; } - path_init(xmlpath,xmlname); - path_init(xslpath,xslname); + path_init(xmlpath, xmlname); + path_init(xslpath, xslname); // create temp files somewhere else instead of current dir // TODO: clean them up too - char * testpath = strdup("/tmp/streamtest-XXXXXX"); - char * testpath2; + char *testpath = strdup("/tmp/streamtest-XXXXXX"); + char *testpath2; testpath2 = mkdtemp(testpath); free(testpath); - if (!testpath2) - { - perror("mkdtemp"); - return 1; + if (!testpath2) { + perror("mkdtemp"); + return 1; } - if (chdir(testpath2)) - { - perror("chdir"); - return 1; + if (chdir(testpath2)) { + perror("chdir"); + return 1; } - if (!doTest()) - { + if (!doTest()) { printf("#### Test failed\n"); - return 1; - } - else - { + return 1; + } else { printf("##### Test succeeded\n"); - } + } return 0; } diff --git a/src/io/stream/stringstream.cpp b/src/io/stream/stringstream.cpp index 0259869f79d3039a26448b4fb5a645f11e25008c..ec62bab3a75ece23e63678cae41a3485bf6f4b0e 100644 --- a/src/io/stream/stringstream.cpp +++ b/src/io/stream/stringstream.cpp @@ -11,67 +11,55 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "stringstream.h" -namespace Inkscape -{ -namespace IO -{ - +namespace Inkscape { +namespace IO { //######################################################################### //# S T R I N G I N P U T S T R E A M //######################################################################### - /** * - */ + */ StringInputStream::StringInputStream(Glib::ustring &sourceString) - : buffer(sourceString) + : buffer(sourceString) { position = 0; } /** * - */ -StringInputStream::~StringInputStream() -= default; + */ +StringInputStream::~StringInputStream() = default; /** * Returns the number of bytes that can be read (or skipped over) from * this input stream without blocking by the next caller of a method for * this input stream. - */ + */ int StringInputStream::available() { return buffer.size() - position; } - /** * Closes this input stream and releases any system resources * associated with the stream. - */ -void StringInputStream::close() -{ -} - + */ +void StringInputStream::close() {} + /** * Reads the next byte of data from the input stream. -1 if EOF - */ + */ int StringInputStream::get() { if (position >= (int)buffer.size()) return -1; - int ch = (int) buffer[position++]; + int ch = (int)buffer[position++]; return ch; } - - - //######################################################################### //# S T R I N G O U T P U T S T R E A M @@ -79,47 +67,41 @@ int StringInputStream::get() /** * - */ -StringOutputStream::StringOutputStream() -= default; + */ +StringOutputStream::StringOutputStream() = default; /** * - */ -StringOutputStream::~StringOutputStream() -= default; + */ +StringOutputStream::~StringOutputStream() = default; /** * Closes this output stream and releases any system resources * associated with this stream. - */ -void StringOutputStream::close() -{ -} - + */ +void StringOutputStream::close() {} + /** * Flushes this output stream and forces any buffered output * bytes to be written out. - */ + */ void StringOutputStream::flush() { - //nothing to do + // nothing to do } - + /** * Writes the specified byte to this output stream. - */ + */ int StringOutputStream::put(char ch) { buffer.push_back(ch); - return 1; + return 1; } - } // namespace IO } // namespace Inkscape - //######################################################################### //# E N D O F F I L E //######################################################################### diff --git a/src/io/stream/stringstream.h b/src/io/stream/stringstream.h index 3afb9a87056c53f5d3626f3ed94f3b54efc229bb..bbd5c8129fcec5e6f2900b0b386ee818b7ee6b02 100644 --- a/src/io/stream/stringstream.h +++ b/src/io/stream/stringstream.h @@ -14,12 +14,8 @@ #include "inkscapestream.h" - -namespace Inkscape -{ -namespace IO -{ - +namespace Inkscape { +namespace IO { //######################################################################### //# S T R I N G I N P U T S T R E A M @@ -31,30 +27,24 @@ namespace IO */ class StringInputStream : public InputStream { - public: - StringInputStream(Glib::ustring &sourceString); - + ~StringInputStream() override; - + int available() override; - + void close() override; - + int get() override; - -private: +private: Glib::ustring &buffer; long position; }; // class StringInputStream - - - //######################################################################### //# S T R I N G O U T P U T S T R E A M //######################################################################### @@ -65,41 +55,27 @@ private: */ class StringOutputStream : public OutputStream { - public: - StringOutputStream(); - + ~StringOutputStream() override; - + void close() override; - + void flush() override; - + int put(char ch) override; - virtual Glib::ustring &getString() - { return buffer; } + virtual Glib::ustring &getString() { return buffer; } - virtual void clear() - { buffer = ""; } + virtual void clear() { buffer = ""; } private: - Glib::ustring buffer; - }; // class StringOutputStream - - - - - - } // namespace IO } // namespace Inkscape - - #endif /* __INKSCAPE_IO_STRINGSTREAM_H__ */ diff --git a/src/io/stream/uristream.cpp b/src/io/stream/uristream.cpp index 734b8fac54b9b3fe591c5b16f2705586ad99c7cd..e129cf50b1264a80dacf770906e042373f91a4a6 100644 --- a/src/io/stream/uristream.cpp +++ b/src/io/stream/uristream.cpp @@ -11,21 +11,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "uristream.h" -#include "io/sys.h" +#include "io/sys.h" -namespace Inkscape -{ -namespace IO -{ +namespace Inkscape { +namespace IO { //######################################################################### //# F I L E I N P U T S T R E A M //######################################################################### - /** * */ @@ -56,18 +52,17 @@ int FileInputStream::available() return 0; } - /** * Closes this input stream and releases any system resources * associated with the stream. */ void FileInputStream::close() { - if (!inf) - return; - fflush(inf); - fclose(inf); - inf=nullptr; + if (!inf) + return; + fflush(inf); + fclose(inf); + inf = nullptr; } /** @@ -76,21 +71,15 @@ void FileInputStream::close() int FileInputStream::get() { int retVal = -1; - if (!inf || feof(inf)) - { - retVal = -1; - } - else - { - retVal = fgetc(inf); - } + if (!inf || feof(inf)) { + retVal = -1; + } else { + retVal = fgetc(inf); + } return retVal; } - - - //######################################################################### //# F I L E O U T P U T S T R E A M //######################################################################### @@ -119,12 +108,12 @@ FileOutputStream::~FileOutputStream() */ void FileOutputStream::close() { - if (!outf) - return; - fflush(outf); - if ( ownsFile ) - fclose(outf); - outf=nullptr; + if (!outf) + return; + fflush(outf); + if (ownsFile) + fclose(outf); + outf = nullptr; } /** @@ -133,9 +122,9 @@ void FileOutputStream::close() */ void FileOutputStream::flush() { - if (!outf) - return; - fflush(outf); + if (!outf) + return; + fflush(outf); } /** @@ -145,25 +134,20 @@ int FileOutputStream::put(char ch) { unsigned char uch; - if (!outf) - return -1; - uch = (unsigned char)(ch & 0xff); - if (fputc(uch, outf) == EOF) { - Glib::ustring err = "ERROR writing to file "; - throw StreamException(err); - } + if (!outf) + return -1; + uch = (unsigned char)(ch & 0xff); + if (fputc(uch, outf) == EOF) { + Glib::ustring err = "ERROR writing to file "; + throw StreamException(err); + } return 1; } - - - - } // namespace IO } // namespace Inkscape - //######################################################################### //# E N D O F F I L E //######################################################################### diff --git a/src/io/stream/uristream.h b/src/io/stream/uristream.h index f0544d876cb31f2d0bbdc7d9f0521f67c270f8de..3ad62fd331902f4cdd8c8ad9171a16de1dc46b43 100644 --- a/src/io/stream/uristream.h +++ b/src/io/stream/uristream.h @@ -15,19 +15,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - -#include "object/uri.h" - #include "inkscapestream.h" +#include "object/uri.h" - -namespace Inkscape -{ +namespace Inkscape { class URI; -namespace IO -{ +namespace IO { //######################################################################### //# F I L E I N P U T S T R E A M @@ -38,7 +33,6 @@ namespace IO */ class FileInputStream : public InputStream { - public: FileInputStream(FILE *source); @@ -51,13 +45,10 @@ public: int get() override; private: - FILE *inf; //for file: uris + FILE *inf; // for file: uris }; // class FileInputStream - - - //######################################################################### //# F I L E O U T P U T S T R E A M //######################################################################### @@ -67,9 +58,7 @@ private: */ class FileOutputStream : public OutputStream { - public: - FileOutputStream(FILE *fp); ~FileOutputStream() override; @@ -81,21 +70,15 @@ public: int put(char ch) override; private: - bool ownsFile; - FILE *outf; //for file: uris + FILE *outf; // for file: uris }; // class FileOutputStream - - - - } // namespace IO } // namespace Inkscape - #endif // SEEN_INKSCAPE_IO_URISTREAM_H // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/io/stream/xsltstream.cpp b/src/io/stream/xsltstream.cpp index 882db30b2c7f20b5cf268333f76770d752477f37..d27ff9eabdfe335014b0ad1a40878f522d953a0a 100644 --- a/src/io/stream/xsltstream.cpp +++ b/src/io/stream/xsltstream.cpp @@ -10,18 +10,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "xsltstream.h" -#include "stringstream.h" -#include +#include +#include "stringstream.h" - -namespace Inkscape -{ -namespace IO -{ +namespace Inkscape { +namespace IO { //######################################################################### //# X S L T S T Y L E S H E E T @@ -31,23 +27,20 @@ namespace IO * */ XsltStyleSheet::XsltStyleSheet(InputStream &xsltSource) - - : stylesheet(nullptr) + + : stylesheet(nullptr) { if (!read(xsltSource)) { throw StreamException("read failed"); - } + } } /** * */ XsltStyleSheet::XsltStyleSheet() - : stylesheet(nullptr) -{ -} - - + : stylesheet(nullptr) +{} /** * @@ -59,57 +52,54 @@ bool XsltStyleSheet::read(InputStream &xsltSource) std::string strBuf = outs.getString().raw(); xmlDocPtr doc = xmlParseMemory(strBuf.c_str(), strBuf.size()); stylesheet = xsltParseStylesheetDoc(doc); - //following not necessary. handled by xsltFreeStylesheet(stylesheet); - //xmlFreeDoc(doc); + // following not necessary. handled by xsltFreeStylesheet(stylesheet); + // xmlFreeDoc(doc); if (!stylesheet) return false; return true; } - /** * - */ + */ XsltStyleSheet::~XsltStyleSheet() { if (stylesheet) xsltFreeStylesheet(stylesheet); } - - //######################################################################### //# X S L T I N P U T S T R E A M //######################################################################### - /** * - */ + */ XsltInputStream::XsltInputStream(InputStream &xmlSource, XsltStyleSheet &sheet) - : BasicInputStream(xmlSource), stylesheet(sheet) + : BasicInputStream(xmlSource) + , stylesheet(sheet) { - //Load the data + // Load the data StringOutputStream outs; pipeStream(source, outs); std::string strBuf = outs.getString().raw(); - - //Do the processing + + // Do the processing const char *params[1]; params[0] = nullptr; xmlDocPtr srcDoc = xmlParseMemory(strBuf.c_str(), strBuf.size()); xmlDocPtr resDoc = xsltApplyStylesheet(stylesheet.stylesheet, srcDoc, params); xmlDocDumpFormatMemory(resDoc, &outbuf, &outsize, 1); outpos = 0; - - //Free our mem + + // Free our mem xmlFreeDoc(resDoc); xmlFreeDoc(srcDoc); } /** * - */ + */ XsltInputStream::~XsltInputStream() { xmlFree(outbuf); @@ -119,39 +109,33 @@ XsltInputStream::~XsltInputStream() * Returns the number of bytes that can be read (or skipped over) from * this input stream without blocking by the next caller of a method for * this input stream. - */ + */ int XsltInputStream::available() { return outsize - outpos; } - /** * Closes this input stream and releases any system resources * associated with the stream. - */ + */ void XsltInputStream::close() { closed = true; } - + /** * Reads the next byte of data from the input stream. -1 if EOF - */ + */ int XsltInputStream::get() { if (closed) return -1; if (outpos >= outsize) return -1; - int ch = (int) outbuf[outpos++]; + int ch = (int)outbuf[outpos++]; return ch; } - - - - - //######################################################################### //# X S L T O U T P U T S T R E A M @@ -159,44 +143,44 @@ int XsltInputStream::get() /** * - */ + */ XsltOutputStream::XsltOutputStream(OutputStream &dest, XsltStyleSheet &sheet) - : BasicOutputStream(dest), stylesheet(sheet) + : BasicOutputStream(dest) + , stylesheet(sheet) { flushed = false; } /** * - */ + */ XsltOutputStream::~XsltOutputStream() { - //do not automatically close + // do not automatically close } /** * Closes this output stream and releases any system resources * associated with this stream. - */ + */ void XsltOutputStream::close() { flush(); destination.close(); } - + /** * Flushes this output stream and forces any buffered output * bytes to be written out. - */ + */ void XsltOutputStream::flush() { - if (flushed) - { + if (flushed) { destination.flush(); return; - } - - //Do the processing + } + + // Do the processing xmlChar *resbuf; int resSize; const char *params[1]; @@ -212,37 +196,31 @@ void XsltOutputStream::flush() } */ - for (int i=0 ; i #include +#include "inkscapestream.h" -namespace Inkscape -{ -namespace IO -{ +namespace Inkscape { +namespace IO { //######################################################################### //# X S L T S T Y L E S H E E T @@ -34,9 +30,7 @@ namespace IO */ class XsltStyleSheet { - public: - /** * Constructor with loading */ @@ -56,13 +50,11 @@ public: * Destructor */ virtual ~XsltStyleSheet(); - - xsltStylesheetPtr stylesheet; + xsltStylesheetPtr stylesheet; }; // class XsltStyleSheet - //######################################################################### //# X S L T I N P U T S T R E A M //######################################################################### @@ -72,22 +64,18 @@ public: */ class XsltInputStream : public BasicInputStream { - public: - XsltInputStream(InputStream &xmlSource, XsltStyleSheet &stylesheet); - + ~XsltInputStream() override; - + int available() override; - + void close() override; - + int get() override; - private: - XsltStyleSheet &stylesheet; xmlChar *outbuf; @@ -96,9 +84,6 @@ private: }; // class XsltInputStream - - - //######################################################################### //# X S L T O U T P U T S T R E A M //######################################################################### @@ -108,33 +93,27 @@ private: */ class XsltOutputStream : public BasicOutputStream { - public: - XsltOutputStream(OutputStream &destination, XsltStyleSheet &stylesheet); - + ~XsltOutputStream() override; - + void close() override; - + void flush() override; - + int put(char ch) override; private: - XsltStyleSheet &stylesheet; Glib::ustring outbuf; - + bool flushed; }; // class XsltOutputStream - - } // namespace IO } // namespace Inkscape - #endif /* __INKSCAPE_IO_XSLTSTREAM_H__ */ diff --git a/src/io/sys.cpp b/src/io/sys.cpp index 53316a1594fdf5c7e813d73475238aaeedaa2274..45253b8c39ab069c064b6e1cdb5ad66e77cfe27a 100644 --- a/src/io/sys.cpp +++ b/src/io/sys.cpp @@ -11,7 +11,6 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include #ifdef _WIN32 #include @@ -36,44 +35,37 @@ void dump_ustr(Glib::ustring const &ustr); extern guint update_in_progress; - -void Inkscape::IO::dump_fopen_call( char const *utf8name, char const *id ) +void Inkscape::IO::dump_fopen_call(char const *utf8name, char const *id) { #ifdef INK_DUMP_FOPEN Glib::ustring str; - for ( int i = 0; utf8name[i]; i++ ) - { - if ( utf8name[i] == '\\' ) - { + for (int i = 0; utf8name[i]; i++) { + if (utf8name[i] == '\\') { str += "\\\\"; - } - else if ( (utf8name[i] >= 0x20) && ((0x0ff & utf8name[i]) <= 0x7f) ) - { + } else if ((utf8name[i] >= 0x20) && ((0x0ff & utf8name[i]) <= 0x7f)) { str += utf8name[i]; - } - else - { + } else { gchar tmp[32]; - g_snprintf( tmp, sizeof(tmp), "\\x%02x", (0x0ff & utf8name[i]) ); + g_snprintf(tmp, sizeof(tmp), "\\x%02x", (0x0ff & utf8name[i])); str += tmp; } } - g_message( "fopen call %s for [%s]", id, str.data() ); + g_message("fopen call %s for [%s]", id, str.data()); #else (void)utf8name; (void)id; #endif } -FILE *Inkscape::IO::fopen_utf8name( char const *utf8name, char const *mode ) +FILE *Inkscape::IO::fopen_utf8name(char const *utf8name, char const *mode) { - FILE* fp = nullptr; + FILE *fp = nullptr; - if (Glib::ustring( utf8name ) == Glib::ustring("-")) { + if (Glib::ustring(utf8name) == Glib::ustring("-")) { // user requests to use pipes - Glib::ustring how( mode ); - if ( how.find("w") != Glib::ustring::npos ) { + Glib::ustring how(mode); + if (how.find("w") != Glib::ustring::npos) { #ifdef _WIN32 setmode(fileno(stdout), O_BINARY); #endif @@ -83,18 +75,15 @@ FILE *Inkscape::IO::fopen_utf8name( char const *utf8name, char const *mode ) } } - gchar *filename = g_filename_from_utf8( utf8name, -1, nullptr, nullptr, nullptr ); - if ( filename ) - { + gchar *filename = g_filename_from_utf8(utf8name, -1, nullptr, nullptr, nullptr); + if (filename) { // ensure we open the file in binary mode (not needed in POSIX but doesn't hurt either) - Glib::ustring how( mode ); - if ( how.find("b") == Glib::ustring::npos ) - { + Glib::ustring how(mode); + if (how.find("b") == Glib::ustring::npos) { how.append("b"); } // when opening a file for writing: create parent directories if they don't exist already - if ( how.find("w") != Glib::ustring::npos ) - { + if (how.find("w") != Glib::ustring::npos) { gchar *dirname = g_path_get_dirname(utf8name); if (g_mkdir_with_parents(dirname, 0777)) { g_warning("Could not create directory '%s'", dirname); @@ -108,13 +97,11 @@ FILE *Inkscape::IO::fopen_utf8name( char const *utf8name, char const *mode ) return fp; } - -int Inkscape::IO::mkdir_utf8name( char const *utf8name ) +int Inkscape::IO::mkdir_utf8name(char const *utf8name) { int retval = -1; - gchar *filename = g_filename_from_utf8( utf8name, -1, nullptr, nullptr, nullptr ); - if ( filename ) - { + gchar *filename = g_filename_from_utf8(utf8name, -1, nullptr, nullptr, nullptr); + if (filename) { retval = g_mkdir(filename, S_IRWXU | S_IRGRP | S_IXGRP); // The mode argument is ignored on Windows. g_free(filename); filename = nullptr; @@ -122,7 +109,7 @@ int Inkscape::IO::mkdir_utf8name( char const *utf8name ) return retval; } -bool Inkscape::IO::file_test( char const *utf8name, GFileTest test ) +bool Inkscape::IO::file_test(char const *utf8name, GFileTest test) { bool exists = false; @@ -130,7 +117,7 @@ bool Inkscape::IO::file_test( char const *utf8name, GFileTest test ) if (g_strcmp0(utf8name, "-") == 0 && G_FILE_TEST_IS_REGULAR) return true; - if ( utf8name ) { + if (utf8name) { gchar *filename = nullptr; if (utf8name && !g_utf8_validate(utf8name, -1, nullptr)) { /* FIXME: Trying to guess whether or not a filename is already in utf8 is unreliable. @@ -139,27 +126,27 @@ bool Inkscape::IO::file_test( char const *utf8name, GFileTest test ) to beginning of this function. */ filename = g_strdup(utf8name); // Looks like g_get_home_dir isn't safe. - //g_warning("invalid UTF-8 detected internally. HUNT IT DOWN AND KILL IT!!!"); + // g_warning("invalid UTF-8 detected internally. HUNT IT DOWN AND KILL IT!!!"); } else { - filename = g_filename_from_utf8 ( utf8name, -1, nullptr, nullptr, nullptr ); + filename = g_filename_from_utf8(utf8name, -1, nullptr, nullptr, nullptr); } - if ( filename ) { - exists = g_file_test (filename, test); + if (filename) { + exists = g_file_test(filename, test); g_free(filename); filename = nullptr; } else { - g_warning( "Unable to convert filename in IO:file_test" ); + g_warning("Unable to convert filename in IO:file_test"); } } return exists; } -bool Inkscape::IO::file_is_writable( char const *utf8name) +bool Inkscape::IO::file_is_writable(char const *utf8name) { bool success = true; - if ( utf8name) { + if (utf8name) { gchar *filename = nullptr; if (utf8name && !g_utf8_validate(utf8name, -1, nullptr)) { /* FIXME: Trying to guess whether or not a filename is already in utf8 is unreliable. @@ -168,21 +155,21 @@ bool Inkscape::IO::file_is_writable( char const *utf8name) to beginning of this function. */ filename = g_strdup(utf8name); // Looks like g_get_home_dir isn't safe. - //g_warning("invalid UTF-8 detected internally. HUNT IT DOWN AND KILL IT!!!"); + // g_warning("invalid UTF-8 detected internally. HUNT IT DOWN AND KILL IT!!!"); } else { - filename = g_filename_from_utf8 ( utf8name, -1, nullptr, nullptr, nullptr ); + filename = g_filename_from_utf8(utf8name, -1, nullptr, nullptr, nullptr); } - if ( filename ) { + if (filename) { GStatBuf st; - if (g_file_test (filename, G_FILE_TEST_EXISTS)){ - if (g_lstat (filename, &st) == 0) { + if (g_file_test(filename, G_FILE_TEST_EXISTS)) { + if (g_lstat(filename, &st) == 0) { success = ((st.st_mode & S_IWRITE) != 0); } } g_free(filename); filename = nullptr; } else { - g_warning( "Unable to convert filename in IO:file_test" ); + g_warning("Unable to convert filename in IO:file_test"); } } @@ -191,10 +178,11 @@ bool Inkscape::IO::file_is_writable( char const *utf8name) /**Checks if directory of file exists, useful * because inkscape doesn't create directories.*/ -bool Inkscape::IO::file_directory_exists( char const *utf8name ){ +bool Inkscape::IO::file_directory_exists(char const *utf8name) +{ bool exists = true; - if ( utf8name) { + if (utf8name) { gchar *filename = nullptr; if (utf8name && !g_utf8_validate(utf8name, -1, nullptr)) { /* FIXME: Trying to guess whether or not a filename is already in utf8 is unreliable. @@ -203,29 +191,27 @@ bool Inkscape::IO::file_directory_exists( char const *utf8name ){ to beginning of this function. */ filename = g_strdup(utf8name); // Looks like g_get_home_dir isn't safe. - //g_warning("invalid UTF-8 detected internally. HUNT IT DOWN AND KILL IT!!!"); + // g_warning("invalid UTF-8 detected internally. HUNT IT DOWN AND KILL IT!!!"); } else { - filename = g_filename_from_utf8 ( utf8name, -1, nullptr, nullptr, nullptr ); + filename = g_filename_from_utf8(utf8name, -1, nullptr, nullptr, nullptr); } - if ( filename ) { + if (filename) { gchar *dirname = g_path_get_dirname(filename); - exists = Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS); + exists = Inkscape::IO::file_test(dirname, G_FILE_TEST_EXISTS); g_free(filename); g_free(dirname); filename = nullptr; dirname = nullptr; } else { - g_warning( "Unable to convert filename in IO:file_test" ); + g_warning("Unable to convert filename in IO:file_test"); } } return exists; - } /** Wrapper around g_dir_open, but taking a utf8name as first argument. */ -GDir * -Inkscape::IO::dir_open(gchar const *const utf8name, guint const flags, GError **const error) +GDir *Inkscape::IO::dir_open(gchar const *const utf8name, guint const flags, GError **const error) { gchar *const opsys_name = g_filename_from_utf8(utf8name, -1, nullptr, nullptr, error); if (opsys_name) { @@ -242,8 +228,7 @@ Inkscape::IO::dir_open(gchar const *const utf8name, guint const flags, GError ** * * N.B. Skips over any dir entries that fail to convert to utf8. */ -gchar * -Inkscape::IO::dir_read_utf8name(GDir *dir) +gchar *Inkscape::IO::dir_read_utf8name(GDir *dir) { for (;;) { gchar const *const opsys_name = g_dir_read_name(dir); @@ -257,79 +242,61 @@ Inkscape::IO::dir_read_utf8name(GDir *dir) } } - -gchar* Inkscape::IO::locale_to_utf8_fallback( const gchar *opsysstring, - gssize len, - gsize *bytes_read, - gsize *bytes_written, - GError **error ) +gchar *Inkscape::IO::locale_to_utf8_fallback(const gchar *opsysstring, gssize len, gsize *bytes_read, + gsize *bytes_written, GError **error) { gchar *result = nullptr; - if ( opsysstring ) { - gchar *newFileName = g_locale_to_utf8( opsysstring, len, bytes_read, bytes_written, error ); - if ( newFileName ) { - if ( !g_utf8_validate(newFileName, -1, nullptr) ) { - g_warning( "input filename did not yield UTF-8" ); - g_free( newFileName ); + if (opsysstring) { + gchar *newFileName = g_locale_to_utf8(opsysstring, len, bytes_read, bytes_written, error); + if (newFileName) { + if (!g_utf8_validate(newFileName, -1, nullptr)) { + g_warning("input filename did not yield UTF-8"); + g_free(newFileName); } else { result = newFileName; } newFileName = nullptr; - } else if ( g_utf8_validate(opsysstring, -1, nullptr) ) { + } else if (g_utf8_validate(opsysstring, -1, nullptr)) { // This *might* be a case that we want // g_warning( "input failed filename->utf8, fell back to original" ); // TODO handle cases when len >= 0 - result = g_strdup( opsysstring ); + result = g_strdup(opsysstring); } else { gchar const *charset = nullptr; g_get_charset(&charset); - g_warning( "input filename conversion failed for file with locale charset '%s'", charset ); + g_warning("input filename conversion failed for file with locale charset '%s'", charset); } } return result; } -void -Inkscape::IO::spawn_async_with_pipes( const std::string& working_directory, - const std::vector& argv, - Glib::SpawnFlags flags, - const sigc::slot& child_setup, - Glib::Pid* child_pid, - int* standard_input, - int* standard_output, - int* standard_error) +void Inkscape::IO::spawn_async_with_pipes(const std::string &working_directory, const std::vector &argv, + Glib::SpawnFlags flags, const sigc::slot &child_setup, + Glib::Pid *child_pid, int *standard_input, int *standard_output, + int *standard_error) { - Glib::spawn_async_with_pipes(working_directory, - argv, - flags, - child_setup, - child_pid, - standard_input, - standard_output, - standard_error); + Glib::spawn_async_with_pipes(working_directory, argv, flags, child_setup, child_pid, standard_input, + standard_output, standard_error); } - -gchar* Inkscape::IO::sanitizeString( gchar const * str ) +gchar *Inkscape::IO::sanitizeString(gchar const *str) { gchar *result = nullptr; - if ( str ) { - if ( g_utf8_validate(str, -1, nullptr) ) { + if (str) { + if (g_utf8_validate(str, -1, nullptr)) { result = g_strdup(str); } else { guchar scratch[8]; Glib::ustring buf; - guchar const *ptr = (guchar const*)str; - while ( *ptr ) - { - if ( *ptr == '\\' ) - { + guchar const *ptr = (guchar const *)str; + while (*ptr) { + if (*ptr == '\\') { buf.append("\\\\"); - } else if ( *ptr < 0x80 ) { + } else if (*ptr < 0x80) { buf += (char)(*ptr); } else { - g_snprintf((gchar*)scratch, sizeof(scratch), "\\x%02x", *ptr); - buf.append((const char*)scratch); + g_snprintf((gchar *)scratch, sizeof(scratch), "\\x%02x", *ptr); + buf.append((const char *)scratch); } ptr++; } @@ -339,7 +306,7 @@ gchar* Inkscape::IO::sanitizeString( gchar const * str ) return result; } -/* +/* * Returns the file extension of a path/filename */ Glib::ustring Inkscape::IO::get_file_extension(Glib::ustring path) diff --git a/src/io/sys.h b/src/io/sys.h index 61041e725544042d3a17b194bf3175629be2e9a1..1d1d4ec2cc5fe88f4b19899270421bc4c24835c9 100644 --- a/src/io/sys.h +++ b/src/io/sys.h @@ -14,11 +14,11 @@ */ #include -#include -#include #include #include #include +#include +#include #include /*##################### @@ -28,43 +28,34 @@ namespace Inkscape { namespace IO { -void dump_fopen_call( char const *utf8name, char const *id ); +void dump_fopen_call(char const *utf8name, char const *id); -FILE *fopen_utf8name( char const *utf8name, char const *mode ); +FILE *fopen_utf8name(char const *utf8name, char const *mode); -int mkdir_utf8name( char const *utf8name ); +int mkdir_utf8name(char const *utf8name); -bool file_test( char const *utf8name, GFileTest test ); +bool file_test(char const *utf8name, GFileTest test); -bool file_directory_exists( char const *utf8name ); +bool file_directory_exists(char const *utf8name); -bool file_is_writable( char const *utf8name); +bool file_is_writable(char const *utf8name); GDir *dir_open(gchar const *utf8name, guint flags, GError **error); gchar *dir_read_utf8name(GDir *dir); -gchar* locale_to_utf8_fallback( const gchar *opsysstring, - gssize len, - gsize *bytes_read, - gsize *bytes_written, - GError **error ); +gchar *locale_to_utf8_fallback(const gchar *opsysstring, gssize len, gsize *bytes_read, gsize *bytes_written, + GError **error); -gchar* sanitizeString( gchar const * str ); +gchar *sanitizeString(gchar const *str); -void spawn_async_with_pipes (const std::string& working_directory, - const std::vector& argv, - Glib::SpawnFlags flags, - const sigc::slot& child_setup, - Glib::Pid* child_pid, - int* standard_input, - int* standard_output, - int* standard_error); +void spawn_async_with_pipes(const std::string &working_directory, const std::vector &argv, + Glib::SpawnFlags flags, const sigc::slot &child_setup, Glib::Pid *child_pid, + int *standard_input, int *standard_output, int *standard_error); Glib::ustring get_file_extension(Glib::ustring path); -} -} - +} // namespace IO +} // namespace Inkscape #endif // SEEN_SYS_H diff --git a/src/knot-enums.h b/src/knot-enums.h index 47ae978a323f33540f923c79e1fb2d1c62703c30..6896f17bb482ed2cf84b30974317474521396417 100644 --- a/src/knot-enums.h +++ b/src/knot-enums.h @@ -4,7 +4,7 @@ /** * @file - * Some enums used by SPKnot and by related types \& functions. + * Some enums used by SPKnot and by related types \& functions. */ /* * Authors: @@ -16,7 +16,8 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -enum SPKnotShapeType { +enum SPKnotShapeType +{ SP_KNOT_SHAPE_SQUARE, SP_KNOT_SHAPE_DIAMOND, SP_KNOT_SHAPE_CIRCLE, @@ -26,12 +27,14 @@ enum SPKnotShapeType { SP_KNOT_SHAPE_IMAGE }; -enum SPKnotModeType { +enum SPKnotModeType +{ SP_KNOT_MODE_COLOR, SP_KNOT_MODE_XOR }; -enum SPKnotStateType { +enum SPKnotStateType +{ SP_KNOT_STATE_NORMAL, SP_KNOT_STATE_MOUSEOVER, SP_KNOT_STATE_DRAGGING, @@ -41,7 +44,8 @@ enum SPKnotStateType { #define SP_KNOT_VISIBLE_STATES 4 -enum { +enum +{ SP_KNOT_VISIBLE = 1 << 0, SP_KNOT_MOUSEOVER = 1 << 1, SP_KNOT_DRAGGING = 1 << 2, @@ -49,7 +53,6 @@ enum { SP_KNOT_SELECTED = 1 << 4 }; - #endif /* !SEEN_KNOT_ENUMS_H */ /* diff --git a/src/knot-holder-entity.cpp b/src/knot-holder-entity.cpp index c7dffe13f5e7f200d50f39f5f6f0331ccb2a8a9b..78fd15f51929eb184070777ab43f51eae34e0d63 100644 --- a/src/knot-holder-entity.cpp +++ b/src/knot-holder-entity.cpp @@ -21,22 +21,19 @@ #include "desktop.h" #include "inkscape.h" #include "knotholder.h" -#include "preferences.h" -#include "snap.h" -#include "style.h" - #include "live_effects/effect.h" #include "object/sp-hatch.h" #include "object/sp-item.h" #include "object/sp-namedview.h" #include "object/sp-pattern.h" - +#include "preferences.h" +#include "snap.h" +#include "style.h" int KnotHolderEntity::counter = 0; void KnotHolderEntity::create(SPDesktop *desktop, SPItem *item, KnotHolder *parent, Inkscape::ControlType type, - const gchar *tip, - SPKnotShapeType shape, SPKnotModeType mode, guint32 color) + const gchar *tip, SPKnotShapeType shape, SPKnotModeType mode, guint32 color) { if (!desktop) { desktop = parent->getDesktop(); @@ -60,19 +57,20 @@ void KnotHolderEntity::create(SPDesktop *desktop, SPItem *item, KnotHolder *pare // TODO base more appearance from this type instead of passing in arbitrary values. knot->item->ctrlType = type; - knot->fill [SP_KNOT_STATE_NORMAL] = color; - g_object_set (G_OBJECT(knot->item), "fill_color", color, NULL); + knot->fill[SP_KNOT_STATE_NORMAL] = color; + g_object_set(G_OBJECT(knot->item), "fill_color", color, NULL); update_knot(); knot->show(); - _mousedown_connection = knot->mousedown_signal.connect(sigc::mem_fun(*parent_holder, &KnotHolder::knot_mousedown_handler)); + _mousedown_connection = + knot->mousedown_signal.connect(sigc::mem_fun(*parent_holder, &KnotHolder::knot_mousedown_handler)); _moved_connection = knot->moved_signal.connect(sigc::mem_fun(*parent_holder, &KnotHolder::knot_moved_handler)); _click_connection = knot->click_signal.connect(sigc::mem_fun(*parent_holder, &KnotHolder::knot_clicked_handler)); - _ungrabbed_connection = knot->ungrabbed_signal.connect(sigc::mem_fun(*parent_holder, &KnotHolder::knot_ungrabbed_handler)); + _ungrabbed_connection = + knot->ungrabbed_signal.connect(sigc::mem_fun(*parent_holder, &KnotHolder::knot_ungrabbed_handler)); } - KnotHolderEntity::~KnotHolderEntity() { _mousedown_connection.disconnect(); @@ -82,7 +80,7 @@ KnotHolderEntity::~KnotHolderEntity() /* unref should call destroy */ if (knot) { - //g_object_unref(knot); + // g_object_unref(knot); knot_unref(knot); } else { // FIXME: This shouldn't occur. Perhaps it is caused by LPE PointParams being knotholder entities, too @@ -91,8 +89,7 @@ KnotHolderEntity::~KnotHolderEntity() } } -void -KnotHolderEntity::update_knot() +void KnotHolderEntity::update_knot() { Geom::Point knot_pos(knot_get()); if (knot_pos.isFinite()) { @@ -107,14 +104,13 @@ KnotHolderEntity::update_knot() } } -Geom::Point -KnotHolderEntity::snap_knot_position(Geom::Point const &p, guint state) +Geom::Point KnotHolderEntity::snap_knot_position(Geom::Point const &p, guint state) { if (state & GDK_SHIFT_MASK) { // Don't snap when shift-key is held return p; } - Geom::Affine const i2dt (parent_holder->getEditTransform() * item->i2dt_affine()); + Geom::Affine const i2dt(parent_holder->getEditTransform() * item->i2dt_affine()); Geom::Point s = p * i2dt; SnapManager &m = desktop->namedview->snap_manager; @@ -125,14 +121,15 @@ KnotHolderEntity::snap_knot_position(Geom::Point const &p, guint state) return s * i2dt.inverse(); } -Geom::Point -KnotHolderEntity::snap_knot_position_constrained(Geom::Point const &p, Inkscape::Snapper::SnapConstraint const &constraint, guint state) +Geom::Point KnotHolderEntity::snap_knot_position_constrained(Geom::Point const &p, + Inkscape::Snapper::SnapConstraint const &constraint, + guint state) { if (state & GDK_SHIFT_MASK) { // Don't snap when shift-key is held return p; } - Geom::Affine const i2d (parent_holder->getEditTransform() * item->i2dt_affine()); + Geom::Affine const i2d(parent_holder->getEditTransform() * item->i2dt_affine()); Geom::Point s = p * i2d; SnapManager &m = desktop->namedview->snap_manager; @@ -140,15 +137,16 @@ KnotHolderEntity::snap_knot_position_constrained(Geom::Point const &p, Inkscape: // constrainedSnap() will first project the point p onto the constraint line and then try to snap along that line. // This way the constraint is already enforced, no need to worry about that later on - Inkscape::Snapper::SnapConstraint transformed_constraint = Inkscape::Snapper::SnapConstraint(constraint.getPoint() * i2d, (constraint.getPoint() + constraint.getDirection()) * i2d - constraint.getPoint() * i2d); + Inkscape::Snapper::SnapConstraint transformed_constraint = Inkscape::Snapper::SnapConstraint( + constraint.getPoint() * i2d, + (constraint.getPoint() + constraint.getDirection()) * i2d - constraint.getPoint() * i2d); m.constrainedSnapReturnByRef(s, Inkscape::SNAPSOURCE_NODE_HANDLE, transformed_constraint); m.unSetup(); return s * i2d.inverse(); } -void -LPEKnotHolderEntity::knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) +void LPEKnotHolderEntity::knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) { Inkscape::LivePathEffect::Effect *effect = _effect; if (effect) { @@ -159,15 +157,16 @@ LPEKnotHolderEntity::knot_ungrabbed(Geom::Point const &p, Geom::Point const &ori /* Pattern manipulation */ -/* TODO: this pattern manipulation is not able to handle general transformation matrices. Only matrices that are the result of a pure scale times a pure rotation. */ +/* TODO: this pattern manipulation is not able to handle general transformation matrices. Only matrices that are the + * result of a pure scale times a pure rotation. */ -void -PatternKnotHolderEntityXY::knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) +void PatternKnotHolderEntityXY::knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) { - // FIXME: this snapping should be done together with knowing whether control was pressed. If GDK_CONTROL_MASK, then constrained snapping should be used. + // FIXME: this snapping should be done together with knowing whether control was pressed. If GDK_CONTROL_MASK, then + // constrained snapping should be used. Geom::Point p_snapped = snap_knot_position(p, state); - if ( state & GDK_CONTROL_MASK ) { + if (state & GDK_CONTROL_MASK) { if (fabs((p - origin)[Geom::X]) > fabs((p - origin)[Geom::Y])) { p_snapped[Geom::Y] = origin[Geom::Y]; } else { @@ -175,7 +174,7 @@ PatternKnotHolderEntityXY::knot_set(Geom::Point const &p, Geom::Point const &ori } } - if (state) { + if (state) { Geom::Point const q = p_snapped - knot_get(); item->adjust_pattern(Geom::Translate(q), false, _fill ? TRANSFORM_FILL : TRANSFORM_STROKE); } @@ -188,72 +187,66 @@ static Geom::Point sp_pattern_knot_get(SPPattern const *pat, gdouble x, gdouble return Geom::Point(x, y) * pat->getTransform(); } -bool -PatternKnotHolderEntity::knot_missing() const +bool PatternKnotHolderEntity::knot_missing() const { SPPattern *pat = _pattern(); return (pat == nullptr); } -SPPattern* -PatternKnotHolderEntity::_pattern() const +SPPattern *PatternKnotHolderEntity::_pattern() const { return _fill ? SP_PATTERN(item->style->getFillPaintServer()) : SP_PATTERN(item->style->getStrokePaintServer()); } -Geom::Point -PatternKnotHolderEntityXY::knot_get() const +Geom::Point PatternKnotHolderEntityXY::knot_get() const { SPPattern *pat = _pattern(); return sp_pattern_knot_get(pat, 0, 0); } -Geom::Point -PatternKnotHolderEntityAngle::knot_get() const +Geom::Point PatternKnotHolderEntityAngle::knot_get() const { SPPattern *pat = _pattern(); return sp_pattern_knot_get(pat, pat->width(), 0); } -Geom::Point -PatternKnotHolderEntityScale::knot_get() const +Geom::Point PatternKnotHolderEntityScale::knot_get() const { SPPattern *pat = _pattern(); return sp_pattern_knot_get(pat, pat->width(), pat->height()); } -void -PatternKnotHolderEntityAngle::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) +void PatternKnotHolderEntityAngle::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int const snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12); - SPPattern *pat = _fill ? SP_PATTERN(item->style->getFillPaintServer()) : SP_PATTERN(item->style->getStrokePaintServer()); + SPPattern *pat = + _fill ? SP_PATTERN(item->style->getFillPaintServer()) : SP_PATTERN(item->style->getStrokePaintServer()); // get the angle from pattern 0,0 to the cursor pos Geom::Point transform_origin = sp_pattern_knot_get(pat, 0, 0); gdouble theta = atan2(p - transform_origin); gdouble theta_old = atan2(knot_get() - transform_origin); - if ( state & GDK_CONTROL_MASK ) { + if (state & GDK_CONTROL_MASK) { /* Snap theta */ - double snaps_radian = M_PI/snaps; - theta = std::round(theta/snaps_radian) * snaps_radian; + double snaps_radian = M_PI / snaps; + theta = std::round(theta / snaps_radian) * snaps_radian; } - Geom::Affine rot = Geom::Translate(-transform_origin) - * Geom::Rotate(theta - theta_old) - * Geom::Translate(transform_origin); + Geom::Affine rot = + Geom::Translate(-transform_origin) * Geom::Rotate(theta - theta_old) * Geom::Translate(transform_origin); item->adjust_pattern(rot, false, _fill ? TRANSFORM_FILL : TRANSFORM_STROKE); item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void -PatternKnotHolderEntityScale::knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) +void PatternKnotHolderEntityScale::knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) { SPPattern *pat = _pattern(); - // FIXME: this snapping should be done together with knowing whether control was pressed. If GDK_CONTROL_MASK, then constrained snapping should be used. + // FIXME: this snapping should be done together with knowing whether control was pressed. If GDK_CONTROL_MASK, then + // constrained snapping should be used. Geom::Point p_snapped = snap_knot_position(p, state); // Get the new scale from the position of the knotholder @@ -264,15 +257,13 @@ PatternKnotHolderEntityScale::knot_set(Geom::Point const &p, Geom::Point const & Geom::Point origin_dt; gdouble pat_x = pat->width(); gdouble pat_y = pat->height(); - if ( state & GDK_CONTROL_MASK ) { + if (state & GDK_CONTROL_MASK) { // if ctrl is pressed: use 1:1 scaling d = d_origin * (d.length() / d_origin.length()); } - Geom::Affine rot = Geom::Translate(-origin_dt) - * Geom::Scale(d.x() / pat_x, d.y() / pat_y) - * Geom::Translate(origin_dt) - * transform; + Geom::Affine rot = Geom::Translate(-origin_dt) * Geom::Scale(d.x() / pat_x, d.y() / pat_y) * + Geom::Translate(origin_dt) * transform; item->adjust_pattern(rot, true, _fill ? TRANSFORM_FILL : TRANSFORM_STROKE); item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); @@ -347,8 +338,8 @@ void HatchKnotHolderEntityAngle::knot_set(Geom::Point const &p, Geom::Point cons if (state & GDK_CONTROL_MASK) { /* Snap theta */ - double snaps_radian = M_PI/snaps; - theta = std::round(theta/snaps_radian) * snaps_radian; + double snaps_radian = M_PI / snaps; + theta = std::round(theta / snaps_radian) * snaps_radian; } Geom::Affine rot = @@ -387,10 +378,11 @@ void HatchKnotHolderEntityScale::knot_set(Geom::Point const &p, Geom::Point cons /* Filter manipulation */ void FilterKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) { - // FIXME: this snapping should be done together with knowing whether control was pressed. If GDK_CONTROL_MASK, then constrained snapping should be used. + // FIXME: this snapping should be done together with knowing whether control was pressed. If GDK_CONTROL_MASK, then + // constrained snapping should be used. Geom::Point p_snapped = snap_knot_position(p, state); - if ( state & GDK_CONTROL_MASK ) { + if (state & GDK_CONTROL_MASK) { if (fabs((p - origin)[Geom::X]) > fabs((p - origin)[Geom::Y])) { p_snapped[Geom::Y] = origin[Geom::Y]; } else { @@ -398,11 +390,13 @@ void FilterKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const &o } } - if (state) { + if (state) { SPFilter *filter = (item->style) ? item->style->getFilter() : nullptr; - if(!filter) return; + if (!filter) + return; Geom::OptRect orig_bbox = item->visualBounds(); - std::unique_ptr new_bbox(_topleft ? new Geom::Rect(p,orig_bbox->max()) : new Geom::Rect(orig_bbox->min(), p)); + std::unique_ptr new_bbox(_topleft ? new Geom::Rect(p, orig_bbox->max()) + : new Geom::Rect(orig_bbox->min(), p)); if (!filter->width._set) { filter->width.set(SVGLength::PERCENT, 1.2); @@ -417,24 +411,24 @@ void FilterKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const &o filter->y.set(SVGLength::PERCENT, -0.1); } - if(_topleft) { + if (_topleft) { float x_a = filter->width.computed; float y_a = filter->height.computed; - filter->height.scale(new_bbox->height()/orig_bbox->height()); - filter->width.scale(new_bbox->width()/orig_bbox->width()); + filter->height.scale(new_bbox->height() / orig_bbox->height()); + filter->width.scale(new_bbox->width() / orig_bbox->width()); float x_b = filter->width.computed; float y_b = filter->height.computed; filter->x.set(filter->x.unit, filter->x.computed + x_a - x_b); filter->y.set(filter->y.unit, filter->y.computed + y_a - y_b); } else { - filter->height.scale(new_bbox->height()/orig_bbox->height()); - filter->width.scale(new_bbox->width()/orig_bbox->width()); + filter->height.scale(new_bbox->height() / orig_bbox->height()); + filter->width.scale(new_bbox->width() / orig_bbox->width()); } filter->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - //filter-> + // filter-> - //item-> //adjust FER + // item-> //adjust FER } item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); @@ -443,10 +437,13 @@ void FilterKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const &o Geom::Point FilterKnotHolderEntity::knot_get() const { SPFilter *filter = (item->style) ? item->style->getFilter() : nullptr; - if(!filter) return Geom::Point(Geom::infinity(), Geom::infinity()); + if (!filter) + return Geom::Point(Geom::infinity(), Geom::infinity()); Geom::OptRect r = item->visualBounds(); - if (_topleft) return Geom::Point(r->min()); - else return Geom::Point(r->max()); + if (_topleft) + return Geom::Point(r->min()); + else + return Geom::Point(r->max()); } /* diff --git a/src/knot-holder-entity.h b/src/knot-holder-entity.h index 0a63bf7e158d5fe8f50a3883e9bda83d5bba81c0..83eb967341164a227144a1eb72ef9fba2323ae0b 100644 --- a/src/knot-holder-entity.h +++ b/src/knot-holder-entity.h @@ -30,35 +30,34 @@ class KnotHolder; namespace Inkscape { namespace LivePathEffect { - class Effect; +class Effect; } // namespace LivePathEffect } // namespace Inkscape -typedef void (* SPKnotHolderSetFunc) (SPItem *item, Geom::Point const &p, Geom::Point const &origin, unsigned int state); -typedef Geom::Point (* SPKnotHolderGetFunc) (SPItem *item); +typedef void (*SPKnotHolderSetFunc)(SPItem *item, Geom::Point const &p, Geom::Point const &origin, unsigned int state); +typedef Geom::Point (*SPKnotHolderGetFunc)(SPItem *item); /** * KnotHolderEntity definition. */ -class KnotHolderEntity { +class KnotHolderEntity +{ public: - KnotHolderEntity(): - knot(nullptr), - item(nullptr), - desktop(nullptr), - parent_holder(nullptr), - my_counter(0), - handler_id(0), - _click_handler_id(0), - _ungrab_handler_id(0) - {} + KnotHolderEntity() + : knot(nullptr) + , item(nullptr) + , desktop(nullptr) + , parent_holder(nullptr) + , my_counter(0) + , handler_id(0) + , _click_handler_id(0) + , _ungrab_handler_id(0) + {} virtual ~KnotHolderEntity(); virtual void create(SPDesktop *desktop, SPItem *item, KnotHolder *parent, - Inkscape::ControlType type = Inkscape::CTRL_TYPE_UNKNOWN, - char const*tip = "", - SPKnotShapeType shape = SP_KNOT_SHAPE_DIAMOND, - SPKnotModeType mode = SP_KNOT_MODE_XOR, + Inkscape::ControlType type = Inkscape::CTRL_TYPE_UNKNOWN, char const *tip = "", + SPKnotShapeType shape = SP_KNOT_SHAPE_DIAMOND, SPKnotModeType mode = SP_KNOT_MODE_XOR, guint32 color = 0xffffff00); /* the get/set/click handlers are virtual functions; each handler class for a knot @@ -71,9 +70,10 @@ public: void update_knot(); -//private: + // private: Geom::Point snap_knot_position(Geom::Point const &p, unsigned int state); - Geom::Point snap_knot_position_constrained(Geom::Point const &p, Inkscape::Snapper::SnapConstraint const &constraint, unsigned int state); + Geom::Point snap_knot_position_constrained(Geom::Point const &p, + Inkscape::Snapper::SnapConstraint const &constraint, unsigned int state); SPKnot *knot; SPItem *item; @@ -85,11 +85,11 @@ public: static int counter; /** Connection to \a knot's "moved" signal. */ - unsigned int handler_id; + unsigned int handler_id; /** Connection to \a knot's "clicked" signal. */ - unsigned int _click_handler_id; + unsigned int _click_handler_id; /** Connection to \a knot's "ungrabbed" signal. */ - unsigned int _ungrab_handler_id; + unsigned int _ungrab_handler_id; private: sigc::connection _mousedown_connection; @@ -99,104 +99,124 @@ private: }; // derived KnotHolderEntity class for LPEs -class LPEKnotHolderEntity : public KnotHolderEntity { +class LPEKnotHolderEntity : public KnotHolderEntity +{ public: - LPEKnotHolderEntity(Inkscape::LivePathEffect::Effect *effect) : _effect(effect) {}; + LPEKnotHolderEntity(Inkscape::LivePathEffect::Effect *effect) + : _effect(effect){}; void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override; + protected: Inkscape::LivePathEffect::Effect *_effect; }; /* pattern manipulation */ -class PatternKnotHolderEntity : public KnotHolderEntity { - public: - PatternKnotHolderEntity(bool fill) : KnotHolderEntity(), _fill(fill) {} +class PatternKnotHolderEntity : public KnotHolderEntity +{ +public: + PatternKnotHolderEntity(bool fill) + : KnotHolderEntity() + , _fill(fill) + {} bool knot_missing() const override; void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; - protected: +protected: // true if the entity tracks fill, false for stroke bool _fill; SPPattern *_pattern() const; }; -class PatternKnotHolderEntityXY : public PatternKnotHolderEntity { +class PatternKnotHolderEntityXY : public PatternKnotHolderEntity +{ public: - PatternKnotHolderEntityXY(bool fill) : PatternKnotHolderEntity(fill) {} + PatternKnotHolderEntityXY(bool fill) + : PatternKnotHolderEntity(fill) + {} Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class PatternKnotHolderEntityAngle : public PatternKnotHolderEntity { +class PatternKnotHolderEntityAngle : public PatternKnotHolderEntity +{ public: - PatternKnotHolderEntityAngle(bool fill) : PatternKnotHolderEntity(fill) {} + PatternKnotHolderEntityAngle(bool fill) + : PatternKnotHolderEntity(fill) + {} Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class PatternKnotHolderEntityScale : public PatternKnotHolderEntity { +class PatternKnotHolderEntityScale : public PatternKnotHolderEntity +{ public: - PatternKnotHolderEntityScale(bool fill) : PatternKnotHolderEntity(fill) {} + PatternKnotHolderEntityScale(bool fill) + : PatternKnotHolderEntity(fill) + {} Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; /* Hatch manipulation */ -class HatchKnotHolderEntity : public KnotHolderEntity { - public: +class HatchKnotHolderEntity : public KnotHolderEntity +{ +public: HatchKnotHolderEntity(bool fill) : KnotHolderEntity() , _fill(fill) - { - } + {} bool knot_missing() const override; void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; - protected: +protected: // true if the entity tracks fill, false for stroke bool _fill; SPHatch *_hatch() const; }; -class HatchKnotHolderEntityXY : public HatchKnotHolderEntity { - public: +class HatchKnotHolderEntityXY : public HatchKnotHolderEntity +{ +public: HatchKnotHolderEntityXY(bool fill) : HatchKnotHolderEntity(fill) - { - } + {} Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class HatchKnotHolderEntityAngle : public HatchKnotHolderEntity { - public: +class HatchKnotHolderEntityAngle : public HatchKnotHolderEntity +{ +public: HatchKnotHolderEntityAngle(bool fill) : HatchKnotHolderEntity(fill) - { - } + {} Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class HatchKnotHolderEntityScale : public HatchKnotHolderEntity { - public: +class HatchKnotHolderEntityScale : public HatchKnotHolderEntity +{ +public: HatchKnotHolderEntityScale(bool fill) : HatchKnotHolderEntity(fill) - { - } + {} Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; - /* Filter manipulation */ -class FilterKnotHolderEntity : public KnotHolderEntity { - public: - FilterKnotHolderEntity(bool topleft) : KnotHolderEntity(), _topleft(topleft) {} +class FilterKnotHolderEntity : public KnotHolderEntity +{ +public: + FilterKnotHolderEntity(bool topleft) + : KnotHolderEntity() + , _topleft(topleft) + {} Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; + private: bool _topleft; // true for topleft point, false for bottomright }; diff --git a/src/knot-ptr.cpp b/src/knot-ptr.cpp index 8e275ac58305ae4b733cc06a494349890b613741..9d467173052eb7c6344c9b5bcf392d9da9e6919b 100644 --- a/src/knot-ptr.cpp +++ b/src/knot-ptr.cpp @@ -7,27 +7,31 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "knot-ptr.h" + #include #include #include -#include "knot-ptr.h" -static std::list deleted_knots; +static std::list deleted_knots; -void knot_deleted_callback(void* knot) { +void knot_deleted_callback(void *knot) +{ if (std::find(deleted_knots.begin(), deleted_knots.end(), knot) == deleted_knots.end()) { deleted_knots.push_back(knot); } } -void knot_created_callback(void* knot) { - std::list::iterator it = std::find(deleted_knots.begin(), deleted_knots.end(), knot); +void knot_created_callback(void *knot) +{ + std::list::iterator it = std::find(deleted_knots.begin(), deleted_knots.end(), knot); if (it != deleted_knots.end()) { deleted_knots.erase(it); } } -void check_if_knot_deleted(void* knot) { +void check_if_knot_deleted(void *knot) +{ if (std::find(deleted_knots.begin(), deleted_knots.end(), knot) != deleted_knots.end()) { g_warning("Accessed knot after it was freed at %p", knot); } diff --git a/src/knot-ptr.h b/src/knot-ptr.h index 5141822440af5e6a7bb9865f9349bbf5826d0056..03afb1c6bc114e951af0e8ba21b454963562f89b 100644 --- a/src/knot-ptr.h +++ b/src/knot-ptr.h @@ -10,8 +10,8 @@ #ifndef KNOT_PTR_DETECTOR #define KNOT_PTR_DETECTOR -void knot_deleted_callback(void* knot); -void knot_created_callback(void* knot); -void check_if_knot_deleted(void* knot); +void knot_deleted_callback(void *knot); +void knot_created_callback(void *knot); +void check_if_knot_deleted(void *knot); #endif diff --git a/src/knot.cpp b/src/knot.cpp index b5b1ec95b95bb5e56e6dcc113aa4932d10d667eb..912e379986e83962ddc80c18dc8e201e368a21a9 100644 --- a/src/knot.cpp +++ b/src/knot.cpp @@ -15,43 +15,40 @@ #ifdef HAVE_CONFIG_H #endif +#include "knot.h" + #include #include -#include "display/sodipodi-ctrl.h" -#include "desktop.h" -#include "knot.h" -#include "knot-ptr.h" -#include "document.h" +#include "desktop.h" +#include "display/sodipodi-ctrl.h" #include "document-undo.h" -#include "message-stack.h" +#include "document.h" +#include "knot-ptr.h" #include "message-context.h" +#include "message-stack.h" #include "ui/tools/node-tool.h" using Inkscape::DocumentUndo; -const int KNOT_EVENT_MASK ( - GDK_BUTTON_PRESS_MASK | - GDK_BUTTON_RELEASE_MASK | - GDK_POINTER_MOTION_MASK | - GDK_KEY_PRESS_MASK | - GDK_KEY_RELEASE_MASK); +const int KNOT_EVENT_MASK(GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | + GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); const gchar *nograbenv = getenv("INKSCAPE_NO_GRAB"); static bool nograb = (nograbenv && *nograbenv && (*nograbenv != '0')); - -void knot_ref(SPKnot* knot) { +void knot_ref(SPKnot *knot) +{ knot->ref_count++; } -void knot_unref(SPKnot* knot) { +void knot_unref(SPKnot *knot) +{ if (--knot->ref_count < 1) { delete knot; } } - static int sp_knot_handler(SPCanvasItem *item, GdkEvent *event, SPKnot *knot); SPKnot::SPKnot(SPDesktop *desktop, gchar const *tip) @@ -59,7 +56,7 @@ SPKnot::SPKnot(SPDesktop *desktop, gchar const *tip) , ref_count(1) { if (tip) { - this->tip = g_strdup (tip); + this->tip = g_strdup(tip); } stroke[SP_KNOT_STATE_NORMAL] = 0x01000000; @@ -77,28 +74,20 @@ SPKnot::SPKnot(SPDesktop *desktop, gchar const *tip) cursor[SP_KNOT_STATE_DRAGGING] = nullptr; cursor[SP_KNOT_STATE_SELECTED] = nullptr; - item = sp_canvas_item_new(desktop->getControls(), - SP_TYPE_CTRL, - "anchor", SP_ANCHOR_CENTER, - "size", 9, - "angle", 0.0, - "filled", true, - "fill_color", 0xffffff00, - "stroked", true, - "stroke_color", 0x01000000, - "mode", SP_KNOT_MODE_XOR, - NULL); + item = sp_canvas_item_new(desktop->getControls(), SP_TYPE_CTRL, "anchor", SP_ANCHOR_CENTER, "size", 9, "angle", 0.0, + "filled", true, "fill_color", 0xffffff00, "stroked", true, "stroke_color", 0x01000000, + "mode", SP_KNOT_MODE_XOR, NULL); item->name = "SPCtrl:Knot"; - _event_handler_id = g_signal_connect(G_OBJECT(this->item), "event", - G_CALLBACK(sp_knot_handler), this); + _event_handler_id = g_signal_connect(G_OBJECT(this->item), "event", G_CALLBACK(sp_knot_handler), this); knot_created_callback(this); } -SPKnot::~SPKnot() { +SPKnot::~SPKnot() +{ auto display = gdk_display_get_default(); - auto seat = gdk_display_get_default_seat(display); - auto device = gdk_seat_get_pointer(seat); + auto seat = gdk_display_get_default_seat(display); + auto device = gdk_seat_get_pointer(seat); if ((this->flags & SP_KNOT_GRABBED) && gdk_display_device_is_grabbed(display, device)) { // This happens e.g. when deleting a node in node tool while dragging it @@ -106,7 +95,7 @@ SPKnot::~SPKnot() { } if (this->_event_handler_id > 0) { - g_signal_handler_disconnect(G_OBJECT (this->item), this->_event_handler_id); + g_signal_handler_disconnect(G_OBJECT(this->item), this->_event_handler_id); this->_event_handler_id = 0; } @@ -115,7 +104,7 @@ SPKnot::~SPKnot() { this->item = nullptr; } - for (auto & i : this->cursor) { + for (auto &i : this->cursor) { if (i) { g_object_unref(i); i = nullptr; @@ -128,11 +117,12 @@ SPKnot::~SPKnot() { } // FIXME: cannot snap to destroyed knot (lp:1309050) - //sp_event_context_discard_delayed_snap_event(this->desktop->event_context); + // sp_event_context_discard_delayed_snap_event(this->desktop->event_context); knot_deleted_callback(this); } -void SPKnot::startDragging(Geom::Point const &p, gint x, gint y, guint32 etime) { +void SPKnot::startDragging(Geom::Point const &p, gint x, gint y, guint32 etime) +{ // save drag origin xp = x; yp = y; @@ -149,14 +139,15 @@ void SPKnot::startDragging(Geom::Point const &p, gint x, gint y, guint32 etime) grabbed = true; } -void SPKnot::selectKnot(bool select){ +void SPKnot::selectKnot(bool select) +{ setFlag(SP_KNOT_SELECTED, select); } /** * Called to handle events on knots. */ -static int sp_knot_handler(SPCanvasItem */*item*/, GdkEvent *event, SPKnot *knot) +static int sp_knot_handler(SPCanvasItem * /*item*/, GdkEvent *event, SPKnot *knot) { g_assert(knot != nullptr); g_assert(SP_IS_KNOT(knot)); @@ -175,175 +166,179 @@ static int sp_knot_handler(SPCanvasItem */*item*/, GdkEvent *event, SPKnot *knot knot->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); switch (event->type) { - case GDK_2BUTTON_PRESS: - if (event->button.button == 1) { - knot->doubleclicked_signal.emit(knot, event->button.state); - - knot->grabbed = false; - knot->moved = false; - consumed = true; - } - break; - case GDK_BUTTON_PRESS: - if ((event->button.button == 1) && knot->desktop && knot->desktop->event_context && !knot->desktop->event_context->space_panning) { - Geom::Point const p = knot->desktop->w2d(Geom::Point(event->button.x, event->button.y)); - knot->startDragging(p, (gint) event->button.x, (gint) event->button.y, event->button.time); - knot->mousedown_signal.emit(knot, event->button.state); - consumed = true; - } - break; - case GDK_BUTTON_RELEASE: - if (event->button.button == 1 && knot->desktop && knot->desktop->event_context && !knot->desktop->event_context->space_panning) { - // If we have any pending snap event, then invoke it now - if (knot->desktop->event_context->_delayed_snap_event) { - sp_event_context_snap_watchdog_callback(knot->desktop->event_context->_delayed_snap_event); - } - sp_event_context_discard_delayed_snap_event(knot->desktop->event_context); - knot->pressure = 0; - - if (knot->transform_escaped) { - knot->transform_escaped = false; - consumed = true; - } else { - knot->setFlag(SP_KNOT_GRABBED, false); - - if (!nograb) { - sp_canvas_item_ungrab(knot->item); - } - - if (knot->moved) { - knot->setFlag(SP_KNOT_DRAGGING, false); - knot->ungrabbed_signal.emit(knot, event->button.state); - } else { - knot->click_signal.emit(knot, event->button.state); - } + case GDK_2BUTTON_PRESS: + if (event->button.button == 1) { + knot->doubleclicked_signal.emit(knot, event->button.state); knot->grabbed = false; knot->moved = false; consumed = true; } - } - Inkscape::UI::Tools::sp_update_helperpath(knot->desktop); - break; - case GDK_MOTION_NOTIFY: - if (!(event->motion.state & GDK_BUTTON1_MASK) && knot->flags & SP_KNOT_DRAGGING) { - // If we have any pending snap event, then invoke it now - if (knot->desktop->event_context->_delayed_snap_event) { - sp_event_context_snap_watchdog_callback(knot->desktop->event_context->_delayed_snap_event); - } - sp_event_context_discard_delayed_snap_event(knot->desktop->event_context); - knot->pressure = 0; - - if (knot->transform_escaped) { - knot->transform_escaped = false; + break; + case GDK_BUTTON_PRESS: + if ((event->button.button == 1) && knot->desktop && knot->desktop->event_context && + !knot->desktop->event_context->space_panning) { + Geom::Point const p = knot->desktop->w2d(Geom::Point(event->button.x, event->button.y)); + knot->startDragging(p, (gint)event->button.x, (gint)event->button.y, event->button.time); + knot->mousedown_signal.emit(knot, event->button.state); consumed = true; - } else { - knot->setFlag(SP_KNOT_GRABBED, false); - - if (!nograb) { - sp_canvas_item_ungrab(knot->item); + } + break; + case GDK_BUTTON_RELEASE: + if (event->button.button == 1 && knot->desktop && knot->desktop->event_context && + !knot->desktop->event_context->space_panning) { + // If we have any pending snap event, then invoke it now + if (knot->desktop->event_context->_delayed_snap_event) { + sp_event_context_snap_watchdog_callback(knot->desktop->event_context->_delayed_snap_event); } + sp_event_context_discard_delayed_snap_event(knot->desktop->event_context); + knot->pressure = 0; - if (knot->moved) { - knot->setFlag(SP_KNOT_DRAGGING, false); - knot->ungrabbed_signal.emit(knot, event->motion.state); + if (knot->transform_escaped) { + knot->transform_escaped = false; + consumed = true; } else { - knot->click_signal.emit(knot, event->motion.state); - } + knot->setFlag(SP_KNOT_GRABBED, false); - knot->grabbed = false; - knot->moved = false; - consumed = true; - Inkscape::UI::Tools::sp_update_helperpath(knot->desktop); - } - } else if (knot->grabbed && knot->desktop && knot->desktop->event_context && - !knot->desktop->event_context->space_panning) { - consumed = true; + if (!nograb) { + sp_canvas_item_ungrab(knot->item); + } + + if (knot->moved) { + knot->setFlag(SP_KNOT_DRAGGING, false); + knot->ungrabbed_signal.emit(knot, event->button.state); + } else { + knot->click_signal.emit(knot, event->button.state); + } - if ( knot->within_tolerance - && ( abs( (gint) event->motion.x - knot->xp ) < knot->tolerance ) - && ( abs( (gint) event->motion.y - knot->yp ) < knot->tolerance ) ) { - break; // do not drag if we're within tolerance from origin + knot->grabbed = false; + knot->moved = false; + consumed = true; + } } + Inkscape::UI::Tools::sp_update_helperpath(knot->desktop); + break; + case GDK_MOTION_NOTIFY: + if (!(event->motion.state & GDK_BUTTON1_MASK) && knot->flags & SP_KNOT_DRAGGING) { + // If we have any pending snap event, then invoke it now + if (knot->desktop->event_context->_delayed_snap_event) { + sp_event_context_snap_watchdog_callback(knot->desktop->event_context->_delayed_snap_event); + } + sp_event_context_discard_delayed_snap_event(knot->desktop->event_context); + knot->pressure = 0; - // 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) - knot->within_tolerance = false; + if (knot->transform_escaped) { + knot->transform_escaped = false; + consumed = true; + } else { + knot->setFlag(SP_KNOT_GRABBED, false); - if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &knot->pressure)) { - knot->pressure = CLAMP (knot->pressure, 0, 1); - } else { - knot->pressure = 0.5; - } + if (!nograb) { + sp_canvas_item_ungrab(knot->item); + } - if (!knot->moved) { - knot->setFlag(SP_KNOT_DRAGGING, true); - knot->grabbed_signal.emit(knot, event->button.state); - } + if (knot->moved) { + knot->setFlag(SP_KNOT_DRAGGING, false); + knot->ungrabbed_signal.emit(knot, event->motion.state); + } else { + knot->click_signal.emit(knot, event->motion.state); + } - sp_event_context_snap_delay_handler(knot->desktop->event_context, nullptr, knot, (GdkEventMotion *)event, Inkscape::UI::Tools::DelayedSnapEvent::KNOT_HANDLER); - sp_knot_handler_request_position(event, knot); - knot->moved = true; - } - break; - case GDK_ENTER_NOTIFY: - knot->setFlag(SP_KNOT_MOUSEOVER, true); - knot->setFlag(SP_KNOT_GRABBED, false); + knot->grabbed = false; + knot->moved = false; + consumed = true; + Inkscape::UI::Tools::sp_update_helperpath(knot->desktop); + } + } else if (knot->grabbed && knot->desktop && knot->desktop->event_context && + !knot->desktop->event_context->space_panning) { + consumed = true; - if (knot->tip && knot->desktop && knot->desktop->event_context) { - knot->desktop->event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, knot->tip); - } + if (knot->within_tolerance && (abs((gint)event->motion.x - knot->xp) < knot->tolerance) && + (abs((gint)event->motion.y - knot->yp) < knot->tolerance)) { + break; // do not drag if we're within tolerance from origin + } - knot->grabbed = false; - knot->moved = false; - consumed = true; - break; - case GDK_LEAVE_NOTIFY: - knot->setFlag(SP_KNOT_MOUSEOVER, false); - knot->setFlag(SP_KNOT_GRABBED, false); + // 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) + knot->within_tolerance = false; - if (knot->tip && knot->desktop && knot->desktop->event_context) { - knot->desktop->event_context->defaultMessageContext()->clear(); - } + if (gdk_event_get_axis(event, GDK_AXIS_PRESSURE, &knot->pressure)) { + knot->pressure = CLAMP(knot->pressure, 0, 1); + } else { + knot->pressure = 0.5; + } - knot->grabbed = false; - knot->moved = false; - consumed = true; - break; - case GDK_KEY_PRESS: // keybindings for knot - switch (Inkscape::UI::Tools::get_latin_keyval(&event->key)) { - case GDK_KEY_Escape: - knot->setFlag(SP_KNOT_GRABBED, false); - - if (!nograb) { - sp_canvas_item_ungrab(knot->item); + if (!knot->moved) { + knot->setFlag(SP_KNOT_DRAGGING, true); + knot->grabbed_signal.emit(knot, event->button.state); } - if (knot->moved) { - knot->setFlag(SP_KNOT_DRAGGING, false); + sp_event_context_snap_delay_handler(knot->desktop->event_context, nullptr, knot, + (GdkEventMotion *)event, + Inkscape::UI::Tools::DelayedSnapEvent::KNOT_HANDLER); + sp_knot_handler_request_position(event, knot); + knot->moved = true; + } + break; + case GDK_ENTER_NOTIFY: + knot->setFlag(SP_KNOT_MOUSEOVER, true); + knot->setFlag(SP_KNOT_GRABBED, false); - knot->ungrabbed_signal.emit(knot, event->button.state); + if (knot->tip && knot->desktop && knot->desktop->event_context) { + knot->desktop->event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, knot->tip); + } - DocumentUndo::undo(knot->desktop->getDocument()); - knot->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Node or handle drag canceled.")); - knot->transform_escaped = true; - consumed = true; - } + knot->grabbed = false; + knot->moved = false; + consumed = true; + break; + case GDK_LEAVE_NOTIFY: + knot->setFlag(SP_KNOT_MOUSEOVER, false); + knot->setFlag(SP_KNOT_GRABBED, false); - knot->grabbed = false; - knot->moved = false; + if (knot->tip && knot->desktop && knot->desktop->event_context) { + knot->desktop->event_context->defaultMessageContext()->clear(); + } - sp_event_context_discard_delayed_snap_event(knot->desktop->event_context); - break; - default: - consumed = false; - key_press_event_unconsumed = true; - break; - } - break; - default: - break; + knot->grabbed = false; + knot->moved = false; + consumed = true; + break; + case GDK_KEY_PRESS: // keybindings for knot + switch (Inkscape::UI::Tools::get_latin_keyval(&event->key)) { + case GDK_KEY_Escape: + knot->setFlag(SP_KNOT_GRABBED, false); + + if (!nograb) { + sp_canvas_item_ungrab(knot->item); + } + + if (knot->moved) { + knot->setFlag(SP_KNOT_DRAGGING, false); + + knot->ungrabbed_signal.emit(knot, event->button.state); + + DocumentUndo::undo(knot->desktop->getDocument()); + knot->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, + _("Node or handle drag canceled.")); + knot->transform_escaped = true; + consumed = true; + } + + knot->grabbed = false; + knot->moved = false; + + sp_event_context_discard_delayed_snap_event(knot->desktop->event_context); + break; + default: + consumed = false; + key_press_event_unconsumed = true; + break; + } + break; + default: + break; } knot_unref(knot); @@ -351,34 +346,39 @@ static int sp_knot_handler(SPCanvasItem */*item*/, GdkEvent *event, SPKnot *knot if (key_press_event_unconsumed) { return false; // e.g. in case "%" was pressed to toggle snapping, or Q for quick zoom (while dragging a handle) } else { - return consumed || knot->grabbed; + return consumed || knot->grabbed; } } -void sp_knot_handler_request_position(GdkEvent *event, SPKnot *knot) { +void sp_knot_handler_request_position(GdkEvent *event, SPKnot *knot) +{ Geom::Point const motion_w(event->motion.x, event->motion.y); Geom::Point const motion_dt = knot->desktop->w2d(motion_w); Geom::Point p = motion_dt - knot->grabbed_rel_pos; knot->requestPosition(p, event->motion.state); - knot->desktop->scroll_to_point (motion_dt); - knot->desktop->set_coordinate_status(knot->pos); // display the coordinate of knot, not cursor - they may be different! + knot->desktop->scroll_to_point(motion_dt); + knot->desktop->set_coordinate_status(knot->pos); // display the coordinate of knot, not cursor - they may be + // different! if (event->motion.state & GDK_BUTTON1_MASK) { Inkscape::UI::Tools::gobble_motion_events(GDK_BUTTON1_MASK); } } -void SPKnot::show() { +void SPKnot::show() +{ this->setFlag(SP_KNOT_VISIBLE, true); } -void SPKnot::hide() { +void SPKnot::hide() +{ this->setFlag(SP_KNOT_VISIBLE, false); } -void SPKnot::requestPosition(Geom::Point const &p, guint state) { - bool done = this->request_signal.emit(this, &const_cast(p), state); +void SPKnot::requestPosition(Geom::Point const &p, guint state) +{ + bool done = this->request_signal.emit(this, &const_cast(p), state); /* If user did not complete, we simply move knot to new position */ if (!done) { @@ -386,7 +386,8 @@ void SPKnot::requestPosition(Geom::Point const &p, guint state) { } } -void SPKnot::setPosition(Geom::Point const &p, guint state) { +void SPKnot::setPosition(Geom::Point const &p, guint state) +{ this->pos = p; if (this->item) { @@ -396,7 +397,8 @@ void SPKnot::setPosition(Geom::Point const &p, guint state) { this->moved_signal.emit(this, p, state); } -void SPKnot::moveto(Geom::Point const &p) { +void SPKnot::moveto(Geom::Point const &p) +{ this->pos = p; if (this->item) { @@ -404,11 +406,13 @@ void SPKnot::moveto(Geom::Point const &p) { } } -Geom::Point SPKnot::position() const { +Geom::Point SPKnot::position() const +{ return this->pos; } -void SPKnot::setFlag(guint flag, bool set) { +void SPKnot::setFlag(guint flag, bool set) +{ if (set) { this->flags |= flag; } else { @@ -416,27 +420,28 @@ void SPKnot::setFlag(guint flag, bool set) { } switch (flag) { - case SP_KNOT_VISIBLE: + case SP_KNOT_VISIBLE: if (set) { sp_canvas_item_show(this->item); } else { sp_canvas_item_hide(this->item); } break; - case SP_KNOT_MOUSEOVER: - case SP_KNOT_DRAGGING: - case SP_KNOT_SELECTED: + case SP_KNOT_MOUSEOVER: + case SP_KNOT_DRAGGING: + case SP_KNOT_SELECTED: this->_setCtrlState(); break; - case SP_KNOT_GRABBED: + case SP_KNOT_GRABBED: break; - default: + default: g_assert_not_reached(); break; } } -void SPKnot::updateCtrl() { +void SPKnot::updateCtrl() +{ if (!this->item) { return; } @@ -454,7 +459,8 @@ void SPKnot::updateCtrl() { this->_setCtrlState(); } -void SPKnot::_setCtrlState() { +void SPKnot::_setCtrlState() +{ int state = SP_KNOT_STATE_NORMAL; if (this->flags & SP_KNOT_DRAGGING) { @@ -464,57 +470,66 @@ void SPKnot::_setCtrlState() { } else if (this->flags & SP_KNOT_SELECTED) { state = SP_KNOT_STATE_SELECTED; } - g_object_set(this->item, "fill_color", this->fill[state], NULL); + g_object_set(this->item, "fill_color", this->fill[state], NULL); g_object_set(this->item, "stroke_color", this->stroke[state], NULL); } - -void SPKnot::setSize(guint i) { +void SPKnot::setSize(guint i) +{ size = i; } -void SPKnot::setShape(guint i) { - shape = (SPKnotShapeType) i; +void SPKnot::setShape(guint i) +{ + shape = (SPKnotShapeType)i; } -void SPKnot::setAnchor(guint i) { - anchor = (SPAnchorType) i; +void SPKnot::setAnchor(guint i) +{ + anchor = (SPAnchorType)i; } -void SPKnot::setMode(guint i) { - mode = (SPKnotModeType) i; +void SPKnot::setMode(guint i) +{ + mode = (SPKnotModeType)i; } -void SPKnot::setPixbuf(gpointer p) { +void SPKnot::setPixbuf(gpointer p) +{ pixbuf = p; } -void SPKnot::setAngle(double i) { +void SPKnot::setAngle(double i) +{ angle = i; } -void SPKnot::setFill(guint32 normal, guint32 mouseover, guint32 dragging, guint32 selected) { +void SPKnot::setFill(guint32 normal, guint32 mouseover, guint32 dragging, guint32 selected) +{ fill[SP_KNOT_STATE_NORMAL] = normal; fill[SP_KNOT_STATE_MOUSEOVER] = mouseover; fill[SP_KNOT_STATE_DRAGGING] = dragging; fill[SP_KNOT_STATE_SELECTED] = selected; } -void SPKnot::setStroke(guint32 normal, guint32 mouseover, guint32 dragging, guint32 selected) { +void SPKnot::setStroke(guint32 normal, guint32 mouseover, guint32 dragging, guint32 selected) +{ stroke[SP_KNOT_STATE_NORMAL] = normal; stroke[SP_KNOT_STATE_MOUSEOVER] = mouseover; stroke[SP_KNOT_STATE_DRAGGING] = dragging; stroke[SP_KNOT_STATE_SELECTED] = selected; } -void SPKnot::setImage(guchar* normal, guchar* mouseover, guchar* dragging, guchar* selected) { +void SPKnot::setImage(guchar *normal, guchar *mouseover, guchar *dragging, guchar *selected) +{ image[SP_KNOT_STATE_NORMAL] = normal; image[SP_KNOT_STATE_MOUSEOVER] = mouseover; image[SP_KNOT_STATE_DRAGGING] = dragging; image[SP_KNOT_STATE_SELECTED] = selected; } -void SPKnot::setCursor(GdkCursor* normal, GdkCursor* mouseover, GdkCursor* dragging, GdkCursor* selected) { +void SPKnot::setCursor(GdkCursor *normal, GdkCursor *mouseover, GdkCursor *dragging, GdkCursor *selected) +{ if (cursor[SP_KNOT_STATE_NORMAL]) { g_object_unref(cursor[SP_KNOT_STATE_NORMAL]); } @@ -544,7 +559,7 @@ void SPKnot::setCursor(GdkCursor* normal, GdkCursor* mouseover, GdkCursor* dragg if (dragging) { g_object_ref(dragging); } - + if (cursor[SP_KNOT_STATE_SELECTED]) { g_object_unref(cursor[SP_KNOT_STATE_SELECTED]); } diff --git a/src/knot.h b/src/knot.h index 050eeafe562fe6926ca904e52fe8fba475410ed8..722ee9db6d894bc9fe630410ed9c8a46771606da 100644 --- a/src/knot.h +++ b/src/knot.h @@ -18,8 +18,8 @@ #include <2geom/point.h> #include -#include "knot-enums.h" #include "enums.h" +#include "knot-enums.h" class SPDesktop; class SPItem; @@ -29,9 +29,8 @@ typedef struct _GdkCursor GdkCursor; typedef union _GdkEvent GdkEvent; typedef unsigned int guint32; -#define SP_KNOT(obj) (dynamic_cast(static_cast(obj))) -#define SP_IS_KNOT(obj) (dynamic_cast(static_cast(obj)) != NULL) - +#define SP_KNOT(obj) (dynamic_cast(static_cast(obj))) +#define SP_IS_KNOT(obj) (dynamic_cast(static_cast(obj)) != NULL) /** * Desktop-bound visual control object. @@ -39,38 +38,39 @@ typedef unsigned int guint32; * A knot is a draggable object, with callbacks to change something by * dragging it, visuably represented by a canvas item (mostly square). */ -class SPKnot { +class SPKnot +{ public: SPKnot(SPDesktop *desktop, char const *tip); virtual ~SPKnot(); - SPKnot(SPKnot const&) = delete; - SPKnot& operator=(SPKnot const&) = delete; + SPKnot(SPKnot const &) = delete; + SPKnot &operator=(SPKnot const &) = delete; int ref_count; // FIXME encapsulation - SPDesktop *desktop = nullptr; /**< Desktop we are on. */ - SPCanvasItem *item = nullptr; /**< Our CanvasItem. */ - SPItem *owner = nullptr; /**< Optional Owner Item */ - SPItem *sub_owner = nullptr; /**< Optional SubOwner Item */ - unsigned int flags = SP_KNOT_VISIBLE; - - unsigned int size = 8; /**< Always square. */ - double angle = 0.0; /**< Angle of mesh handle. */ - Geom::Point pos; /**< Our desktop coordinates. */ - Geom::Point grabbed_rel_pos; /**< Grabbed relative position. */ - Geom::Point drag_origin; /**< Origin of drag. */ - SPAnchorType anchor = SP_ANCHOR_CENTER; /**< Anchor. */ - - bool grabbed = false; - bool moved = false; - int xp = 0.0; /**< Where drag started */ - int yp = 0.0; /**< Where drag started */ - int tolerance = 0; + SPDesktop *desktop = nullptr; /**< Desktop we are on. */ + SPCanvasItem *item = nullptr; /**< Our CanvasItem. */ + SPItem *owner = nullptr; /**< Optional Owner Item */ + SPItem *sub_owner = nullptr; /**< Optional SubOwner Item */ + unsigned int flags = SP_KNOT_VISIBLE; + + unsigned int size = 8; /**< Always square. */ + double angle = 0.0; /**< Angle of mesh handle. */ + Geom::Point pos; /**< Our desktop coordinates. */ + Geom::Point grabbed_rel_pos; /**< Grabbed relative position. */ + Geom::Point drag_origin; /**< Origin of drag. */ + SPAnchorType anchor = SP_ANCHOR_CENTER; /**< Anchor. */ + + bool grabbed = false; + bool moved = false; + int xp = 0.0; /**< Where drag started */ + int yp = 0.0; /**< Where drag started */ + int tolerance = 0; bool within_tolerance = false; bool transform_escaped = false; // true iff resize or rotate was cancelled by esc. - SPKnotShapeType shape = SP_KNOT_SHAPE_SQUARE; /**< Shape type. */ + SPKnotShapeType shape = SP_KNOT_SHAPE_SQUARE; /**< Shape type. */ SPKnotModeType mode = SP_KNOT_MODE_XOR; guint32 fill[SP_KNOT_VISIBLE_STATES]; @@ -80,40 +80,39 @@ public: GdkCursor *cursor[SP_KNOT_VISIBLE_STATES]; GdkCursor *saved_cursor = nullptr; - void* pixbuf = nullptr; + void *pixbuf = nullptr; - char *tip = nullptr; + char *tip = nullptr; unsigned long _event_handler_id = 0; - double pressure = 0.0; /**< The tablet pen pressure when the knot is being dragged. */ + double pressure = 0.0; /**< The tablet pen pressure when the knot is being dragged. */ // FIXME: signals should NOT need to emit the object they came from, the callee should // be able to figure that out sigc::signal click_signal; - sigc::signal doubleclicked_signal; - sigc::signal mousedown_signal; - sigc::signal grabbed_signal; + sigc::signal doubleclicked_signal; + sigc::signal mousedown_signal; + sigc::signal grabbed_signal; sigc::signal ungrabbed_signal; sigc::signal moved_signal; - sigc::signal event_signal; - - sigc::signal request_signal; + sigc::signal event_signal; + sigc::signal request_signal; - //TODO: all the members above should eventualle become private, accessible via setters/getters + // TODO: all the members above should eventualle become private, accessible via setters/getters void setSize(unsigned int i); void setShape(unsigned int i); void setAnchor(unsigned int i); void setMode(unsigned int i); - void setPixbuf(void* p); + void setPixbuf(void *p); void setAngle(double i); void setFill(guint32 normal, guint32 mouseover, guint32 dragging, guint32 selected); void setStroke(guint32 normal, guint32 mouseover, guint32 dragging, guint32 selected); - void setImage(unsigned char* normal, unsigned char* mouseover, unsigned char* dragging, unsigned char* selected); + void setImage(unsigned char *normal, unsigned char *mouseover, unsigned char *dragging, unsigned char *selected); - void setCursor(GdkCursor* normal, GdkCursor* mouseover, GdkCursor* dragging, GdkCursor* selected); + void setCursor(GdkCursor *normal, GdkCursor *mouseover, GdkCursor *dragging, GdkCursor *selected); /** * Show knot on its canvas. @@ -171,8 +170,8 @@ private: void _setCtrlState(); }; -void knot_ref(SPKnot* knot); -void knot_unref(SPKnot* knot); +void knot_ref(SPKnot *knot); +void knot_unref(SPKnot *knot); #define SP_KNOT_IS_VISIBLE(k) ((k->flags & SP_KNOT_VISIBLE) != 0) #define SP_KNOT_IS_SELECTED(k) ((k->flags & SP_KNOT_SELECTED) != 0) diff --git a/src/knotholder.cpp b/src/knotholder.cpp index 221b6c80ea70c59364b5a8b85e4c66edf194ed42..16875e6d177dc99a8ba2d4906b484cb96a761db1 100644 --- a/src/knotholder.cpp +++ b/src/knotholder.cpp @@ -21,11 +21,8 @@ #include "document.h" #include "knot-holder-entity.h" #include "knot.h" -#include "verbs.h" - #include "live_effects/effect.h" #include "live_effects/lpeobject.h" - #include "object/box3d.h" #include "object/sp-ellipse.h" #include "object/sp-hatch.h" @@ -36,7 +33,6 @@ #include "object/sp-spiral.h" #include "object/sp-star.h" #include "style.h" - #include "ui/control-manager.h" #include "ui/shape-editor.h" #include "ui/tools-switch.h" @@ -45,6 +41,7 @@ #include "ui/tools/rect-tool.h" #include "ui/tools/spiral-tool.h" #include "ui/tools/tweak-tool.h" +#include "verbs.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -54,32 +51,34 @@ using Inkscape::DocumentUndo; class SPDesktop; -KnotHolder::KnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) : - desktop(desktop), - item(item), - //XML Tree being used directly for item->getRepr() while it shouldn't be... - repr(item ? item->getRepr() : nullptr), - entity(), - sizeUpdatedConn(), - released(relhandler), - local_change(FALSE), - dragging(false), - _edit_transform(Geom::identity()) +KnotHolder::KnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) + : desktop(desktop) + , item(item) + , + // XML Tree being used directly for item->getRepr() while it shouldn't be... + repr(item ? item->getRepr() : nullptr) + , entity() + , sizeUpdatedConn() + , released(relhandler) + , local_change(FALSE) + , dragging(false) + , _edit_transform(Geom::identity()) { if (!desktop || !item) { - g_print ("Error! Throw an exception, please!\n"); + g_print("Error! Throw an exception, please!\n"); } sp_object_ref(item); - sizeUpdatedConn = ControlManager::getManager().connectCtrlSizeChanged(sigc::mem_fun(*this, &KnotHolder::updateControlSizes)); + sizeUpdatedConn = + ControlManager::getManager().connectCtrlSizeChanged(sigc::mem_fun(*this, &KnotHolder::updateControlSizes)); } -KnotHolder::~KnotHolder() { +KnotHolder::~KnotHolder() +{ sp_object_unref(item); - for (auto & i : entity) - { + for (auto &i : entity) { delete i; i = NULL; } @@ -87,8 +86,7 @@ KnotHolder::~KnotHolder() { sizeUpdatedConn.disconnect(); } -void -KnotHolder::setEditTransform(Geom::Affine edit_transform) +void KnotHolder::setEditTransform(Geom::Affine edit_transform) { _edit_transform = edit_transform; } @@ -104,7 +102,7 @@ void KnotHolder::updateControlSizes() void KnotHolder::update_knots() { - for (auto e = entity.begin(); e != entity.end(); ) { + for (auto e = entity.begin(); e != entity.end();) { // check if pattern was removed without deleting the knot if ((*e)->knot_missing()) { delete (*e); @@ -119,7 +117,8 @@ void KnotHolder::update_knots() /** * Returns true if at least one of the KnotHolderEntities has the mouse hovering above it. */ -bool KnotHolder::knot_mouseover() const { +bool KnotHolder::knot_mouseover() const +{ for (auto i : entity) { const SPKnot *knot = i->knot; @@ -131,18 +130,17 @@ bool KnotHolder::knot_mouseover() const { return false; } -void -KnotHolder::knot_mousedown_handler(SPKnot *knot, guint state) +void KnotHolder::knot_mousedown_handler(SPKnot *knot, guint state) { if (!(state & GDK_SHIFT_MASK)) { unselect_knots(); } - for(auto e : this->entity) { + for (auto e : this->entity) { if (!(state & GDK_SHIFT_MASK)) { e->knot->selectKnot(false); } if (e->knot == knot) { - if (!(e->knot->flags & SP_KNOT_SELECTED) || !(state & GDK_SHIFT_MASK)){ + if (!(e->knot->flags & SP_KNOT_SELECTED) || !(state & GDK_SHIFT_MASK)) { e->knot->selectKnot(true); } else { e->knot->selectKnot(false); @@ -151,12 +149,11 @@ KnotHolder::knot_mousedown_handler(SPKnot *knot, guint state) } } -void -KnotHolder::knot_clicked_handler(SPKnot *knot, guint state) +void KnotHolder::knot_clicked_handler(SPKnot *knot, guint state) { SPItem *saved_item = this->item; - for(auto e : this->entity) { + for (auto e : this->entity) { if (e->knot == knot) // no need to test whether knot_click exists since it's virtual now e->knot_click(state); @@ -197,39 +194,38 @@ KnotHolder::knot_clicked_handler(SPKnot *knot, guint state) // for drag, this is done by ungrabbed_handler, but for click we must do it here - if (saved_item) { //increasingly aggressive sanity checks - if (saved_item->document) { + if (saved_item) { // increasingly aggressive sanity checks + if (saved_item->document) { // enum is unsigned so can't be less than SP_VERB_INVALID if (object_verb <= SP_VERB_LAST) { - DocumentUndo::done(saved_item->document, object_verb, - _("Change handle")); + DocumentUndo::done(saved_item->document, object_verb, _("Change handle")); } - } + } } // else { abort(); } } -void -KnotHolder::transform_selected(Geom::Affine transform){ - for (auto & i : entity) { +void KnotHolder::transform_selected(Geom::Affine transform) +{ + for (auto &i : entity) { SPKnot *knot = i->knot; if (knot->flags & SP_KNOT_SELECTED) { - knot_moved_handler(knot, knot->pos * transform , 0); + knot_moved_handler(knot, knot->pos * transform, 0); knot->selectKnot(true); } } } -void -KnotHolder::unselect_knots(){ +void KnotHolder::unselect_knots() +{ if (tools_isactive(desktop, TOOLS_NODES)) { - Inkscape::UI::Tools::NodeTool *nt = static_cast(desktop->event_context); + Inkscape::UI::Tools::NodeTool *nt = static_cast(desktop->event_context); if (nt) { - for(auto i=nt->_shape_editors.begin();i!=nt->_shape_editors.end();++i){ - Inkscape::UI::ShapeEditor * shape_editor = i->second; + for (auto i = nt->_shape_editors.begin(); i != nt->_shape_editors.end(); ++i) { + Inkscape::UI::ShapeEditor *shape_editor = i->second; if (shape_editor && shape_editor->has_knotholder()) { - KnotHolder * knotholder = shape_editor->knotholder; + KnotHolder *knotholder = shape_editor->knotholder; if (knotholder) { - for(auto e : knotholder->entity) { + for (auto e : knotholder->entity) { if (e->knot->flags & SP_KNOT_SELECTED) { e->knot->selectKnot(false); } @@ -241,17 +237,16 @@ KnotHolder::unselect_knots(){ } } -void -KnotHolder::knot_moved_handler(SPKnot *knot, Geom::Point const &p, guint state) +void KnotHolder::knot_moved_handler(SPKnot *knot, Geom::Point const &p, guint state) { if (this->dragging == false) { - this->dragging = true; + this->dragging = true; } // this was a local change and the knotholder does not need to be recreated: this->local_change = TRUE; - for(auto e : this->entity) { + for (auto e : this->entity) { if (e->knot == knot) { Geom::Point const q = p * item->i2dt_affine().inverse() * _edit_transform.inverse(); e->knot_set(q, e->knot->drag_origin * item->i2dt_affine().inverse() * _edit_transform.inverse(), state); @@ -267,8 +262,7 @@ KnotHolder::knot_moved_handler(SPKnot *knot, Geom::Point const &p, guint state) this->update_knots(); } -void -KnotHolder::knot_ungrabbed_handler(SPKnot *knot, guint state) +void KnotHolder::knot_ungrabbed_handler(SPKnot *knot, guint state) { this->dragging = false; @@ -280,15 +274,17 @@ KnotHolder::knot_ungrabbed_handler(SPKnot *knot, guint state) if (!(knot->flags & SP_KNOT_SELECTED)) { knot->selectKnot(true); } else { - for(auto e : this->entity) { + for (auto e : this->entity) { if (e->knot == knot) { - e->knot_ungrabbed(e->knot->position(), e->knot->drag_origin * item->i2dt_affine().inverse() * _edit_transform.inverse(), state); + e->knot_ungrabbed(e->knot->position(), + e->knot->drag_origin * item->i2dt_affine().inverse() * _edit_transform.inverse(), + state); break; } } } - SPObject *object = (SPObject *) this->item; + SPObject *object = (SPObject *)this->item; // Caution: this call involves a screen update, which may process events, and as a // result the knotholder may be destructed. So, after the updateRepr, we cannot use any @@ -381,8 +377,8 @@ void KnotHolder::add_pattern_knotholder() _("Move the stroke's pattern inside the object"), SP_KNOT_SHAPE_CROSS); entity_scale->create(desktop, item, this, Inkscape::CTRL_TYPE_SIZER, - _("Scale the stroke's pattern; uniformly if with Ctrl"), SP_KNOT_SHAPE_SQUARE, - SP_KNOT_MODE_XOR); + _("Scale the stroke's pattern; uniformly if with Ctrl"), + SP_KNOT_SHAPE_SQUARE, SP_KNOT_MODE_XOR); entity_angle->create(desktop, item, this, Inkscape::CTRL_TYPE_ROTATE, _("Rotate the stroke's pattern; with Ctrl to snap angle"), @@ -441,13 +437,14 @@ void KnotHolder::add_hatch_knotholder() updateControlSizes(); } -void KnotHolder::add_filter_knotholder() { +void KnotHolder::add_filter_knotholder() +{ FilterKnotHolderEntity *entity_tl = new FilterKnotHolderEntity(true); FilterKnotHolderEntity *entity_br = new FilterKnotHolderEntity(false); - entity_tl->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, - _("Resize the filter effect region"), SP_KNOT_SHAPE_DIAMOND); - entity_br->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, - _("Resize the filter effect region"), SP_KNOT_SHAPE_DIAMOND); + entity_tl->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, _("Resize the filter effect region"), + SP_KNOT_SHAPE_DIAMOND); + entity_br->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, _("Resize the filter effect region"), + SP_KNOT_SHAPE_DIAMOND); entity.push_back(entity_tl); entity.push_back(entity_br); updateControlSizes(); diff --git a/src/knotholder.h b/src/knotholder.h index bf52d85ac9a325191e9c784097d221df64b3df38..f952144fe96e32ce1c02955609779f407a9e1bb7 100644 --- a/src/knotholder.h +++ b/src/knotholder.h @@ -18,8 +18,8 @@ * */ -#include <2geom/forward.h> #include <2geom/affine.h> +#include <2geom/forward.h> #include #include @@ -34,8 +34,8 @@ namespace LivePathEffect { class PowerStrokePointArrayParamKnotHolderEntity; class SatellitesArrayParam; class FilletChamferKnotHolderEntity; -} -} +} // namespace LivePathEffect +} // namespace Inkscape class KnotHolderEntity; class SPItem; @@ -43,9 +43,10 @@ class SPDesktop; class SPKnot; /* fixme: Think how to make callbacks most sensitive (Lauris) */ -typedef void (* SPKnotHolderReleasedFunc) (SPItem *item); +typedef void (*SPKnotHolderReleasedFunc)(SPItem *item); -class KnotHolder { +class KnotHolder +{ public: KnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler); virtual ~KnotHolder(); @@ -73,13 +74,12 @@ public: SPDesktop *getDesktop() { return desktop; } SPItem *getItem() { return item; } - friend class Inkscape::UI::ShapeEditor; // FIXME why? + friend class Inkscape::UI::ShapeEditor; // FIXME why? friend class Inkscape::LivePathEffect::SatellitesArrayParam; // why? friend class Inkscape::LivePathEffect::PowerStrokePointArrayParamKnotHolderEntity; // why? - friend class Inkscape::LivePathEffect::FilletChamferKnotHolderEntity; // why? + friend class Inkscape::LivePathEffect::FilletChamferKnotHolderEntity; // why? protected: - void updateControlSizes(); SPDesktop *desktop; diff --git a/src/layer-fns.cpp b/src/layer-fns.cpp index 81c722ddc2b7839638b006cd2e4719230497fea7..469daba2824f38dd0557f1f7f5941accb5ba2400 100644 --- a/src/layer-fns.cpp +++ b/src/layer-fns.cpp @@ -11,13 +11,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "document.h" #include "layer-fns.h" +#include "document.h" #include "object/sp-item-group.h" - #include "util/find-last-if.h" - #include "xml/repr.h" // TODO move the documentation comments into the .h file @@ -26,18 +24,19 @@ namespace Inkscape { namespace { -static bool is_layer(SPObject &object) { - return SP_IS_GROUP(&object) && - SP_GROUP(&object)->layerMode() == SPGroup::LAYER; +static bool is_layer(SPObject &object) +{ + return SP_IS_GROUP(&object) && SP_GROUP(&object)->layerMode() == SPGroup::LAYER; } /** Finds the next sibling layer for a \a layer * * @returns NULL if there are no further layers under a parent */ -static SPObject *next_sibling_layer(SPObject *layer) { +static SPObject *next_sibling_layer(SPObject *layer) +{ if (layer->parent == nullptr) { - return nullptr; + return nullptr; } SPObject::ChildrenList &list = layer->parent->children; auto l = std::find_if(++list.iterator_to(*layer), list.end(), &is_layer); @@ -48,7 +47,8 @@ static SPObject *next_sibling_layer(SPObject *layer) { * * @returns NULL if there are no further layers under a parent */ -static SPObject *previous_sibling_layer(SPObject *layer) { +static SPObject *previous_sibling_layer(SPObject *layer) +{ using Inkscape::Algorithms::find_last_if; SPObject::ChildrenList &list = layer->parent->children; @@ -60,7 +60,8 @@ static SPObject *previous_sibling_layer(SPObject *layer) { * * @returns the layer itself if layer has no sublayers */ -static SPObject *first_descendant_layer(SPObject *layer) { +static SPObject *first_descendant_layer(SPObject *layer) +{ while (true) { auto first_descendant = std::find_if(layer->children.begin(), layer->children.end(), &is_layer); if (first_descendant == layer->children.end()) { @@ -76,18 +77,20 @@ static SPObject *first_descendant_layer(SPObject *layer) { * * @returns NULL if layer has no sublayers */ -static SPObject *last_child_layer(SPObject *layer) { +static SPObject *last_child_layer(SPObject *layer) +{ using Inkscape::Algorithms::find_last_if; auto l = find_last_if(layer->children.begin(), layer->children.end(), &is_layer); return l != layer->children.end() ? &*l : nullptr; } -static SPObject *last_elder_layer(SPObject *root, SPObject *layer) { +static SPObject *last_elder_layer(SPObject *root, SPObject *layer) +{ using Inkscape::Algorithms::find_last_if; SPObject *result = nullptr; - while ( layer != root ) { + while (layer != root) { SPObject *sibling(previous_sibling_layer(layer)); if (sibling) { result = sibling; @@ -99,34 +102,35 @@ static SPObject *last_elder_layer(SPObject *root, SPObject *layer) { return result; } -} +} // namespace /** Finds the next layer under \a root, relative to \a layer in * depth-first order. * * @returns NULL if there are no further layers under \a root */ -SPObject *next_layer(SPObject *root, SPObject *layer) { +SPObject *next_layer(SPObject *root, SPObject *layer) +{ g_return_val_if_fail(layer != nullptr, NULL); SPObject *result = nullptr; SPObject *sibling = next_sibling_layer(layer); if (sibling) { result = first_descendant_layer(sibling); - } else if ( layer->parent != root ) { + } else if (layer->parent != root) { result = layer->parent; } return result; } - /** Finds the previous layer under \a root, relative to \a layer in * depth-first order. * * @returns NULL if there are no prior layers under \a root. */ -SPObject *previous_layer(SPObject *root, SPObject *layer) { +SPObject *previous_layer(SPObject *root, SPObject *layer) +{ using Inkscape::Algorithms::find_last_if; g_return_val_if_fail(layer != nullptr, NULL); @@ -135,7 +139,7 @@ SPObject *previous_layer(SPObject *root, SPObject *layer) { SPObject *child = last_child_layer(layer); if (child) { result = child; - } else if ( layer != root ) { + } else if (layer != root) { SPObject *sibling = previous_sibling_layer(layer); if (sibling) { result = sibling; @@ -148,18 +152,19 @@ SPObject *previous_layer(SPObject *root, SPObject *layer) { } /** -* Creates a new layer. Advances to the next layer id indicated + * Creates a new layer. Advances to the next layer id indicated * by the string "layerNN", then creates a new group object of * that id with attribute inkscape:groupmode='layer', and finally * appends the new group object to \a root after object \a layer. * * \pre \a root should be either \a layer or an ancestor of it */ -SPObject *create_layer(SPObject *root, SPObject *layer, LayerRelativePosition position) { +SPObject *create_layer(SPObject *root, SPObject *layer, LayerRelativePosition position) +{ SPDocument *document = root->document; - static int layer_suffix=1; - gchar *id=nullptr; + static int layer_suffix = 1; + gchar *id = nullptr; do { g_free(id); id = g_strdup_printf("layer%d", layer_suffix++); @@ -171,21 +176,21 @@ SPObject *create_layer(SPObject *root, SPObject *layer, LayerRelativePosition po repr->setAttribute("id", id); g_free(id); - if ( LPOS_CHILD == position ) { + if (LPOS_CHILD == position) { root = layer; SPObject *child_layer = Inkscape::last_child_layer(layer); - if ( nullptr != child_layer ) { + if (nullptr != child_layer) { layer = child_layer; } } - if ( root == layer ) { + if (root == layer) { root->getRepr()->appendChild(repr); } else { Inkscape::XML::Node *layer_repr = layer->getRepr(); layer_repr->parent()->addChild(repr, layer_repr); - if ( LPOS_BELOW == position ) { + if (LPOS_BELOW == position) { SP_ITEM(document->getObjectByRepr(repr))->lowerOne(); } } @@ -193,7 +198,7 @@ SPObject *create_layer(SPObject *root, SPObject *layer, LayerRelativePosition po return document->getObjectByRepr(repr); } -} +} // namespace Inkscape /* Local Variables: diff --git a/src/layer-fns.h b/src/layer-fns.h index 1b9cd7e7a7a1c426ec119df5fed3a8d13c4a55a9..b2292189a72efb5edfcc5a8cd3c0ea9632be9ec9 100644 --- a/src/layer-fns.h +++ b/src/layer-fns.h @@ -17,19 +17,20 @@ class SPObject; namespace Inkscape { -enum LayerRelativePosition { +enum LayerRelativePosition +{ LPOS_ABOVE, LPOS_BELOW, LPOS_CHILD, }; - + SPObject *create_layer(SPObject *root, SPObject *layer, LayerRelativePosition position); - + SPObject *next_layer(SPObject *root, SPObject *layer); SPObject *previous_layer(SPObject *root, SPObject *layer); -} +} // namespace Inkscape #endif /* diff --git a/src/layer-manager.cpp b/src/layer-manager.cpp index d6467c248094063c53889ff070e5a6aebe282e59..36f6a65291acecfbe57ab6fb2c5174f83cf57551 100644 --- a/src/layer-manager.cpp +++ b/src/layer-manager.cpp @@ -9,36 +9,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "layer-manager.h" -#include +#include #include - +#include #include "desktop.h" #include "document.h" #include "gc-finalized.h" -#include "layer-manager.h" -#include "selection.h" - #include "inkgc/gc-managed.h" - #include "object/sp-item-group.h" - +#include "selection.h" #include "xml/node-observer.h" namespace Inkscape { - using Inkscape::XML::Node; -class LayerManager::LayerWatcher : public Inkscape::XML::NodeObserver { +class LayerManager::LayerWatcher : public Inkscape::XML::NodeObserver +{ public: - LayerWatcher(LayerManager* mgr, SPObject* obj) : - _mgr(mgr), - _obj(obj), - _lockedAttr(g_quark_from_string("sodipodi:insensitive")), - _labelAttr(g_quark_from_string("inkscape:label")) + LayerWatcher(LayerManager *mgr, SPObject *obj) + : _mgr(mgr) + , _obj(obj) + , _lockedAttr(g_quark_from_string("sodipodi:insensitive")) + , _labelAttr(g_quark_from_string("inkscape:label")) { _connection = _obj->connectModified(sigc::mem_fun(*mgr, &LayerManager::_objectModified)); _obj->getRepr()->addObserver(*this); @@ -56,20 +52,25 @@ public: } } - void notifyChildAdded( Node &/*node*/, Node &/*child*/, Node */*prev*/ ) override {} - void notifyChildRemoved( Node &/*node*/, Node &/*child*/, Node */*prev*/ ) override {} - void notifyChildOrderChanged( Node &/*node*/, Node &/*child*/, Node */*old_prev*/, Node */*new_prev*/ ) override {} - void notifyContentChanged( Node &/*node*/, Util::ptr_shared /*old_content*/, Util::ptr_shared /*new_content*/ ) override {} - void notifyAttributeChanged( Node &/*node*/, GQuark name, Util::ptr_shared /*old_value*/, Util::ptr_shared /*new_value*/ ) override { - if ( name == _lockedAttr || name == _labelAttr ) { - if ( _mgr && _obj ) { - _mgr->_objectModified( _obj, 0 ); + void notifyChildAdded(Node & /*node*/, Node & /*child*/, Node * /*prev*/) override {} + void notifyChildRemoved(Node & /*node*/, Node & /*child*/, Node * /*prev*/) override {} + void notifyChildOrderChanged(Node & /*node*/, Node & /*child*/, Node * /*old_prev*/, Node * /*new_prev*/) override + {} + void notifyContentChanged(Node & /*node*/, Util::ptr_shared /*old_content*/, + Util::ptr_shared /*new_content*/) override + {} + void notifyAttributeChanged(Node & /*node*/, GQuark name, Util::ptr_shared /*old_value*/, + Util::ptr_shared /*new_value*/) override + { + if (name == _lockedAttr || name == _labelAttr) { + if (_mgr && _obj) { + _mgr->_objectModified(_obj, 0); } } } - LayerManager* _mgr; - SPObject* _obj; + LayerManager *_mgr; + SPObject *_obj; sigc::connection _connection; GQuark _lockedAttr; GQuark _labelAttr; @@ -136,17 +137,19 @@ public: */ LayerManager::LayerManager(SPDesktop *desktop) -: _desktop(desktop), _document(nullptr) + : _desktop(desktop) + , _document(nullptr) { - _layer_connection = desktop->connectCurrentLayerChanged( sigc::mem_fun(*this, &LayerManager::_selectedLayerChanged) ); + _layer_connection = desktop->connectCurrentLayerChanged(sigc::mem_fun(*this, &LayerManager::_selectedLayerChanged)); - sigc::bound_mem_functor1 first = sigc::mem_fun(*this, &LayerManager::_setDocument); + sigc::bound_mem_functor1 first = + sigc::mem_fun(*this, &LayerManager::_setDocument); // This next line has problems on gcc 4.0.2 - sigc::slot base2 = first; + sigc::slot base2 = first; - sigc::slot slot2 = sigc::hide<0>( base2 ); - _document_connection = desktop->connectDocumentReplaced( slot2 ); + sigc::slot slot2 = sigc::hide<0>(base2); + _document_connection = desktop->connectDocumentReplaced(slot2); _setDocument(desktop->doc()); } @@ -159,11 +162,11 @@ LayerManager::~LayerManager() _document = nullptr; } -void LayerManager::setCurrentLayer( SPObject* obj ) +void LayerManager::setCurrentLayer(SPObject *obj) { - //g_return_if_fail( _desktop->currentRoot() ); - if ( _desktop->currentRoot() ) { - _desktop->setCurrentLayer( obj ); + // g_return_if_fail( _desktop->currentRoot() ); + if (_desktop->currentRoot()) { + _desktop->setCurrentLayer(obj); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs->getBool("/options/selection/layerdeselect", true)) { @@ -177,25 +180,25 @@ void LayerManager::setCurrentLayer( SPObject* obj ) * A unique name is made by substituting or appending the label's number suffix with * the next unique larger number suffix not already used for any layer name */ -Glib::ustring LayerManager::getNextLayerName( SPObject* obj, gchar const *label) +Glib::ustring LayerManager::getNextLayerName(SPObject *obj, gchar const *label) { - Glib::ustring incoming( label ? label : "Layer 1" ); + Glib::ustring incoming(label ? label : "Layer 1"); Glib::ustring result(incoming); Glib::ustring base(incoming); Glib::ustring split(" "); guint startNum = 1; - gint pos = base.length()-1; + gint pos = base.length() - 1; while (pos >= 0 && g_ascii_isdigit(base[pos])) { - pos-- ; + pos--; } - gchar* numpart = g_strdup(base.substr(pos+1).c_str()); - if ( numpart ) { - gchar* endPtr = nullptr; - guint64 val = g_ascii_strtoull( numpart, &endPtr, 10); - if ( ((val > 0) || (endPtr != numpart)) && (val < 65536) ) { - base.erase( pos+1); + gchar *numpart = g_strdup(base.substr(pos + 1).c_str()); + if (numpart) { + gchar *endPtr = nullptr; + guint64 val = g_ascii_strtoull(numpart, &endPtr, 10); + if (((val > 0) || (endPtr != numpart)) && (val < 65536)) { + base.erase(pos + 1); result = incoming; startNum = static_cast(val); split = ""; @@ -205,56 +208,57 @@ Glib::ustring LayerManager::getNextLayerName( SPObject* obj, gchar const *label) std::set currentNames; std::vector layers = _document->getResourceList("layer"); - SPObject *root=_desktop->currentRoot(); - if ( root ) { - for (auto layer : layers) { + SPObject *root = _desktop->currentRoot(); + if (root) { + for (auto layer : layers) { if (layer != obj) - currentNames.insert( layer->label() ? Glib::ustring(layer->label()) : Glib::ustring() ); + currentNames.insert(layer->label() ? Glib::ustring(layer->label()) : Glib::ustring()); } } // Not sure if we need to cap it, but we'll just be paranoid for the moment // Intentionally unsigned guint endNum = startNum + 3000; - for ( guint i = startNum; (i < endNum) && (currentNames.find(result) != currentNames.end()); i++ ) { + for (guint i = startNum; (i < endNum) && (currentNames.find(result) != currentNames.end()); i++) { result = Glib::ustring::format(base, split, i); } return result; } -void LayerManager::renameLayer( SPObject* obj, gchar const *label, bool uniquify ) +void LayerManager::renameLayer(SPObject *obj, gchar const *label, bool uniquify) { - Glib::ustring incoming( label ? label : "" ); + Glib::ustring incoming(label ? label : ""); Glib::ustring result(incoming); if (uniquify) { result = getNextLayerName(obj, label); } - obj->setLabel( result.c_str() ); + obj->setLabel(result.c_str()); } - - -void LayerManager::_setDocument(SPDocument *document) { +void LayerManager::_setDocument(SPDocument *document) +{ if (_document) { _resource_connection.disconnect(); } _document = document; if (document) { - _resource_connection = document->connectResourcesChanged("layer", sigc::mem_fun(*this, &LayerManager::_rebuild)); + _resource_connection = + document->connectResourcesChanged("layer", sigc::mem_fun(*this, &LayerManager::_rebuild)); } _rebuild(); } -void LayerManager::_objectModified( SPObject* obj, guint /*flags*/ ) +void LayerManager::_objectModified(SPObject *obj, guint /*flags*/) { - _details_changed_signal.emit( obj ); + _details_changed_signal.emit(obj); } -void LayerManager::_rebuild() { -// Debug::EventTracker tracker1(); +void LayerManager::_rebuild() +{ + // Debug::EventTracker tracker1(); _watchers.clear(); @@ -265,34 +269,34 @@ void LayerManager::_rebuild() { std::vector layers = _document->getResourceList("layer"); - SPObject *root=_desktop->currentRoot(); - if ( root ) { + SPObject *root = _desktop->currentRoot(); + if (root) { _addOne(root); - std::set layersToAdd; + std::set layersToAdd; - for ( std::vector::const_iterator iter = layers.begin(); iter != layers.end(); ++iter ) { + for (std::vector::const_iterator iter = layers.begin(); iter != layers.end(); ++iter) { SPObject *layer = *iter; bool needsAdd = false; - std::set additional; + std::set additional; - if ( root->isAncestorOf(layer) ) { + if (root->isAncestorOf(layer)) { needsAdd = true; - for ( SPObject* curr = layer; curr && (curr != root) && needsAdd; curr = curr->parent ) { - if ( SP_IS_GROUP(curr) ) { - SPGroup* group = SP_GROUP(curr); - if ( group->layerMode() == SPGroup::LAYER ) { + for (SPObject *curr = layer; curr && (curr != root) && needsAdd; curr = curr->parent) { + if (SP_IS_GROUP(curr)) { + SPGroup *group = SP_GROUP(curr); + if (group->layerMode() == SPGroup::LAYER) { // If we have a layer-group as the one or a parent, ensure it is listed as a valid layer. - needsAdd &= ( std::find(layers.begin(),layers.end(),curr) != layers.end() ); - // XML Tree being used here directly while it shouldn't be... - if ( (!(group->getRepr())) || (!(group->getRepr()->parent())) ) { + needsAdd &= (std::find(layers.begin(), layers.end(), curr) != layers.end()); + // XML Tree being used here directly while it shouldn't be... + if ((!(group->getRepr())) || (!(group->getRepr()->parent()))) { needsAdd = false; } } else { // If a non-layer group is a parent of layer groups, then show it also as a layer. // TODO add the magic Inkscape group mode? - // XML Tree being used directly while it shouldn't be... - if ( group->getRepr() && group->getRepr()->parent() ) { + // XML Tree being used directly while it shouldn't be... + if (group->getRepr() && group->getRepr()->parent()) { additional.insert(group); } else { needsAdd = false; @@ -301,12 +305,12 @@ void LayerManager::_rebuild() { } } } - if ( needsAdd ) { - if ( !includes(layer) ) { + if (needsAdd) { + if (!includes(layer)) { layersToAdd.insert(SP_GROUP(layer)); } for (auto it : additional) { - if ( !includes(it) ) { + if (!includes(it)) { layersToAdd.insert(it); } } @@ -320,12 +324,12 @@ void LayerManager::_rebuild() { // See http://sourceforge.net/tracker/index.php?func=detail&aid=1339397&group_id=93438&atid=604306 SPObject const *higher = layer; - while ( higher && (higher->parent != root) ) { + while (higher && (higher->parent != root)) { higher = higher->parent; } - Node const* node = higher ? higher->getRepr() : nullptr; - if ( node && node->parent() ) { -// Debug::EventTracker tracker(*layer); + Node const *node = higher ? higher->getRepr() : nullptr; + if (node && node->parent()) { + // Debug::EventTracker tracker(*layer); _watchers.emplace_back(new LayerWatcher(this, layer)); @@ -342,7 +346,7 @@ void LayerManager::_selectedLayerChanged(SPObject *layer) _layer_changed_signal.emit(layer); } -} +} // namespace Inkscape /* Local Variables: diff --git a/src/layer-manager.h b/src/layer-manager.h index 94a2d26c10cf57b0f7d80b8c02f3dc0b5b475d97..942335c977516b3202a0648edd183f7d565f6761 100644 --- a/src/layer-manager.h +++ b/src/layer-manager.h @@ -11,9 +11,9 @@ #ifndef SEEN_INKSCAPE_LAYER_MANAGER_H #define SEEN_INKSCAPE_LAYER_MANAGER_H +#include #include #include -#include #include "document-subset.h" #include "gc-finalized.h" @@ -24,22 +24,25 @@ class SPDocument; namespace Inkscape { -class LayerManager : public DocumentSubset, - public GC::Finalized +class LayerManager + : public DocumentSubset + , public GC::Finalized { public: LayerManager(SPDesktop *desktop); ~LayerManager() override; - void setCurrentLayer( SPObject* obj ); - void renameLayer( SPObject* obj, char const *label, bool uniquify ); - Glib::ustring getNextLayerName( SPObject* obj, char const *label); + void setCurrentLayer(SPObject *obj); + void renameLayer(SPObject *obj, char const *label, bool uniquify); + Glib::ustring getNextLayerName(SPObject *obj, char const *label); - sigc::connection connectCurrentLayerChanged(const sigc::slot & slot) { + sigc::connection connectCurrentLayerChanged(const sigc::slot &slot) + { return _layer_changed_signal.connect(slot); } - sigc::connection connectLayerDetailsChanged(const sigc::slot & slot) { + sigc::connection connectLayerDetailsChanged(const sigc::slot &slot) + { return _details_changed_signal.connect(slot); } @@ -47,7 +50,7 @@ private: friend class LayerWatcher; class LayerWatcher; - void _objectModified( SPObject* obj, unsigned int flags ); + void _objectModified(SPObject *obj, unsigned int flags); void _setDocument(SPDocument *document); void _rebuild(); void _selectedLayerChanged(SPObject *layer); @@ -61,11 +64,11 @@ private: std::vector> _watchers; - sigc::signal _layer_changed_signal; - sigc::signal _details_changed_signal; + sigc::signal _layer_changed_signal; + sigc::signal _details_changed_signal; }; -} +} // namespace Inkscape #endif /* diff --git a/src/layer-model.cpp b/src/layer-model.cpp index 82f93e94b402b2d7fb9cfaf9b84649dbfd8b3281..f7f3ecf8aae4ff33dbdb74937d30fce93da1041b 100644 --- a/src/layer-model.cpp +++ b/src/layer-model.cpp @@ -27,10 +27,9 @@ #include "document.h" #include "layer-fns.h" #include "object-hierarchy.h" - #include "object/sp-defs.h" -#include "object/sp-item.h" #include "object/sp-item-group.h" +#include "object/sp-item.h" #include "object/sp-root.h" // Callbacks @@ -41,17 +40,16 @@ static void _layer_changed(SPObject *top, SPObject *bottom, Inkscape::LayerModel namespace Inkscape { LayerModel::LayerModel() - : _doc( nullptr ) - , _layer_hierarchy( nullptr ) - , _display_key( 0 ) -{ -} + : _doc(nullptr) + , _layer_hierarchy(nullptr) + , _display_key(0) +{} LayerModel::~LayerModel() { if (_layer_hierarchy) { delete _layer_hierarchy; -// _layer_hierarchy = NULL; //this should be here, but commented to find other bug somewhere else. + // _layer_hierarchy = NULL; //this should be here, but commented to find other bug somewhere else. } } @@ -95,10 +93,11 @@ SPObject *LayerModel::currentLayer() const return _layer_hierarchy ? _layer_hierarchy->bottom() : nullptr; } -/** +/** * Resets the bottom layer to the current root */ -void LayerModel::reset() { +void LayerModel::reset() +{ if (_layer_hierarchy) { _layer_hierarchy->setBottom(currentRoot()); } @@ -109,41 +108,47 @@ void LayerModel::reset() { * * Make \a object the top layer. */ -void LayerModel::setCurrentLayer(SPObject *object) { +void LayerModel::setCurrentLayer(SPObject *object) +{ g_return_if_fail(SP_IS_GROUP(object)); - g_return_if_fail( currentRoot() == object || (currentRoot() && currentRoot()->isAncestorOf(object)) ); + g_return_if_fail(currentRoot() == object || (currentRoot() && currentRoot()->isAncestorOf(object))); // printf("Set Layer to ID: %s\n", object->getId()); _layer_hierarchy->setBottom(object); } -void LayerModel::toggleHideAllLayers(bool hide) { - - for ( SPObject* obj = Inkscape::previous_layer(currentRoot(), currentRoot()); obj; obj = Inkscape::previous_layer(currentRoot(), obj) ) { +void LayerModel::toggleHideAllLayers(bool hide) +{ + for (SPObject *obj = Inkscape::previous_layer(currentRoot(), currentRoot()); obj; + obj = Inkscape::previous_layer(currentRoot(), obj)) { SP_ITEM(obj)->setHidden(hide); } } -void LayerModel::toggleLockAllLayers(bool lock) { - - for ( SPObject* obj = Inkscape::previous_layer(currentRoot(), currentRoot()); obj; obj = Inkscape::previous_layer(currentRoot(), obj) ) { +void LayerModel::toggleLockAllLayers(bool lock) +{ + for (SPObject *obj = Inkscape::previous_layer(currentRoot(), currentRoot()); obj; + obj = Inkscape::previous_layer(currentRoot(), obj)) { SP_ITEM(obj)->setLocked(lock); } } -void LayerModel::toggleLockOtherLayers(SPObject *object) { +void LayerModel::toggleLockOtherLayers(SPObject *object) +{ g_return_if_fail(SP_IS_GROUP(object)); - g_return_if_fail( currentRoot() == object || (currentRoot() && currentRoot()->isAncestorOf(object)) ); + g_return_if_fail(currentRoot() == object || (currentRoot() && currentRoot()->isAncestorOf(object))); bool othersLocked = false; - std::vector layers; - for ( SPObject* obj = Inkscape::next_layer(currentRoot(), object); obj; obj = Inkscape::next_layer(currentRoot(), obj) ) { + std::vector layers; + for (SPObject *obj = Inkscape::next_layer(currentRoot(), object); obj; + obj = Inkscape::next_layer(currentRoot(), obj)) { // Don't lock any ancestors, since that would in turn lock the layer as well if (!obj->isAncestorOf(object)) { layers.push_back(obj); othersLocked |= !SP_ITEM(obj)->isLocked(); } } - for ( SPObject* obj = Inkscape::previous_layer(currentRoot(), object); obj; obj = Inkscape::previous_layer(currentRoot(), obj) ) { + for (SPObject *obj = Inkscape::previous_layer(currentRoot(), object); obj; + obj = Inkscape::previous_layer(currentRoot(), obj)) { if (!obj->isAncestorOf(object)) { layers.push_back(obj); othersLocked |= !SP_ITEM(obj)->isLocked(); @@ -151,43 +156,44 @@ void LayerModel::toggleLockOtherLayers(SPObject *object) { } SPItem *item = SP_ITEM(object); - if ( item->isLocked() ) { + if (item->isLocked()) { item->setLocked(false); } - for (auto & layer : layers) { + for (auto &layer : layers) { SP_ITEM(layer)->setLocked(othersLocked); } } - -void LayerModel::toggleLayerSolo(SPObject *object) { +void LayerModel::toggleLayerSolo(SPObject *object) +{ g_return_if_fail(SP_IS_GROUP(object)); - g_return_if_fail( currentRoot() == object || (currentRoot() && currentRoot()->isAncestorOf(object)) ); + g_return_if_fail(currentRoot() == object || (currentRoot() && currentRoot()->isAncestorOf(object))); bool othersShowing = false; - std::vector layers; - for ( SPObject* obj = Inkscape::next_layer(currentRoot(), object); obj; obj = Inkscape::next_layer(currentRoot(), obj) ) { + std::vector layers; + for (SPObject *obj = Inkscape::next_layer(currentRoot(), object); obj; + obj = Inkscape::next_layer(currentRoot(), obj)) { // Don't hide ancestors, since that would in turn hide the layer as well if (!obj->isAncestorOf(object)) { layers.push_back(obj); othersShowing |= !SP_ITEM(obj)->isHidden(); } } - for ( SPObject* obj = Inkscape::previous_layer(currentRoot(), object); obj; obj = Inkscape::previous_layer(currentRoot(), obj) ) { + for (SPObject *obj = Inkscape::previous_layer(currentRoot(), object); obj; + obj = Inkscape::previous_layer(currentRoot(), obj)) { if (!obj->isAncestorOf(object)) { layers.push_back(obj); othersShowing |= !SP_ITEM(obj)->isHidden(); } } - SPItem *item = SP_ITEM(object); - if ( item->isHidden() ) { + if (item->isHidden()) { item->setHidden(false); } - for (auto & layer : layers) { + for (auto &layer : layers) { SP_ITEM(layer)->setHidden(othersShowing); } } @@ -195,14 +201,15 @@ void LayerModel::toggleLayerSolo(SPObject *object) { /** * Return layer that contains \a object. */ -SPObject *LayerModel::layerForObject(SPObject *object) { +SPObject *LayerModel::layerForObject(SPObject *object) +{ g_return_val_if_fail(object != nullptr, NULL); - SPObject *root=currentRoot(); + SPObject *root = currentRoot(); object = object->parent; - while ( object && object != root && !isLayer(object) ) { + while (object && object != root && !isLayer(object)) { // Objects in defs have no layer and are NOT in the root layer - if(SP_IS_DEFS(object)) + if (SP_IS_DEFS(object)) return nullptr; object = object->parent; } @@ -212,34 +219,31 @@ SPObject *LayerModel::layerForObject(SPObject *object) { /** * True if object is a layer. */ -bool LayerModel::isLayer(SPObject *object) const { - return ( SP_IS_GROUP(object) - && ( SP_GROUP(object)->effectiveLayerMode(_display_key) - == SPGroup::LAYER ) ); +bool LayerModel::isLayer(SPObject *object) const +{ + return (SP_IS_GROUP(object) && (SP_GROUP(object)->effectiveLayerMode(_display_key) == SPGroup::LAYER)); } } // namespace Inkscape - /// Callback -static void -_layer_activated(SPObject *layer, Inkscape::LayerModel *layer_model) { +static void _layer_activated(SPObject *layer, Inkscape::LayerModel *layer_model) +{ g_return_if_fail(SP_IS_GROUP(layer)); layer_model->_layer_activated_signal.emit(layer); } /// Callback -static void -_layer_deactivated(SPObject *layer, Inkscape::LayerModel *layer_model) { +static void _layer_deactivated(SPObject *layer, Inkscape::LayerModel *layer_model) +{ g_return_if_fail(SP_IS_GROUP(layer)); layer_model->_layer_deactivated_signal.emit(layer); } /// Callback -static void -_layer_changed(SPObject *top, SPObject *bottom, Inkscape::LayerModel *layer_model) +static void _layer_changed(SPObject *top, SPObject *bottom, Inkscape::LayerModel *layer_model) { - layer_model->_layer_changed_signal.emit (top, bottom); + layer_model->_layer_changed_signal.emit(top, bottom); } /* diff --git a/src/layer-model.h b/src/layer-model.h index 8e7153875a96147de07fb9b2de8bdf7aaf6c0790..053111db3aeb829017b5b0b00e37fd056746d5d7 100644 --- a/src/layer-model.h +++ b/src/layer-model.h @@ -23,18 +23,18 @@ * */ -#include #include +#include class SPDocument; class SPObject; namespace Inkscape { - + class ObjectHierarchy; namespace XML { - class Node; +class Node; } /** @@ -80,7 +80,7 @@ public: void toggleLockOtherLayers(SPObject *object); SPObject *layerForObject(SPObject *object); bool isLayer(SPObject *object) const; - + sigc::signal _layer_activated_signal; sigc::signal _layer_deactivated_signal; sigc::signal _layer_changed_signal; diff --git a/src/line-geometry.cpp b/src/line-geometry.cpp index dd078551335dc90c08021d595a3c2ffcff5a5b1f..23f6a7fd874c412b02c6db480c0174c87db0bfa0 100644 --- a/src/line-geometry.cpp +++ b/src/line-geometry.cpp @@ -11,32 +11,33 @@ */ #include "line-geometry.h" + #include "desktop.h" namespace Box3D { -/** +/** * Draw a line beginning at 'start'. If is_endpoint is true, use 'vec' as the endpoint * of the segment. Otherwise interpret it as the direction of the line. * FIXME: Think of a better way to distinguish between the two constructors of lines. */ -Line::Line(Geom::Point const &start, Geom::Point const &vec, bool is_endpoint): - pt(start) +Line::Line(Geom::Point const &start, Geom::Point const &vec, bool is_endpoint) + : pt(start) { if (is_endpoint) v_dir = vec - start; else - v_dir = vec; + v_dir = vec; normal = v_dir.ccw(); d0 = Geom::dot(normal, pt); } -Line::Line(Line const &line) -= default; +Line::Line(Line const &line) = default; Line &Line::operator=(Line const &line) = default; -boost::optional Line::intersect(Line const &line) { +boost::optional Line::intersect(Line const &line) +{ Geom::Coord denom = Geom::dot(v_dir, line.normal); boost::optional no_point; if (fabs(denom) < 1e-6) @@ -55,60 +56,62 @@ void Line::set_direction(Geom::Point const &dir) Geom::Point Line::closest_to(Geom::Point const &pt) { - /* return the intersection of this line with a perpendicular line passing through pt */ + /* return the intersection of this line with a perpendicular line passing through pt */ boost::optional result = this->intersect(Line(pt, (this->v_dir).ccw(), false)); - g_return_val_if_fail (result, Geom::Point (0.0, 0.0)); + g_return_val_if_fail(result, Geom::Point(0.0, 0.0)); return *result; } -double Line::lambda (Geom::Point const pt) +double Line::lambda(Geom::Point const pt) { - double sign = (Geom::dot (pt - this->pt, this->v_dir) > 0) ? 1.0 : -1.0; - double lambda = sign * Geom::L2 (pt - this->pt); + double sign = (Geom::dot(pt - this->pt, this->v_dir) > 0) ? 1.0 : -1.0; + double lambda = sign * Geom::L2(pt - this->pt); // FIXME: It may speed things up (but how much?) if we assume that // pt lies on the line and thus skip the following test - Geom::Point test = point_from_lambda (lambda); - if (!pts_coincide (pt, test)) { - g_warning ("Point does not lie on line.\n"); + Geom::Point test = point_from_lambda(lambda); + if (!pts_coincide(pt, test)) { + g_warning("Point does not lie on line.\n"); return 0; } return lambda; } /* The coordinates of w with respect to the basis {v1, v2} */ -std::pair coordinates (Geom::Point const &v1, Geom::Point const &v2, Geom::Point const &w) +std::pair coordinates(Geom::Point const &v1, Geom::Point const &v2, Geom::Point const &w) { - double det = determinant (v1, v2);; - if (fabs (det) < epsilon) { + double det = determinant(v1, v2); + ; + if (fabs(det) < epsilon) { // vectors are not linearly independent; we indicate this in the return value(s) - return std::make_pair (HUGE_VAL, HUGE_VAL); + return std::make_pair(HUGE_VAL, HUGE_VAL); } - double lambda1 = determinant (w, v2) / det; - double lambda2 = determinant (v1, w) / det; - return std::make_pair (lambda1, lambda2); + double lambda1 = determinant(w, v2) / det; + double lambda2 = determinant(v1, w) / det; + return std::make_pair(lambda1, lambda2); } /* whether w lies inside the sector spanned by v1 and v2 */ -bool lies_in_sector (Geom::Point const &v1, Geom::Point const &v2, Geom::Point const &w) +bool lies_in_sector(Geom::Point const &v1, Geom::Point const &v2, Geom::Point const &w) { - std::pair coords = coordinates (v1, v2, w); + std::pair coords = coordinates(v1, v2, w); if (coords.first == HUGE_VAL) { // catch the case that the vectors are not linearly independent // FIXME: Can we assume that it's safe to return true if the vectors point in different directions? - return (Geom::dot (v1, v2) < 0); + return (Geom::dot(v1, v2) < 0); } return (coords.first >= 0 && coords.second >= 0); } -bool lies_in_quadrangle (Geom::Point const &A, Geom::Point const &B, Geom::Point const &C, Geom::Point const &D, Geom::Point const &pt) +bool lies_in_quadrangle(Geom::Point const &A, Geom::Point const &B, Geom::Point const &C, Geom::Point const &D, + Geom::Point const &pt) { - return (lies_in_sector (D - A, B - A, pt - A) && lies_in_sector (D - C, B - C, pt - C)); + return (lies_in_sector(D - A, B - A, pt - A) && lies_in_sector(D - C, B - C, pt - C)); } -static double pos_angle (Geom::Point v, Geom::Point w) +static double pos_angle(Geom::Point v, Geom::Point w) { - return fabs (Geom::atan2 (v) - Geom::atan2 (w)); + return fabs(Geom::atan2(v) - Geom::atan2(w)); } /* @@ -116,68 +119,69 @@ static double pos_angle (Geom::Point v, Geom::Point w) * starting at pt and going into direction dir. * If none of the sides is hit, it returns a pair containing two identical points. */ -std::pair -side_of_intersection (Geom::Point const &A, Geom::Point const &B, Geom::Point const &C, Geom::Point const &D, - Geom::Point const &pt, Geom::Point const &dir) +std::pair side_of_intersection(Geom::Point const &A, Geom::Point const &B, + Geom::Point const &C, Geom::Point const &D, + Geom::Point const &pt, Geom::Point const &dir) { - Geom::Point dir_A (A - pt); - Geom::Point dir_B (B - pt); - Geom::Point dir_C (C - pt); - Geom::Point dir_D (D - pt); + Geom::Point dir_A(A - pt); + Geom::Point dir_B(B - pt); + Geom::Point dir_C(C - pt); + Geom::Point dir_D(D - pt); std::pair result; double angle = -1; double tmp_angle; - if (lies_in_sector (dir_A, dir_B, dir)) { - result = std::make_pair (A, B); - angle = pos_angle (dir_A, dir_B); + if (lies_in_sector(dir_A, dir_B, dir)) { + result = std::make_pair(A, B); + angle = pos_angle(dir_A, dir_B); } - if (lies_in_sector (dir_B, dir_C, dir)) { - tmp_angle = pos_angle (dir_B, dir_C); + if (lies_in_sector(dir_B, dir_C, dir)) { + tmp_angle = pos_angle(dir_B, dir_C); if (tmp_angle > angle) { angle = tmp_angle; - result = std::make_pair (B, C); + result = std::make_pair(B, C); } } - if (lies_in_sector (dir_C, dir_D, dir)) { - tmp_angle = pos_angle (dir_C, dir_D); + if (lies_in_sector(dir_C, dir_D, dir)) { + tmp_angle = pos_angle(dir_C, dir_D); if (tmp_angle > angle) { angle = tmp_angle; - result = std::make_pair (C, D); + result = std::make_pair(C, D); } } - if (lies_in_sector (dir_D, dir_A, dir)) { - tmp_angle = pos_angle (dir_D, dir_A); + if (lies_in_sector(dir_D, dir_A, dir)) { + tmp_angle = pos_angle(dir_D, dir_A); if (tmp_angle > angle) { angle = tmp_angle; - result = std::make_pair (D, A); + result = std::make_pair(D, A); } } if (angle == -1) { // no intersection found; return a pair containing two identical points - return std::make_pair (A, A); + return std::make_pair(A, A); } else { return result; } } -boost::optional Line::intersection_with_viewbox (SPDesktop *desktop) +boost::optional Line::intersection_with_viewbox(SPDesktop *desktop) { auto vb = desktop->get_display_area(); - std::pair e = side_of_intersection (vb.corner(0), vb.corner(1), vb.corner(2), vb.corner(3), this->pt, this->v_dir); + std::pair e = + side_of_intersection(vb.corner(0), vb.corner(1), vb.corner(2), vb.corner(3), this->pt, this->v_dir); if (e.first == e.second) { // perspective line lies outside the canvas return boost::optional(); } - Line line (e.first, e.second); - return this->intersect (line); + Line line(e.first, e.second); + return this->intersect(line); } -} // namespace Box3D - +} // namespace Box3D + /* Local Variables: mode:c++ diff --git a/src/line-geometry.h b/src/line-geometry.h index 9ba686e6d85e9b94ab3191bee48552b84c919cb9..c87ffec442c844231c2222bd2a19541953d6df63 100644 --- a/src/line-geometry.h +++ b/src/line-geometry.h @@ -24,35 +24,36 @@ typedef unsigned int guint32; namespace Box3D { -class Line { +class Line +{ public: Line(Geom::Point const &start, Geom::Point const &vec, bool is_endpoint = true); Line(Line const &line); virtual ~Line() = default; Line &operator=(Line const &line); virtual boost::optional intersect(Line const &line); - inline Geom::Point direction () { return v_dir; } - - Geom::Point closest_to(Geom::Point const &pt); // returns the point on the line closest to pt + inline Geom::Point direction() { return v_dir; } + + Geom::Point closest_to(Geom::Point const &pt); // returns the point on the line closest to pt - friend inline std::ostream &operator<< (std::ostream &out_file, const Line &in_line); - boost::optional intersection_with_viewbox (SPDesktop *desktop); - inline bool lie_on_same_side (Geom::Point const &A, Geom::Point const &B) { + friend inline std::ostream &operator<<(std::ostream &out_file, const Line &in_line); + boost::optional intersection_with_viewbox(SPDesktop *desktop); + inline bool lie_on_same_side(Geom::Point const &A, Geom::Point const &B) + { /* If A is a point in the plane and n is the normal vector of the line then the sign of dot(A, n) specifies the half-plane in which A lies. Thus A and B lie on the same side if the dot products have equal sign. */ return ((Geom::dot(A, normal) - d0) * (Geom::dot(B, normal) - d0)) > 0; } - double lambda (Geom::Point const pt); - inline Geom::Point point_from_lambda (double const lambda) { - return (pt + lambda * Geom::unit_vector (v_dir)); } + double lambda(Geom::Point const pt); + inline Geom::Point point_from_lambda(double const lambda) { return (pt + lambda * Geom::unit_vector(v_dir)); } protected: void set_direction(Geom::Point const &dir); - inline static bool pts_coincide (Geom::Point const pt1, Geom::Point const pt2) + inline static bool pts_coincide(Geom::Point const pt1, Geom::Point const pt2) { - return (Geom::L2 (pt2 - pt1) < epsilon); + return (Geom::L2(pt2 - pt1) < epsilon); } Geom::Point pt; @@ -61,27 +62,28 @@ protected: Geom::Coord d0; }; -inline double determinant (Geom::Point const &a, Geom::Point const &b) +inline double determinant(Geom::Point const &a, Geom::Point const &b) { return (a[Geom::X] * b[Geom::Y] - a[Geom::Y] * b[Geom::X]); } -std::pair coordinates (Geom::Point const &v1, Geom::Point const &v2, Geom::Point const &w); -bool lies_in_sector (Geom::Point const &v1, Geom::Point const &v2, Geom::Point const &w); -bool lies_in_quadrangle (Geom::Point const &A, Geom::Point const &B, Geom::Point const &C, Geom::Point const &D, Geom::Point const &pt); -std::pair side_of_intersection (Geom::Point const &A, Geom::Point const &B, - Geom::Point const &C, Geom::Point const &D, - Geom::Point const &pt, Geom::Point const &dir); +std::pair coordinates(Geom::Point const &v1, Geom::Point const &v2, Geom::Point const &w); +bool lies_in_sector(Geom::Point const &v1, Geom::Point const &v2, Geom::Point const &w); +bool lies_in_quadrangle(Geom::Point const &A, Geom::Point const &B, Geom::Point const &C, Geom::Point const &D, + Geom::Point const &pt); +std::pair side_of_intersection(Geom::Point const &A, Geom::Point const &B, + Geom::Point const &C, Geom::Point const &D, + Geom::Point const &pt, Geom::Point const &dir); /** A function to print out the Line. It just prints out the coordinates of start point and direction on the given output stream */ -inline std::ostream &operator<< (std::ostream &out_file, const Line &in_line) { +inline std::ostream &operator<<(std::ostream &out_file, const Line &in_line) +{ out_file << "Start: " << in_line.pt << " Direction: " << in_line.v_dir; return out_file; } } // namespace Box3D - #endif /* !SEEN_LINE_GEOMETRY_H */ /* diff --git a/src/line-snapper.cpp b/src/line-snapper.cpp index 3a065422aa5a00e1e122e03c3abffda2dc655763..9fcdaef89be8ca25ebbb249e3df16bdf9108129f 100644 --- a/src/line-snapper.cpp +++ b/src/line-snapper.cpp @@ -11,36 +11,35 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "line-snapper.h" + #include <2geom/line.h> -#include "line-snapper.h" #include "snap.h" -Inkscape::LineSnapper::LineSnapper(SnapManager *sm, Geom::Coord const d) : Snapper(sm, d) -{ -} +Inkscape::LineSnapper::LineSnapper(SnapManager *sm, Geom::Coord const d) + : Snapper(sm, d) +{} -void Inkscape::LineSnapper::freeSnap(IntermSnapResults &isr, - Inkscape::SnapCandidatePoint const &p, - Geom::OptRect const &/*bbox_to_snap*/, - std::vector const */*it*/, - std::vector */*unselected_nodes*/) const +void Inkscape::LineSnapper::freeSnap(IntermSnapResults &isr, Inkscape::SnapCandidatePoint const &p, + Geom::OptRect const & /*bbox_to_snap*/, std::vector const * /*it*/, + std::vector * /*unselected_nodes*/) const { - if (!(_snap_enabled && _snapmanager->snapprefs.isSourceSnappable(p.getSourceType())) ) { + if (!(_snap_enabled && _snapmanager->snapprefs.isSourceSnappable(p.getSourceType()))) { return; } /* Get the lines that we will try to snap to */ const LineList lines = _getSnapLines(p.getPoint()); - for (const auto & line : lines) { - Geom::Point const p1 = line.second; // point at guide/grid line + for (const auto &line : lines) { + Geom::Point const p1 = line.second; // point at guide/grid line Geom::Point const p2 = p1 + Geom::rot90(line.first); // 2nd point at guide/grid line - assert(line.first != Geom::Point(0,0)); // we cannot project on an linesegment of zero length + assert(line.first != Geom::Point(0, 0)); // we cannot project on an linesegment of zero length Geom::Point const p_proj = Geom::projection(p.getPoint(), Geom::Line(p1, p2)); Geom::Coord const dist = Geom::L2(p_proj - p.getPoint()); - //Store any line that's within snapping range + // Store any line that's within snapping range if (dist < getSnapperTolerance()) { _addSnappedLine(isr, p_proj, dist, p.getSourceType(), p.getSourceNum(), line.first, line.second); // For any line that's within range, we will also look at it's "point on line" p1. For guides @@ -55,26 +54,31 @@ void Inkscape::LineSnapper::freeSnap(IntermSnapResults &isr, // Here we will try to snap either tangentially or perpendicularly to a grid/guide line // For this we need to know where the origin is located of the line that is currently being rotated, - std::vector > const origins_and_vectors = p.getOriginsAndVectors(); - // Now we will iterate over all the origins and vectors and see which of these will get use a tangential or perpendicular snap - for (const auto & origins_and_vector : origins_and_vectors) { + std::vector> const origins_and_vectors = p.getOriginsAndVectors(); + // Now we will iterate over all the origins and vectors and see which of these will get use a tangential or + // perpendicular snap + for (const auto &origins_and_vector : origins_and_vectors) { if (origins_and_vector.second) { // if "second" is true then "first" is a vector, otherwise it's a point // When snapping a line with a constant vector (constant direction) to a guide or grid line, // then either all points will be perpendicular/tangential or none at all. This is not very useful continue; } - //Geom::Point origin_doc = _snapmanager->getDesktop()->dt2doc((*it_origin_or_vector).first); // "first" contains a Geom::Point, denoting either a point - Geom::Point origin = origins_and_vector.first; // "first" contains a Geom::Point, denoting either a point + // Geom::Point origin_doc = _snapmanager->getDesktop()->dt2doc((*it_origin_or_vector).first); // "first" + // contains a Geom::Point, denoting either a point + Geom::Point origin = + origins_and_vector.first; // "first" contains a Geom::Point, denoting either a point - // We won't try to snap tangentially; a line being tangential to another line can be achieved by snapping both its endpoints - // individually to the other line. There's no need to have an explicit tangential snap here, that would be redundant + // We won't try to snap tangentially; a line being tangential to another line can be achieved by + // snapping both its endpoints individually to the other line. There's no need to have an explicit + // tangential snap here, that would be redundant if (_snapmanager->snapprefs.getSnapPerp()) { // Find the point that leads to a perpendicular snap Geom::Point const origin_proj = Geom::projection(origin, Geom::Line(p1, p2)); Geom::Coord dist = Geom::L2(origin_proj - p.getPoint()); if (dist < getSnapperTolerance()) { - _addSnappedLinePerpendicularly(isr, origin_proj, dist, p.getSourceType(), p.getSourceNum(), false); + _addSnappedLinePerpendicularly(isr, origin_proj, dist, p.getSourceType(), p.getSourceNum(), + false); } } } @@ -82,12 +86,10 @@ void Inkscape::LineSnapper::freeSnap(IntermSnapResults &isr, } } -void Inkscape::LineSnapper::constrainedSnap(IntermSnapResults &isr, - Inkscape::SnapCandidatePoint const &p, - Geom::OptRect const &/*bbox_to_snap*/, - SnapConstraint const &c, - std::vector const */*it*/, - std::vector */*unselected_nodes*/) const +void Inkscape::LineSnapper::constrainedSnap(IntermSnapResults &isr, Inkscape::SnapCandidatePoint const &p, + Geom::OptRect const & /*bbox_to_snap*/, SnapConstraint const &c, + std::vector const * /*it*/, + std::vector * /*unselected_nodes*/) const { if (_snap_enabled == false || _snapmanager->snapprefs.isSourceSnappable(p.getSourceType()) == false) { @@ -100,7 +102,7 @@ void Inkscape::LineSnapper::constrainedSnap(IntermSnapResults &isr, /* Get the lines that we will try to snap to */ const LineList lines = _getSnapLines(pp); - for (const auto & line : lines) { + for (const auto &line : lines) { Geom::Point const point_on_line = c.hasPoint() ? c.getPoint() : pp; Geom::Line gridguide_line(line.second, line.second + Geom::rot90(line.first)); @@ -117,24 +119,23 @@ void Inkscape::LineSnapper::constrainedSnap(IntermSnapResults &isr, } else if (dist < radius) { // Two points of intersection, symmetrical with respect to the projected point // Calculate half the length of the linesegment between the two points of intersection - Geom::Coord l = sqrt(radius*radius - dist*dist); + Geom::Coord l = sqrt(radius * radius - dist * dist); Geom::Coord d = Geom::L2(gridguide_line.versor()); // length of versor, needed to normalize the versor if (d > 0) { - Geom::Point v = l*gridguide_line.versor()/d; - _addSnappedPoint(isr, p_proj + v, Geom::L2(p.getPoint() - (p_proj + v)), p.getSourceType(), p.getSourceNum(), true); - _addSnappedPoint(isr, p_proj - v, Geom::L2(p.getPoint() - (p_proj - v)), p.getSourceType(), p.getSourceNum(), true); + Geom::Point v = l * gridguide_line.versor() / d; + _addSnappedPoint(isr, p_proj + v, Geom::L2(p.getPoint() - (p_proj + v)), p.getSourceType(), + p.getSourceNum(), true); + _addSnappedPoint(isr, p_proj - v, Geom::L2(p.getPoint() - (p_proj - v)), p.getSourceType(), + p.getSourceNum(), true); } } } else { // Find the intersections between the line and the linear constraint Geom::Line constraint_line(point_on_line, point_on_line + c.getDirection()); Geom::OptCrossing inters = Geom::OptCrossing(); // empty by default - try - { + try { inters = Geom::intersection(constraint_line, gridguide_line); - } - catch (Geom::InfiniteSolutions &e) - { + } catch (Geom::InfiniteSolutions &e) { // We're probably dealing with parallel lines, so snapping doesn't make any sense here continue; // jump to the next iterator in the for-loop } @@ -156,9 +157,11 @@ void Inkscape::LineSnapper::constrainedSnap(IntermSnapResults &isr, // Will only be overridden in the guide-snapper class, because grid lines don't have an origin; the // grid-snapper classes will use this default empty method -void Inkscape::LineSnapper::_addSnappedLinesOrigin(IntermSnapResults &/*isr*/, Geom::Point const &/*origin*/, Geom::Coord const &/*snapped_distance*/, SnapSourceType const &/*source_type*/, long /*source_num*/, bool /*constrained_snap*/) const -{ -} +void Inkscape::LineSnapper::_addSnappedLinesOrigin(IntermSnapResults & /*isr*/, Geom::Point const & /*origin*/, + Geom::Coord const & /*snapped_distance*/, + SnapSourceType const & /*source_type*/, long /*source_num*/, + bool /*constrained_snap*/) const +{} /* Local Variables: diff --git a/src/line-snapper.h b/src/line-snapper.h index ea98124c954f3af3915158ab0513bc89d90f962b..ac94181124d93ca0fa5fea0f40766a6c21df7992 100644 --- a/src/line-snapper.h +++ b/src/line-snapper.h @@ -23,42 +23,46 @@ class SnapCandidatePoint; class LineSnapper : public Snapper { public: - LineSnapper(SnapManager *sm, Geom::Coord const d); + LineSnapper(SnapManager *sm, Geom::Coord const d); - void freeSnap(IntermSnapResults &isr, - Inkscape::SnapCandidatePoint const &p, - Geom::OptRect const &bbox_to_snap, - std::vector const *it, - std::vector *unselected_nodes) const override; + void freeSnap(IntermSnapResults &isr, Inkscape::SnapCandidatePoint const &p, Geom::OptRect const &bbox_to_snap, + std::vector const *it, + std::vector *unselected_nodes) const override; - void constrainedSnap(IntermSnapResults &isr, - Inkscape::SnapCandidatePoint const &p, - Geom::OptRect const &bbox_to_snap, - SnapConstraint const &c, - std::vector const *it, - std::vector *unselected_nodes) const override; + void constrainedSnap(IntermSnapResults &isr, Inkscape::SnapCandidatePoint const &p, + Geom::OptRect const &bbox_to_snap, SnapConstraint const &c, + std::vector const *it, + std::vector *unselected_nodes) const override; protected: - typedef std::list > LineList; - //first point is a vector normal to the line - //second point is a point on the line + typedef std::list> LineList; + // first point is a vector normal to the line + // second point is a point on the line private: - /** - * \param p Point that we are trying to snap. - * \return List of lines that we should try snapping to. - */ - virtual LineList _getSnapLines(Geom::Point const &p) const = 0; + /** + * \param p Point that we are trying to snap. + * \return List of lines that we should try snapping to. + */ + virtual LineList _getSnapLines(Geom::Point const &p) const = 0; - virtual void _addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, Geom::Point const &normal_to_line, Geom::Point const &point_on_line) const = 0; + virtual void _addSnappedLine(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, + Geom::Point const &normal_to_line, Geom::Point const &point_on_line) const = 0; - // Will only be implemented for guide lines, because grid lines don't have an origin - virtual void _addSnappedLinesOrigin(IntermSnapResults &isr, Geom::Point const &origin, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const; + // Will only be implemented for guide lines, because grid lines don't have an origin + virtual void _addSnappedLinesOrigin(IntermSnapResults &isr, Geom::Point const &origin, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, bool constrained_snap) const; - virtual void _addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const = 0; - virtual void _addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const = 0; + virtual void _addSnappedLinePerpendicularly(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, bool constrained_snap) const = 0; + virtual void _addSnappedPoint(IntermSnapResults &isr, Geom::Point const &snapped_point, + Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, + bool constrained_snap) const = 0; }; -} +} // namespace Inkscape #endif /* !SEEN_LINE_SNAPPER_H */ diff --git a/src/live_effects/effect-enum.h b/src/live_effects/effect-enum.h index 5fd5614496ae5d79e286cfd8f5b9c860cfe0989e..77a42abbbfb956c79ed93a3b1b09fd3c4b899f86 100644 --- a/src/live_effects/effect-enum.h +++ b/src/live_effects/effect-enum.h @@ -15,8 +15,9 @@ namespace Inkscape { namespace LivePathEffect { -//Please fill in the same order than in effect.cpp:98 -enum EffectType { +// Please fill in the same order than in effect.cpp:98 +enum EffectType +{ BEND_PATH = 0, GEARS, PATTERN_ALONG_PATH, @@ -77,7 +78,8 @@ enum EffectType { }; template -struct EnumEffectData { +struct EnumEffectData +{ E id; const Glib::ustring label; const Glib::ustring key; @@ -101,15 +103,15 @@ const Glib::ustring empty_string(""); * @note that get_label and get_key return an empty string when the requested id is not in the list. */ template -class EnumEffectDataConverter { - public: +class EnumEffectDataConverter +{ +public: typedef EnumEffectData Data; EnumEffectDataConverter(const EnumEffectData *cd, const unsigned int length) : _length(length) , _data(cd) - { - } + {} E get_id_from_label(const Glib::ustring &label) const { @@ -264,15 +266,15 @@ class EnumEffectDataConverter { const unsigned int _length; - private: +private: const EnumEffectData *_data; }; extern const EnumEffectData LPETypeData[]; /// defined in effect.cpp extern const EnumEffectDataConverter LPETypeConverter; /// defined in effect.cpp -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/effect.cpp b/src/live_effects/effect.cpp index 488c7efd7c9ddacc9d556949d609ab4022d7d1f3..ccdb7fe78516b3916d1c84b54735954cf536c6db 100644 --- a/src/live_effects/effect.cpp +++ b/src/live_effects/effect.cpp @@ -7,12 +7,19 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif //#define LPE_ENABLE_TEST_EFFECTS //uncomment for toy effects // include effects: +#include +#include +#include +#include + +#include "display/curve.h" +#include "knotholder.h" #include "live_effects/lpe-angle_bisector.h" #include "live_effects/lpe-attach-path.h" #include "live_effects/lpe-bendpath.h" @@ -68,29 +75,18 @@ #include "live_effects/lpe-text_label.h" #include "live_effects/lpe-transform_2pts.h" #include "live_effects/lpe-vonkoch.h" - #include "live_effects/lpeobject.h" - -#include "xml/node-event-vector.h" -#include "xml/sp-css-attr.h" - -#include "display/curve.h" -#include "knotholder.h" #include "message-stack.h" +#include "object/sp-defs.h" +#include "object/sp-root.h" +#include "object/sp-shape.h" #include "path-chemistry.h" #include "ui/icon-loader.h" #include "ui/tools-switch.h" #include "ui/tools/node-tool.h" #include "ui/tools/pen-tool.h" - -#include "object/sp-defs.h" -#include "object/sp-root.h" -#include "object/sp-shape.h" - -#include -#include -#include -#include +#include "xml/node-event-vector.h" +#include "xml/sp-css-attr.h" namespace Inkscape { @@ -98,782 +94,808 @@ namespace LivePathEffect { const EnumEffectData LPETypeData[] = { // {constant defined in effect-enum.h, N_("name of your effect"), "name of your effect in SVG"} -/* 0.46 */ + /* 0.46 */ { BEND_PATH, - N_("Bend") ,//label - "bend_path" ,//key - "bend-path" ,//icon - "Bend" ,//untranslated name - N_("Bend an object along the curvature of another path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Bend"), // label + "bend_path", // key + "bend-path", // icon + "Bend", // untranslated name + N_("Bend an object along the curvature of another path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { GEARS, - N_("Gears") ,//label - "gears" ,//key - "gears" ,//icon - "Gears" ,//untranslated name - N_("Create interlocking, configurable gears based on the nodes of a path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Gears"), // label + "gears", // key + "gears", // icon + "Gears", // untranslated name + N_("Create interlocking, configurable gears based on the nodes of a path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { PATTERN_ALONG_PATH, - N_("Pattern Along Path") ,//label - "skeletal" ,//key - "skeletal" ,//icon - "Pattern Along Path" ,//untranslated name - N_("Place one or more copies of another path along the path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Pattern Along Path"), // label + "skeletal", // key + "skeletal", // icon + "Pattern Along Path", // untranslated name + N_("Place one or more copies of another path along the path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, // for historic reasons, this effect is called skeletal(strokes) in Inkscape:SVG { CURVE_STITCH, - N_("Stitch Sub-Paths") ,//label - "curvestitching" ,//key - "curvestitching" ,//icon - "Stitch Sub-Paths" ,//untranslated name - N_("Draw perpendicular lines between subpaths of a path, like rungs of a ladder") ,//description - true ,//on_path - false ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Stitch Sub-Paths"), // label + "curvestitching", // key + "curvestitching", // icon + "Stitch Sub-Paths", // untranslated name + N_("Draw perpendicular lines between subpaths of a path, like rungs of a ladder"), // description + true, // on_path + false, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, -/* 0.47 */ + /* 0.47 */ { VONKOCH, - N_("VonKoch") ,//label - "vonkoch" ,//key - "vonkoch" ,//icon - "VonKoch" ,//untranslated name - N_("Create VonKoch fractal") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("VonKoch"), // label + "vonkoch", // key + "vonkoch", // icon + "VonKoch", // untranslated name + N_("Create VonKoch fractal"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { KNOT, - N_("Knot") ,//label - "knot" ,//key - "knot" ,//icon - "Knot" ,//untranslated name - N_("Create gaps in self-intersections, as in Celtic knots") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Knot"), // label + "knot", // key + "knot", // icon + "Knot", // untranslated name + N_("Create gaps in self-intersections, as in Celtic knots"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { CONSTRUCT_GRID, - N_("Construct grid") ,//label - "construct_grid" ,//key - "construct-grid" ,//icon - "Construct grid" ,//untranslated name - N_("Create a (perspective) grid from a 3-node path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Construct grid"), // label + "construct_grid", // key + "construct-grid", // icon + "Construct grid", // untranslated name + N_("Create a (perspective) grid from a 3-node path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { SPIRO, - N_("Spiro spline") ,//label - "spiro" ,//key - "spiro" ,//icon - "Spiro spline" ,//untranslated name - N_("Make the path curl like wire, using Spiro B-Splines. This effect is usually used directly on the canvas with the Spiro mode of the drawing tools.") ,//description - true ,//on_path - false ,//on_shape - false ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Spiro spline"), // label + "spiro", // key + "spiro", // icon + "Spiro spline", // untranslated name + N_("Make the path curl like wire, using Spiro B-Splines. This effect is usually used directly on " + "the canvas " + "with the Spiro mode of the drawing tools."), // description + true, // on_path + false, // on_shape + false, // on_group + false, // on_image + false, // on_text + false, // experimental }, { ENVELOPE, - N_("Envelope Deformation") ,//label - "envelope" ,//key - "envelope" ,//icon - "Envelope Deformation" ,//untranslated name - N_("Adjust the shape of an object by transforming paths on its four sides") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Envelope Deformation"), // label + "envelope", // key + "envelope", // icon + "Envelope Deformation", // untranslated name + N_("Adjust the shape of an object by transforming paths on its four sides"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { INTERPOLATE, - N_("Interpolate Sub-Paths") ,//label - "interpolate" ,//key - "interpolate" ,//icon - "Interpolate Sub-Paths" ,//untranslated name - N_("Create a stepwise transition between the 2 subpaths of a path") ,//description - true ,//on_path - false ,//on_shape - false ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Interpolate Sub-Paths"), // label + "interpolate", // key + "interpolate", // icon + "Interpolate Sub-Paths", // untranslated name + N_("Create a stepwise transition between the 2 subpaths of a path"), // description + true, // on_path + false, // on_shape + false, // on_group + false, // on_image + false, // on_text + false, // experimental }, { ROUGH_HATCHES, - N_("Hatches (rough)") ,//label - "rough_hatches" ,//key - "rough-hatches" ,//icon - "Hatches (rough)" ,//untranslated name - N_("Fill the object with adjustable hatching") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Hatches (rough)"), // label + "rough_hatches", // key + "rough-hatches", // icon + "Hatches (rough)", // untranslated name + N_("Fill the object with adjustable hatching"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { SKETCH, - N_("Sketch") ,//label - "sketch" ,//key - "sketch" ,//icon - "Sketch" ,//untranslated name - N_("Draw multiple short strokes along the path, as in a pencil sketch") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Sketch"), // label + "sketch", // key + "sketch", // icon + "Sketch", // untranslated name + N_("Draw multiple short strokes along the path, as in a pencil sketch"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { RULER, - N_("Ruler") ,//label - "ruler" ,//key - "ruler" ,//icon - "Ruler" ,//untranslated name - N_("Add ruler marks to the object in adjustable intervals, using the object's stroke style.") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Ruler"), // label + "ruler", // key + "ruler", // icon + "Ruler", // untranslated name + N_("Add ruler marks to the object in adjustable intervals, using the object's stroke style."), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, -/* 0.91 */ + /* 0.91 */ { POWERSTROKE, - N_("Power stroke") ,//label - "powerstroke" ,//key - "powerstroke" ,//icon - "Power stroke" ,//untranslated name - N_("Create calligraphic strokes and control their variable width and curvature. This effect can also be used directly on the canvas with a pressure sensitive stylus and the Pencil tool.") ,//description - true ,//on_path - true ,//on_shape - false ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Power stroke"), // label + "powerstroke", // key + "powerstroke", // icon + "Power stroke", // untranslated name + N_("Create calligraphic strokes and control their variable width and curvature. This effect can " + "also be used " + "directly on the canvas with a pressure sensitive stylus and the Pencil tool."), // description + true, // on_path + true, // on_shape + false, // on_group + false, // on_image + false, // on_text + false, // experimental }, { CLONE_ORIGINAL, - N_("Clone original") ,//label - "clone_original" ,//key - "clone-original" ,//icon - "Clone original" ,//untranslated name - N_("Let an object take on the shape, fill, stroke and/or other attributes of another object.") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Clone original"), // label + "clone_original", // key + "clone-original", // icon + "Clone original", // untranslated name + N_("Let an object take on the shape, fill, stroke and/or other attributes of another object."), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, -/* 0.92 */ + /* 0.92 */ { SIMPLIFY, - N_("Simplify") ,//label - "simplify" ,//key - "simplify" ,//icon - "Simplify" ,//untranslated name - N_("Smoothen and simplify a object. This effect is also available in the Pencil tool's tool controls.") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Simplify"), // label + "simplify", // key + "simplify", // icon + "Simplify", // untranslated name + N_("Smoothen and simplify a object. This effect is also available in the Pencil tool's tool " + "controls."), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { LATTICE2, - N_("Lattice Deformation 2") ,//label - "lattice2" ,//key - "lattice2" ,//icon - "Lattice Deformation 2" ,//untranslated name - N_("Warp an object's shape based on a 5x5 grid") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Lattice Deformation 2"), // label + "lattice2", // key + "lattice2", // icon + "Lattice Deformation 2", // untranslated name + N_("Warp an object's shape based on a 5x5 grid"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { PERSPECTIVE_ENVELOPE, - N_("Perspective/Envelope") ,//label - "perspective-envelope" ,//key wrong key with "-" retain because historic - "perspective-envelope" ,//icon - "Perspective/Envelope" ,//untranslated name - N_("Transform the object to fit into a shape with four corners, either by stretching it or creating the illusion of a 3D-perspective") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Perspective/Envelope"), // label + "perspective-envelope", // key wrong key with "-" retain because historic + "perspective-envelope", // icon + "Perspective/Envelope", // untranslated name + N_("Transform the object to fit into a shape with four corners, either by stretching it or " + "creating the " + "illusion of a 3D-perspective"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { INTERPOLATE_POINTS, - N_("Interpolate points") ,//label - "interpolate_points" ,//key - "interpolate-points" ,//icon - "Interpolate points" ,//untranslated name - N_("Connect the nodes of the object (e.g. corresponding to data points) by different types of lines.") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Interpolate points"), // label + "interpolate_points", // key + "interpolate-points", // icon + "Interpolate points", // untranslated name + N_("Connect the nodes of the object (e.g. corresponding to data points) by different types of " + "lines."), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { TRANSFORM_2PTS, - N_("Transform by 2 points") ,//label - "transform_2pts" ,//key - "transform-2pts" ,//icon - "Transform by 2 points" ,//untranslated name - N_("Scale, stretch and rotate an object by two handles") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Transform by 2 points"), // label + "transform_2pts", // key + "transform-2pts", // icon + "Transform by 2 points", // untranslated name + N_("Scale, stretch and rotate an object by two handles"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { SHOW_HANDLES, - N_("Show handles") ,//label - "show_handles" ,//key - "show-handles" ,//icon - "Show handles" ,//untranslated name - N_("Draw the handles and nodes of objects (replaces the original styling with a black stroke)") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Show handles"), // label + "show_handles", // key + "show-handles", // icon + "Show handles", // untranslated name + N_("Draw the handles and nodes of objects (replaces the original styling with a black stroke)"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { ROUGHEN, - N_("Roughen") ,//label - "roughen" ,//key - "roughen" ,//icon - "Roughen" ,//untranslated name - N_("Roughen an object by adding and randomly shifting new nodes") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Roughen"), // label + "roughen", // key + "roughen", // icon + "Roughen", // untranslated name + N_("Roughen an object by adding and randomly shifting new nodes"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { BSPLINE, - N_("BSpline") ,//label - "bspline" ,//key - "bspline" ,//icon - "BSpline" ,//untranslated name - N_("Create a BSpline that molds into the path's corners. This effect is usually used directly on the canvas with the BSpline mode of the drawing tools.") ,//description - true ,//on_path - false ,//on_shape - false ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("BSpline"), // label + "bspline", // key + "bspline", // icon + "BSpline", // untranslated name + N_("Create a BSpline that molds into the path's corners. This effect is usually used directly on " + "the canvas " + "with the BSpline mode of the drawing tools."), // description + true, // on_path + false, // on_shape + false, // on_group + false, // on_image + false, // on_text + false, // experimental }, { JOIN_TYPE, - N_("Join type") ,//label - "join_type" ,//key - "join-type" ,//icon - "Join type" ,//untranslated name - N_("Select among various join types for a object's corner nodes (mitre, rounded, extrapolated arc, ...)") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Join type"), // label + "join_type", // key + "join-type", // icon + "Join type", // untranslated name + N_("Select among various join types for a object's corner nodes (mitre, rounded, extrapolated arc, " + "...)"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { TAPER_STROKE, - N_("Taper stroke") ,//label - "taper_stroke" ,//key - "taper-stroke" ,//icon - "Taper stroke" ,//untranslated name - N_("Let the path's ends narrow down to a tip") ,//description - true ,//on_path - true ,//on_shape - false ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Taper stroke"), // label + "taper_stroke", // key + "taper-stroke", // icon + "Taper stroke", // untranslated name + N_("Let the path's ends narrow down to a tip"), // description + true, // on_path + true, // on_shape + false, // on_group + false, // on_image + false, // on_text + false, // experimental }, { MIRROR_SYMMETRY, - N_("Mirror symmetry") ,//label - "mirror_symmetry" ,//key - "mirror-symmetry" ,//icon - "Mirror symmetry" ,//untranslated name - N_("Mirror an object along a movable axis, or around the page center. The mirrored copy can be styled independently.") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Mirror symmetry"), // label + "mirror_symmetry", // key + "mirror-symmetry", // icon + "Mirror symmetry", // untranslated name + N_("Mirror an object along a movable axis, or around the page center. The mirrored copy can be " + "styled " + "independently."), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { COPY_ROTATE, - N_("Rotate copies") ,//label - "copy_rotate" ,//key - "copy-rotate" ,//icon - "Rotate copies" ,//untranslated name - N_("Create multiple rotated copies of an object, as in a kaleidoscope. The copies can be styled independently.") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Rotate copies"), // label + "copy_rotate", // key + "copy-rotate", // icon + "Rotate copies", // untranslated name + N_("Create multiple rotated copies of an object, as in a kaleidoscope. The copies can be styled " + "independently."), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, -/* Ponyscape -> Inkscape 0.92*/ + /* Ponyscape -> Inkscape 0.92*/ { ATTACH_PATH, - N_("Attach path") ,//label - "attach_path" ,//key - "attach-path" ,//icon - "Attach path" ,//untranslated name - N_("Glue the current path's ends to a specific position on one or two other paths") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Attach path"), // label + "attach_path", // key + "attach-path", // icon + "Attach path", // untranslated name + N_("Glue the current path's ends to a specific position on one or two other paths"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { FILL_BETWEEN_STROKES, - N_("Fill between strokes") ,//label - "fill_between_strokes" ,//key - "fill-between-strokes" ,//icon - "Fill between strokes" ,//untranslated name - N_("Turn the path into a fill between two other open paths (e.g. between two paths with PowerStroke applied to them)") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Fill between strokes"), // label + "fill_between_strokes", // key + "fill-between-strokes", // icon + "Fill between strokes", // untranslated name + N_("Turn the path into a fill between two other open paths (e.g. between two paths with " + "PowerStroke applied to " + "them)"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { FILL_BETWEEN_MANY, - N_("Fill between many") ,//label - "fill_between_many" ,//key - "fill-between-many" ,//icon - "Fill between many" ,//untranslated name - N_("Turn the path into a fill between multiple other open paths (e.g. between paths with PowerStroke applied to them)") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Fill between many"), // label + "fill_between_many", // key + "fill-between-many", // icon + "Fill between many", // untranslated name + N_("Turn the path into a fill between multiple other open paths (e.g. between paths with " + "PowerStroke applied " + "to them)"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { ELLIPSE_5PTS, - N_("Ellipse by 5 points") ,//label - "ellipse_5pts" ,//key - "ellipse-5pts" ,//icon - "Ellipse by 5 points" ,//untranslated name - N_("Create an ellipse from 5 nodes on its circumference") ,//description - true ,//on_path - true ,//on_shape - false ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Ellipse by 5 points"), // label + "ellipse_5pts", // key + "ellipse-5pts", // icon + "Ellipse by 5 points", // untranslated name + N_("Create an ellipse from 5 nodes on its circumference"), // description + true, // on_path + true, // on_shape + false, // on_group + false, // on_image + false, // on_text + false, // experimental }, { BOUNDING_BOX, - N_("Bounding Box") ,//label - "bounding_box" ,//key - "bounding-box" ,//icon - "Bounding Box" ,//untranslated name - N_("Turn the path into a bounding box that entirely encompasses another path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Bounding Box"), // label + "bounding_box", // key + "bounding-box", // icon + "Bounding Box", // untranslated name + N_("Turn the path into a bounding box that entirely encompasses another path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, -/* 1.0 */ + /* 1.0 */ { MEASURE_SEGMENTS, - N_("Measure Segments") ,//label - "measure_segments" ,//key - "measure-segments" ,//icon - "Measure Segments" ,//untranslated name - N_("Add dimensioning for distances between nodes, optionally with projection and many other configuration options") ,//description - true ,//on_path - true ,//on_shape - false ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Measure Segments"), // label + "measure_segments", // key + "measure-segments", // icon + "Measure Segments", // untranslated name + N_("Add dimensioning for distances between nodes, optionally with projection and many other " + "configuration " + "options"), // description + true, // on_path + true, // on_shape + false, // on_group + false, // on_image + false, // on_text + false, // experimental }, { FILLET_CHAMFER, - N_("Corners (Fillet/Chamfer)") ,//label - "fillet_chamfer" ,//key - "fillet-chamfer" ,//icon - "Corners (Fillet/Chamfer)" ,//untranslated name - N_("Adjust the shape of a path's corners, rounding them to a specified radius, or cutting them off") ,//description - true ,//on_path - true ,//on_shape - false ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Corners (Fillet/Chamfer)"), // label + "fillet_chamfer", // key + "fillet-chamfer", // icon + "Corners (Fillet/Chamfer)", // untranslated name + N_("Adjust the shape of a path's corners, rounding them to a specified radius, or cutting them " + "off"), // description + true, // on_path + true, // on_shape + false, // on_group + false, // on_image + false, // on_text + false, // experimental }, { BOOL_OP, - N_("Boolean operation") ,//label - "bool_op" ,//key - "bool-op" ,//icon - "Boolean operation" ,//untranslated name - N_("Cut, union, subtract, intersect and divide a path non-destructively with another path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Boolean operation"), // label + "bool_op", // key + "bool-op", // icon + "Boolean operation", // untranslated name + N_("Cut, union, subtract, intersect and divide a path non-destructively with another path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { POWERCLIP, - N_("Power clip") ,//label - "powerclip" ,//key - "powerclip" ,//icon - "Power clip" ,//untranslated name - N_("Invert, hide or flatten a clip (apply like a Boolean operation)") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Power clip"), // label + "powerclip", // key + "powerclip", // icon + "Power clip", // untranslated name + N_("Invert, hide or flatten a clip (apply like a Boolean operation)"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { POWERMASK, - N_("Power mask") ,//label - "powermask" ,//key - "powermask" ,//icon - "Power mask" ,//untranslated name - N_("Invert or hide a mask, or use its negative") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Power mask"), // label + "powermask", // key + "powermask", // icon + "Power mask", // untranslated name + N_("Invert or hide a mask, or use its negative"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { PTS2ELLIPSE, - N_("Ellipse from points") ,//label - "pts2ellipse" ,//key - "pts2ellipse" ,//icon - "Ellipse from points" ,//untranslated name - N_("Draw a circle, ellipse, arc or slice based on the nodes of a path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Ellipse from points"), // label + "pts2ellipse", // key + "pts2ellipse", // icon + "Ellipse from points", // untranslated name + N_("Draw a circle, ellipse, arc or slice based on the nodes of a path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { OFFSET, - N_("Offset") ,//label - "offset" ,//key - "offset" ,//icon - "Offset" ,//untranslated name - N_("Offset the path, optionally keeping cusp corners cusp") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Offset"), // label + "offset", // key + "offset", // icon + "Offset", // untranslated name + N_("Offset the path, optionally keeping cusp corners cusp"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { DASHED_STROKE, - N_("Dashed Stroke") ,//label - "dashed_stroke" ,//key - "dashed-stroke" ,//icon - "Dashed Stroke" ,//untranslated name - N_("Add a dashed stroke whose dashes end exactly on a node, optionally with the same number of dashes per path segment") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Dashed Stroke"), // label + "dashed_stroke", // key + "dashed-stroke", // icon + "Dashed Stroke", // untranslated name + N_("Add a dashed stroke whose dashes end exactly on a node, optionally with the same number of " + "dashes per path " + "segment"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, { ANGLE_BISECTOR, - N_("Angle bisector") ,//label - "angle_bisector" ,//key - "experimental" ,//icon - "Angle bisector" ,//untranslated name - N_("Draw a line that halves the angle between the first three nodes of the path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Angle bisector"), // label + "angle_bisector", // key + "experimental", // icon + "Angle bisector", // untranslated name + N_("Draw a line that halves the angle between the first three nodes of the path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { CIRCLE_WITH_RADIUS, - N_("Circle (by center and radius)") ,//label - "circle_with_radius" ,//key - "experimental" ,//icon - "Circle (by center and radius)" ,//untranslated name - N_("Draw a circle, where the first node of the path is the center, and the last determines its radius") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Circle (by center and radius)"), // label + "circle_with_radius", // key + "experimental", // icon + "Circle (by center and radius)", // untranslated name + N_("Draw a circle, where the first node of the path is the center, and the last determines its " + "radius"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { CIRCLE_3PTS, - N_("Circle by 3 points") ,//label - "circle_3pts" ,//key - "experimental" ,//icon - "Circle by 3 points" ,//untranslated name - N_("Draw a circle whose circumference passes through the first three nodes of the path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Circle by 3 points"), // label + "circle_3pts", // key + "experimental", // icon + "Circle by 3 points", // untranslated name + N_("Draw a circle whose circumference passes through the first three nodes of the path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { EXTRUDE, - N_("Extrude") ,//label - "extrude" ,//key - "experimental" ,//icon - "Extrude" ,//untranslated name - N_("Extrude the path, creating a face for each path segment") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Extrude"), // label + "extrude", // key + "experimental", // icon + "Extrude", // untranslated name + N_("Extrude the path, creating a face for each path segment"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { LINE_SEGMENT, - N_("Line Segment") ,//label - "line_segment" ,//key - "experimental" ,//icon - "Line Segment" ,//untranslated name - N_("Draw a straight line that connects the first and last node of a path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Line Segment"), // label + "line_segment", // key + "experimental", // icon + "Line Segment", // untranslated name + N_("Draw a straight line that connects the first and last node of a path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { PARALLEL, - N_("Parallel") ,//label - "parallel" ,//key - "experimental" ,//icon - "Parallel" ,//untranslated name - N_("Create a draggable line that will always be parallel to a two-node path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Parallel"), // label + "parallel", // key + "experimental", // icon + "Parallel", // untranslated name + N_("Create a draggable line that will always be parallel to a two-node path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { PERP_BISECTOR, - N_("Perpendicular bisector") ,//label - "perp_bisector" ,//key - "experimental" ,//icon - "Perpendicular bisector" ,//untranslated name - N_("Draw a perpendicular line in the middle of the (imaginary) line that connects the start and end nodes") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Perpendicular bisector"), // label + "perp_bisector", // key + "experimental", // icon + "Perpendicular bisector", // untranslated name + N_("Draw a perpendicular line in the middle of the (imaginary) line that connects the start and " + "end nodes"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { TANGENT_TO_CURVE, - N_("Tangent to curve") ,//label - "tangent_to_curve" ,//key - "experimental" ,//icon - "Tangent to curve" ,//untranslated name - N_("Draw a tangent with variable length and additional angle that can be moved along the path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Tangent to curve"), // label + "tangent_to_curve", // key + "experimental", // icon + "Tangent to curve", // untranslated name + N_("Draw a tangent with variable length and additional angle that can be moved along the path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, #ifdef LPE_ENABLE_TEST_EFFECTS { DOEFFECTSTACK_TEST, - N_("doEffect stack test") ,//label - "doeffectstacktest" ,//key - "experimental" ,//icon - "doEffect stack test" ,//untranslated name - N_("Test LPE") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("doEffect stack test"), // label + "doeffectstacktest", // key + "experimental", // icon + "doEffect stack test", // untranslated name + N_("Test LPE"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { DYNASTROKE, - N_("Dynamic stroke") ,//label - "dynastroke" ,//key - "experimental" ,//icon - "Dynamic stroke" ,//untranslated name - N_("Create calligraphic strokes with variably shaped ends, making use of a parameter for the brush angle") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Dynamic stroke"), // label + "dynastroke", // key + "experimental", // icon + "Dynamic stroke", // untranslated name + N_("Create calligraphic strokes with variably shaped ends, making use of a parameter for the brush " + "angle"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { LATTICE, - N_("Lattice Deformation") ,//label - "lattice" ,//key - "experimental" ,//icon - "Lattice Deformation" ,//untranslated name - N_("Deform an object using a 4x4 grid") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Lattice Deformation"), // label + "lattice", // key + "experimental", // icon + "Lattice Deformation", // untranslated name + N_("Deform an object using a 4x4 grid"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { PATH_LENGTH, - N_("Path length") ,//label - "path_length" ,//key - "experimental" ,//icon - "Path length" ,//untranslated name - N_("Display the total length of a (curved) path") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Path length"), // label + "path_length", // key + "experimental", // icon + "Path length", // untranslated name + N_("Display the total length of a (curved) path"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { RECURSIVE_SKELETON, - N_("Recursive skeleton") ,//label - "recursive_skeleton" ,//key - "experimental" ,//icon - "Recursive skeleton" ,//untranslated name - N_("Draw a path recursively") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Recursive skeleton"), // label + "recursive_skeleton", // key + "experimental", // icon + "Recursive skeleton", // untranslated name + N_("Draw a path recursively"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { TEXT_LABEL, - N_("Text label") ,//label - "text_label" ,//key - "experimental" ,//icon - "Text label" ,//untranslated name - N_("Add a label for the object") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - true ,//experimental + N_("Text label"), // label + "text_label", // key + "experimental", // icon + "Text label", // untranslated name + N_("Add a label for the object"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + true, // experimental }, { EMBRODERY_STITCH, - N_("Embroidery stitch") ,//label - "embrodery_stitch" ,//key - "embrodery-stitch" ,//icon - "Embroidery stitch" ,//untranslated name - N_("Embroidery stitch") ,//description - true ,//on_path - true ,//on_shape - true ,//on_group - false ,//on_image - false ,//on_text - false ,//experimental + N_("Embroidery stitch"), // label + "embrodery_stitch", // key + "embrodery-stitch", // icon + "Embroidery stitch", // untranslated name + N_("Embroidery stitch"), // description + true, // on_path + true, // on_shape + true, // on_group + false, // on_image + false, // on_text + false, // experimental }, #endif @@ -881,185 +903,191 @@ const EnumEffectData LPETypeData[] = { const EnumEffectDataConverter LPETypeConverter(LPETypeData, sizeof(LPETypeData) / sizeof(*LPETypeData)); -int -Effect::acceptsNumClicks(EffectType type) { +int Effect::acceptsNumClicks(EffectType type) +{ switch (type) { - case INVALID_LPE: return -1; // in case we want to distinguish between invalid LPE and valid ones that expect zero clicks - case ANGLE_BISECTOR: return 3; - case CIRCLE_3PTS: return 3; - case CIRCLE_WITH_RADIUS: return 2; - case LINE_SEGMENT: return 2; - case PERP_BISECTOR: return 2; - default: return 0; + case INVALID_LPE: + return -1; // in case we want to distinguish between invalid LPE and valid ones that expect zero clicks + case ANGLE_BISECTOR: + return 3; + case CIRCLE_3PTS: + return 3; + case CIRCLE_WITH_RADIUS: + return 2; + case LINE_SEGMENT: + return 2; + case PERP_BISECTOR: + return 2; + default: + return 0; } } -Effect* -Effect::New(EffectType lpenr, LivePathEffectObject *lpeobj) +Effect *Effect::New(EffectType lpenr, LivePathEffectObject *lpeobj) { - Effect* neweffect = nullptr; + Effect *neweffect = nullptr; switch (lpenr) { case EMBRODERY_STITCH: - neweffect = static_cast ( new LPEEmbroderyStitch(lpeobj) ); + neweffect = static_cast(new LPEEmbroderyStitch(lpeobj)); break; case BOOL_OP: - neweffect = static_cast ( new LPEBool(lpeobj) ); + neweffect = static_cast(new LPEBool(lpeobj)); break; case PATTERN_ALONG_PATH: - neweffect = static_cast ( new LPEPatternAlongPath(lpeobj) ); + neweffect = static_cast(new LPEPatternAlongPath(lpeobj)); break; case BEND_PATH: - neweffect = static_cast ( new LPEBendPath(lpeobj) ); + neweffect = static_cast(new LPEBendPath(lpeobj)); break; case SKETCH: - neweffect = static_cast ( new LPESketch(lpeobj) ); + neweffect = static_cast(new LPESketch(lpeobj)); break; case ROUGH_HATCHES: - neweffect = static_cast ( new LPERoughHatches(lpeobj) ); + neweffect = static_cast(new LPERoughHatches(lpeobj)); break; case VONKOCH: - neweffect = static_cast ( new LPEVonKoch(lpeobj) ); + neweffect = static_cast(new LPEVonKoch(lpeobj)); break; case KNOT: - neweffect = static_cast ( new LPEKnot(lpeobj) ); + neweffect = static_cast(new LPEKnot(lpeobj)); break; case GEARS: - neweffect = static_cast ( new LPEGears(lpeobj) ); + neweffect = static_cast(new LPEGears(lpeobj)); break; case CURVE_STITCH: - neweffect = static_cast ( new LPECurveStitch(lpeobj) ); + neweffect = static_cast(new LPECurveStitch(lpeobj)); break; case LATTICE: - neweffect = static_cast ( new LPELattice(lpeobj) ); + neweffect = static_cast(new LPELattice(lpeobj)); break; case ENVELOPE: - neweffect = static_cast ( new LPEEnvelope(lpeobj) ); + neweffect = static_cast(new LPEEnvelope(lpeobj)); break; case CIRCLE_WITH_RADIUS: - neweffect = static_cast ( new LPECircleWithRadius(lpeobj) ); + neweffect = static_cast(new LPECircleWithRadius(lpeobj)); break; case SPIRO: - neweffect = static_cast ( new LPESpiro(lpeobj) ); + neweffect = static_cast(new LPESpiro(lpeobj)); break; case CONSTRUCT_GRID: - neweffect = static_cast ( new LPEConstructGrid(lpeobj) ); + neweffect = static_cast(new LPEConstructGrid(lpeobj)); break; case PERP_BISECTOR: - neweffect = static_cast ( new LPEPerpBisector(lpeobj) ); + neweffect = static_cast(new LPEPerpBisector(lpeobj)); break; case TANGENT_TO_CURVE: - neweffect = static_cast ( new LPETangentToCurve(lpeobj) ); + neweffect = static_cast(new LPETangentToCurve(lpeobj)); break; case MIRROR_SYMMETRY: - neweffect = static_cast ( new LPEMirrorSymmetry(lpeobj) ); + neweffect = static_cast(new LPEMirrorSymmetry(lpeobj)); break; case CIRCLE_3PTS: - neweffect = static_cast ( new LPECircle3Pts(lpeobj) ); + neweffect = static_cast(new LPECircle3Pts(lpeobj)); break; case ANGLE_BISECTOR: - neweffect = static_cast ( new LPEAngleBisector(lpeobj) ); + neweffect = static_cast(new LPEAngleBisector(lpeobj)); break; case PARALLEL: - neweffect = static_cast ( new LPEParallel(lpeobj) ); + neweffect = static_cast(new LPEParallel(lpeobj)); break; case COPY_ROTATE: - neweffect = static_cast ( new LPECopyRotate(lpeobj) ); + neweffect = static_cast(new LPECopyRotate(lpeobj)); break; case OFFSET: - neweffect = static_cast ( new LPEOffset(lpeobj) ); + neweffect = static_cast(new LPEOffset(lpeobj)); break; case RULER: - neweffect = static_cast ( new LPERuler(lpeobj) ); + neweffect = static_cast(new LPERuler(lpeobj)); break; case INTERPOLATE: - neweffect = static_cast ( new LPEInterpolate(lpeobj) ); + neweffect = static_cast(new LPEInterpolate(lpeobj)); break; case INTERPOLATE_POINTS: - neweffect = static_cast ( new LPEInterpolatePoints(lpeobj) ); + neweffect = static_cast(new LPEInterpolatePoints(lpeobj)); break; case TEXT_LABEL: - neweffect = static_cast ( new LPETextLabel(lpeobj) ); + neweffect = static_cast(new LPETextLabel(lpeobj)); break; case PATH_LENGTH: - neweffect = static_cast ( new LPEPathLength(lpeobj) ); + neweffect = static_cast(new LPEPathLength(lpeobj)); break; case LINE_SEGMENT: - neweffect = static_cast ( new LPELineSegment(lpeobj) ); + neweffect = static_cast(new LPELineSegment(lpeobj)); break; case DOEFFECTSTACK_TEST: - neweffect = static_cast ( new LPEdoEffectStackTest(lpeobj) ); + neweffect = static_cast(new LPEdoEffectStackTest(lpeobj)); break; case BSPLINE: - neweffect = static_cast ( new LPEBSpline(lpeobj) ); + neweffect = static_cast(new LPEBSpline(lpeobj)); break; case DYNASTROKE: - neweffect = static_cast ( new LPEDynastroke(lpeobj) ); + neweffect = static_cast(new LPEDynastroke(lpeobj)); break; case RECURSIVE_SKELETON: - neweffect = static_cast ( new LPERecursiveSkeleton(lpeobj) ); + neweffect = static_cast(new LPERecursiveSkeleton(lpeobj)); break; case EXTRUDE: - neweffect = static_cast ( new LPEExtrude(lpeobj) ); + neweffect = static_cast(new LPEExtrude(lpeobj)); break; case POWERSTROKE: - neweffect = static_cast ( new LPEPowerStroke(lpeobj) ); + neweffect = static_cast(new LPEPowerStroke(lpeobj)); break; case CLONE_ORIGINAL: - neweffect = static_cast ( new LPECloneOriginal(lpeobj) ); + neweffect = static_cast(new LPECloneOriginal(lpeobj)); break; case ATTACH_PATH: - neweffect = static_cast ( new LPEAttachPath(lpeobj) ); + neweffect = static_cast(new LPEAttachPath(lpeobj)); break; case FILL_BETWEEN_STROKES: - neweffect = static_cast ( new LPEFillBetweenStrokes(lpeobj) ); + neweffect = static_cast(new LPEFillBetweenStrokes(lpeobj)); break; case FILL_BETWEEN_MANY: - neweffect = static_cast ( new LPEFillBetweenMany(lpeobj) ); + neweffect = static_cast(new LPEFillBetweenMany(lpeobj)); break; case ELLIPSE_5PTS: - neweffect = static_cast ( new LPEEllipse5Pts(lpeobj) ); + neweffect = static_cast(new LPEEllipse5Pts(lpeobj)); break; case BOUNDING_BOX: - neweffect = static_cast ( new LPEBoundingBox(lpeobj) ); + neweffect = static_cast(new LPEBoundingBox(lpeobj)); break; case JOIN_TYPE: - neweffect = static_cast ( new LPEJoinType(lpeobj) ); + neweffect = static_cast(new LPEJoinType(lpeobj)); break; case TAPER_STROKE: - neweffect = static_cast ( new LPETaperStroke(lpeobj) ); + neweffect = static_cast(new LPETaperStroke(lpeobj)); break; case SIMPLIFY: - neweffect = static_cast ( new LPESimplify(lpeobj) ); + neweffect = static_cast(new LPESimplify(lpeobj)); break; case LATTICE2: - neweffect = static_cast ( new LPELattice2(lpeobj) ); + neweffect = static_cast(new LPELattice2(lpeobj)); break; case PERSPECTIVE_ENVELOPE: - neweffect = static_cast ( new LPEPerspectiveEnvelope(lpeobj) ); + neweffect = static_cast(new LPEPerspectiveEnvelope(lpeobj)); break; case FILLET_CHAMFER: - neweffect = static_cast ( new LPEFilletChamfer(lpeobj) ); + neweffect = static_cast(new LPEFilletChamfer(lpeobj)); break; case POWERCLIP: - neweffect = static_cast ( new LPEPowerClip(lpeobj) ); + neweffect = static_cast(new LPEPowerClip(lpeobj)); break; case POWERMASK: - neweffect = static_cast ( new LPEPowerMask(lpeobj) ); + neweffect = static_cast(new LPEPowerMask(lpeobj)); break; case ROUGHEN: - neweffect = static_cast ( new LPERoughen(lpeobj) ); + neweffect = static_cast(new LPERoughen(lpeobj)); break; case SHOW_HANDLES: - neweffect = static_cast ( new LPEShowHandles(lpeobj) ); + neweffect = static_cast(new LPEShowHandles(lpeobj)); break; case TRANSFORM_2PTS: - neweffect = static_cast ( new LPETransform2Pts(lpeobj) ); + neweffect = static_cast(new LPETransform2Pts(lpeobj)); break; case MEASURE_SEGMENTS: - neweffect = static_cast ( new LPEMeasureSegments(lpeobj) ); + neweffect = static_cast(new LPEMeasureSegments(lpeobj)); break; case PTS2ELLIPSE: - neweffect = static_cast ( new LPEPts2Ellipse(lpeobj) ); + neweffect = static_cast(new LPEPts2Ellipse(lpeobj)); break; case DASHED_STROKE: neweffect = static_cast(new LPEDashedStroke(lpeobj)); @@ -1077,7 +1105,7 @@ Effect::New(EffectType lpenr, LivePathEffectObject *lpeobj) return neweffect; } -void Effect::createAndApply(const char* name, SPDocument *doc, SPItem *item) +void Effect::createAndApply(const char *name, SPDocument *doc, SPItem *item) { // Path effect definition Inkscape::XML::Document *xml_doc = doc->getReprDoc(); @@ -1085,7 +1113,7 @@ void Effect::createAndApply(const char* name, SPDocument *doc, SPItem *item) repr->setAttribute("effect", name); doc->getDefs()->getRepr()->addChild(repr, nullptr); // adds to and assigns the 'id' attribute - const gchar * repr_id = repr->attribute("id"); + const gchar *repr_id = repr->attribute("id"); Inkscape::GC::release(repr); gchar *href = g_strdup_printf("#%s", repr_id); @@ -1093,64 +1121,61 @@ void Effect::createAndApply(const char* name, SPDocument *doc, SPItem *item) g_free(href); } -void -Effect::createAndApply(EffectType type, SPDocument *doc, SPItem *item) +void Effect::createAndApply(EffectType type, SPDocument *doc, SPItem *item) { createAndApply(LPETypeConverter.get_key(type).c_str(), doc, item); } Effect::Effect(LivePathEffectObject *lpeobject) - : apply_to_clippath_and_mask(false), - _provides_knotholder_entities(false), - oncanvasedit_it(0), - is_visible(_("Is visible?"), _("If unchecked, the effect remains applied to the object but is temporarily disabled on canvas"), "is_visible", &wr, this, true), - lpeversion("Version", "version of LPE 0 inksape lower 1, 1 and up versioning", "lpeversion", &wr, this, "0", true), - show_orig_path(false), - keep_paths(false), - is_load(true), - lpeobj(lpeobject), - concatenate_before_pwd2(false), - sp_lpe_item(nullptr), - current_zoom(1), - refresh_widgets(false), - current_shape(nullptr), - provides_own_flash_paths(true), // is automatically set to false if providesOwnFlashPaths() is not overridden - defaultsopen(false), - is_ready(false), - is_applied(false) + : apply_to_clippath_and_mask(false) + , _provides_knotholder_entities(false) + , oncanvasedit_it(0) + , is_visible(_("Is visible?"), + _("If unchecked, the effect remains applied to the object but is temporarily disabled on canvas"), + "is_visible", &wr, this, true) + , lpeversion("Version", "version of LPE 0 inksape lower 1, 1 and up versioning", "lpeversion", &wr, this, "0", true) + , show_orig_path(false) + , keep_paths(false) + , is_load(true) + , lpeobj(lpeobject) + , concatenate_before_pwd2(false) + , sp_lpe_item(nullptr) + , current_zoom(1) + , refresh_widgets(false) + , current_shape(nullptr) + , provides_own_flash_paths(true) + , // is automatically set to false if providesOwnFlashPaths() is not overridden + defaultsopen(false) + , is_ready(false) + , is_applied(false) { - registerParameter( dynamic_cast(&is_visible) ); - registerParameter( dynamic_cast(&lpeversion) ); + registerParameter(dynamic_cast(&is_visible)); + registerParameter(dynamic_cast(&lpeversion)); is_visible.widget_is_visible = false; current_zoom = 0.0; } Effect::~Effect() = default; -Glib::ustring -Effect::getName() const +Glib::ustring Effect::getName() const { - if (lpeobj->effecttype_set && LPETypeConverter.is_valid_id(lpeobj->effecttype) ) - return Glib::ustring( _(LPETypeConverter.get_label(lpeobj->effecttype).c_str()) ); + if (lpeobj->effecttype_set && LPETypeConverter.is_valid_id(lpeobj->effecttype)) + return Glib::ustring(_(LPETypeConverter.get_label(lpeobj->effecttype).c_str())); else - return Glib::ustring( _("No effect") ); + return Glib::ustring(_("No effect")); } -EffectType -Effect::effectType() const { +EffectType Effect::effectType() const +{ return lpeobj->effecttype; } /** * Is performed a single time when the effect is freshly applied to a path */ -void -Effect::doOnApply (SPLPEItem const*/*lpeitem*/) -{ -} +void Effect::doOnApply(SPLPEItem const * /*lpeitem*/) {} -void -Effect::setCurrentZoom(double cZ) +void Effect::setCurrentZoom(double cZ) { current_zoom = cZ; } @@ -1160,21 +1185,19 @@ Effect::setCurrentZoom(double cZ) */ void Effect::transform_multiply(Geom::Affine const &postmul, bool /*set*/) {} -void -Effect::setSelectedNodePoints(std::vector sNP) +void Effect::setSelectedNodePoints(std::vector sNP) { selectedNodesPoints = sNP; } -bool -Effect::isNodePointSelected(Geom::Point const &nodePoint) const +bool Effect::isNodePointSelected(Geom::Point const &nodePoint) const { if (selectedNodesPoints.size() > 0) { using Geom::X; using Geom::Y; for (auto p : selectedNodesPoints) { Geom::Affine transformCoordinate = sp_lpe_item->i2dt_affine(); - Geom::Point p2(nodePoint[X],nodePoint[Y]); + Geom::Point p2(nodePoint[X], nodePoint[Y]); p2 *= transformCoordinate; if (Geom::are_near(p, p2, 0.01)) { return true; @@ -1184,8 +1207,7 @@ Effect::isNodePointSelected(Geom::Point const &nodePoint) const return false; } -void -Effect::processObjects(LPEAction lpe_action) +void Effect::processObjects(LPEAction lpe_action) { SPDocument *document = getSPDoc(); if (!document) { @@ -1197,47 +1219,47 @@ Effect::processObjects(LPEAction lpe_action) } SPObject *elemref = nullptr; if ((elemref = document->getObjectById(id.c_str()))) { - Inkscape::XML::Node * elemnode = elemref->getRepr(); - std::vector item_list; + Inkscape::XML::Node *elemnode = elemref->getRepr(); + std::vector item_list; item_list.push_back(SP_ITEM(elemref)); - std::vector item_to_select; - std::vector item_selected; + std::vector item_to_select; + std::vector item_selected; SPCSSAttr *css; Glib::ustring css_str; SPItem *item = SP_ITEM(elemref); - switch (lpe_action){ - case LPE_TO_OBJECTS: - if (item->isHidden()) { - item->deleteObject(true); - } else { - if (elemnode->attribute("inkscape:path-effect")) { - sp_item_list_to_curves(item_list, item_selected, item_to_select); + switch (lpe_action) { + case LPE_TO_OBJECTS: + if (item->isHidden()) { + item->deleteObject(true); + } else { + if (elemnode->attribute("inkscape:path-effect")) { + sp_item_list_to_curves(item_list, item_selected, item_to_select); + } + elemnode->removeAttribute("sodipodi:insensitive"); + if (!SP_IS_DEFS(SP_ITEM(elemref)->parent)) { + SP_ITEM(elemref)->moveTo(SP_ITEM(sp_lpe_item), false); + } } - elemnode->removeAttribute("sodipodi:insensitive"); - if (!SP_IS_DEFS(SP_ITEM(elemref)->parent)) { - SP_ITEM(elemref)->moveTo(SP_ITEM(sp_lpe_item), false); - } - } - break; + break; - case LPE_ERASE: - item->deleteObject(true); - break; - - case LPE_VISIBILITY: - css = sp_repr_css_attr_new(); - sp_repr_css_attr_add_from_string(css, elemref->getRepr()->attribute("style")); - if (!this->isVisible()/* && std::strcmp(elemref->getId(),sp_lpe_item->getId()) != 0*/) { - css->setAttribute("display", "none"); - } else { - css->removeAttribute("display"); - } - sp_repr_css_write_string(css,css_str); - elemnode->setAttributeOrRemoveIfEmpty("style", css_str); - break; + case LPE_ERASE: + item->deleteObject(true); + break; + + case LPE_VISIBILITY: + css = sp_repr_css_attr_new(); + sp_repr_css_attr_add_from_string(css, elemref->getRepr()->attribute("style")); + if (!this->isVisible() /* && std::strcmp(elemref->getId(),sp_lpe_item->getId()) != 0*/) { + css->setAttribute("display", "none"); + } else { + css->removeAttribute("display"); + } + sp_repr_css_write_string(css, css_str); + elemnode->setAttributeOrRemoveIfEmpty("style", css_str); + break; - default: - break; + default: + break; } } } @@ -1249,13 +1271,12 @@ Effect::processObjects(LPEAction lpe_action) /** * Is performed each time before the effect is updated. */ -void -Effect::doBeforeEffect (SPLPEItem const*/*lpeitem*/) +void Effect::doBeforeEffect(SPLPEItem const * /*lpeitem*/) { - //Do nothing for simple effects + // Do nothing for simple effects } -void Effect::doAfterEffect (SPLPEItem const* /*lpeitem*/) +void Effect::doAfterEffect(SPLPEItem const * /*lpeitem*/) { is_load = false; } @@ -1266,21 +1287,16 @@ void Effect::doOnException(SPLPEItem const * /*lpeitem*/) pathvector_after_effect = pathvector_before_effect; } - -void Effect::doOnRemove (SPLPEItem const* /*lpeitem*/) -{ -} -void Effect::doOnVisibilityToggled(SPLPEItem const* /*lpeitem*/) -{ -} -//secret impl methods (shhhh!) +void Effect::doOnRemove(SPLPEItem const * /*lpeitem*/) {} +void Effect::doOnVisibilityToggled(SPLPEItem const * /*lpeitem*/) {} +// secret impl methods (shhhh!) void Effect::doAfterEffect_impl(SPLPEItem const *lpeitem) { doAfterEffect(lpeitem); is_load = false; is_applied = false; } -void Effect::doOnApply_impl(SPLPEItem const* lpeitem) +void Effect::doOnApply_impl(SPLPEItem const *lpeitem) { sp_lpe_item = const_cast(lpeitem); is_applied = true; @@ -1291,15 +1307,15 @@ void Effect::doOnApply_impl(SPLPEItem const* lpeitem) // repeat inkscape versioning } -void Effect::doBeforeEffect_impl(SPLPEItem const* lpeitem) +void Effect::doBeforeEffect_impl(SPLPEItem const *lpeitem) { sp_lpe_item = const_cast(lpeitem); doBeforeEffect(lpeitem); update_helperpath(); } -void -Effect::writeParamsToSVG() { +void Effect::writeParamsToSVG() +{ std::vector::iterator p; for (p = param_vector.begin(); p != param_vector.end(); ++p) { (*p)->write_to_SVG(); @@ -1311,16 +1327,15 @@ Effect::writeParamsToSVG() { * applied, this is the method that processes the resulting path. Override it to customize it for * your LPE. But don't forget to call the parent method so that is_ready is set to true! */ -void -Effect::acceptParamPath (SPPath const*/*param_path*/) { +void Effect::acceptParamPath(SPPath const * /*param_path*/) +{ setReady(); } /* * Here be the doEffect function chain: */ -void -Effect::doEffect (SPCurve * curve) +void Effect::doEffect(SPCurve *curve) { Geom::PathVector orig_pathv = curve->get_pathvector(); @@ -1329,63 +1344,59 @@ Effect::doEffect (SPCurve * curve) curve->set_pathvector(result_pathv); } -Geom::PathVector -Effect::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector Effect::doEffect_path(Geom::PathVector const &path_in) { Geom::PathVector path_out; - if ( !concatenate_before_pwd2 ) { + if (!concatenate_before_pwd2) { // default behavior - for (const auto & i : path_in) { - Geom::Piecewise > pwd2_in = i.toPwSb(); - Geom::Piecewise > pwd2_out = doEffect_pwd2(pwd2_in); - Geom::PathVector path = Geom::path_from_piecewise( pwd2_out, LPE_CONVERSION_TOLERANCE); + for (const auto &i : path_in) { + Geom::Piecewise> pwd2_in = i.toPwSb(); + Geom::Piecewise> pwd2_out = doEffect_pwd2(pwd2_in); + Geom::PathVector path = Geom::path_from_piecewise(pwd2_out, LPE_CONVERSION_TOLERANCE); // add the output path vector to the already accumulated vector: - for (const auto & j : path) { + for (const auto &j : path) { path_out.push_back(j); } } } else { // concatenate the path into possibly discontinuous pwd2 - Geom::Piecewise > pwd2_in; - for (const auto & i : path_in) { - pwd2_in.concat( i.toPwSb() ); + Geom::Piecewise> pwd2_in; + for (const auto &i : path_in) { + pwd2_in.concat(i.toPwSb()); } - Geom::Piecewise > pwd2_out = doEffect_pwd2(pwd2_in); - path_out = Geom::path_from_piecewise( pwd2_out, LPE_CONVERSION_TOLERANCE); + Geom::Piecewise> pwd2_out = doEffect_pwd2(pwd2_in); + path_out = Geom::path_from_piecewise(pwd2_out, LPE_CONVERSION_TOLERANCE); } return path_out; } -Geom::Piecewise > -Effect::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> Effect::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { g_warning("Effect has no doEffect implementation"); return pwd2_in; } -void -Effect::readallParameters(Inkscape::XML::Node const* repr) +void Effect::readallParameters(Inkscape::XML::Node const *repr) { std::vector::iterator it = param_vector.begin(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); while (it != param_vector.end()) { - Parameter * param = *it; - const gchar * key = param->param_key.c_str(); - const gchar * value = repr->attribute(key); + Parameter *param = *it; + const gchar *key = param->param_key.c_str(); + const gchar *value = repr->attribute(key); if (value) { bool accepted = param->param_readSVGValue(value); if (!accepted) { g_warning("Effect::readallParameters - '%s' not accepted for %s", value, key); } } else { - Glib::ustring pref_path = (Glib::ustring)"/live_effects/" + - (Glib::ustring)LPETypeConverter.get_key(effectType()).c_str() + - (Glib::ustring)"/" + - (Glib::ustring)key; + Glib::ustring pref_path = (Glib::ustring) "/live_effects/" + + (Glib::ustring)LPETypeConverter.get_key(effectType()).c_str() + + (Glib::ustring) "/" + (Glib::ustring)key; bool valid = prefs->getEntry(pref_path).isValid(); - if(valid){ + if (valid) { param->param_update_default(prefs->getString(pref_path).c_str()); } else { param->param_set_default(); @@ -1396,10 +1407,9 @@ Effect::readallParameters(Inkscape::XML::Node const* repr) } /* This function does not and SHOULD NOT write to XML */ -void -Effect::setParameter(const gchar * key, const gchar * new_value) +void Effect::setParameter(const gchar *key, const gchar *new_value) { - Parameter * param = getParameter(key); + Parameter *param = getParameter(key); if (param) { if (new_value) { bool accepted = param->param_readSVGValue(new_value); @@ -1413,25 +1423,23 @@ Effect::setParameter(const gchar * key, const gchar * new_value) } } -void -Effect::registerParameter(Parameter * param) +void Effect::registerParameter(Parameter *param) { param_vector.push_back(param); } - /** * Add all registered LPE knotholder handles to the knotholder */ -void -Effect::addHandles(KnotHolder *knotholder, SPItem *item) { +void Effect::addHandles(KnotHolder *knotholder, SPItem *item) +{ using namespace Inkscape::LivePathEffect; // add handles provided by the effect itself addKnotHolderEntities(knotholder, item); // add handles provided by the effect's parameters (if any) - for (auto & p : param_vector) { + for (auto &p : param_vector) { p->addKnotHolderEntities(knotholder, item); } } @@ -1440,10 +1448,10 @@ Effect::addHandles(KnotHolder *knotholder, SPItem *item) { * Return a vector of PathVectors which contain all canvas indicators for this effect. * This is the function called by external code to get all canvas indicators (effect and its parameters) * lpeitem = the item onto which this effect is applied - * @todo change return type to one pathvector, add all paths to one pathvector instead of maintaining a vector of pathvectors + * @todo change return type to one pathvector, add all paths to one pathvector instead of maintaining a vector of + * pathvectors */ -std::vector -Effect::getCanvasIndicators(SPLPEItem const* lpeitem) +std::vector Effect::getCanvasIndicators(SPLPEItem const *lpeitem) { std::vector hp_vec; @@ -1451,7 +1459,7 @@ Effect::getCanvasIndicators(SPLPEItem const* lpeitem) addCanvasIndicators(lpeitem, hp_vec); // add indicators provided by the effect's parameters - for (auto & p : param_vector) { + for (auto &p : param_vector) { p->addCanvasIndicators(lpeitem, hp_vec); } @@ -1462,36 +1470,32 @@ Effect::getCanvasIndicators(SPLPEItem const* lpeitem) * Add possible canvas indicators (i.e., helperpaths other than the original path) to \a hp_vec * This function should be overwritten by derived effects if they want to provide their own helperpaths. */ -void -Effect::addCanvasIndicators(SPLPEItem const*/*lpeitem*/, std::vector &/*hp_vec*/) -{ -} +void Effect::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector & /*hp_vec*/) {} /** * Call to a method on nodetool to update the helper path from the effect */ -void -Effect::update_helperpath() { +void Effect::update_helperpath() +{ Inkscape::UI::Tools::sp_update_helperpath(SP_ACTIVE_DESKTOP); } /** * This *creates* a new widget, management of deletion should be done by the caller */ -Gtk::Widget * -Effect::newWidget() +Gtk::Widget *Effect::newWidget() { // use manage here, because after deletion of Effect object, others might still be pointing to this widget. - Gtk::VBox * vbox = Gtk::manage( new Gtk::VBox() ); + Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox()); vbox->set_border_width(5); std::vector::iterator it = param_vector.begin(); while (it != param_vector.end()) { if ((*it)->widget_is_visible) { - Parameter * param = *it; - Gtk::Widget * widg = param->param_newWidget(); - Glib::ustring * tip = param->param_getTooltip(); + Parameter *param = *it; + Gtk::Widget *widg = param->param_newWidget(); + Glib::ustring *tip = param->param_getTooltip(); if (widg) { if (param->widget_is_enabled) { widg->set_sensitive(true); @@ -1510,7 +1514,7 @@ Effect::newWidget() ++it; } - if(Gtk::Widget* widg = defaultParamSet()) { + if (Gtk::Widget *widg = defaultParamSet()) { vbox->pack_start(*widg, true, true, 2); } return dynamic_cast(vbox); @@ -1525,12 +1529,11 @@ bool sp_enter_tooltip(GdkEventCrossing *evt, Gtk::Widget *widg) /** * This *creates* a new widget, with default values setter */ -Gtk::Widget * -Effect::defaultParamSet() +Gtk::Widget *Effect::defaultParamSet() { // use manage here, because after deletion of Effect object, others might still be pointing to this widget. Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - Gtk::VBox * vbox_expander = Gtk::manage( new Gtk::VBox() ); + Gtk::VBox *vbox_expander = Gtk::manage(new Gtk::VBox()); Glib::ustring effectname = (Glib::ustring)Inkscape::LivePathEffect::LPETypeConverter.get_label(effectType()); Glib::ustring effectkey = (Glib::ustring)Inkscape::LivePathEffect::LPETypeConverter.get_key(effectType()); std::vector::iterator it = param_vector.begin(); @@ -1538,19 +1541,20 @@ Effect::defaultParamSet() while (it != param_vector.end()) { if ((*it)->widget_is_visible) { has_params = true; - Parameter * param = *it; - const gchar * key = param->param_key.c_str(); - const gchar * label = param->param_label.c_str(); + Parameter *param = *it; + const gchar *key = param->param_key.c_str(); + const gchar *label = param->param_label.c_str(); Glib::ustring value = param->param_getSVGValue(); - Glib::ustring defvalue = param->param_getDefaultSVGValue(); + Glib::ustring defvalue = param->param_getDefaultSVGValue(); Glib::ustring pref_path = "/live_effects/"; pref_path += effectkey; - pref_path +="/"; + pref_path += "/"; pref_path += key; bool valid = prefs->getEntry(pref_path).isValid(); - const gchar * set_or_upd; + const gchar *set_or_upd; Glib::ustring def = Glib::ustring(_("Default value: ")) + defvalue + Glib::ustring("\n"); - Glib::ustring ove = Glib::ustring(_("Default value overridden: ")) + Glib::ustring(prefs->getString(pref_path)) + Glib::ustring("\n"); + Glib::ustring ove = Glib::ustring(_("Default value overridden: ")) + + Glib::ustring(prefs->getString(pref_path)) + Glib::ustring("\n"); if (valid) { set_or_upd = _("Update"); def = Glib::ustring(_("Default value: ")) + defvalue + Glib::ustring("\n"); @@ -1558,7 +1562,7 @@ Effect::defaultParamSet() set_or_upd = _("Set"); ove = Glib::ustring(_("Default value overridden: None\n")); } - Gtk::HBox * vbox_param = Gtk::manage( new Gtk::HBox(true) ); + Gtk::HBox *vbox_param = Gtk::manage(new Gtk::HBox(true)); Gtk::HBox *namedicon = Gtk::manage(new Gtk::HBox(true)); Gtk::Label *parameter_label = Gtk::manage(new Gtk::Label(label, Gtk::ALIGN_START)); parameter_label->set_use_markup(true); @@ -1591,11 +1595,12 @@ Effect::defaultParamSet() ++it; } Glib::ustring tip = "" + effectname + (Glib::ustring)_(": Set default parameters"); - Gtk::Expander * expander = Gtk::manage(new Gtk::Expander(tip)); + Gtk::Expander *expander = Gtk::manage(new Gtk::Expander(tip)); expander->set_use_markup(true); expander->add(*vbox_expander); expander->set_expanded(defaultsopen); - expander->property_expanded().signal_changed().connect(sigc::bind<0>(sigc::mem_fun(*this, &Effect::onDefaultsExpanderChanged), expander )); + expander->property_expanded().signal_changed().connect( + sigc::bind<0>(sigc::mem_fun(*this, &Effect::onDefaultsExpanderChanged), expander)); if (has_params) { Gtk::Widget *vboxwidg = dynamic_cast(expander); vboxwidg->set_margin_bottom(5); @@ -1606,8 +1611,7 @@ Effect::defaultParamSet() } } -void -Effect::onDefaultsExpanderChanged(Gtk::Expander * expander) +void Effect::onDefaultsExpanderChanged(Gtk::Expander *expander) { defaultsopen = expander->get_expanded(); } @@ -1616,10 +1620,10 @@ void Effect::setDefaultParam(Glib::ustring pref_path, Glib::ustring tooltip, Par Gtk::Button *set, Gtk::Button *unset) { Glib::ustring value = param->param_getSVGValue(); - Glib::ustring defvalue = param->param_getDefaultSVGValue(); + Glib::ustring defvalue = param->param_getDefaultSVGValue(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setString(pref_path, value); - gchar * label = _("Update"); + gchar *label = _("Update"); set->set_label((Glib::ustring)label); unset->set_sensitive(true); Glib::ustring def = Glib::ustring(_("Default value: ")) + defvalue + Glib::ustring("\n"); @@ -1631,10 +1635,10 @@ void Effect::unsetDefaultParam(Glib::ustring pref_path, Glib::ustring tooltip, P Gtk::Button *set, Gtk::Button *unset) { Glib::ustring value = param->param_getSVGValue(); - Glib::ustring defvalue = param->param_getDefaultSVGValue(); + Glib::ustring defvalue = param->param_getDefaultSVGValue(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->remove(pref_path); - gchar * label = _("Set"); + gchar *label = _("Set"); set->set_label((Glib::ustring)label); unset->set_sensitive(false); Glib::ustring def = Glib::ustring(_("Default value: ")) + defvalue + Glib::ustring("\n"); @@ -1655,16 +1659,16 @@ SPDocument *Effect::getSPDoc() return lpeobj->document; } -Parameter * -Effect::getParameter(const char * key) +Parameter *Effect::getParameter(const char *key) { Glib::ustring stringkey(key); - if (param_vector.empty()) return nullptr; + if (param_vector.empty()) + return nullptr; std::vector::iterator it = param_vector.begin(); while (it != param_vector.end()) { - Parameter * param = *it; - if ( param->param_key == key) { + Parameter *param = *it; + if (param->param_key == key) { return param; } @@ -1674,8 +1678,7 @@ Effect::getParameter(const char * key) return nullptr; } -Parameter * -Effect::getNextOncanvasEditableParam() +Parameter *Effect::getNextOncanvasEditableParam() { if (param_vector.size() == 0) // no parameters return nullptr; @@ -1687,12 +1690,12 @@ Effect::getNextOncanvasEditableParam() int old_it = oncanvasedit_it; do { - Parameter * param = param_vector[oncanvasedit_it]; - if(param && param->oncanvas_editable) { + Parameter *param = param_vector[oncanvasedit_it]; + if (param && param->oncanvas_editable) { return param; } else { oncanvasedit_it++; - if (oncanvasedit_it == static_cast(param_vector.size())) { // loop round the map + if (oncanvasedit_it == static_cast(param_vector.size())) { // loop round the map oncanvasedit_it = 0; } } @@ -1701,28 +1704,28 @@ Effect::getNextOncanvasEditableParam() return nullptr; } -void -Effect::editNextParamOncanvas(SPItem * item, SPDesktop * desktop) +void Effect::editNextParamOncanvas(SPItem *item, SPDesktop *desktop) { - if (!desktop) return; + if (!desktop) + return; - Parameter * param = getNextOncanvasEditableParam(); + Parameter *param = getNextOncanvasEditableParam(); if (param) { param->param_editOncanvas(item, desktop); gchar *message = g_strdup_printf(_("Editing parameter %s."), param->param_label.c_str()); desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, message); g_free(message); } else { - desktop->messageStack()->flash( Inkscape::WARNING_MESSAGE, - _("None of the applied path effect's parameters can be edited on-canvas.") ); + desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("None of the applied path effect's parameters can be edited on-canvas.")); } } -/* This function should reset the defaults and is used for example to initialize an effect right after it has been applied to a path -* The nice thing about this is that this function can use knowledge of the original path and set things accordingly for example to the size or origin of the original path! -*/ -void -Effect::resetDefaults(SPItem const* /*item*/) +/* This function should reset the defaults and is used for example to initialize an effect right after it has been + * applied to a path The nice thing about this is that this function can use knowledge of the original path and set + * things accordingly for example to the size or origin of the original path! + */ +void Effect::resetDefaults(SPItem const * /*item*/) { std::vector::iterator p; for (p = param_vector.begin(); p != param_vector.end(); ++p) { @@ -1731,8 +1734,7 @@ Effect::resetDefaults(SPItem const* /*item*/) } } -bool -Effect::providesKnotholder() const +bool Effect::providesKnotholder() const { // does the effect actively provide any knotholder entities of its own? if (_provides_knotholder_entities) { diff --git a/src/live_effects/effect.h b/src/live_effects/effect.h index f631646a79740ee6daaa3ca1f8c73afc0da22284..4dc45ba8235970d1f8827e9bbecd769411ab9cb2 100644 --- a/src/live_effects/effect.h +++ b/src/live_effects/effect.h @@ -8,86 +8,89 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "effect-enum.h" -#include "parameter/bool.h" -#include "parameter/hidden.h" -#include "ui/widget/registry.h" #include <2geom/forward.h> #include #include #include +#include "effect-enum.h" +#include "parameter/bool.h" +#include "parameter/hidden.h" +#include "ui/widget/registry.h" -#define LPE_CONVERSION_TOLERANCE 0.01 // FIXME: find good solution for this. +#define LPE_CONVERSION_TOLERANCE 0.01 // FIXME: find good solution for this. -class SPDocument; -class SPDesktop; -class SPItem; -class LivePathEffectObject; -class SPLPEItem; -class KnotHolder; -class KnotHolderEntity; -class SPPath; -class SPCurve; +class SPDocument; +class SPDesktop; +class SPItem; +class LivePathEffectObject; +class SPLPEItem; +class KnotHolder; +class KnotHolderEntity; +class SPPath; +class SPCurve; namespace Gtk { - class Widget; +class Widget; } namespace Inkscape { namespace XML { - class Node; +class Node; } namespace LivePathEffect { -enum LPEPathFlashType { +enum LPEPathFlashType +{ SUPPRESS_FLASH, -// PERMANENT_FLASH, + // PERMANENT_FLASH, DEFAULT }; -enum LPEAction { +enum LPEAction +{ LPE_ERASE = 0, LPE_TO_OBJECTS, LPE_VISIBILITY }; -class Effect { +class Effect +{ public: - static Effect* New(EffectType lpenr, LivePathEffectObject *lpeobj); - static void createAndApply(const char* name, SPDocument *doc, SPItem *item); + static Effect *New(EffectType lpenr, LivePathEffectObject *lpeobj); + static void createAndApply(const char *name, SPDocument *doc, SPItem *item); static void createAndApply(EffectType type, SPDocument *doc, SPItem *item); virtual ~Effect(); - Effect(const Effect&) = delete; - Effect& operator=(const Effect&) = delete; + Effect(const Effect &) = delete; + Effect &operator=(const Effect &) = delete; EffectType effectType() const; - //basically, to get this method called before the derived classes, a bit - //of indirection is needed. We first call these methods, then the below. + // basically, to get this method called before the derived classes, a bit + // of indirection is needed. We first call these methods, then the below. void doAfterEffect_impl(SPLPEItem const *lpeitem); - void doOnApply_impl(SPLPEItem const* lpeitem); - void doBeforeEffect_impl(SPLPEItem const* lpeitem); + void doOnApply_impl(SPLPEItem const *lpeitem); + void doBeforeEffect_impl(SPLPEItem const *lpeitem); void setCurrentZoom(double cZ); void setSelectedNodePoints(std::vector sNP); bool isNodePointSelected(Geom::Point const &nodePoint) const; - virtual void doOnApply (SPLPEItem const* lpeitem); - virtual void doBeforeEffect (SPLPEItem const* lpeitem); + virtual void doOnApply(SPLPEItem const *lpeitem); + virtual void doBeforeEffect(SPLPEItem const *lpeitem); virtual void transform_multiply(Geom::Affine const &postmul, bool set); - virtual void doAfterEffect (SPLPEItem const* lpeitem); + virtual void doAfterEffect(SPLPEItem const *lpeitem); virtual void doOnException(SPLPEItem const *lpeitem); - virtual void doOnRemove (SPLPEItem const* lpeitem); - virtual void doOnVisibilityToggled(SPLPEItem const* lpeitem); + virtual void doOnRemove(SPLPEItem const *lpeitem); + virtual void doOnVisibilityToggled(SPLPEItem const *lpeitem); void writeParamsToSVG(); - virtual void acceptParamPath (SPPath const* param_path); + virtual void acceptParamPath(SPPath const *param_path); static int acceptsNumClicks(EffectType type); int acceptsNumClicks() const { return acceptsNumClicks(effectType()); } - SPShape * getCurrentShape() const { return current_shape; }; - void setCurrentShape(SPShape * shape) { current_shape = shape; } + SPShape *getCurrentShape() const { return current_shape; }; + void setCurrentShape(SPShape *shape) { current_shape = shape; } void processObjects(LPEAction lpe_action); /* @@ -98,14 +101,14 @@ public: inline bool isReady() const { return is_ready; } inline void setReady(bool ready = true) { is_ready = ready; } - virtual void doEffect (SPCurve * curve); + virtual void doEffect(SPCurve *curve); - virtual Gtk::Widget * newWidget(); - virtual Gtk::Widget * defaultParamSet(); + virtual Gtk::Widget *newWidget(); + virtual Gtk::Widget *defaultParamSet(); /** * Sets all parameters to their default values and writes them to SVG. */ - virtual void resetDefaults(SPItem const* item); + virtual void resetDefaults(SPItem const *item); // /TODO: providesKnotholder() is currently used as an indicator of whether a nodepath is // created for an item or not. When we allow both at the same time, this needs rethinking! @@ -114,28 +117,26 @@ public: // (but spiro lpe still needs it!) virtual LPEPathFlashType pathFlashType() const { return DEFAULT; } void addHandles(KnotHolder *knotholder, SPItem *item); - std::vector getCanvasIndicators(SPLPEItem const* lpeitem); + std::vector getCanvasIndicators(SPLPEItem const *lpeitem); void update_helperpath(); bool has_exception; - inline bool providesOwnFlashPaths() const { - return provides_own_flash_paths || show_orig_path; - } + inline bool providesOwnFlashPaths() const { return provides_own_flash_paths || show_orig_path; } inline bool showOrigPath() const { return show_orig_path; } - Glib::ustring getName() const; - Inkscape::XML::Node * getRepr(); - SPDocument * getSPDoc(); - LivePathEffectObject * getLPEObj() {return lpeobj;}; - LivePathEffectObject const * getLPEObj() const {return lpeobj;}; - Parameter * getParameter(const char * key); + Glib::ustring getName() const; + Inkscape::XML::Node *getRepr(); + SPDocument *getSPDoc(); + LivePathEffectObject *getLPEObj() { return lpeobj; }; + LivePathEffectObject const *getLPEObj() const { return lpeobj; }; + Parameter *getParameter(const char *key); - void readallParameters(Inkscape::XML::Node const* repr); - void setParameter(const gchar * key, const gchar * new_value); + void readallParameters(Inkscape::XML::Node const *repr); + void setParameter(const gchar *key, const gchar *new_value); inline bool isVisible() const { return is_visible; } - void editNextParamOncanvas(SPItem * item, SPDesktop * desktop); + void editNextParamOncanvas(SPItem *item, SPDesktop *desktop); bool apply_to_clippath_and_mask; bool keep_paths; // set this to false allow retain extra generated objects, see measure line LPE bool is_load; @@ -147,7 +148,7 @@ public: SPLPEItem *sp_lpe_item; // these get stored in doBeforeEffect_impl, and derived classes may do as they please with // them. SPShape *current_shape; // these get stored in performPathEffects. - protected: +protected: Effect(LivePathEffectObject *lpeobject); // provide a set of doEffect functions so the developer has a choice @@ -155,17 +156,16 @@ public: // the order in which they appear is the order in which they are // called by this base class. (i.e. doEffect(SPCurve * curve) defaults to calling // doEffect(Geom::PathVector ) - virtual Geom::PathVector - doEffect_path (Geom::PathVector const & path_in); - virtual Geom::Piecewise > - doEffect_pwd2 (Geom::Piecewise > const & pwd2_in); + virtual Geom::PathVector doEffect_path(Geom::PathVector const &path_in); + virtual Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in); - void registerParameter(Parameter * param); - Parameter * getNextOncanvasEditableParam(); + void registerParameter(Parameter *param); + Parameter *getNextOncanvasEditableParam(); - virtual void addKnotHolderEntities(KnotHolder * /*knotholder*/, SPItem * /*item*/) {}; + virtual void addKnotHolderEntities(KnotHolder * /*knotholder*/, SPItem * /*item*/){}; - virtual void addCanvasIndicators(SPLPEItem const* lpeitem, std::vector &hp_vec); + virtual void addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec); std::vector param_vector; bool _provides_knotholder_entities; @@ -187,7 +187,7 @@ public: std::vector selectedNodesPoints; private: - void onDefaultsExpanderChanged(Gtk::Expander * expander); + void onDefaultsExpanderChanged(Gtk::Expander *expander); void setDefaultParam(Glib::ustring pref_path, Glib::ustring tooltip, Parameter *param, Gtk::Image *info, Gtk::Button *set, Gtk::Button *unset); void unsetDefaultParam(Glib::ustring pref_path, Glib::ustring tooltip, Parameter *param, Gtk::Image *info, @@ -198,8 +198,8 @@ private: bool defaultsopen; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/fill-conversion.cpp b/src/live_effects/fill-conversion.cpp index d770eece90a5677c6685bdea0ac20642771c37e7..1cfcdcaa10c1c7abd425fe6023b27bdaed0ce336 100644 --- a/src/live_effects/fill-conversion.cpp +++ b/src/live_effects/fill-conversion.cpp @@ -13,28 +13,28 @@ #include "fill-conversion.h" -#include "document.h" #include "desktop-style.h" -#include "object/sp-shape.h" +#include "document.h" #include "object/sp-defs.h" #include "object/sp-paint-server.h" -#include "svg/svg-color.h" -#include "svg/css-ostringstream.h" +#include "object/sp-shape.h" #include "style.h" +#include "svg/css-ostringstream.h" +#include "svg/svg-color.h" static SPObject *generate_linked_fill(SPShape *source) { // Create new fill and effect object SPDocument *doc = source->document; - SPObject *defs = doc->getDefs(); + SPObject *defs = doc->getDefs(); Inkscape::XML::Node *effectRepr = doc->getReprDoc()->createElement("inkscape:path-effect"); - SPObject *effectObj = nullptr; - Inkscape::XML::Node *pathRepr = doc->getReprDoc()->createElement("svg:path"); - SPObject *pathObj = nullptr; + SPObject *effectObj = nullptr; + Inkscape::XML::Node *pathRepr = doc->getReprDoc()->createElement("svg:path"); + SPObject *pathObj = nullptr; gchar *effectTarget = nullptr; - gchar *pathTarget = nullptr; + gchar *pathTarget = nullptr; effectTarget = g_strdup_printf("#%s,0,1", source->getId()); effectRepr->setAttribute("effect", "fill_between_many"); @@ -77,7 +77,8 @@ static void convert_fill_color(SPCSSAttr *css, SPObject *source) { char c[64]; - sp_svg_write_color(c, sizeof(c), source->style->fill.value.color.toRGBA32(SP_SCALE24_TO_FLOAT(source->style->fill_opacity.value))); + sp_svg_write_color( + c, sizeof(c), source->style->fill.value.color.toRGBA32(SP_SCALE24_TO_FLOAT(source->style->fill_opacity.value))); sp_repr_css_set_property(css, "fill", c); } @@ -85,7 +86,9 @@ static void convert_stroke_color(SPCSSAttr *css, SPObject *source) { char c[64]; - sp_svg_write_color(c, sizeof(c), source->style->stroke.value.color.toRGBA32(SP_SCALE24_TO_FLOAT(source->style->stroke_opacity.value))); + sp_svg_write_color( + c, sizeof(c), + source->style->stroke.value.color.toRGBA32(SP_SCALE24_TO_FLOAT(source->style->stroke_opacity.value))); sp_repr_css_set_property(css, "fill", c); } @@ -93,7 +96,8 @@ static void revert_stroke_color(SPCSSAttr *css, SPObject *source) { char c[64]; - sp_svg_write_color(c, sizeof(c), source->style->fill.value.color.toRGBA32(SP_SCALE24_TO_FLOAT(source->style->fill_opacity.value))); + sp_svg_write_color( + c, sizeof(c), source->style->fill.value.color.toRGBA32(SP_SCALE24_TO_FLOAT(source->style->fill_opacity.value))); sp_repr_css_set_property(css, "stroke", c); } @@ -206,7 +210,8 @@ void lpe_shape_revert_stroke_and_fill(SPShape *shape, double width) sp_repr_css_set_property(css, "fill", "none"); } - Inkscape:CSSOStringStream os; +Inkscape: + CSSOStringStream os; os << fabs(width); sp_repr_css_set_property(css, "stroke-width", os.str().c_str()); @@ -214,8 +219,8 @@ void lpe_shape_revert_stroke_and_fill(SPShape *shape, double width) sp_repr_css_attr_unref(css); } -} -} +} // namespace LivePathEffect +} // namespace Inkscape /* Local Variables: diff --git a/src/live_effects/fill-conversion.h b/src/live_effects/fill-conversion.h index e58801993fbecad989f59e4770f6daca67e73b96..6e33dc1df2040382e68c0d88df006379af27a718 100644 --- a/src/live_effects/fill-conversion.h +++ b/src/live_effects/fill-conversion.h @@ -29,8 +29,8 @@ void lpe_shape_convert_stroke_and_fill(SPShape *shape); */ void lpe_shape_revert_stroke_and_fill(SPShape *shape, double width); -} -} +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-angle_bisector.cpp b/src/live_effects/lpe-angle_bisector.cpp index c1e7befd393f239c2d0b89f5c052ca5d6c02c29d..4238dfe39f7d986fb62054b7a2ec8930d44e4a3c 100644 --- a/src/live_effects/lpe-angle_bisector.cpp +++ b/src/live_effects/lpe-angle_bisector.cpp @@ -10,8 +10,8 @@ */ #include "live_effects/lpe-angle_bisector.h" -#include "2geom/sbasis-to-bezier.h" +#include "2geom/sbasis-to-bezier.h" #include "knot-holder-entity.h" #include "knotholder.h" // TODO due to internal breakage in glibmm headers, this must be last: @@ -22,39 +22,41 @@ namespace LivePathEffect { namespace AB { -class KnotHolderEntityLeftEnd : public LPEKnotHolderEntity { +class KnotHolderEntityLeftEnd : public LPEKnotHolderEntity +{ public: - KnotHolderEntityLeftEnd(LPEAngleBisector* effect) : LPEKnotHolderEntity(effect) {}; + KnotHolderEntityLeftEnd(LPEAngleBisector *effect) + : LPEKnotHolderEntity(effect){}; void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; }; -class KnotHolderEntityRightEnd : public LPEKnotHolderEntity { +class KnotHolderEntityRightEnd : public LPEKnotHolderEntity +{ public: - KnotHolderEntityRightEnd(LPEAngleBisector* effect) : LPEKnotHolderEntity(effect) {}; + KnotHolderEntityRightEnd(LPEAngleBisector *effect) + : LPEKnotHolderEntity(effect){}; void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; }; } // namespace AB -LPEAngleBisector::LPEAngleBisector(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - length_left(_("Length left:"), _("Specifies the left end of the bisector"), "length-left", &wr, this, 0), - length_right(_("Length right:"), _("Specifies the right end of the bisector"), "length-right", &wr, this, 250) +LPEAngleBisector::LPEAngleBisector(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , length_left(_("Length left:"), _("Specifies the left end of the bisector"), "length-left", &wr, this, 0) + , length_right(_("Length right:"), _("Specifies the right end of the bisector"), "length-right", &wr, this, 250) { show_orig_path = true; _provides_knotholder_entities = true; - registerParameter( dynamic_cast(&length_left) ); - registerParameter( dynamic_cast(&length_right) ); + registerParameter(dynamic_cast(&length_left)); + registerParameter(dynamic_cast(&length_right)); } -LPEAngleBisector::~LPEAngleBisector() -= default; +LPEAngleBisector::~LPEAngleBisector() = default; -Geom::PathVector -LPEAngleBisector::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPEAngleBisector::doEffect_path(Geom::PathVector const &path_in) { using namespace Geom; @@ -65,34 +67,31 @@ LPEAngleBisector::doEffect_path (Geom::PathVector const & path_in) double angle = angle_between(B - ptA, C - ptA); - dir = unit_vector(B - ptA) * Rotate(angle/2); + dir = unit_vector(B - ptA) * Rotate(angle / 2); Geom::Point D = ptA - dir * length_left; Geom::Point E = ptA + dir * length_right; - Piecewise > output = Piecewise >(D2(SBasis(D[X], E[X]), SBasis(D[Y], E[Y]))); + Piecewise> output = Piecewise>(D2(SBasis(D[X], E[X]), SBasis(D[Y], E[Y]))); return path_from_piecewise(output, LPE_CONVERSION_TOLERANCE); } -void -LPEAngleBisector::addKnotHolderEntities(KnotHolder *knotholder, SPDesktop *desktop, SPItem *item) { - { - KnotHolderEntity *e = new AB::KnotHolderEntityLeftEnd(this); +void LPEAngleBisector::addKnotHolderEntities(KnotHolder *knotholder, SPDesktop *desktop, + SPItem *item){{KnotHolderEntity *e = new AB::KnotHolderEntityLeftEnd(this); e->create(desktop, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the \"left\" end of the bisector")); knotholder->add(e); - } - { - KnotHolderEntity *e = new AB::KnotHolderEntityRightEnd(this); - e->create(desktop, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the \"right\" end of the bisector")); - knotholder->add(e); - } -}; +} // namespace LivePathEffect +{ + KnotHolderEntity *e = new AB::KnotHolderEntityRightEnd(this); + e->create(desktop, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the \"right\" end of the bisector")); + knotholder->add(e); +} +}; // namespace Inkscape namespace AB { -void -KnotHolderEntityLeftEnd::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) +void KnotHolderEntityLeftEnd::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { LPEAngleBisector *lpe = dynamic_cast(_effect); @@ -101,11 +100,10 @@ KnotHolderEntityLeftEnd::knot_set(Geom::Point const &p, Geom::Point const &/*ori double lambda = Geom::nearest_time(s, lpe->ptA, lpe->dir); lpe->length_left.param_set_value(-lambda); - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, true); } -void -KnotHolderEntityRightEnd::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) +void KnotHolderEntityRightEnd::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { LPEAngleBisector *lpe = dynamic_cast(_effect); @@ -114,20 +112,18 @@ KnotHolderEntityRightEnd::knot_set(Geom::Point const &p, Geom::Point const &/*or double lambda = Geom::nearest_time(s, lpe->ptA, lpe->dir); lpe->length_right.param_set_value(lambda); - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, true); } -Geom::Point -KnotHolderEntityLeftEnd::knot_get() const +Geom::Point KnotHolderEntityLeftEnd::knot_get() const { - LPEAngleBisector const* lpe = dynamic_cast(_effect); + LPEAngleBisector const *lpe = dynamic_cast(_effect); return lpe->ptA - lpe->dir * lpe->length_left; } -Geom::Point -KnotHolderEntityRightEnd::knot_get() const +Geom::Point KnotHolderEntityRightEnd::knot_get() const { - LPEAngleBisector const* lpe = dynamic_cast(_effect); + LPEAngleBisector const *lpe = dynamic_cast(_effect); return lpe->ptA + lpe->dir * lpe->length_right; } @@ -135,7 +131,7 @@ KnotHolderEntityRightEnd::knot_get() const /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-angle_bisector.h b/src/live_effects/lpe-angle_bisector.h index b780fcee7e88eff418400d9ff293a714fcfca573..14dedd2cb3dabb4dd360616b3f1a33f471edbb4c 100644 --- a/src/live_effects/lpe-angle_bisector.h +++ b/src/live_effects/lpe-angle_bisector.h @@ -19,35 +19,36 @@ namespace Inkscape { namespace LivePathEffect { namespace AB { - // we use a separate namespace to avoid clashes with other LPEs - class KnotHolderEntityLeftEnd; - class KnotHolderEntityRightEnd; -} +// we use a separate namespace to avoid clashes with other LPEs +class KnotHolderEntityLeftEnd; +class KnotHolderEntityRightEnd; +} // namespace AB -class LPEAngleBisector : public Effect { +class LPEAngleBisector : public Effect +{ public: LPEAngleBisector(LivePathEffectObject *lpeobject); ~LPEAngleBisector() override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; friend class AB::KnotHolderEntityLeftEnd; friend class AB::KnotHolderEntityRightEnd; void addKnotHolderEntities(KnotHolder *knotholder, SPDesktop *desktop, SPItem *item); -//private: + // private: ScalarParam length_left; ScalarParam length_right; Geom::Point ptA; Geom::Point dir; - LPEAngleBisector(const LPEAngleBisector&); - LPEAngleBisector& operator=(const LPEAngleBisector&); + LPEAngleBisector(const LPEAngleBisector &); + LPEAngleBisector &operator=(const LPEAngleBisector &); }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-attach-path.cpp b/src/live_effects/lpe-attach-path.cpp index e266b0a0febe43490454276fa802faa334f5bc56..637b572f4936eac237f4d36438e474ab48325240 100644 --- a/src/live_effects/lpe-attach-path.cpp +++ b/src/live_effects/lpe-attach-path.cpp @@ -5,45 +5,51 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "live_effects/lpe-attach-path.h" -#include "display/curve.h" + +#include + #include "2geom/path-sink.h" +#include "display/curve.h" // TODO due to internal breakage in glibmm headers, this must be last: #include namespace Inkscape { namespace LivePathEffect { -LPEAttachPath::LPEAttachPath(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - start_path(_("Start path:"), _("Path to attach to the start of this path"), "startpath", &wr, this), - start_path_position(_("Start path position:"), _("Position to attach path start to"), "startposition", &wr, this, 0.0), - start_path_curve_start(_("Start path curve start:"), _("Starting curve"), "startcurvestart", &wr, this, Geom::Point(20,0)/*, true*/), - start_path_curve_end(_("Start path curve end:"), _("Ending curve"), "startcurveend", &wr, this, Geom::Point(20,0)/*, true*/), - end_path(_("End path:"), _("Path to attach to the end of this path"), "endpath", &wr, this), - end_path_position(_("End path position:"), _("Position to attach path end to"), "endposition", &wr, this, 0.0), - end_path_curve_start(_("End path curve start:"), _("Starting curve"), "endcurvestart", &wr, this, Geom::Point(20,0)/*, true*/), - end_path_curve_end(_("End path curve end:"), _("Ending curve"), "endcurveend", &wr, this, Geom::Point(20,0)/*, true*/) +LPEAttachPath::LPEAttachPath(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , start_path(_("Start path:"), _("Path to attach to the start of this path"), "startpath", &wr, this) + , start_path_position(_("Start path position:"), _("Position to attach path start to"), "startposition", &wr, this, + 0.0) + , start_path_curve_start(_("Start path curve start:"), _("Starting curve"), "startcurvestart", &wr, this, + Geom::Point(20, 0) /*, true*/) + , start_path_curve_end(_("Start path curve end:"), _("Ending curve"), "startcurveend", &wr, this, + Geom::Point(20, 0) /*, true*/) + , end_path(_("End path:"), _("Path to attach to the end of this path"), "endpath", &wr, this) + , end_path_position(_("End path position:"), _("Position to attach path end to"), "endposition", &wr, this, 0.0) + , end_path_curve_start(_("End path curve start:"), _("Starting curve"), "endcurvestart", &wr, this, + Geom::Point(20, 0) /*, true*/) + , end_path_curve_end(_("End path curve end:"), _("Ending curve"), "endcurveend", &wr, this, + Geom::Point(20, 0) /*, true*/) { registerParameter(&start_path); registerParameter(&start_path_position); registerParameter(&start_path_curve_start); registerParameter(&start_path_curve_end); - + registerParameter(&end_path); registerParameter(&end_path_position); registerParameter(&end_path_curve_start); registerParameter(&end_path_curve_end); - //perceived_path = true; + // perceived_path = true; show_orig_path = true; curve_start_previous_origin = start_path_curve_end.getOrigin(); curve_end_previous_origin = end_path_curve_end.getOrigin(); } -LPEAttachPath::~LPEAttachPath() -= default; +LPEAttachPath::~LPEAttachPath() = default; void LPEAttachPath::resetDefaults(SPItem const * /*item*/) { @@ -51,59 +57,70 @@ void LPEAttachPath::resetDefaults(SPItem const * /*item*/) curve_end_previous_origin = end_path_curve_end.getOrigin(); } -void LPEAttachPath::doEffect (SPCurve * curve) +void LPEAttachPath::doEffect(SPCurve *curve) { Geom::PathVector this_pathv = curve->get_pathvector(); if (sp_lpe_item && !this_pathv.empty()) { Geom::Path p = Geom::Path(this_pathv.front().initialPoint()); - + bool set_start_end = start_path_curve_end.getOrigin() != curve_start_previous_origin; bool set_end_end = end_path_curve_end.getOrigin() != curve_end_previous_origin; - - if (start_path.linksToPath()) { + if (start_path.linksToPath()) { Geom::PathVector linked_pathv = start_path.get_pathvector(); Geom::Affine linkedtransform = start_path.getObject()->getRelativeTransform(sp_lpe_item); - if ( !linked_pathv.empty() ) - { + if (!linked_pathv.empty()) { Geom::Path transformedpath = linked_pathv.front() * linkedtransform; start_path_curve_start.setOrigin(this_pathv.front().initialPoint()); std::vector derivs = this_pathv.front().front().pointAndDerivatives(0, 3); - + for (unsigned deriv_n = 1; deriv_n < derivs.size(); deriv_n++) { Geom::Coord length = derivs[deriv_n].length(); - if ( ! Geom::are_near(length, 0) ) { + if (!Geom::are_near(length, 0)) { if (set_start_end) { - start_path_position.param_set_value(transformedpath.nearestTime(start_path_curve_end.getOrigin()).asFlatTime()); + start_path_position.param_set_value( + transformedpath.nearestTime(start_path_curve_end.getOrigin()).asFlatTime()); } - + if (start_path_position > transformedpath.size()) { start_path_position.param_set_value(transformedpath.size()); } else if (start_path_position < 0) { start_path_position.param_set_value(0); } - Geom::Curve const *c = start_path_position >= transformedpath.size() ? - &transformedpath.back() : &transformedpath.at((int)start_path_position); - - std::vector derivs_2 = c->pointAndDerivatives(start_path_position >= transformedpath.size() ? 1 : (start_path_position - (int)start_path_position), 3); + Geom::Curve const *c = start_path_position >= transformedpath.size() + ? &transformedpath.back() + : &transformedpath.at((int)start_path_position); + + std::vector derivs_2 = + c->pointAndDerivatives(start_path_position >= transformedpath.size() + ? 1 + : (start_path_position - (int)start_path_position), + 3); for (unsigned deriv_n_2 = 1; deriv_n_2 < derivs_2.size(); deriv_n_2++) { Geom::Coord length_2 = derivs[deriv_n_2].length(); - if ( ! Geom::are_near(length_2, 0) ) { + if (!Geom::are_near(length_2, 0)) { start_path_curve_end.setOrigin(derivs_2[0]); curve_start_previous_origin = start_path_curve_end.getOrigin(); - double startangle = atan2(start_path_curve_start.getVector().y(), start_path_curve_start.getVector().x()); - double endangle = atan2(start_path_curve_end.getVector().y(), start_path_curve_end.getVector().x()); + double startangle = atan2(start_path_curve_start.getVector().y(), + start_path_curve_start.getVector().x()); + double endangle = + atan2(start_path_curve_end.getVector().y(), start_path_curve_end.getVector().x()); double startderiv = atan2(derivs[deriv_n].y(), derivs[deriv_n].x()); double endderiv = atan2(derivs_2[deriv_n_2].y(), derivs_2[deriv_n_2].x()); - Geom::Point pt1 = Geom::Point(start_path_curve_start.getVector().length() * cos(startangle + startderiv), start_path_curve_start.getVector().length() * sin(startangle + startderiv)); - Geom::Point pt2 = Geom::Point(start_path_curve_end.getVector().length() * cos(endangle + endderiv), start_path_curve_end.getVector().length() * sin(endangle + endderiv)); + Geom::Point pt1 = Geom::Point( + start_path_curve_start.getVector().length() * cos(startangle + startderiv), + start_path_curve_start.getVector().length() * sin(startangle + startderiv)); + Geom::Point pt2 = + Geom::Point(start_path_curve_end.getVector().length() * cos(endangle + endderiv), + start_path_curve_end.getVector().length() * sin(endangle + endderiv)); p = Geom::Path(derivs_2[0]); - p.appendNew(-pt2 + derivs_2[0], -pt1 + this_pathv.front().initialPoint(), this_pathv.front().initialPoint()); + p.appendNew(-pt2 + derivs_2[0], + -pt1 + this_pathv.front().initialPoint(), + this_pathv.front().initialPoint()); break; - } } break; @@ -111,55 +128,63 @@ void LPEAttachPath::doEffect (SPCurve * curve) } } } - + p.append(this_pathv.front()); - - if (end_path.linksToPath()) { + if (end_path.linksToPath()) { Geom::PathVector linked_pathv = end_path.get_pathvector(); Geom::Affine linkedtransform = end_path.getObject()->getRelativeTransform(sp_lpe_item); - if ( !linked_pathv.empty() ) - { + if (!linked_pathv.empty()) { Geom::Path transformedpath = linked_pathv.front() * linkedtransform; - Geom::Curve * last_seg_reverse = this_pathv.front().back().reverse(); - + Geom::Curve *last_seg_reverse = this_pathv.front().back().reverse(); + end_path_curve_start.setOrigin(last_seg_reverse->initialPoint()); std::vector derivs = last_seg_reverse->pointAndDerivatives(0, 3); for (unsigned deriv_n = 1; deriv_n < derivs.size(); deriv_n++) { Geom::Coord length = derivs[deriv_n].length(); - if ( ! Geom::are_near(length, 0) ) { + if (!Geom::are_near(length, 0)) { if (set_end_end) { - end_path_position.param_set_value(transformedpath.nearestTime(end_path_curve_end.getOrigin()).asFlatTime()); + end_path_position.param_set_value( + transformedpath.nearestTime(end_path_curve_end.getOrigin()).asFlatTime()); } - + if (end_path_position > transformedpath.size()) { end_path_position.param_set_value(transformedpath.size()); } else if (end_path_position < 0) { end_path_position.param_set_value(0); } - const Geom::Curve *c = end_path_position >= transformedpath.size() ? - &transformedpath.back() : &transformedpath.at((int)end_path_position); - - std::vector derivs_2 = c->pointAndDerivatives(end_path_position >= transformedpath.size() ? 1 : (end_path_position - (int)end_path_position), 3); + const Geom::Curve *c = end_path_position >= transformedpath.size() + ? &transformedpath.back() + : &transformedpath.at((int)end_path_position); + + std::vector derivs_2 = c->pointAndDerivatives( + end_path_position >= transformedpath.size() ? 1 + : (end_path_position - (int)end_path_position), + 3); for (unsigned deriv_n_2 = 1; deriv_n_2 < derivs_2.size(); deriv_n_2++) { Geom::Coord length_2 = derivs[deriv_n_2].length(); - if ( ! Geom::are_near(length_2, 0) ) { - + if (!Geom::are_near(length_2, 0)) { end_path_curve_end.setOrigin(derivs_2[0]); curve_end_previous_origin = end_path_curve_end.getOrigin(); - - double startangle = atan2(end_path_curve_start.getVector().y(), end_path_curve_start.getVector().x()); - double endangle = atan2(end_path_curve_end.getVector().y(), end_path_curve_end.getVector().x()); + + double startangle = + atan2(end_path_curve_start.getVector().y(), end_path_curve_start.getVector().x()); + double endangle = + atan2(end_path_curve_end.getVector().y(), end_path_curve_end.getVector().x()); double startderiv = atan2(derivs[deriv_n].y(), derivs[deriv_n].x()); double endderiv = atan2(derivs_2[deriv_n_2].y(), derivs_2[deriv_n_2].x()); - Geom::Point pt1 = Geom::Point(end_path_curve_start.getVector().length() * cos(startangle + startderiv), end_path_curve_start.getVector().length() * sin(startangle + startderiv)); - Geom::Point pt2 = Geom::Point(end_path_curve_end.getVector().length() * cos(endangle + endderiv), end_path_curve_end.getVector().length() * sin(endangle + endderiv)); - p.appendNew(-pt1 + this_pathv.front().finalPoint(), -pt2 + derivs_2[0], derivs_2[0]); + Geom::Point pt1 = Geom::Point( + end_path_curve_start.getVector().length() * cos(startangle + startderiv), + end_path_curve_start.getVector().length() * sin(startangle + startderiv)); + Geom::Point pt2 = + Geom::Point(end_path_curve_end.getVector().length() * cos(endangle + endderiv), + end_path_curve_end.getVector().length() * sin(endangle + endderiv)); + p.appendNew(-pt1 + this_pathv.front().finalPoint(), + -pt2 + derivs_2[0], derivs_2[0]); break; - } } break; diff --git a/src/live_effects/lpe-attach-path.h b/src/live_effects/lpe-attach-path.h index fc8d95c99514f3b7a88567cb2013dfb932c3b0ce..ae54f0f02b9fbe74223c54ac00bb9bc796a7c43a 100644 --- a/src/live_effects/lpe-attach-path.h +++ b/src/live_effects/lpe-attach-path.h @@ -11,31 +11,32 @@ */ #include "live_effects/effect.h" +#include "live_effects/parameter/bool.h" +#include "live_effects/parameter/originalpath.h" #include "live_effects/parameter/parameter.h" #include "live_effects/parameter/point.h" -#include "live_effects/parameter/originalpath.h" -#include "live_effects/parameter/vector.h" -#include "live_effects/parameter/bool.h" #include "live_effects/parameter/transformedpoint.h" +#include "live_effects/parameter/vector.h" namespace Inkscape { namespace LivePathEffect { -class LPEAttachPath : public Effect { +class LPEAttachPath : public Effect +{ public: LPEAttachPath(LivePathEffectObject *lpeobject); ~LPEAttachPath() override; - void doEffect (SPCurve * curve) override; - void resetDefaults(SPItem const * item) override; + void doEffect(SPCurve *curve) override; + void resetDefaults(SPItem const *item) override; private: - LPEAttachPath(const LPEAttachPath&) = delete; - LPEAttachPath& operator=(const LPEAttachPath&) = delete; + LPEAttachPath(const LPEAttachPath &) = delete; + LPEAttachPath &operator=(const LPEAttachPath &) = delete; Geom::Point curve_start_previous_origin; Geom::Point curve_end_previous_origin; - + OriginalPathParam start_path; ScalarParam start_path_position; TransformedPointParam start_path_curve_start; @@ -47,7 +48,7 @@ private: VectorParam end_path_curve_end; }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-bendpath.cpp b/src/live_effects/lpe-bendpath.cpp index afe1c594911f7044bea79fe2f42899918d76983d..06506bb1dd1e072b848cd6291d9de0c2c367b555 100644 --- a/src/live_effects/lpe-bendpath.cpp +++ b/src/live_effects/lpe-bendpath.cpp @@ -6,11 +6,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "live_effects/lpe-bendpath.h" + +#include + +#include "display/curve.h" #include "knot-holder-entity.h" #include "knotholder.h" -#include "display/curve.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -20,10 +22,12 @@ Let B be the skeleton path, and P the pattern (the path to be deformed). P is a map t --> P(t) = ( x(t), y(t) ). B is a map t --> B(t) = ( a(t), b(t) ). -The first step is to re-parametrize B by its arc length: this is the parametrization in which a point p on B is located by its distance s from start. One obtains a new map s --> U(s) = (a'(s),b'(s)), that still describes the same path B, but where the distance along B from start to -U(s) is s itself. +The first step is to re-parametrize B by its arc length: this is the parametrization in which a point p on B is located +by its distance s from start. One obtains a new map s --> U(s) = (a'(s),b'(s)), that still describes the same path B, +but where the distance along B from start to U(s) is s itself. -We also need a unit normal to the path. This can be obtained by computing a unit tangent vector, and rotate it by 90�. Call this normal vector N(s). +We also need a unit normal to the path. This can be obtained by computing a unit tangent vector, and rotate it by 90�. +Call this normal vector N(s). The basic deformation associated to B is then given by: @@ -31,56 +35,60 @@ The basic deformation associated to B is then given by: (i.e. we go for distance x along the path, and then for distance y along the normal) -Of course this formula needs some minor adaptations (as is it depends on the absolute position of P for instance, so a little translation is needed -first) but I think we can first forget about them. +Of course this formula needs some minor adaptations (as is it depends on the absolute position of P for instance, so a +little translation is needed first) but I think we can first forget about them. */ namespace Inkscape { namespace LivePathEffect { namespace BeP { -class KnotHolderEntityWidthBendPath : public LPEKnotHolderEntity { - public: - KnotHolderEntityWidthBendPath(LPEBendPath * effect) : LPEKnotHolderEntity(effect) {} - ~KnotHolderEntityWidthBendPath() override - { - LPEBendPath *lpe = dynamic_cast (_effect); - lpe->_knot_entity = nullptr; - } - void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; - Geom::Point knot_get() const override; - }; -} // BeP - -LPEBendPath::LPEBendPath(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - bend_path(_("Bend path:"), _("Path along which to bend the original path"), "bendpath", &wr, this, "M0,0 L1,0"), - original_height(0.0), - prop_scale(_("_Width:"), _("Width of the path"), "prop_scale", &wr, this, 1.0), - scale_y_rel(_("W_idth in units of length"), _("Scale the width of the path in units of its length"), "scale_y_rel", &wr, this, false), - vertical_pattern(_("_Original path is vertical"), _("Rotates the original 90 degrees, before bending it along the bend path"), "vertical", &wr, this, false), - hide_knot(_("Hide width knot"), _("Hide width knot"),"hide_knot", &wr, this, false) +class KnotHolderEntityWidthBendPath : public LPEKnotHolderEntity { - registerParameter( &bend_path ); - registerParameter( &prop_scale); - registerParameter( &scale_y_rel); - registerParameter( &vertical_pattern); +public: + KnotHolderEntityWidthBendPath(LPEBendPath *effect) + : LPEKnotHolderEntity(effect) + {} + ~KnotHolderEntityWidthBendPath() override + { + LPEBendPath *lpe = dynamic_cast(_effect); + lpe->_knot_entity = nullptr; + } + void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; + Geom::Point knot_get() const override; +}; +} // namespace BeP + +LPEBendPath::LPEBendPath(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , bend_path(_("Bend path:"), _("Path along which to bend the original path"), "bendpath", &wr, this, "M0,0 L1,0") + , original_height(0.0) + , prop_scale(_("_Width:"), _("Width of the path"), "prop_scale", &wr, this, 1.0) + , scale_y_rel(_("W_idth in units of length"), _("Scale the width of the path in units of its length"), + "scale_y_rel", &wr, this, false) + , vertical_pattern(_("_Original path is vertical"), + _("Rotates the original 90 degrees, before bending it along the bend path"), "vertical", &wr, + this, false) + , hide_knot(_("Hide width knot"), _("Hide width knot"), "hide_knot", &wr, this, false) +{ + registerParameter(&bend_path); + registerParameter(&prop_scale); + registerParameter(&scale_y_rel); + registerParameter(&vertical_pattern); registerParameter(&hide_knot); prop_scale.param_set_digits(3); prop_scale.param_set_increments(0.01, 0.10); - + _knot_entity = nullptr; _provides_knotholder_entities = true; apply_to_clippath_and_mask = true; concatenate_before_pwd2 = true; } -LPEBendPath::~LPEBendPath() -= default; +LPEBendPath::~LPEBendPath() = default; -void -LPEBendPath::doBeforeEffect (SPLPEItem const* lpeitem) +void LPEBendPath::doBeforeEffect(SPLPEItem const *lpeitem) { // get the item bounding box original_bbox(lpeitem, false, true); @@ -103,81 +111,82 @@ void LPEBendPath::transform_multiply(Geom::Affine const &postmul, bool /*set*/) } } -Geom::Piecewise > -LPEBendPath::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPEBendPath::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; -/* Much credit should go to jfb and mgsloan of lib2geom development for the code below! */ + /* Much credit should go to jfb and mgsloan of lib2geom development for the code below! */ if (bend_path.changed) { - uskeleton = arc_length_parametrization(Piecewise >(bend_path.get_pwd2()),2,.1); - uskeleton = remove_short_cuts(uskeleton,.01); + uskeleton = arc_length_parametrization(Piecewise>(bend_path.get_pwd2()), 2, .1); + uskeleton = remove_short_cuts(uskeleton, .01); n = rot90(derivative(uskeleton)); - n = force_continuity(remove_short_cuts(n,.01)); + n = force_continuity(remove_short_cuts(n, .01)); bend_path.changed = false; } if (uskeleton.empty()) { - return pwd2_in; /// \todo or throw an exception instead? might be better to throw an exception so that the UI can display an error message or smth + return pwd2_in; /// \todo or throw an exception instead? might be better to throw an exception so that the UI + /// can display an error message or smth } - D2 > patternd2 = make_cuts_independent(pwd2_in); - Piecewise x = vertical_pattern.get_value() ? Piecewise(patternd2[1]) : Piecewise(patternd2[0]); - Piecewise y = vertical_pattern.get_value() ? Piecewise(patternd2[0]) : Piecewise(patternd2[1]); + D2> patternd2 = make_cuts_independent(pwd2_in); + Piecewise x = + vertical_pattern.get_value() ? Piecewise(patternd2[1]) : Piecewise(patternd2[0]); + Piecewise y = + vertical_pattern.get_value() ? Piecewise(patternd2[0]) : Piecewise(patternd2[1]); Interval bboxHorizontal = vertical_pattern.get_value() ? boundingbox_Y : boundingbox_X; Interval bboxVertical = vertical_pattern.get_value() ? boundingbox_X : boundingbox_Y; - + //+0.1 in x fix bug #1658855 - //We use the group bounding box size or the path bbox size to translate well x and y - x-= bboxHorizontal.min() + 0.1; - y-= bboxVertical.middle(); + // We use the group bounding box size or the path bbox size to translate well x and y + x -= bboxHorizontal.min() + 0.1; + y -= bboxVertical.middle(); - double scaling = uskeleton.cuts.back()/bboxHorizontal.extent(); + double scaling = uskeleton.cuts.back() / bboxHorizontal.extent(); if (scaling != 1.0) { - x*=scaling; + x *= scaling; } - if ( scale_y_rel.get_value() ) { - y*=(scaling*prop_scale); + if (scale_y_rel.get_value()) { + y *= (scaling * prop_scale); } else { - if (prop_scale != 1.0) y *= prop_scale; + if (prop_scale != 1.0) + y *= prop_scale; } - Piecewise > output = compose(uskeleton,x) + y*compose(n,x); + Piecewise> output = compose(uskeleton, x) + y * compose(n, x); return output; } -void -LPEBendPath::resetDefaults(SPItem const* item) +void LPEBendPath::resetDefaults(SPItem const *item) { Effect::resetDefaults(item); original_bbox(SP_LPE_ITEM(item), false, true); - Geom::Point start(boundingbox_X.min(), (boundingbox_Y.max()+boundingbox_Y.min())/2); - Geom::Point end(boundingbox_X.max(), (boundingbox_Y.max()+boundingbox_Y.min())/2); + Geom::Point start(boundingbox_X.min(), (boundingbox_Y.max() + boundingbox_Y.min()) / 2); + Geom::Point end(boundingbox_X.max(), (boundingbox_Y.max() + boundingbox_Y.min()) / 2); - if ( Geom::are_near(start,end) ) { - end += Geom::Point(1.,0.); + if (Geom::are_near(start, end)) { + end += Geom::Point(1., 0.); } - + Geom::Path path; - path.start( start ); - path.appendNew( end ); - bend_path.set_new_value( path.toPwSb(), true ); + path.start(start); + path.appendNew(end); + bend_path.set_new_value(path.toPwSb(), true); } -void -LPEBendPath::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) +void LPEBendPath::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { hp_vec.push_back(helper_path); } -void -LPEBendPath::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) +void LPEBendPath::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) { _knot_entity = new BeP::KnotHolderEntityWidthBendPath(this); _knot_entity->create(nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Change the width"), @@ -191,10 +200,9 @@ LPEBendPath::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) namespace BeP { -void -KnotHolderEntityWidthBendPath::knot_set(Geom::Point const &p, Geom::Point const& /*origin*/, guint state) +void KnotHolderEntityWidthBendPath::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { - LPEBendPath *lpe = dynamic_cast (_effect); + LPEBendPath *lpe = dynamic_cast(_effect); Geom::Point const s = snap_knot_position(p, state); Geom::Path path_in = lpe->bend_path.get_pathvector().pathAt(Geom::PathVectorTime(0, 0, 0.0)); @@ -209,21 +217,20 @@ KnotHolderEntityWidthBendPath::knot_set(Geom::Point const &p, Geom::Point const& ray.setAngle(ray.angle() + Geom::rad_from_deg(90)); Geom::Point knot_pos = this->knot->pos * item->i2dt_affine().inverse(); Geom::Coord nearest_to_ray = ray.nearestTime(knot_pos); - if(nearest_to_ray == 0){ - lpe->prop_scale.param_set_value(-Geom::distance(s , ptA)/(lpe->original_height/2.0)); + if (nearest_to_ray == 0) { + lpe->prop_scale.param_set_value(-Geom::distance(s, ptA) / (lpe->original_height / 2.0)); } else { - lpe->prop_scale.param_set_value(Geom::distance(s , ptA)/(lpe->original_height/2.0)); + lpe->prop_scale.param_set_value(Geom::distance(s, ptA) / (lpe->original_height / 2.0)); } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble("/live_effects/bend/width", lpe->prop_scale); - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, true); } -Geom::Point -KnotHolderEntityWidthBendPath::knot_get() const +Geom::Point KnotHolderEntityWidthBendPath::knot_get() const { - LPEBendPath *lpe = dynamic_cast (_effect); + LPEBendPath *lpe = dynamic_cast(_effect); Geom::Path path_in = lpe->bend_path.get_pathvector().pathAt(Geom::PathVectorTime(0, 0, 0.0)); Geom::Point ptA = path_in.pointAt(Geom::PathTime(0, 0.0)); Geom::Point B = path_in.pointAt(Geom::PathTime(1, 0.0)); @@ -234,7 +241,7 @@ KnotHolderEntityWidthBendPath::knot_get() const ray.setPoints(ptA, (*cubic)[1]); } ray.setAngle(ray.angle() + Geom::rad_from_deg(90)); - Geom::Point result_point = Geom::Point::polar(ray.angle(), (lpe->original_height/2.0) * lpe->prop_scale) + ptA; + Geom::Point result_point = Geom::Point::polar(ray.angle(), (lpe->original_height / 2.0) * lpe->prop_scale) + ptA; lpe->helper_path.clear(); if (!lpe->hide_knot) { Geom::Path hp(result_point); diff --git a/src/live_effects/lpe-bendpath.h b/src/live_effects/lpe-bendpath.h index b34f2886b1031194dabaea8bd3f92996991b23fd..0d8b6b9f8899dc200002e9f5cd9ebc9d42f9f1c6 100644 --- a/src/live_effects/lpe-bendpath.h +++ b/src/live_effects/lpe-bendpath.h @@ -11,19 +11,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/enum.h" -#include "live_effects/effect.h" -#include "live_effects/parameter/path.h" -#include "live_effects/parameter/bool.h" - -#include <2geom/sbasis.h> -#include <2geom/sbasis-geometric.h> #include <2geom/bezier-to-sbasis.h> -#include <2geom/sbasis-to-bezier.h> #include <2geom/d2.h> #include <2geom/piecewise.h> +#include <2geom/sbasis-geometric.h> +#include <2geom/sbasis-to-bezier.h> +#include <2geom/sbasis.h> +#include "live_effects/effect.h" #include "live_effects/lpegroupbbox.h" +#include "live_effects/parameter/bool.h" +#include "live_effects/parameter/enum.h" +#include "live_effects/parameter/path.h" namespace Inkscape { namespace LivePathEffect { @@ -32,46 +31,52 @@ namespace BeP { class KnotHolderEntityWidthBendPath; } -//for Bend path on group : we need information concerning the group Bounding box -class LPEBendPath : public Effect, GroupBBoxEffect { +// for Bend path on group : we need information concerning the group Bounding box +class LPEBendPath + : public Effect + , GroupBBoxEffect +{ public: LPEBendPath(LivePathEffectObject *lpeobject); ~LPEBendPath() override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; - void resetDefaults(SPItem const* item) override; + void resetDefaults(SPItem const *item) override; void transform_multiply(Geom::Affine const &postmul, bool set) override; - void addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) override; - - void addKnotHolderEntities(KnotHolder * knotholder, SPItem * item) override; + void addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) override; + + void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) override; PathParam bend_path; friend class BeP::KnotHolderEntityWidthBendPath; + protected: double original_height; ScalarParam prop_scale; + private: BoolParam scale_y_rel; BoolParam vertical_pattern; BoolParam hide_knot; - KnotHolderEntity * _knot_entity; + KnotHolderEntity *_knot_entity; Geom::PathVector helper_path; - Geom::Piecewise > uskeleton; - Geom::Piecewise > n; + Geom::Piecewise> uskeleton; + Geom::Piecewise> n; void on_pattern_pasted(); - LPEBendPath(const LPEBendPath&); - LPEBendPath& operator=(const LPEBendPath&); + LPEBendPath(const LPEBendPath &); + LPEBendPath &operator=(const LPEBendPath &); }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-bool.cpp b/src/live_effects/lpe-bool.cpp index 7681ea9ef96f9ba3be3500e39e946310de28bda7..8753029259612daf0574e56737ca3c9dd2f7356e 100644 --- a/src/live_effects/lpe-bool.cpp +++ b/src/live_effects/lpe-bool.cpp @@ -7,12 +7,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "live_effects/lpe-bool.h" + +#include #include #include -#include - -#include "live_effects/lpe-bool.h" +#include #include "2geom/affine.h" #include "2geom/bezier-curve.h" @@ -20,17 +20,14 @@ #include "2geom/path.h" #include "2geom/svg-path-parser.h" #include "display/curve.h" -#include "object/sp-shape.h" -#include "svg/svg.h" - #include "helper/geom.h" - #include "livarot/Path.h" #include "livarot/Shape.h" #include "livarot/path-description.h" - +#include "object/sp-shape.h" #include "path/path-boolop.h" #include "path/path-util.h" +#include "svg/svg.h" namespace Inkscape { namespace LivePathEffect { @@ -38,30 +35,30 @@ namespace LivePathEffect { // Define an extended boolean operation type static const Util::EnumData BoolOpData[LPEBool::bool_op_ex_count] = { - { LPEBool::bool_op_ex_union, N_("union"), "union" }, - { LPEBool::bool_op_ex_inters, N_("intersection"), "inters" }, - { LPEBool::bool_op_ex_diff, N_("difference"), "diff" }, - { LPEBool::bool_op_ex_symdiff, N_("symmetric difference"), "symdiff" }, - { LPEBool::bool_op_ex_cut, N_("division"), "cut" }, + {LPEBool::bool_op_ex_union, N_("union"), "union"}, + {LPEBool::bool_op_ex_inters, N_("intersection"), "inters"}, + {LPEBool::bool_op_ex_diff, N_("difference"), "diff"}, + {LPEBool::bool_op_ex_symdiff, N_("symmetric difference"), "symdiff"}, + {LPEBool::bool_op_ex_cut, N_("division"), "cut"}, // Note on naming of operations: // bool_op_cut is called "Division" in the manu, see sp_selected_path_cut // bool_op_slice is called "Cut path" in the menu, see sp_selected_path_slice - { LPEBool::bool_op_ex_slice, N_("cut"), "slice" }, + {LPEBool::bool_op_ex_slice, N_("cut"), "slice"}, // Comneted in 1.0 don't work properly // { LPEBool::bool_op_ex_slice_inside, N_("cut inside"), "slice-inside" }, // { LPEBool::bool_op_ex_slice_outside, N_("cut outside"), "slice-outside" }, }; -static const Util::EnumDataConverter BoolOpConverter(BoolOpData, sizeof(BoolOpData) / sizeof(*BoolOpData)); +static const Util::EnumDataConverter BoolOpConverter(BoolOpData, + sizeof(BoolOpData) / sizeof(*BoolOpData)); -static const Util::EnumData FillTypeData[] = { - { fill_oddEven, N_("even-odd"), "oddeven" }, - { fill_nonZero, N_("non-zero"), "nonzero" }, - { fill_positive, N_("positive"), "positive" }, - { fill_justDont, N_("take from object"), "from-curve" } -}; +static const Util::EnumData FillTypeData[] = {{fill_oddEven, N_("even-odd"), "oddeven"}, + {fill_nonZero, N_("non-zero"), "nonzero"}, + {fill_positive, N_("positive"), "positive"}, + {fill_justDont, N_("take from object"), "from-curve"}}; -static const Util::EnumDataConverter FillTypeConverter(FillTypeData, sizeof(FillTypeData) / sizeof(*FillTypeData)); +static const Util::EnumDataConverter FillTypeConverter(FillTypeData, + sizeof(FillTypeData) / sizeof(*FillTypeData)); LPEBool::LPEBool(LivePathEffectObject *lpeobject) : Effect(lpeobject) @@ -89,16 +86,15 @@ LPEBool::LPEBool(LivePathEffectObject *lpeobject) operand = dynamic_cast(operand_path.getObject()); } -LPEBool::~LPEBool() -= default; +LPEBool::~LPEBool() = default; bool cmp_cut_position(const Path::cut_position &a, const Path::cut_position &b) { return a.piece == b.piece ? a.t < b.t : a.piece < b.piece; } -Geom::PathVector -sp_pathvector_boolop_slice_intersect(Geom::PathVector const &pathva, Geom::PathVector const &pathvb, bool inside, fill_typ fra, fill_typ frb) +Geom::PathVector sp_pathvector_boolop_slice_intersect(Geom::PathVector const &pathva, Geom::PathVector const &pathvb, + bool inside, fill_typ fra, fill_typ frb) { // This is similar to sp_pathvector_boolop/bool_op_slice, but keeps only edges inside the cutter area. // The code is also based on sp_pathvector_boolop_slice. @@ -126,10 +122,10 @@ sp_pathvector_boolop_slice_intersect(Geom::PathVector const &pathva, Geom::PathV // graph, this should provide sufficient information. // But since I anyway will change this to the new mechanism some time speed is fairly ok, I didn't look into this. - // extract the livarot Paths from the source objects // also get the winding rule specified in the style - // Livarot's outline of arcs is broken. So convert the path to linear and cubics only, for which the outline is created correctly. + // Livarot's outline of arcs is broken. So convert the path to linear and cubics only, for which the outline is + // created correctly. Path *contour_path = Path_for_pathvector(pathv_to_linear_and_cubic_beziers(pathva)); Path *area_path = Path_for_pathvector(pathv_to_linear_and_cubic_beziers(pathvb)); @@ -168,9 +164,9 @@ sp_pathvector_boolop_slice_intersect(Geom::PathVector const &pathva, Geom::PathV // we need to check that at least one edge from the source path is incident to it // before we declare it's an intersection int cb = combined_inters->getPoint(i).incidentEdge[FIRST]; - int nbOrig = 0; - int nbOther = 0; - int piece = -1; + int nbOrig = 0; + int nbOther = 0; + int piece = -1; float t = 0.0; while (cb >= 0 && cb < combined_inters->numberOfEdges()) { if (combined_inters->ebData[cb].pathID == 0) { @@ -184,7 +180,7 @@ sp_pathvector_boolop_slice_intersect(Geom::PathVector const &pathva, Geom::PathV nbOrig++; } if (combined_inters->ebData[cb].pathID == 1) { - nbOther++; // the cut is incident to this point + nbOther++; // the cut is incident to this point } cb = combined_inters->NextAt(i, cb); } @@ -249,15 +245,15 @@ sp_pathvector_boolop_slice_intersect(Geom::PathVector const &pathva, Geom::PathV // Copy the original path to result and cut at the intersection points result_path->Copy(contour_path); - result_path->ConvertPositionsToMoveTo(toCut.size(), toCut.data()); // cut where you found intersections + result_path->ConvertPositionsToMoveTo(toCut.size(), toCut.data()); // cut where you found intersections // Create an array of bools which states which pieces are in std::vector inside_flags(result_path->descr_cmd.size(), false); - for (auto & inside_piece : inside_pieces) { - inside_flags[ inside_piece.piece ] = true; + for (auto &inside_piece : inside_pieces) { + inside_flags[inside_piece.piece] = true; // also enable the element -1 to get the MoveTo if (inside_piece.piece >= 1) { - inside_flags[ inside_piece.piece - 1 ] = true; + inside_flags[inside_piece.piece - 1] = true; } } @@ -302,7 +298,7 @@ sp_pathvector_boolop_slice_intersect(Geom::PathVector const &pathva, Geom::PathV delete area_path; gchar *result_str = result_path->svg_dump_path(); - Geom::PathVector outres = Geom::parse_svg_path(result_str); + Geom::PathVector outres = Geom::parse_svg_path(result_str); // CONCEPT TESTING g_warning( "%s", result_str ); g_free(result_str); delete result_path; @@ -311,8 +307,7 @@ sp_pathvector_boolop_slice_intersect(Geom::PathVector const &pathva, Geom::PathV } // remove inner contours -Geom::PathVector -sp_pathvector_boolop_remove_inner(Geom::PathVector const &pathva, fill_typ fra) +Geom::PathVector sp_pathvector_boolop_remove_inner(Geom::PathVector const &pathva, fill_typ fra) { Geom::PathVector patht; Path *patha = Path_for_pathvector(pathv_to_linear_and_cubic_beziers(pathva)); @@ -332,7 +327,7 @@ sp_pathvector_boolop_remove_inner(Geom::PathVector const &pathva, fill_typ fra) delete patha; gchar *result_str = resultp->svg_dump_path(); - Geom::PathVector resultpv = Geom::parse_svg_path(result_str); + Geom::PathVector resultpv = Geom::parse_svg_path(result_str); g_free(result_str); delete resultp; @@ -373,7 +368,7 @@ void LPEBool::doBeforeEffect(SPLPEItem const *lpeitem) } operand = current_operand; } - + if (operand && operand->isHidden() != hide_linked) { operand->setHidden(hide_linked); } @@ -417,9 +412,8 @@ void LPEBool::doEffect(SPCurve *curve) return; } if (operand_path.getObject() && operand_path.linksToPath() && operand) { - bool_op_ex op = bool_operation.get_value(); - bool swap = swap_operands.get_value(); + bool swap = swap_operands.get_value(); Geom::Affine current_affine = sp_item_transform_repr(sp_lpe_item); Geom::Affine operand_affine = sp_item_transform_repr(operand); @@ -434,8 +428,10 @@ void LPEBool::doEffect(SPCurve *curve) Geom::PathVector path_a = swap ? path_in : operand_pv; Geom::PathVector path_b = swap ? operand_pv : path_in; - fill_typ fill_this = fill_type_this.get_value() != fill_justDont ? fill_type_this.get_value() : GetFillTyp(current_shape); - fill_typ fill_operand = fill_type_operand.get_value() != fill_justDont ? fill_type_operand.get_value() : GetFillTyp(operand_path.getObject()); + fill_typ fill_this = + fill_type_this.get_value() != fill_justDont ? fill_type_this.get_value() : GetFillTyp(current_shape); + fill_typ fill_operand = fill_type_operand.get_value() != fill_justDont ? fill_type_operand.get_value() + : GetFillTyp(operand_path.getObject()); fill_typ fill_a = swap ? fill_this : fill_operand; fill_typ fill_b = swap ? fill_operand : fill_this; @@ -448,16 +444,18 @@ void LPEBool::doEffect(SPCurve *curve) if (op == bool_op_ex_cut) { // we do in two pass because wrong sp_pathvector_boolop diference, in commnet they sugest make this to fix path_out = sp_pathvector_boolop(path_a, path_b, to_bool_op(bool_op_ex_inters), fill_a, fill_b); - Geom::PathVector path_out_2 = sp_pathvector_boolop(path_b, path_a, to_bool_op(bool_op_ex_diff), fill_b, fill_a); + Geom::PathVector path_out_2 = + sp_pathvector_boolop(path_b, path_a, to_bool_op(bool_op_ex_diff), fill_b, fill_a); path_out.insert(path_out.end(), path_out_2.begin(), path_out_2.end()); } else if (op == bool_op_ex_slice) { - // For slicing, the bool op is added to the line group which is sliced, not the cut path. This swapped order is correct + // For slicing, the bool op is added to the line group which is sliced, not the cut path. This swapped order + // is correct path_out = sp_pathvector_boolop(path_b, path_a, to_bool_op(op), fill_b, fill_a); - /*} else if (op == bool_op_ex_slice_inside) { - path_out = sp_pathvector_boolop_slice_intersect(path_a, path_b, true, fill_a, fill_b); - } else if (op == bool_op_ex_slice_outside) { - path_out = sp_pathvector_boolop_slice_intersect(path_a, path_b, false, fill_a, fill_b); - } */ + /*} else if (op == bool_op_ex_slice_inside) { + path_out = sp_pathvector_boolop_slice_intersect(path_a, path_b, true, fill_a, fill_b); + } else if (op == bool_op_ex_slice_outside) { + path_out = sp_pathvector_boolop_slice_intersect(path_a, path_b, false, fill_a, fill_b); + } */ } else { path_out = sp_pathvector_boolop(path_a, path_b, to_bool_op(op), fill_a, fill_b); } diff --git a/src/live_effects/lpe-bool.h b/src/live_effects/lpe-bool.h index 6e35511c935983dd444d736875393dad7700d583..313db3ab95c8bacf878d0da7929d9b549ebfee3a 100644 --- a/src/live_effects/lpe-bool.h +++ b/src/live_effects/lpe-bool.h @@ -10,17 +10,18 @@ #ifndef INKSCAPE_LPE_BOOL_H #define INKSCAPE_LPE_BOOL_H +#include "livarot/LivarotDefs.h" #include "live_effects/effect.h" -#include "live_effects/parameter/parameter.h" -#include "live_effects/parameter/originalpath.h" #include "live_effects/parameter/bool.h" #include "live_effects/parameter/enum.h" -#include "livarot/LivarotDefs.h" +#include "live_effects/parameter/originalpath.h" +#include "live_effects/parameter/parameter.h" namespace Inkscape { namespace LivePathEffect { -class LPEBool : public Effect { +class LPEBool : public Effect +{ public: LPEBool(LivePathEffectObject *lpeobject); ~LPEBool() override; @@ -31,23 +32,25 @@ public: void doOnVisibilityToggled(SPLPEItem const * /*lpeitem*/) override; void doOnRemove(SPLPEItem const * /*lpeitem*/) override; - enum bool_op_ex { - bool_op_ex_union = bool_op_union, - bool_op_ex_inters = bool_op_inters, - bool_op_ex_diff = bool_op_diff, - bool_op_ex_symdiff = bool_op_symdiff, - bool_op_ex_cut = bool_op_cut, - bool_op_ex_slice = bool_op_slice, + enum bool_op_ex + { + bool_op_ex_union = bool_op_union, + bool_op_ex_inters = bool_op_inters, + bool_op_ex_diff = bool_op_diff, + bool_op_ex_symdiff = bool_op_symdiff, + bool_op_ex_cut = bool_op_cut, + bool_op_ex_slice = bool_op_slice, // Comneted in 1.0 don't work properly - // bool_op_ex_slice_inside, // like bool_op_slice, but leaves only the contour pieces inside of the cut path - // bool_op_ex_slice_outside, // like bool_op_slice, but leaves only the contour pieces outside of the cut path + // bool_op_ex_slice_inside, // like bool_op_slice, but leaves only the contour pieces inside of the + // cut path bool_op_ex_slice_outside, // like bool_op_slice, but leaves only the contour pieces + // outside of the cut path bool_op_ex_count }; inline friend bool_op to_bool_op(bool_op_ex val) { assert(val <= bool_op_ex_slice); - return (bool_op) val; + return (bool_op)val; } private: @@ -64,7 +67,7 @@ private: SPItem *operand; }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-bounding-box.cpp b/src/live_effects/lpe-bounding-box.cpp index 106ba24156815a06b16678fce5b7139fbf1a53d4..d9b9e47fd6f1ecdb04f38dd228a8a5b9f490a6f2 100644 --- a/src/live_effects/lpe-bounding-box.cpp +++ b/src/live_effects/lpe-bounding-box.cpp @@ -11,28 +11,26 @@ // TODO due to internal breakage in glibmm headers, this must be last: #include - namespace Inkscape { namespace LivePathEffect { -LPEBoundingBox::LPEBoundingBox(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - linked_path(_("Linked path:"), _("Path from which to take the original path data"), "linkedpath", &wr, this), - visual_bounds(_("Visual Bounds"), _("Uses the visual bounding box"), "visualbounds", &wr, this) +LPEBoundingBox::LPEBoundingBox(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , linked_path(_("Linked path:"), _("Path from which to take the original path data"), "linkedpath", &wr, this) + , visual_bounds(_("Visual Bounds"), _("Uses the visual bounding box"), "visualbounds", &wr, this) { registerParameter(&linked_path); registerParameter(&visual_bounds); - //perceived_path = true; + // perceived_path = true; } -LPEBoundingBox::~LPEBoundingBox() -= default; +LPEBoundingBox::~LPEBoundingBox() = default; -void LPEBoundingBox::doEffect (SPCurve * curve) +void LPEBoundingBox::doEffect(SPCurve *curve) { if (curve) { - if ( linked_path.linksToPath() && linked_path.getObject() ) { - SPItem * item = linked_path.getObject(); + if (linked_path.linksToPath() && linked_path.getObject()) { + SPItem *item = linked_path.getObject(); Geom::OptRect bbox = visual_bounds.get_value() ? item->visualBounds() : item->geometricBounds(); Geom::Path p(Geom::Point(bbox->left(), bbox->top())); p.appendNew(Geom::Point(bbox->right(), bbox->top())); diff --git a/src/live_effects/lpe-bounding-box.h b/src/live_effects/lpe-bounding-box.h index c5230b4dccdf29a113e5c259936fc307d8c55bdf..83034fc0b7a8e013d5f2ef9959a4d76965e71568 100644 --- a/src/live_effects/lpe-bounding-box.h +++ b/src/live_effects/lpe-bounding-box.h @@ -16,23 +16,24 @@ namespace Inkscape { namespace LivePathEffect { -class LPEBoundingBox : public Effect { +class LPEBoundingBox : public Effect +{ public: LPEBoundingBox(LivePathEffectObject *lpeobject); ~LPEBoundingBox() override; - void doEffect (SPCurve * curve) override; + void doEffect(SPCurve *curve) override; private: - OriginalPathParam linked_path; + OriginalPathParam linked_path; BoolParam visual_bounds; private: - LPEBoundingBox(const LPEBoundingBox&) = delete; - LPEBoundingBox& operator=(const LPEBoundingBox&) = delete; + LPEBoundingBox(const LPEBoundingBox &) = delete; + LPEBoundingBox &operator=(const LPEBoundingBox &) = delete; }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-bspline.cpp b/src/live_effects/lpe-bspline.cpp index 772eb7f4e180d697d1c3021a549d1efeb420430f..ce08d2db3d5ea8969414344452008410ed694693 100644 --- a/src/live_effects/lpe-bspline.cpp +++ b/src/live_effects/lpe-bspline.cpp @@ -2,17 +2,19 @@ /* * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "live_effects/lpe-bspline.h" -#include "ui/widget/scalar.h" + +#include + #include "display/curve.h" +#include "document-undo.h" #include "helper/geom-curves.h" #include "object/sp-path.h" -#include "svg/svg.h" -#include "xml/repr.h" #include "preferences.h" -#include "document-undo.h" +#include "svg/svg.h" +#include "ui/widget/scalar.h" #include "verbs.h" +#include "xml/repr.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -21,18 +23,21 @@ namespace LivePathEffect { const double HANDLE_CUBIC_GAP = 0.001; const double NO_POWER = 0.0; -const double DEFAULT_START_POWER = 1.0/3.0; -const double DEFAULT_END_POWER = 2.0/3.0; +const double DEFAULT_START_POWER = 1.0 / 3.0; +const double DEFAULT_END_POWER = 2.0 / 3.0; Geom::Path sp_bspline_drawHandle(Geom::Point p, double helper_size); LPEBSpline::LPEBSpline(LivePathEffectObject *lpeobject) - : Effect(lpeobject), - steps(_("Steps with CTRL:"), _("Change number of steps with CTRL pressed"), "steps", &wr, this, 2), - helper_size(_("Helper size:"), _("Helper size"), "helper_size", &wr, this, 0), - apply_no_weight(_("Apply changes if weight = 0%"), _("Apply changes if weight = 0%"), "apply_no_weight", &wr, this, true), - apply_with_weight(_("Apply changes if weight > 0%"), _("Apply changes if weight > 0%"), "apply_with_weight", &wr, this, true), - only_selected(_("Change only selected nodes"), _("Change only selected nodes"), "only_selected", &wr, this, false), - weight(_("Change weight %:"), _("Change weight percent of the effect"), "weight", &wr, this, DEFAULT_START_POWER * 100) + : Effect(lpeobject) + , steps(_("Steps with CTRL:"), _("Change number of steps with CTRL pressed"), "steps", &wr, this, 2) + , helper_size(_("Helper size:"), _("Helper size"), "helper_size", &wr, this, 0) + , apply_no_weight(_("Apply changes if weight = 0%"), _("Apply changes if weight = 0%"), "apply_no_weight", &wr, + this, true) + , apply_with_weight(_("Apply changes if weight > 0%"), _("Apply changes if weight > 0%"), "apply_with_weight", &wr, + this, true) + , only_selected(_("Change only selected nodes"), _("Change only selected nodes"), "only_selected", &wr, this, false) + , weight(_("Change weight %:"), _("Change weight percent of the effect"), "weight", &wr, this, + DEFAULT_START_POWER * 100) { registerParameter(&weight); registerParameter(&steps); @@ -58,25 +63,23 @@ LPEBSpline::LPEBSpline(LivePathEffectObject *lpeobject) LPEBSpline::~LPEBSpline() = default; -void LPEBSpline::doBeforeEffect (SPLPEItem const* /*lpeitem*/) +void LPEBSpline::doBeforeEffect(SPLPEItem const * /*lpeitem*/) { - if(!hp.empty()) { + if (!hp.empty()) { hp.clear(); } } - -void LPEBSpline::doOnApply(SPLPEItem const* lpeitem) +void LPEBSpline::doOnApply(SPLPEItem const *lpeitem) { if (!SP_IS_SHAPE(lpeitem)) { g_warning("LPE BSpline can only be applied to shapes (not groups)."); - SPLPEItem * item = const_cast(lpeitem); + SPLPEItem *item = const_cast(lpeitem); item->removeCurrentPathEffect(false); } } -void -LPEBSpline::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) +void LPEBSpline::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { hp_vec.push_back(hp); } @@ -94,35 +97,30 @@ Gtk::Widget *LPEBSpline::newWidget() Parameter *param = *it; Gtk::Widget *widg = dynamic_cast(param->param_newWidget()); if (param->param_key == "weight") { - Gtk::HBox * buttons = Gtk::manage(new Gtk::HBox(true,0)); - Gtk::Button *default_weight = - Gtk::manage(new Gtk::Button(Glib::ustring(_("Default weight")))); - default_weight->signal_clicked() - .connect(sigc::mem_fun(*this, &LPEBSpline::toDefaultWeight)); + Gtk::HBox *buttons = Gtk::manage(new Gtk::HBox(true, 0)); + Gtk::Button *default_weight = Gtk::manage(new Gtk::Button(Glib::ustring(_("Default weight")))); + default_weight->signal_clicked().connect(sigc::mem_fun(*this, &LPEBSpline::toDefaultWeight)); buttons->pack_start(*default_weight, true, true, 2); - Gtk::Button *make_cusp = - Gtk::manage(new Gtk::Button(Glib::ustring(_("Make cusp")))); - make_cusp->signal_clicked() - .connect(sigc::mem_fun(*this, &LPEBSpline::toMakeCusp)); + Gtk::Button *make_cusp = Gtk::manage(new Gtk::Button(Glib::ustring(_("Make cusp")))); + make_cusp->signal_clicked().connect(sigc::mem_fun(*this, &LPEBSpline::toMakeCusp)); buttons->pack_start(*make_cusp, true, true, 2); vbox->pack_start(*buttons, true, true, 2); } if (param->param_key == "weight" || param->param_key == "steps") { Inkscape::UI::Widget::Scalar *widg_registered = Gtk::manage(dynamic_cast(widg)); - widg_registered->signal_value_changed() - .connect(sigc::mem_fun(*this, &LPEBSpline::toWeight)); + widg_registered->signal_value_changed().connect(sigc::mem_fun(*this, &LPEBSpline::toWeight)); widg = dynamic_cast(widg_registered); if (widg) { - Gtk::HBox * hbox_weight_steps = dynamic_cast(widg); - std::vector< Gtk::Widget* > childList = hbox_weight_steps->get_children(); - Gtk::Entry* entry_widget = dynamic_cast(childList[1]); + Gtk::HBox *hbox_weight_steps = dynamic_cast(widg); + std::vector childList = hbox_weight_steps->get_children(); + Gtk::Entry *entry_widget = dynamic_cast(childList[1]); entry_widget->set_width_chars(9); } } - if (param->param_key == "only_selected" || param->param_key == "apply_no_weight" || param->param_key == "apply_with_weight") { - Gtk::CheckButton *widg_registered = - Gtk::manage(dynamic_cast(widg)); + if (param->param_key == "only_selected" || param->param_key == "apply_no_weight" || + param->param_key == "apply_with_weight") { + Gtk::CheckButton *widg_registered = Gtk::manage(dynamic_cast(widg)); widg = dynamic_cast(widg_registered); } Glib::ustring *tip = param->param_getTooltip(); @@ -139,7 +137,7 @@ Gtk::Widget *LPEBSpline::newWidget() ++it; } - if(Gtk::Widget* widg = defaultParamSet()) { + if (Gtk::Widget *widg = defaultParamSet()) { vbox->pack_start(*widg, true, true, 2); } return dynamic_cast(vbox); @@ -166,7 +164,7 @@ void LPEBSpline::toWeight() void LPEBSpline::changeWeight(double weight_ammount) { SPPath *path = dynamic_cast(sp_lpe_item); - if(path) { + if (path) { auto curve = SPCurve::copy(path->curveForEdit()); doBSplineFromWidget(curve.get(), weight_ammount / 100.0); gchar *str = sp_svg_write_path(curve->get_pathvector()); @@ -188,11 +186,11 @@ void sp_bspline_do_effect(SPCurve *curve, double helper_size, Geom::PathVector & Geom::PathVector const original_pathv = curve->get_pathvector(); curve->reset(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - for (const auto & path_it : original_pathv) { + for (const auto &path_it : original_pathv) { if (path_it.empty()) { continue; } - if (!prefs->getBool("/tools/nodes/show_outline", true)){ + if (!prefs->getBool("/tools/nodes/show_outline", true)) { hp.push_back(path_it); } Geom::Path::const_iterator curve_it1 = path_it.begin(); @@ -210,16 +208,16 @@ void sp_bspline_do_effect(SPCurve *curve, double helper_size, Geom::PathVector & Geom::CubicBezier const *cubic = nullptr; curve_n->moveto(curve_it1->initialPoint()); if (path_it.closed()) { - const Geom::Curve &closingline = path_it.back_closed(); - // the closing line segment is always of type - // Geom::LineSegment. - if (are_near(closingline.initialPoint(), closingline.finalPoint())) { - // closingline.isDegenerate() did not work, because it only checks for - // *exact* zero length, which goes wrong for relative coordinates and - // rounding errors... - // the closing line segment has zero-length. So stop before that one! - curve_endit = path_it.end_open(); - } + const Geom::Curve &closingline = path_it.back_closed(); + // the closing line segment is always of type + // Geom::LineSegment. + if (are_near(closingline.initialPoint(), closingline.finalPoint())) { + // closingline.isDegenerate() did not work, because it only checks for + // *exact* zero length, which goes wrong for relative coordinates and + // rounding errors... + // the closing line segment has zero-length. So stop before that one! + curve_endit = path_it.end_open(); + } } while (curve_it1 != curve_endit) { auto in = std::make_unique(); @@ -228,12 +226,12 @@ void sp_bspline_do_effect(SPCurve *curve, double helper_size, Geom::PathVector & cubic = dynamic_cast(&*curve_it1); if (cubic) { sbasis_in = in->first_segment()->toSBasis(); - if(are_near((*cubic)[1],(*cubic)[0]) && !are_near((*cubic)[2],(*cubic)[3])) { + if (are_near((*cubic)[1], (*cubic)[0]) && !are_near((*cubic)[2], (*cubic)[3])) { point_at1 = sbasis_in.valueAt(DEFAULT_START_POWER); } else { point_at1 = sbasis_in.valueAt(Geom::nearest_time((*cubic)[1], *in->first_segment())); } - if(are_near((*cubic)[2],(*cubic)[3]) && !are_near((*cubic)[1],(*cubic)[0])) { + if (are_near((*cubic)[2], (*cubic)[3]) && !are_near((*cubic)[1], (*cubic)[0])) { point_at2 = sbasis_in.valueAt(DEFAULT_END_POWER); } else { point_at2 = sbasis_in.valueAt(Geom::nearest_time((*cubic)[2], *in->first_segment())); @@ -242,14 +240,14 @@ void sp_bspline_do_effect(SPCurve *curve, double helper_size, Geom::PathVector & point_at1 = in->first_segment()->initialPoint(); point_at2 = in->first_segment()->finalPoint(); } - if ( curve_it2 != curve_endit ) { + if (curve_it2 != curve_endit) { auto out = std::make_unique(); out->moveto(curve_it2->initialPoint()); out->lineto(curve_it2->finalPoint()); cubic = dynamic_cast(&*curve_it2); if (cubic) { sbasis_out = out->first_segment()->toSBasis(); - if(are_near((*cubic)[1],(*cubic)[0]) && !are_near((*cubic)[2],(*cubic)[3])) { + if (are_near((*cubic)[1], (*cubic)[0]) && !are_near((*cubic)[2], (*cubic)[3])) { next_point_at1 = sbasis_in.valueAt(DEFAULT_START_POWER); } else { next_point_at1 = sbasis_out.valueAt(Geom::nearest_time((*cubic)[1], *out->first_segment())); @@ -266,8 +264,7 @@ void sp_bspline_do_effect(SPCurve *curve, double helper_size, Geom::PathVector & auto line_helper = std::make_unique(); cubic = dynamic_cast(&*path_it.begin()); if (cubic) { - line_helper->moveto(sbasis_start.valueAt( - Geom::nearest_time((*cubic)[1], *start->first_segment()))); + line_helper->moveto(sbasis_start.valueAt(Geom::nearest_time((*cubic)[1], *start->first_segment()))); } else { line_helper->moveto(start->first_segment()->initialPoint()); } @@ -278,8 +275,7 @@ void sp_bspline_do_effect(SPCurve *curve, double helper_size, Geom::PathVector & Geom::D2 sbasis_end = end->first_segment()->toSBasis(); cubic = dynamic_cast(&*curve_it1); if (cubic) { - line_helper->lineto(sbasis_end.valueAt( - Geom::nearest_time((*cubic)[2], *end->first_segment()))); + line_helper->lineto(sbasis_end.valueAt(Geom::nearest_time((*cubic)[2], *end->first_segment()))); } else { line_helper->lineto(end->first_segment()->finalPoint()); } @@ -287,7 +283,7 @@ void sp_bspline_do_effect(SPCurve *curve, double helper_size, Geom::PathVector & node = sbasis_helper.valueAt(0.5); curve_n->curveto(point_at1, point_at2, node); curve_n->move_endpoints(node, node); - } else if ( curve_it2 == curve_endit) { + } else if (curve_it2 == curve_endit) { curve_n->curveto(point_at1, point_at2, curve_it1->finalPoint()); curve_n->move_endpoints(path_it.begin()->initialPoint(), curve_it1->finalPoint()); } else { @@ -298,12 +294,12 @@ void sp_bspline_do_effect(SPCurve *curve, double helper_size, Geom::PathVector & previousNode = node; node = sbasis_helper.valueAt(0.5); Geom::CubicBezier const *cubic2 = dynamic_cast(&*curve_it1); - if((cubic && are_near((*cubic)[0],(*cubic)[1])) || (cubic2 && are_near((*cubic2)[2],(*cubic2)[3]))) { + if ((cubic && are_near((*cubic)[0], (*cubic)[1])) || (cubic2 && are_near((*cubic2)[2], (*cubic2)[3]))) { node = curve_it1->finalPoint(); } curve_n->curveto(point_at1, point_at2, node); } - if(!are_near(node,curve_it1->finalPoint()) && helper_size > 0.0) { + if (!are_near(node, curve_it1->finalPoint()) && helper_size > 0.0) { hp.push_back(sp_bspline_drawHandle(node, helper_size)); } ++curve_it1; @@ -314,7 +310,7 @@ void sp_bspline_do_effect(SPCurve *curve, double helper_size, Geom::PathVector & } curve->append(*curve_n, false); } - if(helper_size > 0.0) { + if (helper_size > 0.0) { Geom::PathVector const pathv = curve->get_pathvector(); hp.push_back(pathv[0]); } @@ -322,12 +318,12 @@ void sp_bspline_do_effect(SPCurve *curve, double helper_size, Geom::PathVector & Geom::Path sp_bspline_drawHandle(Geom::Point p, double helper_size) { - char const * svgd = "M 1,0.5 A 0.5,0.5 0 0 1 0.5,1 0.5,0.5 0 0 1 0,0.5 0.5,0.5 0 0 1 0.5,0 0.5,0.5 0 0 1 1,0.5 Z"; + char const *svgd = "M 1,0.5 A 0.5,0.5 0 0 1 0.5,1 0.5,0.5 0 0 1 0,0.5 0.5,0.5 0 0 1 0.5,0 0.5,0.5 0 0 1 1,0.5 Z"; Geom::PathVector pathv = sp_svg_read_pathv(svgd); Geom::Affine aff = Geom::Affine(); aff *= Geom::Scale(helper_size); pathv *= aff; - pathv *= Geom::Translate(p - Geom::Point(0.5*helper_size, 0.5*helper_size)); + pathv *= Geom::Translate(p - Geom::Point(0.5 * helper_size, 0.5 * helper_size)); return pathv[0]; } @@ -342,8 +338,7 @@ void LPEBSpline::doBSplineFromWidget(SPCurve *curve, double weight_ammount) Geom::PathVector const original_pathv = curve->get_pathvector(); curve->reset(); - for (const auto & path_it : original_pathv) { - + for (const auto &path_it : original_pathv) { if (path_it.empty()) { continue; } @@ -361,16 +356,16 @@ void LPEBSpline::doBSplineFromWidget(SPCurve *curve, double weight_ammount) Geom::CubicBezier const *cubic = nullptr; curve_n->moveto(curve_it1->initialPoint()); if (path_it.closed()) { - const Geom::Curve &closingline = path_it.back_closed(); - // the closing line segment is always of type - // Geom::LineSegment. - if (are_near(closingline.initialPoint(), closingline.finalPoint())) { - // closingline.isDegenerate() did not work, because it only checks for - // *exact* zero length, which goes wrong for relative coordinates and - // rounding errors... - // the closing line segment has zero-length. So stop before that one! - curve_endit = path_it.end_open(); - } + const Geom::Curve &closingline = path_it.back_closed(); + // the closing line segment is always of type + // Geom::LineSegment. + if (are_near(closingline.initialPoint(), closingline.finalPoint())) { + // closingline.isDegenerate() did not work, because it only checks for + // *exact* zero length, which goes wrong for relative coordinates and + // rounding errors... + // the closing line segment has zero-length. So stop before that one! + curve_endit = path_it.end_open(); + } } while (curve_it1 != curve_endit) { auto in = std::make_unique(); @@ -383,13 +378,11 @@ void LPEBSpline::doBSplineFromWidget(SPCurve *curve, double weight_ammount) if (cubic) { if ((apply_no_weight && apply_with_weight) || (apply_no_weight && Geom::are_near((*cubic)[1], point_at0)) || - (apply_with_weight && !Geom::are_near((*cubic)[1], point_at0))) - { + (apply_with_weight && !Geom::are_near((*cubic)[1], point_at0))) { if (isNodePointSelected(point_at0) || !only_selected) { point_at1 = sbasis_in.valueAt(weight_ammount); if (weight_ammount != NO_POWER) { - point_at1 = - Geom::Point(point_at1[X] + HANDLE_CUBIC_GAP, point_at1[Y] + HANDLE_CUBIC_GAP); + point_at1 = Geom::Point(point_at1[X] + HANDLE_CUBIC_GAP, point_at1[Y] + HANDLE_CUBIC_GAP); } } else { point_at1 = (*cubic)[1]; @@ -399,13 +392,11 @@ void LPEBSpline::doBSplineFromWidget(SPCurve *curve, double weight_ammount) } if ((apply_no_weight && apply_with_weight) || (apply_no_weight && Geom::are_near((*cubic)[2], point_at3)) || - (apply_with_weight && !Geom::are_near((*cubic)[2], point_at3))) - { + (apply_with_weight && !Geom::are_near((*cubic)[2], point_at3))) { if (isNodePointSelected(point_at3) || !only_selected) { point_at2 = sbasis_in.valueAt(1 - weight_ammount); if (weight_ammount != NO_POWER) { - point_at2 = - Geom::Point(point_at2[X] + HANDLE_CUBIC_GAP, point_at2[Y] + HANDLE_CUBIC_GAP); + point_at2 = Geom::Point(point_at2[X] + HANDLE_CUBIC_GAP, point_at2[Y] + HANDLE_CUBIC_GAP); } } else { point_at2 = (*cubic)[2]; @@ -414,21 +405,17 @@ void LPEBSpline::doBSplineFromWidget(SPCurve *curve, double weight_ammount) point_at2 = (*cubic)[2]; } } else { - if ((apply_no_weight && apply_with_weight) || - (apply_no_weight && weight_ammount == NO_POWER) || - (apply_with_weight && weight_ammount != NO_POWER)) - { + if ((apply_no_weight && apply_with_weight) || (apply_no_weight && weight_ammount == NO_POWER) || + (apply_with_weight && weight_ammount != NO_POWER)) { if (isNodePointSelected(point_at0) || !only_selected) { point_at1 = sbasis_in.valueAt(weight_ammount); - point_at1 = - Geom::Point(point_at1[X] + HANDLE_CUBIC_GAP, point_at1[Y] + HANDLE_CUBIC_GAP); + point_at1 = Geom::Point(point_at1[X] + HANDLE_CUBIC_GAP, point_at1[Y] + HANDLE_CUBIC_GAP); } else { point_at1 = in->first_segment()->initialPoint(); } if (isNodePointSelected(point_at3) || !only_selected) { point_at2 = sbasis_in.valueAt(1 - weight_ammount); - point_at2 = - Geom::Point(point_at2[X] + HANDLE_CUBIC_GAP, point_at2[Y] + HANDLE_CUBIC_GAP); + point_at2 = Geom::Point(point_at2[X] + HANDLE_CUBIC_GAP, point_at2[Y] + HANDLE_CUBIC_GAP); } else { point_at2 = in->first_segment()->finalPoint(); } @@ -442,8 +429,7 @@ void LPEBSpline::doBSplineFromWidget(SPCurve *curve, double weight_ammount) ++curve_it2; } if (path_it.closed()) { - curve_n->move_endpoints(path_it.begin()->initialPoint(), - path_it.begin()->initialPoint()); + curve_n->move_endpoints(path_it.begin()->initialPoint(), path_it.begin()->initialPoint()); } else { curve_n->move_endpoints(path_it.begin()->initialPoint(), point_at3); } @@ -454,7 +440,7 @@ void LPEBSpline::doBSplineFromWidget(SPCurve *curve, double weight_ammount) } } -}; //namespace LivePathEffect +}; // namespace LivePathEffect }; /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-bspline.h b/src/live_effects/lpe-bspline.h index 0c3a065563e44527e1790da532649fdd5548dbe5..ea383ca1d5099fd7c62598ed948926ac87545bb1 100644 --- a/src/live_effects/lpe-bspline.h +++ b/src/live_effects/lpe-bspline.h @@ -8,28 +8,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/effect.h" #include +#include "live_effects/effect.h" + namespace Inkscape { namespace LivePathEffect { -class LPEBSpline : public Effect { +class LPEBSpline : public Effect +{ public: LPEBSpline(LivePathEffectObject *lpeobject); ~LPEBSpline() override; LPEBSpline(const LPEBSpline &) = delete; LPEBSpline &operator=(const LPEBSpline &) = delete; - LPEPathFlashType pathFlashType() const override - { - return SUPPRESS_FLASH; - } - void doOnApply(SPLPEItem const* lpeitem) override; + LPEPathFlashType pathFlashType() const override { return SUPPRESS_FLASH; } + void doOnApply(SPLPEItem const *lpeitem) override; void doEffect(SPCurve *curve) override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; void doBSplineFromWidget(SPCurve *curve, double value); - void addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) override; + void addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) override; Gtk::Widget *newWidget() override; void changeWeight(double weightValue); void toDefaultWeight(); @@ -49,6 +48,6 @@ private: }; void sp_bspline_do_effect(SPCurve *curve, double helper_size, Geom::PathVector &hp); -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-circle_3pts.cpp b/src/live_effects/lpe-circle_3pts.cpp index 7982abdf138b6d477332330e15f2ab906ddb73b8..d82bf314aaeff00873f2c2510ee78e358e447a81 100644 --- a/src/live_effects/lpe-circle_3pts.cpp +++ b/src/live_effects/lpe-circle_3pts.cpp @@ -24,19 +24,18 @@ namespace Inkscape { namespace LivePathEffect { -LPECircle3Pts::LPECircle3Pts(LivePathEffectObject *lpeobject) : - Effect(lpeobject) -{ -} +LPECircle3Pts::LPECircle3Pts(LivePathEffectObject *lpeobject) + : Effect(lpeobject) +{} -LPECircle3Pts::~LPECircle3Pts() -= default; +LPECircle3Pts::~LPECircle3Pts() = default; -static void _circle3(Geom::Point const &A, Geom::Point const &B, Geom::Point const &C, Geom::PathVector &path_out) { +static void _circle3(Geom::Point const &A, Geom::Point const &B, Geom::Point const &C, Geom::PathVector &path_out) +{ using namespace Geom; - Point D = (A + B)/2; - Point E = (B + C)/2; + Point D = (A + B) / 2; + Point E = (B + C) / 2; Point v = (B - A).ccw(); Point w = (C - B).ccw(); @@ -58,8 +57,7 @@ static void _circle3(Geom::Point const &A, Geom::Point const &B, Geom::Point con path_out = Geom::Path(c); } -Geom::PathVector -LPECircle3Pts::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPECircle3Pts::doEffect_path(Geom::PathVector const &path_in) { Geom::PathVector path_out = Geom::PathVector(); @@ -75,7 +73,7 @@ LPECircle3Pts::doEffect_path (Geom::PathVector const & path_in) /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-circle_3pts.h b/src/live_effects/lpe-circle_3pts.h index bf89b9faddea7485bbf9a55a733167785a32e5da..a1fbdde2ceba1d42d9d10d299483af73fa3d9c92 100644 --- a/src/live_effects/lpe-circle_3pts.h +++ b/src/live_effects/lpe-circle_3pts.h @@ -23,20 +23,21 @@ namespace Inkscape { namespace LivePathEffect { -class LPECircle3Pts : public Effect { +class LPECircle3Pts : public Effect +{ public: LPECircle3Pts(LivePathEffectObject *lpeobject); ~LPECircle3Pts() override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; private: - LPECircle3Pts(const LPECircle3Pts&) = delete; - LPECircle3Pts& operator=(const LPECircle3Pts&) = delete; + LPECircle3Pts(const LPECircle3Pts &) = delete; + LPECircle3Pts &operator=(const LPECircle3Pts &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-circle_with_radius.cpp b/src/live_effects/lpe-circle_with_radius.cpp index 1a6b3a803dd0371b54edfb07bc36e0ebb4ac79b4..4a379af18912d9806d70b40728a422a418bff35c 100644 --- a/src/live_effects/lpe-circle_with_radius.cpp +++ b/src/live_effects/lpe-circle_with_radius.cpp @@ -13,6 +13,7 @@ */ #include "live_effects/lpe-circle_with_radius.h" + #include "display/curve.h" // You might need to include other 2geom files. You can add them here: @@ -26,20 +27,18 @@ using namespace Geom; namespace Inkscape { namespace LivePathEffect { -LPECircleWithRadius::LPECircleWithRadius(LivePathEffectObject *lpeobject) : - Effect(lpeobject)//, - // initialise your parameters here: - //radius(_("Float parameter"), _("just a real number like 1.4!"), "svgname", &wr, this, 50) +LPECircleWithRadius::LPECircleWithRadius(LivePathEffectObject *lpeobject) + : Effect(lpeobject) //, +// initialise your parameters here: +// radius(_("Float parameter"), _("just a real number like 1.4!"), "svgname", &wr, this, 50) { // register all your parameters here, so Inkscape knows which parameters this effect has: - //registerParameter( dynamic_cast(&radius) ); + // registerParameter( dynamic_cast(&radius) ); } -LPECircleWithRadius::~LPECircleWithRadius() -= default; +LPECircleWithRadius::~LPECircleWithRadius() = default; -Geom::PathVector -LPECircleWithRadius::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPECircleWithRadius::doEffect_path(Geom::PathVector const &path_in) { Geom::PathVector path_out = Geom::PathVector(); @@ -68,7 +67,7 @@ LPECircleWithRadius::doEffect_pwd2 (Geom::Piecewise > & p /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-circle_with_radius.h b/src/live_effects/lpe-circle_with_radius.h index dc9a8b9b6ace3f51b7bdb79eef6708bc61adb712..d630c9896fb1ee0eb1eb2a1eb27805031c17431c 100644 --- a/src/live_effects/lpe-circle_with_radius.h +++ b/src/live_effects/lpe-circle_with_radius.h @@ -21,25 +21,26 @@ namespace Inkscape { namespace LivePathEffect { -class LPECircleWithRadius : public Effect { +class LPECircleWithRadius : public Effect +{ public: LPECircleWithRadius(LivePathEffectObject *lpeobject); ~LPECircleWithRadius() override; -// Choose to implement one of the doEffect functions. You can delete or comment out the others. - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + // Choose to implement one of the doEffect functions. You can delete or comment out the others. + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; private: // add the parameters for your effect here: - //ScalarParam radius; + // ScalarParam radius; // there are all kinds of parameters. Check the /live_effects/parameter directory which types exist! - LPECircleWithRadius(const LPECircleWithRadius&) = delete; - LPECircleWithRadius& operator=(const LPECircleWithRadius&) = delete; + LPECircleWithRadius(const LPECircleWithRadius &) = delete; + LPECircleWithRadius &operator=(const LPECircleWithRadius &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-clone-original.cpp b/src/live_effects/lpe-clone-original.cpp index afc9b39da57db9918b40dcf70144b516fa0ae500..2c474560889d535c94b44c7410b2afc8e0da85ba 100644 --- a/src/live_effects/lpe-clone-original.cpp +++ b/src/live_effects/lpe-clone-original.cpp @@ -6,21 +6,20 @@ */ #include "live_effects/lpe-clone-original.h" -#include "live_effects/lpe-spiro.h" + +#include "display/curve.h" #include "live_effects/lpe-bspline.h" -#include "live_effects/lpeobject.h" +#include "live_effects/lpe-spiro.h" #include "live_effects/lpeobject-reference.h" -#include "display/curve.h" -#include "svg/path-string.h" -#include "svg/svg.h" - -#include "ui/tools-switch.h" +#include "live_effects/lpeobject.h" #include "object/sp-clippath.h" #include "object/sp-mask.h" #include "object/sp-path.h" #include "object/sp-shape.h" #include "object/sp-text.h" - +#include "svg/path-string.h" +#include "svg/svg.h" +#include "ui/tools-switch.h" #include "xml/sp-css-attr.h" // TODO due to internal breakage in glibmm headers, this must be last: @@ -30,10 +29,10 @@ namespace Inkscape { namespace LivePathEffect { static const Util::EnumData ClonelpemethodData[] = { - { CLM_NONE, N_("No Shape"), "none" }, - { CLM_D, N_("With LPE's"), "d" }, - { CLM_ORIGINALD, N_("Without LPE's"), "originald" }, - { CLM_BSPLINESPIRO, N_("Spiro or BSpline Only"), "bsplinespiro" }, + {CLM_NONE, N_("No Shape"), "none"}, + {CLM_D, N_("With LPE's"), "d"}, + {CLM_ORIGINALD, N_("Without LPE's"), "originald"}, + {CLM_BSPLINESPIRO, N_("Spiro or BSpline Only"), "bsplinespiro"}, }; static const Util::EnumDataConverter CLMConverter(ClonelpemethodData, CLM_END); @@ -41,16 +40,16 @@ LPECloneOriginal::LPECloneOriginal(LivePathEffectObject *lpeobject) : Effect(lpeobject) , linkeditem(_("Linked Item:"), _("Item from which to take the original data"), "linkeditem", &wr, this) , method(_("Shape"), _("Shape linked"), "method", CLMConverter, &wr, this, CLM_D) - , attributes("Attributes", "Attributes linked, comma separated attributes like trasform, X, Y...", - "attributes", &wr, this, "") + , attributes("Attributes", "Attributes linked, comma separated attributes like trasform, X, Y...", "attributes", + &wr, this, "") , css_properties("CSS Properties", - "CSS properties linked, comma separated attributes like fill, filter, opacity...", - "css_properties", &wr, this, "") + "CSS properties linked, comma separated attributes like fill, filter, opacity...", + "css_properties", &wr, this, "") , allow_transforms(_("Allow Transforms"), _("Allow transforms"), "allow_transforms", &wr, this, true) { - //0.92 compatibility - const gchar * linkedpath = this->getRepr()->attribute("linkedpath"); - if (linkedpath && strcmp(linkedpath, "") != 0){ + // 0.92 compatibility + const gchar *linkedpath = this->getRepr()->attribute("linkedpath"); + if (linkedpath && strcmp(linkedpath, "") != 0) { this->getRepr()->setAttribute("linkeditem", linkedpath); this->getRepr()->removeAttribute("linkedpath"); this->getRepr()->setAttribute("method", "bsplinespiro"); @@ -69,17 +68,16 @@ LPECloneOriginal::LPECloneOriginal(LivePathEffectObject *lpeobject) css_properties.param_hide_canvas_text(); } -void -LPECloneOriginal::syncOriginal() +void LPECloneOriginal::syncOriginal() { if (method != CLM_NONE) { sync = true; // TODO remove the tools_switch atrocity. - sp_lpe_item_update_patheffect (sp_lpe_item, false, true); + sp_lpe_item_update_patheffect(sp_lpe_item, false, true); method.param_set_value(CLM_NONE); refresh_widgets = true; SPDesktop *desktop = SP_ACTIVE_DESKTOP; - sp_lpe_item_update_patheffect (sp_lpe_item, false, true); + sp_lpe_item_update_patheffect(sp_lpe_item, false, true); if (desktop && tools_isactive(desktop, TOOLS_NODES)) { tools_switch(desktop, TOOLS_SELECT); tools_switch(desktop, TOOLS_NODES); @@ -87,20 +85,19 @@ LPECloneOriginal::syncOriginal() } } -Gtk::Widget * -LPECloneOriginal::newWidget() +Gtk::Widget *LPECloneOriginal::newWidget() { // use manage here, because after deletion of Effect object, others might still be pointing to this widget. - Gtk::VBox * vbox = Gtk::manage( new Gtk::VBox(Effect::newWidget()) ); + Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox(Effect::newWidget())); vbox->set_border_width(5); vbox->set_homogeneous(false); vbox->set_spacing(6); std::vector::iterator it = param_vector.begin(); while (it != param_vector.end()) { if ((*it)->widget_is_visible) { - Parameter * param = *it; - Gtk::Widget * widg = dynamic_cast(param->param_newWidget()); - Glib::ustring * tip = param->param_getTooltip(); + Parameter *param = *it; + Gtk::Widget *widg = dynamic_cast(param->param_newWidget()); + Glib::ustring *tip = param->param_getTooltip(); if (widg) { vbox->pack_start(*widg, true, true, 2); if (tip) { @@ -113,75 +110,76 @@ LPECloneOriginal::newWidget() } ++it; } - Gtk::Button * sync_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("No Shape Sync to Current")))); - sync_button->signal_clicked().connect(sigc::mem_fun (*this,&LPECloneOriginal::syncOriginal)); + Gtk::Button *sync_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("No Shape Sync to Current")))); + sync_button->signal_clicked().connect(sigc::mem_fun(*this, &LPECloneOriginal::syncOriginal)); vbox->pack_start(*sync_button, true, true, 2); - if(Gtk::Widget* widg = defaultParamSet()) { + if (Gtk::Widget *widg = defaultParamSet()) { vbox->pack_start(*widg, true, true, 2); } return dynamic_cast(vbox); } -void -LPECloneOriginal::cloneAttrbutes(SPObject *origin, SPObject *dest, const gchar * attributes, const gchar * css_properties) +void LPECloneOriginal::cloneAttrbutes(SPObject *origin, SPObject *dest, const gchar *attributes, + const gchar *css_properties) { SPDocument *document = getSPDoc(); if (!document || !origin || !dest) { return; } - if ( SP_IS_GROUP(origin) && SP_IS_GROUP(dest) && SP_GROUP(origin)->getItemCount() == SP_GROUP(dest)->getItemCount() ) { - std::vector< SPObject * > childs = origin->childList(true); + if (SP_IS_GROUP(origin) && SP_IS_GROUP(dest) && + SP_GROUP(origin)->getItemCount() == SP_GROUP(dest)->getItemCount()) { + std::vector childs = origin->childList(true); size_t index = 0; - for (auto & child : childs) { - SPObject *dest_child = dest->nthChild(index); - cloneAttrbutes(child, dest_child, attributes, css_properties); + for (auto &child : childs) { + SPObject *dest_child = dest->nthChild(index); + cloneAttrbutes(child, dest_child, attributes, css_properties); index++; } } - if ( SP_IS_TEXT(origin) && SP_IS_TEXT(dest) && SP_TEXT(origin)->children.size() == SP_TEXT(dest)->children.size()) { + if (SP_IS_TEXT(origin) && SP_IS_TEXT(dest) && SP_TEXT(origin)->children.size() == SP_TEXT(dest)->children.size()) { size_t index = 0; - for (auto & child : SP_TEXT(origin)->children) { - SPObject *dest_child = dest->nthChild(index); - cloneAttrbutes(&child, dest_child, attributes, css_properties); + for (auto &child : SP_TEXT(origin)->children) { + SPObject *dest_child = dest->nthChild(index); + cloneAttrbutes(&child, dest_child, attributes, css_properties); index++; } } - //Attributes - SPShape * shape_origin = SP_SHAPE(origin); - SPShape * shape_dest = SP_SHAPE(dest); - SPMask * mask_origin = SP_ITEM(origin)->getMaskObject(); - SPMask * mask_dest = SP_ITEM(dest)->getMaskObject(); - if(mask_origin && mask_dest) { - std::vector mask_list = mask_origin->childList(true); - std::vector mask_list_dest = mask_dest->childList(true); + // Attributes + SPShape *shape_origin = SP_SHAPE(origin); + SPShape *shape_dest = SP_SHAPE(dest); + SPMask *mask_origin = SP_ITEM(origin)->getMaskObject(); + SPMask *mask_dest = SP_ITEM(dest)->getMaskObject(); + if (mask_origin && mask_dest) { + std::vector mask_list = mask_origin->childList(true); + std::vector mask_list_dest = mask_dest->childList(true); if (mask_list.size() == mask_list_dest.size()) { size_t i = 0; for (auto mask_data : mask_list) { - SPObject * mask_dest_data = mask_list_dest[i]; + SPObject *mask_dest_data = mask_list_dest[i]; cloneAttrbutes(mask_data, mask_dest_data, attributes, css_properties); i++; } } } - + SPClipPath *clippath_origin = SP_ITEM(origin)->getClipObject(); SPClipPath *clippath_dest = SP_ITEM(dest)->getClipObject(); - if(clippath_origin && clippath_dest) { - std::vector clippath_list = clippath_origin->childList(true); - std::vector clippath_list_dest = clippath_dest->childList(true); + if (clippath_origin && clippath_dest) { + std::vector clippath_list = clippath_origin->childList(true); + std::vector clippath_list_dest = clippath_dest->childList(true); if (clippath_list.size() == clippath_list_dest.size()) { size_t i = 0; for (auto clippath_data : clippath_list) { - SPObject * clippath_dest_data = clippath_list_dest[i]; + SPObject *clippath_dest_data = clippath_list_dest[i]; cloneAttrbutes(clippath_data, clippath_dest_data, attributes, css_properties); i++; } } } - gchar ** attarray = g_strsplit(old_attributes.c_str(), ",", 0); - gchar ** iter = attarray; + gchar **attarray = g_strsplit(old_attributes.c_str(), ",", 0); + gchar **iter = attarray; while (*iter != nullptr) { - const char* attribute = (*iter); + const char *attribute = (*iter); if (strlen(attribute)) { dest->getRepr()->removeAttribute(attribute); } @@ -190,13 +188,13 @@ LPECloneOriginal::cloneAttrbutes(SPObject *origin, SPObject *dest, const gchar * attarray = g_strsplit(attributes, ",", 0); iter = attarray; while (*iter != nullptr) { - const char* attribute = (*iter); + const char *attribute = (*iter); if (strlen(attribute) && shape_dest && shape_origin) { if (std::strcmp(attribute, "d") == 0) { std::unique_ptr c; if (method == CLM_BSPLINESPIRO) { c = SPCurve::copy(shape_origin->curveForEdit()); - SPLPEItem * lpe_item = SP_LPE_ITEM(origin); + SPLPEItem *lpe_item = SP_LPE_ITEM(origin); if (lpe_item) { PathEffectList lpelist = lpe_item->getEffectList(); PathEffectList::iterator i; @@ -215,14 +213,14 @@ LPECloneOriginal::cloneAttrbutes(SPObject *origin, SPObject *dest, const gchar * } } else if (method == CLM_ORIGINALD) { c = SPCurve::copy(shape_origin->curveForEdit()); - } else if(method == CLM_D){ + } else if (method == CLM_D) { c = SPCurve::copy(shape_origin->curve()); } if (c && method != CLM_NONE) { Geom::PathVector c_pv = c->get_pathvector(); c->set_pathvector(c_pv); gchar *str = sp_svg_write_path(c_pv); - if (sync){ + if (sync) { dest->getRepr()->setAttribute("inkscape:original-d", str); } shape_dest->setCurveInsync(std::move(c)); @@ -240,41 +238,41 @@ LPECloneOriginal::cloneAttrbutes(SPObject *origin, SPObject *dest, const gchar * } iter++; } - g_strfreev (attarray); + g_strfreev(attarray); SPCSSAttr *css_origin = sp_repr_css_attr_new(); sp_repr_css_attr_add_from_string(css_origin, origin->getRepr()->attribute("style")); SPCSSAttr *css_dest = sp_repr_css_attr_new(); sp_repr_css_attr_add_from_string(css_dest, dest->getRepr()->attribute("style")); - gchar ** styleattarray = g_strsplit(old_css_properties.c_str(), ",", 0); - gchar ** styleiter = styleattarray; + gchar **styleattarray = g_strsplit(old_css_properties.c_str(), ",", 0); + gchar **styleiter = styleattarray; while (*styleiter != nullptr) { - const char* attribute = (*styleiter); + const char *attribute = (*styleiter); if (strlen(attribute)) { - sp_repr_css_set_property (css_dest, attribute, nullptr); + sp_repr_css_set_property(css_dest, attribute, nullptr); } styleiter++; } styleattarray = g_strsplit(css_properties, ",", 0); styleiter = styleattarray; while (*styleiter != nullptr) { - const char* attribute = (*styleiter); + const char *attribute = (*styleiter); if (strlen(attribute)) { - const char* origin_attribute = sp_repr_css_property(css_origin, attribute, ""); + const char *origin_attribute = sp_repr_css_property(css_origin, attribute, ""); if (!strlen(origin_attribute)) { //==0 - sp_repr_css_set_property (css_dest, attribute, nullptr); + sp_repr_css_set_property(css_dest, attribute, nullptr); } else { - sp_repr_css_set_property (css_dest, attribute, origin_attribute); + sp_repr_css_set_property(css_dest, attribute, origin_attribute); } } styleiter++; } - g_strfreev (styleattarray); + g_strfreev(styleattarray); Glib::ustring css_str; - sp_repr_css_write_string(css_dest,css_str); + sp_repr_css_write_string(css_dest, css_str); dest->getRepr()->setAttributeOrRemoveIfEmpty("style", css_str); } -void -LPECloneOriginal::doBeforeEffect (SPLPEItem const* lpeitem){ +void LPECloneOriginal::doBeforeEffect(SPLPEItem const *lpeitem) +{ start_listening(); SPDocument *document = getSPDoc(); if (!document) { @@ -283,26 +281,26 @@ LPECloneOriginal::doBeforeEffect (SPLPEItem const* lpeitem){ if (linkeditem.linksToItem()) { Glib::ustring attr = "d,"; if (!allow_transforms) { - attr += Glib::ustring("transform") + Glib::ustring(","); + attr += Glib::ustring("transform") + Glib::ustring(","); } auto attributes_str = attributes.param_getSVGValue(); attr += attributes_str + ","; - if (attr.size() && attributes_str.empty()) { - attr.erase (attr.size()-1, 1); + if (attr.size() && attributes_str.empty()) { + attr.erase(attr.size() - 1, 1); } auto css_properties_str = css_properties.param_getSVGValue(); Glib::ustring style_attr = ""; if (style_attr.size() && css_properties_str.empty()) { - style_attr.erase (style_attr.size()-1, 1); + style_attr.erase(style_attr.size() - 1, 1); } style_attr += css_properties_str + ","; - SPItem * orig = SP_ITEM(linkeditem.getObject()); - if(!orig) { + SPItem *orig = SP_ITEM(linkeditem.getObject()); + if (!orig) { return; } - SPItem * dest = SP_ITEM(sp_lpe_item); - const gchar * id = orig->getId(); + SPItem *dest = SP_ITEM(sp_lpe_item); + const gchar *id = orig->getId(); cloneAttrbutes(orig, dest, attr.c_str(), style_attr.c_str()); old_css_properties = css_properties.param_getSVGValue(); old_attributes = attributes.param_getSVGValue(); @@ -313,28 +311,26 @@ LPECloneOriginal::doBeforeEffect (SPLPEItem const* lpeitem){ } } -void -LPECloneOriginal::start_listening() +void LPECloneOriginal::start_listening() { - if ( !sp_lpe_item || listening ) { + if (!sp_lpe_item || listening) { return; } quit_listening(); - modified_connection = SP_OBJECT(this->getLPEObj())->connectModified(sigc::mem_fun(*this, &LPECloneOriginal::modified)); + modified_connection = + SP_OBJECT(this->getLPEObj())->connectModified(sigc::mem_fun(*this, &LPECloneOriginal::modified)); listening = true; } -void -LPECloneOriginal::quit_listening() +void LPECloneOriginal::quit_listening() { modified_connection.disconnect(); listening = false; } -void -LPECloneOriginal::modified(SPObject */*obj*/, guint /*flags*/) +void LPECloneOriginal::modified(SPObject * /*obj*/, guint /*flags*/) { - if ( !sp_lpe_item || is_updating) { + if (!sp_lpe_item || is_updating) { is_updating = false; return; } @@ -347,8 +343,7 @@ LPECloneOriginal::~LPECloneOriginal() quit_listening(); } -void -LPECloneOriginal::doEffect (SPCurve * curve) +void LPECloneOriginal::doEffect(SPCurve *curve) { if (method != CLM_NONE) { SPCurve const *current_curve = current_shape->curve(); diff --git a/src/live_effects/lpe-clone-original.h b/src/live_effects/lpe-clone-original.h index a89d04eee3a35300c1ed89b67850cc32d7755f3a..ab50a21e1e146e6ae44337abee8060172b55a068 100644 --- a/src/live_effects/lpe-clone-original.h +++ b/src/live_effects/lpe-clone-original.h @@ -9,27 +9,37 @@ * * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include + #include "live_effects/effect.h" +#include "live_effects/lpegroupbbox.h" #include "live_effects/parameter/enum.h" #include "live_effects/parameter/originalitem.h" #include "live_effects/parameter/text.h" -#include "live_effects/lpegroupbbox.h" - -#include namespace Inkscape { namespace LivePathEffect { -enum Clonelpemethod { CLM_NONE, CLM_D, CLM_ORIGINALD, CLM_BSPLINESPIRO, CLM_END }; +enum Clonelpemethod +{ + CLM_NONE, + CLM_D, + CLM_ORIGINALD, + CLM_BSPLINESPIRO, + CLM_END +}; -class LPECloneOriginal : public Effect, GroupBBoxEffect { +class LPECloneOriginal + : public Effect + , GroupBBoxEffect +{ public: LPECloneOriginal(LivePathEffectObject *lpeobject); ~LPECloneOriginal() override; - void doEffect (SPCurve * curve) override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; - void cloneAttrbutes(SPObject *origin, SPObject *dest, const gchar * attributes, const gchar * css_properties); - void modified(SPObject */*obj*/, guint /*flags*/); + void doEffect(SPCurve *curve) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; + void cloneAttrbutes(SPObject *origin, SPObject *dest, const gchar *attributes, const gchar *css_properties); + void modified(SPObject * /*obj*/, guint /*flags*/); Gtk::Widget *newWidget() override; void syncOriginal(); void start_listening(); @@ -43,16 +53,16 @@ private: TextParam css_properties; Glib::ustring old_css_properties; BoolParam allow_transforms; - const gchar * linked; + const gchar *linked; bool listening; bool is_updating; bool sync; sigc::connection modified_connection; - LPECloneOriginal(const LPECloneOriginal&) = delete; - LPECloneOriginal& operator=(const LPECloneOriginal&) = delete; + LPECloneOriginal(const LPECloneOriginal &) = delete; + LPECloneOriginal &operator=(const LPECloneOriginal &) = delete; }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-constructgrid.cpp b/src/live_effects/lpe-constructgrid.cpp index e7586191d45060818396e1afd0334598e91585e8..dc2d777b152326b7c38b70a13a8a8a877b62dcc7 100644 --- a/src/live_effects/lpe-constructgrid.cpp +++ b/src/live_effects/lpe-constructgrid.cpp @@ -20,10 +20,10 @@ namespace LivePathEffect { using namespace Geom; -LPEConstructGrid::LPEConstructGrid(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - nr_x(_("Size _X:"), _("The size of the grid in X direction."), "nr_x", &wr, this, 5), - nr_y(_("Size _Y:"), _("The size of the grid in Y direction."), "nr_y", &wr, this, 5) +LPEConstructGrid::LPEConstructGrid(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , nr_x(_("Size _X:"), _("The size of the grid in X direction."), "nr_x", &wr, this, 5) + , nr_y(_("Size _Y:"), _("The size of the grid in Y direction."), "nr_y", &wr, this, 5) { registerParameter(&nr_x); registerParameter(&nr_y); @@ -34,40 +34,38 @@ LPEConstructGrid::LPEConstructGrid(LivePathEffectObject *lpeobject) : nr_y.param_set_range(1, 1e10); } -LPEConstructGrid::~LPEConstructGrid() -= default; +LPEConstructGrid::~LPEConstructGrid() = default; -Geom::PathVector -LPEConstructGrid::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPEConstructGrid::doEffect_path(Geom::PathVector const &path_in) { - // Check that the path has at least 3 nodes (i.e. 2 segments), more nodes are ignored + // Check that the path has at least 3 nodes (i.e. 2 segments), more nodes are ignored if (path_in[0].size() >= 2) { // read the first 3 nodes: - Geom::Path::const_iterator it ( path_in[0].begin() ); - Geom::Point first_p = (*it++).initialPoint(); - Geom::Point origin = (*it++).initialPoint(); + Geom::Path::const_iterator it(path_in[0].begin()); + Geom::Point first_p = (*it++).initialPoint(); + Geom::Point origin = (*it++).initialPoint(); Geom::Point second_p = (*it++).initialPoint(); // make first_p and second_p be the construction *vectors* of the grid: - first_p -= origin; + first_p -= origin; second_p -= origin; - Geom::Translate first_translation( first_p ); - Geom::Translate second_translation( second_p ); + Geom::Translate first_translation(first_p); + Geom::Translate second_translation(second_p); // create the gridpaths of the two directions - Geom::Path first_path( origin ); - first_path.appendNew( origin + first_p*nr_y ); - Geom::Path second_path( origin ); - second_path.appendNew( origin + second_p*nr_x ); + Geom::Path first_path(origin); + first_path.appendNew(origin + first_p * nr_y); + Geom::Path second_path(origin); + second_path.appendNew(origin + second_p * nr_x); // use the gridpaths and set them in the correct grid Geom::PathVector path_out; path_out.push_back(first_path); for (int ix = 0; ix < nr_x; ix++) { - path_out.push_back(path_out.back() * second_translation ); + path_out.push_back(path_out.back() * second_translation); } path_out.push_back(second_path); for (int iy = 0; iy < nr_y; iy++) { - path_out.push_back(path_out.back() * first_translation ); + path_out.push_back(path_out.back() * first_translation); } return path_out; @@ -76,7 +74,7 @@ LPEConstructGrid::doEffect_path (Geom::PathVector const & path_in) } } -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-constructgrid.h b/src/live_effects/lpe-constructgrid.h index 5865402dd299628b54be8de8d85b0a2d62f3c6b9..19bd0ef8cdecd6d2c8761a04d37dff63a1cf6d90 100644 --- a/src/live_effects/lpe-constructgrid.h +++ b/src/live_effects/lpe-constructgrid.h @@ -21,22 +21,23 @@ namespace Inkscape { namespace LivePathEffect { -class LPEConstructGrid : public Effect { +class LPEConstructGrid : public Effect +{ public: LPEConstructGrid(LivePathEffectObject *lpeobject); ~LPEConstructGrid() override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; private: ScalarParam nr_x; ScalarParam nr_y; - LPEConstructGrid(const LPEConstructGrid&) = delete; - LPEConstructGrid& operator=(const LPEConstructGrid&) = delete; + LPEConstructGrid(const LPEConstructGrid &) = delete; + LPEConstructGrid &operator=(const LPEConstructGrid &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif // INKSCAPE_LPE_CONSTRUCTGRID_H diff --git a/src/live_effects/lpe-copy_rotate.cpp b/src/live_effects/lpe-copy_rotate.cpp index 28be56d54c9ccd4f8eff1fe69938de872511bf09..636056a50121db69a2051e4f93d2e784a58c096d 100644 --- a/src/live_effects/lpe-copy_rotate.cpp +++ b/src/live_effects/lpe-copy_rotate.cpp @@ -13,24 +13,25 @@ */ #include "live_effects/lpe-copy_rotate.h" + +#include <2geom/intersection-graph.h> +#include <2geom/path-intersection.h> +#include <2geom/sbasis-to-bezier.h> +#include +#include + #include "display/curve.h" #include "helper/geom.h" #include "live_effects/lpeobject.h" +#include "object/sp-path.h" +#include "object/sp-shape.h" #include "object/sp-text.h" -#include "path/path-boolop.h" #include "path-chemistry.h" +#include "path/path-boolop.h" #include "style.h" #include "svg/path-string.h" #include "svg/svg.h" #include "xml/sp-css-attr.h" -#include <2geom/intersection-graph.h> -#include <2geom/path-intersection.h> -#include <2geom/sbasis-to-bezier.h> -#include -#include - -#include "object/sp-path.h" -#include "object/sp-shape.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -39,45 +40,46 @@ namespace Inkscape { namespace LivePathEffect { static const Util::EnumData RotateMethodData[RM_END] = { - { RM_NORMAL, N_("Normal"), "normal" }, - { RM_KALEIDOSCOPE, N_("Kaleidoscope"), "kaleidoskope" }, - { RM_FUSE, N_("Fuse paths"), "fuse_paths" } -}; -static const Util::EnumDataConverter -RMConverter(RotateMethodData, RM_END); - -bool -pointInTriangle(Geom::Point const &p, Geom::Point const &p1, Geom::Point const &p2, Geom::Point const &p3) + {RM_NORMAL, N_("Normal"), "normal"}, + {RM_KALEIDOSCOPE, N_("Kaleidoscope"), "kaleidoskope"}, + {RM_FUSE, N_("Fuse paths"), "fuse_paths"}}; +static const Util::EnumDataConverter RMConverter(RotateMethodData, RM_END); + +bool pointInTriangle(Geom::Point const &p, Geom::Point const &p1, Geom::Point const &p2, Geom::Point const &p3) { - //http://totologic.blogspot.com.es/2014/01/accurate-point-in-triangle-test.html + // http://totologic.blogspot.com.es/2014/01/accurate-point-in-triangle-test.html using Geom::X; using Geom::Y; - double denominator = (p1[X]*(p2[Y] - p3[Y]) + p1[Y]*(p3[X] - p2[X]) + p2[X]*p3[Y] - p2[Y]*p3[X]); - double t1 = (p[X]*(p3[Y] - p1[Y]) + p[Y]*(p1[X] - p3[X]) - p1[X]*p3[Y] + p1[Y]*p3[X]) / denominator; - double t2 = (p[X]*(p2[Y] - p1[Y]) + p[Y]*(p1[X] - p2[X]) - p1[X]*p2[Y] + p1[Y]*p2[X]) / -denominator; + double denominator = (p1[X] * (p2[Y] - p3[Y]) + p1[Y] * (p3[X] - p2[X]) + p2[X] * p3[Y] - p2[Y] * p3[X]); + double t1 = (p[X] * (p3[Y] - p1[Y]) + p[Y] * (p1[X] - p3[X]) - p1[X] * p3[Y] + p1[Y] * p3[X]) / denominator; + double t2 = (p[X] * (p2[Y] - p1[Y]) + p[Y] * (p1[X] - p2[X]) - p1[X] * p2[Y] + p1[Y] * p2[X]) / -denominator; double s = t1 + t2; return 0 <= t1 && t1 <= 1 && 0 <= t2 && t2 <= 1 && s <= 1; } -LPECopyRotate::LPECopyRotate(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - method(_("Method:"), _("Rotate methods"), "method", RMConverter, &wr, this, RM_NORMAL), - origin(_("Origin"), _("Adjust origin of the rotation"), "origin", &wr, this, _("Adjust origin of the rotation")), - starting_point(_("Start point"), _("Starting point to define start angle"), "starting_point", &wr, this, _("Adjust starting point to define start angle")), - starting_angle(_("Starting angle"), _("Angle of the first copy"), "starting_angle", &wr, this, 0.0), - rotation_angle(_("Rotation angle"), _("Angle between two successive copies"), "rotation_angle", &wr, this, 60.0), - num_copies(_("Number of copies"), _("Number of copies of the original path"), "num_copies", &wr, this, 6), - gap(_("Gap"), _("Gap space between copies, use small negative gaps to fix some joins"), "gap", &wr, this, -0.01), - copies_to_360(_("Distribute evenly"), _("Angle between copies is 360°/number of copies (ignores rotation angle setting)"), "copies_to_360", &wr, this, true), - mirror_copies(_("Mirror copies"), _("Mirror between copies"), "mirror_copies", &wr, this, false), - split_items(_("Split elements"), _("Split elements, so each can have its own style"), "split_items", &wr, this, false), - dist_angle_handle(100.0) +LPECopyRotate::LPECopyRotate(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , method(_("Method:"), _("Rotate methods"), "method", RMConverter, &wr, this, RM_NORMAL) + , origin(_("Origin"), _("Adjust origin of the rotation"), "origin", &wr, this, _("Adjust origin of the rotation")) + , starting_point(_("Start point"), _("Starting point to define start angle"), "starting_point", &wr, this, + _("Adjust starting point to define start angle")) + , starting_angle(_("Starting angle"), _("Angle of the first copy"), "starting_angle", &wr, this, 0.0) + , rotation_angle(_("Rotation angle"), _("Angle between two successive copies"), "rotation_angle", &wr, this, 60.0) + , num_copies(_("Number of copies"), _("Number of copies of the original path"), "num_copies", &wr, this, 6) + , gap(_("Gap"), _("Gap space between copies, use small negative gaps to fix some joins"), "gap", &wr, this, -0.01) + , copies_to_360(_("Distribute evenly"), + _("Angle between copies is 360°/number of copies (ignores rotation angle setting)"), + "copies_to_360", &wr, this, true) + , mirror_copies(_("Mirror copies"), _("Mirror between copies"), "mirror_copies", &wr, this, false) + , split_items(_("Split elements"), _("Split elements, so each can have its own style"), "split_items", &wr, this, + false) + , dist_angle_handle(100.0) { show_orig_path = true; _provides_knotholder_entities = true; - //0.92 compatibility - if (this->getRepr()->attribute("fuse_paths") && strcmp(this->getRepr()->attribute("fuse_paths"), "true") == 0){ + // 0.92 compatibility + if (this->getRepr()->attribute("fuse_paths") && strcmp(this->getRepr()->attribute("fuse_paths"), "true") == 0) { this->getRepr()->removeAttribute("fuse_paths"); this->getRepr()->setAttribute("method", "kaleidoskope"); this->getRepr()->setAttribute("mirror_copies", "true"); @@ -101,17 +103,15 @@ LPECopyRotate::LPECopyRotate(LivePathEffectObject *lpeobject) : num_copies.param_make_integer(true); apply_to_clippath_and_mask = true; previous_num_copies = num_copies; - previous_origin = Geom::Point(0,0); - previous_start_point = Geom::Point(0,0); + previous_origin = Geom::Point(0, 0); + previous_start_point = Geom::Point(0, 0); starting_point.param_widget_is_visible(false); reset = false; } -LPECopyRotate::~LPECopyRotate() -= default; +LPECopyRotate::~LPECopyRotate() = default; -void -LPECopyRotate::doAfterEffect (SPLPEItem const* lpeitem) +void LPECopyRotate::doAfterEffect(SPLPEItem const *lpeitem) { if (split_items) { SPDocument *document = getSPDoc(); @@ -146,7 +146,7 @@ LPECopyRotate::doAfterEffect (SPLPEItem const* lpeitem) guint counter = 0; Glib::ustring id = "rotated-0-"; id += this->lpeobj->getId(); - while((elemref = document->getObjectById(id.c_str()))) { + while ((elemref = document->getObjectById(id.c_str()))) { id = Glib::ustring("rotated-"); id += std::to_string(counter); id += "-"; @@ -159,7 +159,7 @@ LPECopyRotate::doAfterEffect (SPLPEItem const* lpeitem) Geom::Affine m = Geom::Translate(-origin) * Geom::Rotate(-(Geom::rad_from_deg(starting_angle))); for (size_t i = 1; i < num_copies; ++i) { Geom::Affine r = Geom::identity(); - if(mirror_copies && i%2 != 0) { + if (mirror_copies && i % 2 != 0) { r *= Geom::Rotate(Geom::Angle(half_dir)).inverse(); r *= Geom::Scale(1, -1); r *= Geom::Rotate(Geom::Angle(half_dir)); @@ -168,16 +168,17 @@ LPECopyRotate::doAfterEffect (SPLPEItem const* lpeitem) Geom::Rotate rot(-(Geom::rad_from_deg(rotation_angle * i))); Geom::Affine t = m * r * rot * Geom::Rotate(Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); if (method != RM_NORMAL) { - if(mirror_copies && i%2 != 0) { - t = m * r * rot * Geom::Rotate(-Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); + if (mirror_copies && i % 2 != 0) { + t = m * r * rot * Geom::Rotate(-Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); } } else { - if(mirror_copies && i%2 != 0) { - t = m * Geom::Rotate(Geom::rad_from_deg(-rotation_angle)) * r * rot * Geom::Rotate(-Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); + if (mirror_copies && i % 2 != 0) { + t = m * Geom::Rotate(Geom::rad_from_deg(-rotation_angle)) * r * rot * + Geom::Rotate(-Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); } } t *= sp_lpe_item->transform; - toItem(t, i-1, reset); + toItem(t, i - 1, reset); } reset = false; } else { @@ -202,70 +203,69 @@ void LPECopyRotate::cloneStyle(SPObject *orig, SPObject *dest) } } -void -LPECopyRotate::cloneD(SPObject *orig, SPObject *dest, Geom::Affine transform, bool reset) +void LPECopyRotate::cloneD(SPObject *orig, SPObject *dest, Geom::Affine transform, bool reset) { SPDocument *document = getSPDoc(); if (!document) { return; } - if ( SP_IS_GROUP(orig) && SP_IS_GROUP(dest) && SP_GROUP(orig)->getItemCount() == SP_GROUP(dest)->getItemCount() ) { + if (SP_IS_GROUP(orig) && SP_IS_GROUP(dest) && SP_GROUP(orig)->getItemCount() == SP_GROUP(dest)->getItemCount()) { if (reset) { cloneStyle(orig, dest); } - std::vector< SPObject * > childs = orig->childList(true); + std::vector childs = orig->childList(true); size_t index = 0; - for (auto & child : childs) { - SPObject *dest_child = dest->nthChild(index); - cloneD(child, dest_child, transform, reset); + for (auto &child : childs) { + SPObject *dest_child = dest->nthChild(index); + cloneD(child, dest_child, transform, reset); index++; } return; } - if ( SP_IS_TEXT(orig) && SP_IS_TEXT(dest) && SP_TEXT(orig)->children.size() == SP_TEXT(dest)->children.size()) { + if (SP_IS_TEXT(orig) && SP_IS_TEXT(dest) && SP_TEXT(orig)->children.size() == SP_TEXT(dest)->children.size()) { if (reset) { cloneStyle(orig, dest); } size_t index = 0; - for (auto & child : SP_TEXT(orig)->children) { - SPObject *dest_child = dest->nthChild(index); - cloneD(&child, dest_child, transform, reset); + for (auto &child : SP_TEXT(orig)->children) { + SPObject *dest_child = dest->nthChild(index); + cloneD(&child, dest_child, transform, reset); index++; } } - - SPShape * shape = SP_SHAPE(orig); - SPPath * path = SP_PATH(dest); + + SPShape *shape = SP_SHAPE(orig); + SPPath *path = SP_PATH(dest); if (shape) { SPCurve const *c = shape->curve(); if (c) { gchar *str = sp_svg_write_path(c->get_pathvector()); - if (shape && !path) { - const char * id = dest->getRepr()->attribute("id"); - const char * style = dest->getRepr()->attribute("style"); + if (shape && !path) { + const char *id = dest->getRepr()->attribute("id"); + const char *style = dest->getRepr()->attribute("style"); Inkscape::XML::Document *xml_doc = dest->document->getReprDoc(); - Inkscape::XML::Node *dest_node = xml_doc->createElement("svg:path");; + Inkscape::XML::Node *dest_node = xml_doc->createElement("svg:path"); + ; dest_node->setAttribute("id", id); dest_node->setAttribute("inkscape:connector-curvature", "0"); dest_node->setAttribute("style", style); dest->updateRepr(xml_doc, dest_node, SP_OBJECT_WRITE_ALL); - path = SP_PATH(dest); + path = SP_PATH(dest); } path->getRepr()->setAttribute("d", str); g_free(str); } else { path->getRepr()->removeAttribute("d"); } - } if (reset) { cloneStyle(orig, dest); } } -Inkscape::XML::Node * -LPECopyRotate::createPathBase(SPObject *elemref) { +Inkscape::XML::Node *LPECopyRotate::createPathBase(SPObject *elemref) +{ SPDocument *document = getSPDoc(); if (!document) { return nullptr; @@ -276,7 +276,7 @@ LPECopyRotate::createPathBase(SPObject *elemref) { if (group) { Inkscape::XML::Node *container = xml_doc->createElement("svg:g"); container->setAttribute("transform", prev->attribute("transform")); - std::vector const item_list = sp_item_group_item_list(group); + std::vector const item_list = sp_item_group_item_list(group); Inkscape::XML::Node *previous = nullptr; for (auto sub_item : item_list) { Inkscape::XML::Node *resultnode = createPathBase(sub_item); @@ -291,8 +291,7 @@ LPECopyRotate::createPathBase(SPObject *elemref) { return resultnode; } -void -LPECopyRotate::toItem(Geom::Affine transform, size_t i, bool reset) +void LPECopyRotate::toItem(Geom::Affine transform, size_t i, bool reset) { SPDocument *document = getSPDoc(); if (!document) { @@ -317,7 +316,7 @@ LPECopyRotate::toItem(Geom::Affine transform, size_t i, bool reset) } cloneD(SP_OBJECT(sp_lpe_item), elemref, transform, reset); gchar *str = sp_svg_transform_write(transform); - elemref->getRepr()->setAttribute("transform" , str); + elemref->getRepr()->setAttribute("transform", str); g_free(str); SP_ITEM(elemref)->setHidden(false); if (elemref->parent != container) { @@ -329,13 +328,13 @@ LPECopyRotate::toItem(Geom::Affine transform, size_t i, bool reset) } } -void -LPECopyRotate::resetStyles(){ +void LPECopyRotate::resetStyles() +{ reset = true; doAfterEffect(sp_lpe_item); } -Gtk::Widget * LPECopyRotate::newWidget() +Gtk::Widget *LPECopyRotate::newWidget() { // use manage here, because after deletion of Effect object, others might // still be pointing to this widget. @@ -363,21 +362,19 @@ Gtk::Widget * LPECopyRotate::newWidget() ++it; } - Gtk::HBox * hbox = Gtk::manage(new Gtk::HBox(false,0)); - Gtk::Button * reset_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("Reset styles")))); - reset_button->signal_clicked().connect(sigc::mem_fun (*this,&LPECopyRotate::resetStyles)); + Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox(false, 0)); + Gtk::Button *reset_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("Reset styles")))); + reset_button->signal_clicked().connect(sigc::mem_fun(*this, &LPECopyRotate::resetStyles)); reset_button->set_size_request(110, 20); vbox->pack_start(*hbox, true, true, 2); hbox->pack_start(*reset_button, false, false, 2); - if(Gtk::Widget* widg = defaultParamSet()) { + if (Gtk::Widget *widg = defaultParamSet()) { vbox->pack_start(*widg, true, true, 2); } return dynamic_cast(vbox); } - -void -LPECopyRotate::doOnApply(SPLPEItem const* lpeitem) +void LPECopyRotate::doOnApply(SPLPEItem const *lpeitem) { using namespace Geom; original_bbox(lpeitem, false, true); @@ -390,22 +387,21 @@ LPECopyRotate::doOnApply(SPLPEItem const* lpeitem) dir = unit_vector(B - A); } -void -LPECopyRotate::doBeforeEffect (SPLPEItem const* lpeitem) +void LPECopyRotate::doBeforeEffect(SPLPEItem const *lpeitem) { using namespace Geom; original_bbox(lpeitem, false, true); if (copies_to_360 && num_copies > 2) { - rotation_angle.param_set_value(360.0/(double)num_copies); + rotation_angle.param_set_value(360.0 / (double)num_copies); } if (method != RM_NORMAL && rotation_angle * num_copies > 360 && rotation_angle > 0 && copies_to_360) { - num_copies.param_set_value(floor(360/rotation_angle)); + num_copies.param_set_value(floor(360 / rotation_angle)); } - if (method != RM_NORMAL && mirror_copies && copies_to_360) { - num_copies.param_set_increments(2.0,10.0); - if ((int)num_copies%2 !=0) { - num_copies.param_set_value(num_copies+1); - rotation_angle.param_set_value(360.0/(double)num_copies); + if (method != RM_NORMAL && mirror_copies && copies_to_360) { + num_copies.param_set_increments(2.0, 10.0); + if ((int)num_copies % 2 != 0) { + num_copies.param_set_value(num_copies + 1); + rotation_angle.param_set_value(360.0 / (double)num_copies); } } else { num_copies.param_set_increments(1.0, 10.0); @@ -433,7 +429,7 @@ LPECopyRotate::doBeforeEffect (SPLPEItem const* lpeitem) dist_angle_handle = 1.0; } double distance = dist_angle_handle; - if (previous_start_point != Geom::Point(0,0) || previous_origin != Geom::Point(0,0)) { + if (previous_start_point != Geom::Point(0, 0) || previous_origin != Geom::Point(0, 0)) { distance = Geom::distance(previous_origin, starting_point); } start_pos = origin + dir * Rotate(-rad_from_deg(starting_angle)) * distance; @@ -445,16 +441,15 @@ LPECopyRotate::doBeforeEffect (SPLPEItem const* lpeitem) previous_start_point = (Geom::Point)starting_point; } -void -LPECopyRotate::split(Geom::PathVector &path_on, Geom::Path const ÷r) +void LPECopyRotate::split(Geom::PathVector &path_on, Geom::Path const ÷r) { Geom::PathVector tmp_path; double time_start = 0.0; Geom::Path original = path_on[0]; int position = 0; - Geom::Crossings cs = crossings(original,divider); + Geom::Crossings cs = crossings(original, divider); std::vector crossed; - for(auto & c : cs) { + for (auto &c : cs) { crossed.push_back(c.ta); } std::sort(crossed.begin(), crossed.end()); @@ -462,12 +457,14 @@ LPECopyRotate::split(Geom::PathVector &path_on, Geom::Path const ÷r) if (time_start == time_end || time_end - time_start < Geom::EPSILON) { continue; } - Geom::Path portion_original = original.portion(time_start,time_end); + Geom::Path portion_original = original.portion(time_start, time_end); if (!portion_original.empty()) { Geom::Point side_checker = portion_original.pointAt(0.0001); - position = Geom::sgn(Geom::cross(divider[1].finalPoint() - divider[0].finalPoint(), side_checker - divider[0].finalPoint())); + position = Geom::sgn( + Geom::cross(divider[1].finalPoint() - divider[0].finalPoint(), side_checker - divider[0].finalPoint())); if (rotation_angle != 180) { - position = pointInTriangle(side_checker, divider.initialPoint(), divider[0].finalPoint(), divider[1].finalPoint()); + position = pointInTriangle(side_checker, divider.initialPoint(), divider[0].finalPoint(), + divider[1].finalPoint()); } if (position == 1) { tmp_path.push_back(portion_original); @@ -476,17 +473,19 @@ LPECopyRotate::split(Geom::PathVector &path_on, Geom::Path const ÷r) time_start = time_end; } } - position = Geom::sgn(Geom::cross(divider[1].finalPoint() - divider[0].finalPoint(), original.finalPoint() - divider[0].finalPoint())); + position = Geom::sgn(Geom::cross(divider[1].finalPoint() - divider[0].finalPoint(), + original.finalPoint() - divider[0].finalPoint())); if (rotation_angle != 180) { - position = pointInTriangle(original.finalPoint(), divider.initialPoint(), divider[0].finalPoint(), divider[1].finalPoint()); + position = pointInTriangle(original.finalPoint(), divider.initialPoint(), divider[0].finalPoint(), + divider[1].finalPoint()); } if (cs.size() > 0 && position == 1) { Geom::Path portion_original = original.portion(time_start, original.size()); - if(!portion_original.empty()){ + if (!portion_original.empty()) { if (!original.closed()) { tmp_path.push_back(portion_original); } else { - if (tmp_path.size() > 0 && tmp_path[0].size() > 0 ) { + if (tmp_path.size() > 0 && tmp_path[0].size() > 0) { portion_original.setFinal(tmp_path[0].initialPoint()); portion_original.append(tmp_path[0]); tmp_path[0] = portion_original; @@ -497,32 +496,31 @@ LPECopyRotate::split(Geom::PathVector &path_on, Geom::Path const ÷r) portion_original.clear(); } } - if (cs.size()==0 && position == 1) { + if (cs.size() == 0 && position == 1) { tmp_path.push_back(original); } path_on = tmp_path; } -Geom::PathVector -LPECopyRotate::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPECopyRotate::doEffect_path(Geom::PathVector const &path_in) { Geom::PathVector path_out; - double diagonal = Geom::distance(Geom::Point(boundingbox_X.min(),boundingbox_Y.min()),Geom::Point(boundingbox_X.max(),boundingbox_Y.max())); + double diagonal = Geom::distance(Geom::Point(boundingbox_X.min(), boundingbox_Y.min()), + Geom::Point(boundingbox_X.max(), boundingbox_Y.max())); Geom::OptRect bbox = sp_lpe_item->geometricBounds(); - size_divider = Geom::distance(origin,bbox) + (diagonal * 6); - Geom::Point line_start = origin + dir * Geom::Rotate(-(Geom::rad_from_deg(starting_angle))) * size_divider; - Geom::Point line_end = origin + dir * Geom::Rotate(-(Geom::rad_from_deg(rotation_angle + starting_angle))) * size_divider; + size_divider = Geom::distance(origin, bbox) + (diagonal * 6); + Geom::Point line_start = origin + dir * Geom::Rotate(-(Geom::rad_from_deg(starting_angle))) * size_divider; + Geom::Point line_end = + origin + dir * Geom::Rotate(-(Geom::rad_from_deg(rotation_angle + starting_angle))) * size_divider; divider = Geom::Path(line_start); divider.appendNew((Geom::Point)origin); divider.appendNew(line_end); Geom::OptRect trianglebounds = divider.boundsFast(); divider.close(); - half_dir = unit_vector(Geom::middle_point(line_start,line_end) - (Geom::Point)origin); + half_dir = unit_vector(Geom::middle_point(line_start, line_end) - (Geom::Point)origin); FillRuleBool fillrule = fill_nonZero; - if (current_shape->style && - current_shape->style->fill_rule.set && - current_shape->style->fill_rule.computed == SP_WIND_RULE_EVENODD) - { + if (current_shape->style && current_shape->style->fill_rule.set && + current_shape->style->fill_rule.computed == SP_WIND_RULE_EVENODD) { fillrule = (FillRuleBool)fill_oddEven; } if (method != RM_NORMAL) { @@ -537,7 +535,7 @@ LPECopyRotate::doEffect_path (Geom::PathVector const & path_in) Geom::PathVector triangle; triangle.push_back(divider); path_out = sp_pathvector_boolop(path_out, triangle, bool_op_inters, fillrule, fillrule); - if ( !split_items ) { + if (!split_items) { path_out = doEffect_path_post(path_out, fillrule); } else { path_out *= Geom::Translate(half_dir * gap); @@ -547,7 +545,7 @@ LPECopyRotate::doEffect_path (Geom::PathVector const & path_in) } if (!split_items && method != RM_NORMAL) { Geom::PathVector path_out_tmp; - for (const auto & path_it : path_out) { + for (const auto &path_it : path_out) { if (path_it.empty()) { continue; } @@ -555,8 +553,8 @@ LPECopyRotate::doEffect_path (Geom::PathVector const & path_in) Geom::Path::const_iterator curve_endit = path_it.end_default(); Geom::Path res; if (path_it.closed()) { - const Geom::Curve &closingline = path_it.back_closed(); - // the closing line segment is always of type + const Geom::Curve &closingline = path_it.back_closed(); + // the closing line segment is always of type // Geom::LineSegment. if (are_near(closingline.initialPoint(), closingline.finalPoint())) { // closingline.isDegenerate() did not work, because it only checks for @@ -586,16 +584,16 @@ LPECopyRotate::doEffect_path (Geom::PathVector const & path_in) return pathv_to_linear_and_cubic_beziers(path_out); } -Geom::PathVector -LPECopyRotate::doEffect_path_post (Geom::PathVector const & path_in, FillRuleBool fillrule) +Geom::PathVector LPECopyRotate::doEffect_path_post(Geom::PathVector const &path_in, FillRuleBool fillrule) { if ((split_items || num_copies == 1) && method == RM_NORMAL) { - if (split_items) { - Geom::PathVector path_out = pathv_to_linear_and_cubic_beziers(path_in); - Geom::Affine m = Geom::Translate(-origin) * Geom::Rotate(-(Geom::rad_from_deg(starting_angle))); - Geom::Affine t = m * Geom::Rotate(-Geom::rad_from_deg(starting_angle)) * Geom::Rotate(Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); - return path_out * t; - } + if (split_items) { + Geom::PathVector path_out = pathv_to_linear_and_cubic_beziers(path_in); + Geom::Affine m = Geom::Translate(-origin) * Geom::Rotate(-(Geom::rad_from_deg(starting_angle))); + Geom::Affine t = m * Geom::Rotate(-Geom::rad_from_deg(starting_angle)) * + Geom::Rotate(Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); + return path_out * t; + } return path_in; } @@ -606,17 +604,17 @@ LPECopyRotate::doEffect_path_post (Geom::PathVector const & path_in, FillRuleBoo for (int i = 0; i < num_copies; ++i) { Geom::Rotate rot(-Geom::rad_from_deg(rotation_angle * i)); Geom::Affine r = Geom::identity(); - if( i%2 != 0 && mirror_copies) { + if (i % 2 != 0 && mirror_copies) { r *= Geom::Rotate(Geom::Angle(half_dir)).inverse(); r *= Geom::Scale(1, -1); r *= Geom::Rotate(Geom::Angle(half_dir)); } Geom::Affine t = pre * r * rot * Geom::Rotate(Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); - if(mirror_copies && i%2 != 0) { + if (mirror_copies && i % 2 != 0) { t = pre * r * rot * Geom::Rotate(Geom::rad_from_deg(starting_angle)).inverse() * Geom::Translate(origin); } if (method != RM_NORMAL) { - //we use safest way to union + // we use safest way to union Geom::PathVector join_pv = original_pathv * t; join_pv *= Geom::Translate(half_dir * rot * gap); if (!output_pv.empty()) { @@ -625,9 +623,11 @@ LPECopyRotate::doEffect_path_post (Geom::PathVector const & path_in, FillRuleBoo output_pv = join_pv; } } else { - t = pre * Geom::Rotate(-Geom::rad_from_deg(starting_angle)) * r * rot * Geom::Rotate(Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); - if(mirror_copies && i%2 != 0) { - t = pre * Geom::Rotate(Geom::rad_from_deg(-starting_angle-rotation_angle)) * r * rot * Geom::Rotate(-Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); + t = pre * Geom::Rotate(-Geom::rad_from_deg(starting_angle)) * r * rot * + Geom::Rotate(Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); + if (mirror_copies && i % 2 != 0) { + t = pre * Geom::Rotate(Geom::rad_from_deg(-starting_angle - rotation_angle)) * r * rot * + Geom::Rotate(-Geom::rad_from_deg(starting_angle)) * Geom::Translate(origin); } output_pv = path_in * t; output.insert(output.end(), output_pv.begin(), output_pv.end()); @@ -639,37 +639,34 @@ LPECopyRotate::doEffect_path_post (Geom::PathVector const & path_in, FillRuleBoo return output; } -void -LPECopyRotate::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) +void LPECopyRotate::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { using namespace Geom; hp_vec.clear(); Geom::Path hp; hp.start(start_pos); hp.appendNew((Geom::Point)origin); - hp.appendNew(origin + dir * Rotate(-rad_from_deg(rotation_angle+starting_angle)) * Geom::distance(origin,starting_point)); + hp.appendNew(origin + dir * Rotate(-rad_from_deg(rotation_angle + starting_angle)) * + Geom::distance(origin, starting_point)); Geom::PathVector pathv; pathv.push_back(hp); hp_vec.push_back(pathv); } -void -LPECopyRotate::resetDefaults(SPItem const* item) +void LPECopyRotate::resetDefaults(SPItem const *item) { Effect::resetDefaults(item); original_bbox(SP_LPE_ITEM(item), false, true); } -void -LPECopyRotate::doOnVisibilityToggled(SPLPEItem const* /*lpeitem*/) +void LPECopyRotate::doOnVisibilityToggled(SPLPEItem const * /*lpeitem*/) { processObjects(LPE_VISIBILITY); } -void -LPECopyRotate::doOnRemove (SPLPEItem const* lpeitem) +void LPECopyRotate::doOnRemove(SPLPEItem const *lpeitem) { - //set "keep paths" hook on sp-lpe-item.cpp + // set "keep paths" hook on sp-lpe-item.cpp if (keep_paths) { processObjects(LPE_TO_OBJECTS); items.clear(); @@ -678,7 +675,7 @@ LPECopyRotate::doOnRemove (SPLPEItem const* lpeitem) processObjects(LPE_ERASE); } -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-copy_rotate.h b/src/live_effects/lpe-copy_rotate.h index 8469237f27ff9682594223cdc8d9dd63ef6de476..0c386408a7bc18ee8d9d0898ca8eec7719ccc952 100644 --- a/src/live_effects/lpe-copy_rotate.h +++ b/src/live_effects/lpe-copy_rotate.h @@ -16,18 +16,19 @@ */ #include "live_effects/effect.h" +#include "live_effects/lpegroupbbox.h" #include "live_effects/parameter/enum.h" #include "live_effects/parameter/parameter.h" -#include "live_effects/parameter/text.h" #include "live_effects/parameter/point.h" -#include "live_effects/lpegroupbbox.h" +#include "live_effects/parameter/text.h" // this is only to fillrule #include "livarot/Shape.h" namespace Inkscape { namespace LivePathEffect { -enum RotateMethod { +enum RotateMethod +{ RM_NORMAL, RM_KALEIDOSCOPE, RM_FUSE, @@ -36,26 +37,29 @@ enum RotateMethod { typedef FillRule FillRuleBool; -class LPECopyRotate : public Effect, GroupBBoxEffect { +class LPECopyRotate + : public Effect + , GroupBBoxEffect +{ public: LPECopyRotate(LivePathEffectObject *lpeobject); ~LPECopyRotate() override; - void doOnApply (SPLPEItem const* lpeitem) override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; - void doAfterEffect (SPLPEItem const* lpeitem) override; + void doOnApply(SPLPEItem const *lpeitem) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; + void doAfterEffect(SPLPEItem const *lpeitem) override; void split(Geom::PathVector &path_in, Geom::Path const ÷r); - void resetDefaults(SPItem const* item) override; - void doOnRemove (SPLPEItem const* /*lpeitem*/) override; - void doOnVisibilityToggled(SPLPEItem const* /*lpeitem*/) override; - Gtk::Widget * newWidget() override; + void resetDefaults(SPItem const *item) override; + void doOnRemove(SPLPEItem const * /*lpeitem*/) override; + void doOnVisibilityToggled(SPLPEItem const * /*lpeitem*/) override; + Gtk::Widget *newWidget() override; void cloneStyle(SPObject *orig, SPObject *dest); - Geom::PathVector doEffect_path_post (Geom::PathVector const & path_in, FillRuleBool fillrule); + Geom::PathVector doEffect_path_post(Geom::PathVector const &path_in, FillRuleBool fillrule); void toItem(Geom::Affine transform, size_t i, bool reset); void cloneD(SPObject *orig, SPObject *dest, Geom::Affine transform, bool reset); - Inkscape::XML::Node * createPathBase(SPObject *elemref); + Inkscape::XML::Node *createPathBase(SPObject *elemref); void resetStyles(); - //virtual void setFusion(Geom::PathVector &path_in, Geom::Path divider, double sizeDivider); + // virtual void setFusion(Geom::PathVector &path_in, Geom::Path divider, double sizeDivider); protected: void addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec) override; @@ -82,13 +86,13 @@ private: Geom::Path divider; double previous_num_copies; bool reset; - SPObject * container; - LPECopyRotate(const LPECopyRotate&) = delete; - LPECopyRotate& operator=(const LPECopyRotate&) = delete; + SPObject *container; + LPECopyRotate(const LPECopyRotate &) = delete; + LPECopyRotate &operator=(const LPECopyRotate &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-curvestitch.cpp b/src/live_effects/lpe-curvestitch.cpp index aa7a39b77dcbd3343738fd64fa6a83b39df79361..783d5fe9dcf73822c768d65c42e55c2a064fa41e 100644 --- a/src/live_effects/lpe-curvestitch.cpp +++ b/src/live_effects/lpe-curvestitch.cpp @@ -13,42 +13,53 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/scalar.h" #include "live_effects/lpe-curvestitch.h" -#include "object/sp-path.h" +#include <2geom/bezier-to-sbasis.h> +#include "object/sp-path.h" #include "svg/svg.h" +#include "ui/widget/scalar.h" #include "xml/repr.h" -#include <2geom/bezier-to-sbasis.h> - // TODO due to internal breakage in glibmm headers, this must be last: #include - namespace Inkscape { namespace LivePathEffect { using namespace Geom; -LPECurveStitch::LPECurveStitch(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - strokepath(_("Stitch path:"), _("The path that will be used as stitch."), "strokepath", &wr, this, "M0,0 L1,0"), - nrofpaths(_("N_umber of paths:"), _("The number of paths that will be generated."), "count", &wr, this, 5), - startpoint_edge_variation(_("Sta_rt edge variance:"), _("The amount of random jitter to move the start points of the stitches inside & outside the guide path"), "startpoint_edge_variation", &wr, this, 0), - startpoint_spacing_variation(_("Sta_rt spacing variance:"), _("The amount of random shifting to move the start points of the stitches back & forth along the guide path"), "startpoint_spacing_variation", &wr, this, 0), - endpoint_edge_variation(_("End ed_ge variance:"), _("The amount of randomness that moves the end points of the stitches inside & outside the guide path"), "endpoint_edge_variation", &wr, this, 0), - endpoint_spacing_variation(_("End spa_cing variance:"), _("The amount of random shifting to move the end points of the stitches back & forth along the guide path"), "endpoint_spacing_variation", &wr, this, 0), - prop_scale(_("Scale _width:"), _("Scale the width of the stitch path"), "prop_scale", &wr, this, 1), - scale_y_rel(_("Scale _width relative to length"), _("Scale the width of the stitch path relative to its length"), "scale_y_rel", &wr, this, false) +LPECurveStitch::LPECurveStitch(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , strokepath(_("Stitch path:"), _("The path that will be used as stitch."), "strokepath", &wr, this, "M0,0 L1,0") + , nrofpaths(_("N_umber of paths:"), _("The number of paths that will be generated."), "count", &wr, this, 5) + , startpoint_edge_variation( + _("Sta_rt edge variance:"), + _("The amount of random jitter to move the start points of the stitches inside & outside the guide path"), + "startpoint_edge_variation", &wr, this, 0) + , startpoint_spacing_variation( + _("Sta_rt spacing variance:"), + _("The amount of random shifting to move the start points of the stitches back & forth along the guide path"), + "startpoint_spacing_variation", &wr, this, 0) + , endpoint_edge_variation( + _("End ed_ge variance:"), + _("The amount of randomness that moves the end points of the stitches inside & outside the guide path"), + "endpoint_edge_variation", &wr, this, 0) + , endpoint_spacing_variation( + _("End spa_cing variance:"), + _("The amount of random shifting to move the end points of the stitches back & forth along the guide path"), + "endpoint_spacing_variation", &wr, this, 0) + , prop_scale(_("Scale _width:"), _("Scale the width of the stitch path"), "prop_scale", &wr, this, 1) + , scale_y_rel(_("Scale _width relative to length"), _("Scale the width of the stitch path relative to its length"), + "scale_y_rel", &wr, this, false) { registerParameter(&nrofpaths); registerParameter(&startpoint_edge_variation); registerParameter(&startpoint_spacing_variation); registerParameter(&endpoint_edge_variation); registerParameter(&endpoint_spacing_variation); - registerParameter(&strokepath ); + registerParameter(&strokepath); registerParameter(&prop_scale); registerParameter(&scale_y_rel); @@ -60,11 +71,9 @@ LPECurveStitch::LPECurveStitch(LivePathEffectObject *lpeobject) : transformed = false; } -LPECurveStitch::~LPECurveStitch() -= default; +LPECurveStitch::~LPECurveStitch() = default; -Geom::PathVector -LPECurveStitch::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPECurveStitch::doEffect_path(Geom::PathVector const &path_in) { if (path_in.size() >= 2) { startpoint_edge_variation.resetRandomizer(); @@ -72,72 +81,75 @@ LPECurveStitch::doEffect_path (Geom::PathVector const & path_in) startpoint_spacing_variation.resetRandomizer(); endpoint_spacing_variation.resetRandomizer(); - D2 > stroke = make_cuts_independent(strokepath.get_pwd2()); + D2> stroke = make_cuts_independent(strokepath.get_pwd2()); OptInterval bndsStroke = bounds_exact(stroke[0]); OptInterval bndsStrokeY = bounds_exact(stroke[1]); if (!bndsStroke && !bndsStrokeY) { return path_in; } gdouble scaling = bndsStroke->max() - bndsStroke->min(); - Point stroke_origin(bndsStroke->min(), (bndsStrokeY->max()+bndsStrokeY->min())/2); + Point stroke_origin(bndsStroke->min(), (bndsStrokeY->max() + bndsStrokeY->min()) / 2); Geom::PathVector path_out; // do this for all permutations (ii,jj) if there are more than 2 paths? realllly cool! - for (unsigned ii = 0 ; ii < path_in.size() - 1; ii++) - for (unsigned jj = ii+1; jj < path_in.size(); jj++) - { - Piecewise > A = arc_length_parametrization(Piecewise >(path_in[ii].toPwSb()),2,.1); - Piecewise > B = arc_length_parametrization(Piecewise >(path_in[jj].toPwSb()),2,.1); - Interval bndsA = A.domain(); - Interval bndsB = B.domain(); - gdouble incrementA = (bndsA.max()-bndsA.min()) / (nrofpaths-1); - gdouble incrementB = (bndsB.max()-bndsB.min()) / (nrofpaths-1); - gdouble tA = bndsA.min(); - gdouble tB = bndsB.min(); - gdouble tAclean = tA; // the tA without spacing_variation - gdouble tBclean = tB; // the tB without spacing_variation - - for (int i = 0; i < nrofpaths; i++) { - Point start = A(tA); - Point end = B(tB); - if (startpoint_edge_variation.get_value() != 0) - start = start + (startpoint_edge_variation - startpoint_edge_variation.get_value()/2) * (end - start); - if (endpoint_edge_variation.get_value() != 0) - end = end + (endpoint_edge_variation - endpoint_edge_variation.get_value()/2)* (end - start); - - if (!Geom::are_near(start,end)) { - gdouble scaling_y = 1.0; - if (scale_y_rel.get_value() || transformed) { - scaling_y = (L2(end-start)/scaling)*prop_scale; - transformed = false; - } else { - scaling_y = prop_scale; + for (unsigned ii = 0; ii < path_in.size() - 1; ii++) + for (unsigned jj = ii + 1; jj < path_in.size(); jj++) { + Piecewise> A = + arc_length_parametrization(Piecewise>(path_in[ii].toPwSb()), 2, .1); + Piecewise> B = + arc_length_parametrization(Piecewise>(path_in[jj].toPwSb()), 2, .1); + Interval bndsA = A.domain(); + Interval bndsB = B.domain(); + gdouble incrementA = (bndsA.max() - bndsA.min()) / (nrofpaths - 1); + gdouble incrementB = (bndsB.max() - bndsB.min()) / (nrofpaths - 1); + gdouble tA = bndsA.min(); + gdouble tB = bndsB.min(); + gdouble tAclean = tA; // the tA without spacing_variation + gdouble tBclean = tB; // the tB without spacing_variation + + for (int i = 0; i < nrofpaths; i++) { + Point start = A(tA); + Point end = B(tB); + if (startpoint_edge_variation.get_value() != 0) + start = start + + (startpoint_edge_variation - startpoint_edge_variation.get_value() / 2) * (end - start); + if (endpoint_edge_variation.get_value() != 0) + end = end + (endpoint_edge_variation - endpoint_edge_variation.get_value() / 2) * (end - start); + + if (!Geom::are_near(start, end)) { + gdouble scaling_y = 1.0; + if (scale_y_rel.get_value() || transformed) { + scaling_y = (L2(end - start) / scaling) * prop_scale; + transformed = false; + } else { + scaling_y = prop_scale; + } + + Affine transform; + transform.setXAxis((end - start) / scaling); + transform.setYAxis(rot90(unit_vector(end - start)) * scaling_y); + transform.setTranslation(start); + Piecewise> pwd2_out = (strokepath.get_pwd2() - stroke_origin) * transform; + + // add stuff to one big pw > and then outside the loop convert to path? + // No: this way, the separate result paths are kept separate which might come in handy some + // time! + Geom::PathVector result = Geom::path_from_piecewise(pwd2_out, LPE_CONVERSION_TOLERANCE); + path_out.push_back(result[0]); } - - Affine transform; - transform.setXAxis( (end-start) / scaling ); - transform.setYAxis( rot90(unit_vector(end-start)) * scaling_y); - transform.setTranslation( start ); - Piecewise > pwd2_out = (strokepath.get_pwd2()-stroke_origin) * transform; - - // add stuff to one big pw > and then outside the loop convert to path? - // No: this way, the separate result paths are kept separate which might come in handy some time! - Geom::PathVector result = Geom::path_from_piecewise(pwd2_out, LPE_CONVERSION_TOLERANCE); - path_out.push_back(result[0]); + gdouble svA = startpoint_spacing_variation - startpoint_spacing_variation.get_value() / 2; + gdouble svB = endpoint_spacing_variation - endpoint_spacing_variation.get_value() / 2; + tAclean += incrementA; + tBclean += incrementB; + tA = tAclean + incrementA * svA; + tB = tBclean + incrementB * svB; + if (tA > bndsA.max()) + tA = bndsA.max(); + if (tB > bndsB.max()) + tB = bndsB.max(); } - gdouble svA = startpoint_spacing_variation - startpoint_spacing_variation.get_value()/2; - gdouble svB = endpoint_spacing_variation - endpoint_spacing_variation.get_value()/2; - tAclean += incrementA; - tBclean += incrementB; - tA = tAclean + incrementA * svA; - tB = tBclean + incrementB * svB; - if (tA > bndsA.max()) - tA = bndsA.max(); - if (tB > bndsB.max()) - tB = bndsB.max(); } - } return path_out; } else { @@ -145,34 +157,34 @@ LPECurveStitch::doEffect_path (Geom::PathVector const & path_in) } } -void -LPECurveStitch::resetDefaults(SPItem const* item) +void LPECurveStitch::resetDefaults(SPItem const *item) { Effect::resetDefaults(item); - if (!SP_IS_PATH(item)) return; + if (!SP_IS_PATH(item)) + return; using namespace Geom; // set the stroke path to run horizontally in the middle of the bounding box of the original path - + // calculate bounding box: (isn't there a simpler way?) - Piecewise > pwd2; - Geom::PathVector temppath = sp_svg_read_pathv( item->getRepr()->attribute("inkscape:original-d")); - for (const auto & i : temppath) { - pwd2.concat( i.toPwSb() ); + Piecewise> pwd2; + Geom::PathVector temppath = sp_svg_read_pathv(item->getRepr()->attribute("inkscape:original-d")); + for (const auto &i : temppath) { + pwd2.concat(i.toPwSb()); } - D2 > d2pw = make_cuts_independent(pwd2); + D2> d2pw = make_cuts_independent(pwd2); OptInterval bndsX = bounds_exact(d2pw[0]); OptInterval bndsY = bounds_exact(d2pw[1]); if (bndsX && bndsY) { - Point start(bndsX->min(), (bndsY->max()+bndsY->min())/2); - Point end(bndsX->max(), (bndsY->max()+bndsY->min())/2); - if ( !Geom::are_near(start,end) ) { + Point start(bndsX->min(), (bndsY->max() + bndsY->min()) / 2); + Point end(bndsX->max(), (bndsY->max() + bndsY->min()) / 2); + if (!Geom::are_near(start, end)) { Geom::Path path; - path.start( start ); - path.appendNew( end ); - strokepath.set_new_value( path.toPwSb(), true ); + path.start(start); + path.appendNew(end); + strokepath.set_new_value(path.toPwSb(), true); } else { // bounding box is too small to make decent path. set to default default. :-) strokepath.param_set_and_write_default(); @@ -183,7 +195,7 @@ LPECurveStitch::resetDefaults(SPItem const* item) } } -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-curvestitch.h b/src/live_effects/lpe-curvestitch.h index 7faef725bfcd3effa8e679a3075ae6d76bb1e49f..8089e53bbaa0c9ae5c578f65173ab399986989ba 100644 --- a/src/live_effects/lpe-curvestitch.h +++ b/src/live_effects/lpe-curvestitch.h @@ -16,22 +16,23 @@ */ #include "live_effects/effect.h" -#include "live_effects/parameter/path.h" -#include "live_effects/parameter/parameter.h" #include "live_effects/parameter/bool.h" +#include "live_effects/parameter/parameter.h" +#include "live_effects/parameter/path.h" #include "live_effects/parameter/random.h" namespace Inkscape { namespace LivePathEffect { -class LPECurveStitch : public Effect { +class LPECurveStitch : public Effect +{ public: LPECurveStitch(LivePathEffectObject *lpeobject); ~LPECurveStitch() override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; - void resetDefaults(SPItem const* item) override; + void resetDefaults(SPItem const *item) override; private: PathParam strokepath; @@ -44,11 +45,11 @@ private: BoolParam scale_y_rel; bool transformed; - LPECurveStitch(const LPECurveStitch&) = delete; - LPECurveStitch& operator=(const LPECurveStitch&) = delete; + LPECurveStitch(const LPECurveStitch &) = delete; + LPECurveStitch &operator=(const LPECurveStitch &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-dashed-stroke.cpp b/src/live_effects/lpe-dashed-stroke.cpp index 7edbeacdaafd60adcf9b727ee404a8e92d26ea65..9c96591dbad4d924d4054b327555aee7a1a9e3b1 100644 --- a/src/live_effects/lpe-dashed-stroke.cpp +++ b/src/live_effects/lpe-dashed-stroke.cpp @@ -3,6 +3,7 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "live_effects/lpe-dashed-stroke.h" + #include "2geom/path.h" #include "2geom/pathvector.h" #include "helper/geom.h" @@ -19,7 +20,8 @@ LPEDashedStroke::LPEDashedStroke(LivePathEffectObject *lpeobject) , holefactor(_("Hole factor"), _("Hole factor"), "holefactor", &wr, this, 0.0) , splitsegments(_("Use segments"), _("Use segments"), "splitsegments", &wr, this, true) , halfextreme(_("Half start/end"), _("Start and end of each segment has half size"), "halfextreme", &wr, this, true) - , unifysegment(_("Equalize dashes"), _("Global dash length is approximately the length of the dashes in the shortest path segment"), + , unifysegment(_("Equalize dashes"), + _("Global dash length is approximately the length of the dashes in the shortest path segment"), "unifysegment", &wr, this, true) , message(_("Note"), _("Important messages"), "message", &wr, this, _("Add \"Fill Between Many LPE\" to add fill.")) @@ -43,11 +45,11 @@ LPEDashedStroke::~LPEDashedStroke() = default; void LPEDashedStroke::doBeforeEffect(SPLPEItem const *lpeitem) {} -///Calculate the time in curve_in with a real time of A -//TODO: find a better place to it +/// Calculate the time in curve_in with a real time of A +// TODO: find a better place to it double LPEDashedStroke::timeAtLength(double const A, Geom::Path const &segment) { - if ( A == 0 || segment[0].isDegenerate()) { + if (A == 0 || segment[0].isDegenerate()) { return 0; } double t = 1; @@ -55,11 +57,11 @@ double LPEDashedStroke::timeAtLength(double const A, Geom::Path const &segment) return t; } -///Calculate the time in curve_in with a real time of A -//TODO: find a better place to it +/// Calculate the time in curve_in with a real time of A +// TODO: find a better place to it double LPEDashedStroke::timeAtLength(double const A, Geom::Piecewise> pwd2) { - if ( A == 0 || pwd2.size() == 0) { + if (A == 0 || pwd2.size() == 0) { return 0; } @@ -75,7 +77,7 @@ Geom::PathVector LPEDashedStroke::doEffect_path(Geom::PathVector const &path_in) { Geom::PathVector const pv = pathv_to_linear_and_cubic_beziers(path_in); Geom::PathVector result; - for (const auto & path_it : pv) { + for (const auto &path_it : pv) { if (path_it.empty()) { continue; } @@ -83,19 +85,19 @@ Geom::PathVector LPEDashedStroke::doEffect_path(Geom::PathVector const &path_in) Geom::Path::const_iterator curve_it2 = ++(path_it.begin()); Geom::Path::const_iterator curve_endit = path_it.end_default(); if (path_it.closed()) { - const Geom::Curve &closingline = path_it.back_closed(); - // the closing line segment is always of type - // Geom::LineSegment. - if (are_near(closingline.initialPoint(), closingline.finalPoint())) { - // closingline.isDegenerate() did not work, because it only checks for - // *exact* zero length, which goes wrong for relative coordinates and - // rounding errors... - // the closing line segment has zero-length. So stop before that one! - curve_endit = path_it.end_open(); - } + const Geom::Curve &closingline = path_it.back_closed(); + // the closing line segment is always of type + // Geom::LineSegment. + if (are_near(closingline.initialPoint(), closingline.finalPoint())) { + // closingline.isDegenerate() did not work, because it only checks for + // *exact* zero length, which goes wrong for relative coordinates and + // rounding errors... + // the closing line segment has zero-length. So stop before that one! + curve_endit = path_it.end_open(); + } } size_t numberdashes_fixed = numberdashes; - if(!splitsegments) { + if (!splitsegments) { numberdashes_fixed++; } size_t numberholes = numberdashes_fixed - 1; @@ -103,86 +105,87 @@ Geom::PathVector LPEDashedStroke::doEffect_path(Geom::PathVector const &path_in) if (halfextreme) { ammount--; } - double base = 1/(double)ammount; - double globaldash = base * numberdashes_fixed * (1 + holefactor); - if (halfextreme) { - globaldash = base * (numberdashes_fixed - 1) * (1 + holefactor); + double base = 1 / (double)ammount; + double globaldash = base * numberdashes_fixed * (1 + holefactor); + if (halfextreme) { + globaldash = base * (numberdashes_fixed - 1) * (1 + holefactor); } - double globalhole = 1-globaldash; - double dashpercent = globaldash/numberdashes_fixed; - if (halfextreme) { - dashpercent = globaldash/(numberdashes_fixed -1); + double globalhole = 1 - globaldash; + double dashpercent = globaldash / numberdashes_fixed; + if (halfextreme) { + dashpercent = globaldash / (numberdashes_fixed - 1); } - double holepercent = globalhole/numberholes; + double holepercent = globalhole / numberholes; double dashsize_fixed = 0; double holesize_fixed = 0; - Geom::Piecewise > pwd2 = path_it.toPwSb(); - double length_pwd2 = length (pwd2); + Geom::Piecewise> pwd2 = path_it.toPwSb(); + double length_pwd2 = length(pwd2); double minlength = length_pwd2; - if(unifysegment) { + if (unifysegment) { while (curve_it1 != curve_endit) { double length_segment = (*curve_it1).length(); if (length_segment < minlength) { minlength = length_segment; dashsize_fixed = (*curve_it1).length() * dashpercent; holesize_fixed = (*curve_it1).length() * holepercent; - } + } ++curve_it1; ++curve_it2; - } + } curve_it1 = path_it.begin(); curve_it2 = ++(path_it.begin()); curve_endit = path_it.end_default(); } size_t p_index = 0; size_t start_index = result.size(); - if(splitsegments) { + if (splitsegments) { while (curve_it1 != curve_endit) { Geom::Path segment = path_it.portion(p_index, p_index + 1); - if(unifysegment) { + if (unifysegment) { double integral; - modf((*curve_it1).length()/(dashsize_fixed + holesize_fixed), &integral); + modf((*curve_it1).length() / (dashsize_fixed + holesize_fixed), &integral); numberdashes_fixed = (size_t)integral + 1; numberholes = numberdashes_fixed - 1; ammount = numberdashes_fixed + numberholes; if (halfextreme) { ammount--; } - base = 1/(double)ammount; - globaldash = base * numberdashes_fixed * (1 + holefactor); - if (halfextreme) { - globaldash = base * (numberdashes_fixed - 1) * (1 + holefactor); + base = 1 / (double)ammount; + globaldash = base * numberdashes_fixed * (1 + holefactor); + if (halfextreme) { + globaldash = base * (numberdashes_fixed - 1) * (1 + holefactor); } - globalhole = 1-globaldash; - dashpercent = globaldash/numberdashes_fixed; - if (halfextreme) { - dashpercent = globaldash/(numberdashes_fixed -1); + globalhole = 1 - globaldash; + dashpercent = globaldash / numberdashes_fixed; + if (halfextreme) { + dashpercent = globaldash / (numberdashes_fixed - 1); } - holepercent = globalhole/numberholes; + holepercent = globalhole / numberholes; } double dashsize = (*curve_it1).length() * dashpercent; double holesize = (*curve_it1).length() * holepercent; if ((*curve_it1).isLineSegment()) { - if (result.size() && Geom::are_near(segment.initialPoint(),result[result.size()-1].finalPoint())) { - result[result.size()-1].setFinal(segment.initialPoint()); + if (result.size() && + Geom::are_near(segment.initialPoint(), result[result.size() - 1].finalPoint())) { + result[result.size() - 1].setFinal(segment.initialPoint()); if (halfextreme) { - result[result.size()-1].append(segment.portion(0.0, dashpercent/2.0)); + result[result.size() - 1].append(segment.portion(0.0, dashpercent / 2.0)); } else { - result[result.size()-1].append(segment.portion(0.0, dashpercent)); + result[result.size() - 1].append(segment.portion(0.0, dashpercent)); } } else { if (halfextreme) { - result.push_back(segment.portion(0.0, dashpercent/2.0)); + result.push_back(segment.portion(0.0, dashpercent / 2.0)); } else { result.push_back(segment.portion(0.0, dashpercent)); } } - + double start = dashpercent + holepercent; if (halfextreme) { - start = (dashpercent/2.0) + holepercent; + start = (dashpercent / 2.0) + holepercent; } - while (start < 1) { + while (start < 1) { if (start + dashpercent > 1) { result.push_back(segment.portion(start, 1)); } else { @@ -194,70 +197,71 @@ Geom::PathVector LPEDashedStroke::doEffect_path(Geom::PathVector const &path_in) double start = 0.0; double end = 0.0; if (halfextreme) { - end = timeAtLength(dashsize/2.0,segment); + end = timeAtLength(dashsize / 2.0, segment); } else { - end = timeAtLength(dashsize,segment); + end = timeAtLength(dashsize, segment); } - if (result.size() && Geom::are_near(segment.initialPoint(),result[result.size()-1].finalPoint())) { - result[result.size()-1].setFinal(segment.initialPoint()); - result[result.size()-1].append(segment.portion(start, end)); + if (result.size() && + Geom::are_near(segment.initialPoint(), result[result.size() - 1].finalPoint())) { + result[result.size() - 1].setFinal(segment.initialPoint()); + result[result.size() - 1].append(segment.portion(start, end)); } else { result.push_back(segment.portion(start, end)); } double startsize = dashsize + holesize; if (halfextreme) { - startsize = (dashsize/2.0) + holesize; + startsize = (dashsize / 2.0) + holesize; } double endsize = startsize + dashsize; - start = timeAtLength(startsize,segment); - end = timeAtLength(endsize,segment); - while (start < 1 && start > 0) { + start = timeAtLength(startsize, segment); + end = timeAtLength(endsize, segment); + while (start < 1 && start > 0) { result.push_back(segment.portion(start, end)); startsize = endsize + holesize; endsize = startsize + dashsize; - start = timeAtLength(startsize,segment); - end = timeAtLength(endsize,segment); + start = timeAtLength(startsize, segment); + end = timeAtLength(endsize, segment); } } if (curve_it2 == curve_endit) { if (path_it.closed()) { - Geom::Path end = result[result.size()-1]; + Geom::Path end = result[result.size() - 1]; end.setFinal(result[start_index].initialPoint()); end.append(result[start_index]); result[start_index] = end; } } - p_index ++; + p_index++; ++curve_it1; ++curve_it2; - } + } } else { double start = 0.0; double end = 0.0; double dashsize = length_pwd2 * dashpercent; double holesize = length_pwd2 * holepercent; if (halfextreme) { - end = timeAtLength(dashsize/2.0,pwd2); + end = timeAtLength(dashsize / 2.0, pwd2); } else { - end = timeAtLength(dashsize,pwd2); + end = timeAtLength(dashsize, pwd2); } result.push_back(path_it.portion(start, end)); double startsize = dashsize + holesize; if (halfextreme) { - startsize = (dashsize/2.0) + holesize; + startsize = (dashsize / 2.0) + holesize; } double endsize = startsize + dashsize; - start = timeAtLength(startsize,pwd2); - end = timeAtLength(endsize,pwd2); - while (start < path_it.size() && start > 0) { + start = timeAtLength(startsize, pwd2); + end = timeAtLength(endsize, pwd2); + while (start < path_it.size() && start > 0) { result.push_back(path_it.portion(start, end)); startsize = endsize + holesize; endsize = startsize + dashsize; - start = timeAtLength(startsize,pwd2); - end = timeAtLength(endsize,pwd2); + start = timeAtLength(startsize, pwd2); + end = timeAtLength(endsize, pwd2); } if (path_it.closed()) { - Geom::Path end = result[result.size()-1]; + Geom::Path end = result[result.size() - 1]; end.setFinal(result[start_index].initialPoint()); end.append(result[start_index]); result[start_index] = end; @@ -267,7 +271,7 @@ Geom::PathVector LPEDashedStroke::doEffect_path(Geom::PathVector const &path_in) return result; } -}; //namespace LivePathEffect +}; // namespace LivePathEffect }; /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-dashed-stroke.h b/src/live_effects/lpe-dashed-stroke.h index d001eaf21631c88cbc00b0ef79f3dd9d7ffc752e..404e99b678aeae75c7e181047d05c960dab7335b 100644 --- a/src/live_effects/lpe-dashed-stroke.h +++ b/src/live_effects/lpe-dashed-stroke.h @@ -14,14 +14,16 @@ namespace Inkscape { namespace LivePathEffect { -class LPEDashedStroke : public Effect { - public: +class LPEDashedStroke : public Effect +{ +public: LPEDashedStroke(LivePathEffectObject *lpeobject); ~LPEDashedStroke() override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; double timeAtLength(double const A, Geom::Path const &segment); - double timeAtLength(double const A, Geom::Piecewise > pwd2); + double timeAtLength(double const A, Geom::Piecewise> pwd2); + private: ScalarParam numberdashes; ScalarParam holefactor; @@ -31,6 +33,6 @@ private: MessageParam message; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-dynastroke.cpp b/src/live_effects/lpe-dynastroke.cpp index 52b09fe044baa13c4f525e11e0fc164978f3a406..8171b0275fb5791ca43b92d9d73618e373202257 100644 --- a/src/live_effects/lpe-dynastroke.cpp +++ b/src/live_effects/lpe-dynastroke.cpp @@ -12,6 +12,7 @@ */ #include "live_effects/lpe-dynastroke.h" + #include "display/curve.h" //# include @@ -22,45 +23,46 @@ namespace Inkscape { namespace LivePathEffect { -//TODO: growfor/fadefor can be expressed in unit of width. -//TODO: make round/sharp end choices independent for start and end. -//TODO: define more styles like in calligtool. -//TODO: allow fancy ends. +// TODO: growfor/fadefor can be expressed in unit of width. +// TODO: make round/sharp end choices independent for start and end. +// TODO: define more styles like in calligtool. +// TODO: allow fancy ends. static const Util::EnumData DynastrokeMethodData[DSM_END] = { - {DSM_ELLIPTIC_PEN, N_("Elliptic Pen"), "elliptic_pen"}, - {DSM_THICKTHIN_FAST, N_("Thick-Thin strokes (fast)"), "thickthin_fast"}, - {DSM_THICKTHIN_SLOW, N_("Thick-Thin strokes (slow)"), "thickthin_slow"} -}; + {DSM_ELLIPTIC_PEN, N_("Elliptic Pen"), "elliptic_pen"}, + {DSM_THICKTHIN_FAST, N_("Thick-Thin strokes (fast)"), "thickthin_fast"}, + {DSM_THICKTHIN_SLOW, N_("Thick-Thin strokes (slow)"), "thickthin_slow"}}; static const Util::EnumDataConverter DSMethodConverter(DynastrokeMethodData, DSM_END); static const Util::EnumData DynastrokeCappingTypeData[DSCT_END] = { - {DSCT_SHARP, N_("Sharp"), "sharp"}, - {DSCT_ROUND, N_("Round"), "round"}, + {DSCT_SHARP, N_("Sharp"), "sharp"}, + {DSCT_ROUND, N_("Round"), "round"}, }; static const Util::EnumDataConverter DSCTConverter(DynastrokeCappingTypeData, DSCT_END); -LPEDynastroke::LPEDynastroke(LivePathEffectObject *lpeobject) : - Effect(lpeobject), +LPEDynastroke::LPEDynastroke(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , // initialise your parameters here: - method(_("Method:"), _("Choose pen type"), "method", DSMethodConverter, &wr, this, DSM_THICKTHIN_FAST), - width(_("Pen width:"), _("Maximal stroke width"), "width", &wr, this, 25), - roundness(_("Pen roundness:"), _("Min/Max width ratio"), "roundness", &wr, this, .2), - angle(_("Angle:"), _("direction of thickest strokes (opposite = thinnest)"), "angle", &wr, this, 45), -// modulo_pi(_("modulo pi"), _("Give forward and backward moves in one direction the same thickness "), "modulo_pi", &wr, this, false), - start_cap(_("Start:"), _("Choose start capping type"), "start_cap", DSCTConverter, &wr, this, DSCT_SHARP), - end_cap(_("End:"), _("Choose end capping type"), "end_cap", DSCTConverter, &wr, this, DSCT_SHARP), - growfor(_("Grow for:"), _("Make the stroke thinner near it's start"), "growfor", &wr, this, 100), - fadefor(_("Fade for:"), _("Make the stroke thinner near it's end"), "fadefor", &wr, this, 100), - round_ends(_("Round ends"), _("Strokes end with a round end"), "round_ends", &wr, this, false), - capping(_("Capping:"), _("left capping"), "capping", &wr, this, "M 100,5 C 50,5 0,0 0,0 0,0 50,-5 100,-5") + method(_("Method:"), _("Choose pen type"), "method", DSMethodConverter, &wr, this, DSM_THICKTHIN_FAST) + , width(_("Pen width:"), _("Maximal stroke width"), "width", &wr, this, 25) + , roundness(_("Pen roundness:"), _("Min/Max width ratio"), "roundness", &wr, this, .2) + , angle(_("Angle:"), _("direction of thickest strokes (opposite = thinnest)"), "angle", &wr, this, 45) + , + // modulo_pi(_("modulo pi"), _("Give forward and backward moves in one direction the same thickness "), + // "modulo_pi", &wr, this, false), + start_cap(_("Start:"), _("Choose start capping type"), "start_cap", DSCTConverter, &wr, this, DSCT_SHARP) + , end_cap(_("End:"), _("Choose end capping type"), "end_cap", DSCTConverter, &wr, this, DSCT_SHARP) + , growfor(_("Grow for:"), _("Make the stroke thinner near it's start"), "growfor", &wr, this, 100) + , fadefor(_("Fade for:"), _("Make the stroke thinner near it's end"), "fadefor", &wr, this, 100) + , round_ends(_("Round ends"), _("Strokes end with a round end"), "round_ends", &wr, this, false) + , capping(_("Capping:"), _("left capping"), "capping", &wr, this, "M 100,5 C 50,5 0,0 0,0 0,0 50,-5 100,-5") { - registerParameter(&method); registerParameter(&width); registerParameter(&roundness); registerParameter(&angle); - //registerParameter(&modulo_pi) ); + // registerParameter(&modulo_pi) ); registerParameter(&start_cap); registerParameter(&growfor); registerParameter(&end_cap); @@ -77,27 +79,27 @@ LPEDynastroke::LPEDynastroke(LivePathEffectObject *lpeobject) : show_orig_path = true; } -LPEDynastroke::~LPEDynastroke() -= default; +LPEDynastroke::~LPEDynastroke() = default; -Geom::Piecewise > -LPEDynastroke::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPEDynastroke::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; -// std::cout<<"do effect: debut\n"; - - Piecewise > output; - Piecewise > m = pwd2_in; - Piecewise > v = derivative(m);; - Piecewise > n = unitVector(v); - n = rot90(n); - Piecewise > n1,n2; + // std::cout<<"do effect: debut\n"; -// for (unsigned i=0; i> output; + Piecewise> m = pwd2_in; + Piecewise> v = derivative(m); + ; + Piecewise> n = unitVector(v); + n = rot90(n); + Piecewise> n1, n2; + + // for (unsigned i=0; i k = curvature(m); @@ -119,171 +121,170 @@ LPEDynastroke::doEffect_pwd2 (Geom::Piecewise > const & p return output; #else - double angle_rad = angle*M_PI/180.;//TODO: revert orientation?... - Piecewise w; - - // std::vector corners = find_corners(m); - - DynastrokeMethod stroke_method = method.get_value(); - if (roundness==1.) { -// std::cout<<"round pen.\n"; - n1 = n*double(width); - n2 =-n1; - }else{ - switch(stroke_method) { - case DSM_ELLIPTIC_PEN:{ -// std::cout<<"ellptic pen\n"; - //FIXME: roundness=0??? - double c = cos(angle_rad), s = sin(angle_rad); - Affine rot,slant; - rot = Affine(c, -s, s, c, 0, 0 ); - slant = Affine(double(width)*roundness, 0, 0, double(width), 0, 0 ); - Piecewise > nn = unitVector(v * ( rot * slant ) ); - slant = Affine( 0,-roundness, 1, 0, 0, 0 ); - rot = Affine(-s, -c, c, -s, 0, 0 ); - nn = nn * (slant * rot ); - - n1 = nn*double(width); - n2 =-n1; - break; - } - case DSM_THICKTHIN_FAST:{ -// std::cout<<"fast thick thin pen\n"; - D2 > n_xy = make_cuts_independent(n); - w = n_xy[X]*sin(angle_rad) - n_xy[Y]*cos(angle_rad); - w = w * ((1 - roundness)*width/2.) + ((1 + roundness)*width/2.); - n1 = w*n; - n2 = -n1; - break; - } - case DSM_THICKTHIN_SLOW:{ -// std::cout<<"slow thick thin pen\n"; - D2 > n_xy = make_cuts_independent(n); - w = n_xy[X]*cos(angle_rad)+ n_xy[Y]*sin(angle_rad); - w = w * ((1 - roundness)*width/2.) + ((1 + roundness)*width/2.); - //->Slower and less stable, but more accurate . - // General formula: n1 = w*u with ||u||=1 and u.v = -dw/dt - Piecewise dw = derivative(w); - Piecewise ncomp = sqrt(dot(v,v)-dw*dw,.1,3); - //FIXME: is force continuity useful? compatible with corners? -// std::cout<<"ici\n"; - n1 = -dw*v + ncomp*rot90(v); - n1 = w*force_continuity(unitVector(n1),.1); - n2 = -dw*v - ncomp*rot90(v); - n2 = w*force_continuity(unitVector(n2),.1); -// std::cout<<"ici2\n"; - break; - } - default:{ - n1 = n*double(width); - n2 = n1*(-.5); - break; - } - }//case - }//if/else - - // - //TODO: insert relevant stitch at each corner!! - // - - Piecewise > left, right; - if ( m.segs.front().at0() == m.segs.back().at1()){ - // if closed: -// std::cout<<"closed input.\n"; - left = m + n1;//+ n; - right = m + n2;//- n; - } else { - //if not closed, shape the ends: - //TODO: allow fancy ends... -// std::cout<<"shaping the ends\n"; - double grow_length = growfor;// * width; - double fade_length = fadefor;// * width; - Piecewise s = arcLengthSb(m); - double totlength = s.segs.back().at1(); - - //scale factor for a sharp start - SBasis join = SBasis(2,Linear(0,1)); - join[1] = Linear(1,1); - Piecewise factor_in = Piecewise(join); - factor_in.cuts[1]=grow_length; - if (grow_length < totlength){ - factor_in.concat(Piecewise(Linear(1))); - factor_in.cuts[2]=totlength; - } -// std::cout<<"shaping the ends ici\n"; - //scale factor for a sharp end - join[0] = Linear(1,0); - join[1] = Linear(1,1); - Piecewise factor_out; - if (fade_length < totlength){ - factor_out = Piecewise(Linear(1)); - factor_out.cuts[1] = totlength-fade_length; - factor_out.concat(Piecewise(join)); - factor_out.cuts[2] = totlength; - }else{ - factor_out = Piecewise(join); - factor_out.setDomain(Interval(totlength-fade_length,totlength)); - } -// std::cout<<"shaping the ends ici ici\n"; - - Piecewise factor = factor_in*factor_out; - n1 = compose(factor,s)*n1; - n2 = compose(factor,s)*n2; - - left = m + n1; - right = m + n2; -// std::cout<<"shaping the ends ici ici ici\n"; - - if (start_cap.get_value() == DSCT_ROUND){ -// std::cout<<"shaping round start\n"; - SBasis tau(2,Linear(0)); - tau[1] = Linear(-1,0); - Piecewise hbump; - hbump.concat(Piecewise(tau*grow_length)); - hbump.concat(Piecewise(Linear(0))); - hbump.cuts[0]=0; - hbump.cuts[1]=fmin(grow_length,totlength*grow_length/(grow_length+fade_length)); - hbump.cuts[2]=totlength; - hbump = compose(hbump,s); - - left += - hbump * rot90(n); - right += - hbump * rot90(n); - } - if (end_cap.get_value() == DSCT_ROUND){ -// std::cout<<"shaping round end\n"; - SBasis tau(2,Linear(0)); - tau[1] = Linear(0,1); - Piecewise hbump; - hbump.concat(Piecewise(Linear(0))); - hbump.concat(Piecewise(tau*fade_length)); - hbump.cuts[0]=0; - hbump.cuts[1]=fmax(totlength-fade_length, totlength*grow_length/(grow_length+fade_length)); - hbump.cuts[2]=totlength; - hbump = compose(hbump,s); - - left += - hbump * rot90(n); - right += - hbump * rot90(n); - } - } - - left = force_continuity(left); - right = force_continuity(right); - -// std::cout<<"gathering result: left"; - output = left; -// std::cout<<" + reverse(right)"; - output.concat(reverse(right)); -// std::cout<<". done\n"; + double angle_rad = angle * M_PI / 180.; // TODO: revert orientation?... + Piecewise w; + + // std::vector corners = find_corners(m); + + DynastrokeMethod stroke_method = method.get_value(); + if (roundness == 1.) { + // std::cout<<"round pen.\n"; + n1 = n * double(width); + n2 = -n1; + } else { + switch (stroke_method) { + case DSM_ELLIPTIC_PEN: { + // std::cout<<"ellptic pen\n"; + // FIXME: roundness=0??? + double c = cos(angle_rad), s = sin(angle_rad); + Affine rot, slant; + rot = Affine(c, -s, s, c, 0, 0); + slant = Affine(double(width) * roundness, 0, 0, double(width), 0, 0); + Piecewise> nn = unitVector(v * (rot * slant)); + slant = Affine(0, -roundness, 1, 0, 0, 0); + rot = Affine(-s, -c, c, -s, 0, 0); + nn = nn * (slant * rot); + + n1 = nn * double(width); + n2 = -n1; + break; + } + case DSM_THICKTHIN_FAST: { + // std::cout<<"fast thick thin pen\n"; + D2> n_xy = make_cuts_independent(n); + w = n_xy[X] * sin(angle_rad) - n_xy[Y] * cos(angle_rad); + w = w * ((1 - roundness) * width / 2.) + ((1 + roundness) * width / 2.); + n1 = w * n; + n2 = -n1; + break; + } + case DSM_THICKTHIN_SLOW: { + // std::cout<<"slow thick thin pen\n"; + D2> n_xy = make_cuts_independent(n); + w = n_xy[X] * cos(angle_rad) + n_xy[Y] * sin(angle_rad); + w = w * ((1 - roundness) * width / 2.) + ((1 + roundness) * width / 2.); + //->Slower and less stable, but more accurate . + // General formula: n1 = w*u with ||u||=1 and u.v = -dw/dt + Piecewise dw = derivative(w); + Piecewise ncomp = sqrt(dot(v, v) - dw * dw, .1, 3); + // FIXME: is force continuity useful? compatible with corners? + // std::cout<<"ici\n"; + n1 = -dw * v + ncomp * rot90(v); + n1 = w * force_continuity(unitVector(n1), .1); + n2 = -dw * v - ncomp * rot90(v); + n2 = w * force_continuity(unitVector(n2), .1); + // std::cout<<"ici2\n"; + break; + } + default: { + n1 = n * double(width); + n2 = n1 * (-.5); + break; + } + } // case + } // if/else + + // + // TODO: insert relevant stitch at each corner!! + // + + Piecewise> left, right; + if (m.segs.front().at0() == m.segs.back().at1()) { + // if closed: + // std::cout<<"closed input.\n"; + left = m + n1; //+ n; + right = m + n2; //- n; + } else { + // if not closed, shape the ends: + // TODO: allow fancy ends... + // std::cout<<"shaping the ends\n"; + double grow_length = growfor; // * width; + double fade_length = fadefor; // * width; + Piecewise s = arcLengthSb(m); + double totlength = s.segs.back().at1(); -//----------- - return output; + // scale factor for a sharp start + SBasis join = SBasis(2, Linear(0, 1)); + join[1] = Linear(1, 1); + Piecewise factor_in = Piecewise(join); + factor_in.cuts[1] = grow_length; + if (grow_length < totlength) { + factor_in.concat(Piecewise(Linear(1))); + factor_in.cuts[2] = totlength; + } + // std::cout<<"shaping the ends ici\n"; + // scale factor for a sharp end + join[0] = Linear(1, 0); + join[1] = Linear(1, 1); + Piecewise factor_out; + if (fade_length < totlength) { + factor_out = Piecewise(Linear(1)); + factor_out.cuts[1] = totlength - fade_length; + factor_out.concat(Piecewise(join)); + factor_out.cuts[2] = totlength; + } else { + factor_out = Piecewise(join); + factor_out.setDomain(Interval(totlength - fade_length, totlength)); + } + // std::cout<<"shaping the ends ici ici\n"; + + Piecewise factor = factor_in * factor_out; + n1 = compose(factor, s) * n1; + n2 = compose(factor, s) * n2; + + left = m + n1; + right = m + n2; + // std::cout<<"shaping the ends ici ici ici\n"; + + if (start_cap.get_value() == DSCT_ROUND) { + // std::cout<<"shaping round start\n"; + SBasis tau(2, Linear(0)); + tau[1] = Linear(-1, 0); + Piecewise hbump; + hbump.concat(Piecewise(tau * grow_length)); + hbump.concat(Piecewise(Linear(0))); + hbump.cuts[0] = 0; + hbump.cuts[1] = fmin(grow_length, totlength * grow_length / (grow_length + fade_length)); + hbump.cuts[2] = totlength; + hbump = compose(hbump, s); + + left += -hbump * rot90(n); + right += -hbump * rot90(n); + } + if (end_cap.get_value() == DSCT_ROUND) { + // std::cout<<"shaping round end\n"; + SBasis tau(2, Linear(0)); + tau[1] = Linear(0, 1); + Piecewise hbump; + hbump.concat(Piecewise(Linear(0))); + hbump.concat(Piecewise(tau * fade_length)); + hbump.cuts[0] = 0; + hbump.cuts[1] = fmax(totlength - fade_length, totlength * grow_length / (grow_length + fade_length)); + hbump.cuts[2] = totlength; + hbump = compose(hbump, s); + + left += -hbump * rot90(n); + right += -hbump * rot90(n); + } + } + + left = force_continuity(left); + right = force_continuity(right); + + // std::cout<<"gathering result: left"; + output = left; + // std::cout<<" + reverse(right)"; + output.concat(reverse(right)); + // std::cout<<". done\n"; + + //----------- + return output; #endif } - /* ######################## */ -} //namespace LivePathEffect (setq default-directory "c:/Documents And Settings/jf/Mes Documents/InkscapeSVN") +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-dynastroke.h b/src/live_effects/lpe-dynastroke.h index ae1c511b24587efcb4a95286d3416e7cd50022af..362a0c5059c30c184c4ffc4fff1f35e5c3143259 100644 --- a/src/live_effects/lpe-dynastroke.h +++ b/src/live_effects/lpe-dynastroke.h @@ -15,54 +15,57 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/enum.h" #include "live_effects/effect.h" +#include "live_effects/parameter/bool.h" +#include "live_effects/parameter/enum.h" #include "live_effects/parameter/parameter.h" #include "live_effects/parameter/path.h" -#include "live_effects/parameter/bool.h" namespace Inkscape { namespace LivePathEffect { -enum DynastrokeMethod { +enum DynastrokeMethod +{ DSM_ELLIPTIC_PEN = 0, DSM_THICKTHIN_FAST, DSM_THICKTHIN_SLOW, DSM_END // This must be last }; -enum DynastrokeCappingType { +enum DynastrokeCappingType +{ DSCT_SHARP = 0, DSCT_ROUND, - //DSCT_CUSTOM, + // DSCT_CUSTOM, DSCT_END // This must be last }; - -class LPEDynastroke : public Effect { +class LPEDynastroke : public Effect +{ public: LPEDynastroke(LivePathEffectObject *lpeobject); ~LPEDynastroke() override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; private: EnumParam method; ScalarParam width; ScalarParam roundness; ScalarParam angle; - //BoolParam modulo_pi; + // BoolParam modulo_pi; EnumParam start_cap; EnumParam end_cap; ScalarParam growfor; ScalarParam fadefor; BoolParam round_ends; - PathParam capping; + PathParam capping; - LPEDynastroke(const LPEDynastroke&) = delete; - LPEDynastroke& operator=(const LPEDynastroke&) = delete; + LPEDynastroke(const LPEDynastroke &) = delete; + LPEDynastroke &operator=(const LPEDynastroke &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-ellipse_5pts.cpp b/src/live_effects/lpe-ellipse_5pts.cpp index 29288f8a8ea621d60b1e0cd524791790f0dcfad4..84f2ffb2bd1c153bd2c1b762e4b858c1cddad6e7 100644 --- a/src/live_effects/lpe-ellipse_5pts.cpp +++ b/src/live_effects/lpe-ellipse_5pts.cpp @@ -13,11 +13,13 @@ */ #include "live_effects/lpe-ellipse_5pts.h" + #include <2geom/circle.h> #include <2geom/ellipse.h> #include <2geom/path-sink.h> -#include "inkscape.h" + #include "desktop.h" +#include "inkscape.h" #include "message-stack.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -25,25 +27,22 @@ namespace Inkscape { namespace LivePathEffect { -LPEEllipse5Pts::LPEEllipse5Pts(LivePathEffectObject *lpeobject) : - Effect(lpeobject) +LPEEllipse5Pts::LPEEllipse5Pts(LivePathEffectObject *lpeobject) + : Effect(lpeobject) { - //perceived_path = true; + // perceived_path = true; } -LPEEllipse5Pts::~LPEEllipse5Pts() -= default; +LPEEllipse5Pts::~LPEEllipse5Pts() = default; static double _det3(double (*mat)[3]) { - for (int i = 0; i < 2; i++) - { - for (int j = i + 1; j < 3; j++) - { - for (int k = i + 1; k < 3; k++) - { + for (int i = 0; i < 2; i++) { + for (int j = i + 1; j < 3; j++) { + for (int k = i + 1; k < 3; k++) { mat[j][k] = (mat[j][k] * mat[i][i] - mat[j][i] * mat[i][k]); - if (i) mat[j][k] /= mat[i-1][i-1]; + if (i) + mat[j][k] /= mat[i - 1][i - 1]; } } } @@ -51,28 +50,25 @@ static double _det3(double (*mat)[3]) } static double _det5(double (*mat)[5]) { - for (int i = 0; i < 4; i++) - { - for (int j = i + 1; j < 5; j++) - { - for (int k = i + 1; k < 5; k++) - { + for (int i = 0; i < 4; i++) { + for (int j = i + 1; j < 5; j++) { + for (int k = i + 1; k < 5; k++) { mat[j][k] = (mat[j][k] * mat[i][i] - mat[j][i] * mat[i][k]); - if (i) mat[j][k] /= mat[i-1][i-1]; + if (i) + mat[j][k] /= mat[i - 1][i - 1]; } } } return mat[4][4]; } -Geom::PathVector -LPEEllipse5Pts::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPEEllipse5Pts::doEffect_path(Geom::PathVector const &path_in) { Geom::PathVector path_out = Geom::PathVector(); if (path_in[0].size() < 4) { - - SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Five points required for constructing an ellipse")); + SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Five points required for constructing an ellipse")); return path_in; } // we assume that the path has >= 3 nodes @@ -84,85 +80,89 @@ LPEEllipse5Pts::doEffect_path (Geom::PathVector const & path_in) using namespace Geom; - double rowmajor_matrix[5][6] = - { - {A.x()*A.x(), A.x()*A.y(), A.y()*A.y(), A.x(), A.y(), 1}, - {B.x()*B.x(), B.x()*B.y(), B.y()*B.y(), B.x(), B.y(), 1}, - {C.x()*C.x(), C.x()*C.y(), C.y()*C.y(), C.x(), C.y(), 1}, - {D.x()*D.x(), D.x()*D.y(), D.y()*D.y(), D.x(), D.y(), 1}, - {E.x()*E.x(), E.x()*E.y(), E.y()*E.y(), E.x(), E.y(), 1} - }; - - double mat_a[5][5] = - { - {rowmajor_matrix[0][1], rowmajor_matrix[1][1], rowmajor_matrix[2][1], rowmajor_matrix[3][1], rowmajor_matrix[4][1]}, - {rowmajor_matrix[0][2], rowmajor_matrix[1][2], rowmajor_matrix[2][2], rowmajor_matrix[3][2], rowmajor_matrix[4][2]}, - {rowmajor_matrix[0][3], rowmajor_matrix[1][3], rowmajor_matrix[2][3], rowmajor_matrix[3][3], rowmajor_matrix[4][3]}, - {rowmajor_matrix[0][4], rowmajor_matrix[1][4], rowmajor_matrix[2][4], rowmajor_matrix[3][4], rowmajor_matrix[4][4]}, - {rowmajor_matrix[0][5], rowmajor_matrix[1][5], rowmajor_matrix[2][5], rowmajor_matrix[3][5], rowmajor_matrix[4][5]} - }; - double mat_b[5][5] = - { - {rowmajor_matrix[0][0], rowmajor_matrix[1][0], rowmajor_matrix[2][0], rowmajor_matrix[3][0], rowmajor_matrix[4][0]}, - {rowmajor_matrix[0][2], rowmajor_matrix[1][2], rowmajor_matrix[2][2], rowmajor_matrix[3][2], rowmajor_matrix[4][2]}, - {rowmajor_matrix[0][3], rowmajor_matrix[1][3], rowmajor_matrix[2][3], rowmajor_matrix[3][3], rowmajor_matrix[4][3]}, - {rowmajor_matrix[0][4], rowmajor_matrix[1][4], rowmajor_matrix[2][4], rowmajor_matrix[3][4], rowmajor_matrix[4][4]}, - {rowmajor_matrix[0][5], rowmajor_matrix[1][5], rowmajor_matrix[2][5], rowmajor_matrix[3][5], rowmajor_matrix[4][5]} - }; - double mat_c[5][5] = - { - {rowmajor_matrix[0][0], rowmajor_matrix[1][0], rowmajor_matrix[2][0], rowmajor_matrix[3][0], rowmajor_matrix[4][0]}, - {rowmajor_matrix[0][1], rowmajor_matrix[1][1], rowmajor_matrix[2][1], rowmajor_matrix[3][1], rowmajor_matrix[4][1]}, - {rowmajor_matrix[0][3], rowmajor_matrix[1][3], rowmajor_matrix[2][3], rowmajor_matrix[3][3], rowmajor_matrix[4][3]}, - {rowmajor_matrix[0][4], rowmajor_matrix[1][4], rowmajor_matrix[2][4], rowmajor_matrix[3][4], rowmajor_matrix[4][4]}, - {rowmajor_matrix[0][5], rowmajor_matrix[1][5], rowmajor_matrix[2][5], rowmajor_matrix[3][5], rowmajor_matrix[4][5]} - }; - double mat_d[5][5] = - { - {rowmajor_matrix[0][0], rowmajor_matrix[1][0], rowmajor_matrix[2][0], rowmajor_matrix[3][0], rowmajor_matrix[4][0]}, - {rowmajor_matrix[0][1], rowmajor_matrix[1][1], rowmajor_matrix[2][1], rowmajor_matrix[3][1], rowmajor_matrix[4][1]}, - {rowmajor_matrix[0][2], rowmajor_matrix[1][2], rowmajor_matrix[2][2], rowmajor_matrix[3][2], rowmajor_matrix[4][2]}, - {rowmajor_matrix[0][4], rowmajor_matrix[1][4], rowmajor_matrix[2][4], rowmajor_matrix[3][4], rowmajor_matrix[4][4]}, - {rowmajor_matrix[0][5], rowmajor_matrix[1][5], rowmajor_matrix[2][5], rowmajor_matrix[3][5], rowmajor_matrix[4][5]} - }; - double mat_e[5][5] = - { - {rowmajor_matrix[0][0], rowmajor_matrix[1][0], rowmajor_matrix[2][0], rowmajor_matrix[3][0], rowmajor_matrix[4][0]}, - {rowmajor_matrix[0][1], rowmajor_matrix[1][1], rowmajor_matrix[2][1], rowmajor_matrix[3][1], rowmajor_matrix[4][1]}, - {rowmajor_matrix[0][2], rowmajor_matrix[1][2], rowmajor_matrix[2][2], rowmajor_matrix[3][2], rowmajor_matrix[4][2]}, - {rowmajor_matrix[0][3], rowmajor_matrix[1][3], rowmajor_matrix[2][3], rowmajor_matrix[3][3], rowmajor_matrix[4][3]}, - {rowmajor_matrix[0][5], rowmajor_matrix[1][5], rowmajor_matrix[2][5], rowmajor_matrix[3][5], rowmajor_matrix[4][5]} - }; - double mat_f[5][5] = - { - {rowmajor_matrix[0][0], rowmajor_matrix[1][0], rowmajor_matrix[2][0], rowmajor_matrix[3][0], rowmajor_matrix[4][0]}, - {rowmajor_matrix[0][1], rowmajor_matrix[1][1], rowmajor_matrix[2][1], rowmajor_matrix[3][1], rowmajor_matrix[4][1]}, - {rowmajor_matrix[0][2], rowmajor_matrix[1][2], rowmajor_matrix[2][2], rowmajor_matrix[3][2], rowmajor_matrix[4][2]}, - {rowmajor_matrix[0][3], rowmajor_matrix[1][3], rowmajor_matrix[2][3], rowmajor_matrix[3][3], rowmajor_matrix[4][3]}, - {rowmajor_matrix[0][4], rowmajor_matrix[1][4], rowmajor_matrix[2][4], rowmajor_matrix[3][4], rowmajor_matrix[4][4]} - }; - + double rowmajor_matrix[5][6] = {{A.x() * A.x(), A.x() * A.y(), A.y() * A.y(), A.x(), A.y(), 1}, + {B.x() * B.x(), B.x() * B.y(), B.y() * B.y(), B.x(), B.y(), 1}, + {C.x() * C.x(), C.x() * C.y(), C.y() * C.y(), C.x(), C.y(), 1}, + {D.x() * D.x(), D.x() * D.y(), D.y() * D.y(), D.x(), D.y(), 1}, + {E.x() * E.x(), E.x() * E.y(), E.y() * E.y(), E.x(), E.y(), 1}}; + + double mat_a[5][5] = {{rowmajor_matrix[0][1], rowmajor_matrix[1][1], rowmajor_matrix[2][1], rowmajor_matrix[3][1], + rowmajor_matrix[4][1]}, + {rowmajor_matrix[0][2], rowmajor_matrix[1][2], rowmajor_matrix[2][2], rowmajor_matrix[3][2], + rowmajor_matrix[4][2]}, + {rowmajor_matrix[0][3], rowmajor_matrix[1][3], rowmajor_matrix[2][3], rowmajor_matrix[3][3], + rowmajor_matrix[4][3]}, + {rowmajor_matrix[0][4], rowmajor_matrix[1][4], rowmajor_matrix[2][4], rowmajor_matrix[3][4], + rowmajor_matrix[4][4]}, + {rowmajor_matrix[0][5], rowmajor_matrix[1][5], rowmajor_matrix[2][5], rowmajor_matrix[3][5], + rowmajor_matrix[4][5]}}; + double mat_b[5][5] = {{rowmajor_matrix[0][0], rowmajor_matrix[1][0], rowmajor_matrix[2][0], rowmajor_matrix[3][0], + rowmajor_matrix[4][0]}, + {rowmajor_matrix[0][2], rowmajor_matrix[1][2], rowmajor_matrix[2][2], rowmajor_matrix[3][2], + rowmajor_matrix[4][2]}, + {rowmajor_matrix[0][3], rowmajor_matrix[1][3], rowmajor_matrix[2][3], rowmajor_matrix[3][3], + rowmajor_matrix[4][3]}, + {rowmajor_matrix[0][4], rowmajor_matrix[1][4], rowmajor_matrix[2][4], rowmajor_matrix[3][4], + rowmajor_matrix[4][4]}, + {rowmajor_matrix[0][5], rowmajor_matrix[1][5], rowmajor_matrix[2][5], rowmajor_matrix[3][5], + rowmajor_matrix[4][5]}}; + double mat_c[5][5] = {{rowmajor_matrix[0][0], rowmajor_matrix[1][0], rowmajor_matrix[2][0], rowmajor_matrix[3][0], + rowmajor_matrix[4][0]}, + {rowmajor_matrix[0][1], rowmajor_matrix[1][1], rowmajor_matrix[2][1], rowmajor_matrix[3][1], + rowmajor_matrix[4][1]}, + {rowmajor_matrix[0][3], rowmajor_matrix[1][3], rowmajor_matrix[2][3], rowmajor_matrix[3][3], + rowmajor_matrix[4][3]}, + {rowmajor_matrix[0][4], rowmajor_matrix[1][4], rowmajor_matrix[2][4], rowmajor_matrix[3][4], + rowmajor_matrix[4][4]}, + {rowmajor_matrix[0][5], rowmajor_matrix[1][5], rowmajor_matrix[2][5], rowmajor_matrix[3][5], + rowmajor_matrix[4][5]}}; + double mat_d[5][5] = {{rowmajor_matrix[0][0], rowmajor_matrix[1][0], rowmajor_matrix[2][0], rowmajor_matrix[3][0], + rowmajor_matrix[4][0]}, + {rowmajor_matrix[0][1], rowmajor_matrix[1][1], rowmajor_matrix[2][1], rowmajor_matrix[3][1], + rowmajor_matrix[4][1]}, + {rowmajor_matrix[0][2], rowmajor_matrix[1][2], rowmajor_matrix[2][2], rowmajor_matrix[3][2], + rowmajor_matrix[4][2]}, + {rowmajor_matrix[0][4], rowmajor_matrix[1][4], rowmajor_matrix[2][4], rowmajor_matrix[3][4], + rowmajor_matrix[4][4]}, + {rowmajor_matrix[0][5], rowmajor_matrix[1][5], rowmajor_matrix[2][5], rowmajor_matrix[3][5], + rowmajor_matrix[4][5]}}; + double mat_e[5][5] = {{rowmajor_matrix[0][0], rowmajor_matrix[1][0], rowmajor_matrix[2][0], rowmajor_matrix[3][0], + rowmajor_matrix[4][0]}, + {rowmajor_matrix[0][1], rowmajor_matrix[1][1], rowmajor_matrix[2][1], rowmajor_matrix[3][1], + rowmajor_matrix[4][1]}, + {rowmajor_matrix[0][2], rowmajor_matrix[1][2], rowmajor_matrix[2][2], rowmajor_matrix[3][2], + rowmajor_matrix[4][2]}, + {rowmajor_matrix[0][3], rowmajor_matrix[1][3], rowmajor_matrix[2][3], rowmajor_matrix[3][3], + rowmajor_matrix[4][3]}, + {rowmajor_matrix[0][5], rowmajor_matrix[1][5], rowmajor_matrix[2][5], rowmajor_matrix[3][5], + rowmajor_matrix[4][5]}}; + double mat_f[5][5] = {{rowmajor_matrix[0][0], rowmajor_matrix[1][0], rowmajor_matrix[2][0], rowmajor_matrix[3][0], + rowmajor_matrix[4][0]}, + {rowmajor_matrix[0][1], rowmajor_matrix[1][1], rowmajor_matrix[2][1], rowmajor_matrix[3][1], + rowmajor_matrix[4][1]}, + {rowmajor_matrix[0][2], rowmajor_matrix[1][2], rowmajor_matrix[2][2], rowmajor_matrix[3][2], + rowmajor_matrix[4][2]}, + {rowmajor_matrix[0][3], rowmajor_matrix[1][3], rowmajor_matrix[2][3], rowmajor_matrix[3][3], + rowmajor_matrix[4][3]}, + {rowmajor_matrix[0][4], rowmajor_matrix[1][4], rowmajor_matrix[2][4], rowmajor_matrix[3][4], + rowmajor_matrix[4][4]}}; + double a1 = _det5(mat_a); double b1 = -_det5(mat_b); double c1 = _det5(mat_c); double d1 = -_det5(mat_d); double e1 = _det5(mat_e); double f1 = -_det5(mat_f); - - double mat_check[][3] = - { - {a1, b1/2, d1/2}, - {b1/2, c1, e1/2}, - {d1/2, e1/2, f1} - }; - - if (_det3(mat_check) == 0 || a1*c1 - b1*b1/4 <= 0) { + + double mat_check[][3] = {{a1, b1 / 2, d1 / 2}, {b1 / 2, c1, e1 / 2}, {d1 / 2, e1 / 2, f1}}; + + if (_det3(mat_check) == 0 || a1 * c1 - b1 * b1 / 4 <= 0) { SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No ellipse found for specified points")); return path_in; } - + Geom::Ellipse el(a1, b1, c1, d1, e1, f1); - + double s, e; double x0, y0, x1, y1, x2, y2, x3, y3; double len; @@ -176,7 +176,7 @@ LPEEllipse5Pts::doEffect_path (Geom::PathVector const & path_in) e = s + M_PI_2; if (e > end) e = end; - len = 4*tan((e - s)/4)/3; + len = 4 * tan((e - s) / 4) / 3; x0 = cos(s); y0 = sin(s); x1 = x0 + len * cos(s + M_PI_2); @@ -185,11 +185,11 @@ LPEEllipse5Pts::doEffect_path (Geom::PathVector const & path_in) y3 = sin(e); x2 = x3 + len * cos(e - M_PI_2); y2 = y3 + len * sin(e - M_PI_2); - p.appendNew(Geom::Point(x1,y1), Geom::Point(x2,y2), Geom::Point(x3,y3)); + p.appendNew(Geom::Point(x1, y1), Geom::Point(x2, y2), Geom::Point(x3, y3)); } - + Geom::Affine aff = Geom::Scale(el.rays()) * Geom::Rotate(el.rotationAngle()) * Geom::Translate(el.center()); - + path_out.push_back(p * aff); return path_out; @@ -197,7 +197,7 @@ LPEEllipse5Pts::doEffect_path (Geom::PathVector const & path_in) /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-ellipse_5pts.h b/src/live_effects/lpe-ellipse_5pts.h index 843a9c41f96e92a0cc7147c1d021f01eb31ec60e..16f4619b49a19ee4552329339a782bf10eba61ca 100644 --- a/src/live_effects/lpe-ellipse_5pts.h +++ b/src/live_effects/lpe-ellipse_5pts.h @@ -22,20 +22,21 @@ namespace Inkscape { namespace LivePathEffect { -class LPEEllipse5Pts : public Effect { +class LPEEllipse5Pts : public Effect +{ public: LPEEllipse5Pts(LivePathEffectObject *lpeobject); ~LPEEllipse5Pts() override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; private: - LPEEllipse5Pts(const LPEEllipse5Pts&) = delete; - LPEEllipse5Pts& operator=(const LPEEllipse5Pts&) = delete; + LPEEllipse5Pts(const LPEEllipse5Pts &) = delete; + LPEEllipse5Pts &operator=(const LPEEllipse5Pts &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-embrodery-stitch-ordering.cpp b/src/live_effects/lpe-embrodery-stitch-ordering.cpp index ae22edf16d76dfd8e8ead59ed8df542a84ffb9d7..2261d36d1d6cdf5c1970d75cffdb7f8ef2f92510 100644 --- a/src/live_effects/lpe-embrodery-stitch-ordering.cpp +++ b/src/live_effects/lpe-embrodery-stitch-ordering.cpp @@ -30,14 +30,15 @@ using namespace Geom; #define DebugTraceTSP(list) // list // Combinations of above -#define DebugTrace1TSP(list) DebugTraceTSP( DebugTrace1(list) ) -#define DebugTrace2TSP(list) DebugTraceTSP( DebugTrace2(list) ) +#define DebugTrace1TSP(list) DebugTraceTSP(DebugTrace1(list)) +#define DebugTrace2TSP(list) DebugTraceTSP(DebugTrace2(list)) // ==================== Template Utilities ==================== // Delete all objects pointed to by a vector and clear the vector -template< typename T > void delete_and_clear(std::vector &vector) +template +void delete_and_clear(std::vector &vector) { for (typename std::vector::iterator it = vector.begin(); it != vector.end(); ++it) { delete *it; @@ -47,7 +48,8 @@ template< typename T > void delete_and_clear(std::vector &vector) // Assert that there are no duplicates in a vector -template< typename T > void assert_unique(std::vector &vector) +template +void assert_unique(std::vector &vector) { typename std::vector copy = vector; std::sort(copy.begin(), copy.end()); @@ -56,7 +58,8 @@ template< typename T > void assert_unique(std::vector &vector) // remove element(s) by value -template< typename T > void remove_by_value(std::vector *vector, const T &value) +template +void remove_by_value(std::vector *vector, const T &value) { vector->erase(std::remove(vector->begin(), vector->end(), value), vector->end()); } @@ -65,7 +68,7 @@ template< typename T > void remove_by_value(std::vector *vector, const T &val // iota is included in some C++ libraries, not in other (it is always included for C++11) // To avoid issues, use our own name (not iota) -template +template void fill_increasing(OutputIterator begin, OutputIterator end, Counter counter) { while (begin != end) { @@ -75,7 +78,7 @@ void fill_increasing(OutputIterator begin, OutputIterator end, Counter counter) // check if an iteratable sequence contains an element -template +template bool contains(InputIterator begin, InputIterator end, const Element &elem) { while (begin != end) { @@ -89,7 +92,7 @@ bool contains(InputIterator begin, InputIterator end, const Element &elem) // Check if a vector contains an element -template +template bool contains(std::vector const &vector, const Element &elem) { return contains(vector.begin(), vector.end(), elem); @@ -112,11 +115,12 @@ bool contains(std::vector const &vector, const Element &elem) // // If the number of elements is less then the number of dimensions, the number of dimensions is reduced automatically. // -// I thought about creating an iterator class for this, but it doesn't match that well, so I used functions on iterator vectors. +// I thought about creating an iterator class for this, but it doesn't match that well, so I used functions on iterator +// vectors. // Initialize a vector of iterators -template +template void triangleit_begin(std::vector &iterators, Iterator const &begin, Iterator const &end, size_t n) { iterators.clear(); @@ -133,7 +137,7 @@ void triangleit_begin(std::vector &iterators, Iterator const &begin, I // Increment a vector of iterators -template +template void triangleit_incr(std::vector &iterators, Iterator const &end) { size_t n = iterators.size(); @@ -153,7 +157,7 @@ void triangleit_incr(std::vector &iterators, Iterator const &end) // Check if a vector of iterators is at the end -template +template bool triangleit_test(std::vector &iterators, Iterator const &end) { if (iterators.empty()) { @@ -167,15 +171,13 @@ bool triangleit_test(std::vector &iterators, Iterator const &end) // Sub-path reordering: do nothing - keep original order -void OrderingOriginal(std::vector &infos) -{ -} +void OrderingOriginal(std::vector &infos) {} // Sub-path reordering: reverse every other sub path void OrderingZigZag(std::vector &infos, bool revfirst) { - for (auto & info : infos) { + for (auto &info : infos) { info.reverse = (info.index & 1) == (revfirst ? 0 : 1); } } @@ -193,7 +195,6 @@ void OrderingClosest(std::vector &infos, bool revfirst) infos[0].used = true; - for (unsigned int iRnd = 1; iRnd < infos.size(); iRnd++) { // find closest point to p unsigned iBest = 0; @@ -233,19 +234,23 @@ void OrderingClosest(std::vector &infos, bool revfirst) // ==================== Traveling Salesman k-opt Ordering Function and Utilities ==================== // A Few notes on this: -// - This is a relatively simple Lin-type k-opt algorithm, but the grouping optimizations done make it already quite complex. +// - This is a relatively simple Lin-type k-opt algorithm, but the grouping optimizations done make it already quite +// complex. // - The main Ordering Function is OrderingAdvanced // - Lines which start at the end of another line are connected and treated as one (struct OrderingInfoEx) -// - Groups of zig-zag OrderingInfoEx are grouped (struct OrderingGroup) if both ends of the segment mutually agree with a next neighbor. +// - Groups of zig-zag OrderingInfoEx are grouped (struct OrderingGroup) if both ends of the segment mutually agree with +// a next neighbor. // These groups are treated as a unit in the TSP algorithm. // The only option is to reverse the first segment, so that a group has 4 end points, 2 of which are used externally. // - Run a k-opt (k=2..5) Lin like Traveling Salesman Problem algorithm on the groups as a unit and the remaining edges. // See https://en.wikipedia.org/wiki/Travelling_salesman_problem#Iterative_improvement // The algorithm uses a greedy nearest neighbor as start configuration and does not use repeated random starts. -// - The algorithm searches an open tour (rather than a closed one), so the longest segment in the closed path is ignored. +// - The algorithm searches an open tour (rather than a closed one), so the longest segment in the closed path is +// ignored. // - TODO: it might be faster to use k=3 with a few random starting patterns instead of k=5 // - TODO: it is surely wiser to implement e.g. Lin-Kenrighan TSP, but the simple k-opt works ok. -// - TODO(EASY): add a jump distance, above which threads are removed and make the length of this jump distance constant and large, +// - TODO(EASY): add a jump distance, above which threads are removed and make the length of this jump distance constant +// and large, // so that mostly the number of jumps is optimized // Find 2 nearest points to given point @@ -315,17 +320,13 @@ void OrderingPoint::EnforceMutual() void OrderingPoint::EnforceSymmetric(const OrderingPoint &other) { - if (nearest[0] && !( - (other.nearest[0] && nearest[0]->infoex == other.nearest[0]->infoex) || - (other.nearest[1] && nearest[0]->infoex == other.nearest[1]->infoex) - )) { + if (nearest[0] && !((other.nearest[0] && nearest[0]->infoex == other.nearest[0]->infoex) || + (other.nearest[1] && nearest[0]->infoex == other.nearest[1]->infoex))) { nearest[0] = nullptr; } - if (nearest[1] && !( - (other.nearest[0] && nearest[1]->infoex == other.nearest[0]->infoex) || - (other.nearest[1] && nearest[1]->infoex == other.nearest[1]->infoex) - )) { + if (nearest[1] && !((other.nearest[0] && nearest[1]->infoex == other.nearest[0]->infoex) || + (other.nearest[1] && nearest[1]->infoex == other.nearest[1]->infoex))) { nearest[1] = nullptr; } @@ -342,10 +343,10 @@ void OrderingPoint::Dump() // Coord dist1 = nearest[1] ? distance(point, nearest[1]->point) : -1.0; // int idx0 = nearest[0] ? nearest[0]->infoex->idx : -1; // int idx1 = nearest[1] ? nearest[1]->infoex->idx : -1; - DebugTrace2(("I=%d X=%.5lf Y=%.5lf d1=%.3lf d2=%.3lf i1=%d i2=%d", infoex->idx, point.x(), 297.0 - point.y(), dist0, dist1, idx0, idx1)); + DebugTrace2(("I=%d X=%.5lf Y=%.5lf d1=%.3lf d2=%.3lf i1=%d i2=%d", infoex->idx, point.x(), 297.0 - point.y(), dist0, + dist1, idx0, idx1)); } - // If this element can be grouped (has neighbours) but is not yet grouped, create a new group void OrderingInfoEx::MakeGroup(std::vector &infos, std::vector *groups) @@ -387,11 +388,10 @@ void OrderingInfoEx::AddToGroup(std::vector &infos, OrderingGr // Constructor -OrderingGroupNeighbor::OrderingGroupNeighbor(OrderingGroupPoint *me, OrderingGroupPoint *other) : - point(other), - distance(Geom::distance(me->point, other->point)) -{ -} +OrderingGroupNeighbor::OrderingGroupNeighbor(OrderingGroupPoint *me, OrderingGroupPoint *other) + : point(other) + , distance(Geom::distance(me->point, other->point)) +{} // Comparison function for sorting by distance @@ -404,13 +404,13 @@ bool OrderingGroupNeighbor::Compare(const OrderingGroupNeighbor &a, const Orderi OrderingGroupNeighbor *OrderingGroupPoint::FindNearestUnused() { - for (auto & it : nearest) { + for (auto &it : nearest) { if (!it.point->used) { - DebugTrace1TSP(("Nearest: group %d, size %d, point %d, nghb %d, xFrom %.4lf, yFrom %.4lf, xTo %.4lf, yTo %.4lf, dist %.4lf", - it->point->group->index, it->point->group->items.size(), it->point->indexInGroup, it - nearest.begin(), - point.x(), 297 - point.y(), - it->point->point.x(), 297 - it->point->point.y(), - it->distance)); + DebugTrace1TSP(("Nearest: group %d, size %d, point %d, nghb %d, xFrom %.4lf, yFrom %.4lf, xTo %.4lf, yTo " + "%.4lf, dist %.4lf", + it->point->group->index, it->point->group->items.size(), it->point->indexInGroup, + it - nearest.begin(), point.x(), 297 - point.y(), it->point->point.x(), + 297 - it->point->point.y(), it->distance)); return ⁢ } } @@ -424,7 +424,7 @@ OrderingGroupNeighbor *OrderingGroupPoint::FindNearestUnused() OrderingGroupPoint *OrderingGroupPoint::GetOtherEndGroup() { - return group->endpoints[ indexInGroup ^ 1 ]; + return group->endpoints[indexInGroup ^ 1]; } // Return the alternate point (if one exists), 0 otherwise @@ -435,11 +435,10 @@ OrderingGroupPoint *OrderingGroupPoint::GetAltPointGroup() return nullptr; } - OrderingGroupPoint *alt = group->endpoints[ indexInGroup ^ 2 ]; + OrderingGroupPoint *alt = group->endpoints[indexInGroup ^ 2]; return alt->used ? nullptr : alt; } - // Sets the rev flags in the group assuming that the group starts with this point void OrderingGroupPoint::SetRevInGroup() @@ -471,13 +470,12 @@ void OrderingGroupPoint::UnusePoint() OrderingGroupPoint *OrderingGroupPoint::GetOtherEndConnection() { assert(connection); - assert(connection->points[ indexInConnection ] == this); - assert(connection->points[ indexInConnection ^ 1 ]); + assert(connection->points[indexInConnection] == this); + assert(connection->points[indexInConnection ^ 1]); - return connection->points[ indexInConnection ^ 1 ]; + return connection->points[indexInConnection ^ 1]; } - // Set the end points of a group from the items void OrderingGroup::SetEndpoints() @@ -490,7 +488,7 @@ void OrderingGroup::SetEndpoints() // b0-front--e1 nEndPoints = 2; - endpoints[0] = new OrderingGroupPoint(items.front()->beg.point, this, 0, true, true); + endpoints[0] = new OrderingGroupPoint(items.front()->beg.point, this, 0, true, true); endpoints[1] = new OrderingGroupPoint(items.front()->end.point, this, 1, false, true); } else { // If the number of elements is even, the group is @@ -532,10 +530,10 @@ void OrderingGroup::SetEndpoints() int cross = items.size() & 1 ? 2 : 0; nEndPoints = 4; - endpoints[0 ] = new OrderingGroupPoint(items.front()->beg.point, this, 0, true, true); - endpoints[1 ^ cross] = new OrderingGroupPoint(items.back() ->beg.point, this, 1 ^ cross, true, false); - endpoints[2 ] = new OrderingGroupPoint(items.front()->end.point, this, 2, false, true); - endpoints[3 ^ cross] = new OrderingGroupPoint(items.back() ->end.point, this, 3 ^ cross, false, false); + endpoints[0] = new OrderingGroupPoint(items.front()->beg.point, this, 0, true, true); + endpoints[1 ^ cross] = new OrderingGroupPoint(items.back()->beg.point, this, 1 ^ cross, true, false); + endpoints[2] = new OrderingGroupPoint(items.front()->end.point, this, 2, false, true); + endpoints[3 ^ cross] = new OrderingGroupPoint(items.back()->end.point, this, 3 ^ cross, false, false); } } @@ -588,7 +586,7 @@ void OrderingSegment::AddPoint(OrderingGroupPoint *point) { assert(point); assert(nEndPoints < 4); - endpoints[ nEndPoints++ ] = point; + endpoints[nEndPoints++] = point; // If both ends of a group are added and the group has 4 points, add the other two as well if (nEndPoints == 2 && endpoints[0]->group == endpoints[1]->group) { @@ -618,9 +616,9 @@ OrderingGroupPoint *OrderingSegment::GetEndPoint(unsigned int iSwap, unsigned in return endpoints[iPoint]; } - // Find the next unused point in list -std::vector::iterator FindUnusedAndUse(std::vector *unusedPoints, std::vector::iterator const from) +std::vector::iterator FindUnusedAndUse(std::vector *unusedPoints, + std::vector::iterator const from) { for (std::vector::iterator it = from; it != unusedPoints->end(); ++it) { if (!(*it)->used) { @@ -633,7 +631,9 @@ std::vector::iterator FindUnusedAndUse(std::vector &segments, std::vector &connections, std::vector &allconnections, OrderingGroupConnection **longestConnect, Coord *total, Coord olddist) +bool FindShortestReconnect(std::vector &segments, std::vector &connections, + std::vector &allconnections, + OrderingGroupConnection **longestConnect, Coord *total, Coord olddist) { // Find the longest connection outside of the active set // The longest segment is then the longest of this longest outside segment and all inside segments @@ -642,7 +642,7 @@ bool FindShortestReconnect(std::vector &segments, std::vectorDistance() > length) { if (!contains(connections, allconnection)) { longestOutside = allconnection; @@ -663,7 +663,7 @@ bool FindShortestReconnect(std::vector &segments, std::vector &segments, std::vectorpoint, prevend->point); lengthTotal += length; @@ -724,11 +724,13 @@ bool FindShortestReconnect(std::vector &segments, std::vectorgroup->index, thisbeg->indexInGroup, Geom::distance(thisbeg->point, prevend->point))); - DebugTrace2TSP(("IMP 0T=%d %d %.6lf", prevend->group->index, prevend->indexInGroup, Geom::distance(thisbeg->point, prevend->point))); + // OrderingGroupPoint *thisbeg = segments[it].GetBeginPoint(iSwap, iEnd); + DebugTrace2TSP(("IMP 0F=%d %d %.6lf", thisbeg->group->index, thisbeg->indexInGroup, + Geom::distance(thisbeg->point, prevend->point))); + DebugTrace2TSP(("IMP 0T=%d %d %.6lf", prevend->group->index, prevend->indexInGroup, + Geom::distance(thisbeg->point, prevend->point))); prevend = segments[it].GetEndPoint(iSwap, iEnd); } } @@ -748,44 +750,52 @@ bool FindShortestReconnect(std::vector &segments, std::vector::iterator it = connections.begin(); it != connections.end(); ++it) { - DebugTrace2TSP(("WAS 0F=%d %d %.6lf", (*it)->points[0]->group->index, (*it)->points[0]->indexInGroup, (*it)->Distance())); - DebugTrace2TSP(("WAS 0T=%d %d %.6lf", (*it)->points[1]->group->index, (*it)->points[1]->indexInGroup, (*it)->Distance())); + DebugTrace2TSP(("WAS 0F=%d %d %.6lf", (*it)->points[0]->group->index, (*it)->points[0]->indexInGroup, + (*it)->Distance())); + DebugTrace2TSP(("WAS 0T=%d %d %.6lf", (*it)->points[1]->group->index, (*it)->points[1]->indexInGroup, + (*it)->Distance())); } DebugTrace2TSP(("OLDDIST %.6lf delta %.6lf", olddist, olddist - (*longestConnect)->Distance())); - DebugTrace2TSP(("LONG =%d %d %.6lf", (*longestConnect)->points[0]->group->index, (*longestConnect)->points[0]->indexInGroup, (*longestConnect)->Distance())); - DebugTrace2TSP(("LONG =%d %d %.6lf", (*longestConnect)->points[1]->group->index, (*longestConnect)->points[1]->indexInGroup, (*longestConnect)->Distance())); + DebugTrace2TSP(("LONG =%d %d %.6lf", (*longestConnect)->points[0]->group->index, + (*longestConnect)->points[0]->indexInGroup, (*longestConnect)->Distance())); + DebugTrace2TSP(("LONG =%d %d %.6lf", (*longestConnect)->points[1]->group->index, + (*longestConnect)->points[1]->indexInGroup, (*longestConnect)->Distance())); int perm = permutationBest.back(); for (std::vector::iterator it = connections.begin(); it != connections.end(); ++it) { - (*it)->Connect(1, segments[ perm ].GetEndPoint(iSwapBest, iEndBest)); - perm = permutationBest[ it - connections.begin() ]; - (*it)->Connect(0, segments[ perm ].GetBeginPoint(iSwapBest, iEndBest)); - + (*it)->Connect(1, segments[perm].GetEndPoint(iSwapBest, iEndBest)); + perm = permutationBest[it - connections.begin()]; + (*it)->Connect(0, segments[perm].GetBeginPoint(iSwapBest, iEndBest)); } for (std::vector::iterator it = connections.begin(); it != connections.end(); ++it) { - DebugTrace2TSP(("IS 0F=%d %d %.6lf", (*it)->points[0]->group->index, (*it)->points[0]->indexInGroup, (*it)->Distance())); - DebugTrace2TSP(("IS 0T=%d %d %.6lf", (*it)->points[1]->group->index, (*it)->points[1]->indexInGroup, (*it)->Distance())); + DebugTrace2TSP(("IS 0F=%d %d %.6lf", (*it)->points[0]->group->index, (*it)->points[0]->indexInGroup, + (*it)->Distance())); + DebugTrace2TSP(("IS 0T=%d %d %.6lf", (*it)->points[1]->group->index, (*it)->points[1]->indexInGroup, + (*it)->Distance())); } (*longestConnect) = longestOutside; - for (auto & connection : connections) { + for (auto &connection : connections) { if (connection->Distance() > (*longestConnect)->Distance()) { *longestConnect = connection; } } - DebugTrace2TSP(("LONG =%d %d %.6lf", (*longestConnect)->points[0]->group->index, (*longestConnect)->points[0]->indexInGroup, (*longestConnect)->Distance())); - DebugTrace2TSP(("LONG =%d %d %.6lf", (*longestConnect)->points[1]->group->index, (*longestConnect)->points[1]->indexInGroup, (*longestConnect)->Distance())); + DebugTrace2TSP(("LONG =%d %d %.6lf", (*longestConnect)->points[0]->group->index, + (*longestConnect)->points[0]->indexInGroup, (*longestConnect)->Distance())); + DebugTrace2TSP(("LONG =%d %d %.6lf", (*longestConnect)->points[1]->group->index, + (*longestConnect)->points[1]->indexInGroup, (*longestConnect)->Distance())); } return improved; } // Check if connections form a tour -void AssertIsTour(std::vector &groups, std::vector &connections, OrderingGroupConnection *longestConnection) +void AssertIsTour(std::vector &groups, std::vector &connections, + OrderingGroupConnection *longestConnection) { - for (auto & connection : connections) { + for (auto &connection : connections) { for (auto pnt : connection->points) { assert(pnt->connection == connection); assert(pnt->connection->points[pnt->indexInConnection] == pnt); @@ -798,16 +808,26 @@ void AssertIsTour(std::vector &groups, std::vectorpoints[0]; for (unsigned int n = 0; n < connections.size(); n++) { - DebugTrace2TSP(("Tour test 1 %p g=%d/%d c=%d/%d %p %p %.6lf %.3lf %.3lf %d %d %d", current, current->group->index, current->indexInGroup, current->connection->index, current->indexInConnection, current->connection->points[0], current->connection->points[1], current->connection->Distance(), current->point.x(), 297 - current->point.y(), current->begin, current->front, current->group->items.size())); + DebugTrace2TSP(("Tour test 1 %p g=%d/%d c=%d/%d %p %p %.6lf %.3lf %.3lf %d %d %d", current, + current->group->index, current->indexInGroup, current->connection->index, + current->indexInConnection, current->connection->points[0], current->connection->points[1], + current->connection->Distance(), current->point.x(), 297 - current->point.y(), current->begin, + current->front, current->group->items.size())); Coord length = current->connection->Distance(); length1 += length; longest1 = std::max(length, longest1); current = current->GetOtherEndConnection(); - DebugTrace2TSP(("Tour test 2 %p g=%d/%d c=%d/%d %p %p %.6lf %.3lf %.3lf %d %d %d", current, current->group->index, current->indexInGroup, current->connection->index, current->indexInConnection, current->connection->points[0], current->connection->points[1], current->connection->Distance(), current->point.x(), 297 - current->point.y(), current->begin, current->front, current->group->items.size())); + DebugTrace2TSP(("Tour test 2 %p g=%d/%d c=%d/%d %p %p %.6lf %.3lf %.3lf %d %d %d", current, + current->group->index, current->indexInGroup, current->connection->index, + current->indexInConnection, current->connection->points[0], current->connection->points[1], + current->connection->Distance(), current->point.x(), 297 - current->point.y(), current->begin, + current->front, current->group->items.size())); current = current->GetOtherEndGroup(); } - DebugTrace2TSP(("Tour test 3 %p g=%d/%d c=%d/%d %p %p", current, current->group->index, current->indexInGroup, current->connection->index, current->indexInConnection, current->connection->points[0], current->connection->points[1])); + DebugTrace2TSP(("Tour test 3 %p g=%d/%d c=%d/%d %p %p", current, current->group->index, current->indexInGroup, + current->connection->index, current->indexInConnection, current->connection->points[0], + current->connection->points[1])); assert(current == connections.front()->points[0]); // The other direction @@ -823,15 +843,18 @@ void AssertIsTour(std::vector &groups, std::vectorpoints[0]); - DebugTrace1TSP(("Tour length %.6lf(%.6lf) longest %.6lf(%.6lf) remaining %.6lf(%.6lf)", length1, length2, longest1, longest2, length1 - longest1, length2 - longest2)); + DebugTrace1TSP(("Tour length %.6lf(%.6lf) longest %.6lf(%.6lf) remaining %.6lf(%.6lf)", length1, length2, longest1, + longest2, length1 - longest1, length2 - longest2)); } // Bring a tour into linear order after a modification /* I would like to avoid this. * It is no problem to travel a tour with changing directions using the GetOtherEnd functions, - * but it is difficult to know the segments, that is which endpoint of a connection is connected to which by the unmodified pieces of the tour. - * In the end it is probably better to implement the Lin-Kernighan algorithm which avoids this problem by creating connected changes. */ + * but it is difficult to know the segments, that is which endpoint of a connection is connected to which by the + * unmodified pieces of the tour. + * In the end it is probably better to implement the Lin-Kernighan algorithm which avoids this problem by creating + * connected changes. */ void LinearizeTour(std::vector &connections) { @@ -873,7 +896,7 @@ void OrderGroups(std::vector *groups, const int nDims) } // Initialize the endpoints for all groups - for (auto & group : *groups) { + for (auto &group : *groups) { group->SetEndpoints(); } @@ -891,7 +914,8 @@ void OrderGroups(std::vector *groups, const int nDims) } for (int i = 0; i < (*itThis)->nEndPoints; i++) { - std::sort((*itThis)->endpoints[i]->nearest.begin(), (*itThis)->endpoints[i]->nearest.end(), OrderingGroupNeighbor::Compare); + std::sort((*itThis)->endpoints[i]->nearest.begin(), (*itThis)->endpoints[i]->nearest.end(), + OrderingGroupNeighbor::Compare); } } @@ -946,15 +970,12 @@ void OrderGroups(std::vector *groups, const int nDims) do { improvement = false; - nRuns ++; - std::vector< std::vector::iterator > iterators; + nRuns++; + std::vector::iterator> iterators; - for ( - triangleit_begin(iterators, connections.begin(), connections.end(), nDims); - triangleit_test(iterators, connections.end()); - triangleit_incr(iterators, connections.end()) - ) { - nTrials ++; + for (triangleit_begin(iterators, connections.begin(), connections.end(), nDims); + triangleit_test(iterators, connections.end()); triangleit_incr(iterators, connections.end())) { + nTrials++; Coord dist = 0; @@ -963,7 +984,6 @@ void OrderGroups(std::vector *groups, const int nDims) changedconnections.reserve(3); OrderingGroupConnection *prev = *iterators.back(); - for (size_t i = 0; i < iterators.size(); i++) { dist += (*iterators[i])->Distance(); segments[i].AddPoint(prev->points[1]); @@ -973,7 +993,7 @@ void OrderGroups(std::vector *groups, const int nDims) } if (FindShortestReconnect(segments, changedconnections, connections, &longestConnect, &total, dist)) { - nImprovements ++; + nImprovements++; AssertIsTour(*groups, connections, longestConnect); LinearizeTour(connections); @@ -1040,44 +1060,41 @@ void OrderingAdvanced(std::vector &infos, int nDims) (*it)->end.FindNearest2(infoex); } - DebugTraceGrouping( - DebugTrace2(("STEP1")); - for (std::vector::iterator it = infoex.begin(); it != infoex.end(); ++it) { - (*it)->beg.Dump(); - (*it)->end.Dump(); - } - ) + DebugTraceGrouping(DebugTrace2(("STEP1")); + for (std::vector::iterator it = infoex.begin(); it != infoex.end(); ++it) { + (*it)->beg.Dump(); + (*it)->end.Dump(); + }) - // Make sure the nearest points are mutual - for (auto & it : infoex) { + // Make sure the nearest points are mutual + for (auto &it : infoex) + { it->beg.EnforceMutual(); it->end.EnforceMutual(); } - DebugTraceGrouping( - DebugTrace2(("STEP2")); - for (std::vector::iterator it = infoex.begin(); it != infoex.end(); ++it) { - (*it)->beg.Dump(); - (*it)->end.Dump(); - } - ) + DebugTraceGrouping(DebugTrace2(("STEP2")); + for (std::vector::iterator it = infoex.begin(); it != infoex.end(); ++it) { + (*it)->beg.Dump(); + (*it)->end.Dump(); + }) - // Make sure the nearest points for begin and end lead to the same sub-path (same index) - for (auto & it : infoex) { + // Make sure the nearest points for begin and end lead to the same sub-path (same index) + for (auto &it : infoex) + { it->beg.EnforceSymmetric(it->end); it->end.EnforceSymmetric(it->beg); } - DebugTraceGrouping( - DebugTrace2(("STEP3")); - for (std::vector::iterator it = infoex.begin(); it != infoex.end(); ++it) { - (*it)->beg.Dump(); - (*it)->end.Dump(); - } - ) + DebugTraceGrouping(DebugTrace2(("STEP3")); + for (std::vector::iterator it = infoex.begin(); it != infoex.end(); ++it) { + (*it)->beg.Dump(); + (*it)->end.Dump(); + }) - // The remaining nearest neighbors should be 100% non ambiguous, so group them - std::vector groups; + // The remaining nearest neighbors should be 100% non ambiguous, so group them + std::vector + groups; for (std::vector::iterator it = infoex.begin(); it != infoex.end(); ++it) { (*it)->MakeGroup(infoex, &groups); } @@ -1086,7 +1103,7 @@ void OrderingAdvanced(std::vector &infos, int nDims) std::vector result; result.reserve(infos.size()); int nUngrouped = 0; - for (auto & it : infoex) { + for (auto &it : infoex) { if (!it->grouped) { groups.push_back(new OrderingGroup(groups.size())); groups.back()->items.push_back(it); @@ -1094,19 +1111,16 @@ void OrderingAdvanced(std::vector &infos, int nDims) } } - DebugTraceGrouping( - DebugTrace2(("Ungrouped lines = %d", nUngrouped)); - DebugTrace2(("%d Groups found", groups.size())); - for (std::vector::iterator it = groups.begin(); it != groups.end(); ++it) { - DebugTrace2(("Group size %d", (*it)->items.size())); - } - ) + DebugTraceGrouping(DebugTrace2(("Ungrouped lines = %d", nUngrouped)); + DebugTrace2(("%d Groups found", groups.size())); + for (std::vector::iterator it = groups.begin(); it != groups.end(); + ++it) { DebugTrace2(("Group size %d", (*it)->items.size())); }) - // Order groups, so that the connection path gets shortest - OrderGroups(&groups, nDims); + // Order groups, so that the connection path gets shortest + OrderGroups(&groups, nDims); // Copy grouped lines to output - for (auto & group : groups) { + for (auto &group : groups) { for (unsigned int iItem = 0; iItem < group->items.size(); iItem++) { unsigned int iItemRev = group->revItemList ? group->items.size() - 1 - iItem : iItem; OrderingInfoEx *item = group->items[iItemRev]; @@ -1115,12 +1129,13 @@ void OrderingAdvanced(std::vector &infos, int nDims) // In this case ( ( iItem & 1 ) == 0 )== true, revItems=false, (true==false) == false bool reverse = ((iItem & 1) == 0) == group->revItems; if (!reverse) { - for (int & origIndice : item->origIndices) { + for (int &origIndice : item->origIndices) { result.push_back(infos[origIndice]); result.back().reverse = false; } } else { - for (std::vector::reverse_iterator itOrig = item->origIndices.rbegin(); itOrig != item->origIndices.rend(); ++itOrig) { + for (std::vector::reverse_iterator itOrig = item->origIndices.rbegin(); + itOrig != item->origIndices.rend(); ++itOrig) { result.push_back(infos[*itOrig]); result.back().reverse = true; } @@ -1129,7 +1144,6 @@ void OrderingAdvanced(std::vector &infos, int nDims) result.back().connect = true; } - delete_and_clear(groups); delete_and_clear(infoex); diff --git a/src/live_effects/lpe-embrodery-stitch-ordering.h b/src/live_effects/lpe-embrodery-stitch-ordering.h index 9899f667825b2f17daf4365437624f3cf579fc17..456149cdd0006eeebe38537fa823e1ce7cc697d2 100644 --- a/src/live_effects/lpe-embrodery-stitch-ordering.h +++ b/src/live_effects/lpe-embrodery-stitch-ordering.h @@ -19,30 +19,19 @@ namespace LPEEmbroderyStitchOrdering { // Structure keeping information on the ordering and reversing of sub paths // Used for simple ordering functions like zig-zag -struct OrderingInfo { - int index; - bool reverse; - bool used; - bool connect; +struct OrderingInfo +{ + int index; + bool reverse; + bool used; + bool connect; Geom::Point begOrig; // begin point in original orientation Geom::Point endOrig; // end point in original orientation - Geom::Point GetBegOrig() const - { - return begOrig; - } - Geom::Point GetEndOrig() const - { - return endOrig; - } - Geom::Point GetBegRev() const - { - return reverse ? endOrig : begOrig; - } - Geom::Point GetEndRev() const - { - return reverse ? begOrig : endOrig; - } + Geom::Point GetBegOrig() const { return begOrig; } + Geom::Point GetEndOrig() const { return endOrig; } + Geom::Point GetBegRev() const { return reverse ? endOrig : begOrig; } + Geom::Point GetEndRev() const { return reverse ? begOrig : endOrig; } }; // Structure for a path end-point in OrderingInfoEx. @@ -50,25 +39,20 @@ struct OrderingInfo { struct OrderingInfoEx; -struct OrderingPoint { - OrderingPoint(const Geom::Point &pointIn, OrderingInfoEx *infoexIn, bool beginIn) : - point(pointIn), - infoex(infoexIn), - begin(beginIn) +struct OrderingPoint +{ + OrderingPoint(const Geom::Point &pointIn, OrderingInfoEx *infoexIn, bool beginIn) + : point(pointIn) + , infoex(infoexIn) + , begin(beginIn) { nearest[0] = nearest[1] = nullptr; } // Check if both nearest values are valid - bool IsNearestValid() const - { - return nearest[0] && nearest[1]; - } + bool IsNearestValid() const { return nearest[0] && nearest[1]; } // Check if at least one nearest values are valid - bool HasNearest() const - { - return nearest[0] || nearest[1]; - } + bool HasNearest() const { return nearest[0] || nearest[1]; } // Find 2 nearest points to given point void FindNearest2(const std::vector &infos); // Check if "this" is among the nearest of its nearest @@ -80,7 +64,7 @@ struct OrderingPoint { Geom::Point point; OrderingInfoEx *infoex; - bool begin; + bool begin; const OrderingPoint *nearest[2]; }; @@ -91,12 +75,13 @@ struct OrderingPoint { struct OrderingGroup; -struct OrderingInfoEx { - OrderingInfoEx(const OrderingInfo &infoIn, int idxIn) : - beg(infoIn.begOrig, this, true), - end(infoIn.endOrig, this, false), - idx(idxIn), - grouped(false) +struct OrderingInfoEx +{ + OrderingInfoEx(const OrderingInfo &infoIn, int idxIn) + : beg(infoIn.begOrig, this, true) + , end(infoIn.endOrig, this, false) + , idx(idxIn) + , grouped(false) { origIndices.push_back(infoIn.index); } @@ -107,9 +92,9 @@ struct OrderingInfoEx { void AddToGroup(std::vector &infos, OrderingGroup *group); int idx; - bool grouped; // true if this element has been grouped - OrderingPoint beg; // begin point in original orientation - OrderingPoint end; // end point in original orientation + bool grouped; // true if this element has been grouped + OrderingPoint beg; // begin point in original orientation + OrderingPoint end; // end point in original orientation std::vector origIndices; // Indices of the original OrderInfos (more than 1 if directly connected }; @@ -117,7 +102,8 @@ struct OrderingInfoEx { struct OrderingGroupPoint; -struct OrderingGroupNeighbor { +struct OrderingGroupNeighbor +{ OrderingGroupNeighbor(OrderingGroupPoint *me, OrderingGroupPoint *other); // Distance from owner of this neighbor info @@ -133,18 +119,18 @@ struct OrderingGroupNeighbor { struct OrderingGroupConnection; -struct OrderingGroupPoint { - OrderingGroupPoint(const Geom::Point &pointIn, OrderingGroup *groupIn, int indexIn, bool beginIn, bool frontIn) : - point(pointIn), - group(groupIn), - indexInGroup(indexIn), - connection(nullptr), - indexInConnection(0), - begin(beginIn), - front(frontIn), - used(false) - { - } +struct OrderingGroupPoint +{ + OrderingGroupPoint(const Geom::Point &pointIn, OrderingGroup *groupIn, int indexIn, bool beginIn, bool frontIn) + : point(pointIn) + , group(groupIn) + , indexInGroup(indexIn) + , connection(nullptr) + , indexInConnection(0) + , begin(beginIn) + , front(frontIn) + , used(false) + {} // Find the nearest unused neighbor point OrderingGroupNeighbor *FindNearestUnused(); @@ -184,9 +170,10 @@ struct OrderingGroupPoint { }; // A connection between two points/groups -struct OrderingGroupConnection { - OrderingGroupConnection(OrderingGroupPoint *fromIn, OrderingGroupPoint *toIn, int indexIn) : - index(indexIn) +struct OrderingGroupConnection +{ + OrderingGroupConnection(OrderingGroupPoint *fromIn, OrderingGroupPoint *toIn, int indexIn) + : index(indexIn) { assert(fromIn->connection == 0); assert(toIn->connection == 0); @@ -206,10 +193,7 @@ struct OrderingGroupConnection { } // Get length of connection - Geom::Coord Distance() - { - return Geom::distance(points[0]->point, points[1]->point); - } + Geom::Coord Distance() { return Geom::distance(points[0]->point, points[1]->point); } OrderingGroupPoint *points[2]; // index of connection in the connections vector (just for debugging) @@ -220,14 +204,15 @@ struct OrderingGroupConnection { // A block can have two sets of endpoints. // If a block has 2 sets of endpoints, one can swap between the two sets. -struct OrderingGroup { - OrderingGroup(int indexIn) : - nEndPoints(0), - revItemList(false), - revItems(false), - index(indexIn) +struct OrderingGroup +{ + OrderingGroup(int indexIn) + : nEndPoints(0) + , revItemList(false) + , revItems(false) + , index(indexIn) { - for (auto & endpoint : endpoints) { + for (auto &endpoint : endpoints) { endpoint = nullptr; } } @@ -270,11 +255,12 @@ struct OrderingGroup { // If a segment is just one ordering group, it has the same number of end points as the ordering group // A main difference between a segment and a group is that the segment does not own the end points. -struct OrderingSegment { - OrderingSegment() : - nEndPoints(0), - endbit(0), - swapbit(0) +struct OrderingSegment +{ + OrderingSegment() + : nEndPoints(0) + , endbit(0) + , swapbit(0) {} // Add an end point @@ -294,7 +280,6 @@ struct OrderingSegment { int swapbit; }; - // Sub-path reordering: do nothing - keep original order void OrderingOriginal(std::vector &infos); @@ -307,8 +292,8 @@ void OrderingClosest(std::vector &infos, bool revfirst); // Global optimization of path length void OrderingAdvanced(std::vector &infos, int nDims); -} //LPEEmbroderyStitchOrdering -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LPEEmbroderyStitchOrdering +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-embrodery-stitch.cpp b/src/live_effects/lpe-embrodery-stitch.cpp index 0ba506053b64e694f5e6228d32713cd7a31bb8da..b28f47bca516f796c6c74f0599f22b53e7a97c6d 100644 --- a/src/live_effects/lpe-embrodery-stitch.cpp +++ b/src/live_effects/lpe-embrodery-stitch.cpp @@ -7,18 +7,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/scalar.h" -#include - #include "live_effects/lpe-embrodery-stitch.h" -#include "live_effects/lpe-embrodery-stitch-ordering.h" +#include <2geom/bezier-to-sbasis.h> #include <2geom/path.h> #include <2geom/piecewise.h> -#include <2geom/sbasis.h> #include <2geom/sbasis-geometric.h> -#include <2geom/bezier-to-sbasis.h> #include <2geom/sbasis-to-bezier.h> +#include <2geom/sbasis.h> +#include + +#include "live_effects/lpe-embrodery-stitch-ordering.h" +#include "ui/widget/scalar.h" namespace Inkscape { namespace LivePathEffect { @@ -26,8 +26,9 @@ namespace LivePathEffect { using namespace Geom; using namespace LPEEmbroderyStitchOrdering; -static const Util::EnumData OrderMethodData[LPEEmbroderyStitch::order_method_count] = { - // clang-format off +static const Util::EnumData OrderMethodData[LPEEmbroderyStitch::order_method_count] = + { + // clang-format off { LPEEmbroderyStitch::order_method_no_reorder, N_("no reordering"), "no-reorder" }, { LPEEmbroderyStitch::order_method_zigzag, N_("zig-zag"), "zig-zag" }, { LPEEmbroderyStitch::order_method_zigzag_rev_first, N_("zig-zag, reverse first"), "zig-zag-rev-first" }, @@ -37,32 +38,41 @@ static const Util::EnumData OrderMethodData[LP { LPEEmbroderyStitch::order_method_tsp_kopt_3, N_("traveling salesman 3-opt (fast, ok)"), "tsp-3opt" }, { LPEEmbroderyStitch::order_method_tsp_kopt_4, N_("traveling salesman 4-opt (seconds)"), "tsp-4opt" }, { LPEEmbroderyStitch::order_method_tsp_kopt_5, N_("traveling salesman 5-opt (minutes)"), "tsp-5opt" } - // clang-format on + // clang-format on }; static const Util::EnumDataConverter -OrderMethodConverter(OrderMethodData, sizeof(OrderMethodData) / sizeof(*OrderMethodData)); + OrderMethodConverter(OrderMethodData, sizeof(OrderMethodData) / sizeof(*OrderMethodData)); -static const Util::EnumData ConnectMethodData[LPEEmbroderyStitch::connect_method_count] = { - { LPEEmbroderyStitch::connect_method_line, N_("straight line"), "line" }, - { LPEEmbroderyStitch::connect_method_move_point_from, N_("move to begin"), "move-begin" }, - { LPEEmbroderyStitch::connect_method_move_point_mid, N_("move to middle"), "move-middle" }, - { LPEEmbroderyStitch::connect_method_move_point_to, N_("move to end"), "move-end" } -}; +static const Util::EnumData + ConnectMethodData[LPEEmbroderyStitch::connect_method_count] = { + {LPEEmbroderyStitch::connect_method_line, N_("straight line"), "line"}, + {LPEEmbroderyStitch::connect_method_move_point_from, N_("move to begin"), "move-begin"}, + {LPEEmbroderyStitch::connect_method_move_point_mid, N_("move to middle"), "move-middle"}, + {LPEEmbroderyStitch::connect_method_move_point_to, N_("move to end"), "move-end"}}; static const Util::EnumDataConverter -ConnectMethodConverter(ConnectMethodData, sizeof(ConnectMethodData) / sizeof(*ConnectMethodData)); - -LPEEmbroderyStitch::LPEEmbroderyStitch(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - ordering(_("Ordering method"), _("Method used to order sub paths"), "ordering", OrderMethodConverter, &wr, this, order_method_no_reorder), - connection(_("Connection method"), _("Method to connect end points of sub paths"), "connection", ConnectMethodConverter, &wr, this, connect_method_line), - stitch_length(_("Stitch length"), _("Divide path into straight segments of given length (in user units)"), "stitch-length", &wr, this, 10.0), - stitch_min_length(_("Minimum stitch length [%]"), _("Merge stitches that are shorter than this percentage of the stitch length"), "stitch-min-length", &wr, this, 25.0), - stitch_pattern(_("Stitch pattern"), _("Select between different stitch patterns"), "stitch_pattern", &wr, this, 0), - show_stitches(_("Show stitches"), _("Creates gaps between stitches (use only for preview, deactivate for use with embroidery machines)"), "show-stitches", &wr, this, false), - show_stitch_gap(_("Show stitch gap"), _("Length of the gap between stitches when showing stitches"), "show-stitch-gap", &wr, this, 0.5), - jump_if_longer(_("Jump if longer"), _("Jump connection if longer than"), "jump-if-longer", &wr, this, 100) + ConnectMethodConverter(ConnectMethodData, sizeof(ConnectMethodData) / sizeof(*ConnectMethodData)); + +LPEEmbroderyStitch::LPEEmbroderyStitch(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , ordering(_("Ordering method"), _("Method used to order sub paths"), "ordering", OrderMethodConverter, &wr, this, + order_method_no_reorder) + , connection(_("Connection method"), _("Method to connect end points of sub paths"), "connection", + ConnectMethodConverter, &wr, this, connect_method_line) + , stitch_length(_("Stitch length"), _("Divide path into straight segments of given length (in user units)"), + "stitch-length", &wr, this, 10.0) + , stitch_min_length(_("Minimum stitch length [%]"), + _("Merge stitches that are shorter than this percentage of the stitch length"), + "stitch-min-length", &wr, this, 25.0) + , stitch_pattern(_("Stitch pattern"), _("Select between different stitch patterns"), "stitch_pattern", &wr, this, 0) + , show_stitches( + _("Show stitches"), + _("Creates gaps between stitches (use only for preview, deactivate for use with embroidery machines)"), + "show-stitches", &wr, this, false) + , show_stitch_gap(_("Show stitch gap"), _("Length of the gap between stitches when showing stitches"), + "show-stitch-gap", &wr, this, 0.5) + , jump_if_longer(_("Jump if longer"), _("Jump connection if longer than"), "jump-if-longer", &wr, this, 100) { registerParameter(dynamic_cast(&ordering)); registerParameter(dynamic_cast(&connection)); @@ -83,45 +93,43 @@ LPEEmbroderyStitch::LPEEmbroderyStitch(LivePathEffectObject *lpeobject) : jump_if_longer.param_set_range(0.0, 1000000); } -LPEEmbroderyStitch::~LPEEmbroderyStitch() -= default; +LPEEmbroderyStitch::~LPEEmbroderyStitch() = default; double LPEEmbroderyStitch::GetPatternInitialStep(int pattern, int line) { switch (pattern) { - case 0: - return 0.0; - - case 1: - switch (line % 4) { case 0: return 0.0; - case 1: - return 0.25; - case 2: - return 0.50; - case 3: - return 0.75; - } - return 0.0; - case 2: - switch (line % 4) { - case 0: - return 0.0; case 1: - return 0.5; + switch (line % 4) { + case 0: + return 0.0; + case 1: + return 0.25; + case 2: + return 0.50; + case 3: + return 0.75; + } + return 0.0; + case 2: - return 0.75; - case 3: - return 0.25; - } - return 0.0; + switch (line % 4) { + case 0: + return 0.0; + case 1: + return 0.5; + case 2: + return 0.75; + case 3: + return 0.25; + } + return 0.0; - default: - return 0.0; + default: + return 0.0; } - } Point LPEEmbroderyStitch::GetStartPointInterpolAfterRev(std::vector const &info, unsigned i) @@ -139,16 +147,16 @@ Point LPEEmbroderyStitch::GetStartPointInterpolAfterRev(std::vector const &info, unsigned i) @@ -166,16 +174,16 @@ Point LPEEmbroderyStitch::GetEndPointInterpolAfterRev(std::vector Point start_next = info[i + 1].GetBegRev(); switch (connection.get_value()) { - case connect_method_line: - return end_this; - case connect_method_move_point_from: - return end_this; - case connect_method_move_point_mid: - return 0.5 * start_next + 0.5 * end_this; - case connect_method_move_point_to: - return start_next; - default: - return end_this; + case connect_method_line: + return end_this; + case connect_method_move_point_from: + return end_this; + case connect_method_move_point_mid: + return 0.5 * start_next + 0.5 * end_this; + case connect_method_move_point_to: + return start_next; + default: + return end_this; } } @@ -208,7 +216,7 @@ PathVector LPEEmbroderyStitch::doEffect_path(PathVector const &path_in) bool connect_with_previous = false; for (PathVector::const_iterator it = path_in.begin(); it != path_in.end(); ++it) { - OrderingInfo &info = orderinginfos[ it - path_in.begin() ]; + OrderingInfo &info = orderinginfos[it - path_in.begin()]; info.index = it - path_in.begin(); info.reverse = false; info.used = false; @@ -219,42 +227,41 @@ PathVector LPEEmbroderyStitch::doEffect_path(PathVector const &path_in) // Compute sub-path ordering switch (ordering.get_value()) { - case order_method_no_reorder: - OrderingOriginal(orderinginfos); - break; - - case order_method_zigzag: - OrderingZigZag(orderinginfos, false); - break; + case order_method_no_reorder: + OrderingOriginal(orderinginfos); + break; - case order_method_zigzag_rev_first: - OrderingZigZag(orderinginfos, true); - break; + case order_method_zigzag: + OrderingZigZag(orderinginfos, false); + break; - case order_method_closest: - OrderingClosest(orderinginfos, false); - break; + case order_method_zigzag_rev_first: + OrderingZigZag(orderinginfos, true); + break; - case order_method_closest_rev_first: - OrderingClosest(orderinginfos, true); - break; + case order_method_closest: + OrderingClosest(orderinginfos, false); + break; - case order_method_tsp_kopt_2: - OrderingAdvanced(orderinginfos, 2); - break; + case order_method_closest_rev_first: + OrderingClosest(orderinginfos, true); + break; - case order_method_tsp_kopt_3: - OrderingAdvanced(orderinginfos, 3); - break; + case order_method_tsp_kopt_2: + OrderingAdvanced(orderinginfos, 2); + break; - case order_method_tsp_kopt_4: - OrderingAdvanced(orderinginfos, 4); - break; + case order_method_tsp_kopt_3: + OrderingAdvanced(orderinginfos, 3); + break; - case order_method_tsp_kopt_5: - OrderingAdvanced(orderinginfos, 5); - break; + case order_method_tsp_kopt_4: + OrderingAdvanced(orderinginfos, 4); + break; + case order_method_tsp_kopt_5: + OrderingAdvanced(orderinginfos, 5); + break; } // Iterate over sub-paths in order found above @@ -271,10 +278,10 @@ PathVector LPEEmbroderyStitch::doEffect_path(PathVector const &path_in) double stitch_min_length_abs = stitch_min_length * 0.01 * stitch_length; // convert path to piecewise - Piecewise > pwOrig = path_in[iPath].toPwSb(); + Piecewise> pwOrig = path_in[iPath].toPwSb(); // make piecewise equidistant in time - Piecewise > pwEqdist = arc_length_parametrization(pwOrig); - Piecewise > pwStitch; + Piecewise> pwEqdist = arc_length_parametrization(pwOrig); + Piecewise> pwStitch; // cut into stitches double cutpos = 0.0; @@ -296,7 +303,7 @@ PathVector LPEEmbroderyStitch::doEffect_path(PathVector const &path_in) p1 = GetStartPointInterpolBeforeRev(orderinginfos, iInfo); first = false; } else { - p1 = pwEqdist.valueAt(pos); + p1 = pwEqdist.valueAt(pos); } // end point of this stitch @@ -329,21 +336,22 @@ PathVector LPEEmbroderyStitch::doEffect_path(PathVector const &path_in) // connect end and start point if (end != start_next && distance(end, start_next) <= jump_if_longer) { cutpos += 1.0; - pwStitch.push_seg(D2(SBasis(Linear(end[X], start_next[X])), SBasis(Linear(end[Y], start_next[Y])))); + pwStitch.push_seg( + D2(SBasis(Linear(end[X], start_next[X])), SBasis(Linear(end[Y], start_next[Y])))); pwStitch.push_cut(cutpos); } } if (show_stitches) { - for (auto & seg : pwStitch.segs) { + for (auto &seg : pwStitch.segs) { // Create anew piecewise with just one segment - Piecewise > pwOne; + Piecewise> pwOne; pwOne.push_cut(0); pwOne.push_seg(seg); pwOne.push_cut(1); // make piecewise equidistant in time - Piecewise > pwOneEqdist = arc_length_parametrization(pwOne); + Piecewise> pwOneEqdist = arc_length_parametrization(pwOne); Interval pwdomain = pwOneEqdist.domain(); // Compute the points of the shortened piece @@ -351,18 +359,18 @@ PathVector LPEEmbroderyStitch::doEffect_path(PathVector const &path_in) Coord offs = 0.5 * (show_stitch_gap < 0.5 * len ? show_stitch_gap : 0.5 * len); Point p1 = pwOneEqdist.valueAt(pwdomain.min() + offs); Point p2 = pwOneEqdist.valueAt(pwdomain.max() - offs); - Piecewise > pwOneGap; + Piecewise> pwOneGap; // Create Linear SBasis D2 sbasis = D2(SBasis(Linear(p1[X], p2[X])), SBasis(Linear(p1[Y], p2[Y]))); // Convert to path and add to path list - Geom::Path path = path_from_sbasis(sbasis , LPE_CONVERSION_TOLERANCE, false); + Geom::Path path = path_from_sbasis(sbasis, LPE_CONVERSION_TOLERANCE, false); path_out.push_back(path); } } else { PathVector pathv = path_from_piecewise(pwStitch, LPE_CONVERSION_TOLERANCE); - for (const auto & ipv : pathv) { + for (const auto &ipv : pathv) { if (connect_with_previous) { path_out.back().append(ipv); } else { @@ -380,11 +388,10 @@ PathVector LPEEmbroderyStitch::doEffect_path(PathVector const &path_in) } } -void -LPEEmbroderyStitch::resetDefaults(SPItem const *item) +void LPEEmbroderyStitch::resetDefaults(SPItem const *item) { Effect::resetDefaults(item); } -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ diff --git a/src/live_effects/lpe-embrodery-stitch.h b/src/live_effects/lpe-embrodery-stitch.h index 6bbd931a5d4fb21fd8f05760bded971023dd5176..d9948b5c4f24756c1aa0345cc51016cb4d8e0a3c 100644 --- a/src/live_effects/lpe-embrodery-stitch.h +++ b/src/live_effects/lpe-embrodery-stitch.h @@ -11,19 +11,19 @@ #define INKSCAPE_LPE_EMBRODERY_STITCH_H #include "live_effects/effect.h" -#include "live_effects/parameter/parameter.h" +#include "live_effects/lpe-embrodery-stitch-ordering.h" #include "live_effects/parameter/bool.h" #include "live_effects/parameter/enum.h" -#include "live_effects/lpe-embrodery-stitch-ordering.h" +#include "live_effects/parameter/parameter.h" namespace Inkscape { namespace LivePathEffect { using namespace LPEEmbroderyStitchOrdering; -class LPEEmbroderyStitch : public Effect { +class LPEEmbroderyStitch : public Effect +{ public: - LPEEmbroderyStitch(LivePathEffectObject *lpeobject); ~LPEEmbroderyStitch() override; @@ -31,7 +31,8 @@ public: void resetDefaults(SPItem const *item) override; - enum order_method { + enum order_method + { order_method_no_reorder, order_method_zigzag, order_method_zigzag_rev_first, @@ -43,7 +44,8 @@ public: order_method_tsp_kopt_5, order_method_count }; - enum connect_method { + enum connect_method + { connect_method_line, connect_method_move_point_from, connect_method_move_point_mid, @@ -71,7 +73,7 @@ private: Geom::Point GetEndPointInterpolBeforeRev(std::vector const &info, unsigned i); }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-envelope.cpp b/src/live_effects/lpe-envelope.cpp index b0ff8a4956ad29bd29b12b41a995595130b3c708..b1c6c9e9f7b346612a28791644f72b7065aff469 100644 --- a/src/live_effects/lpe-envelope.cpp +++ b/src/live_effects/lpe-envelope.cpp @@ -6,6 +6,7 @@ */ #include "live_effects/lpe-envelope.h" + #include "display/curve.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -13,14 +14,18 @@ namespace Inkscape { namespace LivePathEffect { -LPEEnvelope::LPEEnvelope(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - bend_path1(_("Top bend path:"), _("Top path along which to bend the original path"), "bendpath1", &wr, this, "M0,0 L1,0"), - bend_path2(_("Right bend path:"), _("Right path along which to bend the original path"), "bendpath2", &wr, this, "M0,0 L1,0"), - bend_path3(_("Bottom bend path:"), _("Bottom path along which to bend the original path"), "bendpath3", &wr, this, "M0,0 L1,0"), - bend_path4(_("Left bend path:"), _("Left path along which to bend the original path"), "bendpath4", &wr, this, "M0,0 L1,0"), - xx(_("_Enable left & right paths"), _("Enable the left and right deformation paths"), "xx", &wr, this, true), - yy(_("_Enable top & bottom paths"), _("Enable the top and bottom deformation paths"), "yy", &wr, this, true) +LPEEnvelope::LPEEnvelope(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , bend_path1(_("Top bend path:"), _("Top path along which to bend the original path"), "bendpath1", &wr, this, + "M0,0 L1,0") + , bend_path2(_("Right bend path:"), _("Right path along which to bend the original path"), "bendpath2", &wr, this, + "M0,0 L1,0") + , bend_path3(_("Bottom bend path:"), _("Bottom path along which to bend the original path"), "bendpath3", &wr, this, + "M0,0 L1,0") + , bend_path4(_("Left bend path:"), _("Left path along which to bend the original path"), "bendpath4", &wr, this, + "M0,0 L1,0") + , xx(_("_Enable left & right paths"), _("Enable the left and right deformation paths"), "xx", &wr, this, true) + , yy(_("_Enable top & bottom paths"), _("Enable the top and bottom deformation paths"), "yy", &wr, this, true) { registerParameter(&yy); registerParameter(&xx); @@ -32,8 +37,7 @@ LPEEnvelope::LPEEnvelope(LivePathEffectObject *lpeobject) : apply_to_clippath_and_mask = true; } -LPEEnvelope::~LPEEnvelope() -= default; +LPEEnvelope::~LPEEnvelope() = default; void LPEEnvelope::transform_multiply(Geom::Affine const &postmul, bool /*set*/) { @@ -45,30 +49,24 @@ void LPEEnvelope::transform_multiply(Geom::Affine const &postmul, bool /*set*/) } } -void -LPEEnvelope::doBeforeEffect (SPLPEItem const* lpeitem) +void LPEEnvelope::doBeforeEffect(SPLPEItem const *lpeitem) { // get the item bounding box original_bbox(lpeitem, false, true); } -Geom::Piecewise > -LPEEnvelope::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPEEnvelope::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { - - if(!xx.get_value() && !yy.get_value()) - { + if (!xx.get_value() && !yy.get_value()) { return pwd2_in; } using namespace Geom; // Don't allow empty path parameters: - if ( bend_path1.get_pathvector().empty() - || bend_path2.get_pathvector().empty() - || bend_path3.get_pathvector().empty() - || bend_path4.get_pathvector().empty() ) - { + if (bend_path1.get_pathvector().empty() || bend_path2.get_pathvector().empty() || + bend_path3.get_pathvector().empty() || bend_path4.get_pathvector().empty()) { return pwd2_in; } @@ -77,73 +75,69 @@ LPEEnvelope::doEffect_pwd2 (Geom::Piecewise > const & pwd Please, read it before trying to understand this one */ - Piecewise > uskeleton1 = arc_length_parametrization(bend_path1.get_pwd2(),2,.1); - uskeleton1 = remove_short_cuts(uskeleton1,.01); - Piecewise > n1 = rot90(derivative(uskeleton1)); - n1 = force_continuity(remove_short_cuts(n1,.1)); - - Piecewise > uskeleton2 = arc_length_parametrization(bend_path2.get_pwd2(),2,.1); - uskeleton2 = remove_short_cuts(uskeleton2,.01); - Piecewise > n2 = rot90(derivative(uskeleton2)); - n2 = force_continuity(remove_short_cuts(n2,.1)); + Piecewise> uskeleton1 = arc_length_parametrization(bend_path1.get_pwd2(), 2, .1); + uskeleton1 = remove_short_cuts(uskeleton1, .01); + Piecewise> n1 = rot90(derivative(uskeleton1)); + n1 = force_continuity(remove_short_cuts(n1, .1)); - Piecewise > uskeleton3 = arc_length_parametrization(bend_path3.get_pwd2(),2,.1); - uskeleton3 = remove_short_cuts(uskeleton3,.01); - Piecewise > n3 = rot90(derivative(uskeleton3)); - n3 = force_continuity(remove_short_cuts(n3,.1)); + Piecewise> uskeleton2 = arc_length_parametrization(bend_path2.get_pwd2(), 2, .1); + uskeleton2 = remove_short_cuts(uskeleton2, .01); + Piecewise> n2 = rot90(derivative(uskeleton2)); + n2 = force_continuity(remove_short_cuts(n2, .1)); - Piecewise > uskeleton4 = arc_length_parametrization(bend_path4.get_pwd2(),2,.1); - uskeleton4 = remove_short_cuts(uskeleton4,.01); - Piecewise > n4 = rot90(derivative(uskeleton4)); - n4 = force_continuity(remove_short_cuts(n4,.1)); + Piecewise> uskeleton3 = arc_length_parametrization(bend_path3.get_pwd2(), 2, .1); + uskeleton3 = remove_short_cuts(uskeleton3, .01); + Piecewise> n3 = rot90(derivative(uskeleton3)); + n3 = force_continuity(remove_short_cuts(n3, .1)); + Piecewise> uskeleton4 = arc_length_parametrization(bend_path4.get_pwd2(), 2, .1); + uskeleton4 = remove_short_cuts(uskeleton4, .01); + Piecewise> n4 = rot90(derivative(uskeleton4)); + n4 = force_continuity(remove_short_cuts(n4, .1)); - D2 > patternd2 = make_cuts_independent(pwd2_in); + D2> patternd2 = make_cuts_independent(pwd2_in); Piecewise x = Piecewise(patternd2[0]); Piecewise y = Piecewise(patternd2[1]); /*The *1.001 is a hack to avoid a small bug : path at x=0 and y=0 don't work well. */ - x-= boundingbox_X.min()*1.001; - y-= boundingbox_Y.min()*1.001; + x -= boundingbox_X.min() * 1.001; + y -= boundingbox_Y.min() * 1.001; - Piecewise x1 = x ; - Piecewise y1 = y ; + Piecewise x1 = x; + Piecewise y1 = y; - Piecewise x2 = x ; - Piecewise y2 = y ; + Piecewise x2 = x; + Piecewise y2 = y; x2 -= boundingbox_X.extent(); - Piecewise x3 = x ; - Piecewise y3 = y ; + Piecewise x3 = x; + Piecewise y3 = y; y3 -= boundingbox_Y.extent(); - Piecewise x4 = x ; - Piecewise y4 = y ; - + Piecewise x4 = x; + Piecewise y4 = y; /*Scaling to the Bend Path length*/ - double scaling1 = uskeleton1.cuts.back()/boundingbox_X.extent(); + double scaling1 = uskeleton1.cuts.back() / boundingbox_X.extent(); if (scaling1 != 1.0) { - x1*=scaling1; + x1 *= scaling1; } - double scaling2 = uskeleton2.cuts.back()/boundingbox_Y.extent(); + double scaling2 = uskeleton2.cuts.back() / boundingbox_Y.extent(); if (scaling2 != 1.0) { - y2*=scaling2; + y2 *= scaling2; } - double scaling3 = uskeleton3.cuts.back()/boundingbox_X.extent(); + double scaling3 = uskeleton3.cuts.back() / boundingbox_X.extent(); if (scaling3 != 1.0) { - x3*=scaling3; + x3 *= scaling3; } - double scaling4 = uskeleton4.cuts.back()/boundingbox_Y.extent(); + double scaling4 = uskeleton4.cuts.back() / boundingbox_Y.extent(); if (scaling4 != 1.0) { - y4*=scaling4; + y4 *= scaling4; } - - Piecewise xbis = x; Piecewise ybis = y; xbis *= -1.0; @@ -152,11 +146,11 @@ LPEEnvelope::doEffect_pwd2 (Geom::Piecewise > const & pwd ybis += boundingbox_Y.extent(); /* This is important : y + ybis = constant and x +xbis = constant */ - Piecewise > output; - Piecewise > output1; - Piecewise > output2; - Piecewise > output_x; - Piecewise > output_y; + Piecewise> output; + Piecewise> output1; + Piecewise> output2; + Piecewise> output_x; + Piecewise> output_y; /* output_y : Deformation by Up and Down Bend Paths @@ -164,37 +158,33 @@ LPEEnvelope::doEffect_pwd2 (Geom::Piecewise > const & pwd This is done by the line "ybis*Derformation1 + y*Deformation2" The result is a mix between the 2 deformed paths */ - output_y = ybis*(compose((uskeleton1),x1) + y1*compose(n1,x1) ) - + y*(compose((uskeleton3),x3) + y3*compose(n3,x3) ); + output_y = ybis * (compose((uskeleton1), x1) + y1 * compose(n1, x1)) + + y * (compose((uskeleton3), x3) + y3 * compose(n3, x3)); output_y /= (boundingbox_Y.extent()); - if(!xx.get_value() && yy.get_value()) - { - return output_y; + if (!xx.get_value() && yy.get_value()) { + return output_y; } /*output_x : Deformation by Left and Right Bend Paths*/ - output_x = x*(compose((uskeleton2),y2) + -x2*compose(n2,y2) ) - + xbis*(compose((uskeleton4),y4) + -x4*compose(n4,y4) ); + output_x = x * (compose((uskeleton2), y2) + -x2 * compose(n2, y2)) + + xbis * (compose((uskeleton4), y4) + -x4 * compose(n4, y4)); output_x /= (boundingbox_X.extent()); - if(xx.get_value() && !yy.get_value()) - { - return output_x; + if (xx.get_value() && !yy.get_value()) { + return output_x; } /*output : Deformation by Up, Left, Right and Down Bend Paths*/ - if(xx.get_value() && yy.get_value()) - { - Piecewise xsqr = x*xbis; /* xsqr = x * (BBox_X - x) */ - Piecewise ysqr = y*ybis; /* xsqr = y * (BBox_Y - y) */ + if (xx.get_value() && yy.get_value()) { + Piecewise xsqr = x * xbis; /* xsqr = x * (BBox_X - x) */ + Piecewise ysqr = y * ybis; /* xsqr = y * (BBox_Y - y) */ Piecewise xsqrbis = xsqr; Piecewise ysqrbis = ysqr; xsqrbis *= -1; - xsqrbis += boundingbox_X.extent()*boundingbox_X.extent()/4.; + xsqrbis += boundingbox_X.extent() * boundingbox_X.extent() / 4.; ysqrbis *= -1; - ysqrbis += boundingbox_Y.extent()*boundingbox_Y.extent()/4.; + ysqrbis += boundingbox_Y.extent() * boundingbox_Y.extent() / 4.; /*This is important : xsqr + xsqrbis = constant*/ - /* Here we mix the last two results : output_x and output_y output1 : The more a point is close to Up and Down, the less it will be affected by output_x. @@ -202,26 +192,24 @@ LPEEnvelope::doEffect_pwd2 (Geom::Piecewise > const & pwd output2 : The more a point is close to Left and Right, the less it will be affected by output_y. output : we do the mean between output1 and output2 for all points. */ - output1 = (ysqrbis*output_y) + (ysqr*output_x); - output1 /= (boundingbox_Y.extent()*boundingbox_Y.extent()/4.); + output1 = (ysqrbis * output_y) + (ysqr * output_x); + output1 /= (boundingbox_Y.extent() * boundingbox_Y.extent() / 4.); - output2 = (xsqrbis*output_x) + (xsqr*output_y); - output2 /= (boundingbox_X.extent()*boundingbox_X.extent()/4.); + output2 = (xsqrbis * output_x) + (xsqr * output_y); + output2 /= (boundingbox_X.extent() * boundingbox_X.extent() / 4.); output = output1 + output2; output /= 2.; return output; /*Of course, the result is not perfect, but on a graphical point of view, this is sufficient.*/ - } // do nothing when xx and yy are both false return pwd2_in; } -void -LPEEnvelope::resetDefaults(SPItem const* item) +void LPEEnvelope::resetDefaults(SPItem const *item) { Effect::resetDefaults(item); @@ -233,26 +221,25 @@ LPEEnvelope::resetDefaults(SPItem const* item) Geom::Point Down_Right(boundingbox_X.max(), boundingbox_Y.max()); Geom::Path path1; - path1.start( Up_Left ); - path1.appendNew( Up_Right ); - bend_path1.set_new_value( path1.toPwSb(), true ); + path1.start(Up_Left); + path1.appendNew(Up_Right); + bend_path1.set_new_value(path1.toPwSb(), true); Geom::Path path2; - path2.start( Up_Right ); - path2.appendNew( Down_Right ); - bend_path2.set_new_value( path2.toPwSb(), true ); + path2.start(Up_Right); + path2.appendNew(Down_Right); + bend_path2.set_new_value(path2.toPwSb(), true); Geom::Path path3; - path3.start( Down_Left ); - path3.appendNew( Down_Right ); - bend_path3.set_new_value( path3.toPwSb(), true ); + path3.start(Down_Left); + path3.appendNew(Down_Right); + bend_path3.set_new_value(path3.toPwSb(), true); Geom::Path path4; - path4.start( Up_Left ); - path4.appendNew( Down_Left ); - bend_path4.set_new_value( path4.toPwSb(), true ); + path4.start(Up_Left); + path4.appendNew(Down_Left); + bend_path4.set_new_value(path4.toPwSb(), true); } - } // namespace LivePathEffect } /* namespace Inkscape */ diff --git a/src/live_effects/lpe-envelope.h b/src/live_effects/lpe-envelope.h index 0cf2bfd3f05aed27a37e13ea4830a7147cd61fcf..ad18a0e37b90e0c0b11d7508544d164cd9231b91 100644 --- a/src/live_effects/lpe-envelope.h +++ b/src/live_effects/lpe-envelope.h @@ -10,50 +10,53 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/enum.h" -#include "live_effects/effect.h" -#include "live_effects/parameter/path.h" -#include "live_effects/parameter/bool.h" - -#include <2geom/sbasis.h> -#include <2geom/sbasis-geometric.h> #include <2geom/bezier-to-sbasis.h> -#include <2geom/sbasis-to-bezier.h> #include <2geom/d2.h> #include <2geom/piecewise.h> +#include <2geom/sbasis-geometric.h> +#include <2geom/sbasis-to-bezier.h> +#include <2geom/sbasis.h> +#include "live_effects/effect.h" #include "live_effects/lpegroupbbox.h" +#include "live_effects/parameter/bool.h" +#include "live_effects/parameter/enum.h" +#include "live_effects/parameter/path.h" namespace Inkscape { namespace LivePathEffect { -class LPEEnvelope : public Effect, GroupBBoxEffect { +class LPEEnvelope + : public Effect + , GroupBBoxEffect +{ public: LPEEnvelope(LivePathEffectObject *lpeobject); ~LPEEnvelope() override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; void transform_multiply(Geom::Affine const &postmul, bool set) override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; - void resetDefaults(SPItem const* item) override; + void resetDefaults(SPItem const *item) override; private: - PathParam bend_path1; - PathParam bend_path2; - PathParam bend_path3; - PathParam bend_path4; - BoolParam xx; - BoolParam yy; + PathParam bend_path1; + PathParam bend_path2; + PathParam bend_path3; + PathParam bend_path4; + BoolParam xx; + BoolParam yy; void on_pattern_pasted(); - LPEEnvelope(const LPEEnvelope&); - LPEEnvelope& operator=(const LPEEnvelope&); + LPEEnvelope(const LPEEnvelope &); + LPEEnvelope &operator=(const LPEEnvelope &); }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-extrude.cpp b/src/live_effects/lpe-extrude.cpp index 57e5ca2ceaac3df12e3ccf77f78af850727f6553..6bb6207676d9ae0b3280040263aa9d4aab90eb89 100644 --- a/src/live_effects/lpe-extrude.cpp +++ b/src/live_effects/lpe-extrude.cpp @@ -17,13 +17,13 @@ // TODO due to internal breakage in glibmm headers, this must be last: #include - namespace Inkscape { namespace LivePathEffect { -LPEExtrude::LPEExtrude(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - extrude_vector(_("Direction"), _("Defines the direction and magnitude of the extrusion"), "extrude_vector", &wr, this, Geom::Point(-10,10)) +LPEExtrude::LPEExtrude(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , extrude_vector(_("Direction"), _("Defines the direction and magnitude of the extrusion"), "extrude_vector", &wr, + this, Geom::Point(-10, 10)) { show_orig_path = true; concatenate_before_pwd2 = false; @@ -31,22 +31,23 @@ LPEExtrude::LPEExtrude(LivePathEffectObject *lpeobject) : registerParameter(&extrude_vector); } -LPEExtrude::~LPEExtrude() -= default; +LPEExtrude::~LPEExtrude() = default; -static bool are_colinear(Geom::Point a, Geom::Point b) { - return Geom::are_near(cross(a,b), 0., 0.5); +static bool are_colinear(Geom::Point a, Geom::Point b) +{ + return Geom::are_near(cross(a, b), 0., 0.5); } // find cusps, except at start/end for closed paths. // this should be factored out later. -static std::vector find_cusps( Geom::Piecewise > const & pwd2_in ) { +static std::vector find_cusps(Geom::Piecewise> const &pwd2_in) +{ using namespace Geom; - Piecewise > deriv = derivative(pwd2_in); + Piecewise> deriv = derivative(pwd2_in); std::vector cusps; // cusps are spots where the derivative jumps. - for (unsigned i = 1 ; i < deriv.size() ; ++i) { - if ( ! are_colinear(deriv[i-1].at1(), deriv[i].at0()) ) { + for (unsigned i = 1; i < deriv.size(); ++i) { + if (!are_colinear(deriv[i - 1].at1(), deriv[i].at0())) { // there is a jump in the derivative, so add it to the cusps list cusps.push_back(deriv.cuts[i]); } @@ -54,117 +55,119 @@ static std::vector find_cusps( Geom::Piecewise > return cusps; } -Geom::Piecewise > -LPEExtrude::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPEExtrude::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; // generate connecting lines (the 'sides' of the extrusion) - Geom::Path path(Point(0.,0.)); - path.appendNew( extrude_vector.getVector() ); - Piecewise > connector = path.toPwSb(); - - switch( 1 ) { - case 0: { - /* This one results in the following subpaths: the original, a displaced copy, and connector lines between the two - */ - - Piecewise > pwd2_out = pwd2_in; - // generate extrusion bottom: (just a copy of original path, displaced a bit) - pwd2_out.concat( pwd2_in + extrude_vector.getVector() ); - - // connecting lines should be put at start and end of path if it is not closed - // it is not possible to check whether a piecewise path is closed, - // so we check whether start and end are close - if ( ! are_near(pwd2_in.firstValue(), pwd2_in.lastValue()) ) { - pwd2_out.concat( connector + pwd2_in.firstValue() ); - pwd2_out.concat( connector + pwd2_in.lastValue() ); - } - // connecting lines should be put at cusps - Piecewise > deriv = derivative(pwd2_in); - std::vector cusps; // = roots(deriv); - for (double cusp : cusps) { - pwd2_out.concat( connector + pwd2_in.valueAt(cusp) ); - } - // connecting lines should be put where the tangent of the path equals the extrude_vector in direction - std::vector rts = roots(dot(deriv, rot90(extrude_vector.getVector()))); - for (double rt : rts) { - pwd2_out.concat( connector + pwd2_in.valueAt(rt) ); + Geom::Path path(Point(0., 0.)); + path.appendNew(extrude_vector.getVector()); + Piecewise> connector = path.toPwSb(); + + switch (1) { + case 0: { + /* This one results in the following subpaths: the original, a displaced copy, and connector lines between + * the two + */ + + Piecewise> pwd2_out = pwd2_in; + // generate extrusion bottom: (just a copy of original path, displaced a bit) + pwd2_out.concat(pwd2_in + extrude_vector.getVector()); + + // connecting lines should be put at start and end of path if it is not closed + // it is not possible to check whether a piecewise path is closed, + // so we check whether start and end are close + if (!are_near(pwd2_in.firstValue(), pwd2_in.lastValue())) { + pwd2_out.concat(connector + pwd2_in.firstValue()); + pwd2_out.concat(connector + pwd2_in.lastValue()); + } + // connecting lines should be put at cusps + Piecewise> deriv = derivative(pwd2_in); + std::vector cusps; // = roots(deriv); + for (double cusp : cusps) { + pwd2_out.concat(connector + pwd2_in.valueAt(cusp)); + } + // connecting lines should be put where the tangent of the path equals the extrude_vector in direction + std::vector rts = roots(dot(deriv, rot90(extrude_vector.getVector()))); + for (double rt : rts) { + pwd2_out.concat(connector + pwd2_in.valueAt(rt)); + } + return pwd2_out; } - return pwd2_out; - } - default: - case 1: { - /* This one creates separate closed subpaths that correspond to the faces of the extruded shape. - * When the LPE is complete, one can convert the shape to a normal path, then break subpaths apart and start coloring them. - */ - - Piecewise > pwd2_out; - // split input path in pieces between points where deriv == vector - Piecewise > deriv = derivative(pwd2_in); - std::vector rts = roots(dot(deriv, rot90(extrude_vector.getVector()))); - - std::vector cusps = find_cusps(pwd2_in); - - // see if we should treat the path as being closed. - bool closed_path = false; - if ( are_near(pwd2_in.firstValue(), pwd2_in.lastValue()) ) { - // the path is closed, however if there is a cusp at the closing point, we should treat it as being an open path. - if ( are_colinear(deriv.firstValue(), deriv.lastValue()) ) { - // there is no jump in the derivative, so treat path as being closed - closed_path = true; + default: + case 1: { + /* This one creates separate closed subpaths that correspond to the faces of the extruded shape. + * When the LPE is complete, one can convert the shape to a normal path, then break subpaths apart and start + * coloring them. + */ + + Piecewise> pwd2_out; + // split input path in pieces between points where deriv == vector + Piecewise> deriv = derivative(pwd2_in); + std::vector rts = roots(dot(deriv, rot90(extrude_vector.getVector()))); + + std::vector cusps = find_cusps(pwd2_in); + + // see if we should treat the path as being closed. + bool closed_path = false; + if (are_near(pwd2_in.firstValue(), pwd2_in.lastValue())) { + // the path is closed, however if there is a cusp at the closing point, we should treat it as being an + // open path. + if (are_colinear(deriv.firstValue(), deriv.lastValue())) { + // there is no jump in the derivative, so treat path as being closed + closed_path = true; + } } - } - std::vector connector_pts; - if (rts.empty()) { - connector_pts = cusps; - } else if (cusps.empty()) { - connector_pts = rts; - } else { - connector_pts = rts; - connector_pts.insert(connector_pts.begin(), cusps.begin(), cusps.end()); - sort(connector_pts.begin(), connector_pts.end()); - } + std::vector connector_pts; + if (rts.empty()) { + connector_pts = cusps; + } else if (cusps.empty()) { + connector_pts = rts; + } else { + connector_pts = rts; + connector_pts.insert(connector_pts.begin(), cusps.begin(), cusps.end()); + sort(connector_pts.begin(), connector_pts.end()); + } - double portion_t = 0.; - for (unsigned i = 0; i < connector_pts.size() ; ++i) { - Piecewise > cut = portion(pwd2_in, portion_t, connector_pts[i] ); - portion_t = connector_pts[i]; - if (closed_path && i == 0) { - // if the path is closed, skip the first cut and add it to the last cut later - continue; + double portion_t = 0.; + for (unsigned i = 0; i < connector_pts.size(); ++i) { + Piecewise> cut = portion(pwd2_in, portion_t, connector_pts[i]); + portion_t = connector_pts[i]; + if (closed_path && i == 0) { + // if the path is closed, skip the first cut and add it to the last cut later + continue; + } + Piecewise> part = cut; + part.continuousConcat(connector + cut.lastValue()); + part.continuousConcat(reverse(cut) + extrude_vector.getVector()); + part.continuousConcat(reverse(connector) + cut.firstValue()); + pwd2_out.concat(part); } - Piecewise > part = cut; - part.continuousConcat(connector + cut.lastValue()); - part.continuousConcat(reverse(cut) + extrude_vector.getVector()); - part.continuousConcat(reverse(connector) + cut.firstValue()); - pwd2_out.concat( part ); - } - if (closed_path) { - Piecewise > cut = portion(pwd2_in, portion_t, pwd2_in.domain().max() ); - cut.continuousConcat(portion(pwd2_in, pwd2_in.domain().min(), connector_pts[0] )); - Piecewise > part = cut; - part.continuousConcat(connector + cut.lastValue()); - part.continuousConcat(reverse(cut) + extrude_vector.getVector()); - part.continuousConcat(reverse(connector) + cut.firstValue()); - pwd2_out.concat( part ); - } else if (!are_near(portion_t, pwd2_in.domain().max())) { - Piecewise > cut = portion(pwd2_in, portion_t, pwd2_in.domain().max() ); - Piecewise > part = cut; - part.continuousConcat(connector + cut.lastValue()); - part.continuousConcat(reverse(cut) + extrude_vector.getVector()); - part.continuousConcat(reverse(connector) + cut.firstValue()); - pwd2_out.concat( part ); + if (closed_path) { + Piecewise> cut = portion(pwd2_in, portion_t, pwd2_in.domain().max()); + cut.continuousConcat(portion(pwd2_in, pwd2_in.domain().min(), connector_pts[0])); + Piecewise> part = cut; + part.continuousConcat(connector + cut.lastValue()); + part.continuousConcat(reverse(cut) + extrude_vector.getVector()); + part.continuousConcat(reverse(connector) + cut.firstValue()); + pwd2_out.concat(part); + } else if (!are_near(portion_t, pwd2_in.domain().max())) { + Piecewise> cut = portion(pwd2_in, portion_t, pwd2_in.domain().max()); + Piecewise> part = cut; + part.continuousConcat(connector + cut.lastValue()); + part.continuousConcat(reverse(cut) + extrude_vector.getVector()); + part.continuousConcat(reverse(connector) + cut.firstValue()); + pwd2_out.concat(part); + } + return pwd2_out; } - return pwd2_out; - } } } -void -LPEExtrude::resetDefaults(SPItem const* item) +void LPEExtrude::resetDefaults(SPItem const *item) { Effect::resetDefaults(item); @@ -174,12 +177,13 @@ LPEExtrude::resetDefaults(SPItem const* item) if (bbox) { Interval const &boundingbox_X = (*bbox)[Geom::X]; Interval const &boundingbox_Y = (*bbox)[Geom::Y]; - extrude_vector.set_and_write_new_values( Geom::Point(boundingbox_X.middle(), boundingbox_Y.middle()), - (boundingbox_X.extent() + boundingbox_Y.extent())*Geom::Point(-0.05,0.2) ); + extrude_vector.set_and_write_new_values(Geom::Point(boundingbox_X.middle(), boundingbox_Y.middle()), + (boundingbox_X.extent() + boundingbox_Y.extent()) * + Geom::Point(-0.05, 0.2)); } } -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-extrude.h b/src/live_effects/lpe-extrude.h index d666138b06c3447654c0ed2381cedcc6f5d8d0f8..f3cdb1f380a0d3b9618e0bf5c1fad2cee5344923 100644 --- a/src/live_effects/lpe-extrude.h +++ b/src/live_effects/lpe-extrude.h @@ -20,24 +20,26 @@ namespace Inkscape { namespace LivePathEffect { -class LPEExtrude : public Effect { +class LPEExtrude : public Effect +{ public: LPEExtrude(LivePathEffectObject *lpeobject); ~LPEExtrude() override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; - void resetDefaults(SPItem const* item) override; + void resetDefaults(SPItem const *item) override; private: VectorParam extrude_vector; - LPEExtrude(const LPEExtrude&) = delete; - LPEExtrude& operator=(const LPEExtrude&) = delete; + LPEExtrude(const LPEExtrude &) = delete; + LPEExtrude &operator=(const LPEExtrude &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-fill-between-many.cpp b/src/live_effects/lpe-fill-between-many.cpp index 2e23c3fbe2c6233891734e67e3f03dd19e9d8295..9e2f2bc6ce003451b803b294ed7cd779205a58ef 100644 --- a/src/live_effects/lpe-fill-between-many.cpp +++ b/src/live_effects/lpe-fill-between-many.cpp @@ -5,17 +5,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "live_effects/lpe-fill-between-many.h" -#include "live_effects/lpeobject.h" -#include "xml/node.h" + #include "display/curve.h" #include "inkscape.h" -#include "selection.h" - +#include "live_effects/lpeobject.h" #include "object/sp-defs.h" #include "object/sp-shape.h" +#include "selection.h" #include "svg/svg.h" +#include "xml/node.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -24,16 +23,16 @@ namespace Inkscape { namespace LivePathEffect { static const Util::EnumData FilllpemethodData[] = { - { FLM_ORIGINALD, N_("Without LPEs"), "originald" }, - { FLM_BSPLINESPIRO, N_("With Spiro or BSpline"), "bsplinespiro" }, - { FLM_D, N_("With all LPEs"), "d" } -}; + {FLM_ORIGINALD, N_("Without LPEs"), "originald"}, + {FLM_BSPLINESPIRO, N_("With Spiro or BSpline"), "bsplinespiro"}, + {FLM_D, N_("With all LPEs"), "d"}}; static const Util::EnumDataConverter FLMConverter(FilllpemethodData, FLM_END); LPEFillBetweenMany::LPEFillBetweenMany(LivePathEffectObject *lpeobject) : Effect(lpeobject) , linked_paths(_("Linked path:"), _("Paths from which to take the original path data"), "linkedpaths", &wr, this) - , method(_("LPEs:"), _("Which LPEs of the linked paths should be considered"), "method", FLMConverter, &wr, this, FLM_BSPLINESPIRO) + , method(_("LPEs:"), _("Which LPEs of the linked paths should be considered"), "method", FLMConverter, &wr, this, + FLM_BSPLINESPIRO) , join(_("Join subpaths"), _("Join subpaths"), "join", &wr, this, true) , close(_("Close"), _("Close path"), "close", &wr, this, true) , autoreverse(_("Autoreverse"), _("Autoreverse"), "autoreverse", &wr, this, true) @@ -48,16 +47,15 @@ LPEFillBetweenMany::LPEFillBetweenMany(LivePathEffectObject *lpeobject) previous_method = FLM_END; } -LPEFillBetweenMany::~LPEFillBetweenMany() -= default; +LPEFillBetweenMany::~LPEFillBetweenMany() = default; -void LPEFillBetweenMany::doEffect (SPCurve * curve) +void LPEFillBetweenMany::doEffect(SPCurve *curve) { if (previous_method != method) { if (method == FLM_BSPLINESPIRO) { linked_paths.allowOnlyBsplineSpiro(true); linked_paths.setFromOriginalD(false); - } else if(method == FLM_ORIGINALD) { + } else if (method == FLM_ORIGINALD) { linked_paths.allowOnlyBsplineSpiro(false); linked_paths.setFromOriginalD(true); } else { @@ -77,7 +75,7 @@ void LPEFillBetweenMany::doEffect (SPCurve * curve) selection = desktop->selection; } if (!autoreverse) { - for (auto & iter : linked_paths._vector) { + for (auto &iter : linked_paths._vector) { SPObject *obj; if (iter->ref.isAttached() && (obj = iter->ref.getObject()) && SP_IS_ITEM(obj) && !iter->_pathvector.empty() && iter->visibled) { @@ -112,7 +110,7 @@ void LPEFillBetweenMany::doEffect (SPCurve * curve) unsigned int counter = 0; Geom::Point current = Geom::Point(); std::vector done; - for (auto & iter : linked_paths._vector) { + for (auto &iter : linked_paths._vector) { SPObject *obj; if (iter->ref.isAttached() && (obj = iter->ref.getObject()) && SP_IS_ITEM(obj) && !iter->_pathvector.empty() && iter->visibled) { @@ -137,7 +135,7 @@ void LPEFillBetweenMany::doEffect (SPCurve * curve) unsigned int counter2 = 0; unsigned int added = 0; PathAndDirectionAndVisible *nearest = nullptr; - for (auto & iter2 : linked_paths._vector) { + for (auto &iter2 : linked_paths._vector) { SPObject *obj2; if (iter2->ref.isAttached() && (obj2 = iter2->ref.getObject()) && SP_IS_ITEM(obj2) && !iter2->_pathvector.empty() && iter2->visibled) { diff --git a/src/live_effects/lpe-fill-between-many.h b/src/live_effects/lpe-fill-between-many.h index 6ddfb6120ba62cd5d02dbb119499a6f51b10a1fc..49928da2fd2ede55a0eb2ccff7edbbea2683b075 100644 --- a/src/live_effects/lpe-fill-between-many.h +++ b/src/live_effects/lpe-fill-between-many.h @@ -12,24 +12,27 @@ #include "live_effects/effect.h" #include "live_effects/parameter/enum.h" -#include "live_effects/parameter/originalpatharray.h" #include "live_effects/parameter/hidden.h" +#include "live_effects/parameter/originalpatharray.h" namespace Inkscape { namespace LivePathEffect { -enum Filllpemethod { +enum Filllpemethod +{ FLM_ORIGINALD, FLM_BSPLINESPIRO, FLM_D, FLM_END }; -class LPEFillBetweenMany : public Effect { +class LPEFillBetweenMany : public Effect +{ public: LPEFillBetweenMany(LivePathEffectObject *lpeobject); ~LPEFillBetweenMany() override; - void doEffect (SPCurve * curve) override; + void doEffect(SPCurve *curve) override; + private: OriginalPathArrayParam linked_paths; EnumParam method; @@ -38,11 +41,11 @@ private: BoolParam autoreverse; HiddenParam applied; Filllpemethod previous_method; - LPEFillBetweenMany(const LPEFillBetweenMany&) = delete; - LPEFillBetweenMany& operator=(const LPEFillBetweenMany&) = delete; + LPEFillBetweenMany(const LPEFillBetweenMany &) = delete; + LPEFillBetweenMany &operator=(const LPEFillBetweenMany &) = delete; }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-fill-between-strokes.cpp b/src/live_effects/lpe-fill-between-strokes.cpp index 525acdc085a47cbf8b5ba2d9ef0475c75ccae159..34621914958b3d33515a6fb14ad4f406b1b046d6 100644 --- a/src/live_effects/lpe-fill-between-strokes.cpp +++ b/src/live_effects/lpe-fill-between-strokes.cpp @@ -15,13 +15,14 @@ namespace Inkscape { namespace LivePathEffect { -LPEFillBetweenStrokes::LPEFillBetweenStrokes(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - linked_path(_("Linked path:"), _("Path from which to take the original path data"), "linkedpath", &wr, this), - second_path(_("Second path:"), _("Second path from which to take the original path data"), "secondpath", &wr, this), - reverse_second(_("Reverse Second"), _("Reverses the second path order"), "reversesecond", &wr, this), - join(_("Join subpaths"), _("Join subpaths"), "join", &wr, this, true), - close(_("Close"), _("Close path"), "close", &wr, this, true) +LPEFillBetweenStrokes::LPEFillBetweenStrokes(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , linked_path(_("Linked path:"), _("Path from which to take the original path data"), "linkedpath", &wr, this) + , second_path(_("Second path:"), _("Second path from which to take the original path data"), "secondpath", &wr, + this) + , reverse_second(_("Reverse Second"), _("Reverses the second path order"), "reversesecond", &wr, this) + , join(_("Join subpaths"), _("Join subpaths"), "join", &wr, this, true) + , close(_("Close"), _("Close path"), "close", &wr, this, true) { registerParameter(&linked_path); registerParameter(&second_path); @@ -30,10 +31,9 @@ LPEFillBetweenStrokes::LPEFillBetweenStrokes(LivePathEffectObject *lpeobject) : registerParameter(&close); } -LPEFillBetweenStrokes::~LPEFillBetweenStrokes() -= default; +LPEFillBetweenStrokes::~LPEFillBetweenStrokes() = default; -void LPEFillBetweenStrokes::doEffect (SPCurve * curve) +void LPEFillBetweenStrokes::doEffect(SPCurve *curve) { if (curve) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; @@ -45,35 +45,36 @@ void LPEFillBetweenStrokes::doEffect (SPCurve * curve) if (transf != Geom::identity()) { sp_lpe_item->doWriteTransform(Geom::identity()); } - if ( linked_path.linksToPath() && second_path.linksToPath() && linked_path.getObject() && second_path.getObject() ) { - SPItem * linked1 = linked_path.getObject(); + if (linked_path.linksToPath() && second_path.linksToPath() && linked_path.getObject() && + second_path.getObject()) { + SPItem *linked1 = linked_path.getObject(); if (linked1 && transf != Geom::identity() && selection && !selection->includes(linked1->getRepr())) { SP_ITEM(linked1)->doWriteTransform(transf); } Geom::PathVector linked_pathv = linked_path.get_pathvector(); - SPItem * linked2 = second_path.getObject(); + SPItem *linked2 = second_path.getObject(); if (linked2 && transf != Geom::identity() && selection && !selection->includes(linked2->getRepr())) { SP_ITEM(linked2)->doWriteTransform(transf); } Geom::PathVector second_pathv = second_path.get_pathvector(); Geom::PathVector result_linked_pathv; Geom::PathVector result_second_pathv; - for (auto & iter : linked_pathv) - { + for (auto &iter : linked_pathv) { result_linked_pathv.push_back(iter); } - for (auto & iter : second_pathv) - { + for (auto &iter : second_pathv) { result_second_pathv.push_back(iter); } - if ( !result_linked_pathv.empty() && !result_second_pathv.empty() && !result_linked_pathv.front().closed() ) { + if (!result_linked_pathv.empty() && !result_second_pathv.empty() && !result_linked_pathv.front().closed()) { if (reverse_second.get_value()) { result_second_pathv.front() = result_second_pathv.front().reversed(); } if (join) { - if (!are_near(result_linked_pathv.front().finalPoint(), result_second_pathv.front().initialPoint(),0.1)) { - result_linked_pathv.front().appendNew(result_second_pathv.front().initialPoint()); + if (!are_near(result_linked_pathv.front().finalPoint(), result_second_pathv.front().initialPoint(), + 0.1)) { + result_linked_pathv.front().appendNew( + result_second_pathv.front().initialPoint()); } else { result_second_pathv.front().setInitial(result_linked_pathv.front().finalPoint()); } @@ -89,42 +90,38 @@ void LPEFillBetweenStrokes::doEffect (SPCurve * curve) result_linked_pathv.push_back(result_second_pathv.front()); } curve->set_pathvector(result_linked_pathv); - } else if ( !result_linked_pathv.empty() ) { + } else if (!result_linked_pathv.empty()) { curve->set_pathvector(result_linked_pathv); - } else if ( !result_second_pathv.empty() ) { + } else if (!result_second_pathv.empty()) { curve->set_pathvector(result_second_pathv); } - } - else if ( linked_path.linksToPath() && linked_path.getObject() ) { + } else if (linked_path.linksToPath() && linked_path.getObject()) { SPItem *linked1 = linked_path.getObject(); if (linked1 && transf != Geom::identity() && selection && !selection->includes(linked1->getRepr())) { SP_ITEM(linked1)->doWriteTransform(transf); } Geom::PathVector linked_pathv = linked_path.get_pathvector(); Geom::PathVector result_pathv; - for (auto & iter : linked_pathv) - { + for (auto &iter : linked_pathv) { result_pathv.push_back(iter); } - if ( !result_pathv.empty() ) { + if (!result_pathv.empty()) { if (close) { result_pathv.front().close(); } curve->set_pathvector(result_pathv); } - } - else if ( second_path.linksToPath() && second_path.getObject() ) { + } else if (second_path.linksToPath() && second_path.getObject()) { SPItem *linked2 = second_path.getObject(); if (linked2 && transf != Geom::identity() && selection && !selection->includes(linked2->getRepr())) { SP_ITEM(linked2)->doWriteTransform(transf); } Geom::PathVector second_pathv = second_path.get_pathvector(); Geom::PathVector result_pathv; - for (auto & iter : second_pathv) - { + for (auto &iter : second_pathv) { result_pathv.push_back(iter); } - if ( !result_pathv.empty() ) { + if (!result_pathv.empty()) { if (close) { result_pathv.front().close(); } diff --git a/src/live_effects/lpe-fill-between-strokes.h b/src/live_effects/lpe-fill-between-strokes.h index 028535f0ab77c8f5bf181fcb195f91ad0ddfe7ff..c9bb6d8970d20ccebaeb288d250c82d708223729 100644 --- a/src/live_effects/lpe-fill-between-strokes.h +++ b/src/live_effects/lpe-fill-between-strokes.h @@ -16,25 +16,26 @@ namespace Inkscape { namespace LivePathEffect { -class LPEFillBetweenStrokes : public Effect { +class LPEFillBetweenStrokes : public Effect +{ public: LPEFillBetweenStrokes(LivePathEffectObject *lpeobject); ~LPEFillBetweenStrokes() override; - void doEffect (SPCurve * curve) override; + void doEffect(SPCurve *curve) override; private: - OriginalPathParam linked_path; - OriginalPathParam second_path; + OriginalPathParam linked_path; + OriginalPathParam second_path; BoolParam reverse_second; BoolParam join; BoolParam close; private: - LPEFillBetweenStrokes(const LPEFillBetweenStrokes&) = delete; - LPEFillBetweenStrokes& operator=(const LPEFillBetweenStrokes&) = delete; + LPEFillBetweenStrokes(const LPEFillBetweenStrokes &) = delete; + LPEFillBetweenStrokes &operator=(const LPEFillBetweenStrokes &) = delete; }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-fillet-chamfer.cpp b/src/live_effects/lpe-fillet-chamfer.cpp index e52743e03ec5e22081972f070a2680193ca052c5..439ead253263d0f45371db588f363faa935b73b7 100644 --- a/src/live_effects/lpe-fillet-chamfer.cpp +++ b/src/live_effects/lpe-fillet-chamfer.cpp @@ -11,17 +11,16 @@ #include "live_effects/lpe-fillet-chamfer.h" -#include "helper/geom.h" -#include "helper/geom-curves.h" -#include "helper/geom-satellite.h" - -#include "display/curve.h" -#include "knotholder.h" -#include "ui/tools/tool-base.h" #include <2geom/elliptical-arc.h> #include +#include "display/curve.h" +#include "helper/geom-curves.h" +#include "helper/geom-satellite.h" +#include "helper/geom.h" +#include "knotholder.h" #include "object/sp-shape.h" +#include "ui/tools/tool-base.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -29,40 +28,30 @@ namespace Inkscape { namespace LivePathEffect { -static const Util::EnumData FilletmethodData[] = { - { FM_AUTO, N_("Auto"), "auto" }, - { FM_ARC, N_("Force arc"), "arc" }, - { FM_BEZIER, N_("Force bezier"), "bezier" } -}; +static const Util::EnumData FilletmethodData[] = {{FM_AUTO, N_("Auto"), "auto"}, + {FM_ARC, N_("Force arc"), "arc"}, + {FM_BEZIER, N_("Force bezier"), "bezier"}}; static const Util::EnumDataConverter FMConverter(FilletmethodData, FM_END); LPEFilletChamfer::LPEFilletChamfer(LivePathEffectObject *lpeobject) - : Effect(lpeobject), - unit(_("Unit:"), _("Unit"), "unit", &wr, this, "px"), - satellites_param("Satellites_param", "Satellites_param", - "satellites_param", &wr, this), - method(_("Method:"), _("Method to calculate the fillet or chamfer"), - "method", FMConverter, &wr, this, FM_AUTO), - mode(_("Mode:"), _("Mode, e.g. fillet or chamfer"), - "mode", &wr, this, "F", true), - radius(_("Radius:"), _("Radius, in unit or %"), "radius", &wr, - this, 0.0), - chamfer_steps(_("Chamfer steps:"), _("Chamfer steps"), "chamfer_steps", - &wr, this, 1), - flexible(_("Radius in %"), _("Flexible radius size (%)"), - "flexible", &wr, this, false), - only_selected(_("Change only selected nodes"), - _("Change only selected nodes"), "only_selected", &wr, this, - false), - use_knot_distance(_("Use knots distance instead radius"), - _("Use knots distance instead radius"), - "use_knot_distance", &wr, this, true), - hide_knots(_("Hide knots"), _("Hide knots"), "hide_knots", &wr, this, - false), - apply_no_radius(_("Apply changes if radius = 0"), _("Apply changes if radius = 0"), "apply_no_radius", &wr, this, true), - apply_with_radius(_("Apply changes if radius > 0"), _("Apply changes if radius > 0"), "apply_with_radius", &wr, this, true), - _pathvector_satellites(nullptr), - _degenerate_hide(false) + : Effect(lpeobject) + , unit(_("Unit:"), _("Unit"), "unit", &wr, this, "px") + , satellites_param("Satellites_param", "Satellites_param", "satellites_param", &wr, this) + , method(_("Method:"), _("Method to calculate the fillet or chamfer"), "method", FMConverter, &wr, this, FM_AUTO) + , mode(_("Mode:"), _("Mode, e.g. fillet or chamfer"), "mode", &wr, this, "F", true) + , radius(_("Radius:"), _("Radius, in unit or %"), "radius", &wr, this, 0.0) + , chamfer_steps(_("Chamfer steps:"), _("Chamfer steps"), "chamfer_steps", &wr, this, 1) + , flexible(_("Radius in %"), _("Flexible radius size (%)"), "flexible", &wr, this, false) + , only_selected(_("Change only selected nodes"), _("Change only selected nodes"), "only_selected", &wr, this, false) + , use_knot_distance(_("Use knots distance instead radius"), _("Use knots distance instead radius"), + "use_knot_distance", &wr, this, true) + , hide_knots(_("Hide knots"), _("Hide knots"), "hide_knots", &wr, this, false) + , apply_no_radius(_("Apply changes if radius = 0"), _("Apply changes if radius = 0"), "apply_no_radius", &wr, this, + true) + , apply_with_radius(_("Apply changes if radius > 0"), _("Apply changes if radius > 0"), "apply_with_radius", &wr, + this, true) + , _pathvector_satellites(nullptr) + , _degenerate_hide(false) { registerParameter(&satellites_param); registerParameter(&unit); @@ -103,15 +92,15 @@ void LPEFilletChamfer::doOnApply(SPLPEItem const *lpeItem) power = Inkscape::Util::Quantity::convert(power, unit.get_abbreviation(), display_unit.c_str()); } SatelliteType satellite_type = FILLET; - std::map gchar_map_to_satellite_type = - boost::assign::map_list_of("F", FILLET)("IF", INVERSE_FILLET)("C", CHAMFER)("IC", INVERSE_CHAMFER)("KO", INVALID_SATELLITE); + std::map gchar_map_to_satellite_type = boost::assign::map_list_of("F", FILLET)( + "IF", INVERSE_FILLET)("C", CHAMFER)("IC", INVERSE_CHAMFER)("KO", INVALID_SATELLITE); auto mode_str = mode.param_getSVGValue(); std::map::iterator it = gchar_map_to_satellite_type.find(mode_str.raw()); if (it != gchar_map_to_satellite_type.end()) { satellite_type = it->second; } Geom::PathVector pathvres; - for (const auto & path_it : pathv) { + for (const auto &path_it : pathv) { if (path_it.empty() || count_path_nodes(path_it) < 2) { continue; } @@ -146,10 +135,10 @@ void LPEFilletChamfer::doOnApply(SPLPEItem const *lpeItem) subpath_satellites.push_back(satellite); } - //we add the last satellite on open path because _pathvector_satellites is related to nodes, not curves - //so maybe in the future we can need this last satellite in other effects - //don't remove for this effect because _pathvector_satellites class has methods when the path is modified - //and we want one method for all uses + // we add the last satellite on open path because _pathvector_satellites is related to nodes, not curves + // so maybe in the future we can need this last satellite in other effects + // don't remove for this effect because _pathvector_satellites class has methods when the path is modified + // and we want one method for all uses if (!path_it.closed()) { Satellite satellite(satellite_type); satellite.setSteps(chamfer_steps); @@ -192,8 +181,7 @@ Gtk::Widget *LPEFilletChamfer::newWidget() if (param->param_key == "radius") { Inkscape::UI::Widget::Scalar *widg_registered = Gtk::manage(dynamic_cast(widg)); - widg_registered->signal_value_changed().connect( - sigc::mem_fun(*this, &LPEFilletChamfer::updateAmount)); + widg_registered->signal_value_changed().connect(sigc::mem_fun(*this, &LPEFilletChamfer::updateAmount)); widg = widg_registered; if (widg) { Gtk::HBox *scalar_parameter = dynamic_cast(widg); @@ -231,30 +219,30 @@ Gtk::Widget *LPEFilletChamfer::newWidget() } Gtk::HBox *fillet_container = Gtk::manage(new Gtk::HBox(true, 0)); - Gtk::Button *fillet = Gtk::manage(new Gtk::Button(Glib::ustring(_("Fillet")))); - fillet->signal_clicked() - .connect(sigc::bind(sigc::mem_fun(*this, &LPEFilletChamfer::updateSatelliteType),FILLET)); + Gtk::Button *fillet = Gtk::manage(new Gtk::Button(Glib::ustring(_("Fillet")))); + fillet->signal_clicked().connect( + sigc::bind(sigc::mem_fun(*this, &LPEFilletChamfer::updateSatelliteType), FILLET)); fillet_container->pack_start(*fillet, true, true, 2); Gtk::Button *inverse_fillet = Gtk::manage(new Gtk::Button(Glib::ustring(_("Inverse fillet")))); - inverse_fillet->signal_clicked() - .connect(sigc::bind(sigc::mem_fun(*this, &LPEFilletChamfer::updateSatelliteType),INVERSE_FILLET)); + inverse_fillet->signal_clicked().connect( + sigc::bind(sigc::mem_fun(*this, &LPEFilletChamfer::updateSatelliteType), INVERSE_FILLET)); fillet_container->pack_start(*inverse_fillet, true, true, 2); Gtk::HBox *chamfer_container = Gtk::manage(new Gtk::HBox(true, 0)); Gtk::Button *chamfer = Gtk::manage(new Gtk::Button(Glib::ustring(_("Chamfer")))); - chamfer->signal_clicked() - .connect(sigc::bind(sigc::mem_fun(*this, &LPEFilletChamfer::updateSatelliteType),CHAMFER)); + chamfer->signal_clicked().connect( + sigc::bind(sigc::mem_fun(*this, &LPEFilletChamfer::updateSatelliteType), CHAMFER)); chamfer_container->pack_start(*chamfer, true, true, 2); Gtk::Button *inverse_chamfer = Gtk::manage(new Gtk::Button(Glib::ustring(_("Inverse chamfer")))); - inverse_chamfer->signal_clicked() - .connect(sigc::bind(sigc::mem_fun(*this, &LPEFilletChamfer::updateSatelliteType),INVERSE_CHAMFER)); + inverse_chamfer->signal_clicked().connect( + sigc::bind(sigc::mem_fun(*this, &LPEFilletChamfer::updateSatelliteType), INVERSE_CHAMFER)); chamfer_container->pack_start(*inverse_chamfer, true, true, 2); vbox->pack_start(*fillet_container, true, true, 2); vbox->pack_start(*chamfer_container, true, true, 2); - if(Gtk::Widget* widg = defaultParamSet()) { + if (Gtk::Widget *widg = defaultParamSet()) { vbox->pack_start(*widg, true, true, 2); } return vbox; @@ -276,8 +264,8 @@ void LPEFilletChamfer::updateAmount() Glib::ustring display_unit = document->getDisplayUnit()->abbr.c_str(); power = Inkscape::Util::Quantity::convert(power, unit.get_abbreviation(), display_unit.c_str()); } - _pathvector_satellites->updateAmount(power, apply_no_radius, apply_with_radius, only_selected, - use_knot_distance, flexible); + _pathvector_satellites->updateAmount(power, apply_no_radius, apply_with_radius, only_selected, use_knot_distance, + flexible); satellites_param.setPathVectorSatellites(_pathvector_satellites); } @@ -290,21 +278,22 @@ void LPEFilletChamfer::updateChamferSteps() void LPEFilletChamfer::updateSatelliteType(SatelliteType satellitetype) { - std::map satellite_type_to_gchar_map = - boost::assign::map_list_of(FILLET, "F")(INVERSE_FILLET, "IF")(CHAMFER, "C")(INVERSE_CHAMFER, "IC")(INVALID_SATELLITE, "KO"); + std::map satellite_type_to_gchar_map = boost::assign::map_list_of(FILLET, "F")( + INVERSE_FILLET, "IF")(CHAMFER, "C")(INVERSE_CHAMFER, "IC")(INVALID_SATELLITE, "KO"); mode.param_setValue((Glib::ustring)satellite_type_to_gchar_map.at(satellitetype)); setSelected(_pathvector_satellites); _pathvector_satellites->updateSatelliteType(satellitetype, apply_no_radius, apply_with_radius, only_selected); satellites_param.setPathVectorSatellites(_pathvector_satellites); } -void LPEFilletChamfer::setSelected(PathVectorSatellites *_pathvector_satellites){ +void LPEFilletChamfer::setSelected(PathVectorSatellites *_pathvector_satellites) +{ Geom::PathVector const pathv = _pathvector_satellites->getPathVector(); Satellites satellites = _pathvector_satellites->getSatellites(); for (size_t i = 0; i < satellites.size(); ++i) { for (size_t j = 0; j < satellites[i].size(); ++j) { Geom::Curve const &curve_in = pathv[i][j]; - if (only_selected && isNodePointSelected(curve_in.initialPoint()) ){ + if (only_selected && isNodePointSelected(curve_in.initialPoint())) { satellites[i][j].setSelected(true); } else { satellites[i][j].setSelected(false); @@ -317,10 +306,10 @@ void LPEFilletChamfer::setSelected(PathVectorSatellites *_pathvector_satellites) void LPEFilletChamfer::doBeforeEffect(SPLPEItem const *lpeItem) { if (!pathvector_before_effect.empty()) { - //fillet chamfer specific calls + // fillet chamfer specific calls satellites_param.setUseDistance(use_knot_distance); satellites_param.setCurrentZoom(current_zoom); - //mandatory call + // mandatory call satellites_param.setEffectType(effectType()); Geom::PathVector const pathv = pathv_to_linear_and_cubic_beziers(pathvector_before_effect); Geom::PathVector pathvres; @@ -349,7 +338,7 @@ void LPEFilletChamfer::doBeforeEffect(SPLPEItem const *lpeItem) } if (Geom::are_near((*curve_it).initialPoint(), (*curve_it).finalPoint())) { return; - } + } pathresult.append(*curve_it); ++curve_it; } @@ -374,8 +363,8 @@ void LPEFilletChamfer::doBeforeEffect(SPLPEItem const *lpeItem) power = Inkscape::Util::Quantity::convert(power, unit.get_abbreviation(), display_unit.c_str()); } SatelliteType satellite_type = FILLET; - std::map gchar_map_to_satellite_type = - boost::assign::map_list_of("F", FILLET)("IF", INVERSE_FILLET)("C", CHAMFER)("IC", INVERSE_CHAMFER)("KO", INVALID_SATELLITE); + std::map gchar_map_to_satellite_type = boost::assign::map_list_of( + "F", FILLET)("IF", INVERSE_FILLET)("C", CHAMFER)("IC", INVERSE_CHAMFER)("KO", INVALID_SATELLITE); auto mode_str = mode.param_getSVGValue(); std::map::iterator it = gchar_map_to_satellite_type.find(mode_str.raw()); if (it != gchar_map_to_satellite_type.end()) { @@ -392,7 +381,7 @@ void LPEFilletChamfer::doBeforeEffect(SPLPEItem const *lpeItem) write = true; } } - + if (_degenerate_hide) { satellites_param.setGlobalKnotHide(true); } else { @@ -419,7 +408,7 @@ void LPEFilletChamfer::doBeforeEffect(SPLPEItem const *lpeItem) } } satellites[i][j].hidden = hide_knots; - if (only_selected && isNodePointSelected(curve_in.initialPoint()) ){ + if (only_selected && isNodePointSelected(curve_in.initialPoint())) { satellites[i][j].setSelected(true); } } @@ -456,14 +445,13 @@ void LPEFilletChamfer::doBeforeEffect(SPLPEItem const *lpeItem) } } -void -LPEFilletChamfer::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) +void LPEFilletChamfer::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { hp_vec.push_back(_hp); } -void -LPEFilletChamfer::addChamferSteps(Geom::Path &tmp_path, Geom::Path path_chamfer, Geom::Point end_arc_point, size_t steps) +void LPEFilletChamfer::addChamferSteps(Geom::Path &tmp_path, Geom::Path path_chamfer, Geom::Point end_arc_point, + size_t steps) { setSelected(_pathvector_satellites); double path_subdivision = 1.0 / steps; @@ -474,8 +462,7 @@ LPEFilletChamfer::addChamferSteps(Geom::Path &tmp_path, Geom::Path path_chamfer, tmp_path.appendNew(end_arc_point); } -Geom::PathVector -LPEFilletChamfer::doEffect_path(Geom::PathVector const &path_in) +Geom::PathVector LPEFilletChamfer::doEffect_path(Geom::PathVector const &path_in) { const double GAP_HELPER = 0.00001; Geom::PathVector path_out; @@ -508,10 +495,10 @@ LPEFilletChamfer::doEffect_path(Geom::PathVector const &path_in) if (curve == count_path_nodes(pathv[path]) - 1 && pathv[path].closed()) { next_index = 0; } - //append last extreme of paths on open paths + // append last extreme of paths on open paths if (curve == count_path_nodes(pathv[path]) - 1 && !pathv[path].closed()) { // the path is open and we are at // end of path - if (time0 != 1) { //Previous satellite not at 100% amount + if (time0 != 1) { // Previous satellite not at 100% amount Geom::Curve *last_curve = curve_it1->portion(time0, 1); last_curve->setInitial(tmp_path.finalPoint()); tmp_path.append(*last_curve); @@ -526,7 +513,7 @@ LPEFilletChamfer::doEffect_path(Geom::PathVector const &path_in) g_warning("Knots hidden if consecutive nodes has the same position."); return path_in; } - if (!curve) { //curve == 0 + if (!curve) { // curve == 0 if (!path_it.closed()) { time0 = 0; } else { @@ -552,7 +539,7 @@ LPEFilletChamfer::doEffect_path(Geom::PathVector const &path_in) Geom::Point start_arc_point = knot_curve_1->finalPoint(); Geom::Point end_arc_point = curve_it2.pointAt(time2); - //add a gap helper + // add a gap helper if (time2 == 1) { end_arc_point = curve_it2.pointAt(time2 - GAP_HELPER); } @@ -588,14 +575,14 @@ LPEFilletChamfer::doEffect_path(Geom::PathVector const &path_in) handle_1 = start_arc_point; inverse_handle_1 = start_arc_point; } - //remove gap helper + // remove gap helper if (time2 == 1) { end_arc_point = curve_it2.pointAt(time2); } if (time1 == time0) { start_arc_point = curve_it1->pointAt(time0); } - if (time1 != 1 && !Geom::are_near(angle,Geom::rad_from_deg(360))) { + if (time1 != 1 && !Geom::are_near(angle, Geom::rad_from_deg(360))) { if (time1 != time0 || (time1 == 1 && time0 == 1)) { if (!knot_curve_1->isDegenerate()) { tmp_path.append(*knot_curve_1); @@ -603,53 +590,52 @@ LPEFilletChamfer::doEffect_path(Geom::PathVector const &path_in) } SatelliteType type = satellite.satellite_type; size_t steps = satellite.steps; - if (!steps) steps = 1; + if (!steps) + steps = 1; Geom::Line const x_line(Geom::Point(0, 0), Geom::Point(1, 0)); Geom::Line const angled_line(start_arc_point, end_arc_point); double arc_angle = Geom::angle_between(x_line, angled_line); - double radius = Geom::distance(start_arc_point, middle_point(start_arc_point, end_arc_point)) / - sin(angle / 2.0); + double radius = + Geom::distance(start_arc_point, middle_point(start_arc_point, end_arc_point)) / sin(angle / 2.0); Geom::Coord rx = radius; Geom::Coord ry = rx; - bool eliptical = (is_straight_curve(*curve_it1) && - is_straight_curve(curve_it2) && method != FM_BEZIER) || - method == FM_ARC; + bool eliptical = + (is_straight_curve(*curve_it1) && is_straight_curve(curve_it2) && method != FM_BEZIER) || + method == FM_ARC; switch (type) { - case CHAMFER: - { + case CHAMFER: { Geom::Path path_chamfer; path_chamfer.start(tmp_path.finalPoint()); if (eliptical) { ccw_toggle = ccw_toggle ? false : true; - path_chamfer.appendNew(rx, ry, arc_angle, 0, ccw_toggle, end_arc_point); + path_chamfer.appendNew(rx, ry, arc_angle, 0, ccw_toggle, + end_arc_point); } else { path_chamfer.appendNew(handle_1, handle_2, end_arc_point); } addChamferSteps(tmp_path, path_chamfer, end_arc_point, steps); - } - break; - case INVERSE_CHAMFER: - { + } break; + case INVERSE_CHAMFER: { Geom::Path path_chamfer; path_chamfer.start(tmp_path.finalPoint()); if (eliptical) { - path_chamfer.appendNew(rx, ry, arc_angle, 0, ccw_toggle, end_arc_point); + path_chamfer.appendNew(rx, ry, arc_angle, 0, ccw_toggle, + end_arc_point); } else { - path_chamfer.appendNew(inverse_handle_1, inverse_handle_2, end_arc_point); + path_chamfer.appendNew(inverse_handle_1, inverse_handle_2, + end_arc_point); } addChamferSteps(tmp_path, path_chamfer, end_arc_point, steps); - } - break; - case INVERSE_FILLET: - { + } break; + case INVERSE_FILLET: { if (eliptical) { tmp_path.appendNew(rx, ry, arc_angle, 0, ccw_toggle, end_arc_point); } else { tmp_path.appendNew(inverse_handle_1, inverse_handle_2, end_arc_point); } - } - break; - default: //fillet + } break; + default + : // fillet { if (eliptical) { ccw_toggle = ccw_toggle ? false : true; @@ -657,8 +643,7 @@ LPEFilletChamfer::doEffect_path(Geom::PathVector const &path_in) } else { tmp_path.appendNew(handle_1, handle_2, end_arc_point); } - } - break; + } break; } } else { if (!knot_curve_1->isDegenerate()) { @@ -683,7 +668,7 @@ LPEFilletChamfer::doEffect_path(Geom::PathVector const &path_in) return path_out; } -}; //namespace LivePathEffect +}; // namespace LivePathEffect }; /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-fillet-chamfer.h b/src/live_effects/lpe-fillet-chamfer.h index 71f0f5e738aac7b050da1a367fe6f519c4865f81..83a32ff04ef4fa4210b8a98d5f8cd04f5fa89c5e 100644 --- a/src/live_effects/lpe-fillet-chamfer.h +++ b/src/live_effects/lpe-fillet-chamfer.h @@ -13,25 +13,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "helper/geom-pathvectorsatellites.h" +#include "helper/geom-satellite.h" +#include "live_effects/effect.h" #include "live_effects/parameter/enum.h" +#include "live_effects/parameter/hidden.h" #include "live_effects/parameter/satellitesarray.h" -#include "live_effects/effect.h" #include "live_effects/parameter/unit.h" -#include "live_effects/parameter/hidden.h" -#include "helper/geom-pathvectorsatellites.h" -#include "helper/geom-satellite.h" namespace Inkscape { namespace LivePathEffect { -enum Filletmethod { +enum Filletmethod +{ FM_AUTO, FM_ARC, FM_BEZIER, FM_END }; -class LPEFilletChamfer : public Effect { +class LPEFilletChamfer : public Effect +{ public: LPEFilletChamfer(LivePathEffectObject *lpeobject); void doBeforeEffect(SPLPEItem const *lpeItem) override; @@ -40,10 +42,10 @@ public: Gtk::Widget *newWidget() override; Geom::Ray getRay(Geom::Point start, Geom::Point end, Geom::Curve *curve, bool reverse); void addChamferSteps(Geom::Path &tmp_path, Geom::Path path_chamfer, Geom::Point end_arc_point, size_t steps); - void addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) override; + void addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) override; void updateSatelliteType(SatelliteType satellitetype); void setSelected(PathVectorSatellites *_pathvector_satellites); - //void convertUnit(); + // void convertUnit(); void updateChamferSteps(); void updateAmount(); void refreshKnots(); @@ -68,11 +70,10 @@ private: Glib::ustring previous_unit; LPEFilletChamfer(const LPEFilletChamfer &); LPEFilletChamfer &operator=(const LPEFilletChamfer &); - }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-gears.cpp b/src/live_effects/lpe-gears.cpp index 465fcbe9dab568cd68bb8f4bbee34ec5976842cc..69553e9eb2f8a7c0565549fe1a32c46bba2c2b63 100644 --- a/src/live_effects/lpe-gears.cpp +++ b/src/live_effects/lpe-gears.cpp @@ -8,50 +8,52 @@ */ #include "live_effects/lpe-gears.h" + #include <2geom/bezier-to-sbasis.h> // TODO due to internal breakage in glibmm headers, this must be last: #include using namespace Geom; -class Gear { +class Gear +{ public: // pitch circles touch on two properly meshed gears // all measurements are taken from the pitch circle - double pitch_diameter() {return (_number_of_teeth * _module) / M_PI;} - double pitch_radius() {return pitch_diameter() / 2.0;} - void pitch_radius(double R) {_module = (2 * M_PI * R) / _number_of_teeth;} + double pitch_diameter() { return (_number_of_teeth * _module) / M_PI; } + double pitch_radius() { return pitch_diameter() / 2.0; } + void pitch_radius(double R) { _module = (2 * M_PI * R) / _number_of_teeth; } // base circle serves as the basis for the involute toothe profile - double base_diameter() {return pitch_diameter() * cos(_pressure_angle);} - double base_radius() {return base_diameter() / 2.0;} + double base_diameter() { return pitch_diameter() * cos(_pressure_angle); } + double base_radius() { return base_diameter() / 2.0; } // diametrical pitch - double diametrical_pitch() {return _number_of_teeth / pitch_diameter();} + double diametrical_pitch() { return _number_of_teeth / pitch_diameter(); } // height of the tooth above the pitch circle - double addendum() {return 1.0 / diametrical_pitch();} + double addendum() { return 1.0 / diametrical_pitch(); } // depth of the tooth below the pitch circle - double dedendum() {return addendum() + _clearance;} + double dedendum() { return addendum() + _clearance; } // root circle specifies the bottom of the fillet between teeth - double root_radius() {return pitch_radius() - dedendum();} - double root_diameter() {return root_radius() * 2.0;} + double root_radius() { return pitch_radius() - dedendum(); } + double root_diameter() { return root_radius() * 2.0; } // outer circle is the outside diameter of the gear - double outer_radius() {return pitch_radius() + addendum();} - double outer_diameter() {return outer_radius() * 2.0;} + double outer_radius() { return pitch_radius() + addendum(); } + double outer_diameter() { return outer_radius() * 2.0; } // angle covered by the tooth on the pitch circle - double tooth_thickness_angle() {return M_PI / _number_of_teeth;} + double tooth_thickness_angle() { return M_PI / _number_of_teeth; } - Geom::Point centre() {return _centre;} - void centre(Geom::Point c) {_centre = c;} + Geom::Point centre() { return _centre; } + void centre(Geom::Point c) { _centre = c; } - double angle() {return _angle;} - void angle(double a) {_angle = a;} + double angle() { return _angle; } + void angle(double a) { _angle = a; } - int number_of_teeth() {return _number_of_teeth;} + int number_of_teeth() { return _number_of_teeth; } Geom::Path path(); Gear spawn(Geom::Point p); @@ -60,8 +62,8 @@ public: : _number_of_teeth(n) , _pressure_angle(phi) , _module(m) - { - } + {} + private: int _number_of_teeth; double _pressure_angle; @@ -69,48 +71,55 @@ private: double _clearance = 0.0; double _angle = 0.0; Geom::Point _centre; - D2 _involute(double start, double stop) { + D2 _involute(double start, double stop) + { D2 B; D2 I; - Linear bo = Linear(start,stop); + Linear bo = Linear(start, stop); - B[0] = cos(bo,2); - B[1] = sin(bo,2); + B[0] = cos(bo, 2); + B[1] = sin(bo, 2); - I = B - Linear(0,1) * derivative(B); - I = I*base_radius() + _centre; + I = B - Linear(0, 1) * derivative(B); + I = I * base_radius() + _centre; return I; } - D2 _arc(double start, double stop, double R) { + D2 _arc(double start, double stop, double R) + { D2 B; - Linear bo = Linear(start,stop); + Linear bo = Linear(start, stop); - B[0] = cos(bo,2); - B[1] = sin(bo,2); + B[0] = cos(bo, 2); + B[1] = sin(bo, 2); - B = B*R + _centre; + B = B * R + _centre; return B; } // angle of the base circle used to create the involute to a certain radius - double involute_swath_angle(double R) { - if (R <= base_radius()) return 0.0; - return sqrt(R*R - base_radius()*base_radius())/base_radius(); + double involute_swath_angle(double R) + { + if (R <= base_radius()) + return 0.0; + return sqrt(R * R - base_radius() * base_radius()) / base_radius(); } // angle of the base circle between the origin of the involute and the intersection on another radius - double involute_intersect_angle(double R) { - if (R <= base_radius()) return 0.0; - return (sqrt(R*R - base_radius()*base_radius())/base_radius()) - acos(base_radius()/R); + double involute_intersect_angle(double R) + { + if (R <= base_radius()) + return 0.0; + return (sqrt(R * R - base_radius() * base_radius()) / base_radius()) - acos(base_radius() / R); } }; -static void -makeContinuous(D2 &a, Point const b) { - for(unsigned d=0;d<2;d++) +static void makeContinuous(D2 &a, Point const b) +{ + for (unsigned d = 0; d < 2; d++) a[d][0][0] = b[d]; } -Geom::Path Gear::path() { +Geom::Path Gear::path() +{ Geom::Path pb; // angle covered by a full tooth and fillet @@ -118,34 +127,37 @@ Geom::Path Gear::path() { // angle covered by an involute double involute_advance = involute_intersect_angle(outer_radius()) - involute_intersect_angle(root_radius()); // angle covered by the tooth tip - double tip_advance = tooth_thickness_angle() - (2 * (involute_intersect_angle(outer_radius()) - involute_intersect_angle(pitch_radius()))); + double tip_advance = tooth_thickness_angle() - + (2 * (involute_intersect_angle(outer_radius()) - involute_intersect_angle(pitch_radius()))); // angle covered by the toothe root double root_advance = (tooth_rotation - tip_advance) - (2.0 * involute_advance); // begin drawing the involute at t if the root circle is larger than the base circle - double involute_t = involute_swath_angle(root_radius())/involute_swath_angle(outer_radius()); + double involute_t = involute_swath_angle(root_radius()) / involute_swath_angle(outer_radius()); - //rewind angle to start drawing from the leading edge of the tooth + // rewind angle to start drawing from the leading edge of the tooth double first_tooth_angle = _angle - ((0.5 * tip_advance) + involute_advance); Geom::Point prev; - for (int i=0; i < _number_of_teeth; i++) - { + for (int i = 0; i < _number_of_teeth; i++) { double cursor = first_tooth_angle + (i * tooth_rotation); - D2 leading_I = compose(_involute(cursor, cursor + involute_swath_angle(outer_radius())), Linear(involute_t,1)); - if(i != 0) makeContinuous(leading_I, prev); + D2 leading_I = + compose(_involute(cursor, cursor + involute_swath_angle(outer_radius())), Linear(involute_t, 1)); + if (i != 0) + makeContinuous(leading_I, prev); pb.append(SBasisCurve(leading_I)); cursor += involute_advance; prev = leading_I.at1(); - D2 tip = _arc(cursor, cursor+tip_advance, outer_radius()); + D2 tip = _arc(cursor, cursor + tip_advance, outer_radius()); makeContinuous(tip, prev); pb.append(SBasisCurve(tip)); cursor += tip_advance; prev = tip.at1(); cursor += involute_advance; - D2 trailing_I = compose(_involute(cursor, cursor - involute_swath_angle(outer_radius())), Linear(1,involute_t)); + D2 trailing_I = + compose(_involute(cursor, cursor - involute_swath_angle(outer_radius())), Linear(1, involute_t)); makeContinuous(trailing_I, prev); pb.append(SBasisCurve(trailing_I)); prev = trailing_I.at1(); @@ -157,10 +169,10 @@ Geom::Path Gear::path() { pb.appendNew(leading_end); } - D2 root = _arc(cursor, cursor+root_advance, root_radius()); + D2 root = _arc(cursor, cursor + root_advance, root_radius()); makeContinuous(root, prev); pb.append(SBasisCurve(root)); - //cursor += root_advance; + // cursor += root_advance; prev = root.at1(); if (base_radius() > root_radius()) { @@ -174,9 +186,10 @@ Geom::Path Gear::path() { return pb; } -Gear Gear::spawn(Geom::Point p) { +Gear Gear::spawn(Geom::Point p) +{ double radius = Geom::distance(this->centre(), p) - this->pitch_radius(); - int N = (int) floor( (radius / this->pitch_radius()) * this->number_of_teeth() ); + int N = (int)floor((radius / this->pitch_radius()) * this->number_of_teeth()); Gear gear(N, _module, _pressure_angle); gear.centre(p); @@ -191,21 +204,17 @@ Gear Gear::spawn(Geom::Point p) { return gear; } - - // ################################################################# - - namespace Inkscape { namespace LivePathEffect { - -LPEGears::LPEGears(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - teeth(_("_Teeth:"), _("The number of teeth"), "teeth", &wr, this, 10), - phi(_("_Phi:"), _("Tooth pressure angle (typically 20-25 deg). The ratio of teeth not in contact."), "phi", &wr, this, 5), - min_radius(_("Min Radius:"), _("Minimum radius, low values can be slow"), "min_radius", &wr, this, 5.0) +LPEGears::LPEGears(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , teeth(_("_Teeth:"), _("The number of teeth"), "teeth", &wr, this, 10) + , phi(_("_Phi:"), _("Tooth pressure angle (typically 20-25 deg). The ratio of teeth not in contact."), "phi", &wr, + this, 5) + , min_radius(_("Min Radius:"), _("Minimum radius, low values can be slow"), "min_radius", &wr, this, 5.0) { /* Tooth pressure angle: The angle between the tooth profile and a perpendicular to the pitch * circle, usually at the point where the pitch circle meets the tooth profile. Standard angles @@ -222,38 +231,38 @@ LPEGears::LPEGears(LivePathEffectObject *lpeobject) : registerParameter(&min_radius); } -LPEGears::~LPEGears() -= default; +LPEGears::~LPEGears() = default; -Geom::PathVector -LPEGears::doEffect_path (Geom::PathVector const &path_in) +Geom::PathVector LPEGears::doEffect_path(Geom::PathVector const &path_in) { Geom::PathVector path_out; Geom::Path gearpath = path_in[0]; Geom::Path::iterator it(gearpath.begin()); - if ( it == gearpath.end() ) return path_out; + if (it == gearpath.end()) + return path_out; - Gear * gear = new Gear(teeth, 200.0, phi * M_PI / 180); + Gear *gear = new Gear(teeth, 200.0, phi * M_PI / 180); Geom::Point gear_centre = (*it).finalPoint(); gear->centre(gear_centre); gear->angle(atan2((*it).initialPoint() - gear_centre)); ++it; - if ( it == gearpath.end() ) return path_out; + if (it == gearpath.end()) + return path_out; double radius = Geom::distance(gear_centre, (*it).finalPoint()); - radius = radius < min_radius?min_radius:radius; + radius = radius < min_radius ? min_radius : radius; gear->pitch_radius(radius); - path_out.push_back( gear->path()); - - for (++it; it != gearpath.end() ; ++it) { + path_out.push_back(gear->path()); + + for (++it; it != gearpath.end(); ++it) { if (are_near((*it).initialPoint(), (*it).finalPoint())) { continue; } // iterate through Geom::Curve in path_in - Gear* gearnew = new Gear(gear->spawn( (*it).finalPoint() )); - path_out.push_back( gearnew->path() ); + Gear *gearnew = new Gear(gear->spawn((*it).finalPoint())); + path_out.push_back(gearnew->path()); delete gear; gear = gearnew; } diff --git a/src/live_effects/lpe-gears.h b/src/live_effects/lpe-gears.h index eb5ec8a2caa345d8f05e22cdf5b0cd8c07bb3fc9..c6966289d5b4707ac45b208951805bdc0b91905d 100644 --- a/src/live_effects/lpe-gears.h +++ b/src/live_effects/lpe-gears.h @@ -18,7 +18,8 @@ namespace Inkscape { namespace LivePathEffect { -class LPEGears : public Effect { +class LPEGears : public Effect +{ public: LPEGears(LivePathEffectObject *lpeobject); ~LPEGears() override; @@ -30,11 +31,11 @@ private: ScalarParam phi; ScalarParam min_radius; - LPEGears(const LPEGears&) = delete; - LPEGears& operator=(const LPEGears&) = delete; + LPEGears(const LPEGears &) = delete; + LPEGears &operator=(const LPEGears &) = delete; }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-interpolate.cpp b/src/live_effects/lpe-interpolate.cpp index 3da8726f264f872e6d7d105d7aab8bafc00c4997..e64674b3d43649e61255213fceba475895479c87 100644 --- a/src/live_effects/lpe-interpolate.cpp +++ b/src/live_effects/lpe-interpolate.cpp @@ -15,13 +15,11 @@ #include <2geom/sbasis-to-bezier.h> #include "display/curve.h" - #include "object/sp-path.h" // TODO due to internal breakage in glibmm headers, this must be last: #include - namespace Inkscape { namespace LivePathEffect { @@ -69,8 +67,8 @@ Geom::PathVector LPEInterpolate::doEffect_path(Geom::PathVector const &path_in) Geom::PathVector path_out; - Geom::Piecewise > pwd2_A = path_in[0].toPwSb(); - Geom::Piecewise > pwd2_B = path_in[1].toPwSb(); + Geom::Piecewise> pwd2_A = path_in[0].toPwSb(); + Geom::Piecewise> pwd2_B = path_in[1].toPwSb(); // Transform both paths to (0,0) midpoint, so they can easily be positioned along interpolate_path Geom::OptRect bounds_A = Geom::bounds_exact(pwd2_A); @@ -84,8 +82,8 @@ Geom::PathVector LPEInterpolate::doEffect_path(Geom::PathVector const &path_in) // Make sure both paths have the same number of segments and cuts at the same locations pwd2_B.setDomain(pwd2_A.domain()); - Geom::Piecewise > pA = Geom::partition(pwd2_A, pwd2_B.cuts); - Geom::Piecewise > pB = Geom::partition(pwd2_B, pwd2_A.cuts); + Geom::Piecewise> pA = Geom::partition(pwd2_A, pwd2_B.cuts); + Geom::Piecewise> pB = Geom::partition(pwd2_B, pwd2_A.cuts); auto trajectory = calculate_trajectory(bounds_A, bounds_B); @@ -94,7 +92,7 @@ Geom::PathVector LPEInterpolate::doEffect_path(Geom::PathVector const &path_in) for (int i = 0; i < number_of_steps; ++i) { double fraction = i / (number_of_steps - 1); - Geom::Piecewise > pResult = pA * (1 - fraction) + pB * fraction; + Geom::Piecewise> pResult = pA * (1 - fraction) + pB * fraction; pResult += trajectory.valueAt(trajectory_domain.min() + fraction * trajectory_domain.extent()); Geom::PathVector pathv = Geom::path_from_piecewise(pResult, LPE_CONVERSION_TOLERANCE); @@ -104,14 +102,13 @@ Geom::PathVector LPEInterpolate::doEffect_path(Geom::PathVector const &path_in) return path_out; } - // returns the lpe parameter trajectory_path, transformed so that it starts at the // bounding box center of the first path and ends at the bounding box center of the // second path -Geom::Piecewise > LPEInterpolate::calculate_trajectory(Geom::OptRect bounds_A, - Geom::OptRect bounds_B) +Geom::Piecewise> LPEInterpolate::calculate_trajectory(Geom::OptRect bounds_A, + Geom::OptRect bounds_B) { - Geom::Piecewise > trajectory = trajectory_path.get_pathvector()[0].toPwSb(); + Geom::Piecewise> trajectory = trajectory_path.get_pathvector()[0].toPwSb(); if (equidistant_spacing) { trajectory = Geom::arc_length_parametrization(trajectory); @@ -165,8 +162,7 @@ void LPEInterpolate::resetDefaults(SPItem const *item) traj_pathv[0].start(bounds_A->midpoint()); traj_pathv[0].appendNew(bounds_B->midpoint()); trajectory_path.set_new_value(traj_pathv, true); - } - else { + } else { trajectory_path.param_set_and_write_default(); } } diff --git a/src/live_effects/lpe-interpolate.h b/src/live_effects/lpe-interpolate.h index 1c943965ee06be33dbc6f0218406d8977c8e5a22..52843d0698963c336f7f780e51d12bbd266c7ce8 100644 --- a/src/live_effects/lpe-interpolate.h +++ b/src/live_effects/lpe-interpolate.h @@ -23,8 +23,9 @@ namespace Inkscape { namespace LivePathEffect { -class LPEInterpolate : public Effect { - public: +class LPEInterpolate : public Effect +{ +public: LPEInterpolate(LivePathEffectObject *lpeobject); ~LPEInterpolate() override; @@ -33,12 +34,12 @@ class LPEInterpolate : public Effect { void resetDefaults(SPItem const *item) override; - private: +private: PathParam trajectory_path; ScalarParam number_of_steps; BoolParam equidistant_spacing; - Geom::Piecewise > calculate_trajectory(Geom::OptRect bounds_A, Geom::OptRect bounds_B); + Geom::Piecewise> calculate_trajectory(Geom::OptRect bounds_A, Geom::OptRect bounds_B); LPEInterpolate(const LPEInterpolate &) = delete; LPEInterpolate &operator=(const LPEInterpolate &) = delete; diff --git a/src/live_effects/lpe-interpolate_points.cpp b/src/live_effects/lpe-interpolate_points.cpp index 1d8481130987dc956189ddafba4237ca0d101754..554825c7ef61a8f754be91100c16942120187ac2 100644 --- a/src/live_effects/lpe-interpolate_points.cpp +++ b/src/live_effects/lpe-interpolate_points.cpp @@ -13,6 +13,7 @@ */ #include "live_effects/lpe-interpolate_points.h" + #include "live_effects/lpe-powerstroke-interpolators.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -20,15 +21,14 @@ namespace Inkscape { namespace LivePathEffect { - static const Util::EnumData InterpolatorTypeData[] = { - {Geom::Interpolate::INTERP_LINEAR , N_("Linear"), "Linear"}, - {Geom::Interpolate::INTERP_CUBICBEZIER , N_("CubicBezierFit"), "CubicBezierFit"}, - {Geom::Interpolate::INTERP_CUBICBEZIER_JOHAN , N_("CubicBezierJohan"), "CubicBezierJohan"}, - {Geom::Interpolate::INTERP_SPIRO , N_("SpiroInterpolator"), "SpiroInterpolator"}, - {Geom::Interpolate::INTERP_CENTRIPETAL_CATMULLROM, N_("Centripetal Catmull-Rom"), "CentripetalCatmullRom"} -}; -static const Util::EnumDataConverter InterpolatorTypeConverter(InterpolatorTypeData, sizeof(InterpolatorTypeData)/sizeof(*InterpolatorTypeData)); + {Geom::Interpolate::INTERP_LINEAR, N_("Linear"), "Linear"}, + {Geom::Interpolate::INTERP_CUBICBEZIER, N_("CubicBezierFit"), "CubicBezierFit"}, + {Geom::Interpolate::INTERP_CUBICBEZIER_JOHAN, N_("CubicBezierJohan"), "CubicBezierJohan"}, + {Geom::Interpolate::INTERP_SPIRO, N_("SpiroInterpolator"), "SpiroInterpolator"}, + {Geom::Interpolate::INTERP_CENTRIPETAL_CATMULLROM, N_("Centripetal Catmull-Rom"), "CentripetalCatmullRom"}}; +static const Util::EnumDataConverter + InterpolatorTypeConverter(InterpolatorTypeData, sizeof(InterpolatorTypeData) / sizeof(*InterpolatorTypeData)); LPEInterpolatePoints::LPEInterpolatePoints(LivePathEffectObject *lpeobject) : Effect(lpeobject) @@ -39,19 +39,18 @@ LPEInterpolatePoints::LPEInterpolatePoints(LivePathEffectObject *lpeobject) { show_orig_path = false; - registerParameter( &interpolator_type ); + registerParameter(&interpolator_type); } -LPEInterpolatePoints::~LPEInterpolatePoints() -= default; +LPEInterpolatePoints::~LPEInterpolatePoints() = default; -Geom::PathVector -LPEInterpolatePoints::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPEInterpolatePoints::doEffect_path(Geom::PathVector const &path_in) { Geom::PathVector path_out; - std::unique_ptr interpolator( Geom::Interpolate::Interpolator::create(static_cast(interpolator_type.get_value())) ); + std::unique_ptr interpolator(Geom::Interpolate::Interpolator::create( + static_cast(interpolator_type.get_value()))); - for(const auto & path_it : path_in) { + for (const auto &path_it : path_in) { if (path_it.empty()) continue; @@ -74,8 +73,7 @@ LPEInterpolatePoints::doEffect_path (Geom::PathVector const & path_in) return path_out; } - -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-interpolate_points.h b/src/live_effects/lpe-interpolate_points.h index 9b563cc4486a48cee4309454b69e0110a427fcc9..97da20901356d760f189920eff96e330648e1399 100644 --- a/src/live_effects/lpe-interpolate_points.h +++ b/src/live_effects/lpe-interpolate_points.h @@ -15,30 +15,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/enum.h" #include "live_effects/effect.h" +#include "live_effects/parameter/enum.h" namespace Inkscape { namespace LivePathEffect { -class LPEInterpolatePoints : public Effect { +class LPEInterpolatePoints : public Effect +{ public: LPEInterpolatePoints(LivePathEffectObject *lpeobject); ~LPEInterpolatePoints() override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; private: EnumParam interpolator_type; - LPEInterpolatePoints(const LPEInterpolatePoints&) = delete; - LPEInterpolatePoints& operator=(const LPEInterpolatePoints&) = delete; + LPEInterpolatePoints(const LPEInterpolatePoints &) = delete; + LPEInterpolatePoints &operator=(const LPEInterpolatePoints &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape -#endif // INKSCAPE_LPE_INTERPOLATEPOINTS_H +#endif // INKSCAPE_LPE_INTERPOLATEPOINTS_H /* Local Variables: diff --git a/src/live_effects/lpe-jointype.cpp b/src/live_effects/lpe-jointype.cpp index 4a8b6261c5e032c805e1e1b47e63732f22d50e13..b979762acc5c635830d61f3b04c851264799eead 100644 --- a/src/live_effects/lpe-jointype.cpp +++ b/src/live_effects/lpe-jointype.cpp @@ -8,25 +8,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/enum.h" -#include "live_effects/fill-conversion.h" -#include "helper/geom-pathstroke.h" +#include "lpe-jointype.h" -#include "desktop-style.h" +#include <2geom/elliptical-arc.h> +#include "desktop-style.h" #include "display/curve.h" - +#include "helper/geom-pathstroke.h" +#include "live_effects/fill-conversion.h" +#include "live_effects/parameter/enum.h" #include "object/sp-item-group.h" #include "object/sp-shape.h" #include "style.h" - #include "svg/css-ostringstream.h" #include "svg/svg-color.h" -#include <2geom/elliptical-arc.h> - -#include "lpe-jointype.h" - // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -54,54 +50,59 @@ static const Util::EnumData CapTypeData[] = { //{BUTT_LEANED, N_("Leaned"), "leaned"} }; -static const Util::EnumDataConverter CapTypeConverter(CapTypeData, sizeof(CapTypeData)/sizeof(*CapTypeData)); -static const Util::EnumDataConverter JoinTypeConverter(JoinTypeData, sizeof(JoinTypeData)/sizeof(*JoinTypeData)); - -LPEJoinType::LPEJoinType(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - line_width(_("Line width"), _("Thickness of the stroke"), "line_width", &wr, this, 1.), - linecap_type(_("Line cap"), _("The end shape of the stroke"), "linecap_type", CapTypeConverter, &wr, this, BUTT_FLAT), - linejoin_type(_("Join:"), _("Determines the shape of the path's corners"), "linejoin_type", JoinTypeConverter, &wr, this, JOIN_EXTRAPOLATE), - //start_lean(_("Start path lean"), _("Start path lean"), "start_lean", &wr, this, 0.), - //end_lean(_("End path lean"), _("End path lean"), "end_lean", &wr, this, 0.), - miter_limit(_("Miter limit:"), _("Maximum length of the miter join (in units of stroke width)"), "miter_limit", &wr, this, 100.), - attempt_force_join(_("Force miter"), _("Overrides the miter limit and forces a join."), "attempt_force_join", &wr, this, true) +static const Util::EnumDataConverter CapTypeConverter(CapTypeData, + sizeof(CapTypeData) / sizeof(*CapTypeData)); +static const Util::EnumDataConverter JoinTypeConverter(JoinTypeData, + sizeof(JoinTypeData) / sizeof(*JoinTypeData)); + +LPEJoinType::LPEJoinType(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , line_width(_("Line width"), _("Thickness of the stroke"), "line_width", &wr, this, 1.) + , linecap_type(_("Line cap"), _("The end shape of the stroke"), "linecap_type", CapTypeConverter, &wr, this, + BUTT_FLAT) + , linejoin_type(_("Join:"), _("Determines the shape of the path's corners"), "linejoin_type", JoinTypeConverter, + &wr, this, JOIN_EXTRAPOLATE) + , + // start_lean(_("Start path lean"), _("Start path lean"), "start_lean", &wr, this, 0.), + // end_lean(_("End path lean"), _("End path lean"), "end_lean", &wr, this, 0.), + miter_limit(_("Miter limit:"), _("Maximum length of the miter join (in units of stroke width)"), "miter_limit", &wr, + this, 100.) + , attempt_force_join(_("Force miter"), _("Overrides the miter limit and forces a join."), "attempt_force_join", &wr, + this, true) { show_orig_path = true; registerParameter(&linecap_type); registerParameter(&line_width); registerParameter(&linejoin_type); - //registerParameter(&start_lean); - //registerParameter(&end_lean); + // registerParameter(&start_lean); + // registerParameter(&end_lean); registerParameter(&miter_limit); registerParameter(&attempt_force_join); - //start_lean.param_set_range(-1,1); - //start_lean.param_set_increments(0.1, 0.1); - //start_lean.param_set_digits(4); - //end_lean.param_set_range(-1,1); - //end_lean.param_set_increments(0.1, 0.1); - //end_lean.param_set_digits(4); + // start_lean.param_set_range(-1,1); + // start_lean.param_set_increments(0.1, 0.1); + // start_lean.param_set_digits(4); + // end_lean.param_set_range(-1,1); + // end_lean.param_set_increments(0.1, 0.1); + // end_lean.param_set_digits(4); } -LPEJoinType::~LPEJoinType() -= default; +LPEJoinType::~LPEJoinType() = default; -void LPEJoinType::doOnApply(SPLPEItem const* lpeitem) +void LPEJoinType::doOnApply(SPLPEItem const *lpeitem) { if (!SP_IS_SHAPE(lpeitem)) { return; } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - SPShape* item = SP_SHAPE(lpeitem); + SPShape *item = SP_SHAPE(lpeitem); double width = (lpeitem && lpeitem->style) ? lpeitem->style->stroke_width.computed : 1.; lpe_shape_convert_stroke_and_fill(item); - Glib::ustring pref_path = (Glib::ustring)"/live_effects/" + - (Glib::ustring)LPETypeConverter.get_key(effectType()).c_str() + - (Glib::ustring)"/" + - (Glib::ustring)"line_width"; + Glib::ustring pref_path = (Glib::ustring) "/live_effects/" + + (Glib::ustring)LPETypeConverter.get_key(effectType()).c_str() + (Glib::ustring) "/" + + (Glib::ustring) "line_width"; bool valid = prefs->getEntry(pref_path).isValid(); @@ -121,9 +122,9 @@ void LPEJoinType::transform_multiply(Geom::Affine const &postmul, bool /*set*/) } } -//from LPEPowerStroke -- sets stroke color from existing fill color +// from LPEPowerStroke -- sets stroke color from existing fill color -void LPEJoinType::doOnRemove(SPLPEItem const* lpeitem) +void LPEJoinType::doOnRemove(SPLPEItem const *lpeitem) { if (!SP_IS_SHAPE(lpeitem)) { return; @@ -132,14 +133,13 @@ void LPEJoinType::doOnRemove(SPLPEItem const* lpeitem) lpe_shape_revert_stroke_and_fill(SP_SHAPE(lpeitem), line_width); } -Geom::PathVector LPEJoinType::doEffect_path(Geom::PathVector const & path_in) +Geom::PathVector LPEJoinType::doEffect_path(Geom::PathVector const &path_in) { Geom::PathVector ret; - for (const auto & i : path_in) { - Geom::PathVector tmp = Inkscape::outline(i, line_width, - (attempt_force_join ? std::numeric_limits::max() : miter_limit), - static_cast(linejoin_type.get_value()), - static_cast(linecap_type.get_value())); + for (const auto &i : path_in) { + Geom::PathVector tmp = Inkscape::outline( + i, line_width, (attempt_force_join ? std::numeric_limits::max() : miter_limit), + static_cast(linejoin_type.get_value()), static_cast(linecap_type.get_value())); ret.insert(ret.begin(), tmp.begin(), tmp.end()); } diff --git a/src/live_effects/lpe-jointype.h b/src/live_effects/lpe-jointype.h index 5d5e20c60ea4cf95a2715502263a3d62ad4742b2..001af7c77b2e14d34362c6f3cebf38106f55c0a0 100644 --- a/src/live_effects/lpe-jointype.h +++ b/src/live_effects/lpe-jointype.h @@ -11,38 +11,39 @@ #define INKSCAPE_LPE_JOINTYPE_H #include "live_effects/effect.h" +#include "live_effects/parameter/enum.h" #include "live_effects/parameter/parameter.h" #include "live_effects/parameter/point.h" -#include "live_effects/parameter/enum.h" namespace Inkscape { namespace LivePathEffect { -class LPEJoinType : public Effect { +class LPEJoinType : public Effect +{ public: LPEJoinType(LivePathEffectObject *lpeobject); ~LPEJoinType() override; - void doOnApply(SPLPEItem const* lpeitem) override; - void doOnRemove(SPLPEItem const* lpeitem) override; + void doOnApply(SPLPEItem const *lpeitem) override; + void doOnRemove(SPLPEItem const *lpeitem) override; void transform_multiply(Geom::Affine const &postmul, bool set) override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; private: - LPEJoinType(const LPEJoinType&) = delete; - LPEJoinType& operator=(const LPEJoinType&) = delete; + LPEJoinType(const LPEJoinType &) = delete; + LPEJoinType &operator=(const LPEJoinType &) = delete; ScalarParam line_width; EnumParam linecap_type; EnumParam linejoin_type; - //ScalarParam start_lean; - //ScalarParam end_lean; + // ScalarParam start_lean; + // ScalarParam end_lean; ScalarParam miter_limit; BoolParam attempt_force_join; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-knot.cpp b/src/live_effects/lpe-knot.cpp index b4bdd19e09a1f9add12e324920b165dbf0310028..d360e573306067ee75202e23c1d4336e9b394dcc 100644 --- a/src/live_effects/lpe-knot.cpp +++ b/src/live_effects/lpe-knot.cpp @@ -13,26 +13,25 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "display/curve.h" #include "live_effects/lpe-knot.h" -#include "knot-holder-entity.h" -#include "knotholder.h" +#include <2geom/basic-intersection.h> +#include <2geom/bezier-to-sbasis.h> +#include <2geom/sbasis-to-bezier.h> #include -#include <2geom/sbasis-to-bezier.h> -#include <2geom/bezier-to-sbasis.h> -#include <2geom/basic-intersection.h> +#include "display/curve.h" #include "helper/geom.h" - -#include "object/sp-shape.h" +#include "knot-holder-entity.h" +#include "knotholder.h" #include "object/sp-path.h" +#include "object/sp-shape.h" #include "style.h" // for change crossing undo -#include "verbs.h" -#include "document.h" #include "document-undo.h" +#include "document.h" +#include "verbs.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -40,16 +39,18 @@ namespace Inkscape { namespace LivePathEffect { -class KnotHolderEntityCrossingSwitcher : public LPEKnotHolderEntity { +class KnotHolderEntityCrossingSwitcher : public LPEKnotHolderEntity +{ public: - KnotHolderEntityCrossingSwitcher(LPEKnot *effect) : LPEKnotHolderEntity(effect) {}; + KnotHolderEntityCrossingSwitcher(LPEKnot *effect) + : LPEKnotHolderEntity(effect){}; void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; void knot_click(guint state) override; }; - -static Geom::Path::size_type size_nondegenerate(Geom::Path const &path) { +static Geom::Path::size_type size_nondegenerate(Geom::Path const &path) +{ Geom::Path::size_type retval = path.size_default(); const Geom::Curve &closingline = path.back_closed(); // the closing line segment is always of type @@ -65,134 +66,136 @@ static Geom::Path::size_type size_nondegenerate(Geom::Path const &path) { } //--------------------------------------------------------------------------- -//LPEKnot specific Interval manipulation. +// LPEKnot specific Interval manipulation. //--------------------------------------------------------------------------- -//remove an interval from an union of intervals. -//TODO: is it worth moving it to 2Geom? -static -std::vector complementOf(Geom::Interval I, std::vector domain){ +// remove an interval from an union of intervals. +// TODO: is it worth moving it to 2Geom? +static std::vector complementOf(Geom::Interval I, std::vector domain) +{ std::vector ret; if (!domain.empty()) { double min = domain.front().min(); double max = domain.back().max(); - Geom::Interval I1 = Geom::Interval(min,I.min()); - Geom::Interval I2 = Geom::Interval(I.max(),max); - - for (auto i : domain){ - boost::optional I1i = intersect(i,I1); - if (I1i && !I1i->isSingular()) ret.push_back(I1i.get()); - boost::optional I2i = intersect(i,I2); - if (I2i && !I2i->isSingular()) ret.push_back(I2i.get()); + Geom::Interval I1 = Geom::Interval(min, I.min()); + Geom::Interval I2 = Geom::Interval(I.max(), max); + + for (auto i : domain) { + boost::optional I1i = intersect(i, I1); + if (I1i && !I1i->isSingular()) + ret.push_back(I1i.get()); + boost::optional I2i = intersect(i, I2); + if (I2i && !I2i->isSingular()) + ret.push_back(I2i.get()); } } return ret; } -//find the time interval during which patha is hidden by pathb near a given crossing. +// find the time interval during which patha is hidden by pathb near a given crossing. // Warning: not accurate! -static -Geom::Interval -findShadowedTime(Geom::Path const &patha, std::vector const &pt_and_dir, - double const ta, double const width){ +static Geom::Interval findShadowedTime(Geom::Path const &patha, std::vector const &pt_and_dir, + double const ta, double const width) +{ using namespace Geom; Point T = unit_vector(pt_and_dir[1]); Point N = T.cw(); - //Point A = pt_and_dir[0] - 3 * width * T; - //Point B = A+6*width*T; + // Point A = pt_and_dir[0] - 3 * width * T; + // Point B = A+6*width*T; - Affine mat = from_basis( T, N, pt_and_dir[0] ); + Affine mat = from_basis(T, N, pt_and_dir[0]); mat = mat.inverse(); Geom::Path p = patha * mat; - + std::vector times; - - //TODO: explore the path fwd/backward from ta (worth?) - for (unsigned i = 0; i < size_nondegenerate(patha); i++){ + + // TODO: explore the path fwd/backward from ta (worth?) + for (unsigned i = 0; i < size_nondegenerate(patha); i++) { D2 f = p[i].toSBasis(); std::vector times_i, temptimes; - temptimes = roots(f[Y]-width); - times_i.insert(times_i.end(), temptimes.begin(), temptimes.end() ); - temptimes = roots(f[Y]+width); - times_i.insert(times_i.end(), temptimes.begin(), temptimes.end() ); - temptimes = roots(f[X]-3*width); - times_i.insert(times_i.end(), temptimes.begin(), temptimes.end() ); - temptimes = roots(f[X]+3*width); - times_i.insert(times_i.end(), temptimes.begin(), temptimes.end() ); - for (double & k : times_i){ - k+=i; + temptimes = roots(f[Y] - width); + times_i.insert(times_i.end(), temptimes.begin(), temptimes.end()); + temptimes = roots(f[Y] + width); + times_i.insert(times_i.end(), temptimes.begin(), temptimes.end()); + temptimes = roots(f[X] - 3 * width); + times_i.insert(times_i.end(), temptimes.begin(), temptimes.end()); + temptimes = roots(f[X] + 3 * width); + times_i.insert(times_i.end(), temptimes.begin(), temptimes.end()); + for (double &k : times_i) { + k += i; } - times.insert(times.end(), times_i.begin(), times_i.end() ); + times.insert(times.end(), times_i.begin(), times_i.end()); } - std::sort( times.begin(), times.end() ); - std::vector::iterator new_end = std::unique( times.begin(), times.end() ); - times.resize( new_end - times.begin() ); + std::sort(times.begin(), times.end()); + std::vector::iterator new_end = std::unique(times.begin(), times.end()); + times.resize(new_end - times.begin()); double tmin = 0, tmax = size_nondegenerate(patha); double period = size_nondegenerate(patha); - if (!times.empty()){ - unsigned rk = upper_bound( times.begin(), times.end(), ta ) - times.begin(); - if ( rk < times.size() ) + if (!times.empty()) { + unsigned rk = upper_bound(times.begin(), times.end(), ta) - times.begin(); + if (rk < times.size()) tmax = times[rk]; - else if ( patha.closed() ) - tmax = times[0]+period; + else if (patha.closed()) + tmax = times[0] + period; - if ( rk > 0 ) - tmin = times[rk-1]; - else if ( patha.closed() ) - tmin = times.back()-period; + if (rk > 0) + tmin = times[rk - 1]; + else if (patha.closed()) + tmin = times.back() - period; } - return Interval(tmin,tmax); + return Interval(tmin, tmax); } //--------------------------------------------------------------------------- -//LPEKnot specific Crossing Data manipulation. +// LPEKnot specific Crossing Data manipulation. //--------------------------------------------------------------------------- -//Yet another crossing data representation. +// Yet another crossing data representation. // an CrossingPoint stores // -an intersection point // -the involved path components -// -for each component, the time at which this crossing occurs + the order of this crossing along the component (when starting from 0). - -namespace LPEKnotNS {//just in case... -CrossingPoints::CrossingPoints(Geom::PathVector const &paths) : std::vector(){ -// std::cout<<"\nCrossingPoints creation from path vector\n"; - for( unsigned i=0; i > times; - if ( (i==j) && (ii==jj) ) { - -// std::cout<<"--(self int)\n"; -// std::cout << paths[i][ii].toSBasis()[Geom::X] <<"\n"; -// std::cout << paths[i][ii].toSBasis()[Geom::Y] <<"\n"; - - find_self_intersections( times, paths[i][ii].toSBasis() ); +// -for each component, the time at which this crossing occurs + the order of this crossing along the component (when +// starting from 0). + +namespace LPEKnotNS { // just in case... +CrossingPoints::CrossingPoints(Geom::PathVector const &paths) + : std::vector() +{ + // std::cout<<"\nCrossingPoints creation from path vector\n"; + for (unsigned i = 0; i < paths.size(); i++) { + for (unsigned ii = 0; ii < size_nondegenerate(paths[i]); ii++) { + for (unsigned j = i; j < paths.size(); j++) { + for (unsigned jj = (i == j ? ii : 0); jj < size_nondegenerate(paths[j]); jj++) { + std::vector> times; + if ((i == j) && (ii == jj)) { + // std::cout<<"--(self int)\n"; + // std::cout << paths[i][ii].toSBasis()[Geom::X] <<"\n"; + // std::cout << paths[i][ii].toSBasis()[Geom::Y] <<"\n"; + + find_self_intersections(times, paths[i][ii].toSBasis()); } else { -// std::cout<<"--(pair int)\n"; -// std::cout << paths[i][ii].toSBasis()[Geom::X] <<"\n"; -// std::cout << paths[i][ii].toSBasis()[Geom::Y] <<"\n"; -// std::cout<<"with\n"; -// std::cout << paths[j][jj].toSBasis()[Geom::X] <<"\n"; -// std::cout << paths[j][jj].toSBasis()[Geom::Y] <<"\n"; - - find_intersections( times, paths[i][ii].toSBasis(), paths[j][jj].toSBasis() ); + // std::cout<<"--(pair int)\n"; + // std::cout << paths[i][ii].toSBasis()[Geom::X] <<"\n"; + // std::cout << paths[i][ii].toSBasis()[Geom::Y] <<"\n"; + // std::cout<<"with\n"; + // std::cout << paths[j][jj].toSBasis()[Geom::X] <<"\n"; + // std::cout << paths[j][jj].toSBasis()[Geom::Y] <<"\n"; + + find_intersections(times, paths[i][ii].toSBasis(), paths[j][jj].toSBasis()); } - for (auto & time : times){ - //std::cout<<"intersection "< cuts; - for( unsigned k=0; k cuts; + for (unsigned k = 0; k < size(); k++) { CrossingPoint cp = (*this)[k]; - if (cp.i == i) cuts[cp.ti] = k; - if (cp.j == i) cuts[cp.tj] = k; + if (cp.i == i) + cuts[cp.ti] = k; + if (cp.j == i) + cuts[cp.tj] = k; } unsigned count = 0; - for (auto & cut : cuts){ - if ( ((*this)[cut.second].i == i) && ((*this)[cut.second].ti == cut.first) ){ + for (auto &cut : cuts) { + if (((*this)[cut.second].i == i) && ((*this)[cut.second].ti == cut.first)) { (*this)[cut.second].ni = count; - }else{ + } else { (*this)[cut.second].nj = count; } count++; @@ -232,11 +238,12 @@ CrossingPoints::CrossingPoints(Geom::PathVector const &paths) : std::vector const &input) : std::vector() +CrossingPoints::CrossingPoints(std::vector const &input) + : std::vector() { - if ( (input.size() > 0) && (input.size()%9 == 0) ){ + if ((input.size() > 0) && (input.size() % 9 == 0)) { using namespace Geom; - for( unsigned n=0; n const &input) : std::vector -CrossingPoints::to_vector() +std::vector CrossingPoints::to_vector() { using namespace Geom; std::vector result; - for( unsigned n=0; n dist_k) ) { + for (unsigned k = 0; k < cpts.size(); k++) { + double dist_k = Geom::L2(p - cpts[k].pt); + if ((dist < 0) || (dist > dist_k)) { result = k; dist = dist_k; } @@ -303,19 +305,14 @@ idx_of_nearest(CrossingPoints const &cpts, Geom::Point const &p) return result; } -//TODO: Find a way to warn the user when the topology changes. -//TODO: be smarter at guessing the signs when the topology changed? -void -CrossingPoints::inherit_signs(CrossingPoints const &other, int default_value) +// TODO: Find a way to warn the user when the topology changes. +// TODO: be smarter at guessing the signs when the topology changed? +void CrossingPoints::inherit_signs(CrossingPoints const &other, int default_value) { bool topo_changed = false; - for (unsigned n=0; n < size(); n++){ - if ( (n < other.size()) - && (other[n].i == (*this)[n].i) - && (other[n].j == (*this)[n].j) - && (other[n].ni == (*this)[n].ni) - && (other[n].nj == (*this)[n].nj) ) - { + for (unsigned n = 0; n < size(); n++) { + if ((n < other.size()) && (other[n].i == (*this)[n].i) && (other[n].j == (*this)[n].j) && + (other[n].ni == (*this)[n].ni) && (other[n].nj == (*this)[n].nj)) { (*this)[n].sign = other[n].sign; } else { topo_changed = true; @@ -323,11 +320,11 @@ CrossingPoints::inherit_signs(CrossingPoints const &other, int default_value) } } if (topo_changed) { - //TODO: Find a way to warn the user!! -// std::cout<<"knot topolgy changed!\n"; - for (unsigned n=0; n < size(); n++){ + // TODO: Find a way to warn the user!! + // std::cout<<"knot topolgy changed!\n"; + for (unsigned n = 0; n < size(); n++) { Geom::Point p = (*this)[n].pt; - unsigned idx = idx_of_nearest(other,p); + unsigned idx = idx_of_nearest(other, p); if (idx < other.size()) { (*this)[n].sign = other[idx].sign; } else { @@ -337,15 +334,14 @@ CrossingPoints::inherit_signs(CrossingPoints const &other, int default_value) } } -} +} // namespace LPEKnotNS //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- -//LPEKnot effect. +// LPEKnot effect. //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- - LPEKnot::LPEKnot(LivePathEffectObject *lpeobject) : Effect(lpeobject) , @@ -384,79 +380,82 @@ LPEKnot::LPEKnot(LivePathEffectObject *lpeobject) _provides_knotholder_entities = true; } -LPEKnot::~LPEKnot() -= default; +LPEKnot::~LPEKnot() = default; -void -LPEKnot::updateSwitcher(){ - if (selectedCrossing < crossing_points.size()){ +void LPEKnot::updateSwitcher() +{ + if (selectedCrossing < crossing_points.size()) { switcher = crossing_points[selectedCrossing].pt; - //std::cout<<"placing switcher at "<0){ + // std::cout<<"placing switcher at "< 0) { selectedCrossing = 0; switcher = crossing_points[selectedCrossing].pt; - //std::cout<<"placing switcher at "<getInt("/options/svgoutput/numericprecision"); prefs->setInt("/options/svgoutput/numericprecision", 4); // I think this is enough for minor differences - for (i0=0; i0setInt("/options/svgoutput/numericprecision", precision); - if (i0 == gpaths.size() ) {THROW_EXCEPTION("lpe-knot error: group member not recognized");}// this should not happen... + if (i0 == gpaths.size()) { + THROW_EXCEPTION("lpe-knot error: group member not recognized"); + } // this should not happen... std::vector dom; dom.emplace_back(0., size_nondegenerate(gpaths[i0])); - for (unsigned p = 0; p < crossing_points.size(); p++){ - if ( (crossing_points[p].i == i0) || (crossing_points[p].j == i0) ) { + for (unsigned p = 0; p < crossing_points.size(); p++) { + if ((crossing_points[p].i == i0) || (crossing_points[p].j == i0)) { unsigned i = crossing_points[p].i; unsigned j = crossing_points[p].j; double ti = crossing_points[p].ti; double tj = crossing_points[p].tj; - + double curveidx, t; - + t = modf(ti, &curveidx); - if(curveidx == size_nondegenerate(gpaths[i]) ) { curveidx--; t = 1.;} + if (curveidx == size_nondegenerate(gpaths[i])) { + curveidx--; + t = 1.; + } assert(curveidx >= 0 && curveidx < size_nondegenerate(gpaths[i])); - std::vector flag_i = gpaths[i][curveidx].pointAndDerivatives(t,1); + std::vector flag_i = gpaths[i][curveidx].pointAndDerivatives(t, 1); t = modf(tj, &curveidx); - if(curveidx == size_nondegenerate(gpaths[j]) ) { curveidx--; t = 1.;} + if (curveidx == size_nondegenerate(gpaths[j])) { + curveidx--; + t = 1.; + } assert(curveidx >= 0 && curveidx < size_nondegenerate(gpaths[j])); - std::vector flag_j = gpaths[j][curveidx].pointAndDerivatives(t,1); - + std::vector flag_j = gpaths[j][curveidx].pointAndDerivatives(t, 1); - int geom_sign = ( cross(flag_i[1], flag_j[1]) < 0 ? 1 : -1); + int geom_sign = (cross(flag_i[1], flag_j[1]) < 0 ? 1 : -1); bool i0_is_under = false; double width = interruption_width; - if ( crossing_points[p].sign * geom_sign > 0 ){ - i0_is_under = ( i == i0 ); - } - else if (crossing_points[p].sign * geom_sign < 0) { - if (j == i0){ + if (crossing_points[p].sign * geom_sign > 0) { + i0_is_under = (i == i0); + } else if (crossing_points[p].sign * geom_sign < 0) { + if (j == i0) { i0_is_under = true; } } @@ -470,12 +469,11 @@ LPEKnot::doEffect_path (Geom::PathVector const &path_in) std::swap(flag_i, flag_j); } } - if (i0_is_under){ - if ( prop_to_stroke_width.get_value() ) { + if (i0_is_under) { + if (prop_to_stroke_width.get_value()) { if (inverse_width) { width *= gstroke_widths[j]; - } - else { + } else { width *= gstroke_widths[i]; } } @@ -485,14 +483,15 @@ LPEKnot::doEffect_path (Geom::PathVector const &path_in) if (add_other_stroke_width.get_value() == "true") { width += gstroke_widths[j]; } - Interval hidden = findShadowedTime(gpaths[i0], flag_j, ti, width/2); - double period = size_nondegenerate(gpaths[i0]); - if (hidden.max() > period ) hidden -= period; - if (hidden.min()<0){ - dom = complementOf( Interval(0,hidden.max()) ,dom); - dom = complementOf( Interval(hidden.min()+period, period) ,dom); - }else{ - dom = complementOf(hidden,dom); + Interval hidden = findShadowedTime(gpaths[i0], flag_j, ti, width / 2); + double period = size_nondegenerate(gpaths[i0]); + if (hidden.max() > period) + hidden -= period; + if (hidden.min() < 0) { + dom = complementOf(Interval(0, hidden.max()), dom); + dom = complementOf(Interval(hidden.min() + period, period), dom); + } else { + dom = complementOf(hidden, dom); } if (crossing_points[p].i == i0 && crossing_points[p].j == i0 && crossing_points[p].sign != 0 && both) { @@ -503,8 +502,7 @@ LPEKnot::doEffect_path (Geom::PathVector const &path_in) if (hidden.min() < 0) { dom = complementOf(Interval(0, hidden.max()), dom); dom = complementOf(Interval(hidden.min() + period, period), dom); - } - else { + } else { dom = complementOf(hidden, dom); } } @@ -512,43 +510,41 @@ LPEKnot::doEffect_path (Geom::PathVector const &path_in) } } - //If the all component is hidden, continue. - if (dom.empty()){ + // If the all component is hidden, continue. + if (dom.empty()) { continue; } - //If the current path is closed and the last/first point is still there, glue first and last piece. + // If the current path is closed and the last/first point is still there, glue first and last piece. unsigned beg_comp = 0, end_comp = dom.size(); - if ( gpaths[i0].closed() && (dom.front().min() == 0) && (dom.back().max() == size_nondegenerate(gpaths[i0])) ) { - if ( dom.size() == 1){ + if (gpaths[i0].closed() && (dom.front().min() == 0) && (dom.back().max() == size_nondegenerate(gpaths[i0]))) { + if (dom.size() == 1) { path_out.push_back(gpaths[i0]); continue; - }else{ + } else { // std::cout<<"fusing first and last component\n"; ++beg_comp; --end_comp; Geom::Path first = gpaths[i0].portion(dom.back()); - //FIXME: stitching should not be necessary (?!?) + // FIXME: stitching should not be necessary (?!?) first.setStitching(true); first.append(gpaths[i0].portion(dom.front())); path_out.push_back(first); } } - for (unsigned comp = beg_comp; comp < end_comp; comp++){ - assert(dom.at(comp).min() >=0 && dom.at(comp).max() <= size_nondegenerate(gpaths.at(i0))); + for (unsigned comp = beg_comp; comp < end_comp; comp++) { + assert(dom.at(comp).min() >= 0 && dom.at(comp).max() <= size_nondegenerate(gpaths.at(i0))); path_out.push_back(gpaths[i0].portion(dom.at(comp))); } } return path_out; } - - -//recursively collect gpaths and stroke widths (stolen from "sp-lpe_item.cpp"). -static void -collectPathsAndWidths (SPLPEItem const *lpeitem, Geom::PathVector &paths, std::vector &stroke_widths){ +// recursively collect gpaths and stroke widths (stolen from "sp-lpe_item.cpp"). +static void collectPathsAndWidths(SPLPEItem const *lpeitem, Geom::PathVector &paths, std::vector &stroke_widths) +{ if (SP_IS_GROUP(lpeitem)) { - std::vector item_list = sp_item_group_item_list(SP_GROUP(lpeitem)); + std::vector item_list = sp_item_group_item_list(SP_GROUP(lpeitem)); for (auto subitem : item_list) { if (SP_IS_LPE_ITEM(subitem)) { collectPathsAndWidths(SP_LPE_ITEM(subitem), paths, stroke_widths); @@ -558,22 +554,20 @@ collectPathsAndWidths (SPLPEItem const *lpeitem, Geom::PathVector &paths, std::v SPCurve const *c = shape->curve(); if (c) { Geom::PathVector subpaths = pathv_to_linear_and_cubic_beziers(c->get_pathvector()); - for (const auto & subpath : subpaths){ + for (const auto &subpath : subpaths) { paths.push_back(subpath); - //FIXME: do we have to be more careful when trying to access stroke width? + // FIXME: do we have to be more careful when trying to access stroke width? stroke_widths.push_back(lpeitem->style->stroke_width.computed); } } } } - -void -LPEKnot::doBeforeEffect (SPLPEItem const* lpeitem) +void LPEKnot::doBeforeEffect(SPLPEItem const *lpeitem) { using namespace Geom; original_bbox(lpeitem); - + if (SP_IS_PATH(lpeitem)) { supplied_path = SP_PATH(lpeitem)->curve()->get_pathvector(); } @@ -583,48 +577,48 @@ LPEKnot::doBeforeEffect (SPLPEItem const* lpeitem) collectPathsAndWidths(lpeitem, gpaths, gstroke_widths); -// std::cout<<"\nPaths on input:\n"; -// for (unsigned i=0; i 0 ) std::cout<<"first crossing sign = "< 0 ) std::cout<<"first crossing sign = "< &hp_vec) +void LPEKnot::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { using namespace Geom; - double r = switcher_size*.1; - char const * svgd; - //TODO: use a nice path! - if ( (selectedCrossing >= crossing_points.size()) || (crossing_points[selectedCrossing].sign > 0) ) { - //svgd = "M -10,0 A 10 10 0 1 0 0,-10 l 5,-1 -1,2"; - svgd = "m -7.07,7.07 c 3.9,3.91 10.24,3.91 14.14,0 3.91,-3.9 3.91,-10.24 0,-14.14 -3.9,-3.91 -10.24,-3.91 -14.14,0 l 2.83,-4.24 0.7,2.12"; + double r = switcher_size * .1; + char const *svgd; + // TODO: use a nice path! + if ((selectedCrossing >= crossing_points.size()) || (crossing_points[selectedCrossing].sign > 0)) { + // svgd = "M -10,0 A 10 10 0 1 0 0,-10 l 5,-1 -1,2"; + svgd = "m -7.07,7.07 c 3.9,3.91 10.24,3.91 14.14,0 3.91,-3.9 3.91,-10.24 0,-14.14 -3.9,-3.91 -10.24,-3.91 " + "-14.14,0 l 2.83,-4.24 0.7,2.12"; } else if (crossing_points[selectedCrossing].sign < 0) { - //svgd = "M 10,0 A 10 10 0 1 1 0,-10 l -5,-1 1,2"; - svgd = "m 7.07,7.07 c -3.9,3.91 -10.24,3.91 -14.14,0 -3.91,-3.9 -3.91,-10.24 0,-14.14 3.9,-3.91 10.24,-3.91 14.14,0 l -2.83,-4.24 -0.7,2.12"; + // svgd = "M 10,0 A 10 10 0 1 1 0,-10 l -5,-1 1,2"; + svgd = "m 7.07,7.07 c -3.9,3.91 -10.24,3.91 -14.14,0 -3.91,-3.9 -3.91,-10.24 0,-14.14 3.9,-3.91 10.24,-3.91 " + "14.14,0 l -2.83,-4.24 -0.7,2.12"; } else { - //svgd = "M 10,0 A 10 10 0 1 0 -10,0 A 10 10 0 1 0 10,0 "; + // svgd = "M 10,0 A 10 10 0 1 0 -10,0 A 10 10 0 1 0 10,0 "; svgd = "M 10,0 C 10,5.52 5.52,10 0,10 -5.52,10 -10,5.52 -10,0 c 0,-5.52 4.48,-10 10,-10 5.52,0 10,4.48 10,10 z"; } PathVector pathv = sp_svg_read_pathv(svgd); - pathv *= Affine(r,0,0,r,0,0) * Translate(switcher); + pathv *= Affine(r, 0, 0, r, 0, 0) * Translate(switcher); hp_vec.push_back(pathv); } @@ -664,56 +659,50 @@ void LPEKnot::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) knotholder->add(e); }; - -void -KnotHolderEntityCrossingSwitcher::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint /*state*/) +void KnotHolderEntityCrossingSwitcher::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint /*state*/) { - LPEKnot* lpe = dynamic_cast(_effect); + LPEKnot *lpe = dynamic_cast(_effect); - lpe->selectedCrossing = idx_of_nearest(lpe->crossing_points,p); + lpe->selectedCrossing = idx_of_nearest(lpe->crossing_points, p); lpe->updateSwitcher(); // FIXME: this should not directly ask for updating the item. It should write to SVG, which triggers updating. - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, true); } -Geom::Point -KnotHolderEntityCrossingSwitcher::knot_get() const +Geom::Point KnotHolderEntityCrossingSwitcher::knot_get() const { - LPEKnot const *lpe = dynamic_cast(_effect); + LPEKnot const *lpe = dynamic_cast(_effect); return lpe->switcher; } -void -KnotHolderEntityCrossingSwitcher::knot_click(guint state) +void KnotHolderEntityCrossingSwitcher::knot_click(guint state) { - LPEKnot* lpe = dynamic_cast(_effect); + LPEKnot *lpe = dynamic_cast(_effect); unsigned s = lpe->selectedCrossing; - if (s < lpe->crossing_points.size()){ - if (state & GDK_SHIFT_MASK){ + if (s < lpe->crossing_points.size()) { + if (state & GDK_SHIFT_MASK) { for (unsigned p = 0; p < lpe->crossing_points.size(); p++) { lpe->crossing_points[p].sign = ((lpe->crossing_points[p].sign + 2) % 3) - 1; } - } - else if (state & GDK_CONTROL_MASK) { + } else if (state & GDK_CONTROL_MASK) { int sign = lpe->crossing_points[s].sign; for (unsigned p = 0; p < lpe->crossing_points.size(); p++) { lpe->crossing_points[p].sign = ((sign + 2) % 3) - 1; } - }else{ + } else { int sign = lpe->crossing_points[s].sign; - lpe->crossing_points[s].sign = ((sign+2)%3)-1; - //std::cout<<"crossing set to"<crossing_points[s].sign<<".\n"; + lpe->crossing_points[s].sign = ((sign + 2) % 3) - 1; + // std::cout<<"crossing set to"<crossing_points[s].sign<<".\n"; } lpe->crossing_points_vector.param_set_and_write_new_value(lpe->crossing_points.to_vector()); DocumentUndo::done(lpe->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, /// @todo Is this the right verb? _("Change knot crossing")); // FIXME: this should not directly ask for updating the item. It should write to SVG, which triggers updating. -// sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + // sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); } } - /* ######################## */ } // namespace LivePathEffect @@ -729,4 +718,3 @@ KnotHolderEntityCrossingSwitcher::knot_click(guint state) End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - diff --git a/src/live_effects/lpe-knot.h b/src/live_effects/lpe-knot.h index 6768d7906aa87650fab0dd7edb942d27b74ff73b..98f3d1b70de7a101f68030c454e7375e033dd1d0 100644 --- a/src/live_effects/lpe-knot.h +++ b/src/live_effects/lpe-knot.h @@ -14,15 +14,14 @@ #ifndef INKSCAPE_LPE_KNOT_H #define INKSCAPE_LPE_KNOT_H - #include "live_effects/effect.h" #include "live_effects/lpegroupbbox.h" #include "live_effects/parameter/array.h" #include "live_effects/parameter/hidden.h" #include "live_effects/parameter/parameter.h" //#include "live_effects/parameter/path.h" -#include "live_effects/parameter/bool.h" #include "2geom/crossing.h" +#include "live_effects/parameter/bool.h" class SPLPEItem; @@ -33,73 +32,79 @@ class KnotHolderEntityCrossingSwitcher; // CrossingPoint, CrossingPoints: // "point oriented" storage of crossing data (needed to find crossing nearest to a click, etc...) -//TODO: evaluate how lpeknot-specific that is? Should something like this exist in 2geom? -namespace LPEKnotNS {//just in case... -struct CrossingPoint { - Geom::Point pt; - int sign; //+/-1 = positive or neg crossing, 0 = flat. - unsigned i, j; //paths components meeting in this point. - unsigned ni, nj; //this crossing is the ni-th along i, nj-th along j. - double ti, tj; //time along paths. +// TODO: evaluate how lpeknot-specific that is? Should something like this exist in 2geom? +namespace LPEKnotNS { // just in case... +struct CrossingPoint +{ + Geom::Point pt; + int sign; //+/-1 = positive or neg crossing, 0 = flat. + unsigned i, j; // paths components meeting in this point. + unsigned ni, nj; // this crossing is the ni-th along i, nj-th along j. + double ti, tj; // time along paths. }; -class CrossingPoints : public std::vector{ +class CrossingPoints : public std::vector +{ public: - CrossingPoints() : std::vector() {} - CrossingPoints(Geom::CrossingSet const &cs, Geom::PathVector const &path);//for self crossings only! - CrossingPoints(Geom::PathVector const &paths); - CrossingPoints(std::vector const &input); - std::vector to_vector(); - CrossingPoint get(unsigned const i, unsigned const ni); - void inherit_signs(CrossingPoints const &from_other, int default_value = 1); + CrossingPoints() + : std::vector() + {} + CrossingPoints(Geom::CrossingSet const &cs, Geom::PathVector const &path); // for self crossings only! + CrossingPoints(Geom::PathVector const &paths); + CrossingPoints(std::vector const &input); + std::vector to_vector(); + CrossingPoint get(unsigned const i, unsigned const ni); + void inherit_signs(CrossingPoints const &from_other, int default_value = 1); }; -} +} // namespace LPEKnotNS -class LPEKnot : public Effect, GroupBBoxEffect { +class LPEKnot + : public Effect + , GroupBBoxEffect +{ public: - LPEKnot(LivePathEffectObject *lpeobject); - ~LPEKnot() override; - - void doBeforeEffect (SPLPEItem const* lpeitem) override; - Geom::PathVector doEffect_path (Geom::PathVector const & input_path) override; - - /* the knotholder entity classes must be declared friends */ - friend class KnotHolderEntityCrossingSwitcher; - void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) override; + LPEKnot(LivePathEffectObject *lpeobject); + ~LPEKnot() override; + + void doBeforeEffect(SPLPEItem const *lpeitem) override; + Geom::PathVector doEffect_path(Geom::PathVector const &input_path) override; + + /* the knotholder entity classes must be declared friends */ + friend class KnotHolderEntityCrossingSwitcher; + void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) override; protected: - void addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec) override; - Geom::PathVector supplied_path; //for knotholder business - + void addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec) override; + Geom::PathVector supplied_path; // for knotholder business + private: - void updateSwitcher(); - - ScalarParam interruption_width; - BoolParam prop_to_stroke_width; - BoolParam both; - BoolParam inverse_width; - // "add_stroke_width" and "add_other_stroke_width" parameters are not used since Inkscape 1.0, - // but changed from bool to hidden parameter to retain backward compatibility and dont show in the UI - HiddenParam add_stroke_width; - HiddenParam add_other_stroke_width; - ScalarParam switcher_size; - ArrayParam crossing_points_vector;//svg storage of crossing_points - - LPEKnotNS::CrossingPoints crossing_points;//topology representation of the knot. - - Geom::PathVector gpaths;//the collection of all the paths in the object or group. - std::vector gstroke_widths;//the collection of all the stroke widths in the object or group. - - //UI: please, someone, help me to improve this!! - unsigned selectedCrossing;//the selected crossing - Geom::Point switcher;//where to put the "switcher" helper - - LPEKnot(const LPEKnot&) = delete; - LPEKnot& operator=(const LPEKnot&) = delete; - + void updateSwitcher(); + + ScalarParam interruption_width; + BoolParam prop_to_stroke_width; + BoolParam both; + BoolParam inverse_width; + // "add_stroke_width" and "add_other_stroke_width" parameters are not used since Inkscape 1.0, + // but changed from bool to hidden parameter to retain backward compatibility and dont show in the UI + HiddenParam add_stroke_width; + HiddenParam add_other_stroke_width; + ScalarParam switcher_size; + ArrayParam crossing_points_vector; // svg storage of crossing_points + + LPEKnotNS::CrossingPoints crossing_points; // topology representation of the knot. + + Geom::PathVector gpaths; // the collection of all the paths in the object or group. + std::vector gstroke_widths; // the collection of all the stroke widths in the object or group. + + // UI: please, someone, help me to improve this!! + unsigned selectedCrossing; // the selected crossing + Geom::Point switcher; // where to put the "switcher" helper + + LPEKnot(const LPEKnot &) = delete; + LPEKnot &operator=(const LPEKnot &) = delete; }; - -} //namespace LivePathEffect -} //namespace Inkscape + +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-lattice.cpp b/src/live_effects/lpe-lattice.cpp index 3dcc703fed732e0c3493dae4648bc96350bf835b..2e9d36968b7d7447b3b6ed9ef4c6643eef0c3872 100644 --- a/src/live_effects/lpe-lattice.cpp +++ b/src/live_effects/lpe-lattice.cpp @@ -17,10 +17,10 @@ #include "live_effects/lpe-lattice.h" -#include "display/curve.h" - -#include <2geom/sbasis-2d.h> #include <2geom/bezier-to-sbasis.h> +#include <2geom/sbasis-2d.h> + +#include "display/curve.h" // TODO due to internal breakage in glibmm headers, this must be last: #include using namespace Geom; @@ -28,27 +28,28 @@ using namespace Geom; namespace Inkscape { namespace LivePathEffect { -LPELattice::LPELattice(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - +LPELattice::LPELattice(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , + // initialise your parameters here: - grid_point0(_("Control handle 0:"), _("Control handle 0"), "gridpoint0", &wr, this), - grid_point1(_("Control handle 1:"), _("Control handle 1"), "gridpoint1", &wr, this), - grid_point2(_("Control handle 2:"), _("Control handle 2"), "gridpoint2", &wr, this), - grid_point3(_("Control handle 3:"), _("Control handle 3"), "gridpoint3", &wr, this), - grid_point4(_("Control handle 4:"), _("Control handle 4"), "gridpoint4", &wr, this), - grid_point5(_("Control handle 5:"), _("Control handle 5"), "gridpoint5", &wr, this), - grid_point6(_("Control handle 6:"), _("Control handle 6"), "gridpoint6", &wr, this), - grid_point7(_("Control handle 7:"), _("Control handle 7"), "gridpoint7", &wr, this), - grid_point8(_("Control handle 8:"), _("Control handle 8"), "gridpoint8", &wr, this), - grid_point9(_("Control handle 9:"), _("Control handle 9"), "gridpoint9", &wr, this), - grid_point10(_("Control handle 10:"), _("Control handle 10"), "gridpoint10", &wr, this), - grid_point11(_("Control handle 11:"), _("Control handle 11"), "gridpoint11", &wr, this), - grid_point12(_("Control handle 12:"), _("Control handle 12"), "gridpoint12", &wr, this), - grid_point13(_("Control handle 13:"), _("Control handle 13"), "gridpoint13", &wr, this), - grid_point14(_("Control handle 14:"), _("Control handle 14"), "gridpoint14", &wr, this), - grid_point15(_("Control handle 15:"), _("Control handle 15"), "gridpoint15", &wr, this) - + grid_point0(_("Control handle 0:"), _("Control handle 0"), "gridpoint0", &wr, this) + , grid_point1(_("Control handle 1:"), _("Control handle 1"), "gridpoint1", &wr, this) + , grid_point2(_("Control handle 2:"), _("Control handle 2"), "gridpoint2", &wr, this) + , grid_point3(_("Control handle 3:"), _("Control handle 3"), "gridpoint3", &wr, this) + , grid_point4(_("Control handle 4:"), _("Control handle 4"), "gridpoint4", &wr, this) + , grid_point5(_("Control handle 5:"), _("Control handle 5"), "gridpoint5", &wr, this) + , grid_point6(_("Control handle 6:"), _("Control handle 6"), "gridpoint6", &wr, this) + , grid_point7(_("Control handle 7:"), _("Control handle 7"), "gridpoint7", &wr, this) + , grid_point8(_("Control handle 8:"), _("Control handle 8"), "gridpoint8", &wr, this) + , grid_point9(_("Control handle 9:"), _("Control handle 9"), "gridpoint9", &wr, this) + , grid_point10(_("Control handle 10:"), _("Control handle 10"), "gridpoint10", &wr, this) + , grid_point11(_("Control handle 11:"), _("Control handle 11"), "gridpoint11", &wr, this) + , grid_point12(_("Control handle 12:"), _("Control handle 12"), "gridpoint12", &wr, this) + , grid_point13(_("Control handle 13:"), _("Control handle 13"), "gridpoint13", &wr, this) + , grid_point14(_("Control handle 14:"), _("Control handle 14"), "gridpoint14", &wr, this) + , grid_point15(_("Control handle 15:"), _("Control handle 15"), "gridpoint15", &wr, this) + { // register all your parameters here, so Inkscape knows which parameters this effect has: registerParameter(&grid_point0); @@ -71,26 +72,24 @@ LPELattice::LPELattice(LivePathEffectObject *lpeobject) : apply_to_clippath_and_mask = true; } -LPELattice::~LPELattice() -= default; +LPELattice::~LPELattice() = default; - -Geom::Piecewise > -LPELattice::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPELattice::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { D2 sb2; - - //Initialisation of the sb2 - for(unsigned dim = 0; dim < 2; dim++) { + + // Initialisation of the sb2 + for (unsigned dim = 0; dim < 2; dim++) { sb2[dim].us = 2; sb2[dim].vs = 2; - const int depth = sb2[dim].us*sb2[dim].vs; + const int depth = sb2[dim].us * sb2[dim].vs; sb2[dim].resize(depth, Linear2d(0)); } - //Grouping the point params in a convenient vector + // Grouping the point params in a convenient vector std::vector handles(16); - + handles[0] = &grid_point0; handles[1] = &grid_point1; handles[2] = &grid_point2; @@ -108,119 +107,116 @@ LPELattice::doEffect_pwd2 (Geom::Piecewise > const & pwd2 handles[14] = &grid_point14; handles[15] = &grid_point15; - Geom::Point origin = Geom::Point(boundingbox_X.min(),boundingbox_Y.min()); - + Geom::Point origin = Geom::Point(boundingbox_X.min(), boundingbox_Y.min()); + double width = boundingbox_X.extent(); double height = boundingbox_Y.extent(); - //numbering is based on 4 rectangles. - for(unsigned dim = 0; dim < 2; dim++) { - Geom::Point dir(0,0); + // numbering is based on 4 rectangles. + for (unsigned dim = 0; dim < 2; dim++) { + Geom::Point dir(0, 0); dir[dim] = 1; - for(unsigned vi = 0; vi < sb2[dim].vs; vi++) { - for(unsigned ui = 0; ui < sb2[dim].us; ui++) { - for(unsigned iv = 0; iv < 2; iv++) { - for(unsigned iu = 0; iu < 2; iu++) { - unsigned corner = iu + 2*iv; - unsigned i = ui + vi*sb2[dim].us; - - //This is the offset from the Upperleft point - Geom::Point base( (ui + iu*(3-2*ui))*width/3., - (vi + iv*(3-2*vi))*height/3.); - - //Special action for corners - if(vi == 0 && ui == 0) { - base = Geom::Point(0,0); + for (unsigned vi = 0; vi < sb2[dim].vs; vi++) { + for (unsigned ui = 0; ui < sb2[dim].us; ui++) { + for (unsigned iv = 0; iv < 2; iv++) { + for (unsigned iu = 0; iu < 2; iu++) { + unsigned corner = iu + 2 * iv; + unsigned i = ui + vi * sb2[dim].us; + + // This is the offset from the Upperleft point + Geom::Point base((ui + iu * (3 - 2 * ui)) * width / 3., (vi + iv * (3 - 2 * vi)) * height / 3.); + + // Special action for corners + if (vi == 0 && ui == 0) { + base = Geom::Point(0, 0); } - + // i = Upperleft corner of the considerated rectangle // corner = actual corner of the rectangle // origin = Upperleft point - double dl = dot((*handles[corner+4*i] - (base + origin)), dir)/dot(dir,dir); - sb2[dim][i][corner] = dl/( dim ? height : width )*pow(4.0,ui+vi); + double dl = dot((*handles[corner + 4 * i] - (base + origin)), dir) / dot(dir, dir); + sb2[dim][i][corner] = dl / (dim ? height : width) * pow(4.0, ui + vi); } } } } } - - Piecewise > output; + + Piecewise> output; output.push_cut(0.); - for(unsigned i = 0; i < pwd2_in.size(); i++) { + for (unsigned i = 0; i < pwd2_in.size(); i++) { D2 B = pwd2_in[i]; - B -= origin; - B*= 1/width; - //Here comes the magic - D2 tB = compose_each(sb2,B); + B -= origin; + B *= 1 / width; + // Here comes the magic + D2 tB = compose_each(sb2, B); tB = tB * width + origin; - output.push(tB,i+1); + output.push(tB, i + 1); } return output; } -void -LPELattice::doBeforeEffect (SPLPEItem const* lpeitem) +void LPELattice::doBeforeEffect(SPLPEItem const *lpeitem) { original_bbox(lpeitem, false, true); } -void -LPELattice::resetDefaults(SPItem const* item) +void LPELattice::resetDefaults(SPItem const *item) { Effect::resetDefaults(item); original_bbox(SP_LPE_ITEM(item), false, true); - + // place the 16 control points grid_point0[Geom::X] = boundingbox_X.min(); grid_point0[Geom::Y] = boundingbox_Y.min(); - + grid_point1[Geom::X] = boundingbox_X.max(); grid_point1[Geom::Y] = boundingbox_Y.min(); - + grid_point2[Geom::X] = boundingbox_X.min(); grid_point2[Geom::Y] = boundingbox_Y.max(); - + grid_point3[Geom::X] = boundingbox_X.max(); grid_point3[Geom::Y] = boundingbox_Y.max(); - - grid_point4[Geom::X] = 1.0/3*boundingbox_X.max()+2.0/3*boundingbox_X.min(); + + grid_point4[Geom::X] = 1.0 / 3 * boundingbox_X.max() + 2.0 / 3 * boundingbox_X.min(); grid_point4[Geom::Y] = boundingbox_Y.min(); - - grid_point5[Geom::X] = 2.0/3*boundingbox_X.max()+1.0/3*boundingbox_X.min(); + + grid_point5[Geom::X] = 2.0 / 3 * boundingbox_X.max() + 1.0 / 3 * boundingbox_X.min(); grid_point5[Geom::Y] = boundingbox_Y.min(); - - grid_point6[Geom::X] = 1.0/3*boundingbox_X.max()+2.0/3*boundingbox_X.min(); + + grid_point6[Geom::X] = 1.0 / 3 * boundingbox_X.max() + 2.0 / 3 * boundingbox_X.min(); grid_point6[Geom::Y] = boundingbox_Y.max(); - - grid_point7[Geom::X] = 2.0/3*boundingbox_X.max()+1.0/3*boundingbox_X.min(); + + grid_point7[Geom::X] = 2.0 / 3 * boundingbox_X.max() + 1.0 / 3 * boundingbox_X.min(); grid_point7[Geom::Y] = boundingbox_Y.max(); - + grid_point8[Geom::X] = boundingbox_X.min(); - grid_point8[Geom::Y] = 1.0/3*boundingbox_Y.max()+2.0/3*boundingbox_Y.min(); + grid_point8[Geom::Y] = 1.0 / 3 * boundingbox_Y.max() + 2.0 / 3 * boundingbox_Y.min(); grid_point9[Geom::X] = boundingbox_X.max(); - grid_point9[Geom::Y] = 1.0/3*boundingbox_Y.max()+2.0/3*boundingbox_Y.min(); - + grid_point9[Geom::Y] = 1.0 / 3 * boundingbox_Y.max() + 2.0 / 3 * boundingbox_Y.min(); + grid_point10[Geom::X] = boundingbox_X.min(); - grid_point10[Geom::Y] = 2.0/3*boundingbox_Y.max()+1.0/3*boundingbox_Y.min(); - + grid_point10[Geom::Y] = 2.0 / 3 * boundingbox_Y.max() + 1.0 / 3 * boundingbox_Y.min(); + grid_point11[Geom::X] = boundingbox_X.max(); - grid_point11[Geom::Y] = 2.0/3*boundingbox_Y.max()+1.0/3*boundingbox_Y.min(); - - grid_point12[Geom::X] = 1.0/3*boundingbox_X.max()+2.0/3*boundingbox_X.min(); - grid_point12[Geom::Y] = 1.0/3*boundingbox_Y.max()+2.0/3*boundingbox_Y.min(); - - grid_point13[Geom::X] = 2.0/3*boundingbox_X.max()+1.0/3*boundingbox_X.min(); - grid_point13[Geom::Y] = 1.0/3*boundingbox_Y.max()+2.0/3*boundingbox_Y.min(); - - grid_point14[Geom::X] = 1.0/3*boundingbox_X.max()+2.0/3*boundingbox_X.min(); - grid_point14[Geom::Y] = 2.0/3*boundingbox_Y.max()+1.0/3*boundingbox_Y.min(); - - grid_point15[Geom::X] = 2.0/3*boundingbox_X.max()+1.0/3*boundingbox_X.min(); - grid_point15[Geom::Y] = 2.0/3*boundingbox_Y.max()+1.0/3*boundingbox_Y.min(); + grid_point11[Geom::Y] = 2.0 / 3 * boundingbox_Y.max() + 1.0 / 3 * boundingbox_Y.min(); + + grid_point12[Geom::X] = 1.0 / 3 * boundingbox_X.max() + 2.0 / 3 * boundingbox_X.min(); + grid_point12[Geom::Y] = 1.0 / 3 * boundingbox_Y.max() + 2.0 / 3 * boundingbox_Y.min(); + + grid_point13[Geom::X] = 2.0 / 3 * boundingbox_X.max() + 1.0 / 3 * boundingbox_X.min(); + grid_point13[Geom::Y] = 1.0 / 3 * boundingbox_Y.max() + 2.0 / 3 * boundingbox_Y.min(); + + grid_point14[Geom::X] = 1.0 / 3 * boundingbox_X.max() + 2.0 / 3 * boundingbox_X.min(); + grid_point14[Geom::Y] = 2.0 / 3 * boundingbox_Y.max() + 1.0 / 3 * boundingbox_Y.min(); + + grid_point15[Geom::X] = 2.0 / 3 * boundingbox_X.max() + 1.0 / 3 * boundingbox_X.min(); + grid_point15[Geom::Y] = 2.0 / 3 * boundingbox_Y.max() + 1.0 / 3 * boundingbox_Y.min(); grid_point1.param_update_default(grid_point1); grid_point2.param_update_default(grid_point2); grid_point3.param_update_default(grid_point3); @@ -295,7 +291,7 @@ LPELattice::addHelperPathsImpl(SPLPEItem *lpeitem, SPDesktop *desktop) /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-lattice.h b/src/live_effects/lpe-lattice.h index 1d81355a9d9c7a22476b19850ae80e0aa1f977e0..7b1bcfba59e69ee1bfe1ce621b0e647e09a5a931 100644 --- a/src/live_effects/lpe-lattice.h +++ b/src/live_effects/lpe-lattice.h @@ -18,29 +18,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/enum.h" #include "live_effects/effect.h" -#include "live_effects/parameter/point.h" #include "live_effects/lpegroupbbox.h" +#include "live_effects/parameter/enum.h" +#include "live_effects/parameter/point.h" namespace Inkscape { namespace LivePathEffect { -class LPELattice : public Effect, GroupBBoxEffect { +class LPELattice + : public Effect + , GroupBBoxEffect +{ public: - LPELattice(LivePathEffectObject *lpeobject); ~LPELattice() override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; - - void resetDefaults(SPItem const* item) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; -protected: - //virtual void addHelperPathsImpl(SPLPEItem *lpeitem, SPDesktop *desktop); + void resetDefaults(SPItem const *item) override; +protected: + // virtual void addHelperPathsImpl(SPLPEItem *lpeitem, SPDesktop *desktop); private: PointParam grid_point0; @@ -59,11 +61,11 @@ private: PointParam grid_point13; PointParam grid_point14; PointParam grid_point15; - LPELattice(const LPELattice&) = delete; - LPELattice& operator=(const LPELattice&) = delete; + LPELattice(const LPELattice &) = delete; + LPELattice &operator=(const LPELattice &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-lattice2.cpp b/src/live_effects/lpe-lattice2.cpp index 0f0a44235ea2064de1aef5ce6c8e8940de56864a..0d3a35e2b29fd76dcd414663e8f1b48a144cb56e 100644 --- a/src/live_effects/lpe-lattice2.cpp +++ b/src/live_effects/lpe-lattice2.cpp @@ -17,12 +17,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "live_effects/lpe-lattice2.h" + +#include <2geom/bezier-to-sbasis.h> +#include <2geom/sbasis-2d.h> +#include + #include "display/curve.h" #include "helper/geom.h" -#include <2geom/sbasis-2d.h> -#include <2geom/bezier-to-sbasis.h> // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -32,38 +34,74 @@ using namespace Geom; namespace Inkscape { namespace LivePathEffect { -LPELattice2::LPELattice2(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - horizontal_mirror(_("Mirror movements in horizontal"), _("Mirror movements in horizontal"), "horizontal_mirror", &wr, this, false), - vertical_mirror(_("Mirror movements in vertical"), _("Mirror movements in vertical"), "vertical_mirror", &wr, this, false), - perimetral(_("Use only perimeter"), _("Use only perimeter"), "perimetral", &wr, this, false), - live_update(_("Update while moving knots (maybe slow)"), _("Update while moving knots (maybe slow)"), "live_update", &wr, this, true), - grid_point_0(_("Control 0:"), _("Control 0 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint0", &wr, this), - grid_point_1(_("Control 1:"), _("Control 1 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint1", &wr, this), - grid_point_2(_("Control 2:"), _("Control 2 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint2", &wr, this), - grid_point_3(_("Control 3:"), _("Control 3 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint3", &wr, this), - grid_point_4(_("Control 4:"), _("Control 4 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint4", &wr, this), - grid_point_5(_("Control 5:"), _("Control 5 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint5", &wr, this), - grid_point_6(_("Control 6:"), _("Control 6 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint6", &wr, this), - grid_point_7(_("Control 7:"), _("Control 7 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint7", &wr, this), - grid_point_8x9(_("Control 8x9:"), _("Control 8x9 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint8x9", &wr, this), - grid_point_10x11(_("Control 10x11:"), _("Control 10x11 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint10x11", &wr, this), - grid_point_12(_("Control 12:"), _("Control 12 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint12", &wr, this), - grid_point_13(_("Control 13:"), _("Control 13 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint13", &wr, this), - grid_point_14(_("Control 14:"), _("Control 14 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint14", &wr, this), - grid_point_15(_("Control 15:"), _("Control 15 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint15", &wr, this), - grid_point_16(_("Control 16:"), _("Control 16 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint16", &wr, this), - grid_point_17(_("Control 17:"), _("Control 17 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint17", &wr, this), - grid_point_18(_("Control 18:"), _("Control 18 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint18", &wr, this), - grid_point_19(_("Control 19:"), _("Control 19 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint19", &wr, this), - grid_point_20x21(_("Control 20x21:"), _("Control 20x21 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint20x21", &wr, this), - grid_point_22x23(_("Control 22x23:"), _("Control 22x23 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint22x23", &wr, this), - grid_point_24x26(_("Control 24x26:"), _("Control 24x26 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint24x26", &wr, this), - grid_point_25x27(_("Control 25x27:"), _("Control 25x27 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint25x27", &wr, this), - grid_point_28x30(_("Control 28x30:"), _("Control 28x30 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint28x30", &wr, this), - grid_point_29x31(_("Control 29x31:"), _("Control 29x31 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint29x31", &wr, this), - grid_point_32x33x34x35(_("Control 32x33x34x35:"), _("Control 32x33x34x35 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "gridpoint32x33x34x35", &wr, this), - expanded(false) +LPELattice2::LPELattice2(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , horizontal_mirror(_("Mirror movements in horizontal"), _("Mirror movements in horizontal"), "horizontal_mirror", + &wr, this, false) + , vertical_mirror(_("Mirror movements in vertical"), _("Mirror movements in vertical"), "vertical_mirror", &wr, + this, false) + , perimetral(_("Use only perimeter"), _("Use only perimeter"), "perimetral", &wr, this, false) + , live_update(_("Update while moving knots (maybe slow)"), _("Update while moving knots (maybe slow)"), + "live_update", &wr, this, true) + , grid_point_0(_("Control 0:"), _("Control 0 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint0", &wr, this) + , grid_point_1(_("Control 1:"), _("Control 1 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint1", &wr, this) + , grid_point_2(_("Control 2:"), _("Control 2 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint2", &wr, this) + , grid_point_3(_("Control 3:"), _("Control 3 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint3", &wr, this) + , grid_point_4(_("Control 4:"), _("Control 4 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint4", &wr, this) + , grid_point_5(_("Control 5:"), _("Control 5 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint5", &wr, this) + , grid_point_6(_("Control 6:"), _("Control 6 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint6", &wr, this) + , grid_point_7(_("Control 7:"), _("Control 7 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint7", &wr, this) + , grid_point_8x9(_("Control 8x9:"), _("Control 8x9 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint8x9", &wr, this) + , grid_point_10x11(_("Control 10x11:"), + _("Control 10x11 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint10x11", &wr, this) + , grid_point_12(_("Control 12:"), _("Control 12 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint12", &wr, this) + , grid_point_13(_("Control 13:"), _("Control 13 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint13", &wr, this) + , grid_point_14(_("Control 14:"), _("Control 14 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint14", &wr, this) + , grid_point_15(_("Control 15:"), _("Control 15 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint15", &wr, this) + , grid_point_16(_("Control 16:"), _("Control 16 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint16", &wr, this) + , grid_point_17(_("Control 17:"), _("Control 17 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint17", &wr, this) + , grid_point_18(_("Control 18:"), _("Control 18 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint18", &wr, this) + , grid_point_19(_("Control 19:"), _("Control 19 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint19", &wr, this) + , grid_point_20x21(_("Control 20x21:"), + _("Control 20x21 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint20x21", &wr, this) + , grid_point_22x23(_("Control 22x23:"), + _("Control 22x23 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint22x23", &wr, this) + , grid_point_24x26(_("Control 24x26:"), + _("Control 24x26 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint24x26", &wr, this) + , grid_point_25x27(_("Control 25x27:"), + _("Control 25x27 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint25x27", &wr, this) + , grid_point_28x30(_("Control 28x30:"), + _("Control 28x30 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint28x30", &wr, this) + , grid_point_29x31(_("Control 29x31:"), + _("Control 29x31 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint29x31", &wr, this) + , grid_point_32x33x34x35(_("Control 32x33x34x35:"), + _("Control 32x33x34x35 - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "gridpoint32x33x34x35", &wr, this) + , expanded(false) { // register all your parameters here, so Inkscape knows which parameters this effect has: registerParameter(&horizontal_mirror); @@ -98,32 +136,31 @@ LPELattice2::LPELattice2(LivePathEffectObject *lpeobject) : apply_to_clippath_and_mask = true; } -LPELattice2::~LPELattice2() -= default; +LPELattice2::~LPELattice2() = default; -Geom::Piecewise > -LPELattice2::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPELattice2::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { - PathVector pathv = path_from_piecewise(pwd2_in,0.001); - //this is because strange problems with sb2 and LineSegment + PathVector pathv = path_from_piecewise(pwd2_in, 0.001); + // this is because strange problems with sb2 and LineSegment PathVector cubic = pathv_to_cubicbezier(pathv); if (cubic.empty()) { return pwd2_in; } - Geom::Piecewise > const &pwd2_in_linear_and_cubic = paths_to_pw(cubic); + Geom::Piecewise> const &pwd2_in_linear_and_cubic = paths_to_pw(cubic); D2 sb2; - //Initialisation of the sb2 - for(unsigned dim = 0; dim < 2; dim++) { + // Initialisation of the sb2 + for (unsigned dim = 0; dim < 2; dim++) { sb2[dim].us = 3; sb2[dim].vs = 3; - const int depth = sb2[dim].us*sb2[dim].vs; + const int depth = sb2[dim].us * sb2[dim].vs; sb2[dim].resize(depth, Linear2d(0)); } - //Grouping the point params in a convenient vector + // Grouping the point params in a convenient vector - std::vector handles(36); + std::vector handles(36); handles[0] = grid_point_0; handles[1] = grid_point_1; @@ -162,94 +199,88 @@ LPELattice2::doEffect_pwd2 (Geom::Piecewise > const & pwd handles[34] = grid_point_32x33x34x35; handles[35] = grid_point_32x33x34x35; - Geom::Point origin = Geom::Point(boundingbox_X.min(),boundingbox_Y.min()); + Geom::Point origin = Geom::Point(boundingbox_X.min(), boundingbox_Y.min()); double width = boundingbox_X.extent(); double height = boundingbox_Y.extent(); - //numbering is based on 4 rectangles.16 - for(unsigned dim = 0; dim < 2; dim++) { - Geom::Point dir(0,0); + // numbering is based on 4 rectangles.16 + for (unsigned dim = 0; dim < 2; dim++) { + Geom::Point dir(0, 0); dir[dim] = 1; - for(unsigned vi = 0; vi < sb2[dim].vs; vi++) { - for(unsigned ui = 0; ui < sb2[dim].us; ui++) { - for(unsigned iv = 0; iv < 2; iv++) { - for(unsigned iu = 0; iu < 2; iu++) { - unsigned corner = iu + 2*iv; - unsigned i = ui + vi*sb2[dim].us; - - //This is the offset from the Upperleft point - Geom::Point base( (ui + iu*(4-2*ui))*width/4., - (vi + iv*(4-2*vi))*height/4.); - - //Special action for corners - if(vi == 0 && ui == 0) { - base = Geom::Point(0,0); + for (unsigned vi = 0; vi < sb2[dim].vs; vi++) { + for (unsigned ui = 0; ui < sb2[dim].us; ui++) { + for (unsigned iv = 0; iv < 2; iv++) { + for (unsigned iu = 0; iu < 2; iu++) { + unsigned corner = iu + 2 * iv; + unsigned i = ui + vi * sb2[dim].us; + + // This is the offset from the Upperleft point + Geom::Point base((ui + iu * (4 - 2 * ui)) * width / 4., (vi + iv * (4 - 2 * vi)) * height / 4.); + + // Special action for corners + if (vi == 0 && ui == 0) { + base = Geom::Point(0, 0); } // i = Upperleft corner of the considerated rectangle // corner = actual corner of the rectangle // origin = Upperleft point - double dl = dot((handles[corner+4*i] - (base + origin)), dir)/dot(dir,dir); - sb2[dim][i][corner] = dl/( dim ? height : width )*pow(4.0,ui+vi); + double dl = dot((handles[corner + 4 * i] - (base + origin)), dir) / dot(dir, dir); + sb2[dim][i][corner] = dl / (dim ? height : width) * pow(4.0, ui + vi); } } } } } - Piecewise > output; + Piecewise> output; output.push_cut(0.); - for(unsigned i = 0; i < pwd2_in_linear_and_cubic.size(); i++) { + for (unsigned i = 0; i < pwd2_in_linear_and_cubic.size(); i++) { D2 B = pwd2_in_linear_and_cubic[i]; B[Geom::X] -= origin[Geom::X]; - B[Geom::X]*= 1/width; + B[Geom::X] *= 1 / width; B[Geom::Y] -= origin[Geom::Y]; - B[Geom::Y]*= 1/height; - //Here comes the magic - D2 tB = compose_each(sb2,B); + B[Geom::Y] *= 1 / height; + // Here comes the magic + D2 tB = compose_each(sb2, B); tB[Geom::X] = tB[Geom::X] * width + origin[Geom::X]; tB[Geom::Y] = tB[Geom::Y] * height + origin[Geom::Y]; - output.push(tB,i+1); + output.push(tB, i + 1); } return output; } - -Gtk::Widget * -LPELattice2::newWidget() +Gtk::Widget *LPELattice2::newWidget() { // use manage here, because after deletion of Effect object, others might still be pointing to this widget. - Gtk::VBox * vbox = Gtk::manage( new Gtk::VBox(Effect::newWidget()) ); + Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox(Effect::newWidget())); vbox->set_border_width(5); vbox->set_homogeneous(false); vbox->set_spacing(6); - Gtk::HBox * hbox = Gtk::manage(new Gtk::HBox(false,0)); - Gtk::VBox * vbox_expander = Gtk::manage( new Gtk::VBox(Effect::newWidget()) ); + Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox(false, 0)); + Gtk::VBox *vbox_expander = Gtk::manage(new Gtk::VBox(Effect::newWidget())); vbox_expander->set_border_width(0); vbox_expander->set_spacing(2); - Gtk::Button * reset_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("Reset grid")))); - reset_button->signal_clicked().connect(sigc::mem_fun (*this,&LPELattice2::resetGrid)); - reset_button->set_size_request(140,30); - vbox->pack_start(*hbox, true,true,2); - hbox->pack_start(*reset_button, false, false,2); + Gtk::Button *reset_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("Reset grid")))); + reset_button->signal_clicked().connect(sigc::mem_fun(*this, &LPELattice2::resetGrid)); + reset_button->set_size_request(140, 30); + vbox->pack_start(*hbox, true, true, 2); + hbox->pack_start(*reset_button, false, false, 2); std::vector::iterator it = param_vector.begin(); while (it != param_vector.end()) { if ((*it)->widget_is_visible) { - Parameter * param = *it; - Gtk::Widget * widg = dynamic_cast(param->param_newWidget()); - if(param->param_key == "grid") { + Parameter *param = *it; + Gtk::Widget *widg = dynamic_cast(param->param_newWidget()); + if (param->param_key == "grid") { widg = nullptr; } - Glib::ustring * tip = param->param_getTooltip(); + Glib::ustring *tip = param->param_getTooltip(); if (widg) { - if (param->param_key == "horizontal_mirror" || - param->param_key == "vertical_mirror" || - param->param_key == "live_update" || - param->param_key == "perimetral") - { + if (param->param_key == "horizontal_mirror" || param->param_key == "vertical_mirror" || + param->param_key == "live_update" || param->param_key == "perimetral") { vbox->pack_start(*widg, true, true, 2); } else { vbox_expander->pack_start(*widg, true, true, 2); @@ -270,36 +301,34 @@ LPELattice2::newWidget() expander->add(*vbox_expander); expander->set_expanded(expanded); vbox->pack_start(*expander, true, true, 2); - expander->property_expanded().signal_changed().connect(sigc::mem_fun(*this, &LPELattice2::onExpanderChanged) ); - if(Gtk::Widget* widg = defaultParamSet()) { + expander->property_expanded().signal_changed().connect(sigc::mem_fun(*this, &LPELattice2::onExpanderChanged)); + if (Gtk::Widget *widg = defaultParamSet()) { vbox->pack_start(*widg, true, true, 2); } return dynamic_cast(vbox); } -void -LPELattice2::onExpanderChanged() +void LPELattice2::onExpanderChanged() { expanded = expander->get_expanded(); - if(expanded) { - expander->set_label (Glib::ustring(_("Hide Points"))); + if (expanded) { + expander->set_label(Glib::ustring(_("Hide Points"))); } else { - expander->set_label (Glib::ustring(_("Show Points"))); + expander->set_label(Glib::ustring(_("Show Points"))); } } -void -LPELattice2::vertical(PointParam ¶m_one, PointParam ¶m_two, Geom::Line vert) +void LPELattice2::vertical(PointParam ¶m_one, PointParam ¶m_two, Geom::Line vert) { Geom::Point A = param_one; Geom::Point B = param_two; - double Y = (A[Geom::Y] + B[Geom::Y])/2; + double Y = (A[Geom::Y] + B[Geom::Y]) / 2; A[Geom::Y] = Y; B[Geom::Y] = Y; Geom::Point nearest = vert.pointAt(vert.nearestTime(A)); - double distance_one = Geom::distance(A,nearest); - double distance_two = Geom::distance(B,nearest); - double distance_middle = (distance_one + distance_two)/2; - if(A[Geom::X] > B[Geom::X]) { + double distance_one = Geom::distance(A, nearest); + double distance_two = Geom::distance(B, nearest); + double distance_middle = (distance_one + distance_two) / 2; + if (A[Geom::X] > B[Geom::X]) { distance_middle *= -1; } A[Geom::X] = nearest[Geom::X] - distance_middle; @@ -308,19 +337,18 @@ LPELattice2::vertical(PointParam ¶m_one, PointParam ¶m_two, Geom::Line v param_two.param_setValue(B, live_update); } -void -LPELattice2::horizontal(PointParam ¶m_one, PointParam ¶m_two, Geom::Line horiz) +void LPELattice2::horizontal(PointParam ¶m_one, PointParam ¶m_two, Geom::Line horiz) { Geom::Point A = param_one; Geom::Point B = param_two; - double X = (A[Geom::X] + B[Geom::X])/2; + double X = (A[Geom::X] + B[Geom::X]) / 2; A[Geom::X] = X; B[Geom::X] = X; Geom::Point nearest = horiz.pointAt(horiz.nearestTime(A)); - double distance_one = Geom::distance(A,nearest); - double distance_two = Geom::distance(B,nearest); - double distance_middle = (distance_one + distance_two)/2; - if(A[Geom::Y] > B[Geom::Y]) { + double distance_one = Geom::distance(A, nearest); + double distance_two = Geom::distance(B, nearest); + double distance_middle = (distance_one + distance_two) / 2; + if (A[Geom::Y] > B[Geom::Y]) { distance_middle *= -1; } A[Geom::Y] = nearest[Geom::Y] - distance_middle; @@ -329,40 +357,38 @@ LPELattice2::horizontal(PointParam ¶m_one, PointParam ¶m_two, Geom::Line param_two.param_setValue(B, live_update); } - -void -LPELattice2::doBeforeEffect (SPLPEItem const* lpeitem) +void LPELattice2::doBeforeEffect(SPLPEItem const *lpeitem) { original_bbox(lpeitem, false, true); setDefaults(); if (is_applied) { resetGrid(); } - Geom::Line vert(grid_point_8x9.param_get_default(),grid_point_10x11.param_get_default()); - Geom::Line horiz(grid_point_24x26.param_get_default(),grid_point_25x27.param_get_default()); - if(vertical_mirror) { - vertical(grid_point_0, grid_point_1,vert); - vertical(grid_point_2, grid_point_3,vert); - vertical(grid_point_4, grid_point_5,vert); - vertical(grid_point_6, grid_point_7,vert); - vertical(grid_point_12, grid_point_13,vert); - vertical(grid_point_14, grid_point_15,vert); - vertical(grid_point_16, grid_point_17,vert); - vertical(grid_point_18, grid_point_19,vert); - vertical(grid_point_24x26, grid_point_25x27,vert); - vertical(grid_point_28x30, grid_point_29x31,vert); + Geom::Line vert(grid_point_8x9.param_get_default(), grid_point_10x11.param_get_default()); + Geom::Line horiz(grid_point_24x26.param_get_default(), grid_point_25x27.param_get_default()); + if (vertical_mirror) { + vertical(grid_point_0, grid_point_1, vert); + vertical(grid_point_2, grid_point_3, vert); + vertical(grid_point_4, grid_point_5, vert); + vertical(grid_point_6, grid_point_7, vert); + vertical(grid_point_12, grid_point_13, vert); + vertical(grid_point_14, grid_point_15, vert); + vertical(grid_point_16, grid_point_17, vert); + vertical(grid_point_18, grid_point_19, vert); + vertical(grid_point_24x26, grid_point_25x27, vert); + vertical(grid_point_28x30, grid_point_29x31, vert); } - if(horizontal_mirror) { - horizontal(grid_point_0, grid_point_2,horiz); - horizontal(grid_point_1, grid_point_3,horiz); - horizontal(grid_point_4, grid_point_6,horiz); - horizontal(grid_point_5, grid_point_7,horiz); - horizontal(grid_point_8x9, grid_point_10x11,horiz); - horizontal(grid_point_12, grid_point_14,horiz); - horizontal(grid_point_13, grid_point_15,horiz); - horizontal(grid_point_16, grid_point_18,horiz); - horizontal(grid_point_17, grid_point_19,horiz); - horizontal(grid_point_20x21, grid_point_22x23,horiz); + if (horizontal_mirror) { + horizontal(grid_point_0, grid_point_2, horiz); + horizontal(grid_point_1, grid_point_3, horiz); + horizontal(grid_point_4, grid_point_6, horiz); + horizontal(grid_point_5, grid_point_7, horiz); + horizontal(grid_point_8x9, grid_point_10x11, horiz); + horizontal(grid_point_12, grid_point_14, horiz); + horizontal(grid_point_13, grid_point_15, horiz); + horizontal(grid_point_16, grid_point_18, horiz); + horizontal(grid_point_17, grid_point_19, horiz); + horizontal(grid_point_20x21, grid_point_22x23, horiz); } if (perimetral) { grid_point_16.param_hide_knot(true); @@ -396,83 +422,82 @@ LPELattice2::doBeforeEffect (SPLPEItem const* lpeitem) } } -void -LPELattice2::setDefaults() +void LPELattice2::setDefaults() { - Geom::Point gp0((boundingbox_X.max()-boundingbox_X.min())/4*0+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*0+boundingbox_Y.min()); + Geom::Point gp0((boundingbox_X.max() - boundingbox_X.min()) / 4 * 0 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 0 + boundingbox_Y.min()); - Geom::Point gp1((boundingbox_X.max()-boundingbox_X.min())/4*4+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*0+boundingbox_Y.min()); + Geom::Point gp1((boundingbox_X.max() - boundingbox_X.min()) / 4 * 4 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 0 + boundingbox_Y.min()); - Geom::Point gp2((boundingbox_X.max()-boundingbox_X.min())/4*0+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*4+boundingbox_Y.min()); + Geom::Point gp2((boundingbox_X.max() - boundingbox_X.min()) / 4 * 0 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 4 + boundingbox_Y.min()); - Geom::Point gp3((boundingbox_X.max()-boundingbox_X.min())/4*4+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*4+boundingbox_Y.min()); + Geom::Point gp3((boundingbox_X.max() - boundingbox_X.min()) / 4 * 4 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 4 + boundingbox_Y.min()); - Geom::Point gp4((boundingbox_X.max()-boundingbox_X.min())/4*1+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*0+boundingbox_Y.min()); + Geom::Point gp4((boundingbox_X.max() - boundingbox_X.min()) / 4 * 1 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 0 + boundingbox_Y.min()); - Geom::Point gp5((boundingbox_X.max()-boundingbox_X.min())/4*3+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*0+boundingbox_Y.min()); + Geom::Point gp5((boundingbox_X.max() - boundingbox_X.min()) / 4 * 3 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 0 + boundingbox_Y.min()); - Geom::Point gp6((boundingbox_X.max()-boundingbox_X.min())/4*1+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*4+boundingbox_Y.min()); + Geom::Point gp6((boundingbox_X.max() - boundingbox_X.min()) / 4 * 1 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 4 + boundingbox_Y.min()); - Geom::Point gp7((boundingbox_X.max()-boundingbox_X.min())/4*3+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*4+boundingbox_Y.min()); + Geom::Point gp7((boundingbox_X.max() - boundingbox_X.min()) / 4 * 3 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 4 + boundingbox_Y.min()); - Geom::Point gp8x9((boundingbox_X.max()-boundingbox_X.min())/4*2+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*0+boundingbox_Y.min()); + Geom::Point gp8x9((boundingbox_X.max() - boundingbox_X.min()) / 4 * 2 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 0 + boundingbox_Y.min()); - Geom::Point gp10x11((boundingbox_X.max()-boundingbox_X.min())/4*2+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*4+boundingbox_Y.min()); + Geom::Point gp10x11((boundingbox_X.max() - boundingbox_X.min()) / 4 * 2 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 4 + boundingbox_Y.min()); - Geom::Point gp12((boundingbox_X.max()-boundingbox_X.min())/4*0+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*1+boundingbox_Y.min()); + Geom::Point gp12((boundingbox_X.max() - boundingbox_X.min()) / 4 * 0 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 1 + boundingbox_Y.min()); - Geom::Point gp13((boundingbox_X.max()-boundingbox_X.min())/4*4+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*1+boundingbox_Y.min()); + Geom::Point gp13((boundingbox_X.max() - boundingbox_X.min()) / 4 * 4 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 1 + boundingbox_Y.min()); - Geom::Point gp14((boundingbox_X.max()-boundingbox_X.min())/4*0+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*3+boundingbox_Y.min()); + Geom::Point gp14((boundingbox_X.max() - boundingbox_X.min()) / 4 * 0 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 3 + boundingbox_Y.min()); - Geom::Point gp15((boundingbox_X.max()-boundingbox_X.min())/4*4+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*3+boundingbox_Y.min()); + Geom::Point gp15((boundingbox_X.max() - boundingbox_X.min()) / 4 * 4 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 3 + boundingbox_Y.min()); - Geom::Point gp16((boundingbox_X.max()-boundingbox_X.min())/4*1+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*1+boundingbox_Y.min()); + Geom::Point gp16((boundingbox_X.max() - boundingbox_X.min()) / 4 * 1 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 1 + boundingbox_Y.min()); - Geom::Point gp17((boundingbox_X.max()-boundingbox_X.min())/4*3+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*1+boundingbox_Y.min()); + Geom::Point gp17((boundingbox_X.max() - boundingbox_X.min()) / 4 * 3 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 1 + boundingbox_Y.min()); - Geom::Point gp18((boundingbox_X.max()-boundingbox_X.min())/4*1+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*3+boundingbox_Y.min()); + Geom::Point gp18((boundingbox_X.max() - boundingbox_X.min()) / 4 * 1 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 3 + boundingbox_Y.min()); - Geom::Point gp19((boundingbox_X.max()-boundingbox_X.min())/4*3+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*3+boundingbox_Y.min()); + Geom::Point gp19((boundingbox_X.max() - boundingbox_X.min()) / 4 * 3 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 3 + boundingbox_Y.min()); - Geom::Point gp20x21((boundingbox_X.max()-boundingbox_X.min())/4*2+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*1+boundingbox_Y.min()); + Geom::Point gp20x21((boundingbox_X.max() - boundingbox_X.min()) / 4 * 2 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 1 + boundingbox_Y.min()); - Geom::Point gp22x23((boundingbox_X.max()-boundingbox_X.min())/4*2+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*3+boundingbox_Y.min()); + Geom::Point gp22x23((boundingbox_X.max() - boundingbox_X.min()) / 4 * 2 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 3 + boundingbox_Y.min()); - Geom::Point gp24x26((boundingbox_X.max()-boundingbox_X.min())/4*0+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*2+boundingbox_Y.min()); + Geom::Point gp24x26((boundingbox_X.max() - boundingbox_X.min()) / 4 * 0 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 2 + boundingbox_Y.min()); - Geom::Point gp25x27((boundingbox_X.max()-boundingbox_X.min())/4*4+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*2+boundingbox_Y.min()); + Geom::Point gp25x27((boundingbox_X.max() - boundingbox_X.min()) / 4 * 4 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 2 + boundingbox_Y.min()); - Geom::Point gp28x30((boundingbox_X.max()-boundingbox_X.min())/4*1+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*2+boundingbox_Y.min()); + Geom::Point gp28x30((boundingbox_X.max() - boundingbox_X.min()) / 4 * 1 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 2 + boundingbox_Y.min()); - Geom::Point gp29x31((boundingbox_X.max()-boundingbox_X.min())/4*3+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*2+boundingbox_Y.min()); + Geom::Point gp29x31((boundingbox_X.max() - boundingbox_X.min()) / 4 * 3 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 2 + boundingbox_Y.min()); - Geom::Point gp32x33x34x35((boundingbox_X.max()-boundingbox_X.min())/4*2+boundingbox_X.min(), - (boundingbox_Y.max()-boundingbox_Y.min())/4*2+boundingbox_Y.min()); + Geom::Point gp32x33x34x35((boundingbox_X.max() - boundingbox_X.min()) / 4 * 2 + boundingbox_X.min(), + (boundingbox_Y.max() - boundingbox_Y.min()) / 4 * 2 + boundingbox_Y.min()); grid_point_0.param_update_default(gp0); grid_point_1.param_update_default(gp1); @@ -526,8 +551,7 @@ LPELattice2::setDefaults() grid_point_32x33x34x35.param_set_liveupdate(live_update); } -void -LPELattice2::resetGrid() +void LPELattice2::resetGrid() { grid_point_0.param_set_default(); grid_point_1.param_set_default(); @@ -556,8 +580,7 @@ LPELattice2::resetGrid() grid_point_32x33x34x35.param_set_default(); } -void -LPELattice2::resetDefaults(SPItem const* item) +void LPELattice2::resetDefaults(SPItem const *item) { Effect::resetDefaults(item); original_bbox(SP_LPE_ITEM(item), false, true); @@ -565,108 +588,105 @@ LPELattice2::resetDefaults(SPItem const* item) resetGrid(); } -void -LPELattice2::calculateCurve(Geom::Point a,Geom::Point b, SPCurve* c, bool horizontal, bool move) +void LPELattice2::calculateCurve(Geom::Point a, Geom::Point b, SPCurve *c, bool horizontal, bool move) { using Geom::X; using Geom::Y; - if(move) c->moveto(a); - Geom::Point cubic1 = a + (1./3)* (b - a); - Geom::Point cubic2 = b + (1./3)* (a - b); - if(horizontal) c->curveto(Geom::Point(cubic1[X],a[Y]),Geom::Point(cubic2[X],b[Y]),b); - else c->curveto(Geom::Point(a[X],cubic1[Y]),Geom::Point(b[X],cubic2[Y]),b); + if (move) + c->moveto(a); + Geom::Point cubic1 = a + (1. / 3) * (b - a); + Geom::Point cubic2 = b + (1. / 3) * (a - b); + if (horizontal) + c->curveto(Geom::Point(cubic1[X], a[Y]), Geom::Point(cubic2[X], b[Y]), b); + else + c->curveto(Geom::Point(a[X], cubic1[Y]), Geom::Point(b[X], cubic2[Y]), b); } -void -LPELattice2::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) +void LPELattice2::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { hp_vec.clear(); SPCurve *c = new SPCurve(); if (perimetral) { - calculateCurve(grid_point_0,grid_point_4, c,true, true); - calculateCurve(grid_point_4,grid_point_8x9, c,true, false); - calculateCurve(grid_point_8x9,grid_point_5, c,true, false); - calculateCurve(grid_point_5,grid_point_1, c,true, false); - - calculateCurve(grid_point_1,grid_point_13, c, false, true); - calculateCurve(grid_point_13,grid_point_25x27, c,false, false); - calculateCurve(grid_point_25x27,grid_point_15, c,false, false); - calculateCurve(grid_point_15,grid_point_3, c, false, false); - - calculateCurve(grid_point_2,grid_point_6, c,true, true); - calculateCurve(grid_point_6,grid_point_10x11, c,true, false); - calculateCurve(grid_point_10x11,grid_point_7, c,true, false); - calculateCurve(grid_point_7,grid_point_3, c,true, false); - - calculateCurve(grid_point_0,grid_point_12, c,false, true); - calculateCurve(grid_point_12,grid_point_24x26, c,false, false); - calculateCurve(grid_point_24x26,grid_point_14, c,false, false); - calculateCurve(grid_point_14,grid_point_2, c,false, false); - + calculateCurve(grid_point_0, grid_point_4, c, true, true); + calculateCurve(grid_point_4, grid_point_8x9, c, true, false); + calculateCurve(grid_point_8x9, grid_point_5, c, true, false); + calculateCurve(grid_point_5, grid_point_1, c, true, false); + + calculateCurve(grid_point_1, grid_point_13, c, false, true); + calculateCurve(grid_point_13, grid_point_25x27, c, false, false); + calculateCurve(grid_point_25x27, grid_point_15, c, false, false); + calculateCurve(grid_point_15, grid_point_3, c, false, false); + + calculateCurve(grid_point_2, grid_point_6, c, true, true); + calculateCurve(grid_point_6, grid_point_10x11, c, true, false); + calculateCurve(grid_point_10x11, grid_point_7, c, true, false); + calculateCurve(grid_point_7, grid_point_3, c, true, false); + + calculateCurve(grid_point_0, grid_point_12, c, false, true); + calculateCurve(grid_point_12, grid_point_24x26, c, false, false); + calculateCurve(grid_point_24x26, grid_point_14, c, false, false); + calculateCurve(grid_point_14, grid_point_2, c, false, false); + } else { - calculateCurve(grid_point_0,grid_point_4, c,true, true); - calculateCurve(grid_point_4,grid_point_8x9, c,true, false); - calculateCurve(grid_point_8x9,grid_point_5, c,true, false); - calculateCurve(grid_point_5,grid_point_1, c,true, false); - - calculateCurve(grid_point_12,grid_point_16, c,true, true); - calculateCurve(grid_point_16,grid_point_20x21, c,true, false); - calculateCurve(grid_point_20x21,grid_point_17, c,true, false); - calculateCurve(grid_point_17,grid_point_13, c,true, false); - - calculateCurve(grid_point_24x26,grid_point_28x30, c,true, true); - calculateCurve(grid_point_28x30,grid_point_32x33x34x35, c,true, false); - calculateCurve(grid_point_32x33x34x35,grid_point_29x31, c,true, false); - calculateCurve(grid_point_29x31,grid_point_25x27, c,true, false); - - calculateCurve(grid_point_14,grid_point_18, c,true, true); - calculateCurve(grid_point_18,grid_point_22x23, c,true, false); - calculateCurve(grid_point_22x23,grid_point_19, c,true, false); - calculateCurve(grid_point_19,grid_point_15, c,true, false); - - calculateCurve(grid_point_2,grid_point_6, c,true, true); - calculateCurve(grid_point_6,grid_point_10x11, c,true, false); - calculateCurve(grid_point_10x11,grid_point_7, c,true, false); - calculateCurve(grid_point_7,grid_point_3, c,true, false); - - calculateCurve(grid_point_0,grid_point_12, c,false, true); - calculateCurve(grid_point_12,grid_point_24x26, c,false, false); - calculateCurve(grid_point_24x26,grid_point_14, c,false, false); - calculateCurve(grid_point_14,grid_point_2, c,false, false); - - calculateCurve(grid_point_4,grid_point_16, c,false, true); - calculateCurve(grid_point_16,grid_point_28x30, c,false, false); - calculateCurve(grid_point_28x30,grid_point_18, c,false, false); - calculateCurve(grid_point_18,grid_point_6, c,false, false); - - calculateCurve(grid_point_8x9,grid_point_20x21, c,false, true); - calculateCurve(grid_point_20x21,grid_point_32x33x34x35, c,false, false); - calculateCurve(grid_point_32x33x34x35,grid_point_22x23, c,false, false); - calculateCurve(grid_point_22x23,grid_point_10x11, c,false, false); - - calculateCurve(grid_point_5,grid_point_17, c, false, true); - calculateCurve(grid_point_17,grid_point_29x31, c,false, false); - calculateCurve(grid_point_29x31,grid_point_19, c,false, false); - calculateCurve(grid_point_19,grid_point_7, c,false, false); - - calculateCurve(grid_point_1,grid_point_13, c, false, true); - calculateCurve(grid_point_13,grid_point_25x27, c,false, false); - calculateCurve(grid_point_25x27,grid_point_15, c,false, false); - calculateCurve(grid_point_15,grid_point_3, c, false, false); + calculateCurve(grid_point_0, grid_point_4, c, true, true); + calculateCurve(grid_point_4, grid_point_8x9, c, true, false); + calculateCurve(grid_point_8x9, grid_point_5, c, true, false); + calculateCurve(grid_point_5, grid_point_1, c, true, false); + + calculateCurve(grid_point_12, grid_point_16, c, true, true); + calculateCurve(grid_point_16, grid_point_20x21, c, true, false); + calculateCurve(grid_point_20x21, grid_point_17, c, true, false); + calculateCurve(grid_point_17, grid_point_13, c, true, false); + + calculateCurve(grid_point_24x26, grid_point_28x30, c, true, true); + calculateCurve(grid_point_28x30, grid_point_32x33x34x35, c, true, false); + calculateCurve(grid_point_32x33x34x35, grid_point_29x31, c, true, false); + calculateCurve(grid_point_29x31, grid_point_25x27, c, true, false); + + calculateCurve(grid_point_14, grid_point_18, c, true, true); + calculateCurve(grid_point_18, grid_point_22x23, c, true, false); + calculateCurve(grid_point_22x23, grid_point_19, c, true, false); + calculateCurve(grid_point_19, grid_point_15, c, true, false); + + calculateCurve(grid_point_2, grid_point_6, c, true, true); + calculateCurve(grid_point_6, grid_point_10x11, c, true, false); + calculateCurve(grid_point_10x11, grid_point_7, c, true, false); + calculateCurve(grid_point_7, grid_point_3, c, true, false); + + calculateCurve(grid_point_0, grid_point_12, c, false, true); + calculateCurve(grid_point_12, grid_point_24x26, c, false, false); + calculateCurve(grid_point_24x26, grid_point_14, c, false, false); + calculateCurve(grid_point_14, grid_point_2, c, false, false); + + calculateCurve(grid_point_4, grid_point_16, c, false, true); + calculateCurve(grid_point_16, grid_point_28x30, c, false, false); + calculateCurve(grid_point_28x30, grid_point_18, c, false, false); + calculateCurve(grid_point_18, grid_point_6, c, false, false); + + calculateCurve(grid_point_8x9, grid_point_20x21, c, false, true); + calculateCurve(grid_point_20x21, grid_point_32x33x34x35, c, false, false); + calculateCurve(grid_point_32x33x34x35, grid_point_22x23, c, false, false); + calculateCurve(grid_point_22x23, grid_point_10x11, c, false, false); + + calculateCurve(grid_point_5, grid_point_17, c, false, true); + calculateCurve(grid_point_17, grid_point_29x31, c, false, false); + calculateCurve(grid_point_29x31, grid_point_19, c, false, false); + calculateCurve(grid_point_19, grid_point_7, c, false, false); + + calculateCurve(grid_point_1, grid_point_13, c, false, true); + calculateCurve(grid_point_13, grid_point_25x27, c, false, false); + calculateCurve(grid_point_25x27, grid_point_15, c, false, false); + calculateCurve(grid_point_15, grid_point_3, c, false, false); } hp_vec.push_back(c->get_pathvector()); } - /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ - - - /* Local Variables: mode:c++ diff --git a/src/live_effects/lpe-lattice2.h b/src/live_effects/lpe-lattice2.h index 319a0dc02c7f9657fe55d4fdac76b5c03307fa13..fae85ada5e56ff1f851f5e01ee6efc337b193d67 100644 --- a/src/live_effects/lpe-lattice2.h +++ b/src/live_effects/lpe-lattice2.h @@ -21,9 +21,9 @@ */ #include "live_effects/effect.h" +#include "live_effects/lpegroupbbox.h" #include "live_effects/parameter/enum.h" #include "live_effects/parameter/point.h" -#include "live_effects/lpegroupbbox.h" namespace Gtk { class Expander; @@ -32,25 +32,28 @@ class Expander; namespace Inkscape { namespace LivePathEffect { -class LPELattice2 : public Effect, GroupBBoxEffect { +class LPELattice2 + : public Effect + , GroupBBoxEffect +{ public: - LPELattice2(LivePathEffectObject *lpeobject); ~LPELattice2() override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; - void resetDefaults(SPItem const* item) override; + void resetDefaults(SPItem const *item) override; - void doBeforeEffect(SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; - Gtk::Widget * newWidget() override; + Gtk::Widget *newWidget() override; - void calculateCurve(Geom::Point a,Geom::Point b, SPCurve *c, bool horizontal, bool move); + void calculateCurve(Geom::Point a, Geom::Point b, SPCurve *c, bool horizontal, bool move); - void vertical(PointParam ¶mA,PointParam ¶mB, Geom::Line vert); + void vertical(PointParam ¶mA, PointParam ¶mB, Geom::Line vert); - void horizontal(PointParam ¶mA,PointParam ¶mB,Geom::Line horiz); + void horizontal(PointParam ¶mA, PointParam ¶mB, Geom::Line horiz); void setDefaults(); @@ -59,9 +62,9 @@ public: void resetGrid(); protected: - void addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) override; -private: + void addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) override; +private: BoolParam horizontal_mirror; BoolParam vertical_mirror; BoolParam perimetral; @@ -93,13 +96,13 @@ private: PointParam grid_point_32x33x34x35; bool expanded; - Gtk::Expander * expander; + Gtk::Expander *expander; - LPELattice2(const LPELattice2&) = delete; - LPELattice2& operator=(const LPELattice2&) = delete; + LPELattice2(const LPELattice2 &) = delete; + LPELattice2 &operator=(const LPELattice2 &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-line_segment.cpp b/src/live_effects/lpe-line_segment.cpp index 5c24aa9bed6028ccd8125f7e90f94da25bdc5319..89fe859bb8d3b633fbc4c999eeafe12e03397e98 100644 --- a/src/live_effects/lpe-line_segment.cpp +++ b/src/live_effects/lpe-line_segment.cpp @@ -13,6 +13,7 @@ */ #include "live_effects/lpe-line_segment.h" + #include "ui/tools/lpe-tool.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -21,32 +22,30 @@ namespace Inkscape { namespace LivePathEffect { static const Util::EnumData EndTypeData[] = { - {END_CLOSED , N_("Closed"), "closed"}, - {END_OPEN_INITIAL , N_("Open start"), "open_start"}, - {END_OPEN_FINAL , N_("Open end"), "open_end"}, - {END_OPEN_BOTH , N_("Open both"), "open_both"}, + {END_CLOSED, N_("Closed"), "closed"}, + {END_OPEN_INITIAL, N_("Open start"), "open_start"}, + {END_OPEN_FINAL, N_("Open end"), "open_end"}, + {END_OPEN_BOTH, N_("Open both"), "open_both"}, }; -static const Util::EnumDataConverter EndTypeConverter(EndTypeData, sizeof(EndTypeData)/sizeof(*EndTypeData)); +static const Util::EnumDataConverter EndTypeConverter(EndTypeData, sizeof(EndTypeData) / sizeof(*EndTypeData)); -LPELineSegment::LPELineSegment(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - end_type(_("End type:"), _("Determines on which side the line or line segment is infinite."), "end_type", EndTypeConverter, &wr, this, END_OPEN_BOTH) +LPELineSegment::LPELineSegment(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , end_type(_("End type:"), _("Determines on which side the line or line segment is infinite."), "end_type", + EndTypeConverter, &wr, this, END_OPEN_BOTH) { /* register all your parameters here, so Inkscape knows which parameters this effect has: */ registerParameter(&end_type); } -LPELineSegment::~LPELineSegment() -= default; +LPELineSegment::~LPELineSegment() = default; -void -LPELineSegment::doBeforeEffect (SPLPEItem const* lpeitem) +void LPELineSegment::doBeforeEffect(SPLPEItem const *lpeitem) { Inkscape::UI::Tools::lpetool_get_limiting_bbox_corners(lpeitem->document, bboxA, bboxB); } -Geom::PathVector -LPELineSegment::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPELineSegment::doEffect_path(Geom::PathVector const &path_in) { Geom::PathVector output; @@ -57,7 +56,7 @@ LPELineSegment::doEffect_path (Geom::PathVector const & path_in) boost::optional intersection_segment = Geom::Line(A, B).clip(dummyRect); if (!intersection_segment) { - g_print ("Possible error - no intersection with limiting bounding box.\n"); + g_print("Possible error - no intersection with limiting bounding box.\n"); return path_in; } @@ -77,7 +76,7 @@ LPELineSegment::doEffect_path (Geom::PathVector const & path_in) return output; } -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-line_segment.h b/src/live_effects/lpe-line_segment.h index c8d3080f26dbf89d4025282e0c5f754b8a446ef4..b02caf40500d4e851c25480929bb1d55e67bbfb1 100644 --- a/src/live_effects/lpe-line_segment.h +++ b/src/live_effects/lpe-line_segment.h @@ -15,41 +15,43 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/enum.h" #include "live_effects/effect.h" +#include "live_effects/parameter/enum.h" namespace Inkscape { namespace LivePathEffect { -enum EndType { +enum EndType +{ END_CLOSED, END_OPEN_INITIAL, END_OPEN_FINAL, END_OPEN_BOTH }; -class LPELineSegment : public Effect { +class LPELineSegment : public Effect +{ public: LPELineSegment(LivePathEffectObject *lpeobject); ~LPELineSegment() override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; -//private: + // private: EnumParam end_type; private: - Geom::Point A, B; // intersections of the line segment with the limiting bounding box + Geom::Point A, B; // intersections of the line segment with the limiting bounding box Geom::Point bboxA, bboxB; // upper left and lower right corner of limiting bounding box - LPELineSegment(const LPELineSegment&) = delete; - LPELineSegment& operator=(const LPELineSegment&) = delete; + LPELineSegment(const LPELineSegment &) = delete; + LPELineSegment &operator=(const LPELineSegment &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-measure-segments.cpp b/src/live_effects/lpe-measure-segments.cpp index bd78d8f34f03705405d519a2263fd1aceb23b219..a1acba2e94a61630194d140979ac5bce567b25f2 100644 --- a/src/live_effects/lpe-measure-segments.cpp +++ b/src/live_effects/lpe-measure-segments.cpp @@ -10,43 +10,44 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/lpeobject.h" -#include "live_effects/lpeobject-reference.h" #include "live_effects/lpe-measure-segments.h" + +#include +#include +#include +#include + #include "2geom/affine.h" #include "2geom/angle.h" #include "2geom/point.h" #include "2geom/ray.h" #include "display/curve.h" +#include "document-undo.h" +#include "document.h" #include "helper/geom.h" -#include "text-editing.h" +#include "inkscape.h" +#include "libnrtype/Layout-TNG.h" +#include "live_effects/lpeobject-reference.h" +#include "live_effects/lpeobject.h" #include "object/sp-defs.h" -#include "object/sp-text.h" #include "object/sp-flowtext.h" #include "object/sp-item-group.h" #include "object/sp-item.h" #include "object/sp-path.h" #include "object/sp-root.h" #include "object/sp-shape.h" +#include "object/sp-text.h" +#include "path-chemistry.h" +#include "preferences.h" +#include "style.h" #include "svg/stringstream.h" -#include "svg/svg.h" #include "svg/svg-color.h" #include "svg/svg-length.h" +#include "svg/svg.h" +#include "text-editing.h" #include "util/units.h" #include "xml/node.h" #include "xml/sp-css-attr.h" -#include "libnrtype/Layout-TNG.h" -#include "document.h" -#include "document-undo.h" -#include "inkscape.h" -#include "preferences.h" -#include "path-chemistry.h" -#include "style.h" - -#include -#include -#include -#include // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -55,55 +56,87 @@ using namespace Geom; namespace Inkscape { namespace LivePathEffect { - static const Util::EnumData OrientationMethodData[] = { - { OM_HORIZONTAL , N_("Horizontal"), "horizontal" }, - { OM_VERTICAL , N_("Vertical") , "vertical" }, - { OM_PARALLEL , N_("Parallel") , "parallel" } -}; + {OM_HORIZONTAL, N_("Horizontal"), "horizontal"}, + {OM_VERTICAL, N_("Vertical"), "vertical"}, + {OM_PARALLEL, N_("Parallel"), "parallel"}}; static const Util::EnumDataConverter OMConverter(OrientationMethodData, OM_END); -LPEMeasureSegments::LPEMeasureSegments(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - unit(_("Unit"), _("Unit of measurement"), "unit", &wr, this, "mm"), - orientation(_("Orientation"), _("Orientation of the line and labels"), "orientation", OMConverter, &wr, this, OM_PARALLEL, false), - coloropacity(_("Color and opacity"), _("Set color and opacity of the dimensions"), "coloropacity", &wr, this, 0x000000ff), - fontbutton(_("Font"), _("Select font for labels"), "fontbutton", &wr, this), - precision(_("Precision"), _("Number of digits after the decimal point"), "precision", &wr, this, 2), - fix_overlaps(_("Merge overlaps °"), _("Minimum angle at which overlapping dimension lines are merged into one, use 180° to disable merging"), "fix_overlaps", &wr, this, 0), - position(_("Position"), _("Distance of dimension line from the path"), "position", &wr, this, 5), - text_top_bottom(_("Label position"), _("Distance of the labels from the dimension line"), "text_top_bottom", &wr, this, 0), - helpline_distance(_("Help line distance"), _("Distance of the perpendicular lines from the path"), "helpline_distance", &wr, this, 0.0), - helpline_overlap(_("Help line elongation"), _("Distance of the perpendicular lines' ends from the dimension line"), "helpline_overlap", &wr, this, 2.0), - line_width(_("Line width"), _("Dimension line width. DIN standard: 0.25 or 0.35 mm"), "line_width", &wr, this, 0.25), - scale(_("Scale"), _("Scaling factor"), "scale", &wr, this, 1.0), - +LPEMeasureSegments::LPEMeasureSegments(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , unit(_("Unit"), _("Unit of measurement"), "unit", &wr, this, "mm") + , orientation(_("Orientation"), _("Orientation of the line and labels"), "orientation", OMConverter, &wr, this, + OM_PARALLEL, false) + , coloropacity(_("Color and opacity"), _("Set color and opacity of the dimensions"), "coloropacity", &wr, this, + 0x000000ff) + , fontbutton(_("Font"), _("Select font for labels"), "fontbutton", &wr, this) + , precision(_("Precision"), _("Number of digits after the decimal point"), "precision", &wr, this, 2) + , fix_overlaps( + _("Merge overlaps °"), + _("Minimum angle at which overlapping dimension lines are merged into one, use 180° to disable merging"), + "fix_overlaps", &wr, this, 0) + , position(_("Position"), _("Distance of dimension line from the path"), "position", &wr, this, 5) + , text_top_bottom(_("Label position"), _("Distance of the labels from the dimension line"), "text_top_bottom", &wr, + this, 0) + , helpline_distance(_("Help line distance"), _("Distance of the perpendicular lines from the path"), + "helpline_distance", &wr, this, 0.0) + , helpline_overlap(_("Help line elongation"), + _("Distance of the perpendicular lines' ends from the dimension line"), "helpline_overlap", &wr, + this, 2.0) + , line_width(_("Line width"), _("Dimension line width. DIN standard: 0.25 or 0.35 mm"), "line_width", &wr, this, + 0.25) + , scale(_("Scale"), _("Scaling factor"), "scale", &wr, this, 1.0) + , + // TRANSLATORS: Don't translate "{measure}" and "{unit}" variables. - format(_("Label format"), _("Label text format, available variables: {measure}, {unit}"), "format", &wr, this,"{measure}{unit}"), - blacklist(_("Blacklist segments"), _("Comma-separated list of indices of segments that should not be measured. You can use another LPE with different parameters to measure these."), "blacklist", &wr, this,""), - whitelist(_("Invert blacklist"), _("Use the blacklist as whitelist"), "whitelist", &wr, this, false), - showindex(_("Show segment index"), _("Display the index of the segments in the text label for easier blacklisting"), "showindex", &wr, this, false), - arrows_outside(_("Arrows outside"), _("Draw arrows pointing in the opposite direction outside the dimension line"), "arrows_outside", &wr, this, false), - flip_side(_("Flip side"), _("Draw dimension lines and labels on the other side of the path"), "flip_side", &wr, this, false), - scale_sensitive(_("Scale sensitive"), _("When the path is grouped and the group is then scaled, adjust the dimensions."), "scale_sensitive", &wr, this, true), - local_locale(_("Localize number format"), _("Use localized number formatting, e.g. '1,0' instead of '1.0' with German locale"), "local_locale", &wr, this, true), - rotate_anotation(_("Rotate labels"), _("Labels are parallel to the dimension line"), "rotate_anotation", &wr, this, true), - hide_back(_("Hide line under label"), _("Hide the dimension line where the label overlaps it"), "hide_back", &wr, this, true), - hide_arrows(_("Hide arrows"), _("Don't show any arrows"), "hide_arrows", &wr, this, false), + format(_("Label format"), _("Label text format, available variables: {measure}, {unit}"), "format", &wr, this, + "{measure}{unit}") + , blacklist(_("Blacklist segments"), + _("Comma-separated list of indices of segments that should not be measured. You can use another LPE " + "with different parameters to measure these."), + "blacklist", &wr, this, "") + , whitelist(_("Invert blacklist"), _("Use the blacklist as whitelist"), "whitelist", &wr, this, false) + , showindex(_("Show segment index"), + _("Display the index of the segments in the text label for easier blacklisting"), "showindex", &wr, + this, false) + , arrows_outside(_("Arrows outside"), + _("Draw arrows pointing in the opposite direction outside the dimension line"), "arrows_outside", + &wr, this, false) + , flip_side(_("Flip side"), _("Draw dimension lines and labels on the other side of the path"), "flip_side", &wr, + this, false) + , scale_sensitive(_("Scale sensitive"), + _("When the path is grouped and the group is then scaled, adjust the dimensions."), + "scale_sensitive", &wr, this, true) + , local_locale(_("Localize number format"), + _("Use localized number formatting, e.g. '1,0' instead of '1.0' with German locale"), "local_locale", + &wr, this, true) + , rotate_anotation(_("Rotate labels"), _("Labels are parallel to the dimension line"), "rotate_anotation", &wr, + this, true) + , hide_back(_("Hide line under label"), _("Hide the dimension line where the label overlaps it"), "hide_back", &wr, + this, true) + , hide_arrows(_("Hide arrows"), _("Don't show any arrows"), "hide_arrows", &wr, this, false) + , // active for 1.1 - smallx100(_("Multiply values < 1"), _("Multiply values smaller than 1 by 100 and leave out the unit"), "smallx100", &wr, this, false), - linked_items(_("Linked objects:"), _("Objects whose nodes are projected onto the path and generate new measurements"), "linked_items", &wr, this), - distance_projection(_("Distance"), _("Distance of the dimension lines from the outermost node"), "distance_projection", &wr, this, 20.0), - angle_projection(_("Angle of projection"), _("Angle of projection in 90° steps"), "angle_projection", &wr, this, 0.0), - active_projection(_("Activate projection"), _("Activate projection mode"), "active_projection", &wr, this, false), - avoid_overlapping(_("Avoid label overlap"), _("Rotate labels if the segment is shorter than the label"), "avoid_overlapping", &wr, this, true), - onbbox(_("Measure bounding box"), _("Add measurements for the geometrical bounding box"), "onbbox", &wr, this, false), - bboxonly(_("Only bounding box"), _("Measure only the geometrical bounding box"), "bboxonly", &wr, this, false), - centers(_("Add object center"), _("Add the projected object center"), "centers", &wr, this, false), - maxmin(_("Only max and min"), _("Compute only max/min projection values"), "maxmin", &wr, this, false), - helpdata(_("Help"), _("Measure segments help"), "helpdata", &wr, this, "", "") + smallx100(_("Multiply values < 1"), _("Multiply values smaller than 1 by 100 and leave out the unit"), "smallx100", + &wr, this, false) + , linked_items(_("Linked objects:"), + _("Objects whose nodes are projected onto the path and generate new measurements"), "linked_items", + &wr, this) + , distance_projection(_("Distance"), _("Distance of the dimension lines from the outermost node"), + "distance_projection", &wr, this, 20.0) + , angle_projection(_("Angle of projection"), _("Angle of projection in 90° steps"), "angle_projection", &wr, this, + 0.0) + , active_projection(_("Activate projection"), _("Activate projection mode"), "active_projection", &wr, this, false) + , avoid_overlapping(_("Avoid label overlap"), _("Rotate labels if the segment is shorter than the label"), + "avoid_overlapping", &wr, this, true) + , onbbox(_("Measure bounding box"), _("Add measurements for the geometrical bounding box"), "onbbox", &wr, this, + false) + , bboxonly(_("Only bounding box"), _("Measure only the geometrical bounding box"), "bboxonly", &wr, this, false) + , centers(_("Add object center"), _("Add the projected object center"), "centers", &wr, this, false) + , maxmin(_("Only max and min"), _("Compute only max/min projection values"), "maxmin", &wr, this, false) + , helpdata(_("Help"), _("Measure segments help"), "helpdata", &wr, this, "", "") { - //set to true the parameters you want to be changed his default values + // set to true the parameters you want to be changed his default values registerParameter(&unit); registerParameter(&orientation); registerParameter(&coloropacity); @@ -142,7 +175,7 @@ LPEMeasureSegments::LPEMeasureSegments(LivePathEffectObject *lpeobject) : Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring format_value = prefs->getString("/live_effects/measure-line/format"); - if(format_value.empty()){ + if (format_value.empty()) { format_value = "{measure}{unit}"; } format.param_update_default(format_value.c_str()); @@ -188,32 +221,33 @@ LPEMeasureSegments::LPEMeasureSegments(LivePathEffectObject *lpeobject) : fontsize = 0; rgb32 = 0; arrow_gap = 0; - //TODO: add newlines for 1.1 (not easy) - helpdata.param_update_default(_("General\n" - "Display and position dimension lines and labels\n\n" - "Projection\n" - "Show a line with measurements based on the selected items\n\n" - "Options\n" - "Options for color, precision, label formatting and display\n\n" - "Tips\n" - "Custom styling: To further customize the styles, " - "use the XML editor to find out the class or ID, then use the " - "Style dialog to apply a new style.\n" - "Blacklists: allow to hide some segments or projection steps.\n" - "Multiple Measure LPEs: In the same object, in conjunction with blacklists," - "this allows for labels and measurements with different orientations or additional projections.\n" - "Set Defaults: For every LPE, default values can be set at the bottom.")); + // TODO: add newlines for 1.1 (not easy) + helpdata.param_update_default( + _("General\n" + "Display and position dimension lines and labels\n\n" + "Projection\n" + "Show a line with measurements based on the selected items\n\n" + "Options\n" + "Options for color, precision, label formatting and display\n\n" + "Tips\n" + "Custom styling: To further customize the styles, " + "use the XML editor to find out the class or ID, then use the " + "Style dialog to apply a new style.\n" + "Blacklists: allow to hide some segments or projection steps.\n" + "Multiple Measure LPEs: In the same object, in conjunction with blacklists," + "this allows for labels and measurements with different orientations or additional projections.\n" + "Set Defaults: For every LPE, default values can be set at the bottom.")); } -LPEMeasureSegments::~LPEMeasureSegments() { +LPEMeasureSegments::~LPEMeasureSegments() +{ doOnRemove(nullptr); } -Gtk::Widget * -LPEMeasureSegments::newWidget() +Gtk::Widget *LPEMeasureSegments::newWidget() { // use manage here, because after deletion of Effect object, others might still be pointing to this widget. - Gtk::VBox * vbox = Gtk::manage( new Gtk::VBox() ); + Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox()); vbox->set_border_width(0); vbox->set_homogeneous(false); vbox->set_spacing(0); @@ -229,7 +263,7 @@ LPEMeasureSegments::newWidget() vbox2->set_border_width(5); vbox2->set_homogeneous(false); vbox2->set_spacing(2); - //Help page + // Help page Gtk::VBox *vbox3 = Gtk::manage(new Gtk::VBox()); vbox3->set_border_width(5); vbox3->set_homogeneous(false); @@ -237,45 +271,34 @@ LPEMeasureSegments::newWidget() std::vector::iterator it = param_vector.begin(); while (it != param_vector.end()) { if ((*it)->widget_is_visible) { - Parameter * param = *it; - Gtk::Widget * widg = param->param_newWidget(); - Glib::ustring * tip = param->param_getTooltip(); + Parameter *param = *it; + Gtk::Widget *widg = param->param_newWidget(); + Glib::ustring *tip = param->param_getTooltip(); if (widg) { - if ( param->param_key == "linked_items") { + if (param->param_key == "linked_items") { vbox1->pack_start(*widg, true, true, 2); - } else if (param->param_key == "active_projection" || - param->param_key == "distance_projection" || - param->param_key == "angle_projection" || - param->param_key == "maxmin" || - param->param_key == "centers" || - param->param_key == "bboxonly" || - param->param_key == "onbbox" ) - { + } else if (param->param_key == "active_projection" || param->param_key == "distance_projection" || + param->param_key == "angle_projection" || param->param_key == "maxmin" || + param->param_key == "centers" || param->param_key == "bboxonly" || + param->param_key == "onbbox") { vbox1->pack_start(*widg, false, true, 2); - } else if (param->param_key == "precision" || - param->param_key == "coloropacity" || - param->param_key == "font" || - param->param_key == "format" || - param->param_key == "blacklist" || - param->param_key == "whitelist" || - param->param_key == "showindex" || - param->param_key == "local_locale" || - param->param_key == "hide_arrows" ) - { + } else if (param->param_key == "precision" || param->param_key == "coloropacity" || + param->param_key == "font" || param->param_key == "format" || + param->param_key == "blacklist" || param->param_key == "whitelist" || + param->param_key == "showindex" || param->param_key == "local_locale" || + param->param_key == "hide_arrows") { vbox2->pack_start(*widg, false, true, 2); - } else if (//TOD: unhack for 1.1 - param->param_key == "smallx100" ) - { - Glib::ustring widgl = param->param_label; + } else if ( // TOD: unhack for 1.1 + param->param_key == "smallx100") { + Glib::ustring widgl = param->param_label; size_t pos = widgl.find("<"); - if (pos != std::string::npos ) { + if (pos != std::string::npos) { widgl.erase(pos, 1); widgl.insert(pos, "<"); } param->param_label = widgl.c_str(); vbox2->pack_start(*widg, false, true, 2); - } else if (param->param_key == "helpdata") - { + } else if (param->param_key == "helpdata") { vbox3->pack_start(*widg, false, true, 2); } else { vbox0->pack_start(*widg, false, true, 2); @@ -293,11 +316,11 @@ LPEMeasureSegments::newWidget() ++it; } - Gtk::Notebook * notebook = Gtk::manage(new Gtk::Notebook()); - notebook->append_page (*vbox0, Glib::ustring(_("General"))); - notebook->append_page (*vbox1, Glib::ustring(_("Projection"))); - notebook->append_page (*vbox2, Glib::ustring(_("Options"))); - notebook->append_page (*vbox3, Glib::ustring(_("Help"))); + Gtk::Notebook *notebook = Gtk::manage(new Gtk::Notebook()); + notebook->append_page(*vbox0, Glib::ustring(_("General"))); + notebook->append_page(*vbox1, Glib::ustring(_("Projection"))); + notebook->append_page(*vbox2, Glib::ustring(_("Options"))); + notebook->append_page(*vbox3, Glib::ustring(_("Help"))); vbox0->show_all(); vbox1->show_all(); vbox2->show_all(); @@ -305,8 +328,8 @@ LPEMeasureSegments::newWidget() vbox->pack_start(*notebook, true, true, 2); notebook->set_current_page(pagenumber); notebook->signal_switch_page().connect(sigc::mem_fun(*this, &LPEMeasureSegments::on_my_switch_page)); - if(Gtk::Widget* widg = defaultParamSet()) { - //Wrap to make it more omogenious + if (Gtk::Widget *widg = defaultParamSet()) { + // Wrap to make it more omogenious Gtk::VBox *vbox4 = Gtk::manage(new Gtk::VBox()); vbox4->set_border_width(5); vbox4->set_homogeneous(false); @@ -317,23 +340,21 @@ LPEMeasureSegments::newWidget() return dynamic_cast(vbox); } -void -LPEMeasureSegments::on_my_switch_page(Gtk::Widget* page, guint page_number) +void LPEMeasureSegments::on_my_switch_page(Gtk::Widget *page, guint page_number) { - if(!page->get_parent()->in_destruction()) { + if (!page->get_parent()->in_destruction()) { pagenumber = page_number; } } -void -LPEMeasureSegments::createArrowMarker(Glib::ustring mode) +void LPEMeasureSegments::createArrowMarker(Glib::ustring mode) { SPDocument *document = getSPDoc(); - if (!document || !sp_lpe_item|| !sp_lpe_item->getId()) { + if (!document || !sp_lpe_item || !sp_lpe_item->getId()) { return; } Glib::ustring lpobjid = this->lpeobj->getId(); - Glib::ustring itemid = sp_lpe_item->getId(); + Glib::ustring itemid = sp_lpe_item->getId(); Glib::ustring style; style = Glib::ustring("fill:context-stroke;"); Inkscape::SVGOStringStream os; @@ -344,7 +365,7 @@ LPEMeasureSegments::createArrowMarker(Glib::ustring mode) SPObject *elemref = nullptr; Inkscape::XML::Node *arrow = nullptr; if ((elemref = document->getObjectById(mode.c_str()))) { - Inkscape::XML::Node *arrow= elemref->getRepr(); + Inkscape::XML::Node *arrow = elemref->getRepr(); if (arrow) { arrow->setAttribute("sodipodi:insensitive", "true"); arrow->removeAttribute("transform"); @@ -395,8 +416,8 @@ LPEMeasureSegments::createArrowMarker(Glib::ustring mode) items.push_back(mode); } -void -LPEMeasureSegments::createTextLabel(Geom::Point pos, size_t counter, double length, Geom::Coord angle, bool remove, bool valid) +void LPEMeasureSegments::createTextLabel(Geom::Point pos, size_t counter, double length, Geom::Coord angle, bool remove, + bool valid) { SPDocument *document = getSPDoc(); if (!document || !sp_lpe_item || !sp_lpe_item->getId()) { @@ -404,7 +425,7 @@ LPEMeasureSegments::createTextLabel(Geom::Point pos, size_t counter, double leng } Inkscape::XML::Document *xml_doc = document->getReprDoc(); Glib::ustring lpobjid = this->lpeobj->getId(); - Glib::ustring itemid = sp_lpe_item->getId(); + Glib::ustring itemid = sp_lpe_item->getId(); Glib::ustring id = Glib::ustring("text-on-"); id += Glib::ustring::format(counter); id += "-"; @@ -459,51 +480,51 @@ LPEMeasureSegments::createTextLabel(Geom::Point pos, size_t counter, double leng auto fontbutton_str = fontbutton.param_getSVGValue(); fontlister->fill_css(css, fontbutton_str); std::stringstream font_size; - setlocale (LC_NUMERIC, "C"); - font_size << fontsize << "px"; - setlocale (LC_NUMERIC, locale_base); + setlocale(LC_NUMERIC, "C"); + font_size << fontsize << "px"; + setlocale(LC_NUMERIC, locale_base); gchar c[32]; sprintf(c, "#%06x", rgb32 >> 8); - sp_repr_css_set_property (css, "fill",c); + sp_repr_css_set_property(css, "fill", c); Inkscape::SVGOStringStream os; os << SP_RGBA32_A_F(coloropacity.get_value()); - sp_repr_css_set_property (css, "fill-opacity",os.str().c_str()); - sp_repr_css_set_property (css, "font-size",font_size.str().c_str()); - sp_repr_css_unset_property (css, "-inkscape-font-specification"); + sp_repr_css_set_property(css, "fill-opacity", os.str().c_str()); + sp_repr_css_set_property(css, "font-size", font_size.str().c_str()); + sp_repr_css_unset_property(css, "-inkscape-font-specification"); if (remove) { - sp_repr_css_set_property (css, "display","none"); + sp_repr_css_set_property(css, "display", "none"); } Glib::ustring css_str; - sp_repr_css_write_string(css,css_str); + sp_repr_css_write_string(css, css_str); rtext->setAttributeOrRemoveIfEmpty("style", css_str); rtspan->setAttributeOrRemoveIfEmpty("style", css_str); rtspan->removeAttribute("transform"); - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); length = Inkscape::Util::Quantity::convert(length, display_unit.c_str(), unit.get_abbreviation()); if (local_locale) { - setlocale (LC_NUMERIC, ""); + setlocale(LC_NUMERIC, ""); } else { - setlocale (LC_NUMERIC, "C"); + setlocale(LC_NUMERIC, "C"); } gchar length_str[64]; bool x100 = false; // active for 1.1 - if (smallx100 && length < 1 ) { - length *=100; + if (smallx100 && length < 1) { + length *= 100; x100 = true; g_snprintf(length_str, 64, "%.*f", (int)precision - 2, length); - } else { + } else { g_snprintf(length_str, 64, "%.*f", (int)precision, length); } - setlocale (LC_NUMERIC, locale_base); + setlocale(LC_NUMERIC, locale_base); auto label_value = format.param_getSVGValue(); - size_t s = label_value.find(Glib::ustring("{measure}"),0); - if(s < label_value.length()) { + size_t s = label_value.find(Glib::ustring("{measure}"), 0); + if (s < label_value.length()) { label_value.replace(s, 9, length_str); } - - s = label_value.find(Glib::ustring("{unit}"),0); - if(s < label_value.length()) { + + s = label_value.find(Glib::ustring("{unit}"), 0); + if (s < label_value.length()) { if (x100) { label_value.replace(s, 6, ""); } else { @@ -526,14 +547,16 @@ LPEMeasureSegments::createTextLabel(Geom::Point pos, size_t counter, double leng rtspan->removeAttribute("style"); } - gchar * transform; + gchar *transform; if (rotate_anotation) { Geom::Affine affine = Geom::Affine(Geom::Translate(pos).inverse()); - angle = std::fmod(angle, 2*M_PI); - if (angle < 0) angle += 2*M_PI; + angle = std::fmod(angle, 2 * M_PI); + if (angle < 0) + angle += 2 * M_PI; if (angle >= rad_from_deg(90) && angle < rad_from_deg(270)) { - angle = std::fmod(angle + rad_from_deg(180), 2*M_PI); - if (angle < 0) angle += 2*M_PI; + angle = std::fmod(angle + rad_from_deg(180), 2 * M_PI); + if (angle < 0) + angle += 2 * M_PI; } affine *= Geom::Rotate(angle); affine *= Geom::Translate(pos); @@ -545,15 +568,15 @@ LPEMeasureSegments::createTextLabel(Geom::Point pos, size_t counter, double leng g_free(transform); } -void -LPEMeasureSegments::createLine(Geom::Point start,Geom::Point end, Glib::ustring name, size_t counter, bool main, bool remove, bool arrows) +void LPEMeasureSegments::createLine(Geom::Point start, Geom::Point end, Glib::ustring name, size_t counter, bool main, + bool remove, bool arrows) { SPDocument *document = getSPDoc(); if (!document || !sp_lpe_item || !sp_lpe_item->getId()) { return; } Glib::ustring lpobjid = this->lpeobj->getId(); - Glib::ustring itemid = sp_lpe_item->getId(); + Glib::ustring itemid = sp_lpe_item->getId(); Glib::ustring id = name; id += Glib::ustring::format(counter); id += "-"; @@ -564,18 +587,14 @@ LPEMeasureSegments::createLine(Geom::Point start,Geom::Point end, Glib::ustring if (!main) { Geom::Ray ray(start, end); Geom::Coord angle = ray.angle(); - start = start + Point::polar(angle, helpline_distance ); - end = end + Point::polar(angle, helpline_overlap ); + start = start + Point::polar(angle, helpline_distance); + end = end + Point::polar(angle, helpline_overlap); } Geom::PathVector line_pathv; - - double k = (Geom::distance(start,end)/2.0) - (anotation_width/1.7); - if (main && - std::abs(text_top_bottom) < fontsize/1.5 && - hide_back && - k > 0) - { - //k = std::max(k , arrow_gap -1); + + double k = (Geom::distance(start, end) / 2.0) - (anotation_width / 1.7); + if (main && std::abs(text_top_bottom) < fontsize / 1.5 && hide_back && k > 0) { + // k = std::max(k , arrow_gap -1); Geom::Ray ray(end, start); Geom::Coord angle = ray.angle(); Geom::Path line_path(start); @@ -592,8 +611,8 @@ LPEMeasureSegments::createLine(Geom::Point start,Geom::Point end, Glib::ustring } if (elemref) { line = elemref->getRepr(); - gchar * line_str = sp_svg_write_path( line_pathv ); - line->setAttribute("d" , line_str); + gchar *line_str = sp_svg_write_path(line_pathv); + line->setAttribute("d", line_str); line->removeAttribute("transform"); g_free(line_str); } else { @@ -612,17 +631,17 @@ LPEMeasureSegments::createLine(Geom::Point start,Geom::Point end, Glib::ustring classlinehelper += " measure-helper-line measure-line"; line->setAttribute("class", classlinehelper); } - gchar * line_str = sp_svg_write_path( line_pathv ); - line->setAttribute("d" , line_str); + gchar *line_str = sp_svg_write_path(line_pathv); + line->setAttribute("d", line_str); g_free(line_str); } line->setAttribute("sodipodi:insensitive", "true"); line_pathv.clear(); - + Glib::ustring style; if (remove) { - style ="display:none;"; + style = "display:none;"; } if (main) { line->setAttribute("inkscape:label", "dinline"); @@ -637,13 +656,13 @@ LPEMeasureSegments::createLine(Geom::Point start,Geom::Point end, Glib::ustring line->setAttribute("inkscape:label", "dinhelpline"); } std::stringstream stroke_w; - setlocale (LC_NUMERIC, "C"); - + setlocale(LC_NUMERIC, "C"); + double stroke_width = Inkscape::Util::Quantity::convert(line_width, unit.get_abbreviation(), display_unit.c_str()); - stroke_w << stroke_width; - setlocale (LC_NUMERIC, locale_base); - style += "stroke-width:"; - style += stroke_w.str(); + stroke_w << stroke_width; + setlocale(LC_NUMERIC, locale_base); + style += "stroke-width:"; + style += stroke_w.str(); gchar c[32]; sprintf(c, "#%06x", rgb32 >> 8); style += ";stroke:"; @@ -654,7 +673,7 @@ LPEMeasureSegments::createLine(Geom::Point start,Geom::Point end, Glib::ustring SPCSSAttr *css = sp_repr_css_attr_new(); sp_repr_css_attr_add_from_string(css, style.c_str()); Glib::ustring css_str; - sp_repr_css_write_string(css,css_str); + sp_repr_css_write_string(css, css_str); line->setAttributeOrRemoveIfEmpty("style", css_str); if (!elemref) { elemref = document->getRoot()->appendChildRepr(line); @@ -662,12 +681,11 @@ LPEMeasureSegments::createLine(Geom::Point start,Geom::Point end, Glib::ustring } } -void -LPEMeasureSegments::doOnApply(SPLPEItem const* lpeitem) +void LPEMeasureSegments::doOnApply(SPLPEItem const *lpeitem) { if (!SP_IS_SHAPE(lpeitem)) { g_warning("LPE measure line can only be applied to shapes (not groups)."); - SPLPEItem * item = const_cast(lpeitem); + SPLPEItem *item = const_cast(lpeitem); item->removeCurrentPathEffect(false); return; } @@ -675,7 +693,7 @@ LPEMeasureSegments::doOnApply(SPLPEItem const* lpeitem) bool saved = DocumentUndo::getUndoSensitive(document); DocumentUndo::setUndoSensitive(document, false); Inkscape::XML::Node *styleNode = nullptr; - Inkscape::XML::Node* textNode = nullptr; + Inkscape::XML::Node *textNode = nullptr; Inkscape::XML::Node *root = document->getReprRoot(); for (unsigned i = 0; i < root->childCount(); ++i) { if (Glib::ustring(root->nthChild(i)->name()) == "svg:style") { @@ -707,7 +725,7 @@ LPEMeasureSegments::doOnApply(SPLPEItem const* lpeitem) } // To fix old meassuring files pre 1.0 Glib::ustring styleContent = Glib::ustring(textNode->content()); - if (styleContent.find(".measure-arrow\n{\n") == std::string::npos) { + if (styleContent.find(".measure-arrow\n{\n") == std::string::npos) { styleContent = styleContent + Glib::ustring("\n.measure-arrow") + Glib::ustring("\n{\n}"); styleContent = styleContent + Glib::ustring("\n.measure-label") + Glib::ustring("\n{\n\n}"); styleContent = styleContent + Glib::ustring("\n.measure-line") + Glib::ustring("\n{\n}"); @@ -716,8 +734,7 @@ LPEMeasureSegments::doOnApply(SPLPEItem const* lpeitem) DocumentUndo::setUndoSensitive(document, saved); } -bool -LPEMeasureSegments::isWhitelist (size_t i, std::string listsegments, bool whitelist) +bool LPEMeasureSegments::isWhitelist(size_t i, std::string listsegments, bool whitelist) { size_t s = listsegments.find(std::to_string(i) + std::string(","), 0); if (s != std::string::npos) { @@ -738,44 +755,42 @@ LPEMeasureSegments::isWhitelist (size_t i, std::string listsegments, bool whitel double getAngle(Geom::Point p1, Geom::Point p2, Geom::Point p3, bool flip_side, double fix_overlaps) { - Geom::Ray ray_1(p2,p1); - Geom::Ray ray_2(p3,p1); + Geom::Ray ray_1(p2, p1); + Geom::Ray ray_2(p3, p1); bool ccw_toggle = cross(p1 - p2, p3 - p2) < 0; double angle = angle_between(ray_1, ray_2, ccw_toggle); - if (Geom::deg_from_rad(angle) < fix_overlaps || - Geom::deg_from_rad(angle) > 180 || - ((ccw_toggle && flip_side) || (!ccw_toggle && !flip_side))) - { + if (Geom::deg_from_rad(angle) < fix_overlaps || Geom::deg_from_rad(angle) > 180 || + ((ccw_toggle && flip_side) || (!ccw_toggle && !flip_side))) { angle = 0; } return angle; } -std::vector< Point > -transformNodes(std::vector< Point > nodes, Geom::Affine transform) +std::vector transformNodes(std::vector nodes, Geom::Affine transform) { - std::vector< Point > result; - for (auto & node : nodes) { + std::vector result; + for (auto &node : nodes) { Geom::Point point = node; result.push_back(point * transform); } return result; } -std::vector< Point > -getNodes(SPItem * item, Geom::Affine transform, bool onbbox, bool centers, bool bboxonly, double angle_projection) +std::vector getNodes(SPItem *item, Geom::Affine transform, bool onbbox, bool centers, bool bboxonly, + double angle_projection) { - std::vector< Point > current_nodes; - SPShape * shape = dynamic_cast (item); - SPText * text = dynamic_cast (item); - SPGroup * group = dynamic_cast (item); - SPFlowtext * flowtext = dynamic_cast (item); - //TODO handle clones/use + std::vector current_nodes; + SPShape *shape = dynamic_cast(item); + SPText *text = dynamic_cast(item); + SPGroup *group = dynamic_cast(item); + SPFlowtext *flowtext = dynamic_cast(item); + // TODO handle clones/use if (group) { - std::vector const item_list = sp_item_group_item_list(group); + std::vector const item_list = sp_item_group_item_list(group); for (auto sub_item : item_list) { - std::vector< Point > nodes = transformNodes(getNodes(sub_item, sub_item->transform, onbbox, centers, bboxonly, angle_projection), transform); + std::vector nodes = transformNodes( + getNodes(sub_item, sub_item->transform, onbbox, centers, bboxonly, angle_projection), transform); current_nodes.insert(current_nodes.end(), nodes.begin(), nodes.end()); } } else if (shape && !bboxonly) { @@ -798,8 +813,8 @@ getNodes(SPItem * item, Geom::Affine transform, bool onbbox, bool centers, bool if (curve->is_empty()) { // whitespace glyph? continue; } - std::vector< Point > letter_nodes = transformNodes(curve->get_pathvector().nodes(), transform); - current_nodes.insert(current_nodes.end(),letter_nodes.begin(),letter_nodes.end()); + std::vector letter_nodes = transformNodes(curve->get_pathvector().nodes(), transform); + current_nodes.insert(current_nodes.end(), letter_nodes.begin(), letter_nodes.end()); if (iter == te_get_layout(item)->end()) { break; } @@ -812,15 +827,11 @@ getNodes(SPItem * item, Geom::Affine transform, bool onbbox, bool centers, bool if (bbox && onbbox) { current_nodes.push_back((*bbox).corner(0) * transform); current_nodes.push_back((*bbox).corner(2) * transform); - if (!Geom::are_near(angle_projection, 0.0) && - !Geom::are_near(angle_projection, 90.0) && - !Geom::are_near(angle_projection, 180.0) && - !Geom::are_near(angle_projection, 360.0)) - { + if (!Geom::are_near(angle_projection, 0.0) && !Geom::are_near(angle_projection, 90.0) && + !Geom::are_near(angle_projection, 180.0) && !Geom::are_near(angle_projection, 360.0)) { current_nodes.push_back((*bbox).corner(1) * transform); current_nodes.push_back((*bbox).corner(3) * transform); } - } if (bbox && centers) { current_nodes.push_back((*bbox).midpoint() * transform); @@ -829,7 +840,8 @@ getNodes(SPItem * item, Geom::Affine transform, bool onbbox, bool centers, bool return current_nodes; } -static void extractFirstPoint(Geom::Point & dest, const Glib::ustring & lpobjid, const char *const prefix, const gint idx, SPDocument *const document) +static void extractFirstPoint(Geom::Point &dest, const Glib::ustring &lpobjid, const char *const prefix, const gint idx, + SPDocument *const document) { Glib::ustring id = Glib::ustring(prefix); id += Glib::ustring::format(idx); @@ -844,67 +856,70 @@ static void extractFirstPoint(Geom::Point & dest, const Glib::ustring & lpobjid, } } -void -LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) +void LPEMeasureSegments::doBeforeEffect(SPLPEItem const *lpeitem) { - SPLPEItem * splpeitem = const_cast(lpeitem); + SPLPEItem *splpeitem = const_cast(lpeitem); Glib::ustring lpobjid = this->lpeobj->getId(); SPDocument *document = getSPDoc(); if (!document) { return; } - //Avoid crashes on previews + // Avoid crashes on previews Geom::Affine parentaffinetransform = i2anc_affine(SP_OBJECT(lpeitem->parent), SP_OBJECT(document->getRoot())); Geom::Affine affinetransform = i2anc_affine(SP_OBJECT(lpeitem), SP_OBJECT(document->getRoot())); Geom::Affine itemtransform = affinetransform * parentaffinetransform.inverse(); - //Projection prepare + // Projection prepare Geom::PathVector pathvector; - std::vector< Point > nodes; + std::vector nodes; if (active_projection) { Geom::OptRect bbox = sp_lpe_item->geometricBounds(); if (bbox) { - Geom::Point mid = bbox->midpoint(); + Geom::Point mid = bbox->midpoint(); double angle = Geom::rad_from_deg(angle_projection); Geom::Affine transform = itemtransform; transform *= Geom::Translate(mid).inverse(); transform *= Geom::Rotate(angle).inverse(); transform *= Geom::Translate(mid); - std::vector< Point > current_nodes = getNodes(splpeitem, transform, onbbox, centers, bboxonly, angle_projection); - nodes.insert(nodes.end(),current_nodes.begin(), current_nodes.end()); - for (auto & iter : linked_items._vector) { + std::vector current_nodes = + getNodes(splpeitem, transform, onbbox, centers, bboxonly, angle_projection); + nodes.insert(nodes.end(), current_nodes.begin(), current_nodes.end()); + for (auto &iter : linked_items._vector) { SPObject *obj; - if (iter->ref.isAttached() && iter->actived && (obj = iter->ref.getObject()) && SP_IS_ITEM(obj)) { - SPItem * item = dynamic_cast(obj); + if (iter->ref.isAttached() && iter->actived && (obj = iter->ref.getObject()) && SP_IS_ITEM(obj)) { + SPItem *item = dynamic_cast(obj); if (item) { - Geom::Affine affinetransform_sub = i2anc_affine(SP_OBJECT(item), SP_OBJECT(document->getRoot())); - Geom::Affine transform = affinetransform_sub ; + Geom::Affine affinetransform_sub = + i2anc_affine(SP_OBJECT(item), SP_OBJECT(document->getRoot())); + Geom::Affine transform = affinetransform_sub; transform *= Geom::Translate(-mid); transform *= Geom::Rotate(angle).inverse(); transform *= Geom::Translate(mid); - std::vector< Point > current_nodes = getNodes(item, transform, onbbox, centers, bboxonly, angle_projection); - nodes.insert(nodes.end(),current_nodes.begin(), current_nodes.end()); + std::vector current_nodes = + getNodes(item, transform, onbbox, centers, bboxonly, angle_projection); + nodes.insert(nodes.end(), current_nodes.begin(), current_nodes.end()); } } } double maxdistance = -std::numeric_limits::max(); std::vector result; - for (auto & node : nodes) { + for (auto &node : nodes) { Geom::Point point = node; if (point[Geom::X] > maxdistance) { maxdistance = point[Geom::X]; } result.push_back(point[Geom::Y]); } - double dproj = Inkscape::Util::Quantity::convert(distance_projection, display_unit.c_str(), unit.get_abbreviation()); + double dproj = + Inkscape::Util::Quantity::convert(distance_projection, display_unit.c_str(), unit.get_abbreviation()); Geom::Coord xpos = maxdistance + dproj; - std::sort (result.begin(), result.end()); + std::sort(result.begin(), result.end()); Geom::Path path; - Geom::Point prevpoint(Geom::infinity(),Geom::infinity()); + Geom::Point prevpoint(Geom::infinity(), Geom::infinity()); bool started = false; Geom::Point point = Geom::Point(); - for (auto & iter : result) { + for (auto &iter : result) { point = Geom::Point(xpos, iter); - if (Geom::are_near(prevpoint, point)){ + if (Geom::are_near(prevpoint, point)) { continue; } if (!started) { @@ -918,7 +933,7 @@ LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) prevpoint = point; } if (maxmin) { - path.appendNew(point); + path.appendNew(point); } pathvector.push_back(path); pathvector *= Geom::Translate(-mid); @@ -927,10 +942,10 @@ LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) } } - //end projection prepare + // end projection prepare SPShape *shape = dynamic_cast(splpeitem); if (shape) { - //only check constrain viewbox on X + // only check constrain viewbox on X display_unit = document->getDisplayUnit()->abbr.c_str(); guint32 color32 = coloropacity.get_value(); bool colorchanged = false; @@ -946,13 +961,13 @@ LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) fontsize = Inkscape::Util::Quantity::convert(newfontsize, "pt", display_unit.c_str()); fontsizechanged = true; } - Geom::Point prev_stored = Geom::Point(0,0); - Geom::Point start_stored = Geom::Point(0,0); - Geom::Point end_stored = Geom::Point(0,0); - Geom::Point next_stored = Geom::Point(0,0); + Geom::Point prev_stored = Geom::Point(0, 0); + Geom::Point start_stored = Geom::Point(0, 0); + Geom::Point end_stored = Geom::Point(0, 0); + Geom::Point next_stored = Geom::Point(0, 0); if (!active_projection) { SPCurve const *c = shape->curve(); - pathvector = pathv_to_linear_and_cubic_beziers(c->get_pathvector()); + pathvector = pathv_to_linear_and_cubic_beziers(c->get_pathvector()); pathvector *= affinetransform; } auto format_str = format.param_getSVGValue(); @@ -967,16 +982,16 @@ LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) bool previous_fix_overlaps = true; for (size_t i = 0; i < pathvector.size(); i++) { size_t count = pathvector[i].size_default(); - if ( pathvector[i].closed()) { - const Geom::Curve &closingline = pathvector[i].back_closed(); - if (are_near(closingline.initialPoint(), closingline.finalPoint())) { - count = pathvector[i].size_open(); - } + if (pathvector[i].closed()) { + const Geom::Curve &closingline = pathvector[i].back_closed(); + if (are_near(closingline.initialPoint(), closingline.finalPoint())) { + count = pathvector[i].size_open(); + } } for (size_t j = 0; j < count; j++) { counter++; gint fix_overlaps_degree = fix_overlaps; - Geom::Point prev = Geom::Point(0,0); + Geom::Point prev = Geom::Point(0, 0); if (j == 0 && pathvector[i].closed()) { prev = pathvector.pointAt(pathvector[i].size() - 1); } else if (j != 0) { @@ -984,36 +999,36 @@ LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) } Geom::Point start = pathvector[i].pointAt(j); Geom::Point end = pathvector[i].pointAt(j + 1); - Geom::Point next = Geom::Point(0,0); - if (pathvector[i].closed() && pathvector[i].size() == j+1){ + Geom::Point next = Geom::Point(0, 0); + if (pathvector[i].closed() && pathvector[i].size() == j + 1) { end = pathvector[i].pointAt(0); next = pathvector[i].pointAt(1); } else if (pathvector[i].size() > j + 1) { - next = pathvector[i].pointAt(j+2); + next = pathvector[i].pointAt(j + 2); } auto blacklist_str = blacklist.param_getSVGValue(); std::string listsegments(blacklist_str.raw() + ","); listsegments.erase(std::remove(listsegments.begin(), listsegments.end(), ' '), listsegments.end()); if (isWhitelist(counter, listsegments, (bool)whitelist) && !Geom::are_near(start, end)) { - extractFirstPoint(prev_stored, lpobjid, "infoline-on-start-", counter-1, document); + extractFirstPoint(prev_stored, lpobjid, "infoline-on-start-", counter - 1, document); extractFirstPoint(start_stored, lpobjid, "infoline-on-start-", counter, document); extractFirstPoint(end_stored, lpobjid, "infoline-on-end-", counter, document); - extractFirstPoint(next_stored, lpobjid, "infoline-on-start-", counter+1, document); + extractFirstPoint(next_stored, lpobjid, "infoline-on-start-", counter + 1, document); Glib::ustring infoline_on_start = "infoline-on-start-"; infoline_on_start += Glib::ustring::format(counter); infoline_on_start += "-"; infoline_on_start += lpobjid; - + Glib::ustring infoline_on_end = "infoline-on-end-"; infoline_on_end += Glib::ustring::format(counter); infoline_on_end += "-"; infoline_on_end += lpobjid; - + Glib::ustring infoline = "infoline-"; infoline += Glib::ustring::format(counter); infoline += "-"; infoline += lpobjid; - + Glib::ustring texton = "text-on-"; texton += Glib::ustring::format(counter); texton += "-"; @@ -1034,100 +1049,99 @@ LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) if (((Geom::are_near(prev, prev_stored, 0.01) && Geom::are_near(next, next_stored, 0.01)) || fix_overlaps_degree == 180) && Geom::are_near(start, start_stored, 0.01) && Geom::are_near(end, end_stored, 0.01) && - !this->refresh_widgets && !colorchanged && !fontsizechanged && !is_load && anotation_width) - { + !this->refresh_widgets && !colorchanged && !fontsizechanged && !is_load && anotation_width) { continue; } Geom::Point hstart = start; Geom::Point hend = end; bool remove = false; if (orientation == OM_VERTICAL) { - Coord xpos = std::max(hstart[Geom::X],hend[Geom::X]); + Coord xpos = std::max(hstart[Geom::X], hend[Geom::X]); if (flip_side) { - xpos = std::min(hstart[Geom::X],hend[Geom::X]); + xpos = std::min(hstart[Geom::X], hend[Geom::X]); } hstart[Geom::X] = xpos; hend[Geom::X] = xpos; if (hstart[Geom::Y] > hend[Geom::Y]) { - swap(hstart,hend); - swap(start,end); + swap(hstart, hend); + swap(start, end); } if (Geom::are_near(hstart[Geom::Y], hend[Geom::Y])) { remove = true; } } else if (orientation == OM_HORIZONTAL) { - Coord ypos = std::max(hstart[Geom::Y],hend[Geom::Y]); + Coord ypos = std::max(hstart[Geom::Y], hend[Geom::Y]); if (flip_side) { - ypos = std::min(hstart[Geom::Y],hend[Geom::Y]); + ypos = std::min(hstart[Geom::Y], hend[Geom::Y]); } hstart[Geom::Y] = ypos; hend[Geom::Y] = ypos; if (hstart[Geom::X] < hend[Geom::X]) { - swap(hstart,hend); - swap(start,end); + swap(hstart, hend); + swap(start, end); } if (Geom::are_near(hstart[Geom::X], hend[Geom::X])) { remove = true; } } else if (fix_overlaps_degree != 180) { - start_angle_cross = getAngle( start, prev, end, flip_side, fix_overlaps_degree); - if (prev == Geom::Point(0,0)) { + start_angle_cross = getAngle(start, prev, end, flip_side, fix_overlaps_degree); + if (prev == Geom::Point(0, 0)) { start_angle_cross = 0; } end_angle_cross = getAngle(end, start, next, flip_side, fix_overlaps_degree); - if (next == Geom::Point(0,0)) { + if (next == Geom::Point(0, 0)) { end_angle_cross = 0; } } if (remove) { createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-"), counter, true, true, true); - createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-on-start-"), counter, true, true, true); - createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-on-end-"), counter, true, true, true); + createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-on-start-"), counter, true, + true, true); + createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-on-end-"), counter, true, true, + true); createTextLabel(Geom::Point(), counter, 0, 0, true, true); continue; } - Geom::Ray ray(hstart,hend); + Geom::Ray ray(hstart, hend); Geom::Coord angle = ray.angle(); if (flip_side) { - angle = std::fmod(angle + rad_from_deg(180), 2*M_PI); - if (angle < 0) angle += 2*M_PI; + angle = std::fmod(angle + rad_from_deg(180), 2 * M_PI); + if (angle < 0) + angle += 2 * M_PI; } - Geom::Coord angle_cross = std::fmod(angle + rad_from_deg(90), 2*M_PI); - if (angle_cross < 0) angle_cross += 2*M_PI; - angle = std::fmod(angle, 2*M_PI); - if (angle < 0) angle += 2*M_PI; + Geom::Coord angle_cross = std::fmod(angle + rad_from_deg(90), 2 * M_PI); + if (angle_cross < 0) + angle_cross += 2 * M_PI; + angle = std::fmod(angle, 2 * M_PI); + if (angle < 0) + angle += 2 * M_PI; double turn = Geom::rad_from_deg(-90); if (flip_side) { end_angle_cross *= -1; start_angle_cross *= -1; - //turn *= -1; + // turn *= -1; } - double position_turned_start = position / sin(start_angle_cross/2.0); - double length = Geom::distance(start,end); - if (fix_overlaps_degree != 180 && - start_angle_cross != 0 && - position_turned_start < length && - previous_fix_overlaps) - { - hstart = hstart - Point::polar(angle_cross - (start_angle_cross/2.0) - turn, position_turned_start); + double position_turned_start = position / sin(start_angle_cross / 2.0); + double length = Geom::distance(start, end); + if (fix_overlaps_degree != 180 && start_angle_cross != 0 && position_turned_start < length && + previous_fix_overlaps) { + hstart = hstart - + Point::polar(angle_cross - (start_angle_cross / 2.0) - turn, position_turned_start); } else { hstart = hstart - Point::polar(angle_cross, position); } createLine(start, hstart, Glib::ustring("infoline-on-start-"), counter, false, false); - double position_turned_end = position / sin(end_angle_cross/2.0); - double endlength = Geom::distance(end,next); - if (fix_overlaps_degree != 180 && - end_angle_cross != 0 && - position_turned_end < length && - position_turned_end < endlength) - { - hend = hend - Point::polar(angle_cross + (end_angle_cross/2.0) + turn, position_turned_end); + double position_turned_end = position / sin(end_angle_cross / 2.0); + double endlength = Geom::distance(end, next); + if (fix_overlaps_degree != 180 && end_angle_cross != 0 && position_turned_end < length && + position_turned_end < endlength) { + hend = hend - Point::polar(angle_cross + (end_angle_cross / 2.0) + turn, position_turned_end); previous_fix_overlaps = true; } else { hend = hend - Point::polar(angle_cross, position); previous_fix_overlaps = false; } - length = Geom::distance(start,end) * scale; + length = Geom::distance(start, end) * scale; Geom::Point pos = Geom::middle_point(hstart, hend); if (!hide_arrows) { if (arrows_outside) { @@ -1139,17 +1153,18 @@ LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) } } if (angle >= rad_from_deg(90) && angle < rad_from_deg(270)) { - pos = pos - Point::polar(angle_cross, text_top_bottom + (fontsize/2.5)); + pos = pos - Point::polar(angle_cross, text_top_bottom + (fontsize / 2.5)); } else { - pos = pos + Point::polar(angle_cross, text_top_bottom + (fontsize/2.5)); + pos = pos + Point::polar(angle_cross, text_top_bottom + (fontsize / 2.5)); } - double parents_scale = (parentaffinetransform.expansionX() + parentaffinetransform.expansionY()) / 2.0; + double parents_scale = + (parentaffinetransform.expansionX() + parentaffinetransform.expansionY()) / 2.0; if (!scale_sensitive) { length /= parents_scale; } - if ((anotation_width/2) > Geom::distance(hstart,hend)/2.0) { + if ((anotation_width / 2) > Geom::distance(hstart, hend) / 2.0) { if (avoid_overlapping) { - pos = pos - Point::polar(angle_cross, position + (anotation_width/2.0)); + pos = pos - Point::polar(angle_cross, position + (anotation_width / 2.0)); angle += Geom::rad_from_deg(90); } else { pos = pos - Point::polar(angle_cross, position); @@ -1160,25 +1175,27 @@ LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) } else { createTextLabel(pos, counter, length, angle, remove, true); } - arrow_gap = 8 * Inkscape::Util::Quantity::convert(line_width, unit.get_abbreviation(), display_unit.c_str()); + arrow_gap = 8 * Inkscape::Util::Quantity::convert(line_width, unit.get_abbreviation(), + display_unit.c_str()); SPCSSAttr *css = sp_repr_css_attr_new(); - setlocale (LC_NUMERIC, "C"); - double width_line = atof(sp_repr_css_property(css,"stroke-width","-1")); - setlocale (LC_NUMERIC, locale_base); + setlocale(LC_NUMERIC, "C"); + double width_line = atof(sp_repr_css_property(css, "stroke-width", "-1")); + setlocale(LC_NUMERIC, locale_base); if (width_line > -0.0001) { - arrow_gap = 8 * Inkscape::Util::Quantity::convert(width_line, unit.get_abbreviation(), display_unit.c_str()); + arrow_gap = 8 * Inkscape::Util::Quantity::convert(width_line, unit.get_abbreviation(), + display_unit.c_str()); } - if(flip_side) { - arrow_gap *= -1; + if (flip_side) { + arrow_gap *= -1; } - if(hide_arrows) { + if (hide_arrows) { arrow_gap *= 0; } createLine(end, hend, Glib::ustring("infoline-on-end-"), counter, false, false); if (!arrows_outside) { hstart = hstart + Point::polar(angle, arrow_gap); - hend = hend - Point::polar(angle, arrow_gap ); + hend = hend - Point::polar(angle, arrow_gap); } if ((Geom::distance(hstart, hend) / 2.0) > (anotation_width / 1.9) + arrow_gap) { createLine(hstart, hend, Glib::ustring("infoline-"), counter, true, false, true); @@ -1187,8 +1204,10 @@ LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) } } else { createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-"), counter, true, true, true); - createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-on-start-"), counter, true, true, true); - createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-on-end-"), counter, true, true, true); + createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-on-start-"), counter, true, true, + true); + createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-on-end-"), counter, true, true, + true); createTextLabel(Geom::Point(), counter, 0, 0, true, true); } } @@ -1196,7 +1215,8 @@ LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) if (previous_size) { for (size_t counter = ncurves; counter < previous_size; counter++) { createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-"), counter, true, true, true); - createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-on-start-"), counter, true, true, true); + createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-on-start-"), counter, true, true, + true); createLine(Geom::Point(), Geom::Point(), Glib::ustring("infoline-on-end-"), counter, true, true, true); createTextLabel(Geom::Point(), counter, 0, 0, true, true); } @@ -1205,16 +1225,14 @@ LPEMeasureSegments::doBeforeEffect (SPLPEItem const* lpeitem) } } -void -LPEMeasureSegments::doOnVisibilityToggled(SPLPEItem const* /*lpeitem*/) +void LPEMeasureSegments::doOnVisibilityToggled(SPLPEItem const * /*lpeitem*/) { processObjects(LPE_VISIBILITY); } -void -LPEMeasureSegments::doOnRemove (SPLPEItem const* /*lpeitem*/) +void LPEMeasureSegments::doOnRemove(SPLPEItem const * /*lpeitem*/) { - //set "keep paths" hook on sp-lpe-item.cpp + // set "keep paths" hook on sp-lpe-item.cpp if (keep_paths) { processObjects(LPE_TO_OBJECTS); items.clear(); @@ -1223,7 +1241,7 @@ LPEMeasureSegments::doOnRemove (SPLPEItem const* /*lpeitem*/) processObjects(LPE_ERASE); } -}; //namespace LivePathEffect +}; // namespace LivePathEffect }; /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-measure-segments.h b/src/live_effects/lpe-measure-segments.h index ea7c8e7a8771a20580e699f3b66efaf912cfb7cb..d9dde2d418992c0832f807697795d55522559df4 100644 --- a/src/live_effects/lpe-measure-segments.h +++ b/src/live_effects/lpe-measure-segments.h @@ -11,42 +11,46 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include + #include "live_effects/effect.h" -#include "live_effects/parameter/enum.h" -#include "live_effects/parameter/originalitemarray.h" #include "live_effects/parameter/bool.h" #include "live_effects/parameter/colorpicker.h" +#include "live_effects/parameter/enum.h" #include "live_effects/parameter/fontbutton.h" #include "live_effects/parameter/message.h" +#include "live_effects/parameter/originalitemarray.h" #include "live_effects/parameter/text.h" #include "live_effects/parameter/unit.h" - namespace Inkscape { namespace LivePathEffect { -enum OrientationMethod { +enum OrientationMethod +{ OM_HORIZONTAL, OM_VERTICAL, OM_PARALLEL, OM_END }; -class LPEMeasureSegments : public Effect { +class LPEMeasureSegments : public Effect +{ public: LPEMeasureSegments(LivePathEffectObject *lpeobject); ~LPEMeasureSegments() override; - void doOnApply(SPLPEItem const* lpeitem) override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; - void doOnRemove(SPLPEItem const* /*lpeitem*/) override; - void doEffect (SPCurve * curve) override {}; - void doOnVisibilityToggled(SPLPEItem const* /*lpeitem*/) override; - Gtk::Widget * newWidget() override; - void createLine(Geom::Point start,Geom::Point end, Glib::ustring name, size_t counter, bool main, bool remove, bool arrows = false); + void doOnApply(SPLPEItem const *lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; + void doOnRemove(SPLPEItem const * /*lpeitem*/) override; + void doEffect(SPCurve *curve) override{}; + void doOnVisibilityToggled(SPLPEItem const * /*lpeitem*/) override; + Gtk::Widget *newWidget() override; + void createLine(Geom::Point start, Geom::Point end, Glib::ustring name, size_t counter, bool main, bool remove, + bool arrows = false); void createTextLabel(Geom::Point pos, size_t counter, double length, Geom::Coord angle, bool remove, bool valid); void createArrowMarker(Glib::ustring mode); - bool isWhitelist(size_t i, std::string listsegments, bool whitelist); - void on_my_switch_page(Gtk::Widget* page, guint page_number); + bool isWhitelist(size_t i, std::string listsegments, bool whitelist); + void on_my_switch_page(Gtk::Widget *page, guint page_number); + private: UnitParam unit; EnumParam orientation; @@ -89,14 +93,13 @@ private: guint32 rgb32; double arrow_gap; guint pagenumber; - gchar const* locale_base; + gchar const *locale_base; LPEMeasureSegments(const LPEMeasureSegments &) = delete; LPEMeasureSegments &operator=(const LPEMeasureSegments &) = delete; - }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-mirror_symmetry.cpp b/src/live_effects/lpe-mirror_symmetry.cpp index 080fa1dafff18e02ad1c3c84696f177a03f44d5b..dd185a5cab3946d84158d2ef766c5981530d66d4 100644 --- a/src/live_effects/lpe-mirror_symmetry.cpp +++ b/src/live_effects/lpe-mirror_symmetry.cpp @@ -16,21 +16,21 @@ */ #include "live_effects/lpe-mirror_symmetry.h" + +#include + #include "2geom/affine.h" #include "2geom/path-intersection.h" #include "display/curve.h" #include "helper/geom.h" -#include "path-chemistry.h" -#include "style.h" -#include "svg/path-string.h" -#include "svg/svg.h" -#include - #include "object/sp-defs.h" #include "object/sp-lpe-item.h" #include "object/sp-path.h" #include "object/sp-text.h" - +#include "path-chemistry.h" +#include "style.h" +#include "svg/path-string.h" +#include "svg/svg.h" #include "xml/sp-css-attr.h" // TODO due to internal breakage in glibmm headers, this must be last: @@ -39,27 +39,34 @@ namespace Inkscape { namespace LivePathEffect { -static const Util::EnumData ModeTypeData[] = { - { MT_V, N_("Vertical page center"), "vertical" }, - { MT_H, N_("Horizontal page center"), "horizontal" }, - { MT_FREE, N_("Freely defined mirror line"), "free" }, - { MT_X, N_("X coordinate of mirror line midpoint"), "X" }, - { MT_Y, N_("Y coordinate of mirror line midpoint"), "Y" } -}; -static const Util::EnumDataConverter -MTConverter(ModeTypeData, MT_END); - - -LPEMirrorSymmetry::LPEMirrorSymmetry(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - mode(_("Mode"), _("Set mode of transformation. Either freely defined by mirror line or constrained to certain symmetry points."), "mode", MTConverter, &wr, this, MT_FREE), - discard_orig_path(_("Discard original path"), _("Only keep mirrored part of the path, remove the original."), "discard_orig_path", &wr, this, false), - fuse_paths(_("Fuse paths"), _("Fuse original path and mirror image into a single path"), "fuse_paths", &wr, this, false), - oposite_fuse(_("Fuse opposite sides"), _("Picks the part on the other side of the mirror line as the original."), "oposite_fuse", &wr, this, false), - split_items(_("Split elements"), _("Split original and mirror image into separate paths, so each can have its own style."), "split_items", &wr, this, false), - start_point(_("Mirror line start"), _("Start point of mirror line"), "start_point", &wr, this, _("Adjust start point of mirror line")), - end_point(_("Mirror line end"), _("End point of mirror line"), "end_point", &wr, this, _("Adjust end point of mirror line")), - center_point(_("Mirror line mid"), _("Center point of mirror line"), "center_point", &wr, this, _("Adjust center point of mirror line")) +static const Util::EnumData ModeTypeData[] = {{MT_V, N_("Vertical page center"), "vertical"}, + {MT_H, N_("Horizontal page center"), "horizontal"}, + {MT_FREE, N_("Freely defined mirror line"), "free"}, + {MT_X, N_("X coordinate of mirror line midpoint"), "X"}, + {MT_Y, N_("Y coordinate of mirror line midpoint"), "Y"}}; +static const Util::EnumDataConverter MTConverter(ModeTypeData, MT_END); + +LPEMirrorSymmetry::LPEMirrorSymmetry(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , mode(_("Mode"), + _("Set mode of transformation. Either freely defined by mirror line or constrained to certain symmetry " + "points."), + "mode", MTConverter, &wr, this, MT_FREE) + , discard_orig_path(_("Discard original path"), _("Only keep mirrored part of the path, remove the original."), + "discard_orig_path", &wr, this, false) + , fuse_paths(_("Fuse paths"), _("Fuse original path and mirror image into a single path"), "fuse_paths", &wr, this, + false) + , oposite_fuse(_("Fuse opposite sides"), _("Picks the part on the other side of the mirror line as the original."), + "oposite_fuse", &wr, this, false) + , split_items(_("Split elements"), + _("Split original and mirror image into separate paths, so each can have its own style."), + "split_items", &wr, this, false) + , start_point(_("Mirror line start"), _("Start point of mirror line"), "start_point", &wr, this, + _("Adjust start point of mirror line")) + , end_point(_("Mirror line end"), _("End point of mirror line"), "end_point", &wr, this, + _("Adjust end point of mirror line")) + , center_point(_("Mirror line mid"), _("Center point of mirror line"), "center_point", &wr, this, + _("Adjust center point of mirror line")) { show_orig_path = true; registerParameter(&mode); @@ -71,18 +78,16 @@ LPEMirrorSymmetry::LPEMirrorSymmetry(LivePathEffectObject *lpeobject) : registerParameter(&end_point); registerParameter(¢er_point); apply_to_clippath_and_mask = true; - previous_center = Geom::Point(0,0); + previous_center = Geom::Point(0, 0); center_point.param_widget_is_visible(false); reset = false; center_horiz = false; center_vert = false; } -LPEMirrorSymmetry::~LPEMirrorSymmetry() -= default; +LPEMirrorSymmetry::~LPEMirrorSymmetry() = default; -void -LPEMirrorSymmetry::doAfterEffect (SPLPEItem const* lpeitem) +void LPEMirrorSymmetry::doAfterEffect(SPLPEItem const *lpeitem) { SPDocument *document = getSPDoc(); if (!document) { @@ -92,7 +97,7 @@ LPEMirrorSymmetry::doAfterEffect (SPLPEItem const* lpeitem) if (split_items && !discard_orig_path) { Geom::Line ls((Geom::Point)start_point, (Geom::Point)end_point); - Geom::Affine m = Geom::reflection (ls.vector(), (Geom::Point)start_point); + Geom::Affine m = Geom::reflection(ls.vector(), (Geom::Point)start_point); m *= sp_lpe_item->transform; toMirror(m, reset); reset = false; @@ -102,8 +107,7 @@ LPEMirrorSymmetry::doAfterEffect (SPLPEItem const* lpeitem) } } -Gtk::Widget * -LPEMirrorSymmetry::newWidget() +Gtk::Widget *LPEMirrorSymmetry::newWidget() { // use manage here, because after deletion of Effect object, others might // still be pointing to this widget. @@ -131,44 +135,43 @@ LPEMirrorSymmetry::newWidget() ++it; } - Gtk::HBox * hbox = Gtk::manage(new Gtk::HBox(false,0)); - Gtk::HBox * hbox2 = Gtk::manage(new Gtk::HBox(false,0)); - Gtk::Button * center_vert_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("Vertical center")))); - center_vert_button->signal_clicked().connect(sigc::mem_fun (*this,&LPEMirrorSymmetry::centerVert)); - center_vert_button->set_size_request(110,20); - Gtk::Button * center_horiz_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("Horizontal center")))); - center_horiz_button->signal_clicked().connect(sigc::mem_fun (*this,&LPEMirrorSymmetry::centerHoriz)); - center_horiz_button->set_size_request(110,20); - Gtk::Button * reset_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("Reset styles")))); - reset_button->signal_clicked().connect(sigc::mem_fun (*this,&LPEMirrorSymmetry::resetStyles)); - reset_button->set_size_request(110,20); - vbox->pack_start(*hbox, true,true,2); - vbox->pack_start(*hbox2, true,true,2); - hbox->pack_start(*reset_button, false, false,2); - hbox2->pack_start(*center_vert_button, false, false,2); - hbox2->pack_start(*center_horiz_button, false, false,2); - if(Gtk::Widget* widg = defaultParamSet()) { + Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox(false, 0)); + Gtk::HBox *hbox2 = Gtk::manage(new Gtk::HBox(false, 0)); + Gtk::Button *center_vert_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("Vertical center")))); + center_vert_button->signal_clicked().connect(sigc::mem_fun(*this, &LPEMirrorSymmetry::centerVert)); + center_vert_button->set_size_request(110, 20); + Gtk::Button *center_horiz_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("Horizontal center")))); + center_horiz_button->signal_clicked().connect(sigc::mem_fun(*this, &LPEMirrorSymmetry::centerHoriz)); + center_horiz_button->set_size_request(110, 20); + Gtk::Button *reset_button = Gtk::manage(new Gtk::Button(Glib::ustring(_("Reset styles")))); + reset_button->signal_clicked().connect(sigc::mem_fun(*this, &LPEMirrorSymmetry::resetStyles)); + reset_button->set_size_request(110, 20); + vbox->pack_start(*hbox, true, true, 2); + vbox->pack_start(*hbox2, true, true, 2); + hbox->pack_start(*reset_button, false, false, 2); + hbox2->pack_start(*center_vert_button, false, false, 2); + hbox2->pack_start(*center_horiz_button, false, false, 2); + if (Gtk::Widget *widg = defaultParamSet()) { vbox->pack_start(*widg, true, true, 2); } return dynamic_cast(vbox); } -void -LPEMirrorSymmetry::centerVert(){ +void LPEMirrorSymmetry::centerVert() +{ center_vert = true; refresh_widgets = true; writeParamsToSVG(); } -void -LPEMirrorSymmetry::centerHoriz(){ +void LPEMirrorSymmetry::centerHoriz() +{ center_horiz = true; refresh_widgets = true; writeParamsToSVG(); } -void -LPEMirrorSymmetry::doBeforeEffect (SPLPEItem const* lpeitem) +void LPEMirrorSymmetry::doBeforeEffect(SPLPEItem const *lpeitem) { using namespace Geom; original_bbox(lpeitem, false, true); @@ -178,24 +181,23 @@ LPEMirrorSymmetry::doBeforeEffect (SPLPEItem const* lpeitem) if (center_vert) { center_point.param_setValue(point_c); end_point.param_setValue(Geom::Point(boundingbox_X.middle(), boundingbox_Y.min())); - //force update - start_point.param_setValue(Geom::Point(boundingbox_X.middle(), boundingbox_Y.max()),true); + // force update + start_point.param_setValue(Geom::Point(boundingbox_X.middle(), boundingbox_Y.max()), true); center_vert = false; } else if (center_horiz) { center_point.param_setValue(point_c); end_point.param_setValue(Geom::Point(boundingbox_X.max(), boundingbox_Y.middle())); - start_point.param_setValue(Geom::Point(boundingbox_X.min(), boundingbox_Y.middle()),true); - //force update + start_point.param_setValue(Geom::Point(boundingbox_X.min(), boundingbox_Y.middle()), true); + // force update center_horiz = false; } else { - if (mode == MT_Y) { - point_a = Geom::Point(boundingbox_X.min(),center_point[Y]); - point_b = Geom::Point(boundingbox_X.max(),center_point[Y]); + point_a = Geom::Point(boundingbox_X.min(), center_point[Y]); + point_b = Geom::Point(boundingbox_X.max(), center_point[Y]); } if (mode == MT_X) { - point_a = Geom::Point(center_point[X],boundingbox_Y.min()); - point_b = Geom::Point(center_point[X],boundingbox_Y.max()); + point_a = Geom::Point(center_point[X], boundingbox_Y.min()); + point_b = Geom::Point(center_point[X], boundingbox_Y.max()); } if ((Geom::Point)start_point == (Geom::Point)end_point) { start_point.param_setValue(point_a); @@ -204,20 +206,20 @@ LPEMirrorSymmetry::doBeforeEffect (SPLPEItem const* lpeitem) center_point.param_setValue(previous_center); return; } - if ( mode == MT_X || mode == MT_Y ) { + if (mode == MT_X || mode == MT_Y) { if (!are_near(previous_center, (Geom::Point)center_point, 0.01)) { center_point.param_setValue(Geom::middle_point(point_a, point_b)); end_point.param_setValue(point_b); start_point.param_setValue(point_a); } else { - if ( mode == MT_X ) { + if (mode == MT_X) { if (!are_near(start_point[X], point_a[X], 0.01)) { start_point.param_setValue(point_a); } if (!are_near(end_point[X], point_b[X], 0.01)) { end_point.param_setValue(point_b); } - } else { //MT_Y + } else { // MT_Y if (!are_near(start_point[Y], point_a[Y], 0.01)) { start_point.param_setValue(point_a); } @@ -226,7 +228,7 @@ LPEMirrorSymmetry::doBeforeEffect (SPLPEItem const* lpeitem) } } } - } else if ( mode == MT_FREE) { + } else if (mode == MT_FREE) { if (are_near(previous_center, (Geom::Point)center_point, 0.01)) { center_point.param_setValue(Geom::middle_point((Geom::Point)start_point, (Geom::Point)end_point)); @@ -235,23 +237,25 @@ LPEMirrorSymmetry::doBeforeEffect (SPLPEItem const* lpeitem) start_point.param_setValue(start_point * trans); end_point.param_setValue(end_point * trans); } - } else if ( mode == MT_V){ + } else if (mode == MT_V) { SPDocument *document = getSPDoc(); if (document) { Geom::Affine transform = i2anc_affine(SP_OBJECT(lpeitem), nullptr).inverse(); - Geom::Point sp = Geom::Point(document->getWidth().value("px")/2.0, 0) * transform; + Geom::Point sp = Geom::Point(document->getWidth().value("px") / 2.0, 0) * transform; start_point.param_setValue(sp); - Geom::Point ep = Geom::Point(document->getWidth().value("px")/2.0, document->getHeight().value("px")) * transform; + Geom::Point ep = + Geom::Point(document->getWidth().value("px") / 2.0, document->getHeight().value("px")) * transform; end_point.param_setValue(ep); center_point.param_setValue(Geom::middle_point((Geom::Point)start_point, (Geom::Point)end_point)); } - } else { //horizontal page + } else { // horizontal page SPDocument *document = getSPDoc(); if (document) { Geom::Affine transform = i2anc_affine(SP_OBJECT(lpeitem), nullptr).inverse(); - Geom::Point sp = Geom::Point(0, document->getHeight().value("px")/2.0) * transform; + Geom::Point sp = Geom::Point(0, document->getHeight().value("px") / 2.0) * transform; start_point.param_setValue(sp); - Geom::Point ep = Geom::Point(document->getWidth().value("px"), document->getHeight().value("px")/2.0) * transform; + Geom::Point ep = + Geom::Point(document->getWidth().value("px"), document->getHeight().value("px") / 2.0) * transform; end_point.param_setValue(ep); center_point.param_setValue(Geom::middle_point((Geom::Point)start_point, (Geom::Point)end_point)); } @@ -276,21 +280,20 @@ void LPEMirrorSymmetry::cloneStyle(SPObject *orig, SPObject *dest) } } -void -LPEMirrorSymmetry::cloneD(SPObject *orig, SPObject *dest, bool reset) +void LPEMirrorSymmetry::cloneD(SPObject *orig, SPObject *dest, bool reset) { SPDocument *document = getSPDoc(); if (!document) { return; } - if ( SP_IS_GROUP(orig) && SP_IS_GROUP(dest) && SP_GROUP(orig)->getItemCount() == SP_GROUP(dest)->getItemCount() ) { + if (SP_IS_GROUP(orig) && SP_IS_GROUP(dest) && SP_GROUP(orig)->getItemCount() == SP_GROUP(dest)->getItemCount()) { if (reset) { cloneStyle(orig, dest); } - std::vector< SPObject * > childs = orig->childList(true); + std::vector childs = orig->childList(true); size_t index = 0; - for (auto & child : childs) { + for (auto &child : childs) { SPObject *dest_child = dest->nthChild(index); cloneD(child, dest_child, reset); index++; @@ -310,8 +313,8 @@ LPEMirrorSymmetry::cloneD(SPObject *orig, SPObject *dest, bool reset) } } - SPShape * shape = SP_SHAPE(orig); - SPPath * path = SP_PATH(dest); + SPShape *shape = SP_SHAPE(orig); + SPPath *path = SP_PATH(dest); if (path && shape) { SPCurve const *c = shape->curve(); if (c) { @@ -327,8 +330,8 @@ LPEMirrorSymmetry::cloneD(SPObject *orig, SPObject *dest, bool reset) } } -Inkscape::XML::Node * -LPEMirrorSymmetry::createPathBase(SPObject *elemref) { +Inkscape::XML::Node *LPEMirrorSymmetry::createPathBase(SPObject *elemref) +{ SPDocument *document = getSPDoc(); if (!document) { return nullptr; @@ -339,7 +342,7 @@ LPEMirrorSymmetry::createPathBase(SPObject *elemref) { if (group) { Inkscape::XML::Node *container = xml_doc->createElement("svg:g"); container->setAttribute("transform", prev->attribute("transform")); - std::vector const item_list = sp_item_group_item_list(group); + std::vector const item_list = sp_item_group_item_list(group); Inkscape::XML::Node *previous = nullptr; for (auto sub_item : item_list) { Inkscape::XML::Node *resultnode = createPathBase(sub_item); @@ -353,8 +356,7 @@ LPEMirrorSymmetry::createPathBase(SPObject *elemref) { return resultnode; } -void -LPEMirrorSymmetry::toMirror(Geom::Affine transform, bool reset) +void LPEMirrorSymmetry::toMirror(Geom::Affine transform, bool reset) { SPDocument *document = getSPDoc(); if (!document) { @@ -378,7 +380,7 @@ LPEMirrorSymmetry::toMirror(Geom::Affine transform, bool reset) } cloneD(SP_OBJECT(sp_lpe_item), elemref, reset); gchar *str = sp_svg_transform_write(transform); - elemref->getRepr()->setAttribute("transform" , str); + elemref->getRepr()->setAttribute("transform", str); g_free(str); if (elemref->parent != container) { Inkscape::XML::Node *copy = phantom->duplicate(xml_doc); @@ -389,25 +391,21 @@ LPEMirrorSymmetry::toMirror(Geom::Affine transform, bool reset) } } - -void -LPEMirrorSymmetry::resetStyles(){ +void LPEMirrorSymmetry::resetStyles() +{ reset = true; doAfterEffect_impl(sp_lpe_item); } - -//TODO: Migrate the tree next function to effect.cpp/h to avoid duplication -void -LPEMirrorSymmetry::doOnVisibilityToggled(SPLPEItem const* /*lpeitem*/) +// TODO: Migrate the tree next function to effect.cpp/h to avoid duplication +void LPEMirrorSymmetry::doOnVisibilityToggled(SPLPEItem const * /*lpeitem*/) { processObjects(LPE_VISIBILITY); } -void -LPEMirrorSymmetry::doOnRemove (SPLPEItem const* /*lpeitem*/) +void LPEMirrorSymmetry::doOnRemove(SPLPEItem const * /*lpeitem*/) { - //set "keep paths" hook on sp-lpe-item.cpp + // set "keep paths" hook on sp-lpe-item.cpp if (keep_paths) { processObjects(LPE_TO_OBJECTS); items.clear(); @@ -416,8 +414,7 @@ LPEMirrorSymmetry::doOnRemove (SPLPEItem const* /*lpeitem*/) processObjects(LPE_ERASE); } -void -LPEMirrorSymmetry::doOnApply (SPLPEItem const* lpeitem) +void LPEMirrorSymmetry::doOnApply(SPLPEItem const *lpeitem) { using namespace Geom; @@ -434,9 +431,7 @@ LPEMirrorSymmetry::doOnApply (SPLPEItem const* lpeitem) previous_center = center_point; } - -Geom::PathVector -LPEMirrorSymmetry::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPEMirrorSymmetry::doEffect_path(Geom::PathVector const &path_in) { if (split_items && !fuse_paths) { return path_in; @@ -449,10 +444,9 @@ LPEMirrorSymmetry::doEffect_path (Geom::PathVector const & path_in) } Geom::Line line_separation((Geom::Point)start_point, (Geom::Point)end_point); - Geom::Affine m = Geom::reflection (line_separation.vector(), (Geom::Point)start_point); + Geom::Affine m = Geom::reflection(line_separation.vector(), (Geom::Point)start_point); if (fuse_paths && !discard_orig_path) { - for (const auto & path_it : original_pathv) - { + for (const auto &path_it : original_pathv) { if (path_it.empty()) { continue; } @@ -469,22 +463,24 @@ LPEMirrorSymmetry::doEffect_path (Geom::PathVector const & path_in) Geom::Path original = path_it; if (end_open && path_it.closed()) { original.close(false); - original.appendNew( original.initialPoint() ); + original.appendNew(original.initialPoint()); original.close(true); } Geom::Point s = start_point; Geom::Point e = end_point; double dir = line_separation.angle(); - double diagonal = Geom::distance(Geom::Point(boundingbox_X.min(),boundingbox_Y.min()),Geom::Point(boundingbox_X.max(),boundingbox_Y.max())); - Geom::Rect bbox(Geom::Point(boundingbox_X.min(),boundingbox_Y.min()),Geom::Point(boundingbox_X.max(),boundingbox_Y.max())); + double diagonal = Geom::distance(Geom::Point(boundingbox_X.min(), boundingbox_Y.min()), + Geom::Point(boundingbox_X.max(), boundingbox_Y.max())); + Geom::Rect bbox(Geom::Point(boundingbox_X.min(), boundingbox_Y.min()), + Geom::Point(boundingbox_X.max(), boundingbox_Y.max())); double size_divider = Geom::distance(center_point, bbox) + diagonal; - s = Geom::Point::polar(dir,size_divider) + center_point; - e = Geom::Point::polar(dir + Geom::rad_from_deg(180),size_divider) + center_point; + s = Geom::Point::polar(dir, size_divider) + center_point; + e = Geom::Point::polar(dir + Geom::rad_from_deg(180), size_divider) + center_point; Geom::Path divider = Geom::Path(s); divider.appendNew(e); Geom::Crossings cs = crossings(original, divider); std::vector crossed; - for(auto & c : cs) { + for (auto &c : cs) { crossed.push_back(c.ta); } std::sort(crossed.begin(), crossed.end()); @@ -497,7 +493,7 @@ LPEMirrorSymmetry::doEffect_path (Geom::PathVector const & path_in) if (time_start != time_end && time_end - time_start > Geom::EPSILON) { Geom::Path portion = original.portion(time_start, time_end); if (!portion.empty()) { - Geom::Point middle = portion.pointAt((double)portion.size()/2.0); + Geom::Point middle = portion.pointAt((double)portion.size() / 2.0); position = Geom::sgn(Geom::cross(e - s, middle - s)); if (!oposite_fuse) { position *= -1; @@ -507,7 +503,7 @@ LPEMirrorSymmetry::doEffect_path (Geom::PathVector const & path_in) Geom::Path mirror = portion.reversed() * m; mirror.setInitial(portion.finalPoint()); portion.append(mirror); - if(i != 0) { + if (i != 0) { portion.setFinal(portion.initialPoint()); portion.close(); } @@ -525,7 +521,7 @@ LPEMirrorSymmetry::doEffect_path (Geom::PathVector const & path_in) if (!oposite_fuse) { position *= -1; } - if (cs.size()!=0 && (position == 1)) { + if (cs.size() != 0 && (position == 1)) { if (time_start != original.size() && original.size() - time_start > Geom::EPSILON) { Geom::Path portion = original.portion(time_start, original.size()); if (!portion.empty()) { @@ -539,7 +535,7 @@ LPEMirrorSymmetry::doEffect_path (Geom::PathVector const & path_in) if (!original.closed()) { tmp_pathvector.push_back(portion); } else { - if (cs.size() > 1 && tmp_pathvector.size() > 0 && tmp_pathvector[0].size() > 0 ) { + if (cs.size() > 1 && tmp_pathvector.size() > 0 && tmp_pathvector[0].size() > 0) { if (swamped || !split_items) { portion.setFinal(tmp_pathvector[0].initialPoint()); portion.setInitial(tmp_pathvector[0].finalPoint()); @@ -566,29 +562,28 @@ LPEMirrorSymmetry::doEffect_path (Geom::PathVector const & path_in) tmp_pathvector.clear(); } } else if (!fuse_paths || discard_orig_path) { - for (const auto & i : original_pathv) { + for (const auto &i : original_pathv) { path_out.push_back(i * m); } } return path_out; } -void -LPEMirrorSymmetry::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) +void LPEMirrorSymmetry::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { using namespace Geom; hp_vec.clear(); Geom::Path path; Geom::Point s = start_point; Geom::Point e = end_point; - path.start( s ); - path.appendNew( e ); + path.start(s); + path.appendNew(e); Geom::PathVector helper; helper.push_back(path); hp_vec.push_back(helper); } -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-mirror_symmetry.h b/src/live_effects/lpe-mirror_symmetry.h index aaddb3836d2671eab2a4f9f43c36ded464685971..7b4ca1ac07f19f038b3dc2217d907342e5c7149b 100644 --- a/src/live_effects/lpe-mirror_symmetry.h +++ b/src/live_effects/lpe-mirror_symmetry.h @@ -18,18 +18,19 @@ */ #include "live_effects/effect.h" -#include "live_effects/lpeobject.h" +#include "live_effects/lpegroupbbox.h" #include "live_effects/lpeobject-reference.h" +#include "live_effects/lpeobject.h" +#include "live_effects/parameter/enum.h" #include "live_effects/parameter/parameter.h" -#include "live_effects/parameter/text.h" #include "live_effects/parameter/point.h" -#include "live_effects/parameter/enum.h" -#include "live_effects/lpegroupbbox.h" +#include "live_effects/parameter/text.h" namespace Inkscape { namespace LivePathEffect { -enum ModeType { +enum ModeType +{ MT_V, MT_H, MT_FREE, @@ -38,21 +39,24 @@ enum ModeType { MT_END }; -class LPEMirrorSymmetry : public Effect, GroupBBoxEffect { +class LPEMirrorSymmetry + : public Effect + , GroupBBoxEffect +{ public: LPEMirrorSymmetry(LivePathEffectObject *lpeobject); ~LPEMirrorSymmetry() override; - void doOnApply (SPLPEItem const* lpeitem) override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; - void doAfterEffect (SPLPEItem const* lpeitem) override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; - void doOnRemove (SPLPEItem const* /*lpeitem*/) override; - void doOnVisibilityToggled(SPLPEItem const* /*lpeitem*/) override; - Gtk::Widget * newWidget() override; + void doOnApply(SPLPEItem const *lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; + void doAfterEffect(SPLPEItem const *lpeitem) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; + void doOnRemove(SPLPEItem const * /*lpeitem*/) override; + void doOnVisibilityToggled(SPLPEItem const * /*lpeitem*/) override; + Gtk::Widget *newWidget() override; void cloneStyle(SPObject *orig, SPObject *dest); void toMirror(Geom::Affine transform, bool reset); void cloneD(SPObject *orig, SPObject *dest, bool reset); - Inkscape::XML::Node * createPathBase(SPObject *elemref); + Inkscape::XML::Node *createPathBase(SPObject *elemref); void resetStyles(); void centerVert(); void centerHoriz(); @@ -70,15 +74,15 @@ private: PointParam end_point; PointParam center_point; Geom::Point previous_center; - SPObject * container; + SPObject *container; bool reset; bool center_vert; bool center_horiz; - LPEMirrorSymmetry(const LPEMirrorSymmetry&) = delete; - LPEMirrorSymmetry& operator=(const LPEMirrorSymmetry&) = delete; + LPEMirrorSymmetry(const LPEMirrorSymmetry &) = delete; + LPEMirrorSymmetry &operator=(const LPEMirrorSymmetry &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-offset.cpp b/src/live_effects/lpe-offset.cpp index c2463488c57e706ccdddc1103c0fd2ed1cdd9c28..182ccb5a18636fd6c89d2c5ea6afbe7cea7ad224 100644 --- a/src/live_effects/lpe-offset.cpp +++ b/src/live_effects/lpe-offset.cpp @@ -14,33 +14,34 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/enum.h" #include "live_effects/lpe-offset.h" -#include "display/curve.h" -#include "inkscape.h" -#include "helper/geom.h" -#include "helper/geom-pathstroke.h" -#include <2geom/sbasis-to-bezier.h> -#include <2geom/piecewise.h> -#include <2geom/path-intersection.h> -#include <2geom/intersection-graph.h> -#include <2geom/elliptical-arc.h> + #include <2geom/angle.h> #include <2geom/curve.h> -#include "object/sp-shape.h" -#include "path/path-boolop.h" +#include <2geom/elliptical-arc.h> +#include <2geom/intersection-graph.h> +#include <2geom/path-intersection.h> +#include <2geom/piecewise.h> +#include <2geom/sbasis-to-bezier.h> +#include + +#include "display/curve.h" +#include "helper/geom-pathstroke.h" +#include "helper/geom.h" +#include "inkscape.h" #include "knot-holder-entity.h" +#include "knot.h" #include "knotholder.h" +#include "live_effects/parameter/enum.h" +#include "object/sp-shape.h" +#include "path/path-boolop.h" #include "util/units.h" -#include "knot.h" -#include // this is only to flatten nonzero fillrule +#include <2geom/elliptical-arc.h> + #include "livarot/Path.h" #include "livarot/Shape.h" - #include "svg/svg.h" - -#include <2geom/elliptical-arc.h> // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -48,15 +49,18 @@ namespace Inkscape { namespace LivePathEffect { namespace OfS { - class KnotHolderEntityOffsetPoint : public LPEKnotHolderEntity { - public: - KnotHolderEntityOffsetPoint(LPEOffset * effect) : LPEKnotHolderEntity(effect) {} - void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; - Geom::Point knot_get() const override; - private: - }; -} // OfS - +class KnotHolderEntityOffsetPoint : public LPEKnotHolderEntity +{ +public: + KnotHolderEntityOffsetPoint(LPEOffset *effect) + : LPEKnotHolderEntity(effect) + {} + void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; + Geom::Point knot_get() const override; + +private: +}; +} // namespace OfS static const Util::EnumData JoinTypeData[] = { // clang-format off @@ -71,17 +75,20 @@ static const Util::EnumData JoinTypeData[] = { // clang-format on }; -static const Util::EnumDataConverter JoinTypeConverter(JoinTypeData, sizeof(JoinTypeData)/sizeof(*JoinTypeData)); - - -LPEOffset::LPEOffset(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - unit(_("Unit"), _("Unit of measurement"), "unit", &wr, this, "mm"), - offset(_("Offset:"), _("Offset"), "offset", &wr, this, 0.0), - linejoin_type(_("Join:"), _("Determines the shape of the path's corners"), "linejoin_type", JoinTypeConverter, &wr, this, JOIN_MITER), - miter_limit(_("Miter limit:"), _("Maximum length of the miter join (in units of stroke width)"), "miter_limit", &wr, this, 4.0), - attempt_force_join(_("Force miter"), _("Overrides the miter limit and forces a join."), "attempt_force_join", &wr, this, true), - update_on_knot_move(_("Live update"), _("Update while moving handle"), "update_on_knot_move", &wr, this, true) +static const Util::EnumDataConverter JoinTypeConverter(JoinTypeData, + sizeof(JoinTypeData) / sizeof(*JoinTypeData)); + +LPEOffset::LPEOffset(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , unit(_("Unit"), _("Unit of measurement"), "unit", &wr, this, "mm") + , offset(_("Offset:"), _("Offset"), "offset", &wr, this, 0.0) + , linejoin_type(_("Join:"), _("Determines the shape of the path's corners"), "linejoin_type", JoinTypeConverter, + &wr, this, JOIN_MITER) + , miter_limit(_("Miter limit:"), _("Maximum length of the miter join (in units of stroke width)"), "miter_limit", + &wr, this, 4.0) + , attempt_force_join(_("Force miter"), _("Overrides the miter limit and forces a join."), "attempt_force_join", &wr, + this, true) + , update_on_knot_move(_("Live update"), _("Update while moving handle"), "update_on_knot_move", &wr, this, true) { show_orig_path = true; registerParameter(&linejoin_type); @@ -99,39 +106,36 @@ LPEOffset::LPEOffset(LivePathEffectObject *lpeobject) : prev_unit = unit.get_abbreviation(); } -LPEOffset::~LPEOffset() -= default; +LPEOffset::~LPEOffset() = default; typedef FillRule FillRuleFlatten; -static void -sp_flatten(Geom::PathVector &pathvector, FillRuleFlatten fillkind) +static void sp_flatten(Geom::PathVector &pathvector, FillRuleFlatten fillkind) { Path *orig = new Path; orig->LoadPathVector(pathvector); Shape *theShape = new Shape; Shape *theRes = new Shape; - orig->ConvertWithBackData (1.0); - orig->Fill (theShape, 0); - theRes->ConvertToShape (theShape, FillRule(fillkind)); + orig->ConvertWithBackData(1.0); + orig->Fill(theShape, 0); + theRes->ConvertToShape(theShape, FillRule(fillkind)); Path *originaux[1]; originaux[0] = orig; Path *res = new Path; - theRes->ConvertToForme (res, 1, originaux, true); + theRes->ConvertToForme(res, 1, originaux, true); delete theShape; delete theRes; - char *res_d = res->svg_dump_path (); + char *res_d = res->svg_dump_path(); delete res; delete orig; - pathvector = sp_svg_read_pathv(res_d); + pathvector = sp_svg_read_pathv(res_d); } -Geom::Point -LPEOffset::get_nearest_point(Geom::PathVector pathv, Geom::Point point) const +Geom::Point LPEOffset::get_nearest_point(Geom::PathVector pathv, Geom::Point point) const { Geom::Point res = Geom::Point(Geom::infinity(), Geom::infinity()); - boost::optional< Geom::PathVectorTime > pathvectortime = pathv.nearestTime(point); + boost::optional pathvectortime = pathv.nearestTime(point); if (pathvectortime) { Geom::PathTime pathtime = pathvectortime->asPathTime(); res = pathv[(*pathvectortime).path_index].pointAt(pathtime.curve_index + pathtime.t); @@ -147,25 +151,23 @@ void LPEOffset::transform_multiply(Geom::Affine const &postmul, bool /*set*/) } } -Geom::Point -LPEOffset::get_default_point(Geom::PathVector pathv) const +Geom::Point LPEOffset::get_default_point(Geom::PathVector pathv) const { Geom::Point origin = Geom::Point(Geom::infinity(), Geom::infinity()); Geom::OptRect bbox = pathv.boundsFast(); if (bbox) { if (SP_IS_GROUP(sp_lpe_item)) { - origin = Geom::Point(boundingbox_X.min(),boundingbox_Y.min()); + origin = Geom::Point(boundingbox_X.min(), boundingbox_Y.min()); } else { - origin = Geom::Point((*bbox).midpoint()[Geom::X],(*bbox).top()); + origin = Geom::Point((*bbox).midpoint()[Geom::X], (*bbox).top()); origin = get_nearest_point(pathv, origin); } - } return origin; } -double -sp_get_distance_point(Geom::PathVector pathv, Geom::Point origin) { - boost::optional< Geom::PathVectorTime > pathvectortime = pathv.nearestTime(origin); +double sp_get_distance_point(Geom::PathVector pathv, Geom::Point origin) +{ + boost::optional pathvectortime = pathv.nearestTime(origin); Geom::Point nearest = origin; if (pathvectortime) { Geom::PathTime pathtime = pathvectortime->asPathTime(); @@ -224,10 +226,9 @@ sp_get_distance_point(Geom::PathVector pathv, Geom::Point origin) { return Geom::distance(origin, nearest); } -double -LPEOffset::sp_get_offset(Geom::Point origin) +double LPEOffset::sp_get_offset(Geom::Point origin) { - SPGroup * group = dynamic_cast(sp_lpe_item); + SPGroup *group = dynamic_cast(sp_lpe_item); double ret_offset = 0; if (group) { Geom::Point initial = get_default_point(filled_rule_pathv); @@ -237,12 +238,12 @@ LPEOffset::sp_get_offset(Geom::Point origin) } return Inkscape::Util::Quantity::convert(ret_offset, "px", unit.get_abbreviation()) * this->scale; } - int winding_value = filled_rule_pathv.winding(origin); + int winding_value = filled_rule_pathv.winding(origin); bool inset = false; if (winding_value % 2 != 0) { inset = true; } - + ret_offset = sp_get_distance_point(filled_rule_pathv, origin); if (inset) { ret_offset *= -1; @@ -250,14 +251,12 @@ LPEOffset::sp_get_offset(Geom::Point origin) return Inkscape::Util::Quantity::convert(ret_offset, "px", unit.get_abbreviation()) * this->scale; } -void -LPEOffset::addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec) +void LPEOffset::addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec) { hp_vec.push_back(helper_path); } -void -LPEOffset::doBeforeEffect (SPLPEItem const* lpeitem) +void LPEOffset::doBeforeEffect(SPLPEItem const *lpeitem) { original_bbox(lpeitem); SPDocument *document = getSPDoc(); @@ -274,7 +273,8 @@ LPEOffset::doBeforeEffect (SPLPEItem const* lpeitem) helper_path.clear(); Geom::Point origin = Geom::Point(boundingbox_X.min(), boundingbox_Y.min()); Geom::Point endpont = Geom::Point(boundingbox_X.min(), boundingbox_Y.min()); - endpont[Geom::Y] = endpont[Geom::Y] + Inkscape::Util::Quantity::convert(offset, unit.get_abbreviation(), "px")/ this->scale; + endpont[Geom::Y] = + endpont[Geom::Y] + Inkscape::Util::Quantity::convert(offset, unit.get_abbreviation(), "px") / this->scale; Geom::Path hp(origin); hp.appendNew(endpont); helper_path.push_back(hp); @@ -285,15 +285,17 @@ int offset_winding(Geom::PathVector pathvector, Geom::Path path) { int wind = 0; Geom::Point p = path.initialPoint(); - for (auto i:pathvector) { - if (i == path) continue; - if (!i.boundsFast().contains(p)) continue; + for (auto i : pathvector) { + if (i == path) + continue; + if (!i.boundsFast().contains(p)) + continue; wind += i.winding(p); } return wind; } -/* Geom::Path +/* Geom::Path sp_get_outer(Geom::PathVector pathv) { sp_flatten(pathv, fill_nonZero); Geom::Path out_bounds; @@ -323,7 +325,7 @@ sp_get_outer(Geom::PathVector pathv) { return out_size; } -Geom::PathVector +Geom::PathVector sp_get_inner(Geom::PathVector pathv, Geom::Path outer) { Geom::PathVector out; for (auto path_child:pathv) { @@ -334,20 +336,18 @@ sp_get_inner(Geom::PathVector pathv, Geom::Path outer) { return out; } */ -Geom::PathVector -LPEOffset::doEffect_path(Geom::PathVector const & path_in) +Geom::PathVector LPEOffset::doEffect_path(Geom::PathVector const &path_in) { - SPItem * item = SP_ITEM(current_shape); + SPItem *item = SP_ITEM(current_shape); if (!item) { return path_in; } SPCSSAttr *css; const gchar *val; - css = sp_repr_css_attr (item->getRepr() , "style"); - val = sp_repr_css_property (css, "fill-rule", nullptr); + css = sp_repr_css_attr(item->getRepr(), "style"); + val = sp_repr_css_property(css, "fill-rule", nullptr); FillRuleFlatten fillrule = fill_nonZero; - if (val && strcmp (val, "evenodd") == 0) - { + if (val && strcmp(val, "evenodd") == 0) { fillrule = fill_oddEven; } Geom::PathVector original_pathv = pathv_to_linear_and_cubic_beziers(path_in); @@ -359,7 +359,7 @@ LPEOffset::doEffect_path(Geom::PathVector const & path_in) Geom::PathVector ret; Geom::PathVector open_ret; Geom::PathVector ret_outline; - for (const auto & path_it : filled_rule_pathv) { + for (const auto &path_it : filled_rule_pathv) { Geom::Path original = path_it; if (original.empty()) { continue; @@ -383,16 +383,12 @@ LPEOffset::doEffect_path(Geom::PathVector const & path_in) if (path_inside && (offset * 2 > (original_height + original_width) / 2.0)) { continue; } - Geom::Path with_dir = half_outline(original, - to_offset, - (attempt_force_join ? std::numeric_limits::max() : miter_limit), - static_cast(linejoin_type.get_value()), - static_cast(BUTT_FLAT)); - Geom::Path against_dir = half_outline(original.reversed(), - to_offset, - (attempt_force_join ? std::numeric_limits::max() : miter_limit), - static_cast(linejoin_type.get_value()), - static_cast(BUTT_FLAT)); + Geom::Path with_dir = + half_outline(original, to_offset, (attempt_force_join ? std::numeric_limits::max() : miter_limit), + static_cast(linejoin_type.get_value()), static_cast(BUTT_FLAT)); + Geom::Path against_dir = half_outline( + original.reversed(), to_offset, (attempt_force_join ? std::numeric_limits::max() : miter_limit), + static_cast(linejoin_type.get_value()), static_cast(BUTT_FLAT)); Geom::Path with_dir_gap = half_outline(original, std::abs(to_offset + gap_size), (attempt_force_join ? std::numeric_limits::max() : miter_limit), @@ -419,24 +415,17 @@ LPEOffset::doEffect_path(Geom::PathVector const & path_in) reversed = against_dir_bounds.contains(with_dir_bounds) == false; // We can have a strange result for the bounding box container // Gives a wrong result, in theory, it happens sometimes on expand offset - if (offset > 0 && - ((original_width < against_dir_width && - original_width < with_dir_width) || - (original_height < against_dir_height && - original_height < with_dir_height))) + if (offset > 0 && ((original_width < against_dir_width && original_width < with_dir_width) || + (original_height < against_dir_height && original_height < with_dir_height))) { - Geom::Path with_dir_size = half_outline(original, - 2, - (attempt_force_join ? std::numeric_limits::max() : miter_limit), - static_cast(linejoin_type.get_value()), - static_cast(BUTT_FLAT)); - Geom::Path against_dir_size = half_outline(original.reversed(), - 2, - (attempt_force_join ? std::numeric_limits::max() : miter_limit), - static_cast(linejoin_type.get_value()), - static_cast(BUTT_FLAT)); - + Geom::Path with_dir_size = + half_outline(original, 2, (attempt_force_join ? std::numeric_limits::max() : miter_limit), + static_cast(linejoin_type.get_value()), static_cast(BUTT_FLAT)); + Geom::Path against_dir_size = half_outline( + original.reversed(), 2, (attempt_force_join ? std::numeric_limits::max() : miter_limit), + static_cast(linejoin_type.get_value()), static_cast(BUTT_FLAT)); + Geom::OptRect against_dir_size_bounds = against_dir_size.boundsFast(); Geom::OptRect with_dir_size_bounds = with_dir_size.boundsFast(); reversed = against_dir_size_bounds.contains(with_dir_size_bounds) == false; @@ -453,15 +442,15 @@ LPEOffset::doEffect_path(Geom::PathVector const & path_in) } if (reversed || !closed) { big = with_dir; - gap = with_dir_gap; + gap = with_dir_gap; small = against_dir; } else { - big = against_dir; + big = against_dir; gap = against_dir_gap; small = with_dir; } - //big = sp_get_outer(big); - //gap = sp_get_outer(gap); + // big = sp_get_outer(big); + // gap = sp_get_outer(gap); if (!closed) { tmp.push_back(small); @@ -477,7 +466,7 @@ LPEOffset::doEffect_path(Geom::PathVector const & path_in) } continue; } - bool fix_reverse = (original_width + original_height) / 2.0 > to_offset * 2; + bool fix_reverse = (original_width + original_height) / 2.0 > to_offset * 2; if (offset < 0) { tmp.push_back(gap); } else { @@ -487,7 +476,7 @@ LPEOffset::doEffect_path(Geom::PathVector const & path_in) } } else { tmp.push_back(big); - } + } } ret.insert(ret.end(), tmp.begin(), tmp.end()); if (offset < 0) { @@ -504,7 +493,7 @@ LPEOffset::doEffect_path(Geom::PathVector const & path_in) sp_flatten(ret, fill_nonZero); ret.insert(ret.end(), open_ret.begin(), open_ret.end()); - + if (offset_pt == Geom::Point(Geom::infinity(), Geom::infinity())) { offset_pt = get_default_point(ret); } @@ -519,11 +508,11 @@ void LPEOffset::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) } namespace OfS { -void KnotHolderEntityOffsetPoint::knot_set(Geom::Point const &p, Geom::Point const& /*origin*/, guint state) +void KnotHolderEntityOffsetPoint::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { using namespace Geom; - SPGroup * group = dynamic_cast(item); - LPEOffset* lpe = dynamic_cast(_effect); + SPGroup *group = dynamic_cast(item); + LPEOffset *lpe = dynamic_cast(_effect); Geom::Point s = snap_knot_position(p, state); if (group) { s[Geom::X] = lpe->boundingbox_X.min(); @@ -532,19 +521,19 @@ void KnotHolderEntityOffsetPoint::knot_set(Geom::Point const &p, Geom::Point con lpe->offset_pt = s; lpe->offset.param_set_value(offset); if (lpe->update_on_knot_move) { - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, false); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, false); } } Geom::Point KnotHolderEntityOffsetPoint::knot_get() const { - SPGroup * group = dynamic_cast(item); - LPEOffset * lpe = dynamic_cast (_effect); + SPGroup *group = dynamic_cast(item); + LPEOffset *lpe = dynamic_cast(_effect); if (!lpe->update_on_knot_move) { return lpe->offset_pt; } Geom::Point nearest = lpe->offset_pt; - + if (lpe->offset_pt == Geom::Point(Geom::infinity(), Geom::infinity())) { if (group) { nearest = Geom::Point(lpe->boundingbox_X.min(), lpe->boundingbox_Y.min()); @@ -558,12 +547,12 @@ Geom::Point KnotHolderEntityOffsetPoint::knot_get() const } } } - + return nearest; } } // namespace OfS -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-offset.h b/src/live_effects/lpe-offset.h index 83d9f2e59d48d47fc4af8b67b53c8ec916961af4..b7962cb3b89ec9882a829d438137ad6b92c1c7dd 100644 --- a/src/live_effects/lpe-offset.h +++ b/src/live_effects/lpe-offset.h @@ -29,20 +29,23 @@ namespace LivePathEffect { namespace OfS { // we need a separate namespace to avoid clashes with other LPEs class KnotHolderEntityOffsetPoint; -} +} // namespace OfS -class LPEOffset : public Effect, GroupBBoxEffect { +class LPEOffset + : public Effect + , GroupBBoxEffect +{ public: LPEOffset(LivePathEffectObject *lpeobject); ~LPEOffset() override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; void transform_multiply(Geom::Affine const &postmul, bool set) override; - void addKnotHolderEntities(KnotHolder * knotholder, SPItem * item) override; + void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) override; void addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec) override; - void calculateOffset (Geom::PathVector const & path_in); + void calculateOffset(Geom::PathVector const &path_in); Geom::Point get_default_point(Geom::PathVector pathv) const; - Geom::Point get_nearest_point(Geom::PathVector pathv, Geom::Point point) const; + Geom::Point get_nearest_point(Geom::PathVector pathv, Geom::Point point) const; double sp_get_offset(Geom::Point origin); friend class OfS::KnotHolderEntityOffsetPoint; @@ -55,18 +58,18 @@ private: BoolParam update_on_knot_move; Geom::Point offset_pt; Glib::ustring prev_unit; - double scale = 1; //take document scale and additional parent transformations into account - KnotHolderEntity * _knot_entity; + double scale = 1; // take document scale and additional parent transformations into account + KnotHolderEntity *_knot_entity; Geom::PathVector filled_rule_pathv; Geom::PathVector helper_path; Inkscape::UI::Widget::Scalar *offset_widget; - LPEOffset(const LPEOffset&); - LPEOffset& operator=(const LPEOffset&); + LPEOffset(const LPEOffset &); + LPEOffset &operator=(const LPEOffset &); }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-parallel.cpp b/src/live_effects/lpe-parallel.cpp index daf454532566a8615334b756afd442d3d9519cdb..addef9239ffaa6b7fba5ee7daf914fba98498a71 100644 --- a/src/live_effects/lpe-parallel.cpp +++ b/src/live_effects/lpe-parallel.cpp @@ -13,10 +13,10 @@ */ #include "live_effects/lpe-parallel.h" -#include "object/sp-shape.h" -#include "display/curve.h" +#include "display/curve.h" #include "knotholder.h" +#include "object/sp-shape.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -26,28 +26,33 @@ namespace LivePathEffect { namespace Pl { -class KnotHolderEntityLeftEnd : public LPEKnotHolderEntity { +class KnotHolderEntityLeftEnd : public LPEKnotHolderEntity +{ public: - KnotHolderEntityLeftEnd(LPEParallel *effect) : LPEKnotHolderEntity(effect) {}; + KnotHolderEntityLeftEnd(LPEParallel *effect) + : LPEKnotHolderEntity(effect){}; void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; }; -class KnotHolderEntityRightEnd : public LPEKnotHolderEntity { +class KnotHolderEntityRightEnd : public LPEKnotHolderEntity +{ public: - KnotHolderEntityRightEnd(LPEParallel *effect) : LPEKnotHolderEntity(effect) {}; + KnotHolderEntityRightEnd(LPEParallel *effect) + : LPEKnotHolderEntity(effect){}; void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; }; } // namespace Pl -LPEParallel::LPEParallel(LivePathEffectObject *lpeobject) : - Effect(lpeobject), +LPEParallel::LPEParallel(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , // initialise your parameters here: - offset_pt(_("Offset"), _("Adjust the offset"), "offset_pt", &wr, this), - length_left(_("Length left:"), _("Specifies the left end of the parallel"), "length-left", &wr, this, 150), - length_right(_("Length right:"), _("Specifies the right end of the parallel"), "length-right", &wr, this, 150) + offset_pt(_("Offset"), _("Adjust the offset"), "offset_pt", &wr, this) + , length_left(_("Length left:"), _("Specifies the left end of the parallel"), "length-left", &wr, this, 150) + , length_right(_("Length right:"), _("Specifies the right end of the parallel"), "length-right", &wr, this, 150) { show_orig_path = true; _provides_knotholder_entities = true; @@ -57,16 +62,14 @@ LPEParallel::LPEParallel(LivePathEffectObject *lpeobject) : registerParameter(&length_right); } -LPEParallel::~LPEParallel() -= default; +LPEParallel::~LPEParallel() = default; -void -LPEParallel::doOnApply (SPLPEItem const* lpeitem) +void LPEParallel::doOnApply(SPLPEItem const *lpeitem) { auto shape = dynamic_cast(lpeitem); if (!shape) { g_warning("LPE parallel can only be applied to shapes (not groups)."); - SPLPEItem * item = const_cast(lpeitem); + SPLPEItem *item = const_cast(lpeitem); item->removeCurrentPathEffect(false); return; } @@ -75,17 +78,17 @@ LPEParallel::doOnApply (SPLPEItem const* lpeitem) A = *(curve->first_point()); B = *(curve->last_point()); dir = unit_vector(B - A); - Geom::Point offset = (A + B)/2 + dir.ccw() * 100; + Geom::Point offset = (A + B) / 2 + dir.ccw() * 100; offset_pt.param_update_default(offset); offset_pt.param_setValue(offset, true); } -Geom::Piecewise > -LPEParallel::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPEParallel::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; - Piecewise > output; + Piecewise> output; A = pwd2_in.firstValue(); B = pwd2_in.lastValue(); @@ -94,28 +97,26 @@ LPEParallel::doEffect_pwd2 (Geom::Piecewise > const & pwd C = offset_pt - dir * length_left; D = offset_pt + dir * length_right; - output = Piecewise >(D2(SBasis(C[X], D[X]), SBasis(C[Y], D[Y]))); - + output = Piecewise>(D2(SBasis(C[X], D[X]), SBasis(C[Y], D[Y]))); + return output + dir; } -void LPEParallel::addKnotHolderEntities(KnotHolder *knotholder, SPDesktop *desktop, SPItem *item) { - { - KnotHolderEntity *e = new Pl::KnotHolderEntityLeftEnd(this); +void LPEParallel::addKnotHolderEntities(KnotHolder *knotholder, SPDesktop *desktop, + SPItem *item){{KnotHolderEntity *e = new Pl::KnotHolderEntityLeftEnd(this); e->create(desktop, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the \"left\" end of the parallel")); knotholder->add(e); - } - { - KnotHolderEntity *e = new Pl::KnotHolderEntityRightEnd(this); - e->create(desktop, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the \"right\" end of the parallel")); - knotholder->add(e); - } -}; +} // namespace LivePathEffect +{ + KnotHolderEntity *e = new Pl::KnotHolderEntityRightEnd(this); + e->create(desktop, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the \"right\" end of the parallel")); + knotholder->add(e); +} +}; // namespace Inkscape namespace Pl { -void -KnotHolderEntityLeftEnd::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) +void KnotHolderEntityLeftEnd::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { using namespace Geom; @@ -126,11 +127,10 @@ KnotHolderEntityLeftEnd::knot_set(Geom::Point const &p, Geom::Point const &/*ori double lambda = L2(s - lpe->offset_pt) * sgn(dot(s - lpe->offset_pt, lpe->dir)); lpe->length_left.param_set_value(-lambda); - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, true); } -void -KnotHolderEntityRightEnd::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) +void KnotHolderEntityRightEnd::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { using namespace Geom; @@ -141,20 +141,18 @@ KnotHolderEntityRightEnd::knot_set(Geom::Point const &p, Geom::Point const &/*or double lambda = L2(s - lpe->offset_pt) * sgn(dot(s - lpe->offset_pt, lpe->dir)); lpe->length_right.param_set_value(lambda); - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, true); } -Geom::Point -KnotHolderEntityLeftEnd::knot_get() const +Geom::Point KnotHolderEntityLeftEnd::knot_get() const { - LPEParallel const *lpe = dynamic_cast(_effect); + LPEParallel const *lpe = dynamic_cast(_effect); return lpe->C; } -Geom::Point -KnotHolderEntityRightEnd::knot_get() const +Geom::Point KnotHolderEntityRightEnd::knot_get() const { - LPEParallel const *lpe = dynamic_cast(_effect); + LPEParallel const *lpe = dynamic_cast(_effect); return lpe->D; } @@ -162,7 +160,7 @@ KnotHolderEntityRightEnd::knot_get() const /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-parallel.h b/src/live_effects/lpe-parallel.h index 0a2f65e806061f59cddcb2f789cbd986ead7721f..a64ce7848205c13680578927316a9df92d90db0a 100644 --- a/src/live_effects/lpe-parallel.h +++ b/src/live_effects/lpe-parallel.h @@ -23,19 +23,21 @@ namespace Inkscape { namespace LivePathEffect { namespace Pl { - // we need a separate namespace to avoid clashes with LPEPerpBisector - class KnotHolderEntityLeftEnd; - class KnotHolderEntityRightEnd; -} +// we need a separate namespace to avoid clashes with LPEPerpBisector +class KnotHolderEntityLeftEnd; +class KnotHolderEntityRightEnd; +} // namespace Pl -class LPEParallel : public Effect { +class LPEParallel : public Effect +{ public: LPEParallel(LivePathEffectObject *lpeobject); ~LPEParallel() override; - void doOnApply (SPLPEItem const* lpeitem) override; + void doOnApply(SPLPEItem const *lpeitem) override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; /* the knotholder entity classes must be declared friends */ friend class Pl::KnotHolderEntityLeftEnd; @@ -55,12 +57,12 @@ private: Geom::Point N; Geom::Point dir; - LPEParallel(const LPEParallel&) = delete; - LPEParallel& operator=(const LPEParallel&) = delete; + LPEParallel(const LPEParallel &) = delete; + LPEParallel &operator=(const LPEParallel &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-path_length.cpp b/src/live_effects/lpe-path_length.cpp index 3a4ca88f76ac412bd74a5ee3cf3eafe28ce278ba..ec007be5fa2cc3867da213ecd36e95fecc15c161 100644 --- a/src/live_effects/lpe-path_length.cpp +++ b/src/live_effects/lpe-path_length.cpp @@ -13,6 +13,7 @@ */ #include "live_effects/lpe-path_length.h" + #include "util/units.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -20,12 +21,12 @@ namespace Inkscape { namespace LivePathEffect { -LPEPathLength::LPEPathLength(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - scale(_("Scale:"), _("Scaling factor"), "scale", &wr, this, 1.0), - info_text(this), - unit(_("Unit:"), _("Unit"), "unit", &wr, this), - display_unit(_("Display unit"), _("Print unit after path length"), "display_unit", &wr, this, true) +LPEPathLength::LPEPathLength(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , scale(_("Scale:"), _("Scaling factor"), "scale", &wr, this, 1.0) + , info_text(this) + , unit(_("Unit:"), _("Unit"), "unit", &wr, this) + , display_unit(_("Display unit"), _("Print unit after path length"), "display_unit", &wr, this, true) { registerParameter(&scale); registerParameter(&info_text); @@ -33,11 +34,10 @@ LPEPathLength::LPEPathLength(LivePathEffectObject *lpeobject) : registerParameter(&display_unit); } -LPEPathLength::~LPEPathLength() -= default; +LPEPathLength::~LPEPathLength() = default; -Geom::Piecewise > -LPEPathLength::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPEPathLength::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; @@ -46,8 +46,7 @@ LPEPathLength::doEffect_pwd2 (Geom::Piecewise > const & p lengthval = Inkscape::Util::Quantity::convert(lengthval, "px", unit.get_abbreviation()); /* ... set it as the canvas text ... */ - gchar *arc_length = g_strdup_printf("%.2f %s", lengthval, - display_unit ? unit.get_abbreviation() : ""); + gchar *arc_length = g_strdup_printf("%.2f %s", lengthval, display_unit ? unit.get_abbreviation() : ""); info_text.param_setValue(arc_length); g_free(arc_length); @@ -55,20 +54,20 @@ LPEPathLength::doEffect_pwd2 (Geom::Piecewise > const & p // TODO: how can we compute the area (such that cw turns don't count negative)? // should we display the area here, too, or write a new LPE for this? - Piecewise > A = integral(pwd2_in); + Piecewise> A = integral(pwd2_in); Point c; double area; if (centroid(pwd2_in, c, area)) { - //g_print ("Area is zero\n"); + // g_print ("Area is zero\n"); } - //g_print ("Area: %f\n", area); + // g_print ("Area: %f\n", area); if (!this->isVisible()) { info_text.param_setValue(""); } return pwd2_in; } -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-path_length.h b/src/live_effects/lpe-path_length.h index 115bf5ca1ac3658e9633568984857719156cd7d7..7c979c753b317874b9abf01b6ae570871e501c1a 100644 --- a/src/live_effects/lpe-path_length.h +++ b/src/live_effects/lpe-path_length.h @@ -16,31 +16,33 @@ */ #include "live_effects/effect.h" +#include "live_effects/parameter/bool.h" #include "live_effects/parameter/text.h" #include "live_effects/parameter/unit.h" -#include "live_effects/parameter/bool.h" namespace Inkscape { namespace LivePathEffect { -class LPEPathLength : public Effect { +class LPEPathLength : public Effect +{ public: LPEPathLength(LivePathEffectObject *lpeobject); ~LPEPathLength() override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; private: - LPEPathLength(const LPEPathLength&) = delete; - LPEPathLength& operator=(const LPEPathLength&) = delete; + LPEPathLength(const LPEPathLength &) = delete; + LPEPathLength &operator=(const LPEPathLength &) = delete; ScalarParam scale; TextParamInternal info_text; UnitParam unit; BoolParam display_unit; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-patternalongpath.cpp b/src/live_effects/lpe-patternalongpath.cpp index 9dffef2034b47a991d292fced1de231a71e8cf31..b6e809334b81b021d6811922514e38be18fff77c 100644 --- a/src/live_effects/lpe-patternalongpath.cpp +++ b/src/live_effects/lpe-patternalongpath.cpp @@ -5,33 +5,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include -#include +#include "live_effects/lpe-patternalongpath.h" #include <2geom/bezier-to-sbasis.h> +#include +#include +#include -#include "live_effects/lpe-patternalongpath.h" -#include "live_effects/lpeobject.h" #include "display/curve.h" - -#include "object/sp-shape.h" - #include "knotholder.h" +#include "live_effects/lpeobject.h" +#include "object/sp-shape.h" // TODO due to internal breakage in glibmm headers, this must be last: #include - /* Theory in e-mail from J.F. Barraud Let B be the skeleton path, and P the pattern (the path to be deformed). P is a map t --> P(t) = ( x(t), y(t) ). B is a map t --> B(t) = ( a(t), b(t) ). -The first step is to re-parametrize B by its arc length: this is the parametrization in which a point p on B is located by its distance s from start. One obtains a new map s --> U(s) = (a'(s),b'(s)), that still describes the same path B, but where the distance along B from start to -U(s) is s itself. +The first step is to re-parametrize B by its arc length: this is the parametrization in which a point p on B is located +by its distance s from start. One obtains a new map s --> U(s) = (a'(s),b'(s)), that still describes the same path B, +but where the distance along B from start to U(s) is s itself. -We also need a unit normal to the path. This can be obtained by computing a unit tangent vector, and rotate it by 90�. Call this normal vector N(s). +We also need a unit normal to the path. This can be obtained by computing a unit tangent vector, and rotate it by 90�. +Call this normal vector N(s). The basic deformation associated to B is then given by: @@ -39,26 +38,29 @@ The basic deformation associated to B is then given by: (i.e. we go for distance x along the path, and then for distance y along the normal) -Of course this formula needs some minor adaptations (as is it depends on the absolute position of P for instance, so a little translation is needed -first) but I think we can first forget about them. +Of course this formula needs some minor adaptations (as is it depends on the absolute position of P for instance, so a +little translation is needed first) but I think we can first forget about them. */ namespace Inkscape { namespace LivePathEffect { namespace WPAP { - class KnotHolderEntityWidthPatternAlongPath : public LPEKnotHolderEntity { - public: - KnotHolderEntityWidthPatternAlongPath(LPEPatternAlongPath * effect) : LPEKnotHolderEntity(effect) {} - ~KnotHolderEntityWidthPatternAlongPath() override - { - LPEPatternAlongPath *lpe = dynamic_cast (_effect); - lpe->_knot_entity = nullptr; - } - void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; - Geom::Point knot_get() const override; - }; -} // WPAP +class KnotHolderEntityWidthPatternAlongPath : public LPEKnotHolderEntity +{ +public: + KnotHolderEntityWidthPatternAlongPath(LPEPatternAlongPath *effect) + : LPEKnotHolderEntity(effect) + {} + ~KnotHolderEntityWidthPatternAlongPath() override + { + LPEPatternAlongPath *lpe = dynamic_cast(_effect); + lpe->_knot_entity = nullptr; + } + void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; + Geom::Point knot_get() const override; +}; +} // namespace WPAP static const Util::EnumData PAPCopyTypeData[PAPCT_END] = { // clang-format off @@ -70,30 +72,30 @@ static const Util::EnumData PAPCopyTypeData[PAPCT_END] = { }; static const Util::EnumDataConverter PAPCopyTypeConverter(PAPCopyTypeData, PAPCT_END); -LPEPatternAlongPath::LPEPatternAlongPath(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - pattern(_("Pattern source:"), _("Path to put along the skeleton path"), "pattern", &wr, this, "M0,0 L1,0"), - original_height(0.0), - prop_scale(_("_Width:"), _("Width of the pattern"), "prop_scale", &wr, this, 1.0), - copytype(_("Pattern copies:"), _("How many pattern copies to place along the skeleton path"), - "copytype", PAPCopyTypeConverter, &wr, this, PAPCT_SINGLE_STRETCHED), - scale_y_rel(_("Wid_th in units of length"), - _("Scale the width of the pattern in units of its length"), - "scale_y_rel", &wr, this, false), - spacing(_("Spa_cing:"), - // xgettext:no-c-format - _("Space between copies of the pattern. Negative values allowed, but are limited to -90% of pattern width."), - "spacing", &wr, this, 0), - normal_offset(_("No_rmal offset:"), "", "normal_offset", &wr, this, 0), - tang_offset(_("Tan_gential offset:"), "", "tang_offset", &wr, this, 0), - prop_units(_("Offsets in _unit of pattern size"), - _("Spacing, tangential and normal offset are expressed as a ratio of width/height"), - "prop_units", &wr, this, false), - vertical_pattern(_("Pattern is _vertical"), _("Rotate pattern 90 deg before applying"), - "vertical_pattern", &wr, this, false), - hide_knot(_("Hide width knot"), _("Hide width knot"),"hide_knot", &wr, this, false), - fuse_tolerance(_("_Fuse nearby ends:"), _("Fuse ends closer than this number. 0 means don't fuse."), - "fuse_tolerance", &wr, this, 0) +LPEPatternAlongPath::LPEPatternAlongPath(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , pattern(_("Pattern source:"), _("Path to put along the skeleton path"), "pattern", &wr, this, "M0,0 L1,0") + , original_height(0.0) + , prop_scale(_("_Width:"), _("Width of the pattern"), "prop_scale", &wr, this, 1.0) + , copytype(_("Pattern copies:"), _("How many pattern copies to place along the skeleton path"), "copytype", + PAPCopyTypeConverter, &wr, this, PAPCT_SINGLE_STRETCHED) + , scale_y_rel(_("Wid_th in units of length"), _("Scale the width of the pattern in units of its length"), + "scale_y_rel", &wr, this, false) + , spacing( + _("Spa_cing:"), + // xgettext:no-c-format + _("Space between copies of the pattern. Negative values allowed, but are limited to -90% of pattern width."), + "spacing", &wr, this, 0) + , normal_offset(_("No_rmal offset:"), "", "normal_offset", &wr, this, 0) + , tang_offset(_("Tan_gential offset:"), "", "tang_offset", &wr, this, 0) + , prop_units(_("Offsets in _unit of pattern size"), + _("Spacing, tangential and normal offset are expressed as a ratio of width/height"), "prop_units", &wr, + this, false) + , vertical_pattern(_("Pattern is _vertical"), _("Rotate pattern 90 deg before applying"), "vertical_pattern", &wr, + this, false) + , hide_knot(_("Hide width knot"), _("Hide width knot"), "hide_knot", &wr, this, false) + , fuse_tolerance(_("_Fuse nearby ends:"), _("Fuse ends closer than this number. 0 means don't fuse."), + "fuse_tolerance", &wr, this, 0) { registerParameter(&pattern); registerParameter(©type); @@ -110,11 +112,9 @@ LPEPatternAlongPath::LPEPatternAlongPath(LivePathEffectObject *lpeobject) : prop_scale.param_set_increments(0.01, 0.10); _knot_entity = nullptr; _provides_knotholder_entities = true; - } -LPEPatternAlongPath::~LPEPatternAlongPath() -= default; +LPEPatternAlongPath::~LPEPatternAlongPath() = default; void LPEPatternAlongPath::transform_multiply(Geom::Affine const &postmul, bool /*set*/) { @@ -123,8 +123,7 @@ void LPEPatternAlongPath::transform_multiply(Geom::Affine const &postmul, bool / } } -void -LPEPatternAlongPath::doBeforeEffect (SPLPEItem const* lpeitem) +void LPEPatternAlongPath::doBeforeEffect(SPLPEItem const *lpeitem) { // get the pattern bounding box Geom::OptRect bbox = pattern.get_pathvector().boundsFast(); @@ -142,46 +141,48 @@ LPEPatternAlongPath::doBeforeEffect (SPLPEItem const* lpeitem) } } -Geom::Piecewise > -LPEPatternAlongPath::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPEPatternAlongPath::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; // Don't allow empty path parameter: - if ( pattern.get_pathvector().empty() ) { + if (pattern.get_pathvector().empty()) { return pwd2_in; } -/* Much credit should go to jfb and mgsloan of lib2geom development for the code below! */ - Piecewise > output; - std::vector > > pre_output; + /* Much credit should go to jfb and mgsloan of lib2geom development for the code below! */ + Piecewise> output; + std::vector>> pre_output; PAPCopyType type = copytype.get_value(); - D2 > patternd2 = make_cuts_independent(pattern.get_pwd2()); - Piecewise x0 = vertical_pattern.get_value() ? Piecewise(patternd2[1]) : Piecewise(patternd2[0]); - Piecewise y0 = vertical_pattern.get_value() ? Piecewise(patternd2[0]) : Piecewise(patternd2[1]); + D2> patternd2 = make_cuts_independent(pattern.get_pwd2()); + Piecewise x0 = + vertical_pattern.get_value() ? Piecewise(patternd2[1]) : Piecewise(patternd2[0]); + Piecewise y0 = + vertical_pattern.get_value() ? Piecewise(patternd2[0]) : Piecewise(patternd2[1]); OptInterval pattBndsX = bounds_exact(x0); OptInterval pattBndsY = bounds_exact(y0); if (pattBndsX && pattBndsY) { x0 -= pattBndsX->min(); y0 -= pattBndsY->middle(); - double xspace = spacing; + double xspace = spacing; double noffset = normal_offset; double toffset = tang_offset; - if (prop_units.get_value()){ - xspace *= pattBndsX->extent(); + if (prop_units.get_value()) { + xspace *= pattBndsX->extent(); noffset *= pattBndsY->extent(); toffset *= pattBndsX->extent(); } - //Prevent more than 90% overlap... + // Prevent more than 90% overlap... if (xspace < -pattBndsX->extent() * 0.9) { xspace = -pattBndsX->extent() * 0.9; } - //TODO: dynamical update of parameter ranges? - //if (prop_units.get_value()){ + // TODO: dynamical update of parameter ranges? + // if (prop_units.get_value()){ // spacing.param_set_range(-.9, Geom::infinity()); // }else{ // spacing.param_set_range(-pattBndsX.extent()*.9, Geom::infinity()); @@ -189,61 +190,66 @@ LPEPatternAlongPath::doEffect_pwd2 (Geom::Piecewise > con y0 += noffset; - std::vector > > paths_in; + std::vector>> paths_in; paths_in = split_at_discontinuities(pwd2_in); - for (auto path_i : paths_in){ + for (auto path_i : paths_in) { Piecewise x = x0; Piecewise y = y0; - Piecewise > uskeleton = arc_length_parametrization(path_i,2, 0.1); + Piecewise> uskeleton = arc_length_parametrization(path_i, 2, 0.1); uskeleton = remove_short_cuts(uskeleton, 0.01); - Piecewise > n = rot90(derivative(uskeleton)); - if (Geom::are_near(pwd2_in[0].at0(),pwd2_in[pwd2_in.size()-1].at1(), 0.01)) { + Piecewise> n = rot90(derivative(uskeleton)); + if (Geom::are_near(pwd2_in[0].at0(), pwd2_in[pwd2_in.size() - 1].at1(), 0.01)) { n = force_continuity(remove_short_cuts(n, 0.1), 0.01); } else { n = force_continuity(remove_short_cuts(n, 0.1)); - } + } int nbCopies = 0; double scaling = 1; - switch(type) { + switch (type) { case PAPCT_REPEATED: - nbCopies = static_cast(floor((uskeleton.domain().extent() - toffset + xspace)/(pattBndsX->extent()+xspace))); - pattBndsX = Interval(pattBndsX->min(),pattBndsX->max()+xspace); + nbCopies = static_cast( + floor((uskeleton.domain().extent() - toffset + xspace) / (pattBndsX->extent() + xspace))); + pattBndsX = Interval(pattBndsX->min(), pattBndsX->max() + xspace); break; - + case PAPCT_SINGLE: nbCopies = (toffset + pattBndsX->extent() < uskeleton.domain().extent()) ? 1 : 0; break; - + case PAPCT_SINGLE_STRETCHED: nbCopies = 1; - scaling = (uskeleton.domain().extent() - toffset)/pattBndsX->extent(); + scaling = (uskeleton.domain().extent() - toffset) / pattBndsX->extent(); break; - + case PAPCT_REPEATED_STRETCHED: // if uskeleton is closed: - if (are_near(path_i.segs.front().at0(), path_i.segs.back().at1())){ - nbCopies = std::max(1, static_cast(std::floor((uskeleton.domain().extent() - toffset)/(pattBndsX->extent()+xspace)))); - pattBndsX = Interval(pattBndsX->min(),pattBndsX->max()+xspace); - scaling = (uskeleton.domain().extent() - toffset)/(((double)nbCopies)*pattBndsX->extent()); + if (are_near(path_i.segs.front().at0(), path_i.segs.back().at1())) { + nbCopies = std::max(1, static_cast(std::floor((uskeleton.domain().extent() - toffset) / + (pattBndsX->extent() + xspace)))); + pattBndsX = Interval(pattBndsX->min(), pattBndsX->max() + xspace); + scaling = (uskeleton.domain().extent() - toffset) / (((double)nbCopies) * pattBndsX->extent()); // if not closed: no space at the end - }else{ - nbCopies = std::max(1, static_cast(std::floor((uskeleton.domain().extent() - toffset + xspace)/(pattBndsX->extent()+xspace)))); - pattBndsX = Interval(pattBndsX->min(),pattBndsX->max()+xspace); - scaling = (uskeleton.domain().extent() - toffset)/(((double)nbCopies)*pattBndsX->extent() - xspace); + } else { + nbCopies = + std::max(1, static_cast(std::floor((uskeleton.domain().extent() - toffset + xspace) / + (pattBndsX->extent() + xspace)))); + pattBndsX = Interval(pattBndsX->min(), pattBndsX->max() + xspace); + scaling = (uskeleton.domain().extent() - toffset) / + (((double)nbCopies) * pattBndsX->extent() - xspace); } break; - + default: return pwd2_in; }; - - //Ceil to 6 decimals + + // Ceil to 6 decimals scaling = ceil(scaling * 1000000) / 1000000; double pattWidth = pattBndsX->extent() * scaling; - + x *= scaling; - if ( scale_y_rel.get_value() ) { + if (scale_y_rel.get_value()) { y *= prop_scale * scaling; } else { y *= prop_scale; @@ -251,20 +257,22 @@ LPEPatternAlongPath::doEffect_pwd2 (Geom::Piecewise > con x += toffset; double offs = 0; - for (int i=0; i 0){ - Geom::Piecewise > output_piece = compose(uskeleton,x+offs)+y*compose(n,x+offs); - std::vector > > splited_output_piece = split_at_discontinuities(output_piece); - pre_output.insert(pre_output.end(), splited_output_piece.begin(), splited_output_piece.end() ); - }else{ - output.concat(compose(uskeleton,x+offs)+y*compose(n,x+offs)); + for (int i = 0; i < nbCopies; i++) { + if (fuse_tolerance > 0) { + Geom::Piecewise> output_piece = + compose(uskeleton, x + offs) + y * compose(n, x + offs); + std::vector>> splited_output_piece = + split_at_discontinuities(output_piece); + pre_output.insert(pre_output.end(), splited_output_piece.begin(), splited_output_piece.end()); + } else { + output.concat(compose(uskeleton, x + offs) + y * compose(n, x + offs)); } - offs+=pattWidth; + offs += pattWidth; } } - if (fuse_tolerance > 0){ + if (fuse_tolerance > 0) { pre_output = fuse_nearby_ends(pre_output, fuse_tolerance); - for (const auto & i : pre_output){ + for (const auto &i : pre_output) { output.concat(i); } } @@ -274,15 +282,12 @@ LPEPatternAlongPath::doEffect_pwd2 (Geom::Piecewise > con } } -void -LPEPatternAlongPath::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) +void LPEPatternAlongPath::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { hp_vec.push_back(helper_path); } - -void -LPEPatternAlongPath::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) +void LPEPatternAlongPath::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) { _knot_entity = new WPAP::KnotHolderEntityWidthPatternAlongPath(this); _knot_entity->create(nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Change the width"), @@ -296,10 +301,9 @@ LPEPatternAlongPath::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) namespace WPAP { -void -KnotHolderEntityWidthPatternAlongPath::knot_set(Geom::Point const &p, Geom::Point const& /*origin*/, guint state) +void KnotHolderEntityWidthPatternAlongPath::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { - LPEPatternAlongPath *lpe = dynamic_cast (_effect); + LPEPatternAlongPath *lpe = dynamic_cast(_effect); Geom::Point const s = snap_knot_position(p, state); SPShape const *sp_shape = dynamic_cast(SP_LPE_ITEM(item)); @@ -318,22 +322,21 @@ KnotHolderEntityWidthPatternAlongPath::knot_set(Geom::Point const &p, Geom::Poin ray.setAngle(ray.angle() + Geom::rad_from_deg(90)); Geom::Point knot_pos = this->knot->pos * item->i2dt_affine().inverse(); Geom::Coord nearest_to_ray = ray.nearestTime(knot_pos); - if(nearest_to_ray == 0){ - lpe->prop_scale.param_set_value(-Geom::distance(s , ptA)/(lpe->original_height/2.0)); + if (nearest_to_ray == 0) { + lpe->prop_scale.param_set_value(-Geom::distance(s, ptA) / (lpe->original_height / 2.0)); } else { - lpe->prop_scale.param_set_value(Geom::distance(s , ptA)/(lpe->original_height/2.0)); + lpe->prop_scale.param_set_value(Geom::distance(s, ptA) / (lpe->original_height / 2.0)); } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble("/live_effects/pap/width", lpe->prop_scale); } } - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, true); } -Geom::Point -KnotHolderEntityWidthPatternAlongPath::knot_get() const +Geom::Point KnotHolderEntityWidthPatternAlongPath::knot_get() const { - LPEPatternAlongPath *lpe = dynamic_cast (_effect); + LPEPatternAlongPath *lpe = dynamic_cast(_effect); SPShape const *sp_shape = dynamic_cast(SP_LPE_ITEM(item)); if (sp_shape) { auto curve_before = SPCurve::copy(sp_shape->curveForEdit()); @@ -348,7 +351,8 @@ KnotHolderEntityWidthPatternAlongPath::knot_get() const ray.setPoints(ptA, (*cubic)[1]); } ray.setAngle(ray.angle() + Geom::rad_from_deg(90)); - Geom::Point result_point = Geom::Point::polar(ray.angle(), (lpe->original_height/2.0) * lpe->prop_scale) + ptA; + Geom::Point result_point = + Geom::Point::polar(ray.angle(), (lpe->original_height / 2.0) * lpe->prop_scale) + ptA; lpe->helper_path.clear(); if (!lpe->hide_knot) { Geom::Path hp(result_point); diff --git a/src/live_effects/lpe-patternalongpath.h b/src/live_effects/lpe-patternalongpath.h index 690aaa99f3d1121b366d1706078c6eaabe6c6fbd..407ae62e76882c3b3848a93418307e3b8e6ade29 100644 --- a/src/live_effects/lpe-patternalongpath.h +++ b/src/live_effects/lpe-patternalongpath.h @@ -10,10 +10,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/enum.h" #include "live_effects/effect.h" -#include "live_effects/parameter/path.h" #include "live_effects/parameter/bool.h" +#include "live_effects/parameter/enum.h" +#include "live_effects/parameter/path.h" #include "live_effects/parameter/point.h" namespace Inkscape { @@ -23,7 +23,8 @@ namespace WPAP { class KnotHolderEntityWidthPatternAlongPath; } -enum PAPCopyType { +enum PAPCopyType +{ PAPCT_SINGLE = 0, PAPCT_SINGLE_STRETCHED, PAPCT_REPEATED, @@ -31,24 +32,27 @@ enum PAPCopyType { PAPCT_END // This must be last }; -class LPEPatternAlongPath : public Effect { +class LPEPatternAlongPath : public Effect +{ public: LPEPatternAlongPath(LivePathEffectObject *lpeobject); ~LPEPatternAlongPath() override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; void transform_multiply(Geom::Affine const &postmul, bool set) override; - void addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) override; - - void addKnotHolderEntities(KnotHolder * knotholder, SPItem * item) override; + void addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) override; + + void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) override; - PathParam pattern; + PathParam pattern; friend class WPAP::KnotHolderEntityWidthPatternAlongPath; + protected: double original_height; ScalarParam prop_scale; @@ -56,23 +60,23 @@ protected: private: EnumParam copytype; BoolParam scale_y_rel; - ScalarParam spacing; - ScalarParam normal_offset; - ScalarParam tang_offset; - BoolParam prop_units; - BoolParam vertical_pattern; - BoolParam hide_knot; - ScalarParam fuse_tolerance; - KnotHolderEntity * _knot_entity; + ScalarParam spacing; + ScalarParam normal_offset; + ScalarParam tang_offset; + BoolParam prop_units; + BoolParam vertical_pattern; + BoolParam hide_knot; + ScalarParam fuse_tolerance; + KnotHolderEntity *_knot_entity; Geom::PathVector helper_path; void on_pattern_pasted(); - LPEPatternAlongPath(const LPEPatternAlongPath&); - LPEPatternAlongPath& operator=(const LPEPatternAlongPath&); + LPEPatternAlongPath(const LPEPatternAlongPath &); + LPEPatternAlongPath &operator=(const LPEPatternAlongPath &); }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-perp_bisector.cpp b/src/live_effects/lpe-perp_bisector.cpp index b77b882cf4ace756fbe0cbaf42a59ecfb389b9c0..3b291ff42b86a4bf8a5423335a877287d8470fe3 100644 --- a/src/live_effects/lpe-perp_bisector.cpp +++ b/src/live_effects/lpe-perp_bisector.cpp @@ -13,13 +13,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "live_effects/lpe-perp_bisector.h" + #include "display/curve.h" +#include "knotholder.h" #include "line-geometry.h" - #include "object/sp-path.h" -#include "knotholder.h" - // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -27,42 +26,49 @@ namespace Inkscape { namespace LivePathEffect { namespace PB { -class KnotHolderEntityEnd : public LPEKnotHolderEntity { +class KnotHolderEntityEnd : public LPEKnotHolderEntity +{ public: - KnotHolderEntityEnd(LPEPerpBisector *effect) : LPEKnotHolderEntity(effect) {}; + KnotHolderEntityEnd(LPEPerpBisector *effect) + : LPEKnotHolderEntity(effect){}; void bisector_end_set(Geom::Point const &p, guint state, bool left = true); }; -class KnotHolderEntityLeftEnd : public KnotHolderEntityEnd { +class KnotHolderEntityLeftEnd : public KnotHolderEntityEnd +{ public: - KnotHolderEntityLeftEnd(LPEPerpBisector *effect) : KnotHolderEntityEnd(effect) {}; + KnotHolderEntityLeftEnd(LPEPerpBisector *effect) + : KnotHolderEntityEnd(effect){}; void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; }; -class KnotHolderEntityRightEnd : public KnotHolderEntityEnd { +class KnotHolderEntityRightEnd : public KnotHolderEntityEnd +{ public: - KnotHolderEntityRightEnd(LPEPerpBisector *effect) : KnotHolderEntityEnd(effect) {}; + KnotHolderEntityRightEnd(LPEPerpBisector *effect) + : KnotHolderEntityEnd(effect){}; void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; }; -Geom::Point -KnotHolderEntityLeftEnd::knot_get() const { - LPEPerpBisector const* lpe = dynamic_cast(_effect); +Geom::Point KnotHolderEntityLeftEnd::knot_get() const +{ + LPEPerpBisector const *lpe = dynamic_cast(_effect); return Geom::Point(lpe->C); } -Geom::Point -KnotHolderEntityRightEnd::knot_get() const { - LPEPerpBisector const* lpe = dynamic_cast(_effect); +Geom::Point KnotHolderEntityRightEnd::knot_get() const +{ + LPEPerpBisector const *lpe = dynamic_cast(_effect); return Geom::Point(lpe->D); } -void -KnotHolderEntityEnd::bisector_end_set(Geom::Point const &p, guint state, bool left) { +void KnotHolderEntityEnd::bisector_end_set(Geom::Point const &p, guint state, bool left) +{ LPEPerpBisector *lpe = dynamic_cast(_effect); - if (!lpe) return; + if (!lpe) + return; Geom::Point const s = snap_knot_position(p, state); @@ -76,26 +82,31 @@ KnotHolderEntityEnd::bisector_end_set(Geom::Point const &p, guint state, bool le } // FIXME: this should not directly ask for updating the item. It should write to SVG, which triggers updating. - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), true, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), true, true); } -void -KnotHolderEntityLeftEnd::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) { +void KnotHolderEntityLeftEnd::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) +{ bisector_end_set(p, state); } -void -KnotHolderEntityRightEnd::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) { +void KnotHolderEntityRightEnd::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) +{ bisector_end_set(p, state, false); } -} //namescape PB - -LPEPerpBisector::LPEPerpBisector(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - length_left(_("Length left:"), _("Specifies the left end of the bisector"), "length-left", &wr, this, 200), - length_right(_("Length right:"), _("Specifies the right end of the bisector"), "length-right", &wr, this, 200), - A(0,0), B(0,0), M(0,0), C(0,0), D(0,0), perp_dir(0,0) +} // namespace PB + +LPEPerpBisector::LPEPerpBisector(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , length_left(_("Length left:"), _("Specifies the left end of the bisector"), "length-left", &wr, this, 200) + , length_right(_("Length right:"), _("Specifies the right end of the bisector"), "length-right", &wr, this, 200) + , A(0, 0) + , B(0, 0) + , M(0, 0) + , C(0, 0) + , D(0, 0) + , perp_dir(0, 0) { show_orig_path = true; _provides_knotholder_entities = true; @@ -105,11 +116,9 @@ LPEPerpBisector::LPEPerpBisector(LivePathEffectObject *lpeobject) : registerParameter(&length_right); } -LPEPerpBisector::~LPEPerpBisector() -= default; +LPEPerpBisector::~LPEPerpBisector() = default; -void -LPEPerpBisector::doOnApply (SPLPEItem const*/*lpeitem*/) +void LPEPerpBisector::doOnApply(SPLPEItem const * /*lpeitem*/) { /* make the path a straight line */ /** @@ -127,45 +136,42 @@ LPEPerpBisector::doOnApply (SPLPEItem const*/*lpeitem*/) **/ } - -Geom::Piecewise > -LPEPerpBisector::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPEPerpBisector::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; - Piecewise > output; + Piecewise> output; A = pwd2_in.firstValue(); B = pwd2_in.lastValue(); - M = (A + B)/2; + M = (A + B) / 2; perp_dir = unit_vector((B - A).ccw()); C = M + perp_dir * length_left; D = M - perp_dir * length_right; - output = Piecewise >(D2(SBasis(C[X], D[X]), SBasis(C[Y], D[Y]))); + output = Piecewise>(D2(SBasis(C[X], D[X]), SBasis(C[Y], D[Y]))); return output; } -void -LPEPerpBisector::addKnotHolderEntities(KnotHolder *knotholder, SPDesktop *desktop, SPItem *item) { - { - KnotHolderEntity *e = new PB::KnotHolderEntityLeftEnd(this); +void LPEPerpBisector::addKnotHolderEntities(KnotHolder *knotholder, SPDesktop *desktop, + SPItem *item){{KnotHolderEntity *e = new PB::KnotHolderEntityLeftEnd(this); e->create(desktop, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the \"left\" end of the bisector")); knotholder->add(e); - } - { - KnotHolderEntity *e = new PB::KnotHolderEntityRightEnd(this); - e->create(desktop, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the \"right\" end of the bisector")); - knotholder->add(e); - } -}; +} // namespace LivePathEffect +{ + KnotHolderEntity *e = new PB::KnotHolderEntityRightEnd(this); + e->create(desktop, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the \"right\" end of the bisector")); + knotholder->add(e); +} +}; // namespace Inkscape /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-perp_bisector.h b/src/live_effects/lpe-perp_bisector.h index 4d09f88604e329a76db223bd30ddd519f7dc099f..229f8a4d42f160611432d06f0e296aa651058b7b 100644 --- a/src/live_effects/lpe-perp_bisector.h +++ b/src/live_effects/lpe-perp_bisector.h @@ -24,24 +24,25 @@ namespace Inkscape { namespace LivePathEffect { namespace PB { - // we need a separate namespace to avoid clashes with LPETangentToCurve - class KnotHolderEntityEnd; - class KnotHolderEntityLeftEnd; - class KnotHolderEntityRightEnd; - void bisector_end_set(SPItem *item, Geom::Point const &p, guint state, bool left = true); -} +// we need a separate namespace to avoid clashes with LPETangentToCurve +class KnotHolderEntityEnd; +class KnotHolderEntityLeftEnd; +class KnotHolderEntityRightEnd; +void bisector_end_set(SPItem *item, Geom::Point const &p, guint state, bool left = true); +} // namespace PB -class LPEPerpBisector : public Effect { +class LPEPerpBisector : public Effect +{ public: LPEPerpBisector(LivePathEffectObject *lpeobject); ~LPEPerpBisector() override; - virtual EffectType effectType () { return PERP_BISECTOR; } + virtual EffectType effectType() { return PERP_BISECTOR; } - void doOnApply (SPLPEItem const* lpeitem) override; + void doOnApply(SPLPEItem const *lpeitem) override; - Geom::Piecewise > - doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; /* the knotholder entity functions must be declared friends */ friend class PB::KnotHolderEntityEnd; @@ -61,11 +62,11 @@ private: Geom::Point D; // right end of bisector Geom::Point perp_dir; - LPEPerpBisector(const LPEPerpBisector&) = delete; - LPEPerpBisector& operator=(const LPEPerpBisector&) = delete; + LPEPerpBisector(const LPEPerpBisector &) = delete; + LPEPerpBisector &operator=(const LPEPerpBisector &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-perspective-envelope.cpp b/src/live_effects/lpe-perspective-envelope.cpp index 4167c691030be9198917a88b2428a36df317368a..02077860ebe5e0e901bcac8ae44fb2562e96ad00 100644 --- a/src/live_effects/lpe-perspective-envelope.cpp +++ b/src/live_effects/lpe-perspective-envelope.cpp @@ -15,11 +15,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "live_effects/lpe-perspective-envelope.h" -#include "helper/geom.h" -#include "display/curve.h" + #include +#include + +#include "display/curve.h" +#include "helper/geom.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -29,28 +31,37 @@ using namespace Geom; namespace Inkscape { namespace LivePathEffect { -enum DeformationType { +enum DeformationType +{ DEFORMATION_PERSPECTIVE, DEFORMATION_ENVELOPE }; static const Util::EnumData DeformationTypeData[] = { - {DEFORMATION_PERSPECTIVE , N_("Perspective"), "perspective"}, - {DEFORMATION_ENVELOPE , N_("Envelope deformation"), "envelope_deformation"} -}; - -static const Util::EnumDataConverter DeformationTypeConverter(DeformationTypeData, sizeof(DeformationTypeData)/sizeof(*DeformationTypeData)); - -LPEPerspectiveEnvelope::LPEPerspectiveEnvelope(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - horizontal_mirror(_("Mirror movements in horizontal"), _("Mirror movements in horizontal"), "horizontal_mirror", &wr, this, false), - vertical_mirror(_("Mirror movements in vertical"), _("Mirror movements in vertical"), "vertical_mirror", &wr, this, false), - overflow_perspective(_("Overflow perspective"), _("Overflow perspective"), "overflow_perspective", &wr, this, false), - deform_type(_("Type"), _("Select the type of deformation"), "deform_type", DeformationTypeConverter, &wr, this, DEFORMATION_PERSPECTIVE), - up_left_point(_("Top Left"), _("Top Left - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "up_left_point", &wr, this), - up_right_point(_("Top Right"), _("Top Right - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "up_right_point", &wr, this), - down_left_point(_("Down Left"), _("Down Left - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "down_left_point", &wr, this), - down_right_point(_("Down Right"), _("Down Right - Ctrl+Alt+Click: reset, Ctrl: move along axes"), "down_right_point", &wr, this) + {DEFORMATION_PERSPECTIVE, N_("Perspective"), "perspective"}, + {DEFORMATION_ENVELOPE, N_("Envelope deformation"), "envelope_deformation"}}; + +static const Util::EnumDataConverter + DeformationTypeConverter(DeformationTypeData, sizeof(DeformationTypeData) / sizeof(*DeformationTypeData)); + +LPEPerspectiveEnvelope::LPEPerspectiveEnvelope(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , horizontal_mirror(_("Mirror movements in horizontal"), _("Mirror movements in horizontal"), "horizontal_mirror", + &wr, this, false) + , vertical_mirror(_("Mirror movements in vertical"), _("Mirror movements in vertical"), "vertical_mirror", &wr, + this, false) + , overflow_perspective(_("Overflow perspective"), _("Overflow perspective"), "overflow_perspective", &wr, this, + false) + , deform_type(_("Type"), _("Select the type of deformation"), "deform_type", DeformationTypeConverter, &wr, this, + DEFORMATION_PERSPECTIVE) + , up_left_point(_("Top Left"), _("Top Left - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "up_left_point", &wr, this) + , up_right_point(_("Top Right"), _("Top Right - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "up_right_point", &wr, this) + , down_left_point(_("Down Left"), _("Down Left - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "down_left_point", &wr, this) + , down_right_point(_("Down Right"), _("Down Right - Ctrl+Alt+Click: reset, Ctrl: move along axes"), + "down_right_point", &wr, this) { // register all your parameters here, so Inkscape knows which parameters this effect has: registerParameter(&deform_type); @@ -64,8 +75,7 @@ LPEPerspectiveEnvelope::LPEPerspectiveEnvelope(LivePathEffectObject *lpeobject) apply_to_clippath_and_mask = true; } -LPEPerspectiveEnvelope::~LPEPerspectiveEnvelope() -= default; +LPEPerspectiveEnvelope::~LPEPerspectiveEnvelope() = default; void LPEPerspectiveEnvelope::transform_multiply(Geom::Affine const &postmul, bool /*set*/) { @@ -100,7 +110,7 @@ bool pointInTriangle(Geom::Point const &p, std::vector points) void LPEPerspectiveEnvelope::doEffect(SPCurve *curve) { double projmatrix[3][3]; - if(deform_type == DEFORMATION_PERSPECTIVE) { + if (deform_type == DEFORMATION_PERSPECTIVE) { using Geom::X; using Geom::Y; std::vector source_handles(4); @@ -111,40 +121,40 @@ void LPEPerspectiveEnvelope::doEffect(SPCurve *curve) double solmatrix[8][8] = {{0}}; double free_term[8] = {0}; double gslSolmatrix[64]; - for(unsigned int i = 0; i < 4; ++i) { + for (unsigned int i = 0; i < 4; ++i) { solmatrix[i][0] = source_handles[i][X]; solmatrix[i][1] = source_handles[i][Y]; solmatrix[i][2] = 1; solmatrix[i][6] = -handles[i][X] * source_handles[i][X]; solmatrix[i][7] = -handles[i][X] * source_handles[i][Y]; - solmatrix[i+4][3] = source_handles[i][X]; - solmatrix[i+4][4] = source_handles[i][Y]; - solmatrix[i+4][5] = 1; - solmatrix[i+4][6] = -handles[i][Y] * source_handles[i][X]; - solmatrix[i+4][7] = -handles[i][Y] * source_handles[i][Y]; + solmatrix[i + 4][3] = source_handles[i][X]; + solmatrix[i + 4][4] = source_handles[i][Y]; + solmatrix[i + 4][5] = 1; + solmatrix[i + 4][6] = -handles[i][Y] * source_handles[i][X]; + solmatrix[i + 4][7] = -handles[i][Y] * source_handles[i][Y]; free_term[i] = handles[i][X]; - free_term[i+4] = handles[i][Y]; + free_term[i + 4] = handles[i][Y]; } int h = 0; - for(auto & i : solmatrix) { - for(double j : i) { + for (auto &i : solmatrix) { + for (double j : i) { gslSolmatrix[h] = j; h++; } } - //this is get by this page: - //http://www.gnu.org/software/gsl/manual/html_node/Linear-Algebra-Examples.html#Linear-Algebra-Examples - gsl_matrix_view m = gsl_matrix_view_array (gslSolmatrix, 8, 8); - gsl_vector_view b = gsl_vector_view_array (free_term, 8); - gsl_vector *x = gsl_vector_alloc (8); + // this is get by this page: + // http://www.gnu.org/software/gsl/manual/html_node/Linear-Algebra-Examples.html#Linear-Algebra-Examples + gsl_matrix_view m = gsl_matrix_view_array(gslSolmatrix, 8, 8); + gsl_vector_view b = gsl_vector_view_array(free_term, 8); + gsl_vector *x = gsl_vector_alloc(8); int s; - gsl_permutation * p = gsl_permutation_alloc (8); - gsl_linalg_LU_decomp (&m.matrix, p, &s); - gsl_linalg_LU_solve (&m.matrix, p, &b.vector, x); + gsl_permutation *p = gsl_permutation_alloc(8); + gsl_linalg_LU_decomp(&m.matrix, p, &s); + gsl_linalg_LU_solve(&m.matrix, p, &b.vector, x); h = 0; - for(auto & i : projmatrix) { - for(double & j : i) { - if(h==8) { + for (auto &i : projmatrix) { + for (double &j : i) { + if (h == 8) { projmatrix[2][2] = 1.0; continue; } @@ -152,8 +162,8 @@ void LPEPerspectiveEnvelope::doEffect(SPCurve *curve) h++; } } - gsl_permutation_free (p); - gsl_vector_free (x); + gsl_permutation_free(p); + gsl_vector_free(x); } Geom::PathVector const original_pathv = pathv_to_linear_and_cubic_beziers(curve->get_pathvector()); curve->reset(); @@ -161,11 +171,11 @@ void LPEPerspectiveEnvelope::doEffect(SPCurve *curve) Geom::Point point_at1(0, 0); Geom::Point point_at2(0, 0); Geom::Point point_at3(0, 0); - for (const auto & path_it : original_pathv) { - //Si está vacío... + for (const auto &path_it : original_pathv) { + // Si está vacío... if (path_it.empty()) continue; - //Itreadores + // Itreadores auto nCurve = std::make_unique(); Geom::Path::const_iterator curve_it1 = path_it.begin(); Geom::Path::const_iterator curve_endit = path_it.end_default(); @@ -176,7 +186,7 @@ void LPEPerspectiveEnvelope::doEffect(SPCurve *curve) curve_endit = path_it.end_open(); } } - if(deform_type == DEFORMATION_PERSPECTIVE) { + if (deform_type == DEFORMATION_PERSPECTIVE) { nCurve->moveto(projectPoint(curve_it1->initialPoint(), projmatrix)); } else { nCurve->moveto(projectPoint(curve_it1->initialPoint())); @@ -191,7 +201,7 @@ void LPEPerspectiveEnvelope::doEffect(SPCurve *curve) point_at2 = curve_it1->finalPoint(); } point_at3 = curve_it1->finalPoint(); - if(deform_type == DEFORMATION_PERSPECTIVE) { + if (deform_type == DEFORMATION_PERSPECTIVE) { point_at1 = projectPoint(point_at1, projmatrix); point_at2 = projectPoint(point_at2, projmatrix); point_at3 = projectPoint(point_at3, projmatrix); @@ -207,7 +217,7 @@ void LPEPerspectiveEnvelope::doEffect(SPCurve *curve) } ++curve_it1; } - //y cerramos la curva + // y cerramos la curva if (path_it.closed()) { nCurve->move_endpoints(point_at3, point_at3); nCurve->closepath_current(); @@ -216,8 +226,7 @@ void LPEPerspectiveEnvelope::doEffect(SPCurve *curve) } } -Geom::Point -LPEPerspectiveEnvelope::projectPoint(Geom::Point p) +Geom::Point LPEPerspectiveEnvelope::projectPoint(Geom::Point p) { double width = boundingbox_X.extent(); double height = boundingbox_Y.extent(); @@ -227,73 +236,71 @@ LPEPerspectiveEnvelope::projectPoint(Geom::Point p) Geom::Coord y_ratio = delta_y / height; Geom::Line horiz; Geom::Line vert; - vert.setPoints (pointAtRatio(y_ratio,down_left_point,up_left_point),pointAtRatio(y_ratio,down_right_point,up_right_point)); - horiz.setPoints (pointAtRatio(x_ratio,down_left_point,down_right_point),pointAtRatio(x_ratio,up_left_point,up_right_point)); + vert.setPoints(pointAtRatio(y_ratio, down_left_point, up_left_point), + pointAtRatio(y_ratio, down_right_point, up_right_point)); + horiz.setPoints(pointAtRatio(x_ratio, down_left_point, down_right_point), + pointAtRatio(x_ratio, up_left_point, up_right_point)); - OptCrossing crossPoint = intersection(horiz,vert); - if(crossPoint) { + OptCrossing crossPoint = intersection(horiz, vert); + if (crossPoint) { return horiz.pointAt(Geom::Coord(crossPoint->ta)); } else { return p; } } -Geom::Point -LPEPerspectiveEnvelope::projectPoint(Geom::Point p, double m[][3]) +Geom::Point LPEPerspectiveEnvelope::projectPoint(Geom::Point p, double m[][3]) { Geom::Coord x = p[0]; Geom::Coord y = p[1]; - return Geom::Point( - Geom::Coord((x*m[0][0] + y*m[0][1] + m[0][2])/(x*m[2][0]+y*m[2][1]+m[2][2])), - Geom::Coord((x*m[1][0] + y*m[1][1] + m[1][2])/(x*m[2][0]+y*m[2][1]+m[2][2]))); + return Geom::Point(Geom::Coord((x * m[0][0] + y * m[0][1] + m[0][2]) / (x * m[2][0] + y * m[2][1] + m[2][2])), + Geom::Coord((x * m[1][0] + y * m[1][1] + m[1][2]) / (x * m[2][0] + y * m[2][1] + m[2][2]))); } -Geom::Point -LPEPerspectiveEnvelope::pointAtRatio(Geom::Coord ratio,Geom::Point A, Geom::Point B) +Geom::Point LPEPerspectiveEnvelope::pointAtRatio(Geom::Coord ratio, Geom::Point A, Geom::Point B) { - Geom::Coord x = A[X] + (ratio * (B[X]-A[X])); - Geom::Coord y = A[Y]+ (ratio * (B[Y]-A[Y])); + Geom::Coord x = A[X] + (ratio * (B[X] - A[X])); + Geom::Coord y = A[Y] + (ratio * (B[Y] - A[Y])); return Point(x, y); } - -Gtk::Widget * -LPEPerspectiveEnvelope::newWidget() +Gtk::Widget *LPEPerspectiveEnvelope::newWidget() { // use manage here, because after deletion of Effect object, others might still be pointing to this widget. - Gtk::VBox * vbox = Gtk::manage( new Gtk::VBox(Effect::newWidget()) ); + Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox(Effect::newWidget())); vbox->set_border_width(5); vbox->set_homogeneous(false); vbox->set_spacing(6); std::vector::iterator it = param_vector.begin(); - Gtk::HBox * hbox_up_handles = Gtk::manage(new Gtk::HBox(false,0)); - Gtk::HBox * hbox_down_handles = Gtk::manage(new Gtk::HBox(false,0)); + Gtk::HBox *hbox_up_handles = Gtk::manage(new Gtk::HBox(false, 0)); + Gtk::HBox *hbox_down_handles = Gtk::manage(new Gtk::HBox(false, 0)); while (it != param_vector.end()) { if ((*it)->widget_is_visible) { - Parameter * param = *it; - Gtk::Widget * widg = dynamic_cast(param->param_newWidget()); - if (param->param_key == "up_left_point" || - param->param_key == "up_right_point" || - param->param_key == "down_left_point" || - param->param_key == "down_right_point") { - Gtk::HBox * point_hbox = dynamic_cast(widg); - std::vector< Gtk::Widget* > child_list = point_hbox->get_children(); - Gtk::HBox * point_hboxHBox = dynamic_cast(child_list[0]); - std::vector< Gtk::Widget* > child_list2 = point_hboxHBox->get_children(); + Parameter *param = *it; + Gtk::Widget *widg = dynamic_cast(param->param_newWidget()); + if (param->param_key == "up_left_point" || param->param_key == "up_right_point" || + param->param_key == "down_left_point" || param->param_key == "down_right_point") { + Gtk::HBox *point_hbox = dynamic_cast(widg); + std::vector child_list = point_hbox->get_children(); + Gtk::HBox *point_hboxHBox = dynamic_cast(child_list[0]); + std::vector child_list2 = point_hboxHBox->get_children(); point_hboxHBox->remove(child_list2[0][0]); - Glib::ustring * tip = param->param_getTooltip(); + Glib::ustring *tip = param->param_getTooltip(); if (widg) { - if(param->param_key == "up_left_point") { - Gtk::Label* handles = Gtk::manage(new Gtk::Label(Glib::ustring(_("Handles:")),Gtk::ALIGN_START)); + if (param->param_key == "up_left_point") { + Gtk::Label *handles = + Gtk::manage(new Gtk::Label(Glib::ustring(_("Handles:")), Gtk::ALIGN_START)); vbox->pack_start(*handles, false, false, 2); hbox_up_handles->pack_start(*widg, true, true, 2); - hbox_up_handles->pack_start(*Gtk::manage(new Gtk::Separator(Gtk::ORIENTATION_VERTICAL)), Gtk::PACK_EXPAND_WIDGET); - } else if(param->param_key == "up_right_point") { + hbox_up_handles->pack_start(*Gtk::manage(new Gtk::Separator(Gtk::ORIENTATION_VERTICAL)), + Gtk::PACK_EXPAND_WIDGET); + } else if (param->param_key == "up_right_point") { hbox_up_handles->pack_start(*widg, true, true, 2); - } else if(param->param_key == "down_left_point") { + } else if (param->param_key == "down_left_point") { hbox_down_handles->pack_start(*widg, true, true, 2); - hbox_down_handles->pack_start(*Gtk::manage(new Gtk::Separator(Gtk::ORIENTATION_VERTICAL)), Gtk::PACK_EXPAND_WIDGET); + hbox_down_handles->pack_start(*Gtk::manage(new Gtk::Separator(Gtk::ORIENTATION_VERTICAL)), + Gtk::PACK_EXPAND_WIDGET); } else { hbox_down_handles->pack_start(*widg, true, true, 2); } @@ -305,7 +312,7 @@ LPEPerspectiveEnvelope::newWidget() } } } else { - Glib::ustring * tip = param->param_getTooltip(); + Glib::ustring *tip = param->param_getTooltip(); if (widg) { vbox->pack_start(*widg, true, true, 2); if (tip) { @@ -320,38 +327,37 @@ LPEPerspectiveEnvelope::newWidget() ++it; } - vbox->pack_start(*hbox_up_handles,true, true, 2); - Gtk::HBox * hbox_middle = Gtk::manage(new Gtk::HBox(true,2)); + vbox->pack_start(*hbox_up_handles, true, true, 2); + Gtk::HBox *hbox_middle = Gtk::manage(new Gtk::HBox(true, 2)); hbox_middle->pack_start(*Gtk::manage(new Gtk::Separator(Gtk::ORIENTATION_HORIZONTAL)), Gtk::PACK_EXPAND_WIDGET); hbox_middle->pack_start(*Gtk::manage(new Gtk::Separator(Gtk::ORIENTATION_HORIZONTAL)), Gtk::PACK_EXPAND_WIDGET); vbox->pack_start(*hbox_middle, false, true, 2); vbox->pack_start(*hbox_down_handles, true, true, 2); - Gtk::HBox * hbox = Gtk::manage(new Gtk::HBox(false,0)); - Gtk::Button* reset_button = Gtk::manage(new Gtk::Button(_("_Clear"), true)); + Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox(false, 0)); + Gtk::Button *reset_button = Gtk::manage(new Gtk::Button(_("_Clear"), true)); reset_button->set_image_from_icon_name("edit-clear"); - reset_button->signal_clicked().connect(sigc::mem_fun (*this,&LPEPerspectiveEnvelope::resetGrid)); - reset_button->set_size_request(140,30); - vbox->pack_start(*hbox, true,true,2); - hbox->pack_start(*reset_button, false, false,2); - if(Gtk::Widget* widg = defaultParamSet()) { + reset_button->signal_clicked().connect(sigc::mem_fun(*this, &LPEPerspectiveEnvelope::resetGrid)); + reset_button->set_size_request(140, 30); + vbox->pack_start(*hbox, true, true, 2); + hbox->pack_start(*reset_button, false, false, 2); + if (Gtk::Widget *widg = defaultParamSet()) { vbox->pack_start(*widg, true, true, 2); } return dynamic_cast(vbox); } -void -LPEPerspectiveEnvelope::vertical(PointParam ¶m_one, PointParam ¶m_two, Geom::Line vert) +void LPEPerspectiveEnvelope::vertical(PointParam ¶m_one, PointParam ¶m_two, Geom::Line vert) { Geom::Point A = param_one; Geom::Point B = param_two; - double Y = (A[Geom::Y] + B[Geom::Y])/2; + double Y = (A[Geom::Y] + B[Geom::Y]) / 2; A[Geom::Y] = Y; B[Geom::Y] = Y; Geom::Point nearest = vert.pointAt(vert.nearestTime(A)); - double distance_one = Geom::distance(A,nearest); - double distance_two = Geom::distance(B,nearest); - double distance_middle = (distance_one + distance_two)/2; - if(A[Geom::X] > B[Geom::X]) { + double distance_one = Geom::distance(A, nearest); + double distance_two = Geom::distance(B, nearest); + double distance_middle = (distance_one + distance_two) / 2; + if (A[Geom::X] > B[Geom::X]) { distance_middle *= -1; } A[Geom::X] = nearest[Geom::X] - distance_middle; @@ -360,19 +366,18 @@ LPEPerspectiveEnvelope::vertical(PointParam ¶m_one, PointParam ¶m_two, G param_two.param_setValue(B); } -void -LPEPerspectiveEnvelope::horizontal(PointParam ¶m_one, PointParam ¶m_two, Geom::Line horiz) +void LPEPerspectiveEnvelope::horizontal(PointParam ¶m_one, PointParam ¶m_two, Geom::Line horiz) { Geom::Point A = param_one; Geom::Point B = param_two; - double X = (A[Geom::X] + B[Geom::X])/2; + double X = (A[Geom::X] + B[Geom::X]) / 2; A[Geom::X] = X; B[Geom::X] = X; Geom::Point nearest = horiz.pointAt(horiz.nearestTime(A)); - double distance_one = Geom::distance(A,nearest); - double distance_two = Geom::distance(B,nearest); - double distance_middle = (distance_one + distance_two)/2; - if(A[Geom::Y] > B[Geom::Y]) { + double distance_one = Geom::distance(A, nearest); + double distance_two = Geom::distance(B, nearest); + double distance_middle = (distance_one + distance_two) / 2; + if (A[Geom::Y] > B[Geom::Y]) { distance_middle *= -1; } A[Geom::Y] = nearest[Geom::Y] - distance_middle; @@ -381,19 +386,20 @@ LPEPerspectiveEnvelope::horizontal(PointParam ¶m_one, PointParam ¶m_two, param_two.param_setValue(B); } -void -LPEPerspectiveEnvelope::doBeforeEffect (SPLPEItem const* lpeitem) +void LPEPerspectiveEnvelope::doBeforeEffect(SPLPEItem const *lpeitem) { original_bbox(lpeitem, false, true); - Geom::Line vert(Geom::Point(boundingbox_X.middle(),boundingbox_Y.max()), Geom::Point(boundingbox_X.middle(), boundingbox_Y.min())); - Geom::Line horiz(Geom::Point(boundingbox_X.min(),boundingbox_Y.middle()), Geom::Point(boundingbox_X.max(), boundingbox_Y.middle())); - if(vertical_mirror) { - vertical(up_left_point, up_right_point,vert); - vertical(down_left_point, down_right_point,vert); + Geom::Line vert(Geom::Point(boundingbox_X.middle(), boundingbox_Y.max()), + Geom::Point(boundingbox_X.middle(), boundingbox_Y.min())); + Geom::Line horiz(Geom::Point(boundingbox_X.min(), boundingbox_Y.middle()), + Geom::Point(boundingbox_X.max(), boundingbox_Y.middle())); + if (vertical_mirror) { + vertical(up_left_point, up_right_point, vert); + vertical(down_left_point, down_right_point, vert); } - if(horizontal_mirror) { - horizontal(up_left_point, down_left_point,horiz); - horizontal(up_right_point, down_right_point,horiz); + if (horizontal_mirror) { + horizontal(up_left_point, down_left_point, horiz); + horizontal(up_right_point, down_right_point, horiz); } setDefaults(); if (are_near(up_left_point, up_right_point) && are_near(up_right_point, down_left_point) && @@ -508,8 +514,7 @@ LPEPerspectiveEnvelope::doBeforeEffect (SPLPEItem const* lpeitem) } } -void -LPEPerspectiveEnvelope::setDefaults() +void LPEPerspectiveEnvelope::setDefaults() { Geom::Point up_left(boundingbox_X.min(), boundingbox_Y.min()); Geom::Point up_right(boundingbox_X.max(), boundingbox_Y.min()); @@ -522,8 +527,7 @@ LPEPerspectiveEnvelope::setDefaults() down_left_point.param_update_default(down_left); } -void -LPEPerspectiveEnvelope::resetGrid() +void LPEPerspectiveEnvelope::resetGrid() { up_left_point.param_set_default(); up_right_point.param_set_default(); @@ -531,8 +535,7 @@ LPEPerspectiveEnvelope::resetGrid() down_left_point.param_set_default(); } -void -LPEPerspectiveEnvelope::resetDefaults(SPItem const* item) +void LPEPerspectiveEnvelope::resetDefaults(SPItem const *item) { Effect::resetDefaults(item); original_bbox(SP_LPE_ITEM(item), false, true); @@ -540,8 +543,7 @@ LPEPerspectiveEnvelope::resetDefaults(SPItem const* item) resetGrid(); } -void -LPEPerspectiveEnvelope::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) +void LPEPerspectiveEnvelope::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { hp_vec.clear(); @@ -554,15 +556,11 @@ LPEPerspectiveEnvelope::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::v hp_vec.push_back(c->get_pathvector()); } - /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ - - - /* Local Variables: mode:c++ diff --git a/src/live_effects/lpe-perspective-envelope.h b/src/live_effects/lpe-perspective-envelope.h index 7aa32ecc1a2756fc6fd0fc5a7f19cfc5dee240e2..5c1e7e36dd86cd448edd3fbd7e02c402313b5241 100644 --- a/src/live_effects/lpe-perspective-envelope.h +++ b/src/live_effects/lpe-perspective-envelope.h @@ -18,17 +18,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/enum.h" #include "live_effects/effect.h" -#include "live_effects/parameter/point.h" #include "live_effects/lpegroupbbox.h" +#include "live_effects/parameter/enum.h" +#include "live_effects/parameter/point.h" namespace Inkscape { namespace LivePathEffect { -class LPEPerspectiveEnvelope : public Effect, GroupBBoxEffect { +class LPEPerspectiveEnvelope + : public Effect + , GroupBBoxEffect +{ public: - LPEPerspectiveEnvelope(LivePathEffectObject *lpeobject); ~LPEPerspectiveEnvelope() override; @@ -39,28 +41,28 @@ public: void transform_multiply(Geom::Affine const &postmul, bool set) override; - virtual Geom::Point projectPoint(Geom::Point p, double m[][3]); + virtual Geom::Point projectPoint(Geom::Point p, double m[][3]); - virtual Geom::Point pointAtRatio(Geom::Coord ratio,Geom::Point A, Geom::Point B); + virtual Geom::Point pointAtRatio(Geom::Coord ratio, Geom::Point A, Geom::Point B); - void resetDefaults(SPItem const* item) override; + void resetDefaults(SPItem const *item) override; - virtual void vertical(PointParam ¶mA,PointParam ¶mB, Geom::Line vert); + virtual void vertical(PointParam ¶mA, PointParam ¶mB, Geom::Line vert); - virtual void horizontal(PointParam ¶mA,PointParam ¶mB,Geom::Line horiz); + virtual void horizontal(PointParam ¶mA, PointParam ¶mB, Geom::Line horiz); - void doBeforeEffect(SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; - Gtk::Widget * newWidget() override; + Gtk::Widget *newWidget() override; virtual void setDefaults(); virtual void resetGrid(); protected: - void addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) override; -private: + void addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) override; +private: BoolParam horizontal_mirror; BoolParam vertical_mirror; BoolParam overflow_perspective; @@ -70,11 +72,11 @@ private: PointParam down_left_point; PointParam down_right_point; std::vector handles; - LPEPerspectiveEnvelope(const LPEPerspectiveEnvelope&) = delete; - LPEPerspectiveEnvelope& operator=(const LPEPerspectiveEnvelope&) = delete; + LPEPerspectiveEnvelope(const LPEPerspectiveEnvelope &) = delete; + LPEPerspectiveEnvelope &operator=(const LPEPerspectiveEnvelope &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-powerclip.cpp b/src/live_effects/lpe-powerclip.cpp index abc875e2cbed34acf6c19b38f90cee7cb1dc84a7..da89cdda085091e0da4fbc41613a656c86b33195 100644 --- a/src/live_effects/lpe-powerclip.cpp +++ b/src/live_effects/lpe-powerclip.cpp @@ -3,6 +3,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "live_effects/lpe-powerclip.h" + +#include <2geom/intersection-graph.h> +#include <2geom/path-intersection.h> + #include "display/curve.h" #include "live_effects/lpeobject-reference.h" #include "live_effects/lpeobject.h" @@ -15,9 +19,6 @@ #include "object/sp-use.h" #include "style.h" #include "svg/svg.h" - -#include <2geom/intersection-graph.h> -#include <2geom/path-intersection.h> // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -98,7 +99,7 @@ Geom::PathVector LPEPowerClip::getClipPathvector() SPObject *clip_path = sp_lpe_item->getClipObject(); if (clip_path) { - std::vector clip_path_list = clip_path->childList(true); + std::vector clip_path_list = clip_path->childList(true); clip_path_list.pop_back(); if (clip_path_list.size()) { for (auto clip : clip_path_list) { @@ -174,7 +175,7 @@ void LPEPowerClip::add() elemref->setAttribute("style", childitem->getAttribute("style")); } else { elemref->setAttribute("style", "fill-rule:evenodd"); - } + } elemref->setAttribute("class", "powerclip"); elemref->setAttribute("id", getId()); gchar *str = sp_svg_write_path(getClipPathvector()); @@ -188,7 +189,10 @@ void LPEPowerClip::add() } } -Glib::ustring LPEPowerClip::getId() { return Glib::ustring("lpe_") + Glib::ustring(getLPEObj()->getId()); } +Glib::ustring LPEPowerClip::getId() +{ + return Glib::ustring("lpe_") + Glib::ustring(getLPEObj()->getId()); +} void LPEPowerClip::upd() { @@ -207,7 +211,6 @@ void LPEPowerClip::upd() } } - void LPEPowerClip::doBeforeEffect(SPLPEItem const *lpeitem) { if (!_updating) { @@ -215,8 +218,7 @@ void LPEPowerClip::doBeforeEffect(SPLPEItem const *lpeitem) } } -void -LPEPowerClip::doOnRemove (SPLPEItem const* /*lpeitem*/) +void LPEPowerClip::doOnRemove(SPLPEItem const * /*lpeitem*/) { SPDocument *document = getSPDoc(); if (!document) { @@ -252,8 +254,8 @@ LPEPowerClip::doOnRemove (SPLPEItem const* /*lpeitem*/) } } -Geom::PathVector -LPEPowerClip::doEffect_path(Geom::PathVector const & path_in){ +Geom::PathVector LPEPowerClip::doEffect_path(Geom::PathVector const &path_in) +{ Geom::PathVector path_out = path_in; if (flatten) { Geom::PathVector c_pv = getClipPathvector(); @@ -265,7 +267,10 @@ LPEPowerClip::doEffect_path(Geom::PathVector const & path_in){ return path_out; } -void LPEPowerClip::doOnVisibilityToggled(SPLPEItem const *lpeitem) { upd(); } +void LPEPowerClip::doOnVisibilityToggled(SPLPEItem const *lpeitem) +{ + upd(); +} void sp_remove_powerclip(Inkscape::Selection *sel) { @@ -298,24 +303,25 @@ void sp_remove_powerclip(Inkscape::Selection *sel) } } -void sp_inverse_powerclip(Inkscape::Selection *sel) { +void sp_inverse_powerclip(Inkscape::Selection *sel) +{ if (!sel->isEmpty()) { auto selList = sel->items(); - for(auto i = boost::rbegin(selList); i != boost::rend(selList); ++i) { - SPLPEItem* lpeitem = dynamic_cast(*i); + for (auto i = boost::rbegin(selList); i != boost::rend(selList); ++i) { + SPLPEItem *lpeitem = dynamic_cast(*i); if (lpeitem) { SPClipPath *clip_path = SP_ITEM(lpeitem)->getClipObject(); - if(clip_path) { - std::vector clip_path_list = clip_path->childList(true); + if (clip_path) { + std::vector clip_path_list = clip_path->childList(true); for (auto iter : clip_path_list) { - SPUse *use = dynamic_cast(iter); + SPUse *use = dynamic_cast(iter); if (use) { g_warning("We can`t add inverse clip on clones"); return; } } Effect::createAndApply(POWERCLIP, SP_ACTIVE_DOCUMENT, lpeitem); - Effect* lpe = lpeitem->getCurrentLPE(); + Effect *lpe = lpeitem->getCurrentLPE(); if (lpe) { lpe->getRepr()->setAttribute("inverse", "true"); } @@ -325,7 +331,7 @@ void sp_inverse_powerclip(Inkscape::Selection *sel) { } } -}; //namespace LivePathEffect +}; // namespace LivePathEffect }; /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-powerclip.h b/src/live_effects/lpe-powerclip.h index fab59ed1ee761c7ce1683af653ecde69c2e23ee9..dd6e955b5f5206359b98b3d5e0a5ace19602527b 100644 --- a/src/live_effects/lpe-powerclip.h +++ b/src/live_effects/lpe-powerclip.h @@ -14,21 +14,22 @@ namespace Inkscape { namespace LivePathEffect { -class LPEPowerClip : public Effect { +class LPEPowerClip : public Effect +{ public: LPEPowerClip(LivePathEffectObject *lpeobject); ~LPEPowerClip() override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; - void doOnRemove (SPLPEItem const* /*lpeitem*/) override; - void doOnVisibilityToggled(SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; + void doOnRemove(SPLPEItem const * /*lpeitem*/) override; + void doOnVisibilityToggled(SPLPEItem const *lpeitem) override; Glib::ustring getId(); void add(); void upd(); void del(); Geom::PathVector getClipPathvector(); - private: +private: BoolParam inverse; BoolParam flatten; BoolParam hide_clip; @@ -40,6 +41,6 @@ public: void sp_remove_powerclip(Inkscape::Selection *sel); void sp_inverse_powerclip(Inkscape::Selection *sel); -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-powermask.cpp b/src/live_effects/lpe-powermask.cpp index 279f132f8ec7423ebf7ab3aa167367226a617af8..473cbd98abc832ab01e5bb95f6db1cfce8541bc2 100644 --- a/src/live_effects/lpe-powermask.cpp +++ b/src/live_effects/lpe-powermask.cpp @@ -3,27 +3,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "live_effects/lpe-powermask.h" -#include "live_effects/lpeobject.h" -#include "live_effects/lpeobject-reference.h" -#include <2geom/path-intersection.h> + #include <2geom/intersection-graph.h> -#include "display/curve.h" -#include "helper/geom.h" -#include "svg/svg.h" -#include "svg/svg-color.h" -#include "svg/stringstream.h" -#include "ui/tools-switch.h" -#include "path-chemistry.h" -#include "extract-uri.h" +#include <2geom/path-intersection.h> #include +#include "display/curve.h" +#include "extract-uri.h" +#include "helper/geom.h" +#include "live_effects/lpeobject-reference.h" +#include "live_effects/lpeobject.h" +#include "object/sp-defs.h" +#include "object/sp-item-group.h" #include "object/sp-mask.h" #include "object/sp-path.h" #include "object/sp-shape.h" -#include "object/sp-defs.h" -#include "object/sp-item-group.h" #include "object/uri.h" - +#include "path-chemistry.h" +#include "svg/stringstream.h" +#include "svg/svg-color.h" +#include "svg/svg.h" +#include "ui/tools-switch.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -32,13 +32,15 @@ namespace Inkscape { namespace LivePathEffect { LPEPowerMask::LPEPowerMask(LivePathEffectObject *lpeobject) - : Effect(lpeobject), - uri("Store the uri of mask", "", "uri", &wr, this, "false", false), - invert(_("Invert mask"), _("Invert mask"), "invert", &wr, this, false), - //wrap(_("Wrap mask data"), _("Wrap mask data allowing previous filters"), "wrap", &wr, this, false), - hide_mask(_("Hide mask"), _("Hide mask"), "hide_mask", &wr, this, false), - background(_("Add background to mask"), _("Add background to mask"), "background", &wr, this, false), - background_color(_("Background color and opacity"), _("Set color and opacity of the background"), "background_color", &wr, this, 0xffffffff) + : Effect(lpeobject) + , uri("Store the uri of mask", "", "uri", &wr, this, "false", false) + , invert(_("Invert mask"), _("Invert mask"), "invert", &wr, this, false) + , + // wrap(_("Wrap mask data"), _("Wrap mask data allowing previous filters"), "wrap", &wr, this, false), + hide_mask(_("Hide mask"), _("Hide mask"), "hide_mask", &wr, this, false) + , background(_("Add background to mask"), _("Add background to mask"), "background", &wr, this, false) + , background_color(_("Background color and opacity"), _("Set color and opacity of the background"), + "background_color", &wr, this, 0xffffffff) { registerParameter(&uri); registerParameter(&invert); @@ -50,13 +52,15 @@ LPEPowerMask::LPEPowerMask(LivePathEffectObject *lpeobject) LPEPowerMask::~LPEPowerMask() = default; -Glib::ustring LPEPowerMask::getId() { return Glib::ustring("mask-powermask-") + Glib::ustring(getLPEObj()->getId()); } +Glib::ustring LPEPowerMask::getId() +{ + return Glib::ustring("mask-powermask-") + Glib::ustring(getLPEObj()->getId()); +} -void -LPEPowerMask::doOnApply (SPLPEItem const * lpeitem) +void LPEPowerMask::doOnApply(SPLPEItem const *lpeitem) { - SPLPEItem *item = const_cast(lpeitem); - SPObject * mask = item->getMaskObject(); + SPLPEItem *item = const_cast(lpeitem); + SPObject *mask = item->getMaskObject(); bool hasit = false; if (lpeitem->hasPathEffect() && lpeitem->pathEffectsEnabled()) { PathEffectList path_effect_list(*lpeitem->path_effect_list); @@ -64,8 +68,9 @@ LPEPowerMask::doOnApply (SPLPEItem const * lpeitem) LivePathEffectObject *lpeobj = lperef->lpeobject; if (!lpeobj) { /** \todo Investigate the cause of this. - * For example, this happens when copy pasting an object with LPE applied. Probably because the object is pasted while the effect is not yet pasted to defs, and cannot be found. - */ + * For example, this happens when copy pasting an object with LPE applied. Probably because the object + * is pasted while the effect is not yet pasted to defs, and cannot be found. + */ g_warning("SPLPEItem::performPathEffect - NULL lpeobj in list!"); return; } @@ -105,11 +110,11 @@ void LPEPowerMask::tryForkMask() } } -void -LPEPowerMask::doBeforeEffect (SPLPEItem const* lpeitem){ - //To avoid close of color dialog and better performance on change color +void LPEPowerMask::doBeforeEffect(SPLPEItem const *lpeitem) +{ + // To avoid close of color dialog and better performance on change color tryForkMask(); - SPObject * mask = SP_ITEM(sp_lpe_item)->getMaskObject(); + SPObject *mask = SP_ITEM(sp_lpe_item)->getMaskObject(); auto uri_str = uri.param_getSVGValue(); if (hide_mask && mask) { SP_ITEM(sp_lpe_item)->getMaskRef().detach(); @@ -125,7 +130,7 @@ LPEPowerMask::doBeforeEffect (SPLPEItem const* lpeitem){ uri.param_setValue(Glib::ustring(extract_uri(sp_lpe_item->getRepr()->attribute("mask"))), true); SP_ITEM(sp_lpe_item)->getMaskRef().detach(); Geom::OptRect bbox = lpeitem->visualBounds(); - if(!bbox) { + if (!bbox) { return; } uri_str = uri.param_getSVGValue(); @@ -137,14 +142,14 @@ LPEPowerMask::doBeforeEffect (SPLPEItem const* lpeitem){ mask_box = Geom::Path(bboxrect); setMask(); } - } else if(!hide_mask) { - SPLPEItem * item = const_cast(lpeitem); + } else if (!hide_mask) { + SPLPEItem *item = const_cast(lpeitem); item->removeCurrentPathEffect(false); } } -void -LPEPowerMask::setMask(){ +void LPEPowerMask::setMask() +{ SPMask *mask = SP_ITEM(sp_lpe_item)->getMaskObject(); SPObject *elemref = nullptr; SPDocument *document = getSPDoc(); @@ -154,12 +159,12 @@ LPEPowerMask::setMask(){ Inkscape::XML::Document *xml_doc = document->getReprDoc(); Inkscape::XML::Node *box = nullptr; Inkscape::XML::Node *filter = nullptr; - SPDefs * defs = document->getDefs(); + SPDefs *defs = document->getDefs(); Glib::ustring mask_id = getId(); - Glib::ustring box_id = mask_id + (Glib::ustring)"_box"; - Glib::ustring filter_id = mask_id + (Glib::ustring)"_inverse"; - Glib::ustring filter_label = (Glib::ustring)"filter" + mask_id; - Glib::ustring filter_uri = (Glib::ustring)"url(#" + filter_id + (Glib::ustring)")"; + Glib::ustring box_id = mask_id + (Glib::ustring) "_box"; + Glib::ustring filter_id = mask_id + (Glib::ustring) "_inverse"; + Glib::ustring filter_label = (Glib::ustring) "filter" + mask_id; + Glib::ustring filter_uri = (Glib::ustring) "url(#" + filter_id + (Glib::ustring) ")"; if (!(elemref = document->getObjectById(filter_id))) { filter = xml_doc->createElement("svg:filter"); filter->setAttribute("id", filter_id); @@ -172,14 +177,14 @@ LPEPowerMask::setMask(){ filter->setAttribute("width", "100"); filter->setAttribute("x", "-50"); filter->setAttribute("y", "-50"); - Inkscape::XML::Node *primitive1 = xml_doc->createElement("svg:feColorMatrix"); - Glib::ustring primitive1_id = (mask_id + (Glib::ustring)"_primitive1").c_str(); + Inkscape::XML::Node *primitive1 = xml_doc->createElement("svg:feColorMatrix"); + Glib::ustring primitive1_id = (mask_id + (Glib::ustring) "_primitive1").c_str(); primitive1->setAttribute("id", primitive1_id); primitive1->setAttribute("values", "1"); primitive1->setAttribute("type", "saturate"); primitive1->setAttribute("result", "fbSourceGraphic"); - Inkscape::XML::Node *primitive2 = xml_doc->createElement("svg:feColorMatrix"); - Glib::ustring primitive2_id = (mask_id + (Glib::ustring)"_primitive2").c_str(); + Inkscape::XML::Node *primitive2 = xml_doc->createElement("svg:feColorMatrix"); + Glib::ustring primitive2_id = (mask_id + (Glib::ustring) "_primitive2").c_str(); primitive2->setAttribute("id", primitive2_id); primitive2->setAttribute("values", "-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0 "); primitive2->setAttribute("in", "fbSourceGraphic"); @@ -190,9 +195,9 @@ LPEPowerMask::setMask(){ filter->appendChild(primitive2); Inkscape::GC::release(primitive2); } - Glib::ustring g_data_id = mask_id + (Glib::ustring)"_container"; - if((elemref = document->getObjectById(g_data_id))){ - std::vector item_list = sp_item_group_item_list(SP_GROUP(elemref)); + Glib::ustring g_data_id = mask_id + (Glib::ustring) "_container"; + if ((elemref = document->getObjectById(g_data_id))) { + std::vector item_list = sp_item_group_item_list(SP_GROUP(elemref)); for (auto iter : item_list) { Inkscape::XML::Node *mask_node = iter->getRepr(); elemref->getRepr()->removeChild(mask_node); @@ -201,24 +206,24 @@ LPEPowerMask::setMask(){ } elemref->deleteObject(true); } - std::vector mask_list = mask->childList(true); + std::vector mask_list = mask->childList(true); for (auto iter : mask_list) { - SPItem * mask_data = SP_ITEM(iter); + SPItem *mask_data = SP_ITEM(iter); Inkscape::XML::Node *mask_node = mask_data->getRepr(); - if (! strcmp(mask_data->getId(), box_id.c_str())){ + if (!strcmp(mask_data->getId(), box_id.c_str())) { continue; } Glib::ustring mask_data_id = (Glib::ustring)mask_data->getId(); SPCSSAttr *css = sp_repr_css_attr_new(); - if(mask_node->attribute("style")) { + if (mask_node->attribute("style")) { sp_repr_css_attr_add_from_string(css, mask_node->attribute("style")); } - char const* filter = sp_repr_css_property (css, "filter", nullptr); - if(!filter || !strcmp(filter, filter_uri.c_str())) { + char const *filter = sp_repr_css_property(css, "filter", nullptr); + if (!filter || !strcmp(filter, filter_uri.c_str())) { if (invert && is_visible) { - sp_repr_css_set_property (css, "filter", filter_uri.c_str()); + sp_repr_css_set_property(css, "filter", filter_uri.c_str()); } else { - sp_repr_css_set_property (css, "filter", nullptr); + sp_repr_css_set_property(css, "filter", nullptr); } Glib::ustring css_str; sp_repr_css_write_string(css, css_str); @@ -245,20 +250,19 @@ LPEPowerMask::setMask(){ style = style + Glib::ustring(";fill-opacity:") + Glib::ustring(os.str()); SPCSSAttr *css = sp_repr_css_attr_new(); sp_repr_css_attr_add_from_string(css, style.c_str()); - char const* filter = sp_repr_css_property (css, "filter", nullptr); - if(!filter || !strcmp(filter, filter_uri.c_str())) { + char const *filter = sp_repr_css_property(css, "filter", nullptr); + if (!filter || !strcmp(filter, filter_uri.c_str())) { if (invert && is_visible) { - sp_repr_css_set_property (css, "filter", filter_uri.c_str()); + sp_repr_css_set_property(css, "filter", filter_uri.c_str()); } else { - sp_repr_css_set_property (css, "filter", nullptr); + sp_repr_css_set_property(css, "filter", nullptr); } - } Glib::ustring css_str; sp_repr_css_write_string(css, css_str); box->setAttributeOrRemoveIfEmpty("style", css_str); - gchar * box_str = sp_svg_write_path( mask_box ); - box->setAttribute("d" , box_str); + gchar *box_str = sp_svg_write_path(mask_box); + box->setAttribute("d", box_str); g_free(box_str); if (!exist) { elemref = mask->appendChildRepr(box); @@ -271,19 +275,14 @@ LPEPowerMask::setMask(){ mask->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void -LPEPowerMask::doOnVisibilityToggled(SPLPEItem const* lpeitem) +void LPEPowerMask::doOnVisibilityToggled(SPLPEItem const *lpeitem) { doBeforeEffect(lpeitem); } -void -LPEPowerMask::doEffect (SPCurve * curve) -{ -} +void LPEPowerMask::doEffect(SPCurve *curve) {} -void -LPEPowerMask::doOnRemove (SPLPEItem const* lpeitem) +void LPEPowerMask::doOnRemove(SPLPEItem const *lpeitem) { SPMask *mask = lpeitem->getMaskObject(); if (mask) { @@ -291,33 +290,34 @@ LPEPowerMask::doOnRemove (SPLPEItem const* lpeitem) return; } invert.param_setValue(false); - //wrap.param_setValue(false); + // wrap.param_setValue(false); background.param_setValue(false); setMask(); SPObject *elemref = nullptr; SPDocument *document = getSPDoc(); Glib::ustring mask_id = getId(); - Glib::ustring filter_id = mask_id + (Glib::ustring)"_inverse"; + Glib::ustring filter_id = mask_id + (Glib::ustring) "_inverse"; if ((elemref = document->getObjectById(filter_id))) { elemref->deleteObject(true); } } } -void sp_inverse_powermask(Inkscape::Selection *sel) { +void sp_inverse_powermask(Inkscape::Selection *sel) +{ if (!sel->isEmpty()) { SPDocument *document = SP_ACTIVE_DOCUMENT; if (!document) { return; } auto selList = sel->items(); - for(auto i = boost::rbegin(selList); i != boost::rend(selList); ++i) { - SPLPEItem* lpeitem = dynamic_cast(*i); + for (auto i = boost::rbegin(selList); i != boost::rend(selList); ++i) { + SPLPEItem *lpeitem = dynamic_cast(*i); if (lpeitem) { SPMask *mask = lpeitem->getMaskObject(); if (mask) { Effect::createAndApply(POWERMASK, SP_ACTIVE_DOCUMENT, lpeitem); - Effect* lpe = lpeitem->getCurrentLPE(); + Effect *lpe = lpeitem->getCurrentLPE(); if (lpe) { lpe->getRepr()->setAttribute("invert", "false"); lpe->getRepr()->setAttribute("is_visible", "true"); @@ -331,7 +331,8 @@ void sp_inverse_powermask(Inkscape::Selection *sel) { } } -void sp_remove_powermask(Inkscape::Selection *sel) { +void sp_remove_powermask(Inkscape::Selection *sel) +{ if (!sel->isEmpty()) { auto selList = sel->items(); for (auto i = boost::rbegin(selList); i != boost::rend(selList); ++i) { @@ -361,7 +362,7 @@ void sp_remove_powermask(Inkscape::Selection *sel) { } } -}; //namespace LivePathEffect +}; // namespace LivePathEffect }; /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-powermask.h b/src/live_effects/lpe-powermask.h index 16b74d554a2eb9e91bf24806eed37eec3b1cd8d2..ea3dfbea46fe4d52064460e6be6d19a6a2eb4de4 100644 --- a/src/live_effects/lpe-powermask.h +++ b/src/live_effects/lpe-powermask.h @@ -9,30 +9,32 @@ */ #include "live_effects/effect.h" #include "live_effects/parameter/bool.h" -#include "live_effects/parameter/text.h" -#include "live_effects/parameter/hidden.h" #include "live_effects/parameter/colorpicker.h" +#include "live_effects/parameter/hidden.h" +#include "live_effects/parameter/text.h" namespace Inkscape { namespace LivePathEffect { -class LPEPowerMask : public Effect { +class LPEPowerMask : public Effect +{ public: LPEPowerMask(LivePathEffectObject *lpeobject); ~LPEPowerMask() override; - void doOnApply (SPLPEItem const * lpeitem) override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; - void doEffect (SPCurve * curve) override; - void doOnRemove (SPLPEItem const* /*lpeitem*/) override; - void doOnVisibilityToggled(SPLPEItem const* lpeitem) override; + void doOnApply(SPLPEItem const *lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; + void doEffect(SPCurve *curve) override; + void doOnRemove(SPLPEItem const * /*lpeitem*/) override; + void doOnVisibilityToggled(SPLPEItem const *lpeitem) override; void toggleMaskVisibility(); void tryForkMask(); Glib::ustring getId(); void setMask(); + private: HiddenParam uri; BoolParam invert; - //BoolParam wrap; + // BoolParam wrap; BoolParam hide_mask; BoolParam background; ColorPickerParam background_color; @@ -43,7 +45,7 @@ private: void sp_remove_powermask(Inkscape::Selection *sel); void sp_inverse_powermask(Inkscape::Selection *sel); -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-powerstroke-interpolators.h b/src/live_effects/lpe-powerstroke-interpolators.h index 940d97e4f6b7abd8e207a3ec4c273806398b337d..10191fed5fc4c8a201884a0bb43f85aa08b58f6e 100644 --- a/src/live_effects/lpe-powerstroke-interpolators.h +++ b/src/live_effects/lpe-powerstroke-interpolators.h @@ -13,86 +13,95 @@ #ifndef INKSCAPE_LPE_POWERSTROKE_INTERPOLATORS_H #define INKSCAPE_LPE_POWERSTROKE_INTERPOLATORS_H -#include <2geom/path.h> #include <2geom/bezier-utils.h> +#include <2geom/path.h> #include <2geom/sbasis-to-bezier.h> #include "live_effects/spiro.h" - /// @TODO Move this to 2geom? namespace Geom { namespace Interpolate { -enum InterpolatorType { - INTERP_LINEAR, - INTERP_CUBICBEZIER, - INTERP_CUBICBEZIER_JOHAN, - INTERP_SPIRO, - INTERP_CUBICBEZIER_SMOOTH, - INTERP_CENTRIPETAL_CATMULLROM +enum InterpolatorType +{ + INTERP_LINEAR, + INTERP_CUBICBEZIER, + INTERP_CUBICBEZIER_JOHAN, + INTERP_SPIRO, + INTERP_CUBICBEZIER_SMOOTH, + INTERP_CENTRIPETAL_CATMULLROM }; -class Interpolator { +class Interpolator +{ public: - Interpolator() = default;; - virtual ~Interpolator() = default;; + Interpolator() = default; + ; + virtual ~Interpolator() = default; + ; - static Interpolator* create(InterpolatorType type); + static Interpolator *create(InterpolatorType type); virtual Geom::Path interpolateToPath(std::vector const &points) const = 0; private: - Interpolator(const Interpolator&) = delete; - Interpolator& operator=(const Interpolator&) = delete; + Interpolator(const Interpolator &) = delete; + Interpolator &operator=(const Interpolator &) = delete; }; -class Linear : public Interpolator { +class Linear : public Interpolator +{ public: - Linear() = default;; - ~Linear() override = default;; + Linear() = default; + ; + ~Linear() override = default; + ; - Path interpolateToPath(std::vector const &points) const override { + Path interpolateToPath(std::vector const &points) const override + { Path path; - path.start( points.at(0) ); - for (unsigned int i = 1 ; i < points.size(); ++i) { + path.start(points.at(0)); + for (unsigned int i = 1; i < points.size(); ++i) { path.appendNew(points.at(i)); } return path; }; private: - Linear(const Linear&) = delete; - Linear& operator=(const Linear&) = delete; + Linear(const Linear &) = delete; + Linear &operator=(const Linear &) = delete; }; // this class is terrible -class CubicBezierFit : public Interpolator { +class CubicBezierFit : public Interpolator +{ public: - CubicBezierFit() = default;; - ~CubicBezierFit() override = default;; + CubicBezierFit() = default; + ; + ~CubicBezierFit() override = default; + ; - Path interpolateToPath(std::vector const &points) const override { + Path interpolateToPath(std::vector const &points) const override + { unsigned int n_points = points.size(); // worst case gives us 2 segment per point - int max_segs = 8*n_points; - Geom::Point * b = g_new(Geom::Point, max_segs); - Geom::Point * points_array = g_new(Geom::Point, 4*n_points); + int max_segs = 8 * n_points; + Geom::Point *b = g_new(Geom::Point, max_segs); + Geom::Point *points_array = g_new(Geom::Point, 4 * n_points); for (unsigned i = 0; i < n_points; ++i) { points_array[i] = points.at(i); } double tolerance_sq = 0; // this value is just a random guess - int const n_segs = Geom::bezier_fit_cubic_r(b, points_array, n_points, - tolerance_sq, max_segs); + int const n_segs = Geom::bezier_fit_cubic_r(b, points_array, n_points, tolerance_sq, max_segs); Geom::Path fit; - if ( n_segs > 0) - { + if (n_segs > 0) { fit.start(b[0]); for (int c = 0; c < n_segs; c++) { - fit.appendNew(b[4*c+1], b[4*c+2], b[4*c+3]); + fit.appendNew(b[4 * c + 1], b[4 * c + 2], b[4 * c + 3]); } } g_free(b); @@ -101,91 +110,93 @@ public: }; private: - CubicBezierFit(const CubicBezierFit&) = delete; - CubicBezierFit& operator=(const CubicBezierFit&) = delete; + CubicBezierFit(const CubicBezierFit &) = delete; + CubicBezierFit &operator=(const CubicBezierFit &) = delete; }; /// @todo invent name for this class -class CubicBezierJohan : public Interpolator { +class CubicBezierJohan : public Interpolator +{ public: - CubicBezierJohan(double beta = 0.2) { - _beta = beta; - }; - ~CubicBezierJohan() override = default;; + CubicBezierJohan(double beta = 0.2) { _beta = beta; }; + ~CubicBezierJohan() override = default; + ; - Path interpolateToPath(std::vector const &points) const override { + Path interpolateToPath(std::vector const &points) const override + { Path fit; fit.start(points.at(0)); for (unsigned int i = 1; i < points.size(); ++i) { - Point p0 = points.at(i-1); + Point p0 = points.at(i - 1); Point p1 = points.at(i); Point dx = Point(p1[X] - p0[X], 0); - fit.appendNew(p0+_beta*dx, p1-_beta*dx, p1); + fit.appendNew(p0 + _beta * dx, p1 - _beta * dx, p1); } return fit; }; - void setBeta(double beta) { - _beta = beta; - } + void setBeta(double beta) { _beta = beta; } double _beta; private: - CubicBezierJohan(const CubicBezierJohan&) = delete; - CubicBezierJohan& operator=(const CubicBezierJohan&) = delete; + CubicBezierJohan(const CubicBezierJohan &) = delete; + CubicBezierJohan &operator=(const CubicBezierJohan &) = delete; }; /// @todo invent name for this class -class CubicBezierSmooth : public Interpolator { +class CubicBezierSmooth : public Interpolator +{ public: - CubicBezierSmooth(double beta = 0.2) { - _beta = beta; - }; - ~CubicBezierSmooth() override = default;; + CubicBezierSmooth(double beta = 0.2) { _beta = beta; }; + ~CubicBezierSmooth() override = default; + ; - Path interpolateToPath(std::vector const &points) const override { + Path interpolateToPath(std::vector const &points) const override + { Path fit; fit.start(points.at(0)); unsigned int num_points = points.size(); for (unsigned int i = 1; i < num_points; ++i) { - Point p0 = points.at(i-1); + Point p0 = points.at(i - 1); Point p1 = points.at(i); Point dx = Point(p1[X] - p0[X], 0); if (i == 1) { - fit.appendNew(p0, p1-0.75*dx, p1); + fit.appendNew(p0, p1 - 0.75 * dx, p1); } else if (i == points.size() - 1) { - fit.appendNew(p0+0.75*dx, p1, p1); + fit.appendNew(p0 + 0.75 * dx, p1, p1); } else { - fit.appendNew(p0+_beta*dx, p1-_beta*dx, p1); + fit.appendNew(p0 + _beta * dx, p1 - _beta * dx, p1); } } return fit; }; - void setBeta(double beta) { - _beta = beta; - } + void setBeta(double beta) { _beta = beta; } double _beta; private: - CubicBezierSmooth(const CubicBezierSmooth&) = delete; - CubicBezierSmooth& operator=(const CubicBezierSmooth&) = delete; + CubicBezierSmooth(const CubicBezierSmooth &) = delete; + CubicBezierSmooth &operator=(const CubicBezierSmooth &) = delete; }; -class SpiroInterpolator : public Interpolator { +class SpiroInterpolator : public Interpolator +{ public: - SpiroInterpolator() = default;; - ~SpiroInterpolator() override = default;; + SpiroInterpolator() = default; + ; + ~SpiroInterpolator() override = default; + ; - Path interpolateToPath(std::vector const &points) const override { + Path interpolateToPath(std::vector const &points) const override + { Path fit; Coord scale_y = 100.; guint len = points.size(); - Spiro::spiro_cp *controlpoints = g_new (Spiro::spiro_cp, len); + Spiro::spiro_cp *controlpoints = g_new(Spiro::spiro_cp, len); for (unsigned int i = 0; i < len; ++i) { controlpoints[i].x = points[i][X]; controlpoints[i].y = points[i][Y] / scale_y; @@ -193,44 +204,49 @@ public: } controlpoints[0].ty = '{'; controlpoints[1].ty = 'v'; - controlpoints[len-2].ty = 'v'; - controlpoints[len-1].ty = '}'; + controlpoints[len - 2].ty = 'v'; + controlpoints[len - 1].ty = '}'; Spiro::spiro_run(controlpoints, len, fit); - fit *= Scale(1,scale_y); + fit *= Scale(1, scale_y); g_free(controlpoints); return fit; }; private: - SpiroInterpolator(const SpiroInterpolator&) = delete; - SpiroInterpolator& operator=(const SpiroInterpolator&) = delete; + SpiroInterpolator(const SpiroInterpolator &) = delete; + SpiroInterpolator &operator=(const SpiroInterpolator &) = delete; }; // Quick mockup for testing the behavior for powerstroke controlpoint interpolation -class CentripetalCatmullRomInterpolator : public Interpolator { +class CentripetalCatmullRomInterpolator : public Interpolator +{ public: - CentripetalCatmullRomInterpolator() = default;; - ~CentripetalCatmullRomInterpolator() override = default;; + CentripetalCatmullRomInterpolator() = default; + ; + ~CentripetalCatmullRomInterpolator() override = default; + ; - Path interpolateToPath(std::vector const &points) const override { + Path interpolateToPath(std::vector const &points) const override + { unsigned int n_points = points.size(); Geom::Path fit(points.front()); - if (n_points < 3) return fit; // TODO special cases for 0,1 and 2 input points + if (n_points < 3) + return fit; // TODO special cases for 0,1 and 2 input points // return n_points-1 cubic segments // duplicate first point - fit.append(calc_bezier(points[0],points[0],points[1],points[2])); + fit.append(calc_bezier(points[0], points[0], points[1], points[2])); - for (std::size_t i = 0; i < n_points-2; ++i) { + for (std::size_t i = 0; i < n_points - 2; ++i) { Point p0 = points[i]; - Point p1 = points[i+1]; - Point p2 = points[i+2]; - Point p3 = (i < n_points-3) ? points[i+3] : points[i+2]; + Point p1 = points[i + 1]; + Point p2 = points[i + 2]; + Point p3 = (i < n_points - 3) ? points[i + 3] : points[i + 2]; fit.append(calc_bezier(p0, p1, p2, p3)); } @@ -239,21 +255,21 @@ public: }; private: - CubicBezier calc_bezier(Point p0, Point p1, Point p2, Point p3) const { + CubicBezier calc_bezier(Point p0, Point p1, Point p2, Point p3) const + { // create interpolating bezier between p1 and p2 // Part of the code comes from StackOverflow user eriatarka84 // http://stackoverflow.com/a/23980479/2929337 // calculate time coords (deltas) of points - // the factor 0.25 can be generalized for other Catmull-Rom interpolation types - // see alpha in Yuksel et al. "On the Parameterization of Catmull-Rom Curves", + // the factor 0.25 can be generalized for other Catmull-Rom interpolation types + // see alpha in Yuksel et al. "On the Parameterization of Catmull-Rom Curves", // --> http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf double dt0 = powf(distanceSq(p0, p1), 0.25); double dt1 = powf(distanceSq(p1, p2), 0.25); double dt2 = powf(distanceSq(p2, p3), 0.25); - // safety check for repeated points double eps = Geom::EPSILON; if (dt1 < eps) @@ -284,33 +300,32 @@ private: return CubicBezier(b0, b1, b2, b3); } - CentripetalCatmullRomInterpolator(const CentripetalCatmullRomInterpolator&) = delete; - CentripetalCatmullRomInterpolator& operator=(const CentripetalCatmullRomInterpolator&) = delete; + CentripetalCatmullRomInterpolator(const CentripetalCatmullRomInterpolator &) = delete; + CentripetalCatmullRomInterpolator &operator=(const CentripetalCatmullRomInterpolator &) = delete; }; - -inline Interpolator* -Interpolator::create(InterpolatorType type) { +inline Interpolator *Interpolator::create(InterpolatorType type) +{ switch (type) { - case INTERP_LINEAR: - return new Geom::Interpolate::Linear(); - case INTERP_CUBICBEZIER: - return new Geom::Interpolate::CubicBezierFit(); - case INTERP_CUBICBEZIER_JOHAN: - return new Geom::Interpolate::CubicBezierJohan(); - case INTERP_SPIRO: - return new Geom::Interpolate::SpiroInterpolator(); - case INTERP_CUBICBEZIER_SMOOTH: - return new Geom::Interpolate::CubicBezierSmooth(); - case INTERP_CENTRIPETAL_CATMULLROM: - return new Geom::Interpolate::CentripetalCatmullRomInterpolator(); - default: - return new Geom::Interpolate::Linear(); + case INTERP_LINEAR: + return new Geom::Interpolate::Linear(); + case INTERP_CUBICBEZIER: + return new Geom::Interpolate::CubicBezierFit(); + case INTERP_CUBICBEZIER_JOHAN: + return new Geom::Interpolate::CubicBezierJohan(); + case INTERP_SPIRO: + return new Geom::Interpolate::SpiroInterpolator(); + case INTERP_CUBICBEZIER_SMOOTH: + return new Geom::Interpolate::CubicBezierSmooth(); + case INTERP_CENTRIPETAL_CATMULLROM: + return new Geom::Interpolate::CentripetalCatmullRomInterpolator(); + default: + return new Geom::Interpolate::Linear(); } } -} //namespace Interpolate -} //namespace Geom +} // namespace Interpolate +} // namespace Geom #endif diff --git a/src/live_effects/lpe-powerstroke.cpp b/src/live_effects/lpe-powerstroke.cpp index 8c9a6a11a2439a2b8776ac0e30ee90f65c072a39..e49d4e19d6be1589cead34a22f4a76e5954f71f7 100644 --- a/src/live_effects/lpe-powerstroke.cpp +++ b/src/live_effects/lpe-powerstroke.cpp @@ -12,24 +12,23 @@ */ #include "live_effects/lpe-powerstroke.h" -#include "live_effects/lpe-powerstroke-interpolators.h" -#include "live_effects/lpe-simplify.h" -#include "live_effects/lpeobject.h" -#include "live_effects/fill-conversion.h" - -#include "svg/svg-color.h" -#include "desktop-style.h" -#include "svg/css-ostringstream.h" -#include "display/curve.h" +#include <2geom/circle.h> #include <2geom/elliptical-arc.h> -#include <2geom/path-sink.h> #include <2geom/path-intersection.h> -#include <2geom/circle.h> -#include "helper/geom.h" +#include <2geom/path-sink.h> +#include "desktop-style.h" +#include "display/curve.h" +#include "helper/geom.h" +#include "live_effects/fill-conversion.h" +#include "live_effects/lpe-powerstroke-interpolators.h" +#include "live_effects/lpe-simplify.h" +#include "live_effects/lpeobject.h" #include "object/sp-shape.h" #include "style.h" +#include "svg/css-ostringstream.h" +#include "svg/svg-color.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -38,23 +37,23 @@ namespace Geom { // should all be moved to 2geom at some point /** Find the point where two straight lines cross. -*/ -static boost::optional intersection_point( Point const & origin_a, Point const & vector_a, - Point const & origin_b, Point const & vector_b) + */ +static boost::optional intersection_point(Point const &origin_a, Point const &vector_a, Point const &origin_b, + Point const &vector_b) { Coord denom = cross(vector_a, vector_b); - if (!are_near(denom,0.)){ + if (!are_near(denom, 0.)) { Coord t = (cross(vector_b, origin_a) + cross(origin_b, vector_b)) / denom; return origin_a + t * vector_a; } return boost::none; } -static Geom::CubicBezier sbasis_to_cubicbezier(Geom::D2 const & sbasis_in) +static Geom::CubicBezier sbasis_to_cubicbezier(Geom::D2 const &sbasis_in) { std::vector temp; sbasis_to_bezier(temp, sbasis_in, 4); - return Geom::CubicBezier( temp ); + return Geom::CubicBezier(temp); } /** @@ -67,24 +66,24 @@ static Ellipse find_ellipse(Point P, Point Q, Point O) { Point p = P - O; Point q = Q - O; - Coord K = 4 * dot(p,q) / (L2sq(p) + L2sq(q)); + Coord K = 4 * dot(p, q) / (L2sq(p) + L2sq(q)); - double cross = p[Y]*q[X] - p[X]*q[Y]; - double a = -q[Y]/cross; - double b = q[X]/cross; - double c = (O[X]*q[Y] - O[Y]*q[X])/cross; + double cross = p[Y] * q[X] - p[X] * q[Y]; + double a = -q[Y] / cross; + double b = q[X] / cross; + double c = (O[X] * q[Y] - O[Y] * q[X]) / cross; - double d = p[Y]/cross; - double e = -p[X]/cross; - double f = (-O[X]*p[Y] + O[Y]*p[X])/cross; + double d = p[Y] / cross; + double e = -p[X] / cross; + double f = (-O[X] * p[Y] + O[Y] * p[X]) / cross; // Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 - double A = (a*d*K+d*d+a*a); - double B = (a*e*K+b*d*K+2*d*e+2*a*b); - double C = (b*e*K+e*e+b*b); - double D = (a*f*K+c*d*K+2*d*f-2*d+2*a*c-2*a); - double E = (b*f*K+c*e*K+2*e*f-2*e+2*b*c-2*b); - double F = c*f*K+f*f-2*f+c*c-2*c+1; + double A = (a * d * K + d * d + a * a); + double B = (a * e * K + b * d * K + 2 * d * e + 2 * a * b); + double C = (b * e * K + e * e + b * b); + double D = (a * f * K + c * d * K + 2 * d * f - 2 * d + 2 * a * c - 2 * a); + double E = (b * f * K + c * e * K + 2 * e * f - 2 * e + 2 * b * c - 2 * b); + double F = c * f * K + f * f - 2 * f + c * c - 2 * c + 1; return Ellipse(A, B, C, D, E, F); } @@ -93,31 +92,31 @@ static Ellipse find_ellipse(Point P, Point Q, Point O) * Find circle that touches inside of the curve, with radius matching the curvature, at time value \c t. * Because this method internally uses unitTangentAt, t should be smaller than 1.0 (see unitTangentAt). */ -static Circle touching_circle( D2 const &curve, double t, double tol=0.01 ) +static Circle touching_circle(D2 const &curve, double t, double tol = 0.01) { - //Piecewise k = curvature(curve, tol); - D2 dM=derivative(curve); - if ( are_near(L2sq(dM(t)),0.) && (dM[0].size() > 1) && (dM[1].size() > 1) ) { - dM=derivative(dM); + // Piecewise k = curvature(curve, tol); + D2 dM = derivative(curve); + if (are_near(L2sq(dM(t)), 0.) && (dM[0].size() > 1) && (dM[1].size() > 1)) { + dM = derivative(dM); } - if ( are_near(L2sq(dM(t)),0.) && (dM[0].size() > 1) && (dM[1].size() > 1) ) { // try second time - dM=derivative(dM); + if (are_near(L2sq(dM(t)), 0.) && (dM[0].size() > 1) && (dM[1].size() > 1)) { // try second time + dM = derivative(dM); } - if ( dM.isZero(tol) || (are_near(L2sq(dM(t)),0.) && (dM[0].size() > 1) && (dM[1].size() > 1) )) { // admit defeat + if (dM.isZero(tol) || (are_near(L2sq(dM(t)), 0.) && (dM[0].size() > 1) && (dM[1].size() > 1))) { // admit defeat return Geom::Circle(Geom::Point(0., 0.), 0.); } - Piecewise > unitv = unitVector(dM,tol); - if (unitv.empty()) { // admit defeat + Piecewise> unitv = unitVector(dM, tol); + if (unitv.empty()) { // admit defeat return Geom::Circle(Geom::Point(0., 0.), 0.); } - Piecewise dMlength = dot(Piecewise >(dM),unitv); - Piecewise k = cross(derivative(unitv),unitv); - k = divide(k,dMlength,tol,3); + Piecewise dMlength = dot(Piecewise>(dM), unitv); + Piecewise k = cross(derivative(unitv), unitv); + k = divide(k, dMlength, tol, 3); double curv = k(t); // note that this value is signed Geom::Point normal = unitTangentAt(curve, t).cw(); - double radius = 1/curv; - Geom::Point center = curve(t) + radius*normal; + double radius = 1 / curv; + Geom::Point center = curve(t) + radius * normal; return Geom::Circle(center, fabs(radius)); } @@ -127,52 +126,66 @@ namespace Inkscape { namespace LivePathEffect { static const Util::EnumData InterpolatorTypeData[] = { - {Geom::Interpolate::INTERP_CUBICBEZIER_SMOOTH, N_("CubicBezierSmooth"), "CubicBezierSmooth"}, - {Geom::Interpolate::INTERP_LINEAR , N_("Linear"), "Linear"}, - {Geom::Interpolate::INTERP_CUBICBEZIER , N_("CubicBezierFit"), "CubicBezierFit"}, - {Geom::Interpolate::INTERP_CUBICBEZIER_JOHAN , N_("CubicBezierJohan"), "CubicBezierJohan"}, - {Geom::Interpolate::INTERP_SPIRO , N_("SpiroInterpolator"), "SpiroInterpolator"}, - {Geom::Interpolate::INTERP_CENTRIPETAL_CATMULLROM, N_("Centripetal Catmull-Rom"), "CentripetalCatmullRom"} -}; -static const Util::EnumDataConverter InterpolatorTypeConverter(InterpolatorTypeData, sizeof(InterpolatorTypeData)/sizeof(*InterpolatorTypeData)); - -enum LineJoinType { - LINEJOIN_BEVEL, - LINEJOIN_ROUND, - LINEJOIN_EXTRP_MITER, - LINEJOIN_MITER, - LINEJOIN_SPIRO, - LINEJOIN_EXTRP_MITER_ARC + {Geom::Interpolate::INTERP_CUBICBEZIER_SMOOTH, N_("CubicBezierSmooth"), "CubicBezierSmooth"}, + {Geom::Interpolate::INTERP_LINEAR, N_("Linear"), "Linear"}, + {Geom::Interpolate::INTERP_CUBICBEZIER, N_("CubicBezierFit"), "CubicBezierFit"}, + {Geom::Interpolate::INTERP_CUBICBEZIER_JOHAN, N_("CubicBezierJohan"), "CubicBezierJohan"}, + {Geom::Interpolate::INTERP_SPIRO, N_("SpiroInterpolator"), "SpiroInterpolator"}, + {Geom::Interpolate::INTERP_CENTRIPETAL_CATMULLROM, N_("Centripetal Catmull-Rom"), "CentripetalCatmullRom"}}; +static const Util::EnumDataConverter + InterpolatorTypeConverter(InterpolatorTypeData, sizeof(InterpolatorTypeData) / sizeof(*InterpolatorTypeData)); + +enum LineJoinType +{ + LINEJOIN_BEVEL, + LINEJOIN_ROUND, + LINEJOIN_EXTRP_MITER, + LINEJOIN_MITER, + LINEJOIN_SPIRO, + LINEJOIN_EXTRP_MITER_ARC }; static const Util::EnumData LineJoinTypeData[] = { - {LINEJOIN_BEVEL, N_("Beveled"), "bevel"}, - {LINEJOIN_ROUND, N_("Rounded"), "round"}, -// {LINEJOIN_EXTRP_MITER, N_("Extrapolated"), "extrapolated"}, // disabled because doesn't work well - {LINEJOIN_EXTRP_MITER_ARC, N_("Extrapolated arc"), "extrp_arc"}, - {LINEJOIN_MITER, N_("Miter"), "miter"}, - {LINEJOIN_SPIRO, N_("Spiro"), "spiro"}, + {LINEJOIN_BEVEL, N_("Beveled"), "bevel"}, + {LINEJOIN_ROUND, N_("Rounded"), "round"}, + // {LINEJOIN_EXTRP_MITER, N_("Extrapolated"), "extrapolated"}, // disabled because doesn't work well + {LINEJOIN_EXTRP_MITER_ARC, N_("Extrapolated arc"), "extrp_arc"}, + {LINEJOIN_MITER, N_("Miter"), "miter"}, + {LINEJOIN_SPIRO, N_("Spiro"), "spiro"}, }; -static const Util::EnumDataConverter LineJoinTypeConverter(LineJoinTypeData, sizeof(LineJoinTypeData)/sizeof(*LineJoinTypeData)); - -LPEPowerStroke::LPEPowerStroke(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - offset_points(_("Offset points"), _("Offset points"), "offset_points", &wr, this), - not_jump(_("Not jump"), _("Not jump between further segments"), "not_jump", &wr, this, false), - sort_points(_("Sort points"), _("Sort offset points according to their time value along the curve"), "sort_points", &wr, this, true), - interpolator_type(_("Interpolator type:"), _("Determines which kind of interpolator will be used to interpolate between stroke width along the path"), "interpolator_type", InterpolatorTypeConverter, &wr, this, Geom::Interpolate::INTERP_CENTRIPETAL_CATMULLROM), - interpolator_beta(_("Smoothness:"), _("Sets the smoothness for the CubicBezierJohan interpolator; 0 = linear interpolation, 1 = smooth"), "interpolator_beta", &wr, this, 0.2), - scale_width(_("Width factor:"), _("Scale the stroke's width uniformly along the whole path"), "scale_width", &wr, this, 1.0), - start_linecap_type(_("Start cap:"), _("Determines the shape of the path's start"), "start_linecap_type", LineCapTypeConverter, &wr, this, LINECAP_ZERO_WIDTH), - linejoin_type(_("Join:"), _("Determines the shape of the path's corners"), "linejoin_type", LineJoinTypeConverter, &wr, this, LINEJOIN_ROUND), - miter_limit(_("Miter limit:"), _("Maximum length of the miter (in units of stroke width)"), "miter_limit", &wr, this, 4.), - end_linecap_type(_("End cap:"), _("Determines the shape of the path's end"), "end_linecap_type", LineCapTypeConverter, &wr, this, LINECAP_ZERO_WIDTH) +static const Util::EnumDataConverter LineJoinTypeConverter(LineJoinTypeData, sizeof(LineJoinTypeData) / + sizeof(*LineJoinTypeData)); + +LPEPowerStroke::LPEPowerStroke(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , offset_points(_("Offset points"), _("Offset points"), "offset_points", &wr, this) + , not_jump(_("Not jump"), _("Not jump between further segments"), "not_jump", &wr, this, false) + , sort_points(_("Sort points"), _("Sort offset points according to their time value along the curve"), + "sort_points", &wr, this, true) + , interpolator_type( + _("Interpolator type:"), + _("Determines which kind of interpolator will be used to interpolate between stroke width along the path"), + "interpolator_type", InterpolatorTypeConverter, &wr, this, Geom::Interpolate::INTERP_CENTRIPETAL_CATMULLROM) + , interpolator_beta( + _("Smoothness:"), + _("Sets the smoothness for the CubicBezierJohan interpolator; 0 = linear interpolation, 1 = smooth"), + "interpolator_beta", &wr, this, 0.2) + , scale_width(_("Width factor:"), _("Scale the stroke's width uniformly along the whole path"), "scale_width", &wr, + this, 1.0) + , start_linecap_type(_("Start cap:"), _("Determines the shape of the path's start"), "start_linecap_type", + LineCapTypeConverter, &wr, this, LINECAP_ZERO_WIDTH) + , linejoin_type(_("Join:"), _("Determines the shape of the path's corners"), "linejoin_type", LineJoinTypeConverter, + &wr, this, LINEJOIN_ROUND) + , miter_limit(_("Miter limit:"), _("Maximum length of the miter (in units of stroke width)"), "miter_limit", &wr, + this, 4.) + , end_linecap_type(_("End cap:"), _("Determines the shape of the path's end"), "end_linecap_type", + LineCapTypeConverter, &wr, this, LINECAP_ZERO_WIDTH) { show_orig_path = true; /// @todo offset_points are initialized with empty path, is that bug-save? interpolator_beta.addSlider(true); - interpolator_beta.param_set_range(0.,1.); + interpolator_beta.param_set_range(0., 1.); registerParameter(&offset_points); registerParameter(¬_jump); @@ -193,8 +206,7 @@ LPEPowerStroke::LPEPowerStroke(LivePathEffectObject *lpeobject) : LPEPowerStroke::~LPEPowerStroke() = default; -void -LPEPowerStroke::doBeforeEffect(SPLPEItem const *lpeItem) +void LPEPowerStroke::doBeforeEffect(SPLPEItem const *lpeItem) { offset_points.set_scale_width(scale_width); if (has_recursion) { @@ -208,11 +220,10 @@ void LPEPowerStroke::applyStyle(SPLPEItem *lpeitem) lpe_shape_convert_stroke_and_fill(SP_SHAPE(lpeitem)); } -void -LPEPowerStroke::doOnApply(SPLPEItem const* lpeitem) +void LPEPowerStroke::doOnApply(SPLPEItem const *lpeitem) { if (auto shape = dynamic_cast(lpeitem)) { - SPLPEItem* item = const_cast(lpeitem); + SPLPEItem *item = const_cast(lpeitem); std::vector points; Geom::PathVector const &pathv = pathv_to_linear_and_cubic_beziers(shape->curve()->get_pathvector()); double width = (lpeitem && lpeitem->style) ? lpeitem->style->stroke_width.computed / 2 : 1.; @@ -226,7 +237,7 @@ LPEPowerStroke::doOnApply(SPLPEItem const* lpeitem) if (!clipboard && !powerpencil) { item->updateRepr(); if (pathv.empty()) { - points.emplace_back(0.2,width ); + points.emplace_back(0.2, width); points.emplace_back(0.5, width); points.emplace_back(0.8, width); } else { @@ -250,34 +261,31 @@ LPEPowerStroke::doOnApply(SPLPEItem const* lpeitem) } } -void LPEPowerStroke::doOnRemove(SPLPEItem const* lpeitem) +void LPEPowerStroke::doOnRemove(SPLPEItem const *lpeitem) { if (SP_IS_SHAPE(lpeitem) && !keep_paths) { - lpe_shape_revert_stroke_and_fill(SP_SHAPE(lpeitem), offset_points.median_width()*2); + lpe_shape_revert_stroke_and_fill(SP_SHAPE(lpeitem), offset_points.median_width() * 2); } } -void -LPEPowerStroke::adjustForNewPath(Geom::PathVector const & path_in) +void LPEPowerStroke::adjustForNewPath(Geom::PathVector const &path_in) { if (!path_in.empty()) { offset_points.recalculate_controlpoints_for_new_pwd2(path_in[0].toPwSb()); } } -static bool compare_offsets (Geom::Point first, Geom::Point second) +static bool compare_offsets(Geom::Point first, Geom::Point second) { return first[Geom::X] < second[Geom::X]; } -static Geom::Path path_from_piecewise_fix_cusps( Geom::Piecewise > const & B, - Geom::Piecewise const & y, // width path - LineJoinType jointype, - double miter_limit, - double tol=Geom::EPSILON) +static Geom::Path path_from_piecewise_fix_cusps(Geom::Piecewise> const &B, + Geom::Piecewise const &y, // width path + LineJoinType jointype, double miter_limit, double tol = Geom::EPSILON) { -/* per definition, each discontinuity should be fixed with a join-ending, as defined by linejoin_type -*/ + /* per definition, each discontinuity should be fixed with a join-ending, as defined by linejoin_type + */ Geom::PathBuilder pb; Geom::OptRect bbox = bounds_fast(B); if (B.empty() || !bbox) { @@ -290,142 +298,158 @@ static Geom::Path path_from_piecewise_fix_cusps( Geom::Piecewise 1e-5) + // the degeneracy/constancy test had to be loosened (eps > 1e-5) if (B[i].isConstant(1e-4)) { continue; } - if (!are_near(B[prev_i].at1(), B[i].at0(), tol) ) - { // discontinuity found, so fix it :-) - double width = y( B.cuts[i] ); + if (!are_near(B[prev_i].at1(), B[i].at0(), tol)) { // discontinuity found, so fix it :-) + double width = y(B.cuts[i]); - Geom::Point tang1 = -unitTangentAt(reverse(B[prev_i]),0.); // = unitTangentAt(B[prev_i],1); - Geom::Point tang2 = unitTangentAt(B[i],0); + Geom::Point tang1 = -unitTangentAt(reverse(B[prev_i]), 0.); // = unitTangentAt(B[prev_i],1); + Geom::Point tang2 = unitTangentAt(B[i], 0); Geom::Point discontinuity_vec = B[i].at0() - B[prev_i].at1(); - bool on_outside = ( dot(tang1, discontinuity_vec) >= 0. ); + bool on_outside = (dot(tang1, discontinuity_vec) >= 0.); if (on_outside) { // we are on the outside: add some type of join! switch (jointype) { - case LINEJOIN_ROUND: { - /* for constant width paths, the rounding is a circular arc (rx == ry), - for non-constant width paths, the rounding can be done with an ellipse but is hard and ambiguous. - The elliptical arc should go through the discontinuity's start and end points (of course!) - and also should match the discontinuity tangents at those start and end points. - To resolve the ambiguity, the elliptical arc with minimal eccentricity should be chosen. - A 2Geom method was created to do exactly this :) - */ - - boost::optional O = intersection_point( B[prev_i].at1(), tang1, - B[i].at0(), tang2 ); - if (!O) { - // no center found, i.e. 180 degrees round - pb.lineTo(B[i].at0()); // default to bevel for too shallow cusp angles - break; - } + case LINEJOIN_ROUND: { + /* for constant width paths, the rounding is a circular arc (rx == ry), + for non-constant width paths, the rounding can be done with an ellipse but is hard and + ambiguous. The elliptical arc should go through the discontinuity's start and end points (of + course!) and also should match the discontinuity tangents at those start and end points. To + resolve the ambiguity, the elliptical arc with minimal eccentricity should be chosen. A 2Geom + method was created to do exactly this :) + */ + + boost::optional O = intersection_point(B[prev_i].at1(), tang1, B[i].at0(), tang2); + if (!O) { + // no center found, i.e. 180 degrees round + pb.lineTo(B[i].at0()); // default to bevel for too shallow cusp angles + break; + } - Geom::Ellipse ellipse; - try { - ellipse = find_ellipse(B[prev_i].at1(), B[i].at0(), *O); - } - catch (Geom::LogicalError &e) { - // 2geom did not find a fitting ellipse, this happens for weird thick paths :) - // do bevel, and break - pb.lineTo(B[i].at0()); - break; - } + Geom::Ellipse ellipse; + try { + ellipse = find_ellipse(B[prev_i].at1(), B[i].at0(), *O); + } catch (Geom::LogicalError &e) { + // 2geom did not find a fitting ellipse, this happens for weird thick paths :) + // do bevel, and break + pb.lineTo(B[i].at0()); + break; + } - // check if ellipse.ray is within 'sane' range. - if ( ( fabs(ellipse.ray(Geom::X)) > 1e6 ) || - ( fabs(ellipse.ray(Geom::Y)) > 1e6 ) ) - { - // do bevel, and break - pb.lineTo(B[i].at0()); - break; - } + // check if ellipse.ray is within 'sane' range. + if ((fabs(ellipse.ray(Geom::X)) > 1e6) || (fabs(ellipse.ray(Geom::Y)) > 1e6)) { + // do bevel, and break + pb.lineTo(B[i].at0()); + break; + } - pb.arcTo( ellipse.ray(Geom::X), ellipse.ray(Geom::Y), ellipse.rotationAngle(), - false, width < 0, B[i].at0() ); + pb.arcTo(ellipse.ray(Geom::X), ellipse.ray(Geom::Y), ellipse.rotationAngle(), false, width < 0, + B[i].at0()); - break; - } - case LINEJOIN_EXTRP_MITER: { - Geom::D2 newcurve1 = B[prev_i] * Geom::reflection(rot90(tang1), B[prev_i].at1()); - Geom::CubicBezier bzr1 = sbasis_to_cubicbezier( reverse(newcurve1) ); + break; + } + case LINEJOIN_EXTRP_MITER: { + Geom::D2 newcurve1 = B[prev_i] * Geom::reflection(rot90(tang1), B[prev_i].at1()); + Geom::CubicBezier bzr1 = sbasis_to_cubicbezier(reverse(newcurve1)); - Geom::D2 newcurve2 = B[i] * Geom::reflection(rot90(tang2), B[i].at0()); - Geom::CubicBezier bzr2 = sbasis_to_cubicbezier( reverse(newcurve2) ); + Geom::D2 newcurve2 = B[i] * Geom::reflection(rot90(tang2), B[i].at0()); + Geom::CubicBezier bzr2 = sbasis_to_cubicbezier(reverse(newcurve2)); - Geom::Crossings cross = crossings(bzr1, bzr2); - if (cross.empty()) { - // empty crossing: default to bevel - pb.lineTo(B[i].at0()); - } else { - // check size of miter - Geom::Point point_on_path = B[prev_i].at1() - rot90(tang1) * width; - Geom::Coord len = distance(bzr1.pointAt(cross[0].ta), point_on_path); - if (len > fabs(width) * miter_limit) { - // miter too big: default to bevel + Geom::Crossings cross = crossings(bzr1, bzr2); + if (cross.empty()) { + // empty crossing: default to bevel pb.lineTo(B[i].at0()); } else { - std::pair sub1 = bzr1.subdivide(cross[0].ta); - std::pair sub2 = bzr2.subdivide(cross[0].tb); - pb.curveTo(sub1.first[1], sub1.first[2], sub1.first[3]); - pb.curveTo(sub2.second[1], sub2.second[2], sub2.second[3]); + // check size of miter + Geom::Point point_on_path = B[prev_i].at1() - rot90(tang1) * width; + Geom::Coord len = distance(bzr1.pointAt(cross[0].ta), point_on_path); + if (len > fabs(width) * miter_limit) { + // miter too big: default to bevel + pb.lineTo(B[i].at0()); + } else { + std::pair sub1 = bzr1.subdivide(cross[0].ta); + std::pair sub2 = bzr2.subdivide(cross[0].tb); + pb.curveTo(sub1.first[1], sub1.first[2], sub1.first[3]); + pb.curveTo(sub2.second[1], sub2.second[2], sub2.second[3]); + } } + break; } - break; - } - case LINEJOIN_EXTRP_MITER_ARC: { - // Extrapolate using the curvature at the end of the path segments to join - Geom::Circle circle1 = Geom::touching_circle(reverse(B[prev_i]), 0.0); - Geom::Circle circle2 = Geom::touching_circle(B[i], 0.0); - std::vector solutions; - solutions = circle1.intersect(circle2); - if (solutions.size() == 2) { - Geom::Point sol(0.,0.); - bool solok = true; - bool point0bad = false; - bool point1bad = false; - if ( dot(tang2, solutions[0].point() - B[i].at0()) > 0) - { - // points[0] is bad, choose points[1] - point0bad = true; - } - if ( dot(tang2, solutions[1].point() - B[i].at0()) > 0) - { - // points[1] is bad, choose points[0] - point1bad = true; - } - if (!point0bad && !point1bad ) { - // both points are good, choose nearest - sol = ( distanceSq(B[i].at0(), solutions[0].point()) < distanceSq(B[i].at0(), solutions[1].point()) ) ? - solutions[0].point() : solutions[1].point(); - } else if (!point0bad) { - sol = solutions[0].point(); - } else if (!point1bad) { - sol = solutions[1].point(); - } else { - solok = false; - } - (*bbox).expandBy (bbox->width()/4); + case LINEJOIN_EXTRP_MITER_ARC: { + // Extrapolate using the curvature at the end of the path segments to join + Geom::Circle circle1 = Geom::touching_circle(reverse(B[prev_i]), 0.0); + Geom::Circle circle2 = Geom::touching_circle(B[i], 0.0); + std::vector solutions; + solutions = circle1.intersect(circle2); + if (solutions.size() == 2) { + Geom::Point sol(0., 0.); + bool solok = true; + bool point0bad = false; + bool point1bad = false; + if (dot(tang2, solutions[0].point() - B[i].at0()) > 0) { + // points[0] is bad, choose points[1] + point0bad = true; + } + if (dot(tang2, solutions[1].point() - B[i].at0()) > 0) { + // points[1] is bad, choose points[0] + point1bad = true; + } + if (!point0bad && !point1bad) { + // both points are good, choose nearest + sol = (distanceSq(B[i].at0(), solutions[0].point()) < + distanceSq(B[i].at0(), solutions[1].point())) + ? solutions[0].point() + : solutions[1].point(); + } else if (!point0bad) { + sol = solutions[0].point(); + } else if (!point1bad) { + sol = solutions[1].point(); + } else { + solok = false; + } + (*bbox).expandBy(bbox->width() / 4); - if (!(*bbox).contains(sol)) { - solok = false; - } - Geom::EllipticalArc *arc0 = nullptr; - Geom::EllipticalArc *arc1 = nullptr; - bool build = false; - if (solok) { - arc0 = circle1.arc(B[prev_i].at1(), 0.5*(B[prev_i].at1()+sol), sol); - arc1 = circle2.arc(sol, 0.5*(sol+B[i].at0()), B[i].at0()); - if (arc0) { - // FIX: Some assertions errors here - build_from_sbasis(pb,arc0->toSBasis(), tol, false); - } else if (arc1) { - boost::optional p = intersection_point( B[prev_i].at1(), tang1, - B[i].at0(), tang2 ); + if (!(*bbox).contains(sol)) { + solok = false; + } + Geom::EllipticalArc *arc0 = nullptr; + Geom::EllipticalArc *arc1 = nullptr; + bool build = false; + if (solok) { + arc0 = circle1.arc(B[prev_i].at1(), 0.5 * (B[prev_i].at1() + sol), sol); + arc1 = circle2.arc(sol, 0.5 * (sol + B[i].at0()), B[i].at0()); + if (arc0) { + // FIX: Some assertions errors here + build_from_sbasis(pb, arc0->toSBasis(), tol, false); + } else if (arc1) { + boost::optional p = + intersection_point(B[prev_i].at1(), tang1, B[i].at0(), tang2); + if (p) { + // check size of miter + Geom::Point point_on_path = B[prev_i].at1() - rot90(tang1) * width; + Geom::Coord len = distance(*p, point_on_path); + if (len <= fabs(width) * miter_limit) { + // miter OK + pb.lineTo(*p); + build = true; + } + } + } + if (build) { + build_from_sbasis(pb, arc1->toSBasis(), tol, false); + } else if (arc0) { + pb.lineTo(B[i].at0()); + } + } + if (!solok || !(arc0 && build)) { + // fall back to miter + boost::optional p = + intersection_point(B[prev_i].at1(), tang1, B[i].at0(), tang2); if (p) { // check size of miter Geom::Point point_on_path = B[prev_i].at1() - rot90(tang1) * width; @@ -433,20 +457,22 @@ static Geom::Path path_from_piecewise_fix_cusps( Geom::PiecewisetoSBasis(), tol, false); - } else if (arc0) { pb.lineTo(B[i].at0()); } - } - if (!solok || !(arc0 && build)) { + if (arc0) { + delete arc0; + arc0 = nullptr; + } + if (arc1) { + delete arc1; + arc1 = nullptr; + } + } else { // fall back to miter - boost::optional p = intersection_point( B[prev_i].at1(), tang1, - B[i].at0(), tang2 ); + boost::optional p = + intersection_point(B[prev_i].at1(), tang1, B[i].at0(), tang2); if (p) { // check size of miter Geom::Point point_on_path = B[prev_i].at1() - rot90(tang1) * width; @@ -458,18 +484,18 @@ static Geom::Path path_from_piecewise_fix_cusps( Geom::Piecewise p = intersection_point( B[prev_i].at1(), tang1, - B[i].at0(), tang2 ); + /*else if (solutions == 1) { // one circle is inside the other + // don't know what to do: default to bevel + pb.lineTo(B[i].at0()); + } else { // no intersections + // don't know what to do: default to bevel + pb.lineTo(B[i].at0()); + } */ + + break; + } + case LINEJOIN_MITER: { + boost::optional p = intersection_point(B[prev_i].at1(), tang1, B[i].at0(), tang2); if (p) { // check size of miter Geom::Point point_on_path = B[prev_i].at1() - rot90(tang1) * width; @@ -480,68 +506,44 @@ static Geom::Path path_from_piecewise_fix_cusps( Geom::Piecewise p = intersection_point( B[prev_i].at1(), tang1, - B[i].at0(), tang2 ); - if (p) { - // check size of miter - Geom::Point point_on_path = B[prev_i].at1() - rot90(tang1) * width; - Geom::Coord len = distance(*p, point_on_path); - if (len <= fabs(width) * miter_limit) { - // miter OK - pb.lineTo(*p); - } + case LINEJOIN_SPIRO: { + Geom::Point direction = B[i].at0() - B[prev_i].at1(); + double tang1_sign = dot(direction, tang1); + double tang2_sign = dot(direction, tang2); + + Spiro::spiro_cp *controlpoints = g_new(Spiro::spiro_cp, 4); + controlpoints[0].x = (B[prev_i].at1() - tang1_sign * tang1)[Geom::X]; + controlpoints[0].y = (B[prev_i].at1() - tang1_sign * tang1)[Geom::Y]; + controlpoints[0].ty = '{'; + controlpoints[1].x = B[prev_i].at1()[Geom::X]; + controlpoints[1].y = B[prev_i].at1()[Geom::Y]; + controlpoints[1].ty = ']'; + controlpoints[2].x = B[i].at0()[Geom::X]; + controlpoints[2].y = B[i].at0()[Geom::Y]; + controlpoints[2].ty = '['; + controlpoints[3].x = (B[i].at0() + tang2_sign * tang2)[Geom::X]; + controlpoints[3].y = (B[i].at0() + tang2_sign * tang2)[Geom::Y]; + controlpoints[3].ty = '}'; + + Geom::Path spiro; + Spiro::spiro_run(controlpoints, 4, spiro); + pb.append(spiro.portion(1, spiro.size_open() - 1)); + break; } - pb.lineTo(B[i].at0()); - break; - } - case LINEJOIN_SPIRO: { - Geom::Point direction = B[i].at0() - B[prev_i].at1(); - double tang1_sign = dot(direction,tang1); - double tang2_sign = dot(direction,tang2); - - Spiro::spiro_cp *controlpoints = g_new (Spiro::spiro_cp, 4); - controlpoints[0].x = (B[prev_i].at1() - tang1_sign*tang1)[Geom::X]; - controlpoints[0].y = (B[prev_i].at1() - tang1_sign*tang1)[Geom::Y]; - controlpoints[0].ty = '{'; - controlpoints[1].x = B[prev_i].at1()[Geom::X]; - controlpoints[1].y = B[prev_i].at1()[Geom::Y]; - controlpoints[1].ty = ']'; - controlpoints[2].x = B[i].at0()[Geom::X]; - controlpoints[2].y = B[i].at0()[Geom::Y]; - controlpoints[2].ty = '['; - controlpoints[3].x = (B[i].at0() + tang2_sign*tang2)[Geom::X]; - controlpoints[3].y = (B[i].at0() + tang2_sign*tang2)[Geom::Y]; - controlpoints[3].ty = '}'; - - Geom::Path spiro; - Spiro::spiro_run(controlpoints, 4, spiro); - pb.append(spiro.portion(1, spiro.size_open() - 1)); - break; - } - case LINEJOIN_BEVEL: - default: - pb.lineTo(B[i].at0()); - break; + case LINEJOIN_BEVEL: + default: + pb.lineTo(B[i].at0()); + break; } build_from_sbasis(pb, B[i], tol, false); } else { // we are on inside of corner! - Geom::Path bzr1 = path_from_sbasis( B[prev_i], tol ); - Geom::Path bzr2 = path_from_sbasis( B[i], tol ); + Geom::Path bzr1 = path_from_sbasis(B[prev_i], tol); + Geom::Path bzr2 = path_from_sbasis(B[i], tol); Geom::Crossings cross = crossings(bzr1, bzr2); if (cross.size() != 1) { // empty crossing or too many crossings: default to bevel @@ -549,12 +551,12 @@ static Geom::Path path_from_piecewise_fix_cusps( Geom::Piecewise > pwd2_in = pathv[0].toPwSb(); + Geom::Piecewise> pwd2_in = pathv[0].toPwSb(); if (pwd2_in.empty()) { return path_in; } - Piecewise > der = derivative(pwd2_in); + Piecewise> der = derivative(pwd2_in); if (der.empty()) { return path_in; } - Piecewise > n = unitVector(der,0.00001); + Piecewise> n = unitVector(der, 0.00001); if (n.empty()) { return path_in; } @@ -602,7 +603,7 @@ LPEPowerStroke::doEffect_path (Geom::PathVector const & path_in) return path_in; } std::vector ts; - for (auto & tsp : ts_no_scale) { + for (auto &tsp : ts_no_scale) { Geom::Point p = Geom::Point(tsp[Geom::X], tsp[Geom::Y] * scale_width); ts.push_back(p); } @@ -610,18 +611,21 @@ LPEPowerStroke::doEffect_path (Geom::PathVector const & path_in) sort(ts.begin(), ts.end(), compare_offsets); } // create stroke path where points (x,y) := (t, offset) - Geom::Interpolate::Interpolator *interpolator = Geom::Interpolate::Interpolator::create(static_cast(interpolator_type.get_value())); - if (Geom::Interpolate::CubicBezierJohan *johan = dynamic_cast(interpolator)) { + Geom::Interpolate::Interpolator *interpolator = Geom::Interpolate::Interpolator::create( + static_cast(interpolator_type.get_value())); + if (Geom::Interpolate::CubicBezierJohan *johan = + dynamic_cast(interpolator)) { johan->setBeta(interpolator_beta); } - if (Geom::Interpolate::CubicBezierSmooth *smooth = dynamic_cast(interpolator)) { + if (Geom::Interpolate::CubicBezierSmooth *smooth = + dynamic_cast(interpolator)) { smooth->setBeta(interpolator_beta); } if (pathv[0].closed()) { std::vector ts_close; - //we have only one knot or overwrite before - Geom::Point start = Geom::Point( pwd2_in.domain().min(), ts.front()[Geom::Y]); - Geom::Point end = Geom::Point( pwd2_in.domain().max(), ts.front()[Geom::Y]); + // we have only one knot or overwrite before + Geom::Point start = Geom::Point(pwd2_in.domain().min(), ts.front()[Geom::Y]); + Geom::Point end = Geom::Point(pwd2_in.domain().max(), ts.front()[Geom::Y]); if (ts.size() > 1) { end = Geom::Point(pwd2_in.domain().max(), 0); Geom::Point tmpstart(0, 0); @@ -636,40 +640,40 @@ LPEPowerStroke::doEffect_path (Geom::PathVector const & path_in) start = end; start[Geom::X] = pwd2_in.domain().min(); } - ts.insert(ts.begin(), start ); - ts.push_back( end ); + ts.insert(ts.begin(), start); + ts.push_back(end); ts_close.clear(); } else { // add width data for first and last point on the path - // depending on cap type, these first and last points have width zero or take the width from the closest width point. - ts.insert(ts.begin(), Point( pwd2_in.domain().min(), - (start_linecap==LINECAP_ZERO_WIDTH) ? 0. : ts.front()[Geom::Y]) ); - ts.emplace_back( pwd2_in.domain().max(), - (end_linecap==LINECAP_ZERO_WIDTH) ? 0. : ts.back()[Geom::Y] ); + // depending on cap type, these first and last points have width zero or take the width from the closest width + // point. + ts.insert(ts.begin(), + Point(pwd2_in.domain().min(), (start_linecap == LINECAP_ZERO_WIDTH) ? 0. : ts.front()[Geom::Y])); + ts.emplace_back(pwd2_in.domain().max(), (end_linecap == LINECAP_ZERO_WIDTH) ? 0. : ts.back()[Geom::Y]); } // do the interpolation in a coordinate system that is more alike to the on-canvas knots, // instead of the heavily compressed coordinate system of (segment_no offset, Y) in which the knots are stored double pwd2_in_arclength = length(pwd2_in); double xcoord_scaling = pwd2_in_arclength / ts.back()[Geom::X]; - for (auto & t : ts) { + for (auto &t : ts) { t[Geom::X] *= xcoord_scaling; } - + Geom::Path strokepath = interpolator->interpolateToPath(ts); delete interpolator; // apply the inverse knot-xcoord scaling that was applied before the interpolation - strokepath *= Scale(1/xcoord_scaling, 1); + strokepath *= Scale(1 / xcoord_scaling, 1); - D2 > patternd2 = make_cuts_independent(strokepath.toPwSb()); + D2> patternd2 = make_cuts_independent(strokepath.toPwSb()); Piecewise x = Piecewise(patternd2[0]); Piecewise y = Piecewise(patternd2[1]); // find time values for which x lies outside path domain // and only take portion of x and y that lies within those time values - std::vector< double > rtsmin = roots (x - pwd2_in.domain().min()); - std::vector< double > rtsmax = roots (x + pwd2_in.domain().max()); - if ( !rtsmin.empty() && !rtsmax.empty() ) { + std::vector rtsmin = roots(x - pwd2_in.domain().min()); + std::vector rtsmax = roots(x + pwd2_in.domain().max()); + if (!rtsmin.empty() && !rtsmax.empty()) { x = portion(x, rtsmin.at(0), rtsmax.at(0)); y = portion(y, rtsmin.at(0), rtsmax.at(0)); } @@ -678,11 +682,12 @@ LPEPowerStroke::doEffect_path (Geom::PathVector const & path_in) if (x.empty() || y.empty()) { return path_in; } - Piecewise > pwd2_out = compose(pwd2_in,x) + y*compose(n,x); - Piecewise > mirrorpath = reverse( compose(pwd2_in,x) - y*compose(n,x)); + Piecewise> pwd2_out = compose(pwd2_in, x) + y * compose(n, x); + Piecewise> mirrorpath = reverse(compose(pwd2_in, x) - y * compose(n, x)); - Geom::Path fixed_path = path_from_piecewise_fix_cusps( pwd2_out, y, jointype, miter_limit, LPE_CONVERSION_TOLERANCE); - Geom::Path fixed_mirrorpath = path_from_piecewise_fix_cusps( mirrorpath, reverse(y), jointype, miter_limit, LPE_CONVERSION_TOLERANCE); + Geom::Path fixed_path = path_from_piecewise_fix_cusps(pwd2_out, y, jointype, miter_limit, LPE_CONVERSION_TOLERANCE); + Geom::Path fixed_mirrorpath = + path_from_piecewise_fix_cusps(mirrorpath, reverse(y), jointype, miter_limit, LPE_CONVERSION_TOLERANCE); if (pathv[0].closed()) { fixed_path.close(true); path_out.push_back(fixed_path); @@ -694,34 +699,32 @@ LPEPowerStroke::doEffect_path (Geom::PathVector const & path_in) case LINECAP_ZERO_WIDTH: // do nothing break; - case LINECAP_PEAK: - { - Geom::Point end_deriv = -unitTangentAt( reverse(pwd2_in.segs.back()), 0.); + case LINECAP_PEAK: { + Geom::Point end_deriv = -unitTangentAt(reverse(pwd2_in.segs.back()), 0.); double radius = 0.5 * distance(fixed_path.finalPoint(), fixed_mirrorpath.initialPoint()); - Geom::Point midpoint = 0.5*(fixed_path.finalPoint() + fixed_mirrorpath.initialPoint()) + radius*end_deriv; + Geom::Point midpoint = + 0.5 * (fixed_path.finalPoint() + fixed_mirrorpath.initialPoint()) + radius * end_deriv; fixed_path.appendNew(midpoint); fixed_path.appendNew(fixed_mirrorpath.initialPoint()); break; } - case LINECAP_SQUARE: - { - Geom::Point end_deriv = -unitTangentAt( reverse(pwd2_in.segs.back()), 0.); + case LINECAP_SQUARE: { + Geom::Point end_deriv = -unitTangentAt(reverse(pwd2_in.segs.back()), 0.); double radius = 0.5 * distance(fixed_path.finalPoint(), fixed_mirrorpath.initialPoint()); - fixed_path.appendNew( fixed_path.finalPoint() + radius*end_deriv ); - fixed_path.appendNew( fixed_mirrorpath.initialPoint() + radius*end_deriv ); - fixed_path.appendNew( fixed_mirrorpath.initialPoint() ); + fixed_path.appendNew(fixed_path.finalPoint() + radius * end_deriv); + fixed_path.appendNew(fixed_mirrorpath.initialPoint() + radius * end_deriv); + fixed_path.appendNew(fixed_mirrorpath.initialPoint()); break; } - case LINECAP_BUTT: - { - fixed_path.appendNew( fixed_mirrorpath.initialPoint() ); + case LINECAP_BUTT: { + fixed_path.appendNew(fixed_mirrorpath.initialPoint()); break; } case LINECAP_ROUND: - default: - { + default: { double radius1 = 0.5 * distance(fixed_path.finalPoint(), fixed_mirrorpath.initialPoint()); - fixed_path.appendNew( radius1, radius1, M_PI/2., false, y.lastValue() < 0, fixed_mirrorpath.initialPoint() ); + fixed_path.appendNew(radius1, radius1, M_PI / 2., false, y.lastValue() < 0, + fixed_mirrorpath.initialPoint()); break; } } @@ -731,34 +734,32 @@ LPEPowerStroke::doEffect_path (Geom::PathVector const & path_in) case LINECAP_ZERO_WIDTH: // do nothing break; - case LINECAP_PEAK: - { - Geom::Point start_deriv = unitTangentAt( pwd2_in.segs.front(), 0.); + case LINECAP_PEAK: { + Geom::Point start_deriv = unitTangentAt(pwd2_in.segs.front(), 0.); double radius = 0.5 * distance(fixed_path.initialPoint(), fixed_mirrorpath.finalPoint()); - Geom::Point midpoint = 0.5*(fixed_mirrorpath.finalPoint() + fixed_path.initialPoint()) - radius*start_deriv; - fixed_path.appendNew( midpoint ); - fixed_path.appendNew( fixed_path.initialPoint() ); + Geom::Point midpoint = + 0.5 * (fixed_mirrorpath.finalPoint() + fixed_path.initialPoint()) - radius * start_deriv; + fixed_path.appendNew(midpoint); + fixed_path.appendNew(fixed_path.initialPoint()); break; } - case LINECAP_SQUARE: - { - Geom::Point start_deriv = unitTangentAt( pwd2_in.segs.front(), 0.); + case LINECAP_SQUARE: { + Geom::Point start_deriv = unitTangentAt(pwd2_in.segs.front(), 0.); double radius = 0.5 * distance(fixed_path.initialPoint(), fixed_mirrorpath.finalPoint()); - fixed_path.appendNew( fixed_mirrorpath.finalPoint() - radius*start_deriv ); - fixed_path.appendNew( fixed_path.initialPoint() - radius*start_deriv ); - fixed_path.appendNew( fixed_path.initialPoint() ); + fixed_path.appendNew(fixed_mirrorpath.finalPoint() - radius * start_deriv); + fixed_path.appendNew(fixed_path.initialPoint() - radius * start_deriv); + fixed_path.appendNew(fixed_path.initialPoint()); break; } - case LINECAP_BUTT: - { - fixed_path.appendNew( fixed_path.initialPoint() ); + case LINECAP_BUTT: { + fixed_path.appendNew(fixed_path.initialPoint()); break; } case LINECAP_ROUND: - default: - { + default: { double radius2 = 0.5 * distance(fixed_path.initialPoint(), fixed_mirrorpath.finalPoint()); - fixed_path.appendNew( radius2, radius2, M_PI/2., false, y.firstValue() < 0, fixed_path.initialPoint() ); + fixed_path.appendNew(radius2, radius2, M_PI / 2., false, y.firstValue() < 0, + fixed_path.initialPoint()); break; } } @@ -800,7 +801,7 @@ void LPEPowerStroke::doAfterEffect(SPLPEItem const *lpeitem) /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-powerstroke.h b/src/live_effects/lpe-powerstroke.h index 8a4029b788f0a59c28220f8e83cbefbb0be515d7..9aaf2a27fe66dde1ebd78f334870fddfb3773818 100644 --- a/src/live_effects/lpe-powerstroke.h +++ b/src/live_effects/lpe-powerstroke.h @@ -22,35 +22,44 @@ namespace Inkscape { namespace LivePathEffect { -enum LineCapType { LINECAP_BUTT, LINECAP_SQUARE, LINECAP_ROUND, LINECAP_PEAK, LINECAP_ZERO_WIDTH }; +enum LineCapType +{ + LINECAP_BUTT, + LINECAP_SQUARE, + LINECAP_ROUND, + LINECAP_PEAK, + LINECAP_ZERO_WIDTH +}; -static const Util::EnumData LineCapTypeData[] = { { LINECAP_BUTT, N_("Butt"), "butt" }, - { LINECAP_SQUARE, N_("Square"), "square" }, - { LINECAP_ROUND, N_("Round"), "round" }, - { LINECAP_PEAK, N_("Peak"), "peak" }, - { LINECAP_ZERO_WIDTH, N_("Zero width"), "zerowidth" } }; +static const Util::EnumData LineCapTypeData[] = {{LINECAP_BUTT, N_("Butt"), "butt"}, + {LINECAP_SQUARE, N_("Square"), "square"}, + {LINECAP_ROUND, N_("Round"), "round"}, + {LINECAP_PEAK, N_("Peak"), "peak"}, + {LINECAP_ZERO_WIDTH, N_("Zero width"), "zerowidth"}}; static const Util::EnumDataConverter LineCapTypeConverter(LineCapTypeData, sizeof(LineCapTypeData) / sizeof(*LineCapTypeData)); -class LPEPowerStroke : public Effect { +class LPEPowerStroke : public Effect +{ public: LPEPowerStroke(LivePathEffectObject *lpeobject); ~LPEPowerStroke() override; - LPEPowerStroke(const LPEPowerStroke&) = delete; - LPEPowerStroke& operator=(const LPEPowerStroke&) = delete; - - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + LPEPowerStroke(const LPEPowerStroke &) = delete; + LPEPowerStroke &operator=(const LPEPowerStroke &) = delete; + + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; void doBeforeEffect(SPLPEItem const *lpeItem) override; - void doOnApply(SPLPEItem const* lpeitem) override; - void doOnRemove(SPLPEItem const* lpeitem) override; + void doOnApply(SPLPEItem const *lpeitem) override; + void doOnRemove(SPLPEItem const *lpeitem) override; void doAfterEffect(SPLPEItem const *lpeitem) override; void transform_multiply(Geom::Affine const &postmul, bool set) override; void applyStyle(SPLPEItem *lpeitem); // methods called by path-manipulator upon edits - void adjustForNewPath(Geom::PathVector const & path_in); + void adjustForNewPath(Geom::PathVector const &path_in); PowerStrokePointArrayParam offset_points; BoolParam not_jump; + private: BoolParam sort_points; EnumParam interpolator_type; @@ -64,8 +73,8 @@ private: bool has_recursion; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-pts2ellipse.cpp b/src/live_effects/lpe-pts2ellipse.cpp index 8559bf499c6000ab7f521056cd99b11e3c35b2fd..fbe66ab876cf3c4e16619e570ac59f00118c76f5 100644 --- a/src/live_effects/lpe-pts2ellipse.cpp +++ b/src/live_effects/lpe-pts2ellipse.cpp @@ -14,48 +14,46 @@ #include "lpe-pts2ellipse.h" - -#include -#include -#include -#include -#include - #include <2geom/circle.h> #include <2geom/ellipse.h> #include <2geom/elliptical-arc.h> #include <2geom/path.h> #include <2geom/pathvector.h> - #include +#include +#include +#include +#include +#include namespace Inkscape { namespace LivePathEffect { static const Util::EnumData EllipseMethodData[] = { - { EM_AUTO, N_("Auto ellipse"), "auto" }, //!< (2..4 points: circle, from 5 points: ellipse) - { EM_CIRCLE, N_("Force circle"), "circle" }, //!< always fit a circle - { EM_ISOMETRIC_CIRCLE, N_("Isometric circle"), "iso_circle" }, //!< use first two edges to generate a sheared - //!< ellipse - { EM_PERSPECTIVE_CIRCLE, N_("Perspective circle"), "perspective_circle" }, //!< use first three edges to generate an - //!< ellipse representing a distorted - //!< circle in perspective - { EM_STEINER_ELLIPSE, N_("Steiner ellipse"), "steiner_ellipse" }, //!< generate a steiner ellipse from the first - //!< three points - { EM_STEINER_INELLIPSE, N_("Steiner inellipse"), "steiner_inellipse" } //!< generate a steiner inellipse from the - //!< first three points + {EM_AUTO, N_("Auto ellipse"), "auto"}, //!< (2..4 points: circle, from 5 points: ellipse) + {EM_CIRCLE, N_("Force circle"), "circle"}, //!< always fit a circle + {EM_ISOMETRIC_CIRCLE, N_("Isometric circle"), "iso_circle"}, //!< use first two edges to generate a sheared + //!< ellipse + {EM_PERSPECTIVE_CIRCLE, N_("Perspective circle"), "perspective_circle"}, //!< use first three edges to generate an + //!< ellipse representing a distorted + //!< circle in perspective + {EM_STEINER_ELLIPSE, N_("Steiner ellipse"), "steiner_ellipse"}, //!< generate a steiner ellipse from the first + //!< three points + {EM_STEINER_INELLIPSE, N_("Steiner inellipse"), "steiner_inellipse"} //!< generate a steiner inellipse from the + //!< first three points }; static const Util::EnumDataConverter EMConverter(EllipseMethodData, EM_END); LPEPts2Ellipse::LPEPts2Ellipse(LivePathEffectObject *lpeobject) : Effect(lpeobject) - , method( - _("Method:"), - _("Methods to generate the ellipse\n- Auto ellipse: fits a circle (2, 3 or 4 nodes in the path) or an ellipse (at least 5 " - "nodes)\n- Force circle: (at least 2 nodes) always create a circle\n- Isometric circle: (3 nodes) use " - "first two segments as edges\n- Perspective circle: (4 nodes) circle in a square in perspective view\n- Steiner " - "ellipse: (3 nodes) ellipse on a triangle\n- Steiner inellipse: (3 nodes) ellipse inside a triangle"), - "method", EMConverter, &wr, this, EM_AUTO) + , method(_("Method:"), + _("Methods to generate the ellipse\n- Auto ellipse: fits a circle (2, 3 or 4 nodes in the path) or an " + "ellipse (at least 5 " + "nodes)\n- Force circle: (at least 2 nodes) always create a circle\n- Isometric circle: (3 nodes) use " + "first two segments as edges\n- Perspective circle: (4 nodes) circle in a square in perspective view\n- " + "Steiner " + "ellipse: (3 nodes) ellipse on a triangle\n- Steiner inellipse: (3 nodes) ellipse inside a triangle"), + "method", EMConverter, &wr, this, EM_AUTO) , gen_isometric_frame(_("_Frame (isometric rectangle)"), _("Draw parallelogram around the ellipse"), "gen_isometric_frame", &wr, this, false) , gen_perspective_frame( @@ -111,9 +109,15 @@ inline double range2pi(double a) return a; } -inline double deg2rad(double a) { return a * M_PI / 180.0; } +inline double deg2rad(double a) +{ + return a * M_PI / 180.0; +} -inline double rad2deg(double a) { return a * 180.0 / M_PI; } +inline double rad2deg(double a) +{ + return a * 180.0 / M_PI; +} // helper function, calculates the angle between a0 and a1 in ccw sense // examples: 0..1->1, -1..1->2, pi/4..-pi/4->1.5pi @@ -202,7 +206,7 @@ void LPEPts2Ellipse::gen_iso_frame_paths(Geom::PathVector &path_out, const Geom: void LPEPts2Ellipse::gen_perspective_frame_paths(Geom::PathVector &path_out, const double rot_angle, double projmatrix[3][3]) { - Geom::Point pts0[4] = { { -1.0, -1.0 }, { +1.0, -1.0 }, { +1.0, +1.0 }, { -1.0, +1.0 } }; + Geom::Point pts0[4] = {{-1.0, -1.0}, {+1.0, -1.0}, {+1.0, +1.0}, {-1.0, +1.0}}; // five_pts.resize(4); Geom::Affine affine2; // const double rot_angle = deg2rad(rot_axes); // negative for ccw rotation @@ -316,7 +320,6 @@ Geom::PathVector LPEPts2Ellipse::doEffect_path(Geom::PathVector const &path_in) path_out.insert(path_out.end(), path_in.begin(), path_in.end()); } - // 2) get all points // (from: extension/internal/odf.cpp) points.resize(0); @@ -645,9 +648,9 @@ int LPEPts2Ellipse::genPerspectiveEllipse(std::vector const &pts, G // 1) check if the first three edges are a valid perspective // calc edge - Geom::Point e[] = { pts[0] - pts[1], pts[1] - pts[2], pts[2] - pts[3], pts[3] - pts[0] }; + Geom::Point e[] = {pts[0] - pts[1], pts[1] - pts[2], pts[2] - pts[3], pts[3] - pts[0]}; // calc directions - Geom::Coord c[] = { cross(e[0], e[1]), cross(e[1], e[2]), cross(e[2], e[3]), cross(e[3], e[0]) }; + Geom::Coord c[] = {cross(e[0], e[1]), cross(e[1], e[2]), cross(e[2], e[3]), cross(e[3], e[0])}; // is this quad not convex? if (!((c[0] > 0 && c[1] > 0 && c[2] > 0 && c[3] > 0) || (c[0] < 0 && c[1] < 0 && c[2] < 0 && c[3] < 0))) return -1; @@ -656,11 +659,11 @@ int LPEPts2Ellipse::genPerspectiveEllipse(std::vector const &pts, G // https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/) // the square points in the initial configuration (about the unit circle): - Geom::Point pts0[4] = { { -1.0, -1.0 }, { +1.0, -1.0 }, { +1.0, +1.0 }, { -1.0, +1.0 } }; + Geom::Point pts0[4] = {{-1.0, -1.0}, {+1.0, -1.0}, {+1.0, +1.0}, {-1.0, +1.0}}; // build equation in matrix form - double eqnVec[8] = { 0 }; - double eqnMat[64] = { 0 }; + double eqnVec[8] = {0}; + double eqnMat[64] = {0}; for (unsigned int i = 0; i < 4; ++i) { eqnMat[8 * (i + 0) + 0] = pts0[i][X]; eqnMat[8 * (i + 0) + 1] = pts0[i][Y]; @@ -753,7 +756,6 @@ int LPEPts2Ellipse::genPerspectiveEllipse(std::vector const &pts, G return 0; } - /* ######################## */ } // namespace LivePathEffect diff --git a/src/live_effects/lpe-pts2ellipse.h b/src/live_effects/lpe-pts2ellipse.h index 3ccf0c4bb9963b8d3164b0116e968e46acaebdd7..0e844c0117d72df87832571e538aee2b34265a68 100644 --- a/src/live_effects/lpe-pts2ellipse.h +++ b/src/live_effects/lpe-pts2ellipse.h @@ -15,20 +15,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include + #include "live_effects/effect.h" #include "live_effects/parameter/bool.h" #include "live_effects/parameter/enum.h" -#include - - // struct gsl_vector; // struct gsl_permutation; namespace Inkscape { namespace LivePathEffect { -enum EllipseMethod { +enum EllipseMethod +{ EM_AUTO, EM_CIRCLE, EM_ISOMETRIC_CIRCLE, @@ -38,18 +38,18 @@ enum EllipseMethod { EM_END }; -class LPEPts2Ellipse : public Effect { - public: +class LPEPts2Ellipse : public Effect +{ +public: LPEPts2Ellipse(LivePathEffectObject *lpeobject); ~LPEPts2Ellipse() override; Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; - private: +private: LPEPts2Ellipse(const LPEPts2Ellipse &) = delete; LPEPts2Ellipse &operator=(const LPEPts2Ellipse &) = delete; - int genIsometricEllipse(std::vector const &points_in, Geom::PathVector &path_out); int genFitEllipse(std::vector const &points_in, Geom::PathVector &path_out); diff --git a/src/live_effects/lpe-recursiveskeleton.cpp b/src/live_effects/lpe-recursiveskeleton.cpp index 0a67cdbbc7a66777341f853909d26e3388e756c8..26fc1b42159a7f4970a9ab16d56da77381a8209f 100644 --- a/src/live_effects/lpe-recursiveskeleton.cpp +++ b/src/live_effects/lpe-recursiveskeleton.cpp @@ -21,92 +21,91 @@ namespace Inkscape { namespace LivePathEffect { -LPERecursiveSkeleton::LPERecursiveSkeleton(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - iterations(_("Iterations:"), _("recursivity"), "iterations", &wr, this, 2) +LPERecursiveSkeleton::LPERecursiveSkeleton(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , iterations(_("Iterations:"), _("recursivity"), "iterations", &wr, this, 2) { show_orig_path = true; concatenate_before_pwd2 = true; iterations.param_make_integer(true); iterations.param_set_range(1, 15); registerParameter(&iterations); - } -LPERecursiveSkeleton::~LPERecursiveSkeleton() -= default; - +LPERecursiveSkeleton::~LPERecursiveSkeleton() = default; -Geom::Piecewise > -LPERecursiveSkeleton::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPERecursiveSkeleton::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; - Piecewise > output; + Piecewise> output; double prop_scale = 1.0; - D2 > patternd2 = make_cuts_independent(pwd2_in); - Piecewise x0 = false /*vertical_pattern.get_value()*/ ? Piecewise(patternd2[1]) : Piecewise(patternd2[0]); - Piecewise y0 = false /*vertical_pattern.get_value()*/ ? Piecewise(patternd2[0]) : Piecewise(patternd2[1]); + D2> patternd2 = make_cuts_independent(pwd2_in); + Piecewise x0 = + false /*vertical_pattern.get_value()*/ ? Piecewise(patternd2[1]) : Piecewise(patternd2[0]); + Piecewise y0 = + false /*vertical_pattern.get_value()*/ ? Piecewise(patternd2[0]) : Piecewise(patternd2[1]); OptInterval pattBndsX = bounds_exact(x0); OptInterval pattBndsY = bounds_exact(y0); - if ( !pattBndsX || !pattBndsY) { + if (!pattBndsX || !pattBndsY) { return pwd2_in; } x0 -= pattBndsX->min(); y0 -= pattBndsY->middle(); - double noffset = 0;//normal_offset; - double toffset = 0;//tang_offset; - if (false /*prop_units.get_value()*/){ + double noffset = 0; // normal_offset; + double toffset = 0; // tang_offset; + if (false /*prop_units.get_value()*/) { noffset *= pattBndsY->extent(); toffset *= pattBndsX->extent(); } - y0+=noffset; + y0 += noffset; output = pwd2_in; for (int i = 0; i < iterations; ++i) { - std::vector > > skeleton = split_at_discontinuities(output); + std::vector>> skeleton = split_at_discontinuities(output); output.clear(); - for (auto path_i : skeleton){ + for (auto path_i : skeleton) { Piecewise x = x0; Piecewise y = y0; - Piecewise > uskeleton = arc_length_parametrization(path_i,2,.1); - uskeleton = remove_short_cuts(uskeleton,.01); - Piecewise > n = rot90(derivative(uskeleton)); - n = force_continuity(remove_short_cuts(n,.1)); + Piecewise> uskeleton = arc_length_parametrization(path_i, 2, .1); + uskeleton = remove_short_cuts(uskeleton, .01); + Piecewise> n = rot90(derivative(uskeleton)); + n = force_continuity(remove_short_cuts(n, .1)); - double scaling = (uskeleton.domain().extent() - toffset)/pattBndsX->extent(); + double scaling = (uskeleton.domain().extent() - toffset) / pattBndsX->extent(); // TODO investigate why pattWidth is not being used: // - Doesn't appear to have been used anywhere in bzr history (Alex V: 2013-03-16) // double pattWidth = pattBndsX->extent() * scaling; if (scaling != 1.0) { - x*=scaling; + x *= scaling; } - if ( true /*scale_y_rel.get_value()*/ ) { - y*=(scaling*prop_scale); + if (true /*scale_y_rel.get_value()*/) { + y *= (scaling * prop_scale); } else { - if (prop_scale != 1.0) y *= prop_scale; + if (prop_scale != 1.0) + y *= prop_scale; } x += toffset; - output.concat(compose(uskeleton,x)+y*compose(n,x)); + output.concat(compose(uskeleton, x) + y * compose(n, x)); } } return output; } - -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-recursiveskeleton.h b/src/live_effects/lpe-recursiveskeleton.h index 1347befd40c28f5a79171c9fc3377e9a621bd949..6f4cd6aabf9982197628ed535627636f6a1b0b74 100644 --- a/src/live_effects/lpe-recursiveskeleton.h +++ b/src/live_effects/lpe-recursiveskeleton.h @@ -19,23 +19,24 @@ namespace Inkscape { namespace LivePathEffect { - -class LPERecursiveSkeleton : public Effect { +class LPERecursiveSkeleton : public Effect +{ public: LPERecursiveSkeleton(LivePathEffectObject *lpeobject); ~LPERecursiveSkeleton() override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; private: ScalarParam iterations; - LPERecursiveSkeleton(const LPERecursiveSkeleton&) = delete; - LPERecursiveSkeleton& operator=(const LPERecursiveSkeleton&) = delete; + LPERecursiveSkeleton(const LPERecursiveSkeleton &) = delete; + LPERecursiveSkeleton &operator=(const LPERecursiveSkeleton &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-rough-hatches.cpp b/src/live_effects/lpe-rough-hatches.cpp index acda1f40172749227b22193b1c93897b7e5e2a5b..a551bd0113bd82521eb7f5ec7cec4ae97824cdf6 100644 --- a/src/live_effects/lpe-rough-hatches.cpp +++ b/src/live_effects/lpe-rough-hatches.cpp @@ -13,16 +13,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/scalar.h" #include "live_effects/lpe-rough-hatches.h" -#include "object/sp-item.h" +#include <2geom/bezier-to-sbasis.h> +#include <2geom/sbasis-math.h> +#include "object/sp-item.h" +#include "ui/widget/scalar.h" #include "xml/repr.h" -#include <2geom/sbasis-math.h> -#include <2geom/bezier-to-sbasis.h> - // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -34,77 +33,82 @@ using namespace Geom; //------------------------------------------------ // Some goodies to navigate through curve's levels. //------------------------------------------------ -struct LevelCrossing{ +struct LevelCrossing +{ Point pt; double t; bool sign; bool used; - std::pair next_on_curve; - std::pair prev_on_curve; + std::pair next_on_curve; + std::pair prev_on_curve; }; -struct LevelCrossingOrder { - bool operator()(LevelCrossing a, LevelCrossing b) { - return ( a.pt[Y] < b.pt[Y] );// a.pt[X] == b.pt[X] since we are supposed to be on the same level... - //return ( a.pt[X] < b.pt[X] || ( a.pt[X] == b.pt[X] && a.pt[Y] < b.pt[Y] ) ); +struct LevelCrossingOrder +{ + bool operator()(LevelCrossing a, LevelCrossing b) + { + return (a.pt[Y] < b.pt[Y]); // a.pt[X] == b.pt[X] since we are supposed to be on the same level... + // return ( a.pt[X] < b.pt[X] || ( a.pt[X] == b.pt[X] && a.pt[Y] < b.pt[Y] ) ); } }; -struct LevelCrossingInfo{ +struct LevelCrossingInfo +{ double t; unsigned level; unsigned idx; }; -struct LevelCrossingInfoOrder { - bool operator()(LevelCrossingInfo a, LevelCrossingInfo b) { - return a.t < b.t; - } +struct LevelCrossingInfoOrder +{ + bool operator()(LevelCrossingInfo a, LevelCrossingInfo b) { return a.t < b.t; } }; typedef std::vector LevelCrossings; -static std::vector -discontinuities(Piecewise > const &f){ +static std::vector discontinuities(Piecewise> const &f) +{ std::vector result; - if (f.size()==0) return result; + if (f.size() == 0) + return result; result.push_back(f.cuts[0]); Point prev_pt = f.segs[0].at1(); - //double old_t = f.cuts[0]; - for(unsigned i=1; i{ +class LevelsCrossings : public std::vector +{ public: - LevelsCrossings():std::vector(){}; - LevelsCrossings(std::vector > const ×, - Piecewise > const &f, - Piecewise const &dx){ - - for (const auto & time : times){ + LevelsCrossings() + : std::vector(){}; + LevelsCrossings(std::vector> const ×, Piecewise> const &f, + Piecewise const &dx) + { + for (const auto &time : times) { LevelCrossings lcs; - for (double j : time){ + for (double j : time) { LevelCrossing lc; lc.pt = f.valueAt(j); lc.t = j; - lc.sign = ( dx.valueAt(j)>0 ); + lc.sign = (dx.valueAt(j) > 0); lc.used = false; lcs.push_back(lc); } std::sort(lcs.begin(), lcs.end(), LevelCrossingOrder()); push_back(lcs); } - //Now create time ordering. - std::vectortemp; - for (unsigned i=0; i temp; + for (unsigned i = 0; i < size(); i++) { + for (unsigned j = 0; j < (*this)[i].size(); j++) { LevelCrossingInfo elem; elem.t = (*this)[i][j].t; elem.level = i; @@ -112,37 +116,38 @@ public: temp.push_back(elem); } } - std::sort(temp.begin(),temp.end(),LevelCrossingInfoOrder()); + std::sort(temp.begin(), temp.end(), LevelCrossingInfoOrder()); std::vector jumps = discontinuities(f); unsigned jump_idx = 0; unsigned first_in_comp = 0; - for (unsigned i=0; i jumps[jump_idx+1]){ - std::pairnext_data(temp[first_in_comp].level,temp[first_in_comp].idx); + if (i == temp.size() - 1 || temp[i + 1].t > jumps[jump_idx + 1]) { + std::pair next_data(temp[first_in_comp].level, temp[first_in_comp].idx); (*this)[lvl][idx].next_on_curve = next_data; - first_in_comp = i+1; + first_in_comp = i + 1; jump_idx += 1; - }else{ - std::pair next_data(temp[i+1].level,temp[i+1].idx); + } else { + std::pair next_data(temp[i + 1].level, temp[i + 1].idx); (*this)[lvl][idx].next_on_curve = next_data; } } - for (unsigned i=0; i next = (*this)[i][j].next_on_curve; - (*this)[next.first][next.second].prev_on_curve = std::pair(i,j); + for (unsigned i = 0; i < size(); i++) { + for (unsigned j = 0; j < (*this)[i].size(); j++) { + std::pair next = (*this)[i][j].next_on_curve; + (*this)[next.first][next.second].prev_on_curve = std::pair(i, j); } } } - void findFirstUnused(unsigned &level, unsigned &idx){ + void findFirstUnused(unsigned &level, unsigned &idx) + { level = size(); idx = 0; - for (unsigned i=0; i= (*this)[level].size()-1 || (*this)[level][idx+1].used ) { + if (idx >= (*this)[level].size() - 1 || (*this)[level][idx + 1].used) { level = size(); return; } idx += 1; - }else{ - if ( idx <= 0 || (*this)[level][idx-1].used ) { + } else { + if (idx <= 0 || (*this)[level][idx - 1].used) { level = size(); return; } @@ -174,23 +180,23 @@ public: direction += 1; return; } - //double t = (*this)[level][idx].t; + // double t = (*this)[level][idx].t; double sign = ((*this)[level][idx].sign ? 1 : -1); //---double next_t = t; - //level += 1; - direction = (direction + 1)%4; - if (level == size()){ + // level += 1; + direction = (direction + 1) % 4; + if (level == size()) { return; } - std::pair next; - if ( sign > 0 ){ + std::pair next; + if (sign > 0) { next = (*this)[level][idx].next_on_curve; - }else{ + } else { next = (*this)[level][idx].prev_on_curve; } - if ( level+1 != next.first || (*this)[next.first][next.second].used ) { + if (level + 1 != next.first || (*this)[next.first][next.second].used) { level = size(); return; } @@ -204,8 +210,9 @@ public: // Bend a path... //------------------------------------------------------- -static Piecewise > bend(Piecewise > const &f, Piecewise bending){ - D2 > ff = make_cuts_independent(f); +static Piecewise> bend(Piecewise> const &f, Piecewise bending) +{ + D2> ff = make_cuts_independent(f); ff[X] += compose(bending, ff[Y]); return sectionize(ff); } @@ -213,34 +220,59 @@ static Piecewise > bend(Piecewise > const &f, Piecewise > -LPERoughHatches::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in){ - - //std::cout<<"doEffect_pwd2:\n"; +Geom::Piecewise> +LPERoughHatches::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) +{ + // std::cout<<"doEffect_pwd2:\n"; - Piecewise > result; + Piecewise> result; - Piecewise > transformed_pwd2_in = pwd2_in; + Piecewise> transformed_pwd2_in = pwd2_in; Point start = pwd2_in.segs.front().at0(); Point end = pwd2_in.segs.back().at1(); - if (end != start ){ - transformed_pwd2_in.push_cut( transformed_pwd2_in.cuts.back() + 1 ); - D2 stitch( SBasis( 1, Linear(end[X],start[X]) ), SBasis( 1, Linear(end[Y],start[Y]) ) ); - transformed_pwd2_in.push_seg( stitch ); + if (end != start) { + transformed_pwd2_in.push_cut(transformed_pwd2_in.cuts.back() + 1); + D2 stitch(SBasis(1, Linear(end[X], start[X])), SBasis(1, Linear(end[Y], start[Y]))); + transformed_pwd2_in.push_seg(stitch); } Point transformed_org = direction.getOrigin(); - Piecewise tilter;//used to bend the hatches - Affine bend_mat;//used to bend the hatches + Piecewise tilter; // used to bend the hatches + Affine bend_mat; // used to bend the hatches - if (do_bend.get_value()){ + if (do_bend.get_value()) { Point bend_dir = -rot90(unit_vector(bender.getVector())); double bend_amount = L2(bender.getVector()); - bend_mat = Affine(-bend_dir[Y], bend_dir[X], bend_dir[X], bend_dir[Y],0,0); + bend_mat = Affine(-bend_dir[Y], bend_dir[X], bend_dir[X], bend_dir[Y], 0, 0); transformed_pwd2_in = transformed_pwd2_in * bend_mat; - tilter = Piecewise(shift(Linear(-bend_amount),1)); - OptRect bbox = bounds_exact( transformed_pwd2_in ); - if (!(bbox)) return pwd2_in; + tilter = Piecewise(shift(Linear(-bend_amount), 1)); + OptRect bbox = bounds_exact(transformed_pwd2_in); + if (!(bbox)) + return pwd2_in; tilter.setDomain((*bbox)[Y]); transformed_pwd2_in = bend(transformed_pwd2_in, tilter); transformed_pwd2_in = transformed_pwd2_in * bend_mat.inverse(); } - hatch_dist = Geom::L2(direction.getVector())/5; + hatch_dist = Geom::L2(direction.getVector()) / 5; Point hatches_dir = rot90(unit_vector(direction.getVector())); - Affine mat(-hatches_dir[Y], hatches_dir[X], hatches_dir[X], hatches_dir[Y],0,0); + Affine mat(-hatches_dir[Y], hatches_dir[X], hatches_dir[X], hatches_dir[Y], 0, 0); transformed_pwd2_in = transformed_pwd2_in * mat; transformed_org *= mat; - std::vector > snakePoints; + std::vector> snakePoints; snakePoints = linearSnake(transformed_pwd2_in, transformed_org); - if (!snakePoints.empty()){ - Piecewise >smthSnake = smoothSnake(snakePoints); - smthSnake = smthSnake*mat.inverse(); - if (do_bend.get_value()){ - smthSnake = smthSnake*bend_mat; + if (!snakePoints.empty()) { + Piecewise> smthSnake = smoothSnake(snakePoints); + smthSnake = smthSnake * mat.inverse(); + if (do_bend.get_value()) { + smthSnake = smthSnake * bend_mat; smthSnake = bend(smthSnake, -tilter); - smthSnake = smthSnake*bend_mat.inverse(); + smthSnake = smthSnake * bend_mat.inverse(); } return (smthSnake); } @@ -340,51 +372,50 @@ LPERoughHatches::doEffect_pwd2 (Geom::Piecewise > const & //------------------------------------------------ // Generate the levels with random, growth... //------------------------------------------------ -std::vector -LPERoughHatches::generateLevels(Interval const &domain, double x_org){ +std::vector LPERoughHatches::generateLevels(Interval const &domain, double x_org) +{ std::vector result; - int n = int((domain.min()-x_org)/hatch_dist); - double x = x_org + n * hatch_dist; - //double x = domain.min() + double(hatch_dist)/2.; + int n = int((domain.min() - x_org) / hatch_dist); + double x = x_org + n * hatch_dist; + // double x = domain.min() + double(hatch_dist)/2.; double step = double(hatch_dist); - double scale = 1+(hatch_dist*growth/domain.extent()); - while (x < domain.max()){ + double scale = 1 + (hatch_dist * growth / domain.extent()); + while (x < domain.max()) { result.push_back(x); double rdm = 1; if (dist_rdm.get_value() != 0) - rdm = 1.+ double((2*dist_rdm - dist_rdm.get_value()))/100.; - x+= step*rdm; - step*=scale;//(1.+double(growth)); + rdm = 1. + double((2 * dist_rdm - dist_rdm.get_value())) / 100.; + x += step * rdm; + step *= scale; //(1.+double(growth)); } return result; } - //------------------------------------------------------- // Walk through the intersections to create linear hatches //------------------------------------------------------- -std::vector > -LPERoughHatches::linearSnake(Piecewise > const &f, Point const &org){ - - //std::cout<<"linearSnake:\n"; - std::vector > result; +std::vector> LPERoughHatches::linearSnake(Piecewise> const &f, Point const &org) +{ + // std::cout<<"linearSnake:\n"; + std::vector> result; Piecewise x = make_cuts_independent(f)[X]; - //Remark: derivative is computed twice in the 2 lines below!! + // Remark: derivative is computed twice in the 2 lines below!! Piecewise dx = derivative(x); OptInterval range = bounds_exact(x); - if (!range) return result; + if (!range) + return result; std::vector levels = generateLevels(*range, org[X]); - std::vector > times; - times = multi_roots(x,levels); -//TODO: fix multi_roots!!!***************************************** -//remove doubles :-( - std::vector > cleaned_times(levels.size(),std::vector()); - for (unsigned i=0; i0 ){ - double last_t = times[i][0]-1;//ugly hack!! - for (unsigned j=0; j0.000001){ + std::vector> times; + times = multi_roots(x, levels); + // TODO: fix multi_roots!!!***************************************** + // remove doubles :-( + std::vector> cleaned_times(levels.size(), std::vector()); + for (unsigned i = 0; i < times.size(); i++) { + if (times[i].size() > 0) { + double last_t = times[i][0] - 1; // ugly hack!! + for (unsigned j = 0; j < times[i].size(); j++) { + if (times[i][j] - last_t > 0.000001) { last_t = times[i][j]; cleaned_times[i].push_back(last_t); } @@ -392,32 +423,32 @@ LPERoughHatches::linearSnake(Piecewise > const &f, Point const &org){ } } times = cleaned_times; -//******************************************************************* + //******************************************************************* - LevelsCrossings lscs(times,f,dx); + LevelsCrossings lscs(times, f, dx); - unsigned i,j; - lscs.findFirstUnused(i,j); + unsigned i, j; + lscs.findFirstUnused(i, j); std::vector result_component; - int n = int((range->min()-org[X])/hatch_dist); + int n = int((range->min() - org[X]) / hatch_dist); - while ( i < lscs.size() ){ + while (i < lscs.size()) { int dir = 0; - //switch orientation of first segment according to starting point. - if ((static_cast(i) % 2 == n % 2) && ((j + 1) < lscs[i].size()) && !lscs[i][j].used){ + // switch orientation of first segment according to starting point. + if ((static_cast(i) % 2 == n % 2) && ((j + 1) < lscs[i].size()) && !lscs[i][j].used) { j += 1; dir = 2; } - while ( i < lscs.size() ){ + while (i < lscs.size()) { result_component.push_back(lscs[i][j].pt); lscs[i][j].used = true; - lscs.step(i,j, dir); + lscs.step(i, j, dir); } result.push_back(result_component); result_component = std::vector(); - lscs.findFirstUnused(i,j); + lscs.findFirstUnused(i, j); } return result; } @@ -425,101 +456,106 @@ LPERoughHatches::linearSnake(Piecewise > const &f, Point const &org){ //------------------------------------------------------- // Smooth the linear hatches according to params... //------------------------------------------------------- -Piecewise > -LPERoughHatches::smoothSnake(std::vector > const &linearSnake){ - - Piecewise > result; - for (const auto & comp : linearSnake){ - if (comp.size()>=2){ +Piecewise> LPERoughHatches::smoothSnake(std::vector> const &linearSnake) +{ + Piecewise> result; + for (const auto &comp : linearSnake) { + if (comp.size() >= 2) { Point last_pt = comp[0]; - //Point last_top = linearSnake[comp][0]; - //Point last_bot = linearSnake[comp][0]; + // Point last_top = linearSnake[comp][0]; + // Point last_bot = linearSnake[comp][0]; Point last_hdle = comp[0]; Point last_top_hdle = comp[0]; Point last_bot_hdle = comp[0]; Geom::Path res_comp(last_pt); Geom::Path res_comp_top(last_pt); Geom::Path res_comp_bot(last_pt); - unsigned i=1; - //bool is_top = true;//Inversion here; due to downward y? - bool is_top = ( comp[0][Y] < comp[1][Y] ); + unsigned i = 1; + // bool is_top = true;//Inversion here; due to downward y? + bool is_top = (comp[0][Y] < comp[1][Y]); - while( i+1 inside[X]) inside_hdle_in = inside; - //if (inside_hdle_out[X] < inside[X]) inside_hdle_out = inside; - - if (is_top){ - res_comp_top.appendNew(last_top_hdle,new_hdle_in,new_pt); - res_comp_bot.appendNew(last_bot_hdle,inside_hdle_in,inside); + inside[Y] += double((is_top ? -stroke_width_top : stroke_width_bot)); + inside_hdle_in = inside + (new_hdle_in - new_pt); // + hdle_offset * double((is_top ? + // front_thickness : back_thickness)); + inside_hdle_out = inside + (new_hdle_out - new_pt); // - hdle_offset * double((is_top ? + // back_thickness : front_thickness)); + + inside_hdle_in += + (pt1 - pt0) / 2 * (double((is_top ? front_thickness : back_thickness)) / (pt1[X] - pt0[X])); + inside_hdle_out -= + (pt1 - pt0) / 2 * (double((is_top ? back_thickness : front_thickness)) / (pt1[X] - pt0[X])); + + new_hdle_in -= + (pt1 - pt0) / 2 * (double((is_top ? front_thickness : back_thickness)) / (pt1[X] - pt0[X])); + new_hdle_out += + (pt1 - pt0) / 2 * (double((is_top ? back_thickness : front_thickness)) / (pt1[X] - pt0[X])); + // TODO: find a good way to handle limit cases (small smoothness, large stroke). + // if (inside_hdle_in[X] > inside[X]) inside_hdle_in = inside; + // if (inside_hdle_out[X] < inside[X]) inside_hdle_out = inside; + + if (is_top) { + res_comp_top.appendNew(last_top_hdle, new_hdle_in, new_pt); + res_comp_bot.appendNew(last_bot_hdle, inside_hdle_in, inside); last_top_hdle = new_hdle_out; last_bot_hdle = inside_hdle_out; - }else{ - res_comp_top.appendNew(last_top_hdle,inside_hdle_in,inside); - res_comp_bot.appendNew(last_bot_hdle,new_hdle_in,new_pt); + } else { + res_comp_top.appendNew(last_top_hdle, inside_hdle_in, inside); + res_comp_bot.appendNew(last_bot_hdle, new_hdle_in, new_pt); last_top_hdle = inside_hdle_out; last_bot_hdle = new_hdle_out; } - }else{ - res_comp.appendNew(last_hdle,new_hdle_in,new_pt); + } else { + res_comp.appendNew(last_hdle, new_hdle_in, new_pt); } last_hdle = new_hdle_out; - i+=2; + i += 2; is_top = !is_top; } - if ( i(last_top_hdle,comp[i],comp[i]); - res_comp_bot.appendNew(last_bot_hdle,comp[i],comp[i]); - }else{ - res_comp.appendNew(last_hdle,comp[i],comp[i]); + if (i < comp.size()) { + if (fat_output.get_value()) { + res_comp_top.appendNew(last_top_hdle, comp[i], comp[i]); + res_comp_bot.appendNew(last_bot_hdle, comp[i], comp[i]); + } else { + res_comp.appendNew(last_hdle, comp[i], comp[i]); } } - if ( fat_output.get_value() ){ + if (fat_output.get_value()) { res_comp = res_comp_bot; res_comp.setStitching(true); res_comp.append(res_comp_top.reversed()); @@ -530,8 +566,7 @@ LPERoughHatches::smoothSnake(std::vector > const &linearSnake return result; } -void -LPERoughHatches::doBeforeEffect (SPLPEItem const*/*lpeitem*/) +void LPERoughHatches::doBeforeEffect(SPLPEItem const * /*lpeitem*/) { using namespace Geom; top_edge_variation.resetRandomizer(); @@ -542,35 +577,32 @@ LPERoughHatches::doBeforeEffect (SPLPEItem const*/*lpeitem*/) bot_smth_variation.resetRandomizer(); dist_rdm.resetRandomizer(); - //original_bbox(lpeitem); + // original_bbox(lpeitem); } - -void -LPERoughHatches::resetDefaults(SPItem const* item) +void LPERoughHatches::resetDefaults(SPItem const *item) { Effect::resetDefaults(item); Geom::OptRect bbox = item->geometricBounds(); - Geom::Point origin(0.,0.); - Geom::Point vector(50.,0.); + Geom::Point origin(0., 0.); + Geom::Point vector(50., 0.); if (bbox) { origin = bbox->midpoint(); - vector = Geom::Point((*bbox)[X].extent()/4, 0.); - top_edge_variation.param_set_value( (*bbox)[Y].extent()/10, 0 ); - bot_edge_variation.param_set_value( (*bbox)[Y].extent()/10, 0 ); + vector = Geom::Point((*bbox)[X].extent() / 4, 0.); + top_edge_variation.param_set_value((*bbox)[Y].extent() / 10, 0); + bot_edge_variation.param_set_value((*bbox)[Y].extent() / 10, 0); top_edge_variation.write_to_SVG(); bot_edge_variation.write_to_SVG(); } - //direction.set_and_write_new_values(origin, vector); - //bender.param_set_and_write_new_value( origin + Geom::Point(5,0) ); - direction.set_and_write_new_values(origin + Geom::Point(0,-5), vector); - bender.set_and_write_new_values( origin, Geom::Point(5,0) ); - hatch_dist = Geom::L2(vector)/2; + // direction.set_and_write_new_values(origin, vector); + // bender.param_set_and_write_new_value( origin + Geom::Point(5,0) ); + direction.set_and_write_new_values(origin + Geom::Point(0, -5), vector); + bender.set_and_write_new_values(origin, Geom::Point(5, 0)); + hatch_dist = Geom::L2(vector) / 2; } - -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-rough-hatches.h b/src/live_effects/lpe-rough-hatches.h index ea4b0c32616dde05153e3f80524d6b34ba639b91..31e05e2c3820b2085bdf159e2698418f34f1b306 100644 --- a/src/live_effects/lpe-rough-hatches.h +++ b/src/live_effects/lpe-rough-hatches.h @@ -16,62 +16,61 @@ */ #include "live_effects/effect.h" -#include "live_effects/parameter/parameter.h" #include "live_effects/parameter/bool.h" +#include "live_effects/parameter/parameter.h" #include "live_effects/parameter/random.h" #include "live_effects/parameter/vector.h" namespace Inkscape { namespace LivePathEffect { -class LPERoughHatches : public Effect { +class LPERoughHatches : public Effect +{ public: LPERoughHatches(LivePathEffectObject *lpeobject); ~LPERoughHatches() override; - Geom::Piecewise > - doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; + + void resetDefaults(SPItem const *item) override; - void resetDefaults(SPItem const* item) override; + void doBeforeEffect(SPLPEItem const *item) override; - void doBeforeEffect(SPLPEItem const* item) override; + std::vector generateLevels(Geom::Interval const &domain, double x_org); - std::vector - generateLevels(Geom::Interval const &domain, double x_org); + std::vector> linearSnake(Geom::Piecewise> const &f, + Geom::Point const &org); - std::vector > - linearSnake(Geom::Piecewise > const &f, Geom::Point const &org); + Geom::Piecewise> smoothSnake(std::vector> const &linearSnake); - Geom::Piecewise > - smoothSnake(std::vector > const &linearSnake); - private: - double hatch_dist; - RandomParam dist_rdm; - ScalarParam growth; - //topfront,topback,bottomfront,bottomback handle scales. - ScalarParam scale_tf, scale_tb, scale_bf, scale_bb; - - RandomParam top_edge_variation; - RandomParam bot_edge_variation; - RandomParam top_tgt_variation; - RandomParam bot_tgt_variation; - RandomParam top_smth_variation; - RandomParam bot_smth_variation; - - BoolParam fat_output, do_bend; - ScalarParam stroke_width_top; - ScalarParam stroke_width_bot; - ScalarParam front_thickness, back_thickness; - - VectorParam direction; - VectorParam bender; - - LPERoughHatches(const LPERoughHatches&) = delete; - LPERoughHatches& operator=(const LPERoughHatches&) = delete; + double hatch_dist; + RandomParam dist_rdm; + ScalarParam growth; + // topfront,topback,bottomfront,bottomback handle scales. + ScalarParam scale_tf, scale_tb, scale_bf, scale_bb; + + RandomParam top_edge_variation; + RandomParam bot_edge_variation; + RandomParam top_tgt_variation; + RandomParam bot_tgt_variation; + RandomParam top_smth_variation; + RandomParam bot_smth_variation; + + BoolParam fat_output, do_bend; + ScalarParam stroke_width_top; + ScalarParam stroke_width_bot; + ScalarParam front_thickness, back_thickness; + + VectorParam direction; + VectorParam bender; + + LPERoughHatches(const LPERoughHatches &) = delete; + LPERoughHatches &operator=(const LPERoughHatches &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-roughen.cpp b/src/live_effects/lpe-roughen.cpp index 9980351e16045057db404de88b42ae14cdd4d222..2893d309de7c56f852fa7c4748a8c35b7f72b69e 100644 --- a/src/live_effects/lpe-roughen.cpp +++ b/src/live_effects/lpe-roughen.cpp @@ -15,11 +15,13 @@ */ #include "live_effects/lpe-roughen.h" -#include "display/curve.h" -#include "helper/geom.h" + #include #include +#include "display/curve.h" +#include "helper/geom.h" + // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -27,14 +29,14 @@ namespace Inkscape { namespace LivePathEffect { static const Util::EnumData DivisionMethodData[DM_END] = { - { DM_SEGMENTS, N_("By number of segments"), "segments" }, { DM_SIZE, N_("By max. segment size"), "size" } -}; + {DM_SEGMENTS, N_("By number of segments"), "segments"}, + {DM_SIZE, N_("By max. segment size"), "size"}}; static const Util::EnumDataConverter DMConverter(DivisionMethodData, DM_END); -static const Util::EnumData HandlesMethodData[HM_END] = { { HM_ALONG_NODES, N_("Along nodes"), "along" }, - { HM_RAND, N_("Rand"), "rand" }, - { HM_RETRACT, N_("Retract"), "retract" }, - { HM_SMOOTH, N_("Smooth"), "smooth" } }; +static const Util::EnumData HandlesMethodData[HM_END] = {{HM_ALONG_NODES, N_("Along nodes"), "along"}, + {HM_RAND, N_("Rand"), "rand"}, + {HM_RETRACT, N_("Retract"), "retract"}, + {HM_SMOOTH, N_("Smooth"), "smooth"}}; static const Util::EnumDataConverter HMConverter(HandlesMethodData, HM_END); LPERoughen::LPERoughen(LivePathEffectObject *lpeobject) @@ -111,7 +113,6 @@ void LPERoughen::doOnApply(SPLPEItem const *lpeitem) (Glib::ustring)LPETypeConverter.get_key(effectType()).c_str() + (Glib::ustring) "/" + (Glib::ustring)key; - bool valid = prefs->getEntry(pref_path).isValid(); // double lenght = sp_get_perimeter(lpeitem); Glib::ustring displace_x_str = Glib::ustring::format((*bbox).width() / 100.0); @@ -355,8 +356,8 @@ void LPERoughen::doEffect(SPCurve *curve) } } -std::unique_ptr LPERoughen::addNodesAndJitter(Geom::Curve const *A, Geom::Point &prev, Geom::Point &last_move, double t, - bool last) +std::unique_ptr LPERoughen::addNodesAndJitter(Geom::Curve const *A, Geom::Point &prev, Geom::Point &last_move, + double t, bool last) { auto out = std::make_unique(); Geom::CubicBezier const *cubic = dynamic_cast(&*A); diff --git a/src/live_effects/lpe-roughen.h b/src/live_effects/lpe-roughen.h index 8940f93bf9b778fee40963f8b8d6d8b501e50da7..7cad586afd89e0a0c953fbd73ae65bf72cf8d54a 100644 --- a/src/live_effects/lpe-roughen.h +++ b/src/live_effects/lpe-roughen.h @@ -13,25 +13,27 @@ #ifndef INKSCAPE_LPE_ROUGHEN_H #define INKSCAPE_LPE_ROUGHEN_H +#include + #include "live_effects/effect.h" +#include "live_effects/parameter/bool.h" #include "live_effects/parameter/enum.h" #include "live_effects/parameter/parameter.h" #include "live_effects/parameter/path.h" -#include "live_effects/parameter/bool.h" #include "live_effects/parameter/random.h" -#include - namespace Inkscape { namespace LivePathEffect { -enum DivisionMethod { +enum DivisionMethod +{ DM_SEGMENTS, DM_SIZE, DM_END }; -enum HandlesMethod { +enum HandlesMethod +{ HM_ALONG_NODES, HM_RAND, HM_RETRACT, @@ -39,9 +41,8 @@ enum HandlesMethod { HM_END }; - -class LPERoughen : public Effect { - +class LPERoughen : public Effect +{ public: LPERoughen(LivePathEffectObject *lpeobject); ~LPERoughen() override; @@ -50,7 +51,7 @@ public: void doEffect(SPCurve *curve) override; virtual double sign(double randNumber); virtual Geom::Point randomize(double max_length, bool is_node = false); - void doBeforeEffect(SPLPEItem const * lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; virtual Geom::Point tPoint(Geom::Point A, Geom::Point B, double t = 0.5); Gtk::Widget *newWidget() override; @@ -72,9 +73,8 @@ private: long seed; LPERoughen(const LPERoughen &) = delete; LPERoughen &operator=(const LPERoughen &) = delete; - }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-ruler.cpp b/src/live_effects/lpe-ruler.cpp index 60050837264e04a2bbaca9537fb4592c3dd567bb..bdfde5d6aab4d2a401977fee4e1b4822c039fd34 100644 --- a/src/live_effects/lpe-ruler.cpp +++ b/src/live_effects/lpe-ruler.cpp @@ -20,31 +20,36 @@ namespace Inkscape { namespace LivePathEffect { static const Util::EnumData MarkDirData[] = { - {MARKDIR_LEFT , N_("Left"), "left"}, - {MARKDIR_RIGHT , N_("Right"), "right"}, - {MARKDIR_BOTH , N_("Both"), "both"}, + {MARKDIR_LEFT, N_("Left"), "left"}, + {MARKDIR_RIGHT, N_("Right"), "right"}, + {MARKDIR_BOTH, N_("Both"), "both"}, }; -static const Util::EnumDataConverter MarkDirTypeConverter(MarkDirData, sizeof(MarkDirData)/sizeof(*MarkDirData)); +static const Util::EnumDataConverter MarkDirTypeConverter(MarkDirData, + sizeof(MarkDirData) / sizeof(*MarkDirData)); static const Util::EnumData BorderMarkData[] = { - {BORDERMARK_NONE , NC_("Border mark", "None"), "none"}, - {BORDERMARK_START , N_("Start"), "start"}, - {BORDERMARK_END , N_("End"), "end"}, - {BORDERMARK_BOTH , N_("Both"), "both"}, + {BORDERMARK_NONE, NC_("Border mark", "None"), "none"}, + {BORDERMARK_START, N_("Start"), "start"}, + {BORDERMARK_END, N_("End"), "end"}, + {BORDERMARK_BOTH, N_("Both"), "both"}, }; -static const Util::EnumDataConverter BorderMarkTypeConverter(BorderMarkData, sizeof(BorderMarkData)/sizeof(*BorderMarkData)); - -LPERuler::LPERuler(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - mark_distance(_("_Mark distance:"), _("Distance between successive ruler marks"), "mark_distance", &wr, this, 20.0), - unit(_("Unit:"), _("Unit"), "unit", &wr, this), - mark_length(_("Ma_jor length:"), _("Length of major ruler marks"), "mark_length", &wr, this, 14.0), - minor_mark_length(_("Mino_r length:"), _("Length of minor ruler marks"), "minor_mark_length", &wr, this, 7.0), - major_mark_steps(_("Major steps_:"), _("Draw a major mark every ... steps"), "major_mark_steps", &wr, this, 5), - shift(_("Shift marks _by:"), _("Shift marks by this many steps"), "shift", &wr, this, 0), - mark_dir(_("Mark direction:"), _("Direction of marks (when viewing along the path from start to end)"), "mark_dir", MarkDirTypeConverter, &wr, this, MARKDIR_LEFT), - offset(_("_Offset:"), _("Offset of first mark"), "offset", &wr, this, 0.0), - border_marks(_("Border marks:"), _("Choose whether to draw marks at the beginning and end of the path"), "border_marks", BorderMarkTypeConverter, &wr, this, BORDERMARK_BOTH) +static const Util::EnumDataConverter + BorderMarkTypeConverter(BorderMarkData, sizeof(BorderMarkData) / sizeof(*BorderMarkData)); + +LPERuler::LPERuler(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , mark_distance(_("_Mark distance:"), _("Distance between successive ruler marks"), "mark_distance", &wr, this, + 20.0) + , unit(_("Unit:"), _("Unit"), "unit", &wr, this) + , mark_length(_("Ma_jor length:"), _("Length of major ruler marks"), "mark_length", &wr, this, 14.0) + , minor_mark_length(_("Mino_r length:"), _("Length of minor ruler marks"), "minor_mark_length", &wr, this, 7.0) + , major_mark_steps(_("Major steps_:"), _("Draw a major mark every ... steps"), "major_mark_steps", &wr, this, 5) + , shift(_("Shift marks _by:"), _("Shift marks by this many steps"), "shift", &wr, this, 0) + , mark_dir(_("Mark direction:"), _("Direction of marks (when viewing along the path from start to end)"), + "mark_dir", MarkDirTypeConverter, &wr, this, MARKDIR_LEFT) + , offset(_("_Offset:"), _("Offset of first mark"), "offset", &wr, this, 0.0) + , border_marks(_("Border marks:"), _("Choose whether to draw marks at the beginning and end of the path"), + "border_marks", BorderMarkTypeConverter, &wr, this, BORDERMARK_BOTH) { registerParameter(&unit); registerParameter(&mark_distance); @@ -65,25 +70,26 @@ LPERuler::LPERuler(LivePathEffectObject *lpeobject) : offset.param_set_increments(1.0, 10.0); } -LPERuler::~LPERuler() -= default; +LPERuler::~LPERuler() = default; Geom::Point LPERuler::n_major; Geom::Point LPERuler::n_minor; -Geom::Piecewise > -LPERuler::ruler_mark(Geom::Point const &A, Geom::Point const &n, MarkType const &marktype) +Geom::Piecewise> LPERuler::ruler_mark(Geom::Point const &A, Geom::Point const &n, + MarkType const &marktype) { using namespace Geom; double real_mark_length = mark_length; SPDocument *document = getSPDoc(); if (document) { - real_mark_length = Inkscape::Util::Quantity::convert(real_mark_length, unit.get_abbreviation(), document->getDisplayUnit()->abbr.c_str()); + real_mark_length = Inkscape::Util::Quantity::convert(real_mark_length, unit.get_abbreviation(), + document->getDisplayUnit()->abbr.c_str()); } double real_minor_mark_length = minor_mark_length; if (document) { - real_minor_mark_length = Inkscape::Util::Quantity::convert(real_minor_mark_length, unit.get_abbreviation(), document->getDisplayUnit()->abbr.c_str()); + real_minor_mark_length = Inkscape::Util::Quantity::convert(real_minor_mark_length, unit.get_abbreviation(), + document->getDisplayUnit()->abbr.c_str()); } n_major = real_mark_length * n; n_minor = real_minor_mark_length * n; @@ -111,85 +117,83 @@ LPERuler::ruler_mark(Geom::Point const &A, Geom::Point const &n, MarkType const break; } - Piecewise > seg(D2(SBasis(C[X], D[X]), SBasis(C[Y], D[Y]))); + Piecewise> seg(D2(SBasis(C[X], D[X]), SBasis(C[Y], D[Y]))); return seg; } -Geom::Piecewise > -LPERuler::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> LPERuler::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; const int mminterval = static_cast(major_mark_steps); const int i_shift = static_cast(shift) % mminterval; - int sign = (mark_dir == MARKDIR_RIGHT ? 1 : -1 ); + int sign = (mark_dir == MARKDIR_RIGHT ? 1 : -1); - Piecewise >output(pwd2_in); - Piecewise >speed = derivative(pwd2_in); + Piecewise> output(pwd2_in); + Piecewise> speed = derivative(pwd2_in); Piecewise arclength = arcLengthSb(pwd2_in); double totlength = arclength.lastValue(); - - //find at which times to draw a mark: + + // find at which times to draw a mark: std::vector s_cuts; double real_mark_distance = mark_distance; SPDocument *document = getSPDoc(); if (document) { - real_mark_distance = Inkscape::Util::Quantity::convert(real_mark_distance, unit.get_abbreviation(), document->getDisplayUnit()->abbr.c_str()); - } + real_mark_distance = Inkscape::Util::Quantity::convert(real_mark_distance, unit.get_abbreviation(), + document->getDisplayUnit()->abbr.c_str()); + } double real_offset = offset; if (document) { - real_offset = Inkscape::Util::Quantity::convert(real_offset, unit.get_abbreviation(), document->getDisplayUnit()->abbr.c_str()); + real_offset = Inkscape::Util::Quantity::convert(real_offset, unit.get_abbreviation(), + document->getDisplayUnit()->abbr.c_str()); } - for (double s = real_offset; s > roots = multi_roots(arclength, s_cuts); + std::vector> roots = multi_roots(arclength, s_cuts); std::vector t_cuts; - for (auto & root : roots){ - //FIXME: 2geom multi_roots solver seem to sometimes "repeat" solutions. - //Here, we are supposed to have one and only one solution for each s. - if(root.size()>0) + for (auto &root : roots) { + // FIXME: 2geom multi_roots solver seem to sometimes "repeat" solutions. + // Here, we are supposed to have one and only one solution for each s. + if (root.size() > 0) t_cuts.push_back(root[0]); } - //draw the marks + // draw the marks for (size_t i = 0; i < t_cuts.size(); i++) { Point A = pwd2_in(t_cuts[i]); - Point n = rot90(unit_vector(speed(t_cuts[i])))*sign; + Point n = rot90(unit_vector(speed(t_cuts[i]))) * sign; if (static_cast(i % mminterval) == i_shift) { - output.concat (ruler_mark(A, n, MARK_MAJOR)); + output.concat(ruler_mark(A, n, MARK_MAJOR)); } else { - output.concat (ruler_mark(A, n, MARK_MINOR)); + output.concat(ruler_mark(A, n, MARK_MINOR)); } } - //eventually draw a mark at start - if ((border_marks == BORDERMARK_START || border_marks == BORDERMARK_BOTH) && (offset != 0.0 || i_shift != 0)){ + // eventually draw a mark at start + if ((border_marks == BORDERMARK_START || border_marks == BORDERMARK_BOTH) && (offset != 0.0 || i_shift != 0)) { Point A = pwd2_in.firstValue(); - Point n = rot90(unit_vector(speed.firstValue()))*sign; - output.concat (ruler_mark(A, n, MARK_MAJOR)); + Point n = rot90(unit_vector(speed.firstValue())) * sign; + output.concat(ruler_mark(A, n, MARK_MAJOR)); } - //eventually draw a mark at end - if (border_marks == BORDERMARK_END || border_marks == BORDERMARK_BOTH){ + // eventually draw a mark at end + if (border_marks == BORDERMARK_END || border_marks == BORDERMARK_BOTH) { Point A = pwd2_in.lastValue(); - Point n = rot90(unit_vector(speed.lastValue()))*sign; - //speed.lastValue() is sometimes wrong when the path is closed: a tiny line seg might added at the end to fix rounding errors... - //TODO: Find a better fix!! (How do we know if the path was closed?) - if ( A == pwd2_in.firstValue() && - speed.segs.size() > 1 && - speed.segs.back()[X].size() <= 1 && - speed.segs.back()[Y].size() <= 1 && - speed.segs.back()[X].tailError(0) <= 1e-10 && - speed.segs.back()[Y].tailError(0) <= 1e-10 - ){ - n = rot90(unit_vector(speed.segs[speed.segs.size()-2].at1()))*sign; + Point n = rot90(unit_vector(speed.lastValue())) * sign; + // speed.lastValue() is sometimes wrong when the path is closed: a tiny line seg might added at the end to fix + // rounding errors... + // TODO: Find a better fix!! (How do we know if the path was closed?) + if (A == pwd2_in.firstValue() && speed.segs.size() > 1 && speed.segs.back()[X].size() <= 1 && + speed.segs.back()[Y].size() <= 1 && speed.segs.back()[X].tailError(0) <= 1e-10 && + speed.segs.back()[Y].tailError(0) <= 1e-10) { + n = rot90(unit_vector(speed.segs[speed.segs.size() - 2].at1())) * sign; } - output.concat (ruler_mark(A, n, MARK_MAJOR)); + output.concat(ruler_mark(A, n, MARK_MAJOR)); } return output; } -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-ruler.h b/src/live_effects/lpe-ruler.h index 37667172cfdbd226f135074be63db344bde90023..6eebd377688b2617046aa53ecd73b573acadece7 100644 --- a/src/live_effects/lpe-ruler.h +++ b/src/live_effects/lpe-ruler.h @@ -16,40 +16,46 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/enum.h" #include "live_effects/effect.h" +#include "live_effects/parameter/enum.h" #include "live_effects/parameter/unit.h" namespace Inkscape { namespace LivePathEffect { -enum MarkType { +enum MarkType +{ MARK_MAJOR, MARK_MINOR }; -enum MarkDirType { +enum MarkDirType +{ MARKDIR_LEFT, MARKDIR_RIGHT, MARKDIR_BOTH, }; -enum BorderMarkType { +enum BorderMarkType +{ BORDERMARK_NONE, BORDERMARK_START, BORDERMARK_END, BORDERMARK_BOTH, }; -class LPERuler : public Effect { +class LPERuler : public Effect +{ public: LPERuler(LivePathEffectObject *lpeobject); ~LPERuler() override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; private: - Geom::Piecewise > ruler_mark(Geom::Point const &A, Geom::Point const &n, MarkType const &marktype); + Geom::Piecewise> ruler_mark(Geom::Point const &A, Geom::Point const &n, + MarkType const &marktype); ScalarParam mark_distance; UnitParam unit; @@ -63,12 +69,12 @@ private: static Geom::Point n_major, n_minor; // used for internal computations - LPERuler(const LPERuler&) = delete; - LPERuler& operator=(const LPERuler&) = delete; + LPERuler(const LPERuler &) = delete; + LPERuler &operator=(const LPERuler &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-show_handles.cpp b/src/live_effects/lpe-show_handles.cpp index 83bac25950247fd00a8620777e5412671f437458..10e75e5b695cdccb4802d39fd94d14c26f3bc07e 100644 --- a/src/live_effects/lpe-show_handles.cpp +++ b/src/live_effects/lpe-show_handles.cpp @@ -7,17 +7,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "live_effects/lpe-show_handles.h" + #include <2geom/sbasis-to-bezier.h> #include <2geom/svg-path-parser.h> -#include "helper/geom.h" +#include + #include "desktop-style.h" #include "display/curve.h" -#include "svg/svg.h" - +#include "helper/geom.h" #include "object/sp-shape.h" #include "style.h" +#include "svg/svg.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -26,13 +27,14 @@ namespace Inkscape { namespace LivePathEffect { LPEShowHandles::LPEShowHandles(LivePathEffectObject *lpeobject) - : Effect(lpeobject), - nodes(_("Show nodes"), _("Show nodes"), "nodes", &wr, this, true), - handles(_("Show handles"), _("Show handles"), "handles", &wr, this, true), - original_path(_("Show path"), _("Show path"), "original_path", &wr, this, true), - show_center_node(_("Show center of node"), _("Show center of node"), "show_center_node", &wr, this, false), - original_d(_("Show original"), _("Show original"), "original_d", &wr, this, false), - scale_nodes_and_handles(_("Scale nodes and handles"), _("Scale nodes and handles"), "scale_nodes_and_handles", &wr, this, 10) + : Effect(lpeobject) + , nodes(_("Show nodes"), _("Show nodes"), "nodes", &wr, this, true) + , handles(_("Show handles"), _("Show handles"), "handles", &wr, this, true) + , original_path(_("Show path"), _("Show path"), "original_path", &wr, this, true) + , show_center_node(_("Show center of node"), _("Show center of node"), "show_center_node", &wr, this, false) + , original_d(_("Show original"), _("Show original"), "original_d", &wr, this, false) + , scale_nodes_and_handles(_("Scale nodes and handles"), _("Scale nodes and handles"), "scale_nodes_and_handles", + &wr, this, 10) { registerParameter(&nodes); registerParameter(&handles); @@ -53,54 +55,55 @@ bool LPEShowHandles::alerts_off = false; * this permanently remove.some styles of the element */ -void LPEShowHandles::doOnApply(SPLPEItem const* lpeitem) +void LPEShowHandles::doOnApply(SPLPEItem const *lpeitem) { - if(!alerts_off) { - char *msg = _("The \"show handles\" path effect will remove any custom style on the object you are applying it to. If this is not what you want, click Cancel."); + if (!alerts_off) { + char *msg = _("The \"show handles\" path effect will remove any custom style on the object you are applying it " + "to. If this is not what you want, click Cancel."); Gtk::MessageDialog dialog(msg, false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_OK_CANCEL, true); gint response = dialog.run(); alerts_off = true; - if(response == GTK_RESPONSE_CANCEL) { - SPLPEItem* item = const_cast(lpeitem); + if (response == GTK_RESPONSE_CANCEL) { + SPLPEItem *item = const_cast(lpeitem); item->removeCurrentPathEffect(false); return; } } - SPLPEItem* item = const_cast(lpeitem); - SPCSSAttr *css = sp_repr_css_attr_new (); - sp_repr_css_set_property (css, "stroke", "black"); - sp_repr_css_set_property (css, "stroke-width", "1"); - sp_repr_css_set_property (css, "stroke-linecap", "butt"); + SPLPEItem *item = const_cast(lpeitem); + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "stroke", "black"); + sp_repr_css_set_property(css, "stroke-width", "1"); + sp_repr_css_set_property(css, "stroke-linecap", "butt"); sp_repr_css_set_property(css, "fill", "none"); sp_desktop_apply_css_recursive(item, css, true); - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); } -void LPEShowHandles::doBeforeEffect (SPLPEItem const* lpeitem) +void LPEShowHandles::doBeforeEffect(SPLPEItem const *lpeitem) { - SPItem const* item = SP_ITEM(lpeitem); + SPItem const *item = SP_ITEM(lpeitem); stroke_width = item->style->stroke_width.computed; } -Geom::PathVector LPEShowHandles::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPEShowHandles::doEffect_path(Geom::PathVector const &path_in) { Geom::PathVector path_out; Geom::PathVector original_pathv = pathv_to_linear_and_cubic_beziers(path_in); - if(original_path) { - for (const auto & i : path_in) { + if (original_path) { + for (const auto &i : path_in) { path_out.push_back(i); } } - if(!outline_path.empty()) { + if (!outline_path.empty()) { outline_path.clear(); } if (original_d) { auto shape_curve = SPCurve::copy(current_shape->curveForEdit()); if (shape_curve) { Geom::PathVector original_curve = shape_curve->get_pathvector(); - if(original_path) { - for (const auto & i : original_curve) { + if (original_path) { + for (const auto &i : original_curve) { path_out.push_back(i); } } @@ -110,29 +113,28 @@ Geom::PathVector LPEShowHandles::doEffect_path (Geom::PathVector const & path_in } else { generateHelperPath(original_pathv); } - for (const auto & i : outline_path) { + for (const auto &i : outline_path) { path_out.push_back(i); } return path_out; } -void -LPEShowHandles::generateHelperPath(Geom::PathVector result) +void LPEShowHandles::generateHelperPath(Geom::PathVector result) { - if(!handles && !nodes) { + if (!handles && !nodes) { return; } Geom::CubicBezier const *cubic = nullptr; - for (auto & path_it : result) { - //Si está vacío... + for (auto &path_it : result) { + // Si está vacío... if (path_it.empty()) { continue; } - //Itreadores - Geom::Path::iterator curve_it1 = path_it.begin(); // incoming curve - Geom::Path::iterator curve_it2 = ++(path_it.begin()); // outgoing curve + // Itreadores + Geom::Path::iterator curve_it1 = path_it.begin(); // incoming curve + Geom::Path::iterator curve_it2 = ++(path_it.begin()); // outgoing curve Geom::Path::iterator curve_endit = path_it.end_default(); // this determines when the loop has to stop if (path_it.closed()) { @@ -148,51 +150,51 @@ LPEShowHandles::generateHelperPath(Geom::PathVector result) curve_endit = path_it.end_open(); } } - if(nodes) { + if (nodes) { Geom::NodeType nodetype = Geom::NODE_CUSP; - if(path_it.closed()) { + if (path_it.closed()) { nodetype = Geom::get_nodetype(path_it.finalCurve(), *curve_it1); - } + } drawNode(curve_it1->initialPoint(), nodetype); } while (curve_it1 != curve_endit) { cubic = dynamic_cast(&*curve_it1); if (cubic) { - if(handles) { - if(!are_near((*cubic)[0],(*cubic)[1])) { + if (handles) { + if (!are_near((*cubic)[0], (*cubic)[1])) { drawHandle((*cubic)[1]); - drawHandleLine((*cubic)[0],(*cubic)[1]); + drawHandleLine((*cubic)[0], (*cubic)[1]); } - if(!are_near((*cubic)[3],(*cubic)[2])) { + if (!are_near((*cubic)[3], (*cubic)[2])) { drawHandle((*cubic)[2]); - drawHandleLine((*cubic)[3],(*cubic)[2]); + drawHandleLine((*cubic)[3], (*cubic)[2]); } } } - if(nodes && (curve_it2 != curve_endit || !path_it.closed())) { + if (nodes && (curve_it2 != curve_endit || !path_it.closed())) { Geom::NodeType nodetype = Geom::get_nodetype(*curve_it1, *curve_it2); drawNode(curve_it1->finalPoint(), nodetype); } ++curve_it1; - if(curve_it2 != curve_endit) { + if (curve_it2 != curve_endit) { ++curve_it2; } } } } -void -LPEShowHandles::drawNode(Geom::Point p, Geom::NodeType nodetype) +void LPEShowHandles::drawNode(Geom::Point p, Geom::NodeType nodetype) { - if(stroke_width * scale_nodes_and_handles > 0.0) { + if (stroke_width * scale_nodes_and_handles > 0.0) { Geom::Rotate rotate = Geom::Rotate(0); - if ( nodetype == Geom::NODE_CUSP) { + if (nodetype == Geom::NODE_CUSP) { rotate = Geom::Rotate::from_degrees(45); } double diameter = stroke_width * scale_nodes_and_handles; - char const * svgd; + char const *svgd; if (show_center_node) { - svgd = "M 0.05,0 A 0.05,0.05 0 0 1 0,0.05 0.05,0.05 0 0 1 -0.05,0 0.05,0.05 0 0 1 0,-0.05 0.05,0.05 0 0 1 0.05,0 Z M -0.5,-0.5 0.5,-0.5 0.5,0.5 -0.5,0.5 Z"; + svgd = "M 0.05,0 A 0.05,0.05 0 0 1 0,0.05 0.05,0.05 0 0 1 -0.05,0 0.05,0.05 0 0 1 0,-0.05 0.05,0.05 0 0 1 " + "0.05,0 Z M -0.5,-0.5 0.5,-0.5 0.5,0.5 -0.5,0.5 Z"; } else { svgd = "M -0.5,-0.5 0.5,-0.5 0.5,0.5 -0.5,0.5 Z"; } @@ -205,35 +207,33 @@ LPEShowHandles::drawNode(Geom::Point p, Geom::NodeType nodetype) } } -void -LPEShowHandles::drawHandle(Geom::Point p) +void LPEShowHandles::drawHandle(Geom::Point p) { - if(stroke_width * scale_nodes_and_handles > 0.0) { + if (stroke_width * scale_nodes_and_handles > 0.0) { double diameter = stroke_width * scale_nodes_and_handles; - char const * svgd; - svgd = "M 0.7,0.35 A 0.35,0.35 0 0 1 0.35,0.7 0.35,0.35 0 0 1 0,0.35 0.35,0.35 0 0 1 0.35,0 0.35,0.35 0 0 1 0.7,0.35 Z"; + char const *svgd; + svgd = "M 0.7,0.35 A 0.35,0.35 0 0 1 0.35,0.7 0.35,0.35 0 0 1 0,0.35 0.35,0.35 0 0 1 0.35,0 0.35,0.35 0 0 1 " + "0.7,0.35 Z"; Geom::PathVector pathv = sp_svg_read_pathv(svgd); - pathv *= Geom::Scale (diameter) * Geom::Translate(p - Geom::Point(diameter * 0.35,diameter * 0.35)); + pathv *= Geom::Scale(diameter) * Geom::Translate(p - Geom::Point(diameter * 0.35, diameter * 0.35)); outline_path.push_back(pathv[0]); } } - -void -LPEShowHandles::drawHandleLine(Geom::Point p,Geom::Point p2) +void LPEShowHandles::drawHandleLine(Geom::Point p, Geom::Point p2) { Geom::Path path; double diameter = stroke_width * scale_nodes_and_handles; - if(diameter > 0.0 && Geom::distance(p,p2) > (diameter * 0.35)) { + if (diameter > 0.0 && Geom::distance(p, p2) > (diameter * 0.35)) { Geom::Ray ray2(p, p2); - p2 = p2 - Geom::Point::polar(ray2.angle(),(diameter * 0.35)); + p2 = p2 - Geom::Point::polar(ray2.angle(), (diameter * 0.35)); } - path.start( p ); - path.appendNew( p2 ); + path.start(p); + path.appendNew(p2); outline_path.push_back(path); } -}; //namespace LivePathEffect +}; // namespace LivePathEffect }; /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-show_handles.h b/src/live_effects/lpe-show_handles.h index 865034ebc61c33be019f620ae4875ee97232d83c..4001685870ae646651a624874e115cb776d8667b 100644 --- a/src/live_effects/lpe-show_handles.h +++ b/src/live_effects/lpe-show_handles.h @@ -17,15 +17,17 @@ namespace Inkscape { namespace LivePathEffect { -class LPEShowHandles : public Effect , GroupBBoxEffect { - +class LPEShowHandles + : public Effect + , GroupBBoxEffect +{ public: LPEShowHandles(LivePathEffectObject *lpeobject); ~LPEShowHandles() override = default; - void doOnApply(SPLPEItem const* lpeitem) override; + void doOnApply(SPLPEItem const *lpeitem) override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; virtual void generateHelperPath(Geom::PathVector result); @@ -33,14 +35,12 @@ public: virtual void drawHandle(Geom::Point p); - virtual void drawHandleLine(Geom::Point p,Geom::Point p2); + virtual void drawHandleLine(Geom::Point p, Geom::Point p2); protected: - - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; private: - BoolParam nodes; BoolParam handles; BoolParam original_path; @@ -54,11 +54,10 @@ private: LPEShowHandles(const LPEShowHandles &) = delete; LPEShowHandles &operator=(const LPEShowHandles &) = delete; - }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/live_effects/lpe-simplify.cpp b/src/live_effects/lpe-simplify.cpp index 2c424d915a1c8396d91d619583204ca2e470262e..6cdcb59cdb0ebabbb85e8fbac3ac4bbee2c780da 100644 --- a/src/live_effects/lpe-simplify.cpp +++ b/src/live_effects/lpe-simplify.cpp @@ -3,10 +3,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include - #include "live_effects/lpe-simplify.h" +#include <2geom/svg-path-parser.h> +#include + #include "display/curve.h" #include "helper/geom.h" #include "path/path-util.h" @@ -14,8 +15,6 @@ #include "ui/icon-names.h" #include "ui/tools/node-tool.h" -#include <2geom/svg-path-parser.h> - // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -63,34 +62,31 @@ LPESimplify::LPESimplify(LivePathEffectObject *lpeobject) LPESimplify::~LPESimplify() = default; -void -LPESimplify::doBeforeEffect (SPLPEItem const* lpeitem) +void LPESimplify::doBeforeEffect(SPLPEItem const *lpeitem) { - if(!hp.empty()) { + if (!hp.empty()) { hp.clear(); } bbox = SP_ITEM(lpeitem)->visualBounds(); radius_helper_nodes = helper_size; } -Gtk::Widget * -LPESimplify::newWidget() +Gtk::Widget *LPESimplify::newWidget() { // use manage here, because after deletion of Effect object, others might still be pointing to this widget. - Gtk::VBox * vbox = Gtk::manage( new Gtk::VBox(Effect::newWidget()) ); - + Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox(Effect::newWidget())); + vbox->set_border_width(5); vbox->set_homogeneous(false); vbox->set_spacing(2); std::vector::iterator it = param_vector.begin(); - Gtk::HBox * buttons = Gtk::manage(new Gtk::HBox(true,0)); + Gtk::HBox *buttons = Gtk::manage(new Gtk::HBox(true, 0)); while (it != param_vector.end()) { if ((*it)->widget_is_visible) { - Parameter * param = *it; - Gtk::Widget * widg = dynamic_cast(param->param_newWidget()); - if (param->param_key == "simplify_individual_paths" || - param->param_key == "simplify_just_coalesce") { - Glib::ustring * tip = param->param_getTooltip(); + Parameter *param = *it; + Gtk::Widget *widg = dynamic_cast(param->param_newWidget()); + if (param->param_key == "simplify_individual_paths" || param->param_key == "simplify_just_coalesce") { + Glib::ustring *tip = param->param_getTooltip(); if (widg) { buttons->pack_start(*widg, true, true, 2); if (tip) { @@ -101,11 +97,11 @@ LPESimplify::newWidget() } } } else { - Glib::ustring * tip = param->param_getTooltip(); + Glib::ustring *tip = param->param_getTooltip(); if (widg) { - Gtk::HBox * horizontal_box = dynamic_cast(widg); - std::vector< Gtk::Widget* > child_list = horizontal_box->get_children(); - Gtk::Entry* entry_widg = dynamic_cast(child_list[1]); + Gtk::HBox *horizontal_box = dynamic_cast(widg); + std::vector child_list = horizontal_box->get_children(); + Gtk::Entry *entry_widg = dynamic_cast(child_list[1]); entry_widg->set_width_chars(8); vbox->pack_start(*widg, true, true, 2); if (tip) { @@ -120,26 +116,25 @@ LPESimplify::newWidget() ++it; } - vbox->pack_start(*buttons,true, true, 2); - if(Gtk::Widget* widg = defaultParamSet()) { + vbox->pack_start(*buttons, true, true, 2); + if (Gtk::Widget *widg = defaultParamSet()) { vbox->pack_start(*widg, true, true, 2); } return dynamic_cast(vbox); } -void -LPESimplify::doEffect(SPCurve *curve) +void LPESimplify::doEffect(SPCurve *curve) { Geom::PathVector const original_pathv = pathv_to_linear_and_cubic_beziers(curve->get_pathvector()); - gdouble size = Geom::L2(bbox->dimensions()); - //size /= Geom::Affine(0,0,0,0,0,0).descrim(); - Path* pathliv = Path_for_pathvector(original_pathv); - if(simplify_individual_paths) { + gdouble size = Geom::L2(bbox->dimensions()); + // size /= Geom::Affine(0,0,0,0,0,0).descrim(); + Path *pathliv = Path_for_pathvector(original_pathv); + if (simplify_individual_paths) { size = Geom::L2(Geom::bounds_fast(original_pathv)->dimensions()); } size /= sp_lpe_item->i2doc_affine().descrim(); for (int unsigned i = 0; i < steps; i++) { - if ( simplify_just_coalesce ) { + if (simplify_just_coalesce) { pathliv->Coalesce(threshold * size); } else { pathliv->ConvertEvenLines(threshold * size); @@ -152,28 +147,26 @@ LPESimplify::doEffect(SPCurve *curve) update_helperpath(); } -void -LPESimplify::generateHelperPathAndSmooth(Geom::PathVector &result) +void LPESimplify::generateHelperPathAndSmooth(Geom::PathVector &result) { - if(steps < 1) { + if (steps < 1) { return; } Geom::PathVector tmp_path; Geom::CubicBezier const *cubic = nullptr; - for (auto & path_it : result) { + for (auto &path_it : result) { if (path_it.empty()) { continue; } - Geom::Path::iterator curve_it1 = path_it.begin(); // incoming curve - Geom::Path::iterator curve_it2 = ++(path_it.begin());// outgoing curve + Geom::Path::iterator curve_it1 = path_it.begin(); // incoming curve + Geom::Path::iterator curve_it2 = ++(path_it.begin()); // outgoing curve Geom::Path::iterator curve_endit = path_it.end_default(); // this determines when the loop has to stop SPCurve *nCurve = new SPCurve(); if (path_it.closed()) { // if the path is closed, maybe we have to stop a bit earlier because the // closing line segment has zerolength. - const Geom::Curve &closingline = - path_it.back_closed(); // the closing line segment is always of type + const Geom::Curve &closingline = path_it.back_closed(); // the closing line segment is always of type // Geom::LineSegment. if (are_near(closingline.initialPoint(), closingline.finalPoint())) { // closingline.isDegenerate() did not work, because it only checks for @@ -183,11 +176,11 @@ LPESimplify::generateHelperPathAndSmooth(Geom::PathVector &result) curve_endit = path_it.end_open(); } } - if(helper_size > 0) { + if (helper_size > 0) { drawNode(curve_it1->initialPoint()); } nCurve->moveto(curve_it1->initialPoint()); - Geom::Point start = Geom::Point(0,0); + Geom::Point start = Geom::Point(0, 0); while (curve_it1 != curve_endit) { cubic = dynamic_cast(&*curve_it1); Geom::Point point_at1 = curve_it1->initialPoint(); @@ -195,7 +188,7 @@ LPESimplify::generateHelperPathAndSmooth(Geom::PathVector &result) Geom::Point point_at3 = curve_it1->finalPoint(); Geom::Point point_at4 = curve_it1->finalPoint(); - if(start == Geom::Point(0,0)) { + if (start == Geom::Point(0, 0)) { start = point_at1; } @@ -204,10 +197,10 @@ LPESimplify::generateHelperPathAndSmooth(Geom::PathVector &result) point_at2 = (*cubic)[2]; } - if(path_it.closed() && curve_it2 == curve_endit) { + if (path_it.closed() && curve_it2 == curve_endit) { point_at4 = start; } - if(curve_it2 != curve_endit) { + if (curve_it2 != curve_endit) { cubic = dynamic_cast(&*curve_it2); if (cubic) { point_at4 = (*cubic)[1]; @@ -217,29 +210,30 @@ LPESimplify::generateHelperPathAndSmooth(Geom::PathVector &result) Geom::Ray ray2(point_at3, point_at4); double angle1 = Geom::deg_from_rad(ray1.angle()); double angle2 = Geom::deg_from_rad(ray2.angle()); - if((smooth_angles >= std::abs(angle2 - angle1)) && !are_near(point_at4,point_at3) && !are_near(point_at2,point_at3)) { - double dist = Geom::distance(point_at2,point_at3); + if ((smooth_angles >= std::abs(angle2 - angle1)) && !are_near(point_at4, point_at3) && + !are_near(point_at2, point_at3)) { + double dist = Geom::distance(point_at2, point_at3); Geom::Angle angleFixed = ray2.angle(); angleFixed -= Geom::Angle::from_degrees(180.0); - point_at2 = Geom::Point::polar(angleFixed, dist) + point_at3; + point_at2 = Geom::Point::polar(angleFixed, dist) + point_at3; } nCurve->curveto(point_at1, point_at2, curve_it1->finalPoint()); cubic = dynamic_cast(nCurve->last_segment()); if (cubic) { point_at1 = (*cubic)[1]; point_at2 = (*cubic)[2]; - if(helper_size > 0) { - if(!are_near((*cubic)[0],(*cubic)[1])) { + if (helper_size > 0) { + if (!are_near((*cubic)[0], (*cubic)[1])) { drawHandle((*cubic)[1]); - drawHandleLine((*cubic)[0],(*cubic)[1]); + drawHandleLine((*cubic)[0], (*cubic)[1]); } - if(!are_near((*cubic)[3],(*cubic)[2])) { + if (!are_near((*cubic)[3], (*cubic)[2])) { drawHandle((*cubic)[2]); - drawHandleLine((*cubic)[3],(*cubic)[2]); + drawHandleLine((*cubic)[3], (*cubic)[2]); } } } - if(helper_size > 0) { + if (helper_size > 0) { drawNode(curve_it1->finalPoint()); } ++curve_it1; @@ -255,52 +249,48 @@ LPESimplify::generateHelperPathAndSmooth(Geom::PathVector &result) result = tmp_path; } -void -LPESimplify::drawNode(Geom::Point p) +void LPESimplify::drawNode(Geom::Point p) { double r = radius_helper_nodes; - char const * svgd; - svgd = "M 0.55,0.5 A 0.05,0.05 0 0 1 0.5,0.55 0.05,0.05 0 0 1 0.45,0.5 0.05,0.05 0 0 1 0.5,0.45 0.05,0.05 0 0 1 0.55,0.5 Z M 0,0 1,0 1,1 0,1 Z"; + char const *svgd; + svgd = "M 0.55,0.5 A 0.05,0.05 0 0 1 0.5,0.55 0.05,0.05 0 0 1 0.45,0.5 0.05,0.05 0 0 1 0.5,0.45 0.05,0.05 0 0 1 " + "0.55,0.5 Z M 0,0 1,0 1,1 0,1 Z"; Geom::PathVector pathv = sp_svg_read_pathv(svgd); - pathv *= Geom::Scale(r) * Geom::Translate(p - Geom::Point(0.5*r,0.5*r)); + pathv *= Geom::Scale(r) * Geom::Translate(p - Geom::Point(0.5 * r, 0.5 * r)); hp.push_back(pathv[0]); hp.push_back(pathv[1]); } -void -LPESimplify::drawHandle(Geom::Point p) +void LPESimplify::drawHandle(Geom::Point p) { double r = radius_helper_nodes; - char const * svgd; - svgd = "M 0.7,0.35 A 0.35,0.35 0 0 1 0.35,0.7 0.35,0.35 0 0 1 0,0.35 0.35,0.35 0 0 1 0.35,0 0.35,0.35 0 0 1 0.7,0.35 Z"; + char const *svgd; + svgd = "M 0.7,0.35 A 0.35,0.35 0 0 1 0.35,0.7 0.35,0.35 0 0 1 0,0.35 0.35,0.35 0 0 1 0.35,0 0.35,0.35 0 0 1 " + "0.7,0.35 Z"; Geom::PathVector pathv = sp_svg_read_pathv(svgd); - pathv *= Geom::Scale(r) * Geom::Translate(p - Geom::Point(0.35*r,0.35*r)); + pathv *= Geom::Scale(r) * Geom::Translate(p - Geom::Point(0.35 * r, 0.35 * r)); hp.push_back(pathv[0]); } - -void -LPESimplify::drawHandleLine(Geom::Point p,Geom::Point p2) +void LPESimplify::drawHandleLine(Geom::Point p, Geom::Point p2) { Geom::Path path; - path.start( p ); + path.start(p); double diameter = radius_helper_nodes; - if(helper_size > 0 && Geom::distance(p,p2) > (diameter * 0.35)) { + if (helper_size > 0 && Geom::distance(p, p2) > (diameter * 0.35)) { Geom::Ray ray2(p, p2); - p2 = p2 - Geom::Point::polar(ray2.angle(),(diameter * 0.35)); + p2 = p2 - Geom::Point::polar(ray2.angle(), (diameter * 0.35)); } - path.appendNew( p2 ); + path.appendNew(p2); hp.push_back(path); } -void -LPESimplify::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) +void LPESimplify::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { hp_vec.push_back(hp); } - -}; //namespace LivePathEffect +}; // namespace LivePathEffect }; /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-simplify.h b/src/live_effects/lpe-simplify.h index 9eb3d15e9b5c5fc1daeb7ba96f1195ed7a85328a..8656c2bf0691731d8f663a974ea81dcda42b082f 100644 --- a/src/live_effects/lpe-simplify.h +++ b/src/live_effects/lpe-simplify.h @@ -8,14 +8,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "live_effects/effect.h" -#include "live_effects/parameter/togglebutton.h" #include "live_effects/lpegroupbbox.h" +#include "live_effects/parameter/togglebutton.h" namespace Inkscape { namespace LivePathEffect { -class LPESimplify : public Effect , GroupBBoxEffect { - +class LPESimplify + : public Effect + , GroupBBoxEffect +{ public: LPESimplify(LivePathEffectObject *lpeobject); ~LPESimplify() override; @@ -24,21 +26,21 @@ public: void doEffect(SPCurve *curve) override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; virtual void generateHelperPathAndSmooth(Geom::PathVector &result); - Gtk::Widget * newWidget() override; + Gtk::Widget *newWidget() override; virtual void drawNode(Geom::Point p); virtual void drawHandle(Geom::Point p); - virtual void drawHandleLine(Geom::Point p,Geom::Point p2); + virtual void drawHandleLine(Geom::Point p, Geom::Point p2); ScalarParam threshold; - protected: - void addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) override; +protected: + void addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) override; private: ScalarParam steps; @@ -52,6 +54,6 @@ private: Geom::OptRect bbox; }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-skeleton.cpp b/src/live_effects/lpe-skeleton.cpp index 302a6a29494d275f5a0b141d9aaba2e13e96ed31..e760e7b6aba6d7419e32ca2ee2b746543af7f023 100644 --- a/src/live_effects/lpe-skeleton.cpp +++ b/src/live_effects/lpe-skeleton.cpp @@ -27,13 +27,14 @@ namespace Inkscape { namespace LivePathEffect { -LPESkeleton::LPESkeleton(LivePathEffectObject *lpeobject) : - Effect(lpeobject), +LPESkeleton::LPESkeleton(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , // initialise your parameters here: number(_("Float parameter"), _("just a real number like 1.4!"), "svgname", &wr, this, 1.2) { /* uncomment the following line to have the original path displayed while the item is selected */ - //show_orig_path = true; + // show_orig_path = true; /* uncomment the following line to enable display of the effect-specific on-canvas handles (knotholder entities) */ //_provides_knotholder_entities @@ -41,9 +42,7 @@ LPESkeleton::LPESkeleton(LivePathEffectObject *lpeobject) : registerParameter(&number); } -LPESkeleton::~LPESkeleton() -= default; - +LPESkeleton::~LPESkeleton() = default; /* ######################## * Choose to implement one of the doEffect functions. You can delete or comment out the others. @@ -67,12 +66,12 @@ LPESkeleton::doEffect_path (Geom::PathVector const & path_in) } */ -Geom::Piecewise > -LPESkeleton::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPESkeleton::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { - Geom::Piecewise > output; + Geom::Piecewise> output; - output = pwd2_in; // spice this up to make the effect actually *do* something! + output = pwd2_in; // spice this up to make the effect actually *do* something! return output; } @@ -109,7 +108,7 @@ LPESkeleton::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) { /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-skeleton.h b/src/live_effects/lpe-skeleton.h index 57d6d73734b1ea00416d4db03c17dd9cc45e06b0..7d647a65b02169f084015ccb2133a75d9d449751 100644 --- a/src/live_effects/lpe-skeleton.h +++ b/src/live_effects/lpe-skeleton.h @@ -30,31 +30,33 @@ namespace Skeleton { } **/ -class LPESkeleton : public Effect { +class LPESkeleton : public Effect +{ public: LPESkeleton(LivePathEffectObject *lpeobject); ~LPESkeleton() override; -// Choose to implement one of the doEffect functions. You can delete or comment out the others. -// virtual void doEffect (SPCurve * curve); -// virtual Geom::PathVector doEffect_path (Geom::PathVector const &path_in); - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const &pwd2_in) override; + // Choose to implement one of the doEffect functions. You can delete or comment out the others. + // virtual void doEffect (SPCurve * curve); + // virtual Geom::PathVector doEffect_path (Geom::PathVector const &path_in); + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; /* the knotholder entity classes (if any) can be declared friends */ - //friend class Skeleton::KnotHolderEntityMyHandle; - //virtual void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item); + // friend class Skeleton::KnotHolderEntityMyHandle; + // virtual void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item); private: // add the parameters for your effect here: ScalarParam number; // there are all kinds of parameters. Check the /live_effects/parameter directory which types exist! - LPESkeleton(const LPESkeleton&) = delete; - LPESkeleton& operator=(const LPESkeleton&) = delete; + LPESkeleton(const LPESkeleton &) = delete; + LPESkeleton &operator=(const LPESkeleton &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-sketch.cpp b/src/live_effects/lpe-sketch.cpp index 614d71102c8507de24deacbb45fb75f227e67fd0..927bc573f0b326fecec0803bd2bc2fb9465339f2 100644 --- a/src/live_effects/lpe-sketch.cpp +++ b/src/live_effects/lpe-sketch.cpp @@ -15,9 +15,9 @@ #include "live_effects/lpe-sketch.h" // You might need to include other 2geom files. You can add them here: -#include <2geom/sbasis-math.h> #include <2geom/bezier-to-sbasis.h> #include <2geom/path-intersection.h> +#include <2geom/sbasis-math.h> // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -25,45 +25,51 @@ namespace Inkscape { namespace LivePathEffect { -LPESketch::LPESketch(LivePathEffectObject *lpeobject) : - Effect(lpeobject), +LPESketch::LPESketch(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , // initialise your parameters here: - //testpointA(_("Test Point A"), _("Test A"), "ptA", &wr, this, Geom::Point(100,100)), - nbiter_approxstrokes(_("Strokes:"), _("Draw that many approximating strokes"), "nbiter_approxstrokes", &wr, this, 5), - strokelength(_("Max stroke length:"), - _("Maximum length of approximating strokes"), "strokelength", &wr, this, 100.), - strokelength_rdm(_("Stroke length variation:"), - _("Random variation of stroke length (relative to maximum length)"), "strokelength_rdm", &wr, this, .3), - strokeoverlap(_("Max. overlap:"), - _("How much successive strokes should overlap (relative to maximum length)"), "strokeoverlap", &wr, this, .3), - strokeoverlap_rdm(_("Overlap variation:"), - _("Random variation of overlap (relative to maximum overlap)"), "strokeoverlap_rdm", &wr, this, .3), - ends_tolerance(_("Max. end tolerance:"), - _("Maximum distance between ends of original and approximating paths (relative to maximum length)"), "ends_tolerance", &wr, this, .1), - parallel_offset(_("Average offset:"), - _("Average distance each stroke is away from the original path"), "parallel_offset", &wr, this, 5.), - tremble_size(_("Max. tremble:"), - _("Maximum tremble magnitude"), "tremble_size", &wr, this, 5.), - tremble_frequency(_("Tremble frequency:"), - _("Average number of tremble periods in a stroke"), "tremble_frequency", &wr, this, 1.) + // testpointA(_("Test Point A"), _("Test A"), "ptA", &wr, this, Geom::Point(100,100)), + nbiter_approxstrokes(_("Strokes:"), _("Draw that many approximating strokes"), "nbiter_approxstrokes", &wr, this, 5) + , strokelength(_("Max stroke length:"), _("Maximum length of approximating strokes"), "strokelength", &wr, this, + 100.) + , strokelength_rdm(_("Stroke length variation:"), + _("Random variation of stroke length (relative to maximum length)"), "strokelength_rdm", &wr, + this, .3) + , strokeoverlap(_("Max. overlap:"), _("How much successive strokes should overlap (relative to maximum length)"), + "strokeoverlap", &wr, this, .3) + , strokeoverlap_rdm(_("Overlap variation:"), _("Random variation of overlap (relative to maximum overlap)"), + "strokeoverlap_rdm", &wr, this, .3) + , ends_tolerance( + _("Max. end tolerance:"), + _("Maximum distance between ends of original and approximating paths (relative to maximum length)"), + "ends_tolerance", &wr, this, .1) + , parallel_offset(_("Average offset:"), _("Average distance each stroke is away from the original path"), + "parallel_offset", &wr, this, 5.) + , tremble_size(_("Max. tremble:"), _("Maximum tremble magnitude"), "tremble_size", &wr, this, 5.) + , tremble_frequency(_("Tremble frequency:"), _("Average number of tremble periods in a stroke"), + "tremble_frequency", &wr, this, 1.) #ifdef LPE_SKETCH_USE_CONSTRUCTION_LINES - ,nbtangents(_("Construction lines:"), - _("How many construction lines (tangents) to draw"), "nbtangents", &wr, this, 5), - tgtscale(_("Scale:"), - _("Scale factor relating curvature and length of construction lines (try 5*offset)"), "tgtscale", &wr, this, 10.0), - tgtlength(_("Max. length:"), _("Maximum length of construction lines"), "tgtlength", &wr, this, 100.0), - tgtlength_rdm(_("Length variation:"), _("Random variation of the length of construction lines"), "tgtlength_rdm", &wr, this, .3), - tgt_places_rdmness(_("Placement randomness:"), _("0: evenly distributed construction lines, 1: purely random placement"), "tgt_places_rdmness", &wr, this, 1.) + , nbtangents(_("Construction lines:"), _("How many construction lines (tangents) to draw"), "nbtangents", &wr, this, + 5) + , tgtscale(_("Scale:"), _("Scale factor relating curvature and length of construction lines (try 5*offset)"), + "tgtscale", &wr, this, 10.0) + , tgtlength(_("Max. length:"), _("Maximum length of construction lines"), "tgtlength", &wr, this, 100.0) + , tgtlength_rdm(_("Length variation:"), _("Random variation of the length of construction lines"), "tgtlength_rdm", + &wr, this, .3) + , tgt_places_rdmness(_("Placement randomness:"), + _("0: evenly distributed construction lines, 1: purely random placement"), + "tgt_places_rdmness", &wr, this, 1.) #ifdef LPE_SKETCH_USE_CURVATURE - ,min_curvature(_("k_min:"), _("min curvature"), "k_min", &wr, this, 4.0) - ,max_curvature(_("k_max:"), _("max curvature"), "k_max", &wr, this, 1000.0) + , min_curvature(_("k_min:"), _("min curvature"), "k_min", &wr, this, 4.0) + , max_curvature(_("k_max:"), _("max curvature"), "k_max", &wr, this, 1000.0) #endif #endif { // register all your parameters here, so Inkscape knows which parameters this effect has: - //Add some comment in the UI: *warning* the precise output of this effect might change in future releases! - //convert to path if you want to keep exact output unchanged in future releases... - //registerParameter(&testpointA) ); + // Add some comment in the UI: *warning* the precise output of this effect might change in future releases! + // convert to path if you want to keep exact output unchanged in future releases... + // registerParameter(&testpointA) ); registerParameter(&nbiter_approxstrokes); registerParameter(&strokelength); registerParameter(&strokelength_rdm); @@ -107,14 +113,13 @@ LPESketch::LPESketch(LivePathEffectObject *lpeobject) : tgtlength.param_set_increments(1., 5.); tgtlength_rdm.param_set_range(0, 1.); tgt_places_rdmness.param_set_range(0, 1.); - //this is not very smart, but required to avoid having lot of tangents stacked on short components. - //Note: we could specify a density instead of an absolute number, but this would be scale dependent. + // this is not very smart, but required to avoid having lot of tangents stacked on short components. + // Note: we could specify a density instead of an absolute number, but this would be scale dependent. concatenate_before_pwd2 = true; #endif } -LPESketch::~LPESketch() -= default; +LPESketch::~LPESketch() = default; /* Geom::Piecewise > @@ -146,137 +151,137 @@ addLinearEnds (Geom::Piecewise > & m){ } */ - - -//This returns a random perturbation. Notice the domain is [s0,s0+first multiple of period>s1]... -Geom::Piecewise > -LPESketch::computePerturbation (double s0, double s1){ +// This returns a random perturbation. Notice the domain is [s0,s0+first multiple of period>s1]... +Geom::Piecewise> LPESketch::computePerturbation(double s0, double s1) +{ using namespace Geom; - Piecewise >res; - - //global offset for this stroke. - double offsetX = 2*parallel_offset-parallel_offset.get_value(); - double offsetY = 2*parallel_offset-parallel_offset.get_value(); - Point A,dA,B,dB,offset = Point(offsetX,offsetY); - //start point A - for (unsigned dim=0; dim<2; dim++){ - A[dim] = offset[dim] + 2*tremble_size-tremble_size.get_value(); - dA[dim] = 2*tremble_size-tremble_size.get_value(); + Piecewise> res; + + // global offset for this stroke. + double offsetX = 2 * parallel_offset - parallel_offset.get_value(); + double offsetY = 2 * parallel_offset - parallel_offset.get_value(); + Point A, dA, B, dB, offset = Point(offsetX, offsetY); + // start point A + for (unsigned dim = 0; dim < 2; dim++) { + A[dim] = offset[dim] + 2 * tremble_size - tremble_size.get_value(); + dA[dim] = 2 * tremble_size - tremble_size.get_value(); } - //compute howmany deg 3 sbasis to concat according to frequency. + // compute howmany deg 3 sbasis to concat according to frequency. - unsigned count = unsigned((s1-s0)/strokelength*tremble_frequency)+1; - //unsigned count = unsigned((s1-s0)/tremble_frequency)+1; + unsigned count = unsigned((s1 - s0) / strokelength * tremble_frequency) + 1; + // unsigned count = unsigned((s1-s0)/tremble_frequency)+1; - for (unsigned i=0; i perturb = D2(SBasis(2, Linear()), SBasis(2, Linear())); - for (unsigned dim=0; dim<2; dim++){ - B[dim] = offset[dim] + 2*tremble_size-tremble_size.get_value(); - perturb[dim][0] = Linear(A[dim],B[dim]); - dA[dim] = dA[dim]-B[dim]+A[dim]; - //avoid dividing by 0. Very short strokes will have ends parallel to the curve... - if ( s1-s0 > 1e-2) - dB[dim] = -(2*tremble_size-tremble_size.get_value())/(s0-s1)-B[dim]+A[dim]; + for (unsigned dim = 0; dim < 2; dim++) { + B[dim] = offset[dim] + 2 * tremble_size - tremble_size.get_value(); + perturb[dim][0] = Linear(A[dim], B[dim]); + dA[dim] = dA[dim] - B[dim] + A[dim]; + // avoid dividing by 0. Very short strokes will have ends parallel to the curve... + if (s1 - s0 > 1e-2) + dB[dim] = -(2 * tremble_size - tremble_size.get_value()) / (s0 - s1) - B[dim] + A[dim]; else - dB[dim] = -(2*tremble_size-tremble_size.get_value())-B[dim]+A[dim]; - perturb[dim][1] = Linear(dA[dim],dB[dim]); + dB[dim] = -(2 * tremble_size - tremble_size.get_value()) - B[dim] + A[dim]; + perturb[dim][1] = Linear(dA[dim], dB[dim]); } - dA = B-A-dB; + dA = B - A - dB; A = B; - //dA = B-A-dB; - res.concat(Piecewise >(perturb)); + // dA = B-A-dB; + res.concat(Piecewise>(perturb)); } - res.setDomain(Interval(s0,s0+count*strokelength/tremble_frequency)); - //res.setDomain(Interval(s0,s0+count*tremble_frequency)); + res.setDomain(Interval(s0, s0 + count * strokelength / tremble_frequency)); + // res.setDomain(Interval(s0,s0+count*tremble_frequency)); return res; } - // Main effect body... -Geom::Piecewise > -LPESketch::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> LPESketch::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; - //If the input path is empty, do nothing. - //Note: this happens when duplicating a 3d box... dunno why. - if (pwd2_in.size()==0) return pwd2_in; + // If the input path is empty, do nothing. + // Note: this happens when duplicating a 3d box... dunno why. + if (pwd2_in.size() == 0) + return pwd2_in; - Piecewise > output; + Piecewise> output; // some variables for futur use (for construction lines; compute arclength only once...) // notations will be : t = path time, s = distance from start along the path. Piecewise pathlength; double total_length = 0; - //TODO: split Construction Lines/Approximated Strokes into two separate effects? + // TODO: split Construction Lines/Approximated Strokes into two separate effects? //----- Approximated Strokes. - std::vector > > pieces_in = split_at_discontinuities (pwd2_in); - - //work separately on each component. - for (auto piece : pieces_in){ + std::vector>> pieces_in = split_at_discontinuities(pwd2_in); - Piecewise piecelength = arcLengthSb(piece,.1); - double piece_total_length = piecelength.segs.back().at1()-piecelength.segs.front().at0(); + // work separately on each component. + for (auto piece : pieces_in) { + Piecewise piecelength = arcLengthSb(piece, .1); + double piece_total_length = piecelength.segs.back().at1() - piecelength.segs.front().at0(); pathlength.concat(piecelength + total_length); total_length += piece_total_length; - - //TODO: better check this on the Geom::Path. + // TODO: better check this on the Geom::Path. bool closed = piece.segs.front().at0() == piece.segs.back().at1(); - if (closed){ + if (closed) { piece.concat(piece); - piecelength.concat(piecelength+piece_total_length); + piecelength.concat(piecelength + piece_total_length); } - for (unsigned i = 0; ipiece_total_length - ends_tolerance.get_value()*strokelength) break; - if ( closed && s0>piece_total_length + s0_initial) break; + if (!closed && s1 > piece_total_length - ends_tolerance.get_value() * strokelength) + break; + if (closed && s0 > piece_total_length + s0_initial) + break; std::vector times; - times = roots(piecelength-s0); - t0 = times.at(0);//there should be one and only one solution!! + times = roots(piecelength - s0); + t0 = times.at(0); // there should be one and only one solution!! // pick a new end point (s1 = s0 + strokelength). - s1 = s0 + strokelength*(1-strokelength_rdm); + s1 = s0 + strokelength * (1 - strokelength_rdm); // don't let it go beyond the end of the original path. // TODO/FIXME: this might result in short strokes near the end... - if (!closed && s1>piece_total_length-ends_tolerance.get_value()*strokelength){ + if (!closed && s1 > piece_total_length - ends_tolerance.get_value() * strokelength) { done = true; //!!the root solver might miss s1==piece_total_length... - if (s1>piece_total_length){s1 = piece_total_length - ends_tolerance*strokelength-0.0001;} + if (s1 > piece_total_length) { + s1 = piece_total_length - ends_tolerance * strokelength - 0.0001; + } } - if (closed && s1>piece_total_length + s0_initial){ + if (closed && s1 > piece_total_length + s0_initial) { done = true; - if (closed && s1>2*piece_total_length){ - s1 = 2*piece_total_length - strokeoverlap*(1-strokeoverlap_rdm)*strokelength-0.0001; + if (closed && s1 > 2 * piece_total_length) { + s1 = 2 * piece_total_length - strokeoverlap * (1 - strokeoverlap_rdm) * strokelength - 0.0001; } } - times = roots(piecelength-s1); - if (times.empty()) break;//we should not be there. + times = roots(piecelength - s1); + if (times.empty()) + break; // we should not be there. t1 = times[0]; - //pick a rdm perturbation, and collect the perturbed piece into output. - Piecewise > pwperturb = computePerturbation(s0-0.01,s1+0.01); - pwperturb = compose(pwperturb,portion(piecelength,t0,t1)); + // pick a rdm perturbation, and collect the perturbed piece into output. + Piecewise> pwperturb = computePerturbation(s0 - 0.01, s1 + 0.01); + pwperturb = compose(pwperturb, portion(piecelength, t0, t1)); - output.concat(portion(piece,t0,t1)+pwperturb); + output.concat(portion(piece, t0, t1) + pwperturb); - //step points: s0 = s1 - overlap. - //TODO: make sure this has to end? - s0 = s1 - strokeoverlap*(1-strokeoverlap_rdm)*(s1-s0); + // step points: s0 = s1 - overlap. + // TODO: make sure this has to end? + s0 = s1 - strokeoverlap * (1 - strokeoverlap_rdm) * (s1 - s0); } } } @@ -284,14 +289,14 @@ LPESketch::doEffect_pwd2 (Geom::Piecewise > const & pwd2_ #ifdef LPE_SKETCH_USE_CONSTRUCTION_LINES //----- Construction lines. - //TODO: choose places according to curvature?. + // TODO: choose places according to curvature?. - //at this point we should have: - //pathlength = arcLengthSb(pwd2_in,.1); - //total_length = pathlength.segs.back().at1()-pathlength.segs.front().at0(); - Piecewise > m = pwd2_in; - Piecewise > v = derivative(pwd2_in); - Piecewise > a = derivative(v); + // at this point we should have: + // pathlength = arcLengthSb(pwd2_in,.1); + // total_length = pathlength.segs.back().at1()-pathlength.segs.front().at0(); + Piecewise> m = pwd2_in; + Piecewise> v = derivative(pwd2_in); + Piecewise> a = derivative(v); #ifdef LPE_SKETCH_USE_CURVATURE //---- curvature experiment...(enable @@ -301,61 +306,60 @@ LPESketch::doEffect_pwd2 (Geom::Piecewise > const & pwd2_ double k_max = k_bnds->min() + k_bnds->extent() * max_curvature; Piecewise bump; - //SBasis bump_seg = SBasis( 2, Linear(0) ); - //bump_seg[1] = Linear( 4. ); - SBasis bump_seg = SBasis( 1, Linear(1) ); - bump.push_cut( k_bnds->min() - 1 ); - bump.push( Linear(0), k_min ); - bump.push(bump_seg,k_max); - bump.push( Linear(0), k_bnds->max()+1 ); - - Piecewise repartition = compose( bump, k ); + // SBasis bump_seg = SBasis( 2, Linear(0) ); + // bump_seg[1] = Linear( 4. ); + SBasis bump_seg = SBasis(1, Linear(1)); + bump.push_cut(k_bnds->min() - 1); + bump.push(Linear(0), k_min); + bump.push(bump_seg, k_max); + bump.push(Linear(0), k_bnds->max() + 1); + + Piecewise repartition = compose(bump, k); repartition = integral(repartition); //------------------------------- #endif - for (unsigned i=0; i times; times = roots(repartition - proba); - double t = times.at(0);//there should be one and only one solution! + double t = times.at(0); // there should be one and only one solution! #else - //double s = total_length * ( i + tgtlength_rdm ) / (nbtangents+1.); - double reg_place = total_length * ( i + .5) / ( nbtangents ); + // double s = total_length * ( i + tgtlength_rdm ) / (nbtangents+1.); + double reg_place = total_length * (i + .5) / (nbtangents); double rdm_place = total_length * tgt_places_rdmness; - double s = ( 1.- tgt_places_rdmness.get_value() ) * reg_place + rdm_place ; + double s = (1. - tgt_places_rdmness.get_value()) * reg_place + rdm_place; std::vector times; - times = roots(pathlength-s); - double t = times.at(0);//there should be one and only one solution! + times = roots(pathlength - s); + double t = times.at(0); // there should be one and only one solution! #endif Point m_t = m(t), v_t = v(t), a_t = a(t); - //Compute tgt length according to curvature (not exceeding tgtlength) so that + // Compute tgt length according to curvature (not exceeding tgtlength) so that // dist to original curve ~ 4 * (parallel_offset+tremble_size). - //TODO: put this 4 as a parameter in the UI... - //TODO: what if with v=0? - double l = tgtlength*(1-tgtlength_rdm)/v_t.length(); + // TODO: put this 4 as a parameter in the UI... + // TODO: what if with v=0? + double l = tgtlength * (1 - tgtlength_rdm) / v_t.length(); double r = std::pow(v_t.length(), 3) / cross(v_t, a_t); - r = sqrt((2*fabs(r)-tgtscale)*tgtscale)/v_t.length(); - l=(r tgt = D2(); - for (unsigned dim=0; dim<2; dim++){ - tgt[dim] = SBasis(Linear(m_t[dim]-v_t[dim]*l, m_t[dim]+v_t[dim]*l)); + for (unsigned dim = 0; dim < 2; dim++) { + tgt[dim] = SBasis(Linear(m_t[dim] - v_t[dim] * l, m_t[dim] + v_t[dim] * l)); } - output.concat(Piecewise >(tgt)); + output.concat(Piecewise>(tgt)); } #endif return output; } -void -LPESketch::doBeforeEffect (SPLPEItem const*/*lpeitem*/) +void LPESketch::doBeforeEffect(SPLPEItem const * /*lpeitem*/) { - //init random parameters. + // init random parameters. parallel_offset.resetRandomizer(); strokelength_rdm.resetRandomizer(); strokeoverlap_rdm.resetRandomizer(); @@ -369,7 +373,7 @@ LPESketch::doBeforeEffect (SPLPEItem const*/*lpeitem*/) /* ######################## */ -} //namespace LivePathEffect (setq default-directory "c:/Documents And Settings/jf/Mes Documents/InkscapeSVN") +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-sketch.h b/src/live_effects/lpe-sketch.h index 4d34088d06a8d84553152358e7ef32b7212e44f4..05223f761a523c94714be07765d8ec9d6efd9448 100644 --- a/src/live_effects/lpe-sketch.h +++ b/src/live_effects/lpe-sketch.h @@ -16,8 +16,8 @@ #include "live_effects/effect.h" #include "live_effects/parameter/parameter.h" -#include "live_effects/parameter/random.h" #include "live_effects/parameter/point.h" +#include "live_effects/parameter/random.h" #define LPE_SKETCH_USE_CONSTRUCTION_LINES //#define LPE_SKETCH_USE_CURVATURE @@ -25,18 +25,20 @@ namespace Inkscape { namespace LivePathEffect { -class LPESketch : public Effect { +class LPESketch : public Effect +{ public: LPESketch(LivePathEffectObject *lpeobject); ~LPESketch() override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; private: // add the parameters for your effect here: - //PointParam testpointA; + // PointParam testpointA; ScalarParam nbiter_approxstrokes; ScalarParam strokelength; RandomParam strokelength_rdm; @@ -58,15 +60,14 @@ private: ScalarParam max_curvature; #endif #endif - LPESketch(const LPESketch&) = delete; - LPESketch& operator=(const LPESketch&) = delete; - - Geom::Piecewise > computePerturbation (double s0, double s1); + LPESketch(const LPESketch &) = delete; + LPESketch &operator=(const LPESketch &) = delete; + Geom::Piecewise> computePerturbation(double s0, double s1); }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-spiro.cpp b/src/live_effects/lpe-spiro.cpp index e0464a2a04ed36a50924ec3d841510dbd6e4b275..4fda8b826018b79958ee04083e1b3d720af4f8d8 100644 --- a/src/live_effects/lpe-spiro.cpp +++ b/src/live_effects/lpe-spiro.cpp @@ -7,35 +7,33 @@ #include "live_effects/lpe-spiro.h" -#include "display/curve.h" #include <2geom/curves.h> -#include "helper/geom-nodetype.h" -#include "helper/geom-curves.h" +#include "display/curve.h" +#include "helper/geom-curves.h" +#include "helper/geom-nodetype.h" #include "live_effects/spiro.h" // For handling un-continuous paths: -#include "message-stack.h" #include "inkscape.h" +#include "message-stack.h" namespace Inkscape { namespace LivePathEffect { -LPESpiro::LPESpiro(LivePathEffectObject *lpeobject) : - Effect(lpeobject) -{ -} +LPESpiro::LPESpiro(LivePathEffectObject *lpeobject) + : Effect(lpeobject) +{} -LPESpiro::~LPESpiro() -= default; +LPESpiro::~LPESpiro() = default; -void -LPESpiro::doEffect(SPCurve * curve) +void LPESpiro::doEffect(SPCurve *curve) { sp_spiro_do_effect(curve); } -void sp_spiro_do_effect(SPCurve *curve){ +void sp_spiro_do_effect(SPCurve *curve) +{ using Geom::X; using Geom::Y; @@ -44,10 +42,10 @@ void sp_spiro_do_effect(SPCurve *curve){ guint len = curve->get_segment_count() + 2; curve->reset(); - Spiro::spiro_cp *path = g_new (Spiro::spiro_cp, len); + Spiro::spiro_cp *path = g_new(Spiro::spiro_cp, len); int ip = 0; - for(const auto & path_it : original_pathv) { + for (const auto &path_it : original_pathv) { if (path_it.empty()) continue; @@ -56,17 +54,16 @@ void sp_spiro_do_effect(SPCurve *curve){ Geom::Point p = path_it.initialPoint(); path[ip].x = p[X]; path[ip].y = p[Y]; - path[ip].ty = '{' ; // for closed paths, this is overwritten + path[ip].ty = '{'; // for closed paths, this is overwritten ip++; } // midpoints - Geom::Path::const_iterator curve_it1 = path_it.begin(); // incoming curve - Geom::Path::const_iterator curve_it2 = ++(path_it.begin()); // outgoing curve + Geom::Path::const_iterator curve_it1 = path_it.begin(); // incoming curve + Geom::Path::const_iterator curve_it2 = ++(path_it.begin()); // outgoing curve Geom::Path::const_iterator curve_endit = path_it.end_default(); // this determines when the loop has to stop - while ( curve_it2 != curve_endit ) - { + while (curve_it2 != curve_endit) { /* This deals with the node between curve_it1 and curve_it2. * Loop to end_default (so without last segment), loop ends when curve_it2 hits the end * and then curve_it1 points to end or closing segment */ @@ -81,8 +78,7 @@ void sp_spiro_do_effect(SPCurve *curve){ Geom::NodeType nodetype = Geom::get_nodetype(*curve_it1, *curve_it2); - if ( nodetype == Geom::NODE_SMOOTH || nodetype == Geom::NODE_SYMM ) - { + if (nodetype == Geom::NODE_SMOOTH || nodetype == Geom::NODE_SYMM) { if (this_is_line && !next_is_line) { path[ip].ty = ']'; } else if (next_is_line && !this_is_line) { @@ -104,7 +100,8 @@ void sp_spiro_do_effect(SPCurve *curve){ path[ip].x = p[X]; path[ip].y = p[Y]; if (path_it.closed()) { - // curve_it1 points to the (visually) closing segment. determine the match between first and this last segment (the closing node) + // curve_it1 points to the (visually) closing segment. determine the match between first and this last + // segment (the closing node) Geom::NodeType nodetype = Geom::get_nodetype(*curve_it1, path_it.front()); switch (nodetype) { case Geom::NODE_NONE: // can't happen! but if it does, it means the path isn't closed :-) @@ -131,10 +128,10 @@ void sp_spiro_do_effect(SPCurve *curve){ ip = 0; } - g_free (path); + g_free(path); } -}; //namespace LivePathEffect +}; // namespace LivePathEffect }; /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-spiro.h b/src/live_effects/lpe-spiro.h index ce07de854a0a9e1e3a465a9b118f25e164223d5c..5cf3371d80819867f856499d37a754fd6fa615ca 100644 --- a/src/live_effects/lpe-spiro.h +++ b/src/live_effects/lpe-spiro.h @@ -10,25 +10,25 @@ #include "live_effects/effect.h" - namespace Inkscape { namespace LivePathEffect { -class LPESpiro : public Effect { +class LPESpiro : public Effect +{ public: LPESpiro(LivePathEffectObject *lpeobject); ~LPESpiro() override; - LPESpiro(const LPESpiro&) = delete; - LPESpiro& operator=(const LPESpiro&) = delete; + LPESpiro(const LPESpiro &) = delete; + LPESpiro &operator=(const LPESpiro &) = delete; LPEPathFlashType pathFlashType() const override { return SUPPRESS_FLASH; } - void doEffect(SPCurve * curve) override; + void doEffect(SPCurve *curve) override; }; void sp_spiro_do_effect(SPCurve *curve); -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-tangent_to_curve.cpp b/src/live_effects/lpe-tangent_to_curve.cpp index 827ee466d6938f75e784736c75c021bd0ff68e7d..97e10ec3ffb915e36af25d98644cd0003dd9c470 100644 --- a/src/live_effects/lpe-tangent_to_curve.cpp +++ b/src/live_effects/lpe-tangent_to_curve.cpp @@ -15,11 +15,11 @@ */ #include "live_effects/lpe-tangent_to_curve.h" + #include "display/curve.h" #include "knotholder.h" - -#include "object/sp-shape.h" #include "object/sp-object-group.h" +#include "object/sp-shape.h" // TODO due to internal breakage in glibmm headers, this must be last: #include @@ -29,16 +29,20 @@ namespace LivePathEffect { namespace TtC { -class KnotHolderEntityAttachPt : public LPEKnotHolderEntity { +class KnotHolderEntityAttachPt : public LPEKnotHolderEntity +{ public: - KnotHolderEntityAttachPt(LPETangentToCurve *effect) : LPEKnotHolderEntity(effect) {}; + KnotHolderEntityAttachPt(LPETangentToCurve *effect) + : LPEKnotHolderEntity(effect){}; void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; }; -class KnotHolderEntityLeftEnd : public LPEKnotHolderEntity { +class KnotHolderEntityLeftEnd : public LPEKnotHolderEntity +{ public: - KnotHolderEntityLeftEnd(LPETangentToCurve *effect) : LPEKnotHolderEntity(effect) {}; + KnotHolderEntityLeftEnd(LPETangentToCurve *effect) + : LPEKnotHolderEntity(effect){}; void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; }; @@ -46,19 +50,22 @@ public: class KnotHolderEntityRightEnd : public LPEKnotHolderEntity { public: - KnotHolderEntityRightEnd(LPETangentToCurve *effect) : LPEKnotHolderEntity(effect) {}; + KnotHolderEntityRightEnd(LPETangentToCurve *effect) + : LPEKnotHolderEntity(effect){}; void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; }; } // namespace TtC -LPETangentToCurve::LPETangentToCurve(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - angle(_("Angle:"), _("Additional angle between tangent and curve"), "angle", &wr, this, 0.0), - t_attach(_("Location along curve:"), _("Location of the point of attachment along the curve (between 0.0 and number-of-segments)"), "t_attach", &wr, this, 0.5), - length_left(_("Length left:"), _("Specifies the left end of the tangent"), "length-left", &wr, this, 150), - length_right(_("Length right:"), _("Specifies the right end of the tangent"), "length-right", &wr, this, 150) +LPETangentToCurve::LPETangentToCurve(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , angle(_("Angle:"), _("Additional angle between tangent and curve"), "angle", &wr, this, 0.0) + , t_attach(_("Location along curve:"), + _("Location of the point of attachment along the curve (between 0.0 and number-of-segments)"), + "t_attach", &wr, this, 0.5) + , length_left(_("Length left:"), _("Specifies the left end of the tangent"), "length-left", &wr, this, 150) + , length_right(_("Length right:"), _("Specifies the right end of the tangent"), "length-right", &wr, this, 150) { show_orig_path = true; _provides_knotholder_entities = true; @@ -69,14 +76,13 @@ LPETangentToCurve::LPETangentToCurve(LivePathEffectObject *lpeobject) : registerParameter(&length_right); } -LPETangentToCurve::~LPETangentToCurve() -= default; +LPETangentToCurve::~LPETangentToCurve() = default; -Geom::Piecewise > -LPETangentToCurve::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPETangentToCurve::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; - Piecewise > output; + Piecewise> output; ptA = pwd2_in.valueAt(t_attach); derivA = unit_vector(derivative(pwd2_in).valueAt(t_attach)); @@ -88,57 +94,53 @@ LPETangentToCurve::doEffect_pwd2 (Geom::Piecewise > const C = ptA - derivA * length_left; D = ptA + derivA * length_right; - output = Piecewise >(D2(SBasis(C[X], D[X]), SBasis(C[Y], D[Y]))); + output = Piecewise>(D2(SBasis(C[X], D[X]), SBasis(C[Y], D[Y]))); return output; } -void -LPETangentToCurve::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) { - { - KnotHolderEntity *e = new TtC::KnotHolderEntityAttachPt(this); +void LPETangentToCurve::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item){ + {KnotHolderEntity *e = new TtC::KnotHolderEntityAttachPt(this); e->create(nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the point of attachment of the tangent")); knotholder->add(e); - } - { - KnotHolderEntity *e = new TtC::KnotHolderEntityLeftEnd(this); - e->create(nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the left end of the tangent")); - knotholder->add(e); - } - { - KnotHolderEntity *e = new TtC::KnotHolderEntityRightEnd(this); - e->create(nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the right end of the tangent")); - knotholder->add(e); - } -}; +} // namespace LivePathEffect +{ + KnotHolderEntity *e = new TtC::KnotHolderEntityLeftEnd(this); + e->create(nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the left end of the tangent")); + knotholder->add(e); +} +{ + KnotHolderEntity *e = new TtC::KnotHolderEntityRightEnd(this); + e->create(nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Adjust the right end of the tangent")); + knotholder->add(e); +} +}; // namespace Inkscape namespace TtC { -void -KnotHolderEntityAttachPt::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) +void KnotHolderEntityAttachPt::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { using namespace Geom; - LPETangentToCurve* lpe = dynamic_cast(_effect); + LPETangentToCurve *lpe = dynamic_cast(_effect); Geom::Point const s = snap_knot_position(p, state); - if ( !SP_IS_SHAPE(lpe->sp_lpe_item) ) { - //lpe->t_attach.param_set_value(0); + if (!SP_IS_SHAPE(lpe->sp_lpe_item)) { + // lpe->t_attach.param_set_value(0); g_warning("LPEItem is not a path! %s:%d\n", __FILE__, __LINE__); return; } - Piecewise > pwd2 = paths_to_pw( lpe->pathvector_before_effect ); - + Piecewise> pwd2 = paths_to_pw(lpe->pathvector_before_effect); + double t0 = nearest_time(s, pwd2); lpe->t_attach.param_set_value(t0); // FIXME: this should not directly ask for updating the item. It should write to SVG, which triggers updating. - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, true); } -void -KnotHolderEntityLeftEnd::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) +void KnotHolderEntityLeftEnd::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { LPETangentToCurve *lpe = dynamic_cast(_effect); @@ -147,46 +149,42 @@ KnotHolderEntityLeftEnd::knot_set(Geom::Point const &p, Geom::Point const &/*ori double lambda = Geom::nearest_time(s, lpe->ptA, lpe->derivA); lpe->length_left.param_set_value(-lambda); - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, true); } -void -KnotHolderEntityRightEnd::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) +void KnotHolderEntityRightEnd::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { LPETangentToCurve *lpe = dynamic_cast(_effect); - + Geom::Point const s = snap_knot_position(p, state); double lambda = Geom::nearest_time(s, lpe->ptA, lpe->derivA); lpe->length_right.param_set_value(lambda); - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, true); } -Geom::Point -KnotHolderEntityAttachPt::knot_get() const +Geom::Point KnotHolderEntityAttachPt::knot_get() const { - LPETangentToCurve const *lpe = dynamic_cast(_effect); + LPETangentToCurve const *lpe = dynamic_cast(_effect); return lpe->ptA; } -Geom::Point -KnotHolderEntityLeftEnd::knot_get() const +Geom::Point KnotHolderEntityLeftEnd::knot_get() const { - LPETangentToCurve const *lpe = dynamic_cast(_effect); + LPETangentToCurve const *lpe = dynamic_cast(_effect); return lpe->C; } -Geom::Point -KnotHolderEntityRightEnd::knot_get() const +Geom::Point KnotHolderEntityRightEnd::knot_get() const { - LPETangentToCurve const *lpe = dynamic_cast(_effect); + LPETangentToCurve const *lpe = dynamic_cast(_effect); return lpe->D; } } // namespace TtC -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-tangent_to_curve.h b/src/live_effects/lpe-tangent_to_curve.h index 32cacd1c4c35b65c8c265f0e2b12146174485657..093a4186a2f5e03ebd379c23effc23411bab2a29 100644 --- a/src/live_effects/lpe-tangent_to_curve.h +++ b/src/live_effects/lpe-tangent_to_curve.h @@ -25,24 +25,25 @@ namespace Inkscape { namespace LivePathEffect { namespace TtC { - // we need a separate namespace to avoid clashes with LPEPerpBisector - class KnotHolderEntityLeftEnd; - class KnotHolderEntityRightEnd; - class KnotHolderEntityAttachPt; -} +// we need a separate namespace to avoid clashes with LPEPerpBisector +class KnotHolderEntityLeftEnd; +class KnotHolderEntityRightEnd; +class KnotHolderEntityAttachPt; +} // namespace TtC -class LPETangentToCurve : public Effect { +class LPETangentToCurve : public Effect +{ public: LPETangentToCurve(LivePathEffectObject *lpeobject); ~LPETangentToCurve() override; - Geom::Piecewise > - doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; /* the knotholder entity classes must be declared friends */ friend class TtC::KnotHolderEntityLeftEnd; friend class TtC::KnotHolderEntityRightEnd; friend class TtC::KnotHolderEntityAttachPt; - void addKnotHolderEntities(KnotHolder * knotholder, SPItem * item) override; + void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) override; private: ScalarParam angle; @@ -57,11 +58,11 @@ private: Geom::Point C; // left end of tangent Geom::Point D; // right end of tangent - LPETangentToCurve(const LPETangentToCurve&) = delete; - LPETangentToCurve& operator=(const LPETangentToCurve&) = delete; + LPETangentToCurve(const LPETangentToCurve &) = delete; + LPETangentToCurve &operator=(const LPETangentToCurve &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-taperstroke.cpp b/src/live_effects/lpe-taperstroke.cpp index 398b4261ba2c8a9b0cb085e36d82be0d3491fb80..ee14d6ce71af827f4e32cddd6b7116031da44fe3 100644 --- a/src/live_effects/lpe-taperstroke.cpp +++ b/src/live_effects/lpe-taperstroke.cpp @@ -13,27 +13,27 @@ */ #include "live_effects/lpe-taperstroke.h" -#include "live_effects/fill-conversion.h" #include <2geom/circle.h> #include <2geom/sbasis-to-bezier.h> +#include "display/curve.h" #include "helper/geom-nodetype.h" #include "helper/geom-pathstroke.h" +#include "knotholder.h" +#include "live_effects/fill-conversion.h" #include "object/sp-shape.h" -#include "display/curve.h" -#include "svg/svg-color.h" +#include "style.h" #include "svg/css-ostringstream.h" +#include "svg/svg-color.h" #include "svg/svg.h" -#include "knotholder.h" -#include "style.h" - // TODO due to internal breakage in glibmm headers, this must be last: #include -template -inline bool withinRange(T value, T low, T high) { +template +inline bool withinRange(T value, T low, T high) +{ return (value > low && value < high); } @@ -41,22 +41,28 @@ namespace Inkscape { namespace LivePathEffect { namespace TpS { - class KnotHolderEntityAttachBegin : public LPEKnotHolderEntity { - public: - KnotHolderEntityAttachBegin(LPETaperStroke * effect) : LPEKnotHolderEntity(effect) {} - void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; - void knot_click(guint state) override; - Geom::Point knot_get() const override; - }; - - class KnotHolderEntityAttachEnd : public LPEKnotHolderEntity { - public: - KnotHolderEntityAttachEnd(LPETaperStroke * effect) : LPEKnotHolderEntity(effect) {} - void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; - void knot_click(guint state) override; - Geom::Point knot_get() const override; - }; -} // TpS +class KnotHolderEntityAttachBegin : public LPEKnotHolderEntity +{ +public: + KnotHolderEntityAttachBegin(LPETaperStroke *effect) + : LPEKnotHolderEntity(effect) + {} + void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; + void knot_click(guint state) override; + Geom::Point knot_get() const override; +}; + +class KnotHolderEntityAttachEnd : public LPEKnotHolderEntity +{ +public: + KnotHolderEntityAttachEnd(LPETaperStroke *effect) + : LPEKnotHolderEntity(effect) + {} + void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; + void knot_click(guint state) override; + Geom::Point knot_get() const override; +}; +} // namespace TpS static const Util::EnumData JoinType[] = { // clang-format off @@ -67,7 +73,8 @@ static const Util::EnumData JoinType[] = { // clang-format on }; -enum TaperShape { +enum TaperShape +{ TAPER_CENTER, TAPER_RIGHT, TAPER_LEFT, @@ -76,24 +83,30 @@ enum TaperShape { static const Util::EnumData TaperShapeType[] = { {TAPER_CENTER, N_("Center"), "center"}, - {TAPER_LEFT, N_("Left"), "left"}, - {TAPER_RIGHT, N_("Right"), "right"}, + {TAPER_LEFT, N_("Left"), "left"}, + {TAPER_RIGHT, N_("Right"), "right"}, }; -static const Util::EnumDataConverter JoinTypeConverter(JoinType, sizeof (JoinType)/sizeof(*JoinType)); -static const Util::EnumDataConverter TaperShapeTypeConverter(TaperShapeType, sizeof (TaperShapeType)/sizeof(*TaperShapeType)); - -LPETaperStroke::LPETaperStroke(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - line_width(_("Stroke width:"), _("The (non-tapered) width of the path"), "stroke_width", &wr, this, 1.), - attach_start(_("Start offset:"), _("Taper distance from path start"), "attach_start", &wr, this, 0.2), - attach_end(_("End offset:"), _("The ending position of the taper"), "end_offset", &wr, this, 0.2), - start_smoothing(_("Start smoothing:"), _("Amount of smoothing to apply to the start taper"), "start_smoothing", &wr, this, 0.5), - end_smoothing(_("End smoothing:"), _("Amount of smoothing to apply to the end taper"), "end_smoothing", &wr, this, 0.5), - join_type(_("Join type:"), _("Join type for non-smooth nodes"), "jointype", JoinTypeConverter, &wr, this, JOIN_EXTRAPOLATE), - start_shape(_("Start direction:"), _("Direction of the taper at the path start"), "start_shape", TaperShapeTypeConverter, &wr, this, TAPER_CENTER), - end_shape(_("End direction:"), _("Direction of the taper at the path end"), "end_shape", TaperShapeTypeConverter, &wr, this, TAPER_CENTER), - miter_limit(_("Miter limit:"), _("Limit for miter joins"), "miter_limit", &wr, this, 100.) +static const Util::EnumDataConverter JoinTypeConverter(JoinType, sizeof(JoinType) / sizeof(*JoinType)); +static const Util::EnumDataConverter TaperShapeTypeConverter(TaperShapeType, sizeof(TaperShapeType) / + sizeof(*TaperShapeType)); + +LPETaperStroke::LPETaperStroke(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , line_width(_("Stroke width:"), _("The (non-tapered) width of the path"), "stroke_width", &wr, this, 1.) + , attach_start(_("Start offset:"), _("Taper distance from path start"), "attach_start", &wr, this, 0.2) + , attach_end(_("End offset:"), _("The ending position of the taper"), "end_offset", &wr, this, 0.2) + , start_smoothing(_("Start smoothing:"), _("Amount of smoothing to apply to the start taper"), "start_smoothing", + &wr, this, 0.5) + , end_smoothing(_("End smoothing:"), _("Amount of smoothing to apply to the end taper"), "end_smoothing", &wr, this, + 0.5) + , join_type(_("Join type:"), _("Join type for non-smooth nodes"), "jointype", JoinTypeConverter, &wr, this, + JOIN_EXTRAPOLATE) + , start_shape(_("Start direction:"), _("Direction of the taper at the path start"), "start_shape", + TaperShapeTypeConverter, &wr, this, TAPER_CENTER) + , end_shape(_("End direction:"), _("Direction of the taper at the path end"), "end_shape", TaperShapeTypeConverter, + &wr, this, TAPER_CENTER) + , miter_limit(_("Miter limit:"), _("Limit for miter joins"), "miter_limit", &wr, this, 100.) { show_orig_path = true; _provides_knotholder_entities = true; @@ -124,23 +137,22 @@ void LPETaperStroke::transform_multiply(Geom::Affine const &postmul, bool /*set* } } -void LPETaperStroke::doOnApply(SPLPEItem const* lpeitem) +void LPETaperStroke::doOnApply(SPLPEItem const *lpeitem) { if (!SP_IS_SHAPE(lpeitem)) { printf("WARNING: It only makes sense to apply Taper stroke to paths (not groups).\n"); } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - SPShape* item = SP_SHAPE(lpeitem); + SPShape *item = SP_SHAPE(lpeitem); double width = (lpeitem && lpeitem->style) ? lpeitem->style->stroke_width.computed : 1.; lpe_shape_convert_stroke_and_fill(item); - Glib::ustring pref_path = (Glib::ustring)"/live_effects/" + - (Glib::ustring)LPETypeConverter.get_key(effectType()).c_str() + - (Glib::ustring)"/" + - (Glib::ustring)"stroke_width"; + Glib::ustring pref_path = (Glib::ustring) "/live_effects/" + + (Glib::ustring)LPETypeConverter.get_key(effectType()).c_str() + (Glib::ustring) "/" + + (Glib::ustring) "stroke_width"; bool valid = prefs->getEntry(pref_path).isValid(); @@ -151,7 +163,7 @@ void LPETaperStroke::doOnApply(SPLPEItem const* lpeitem) line_width.write_to_SVG(); } -void LPETaperStroke::doOnRemove(SPLPEItem const* lpeitem) +void LPETaperStroke::doOnRemove(SPLPEItem const *lpeitem) { if (!SP_IS_SHAPE(lpeitem)) { return; @@ -162,38 +174,38 @@ void LPETaperStroke::doOnRemove(SPLPEItem const* lpeitem) lpe_shape_revert_stroke_and_fill(item, line_width); } -using Geom::Piecewise; using Geom::D2; +using Geom::Piecewise; using Geom::SBasis; // leave Geom::Path -static Geom::Path return_at_first_cusp(Geom::Path const & path_in, double /*smooth_tolerance*/ = 0.05) +static Geom::Path return_at_first_cusp(Geom::Path const &path_in, double /*smooth_tolerance*/ = 0.05) { Geom::Path temp; for (unsigned i = 0; i < path_in.size(); i++) { temp.append(path_in[i]); - if (Geom::get_nodetype(path_in[i], path_in[i + 1]) != Geom::NODE_SMOOTH ) { + if (Geom::get_nodetype(path_in[i], path_in[i + 1]) != Geom::NODE_SMOOTH) { break; } } - + return temp; } -Piecewise > stretch_along(Piecewise > pwd2_in, Geom::Path pattern, double width); +Piecewise> stretch_along(Piecewise> pwd2_in, Geom::Path pattern, double width); // actual effect -Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const& path_in) +Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const &path_in) { Geom::Path first_cusp = return_at_first_cusp(path_in[0]); Geom::Path last_cusp = return_at_first_cusp(path_in[0].reversed()); - bool zeroStart = false; // [distance from start taper knot -> start of path] == 0 - bool zeroEnd = false; // [distance from end taper knot -> end of path] == 0 + bool zeroStart = false; // [distance from start taper knot -> start of path] == 0 + bool zeroEnd = false; // [distance from end taper knot -> end of path] == 0 bool metInMiddle = false; // knots are touching - + // there is a pretty good chance that people will try to drag the knots // on top of each other, so block it @@ -201,12 +213,12 @@ Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const& path_in) if (size == first_cusp.size()) { // check to see if the knots were dragged over each other // if so, reset the end offset, but still allow the start offset. - if ( attach_start >= (size - attach_end) ) { - attach_end.param_set_value( size - attach_start ); + if (attach_start >= (size - attach_end)) { + attach_end.param_set_value(size - attach_start); metInMiddle = true; } } - + if (attach_start == size - attach_end) { metInMiddle = true; } @@ -220,7 +232,7 @@ Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const& path_in) attach_start.param_set_value(attach_start - 0.00001); } if (double(unsigned(attach_end)) == attach_end) { - attach_end.param_set_value(attach_end - 0.00001); + attach_end.param_set_value(attach_end - 0.00001); } } @@ -236,14 +248,14 @@ Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const& path_in) attach_end.param_set_value((double)allowed_end - 0.00001); } } - + // don't let it be zero (this is stupid too!) if (attach_start < 0.0000001 || withinRange(double(attach_start), 0.00000001, 0.000001)) { - attach_start.param_set_value( 0.0000001 ); + attach_start.param_set_value(0.0000001); zeroStart = true; } if (attach_end < 0.0000001 || withinRange(double(attach_end), 0.00000001, 0.000001)) { - attach_end.param_set_value( 0.0000001 ); + attach_end.param_set_value(0.0000001); zeroEnd = true; } @@ -260,7 +272,7 @@ Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const& path_in) Geom::PathVector real_pathv; Geom::Path real_path; Geom::PathVector pat_vec; - Piecewise > pwd2; + Piecewise> pwd2; Geom::Path throwaway_path; if (!zeroStart) { @@ -276,7 +288,8 @@ Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const& path_in) pat_str << "M 1,0 L 0,0 Q " << 1 - (double)start_smoothing << ",1 1,1"; break; default: - pat_str << "M 1,0 C " << 1 - (double)start_smoothing << ",0 0,0.5 0,0.5 0,0.5 " << 1 - (double)start_smoothing << ",1 1,1"; + pat_str << "M 1,0 C " << 1 - (double)start_smoothing << ",0 0,0.5 0,0.5 0,0.5 " + << 1 - (double)start_smoothing << ",1 1,1"; break; } @@ -286,12 +299,13 @@ Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const& path_in) real_path.append(throwaway_path); } - - // if this condition happens to evaluate false, i.e. there was no space for a path to be drawn, it is simply skipped. - // although this seems obvious, it can probably lead to bugs. + + // if this condition happens to evaluate false, i.e. there was no space for a path to be drawn, it is simply + // skipped. although this seems obvious, it can probably lead to bugs. if (!metInMiddle) { // append the outside outline of the path (goes with the direction of the path) - throwaway_path = half_outline(pathv_out[1], fabs(line_width)/2., miter_limit, static_cast(join_type.get_value())); + throwaway_path = half_outline(pathv_out[1], fabs(line_width) / 2., miter_limit, + static_cast(join_type.get_value())); if (!zeroStart && real_path.size() >= 1 && throwaway_path.size() >= 1) { if (!Geom::are_near(real_path.finalPoint(), throwaway_path.initialPoint())) { real_path.appendNew(throwaway_path.initialPoint()); @@ -315,13 +329,14 @@ Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const& path_in) pat_str_1 << "M 0,1 Q " << (double)end_smoothing << ",1 1,0 L 0,0"; break; default: - pat_str_1 << "M 0,1 C " << (double)end_smoothing << ",1 1,0.5 1,0.5 1,0.5 " << (double)end_smoothing << ",0 0,0"; + pat_str_1 << "M 0,1 C " << (double)end_smoothing << ",1 1,0.5 1,0.5 1,0.5 " << (double)end_smoothing + << ",0 0,0"; break; } pat_vec = sp_svg_read_pathv(pat_str_1.str().c_str()); - pwd2 = Piecewise >(); + pwd2 = Piecewise>(); pwd2.concat(stretch_along(pathv_out[2].toPwSb(), pat_vec[0], fabs(line_width))); throwaway_path = Geom::path_from_piecewise(pwd2, LPE_CONVERSION_TOLERANCE)[0]; @@ -332,11 +347,12 @@ Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const& path_in) } real_path.append(throwaway_path); } - + if (!metInMiddle) { // append the inside outline of the path (against direction) - throwaway_path = half_outline(pathv_out[1].reversed(), fabs(line_width)/2., miter_limit, static_cast(join_type.get_value())); - + throwaway_path = half_outline(pathv_out[1].reversed(), fabs(line_width) / 2., miter_limit, + static_cast(join_type.get_value())); + if (!Geom::are_near(real_path.finalPoint(), throwaway_path.initialPoint()) && real_path.size() >= 1) { real_path.appendNew(throwaway_path.initialPoint()); } else { @@ -344,14 +360,14 @@ Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const& path_in) } real_path.append(throwaway_path); } - + if (!Geom::are_near(real_path.finalPoint(), real_path.initialPoint())) { real_path.appendNew(real_path.initialPoint()); } else { real_path.setFinal(real_path.initialPoint()); } real_path.close(); - + real_pathv.push_back(real_path); return real_pathv; @@ -363,42 +379,41 @@ Geom::PathVector LPETaperStroke::doEffect_path(Geom::PathVector const& path_in) * The positions of the effect knots are accessed to determine * where exactly the input path should be split. */ -Geom::PathVector LPETaperStroke::doEffect_simplePath(Geom::PathVector const & path_in) +Geom::PathVector LPETaperStroke::doEffect_simplePath(Geom::PathVector const &path_in) { Geom::Coord endTime = path_in[0].size() - attach_end; Geom::Path p1 = path_in[0].portion(0., attach_start); Geom::Path p2 = path_in[0].portion(attach_start, endTime); Geom::Path p3 = path_in[0].portion(endTime, path_in[0].size()); - + Geom::PathVector out; out.push_back(p1); out.push_back(p2); out.push_back(p3); - + return out; } - /** * Most of the below function is verbatim from Pattern Along Path. However, it needed a little * tweaking to get it to work right in this case. Also, large portions of the effect have been * stripped out as I deemed them unnecessary for the relative simplicity of this effect. */ -Piecewise > stretch_along(Piecewise > pwd2_in, Geom::Path pattern, double prop_scale) +Piecewise> stretch_along(Piecewise> pwd2_in, Geom::Path pattern, double prop_scale) { using namespace Geom; // Don't allow empty path parameter: - if ( pattern.empty() ) { + if (pattern.empty()) { return pwd2_in; } /* Much credit should go to jfb and mgsloan of lib2geom development for the code below! */ - Piecewise > output; - std::vector > > pre_output; + Piecewise> output; + std::vector>> pre_output; - D2 > patternd2 = make_cuts_independent(pattern.toPwSb()); + D2> patternd2 = make_cuts_independent(pattern.toPwSb()); Piecewise x0 = Piecewise(patternd2[0]); Piecewise y0 = Piecewise(patternd2[1]); OptInterval pattBndsX = bounds_exact(x0); @@ -411,45 +426,46 @@ Piecewise > stretch_along(Piecewise > pwd2_in, Geom::Path double toffset = 0; // Prevent more than 90% overlap... - y0+=noffset; + y0 += noffset; - std::vector > > paths_in; + std::vector>> paths_in; paths_in = split_at_discontinuities(pwd2_in); for (auto path_i : paths_in) { Piecewise x = x0; Piecewise y = y0; - Piecewise > uskeleton = arc_length_parametrization(path_i,2,.1); - uskeleton = remove_short_cuts(uskeleton,.01); - Piecewise > n = rot90(derivative(uskeleton)); - n = force_continuity(remove_short_cuts(n,.1)); + Piecewise> uskeleton = arc_length_parametrization(path_i, 2, .1); + uskeleton = remove_short_cuts(uskeleton, .01); + Piecewise> n = rot90(derivative(uskeleton)); + n = force_continuity(remove_short_cuts(n, .1)); int nbCopies = 0; - double scaling = (uskeleton.domain().extent() - toffset)/pattBndsX->extent(); + double scaling = (uskeleton.domain().extent() - toffset) / pattBndsX->extent(); nbCopies = 1; double pattWidth = pattBndsX->extent() * scaling; if (scaling != 1.0) { - x*=scaling; + x *= scaling; } - if ( false ) { - y*=(scaling*prop_scale); + if (false) { + y *= (scaling * prop_scale); } else { - if (prop_scale != 1.0) y *= prop_scale; + if (prop_scale != 1.0) + y *= prop_scale; } x += toffset; double offs = 0; - for (int i=0; i > output_piece = compose(uskeleton,x+offs)+y*compose(n,x+offs); - std::vector > > splited_output_piece = split_at_discontinuities(output_piece); - pre_output.insert(pre_output.end(), splited_output_piece.begin(), splited_output_piece.end() ); + Piecewise> output_piece = compose(uskeleton, x + offs) + y * compose(n, x + offs); + std::vector>> splited_output_piece = split_at_discontinuities(output_piece); + pre_output.insert(pre_output.end(), splited_output_piece.begin(), splited_output_piece.end()); } else { - output.concat(compose(uskeleton,x+offs)+y*compose(n,x+offs)); + output.concat(compose(uskeleton, x + offs) + y * compose(n, x + offs)); } - offs+=pattWidth; + offs += pattWidth; } } return output; @@ -461,21 +477,27 @@ Piecewise > stretch_along(Piecewise > pwd2_in, Geom::Path void LPETaperStroke::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) { KnotHolderEntity *e = new TpS::KnotHolderEntityAttachBegin(this); - e->create(nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("Start point of the taper: drag to alter the taper, Shift+click changes the taper direction"), SP_KNOT_SHAPE_CIRCLE); + e->create( + nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, + _("Start point of the taper: drag to alter the taper, Shift+click changes the taper direction"), + SP_KNOT_SHAPE_CIRCLE); knotholder->add(e); KnotHolderEntity *f = new TpS::KnotHolderEntityAttachEnd(this); - f->create(nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, _("End point of the taper: drag to alter the taper, Shift+click changes the taper direction"), SP_KNOT_SHAPE_CIRCLE); + f->create( + nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, + _("End point of the taper: drag to alter the taper, Shift+click changes the taper direction"), + SP_KNOT_SHAPE_CIRCLE); knotholder->add(f); } namespace TpS { -void KnotHolderEntityAttachBegin::knot_set(Geom::Point const &p, Geom::Point const&/*origin*/, guint state) +void KnotHolderEntityAttachBegin::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { using namespace Geom; - LPETaperStroke* lpe = dynamic_cast(_effect); + LPETaperStroke *lpe = dynamic_cast(_effect); Geom::Point const s = snap_knot_position(p, state); @@ -483,16 +505,16 @@ void KnotHolderEntityAttachBegin::knot_set(Geom::Point const &p, Geom::Point con printf("WARNING: LPEItem is not a path!\n"); return; } - + if (!SP_SHAPE(lpe->sp_lpe_item)->curve()) { // oops return; } // in case you are wondering, the above are simply sanity checks. we never want to actually // use that object. - + Geom::PathVector pathv = lpe->pathvector_before_effect; - Piecewise > pwd2; + Piecewise> pwd2; Geom::Path p_in = return_at_first_cusp(pathv[0]); pwd2.concat(p_in.toPwSb()); @@ -509,7 +531,7 @@ void KnotHolderEntityAttachBegin::knot_click(guint state) return; } - LPETaperStroke* lpe = dynamic_cast(_effect); + LPETaperStroke *lpe = dynamic_cast(_effect); lpe->start_shape.param_set_value((lpe->start_shape.get_value() + 1) % LAST_SHAPE); lpe->start_shape.write_to_SVG(); @@ -521,48 +543,48 @@ void KnotHolderEntityAttachEnd::knot_click(guint state) return; } - LPETaperStroke* lpe = dynamic_cast(_effect); + LPETaperStroke *lpe = dynamic_cast(_effect); lpe->end_shape.param_set_value((lpe->end_shape.get_value() + 1) % LAST_SHAPE); lpe->end_shape.write_to_SVG(); } -void KnotHolderEntityAttachEnd::knot_set(Geom::Point const &p, Geom::Point const& /*origin*/, guint state) +void KnotHolderEntityAttachEnd::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { using namespace Geom; - LPETaperStroke* lpe = dynamic_cast(_effect); + LPETaperStroke *lpe = dynamic_cast(_effect); Geom::Point const s = snap_knot_position(p, state); - if (!SP_IS_SHAPE(lpe->sp_lpe_item) ) { + if (!SP_IS_SHAPE(lpe->sp_lpe_item)) { printf("WARNING: LPEItem is not a path!\n"); return; } - + if (!SP_SHAPE(lpe->sp_lpe_item)->curve()) { // oops return; } Geom::PathVector pathv = lpe->pathvector_before_effect; Geom::Path p_in = return_at_first_cusp(pathv[0].reversed()); - Piecewise > pwd2 = p_in.toPwSb(); - + Piecewise> pwd2 = p_in.toPwSb(); + double t0 = nearest_time(s, pwd2); lpe->attach_end.param_set_value(t0); - sp_lpe_item_update_patheffect (SP_LPE_ITEM(item), false, true); + sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, true); } Geom::Point KnotHolderEntityAttachBegin::knot_get() const { - LPETaperStroke const * lpe = dynamic_cast (_effect); + LPETaperStroke const *lpe = dynamic_cast(_effect); return lpe->start_attach_point; } Geom::Point KnotHolderEntityAttachEnd::knot_get() const { - LPETaperStroke const * lpe = dynamic_cast (_effect); + LPETaperStroke const *lpe = dynamic_cast(_effect); return lpe->end_attach_point; } diff --git a/src/live_effects/lpe-taperstroke.h b/src/live_effects/lpe-taperstroke.h index 21aa7966605b8b88530c92b27094be504aec12b7..579cd37e6a9c6b83591cc7951745c653a79b0c87 100644 --- a/src/live_effects/lpe-taperstroke.h +++ b/src/live_effects/lpe-taperstroke.h @@ -12,8 +12,8 @@ #ifndef INKSCAPE_LPE_TAPERSTROKE_H #define INKSCAPE_LPE_TAPERSTROKE_H -#include "live_effects/parameter/enum.h" #include "live_effects/effect.h" +#include "live_effects/parameter/enum.h" #include "live_effects/parameter/parameter.h" #include "live_effects/parameter/vector.h" @@ -24,24 +24,26 @@ namespace TpS { // we need a separate namespace to avoid clashes with other LPEs class KnotHolderEntityAttachBegin; class KnotHolderEntityAttachEnd; -} +} // namespace TpS -class LPETaperStroke : public Effect { +class LPETaperStroke : public Effect +{ public: LPETaperStroke(LivePathEffectObject *lpeobject); ~LPETaperStroke() override = default; - void doOnApply(SPLPEItem const* lpeitem) override; - void doOnRemove(SPLPEItem const* lpeitem) override; + void doOnApply(SPLPEItem const *lpeitem) override; + void doOnRemove(SPLPEItem const *lpeitem) override; - Geom::PathVector doEffect_path (Geom::PathVector const& path_in) override; - Geom::PathVector doEffect_simplePath(Geom::PathVector const& path_in); + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; + Geom::PathVector doEffect_simplePath(Geom::PathVector const &path_in); void transform_multiply(Geom::Affine const &postmul, bool set) override; - void addKnotHolderEntities(KnotHolder * knotholder, SPItem * item) override; + void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) override; friend class TpS::KnotHolderEntityAttachBegin; friend class TpS::KnotHolderEntityAttachEnd; + private: ScalarParam line_width; ScalarParam attach_start; @@ -56,12 +58,12 @@ private: Geom::Point start_attach_point; Geom::Point end_attach_point; - LPETaperStroke(const LPETaperStroke&) = delete; - LPETaperStroke& operator=(const LPETaperStroke&) = delete; + LPETaperStroke(const LPETaperStroke &) = delete; + LPETaperStroke &operator=(const LPETaperStroke &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-test-doEffect-stack.cpp b/src/live_effects/lpe-test-doEffect-stack.cpp index 55d707af2e258a8972d72668fb6d7a2120d32848..a6c3174d75cefe8b2e626aa268bff7bb9bc14e78 100644 --- a/src/live_effects/lpe-test-doEffect-stack.cpp +++ b/src/live_effects/lpe-test-doEffect-stack.cpp @@ -13,12 +13,11 @@ namespace Inkscape { namespace LivePathEffect { - -LPEdoEffectStackTest::LPEdoEffectStackTest(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - step(_("Stack step:"), ("How deep we should go into the stack"), "step", &wr, this), - point(_("Point param:"), "tooltip of point parameter", "point_param", &wr, this), - path(_("Path param:"), "tooltip of path parameter", "path_param", &wr, this,"M 0,100 100,0") +LPEdoEffectStackTest::LPEdoEffectStackTest(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , step(_("Stack step:"), ("How deep we should go into the stack"), "step", &wr, this) + , point(_("Point param:"), "tooltip of point parameter", "point_param", &wr, this) + , path(_("Path param:"), "tooltip of path parameter", "path_param", &wr, this, "M 0,100 100,0") { registerParameter(&step); registerParameter(&point); @@ -28,11 +27,9 @@ LPEdoEffectStackTest::LPEdoEffectStackTest(LivePathEffectObject *lpeobject) : point.param_setValue(point); } -LPEdoEffectStackTest::~LPEdoEffectStackTest() -= default; +LPEdoEffectStackTest::~LPEdoEffectStackTest() = default; -void -LPEdoEffectStackTest::doEffect (SPCurve * curve) +void LPEdoEffectStackTest::doEffect(SPCurve *curve) { if (step >= 1) { Effect::doEffect(curve); @@ -42,8 +39,7 @@ LPEdoEffectStackTest::doEffect (SPCurve * curve) } } -Geom::PathVector -LPEdoEffectStackTest::doEffect_path (Geom::PathVector const &path_in) +Geom::PathVector LPEdoEffectStackTest::doEffect_path(Geom::PathVector const &path_in) { if (step >= 2) { return Effect::doEffect_path(path_in); @@ -54,15 +50,14 @@ LPEdoEffectStackTest::doEffect_path (Geom::PathVector const &path_in) } } -Geom::Piecewise > -LPEdoEffectStackTest::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPEdoEffectStackTest::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { - Geom::Piecewise > output = pwd2_in; + Geom::Piecewise> output = pwd2_in; return output; } - } // namespace LivePathEffect } /* namespace Inkscape */ diff --git a/src/live_effects/lpe-test-doEffect-stack.h b/src/live_effects/lpe-test-doEffect-stack.h index 1103e89319385d22b971cb2028f25a147adbcf3a..3a0ec1e3317c2e78e656604a3bb90fa5bcd04062 100644 --- a/src/live_effects/lpe-test-doEffect-stack.h +++ b/src/live_effects/lpe-test-doEffect-stack.h @@ -16,31 +16,33 @@ #include "live_effects/effect.h" #include "live_effects/parameter/parameter.h" -#include "live_effects/parameter/point.h" #include "live_effects/parameter/path.h" +#include "live_effects/parameter/point.h" namespace Inkscape { namespace LivePathEffect { -class LPEdoEffectStackTest : public Effect { +class LPEdoEffectStackTest : public Effect +{ public: LPEdoEffectStackTest(LivePathEffectObject *lpeobject); ~LPEdoEffectStackTest() override; - void doEffect (SPCurve * curve) override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + void doEffect(SPCurve *curve) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; private: ScalarParam step; PointParam point; PathParam path; - LPEdoEffectStackTest(const LPEdoEffectStackTest&) = delete; - LPEdoEffectStackTest& operator=(const LPEdoEffectStackTest&) = delete; + LPEdoEffectStackTest(const LPEdoEffectStackTest &) = delete; + LPEdoEffectStackTest &operator=(const LPEdoEffectStackTest &) = delete; }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpe-text_label.cpp b/src/live_effects/lpe-text_label.cpp index aa50296eae1126895fa2ea21c561b9b7def3eedc..b738c4c9dfe1cde264810ff1d17e24933718c343 100644 --- a/src/live_effects/lpe-text_label.cpp +++ b/src/live_effects/lpe-text_label.cpp @@ -20,18 +20,17 @@ namespace Inkscape { namespace LivePathEffect { -LPETextLabel::LPETextLabel(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - label(_("Label:"), _("Text label attached to the path"), "label", &wr, this, "This is a label") +LPETextLabel::LPETextLabel(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , label(_("Label:"), _("Text label attached to the path"), "label", &wr, this, "This is a label") { registerParameter(&label); } -LPETextLabel::~LPETextLabel() -= default; +LPETextLabel::~LPETextLabel() = default; -Geom::Piecewise > -LPETextLabel::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPETextLabel::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { using namespace Geom; @@ -40,14 +39,14 @@ LPETextLabel::doEffect_pwd2 (Geom::Piecewise > const & pw Point dir(unit_vector(derivative(pwd2_in).valueAt(t))); Point n(-rot90(dir) * 30); - double angle = angle_between(dir, Point(1,0)); + double angle = angle_between(dir, Point(1, 0)); label.setPos(pos + n); label.setAnchor(std::sin(angle), -std::cos(angle)); return pwd2_in; } -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-text_label.h b/src/live_effects/lpe-text_label.h index 61fff9a1c45a37af9fd6d1e466c27ee3a9b00f38..6fba41e11da94b153da3d2c91c835cedc7ca8ff5 100644 --- a/src/live_effects/lpe-text_label.h +++ b/src/live_effects/lpe-text_label.h @@ -21,22 +21,24 @@ namespace Inkscape { namespace LivePathEffect { -class LPETextLabel : public Effect { +class LPETextLabel : public Effect +{ public: LPETextLabel(LivePathEffectObject *lpeobject); ~LPETextLabel() override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; private: TextParam label; - LPETextLabel(const LPETextLabel&) = delete; - LPETextLabel& operator=(const LPETextLabel&) = delete; + LPETextLabel(const LPETextLabel &) = delete; + LPETextLabel &operator=(const LPETextLabel &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-transform_2pts.cpp b/src/live_effects/lpe-transform_2pts.cpp index 4a6da0aba88d4ca3475b4c0f86a03a3f61d1cf84..1a27e3cd6c995819d130572cef8348ee93978c05 100644 --- a/src/live_effects/lpe-transform_2pts.cpp +++ b/src/live_effects/lpe-transform_2pts.cpp @@ -11,11 +11,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "live_effects/lpe-transform_2pts.h" + #include #include "display/curve.h" #include "helper/geom.h" -#include "live_effects/lpe-transform_2pts.h" #include "object/sp-path.h" #include "svg/svg.h" #include "ui/icon-names.h" @@ -24,35 +25,39 @@ // TODO due to internal breakage in glibmm headers, this must be last: #include - namespace Inkscape { namespace LivePathEffect { -LPETransform2Pts::LPETransform2Pts(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - elastic(_("Elastic"), _("Elastic transform mode"), "elastic", &wr, this, false,"", INKSCAPE_ICON("on-outline"), INKSCAPE_ICON("off-outline")), - from_original_width(_("From original width"), _("From original width"), "from_original_width", &wr, this, false,"", INKSCAPE_ICON("on-outline"), INKSCAPE_ICON("off-outline")), - lock_length(_("Lock length"), _("Lock length to current distance"), "lock_length", &wr, this, false,"", INKSCAPE_ICON("on-outline"), INKSCAPE_ICON("off-outline")), - lock_angle(_("Lock angle"), _("Lock angle"), "lock_angle", &wr, this, false,"", INKSCAPE_ICON("on-outline"), INKSCAPE_ICON("off-outline")), - flip_horizontal(_("Flip horizontal"), _("Flip horizontal"), "flip_horizontal", &wr, this, false,"", INKSCAPE_ICON("on-outline"), INKSCAPE_ICON("off-outline")), - flip_vertical(_("Flip vertical"), _("Flip vertical"), "flip_vertical", &wr, this, false,"", INKSCAPE_ICON("on-outline"), INKSCAPE_ICON("off-outline")), - start(_("Start"), _("Start point"), "start", &wr, this, "Start point"), - end(_("End"), _("End point"), "end", &wr, this, "End point"), - stretch(_("Stretch"), _("Stretch the result"), "stretch", &wr, this, 1), - offset(_("Offset"), _("Offset from knots"), "offset", &wr, this, 0), - first_knot(_("First Knot"), _("First Knot"), "first_knot", &wr, this, 1), - last_knot(_("Last Knot"), _("Last Knot"), "last_knot", &wr, this, 1), - helper_size(_("Helper size:"), _("Rotation helper size"), "helper_size", &wr, this, 3), - from_original_width_toggler(false), - point_a(Geom::Point()), - point_b(Geom::Point()), - pathvector(), - append_path(false), - previous_angle(Geom::rad_from_deg(0)), - previous_start(Geom::Point()), - previous_length(-1) +LPETransform2Pts::LPETransform2Pts(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , elastic(_("Elastic"), _("Elastic transform mode"), "elastic", &wr, this, false, "", INKSCAPE_ICON("on-outline"), + INKSCAPE_ICON("off-outline")) + , from_original_width(_("From original width"), _("From original width"), "from_original_width", &wr, this, false, + "", INKSCAPE_ICON("on-outline"), INKSCAPE_ICON("off-outline")) + , lock_length(_("Lock length"), _("Lock length to current distance"), "lock_length", &wr, this, false, "", + INKSCAPE_ICON("on-outline"), INKSCAPE_ICON("off-outline")) + , lock_angle(_("Lock angle"), _("Lock angle"), "lock_angle", &wr, this, false, "", INKSCAPE_ICON("on-outline"), + INKSCAPE_ICON("off-outline")) + , flip_horizontal(_("Flip horizontal"), _("Flip horizontal"), "flip_horizontal", &wr, this, false, "", + INKSCAPE_ICON("on-outline"), INKSCAPE_ICON("off-outline")) + , flip_vertical(_("Flip vertical"), _("Flip vertical"), "flip_vertical", &wr, this, false, "", + INKSCAPE_ICON("on-outline"), INKSCAPE_ICON("off-outline")) + , start(_("Start"), _("Start point"), "start", &wr, this, "Start point") + , end(_("End"), _("End point"), "end", &wr, this, "End point") + , stretch(_("Stretch"), _("Stretch the result"), "stretch", &wr, this, 1) + , offset(_("Offset"), _("Offset from knots"), "offset", &wr, this, 0) + , first_knot(_("First Knot"), _("First Knot"), "first_knot", &wr, this, 1) + , last_knot(_("Last Knot"), _("Last Knot"), "last_knot", &wr, this, 1) + , helper_size(_("Helper size:"), _("Rotation helper size"), "helper_size", &wr, this, 3) + , from_original_width_toggler(false) + , point_a(Geom::Point()) + , point_b(Geom::Point()) + , pathvector() + , append_path(false) + , previous_angle(Geom::rad_from_deg(0)) + , previous_start(Geom::Point()) + , previous_length(-1) { - registerParameter(&first_knot); registerParameter(&last_knot); registerParameter(&helper_size); @@ -83,33 +88,31 @@ LPETransform2Pts::LPETransform2Pts(LivePathEffectObject *lpeobject) : apply_to_clippath_and_mask = true; } -LPETransform2Pts::~LPETransform2Pts() -= default; +LPETransform2Pts::~LPETransform2Pts() = default; -void -LPETransform2Pts::doOnApply(SPLPEItem const* lpeitem) +void LPETransform2Pts::doOnApply(SPLPEItem const *lpeitem) { using namespace Geom; original_bbox(lpeitem, false, true); point_a = Point(boundingbox_X.min(), boundingbox_Y.middle()); point_b = Point(boundingbox_X.max(), boundingbox_Y.middle()); - SPLPEItem * splpeitem = const_cast(lpeitem); + SPLPEItem *splpeitem = const_cast(lpeitem); SPPath *sp_path = dynamic_cast(splpeitem); if (sp_path) { pathvector = sp_path->curveForEdit()->get_pathvector(); } - if(!pathvector.empty()) { + if (!pathvector.empty()) { point_a = pathvector.initialPoint(); point_b = pathvector.finalPoint(); - if(are_near(point_a,point_b)) { + if (are_near(point_a, point_b)) { point_b = pathvector.back().finalCurve().initialPoint(); } size_t nnodes = nodeCount(pathvector); last_knot.param_set_value(nnodes); } - previous_length = Geom::distance(point_a,point_b); - Geom::Ray transformed(point_a,point_b); + previous_length = Geom::distance(point_a, point_b); + Geom::Ray transformed(point_a, point_b); previous_angle = transformed.angle(); start.param_update_default(point_a); start.param_set_default(); @@ -125,81 +128,79 @@ void LPETransform2Pts::transform_multiply(Geom::Affine const &postmul, bool /*se } } -void -LPETransform2Pts::doBeforeEffect (SPLPEItem const* lpeitem) +void LPETransform2Pts::doBeforeEffect(SPLPEItem const *lpeitem) { using namespace Geom; original_bbox(lpeitem, false, true); point_a = Point(boundingbox_X.min(), boundingbox_Y.middle()); point_b = Point(boundingbox_X.max(), boundingbox_Y.middle()); - SPLPEItem * splpeitem = const_cast(lpeitem); + SPLPEItem *splpeitem = const_cast(lpeitem); SPPath *sp_path = dynamic_cast(splpeitem); if (sp_path) { pathvector = sp_path->curveForEdit()->get_pathvector(); } - if(from_original_width_toggler != from_original_width) { + if (from_original_width_toggler != from_original_width) { from_original_width_toggler = from_original_width; reset(); } - if(!pathvector.empty() && !from_original_width) { + if (!pathvector.empty() && !from_original_width) { append_path = false; - point_a = pointAtNodeIndex(pathvector,(size_t)first_knot-1); - point_b = pointAtNodeIndex(pathvector,(size_t)last_knot-1); + point_a = pointAtNodeIndex(pathvector, (size_t)first_knot - 1); + point_b = pointAtNodeIndex(pathvector, (size_t)last_knot - 1); size_t nnodes = nodeCount(pathvector); - first_knot.param_set_range(1, last_knot-1); - last_knot.param_set_range(first_knot+1, nnodes); - if (from_original_width){ + first_knot.param_set_range(1, last_knot - 1); + last_knot.param_set_range(first_knot + 1, nnodes); + if (from_original_width) { from_original_width.param_setValue(false); } } else { - if (first_knot != 1){ + if (first_knot != 1) { first_knot.param_set_value(1); } - if (last_knot != 2){ + if (last_knot != 2) { last_knot.param_set_value(2); } - first_knot.param_set_range(1,1); - last_knot.param_set_range(2,2); + first_knot.param_set_range(1, 1); + last_knot.param_set_range(2, 2); append_path = false; - if (!from_original_width){ + if (!from_original_width) { from_original_width.param_setValue(true); } } - if(lock_length && !lock_angle && previous_length != -1) { - Geom::Ray transformed((Geom::Point)start,(Geom::Point)end); - if(previous_start == start || previous_angle == Geom::rad_from_deg(0)) { + if (lock_length && !lock_angle && previous_length != -1) { + Geom::Ray transformed((Geom::Point)start, (Geom::Point)end); + if (previous_start == start || previous_angle == Geom::rad_from_deg(0)) { previous_angle = transformed.angle(); } - } else if(lock_angle && !lock_length && previous_angle != Geom::rad_from_deg(0)) { - if(previous_start == start){ + } else if (lock_angle && !lock_length && previous_angle != Geom::rad_from_deg(0)) { + if (previous_start == start) { previous_length = Geom::distance((Geom::Point)start, (Geom::Point)end); } } - if(lock_length || lock_angle ) { + if (lock_length || lock_angle) { Geom::Point end_point = Geom::Point::polar(previous_angle, previous_length) + (Geom::Point)start; end.param_setValue(end_point); } - Geom::Ray transformed((Geom::Point)start,(Geom::Point)end); + Geom::Ray transformed((Geom::Point)start, (Geom::Point)end); previous_angle = transformed.angle(); previous_length = Geom::distance((Geom::Point)start, (Geom::Point)end); previous_start = start; } -void -LPETransform2Pts::updateIndex() +void LPETransform2Pts::updateIndex() { - SPLPEItem * splpeitem = const_cast(sp_lpe_item); + SPLPEItem *splpeitem = const_cast(sp_lpe_item); SPPath *sp_path = dynamic_cast(splpeitem); if (sp_path) { pathvector = sp_path->curveForEdit()->get_pathvector(); } - if(pathvector.empty()) { + if (pathvector.empty()) { return; } - if(!from_original_width) { - point_a = pointAtNodeIndex(pathvector,(size_t)first_knot-1); - point_b = pointAtNodeIndex(pathvector,(size_t)last_knot-1); + if (!from_original_width) { + point_a = pointAtNodeIndex(pathvector, (size_t)first_knot - 1); + point_b = pointAtNodeIndex(pathvector, (size_t)last_knot - 1); start.param_update_default(point_a); start.param_set_default(); end.param_update_default(point_b); @@ -211,24 +212,22 @@ LPETransform2Pts::updateIndex() } DocumentUndo::done(getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change index of knot")); } -//todo migrate to PathVector class? -size_t -LPETransform2Pts::nodeCount(Geom::PathVector pathvector) const +// todo migrate to PathVector class? +size_t LPETransform2Pts::nodeCount(Geom::PathVector pathvector) const { size_t n = 0; - for (auto & it : pathvector) { + for (auto &it : pathvector) { n += count_path_nodes(it); } return n; } -//todo migrate to PathVector class? -Geom::Point -LPETransform2Pts::pointAtNodeIndex(Geom::PathVector pathvector, size_t index) const +// todo migrate to PathVector class? +Geom::Point LPETransform2Pts::pointAtNodeIndex(Geom::PathVector pathvector, size_t index) const { size_t n = 0; - for (auto & pv_it : pathvector) { + for (auto &pv_it : pathvector) { for (Geom::Path::iterator curve_it = pv_it.begin(); curve_it != pv_it.end_closed(); ++curve_it) { - if(index == n) { + if (index == n) { return curve_it->initialPoint(); } n++; @@ -236,14 +235,13 @@ LPETransform2Pts::pointAtNodeIndex(Geom::PathVector pathvector, size_t index) co } return Geom::Point(); } -//todo migrate to PathVector class? Not used -Geom::Path -LPETransform2Pts::pathAtNodeIndex(Geom::PathVector pathvector, size_t index) const +// todo migrate to PathVector class? Not used +Geom::Path LPETransform2Pts::pathAtNodeIndex(Geom::PathVector pathvector, size_t index) const { size_t n = 0; - for (auto & pv_it : pathvector) { + for (auto &pv_it : pathvector) { for (Geom::Path::iterator curve_it = pv_it.begin(); curve_it != pv_it.end_closed(); ++curve_it) { - if(index == n) { + if (index == n) { return pv_it; } n++; @@ -252,16 +250,14 @@ LPETransform2Pts::pathAtNodeIndex(Geom::PathVector pathvector, size_t index) con return Geom::Path(); } - -void -LPETransform2Pts::reset() +void LPETransform2Pts::reset() { point_a = Geom::Point(boundingbox_X.min(), boundingbox_Y.middle()); point_b = Geom::Point(boundingbox_X.max(), boundingbox_Y.middle()); - if(!pathvector.empty() && !from_original_width) { + if (!pathvector.empty() && !from_original_width) { size_t nnodes = nodeCount(pathvector); - first_knot.param_set_range(1, last_knot-1); - last_knot.param_set_range(first_knot+1, nnodes); + first_knot.param_set_range(1, last_knot - 1); + last_knot.param_set_range(first_knot + 1, nnodes); first_knot.param_set_value(1); last_knot.param_set_value(nnodes); point_a = pathvector.initialPoint(); @@ -292,17 +288,18 @@ Gtk::Widget *LPETransform2Pts::newWidget() vbox->set_spacing(6); std::vector::iterator it = param_vector.begin(); - Gtk::HBox * button1 = Gtk::manage(new Gtk::HBox(true,0)); - Gtk::HBox * button2 = Gtk::manage(new Gtk::HBox(true,0)); - Gtk::HBox * button3 = Gtk::manage(new Gtk::HBox(true,0)); - Gtk::HBox * button4 = Gtk::manage(new Gtk::HBox(true,0)); + Gtk::HBox *button1 = Gtk::manage(new Gtk::HBox(true, 0)); + Gtk::HBox *button2 = Gtk::manage(new Gtk::HBox(true, 0)); + Gtk::HBox *button3 = Gtk::manage(new Gtk::HBox(true, 0)); + Gtk::HBox *button4 = Gtk::manage(new Gtk::HBox(true, 0)); while (it != param_vector.end()) { if ((*it)->widget_is_visible) { Parameter *param = *it; Gtk::Widget *widg = dynamic_cast(param->param_newWidget()); Glib::ustring *tip = param->param_getTooltip(); if (param->param_key == "first_knot" || param->param_key == "last_knot") { - Inkscape::UI::Widget::Scalar *registered_widget = Gtk::manage(dynamic_cast(widg)); + Inkscape::UI::Widget::Scalar *registered_widget = + Gtk::manage(dynamic_cast(widg)); registered_widget->signal_value_changed().connect(sigc::mem_fun(*this, &LPETransform2Pts::updateIndex)); widg = registered_widget; if (widg) { @@ -319,7 +316,7 @@ Gtk::Widget *LPETransform2Pts::newWidget() } } } else if (param->param_key == "from_original_width" || param->param_key == "elastic") { - Glib::ustring * tip = param->param_getTooltip(); + Glib::ustring *tip = param->param_getTooltip(); if (widg) { button1->pack_start(*widg, true, true, 2); if (tip) { @@ -330,7 +327,7 @@ Gtk::Widget *LPETransform2Pts::newWidget() } } } else if (param->param_key == "flip_horizontal" || param->param_key == "flip_vertical") { - Glib::ustring * tip = param->param_getTooltip(); + Glib::ustring *tip = param->param_getTooltip(); if (widg) { button2->pack_start(*widg, true, true, 2); if (tip) { @@ -341,7 +338,7 @@ Gtk::Widget *LPETransform2Pts::newWidget() } } } else if (param->param_key == "lock_angle" || param->param_key == "lock_length") { - Glib::ustring * tip = param->param_getTooltip(); + Glib::ustring *tip = param->param_getTooltip(); if (widg) { button3->pack_start(*widg, true, true, 2); if (tip) { @@ -371,49 +368,49 @@ Gtk::Widget *LPETransform2Pts::newWidget() vbox->pack_start(*button2, true, true, 2); vbox->pack_start(*button3, true, true, 2); vbox->pack_start(*button4, true, true, 2); - if(Gtk::Widget* widg = defaultParamSet()) { + if (Gtk::Widget *widg = defaultParamSet()) { vbox->pack_start(*widg, true, true, 2); } return dynamic_cast(vbox); } -Geom::Piecewise > -LPETransform2Pts::doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) +Geom::Piecewise> +LPETransform2Pts::doEffect_pwd2(Geom::Piecewise> const &pwd2_in) { - Geom::Piecewise > output; - double sca = Geom::distance((Geom::Point)start,(Geom::Point)end)/Geom::distance(point_a,point_b); - Geom::Ray original(point_a,point_b); - Geom::Ray transformed((Geom::Point)start,(Geom::Point)end); + Geom::Piecewise> output; + double sca = Geom::distance((Geom::Point)start, (Geom::Point)end) / Geom::distance(point_a, point_b); + Geom::Ray original(point_a, point_b); + Geom::Ray transformed((Geom::Point)start, (Geom::Point)end); double rot = transformed.angle() - original.angle(); Geom::Path helper; helper.start(point_a); helper.appendNew(point_b); Geom::Affine m; Geom::Angle original_angle = original.angle(); - if(flip_horizontal && flip_vertical){ + if (flip_horizontal && flip_vertical) { m *= Geom::Rotate(-original_angle); - m *= Geom::Scale(-1,-1); + m *= Geom::Scale(-1, -1); m *= Geom::Rotate(original_angle); - } else if(flip_vertical){ + } else if (flip_vertical) { m *= Geom::Rotate(-original_angle); - m *= Geom::Scale(1,-1); + m *= Geom::Scale(1, -1); m *= Geom::Rotate(original_angle); - } else if(flip_horizontal){ + } else if (flip_horizontal) { m *= Geom::Rotate(-original_angle); - m *= Geom::Scale(-1,1); + m *= Geom::Scale(-1, 1); m *= Geom::Rotate(original_angle); } - if(stretch != 1){ + if (stretch != 1) { m *= Geom::Rotate(-original_angle); - m *= Geom::Scale(1,stretch); + m *= Geom::Scale(1, stretch); m *= Geom::Rotate(original_angle); } - if(elastic) { + if (elastic) { m *= Geom::Rotate(-original_angle); - if(sca > 1){ + if (sca > 1) { m *= Geom::Scale(sca, 1.0); } else { - m *= Geom::Scale(sca, 1.0-((1.0-sca)/2.0)); + m *= Geom::Scale(sca, 1.0 - ((1.0 - sca) / 2.0)); } m *= Geom::Rotate(transformed.angle()); } else { @@ -422,11 +419,11 @@ LPETransform2Pts::doEffect_pwd2 (Geom::Piecewise > const } helper *= m; Geom::Point trans = (Geom::Point)start - helper.initialPoint(); - if(flip_horizontal){ + if (flip_horizontal) { trans = (Geom::Point)end - helper.initialPoint(); } - if(offset != 0){ - trans = Geom::Point::polar(transformed.angle() + Geom::rad_from_deg(-90),offset) + trans; + if (offset != 0) { + trans = Geom::Point::polar(transformed.angle() + Geom::rad_from_deg(-90), offset) + trans; } m *= Geom::Translate(trans); @@ -435,8 +432,7 @@ LPETransform2Pts::doEffect_pwd2 (Geom::Piecewise > const return output; } -void -LPETransform2Pts::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) +void LPETransform2Pts::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { using namespace Geom; hp_vec.clear(); @@ -445,29 +441,31 @@ LPETransform2Pts::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector< hp.appendNew((Geom::Point)end); Geom::PathVector pathv; pathv.push_back(hp); - double r = helper_size*.1; - if(lock_length || lock_angle ) { - char const * svgd; - svgd = "M -5.39,8.78 -9.13,5.29 -10.38,10.28 Z M -7.22,7.07 -3.43,3.37 m -1.95,-12.16 -3.74,3.5 -1.26,-5 z m -1.83,1.71 3.78,3.7 M 5.24,8.78 8.98,5.29 10.24,10.28 Z M 7.07,7.07 3.29,3.37 M 5.24,-8.78 l 3.74,3.5 1.26,-5 z M 7.07,-7.07 3.29,-3.37"; + double r = helper_size * .1; + if (lock_length || lock_angle) { + char const *svgd; + svgd = "M -5.39,8.78 -9.13,5.29 -10.38,10.28 Z M -7.22,7.07 -3.43,3.37 m -1.95,-12.16 -3.74,3.5 -1.26,-5 z m " + "-1.83,1.71 3.78,3.7 M 5.24,8.78 8.98,5.29 10.24,10.28 Z M 7.07,7.07 3.29,3.37 M 5.24,-8.78 l 3.74,3.5 " + "1.26,-5 z M 7.07,-7.07 3.29,-3.37"; PathVector pathv_move = sp_svg_read_pathv(svgd); - pathv_move *= Affine(r,0,0,r,0,0) * Translate(Geom::Point(start)); + pathv_move *= Affine(r, 0, 0, r, 0, 0) * Translate(Geom::Point(start)); hp_vec.push_back(pathv_move); } - if(!lock_angle && lock_length) { - char const * svgd; - svgd = "M 0,9.94 C -2.56,9.91 -5.17,8.98 -7.07,7.07 c -3.91,-3.9 -3.91,-10.24 0,-14.14 1.97,-1.97 4.51,-3.02 7.07,-3.04 2.56,0.02 5.1,1.07 7.07,3.04 3.91,3.9 3.91,10.24 0,14.14 C 5.17,8.98 2.56,9.91 0,9.94 Z"; + if (!lock_angle && lock_length) { + char const *svgd; + svgd = "M 0,9.94 C -2.56,9.91 -5.17,8.98 -7.07,7.07 c -3.91,-3.9 -3.91,-10.24 0,-14.14 1.97,-1.97 4.51,-3.02 " + "7.07,-3.04 2.56,0.02 5.1,1.07 7.07,3.04 3.91,3.9 3.91,10.24 0,14.14 C 5.17,8.98 2.56,9.91 0,9.94 Z"; PathVector pathv_turn = sp_svg_read_pathv(svgd); pathv_turn *= Geom::Rotate(previous_angle); - pathv_turn *= Affine(r,0,0,r,0,0) * Translate(Geom::Point(end)); + pathv_turn *= Affine(r, 0, 0, r, 0, 0) * Translate(Geom::Point(end)); hp_vec.push_back(pathv_turn); } hp_vec.push_back(pathv); } - /* ######################## */ -} //namespace LivePathEffect +} // namespace LivePathEffect } /* namespace Inkscape */ /* diff --git a/src/live_effects/lpe-transform_2pts.h b/src/live_effects/lpe-transform_2pts.h index d72e69a6c38a328e95cf9265378b327fadab147a..25f6b3f5e615328bacb86a770cd674adc3bef3cd 100644 --- a/src/live_effects/lpe-transform_2pts.h +++ b/src/live_effects/lpe-transform_2pts.h @@ -17,22 +17,26 @@ #include "live_effects/effect.h" #include "live_effects/lpegroupbbox.h" #include "live_effects/parameter/parameter.h" -#include "live_effects/parameter/togglebutton.h" #include "live_effects/parameter/point.h" +#include "live_effects/parameter/togglebutton.h" namespace Inkscape { namespace LivePathEffect { -class LPETransform2Pts : public Effect, GroupBBoxEffect { +class LPETransform2Pts + : public Effect + , GroupBBoxEffect +{ public: LPETransform2Pts(LivePathEffectObject *lpeobject); ~LPETransform2Pts() override; - void doOnApply (SPLPEItem const* lpeitem) override; + void doOnApply(SPLPEItem const *lpeitem) override; - Geom::Piecewise > doEffect_pwd2 (Geom::Piecewise > const & pwd2_in) override; + Geom::Piecewise> + doEffect_pwd2(Geom::Piecewise> const &pwd2_in) override; - void doBeforeEffect (SPLPEItem const* lpeitem) override; + void doBeforeEffect(SPLPEItem const *lpeitem) override; void transform_multiply(Geom::Affine const &postmul, bool set) override; @@ -73,12 +77,12 @@ private: Geom::Angle previous_angle; Geom::Point previous_start; double previous_length; - LPETransform2Pts(const LPETransform2Pts&) = delete; - LPETransform2Pts& operator=(const LPETransform2Pts&) = delete; + LPETransform2Pts(const LPETransform2Pts &) = delete; + LPETransform2Pts &operator=(const LPETransform2Pts &) = delete; }; -} //namespace LivePathEffect -} //namespace Inkscape +} // namespace LivePathEffect +} // namespace Inkscape #endif diff --git a/src/live_effects/lpe-vonkoch.cpp b/src/live_effects/lpe-vonkoch.cpp index 8936bd83aff5966af7c92053949c1226ba9de2d0..a6bb801372bd51cc8be038d156d1cd95d863ee39 100644 --- a/src/live_effects/lpe-vonkoch.cpp +++ b/src/live_effects/lpe-vonkoch.cpp @@ -5,64 +5,70 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "live_effects/lpe-vonkoch.h" + +#include // TODO due to internal breakage in glibmm headers, this must be last: #include namespace Inkscape { namespace LivePathEffect { -void -VonKochPathParam::param_setup_nodepath(Inkscape::NodePath::Path *np) -{ +void VonKochPathParam::param_setup_nodepath(Inkscape::NodePath::Path *np) +{ PathParam::param_setup_nodepath(np); - //sp_nodepath_make_straight_path(np); + // sp_nodepath_make_straight_path(np); } -//FIXME: a path is used here instead of 2 points to work around path/point param incompatibility bug. -void -VonKochRefPathParam::param_setup_nodepath(Inkscape::NodePath::Path *np) -{ +// FIXME: a path is used here instead of 2 points to work around path/point param incompatibility bug. +void VonKochRefPathParam::param_setup_nodepath(Inkscape::NodePath::Path *np) +{ PathParam::param_setup_nodepath(np); - //sp_nodepath_make_straight_path(np); + // sp_nodepath_make_straight_path(np); } -bool -VonKochRefPathParam::param_readSVGValue(const gchar * strvalue) -{ +bool VonKochRefPathParam::param_readSVGValue(const gchar *strvalue) +{ Geom::PathVector old = _pathvector; bool res = PathParam::param_readSVGValue(strvalue); - if (res && _pathvector.size()==1 && _pathvector.front().size()==1){ + if (res && _pathvector.size() == 1 && _pathvector.front().size() == 1) { return true; - }else{ + } else { _pathvector = old; return false; } } -LPEVonKoch::LPEVonKoch(LivePathEffectObject *lpeobject) : - Effect(lpeobject), - nbgenerations(_("N_r of generations:"), _("Depth of the recursion --- keep low!!"), "nbgenerations", &wr, this, 1), - generator(_("Generating path:"), _("Path whose segments define the iterated transforms"), "generator", &wr, this, "M0,0 L30,0 M0,10 L10,10 M 20,10 L30,10"), - similar_only(_("_Use uniform transforms only"), _("2 consecutive segments are used to reverse/preserve orientation only (otherwise, they define a general transform)."), "similar_only", &wr, this, false), - drawall(_("Dra_w all generations"), _("If unchecked, draw only the last generation"), "drawall", &wr, this, true), +LPEVonKoch::LPEVonKoch(LivePathEffectObject *lpeobject) + : Effect(lpeobject) + , nbgenerations(_("N_r of generations:"), _("Depth of the recursion --- keep low!!"), "nbgenerations", &wr, this, 1) + , generator(_("Generating path:"), _("Path whose segments define the iterated transforms"), "generator", &wr, this, + "M0,0 L30,0 M0,10 L10,10 M 20,10 L30,10") + , similar_only(_("_Use uniform transforms only"), + _("2 consecutive segments are used to reverse/preserve orientation only (otherwise, they define a " + "general transform)."), + "similar_only", &wr, this, false) + , drawall(_("Dra_w all generations"), _("If unchecked, draw only the last generation"), "drawall", &wr, this, true) + , //,draw_boxes(_("Display boxes"), _("Display boxes instead of paths only"), "draw_boxes", &wr, this, true) - ref_path(_("Reference segment:"), _("The reference segment. Defaults to the horizontal midline of the bbox."), "ref_path", &wr, this, "M0,0 L10,0"), - //refA(_("Ref Start"), _("Left side middle of the reference box"), "refA", &wr, this), - //refB(_("Ref End"), _("Right side middle of the reference box"), "refB", &wr, this), - //FIXME: a path is used here instead of 2 points to work around path/point param incompatibility bug. - maxComplexity(_("_Max complexity:"), _("Disable effect if the output is too complex"), "maxComplexity", &wr, this, 1000) + ref_path(_("Reference segment:"), _("The reference segment. Defaults to the horizontal midline of the bbox."), + "ref_path", &wr, this, "M0,0 L10,0") + , + // refA(_("Ref Start"), _("Left side middle of the reference box"), "refA", &wr, this), + // refB(_("Ref End"), _("Right side middle of the reference box"), "refB", &wr, this), + // FIXME: a path is used here instead of 2 points to work around path/point param incompatibility bug. + maxComplexity(_("_Max complexity:"), _("Disable effect if the output is too complex"), "maxComplexity", &wr, this, + 1000) { - //FIXME: a path is used here instead of 2 points to work around path/point param incompatibility bug. + // FIXME: a path is used here instead of 2 points to work around path/point param incompatibility bug. registerParameter(&ref_path); - //registerParameter(&refA) ); - //registerParameter(&refB) ); + // registerParameter(&refA) ); + // registerParameter(&refB) ); registerParameter(&generator); registerParameter(&similar_only); registerParameter(&nbgenerations); registerParameter(&drawall); registerParameter(&maxComplexity); - //registerParameter(&draw_boxes) ); + // registerParameter(&draw_boxes) ); apply_to_clippath_and_mask = true; nbgenerations.param_make_integer(); nbgenerations.param_set_range(0, Geom::infinity()); @@ -70,96 +76,94 @@ LPEVonKoch::LPEVonKoch(LivePathEffectObject *lpeobject) : maxComplexity.param_set_range(0, Geom::infinity()); } -LPEVonKoch::~LPEVonKoch() -= default; +LPEVonKoch::~LPEVonKoch() = default; -Geom::PathVector -LPEVonKoch::doEffect_path (Geom::PathVector const & path_in) +Geom::PathVector LPEVonKoch::doEffect_path(Geom::PathVector const &path_in) { using namespace Geom; Geom::PathVector generating_path = generator.get_pathvector(); - + if (generating_path.empty()) { return path_in; } - //Collect transform matrices. + // Collect transform matrices. Affine m0; Geom::Path refpath = ref_path.get_pathvector().front(); Point A = refpath.pointAt(0); Point B = refpath.pointAt(refpath.size()); - Point u = B-A; - m0 = Affine(u[X], u[Y],-u[Y], u[X], A[X], A[Y]); - - //FIXME: a path is used as ref instead of 2 points to work around path/point param incompatibility bug. - //Point u = refB-refA; - //m0 = Affine(u[X], u[Y],-u[Y], u[X], refA[X], refA[Y]); + Point u = B - A; + m0 = Affine(u[X], u[Y], -u[Y], u[X], A[X], A[Y]); + + // FIXME: a path is used as ref instead of 2 points to work around path/point param incompatibility bug. + // Point u = refB-refA; + // m0 = Affine(u[X], u[Y],-u[Y], u[X], refA[X], refA[Y]); m0 = m0.inverse(); std::vector transforms; - for (const auto & i : generating_path){ + for (const auto &i : generating_path) { Affine m; - if(i.size()==1){ + if (i.size() == 1) { Point p = i.pointAt(0); - Point u = i.pointAt(1)-p; - m = Affine(u[X], u[Y],-u[Y], u[X], p[X], p[Y]); - m = m0*m; + Point u = i.pointAt(1) - p; + m = Affine(u[X], u[Y], -u[Y], u[X], p[X], p[Y]); + m = m0 * m; transforms.push_back(m); - }else if(i.size()>=2){ + } else if (i.size() >= 2) { Point p = i.pointAt(1); - Point u = i.pointAt(2)-p; - Point v = p-i.pointAt(0); - if (similar_only.get_value()){ - int sign = (u[X]*v[Y]-u[Y]*v[X]>=0?1:-1); - v[X] = -u[Y]*sign; - v[Y] = u[X]*sign; + Point u = i.pointAt(2) - p; + Point v = p - i.pointAt(0); + if (similar_only.get_value()) { + int sign = (u[X] * v[Y] - u[Y] * v[X] >= 0 ? 1 : -1); + v[X] = -u[Y] * sign; + v[Y] = u[X] * sign; } - m = Affine(u[X], u[Y],v[X], v[Y], p[X], p[Y]); - m = m0*m; + m = Affine(u[X], u[Y], v[X], v[Y], p[X], p[Y]); + m = m0 * m; transforms.push_back(m); } } - if (transforms.empty()){ + if (transforms.empty()) { return path_in; } - //Do nothing if the output is too complex... + // Do nothing if the output is too complex... int path_in_complexity = 0; - for (const auto & k : path_in){ - path_in_complexity+=k.size(); + for (const auto &k : path_in) { + path_in_complexity += k.size(); } double complexity = std::pow(transforms.size(), nbgenerations) * path_in_complexity; - if (drawall.get_value()){ + if (drawall.get_value()) { int k = transforms.size(); - if(k>1){ - complexity = (std::pow(k,nbgenerations+1)-1)/(k-1)*path_in_complexity; - }else{ - complexity = nbgenerations*k*path_in_complexity; + if (k > 1) { + complexity = (std::pow(k, nbgenerations + 1) - 1) / (k - 1) * path_in_complexity; + } else { + complexity = nbgenerations * k * path_in_complexity; } } - if (complexity > double(maxComplexity)){ + if (complexity > double(maxComplexity)) { g_warning("VonKoch lpe's output too complex. Effect bypassed."); return path_in; } - //Generate path: + // Generate path: Geom::PathVector pathi = path_in; Geom::PathVector path_out = path_in; - - for (unsigned i = 0; i &hp_vec) +// Useful?? +// void +// LPEVonKoch::addCanvasIndicators(SPLPEItem const */*lpeitem*/, std::vector &hp_vec) /*{ using namespace Geom; if (draw_boxes.get_value()){ double ratio = .5; if (similar_only.get_value()) ratio = boundingbox_Y.extent()/boundingbox_X.extent()/2; - + Point BB1,BB2,BB3,BB4,v; - + //Draw the reference box (ref_path is supposed to consist in one line segment) //FIXME: a path is used as ref instead of 2 points to work around path/point param incompatibility bug. Geom::Path refpath = ref_path.get_pathvector().front(); @@ -234,71 +237,68 @@ LPEVonKoch::doEffect_path (Geom::PathVector const & path_in) } */ -void -LPEVonKoch::doBeforeEffect (SPLPEItem const* lpeitem) +void LPEVonKoch::doBeforeEffect(SPLPEItem const *lpeitem) { using namespace Geom; original_bbox(lpeitem, false, true); - + Geom::PathVector paths = ref_path.get_pathvector(); - Geom::Point A,B; - if (paths.empty()||paths.front().size()==0){ - //FIXME: a path is used as ref instead of 2 points to work around path/point param incompatibility bug. - //refA.param_setValue( Geom::Point(boundingbox_X.min(), boundingbox_Y.middle()) ); - //refB.param_setValue( Geom::Point(boundingbox_X.max(), boundingbox_Y.middle()) ); + Geom::Point A, B; + if (paths.empty() || paths.front().size() == 0) { + // FIXME: a path is used as ref instead of 2 points to work around path/point param incompatibility bug. + // refA.param_setValue( Geom::Point(boundingbox_X.min(), boundingbox_Y.middle()) ); + // refB.param_setValue( Geom::Point(boundingbox_X.max(), boundingbox_Y.middle()) ); A = Point(boundingbox_X.min(), boundingbox_Y.middle()); B = Point(boundingbox_X.max(), boundingbox_Y.middle()); - }else{ + } else { A = paths.front().pointAt(0); B = paths.front().pointAt(paths.front().size()); } - if (paths.size()!=1||paths.front().size()!=1){ + if (paths.size() != 1 || paths.front().size() != 1) { Geom::Path tmp_path(A); tmp_path.appendNew(B); Geom::PathVector tmp_pathv; tmp_pathv.push_back(tmp_path); - ref_path.set_new_value(tmp_pathv,true); + ref_path.set_new_value(tmp_pathv, true); } } - -void -LPEVonKoch::resetDefaults(SPItem const* item) +void LPEVonKoch::resetDefaults(SPItem const *item) { Effect::resetDefaults(item); using namespace Geom; original_bbox(SP_LPE_ITEM(item), false, true); - Point A,B; + Point A, B; A[Geom::X] = boundingbox_X.min(); A[Geom::Y] = boundingbox_Y.middle(); B[Geom::X] = boundingbox_X.max(); B[Geom::Y] = boundingbox_Y.middle(); - Geom::PathVector paths,refpaths; + Geom::PathVector paths, refpaths; Geom::Path path = Geom::Path(A); path.appendNew(B); refpaths.push_back(path); ref_path.set_new_value(refpaths, true); - paths.push_back(path * Affine(1./3,0,0,1./3, A[X]*2./3, A[Y]*2./3 + boundingbox_Y.extent()/2)); - paths.push_back(path * Affine(1./3,0,0,1./3, B[X]*2./3, B[Y]*2./3 + boundingbox_Y.extent()/2)); + paths.push_back(path * Affine(1. / 3, 0, 0, 1. / 3, A[X] * 2. / 3, A[Y] * 2. / 3 + boundingbox_Y.extent() / 2)); + paths.push_back(path * Affine(1. / 3, 0, 0, 1. / 3, B[X] * 2. / 3, B[Y] * 2. / 3 + boundingbox_Y.extent() / 2)); generator.set_new_value(paths, true); - //FIXME: a path is used as ref instead of 2 points to work around path/point param incompatibility bug. - //refA[Geom::X] = boundingbox_X.min(); - //refA[Geom::Y] = boundingbox_Y.middle(); - //refB[Geom::X] = boundingbox_X.max(); - //refB[Geom::Y] = boundingbox_Y.middle(); - //Geom::PathVector paths; - //Geom::Path path = Geom::Path( (Point) refA); - //path.appendNew( (Point) refB ); - //paths.push_back(path * Affine(1./3,0,0,1./3, refA[X]*2./3, refA[Y]*2./3 + boundingbox_Y.extent()/2)); - //paths.push_back(path * Affine(1./3,0,0,1./3, refB[X]*2./3, refB[Y]*2./3 + boundingbox_Y.extent()/2)); - //paths.push_back(path); - //generator.set_new_value(paths, true); + // FIXME: a path is used as ref instead of 2 points to work around path/point param incompatibility bug. + // refA[Geom::X] = boundingbox_X.min(); + // refA[Geom::Y] = boundingbox_Y.middle(); + // refB[Geom::X] = boundingbox_X.max(); + // refB[Geom::Y] = boundingbox_Y.middle(); + // Geom::PathVector paths; + // Geom::Path path = Geom::Path( (Point) refA); + // path.appendNew( (Point) refB ); + // paths.push_back(path * Affine(1./3,0,0,1./3, refA[X]*2./3, refA[Y]*2./3 + boundingbox_Y.extent()/2)); + // paths.push_back(path * Affine(1./3,0,0,1./3, refB[X]*2./3, refB[Y]*2./3 + boundingbox_Y.extent()/2)); + // paths.push_back(path); + // generator.set_new_value(paths, true); } } // namespace LivePathEffect diff --git a/src/live_effects/lpe-vonkoch.h b/src/live_effects/lpe-vonkoch.h index 724425395115f9de699970ef7d25410bc37c007f..ffe2949bbf81acb773c5eab9d1091c48206aef8b 100644 --- a/src/live_effects/lpe-vonkoch.h +++ b/src/live_effects/lpe-vonkoch.h @@ -12,71 +12,72 @@ #include "live_effects/effect.h" #include "live_effects/lpegroupbbox.h" +#include "live_effects/parameter/bool.h" #include "live_effects/parameter/path.h" #include "live_effects/parameter/point.h" -#include "live_effects/parameter/bool.h" namespace Inkscape { namespace LivePathEffect { -class VonKochPathParam : public PathParam{ +class VonKochPathParam : public PathParam +{ public: - VonKochPathParam ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - const gchar * default_value = "M0,0 L1,1"):PathParam(label,tip,key,wr,effect,default_value){} - ~VonKochPathParam() override= default; - void param_setup_nodepath(Inkscape::NodePath::Path *np) override; - }; + VonKochPathParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const gchar *default_value = "M0,0 L1,1") + : PathParam(label, tip, key, wr, effect, default_value) + {} + ~VonKochPathParam() override = default; + void param_setup_nodepath(Inkscape::NodePath::Path *np) override; +}; - //FIXME: a path is used here instead of 2 points to work around path/point param incompatibility bug. -class VonKochRefPathParam : public PathParam{ +// FIXME: a path is used here instead of 2 points to work around path/point param incompatibility bug. +class VonKochRefPathParam : public PathParam +{ public: - VonKochRefPathParam ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - const gchar * default_value = "M0,0 L1,1"):PathParam(label,tip,key,wr,effect,default_value){} - ~VonKochRefPathParam() override= default; - void param_setup_nodepath(Inkscape::NodePath::Path *np) override; - bool param_readSVGValue(const gchar * strvalue) override; - }; - -class LPEVonKoch : public Effect, GroupBBoxEffect { + VonKochRefPathParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const gchar *default_value = "M0,0 L1,1") + : PathParam(label, tip, key, wr, effect, default_value) + {} + ~VonKochRefPathParam() override = default; + void param_setup_nodepath(Inkscape::NodePath::Path *np) override; + bool param_readSVGValue(const gchar *strvalue) override; +}; + +class LPEVonKoch + : public Effect + , GroupBBoxEffect +{ public: LPEVonKoch(LivePathEffectObject *lpeobject); ~LPEVonKoch() override; - Geom::PathVector doEffect_path (Geom::PathVector const & path_in) override; + Geom::PathVector doEffect_path(Geom::PathVector const &path_in) override; - void resetDefaults(SPItem const* item) override; + void resetDefaults(SPItem const *item) override; - void doBeforeEffect(SPLPEItem const* item) override; + void doBeforeEffect(SPLPEItem const *item) override; - //Useful?? - // protected: - //virtual void addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec); + // Useful?? + // protected: + // virtual void addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec); private: - ScalarParam nbgenerations; - VonKochPathParam generator; - BoolParam similar_only; - BoolParam drawall; - //BoolParam draw_boxes; - //FIXME: a path is used here instead of 2 points to work around path/point param incompatibility bug. - VonKochRefPathParam ref_path; + ScalarParam nbgenerations; + VonKochPathParam generator; + BoolParam similar_only; + BoolParam drawall; + // BoolParam draw_boxes; + // FIXME: a path is used here instead of 2 points to work around path/point param incompatibility bug. + VonKochRefPathParam ref_path; // PointParam refA; // PointParam refB; - ScalarParam maxComplexity; + ScalarParam maxComplexity; - LPEVonKoch(const LPEVonKoch&) = delete; - LPEVonKoch& operator=(const LPEVonKoch&) = delete; + LPEVonKoch(const LPEVonKoch &) = delete; + LPEVonKoch &operator=(const LPEVonKoch &) = delete; }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpegroupbbox.cpp b/src/live_effects/lpegroupbbox.cpp index 863b08cc139828c7718310de543dff7ba28c3195..a870495b35fe2db9812fbb3f404a6c4aff1dce29 100644 --- a/src/live_effects/lpegroupbbox.cpp +++ b/src/live_effects/lpegroupbbox.cpp @@ -6,14 +6,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "document.h" #include "live_effects/lpegroupbbox.h" + +#include "document.h" #include "object/sp-clippath.h" +#include "object/sp-item-group.h" +#include "object/sp-lpe-item.h" #include "object/sp-mask.h" #include "object/sp-root.h" #include "object/sp-shape.h" -#include "object/sp-item-group.h" -#include "object/sp-lpe-item.h" namespace Inkscape { namespace LivePathEffect { @@ -21,32 +22,33 @@ namespace LivePathEffect { /** * Updates the \c boundingbox_X and \c boundingbox_Y values from the geometric bounding box of \c lpeitem. * - * @pre lpeitem must have an existing geometric boundingbox (usually this is guaranteed when: \code SP_SHAPE(lpeitem)->curve != NULL \endcode ) - * It's not possible to run LPEs on items without their original-d having a bbox. + * @pre lpeitem must have an existing geometric boundingbox (usually this is guaranteed when: \code + * SP_SHAPE(lpeitem)->curve != NULL \endcode ) It's not possible to run LPEs on items without their original-d having a + * bbox. * @param lpeitem This is not allowed to be NULL. - * @param absolute Determines whether the bbox should be calculated of the untransformed lpeitem (\c absolute = \c false) - * or of the transformed lpeitem (\c absolute = \c true) using sp_item_i2doc_affine. - * @post Updated values of boundingbox_X and boundingbox_Y. These intervals are set to empty intervals when the precondition is not met. + * @param absolute Determines whether the bbox should be calculated of the untransformed lpeitem (\c absolute = \c + * false) or of the transformed lpeitem (\c absolute = \c true) using sp_item_i2doc_affine. + * @post Updated values of boundingbox_X and boundingbox_Y. These intervals are set to empty intervals when the + * precondition is not met. */ -Geom::OptRect -GroupBBoxEffect::clip_mask_bbox(SPLPEItem *item, Geom::Affine transform) +Geom::OptRect GroupBBoxEffect::clip_mask_bbox(SPLPEItem *item, Geom::Affine transform) { Geom::OptRect bbox; Geom::Affine affine = transform * item->transform; SPClipPath *clip_path = item->getClipObject(); - if(clip_path) { + if (clip_path) { bbox.unionWith(clip_path->geometricBounds(affine)); } - SPMask * mask_path = item->getMaskObject(); - if(mask_path) { + SPMask *mask_path = item->getMaskObject(); + if (mask_path) { bbox.unionWith(mask_path->visualBounds(affine)); } - SPGroup * group = dynamic_cast(item); + SPGroup *group = dynamic_cast(item); if (group) { - std::vector item_list = sp_item_group_item_list(group); + std::vector item_list = sp_item_group_item_list(group); for (auto iter : item_list) { - SPLPEItem * subitem = dynamic_cast(iter); + SPLPEItem *subitem = dynamic_cast(iter); if (subitem) { bbox.unionWith(clip_mask_bbox(subitem, affine)); } @@ -55,20 +57,19 @@ GroupBBoxEffect::clip_mask_bbox(SPLPEItem *item, Geom::Affine transform) return bbox; } -void GroupBBoxEffect::original_bbox(SPLPEItem const* lpeitem, bool absolute, bool clip_mask) +void GroupBBoxEffect::original_bbox(SPLPEItem const *lpeitem, bool absolute, bool clip_mask) { // Get item bounding box Geom::Affine transform; if (absolute) { transform = lpeitem->i2doc_affine(); - } - else { + } else { transform = Geom::identity(); } - + Geom::OptRect bbox = lpeitem->geometricBounds(transform); if (clip_mask) { - SPLPEItem * item = const_cast(lpeitem); + SPLPEItem *item = const_cast(lpeitem); bbox.unionWith(clip_mask_bbox(item, transform * item->transform.inverse())); } if (bbox) { diff --git a/src/live_effects/lpegroupbbox.h b/src/live_effects/lpegroupbbox.h index 8c71151d85900a8ebf24a40bf7424ffe211355c9..faa0510724b7ecc52925911ce092814028b49b38 100644 --- a/src/live_effects/lpegroupbbox.h +++ b/src/live_effects/lpegroupbbox.h @@ -17,18 +17,19 @@ class SPLPEItem; namespace Inkscape { namespace LivePathEffect { -class GroupBBoxEffect { +class GroupBBoxEffect +{ protected: // Bounding box of the item the path effect is applied on Geom::Interval boundingbox_X; Geom::Interval boundingbox_Y; - //This sets boundingbox_X and boundingbox_Y - Geom::OptRect clip_mask_bbox(SPLPEItem * item, Geom::Affine transform); - void original_bbox(SPLPEItem const* lpeitem, bool absolute = false, bool clip_mask = false); + // This sets boundingbox_X and boundingbox_Y + Geom::OptRect clip_mask_bbox(SPLPEItem *item, Geom::Affine transform); + void original_bbox(SPLPEItem const *lpeitem, bool absolute = false, bool clip_mask = false); }; -}; //namespace LivePathEffect -}; //namespace Inkscape +}; // namespace LivePathEffect +}; // namespace Inkscape #endif diff --git a/src/live_effects/lpeobject-reference.cpp b/src/live_effects/lpeobject-reference.cpp index 10eec64eba98d74302b634f087296cf33cff94b8..ca253b62b61bc4c5fd4b0b835a3bdc365aee15fb 100644 --- a/src/live_effects/lpeobject-reference.cpp +++ b/src/live_effects/lpeobject-reference.cpp @@ -23,13 +23,15 @@ static void lpeobjectreference_href_changed(SPObject *old_ref, SPObject *ref, LP static void lpeobjectreference_delete_self(SPObject *deleted, LPEObjectReference *lpeobjref); static void lpeobjectreference_source_modified(SPObject *iSource, guint flags, LPEObjectReference *lpeobjref); -LPEObjectReference::LPEObjectReference(SPObject* i_owner) : URIReference(i_owner) +LPEObjectReference::LPEObjectReference(SPObject *i_owner) + : URIReference(i_owner) { - owner=i_owner; + owner = i_owner; lpeobject_href = nullptr; lpeobject_repr = nullptr; lpeobject = nullptr; - _changed_connection = changedSignal().connect(sigc::bind(sigc::ptr_fun(lpeobjectreference_href_changed), this)); // listening to myself, this should be virtual instead + _changed_connection = changedSignal().connect(sigc::bind( + sigc::ptr_fun(lpeobjectreference_href_changed), this)); // listening to myself, this should be virtual instead user_unlink = nullptr; } @@ -42,7 +44,7 @@ LPEObjectReference::~LPEObjectReference() unlink(); } -bool LPEObjectReference::_acceptObject(SPObject * const obj) const +bool LPEObjectReference::_acceptObject(SPObject *const obj) const { LivePathEffectObject *lpobj = dynamic_cast(obj); if (lpobj) { @@ -52,14 +54,13 @@ bool LPEObjectReference::_acceptObject(SPObject * const obj) const } } -void -LPEObjectReference::link(const char *to) +void LPEObjectReference::link(const char *to) { if (!to || !to[0]) { quit_listening(); unlink(); } else { - if ( !lpeobject_href || ( strcmp(to, lpeobject_href) != 0 ) ) { + if (!lpeobject_href || (strcmp(to, lpeobject_href) != 0)) { if (lpeobject_href) { g_free(lpeobject_href); } @@ -77,8 +78,7 @@ LPEObjectReference::link(const char *to) } } -void -LPEObjectReference::unlink() +void LPEObjectReference::unlink() { if (lpeobject_href) { g_free(lpeobject_href); @@ -87,10 +87,9 @@ LPEObjectReference::unlink() detach(); } -void -LPEObjectReference::start_listening(LivePathEffectObject* to) +void LPEObjectReference::start_listening(LivePathEffectObject *to) { - if ( to == nullptr ) { + if (to == nullptr) { return; } lpeobject = to; @@ -99,8 +98,7 @@ LPEObjectReference::start_listening(LivePathEffectObject* to) _modified_connection = to->connectModified(sigc::bind<2>(sigc::ptr_fun(&lpeobjectreference_source_modified), this)); } -void -LPEObjectReference::quit_listening() +void LPEObjectReference::quit_listening() { _modified_connection.disconnect(); _delete_connection.disconnect(); @@ -108,12 +106,11 @@ LPEObjectReference::quit_listening() lpeobject = nullptr; } -static void -lpeobjectreference_href_changed(SPObject */*old_ref*/, SPObject */*ref*/, LPEObjectReference *lpeobjref) +static void lpeobjectreference_href_changed(SPObject * /*old_ref*/, SPObject * /*ref*/, LPEObjectReference *lpeobjref) { lpeobjref->quit_listening(); - LivePathEffectObject *refobj = dynamic_cast( lpeobjref->getObject() ); - if ( refobj ) { + LivePathEffectObject *refobj = dynamic_cast(lpeobjref->getObject()); + if (refobj) { lpeobjref->start_listening(refobj); } if (lpeobjref->owner) { @@ -121,8 +118,7 @@ lpeobjectreference_href_changed(SPObject */*old_ref*/, SPObject */*ref*/, LPEObj } } -static void -lpeobjectreference_delete_self(SPObject */*deleted*/, LPEObjectReference *lpeobjref) +static void lpeobjectreference_delete_self(SPObject * /*deleted*/, LPEObjectReference *lpeobjref) { lpeobjref->quit_listening(); lpeobjref->unlink(); @@ -131,20 +127,19 @@ lpeobjectreference_delete_self(SPObject */*deleted*/, LPEObjectReference *lpeobj } } -static void -lpeobjectreference_source_modified(SPObject */*iSource*/, guint /*flags*/, LPEObjectReference *lpeobjref) +static void lpeobjectreference_source_modified(SPObject * /*iSource*/, guint /*flags*/, LPEObjectReference *lpeobjref) { -// We dont need to request update when LPE XML is updated -// Retain it temporary, drop if no regression -// SPObject *owner_obj = lpeobjref->owner; -// if (owner_obj) { -// lpeobjref->owner->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); -// } + // We dont need to request update when LPE XML is updated + // Retain it temporary, drop if no regression + // SPObject *owner_obj = lpeobjref->owner; + // if (owner_obj) { + // lpeobjref->owner->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + // } } -} //namespace LivePathEffect +} // namespace LivePathEffect -} // namespace inkscape +} // namespace Inkscape /* Local Variables: diff --git a/src/live_effects/lpeobject-reference.h b/src/live_effects/lpeobject-reference.h index a57d01a701cf541b64ab1449b43ffeba0d1d2ef8..ac486fcf7da0fe905e5c947c03ba2456c31711cd 100644 --- a/src/live_effects/lpeobject-reference.h +++ b/src/live_effects/lpeobject-reference.h @@ -19,7 +19,7 @@ namespace Inkscape { namespace XML { class Node; } -} +} // namespace Inkscape class LivePathEffectObject; @@ -27,37 +27,37 @@ namespace Inkscape { namespace LivePathEffect { -class LPEObjectReference : public Inkscape::URIReference { +class LPEObjectReference : public Inkscape::URIReference +{ public: LPEObjectReference(SPObject *owner); ~LPEObjectReference() override; - SPObject *owner; + SPObject *owner; // concerning the LPEObject that is referred to: - char *lpeobject_href; - Inkscape::XML::Node *lpeobject_repr; + char *lpeobject_href; + Inkscape::XML::Node *lpeobject_repr; LivePathEffectObject *lpeobject; sigc::connection _modified_connection; sigc::connection _delete_connection; sigc::connection _changed_connection; - void link(const char* to); - void unlink(); - void start_listening(LivePathEffectObject* to); - void quit_listening(); + void link(const char *to); + void unlink(); + void start_listening(LivePathEffectObject *to); + void quit_listening(); - void (*user_unlink) (LPEObjectReference *me, SPObject *user); + void (*user_unlink)(LPEObjectReference *me, SPObject *user); protected: - bool _acceptObject(SPObject * const obj) const override; - + bool _acceptObject(SPObject *const obj) const override; }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} // namespace inkscape +} // namespace Inkscape #endif /* !SEEN_LPEOBJECT_REFERENCE_H */ diff --git a/src/live_effects/lpeobject.cpp b/src/live_effects/lpeobject.cpp index f931515fd2d838b6a61f1d4d65480b2fb18c97ea..41304b2c19743dbbcb31a49e7413e8331e81564f 100644 --- a/src/live_effects/lpeobject.cpp +++ b/src/live_effects/lpeobject.cpp @@ -8,31 +8,30 @@ #include "live_effects/lpeobject.h" -#include "live_effects/effect.h" - -#include "xml/repr.h" -#include "xml/node-event-vector.h" #include "attributes.h" #include "document.h" - +#include "live_effects/effect.h" #include "object/sp-defs.h" +#include "xml/node-event-vector.h" +#include "xml/repr.h" //#define LIVEPATHEFFECT_VERBOSE -static void livepatheffect_on_repr_attr_changed (Inkscape::XML::Node * repr, const gchar *key, const gchar *oldval, const gchar *newval, bool is_interactive, void * data); +static void livepatheffect_on_repr_attr_changed(Inkscape::XML::Node *repr, const gchar *key, const gchar *oldval, + const gchar *newval, bool is_interactive, void *data); static Inkscape::XML::NodeEventVector const livepatheffect_repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - livepatheffect_on_repr_attr_changed, - nullptr, /* content_changed */ - nullptr /* order_changed */ + nullptr, /* child_added */ + nullptr, /* child_removed */ + livepatheffect_on_repr_attr_changed, nullptr, /* content_changed */ + nullptr /* order_changed */ }; - LivePathEffectObject::LivePathEffectObject() - : SPObject(), effecttype(Inkscape::LivePathEffect::INVALID_LPE), effecttype_set(false), - lpe(nullptr) + : SPObject() + , effecttype(Inkscape::LivePathEffect::INVALID_LPE) + , effecttype_set(false) + , lpe(nullptr) { #ifdef LIVEPATHEFFECT_VERBOSE g_message("Init livepatheffectobject"); @@ -44,7 +43,8 @@ LivePathEffectObject::~LivePathEffectObject() = default; /** * Virtual build: set livepatheffect attributes from its associated XML node. */ -void LivePathEffectObject::build(SPDocument *document, Inkscape::XML::Node *repr) { +void LivePathEffectObject::build(SPDocument *document, Inkscape::XML::Node *repr) +{ g_assert(SP_IS_OBJECT(this)); SPObject::build(document, repr); @@ -52,34 +52,35 @@ void LivePathEffectObject::build(SPDocument *document, Inkscape::XML::Node *repr this->readAttr(SPAttr::PATH_EFFECT); if (repr) { - repr->addListener (&livepatheffect_repr_events, this); + repr->addListener(&livepatheffect_repr_events, this); } /* Register ourselves, is this necessary? */ -// document->addResource("path-effect", object); + // document->addResource("path-effect", object); } /** * Virtual release of livepatheffect members before destruction. */ -void LivePathEffectObject::release() { +void LivePathEffectObject::release() +{ this->getRepr()->removeListenerByData(this); -/* - if (object->document) { - // Unregister ourselves - sp_document_removeResource(object->document, "livepatheffect", object); - } + /* + if (object->document) { + // Unregister ourselves + sp_document_removeResource(object->document, "livepatheffect", object); + } - if (gradient->ref) { - gradient->modified_connection.disconnect(); - gradient->ref->detach(); - delete gradient->ref; - gradient->ref = NULL; - } + if (gradient->ref) { + gradient->modified_connection.disconnect(); + gradient->ref->detach(); + delete gradient->ref; + gradient->ref = NULL; + } - gradient->modified_connection.~connection(); -*/ + gradient->modified_connection.~connection(); + */ if (this->lpe) { delete this->lpe; @@ -94,7 +95,8 @@ void LivePathEffectObject::release() { /** * Virtual set: set attribute to value. */ -void LivePathEffectObject::set(SPAttr key, gchar const *value) { +void LivePathEffectObject::set(SPAttr key, gchar const *value) +{ #ifdef LIVEPATHEFFECT_VERBOSE g_print("Set livepatheffect"); #endif @@ -106,7 +108,7 @@ void LivePathEffectObject::set(SPAttr key, gchar const *value) { this->lpe = nullptr; } - if ( value && Inkscape::LivePathEffect::LPETypeConverter.is_valid_key(value) ) { + if (value && Inkscape::LivePathEffect::LPETypeConverter.is_valid_key(value)) { this->effecttype = Inkscape::LivePathEffect::LPETypeConverter.get_id_from_key(value); this->lpe = Inkscape::LivePathEffect::Effect::New(this->effecttype, this); this->effecttype_set = true; @@ -126,13 +128,16 @@ void LivePathEffectObject::set(SPAttr key, gchar const *value) { /** * Virtual write: write object attributes to repr. */ -Inkscape::XML::Node* LivePathEffectObject::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *LivePathEffectObject::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("inkscape:path-effect"); } if ((flags & SP_OBJECT_WRITE_ALL) || this->lpe) { - repr->setAttributeOrRemoveIfEmpty("effect", Inkscape::LivePathEffect::LPETypeConverter.get_key(this->effecttype)); + repr->setAttributeOrRemoveIfEmpty("effect", + Inkscape::LivePathEffect::LPETypeConverter.get_key(this->effecttype)); this->lpe->writeParamsToSVG(); } @@ -142,13 +147,9 @@ Inkscape::XML::Node* LivePathEffectObject::write(Inkscape::XML::Document *xml_do return repr; } -static void -livepatheffect_on_repr_attr_changed ( Inkscape::XML::Node * /*repr*/, - const gchar *key, - const gchar */*oldval*/, - const gchar *newval, - bool /*is_interactive*/, - void * data ) +static void livepatheffect_on_repr_attr_changed(Inkscape::XML::Node * /*repr*/, const gchar *key, + const gchar * /*oldval*/, const gchar *newval, bool /*is_interactive*/, + void *data) { #ifdef LIVEPATHEFFECT_VERBOSE g_print("livepatheffect_on_repr_attr_changed"); @@ -157,7 +158,7 @@ livepatheffect_on_repr_attr_changed ( Inkscape::XML::Node * /*repr*/, if (!data) return; - LivePathEffectObject *lpeobj = (LivePathEffectObject*) data; + LivePathEffectObject *lpeobj = (LivePathEffectObject *)data; if (!lpeobj->get_lpe()) return; diff --git a/src/live_effects/lpeobject.h b/src/live_effects/lpeobject.h index 7353d4e93594f36bcf0c7424234d8a337930be22..53a1cb9c8ee7965946500e3c6f47b46fad3eb69e 100644 --- a/src/live_effects/lpeobject.h +++ b/src/live_effects/lpeobject.h @@ -10,28 +10,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "effect-enum.h" - #include "object/sp-object.h" namespace Inkscape { - namespace XML { - class Node; - struct Document; - } - namespace LivePathEffect { - class Effect; - } +namespace XML { +class Node; +struct Document; +} // namespace XML +namespace LivePathEffect { +class Effect; } +} // namespace Inkscape -#define LIVEPATHEFFECT(obj) ((LivePathEffectObject*)obj) -#define IS_LIVEPATHEFFECT(obj) (dynamic_cast((SPObject*)obj)) +#define LIVEPATHEFFECT(obj) ((LivePathEffectObject *)obj) +#define IS_LIVEPATHEFFECT(obj) (dynamic_cast((SPObject *)obj)) -class LivePathEffectObject : public SPObject { +class LivePathEffectObject : public SPObject +{ public: - LivePathEffectObject(); - ~LivePathEffectObject() override; + LivePathEffectObject(); + ~LivePathEffectObject() override; Inkscape::LivePathEffect::EffectType effecttype; @@ -39,26 +38,22 @@ public: // dont check values only structure and ID bool is_similar(LivePathEffectObject *that); - LivePathEffectObject * fork_private_if_necessary(unsigned int nr_of_allowed_users = 1); + LivePathEffectObject *fork_private_if_necessary(unsigned int nr_of_allowed_users = 1); - /* Note that the returned pointer can be NULL in a valid LivePathEffectObject contained in a valid list of lpeobjects in an lpeitem! - * So one should always check whether the returned value is NULL or not */ - Inkscape::LivePathEffect::Effect * get_lpe() { - return lpe; - } - Inkscape::LivePathEffect::Effect const * get_lpe() const { - return lpe; - }; + /* Note that the returned pointer can be NULL in a valid LivePathEffectObject contained in a valid list of + * lpeobjects in an lpeitem! So one should always check whether the returned value is NULL or not */ + Inkscape::LivePathEffect::Effect *get_lpe() { return lpe; } + Inkscape::LivePathEffect::Effect const *get_lpe() const { return lpe; }; Inkscape::LivePathEffect::Effect *lpe; // this can be NULL in a valid LivePathEffectObject protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif diff --git a/src/live_effects/parameter/array.cpp b/src/live_effects/parameter/array.cpp index 376252f45cf259efba283733ffa495bd2776d50e..8fb5811583a111c2e93a8cfc79675dd01ee21d42 100644 --- a/src/live_effects/parameter/array.cpp +++ b/src/live_effects/parameter/array.cpp @@ -6,17 +6,18 @@ */ #include "live_effects/parameter/array.h" -#include "helper-fns.h" + #include <2geom/coord.h> #include <2geom/point.h> +#include "helper-fns.h" + namespace Inkscape { namespace LivePathEffect { template <> -double -ArrayParam::readsvg(const gchar * str) +double ArrayParam::readsvg(const gchar *str) { double newx = Geom::infinity(); sp_svg_number_read_d(str, &newx); @@ -24,8 +25,7 @@ ArrayParam::readsvg(const gchar * str) } template <> -float -ArrayParam::readsvg(const gchar * str) +float ArrayParam::readsvg(const gchar *str) { float newx = Geom::infinity(); sp_svg_number_read_f(str, &newx); @@ -33,41 +33,38 @@ ArrayParam::readsvg(const gchar * str) } template <> -Geom::Point -ArrayParam::readsvg(const gchar * str) +Geom::Point ArrayParam::readsvg(const gchar *str) { - gchar ** strarray = g_strsplit(str, ",", 2); + gchar **strarray = g_strsplit(str, ",", 2); double newx, newy; unsigned int success = sp_svg_number_read_d(strarray[0], &newx); success += sp_svg_number_read_d(strarray[1], &newy); - g_strfreev (strarray); + g_strfreev(strarray); if (success == 2) { return Geom::Point(newx, newy); } - return Geom::Point(Geom::infinity(),Geom::infinity()); + return Geom::Point(Geom::infinity(), Geom::infinity()); } - template <> -std::vector -ArrayParam >::readsvg(const gchar * str) +std::vector ArrayParam>::readsvg(const gchar *str) { std::vector subpath_satellites; if (!str) { return subpath_satellites; } - gchar ** strarray = g_strsplit(str, "@", 0); - gchar ** iter = strarray; + gchar **strarray = g_strsplit(str, "@", 0); + gchar **iter = strarray; while (*iter != nullptr) { - gchar ** strsubarray = g_strsplit(*iter, ",", 8); - if (*strsubarray[7]) {//steps always > 0 + gchar **strsubarray = g_strsplit(*iter, ",", 8); + if (*strsubarray[7]) { // steps always > 0 Satellite *satellite = new Satellite(); satellite->setSatelliteType(g_strstrip(strsubarray[0])); - satellite->is_time = strncmp(strsubarray[1],"1",1) == 0; - satellite->selected = strncmp(strsubarray[2],"1",1) == 0; - satellite->has_mirror = strncmp(strsubarray[3],"1",1) == 0; - satellite->hidden = strncmp(strsubarray[4],"1",1) == 0; - double amount,angle; + satellite->is_time = strncmp(strsubarray[1], "1", 1) == 0; + satellite->selected = strncmp(strsubarray[2], "1", 1) == 0; + satellite->has_mirror = strncmp(strsubarray[3], "1", 1) == 0; + satellite->hidden = strncmp(strsubarray[4], "1", 1) == 0; + double amount, angle; float stepsTmp; sp_svg_number_read_d(strsubarray[5], &amount); sp_svg_number_read_d(strsubarray[6], &angle); @@ -78,14 +75,13 @@ ArrayParam >::readsvg(const gchar * str) satellite->steps = steps; subpath_satellites.push_back(*satellite); } - g_strfreev (strsubarray); + g_strfreev(strsubarray); iter++; } - g_strfreev (strarray); + g_strfreev(strarray); return subpath_satellites; } - } /* namespace LivePathEffect */ } /* namespace Inkscape */ diff --git a/src/live_effects/parameter/array.h b/src/live_effects/parameter/array.h index 1c9ffc4e0ecafbabc224727c3f83956769e48ef5..6fd60c5da20fac476c476b50b1bc587ba99b1fe7 100644 --- a/src/live_effects/parameter/array.h +++ b/src/live_effects/parameter/array.h @@ -10,78 +10,67 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include - #include - -#include "live_effects/parameter/parameter.h" +#include #include "helper/geom-satellite.h" -#include "svg/svg.h" +#include "live_effects/parameter/parameter.h" #include "svg/stringstream.h" +#include "svg/svg.h" namespace Inkscape { namespace LivePathEffect { template -class ArrayParam : public Parameter { +class ArrayParam : public Parameter +{ public: - ArrayParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - size_t n = 0 ) - : Parameter(label, tip, key, wr, effect), _vector(n), _default_size(n) - { + ArrayParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, size_t n = 0) + : Parameter(label, tip, key, wr, effect) + , _vector(n) + , _default_size(n) + {} - } + ~ArrayParam() override = default; + ; - ~ArrayParam() override = default;; + std::vector const &data() const { return _vector; } - std::vector const & data() const { - return _vector; - } + Gtk::Widget *param_newWidget() override { return nullptr; } - Gtk::Widget * param_newWidget() override { - return nullptr; - } - - bool param_readSVGValue(const gchar * strvalue) override { + bool param_readSVGValue(const gchar *strvalue) override + { _vector.clear(); - gchar ** strarray = g_strsplit(strvalue, "|", 0); - gchar ** iter = strarray; + gchar **strarray = g_strsplit(strvalue, "|", 0); + gchar **iter = strarray; while (*iter != nullptr) { - _vector.push_back( readsvg(*iter) ); + _vector.push_back(readsvg(*iter)); iter++; } - g_strfreev (strarray); + g_strfreev(strarray); return true; } - void param_update_default(const gchar * default_value) override{}; - Glib::ustring param_getSVGValue() const override { + void param_update_default(const gchar *default_value) override{}; + Glib::ustring param_getSVGValue() const override + { Inkscape::SVGOStringStream os; writesvg(os, _vector); return os.str(); } - - Glib::ustring param_getDefaultSVGValue() const override { - return ""; - } - void param_setValue(std::vector const &new_vector) { - _vector = new_vector; - } + Glib::ustring param_getDefaultSVGValue() const override { return ""; } - void param_set_default() override { - param_setValue( std::vector(_default_size) ); - } + void param_setValue(std::vector const &new_vector) { _vector = new_vector; } - void param_set_and_write_new_value(std::vector const &new_vector) { + void param_set_default() override { param_setValue(std::vector(_default_size)); } + + void param_set_and_write_new_value(std::vector const &new_vector) + { Inkscape::SVGOStringStream os; writesvg(os, new_vector); - gchar * str = g_strdup(os.str().c_str()); + gchar *str = g_strdup(os.str().c_str()); param_write_to_repr(str); g_free(str); } @@ -90,29 +79,25 @@ protected: std::vector _vector; size_t _default_size; - void writesvg(SVGOStringStream &str, std::vector const &vector) const { + void writesvg(SVGOStringStream &str, std::vector const &vector) const + { for (unsigned int i = 0; i < vector.size(); ++i) { if (i != 0) { // separate items with pipe symbol str << " | "; } - writesvgData(str,vector[i]); + writesvgData(str, vector[i]); } } - - void writesvgData(SVGOStringStream &str, float const &vector_data) const { - str << vector_data; - } - void writesvgData(SVGOStringStream &str, double const &vector_data) const { - str << vector_data; - } + void writesvgData(SVGOStringStream &str, float const &vector_data) const { str << vector_data; } - void writesvgData(SVGOStringStream &str, Geom::Point const &vector_data) const { - str << vector_data; - } + void writesvgData(SVGOStringStream &str, double const &vector_data) const { str << vector_data; } - void writesvgData(SVGOStringStream &str, std::vector const &vector_data) const { + void writesvgData(SVGOStringStream &str, Geom::Point const &vector_data) const { str << vector_data; } + + void writesvgData(SVGOStringStream &str, std::vector const &vector_data) const + { for (size_t i = 0; i < vector_data.size(); ++i) { if (i != 0) { // separate items with @ symbol ¿Any other? @@ -136,17 +121,16 @@ protected: } } - StorageType readsvg(const gchar * str); + StorageType readsvg(const gchar *str); private: - ArrayParam(const ArrayParam&); - ArrayParam& operator=(const ArrayParam&); + ArrayParam(const ArrayParam &); + ArrayParam &operator=(const ArrayParam &); }; +} // namespace LivePathEffect -} //namespace LivePathEffect - -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/bool.cpp b/src/live_effects/parameter/bool.cpp index d5e77caf38c0e85449d1eedfddc75ae0fded0e75..2ded7629da8fe0cbe851829d88e6384593f831cd 100644 --- a/src/live_effects/parameter/bool.cpp +++ b/src/live_effects/parameter/bool.cpp @@ -5,91 +5,79 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/registered-widget.h" #include "live_effects/parameter/bool.h" + +#include + +#include "helper-fns.h" +#include "inkscape.h" #include "live_effects/effect.h" -#include "svg/svg.h" #include "svg/stringstream.h" -#include "inkscape.h" +#include "svg/svg.h" +#include "ui/widget/registered-widget.h" #include "verbs.h" -#include "helper-fns.h" -#include namespace Inkscape { namespace LivePathEffect { -BoolParam::BoolParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, bool default_value) - : Parameter(label, tip, key, wr, effect), value(default_value), defvalue(default_value) -{ -} +BoolParam::BoolParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, bool default_value) + : Parameter(label, tip, key, wr, effect) + , value(default_value) + , defvalue(default_value) +{} -BoolParam::~BoolParam() -= default; +BoolParam::~BoolParam() = default; -void -BoolParam::param_set_default() +void BoolParam::param_set_default() { param_setValue(defvalue); } -void -BoolParam::param_update_default(bool const default_value) +void BoolParam::param_update_default(bool const default_value) { defvalue = default_value; } -void -BoolParam::param_update_default(const gchar * default_value) +void BoolParam::param_update_default(const gchar *default_value) { param_update_default(helperfns_read_bool(default_value, defvalue)); } -bool -BoolParam::param_readSVGValue(const gchar * strvalue) +bool BoolParam::param_readSVGValue(const gchar *strvalue) { param_setValue(helperfns_read_bool(strvalue, defvalue)); return true; // not correct: if value is unacceptable, should return false! } -Glib::ustring -BoolParam::param_getSVGValue() const +Glib::ustring BoolParam::param_getSVGValue() const { return value ? "true" : "false"; } -Glib::ustring -BoolParam::param_getDefaultSVGValue() const +Glib::ustring BoolParam::param_getDefaultSVGValue() const { return defvalue ? "true" : "false"; } -Gtk::Widget * -BoolParam::param_newWidget() +Gtk::Widget *BoolParam::param_newWidget() { - if(widget_is_visible){ - Inkscape::UI::Widget::RegisteredCheckButton * checkwdg = Gtk::manage( - new Inkscape::UI::Widget::RegisteredCheckButton( param_label, - param_tooltip, - param_key, - *param_wr, - false, - param_effect->getRepr(), - param_effect->getSPDoc()) ); + if (widget_is_visible) { + Inkscape::UI::Widget::RegisteredCheckButton *checkwdg = Gtk::manage( + new Inkscape::UI::Widget::RegisteredCheckButton(param_label, param_tooltip, param_key, *param_wr, false, + param_effect->getRepr(), param_effect->getSPDoc())); checkwdg->setActive(value); checkwdg->setProgrammatically = false; checkwdg->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change bool parameter")); - return dynamic_cast (checkwdg); + return dynamic_cast(checkwdg); } else { return nullptr; } } -void -BoolParam::param_setValue(bool newvalue) +void BoolParam::param_setValue(bool newvalue) { if (value != newvalue) { param_effect->refresh_widgets = true; diff --git a/src/live_effects/parameter/bool.h b/src/live_effects/parameter/bool.h index 72af92176fcbaff0d16d5dac27ac3e09bbb0c25f..f6c12d0bfedcdd23553c414d26445fb86d7c1400 100644 --- a/src/live_effects/parameter/bool.h +++ b/src/live_effects/parameter/bool.h @@ -18,29 +18,25 @@ namespace Inkscape { namespace LivePathEffect { - -class BoolParam : public Parameter { +class BoolParam : public Parameter +{ public: - BoolParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - bool default_value = false); + BoolParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, bool default_value = false); ~BoolParam() override; - BoolParam(const BoolParam&) = delete; - BoolParam& operator=(const BoolParam&) = delete; + BoolParam(const BoolParam &) = delete; + BoolParam &operator=(const BoolParam &) = delete; - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; - bool param_readSVGValue(const gchar * strvalue) override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; void param_setValue(bool newvalue); void param_set_default() override; void param_update_default(bool const default_value); - void param_update_default(const gchar * default_value) override; + void param_update_default(const gchar *default_value) override; bool get_value() const { return value; }; inline operator bool() const { return value; }; @@ -49,9 +45,8 @@ private: bool defvalue; }; +} // namespace LivePathEffect -} //namespace LivePathEffect - -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/colorpicker.cpp b/src/live_effects/parameter/colorpicker.cpp index d4300692dcef7b548d74e78503242bc50387c89c..66ad4bbd0a4fb99bb05edb271ff35710b90043d3 100644 --- a/src/live_effects/parameter/colorpicker.cpp +++ b/src/live_effects/parameter/colorpicker.cpp @@ -5,38 +5,35 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include "ui/widget/registered-widget.h" #include "live_effects/parameter/colorpicker.h" -#include "live_effects/effect.h" -#include "ui/widget/color-picker.h" -#include "svg/svg.h" -#include "svg/svg-color.h" + +#include +#include + #include "color.h" +#include "document-undo.h" +#include "document.h" #include "inkscape.h" +#include "live_effects/effect.h" #include "svg/stringstream.h" +#include "svg/svg-color.h" +#include "svg/svg.h" +#include "ui/widget/color-picker.h" +#include "ui/widget/registered-widget.h" #include "verbs.h" -#include "document.h" -#include "document-undo.h" - -#include namespace Inkscape { namespace LivePathEffect { -ColorPickerParam::ColorPickerParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, const guint32 default_color ) - : Parameter(label, tip, key, wr, effect), - value(default_color), - defvalue(default_color) -{ - -} +ColorPickerParam::ColorPickerParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const guint32 default_color) + : Parameter(label, tip, key, wr, effect) + , value(default_color) + , defvalue(default_color) +{} -void -ColorPickerParam::param_set_default() +void ColorPickerParam::param_set_default() { param_setValue(defvalue); } @@ -44,9 +41,12 @@ ColorPickerParam::param_set_default() static guint32 sp_read_color_alpha(gchar const *str, guint32 def) { guint32 val = 0; - if (str == nullptr) return def; - while ((*str <= ' ') && *str) str++; - if (!*str) return def; + if (str == nullptr) + return def; + while ((*str <= ' ') && *str) + str++; + if (!*str) + return def; if (str[0] == '#') { gint i; @@ -69,69 +69,56 @@ static guint32 sp_read_color_alpha(gchar const *str, guint32 def) return val; } -void -ColorPickerParam::param_update_default(const gchar * default_value) +void ColorPickerParam::param_update_default(const gchar *default_value) { defvalue = sp_read_color_alpha(default_value, 0x000000ff); } -bool -ColorPickerParam::param_readSVGValue(const gchar * strvalue) +bool ColorPickerParam::param_readSVGValue(const gchar *strvalue) { param_setValue(sp_read_color_alpha(strvalue, 0x000000ff)); return true; } -Glib::ustring -ColorPickerParam::param_getSVGValue() const +Glib::ustring ColorPickerParam::param_getSVGValue() const { gchar c[32]; sprintf(c, "#%08x", value); return c; } -Glib::ustring -ColorPickerParam::param_getDefaultSVGValue() const +Glib::ustring ColorPickerParam::param_getDefaultSVGValue() const { gchar c[32]; sprintf(c, "#%08x", defvalue); return c; } -Gtk::Widget * -ColorPickerParam::param_newWidget() +Gtk::Widget *ColorPickerParam::param_newWidget() { Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox()); hbox->set_border_width(5); hbox->set_homogeneous(false); hbox->set_spacing(2); - Inkscape::UI::Widget::RegisteredColorPicker * colorpickerwdg = - new Inkscape::UI::Widget::RegisteredColorPicker( param_label, - param_label, - param_tooltip, - param_key, - param_key + "_opacity_LPE", - *param_wr, - param_effect->getRepr(), - param_effect->getSPDoc() ); + Inkscape::UI::Widget::RegisteredColorPicker *colorpickerwdg = new Inkscape::UI::Widget::RegisteredColorPicker( + param_label, param_label, param_tooltip, param_key, param_key + "_opacity_LPE", *param_wr, + param_effect->getRepr(), param_effect->getSPDoc()); SPDocument *document = param_effect->getSPDoc(); bool saved = DocumentUndo::getUndoSensitive(document); DocumentUndo::setUndoSensitive(document, false); colorpickerwdg->setRgba32(value); DocumentUndo::setUndoSensitive(document, saved); colorpickerwdg->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change color button parameter")); - hbox->pack_start(*dynamic_cast (colorpickerwdg), true, true); - return dynamic_cast (hbox); + hbox->pack_start(*dynamic_cast(colorpickerwdg), true, true); + return dynamic_cast(hbox); } -void -ColorPickerParam::param_setValue(const guint32 newvalue) +void ColorPickerParam::param_setValue(const guint32 newvalue) { value = newvalue; } - } /* namespace LivePathEffect */ } /* namespace Inkscape */ diff --git a/src/live_effects/parameter/colorpicker.h b/src/live_effects/parameter/colorpicker.h index ef917b270be404d10391badf7c191f5df1bfbd23..c2ee3686dbf82466a0d91fe79ff275fb2317d1ba 100644 --- a/src/live_effects/parameter/colorpicker.h +++ b/src/live_effects/parameter/colorpicker.h @@ -9,44 +9,42 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include + #include "live_effects/parameter/parameter.h" namespace Inkscape { namespace LivePathEffect { -class ColorPickerParam : public Parameter { +class ColorPickerParam : public Parameter +{ public: - ColorPickerParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - const guint32 default_color = 0x000000ff); + ColorPickerParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const guint32 default_color = 0x000000ff); ~ColorPickerParam() override = default; - Gtk::Widget * param_newWidget() override; - bool param_readSVGValue(const gchar * strvalue) override; - void param_update_default(const gchar * default_value) override; + Gtk::Widget *param_newWidget() override; + bool param_readSVGValue(const gchar *strvalue) override; + void param_update_default(const gchar *default_value) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; void param_setValue(guint32 newvalue); - + void param_set_default() override; const guint32 get_value() const { return value; }; private: - ColorPickerParam(const ColorPickerParam&) = delete; - ColorPickerParam& operator=(const ColorPickerParam&) = delete; + ColorPickerParam(const ColorPickerParam &) = delete; + ColorPickerParam &operator=(const ColorPickerParam &) = delete; guint32 value; guint32 defvalue; }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/enum.h b/src/live_effects/parameter/enum.h index 251959346162fa7da0057a6e1db4ee7e2b494d92..9759a19fad81ba2d6a3ade4fcc95cbfe1a81cb8d 100644 --- a/src/live_effects/parameter/enum.h +++ b/src/live_effects/parameter/enum.h @@ -10,26 +10,24 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/registered-enums.h" #include + #include "live_effects/effect.h" #include "live_effects/parameter/parameter.h" +#include "ui/widget/registered-enums.h" #include "verbs.h" namespace Inkscape { namespace LivePathEffect { -template class EnumParam : public Parameter { +template +class EnumParam : public Parameter +{ public: - EnumParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - const Util::EnumDataConverter& c, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - E default_value, - bool sort = true) + EnumParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + const Util::EnumDataConverter &c, Inkscape::UI::Widget::Registry *wr, Effect *effect, E default_value, + bool sort = true) : Parameter(label, tip, key, wr, effect) { enumdataconv = &c; @@ -38,76 +36,65 @@ public: sorted = sort; }; - ~EnumParam() override = default;; - EnumParam(const EnumParam&) = delete; - EnumParam& operator=(const EnumParam&) = delete; + ~EnumParam() override = default; + ; + EnumParam(const EnumParam &) = delete; + EnumParam &operator=(const EnumParam &) = delete; - Gtk::Widget * param_newWidget() override { - Inkscape::UI::Widget::RegisteredEnum *regenum = Gtk::manage ( - new Inkscape::UI::Widget::RegisteredEnum( param_label, param_tooltip, - param_key, *enumdataconv, *param_wr, param_effect->getRepr(), param_effect->getSPDoc(), sorted ) ); + Gtk::Widget *param_newWidget() override + { + Inkscape::UI::Widget::RegisteredEnum *regenum = Gtk::manage( + new Inkscape::UI::Widget::RegisteredEnum(param_label, param_tooltip, param_key, *enumdataconv, *param_wr, + param_effect->getRepr(), param_effect->getSPDoc(), sorted)); regenum->set_active_by_id(value); regenum->combobox()->setProgrammatically = false; - regenum->combobox()->signal_changed().connect(sigc::mem_fun (*this, &EnumParam::_on_change_combo)); + regenum->combobox()->signal_changed().connect(sigc::mem_fun(*this, &EnumParam::_on_change_combo)); regenum->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change enumeration parameter")); - - return dynamic_cast (regenum); + + return dynamic_cast(regenum); }; void _on_change_combo() { param_effect->refresh_widgets = true; } - bool param_readSVGValue(const gchar * strvalue) override { + bool param_readSVGValue(const gchar *strvalue) override + { if (!strvalue) { param_set_default(); return true; } - param_set_value( enumdataconv->get_id_from_key(Glib::ustring(strvalue)) ); + param_set_value(enumdataconv->get_id_from_key(Glib::ustring(strvalue))); return true; }; - Glib::ustring param_getSVGValue() const override { - return enumdataconv->get_key(value); - }; - - Glib::ustring param_getDefaultSVGValue() const override { - return enumdataconv->get_key(defvalue).c_str(); - }; - - E get_value() const { - return value; - } + Glib::ustring param_getSVGValue() const override { return enumdataconv->get_key(value); }; - inline operator E() const { - return value; - }; + Glib::ustring param_getDefaultSVGValue() const override { return enumdataconv->get_key(defvalue).c_str(); }; - void param_set_default() override { - param_set_value(defvalue); - } - - void param_update_default(E default_value) { - defvalue = default_value; - } - - void param_update_default(const gchar * default_value) override { + E get_value() const { return value; } + + inline operator E() const { return value; }; + + void param_set_default() override { param_set_value(defvalue); } + + void param_update_default(E default_value) { defvalue = default_value; } + + void param_update_default(const gchar *default_value) override + { param_update_default(enumdataconv->get_id_from_key(Glib::ustring(default_value))); } - - void param_set_value(E val) { - value = val; - } + + void param_set_value(E val) { value = val; } private: E value; E defvalue; bool sorted; - const Util::EnumDataConverter * enumdataconv; + const Util::EnumDataConverter *enumdataconv; }; +}; // namespace LivePathEffect -}; //namespace LivePathEffect - -}; //namespace Inkscape +}; // namespace Inkscape #endif diff --git a/src/live_effects/parameter/fontbutton.cpp b/src/live_effects/parameter/fontbutton.cpp index 523c7d8e693d15ee8cd69ea67e4924a6bc2ec4d9..1b6b919459c4b4869faef1df9750a2ca81333067 100644 --- a/src/live_effects/parameter/fontbutton.cpp +++ b/src/live_effects/parameter/fontbutton.cpp @@ -5,44 +5,40 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include "ui/widget/registered-widget.h" #include "live_effects/parameter/fontbutton.h" + +#include +#include + #include "live_effects/effect.h" -#include "ui/widget/font-button.h" -#include "svg/svg.h" #include "svg/stringstream.h" +#include "svg/svg.h" +#include "ui/widget/font-button.h" +#include "ui/widget/registered-widget.h" #include "verbs.h" -#include - namespace Inkscape { namespace LivePathEffect { -FontButtonParam::FontButtonParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, const Glib::ustring default_value ) - : Parameter(label, tip, key, wr, effect), - value(default_value), - defvalue(default_value) -{ -} +FontButtonParam::FontButtonParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const Glib::ustring default_value) + : Parameter(label, tip, key, wr, effect) + , value(default_value) + , defvalue(default_value) +{} -void -FontButtonParam::param_set_default() +void FontButtonParam::param_set_default() { param_setValue(defvalue); } -void -FontButtonParam::param_update_default(const gchar * default_value) +void FontButtonParam::param_update_default(const gchar *default_value) { defvalue = Glib::ustring(default_value); } -bool -FontButtonParam::param_readSVGValue(const gchar * strvalue) +bool FontButtonParam::param_readSVGValue(const gchar *strvalue) { Inkscape::SVGOStringStream os; os << strvalue; @@ -50,38 +46,28 @@ FontButtonParam::param_readSVGValue(const gchar * strvalue) return true; } -Glib::ustring -FontButtonParam::param_getSVGValue() const +Glib::ustring FontButtonParam::param_getSVGValue() const { return value.c_str(); } -Glib::ustring -FontButtonParam::param_getDefaultSVGValue() const +Glib::ustring FontButtonParam::param_getDefaultSVGValue() const { return defvalue; } - - -Gtk::Widget * -FontButtonParam::param_newWidget() +Gtk::Widget *FontButtonParam::param_newWidget() { - Inkscape::UI::Widget::RegisteredFontButton * fontbuttonwdg = Gtk::manage( - new Inkscape::UI::Widget::RegisteredFontButton( param_label, - param_tooltip, - param_key, - *param_wr, - param_effect->getRepr(), - param_effect->getSPDoc() ) ); + Inkscape::UI::Widget::RegisteredFontButton *fontbuttonwdg = + Gtk::manage(new Inkscape::UI::Widget::RegisteredFontButton(param_label, param_tooltip, param_key, *param_wr, + param_effect->getRepr(), param_effect->getSPDoc())); Glib::ustring fontspec = param_getSVGValue(); - fontbuttonwdg->setValue( fontspec); + fontbuttonwdg->setValue(fontspec); fontbuttonwdg->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change font button parameter")); - return dynamic_cast (fontbuttonwdg); + return dynamic_cast(fontbuttonwdg); } -void -FontButtonParam::param_setValue(const Glib::ustring newvalue) +void FontButtonParam::param_setValue(const Glib::ustring newvalue) { if (value != newvalue) { param_effect->refresh_widgets = true; @@ -89,7 +75,6 @@ FontButtonParam::param_setValue(const Glib::ustring newvalue) value = newvalue; } - } /* namespace LivePathEffect */ } /* namespace Inkscape */ diff --git a/src/live_effects/parameter/fontbutton.h b/src/live_effects/parameter/fontbutton.h index 4f2950965038c2b78fa2b3b1711cbd017b9c0807..c2c35158f67abe0598cba4d61dda6c00f49d9972 100644 --- a/src/live_effects/parameter/fontbutton.h +++ b/src/live_effects/parameter/fontbutton.h @@ -9,45 +9,42 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include + #include "live_effects/parameter/parameter.h" namespace Inkscape { namespace LivePathEffect { -class FontButtonParam : public Parameter { +class FontButtonParam : public Parameter +{ public: - FontButtonParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - const Glib::ustring default_value = "Sans 10"); + FontButtonParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const Glib::ustring default_value = "Sans 10"); ~FontButtonParam() override = default; - Gtk::Widget * param_newWidget() override; - bool param_readSVGValue(const gchar * strvalue) override; - void param_update_default(const gchar * default_value) override; + Gtk::Widget *param_newWidget() override; + bool param_readSVGValue(const gchar *strvalue) override; + void param_update_default(const gchar *default_value) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; void param_setValue(Glib::ustring newvalue); - + void param_set_default() override; const Glib::ustring get_value() const { return defvalue; }; private: - FontButtonParam(const FontButtonParam&) = delete; - FontButtonParam& operator=(const FontButtonParam&) = delete; + FontButtonParam(const FontButtonParam &) = delete; + FontButtonParam &operator=(const FontButtonParam &) = delete; Glib::ustring value; Glib::ustring defvalue; - }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/hidden.cpp b/src/live_effects/parameter/hidden.cpp index dcb468efa3015461c2820cbef654ffe2fc9a15f2..529142c18369e9c78abf567cfbf0b3ac50544cef 100644 --- a/src/live_effects/parameter/hidden.cpp +++ b/src/live_effects/parameter/hidden.cpp @@ -11,66 +11,58 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "live_effects/parameter/hidden.h" + #include "live_effects/effect.h" -#include "svg/svg.h" #include "svg/stringstream.h" +#include "svg/svg.h" namespace Inkscape { namespace LivePathEffect { -HiddenParam::HiddenParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, const Glib::ustring default_value, bool is_visible) - : Parameter(label, tip, key, wr, effect), - value(default_value), - defvalue(default_value) +HiddenParam::HiddenParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const Glib::ustring default_value, + bool is_visible) + : Parameter(label, tip, key, wr, effect) + , value(default_value) + , defvalue(default_value) { param_widget_is_visible(is_visible); } -void -HiddenParam::param_set_default() +void HiddenParam::param_set_default() { param_setValue(defvalue); } -void -HiddenParam::param_update_default(const gchar * default_value) +void HiddenParam::param_update_default(const gchar *default_value) { defvalue = (Glib::ustring)default_value; } - -bool -HiddenParam::param_readSVGValue(const gchar * strvalue) +bool HiddenParam::param_readSVGValue(const gchar *strvalue) { param_setValue(strvalue); return true; } -Glib::ustring -HiddenParam::param_getSVGValue() const +Glib::ustring HiddenParam::param_getSVGValue() const { return value; } -Glib::ustring -HiddenParam::param_getDefaultSVGValue() const +Glib::ustring HiddenParam::param_getDefaultSVGValue() const { return defvalue; } -Gtk::Widget * -HiddenParam::param_newWidget() +Gtk::Widget *HiddenParam::param_newWidget() { return nullptr; } -void -HiddenParam::param_setValue(const Glib::ustring newvalue, bool write) +void HiddenParam::param_setValue(const Glib::ustring newvalue, bool write) { value = newvalue; if (write) { diff --git a/src/live_effects/parameter/hidden.h b/src/live_effects/parameter/hidden.h index 0a0df17cdf127b6d64a5ece909ab0f47576ea1dd..eb4aebcb173e886ae1b622fd8325323253a2ffa6 100644 --- a/src/live_effects/parameter/hidden.h +++ b/src/live_effects/parameter/hidden.h @@ -18,44 +18,40 @@ #include "live_effects/parameter/parameter.h" - namespace Inkscape { namespace LivePathEffect { -class HiddenParam : public Parameter { +class HiddenParam : public Parameter +{ public: - HiddenParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - const Glib::ustring default_value = "", - bool widget_is_visible = false); + HiddenParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const Glib::ustring default_value = "", + bool widget_is_visible = false); ~HiddenParam() override = default; - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; - bool param_readSVGValue(const gchar * strvalue) override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; void param_setValue(Glib::ustring newvalue, bool write = false); void param_set_default() override; - void param_update_default(const gchar * default_value) override; + void param_update_default(const gchar *default_value) override; const Glib::ustring get_value() const { return value; }; private: - HiddenParam(const HiddenParam&) = delete; - HiddenParam& operator=(const HiddenParam&) = delete; + HiddenParam(const HiddenParam &) = delete; + HiddenParam &operator=(const HiddenParam &) = delete; Glib::ustring value; Glib::ustring defvalue; }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/item-reference.cpp b/src/live_effects/parameter/item-reference.cpp index cea49010d51f363e708abe1c0d2b86add023d929..c2ba2fa11ee087f28cece3e9f4855a7dcc419e28 100644 --- a/src/live_effects/parameter/item-reference.cpp +++ b/src/live_effects/parameter/item-reference.cpp @@ -9,14 +9,14 @@ #include "live_effects/parameter/item-reference.h" +#include "object/sp-item-group.h" #include "object/sp-shape.h" #include "object/sp-text.h" -#include "object/sp-item-group.h" namespace Inkscape { namespace LivePathEffect { -bool ItemReference::_acceptObject(SPObject * const obj) const +bool ItemReference::_acceptObject(SPObject *const obj) const { if (SP_IS_SHAPE(obj) || SP_IS_TEXT(obj) || SP_IS_GROUP(obj)) { /* Refuse references to lpeobject */ diff --git a/src/live_effects/parameter/item-reference.h b/src/live_effects/parameter/item-reference.h index 64aaac0a77344d328b73df69dae510b68d76a789..79df538a2805156dd0131aa8ffab90ae8b8e7392 100644 --- a/src/live_effects/parameter/item-reference.h +++ b/src/live_effects/parameter/item-reference.h @@ -14,35 +14,36 @@ class SPItem; namespace Inkscape { -namespace XML { class Node; } +namespace XML { +class Node; +} namespace LivePathEffect { /** * The reference corresponding to href of LPE ItemParam. */ -class ItemReference : public Inkscape::URIReference { +class ItemReference : public Inkscape::URIReference +{ public: - ItemReference(SPObject *owner) : URIReference(owner) {} + ItemReference(SPObject *owner) + : URIReference(owner) + {} - SPItem *getObject() const { - return (SPItem *)URIReference::getObject(); - } + SPItem *getObject() const { return (SPItem *)URIReference::getObject(); } protected: - bool _acceptObject(SPObject * const obj) const override; + bool _acceptObject(SPObject *const obj) const override; private: - ItemReference(const ItemReference&) = delete; - ItemReference& operator=(const ItemReference&) = delete; + ItemReference(const ItemReference &) = delete; + ItemReference &operator=(const ItemReference &) = delete; }; } // namespace LivePathEffect } // namespace Inkscape - - #endif /* !SEEN_LPE_PATH_REFERENCE_H */ /* diff --git a/src/live_effects/parameter/item.cpp b/src/live_effects/parameter/item.cpp index dbcc45e63c388075de23c956c2d643007390f7a3..215c08fd540b6137d6c284ba6dc932b4d4683750 100644 --- a/src/live_effects/parameter/item.cpp +++ b/src/live_effects/parameter/item.cpp @@ -9,40 +9,35 @@ #include "live_effects/parameter/item.h" #include - #include #include #include "bad-uri-exception.h" -#include "ui/widget/point.h" - -#include "live_effects/effect.h" -#include "svg/svg.h" - #include "desktop.h" #include "inkscape.h" +#include "live_effects/effect.h" #include "message-stack.h" #include "selection-chemistry.h" +#include "svg/svg.h" #include "ui/icon-loader.h" +#include "ui/widget/point.h" #include "xml/repr.h" // clipboard support #include "ui/clipboard.h" // required for linking to other paths #include "object/uri.h" - #include "ui/icon-names.h" namespace Inkscape { namespace LivePathEffect { -ItemParam::ItemParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, const gchar * default_value) - : Parameter(label, tip, key, wr, effect), - changed(true), - href(nullptr), - ref( (SPObject*)effect->getLPEObj() ) +ItemParam::ItemParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const gchar *default_value) + : Parameter(label, tip, key, wr, effect) + , changed(true) + , href(nullptr) + , ref((SPObject *)effect->getLPEObj()) { last_transform = Geom::identity(); defvalue = g_strdup(default_value); @@ -55,25 +50,22 @@ ItemParam::~ItemParam() g_free(defvalue); } -void -ItemParam::param_set_default() +void ItemParam::param_set_default() { param_readSVGValue(defvalue); } -void -ItemParam::param_update_default(const gchar * default_value){ +void ItemParam::param_update_default(const gchar *default_value) +{ defvalue = strdup(default_value); } -void -ItemParam::param_set_and_write_default() +void ItemParam::param_set_and_write_default() { param_write_to_repr(defvalue); } -bool -ItemParam::param_readSVGValue(const gchar * strvalue) +bool ItemParam::param_readSVGValue(const gchar *strvalue) { if (strvalue) { remove_link(); @@ -83,8 +75,8 @@ ItemParam::param_readSVGValue(const gchar * strvalue) href = g_strdup(strvalue); try { ref.attach(Inkscape::URI(href)); - //lp:1299948 - SPItem* i = ref.getObject(); + // lp:1299948 + SPItem *i = ref.getObject(); if (i) { linked_modified_callback(i, SP_OBJECT_MODIFIED_FLAG); } // else: document still processing new events. Repr of the linked object not created yet. @@ -100,8 +92,7 @@ ItemParam::param_readSVGValue(const gchar * strvalue) return false; } -Glib::ustring -ItemParam::param_getSVGValue() const +Glib::ustring ItemParam::param_getSVGValue() const { if (href) { return href; @@ -109,81 +100,70 @@ ItemParam::param_getSVGValue() const return ""; } -Glib::ustring -ItemParam::param_getDefaultSVGValue() const +Glib::ustring ItemParam::param_getDefaultSVGValue() const { return defvalue; } -Gtk::Widget * -ItemParam::param_newWidget() +Gtk::Widget *ItemParam::param_newWidget() { - Gtk::HBox * _widget = Gtk::manage(new Gtk::HBox()); + Gtk::HBox *_widget = Gtk::manage(new Gtk::HBox()); Gtk::Image *pIcon = Gtk::manage(sp_get_icon_image("edit-clone", Gtk::ICON_SIZE_BUTTON)); - Gtk::Button * pButton = Gtk::manage(new Gtk::Button()); - Gtk::Label* pLabel = Gtk::manage(new Gtk::Label(param_label)); - static_cast(_widget)->pack_start(*pLabel, true, true); + Gtk::Button *pButton = Gtk::manage(new Gtk::Button()); + Gtk::Label *pLabel = Gtk::manage(new Gtk::Label(param_label)); + static_cast(_widget)->pack_start(*pLabel, true, true); pLabel->set_tooltip_text(param_tooltip); pButton->set_relief(Gtk::RELIEF_NONE); pIcon->show(); pButton->add(*pIcon); pButton->show(); pButton->signal_clicked().connect(sigc::mem_fun(*this, &ItemParam::on_link_button_click)); - static_cast(_widget)->pack_start(*pButton, true, true); + static_cast(_widget)->pack_start(*pButton, true, true); pButton->set_tooltip_text(_("Link to item on clipboard")); - static_cast(_widget)->show_all_children(); + static_cast(_widget)->show_all_children(); - return dynamic_cast (_widget); + return dynamic_cast(_widget); } -void -ItemParam::emit_changed() +void ItemParam::emit_changed() { changed = true; signal_item_changed.emit(); } +void ItemParam::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) {} -void -ItemParam::addCanvasIndicators(SPLPEItem const*/*lpeitem*/, std::vector &hp_vec) -{ -} - - -void -ItemParam::start_listening(SPObject * to) +void ItemParam::start_listening(SPObject *to) { - if ( to == nullptr ) { + if (to == nullptr) { return; } linked_delete_connection = to->connectDelete(sigc::mem_fun(*this, &ItemParam::linked_delete)); linked_modified_connection = to->connectModified(sigc::mem_fun(*this, &ItemParam::linked_modified)); if (SP_IS_ITEM(to)) { - linked_transformed_connection = SP_ITEM(to)->connectTransformed(sigc::mem_fun(*this, &ItemParam::linked_transformed)); + linked_transformed_connection = + SP_ITEM(to)->connectTransformed(sigc::mem_fun(*this, &ItemParam::linked_transformed)); } linked_modified(to, SP_OBJECT_MODIFIED_FLAG); // simulate linked_modified signal, so that path data is updated } -void -ItemParam::quit_listening() +void ItemParam::quit_listening() { linked_modified_connection.disconnect(); linked_delete_connection.disconnect(); linked_transformed_connection.disconnect(); } -void -ItemParam::ref_changed(SPObject */*old_ref*/, SPObject *new_ref) +void ItemParam::ref_changed(SPObject * /*old_ref*/, SPObject *new_ref) { quit_listening(); - if ( new_ref ) { + if (new_ref) { start_listening(new_ref); } } -void -ItemParam::remove_link() +void ItemParam::remove_link() { if (href) { ref.detach(); @@ -192,8 +172,7 @@ ItemParam::remove_link() } } -void -ItemParam::linked_delete(SPObject */*deleted*/) +void ItemParam::linked_delete(SPObject * /*deleted*/) { quit_listening(); remove_link(); @@ -209,24 +188,20 @@ void ItemParam::linked_transformed(Geom::Affine const *rel_transf, SPItem *moved linked_transformed_callback(rel_transf, moved_item); } -void -ItemParam::linked_modified_callback(SPObject *linked_obj, guint /*flags*/) +void ItemParam::linked_modified_callback(SPObject *linked_obj, guint /*flags*/) { emit_changed(); SP_OBJECT(param_effect->getLPEObj())->requestModified(SP_OBJECT_MODIFIED_FLAG); last_transform = Geom::identity(); } -void -ItemParam::linked_transformed_callback(Geom::Affine const *rel_transf, SPItem */*moved_item*/) +void ItemParam::linked_transformed_callback(Geom::Affine const *rel_transf, SPItem * /*moved_item*/) { last_transform = *rel_transf; SP_OBJECT(param_effect->getLPEObj())->requestModified(SP_OBJECT_MODIFIED_FLAG); } - -void -ItemParam::linkitem(Glib::ustring itemid) +void ItemParam::linkitem(Glib::ustring itemid) { if (itemid.empty()) { return; @@ -234,7 +209,7 @@ ItemParam::linkitem(Glib::ustring itemid) // add '#' at start to make it an uri. itemid.insert(itemid.begin(), '#'); - if ( href && strcmp(itemid.c_str(), href) == 0 ) { + if (href && strcmp(itemid.c_str(), href) == 0) { // no change, do nothing return; } else { @@ -243,20 +218,18 @@ ItemParam::linkitem(Glib::ustring itemid) // check if linking to object to which LPE is applied (maybe delegated to PathReference param_write_to_repr(itemid.c_str()); - DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Link item parameter to path")); + DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Link item parameter to path")); } } -void -ItemParam::on_link_button_click() +void ItemParam::on_link_button_click() { Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); auto itemid = cm->getFirstObjectID(); if (itemid.empty()) { return; } - + linkitem(itemid); } diff --git a/src/live_effects/parameter/item.h b/src/live_effects/parameter/item.h index a6a0e36b1200f911976f2267a0705cc24b575e59..66115e4cb98434554bb85858b883fde41a64f574 100644 --- a/src/live_effects/parameter/item.h +++ b/src/live_effects/parameter/item.h @@ -10,45 +10,40 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include #include +#include - -#include "live_effects/parameter/parameter.h" #include "live_effects/parameter/item-reference.h" -#include -#include +#include "live_effects/parameter/parameter.h" namespace Inkscape { namespace LivePathEffect { -class ItemParam : public Parameter { +class ItemParam : public Parameter +{ public: - ItemParam ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - const gchar * default_value = ""); + ItemParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const gchar *default_value = ""); ~ItemParam() override; - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; - bool param_readSVGValue(const gchar * strvalue) override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; void param_set_default() override; - void param_update_default(const gchar * default_value) override; + void param_update_default(const gchar *default_value) override; void param_set_and_write_default(); - void addCanvasIndicators(SPLPEItem const* lpeitem, std::vector &hp_vec) override; - sigc::signal signal_item_pasted; - sigc::signal signal_item_changed; + void addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec) override; + sigc::signal signal_item_pasted; + sigc::signal signal_item_changed; void linkitem(Glib::ustring itemid); Geom::Affine last_transform; - bool changed; /* this gets set whenever the path is changed (this is set to true, and then the signal_item_changed signal is emitted). - * the user must set it back to false if she wants to use it sensibly */ + bool changed; /* this gets set whenever the path is changed (this is set to true, and then the signal_item_changed + * signal is emitted). the user must set it back to false if she wants to use it sensibly */ protected: - - gchar * href; // contains link to other object, e.g. "#path2428", NULL if ItemParam contains pathdata itself + gchar *href; // contains link to other object, e.g. "#path2428", NULL if ItemParam contains pathdata itself ItemReference ref; sigc::connection ref_changed_connection; sigc::connection linked_delete_connection; @@ -56,26 +51,25 @@ protected: sigc::connection linked_transformed_connection; void ref_changed(SPObject *old_ref, SPObject *new_ref); void remove_link(); - void start_listening(SPObject * to); + void start_listening(SPObject *to); void quit_listening(); void linked_delete(SPObject *deleted); void linked_modified(SPObject *linked_obj, guint flags); void linked_transformed(Geom::Affine const *rel_transf, SPItem *moved_item); virtual void linked_modified_callback(SPObject *linked_obj, guint flags); - virtual void linked_transformed_callback(Geom::Affine const *rel_transf, SPItem */*moved_item*/); + virtual void linked_transformed_callback(Geom::Affine const *rel_transf, SPItem * /*moved_item*/); void on_link_button_click(); void emit_changed(); - gchar * defvalue; + gchar *defvalue; private: - ItemParam(const ItemParam&) = delete; - ItemParam& operator=(const ItemParam&) = delete; + ItemParam(const ItemParam &) = delete; + ItemParam &operator=(const ItemParam &) = delete; }; +} // namespace LivePathEffect -} //namespace LivePathEffect - -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/message.cpp b/src/live_effects/parameter/message.cpp index 341fc58fdcfc6e67d1b9f34e2c214121e64e1c50..d2c61a12fe32745fe65cebfb9a59dcf4101c8e8c 100644 --- a/src/live_effects/parameter/message.cpp +++ b/src/live_effects/parameter/message.cpp @@ -5,72 +5,66 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "live_effects/parameter/message.h" + #include #include - #include #include "include/gtkmm_version.h" -#include "live_effects/parameter/message.h" #include "live_effects/effect.h" namespace Inkscape { namespace LivePathEffect { -MessageParam::MessageParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, const gchar * default_message, Glib::ustring legend, - Gtk::Align halign, Gtk::Align valign, double marginstart, double marginend) - : Parameter(label, tip, key, wr, effect), - message(default_message), - defmessage(default_message), - _legend(std::move(legend)), - _halign(halign), - _valign(valign), - _marginstart(marginstart), - _marginend(marginend) +MessageParam::MessageParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const gchar *default_message, + Glib::ustring legend, Gtk::Align halign, Gtk::Align valign, double marginstart, + double marginend) + : Parameter(label, tip, key, wr, effect) + , message(default_message) + , defmessage(default_message) + , _legend(std::move(legend)) + , _halign(halign) + , _valign(valign) + , _marginstart(marginstart) + , _marginend(marginend) { if (_legend == Glib::ustring("Use Label")) { _legend = label; } - _label = nullptr; + _label = nullptr; _min_height = -1; } -void -MessageParam::param_set_default() +void MessageParam::param_set_default() { param_setValue(defmessage); } -void -MessageParam::param_update_default(const gchar * default_message) +void MessageParam::param_update_default(const gchar *default_message) { defmessage = default_message; } -bool -MessageParam::param_readSVGValue(const gchar * strvalue) +bool MessageParam::param_readSVGValue(const gchar *strvalue) { param_setValue(strvalue); return true; } -Glib::ustring -MessageParam::param_getSVGValue() const +Glib::ustring MessageParam::param_getSVGValue() const { return message; } -Glib::ustring -MessageParam::param_getDefaultSVGValue() const +Glib::ustring MessageParam::param_getDefaultSVGValue() const { return defmessage; } -void -MessageParam::param_set_min_height(int height) +void MessageParam::param_set_min_height(int height) { _min_height = height; if (_label) { @@ -78,31 +72,28 @@ MessageParam::param_set_min_height(int height) } } - -Gtk::Widget * -MessageParam::param_newWidget() +Gtk::Widget *MessageParam::param_newWidget() { - Gtk::Frame * frame = new Gtk::Frame (_legend); - Gtk::Widget * widg_frame = frame->get_label_widget(); + Gtk::Frame *frame = new Gtk::Frame(_legend); + Gtk::Widget *widg_frame = frame->get_label_widget(); widg_frame->set_margin_end(_marginend); widg_frame->set_margin_start(_marginstart); - _label = new Gtk::Label (message, Gtk::ALIGN_END); - _label->set_use_underline (true); + _label = new Gtk::Label(message, Gtk::ALIGN_END); + _label->set_use_underline(true); _label->set_use_markup(); _label->set_line_wrap(true); _label->set_size_request(-1, _min_height); - Gtk::Widget* widg_label = dynamic_cast (_label); + Gtk::Widget *widg_label = dynamic_cast(_label); widg_label->set_halign(_halign); widg_label->set_valign(_valign); widg_label->set_margin_end(_marginend); widg_label->set_margin_start(_marginstart); frame->add(*widg_label); - return dynamic_cast (frame); + return dynamic_cast(frame); } -void -MessageParam::param_setValue(const gchar * strvalue) +void MessageParam::param_setValue(const gchar *strvalue) { if (strcmp(strvalue, message) != 0) { param_effect->refresh_widgets = true; @@ -110,7 +101,6 @@ MessageParam::param_setValue(const gchar * strvalue) message = strvalue; } - } /* namespace LivePathEffect */ } /* namespace Inkscape */ diff --git a/src/live_effects/parameter/message.h b/src/live_effects/parameter/message.h index a08068c74731b1e5e10f8a37aeffbed88efbd20b..80daf7f71885e9f89d8d9e98b335f94cad5ab2ea 100644 --- a/src/live_effects/parameter/message.h +++ b/src/live_effects/parameter/message.h @@ -9,46 +9,41 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include + #include "live_effects/parameter/parameter.h" namespace Inkscape { namespace LivePathEffect { -class MessageParam : public Parameter { +class MessageParam : public Parameter +{ public: - MessageParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - const gchar * default_message = "Default message", - Glib::ustring legend = "Use Label", - Gtk::Align halign = Gtk::ALIGN_START, - Gtk::Align valign = Gtk::ALIGN_CENTER, - double marginstart = 6, - double marginend = 6); + MessageParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const gchar *default_message = "Default message", + Glib::ustring legend = "Use Label", Gtk::Align halign = Gtk::ALIGN_START, + Gtk::Align valign = Gtk::ALIGN_CENTER, double marginstart = 6, double marginend = 6); ~MessageParam() override = default; - Gtk::Widget * param_newWidget() override; - bool param_readSVGValue(const gchar * strvalue) override; - void param_update_default(const gchar * default_value) override; + Gtk::Widget *param_newWidget() override; + bool param_readSVGValue(const gchar *strvalue) override; + void param_update_default(const gchar *default_value) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; - void param_setValue(const gchar * message); - + void param_setValue(const gchar *message); + void param_set_default() override; void param_set_min_height(int height); - const gchar * get_value() const { return message; }; + const gchar *get_value() const { return message; }; private: - Gtk::Label * _label; + Gtk::Label *_label; int _min_height; - MessageParam(const MessageParam&) = delete; - MessageParam& operator=(const MessageParam&) = delete; - const gchar * message; - const gchar * defmessage; + MessageParam(const MessageParam &) = delete; + MessageParam &operator=(const MessageParam &) = delete; + const gchar *message; + const gchar *defmessage; Glib::ustring _legend; Gtk::Align _halign; Gtk::Align _valign; @@ -56,13 +51,11 @@ private: double _marginend; double _marginleft; double _marginright; - - }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/originalitem.cpp b/src/live_effects/parameter/originalitem.cpp index f4ad3815fc4996c8c407029d58523124cdd2c3c7..f5154757b7db7cd6108a4fd86b69acdd357a2888 100644 --- a/src/live_effects/parameter/originalitem.cpp +++ b/src/live_effects/parameter/originalitem.cpp @@ -5,22 +5,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "live_effects/parameter/originalitem.h" #include +#include #include #include +#include "desktop.h" #include "display/curve.h" -#include "live_effects/effect.h" - #include "inkscape.h" -#include "desktop.h" -#include "selection.h" - +#include "live_effects/effect.h" #include "object/uri.h" - +#include "selection.h" #include "ui/icon-loader.h" #include "ui/icon-names.h" @@ -28,24 +25,20 @@ namespace Inkscape { namespace LivePathEffect { -OriginalItemParam::OriginalItemParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect) +OriginalItemParam::OriginalItemParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect) : ItemParam(label, tip, key, wr, effect, "") -{ -} +{} -OriginalItemParam::~OriginalItemParam() -= default; +OriginalItemParam::~OriginalItemParam() = default; -Gtk::Widget * -OriginalItemParam::param_newWidget() +Gtk::Widget *OriginalItemParam::param_newWidget() { Gtk::HBox *_widget = Gtk::manage(new Gtk::HBox()); { // Label Gtk::Label *pLabel = Gtk::manage(new Gtk::Label(param_label)); - static_cast(_widget)->pack_start(*pLabel, true, true); + static_cast(_widget)->pack_start(*pLabel, true, true); pLabel->set_tooltip_text(param_tooltip); } @@ -57,7 +50,7 @@ OriginalItemParam::param_newWidget() pButton->add(*pIcon); pButton->show(); pButton->signal_clicked().connect(sigc::mem_fun(*this, &OriginalItemParam::on_link_button_click)); - static_cast(_widget)->pack_start(*pButton, true, true); + static_cast(_widget)->pack_start(*pButton, true, true); pButton->set_tooltip_text(_("Link to item")); } @@ -69,33 +62,29 @@ OriginalItemParam::param_newWidget() pButton->add(*pIcon); pButton->show(); pButton->signal_clicked().connect(sigc::mem_fun(*this, &OriginalItemParam::on_select_original_button_click)); - static_cast(_widget)->pack_start(*pButton, true, true); + static_cast(_widget)->pack_start(*pButton, true, true); pButton->set_tooltip_text(_("Select original")); } - static_cast(_widget)->show_all_children(); + static_cast(_widget)->show_all_children(); - return dynamic_cast (_widget); + return dynamic_cast(_widget); } -void -OriginalItemParam::linked_modified_callback(SPObject *linked_obj, guint /*flags*/) +void OriginalItemParam::linked_modified_callback(SPObject *linked_obj, guint /*flags*/) { emit_changed(); SP_OBJECT(param_effect->getLPEObj())->requestModified(SP_OBJECT_MODIFIED_FLAG); last_transform = Geom::identity(); } -void -OriginalItemParam::linked_transformed_callback(Geom::Affine const * rel_transf, SPItem *moved_item) +void OriginalItemParam::linked_transformed_callback(Geom::Affine const *rel_transf, SPItem *moved_item) { last_transform = *rel_transf; SP_OBJECT(param_effect->getLPEObj())->requestModified(SP_OBJECT_MODIFIED_FLAG); } - -void -OriginalItemParam::on_select_original_button_click() +void OriginalItemParam::on_select_original_button_click() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; SPItem *original = ref.getObject(); diff --git a/src/live_effects/parameter/originalitem.h b/src/live_effects/parameter/originalitem.h index 26729f6de8dbae85f6046d41a31a254c3d1d9edb..988154682a2b2cd40bb367cee1465024259a0f8d 100644 --- a/src/live_effects/parameter/originalitem.h +++ b/src/live_effects/parameter/originalitem.h @@ -16,18 +16,16 @@ namespace Inkscape { namespace LivePathEffect { -class OriginalItemParam: public ItemParam { +class OriginalItemParam : public ItemParam +{ public: - OriginalItemParam ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect); + OriginalItemParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect); ~OriginalItemParam() override; bool linksToItem() const { return (href != nullptr); } - SPItem * getObject() const { return ref.getObject(); } + SPItem *getObject() const { return ref.getObject(); } - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; protected: void linked_modified_callback(SPObject *linked_obj, guint flags) override; @@ -36,13 +34,12 @@ protected: void on_select_original_button_click(); private: - OriginalItemParam(const OriginalItemParam&) = delete; - OriginalItemParam& operator=(const OriginalItemParam&) = delete; + OriginalItemParam(const OriginalItemParam &) = delete; + OriginalItemParam &operator=(const OriginalItemParam &) = delete; }; +} // namespace LivePathEffect -} //namespace LivePathEffect - -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/originalitemarray.cpp b/src/live_effects/parameter/originalitemarray.cpp index 30b25dc4b8fd4aec5d2ebb6cdd59d34fe1808400..b43787b8f51e93d93d1a6ad4a0d537056f4349dd 100644 --- a/src/live_effects/parameter/originalitemarray.cpp +++ b/src/live_effects/parameter/originalitemarray.cpp @@ -7,28 +7,24 @@ #include "live_effects/parameter/originalitemarray.h" -#include +#include #include #include -#include #include +#include +#include -#include - +#include "document-undo.h" +#include "document.h" #include "inkscape.h" +#include "live_effects/effect.h" +#include "object/uri.h" #include "originalitem.h" #include "svg/stringstream.h" #include "svg/svg.h" #include "ui/clipboard.h" #include "ui/icon-loader.h" - -#include "object/uri.h" - -#include "live_effects/effect.h" - #include "verbs.h" -#include "document-undo.h" -#include "document.h" namespace Inkscape { @@ -37,7 +33,6 @@ namespace LivePathEffect { class OriginalItemArrayParam::ModelColumns : public Gtk::TreeModel::ColumnRecord { public: - ModelColumns() { add(_colObject); @@ -46,52 +41,50 @@ public: } ~ModelColumns() override = default; - Gtk::TreeModelColumn _colObject; + Gtk::TreeModelColumn _colObject; Gtk::TreeModelColumn _colLabel; Gtk::TreeModelColumn _colActive; }; -OriginalItemArrayParam::OriginalItemArrayParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect ) -: Parameter(label, tip, key, wr, effect), - _vector(), - _tree(), - _text_renderer(), - _toggle_active(), - _scroller() -{ +OriginalItemArrayParam::OriginalItemArrayParam(const Glib::ustring &label, const Glib::ustring &tip, + const Glib::ustring &key, Inkscape::UI::Widget::Registry *wr, + Effect *effect) + : Parameter(label, tip, key, wr, effect) + , _vector() + , _tree() + , _text_renderer() + , _toggle_active() + , _scroller() +{ _model = new ModelColumns(); _store = Gtk::TreeStore::create(*_model); _tree.set_model(_store); _tree.set_reorderable(true); - _tree.enable_model_drag_dest (Gdk::ACTION_MOVE); - - Gtk::CellRendererToggle * _toggle_active = manage(new Gtk::CellRendererToggle()); + _tree.enable_model_drag_dest(Gdk::ACTION_MOVE); + + Gtk::CellRendererToggle *_toggle_active = manage(new Gtk::CellRendererToggle()); int activeColNum = _tree.append_column(_("Active"), *_toggle_active) - 1; - Gtk::TreeViewColumn* col_active = _tree.get_column(activeColNum); + Gtk::TreeViewColumn *col_active = _tree.get_column(activeColNum); _toggle_active->set_activatable(true); _toggle_active->signal_toggled().connect(sigc::mem_fun(*this, &OriginalItemArrayParam::on_active_toggled)); col_active->add_attribute(_toggle_active->property_active(), _model->_colActive); - + _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_expander_column(*_tree.get_column(nameColNum)); _tree.set_search_column(_model->_colLabel); - - //quick little hack -- newer versions of gtk gave the item zero space allotment + + // quick little hack -- newer versions of gtk gave the item zero space allotment _scroller.set_size_request(-1, 120); _scroller.add(_tree); - _scroller.set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC ); + _scroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); //_scroller.set_shadow_type(Gtk::SHADOW_IN); - + oncanvas_editable = true; } @@ -106,33 +99,28 @@ OriginalItemArrayParam::~OriginalItemArrayParam() delete _model; } -void OriginalItemArrayParam::on_active_toggled(const Glib::ustring& item) +void OriginalItemArrayParam::on_active_toggled(const Glib::ustring &item) { Gtk::TreeModel::iterator iter = _store->get_iter(item); Gtk::TreeModel::Row row = *iter; ItemAndActive *w = row[_model->_colObject]; row[_model->_colActive] = !row[_model->_colActive]; w->actived = row[_model->_colActive]; - + auto full = param_getSVGValue(); param_write_to_repr(full.c_str()); - DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Link item parameter to item")); + DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Link item parameter to item")); } -void OriginalItemArrayParam::param_set_default() -{ - -} +void OriginalItemArrayParam::param_set_default() {} -Gtk::Widget* OriginalItemArrayParam::param_newWidget() +Gtk::Widget *OriginalItemArrayParam::param_newWidget() { - Gtk::VBox* vbox = Gtk::manage(new Gtk::VBox()); - Gtk::HBox* hbox = Gtk::manage(new Gtk::HBox()); + Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox()); + Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox()); vbox->pack_start(_scroller, Gtk::PACK_EXPAND_WIDGET); - - + { // Paste item to link button Gtk::Image *pIcon = Gtk::manage(sp_get_icon_image("edit-clone", Gtk::ICON_SIZE_BUTTON)); Gtk::Button *pButton = Gtk::manage(new Gtk::Button()); @@ -144,7 +132,7 @@ Gtk::Widget* OriginalItemArrayParam::param_newWidget() hbox->pack_start(*pButton, Gtk::PACK_SHRINK); pButton->set_tooltip_text(_("Link to item")); } - + { // Remove linked item Gtk::Image *pIcon = Gtk::manage(sp_get_icon_image("list-remove", Gtk::ICON_SIZE_BUTTON)); Gtk::Button *pButton = Gtk::manage(new Gtk::Button()); @@ -156,7 +144,7 @@ Gtk::Widget* OriginalItemArrayParam::param_newWidget() hbox->pack_start(*pButton, Gtk::PACK_SHRINK); pButton->set_tooltip_text(_("Remove Item")); } - + { // Move Down Gtk::Image *pIcon = Gtk::manage(sp_get_icon_image("go-down", Gtk::ICON_SIZE_BUTTON)); Gtk::Button *pButton = Gtk::manage(new Gtk::Button()); @@ -168,7 +156,7 @@ Gtk::Widget* OriginalItemArrayParam::param_newWidget() hbox->pack_end(*pButton, Gtk::PACK_SHRINK); pButton->set_tooltip_text(_("Move Down")); } - + { // Move Down Gtk::Image *pIcon = Gtk::manage(sp_get_icon_image("go-up", Gtk::ICON_SIZE_BUTTON)); Gtk::Button *pButton = Gtk::manage(new Gtk::Button()); @@ -180,15 +168,15 @@ Gtk::Widget* OriginalItemArrayParam::param_newWidget() hbox->pack_end(*pButton, Gtk::PACK_SHRINK); pButton->set_tooltip_text(_("Move Up")); } - + vbox->pack_end(*hbox, Gtk::PACK_SHRINK); - + vbox->show_all_children(true); - + return vbox; } -bool OriginalItemArrayParam::_selectIndex(const Gtk::TreeIter& iter, int* i) +bool OriginalItemArrayParam::_selectIndex(const Gtk::TreeIter &iter, int *i) { if ((*i)-- <= 0) { _tree.get_selection()->select(iter); @@ -202,24 +190,24 @@ void OriginalItemArrayParam::on_up_button_click() Gtk::TreeModel::iterator iter = _tree.get_selection()->get_selected(); if (iter) { Gtk::TreeModel::Row row = *iter; - + int i = -1; - std::vector::iterator piter = _vector.begin(); - for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); piter = iter, i++, ++iter) { + std::vector::iterator piter = _vector.begin(); + for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); + piter = iter, i++, ++iter) { if (*iter == row[_model->_colObject]) { _vector.erase(iter); _vector.insert(piter, row[_model->_colObject]); break; } } - + auto full = param_getSVGValue(); param_write_to_repr(full.c_str()); - - DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Move item up")); - - _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::_selectIndex), &i)); + + DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Move item up")); + + _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::_selectIndex), &i)); } } @@ -230,9 +218,9 @@ void OriginalItemArrayParam::on_down_button_click() Gtk::TreeModel::Row row = *iter; int i = 0; - for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); i++, ++iter) { + for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); i++, ++iter) { if (*iter == row[_model->_colObject]) { - std::vector::iterator niter = _vector.erase(iter); + std::vector::iterator niter = _vector.erase(iter); if (niter != _vector.end()) { ++niter; i++; @@ -241,14 +229,13 @@ void OriginalItemArrayParam::on_down_button_click() break; } } - + auto full = param_getSVGValue(); param_write_to_repr(full.c_str()); - - DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Move item down")); - - _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::_selectIndex), &i)); + + DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Move item down")); + + _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::_selectIndex), &i)); } } @@ -258,27 +245,24 @@ void OriginalItemArrayParam::on_remove_button_click() if (iter) { Gtk::TreeModel::Row row = *iter; remove_link(row[_model->_colObject]); - + auto full = param_getSVGValue(); param_write_to_repr(full.c_str()); - - DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Remove item")); + + DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Remove item")); } - } -void -OriginalItemArrayParam::on_link_button_click() +void OriginalItemArrayParam::on_link_button_click() { Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); - //without second parameter populate all elements filled inside the called function + // without second parameter populate all elements filled inside the called function std::vector itemsid = cm->getElementsOfType(SP_ACTIVE_DESKTOP, "*", 1); if (itemsid.empty()) { return; } - + bool foundOne = false; Inkscape::SVGOStringStream os; for (auto iter : _vector) { @@ -305,7 +289,7 @@ OriginalItemArrayParam::on_link_button_click() _("Link itemarray parameter to item")); } -void OriginalItemArrayParam::unlink(ItemAndActive* to) +void OriginalItemArrayParam::unlink(ItemAndActive *to) { to->linked_modified_connection.disconnect(); to->linked_delete_connection.disconnect(); @@ -313,13 +297,13 @@ void OriginalItemArrayParam::unlink(ItemAndActive* to) if (to->href) { g_free(to->href); to->href = nullptr; - } + } } -void OriginalItemArrayParam::remove_link(ItemAndActive* to) +void OriginalItemArrayParam::remove_link(ItemAndActive *to) { unlink(to); - for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); ++iter) { + for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); ++iter) { if (*iter == to) { ItemAndActive *w = *iter; _vector.erase(iter); @@ -329,52 +313,56 @@ void OriginalItemArrayParam::remove_link(ItemAndActive* to) } } -void OriginalItemArrayParam::linked_delete(SPObject */*deleted*/, ItemAndActive* to) +void OriginalItemArrayParam::linked_delete(SPObject * /*deleted*/, ItemAndActive *to) { remove_link(to); auto full = param_getSVGValue(); param_write_to_repr(full.c_str()); } -bool OriginalItemArrayParam::_updateLink(const Gtk::TreeIter& iter, ItemAndActive* pd) +bool OriginalItemArrayParam::_updateLink(const Gtk::TreeIter &iter, ItemAndActive *pd) { Gtk::TreeModel::Row row = *iter; if (row[_model->_colObject] == pd) { SPObject *obj = pd->ref.getObject(); - row[_model->_colLabel] = obj && obj->getId() ? ( obj->label() ? obj->label() : obj->getId() ) : pd->href; + row[_model->_colLabel] = obj && obj->getId() ? (obj->label() ? obj->label() : obj->getId()) : pd->href; return true; } return false; } -void OriginalItemArrayParam::linked_changed(SPObject */*old_obj*/, SPObject *new_obj, ItemAndActive* to) +void OriginalItemArrayParam::linked_changed(SPObject * /*old_obj*/, SPObject *new_obj, ItemAndActive *to) { to->linked_delete_connection.disconnect(); to->linked_modified_connection.disconnect(); to->linked_transformed_connection.disconnect(); - + if (new_obj && SP_IS_ITEM(new_obj)) { - to->linked_delete_connection = new_obj->connectDelete(sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::linked_delete), to)); - to->linked_modified_connection = new_obj->connectModified(sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::linked_modified), to)); - to->linked_transformed_connection = SP_ITEM(new_obj)->connectTransformed(sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::linked_transformed), to)); + to->linked_delete_connection = new_obj->connectDelete( + sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::linked_delete), to)); + to->linked_modified_connection = new_obj->connectModified( + sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::linked_modified), to)); + to->linked_transformed_connection = SP_ITEM(new_obj)->connectTransformed( + sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::linked_transformed), to)); linked_modified(new_obj, SP_OBJECT_MODIFIED_FLAG, to); } else { SP_OBJECT(param_effect->getLPEObj())->requestModified(SP_OBJECT_MODIFIED_FLAG); - _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::_updateLink), to)); + _store->foreach_iter( + sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::_updateLink), to)); } } -void OriginalItemArrayParam::linked_modified(SPObject *linked_obj, guint flags, ItemAndActive* to) +void OriginalItemArrayParam::linked_modified(SPObject *linked_obj, guint flags, ItemAndActive *to) { if (!to) { return; } SP_OBJECT(param_effect->getLPEObj())->requestModified(SP_OBJECT_MODIFIED_FLAG); - _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::_updateLink), to)); + _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::_updateLink), to)); } -bool OriginalItemArrayParam::param_readSVGValue(const gchar* strvalue) +bool OriginalItemArrayParam::param_readSVGValue(const gchar *strvalue) { if (strvalue) { while (!_vector.empty()) { @@ -385,14 +373,15 @@ bool OriginalItemArrayParam::param_readSVGValue(const gchar* strvalue) } _store->clear(); - gchar ** strarray = g_strsplit(strvalue, "|", 0); - for (gchar ** iter = strarray; *iter != nullptr; iter++) { + gchar **strarray = g_strsplit(strvalue, "|", 0); + for (gchar **iter = strarray; *iter != nullptr; iter++) { if ((*iter)[0] == '#') { - gchar ** substrarray = g_strsplit(*iter, ",", 0); - ItemAndActive* w = new ItemAndActive((SPObject *)param_effect->getLPEObj()); + gchar **substrarray = g_strsplit(*iter, ",", 0); + ItemAndActive *w = new ItemAndActive((SPObject *)param_effect->getLPEObj()); w->href = g_strdup(*substrarray); - w->actived = *(substrarray+1) != nullptr && (*(substrarray+1))[0] == '1'; - w->linked_changed_connection = w->ref.changedSignal().connect(sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::linked_changed), w)); + w->actived = *(substrarray + 1) != nullptr && (*(substrarray + 1))[0] == '1'; + w->linked_changed_connection = w->ref.changedSignal().connect( + sigc::bind(sigc::mem_fun(*this, &OriginalItemArrayParam::linked_changed), w)); w->ref.attach(URI(w->href)); _vector.push_back(w); @@ -402,19 +391,18 @@ bool OriginalItemArrayParam::param_readSVGValue(const gchar* strvalue) SPObject *obj = w->ref.getObject(); row[_model->_colObject] = w; - row[_model->_colLabel] = obj ? ( obj->label() ? obj->label() : obj->getId() ) : w->href; + row[_model->_colLabel] = obj ? (obj->label() ? obj->label() : obj->getId()) : w->href; row[_model->_colActive] = w->actived; - g_strfreev (substrarray); + g_strfreev(substrarray); } } - g_strfreev (strarray); + g_strfreev(strarray); return true; } return false; } -Glib::ustring -OriginalItemArrayParam::param_getSVGValue() const +Glib::ustring OriginalItemArrayParam::param_getSVGValue() const { Inkscape::SVGOStringStream os; bool foundOne = false; @@ -429,15 +417,14 @@ OriginalItemArrayParam::param_getSVGValue() const return os.str(); } -Glib::ustring -OriginalItemArrayParam::param_getDefaultSVGValue() const +Glib::ustring OriginalItemArrayParam::param_getDefaultSVGValue() const { return ""; } void OriginalItemArrayParam::update() { - for (auto & iter : _vector) { + for (auto &iter : _vector) { SPObject *linked_obj = iter->ref.getObject(); linked_modified(linked_obj, SP_OBJECT_MODIFIED_FLAG, iter); } diff --git a/src/live_effects/parameter/originalitemarray.h b/src/live_effects/parameter/originalitemarray.h index baa764622768977e09082b8ccfd425aa00694f87..def6113c1d8c80d8b176ac0f7ad3412272540e8f 100644 --- a/src/live_effects/parameter/originalitemarray.h +++ b/src/live_effects/parameter/originalitemarray.h @@ -10,19 +10,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include - #include -#include -#include #include +#include +#include +#include -#include "live_effects/parameter/parameter.h" +#include "item-reference.h" #include "live_effects/parameter/item-reference.h" - -#include "svg/svg.h" +#include "live_effects/parameter/parameter.h" #include "svg/stringstream.h" -#include "item-reference.h" +#include "svg/svg.h" class SPObject; @@ -30,62 +28,59 @@ namespace Inkscape { namespace LivePathEffect { -class ItemAndActive { +class ItemAndActive +{ public: ItemAndActive(SPObject *owner) - : href(nullptr), - ref(owner), - actived(true) - { - - } + : href(nullptr) + , ref(owner) + , actived(true) + {} gchar *href; URIReference ref; bool actived; - + sigc::connection linked_changed_connection; sigc::connection linked_delete_connection; sigc::connection linked_modified_connection; sigc::connection linked_transformed_connection; }; - -class OriginalItemArrayParam : public Parameter { + +class OriginalItemArrayParam : public Parameter +{ public: class ModelColumns; - - OriginalItemArrayParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect); + + OriginalItemArrayParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect); ~OriginalItemArrayParam() override; - Gtk::Widget * param_newWidget() override; - bool param_readSVGValue(const gchar * strvalue) override; + Gtk::Widget *param_newWidget() override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; void param_set_default() override; - void param_update_default(const gchar * default_value) override{}; + void param_update_default(const gchar *default_value) override{}; /** Disable the canvas indicators of parent class by overriding this method */ - void param_editOncanvas(SPItem * /*item*/, SPDesktop * /*dt*/) override {}; + void param_editOncanvas(SPItem * /*item*/, SPDesktop * /*dt*/) override{}; /** Disable the canvas indicators of parent class by overriding this method */ - void addCanvasIndicators(SPLPEItem const* /*lpeitem*/, std::vector & /*hp_vec*/) override {}; + void addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector & /*hp_vec*/) override{}; + + std::vector _vector; - std::vector _vector; - protected: - bool _updateLink(const Gtk::TreeIter& iter, ItemAndActive* pd); - bool _selectIndex(const Gtk::TreeIter& iter, int* i); - void unlink(ItemAndActive* to); - void remove_link(ItemAndActive* to); - void setItem(SPObject *linked_obj, guint flags, ItemAndActive* to); - - void linked_changed(SPObject *old_obj, SPObject *new_obj, ItemAndActive* to); - void linked_modified(SPObject *linked_obj, guint flags, ItemAndActive* to); - void linked_transformed(Geom::Affine const *, SPItem *, ItemAndActive*) {} - void linked_delete(SPObject *deleted, ItemAndActive* to); - + bool _updateLink(const Gtk::TreeIter &iter, ItemAndActive *pd); + bool _selectIndex(const Gtk::TreeIter &iter, int *i); + void unlink(ItemAndActive *to); + void remove_link(ItemAndActive *to); + void setItem(SPObject *linked_obj, guint flags, ItemAndActive *to); + + void linked_changed(SPObject *old_obj, SPObject *new_obj, ItemAndActive *to); + void linked_modified(SPObject *linked_obj, guint flags, ItemAndActive *to); + void linked_transformed(Geom::Affine const *, SPItem *, ItemAndActive *) {} + void linked_delete(SPObject *deleted, ItemAndActive *to); + ModelColumns *_model; Glib::RefPtr _store; Gtk::TreeView _tree; @@ -93,22 +88,22 @@ protected: Gtk::CellRendererToggle *_toggle_active; Gtk::TreeView::Column *_name_column; Gtk::ScrolledWindow _scroller; - + void on_link_button_click(); void on_remove_button_click(); void on_up_button_click(); void on_down_button_click(); - void on_active_toggled(const Glib::ustring& item); - + void on_active_toggled(const Glib::ustring &item); + private: void update(); - OriginalItemArrayParam(const OriginalItemArrayParam&); - OriginalItemArrayParam& operator=(const OriginalItemArrayParam&); + OriginalItemArrayParam(const OriginalItemArrayParam &); + OriginalItemArrayParam &operator=(const OriginalItemArrayParam &); }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/originalpath.cpp b/src/live_effects/parameter/originalpath.cpp index 4e65e1d3b9c8a4f32073ba0771152e8c65f5bdc7..7da460067d0fd29e1abd6c42e80c0bcfb793018c 100644 --- a/src/live_effects/parameter/originalpath.cpp +++ b/src/live_effects/parameter/originalpath.cpp @@ -5,22 +5,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "live_effects/parameter/originalpath.h" #include +#include #include #include +#include "desktop.h" #include "display/curve.h" +#include "inkscape.h" #include "live_effects/effect.h" - -#include "object/uri.h" #include "object/sp-shape.h" #include "object/sp-text.h" - -#include "inkscape.h" -#include "desktop.h" +#include "object/uri.h" #include "selection.h" #include "ui/icon-names.h" @@ -28,26 +26,23 @@ namespace Inkscape { namespace LivePathEffect { -OriginalPathParam::OriginalPathParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect) +OriginalPathParam::OriginalPathParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect) : PathParam(label, tip, key, wr, effect, "") { oncanvas_editable = false; _from_original_d = false; } -OriginalPathParam::~OriginalPathParam() -= default; +OriginalPathParam::~OriginalPathParam() = default; -Gtk::Widget * -OriginalPathParam::param_newWidget() +Gtk::Widget *OriginalPathParam::param_newWidget() { Gtk::HBox *_widget = Gtk::manage(new Gtk::HBox()); { // Label Gtk::Label *pLabel = Gtk::manage(new Gtk::Label(param_label)); - static_cast(_widget)->pack_start(*pLabel, true, true); + static_cast(_widget)->pack_start(*pLabel, true, true); pLabel->set_tooltip_text(param_tooltip); } @@ -60,7 +55,7 @@ OriginalPathParam::param_newWidget() pButton->add(*pIcon); pButton->show(); pButton->signal_clicked().connect(sigc::mem_fun(*this, &OriginalPathParam::on_link_button_click)); - static_cast(_widget)->pack_start(*pButton, true, true); + static_cast(_widget)->pack_start(*pButton, true, true); pButton->set_tooltip_text(_("Link to path in clipboard")); } @@ -73,17 +68,16 @@ OriginalPathParam::param_newWidget() pButton->add(*pIcon); pButton->show(); pButton->signal_clicked().connect(sigc::mem_fun(*this, &OriginalPathParam::on_select_original_button_click)); - static_cast(_widget)->pack_start(*pButton, true, true); + static_cast(_widget)->pack_start(*pButton, true, true); pButton->set_tooltip_text(_("Select original")); } - static_cast(_widget)->show_all_children(); + static_cast(_widget)->show_all_children(); - return dynamic_cast (_widget); + return dynamic_cast(_widget); } -void -OriginalPathParam::on_select_original_button_click() +void OriginalPathParam::on_select_original_button_click() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; SPItem *original = ref.getObject(); diff --git a/src/live_effects/parameter/originalpath.h b/src/live_effects/parameter/originalpath.h index bcf9050436316ec1367d0089b8712b8f9016e8aa..7993908429d2c101910a61aa757746ec40729658 100644 --- a/src/live_effects/parameter/originalpath.h +++ b/src/live_effects/parameter/originalpath.h @@ -16,34 +16,31 @@ namespace Inkscape { namespace LivePathEffect { -class OriginalPathParam: public PathParam { +class OriginalPathParam : public PathParam +{ public: - OriginalPathParam ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect); + OriginalPathParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect); ~OriginalPathParam() override; bool linksToPath() const { return (href != nullptr); } - SPItem * getObject() const { return ref.getObject(); } + SPItem *getObject() const { return ref.getObject(); } - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; /** Disable the canvas indicators of parent class by overriding this method */ - void param_editOncanvas(SPItem * /*item*/, SPDesktop * /*dt*/) override {}; + void param_editOncanvas(SPItem * /*item*/, SPDesktop * /*dt*/) override{}; /** Disable the canvas indicators of parent class by overriding this method */ - void addCanvasIndicators(SPLPEItem const* /*lpeitem*/, std::vector & /*hp_vec*/) override {}; + void addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector & /*hp_vec*/) override{}; protected: void on_select_original_button_click(); private: - OriginalPathParam(const OriginalPathParam&) = delete; - OriginalPathParam& operator=(const OriginalPathParam&) = delete; + OriginalPathParam(const OriginalPathParam &) = delete; + OriginalPathParam &operator=(const OriginalPathParam &) = delete; }; +} // namespace LivePathEffect -} //namespace LivePathEffect - -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/originalpatharray.cpp b/src/live_effects/parameter/originalpatharray.cpp index 14eecd28f84b4428d9a069ce57a121edfd690e07..f2024b2515332e606c2ff4810343be724558c436 100644 --- a/src/live_effects/parameter/originalpatharray.cpp +++ b/src/live_effects/parameter/originalpatharray.cpp @@ -6,40 +6,34 @@ */ #include "live_effects/parameter/originalpatharray.h" -#include "live_effects/lpe-spiro.h" -#include "live_effects/lpe-bspline.h" -#include "live_effects/lpeobject.h" -#include "live_effects/lpeobject-reference.h" -#include +#include <2geom/coord.h> +#include <2geom/point.h> +#include #include #include -#include #include +#include +#include -#include - -#include "inkscape.h" -#include "ui/clipboard.h" -#include "svg/svg.h" -#include "svg/stringstream.h" -#include "originalpath.h" #include "display/curve.h" - -#include <2geom/coord.h> -#include <2geom/point.h> - -#include "ui/icon-loader.h" - +#include "document-undo.h" +#include "document.h" +#include "inkscape.h" +#include "live_effects/effect.h" +#include "live_effects/lpe-bspline.h" +#include "live_effects/lpe-spiro.h" +#include "live_effects/lpeobject-reference.h" +#include "live_effects/lpeobject.h" #include "object/sp-shape.h" #include "object/sp-text.h" #include "object/uri.h" - -#include "live_effects/effect.h" - +#include "originalpath.h" +#include "svg/stringstream.h" +#include "svg/svg.h" +#include "ui/clipboard.h" +#include "ui/icon-loader.h" #include "verbs.h" -#include "document-undo.h" -#include "document.h" namespace Inkscape { @@ -48,7 +42,6 @@ namespace LivePathEffect { class OriginalPathArrayParam::ModelColumns : public Gtk::TreeModel::ColumnRecord { public: - ModelColumns() { add(_colObject); @@ -58,67 +51,62 @@ public: } ~ModelColumns() override = default; - Gtk::TreeModelColumn _colObject; + Gtk::TreeModelColumn _colObject; Gtk::TreeModelColumn _colLabel; Gtk::TreeModelColumn _colReverse; Gtk::TreeModelColumn _colVisible; }; -OriginalPathArrayParam::OriginalPathArrayParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect ) -: Parameter(label, tip, key, wr, effect), - _vector(), - _tree(), - _text_renderer(), - _toggle_reverse(), - _toggle_visible(), - _scroller() -{ +OriginalPathArrayParam::OriginalPathArrayParam(const Glib::ustring &label, const Glib::ustring &tip, + const Glib::ustring &key, Inkscape::UI::Widget::Registry *wr, + Effect *effect) + : Parameter(label, tip, key, wr, effect) + , _vector() + , _tree() + , _text_renderer() + , _toggle_reverse() + , _toggle_visible() + , _scroller() +{ _model = new ModelColumns(); _store = Gtk::TreeStore::create(*_model); _tree.set_model(_store); _tree.set_reorderable(true); - _tree.enable_model_drag_dest (Gdk::ACTION_MOVE); - - - Gtk::CellRendererToggle * _toggle_reverse = manage(new Gtk::CellRendererToggle()); + _tree.enable_model_drag_dest(Gdk::ACTION_MOVE); + + Gtk::CellRendererToggle *_toggle_reverse = manage(new Gtk::CellRendererToggle()); int reverseColNum = _tree.append_column(_("Reverse"), *_toggle_reverse) - 1; - Gtk::TreeViewColumn* col_reverse = _tree.get_column(reverseColNum); + Gtk::TreeViewColumn *col_reverse = _tree.get_column(reverseColNum); _toggle_reverse->set_activatable(true); _toggle_reverse->signal_toggled().connect(sigc::mem_fun(*this, &OriginalPathArrayParam::on_reverse_toggled)); col_reverse->add_attribute(_toggle_reverse->property_active(), _model->_colReverse); - - Gtk::CellRendererToggle * _toggle_visible = manage(new Gtk::CellRendererToggle()); + Gtk::CellRendererToggle *_toggle_visible = manage(new Gtk::CellRendererToggle()); int visibleColNum = _tree.append_column(_("Visible"), *_toggle_visible) - 1; - Gtk::TreeViewColumn* col_visible = _tree.get_column(visibleColNum); + Gtk::TreeViewColumn *col_visible = _tree.get_column(visibleColNum); _toggle_visible->set_activatable(true); _toggle_visible->signal_toggled().connect(sigc::mem_fun(*this, &OriginalPathArrayParam::on_visible_toggled)); col_visible->add_attribute(_toggle_visible->property_active(), _model->_colVisible); - + _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_expander_column(*_tree.get_column(nameColNum)); _tree.set_search_column(_model->_colLabel); - - //quick little hack -- newer versions of gtk gave the item zero space allotment + + // quick little hack -- newer versions of gtk gave the item zero space allotment _scroller.set_size_request(-1, 120); _scroller.add(_tree); - _scroller.set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC ); + _scroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); //_scroller.set_shadow_type(Gtk::SHADOW_IN); - + oncanvas_editable = true; _from_original_d = false; _allow_only_bspline_spiro = false; - } OriginalPathArrayParam::~OriginalPathArrayParam() @@ -132,45 +120,40 @@ OriginalPathArrayParam::~OriginalPathArrayParam() delete _model; } -void OriginalPathArrayParam::on_reverse_toggled(const Glib::ustring& path) +void OriginalPathArrayParam::on_reverse_toggled(const Glib::ustring &path) { Gtk::TreeModel::iterator iter = _store->get_iter(path); Gtk::TreeModel::Row row = *iter; PathAndDirectionAndVisible *w = row[_model->_colObject]; row[_model->_colReverse] = !row[_model->_colReverse]; w->reversed = row[_model->_colReverse]; - + param_write_to_repr(param_getSVGValue().c_str()); - DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Link path parameter to path")); + DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Link path parameter to path")); } -void OriginalPathArrayParam::on_visible_toggled(const Glib::ustring& path) +void OriginalPathArrayParam::on_visible_toggled(const Glib::ustring &path) { Gtk::TreeModel::iterator iter = _store->get_iter(path); Gtk::TreeModel::Row row = *iter; PathAndDirectionAndVisible *w = row[_model->_colObject]; row[_model->_colVisible] = !row[_model->_colVisible]; w->visibled = row[_model->_colVisible]; - + param_write_to_repr(param_getSVGValue().c_str()); DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Toggle path parameter visibility")); } -void OriginalPathArrayParam::param_set_default() -{ - -} +void OriginalPathArrayParam::param_set_default() {} -Gtk::Widget* OriginalPathArrayParam::param_newWidget() +Gtk::Widget *OriginalPathArrayParam::param_newWidget() { - Gtk::VBox* vbox = Gtk::manage(new Gtk::VBox()); - Gtk::HBox* hbox = Gtk::manage(new Gtk::HBox()); + Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox()); + Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox()); vbox->pack_start(_scroller, Gtk::PACK_EXPAND_WIDGET); - - + { // Paste path to link button Gtk::Image *pIcon = Gtk::manage(sp_get_icon_image("edit-clone", Gtk::ICON_SIZE_BUTTON)); Gtk::Button *pButton = Gtk::manage(new Gtk::Button()); @@ -182,7 +165,7 @@ Gtk::Widget* OriginalPathArrayParam::param_newWidget() hbox->pack_start(*pButton, Gtk::PACK_SHRINK); pButton->set_tooltip_text(_("Link to path in clipboard")); } - + { // Remove linked path Gtk::Image *pIcon = Gtk::manage(sp_get_icon_image("list-remove", Gtk::ICON_SIZE_BUTTON)); Gtk::Button *pButton = Gtk::manage(new Gtk::Button()); @@ -194,7 +177,7 @@ Gtk::Widget* OriginalPathArrayParam::param_newWidget() hbox->pack_start(*pButton, Gtk::PACK_SHRINK); pButton->set_tooltip_text(_("Remove Path")); } - + { // Move Down Gtk::Image *pIcon = Gtk::manage(sp_get_icon_image("go-down", Gtk::ICON_SIZE_BUTTON)); Gtk::Button *pButton = Gtk::manage(new Gtk::Button()); @@ -206,7 +189,7 @@ Gtk::Widget* OriginalPathArrayParam::param_newWidget() hbox->pack_end(*pButton, Gtk::PACK_SHRINK); pButton->set_tooltip_text(_("Move Down")); } - + { // Move Down Gtk::Image *pIcon = Gtk::manage(sp_get_icon_image("go-up", Gtk::ICON_SIZE_BUTTON)); Gtk::Button *pButton = Gtk::manage(new Gtk::Button()); @@ -218,15 +201,15 @@ Gtk::Widget* OriginalPathArrayParam::param_newWidget() hbox->pack_end(*pButton, Gtk::PACK_SHRINK); pButton->set_tooltip_text(_("Move Up")); } - + vbox->pack_end(*hbox, Gtk::PACK_SHRINK); - + vbox->show_all_children(true); - + return vbox; } -bool OriginalPathArrayParam::_selectIndex(const Gtk::TreeIter& iter, int* i) +bool OriginalPathArrayParam::_selectIndex(const Gtk::TreeIter &iter, int *i) { if ((*i)-- <= 0) { _tree.get_selection()->select(iter); @@ -240,23 +223,23 @@ void OriginalPathArrayParam::on_up_button_click() Gtk::TreeModel::iterator iter = _tree.get_selection()->get_selected(); if (iter) { Gtk::TreeModel::Row row = *iter; - + int i = -1; - std::vector::iterator piter = _vector.begin(); - for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); piter = iter, i++, ++iter) { + std::vector::iterator piter = _vector.begin(); + for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); + piter = iter, i++, ++iter) { if (*iter == row[_model->_colObject]) { _vector.erase(iter); _vector.insert(piter, row[_model->_colObject]); break; } } - + param_write_to_repr(param_getSVGValue().c_str()); - DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Move path up")); - - _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::_selectIndex), &i)); + DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Move path up")); + + _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::_selectIndex), &i)); } } @@ -267,9 +250,10 @@ void OriginalPathArrayParam::on_down_button_click() Gtk::TreeModel::Row row = *iter; int i = 0; - for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); i++, ++iter) { + for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); + i++, ++iter) { if (*iter == row[_model->_colObject]) { - std::vector::iterator niter = _vector.erase(iter); + std::vector::iterator niter = _vector.erase(iter); if (niter != _vector.end()) { ++niter; i++; @@ -278,13 +262,12 @@ void OriginalPathArrayParam::on_down_button_click() break; } } - + param_write_to_repr(param_getSVGValue().c_str()); - - DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Move path down")); - - _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::_selectIndex), &i)); + + DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Move path down")); + + _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::_selectIndex), &i)); } } @@ -294,17 +277,14 @@ void OriginalPathArrayParam::on_remove_button_click() if (iter) { Gtk::TreeModel::Row row = *iter; remove_link(row[_model->_colObject]); - + param_write_to_repr(param_getSVGValue().c_str()); - - DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Remove path")); + + DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Remove path")); } - } -void -OriginalPathArrayParam::on_link_button_click() +void OriginalPathArrayParam::on_link_button_click() { Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); std::vector pathsid = cm->getElementsOfType(SP_ACTIVE_DESKTOP, "svg:path"); @@ -339,7 +319,7 @@ OriginalPathArrayParam::on_link_button_click() _("Link patharray parameter to path")); } -void OriginalPathArrayParam::unlink(PathAndDirectionAndVisible* to) +void OriginalPathArrayParam::unlink(PathAndDirectionAndVisible *to) { to->linked_modified_connection.disconnect(); to->linked_delete_connection.disconnect(); @@ -351,10 +331,10 @@ void OriginalPathArrayParam::unlink(PathAndDirectionAndVisible* to) } } -void OriginalPathArrayParam::remove_link(PathAndDirectionAndVisible* to) +void OriginalPathArrayParam::remove_link(PathAndDirectionAndVisible *to) { unlink(to); - for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); ++iter) { + for (std::vector::iterator iter = _vector.begin(); iter != _vector.end(); ++iter) { if (*iter == to) { PathAndDirectionAndVisible *w = *iter; _vector.erase(iter); @@ -364,44 +344,49 @@ void OriginalPathArrayParam::remove_link(PathAndDirectionAndVisible* to) } } -void OriginalPathArrayParam::linked_delete(SPObject */*deleted*/, PathAndDirectionAndVisible* /*to*/) +void OriginalPathArrayParam::linked_delete(SPObject * /*deleted*/, PathAndDirectionAndVisible * /*to*/) { - //remove_link(to); + // remove_link(to); param_write_to_repr(param_getSVGValue().c_str()); } -bool OriginalPathArrayParam::_updateLink(const Gtk::TreeIter& iter, PathAndDirectionAndVisible* pd) +bool OriginalPathArrayParam::_updateLink(const Gtk::TreeIter &iter, PathAndDirectionAndVisible *pd) { Gtk::TreeModel::Row row = *iter; if (row[_model->_colObject] == pd) { SPObject *obj = pd->ref.getObject(); - row[_model->_colLabel] = obj && obj->getId() ? ( obj->label() ? obj->label() : obj->getId() ) : pd->href; + row[_model->_colLabel] = obj && obj->getId() ? (obj->label() ? obj->label() : obj->getId()) : pd->href; return true; } return false; } -void OriginalPathArrayParam::linked_changed(SPObject */*old_obj*/, SPObject *new_obj, PathAndDirectionAndVisible* to) +void OriginalPathArrayParam::linked_changed(SPObject * /*old_obj*/, SPObject *new_obj, PathAndDirectionAndVisible *to) { to->linked_delete_connection.disconnect(); to->linked_modified_connection.disconnect(); to->linked_transformed_connection.disconnect(); - + if (new_obj && SP_IS_ITEM(new_obj)) { - to->linked_delete_connection = new_obj->connectDelete(sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::linked_delete), to)); - to->linked_modified_connection = new_obj->connectModified(sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::linked_modified), to)); - to->linked_transformed_connection = SP_ITEM(new_obj)->connectTransformed(sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::linked_transformed), to)); + to->linked_delete_connection = new_obj->connectDelete( + sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::linked_delete), to)); + to->linked_modified_connection = new_obj->connectModified(sigc::bind( + sigc::mem_fun(*this, &OriginalPathArrayParam::linked_modified), to)); + to->linked_transformed_connection = + SP_ITEM(new_obj)->connectTransformed(sigc::bind( + sigc::mem_fun(*this, &OriginalPathArrayParam::linked_transformed), to)); linked_modified(new_obj, SP_OBJECT_MODIFIED_FLAG, to); } else { to->_pathvector = Geom::PathVector(); SP_OBJECT(param_effect->getLPEObj())->requestModified(SP_OBJECT_MODIFIED_FLAG); - _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::_updateLink), to)); + _store->foreach_iter( + sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::_updateLink), to)); } } -void OriginalPathArrayParam::setPathVector(SPObject *linked_obj, guint /*flags*/, PathAndDirectionAndVisible* to) +void OriginalPathArrayParam::setPathVector(SPObject *linked_obj, guint /*flags*/, PathAndDirectionAndVisible *to) { if (!to) { return; @@ -409,10 +394,10 @@ void OriginalPathArrayParam::setPathVector(SPObject *linked_obj, guint /*flags*/ std::unique_ptr curve; SPText *text = dynamic_cast(linked_obj); if (auto shape = dynamic_cast(linked_obj)) { - SPLPEItem * lpe_item = SP_LPE_ITEM(linked_obj); + SPLPEItem *lpe_item = SP_LPE_ITEM(linked_obj); if (_from_original_d) { curve = SPCurve::copy(shape->curveForEdit()); - } else if (_allow_only_bspline_spiro && lpe_item && lpe_item->hasPathEffect()){ + } else if (_allow_only_bspline_spiro && lpe_item && lpe_item->hasPathEffect()) { curve = SPCurve::copy(shape->curveForEdit()); PathEffectList lpelist = lpe_item->getEffectList(); PathEffectList::iterator i; @@ -455,20 +440,20 @@ void OriginalPathArrayParam::setPathVector(SPObject *linked_obj, guint /*flags*/ } else { to->_pathvector = curve->get_pathvector(); } - } -void OriginalPathArrayParam::linked_modified(SPObject *linked_obj, guint flags, PathAndDirectionAndVisible* to) +void OriginalPathArrayParam::linked_modified(SPObject *linked_obj, guint flags, PathAndDirectionAndVisible *to) { if (!to) { return; } setPathVector(linked_obj, flags, to); SP_OBJECT(param_effect->getLPEObj())->requestModified(SP_OBJECT_MODIFIED_FLAG); - _store->foreach_iter(sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::_updateLink), to)); + _store->foreach_iter( + sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::_updateLink), to)); } -bool OriginalPathArrayParam::param_readSVGValue(const gchar* strvalue) +bool OriginalPathArrayParam::param_readSVGValue(const gchar *strvalue) { if (strvalue) { while (!_vector.empty()) { @@ -479,16 +464,17 @@ bool OriginalPathArrayParam::param_readSVGValue(const gchar* strvalue) } _store->clear(); - gchar ** strarray = g_strsplit(strvalue, "|", 0); - for (gchar ** iter = strarray; *iter != nullptr; iter++) { + gchar **strarray = g_strsplit(strvalue, "|", 0); + for (gchar **iter = strarray; *iter != nullptr; iter++) { if ((*iter)[0] == '#') { - gchar ** substrarray = g_strsplit(*iter, ",", 0); - PathAndDirectionAndVisible* w = new PathAndDirectionAndVisible((SPObject *)param_effect->getLPEObj()); + gchar **substrarray = g_strsplit(*iter, ",", 0); + PathAndDirectionAndVisible *w = new PathAndDirectionAndVisible((SPObject *)param_effect->getLPEObj()); w->href = g_strdup(*substrarray); - w->reversed = *(substrarray+1) != nullptr && (*(substrarray+1))[0] == '1'; - //Like this to make backwards compatible, new value added in 0.93 - w->visibled = *(substrarray+2) == nullptr || (*(substrarray+2))[0] == '1'; - w->linked_changed_connection = w->ref.changedSignal().connect(sigc::bind(sigc::mem_fun(*this, &OriginalPathArrayParam::linked_changed), w)); + w->reversed = *(substrarray + 1) != nullptr && (*(substrarray + 1))[0] == '1'; + // Like this to make backwards compatible, new value added in 0.93 + w->visibled = *(substrarray + 2) == nullptr || (*(substrarray + 2))[0] == '1'; + w->linked_changed_connection = w->ref.changedSignal().connect(sigc::bind( + sigc::mem_fun(*this, &OriginalPathArrayParam::linked_changed), w)); w->ref.attach(URI(w->href)); _vector.push_back(w); @@ -498,20 +484,19 @@ bool OriginalPathArrayParam::param_readSVGValue(const gchar* strvalue) SPObject *obj = w->ref.getObject(); row[_model->_colObject] = w; - row[_model->_colLabel] = obj ? ( obj->label() ? obj->label() : obj->getId() ) : w->href; + row[_model->_colLabel] = obj ? (obj->label() ? obj->label() : obj->getId()) : w->href; row[_model->_colReverse] = w->reversed; row[_model->_colVisible] = w->visibled; - g_strfreev (substrarray); + g_strfreev(substrarray); } } - g_strfreev (strarray); + g_strfreev(strarray); return true; } return false; } -Glib::ustring -OriginalPathArrayParam::param_getSVGValue() const +Glib::ustring OriginalPathArrayParam::param_getSVGValue() const { Inkscape::SVGOStringStream os; bool foundOne = false; @@ -526,15 +511,14 @@ OriginalPathArrayParam::param_getSVGValue() const return os.str(); } -Glib::ustring -OriginalPathArrayParam::param_getDefaultSVGValue() const +Glib::ustring OriginalPathArrayParam::param_getDefaultSVGValue() const { return ""; } void OriginalPathArrayParam::update() { - for (auto & iter : _vector) { + for (auto &iter : _vector) { SPObject *linked_obj = iter->ref.getObject(); linked_modified(linked_obj, SP_OBJECT_MODIFIED_FLAG, iter); } diff --git a/src/live_effects/parameter/originalpatharray.h b/src/live_effects/parameter/originalpatharray.h index 6f58627bdced5bc65bcd163a863a208f1cf633fa..e441c0606b687e93001cf059725161890cc9f150 100644 --- a/src/live_effects/parameter/originalpatharray.h +++ b/src/live_effects/parameter/originalpatharray.h @@ -10,19 +10,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include - #include -#include -#include #include +#include +#include +#include #include "live_effects/parameter/parameter.h" #include "live_effects/parameter/path-reference.h" - -#include "svg/svg.h" -#include "svg/stringstream.h" #include "path-reference.h" +#include "svg/stringstream.h" +#include "svg/svg.h" class SPObject; @@ -30,68 +28,73 @@ namespace Inkscape { namespace LivePathEffect { -class PathAndDirectionAndVisible { +class PathAndDirectionAndVisible +{ public: PathAndDirectionAndVisible(SPObject *owner) - : href(nullptr), - ref(owner), - _pathvector(Geom::PathVector()), - reversed(false), - visibled(true) - { - - } + : href(nullptr) + , ref(owner) + , _pathvector(Geom::PathVector()) + , reversed(false) + , visibled(true) + {} gchar *href; URIReference ref; Geom::PathVector _pathvector; bool reversed; bool visibled; - + sigc::connection linked_changed_connection; sigc::connection linked_delete_connection; sigc::connection linked_modified_connection; sigc::connection linked_transformed_connection; }; - -class OriginalPathArrayParam : public Parameter { + +class OriginalPathArrayParam : public Parameter +{ public: class ModelColumns; - - OriginalPathArrayParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect); + + OriginalPathArrayParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect); ~OriginalPathArrayParam() override; - Gtk::Widget * param_newWidget() override; - bool param_readSVGValue(const gchar * strvalue) override; + Gtk::Widget *param_newWidget() override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; void param_set_default() override; - void param_update_default(const gchar * default_value) override{}; + void param_update_default(const gchar *default_value) override{}; /** Disable the canvas indicators of parent class by overriding this method */ - void param_editOncanvas(SPItem * /*item*/, SPDesktop * /*dt*/) override {}; + void param_editOncanvas(SPItem * /*item*/, SPDesktop * /*dt*/) override{}; /** Disable the canvas indicators of parent class by overriding this method */ - void addCanvasIndicators(SPLPEItem const* /*lpeitem*/, std::vector & /*hp_vec*/) override {}; - void setFromOriginalD(bool from_original_d){ _from_original_d = from_original_d; update();}; - void allowOnlyBsplineSpiro(bool allow_only_bspline_spiro){ _allow_only_bspline_spiro = allow_only_bspline_spiro; update();}; + void addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector & /*hp_vec*/) override{}; + void setFromOriginalD(bool from_original_d) + { + _from_original_d = from_original_d; + update(); + }; + void allowOnlyBsplineSpiro(bool allow_only_bspline_spiro) + { + _allow_only_bspline_spiro = allow_only_bspline_spiro; + update(); + }; - std::vector _vector; + std::vector _vector; protected: - bool _updateLink(const Gtk::TreeIter& iter, PathAndDirectionAndVisible* pd); - bool _selectIndex(const Gtk::TreeIter& iter, int* i); - void unlink(PathAndDirectionAndVisible* to); - void remove_link(PathAndDirectionAndVisible* to); - void setPathVector(SPObject *linked_obj, guint flags, PathAndDirectionAndVisible* to); - - void linked_changed(SPObject *old_obj, SPObject *new_obj, PathAndDirectionAndVisible* to); - void linked_modified(SPObject *linked_obj, guint flags, PathAndDirectionAndVisible* to); - void linked_transformed(Geom::Affine const *, SPItem *, PathAndDirectionAndVisible*) {} - void linked_delete(SPObject *deleted, PathAndDirectionAndVisible* to); - + bool _updateLink(const Gtk::TreeIter &iter, PathAndDirectionAndVisible *pd); + bool _selectIndex(const Gtk::TreeIter &iter, int *i); + void unlink(PathAndDirectionAndVisible *to); + void remove_link(PathAndDirectionAndVisible *to); + void setPathVector(SPObject *linked_obj, guint flags, PathAndDirectionAndVisible *to); + + void linked_changed(SPObject *old_obj, SPObject *new_obj, PathAndDirectionAndVisible *to); + void linked_modified(SPObject *linked_obj, guint flags, PathAndDirectionAndVisible *to); + void linked_transformed(Geom::Affine const *, SPItem *, PathAndDirectionAndVisible *) {} + void linked_delete(SPObject *deleted, PathAndDirectionAndVisible *to); + ModelColumns *_model; Glib::RefPtr _store; Gtk::TreeView _tree; @@ -100,25 +103,25 @@ protected: Gtk::CellRendererToggle *_toggle_visible; Gtk::TreeView::Column *_name_column; Gtk::ScrolledWindow _scroller; - + void on_link_button_click(); void on_remove_button_click(); void on_up_button_click(); void on_down_button_click(); - void on_reverse_toggled(const Glib::ustring& path); - void on_visible_toggled(const Glib::ustring& path); - + void on_reverse_toggled(const Glib::ustring &path); + void on_visible_toggled(const Glib::ustring &path); + private: bool _from_original_d; bool _allow_only_bspline_spiro; void update(); - OriginalPathArrayParam(const OriginalPathArrayParam&) = delete; - OriginalPathArrayParam& operator=(const OriginalPathArrayParam&) = delete; + OriginalPathArrayParam(const OriginalPathArrayParam &) = delete; + OriginalPathArrayParam &operator=(const OriginalPathArrayParam &) = delete; }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/parameter.cpp b/src/live_effects/parameter/parameter.cpp index 355e7dde7110fc8ad56b8e23b8c54d1e87af6557..29b5af9a955b49ad702cbae77ab381f3c65f3d52 100644 --- a/src/live_effects/parameter/parameter.cpp +++ b/src/live_effects/parameter/parameter.cpp @@ -5,27 +5,23 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "live_effects/parameter/parameter.h" -#include "live_effects/effect.h" -#include "svg/svg.h" -#include "xml/repr.h" - -#include "svg/stringstream.h" - -#include "verbs.h" #include - #include +#include "live_effects/effect.h" +#include "svg/stringstream.h" +#include "svg/svg.h" +#include "verbs.h" +#include "xml/repr.h" + #define noLPEREALPARAM_DEBUG namespace Inkscape { namespace LivePathEffect { - Parameter::Parameter(Glib::ustring label, Glib::ustring tip, Glib::ustring key, Inkscape::UI::Widget::Registry *wr, Effect *effect) : param_key(std::move(key)) @@ -36,8 +32,7 @@ Parameter::Parameter(Glib::ustring label, Glib::ustring tip, Glib::ustring key, , widget_is_enabled(true) , param_tooltip(std::move(tip)) , param_effect(effect) -{ -} +{} void Parameter::param_write_to_repr(const char *svgd) { @@ -65,8 +60,7 @@ ScalarParam::ScalarParam(const Glib::ustring &label, const Glib::ustring &tip, c , inc_page(1) , add_slider(false) , _set_undo(true) -{ -} +{} ScalarParam::~ScalarParam() = default; @@ -95,9 +89,15 @@ Glib::ustring ScalarParam::param_getDefaultSVGValue() const return os.str(); } -void ScalarParam::param_set_default() { param_set_value(defvalue); } +void ScalarParam::param_set_default() +{ + param_set_value(defvalue); +} -void ScalarParam::param_update_default(gdouble default_value) { defvalue = default_value; } +void ScalarParam::param_update_default(gdouble default_value) +{ + defvalue = default_value; +} void ScalarParam::param_update_default(const gchar *default_value) { @@ -158,7 +158,10 @@ void ScalarParam::param_make_integer(bool yes) inc_page = 10; } -void ScalarParam::param_set_undo(bool set_undo) { _set_undo = set_undo; } +void ScalarParam::param_set_undo(bool set_undo) +{ + _set_undo = set_undo; +} Gtk::Widget *ScalarParam::param_newWidget() { @@ -183,7 +186,10 @@ Gtk::Widget *ScalarParam::param_newWidget() } } -void ScalarParam::param_set_digits(unsigned digits) { this->digits = digits; } +void ScalarParam::param_set_digits(unsigned digits) +{ + this->digits = digits; +} void ScalarParam::param_set_increments(double step, double page) { @@ -191,8 +197,6 @@ void ScalarParam::param_set_increments(double step, double page) inc_page = page; } - - } /* namespace LivePathEffect */ } /* namespace Inkscape */ diff --git a/src/live_effects/parameter/parameter.h b/src/live_effects/parameter/parameter.h index b73a5fe830865f4b2aeadeab2bbcb6d08730254f..2dfe5ea2a8d31d608d4c59b8e927d5c5daa5abe9 100644 --- a/src/live_effects/parameter/parameter.h +++ b/src/live_effects/parameter/parameter.h @@ -10,11 +10,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/registered-widget.h" #include <2geom/forward.h> #include <2geom/pathvector.h> #include +#include "ui/widget/registered-widget.h" + // In gtk2, this wasn't an issue; we could toss around // G_MAXDOUBLE and not worry about size allocations. But // in gtk3, it is an issue: it allocates widget size for the maxmium @@ -48,8 +49,9 @@ namespace LivePathEffect { class Effect; -class Parameter { - public: +class Parameter +{ +public: Parameter(Glib::ustring label, Glib::ustring tip, Glib::ustring key, Inkscape::UI::Widget::Registry *wr, Effect *effect); virtual ~Parameter() = default; @@ -91,15 +93,15 @@ class Parameter { bool widget_is_visible; bool widget_is_enabled; - protected: +protected: Effect *param_effect; void param_write_to_repr(const char *svgd); }; - -class ScalarParam : public Parameter { - public: +class ScalarParam : public Parameter +{ +public: ScalarParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, Inkscape::UI::Widget::Registry *wr, Effect *effect, gdouble default_value = 1.0); ~ScalarParam() override; @@ -127,7 +129,7 @@ class ScalarParam : public Parameter { inline operator gdouble() const { return value; }; - protected: +protected: gdouble value; gdouble min; gdouble max; diff --git a/src/live_effects/parameter/path-reference.cpp b/src/live_effects/parameter/path-reference.cpp index c3ce3d5d32255633c8dab2351f068114bd6b2c62..220ac3c46552fad83747c5b26809cee4217ac5e4 100644 --- a/src/live_effects/parameter/path-reference.cpp +++ b/src/live_effects/parameter/path-reference.cpp @@ -15,7 +15,7 @@ namespace Inkscape { namespace LivePathEffect { -bool PathReference::_acceptObject(SPObject * const obj) const +bool PathReference::_acceptObject(SPObject *const obj) const { if (SP_IS_SHAPE(obj) || SP_IS_TEXT(obj)) { /* Refuse references to lpeobject */ diff --git a/src/live_effects/parameter/path-reference.h b/src/live_effects/parameter/path-reference.h index 0b33194906a78e4ddc066d4af54e89b7c220bf9b..efe04eb7da4ef0ff973a06dcf45e6ac6f3584553 100644 --- a/src/live_effects/parameter/path-reference.h +++ b/src/live_effects/parameter/path-reference.h @@ -14,35 +14,36 @@ class SPItem; namespace Inkscape { -namespace XML { class Node; } +namespace XML { +class Node; +} namespace LivePathEffect { /** * The reference corresponding to href of LPE PathParam. */ -class PathReference : public Inkscape::URIReference { +class PathReference : public Inkscape::URIReference +{ public: - PathReference(SPObject *owner) : URIReference(owner) {} + PathReference(SPObject *owner) + : URIReference(owner) + {} - SPItem *getObject() const { - return (SPItem *)URIReference::getObject(); - } + SPItem *getObject() const { return (SPItem *)URIReference::getObject(); } protected: - bool _acceptObject(SPObject * const obj) const override; + bool _acceptObject(SPObject *const obj) const override; private: - PathReference(const PathReference&) = delete; - PathReference& operator=(const PathReference&) = delete; + PathReference(const PathReference &) = delete; + PathReference &operator=(const PathReference &) = delete; }; } // namespace LivePathEffect } // namespace Inkscape - - #endif /* !SEEN_LPE_PATH_REFERENCE_H */ /* diff --git a/src/live_effects/parameter/path.cpp b/src/live_effects/parameter/path.cpp index 2c9a230cf253d430dfc5fef4d633773a5320a5b6..4e68079565345fb4e03b699539ad88704e91bb8e 100644 --- a/src/live_effects/parameter/path.cpp +++ b/src/live_effects/parameter/path.cpp @@ -7,101 +7,93 @@ */ #include "live_effects/parameter/path.h" -#include "live_effects/lpeobject.h" +#include <2geom/d2.h> +#include <2geom/pathvector.h> +#include <2geom/sbasis-to-bezier.h> +#include <2geom/svg-path-parser.h> #include #include - #include #include #include "bad-uri-exception.h" -#include "ui/widget/point.h" - -#include "live_effects/effect.h" -#include "svg/svg.h" -#include <2geom/svg-path-parser.h> -#include <2geom/sbasis-to-bezier.h> -#include <2geom/pathvector.h> -#include <2geom/d2.h> - #include "desktop.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" +#include "live_effects/effect.h" +#include "live_effects/lpeobject.h" #include "message-stack.h" #include "selection-chemistry.h" +#include "svg/svg.h" #include "ui/icon-loader.h" +#include "ui/widget/point.h" #include "verbs.h" #include "xml/repr.h" // needed for on-canvas editing: -#include "ui/tools-switch.h" -#include "ui/shape-editor.h" - #include "selection.h" +#include "ui/shape-editor.h" +#include "ui/tools-switch.h" // clipboard support #include "ui/clipboard.h" // required for linking to other paths -#include "object/uri.h" +#include "display/curve.h" #include "object/sp-shape.h" #include "object/sp-text.h" - -#include "display/curve.h" - -#include "ui/tools/node-tool.h" +#include "object/uri.h" +#include "ui/icon-names.h" #include "ui/tool/multi-path-manipulator.h" #include "ui/tool/shape-record.h" - -#include "ui/icon-names.h" +#include "ui/tools/node-tool.h" namespace Inkscape { namespace LivePathEffect { -PathParam::PathParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, const gchar * default_value) - : Parameter(label, tip, key, wr, effect), - changed(true), - _pathvector(), - _pwd2(), - must_recalculate_pwd2(false), - href(nullptr), - ref( (SPObject*)effect->getLPEObj() ) +PathParam::PathParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const gchar *default_value) + : Parameter(label, tip, key, wr, effect) + , changed(true) + , _pathvector() + , _pwd2() + , must_recalculate_pwd2(false) + , href(nullptr) + , ref((SPObject *)effect->getLPEObj()) { defvalue = g_strdup(default_value); param_readSVGValue(defvalue); oncanvas_editable = true; _from_original_d = false; - _edit_button = true; - _copy_button = true; + _edit_button = true; + _copy_button = true; _paste_button = true; - _link_button = true; + _link_button = true; ref_changed_connection = ref.changedSignal().connect(sigc::mem_fun(*this, &PathParam::ref_changed)); } PathParam::~PathParam() { remove_link(); -//TODO: Removed to fix a bug https://bugs.launchpad.net/inkscape/+bug/1716926 -// Maybe wee need to resurrect, not know when this code is added, but seems also not working now in a few test I do. -// in the future and do a deeper fix in multi-path-manipulator -// using namespace Inkscape::UI; -// SPDesktop *desktop = SP_ACTIVE_DESKTOP; -// if (desktop) { -// if (tools_isactive(desktop, TOOLS_NODES)) { -// SPItem * item = SP_ACTIVE_DESKTOP->getSelection()->singleItem(); -// if (item) { -// Inkscape::UI::Tools::NodeTool *nt = static_cast(desktop->event_context); -// std::set shapes; -// ShapeRecord r; -// r.item = item; -// shapes.insert(r); -// nt->_multipath->setItems(shapes); -// } -// } -// } + // TODO: Removed to fix a bug https://bugs.launchpad.net/inkscape/+bug/1716926 + // Maybe wee need to resurrect, not know when this code is added, but seems also not working now in a few test + // I do. in the future and do a deeper fix in multi-path-manipulator + // using namespace Inkscape::UI; + // SPDesktop *desktop = SP_ACTIVE_DESKTOP; + // if (desktop) { + // if (tools_isactive(desktop, TOOLS_NODES)) { + // SPItem * item = SP_ACTIVE_DESKTOP->getSelection()->singleItem(); + // if (item) { + // Inkscape::UI::Tools::NodeTool *nt = + // static_cast(desktop->event_context); std::set shapes; + // ShapeRecord r; + // r.item = item; + // shapes.insert(r); + // nt->_multipath->setItems(shapes); + // } + // } + // } SPDesktop *desktop = SP_ACTIVE_DESKTOP; if (desktop) { // TODO remove the tools_switch atrocity. @@ -113,33 +105,28 @@ PathParam::~PathParam() g_free(defvalue); } -Geom::PathVector const & -PathParam::get_pathvector() const +Geom::PathVector const &PathParam::get_pathvector() const { return _pathvector; } -Geom::Piecewise > const & -PathParam::get_pwd2() +Geom::Piecewise> const &PathParam::get_pwd2() { ensure_pwd2(); return _pwd2; } -void -PathParam::param_set_default() +void PathParam::param_set_default() { param_readSVGValue(defvalue); } -void -PathParam::param_set_and_write_default() +void PathParam::param_set_and_write_default() { param_write_to_repr(defvalue); } -bool -PathParam::param_readSVGValue(const gchar * strvalue) +bool PathParam::param_readSVGValue(const gchar *strvalue) { if (strvalue) { _pathvector.clear(); @@ -154,8 +141,8 @@ PathParam::param_readSVGValue(const gchar * strvalue) // Now do the attaching, which emits the changed signal. try { ref.attach(Inkscape::URI(href)); - //lp:1299948 - SPItem* i = ref.getObject(); + // lp:1299948 + SPItem *i = ref.getObject(); if (i) { linked_modified_callback(i, SP_OBJECT_MODIFIED_FLAG); } // else: document still processing new events. Repr of the linked object not created yet. @@ -175,42 +162,38 @@ PathParam::param_readSVGValue(const gchar * strvalue) return false; } -Glib::ustring -PathParam::param_getSVGValue() const +Glib::ustring PathParam::param_getSVGValue() const { if (href) { return href; } else { - gchar * svgd = sp_svg_write_path( _pathvector ); + gchar *svgd = sp_svg_write_path(_pathvector); return Glib::convert_return_gchar_ptr_to_ustring(svgd); } } -Glib::ustring -PathParam::param_getDefaultSVGValue() const +Glib::ustring PathParam::param_getDefaultSVGValue() const { return defvalue; } -void -PathParam::set_buttons(bool edit_button, bool copy_button, bool paste_button, bool link_button) +void PathParam::set_buttons(bool edit_button, bool copy_button, bool paste_button, bool link_button) { - _edit_button = edit_button; - _copy_button = copy_button; + _edit_button = edit_button; + _copy_button = copy_button; _paste_button = paste_button; - _link_button = link_button; + _link_button = link_button; } -Gtk::Widget * -PathParam::param_newWidget() +Gtk::Widget *PathParam::param_newWidget() { - Gtk::HBox * _widget = Gtk::manage(new Gtk::HBox()); + Gtk::HBox *_widget = Gtk::manage(new Gtk::HBox()); - Gtk::Label* pLabel = Gtk::manage(new Gtk::Label(param_label)); - static_cast(_widget)->pack_start(*pLabel, true, true); + Gtk::Label *pLabel = Gtk::manage(new Gtk::Label(param_label)); + static_cast(_widget)->pack_start(*pLabel, true, true); pLabel->set_tooltip_text(param_tooltip); - Gtk::Image * pIcon = nullptr; - Gtk::Button * pButton = nullptr; + Gtk::Image *pIcon = nullptr; + Gtk::Button *pButton = nullptr; if (_edit_button) { pIcon = Gtk::manage(sp_get_icon_image("tool-node-editor", Gtk::ICON_SIZE_BUTTON)); pButton = Gtk::manage(new Gtk::Button()); @@ -219,7 +202,7 @@ PathParam::param_newWidget() pButton->add(*pIcon); pButton->show(); pButton->signal_clicked().connect(sigc::mem_fun(*this, &PathParam::on_edit_button_click)); - static_cast(_widget)->pack_start(*pButton, true, true); + static_cast(_widget)->pack_start(*pButton, true, true); pButton->set_tooltip_text(_("Edit on-canvas")); } @@ -231,7 +214,7 @@ PathParam::param_newWidget() pButton->add(*pIcon); pButton->show(); pButton->signal_clicked().connect(sigc::mem_fun(*this, &PathParam::on_copy_button_click)); - static_cast(_widget)->pack_start(*pButton, true, true); + static_cast(_widget)->pack_start(*pButton, true, true); pButton->set_tooltip_text(_("Copy path")); } @@ -243,7 +226,7 @@ PathParam::param_newWidget() pButton->add(*pIcon); pButton->show(); pButton->signal_clicked().connect(sigc::mem_fun(*this, &PathParam::on_paste_button_click)); - static_cast(_widget)->pack_start(*pButton, true, true); + static_cast(_widget)->pack_start(*pButton, true, true); pButton->set_tooltip_text(_("Paste path")); } if (_link_button) { @@ -254,17 +237,16 @@ PathParam::param_newWidget() pButton->add(*pIcon); pButton->show(); pButton->signal_clicked().connect(sigc::mem_fun(*this, &PathParam::on_link_button_click)); - static_cast(_widget)->pack_start(*pButton, true, true); + static_cast(_widget)->pack_start(*pButton, true, true); pButton->set_tooltip_text(_("Link to path in clipboard")); } - static_cast(_widget)->show_all_children(); + static_cast(_widget)->show_all_children(); - return dynamic_cast (_widget); + return dynamic_cast(_widget); } -void -PathParam::param_editOncanvas(SPItem *item, SPDesktop * dt) +void PathParam::param_editOncanvas(SPItem *item, SPDesktop *dt) { SPDocument *document = dt->getDocument(); bool saved = DocumentUndo::getUndoSensitive(document); @@ -276,7 +258,7 @@ PathParam::param_editOncanvas(SPItem *item, SPDesktop * dt) tools_switch(dt, TOOLS_NODES); } - Inkscape::UI::Tools::NodeTool *nt = static_cast(dt->event_context); + Inkscape::UI::Tools::NodeTool *nt = static_cast(dt->event_context); std::set shapes; ShapeRecord r; @@ -285,7 +267,7 @@ PathParam::param_editOncanvas(SPItem *item, SPDesktop * dt) if (!href) { r.object = dynamic_cast(param_effect->getLPEObj()); r.lpe_key = param_key; - Geom::PathVector stored_pv = _pathvector; + Geom::PathVector stored_pv = _pathvector; if (_pathvector.empty()) { param_write_to_repr("M0,0 L1,0"); } else { @@ -301,14 +283,12 @@ PathParam::param_editOncanvas(SPItem *item, SPDesktop * dt) DocumentUndo::setUndoSensitive(document, saved); } -void -PathParam::param_setup_nodepath(Inkscape::NodePath::Path *) +void PathParam::param_setup_nodepath(Inkscape::NodePath::Path *) { // TODO this method should not exist at all! } -void -PathParam::addCanvasIndicators(SPLPEItem const*/*lpeitem*/, std::vector &hp_vec) +void PathParam::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { hp_vec.push_back(_pathvector); } @@ -316,26 +296,24 @@ PathParam::addCanvasIndicators(SPLPEItem const*/*lpeitem*/, std::vector > const & newpath, bool write_to_svg) +void PathParam::set_new_value(Geom::Piecewise> const &newpath, bool write_to_svg) { remove_link(); _pathvector = Geom::path_from_piecewise(newpath, LPE_CONVERSION_TOLERANCE); if (write_to_svg) { - gchar * svgd = sp_svg_write_path( _pathvector ); + gchar *svgd = sp_svg_write_path(_pathvector); param_write_to_repr(svgd); g_free(svgd); @@ -361,8 +339,7 @@ PathParam::set_new_value (Geom::Piecewise > const & newpa * If write_to_svg = false : * The new path data is not written to SVG. This method will emit the signal_path_changed signal. */ -void -PathParam::set_new_value (Geom::PathVector const &newpath, bool write_to_svg) +void PathParam::set_new_value(Geom::PathVector const &newpath, bool write_to_svg) { remove_link(); if (newpath.empty()) { @@ -374,7 +351,7 @@ PathParam::set_new_value (Geom::PathVector const &newpath, bool write_to_svg) must_recalculate_pwd2 = true; if (write_to_svg) { - gchar * svgd = sp_svg_write_path( _pathvector ); + gchar *svgd = sp_svg_write_path(_pathvector); param_write_to_repr(svgd); g_free(svgd); } else { @@ -382,59 +359,54 @@ PathParam::set_new_value (Geom::PathVector const &newpath, bool write_to_svg) } } -void -PathParam::ensure_pwd2() +void PathParam::ensure_pwd2() { if (must_recalculate_pwd2) { _pwd2.clear(); - for (const auto & i : _pathvector) { - _pwd2.concat( i.toPwSb() ); + for (const auto &i : _pathvector) { + _pwd2.concat(i.toPwSb()); } must_recalculate_pwd2 = false; } } -void -PathParam::emit_changed() +void PathParam::emit_changed() { changed = true; signal_path_changed.emit(); } -void -PathParam::start_listening(SPObject * to) +void PathParam::start_listening(SPObject *to) { - if ( to == nullptr ) { + if (to == nullptr) { return; } linked_delete_connection = to->connectDelete(sigc::mem_fun(*this, &PathParam::linked_delete)); linked_modified_connection = to->connectModified(sigc::mem_fun(*this, &PathParam::linked_modified)); if (SP_IS_ITEM(to)) { - linked_transformed_connection = SP_ITEM(to)->connectTransformed(sigc::mem_fun(*this, &PathParam::linked_transformed)); + linked_transformed_connection = + SP_ITEM(to)->connectTransformed(sigc::mem_fun(*this, &PathParam::linked_transformed)); } linked_modified(to, SP_OBJECT_MODIFIED_FLAG); // simulate linked_modified signal, so that path data is updated } -void -PathParam::quit_listening() +void PathParam::quit_listening() { linked_modified_connection.disconnect(); linked_delete_connection.disconnect(); linked_transformed_connection.disconnect(); } -void -PathParam::ref_changed(SPObject */*old_ref*/, SPObject *new_ref) +void PathParam::ref_changed(SPObject * /*old_ref*/, SPObject *new_ref) { quit_listening(); - if ( new_ref ) { + if (new_ref) { start_listening(new_ref); } } -void -PathParam::remove_link() +void PathParam::remove_link() { if (href) { ref.detach(); @@ -443,12 +415,11 @@ PathParam::remove_link() } } -void -PathParam::linked_delete(SPObject */*deleted*/) +void PathParam::linked_delete(SPObject * /*deleted*/) { quit_listening(); remove_link(); - set_new_value (_pathvector, true); + set_new_value(_pathvector, true); } void PathParam::linked_modified(SPObject *linked_obj, guint flags) @@ -461,8 +432,7 @@ void PathParam::linked_transformed(Geom::Affine const *rel_transf, SPItem *moved linked_transformed_callback(rel_transf, moved_item); } -void -PathParam::linked_modified_callback(SPObject *linked_obj, guint /*flags*/) +void PathParam::linked_modified_callback(SPObject *linked_obj, guint /*flags*/) { std::unique_ptr curve; if (auto shape = dynamic_cast(linked_obj)) { @@ -504,32 +474,30 @@ PathParam::linked_modified_callback(SPObject *linked_obj, guint /*flags*/) SP_OBJECT(param_effect->getLPEObj())->requestModified(SP_OBJECT_MODIFIED_FLAG); } -void -PathParam::param_update_default(const gchar * default_value){ +void PathParam::param_update_default(const gchar *default_value) +{ defvalue = strdup(default_value); } /* CALLBACK FUNCTIONS FOR THE BUTTONS */ -void -PathParam::on_edit_button_click() +void PathParam::on_edit_button_click() { - SPItem * item = SP_ACTIVE_DESKTOP->getSelection()->singleItem(); + SPItem *item = SP_ACTIVE_DESKTOP->getSelection()->singleItem(); if (item != nullptr) { param_editOncanvas(item, SP_ACTIVE_DESKTOP); } } -void -PathParam::paste_param_path(const char *svgd) +void PathParam::paste_param_path(const char *svgd) { // only recognize a non-null, non-empty string if (svgd && *svgd) { // remove possible link to path remove_link(); - SPItem * item = SP_ACTIVE_DESKTOP->getSelection()->singleItem(); + SPItem *item = SP_ACTIVE_DESKTOP->getSelection()->singleItem(); char *svgd_new = nullptr; if (item != nullptr) { - Geom::PathVector path_clipboard = sp_svg_read_pathv(svgd); + Geom::PathVector path_clipboard = sp_svg_read_pathv(svgd); path_clipboard *= item->i2doc_affine().inverse(); svgd_new = sp_svg_write_path(path_clipboard); svgd = svgd_new; @@ -541,25 +509,21 @@ PathParam::paste_param_path(const char *svgd) } } -void -PathParam::on_paste_button_click() +void PathParam::on_paste_button_click() { Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); Glib::ustring svgd = cm->getPathParameter(SP_ACTIVE_DESKTOP); paste_param_path(svgd.data()); - DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Paste path parameter")); + DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Paste path parameter")); } -void -PathParam::on_copy_button_click() +void PathParam::on_copy_button_click() { Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); cm->copyPathParameter(this); } -void -PathParam::linkitem(Glib::ustring pathid) +void PathParam::linkitem(Glib::ustring pathid) { if (pathid.empty()) { return; @@ -567,7 +531,7 @@ PathParam::linkitem(Glib::ustring pathid) // add '#' at start to make it an uri. pathid.insert(pathid.begin(), '#'); - if ( href && strcmp(pathid.c_str(), href) == 0 ) { + if (href && strcmp(pathid.c_str(), href) == 0) { // no change, do nothing return; } else { @@ -576,13 +540,11 @@ PathParam::linkitem(Glib::ustring pathid) // check if linking to object to which LPE is applied (maybe delegated to PathReference param_write_to_repr(pathid.c_str()); - DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Link path parameter to path")); + DocumentUndo::done(param_effect->getSPDoc(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Link path parameter to path")); } } -void -PathParam::on_link_button_click() +void PathParam::on_link_button_click() { Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); Glib::ustring pathid = cm->getShapeOrTextObjectId(SP_ACTIVE_DESKTOP); diff --git a/src/live_effects/parameter/path.h b/src/live_effects/parameter/path.h index 381aa25447dcdeda8b3c39d692cd19c6d4289636..7005e50ab3127b555f7661010be6dbd38d51bc11 100644 --- a/src/live_effects/parameter/path.h +++ b/src/live_effects/parameter/path.h @@ -10,67 +10,64 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include <2geom/path.h> +#include +#include +#include #include "live_effects/parameter/parameter.h" #include "live_effects/parameter/path-reference.h" -#include -#include namespace Inkscape { namespace LivePathEffect { -class PathParam : public Parameter { +class PathParam : public Parameter +{ public: - PathParam ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - const gchar * default_value = "M0,0 L1,1"); + PathParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const gchar *default_value = "M0,0 L1,1"); ~PathParam() override; - Geom::PathVector const & get_pathvector() const; - Geom::Piecewise > const & get_pwd2(); + Geom::PathVector const &get_pathvector() const; + Geom::Piecewise> const &get_pwd2(); - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; - bool param_readSVGValue(const gchar * strvalue) override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; void param_set_default() override; - void param_update_default(const gchar * default_value) override; + void param_update_default(const gchar *default_value) override; void param_set_and_write_default(); - void set_new_value (Geom::PathVector const &newpath, bool write_to_svg); - void set_new_value (Geom::Piecewise > const &newpath, bool write_to_svg); + void set_new_value(Geom::PathVector const &newpath, bool write_to_svg); + void set_new_value(Geom::Piecewise> const &newpath, bool write_to_svg); void set_buttons(bool edit_button, bool copy_button, bool paste_button, bool link_button); - void param_editOncanvas(SPItem * item, SPDesktop * dt) override; + void param_editOncanvas(SPItem *item, SPDesktop *dt) override; void param_setup_nodepath(Inkscape::NodePath::Path *np) override; - void addCanvasIndicators(SPLPEItem const* lpeitem, std::vector &hp_vec) override; + void addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec) override; void param_transform_multiply(Geom::Affine const &postmul, bool set) override; - void setFromOriginalD(bool from_original_d){ _from_original_d = from_original_d; }; + void setFromOriginalD(bool from_original_d) { _from_original_d = from_original_d; }; - sigc::signal signal_path_pasted; - sigc::signal signal_path_changed; - bool changed; /* this gets set whenever the path is changed (this is set to true, and then the signal_path_changed signal is emitted). - * the user must set it back to false if she wants to use it sensibly */ + sigc::signal signal_path_pasted; + sigc::signal signal_path_changed; + bool changed; /* this gets set whenever the path is changed (this is set to true, and then the signal_path_changed + * signal is emitted). the user must set it back to false if she wants to use it sensibly */ void paste_param_path(const char *svgd); void on_paste_button_click(); void linkitem(Glib::ustring pathid); protected: - Geom::PathVector _pathvector; // this is primary data storage, since it is closest to SVG. + Geom::PathVector _pathvector; // this is primary data storage, since it is closest to SVG. - Geom::Piecewise > _pwd2; // secondary, hence the bool must_recalculate_pwd2 - bool must_recalculate_pwd2; // set when _pathvector was updated, but _pwd2 not - void ensure_pwd2(); // ensures _pwd2 is up to date + Geom::Piecewise> _pwd2; // secondary, hence the bool must_recalculate_pwd2 + bool must_recalculate_pwd2; // set when _pathvector was updated, but _pwd2 not + void ensure_pwd2(); // ensures _pwd2 is up to date - gchar * href; // contains link to other object, e.g. "#path2428", NULL if PathParam contains pathdata itself + gchar *href; // contains link to other object, e.g. "#path2428", NULL if PathParam contains pathdata itself PathReference ref; sigc::connection ref_changed_connection; sigc::connection linked_delete_connection; @@ -78,13 +75,13 @@ protected: sigc::connection linked_transformed_connection; void ref_changed(SPObject *old_ref, SPObject *new_ref); void remove_link(); - void start_listening(SPObject * to); + void start_listening(SPObject *to); void quit_listening(); void linked_delete(SPObject *deleted); void linked_modified(SPObject *linked_obj, guint flags); void linked_transformed(Geom::Affine const *rel_transf, SPItem *moved_item); virtual void linked_modified_callback(SPObject *linked_obj, guint flags); - virtual void linked_transformed_callback(Geom::Affine const * /*rel_transf*/, SPItem * /*moved_item*/) {}; + virtual void linked_transformed_callback(Geom::Affine const * /*rel_transf*/, SPItem * /*moved_item*/){}; void on_edit_button_click(); void on_copy_button_click(); @@ -92,20 +89,20 @@ protected: void emit_changed(); - gchar * defvalue; + gchar *defvalue; bool _from_original_d; + private: bool _edit_button; bool _copy_button; bool _paste_button; bool _link_button; - PathParam(const PathParam&) = delete; - PathParam& operator=(const PathParam&) = delete; + PathParam(const PathParam &) = delete; + PathParam &operator=(const PathParam &) = delete; }; +} // namespace LivePathEffect -} //namespace LivePathEffect - -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/point.cpp b/src/live_effects/parameter/point.cpp index 8f627a952b8532b6e4ee2071953a948ead72de1e..bd45c378542268e42ff4aa5a3fc61cf799b28467 100644 --- a/src/live_effects/parameter/point.cpp +++ b/src/live_effects/parameter/point.cpp @@ -6,30 +6,31 @@ */ #include "live_effects/parameter/point.h" + +#include + +#include "inkscape.h" +#include "knotholder.h" #include "live_effects/effect.h" -#include "svg/svg.h" #include "svg/stringstream.h" +#include "svg/svg.h" #include "ui/widget/point.h" -#include "inkscape.h" #include "verbs.h" -#include "knotholder.h" -#include namespace Inkscape { namespace LivePathEffect { -PointParam::PointParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, const gchar *htip, Geom::Point default_value, - bool live_update ) - : Parameter(label, tip, key, wr, effect), - defvalue(default_value), - liveupdate(live_update), - _knot_entity(nullptr) +PointParam::PointParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const gchar *htip, Geom::Point default_value, + bool live_update) + : Parameter(label, tip, key, wr, effect) + , defvalue(default_value) + , liveupdate(live_update) + , _knot_entity(nullptr) { knot_shape = SP_KNOT_SHAPE_DIAMOND; - knot_mode = SP_KNOT_MODE_XOR; + knot_mode = SP_KNOT_MODE_XOR; knot_color = 0xffffff00; handle_tip = g_strdup(htip); } @@ -40,50 +41,46 @@ PointParam::~PointParam() g_free(handle_tip); } -void -PointParam::param_set_default() +void PointParam::param_set_default() { - param_setValue(defvalue,true); + param_setValue(defvalue, true); } -void -PointParam::param_set_liveupdate( bool live_update) +void PointParam::param_set_liveupdate(bool live_update) { liveupdate = live_update; } -Geom::Point -PointParam::param_get_default() const{ +Geom::Point PointParam::param_get_default() const +{ return defvalue; } -void -PointParam::param_update_default(Geom::Point default_point) +void PointParam::param_update_default(Geom::Point default_point) { defvalue = default_point; } -void -PointParam::param_update_default(const gchar * default_point) +void PointParam::param_update_default(const gchar *default_point) { - gchar ** strarray = g_strsplit(default_point, ",", 2); + gchar **strarray = g_strsplit(default_point, ",", 2); double newx, newy; unsigned int success = sp_svg_number_read_d(strarray[0], &newx); success += sp_svg_number_read_d(strarray[1], &newy); - g_strfreev (strarray); + g_strfreev(strarray); if (success == 2) { - param_update_default( Geom::Point(newx, newy) ); + param_update_default(Geom::Point(newx, newy)); } } -void -PointParam::param_hide_knot(bool hide) { +void PointParam::param_hide_knot(bool hide) +{ if (_knot_entity) { bool update = false; if (hide && _knot_entity->knot->flags & SP_KNOT_VISIBLE) { update = true; _knot_entity->knot->hide(); - } else if(!hide && !(_knot_entity->knot->flags & SP_KNOT_VISIBLE)) { + } else if (!hide && !(_knot_entity->knot->flags & SP_KNOT_VISIBLE)) { update = true; _knot_entity->knot->show(); } @@ -93,99 +90,90 @@ PointParam::param_hide_knot(bool hide) { } } -void -PointParam::param_setValue(Geom::Point newpoint, bool write) +void PointParam::param_setValue(Geom::Point newpoint, bool write) { - *dynamic_cast( this ) = newpoint; - if(write){ + *dynamic_cast(this) = newpoint; + if (write) { Inkscape::SVGOStringStream os; os << newpoint; - gchar * str = g_strdup(os.str().c_str()); + gchar *str = g_strdup(os.str().c_str()); param_write_to_repr(str); g_free(str); } - if(_knot_entity && liveupdate){ + if (_knot_entity && liveupdate) { _knot_entity->update_knot(); } } -bool -PointParam::param_readSVGValue(const gchar * strvalue) +bool PointParam::param_readSVGValue(const gchar *strvalue) { - gchar ** strarray = g_strsplit(strvalue, ",", 2); + gchar **strarray = g_strsplit(strvalue, ",", 2); double newx, newy; unsigned int success = sp_svg_number_read_d(strarray[0], &newx); success += sp_svg_number_read_d(strarray[1], &newy); - g_strfreev (strarray); + g_strfreev(strarray); if (success == 2) { - param_setValue( Geom::Point(newx, newy) ); + param_setValue(Geom::Point(newx, newy)); return true; } return false; } -Glib::ustring -PointParam::param_getSVGValue() const +Glib::ustring PointParam::param_getSVGValue() const { Inkscape::SVGOStringStream os; - os << *dynamic_cast( this ); + os << *dynamic_cast(this); return os.str(); } -Glib::ustring -PointParam::param_getDefaultSVGValue() const +Glib::ustring PointParam::param_getDefaultSVGValue() const { Inkscape::SVGOStringStream os; os << defvalue; return os.str(); } -void -PointParam::param_transform_multiply(Geom::Affine const& postmul, bool /*set*/) +void PointParam::param_transform_multiply(Geom::Affine const &postmul, bool /*set*/) { - param_setValue( (*this) * postmul, true); + param_setValue((*this) * postmul, true); } -Gtk::Widget * -PointParam::param_newWidget() +Gtk::Widget *PointParam::param_newWidget() { - Inkscape::UI::Widget::RegisteredTransformedPoint * pointwdg = Gtk::manage( - new Inkscape::UI::Widget::RegisteredTransformedPoint( param_label, - param_tooltip, - param_key, - *param_wr, - param_effect->getRepr(), - param_effect->getSPDoc() ) ); + Inkscape::UI::Widget::RegisteredTransformedPoint *pointwdg = + Gtk::manage(new Inkscape::UI::Widget::RegisteredTransformedPoint( + param_label, param_tooltip, param_key, *param_wr, param_effect->getRepr(), param_effect->getSPDoc())); Geom::Affine transf = SP_ACTIVE_DESKTOP->doc2dt(); pointwdg->setTransform(transf); - pointwdg->setValue( *this ); + pointwdg->setValue(*this); pointwdg->clearProgrammatically(); pointwdg->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change point parameter")); - pointwdg->signal_button_release_event().connect(sigc::mem_fun (*this, &PointParam::on_button_release)); + pointwdg->signal_button_release_event().connect(sigc::mem_fun(*this, &PointParam::on_button_release)); - Gtk::HBox * hbox = Gtk::manage( new Gtk::HBox() ); - static_cast(hbox)->pack_start(*pointwdg, true, true); - static_cast(hbox)->show_all_children(); - return dynamic_cast (hbox); + Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox()); + static_cast(hbox)->pack_start(*pointwdg, true, true); + static_cast(hbox)->show_all_children(); + return dynamic_cast(hbox); } -bool PointParam::on_button_release(GdkEventButton* button_event) { +bool PointParam::on_button_release(GdkEventButton *button_event) +{ param_effect->refresh_widgets = true; return false; } -void -PointParam::set_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color) +void PointParam::set_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color) { knot_shape = shape; - knot_mode = mode; + knot_mode = mode; knot_color = color; } -class PointParamKnotHolderEntity : public KnotHolderEntity { +class PointParamKnotHolderEntity : public KnotHolderEntity +{ public: PointParamKnotHolderEntity(PointParam *p) { this->pparam = p; } - ~PointParamKnotHolderEntity() override { this->pparam->_knot_entity = nullptr;} + ~PointParamKnotHolderEntity() override { this->pparam->_knot_entity = nullptr; } void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; @@ -196,54 +184,49 @@ private: PointParam *pparam; }; -void -PointParamKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) +void PointParamKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) { Geom::Point s = snap_knot_position(p, state); if (state & GDK_CONTROL_MASK) { - Geom::Point A(origin[Geom::X],p[Geom::Y]); - Geom::Point B(p[Geom::X],origin[Geom::Y]); - double distanceA = Geom::distance(A,p); - double distanceB = Geom::distance(B,p); - if(distanceA > distanceB){ + Geom::Point A(origin[Geom::X], p[Geom::Y]); + Geom::Point B(p[Geom::X], origin[Geom::Y]); + double distanceA = Geom::distance(A, p); + double distanceB = Geom::distance(B, p); + if (distanceA > distanceB) { s = B; } else { s = A; } } - if(this->pparam->liveupdate){ + if (this->pparam->liveupdate) { pparam->param_setValue(s, true); } else { pparam->param_setValue(s); } } -void -PointParamKnotHolderEntity::knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) +void PointParamKnotHolderEntity::knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) { pparam->param_effect->refresh_widgets = true; pparam->write_to_SVG(); } -Geom::Point -PointParamKnotHolderEntity::knot_get() const +Geom::Point PointParamKnotHolderEntity::knot_get() const { return *pparam; } -void -PointParamKnotHolderEntity::knot_click(guint state) +void PointParamKnotHolderEntity::knot_click(guint state) { if (state & GDK_CONTROL_MASK) { if (state & GDK_MOD1_MASK) { this->pparam->param_set_default(); - pparam->param_setValue(*pparam,true); + pparam->param_setValue(*pparam, true); } } } -void -PointParam::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) +void PointParam::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) { _knot_entity = new PointParamKnotHolderEntity(this); // TODO: can we ditch handleTip() etc. because we have access to handle_tip etc. itself??? diff --git a/src/live_effects/parameter/point.h b/src/live_effects/parameter/point.h index 26e0e32c81fe889844801049d3cbc622cd2994fb..a775fc467f604fc63a9ce62644560e2929fb8126 100644 --- a/src/live_effects/parameter/point.h +++ b/src/live_effects/parameter/point.h @@ -10,12 +10,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include <2geom/point.h> -#include "ui/widget/registered-widget.h" -#include "live_effects/parameter/parameter.h" +#include #include "knot-holder-entity.h" +#include "live_effects/parameter/parameter.h" +#include "ui/widget/registered-widget.h" namespace Inkscape { @@ -23,21 +23,20 @@ namespace LivePathEffect { class PointParamKnotHolderEntity; -class PointParam : public Geom::Point, public Parameter { +class PointParam + : public Geom::Point + , public Parameter +{ public: - PointParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - const gchar *handle_tip = nullptr,// tip for automatically associated on-canvas handle - Geom::Point default_value = Geom::Point(0,0), - bool live_update = true ); + PointParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, + const gchar *handle_tip = nullptr, // tip for automatically associated on-canvas handle + Geom::Point default_value = Geom::Point(0, 0), bool live_update = true); ~PointParam() override; - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; - bool param_readSVGValue(const gchar * strvalue) override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; inline const gchar *handleTip() const { return handle_tip ? handle_tip : param_tooltip.c_str(); } @@ -48,7 +47,7 @@ public: void param_set_liveupdate(bool live_update); void param_update_default(Geom::Point default_point); - void param_update_default(const gchar * default_point) override; + void param_update_default(const gchar *default_point) override; void param_transform_multiply(Geom::Affine const & /*postmul*/, bool set) override; void set_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color); @@ -56,22 +55,22 @@ public: bool providesKnotHolderEntities() const override { return true; } void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) override; friend class PointParamKnotHolderEntity; + private: - PointParam(const PointParam&) = delete; - PointParam& operator=(const PointParam&) = delete; - bool on_button_release(GdkEventButton* button_event); + PointParam(const PointParam &) = delete; + PointParam &operator=(const PointParam &) = delete; + bool on_button_release(GdkEventButton *button_event); Geom::Point defvalue; bool liveupdate; - KnotHolderEntity * _knot_entity; + KnotHolderEntity *_knot_entity; SPKnotShapeType knot_shape; SPKnotModeType knot_mode; guint32 knot_color; gchar *handle_tip; }; +} // namespace LivePathEffect -} //namespace LivePathEffect - -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/powerstrokepointarray.cpp b/src/live_effects/parameter/powerstrokepointarray.cpp index eaf0a1268a8df96bd9219696d7c0918f9582fbdb..40f8f84c2ca2b435476857ce47bc17d4314f1186 100644 --- a/src/live_effects/parameter/powerstrokepointarray.cpp +++ b/src/live_effects/parameter/powerstrokepointarray.cpp @@ -5,42 +5,37 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/dialog/lpe-powerstroke-properties.h" #include "live_effects/parameter/powerstrokepointarray.h" -#include "knotholder.h" -#include "live_effects/effect.h" -#include "live_effects/lpe-powerstroke.h" -#include <2geom/sbasis-2d.h> #include <2geom/bezier-to-sbasis.h> - - #include <2geom/piecewise.h> +#include <2geom/sbasis-2d.h> #include <2geom/sbasis-geometric.h> +#include +#include "knotholder.h" +#include "live_effects/effect.h" +#include "live_effects/lpe-powerstroke.h" #include "preferences.h" // for proportional stroke/path scaling behavior - -#include +#include "ui/dialog/lpe-powerstroke-properties.h" namespace Inkscape { namespace LivePathEffect { -PowerStrokePointArrayParam::PowerStrokePointArrayParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect) +PowerStrokePointArrayParam::PowerStrokePointArrayParam(const Glib::ustring &label, const Glib::ustring &tip, + const Glib::ustring &key, Inkscape::UI::Widget::Registry *wr, + Effect *effect) : ArrayParam(label, tip, key, wr, effect, 0) { knot_shape = SP_KNOT_SHAPE_DIAMOND; - knot_mode = SP_KNOT_MODE_XOR; + knot_mode = SP_KNOT_MODE_XOR; knot_color = 0xff88ff00; } -PowerStrokePointArrayParam::~PowerStrokePointArrayParam() -= default; +PowerStrokePointArrayParam::~PowerStrokePointArrayParam() = default; -Gtk::Widget * -PowerStrokePointArrayParam::param_newWidget() +Gtk::Widget *PowerStrokePointArrayParam::param_newWidget() { return nullptr; } @@ -53,8 +48,7 @@ void PowerStrokePointArrayParam::param_transform_multiply(Geom::Affine const &po if (transform_stroke) { std::vector result; result.reserve(_vector.size()); // reserve space for the points that will be added in the for loop - for (auto point_it : _vector) - { + for (auto point_it : _vector) { // scale each width knot with the average scaling in X and Y Geom::Coord const A = point_it[Geom::Y] * postmul.descrim(); result.emplace_back(point_it[Geom::X], A); @@ -63,23 +57,26 @@ void PowerStrokePointArrayParam::param_transform_multiply(Geom::Affine const &po } } -/** call this method to recalculate the controlpoints such that they stay at the same location relative to the new path. Useful after adding/deleting nodes to the path.*/ -void -PowerStrokePointArrayParam::recalculate_controlpoints_for_new_pwd2(Geom::Piecewise > const & pwd2_in) +/** call this method to recalculate the controlpoints such that they stay at the same location relative to the new path. + * Useful after adding/deleting nodes to the path.*/ +void PowerStrokePointArrayParam::recalculate_controlpoints_for_new_pwd2( + Geom::Piecewise> const &pwd2_in) { - Inkscape::LivePathEffect::LPEPowerStroke *lpe = dynamic_cast(param_effect); + Inkscape::LivePathEffect::LPEPowerStroke *lpe = + dynamic_cast(param_effect); if (lpe) { if (last_pwd2.size() > pwd2_in.size()) { double factor = (double)pwd2_in.size() / (double)last_pwd2.size(); - for (auto & i : _vector) { + for (auto &i : _vector) { i[Geom::X] *= factor; } } else if (last_pwd2.size() < pwd2_in.size()) { // Path has become longer: probably node added, maintain position of knots - Geom::Piecewise > normal = rot90(unitVector(derivative(pwd2_in))); - for (auto & i : _vector) { + Geom::Piecewise> normal = rot90(unitVector(derivative(pwd2_in))); + for (auto &i : _vector) { Geom::Point pt = i; - Geom::Point position = last_pwd2.valueAt(pt[Geom::X]) + pt[Geom::Y] * last_pwd2_normal.valueAt(pt[Geom::X]); + Geom::Point position = + last_pwd2.valueAt(pt[Geom::X]) + pt[Geom::Y] * last_pwd2_normal.valueAt(pt[Geom::X]); double t = nearest_time(position, pwd2_in); i[Geom::X] = t; } @@ -89,16 +86,15 @@ PowerStrokePointArrayParam::recalculate_controlpoints_for_new_pwd2(Geom::Piecewi } /** call this method to recalculate the controlpoints when path is reversed.*/ -std::vector -PowerStrokePointArrayParam::reverse_controlpoints(bool write) +std::vector PowerStrokePointArrayParam::reverse_controlpoints(bool write) { std::vector controlpoints; if (!last_pwd2.empty()) { - Geom::Piecewise > const & pwd2_in_reverse = reverse(last_pwd2); - for (auto & i : _vector) { + Geom::Piecewise> const &pwd2_in_reverse = reverse(last_pwd2); + for (auto &i : _vector) { Geom::Point control_pos = last_pwd2.valueAt(i[Geom::X]); double new_pos = Geom::nearest_time(control_pos, pwd2_in_reverse); - controlpoints.emplace_back(new_pos,i[Geom::Y]); + controlpoints.emplace_back(new_pos, i[Geom::Y]); i[Geom::X] = new_pos; } if (write) { @@ -115,34 +111,28 @@ PowerStrokePointArrayParam::reverse_controlpoints(bool write) float PowerStrokePointArrayParam::median_width() { - size_t size = _vector.size(); - if (size > 0) - { - if (size % 2 == 0) - { - return (_vector[size / 2 - 1].y() + _vector[size / 2].y()) / 2; - } - else - { - return _vector[size / 2].y(); - } - } - return 1; + size_t size = _vector.size(); + if (size > 0) { + if (size % 2 == 0) { + return (_vector[size / 2 - 1].y() + _vector[size / 2].y()) / 2; + } else { + return _vector[size / 2].y(); + } + } + return 1; } -void -PowerStrokePointArrayParam::set_pwd2(Geom::Piecewise > const & pwd2_in, Geom::Piecewise > const & pwd2_normal_in) +void PowerStrokePointArrayParam::set_pwd2(Geom::Piecewise> const &pwd2_in, + Geom::Piecewise> const &pwd2_normal_in) { last_pwd2 = pwd2_in; last_pwd2_normal = pwd2_normal_in; } - -void -PowerStrokePointArrayParam::set_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color) +void PowerStrokePointArrayParam::set_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color) { knot_shape = shape; - knot_mode = mode; + knot_mode = mode; knot_color = color; } /* @@ -165,14 +155,14 @@ private: unsigned int _index; };*/ -PowerStrokePointArrayParamKnotHolderEntity::PowerStrokePointArrayParamKnotHolderEntity(PowerStrokePointArrayParam *p, unsigned int index) - : _pparam(p), - _index(index) -{ -} +PowerStrokePointArrayParamKnotHolderEntity::PowerStrokePointArrayParamKnotHolderEntity(PowerStrokePointArrayParam *p, + unsigned int index) + : _pparam(p) + , _index(index) +{} -void -PowerStrokePointArrayParamKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) +void PowerStrokePointArrayParamKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, + guint state) { using namespace Geom; @@ -180,21 +170,22 @@ PowerStrokePointArrayParamKnotHolderEntity::knot_set(Geom::Point const &p, Geom: return; } static gint prev_index = 0; - Piecewise > const & pwd2 = _pparam->get_pwd2(); - Piecewise > pwd2port = _pparam->get_pwd2(); - Geom::Point s = snap_knot_position(p, state); + Piecewise> const &pwd2 = _pparam->get_pwd2(); + Piecewise> pwd2port = _pparam->get_pwd2(); + Geom::Point s = snap_knot_position(p, state); double t2 = 0; LPEPowerStroke *ps = dynamic_cast(_pparam->param_effect); if (ps && ps->not_jump) { s = p; t2 = _pparam->_vector.at(_index)[Geom::X]; Geom::PathVector pathv = path_from_piecewise(pwd2port, 0.001); - pathv[0] = pathv[0].portion(std::max(std::floor(t2) - 1, 0.0), std::min(std::ceil(t2) + 1, (double)pathv[0].size())); + pathv[0] = + pathv[0].portion(std::max(std::floor(t2) - 1, 0.0), std::min(std::ceil(t2) + 1, (double)pathv[0].size())); pwd2port = paths_to_pw(pathv); } /// @todo how about item transforms??? - - Piecewise > const & n = _pparam->get_pwd2_normal(); + + Piecewise> const &n = _pparam->get_pwd2_normal(); gint index = std::floor(nearest_time(s, pwd2)); bool bigjump = false; if (std::abs(prev_index - index) > 1) { @@ -211,20 +202,19 @@ PowerStrokePointArrayParamKnotHolderEntity::knot_set(Geom::Point const &p, Geom: tpos = prevpos; } offset = dot(s - pwd2.valueAt(tpos), n.valueAt(tpos)); - _pparam->_vector.at(_index) = Geom::Point(tpos, offset/_pparam->_scale_width); + _pparam->_vector.at(_index) = Geom::Point(tpos, offset / _pparam->_scale_width); } else { offset = dot(s - pwd2.valueAt(t), n.valueAt(t)); - _pparam->_vector.at(_index) = Geom::Point(t, offset/_pparam->_scale_width); + _pparam->_vector.at(_index) = Geom::Point(t, offset / _pparam->_scale_width); } - if (_pparam->_vector.size() == 1 ) { + if (_pparam->_vector.size() == 1) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble("/live_effects/powerstroke/width", offset); } sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, false); } -Geom::Point -PowerStrokePointArrayParamKnotHolderEntity::knot_get() const +Geom::Point PowerStrokePointArrayParamKnotHolderEntity::knot_get() const { using namespace Geom; @@ -232,20 +222,21 @@ PowerStrokePointArrayParamKnotHolderEntity::knot_get() const return Geom::Point(infinity(), infinity()); } - Piecewise > const & pwd2 = _pparam->get_pwd2(); - Piecewise > const & n = _pparam->get_pwd2_normal(); + Piecewise> const &pwd2 = _pparam->get_pwd2(); + Piecewise> const &n = _pparam->get_pwd2_normal(); Point offset_point = _pparam->_vector.at(_index); if (offset_point[X] > pwd2.size() || offset_point[X] < 0) { g_warning("Broken powerstroke point at %f, I won't try to add that", offset_point[X]); return Geom::Point(infinity(), infinity()); } - Point canvas_point = pwd2.valueAt(offset_point[X]) + (offset_point[Y] * _pparam->_scale_width) * n.valueAt(offset_point[X]); + Point canvas_point = + pwd2.valueAt(offset_point[X]) + (offset_point[Y] * _pparam->_scale_width) * n.valueAt(offset_point[X]); return canvas_point; } -void -PowerStrokePointArrayParamKnotHolderEntity::knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) +void PowerStrokePointArrayParamKnotHolderEntity::knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, + guint state) { _pparam->param_effect->refresh_widgets = true; _pparam->write_to_SVG(); @@ -254,23 +245,24 @@ PowerStrokePointArrayParamKnotHolderEntity::knot_ungrabbed(Geom::Point const &p, void PowerStrokePointArrayParamKnotHolderEntity::knot_set_offset(Geom::Point offset) { _pparam->_vector.at(_index) = Geom::Point(offset.x(), offset.y() / 2); - this->parent_holder->knot_ungrabbed_handler(this->knot, 0); + this->parent_holder->knot_ungrabbed_handler(this->knot, 0); } -void -PowerStrokePointArrayParamKnotHolderEntity::knot_click(guint state) +void PowerStrokePointArrayParamKnotHolderEntity::knot_click(guint state) { if (state & GDK_CONTROL_MASK) { if (state & GDK_MOD1_MASK) { // delete the clicked knot - std::vector & vec = _pparam->_vector; - if (vec.size() > 1) { //Force don't remove last knot + std::vector &vec = _pparam->_vector; + if (vec.size() > 1) { // Force don't remove last knot vec.erase(vec.begin() + _index); _pparam->param_set_and_write_new_value(vec); // shift knots down one index - for(auto & ent : parent_holder->entity) { - PowerStrokePointArrayParamKnotHolderEntity *pspa_ent = dynamic_cast(ent); - if ( pspa_ent && pspa_ent->_pparam == this->_pparam ) { // check if the knotentity belongs to this powerstrokepointarray parameter + for (auto &ent : parent_holder->entity) { + PowerStrokePointArrayParamKnotHolderEntity *pspa_ent = + dynamic_cast(ent); + if (pspa_ent && pspa_ent->_pparam == this->_pparam) { // check if the knotentity belongs to this + // powerstrokepointarray parameter if (pspa_ent->_index > this->_index) { --pspa_ent->_index; } @@ -282,33 +274,34 @@ PowerStrokePointArrayParamKnotHolderEntity::knot_click(guint state) return; } else { // add a knot to XML - std::vector & vec = _pparam->_vector; + std::vector &vec = _pparam->_vector; vec.insert(vec.begin() + _index, 1, vec.at(_index)); // this clicked knot is duplicated _pparam->param_set_and_write_new_value(vec); // shift knots up one index - for(auto & ent : parent_holder->entity) { - PowerStrokePointArrayParamKnotHolderEntity *pspa_ent = dynamic_cast(ent); - if ( pspa_ent && pspa_ent->_pparam == this->_pparam ) { // check if the knotentity belongs to this powerstrokepointarray parameter + for (auto &ent : parent_holder->entity) { + PowerStrokePointArrayParamKnotHolderEntity *pspa_ent = + dynamic_cast(ent); + if (pspa_ent && pspa_ent->_pparam == this->_pparam) { // check if the knotentity belongs to this + // powerstrokepointarray parameter if (pspa_ent->_index > this->_index) { ++pspa_ent->_index; } } }; // add knot to knotholder - PowerStrokePointArrayParamKnotHolderEntity *e = new PowerStrokePointArrayParamKnotHolderEntity(_pparam, _index+1); + PowerStrokePointArrayParamKnotHolderEntity *e = + new PowerStrokePointArrayParamKnotHolderEntity(_pparam, _index + 1); e->create(this->desktop, this->item, parent_holder, Inkscape::CTRL_TYPE_LPE, _("Stroke width control point: drag to alter the stroke width. Ctrl+click adds a " "control point, Ctrl+Alt+click deletes it, Shift+click launches width dialog."), _pparam->knot_shape, _pparam->knot_mode, _pparam->knot_color); parent_holder->add(e); } + } else if ((state & GDK_MOD1_MASK) || (state & GDK_SHIFT_MASK)) { + Geom::Point offset = Geom::Point(_pparam->_vector.at(_index).x(), _pparam->_vector.at(_index).y() * 2); + Inkscape::UI::Dialogs::PowerstrokePropertiesDialog::showDialog(this->desktop, offset, this); } - else if ((state & GDK_MOD1_MASK) || (state & GDK_SHIFT_MASK)) - { - Geom::Point offset = Geom::Point(_pparam->_vector.at(_index).x(), _pparam->_vector.at(_index).y() * 2); - Inkscape::UI::Dialogs::PowerstrokePropertiesDialog::showDialog(this->desktop, offset, this); - } } void PowerStrokePointArrayParam::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) diff --git a/src/live_effects/parameter/powerstrokepointarray.h b/src/live_effects/parameter/powerstrokepointarray.h index 36c44322b8bb6801773f8bc8e75afa5d98e44906..930e0d5d4435081c44cf50682b8a4d813c4d4b3c 100644 --- a/src/live_effects/parameter/powerstrokepointarray.h +++ b/src/live_effects/parameter/powerstrokepointarray.h @@ -10,49 +10,46 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include <2geom/point.h> - -#include "live_effects/parameter/array.h" +#include #include "knot-holder-entity.h" +#include "live_effects/parameter/array.h" namespace Inkscape { namespace LivePathEffect { -class PowerStrokePointArrayParam : public ArrayParam { +class PowerStrokePointArrayParam : public ArrayParam +{ public: - PowerStrokePointArrayParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect); + PowerStrokePointArrayParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect); ~PowerStrokePointArrayParam() override; - PowerStrokePointArrayParam(const PowerStrokePointArrayParam&) = delete; - PowerStrokePointArrayParam& operator=(const PowerStrokePointArrayParam&) = delete; + PowerStrokePointArrayParam(const PowerStrokePointArrayParam &) = delete; + PowerStrokePointArrayParam &operator=(const PowerStrokePointArrayParam &) = delete; - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; - void param_transform_multiply(Geom::Affine const& postmul, bool /*set*/) override; + void param_transform_multiply(Geom::Affine const &postmul, bool /*set*/) override; void set_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color); - float median_width(); bool providesKnotHolderEntities() const override { return true; } void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) override; - void param_update_default(const gchar * default_value) override{}; + void param_update_default(const gchar *default_value) override{}; - void set_pwd2(Geom::Piecewise > const & pwd2_in, Geom::Piecewise > const & pwd2_normal_in); - Geom::Piecewise > const & get_pwd2() const { return last_pwd2; } - Geom::Piecewise > const & get_pwd2_normal() const { return last_pwd2_normal; } + void set_pwd2(Geom::Piecewise> const &pwd2_in, + Geom::Piecewise> const &pwd2_normal_in); + Geom::Piecewise> const &get_pwd2() const { return last_pwd2; } + Geom::Piecewise> const &get_pwd2_normal() const { return last_pwd2_normal; } - void recalculate_controlpoints_for_new_pwd2(Geom::Piecewise > const & pwd2_in); + void recalculate_controlpoints_for_new_pwd2(Geom::Piecewise> const &pwd2_in); std::vector reverse_controlpoints(bool write); - void set_scale_width(double scale_width){_scale_width = scale_width;}; + void set_scale_width(double scale_width) { _scale_width = scale_width; }; double _scale_width; friend class PowerStrokePointArrayParamKnotHolderEntity; @@ -61,11 +58,12 @@ private: SPKnotModeType knot_mode; guint32 knot_color; - Geom::Piecewise > last_pwd2; - Geom::Piecewise > last_pwd2_normal; + Geom::Piecewise> last_pwd2; + Geom::Piecewise> last_pwd2_normal; }; -class PowerStrokePointArrayParamKnotHolderEntity : public KnotHolderEntity { +class PowerStrokePointArrayParamKnotHolderEntity : public KnotHolderEntity +{ public: PowerStrokePointArrayParamKnotHolderEntity(PowerStrokePointArrayParam *p, unsigned int index); ~PowerStrokePointArrayParamKnotHolderEntity() override = default; @@ -77,17 +75,15 @@ public: void knot_click(guint state) override; /** Checks whether the index falls within the size of the parameter's vector */ - bool valid_index(unsigned int index) const { - return (_pparam->_vector.size() > index); - }; + bool valid_index(unsigned int index) const { return (_pparam->_vector.size() > index); }; private: PowerStrokePointArrayParam *_pparam; unsigned int _index; }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/random.cpp b/src/live_effects/parameter/random.cpp index c5346d1f53c5712afdb39b3c4e9e868efc83df30..2517ac7ac8fd37896ffb681feb2cc5e21994c577 100644 --- a/src/live_effects/parameter/random.cpp +++ b/src/live_effects/parameter/random.cpp @@ -5,15 +5,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/registered-widget.h" #include "live_effects/parameter/random.h" -#include "live_effects/effect.h" + #include -#include "svg/svg.h" -#include "ui/widget/random.h" +#include "live_effects/effect.h" #include "svg/stringstream.h" - +#include "svg/svg.h" +#include "ui/widget/random.h" +#include "ui/widget/registered-widget.h" #include "verbs.h" #define noLPERANDOMPARAM_DEBUG @@ -22,10 +22,8 @@ namespace Inkscape { namespace LivePathEffect { - -RandomParam::RandomParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, gdouble default_value, long default_seed) +RandomParam::RandomParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, gdouble default_value, long default_seed) : Parameter(label, tip, key, wr, effect) { defvalue = default_value; @@ -39,14 +37,12 @@ RandomParam::RandomParam( const Glib::ustring& label, const Glib::ustring& tip, seed = startseed; } -RandomParam::~RandomParam() -= default; +RandomParam::~RandomParam() = default; -bool -RandomParam::param_readSVGValue(const gchar * strvalue) +bool RandomParam::param_readSVGValue(const gchar *strvalue) { double newval, newstartseed; - gchar** stringarray = g_strsplit (strvalue, ";", 2); + gchar **stringarray = g_strsplit(strvalue, ";", 2); unsigned int success = sp_svg_number_read_d(stringarray[0], &newval); if (success == 1) { success += sp_svg_number_read_d(stringarray[1], &newstartseed); @@ -62,35 +58,32 @@ RandomParam::param_readSVGValue(const gchar * strvalue) return false; } -Glib::ustring -RandomParam::param_getSVGValue() const +Glib::ustring RandomParam::param_getSVGValue() const { Inkscape::SVGOStringStream os; os << value << ';' << startseed; return os.str(); } -Glib::ustring -RandomParam::param_getDefaultSVGValue() const +Glib::ustring RandomParam::param_getDefaultSVGValue() const { Inkscape::SVGOStringStream os; os << defvalue << ';' << defseed; return os.str(); } -void -RandomParam::param_set_default() +void RandomParam::param_set_default() { param_set_value(defvalue, defseed); } -void -RandomParam::param_update_default(gdouble default_value){ +void RandomParam::param_update_default(gdouble default_value) +{ defvalue = default_value; } -void -RandomParam::param_update_default(const gchar * default_value){ +void RandomParam::param_update_default(const gchar *default_value) +{ double newval; unsigned int success = sp_svg_number_read_d(default_value, &newval); if (success == 1) { @@ -98,8 +91,7 @@ RandomParam::param_update_default(const gchar * default_value){ } } -void -RandomParam::param_set_value(gdouble val, long newseed) +void RandomParam::param_set_value(gdouble val, long newseed) { value = val; if (integer) @@ -113,36 +105,26 @@ RandomParam::param_set_value(gdouble val, long newseed) seed = startseed; } -void -RandomParam::param_set_range(gdouble min, gdouble max) +void RandomParam::param_set_range(gdouble min, gdouble max) { this->min = min; this->max = max; } -void -RandomParam::param_make_integer(bool yes) +void RandomParam::param_make_integer(bool yes) { integer = yes; } -void -RandomParam::resetRandomizer() +void RandomParam::resetRandomizer() { seed = startseed; } - -Gtk::Widget * -RandomParam::param_newWidget() +Gtk::Widget *RandomParam::param_newWidget() { - Inkscape::UI::Widget::RegisteredRandom* regrandom = Gtk::manage( - new Inkscape::UI::Widget::RegisteredRandom( param_label, - param_tooltip, - param_key, - *param_wr, - param_effect->getRepr(), - param_effect->getSPDoc() ) ); + Inkscape::UI::Widget::RegisteredRandom *regrandom = Gtk::manage(new Inkscape::UI::Widget::RegisteredRandom( + param_label, param_tooltip, param_key, *param_wr, param_effect->getRepr(), param_effect->getSPDoc())); regrandom->setValue(value, startseed); if (integer) { @@ -151,14 +133,15 @@ RandomParam::param_newWidget() } regrandom->setRange(min, max); regrandom->setProgrammatically = false; - regrandom->signal_button_release_event().connect(sigc::mem_fun (*this, &RandomParam::on_button_release)); + regrandom->signal_button_release_event().connect(sigc::mem_fun(*this, &RandomParam::on_button_release)); regrandom->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change random parameter")); - return dynamic_cast (regrandom); + return dynamic_cast(regrandom); } -bool RandomParam::on_button_release(GdkEventButton* button_event) { +bool RandomParam::on_button_release(GdkEventButton *button_event) +{ param_effect->refresh_widgets = true; return false; } @@ -170,33 +153,33 @@ RandomParam::operator gdouble() /* RNG stolen from /display/nr-filter-turbulence.cpp */ #define RAND_m 2147483647 /* 2**31 - 1 */ -#define RAND_a 16807 /* 7**5; primitive root of m */ -#define RAND_q 127773 /* m / a */ -#define RAND_r 2836 /* m % a */ +#define RAND_a 16807 /* 7**5; primitive root of m */ +#define RAND_q 127773 /* m / a */ +#define RAND_r 2836 /* m % a */ #define BSize 0x100 -long -RandomParam::setup_seed(long lSeed) +long RandomParam::setup_seed(long lSeed) { - if (lSeed <= 0) lSeed = -(lSeed % (RAND_m - 1)) + 1; - if (lSeed > RAND_m - 1) lSeed = RAND_m - 1; - return lSeed; + if (lSeed <= 0) + lSeed = -(lSeed % (RAND_m - 1)) + 1; + if (lSeed > RAND_m - 1) + lSeed = RAND_m - 1; + return lSeed; } // generates random number between 0 and 1 -gdouble -RandomParam::rand() +gdouble RandomParam::rand() { - long result; - result = RAND_a * (seed % RAND_q) - RAND_r * (seed / RAND_q); - if (result <= 0) result += RAND_m; - seed = result; - - gdouble dresult = (gdouble)(result % BSize) / BSize; - return dresult; + long result; + result = RAND_a * (seed % RAND_q) - RAND_r * (seed / RAND_q); + if (result <= 0) + result += RAND_m; + seed = result; + + gdouble dresult = (gdouble)(result % BSize) / BSize; + return dresult; } - } /* namespace LivePathEffect */ } /* namespace Inkscape */ diff --git a/src/live_effects/parameter/random.h b/src/live_effects/parameter/random.h index e0bb07a25026c5ce4db1fd4a485742f1fcd9fb36..2523f1fa52675ffc0968374b56e42f94822abeec 100644 --- a/src/live_effects/parameter/random.h +++ b/src/live_effects/parameter/random.h @@ -10,41 +10,38 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/parameter.h" -#include -#include <2geom/point.h> #include <2geom/path.h> +#include <2geom/point.h> +#include + +#include "live_effects/parameter/parameter.h" namespace Inkscape { namespace LivePathEffect { -class RandomParam : public Parameter { +class RandomParam : public Parameter +{ public: - RandomParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - gdouble default_value = 1.0, - long default_seed = 0); + RandomParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, gdouble default_value = 1.0, long default_seed = 0); ~RandomParam() override; - bool param_readSVGValue(const gchar * strvalue) override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; void param_set_default() override; - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; void param_set_value(gdouble val, long newseed); void param_make_integer(bool yes = true); void param_set_range(gdouble min, gdouble max); void param_update_default(gdouble default_value); - void param_update_default(const gchar * default_value) override; + void param_update_default(const gchar *default_value) override; void resetRandomizer(); operator gdouble(); - inline gdouble get_value() { return value; } ; + inline gdouble get_value() { return value; }; protected: long startseed; @@ -58,16 +55,16 @@ protected: gdouble defvalue; private: - bool on_button_release(GdkEventButton* button_event); + bool on_button_release(GdkEventButton *button_event); long setup_seed(long); gdouble rand(); - RandomParam(const RandomParam&) = delete; - RandomParam& operator=(const RandomParam&) = delete; + RandomParam(const RandomParam &) = delete; + RandomParam &operator=(const RandomParam &) = delete; }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/satellitesarray.cpp b/src/live_effects/parameter/satellitesarray.cpp index 7f15298cf3e67eb23ed5d7b63772998992779201..7d351d9aab2930e66cb120f4df1968954f80984f 100644 --- a/src/live_effects/parameter/satellitesarray.cpp +++ b/src/live_effects/parameter/satellitesarray.cpp @@ -8,7 +8,11 @@ */ #include "live_effects/parameter/satellitesarray.h" + +#include + #include "helper/geom.h" +#include "inkscape.h" #include "knotholder.h" #include "live_effects/effect.h" #include "live_effects/lpe-fillet-chamfer.h" @@ -16,9 +20,6 @@ #include "ui/shape-editor.h" #include "ui/tools-switch.h" #include "ui/tools/node-tool.h" - -#include "inkscape.h" -#include // TODO due to internal breakage in glibmm headers, // this has to be included last. #include @@ -27,12 +28,10 @@ namespace Inkscape { namespace LivePathEffect { -SatellitesArrayParam::SatellitesArrayParam(const Glib::ustring &label, - const Glib::ustring &tip, - const Glib::ustring &key, - Inkscape::UI::Widget::Registry *wr, - Effect *effect) - : ArrayParam >(label, tip, key, wr, effect, 0), _knoth(nullptr) +SatellitesArrayParam::SatellitesArrayParam(const Glib::ustring &label, const Glib::ustring &tip, + const Glib::ustring &key, Inkscape::UI::Widget::Registry *wr, Effect *effect) + : ArrayParam>(label, tip, key, wr, effect, 0) + , _knoth(nullptr) { _knot_shape = SP_KNOT_SHAPE_DIAMOND; _knot_mode = SP_KNOT_MODE_XOR; @@ -45,10 +44,7 @@ SatellitesArrayParam::SatellitesArrayParam(const Glib::ustring &label, param_widget_is_visible(false); } - -void SatellitesArrayParam::set_oncanvas_looks(SPKnotShapeType shape, - SPKnotModeType mode, - guint32 color) +void SatellitesArrayParam::set_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color) { _knot_shape = shape; _knot_mode = mode; @@ -121,13 +117,13 @@ void SatellitesArrayParam::updateCanvasIndicators(bool mirror) if (_effectType == FILLET_CHAMFER) { for (size_t i = 0; i < _vector.size(); ++i) { for (size_t j = 0; j < _vector[i].size(); ++j) { - if (_vector[i][j].hidden || //Ignore if hidden - (!_vector[i][j].has_mirror && mirror == true) || //Ignore if not have mirror and we are in mirror loop - _vector[i][j].amount == 0 || //no helper in 0 value - j >= count_path_nodes(pathv[i]) || //ignore last satellite in open paths with fillet chamfer effect - (!pathv[i].closed() && j == 0) || //ignore first satellites on open paths - count_path_nodes(pathv[i]) == 2) - { + if (_vector[i][j].hidden || // Ignore if hidden + (!_vector[i][j].has_mirror && mirror == true) || // Ignore if not have mirror and we are in mirror + // loop + _vector[i][j].amount == 0 || // no helper in 0 value + j >= count_path_nodes(pathv[i]) || // ignore last satellite in open paths with fillet chamfer effect + (!pathv[i].closed() && j == 0) || // ignore first satellites on open paths + count_path_nodes(pathv[i]) == 2) { continue; } Geom::Curve *curve_in = pathv[i][j].duplicate(); @@ -135,11 +131,11 @@ void SatellitesArrayParam::updateCanvasIndicators(bool mirror) bool overflow = false; double size_out = _vector[i][j].arcDistance(*curve_in); double length_out = curve_in->length(); - gint previous_index = j - 1; //Always are previous index because we skip first satellite on open paths + gint previous_index = j - 1; // Always are previous index because we skip first satellite on open paths if (j == 0 && pathv[i].closed()) { previous_index = count_path_nodes(pathv[i]) - 1; } - if ( previous_index < 0 ) { + if (previous_index < 0) { return; } double length_in = pathv.curveAt(previous_index).length(); @@ -170,8 +166,7 @@ void SatellitesArrayParam::updateCanvasIndicators() updateCanvasIndicators(true); } -void SatellitesArrayParam::addCanvasIndicators( - SPLPEItem const */*lpeitem*/, std::vector &hp_vec) +void SatellitesArrayParam::addCanvasIndicators(SPLPEItem const * /*lpeitem*/, std::vector &hp_vec) { hp_vec.push_back(_hp); } @@ -181,8 +176,8 @@ void SatellitesArrayParam::param_transform_multiply(Geom::Affine const &postmul, Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs->getBool("/options/transform/rectcorners", true)) { - for (auto & i : _vector) { - for (auto & j : i) { + for (auto &i : _vector) { + for (auto &j : i) { if (!j.is_time && j.amount > 0) { j.amount = j.amount * ((postmul.expansionX() + postmul.expansionY()) / 2); } @@ -192,9 +187,7 @@ void SatellitesArrayParam::param_transform_multiply(Geom::Affine const &postmul, } } -void SatellitesArrayParam::addKnotHolderEntities(KnotHolder *knotholder, - SPItem *item, - bool mirror) +void SatellitesArrayParam::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item, bool mirror) { if (!_last_pathvector_satellites) { return; @@ -210,7 +203,7 @@ void SatellitesArrayParam::addKnotHolderEntities(KnotHolder *knotholder, index += _last_pathvector_satellites->getTotalSatellites(); } using namespace Geom; - //If is for filletChamfer effect... + // If is for filletChamfer effect... if (_effectType == FILLET_CHAMFER) { const gchar *tip; if (type == CHAMFER) { @@ -244,13 +237,13 @@ void SatellitesArrayParam::addKnotHolderEntities(KnotHolder *knotholder, } void SatellitesArrayParam::updateAmmount(double amount) -{ +{ Geom::PathVector const pathv = _last_pathvector_satellites->getPathVector(); Satellites satellites = _last_pathvector_satellites->getSatellites(); for (size_t i = 0; i < satellites.size(); ++i) { for (size_t j = 0; j < satellites[i].size(); ++j) { Geom::Curve const &curve_in = pathv[i][j]; - if (param_effect->isNodePointSelected(curve_in.initialPoint()) ){ + if (param_effect->isNodePointSelected(curve_in.initialPoint())) { _vector[i][j].amount = amount; _vector[i][j].setSelected(true); } else { @@ -260,21 +253,18 @@ void SatellitesArrayParam::updateAmmount(double amount) } } -void SatellitesArrayParam::addKnotHolderEntities(KnotHolder *knotholder, - SPItem *item) +void SatellitesArrayParam::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) { _knoth = knotholder; addKnotHolderEntities(knotholder, item, true); } -FilletChamferKnotHolderEntity::FilletChamferKnotHolderEntity( - SatellitesArrayParam *p, size_t index) - : _pparam(p), _index(index) {} - +FilletChamferKnotHolderEntity::FilletChamferKnotHolderEntity(SatellitesArrayParam *p, size_t index) + : _pparam(p) + , _index(index) +{} -void FilletChamferKnotHolderEntity::knot_set(Geom::Point const &p, - Geom::Point const &/*origin*/, - guint state) +void FilletChamferKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) { if (!_pparam->_last_pathvector_satellites) { return; @@ -289,17 +279,17 @@ void FilletChamferKnotHolderEntity::knot_set(Geom::Point const &p, std::pair index_data = _pparam->_last_pathvector_satellites->getIndexData(index); size_t satelite_index = index_data.first; size_t subsatelite_index = index_data.second; - + Geom::Point s = snap_knot_position(p, state); if (!valid_index(satelite_index, subsatelite_index)) { return; } Satellite satellite = _pparam->_vector[satelite_index][subsatelite_index]; Geom::PathVector pathv = _pparam->_last_pathvector_satellites->getPathVector(); - if (satellite.hidden || - (!pathv[satelite_index].closed() && - (subsatelite_index == 0||//ignore first satellites on open paths - count_path_nodes(pathv[satelite_index]) - 1 == subsatelite_index))) //ignore last satellite in open paths with fillet chamfer effect + if (satellite.hidden || (!pathv[satelite_index].closed() && + (subsatelite_index == 0 || // ignore first satellites on open paths + count_path_nodes(pathv[satelite_index]) - 1 == + subsatelite_index))) // ignore last satellite in open paths with fillet chamfer effect { return; } @@ -307,7 +297,7 @@ void FilletChamferKnotHolderEntity::knot_set(Geom::Point const &p, if (subsatelite_index == 0 && pathv[satelite_index].closed()) { previous_index = count_path_nodes(pathv[satelite_index]) - 1; } - if ( previous_index < 0 ) { + if (previous_index < 0) { return; } Geom::Curve const &curve_in = pathv[satelite_index][previous_index]; @@ -315,8 +305,8 @@ void FilletChamferKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point mirror = curve_in.pointAt(mirror_time); double normal_time = Geom::nearest_time(s, pathv[satelite_index][subsatelite_index]); Geom::Point normal = pathv[satelite_index][subsatelite_index].pointAt(normal_time); - double distance_mirror = Geom::distance(mirror,s); - double distance_normal = Geom::distance(normal,s); + double distance_mirror = Geom::distance(mirror, s); + double distance_normal = Geom::distance(normal, s); if (Geom::are_near(s, pathv[satelite_index][subsatelite_index].initialPoint(), 1.5 / _pparam->_current_zoom)) { satellite.amount = 0; } else if (distance_mirror < distance_normal) { @@ -335,17 +325,18 @@ void FilletChamferKnotHolderEntity::knot_set(Geom::Point const &p, } else { satellite.setPosition(s, pathv[satelite_index][subsatelite_index]); } - Inkscape::LivePathEffect::LPEFilletChamfer *filletchamfer = dynamic_cast(_pparam->param_effect); + Inkscape::LivePathEffect::LPEFilletChamfer *filletchamfer = + dynamic_cast(_pparam->param_effect); filletchamfer->helperpath = true; _pparam->updateAmmount(satellite.amount); _pparam->_vector[satelite_index][subsatelite_index] = satellite; sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, false); } -void -FilletChamferKnotHolderEntity::knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) +void FilletChamferKnotHolderEntity::knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) { - Inkscape::LivePathEffect::LPEFilletChamfer *filletchamfer = dynamic_cast(_pparam->param_effect); + Inkscape::LivePathEffect::LPEFilletChamfer *filletchamfer = + dynamic_cast(_pparam->param_effect); if (filletchamfer) { filletchamfer->refresh_widgets = true; filletchamfer->helperpath = false; @@ -376,8 +367,9 @@ Geom::Point FilletChamferKnotHolderEntity::knot_get() const Satellite satellite = _pparam->_vector[satelite_index][subsatelite_index]; Geom::PathVector pathv = _pparam->_last_pathvector_satellites->getPathVector(); if (satellite.hidden || - (!pathv[satelite_index].closed() && (subsatelite_index == 0 || - subsatelite_index == count_path_nodes(pathv[satelite_index]) - 1))) //ignore first and last satellites on open paths + (!pathv[satelite_index].closed() && + (subsatelite_index == 0 || subsatelite_index == count_path_nodes(pathv[satelite_index]) - + 1))) // ignore first and last satellites on open paths { return Geom::Point(Geom::infinity(), Geom::infinity()); } @@ -387,7 +379,7 @@ Geom::Point FilletChamferKnotHolderEntity::knot_get() const if (subsatelite_index == 0 && pathv[satelite_index].closed()) { previous_index = count_path_nodes(pathv[satelite_index]) - 1; } - if ( previous_index < 0 ) { + if (previous_index < 0) { return Geom::Point(Geom::infinity(), Geom::infinity()); } Geom::Curve const &curve_in = pathv[satelite_index][previous_index]; @@ -400,7 +392,8 @@ Geom::Point FilletChamferKnotHolderEntity::knot_get() const t = 0; } double time_start = 0; - time_start = _pparam->_last_pathvector_satellites->getSatellites()[satelite_index][previous_index].time(curve_in); + time_start = + _pparam->_last_pathvector_satellites->getSatellites()[satelite_index][previous_index].time(curve_in); if (time_start > t) { t = time_start; } @@ -431,9 +424,10 @@ void FilletChamferKnotHolderEntity::knot_click(guint state) return; } Geom::PathVector pathv = _pparam->_last_pathvector_satellites->getPathVector(); - if (!pathv[satelite_index].closed() && - (subsatelite_index == 0 || - count_path_nodes(pathv[satelite_index]) - 1 == subsatelite_index)) //ignore last satellite in open paths with fillet chamfer effect + if (!pathv[satelite_index].closed() && + (subsatelite_index == 0 || + count_path_nodes(pathv[satelite_index]) - 1 == subsatelite_index)) // ignore last satellite in open paths with + // fillet chamfer effect { return; } @@ -445,18 +439,18 @@ void FilletChamferKnotHolderEntity::knot_click(guint state) using namespace Geom; SatelliteType type = _pparam->_vector[satelite_index][subsatelite_index].satellite_type; switch (type) { - case FILLET: - type = INVERSE_FILLET; - break; - case INVERSE_FILLET: - type = CHAMFER; - break; - case CHAMFER: - type = INVERSE_CHAMFER; - break; - default: - type = FILLET; - break; + case FILLET: + type = INVERSE_FILLET; + break; + case INVERSE_FILLET: + type = CHAMFER; + break; + case CHAMFER: + type = INVERSE_CHAMFER; + break; + default: + type = FILLET; + break; } _pparam->_vector[satelite_index][subsatelite_index].satellite_type = type; sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, false); @@ -487,7 +481,7 @@ void FilletChamferKnotHolderEntity::knot_click(guint state) if (subsatelite_index == 0 && pathv[satelite_index].closed()) { previous_index = count_path_nodes(pathv[satelite_index]) - 1; } - if ( previous_index < 0 ) { + if (previous_index < 0) { return; } if (!_pparam->_use_distance && !_pparam->_vector[satelite_index][subsatelite_index].is_time) { @@ -498,11 +492,9 @@ void FilletChamferKnotHolderEntity::knot_click(guint state) bool aprox = false; Geom::D2 d2_out = pathv[satelite_index][subsatelite_index].toSBasis(); Geom::D2 d2_in = pathv[satelite_index][previous_index].toSBasis(); - aprox = ((d2_in)[0].degreesOfFreedom() != 2 || - d2_out[0].degreesOfFreedom() != 2) && - !_pparam->_use_distance - ? true - : false; + aprox = ((d2_in)[0].degreesOfFreedom() != 2 || d2_out[0].degreesOfFreedom() != 2) && !_pparam->_use_distance + ? true + : false; Inkscape::UI::Dialogs::FilletChamferPropertiesDialog::showDialog( this->desktop, amount, this, _pparam->_use_distance, aprox, _pparam->_vector[satelite_index][subsatelite_index]); @@ -528,9 +520,10 @@ void FilletChamferKnotHolderEntity::knot_set_offset(Satellite satellite) return; } Geom::PathVector pathv = _pparam->_last_pathvector_satellites->getPathVector(); - if (satellite.hidden || - (!pathv[satelite_index].closed() && - (subsatelite_index == 0 || count_path_nodes(pathv[satelite_index]) - 1 == subsatelite_index))) //ignore last satellite in open paths with fillet chamfer effect + if (satellite.hidden || (!pathv[satelite_index].closed() && + (subsatelite_index == 0 || count_path_nodes(pathv[satelite_index]) - 1 == + subsatelite_index))) // ignore last satellite in open paths + // with fillet chamfer effect { return; } @@ -541,7 +534,7 @@ void FilletChamferKnotHolderEntity::knot_set_offset(Satellite satellite) if (subsatelite_index == 0 && pathv[satelite_index].closed()) { previous_index = count_path_nodes(pathv[satelite_index]) - 1; } - if ( previous_index < 0 ) { + if (previous_index < 0) { return; } amount = _pparam->_vector[satelite_index][subsatelite_index].radToLen( diff --git a/src/live_effects/parameter/satellitesarray.h b/src/live_effects/parameter/satellitesarray.h index c15b7107bb29785b58ca1a6b331d172b16d30bdf..82d7c5425f292099f888b7eebe0111a45ac85c09 100644 --- a/src/live_effects/parameter/satellitesarray.h +++ b/src/live_effects/parameter/satellitesarray.h @@ -19,11 +19,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/parameter/array.h" -#include "live_effects/effect-enum.h" +#include + #include "helper/geom-pathvectorsatellites.h" #include "knot-holder-entity.h" -#include +#include "live_effects/effect-enum.h" +#include "live_effects/parameter/array.h" namespace Inkscape { @@ -31,32 +32,26 @@ namespace LivePathEffect { class FilletChamferKnotHolderEntity; -class SatellitesArrayParam : public ArrayParam > { +class SatellitesArrayParam : public ArrayParam> +{ public: - SatellitesArrayParam(const Glib::ustring &label, const Glib::ustring &tip, - const Glib::ustring &key, - Inkscape::UI::Widget::Registry *wr, Effect *effect); + SatellitesArrayParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect); - Gtk::Widget *param_newWidget() override - { - return nullptr; - } + Gtk::Widget *param_newWidget() override { return nullptr; } void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) override; virtual void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item, bool mirror); void addCanvasIndicators(SPLPEItem const *lpeitem, std::vector &hp_vec) override; virtual void updateCanvasIndicators(); virtual void updateCanvasIndicators(bool mirror); - bool providesKnotHolderEntities() const override - { - return true; - } + bool providesKnotHolderEntities() const override { return true; } void param_transform_multiply(Geom::Affine const &postmul, bool /*set*/) override; void setUseDistance(bool use_knot_distance); void setCurrentZoom(double current_zoom); void setGlobalKnotHide(bool global_knot_hide); void setEffectType(EffectType et); void reloadKnots(); - void updateAmmount(double amount); + void updateAmmount(double amount); void setPathVectorSatellites(PathVectorSatellites *pathVectorSatellites, bool write = true); void set_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color); @@ -79,18 +74,14 @@ private: double _current_zoom; EffectType _effectType; PathVectorSatellites *_last_pathvector_satellites; - }; -class FilletChamferKnotHolderEntity : public KnotHolderEntity { +class FilletChamferKnotHolderEntity : public KnotHolderEntity +{ public: FilletChamferKnotHolderEntity(SatellitesArrayParam *p, size_t index); - ~FilletChamferKnotHolderEntity() override - { - _pparam->_knoth = nullptr; - } - void knot_set(Geom::Point const &p, Geom::Point const &origin, - guint state) override; + ~FilletChamferKnotHolderEntity() override { _pparam->_knoth = nullptr; } + void knot_set(Geom::Point const &p, Geom::Point const &origin, guint state) override; Geom::Point knot_get() const override; void knot_click(guint state) override; void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override; @@ -107,8 +98,8 @@ private: size_t _index; }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/text.cpp b/src/live_effects/parameter/text.cpp index 0a32bf79fdfce72e9d49840fdb83abc5e3a4fe70..51cc5edfc91d7d1243c8bcd3439f0defdd288f1f 100644 --- a/src/live_effects/parameter/text.cpp +++ b/src/live_effects/parameter/text.cpp @@ -9,55 +9,51 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/registered-widget.h" +#include "live_effects/parameter/text.h" + +#include <2geom/sbasis-geometric.h> +#include #include -#include "live_effects/parameter/text.h" +#include "display/canvas-text.h" +#include "inkscape.h" #include "live_effects/effect.h" -#include "svg/svg.h" #include "svg/stringstream.h" -#include "inkscape.h" +#include "svg/svg.h" +#include "ui/widget/registered-widget.h" #include "verbs.h" -#include "display/canvas-text.h" -#include <2geom/sbasis-geometric.h> - -#include namespace Inkscape { namespace LivePathEffect { -TextParam::TextParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, const Glib::ustring default_value ) - : Parameter(label, tip, key, wr, effect), - value(default_value), - defvalue(default_value), - _hide_canvas_text(false) +TextParam::TextParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const Glib::ustring default_value) + : Parameter(label, tip, key, wr, effect) + , value(default_value) + , defvalue(default_value) + , _hide_canvas_text(false) { if (SPDesktop *desktop = SP_ACTIVE_DESKTOP) { // FIXME: we shouldn't use this! - canvas_text = (SPCanvasText *) sp_canvastext_new(desktop->getTempGroup(), desktop, Geom::Point(0,0), ""); - sp_canvastext_set_text (canvas_text, default_value.c_str()); - sp_canvastext_set_coords (canvas_text, 0, 0); + canvas_text = (SPCanvasText *)sp_canvastext_new(desktop->getTempGroup(), desktop, Geom::Point(0, 0), ""); + sp_canvastext_set_text(canvas_text, default_value.c_str()); + sp_canvastext_set_coords(canvas_text, 0, 0); } else { _hide_canvas_text = true; } } -void -TextParam::param_set_default() +void TextParam::param_set_default() { param_setValue(defvalue); } -void -TextParam::param_update_default(const gchar * default_value) +void TextParam::param_update_default(const gchar *default_value) { defvalue = (Glib::ustring)default_value; } -void -TextParam::param_hide_canvas_text() +void TextParam::param_hide_canvas_text() { if (!_hide_canvas_text) { sp_canvastext_set_text(canvas_text, " "); @@ -65,71 +61,63 @@ TextParam::param_hide_canvas_text() } } -void -TextParam::setPos(Geom::Point pos) +void TextParam::setPos(Geom::Point pos) { if (!_hide_canvas_text) { - sp_canvastext_set_coords (canvas_text, pos); + sp_canvastext_set_coords(canvas_text, pos); } } -void -TextParam::setPosAndAnchor(const Geom::Piecewise > &pwd2, - const double t, const double length, bool /*use_curvature*/) +void TextParam::setPosAndAnchor(const Geom::Piecewise> &pwd2, const double t, + const double length, bool /*use_curvature*/) { using namespace Geom; - Piecewise > pwd2_reparam = arc_length_parametrization(pwd2, 2 , 0.1); + Piecewise> 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)); + double angle = Geom::angle_between(dir, Point(1, 0)); if (!_hide_canvas_text) { sp_canvastext_set_coords(canvas_text, pos + n * length); sp_canvastext_set_anchor_manually(canvas_text, std::sin(angle), -std::cos(angle)); } } -void -TextParam::setAnchor(double x_value, double y_value) +void TextParam::setAnchor(double x_value, double y_value) { anchor_x = x_value; anchor_y = y_value; if (!_hide_canvas_text) { - sp_canvastext_set_anchor_manually (canvas_text, anchor_x, anchor_y); + sp_canvastext_set_anchor_manually(canvas_text, anchor_x, anchor_y); } } -bool -TextParam::param_readSVGValue(const gchar * strvalue) +bool TextParam::param_readSVGValue(const gchar *strvalue) { param_setValue(strvalue); return true; } -Glib::ustring -TextParam::param_getSVGValue() const +Glib::ustring TextParam::param_getSVGValue() const { return value; } -Glib::ustring -TextParam::param_getDefaultSVGValue() const +Glib::ustring TextParam::param_getDefaultSVGValue() const { return defvalue; } -void -TextParam::setTextParam(Inkscape::UI::Widget::RegisteredText *rsu) +void TextParam::setTextParam(Inkscape::UI::Widget::RegisteredText *rsu) { Glib::ustring str(rsu->getText()); param_setValue(str); write_to_SVG(); } -Gtk::Widget * -TextParam::param_newWidget() +Gtk::Widget *TextParam::param_newWidget() { Inkscape::UI::Widget::RegisteredText *rsu = Gtk::manage(new Inkscape::UI::Widget::RegisteredText( param_label, param_tooltip, param_key, *param_wr, param_effect->getRepr(), param_effect->getSPDoc())); @@ -137,25 +125,24 @@ TextParam::param_newWidget() rsu->setProgrammatically = false; rsu->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change text parameter")); Gtk::Box *text_container = Gtk::manage(new Gtk::Box()); - Gtk::Button *set = Gtk::manage(new Gtk::Button(Glib::ustring("✔"))); - set->signal_clicked() - .connect(sigc::bind(sigc::mem_fun(*this, &TextParam::setTextParam),rsu)); + Gtk::Button *set = Gtk::manage(new Gtk::Button(Glib::ustring("✔"))); + set->signal_clicked().connect( + sigc::bind(sigc::mem_fun(*this, &TextParam::setTextParam), rsu)); text_container->pack_start(*rsu, false, false, 2); text_container->pack_start(*set, false, false, 2); - Gtk::Widget *return_widg = dynamic_cast (text_container); + Gtk::Widget *return_widg = dynamic_cast(text_container); return_widg->set_halign(Gtk::ALIGN_END); return return_widg; } -void -TextParam::param_setValue(const Glib::ustring newvalue) +void TextParam::param_setValue(const Glib::ustring newvalue) { if (value != newvalue) { param_effect->refresh_widgets = true; } value = newvalue; if (!_hide_canvas_text) { - sp_canvastext_set_text (canvas_text, newvalue.c_str()); + sp_canvastext_set_text(canvas_text, newvalue.c_str()); } } diff --git a/src/live_effects/parameter/text.h b/src/live_effects/parameter/text.h index 2d25c612808a085e0cf2e7295d15d55ca3fa9206..9d11f8a6c81ae6244643d87c97688132b43192e7 100644 --- a/src/live_effects/parameter/text.h +++ b/src/live_effects/parameter/text.h @@ -25,19 +25,16 @@ namespace Inkscape { namespace LivePathEffect { -class TextParam : public Parameter { +class TextParam : public Parameter +{ public: - TextParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - const Glib::ustring default_value = ""); + TextParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, const Glib::ustring default_value = ""); ~TextParam() override = default; - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; - bool param_readSVGValue(const gchar * strvalue) override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; @@ -45,17 +42,17 @@ public: void param_hide_canvas_text(); void setTextParam(Inkscape::UI::Widget::RegisteredText *rsu); void param_set_default() override; - void param_update_default(const gchar * default_value) override; + void param_update_default(const gchar *default_value) override; void setPos(Geom::Point pos); - void setPosAndAnchor(const Geom::Piecewise > &pwd2, - const double t, const double length, bool use_curvature = false); + void setPosAndAnchor(const Geom::Piecewise> &pwd2, const double t, const double length, + bool use_curvature = false); void setAnchor(double x_value, double y_value); const Glib::ustring get_value() const { return value; }; private: - TextParam(const TextParam&) = delete; - TextParam& operator=(const TextParam&) = delete; + TextParam(const TextParam &) = delete; + TextParam &operator=(const TextParam &) = delete; double anchor_x; double anchor_y; bool _hide_canvas_text; @@ -71,17 +68,19 @@ private: * parameter must be initialized differently than usual (only with a pointer to the parent effect; * no label, no tooltip, etc.). */ -class TextParamInternal : public TextParam { +class TextParamInternal : public TextParam +{ public: - TextParamInternal(Effect* effect) : - TextParam("", "", "", nullptr, effect) {} + TextParamInternal(Effect *effect) + : TextParam("", "", "", nullptr, effect) + {} - Gtk::Widget * param_newWidget() override { return nullptr; } + Gtk::Widget *param_newWidget() override { return nullptr; } }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/togglebutton.cpp b/src/live_effects/parameter/togglebutton.cpp index 4cd2927f07ba088a36cabd0c561be06be15d8889..5c0813791914e0da555d0d7aba9f6fb634db892f 100644 --- a/src/live_effects/parameter/togglebutton.cpp +++ b/src/live_effects/parameter/togglebutton.cpp @@ -6,19 +6,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/registered-widget.h" -#include +#include "live_effects/parameter/togglebutton.h" +#include #include #include "helper-fns.h" #include "inkscape.h" #include "live_effects/effect.h" -#include "live_effects/parameter/togglebutton.h" #include "selection.h" #include "svg/stringstream.h" #include "svg/svg.h" #include "ui/icon-loader.h" +#include "ui/widget/registered-widget.h" #include "verbs.h" namespace Inkscape { @@ -47,125 +47,113 @@ ToggleButtonParam::~ToggleButtonParam() } } -void -ToggleButtonParam::param_set_default() +void ToggleButtonParam::param_set_default() { param_setValue(defvalue); } -bool -ToggleButtonParam::param_readSVGValue(const gchar * strvalue) +bool ToggleButtonParam::param_readSVGValue(const gchar *strvalue) { param_setValue(helperfns_read_bool(strvalue, defvalue)); return true; // not correct: if value is unacceptable, should return false! } -Glib::ustring -ToggleButtonParam::param_getSVGValue() const +Glib::ustring ToggleButtonParam::param_getSVGValue() const { return value ? "true" : "false"; } -Glib::ustring -ToggleButtonParam::param_getDefaultSVGValue() const +Glib::ustring ToggleButtonParam::param_getDefaultSVGValue() const { return defvalue ? "true" : "false"; } -void -ToggleButtonParam::param_update_default(bool default_value) +void ToggleButtonParam::param_update_default(bool default_value) { defvalue = default_value; } -void -ToggleButtonParam::param_update_default(const gchar * default_value) +void ToggleButtonParam::param_update_default(const gchar *default_value) { param_update_default(helperfns_read_bool(default_value, defvalue)); } -Gtk::Widget * -ToggleButtonParam::param_newWidget() +Gtk::Widget *ToggleButtonParam::param_newWidget() { if (_toggled_connection.connected()) { _toggled_connection.disconnect(); } - checkwdg = Gtk::manage( - new Inkscape::UI::Widget::RegisteredToggleButton(param_label, - param_tooltip, - param_key, - *param_wr, - false, - param_effect->getRepr(), - param_effect->getSPDoc()) ); - auto box_button = new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL); - box_button->set_homogeneous(false); - Gtk::Label *label = new Gtk::Label(""); - if (!param_label.empty()) { - if (value || inactive_label.empty()) { - label->set_text(param_label.c_str()); - } else { - label->set_text(inactive_label.c_str()); - } - } - label->show(); - if (_icon_active) { - if (!_icon_inactive) { - _icon_inactive = _icon_active; - } - box_button->show(); - Gtk::Widget *icon_button = nullptr; - if (!value) { - icon_button = sp_get_icon_image(_icon_inactive, _icon_size); - } else { - icon_button = sp_get_icon_image(_icon_active, _icon_size); - } - icon_button->show(); - box_button->pack_start(*icon_button, false, false, 1); - if (!param_label.empty()) { - box_button->pack_start(*label, false, false, 1); - } - } else { - box_button->pack_start(*label, false, false, 1); - } - - checkwdg->add(*Gtk::manage(box_button)); - checkwdg->setActive(value); - checkwdg->setProgrammatically = false; - checkwdg->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change togglebutton parameter")); - - _toggled_connection = checkwdg->signal_toggled().connect(sigc::mem_fun(*this, &ToggleButtonParam::toggled)); - return checkwdg; + checkwdg = Gtk::manage(new Inkscape::UI::Widget::RegisteredToggleButton( + param_label, param_tooltip, param_key, *param_wr, false, param_effect->getRepr(), param_effect->getSPDoc())); + auto box_button = new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL); + box_button->set_homogeneous(false); + Gtk::Label *label = new Gtk::Label(""); + if (!param_label.empty()) { + if (value || inactive_label.empty()) { + label->set_text(param_label.c_str()); + } else { + label->set_text(inactive_label.c_str()); + } + } + label->show(); + if (_icon_active) { + if (!_icon_inactive) { + _icon_inactive = _icon_active; + } + box_button->show(); + Gtk::Widget *icon_button = nullptr; + if (!value) { + icon_button = sp_get_icon_image(_icon_inactive, _icon_size); + } else { + icon_button = sp_get_icon_image(_icon_active, _icon_size); + } + icon_button->show(); + box_button->pack_start(*icon_button, false, false, 1); + if (!param_label.empty()) { + box_button->pack_start(*label, false, false, 1); + } + } else { + box_button->pack_start(*label, false, false, 1); + } + + checkwdg->add(*Gtk::manage(box_button)); + checkwdg->setActive(value); + checkwdg->setProgrammatically = false; + checkwdg->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change togglebutton parameter")); + + _toggled_connection = checkwdg->signal_toggled().connect(sigc::mem_fun(*this, &ToggleButtonParam::toggled)); + return checkwdg; } -void -ToggleButtonParam::refresh_button() +void ToggleButtonParam::refresh_button() { if (!_toggled_connection.connected()) { return; } - if(!checkwdg){ + if (!checkwdg) { return; } Gtk::Container *box_button = dynamic_cast(checkwdg->get_child()); - if(!box_button){ + if (!box_button) { return; } std::vector children = box_button->get_children(); if (!param_label.empty()) { - Gtk::Label *lab = dynamic_cast(children[children.size()-1]); - if (!lab) return; - if(value || inactive_label.empty()){ + Gtk::Label *lab = dynamic_cast(children[children.size() - 1]); + if (!lab) + return; + if (value || inactive_label.empty()) { lab->set_text(param_label.c_str()); - }else{ + } else { lab->set_text(inactive_label.c_str()); } } - if ( _icon_active ) { + if (_icon_active) { Gtk::Widget *im = dynamic_cast(children[0]); - if (!im) return; + if (!im) + return; if (!value) { im = sp_get_icon_image(_icon_inactive, _icon_size); } else { @@ -174,8 +162,7 @@ ToggleButtonParam::refresh_button() } } -void -ToggleButtonParam::param_setValue(bool newvalue) +void ToggleButtonParam::param_setValue(bool newvalue) { if (value != newvalue) { param_effect->refresh_widgets = true; @@ -184,8 +171,8 @@ ToggleButtonParam::param_setValue(bool newvalue) refresh_button(); } -void -ToggleButtonParam::toggled() { +void ToggleButtonParam::toggled() +{ if (SP_ACTIVE_DESKTOP) { Inkscape::Selection *selection = SP_ACTIVE_DESKTOP->getSelection(); selection->emitModified(); diff --git a/src/live_effects/parameter/togglebutton.h b/src/live_effects/parameter/togglebutton.h index 1c44ffb04d572936e4a726239fea4e25944b2298..35dbb6e6c4187847d4cdeab12fd89abbb288307e 100644 --- a/src/live_effects/parameter/togglebutton.h +++ b/src/live_effects/parameter/togglebutton.h @@ -23,51 +23,52 @@ namespace LivePathEffect { * class ToggleButtonParam: * represents a Gtk::ToggleButton as a Live Path Effect parameter */ -class ToggleButtonParam : public Parameter { +class ToggleButtonParam : public Parameter +{ public: - ToggleButtonParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, - Inkscape::UI::Widget::Registry *wr, Effect *effect, bool default_value = false, - Glib::ustring inactive_label = "", char const *icon_active = nullptr, - char const *icon_inactive = nullptr, Gtk::BuiltinIconSize icon_size = Gtk::ICON_SIZE_SMALL_TOOLBAR); - ~ToggleButtonParam() override; - ToggleButtonParam(const ToggleButtonParam &) = delete; - ToggleButtonParam &operator=(const ToggleButtonParam &) = delete; + ToggleButtonParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, bool default_value = false, + Glib::ustring inactive_label = "", char const *icon_active = nullptr, + char const *icon_inactive = nullptr, + Gtk::BuiltinIconSize icon_size = Gtk::ICON_SIZE_SMALL_TOOLBAR); + ~ToggleButtonParam() override; + ToggleButtonParam(const ToggleButtonParam &) = delete; + ToggleButtonParam &operator=(const ToggleButtonParam &) = delete; - Gtk::Widget *param_newWidget() override; + Gtk::Widget *param_newWidget() override; - bool param_readSVGValue(const gchar *strvalue) override; - Glib::ustring param_getSVGValue() const override; - Glib::ustring param_getDefaultSVGValue() const override; + bool param_readSVGValue(const gchar *strvalue) override; + Glib::ustring param_getSVGValue() const override; + Glib::ustring param_getDefaultSVGValue() const override; - void param_setValue(bool newvalue); - void param_set_default() override; + void param_setValue(bool newvalue); + void param_set_default() override; - bool get_value() const { return value; }; + bool get_value() const { return value; }; - inline operator bool() const { return value; }; + inline operator bool() const { return value; }; - sigc::signal &signal_toggled() { return _signal_toggled; } - virtual void toggled(); - void param_update_default(bool default_value); - void param_update_default(const gchar *default_value) override; + sigc::signal &signal_toggled() { return _signal_toggled; } + virtual void toggled(); + void param_update_default(bool default_value); + void param_update_default(const gchar *default_value) override; private: void refresh_button(); bool value; bool defvalue; const Glib::ustring inactive_label; - const char * _icon_active; - const char * _icon_inactive; + const char *_icon_active; + const char *_icon_inactive; Gtk::BuiltinIconSize _icon_size; - Inkscape::UI::Widget::RegisteredToggleButton * checkwdg; + Inkscape::UI::Widget::RegisteredToggleButton *checkwdg; sigc::signal _signal_toggled; sigc::connection _toggled_connection; }; +} // namespace LivePathEffect -} //namespace LivePathEffect - -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/transformedpoint.cpp b/src/live_effects/parameter/transformedpoint.cpp index 694f946adb07acbf6765c1c3e710af099edf3813..4d43b51319187f8bcf3f14863b762c9fcb87ad20 100644 --- a/src/live_effects/parameter/transformedpoint.cpp +++ b/src/live_effects/parameter/transformedpoint.cpp @@ -5,52 +5,47 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/registered-widget.h" #include "live_effects/parameter/transformedpoint.h" -#include "knotholder.h" -#include "svg/svg.h" -#include "svg/stringstream.h" +#include -#include "live_effects/effect.h" #include "desktop.h" +#include "knotholder.h" +#include "live_effects/effect.h" +#include "svg/stringstream.h" +#include "svg/svg.h" +#include "ui/widget/registered-widget.h" #include "verbs.h" -#include - namespace Inkscape { namespace LivePathEffect { -TransformedPointParam::TransformedPointParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, Geom::Point default_vector, - bool dontTransform) - : Parameter(label, tip, key, wr, effect), - defvalue(default_vector), - origin(0.,0.), - vector(default_vector), - noTransform(dontTransform) +TransformedPointParam::TransformedPointParam(const Glib::ustring &label, const Glib::ustring &tip, + const Glib::ustring &key, Inkscape::UI::Widget::Registry *wr, + Effect *effect, Geom::Point default_vector, bool dontTransform) + : Parameter(label, tip, key, wr, effect) + , defvalue(default_vector) + , origin(0., 0.) + , vector(default_vector) + , noTransform(dontTransform) { vec_knot_shape = SP_KNOT_SHAPE_DIAMOND; - vec_knot_mode = SP_KNOT_MODE_XOR; + vec_knot_mode = SP_KNOT_MODE_XOR; vec_knot_color = 0xffffb500; } -TransformedPointParam::~TransformedPointParam() -= default; +TransformedPointParam::~TransformedPointParam() = default; -void -TransformedPointParam::param_set_default() +void TransformedPointParam::param_set_default() { - setOrigin(Geom::Point(0.,0.)); + setOrigin(Geom::Point(0., 0.)); setVector(defvalue); } -bool -TransformedPointParam::param_readSVGValue(const gchar * strvalue) +bool TransformedPointParam::param_readSVGValue(const gchar *strvalue) { - gchar ** strarray = g_strsplit(strvalue, ",", 4); + gchar **strarray = g_strsplit(strvalue, ",", 4); if (!strarray) { return false; } @@ -63,108 +58,97 @@ TransformedPointParam::param_readSVGValue(const gchar * strvalue) break; } } - g_strfreev (strarray); + g_strfreev(strarray); if (i == 4) { - setOrigin( Geom::Point(val[0], val[1]) ); - setVector( Geom::Point(val[2], val[3]) ); + setOrigin(Geom::Point(val[0], val[1])); + setVector(Geom::Point(val[2], val[3])); return true; } return false; } -Glib::ustring -TransformedPointParam::param_getSVGValue() const +Glib::ustring TransformedPointParam::param_getSVGValue() const { Inkscape::SVGOStringStream os; os << origin << " , " << vector; return os.str(); } -Glib::ustring -TransformedPointParam::param_getDefaultSVGValue() const +Glib::ustring TransformedPointParam::param_getDefaultSVGValue() const { Inkscape::SVGOStringStream os; os << defvalue; return os.str(); } -void -TransformedPointParam::param_update_default(Geom::Point default_point) +void TransformedPointParam::param_update_default(Geom::Point default_point) { defvalue = default_point; } -void -TransformedPointParam::param_update_default(const gchar * default_point) +void TransformedPointParam::param_update_default(const gchar *default_point) { - gchar ** strarray = g_strsplit(default_point, ",", 2); + gchar **strarray = g_strsplit(default_point, ",", 2); double newx, newy; unsigned int success = sp_svg_number_read_d(strarray[0], &newx); success += sp_svg_number_read_d(strarray[1], &newy); - g_strfreev (strarray); + g_strfreev(strarray); if (success == 2) { - param_update_default( Geom::Point(newx, newy) ); + param_update_default(Geom::Point(newx, newy)); } } -Gtk::Widget * -TransformedPointParam::param_newWidget() +Gtk::Widget *TransformedPointParam::param_newWidget() { - Inkscape::UI::Widget::RegisteredVector * pointwdg = Gtk::manage( - new Inkscape::UI::Widget::RegisteredVector( param_label, - param_tooltip, - param_key, - *param_wr, - param_effect->getRepr(), - param_effect->getSPDoc() ) ); + Inkscape::UI::Widget::RegisteredVector *pointwdg = Gtk::manage(new Inkscape::UI::Widget::RegisteredVector( + param_label, param_tooltip, param_key, *param_wr, param_effect->getRepr(), param_effect->getSPDoc())); pointwdg->setPolarCoords(); - pointwdg->setValue( vector, origin ); + pointwdg->setValue(vector, origin); pointwdg->clearProgrammatically(); pointwdg->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change vector parameter")); - - Gtk::HBox * hbox = Gtk::manage( new Gtk::HBox() ); - static_cast(hbox)->pack_start(*pointwdg, true, true); - static_cast(hbox)->show_all_children(); - return dynamic_cast (hbox); + Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox()); + static_cast(hbox)->pack_start(*pointwdg, true, true); + static_cast(hbox)->show_all_children(); + + return dynamic_cast(hbox); } -void -TransformedPointParam::set_and_write_new_values(Geom::Point const &new_origin, Geom::Point const &new_vector) +void TransformedPointParam::set_and_write_new_values(Geom::Point const &new_origin, Geom::Point const &new_vector) { setValues(new_origin, new_vector); param_write_to_repr(param_getSVGValue().c_str()); } -void -TransformedPointParam::param_transform_multiply(Geom::Affine const& postmul, bool /*set*/) +void TransformedPointParam::param_transform_multiply(Geom::Affine const &postmul, bool /*set*/) { if (!noTransform) { - set_and_write_new_values( origin * postmul, vector * postmul.withoutTranslation() ); + set_and_write_new_values(origin * postmul, vector * postmul.withoutTranslation()); } } - -void -TransformedPointParam::set_vector_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color) +void TransformedPointParam::set_vector_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color) { vec_knot_shape = shape; - vec_knot_mode = mode; + vec_knot_mode = mode; vec_knot_color = color; } -void -TransformedPointParam::set_oncanvas_color(guint32 color) +void TransformedPointParam::set_oncanvas_color(guint32 color) { vec_knot_color = color; } -class TransformedPointParamKnotHolderEntity_Vector : public KnotHolderEntity { +class TransformedPointParamKnotHolderEntity_Vector : public KnotHolderEntity +{ public: - TransformedPointParamKnotHolderEntity_Vector(TransformedPointParam *p) : param(p) { } + TransformedPointParamKnotHolderEntity_Vector(TransformedPointParam *p) + : param(p) + {} ~TransformedPointParamKnotHolderEntity_Vector() override = default; - void knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint /*state*/) override { + void knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint /*state*/) override + { Geom::Point const s = p - param->origin; /// @todo implement angle snapping when holding CTRL param->setVector(s); @@ -176,19 +160,17 @@ public: param->param_effect->refresh_widgets = true; param->write_to_SVG(); }; - Geom::Point knot_get() const override{ - return param->origin + param->vector; - }; - void knot_click(guint /*state*/) override{ - g_print ("This is the vector handle associated to parameter '%s'\n", param->param_key.c_str()); + Geom::Point knot_get() const override { return param->origin + param->vector; }; + void knot_click(guint /*state*/) override + { + g_print("This is the vector handle associated to parameter '%s'\n", param->param_key.c_str()); }; private: TransformedPointParam *param; }; -void -TransformedPointParam::addKnotHolderEntities(KnotHolder *knotholder, SPDesktop *desktop, SPItem *item) +void TransformedPointParam::addKnotHolderEntities(KnotHolder *knotholder, SPDesktop *desktop, SPItem *item) { TransformedPointParamKnotHolderEntity_Vector *vector_e = new TransformedPointParamKnotHolderEntity_Vector(this); vector_e->create(desktop, item, knotholder, Inkscape::CTRL_TYPE_LPE, handleTip(), vec_knot_shape, vec_knot_mode, diff --git a/src/live_effects/parameter/transformedpoint.h b/src/live_effects/parameter/transformedpoint.h index 3fd6989be2d9575f7a450f7d6223bbb0b3e44092..db99f5325d7ea76df2cc0843c3c18c9b1a57b5db 100644 --- a/src/live_effects/parameter/transformedpoint.h +++ b/src/live_effects/parameter/transformedpoint.h @@ -10,39 +10,38 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include <2geom/point.h> - -#include "live_effects/parameter/parameter.h" +#include #include "knot-holder-entity.h" +#include "live_effects/parameter/parameter.h" namespace Inkscape { namespace LivePathEffect { - -class TransformedPointParam : public Parameter { +class TransformedPointParam : public Parameter +{ public: - TransformedPointParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - Geom::Point default_vector = Geom::Point(1,0), - bool dontTransform = false); + TransformedPointParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, + Geom::Point default_vector = Geom::Point(1, 0), bool dontTransform = false); ~TransformedPointParam() override; - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; inline const gchar *handleTip() const { return param_tooltip.c_str(); } - bool param_readSVGValue(const gchar * strvalue) override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; Geom::Point getVector() const { return vector; }; Geom::Point getOrigin() const { return origin; }; - void setValues(Geom::Point const &new_origin, Geom::Point const &new_vector) { setVector(new_vector); setOrigin(new_origin); }; + void setValues(Geom::Point const &new_origin, Geom::Point const &new_vector) + { + setVector(new_vector); + setOrigin(new_origin); + }; void setVector(Geom::Point const &new_vector) { vector = new_vector; }; void setOrigin(Geom::Point const &new_origin) { origin = new_origin; }; void param_set_default() override; @@ -55,13 +54,13 @@ public: void set_oncanvas_color(guint32 color); Geom::Point param_get_default() { return defvalue; } void param_update_default(Geom::Point default_point); - void param_update_default(const gchar * default_point) override; + void param_update_default(const gchar *default_point) override; bool providesKnotHolderEntities() const override { return true; } virtual void addKnotHolderEntities(KnotHolder *knotholder, SPDesktop *desktop, SPItem *item); private: - TransformedPointParam(const TransformedPointParam&) = delete; - TransformedPointParam& operator=(const TransformedPointParam&) = delete; + TransformedPointParam(const TransformedPointParam &) = delete; + TransformedPointParam &operator=(const TransformedPointParam &) = delete; Geom::Point defvalue; @@ -69,18 +68,17 @@ private: Geom::Point vector; bool noTransform; - + /// The looks of the vector and origin knots oncanvas SPKnotShapeType vec_knot_shape; - SPKnotModeType vec_knot_mode; - guint32 vec_knot_color; + SPKnotModeType vec_knot_mode; + guint32 vec_knot_color; friend class TransformedPointParamKnotHolderEntity_Vector; }; +} // namespace LivePathEffect -} //namespace LivePathEffect - -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/unit.cpp b/src/live_effects/parameter/unit.cpp index 65a939b7e118a62d84c64339b1c4e05ab8643f67..9e4b6c8ebacc7b5fa65776e87d5cee36163400c0 100644 --- a/src/live_effects/parameter/unit.cpp +++ b/src/live_effects/parameter/unit.cpp @@ -5,13 +5,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/registered-widget.h" +#include "live_effects/parameter/unit.h" + #include -#include "live_effects/parameter/unit.h" #include "live_effects/effect.h" -#include "verbs.h" +#include "ui/widget/registered-widget.h" #include "util/units.h" +#include "verbs.h" using Inkscape::Util::unit_table; @@ -19,21 +20,17 @@ namespace Inkscape { namespace LivePathEffect { - -UnitParam::UnitParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, Glib::ustring default_unit) +UnitParam::UnitParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, Glib::ustring default_unit) : Parameter(label, tip, key, wr, effect) { defunit = unit_table.getUnit(default_unit); unit = defunit; } -UnitParam::~UnitParam() -= default; +UnitParam::~UnitParam() = default; -bool -UnitParam::param_readSVGValue(const gchar * strvalue) +bool UnitParam::param_readSVGValue(const gchar *strvalue) { if (strvalue) { param_set_value(*unit_table.getUnit(strvalue)); @@ -42,57 +39,46 @@ UnitParam::param_readSVGValue(const gchar * strvalue) return false; } -Glib::ustring -UnitParam::param_getSVGValue() const +Glib::ustring UnitParam::param_getSVGValue() const { return unit->abbr; } -Glib::ustring -UnitParam::param_getDefaultSVGValue() const +Glib::ustring UnitParam::param_getDefaultSVGValue() const { return defunit->abbr; } -void -UnitParam::param_set_default() +void UnitParam::param_set_default() { param_set_value(*defunit); } -void -UnitParam::param_update_default(const gchar * default_unit) +void UnitParam::param_update_default(const gchar *default_unit) { defunit = unit_table.getUnit((Glib::ustring)default_unit); } -void -UnitParam::param_set_value(Inkscape::Util::Unit const &val) +void UnitParam::param_set_value(Inkscape::Util::Unit const &val) { param_effect->refresh_widgets = true; unit = new Inkscape::Util::Unit(val); } -const gchar * -UnitParam::get_abbreviation() const +const gchar *UnitParam::get_abbreviation() const { return unit->abbr.c_str(); } -Gtk::Widget * -UnitParam::param_newWidget() +Gtk::Widget *UnitParam::param_newWidget() { - Inkscape::UI::Widget::RegisteredUnitMenu* unit_menu = Gtk::manage( - new Inkscape::UI::Widget::RegisteredUnitMenu(param_label, - param_key, - *param_wr, - param_effect->getRepr(), - param_effect->getSPDoc())); + Inkscape::UI::Widget::RegisteredUnitMenu *unit_menu = Gtk::manage(new Inkscape::UI::Widget::RegisteredUnitMenu( + param_label, param_key, *param_wr, param_effect->getRepr(), param_effect->getSPDoc())); unit_menu->setUnit(unit->abbr); unit_menu->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change unit parameter")); - - return dynamic_cast (unit_menu); + + return dynamic_cast(unit_menu); } } /* namespace LivePathEffect */ diff --git a/src/live_effects/parameter/unit.h b/src/live_effects/parameter/unit.h index b87d29a32a85b118e3433001121316010f538faa..6d41490e57897978a24141fbda014cb7910e8f44 100644 --- a/src/live_effects/parameter/unit.h +++ b/src/live_effects/parameter/unit.h @@ -15,42 +15,39 @@ namespace Inkscape { namespace Util { - class Unit; +class Unit; } namespace LivePathEffect { -class UnitParam : public Parameter { +class UnitParam : public Parameter +{ public: - UnitParam(const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - Glib::ustring default_unit = "px"); + UnitParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, Glib::ustring default_unit = "px"); ~UnitParam() override; - bool param_readSVGValue(const gchar * strvalue) override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; void param_set_default() override; void param_set_value(Inkscape::Util::Unit const &val); - void param_update_default(const gchar * default_unit) override; + void param_update_default(const gchar *default_unit) override; const gchar *get_abbreviation() const; - Gtk::Widget * param_newWidget() override; - + Gtk::Widget *param_newWidget() override; + operator Inkscape::Util::Unit const *() const { return unit; } private: Inkscape::Util::Unit const *unit; Inkscape::Util::Unit const *defunit; - UnitParam(const UnitParam&) = delete; - UnitParam& operator=(const UnitParam&) = delete; + UnitParam(const UnitParam &) = delete; + UnitParam &operator=(const UnitParam &) = delete; }; -} //namespace LivePathEffect +} // namespace LivePathEffect -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/parameter/vector.cpp b/src/live_effects/parameter/vector.cpp index ab0a9aea480dfd36b4dfb1b3eb3299631f8bdaa3..174232254d775451e4df53bf3c68ef5c85edb46e 100644 --- a/src/live_effects/parameter/vector.cpp +++ b/src/live_effects/parameter/vector.cpp @@ -5,71 +5,64 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/registered-widget.h" -#include - #include "live_effects/parameter/vector.h" -#include "knotholder.h" -#include "svg/svg.h" -#include "svg/stringstream.h" +#include +#include "knotholder.h" #include "live_effects/effect.h" +#include "svg/stringstream.h" +#include "svg/svg.h" +#include "ui/widget/registered-widget.h" #include "verbs.h" namespace Inkscape { namespace LivePathEffect { -VectorParam::VectorParam( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Inkscape::UI::Widget::Registry* wr, - Effect* effect, Geom::Point default_vector) - : Parameter(label, tip, key, wr, effect), - defvalue(default_vector), - origin(0.,0.), - vector(default_vector) +VectorParam::VectorParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, Geom::Point default_vector) + : Parameter(label, tip, key, wr, effect) + , defvalue(default_vector) + , origin(0., 0.) + , vector(default_vector) { vec_knot_shape = SP_KNOT_SHAPE_DIAMOND; - vec_knot_mode = SP_KNOT_MODE_XOR; + vec_knot_mode = SP_KNOT_MODE_XOR; vec_knot_color = 0xffffb500; ori_knot_shape = SP_KNOT_SHAPE_CIRCLE; - ori_knot_mode = SP_KNOT_MODE_XOR; + ori_knot_mode = SP_KNOT_MODE_XOR; ori_knot_color = 0xffffb500; } -VectorParam::~VectorParam() -= default; +VectorParam::~VectorParam() = default; -void -VectorParam::param_set_default() +void VectorParam::param_set_default() { - setOrigin(Geom::Point(0.,0.)); + setOrigin(Geom::Point(0., 0.)); setVector(defvalue); } -void -VectorParam::param_update_default(Geom::Point default_point) +void VectorParam::param_update_default(Geom::Point default_point) { defvalue = default_point; } -void -VectorParam::param_update_default(const gchar * default_point) +void VectorParam::param_update_default(const gchar *default_point) { - gchar ** strarray = g_strsplit(default_point, ",", 2); + gchar **strarray = g_strsplit(default_point, ",", 2); double newx, newy; unsigned int success = sp_svg_number_read_d(strarray[0], &newx); success += sp_svg_number_read_d(strarray[1], &newy); - g_strfreev (strarray); + g_strfreev(strarray); if (success == 2) { - param_update_default( Geom::Point(newx, newy) ); + param_update_default(Geom::Point(newx, newy)); } } -bool -VectorParam::param_readSVGValue(const gchar * strvalue) +bool VectorParam::param_readSVGValue(const gchar *strvalue) { - gchar ** strarray = g_strsplit(strvalue, ",", 4); + gchar **strarray = g_strsplit(strvalue, ",", 4); if (!strarray) { return false; } @@ -82,147 +75,138 @@ VectorParam::param_readSVGValue(const gchar * strvalue) break; } } - g_strfreev (strarray); + g_strfreev(strarray); if (i == 4) { - setOrigin( Geom::Point(val[0], val[1]) ); - setVector( Geom::Point(val[2], val[3]) ); + setOrigin(Geom::Point(val[0], val[1])); + setVector(Geom::Point(val[2], val[3])); return true; } return false; } -Glib::ustring -VectorParam::param_getSVGValue() const +Glib::ustring VectorParam::param_getSVGValue() const { Inkscape::SVGOStringStream os; os << origin << " , " << vector; return os.str(); } -Glib::ustring -VectorParam::param_getDefaultSVGValue() const +Glib::ustring VectorParam::param_getDefaultSVGValue() const { Inkscape::SVGOStringStream os; os << defvalue; return os.str(); } -Gtk::Widget * -VectorParam::param_newWidget() +Gtk::Widget *VectorParam::param_newWidget() { - Inkscape::UI::Widget::RegisteredVector * pointwdg = Gtk::manage( - new Inkscape::UI::Widget::RegisteredVector( param_label, - param_tooltip, - param_key, - *param_wr, - param_effect->getRepr(), - param_effect->getSPDoc() ) ); + Inkscape::UI::Widget::RegisteredVector *pointwdg = Gtk::manage(new Inkscape::UI::Widget::RegisteredVector( + param_label, param_tooltip, param_key, *param_wr, param_effect->getRepr(), param_effect->getSPDoc())); pointwdg->setPolarCoords(); - pointwdg->setValue( vector, origin ); + pointwdg->setValue(vector, origin); pointwdg->clearProgrammatically(); pointwdg->set_undo_parameters(SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Change vector parameter")); - Gtk::HBox * hbox = Gtk::manage( new Gtk::HBox() ); - static_cast(hbox)->pack_start(*pointwdg, true, true); - static_cast(hbox)->show_all_children(); + Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox()); + static_cast(hbox)->pack_start(*pointwdg, true, true); + static_cast(hbox)->show_all_children(); - return dynamic_cast (hbox); + return dynamic_cast(hbox); } -void -VectorParam::set_and_write_new_values(Geom::Point const &new_origin, Geom::Point const &new_vector) +void VectorParam::set_and_write_new_values(Geom::Point const &new_origin, Geom::Point const &new_vector) { setValues(new_origin, new_vector); param_write_to_repr(param_getSVGValue().c_str()); } -void -VectorParam::param_transform_multiply(Geom::Affine const& postmul, bool /*set*/) +void VectorParam::param_transform_multiply(Geom::Affine const &postmul, bool /*set*/) { - set_and_write_new_values( origin * postmul, vector * postmul.withoutTranslation() ); + set_and_write_new_values(origin * postmul, vector * postmul.withoutTranslation()); } - -void -VectorParam::set_vector_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color) +void VectorParam::set_vector_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color) { vec_knot_shape = shape; - vec_knot_mode = mode; + vec_knot_mode = mode; vec_knot_color = color; } -void -VectorParam::set_origin_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color) +void VectorParam::set_origin_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color) { ori_knot_shape = shape; - ori_knot_mode = mode; + ori_knot_mode = mode; ori_knot_color = color; } -void -VectorParam::set_oncanvas_color(guint32 color) +void VectorParam::set_oncanvas_color(guint32 color) { vec_knot_color = color; ori_knot_color = color; } -class VectorParamKnotHolderEntity_Origin : public KnotHolderEntity { +class VectorParamKnotHolderEntity_Origin : public KnotHolderEntity +{ public: - VectorParamKnotHolderEntity_Origin(VectorParam *p) : param(p) { } + VectorParamKnotHolderEntity_Origin(VectorParam *p) + : param(p) + {} ~VectorParamKnotHolderEntity_Origin() override = default; - void knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint state) override { + void knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint state) override + { Geom::Point const s = snap_knot_position(p, state); param->setOrigin(s); param->set_and_write_new_values(param->origin, param->vector); sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, false); }; - Geom::Point knot_get() const override { - return param->origin; - }; + Geom::Point knot_get() const override { return param->origin; }; void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override { param->param_effect->refresh_widgets = true; param->write_to_SVG(); }; - void knot_click(guint /*state*/) override{ - g_print ("This is the origin handle associated to parameter '%s'\n", param->param_key.c_str()); + void knot_click(guint /*state*/) override + { + g_print("This is the origin handle associated to parameter '%s'\n", param->param_key.c_str()); }; private: VectorParam *param; }; -class VectorParamKnotHolderEntity_Vector : public KnotHolderEntity { +class VectorParamKnotHolderEntity_Vector : public KnotHolderEntity +{ public: - VectorParamKnotHolderEntity_Vector(VectorParam *p) : param(p) { } + VectorParamKnotHolderEntity_Vector(VectorParam *p) + : param(p) + {} ~VectorParamKnotHolderEntity_Vector() override = default; - void knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, guint /*state*/) override { + void knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, guint /*state*/) override + { Geom::Point const s = p - param->origin; /// @todo implement angle snapping when holding CTRL param->setVector(s); param->set_and_write_new_values(param->origin, param->vector); sp_lpe_item_update_patheffect(SP_LPE_ITEM(item), false, false); }; - Geom::Point knot_get() const override { - return param->origin + param->vector; - }; + Geom::Point knot_get() const override { return param->origin + param->vector; }; void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override { param->param_effect->refresh_widgets = true; param->write_to_SVG(); }; - void knot_click(guint /*state*/) override{ - g_print ("This is the vector handle associated to parameter '%s'\n", param->param_key.c_str()); + void knot_click(guint /*state*/) override + { + g_print("This is the vector handle associated to parameter '%s'\n", param->param_key.c_str()); }; private: VectorParam *param; }; -void -VectorParam::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) +void VectorParam::addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) { VectorParamKnotHolderEntity_Origin *origin_e = new VectorParamKnotHolderEntity_Origin(this); origin_e->create(nullptr, item, knotholder, Inkscape::CTRL_TYPE_LPE, handleTip(), ori_knot_shape, ori_knot_mode, diff --git a/src/live_effects/parameter/vector.h b/src/live_effects/parameter/vector.h index d9894e92c7322bb248f7b3d044f0dbb3cabdd12d..cc842c98fc6b16bd6c8bdb6a4ee244f0175586fd 100644 --- a/src/live_effects/parameter/vector.h +++ b/src/live_effects/parameter/vector.h @@ -10,38 +10,37 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include <2geom/point.h> - -#include "live_effects/parameter/parameter.h" +#include #include "knot-holder-entity.h" +#include "live_effects/parameter/parameter.h" namespace Inkscape { namespace LivePathEffect { - -class VectorParam : public Parameter { +class VectorParam : public Parameter +{ public: - VectorParam( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Inkscape::UI::Widget::Registry* wr, - Effect* effect, - Geom::Point default_vector = Geom::Point(1,0) ); + VectorParam(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Inkscape::UI::Widget::Registry *wr, Effect *effect, Geom::Point default_vector = Geom::Point(1, 0)); ~VectorParam() override; - Gtk::Widget * param_newWidget() override; + Gtk::Widget *param_newWidget() override; inline const gchar *handleTip() const { return param_tooltip.c_str(); } - bool param_readSVGValue(const gchar * strvalue) override; + bool param_readSVGValue(const gchar *strvalue) override; Glib::ustring param_getSVGValue() const override; Glib::ustring param_getDefaultSVGValue() const override; Geom::Point getVector() const { return vector; }; Geom::Point getOrigin() const { return origin; }; - void setValues(Geom::Point const &new_origin, Geom::Point const &new_vector) { setVector(new_vector); setOrigin(new_origin); }; + void setValues(Geom::Point const &new_origin, Geom::Point const &new_vector) + { + setVector(new_vector); + setOrigin(new_origin); + }; void setVector(Geom::Point const &new_vector) { vector = new_vector; }; void setOrigin(Geom::Point const &new_origin) { origin = new_origin; }; void param_set_default() override; @@ -54,13 +53,13 @@ public: void set_origin_oncanvas_looks(SPKnotShapeType shape, SPKnotModeType mode, guint32 color); void set_oncanvas_color(guint32 color); void param_update_default(Geom::Point default_point); - void param_update_default(const gchar * default_point) override; + void param_update_default(const gchar *default_point) override; bool providesKnotHolderEntities() const override { return true; } void addKnotHolderEntities(KnotHolder *knotholder, SPItem *item) override; private: - VectorParam(const VectorParam&) = delete; - VectorParam& operator=(const VectorParam&) = delete; + VectorParam(const VectorParam &) = delete; + VectorParam &operator=(const VectorParam &) = delete; Geom::Point defvalue; @@ -69,19 +68,18 @@ private: /// The looks of the vector and origin knots oncanvas SPKnotShapeType vec_knot_shape; - SPKnotModeType vec_knot_mode; - guint32 vec_knot_color; + SPKnotModeType vec_knot_mode; + guint32 vec_knot_color; SPKnotShapeType ori_knot_shape; - SPKnotModeType ori_knot_mode; - guint32 ori_knot_color; + SPKnotModeType ori_knot_mode; + guint32 ori_knot_color; friend class VectorParamKnotHolderEntity_Origin; friend class VectorParamKnotHolderEntity_Vector; }; +} // namespace LivePathEffect -} //namespace LivePathEffect - -} //namespace Inkscape +} // namespace Inkscape #endif diff --git a/src/live_effects/spiro-converters.cpp b/src/live_effects/spiro-converters.cpp index 411fb659f1193f7c0a80b00d779d00aec435cd70..6f244c9d70b0cfdaba4cff43d1598af4232256cd 100644 --- a/src/live_effects/spiro-converters.cpp +++ b/src/live_effects/spiro-converters.cpp @@ -8,33 +8,33 @@ */ #include "spiro-converters.h" + #include <2geom/path.h> -#include "display/curve.h" #include +#include "display/curve.h" + #define SPIRO_SHOW_INFINITE_COORDINATE_CALLS #ifdef SPIRO_SHOW_INFINITE_COORDINATE_CALLS -# define SPIRO_G_MESSAGE(x) g_message(x) +#define SPIRO_G_MESSAGE(x) g_message(x) #else -# define SPIRO_G_MESSAGE(x) +#define SPIRO_G_MESSAGE(x) #endif namespace Spiro { -void -ConverterSPCurve::moveto(double x, double y) +void ConverterSPCurve::moveto(double x, double y) { - if ( std::isfinite(x) && std::isfinite(y) ) { + if (std::isfinite(x) && std::isfinite(y)) { _curve.moveto(x, y); } else { SPIRO_G_MESSAGE("Spiro: moveto not finite"); } } -void -ConverterSPCurve::lineto(double x, double y, bool close_last) +void ConverterSPCurve::lineto(double x, double y, bool close_last) { - if ( std::isfinite(x) && std::isfinite(y) ) { + if (std::isfinite(x) && std::isfinite(y)) { _curve.lineto(x, y); if (close_last) { _curve.closepath(); @@ -44,10 +44,9 @@ ConverterSPCurve::lineto(double x, double y, bool close_last) } } -void -ConverterSPCurve::quadto(double xm, double ym, double x3, double y3, bool close_last) +void ConverterSPCurve::quadto(double xm, double ym, double x3, double y3, bool close_last) { - if ( std::isfinite(xm) && std::isfinite(ym) && std::isfinite(x3) && std::isfinite(y3) ) { + if (std::isfinite(xm) && std::isfinite(ym) && std::isfinite(x3) && std::isfinite(y3)) { _curve.quadto(xm, ym, x3, y3); if (close_last) { _curve.closepath(); @@ -57,10 +56,9 @@ ConverterSPCurve::quadto(double xm, double ym, double x3, double y3, bool close_ } } -void -ConverterSPCurve::curveto(double x1, double y1, double x2, double y2, double x3, double y3, bool close_last) +void ConverterSPCurve::curveto(double x1, double y1, double x2, double y2, double x3, double y3, bool close_last) { - if ( std::isfinite(x1) && std::isfinite(y1) && std::isfinite(x2) && std::isfinite(y2) ) { + if (std::isfinite(x1) && std::isfinite(y1) && std::isfinite(x2) && std::isfinite(y2)) { _curve.curveto(x1, y1, x2, y2, x3, y3); if (close_last) { _curve.closepath(); @@ -70,38 +68,34 @@ ConverterSPCurve::curveto(double x1, double y1, double x2, double y2, double x3, } } - ConverterPath::ConverterPath(Geom::Path &path) : _path(path) { _path.setStitching(true); } -void -ConverterPath::moveto(double x, double y) +void ConverterPath::moveto(double x, double y) { - if ( std::isfinite(x) && std::isfinite(y) ) { + if (std::isfinite(x) && std::isfinite(y)) { _path.start(Geom::Point(x, y)); } else { SPIRO_G_MESSAGE("spiro moveto not finite"); } } -void -ConverterPath::lineto(double x, double y, bool close_last) +void ConverterPath::lineto(double x, double y, bool close_last) { - if ( std::isfinite(x) && std::isfinite(y) ) { - _path.appendNew( Geom::Point(x, y) ); + if (std::isfinite(x) && std::isfinite(y)) { + _path.appendNew(Geom::Point(x, y)); _path.close(close_last); } else { SPIRO_G_MESSAGE("spiro lineto not finite"); } } -void -ConverterPath::quadto(double xm, double ym, double x3, double y3, bool close_last) +void ConverterPath::quadto(double xm, double ym, double x3, double y3, bool close_last) { - if ( std::isfinite(xm) && std::isfinite(ym) && std::isfinite(x3) && std::isfinite(y3) ) { + if (std::isfinite(xm) && std::isfinite(ym) && std::isfinite(x3) && std::isfinite(y3)) { _path.appendNew(Geom::Point(xm, ym), Geom::Point(x3, y3)); _path.close(close_last); } else { @@ -109,10 +103,9 @@ ConverterPath::quadto(double xm, double ym, double x3, double y3, bool close_las } } -void -ConverterPath::curveto(double x1, double y1, double x2, double y2, double x3, double y3, bool close_last) +void ConverterPath::curveto(double x1, double y1, double x2, double y2, double x3, double y3, bool close_last) { - if ( std::isfinite(x1) && std::isfinite(y1) && std::isfinite(x2) && std::isfinite(y2) ) { + if (std::isfinite(x1) && std::isfinite(y1) && std::isfinite(x2) && std::isfinite(y2)) { _path.appendNew(Geom::Point(x1, y1), Geom::Point(x2, y2), Geom::Point(x3, y3)); _path.close(close_last); } else { @@ -122,8 +115,6 @@ ConverterPath::curveto(double x1, double y1, double x2, double y2, double x3, do } // namespace Spiro - - /* Local Variables: mode:c++ diff --git a/src/live_effects/spiro-converters.h b/src/live_effects/spiro-converters.h index 98041a22c8e18d995df31bcf8b1d7d681b877f22..3497a96b35a5b46b5aa5e1debdd23eee00ffcf1c 100644 --- a/src/live_effects/spiro-converters.h +++ b/src/live_effects/spiro-converters.h @@ -15,10 +15,13 @@ class SPCurve; namespace Spiro { -class ConverterBase { +class ConverterBase +{ public: - ConverterBase() = default;; - virtual ~ConverterBase() = default;; + ConverterBase() = default; + ; + virtual ~ConverterBase() = default; + ; virtual void moveto(double x, double y) = 0; virtual void lineto(double x, double y, bool close_last) = 0; @@ -26,11 +29,11 @@ public: virtual void curveto(double x1, double y1, double x2, double y2, double x3, double y3, bool close_last) = 0; }; - /** * Converts Spiro to Inkscape's SPCurve */ -class ConverterSPCurve : public ConverterBase { +class ConverterSPCurve : public ConverterBase +{ public: ConverterSPCurve(SPCurve &curve) : _curve(curve) @@ -44,15 +47,15 @@ public: private: SPCurve &_curve; - ConverterSPCurve(const ConverterSPCurve&) = delete; - ConverterSPCurve& operator=(const ConverterSPCurve&) = delete; + ConverterSPCurve(const ConverterSPCurve &) = delete; + ConverterSPCurve &operator=(const ConverterSPCurve &) = delete; }; - /** * Converts Spiro to 2Geom's Path */ -class ConverterPath : public ConverterBase { +class ConverterPath : public ConverterBase +{ public: ConverterPath(Geom::Path &path); @@ -64,11 +67,10 @@ public: private: Geom::Path &_path; - ConverterPath(const ConverterPath&) = delete; - ConverterPath& operator=(const ConverterPath&) = delete; + ConverterPath(const ConverterPath &) = delete; + ConverterPath &operator=(const ConverterPath &) = delete; }; - } // namespace Spiro #endif diff --git a/src/live_effects/spiro.cpp b/src/live_effects/spiro.cpp index 4c129bafd28ffd886954e90189ad67cfba298ff0..eba07953b9bda140698e91462967d40ae548e1db 100644 --- a/src/live_effects/spiro.cpp +++ b/src/live_effects/spiro.cpp @@ -38,12 +38,12 @@ void spiro_run(const spiro_cp *src, int src_len, Geom::Path &path) free(s); } - /************************************ * Spiro math */ -struct spiro_seg_s { +struct spiro_seg_s +{ double x; double y; char ty; @@ -54,13 +54,14 @@ struct spiro_seg_s { double l; }; -struct bandmat { +struct bandmat +{ double a[11]; /* band-diagonal matrix */ double al[5]; /* lower part of band-diagonal decomposition */ }; #ifndef M_PI -#define M_PI 3.14159265358979323846 /* pi */ +#define M_PI 3.14159265358979323846 /* pi */ #endif int n = 4; @@ -70,16 +71,15 @@ int n = 4; #endif /* Integrate polynomial spiral curve over range -.5 .. .5. */ -static void -integrate_spiro(const double ks[4], double xy[2]) +static void integrate_spiro(const double ks[4], double xy[2]) { #if 0 int n = 1024; #endif double th1 = ks[0]; double th2 = .5 * ks[1]; - double th3 = (1./6) * ks[2]; - double th4 = (1./24) * ks[3]; + double th3 = (1. / 6) * ks[2]; + double th4 = (1. / 24) * ks[3]; double x, y; double ds = 1. / n; double ds2 = ds * ds; @@ -95,347 +95,354 @@ integrate_spiro(const double ks[4], double xy[2]) y = 0; for (i = 0; i < n; i++) { - #if ORDER > 2 - double u, v; - double km0, km1, km2, km3; - - if (n == 1) { - km0 = k0; - km1 = k1 * ds; - km2 = k2 * ds2; - } else { - km0 = (((1./6) * k3 * s + .5 * k2) * s + k1) * s + k0; - km1 = ((.5 * k3 * s + k2) * s + k1) * ds; - km2 = (k3 * s + k2) * ds2; - } - km3 = k3 * ds3; + double u, v; + double km0, km1, km2, km3; + + if (n == 1) { + km0 = k0; + km1 = k1 * ds; + km2 = k2 * ds2; + } else { + km0 = (((1. / 6) * k3 * s + .5 * k2) * s + k1) * s + k0; + km1 = ((.5 * k3 * s + k2) * s + k1) * ds; + km2 = (k3 * s + k2) * ds2; + } + km3 = k3 * ds3; #endif - { - + { #if ORDER == 4 - double km0_2 = km0 * km0; - u = 24 - km0_2; - v = km1; + double km0_2 = km0 * km0; + u = 24 - km0_2; + v = km1; #endif #if ORDER == 6 - double km0_2 = km0 * km0; - double km0_4 = km0_2 * km0_2; - u = 24 - km0_2 + (km0_4 - 4 * km0 * km2 - 3 * km1 * km1) * (1./80); - v = km1 + (km3 - 6 * km0_2 * km1) * (1./80); + double km0_2 = km0 * km0; + double km0_4 = km0_2 * km0_2; + u = 24 - km0_2 + (km0_4 - 4 * km0 * km2 - 3 * km1 * km1) * (1. / 80); + v = km1 + (km3 - 6 * km0_2 * km1) * (1. / 80); #endif #if ORDER == 8 - double t1_1 = km0; - double t1_2 = .5 * km1; - double t1_3 = (1./6) * km2; - double t1_4 = (1./24) * km3; - double t2_2 = t1_1 * t1_1; - double t2_3 = 2 * (t1_1 * t1_2); - double t2_4 = 2 * (t1_1 * t1_3) + t1_2 * t1_2; - double t2_5 = 2 * (t1_1 * t1_4 + t1_2 * t1_3); - double t2_6 = 2 * (t1_2 * t1_4) + t1_3 * t1_3; - double t3_4 = t2_2 * t1_2 + t2_3 * t1_1; - double t3_6 = t2_2 * t1_4 + t2_3 * t1_3 + t2_4 * t1_2 + t2_5 * t1_1; - double t4_4 = t2_2 * t2_2; - double t4_5 = 2 * (t2_2 * t2_3); - double t4_6 = 2 * (t2_2 * t2_4) + t2_3 * t2_3; - double t5_6 = t4_4 * t1_2 + t4_5 * t1_1; - double t6_6 = t4_4 * t2_2; - u = 1; - v = 0; - v += (1./12) * t1_2 + (1./80) * t1_4; - u -= (1./24) * t2_2 + (1./160) * t2_4 + (1./896) * t2_6; - v -= (1./480) * t3_4 + (1./2688) * t3_6; - u += (1./1920) * t4_4 + (1./10752) * t4_6; - v += (1./53760) * t5_6; - u -= (1./322560) * t6_6; + double t1_1 = km0; + double t1_2 = .5 * km1; + double t1_3 = (1. / 6) * km2; + double t1_4 = (1. / 24) * km3; + double t2_2 = t1_1 * t1_1; + double t2_3 = 2 * (t1_1 * t1_2); + double t2_4 = 2 * (t1_1 * t1_3) + t1_2 * t1_2; + double t2_5 = 2 * (t1_1 * t1_4 + t1_2 * t1_3); + double t2_6 = 2 * (t1_2 * t1_4) + t1_3 * t1_3; + double t3_4 = t2_2 * t1_2 + t2_3 * t1_1; + double t3_6 = t2_2 * t1_4 + t2_3 * t1_3 + t2_4 * t1_2 + t2_5 * t1_1; + double t4_4 = t2_2 * t2_2; + double t4_5 = 2 * (t2_2 * t2_3); + double t4_6 = 2 * (t2_2 * t2_4) + t2_3 * t2_3; + double t5_6 = t4_4 * t1_2 + t4_5 * t1_1; + double t6_6 = t4_4 * t2_2; + u = 1; + v = 0; + v += (1. / 12) * t1_2 + (1. / 80) * t1_4; + u -= (1. / 24) * t2_2 + (1. / 160) * t2_4 + (1. / 896) * t2_6; + v -= (1. / 480) * t3_4 + (1. / 2688) * t3_6; + u += (1. / 1920) * t4_4 + (1. / 10752) * t4_6; + v += (1. / 53760) * t5_6; + u -= (1. / 322560) * t6_6; #endif #if ORDER == 10 - double t1_1 = km0; - double t1_2 = .5 * km1; - double t1_3 = (1./6) * km2; - double t1_4 = (1./24) * km3; - double t2_2 = t1_1 * t1_1; - double t2_3 = 2 * (t1_1 * t1_2); - double t2_4 = 2 * (t1_1 * t1_3) + t1_2 * t1_2; - double t2_5 = 2 * (t1_1 * t1_4 + t1_2 * t1_3); - double t2_6 = 2 * (t1_2 * t1_4) + t1_3 * t1_3; - double t2_7 = 2 * (t1_3 * t1_4); - double t2_8 = t1_4 * t1_4; - double t3_4 = t2_2 * t1_2 + t2_3 * t1_1; - double t3_6 = t2_2 * t1_4 + t2_3 * t1_3 + t2_4 * t1_2 + t2_5 * t1_1; - double t3_8 = t2_4 * t1_4 + t2_5 * t1_3 + t2_6 * t1_2 + t2_7 * t1_1; - double t4_4 = t2_2 * t2_2; - double t4_5 = 2 * (t2_2 * t2_3); - double t4_6 = 2 * (t2_2 * t2_4) + t2_3 * t2_3; - double t4_7 = 2 * (t2_2 * t2_5 + t2_3 * t2_4); - double t4_8 = 2 * (t2_2 * t2_6 + t2_3 * t2_5) + t2_4 * t2_4; - double t5_6 = t4_4 * t1_2 + t4_5 * t1_1; - double t5_8 = t4_4 * t1_4 + t4_5 * t1_3 + t4_6 * t1_2 + t4_7 * t1_1; - double t6_6 = t4_4 * t2_2; - double t6_7 = t4_4 * t2_3 + t4_5 * t2_2; - double t6_8 = t4_4 * t2_4 + t4_5 * t2_3 + t4_6 * t2_2; - double t7_8 = t6_6 * t1_2 + t6_7 * t1_1; - double t8_8 = t6_6 * t2_2; - u = 1; - v = 0; - v += (1./12) * t1_2 + (1./80) * t1_4; - u -= (1./24) * t2_2 + (1./160) * t2_4 + (1./896) * t2_6 + (1./4608) * t2_8; - v -= (1./480) * t3_4 + (1./2688) * t3_6 + (1./13824) * t3_8; - u += (1./1920) * t4_4 + (1./10752) * t4_6 + (1./55296) * t4_8; - v += (1./53760) * t5_6 + (1./276480) * t5_8; - u -= (1./322560) * t6_6 + (1./1.65888e+06) * t6_8; - v -= (1./1.16122e+07) * t7_8; - u += (1./9.28973e+07) * t8_8; + double t1_1 = km0; + double t1_2 = .5 * km1; + double t1_3 = (1. / 6) * km2; + double t1_4 = (1. / 24) * km3; + double t2_2 = t1_1 * t1_1; + double t2_3 = 2 * (t1_1 * t1_2); + double t2_4 = 2 * (t1_1 * t1_3) + t1_2 * t1_2; + double t2_5 = 2 * (t1_1 * t1_4 + t1_2 * t1_3); + double t2_6 = 2 * (t1_2 * t1_4) + t1_3 * t1_3; + double t2_7 = 2 * (t1_3 * t1_4); + double t2_8 = t1_4 * t1_4; + double t3_4 = t2_2 * t1_2 + t2_3 * t1_1; + double t3_6 = t2_2 * t1_4 + t2_3 * t1_3 + t2_4 * t1_2 + t2_5 * t1_1; + double t3_8 = t2_4 * t1_4 + t2_5 * t1_3 + t2_6 * t1_2 + t2_7 * t1_1; + double t4_4 = t2_2 * t2_2; + double t4_5 = 2 * (t2_2 * t2_3); + double t4_6 = 2 * (t2_2 * t2_4) + t2_3 * t2_3; + double t4_7 = 2 * (t2_2 * t2_5 + t2_3 * t2_4); + double t4_8 = 2 * (t2_2 * t2_6 + t2_3 * t2_5) + t2_4 * t2_4; + double t5_6 = t4_4 * t1_2 + t4_5 * t1_1; + double t5_8 = t4_4 * t1_4 + t4_5 * t1_3 + t4_6 * t1_2 + t4_7 * t1_1; + double t6_6 = t4_4 * t2_2; + double t6_7 = t4_4 * t2_3 + t4_5 * t2_2; + double t6_8 = t4_4 * t2_4 + t4_5 * t2_3 + t4_6 * t2_2; + double t7_8 = t6_6 * t1_2 + t6_7 * t1_1; + double t8_8 = t6_6 * t2_2; + u = 1; + v = 0; + v += (1. / 12) * t1_2 + (1. / 80) * t1_4; + u -= (1. / 24) * t2_2 + (1. / 160) * t2_4 + (1. / 896) * t2_6 + (1. / 4608) * t2_8; + v -= (1. / 480) * t3_4 + (1. / 2688) * t3_6 + (1. / 13824) * t3_8; + u += (1. / 1920) * t4_4 + (1. / 10752) * t4_6 + (1. / 55296) * t4_8; + v += (1. / 53760) * t5_6 + (1. / 276480) * t5_8; + u -= (1. / 322560) * t6_6 + (1. / 1.65888e+06) * t6_8; + v -= (1. / 1.16122e+07) * t7_8; + u += (1. / 9.28973e+07) * t8_8; #endif #if ORDER == 12 - double t1_1 = km0; - double t1_2 = .5 * km1; - double t1_3 = (1./6) * km2; - double t1_4 = (1./24) * km3; - double t2_2 = t1_1 * t1_1; - double t2_3 = 2 * (t1_1 * t1_2); - double t2_4 = 2 * (t1_1 * t1_3) + t1_2 * t1_2; - double t2_5 = 2 * (t1_1 * t1_4 + t1_2 * t1_3); - double t2_6 = 2 * (t1_2 * t1_4) + t1_3 * t1_3; - double t2_7 = 2 * (t1_3 * t1_4); - double t2_8 = t1_4 * t1_4; - double t3_4 = t2_2 * t1_2 + t2_3 * t1_1; - double t3_6 = t2_2 * t1_4 + t2_3 * t1_3 + t2_4 * t1_2 + t2_5 * t1_1; - double t3_8 = t2_4 * t1_4 + t2_5 * t1_3 + t2_6 * t1_2 + t2_7 * t1_1; - double t3_10 = t2_6 * t1_4 + t2_7 * t1_3 + t2_8 * t1_2; - double t4_4 = t2_2 * t2_2; - double t4_5 = 2 * (t2_2 * t2_3); - double t4_6 = 2 * (t2_2 * t2_4) + t2_3 * t2_3; - double t4_7 = 2 * (t2_2 * t2_5 + t2_3 * t2_4); - double t4_8 = 2 * (t2_2 * t2_6 + t2_3 * t2_5) + t2_4 * t2_4; - double t4_9 = 2 * (t2_2 * t2_7 + t2_3 * t2_6 + t2_4 * t2_5); - double t4_10 = 2 * (t2_2 * t2_8 + t2_3 * t2_7 + t2_4 * t2_6) + t2_5 * t2_5; - double t5_6 = t4_4 * t1_2 + t4_5 * t1_1; - double t5_8 = t4_4 * t1_4 + t4_5 * t1_3 + t4_6 * t1_2 + t4_7 * t1_1; - double t5_10 = t4_6 * t1_4 + t4_7 * t1_3 + t4_8 * t1_2 + t4_9 * t1_1; - double t6_6 = t4_4 * t2_2; - double t6_7 = t4_4 * t2_3 + t4_5 * t2_2; - double t6_8 = t4_4 * t2_4 + t4_5 * t2_3 + t4_6 * t2_2; - double t6_9 = t4_4 * t2_5 + t4_5 * t2_4 + t4_6 * t2_3 + t4_7 * t2_2; - double t6_10 = t4_4 * t2_6 + t4_5 * t2_5 + t4_6 * t2_4 + t4_7 * t2_3 + t4_8 * t2_2; - double t7_8 = t6_6 * t1_2 + t6_7 * t1_1; - double t7_10 = t6_6 * t1_4 + t6_7 * t1_3 + t6_8 * t1_2 + t6_9 * t1_1; - double t8_8 = t6_6 * t2_2; - double t8_9 = t6_6 * t2_3 + t6_7 * t2_2; - double t8_10 = t6_6 * t2_4 + t6_7 * t2_3 + t6_8 * t2_2; - double t9_10 = t8_8 * t1_2 + t8_9 * t1_1; - double t10_10 = t8_8 * t2_2; - u = 1; - v = 0; - v += (1./12) * t1_2 + (1./80) * t1_4; - u -= (1./24) * t2_2 + (1./160) * t2_4 + (1./896) * t2_6 + (1./4608) * t2_8; - v -= (1./480) * t3_4 + (1./2688) * t3_6 + (1./13824) * t3_8 + (1./67584) * t3_10; - u += (1./1920) * t4_4 + (1./10752) * t4_6 + (1./55296) * t4_8 + (1./270336) * t4_10; - v += (1./53760) * t5_6 + (1./276480) * t5_8 + (1./1.35168e+06) * t5_10; - u -= (1./322560) * t6_6 + (1./1.65888e+06) * t6_8 + (1./8.11008e+06) * t6_10; - v -= (1./1.16122e+07) * t7_8 + (1./5.67706e+07) * t7_10; - u += (1./9.28973e+07) * t8_8 + (1./4.54164e+08) * t8_10; - v += (1./4.08748e+09) * t9_10; - u -= (1./4.08748e+10) * t10_10; + double t1_1 = km0; + double t1_2 = .5 * km1; + double t1_3 = (1. / 6) * km2; + double t1_4 = (1. / 24) * km3; + double t2_2 = t1_1 * t1_1; + double t2_3 = 2 * (t1_1 * t1_2); + double t2_4 = 2 * (t1_1 * t1_3) + t1_2 * t1_2; + double t2_5 = 2 * (t1_1 * t1_4 + t1_2 * t1_3); + double t2_6 = 2 * (t1_2 * t1_4) + t1_3 * t1_3; + double t2_7 = 2 * (t1_3 * t1_4); + double t2_8 = t1_4 * t1_4; + double t3_4 = t2_2 * t1_2 + t2_3 * t1_1; + double t3_6 = t2_2 * t1_4 + t2_3 * t1_3 + t2_4 * t1_2 + t2_5 * t1_1; + double t3_8 = t2_4 * t1_4 + t2_5 * t1_3 + t2_6 * t1_2 + t2_7 * t1_1; + double t3_10 = t2_6 * t1_4 + t2_7 * t1_3 + t2_8 * t1_2; + double t4_4 = t2_2 * t2_2; + double t4_5 = 2 * (t2_2 * t2_3); + double t4_6 = 2 * (t2_2 * t2_4) + t2_3 * t2_3; + double t4_7 = 2 * (t2_2 * t2_5 + t2_3 * t2_4); + double t4_8 = 2 * (t2_2 * t2_6 + t2_3 * t2_5) + t2_4 * t2_4; + double t4_9 = 2 * (t2_2 * t2_7 + t2_3 * t2_6 + t2_4 * t2_5); + double t4_10 = 2 * (t2_2 * t2_8 + t2_3 * t2_7 + t2_4 * t2_6) + t2_5 * t2_5; + double t5_6 = t4_4 * t1_2 + t4_5 * t1_1; + double t5_8 = t4_4 * t1_4 + t4_5 * t1_3 + t4_6 * t1_2 + t4_7 * t1_1; + double t5_10 = t4_6 * t1_4 + t4_7 * t1_3 + t4_8 * t1_2 + t4_9 * t1_1; + double t6_6 = t4_4 * t2_2; + double t6_7 = t4_4 * t2_3 + t4_5 * t2_2; + double t6_8 = t4_4 * t2_4 + t4_5 * t2_3 + t4_6 * t2_2; + double t6_9 = t4_4 * t2_5 + t4_5 * t2_4 + t4_6 * t2_3 + t4_7 * t2_2; + double t6_10 = t4_4 * t2_6 + t4_5 * t2_5 + t4_6 * t2_4 + t4_7 * t2_3 + t4_8 * t2_2; + double t7_8 = t6_6 * t1_2 + t6_7 * t1_1; + double t7_10 = t6_6 * t1_4 + t6_7 * t1_3 + t6_8 * t1_2 + t6_9 * t1_1; + double t8_8 = t6_6 * t2_2; + double t8_9 = t6_6 * t2_3 + t6_7 * t2_2; + double t8_10 = t6_6 * t2_4 + t6_7 * t2_3 + t6_8 * t2_2; + double t9_10 = t8_8 * t1_2 + t8_9 * t1_1; + double t10_10 = t8_8 * t2_2; + u = 1; + v = 0; + v += (1. / 12) * t1_2 + (1. / 80) * t1_4; + u -= (1. / 24) * t2_2 + (1. / 160) * t2_4 + (1. / 896) * t2_6 + (1. / 4608) * t2_8; + v -= (1. / 480) * t3_4 + (1. / 2688) * t3_6 + (1. / 13824) * t3_8 + (1. / 67584) * t3_10; + u += (1. / 1920) * t4_4 + (1. / 10752) * t4_6 + (1. / 55296) * t4_8 + (1. / 270336) * t4_10; + v += (1. / 53760) * t5_6 + (1. / 276480) * t5_8 + (1. / 1.35168e+06) * t5_10; + u -= (1. / 322560) * t6_6 + (1. / 1.65888e+06) * t6_8 + (1. / 8.11008e+06) * t6_10; + v -= (1. / 1.16122e+07) * t7_8 + (1. / 5.67706e+07) * t7_10; + u += (1. / 9.28973e+07) * t8_8 + (1. / 4.54164e+08) * t8_10; + v += (1. / 4.08748e+09) * t9_10; + u -= (1. / 4.08748e+10) * t10_10; #endif #if ORDER == 14 - double t1_1 = km0; - double t1_2 = .5 * km1; - double t1_3 = (1./6) * km2; - double t1_4 = (1./24) * km3; - double t2_2 = t1_1 * t1_1; - double t2_3 = 2 * (t1_1 * t1_2); - double t2_4 = 2 * (t1_1 * t1_3) + t1_2 * t1_2; - double t2_5 = 2 * (t1_1 * t1_4 + t1_2 * t1_3); - double t2_6 = 2 * (t1_2 * t1_4) + t1_3 * t1_3; - double t2_7 = 2 * (t1_3 * t1_4); - double t2_8 = t1_4 * t1_4; - double t3_4 = t2_2 * t1_2 + t2_3 * t1_1; - double t3_6 = t2_2 * t1_4 + t2_3 * t1_3 + t2_4 * t1_2 + t2_5 * t1_1; - double t3_8 = t2_4 * t1_4 + t2_5 * t1_3 + t2_6 * t1_2 + t2_7 * t1_1; - double t3_10 = t2_6 * t1_4 + t2_7 * t1_3 + t2_8 * t1_2; - double t3_12 = t2_8 * t1_4; - double t4_4 = t2_2 * t2_2; - double t4_5 = 2 * (t2_2 * t2_3); - double t4_6 = 2 * (t2_2 * t2_4) + t2_3 * t2_3; - double t4_7 = 2 * (t2_2 * t2_5 + t2_3 * t2_4); - double t4_8 = 2 * (t2_2 * t2_6 + t2_3 * t2_5) + t2_4 * t2_4; - double t4_9 = 2 * (t2_2 * t2_7 + t2_3 * t2_6 + t2_4 * t2_5); - double t4_10 = 2 * (t2_2 * t2_8 + t2_3 * t2_7 + t2_4 * t2_6) + t2_5 * t2_5; - double t4_11 = 2 * (t2_3 * t2_8 + t2_4 * t2_7 + t2_5 * t2_6); - double t4_12 = 2 * (t2_4 * t2_8 + t2_5 * t2_7) + t2_6 * t2_6; - double t5_6 = t4_4 * t1_2 + t4_5 * t1_1; - double t5_8 = t4_4 * t1_4 + t4_5 * t1_3 + t4_6 * t1_2 + t4_7 * t1_1; - double t5_10 = t4_6 * t1_4 + t4_7 * t1_3 + t4_8 * t1_2 + t4_9 * t1_1; - double t5_12 = t4_8 * t1_4 + t4_9 * t1_3 + t4_10 * t1_2 + t4_11 * t1_1; - double t6_6 = t4_4 * t2_2; - double t6_7 = t4_4 * t2_3 + t4_5 * t2_2; - double t6_8 = t4_4 * t2_4 + t4_5 * t2_3 + t4_6 * t2_2; - double t6_9 = t4_4 * t2_5 + t4_5 * t2_4 + t4_6 * t2_3 + t4_7 * t2_2; - double t6_10 = t4_4 * t2_6 + t4_5 * t2_5 + t4_6 * t2_4 + t4_7 * t2_3 + t4_8 * t2_2; - double t6_11 = t4_4 * t2_7 + t4_5 * t2_6 + t4_6 * t2_5 + t4_7 * t2_4 + t4_8 * t2_3 + t4_9 * t2_2; - double t6_12 = t4_4 * t2_8 + t4_5 * t2_7 + t4_6 * t2_6 + t4_7 * t2_5 + t4_8 * t2_4 + t4_9 * t2_3 + t4_10 * t2_2; - double t7_8 = t6_6 * t1_2 + t6_7 * t1_1; - double t7_10 = t6_6 * t1_4 + t6_7 * t1_3 + t6_8 * t1_2 + t6_9 * t1_1; - double t7_12 = t6_8 * t1_4 + t6_9 * t1_3 + t6_10 * t1_2 + t6_11 * t1_1; - double t8_8 = t6_6 * t2_2; - double t8_9 = t6_6 * t2_3 + t6_7 * t2_2; - double t8_10 = t6_6 * t2_4 + t6_7 * t2_3 + t6_8 * t2_2; - double t8_11 = t6_6 * t2_5 + t6_7 * t2_4 + t6_8 * t2_3 + t6_9 * t2_2; - double t8_12 = t6_6 * t2_6 + t6_7 * t2_5 + t6_8 * t2_4 + t6_9 * t2_3 + t6_10 * t2_2; - double t9_10 = t8_8 * t1_2 + t8_9 * t1_1; - double t9_12 = t8_8 * t1_4 + t8_9 * t1_3 + t8_10 * t1_2 + t8_11 * t1_1; - double t10_10 = t8_8 * t2_2; - double t10_11 = t8_8 * t2_3 + t8_9 * t2_2; - double t10_12 = t8_8 * t2_4 + t8_9 * t2_3 + t8_10 * t2_2; - double t11_12 = t10_10 * t1_2 + t10_11 * t1_1; - double t12_12 = t10_10 * t2_2; - u = 1; - v = 0; - v += (1./12) * t1_2 + (1./80) * t1_4; - u -= (1./24) * t2_2 + (1./160) * t2_4 + (1./896) * t2_6 + (1./4608) * t2_8; - v -= (1./480) * t3_4 + (1./2688) * t3_6 + (1./13824) * t3_8 + (1./67584) * t3_10 + (1./319488) * t3_12; - u += (1./1920) * t4_4 + (1./10752) * t4_6 + (1./55296) * t4_8 + (1./270336) * t4_10 + (1./1.27795e+06) * t4_12; - v += (1./53760) * t5_6 + (1./276480) * t5_8 + (1./1.35168e+06) * t5_10 + (1./6.38976e+06) * t5_12; - u -= (1./322560) * t6_6 + (1./1.65888e+06) * t6_8 + (1./8.11008e+06) * t6_10 + (1./3.83386e+07) * t6_12; - v -= (1./1.16122e+07) * t7_8 + (1./5.67706e+07) * t7_10 + (1./2.6837e+08) * t7_12; - u += (1./9.28973e+07) * t8_8 + (1./4.54164e+08) * t8_10 + (1./2.14696e+09) * t8_12; - v += (1./4.08748e+09) * t9_10 + (1./1.93226e+10) * t9_12; - u -= (1./4.08748e+10) * t10_10 + (1./1.93226e+11) * t10_12; - v -= (1./2.12549e+12) * t11_12; - u += (1./2.55059e+13) * t12_12; + double t1_1 = km0; + double t1_2 = .5 * km1; + double t1_3 = (1. / 6) * km2; + double t1_4 = (1. / 24) * km3; + double t2_2 = t1_1 * t1_1; + double t2_3 = 2 * (t1_1 * t1_2); + double t2_4 = 2 * (t1_1 * t1_3) + t1_2 * t1_2; + double t2_5 = 2 * (t1_1 * t1_4 + t1_2 * t1_3); + double t2_6 = 2 * (t1_2 * t1_4) + t1_3 * t1_3; + double t2_7 = 2 * (t1_3 * t1_4); + double t2_8 = t1_4 * t1_4; + double t3_4 = t2_2 * t1_2 + t2_3 * t1_1; + double t3_6 = t2_2 * t1_4 + t2_3 * t1_3 + t2_4 * t1_2 + t2_5 * t1_1; + double t3_8 = t2_4 * t1_4 + t2_5 * t1_3 + t2_6 * t1_2 + t2_7 * t1_1; + double t3_10 = t2_6 * t1_4 + t2_7 * t1_3 + t2_8 * t1_2; + double t3_12 = t2_8 * t1_4; + double t4_4 = t2_2 * t2_2; + double t4_5 = 2 * (t2_2 * t2_3); + double t4_6 = 2 * (t2_2 * t2_4) + t2_3 * t2_3; + double t4_7 = 2 * (t2_2 * t2_5 + t2_3 * t2_4); + double t4_8 = 2 * (t2_2 * t2_6 + t2_3 * t2_5) + t2_4 * t2_4; + double t4_9 = 2 * (t2_2 * t2_7 + t2_3 * t2_6 + t2_4 * t2_5); + double t4_10 = 2 * (t2_2 * t2_8 + t2_3 * t2_7 + t2_4 * t2_6) + t2_5 * t2_5; + double t4_11 = 2 * (t2_3 * t2_8 + t2_4 * t2_7 + t2_5 * t2_6); + double t4_12 = 2 * (t2_4 * t2_8 + t2_5 * t2_7) + t2_6 * t2_6; + double t5_6 = t4_4 * t1_2 + t4_5 * t1_1; + double t5_8 = t4_4 * t1_4 + t4_5 * t1_3 + t4_6 * t1_2 + t4_7 * t1_1; + double t5_10 = t4_6 * t1_4 + t4_7 * t1_3 + t4_8 * t1_2 + t4_9 * t1_1; + double t5_12 = t4_8 * t1_4 + t4_9 * t1_3 + t4_10 * t1_2 + t4_11 * t1_1; + double t6_6 = t4_4 * t2_2; + double t6_7 = t4_4 * t2_3 + t4_5 * t2_2; + double t6_8 = t4_4 * t2_4 + t4_5 * t2_3 + t4_6 * t2_2; + double t6_9 = t4_4 * t2_5 + t4_5 * t2_4 + t4_6 * t2_3 + t4_7 * t2_2; + double t6_10 = t4_4 * t2_6 + t4_5 * t2_5 + t4_6 * t2_4 + t4_7 * t2_3 + t4_8 * t2_2; + double t6_11 = t4_4 * t2_7 + t4_5 * t2_6 + t4_6 * t2_5 + t4_7 * t2_4 + t4_8 * t2_3 + t4_9 * t2_2; + double t6_12 = + t4_4 * t2_8 + t4_5 * t2_7 + t4_6 * t2_6 + t4_7 * t2_5 + t4_8 * t2_4 + t4_9 * t2_3 + t4_10 * t2_2; + double t7_8 = t6_6 * t1_2 + t6_7 * t1_1; + double t7_10 = t6_6 * t1_4 + t6_7 * t1_3 + t6_8 * t1_2 + t6_9 * t1_1; + double t7_12 = t6_8 * t1_4 + t6_9 * t1_3 + t6_10 * t1_2 + t6_11 * t1_1; + double t8_8 = t6_6 * t2_2; + double t8_9 = t6_6 * t2_3 + t6_7 * t2_2; + double t8_10 = t6_6 * t2_4 + t6_7 * t2_3 + t6_8 * t2_2; + double t8_11 = t6_6 * t2_5 + t6_7 * t2_4 + t6_8 * t2_3 + t6_9 * t2_2; + double t8_12 = t6_6 * t2_6 + t6_7 * t2_5 + t6_8 * t2_4 + t6_9 * t2_3 + t6_10 * t2_2; + double t9_10 = t8_8 * t1_2 + t8_9 * t1_1; + double t9_12 = t8_8 * t1_4 + t8_9 * t1_3 + t8_10 * t1_2 + t8_11 * t1_1; + double t10_10 = t8_8 * t2_2; + double t10_11 = t8_8 * t2_3 + t8_9 * t2_2; + double t10_12 = t8_8 * t2_4 + t8_9 * t2_3 + t8_10 * t2_2; + double t11_12 = t10_10 * t1_2 + t10_11 * t1_1; + double t12_12 = t10_10 * t2_2; + u = 1; + v = 0; + v += (1. / 12) * t1_2 + (1. / 80) * t1_4; + u -= (1. / 24) * t2_2 + (1. / 160) * t2_4 + (1. / 896) * t2_6 + (1. / 4608) * t2_8; + v -= (1. / 480) * t3_4 + (1. / 2688) * t3_6 + (1. / 13824) * t3_8 + (1. / 67584) * t3_10 + + (1. / 319488) * t3_12; + u += (1. / 1920) * t4_4 + (1. / 10752) * t4_6 + (1. / 55296) * t4_8 + (1. / 270336) * t4_10 + + (1. / 1.27795e+06) * t4_12; + v += (1. / 53760) * t5_6 + (1. / 276480) * t5_8 + (1. / 1.35168e+06) * t5_10 + (1. / 6.38976e+06) * t5_12; + u -= (1. / 322560) * t6_6 + (1. / 1.65888e+06) * t6_8 + (1. / 8.11008e+06) * t6_10 + + (1. / 3.83386e+07) * t6_12; + v -= (1. / 1.16122e+07) * t7_8 + (1. / 5.67706e+07) * t7_10 + (1. / 2.6837e+08) * t7_12; + u += (1. / 9.28973e+07) * t8_8 + (1. / 4.54164e+08) * t8_10 + (1. / 2.14696e+09) * t8_12; + v += (1. / 4.08748e+09) * t9_10 + (1. / 1.93226e+10) * t9_12; + u -= (1. / 4.08748e+10) * t10_10 + (1. / 1.93226e+11) * t10_12; + v -= (1. / 2.12549e+12) * t11_12; + u += (1. / 2.55059e+13) * t12_12; #endif #if ORDER == 16 - double t1_1 = km0; - double t1_2 = .5 * km1; - double t1_3 = (1./6) * km2; - double t1_4 = (1./24) * km3; - double t2_2 = t1_1 * t1_1; - double t2_3 = 2 * (t1_1 * t1_2); - double t2_4 = 2 * (t1_1 * t1_3) + t1_2 * t1_2; - double t2_5 = 2 * (t1_1 * t1_4 + t1_2 * t1_3); - double t2_6 = 2 * (t1_2 * t1_4) + t1_3 * t1_3; - double t2_7 = 2 * (t1_3 * t1_4); - double t2_8 = t1_4 * t1_4; - double t3_4 = t2_2 * t1_2 + t2_3 * t1_1; - double t3_6 = t2_2 * t1_4 + t2_3 * t1_3 + t2_4 * t1_2 + t2_5 * t1_1; - double t3_8 = t2_4 * t1_4 + t2_5 * t1_3 + t2_6 * t1_2 + t2_7 * t1_1; - double t3_10 = t2_6 * t1_4 + t2_7 * t1_3 + t2_8 * t1_2; - double t3_12 = t2_8 * t1_4; - double t4_4 = t2_2 * t2_2; - double t4_5 = 2 * (t2_2 * t2_3); - double t4_6 = 2 * (t2_2 * t2_4) + t2_3 * t2_3; - double t4_7 = 2 * (t2_2 * t2_5 + t2_3 * t2_4); - double t4_8 = 2 * (t2_2 * t2_6 + t2_3 * t2_5) + t2_4 * t2_4; - double t4_9 = 2 * (t2_2 * t2_7 + t2_3 * t2_6 + t2_4 * t2_5); - double t4_10 = 2 * (t2_2 * t2_8 + t2_3 * t2_7 + t2_4 * t2_6) + t2_5 * t2_5; - double t4_11 = 2 * (t2_3 * t2_8 + t2_4 * t2_7 + t2_5 * t2_6); - double t4_12 = 2 * (t2_4 * t2_8 + t2_5 * t2_7) + t2_6 * t2_6; - double t4_13 = 2 * (t2_5 * t2_8 + t2_6 * t2_7); - double t4_14 = 2 * (t2_6 * t2_8) + t2_7 * t2_7; - double t5_6 = t4_4 * t1_2 + t4_5 * t1_1; - double t5_8 = t4_4 * t1_4 + t4_5 * t1_3 + t4_6 * t1_2 + t4_7 * t1_1; - double t5_10 = t4_6 * t1_4 + t4_7 * t1_3 + t4_8 * t1_2 + t4_9 * t1_1; - double t5_12 = t4_8 * t1_4 + t4_9 * t1_3 + t4_10 * t1_2 + t4_11 * t1_1; - double t5_14 = t4_10 * t1_4 + t4_11 * t1_3 + t4_12 * t1_2 + t4_13 * t1_1; - double t6_6 = t4_4 * t2_2; - double t6_7 = t4_4 * t2_3 + t4_5 * t2_2; - double t6_8 = t4_4 * t2_4 + t4_5 * t2_3 + t4_6 * t2_2; - double t6_9 = t4_4 * t2_5 + t4_5 * t2_4 + t4_6 * t2_3 + t4_7 * t2_2; - double t6_10 = t4_4 * t2_6 + t4_5 * t2_5 + t4_6 * t2_4 + t4_7 * t2_3 + t4_8 * t2_2; - double t6_11 = t4_4 * t2_7 + t4_5 * t2_6 + t4_6 * t2_5 + t4_7 * t2_4 + t4_8 * t2_3 + t4_9 * t2_2; - double t6_12 = t4_4 * t2_8 + t4_5 * t2_7 + t4_6 * t2_6 + t4_7 * t2_5 + t4_8 * t2_4 + t4_9 * t2_3 + t4_10 * t2_2; - double t6_13 = t4_5 * t2_8 + t4_6 * t2_7 + t4_7 * t2_6 + t4_8 * t2_5 + t4_9 * t2_4 + t4_10 * t2_3 + t4_11 * t2_2; - double t6_14 = t4_6 * t2_8 + t4_7 * t2_7 + t4_8 * t2_6 + t4_9 * t2_5 + t4_10 * t2_4 + t4_11 * t2_3 + t4_12 * t2_2; - double t7_8 = t6_6 * t1_2 + t6_7 * t1_1; - double t7_10 = t6_6 * t1_4 + t6_7 * t1_3 + t6_8 * t1_2 + t6_9 * t1_1; - double t7_12 = t6_8 * t1_4 + t6_9 * t1_3 + t6_10 * t1_2 + t6_11 * t1_1; - double t7_14 = t6_10 * t1_4 + t6_11 * t1_3 + t6_12 * t1_2 + t6_13 * t1_1; - double t8_8 = t6_6 * t2_2; - double t8_9 = t6_6 * t2_3 + t6_7 * t2_2; - double t8_10 = t6_6 * t2_4 + t6_7 * t2_3 + t6_8 * t2_2; - double t8_11 = t6_6 * t2_5 + t6_7 * t2_4 + t6_8 * t2_3 + t6_9 * t2_2; - double t8_12 = t6_6 * t2_6 + t6_7 * t2_5 + t6_8 * t2_4 + t6_9 * t2_3 + t6_10 * t2_2; - double t8_13 = t6_6 * t2_7 + t6_7 * t2_6 + t6_8 * t2_5 + t6_9 * t2_4 + t6_10 * t2_3 + t6_11 * t2_2; - double t8_14 = t6_6 * t2_8 + t6_7 * t2_7 + t6_8 * t2_6 + t6_9 * t2_5 + t6_10 * t2_4 + t6_11 * t2_3 + t6_12 * t2_2; - double t9_10 = t8_8 * t1_2 + t8_9 * t1_1; - double t9_12 = t8_8 * t1_4 + t8_9 * t1_3 + t8_10 * t1_2 + t8_11 * t1_1; - double t9_14 = t8_10 * t1_4 + t8_11 * t1_3 + t8_12 * t1_2 + t8_13 * t1_1; - double t10_10 = t8_8 * t2_2; - double t10_11 = t8_8 * t2_3 + t8_9 * t2_2; - double t10_12 = t8_8 * t2_4 + t8_9 * t2_3 + t8_10 * t2_2; - double t10_13 = t8_8 * t2_5 + t8_9 * t2_4 + t8_10 * t2_3 + t8_11 * t2_2; - double t10_14 = t8_8 * t2_6 + t8_9 * t2_5 + t8_10 * t2_4 + t8_11 * t2_3 + t8_12 * t2_2; - double t11_12 = t10_10 * t1_2 + t10_11 * t1_1; - double t11_14 = t10_10 * t1_4 + t10_11 * t1_3 + t10_12 * t1_2 + t10_13 * t1_1; - double t12_12 = t10_10 * t2_2; - double t12_13 = t10_10 * t2_3 + t10_11 * t2_2; - double t12_14 = t10_10 * t2_4 + t10_11 * t2_3 + t10_12 * t2_2; - double t13_14 = t12_12 * t1_2 + t12_13 * t1_1; - double t14_14 = t12_12 * t2_2; - u = 1; - u -= 1./24 * t2_2 + 1./160 * t2_4 + 1./896 * t2_6 + 1./4608 * t2_8; - u += 1./1920 * t4_4 + 1./10752 * t4_6 + 1./55296 * t4_8 + 1./270336 * t4_10 + 1./1277952 * t4_12 + 1./5898240 * t4_14; - u -= 1./322560 * t6_6 + 1./1658880 * t6_8 + 1./8110080 * t6_10 + 1./38338560 * t6_12 + 1./176947200 * t6_14; - u += 1./92897280 * t8_8 + 1./454164480 * t8_10 + 4.6577500191e-10 * t8_12 + 1.0091791708e-10 * t8_14; - u -= 2.4464949595e-11 * t10_10 + 5.1752777990e-12 * t10_12 + 1.1213101898e-12 * t10_14; - u += 3.9206649992e-14 * t12_12 + 8.4947741650e-15 * t12_14; - u -= 4.6674583324e-17 * t14_14; - v = 0; - v += 1./12 * t1_2 + 1./80 * t1_4; - v -= 1./480 * t3_4 + 1./2688 * t3_6 + 1./13824 * t3_8 + 1./67584 * t3_10 + 1./319488 * t3_12; - v += 1./53760 * t5_6 + 1./276480 * t5_8 + 1./1351680 * t5_10 + 1./6389760 * t5_12 + 1./29491200 * t5_14; - v -= 1./11612160 * t7_8 + 1./56770560 * t7_10 + 1./268369920 * t7_12 + 8.0734333664e-10 * t7_14; - v += 2.4464949595e-10 * t9_10 + 5.1752777990e-11 * t9_12 + 1.1213101898e-11 * t9_14; - v -= 4.7047979991e-13 * t11_12 + 1.0193728998e-13 * t11_14; - v += 6.5344416654e-16 * t13_14; + double t1_1 = km0; + double t1_2 = .5 * km1; + double t1_3 = (1. / 6) * km2; + double t1_4 = (1. / 24) * km3; + double t2_2 = t1_1 * t1_1; + double t2_3 = 2 * (t1_1 * t1_2); + double t2_4 = 2 * (t1_1 * t1_3) + t1_2 * t1_2; + double t2_5 = 2 * (t1_1 * t1_4 + t1_2 * t1_3); + double t2_6 = 2 * (t1_2 * t1_4) + t1_3 * t1_3; + double t2_7 = 2 * (t1_3 * t1_4); + double t2_8 = t1_4 * t1_4; + double t3_4 = t2_2 * t1_2 + t2_3 * t1_1; + double t3_6 = t2_2 * t1_4 + t2_3 * t1_3 + t2_4 * t1_2 + t2_5 * t1_1; + double t3_8 = t2_4 * t1_4 + t2_5 * t1_3 + t2_6 * t1_2 + t2_7 * t1_1; + double t3_10 = t2_6 * t1_4 + t2_7 * t1_3 + t2_8 * t1_2; + double t3_12 = t2_8 * t1_4; + double t4_4 = t2_2 * t2_2; + double t4_5 = 2 * (t2_2 * t2_3); + double t4_6 = 2 * (t2_2 * t2_4) + t2_3 * t2_3; + double t4_7 = 2 * (t2_2 * t2_5 + t2_3 * t2_4); + double t4_8 = 2 * (t2_2 * t2_6 + t2_3 * t2_5) + t2_4 * t2_4; + double t4_9 = 2 * (t2_2 * t2_7 + t2_3 * t2_6 + t2_4 * t2_5); + double t4_10 = 2 * (t2_2 * t2_8 + t2_3 * t2_7 + t2_4 * t2_6) + t2_5 * t2_5; + double t4_11 = 2 * (t2_3 * t2_8 + t2_4 * t2_7 + t2_5 * t2_6); + double t4_12 = 2 * (t2_4 * t2_8 + t2_5 * t2_7) + t2_6 * t2_6; + double t4_13 = 2 * (t2_5 * t2_8 + t2_6 * t2_7); + double t4_14 = 2 * (t2_6 * t2_8) + t2_7 * t2_7; + double t5_6 = t4_4 * t1_2 + t4_5 * t1_1; + double t5_8 = t4_4 * t1_4 + t4_5 * t1_3 + t4_6 * t1_2 + t4_7 * t1_1; + double t5_10 = t4_6 * t1_4 + t4_7 * t1_3 + t4_8 * t1_2 + t4_9 * t1_1; + double t5_12 = t4_8 * t1_4 + t4_9 * t1_3 + t4_10 * t1_2 + t4_11 * t1_1; + double t5_14 = t4_10 * t1_4 + t4_11 * t1_3 + t4_12 * t1_2 + t4_13 * t1_1; + double t6_6 = t4_4 * t2_2; + double t6_7 = t4_4 * t2_3 + t4_5 * t2_2; + double t6_8 = t4_4 * t2_4 + t4_5 * t2_3 + t4_6 * t2_2; + double t6_9 = t4_4 * t2_5 + t4_5 * t2_4 + t4_6 * t2_3 + t4_7 * t2_2; + double t6_10 = t4_4 * t2_6 + t4_5 * t2_5 + t4_6 * t2_4 + t4_7 * t2_3 + t4_8 * t2_2; + double t6_11 = t4_4 * t2_7 + t4_5 * t2_6 + t4_6 * t2_5 + t4_7 * t2_4 + t4_8 * t2_3 + t4_9 * t2_2; + double t6_12 = + t4_4 * t2_8 + t4_5 * t2_7 + t4_6 * t2_6 + t4_7 * t2_5 + t4_8 * t2_4 + t4_9 * t2_3 + t4_10 * t2_2; + double t6_13 = + t4_5 * t2_8 + t4_6 * t2_7 + t4_7 * t2_6 + t4_8 * t2_5 + t4_9 * t2_4 + t4_10 * t2_3 + t4_11 * t2_2; + double t6_14 = + t4_6 * t2_8 + t4_7 * t2_7 + t4_8 * t2_6 + t4_9 * t2_5 + t4_10 * t2_4 + t4_11 * t2_3 + t4_12 * t2_2; + double t7_8 = t6_6 * t1_2 + t6_7 * t1_1; + double t7_10 = t6_6 * t1_4 + t6_7 * t1_3 + t6_8 * t1_2 + t6_9 * t1_1; + double t7_12 = t6_8 * t1_4 + t6_9 * t1_3 + t6_10 * t1_2 + t6_11 * t1_1; + double t7_14 = t6_10 * t1_4 + t6_11 * t1_3 + t6_12 * t1_2 + t6_13 * t1_1; + double t8_8 = t6_6 * t2_2; + double t8_9 = t6_6 * t2_3 + t6_7 * t2_2; + double t8_10 = t6_6 * t2_4 + t6_7 * t2_3 + t6_8 * t2_2; + double t8_11 = t6_6 * t2_5 + t6_7 * t2_4 + t6_8 * t2_3 + t6_9 * t2_2; + double t8_12 = t6_6 * t2_6 + t6_7 * t2_5 + t6_8 * t2_4 + t6_9 * t2_3 + t6_10 * t2_2; + double t8_13 = t6_6 * t2_7 + t6_7 * t2_6 + t6_8 * t2_5 + t6_9 * t2_4 + t6_10 * t2_3 + t6_11 * t2_2; + double t8_14 = + t6_6 * t2_8 + t6_7 * t2_7 + t6_8 * t2_6 + t6_9 * t2_5 + t6_10 * t2_4 + t6_11 * t2_3 + t6_12 * t2_2; + double t9_10 = t8_8 * t1_2 + t8_9 * t1_1; + double t9_12 = t8_8 * t1_4 + t8_9 * t1_3 + t8_10 * t1_2 + t8_11 * t1_1; + double t9_14 = t8_10 * t1_4 + t8_11 * t1_3 + t8_12 * t1_2 + t8_13 * t1_1; + double t10_10 = t8_8 * t2_2; + double t10_11 = t8_8 * t2_3 + t8_9 * t2_2; + double t10_12 = t8_8 * t2_4 + t8_9 * t2_3 + t8_10 * t2_2; + double t10_13 = t8_8 * t2_5 + t8_9 * t2_4 + t8_10 * t2_3 + t8_11 * t2_2; + double t10_14 = t8_8 * t2_6 + t8_9 * t2_5 + t8_10 * t2_4 + t8_11 * t2_3 + t8_12 * t2_2; + double t11_12 = t10_10 * t1_2 + t10_11 * t1_1; + double t11_14 = t10_10 * t1_4 + t10_11 * t1_3 + t10_12 * t1_2 + t10_13 * t1_1; + double t12_12 = t10_10 * t2_2; + double t12_13 = t10_10 * t2_3 + t10_11 * t2_2; + double t12_14 = t10_10 * t2_4 + t10_11 * t2_3 + t10_12 * t2_2; + double t13_14 = t12_12 * t1_2 + t12_13 * t1_1; + double t14_14 = t12_12 * t2_2; + u = 1; + u -= 1. / 24 * t2_2 + 1. / 160 * t2_4 + 1. / 896 * t2_6 + 1. / 4608 * t2_8; + u += 1. / 1920 * t4_4 + 1. / 10752 * t4_6 + 1. / 55296 * t4_8 + 1. / 270336 * t4_10 + 1. / 1277952 * t4_12 + + 1. / 5898240 * t4_14; + u -= 1. / 322560 * t6_6 + 1. / 1658880 * t6_8 + 1. / 8110080 * t6_10 + 1. / 38338560 * t6_12 + + 1. / 176947200 * t6_14; + u += 1. / 92897280 * t8_8 + 1. / 454164480 * t8_10 + 4.6577500191e-10 * t8_12 + 1.0091791708e-10 * t8_14; + u -= 2.4464949595e-11 * t10_10 + 5.1752777990e-12 * t10_12 + 1.1213101898e-12 * t10_14; + u += 3.9206649992e-14 * t12_12 + 8.4947741650e-15 * t12_14; + u -= 4.6674583324e-17 * t14_14; + v = 0; + v += 1. / 12 * t1_2 + 1. / 80 * t1_4; + v -= 1. / 480 * t3_4 + 1. / 2688 * t3_6 + 1. / 13824 * t3_8 + 1. / 67584 * t3_10 + 1. / 319488 * t3_12; + v += 1. / 53760 * t5_6 + 1. / 276480 * t5_8 + 1. / 1351680 * t5_10 + 1. / 6389760 * t5_12 + + 1. / 29491200 * t5_14; + v -= 1. / 11612160 * t7_8 + 1. / 56770560 * t7_10 + 1. / 268369920 * t7_12 + 8.0734333664e-10 * t7_14; + v += 2.4464949595e-10 * t9_10 + 5.1752777990e-11 * t9_12 + 1.1213101898e-11 * t9_14; + v -= 4.7047979991e-13 * t11_12 + 1.0193728998e-13 * t11_14; + v += 6.5344416654e-16 * t13_14; #endif + } - } - - if (n == 1) { + if (n == 1) { #if ORDER == 2 - x = 1; - y = 0; + x = 1; + y = 0; #else - x = u; - y = v; + x = u; + y = v; #endif - } else { - double th = (((th4 * s + th3) * s + th2) * s + th1) * s; - double cth = cos(th); - double sth = sin(th); + } else { + double th = (((th4 * s + th3) * s + th2) * s + th1) * s; + double cth = cos(th); + double sth = sin(th); #if ORDER == 2 - x += cth; - y += sth; + x += cth; + y += sth; #else - x += cth * u - sth * v; - y += cth * v + sth * u; + x += cth * u - sth * v; + y += cth * v + sth * u; #endif - s += ds; - } + s += ds; + } } #if ORDER == 4 || ORDER == 6 - xy[0] = x * (1./24 * ds); - xy[1] = y * (1./24 * ds); + xy[0] = x * (1. / 24 * ds); + xy[1] = y * (1. / 24 * ds); #else xy[0] = x * ds; xy[1] = y * ds; #endif } -static double -compute_ends(const double ks[4], double ends[2][4], double seg_ch) +static double compute_ends(const double ks[4], double ends[2][4], double seg_ch) { double xy[2]; double ch, th; @@ -450,12 +457,12 @@ compute_ends(const double ks[4], double ends[2][4], double seg_ch) th = atan2(xy[1], xy[0]); l = ch / seg_ch; - th_even = .5 * ks[0] + (1./48) * ks[2]; - th_odd = .125 * ks[1] + (1./384) * ks[3] - th; + th_even = .5 * ks[0] + (1. / 48) * ks[2]; + th_odd = .125 * ks[1] + (1. / 384) * ks[3] - th; ends[0][0] = th_even - th_odd; ends[1][0] = th_even + th_odd; k0_even = l * (ks[0] + .125 * ks[2]); - k0_odd = l * (.5 * ks[1] + (1./48) * ks[3]); + k0_odd = l * (.5 * ks[1] + (1. / 48) * ks[3]); ends[0][1] = k0_even - k0_odd; ends[1][1] = k0_even + k0_odd; l2 = l * l; @@ -472,37 +479,33 @@ compute_ends(const double ks[4], double ends[2][4], double seg_ch) return l; } -static void -compute_pderivs(const spiro_seg *s, double ends[2][4], double derivs[4][2][4], - int jinc) +static void compute_pderivs(const spiro_seg *s, double ends[2][4], double derivs[4][2][4], int jinc) { double recip_d = 2e6; - double delta = 1./ recip_d; + double delta = 1. / recip_d; double try_ks[4]; double try_ends[2][4]; int i, j, k; compute_ends(s->ks, ends, s->seg_ch); for (i = 0; i < jinc; i++) { - for (j = 0; j < 4; j++) - try_ks[j] = s->ks[j]; - try_ks[i] += delta; - compute_ends(try_ks, try_ends, s->seg_ch); - for (k = 0; k < 2; k++) - for (j = 0; j < 4; j++) - derivs[j][k][i] = recip_d * (try_ends[k][j] - ends[k][j]); + for (j = 0; j < 4; j++) + try_ks[j] = s->ks[j]; + try_ks[i] += delta; + compute_ends(try_ks, try_ends, s->seg_ch); + for (k = 0; k < 2; k++) + for (j = 0; j < 4; j++) + derivs[j][k][i] = recip_d * (try_ends[k][j] - ends[k][j]); } } -static double -mod_2pi(double th) +static double mod_2pi(double th) { double u = th / (2 * M_PI); return 2 * M_PI * (u - floor(u + 0.5)); } -static spiro_seg * -setup_path(const spiro_cp *src, int n) +static spiro_seg *setup_path(const spiro_cp *src, int n) { int n_seg = src[0].ty == '{' ? n - 1 : n; spiro_seg *r = (spiro_seg *)malloc((n_seg + 1) * sizeof(spiro_seg)); @@ -510,126 +513,126 @@ setup_path(const spiro_cp *src, int n) int ilast; for (i = 0; i < n_seg; i++) { - r[i].x = src[i].x; - r[i].y = src[i].y; - r[i].ty = src[i].ty; - r[i].ks[0] = 0.; - r[i].ks[1] = 0.; - r[i].ks[2] = 0.; - r[i].ks[3] = 0.; + r[i].x = src[i].x; + r[i].y = src[i].y; + r[i].ty = src[i].ty; + r[i].ks[0] = 0.; + r[i].ks[1] = 0.; + r[i].ks[2] = 0.; + r[i].ks[3] = 0.; } r[n_seg].x = src[n_seg % n].x; r[n_seg].y = src[n_seg % n].y; r[n_seg].ty = src[n_seg % n].ty; for (i = 0; i < n_seg; i++) { - double dx = r[i + 1].x - r[i].x; - double dy = r[i + 1].y - r[i].y; - r[i].seg_ch = hypot(dx, dy); - r[i].seg_th = atan2(dy, dx); + double dx = r[i + 1].x - r[i].x; + double dy = r[i + 1].y - r[i].y; + r[i].seg_ch = hypot(dx, dy); + r[i].seg_th = atan2(dy, dx); } ilast = n_seg - 1; for (i = 0; i < n_seg; i++) { - if (r[i].ty == '{' || r[i].ty == '}' || r[i].ty == 'v') - r[i].bend_th = 0.; - else - r[i].bend_th = mod_2pi(r[i].seg_th - r[ilast].seg_th); - ilast = i; + if (r[i].ty == '{' || r[i].ty == '}' || r[i].ty == 'v') + r[i].bend_th = 0.; + else + r[i].bend_th = mod_2pi(r[i].seg_th - r[ilast].seg_th); + ilast = i; } return r; } -static void -bandec11(bandmat *m, int *perm, int n) +static void bandec11(bandmat *m, int *perm, int n) { int i, j, k; int l; /* pack top triangle to the left. */ for (i = 0; i < 5; i++) { - for (j = 0; j < i + 6; j++) - m[i].a[j] = m[i].a[j + 5 - i]; - for (; j < 11; j++) - m[i].a[j] = 0.; + for (j = 0; j < i + 6; j++) + m[i].a[j] = m[i].a[j + 5 - i]; + for (; j < 11; j++) + m[i].a[j] = 0.; } l = 5; for (k = 0; k < n; k++) { - int pivot = k; - double pivot_val = m[k].a[0]; - double pivot_scale; - - l = l < n ? l + 1 : n; - - for (j = k + 1; j < l; j++) - if (fabs(m[j].a[0]) > fabs(pivot_val)) { - pivot_val = m[j].a[0]; - pivot = j; - } - - perm[k] = pivot; - if (pivot != k) { - for (j = 0; j < 11; j++) { - double tmp = m[k].a[j]; - m[k].a[j] = m[pivot].a[j]; - m[pivot].a[j] = tmp; - } - } - - if (fabs(pivot_val) < 1e-12) pivot_val = 1e-12; - pivot_scale = 1. / pivot_val; - for (i = k + 1; i < l; i++) { - double x = m[i].a[0] * pivot_scale; - m[k].al[i - k - 1] = x; - for (j = 1; j < 11; j++) - m[i].a[j - 1] = m[i].a[j] - x * m[k].a[j]; - m[i].a[10] = 0.; - } + int pivot = k; + double pivot_val = m[k].a[0]; + double pivot_scale; + + l = l < n ? l + 1 : n; + + for (j = k + 1; j < l; j++) + if (fabs(m[j].a[0]) > fabs(pivot_val)) { + pivot_val = m[j].a[0]; + pivot = j; + } + + perm[k] = pivot; + if (pivot != k) { + for (j = 0; j < 11; j++) { + double tmp = m[k].a[j]; + m[k].a[j] = m[pivot].a[j]; + m[pivot].a[j] = tmp; + } + } + + if (fabs(pivot_val) < 1e-12) + pivot_val = 1e-12; + pivot_scale = 1. / pivot_val; + for (i = k + 1; i < l; i++) { + double x = m[i].a[0] * pivot_scale; + m[k].al[i - k - 1] = x; + for (j = 1; j < 11; j++) + m[i].a[j - 1] = m[i].a[j] - x * m[k].a[j]; + m[i].a[10] = 0.; + } } } -static void -banbks11(const bandmat *m, const int *perm, double *v, int n) +static void banbks11(const bandmat *m, const int *perm, double *v, int n) { int i, k, l; /* forward substitution */ l = 5; for (k = 0; k < n; k++) { - i = perm[k]; - if (i != k) { - double tmp = v[k]; - v[k] = v[i]; - v[i] = tmp; - } - if (l < n) l++; - for (i = k + 1; i < l; i++) - v[i] -= m[k].al[i - k - 1] * v[k]; + i = perm[k]; + if (i != k) { + double tmp = v[k]; + v[k] = v[i]; + v[i] = tmp; + } + if (l < n) + l++; + for (i = k + 1; i < l; i++) + v[i] -= m[k].al[i - k - 1] * v[k]; } /* back substitution */ l = 1; for (i = n - 1; i >= 0; i--) { - double x = v[i]; - for (k = 1; k < l; k++) - x -= m[i].a[k] * v[k + i]; - v[i] = x / m[i].a[0]; - if (l < 11) l++; + double x = v[i]; + for (k = 1; k < l; k++) + x -= m[i].a[k] * v[k + i]; + v[i] = x / m[i].a[0]; + if (l < 11) + l++; } } static int compute_jinc(char ty0, char ty1) { - if (ty0 == 'o' || ty1 == 'o' || - ty0 == ']' || ty1 == '[') - return 4; + if (ty0 == 'o' || ty1 == 'o' || ty0 == ']' || ty1 == '[') + return 4; else if (ty0 == 'c' && ty1 == 'c') - return 2; + return 2; else if (((ty0 == '{' || ty0 == 'v' || ty0 == '[') && ty1 == 'c') || - (ty0 == 'c' && (ty1 == '}' || ty1 == 'v' || ty1 == ']'))) - return 1; + (ty0 == 'c' && (ty1 == '}' || ty1 == 'v' || ty1 == ']'))) + return 1; else - return 0; + return 0; } static int count_vec(const spiro_seg *s, int nseg) @@ -638,33 +641,29 @@ static int count_vec(const spiro_seg *s, int nseg) int n = 0; for (i = 0; i < nseg; i++) - n += compute_jinc(s[i].ty, s[i + 1].ty); + n += compute_jinc(s[i].ty, s[i + 1].ty); return n; } -static void -add_mat_line(bandmat *m, double *v, - double derivs[4], double x, double y, int j, int jj, int jinc, - int nmat) +static void add_mat_line(bandmat *m, double *v, double derivs[4], double x, double y, int j, int jj, int jinc, int nmat) { if (jj >= 0) { - int joff = (j + 5 - jj + nmat) % nmat; - if (nmat < 6) { - joff = j + 5 - jj; - } else if (nmat == 6) { - joff = 2 + (j + 3 - jj + nmat) % nmat; - } + int joff = (j + 5 - jj + nmat) % nmat; + if (nmat < 6) { + joff = j + 5 - jj; + } else if (nmat == 6) { + joff = 2 + (j + 3 - jj + nmat) % nmat; + } #ifdef VERBOSE - printf("add_mat_line j=%d jj=%d jinc=%d nmat=%d joff=%d\n", j, jj, jinc, nmat, joff); + printf("add_mat_line j=%d jj=%d jinc=%d nmat=%d joff=%d\n", j, jj, jinc, nmat, joff); #endif - v[jj] += x; - for (int k = 0; k < jinc; k++) - m[jj].a[joff + k] += y * derivs[k]; + v[jj] += x; + for (int k = 0; k < jinc; k++) + m[jj].a[joff + k] += y * derivs[k]; } } -static double -spiro_iter(spiro_seg *s, bandmat *m, int *perm, double *v, const int n) +static double spiro_iter(spiro_seg *s, bandmat *m, int *perm, double *v, const int n) { int cyclic = s[0].ty != '{' && s[0].ty != 'v'; int nmat = count_vec(s, n); @@ -672,10 +671,10 @@ spiro_iter(spiro_seg *s, bandmat *m, int *perm, double *v, const int n) for (int i = 0; i < nmat; i++) { v[i] = 0.; - for (double & j : m[i].a) { + for (double &j : m[i].a) { j = 0.; } - for (double & j : m[i].al) { + for (double &j : m[i].al) { j = 0.; } } @@ -714,18 +713,16 @@ spiro_iter(spiro_seg *s, bandmat *m, int *perm, double *v, const int n) } /* constraints on left */ - if ((ty0 == '[' || ty0 == 'v' || ty0 == '{' || ty0 == 'c') && - jinc == 4) { + if ((ty0 == '[' || ty0 == 'v' || ty0 == '{' || ty0 == 'c') && jinc == 4) { if (ty0 != 'c') - jk1l = jj++; + jk1l = jj++; jk2l = jj++; } /* constraints on right */ - if ((ty1 == ']' || ty1 == 'v' || ty1 == '}' || ty1 == 'c') && - jinc == 4) { + if ((ty1 == ']' || ty1 == 'v' || ty1 == '}' || ty1 == 'c') && jinc == 4) { if (ty1 != 'c') - jk1r = jj++; + jk1r = jj++; jk2r = jj++; } @@ -775,7 +772,7 @@ spiro_iter(spiro_seg *s, bandmat *m, int *perm, double *v, const int n) #endif bandec11(m, perm, n_invert); banbks11(m, perm, v, n_invert); - + double norm = 0.; for (int i = 0; i < n; i++) { char ty0 = s[i].ty; @@ -792,13 +789,12 @@ spiro_iter(spiro_seg *s, bandmat *m, int *perm, double *v, const int n) s[i].ks[k] += dk; norm += dk * dk; } - s[i].ks[0] = 2.0*mod_2pi(s[i].ks[0]/2.0); + s[i].ks[0] = 2.0 * mod_2pi(s[i].ks[0] / 2.0); } return norm; } -static int -solve_spiro(spiro_seg *s, const int nseg) +static int solve_spiro(spiro_seg *s, const int nseg) { int nmat = count_vec(s, nseg); int n_alloc = nmat; @@ -822,7 +818,8 @@ solve_spiro(spiro_seg *s, const int nseg) #ifdef VERBOSE printf("%% norm = %g\n", norm); #endif - if (norm < 1e-12) break; + if (norm < 1e-12) + break; } free(m); @@ -831,93 +828,87 @@ solve_spiro(spiro_seg *s, const int nseg) return 0; } -static void -spiro_seg_to_otherpath(const double ks[4], - double x0, double y0, double x1, double y1, - ConverterBase &bc, int depth, bool close_last) +static void spiro_seg_to_otherpath(const double ks[4], double x0, double y0, double x1, double y1, ConverterBase &bc, + int depth, bool close_last) { - double bend = fabs(ks[0]) + fabs(.5 * ks[1]) + fabs(.125 * ks[2]) + - fabs((1./48) * ks[3]); + double bend = fabs(ks[0]) + fabs(.5 * ks[1]) + fabs(.125 * ks[2]) + fabs((1. / 48) * ks[3]); if (!(bend > 1e-8)) { bc.lineto(x1, y1, close_last); } else { - double seg_ch = hypot(x1 - x0, y1 - y0); - double seg_th = atan2(y1 - y0, x1 - x0); - double xy[2]; - double ch, th; - double scale, rot; - - integrate_spiro(ks, xy); - ch = hypot(xy[0], xy[1]); - th = atan2(xy[1], xy[0]); - scale = seg_ch / ch; - rot = seg_th - th; - if (depth > 5 || bend < 1.) { - double ul, vl; - double ur, vr; - double th_even, th_odd; - th_even = (1./384) * ks[3] + (1./8) * ks[1] + rot; - th_odd = (1./48) * ks[2] + .5 * ks[0]; - ul = (scale * (1./3)) * cos(th_even - th_odd); - vl = (scale * (1./3)) * sin(th_even - th_odd); - ur = (scale * (1./3)) * cos(th_even + th_odd); - vr = (scale * (1./3)) * sin(th_even + th_odd); - bc.curveto(x0 + ul, y0 + vl, x1 - ur, y1 - vr, x1, y1, close_last); - } else { - /* subdivide */ - double ksub[4]; - double thsub; - double xysub[2]; - double xmid, ymid; - double cth, sth; - - ksub[0] = .5 * ks[0] - .125 * ks[1] + (1./64) * ks[2] - (1./768) * ks[3]; - ksub[1] = .25 * ks[1] - (1./16) * ks[2] + (1./128) * ks[3]; - ksub[2] = .125 * ks[2] - (1./32) * ks[3]; - ksub[3] = (1./16) * ks[3]; - thsub = rot - .25 * ks[0] + (1./32) * ks[1] - (1./384) * ks[2] + (1./6144) * ks[3]; - cth = .5 * scale * cos(thsub); - sth = .5 * scale * sin(thsub); - integrate_spiro(ksub, xysub); - xmid = x0 + cth * xysub[0] - sth * xysub[1]; - ymid = y0 + cth * xysub[1] + sth * xysub[0]; - spiro_seg_to_otherpath(ksub, x0, y0, xmid, ymid, bc, depth + 1, false); - ksub[0] += .25 * ks[1] + (1./384) * ks[3]; - ksub[1] += .125 * ks[2]; - ksub[2] += (1./16) * ks[3]; - spiro_seg_to_otherpath(ksub, xmid, ymid, x1, y1, bc, depth + 1, close_last); - } + double seg_ch = hypot(x1 - x0, y1 - y0); + double seg_th = atan2(y1 - y0, x1 - x0); + double xy[2]; + double ch, th; + double scale, rot; + + integrate_spiro(ks, xy); + ch = hypot(xy[0], xy[1]); + th = atan2(xy[1], xy[0]); + scale = seg_ch / ch; + rot = seg_th - th; + if (depth > 5 || bend < 1.) { + double ul, vl; + double ur, vr; + double th_even, th_odd; + th_even = (1. / 384) * ks[3] + (1. / 8) * ks[1] + rot; + th_odd = (1. / 48) * ks[2] + .5 * ks[0]; + ul = (scale * (1. / 3)) * cos(th_even - th_odd); + vl = (scale * (1. / 3)) * sin(th_even - th_odd); + ur = (scale * (1. / 3)) * cos(th_even + th_odd); + vr = (scale * (1. / 3)) * sin(th_even + th_odd); + bc.curveto(x0 + ul, y0 + vl, x1 - ur, y1 - vr, x1, y1, close_last); + } else { + /* subdivide */ + double ksub[4]; + double thsub; + double xysub[2]; + double xmid, ymid; + double cth, sth; + + ksub[0] = .5 * ks[0] - .125 * ks[1] + (1. / 64) * ks[2] - (1. / 768) * ks[3]; + ksub[1] = .25 * ks[1] - (1. / 16) * ks[2] + (1. / 128) * ks[3]; + ksub[2] = .125 * ks[2] - (1. / 32) * ks[3]; + ksub[3] = (1. / 16) * ks[3]; + thsub = rot - .25 * ks[0] + (1. / 32) * ks[1] - (1. / 384) * ks[2] + (1. / 6144) * ks[3]; + cth = .5 * scale * cos(thsub); + sth = .5 * scale * sin(thsub); + integrate_spiro(ksub, xysub); + xmid = x0 + cth * xysub[0] - sth * xysub[1]; + ymid = y0 + cth * xysub[1] + sth * xysub[0]; + spiro_seg_to_otherpath(ksub, x0, y0, xmid, ymid, bc, depth + 1, false); + ksub[0] += .25 * ks[1] + (1. / 384) * ks[3]; + ksub[1] += .125 * ks[2]; + ksub[2] += (1. / 16) * ks[3]; + spiro_seg_to_otherpath(ksub, xmid, ymid, x1, y1, bc, depth + 1, close_last); + } } } -spiro_seg * -run_spiro(const spiro_cp *src, int n) +spiro_seg *run_spiro(const spiro_cp *src, int n) { int nseg = src[0].ty == '{' ? n - 1 : n; spiro_seg *s = setup_path(src, n); if (nseg > 1) - solve_spiro(s, nseg); + solve_spiro(s, nseg); return s; } -void -free_spiro(spiro_seg *s) +void free_spiro(spiro_seg *s) { free(s); } -void -spiro_to_otherpath(const spiro_seg *s, int n, ConverterBase &bc) +void spiro_to_otherpath(const spiro_seg *s, int n, ConverterBase &bc) { int i; int nsegs = s[n - 1].ty == '}' ? n - 1 : n; for (i = 0; i < nsegs; i++) { - double x0 = s[i].x; - double y0 = s[i].y; - double x1 = s[i + 1].x; - double y1 = s[i + 1].y; + double x0 = s[i].x; + double y0 = s[i].y; + double x1 = s[i + 1].x; + double y1 = s[i + 1].y; if (i == 0) { bc.moveto(x0, y0); @@ -927,47 +918,43 @@ spiro_to_otherpath(const spiro_seg *s, int n, ConverterBase &bc) } } -double -get_knot_th(const spiro_seg *s, int i) +double get_knot_th(const spiro_seg *s, int i) { double ends[2][4]; if (i == 0) { - compute_ends(s[i].ks, ends, s[i].seg_ch); - return s[i].seg_th - ends[0][0]; + compute_ends(s[i].ks, ends, s[i].seg_ch); + return s[i].seg_th - ends[0][0]; } else { - compute_ends(s[i - 1].ks, ends, s[i - 1].seg_ch); - return s[i - 1].seg_th + ends[1][0]; + compute_ends(s[i - 1].ks, ends, s[i - 1].seg_ch); + return s[i - 1].seg_th + ends[1][0]; } } - } // namespace Spiro /************************************ * Unit_test code */ - #ifdef UNIT_TEST #include #include /* for gettimeofday */ using namespace Spiro; -static double -get_time (void) +static double get_time(void) { - struct timeval tv; - struct timezone tz; + struct timeval tv; + struct timezone tz; - gettimeofday (&tv, &tz); + gettimeofday(&tv, &tz); - return tv.tv_sec + 1e-6 * tv.tv_usec; + return tv.tv_sec + 1e-6 * tv.tv_usec; } -int -test_integ(void) { +int test_integ(void) +{ double ks[] = {1, 2, 3, 4}; double xy[2]; double xynom[2]; @@ -978,17 +965,17 @@ test_integ(void) { integrate_spiro(ks, xynom); nsubdiv = ORDER < 12 ? 8 : 7; for (i = 0; i < nsubdiv; i++) { - double st, en; - double err; - int n_iter = (1 << (20 - i)); - - n = 1 << i; - st = get_time(); - for (j = 0; j < n_iter; j++) - integrate_spiro(ks, xy); - en = get_time(); - err = hypot(xy[0] - xynom[0], xy[1] - xynom[1]); - printf("%d %d %g %g\n", ORDER, n, (en - st) / n_iter, err); + double st, en; + double err; + int n_iter = (1 << (20 - i)); + + n = 1 << i; + st = get_time(); + for (j = 0; j < n_iter; j++) + integrate_spiro(ks, xy); + en = get_time(); + err = hypot(xy[0] - xynom[0], xy[1] - xynom[1]); + printf("%d %d %g %g\n", ORDER, n, (en - st) / n_iter, err); #if 0 double ch, th; ch = hypot(xy[0], xy[1]); @@ -1001,113 +988,93 @@ test_integ(void) { return 0; } -void -print_seg(const double ks[4], double x0, double y0, double x1, double y1) +void print_seg(const double ks[4], double x0, double y0, double x1, double y1) { - double bend = fabs(ks[0]) + fabs(.5 * ks[1]) + fabs(.125 * ks[2]) + - fabs((1./48) * ks[3]); + double bend = fabs(ks[0]) + fabs(.5 * ks[1]) + fabs(.125 * ks[2]) + fabs((1. / 48) * ks[3]); if (bend < 1e-8) { - printf("%g %g lineto\n", x1, y1); + printf("%g %g lineto\n", x1, y1); } else { - double seg_ch = hypot(x1 - x0, y1 - y0); - double seg_th = atan2(y1 - y0, x1 - x0); - double xy[2]; - double ch, th; - double scale, rot; - - integrate_spiro(ks, xy); - ch = hypot(xy[0], xy[1]); - th = atan2(xy[1], xy[0]); - scale = seg_ch / ch; - rot = seg_th - th; - if (bend < 1.) { - double th_even, th_odd; - double ul, vl; - double ur, vr; - th_even = (1./384) * ks[3] + (1./8) * ks[1] + rot; - th_odd = (1./48) * ks[2] + .5 * ks[0]; - ul = (scale * (1./3)) * cos(th_even - th_odd); - vl = (scale * (1./3)) * sin(th_even - th_odd); - ur = (scale * (1./3)) * cos(th_even + th_odd); - vr = (scale * (1./3)) * sin(th_even + th_odd); - printf("%g %g %g %g %g %g curveto\n", - x0 + ul, y0 + vl, x1 - ur, y1 - vr, x1, y1); - - } else { - /* subdivide */ - double ksub[4]; - double thsub; - double xysub[2]; - double xmid, ymid; - double cth, sth; - - ksub[0] = .5 * ks[0] - .125 * ks[1] + (1./64) * ks[2] - (1./768) * ks[3]; - ksub[1] = .25 * ks[1] - (1./16) * ks[2] + (1./128) * ks[3]; - ksub[2] = .125 * ks[2] - (1./32) * ks[3]; - ksub[3] = (1./16) * ks[3]; - thsub = rot - .25 * ks[0] + (1./32) * ks[1] - (1./384) * ks[2] + (1./6144) * ks[3]; - cth = .5 * scale * cos(thsub); - sth = .5 * scale * sin(thsub); - integrate_spiro(ksub, xysub); - xmid = x0 + cth * xysub[0] - sth * xysub[1]; - ymid = y0 + cth * xysub[1] + sth * xysub[0]; - print_seg(ksub, x0, y0, xmid, ymid); - ksub[0] += .25 * ks[1] + (1./384) * ks[3]; - ksub[1] += .125 * ks[2]; - ksub[2] += (1./16) * ks[3]; - print_seg(ksub, xmid, ymid, x1, y1); - } + double seg_ch = hypot(x1 - x0, y1 - y0); + double seg_th = atan2(y1 - y0, x1 - x0); + double xy[2]; + double ch, th; + double scale, rot; + + integrate_spiro(ks, xy); + ch = hypot(xy[0], xy[1]); + th = atan2(xy[1], xy[0]); + scale = seg_ch / ch; + rot = seg_th - th; + if (bend < 1.) { + double th_even, th_odd; + double ul, vl; + double ur, vr; + th_even = (1. / 384) * ks[3] + (1. / 8) * ks[1] + rot; + th_odd = (1. / 48) * ks[2] + .5 * ks[0]; + ul = (scale * (1. / 3)) * cos(th_even - th_odd); + vl = (scale * (1. / 3)) * sin(th_even - th_odd); + ur = (scale * (1. / 3)) * cos(th_even + th_odd); + vr = (scale * (1. / 3)) * sin(th_even + th_odd); + printf("%g %g %g %g %g %g curveto\n", x0 + ul, y0 + vl, x1 - ur, y1 - vr, x1, y1); + + } else { + /* subdivide */ + double ksub[4]; + double thsub; + double xysub[2]; + double xmid, ymid; + double cth, sth; + + ksub[0] = .5 * ks[0] - .125 * ks[1] + (1. / 64) * ks[2] - (1. / 768) * ks[3]; + ksub[1] = .25 * ks[1] - (1. / 16) * ks[2] + (1. / 128) * ks[3]; + ksub[2] = .125 * ks[2] - (1. / 32) * ks[3]; + ksub[3] = (1. / 16) * ks[3]; + thsub = rot - .25 * ks[0] + (1. / 32) * ks[1] - (1. / 384) * ks[2] + (1. / 6144) * ks[3]; + cth = .5 * scale * cos(thsub); + sth = .5 * scale * sin(thsub); + integrate_spiro(ksub, xysub); + xmid = x0 + cth * xysub[0] - sth * xysub[1]; + ymid = y0 + cth * xysub[1] + sth * xysub[0]; + print_seg(ksub, x0, y0, xmid, ymid); + ksub[0] += .25 * ks[1] + (1. / 384) * ks[3]; + ksub[1] += .125 * ks[2]; + ksub[2] += (1. / 16) * ks[3]; + print_seg(ksub, xmid, ymid, x1, y1); + } } } -void -print_segs(const spiro_seg *segs, int nsegs) +void print_segs(const spiro_seg *segs, int nsegs) { int i; for (i = 0; i < nsegs; i++) { - double x0 = segs[i].x; - double y0 = segs[i].y; - double x1 = segs[i + 1].x; - double y1 = segs[i + 1].y; - - if (i == 0) - printf("%g %g moveto\n", x0, y0); - printf("%% ks = [ %g %g %g %g ]\n", - segs[i].ks[0], segs[i].ks[1], segs[i].ks[2], segs[i].ks[3]); - print_seg(segs[i].ks, x0, y0, x1, y1); + double x0 = segs[i].x; + double y0 = segs[i].y; + double x1 = segs[i + 1].x; + double y1 = segs[i + 1].y; + + if (i == 0) + printf("%g %g moveto\n", x0, y0); + printf("%% ks = [ %g %g %g %g ]\n", segs[i].ks[0], segs[i].ks[1], segs[i].ks[2], segs[i].ks[3]); + print_seg(segs[i].ks, x0, y0, x1, y1); } printf("stroke\n"); } -int -test_curve(void) +int test_curve(void) { - spiro_cp path[] = { - {334, 117, 'v'}, - {305, 176, 'v'}, - {212, 142, 'c'}, - {159, 171, 'c'}, - {224, 237, 'c'}, - {347, 335, 'c'}, - {202, 467, 'c'}, - {81, 429, 'v'}, - {114, 368, 'v'}, - {201, 402, 'c'}, - {276, 369, 'c'}, - {218, 308, 'c'}, - {91, 211, 'c'}, - {124, 111, 'c'}, - {229, 82, 'c'} - }; + spiro_cp path[] = {{334, 117, 'v'}, {305, 176, 'v'}, {212, 142, 'c'}, {159, 171, 'c'}, {224, 237, 'c'}, + {347, 335, 'c'}, {202, 467, 'c'}, {81, 429, 'v'}, {114, 368, 'v'}, {201, 402, 'c'}, + {276, 369, 'c'}, {218, 308, 'c'}, {91, 211, 'c'}, {124, 111, 'c'}, {229, 82, 'c'}}; spiro_seg *segs; int i; n = 1; for (i = 0; i < 1000; i++) { - segs = setup_path(path, 15); - solve_spiro(segs, 15); + segs = setup_path(path, 15); + solve_spiro(segs, 15); } printf("100 800 translate 1 -1 scale 1 setlinewidth\n"); print_segs(segs, 15); diff --git a/src/live_effects/spiro.h b/src/live_effects/spiro.h index 3ca1fb87bb7ff0ff932139f57f23880689dbb0cf..286b42ec2e9fe8b6477761c539a43ac09c6d226d 100644 --- a/src/live_effects/spiro.h +++ b/src/live_effects/spiro.h @@ -12,31 +12,31 @@ #ifndef INKSCAPE_SPIRO_H #define INKSCAPE_SPIRO_H -#include "live_effects/spiro-converters.h" #include <2geom/forward.h> +#include "live_effects/spiro-converters.h" + class SPCurve; namespace Spiro { -struct spiro_cp { +struct spiro_cp +{ double x; double y; char ty; }; - void spiro_run(const spiro_cp *src, int src_len, SPCurve &curve); void spiro_run(const spiro_cp *src, int src_len, Geom::Path &path); /* the following methods are only for expert use: */ typedef struct spiro_seg_s spiro_seg; -spiro_seg * run_spiro(const spiro_cp *src, int n); +spiro_seg *run_spiro(const spiro_cp *src, int n); void free_spiro(spiro_seg *s); void spiro_to_otherpath(const spiro_seg *s, int n, ConverterBase &bc); double get_knot_th(const spiro_seg *s, int i); - } // namespace Spiro #endif // INKSCAPE_SPIRO_H diff --git a/src/media.cpp b/src/media.cpp index 75a67f5a4bd8d51296ec76d5818e18c387d48e25..7f583a98e4ed9a8e984c8bb5969290a617313ea2 100644 --- a/src/media.cpp +++ b/src/media.cpp @@ -9,21 +9,18 @@ */ #include "media.h" -void -media_clear_all(Media &media) +void media_clear_all(Media &media) { media.print = false; media.screen = false; } -void -media_set_all(Media &media) +void media_set_all(Media &media) { media.print = true; media.screen = true; } - /* Local Variables: mode:c++ diff --git a/src/media.h b/src/media.h index 5a9353a766a30bef85d046dbf29c6c7560e2b65c..0a30c8711fdad8a4f5b5d122eda93b6cc0f9a496 100644 --- a/src/media.h +++ b/src/media.h @@ -10,7 +10,8 @@ #ifndef INKSCAPE_MEDIA_H #define INKSCAPE_MEDIA_H -class Media { +class Media +{ public: bool print; bool screen; diff --git a/src/menus-skeleton.h b/src/menus-skeleton.h index 5cf816415bd7f9e8fed3ed9e232f788bc3409cfd..1c9acb0b94c08e60e69c90a9c7d31f6e3e87c3fc 100644 --- a/src/menus-skeleton.h +++ b/src/menus-skeleton.h @@ -16,19 +16,17 @@ #define N_(x) x #endif -static char const menus_skeleton[] = -"\n" -"\n" -" \n" -" \n" -" \n" -"\n"; +static char const menus_skeleton[] = "\n" + "\n" + " \n" + " \n" + " \n" + "\n"; #define MENUS_SKELETON_SIZE (sizeof(menus_skeleton) - 1) - #endif /* !SEEN_MENUS_SKELETON_H */ /* diff --git a/src/message-context.cpp b/src/message-context.cpp index 4ff92a99cca08483445faaf1c9b89a0f4d11ec12..85d9e155269e711c8aa4a9877a321046eb69f1dd 100644 --- a/src/message-context.cpp +++ b/src/message-context.cpp @@ -10,22 +10,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include "message-context.h" + +#include + #include "message-stack.h" namespace Inkscape { MessageContext::MessageContext(std::shared_ptr stack) -: _stack(std::move(stack)), _message_id(0), _flash_message_id(0) + : _stack(std::move(stack)) + , _message_id(0) + , _flash_message_id(0) {} -MessageContext::~MessageContext() { +MessageContext::~MessageContext() +{ clear(); _stack = nullptr; } -void MessageContext::set(MessageType type, gchar const *message) { +void MessageContext::set(MessageType type, gchar const *message) +{ if (_message_id) { _stack->cancel(_message_id); } @@ -42,32 +48,36 @@ void MessageContext::setF(MessageType type, gchar const *format, ...) void MessageContext::setVF(MessageType type, gchar const *format, va_list args) { - gchar *message=g_strdup_vprintf(format, args); + gchar *message = g_strdup_vprintf(format, args); set(type, message); g_free(message); } -void MessageContext::flash(MessageType type, gchar const *message) { +void MessageContext::flash(MessageType type, gchar const *message) +{ if (_flash_message_id) { _stack->cancel(_flash_message_id); } _flash_message_id = _stack->flash(type, message); } -void MessageContext::flashF(MessageType type, gchar const *format, ...) { +void MessageContext::flashF(MessageType type, gchar const *format, ...) +{ va_list args; va_start(args, format); flashVF(type, format, args); va_end(args); } -void MessageContext::flashVF(MessageType type, gchar const *format, va_list args) { - gchar *message=g_strdup_vprintf(format, args); +void MessageContext::flashVF(MessageType type, gchar const *format, va_list args) +{ + gchar *message = g_strdup_vprintf(format, args); flash(type, message); g_free(message); } -void MessageContext::clear() { +void MessageContext::clear() +{ if (_message_id) { _stack->cancel(_message_id); _message_id = 0; @@ -78,7 +88,7 @@ void MessageContext::clear() { } } -} +} // namespace Inkscape /* Local Variables: diff --git a/src/message-context.h b/src/message-context.h index cfe155aa37115eae9ed2cc34f7005eb8da3132b7..bf2d17818691318d96fb3688dbf1e6675440c073 100644 --- a/src/message-context.h +++ b/src/message-context.h @@ -16,8 +16,8 @@ #define SEEN_INKSCAPE_MESSAGE_CONTEXT_H #include -#include #include +#include #include "message.h" @@ -26,75 +26,76 @@ namespace Inkscape { class MessageStack; /** A convenience class for working with MessageStacks. - * - * In general, a particular piece of code will only want to display - * one status message at a time. This class takes care of tracking - * a "current" message id in a particular stack for us, and provides - * a convenient means to remove or replace it. - * - * @see Inkscape::MessageStack - */ -class MessageContext { + * + * In general, a particular piece of code will only want to display + * one status message at a time. This class takes care of tracking + * a "current" message id in a particular stack for us, and provides + * a convenient means to remove or replace it. + * + * @see Inkscape::MessageStack + */ +class MessageContext +{ public: /** Constructs an Inkscape::MessageContext referencing a particular - * Inkscape::MessageStack, which will be used for our messages - * - * MessageContexts retain references to the MessageStacks they use. - * - * @param stack the Inkscape::MessageStack to use for our messages - */ + * Inkscape::MessageStack, which will be used for our messages + * + * MessageContexts retain references to the MessageStacks they use. + * + * @param stack the Inkscape::MessageStack to use for our messages + */ MessageContext(std::shared_ptr stack); ~MessageContext(); /** @brief pushes a message on the stack, replacing our old message - * - * @param type the message type - * @param message the message text - */ + * + * @param type the message type + * @param message the message text + */ void set(MessageType type, char const *message); /** @brief pushes a message on the stack using prinf-style formatting, - * and replacing our old message - * - * @param type the message type - * @param format a printf-style formatting string - */ - void setF(MessageType type, char const *format, ...) G_GNUC_PRINTF(3,4); + * and replacing our old message + * + * @param type the message type + * @param format a printf-style formatting string + */ + void setF(MessageType type, char const *format, ...) G_GNUC_PRINTF(3, 4); /** @brief pushes a message on the stack using printf-style formatting, - * and a stdarg argument list - * - * @param type the message type - * @param format a printf-style formatting string - * @param args printf-style arguments - */ + * and a stdarg argument list + * + * @param type the message type + * @param format a printf-style formatting string + * @param args printf-style arguments + */ void setVF(MessageType type, char const *format, va_list args); /** @brief pushes a message onto the stack for a brief period of time - * without disturbing our "current" message - * - * @param type the message type - * @param message the message text - */ + * without disturbing our "current" message + * + * @param type the message type + * @param message the message text + */ void flash(MessageType type, char const *message); /** @brief pushes a message onto the stack for a brief period of time - * using printf-style formatting, without disturbing our current - * message - * - * @param type the message type - * @param format a printf-style formatting string - */ - void flashF(MessageType type, char const *format, ...) G_GNUC_PRINTF(3,4); + * using printf-style formatting, without disturbing our current + * message + * + * @param type the message type + * @param format a printf-style formatting string + */ + void flashF(MessageType type, char const *format, ...) G_GNUC_PRINTF(3, 4); /** @brief pushes a message onto the stack for a brief period of time - * using printf-style formatting and a stdarg argument list; - * it does not disturb our "current" message - * - * @param type the message type - * @param format a printf-style formatting string - * @param args printf-style arguments - */ + * using printf-style formatting and a stdarg argument list; + * it does not disturb our "current" message + * + * @param type the message type + * @param format a printf-style formatting string + * @param args printf-style arguments + */ void flashVF(MessageType type, char const *format, va_list args); /** @brief removes our current message from the stack */ @@ -102,11 +103,11 @@ public: private: std::shared_ptr _stack; ///< the message stack to use - MessageId _message_id; ///< our current message id, or 0 - MessageId _flash_message_id; ///< current flashed message id, or 0 + MessageId _message_id; ///< our current message id, or 0 + MessageId _flash_message_id; ///< current flashed message id, or 0 }; -} +} // namespace Inkscape #endif /* diff --git a/src/message-stack.cpp b/src/message-stack.cpp index cebd5f23c6412571a54c04cd6d024904a1603926..0da59c75d78eec23c561a923a8cb9c7b60d4afe7 100644 --- a/src/message-stack.cpp +++ b/src/message-stack.cpp @@ -10,17 +10,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "message-stack.h" + #include #include -#include -#include "message-stack.h" namespace Inkscape { MessageStack::MessageStack() -: _messages(nullptr), _next_id(1) -{ -} + : _messages(nullptr) + , _next_id(1) +{} MessageStack::~MessageStack() { @@ -29,7 +29,8 @@ MessageStack::~MessageStack() } } -MessageId MessageStack::push(MessageType type, gchar const *message) { +MessageId MessageStack::push(MessageType type, gchar const *message) +{ return _push(type, 0, message); } @@ -37,7 +38,7 @@ MessageId MessageStack::pushF(MessageType type, gchar const *format, ...) { va_list args; va_start(args, format); - MessageId id=pushVF(type, format, args); + MessageId id = pushVF(type, format, args); va_end(args); return id; } @@ -45,16 +46,17 @@ MessageId MessageStack::pushF(MessageType type, gchar const *format, ...) MessageId MessageStack::pushVF(MessageType type, gchar const *format, va_list args) { MessageId id; - gchar *message=g_strdup_vprintf(format, args); + gchar *message = g_strdup_vprintf(format, args); id = push(type, message); g_free(message); return id; } -void MessageStack::cancel(MessageId id) { +void MessageStack::cancel(MessageId id) +{ Message **ref; - for ( ref = &_messages ; *ref ; ref = &(*ref)->next ) { - if ( (*ref)->id == id ) { + for (ref = &_messages; *ref; ref = &(*ref)->next) { + if ((*ref)->id == id) { *ref = _discard(*ref); _emitChanged(); break; @@ -64,32 +66,34 @@ void MessageStack::cancel(MessageId id) { MessageId MessageStack::flash(MessageType type, Glib::ustring const &message) { - MessageId id = flash( type, message.c_str() ); + MessageId id = flash(type, message.c_str()); return id; } -MessageId MessageStack::flash(MessageType type, gchar const *message) { +MessageId MessageStack::flash(MessageType type, gchar const *message) +{ switch (type) { - case INFORMATION_MESSAGE: // stay rather long so as to seem permanent, but eventually disappear - return _push(type, 6000 + 80*strlen(message), message); - break; - case ERROR_MESSAGE: // pretty important stuff, but temporary - return _push(type, 4000 + 60*strlen(message), message); - break; - case WARNING_MESSAGE: // a bit less important than error - return _push(type, 2000 + 40*strlen(message), message); - break; - case IMMEDIATE_MESSAGE: // same length as normal, higher priority - return _push(type, 1000 + 20*strlen(message), message); - break; - case NORMAL_MESSAGE: // something ephemeral - default: - return _push(type, 1000 + 20*strlen(message), message); - break; + case INFORMATION_MESSAGE: // stay rather long so as to seem permanent, but eventually disappear + return _push(type, 6000 + 80 * strlen(message), message); + break; + case ERROR_MESSAGE: // pretty important stuff, but temporary + return _push(type, 4000 + 60 * strlen(message), message); + break; + case WARNING_MESSAGE: // a bit less important than error + return _push(type, 2000 + 40 * strlen(message), message); + break; + case IMMEDIATE_MESSAGE: // same length as normal, higher priority + return _push(type, 1000 + 20 * strlen(message), message); + break; + case NORMAL_MESSAGE: // something ephemeral + default: + return _push(type, 1000 + 20 * strlen(message), message); + break; } } -MessageId MessageStack::flashF(MessageType type, gchar const *format, ...) { +MessageId MessageStack::flashF(MessageType type, gchar const *format, ...) +{ va_list args; va_start(args, format); MessageId id = flashVF(type, format, args); @@ -99,7 +103,7 @@ MessageId MessageStack::flashF(MessageType type, gchar const *format, ...) { MessageId MessageStack::flashVF(MessageType type, gchar const *format, va_list args) { - gchar *message=g_strdup_vprintf(format, args); + gchar *message = g_strdup_vprintf(format, args); MessageId id = flash(type, message); g_free(message); return id; @@ -107,8 +111,8 @@ MessageId MessageStack::flashVF(MessageType type, gchar const *format, va_list a MessageId MessageStack::_push(MessageType type, guint lifetime, gchar const *message) { - Message *m=new Message; - MessageId id=_next_id++; + Message *m = new Message; + MessageId id = _next_id++; m->stack = this; m->id = id; @@ -131,7 +135,7 @@ MessageId MessageStack::_push(MessageType type, guint lifetime, gchar const *mes MessageStack::Message *MessageStack::_discard(MessageStack::Message *m) { - Message *next=m->next; + Message *next = m->next; if (m->timeout_id) { g_source_remove(m->timeout_id); m->timeout_id = 0; @@ -143,7 +147,8 @@ MessageStack::Message *MessageStack::_discard(MessageStack::Message *m) return next; } -void MessageStack::_emitChanged() { +void MessageStack::_emitChanged() +{ if (_messages) { _changed_signal.emit(_messages->type, _messages->message); } else { @@ -151,14 +156,15 @@ void MessageStack::_emitChanged() { } } -gboolean MessageStack::_timeout(gpointer data) { - Message *m=reinterpret_cast(data); +gboolean MessageStack::_timeout(gpointer data) +{ + Message *m = reinterpret_cast(data); m->timeout_id = 0; m->stack->cancel(m->id); return FALSE; } -} +} // namespace Inkscape /* Local Variables: diff --git a/src/message-stack.h b/src/message-stack.h index f86ae7b94b3bc604288d2f660a7dad4643465a0a..a50e350f92ad397c43e7dce96fb0abb16be9e555 100644 --- a/src/message-stack.h +++ b/src/message-stack.h @@ -28,9 +28,9 @@ namespace Inkscape { /** - * A class which holds a stack of displayed messages. + * A class which holds a stack of displayed messages. * - * Messages can be pushed onto the top of the stack, and removed + * Messages can be pushed onto the top of the stack, and removed * from any point in the stack by their id. * * Messages may also be "flashed", meaning that they will be @@ -51,64 +51,60 @@ public: MessageStack(); ~MessageStack(); - MessageStack(MessageStack const &) = delete; // no copy + MessageStack(MessageStack const &) = delete; // no copy void operator=(MessageStack const &) = delete; // no assign /** @brief returns the type of message currently at the top of the stack */ - MessageType currentMessageType() { - return _messages ? _messages->type : NORMAL_MESSAGE; - } + MessageType currentMessageType() { return _messages ? _messages->type : NORMAL_MESSAGE; } /** @brief returns the text of the message currently at the top of - * the stack - */ - char const *currentMessage() { - return _messages ? _messages->message : nullptr; - } + * the stack + */ + char const *currentMessage() { return _messages ? _messages->message : nullptr; } /** @brief connects to the "changed" signal which is emitted whenever - * the topmost message on the stack changes. - */ + * the topmost message on the stack changes. + */ sigc::connection connectChanged(sigc::slot slot) { return _changed_signal.connect(slot); } /** @brief pushes a message onto the stack - * - * @param type the message type - * @param message the message text - * - * @return the id of the pushed message - */ + * + * @param type the message type + * @param message the message text + * + * @return the id of the pushed message + */ MessageId push(MessageType type, char const *message); /** @brief pushes a message onto the stack using printf-like formatting - * - * @param type the message type - * @param format a printf-style format string - * - * @return the id of the pushed message - */ - MessageId pushF(MessageType type, char const *format, ...) G_GNUC_PRINTF(3,4); + * + * @param type the message type + * @param format a printf-style format string + * + * @return the id of the pushed message + */ + MessageId pushF(MessageType type, char const *format, ...) G_GNUC_PRINTF(3, 4); /** @brief pushes a message onto the stack using printf-like formatting, - * using a stdarg argument list - * - * @param type the message type - * @param format a printf-style format string - * @param args the subsequent printf-style arguments - * - * @return the id of the pushed message - */ + * using a stdarg argument list + * + * @param type the message type + * @param format a printf-style format string + * @param args the subsequent printf-style arguments + * + * @return the id of the pushed message + */ MessageId pushVF(MessageType type, char const *format, va_list args); /** @brief removes a message from the stack, given its id - * - * This method will remove a message from the stack if it has not - * already been removed. It may be removed from any part of the stack. - * - * @param id the message id to remove - */ + * + * This method will remove a message from the stack if it has not + * already been removed. It may be removed from any part of the stack. + * + * @param id the message id to remove + */ void cancel(MessageId id); /** @@ -131,30 +127,30 @@ public: */ MessageId flash(MessageType type, Glib::ustring const &message); - /** @brief temporarily pushes a message onto the stack using - * printf-like formatting - * - * @param type the message type - * @param format a printf-style format string - * - * @return the id of the pushed message - */ - MessageId flashF(MessageType type, char const *format, ...) G_GNUC_PRINTF(3,4); + * printf-like formatting + * + * @param type the message type + * @param format a printf-style format string + * + * @return the id of the pushed message + */ + MessageId flashF(MessageType type, char const *format, ...) G_GNUC_PRINTF(3, 4); /** @brief temporarily pushes a message onto the stack using - * printf-like formatting, using a stdarg argument list - * - * @param type the message type - * @param format a printf-style format string - * @param args the printf-style arguments - * - * @return the id of the pushed message - */ + * printf-like formatting, using a stdarg argument list + * + * @param type the message type + * @param format a printf-style format string + * @param args the printf-style arguments + * + * @return the id of the pushed message + */ MessageId flashVF(MessageType type, char const *format, va_list args); private: - struct Message { + struct Message + { Message *next; MessageStack *stack; MessageId id; @@ -166,16 +162,16 @@ private: /// pushes a message onto the stack with an optional timeout MessageId _push(MessageType type, unsigned int lifetime, char const *message); - Message *_discard(Message *m); ///< frees a message struct and returns the next such struct in the list - void _emitChanged(); ///< emits the "changed" signal - static int _timeout(void* data); ///< callback to expire flashed messages + Message *_discard(Message *m); ///< frees a message struct and returns the next such struct in the list + void _emitChanged(); ///< emits the "changed" signal + static int _timeout(void *data); ///< callback to expire flashed messages sigc::signal _changed_signal; Message *_messages; ///< the stack of messages as a linked list MessageId _next_id; ///< the next message id to assign }; -} +} // namespace Inkscape #endif /* diff --git a/src/message.h b/src/message.h index fe16bbd5e5965620547dc0eebbbf7c11fa30cbee..da7eb40e3630c57c0bfda0aae6acd4948eccf1a7 100644 --- a/src/message.h +++ b/src/message.h @@ -20,7 +20,8 @@ namespace Inkscape { * a message advising the user of some significant or unexpected condition, * or a message indicating an unambiguous error. */ -enum MessageType { +enum MessageType +{ NORMAL_MESSAGE, IMMEDIATE_MESSAGE, WARNING_MESSAGE, @@ -36,7 +37,7 @@ enum MessageType { */ typedef unsigned long MessageId; -} +} // namespace Inkscape #endif /* diff --git a/src/mod360.cpp b/src/mod360.cpp index 182022dbbe773c23f367e21b78eab5a049e2dcd7..034cde980c1c5eeb6fe4ca371696475df85430e4 100644 --- a/src/mod360.cpp +++ b/src/mod360.cpp @@ -7,24 +7,19 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include - #include "mod360.h" +#include +#include + /** Returns \a x wrapped around to between 0 and less than 360, or 0 if \a x isn't finite. **/ double mod360(double const x) { double const m = fmod(x, 360.0); - double const ret = ( std::isnan(m) - ? 0.0 - : ( m < 0 - ? m + 360 - : m ) ); - g_return_val_if_fail(0.0 <= ret && ret < 360.0, - 0.0); + double const ret = (std::isnan(m) ? 0.0 : (m < 0 ? m + 360 : m)); + g_return_val_if_fail(0.0 <= ret && ret < 360.0, 0.0); return ret; } @@ -34,8 +29,8 @@ double mod360(double const x) double mod360symm(double const x) { double m = mod360(x); - - return m < 180.0 ? m : m - 360.0; + + return m < 180.0 ? m : m - 360.0; } /* diff --git a/src/mod360.h b/src/mod360.h index 5dd14018a370b9d8fc43420737c36dad13d822c5..fe71ab8f4c81433d408fc1152d3e973632770b9e 100644 --- a/src/mod360.h +++ b/src/mod360.h @@ -11,7 +11,7 @@ #define SEEN_MOD360_H double mod360(double const x); -double mod360symm (double const x); +double mod360symm(double const x); #endif /* !SEEN_MOD360_H */ diff --git a/src/number-opt-number.h b/src/number-opt-number.h index 6bb97f6df3a3bf0ba9e2d31105c66b23c910c1a3..e36504f21d4d3f0f68fe060a661007285185cb58 100644 --- a/src/number-opt-number.h +++ b/src/number-opt-number.h @@ -14,17 +14,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include #include #include -#include #include "svg/stringstream.h" -class NumberOptNumber { - +class NumberOptNumber +{ public: - - float number; + float number; float optNumber; @@ -43,14 +42,14 @@ public: float getNumber() { - if(_set) + if (_set) return number; return -1; } float getOptNumber() { - if(optNumber_set) + if (optNumber_set) return optNumber; return -1; } @@ -67,26 +66,18 @@ public: number = num; } - bool optNumIsSet(){ - return optNumber_set; - } + bool optNumIsSet() { return optNumber_set; } + + bool numIsSet() { return _set; } - bool numIsSet(){ - return _set; - } - char *getValueString() { Inkscape::SVGOStringStream os; - if( _set ) - { - - if( optNumber_set ) - { + if (_set) { + if (optNumber_set) { os << number << " " << optNumber; - } - else { + } else { os << number; } } @@ -95,32 +86,27 @@ public: void set(char const *str) { - if(!str) + if (!str) return; char **values = g_strsplit(str, " ", 2); - if( values[0] != nullptr ) - { + if (values[0] != nullptr) { number = g_ascii_strtod(values[0], nullptr); _set = TRUE; - if( values[1] != nullptr ) - { + if (values[1] != nullptr) { optNumber = g_ascii_strtod(values[1], nullptr); optNumber_set = TRUE; - } - else - optNumber_set = FALSE; - } - else { - _set = FALSE; + } else optNumber_set = FALSE; + } else { + _set = FALSE; + optNumber_set = FALSE; } g_strfreev(values); } - }; #endif /* !SEEN_NUMBER_OPT_NUMBER_H */ diff --git a/src/object-hierarchy.cpp b/src/object-hierarchy.cpp index c05bb6f33d4dcdb7dc939a64b0db44b970a08631..e0635c045d409eb334ddf67a4f0424085114bc1c 100644 --- a/src/object-hierarchy.cpp +++ b/src/object-hierarchy.cpp @@ -10,33 +10,40 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include - #include "object-hierarchy.h" +#include + #include "object/sp-object.h" namespace Inkscape { -ObjectHierarchy::ObjectHierarchy(SPObject *top) { +ObjectHierarchy::ObjectHierarchy(SPObject *top) +{ if (top) { _addBottom(top); } } -ObjectHierarchy::~ObjectHierarchy() { +ObjectHierarchy::~ObjectHierarchy() +{ _clear(); } -void ObjectHierarchy::clear() { +void ObjectHierarchy::clear() +{ _clear(); _changed_signal.emit(nullptr, nullptr); } -void ObjectHierarchy::setTop(SPObject *object) { - if (object == nullptr) { printf("Assertion object != NULL failed\n"); return; } +void ObjectHierarchy::setTop(SPObject *object) +{ + if (object == nullptr) { + printf("Assertion object != NULL failed\n"); + return; + } - if ( top() == object ) { + if (top() == object) { return; } @@ -44,7 +51,7 @@ void ObjectHierarchy::setTop(SPObject *object) { _addTop(object); } else if (object->isAncestorOf(top())) { _addTop(object, top()); - } else if ( object == bottom() || object->isAncestorOf(bottom()) ) { + } else if (object == bottom() || object->isAncestorOf(bottom())) { _trimAbove(object); } else { _clear(); @@ -54,7 +61,8 @@ void ObjectHierarchy::setTop(SPObject *object) { _changed_signal.emit(top(), bottom()); } -void ObjectHierarchy::_addTop(SPObject *senior, SPObject *junior) { +void ObjectHierarchy::_addTop(SPObject *senior, SPObject *junior) +{ assert(junior != NULL); assert(senior != NULL); @@ -62,18 +70,20 @@ void ObjectHierarchy::_addTop(SPObject *senior, SPObject *junior) { do { _addTop(object); object = object->parent; - } while ( object != senior ); + } while (object != senior); } -void ObjectHierarchy::_addTop(SPObject *object) { +void ObjectHierarchy::_addTop(SPObject *object) +{ assert(object != NULL); _hierarchy.push_back(_attach(object)); _added_signal.emit(object); } -void ObjectHierarchy::_trimAbove(SPObject *limit) { - while ( !_hierarchy.empty() && _hierarchy.back().object != limit ) { - SPObject *object=_hierarchy.back().object; +void ObjectHierarchy::_trimAbove(SPObject *limit) +{ + while (!_hierarchy.empty() && _hierarchy.back().object != limit) { + SPObject *object = _hierarchy.back().object; sp_object_ref(object, nullptr); _detach(_hierarchy.back()); @@ -83,10 +93,14 @@ void ObjectHierarchy::_trimAbove(SPObject *limit) { } } -void ObjectHierarchy::setBottom(SPObject *object) { - if (object == nullptr) { printf("assertion object != NULL failed\n"); return; } +void ObjectHierarchy::setBottom(SPObject *object) +{ + if (object == nullptr) { + printf("assertion object != NULL failed\n"); + return; + } - if ( bottom() == object ) { + if (bottom() == object) { return; } @@ -94,13 +108,13 @@ void ObjectHierarchy::setBottom(SPObject *object) { _addBottom(object); } else if (bottom()->isAncestorOf(object)) { _addBottom(bottom(), object); - } else if ( top() == object ) { + } else if (top() == object) { _trimBelow(top()); } else if (top()->isAncestorOf(object)) { if (object->isAncestorOf(bottom())) { _trimBelow(object); } else { // object is a sibling or cousin of bottom() - SPObject *saved_top=top(); + SPObject *saved_top = top(); sp_object_ref(saved_top, nullptr); _clear(); _addBottom(saved_top); @@ -115,9 +129,10 @@ void ObjectHierarchy::setBottom(SPObject *object) { _changed_signal.emit(top(), bottom()); } -void ObjectHierarchy::_trimBelow(SPObject *limit) { - while ( !_hierarchy.empty() && _hierarchy.front().object != limit ) { - SPObject *object=_hierarchy.front().object; +void ObjectHierarchy::_trimBelow(SPObject *limit) +{ + while (!_hierarchy.empty() && _hierarchy.front().object != limit) { + SPObject *object = _hierarchy.front().object; sp_object_ref(object, nullptr); _detach(_hierarchy.front()); _hierarchy.pop_front(); @@ -126,23 +141,26 @@ void ObjectHierarchy::_trimBelow(SPObject *limit) { } } -void ObjectHierarchy::_addBottom(SPObject *senior, SPObject *junior) { +void ObjectHierarchy::_addBottom(SPObject *senior, SPObject *junior) +{ assert(junior != NULL); assert(senior != NULL); - if ( junior != senior ) { + if (junior != senior) { _addBottom(senior, junior->parent); _addBottom(junior); } } -void ObjectHierarchy::_addBottom(SPObject *object) { +void ObjectHierarchy::_addBottom(SPObject *object) +{ assert(object != NULL); _hierarchy.push_front(_attach(object)); _added_signal.emit(object); } -void ObjectHierarchy::_trim_for_release(SPObject *object) { +void ObjectHierarchy::_trim_for_release(SPObject *object) +{ this->_trimBelow(object); assert(!this->_hierarchy.empty()); assert(this->_hierarchy.front().object == object); @@ -156,21 +174,20 @@ void ObjectHierarchy::_trim_for_release(SPObject *object) { this->_changed_signal.emit(this->top(), this->bottom()); } -ObjectHierarchy::Record ObjectHierarchy::_attach(SPObject *object) { +ObjectHierarchy::Record ObjectHierarchy::_attach(SPObject *object) +{ sp_object_ref(object, nullptr); - sigc::connection connection - = object->connectRelease( - sigc::mem_fun(*this, &ObjectHierarchy::_trim_for_release) - ); + sigc::connection connection = object->connectRelease(sigc::mem_fun(*this, &ObjectHierarchy::_trim_for_release)); return Record(object, connection); } -void ObjectHierarchy::_detach(ObjectHierarchy::Record &rec) { +void ObjectHierarchy::_detach(ObjectHierarchy::Record &rec) +{ rec.connection.disconnect(); sp_object_unref(rec.object, nullptr); } -} +} // namespace Inkscape /* Local Variables: diff --git a/src/object-hierarchy.h b/src/object-hierarchy.h index e515a3db561e55ab9bf80a9966f1281f385fc2e6..02bfadaad5f011967c88a29392b319224adf4412 100644 --- a/src/object-hierarchy.h +++ b/src/object-hierarchy.h @@ -34,25 +34,21 @@ namespace Inkscape { * * @see SPObject */ -class ObjectHierarchy { +class ObjectHierarchy +{ public: - /** * Create new object hierarchy. * @param top The first entry if non-NULL. */ - ObjectHierarchy(SPObject *top=nullptr); + ObjectHierarchy(SPObject *top = nullptr); ~ObjectHierarchy(); bool contains(SPObject *object); - sigc::connection connectAdded(const sigc::slot &slot) { - return _added_signal.connect(slot); - } - sigc::connection connectRemoved(const sigc::slot &slot) { - return _removed_signal.connect(slot); - } + sigc::connection connectAdded(const sigc::slot &slot) { return _added_signal.connect(slot); } + sigc::connection connectRemoved(const sigc::slot &slot) { return _removed_signal.connect(slot); } sigc::connection connectChanged(const sigc::slot &slot) { return _changed_signal.connect(slot); @@ -63,18 +59,14 @@ public: */ void clear(); - SPObject *top() { - return !_hierarchy.empty() ? _hierarchy.back().object : nullptr; - } + SPObject *top() { return !_hierarchy.empty() ? _hierarchy.back().object : nullptr; } /** * Trim or expand hierarchy on top such that object becomes top entry. */ void setTop(SPObject *object); - SPObject *bottom() { - return !_hierarchy.empty() ? _hierarchy.front().object : nullptr; - } + SPObject *bottom() { return !_hierarchy.empty() ? _hierarchy.front().object : nullptr; } /** * Trim or expand hierarchy at bottom such that object becomes bottom entry. @@ -82,9 +74,12 @@ public: void setBottom(SPObject *object); private: - struct Record { + struct Record + { Record(SPObject *o, sigc::connection c) - : object(o), connection(c) {} + : object(o) + , connection(c) + {} SPObject *object; sigc::connection connection; @@ -142,7 +137,7 @@ private: sigc::signal _changed_signal; }; -} +} // namespace Inkscape #endif /* diff --git a/src/object-snapper.cpp b/src/object-snapper.cpp index e78044d1c1931b41cde2cef27d76b2553c288152..3bb913d7c32b7891db1457f7b794258022be4899 100644 --- a/src/object-snapper.cpp +++ b/src/object-snapper.cpp @@ -19,11 +19,9 @@ #include <2geom/path-sink.h> #include "desktop.h" +#include "display/curve.h" #include "document.h" #include "inkscape.h" -#include "preferences.h" -#include "text-editing.h" - #include "object/sp-clippath.h" #include "object/sp-flowtext.h" #include "object/sp-image.h" @@ -35,18 +33,17 @@ #include "object/sp-shape.h" #include "object/sp-text.h" #include "object/sp-use.h" - -#include "display/curve.h" -#include "path/path-util.h" // curve_for_item - +#include "path/path-util.h" // curve_for_item +#include "preferences.h" #include "svg/svg.h" +#include "text-editing.h" Inkscape::ObjectSnapper::ObjectSnapper(SnapManager *sm, Geom::Coord const d) : Snapper(sm, d) { _candidates = new std::vector; _points_to_snap_to = new std::vector; - _paths_to_snap_to = new std::vector; + _paths_to_snap_to = new std::vector; } Inkscape::ObjectSnapper::~ObjectSnapper() @@ -64,21 +61,21 @@ Inkscape::ObjectSnapper::~ObjectSnapper() Geom::Coord Inkscape::ObjectSnapper::getSnapperTolerance() const { SPDesktop const *dt = _snapmanager->getDesktop(); - double const zoom = dt ? dt->current_zoom() : 1; + double const zoom = dt ? dt->current_zoom() : 1; return _snapmanager->snapprefs.getObjectTolerance() / zoom; } bool Inkscape::ObjectSnapper::getSnapperAlwaysSnap() const { - return _snapmanager->snapprefs.getObjectTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp + return _snapmanager->snapprefs.getObjectTolerance() == + 10000; // TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp } -void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent, - std::vector const *it, - bool const &first_point, - Geom::Rect const &bbox_to_snap, +void Inkscape::ObjectSnapper::_findCandidates(SPObject *parent, std::vector const *it, + bool const &first_point, Geom::Rect const &bbox_to_snap, bool const clip_or_mask, - Geom::Affine const additional_affine) const // transformation of the item being clipped / masked + Geom::Affine const additional_affine) const // transformation of the item + // being clipped / masked { SPDesktop const *dt = _snapmanager->getDesktop(); if (dt == nullptr) { @@ -90,10 +87,10 @@ void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent, _candidates->clear(); } - Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance + Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see? - for (auto& o: parent->children) { + for (auto &o : parent->children) { g_assert(dt != nullptr); SPItem *item = dynamic_cast(&o); if (item && !(dt->itemIsHidden(item) && !clip_or_mask)) { @@ -133,26 +130,33 @@ void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent, // We'll only need to obtain the visual bounding box if the user preferences tell // us to, AND if we are snapping to the bounding box itself. If we're snapping to // paths only, then we can just as well use the geometric bounding box (which is faster) - SPItem::BBoxType bbox_type = (!prefs_bbox && _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_CATEGORY)) ? - SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; + SPItem::BBoxType bbox_type = + (!prefs_bbox && _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_CATEGORY)) + ? SPItem::VISUAL_BBOX + : SPItem::GEOMETRIC_BBOX; if (clip_or_mask) { // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to - // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine) - bbox_of_item = item->bounds(bbox_type, item->i2doc_affine() * additional_affine * dt->doc2dt()); + // insert an additional transformation in document coordinates (code copied from + // sp_item_i2d_affine) + bbox_of_item = + item->bounds(bbox_type, item->i2doc_affine() * additional_affine * dt->doc2dt()); } else { bbox_of_item = item->desktopBounds(bbox_type); } if (bbox_of_item) { // See if the item is within range - if (bbox_to_snap_incl.intersects(*bbox_of_item) - || (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_ROTATION_CENTER) && bbox_to_snap_incl.contains(item->getCenter()))) { // rotation center might be outside of the bounding box + if (bbox_to_snap_incl.intersects(*bbox_of_item) || + (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_ROTATION_CENTER) && + bbox_to_snap_incl.contains(item->getCenter()))) { // rotation center might be outside + // of the bounding box // This item is within snapping range, so record it as a candidate _candidates->push_back(SnapCandidateItem(item, clip_or_mask, additional_affine)); // For debugging: print the id of the candidate to the console // SPObject *obj = (SPObject*)item; // std::cout << "Snap candidate added: " << obj->getId() << std::endl; if (_candidates->size() > 200) { // This makes Inkscape crawl already - std::cout << "Warning: limit of 200 snap target paths reached, some will be ignored" << std::endl; + std::cout << "Warning: limit of 200 snap target paths reached, some will be ignored" + << std::endl; break; } } @@ -164,9 +168,7 @@ void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent, } } - -void Inkscape::ObjectSnapper::_collectNodes(SnapSourceType const &t, - bool const &first_point) const +void Inkscape::ObjectSnapper::_collectNodes(SnapSourceType const &t, bool const &first_point) const { // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap, // e.g. when translating an item using the selector tool, then we will only do this for the @@ -174,7 +176,7 @@ void Inkscape::ObjectSnapper::_collectNodes(SnapSourceType const &t, if (first_point) { _points_to_snap_to->clear(); - // Determine the type of bounding box we should snap to + // Determine the type of bounding box we should snap to SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX; bool p_is_a_node = t & SNAPSOURCE_NODE_CATEGORY; @@ -186,11 +188,11 @@ void Inkscape::ObjectSnapper::_collectNodes(SnapSourceType const &t, g_warning("Snap warning: node type is ambiguous"); } - if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_CORNER, SNAPTARGET_BBOX_EDGE_MIDPOINT, SNAPTARGET_BBOX_MIDPOINT)) { + if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_CORNER, SNAPTARGET_BBOX_EDGE_MIDPOINT, + SNAPTARGET_BBOX_MIDPOINT)) { Preferences *prefs = Preferences::get(); bool prefs_bbox = prefs->getBool("/tools/bounding_box"); - bbox_type = !prefs_bbox ? - SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; + bbox_type = !prefs_bbox ? SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; } // Consider the page border for snapping to @@ -198,8 +200,8 @@ void Inkscape::ObjectSnapper::_collectNodes(SnapSourceType const &t, _getBorderNodes(_points_to_snap_to); } - for (const auto & _candidate : *_candidates) { - //Geom::Affine i2doc(Geom::identity()); + for (const auto &_candidate : *_candidates) { + // Geom::Affine i2doc(Geom::identity()); SPItem *root_item = _candidate.item; SPUse *use = dynamic_cast(_candidate.item); @@ -208,7 +210,7 @@ void Inkscape::ObjectSnapper::_collectNodes(SnapSourceType const &t, } g_return_if_fail(root_item); - //Collect all nodes so we can snap to them + // Collect all nodes so we can snap to them if (p_is_a_node || p_is_other || (p_is_a_bbox && !_snapmanager->snapprefs.getStrictSnapping())) { // Note: there are two ways in which intersections are considered: // Method 1: Intersections are calculated for each shape individually, for both the @@ -225,10 +227,11 @@ void Inkscape::ObjectSnapper::_collectNodes(SnapSourceType const &t, // If both methods are being used simultaneously, then this might lead to duplicate targets! // Well, here we will be looking for snap TARGETS. Both methods can therefore be used. - // When snapping to paths, we will get a collection of snapped lines and snapped curves. findBestSnap() will - // go hunting for intersections (but only when asked to in the prefs of course). In that case we can just - // temporarily block the intersections in sp_item_snappoints, we don't need duplicates. If we're not snapping to - // paths though but only to item nodes then we should still look for the intersections in sp_item_snappoints() + // When snapping to paths, we will get a collection of snapped lines and snapped curves. findBestSnap() + // will go hunting for intersections (but only when asked to in the prefs of course). In that case we + // can just temporarily block the intersections in sp_item_snappoints, we don't need duplicates. If + // we're not snapping to paths though but only to item nodes then we should still look for the + // intersections in sp_item_snappoints() bool old_pref = _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH_INTERSECTION); if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH)) { // So if we snap to paths, then findBestSnap will find the intersections @@ -241,7 +244,7 @@ void Inkscape::ObjectSnapper::_collectNodes(SnapSourceType const &t, // current selection (see the comment in SelTrans::centerRequest()) bool old_pref2 = _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_ROTATION_CENTER); if (old_pref2) { - std::vector rotationSource=_snapmanager->getRotationCenterSource(); + std::vector rotationSource = _snapmanager->getRotationCenterSource(); for (auto itemlist : rotationSource) { if (_candidate.item == itemlist) { // don't snap to this item's rotation center @@ -258,26 +261,24 @@ void Inkscape::ObjectSnapper::_collectNodes(SnapSourceType const &t, _snapmanager->snapprefs.setTargetSnappable(SNAPTARGET_ROTATION_CENTER, old_pref2); } - //Collect the bounding box's corners so we can snap to them + // Collect the bounding box's corners so we can snap to them if (p_is_a_bbox || (!_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node) || p_is_other) { // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox // of the item AND the bbox of the clipping path at the same time if (!_candidate.clip_or_mask) { Geom::OptRect b = root_item->desktopBounds(bbox_type); getBBoxPoints(b, _points_to_snap_to, true, - _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_CORNER), - _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_EDGE_MIDPOINT), - _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_MIDPOINT)); + _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_CORNER), + _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_EDGE_MIDPOINT), + _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_MIDPOINT)); } } } } } -void Inkscape::ObjectSnapper::_snapNodes(IntermSnapResults &isr, - SnapCandidatePoint const &p, - std::vector *unselected_nodes, - SnapConstraint const &c, +void Inkscape::ObjectSnapper::_snapNodes(IntermSnapResults &isr, SnapCandidatePoint const &p, + std::vector *unselected_nodes, SnapConstraint const &c, Geom::Point const &p_proj_on_constraint) const { // Iterate through all nodes, find out which one is the closest to p, and snap to it! @@ -293,7 +294,7 @@ void Inkscape::ObjectSnapper::_snapNodes(IntermSnapResults &isr, bool success = false; bool strict_snapping = _snapmanager->snapprefs.getStrictSnapping(); - for (const auto & k : *_points_to_snap_to) { + for (const auto &k : *_points_to_snap_to) { if (_allowSourceToSnapToTarget(p.getSourceType(), k.getTargetType(), strict_snapping)) { Geom::Point target_pt = k.getPoint(); Geom::Coord dist = Geom::L2(target_pt - p.getPoint()); // Default: free (unconstrained) snapping @@ -309,7 +310,8 @@ void Inkscape::ObjectSnapper::_snapNodes(IntermSnapResults &isr, } if (dist < getSnapperTolerance() && dist < s.getSnapDistance()) { - s = SnappedPoint(target_pt, p.getSourceType(), p.getSourceNum(), k.getTargetType(), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, true, k.getTargetBBox()); + s = SnappedPoint(target_pt, p.getSourceType(), p.getSourceNum(), k.getTargetType(), dist, + getSnapperTolerance(), getSnapperAlwaysSnap(), false, true, k.getTargetBBox()); success = true; } } @@ -320,14 +322,14 @@ void Inkscape::ObjectSnapper::_snapNodes(IntermSnapResults &isr, } } -void Inkscape::ObjectSnapper::_snapTranslatingGuide(IntermSnapResults &isr, - Geom::Point const &p, - Geom::Point const &guide_normal) const +void Inkscape::ObjectSnapper::_snapTranslatingGuide(IntermSnapResults &isr, Geom::Point const &p, + Geom::Point const &guide_normal) const { // Iterate through all nodes, find out which one is the closest to this guide, and snap to it! _collectNodes(SNAPSOURCE_GUIDE, true); - if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION, SNAPTARGET_BBOX_EDGE, SNAPTARGET_PAGE_BORDER, SNAPTARGET_TEXT_BASELINE)) { + if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION, SNAPTARGET_BBOX_EDGE, + SNAPTARGET_PAGE_BORDER, SNAPTARGET_TEXT_BASELINE)) { _collectPaths(p, SNAPSOURCE_GUIDE, true); _snapPaths(isr, SnapCandidatePoint(p, SNAPSOURCE_GUIDE), nullptr, nullptr); } @@ -336,24 +338,24 @@ void Inkscape::ObjectSnapper::_snapTranslatingGuide(IntermSnapResults &isr, Geom::Coord tol = getSnapperTolerance(); - for (const auto & k : *_points_to_snap_to) { + for (const auto &k : *_points_to_snap_to) { Geom::Point target_pt = k.getPoint(); // Project each node (*k) on the guide line (running through point p) Geom::Point p_proj = Geom::projection(target_pt, Geom::Line(p, p + Geom::rot90(guide_normal))); Geom::Coord dist = Geom::L2(target_pt - p_proj); // distance from node to the guide - Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location + Geom::Coord dist2 = + Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location if ((dist < tol && dist2 < tol) || getSnapperAlwaysSnap()) { - s = SnappedPoint(target_pt, SNAPSOURCE_GUIDE, 0, k.getTargetType(), dist, tol, getSnapperAlwaysSnap(), false, true, k.getTargetBBox()); + s = SnappedPoint(target_pt, SNAPSOURCE_GUIDE, 0, k.getTargetType(), dist, tol, getSnapperAlwaysSnap(), + false, true, k.getTargetBBox()); isr.points.push_back(s); } } } - /// @todo investigate why Geom::Point p is passed in but ignored. -void Inkscape::ObjectSnapper::_collectPaths(Geom::Point /*p*/, - SnapSourceType const source_type, - bool const &first_point) const +void Inkscape::ObjectSnapper::_collectPaths(Geom::Point /*p*/, SnapSourceType const source_type, + bool const &first_point) const { // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap, // e.g. when translating an item using the selector tool, then we will only do this for the @@ -371,20 +373,19 @@ void Inkscape::ObjectSnapper::_collectPaths(Geom::Point /*p*/, if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_EDGE)) { Preferences *prefs = Preferences::get(); int prefs_bbox = prefs->getBool("/tools/bounding_box", false); - bbox_type = !prefs_bbox ? - SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; + bbox_type = !prefs_bbox ? SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; } // Consider the page border for snapping - if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PAGE_BORDER) && _snapmanager->snapprefs.isAnyCategorySnappable()) { + if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PAGE_BORDER) && + _snapmanager->snapprefs.isAnyCategorySnappable()) { Geom::PathVector *border_path = _getBorderPathv(); if (border_path != nullptr) { _paths_to_snap_to->push_back(SnapCandidatePath(border_path, SNAPTARGET_PAGE_BORDER, Geom::OptRect())); } } - for (const auto & _candidate : *_candidates) { - + for (const auto &_candidate : *_candidates) { /* Transform the requested snap point to this item's coordinates */ Geom::Affine i2doc(Geom::identity()); SPItem *root_item = nullptr; @@ -399,10 +400,11 @@ void Inkscape::ObjectSnapper::_collectPaths(Geom::Point /*p*/, root_item = _candidate.item; } - //Build a list of all paths considered for snapping to + // Build a list of all paths considered for snapping to - //Add the item's path to snap to - if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION, SNAPTARGET_TEXT_BASELINE)) { + // Add the item's path to snap to + if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION, + SNAPTARGET_TEXT_BASELINE)) { if (p_is_other || p_is_a_node || (!_snapmanager->snapprefs.getStrictSnapping() && p_is_a_bbox)) { if (dynamic_cast(root_item) || dynamic_cast(root_item)) { if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_TEXT_BASELINE)) { @@ -410,8 +412,10 @@ void Inkscape::ObjectSnapper::_collectPaths(Geom::Point /*p*/, Text::Layout const *layout = te_get_layout(static_cast(root_item)); if (layout != nullptr && layout->outputExists()) { Geom::PathVector *pv = new Geom::PathVector(); - pv->push_back(layout->baseline() * root_item->i2dt_affine() * _candidate.additional_affine * _snapmanager->getDesktop()->doc2dt()); - _paths_to_snap_to->push_back(SnapCandidatePath(pv, SNAPTARGET_TEXT_BASELINE, Geom::OptRect())); + pv->push_back(layout->baseline() * root_item->i2dt_affine() * + _candidate.additional_affine * _snapmanager->getDesktop()->doc2dt()); + _paths_to_snap_to->push_back( + SnapCandidatePath(pv, SNAPTARGET_TEXT_BASELINE, Geom::OptRect())); } } } else { @@ -424,27 +428,32 @@ void Inkscape::ObjectSnapper::_collectPaths(Geom::Point /*p*/, very_complex_path = path->nodesInPath() > 500; } - if (!very_complex_path && root_item && _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION)) { + if (!very_complex_path && root_item && + _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION)) { std::unique_ptr curve; SPShape *shape = dynamic_cast(root_item); if (shape) { curve = SPCurve::copy(shape->curve()); - }/* else if (dynamic_cast(root_item) || dynamic_cast(root_item)) { - curve = te_get_layout(root_item)->convertToCurves(); - }*/ + } /* else if (dynamic_cast(root_item) || dynamic_cast(root_item)) { + curve = te_get_layout(root_item)->convertToCurves(); + }*/ if (curve) { // We will get our own copy of the pathvector, which must be freed at some point Geom::PathVector *pv = new Geom::PathVector(curve->get_pathvector()); - (*pv) *= root_item->i2dt_affine() * _candidate.additional_affine * _snapmanager->getDesktop()->doc2dt(); // (_edit_transform * _i2d_transform); + (*pv) *= root_item->i2dt_affine() * _candidate.additional_affine * + _snapmanager->getDesktop()->doc2dt(); // (_edit_transform * _i2d_transform); - _paths_to_snap_to->push_back(SnapCandidatePath(pv, SNAPTARGET_PATH, Geom::OptRect())); // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it. + _paths_to_snap_to->push_back(SnapCandidatePath( + pv, SNAPTARGET_PATH, Geom::OptRect())); // Perhaps for speed, get a reference to the + // Geom::pathvector, and store the + // transformation besides it. } } } } } - //Add the item's bounding box to snap to + // Add the item's bounding box to snap to if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_BBOX_EDGE)) { if (p_is_other || p_is_a_bbox || (!_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node)) { // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox @@ -463,10 +472,9 @@ void Inkscape::ObjectSnapper::_collectPaths(Geom::Point /*p*/, } } -void Inkscape::ObjectSnapper::_snapPaths(IntermSnapResults &isr, - SnapCandidatePoint const &p, - std::vector *unselected_nodes, - SPPath const *selected_path) const +void Inkscape::ObjectSnapper::_snapPaths(IntermSnapResults &isr, SnapCandidatePoint const &p, + std::vector *unselected_nodes, + SPPath const *selected_path) const { _collectPaths(p.getPoint(), p.getSourceType(), p.getSourceNum() <= 0); // Now we can finally do the real snapping, using the paths collected above @@ -475,7 +483,9 @@ void Inkscape::ObjectSnapper::_snapPaths(IntermSnapResults &isr, g_assert(dt != nullptr); Geom::Point const p_doc = dt->dt2doc(p.getPoint()); - bool const node_tool_active = _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION) && selected_path != nullptr; + bool const node_tool_active = + _snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION) && + selected_path != nullptr; if (p.getSourceNum() <= 0) { /* findCandidates() is used for snapping to both paths and nodes. It ignores the path that is @@ -503,25 +513,27 @@ void Inkscape::ObjectSnapper::_snapPaths(IntermSnapResults &isr, bool snap_perp = _snapmanager->snapprefs.getSnapPerp(); bool snap_tang = _snapmanager->snapprefs.getSnapTang(); - //dt->snapindicator->remove_debugging_points(); - for (const auto & it_p : *_paths_to_snap_to) { + // dt->snapindicator->remove_debugging_points(); + for (const auto &it_p : *_paths_to_snap_to) { if (_allowSourceToSnapToTarget(p.getSourceType(), it_p.target_type, strict_snapping)) { bool const being_edited = node_tool_active && it_p.currently_being_edited; - //if true then this pathvector it_pv is currently being edited in the node tool + // if true then this pathvector it_pv is currently being edited in the node tool - for(Geom::PathVector::iterator it_pv = (it_p.path_vector)->begin(); it_pv != (it_p.path_vector)->end(); ++it_pv) { + for (Geom::PathVector::iterator it_pv = (it_p.path_vector)->begin(); it_pv != (it_p.path_vector)->end(); + ++it_pv) { // Find a nearest point for each curve within this path // n curves will return n time values with 0 <= t <= 1 std::vector anp = (*it_pv).nearestTimePerCurve(p_doc); - //std::cout << "#nearest points = " << anp.size() << " | p = " << p.getPoint() << std::endl; - // Now we will examine each of the nearest points, and determine whether it's within snapping range and if we should snap to it + // std::cout << "#nearest points = " << anp.size() << " | p = " << p.getPoint() << std::endl; + // Now we will examine each of the nearest points, and determine whether it's within snapping range and + // if we should snap to it std::vector::const_iterator np = anp.begin(); unsigned int index = 0; for (; np != anp.end(); ++np, index++) { Geom::Curve const *curve = &(it_pv->at(index)); Geom::Point const sp_doc = curve->pointAt(*np); - //dt->snapindicator->set_new_debugging_point(sp_doc*dt->doc2dt()); + // dt->snapindicator->set_new_debugging_point(sp_doc*dt->doc2dt()); bool c1 = true; bool c2 = true; if (being_edited) { @@ -535,11 +547,13 @@ void Inkscape::ObjectSnapper::_snapPaths(IntermSnapResults &isr, Geom::Point end_pt = dt->doc2dt(curve->pointAt(1)); c1 = isUnselectedNode(start_pt, unselected_nodes); c2 = isUnselectedNode(end_pt, unselected_nodes); - /* Unfortunately, this might yield false positives for coincident nodes. Inkscape might therefore mistakenly - * snap to path segments that are not stationary. There are at least two possible ways to overcome this: - * - Linking the individual nodes of the SPPath we have here, to the nodes of the NodePath::SubPath class as being - * used in sp_nodepath_selected_nodes_move. This class has a member variable called "selected". For this the nodes - * should be in the exact same order for both classes, so we can index them + /* Unfortunately, this might yield false positives for coincident nodes. Inkscape might + * therefore mistakenly snap to path segments that are not stationary. There are at least two + * possible ways to overcome this: + * - Linking the individual nodes of the SPPath we have here, to the nodes of the + * NodePath::SubPath class as being used in sp_nodepath_selected_nodes_move. This class has a + * member variable called "selected". For this the nodes should be in the exact same order for + * both classes, so we can index them * - Replacing the SPPath being used here by the NodePath::SubPath class; but how? */ } @@ -550,16 +564,19 @@ void Inkscape::ObjectSnapper::_snapPaths(IntermSnapResults &isr, // std::cout << " dist -> " << dist << std::endl; if (dist < getSnapperTolerance()) { // Add the curve we have snapped to - Geom::Point sp_tangent_dt = Geom::Point(0,0); + Geom::Point sp_tangent_dt = Geom::Point(0, 0); if (p.getSourceType() == Inkscape::SNAPSOURCE_GUIDE_ORIGIN) { // We currently only use the tangent when snapping guides, so only in this case we will // actually calculate the tangent to avoid wasting CPU cycles Geom::Point sp_tangent_doc = curve->unitTangentAt(*np); - sp_tangent_dt = dt->doc2dt(sp_tangent_doc) - dt->doc2dt(Geom::Point(0,0)); + sp_tangent_dt = dt->doc2dt(sp_tangent_doc) - dt->doc2dt(Geom::Point(0, 0)); } - isr.curves.emplace_back(sp_dt, sp_tangent_dt, num_path, index, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, curve, p.getSourceType(), p.getSourceNum(), it_p.target_type, it_p.target_bbox); + isr.curves.emplace_back(sp_dt, sp_tangent_dt, num_path, index, dist, getSnapperTolerance(), + getSnapperAlwaysSnap(), false, curve, p.getSourceType(), + p.getSourceNum(), it_p.target_type, it_p.target_bbox); if (snap_tang || snap_perp) { - // For each curve that's within snapping range, we will now also search for tangential and perpendicular snaps + // For each curve that's within snapping range, we will now also search for tangential + // and perpendicular snaps _snapPathsTangPerp(snap_tang, snap_perp, isr, p, curve, dt); } } @@ -572,7 +589,8 @@ void Inkscape::ObjectSnapper::_snapPaths(IntermSnapResults &isr, } /* Returns true if point is coincident with one of the unselected nodes */ -bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::vector const *unselected_nodes) const +bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, + std::vector const *unselected_nodes) const { if (unselected_nodes == nullptr) { return false; @@ -582,7 +600,7 @@ bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::ve return false; } - for (const auto & unselected_node : *unselected_nodes) { + for (const auto &unselected_node : *unselected_nodes) { if (Geom::L2(point - unselected_node.getPoint()) < 1e-4) { return true; } @@ -591,12 +609,10 @@ bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::ve return false; } -void Inkscape::ObjectSnapper::_snapPathsConstrained(IntermSnapResults &isr, - SnapCandidatePoint const &p, - SnapConstraint const &c, - Geom::Point const &p_proj_on_constraint) const +void Inkscape::ObjectSnapper::_snapPathsConstrained(IntermSnapResults &isr, SnapCandidatePoint const &p, + SnapConstraint const &c, + Geom::Point const &p_proj_on_constraint) const { - _collectPaths(p_proj_on_constraint, p.getSourceType(), p.getSourceNum() <= 0); // Now we can finally do the real snapping, using the paths collected above @@ -615,8 +631,8 @@ void Inkscape::ObjectSnapper::_snapPathsConstrained(IntermSnapResults &isr, Geom::Point const p_max_on_cl = dt->dt2doc(p_proj_on_constraint + getSnapperTolerance() * direction_vector); Geom::Coord tolerance = getSnapperTolerance(); - // PS: Because the paths we're about to snap to are all expressed relative to document coordinate system, we will have - // to convert the snapper coordinates from the desktop coordinates to document coordinates + // PS: Because the paths we're about to snap to are all expressed relative to document coordinate system, we will + // have to convert the snapper coordinates from the desktop coordinates to document coordinates Geom::PathVector constraint_path; if (c.isCircular()) { @@ -635,18 +651,20 @@ void Inkscape::ObjectSnapper::_snapPathsConstrained(IntermSnapResults &isr, bool strict_snapping = _snapmanager->snapprefs.getStrictSnapping(); // Find all intersections of the constrained path with the snap target candidates - for (const auto & k : *_paths_to_snap_to) { + for (const auto &k : *_paths_to_snap_to) { if (k.path_vector && _allowSourceToSnapToTarget(p.getSourceType(), k.target_type, strict_snapping)) { // Do the intersection math std::vector inters = constraint_path.intersect(*(k.path_vector)); // Convert the collected intersections to snapped points - for (const auto & inter : inters) { + for (const auto &inter : inters) { // Convert to desktop coordinates Geom::Point p_inters = dt->doc2dt(inter.point()); // Construct a snapped point Geom::Coord dist = Geom::L2(p.getPoint() - p_inters); - SnappedPoint s = SnappedPoint(p_inters, p.getSourceType(), p.getSourceNum(), k.target_type, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true, false, k.target_bbox); + SnappedPoint s = + SnappedPoint(p_inters, p.getSourceType(), p.getSourceNum(), k.target_type, dist, + getSnapperTolerance(), getSnapperAlwaysSnap(), true, false, k.target_bbox); // Store the snapped point if (dist <= tolerance) { // If the intersection is within snapping range, then we might snap to it isr.points.push_back(s); @@ -656,26 +674,26 @@ void Inkscape::ObjectSnapper::_snapPathsConstrained(IntermSnapResults &isr, } } - -void Inkscape::ObjectSnapper::freeSnap(IntermSnapResults &isr, - SnapCandidatePoint const &p, - Geom::OptRect const &bbox_to_snap, - std::vector const *it, - std::vector *unselected_nodes) const +void Inkscape::ObjectSnapper::freeSnap(IntermSnapResults &isr, SnapCandidatePoint const &p, + Geom::OptRect const &bbox_to_snap, std::vector const *it, + std::vector *unselected_nodes) const { - if (_snap_enabled == false || _snapmanager->snapprefs.isSourceSnappable(p.getSourceType()) == false || ThisSnapperMightSnap() == false) { + if (_snap_enabled == false || _snapmanager->snapprefs.isSourceSnappable(p.getSourceType()) == false || + ThisSnapperMightSnap() == false) { return; } /* Get a list of all the SPItems that we will try to snap to */ if (p.getSourceNum() <= 0) { Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint()); - _findCandidates(_snapmanager->getDocument()->getRoot(), it, p.getSourceNum() <= 0, local_bbox_to_snap, false, Geom::identity()); + _findCandidates(_snapmanager->getDocument()->getRoot(), it, p.getSourceNum() <= 0, local_bbox_to_snap, false, + Geom::identity()); } _snapNodes(isr, p, unselected_nodes); - if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION, SNAPTARGET_BBOX_EDGE, SNAPTARGET_PAGE_BORDER, SNAPTARGET_TEXT_BASELINE)) { + if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION, SNAPTARGET_BBOX_EDGE, + SNAPTARGET_PAGE_BORDER, SNAPTARGET_TEXT_BASELINE)) { unsigned n = (unselected_nodes == nullptr) ? 0 : unselected_nodes->size(); if (n > 0) { /* While editing a path in the node tool, findCandidates must ignore that path because @@ -688,7 +706,8 @@ void Inkscape::ObjectSnapper::freeSnap(IntermSnapResults &isr, SPPath const *tmpPath = dynamic_cast(*it->begin()); if ((it->size() == 1) && tmpPath) { path = tmpPath; - } // else: *it->begin() might be a SPGroup, e.g. when editing a LPE of text that has been converted to a group of paths + } // else: *it->begin() might be a SPGroup, e.g. when editing a LPE of text that has been converted to a + // group of paths // as reported in bug #356743. In that case we can just ignore it, i.e. not snap to this item } _snapPaths(isr, p, unselected_nodes, path); @@ -698,14 +717,13 @@ void Inkscape::ObjectSnapper::freeSnap(IntermSnapResults &isr, } } -void Inkscape::ObjectSnapper::constrainedSnap( IntermSnapResults &isr, - SnapCandidatePoint const &p, - Geom::OptRect const &bbox_to_snap, - SnapConstraint const &c, - std::vector const *it, - std::vector *unselected_nodes) const +void Inkscape::ObjectSnapper::constrainedSnap(IntermSnapResults &isr, SnapCandidatePoint const &p, + Geom::OptRect const &bbox_to_snap, SnapConstraint const &c, + std::vector const *it, + std::vector *unselected_nodes) const { - if (_snap_enabled == false || _snapmanager->snapprefs.isSourceSnappable(p.getSourceType()) == false || ThisSnapperMightSnap() == false) { + if (_snap_enabled == false || _snapmanager->snapprefs.isSourceSnappable(p.getSourceType()) == false || + ThisSnapperMightSnap() == false) { return; } @@ -715,7 +733,8 @@ void Inkscape::ObjectSnapper::constrainedSnap( IntermSnapResults &isr, /* Get a list of all the SPItems that we will try to snap to */ if (p.getSourceNum() <= 0) { Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(pp, pp); - _findCandidates(_snapmanager->getDocument()->getRoot(), it, p.getSourceNum() <= 0, local_bbox_to_snap, false, Geom::identity()); + _findCandidates(_snapmanager->getDocument()->getRoot(), it, p.getSourceNum() <= 0, local_bbox_to_snap, false, + Geom::identity()); } // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line). @@ -724,7 +743,8 @@ void Inkscape::ObjectSnapper::constrainedSnap( IntermSnapResults &isr, _snapNodes(isr, p, unselected_nodes, c, pp); - if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION, SNAPTARGET_BBOX_EDGE, SNAPTARGET_PAGE_BORDER, SNAPTARGET_TEXT_BASELINE)) { + if (_snapmanager->snapprefs.isTargetSnappable(SNAPTARGET_PATH, SNAPTARGET_PATH_INTERSECTION, SNAPTARGET_BBOX_EDGE, + SNAPTARGET_PAGE_BORDER, SNAPTARGET_TEXT_BASELINE)) { _snapPathsConstrained(isr, p, c, pp); } } @@ -736,19 +756,21 @@ bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const void Inkscape::ObjectSnapper::_clear_paths() const { - for (const auto & k : *_paths_to_snap_to) { + for (const auto &k : *_paths_to_snap_to) { delete k.path_vector; } _paths_to_snap_to->clear(); } -Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const +Geom::PathVector *Inkscape::ObjectSnapper::_getBorderPathv() const { - Geom::Rect const border_rect = Geom::Rect(Geom::Point(0,0), Geom::Point((_snapmanager->getDocument())->getWidth().value("px"),(_snapmanager->getDocument())->getHeight().value("px"))); + Geom::Rect const border_rect = + Geom::Rect(Geom::Point(0, 0), Geom::Point((_snapmanager->getDocument())->getWidth().value("px"), + (_snapmanager->getDocument())->getHeight().value("px"))); return _getPathvFromRect(border_rect); } -Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const +Geom::PathVector *Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const { auto const border_curve = SPCurve::new_from_rect(rect, true); if (border_curve) { @@ -763,37 +785,39 @@ void Inkscape::ObjectSnapper::_getBorderNodes(std::vector *p { Geom::Coord w = (_snapmanager->getDocument())->getWidth().value("px"); Geom::Coord h = (_snapmanager->getDocument())->getHeight().value("px"); - points->push_back(SnapCandidatePoint(Geom::Point(0,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER)); - points->push_back(SnapCandidatePoint(Geom::Point(0,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER)); - points->push_back(SnapCandidatePoint(Geom::Point(w,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER)); - points->push_back(SnapCandidatePoint(Geom::Point(w,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER)); + points->push_back(SnapCandidatePoint(Geom::Point(0, 0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER)); + points->push_back(SnapCandidatePoint(Geom::Point(0, h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER)); + points->push_back(SnapCandidatePoint(Geom::Point(w, h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER)); + points->push_back(SnapCandidatePoint(Geom::Point(w, 0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER)); } -void Inkscape::getBBoxPoints(Geom::OptRect const bbox, - std::vector *points, - bool const /*isTarget*/, - bool const includeCorners, - bool const includeLineMidpoints, +void Inkscape::getBBoxPoints(Geom::OptRect const bbox, std::vector *points, bool const /*isTarget*/, + bool const includeCorners, bool const includeLineMidpoints, bool const includeObjectMidpoints) { if (bbox) { // collect the corners of the bounding box - for ( unsigned k = 0 ; k < 4 ; k++ ) { + for (unsigned k = 0; k < 4; k++) { if (includeCorners) { - points->push_back(SnapCandidatePoint(bbox->corner(k), SNAPSOURCE_BBOX_CORNER, -1, SNAPTARGET_BBOX_CORNER, *bbox)); + points->push_back( + SnapCandidatePoint(bbox->corner(k), SNAPSOURCE_BBOX_CORNER, -1, SNAPTARGET_BBOX_CORNER, *bbox)); } // optionally, collect the midpoints of the bounding box's edges too if (includeLineMidpoints) { - points->push_back(SnapCandidatePoint((bbox->corner(k) + bbox->corner((k+1) % 4))/2, SNAPSOURCE_BBOX_EDGE_MIDPOINT, -1, SNAPTARGET_BBOX_EDGE_MIDPOINT, *bbox)); + points->push_back(SnapCandidatePoint((bbox->corner(k) + bbox->corner((k + 1) % 4)) / 2, + SNAPSOURCE_BBOX_EDGE_MIDPOINT, -1, SNAPTARGET_BBOX_EDGE_MIDPOINT, + *bbox)); } } if (includeObjectMidpoints) { - points->push_back(SnapCandidatePoint(bbox->midpoint(), SNAPSOURCE_BBOX_MIDPOINT, -1, SNAPTARGET_BBOX_MIDPOINT, *bbox)); + points->push_back( + SnapCandidatePoint(bbox->midpoint(), SNAPSOURCE_BBOX_MIDPOINT, -1, SNAPTARGET_BBOX_MIDPOINT, *bbox)); } } } -bool Inkscape::ObjectSnapper::_allowSourceToSnapToTarget(SnapSourceType source, SnapTargetType target, bool strict_snapping) const +bool Inkscape::ObjectSnapper::_allowSourceToSnapToTarget(SnapSourceType source, SnapTargetType target, + bool strict_snapping) const { bool allow_this_pair_to_snap = true; @@ -807,32 +831,38 @@ bool Inkscape::ObjectSnapper::_allowSourceToSnapToTarget(SnapSourceType source, return allow_this_pair_to_snap; } -void Inkscape::ObjectSnapper::_snapPathsTangPerp(bool snap_tang, bool snap_perp, IntermSnapResults &isr, SnapCandidatePoint const &p, Geom::Curve const *curve, SPDesktop const *dt) const +void Inkscape::ObjectSnapper::_snapPathsTangPerp(bool snap_tang, bool snap_perp, IntermSnapResults &isr, + SnapCandidatePoint const &p, Geom::Curve const *curve, + SPDesktop const *dt) const { - // Here we will try to snap either tangentially or perpendicularly to a single path; for this we need to know where the origin is located of the line that is currently being rotated, - // or we need to know the vector of the guide which is currently being translated - std::vector > const origins_and_vectors = p.getOriginsAndVectors(); - // Now we will iterate over all the origins and vectors and see which of these will get use a tangential or perpendicular snap - for (const auto & origins_and_vector : origins_and_vectors) { - Geom::Point origin_or_vector_doc = dt->dt2doc(origins_and_vector.first); // "first" contains a Geom::Point, denoting either a point or vector + // Here we will try to snap either tangentially or perpendicularly to a single path; for this we need to know where + // the origin is located of the line that is currently being rotated, or we need to know the vector of the guide + // which is currently being translated + std::vector> const origins_and_vectors = p.getOriginsAndVectors(); + // Now we will iterate over all the origins and vectors and see which of these will get use a tangential or + // perpendicular snap + for (const auto &origins_and_vector : origins_and_vectors) { + Geom::Point origin_or_vector_doc = + dt->dt2doc(origins_and_vector.first); // "first" contains a Geom::Point, denoting either a point or vector if (origins_and_vector.second) { // if "second" is true then "first" is a vector, otherwise it's a point // So we have a vector, which tells us what tangential or perpendicular direction we're looking for if (curve->degreesOfFreedom() <= 2) { // A LineSegment has order one, and therefore 2 DOF - // When snapping to a point of a line segment that has a specific tangential or normal vector, then either all point - // along that line will be snapped to or no points at all will be snapped to. This is not very useful, so let's skip - // any line segments and lets only snap to higher order curves + // When snapping to a point of a line segment that has a specific tangential or normal vector, then + // either all point along that line will be snapped to or no points at all will be snapped to. This is + // not very useful, so let's skip any line segments and lets only snap to higher order curves continue; } - // The vector is being treated as a point (relative to the origin), and has been translated to document coordinates accordingly - // We need however to make it a vector again, because also the origin has been transformed - origin_or_vector_doc -= dt->dt2doc(Geom::Point(0,0)); + // The vector is being treated as a point (relative to the origin), and has been translated to document + // coordinates accordingly We need however to make it a vector again, because also the origin has been + // transformed + origin_or_vector_doc -= dt->dt2doc(Geom::Point(0, 0)); } Geom::Point point_dt; Geom::Coord dist; std::vector ts; - if (snap_tang) { // Find all points that lead to a tangential snap + if (snap_tang) { // Find all points that lead to a tangential snap if (origins_and_vector.second) { // if "second" is true then "first" is a vector, otherwise it's a point ts = find_tangents_by_vector(origin_or_vector_doc, curve->toSBasis()); } else { @@ -841,7 +871,8 @@ void Inkscape::ObjectSnapper::_snapPathsTangPerp(bool snap_tang, bool snap_perp, for (double t : ts) { point_dt = dt->doc2dt(curve->pointAt(t)); dist = Geom::distance(point_dt, p.getPoint()); - isr.points.emplace_back(point_dt, p.getSourceType(), p.getSourceNum(), SNAPTARGET_PATH_TANGENTIAL, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, true); + isr.points.emplace_back(point_dt, p.getSourceType(), p.getSourceNum(), SNAPTARGET_PATH_TANGENTIAL, dist, + getSnapperTolerance(), getSnapperAlwaysSnap(), false, true); } } @@ -854,7 +885,8 @@ void Inkscape::ObjectSnapper::_snapPathsTangPerp(bool snap_tang, bool snap_perp, for (double t : ts) { point_dt = dt->doc2dt(curve->pointAt(t)); dist = Geom::distance(point_dt, p.getPoint()); - isr.points.emplace_back(point_dt, p.getSourceType(), p.getSourceNum(), SNAPTARGET_PATH_PERPENDICULAR, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, true); + isr.points.emplace_back(point_dt, p.getSourceType(), p.getSourceNum(), SNAPTARGET_PATH_PERPENDICULAR, + dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, true); } } } diff --git a/src/object-snapper.h b/src/object-snapper.h index 1709137db30fe29c573992b15581c65a7b06f0a3..ba1c7d140ccca4c933162834d35defffe5c82229 100644 --- a/src/object-snapper.h +++ b/src/object-snapper.h @@ -11,8 +11,8 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "snapper.h" #include "snap-candidate.h" +#include "snapper.h" class SPDesktop; class SPNamedView; @@ -21,15 +21,13 @@ class SPObject; class SPPath; class SPDesktop; -namespace Inkscape -{ +namespace Inkscape { /** * Snapping things to objects. */ class ObjectSnapper : public Snapper { - public: ObjectSnapper(SnapManager *sm, Geom::Coord const d); ~ObjectSnapper() override; @@ -40,93 +38,81 @@ public: bool ThisSnapperMightSnap() const override; /** - * @return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen pixels. + * @return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen + * pixels. */ - Geom::Coord getSnapperTolerance() const override; //returns the tolerance of the snapper in screen pixels (i.e. independent of zoom) + Geom::Coord getSnapperTolerance() const override; // returns the tolerance of the snapper in screen pixels (i.e. + // independent of zoom) - bool getSnapperAlwaysSnap() const override; //if true, then the snapper will always snap, regardless of its tolerance + bool getSnapperAlwaysSnap() const override; // if true, then the snapper will always snap, regardless of its + // tolerance - void freeSnap(IntermSnapResults &isr, - Inkscape::SnapCandidatePoint const &p, - Geom::OptRect const &bbox_to_snap, + void freeSnap(IntermSnapResults &isr, Inkscape::SnapCandidatePoint const &p, Geom::OptRect const &bbox_to_snap, std::vector const *it, std::vector *unselected_nodes) const override; - void constrainedSnap(IntermSnapResults &isr, - Inkscape::SnapCandidatePoint const &p, - Geom::OptRect const &bbox_to_snap, - SnapConstraint const &c, - std::vector const *it, - std::vector *unselected_nodes) const override; + void constrainedSnap(IntermSnapResults &isr, Inkscape::SnapCandidatePoint const &p, + Geom::OptRect const &bbox_to_snap, SnapConstraint const &c, + std::vector const *it, + std::vector *unselected_nodes) const override; private: - //store some lists of candidates, points and paths, so we don't have to rebuild them for each point we want to snap + // store some lists of candidates, points and paths, so we don't have to rebuild them for each point we want to snap std::vector *_candidates; std::vector *_points_to_snap_to; - std::vector *_paths_to_snap_to; + std::vector *_paths_to_snap_to; /** * Find all items within snapping range. * @param parent Pointer to the document's root, or to a clipped path or mask object. * @param it List of items to ignore. - * @param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation. + * @param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the + * same transformation. * @param clip_or_mask The parent object being passed is either a clip or mask. */ - void _findCandidates(SPObject* parent, - std::vector const *it, - bool const &first_point, - Geom::Rect const &bbox_to_snap, - bool const _clip_or_mask, - Geom::Affine const additional_affine) const; + void _findCandidates(SPObject *parent, std::vector const *it, bool const &first_point, + Geom::Rect const &bbox_to_snap, bool const _clip_or_mask, + Geom::Affine const additional_affine) const; void _snapNodes(IntermSnapResults &isr, - Inkscape::SnapCandidatePoint const &p, // in desktop coordinates - std::vector *unselected_nodes, - SnapConstraint const &c = SnapConstraint(), - Geom::Point const &p_proj_on_constraint = Geom::Point()) const; + Inkscape::SnapCandidatePoint const &p, // in desktop coordinates + std::vector *unselected_nodes, SnapConstraint const &c = SnapConstraint(), + Geom::Point const &p_proj_on_constraint = Geom::Point()) const; - void _snapTranslatingGuide(IntermSnapResults &isr, - Geom::Point const &p, - Geom::Point const &guide_normal) const; + void _snapTranslatingGuide(IntermSnapResults &isr, Geom::Point const &p, Geom::Point const &guide_normal) const; - void _collectNodes(Inkscape::SnapSourceType const &t, - bool const &first_point) const; + void _collectNodes(Inkscape::SnapSourceType const &t, bool const &first_point) const; void _snapPaths(IntermSnapResults &isr, - Inkscape::SnapCandidatePoint const &p, // in desktop coordinates - std::vector *unselected_nodes, // in desktop coordinates - SPPath const *selected_path) const; + Inkscape::SnapCandidatePoint const &p, // in desktop coordinates + std::vector *unselected_nodes, // in desktop coordinates + SPPath const *selected_path) const; void _snapPathsConstrained(IntermSnapResults &isr, - Inkscape::SnapCandidatePoint const &p, // in desktop coordinates - SnapConstraint const &c, - Geom::Point const &p_proj_on_constraint) const; + Inkscape::SnapCandidatePoint const &p, // in desktop coordinates + SnapConstraint const &c, Geom::Point const &p_proj_on_constraint) const; - void _snapPathsTangPerp(bool snap_tang, - bool snap_perp, - IntermSnapResults &isr, - SnapCandidatePoint const &p, - Geom::Curve const *curve, - SPDesktop const *dt) const; + void _snapPathsTangPerp(bool snap_tang, bool snap_perp, IntermSnapResults &isr, SnapCandidatePoint const &p, + Geom::Curve const *curve, SPDesktop const *dt) const; - bool isUnselectedNode(Geom::Point const &point, std::vector const *unselected_nodes) const; + bool isUnselectedNode(Geom::Point const &point, + std::vector const *unselected_nodes) const; /** * Returns index of first NR_END bpath in array. */ - void _collectPaths(Geom::Point p, - Inkscape::SnapSourceType const source_type, - bool const &first_point) const; + void _collectPaths(Geom::Point p, Inkscape::SnapSourceType const source_type, bool const &first_point) const; void _clear_paths() const; - Geom::PathVector* _getBorderPathv() const; - Geom::PathVector* _getPathvFromRect(Geom::Rect const rect) const; + Geom::PathVector *_getBorderPathv() const; + Geom::PathVector *_getPathvFromRect(Geom::Rect const rect) const; void _getBorderNodes(std::vector *points) const; bool _allowSourceToSnapToTarget(SnapSourceType source, SnapTargetType target, bool strict_snapping) const; }; // end of ObjectSnapper class -void getBBoxPoints(Geom::OptRect const bbox, std::vector *points, bool const isTarget, bool const includeCorners, bool const includeLineMidpoints, bool const includeObjectMidpoints); +void getBBoxPoints(Geom::OptRect const bbox, std::vector *points, bool const isTarget, + bool const includeCorners, bool const includeLineMidpoints, bool const includeObjectMidpoints); } // end of namespace Inkscape diff --git a/src/object/box3d-side.cpp b/src/object/box3d-side.cpp index b24d62cc494c36d346a1beea4fcc70382351bfd4..472237df3129af46b6259b453232d5829cda6d32 100644 --- a/src/object/box3d-side.cpp +++ b/src/object/box3d-side.cpp @@ -13,22 +13,25 @@ */ #include "box3d-side.h" -#include "document.h" -#include "xml/document.h" -#include "xml/repr.h" -#include "display/curve.h" -#include "svg/svg.h" + #include "attributes.h" +#include "desktop-style.h" +#include "display/curve.h" +#include "document.h" #include "inkscape.h" -#include "object/persp3d.h" -#include "object/persp3d-reference.h" #include "object/box3d.h" +#include "object/persp3d-reference.h" +#include "object/persp3d.h" +#include "svg/svg.h" #include "ui/tools/box3d-tool.h" -#include "desktop-style.h" +#include "xml/document.h" +#include "xml/repr.h" static void box3d_side_compute_corner_ids(Box3DSide *side, unsigned int corners[4]); -Box3DSide::Box3DSide() : SPPolygon() { +Box3DSide::Box3DSide() + : SPPolygon() +{ this->dir1 = Box3D::NONE; this->dir2 = Box3D::NONE; this->front_or_rear = Box3D::FRONT; @@ -36,14 +39,15 @@ Box3DSide::Box3DSide() : SPPolygon() { Box3DSide::~Box3DSide() = default; -void Box3DSide::build(SPDocument * document, Inkscape::XML::Node * repr) { +void Box3DSide::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPPolygon::build(document, repr); this->readAttr(SPAttr::INKSCAPE_BOX3D_SIDE_TYPE); } - -Inkscape::XML::Node* Box3DSide::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *Box3DSide::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { // this is where we end up when saving as plain SVG (also in other circumstances?) // thus we don' set "sodipodi:type" so that the box is only saved as an ordinary svg:path @@ -59,21 +63,22 @@ Inkscape::XML::Node* Box3DSide::write(Inkscape::XML::Document *xml_doc, Inkscape /* Duplicate the path */ SPCurve const *curve = this->_curve.get(); - //Nulls might be possible if this called iteratively - if ( !curve ) { + // Nulls might be possible if this called iteratively + if (!curve) { return nullptr; } - char *d = sp_svg_write_path ( curve->get_pathvector() ); + char *d = sp_svg_write_path(curve->get_pathvector()); repr->setAttribute("d", d); - g_free (d); + g_free(d); SPPolygon::write(xml_doc, repr, flags); return repr; } -void Box3DSide::set(SPAttr key, const gchar* value) { +void Box3DSide::set(SPAttr key, const gchar *value) +{ // TODO: In case the box was recreated (by undo, e.g.) we need to recreate the path // (along with other info?) from the parent box. @@ -81,38 +86,37 @@ void Box3DSide::set(SPAttr key, const gchar* value) { switch (key) { case SPAttr::INKSCAPE_BOX3D_SIDE_TYPE: if (value) { - guint desc = atoi (value); + guint desc = atoi(value); if (!Box3D::is_face_id(desc)) { - g_print ("desc is not a face id: =%s=\n", value); + g_print("desc is not a face id: =%s=\n", value); } - g_return_if_fail (Box3D::is_face_id (desc)); + g_return_if_fail(Box3D::is_face_id(desc)); - Box3D::Axis plane = (Box3D::Axis) (desc & 0x7); + Box3D::Axis plane = (Box3D::Axis)(desc & 0x7); plane = (Box3D::is_plane(plane) ? plane : Box3D::orth_plane_or_axis(plane)); this->dir1 = Box3D::extract_first_axis_direction(plane); this->dir2 = Box3D::extract_second_axis_direction(plane); - this->front_or_rear = (Box3D::FrontOrRear) (desc & 0x8); + this->front_or_rear = (Box3D::FrontOrRear)(desc & 0x8); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } break; - default: - SPPolygon::set(key, value); - break; + default: + SPPolygon::set(key, value); + break; } } -void Box3DSide::update(SPCtx* ctx, guint flags) { +void Box3DSide::update(SPCtx *ctx, guint flags) +{ if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - flags &= ~SP_OBJECT_USER_MODIFIED_FLAG_B; // since we change the description, it's not a "just translation" anymore + flags &= + ~SP_OBJECT_USER_MODIFIED_FLAG_B; // since we change the description, it's not a "just translation" anymore } - if (flags & (SP_OBJECT_MODIFIED_FLAG | - SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { this->set_shape(); } @@ -120,34 +124,36 @@ void Box3DSide::update(SPCtx* ctx, guint flags) { } /* Create a new Box3DSide and append it to the parent box */ -Box3DSide * Box3DSide::createBox3DSide(SPBox3D *box) +Box3DSide *Box3DSide::createBox3DSide(SPBox3D *box) { - Box3DSide *box3d_side = nullptr; - Inkscape::XML::Document *xml_doc = box->document->getReprDoc();; - Inkscape::XML::Node *repr_side = xml_doc->createElement("svg:path"); - repr_side->setAttribute("sodipodi:type", "inkscape:box3dside"); - box3d_side = static_cast(box->appendChildRepr(repr_side)); - return box3d_side; + Box3DSide *box3d_side = nullptr; + Inkscape::XML::Document *xml_doc = box->document->getReprDoc(); + ; + Inkscape::XML::Node *repr_side = xml_doc->createElement("svg:path"); + repr_side->setAttribute("sodipodi:type", "inkscape:box3dside"); + box3d_side = static_cast(box->appendChildRepr(repr_side)); + return box3d_side; } /* - * Function which return the type attribute for Box3D. + * Function which return the type attribute for Box3D. * Acts as a replacement for directly accessing the XML Tree directly. */ int Box3DSide::getFaceId() { - return this->getIntAttribute("inkscape:box3dsidetype", -1); + return this->getIntAttribute("inkscape:box3dsidetype", -1); } -void -Box3DSide::position_set () { - this->set_shape(); +void Box3DSide::position_set() +{ + this->set_shape(); // This call is responsible for live update of the sides during the initial drag this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void Box3DSide::set_shape() { +void Box3DSide::set_shape() +{ if (!this->document->getRoot()) { // avoid a warning caused by sp_document_height() (which is called from sp_item_i2d_affine() below) // when reading a file containing 3D boxes @@ -178,12 +184,9 @@ void Box3DSide::set_shape() { auto c = std::make_unique(); - if (!box->get_corner_screen(corners[0]).isFinite() || - !box->get_corner_screen(corners[1]).isFinite() || - !box->get_corner_screen(corners[2]).isFinite() || - !box->get_corner_screen(corners[3]).isFinite() ) - { - g_warning ("Trying to draw a 3D box side with invalid coordinates.\n"); + if (!box->get_corner_screen(corners[0]).isFinite() || !box->get_corner_screen(corners[1]).isFinite() || + !box->get_corner_screen(corners[2]).isFinite() || !box->get_corner_screen(corners[3]).isFinite()) { + g_warning("Trying to draw a 3D box side with invalid coordinates.\n"); return; } @@ -194,7 +197,8 @@ void Box3DSide::set_shape() { c->closepath(); /* Reset the shape's curve to the "original_curve" - * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in shape)*/ + * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in + * shape)*/ SPCurve const *before = curveBeforeLPE(); if (before && before->get_pathvector() != c->get_pathvector()) { @@ -214,9 +218,9 @@ void Box3DSide::set_shape() { Glib::ustring Box3DSide::axes_string() const { - Glib::ustring result(Box3D::string_from_axes((Box3D::Axis) (this->dir1 ^ this->dir2))); + Glib::ustring result(Box3D::string_from_axes((Box3D::Axis)(this->dir1 ^ this->dir2))); - switch ((Box3D::Axis) (this->dir1 ^ this->dir2)) { + switch ((Box3D::Axis)(this->dir1 ^ this->dir2)) { case Box3D::XY: result += ((this->front_or_rear == Box3D::FRONT) ? "front" : "rear"); break; @@ -236,9 +240,9 @@ Glib::ustring Box3DSide::axes_string() const return result; } -static void -box3d_side_compute_corner_ids(Box3DSide *side, unsigned int corners[4]) { - Box3D::Axis orth = Box3D::third_axis_direction (side->dir1, side->dir2); +static void box3d_side_compute_corner_ids(Box3DSide *side, unsigned int corners[4]) +{ + Box3D::Axis orth = Box3D::third_axis_direction(side->dir1, side->dir2); corners[0] = (side->front_or_rear ? orth : 0); corners[1] = corners[0] ^ side->dir1; @@ -246,13 +250,14 @@ box3d_side_compute_corner_ids(Box3DSide *side, unsigned int corners[4]) { corners[3] = corners[0] ^ side->dir2; } -Persp3D * -Box3DSide::perspective() const { +Persp3D *Box3DSide::perspective() const +{ SPBox3D *box = dynamic_cast(this->parent); return box ? box->persp_ref->getObject() : nullptr; } -Inkscape::XML::Node *Box3DSide::convert_to_path() const { +Inkscape::XML::Node *Box3DSide::convert_to_path() const +{ // TODO: Copy over all important attributes (see sp_selected_item_to_curved_repr() for an example) SPDocument *doc = this->document; Inkscape::XML::Document *xml_doc = doc->getReprDoc(); diff --git a/src/object/box3d-side.h b/src/object/box3d-side.h index 995feaa7bcdcccf004da5f9155a1237d1e0f0c8a..c300359151e4fe03087f51ba587f1388b81274a2 100644 --- a/src/object/box3d-side.h +++ b/src/object/box3d-side.h @@ -15,31 +15,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "sp-polygon.h" #include "axis-manip.h" - +#include "sp-polygon.h" class SPBox3D; class Persp3D; // FIXME: Would it be better to inherit from SPPath instead? -class Box3DSide : public SPPolygon { +class Box3DSide : public SPPolygon +{ public: - Box3DSide(); - ~Box3DSide() override; + Box3DSide(); + ~Box3DSide() override; Box3D::Axis dir1; Box3D::Axis dir2; Box3D::FrontOrRear front_or_rear; int getFaceId(); - static Box3DSide * createBox3DSide(SPBox3D *box); + static Box3DSide *createBox3DSide(SPBox3D *box); - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void set(SPAttr key, char const* value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - void update(SPCtx *ctx, unsigned int flags) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void set(SPAttr key, char const *value) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - void set_shape() override; + void set_shape() override; void position_set(); // FIXME: Replace this by Box3DSide::set_shape?? @@ -47,7 +48,6 @@ public: Persp3D *perspective() const; - Inkscape::XML::Node *convert_to_path() const; }; diff --git a/src/object/box3d.cpp b/src/object/box3d.cpp index 80099631855e2c32c1f5778c3bbd0dbd33ef0131..48dc64d479850f49601b03a039589012b00cf7e5 100644 --- a/src/object/box3d.cpp +++ b/src/object/box3d.cpp @@ -18,30 +18,30 @@ #include "box3d.h" +#include <2geom/line.h> #include -#include "attributes.h" -#include "xml/document.h" -#include "xml/repr.h" +#include "attributes.h" #include "bad-uri-exception.h" #include "box3d-side.h" -#include "ui/tools/box3d-tool.h" -#include "perspective-line.h" +#include "desktop.h" +#include "include/macros.h" #include "persp3d-reference.h" -#include "uri.h" -#include <2geom/line.h> +#include "perspective-line.h" #include "sp-guide.h" #include "sp-namedview.h" - -#include "desktop.h" - -#include "include/macros.h" +#include "ui/tools/box3d-tool.h" +#include "uri.h" +#include "xml/document.h" +#include "xml/repr.h" static void box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box); static gint counter = 0; -SPBox3D::SPBox3D() : SPGroup() { +SPBox3D::SPBox3D() + : SPGroup() +{ this->my_counter = 0; this->swapped = Box3D::NONE; @@ -49,26 +49,27 @@ SPBox3D::SPBox3D() : SPGroup() { this->persp_ref = new Persp3DReference(this); /* we initialize the z-orders to zero so that they are updated during dragging */ - for (int & z_order : z_orders) { + for (int &z_order : z_orders) { z_order = 0; } } SPBox3D::~SPBox3D() = default; -void SPBox3D::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPBox3D::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPGroup::build(document, repr); my_counter = counter++; /* we initialize the z-orders to zero so that they are updated during dragging */ - for (int & z_order : z_orders) { + for (int &z_order : z_orders) { z_order = 0; } // TODO: Create/link to the correct perspective - if ( document ) { + if (document) { persp_ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(box3d_ref_changed), this)); readAttr(SPAttr::INKSCAPE_BOX3D_PERSPECTIVE_ID); @@ -77,8 +78,9 @@ void SPBox3D::build(SPDocument *document, Inkscape::XML::Node *repr) { } } -void SPBox3D::release() { - SPBox3D* object = this; +void SPBox3D::release() +{ + SPBox3D *object = this; SPBox3D *box = object; if (box->persp_href) { @@ -97,7 +99,7 @@ void SPBox3D::release() { } if (persp) { - persp->remove_box (box); + persp->remove_box(box); /* // TODO: This deletes a perspective when the last box referring to it is gone. Eventually, // it would be nice to have this but currently it crashes when undoing/redoing box deletion @@ -115,13 +117,14 @@ void SPBox3D::release() { SPGroup::release(); } -void SPBox3D::set(SPAttr key, const gchar* value) { - SPBox3D* object = this; +void SPBox3D::set(SPAttr key, const gchar *value) +{ + SPBox3D *object = this; SPBox3D *box = object; switch (key) { case SPAttr::INKSCAPE_BOX3D_PERSPECTIVE_ID: - if ( value && box->persp_href && ( strcmp(value, box->persp_href) == 0 ) ) { + if (value && box->persp_href && (strcmp(value, box->persp_href) == 0)) { /* No change, do nothing. */ } else { if (box->persp_href) { @@ -170,8 +173,7 @@ void SPBox3D::set(SPAttr key, const gchar* value) { /** * Gets called when (re)attached to another perspective. */ -static void -box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box) +static void box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box) { if (old_ref) { sp_signal_disconnect_by_data(old_ref, box); @@ -181,27 +183,27 @@ box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box) } } Persp3D *persp = dynamic_cast(ref); - if ( persp && (ref != box) ) // FIXME: Comparisons sane? + if (persp && (ref != box)) // FIXME: Comparisons sane? { persp->add_box(box); } } -void SPBox3D::update(SPCtx *ctx, guint flags) { +void SPBox3D::update(SPCtx *ctx, guint flags) +{ if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - /* FIXME?: Perhaps the display updates of box sides should be instantiated from here, but this causes evil update loops so it's all done from SPBox3D::position_set, which is called from various other places (like the handlers in shape-editor-knotholders.cpp, vanishing-point.cpp, etc. */ - } // Invoke parent method SPGroup::update(ctx, flags); } -Inkscape::XML::Node* SPBox3D::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - SPBox3D* object = this; +Inkscape::XML::Node *SPBox3D::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + SPBox3D *object = this; SPBox3D *box = object; if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { @@ -211,7 +213,6 @@ Inkscape::XML::Node* SPBox3D::write(Inkscape::XML::Document *xml_doc, Inkscape:: } if (flags & SP_OBJECT_WRITE_EXT) { - if (box->persp_href) { repr->setAttribute("inkscape:perspectiveID", box->persp_href); } else { @@ -246,7 +247,8 @@ Inkscape::XML::Node* SPBox3D::write(Inkscape::XML::Document *xml_doc, Inkscape:: return repr; } -const char* SPBox3D::display_name() { +const char *SPBox3D::display_name() +{ return _("3D Box"); } @@ -254,7 +256,7 @@ void SPBox3D::position_set() { /* This draws the curve and calls requestDisplayUpdate() for each side (the latter is done in Box3DSide::position_set() to avoid update conflicts with the parent box) */ - for (auto& obj: this->children) { + for (auto &obj : this->children) { Box3DSide *side = dynamic_cast(&obj); if (side) { side->position_set(); @@ -262,7 +264,8 @@ void SPBox3D::position_set() } } -Geom::Affine SPBox3D::set_transform(Geom::Affine const &xform) { +Geom::Affine SPBox3D::set_transform(Geom::Affine const &xform) +{ // We don't apply the transform to the box directly but instead to its perspective (which is // done in sp_selection_apply_affine). Here we only adjust strokes, patterns, etc. @@ -270,7 +273,7 @@ Geom::Affine SPBox3D::set_transform(Geom::Affine const &xform) { gdouble const sw = hypot(ret[0], ret[1]); gdouble const sh = hypot(ret[2], ret[3]); - for (auto& child: children) { + for (auto &child : children) { SPItem *childitem = dynamic_cast(&child); if (childitem) { // Adjust stroke width @@ -287,29 +290,26 @@ Geom::Affine SPBox3D::set_transform(Geom::Affine const &xform) { return Geom::identity(); } -static Proj::Pt3 -box3d_get_proj_corner (guint id, Proj::Pt3 const &c0, Proj::Pt3 const &c7) { - return Proj::Pt3 ((id & Box3D::X) ? c7[Proj::X] : c0[Proj::X], - (id & Box3D::Y) ? c7[Proj::Y] : c0[Proj::Y], - (id & Box3D::Z) ? c7[Proj::Z] : c0[Proj::Z], - 1.0); +static Proj::Pt3 box3d_get_proj_corner(guint id, Proj::Pt3 const &c0, Proj::Pt3 const &c7) +{ + return Proj::Pt3((id & Box3D::X) ? c7[Proj::X] : c0[Proj::X], (id & Box3D::Y) ? c7[Proj::Y] : c0[Proj::Y], + (id & Box3D::Z) ? c7[Proj::Z] : c0[Proj::Z], 1.0); } -static Proj::Pt3 -box3d_get_proj_corner (SPBox3D const *box, guint id) { - return Proj::Pt3 ((id & Box3D::X) ? box->orig_corner7[Proj::X] : box->orig_corner0[Proj::X], - (id & Box3D::Y) ? box->orig_corner7[Proj::Y] : box->orig_corner0[Proj::Y], - (id & Box3D::Z) ? box->orig_corner7[Proj::Z] : box->orig_corner0[Proj::Z], - 1.0); +static Proj::Pt3 box3d_get_proj_corner(SPBox3D const *box, guint id) +{ + return Proj::Pt3((id & Box3D::X) ? box->orig_corner7[Proj::X] : box->orig_corner0[Proj::X], + (id & Box3D::Y) ? box->orig_corner7[Proj::Y] : box->orig_corner0[Proj::Y], + (id & Box3D::Z) ? box->orig_corner7[Proj::Z] : box->orig_corner0[Proj::Z], 1.0); } -Geom::Point -SPBox3D::get_corner_screen (guint id, bool item_coords) const { - Proj::Pt3 proj_corner (box3d_get_proj_corner (this, id)); +Geom::Point SPBox3D::get_corner_screen(guint id, bool item_coords) const +{ + Proj::Pt3 proj_corner(box3d_get_proj_corner(this, id)); if (!this->get_perspective()) { - return Geom::Point (Geom::infinity(), Geom::infinity()); + return Geom::Point(Geom::infinity(), Geom::infinity()); } - Geom::Affine const i2d(this->i2dt_affine ()); + Geom::Affine const i2d(this->i2dt_affine()); if (item_coords) { return this->get_perspective()->perspective_impl->tmat.image(proj_corner).affine() * i2d.inverse(); } else { @@ -317,23 +317,22 @@ SPBox3D::get_corner_screen (guint id, bool item_coords) const { } } -Proj::Pt3 -SPBox3D::get_proj_center () { +Proj::Pt3 SPBox3D::get_proj_center() +{ this->orig_corner0.normalize(); this->orig_corner7.normalize(); - return Proj::Pt3 ((this->orig_corner0[Proj::X] + this->orig_corner7[Proj::X]) / 2, - (this->orig_corner0[Proj::Y] + this->orig_corner7[Proj::Y]) / 2, - (this->orig_corner0[Proj::Z] + this->orig_corner7[Proj::Z]) / 2, - 1.0); + return Proj::Pt3((this->orig_corner0[Proj::X] + this->orig_corner7[Proj::X]) / 2, + (this->orig_corner0[Proj::Y] + this->orig_corner7[Proj::Y]) / 2, + (this->orig_corner0[Proj::Z] + this->orig_corner7[Proj::Z]) / 2, 1.0); } -Geom::Point -SPBox3D::get_center_screen () { - Proj::Pt3 proj_center (this->get_proj_center ()); +Geom::Point SPBox3D::get_center_screen() +{ + Proj::Pt3 proj_center(this->get_proj_center()); if (!this->get_perspective()) { - return Geom::Point (Geom::infinity(), Geom::infinity()); + return Geom::Point(Geom::infinity(), Geom::infinity()); } - Geom::Affine const i2d( this->i2dt_affine() ); + Geom::Affine const i2d(this->i2dt_affine()); return this->get_perspective()->perspective_impl->tmat.image(proj_center).affine() * i2d.inverse(); } @@ -350,18 +349,18 @@ static guint remember_snap_index = 0; // constant for sizing the array of points to be considered: static const int MAX_POINT_COUNT = 4; -static Proj::Pt3 -box3d_snap (SPBox3D *box, int id, Proj::Pt3 const &pt_proj, Proj::Pt3 const &start_pt) { +static Proj::Pt3 box3d_snap(SPBox3D *box, int id, Proj::Pt3 const &pt_proj, Proj::Pt3 const &start_pt) +{ double z_coord = start_pt[Proj::Z]; double diff_x = box->save_corner7[Proj::X] - box->save_corner0[Proj::X]; double diff_y = box->save_corner7[Proj::Y] - box->save_corner0[Proj::Y]; double x_coord = start_pt[Proj::X]; double y_coord = start_pt[Proj::Y]; - Proj::Pt3 A_proj (x_coord, y_coord, z_coord, 1.0); - Proj::Pt3 B_proj (x_coord + diff_x, y_coord, z_coord, 1.0); - Proj::Pt3 C_proj (x_coord + diff_x, y_coord + diff_y, z_coord, 1.0); - Proj::Pt3 D_proj (x_coord, y_coord + diff_y, z_coord, 1.0); - Proj::Pt3 E_proj (x_coord - diff_x, y_coord + diff_y, z_coord, 1.0); + Proj::Pt3 A_proj(x_coord, y_coord, z_coord, 1.0); + Proj::Pt3 B_proj(x_coord + diff_x, y_coord, z_coord, 1.0); + Proj::Pt3 C_proj(x_coord + diff_x, y_coord + diff_y, z_coord, 1.0); + Proj::Pt3 D_proj(x_coord, y_coord + diff_y, z_coord, 1.0); + Proj::Pt3 E_proj(x_coord - diff_x, y_coord + diff_y, z_coord, 1.0); Persp3DImpl *persp_impl = box->get_perspective()->perspective_impl; Geom::Point A = persp_impl->tmat.image(A_proj).affine(); @@ -381,11 +380,11 @@ box3d_snap (SPBox3D *box, int id, Proj::Pt3 const &pt_proj, Proj::Pt3 const &sta int num_snap_lines = (id != -1) ? 3 : 4; Geom::Point snap_pts[MAX_POINT_COUNT]; - snap_pts[0] = pl1.closest_to (pt); - snap_pts[1] = pl2.closest_to (pt); - snap_pts[2] = diag1.closest_to (pt); + snap_pts[0] = pl1.closest_to(pt); + snap_pts[1] = pl2.closest_to(pt); + snap_pts[2] = diag1.closest_to(pt); if (id == -1) { - snap_pts[3] = diag2.closest_to (pt); + snap_pts[3] = diag2.closest_to(pt); } gdouble const zoom = SP_ACTIVE_DESKTOP->current_zoom(); @@ -393,7 +392,7 @@ box3d_snap (SPBox3D *box, int id, Proj::Pt3 const &pt_proj, Proj::Pt3 const &sta // determine the distances to all potential snapping points double snap_dists[MAX_POINT_COUNT]; for (int i = 0; i < num_snap_lines; ++i) { - snap_dists[i] = Geom::L2 (snap_pts[i] - pt) * zoom; + snap_dists[i] = Geom::L2(snap_pts[i] - pt) * zoom; } // while we are within a given tolerance of the starting point, @@ -425,10 +424,10 @@ box3d_snap (SPBox3D *box, int id, Proj::Pt3 const &pt_proj, Proj::Pt3 const &sta remember_snap_index = snap_index; result = snap_pts[snap_index]; } - return box->get_perspective()->perspective_impl->tmat.preimage (result, z_coord, Proj::Z); + return box->get_perspective()->perspective_impl->tmat.preimage(result, z_coord, Proj::Z); } -SPBox3D * SPBox3D::createBox3D(SPItem * parent) +SPBox3D *SPBox3D::createBox3D(SPItem *parent) { SPBox3D *box3d = nullptr; Inkscape::XML::Document *xml_doc = parent->document->getReprDoc(); @@ -438,9 +437,9 @@ SPBox3D * SPBox3D::createBox3D(SPItem * parent) return box3d; } -void -SPBox3D::set_corner (const guint id, Geom::Point const &new_pos, const Box3D::Axis movement, bool constrained) { - g_return_if_fail ((movement != Box3D::NONE) && (movement != Box3D::XYZ)); +void SPBox3D::set_corner(const guint id, Geom::Point const &new_pos, const Box3D::Axis movement, bool constrained) +{ + g_return_if_fail((movement != Box3D::NONE) && (movement != Box3D::XYZ)); this->orig_corner0.normalize(); this->orig_corner7.normalize(); @@ -448,52 +447,50 @@ SPBox3D::set_corner (const guint id, Geom::Point const &new_pos, const Box3D::Ax /* update corners 0 and 7 according to which handle was moved and to the axes of movement */ if (!(movement & Box3D::Z)) { Persp3DImpl *persp_impl = this->get_perspective()->perspective_impl; - Proj::Pt3 pt_proj (persp_impl->tmat.preimage (new_pos, (id < 4) ? this->orig_corner0[Proj::Z] : - this->orig_corner7[Proj::Z], Proj::Z)); + Proj::Pt3 pt_proj(persp_impl->tmat.preimage( + new_pos, (id < 4) ? this->orig_corner0[Proj::Z] : this->orig_corner7[Proj::Z], Proj::Z)); if (constrained) { - pt_proj = box3d_snap (this, id, pt_proj, box3d_get_proj_corner (id, this->save_corner0, this->save_corner7)); + pt_proj = box3d_snap(this, id, pt_proj, box3d_get_proj_corner(id, this->save_corner0, this->save_corner7)); } // normalizing pt_proj is essential because we want to mingle affine coordinates pt_proj.normalize(); - this->orig_corner0 = Proj::Pt3 ((id & Box3D::X) ? this->save_corner0[Proj::X] : pt_proj[Proj::X], + this->orig_corner0 = Proj::Pt3((id & Box3D::X) ? this->save_corner0[Proj::X] : pt_proj[Proj::X], (id & Box3D::Y) ? this->save_corner0[Proj::Y] : pt_proj[Proj::Y], - this->save_corner0[Proj::Z], - 1.0); - this->orig_corner7 = Proj::Pt3 ((id & Box3D::X) ? pt_proj[Proj::X] : this->save_corner7[Proj::X], + this->save_corner0[Proj::Z], 1.0); + this->orig_corner7 = Proj::Pt3((id & Box3D::X) ? pt_proj[Proj::X] : this->save_corner7[Proj::X], (id & Box3D::Y) ? pt_proj[Proj::Y] : this->save_corner7[Proj::Y], - this->save_corner7[Proj::Z], - 1.0); + this->save_corner7[Proj::Z], 1.0); } else { Persp3D *persp = this->get_perspective(); Persp3DImpl *persp_impl = this->get_perspective()->perspective_impl; - Box3D::PerspectiveLine pl(persp_impl->tmat.image( - box3d_get_proj_corner (id, this->save_corner0, this->save_corner7)).affine(), - Proj::Z, persp); + Box3D::PerspectiveLine pl( + persp_impl->tmat.image(box3d_get_proj_corner(id, this->save_corner0, this->save_corner7)).affine(), Proj::Z, + persp); Geom::Point new_pos_snapped(pl.closest_to(new_pos)); - Proj::Pt3 pt_proj (persp_impl->tmat.preimage (new_pos_snapped, - box3d_get_proj_corner (this, id)[(movement & Box3D::Y) ? Proj::X : Proj::Y], - (movement & Box3D::Y) ? Proj::X : Proj::Y)); + Proj::Pt3 pt_proj(persp_impl->tmat.preimage( + new_pos_snapped, box3d_get_proj_corner(this, id)[(movement & Box3D::Y) ? Proj::X : Proj::Y], + (movement & Box3D::Y) ? Proj::X : Proj::Y)); bool corner0_move_x = !(id & Box3D::X) && (movement & Box3D::X); bool corner0_move_y = !(id & Box3D::Y) && (movement & Box3D::Y); - bool corner7_move_x = (id & Box3D::X) && (movement & Box3D::X); - bool corner7_move_y = (id & Box3D::Y) && (movement & Box3D::Y); + bool corner7_move_x = (id & Box3D::X) && (movement & Box3D::X); + bool corner7_move_y = (id & Box3D::Y) && (movement & Box3D::Y); // normalizing pt_proj is essential because we want to mingle affine coordinates pt_proj.normalize(); - this->orig_corner0 = Proj::Pt3 (corner0_move_x ? pt_proj[Proj::X] : this->orig_corner0[Proj::X], + this->orig_corner0 = Proj::Pt3(corner0_move_x ? pt_proj[Proj::X] : this->orig_corner0[Proj::X], corner0_move_y ? pt_proj[Proj::Y] : this->orig_corner0[Proj::Y], - (id & Box3D::Z) ? this->orig_corner0[Proj::Z] : pt_proj[Proj::Z], - 1.0); - this->orig_corner7 = Proj::Pt3 (corner7_move_x ? pt_proj[Proj::X] : this->orig_corner7[Proj::X], + (id & Box3D::Z) ? this->orig_corner0[Proj::Z] : pt_proj[Proj::Z], 1.0); + this->orig_corner7 = Proj::Pt3(corner7_move_x ? pt_proj[Proj::X] : this->orig_corner7[Proj::X], corner7_move_y ? pt_proj[Proj::Y] : this->orig_corner7[Proj::Y], - (id & Box3D::Z) ? pt_proj[Proj::Z] : this->orig_corner7[Proj::Z], - 1.0); + (id & Box3D::Z) ? pt_proj[Proj::Z] : this->orig_corner7[Proj::Z], 1.0); } // FIXME: Should we update the box here? If so, how? } -void SPBox3D::set_center (Geom::Point const &new_pos, Geom::Point const &old_pos, const Box3D::Axis movement, bool constrained) { - g_return_if_fail ((movement != Box3D::NONE) && (movement != Box3D::XYZ)); +void SPBox3D::set_center(Geom::Point const &new_pos, Geom::Point const &old_pos, const Box3D::Axis movement, + bool constrained) +{ + g_return_if_fail((movement != Box3D::NONE) && (movement != Box3D::XYZ)); this->orig_corner0.normalize(); this->orig_corner7.normalize(); @@ -504,40 +501,34 @@ void SPBox3D::set_center (Geom::Point const &new_pos, Geom::Point const &old_pos double radx = (this->orig_corner7[Proj::X] - this->orig_corner0[Proj::X]) / 2; double rady = (this->orig_corner7[Proj::Y] - this->orig_corner0[Proj::Y]) / 2; - Proj::Pt3 pt_proj (persp->perspective_impl->tmat.preimage (new_pos, coord, Proj::Z)); + Proj::Pt3 pt_proj(persp->perspective_impl->tmat.preimage(new_pos, coord, Proj::Z)); if (constrained) { - Proj::Pt3 old_pos_proj (persp->perspective_impl->tmat.preimage (old_pos, coord, Proj::Z)); + Proj::Pt3 old_pos_proj(persp->perspective_impl->tmat.preimage(old_pos, coord, Proj::Z)); old_pos_proj.normalize(); - pt_proj = box3d_snap (this, -1, pt_proj, old_pos_proj); + pt_proj = box3d_snap(this, -1, pt_proj, old_pos_proj); } // normalizing pt_proj is essential because we want to mingle affine coordinates pt_proj.normalize(); - this->orig_corner0 = Proj::Pt3 ((movement & Box3D::X) ? pt_proj[Proj::X] - radx : this->orig_corner0[Proj::X], + this->orig_corner0 = Proj::Pt3((movement & Box3D::X) ? pt_proj[Proj::X] - radx : this->orig_corner0[Proj::X], (movement & Box3D::Y) ? pt_proj[Proj::Y] - rady : this->orig_corner0[Proj::Y], - this->orig_corner0[Proj::Z], - 1.0); - this->orig_corner7 = Proj::Pt3 ((movement & Box3D::X) ? pt_proj[Proj::X] + radx : this->orig_corner7[Proj::X], + this->orig_corner0[Proj::Z], 1.0); + this->orig_corner7 = Proj::Pt3((movement & Box3D::X) ? pt_proj[Proj::X] + radx : this->orig_corner7[Proj::X], (movement & Box3D::Y) ? pt_proj[Proj::Y] + rady : this->orig_corner7[Proj::Y], - this->orig_corner7[Proj::Z], - 1.0); + this->orig_corner7[Proj::Z], 1.0); } else { double coord = (this->orig_corner0[Proj::X] + this->orig_corner7[Proj::X]) / 2; double radz = (this->orig_corner7[Proj::Z] - this->orig_corner0[Proj::Z]) / 2; Box3D::PerspectiveLine pl(old_pos, Proj::Z, persp); Geom::Point new_pos_snapped(pl.closest_to(new_pos)); - Proj::Pt3 pt_proj (persp->perspective_impl->tmat.preimage (new_pos_snapped, coord, Proj::X)); + Proj::Pt3 pt_proj(persp->perspective_impl->tmat.preimage(new_pos_snapped, coord, Proj::X)); /* normalizing pt_proj is essential because we want to mingle affine coordinates */ pt_proj.normalize(); - this->orig_corner0 = Proj::Pt3 (this->orig_corner0[Proj::X], - this->orig_corner0[Proj::Y], - pt_proj[Proj::Z] - radz, - 1.0); - this->orig_corner7 = Proj::Pt3 (this->orig_corner7[Proj::X], - this->orig_corner7[Proj::Y], - pt_proj[Proj::Z] + radz, - 1.0); + this->orig_corner0 = + Proj::Pt3(this->orig_corner0[Proj::X], this->orig_corner0[Proj::Y], pt_proj[Proj::Z] - radz, 1.0); + this->orig_corner7 = + Proj::Pt3(this->orig_corner7[Proj::X], this->orig_corner7[Proj::Y], pt_proj[Proj::Z] + radz, 1.0); } } @@ -545,38 +536,37 @@ void SPBox3D::set_center (Geom::Point const &new_pos, Geom::Point const &old_pos * Manipulates corner1 through corner4 to contain the indices of the corners * from which the perspective lines in the direction of 'axis' emerge */ -void SPBox3D::corners_for_PLs (Proj::Axis axis, - Geom::Point &corner1, Geom::Point &corner2, Geom::Point &corner3, Geom::Point &corner4) const +void SPBox3D::corners_for_PLs(Proj::Axis axis, Geom::Point &corner1, Geom::Point &corner2, Geom::Point &corner3, + Geom::Point &corner4) const { Persp3D *persp = this->get_perspective(); - g_return_if_fail (persp); + g_return_if_fail(persp); Persp3DImpl *persp_impl = persp->perspective_impl; - //this->orig_corner0.normalize(); - //this->orig_corner7.normalize(); - double coord = (this->orig_corner0[axis] > this->orig_corner7[axis]) ? - this->orig_corner0[axis] : - this->orig_corner7[axis]; + // this->orig_corner0.normalize(); + // this->orig_corner7.normalize(); + double coord = + (this->orig_corner0[axis] > this->orig_corner7[axis]) ? this->orig_corner0[axis] : this->orig_corner7[axis]; Proj::Pt3 c1, c2, c3, c4; // FIXME: This can certainly be done more elegantly/efficiently than by a case-by-case analysis. switch (axis) { case Proj::X: - c1 = Proj::Pt3 (coord, this->orig_corner0[Proj::Y], this->orig_corner0[Proj::Z], 1.0); - c2 = Proj::Pt3 (coord, this->orig_corner7[Proj::Y], this->orig_corner0[Proj::Z], 1.0); - c3 = Proj::Pt3 (coord, this->orig_corner7[Proj::Y], this->orig_corner7[Proj::Z], 1.0); - c4 = Proj::Pt3 (coord, this->orig_corner0[Proj::Y], this->orig_corner7[Proj::Z], 1.0); + c1 = Proj::Pt3(coord, this->orig_corner0[Proj::Y], this->orig_corner0[Proj::Z], 1.0); + c2 = Proj::Pt3(coord, this->orig_corner7[Proj::Y], this->orig_corner0[Proj::Z], 1.0); + c3 = Proj::Pt3(coord, this->orig_corner7[Proj::Y], this->orig_corner7[Proj::Z], 1.0); + c4 = Proj::Pt3(coord, this->orig_corner0[Proj::Y], this->orig_corner7[Proj::Z], 1.0); break; case Proj::Y: - c1 = Proj::Pt3 (this->orig_corner0[Proj::X], coord, this->orig_corner0[Proj::Z], 1.0); - c2 = Proj::Pt3 (this->orig_corner7[Proj::X], coord, this->orig_corner0[Proj::Z], 1.0); - c3 = Proj::Pt3 (this->orig_corner7[Proj::X], coord, this->orig_corner7[Proj::Z], 1.0); - c4 = Proj::Pt3 (this->orig_corner0[Proj::X], coord, this->orig_corner7[Proj::Z], 1.0); + c1 = Proj::Pt3(this->orig_corner0[Proj::X], coord, this->orig_corner0[Proj::Z], 1.0); + c2 = Proj::Pt3(this->orig_corner7[Proj::X], coord, this->orig_corner0[Proj::Z], 1.0); + c3 = Proj::Pt3(this->orig_corner7[Proj::X], coord, this->orig_corner7[Proj::Z], 1.0); + c4 = Proj::Pt3(this->orig_corner0[Proj::X], coord, this->orig_corner7[Proj::Z], 1.0); break; case Proj::Z: - c1 = Proj::Pt3 (this->orig_corner7[Proj::X], this->orig_corner7[Proj::Y], coord, 1.0); - c2 = Proj::Pt3 (this->orig_corner7[Proj::X], this->orig_corner0[Proj::Y], coord, 1.0); - c3 = Proj::Pt3 (this->orig_corner0[Proj::X], this->orig_corner0[Proj::Y], coord, 1.0); - c4 = Proj::Pt3 (this->orig_corner0[Proj::X], this->orig_corner7[Proj::Y], coord, 1.0); + c1 = Proj::Pt3(this->orig_corner7[Proj::X], this->orig_corner7[Proj::Y], coord, 1.0); + c2 = Proj::Pt3(this->orig_corner7[Proj::X], this->orig_corner0[Proj::Y], coord, 1.0); + c3 = Proj::Pt3(this->orig_corner0[Proj::X], this->orig_corner0[Proj::Y], coord, 1.0); + c4 = Proj::Pt3(this->orig_corner0[Proj::X], this->orig_corner7[Proj::Y], coord, 1.0); break; default: return; @@ -588,25 +578,22 @@ void SPBox3D::corners_for_PLs (Proj::Axis axis, } /* Auxiliary function: Checks whether the half-line from A to B crosses the line segment joining C and D */ -static bool -box3d_half_line_crosses_joining_line (Geom::Point const &A, Geom::Point const &B, - Geom::Point const &C, Geom::Point const &D) { +static bool box3d_half_line_crosses_joining_line(Geom::Point const &A, Geom::Point const &B, Geom::Point const &C, + Geom::Point const &D) +{ Geom::Point n0 = (B - A).ccw(); - double d0 = dot(n0,A); + double d0 = dot(n0, A); Geom::Point n1 = (D - C).ccw(); - double d1 = dot(n1,C); + double d1 = dot(n1, C); - Geom::Line lineAB(A,B); - Geom::Line lineCD(C,D); + Geom::Line lineAB(A, B); + Geom::Line lineCD(C, D); Geom::OptCrossing inters = Geom::OptCrossing(); // empty by default - try - { + try { inters = Geom::intersection(lineAB, lineCD); - } - catch (Geom::InfiniteSolutions& e) - { + } catch (Geom::InfiniteSolutions &e) { // We're probably dealing with parallel lines, so they don't really cross return false; } @@ -617,14 +604,14 @@ box3d_half_line_crosses_joining_line (Geom::Point const &A, Geom::Point const &B Geom::Point E = lineAB.pointAt((*inters).ta); // the point of intersection - if ((dot(C,n0) < d0) == (dot(D,n0) < d0)) { + if ((dot(C, n0) < d0) == (dot(D, n0) < d0)) { // C and D lie on the same side of the line AB return false; } - if ((dot(A,n1) < d1) != (dot(B,n1) < d1)) { + if ((dot(A, n1) < d1) != (dot(B, n1) < d1)) { // A and B lie on different sides of the line CD return true; - } else if (Geom::distance(E,A) < Geom::distance(E,B)) { + } else if (Geom::distance(E, A) < Geom::distance(E, B)) { // The line CD passes on the "wrong" side of A return false; } @@ -633,8 +620,8 @@ box3d_half_line_crosses_joining_line (Geom::Point const &A, Geom::Point const &B return true; } -static bool -box3d_XY_axes_are_swapped (SPBox3D *box) { +static bool box3d_XY_axes_are_swapped(SPBox3D *box) +{ Persp3D *persp = box->get_perspective(); g_return_val_if_fail(persp, false); Box3D::PerspectiveLine l1(box->get_corner_screen(3, false), Proj::X, persp); @@ -644,11 +631,11 @@ box3d_XY_axes_are_swapped (SPBox3D *box) { v1.normalize(); v2.normalize(); - return (v1[Geom::X]*v2[Geom::Y] - v1[Geom::Y]*v2[Geom::X] > 0); + return (v1[Geom::X] * v2[Geom::Y] - v1[Geom::Y] * v2[Geom::X] > 0); } -static inline void -box3d_aux_set_z_orders (int z_orders[6], int a, int b, int c, int d, int e, int f) { +static inline void box3d_aux_set_z_orders(int z_orders[6], int a, int b, int c, int d, int e, int f) +{ // TODO add function argument: SPDocument *doc = box->document auto doc = SP_ACTIVE_DOCUMENT; @@ -666,7 +653,6 @@ box3d_aux_set_z_orders (int z_orders[6], int a, int b, int c, int d, int e, int z_orders[5] = f; } - /* * In standard perspective we have: * 2 = front face @@ -678,37 +664,37 @@ box3d_aux_set_z_orders (int z_orders[6], int a, int b, int c, int d, int e, int */ /* All VPs infinite */ -static void -box3d_set_new_z_orders_case0 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis) { +static void box3d_set_new_z_orders_case0(SPBox3D *box, int z_orders[6], Box3D::Axis central_axis) +{ bool swapped = box3d_XY_axes_are_swapped(box); - switch(central_axis) { + switch (central_axis) { case Box3D::X: if (!swapped) { - box3d_aux_set_z_orders (z_orders, 2, 0, 4, 1, 3, 5); + box3d_aux_set_z_orders(z_orders, 2, 0, 4, 1, 3, 5); } else { - box3d_aux_set_z_orders (z_orders, 3, 1, 5, 2, 4, 0); + box3d_aux_set_z_orders(z_orders, 3, 1, 5, 2, 4, 0); } break; case Box3D::Y: if (!swapped) { - box3d_aux_set_z_orders (z_orders, 2, 3, 1, 4, 0, 5); + box3d_aux_set_z_orders(z_orders, 2, 3, 1, 4, 0, 5); } else { - box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2); + box3d_aux_set_z_orders(z_orders, 5, 0, 4, 1, 3, 2); } break; case Box3D::Z: if (!swapped) { - box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5); + box3d_aux_set_z_orders(z_orders, 2, 0, 1, 4, 3, 5); } else { - box3d_aux_set_z_orders (z_orders, 5, 3, 4, 1, 0, 2); + box3d_aux_set_z_orders(z_orders, 5, 3, 4, 1, 0, 2); } break; case Box3D::NONE: if (!swapped) { - box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5); + box3d_aux_set_z_orders(z_orders, 2, 3, 4, 1, 0, 5); } else { - box3d_aux_set_z_orders (z_orders, 5, 0, 1, 4, 3, 2); + box3d_aux_set_z_orders(z_orders, 5, 0, 1, 4, 3, 2); } break; default: @@ -718,8 +704,8 @@ box3d_set_new_z_orders_case0 (SPBox3D *box, int z_orders[6], Box3D::Axis central } /* Precisely one finite VP */ -static void -box3d_set_new_z_orders_case1 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, Box3D::Axis fin_axis) { +static void box3d_set_new_z_orders_case1(SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, Box3D::Axis fin_axis) +{ Persp3D *persp = box->get_perspective(); Geom::Point vp(persp->get_VP(Box3D::toProj(fin_axis)).affine()); @@ -728,59 +714,59 @@ box3d_set_new_z_orders_case1 (SPBox3D *box, int z_orders[6], Box3D::Axis central Box3D::Axis oaxis2 = Box3D::get_remaining_axes(fin_axis).second; int inside1 = 0; int inside2 = 0; - inside1 = box->pt_lies_in_PL_sector (vp, 3, 3 ^ oaxis2, oaxis1); - inside2 = box->pt_lies_in_PL_sector (vp, 3, 3 ^ oaxis1, oaxis2); + inside1 = box->pt_lies_in_PL_sector(vp, 3, 3 ^ oaxis2, oaxis1); + inside2 = box->pt_lies_in_PL_sector(vp, 3, 3 ^ oaxis1, oaxis2); bool swapped = box3d_XY_axes_are_swapped(box); - switch(central_axis) { + switch (central_axis) { case Box3D::X: if (!swapped) { - box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5); + box3d_aux_set_z_orders(z_orders, 2, 4, 0, 1, 3, 5); } else { - box3d_aux_set_z_orders (z_orders, 5, 3, 1, 0, 2, 4); + box3d_aux_set_z_orders(z_orders, 5, 3, 1, 0, 2, 4); } break; case Box3D::Y: if (inside2 > 0) { - box3d_aux_set_z_orders (z_orders, 1, 2, 3, 0, 5, 4); + box3d_aux_set_z_orders(z_orders, 1, 2, 3, 0, 5, 4); } else if (inside2 < 0) { - box3d_aux_set_z_orders (z_orders, 2, 3, 1, 4, 0, 5); + box3d_aux_set_z_orders(z_orders, 2, 3, 1, 4, 0, 5); } else { if (!swapped) { - box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4); + box3d_aux_set_z_orders(z_orders, 2, 3, 1, 5, 0, 4); } else { - box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2); + box3d_aux_set_z_orders(z_orders, 5, 0, 4, 1, 3, 2); } } break; case Box3D::Z: if (inside2) { if (!swapped) { - box3d_aux_set_z_orders (z_orders, 2, 1, 3, 0, 4, 5); + box3d_aux_set_z_orders(z_orders, 2, 1, 3, 0, 4, 5); } else { - box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 1, 2); + box3d_aux_set_z_orders(z_orders, 5, 3, 4, 0, 1, 2); } } else if (inside1) { if (!swapped) { - box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5); + box3d_aux_set_z_orders(z_orders, 2, 0, 1, 4, 3, 5); } else { - box3d_aux_set_z_orders (z_orders, 5, 3, 4, 1, 0, 2); + box3d_aux_set_z_orders(z_orders, 5, 3, 4, 1, 0, 2); } } else { // "regular" case if (!swapped) { - box3d_aux_set_z_orders (z_orders, 0, 1, 2, 5, 4, 3); + box3d_aux_set_z_orders(z_orders, 0, 1, 2, 5, 4, 3); } else { - box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 2, 1); + box3d_aux_set_z_orders(z_orders, 5, 3, 4, 0, 2, 1); } } break; case Box3D::NONE: if (!swapped) { - box3d_aux_set_z_orders (z_orders, 2, 3, 4, 5, 0, 1); + box3d_aux_set_z_orders(z_orders, 2, 3, 4, 5, 0, 1); } else { - box3d_aux_set_z_orders (z_orders, 5, 0, 1, 3, 2, 4); + box3d_aux_set_z_orders(z_orders, 5, 0, 1, 3, 2, 4); } break; default: @@ -789,40 +775,41 @@ box3d_set_new_z_orders_case1 (SPBox3D *box, int z_orders[6], Box3D::Axis central } /* Precisely 2 finite VPs */ -static void -box3d_set_new_z_orders_case2 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, Box3D::Axis /*infinite_axis*/) { +static void box3d_set_new_z_orders_case2(SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, + Box3D::Axis /*infinite_axis*/) +{ bool swapped = box3d_XY_axes_are_swapped(box); - int insidexy = box->VP_lies_in_PL_sector (Proj::X, 3, 3 ^ Box3D::Z, Box3D::Y); - //int insidexz = box->VP_lies_in_PL_sector (Proj::X, 3, 3 ^ Box3D::Y, Box3D::Z); + int insidexy = box->VP_lies_in_PL_sector(Proj::X, 3, 3 ^ Box3D::Z, Box3D::Y); + // int insidexz = box->VP_lies_in_PL_sector (Proj::X, 3, 3 ^ Box3D::Y, Box3D::Z); - int insideyx = box->VP_lies_in_PL_sector (Proj::Y, 3, 3 ^ Box3D::Z, Box3D::X); - int insideyz = box->VP_lies_in_PL_sector (Proj::Y, 3, 3 ^ Box3D::X, Box3D::Z); + int insideyx = box->VP_lies_in_PL_sector(Proj::Y, 3, 3 ^ Box3D::Z, Box3D::X); + int insideyz = box->VP_lies_in_PL_sector(Proj::Y, 3, 3 ^ Box3D::X, Box3D::Z); - //int insidezx = box->VP_lies_in_PL_sector (Proj::Z, 3, 3 ^ Box3D::Y, Box3D::X); - int insidezy = box->VP_lies_in_PL_sector (Proj::Z, 3, 3 ^ Box3D::X, Box3D::Y); + // int insidezx = box->VP_lies_in_PL_sector (Proj::Z, 3, 3 ^ Box3D::Y, Box3D::X); + int insidezy = box->VP_lies_in_PL_sector(Proj::Z, 3, 3 ^ Box3D::X, Box3D::Y); - switch(central_axis) { + switch (central_axis) { case Box3D::X: if (!swapped) { if (insidezy == -1) { - box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5); + box3d_aux_set_z_orders(z_orders, 2, 4, 0, 1, 3, 5); } else if (insidexy == 1) { - box3d_aux_set_z_orders (z_orders, 2, 4, 0, 5, 1, 3); + box3d_aux_set_z_orders(z_orders, 2, 4, 0, 5, 1, 3); } else { - box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5); + box3d_aux_set_z_orders(z_orders, 2, 4, 0, 1, 3, 5); } } else { if (insideyz == -1) { - box3d_aux_set_z_orders (z_orders, 3, 1, 5, 0, 2, 4); + box3d_aux_set_z_orders(z_orders, 3, 1, 5, 0, 2, 4); } else { if (!swapped) { - box3d_aux_set_z_orders (z_orders, 3, 1, 5, 2, 4, 0); + box3d_aux_set_z_orders(z_orders, 3, 1, 5, 2, 4, 0); } else { if (insidexy == 0) { - box3d_aux_set_z_orders (z_orders, 3, 5, 1, 0, 2, 4); + box3d_aux_set_z_orders(z_orders, 3, 5, 1, 0, 2, 4); } else { - box3d_aux_set_z_orders (z_orders, 3, 1, 5, 0, 2, 4); + box3d_aux_set_z_orders(z_orders, 3, 1, 5, 0, 2, 4); } } } @@ -831,36 +818,36 @@ box3d_set_new_z_orders_case2 (SPBox3D *box, int z_orders[6], Box3D::Axis central case Box3D::Y: if (!swapped) { if (insideyz == 1) { - box3d_aux_set_z_orders (z_orders, 2, 3, 1, 0, 5, 4); + box3d_aux_set_z_orders(z_orders, 2, 3, 1, 0, 5, 4); } else { - box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4); + box3d_aux_set_z_orders(z_orders, 2, 3, 1, 5, 0, 4); } } else { if (insideyx == 1) { - box3d_aux_set_z_orders (z_orders, 4, 0, 5, 1, 3, 2); + box3d_aux_set_z_orders(z_orders, 4, 0, 5, 1, 3, 2); } else { - box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2); + box3d_aux_set_z_orders(z_orders, 5, 0, 4, 1, 3, 2); } } break; case Box3D::Z: if (!swapped) { if (insidezy == 1) { - box3d_aux_set_z_orders (z_orders, 2, 1, 0, 4, 3, 5); + box3d_aux_set_z_orders(z_orders, 2, 1, 0, 4, 3, 5); } else if (insidexy == -1) { - box3d_aux_set_z_orders (z_orders, 2, 1, 0, 5, 4, 3); + box3d_aux_set_z_orders(z_orders, 2, 1, 0, 5, 4, 3); } else { - box3d_aux_set_z_orders (z_orders, 2, 0, 1, 5, 3, 4); + box3d_aux_set_z_orders(z_orders, 2, 0, 1, 5, 3, 4); } } else { - box3d_aux_set_z_orders (z_orders, 3, 4, 5, 1, 0, 2); + box3d_aux_set_z_orders(z_orders, 3, 4, 5, 1, 0, 2); } break; case Box3D::NONE: if (!swapped) { - box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5); + box3d_aux_set_z_orders(z_orders, 2, 3, 4, 1, 0, 5); } else { - box3d_aux_set_z_orders (z_orders, 5, 0, 1, 4, 3, 2); + box3d_aux_set_z_orders(z_orders, 5, 0, 1, 4, 3, 2); } break; default: @@ -873,25 +860,26 @@ box3d_set_new_z_orders_case2 (SPBox3D *box, int z_orders[6], Box3D::Axis central * It can happen that during dragging the box is everted. * In this case the opposite sides in this direction need to be swapped */ -static Box3D::Axis -box3d_everted_directions (SPBox3D *box) { +static Box3D::Axis box3d_everted_directions(SPBox3D *box) +{ Box3D::Axis ev = Box3D::NONE; box->orig_corner0.normalize(); box->orig_corner7.normalize(); if (box->orig_corner0[Proj::X] < box->orig_corner7[Proj::X]) - ev = (Box3D::Axis) (ev ^ Box3D::X); + ev = (Box3D::Axis)(ev ^ Box3D::X); if (box->orig_corner0[Proj::Y] < box->orig_corner7[Proj::Y]) - ev = (Box3D::Axis) (ev ^ Box3D::Y); - if (box->orig_corner0[Proj::Z] > box->orig_corner7[Proj::Z]) // FIXME: Remove the need to distinguish signs among the cases - ev = (Box3D::Axis) (ev ^ Box3D::Z); + ev = (Box3D::Axis)(ev ^ Box3D::Y); + if (box->orig_corner0[Proj::Z] > box->orig_corner7[Proj::Z]) // FIXME: Remove the need to distinguish signs among + // the cases + ev = (Box3D::Axis)(ev ^ Box3D::Z); return ev; } -static void -box3d_swap_sides(int z_orders[6], Box3D::Axis axis) { +static void box3d_swap_sides(int z_orders[6], Box3D::Axis axis) +{ int pos1 = -1; int pos2 = -1; @@ -906,16 +894,15 @@ box3d_swap_sides(int z_orders[6], Box3D::Axis axis) { } } - if ((pos1 != -1) && (pos2 != -1)){ + if ((pos1 != -1) && (pos2 != -1)) { int tmp = z_orders[pos1]; z_orders[pos1] = z_orders[pos2]; z_orders[pos2] = tmp; } } - -bool -SPBox3D::recompute_z_orders () { +bool SPBox3D::recompute_z_orders() +{ Persp3D *persp = this->get_perspective(); if (!persp) @@ -942,11 +929,11 @@ SPBox3D::recompute_z_orders () { // determine the "central" axis (if there is one) Box3D::Axis central_axis = Box3D::NONE; - if(Box3D::lies_in_sector(dirs[0], dirs[1], dirs[2])) { + if (Box3D::lies_in_sector(dirs[0], dirs[1], dirs[2])) { central_axis = Box3D::Z; - } else if(Box3D::lies_in_sector(dirs[1], dirs[2], dirs[0])) { + } else if (Box3D::lies_in_sector(dirs[1], dirs[2], dirs[0])) { central_axis = Box3D::X; - } else if(Box3D::lies_in_sector(dirs[2], dirs[0], dirs[1])) { + } else if (Box3D::lies_in_sector(dirs[2], dirs[0], dirs[1])) { central_axis = Box3D::Y; } @@ -964,95 +951,95 @@ SPBox3D::recompute_z_orders () { box3d_set_new_z_orders_case2(this, z_orders, central_axis, axis_infinite); break; default: - /* - * For each VP F, check whether the half-line from the corner3 to F crosses the line segment - * joining the other two VPs. If this is the case, it determines the "central" corner from - * which the visible sides can be deduced. Otherwise, corner3 is the central corner. - */ - // FIXME: We should eliminate the use of Geom::Point altogether - Box3D::Axis central_axis = Box3D::NONE; - Geom::Point vp_x = persp->get_VP(Proj::X).affine(); - Geom::Point vp_y = persp->get_VP(Proj::Y).affine(); - Geom::Point vp_z = persp->get_VP(Proj::Z).affine(); - Geom::Point vpx(vp_x[Geom::X], vp_x[Geom::Y]); - Geom::Point vpy(vp_y[Geom::X], vp_y[Geom::Y]); - Geom::Point vpz(vp_z[Geom::X], vp_z[Geom::Y]); - - Geom::Point c3 = this->get_corner_screen(3, false); - Geom::Point corner3(c3[Geom::X], c3[Geom::Y]); - - if (box3d_half_line_crosses_joining_line (corner3, vpx, vpy, vpz)) { - central_axis = Box3D::X; - } else if (box3d_half_line_crosses_joining_line (corner3, vpy, vpz, vpx)) { - central_axis = Box3D::Y; - } else if (box3d_half_line_crosses_joining_line (corner3, vpz, vpx, vpy)) { - central_axis = Box3D::Z; - } - - // FIXME: At present, this is not used. Why is it calculated? - /* - unsigned int central_corner = 3 ^ central_axis; - if (central_axis == Box3D::Z) { - central_corner = central_corner ^ Box3D::XYZ; - } - if (box3d_XY_axes_are_swapped(this)) { - central_corner = central_corner ^ Box3D::XYZ; - } - */ - - Geom::Point c1(this->get_corner_screen(1, false)); - Geom::Point c2(this->get_corner_screen(2, false)); - Geom::Point c7(this->get_corner_screen(7, false)); - - Geom::Point corner1(c1[Geom::X], c1[Geom::Y]); - Geom::Point corner2(c2[Geom::X], c2[Geom::Y]); - Geom::Point corner7(c7[Geom::X], c7[Geom::Y]); - // FIXME: At present we don't use the information about central_corner computed above. - switch (central_axis) { - case Box3D::Y: - if (!box3d_half_line_crosses_joining_line(vpz, vpy, corner3, corner2)) { - box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4); - } else { - // degenerate case - box3d_aux_set_z_orders (z_orders, 2, 1, 3, 0, 5, 4); - } - break; + /* + * For each VP F, check whether the half-line from the corner3 to F crosses the line segment + * joining the other two VPs. If this is the case, it determines the "central" corner from + * which the visible sides can be deduced. Otherwise, corner3 is the central corner. + */ + // FIXME: We should eliminate the use of Geom::Point altogether + Box3D::Axis central_axis = Box3D::NONE; + Geom::Point vp_x = persp->get_VP(Proj::X).affine(); + Geom::Point vp_y = persp->get_VP(Proj::Y).affine(); + Geom::Point vp_z = persp->get_VP(Proj::Z).affine(); + Geom::Point vpx(vp_x[Geom::X], vp_x[Geom::Y]); + Geom::Point vpy(vp_y[Geom::X], vp_y[Geom::Y]); + Geom::Point vpz(vp_z[Geom::X], vp_z[Geom::Y]); + + Geom::Point c3 = this->get_corner_screen(3, false); + Geom::Point corner3(c3[Geom::X], c3[Geom::Y]); + + if (box3d_half_line_crosses_joining_line(corner3, vpx, vpy, vpz)) { + central_axis = Box3D::X; + } else if (box3d_half_line_crosses_joining_line(corner3, vpy, vpz, vpx)) { + central_axis = Box3D::Y; + } else if (box3d_half_line_crosses_joining_line(corner3, vpz, vpx, vpy)) { + central_axis = Box3D::Z; + } - case Box3D::Z: - if (box3d_half_line_crosses_joining_line(vpx, vpz, corner3, corner1)) { - // degenerate case - box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5); - } else if (box3d_half_line_crosses_joining_line(vpx, vpy, corner3, corner7)) { - // degenerate case - box3d_aux_set_z_orders (z_orders, 2, 1, 0, 5, 3, 4); - } else { - box3d_aux_set_z_orders (z_orders, 2, 1, 0, 3, 4, 5); - } - break; + // FIXME: At present, this is not used. Why is it calculated? + /* + unsigned int central_corner = 3 ^ central_axis; + if (central_axis == Box3D::Z) { + central_corner = central_corner ^ Box3D::XYZ; + } + if (box3d_XY_axes_are_swapped(this)) { + central_corner = central_corner ^ Box3D::XYZ; + } + */ + + Geom::Point c1(this->get_corner_screen(1, false)); + Geom::Point c2(this->get_corner_screen(2, false)); + Geom::Point c7(this->get_corner_screen(7, false)); + + Geom::Point corner1(c1[Geom::X], c1[Geom::Y]); + Geom::Point corner2(c2[Geom::X], c2[Geom::Y]); + Geom::Point corner7(c7[Geom::X], c7[Geom::Y]); + // FIXME: At present we don't use the information about central_corner computed above. + switch (central_axis) { + case Box3D::Y: + if (!box3d_half_line_crosses_joining_line(vpz, vpy, corner3, corner2)) { + box3d_aux_set_z_orders(z_orders, 2, 3, 1, 5, 0, 4); + } else { + // degenerate case + box3d_aux_set_z_orders(z_orders, 2, 1, 3, 0, 5, 4); + } + break; + + case Box3D::Z: + if (box3d_half_line_crosses_joining_line(vpx, vpz, corner3, corner1)) { + // degenerate case + box3d_aux_set_z_orders(z_orders, 2, 0, 1, 4, 3, 5); + } else if (box3d_half_line_crosses_joining_line(vpx, vpy, corner3, corner7)) { + // degenerate case + box3d_aux_set_z_orders(z_orders, 2, 1, 0, 5, 3, 4); + } else { + box3d_aux_set_z_orders(z_orders, 2, 1, 0, 3, 4, 5); + } + break; - case Box3D::X: - if (box3d_half_line_crosses_joining_line(vpz, vpx, corner3, corner1)) { - // degenerate case - box3d_aux_set_z_orders (z_orders, 2, 1, 0, 4, 5, 3); - } else { - box3d_aux_set_z_orders (z_orders, 2, 4, 0, 5, 1, 3); - } - break; + case Box3D::X: + if (box3d_half_line_crosses_joining_line(vpz, vpx, corner3, corner1)) { + // degenerate case + box3d_aux_set_z_orders(z_orders, 2, 1, 0, 4, 5, 3); + } else { + box3d_aux_set_z_orders(z_orders, 2, 4, 0, 5, 1, 3); + } + break; - case Box3D::NONE: - box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5); - break; + case Box3D::NONE: + box3d_aux_set_z_orders(z_orders, 2, 3, 4, 1, 0, 5); + break; - default: - g_assert_not_reached(); - break; - } // end default case + default: + g_assert_not_reached(); + break; + } // end default case } // TODO: If there are still errors in z-orders of everted boxes, we need to choose a variable corner // instead of the hard-coded corner #3 in the computations above Box3D::Axis ev = box3d_everted_directions(this); - for (auto & axe : Box3D::axes) { + for (auto &axe : Box3D::axes) { if (ev & axe) { box3d_swap_sides(z_orders, axe); } @@ -1073,7 +1060,7 @@ SPBox3D::recompute_z_orders () { static std::map box3d_get_sides(SPBox3D *box) { std::map sides; - for (auto& obj: box->children) { + for (auto &obj : box->children) { Box3DSide *side = dynamic_cast(&obj); if (side) { sides[Box3D::face_to_int(side->getFaceId())] = side; @@ -1083,12 +1070,11 @@ static std::map box3d_get_sides(SPBox3D *box) return sides; } - // TODO: Check whether the box is everted in any direction and swap the sides opposite to this direction -void -SPBox3D::set_z_orders () { +void SPBox3D::set_z_orders() +{ // For efficiency reasons, we only set the new z-orders if something really changed - if (this->recompute_z_orders ()) { + if (this->recompute_z_orders()) { std::map sides = box3d_get_sides(this); std::map::iterator side; for (int z_order : this->z_orders) { @@ -1112,8 +1098,8 @@ SPBox3D::set_z_orders () { */ // TODO: Maybe it would be useful to have a similar method for projective points pt because then we // can use it for VPs and perhaps merge the case distinctions during z-order recomputation. -int -SPBox3D::pt_lies_in_PL_sector (Geom::Point const &pt, int id1, int id2, Box3D::Axis axis) const { +int SPBox3D::pt_lies_in_PL_sector(Geom::Point const &pt, int id1, int id2, Box3D::Axis axis) const +{ Persp3D *persp = this->get_perspective(); // the two corners @@ -1132,7 +1118,7 @@ SPBox3D::pt_lies_in_PL_sector (Geom::Point const &pt, int id1, int id2, Box3D::A Box3D::PerspectiveLine pl2(c2, Box3D::toProj(axis), persp); if (pl1.lie_on_same_side(pt, c2) && pl2.lie_on_same_side(pt, c1)) { // test whether pt lies "towards" or "away from" the VP - Box3D::Line edge(c1,c2); + Box3D::Line edge(c1, c2); Geom::Point c3(this->get_corner_screen(id1 ^ axis, false)); if (edge.lie_on_same_side(pt, c3)) { ret = 1; @@ -1144,8 +1130,8 @@ SPBox3D::pt_lies_in_PL_sector (Geom::Point const &pt, int id1, int id2, Box3D::A return ret; } -int -SPBox3D::VP_lies_in_PL_sector (Proj::Axis vpdir, int id1, int id2, Box3D::Axis axis) const { +int SPBox3D::VP_lies_in_PL_sector(Proj::Axis vpdir, int id1, int id2, Box3D::Axis axis) const +{ Persp3D *persp = this->get_perspective(); if (!Persp3D::VP_is_finite(persp->perspective_impl, vpdir)) { @@ -1156,8 +1142,8 @@ SPBox3D::VP_lies_in_PL_sector (Proj::Axis vpdir, int id1, int id2, Box3D::Axis a } /* swap the coordinates of corner0 and corner7 along the specified axis */ -static void -box3d_swap_coords(SPBox3D *box, Proj::Axis axis, bool smaller = true) { +static void box3d_swap_coords(SPBox3D *box, Proj::Axis axis, bool smaller = true) +{ box->orig_corner0.normalize(); box->orig_corner7.normalize(); if ((box->orig_corner0[axis] < box->orig_corner7[axis]) != smaller) { @@ -1169,27 +1155,27 @@ box3d_swap_coords(SPBox3D *box, Proj::Axis axis, bool smaller = true) { } /* ensure that the coordinates of corner0 and corner7 are in the correct order (to prevent everted boxes) */ -void -SPBox3D::relabel_corners() { +void SPBox3D::relabel_corners() +{ box3d_swap_coords(this, Proj::X, false); box3d_swap_coords(this, Proj::Y, false); box3d_swap_coords(this, Proj::Z, true); } -static void -box3d_check_for_swapped_coords(SPBox3D *box, Proj::Axis axis, bool smaller) { +static void box3d_check_for_swapped_coords(SPBox3D *box, Proj::Axis axis, bool smaller) +{ box->orig_corner0.normalize(); box->orig_corner7.normalize(); if ((box->orig_corner0[axis] < box->orig_corner7[axis]) != smaller) { - box->swapped = (Box3D::Axis) (box->swapped | Proj::toAffine(axis)); + box->swapped = (Box3D::Axis)(box->swapped | Proj::toAffine(axis)); } else { - box->swapped = (Box3D::Axis) (box->swapped & ~Proj::toAffine(axis)); + box->swapped = (Box3D::Axis)(box->swapped & ~Proj::toAffine(axis)); } } -static void -box3d_exchange_coords(SPBox3D *box) { +static void box3d_exchange_coords(SPBox3D *box) +{ box->orig_corner0.normalize(); box->orig_corner7.normalize(); @@ -1202,8 +1188,8 @@ box3d_exchange_coords(SPBox3D *box) { } } -void -SPBox3D::check_for_swapped_coords() { +void SPBox3D::check_for_swapped_coords() +{ box3d_check_for_swapped_coords(this, Proj::X, false); box3d_check_for_swapped_coords(this, Proj::Y, false); box3d_check_for_swapped_coords(this, Proj::Z, true); @@ -1211,31 +1197,32 @@ SPBox3D::check_for_swapped_coords() { box3d_exchange_coords(this); } -static void box3d_extract_boxes_rec(SPObject *obj, std::list &boxes) { +static void box3d_extract_boxes_rec(SPObject *obj, std::list &boxes) +{ SPBox3D *box = dynamic_cast(obj); if (box) { boxes.push_back(box); } else if (dynamic_cast(obj)) { - for (auto& child: obj->children) { + for (auto &child : obj->children) { box3d_extract_boxes_rec(&child, boxes); } } } -std::list -SPBox3D::extract_boxes(SPObject *obj) { +std::list SPBox3D::extract_boxes(SPObject *obj) +{ std::list boxes; box3d_extract_boxes_rec(obj, boxes); return boxes; } -Persp3D * -SPBox3D::get_perspective() const { +Persp3D *SPBox3D::get_perspective() const +{ return this->persp_ref->getObject(); } -void -SPBox3D::switch_perspectives(Persp3D *old_persp, Persp3D *new_persp, bool recompute_corners) { +void SPBox3D::switch_perspectives(Persp3D *old_persp, Persp3D *new_persp, bool recompute_corners) +{ if (recompute_corners) { this->orig_corner0.normalize(); this->orig_corner7.normalize(); @@ -1248,8 +1235,8 @@ SPBox3D::switch_perspectives(Persp3D *old_persp, Persp3D *new_persp, bool recomp this->orig_corner7 = new_persp->perspective_impl->tmat.preimage(corner7_screen, z7, Proj::Z); } - old_persp->remove_box (this); - new_persp->add_box (this); + old_persp->remove_box(this); + new_persp->add_box(this); Glib::ustring href = "#"; href += new_persp->getId(); @@ -1275,7 +1262,7 @@ SPGroup *SPBox3D::convert_to_group() // create a new group and add the sides (converted to ordinary paths) as its children Inkscape::XML::Node *grepr = xml_doc->createElement("svg:g"); - for (auto& obj: this->children) { + for (auto &obj : this->children) { Box3DSide *side = dynamic_cast(&obj); if (side) { Inkscape::XML::Node *repr = side->convert_to_path(); @@ -1302,22 +1289,25 @@ SPGroup *SPBox3D::convert_to_group() return group; } -const char *SPBox3D::displayName() const { +const char *SPBox3D::displayName() const +{ return _("3D Box"); } -gchar *SPBox3D::description() const { +gchar *SPBox3D::description() const +{ // We could put more details about the 3d box here return g_strdup(""); } -static inline void -box3d_push_back_corner_pair(SPBox3D const *box, std::list > &pts, int c1, int c2) { - pts.emplace_back(box->get_corner_screen(c1, false), - box->get_corner_screen(c2, false)); +static inline void box3d_push_back_corner_pair(SPBox3D const *box, std::list> &pts, + int c1, int c2) +{ + pts.emplace_back(box->get_corner_screen(c1, false), box->get_corner_screen(c2, false)); } -void SPBox3D::convert_to_guides() const { +void SPBox3D::convert_to_guides() const +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (!prefs->getBool("/tools/shapes/3dbox/convertguides", true)) { @@ -1325,7 +1315,7 @@ void SPBox3D::convert_to_guides() const { return; } - std::list > pts; + std::list> pts; /* perspective lines in X direction */ box3d_push_back_corner_pair(this, pts, 0, 1); diff --git a/src/object/box3d.h b/src/object/box3d.h index 9476f8e75da1c8da170f51fd8488ef885dd7d41c..425097eb5d3c79cfb4bbeecdaf1f7a803ebf5567 100644 --- a/src/object/box3d.h +++ b/src/object/box3d.h @@ -18,19 +18,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "sp-item-group.h" -#include "proj_pt.h" #include "axis-manip.h" +#include "proj_pt.h" +#include "sp-item-group.h" -#define SP_TYPE_BOX3D (box3d_get_type ()) +#define SP_TYPE_BOX3D (box3d_get_type()) class Persp3D; class Persp3DReference; -class SPBox3D : public SPGroup { +class SPBox3D : public SPGroup +{ public: - SPBox3D(); - ~SPBox3D() override; + SPBox3D(); + ~SPBox3D() override; int z_orders[6]; // z_orders[i] holds the ID of the face at position #i in the group (from top to bottom) @@ -50,33 +51,35 @@ public: /** * Create a SPBox3D and append it to the parent. */ - static SPBox3D * createBox3D(SPItem * parent); + static SPBox3D *createBox3D(SPItem *parent); - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; - void set(SPAttr key, char const* value) override; - void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, char const *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; - virtual const char* display_name(); - Geom::Affine set_transform(Geom::Affine const &transform) override; + virtual const char *display_name(); + Geom::Affine set_transform(Geom::Affine const &transform) override; void convert_to_guides() const override; - const char* displayName() const override; + const char *displayName() const override; char *description() const override; - void position_set (); - Geom::Point get_corner_screen (unsigned int id, bool item_coords = true) const; - Proj::Pt3 get_proj_center (); - Geom::Point get_center_screen (); + void position_set(); + Geom::Point get_corner_screen(unsigned int id, bool item_coords = true) const; + Proj::Pt3 get_proj_center(); + Geom::Point get_center_screen(); - void set_corner (unsigned int id, Geom::Point const &new_pos, Box3D::Axis movement, bool constrained); - void set_center (Geom::Point const &new_pos, Geom::Point const &old_pos, Box3D::Axis movement, bool constrained); - void corners_for_PLs (Proj::Axis axis, Geom::Point &corner1, Geom::Point &corner2, Geom::Point &corner3, Geom::Point &corner4) const; - bool recompute_z_orders (); - void set_z_orders (); + void set_corner(unsigned int id, Geom::Point const &new_pos, Box3D::Axis movement, bool constrained); + void set_center(Geom::Point const &new_pos, Geom::Point const &old_pos, Box3D::Axis movement, bool constrained); + void corners_for_PLs(Proj::Axis axis, Geom::Point &corner1, Geom::Point &corner2, Geom::Point &corner3, + Geom::Point &corner4) const; + bool recompute_z_orders(); + void set_z_orders(); - int pt_lies_in_PL_sector (Geom::Point const &pt, int id1, int id2, Box3D::Axis axis) const; - int VP_lies_in_PL_sector (Proj::Axis vpdir, int id1, int id2, Box3D::Axis axis) const; + int pt_lies_in_PL_sector(Geom::Point const &pt, int id1, int id2, Box3D::Axis axis) const; + int VP_lies_in_PL_sector(Proj::Axis vpdir, int id1, int id2, Box3D::Axis axis) const; void relabel_corners(); void check_for_swapped_coords(); @@ -89,7 +92,6 @@ public: SPGroup *convert_to_group(); }; - #endif // SEEN_SP_BOX3D_H /* diff --git a/src/object/color-profile.cpp b/src/object/color-profile.cpp index 6040d3326902f85677096d8f4ee25a5df89e2d90..09d5f1f1e7606e0f120a26733648c588dc81cf71 100644 --- a/src/object/color-profile.cpp +++ b/src/object/color-profile.cpp @@ -8,47 +8,47 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #define noDEBUG_LCMS -#include - -#include #include +#include #include +#include #ifdef DEBUG_LCMS #include #endif // DEBUG_LCMS -#include #include -#include -#include #include +#include +#include +#include #ifdef _WIN32 #include #endif #if HAVE_LIBLCMS2 -# include +#include #endif // HAVE_LIBLCMS2 -#include "xml/repr.h" -#include "color.h" -#include "color-profile.h" +#include +#include + +#include "attributes.h" #include "cms-system.h" #include "color-profile-cms-fns.h" -#include "attributes.h" -#include "inkscape.h" +#include "color-profile.h" +#include "color.h" #include "document.h" +#include "inkscape.h" #include "preferences.h" -#include -#include #include "uri.h" +#include "xml/repr.h" #ifdef _WIN32 #include @@ -57,50 +57,39 @@ using Inkscape::ColorProfile; using Inkscape::ColorProfileImpl; -namespace -{ +namespace { #if defined(HAVE_LIBLCMS2) cmsHPROFILE getSystemProfileHandle(); cmsHPROFILE getProofProfileHandle(); void loadProfiles(); Glib::ustring getNameFromProfile(cmsHPROFILE profile); #endif // defined(HAVE_LIBLCMS2) -} +} // namespace #ifdef DEBUG_LCMS extern guint update_in_progress; -#define DEBUG_MESSAGE_SCISLAC(key, ...) \ -{\ - Inkscape::Preferences *prefs = Inkscape::Preferences::get();\ - bool dump = prefs->getBool(Glib::ustring("/options/scislac/") + #key);\ - bool dumpD = prefs->getBool(Glib::ustring("/options/scislac/") + #key"D");\ - bool dumpD2 = prefs->getBool(Glib::ustring("/options/scislac/") + #key"D2");\ - dumpD &= ( (update_in_progress == 0) || dumpD2 );\ - if ( dump )\ - {\ - g_message( __VA_ARGS__ );\ -\ - }\ - if ( dumpD )\ - {\ - GtkWidget *dialog = gtk_message_dialog_new(NULL,\ - GTK_DIALOG_DESTROY_WITH_PARENT, \ - GTK_MESSAGE_INFO, \ - GTK_BUTTONS_OK, \ - __VA_ARGS__ \ - );\ - g_signal_connect_swapped(dialog, "response",\ - G_CALLBACK(gtk_widget_destroy), \ - dialog); \ - gtk_widget_show_all( dialog );\ - }\ -} - +#define DEBUG_MESSAGE_SCISLAC(key, ...) \ + { \ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); \ + bool dump = prefs->getBool(Glib::ustring("/options/scislac/") + #key); \ + bool dumpD = prefs->getBool(Glib::ustring("/options/scislac/") + #key "D"); \ + bool dumpD2 = prefs->getBool(Glib::ustring("/options/scislac/") + #key "D2"); \ + dumpD &= ((update_in_progress == 0) || dumpD2); \ + if (dump) { \ + g_message(__VA_ARGS__); \ + } \ + if (dumpD) { \ + GtkWidget *dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, \ + GTK_BUTTONS_OK, __VA_ARGS__); \ + g_signal_connect_swapped(dialog, "response", G_CALLBACK(gtk_widget_destroy), dialog); \ + gtk_widget_show_all(dialog); \ + } \ + } -#define DEBUG_MESSAGE(key, ...)\ -{\ - g_message( __VA_ARGS__ );\ -} +#define DEBUG_MESSAGE(key, ...) \ + { \ + g_message(__VA_ARGS__); \ + } #else #define DEBUG_MESSAGE_SCISLAC(key, ...) @@ -109,7 +98,8 @@ extern guint update_in_progress; namespace Inkscape { -class ColorProfileImpl { +class ColorProfileImpl +{ public: #if defined(HAVE_LIBLCMS2) static cmsHPROFILE _sRGBProf; @@ -119,7 +109,7 @@ public: ColorProfileImpl(); #if defined(HAVE_LIBLCMS2) - static cmsUInt32Number _getInputFormat( cmsColorSpaceSignature space ); + static cmsUInt32Number _getInputFormat(cmsColorSpaceSignature space); static cmsHPROFILE getNULLProfile(); static cmsHPROFILE getSRGBProfile(); @@ -136,12 +126,12 @@ public: }; #if defined(HAVE_LIBLCMS2) -cmsColorSpaceSignature asICColorSpaceSig(ColorSpaceSig const & sig) +cmsColorSpaceSignature asICColorSpaceSig(ColorSpaceSig const &sig) { return ColorSpaceSigWrapper(sig); } -cmsProfileClassSignature asICColorProfileClassSig(ColorProfileClassSig const & sig) +cmsProfileClassSignature asICColorProfileClassSig(ColorProfileClassSig const &sig) { return ColorProfileClassSigWrapper(sig); } @@ -151,23 +141,22 @@ cmsProfileClassSignature asICColorProfileClassSig(ColorProfileClassSig const & s ColorProfileImpl::ColorProfileImpl() #if defined(HAVE_LIBLCMS2) - : - _profHandle(nullptr), - _profileClass(cmsSigInputClass), - _profileSpace(cmsSigRgbData), - _transf(nullptr), - _revTransf(nullptr), - _gamutTransf(nullptr) + : _profHandle(nullptr) + , _profileClass(cmsSigInputClass) + , _profileSpace(cmsSigRgbData) + , _transf(nullptr) + , _revTransf(nullptr) + , _gamutTransf(nullptr) #endif // defined(HAVE_LIBLCMS2) -{ -} +{} #if defined(HAVE_LIBLCMS2) cmsHPROFILE ColorProfileImpl::_sRGBProf = nullptr; -cmsHPROFILE ColorProfileImpl::getSRGBProfile() { - if ( !_sRGBProf ) { +cmsHPROFILE ColorProfileImpl::getSRGBProfile() +{ + if (!_sRGBProf) { _sRGBProf = cmsCreate_sRGBProfile(); } return ColorProfileImpl::_sRGBProf; @@ -175,8 +164,9 @@ cmsHPROFILE ColorProfileImpl::getSRGBProfile() { cmsHPROFILE ColorProfileImpl::_NullProf = nullptr; -cmsHPROFILE ColorProfileImpl::getNULLProfile() { - if ( !_NullProf ) { +cmsHPROFILE ColorProfileImpl::getNULLProfile() +{ + if (!_NullProf) { _NullProf = cmsCreateNULLProfile(); } return _NullProf; @@ -184,33 +174,44 @@ cmsHPROFILE ColorProfileImpl::getNULLProfile() { #endif // defined(HAVE_LIBLCMS2) -ColorProfile::FilePlusHome::FilePlusHome(Glib::ustring filename, bool isInHome) : filename(std::move(filename)), isInHome(isInHome) { -} +ColorProfile::FilePlusHome::FilePlusHome(Glib::ustring filename, bool isInHome) + : filename(std::move(filename)) + , isInHome(isInHome) +{} -ColorProfile::FilePlusHome::FilePlusHome(const ColorProfile::FilePlusHome &filePlusHome) : FilePlusHome(filePlusHome.filename, filePlusHome.isInHome) { -} +ColorProfile::FilePlusHome::FilePlusHome(const ColorProfile::FilePlusHome &filePlusHome) + : FilePlusHome(filePlusHome.filename, filePlusHome.isInHome) +{} -bool ColorProfile::FilePlusHome::operator<(FilePlusHome const &other) const { +bool ColorProfile::FilePlusHome::operator<(FilePlusHome const &other) const +{ // if one is from home folder, other from global folder, sort home folder first. cf bug 1457126 bool result; - if (this->isInHome != other.isInHome) result = this->isInHome; - else result = this->filename < other.filename; + if (this->isInHome != other.isInHome) + result = this->isInHome; + else + result = this->filename < other.filename; return result; } ColorProfile::FilePlusHomeAndName::FilePlusHomeAndName(ColorProfile::FilePlusHome filePlusHome, Glib::ustring name) - : FilePlusHome(filePlusHome), name(std::move(name)) { -} + : FilePlusHome(filePlusHome) + , name(std::move(name)) +{} -bool ColorProfile::FilePlusHomeAndName::operator<(ColorProfile::FilePlusHomeAndName const &other) const { +bool ColorProfile::FilePlusHomeAndName::operator<(ColorProfile::FilePlusHomeAndName const &other) const +{ bool result; - if (this->isInHome != other.isInHome) result = this->isInHome; - else result = this->name < other.name; + if (this->isInHome != other.isInHome) + result = this->isInHome; + else + result = this->name < other.name; return result; } - -ColorProfile::ColorProfile() : SPObject() { +ColorProfile::ColorProfile() + : SPObject() +{ this->impl = new ColorProfileImpl(); this->href = nullptr; @@ -222,9 +223,10 @@ ColorProfile::ColorProfile() : SPObject() { ColorProfile::~ColorProfile() = default; -bool ColorProfile::operator<(ColorProfile const &other) const { - gchar *a_name_casefold = g_utf8_casefold(this->name, -1 ); - gchar *b_name_casefold = g_utf8_casefold(other.name, -1 ); +bool ColorProfile::operator<(ColorProfile const &other) const +{ + gchar *a_name_casefold = g_utf8_casefold(this->name, -1); + gchar *b_name_casefold = g_utf8_casefold(other.name, -1); int result = g_strcmp0(a_name_casefold, b_name_casefold); g_free(a_name_casefold); g_free(b_name_casefold); @@ -234,29 +236,30 @@ bool ColorProfile::operator<(ColorProfile const &other) const { /** * Callback: free object */ -void ColorProfile::release() { +void ColorProfile::release() +{ // Unregister ourselves - if ( this->document ) { + if (this->document) { this->document->removeResource("iccprofile", this); } - if ( this->href ) { - g_free( this->href ); + if (this->href) { + g_free(this->href); this->href = nullptr; } - if ( this->local ) { - g_free( this->local ); + if (this->local) { + g_free(this->local); this->local = nullptr; } - if ( this->name ) { - g_free( this->name ); + if (this->name) { + g_free(this->name); this->name = nullptr; } - if ( this->intentStr ) { - g_free( this->intentStr ); + if (this->intentStr) { + g_free(this->intentStr); this->intentStr = nullptr; } @@ -273,20 +276,20 @@ void ColorProfileImpl::_clearProfile() { _profileSpace = cmsSigRgbData; - if ( _transf ) { - cmsDeleteTransform( _transf ); + if (_transf) { + cmsDeleteTransform(_transf); _transf = nullptr; } - if ( _revTransf ) { - cmsDeleteTransform( _revTransf ); + if (_revTransf) { + cmsDeleteTransform(_revTransf); _revTransf = nullptr; } - if ( _gamutTransf ) { - cmsDeleteTransform( _gamutTransf ); + if (_gamutTransf) { + cmsDeleteTransform(_gamutTransf); _gamutTransf = nullptr; } - if ( _profHandle ) { - cmsCloseProfile( _profHandle ); + if (_profHandle) { + cmsCloseProfile(_profHandle); _profHandle = nullptr; } } @@ -295,7 +298,8 @@ void ColorProfileImpl::_clearProfile() /** * Callback: set attributes from associated repr. */ -void ColorProfile::build(SPDocument *document, Inkscape::XML::Node *repr) { +void ColorProfile::build(SPDocument *document, Inkscape::XML::Node *repr) +{ g_assert(this->href == nullptr); g_assert(this->local == nullptr); g_assert(this->name == nullptr); @@ -310,30 +314,30 @@ void ColorProfile::build(SPDocument *document, Inkscape::XML::Node *repr) { this->readAttr(SPAttr::RENDERING_INTENT); // Register - if ( document ) { - document->addResource( "iccprofile", this ); + if (document) { + document->addResource("iccprofile", this); } } - /** * Callback: set attribute. */ -void ColorProfile::set(SPAttr key, gchar const *value) { +void ColorProfile::set(SPAttr key, gchar const *value) +{ switch (key) { case SPAttr::XLINK_HREF: - if ( this->href ) { - g_free( this->href ); + if (this->href) { + g_free(this->href); this->href = nullptr; } - if ( value ) { - this->href = g_strdup( value ); - if ( *this->href ) { + if (value) { + this->href = g_strdup(value); + if (*this->href) { #if defined(HAVE_LIBLCMS2) // TODO open filename and URIs properly - //FILE* fp = fopen_utf8name( filename, "r" ); - //LCMSAPI cmsHPROFILE LCMSEXPORT cmsOpenProfileFromMem(LPVOID MemPtr, cmsUInt32Number dwSize); + // FILE* fp = fopen_utf8name( filename, "r" ); + // LCMSAPI cmsHPROFILE LCMSEXPORT cmsOpenProfileFromMem(LPVOID MemPtr, cmsUInt32Number dwSize); // Try to open relative SPDocument *doc = this->document; @@ -359,11 +363,12 @@ void ColorProfile::set(SPAttr key, gchar const *value) { g_warning("Failed to open CMS profile URI '%.100s'", this->href); } - if ( this->impl->_profHandle ) { - this->impl->_profileSpace = cmsGetColorSpace( this->impl->_profHandle ); - this->impl->_profileClass = cmsGetDeviceClass( this->impl->_profHandle ); + if (this->impl->_profHandle) { + this->impl->_profileSpace = cmsGetColorSpace(this->impl->_profHandle); + this->impl->_profileClass = cmsGetDeviceClass(this->impl->_profHandle); } - DEBUG_MESSAGE( lcmsOne, "cmsOpenProfileFromFile( '%s'...) = %p", fullname, (void*)this->impl->_profHandle ); + DEBUG_MESSAGE(lcmsOne, "cmsOpenProfileFromFile( '%s'...) = %p", fullname, + (void *)this->impl->_profHandle); #endif // defined(HAVE_LIBLCMS2) } } @@ -371,41 +376,41 @@ void ColorProfile::set(SPAttr key, gchar const *value) { break; case SPAttr::LOCAL: - if ( this->local ) { - g_free( this->local ); + if (this->local) { + g_free(this->local); this->local = nullptr; } - this->local = g_strdup( value ); + this->local = g_strdup(value); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::NAME: - if ( this->name ) { - g_free( this->name ); + if (this->name) { + g_free(this->name); this->name = nullptr; } - this->name = g_strdup( value ); - DEBUG_MESSAGE( lcmsTwo, " name set to '%s'", this->name ); + this->name = g_strdup(value); + DEBUG_MESSAGE(lcmsTwo, " name set to '%s'", this->name); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::RENDERING_INTENT: - if ( this->intentStr ) { - g_free( this->intentStr ); + if (this->intentStr) { + g_free(this->intentStr); this->intentStr = nullptr; } - this->intentStr = g_strdup( value ); + this->intentStr = g_strdup(value); - if ( value ) { - if ( strcmp( value, "auto" ) == 0 ) { + if (value) { + if (strcmp(value, "auto") == 0) { this->rendering_intent = RENDERING_INTENT_AUTO; - } else if ( strcmp( value, "perceptual" ) == 0 ) { + } else if (strcmp(value, "perceptual") == 0) { this->rendering_intent = RENDERING_INTENT_PERCEPTUAL; - } else if ( strcmp( value, "relative-colorimetric" ) == 0 ) { + } else if (strcmp(value, "relative-colorimetric") == 0) { this->rendering_intent = RENDERING_INTENT_RELATIVE_COLORIMETRIC; - } else if ( strcmp( value, "saturation" ) == 0 ) { + } else if (strcmp(value, "saturation") == 0) { this->rendering_intent = RENDERING_INTENT_SATURATION; - } else if ( strcmp( value, "absolute-colorimetric" ) == 0 ) { + } else if (strcmp(value, "absolute-colorimetric") == 0) { this->rendering_intent = RENDERING_INTENT_ABSOLUTE_COLORIMETRIC; } else { this->rendering_intent = RENDERING_INTENT_UNKNOWN; @@ -418,7 +423,7 @@ void ColorProfile::set(SPAttr key, gchar const *value) { break; default: - SPObject::set(key, value); + SPObject::set(key, value); break; } } @@ -426,25 +431,26 @@ void ColorProfile::set(SPAttr key, gchar const *value) { /** * Callback: write attributes to associated repr. */ -Inkscape::XML::Node* ColorProfile::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *ColorProfile::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:color-profile"); } - if ( (flags & SP_OBJECT_WRITE_ALL) || this->href ) { - repr->setAttribute( "xlink:href", this->href ); + if ((flags & SP_OBJECT_WRITE_ALL) || this->href) { + repr->setAttribute("xlink:href", this->href); } - if ( (flags & SP_OBJECT_WRITE_ALL) || this->local ) { - repr->setAttribute( "local", this->local ); + if ((flags & SP_OBJECT_WRITE_ALL) || this->local) { + repr->setAttribute("local", this->local); } - if ( (flags & SP_OBJECT_WRITE_ALL) || this->name ) { - repr->setAttribute( "name", this->name ); + if ((flags & SP_OBJECT_WRITE_ALL) || this->name) { + repr->setAttribute("name", this->name); } - if ( (flags & SP_OBJECT_WRITE_ALL) || this->intentStr ) { - repr->setAttribute( "rendering-intent", this->intentStr ); + if ((flags & SP_OBJECT_WRITE_ALL) || this->intentStr) { + repr->setAttribute("rendering-intent", this->intentStr); } SPObject::write(xml_doc, repr, flags); @@ -452,33 +458,33 @@ Inkscape::XML::Node* ColorProfile::write(Inkscape::XML::Document *xml_doc, Inksc return repr; } - #if defined(HAVE_LIBLCMS2) -struct MapMap { +struct MapMap +{ cmsColorSpaceSignature space; cmsUInt32Number inForm; }; -cmsUInt32Number ColorProfileImpl::_getInputFormat( cmsColorSpaceSignature space ) +cmsUInt32Number ColorProfileImpl::_getInputFormat(cmsColorSpaceSignature space) { MapMap possible[] = { - {cmsSigXYZData, TYPE_XYZ_16}, - {cmsSigLabData, TYPE_Lab_16}, - //cmsSigLuvData + {cmsSigXYZData, TYPE_XYZ_16}, + {cmsSigLabData, TYPE_Lab_16}, + // cmsSigLuvData {cmsSigYCbCrData, TYPE_YCbCr_16}, - {cmsSigYxyData, TYPE_Yxy_16}, - {cmsSigRgbData, TYPE_RGB_16}, - {cmsSigGrayData, TYPE_GRAY_16}, - {cmsSigHsvData, TYPE_HSV_16}, - {cmsSigHlsData, TYPE_HLS_16}, - {cmsSigCmykData, TYPE_CMYK_16}, - {cmsSigCmyData, TYPE_CMY_16}, + {cmsSigYxyData, TYPE_Yxy_16}, + {cmsSigRgbData, TYPE_RGB_16}, + {cmsSigGrayData, TYPE_GRAY_16}, + {cmsSigHsvData, TYPE_HSV_16}, + {cmsSigHlsData, TYPE_HLS_16}, + {cmsSigCmykData, TYPE_CMYK_16}, + {cmsSigCmyData, TYPE_CMY_16}, }; int index = 0; - for ( guint i = 0; i < G_N_ELEMENTS(possible); i++ ) { - if ( possible[i].space == space ) { + for (guint i = 0; i < G_N_ELEMENTS(possible); i++) { + if (possible[i].space == space) { index = i; break; } @@ -487,10 +493,10 @@ cmsUInt32Number ColorProfileImpl::_getInputFormat( cmsColorSpaceSignature space return possible[index].inForm; } -static int getLcmsIntent( guint svgIntent ) +static int getLcmsIntent(guint svgIntent) { int intent = INTENT_PERCEPTUAL; - switch ( svgIntent ) { + switch (svgIntent) { case Inkscape::RENDERING_INTENT_RELATIVE_COLORIMETRIC: intent = INTENT_RELATIVE_COLORIMETRIC; break; @@ -509,15 +515,15 @@ static int getLcmsIntent( guint svgIntent ) return intent; } -static SPObject* bruteFind( SPDocument* document, gchar const* name ) +static SPObject *bruteFind(SPDocument *document, gchar const *name) { - SPObject* result = nullptr; + SPObject *result = nullptr; std::vector current = document->getResourceList("iccprofile"); for (std::vector::const_iterator it = current.begin(); (!result) && (it != current.end()); ++it) { - if ( IS_COLORPROFILE(*it) ) { - ColorProfile* prof = COLORPROFILE(*it); - if ( prof ) { - if ( prof->name && (strcmp(prof->name, name) == 0) ) { + if (IS_COLORPROFILE(*it)) { + ColorProfile *prof = COLORPROFILE(*it); + if (prof) { + if (prof->name && (strcmp(prof->name, name) == 0)) { result = SP_OBJECT(*it); break; } @@ -528,61 +534,62 @@ static SPObject* bruteFind( SPDocument* document, gchar const* name ) return result; } -cmsHPROFILE Inkscape::CMSSystem::getHandle( SPDocument* document, guint* intent, gchar const* name ) +cmsHPROFILE Inkscape::CMSSystem::getHandle(SPDocument *document, guint *intent, gchar const *name) { cmsHPROFILE prof = nullptr; - SPObject* thing = bruteFind( document, name ); - if ( thing ) { + SPObject *thing = bruteFind(document, name); + if (thing) { prof = COLORPROFILE(thing)->impl->_profHandle; } - if ( intent ) { + if (intent) { *intent = thing ? COLORPROFILE(thing)->rendering_intent : (guint)RENDERING_INTENT_UNKNOWN; } - DEBUG_MESSAGE( lcmsThree, " queried for profile of '%s'. Returning %p with intent of %d", name, prof, (intent? *intent:0) ); + DEBUG_MESSAGE(lcmsThree, " queried for profile of '%s'. Returning %p with intent of %d", name, prof, + (intent ? *intent : 0)); return prof; } -Inkscape::ColorSpaceSig ColorProfile::getColorSpace() const { +Inkscape::ColorSpaceSig ColorProfile::getColorSpace() const +{ return ColorSpaceSigWrapper(impl->_profileSpace); } -Inkscape::ColorProfileClassSig ColorProfile::getProfileClass() const { +Inkscape::ColorProfileClassSig ColorProfile::getProfileClass() const +{ return ColorProfileClassSigWrapper(impl->_profileClass); } cmsHTRANSFORM ColorProfile::getTransfToSRGB8() { - if ( !impl->_transf && impl->_profHandle ) { + if (!impl->_transf && impl->_profHandle) { int intent = getLcmsIntent(rendering_intent); - impl->_transf = cmsCreateTransform( impl->_profHandle, ColorProfileImpl::_getInputFormat(impl->_profileSpace), ColorProfileImpl::getSRGBProfile(), TYPE_RGBA_8, intent, 0 ); + impl->_transf = cmsCreateTransform(impl->_profHandle, ColorProfileImpl::_getInputFormat(impl->_profileSpace), + ColorProfileImpl::getSRGBProfile(), TYPE_RGBA_8, intent, 0); } return impl->_transf; } cmsHTRANSFORM ColorProfile::getTransfFromSRGB8() { - if ( !impl->_revTransf && impl->_profHandle ) { + if (!impl->_revTransf && impl->_profHandle) { int intent = getLcmsIntent(rendering_intent); - impl->_revTransf = cmsCreateTransform( ColorProfileImpl::getSRGBProfile(), TYPE_RGBA_8, impl->_profHandle, ColorProfileImpl::_getInputFormat(impl->_profileSpace), intent, 0 ); + impl->_revTransf = cmsCreateTransform(ColorProfileImpl::getSRGBProfile(), TYPE_RGBA_8, impl->_profHandle, + ColorProfileImpl::_getInputFormat(impl->_profileSpace), intent, 0); } return impl->_revTransf; } cmsHTRANSFORM ColorProfile::getTransfGamutCheck() { - if ( !impl->_gamutTransf ) { - impl->_gamutTransf = cmsCreateProofingTransform(ColorProfileImpl::getSRGBProfile(), - TYPE_BGRA_8, - ColorProfileImpl::getNULLProfile(), - TYPE_GRAY_8, - impl->_profHandle, - INTENT_RELATIVE_COLORIMETRIC, - INTENT_RELATIVE_COLORIMETRIC, - (cmsFLAGS_GAMUTCHECK | cmsFLAGS_SOFTPROOFING)); + if (!impl->_gamutTransf) { + impl->_gamutTransf = cmsCreateProofingTransform( + ColorProfileImpl::getSRGBProfile(), TYPE_BGRA_8, ColorProfileImpl::getNULLProfile(), TYPE_GRAY_8, + impl->_profHandle, INTENT_RELATIVE_COLORIMETRIC, INTENT_RELATIVE_COLORIMETRIC, + (cmsFLAGS_GAMUTCHECK | cmsFLAGS_SOFTPROOFING)); } return impl->_gamutTransf; } @@ -600,11 +607,8 @@ bool ColorProfile::GamutCheck(SPColor color) #endif cmsUInt8Number outofgamut = 0; - guchar check_color[4] = { - static_cast(SP_RGBA32_R_U(val)), - static_cast(SP_RGBA32_G_U(val)), - static_cast(SP_RGBA32_B_U(val)), - 255}; + guchar check_color[4] = {static_cast(SP_RGBA32_R_U(val)), static_cast(SP_RGBA32_G_U(val)), + static_cast(SP_RGBA32_B_U(val)), 255}; cmsHTRANSFORM gamutCheck = ColorProfile::getTransfGamutCheck(); if (gamutCheck) { @@ -621,12 +625,12 @@ bool ColorProfile::GamutCheck(SPColor color) class ProfileInfo { public: - ProfileInfo( cmsHPROFILE prof, Glib::ustring path ); + ProfileInfo(cmsHPROFILE prof, Glib::ustring path); - Glib::ustring const& getName() {return _name;} - Glib::ustring const& getPath() {return _path;} - cmsColorSpaceSignature getSpace() {return _profileSpace;} - cmsProfileClassSignature getClass() {return _profileClass;} + Glib::ustring const &getName() { return _name; } + Glib::ustring const &getPath() { return _path; } + cmsColorSpaceSignature getSpace() { return _profileSpace; } + cmsProfileClassSignature getClass() { return _profileClass; } private: Glib::ustring _path; @@ -635,15 +639,12 @@ private: cmsProfileClassSignature _profileClass; }; -ProfileInfo::ProfileInfo( cmsHPROFILE prof, Glib::ustring path ) : - _path(std::move( path )), - _name( getNameFromProfile(prof) ), - _profileSpace( cmsGetColorSpace( prof ) ), - _profileClass( cmsGetDeviceClass( prof ) ) -{ -} - - +ProfileInfo::ProfileInfo(cmsHPROFILE prof, Glib::ustring path) + : _path(std::move(path)) + , _name(getNameFromProfile(prof)) + , _profileSpace(cmsGetColorSpace(prof)) + , _profileClass(cmsGetDeviceClass(prof)) +{} static std::vector knownProfiles; @@ -652,9 +653,9 @@ std::vector Inkscape::CMSSystem::getDisplayNames() loadProfiles(); std::vector result; - for (auto & knownProfile : knownProfiles) { - if ( knownProfile.getClass() == cmsSigDisplayClass && knownProfile.getSpace() == cmsSigRgbData ) { - result.push_back( knownProfile.getName() ); + for (auto &knownProfile : knownProfiles) { + if (knownProfile.getClass() == cmsSigDisplayClass && knownProfile.getSpace() == cmsSigRgbData) { + result.push_back(knownProfile.getName()); } } std::sort(result.begin(), result.end()); @@ -667,9 +668,9 @@ std::vector Inkscape::CMSSystem::getSoftproofNames() loadProfiles(); std::vector result; - for (auto & knownProfile : knownProfiles) { - if ( knownProfile.getClass() == cmsSigOutputClass ) { - result.push_back( knownProfile.getName() ); + for (auto &knownProfile : knownProfiles) { + if (knownProfile.getClass() == cmsSigOutputClass) { + result.push_back(knownProfile.getName()); } } std::sort(result.begin(), result.end()); @@ -677,13 +678,13 @@ std::vector Inkscape::CMSSystem::getSoftproofNames() return result; } -Glib::ustring Inkscape::CMSSystem::getPathForProfile(Glib::ustring const& name) +Glib::ustring Inkscape::CMSSystem::getPathForProfile(Glib::ustring const &name) { loadProfiles(); Glib::ustring result; - for (auto & knownProfile : knownProfiles) { - if ( name == knownProfile.getName() ) { + for (auto &knownProfile : knownProfiles) { + if (name == knownProfile.getName()) { result = knownProfile.getPath(); break; } @@ -700,7 +701,7 @@ void Inkscape::CMSSystem::doTransform(cmsHTRANSFORM transform, void *inBuf, void bool Inkscape::CMSSystem::isPrintColorSpace(ColorProfile const *profile) { bool isPrint = false; - if ( profile ) { + if (profile) { ColorSpaceSigWrapper colorspace = profile->getColorSpace(); isPrint = (colorspace == cmsSigCmykData) || (colorspace == cmsSigCmyData); } @@ -710,9 +711,9 @@ bool Inkscape::CMSSystem::isPrintColorSpace(ColorProfile const *profile) gint Inkscape::CMSSystem::getChannelCount(ColorProfile const *profile) { gint count = 0; - if ( profile ) { + if (profile) { #if HAVE_LIBLCMS2 - count = cmsChannelsOf( asICColorSpaceSig(profile->getColorSpace()) ); + count = cmsChannelsOf(asICColorSpaceSig(profile->getColorSpace())); #endif } return count; @@ -722,7 +723,8 @@ gint Inkscape::CMSSystem::getChannelCount(ColorProfile const *profile) // the bool return value tells if it's a user's directory or a system location // note that this will treat places under $HOME as system directories when they are found via $XDG_DATA_DIRS -std::set ColorProfile::getBaseProfileDirs() { +std::set ColorProfile::getBaseProfileDirs() +{ #if defined(HAVE_LIBLCMS2) static bool warnSet = false; if (!warnSet) { @@ -732,12 +734,13 @@ std::set ColorProfile::getBaseProfileDirs() { std::set sources; // first try user's local dir - gchar* path = g_build_filename(g_get_user_data_dir(), "color", "icc", NULL); + gchar *path = g_build_filename(g_get_user_data_dir(), "color", "icc", NULL); sources.insert(FilePlusHome(path, true)); g_free(path); // search colord ICC store paths - // (see https://github.com/hughsie/colord/blob/fe10f76536bb27614ced04e0ff944dc6fb4625c0/lib/colord/cd-icc-store.c#L590) + // (see + // https://github.com/hughsie/colord/blob/fe10f76536bb27614ced04e0ff944dc6fb4625c0/lib/colord/cd-icc-store.c#L590) // user store path = g_build_filename(g_get_user_data_dir(), "icc", NULL); @@ -752,9 +755,9 @@ std::set ColorProfile::getBaseProfileDirs() { sources.insert(FilePlusHome("/var/lib/color/icc", false)); sources.insert(FilePlusHome("/var/lib/colord/icc", false)); - const gchar* const * dataDirs = g_get_system_data_dirs(); - for ( int i = 0; dataDirs[i]; i++ ) { - gchar* path = g_build_filename(dataDirs[i], "color", "icc", NULL); + const gchar *const *dataDirs = g_get_system_data_dirs(); + for (int i = 0; dataDirs[i]; i++) { + gchar *path = g_build_filename(dataDirs[i], "color", "icc", NULL); sources.insert(FilePlusHome(path, false)); g_free(path); } @@ -774,51 +777,52 @@ std::set ColorProfile::getBaseProfileDirs() { pathBuf[0] = 0; DWORD pathSize = sizeof(pathBuf); g_assert(sizeof(wchar_t) == sizeof(gunichar2)); - if ( GetColorDirectoryW( NULL, pathBuf, &pathSize ) ) { - gchar * utf8Path = g_utf16_to_utf8( (gunichar2*)(&pathBuf[0]), -1, NULL, NULL, NULL ); - if ( !g_utf8_validate(utf8Path, -1, NULL) ) { - g_warning( "GetColorDirectoryW() resulted in invalid UTF-8" ); + if (GetColorDirectoryW(NULL, pathBuf, &pathSize)) { + gchar *utf8Path = g_utf16_to_utf8((gunichar2 *)(&pathBuf[0]), -1, NULL, NULL, NULL); + if (!g_utf8_validate(utf8Path, -1, NULL)) { + g_warning("GetColorDirectoryW() resulted in invalid UTF-8"); } else { sources.insert(FilePlusHome(utf8Path, false)); } - g_free( utf8Path ); + g_free(utf8Path); } #endif // _WIN32 return sources; } -static bool isIccFile( gchar const *filepath ) +static bool isIccFile(gchar const *filepath) { bool isIccFile = false; GStatBuf st; - if ( g_stat(filepath, &st) == 0 && (st.st_size > 128) ) { - //0-3 == size - //36-39 == 'acsp' 0x61637370 - int fd = g_open( filepath, O_RDONLY, S_IRWXU); - if ( fd != -1 ) { + if (g_stat(filepath, &st) == 0 && (st.st_size > 128)) { + // 0-3 == size + // 36-39 == 'acsp' 0x61637370 + int fd = g_open(filepath, O_RDONLY, S_IRWXU); + if (fd != -1) { guchar scratch[40] = {0}; size_t len = sizeof(scratch); - //size_t left = 40; + // size_t left = 40; ssize_t got = read(fd, scratch, len); - if ( got != -1 ) { + if (got != -1) { size_t calcSize = (scratch[0] << 24) | (scratch[1] << 16) | (scratch[2] << 8) | scratch[3]; - if ( calcSize > 128 && calcSize <= static_cast(st.st_size) ) { - isIccFile = (scratch[36] == 'a') && (scratch[37] == 'c') && (scratch[38] == 's') && (scratch[39] == 'p'); + if (calcSize > 128 && calcSize <= static_cast(st.st_size)) { + isIccFile = + (scratch[36] == 'a') && (scratch[37] == 'c') && (scratch[38] == 's') && (scratch[39] == 'p'); } } close(fd); #if defined(HAVE_LIBLCMS2) if (isIccFile) { - cmsHPROFILE prof = cmsOpenProfileFromFile( filepath, "r" ); - if ( prof ) { + cmsHPROFILE prof = cmsOpenProfileFromFile(filepath, "r"); + if (prof) { cmsProfileClassSignature profClass = cmsGetDeviceClass(prof); - if ( profClass == cmsSigNamedColorClass ) { + if (profClass == cmsSigNamedColorClass) { isIccFile = false; // Ignore named color profiles for now. } - cmsCloseProfile( prof ); + cmsCloseProfile(prof); } } #endif // defined(HAVE_LIBLCMS2) @@ -827,14 +831,14 @@ static bool isIccFile( gchar const *filepath ) return isIccFile; } -std::set ColorProfile::getProfileFiles() +std::set ColorProfile::getProfileFiles() { std::set files; using Inkscape::IO::Resource::get_filenames; - for (auto &path: ColorProfile::getBaseProfileDirs()) { - for(auto &filename: get_filenames(path.filename, {".icc", ".icm"})) { - if ( isIccFile(filename.c_str()) ) { + for (auto &path : ColorProfile::getBaseProfileDirs()) { + for (auto &filename : get_filenames(path.filename, {".icc", ".icm"})) { + if (isIccFile(filename.c_str())) { files.insert(FilePlusHome(filename, path.isInHome)); } } @@ -848,11 +852,11 @@ std::set ColorProfile::getProfileFilesWithNam std::set result; #if defined(HAVE_LIBLCMS2) - for (auto &profile: getProfileFiles()) { + for (auto &profile : getProfileFiles()) { cmsHPROFILE hProfile = cmsOpenProfileFromFile(profile.filename.c_str(), "r"); - if ( hProfile ) { + if (hProfile) { Glib::ustring name = getNameFromProfile(hProfile); - result.insert( FilePlusHomeAndName(profile, name) ); + result.insert(FilePlusHomeAndName(profile, name)); cmsCloseProfile(hProfile); } } @@ -867,33 +871,31 @@ void errorHandlerCB(cmsContext /*contextID*/, cmsUInt32Number errorCode, char co { g_message("lcms: Error %d", errorCode); g_message(" %p", errorText); - //g_message("lcms: Error %d; %s", errorCode, errorText); + // g_message("lcms: Error %d; %s", errorCode, errorText); } #endif -namespace -{ +namespace { Glib::ustring getNameFromProfile(cmsHPROFILE profile) { Glib::ustring nameStr; - if ( profile ) { + if (profile) { #if HAVE_LIBLCMS2 - cmsUInt32Number byteLen = cmsGetProfileInfo(profile, cmsInfoDescription, "en", "US", nullptr, 0); - if (byteLen > 0) { - // TODO investigate wchar_t and cmsGetProfileInfo() - std::vector data(byteLen); - cmsUInt32Number readLen = cmsGetProfileInfoASCII(profile, cmsInfoDescription, - "en", "US", - data.data(), data.size()); - if (readLen < data.size()) { - data.resize(readLen); + cmsUInt32Number byteLen = cmsGetProfileInfo(profile, cmsInfoDescription, "en", "US", nullptr, 0); + if (byteLen > 0) { + // TODO investigate wchar_t and cmsGetProfileInfo() + std::vector data(byteLen); + cmsUInt32Number readLen = + cmsGetProfileInfoASCII(profile, cmsInfoDescription, "en", "US", data.data(), data.size()); + if (readLen < data.size()) { + data.resize(readLen); + } + nameStr = Glib::ustring(data.begin(), data.end()); + } + if (nameStr.empty() || !g_utf8_validate(nameStr.c_str(), -1, nullptr)) { + nameStr = _("(invalid UTF-8 string)"); } - nameStr = Glib::ustring(data.begin(), data.end()); - } - if (nameStr.empty() || !g_utf8_validate(nameStr.c_str(), -1, nullptr)) { - nameStr = _("(invalid UTF-8 string)"); - } #endif } return nameStr; @@ -908,32 +910,32 @@ void loadProfiles() static bool error_handler_set = false; if (!error_handler_set) { #if HAVE_LIBLCMS2 - //cmsSetLogErrorHandler(errorHandlerCB); - //g_message("LCMS error handler set"); + // cmsSetLogErrorHandler(errorHandlerCB); + // g_message("LCMS error handler set"); #endif error_handler_set = true; } static bool profiles_searched = false; - if ( !profiles_searched ) { + if (!profiles_searched) { knownProfiles.clear(); - for (auto &profile: ColorProfile::getProfileFiles()) { - cmsHPROFILE prof = cmsOpenProfileFromFile( profile.filename.c_str(), "r" ); - if ( prof ) { - ProfileInfo info( prof, Glib::filename_to_utf8( profile.filename.c_str() ) ); - cmsCloseProfile( prof ); + for (auto &profile : ColorProfile::getProfileFiles()) { + cmsHPROFILE prof = cmsOpenProfileFromFile(profile.filename.c_str(), "r"); + if (prof) { + ProfileInfo info(prof, Glib::filename_to_utf8(profile.filename.c_str())); + cmsCloseProfile(prof); prof = nullptr; bool sameName = false; - for(auto &knownProfile: knownProfiles) { - if ( knownProfile.getName() == info.getName() ) { + for (auto &knownProfile : knownProfiles) { + if (knownProfile.getName() == info.getName()) { sameName = true; break; } } - if ( !sameName ) { + if (!sameName) { knownProfiles.push_back(info); } } @@ -966,41 +968,41 @@ cmsHPROFILE getSystemProfileHandle() Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring uri = prefs->getString("/options/displayprofile/uri"); - if ( !uri.empty() ) { - if ( uri != lastURI ) { + if (!uri.empty()) { + if (uri != lastURI) { lastURI.clear(); - if ( theOne ) { - cmsCloseProfile( theOne ); + if (theOne) { + cmsCloseProfile(theOne); } - if ( transf ) { - cmsDeleteTransform( transf ); + if (transf) { + cmsDeleteTransform(transf); transf = nullptr; } - theOne = cmsOpenProfileFromFile( uri.data(), "r" ); - if ( theOne ) { + theOne = cmsOpenProfileFromFile(uri.data(), "r"); + if (theOne) { // a display profile must have the proper stuff cmsColorSpaceSignature space = cmsGetColorSpace(theOne); cmsProfileClassSignature profClass = cmsGetDeviceClass(theOne); - if ( profClass != cmsSigDisplayClass ) { + if (profClass != cmsSigDisplayClass) { g_warning("Not a display profile"); - cmsCloseProfile( theOne ); + cmsCloseProfile(theOne); theOne = nullptr; - } else if ( space != cmsSigRgbData ) { + } else if (space != cmsSigRgbData) { g_warning("Not an RGB profile"); - cmsCloseProfile( theOne ); + cmsCloseProfile(theOne); theOne = nullptr; } else { lastURI = uri; } } } - } else if ( theOne ) { - cmsCloseProfile( theOne ); + } else if (theOne) { + cmsCloseProfile(theOne); theOne = nullptr; lastURI.clear(); - if ( transf ) { - cmsDeleteTransform( transf ); + if (transf) { + cmsDeleteTransform(transf); transf = nullptr; } } @@ -1008,7 +1010,6 @@ cmsHPROFILE getSystemProfileHandle() return theOne; } - cmsHPROFILE getProofProfileHandle() { static cmsHPROFILE theOne = nullptr; @@ -1017,50 +1018,50 @@ cmsHPROFILE getProofProfileHandle() loadProfiles(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool which = prefs->getBool( "/options/softproof/enable"); + bool which = prefs->getBool("/options/softproof/enable"); Glib::ustring uri = prefs->getString("/options/softproof/uri"); - if ( which && !uri.empty() ) { - if ( lastURI != uri ) { + if (which && !uri.empty()) { + if (lastURI != uri) { lastURI.clear(); - if ( theOne ) { - cmsCloseProfile( theOne ); + if (theOne) { + cmsCloseProfile(theOne); } - if ( transf ) { - cmsDeleteTransform( transf ); + if (transf) { + cmsDeleteTransform(transf); transf = nullptr; } - theOne = cmsOpenProfileFromFile( uri.data(), "r" ); - if ( theOne ) { + theOne = cmsOpenProfileFromFile(uri.data(), "r"); + if (theOne) { // a display profile must have the proper stuff cmsColorSpaceSignature space = cmsGetColorSpace(theOne); cmsProfileClassSignature profClass = cmsGetDeviceClass(theOne); (void)space; (void)profClass; -/* - if ( profClass != cmsSigDisplayClass ) { - g_warning("Not a display profile"); - cmsCloseProfile( theOne ); - theOne = 0; - } else if ( space != cmsSigRgbData ) { - g_warning("Not an RGB profile"); - cmsCloseProfile( theOne ); - theOne = 0; - } else { -*/ - lastURI = uri; -/* - } -*/ + /* + if ( profClass != cmsSigDisplayClass ) { + g_warning("Not a display profile"); + cmsCloseProfile( theOne ); + theOne = 0; + } else if ( space != cmsSigRgbData ) { + g_warning("Not an RGB profile"); + cmsCloseProfile( theOne ); + theOne = 0; + } else { + */ + lastURI = uri; + /* + } + */ } } - } else if ( theOne ) { - cmsCloseProfile( theOne ); + } else if (theOne) { + cmsCloseProfile(theOne); theOne = nullptr; lastURI.clear(); - if ( transf ) { - cmsDeleteTransform( transf ); + if (transf) { + cmsDeleteTransform(transf); transf = nullptr; } } @@ -1074,34 +1075,30 @@ static void free_transforms(); cmsHTRANSFORM Inkscape::CMSSystem::getDisplayTransform() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool fromDisplay = prefs->getBool( "/options/displayprofile/from_display"); - if ( fromDisplay ) { - if ( transf ) { + bool fromDisplay = prefs->getBool("/options/displayprofile/from_display"); + if (fromDisplay) { + if (transf) { cmsDeleteTransform(transf); transf = nullptr; } return nullptr; } - bool warn = prefs->getBool( "/options/softproof/gamutwarn"); - int intent = prefs->getIntLimited( "/options/displayprofile/intent", 0, 0, 3 ); - int proofIntent = prefs->getIntLimited( "/options/softproof/intent", 0, 0, 3 ); - bool bpc = prefs->getBool( "/options/softproof/bpc"); + bool warn = prefs->getBool("/options/softproof/gamutwarn"); + int intent = prefs->getIntLimited("/options/displayprofile/intent", 0, 0, 3); + int proofIntent = prefs->getIntLimited("/options/softproof/intent", 0, 0, 3); + bool bpc = prefs->getBool("/options/softproof/bpc"); #if defined(cmsFLAGS_PRESERVEBLACK) - bool preserveBlack = prefs->getBool( "/options/softproof/preserveblack"); -#endif //defined(cmsFLAGS_PRESERVEBLACK) + bool preserveBlack = prefs->getBool("/options/softproof/preserveblack"); +#endif // defined(cmsFLAGS_PRESERVEBLACK) Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor"); - Gdk::RGBA gamutColor( colorStr.empty() ? "#808080" : colorStr ); + Gdk::RGBA gamutColor(colorStr.empty() ? "#808080" : colorStr); - if ( (warn != gamutWarn) - || (lastIntent != intent) - || (lastProofIntent != proofIntent) - || (bpc != lastBPC) + if ((warn != gamutWarn) || (lastIntent != intent) || (lastProofIntent != proofIntent) || (bpc != lastBPC) #if defined(cmsFLAGS_PRESERVEBLACK) - || (preserveBlack != lastPreserveBlack) + || (preserveBlack != lastPreserveBlack) #endif // defined(cmsFLAGS_PRESERVEBLACK) - || (gamutColor != lastGamutColor) - ) { + || (gamutColor != lastGamutColor)) { gamutWarn = warn; free_transforms(); lastIntent = intent; @@ -1117,10 +1114,10 @@ cmsHTRANSFORM Inkscape::CMSSystem::getDisplayTransform() cmsHPROFILE hprof = getSystemProfileHandle(); cmsHPROFILE proofProf = hprof ? getProofProfileHandle() : nullptr; - if ( !transf ) { - if ( hprof && proofProf ) { + if (!transf) { + if (hprof && proofProf) { cmsUInt32Number dwFlags = cmsFLAGS_SOFTPROOFING; - if ( gamutWarn ) { + if (gamutWarn) { dwFlags |= cmsFLAGS_GAMUTCHECK; auto gamutColor_r = gamutColor.get_red_u(); @@ -1136,25 +1133,26 @@ cmsHTRANSFORM Inkscape::CMSSystem::getDisplayTransform() cmsSetAlarmCodes(newAlarmCodes); #endif } - if ( bpc ) { + if (bpc) { dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION; } #if defined(cmsFLAGS_PRESERVEBLACK) - if ( preserveBlack ) { + if (preserveBlack) { dwFlags |= cmsFLAGS_PRESERVEBLACK; } #endif // defined(cmsFLAGS_PRESERVEBLACK) - transf = cmsCreateProofingTransform( ColorProfileImpl::getSRGBProfile(), TYPE_BGRA_8, hprof, TYPE_BGRA_8, proofProf, intent, proofIntent, dwFlags ); - } else if ( hprof ) { - transf = cmsCreateTransform( ColorProfileImpl::getSRGBProfile(), TYPE_BGRA_8, hprof, TYPE_BGRA_8, intent, 0 ); + transf = cmsCreateProofingTransform(ColorProfileImpl::getSRGBProfile(), TYPE_BGRA_8, hprof, TYPE_BGRA_8, + proofProf, intent, proofIntent, dwFlags); + } else if (hprof) { + transf = cmsCreateTransform(ColorProfileImpl::getSRGBProfile(), TYPE_BGRA_8, hprof, TYPE_BGRA_8, intent, 0); } } return transf; } - -class MemProfile { +class MemProfile +{ public: MemProfile(); ~MemProfile(); @@ -1164,27 +1162,25 @@ public: cmsHTRANSFORM transf; }; -MemProfile::MemProfile() : - id(), - hprof(nullptr), - transf(nullptr) -{ -} +MemProfile::MemProfile() + : id() + , hprof(nullptr) + , transf(nullptr) +{} -MemProfile::~MemProfile() -= default; +MemProfile::~MemProfile() = default; static std::vector perMonitorProfiles; void free_transforms() { - if ( transf ) { + if (transf) { cmsDeleteTransform(transf); transf = nullptr; } - for ( auto profile : perMonitorProfiles ) { - if ( profile.transf ) { + for (auto profile : perMonitorProfiles) { + if (profile.transf) { cmsDeleteTransform(profile.transf); profile.transf = nullptr; } @@ -1195,33 +1191,32 @@ std::string Inkscape::CMSSystem::getDisplayId(int monitor) { std::string id; - if ( monitor >= 0 && monitor < static_cast(perMonitorProfiles.size()) ) { - MemProfile& item = perMonitorProfiles[monitor]; + if (monitor >= 0 && monitor < static_cast(perMonitorProfiles.size())) { + MemProfile &item = perMonitorProfiles[monitor]; id = item.id; } return id; } -Glib::ustring Inkscape::CMSSystem::setDisplayPer( gpointer buf, guint bufLen, int monitor ) +Glib::ustring Inkscape::CMSSystem::setDisplayPer(gpointer buf, guint bufLen, int monitor) { - while ( static_cast(perMonitorProfiles.size()) <= monitor ) { + while (static_cast(perMonitorProfiles.size()) <= monitor) { MemProfile tmp; perMonitorProfiles.push_back(tmp); } - MemProfile& item = perMonitorProfiles[monitor]; + MemProfile &item = perMonitorProfiles[monitor]; - if ( item.hprof ) { - cmsCloseProfile( item.hprof ); + if (item.hprof) { + cmsCloseProfile(item.hprof); item.hprof = nullptr; } Glib::ustring id; - if ( buf && bufLen ) { + if (buf && bufLen) { gsize len = bufLen; // len is an inout parameter - id = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_MD5, - reinterpret_cast(buf), len); + id = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_MD5, reinterpret_cast(buf), len); // Note: if this is not a valid profile, item.hprof will be set to null. item.hprof = cmsOpenProfileFromMem(buf, bufLen); @@ -1234,36 +1229,32 @@ Glib::ustring Inkscape::CMSSystem::setDisplayPer( gpointer buf, guint bufLen, in cmsHTRANSFORM Inkscape::CMSSystem::getDisplayPer(std::string const &id) { cmsHTRANSFORM result = nullptr; - if ( id.empty() ) { + if (id.empty()) { return nullptr; } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool found = false; - for ( auto it2 = perMonitorProfiles.begin(); it2 != perMonitorProfiles.end() && !found; ++it2 ) { - if ( id == it2->id ) { - MemProfile& item = *it2; + for (auto it2 = perMonitorProfiles.begin(); it2 != perMonitorProfiles.end() && !found; ++it2) { + if (id == it2->id) { + MemProfile &item = *it2; - bool warn = prefs->getBool( "/options/softproof/gamutwarn"); - int intent = prefs->getIntLimited( "/options/displayprofile/intent", 0, 0, 3 ); - int proofIntent = prefs->getIntLimited( "/options/softproof/intent", 0, 0, 3 ); - bool bpc = prefs->getBool( "/options/softproof/bpc"); + bool warn = prefs->getBool("/options/softproof/gamutwarn"); + int intent = prefs->getIntLimited("/options/displayprofile/intent", 0, 0, 3); + int proofIntent = prefs->getIntLimited("/options/softproof/intent", 0, 0, 3); + bool bpc = prefs->getBool("/options/softproof/bpc"); #if defined(cmsFLAGS_PRESERVEBLACK) - bool preserveBlack = prefs->getBool( "/options/softproof/preserveblack"); -#endif //defined(cmsFLAGS_PRESERVEBLACK) + bool preserveBlack = prefs->getBool("/options/softproof/preserveblack"); +#endif // defined(cmsFLAGS_PRESERVEBLACK) Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor"); - Gdk::RGBA gamutColor( colorStr.empty() ? "#808080" : colorStr ); + Gdk::RGBA gamutColor(colorStr.empty() ? "#808080" : colorStr); - if ( (warn != gamutWarn) - || (lastIntent != intent) - || (lastProofIntent != proofIntent) - || (bpc != lastBPC) + if ((warn != gamutWarn) || (lastIntent != intent) || (lastProofIntent != proofIntent) || (bpc != lastBPC) #if defined(cmsFLAGS_PRESERVEBLACK) - || (preserveBlack != lastPreserveBlack) + || (preserveBlack != lastPreserveBlack) #endif // defined(cmsFLAGS_PRESERVEBLACK) - || (gamutColor != lastGamutColor) - ) { + || (gamutColor != lastGamutColor)) { gamutWarn = warn; free_transforms(); lastIntent = intent; @@ -1278,10 +1269,10 @@ cmsHTRANSFORM Inkscape::CMSSystem::getDisplayPer(std::string const &id) // Fetch these now, as they might clear the transform as a side effect. cmsHPROFILE proofProf = item.hprof ? getProofProfileHandle() : nullptr; - if ( !item.transf ) { - if ( item.hprof && proofProf ) { + if (!item.transf) { + if (item.hprof && proofProf) { cmsUInt32Number dwFlags = cmsFLAGS_SOFTPROOFING; - if ( gamutWarn ) { + if (gamutWarn) { dwFlags |= cmsFLAGS_GAMUTCHECK; auto gamutColor_r = gamutColor.get_red_u(); auto gamutColor_g = gamutColor.get_green_u(); @@ -1296,17 +1287,20 @@ cmsHTRANSFORM Inkscape::CMSSystem::getDisplayPer(std::string const &id) cmsSetAlarmCodes(newAlarmCodes); #endif } - if ( bpc ) { + if (bpc) { dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION; } #if defined(cmsFLAGS_PRESERVEBLACK) - if ( preserveBlack ) { + if (preserveBlack) { dwFlags |= cmsFLAGS_PRESERVEBLACK; } #endif // defined(cmsFLAGS_PRESERVEBLACK) - item.transf = cmsCreateProofingTransform( ColorProfileImpl::getSRGBProfile(), TYPE_BGRA_8, item.hprof, TYPE_BGRA_8, proofProf, intent, proofIntent, dwFlags ); - } else if ( item.hprof ) { - item.transf = cmsCreateTransform( ColorProfileImpl::getSRGBProfile(), TYPE_BGRA_8, item.hprof, TYPE_BGRA_8, intent, 0 ); + item.transf = + cmsCreateProofingTransform(ColorProfileImpl::getSRGBProfile(), TYPE_BGRA_8, item.hprof, + TYPE_BGRA_8, proofProf, intent, proofIntent, dwFlags); + } else if (item.hprof) { + item.transf = cmsCreateTransform(ColorProfileImpl::getSRGBProfile(), TYPE_BGRA_8, item.hprof, + TYPE_BGRA_8, intent, 0); } } @@ -1318,8 +1312,6 @@ cmsHTRANSFORM Inkscape::CMSSystem::getDisplayPer(std::string const &id) return result; } - - #endif // defined(HAVE_LIBLCMS2) /* diff --git a/src/object/color-profile.h b/src/object/color-profile.h index 009b52f2a2e7dfa075ce5374d212b5e1f2b32c69..0928eaa6c41659655fc05f728356456112cad6ed 100644 --- a/src/object/color-profile.h +++ b/src/object/color-profile.h @@ -11,22 +11,22 @@ #define SEEN_COLOR_PROFILE_H #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif +#include #include #include -#include #include "cms-color-types.h" - #include "sp-object.h" struct SPColor; namespace Inkscape { -enum { +enum +{ RENDERING_INTENT_UNKNOWN = 0, RENDERING_INTENT_AUTO = 1, RENDERING_INTENT_PERCEPTUAL = 2, @@ -37,21 +37,22 @@ enum { class ColorProfileImpl; - /** * Color Profile. */ -class ColorProfile : public SPObject { +class ColorProfile : public SPObject +{ public: ColorProfile(); ~ColorProfile() override; bool operator<(ColorProfile const &other) const; - friend cmsHPROFILE colorprofile_get_handle( SPDocument*, unsigned int*, char const* ); + friend cmsHPROFILE colorprofile_get_handle(SPDocument *, unsigned int *, char const *); friend class CMSSystem; - class FilePlusHome { + class FilePlusHome + { public: FilePlusHome(Glib::ustring filename, bool isInHome); FilePlusHome(const FilePlusHome &filePlusHome); @@ -59,7 +60,8 @@ public: Glib::ustring filename; bool isInHome; }; - class FilePlusHomeAndName: public FilePlusHome { + class FilePlusHomeAndName : public FilePlusHome + { public: FilePlusHomeAndName(FilePlusHome filePlusHome, Glib::ustring name); bool operator<(FilePlusHomeAndName const &other) const; @@ -70,9 +72,9 @@ public: static std::set getProfileFiles(); static std::set getProfileFilesWithNames(); #if defined(HAVE_LIBLCMS2) - //icColorSpaceSignature getColorSpace() const; + // icColorSpaceSignature getColorSpace() const; ColorSpaceSig getColorSpace() const; - //icProfileClassSignature getProfileClass() const; + // icProfileClassSignature getProfileClass() const; ColorProfileClassSig getProfileClass() const; cmsHTRANSFORM getTransfToSRGB8(); cmsHTRANSFORM getTransfFromSRGB8(); @@ -81,28 +83,28 @@ public: #endif // defined(HAVE_LIBLCMS2) - char* href; - char* local; - char* name; - char* intentStr; + char *href; + char *local; + char *name; + char *intentStr; unsigned int rendering_intent; // FIXME: type the enum and hold that instead protected: ColorProfileImpl *impl; - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; void release() override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; } // namespace Inkscape //#define COLORPROFILE_TYPE (Inkscape::colorprofile_get_type()) -#define COLORPROFILE(obj) ((Inkscape::ColorProfile*)obj) -#define IS_COLORPROFILE(obj) (dynamic_cast((SPObject*)obj)) +#define COLORPROFILE(obj) ((Inkscape::ColorProfile *)obj) +#define IS_COLORPROFILE(obj) (dynamic_cast((SPObject *)obj)) #endif // !SEEN_COLOR_PROFILE_H diff --git a/src/object/filters/blend.cpp b/src/object/filters/blend.cpp index 49a7cd8abefb09d817cb438c12ff849fd8059b87..116133966d019bd1de9037b9568e8823bac71cfb 100644 --- a/src/object/filters/blend.cpp +++ b/src/object/filters/blend.cpp @@ -14,24 +14,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include - #include "blend.h" -#include "attributes.h" +#include +#include "attributes.h" #include "display/nr-filter.h" - #include "object/sp-filter.h" - #include "xml/repr.h" - SPFeBlend::SPFeBlend() - : SPFilterPrimitive(), blend_mode(SP_CSS_BLEND_NORMAL), - in2(Inkscape::Filters::NR_FILTER_SLOT_NOT_SET) -{ -} + : SPFilterPrimitive() + , blend_mode(SP_CSS_BLEND_NORMAL) + , in2(Inkscape::Filters::NR_FILTER_SLOT_NOT_SET) +{} SPFeBlend::~SPFeBlend() = default; @@ -40,7 +36,8 @@ SPFeBlend::~SPFeBlend() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeBlend::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPFeBlend::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPFilterPrimitive::build(document, repr); /*LOAD ATTRIBUTES FROM REPR HERE*/ @@ -50,8 +47,7 @@ void SPFeBlend::build(SPDocument *document, Inkscape::XML::Node *repr) { /* Unlike normal in, in2 is required attribute. Make sure, we can call * it by some name. */ if (this->in2 == Inkscape::Filters::NR_FILTER_SLOT_NOT_SET || - this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) - { + this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) { SPFilter *parent = SP_FILTER(this->parent); this->in2 = this->name_previous_out(); repr->setAttribute("in2", parent->name_for_image(this->in2)); @@ -61,13 +57,15 @@ void SPFeBlend::build(SPDocument *document, Inkscape::XML::Node *repr) { /** * Drops any allocated memory. */ -void SPFeBlend::release() { - SPFilterPrimitive::release(); +void SPFeBlend::release() +{ + SPFilterPrimitive::release(); } -static SPBlendMode sp_feBlend_readmode(gchar const *value) { +static SPBlendMode sp_feBlend_readmode(gchar const *value) +{ if (!value) { - return SP_CSS_BLEND_NORMAL; + return SP_CSS_BLEND_NORMAL; } switch (value[0]) { @@ -130,12 +128,13 @@ static SPBlendMode sp_feBlend_readmode(gchar const *value) { /** * Sets a specific value in the SPFeBlend. */ -void SPFeBlend::set(SPAttr key, gchar const *value) { +void SPFeBlend::set(SPAttr key, gchar const *value) +{ SPBlendMode mode; int input; - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ case SPAttr::MODE: mode = sp_feBlend_readmode(value); @@ -153,7 +152,7 @@ void SPFeBlend::set(SPAttr key, gchar const *value) { } break; default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -161,7 +160,8 @@ void SPFeBlend::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeBlend::update(SPCtx *ctx, guint flags) { +void SPFeBlend::update(SPCtx *ctx, guint flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { this->readAttr(SPAttr::MODE); this->readAttr(SPAttr::IN2); @@ -169,11 +169,10 @@ void SPFeBlend::update(SPCtx *ctx, guint flags) { /* Unlike normal in, in2 is required attribute. Make sure, we can call * it by some name. */ - /* This may not be true.... see issue at + /* This may not be true.... see issue at * http://www.w3.org/TR/filter-effects/#feBlendElement (but it doesn't hurt). */ if (this->in2 == Inkscape::Filters::NR_FILTER_SLOT_NOT_SET || - this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) - { + this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) { SPFilter *parent = SP_FILTER(this->parent); this->in2 = this->name_previous_out(); @@ -187,7 +186,8 @@ void SPFeBlend::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeBlend::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeBlend::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ SPFilter *parent = SP_FILTER(this->parent); if (!repr) { @@ -196,17 +196,16 @@ Inkscape::XML::Node* SPFeBlend::write(Inkscape::XML::Document *doc, Inkscape::XM gchar const *in2_name = parent->name_for_image(this->in2); - if( !in2_name ) { - + if (!in2_name) { // This code is very similar to name_previous_out() SPObject *i = parent->firstChild(); // Find previous filter primitive while (i && i->getNext() != this) { - i = i->getNext(); + i = i->getNext(); } - if( i ) { + if (i) { SPFilterPrimitive *i_prim = SP_FILTER_PRIMITIVE(i); in2_name = parent->name_for_image(i_prim->image_out); } @@ -219,40 +218,56 @@ Inkscape::XML::Node* SPFeBlend::write(Inkscape::XML::Document *doc, Inkscape::XM } char const *mode; - switch(this->blend_mode) { + switch (this->blend_mode) { case SP_CSS_BLEND_NORMAL: - mode = "normal"; break; + mode = "normal"; + break; case SP_CSS_BLEND_MULTIPLY: - mode = "multiply"; break; + mode = "multiply"; + break; case SP_CSS_BLEND_SCREEN: - mode = "screen"; break; + mode = "screen"; + break; case SP_CSS_BLEND_DARKEN: - mode = "darken"; break; + mode = "darken"; + break; case SP_CSS_BLEND_LIGHTEN: - mode = "lighten"; break; + mode = "lighten"; + break; // New case SP_CSS_BLEND_OVERLAY: - mode = "overlay"; break; + mode = "overlay"; + break; case SP_CSS_BLEND_COLORDODGE: - mode = "color-dodge"; break; + mode = "color-dodge"; + break; case SP_CSS_BLEND_COLORBURN: - mode = "color-burn"; break; + mode = "color-burn"; + break; case SP_CSS_BLEND_HARDLIGHT: - mode = "hard-light"; break; + mode = "hard-light"; + break; case SP_CSS_BLEND_SOFTLIGHT: - mode = "soft-light"; break; + mode = "soft-light"; + break; case SP_CSS_BLEND_DIFFERENCE: - mode = "difference"; break; + mode = "difference"; + break; case SP_CSS_BLEND_EXCLUSION: - mode = "exclusion"; break; + mode = "exclusion"; + break; case SP_CSS_BLEND_HUE: - mode = "hue"; break; + mode = "hue"; + break; case SP_CSS_BLEND_SATURATION: - mode = "saturation"; break; + mode = "saturation"; + break; case SP_CSS_BLEND_COLOR: - mode = "color"; break; + mode = "color"; + break; case SP_CSS_BLEND_LUMINOSITY: - mode = "luminosity"; break; + mode = "luminosity"; + break; default: mode = nullptr; } @@ -264,12 +279,13 @@ Inkscape::XML::Node* SPFeBlend::write(Inkscape::XML::Document *doc, Inkscape::XM return repr; } -void SPFeBlend::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeBlend::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_BLEND); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterBlend *nr_blend = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterBlend *nr_blend = dynamic_cast(nr_primitive); g_assert(nr_blend != nullptr); this->renderer_common(nr_primitive); diff --git a/src/object/filters/blend.h b/src/object/filters/blend.h index 7eee98636ac2e6760f3ba81ba037ad77171deccb..cc5f7ad429388dc2c97f2e8078bb4bd4dfe871d9 100644 --- a/src/object/filters/blend.h +++ b/src/object/filters/blend.h @@ -14,31 +14,32 @@ #ifndef SP_FEBLEND_H_SEEN #define SP_FEBLEND_H_SEEN -#include "sp-filter-primitive.h" #include "display/nr-filter-blend.h" +#include "sp-filter-primitive.h" -#define SP_FEBLEND(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FEBLEND(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FEBLEND(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FEBLEND(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPFeBlend : public SPFilterPrimitive { +class SPFeBlend : public SPFilterPrimitive +{ public: - SPFeBlend(); - ~SPFeBlend() override; + SPFeBlend(); + ~SPFeBlend() override; SPBlendMode blend_mode; int in2; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FEBLEND_H_SEEN */ diff --git a/src/object/filters/colormatrix.cpp b/src/object/filters/colormatrix.cpp index 5550ec0d2c8a7bed7a16ac9e1182ab405fcbcad7..544fcdc284605c75b4527869383241ea01e605e9 100644 --- a/src/object/filters/colormatrix.cpp +++ b/src/object/filters/colormatrix.cpp @@ -15,20 +15,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "colormatrix.h" + #include #include "attributes.h" +#include "display/nr-filter.h" +#include "helper-fns.h" #include "svg/svg.h" -#include "colormatrix.h" #include "xml/repr.h" -#include "helper-fns.h" - -#include "display/nr-filter.h" -SPFeColorMatrix::SPFeColorMatrix() - : SPFilterPrimitive(), type(Inkscape::Filters::COLORMATRIX_MATRIX), value(0) -{ -} +SPFeColorMatrix::SPFeColorMatrix() + : SPFilterPrimitive() + , type(Inkscape::Filters::COLORMATRIX_MATRIX) + , value(0) +{} SPFeColorMatrix::~SPFeColorMatrix() = default; @@ -37,69 +38,77 @@ SPFeColorMatrix::~SPFeColorMatrix() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeColorMatrix::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); +void SPFeColorMatrix::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); - /*LOAD ATTRIBUTES FROM REPR HERE*/ - this->readAttr(SPAttr::TYPE); - this->readAttr(SPAttr::VALUES); + /*LOAD ATTRIBUTES FROM REPR HERE*/ + this->readAttr(SPAttr::TYPE); + this->readAttr(SPAttr::VALUES); } /** * Drops any allocated memory. */ -void SPFeColorMatrix::release() { - SPFilterPrimitive::release(); +void SPFeColorMatrix::release() +{ + SPFilterPrimitive::release(); } -static Inkscape::Filters::FilterColorMatrixType sp_feColorMatrix_read_type(gchar const *value){ +static Inkscape::Filters::FilterColorMatrixType sp_feColorMatrix_read_type(gchar const *value) +{ if (!value) { - return Inkscape::Filters::COLORMATRIX_MATRIX; //matrix is default + return Inkscape::Filters::COLORMATRIX_MATRIX; // matrix is default } - switch(value[0]){ + switch (value[0]) { case 'm': - if (strcmp(value, "matrix") == 0) return Inkscape::Filters::COLORMATRIX_MATRIX; + if (strcmp(value, "matrix") == 0) + return Inkscape::Filters::COLORMATRIX_MATRIX; break; case 's': - if (strcmp(value, "saturate") == 0) return Inkscape::Filters::COLORMATRIX_SATURATE; + if (strcmp(value, "saturate") == 0) + return Inkscape::Filters::COLORMATRIX_SATURATE; break; case 'h': - if (strcmp(value, "hueRotate") == 0) return Inkscape::Filters::COLORMATRIX_HUEROTATE; + if (strcmp(value, "hueRotate") == 0) + return Inkscape::Filters::COLORMATRIX_HUEROTATE; break; case 'l': - if (strcmp(value, "luminanceToAlpha") == 0) return Inkscape::Filters::COLORMATRIX_LUMINANCETOALPHA; + if (strcmp(value, "luminanceToAlpha") == 0) + return Inkscape::Filters::COLORMATRIX_LUMINANCETOALPHA; break; } - return Inkscape::Filters::COLORMATRIX_MATRIX; //matrix is default + return Inkscape::Filters::COLORMATRIX_MATRIX; // matrix is default } /** * Sets a specific value in the SPFeColorMatrix. */ -void SPFeColorMatrix::set(SPAttr key, gchar const *str) { +void SPFeColorMatrix::set(SPAttr key, gchar const *str) +{ Inkscape::Filters::FilterColorMatrixType read_type; - /*DEAL WITH SETTING ATTRIBUTES HERE*/ - switch(key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ + switch (key) { case SPAttr::TYPE: read_type = sp_feColorMatrix_read_type(str); - if (this->type != read_type){ + if (this->type != read_type) { this->type = read_type; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; case SPAttr::VALUES: - if (str){ + if (str) { this->values = helperfns_read_vector(str); this->value = helperfns_read_number(str, HELPERFNS_NO_WARNING); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; default: - SPFilterPrimitive::set(key, str); + SPFilterPrimitive::set(key, str); break; } } @@ -107,21 +116,20 @@ void SPFeColorMatrix::set(SPAttr key, gchar const *str) { /** * Receives update notifications. */ -void SPFeColorMatrix::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - +void SPFeColorMatrix::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something to trigger redisplay, updates? */ - } - SPFilterPrimitive::update(ctx, flags); + SPFilterPrimitive::update(ctx, flags); } /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeColorMatrix::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeColorMatrix::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values into it */ if (!repr) { @@ -133,12 +141,14 @@ Inkscape::XML::Node* SPFeColorMatrix::write(Inkscape::XML::Document *doc, Inksca return repr; } -void SPFeColorMatrix::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeColorMatrix::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_COLORMATRIX); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterColorMatrix *nr_colormatrix = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterColorMatrix *nr_colormatrix = + dynamic_cast(nr_primitive); g_assert(nr_colormatrix != nullptr); this->renderer_common(nr_primitive); diff --git a/src/object/filters/colormatrix.h b/src/object/filters/colormatrix.h index a0256a8a307722ac5127c5ea8b252a7f07a9cb07..aed20f9d434d2c06ecaea8032067ea8663a92a3c 100644 --- a/src/object/filters/colormatrix.h +++ b/src/object/filters/colormatrix.h @@ -13,32 +13,34 @@ #define SP_FECOLORMATRIX_H_SEEN #include -#include "sp-filter-primitive.h" + #include "display/nr-filter-colormatrix.h" +#include "sp-filter-primitive.h" -#define SP_FECOLORMATRIX(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FECOLORMATRIX(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FECOLORMATRIX(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FECOLORMATRIX(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPFeColorMatrix : public SPFilterPrimitive { +class SPFeColorMatrix : public SPFilterPrimitive +{ public: - SPFeColorMatrix(); - ~SPFeColorMatrix() override; + SPFeColorMatrix(); + ~SPFeColorMatrix() override; Inkscape::Filters::FilterColorMatrixType type; gdouble value; std::vector values; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FECOLORMATRIX_H_SEEN */ diff --git a/src/object/filters/componenttransfer-funcnode.cpp b/src/object/filters/componenttransfer-funcnode.cpp index d73fbee6fd3e1fcdbcbe6b28ddb40a1579aaeb90..8ced67cbdb49baf4f1f7305abdfaa2bc120a3167 100644 --- a/src/object/filters/componenttransfer-funcnode.cpp +++ b/src/object/filters/componenttransfer-funcnode.cpp @@ -14,20 +14,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "componenttransfer-funcnode.h" + #include #include "attributes.h" -#include "document.h" #include "componenttransfer.h" -#include "componenttransfer-funcnode.h" -#include "xml/repr.h" +#include "document.h" #include "helper-fns.h" +#include "xml/repr.h" /* FeFuncNode class */ SPFeFuncNode::SPFeFuncNode(SPFeFuncNode::Channel channel) - : SPObject(), type(Inkscape::Filters::COMPONENTTRANSFER_TYPE_IDENTITY), - slope(1), intercept(0), amplitude(1), exponent(1), offset(0), channel(channel) { -} + : SPObject() + , type(Inkscape::Filters::COMPONENTTRANSFER_TYPE_IDENTITY) + , slope(1) + , intercept(0) + , amplitude(1) + , exponent(1) + , offset(0) + , channel(channel) +{} SPFeFuncNode::~SPFeFuncNode() = default; @@ -36,10 +43,11 @@ SPFeFuncNode::~SPFeFuncNode() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeFuncNode::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPObject::build(document, repr); +void SPFeFuncNode::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPObject::build(document, repr); - //Read values of key attributes from XML nodes into object. + // Read values of key attributes from XML nodes into object. this->readAttr(SPAttr::TYPE); this->readAttr(SPAttr::TABLEVALUES); this->readAttr(SPAttr::SLOPE); @@ -48,77 +56,79 @@ void SPFeFuncNode::build(SPDocument *document, Inkscape::XML::Node *repr) { this->readAttr(SPAttr::EXPONENT); this->readAttr(SPAttr::OFFSET); - -//is this necessary? - document->addResource("fefuncnode", this); //maybe feFuncR, fefuncG, feFuncB and fefuncA ? + // is this necessary? + document->addResource("fefuncnode", this); // maybe feFuncR, fefuncG, feFuncB and fefuncA ? } /** * Drops any allocated memory. */ -void SPFeFuncNode::release() { - if ( this->document ) { +void SPFeFuncNode::release() +{ + if (this->document) { // Unregister ourselves this->document->removeResource("fefuncnode", this); } -//TODO: release resources here + // TODO: release resources here } -static Inkscape::Filters::FilterComponentTransferType sp_feComponenttransfer_read_type(gchar const *value){ +static Inkscape::Filters::FilterComponentTransferType sp_feComponenttransfer_read_type(gchar const *value) +{ if (!value) { - return Inkscape::Filters::COMPONENTTRANSFER_TYPE_ERROR; //type attribute is REQUIRED. + return Inkscape::Filters::COMPONENTTRANSFER_TYPE_ERROR; // type attribute is REQUIRED. } - switch(value[0]){ + switch (value[0]) { case 'i': if (strncmp(value, "identity", 8) == 0) { - return Inkscape::Filters::COMPONENTTRANSFER_TYPE_IDENTITY; + return Inkscape::Filters::COMPONENTTRANSFER_TYPE_IDENTITY; } break; case 't': if (strncmp(value, "table", 5) == 0) { - return Inkscape::Filters::COMPONENTTRANSFER_TYPE_TABLE; + return Inkscape::Filters::COMPONENTTRANSFER_TYPE_TABLE; } break; case 'd': if (strncmp(value, "discrete", 8) == 0) { - return Inkscape::Filters::COMPONENTTRANSFER_TYPE_DISCRETE; + return Inkscape::Filters::COMPONENTTRANSFER_TYPE_DISCRETE; } break; case 'l': if (strncmp(value, "linear", 6) == 0) { - return Inkscape::Filters::COMPONENTTRANSFER_TYPE_LINEAR; + return Inkscape::Filters::COMPONENTTRANSFER_TYPE_LINEAR; } break; case 'g': if (strncmp(value, "gamma", 5) == 0) { - return Inkscape::Filters::COMPONENTTRANSFER_TYPE_GAMMA; + return Inkscape::Filters::COMPONENTTRANSFER_TYPE_GAMMA; } break; } - return Inkscape::Filters::COMPONENTTRANSFER_TYPE_ERROR; //type attribute is REQUIRED. + return Inkscape::Filters::COMPONENTTRANSFER_TYPE_ERROR; // type attribute is REQUIRED. } /** * Sets a specific value in the SPFeFuncNode. */ -void SPFeFuncNode::set(SPAttr key, gchar const *value) { +void SPFeFuncNode::set(SPAttr key, gchar const *value) +{ Inkscape::Filters::FilterComponentTransferType type; double read_num; - switch(key) { + switch (key) { case SPAttr::TYPE: type = sp_feComponenttransfer_read_type(value); - if(type != this->type) { + if (type != this->type) { this->type = type; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; case SPAttr::TABLEVALUES: - if (value){ + if (value) { this->tableValues = helperfns_read_vector(value); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } @@ -164,7 +174,7 @@ void SPFeFuncNode::set(SPAttr key, gchar const *value) { } break; default: - SPObject::set(key, value); + SPObject::set(key, value); break; } } @@ -172,7 +182,8 @@ void SPFeFuncNode::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeFuncNode::update(SPCtx *ctx, guint flags) { +void SPFeFuncNode::update(SPCtx *ctx, guint flags) +{ std::cout << "SPFeFuncNode::update" << std::endl; if (flags & SP_OBJECT_MODIFIED_FLAG) { this->readAttr(SPAttr::TYPE); @@ -190,7 +201,8 @@ void SPFeFuncNode::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeFuncNode::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeFuncNode::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ std::cout << "SPFeFuncNode::write" << std::endl; if (!repr) { repr = this->getRepr()->duplicate(doc); diff --git a/src/object/filters/componenttransfer-funcnode.h b/src/object/filters/componenttransfer-funcnode.h index d16aacc96e61631c2b8066821af01435532515d3..2b4a1f114eabf3dcc393b0d752ac40d2d31e7dfd 100644 --- a/src/object/filters/componenttransfer-funcnode.h +++ b/src/object/filters/componenttransfer-funcnode.h @@ -19,16 +19,21 @@ #include "../sp-object.h" #include "display/nr-filter-component-transfer.h" -#define SP_FEFUNCNODE(obj) (dynamic_cast((SPObject*)obj)) +#define SP_FEFUNCNODE(obj) (dynamic_cast((SPObject *)obj)) -class SPFeFuncNode : public SPObject { +class SPFeFuncNode : public SPObject +{ public: - enum Channel { - R, G, B, A + enum Channel + { + R, + G, + B, + A }; - SPFeFuncNode(Channel channel); - ~SPFeFuncNode() override; + SPFeFuncNode(Channel channel); + ~SPFeFuncNode() override; Inkscape::Filters::FilterComponentTransferType type; std::vector tableValues; @@ -40,14 +45,14 @@ public: Channel channel; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; }; #endif /* !SP_FECOMPONENTTRANSFER_FUNCNODE_H_SEEN */ diff --git a/src/object/filters/componenttransfer.cpp b/src/object/filters/componenttransfer.cpp index b194902d187a1bdb9419d3bac674ccd5ef64f474..c0e624daca755741f577ca2b87fb44e683c4874b 100644 --- a/src/object/filters/componenttransfer.cpp +++ b/src/object/filters/componenttransfer.cpp @@ -17,17 +17,15 @@ #include "document.h" // In same directory -#include "componenttransfer.h" #include "componenttransfer-funcnode.h" - +#include "componenttransfer.h" #include "display/nr-filter.h" - #include "xml/repr.h" SPFeComponentTransfer::SPFeComponentTransfer() - : SPFilterPrimitive(), renderer(nullptr) -{ -} + : SPFilterPrimitive() + , renderer(nullptr) +{} SPFeComponentTransfer::~SPFeComponentTransfer() = default; @@ -36,57 +34,58 @@ SPFeComponentTransfer::~SPFeComponentTransfer() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeComponentTransfer::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); +void SPFeComponentTransfer::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); - /*LOAD ATTRIBUTES FROM REPR HERE*/ + /*LOAD ATTRIBUTES FROM REPR HERE*/ - //do we need this? - //document->addResource("feComponentTransfer", object); + // do we need this? + // document->addResource("feComponentTransfer", object); } static void sp_feComponentTransfer_children_modified(SPFeComponentTransfer *sp_componenttransfer) { if (sp_componenttransfer->renderer) { bool set[4] = {false, false, false, false}; - for(auto& node: sp_componenttransfer->children) { + for (auto &node : sp_componenttransfer->children) { int i = 4; SPFeFuncNode *funcNode = SP_FEFUNCNODE(&node); - if(!funcNode) { - continue; - } + if (!funcNode) { + continue; + } switch (funcNode->channel) { - case SPFeFuncNode::R: - i = 0; - break; - case SPFeFuncNode::G: - i = 1; - break; - case SPFeFuncNode::B: - i = 2; - break; - case SPFeFuncNode::A: - i = 3; - break; + case SPFeFuncNode::R: + i = 0; + break; + case SPFeFuncNode::G: + i = 1; + break; + case SPFeFuncNode::B: + i = 2; + break; + case SPFeFuncNode::A: + i = 3; + break; } if (i == 4) { g_warning("Unrecognized channel for component transfer."); break; } - sp_componenttransfer->renderer->type[i] = ((SPFeFuncNode *) &node)->type; - sp_componenttransfer->renderer->tableValues[i] = ((SPFeFuncNode *) &node)->tableValues; - sp_componenttransfer->renderer->slope[i] = ((SPFeFuncNode *) &node)->slope; - sp_componenttransfer->renderer->intercept[i] = ((SPFeFuncNode *) &node)->intercept; - sp_componenttransfer->renderer->amplitude[i] = ((SPFeFuncNode *) &node)->amplitude; - sp_componenttransfer->renderer->exponent[i] = ((SPFeFuncNode *) &node)->exponent; - sp_componenttransfer->renderer->offset[i] = ((SPFeFuncNode *) &node)->offset; + sp_componenttransfer->renderer->type[i] = ((SPFeFuncNode *)&node)->type; + sp_componenttransfer->renderer->tableValues[i] = ((SPFeFuncNode *)&node)->tableValues; + sp_componenttransfer->renderer->slope[i] = ((SPFeFuncNode *)&node)->slope; + sp_componenttransfer->renderer->intercept[i] = ((SPFeFuncNode *)&node)->intercept; + sp_componenttransfer->renderer->amplitude[i] = ((SPFeFuncNode *)&node)->amplitude; + sp_componenttransfer->renderer->exponent[i] = ((SPFeFuncNode *)&node)->exponent; + sp_componenttransfer->renderer->offset[i] = ((SPFeFuncNode *)&node)->offset; set[i] = true; } // Set any types not explicitly set to the identity transform - for(int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { if (!set[i]) { sp_componenttransfer->renderer->type[i] = Inkscape::Filters::COMPONENTTRANSFER_TYPE_IDENTITY; } @@ -97,7 +96,8 @@ static void sp_feComponentTransfer_children_modified(SPFeComponentTransfer *sp_c /** * Callback for child_added event. */ -void SPFeComponentTransfer::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { +void SPFeComponentTransfer::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ SPFilterPrimitive::child_added(child, ref); sp_feComponentTransfer_children_modified(this); @@ -107,7 +107,8 @@ void SPFeComponentTransfer::child_added(Inkscape::XML::Node *child, Inkscape::XM /** * Callback for remove_child event. */ -void SPFeComponentTransfer::remove_child(Inkscape::XML::Node *child) { +void SPFeComponentTransfer::remove_child(Inkscape::XML::Node *child) +{ SPFilterPrimitive::remove_child(child); sp_feComponentTransfer_children_modified(this); @@ -117,18 +118,20 @@ void SPFeComponentTransfer::remove_child(Inkscape::XML::Node *child) { /** * Drops any allocated memory. */ -void SPFeComponentTransfer::release() { - SPFilterPrimitive::release(); +void SPFeComponentTransfer::release() +{ + SPFilterPrimitive::release(); } /** * Sets a specific value in the SPFeComponentTransfer. */ -void SPFeComponentTransfer::set(SPAttr key, gchar const *value) { - switch(key) { +void SPFeComponentTransfer::set(SPAttr key, gchar const *value) +{ + switch (key) { /*DEAL WITH SETTING ATTRIBUTES HERE*/ default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -136,12 +139,10 @@ void SPFeComponentTransfer::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeComponentTransfer::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - +void SPFeComponentTransfer::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something to trigger redisplay, updates? */ - } SPFilterPrimitive::update(ctx, flags); @@ -150,7 +151,8 @@ void SPFeComponentTransfer::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeComponentTransfer::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeComponentTransfer::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values into it */ if (!repr) { @@ -162,19 +164,20 @@ Inkscape::XML::Node* SPFeComponentTransfer::write(Inkscape::XML::Document *doc, return repr; } -void SPFeComponentTransfer::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeComponentTransfer::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_COMPONENTTRANSFER); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterComponentTransfer *nr_componenttransfer = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterComponentTransfer *nr_componenttransfer = + dynamic_cast(nr_primitive); g_assert(nr_componenttransfer != nullptr); this->renderer = nr_componenttransfer; this->renderer_common(nr_primitive); - - sp_feComponentTransfer_children_modified(this); //do we need it?! + sp_feComponentTransfer_children_modified(this); // do we need it?! } /* diff --git a/src/object/filters/componenttransfer.h b/src/object/filters/componenttransfer.h index b0930a445e6e45b7dd2785e5ad4bdd8e02d4f8ed..c718e78d92401adc942b614800e65d344537d219 100644 --- a/src/object/filters/componenttransfer.h +++ b/src/object/filters/componenttransfer.h @@ -14,35 +14,37 @@ #include "sp-filter-primitive.h" -#define SP_FECOMPONENTTRANSFER(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FECOMPONENTTRANSFER(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FECOMPONENTTRANSFER(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FECOMPONENTTRANSFER(obj) (dynamic_cast((SPObject *)obj) != NULL) namespace Inkscape { namespace Filters { class FilterComponentTransfer; -} } +} +} // namespace Inkscape -class SPFeComponentTransfer : public SPFilterPrimitive { +class SPFeComponentTransfer : public SPFilterPrimitive +{ public: - SPFeComponentTransfer(); - ~SPFeComponentTransfer() override; + SPFeComponentTransfer(); + ~SPFeComponentTransfer() override; Inkscape::Filters::FilterComponentTransfer *renderer; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FECOMPONENTTRANSFER_H_SEEN */ diff --git a/src/object/filters/composite.cpp b/src/object/filters/composite.cpp index bd315aa76cfe2a1121a3eb9ab0217e08a6a5476d..c8b8be1241fac4a6c623349307b7c9e581127fa7 100644 --- a/src/object/filters/composite.cpp +++ b/src/object/filters/composite.cpp @@ -16,22 +16,22 @@ #include "composite.h" #include "attributes.h" -#include "helper-fns.h" - -#include "display/nr-filter.h" #include "display/nr-filter-composite.h" - +#include "display/nr-filter.h" +#include "helper-fns.h" #include "object/sp-filter.h" - #include "svg/svg.h" - #include "xml/repr.h" SPFeComposite::SPFeComposite() - : SPFilterPrimitive(), composite_operator(COMPOSITE_DEFAULT), - k1(0), k2(0), k3(0), k4(0), in2(Inkscape::Filters::NR_FILTER_SLOT_NOT_SET) -{ -} + : SPFilterPrimitive() + , composite_operator(COMPOSITE_DEFAULT) + , k1(0) + , k2(0) + , k3(0) + , k4(0) + , in2(Inkscape::Filters::NR_FILTER_SLOT_NOT_SET) +{} SPFeComposite::~SPFeComposite() = default; @@ -40,74 +40,75 @@ SPFeComposite::~SPFeComposite() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeComposite::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); - - this->readAttr(SPAttr::OPERATOR); - - if (this->composite_operator == COMPOSITE_ARITHMETIC) { - this->readAttr(SPAttr::K1); - this->readAttr(SPAttr::K2); - this->readAttr(SPAttr::K3); - this->readAttr(SPAttr::K4); - } - - this->readAttr(SPAttr::IN2); - - /* Unlike normal in, in2 is required attribute. Make sure, we can call - * it by some name. */ - if (this->in2 == Inkscape::Filters::NR_FILTER_SLOT_NOT_SET || - this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) - { - SPFilter *parent = SP_FILTER(this->parent); - this->in2 = this->name_previous_out(); - repr->setAttribute("in2", parent->name_for_image(this->in2)); - } +void SPFeComposite::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); + + this->readAttr(SPAttr::OPERATOR); + + if (this->composite_operator == COMPOSITE_ARITHMETIC) { + this->readAttr(SPAttr::K1); + this->readAttr(SPAttr::K2); + this->readAttr(SPAttr::K3); + this->readAttr(SPAttr::K4); + } + + this->readAttr(SPAttr::IN2); + + /* Unlike normal in, in2 is required attribute. Make sure, we can call + * it by some name. */ + if (this->in2 == Inkscape::Filters::NR_FILTER_SLOT_NOT_SET || + this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) { + SPFilter *parent = SP_FILTER(this->parent); + this->in2 = this->name_previous_out(); + repr->setAttribute("in2", parent->name_for_image(this->in2)); + } } /** * Drops any allocated memory. */ -void SPFeComposite::release() { - SPFilterPrimitive::release(); +void SPFeComposite::release() +{ + SPFilterPrimitive::release(); } -static FeCompositeOperator -sp_feComposite_read_operator(gchar const *value) { +static FeCompositeOperator sp_feComposite_read_operator(gchar const *value) +{ if (!value) { - return COMPOSITE_DEFAULT; + return COMPOSITE_DEFAULT; } if (strcmp(value, "over") == 0) { - return COMPOSITE_OVER; + return COMPOSITE_OVER; } else if (strcmp(value, "in") == 0) { - return COMPOSITE_IN; + return COMPOSITE_IN; } else if (strcmp(value, "out") == 0) { - return COMPOSITE_OUT; + return COMPOSITE_OUT; } else if (strcmp(value, "atop") == 0) { - return COMPOSITE_ATOP; + return COMPOSITE_ATOP; } else if (strcmp(value, "xor") == 0) { - return COMPOSITE_XOR; + return COMPOSITE_XOR; } else if (strcmp(value, "arithmetic") == 0) { - return COMPOSITE_ARITHMETIC; + return COMPOSITE_ARITHMETIC; } #ifdef WITH_CSSCOMPOSITE - else if (strcmp(value, "clear") == 0) { - return COMPOSITE_CLEAR; + else if (strcmp(value, "clear") == 0) { + return COMPOSITE_CLEAR; } else if (strcmp(value, "copy") == 0) { - return COMPOSITE_COPY; + return COMPOSITE_COPY; } else if (strcmp(value, "destination") == 0) { - return COMPOSITE_DESTINATION; + return COMPOSITE_DESTINATION; } else if (strcmp(value, "destination-over") == 0) { - return COMPOSITE_DESTINATION_OVER; + return COMPOSITE_DESTINATION_OVER; } else if (strcmp(value, "destination-in") == 0) { - return COMPOSITE_DESTINATION_IN; + return COMPOSITE_DESTINATION_IN; } else if (strcmp(value, "destination-out") == 0) { - return COMPOSITE_DESTINATION_OUT; + return COMPOSITE_DESTINATION_OUT; } else if (strcmp(value, "destination-atop") == 0) { - return COMPOSITE_DESTINATION_ATOP; + return COMPOSITE_DESTINATION_ATOP; } else if (strcmp(value, "lighter") == 0) { - return COMPOSITE_LIGHTER; + return COMPOSITE_LIGHTER; } #endif std::cout << "Inkscape::Filters::FilterCompositeOperator: Unimplemented operator: " << value << std::endl; @@ -118,13 +119,14 @@ sp_feComposite_read_operator(gchar const *value) { /** * Sets a specific value in the SPFeComposite. */ -void SPFeComposite::set(SPAttr key, gchar const *value) { +void SPFeComposite::set(SPAttr key, gchar const *value) +{ int input; FeCompositeOperator op; double k_n; - - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ + + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ case SPAttr::OPERATOR: op = sp_feComposite_read_operator(value); if (op != this->composite_operator) { @@ -178,7 +180,7 @@ void SPFeComposite::set(SPAttr key, gchar const *value) { break; default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -186,25 +188,22 @@ void SPFeComposite::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeComposite::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - +void SPFeComposite::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something to trigger redisplay, updates? */ - } /* Unlike normal in, in2 is required attribute. Make sure, we can call * it by some name. */ - /* This may not be true.... see issue at + /* This may not be true.... see issue at * http://www.w3.org/TR/filter-effects/#feBlendElement (but it doesn't hurt). */ if (this->in2 == Inkscape::Filters::NR_FILTER_SLOT_NOT_SET || - this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) - { + this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) { SPFilter *parent = SP_FILTER(this->parent); this->in2 = this->name_previous_out(); - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. this->setAttribute("in2", parent->name_for_image(this->in2)); } @@ -214,7 +213,8 @@ void SPFeComposite::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeComposite::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeComposite::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ SPFilter *parent = SP_FILTER(this->parent); if (!repr) { @@ -223,17 +223,16 @@ Inkscape::XML::Node* SPFeComposite::write(Inkscape::XML::Document *doc, Inkscape gchar const *in2_name = parent->name_for_image(this->in2); - if( !in2_name ) { - + if (!in2_name) { // This code is very similar to name_previous_out() SPObject *i = parent->firstChild(); // Find previous filter primitive while (i && i->getNext() != this) { - i = i->getNext(); + i = i->getNext(); } - if( i ) { + if (i) { SPFilterPrimitive *i_prim = SP_FILTER_PRIMITIVE(i); in2_name = parent->name_for_image(i_prim->image_out); } @@ -249,35 +248,49 @@ Inkscape::XML::Node* SPFeComposite::write(Inkscape::XML::Document *doc, Inkscape switch (this->composite_operator) { case COMPOSITE_OVER: - comp_op = "over"; break; + comp_op = "over"; + break; case COMPOSITE_IN: - comp_op = "in"; break; + comp_op = "in"; + break; case COMPOSITE_OUT: - comp_op = "out"; break; + comp_op = "out"; + break; case COMPOSITE_ATOP: - comp_op = "atop"; break; + comp_op = "atop"; + break; case COMPOSITE_XOR: - comp_op = "xor"; break; + comp_op = "xor"; + break; case COMPOSITE_ARITHMETIC: - comp_op = "arithmetic"; break; + comp_op = "arithmetic"; + break; #ifdef WITH_CSSCOMPOSITE // New CSS operators case COMPOSITE_CLEAR: - comp_op = "clear"; break; + comp_op = "clear"; + break; case COMPOSITE_COPY: - comp_op = "copy"; break; + comp_op = "copy"; + break; case COMPOSITE_DESTINATION: - comp_op = "destination"; break; + comp_op = "destination"; + break; case COMPOSITE_DESTINATION_OVER: - comp_op = "destination-over"; break; + comp_op = "destination-over"; + break; case COMPOSITE_DESTINATION_IN: - comp_op = "destination-in"; break; + comp_op = "destination-in"; + break; case COMPOSITE_DESTINATION_OUT: - comp_op = "destination-out"; break; + comp_op = "destination-out"; + break; case COMPOSITE_DESTINATION_ATOP: - comp_op = "destination-atop"; break; + comp_op = "destination-atop"; + break; case COMPOSITE_LIGHTER: - comp_op = "lighter"; break; + comp_op = "lighter"; + break; #endif default: comp_op = nullptr; @@ -302,12 +315,13 @@ Inkscape::XML::Node* SPFeComposite::write(Inkscape::XML::Document *doc, Inkscape return repr; } -void SPFeComposite::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeComposite::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_COMPOSITE); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterComposite *nr_composite = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterComposite *nr_composite = dynamic_cast(nr_primitive); g_assert(nr_composite != nullptr); this->renderer_common(nr_primitive); @@ -316,8 +330,7 @@ void SPFeComposite::build_renderer(Inkscape::Filters::Filter* filter) { nr_composite->set_input(1, this->in2); if (this->composite_operator == COMPOSITE_ARITHMETIC) { - nr_composite->set_arithmetic(this->k1, this->k2, - this->k3, this->k4); + nr_composite->set_arithmetic(this->k1, this->k2, this->k3, this->k4); } } diff --git a/src/object/filters/composite.h b/src/object/filters/composite.h index 282dfb88dec72d675dd523f268d80c457a7dcc0f..43cc20f915910f0d909e61d70d5eddea696e9743 100644 --- a/src/object/filters/composite.h +++ b/src/object/filters/composite.h @@ -14,53 +14,55 @@ #include "sp-filter-primitive.h" -#define SP_FECOMPOSITE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FECOMPOSITE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FECOMPOSITE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FECOMPOSITE(obj) (dynamic_cast((SPObject *)obj) != NULL) -enum FeCompositeOperator { +enum FeCompositeOperator +{ // Default value is 'over', but let's distinquish specifying the // default and implicitly using the default COMPOSITE_DEFAULT, - COMPOSITE_OVER, /* Source Over */ - COMPOSITE_IN, /* Source In */ - COMPOSITE_OUT, /* Source Out */ - COMPOSITE_ATOP, /* Source Atop */ + COMPOSITE_OVER, /* Source Over */ + COMPOSITE_IN, /* Source In */ + COMPOSITE_OUT, /* Source Out */ + COMPOSITE_ATOP, /* Source Atop */ COMPOSITE_XOR, - COMPOSITE_ARITHMETIC, /* Not a fundamental PorterDuff operator, nor Cairo */ + COMPOSITE_ARITHMETIC, /* Not a fundamental PorterDuff operator, nor Cairo */ #ifdef WITH_CSSCOMPOSITE // New in CSS COMPOSITE_CLEAR, - COMPOSITE_COPY, /* Source */ + COMPOSITE_COPY, /* Source */ COMPOSITE_DESTINATION, COMPOSITE_DESTINATION_OVER, COMPOSITE_DESTINATION_IN, COMPOSITE_DESTINATION_OUT, COMPOSITE_DESTINATION_ATOP, - COMPOSITE_LIGHTER, /* Plus, Add (Not a fundamental PorterDuff operator */ + COMPOSITE_LIGHTER, /* Plus, Add (Not a fundamental PorterDuff operator */ #endif - COMPOSITE_ENDOPERATOR /* Cairo Saturate is not included in CSS */ + COMPOSITE_ENDOPERATOR /* Cairo Saturate is not included in CSS */ }; -class SPFeComposite : public SPFilterPrimitive { +class SPFeComposite : public SPFilterPrimitive +{ public: - SPFeComposite(); - ~SPFeComposite() override; + SPFeComposite(); + ~SPFeComposite() override; FeCompositeOperator composite_operator; double k1, k2, k3, k4; int in2; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FECOMPOSITE_H_SEEN */ diff --git a/src/object/filters/convolvematrix.cpp b/src/object/filters/convolvematrix.cpp index 69a41726585e7004ca4972d843564380d9364066..a028d8ffc3412626014363bfab380c762b1a9c3c 100644 --- a/src/object/filters/convolvematrix.cpp +++ b/src/object/filters/convolvematrix.cpp @@ -14,32 +14,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "convolvematrix.h" + #include +#include #include -#include "convolvematrix.h" - #include "attributes.h" -#include "helper-fns.h" - #include "display/nr-filter.h" - +#include "helper-fns.h" #include "xml/repr.h" -SPFeConvolveMatrix::SPFeConvolveMatrix() : SPFilterPrimitive() { - this->bias = 0; - this->divisorIsSet = false; - this->divisor = 0; +SPFeConvolveMatrix::SPFeConvolveMatrix() + : SPFilterPrimitive() +{ + this->bias = 0; + this->divisorIsSet = false; + this->divisor = 0; - //Setting default values: + // Setting default values: this->order.set("3 3"); this->targetX = 1; this->targetY = 1; this->edgeMode = Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_DUPLICATE; this->preserveAlpha = false; - //some helper variables: + // some helper variables: this->targetXIsSet = false; this->targetYIsSet = false; this->kernelMatrixIsSet = false; @@ -52,127 +52,132 @@ SPFeConvolveMatrix::~SPFeConvolveMatrix() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeConvolveMatrix::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); - - /*LOAD ATTRIBUTES FROM REPR HERE*/ - this->readAttr(SPAttr::ORDER); - this->readAttr(SPAttr::KERNELMATRIX); - this->readAttr(SPAttr::DIVISOR); - this->readAttr(SPAttr::BIAS); - this->readAttr(SPAttr::TARGETX); - this->readAttr(SPAttr::TARGETY); - this->readAttr(SPAttr::EDGEMODE); - this->readAttr(SPAttr::KERNELUNITLENGTH); - this->readAttr(SPAttr::PRESERVEALPHA); +void SPFeConvolveMatrix::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); + + /*LOAD ATTRIBUTES FROM REPR HERE*/ + this->readAttr(SPAttr::ORDER); + this->readAttr(SPAttr::KERNELMATRIX); + this->readAttr(SPAttr::DIVISOR); + this->readAttr(SPAttr::BIAS); + this->readAttr(SPAttr::TARGETX); + this->readAttr(SPAttr::TARGETY); + this->readAttr(SPAttr::EDGEMODE); + this->readAttr(SPAttr::KERNELUNITLENGTH); + this->readAttr(SPAttr::PRESERVEALPHA); } /** * Drops any allocated memory. */ -void SPFeConvolveMatrix::release() { - SPFilterPrimitive::release(); +void SPFeConvolveMatrix::release() +{ + SPFilterPrimitive::release(); } -static Inkscape::Filters::FilterConvolveMatrixEdgeMode sp_feConvolveMatrix_read_edgeMode(gchar const *value){ +static Inkscape::Filters::FilterConvolveMatrixEdgeMode sp_feConvolveMatrix_read_edgeMode(gchar const *value) +{ if (!value) { - return Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_DUPLICATE; //duplicate is default + return Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_DUPLICATE; // duplicate is default } - + switch (value[0]) { case 'd': if (strncmp(value, "duplicate", 9) == 0) { - return Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_DUPLICATE; + return Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_DUPLICATE; } break; case 'w': if (strncmp(value, "wrap", 4) == 0) { - return Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_WRAP; + return Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_WRAP; } break; case 'n': if (strncmp(value, "none", 4) == 0) { - return Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_NONE; + return Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_NONE; } break; } - - return Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_DUPLICATE; //duplicate is default + + return Inkscape::Filters::CONVOLVEMATRIX_EDGEMODE_DUPLICATE; // duplicate is default } /** * Sets a specific value in the SPFeConvolveMatrix. */ -void SPFeConvolveMatrix::set(SPAttr key, gchar const *value) { +void SPFeConvolveMatrix::set(SPAttr key, gchar const *value) +{ double read_num; int read_int; bool read_bool; Inkscape::Filters::FilterConvolveMatrixEdgeMode read_mode; - - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ + + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ case SPAttr::ORDER: this->order.set(value); - - //From SVG spec: If is not provided, it defaults to . + + // From SVG spec: If is not provided, it defaults to . if (this->order.optNumIsSet() == false) { this->order.setOptNumber(this->order.getNumber()); } - + if (this->targetXIsSet == false) { - this->targetX = (int) floor(this->order.getNumber()/2); + this->targetX = (int)floor(this->order.getNumber() / 2); } - + if (this->targetYIsSet == false) { - this->targetY = (int) floor(this->order.getOptNumber()/2); + this->targetY = (int)floor(this->order.getOptNumber() / 2); } - + this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::KERNELMATRIX: - if (value){ + if (value) { this->kernelMatrixIsSet = true; this->kernelMatrix = helperfns_read_vector(value); - - if (! this->divisorIsSet) { + + if (!this->divisorIsSet) { this->divisor = 0; - + for (double i : this->kernelMatrix) { this->divisor += i; } - + if (this->divisor == 0) { - this->divisor = 1; + this->divisor = 1; } } - + this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } else { g_warning("For feConvolveMatrix you MUST pass a kernelMatrix parameter!"); } break; case SPAttr::DIVISOR: - if (value) { + if (value) { read_num = helperfns_read_number(value); - + if (read_num == 0) { - // This should actually be an error, but given our UI it is more useful to simply set divisor to the default. + // This should actually be an error, but given our UI it is more useful to simply set divisor to the + // default. if (this->kernelMatrixIsSet) { for (double i : this->kernelMatrix) { read_num += i; } } - + if (read_num == 0) { - read_num = 1; + read_num = 1; } - - if (this->divisorIsSet || this->divisor!=read_num) { + + if (this->divisorIsSet || this->divisor != read_num) { this->divisorIsSet = false; this->divisor = read_num; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } - } else if (!this->divisorIsSet || this->divisor!=read_num) { + } else if (!this->divisorIsSet || this->divisor != read_num) { this->divisorIsSet = true; this->divisor = read_num; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); @@ -182,26 +187,27 @@ void SPFeConvolveMatrix::set(SPAttr key, gchar const *value) { case SPAttr::BIAS: read_num = 0; if (value) { - read_num = helperfns_read_number(value); + read_num = helperfns_read_number(value); } - - if (read_num != this->bias){ + + if (read_num != this->bias) { this->bias = read_num; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; case SPAttr::TARGETX: if (value) { - read_int = (int) helperfns_read_number(value); - - if (read_int < 0 || read_int > this->order.getNumber()){ - g_warning("targetX must be a value between 0 and orderX! Assuming floor(orderX/2) as default value."); - read_int = (int) floor(this->order.getNumber()/2.0); + read_int = (int)helperfns_read_number(value); + + if (read_int < 0 || read_int > this->order.getNumber()) { + g_warning( + "targetX must be a value between 0 and orderX! Assuming floor(orderX/2) as default value."); + read_int = (int)floor(this->order.getNumber() / 2.0); } - + this->targetXIsSet = true; - - if (read_int != this->targetX){ + + if (read_int != this->targetX) { this->targetX = read_int; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } @@ -209,16 +215,17 @@ void SPFeConvolveMatrix::set(SPAttr key, gchar const *value) { break; case SPAttr::TARGETY: if (value) { - read_int = (int) helperfns_read_number(value); - - if (read_int < 0 || read_int > this->order.getOptNumber()){ - g_warning("targetY must be a value between 0 and orderY! Assuming floor(orderY/2) as default value."); - read_int = (int) floor(this->order.getOptNumber()/2.0); + read_int = (int)helperfns_read_number(value); + + if (read_int < 0 || read_int > this->order.getOptNumber()) { + g_warning( + "targetY must be a value between 0 and orderY! Assuming floor(orderY/2) as default value."); + read_int = (int)floor(this->order.getOptNumber() / 2.0); } - + this->targetYIsSet = true; - - if (read_int != this->targetY){ + + if (read_int != this->targetY) { this->targetY = read_int; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } @@ -226,46 +233,43 @@ void SPFeConvolveMatrix::set(SPAttr key, gchar const *value) { break; case SPAttr::EDGEMODE: read_mode = sp_feConvolveMatrix_read_edgeMode(value); - - if (read_mode != this->edgeMode){ + + if (read_mode != this->edgeMode) { this->edgeMode = read_mode; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; case SPAttr::KERNELUNITLENGTH: this->kernelUnitLength.set(value); - - //From SVG spec: If the value is not specified, it defaults to the same value as . + + // From SVG spec: If the value is not specified, it defaults to the same value as . if (this->kernelUnitLength.optNumIsSet() == false) { this->kernelUnitLength.setOptNumber(this->kernelUnitLength.getNumber()); } - + this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::PRESERVEALPHA: read_bool = helperfns_read_bool(value, false); - - if (read_bool != this->preserveAlpha){ + + if (read_bool != this->preserveAlpha) { this->preserveAlpha = read_bool; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } - } /** * Receives update notifications. */ -void SPFeConvolveMatrix::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - +void SPFeConvolveMatrix::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something to trigger redisplay, updates? */ - } SPFilterPrimitive::update(ctx, flags); @@ -274,33 +278,35 @@ void SPFeConvolveMatrix::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeConvolveMatrix::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeConvolveMatrix::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values into it */ if (!repr) { repr = this->getRepr()->duplicate(doc); } - SPFilterPrimitive::write(doc, repr, flags); return repr; } -void SPFeConvolveMatrix::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeConvolveMatrix::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_CONVOLVEMATRIX); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterConvolveMatrix *nr_convolve = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterConvolveMatrix *nr_convolve = + dynamic_cast(nr_primitive); g_assert(nr_convolve != nullptr); this->renderer_common(nr_primitive); nr_convolve->set_targetX(this->targetX); nr_convolve->set_targetY(this->targetY); - nr_convolve->set_orderX( (int)this->order.getNumber() ); - nr_convolve->set_orderY( (int)this->order.getOptNumber() ); + nr_convolve->set_orderX((int)this->order.getNumber()); + nr_convolve->set_orderY((int)this->order.getOptNumber()); nr_convolve->set_kernelMatrix(this->kernelMatrix); nr_convolve->set_divisor(this->divisor); nr_convolve->set_bias(this->bias); diff --git a/src/object/filters/convolvematrix.h b/src/object/filters/convolvematrix.h index 501e3c52c1985ad942207b1df095e6f6bf74dc54..63c5c3697f18c42cf5a0f30609b0bac39b0681d9 100644 --- a/src/object/filters/convolvematrix.h +++ b/src/object/filters/convolvematrix.h @@ -15,17 +15,19 @@ #define SP_FECONVOLVEMATRIX_H_SEEN #include -#include "sp-filter-primitive.h" -#include "number-opt-number.h" + #include "display/nr-filter-convolve-matrix.h" +#include "number-opt-number.h" +#include "sp-filter-primitive.h" -#define SP_FECONVOLVEMATRIX(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FECONVOLVEMATRIX(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FECONVOLVEMATRIX(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FECONVOLVEMATRIX(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPFeConvolveMatrix : public SPFilterPrimitive { +class SPFeConvolveMatrix : public SPFilterPrimitive +{ public: - SPFeConvolveMatrix(); - ~SPFeConvolveMatrix() override; + SPFeConvolveMatrix(); + ~SPFeConvolveMatrix() override; NumberOptNumber order; std::vector kernelMatrix; @@ -41,16 +43,16 @@ public: bool kernelMatrixIsSet; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FECONVOLVEMATRIX_H_SEEN */ diff --git a/src/object/filters/diffuselighting.cpp b/src/object/filters/diffuselighting.cpp index 2623de7477ec759b90031ee402a72c32c08bcac1..a5fa354695ec2b68f98f39a437d475ba937a1054 100644 --- a/src/object/filters/diffuselighting.cpp +++ b/src/object/filters/diffuselighting.cpp @@ -17,32 +17,31 @@ // Same directory #include "diffuselighting.h" + +#include "attributes.h" +#include "display/nr-filter-diffuselighting.h" +#include "display/nr-filter.h" #include "distantlight.h" #include "pointlight.h" #include "spotlight.h" - #include "strneq.h" -#include "attributes.h" - -#include "display/nr-filter.h" -#include "display/nr-filter-diffuselighting.h" - -#include "svg/svg.h" #include "svg/svg-color.h" #include "svg/svg-icc-color.h" - +#include "svg/svg.h" #include "xml/repr.h" /* FeDiffuseLighting base class */ static void sp_feDiffuseLighting_children_modified(SPFeDiffuseLighting *sp_diffuselighting); -SPFeDiffuseLighting::SPFeDiffuseLighting() : SPFilterPrimitive() { +SPFeDiffuseLighting::SPFeDiffuseLighting() + : SPFilterPrimitive() +{ this->surfaceScale = 1; this->diffuseConstant = 1; this->lighting_color = 0xffffffff; this->icc = nullptr; - //TODO kernelUnit + // TODO kernelUnit this->renderer = nullptr; this->surfaceScale_set = FALSE; @@ -57,33 +56,36 @@ SPFeDiffuseLighting::~SPFeDiffuseLighting() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeDiffuseLighting::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); - - /*LOAD ATTRIBUTES FROM REPR HERE*/ - this->readAttr(SPAttr::SURFACESCALE); - this->readAttr(SPAttr::DIFFUSECONSTANT); - this->readAttr(SPAttr::KERNELUNITLENGTH); - this->readAttr(SPAttr::LIGHTING_COLOR); +void SPFeDiffuseLighting::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); + + /*LOAD ATTRIBUTES FROM REPR HERE*/ + this->readAttr(SPAttr::SURFACESCALE); + this->readAttr(SPAttr::DIFFUSECONSTANT); + this->readAttr(SPAttr::KERNELUNITLENGTH); + this->readAttr(SPAttr::LIGHTING_COLOR); } /** * Drops any allocated memory. */ -void SPFeDiffuseLighting::release() { - SPFilterPrimitive::release(); +void SPFeDiffuseLighting::release() +{ + SPFilterPrimitive::release(); } /** * Sets a specific value in the SPFeDiffuseLighting. */ -void SPFeDiffuseLighting::set(SPAttr key, gchar const *value) { +void SPFeDiffuseLighting::set(SPAttr key, gchar const *value) +{ gchar const *cend_ptr = nullptr; gchar *end_ptr = nullptr; - - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ - //TODO test forbidden values + + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ + // TODO test forbidden values case SPAttr::SURFACESCALE: end_ptr = nullptr; @@ -93,7 +95,7 @@ void SPFeDiffuseLighting::set(SPAttr key, gchar const *value) { if (end_ptr) { this->surfaceScale_set = TRUE; } - } + } if (!value || !end_ptr) { this->surfaceScale = 1; @@ -118,7 +120,7 @@ void SPFeDiffuseLighting::set(SPAttr key, gchar const *value) { end_ptr = nullptr; g_warning("this: diffuseConstant should be a positive number ... defaulting to 1"); } - } + } if (!value || !end_ptr) { this->diffuseConstant = 1; @@ -132,8 +134,8 @@ void SPFeDiffuseLighting::set(SPAttr key, gchar const *value) { this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::KERNELUNITLENGTH: - //TODO kernelUnit - //this->kernelUnitLength.set(value); + // TODO kernelUnit + // this->kernelUnitLength.set(value); /*TODOif (feDiffuseLighting->renderer) { feDiffuseLighting->renderer->surfaceScale = feDiffuseLighting->renderer; } @@ -144,7 +146,7 @@ void SPFeDiffuseLighting::set(SPAttr key, gchar const *value) { cend_ptr = nullptr; this->lighting_color = sp_svg_read_color(value, &cend_ptr, 0xffffffff); - //if a value was read + // if a value was read if (cend_ptr) { while (g_ascii_isspace(*cend_ptr)) { ++cend_ptr; @@ -152,10 +154,10 @@ void SPFeDiffuseLighting::set(SPAttr key, gchar const *value) { if (strneq(cend_ptr, "icc-color(", 10)) { if (!this->icc) { - this->icc = new SVGICCColor(); + this->icc = new SVGICCColor(); } - if ( ! sp_svg_read_icc_color( cend_ptr, this->icc ) ) { + if (!sp_svg_read_icc_color(cend_ptr, this->icc)) { delete this->icc; this->icc = nullptr; } @@ -163,7 +165,7 @@ void SPFeDiffuseLighting::set(SPAttr key, gchar const *value) { this->lighting_color_set = TRUE; } else { - //lighting_color already contains the default value + // lighting_color already contains the default value this->lighting_color_set = FALSE; } @@ -174,7 +176,7 @@ void SPFeDiffuseLighting::set(SPAttr key, gchar const *value) { this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -182,7 +184,8 @@ void SPFeDiffuseLighting::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeDiffuseLighting::update(SPCtx *ctx, guint flags) { +void SPFeDiffuseLighting::update(SPCtx *ctx, guint flags) +{ if (flags & (SP_OBJECT_MODIFIED_FLAG)) { this->readAttr(SPAttr::SURFACESCALE); this->readAttr(SPAttr::DIFFUSECONSTANT); @@ -196,14 +199,15 @@ void SPFeDiffuseLighting::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeDiffuseLighting::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeDiffuseLighting::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values _and children_ into it */ if (!repr) { repr = this->getRepr()->duplicate(doc); - //repr = doc->createElement("svg:feDiffuseLighting"); + // repr = doc->createElement("svg:feDiffuseLighting"); } - + if (this->surfaceScale_set) { sp_repr_set_css_double(repr, "surfaceScale", this->surfaceScale); } else { @@ -224,7 +228,7 @@ Inkscape::XML::Node* SPFeDiffuseLighting::write(Inkscape::XML::Document *doc, In } else { repr->removeAttribute("lighting-color"); } - + SPFilterPrimitive::write(doc, repr, flags); return repr; @@ -233,7 +237,8 @@ Inkscape::XML::Node* SPFeDiffuseLighting::write(Inkscape::XML::Document *doc, In /** * Callback for child_added event. */ -void SPFeDiffuseLighting::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { +void SPFeDiffuseLighting::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ SPFilterPrimitive::child_added(child, ref); sp_feDiffuseLighting_children_modified(this); @@ -243,14 +248,17 @@ void SPFeDiffuseLighting::child_added(Inkscape::XML::Node *child, Inkscape::XML: /** * Callback for remove_child event. */ -void SPFeDiffuseLighting::remove_child(Inkscape::XML::Node *child) { - SPFilterPrimitive::remove_child(child); +void SPFeDiffuseLighting::remove_child(Inkscape::XML::Node *child) +{ + SPFilterPrimitive::remove_child(child); - sp_feDiffuseLighting_children_modified(this); - this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); + sp_feDiffuseLighting_children_modified(this); + this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } -void SPFeDiffuseLighting::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref) { +void SPFeDiffuseLighting::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, + Inkscape::XML::Node *new_ref) +{ SPFilterPrimitive::order_changed(child, old_ref, new_ref); sp_feDiffuseLighting_children_modified(this); @@ -259,7 +267,7 @@ void SPFeDiffuseLighting::order_changed(Inkscape::XML::Node *child, Inkscape::XM static void sp_feDiffuseLighting_children_modified(SPFeDiffuseLighting *sp_diffuselighting) { - if (sp_diffuselighting->renderer) { + if (sp_diffuselighting->renderer) { sp_diffuselighting->renderer->light_type = Inkscape::Filters::NO_LIGHT; if (SP_IS_FEDISTANTLIGHT(sp_diffuselighting->firstChild())) { sp_diffuselighting->renderer->light_type = Inkscape::Filters::DISTANT_LIGHT; @@ -273,15 +281,17 @@ static void sp_feDiffuseLighting_children_modified(SPFeDiffuseLighting *sp_diffu sp_diffuselighting->renderer->light_type = Inkscape::Filters::SPOT_LIGHT; sp_diffuselighting->renderer->light.spot = SP_FESPOTLIGHT(sp_diffuselighting->firstChild()); } - } + } } -void SPFeDiffuseLighting::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeDiffuseLighting::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_DIFFUSELIGHTING); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterDiffuseLighting *nr_diffuselighting = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterDiffuseLighting *nr_diffuselighting = + dynamic_cast(nr_primitive); g_assert(nr_diffuselighting != nullptr); this->renderer = nr_diffuselighting; @@ -292,7 +302,7 @@ void SPFeDiffuseLighting::build_renderer(Inkscape::Filters::Filter* filter) { nr_diffuselighting->lighting_color = this->lighting_color; nr_diffuselighting->set_icc(this->icc); - //We assume there is at most one child + // We assume there is at most one child nr_diffuselighting->light_type = Inkscape::Filters::NO_LIGHT; if (SP_IS_FEDISTANTLIGHT(this->firstChild())) { @@ -309,9 +319,9 @@ void SPFeDiffuseLighting::build_renderer(Inkscape::Filters::Filter* filter) { nr_diffuselighting->light_type = Inkscape::Filters::SPOT_LIGHT; nr_diffuselighting->light.spot = SP_FESPOTLIGHT(this->firstChild()); } - - //nr_offset->set_dx(sp_offset->dx); - //nr_offset->set_dy(sp_offset->dy); + + // nr_offset->set_dx(sp_offset->dx); + // nr_offset->set_dy(sp_offset->dy); } /* diff --git a/src/object/filters/diffuselighting.h b/src/object/filters/diffuselighting.h index 23f67786988471a1fe3fdbf4573ae78099087076..9ef134866ba6c34fe5f18ca8253058228b40fd38 100644 --- a/src/object/filters/diffuselighting.h +++ b/src/object/filters/diffuselighting.h @@ -13,23 +13,25 @@ #ifndef SP_FEDIFFUSELIGHTING_H_SEEN #define SP_FEDIFFUSELIGHTING_H_SEEN -#include "sp-filter-primitive.h" #include "number-opt-number.h" +#include "sp-filter-primitive.h" -#define SP_FEDIFFUSELIGHTING(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FEDIFFUSELIGHTING(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FEDIFFUSELIGHTING(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FEDIFFUSELIGHTING(obj) (dynamic_cast((SPObject *)obj) != NULL) struct SVGICCColor; namespace Inkscape { namespace Filters { class FilterDiffuseLighting; -} } +} +} // namespace Inkscape -class SPFeDiffuseLighting : public SPFilterPrimitive { +class SPFeDiffuseLighting : public SPFilterPrimitive +{ public: - SPFeDiffuseLighting(); - ~SPFeDiffuseLighting() override; + SPFeDiffuseLighting(); + ~SPFeDiffuseLighting() override; gfloat surfaceScale; guint surfaceScale_set : 1; @@ -42,21 +44,22 @@ public: SVGICCColor *icc; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; - void order_changed(Inkscape::XML::Node* child, Inkscape::XML::Node* old_repr, Inkscape::XML::Node* new_repr) override; + void order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_repr, + Inkscape::XML::Node *new_repr) override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FEDIFFUSELIGHTING_H_SEEN */ diff --git a/src/object/filters/displacementmap.cpp b/src/object/filters/displacementmap.cpp index 793aa24bc931462d672c27ad911704fdb87cfe60..aee427aaf66089f03cf62027593dd62c580d849d 100644 --- a/src/object/filters/displacementmap.cpp +++ b/src/object/filters/displacementmap.cpp @@ -16,19 +16,17 @@ #include "displacementmap.h" #include "attributes.h" -#include "helper-fns.h" - #include "display/nr-filter-displacement-map.h" #include "display/nr-filter.h" - +#include "helper-fns.h" #include "object/sp-filter.h" - #include "svg/svg.h" - #include "xml/repr.h" -SPFeDisplacementMap::SPFeDisplacementMap() : SPFilterPrimitive() { - this->scale=0; +SPFeDisplacementMap::SPFeDisplacementMap() + : SPFilterPrimitive() +{ + this->scale = 0; this->xChannelSelector = DISPLACEMENTMAP_CHANNEL_ALPHA; this->yChannelSelector = DISPLACEMENTMAP_CHANNEL_ALPHA; this->in2 = Inkscape::Filters::NR_FILTER_SLOT_NOT_SET; @@ -41,37 +39,39 @@ SPFeDisplacementMap::~SPFeDisplacementMap() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeDisplacementMap::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); - - /*LOAD ATTRIBUTES FROM REPR HERE*/ - this->readAttr(SPAttr::SCALE); - this->readAttr(SPAttr::IN2); - this->readAttr(SPAttr::XCHANNELSELECTOR); - this->readAttr(SPAttr::YCHANNELSELECTOR); - - /* Unlike normal in, in2 is required attribute. Make sure, we can call - * it by some name. */ - if (this->in2 == Inkscape::Filters::NR_FILTER_SLOT_NOT_SET || - this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) - { - SPFilter *parent = SP_FILTER(this->parent); - this->in2 = this->name_previous_out(); - repr->setAttribute("in2", parent->name_for_image(this->in2)); - } +void SPFeDisplacementMap::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); + + /*LOAD ATTRIBUTES FROM REPR HERE*/ + this->readAttr(SPAttr::SCALE); + this->readAttr(SPAttr::IN2); + this->readAttr(SPAttr::XCHANNELSELECTOR); + this->readAttr(SPAttr::YCHANNELSELECTOR); + + /* Unlike normal in, in2 is required attribute. Make sure, we can call + * it by some name. */ + if (this->in2 == Inkscape::Filters::NR_FILTER_SLOT_NOT_SET || + this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) { + SPFilter *parent = SP_FILTER(this->parent); + this->in2 = this->name_previous_out(); + repr->setAttribute("in2", parent->name_for_image(this->in2)); + } } /** * Drops any allocated memory. */ -void SPFeDisplacementMap::release() { - SPFilterPrimitive::release(); +void SPFeDisplacementMap::release() +{ + SPFilterPrimitive::release(); } static FilterDisplacementMapChannelSelector sp_feDisplacementMap_readChannelSelector(gchar const *value) { - if (!value) return DISPLACEMENTMAP_CHANNEL_ALPHA; - + if (!value) + return DISPLACEMENTMAP_CHANNEL_ALPHA; + switch (value[0]) { case 'R': return DISPLACEMENTMAP_CHANNEL_RED; @@ -90,39 +90,40 @@ static FilterDisplacementMapChannelSelector sp_feDisplacementMap_readChannelSele g_warning("Invalid attribute for Channel Selector. Valid modes are 'R', 'G', 'B' or 'A'"); break; } - - return DISPLACEMENTMAP_CHANNEL_ALPHA; //default is Alpha Channel + + return DISPLACEMENTMAP_CHANNEL_ALPHA; // default is Alpha Channel } /** * Sets a specific value in the SPFeDisplacementMap. */ -void SPFeDisplacementMap::set(SPAttr key, gchar const *value) { +void SPFeDisplacementMap::set(SPAttr key, gchar const *value) +{ int input; double read_num; FilterDisplacementMapChannelSelector read_selector; - - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ + + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ case SPAttr::XCHANNELSELECTOR: read_selector = sp_feDisplacementMap_readChannelSelector(value); - - if (read_selector != this->xChannelSelector){ + + if (read_selector != this->xChannelSelector) { this->xChannelSelector = read_selector; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; case SPAttr::YCHANNELSELECTOR: read_selector = sp_feDisplacementMap_readChannelSelector(value); - - if (read_selector != this->yChannelSelector){ + + if (read_selector != this->yChannelSelector) { this->yChannelSelector = read_selector; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; case SPAttr::SCALE: read_num = value ? helperfns_read_number(value) : 0; - + if (read_num != this->scale) { this->scale = read_num; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); @@ -130,14 +131,14 @@ void SPFeDisplacementMap::set(SPAttr key, gchar const *value) { break; case SPAttr::IN2: input = this->read_in(value); - + if (input != this->in2) { this->in2 = input; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -145,31 +146,29 @@ void SPFeDisplacementMap::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeDisplacementMap::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - +void SPFeDisplacementMap::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something to trigger redisplay, updates? */ - } /* Unlike normal in, in2 is required attribute. Make sure, we can call * it by some name. */ if (this->in2 == Inkscape::Filters::NR_FILTER_SLOT_NOT_SET || - this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) - { + this->in2 == Inkscape::Filters::NR_FILTER_UNNAMED_SLOT) { SPFilter *parent = SP_FILTER(this->parent); this->in2 = this->name_previous_out(); - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. this->setAttribute("in2", parent->name_for_image(this->in2)); } SPFilterPrimitive::update(ctx, flags); } -static char const * get_channelselector_name(FilterDisplacementMapChannelSelector selector) { - switch(selector) { +static char const *get_channelselector_name(FilterDisplacementMapChannelSelector selector) +{ + switch (selector) { case DISPLACEMENTMAP_CHANNEL_RED: return "R"; case DISPLACEMENTMAP_CHANNEL_GREEN: @@ -186,7 +185,8 @@ static char const * get_channelselector_name(FilterDisplacementMapChannelSelecto /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeDisplacementMap::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeDisplacementMap::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ SPFilter *parent = SP_FILTER(this->parent); if (!repr) { @@ -195,17 +195,16 @@ Inkscape::XML::Node* SPFeDisplacementMap::write(Inkscape::XML::Document *doc, In gchar const *in2_name = parent->name_for_image(this->in2); - if( !in2_name ) { - + if (!in2_name) { // This code is very similar to name_previous_out() SPObject *i = parent->firstChild(); // Find previous filter primitive while (i && i->getNext() != this) { - i = i->getNext(); + i = i->getNext(); } - if( i ) { + if (i) { SPFilterPrimitive *i_prim = SP_FILTER_PRIMITIVE(i); in2_name = parent->name_for_image(i_prim->image_out); } @@ -218,22 +217,22 @@ Inkscape::XML::Node* SPFeDisplacementMap::write(Inkscape::XML::Document *doc, In } sp_repr_set_svg_double(repr, "scale", this->scale); - repr->setAttribute("xChannelSelector", - get_channelselector_name(this->xChannelSelector)); - repr->setAttribute("yChannelSelector", - get_channelselector_name(this->yChannelSelector)); + repr->setAttribute("xChannelSelector", get_channelselector_name(this->xChannelSelector)); + repr->setAttribute("yChannelSelector", get_channelselector_name(this->yChannelSelector)); SPFilterPrimitive::write(doc, repr, flags); return repr; } -void SPFeDisplacementMap::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeDisplacementMap::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_DISPLACEMENTMAP); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterDisplacementMap *nr_displacement_map = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterDisplacementMap *nr_displacement_map = + dynamic_cast(nr_primitive); g_assert(nr_displacement_map != nullptr); this->renderer_common(nr_primitive); diff --git a/src/object/filters/displacementmap.h b/src/object/filters/displacementmap.h index 27243dc0cef3e52c789af2f5bd1c5ab4a8c93dab..34fd83b1df8b3839300bd5441ef5654deb2e9352 100644 --- a/src/object/filters/displacementmap.h +++ b/src/object/filters/displacementmap.h @@ -15,10 +15,11 @@ #include "sp-filter-primitive.h" -#define SP_FEDISPLACEMENTMAP(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FEDISPLACEMENTMAP(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FEDISPLACEMENTMAP(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FEDISPLACEMENTMAP(obj) (dynamic_cast((SPObject *)obj) != NULL) -enum FilterDisplacementMapChannelSelector { +enum FilterDisplacementMapChannelSelector +{ DISPLACEMENTMAP_CHANNEL_RED, DISPLACEMENTMAP_CHANNEL_GREEN, DISPLACEMENTMAP_CHANNEL_BLUE, @@ -26,27 +27,28 @@ enum FilterDisplacementMapChannelSelector { DISPLACEMENTMAP_CHANNEL_ENDTYPE }; -class SPFeDisplacementMap : public SPFilterPrimitive { +class SPFeDisplacementMap : public SPFilterPrimitive +{ public: - SPFeDisplacementMap(); - ~SPFeDisplacementMap() override; + SPFeDisplacementMap(); + ~SPFeDisplacementMap() override; - int in2; + int in2; double scale; FilterDisplacementMapChannelSelector xChannelSelector; FilterDisplacementMapChannelSelector yChannelSelector; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FEDISPLACEMENTMAP_H_SEEN */ diff --git a/src/object/filters/distantlight.cpp b/src/object/filters/distantlight.cpp index 0c845b487037a2f1cd06d75602ccc947cb5d4ce7..ddeb4a3d846c073316e60d849db2c4c58d163124 100644 --- a/src/object/filters/distantlight.cpp +++ b/src/object/filters/distantlight.cpp @@ -17,18 +17,20 @@ #include // In same directory -#include "distantlight.h" -#include "diffuselighting.h" -#include "specularlighting.h" - #include "attributes.h" +#include "diffuselighting.h" +#include "distantlight.h" #include "document.h" - +#include "specularlighting.h" #include "xml/repr.h" SPFeDistantLight::SPFeDistantLight() - : SPObject(), azimuth(0), azimuth_set(FALSE), elevation(0), elevation_set(FALSE) { -} + : SPObject() + , azimuth(0) + , azimuth_set(FALSE) + , elevation(0) + , elevation_set(FALSE) +{} SPFeDistantLight::~SPFeDistantLight() = default; @@ -37,91 +39,91 @@ SPFeDistantLight::~SPFeDistantLight() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeDistantLight::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPObject::build(document, repr); +void SPFeDistantLight::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPObject::build(document, repr); - //Read values of key attributes from XML nodes into object. + // Read values of key attributes from XML nodes into object. this->readAttr(SPAttr::AZIMUTH); this->readAttr(SPAttr::ELEVATION); -//is this necessary? + // is this necessary? document->addResource("fedistantlight", this); } /** * Drops any allocated memory. */ -void SPFeDistantLight::release() { - if ( this->document ) { +void SPFeDistantLight::release() +{ + if (this->document) { // Unregister ourselves this->document->removeResource("fedistantlight", this); } -//TODO: release resources here + // TODO: release resources here } /** * Sets a specific value in the SPFeDistantLight. */ -void SPFeDistantLight::set(SPAttr key, gchar const *value) { +void SPFeDistantLight::set(SPAttr key, gchar const *value) +{ gchar *end_ptr; switch (key) { - case SPAttr::AZIMUTH: - end_ptr =nullptr; + case SPAttr::AZIMUTH: + end_ptr = nullptr; - if (value) { - this->azimuth = g_ascii_strtod(value, &end_ptr); + if (value) { + this->azimuth = g_ascii_strtod(value, &end_ptr); - if (end_ptr) { - this->azimuth_set = TRUE; + if (end_ptr) { + this->azimuth_set = TRUE; + } } - } - if (!value || !end_ptr) { + if (!value || !end_ptr) { this->azimuth_set = FALSE; this->azimuth = 0; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - case SPAttr::ELEVATION: - end_ptr =nullptr; - - if (value) { - this->elevation = g_ascii_strtod(value, &end_ptr); - - if (end_ptr) { - this->elevation_set = TRUE; } - } - if (!value || !end_ptr) { + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); + } + break; + case SPAttr::ELEVATION: + end_ptr = nullptr; + + if (value) { + this->elevation = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->elevation_set = TRUE; + } + } + + if (!value || !end_ptr) { this->elevation_set = FALSE; this->elevation = 0; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - default: - // See if any parents need this value. - SPObject::set(key, value); - break; + } + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); + } + break; + default: + // See if any parents need this value. + SPObject::set(key, value); + break; } } /** * * Receives update notifications. * */ -void SPFeDistantLight::update(SPCtx *ctx, guint flags) { +void SPFeDistantLight::update(SPCtx *ctx, guint flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { /* do something to trigger redisplay, updates? */ this->readAttr(SPAttr::AZIMUTH); @@ -134,7 +136,8 @@ void SPFeDistantLight::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeDistantLight::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeDistantLight::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ if (!repr) { repr = this->getRepr()->duplicate(doc); } diff --git a/src/object/filters/distantlight.h b/src/object/filters/distantlight.h index c2f1f0a1627fac50148221cffc719029451c9bcc..fe476216c138fff2507097938918e66534aee86e 100644 --- a/src/object/filters/distantlight.h +++ b/src/object/filters/distantlight.h @@ -18,14 +18,15 @@ #include "../sp-object.h" -#define SP_FEDISTANTLIGHT(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FEDISTANTLIGHT(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FEDISTANTLIGHT(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FEDISTANTLIGHT(obj) (dynamic_cast((SPObject *)obj) != NULL) /* Distant light class */ -class SPFeDistantLight : public SPObject { +class SPFeDistantLight : public SPObject +{ public: - SPFeDistantLight(); - ~SPFeDistantLight() override; + SPFeDistantLight(); + ~SPFeDistantLight() override; /** azimuth attribute */ float azimuth; @@ -35,14 +36,14 @@ public: unsigned int elevation_set : 1; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif /* !SP_FEDISTANTLIGHT_H_SEEN */ diff --git a/src/object/filters/flood.cpp b/src/object/filters/flood.cpp index 9e179bf09890d496bcf2171d81adb1a894e61e39..8a67d065903dfbae06d62a785a7f678afd09cae6 100644 --- a/src/object/filters/flood.cpp +++ b/src/object/filters/flood.cpp @@ -15,19 +15,18 @@ #include "flood.h" -#include "strneq.h" #include "attributes.h" - -#include "svg/svg.h" -#include "svg/svg-color.h" - -#include "display/nr-filter.h" #include "display/nr-filter-flood.h" - +#include "display/nr-filter.h" +#include "strneq.h" +#include "svg/svg-color.h" +#include "svg/svg.h" #include "xml/repr.h" -SPFeFlood::SPFeFlood() : SPFilterPrimitive() { - this->color = 0; +SPFeFlood::SPFeFlood() + : SPFilterPrimitive() +{ + this->color = 0; this->opacity = 1; this->icc = nullptr; @@ -40,53 +39,56 @@ SPFeFlood::~SPFeFlood() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeFlood::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); +void SPFeFlood::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); - /*LOAD ATTRIBUTES FROM REPR HERE*/ - this->readAttr(SPAttr::FLOOD_OPACITY); - this->readAttr(SPAttr::FLOOD_COLOR); + /*LOAD ATTRIBUTES FROM REPR HERE*/ + this->readAttr(SPAttr::FLOOD_OPACITY); + this->readAttr(SPAttr::FLOOD_COLOR); } /** * Drops any allocated memory. */ -void SPFeFlood::release() { - SPFilterPrimitive::release(); +void SPFeFlood::release() +{ + SPFilterPrimitive::release(); } /** * Sets a specific value in the SPFeFlood. */ -void SPFeFlood::set(SPAttr key, gchar const *value) { +void SPFeFlood::set(SPAttr key, gchar const *value) +{ gchar const *cend_ptr = nullptr; gchar *end_ptr = nullptr; guint32 read_color; double read_num; bool dirty = false; - - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ + + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ case SPAttr::FLOOD_COLOR: cend_ptr = nullptr; read_color = sp_svg_read_color(value, &cend_ptr, 0xffffffff); - if (cend_ptr && read_color != this->color){ + if (cend_ptr && read_color != this->color) { this->color = read_color; - dirty=true; + dirty = true; } - if (cend_ptr){ + if (cend_ptr) { while (g_ascii_isspace(*cend_ptr)) { ++cend_ptr; } if (strneq(cend_ptr, "icc-color(", 10)) { if (!this->icc) { - this->icc = new SVGICCColor(); + this->icc = new SVGICCColor(); } - if ( ! sp_svg_read_icc_color( cend_ptr, this->icc ) ) { + if (!sp_svg_read_icc_color(cend_ptr, this->icc)) { delete this->icc; this->icc = nullptr; } @@ -119,7 +121,7 @@ void SPFeFlood::set(SPAttr key, gchar const *value) { } break; default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -127,12 +129,10 @@ void SPFeFlood::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeFlood::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - +void SPFeFlood::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something to trigger redisplay, updates? */ - } SPFilterPrimitive::update(ctx, flags); @@ -141,7 +141,8 @@ void SPFeFlood::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeFlood::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeFlood::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values into it */ if (!repr) { @@ -153,16 +154,17 @@ Inkscape::XML::Node* SPFeFlood::write(Inkscape::XML::Document *doc, Inkscape::XM return repr; } -void SPFeFlood::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeFlood::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_FLOOD); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterFlood *nr_flood = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterFlood *nr_flood = dynamic_cast(nr_primitive); g_assert(nr_flood != nullptr); this->renderer_common(nr_primitive); - + nr_flood->set_opacity(this->opacity); nr_flood->set_color(this->color); nr_flood->set_icc(this->icc); diff --git a/src/object/filters/flood.h b/src/object/filters/flood.h index 908fffd343eb1a05bf38f52d06d15ea440afe11d..5f9c186125cf28169425ccb21824d1ad2d17ec26 100644 --- a/src/object/filters/flood.h +++ b/src/object/filters/flood.h @@ -16,29 +16,30 @@ #include "sp-filter-primitive.h" #include "svg/svg-icc-color.h" -#define SP_FEFLOOD(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FEFLOOD(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FEFLOOD(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FEFLOOD(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPFeFlood : public SPFilterPrimitive { +class SPFeFlood : public SPFilterPrimitive +{ public: - SPFeFlood(); - ~SPFeFlood() override; + SPFeFlood(); + ~SPFeFlood() override; guint32 color; SVGICCColor *icc; double opacity; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FEFLOOD_H_SEEN */ diff --git a/src/object/filters/gaussian-blur.cpp b/src/object/filters/gaussian-blur.cpp index afad293ee23a5d4cc199cc00911d3296f596eb02..561e82e17d36038357f4d673f691a75100308a4b 100644 --- a/src/object/filters/gaussian-blur.cpp +++ b/src/object/filters/gaussian-blur.cpp @@ -17,16 +17,14 @@ #include "gaussian-blur.h" #include "attributes.h" - -#include "display/nr-filter.h" #include "display/nr-filter-gaussian.h" - +#include "display/nr-filter.h" #include "svg/svg.h" - #include "xml/repr.h" -SPGaussianBlur::SPGaussianBlur() : SPFilterPrimitive() { -} +SPGaussianBlur::SPGaussianBlur() + : SPFilterPrimitive() +{} SPGaussianBlur::~SPGaussianBlur() = default; @@ -35,8 +33,9 @@ SPGaussianBlur::~SPGaussianBlur() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPGaussianBlur::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); +void SPGaussianBlur::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); this->readAttr(SPAttr::STDDEVIATION); } @@ -44,21 +43,23 @@ void SPGaussianBlur::build(SPDocument *document, Inkscape::XML::Node *repr) { /** * Drops any allocated memory. */ -void SPGaussianBlur::release() { - SPFilterPrimitive::release(); +void SPGaussianBlur::release() +{ + SPFilterPrimitive::release(); } /** * Sets a specific value in the SPGaussianBlur. */ -void SPGaussianBlur::set(SPAttr key, gchar const *value) { - switch(key) { +void SPGaussianBlur::set(SPAttr key, gchar const *value) +{ + switch (key) { case SPAttr::STDDEVIATION: this->stdDeviation.set(value); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -66,7 +67,8 @@ void SPGaussianBlur::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPGaussianBlur::update(SPCtx *ctx, guint flags) { +void SPGaussianBlur::update(SPCtx *ctx, guint flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { this->readAttr(SPAttr::STDDEVIATION); } @@ -77,7 +79,8 @@ void SPGaussianBlur::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPGaussianBlur::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPGaussianBlur::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values into it */ if (!repr) { @@ -89,21 +92,22 @@ Inkscape::XML::Node* SPGaussianBlur::write(Inkscape::XML::Document *doc, Inkscap return repr; } -void sp_gaussianBlur_setDeviation(SPGaussianBlur *blur, float num) +void sp_gaussianBlur_setDeviation(SPGaussianBlur *blur, float num) { blur->stdDeviation.setNumber(num); } -void sp_gaussianBlur_setDeviation(SPGaussianBlur *blur, float num, float optnum) +void sp_gaussianBlur_setDeviation(SPGaussianBlur *blur, float num, float optnum) { blur->stdDeviation.setNumber(num); blur->stdDeviation.setOptNumber(optnum); } -void SPGaussianBlur::build_renderer(Inkscape::Filters::Filter* filter) { +void SPGaussianBlur::build_renderer(Inkscape::Filters::Filter *filter) +{ int handle = filter->add_primitive(Inkscape::Filters::NR_FILTER_GAUSSIANBLUR); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(handle); - Inkscape::Filters::FilterGaussian *nr_blur = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterGaussian *nr_blur = dynamic_cast(nr_primitive); this->renderer_common(nr_primitive); @@ -112,10 +116,10 @@ void SPGaussianBlur::build_renderer(Inkscape::Filters::Filter* filter) { if (num >= 0.0) { gfloat optnum = this->stdDeviation.getOptNumber(); - if(optnum >= 0.0) { - nr_blur->set_deviation((double) num, (double) optnum); + if (optnum >= 0.0) { + nr_blur->set_deviation((double)num, (double)optnum); } else { - nr_blur->set_deviation((double) num); + nr_blur->set_deviation((double)num); } } } diff --git a/src/object/filters/gaussian-blur.h b/src/object/filters/gaussian-blur.h index 5def69c0366b23850e1baa272d01fa9ef60c968e..c31b646e185edf177372be3879e9bcde6c80f68b 100644 --- a/src/object/filters/gaussian-blur.h +++ b/src/object/filters/gaussian-blur.h @@ -13,35 +13,36 @@ #ifndef SP_GAUSSIANBLUR_H_SEEN #define SP_GAUSSIANBLUR_H_SEEN -#include "sp-filter-primitive.h" #include "number-opt-number.h" +#include "sp-filter-primitive.h" -#define SP_GAUSSIANBLUR(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_GAUSSIANBLUR(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_GAUSSIANBLUR(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_GAUSSIANBLUR(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPGaussianBlur : public SPFilterPrimitive { +class SPGaussianBlur : public SPFilterPrimitive +{ public: - SPGaussianBlur(); - ~SPGaussianBlur() override; + SPGaussianBlur(); + ~SPGaussianBlur() override; /** stdDeviation attribute */ NumberOptNumber stdDeviation; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; -void sp_gaussianBlur_setDeviation(SPGaussianBlur *blur, float num); -void sp_gaussianBlur_setDeviation(SPGaussianBlur *blur, float num, float optnum); +void sp_gaussianBlur_setDeviation(SPGaussianBlur *blur, float num); +void sp_gaussianBlur_setDeviation(SPGaussianBlur *blur, float num, float optnum); #endif /* !SP_GAUSSIANBLUR_H_SEEN */ diff --git a/src/object/filters/image.cpp b/src/object/filters/image.cpp index 876fd39059f842f6d8ff33e1ca1d4372f275e8b5..f61f9cafa8d22321f7e44a4f2bb92f1c6d337d59 100644 --- a/src/object/filters/image.cpp +++ b/src/object/filters/image.cpp @@ -20,28 +20,25 @@ #include #include "attributes.h" -#include "enums.h" - #include "bad-uri-exception.h" - -#include "object/sp-image.h" -#include "object/uri.h" -#include "object/uri-references.h" - #include "display/nr-filter-image.h" #include "display/nr-filter.h" - +#include "enums.h" +#include "object/sp-image.h" +#include "object/uri-references.h" +#include "object/uri.h" #include "xml/repr.h" - -SPFeImage::SPFeImage() : SPFilterPrimitive() { - this->href = nullptr; - this->from_element = false; - this->SVGElemRef = nullptr; - this->SVGElem = nullptr; +SPFeImage::SPFeImage() + : SPFilterPrimitive() +{ + this->href = nullptr; + this->from_element = false; + this->SVGElemRef = nullptr; + this->SVGElem = nullptr; this->aspect_align = SP_ASPECT_XMID_YMID; // Default - this->aspect_clip = SP_ASPECT_MEET; // Default + this->aspect_clip = SP_ASPECT_MEET; // Default } SPFeImage::~SPFeImage() = default; @@ -64,29 +61,31 @@ void SPFeImage::build(SPDocument *document, Inkscape::XML::Node *repr) /** * Drops any allocated memory. */ -void SPFeImage::release() { +void SPFeImage::release() +{ this->_image_modified_connection.disconnect(); this->_href_modified_connection.disconnect(); if (this->SVGElemRef) { - delete this->SVGElemRef; + delete this->SVGElemRef; } SPFilterPrimitive::release(); } -static void sp_feImage_elem_modified(SPObject* /*href*/, guint /*flags*/, SPObject* obj) +static void sp_feImage_elem_modified(SPObject * /*href*/, guint /*flags*/, SPObject *obj) { obj->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } -static void sp_feImage_href_modified(SPObject* /*old_elem*/, SPObject* new_elem, SPObject* obj) +static void sp_feImage_href_modified(SPObject * /*old_elem*/, SPObject *new_elem, SPObject *obj) { SPFeImage *feImage = SP_FEIMAGE(obj); feImage->_image_modified_connection.disconnect(); if (new_elem) { feImage->SVGElem = SP_ITEM(new_elem); - feImage->_image_modified_connection = ((SPObject*) feImage->SVGElem)->connectModified(sigc::bind(sigc::ptr_fun(&sp_feImage_elem_modified), obj)); + feImage->_image_modified_connection = + ((SPObject *)feImage->SVGElem)->connectModified(sigc::bind(sigc::ptr_fun(&sp_feImage_elem_modified), obj)); } else { feImage->SVGElem = nullptr; } @@ -97,29 +96,34 @@ static void sp_feImage_href_modified(SPObject* /*old_elem*/, SPObject* new_elem, /** * Sets a specific value in the SPFeImage. */ -void SPFeImage::set(SPAttr key, gchar const *value) { - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ +void SPFeImage::set(SPAttr key, gchar const *value) +{ + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ case SPAttr::XLINK_HREF: if (this->href) { g_free(this->href); } - this->href = (value) ? g_strdup (value) : nullptr; - if (!this->href) return; + this->href = (value) ? g_strdup(value) : nullptr; + if (!this->href) + return; delete this->SVGElemRef; this->SVGElemRef = nullptr; this->SVGElem = nullptr; this->_image_modified_connection.disconnect(); this->_href_modified_connection.disconnect(); - try{ + try { Inkscape::URI SVGElem_uri(this->href); this->SVGElemRef = new Inkscape::URIReference(this->document); this->SVGElemRef->attach(SVGElem_uri); this->from_element = true; - this->_href_modified_connection = this->SVGElemRef->changedSignal().connect(sigc::bind(sigc::ptr_fun(&sp_feImage_href_modified), this)); + this->_href_modified_connection = this->SVGElemRef->changedSignal().connect( + sigc::bind(sigc::ptr_fun(&sp_feImage_href_modified), this)); if (SPObject *elemref = this->SVGElemRef->getObject()) { this->SVGElem = SP_ITEM(elemref); - this->_image_modified_connection = ((SPObject*) this->SVGElem)->connectModified(sigc::bind(sigc::ptr_fun(&sp_feImage_elem_modified), this)); + this->_image_modified_connection = + ((SPObject *)this->SVGElem) + ->connectModified(sigc::bind(sigc::ptr_fun(&sp_feImage_elem_modified), this)); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } else { @@ -127,11 +131,10 @@ void SPFeImage::set(SPAttr key, gchar const *value) { } } // catches either MalformedURIException or UnsupportedURIException - catch(const Inkscape::BadURIException & e) - { + catch (const Inkscape::BadURIException &e) { this->from_element = false; /* This occurs when using external image as the source */ - //g_warning("caught Inkscape::BadURIException in sp_feImage_set"); + // g_warning("caught Inkscape::BadURIException in sp_feImage_set"); break; } break; @@ -140,7 +143,7 @@ void SPFeImage::set(SPAttr key, gchar const *value) { /* Copied from sp-image.cpp */ /* Do setup before, so we can use break to escape */ this->aspect_align = SP_ASPECT_XMID_YMID; // Default - this->aspect_clip = SP_ASPECT_MEET; // Default + this->aspect_clip = SP_ASPECT_MEET; // Default this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); if (value) { int len; @@ -148,45 +151,50 @@ void SPFeImage::set(SPAttr key, gchar const *value) { const gchar *p, *e; unsigned int align, clip; p = value; - while (*p && *p == 32) p += 1; - if (!*p) break; + while (*p && *p == 32) + p += 1; + if (!*p) + break; e = p; - while (*e && *e != 32) e += 1; + while (*e && *e != 32) + e += 1; len = e - p; - if (len > 8) break; - memcpy (c, value, len); + if (len > 8) + break; + memcpy(c, value, len); c[len] = 0; /* Now the actual part */ - if (!strcmp (c, "none")) { + if (!strcmp(c, "none")) { align = SP_ASPECT_NONE; - } else if (!strcmp (c, "xMinYMin")) { + } else if (!strcmp(c, "xMinYMin")) { align = SP_ASPECT_XMIN_YMIN; - } else if (!strcmp (c, "xMidYMin")) { + } else if (!strcmp(c, "xMidYMin")) { align = SP_ASPECT_XMID_YMIN; - } else if (!strcmp (c, "xMaxYMin")) { + } else if (!strcmp(c, "xMaxYMin")) { align = SP_ASPECT_XMAX_YMIN; - } else if (!strcmp (c, "xMinYMid")) { + } else if (!strcmp(c, "xMinYMid")) { align = SP_ASPECT_XMIN_YMID; - } else if (!strcmp (c, "xMidYMid")) { + } else if (!strcmp(c, "xMidYMid")) { align = SP_ASPECT_XMID_YMID; - } else if (!strcmp (c, "xMaxYMid")) { + } else if (!strcmp(c, "xMaxYMid")) { align = SP_ASPECT_XMAX_YMID; - } else if (!strcmp (c, "xMinYMax")) { + } else if (!strcmp(c, "xMinYMax")) { align = SP_ASPECT_XMIN_YMAX; - } else if (!strcmp (c, "xMidYMax")) { + } else if (!strcmp(c, "xMidYMax")) { align = SP_ASPECT_XMID_YMAX; - } else if (!strcmp (c, "xMaxYMax")) { + } else if (!strcmp(c, "xMaxYMax")) { align = SP_ASPECT_XMAX_YMAX; } else { g_warning("Illegal preserveAspectRatio: %s", c); break; } clip = SP_ASPECT_MEET; - while (*e && *e == 32) e += 1; + while (*e && *e == 32) + e += 1; if (*e) { - if (!strcmp (e, "meet")) { + if (!strcmp(e, "meet")) { clip = SP_ASPECT_MEET; - } else if (!strcmp (e, "slice")) { + } else if (!strcmp(e, "slice")) { clip = SP_ASPECT_SLICE; } else { break; @@ -198,7 +206,7 @@ void SPFeImage::set(SPAttr key, gchar const *value) { break; default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -206,10 +214,9 @@ void SPFeImage::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeImage::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - +void SPFeImage::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something to trigger redisplay, updates? */ } @@ -219,7 +226,8 @@ void SPFeImage::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeImage::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeImage::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values into it */ if (!repr) { @@ -231,20 +239,21 @@ Inkscape::XML::Node* SPFeImage::write(Inkscape::XML::Document *doc, Inkscape::XM return repr; } -void SPFeImage::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeImage::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_IMAGE); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterImage *nr_image = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterImage *nr_image = dynamic_cast(nr_primitive); g_assert(nr_image != nullptr); this->renderer_common(nr_primitive); nr_image->from_element = this->from_element; nr_image->SVGElem = this->SVGElem; - nr_image->set_align( this->aspect_align ); - nr_image->set_clip( this->aspect_clip ); + nr_image->set_align(this->aspect_align); + nr_image->set_clip(this->aspect_clip); nr_image->set_href(this->href); nr_image->set_document(this->document); } diff --git a/src/object/filters/image.h b/src/object/filters/image.h index 33addda314a82d3b99714266690f10d6f0edf811..f4201563a6abb14e9b1bc4cdfbe3314955865c68 100644 --- a/src/object/filters/image.h +++ b/src/object/filters/image.h @@ -16,8 +16,8 @@ #include "sp-filter-primitive.h" -#define SP_FEIMAGE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FEIMAGE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FEIMAGE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FEIMAGE(obj) (dynamic_cast((SPObject *)obj) != NULL) class SPItem; @@ -25,10 +25,11 @@ namespace Inkscape { class URIReference; } -class SPFeImage : public SPFilterPrimitive { +class SPFeImage : public SPFilterPrimitive +{ public: - SPFeImage(); - ~SPFeImage() override; + SPFeImage(); + ~SPFeImage() override; gchar *href; @@ -37,22 +38,22 @@ public: unsigned int aspect_clip : 1; bool from_element; - SPItem* SVGElem; - Inkscape::URIReference* SVGElemRef; + SPItem *SVGElem; + Inkscape::URIReference *SVGElemRef; sigc::connection _image_modified_connection; sigc::connection _href_modified_connection; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FEIMAGE_H_SEEN */ diff --git a/src/object/filters/merge.cpp b/src/object/filters/merge.cpp index 2fe993b023d170b3755a6156280d83458e1af7a8..eb8d55ab597aff2638072fcf7ff81e5888478dd5 100644 --- a/src/object/filters/merge.cpp +++ b/src/object/filters/merge.cpp @@ -12,17 +12,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "merge.h" + #include "attributes.h" +#include "display/nr-filter-merge.h" +#include "display/nr-filter.h" +#include "mergenode.h" #include "svg/svg.h" #include "xml/repr.h" -#include "merge.h" -#include "mergenode.h" -#include "display/nr-filter.h" -#include "display/nr-filter-merge.h" - -SPFeMerge::SPFeMerge() : SPFilterPrimitive() { -} +SPFeMerge::SPFeMerge() + : SPFilterPrimitive() +{} SPFeMerge::~SPFeMerge() = default; @@ -31,25 +32,28 @@ SPFeMerge::~SPFeMerge() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeMerge::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); +void SPFeMerge::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); } /** * Drops any allocated memory. */ -void SPFeMerge::release() { - SPFilterPrimitive::release(); +void SPFeMerge::release() +{ + SPFilterPrimitive::release(); } /** * Sets a specific value in the SPFeMerge. */ -void SPFeMerge::set(SPAttr key, gchar const *value) { - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ +void SPFeMerge::set(SPAttr key, gchar const *value) +{ + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -57,7 +61,8 @@ void SPFeMerge::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeMerge::update(SPCtx *ctx, guint flags) { +void SPFeMerge::update(SPCtx *ctx, guint flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } @@ -68,32 +73,33 @@ void SPFeMerge::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeMerge::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeMerge::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values into it. And child nodes, too! */ if (!repr) { repr = this->getRepr()->duplicate(doc); } - SPFilterPrimitive::write(doc, repr, flags); return repr; } -void SPFeMerge::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeMerge::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_MERGE); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterMerge *nr_merge = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterMerge *nr_merge = dynamic_cast(nr_primitive); g_assert(nr_merge != nullptr); this->renderer_common(nr_primitive); int in_nr = 0; - for(auto& input: children) { + for (auto &input : children) { if (SP_IS_FEMERGENODE(&input)) { SPFeMergeNode *node = SP_FEMERGENODE(&input); nr_merge->set_input(in_nr, node->input); @@ -102,7 +108,6 @@ void SPFeMerge::build_renderer(Inkscape::Filters::Filter* filter) { } } - /* Local Variables: mode:c++ diff --git a/src/object/filters/merge.h b/src/object/filters/merge.h index 66216743e04938f1f13b739a519763bdcf9a407d..3e4fa4b8dd1084ff39e61fe44d1a645cea39e0b1 100644 --- a/src/object/filters/merge.h +++ b/src/object/filters/merge.h @@ -13,25 +13,26 @@ #include "sp-filter-primitive.h" -#define SP_FEMERGE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FEMERGE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FEMERGE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FEMERGE(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPFeMerge : public SPFilterPrimitive { +class SPFeMerge : public SPFilterPrimitive +{ public: - SPFeMerge(); + SPFeMerge(); ~SPFeMerge() override; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FEMERGE_H_SEEN */ diff --git a/src/object/filters/mergenode.cpp b/src/object/filters/mergenode.cpp index 59f0d3f269177f2542d8547d2952d9916049f004..fd81252de09fe076d619f9e590337766e0e76c6b 100644 --- a/src/object/filters/mergenode.cpp +++ b/src/object/filters/mergenode.cpp @@ -15,17 +15,16 @@ */ #include "mergenode.h" -#include "merge.h" #include "attributes.h" - #include "display/nr-filter-types.h" - +#include "merge.h" #include "xml/repr.h" SPFeMergeNode::SPFeMergeNode() - : SPObject(), input(Inkscape::Filters::NR_FILTER_SLOT_NOT_SET) { -} + : SPObject() + , input(Inkscape::Filters::NR_FILTER_SLOT_NOT_SET) +{} SPFeMergeNode::~SPFeMergeNode() = default; @@ -34,21 +33,24 @@ SPFeMergeNode::~SPFeMergeNode() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeMergeNode::build(SPDocument */*document*/, Inkscape::XML::Node */*repr*/) { - this->readAttr(SPAttr::IN_); +void SPFeMergeNode::build(SPDocument * /*document*/, Inkscape::XML::Node * /*repr*/) +{ + this->readAttr(SPAttr::IN_); } /** * Drops any allocated memory. */ -void SPFeMergeNode::release() { - SPObject::release(); +void SPFeMergeNode::release() +{ + SPObject::release(); } /** * Sets a specific value in the SPFeMergeNode. */ -void SPFeMergeNode::set(SPAttr key, gchar const *value) { +void SPFeMergeNode::set(SPAttr key, gchar const *value) +{ SPFeMerge *parent = SP_FEMERGE(this->parent); if (key == SPAttr::IN_) { @@ -66,7 +68,8 @@ void SPFeMergeNode::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeMergeNode::update(SPCtx *ctx, guint flags) { +void SPFeMergeNode::update(SPCtx *ctx, guint flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } @@ -77,12 +80,13 @@ void SPFeMergeNode::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeMergeNode::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeMergeNode::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ // Inkscape-only this, not copied during an "plain SVG" dump: if (flags & SP_OBJECT_WRITE_EXT) { if (repr) { // is this sane? - //repr->mergeFrom(object->getRepr(), "id"); + // repr->mergeFrom(object->getRepr(), "id"); } else { repr = this->getRepr()->duplicate(doc); } @@ -93,7 +97,6 @@ Inkscape::XML::Node* SPFeMergeNode::write(Inkscape::XML::Document *doc, Inkscape return repr; } - /* Local Variables: mode:c++ diff --git a/src/object/filters/mergenode.h b/src/object/filters/mergenode.h index a06513777fdf2e0d49a9129420d73603f00a1794..4c7a4850ed8c9a5156638e0ddb4ce8b30726b8ae 100644 --- a/src/object/filters/mergenode.h +++ b/src/object/filters/mergenode.h @@ -18,25 +18,26 @@ #include "object/sp-object.h" -#define SP_FEMERGENODE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FEMERGENODE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FEMERGENODE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FEMERGENODE(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPFeMergeNode : public SPObject { +class SPFeMergeNode : public SPObject +{ public: - SPFeMergeNode(); - ~SPFeMergeNode() override; + SPFeMergeNode(); + ~SPFeMergeNode() override; int input; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; }; #endif /* !SP_FEMERGENODE_H_SEEN */ diff --git a/src/object/filters/morphology.cpp b/src/object/filters/morphology.cpp index 532705f5a5317756e454ae7f48e4e0f8ee5a71cb..3f55a625f9b7bf76959ba670dec787f415012342 100644 --- a/src/object/filters/morphology.cpp +++ b/src/object/filters/morphology.cpp @@ -14,18 +14,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "morphology.h" + #include #include "attributes.h" +#include "display/nr-filter.h" #include "svg/svg.h" -#include "morphology.h" #include "xml/repr.h" -#include "display/nr-filter.h" -SPFeMorphology::SPFeMorphology() : SPFilterPrimitive() { - this->Operator = Inkscape::Filters::MORPHOLOGY_OPERATOR_ERODE; +SPFeMorphology::SPFeMorphology() + : SPFilterPrimitive() +{ + this->Operator = Inkscape::Filters::MORPHOLOGY_OPERATOR_ERODE; - //Setting default values: + // Setting default values: this->radius.set("0"); } @@ -36,54 +39,58 @@ SPFeMorphology::~SPFeMorphology() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeMorphology::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); +void SPFeMorphology::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); - /*LOAD ATTRIBUTES FROM REPR HERE*/ - this->readAttr(SPAttr::OPERATOR); - this->readAttr(SPAttr::RADIUS); + /*LOAD ATTRIBUTES FROM REPR HERE*/ + this->readAttr(SPAttr::OPERATOR); + this->readAttr(SPAttr::RADIUS); } /** * Drops any allocated memory. */ -void SPFeMorphology::release() { - SPFilterPrimitive::release(); +void SPFeMorphology::release() +{ + SPFilterPrimitive::release(); } -static Inkscape::Filters::FilterMorphologyOperator sp_feMorphology_read_operator(gchar const *value){ +static Inkscape::Filters::FilterMorphologyOperator sp_feMorphology_read_operator(gchar const *value) +{ if (!value) { - return Inkscape::Filters::MORPHOLOGY_OPERATOR_ERODE; //erode is default + return Inkscape::Filters::MORPHOLOGY_OPERATOR_ERODE; // erode is default } - - switch(value[0]){ + + switch (value[0]) { case 'e': if (strncmp(value, "erode", 5) == 0) { - return Inkscape::Filters::MORPHOLOGY_OPERATOR_ERODE; + return Inkscape::Filters::MORPHOLOGY_OPERATOR_ERODE; } break; case 'd': if (strncmp(value, "dilate", 6) == 0) { - return Inkscape::Filters::MORPHOLOGY_OPERATOR_DILATE; + return Inkscape::Filters::MORPHOLOGY_OPERATOR_DILATE; } break; } - - return Inkscape::Filters::MORPHOLOGY_OPERATOR_ERODE; //erode is default + + return Inkscape::Filters::MORPHOLOGY_OPERATOR_ERODE; // erode is default } /** * Sets a specific value in the SPFeMorphology. */ -void SPFeMorphology::set(SPAttr key, gchar const *value) { +void SPFeMorphology::set(SPAttr key, gchar const *value) +{ Inkscape::Filters::FilterMorphologyOperator read_operator; - - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ + + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ case SPAttr::OPERATOR: read_operator = sp_feMorphology_read_operator(value); - if (read_operator != this->Operator){ + if (read_operator != this->Operator) { this->Operator = read_operator; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } @@ -91,7 +98,7 @@ void SPFeMorphology::set(SPAttr key, gchar const *value) { case SPAttr::RADIUS: this->radius.set(value); - //From SVG spec: If is not provided, it defaults to . + // From SVG spec: If is not provided, it defaults to . if (this->radius.optNumIsSet() == false) { this->radius.setOptNumber(this->radius.getNumber()); } @@ -99,21 +106,18 @@ void SPFeMorphology::set(SPAttr key, gchar const *value) { this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } - } /** * Receives update notifications. */ -void SPFeMorphology::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - +void SPFeMorphology::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something to trigger redisplay, updates? */ - } SPFilterPrimitive::update(ctx, flags); @@ -122,8 +126,9 @@ void SPFeMorphology::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeMorphology::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { - /* TODO: Don't just clone, but create a new repr node and write all +Inkscape::XML::Node *SPFeMorphology::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ + /* TODO: Don't just clone, but create a new repr node and write all * relevant values into it */ if (!repr) { repr = this->getRepr()->duplicate(doc); @@ -134,19 +139,21 @@ Inkscape::XML::Node* SPFeMorphology::write(Inkscape::XML::Document *doc, Inkscap return repr; } -void SPFeMorphology::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeMorphology::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_MORPHOLOGY); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterMorphology *nr_morphology = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterMorphology *nr_morphology = + dynamic_cast(nr_primitive); g_assert(nr_morphology != nullptr); this->renderer_common(nr_primitive); - + nr_morphology->set_operator(this->Operator); - nr_morphology->set_xradius( this->radius.getNumber() ); - nr_morphology->set_yradius( this->radius.getOptNumber() ); + nr_morphology->set_xradius(this->radius.getNumber()); + nr_morphology->set_yradius(this->radius.getOptNumber()); } /* diff --git a/src/object/filters/morphology.h b/src/object/filters/morphology.h index 0ae54adabadd4e235d1e5471b61fbc47a86a64a9..507702716cd80b29b96f40eb32911c4e9290aeb5 100644 --- a/src/object/filters/morphology.h +++ b/src/object/filters/morphology.h @@ -13,32 +13,33 @@ #ifndef SP_FEMORPHOLOGY_H_SEEN #define SP_FEMORPHOLOGY_H_SEEN -#include "sp-filter-primitive.h" -#include "number-opt-number.h" #include "display/nr-filter-morphology.h" +#include "number-opt-number.h" +#include "sp-filter-primitive.h" -#define SP_FEMORPHOLOGY(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FEMORPHOLOGY(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FEMORPHOLOGY(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FEMORPHOLOGY(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPFeMorphology : public SPFilterPrimitive { +class SPFeMorphology : public SPFilterPrimitive +{ public: - SPFeMorphology(); - ~SPFeMorphology() override; + SPFeMorphology(); + ~SPFeMorphology() override; Inkscape::Filters::FilterMorphologyOperator Operator; NumberOptNumber radius; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FEMORPHOLOGY_H_SEEN */ diff --git a/src/object/filters/offset.cpp b/src/object/filters/offset.cpp index 51e81d8dbf97f186decdd1ee1cd8b752870331a3..f88327f84ec9685bbb6a18dbbdf8643a931adf2a 100644 --- a/src/object/filters/offset.cpp +++ b/src/object/filters/offset.cpp @@ -17,16 +17,15 @@ #include "offset.h" #include "attributes.h" -#include "helper-fns.h" - -#include "display/nr-filter.h" #include "display/nr-filter-offset.h" - +#include "display/nr-filter.h" +#include "helper-fns.h" #include "svg/svg.h" - #include "xml/repr.h" -SPFeOffset::SPFeOffset() : SPFilterPrimitive() { +SPFeOffset::SPFeOffset() + : SPFilterPrimitive() +{ this->dx = 0; this->dy = 0; } @@ -38,27 +37,30 @@ SPFeOffset::~SPFeOffset() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeOffset::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); +void SPFeOffset::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); - this->readAttr(SPAttr::DX); - this->readAttr(SPAttr::DY); + this->readAttr(SPAttr::DX); + this->readAttr(SPAttr::DY); } /** * Drops any allocated memory. */ -void SPFeOffset::release() { - SPFilterPrimitive::release(); +void SPFeOffset::release() +{ + SPFilterPrimitive::release(); } /** * Sets a specific value in the SPFeOffset. */ -void SPFeOffset::set(SPAttr key, gchar const *value) { +void SPFeOffset::set(SPAttr key, gchar const *value) +{ double read_num; - switch(key) { + switch (key) { case SPAttr::DX: read_num = value ? helperfns_read_number(value) : 0; @@ -75,10 +77,10 @@ void SPFeOffset::set(SPAttr key, gchar const *value) { this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; - - /*DEAL WITH SETTING ATTRIBUTES HERE*/ + + /*DEAL WITH SETTING ATTRIBUTES HERE*/ default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -86,7 +88,8 @@ void SPFeOffset::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeOffset::update(SPCtx *ctx, guint flags) { +void SPFeOffset::update(SPCtx *ctx, guint flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { this->readAttr(SPAttr::DX); this->readAttr(SPAttr::DY); @@ -98,7 +101,8 @@ void SPFeOffset::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeOffset::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeOffset::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values into it */ if (!repr) { @@ -110,12 +114,13 @@ Inkscape::XML::Node* SPFeOffset::write(Inkscape::XML::Document *doc, Inkscape::X return repr; } -void SPFeOffset::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeOffset::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_OFFSET); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterOffset *nr_offset = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterOffset *nr_offset = dynamic_cast(nr_primitive); g_assert(nr_offset != nullptr); this->renderer_common(nr_primitive); @@ -124,7 +129,6 @@ void SPFeOffset::build_renderer(Inkscape::Filters::Filter* filter) { nr_offset->set_dy(this->dy); } - /* Local Variables: mode:c++ diff --git a/src/object/filters/offset.h b/src/object/filters/offset.h index f847da16a9f126539537bcfe6f719d49983652f2..3ae4410bfd15690161097166216b9a1a667c92b6 100644 --- a/src/object/filters/offset.h +++ b/src/object/filters/offset.h @@ -15,27 +15,28 @@ #include "sp-filter-primitive.h" -#define SP_FEOFFSET(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FEOFFSET(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FEOFFSET(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FEOFFSET(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPFeOffset : public SPFilterPrimitive { +class SPFeOffset : public SPFilterPrimitive +{ public: - SPFeOffset(); - ~SPFeOffset() override; + SPFeOffset(); + ~SPFeOffset() override; double dx, dy; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FEOFFSET_H_SEEN */ diff --git a/src/object/filters/pointlight.cpp b/src/object/filters/pointlight.cpp index 9e5fe201320084a5cca170c7e87ca7c0b2cd8506..a9504ae9b0ac95a38bee8a4badaafcb39763f608 100644 --- a/src/object/filters/pointlight.cpp +++ b/src/object/filters/pointlight.cpp @@ -16,138 +16,139 @@ // Same directory #include "pointlight.h" -#include "diffuselighting.h" -#include "specularlighting.h" #include #include "attributes.h" +#include "diffuselighting.h" #include "document.h" - - +#include "specularlighting.h" #include "xml/node.h" #include "xml/repr.h" -SPFePointLight::SPFePointLight() - : SPObject(), x(0), x_set(FALSE), y(0), y_set(FALSE), z(0), z_set(FALSE) { -} +SPFePointLight::SPFePointLight() + : SPObject() + , x(0) + , x_set(FALSE) + , y(0) + , y_set(FALSE) + , z(0) + , z_set(FALSE) +{} SPFePointLight::~SPFePointLight() = default; - /** * Reads the Inkscape::XML::Node, and initializes SPPointLight variables. For this to get called, * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFePointLight::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPObject::build(document, repr); +void SPFePointLight::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPObject::build(document, repr); - //Read values of key attributes from XML nodes into object. + // Read values of key attributes from XML nodes into object. this->readAttr(SPAttr::X); this->readAttr(SPAttr::Y); this->readAttr(SPAttr::Z); -//is this necessary? + // is this necessary? document->addResource("fepointlight", this); } /** * Drops any allocated memory. */ -void SPFePointLight::release() { - if ( this->document ) { +void SPFePointLight::release() +{ + if (this->document) { // Unregister ourselves this->document->removeResource("fepointlight", this); } -//TODO: release resources here + // TODO: release resources here } /** * Sets a specific value in the SPFePointLight. */ -void SPFePointLight::set(SPAttr key, gchar const *value) { +void SPFePointLight::set(SPAttr key, gchar const *value) +{ gchar *end_ptr; switch (key) { - case SPAttr::X: - end_ptr = nullptr; + case SPAttr::X: + end_ptr = nullptr; + + if (value) { + this->x = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->x_set = TRUE; + } + } + + if (!value || !end_ptr) { + this->x = 0; + this->x_set = FALSE; + } + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); + } + break; + case SPAttr::Y: + end_ptr = nullptr; + + if (value) { + this->y = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->y_set = TRUE; + } + } - if (value) { - this->x = g_ascii_strtod(value, &end_ptr); + if (!value || !end_ptr) { + this->y = 0; + this->y_set = FALSE; + } + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); + } + break; + case SPAttr::Z: + end_ptr = nullptr; - if (end_ptr) { - this->x_set = TRUE; + if (value) { + this->z = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->z_set = TRUE; + } } - } - - if (!value || !end_ptr) { - this->x = 0; - this->x_set = FALSE; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - case SPAttr::Y: - end_ptr = nullptr; - - if (value) { - this->y = g_ascii_strtod(value, &end_ptr); - - if (end_ptr) { - this->y_set = TRUE; + + if (!value || !end_ptr) { + this->z = 0; + this->z_set = FALSE; } - } - - if (!value || !end_ptr) { - this->y = 0; - this->y_set = FALSE; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - case SPAttr::Z: - end_ptr = nullptr; - - if (value) { - this->z = g_ascii_strtod(value, &end_ptr); - - if (end_ptr) { - this->z_set = TRUE; + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } - } - - if (!value || !end_ptr) { - this->z = 0; - this->z_set = FALSE; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - default: - // See if any parents need this value. - SPObject::set(key, value); - break; + break; + default: + // See if any parents need this value. + SPObject::set(key, value); + break; } } /** * * Receives update notifications. * */ -void SPFePointLight::update(SPCtx *ctx, guint flags) { +void SPFePointLight::update(SPCtx *ctx, guint flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { /* do something to trigger redisplay, updates? */ this->readAttr(SPAttr::X); @@ -161,7 +162,8 @@ void SPFePointLight::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFePointLight::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFePointLight::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ if (!repr) { repr = this->getRepr()->duplicate(doc); } diff --git a/src/object/filters/pointlight.h b/src/object/filters/pointlight.h index 6091b4396ef50c2fa41c442d258e8df8df85f8bb..0930ca02146a62e76b2df1e2f93d5e08be4dc207 100644 --- a/src/object/filters/pointlight.h +++ b/src/object/filters/pointlight.h @@ -18,33 +18,34 @@ #include "object/sp-object.h" -#define SP_FEPOINTLIGHT(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FEPOINTLIGHT(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FEPOINTLIGHT(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FEPOINTLIGHT(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPFePointLight : public SPObject { +class SPFePointLight : public SPObject +{ public: - SPFePointLight(); - ~SPFePointLight() override; + SPFePointLight(); + ~SPFePointLight() override; /** x coordinate of the light source */ - float x; + float x; unsigned int x_set : 1; /** y coordinate of the light source */ - float y; + float y; unsigned int y_set : 1; /** z coordinate of the light source */ - float z; + float z; unsigned int z_set : 1; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif /* !SP_FEPOINTLIGHT_H_SEEN */ diff --git a/src/object/filters/sp-filter-primitive.cpp b/src/object/filters/sp-filter-primitive.cpp index 6c0a787f42e48cbd02004d43293ce865a5815e5c..89e87958fbd48e3679ec6f8763606cbf0ee670d4 100644 --- a/src/object/filters/sp-filter-primitive.cpp +++ b/src/object/filters/sp-filter-primitive.cpp @@ -14,23 +14,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include - #include "sp-filter-primitive.h" -#include "attributes.h" +#include +#include "attributes.h" #include "display/nr-filter-primitive.h" - #include "style.h" - // CPPIFY: Make pure virtual. -//void SPFilterPrimitive::build_renderer(Inkscape::Filters::Filter* filter) { +// void SPFilterPrimitive::build_renderer(Inkscape::Filters::Filter* filter) { // throw; //} -SPFilterPrimitive::SPFilterPrimitive() : SPObject() { +SPFilterPrimitive::SPFilterPrimitive() + : SPObject() +{ this->image_in = Inkscape::Filters::NR_FILTER_SLOT_NOT_SET; this->image_out = Inkscape::Filters::NR_FILTER_SLOT_NOT_SET; @@ -52,8 +51,9 @@ SPFilterPrimitive::~SPFilterPrimitive() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFilterPrimitive::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive* object = this; +void SPFilterPrimitive::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive *object = this; object->readAttr(SPAttr::STYLE); // struct not derived from SPItem, we need to do this ourselves. object->readAttr(SPAttr::IN_); @@ -69,15 +69,16 @@ void SPFilterPrimitive::build(SPDocument *document, Inkscape::XML::Node *repr) { /** * Drops any allocated memory. */ -void SPFilterPrimitive::release() { +void SPFilterPrimitive::release() +{ SPObject::release(); } /** * Sets a specific value in the SPFilterPrimitive. */ -void SPFilterPrimitive::set(SPAttr key, gchar const *value) { - +void SPFilterPrimitive::set(SPAttr key, gchar const *value) +{ int image_nr; switch (key) { case SPAttr::IN_: @@ -129,14 +130,14 @@ void SPFilterPrimitive::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFilterPrimitive::update(SPCtx *ctx, guint flags) { - - SPItemCtx *ictx = (SPItemCtx *) ctx; +void SPFilterPrimitive::update(SPCtx *ctx, guint flags) +{ + SPItemCtx *ictx = (SPItemCtx *)ctx; // Do here since we know viewport (Bounding box case handled during rendering) SPFilter *parent = SP_FILTER(this->parent); - if( parent->primitiveUnits == SP_FILTER_UNITS_USERSPACEONUSE ) { + if (parent->primitiveUnits == SP_FILTER_UNITS_USERSPACEONUSE) { this->calcDimsFromParentViewport(ictx, true); } @@ -146,8 +147,9 @@ void SPFilterPrimitive::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFilterPrimitive::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { - SPFilterPrimitive* object = this; +Inkscape::XML::Node *SPFilterPrimitive::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ + SPFilterPrimitive *object = this; SPFilterPrimitive *prim = SP_FILTER_PRIMITIVE(object); SPFilter *parent = SP_FILTER(object->parent); @@ -170,7 +172,7 @@ Inkscape::XML::Node* SPFilterPrimitive::write(Inkscape::XML::Document *doc, Inks int SPFilterPrimitive::read_in(gchar const *name) { - if (!name){ + if (!name) { return Inkscape::Filters::NR_FILTER_SLOT_NOT_SET; } // TODO: are these case sensitive or not? (assumed yes) @@ -197,7 +199,8 @@ int SPFilterPrimitive::read_in(gchar const *name) SPFilter *parent = SP_FILTER(this->parent); int ret = parent->get_image_name(name); - if (ret >= 0) return ret; + if (ret >= 0) + return ret; return Inkscape::Filters::NR_FILTER_SLOT_NOT_SET; } @@ -206,10 +209,12 @@ int SPFilterPrimitive::read_result(gchar const *name) { SPFilter *parent = SP_FILTER(this->parent); int ret = parent->get_image_name(name); - if (ret >= 0) return ret; + if (ret >= 0) + return ret; ret = parent->set_image_name(name); - if (ret >= 0) return ret; + if (ret >= 0) + return ret; return Inkscape::Filters::NR_FILTER_SLOT_NOT_SET; } @@ -220,7 +225,8 @@ int SPFilterPrimitive::read_result(gchar const *name) * of previous primitive, or NR_FILTER_SOURCEGRAPHIC if this is the first * primitive. */ -int SPFilterPrimitive::name_previous_out() { +int SPFilterPrimitive::name_previous_out() +{ SPFilter *parent = SP_FILTER(this->parent); SPObject *i = parent->firstChild(); while (i && i->getNext() != this) { @@ -232,7 +238,7 @@ int SPFilterPrimitive::name_previous_out() { Glib::ustring name = parent->get_new_result_name(); int slot = parent->set_image_name(name.c_str()); i_prim->image_out = slot; - //XML Tree is being directly used while it shouldn't be. + // XML Tree is being directly used while it shouldn't be. i_prim->setAttributeOrRemoveIfEmpty("result", name); return slot; } else { @@ -247,20 +253,17 @@ void SPFilterPrimitive::renderer_common(Inkscape::Filters::FilterPrimitive *nr_p { g_assert(nr_prim != nullptr); - nr_prim->set_input(this->image_in); nr_prim->set_output(this->image_out); /* TODO: place here code to handle input images, filter area etc. */ // We don't know current viewport or bounding box, this is wrong approach. - nr_prim->set_subregion( this->x, this->y, this->width, this->height ); + nr_prim->set_subregion(this->x, this->y, this->width, this->height); // Give renderer access to filter properties - nr_prim->setStyle( this->style ); + nr_prim->setStyle(this->style); } - - /* Local Variables: mode:c++ diff --git a/src/object/filters/sp-filter-primitive.h b/src/object/filters/sp-filter-primitive.h index ed74c1fd20bb563c017d0a1020bfbdbaadb070fc..f52857f1a2a8fa143d00f146264fdcc36140f955 100644 --- a/src/object/filters/sp-filter-primitive.h +++ b/src/object/filters/sp-filter-primitive.h @@ -15,44 +15,48 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "../sp-object.h" #include "../sp-dimensions.h" +#include "../sp-object.h" -#define SP_FILTER_PRIMITIVE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FILTER_PRIMITIVE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FILTER_PRIMITIVE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FILTER_PRIMITIVE(obj) (dynamic_cast((SPObject *)obj) != NULL) namespace Inkscape { namespace Filters { class Filter; class FilterPrimitive; -} } +} // namespace Filters +} // namespace Inkscape -class SPFilterPrimitive : public SPObject, public SPDimensions { +class SPFilterPrimitive + : public SPObject + , public SPDimensions +{ public: - SPFilterPrimitive(); - ~SPFilterPrimitive() override; + SPFilterPrimitive(); + ~SPFilterPrimitive() override; int image_in, image_out; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; public: - virtual void build_renderer(Inkscape::Filters::Filter* filter) = 0; + virtual void build_renderer(Inkscape::Filters::Filter *filter) = 0; - /* Common initialization for filter primitives */ - void renderer_common(Inkscape::Filters::FilterPrimitive *nr_prim); + /* Common initialization for filter primitives */ + void renderer_common(Inkscape::Filters::FilterPrimitive *nr_prim); - int name_previous_out(); - int read_in(char const *name); - int read_result(char const *name); + int name_previous_out(); + int read_in(char const *name); + int read_result(char const *name); }; #endif diff --git a/src/object/filters/specularlighting.cpp b/src/object/filters/specularlighting.cpp index eb9dd9467934f2326abc7767cf1955908d522a46..977c71ac7e511111961c9b00a5f0d9c35f9a34ff 100644 --- a/src/object/filters/specularlighting.cpp +++ b/src/object/filters/specularlighting.cpp @@ -17,37 +17,35 @@ // Same directory #include "specularlighting.h" -#include "distantlight.h" -#include "pointlight.h" -#include "spotlight.h" #include "attributes.h" -#include "strneq.h" - -#include "display/nr-filter.h" #include "display/nr-filter-specularlighting.h" - +#include "display/nr-filter.h" +#include "distantlight.h" #include "object/sp-object.h" - -#include "svg/svg.h" +#include "pointlight.h" +#include "spotlight.h" +#include "strneq.h" #include "svg/svg-color.h" #include "svg/svg-icc-color.h" - +#include "svg/svg.h" #include "xml/repr.h" /* FeSpecularLighting base class */ static void sp_feSpecularLighting_children_modified(SPFeSpecularLighting *sp_specularlighting); -SPFeSpecularLighting::SPFeSpecularLighting() : SPFilterPrimitive() { +SPFeSpecularLighting::SPFeSpecularLighting() + : SPFilterPrimitive() +{ this->surfaceScale = 1; this->specularConstant = 1; this->specularExponent = 1; this->lighting_color = 0xffffffff; this->icc = nullptr; - //TODO kernelUnit + // TODO kernelUnit this->renderer = nullptr; - + this->surfaceScale_set = FALSE; this->specularConstant_set = FALSE; this->specularExponent_set = FALSE; @@ -61,34 +59,37 @@ SPFeSpecularLighting::~SPFeSpecularLighting() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeSpecularLighting::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); - - /*LOAD ATTRIBUTES FROM REPR HERE*/ - this->readAttr(SPAttr::SURFACESCALE); - this->readAttr(SPAttr::SPECULARCONSTANT); - this->readAttr(SPAttr::SPECULAREXPONENT); - this->readAttr(SPAttr::KERNELUNITLENGTH); - this->readAttr(SPAttr::LIGHTING_COLOR); +void SPFeSpecularLighting::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); + + /*LOAD ATTRIBUTES FROM REPR HERE*/ + this->readAttr(SPAttr::SURFACESCALE); + this->readAttr(SPAttr::SPECULARCONSTANT); + this->readAttr(SPAttr::SPECULAREXPONENT); + this->readAttr(SPAttr::KERNELUNITLENGTH); + this->readAttr(SPAttr::LIGHTING_COLOR); } /** * Drops any allocated memory. */ -void SPFeSpecularLighting::release() { - SPFilterPrimitive::release(); +void SPFeSpecularLighting::release() +{ + SPFilterPrimitive::release(); } /** * Sets a specific value in the SPFeSpecularLighting. */ -void SPFeSpecularLighting::set(SPAttr key, gchar const *value) { +void SPFeSpecularLighting::set(SPAttr key, gchar const *value) +{ gchar const *cend_ptr = nullptr; gchar *end_ptr = nullptr; - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ -//TODO test forbidden values + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ + // TODO test forbidden values case SPAttr::SURFACESCALE: end_ptr = nullptr; if (value) { @@ -98,9 +99,8 @@ void SPFeSpecularLighting::set(SPAttr key, gchar const *value) { } else { g_warning("this: surfaceScale should be a number ... defaulting to 1"); } - } - //if the attribute is not set or has an unreadable value + // if the attribute is not set or has an unreadable value if (!value || !end_ptr) { this->surfaceScale = 1; this->surfaceScale_set = FALSE; @@ -140,7 +140,7 @@ void SPFeSpecularLighting::set(SPAttr key, gchar const *value) { end_ptr = nullptr; g_warning("this: specularExponent should be a number in range [1, 128] ... defaulting to 1"); } - } + } if (!value || !end_ptr) { this->specularExponent = 1; this->specularExponent_set = FALSE; @@ -151,8 +151,8 @@ void SPFeSpecularLighting::set(SPAttr key, gchar const *value) { this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::KERNELUNITLENGTH: - //TODO kernelUnit - //this->kernelUnitLength.set(value); + // TODO kernelUnit + // this->kernelUnitLength.set(value); /*TODOif (feSpecularLighting->renderer) { feSpecularLighting->renderer->surfaceScale = feSpecularLighting->renderer; } @@ -162,21 +162,22 @@ void SPFeSpecularLighting::set(SPAttr key, gchar const *value) { case SPAttr::LIGHTING_COLOR: cend_ptr = nullptr; this->lighting_color = sp_svg_read_color(value, &cend_ptr, 0xffffffff); - //if a value was read + // if a value was read if (cend_ptr) { while (g_ascii_isspace(*cend_ptr)) { ++cend_ptr; } if (strneq(cend_ptr, "icc-color(", 10)) { - if (!this->icc) this->icc = new SVGICCColor(); - if ( ! sp_svg_read_icc_color( cend_ptr, this->icc ) ) { + if (!this->icc) + this->icc = new SVGICCColor(); + if (!sp_svg_read_icc_color(cend_ptr, this->icc)) { delete this->icc; this->icc = nullptr; } } this->lighting_color_set = TRUE; } else { - //lighting_color already contains the default value + // lighting_color already contains the default value this->lighting_color_set = FALSE; } if (this->renderer) { @@ -185,7 +186,7 @@ void SPFeSpecularLighting::set(SPAttr key, gchar const *value) { this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -193,7 +194,8 @@ void SPFeSpecularLighting::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeSpecularLighting::update(SPCtx *ctx, guint flags) { +void SPFeSpecularLighting::update(SPCtx *ctx, guint flags) +{ if (flags & (SP_OBJECT_MODIFIED_FLAG)) { this->readAttr(SPAttr::SURFACESCALE); this->readAttr(SPAttr::SPECULARCONSTANT); @@ -208,12 +210,13 @@ void SPFeSpecularLighting::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeSpecularLighting::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeSpecularLighting::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values _and children_ into it */ if (!repr) { repr = this->getRepr()->duplicate(doc); - //repr = doc->createElement("svg:feSpecularLighting"); + // repr = doc->createElement("svg:feSpecularLighting"); } if (this->surfaceScale_set) { @@ -228,13 +231,13 @@ Inkscape::XML::Node* SPFeSpecularLighting::write(Inkscape::XML::Document *doc, I sp_repr_set_css_double(repr, "specularExponent", this->specularExponent); } - /*TODO kernelUnits */ + /*TODO kernelUnits */ if (this->lighting_color_set) { gchar c[64]; sp_svg_write_color(c, sizeof(c), this->lighting_color); repr->setAttribute("lighting-color", c); } - + SPFilterPrimitive::write(doc, repr, flags); return repr; @@ -243,7 +246,8 @@ Inkscape::XML::Node* SPFeSpecularLighting::write(Inkscape::XML::Document *doc, I /** * Callback for child_added event. */ -void SPFeSpecularLighting::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { +void SPFeSpecularLighting::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ SPFilterPrimitive::child_added(child, ref); sp_feSpecularLighting_children_modified(this); @@ -253,47 +257,53 @@ void SPFeSpecularLighting::child_added(Inkscape::XML::Node *child, Inkscape::XML /** * Callback for remove_child event. */ -void SPFeSpecularLighting::remove_child(Inkscape::XML::Node *child) { +void SPFeSpecularLighting::remove_child(Inkscape::XML::Node *child) +{ SPFilterPrimitive::remove_child(child); sp_feSpecularLighting_children_modified(this); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } -void SPFeSpecularLighting::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref) { +void SPFeSpecularLighting::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, + Inkscape::XML::Node *new_ref) +{ SPFilterPrimitive::order_changed(child, old_ref, new_ref); sp_feSpecularLighting_children_modified(this); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } -static void sp_feSpecularLighting_children_modified(SPFeSpecularLighting *sp_specularlighting) { - if (sp_specularlighting->renderer) { +static void sp_feSpecularLighting_children_modified(SPFeSpecularLighting *sp_specularlighting) +{ + if (sp_specularlighting->renderer) { sp_specularlighting->renderer->light_type = Inkscape::Filters::NO_LIGHT; - + if (SP_IS_FEDISTANTLIGHT(sp_specularlighting->firstChild())) { sp_specularlighting->renderer->light_type = Inkscape::Filters::DISTANT_LIGHT; sp_specularlighting->renderer->light.distant = SP_FEDISTANTLIGHT(sp_specularlighting->firstChild()); } - + if (SP_IS_FEPOINTLIGHT(sp_specularlighting->firstChild())) { sp_specularlighting->renderer->light_type = Inkscape::Filters::POINT_LIGHT; sp_specularlighting->renderer->light.point = SP_FEPOINTLIGHT(sp_specularlighting->firstChild()); } - + if (SP_IS_FESPOTLIGHT(sp_specularlighting->firstChild())) { sp_specularlighting->renderer->light_type = Inkscape::Filters::SPOT_LIGHT; sp_specularlighting->renderer->light.spot = SP_FESPOTLIGHT(sp_specularlighting->firstChild()); } - } + } } -void SPFeSpecularLighting::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeSpecularLighting::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_SPECULARLIGHTING); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterSpecularLighting *nr_specularlighting = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterSpecularLighting *nr_specularlighting = + dynamic_cast(nr_primitive); g_assert(nr_specularlighting != nullptr); this->renderer = nr_specularlighting; @@ -305,7 +315,7 @@ void SPFeSpecularLighting::build_renderer(Inkscape::Filters::Filter* filter) { nr_specularlighting->lighting_color = this->lighting_color; nr_specularlighting->set_icc(this->icc); - //We assume there is at most one child + // We assume there is at most one child nr_specularlighting->light_type = Inkscape::Filters::NO_LIGHT; if (SP_IS_FEDISTANTLIGHT(this->firstChild())) { @@ -322,11 +332,10 @@ void SPFeSpecularLighting::build_renderer(Inkscape::Filters::Filter* filter) { nr_specularlighting->light_type = Inkscape::Filters::SPOT_LIGHT; nr_specularlighting->light.spot = SP_FESPOTLIGHT(this->firstChild()); } - - //nr_offset->set_dx(sp_offset->dx); - //nr_offset->set_dy(sp_offset->dy); -} + // nr_offset->set_dx(sp_offset->dx); + // nr_offset->set_dy(sp_offset->dy); +} /* Local Variables: diff --git a/src/object/filters/specularlighting.h b/src/object/filters/specularlighting.h index 2892c3784995664752c688ad194d3fc9dd8fe42b..31954ea299de11b88e66e90714026fad0f529c30 100644 --- a/src/object/filters/specularlighting.h +++ b/src/object/filters/specularlighting.h @@ -15,11 +15,11 @@ #ifndef SP_FESPECULARLIGHTING_H_SEEN #define SP_FESPECULARLIGHTING_H_SEEN -#include "sp-filter-primitive.h" #include "number-opt-number.h" +#include "sp-filter-primitive.h" -#define SP_FESPECULARLIGHTING(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FESPECULARLIGHTING(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FESPECULARLIGHTING(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FESPECULARLIGHTING(obj) (dynamic_cast((SPObject *)obj) != NULL) struct SVGICCColor; @@ -27,12 +27,13 @@ namespace Inkscape { namespace Filters { class FilterSpecularLighting; } -} +} // namespace Inkscape -class SPFeSpecularLighting : public SPFilterPrimitive { +class SPFeSpecularLighting : public SPFilterPrimitive +{ public: - SPFeSpecularLighting(); - ~SPFeSpecularLighting() override; + SPFeSpecularLighting(); + ~SPFeSpecularLighting() override; gfloat surfaceScale; guint surfaceScale_set : 1; @@ -48,21 +49,22 @@ public: Inkscape::Filters::FilterSpecularLighting *renderer; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; - void order_changed(Inkscape::XML::Node* child, Inkscape::XML::Node* old_repr, Inkscape::XML::Node* new_repr) override; + void order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_repr, + Inkscape::XML::Node *new_repr) override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FESPECULARLIGHTING_H_SEEN */ diff --git a/src/object/filters/spotlight.cpp b/src/object/filters/spotlight.cpp index 12c9ac729286caac9cb1ce8b9e3419db71ca6cc3..71e8e5e7d872de20e6fd1b72037fbfc3549b237c 100644 --- a/src/object/filters/spotlight.cpp +++ b/src/object/filters/spotlight.cpp @@ -16,34 +16,45 @@ // Same directory #include "spotlight.h" -#include "diffuselighting.h" -#include "specularlighting.h" #include "attributes.h" +#include "diffuselighting.h" #include "document.h" - +#include "specularlighting.h" #include "xml/repr.h" SPFeSpotLight::SPFeSpotLight() - : SPObject(), x(0), x_set(FALSE), y(0), y_set(FALSE), z(0), z_set(FALSE), pointsAtX(0), pointsAtX_set(FALSE), - pointsAtY(0), pointsAtY_set(FALSE), pointsAtZ(0), pointsAtZ_set(FALSE), - specularExponent(1), specularExponent_set(FALSE), limitingConeAngle(90), - limitingConeAngle_set(FALSE) -{ -} + : SPObject() + , x(0) + , x_set(FALSE) + , y(0) + , y_set(FALSE) + , z(0) + , z_set(FALSE) + , pointsAtX(0) + , pointsAtX_set(FALSE) + , pointsAtY(0) + , pointsAtY_set(FALSE) + , pointsAtZ(0) + , pointsAtZ_set(FALSE) + , specularExponent(1) + , specularExponent_set(FALSE) + , limitingConeAngle(90) + , limitingConeAngle_set(FALSE) +{} SPFeSpotLight::~SPFeSpotLight() = default; - /** * Reads the Inkscape::XML::Node, and initializes SPPointLight variables. For this to get called, * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeSpotLight::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPObject::build(document, repr); +void SPFeSpotLight::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPObject::build(document, repr); - //Read values of key attributes from XML nodes into object. + // Read values of key attributes from XML nodes into object. this->readAttr(SPAttr::X); this->readAttr(SPAttr::Y); this->readAttr(SPAttr::Z); @@ -53,216 +64,203 @@ void SPFeSpotLight::build(SPDocument *document, Inkscape::XML::Node *repr) { this->readAttr(SPAttr::SPECULAREXPONENT); this->readAttr(SPAttr::LIMITINGCONEANGLE); -//is this necessary? + // is this necessary? document->addResource("fespotlight", this); } /** * Drops any allocated memory. */ -void SPFeSpotLight::release() { - if ( this->document ) { +void SPFeSpotLight::release() +{ + if (this->document) { // Unregister ourselves this->document->removeResource("fespotlight", this); } -//TODO: release resources here + // TODO: release resources here } /** * Sets a specific value in the SPFeSpotLight. */ -void SPFeSpotLight::set(SPAttr key, gchar const *value) { +void SPFeSpotLight::set(SPAttr key, gchar const *value) +{ gchar *end_ptr; switch (key) { - case SPAttr::X: - end_ptr = nullptr; - - if (value) { - this->x = g_ascii_strtod(value, &end_ptr); - - if (end_ptr) { - this->x_set = TRUE; + case SPAttr::X: + end_ptr = nullptr; + + if (value) { + this->x = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->x_set = TRUE; + } } - } - - if(!value || !end_ptr) { - this->x = 0; - this->x_set = FALSE; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - case SPAttr::Y: - end_ptr = nullptr; - - if (value) { - this->y = g_ascii_strtod(value, &end_ptr); - - if (end_ptr) { - this->y_set = TRUE; + + if (!value || !end_ptr) { + this->x = 0; + this->x_set = FALSE; } - } - - if(!value || !end_ptr) { - this->y = 0; - this->y_set = FALSE; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - case SPAttr::Z: - end_ptr = nullptr; - - if (value) { - this->z = g_ascii_strtod(value, &end_ptr); - - if (end_ptr) { - this->z_set = TRUE; + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } - } - - if(!value || !end_ptr) { - this->z = 0; - this->z_set = FALSE; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - case SPAttr::POINTSATX: - end_ptr = nullptr; - - if (value) { - this->pointsAtX = g_ascii_strtod(value, &end_ptr); - - if (end_ptr) { - this->pointsAtX_set = TRUE; + break; + case SPAttr::Y: + end_ptr = nullptr; + + if (value) { + this->y = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->y_set = TRUE; + } + } + + if (!value || !end_ptr) { + this->y = 0; + this->y_set = FALSE; } - } - - if(!value || !end_ptr) { - this->pointsAtX = 0; - this->pointsAtX_set = FALSE; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - case SPAttr::POINTSATY: - end_ptr = nullptr; - - if (value) { - this->pointsAtY = g_ascii_strtod(value, &end_ptr); - - if (end_ptr) { - this->pointsAtY_set = TRUE; + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } - } - - if(!value || !end_ptr) { - this->pointsAtY = 0; - this->pointsAtY_set = FALSE; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - case SPAttr::POINTSATZ: - end_ptr = nullptr; - - if (value) { - this->pointsAtZ = g_ascii_strtod(value, &end_ptr); - - if (end_ptr) { - this->pointsAtZ_set = TRUE; + break; + case SPAttr::Z: + end_ptr = nullptr; + + if (value) { + this->z = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->z_set = TRUE; + } } - } - - if(!value || !end_ptr) { - this->pointsAtZ = 0; - this->pointsAtZ_set = FALSE; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - case SPAttr::SPECULAREXPONENT: - end_ptr = nullptr; - - if (value) { - this->specularExponent = g_ascii_strtod(value, &end_ptr); - - if (end_ptr) { - this->specularExponent_set = TRUE; + + if (!value || !end_ptr) { + this->z = 0; + this->z_set = FALSE; } - } - - if(!value || !end_ptr) { - this->specularExponent = 1; - this->specularExponent_set = FALSE; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - case SPAttr::LIMITINGCONEANGLE: - end_ptr = nullptr; - - if (value) { - this->limitingConeAngle = g_ascii_strtod(value, &end_ptr); - - if (end_ptr) { - this->limitingConeAngle_set = TRUE; + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); + } + break; + case SPAttr::POINTSATX: + end_ptr = nullptr; + + if (value) { + this->pointsAtX = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->pointsAtX_set = TRUE; + } + } + + if (!value || !end_ptr) { + this->pointsAtX = 0; + this->pointsAtX_set = FALSE; + } + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } - } - - if(!value || !end_ptr) { - this->limitingConeAngle = 90; - this->limitingConeAngle_set = FALSE; - } - - if (this->parent && - (SP_IS_FEDIFFUSELIGHTING(this->parent) || - SP_IS_FESPECULARLIGHTING(this->parent))) { - this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); - } - break; - default: - // See if any parents need this value. - SPObject::set(key, value); - break; + break; + case SPAttr::POINTSATY: + end_ptr = nullptr; + + if (value) { + this->pointsAtY = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->pointsAtY_set = TRUE; + } + } + + if (!value || !end_ptr) { + this->pointsAtY = 0; + this->pointsAtY_set = FALSE; + } + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); + } + break; + case SPAttr::POINTSATZ: + end_ptr = nullptr; + + if (value) { + this->pointsAtZ = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->pointsAtZ_set = TRUE; + } + } + + if (!value || !end_ptr) { + this->pointsAtZ = 0; + this->pointsAtZ_set = FALSE; + } + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); + } + break; + case SPAttr::SPECULAREXPONENT: + end_ptr = nullptr; + + if (value) { + this->specularExponent = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->specularExponent_set = TRUE; + } + } + + if (!value || !end_ptr) { + this->specularExponent = 1; + this->specularExponent_set = FALSE; + } + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); + } + break; + case SPAttr::LIMITINGCONEANGLE: + end_ptr = nullptr; + + if (value) { + this->limitingConeAngle = g_ascii_strtod(value, &end_ptr); + + if (end_ptr) { + this->limitingConeAngle_set = TRUE; + } + } + + if (!value || !end_ptr) { + this->limitingConeAngle = 90; + this->limitingConeAngle_set = FALSE; + } + + if (this->parent && (SP_IS_FEDIFFUSELIGHTING(this->parent) || SP_IS_FESPECULARLIGHTING(this->parent))) { + this->parent->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); + } + break; + default: + // See if any parents need this value. + SPObject::set(key, value); + break; } } /** * * Receives update notifications. * */ -void SPFeSpotLight::update(SPCtx *ctx, guint flags) { +void SPFeSpotLight::update(SPCtx *ctx, guint flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { /* do something to trigger redisplay, updates? */ this->readAttr(SPAttr::X); @@ -281,7 +279,8 @@ void SPFeSpotLight::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeSpotLight::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeSpotLight::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ if (!repr) { repr = this->getRepr()->duplicate(doc); } diff --git a/src/object/filters/spotlight.h b/src/object/filters/spotlight.h index 55dea72082dcd83c635d6d976bfedb5b5ecdf21b..2c81fc58dea1975a88bdc84a8b7f4c027475fb68 100644 --- a/src/object/filters/spotlight.h +++ b/src/object/filters/spotlight.h @@ -18,22 +18,23 @@ #include "object/sp-object.h" -#define SP_FESPOTLIGHT(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FESPOTLIGHT(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FESPOTLIGHT(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FESPOTLIGHT(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPFeSpotLight : public SPObject { +class SPFeSpotLight : public SPObject +{ public: - SPFeSpotLight(); - ~SPFeSpotLight() override; + SPFeSpotLight(); + ~SPFeSpotLight() override; /** x coordinate of the light source */ - float x; + float x; unsigned int x_set : 1; /** y coordinate of the light source */ - float y; + float y; unsigned int y_set : 1; /** z coordinate of the light source */ - float z; + float z; unsigned int z_set : 1; /** x coordinate of the point the source is pointing at */ float pointsAtX; @@ -50,17 +51,17 @@ public: /** limiting cone angle */ float limitingConeAngle; unsigned int limitingConeAngle_set : 1; - //other fields + // other fields protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif /* !SP_FESPOTLIGHT_H_SEEN */ diff --git a/src/object/filters/tile.cpp b/src/object/filters/tile.cpp index 860ca5a3fc3a00796b8d294e5b8cc913bd21b8ca..5bbacc9eef0ffd3f481e3906c3f42e92941ad5e5 100644 --- a/src/object/filters/tile.cpp +++ b/src/object/filters/tile.cpp @@ -15,16 +15,14 @@ #include "tile.h" #include "attributes.h" - -#include "display/nr-filter.h" #include "display/nr-filter-tile.h" - +#include "display/nr-filter.h" #include "svg/svg.h" - #include "xml/repr.h" -SPFeTile::SPFeTile() : SPFilterPrimitive() { -} +SPFeTile::SPFeTile() + : SPFilterPrimitive() +{} SPFeTile::~SPFeTile() = default; @@ -33,25 +31,28 @@ SPFeTile::~SPFeTile() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeTile::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); +void SPFeTile::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); } /** * Drops any allocated memory. */ -void SPFeTile::release() { - SPFilterPrimitive::release(); +void SPFeTile::release() +{ + SPFilterPrimitive::release(); } /** * Sets a specific value in the SPFeTile. */ -void SPFeTile::set(SPAttr key, gchar const *value) { - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ +void SPFeTile::set(SPAttr key, gchar const *value) +{ + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -59,12 +60,10 @@ void SPFeTile::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeTile::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - +void SPFeTile::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something to trigger redisplay, updates? */ - } SPFilterPrimitive::update(ctx, flags); @@ -73,7 +72,8 @@ void SPFeTile::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeTile::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeTile::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values into it */ if (!repr) { @@ -85,12 +85,13 @@ Inkscape::XML::Node* SPFeTile::write(Inkscape::XML::Document *doc, Inkscape::XML return repr; } -void SPFeTile::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeTile::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_TILE); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterTile *nr_tile = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterTile *nr_tile = dynamic_cast(nr_primitive); g_assert(nr_tile != nullptr); this->renderer_common(nr_primitive); diff --git a/src/object/filters/tile.h b/src/object/filters/tile.h index d13d702766efb0a28c2c65167126623e690c840e..7300f0dba911fbd2ebc05d77a94e868bf437f560 100644 --- a/src/object/filters/tile.h +++ b/src/object/filters/tile.h @@ -15,26 +15,27 @@ #include "sp-filter-primitive.h" -#define SP_FETILE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FETILE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FETILE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FETILE(obj) (dynamic_cast((SPObject *)obj) != NULL) /* FeTile base class */ -class SPFeTile : public SPFilterPrimitive { +class SPFeTile : public SPFilterPrimitive +{ public: - SPFeTile(); + SPFeTile(); ~SPFeTile() override; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FETILE_H_SEEN */ diff --git a/src/object/filters/turbulence.cpp b/src/object/filters/turbulence.cpp index d8fe979596bf8bd537834982f741b35df46f0d97..4b45585d037e30e65c0e12cf0c8e7cc800744116 100644 --- a/src/object/filters/turbulence.cpp +++ b/src/object/filters/turbulence.cpp @@ -15,21 +15,23 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "attributes.h" -#include "svg/svg.h" #include "turbulence.h" -#include "helper-fns.h" -#include "xml/repr.h" +#include "attributes.h" #include "display/nr-filter.h" +#include "helper-fns.h" +#include "svg/svg.h" +#include "xml/repr.h" -SPFeTurbulence::SPFeTurbulence() : SPFilterPrimitive() { - this->stitchTiles = false; - this->seed = 0; - this->numOctaves = 0; - this->type = Inkscape::Filters::TURBULENCE_FRACTALNOISE; +SPFeTurbulence::SPFeTurbulence() + : SPFilterPrimitive() +{ + this->stitchTiles = false; + this->seed = 0; + this->numOctaves = 0; + this->type = Inkscape::Filters::TURBULENCE_FRACTALNOISE; - this->updated=false; + this->updated = false; } SPFeTurbulence::~SPFeTurbulence() = default; @@ -39,38 +41,41 @@ SPFeTurbulence::~SPFeTurbulence() = default; * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFeTurbulence::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPFilterPrimitive::build(document, repr); - - /*LOAD ATTRIBUTES FROM REPR HERE*/ - this->readAttr(SPAttr::BASEFREQUENCY); - this->readAttr(SPAttr::NUMOCTAVES); - this->readAttr(SPAttr::SEED); - this->readAttr(SPAttr::STITCHTILES); - this->readAttr(SPAttr::TYPE); +void SPFeTurbulence::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPFilterPrimitive::build(document, repr); + + /*LOAD ATTRIBUTES FROM REPR HERE*/ + this->readAttr(SPAttr::BASEFREQUENCY); + this->readAttr(SPAttr::NUMOCTAVES); + this->readAttr(SPAttr::SEED); + this->readAttr(SPAttr::STITCHTILES); + this->readAttr(SPAttr::TYPE); } /** * Drops any allocated memory. */ -void SPFeTurbulence::release() { - SPFilterPrimitive::release(); +void SPFeTurbulence::release() +{ + SPFilterPrimitive::release(); } -static bool sp_feTurbulence_read_stitchTiles(gchar const *value){ +static bool sp_feTurbulence_read_stitchTiles(gchar const *value) +{ if (!value) { - return false; // 'noStitch' is default + return false; // 'noStitch' is default } - switch(value[0]){ + switch (value[0]) { case 's': if (strncmp(value, "stitch", 6) == 0) { - return true; + return true; } break; case 'n': if (strncmp(value, "noStitch", 8) == 0) { - return false; + return false; } break; } @@ -78,20 +83,21 @@ static bool sp_feTurbulence_read_stitchTiles(gchar const *value){ return false; // 'noStitch' is default } -static Inkscape::Filters::FilterTurbulenceType sp_feTurbulence_read_type(gchar const *value){ +static Inkscape::Filters::FilterTurbulenceType sp_feTurbulence_read_type(gchar const *value) +{ if (!value) { - return Inkscape::Filters::TURBULENCE_TURBULENCE; // 'turbulence' is default + return Inkscape::Filters::TURBULENCE_TURBULENCE; // 'turbulence' is default } - switch(value[0]){ + switch (value[0]) { case 'f': if (strncmp(value, "fractalNoise", 12) == 0) { - return Inkscape::Filters::TURBULENCE_FRACTALNOISE; + return Inkscape::Filters::TURBULENCE_FRACTALNOISE; } break; case 't': if (strncmp(value, "turbulence", 10) == 0) { - return Inkscape::Filters::TURBULENCE_TURBULENCE; + return Inkscape::Filters::TURBULENCE_TURBULENCE; } break; } @@ -102,14 +108,15 @@ static Inkscape::Filters::FilterTurbulenceType sp_feTurbulence_read_type(gchar c /** * Sets a specific value in the SPFeTurbulence. */ -void SPFeTurbulence::set(SPAttr key, gchar const *value) { +void SPFeTurbulence::set(SPAttr key, gchar const *value) +{ int read_int; double read_num; bool read_bool; Inkscape::Filters::FilterTurbulenceType read_type; - switch(key) { - /*DEAL WITH SETTING ATTRIBUTES HERE*/ + switch (key) { + /*DEAL WITH SETTING ATTRIBUTES HERE*/ case SPAttr::BASEFREQUENCY: this->baseFrequency.set(value); @@ -127,7 +134,7 @@ void SPFeTurbulence::set(SPAttr key, gchar const *value) { case SPAttr::NUMOCTAVES: read_int = value ? (int)floor(helperfns_read_number(value)) : 1; - if (read_int != this->numOctaves){ + if (read_int != this->numOctaves) { this->numOctaves = read_int; this->updated = false; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); @@ -136,7 +143,7 @@ void SPFeTurbulence::set(SPAttr key, gchar const *value) { case SPAttr::SEED: read_num = value ? helperfns_read_number(value) : 0; - if (read_num != this->seed){ + if (read_num != this->seed) { this->seed = read_num; this->updated = false; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); @@ -145,7 +152,7 @@ void SPFeTurbulence::set(SPAttr key, gchar const *value) { case SPAttr::STITCHTILES: read_bool = sp_feTurbulence_read_stitchTiles(value); - if (read_bool != this->stitchTiles){ + if (read_bool != this->stitchTiles) { this->stitchTiles = read_bool; this->updated = false; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); @@ -154,14 +161,14 @@ void SPFeTurbulence::set(SPAttr key, gchar const *value) { case SPAttr::TYPE: read_type = sp_feTurbulence_read_type(value); - if (read_type != this->type){ + if (read_type != this->type) { this->type = read_type; this->updated = false; this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; default: - SPFilterPrimitive::set(key, value); + SPFilterPrimitive::set(key, value); break; } } @@ -169,12 +176,10 @@ void SPFeTurbulence::set(SPAttr key, gchar const *value) { /** * Receives update notifications. */ -void SPFeTurbulence::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - +void SPFeTurbulence::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something to trigger redisplay, updates? */ - } SPFilterPrimitive::update(ctx, flags); @@ -183,7 +188,8 @@ void SPFeTurbulence::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFeTurbulence::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFeTurbulence::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ /* TODO: Don't just clone, but create a new repr node and write all * relevant values into it */ if (!repr) { @@ -198,12 +204,14 @@ Inkscape::XML::Node* SPFeTurbulence::write(Inkscape::XML::Document *doc, Inkscap return repr; } -void SPFeTurbulence::build_renderer(Inkscape::Filters::Filter* filter) { +void SPFeTurbulence::build_renderer(Inkscape::Filters::Filter *filter) +{ g_assert(filter != nullptr); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_TURBULENCE); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); - Inkscape::Filters::FilterTurbulence *nr_turbulence = dynamic_cast(nr_primitive); + Inkscape::Filters::FilterTurbulence *nr_turbulence = + dynamic_cast(nr_primitive); g_assert(nr_turbulence != nullptr); this->renderer_common(nr_primitive); diff --git a/src/object/filters/turbulence.h b/src/object/filters/turbulence.h index 5bc1ad2e671cb12086d8eb87b4e9152250f5fbd7..d3547f7c64c06610e8fb18ef019133e86cf0b6da 100644 --- a/src/object/filters/turbulence.h +++ b/src/object/filters/turbulence.h @@ -14,19 +14,20 @@ #ifndef SP_FETURBULENCE_H_SEEN #define SP_FETURBULENCE_H_SEEN -#include "sp-filter-primitive.h" -#include "number-opt-number.h" #include "display/nr-filter-turbulence.h" +#include "number-opt-number.h" +#include "sp-filter-primitive.h" -#define SP_FETURBULENCE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FETURBULENCE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FETURBULENCE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FETURBULENCE(obj) (dynamic_cast((SPObject *)obj) != NULL) /* FeTurbulence base class */ -class SPFeTurbulence : public SPFilterPrimitive { +class SPFeTurbulence : public SPFilterPrimitive +{ public: - SPFeTurbulence(); - ~SPFeTurbulence() override; + SPFeTurbulence(); + ~SPFeTurbulence() override; /** TURBULENCE ATTRIBUTES HERE */ NumberOptNumber baseFrequency; @@ -38,16 +39,16 @@ public: bool updated; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const gchar* value) override; + void set(SPAttr key, const gchar *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - void build_renderer(Inkscape::Filters::Filter* filter) override; + void build_renderer(Inkscape::Filters::Filter *filter) override; }; #endif /* !SP_FETURBULENCE_H_SEEN */ diff --git a/src/object/object-set.cpp b/src/object/object-set.cpp index 49dd2e837c0efae52115da4a78670d95142fac22..aec617ea8232511d1dd758ee18272cb4edd37c42 100644 --- a/src/object/object-set.cpp +++ b/src/object/object-set.cpp @@ -10,18 +10,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include #include "object-set.h" + +#include +#include +#include +#include + #include "box3d.h" #include "persp3d.h" #include "preferences.h" -#include -#include namespace Inkscape { -bool ObjectSet::add(SPObject* object, bool nosignal) { +bool ObjectSet::add(SPObject *object, bool nosignal) +{ g_return_val_if_fail(object != nullptr, false); g_return_val_if_fail(SP_IS_OBJECT(object), false); @@ -32,7 +35,7 @@ bool ObjectSet::add(SPObject* object, bool nosignal) { // very nice function, but changes selection behavior (probably needs new selection option to deal with it) // check if there is mutual ancestor for some elements, which can replace all of them in the set -// object = _getMutualAncestor(object); + // object = _getMutualAncestor(object); // remove all descendants from the set _removeDescendantsFromSet(object); @@ -52,7 +55,8 @@ void ObjectSet::add(XML::Node *repr) } } -bool ObjectSet::remove(SPObject* object) { +bool ObjectSet::remove(SPObject *object) +{ g_return_val_if_fail(object != nullptr, false); g_return_val_if_fail(SP_IS_OBJECT(object), false); @@ -74,24 +78,28 @@ bool ObjectSet::remove(SPObject* object) { return false; } -bool ObjectSet::includes(SPObject *object) { +bool ObjectSet::includes(SPObject *object) +{ g_return_val_if_fail(object != nullptr, false); g_return_val_if_fail(SP_IS_OBJECT(object), false); return _container.get().find(object) != _container.get().end(); } -void ObjectSet::clear() { +void ObjectSet::clear() +{ _clear(); _emitSignals(); } -int ObjectSet::size() { +int ObjectSet::size() +{ return _container.size(); } -bool ObjectSet::_anyAncestorIsInSet(SPObject *object) { - SPObject* o = object; +bool ObjectSet::_anyAncestorIsInSet(SPObject *object) +{ + SPObject *o = object; while (o != nullptr) { if (includes(o)) { return true; @@ -102,8 +110,9 @@ bool ObjectSet::_anyAncestorIsInSet(SPObject *object) { return false; } -void ObjectSet::_removeDescendantsFromSet(SPObject *object) { - for (auto& child: object->children) { +void ObjectSet::_removeDescendantsFromSet(SPObject *object) +{ + for (auto &child : object->children) { if (includes(&child)) { _remove(&child); // there is certainly no children of this child in the set @@ -114,38 +123,43 @@ void ObjectSet::_removeDescendantsFromSet(SPObject *object) { } } -void ObjectSet::_disconnect(SPObject *object) { +void ObjectSet::_disconnect(SPObject *object) +{ _releaseConnections[object].disconnect(); _releaseConnections.erase(object); _remove3DBoxesRecursively(object); _releaseSignals(object); } -void ObjectSet::_remove(SPObject *object) { +void ObjectSet::_remove(SPObject *object) +{ _disconnect(object); _container.get().erase(object); } -void ObjectSet::_add(SPObject *object) { +void ObjectSet::_add(SPObject *object) +{ _releaseConnections[object] = object->connectRelease(sigc::hide_return(sigc::mem_fun(*this, &ObjectSet::remove))); _container.push_back(object); _add3DBoxesRecursively(object); _connectSignals(object); } -void ObjectSet::_clear() { - for (auto object: _container) +void ObjectSet::_clear() +{ + for (auto object : _container) _disconnect(object); _container.clear(); } -SPObject *ObjectSet::_getMutualAncestor(SPObject *object) { +SPObject *ObjectSet::_getMutualAncestor(SPObject *object) +{ SPObject *o = object; bool flag = true; while (o->parent != nullptr) { - for (auto &child: o->parent->children) { - if(&child != o && !includes(&child)) { + for (auto &child : o->parent->children) { + if (&child != o && !includes(&child)) { flag = false; break; } @@ -158,10 +172,11 @@ SPObject *ObjectSet::_getMutualAncestor(SPObject *object) { return o; } -void ObjectSet::_removeAncestorsFromSet(SPObject *object) { - SPObject* o = object; +void ObjectSet::_removeAncestorsFromSet(SPObject *object) +{ + SPObject *o = object; while (o->parent != nullptr) { - for (auto &child: o->parent->children) { + for (auto &child : o->parent->children) { if (&child != o) { _add(&child); } @@ -174,11 +189,13 @@ void ObjectSet::_removeAncestorsFromSet(SPObject *object) { } } -ObjectSet::~ObjectSet() { +ObjectSet::~ObjectSet() +{ _clear(); } -void ObjectSet::toggle(SPObject *obj) { +void ObjectSet::toggle(SPObject *obj) +{ if (includes(obj)) { remove(obj); } else { @@ -186,17 +203,20 @@ void ObjectSet::toggle(SPObject *obj) { } } -bool ObjectSet::isEmpty() { +bool ObjectSet::isEmpty() +{ return _container.size() == 0; } -SPObject *ObjectSet::single() { +SPObject *ObjectSet::single() +{ return _container.size() == 1 ? *_container.begin() : nullptr; } -SPItem *ObjectSet::singleItem() { +SPItem *ObjectSet::singleItem() +{ if (_container.size() == 1) { - SPObject* obj = *_container.begin(); + SPObject *obj = *_container.begin(); if (SP_IS_ITEM(obj)) { return SP_ITEM(obj); } @@ -205,15 +225,18 @@ SPItem *ObjectSet::singleItem() { return nullptr; } -SPItem *ObjectSet::smallestItem(CompareSize compare) { +SPItem *ObjectSet::smallestItem(CompareSize compare) +{ return _sizeistItem(true, compare); } -SPItem *ObjectSet::largestItem(CompareSize compare) { +SPItem *ObjectSet::largestItem(CompareSize compare) +{ return _sizeistItem(false, compare); } -SPItem *ObjectSet::_sizeistItem(bool sml, CompareSize compare) { +SPItem *ObjectSet::_sizeistItem(bool sml, CompareSize compare) +{ auto items = this->items(); gdouble max = sml ? 1e18 : 0; SPItem *ist = nullptr; @@ -226,8 +249,7 @@ SPItem *ObjectSet::_sizeistItem(bool sml, CompareSize compare) { Geom::Rect bbox = *obox; - gdouble size = compare == AREA ? bbox.area() : - (compare == VERTICAL ? bbox.height() : bbox.width()); + gdouble size = compare == AREA ? bbox.area() : (compare == VERTICAL ? bbox.height() : bbox.width()); size = sml ? size : size * -1; if (size < max) { max = size; @@ -238,20 +260,23 @@ SPItem *ObjectSet::_sizeistItem(bool sml, CompareSize compare) { return ist; } -SPObjectRange ObjectSet::objects() { +SPObjectRange ObjectSet::objects() +{ return SPObjectRange(_container.get().begin(), _container.get().end()); } -Inkscape::XML::Node *ObjectSet::singleRepr() { +Inkscape::XML::Node *ObjectSet::singleRepr() +{ SPObject *obj = single(); return obj ? obj->getRepr() : nullptr; } -void ObjectSet::set(SPObject *object, bool persist_selection_context) { +void ObjectSet::set(SPObject *object, bool persist_selection_context) +{ _clear(); _add(object); - if(dynamic_cast(this)) - return dynamic_cast(this)->_emitChanged(persist_selection_context); + if (dynamic_cast(this)) + return dynamic_cast(this)->_emitChanged(persist_selection_context); } void ObjectSet::set(XML::Node *repr) @@ -263,8 +288,9 @@ void ObjectSet::set(XML::Node *repr) } } -void ObjectSet::setReprList(std::vector const &list) { - if(!document()) +void ObjectSet::setReprList(std::vector const &list) +{ + if (!document()) return; clear(); for (auto iter = list.rbegin(); iter != list.rend(); ++iter) { @@ -280,16 +306,13 @@ void ObjectSet::setReprList(std::vector const &list) { } } _emitSignals(); - if(dynamic_cast(this)) - return dynamic_cast(this)->_emitChanged();// + if (dynamic_cast(this)) + return dynamic_cast(this)->_emitChanged(); // } - - Geom::OptRect ObjectSet::bounds(SPItem::BBoxType type) const { - return (type == SPItem::GEOMETRIC_BBOX) ? - geometricBounds() : visualBounds(); + return (type == SPItem::GEOMETRIC_BBOX) ? geometricBounds() : visualBounds(); } Geom::OptRect ObjectSet::geometricBounds() const @@ -327,7 +350,8 @@ Geom::OptRect ObjectSet::documentBounds(SPItem::BBoxType type) const { Geom::OptRect bbox; auto items = const_cast(this)->items(); - if (items.empty()) return bbox; + if (items.empty()) + return bbox; for (auto iter = items.begin(); iter != items.end(); ++iter) { SPItem *item = SP_ITEM(*iter); @@ -339,11 +363,12 @@ Geom::OptRect ObjectSet::documentBounds(SPItem::BBoxType type) const // If we have a selection of multiple items, then the center of the first item // will be returned; this is also the case in SelTrans::centerRequest() -boost::optional ObjectSet::center() const { +boost::optional ObjectSet::center() const +{ auto items = const_cast(this)->items(); if (!items.empty()) { SPItem *first = items.back(); // from the first item in selection - if (first->isCenterSet()) { // only if set explicitly + if (first->isCenterSet()) { // only if set explicitly return first->getCenter(); } } @@ -355,9 +380,10 @@ boost::optional ObjectSet::center() const { } } -std::list const ObjectSet::perspList() { +std::list const ObjectSet::perspList() +{ std::list pl; - for (auto & _3dboxe : _3dboxes) { + for (auto &_3dboxe : _3dboxes) { Persp3D *persp = _3dboxe->get_perspective(); if (std::find(pl.begin(), pl.end(), persp) == pl.end()) pl.push_back(persp); @@ -365,7 +391,8 @@ std::list const ObjectSet::perspList() { return pl; } -std::list const ObjectSet::box3DList(Persp3D *persp) { +std::list const ObjectSet::box3DList(Persp3D *persp) +{ std::list boxes; if (persp) { for (auto box : _3dboxes) { @@ -379,7 +406,8 @@ std::list const ObjectSet::box3DList(Persp3D *persp) { return boxes; } -void ObjectSet::_add3DBoxesRecursively(SPObject *obj) { +void ObjectSet::_add3DBoxesRecursively(SPObject *obj) +{ std::list boxes = SPBox3D::extract_boxes(obj); for (auto box : boxes) { @@ -387,13 +415,14 @@ void ObjectSet::_add3DBoxesRecursively(SPObject *obj) { } } -void ObjectSet::_remove3DBoxesRecursively(SPObject *obj) { +void ObjectSet::_remove3DBoxesRecursively(SPObject *obj) +{ std::list boxes = SPBox3D::extract_boxes(obj); for (auto box : boxes) { std::list::iterator b = std::find(_3dboxes.begin(), _3dboxes.end(), box); if (b == _3dboxes.end()) { - g_print ("Warning! Trying to remove unselected box from selection.\n"); + g_print("Warning! Trying to remove unselected box from selection.\n"); return; } _3dboxes.erase(b); diff --git a/src/object/object-set.h b/src/object/object-set.h index 3c71e2da822165d09d96bffbf02202b6ea04ab3e..b96c5c16ed6f33df05b388d0998368eff6c35a82 100644 --- a/src/object/object-set.h +++ b/src/object/object-set.h @@ -14,29 +14,31 @@ #ifndef INKSCAPE_PROTOTYPE_OBJECTSET_H #define INKSCAPE_PROTOTYPE_OBJECTSET_H -#include -#include -#include -#include -#include #include +#include #include +#include +#include #include #include -#include #include +#include #include #include -#include #include -#include "sp-object.h" -#include "sp-item.h" -#include "sp-item-group.h" +#include +#include +#include + #include "desktop.h" #include "document.h" +#include "sp-item-group.h" +#include "sp-item.h" +#include "sp-object.h" #include "verbs.h" -enum BoolOpErrors { +enum BoolOpErrors +{ DONE, DONE_NO_PATH, DONE_NO_ACTION, @@ -49,12 +51,12 @@ enum BoolOpErrors { // boolean operation enum bool_op { - bool_op_union, // A OR B - bool_op_inters, // A AND B - bool_op_diff, // A \ B - bool_op_symdiff, // A XOR B - bool_op_cut, // coupure (pleines) - bool_op_slice // coupure (contour) + bool_op_union, // A OR B + bool_op_inters, // A AND B + bool_op_diff, // A \ B + bool_op_symdiff, // A XOR B + bool_op_cut, // coupure (pleines) + bool_op_slice // coupure (contour) }; typedef enum bool_op BooleanOp; @@ -67,78 +69,82 @@ namespace XML { class Node; } -struct hashed{}; -struct random_access{}; +struct hashed +{ +}; +struct random_access +{ +}; -struct is_item { - bool operator()(SPObject* obj) { - return SP_IS_ITEM(obj); - } +struct is_item +{ + bool operator()(SPObject *obj) { return SP_IS_ITEM(obj); } }; -struct is_group { - bool operator()(SPObject* obj) { - return SP_IS_GROUP(obj); - } +struct is_group +{ + bool operator()(SPObject *obj) { return SP_IS_GROUP(obj); } }; -struct object_to_item { - typedef SPItem* result_type; - SPItem* operator()(SPObject* obj) const { - return SP_ITEM(obj); - } +struct object_to_item +{ + typedef SPItem *result_type; + SPItem *operator()(SPObject *obj) const { return SP_ITEM(obj); } }; -struct object_to_node { - typedef XML::Node* result_type; - XML::Node* operator()(SPObject* obj) const { - return obj->getRepr(); - } +struct object_to_node +{ + typedef XML::Node *result_type; + XML::Node *operator()(SPObject *obj) const { return obj->getRepr(); } }; -struct object_to_group { - typedef SPGroup* result_type; - SPGroup* operator()(SPObject* obj) const { - return SP_GROUP(obj); - } +struct object_to_group +{ + typedef SPGroup *result_type; + SPGroup *operator()(SPObject *obj) const { return SP_GROUP(obj); } }; typedef boost::multi_index_container< - SPObject*, - boost::multi_index::indexed_by< - boost::multi_index::sequenced<>, - boost::multi_index::random_access< - boost::multi_index::tag>, - boost::multi_index::hashed_unique< - boost::multi_index::tag, - boost::multi_index::identity> - >> MultiIndexContainer; - -typedef boost::any_range< - SPObject*, - boost::random_access_traversal_tag, - SPObject* const&, - std::ptrdiff_t> SPObjectRange; - -class ObjectSet { -public: - enum CompareSize {HORIZONTAL, VERTICAL, AREA}; - typedef decltype(MultiIndexContainer().get() | boost::adaptors::filtered(is_item()) | boost::adaptors::transformed(object_to_item())) SPItemRange; - typedef decltype(MultiIndexContainer().get() | boost::adaptors::filtered(is_group()) | boost::adaptors::transformed(object_to_group())) SPGroupRange; - typedef decltype(MultiIndexContainer().get() | boost::adaptors::filtered(is_item()) | boost::adaptors::transformed(object_to_node())) XMLNodeRange; + SPObject *, + boost::multi_index::indexed_by< + boost::multi_index::sequenced<>, boost::multi_index::random_access>, + boost::multi_index::hashed_unique, boost::multi_index::identity>>> + MultiIndexContainer; - ObjectSet(SPDesktop* desktop): _desktop(desktop) { +typedef boost::any_range + SPObjectRange; + +class ObjectSet +{ +public: + enum CompareSize + { + HORIZONTAL, + VERTICAL, + AREA + }; + typedef decltype(MultiIndexContainer().get() | boost::adaptors::filtered(is_item()) | + boost::adaptors::transformed(object_to_item())) SPItemRange; + typedef decltype(MultiIndexContainer().get() | boost::adaptors::filtered(is_group()) | + boost::adaptors::transformed(object_to_group())) SPGroupRange; + typedef decltype(MultiIndexContainer().get() | boost::adaptors::filtered(is_item()) | + boost::adaptors::transformed(object_to_node())) XMLNodeRange; + + ObjectSet(SPDesktop *desktop) + : _desktop(desktop) + { if (desktop) - _document = desktop->getDocument(); + _document = desktop->getDocument(); }; - ObjectSet(SPDocument* doc): _desktop(nullptr), _document(doc) {}; - ObjectSet(): _desktop(nullptr), _document(nullptr) {}; // Used in spray-tool.h. + ObjectSet(SPDocument *doc) + : _desktop(nullptr) + , _document(doc){}; + ObjectSet() + : _desktop(nullptr) + , _document(nullptr){}; // Used in spray-tool.h. virtual ~ObjectSet(); - - void setDocument(SPDocument* doc){ - _document = doc; - } - + + void setDocument(SPDocument *doc) { _document = doc; } /** * Add an SPObject to the set of selected objects. @@ -146,7 +152,7 @@ public: * @param obj the SPObject to add * @param nosignal true if no signals should be sent */ - bool add(SPObject* object, bool nosignal = false); + bool add(SPObject *object, bool nosignal = false); /** * Add an XML node's SPObject to the set of selected objects. @@ -160,8 +166,9 @@ public: * \param to the end iterator */ template - void add(InputIterator from, InputIterator to) { - for(auto it = from; it != to; ++it) { + void add(InputIterator from, InputIterator to) + { + for (auto it = from; it != to; ++it) { _add(*it); } _emitSignals(); @@ -176,7 +183,7 @@ public: * * @return is success */ - bool remove(SPObject* object); + bool remove(SPObject *object); /** * Returns true if the given object is selected. @@ -240,24 +247,24 @@ public: SPObjectRange objects(); /** Returns a range of selected SPItems. */ - SPItemRange items() { - return SPItemRange(_container.get() - | boost::adaptors::filtered(is_item()) - | boost::adaptors::transformed(object_to_item())); + SPItemRange items() + { + return SPItemRange(_container.get() | boost::adaptors::filtered(is_item()) | + boost::adaptors::transformed(object_to_item())); }; /** Returns a range of selected groups. */ - SPGroupRange groups() { - return SPGroupRange (_container.get() - | boost::adaptors::filtered(is_group()) - | boost::adaptors::transformed(object_to_group())); + SPGroupRange groups() + { + return SPGroupRange(_container.get() | boost::adaptors::filtered(is_group()) | + boost::adaptors::transformed(object_to_group())); } /** Returns a range of the xml nodes of all selected objects. */ - XMLNodeRange xmlNodes() { - return XMLNodeRange(_container.get() - | boost::adaptors::filtered(is_item()) - | boost::adaptors::transformed(object_to_node())); + XMLNodeRange xmlNodes() + { + return XMLNodeRange(_container.get() | boost::adaptors::filtered(is_item()) | + boost::adaptors::transformed(object_to_node())); } /** @@ -273,20 +280,20 @@ public: * @param objs the objects to select */ template - typename boost::enable_if, void>::type - setList(const std::vector &objs) { + typename boost::enable_if, void>::type setList(const std::vector &objs) + { _clear(); addList(objs); } - + /** * Selects the objects with the same IDs as those in `list`. * * @todo How about adding `setIdList(std::vector const &list)` - * + * * @param list the repr list to add */ - void setReprList(std::vector const &list); + void setReprList(std::vector const &list); /** * Adds the specified objects to selection, without deselecting first. @@ -294,9 +301,9 @@ public: * @param objs the objects to select */ template - typename boost::enable_if, void>::type - addList(const std::vector &objs) { - for (auto obj: objs) { + typename boost::enable_if, void>::type addList(const std::vector &objs) + { + for (auto obj : objs) { if (!includes(obj)) { add(obj, true); } @@ -347,8 +354,8 @@ public: */ SPDocument *document() { return _document; } - //item groups operations - //in selection-chemistry.cpp + // item groups operations + // in selection-chemistry.cpp void deleteItems(); void duplicate(bool suppressDone = false, bool duplicateLayer = false); void clone(); @@ -368,12 +375,12 @@ public: void relink(); void cloneOriginal(); void cloneOriginalPathLPE(bool allow_transforms = false); - Inkscape::XML::Node* group(); + Inkscape::XML::Node *group(); void popFromGroup(); void ungroup(); - - //z-order management - //in selection-chemistry.cpp + + // z-order management + // in selection-chemistry.cpp void stackUp(bool skip_undo = false); void raise(bool skip_undo = false); void raiseToTop(bool skip_undo = false); @@ -384,17 +391,17 @@ public: void toPrevLayer(bool skip_undo = false); void toLayer(SPObject *layer, bool skip_undo = false); - //clipboard management - //in selection-chemistry.cpp + // clipboard management + // in selection-chemistry.cpp void copy(); void cut(); void pasteStyle(); void pasteSize(bool apply_x, bool apply_y); void pasteSizeSeparately(bool apply_x, bool apply_y); void pastePathEffect(); - - //path operations - //in path-chemistry.cpp + + // path operations + // in path-chemistry.cpp void combine(bool skip_undo = false); void breakApart(bool skip_undo = false); void toCurves(bool skip_undo = false); @@ -415,8 +422,8 @@ public: bool pathCut(const bool skip_undo = false); bool pathSlice(const bool skip_undo = false); - //Other path operations - //in selection-chemistry.cpp + // Other path operations + // in selection-chemistry.cpp void toMarker(bool apply = true); void toGuides(); void toSymbol(); @@ -428,17 +435,18 @@ public: void editMask(bool clip); void unsetMask(const bool apply_clip_path, const bool skip_undo = false); void setClipGroup(); - + // moves // in selection-chemistry.cpp void removeLPE(); void removeFilter(); - void applyAffine(Geom::Affine const &affine, bool set_i2d=true,bool compensate=true, bool adjust_transf_center=true); + void applyAffine(Geom::Affine const &affine, bool set_i2d = true, bool compensate = true, + bool adjust_transf_center = true); void removeTransform(); void setScaleAbsolute(double, double, double, double); - void setScaleRelative(const Geom::Point&, const Geom::Scale&); - void rotateRelative(const Geom::Point&, double); - void skewRelative(const Geom::Point&, double, double); + void setScaleRelative(const Geom::Point &, const Geom::Scale &); + void rotateRelative(const Geom::Point &, double); + void skewRelative(const Geom::Point &, double, double); void moveRelative(const Geom::Point &move, bool compensate = true); void moveRelative(double dx, double dy); void rotate90(bool ccw); @@ -449,7 +457,7 @@ public: void scaleTimes(double); void move(double dx, double dy); void moveScreen(double dx, double dy); - + // various void getExportHints(Glib::ustring &filename, float *xdpi, float *ydpi); bool fitCanvas(bool with_margins, bool skip_undo = false); @@ -457,12 +465,12 @@ public: void fillBetweenMany(); protected: - virtual void _connectSignals(SPObject* object) {}; - virtual void _releaseSignals(SPObject* object) {}; - virtual void _emitSignals() {}; - void _add(SPObject* object); + virtual void _connectSignals(SPObject *object){}; + virtual void _releaseSignals(SPObject *object){}; + virtual void _emitSignals(){}; + void _add(SPObject *object); void _clear(); - void _remove(SPObject* object); + void _remove(SPObject *object); bool _anyAncestorIsInSet(SPObject *object); void _removeDescendantsFromSet(SPObject *object); void _removeAncestorsFromSet(SPObject *object); @@ -475,12 +483,12 @@ protected: GC::soft_ptr _desktop; GC::soft_ptr _document; std::list _3dboxes; - std::unordered_map _releaseConnections; + std::unordered_map _releaseConnections; private: - BoolOpErrors pathBoolOp(bool_op bop, const bool skip_undo, const bool checked = false, const unsigned int verb = SP_VERB_NONE, const Glib::ustring description = ""); - void _disconnect(SPObject* object); - + BoolOpErrors pathBoolOp(bool_op bop, const bool skip_undo, const bool checked = false, + const unsigned int verb = SP_VERB_NONE, const Glib::ustring description = ""); + void _disconnect(SPObject *object); }; typedef ObjectSet::SPItemRange SPItemRange; @@ -489,7 +497,7 @@ typedef ObjectSet::XMLNodeRange XMLNodeRange; } // namespace Inkscape -#endif //INKSCAPE_PROTOTYPE_OBJECTSET_H +#endif // INKSCAPE_PROTOTYPE_OBJECTSET_H /* Local Variables: diff --git a/src/object/persp3d-reference.cpp b/src/object/persp3d-reference.cpp index 294c62dc8e6d3cb228a1baf0869be52865da6664..7c10eeb502eb9f147fddacab2da21661e0820d5b 100644 --- a/src/object/persp3d-reference.cpp +++ b/src/object/persp3d-reference.cpp @@ -9,19 +9,22 @@ */ #include "persp3d-reference.h" + #include "uri.h" static void persp3dreference_href_changed(SPObject *old_ref, SPObject *ref, Persp3DReference *persp3dref); static void persp3dreference_delete_self(SPObject *deleted, Persp3DReference *persp3dref); static void persp3dreference_source_modified(SPObject *iSource, guint flags, Persp3DReference *persp3dref); -Persp3DReference::Persp3DReference(SPObject* i_owner) : URIReference(i_owner) +Persp3DReference::Persp3DReference(SPObject *i_owner) + : URIReference(i_owner) { - owner=i_owner; + owner = i_owner; persp_href = nullptr; persp_repr = nullptr; persp = nullptr; - _changed_connection = changedSignal().connect(sigc::bind(sigc::ptr_fun(persp3dreference_href_changed), this)); // listening to myself, this should be virtual instead + _changed_connection = changedSignal().connect(sigc::bind( + sigc::ptr_fun(persp3dreference_href_changed), this)); // listening to myself, this should be virtual instead } Persp3DReference::~Persp3DReference() @@ -32,27 +35,24 @@ Persp3DReference::~Persp3DReference() unlink(); } -bool -Persp3DReference::_acceptObject(SPObject *obj) const +bool Persp3DReference::_acceptObject(SPObject *obj) const { return SP_IS_PERSP3D(obj) && URIReference::_acceptObject(obj); -; + ; /* effic: Don't bother making this an inline function: _acceptObject is a virtual function, typically called from a context where the runtime type is not known at compile time. */ } -void -Persp3DReference::unlink() +void Persp3DReference::unlink() { g_free(persp_href); persp_href = nullptr; detach(); } -void -Persp3DReference::start_listening(Persp3D* to) +void Persp3DReference::start_listening(Persp3D *to) { - if ( to == nullptr ) { + if (to == nullptr) { return; } persp = to; @@ -61,10 +61,9 @@ Persp3DReference::start_listening(Persp3D* to) _modified_connection = to->connectModified(sigc::bind<2>(sigc::ptr_fun(&persp3dreference_source_modified), this)); } -void -Persp3DReference::quit_listening() +void Persp3DReference::quit_listening() { - if ( persp == nullptr ) { + if (persp == nullptr) { return; } _modified_connection.disconnect(); @@ -73,32 +72,28 @@ Persp3DReference::quit_listening() persp = nullptr; } -static void -persp3dreference_href_changed(SPObject */*old_ref*/, SPObject */*ref*/, Persp3DReference *persp3dref) +static void persp3dreference_href_changed(SPObject * /*old_ref*/, SPObject * /*ref*/, Persp3DReference *persp3dref) { persp3dref->quit_listening(); Persp3D *refobj = SP_PERSP3D(persp3dref->getObject()); - if ( refobj ) { + if (refobj) { persp3dref->start_listening(refobj); } persp3dref->owner->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -static void -persp3dreference_delete_self(SPObject */*deleted*/, Persp3DReference *persp3dref) +static void persp3dreference_delete_self(SPObject * /*deleted*/, Persp3DReference *persp3dref) { g_return_if_fail(persp3dref->owner); persp3dref->owner->deleteObject(); } -static void -persp3dreference_source_modified(SPObject */*iSource*/, guint /*flags*/, Persp3DReference *persp3dref) +static void persp3dreference_source_modified(SPObject * /*iSource*/, guint /*flags*/, Persp3DReference *persp3dref) { persp3dref->owner->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } - /* Local Variables: mode:c++ diff --git a/src/object/persp3d-reference.h b/src/object/persp3d-reference.h index 8d254dd3c2b8e89c8ef59fe28e37c8b9aed4ad34..9f1e885d393e9b6e8ff7b74854d5cf3544abda8f 100644 --- a/src/object/persp3d-reference.h +++ b/src/object/persp3d-reference.h @@ -14,8 +14,8 @@ #include #include -#include "uri-references.h" #include "persp3d.h" +#include "uri-references.h" class SPObject; @@ -23,16 +23,15 @@ namespace Inkscape { namespace XML { class Node; } -} +} // namespace Inkscape -class Persp3DReference : public Inkscape::URIReference { +class Persp3DReference : public Inkscape::URIReference +{ public: Persp3DReference(SPObject *obj); ~Persp3DReference() override; - Persp3D *getObject() const { - return SP_PERSP3D(URIReference::getObject()); - } + Persp3D *getObject() const { return SP_PERSP3D(URIReference::getObject()); } SPObject *owner; @@ -45,16 +44,15 @@ public: sigc::connection _modified_connection; sigc::connection _delete_connection; - void link(char* to); + void link(char *to); void unlink(); - void start_listening(Persp3D* to); + void start_listening(Persp3D *to); void quit_listening(); protected: bool _acceptObject(SPObject *obj) const override; }; - #endif /* !SEEN_PERSP3D_REFERENCE_H */ /* diff --git a/src/object/persp3d.cpp b/src/object/persp3d.cpp index 3587f6d4b03a88458b5b6260f56496d010ac1227..6bb86e28e123a7726f7efaf40659fdd21a82615d 100644 --- a/src/object/persp3d.cpp +++ b/src/object/persp3d.cpp @@ -13,59 +13,60 @@ */ #include "persp3d.h" -#include "perspective-line.h" -#include "sp-root.h" -#include "sp-defs.h" -#include "box3d.h" + +#include #include "attributes.h" +#include "box3d.h" +#include "desktop.h" #include "document-undo.h" -#include "vanishing-point.h" -#include "ui/tools/box3d-tool.h" +#include "perspective-line.h" +#include "sp-defs.h" +#include "sp-root.h" #include "svg/stringstream.h" -#include "xml/node-event-vector.h" -#include "desktop.h" - -#include -#include "verbs.h" +#include "ui/tools/box3d-tool.h" #include "util/units.h" +#include "vanishing-point.h" +#include "verbs.h" +#include "xml/node-event-vector.h" using Inkscape::DocumentUndo; -static void persp3d_on_repr_attr_changed (Inkscape::XML::Node * repr, const gchar *key, const gchar *oldval, const gchar *newval, bool is_interactive, void * data); +static void persp3d_on_repr_attr_changed(Inkscape::XML::Node *repr, const gchar *key, const gchar *oldval, + const gchar *newval, bool is_interactive, void *data); static int global_counter = 0; /* Constructor/destructor for the internal class */ -Persp3DImpl::Persp3DImpl() : - tmat (Proj::TransfMat3x4 ()), - document (nullptr) +Persp3DImpl::Persp3DImpl() + : tmat(Proj::TransfMat3x4()) + , document(nullptr) { my_counter = global_counter++; } static Inkscape::XML::NodeEventVector const persp3d_repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - persp3d_on_repr_attr_changed, - nullptr, /* content_changed */ - nullptr /* order_changed */ + nullptr, /* child_added */ + nullptr, /* child_removed */ + persp3d_on_repr_attr_changed, nullptr, /* content_changed */ + nullptr /* order_changed */ }; - -Persp3D::Persp3D() : SPObject() { +Persp3D::Persp3D() + : SPObject() +{ this->perspective_impl = new Persp3DImpl(); } Persp3D::~Persp3D() = default; - /** * Virtual build: set persp3d attributes from its associated XML node. */ -void Persp3D::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPObject::build(document, repr); +void Persp3D::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPObject::build(document, repr); this->readAttr(SPAttr::INKSCAPE_PERSP3D_VP_X); this->readAttr(SPAttr::INKSCAPE_PERSP3D_VP_Y); @@ -73,14 +74,15 @@ void Persp3D::build(SPDocument *document, Inkscape::XML::Node *repr) { this->readAttr(SPAttr::INKSCAPE_PERSP3D_ORIGIN); if (repr) { - repr->addListener (&persp3d_repr_events, this); + repr->addListener(&persp3d_repr_events, this); } } /** * Virtual release of Persp3D members before destruction. */ -void Persp3D::release() { +void Persp3D::release() +{ delete this->perspective_impl; this->getRepr()->removeListenerByData(this); } @@ -88,7 +90,8 @@ void Persp3D::release() { /** * Apply viewBox and legacy desktop transformation to point loaded from SVG */ -static Proj::Pt2 legacy_transform_forward(Proj::Pt2 pt, SPDocument const *doc) { +static Proj::Pt2 legacy_transform_forward(Proj::Pt2 pt, SPDocument const *doc) +{ // Read values are in 'user units'. auto root = doc->getRoot(); if (root->viewBox_set) { @@ -110,7 +113,8 @@ static Proj::Pt2 legacy_transform_forward(Proj::Pt2 pt, SPDocument const *doc) { /** * Apply viewBox and legacy desktop transformation to point to be written to SVG */ -static Proj::Pt2 legacy_transform_backward(Proj::Pt2 pt, SPDocument const *doc) { +static Proj::Pt2 legacy_transform_backward(Proj::Pt2 pt, SPDocument const *doc) +{ // stores inverted y-axis coordinates if (doc->is_yaxisdown()) { pt[1] *= -1; @@ -134,43 +138,43 @@ static Proj::Pt2 legacy_transform_backward(Proj::Pt2 pt, SPDocument const *doc) */ // FIXME: Currently we only read the finite positions of vanishing points; // should we move VPs into their own repr (as it's done for SPStop, e.g.)? -void Persp3D::set(SPAttr key, gchar const *value) { - +void Persp3D::set(SPAttr key, gchar const *value) +{ switch (key) { case SPAttr::INKSCAPE_PERSP3D_VP_X: { if (value) { - Proj::Pt2 pt (value); + Proj::Pt2 pt(value); Proj::Pt2 ptn = legacy_transform_forward(pt, document); - perspective_impl->tmat.set_image_pt( Proj::X, ptn ); + perspective_impl->tmat.set_image_pt(Proj::X, ptn); } break; } case SPAttr::INKSCAPE_PERSP3D_VP_Y: { if (value) { - Proj::Pt2 pt (value); + Proj::Pt2 pt(value); Proj::Pt2 ptn = legacy_transform_forward(pt, document); - perspective_impl->tmat.set_image_pt( Proj::Y, ptn ); + perspective_impl->tmat.set_image_pt(Proj::Y, ptn); } break; } case SPAttr::INKSCAPE_PERSP3D_VP_Z: { if (value) { - Proj::Pt2 pt (value); + Proj::Pt2 pt(value); Proj::Pt2 ptn = legacy_transform_forward(pt, document); - perspective_impl->tmat.set_image_pt( Proj::Z, ptn ); + perspective_impl->tmat.set_image_pt(Proj::Z, ptn); } break; } case SPAttr::INKSCAPE_PERSP3D_ORIGIN: { if (value) { - Proj::Pt2 pt (value); + Proj::Pt2 pt(value); Proj::Pt2 ptn = legacy_transform_forward(pt, document); - perspective_impl->tmat.set_image_pt( Proj::W, ptn ); + perspective_impl->tmat.set_image_pt(Proj::W, ptn); } break; } default: { - SPObject::set(key, value); + SPObject::set(key, value); break; } } @@ -186,18 +190,17 @@ void Persp3D::set(SPAttr key, gchar const *value) { } } -void Persp3D::update(SPCtx *ctx, guint flags) { +void Persp3D::update(SPCtx *ctx, guint flags) +{ if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - /* TODO: Should we update anything here? */ - } SPObject::update(ctx, flags); } -Persp3D * -Persp3D::create_xml_element(SPDocument *document, Persp3DImpl *dup) {// if dup is given, copy the attributes over +Persp3D *Persp3D::create_xml_element(SPDocument *document, Persp3DImpl *dup) +{ // if dup is given, copy the attributes over SPDefs *defs = document->getDefs(); Inkscape::XML::Document *xml_doc = document->getReprDoc(); Inkscape::XML::Node *repr; @@ -209,50 +212,49 @@ Persp3D::create_xml_element(SPDocument *document, Persp3DImpl *dup) {// if dup i // Use 'user-units' double width = document->getWidth().value("px"); double height = document->getHeight().value("px"); - if( document->getRoot()->viewBox_set ) { + if (document->getRoot()->viewBox_set) { Geom::Rect vb = document->getRoot()->viewBox; width = vb.width(); height = vb.height(); } - Proj::Pt2 proj_vp_x = Proj::Pt2 (0.0, height/2.0, 1.0); - Proj::Pt2 proj_vp_y = Proj::Pt2 (0.0, 1000.0, 0.0); - Proj::Pt2 proj_vp_z = Proj::Pt2 (width, height/2.0, 1.0); - Proj::Pt2 proj_origin = Proj::Pt2 (width/2.0, height/3.0, 1.0 ); + Proj::Pt2 proj_vp_x = Proj::Pt2(0.0, height / 2.0, 1.0); + Proj::Pt2 proj_vp_y = Proj::Pt2(0.0, 1000.0, 0.0); + Proj::Pt2 proj_vp_z = Proj::Pt2(width, height / 2.0, 1.0); + Proj::Pt2 proj_origin = Proj::Pt2(width / 2.0, height / 3.0, 1.0); if (dup) { - proj_vp_x = dup->tmat.column (Proj::X); - proj_vp_y = dup->tmat.column (Proj::Y); - proj_vp_z = dup->tmat.column (Proj::Z); - proj_origin = dup->tmat.column (Proj::W); + proj_vp_x = dup->tmat.column(Proj::X); + proj_vp_y = dup->tmat.column(Proj::Y); + proj_vp_z = dup->tmat.column(Proj::Z); + proj_origin = dup->tmat.column(Proj::W); } gchar *str = nullptr; str = proj_vp_x.coord_string(); repr->setAttribute("inkscape:vp_x", str); - g_free (str); + g_free(str); str = proj_vp_y.coord_string(); repr->setAttribute("inkscape:vp_y", str); - g_free (str); + g_free(str); str = proj_vp_z.coord_string(); repr->setAttribute("inkscape:vp_z", str); - g_free (str); + g_free(str); str = proj_origin.coord_string(); repr->setAttribute("inkscape:persp3d-origin", str); - g_free (str); + g_free(str); /* Append the new persp3d to defs */ defs->getRepr()->addChild(repr, nullptr); Inkscape::GC::release(repr); - return reinterpret_cast( defs->get_child_by_repr(repr) ); + return reinterpret_cast(defs->get_child_by_repr(repr)); } -Persp3D * -Persp3D::document_first_persp(SPDocument *document) +Persp3D *Persp3D::document_first_persp(SPDocument *document) { Persp3D *first = nullptr; - for (auto& child: document->getDefs()->children) { + for (auto &child : document->getDefs()->children) { if (SP_IS_PERSP3D(&child)) { first = SP_PERSP3D(&child); break; @@ -264,8 +266,8 @@ Persp3D::document_first_persp(SPDocument *document) /** * Virtual write: write object attributes to repr. */ -Inkscape::XML::Node* Persp3D::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - +Inkscape::XML::Node *Persp3D::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD & SP_OBJECT_WRITE_EXT) && !repr) { // this is where we end up when saving as plain SVG (also in other circumstances?); // hence we don't set the sodipodi:type attribute @@ -274,28 +276,28 @@ Inkscape::XML::Node* Persp3D::write(Inkscape::XML::Document *xml_doc, Inkscape:: if (flags & SP_OBJECT_WRITE_EXT) { { - Proj::Pt2 pt = perspective_impl->tmat.column( Proj::X ); + Proj::Pt2 pt = perspective_impl->tmat.column(Proj::X); Inkscape::SVGOStringStream os; pt = legacy_transform_backward(pt, document); os << pt[0] << " : " << pt[1] << " : " << pt[2]; repr->setAttribute("inkscape:vp_x", os.str()); } { - Proj::Pt2 pt = perspective_impl->tmat.column( Proj::Y ); + Proj::Pt2 pt = perspective_impl->tmat.column(Proj::Y); Inkscape::SVGOStringStream os; pt = legacy_transform_backward(pt, document); os << pt[0] << " : " << pt[1] << " : " << pt[2]; repr->setAttribute("inkscape:vp_y", os.str()); } { - Proj::Pt2 pt = perspective_impl->tmat.column( Proj::Z ); + Proj::Pt2 pt = perspective_impl->tmat.column(Proj::Z); Inkscape::SVGOStringStream os; pt = legacy_transform_backward(pt, document); os << pt[0] << " : " << pt[1] << " : " << pt[2]; repr->setAttribute("inkscape:vp_z", os.str()); } { - Proj::Pt2 pt = perspective_impl->tmat.column( Proj::W ); + Proj::Pt2 pt = perspective_impl->tmat.column(Proj::W); Inkscape::SVGOStringStream os; pt = legacy_transform_backward(pt, document); os << pt[0] << " : " << pt[1] << " : " << pt[2]; @@ -309,8 +311,8 @@ Inkscape::XML::Node* Persp3D::write(Inkscape::XML::Document *xml_doc, Inkscape:: } /* convenience wrapper around Persp3D::get_finite_dir() and Persp3D::get_infinite_dir() */ -Geom::Point -Persp3D::get_PL_dir_from_pt (Geom::Point const &pt, Proj::Axis axis) const { +Geom::Point Persp3D::get_PL_dir_from_pt(Geom::Point const &pt, Proj::Axis axis) const +{ if (Persp3D::VP_is_finite(this->perspective_impl, axis)) { return this->get_finite_dir(pt, axis); } else { @@ -318,34 +320,34 @@ Persp3D::get_PL_dir_from_pt (Geom::Point const &pt, Proj::Axis axis) const { } } -Geom::Point -Persp3D::get_finite_dir (Geom::Point const &pt, Proj::Axis axis) const { +Geom::Point Persp3D::get_finite_dir(Geom::Point const &pt, Proj::Axis axis) const +{ Box3D::PerspectiveLine pl(pt, axis, this); return pl.direction(); } -Geom::Point -Persp3D::get_infinite_dir (Proj::Axis axis) const { +Geom::Point Persp3D::get_infinite_dir(Proj::Axis axis) const +{ Proj::Pt2 vp(this->get_VP(axis)); if (vp[2] != 0.0) { - g_print ("VP should be infinite but is (%f : %f : %f)\n", vp[0], vp[1], vp[2]); + g_print("VP should be infinite but is (%f : %f : %f)\n", vp[0], vp[1], vp[2]); g_return_val_if_fail(vp[2] != 0.0, Geom::Point(0.0, 0.0)); } return Geom::Point(vp[0], vp[1]); } -double -Persp3D::get_infinite_angle (Proj::Axis axis) const { +double Persp3D::get_infinite_angle(Proj::Axis axis) const +{ return this->perspective_impl->tmat.get_infinite_angle(axis); } -bool -Persp3D::VP_is_finite (Persp3DImpl *persp_impl, Proj::Axis axis) { +bool Persp3D::VP_is_finite(Persp3DImpl *persp_impl, Proj::Axis axis) +{ return persp_impl->tmat.has_finite_image(axis); } -void -Persp3D::toggle_VP (Proj::Axis axis, bool set_undo) { +void Persp3D::toggle_VP(Proj::Axis axis, bool set_undo) +{ this->perspective_impl->tmat.toggle_finite(axis); // FIXME: Remove this repr update and rely on vp_drag_sel_modified() to do this for us // On the other hand, vp_drag_sel_modified() would update all boxes; @@ -353,81 +355,79 @@ Persp3D::toggle_VP (Proj::Axis axis, bool set_undo) { this->update_box_reprs(); this->updateRepr(SP_OBJECT_WRITE_EXT); if (set_undo) { - DocumentUndo::done(SP_ACTIVE_DESKTOP->getDocument(), SP_VERB_CONTEXT_3DBOX, - _("Toggle vanishing point")); + DocumentUndo::done(SP_ACTIVE_DESKTOP->getDocument(), SP_VERB_CONTEXT_3DBOX, _("Toggle vanishing point")); } } /* toggle VPs for the same axis in all perspectives of a given list */ -void -Persp3D::toggle_VPs (std::list list, Proj::Axis axis) { +void Persp3D::toggle_VPs(std::list list, Proj::Axis axis) +{ for (Persp3D *persp : list) { persp->toggle_VP(axis, false); } - DocumentUndo::done(SP_ACTIVE_DESKTOP->getDocument(), SP_VERB_CONTEXT_3DBOX, - _("Toggle multiple vanishing points")); + DocumentUndo::done(SP_ACTIVE_DESKTOP->getDocument(), SP_VERB_CONTEXT_3DBOX, _("Toggle multiple vanishing points")); } -void -Persp3D::set_VP_state (Proj::Axis axis, Proj::VPState state) { +void Persp3D::set_VP_state(Proj::Axis axis, Proj::VPState state) +{ if (Persp3D::VP_is_finite(this->perspective_impl, axis) != (state == Proj::VP_FINITE)) { this->toggle_VP(axis); } } -void -Persp3D::rotate_VP (Proj::Axis axis, double angle, bool alt_pressed) { // angle is in degrees +void Persp3D::rotate_VP(Proj::Axis axis, double angle, bool alt_pressed) +{ // angle is in degrees // FIXME: Most of this functionality should be moved to trans_mat_3x4.(h|cpp) if (this->perspective_impl->tmat.has_finite_image(axis)) { // don't rotate anything for finite VPs return; } - Proj::Pt2 v_dir_proj (this->perspective_impl->tmat.column(axis)); - Geom::Point v_dir (v_dir_proj[0], v_dir_proj[1]); - double a = Geom::atan2 (v_dir) * 180/M_PI; - a += alt_pressed ? 0.5 * ((angle > 0 ) - (angle < 0)) : angle; // the r.h.s. yields +/-0.5 or angle - this->perspective_impl->tmat.set_infinite_direction (axis, a); + Proj::Pt2 v_dir_proj(this->perspective_impl->tmat.column(axis)); + Geom::Point v_dir(v_dir_proj[0], v_dir_proj[1]); + double a = Geom::atan2(v_dir) * 180 / M_PI; + a += alt_pressed ? 0.5 * ((angle > 0) - (angle < 0)) : angle; // the r.h.s. yields +/-0.5 or angle + this->perspective_impl->tmat.set_infinite_direction(axis, a); - this->update_box_reprs (); + this->update_box_reprs(); this->updateRepr(SP_OBJECT_WRITE_EXT); } -void -Persp3D::apply_affine_transformation (Geom::Affine const &xform) { +void Persp3D::apply_affine_transformation(Geom::Affine const &xform) +{ this->perspective_impl->tmat *= xform; this->update_box_reprs(); this->updateRepr(SP_OBJECT_WRITE_EXT); } -void -Persp3D::add_box (SPBox3D *box) { +void Persp3D::add_box(SPBox3D *box) +{ Persp3DImpl *persp_impl = this->perspective_impl; if (!box) { return; } - if (std::find (persp_impl->boxes.begin(), persp_impl->boxes.end(), box) != persp_impl->boxes.end()) { + if (std::find(persp_impl->boxes.begin(), persp_impl->boxes.end(), box) != persp_impl->boxes.end()) { return; } persp_impl->boxes.push_back(box); } -void -Persp3D::remove_box (SPBox3D *box) { +void Persp3D::remove_box(SPBox3D *box) +{ Persp3DImpl *persp_impl = this->perspective_impl; - std::vector::iterator i = std::find (persp_impl->boxes.begin(), persp_impl->boxes.end(), box); + std::vector::iterator i = std::find(persp_impl->boxes.begin(), persp_impl->boxes.end(), box); if (i != persp_impl->boxes.end()) persp_impl->boxes.erase(i); } -bool -Persp3D::has_box (SPBox3D *box) const { +bool Persp3D::has_box(SPBox3D *box) const +{ Persp3DImpl *persp_impl = this->perspective_impl; // FIXME: For some reason, std::find() does not seem to compare pointers "correctly" (or do we need to // provide a proper comparison function?), so we manually traverse the list. - for (auto & boxe : persp_impl->boxes) { + for (auto &boxe : persp_impl->boxes) { if (boxe == box) { return true; } @@ -435,36 +435,36 @@ Persp3D::has_box (SPBox3D *box) const { return false; } -void -Persp3D::update_box_displays () { +void Persp3D::update_box_displays() +{ Persp3DImpl *persp_impl = this->perspective_impl; if (persp_impl->boxes.empty()) return; - for (auto & boxe : persp_impl->boxes) { + for (auto &boxe : persp_impl->boxes) { boxe->position_set(); } } -void -Persp3D::update_box_reprs () { +void Persp3D::update_box_reprs() +{ Persp3DImpl *persp_impl = this->perspective_impl; if (persp_impl->boxes.empty()) return; - for (auto & boxe : persp_impl->boxes) { + for (auto &boxe : persp_impl->boxes) { boxe->updateRepr(SP_OBJECT_WRITE_EXT); boxe->set_z_orders(); } } -void -Persp3D::update_z_orders () { +void Persp3D::update_z_orders() +{ Persp3DImpl *persp_impl = this->perspective_impl; if (persp_impl->boxes.empty()) return; - for (auto & boxe : persp_impl->boxes) { + for (auto &boxe : persp_impl->boxes) { boxe->set_z_orders(); } } @@ -472,61 +472,56 @@ Persp3D::update_z_orders () { // FIXME: For some reason we seem to require a vector instead of a list in Persp3D, but in vp_knot_moved_handler() // we need a list of boxes. If we can store a list in Persp3D right from the start, this function becomes // obsolete. We should do this. -std::list -Persp3D::list_of_boxes() const { +std::list Persp3D::list_of_boxes() const +{ Persp3DImpl *persp_impl = this->perspective_impl; std::list bx_lst; - for (auto & boxe : persp_impl->boxes) { + for (auto &boxe : persp_impl->boxes) { bx_lst.push_back(boxe); } return bx_lst; } -bool -Persp3D::perspectives_coincide(const Persp3D *other) const +bool Persp3D::perspectives_coincide(const Persp3D *other) const { return this->perspective_impl->tmat == other->perspective_impl->tmat; } -void -Persp3D::absorb(Persp3D *other) { +void Persp3D::absorb(Persp3D *other) +{ /* double check if we are called in sane situations */ - g_return_if_fail (this->perspectives_coincide(other) && this != other); + g_return_if_fail(this->perspectives_coincide(other) && this != other); // Note: We first need to copy the boxes of other into a separate list; // otherwise the loop below gets confused when perspectives are reattached. std::list boxes_of_persp2 = other->list_of_boxes(); - for (auto & box : boxes_of_persp2) { + for (auto &box : boxes_of_persp2) { box->switch_perspectives(other, this, true); box->updateRepr(SP_OBJECT_WRITE_EXT); // so that undo/redo can do its job properly } } -static void -persp3d_on_repr_attr_changed ( Inkscape::XML::Node * /*repr*/, - const gchar */*key*/, - const gchar */*oldval*/, - const gchar */*newval*/, - bool /*is_interactive*/, - void * data ) +static void persp3d_on_repr_attr_changed(Inkscape::XML::Node * /*repr*/, const gchar * /*key*/, + const gchar * /*oldval*/, const gchar * /*newval*/, bool /*is_interactive*/, + void *data) { if (!data) return; - Persp3D *persp = (Persp3D*) data; - persp->update_box_displays (); + Persp3D *persp = (Persp3D *)data; + persp->update_box_displays(); } /* checks whether all boxes linked to this perspective are currently selected */ -bool -Persp3D::has_all_boxes_in_selection (Inkscape::ObjectSet *set) const { +bool Persp3D::has_all_boxes_in_selection(Inkscape::ObjectSet *set) const +{ Persp3DImpl *persp_impl = this->perspective_impl; std::list selboxes = set->box3DList(); - for (auto & boxe : persp_impl->boxes) { + for (auto &boxe : persp_impl->boxes) { if (std::find(selboxes.begin(), selboxes.end(), boxe) == selboxes.end()) { // we have an unselected box in the perspective return false; @@ -537,32 +532,31 @@ Persp3D::has_all_boxes_in_selection (Inkscape::ObjectSet *set) const { /* some debugging stuff follows */ -void -Persp3D::print_debugging_info () const { +void Persp3D::print_debugging_info() const +{ Persp3DImpl *persp_impl = this->perspective_impl; - g_print ("=== Info for Persp3D %d ===\n", persp_impl->my_counter); - gchar * cstr; - for (auto & axe : Proj::axes) { + g_print("=== Info for Persp3D %d ===\n", persp_impl->my_counter); + gchar *cstr; + for (auto &axe : Proj::axes) { cstr = this->get_VP(axe).coord_string(); - g_print (" VP %s: %s\n", Proj::string_from_axis(axe), cstr); + g_print(" VP %s: %s\n", Proj::string_from_axis(axe), cstr); g_free(cstr); } cstr = this->get_VP(Proj::W).coord_string(); - g_print (" Origin: %s\n", cstr); + g_print(" Origin: %s\n", cstr); g_free(cstr); - g_print (" Boxes: "); - for (auto & boxe : persp_impl->boxes) { - g_print ("%d (%d) ", boxe->my_counter, boxe->get_perspective()->perspective_impl->my_counter); + g_print(" Boxes: "); + for (auto &boxe : persp_impl->boxes) { + g_print("%d (%d) ", boxe->my_counter, boxe->get_perspective()->perspective_impl->my_counter); } - g_print ("\n"); - g_print ("========================\n"); + g_print("\n"); + g_print("========================\n"); } -void -Persp3D::print_debugging_info_all(SPDocument *document) +void Persp3D::print_debugging_info_all(SPDocument *document) { - for (auto& child: document->getDefs()->children) { + for (auto &child : document->getDefs()->children) { if (SP_IS_PERSP3D(&child)) { SP_PERSP3D(&child)->print_debugging_info(); } @@ -570,29 +564,28 @@ Persp3D::print_debugging_info_all(SPDocument *document) Persp3D::print_all_selected(); } -void -Persp3D::print_all_selected() { - g_print ("\n======================================\n"); - g_print ("Selected perspectives and their boxes:\n"); +void Persp3D::print_all_selected() +{ + g_print("\n======================================\n"); + g_print("Selected perspectives and their boxes:\n"); std::list sel_persps = SP_ACTIVE_DESKTOP->getSelection()->perspList(); - for (auto & sel_persp : sel_persps) { + for (auto &sel_persp : sel_persps) { Persp3D *persp = SP_PERSP3D(sel_persp); Persp3DImpl *persp_impl = persp->perspective_impl; - g_print (" %s (%d): ", persp->getRepr()->attribute("id"), persp->perspective_impl->my_counter); - for (auto & boxe : persp_impl->boxes) { - g_print ("%d ", boxe->my_counter); + g_print(" %s (%d): ", persp->getRepr()->attribute("id"), persp->perspective_impl->my_counter); + for (auto &boxe : persp_impl->boxes) { + g_print("%d ", boxe->my_counter); } - g_print ("\n"); + g_print("\n"); } - g_print ("======================================\n\n"); - } + g_print("======================================\n\n"); +} -void print_current_persp3d(gchar *func_name, Persp3D *persp) { - g_print ("%s: current_persp3d is now %s\n", - func_name, - persp ? persp->getRepr()->attribute("id") : "NULL"); +void print_current_persp3d(gchar *func_name, Persp3D *persp) +{ + g_print("%s: current_persp3d is now %s\n", func_name, persp ? persp->getRepr()->attribute("id") : "NULL"); } /* diff --git a/src/object/persp3d.h b/src/object/persp3d.h index 85f6df7375d2e4d38f3f89e4a8d798208f24a03b..ce52b2c25092553a206e85d22a569ab59fdf6556 100644 --- a/src/object/persp3d.h +++ b/src/object/persp3d.h @@ -13,18 +13,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#define SP_PERSP3D(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_PERSP3D(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_PERSP3D(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_PERSP3D(obj) (dynamic_cast((SPObject *)obj) != NULL) #include #include #include -#include "transf_mat_3x4.h" #include "document.h" #include "inkscape.h" // for SP_ACTIVE_DOCUMENT - #include "sp-object.h" +#include "transf_mat_3x4.h" class SPBox3D; @@ -35,15 +34,15 @@ namespace Tools { class Box3dTool; } -} -} - +} // namespace UI +} // namespace Inkscape -class Persp3DImpl { +class Persp3DImpl +{ public: Persp3DImpl(); -//private: + // private: Proj::TransfMat3x4 tmat; // Also write the list of boxes into the xml repr and vice versa link boxes to their persp3d? @@ -53,65 +52,65 @@ public: // for debugging only int my_counter; -// friend class Persp3D; + // friend class Persp3D; }; -class Persp3D : public SPObject { +class Persp3D : public SPObject +{ public: - Persp3D(); - ~Persp3D() override; + Persp3D(); + ~Persp3D() override; Persp3DImpl *perspective_impl; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; - void update(SPCtx* ctx, unsigned int flags) override; - - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; public: // FIXME: Make more of these inline! - static Persp3D * get_from_repr (Inkscape::XML::Node *repr) { + static Persp3D *get_from_repr(Inkscape::XML::Node *repr) + { return SP_PERSP3D(SP_ACTIVE_DOCUMENT->getObjectByRepr(repr)); } - Proj::Pt2 get_VP (Proj::Axis axis) const { - return perspective_impl->tmat.column(axis); - } - Geom::Point get_PL_dir_from_pt (Geom::Point const &pt, Proj::Axis axis) const; // convenience wrapper around the following two - Geom::Point get_finite_dir (Geom::Point const &pt, Proj::Axis axis) const; - Geom::Point get_infinite_dir (Proj::Axis axis) const; - double get_infinite_angle (Proj::Axis axis) const; - static bool VP_is_finite (Persp3DImpl *persp_impl, Proj::Axis axis); - void toggle_VP (Proj::Axis axis, bool set_undo = true); - static void toggle_VPs (std::list, Proj::Axis axis); - void set_VP_state (Proj::Axis axis, Proj::VPState state); - void rotate_VP (Proj::Axis axis, double angle, bool alt_pressed); // angle is in degrees - void apply_affine_transformation (Geom::Affine const &xform); - - void add_box (SPBox3D *box); - void remove_box (SPBox3D *box); - bool has_box (SPBox3D *box) const; - - void update_box_displays (); - void update_box_reprs (); - void update_z_orders (); - unsigned int num_boxes () const { return perspective_impl->boxes.size(); } + Proj::Pt2 get_VP(Proj::Axis axis) const { return perspective_impl->tmat.column(axis); } + Geom::Point get_PL_dir_from_pt(Geom::Point const &pt, + Proj::Axis axis) const; // convenience wrapper around the following two + Geom::Point get_finite_dir(Geom::Point const &pt, Proj::Axis axis) const; + Geom::Point get_infinite_dir(Proj::Axis axis) const; + double get_infinite_angle(Proj::Axis axis) const; + static bool VP_is_finite(Persp3DImpl *persp_impl, Proj::Axis axis); + void toggle_VP(Proj::Axis axis, bool set_undo = true); + static void toggle_VPs(std::list, Proj::Axis axis); + void set_VP_state(Proj::Axis axis, Proj::VPState state); + void rotate_VP(Proj::Axis axis, double angle, bool alt_pressed); // angle is in degrees + void apply_affine_transformation(Geom::Affine const &xform); + + void add_box(SPBox3D *box); + void remove_box(SPBox3D *box); + bool has_box(SPBox3D *box) const; + + void update_box_displays(); + void update_box_reprs(); + void update_z_orders(); + unsigned int num_boxes() const { return perspective_impl->boxes.size(); } std::list list_of_boxes() const; bool perspectives_coincide(Persp3D const *rhs) const; void absorb(Persp3D *persp2); - static Persp3D * create_xml_element (SPDocument *document, Persp3DImpl *dup = nullptr); - static Persp3D * document_first_persp (SPDocument *document); + static Persp3D *create_xml_element(SPDocument *document, Persp3DImpl *dup = nullptr); + static Persp3D *document_first_persp(SPDocument *document); - bool has_all_boxes_in_selection (Inkscape::ObjectSet *set) const; + bool has_all_boxes_in_selection(Inkscape::ObjectSet *set) const; - void print_debugging_info () const; + void print_debugging_info() const; static void print_debugging_info_all(SPDocument *doc); static void print_all_selected(); }; diff --git a/src/object/sp-anchor.cpp b/src/object/sp-anchor.cpp index 721726a7bddfbd83aecd5f95ddfb5bd60de540dc..9581ba07c026f6c104d0e9255fe70ec16959e529 100644 --- a/src/object/sp-anchor.cpp +++ b/src/object/sp-anchor.cpp @@ -15,15 +15,19 @@ #define noSP_ANCHOR_VERBOSE +#include "sp-anchor.h" + #include -#include "xml/quote.h" -#include "xml/repr.h" + #include "attributes.h" -#include "sp-anchor.h" -#include "ui/view/svg-view-widget.h" #include "document.h" +#include "ui/view/svg-view-widget.h" +#include "xml/quote.h" +#include "xml/repr.h" -SPAnchor::SPAnchor() : SPGroup() { +SPAnchor::SPAnchor() + : SPGroup() +{ this->href = nullptr; this->type = nullptr; this->title = nullptr; @@ -32,7 +36,8 @@ SPAnchor::SPAnchor() : SPGroup() { SPAnchor::~SPAnchor() = default; -void SPAnchor::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPAnchor::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPGroup::build(document, repr); this->readAttr(SPAttr::XLINK_TYPE); @@ -45,7 +50,8 @@ void SPAnchor::build(SPDocument *document, Inkscape::XML::Node *repr) { this->readAttr(SPAttr::TARGET); } -void SPAnchor::release() { +void SPAnchor::release() +{ if (this->href) { g_free(this->href); this->href = nullptr; @@ -66,34 +72,35 @@ void SPAnchor::release() { SPGroup::release(); } -void SPAnchor::set(SPAttr key, const gchar* value) { +void SPAnchor::set(SPAttr key, const gchar *value) +{ switch (key) { - case SPAttr::XLINK_HREF: + case SPAttr::XLINK_HREF: g_free(this->href); this->href = g_strdup(value); this->requestModified(SP_OBJECT_MODIFIED_FLAG); this->updatePageAnchor(); break; - case SPAttr::XLINK_TYPE: + case SPAttr::XLINK_TYPE: g_free(this->type); this->type = g_strdup(value); this->updatePageAnchor(); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::XLINK_ROLE: - case SPAttr::XLINK_ARCROLE: - case SPAttr::XLINK_TITLE: + case SPAttr::XLINK_ROLE: + case SPAttr::XLINK_ARCROLE: + case SPAttr::XLINK_TITLE: g_free(this->title); this->title = g_strdup(value); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::XLINK_SHOW: - case SPAttr::XLINK_ACTUATE: - case SPAttr::TARGET: + case SPAttr::XLINK_SHOW: + case SPAttr::XLINK_ACTUATE: + case SPAttr::TARGET: this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - default: + default: SPGroup::set(key, value); break; } @@ -103,24 +110,28 @@ void SPAnchor::set(SPAttr key, const gchar* value) { * Detect if this anchor qualifies as a page link and append * the new page document to this document. */ -void SPAnchor::updatePageAnchor() { +void SPAnchor::updatePageAnchor() +{ if (this->type && !strcmp(this->type, "page")) { if (this->href && !this->page) { - this->page = this->document->createChildDoc(this->href); + this->page = this->document->createChildDoc(this->href); } - } + } } -#define COPY_ATTR(rd,rs,key) (rd)->setAttribute((key), rs->attribute(key)); +#define COPY_ATTR(rd, rs, key) (rd)->setAttribute((key), rs->attribute(key)); -Inkscape::XML::Node* SPAnchor::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPAnchor::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:a"); } repr->setAttribute("xlink:href", this->href); - if (this->type) repr->setAttribute("xlink:type", this->type); - if (this->title) repr->setAttribute("xlink:title", this->title); + if (this->type) + repr->setAttribute("xlink:type", this->type); + if (this->title) + repr->setAttribute("xlink:title", this->title); if (repr != this->getRepr()) { // XML Tree being directly used while it shouldn't be in the @@ -137,28 +148,30 @@ Inkscape::XML::Node* SPAnchor::write(Inkscape::XML::Document *xml_doc, Inkscape: return repr; } -const char* SPAnchor::displayName() const { +const char *SPAnchor::displayName() const +{ return _("Link"); } -gchar* SPAnchor::description() const { +gchar *SPAnchor::description() const +{ if (this->href) { char *quoted_href = xml_quote_strdup(this->href); char *ret = g_strdup_printf(_("to %s"), quoted_href); g_free(quoted_href); return ret; } else { - return g_strdup (_("without URI")); + return g_strdup(_("without URI")); } } /* fixme: We should forward event to appropriate container/view */ /* The only use of SPEvent appears to be here, to change the cursor in Inkview when over a link (and * which hasn't worked since at least 0.48). GUI code should not be here. */ -int SPAnchor::event(SPEvent* event) { - +int SPAnchor::event(SPEvent *event) +{ switch (event->type) { - case SPEvent::ACTIVATE: + case SPEvent::ACTIVATE: if (this->href) { // If this actually worked, it could be useful to open a webpage with the link. g_print("Activated xlink:href=\"%s\"\n", this->href); @@ -166,23 +179,21 @@ int SPAnchor::event(SPEvent* event) { } break; - case SPEvent::MOUSEOVER: - { + case SPEvent::MOUSEOVER: { if (event->view) { event->view->mouseover(); } break; } - case SPEvent::MOUSEOUT: - { + case SPEvent::MOUSEOUT: { if (event->view) { event->view->mouseout(); } break; } - default: + default: break; } diff --git a/src/object/sp-anchor.h b/src/object/sp-anchor.h index 8974c8009248876eb203872469b48816af220892..d0ef1c1a83cfaed105551e9343e349248d28bd12 100644 --- a/src/object/sp-anchor.h +++ b/src/object/sp-anchor.h @@ -16,28 +16,30 @@ #include "sp-item-group.h" -#define SP_ANCHOR(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_ANCHOR(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_ANCHOR(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_ANCHOR(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPAnchor : public SPGroup { +class SPAnchor : public SPGroup +{ public: - SPAnchor(); - ~SPAnchor() override; - - char *href; - char *type; - char *title; - SPDocument *page; - - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; - void set(SPAttr key, char const* value) override; - virtual void updatePageAnchor(); - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - - const char* displayName() const override; - char* description() const override; - int event(SPEvent *event) override; + SPAnchor(); + ~SPAnchor() override; + + char *href; + char *type; + char *title; + SPDocument *page; + + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, char const *value) override; + virtual void updatePageAnchor(); + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + + const char *displayName() const override; + char *description() const override; + int event(SPEvent *event) override; }; #endif diff --git a/src/object/sp-clippath.cpp b/src/object/sp-clippath.cpp index 31c9c1d0b2a4914dc01aaf30bf924d459cbf0432..0a7077b8fc6ba57dba18648204f48fa6b71cedd3 100644 --- a/src/object/sp-clippath.cpp +++ b/src/object/sp-clippath.cpp @@ -13,26 +13,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-clippath.h" + +#include <2geom/transforms.h> #include #include -#include "xml/repr.h" - -#include "enums.h" #include "attributes.h" #include "document.h" -#include "style.h" - -#include <2geom/transforms.h> - -#include "sp-clippath.h" -#include "sp-item.h" +#include "enums.h" #include "sp-defs.h" +#include "sp-item.h" +#include "style.h" +#include "xml/repr.h" -static SPClipPathView* sp_clippath_view_new_prepend(SPClipPathView *list, unsigned int key, Inkscape::DrawingItem *arenaitem); -static SPClipPathView* sp_clippath_view_list_remove(SPClipPathView *list, SPClipPathView *view); +static SPClipPathView *sp_clippath_view_new_prepend(SPClipPathView *list, unsigned int key, + Inkscape::DrawingItem *arenaitem); +static SPClipPathView *sp_clippath_view_list_remove(SPClipPathView *list, SPClipPathView *view); -SPClipPath::SPClipPath() : SPObjectGroup() { +SPClipPath::SPClipPath() + : SPObjectGroup() +{ this->clipPathUnits_set = FALSE; this->clipPathUnits = SP_CONTENT_UNITS_USERSPACEONUSE; @@ -41,7 +42,8 @@ SPClipPath::SPClipPath() : SPObjectGroup() { SPClipPath::~SPClipPath() = default; -void SPClipPath::build(SPDocument* doc, Inkscape::XML::Node* repr) { +void SPClipPath::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ SPObjectGroup::build(doc, repr); this->readAttr(SPAttr::STYLE); @@ -51,7 +53,8 @@ void SPClipPath::build(SPDocument* doc, Inkscape::XML::Node* repr) { doc->addResource("clipPath", this); } -void SPClipPath::release() { +void SPClipPath::release() +{ if (this->document) { // Unregister ourselves this->document->removeResource("clipPath", this); @@ -65,12 +68,13 @@ void SPClipPath::release() { SPObjectGroup::release(); } -void SPClipPath::set(SPAttr key, const gchar* value) { +void SPClipPath::set(SPAttr key, const gchar *value) +{ switch (key) { case SPAttr::CLIPPATHUNITS: this->clipPathUnits = SP_CONTENT_UNITS_USERSPACEONUSE; this->clipPathUnits_set = FALSE; - + if (value) { if (!strcmp(value, "userSpaceOnUse")) { this->clipPathUnits_set = TRUE; @@ -79,7 +83,7 @@ void SPClipPath::set(SPAttr key, const gchar* value) { this->clipPathUnits_set = TRUE; } } - + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; default: @@ -93,16 +97,18 @@ void SPClipPath::set(SPAttr key, const gchar* value) { } } -void SPClipPath::child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) { +void SPClipPath::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ /* Invoke SPObjectGroup implementation */ - SPObjectGroup::child_added(child, ref); + SPObjectGroup::child_added(child, ref); /* Show new object */ SPObject *ochild = this->document->getObjectByRepr(child); if (SP_IS_ITEM(ochild)) { for (SPClipPathView *v = this->display; v != nullptr; v = v->next) { - Inkscape::DrawingItem *ac = SP_ITEM(ochild)->invoke_show(v->arenaitem->drawing(), v->key, SP_ITEM_REFERENCE_FLAGS); + Inkscape::DrawingItem *ac = + SP_ITEM(ochild)->invoke_show(v->arenaitem->drawing(), v->key, SP_ITEM_REFERENCE_FLAGS); if (ac) { v->arenaitem->prependChild(ac); @@ -111,7 +117,8 @@ void SPClipPath::child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* re } } -void SPClipPath::update(SPCtx* ctx, unsigned int flags) { +void SPClipPath::update(SPCtx *ctx, unsigned int flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } @@ -119,12 +126,12 @@ void SPClipPath::update(SPCtx* ctx, unsigned int flags) { flags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for (auto child:l) { + for (auto child : l) { if (flags || (child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->updateDisplay(ctx, flags); } @@ -145,7 +152,8 @@ void SPClipPath::update(SPCtx* ctx, unsigned int flags) { } } -void SPClipPath::modified(unsigned int flags) { +void SPClipPath::modified(unsigned int flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } @@ -153,12 +161,12 @@ void SPClipPath::modified(unsigned int flags) { flags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for (auto child:l) { + for (auto child : l) { if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->emitModified(flags); } @@ -166,7 +174,8 @@ void SPClipPath::modified(unsigned int flags) { } } -Inkscape::XML::Node* SPClipPath::write(Inkscape::XML::Document* xml_doc, Inkscape::XML::Node* repr, guint flags) { +Inkscape::XML::Node *SPClipPath::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:clipPath"); } @@ -176,11 +185,12 @@ Inkscape::XML::Node* SPClipPath::write(Inkscape::XML::Document* xml_doc, Inkscap return repr; } -Inkscape::DrawingItem *SPClipPath::show(Inkscape::Drawing &drawing, unsigned int key) { +Inkscape::DrawingItem *SPClipPath::show(Inkscape::Drawing &drawing, unsigned int key) +{ Inkscape::DrawingGroup *ai = new Inkscape::DrawingGroup(drawing); display = sp_clippath_view_new_prepend(display, key, ai); - for (auto& child: children) { + for (auto &child : children) { if (SP_IS_ITEM(&child)) { Inkscape::DrawingItem *ac = SP_ITEM(&child)->invoke_show(drawing, key, SP_ITEM_REFERENCE_FLAGS); @@ -202,8 +212,9 @@ Inkscape::DrawingItem *SPClipPath::show(Inkscape::Drawing &drawing, unsigned int return ai; } -void SPClipPath::hide(unsigned int key) { - for (auto& child: children) { +void SPClipPath::hide(unsigned int key) +{ + for (auto &child : children) { if (SP_IS_ITEM(&child)) { SP_ITEM(&child)->invoke_hide(key); } @@ -217,7 +228,8 @@ void SPClipPath::hide(unsigned int key) { } } -void SPClipPath::setBBox(unsigned int key, Geom::OptRect const &bbox) { +void SPClipPath::setBBox(unsigned int key, Geom::OptRect const &bbox) +{ for (SPClipPathView *v = display; v != nullptr; v = v->next) { if (v->key == key) { v->bbox = bbox; @@ -226,9 +238,10 @@ void SPClipPath::setBBox(unsigned int key, Geom::OptRect const &bbox) { } } -Geom::OptRect SPClipPath::geometricBounds(Geom::Affine const &transform) { +Geom::OptRect SPClipPath::geometricBounds(Geom::Affine const &transform) +{ Geom::OptRect bbox; - for (auto& i: children) { + for (auto &i : children) { if (SP_IS_ITEM(&i)) { Geom::OptRect tmp = SP_ITEM(&i)->geometricBounds(SP_ITEM(&i)->transform * transform); bbox.unionWith(tmp); @@ -239,8 +252,7 @@ Geom::OptRect SPClipPath::geometricBounds(Geom::Affine const &transform) { /* ClipPath views */ -SPClipPathView * -sp_clippath_view_new_prepend(SPClipPathView *list, unsigned int key, Inkscape::DrawingItem *arenaitem) +SPClipPathView *sp_clippath_view_new_prepend(SPClipPathView *list, unsigned int key, Inkscape::DrawingItem *arenaitem) { SPClipPathView *new_path_view = g_new(SPClipPathView, 1); @@ -252,15 +264,15 @@ sp_clippath_view_new_prepend(SPClipPathView *list, unsigned int key, Inkscape::D return new_path_view; } -SPClipPathView * -sp_clippath_view_list_remove(SPClipPathView *list, SPClipPathView *view) +SPClipPathView *sp_clippath_view_list_remove(SPClipPathView *list, SPClipPathView *view) { if (view == list) { list = list->next; } else { SPClipPathView *prev; prev = list; - while (prev->next != view) prev = prev->next; + while (prev->next != view) + prev = prev->next; prev->next = view->next; } @@ -271,7 +283,7 @@ sp_clippath_view_list_remove(SPClipPathView *list, SPClipPathView *view) } // Create a mask element (using passed elements), add it to -const gchar *SPClipPath::create (std::vector &reprs, SPDocument *document) +const gchar *SPClipPath::create(std::vector &reprs, SPDocument *document) { Inkscape::XML::Node *defsrepr = document->getDefs()->getRepr(); diff --git a/src/object/sp-clippath.h b/src/object/sp-clippath.h index 69a34a9237b11b667497d9888461ea58c112a052..1a0467b1253f4d790e7d3ba0fbb4afd9c9e0d88d 100644 --- a/src/object/sp-clippath.h +++ b/src/object/sp-clippath.h @@ -17,14 +17,15 @@ */ #include -#include "sp-object-group.h" -#include "display/drawing.h" + #include "display/drawing-group.h" +#include "display/drawing.h" +#include "sp-object-group.h" #include "uri-references.h" #include "xml/node.h" -#define SP_CLIPPATH(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_CLIPPATH(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_CLIPPATH(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_CLIPPATH(obj) (dynamic_cast((SPObject *)obj) != NULL) namespace Inkscape { @@ -33,18 +34,19 @@ class DrawingItem; } // namespace Inkscape - -struct SPClipPathView { +struct SPClipPathView +{ SPClipPathView *next; unsigned int key; Inkscape::DrawingItem *arenaitem; Geom::OptRect bbox; }; -class SPClipPath : public SPObjectGroup { +class SPClipPath : public SPObjectGroup +{ public: - SPClipPath(); - ~SPClipPath() override; + SPClipPath(); + ~SPClipPath() override; class Reference; @@ -52,8 +54,8 @@ public: unsigned int clipPathUnits : 1; SPClipPathView *display; - static char const *create(std::vector &reprs, SPDocument *document); - //static GType sp_clippath_get_type(void); + static char const *create(std::vector &reprs, SPDocument *document); + // static GType sp_clippath_get_type(void); Inkscape::DrawingItem *show(Inkscape::Drawing &drawing, unsigned int key); void hide(unsigned int key); @@ -62,26 +64,26 @@ public: Geom::OptRect geometricBounds(Geom::Affine const &transform); protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; - -class SPClipPathReference : public Inkscape::URIReference { +class SPClipPathReference : public Inkscape::URIReference +{ public: - SPClipPathReference(SPObject *obj) : URIReference(obj) {} - SPClipPath *getObject() const { - return static_cast(URIReference::getObject()); - } + SPClipPathReference(SPObject *obj) + : URIReference(obj) + {} + SPClipPath *getObject() const { return static_cast(URIReference::getObject()); } protected: /** @@ -90,20 +92,21 @@ protected: * \return false if obj is not a clippath or if obj is a parent of this * reference's owner element. True otherwise. */ - bool _acceptObject(SPObject *obj) const override { + bool _acceptObject(SPObject *obj) const override + { if (!SP_IS_CLIPPATH(obj)) { return false; } - SPObject * const owner = this->getOwner(); + SPObject *const owner = this->getOwner(); if (!URIReference::_acceptObject(obj)) { - //XML Tree being used directly here while it shouldn't be... - Inkscape::XML::Node * const owner_repr = owner->getRepr(); - //XML Tree being used directly here while it shouldn't be... - Inkscape::XML::Node * const obj_repr = obj->getRepr(); - char const * owner_name = ""; - char const * owner_clippath = ""; - char const * obj_name = ""; - char const * obj_id = ""; + // XML Tree being used directly here while it shouldn't be... + Inkscape::XML::Node *const owner_repr = owner->getRepr(); + // XML Tree being used directly here while it shouldn't be... + Inkscape::XML::Node *const obj_repr = obj->getRepr(); + char const *owner_name = ""; + char const *owner_clippath = ""; + char const *obj_name = ""; + char const *obj_id = ""; if (owner_repr != nullptr) { owner_name = owner_repr->name(); owner_clippath = owner_repr->attribute("clippath"); @@ -113,9 +116,8 @@ protected: obj_id = obj_repr->attribute("id"); } printf("WARNING: Ignoring recursive clippath reference " - "<%s clippath=\"%s\"> in <%s id=\"%s\">", - owner_name, owner_clippath, - obj_name, obj_id); + "<%s clippath=\"%s\"> in <%s id=\"%s\">", + owner_name, owner_clippath, obj_name, obj_id); return false; } return true; diff --git a/src/object/sp-conn-end-pair.cpp b/src/object/sp-conn-end-pair.cpp index c6aa18a48592a1dffdc838034ba03e85f596b56a..3363e4bfd15cbe3a83b1e203db6ad15bdbe786fd 100644 --- a/src/object/sp-conn-end-pair.cpp +++ b/src/object/sp-conn-end-pair.cpp @@ -13,20 +13,19 @@ */ #include -#include #include +#include +#include "3rdparty/adaptagrams/libavoid/router.h" #include "attributes.h" -#include "sp-conn-end.h" -#include "uri.h" #include "display/curve.h" -#include "xml/repr.h" -#include "sp-path.h" -#include "sp-use.h" -#include "3rdparty/adaptagrams/libavoid/router.h" #include "document.h" +#include "sp-conn-end.h" #include "sp-item-group.h" - +#include "sp-path.h" +#include "sp-use.h" +#include "uri.h" +#include "xml/repr.h" SPConnEndPair::SPConnEndPair(SPPath *const owner) : _path(owner) @@ -37,16 +36,14 @@ SPConnEndPair::SPConnEndPair(SPPath *const owner) { for (unsigned handle_ix = 0; handle_ix <= 1; ++handle_ix) { this->_connEnd[handle_ix] = new SPConnEnd(SP_OBJECT(owner)); - this->_connEnd[handle_ix]->_changed_connection - = this->_connEnd[handle_ix]->ref.changedSignal() - .connect(sigc::bind(sigc::ptr_fun(sp_conn_end_href_changed), - this->_connEnd[handle_ix], owner, handle_ix)); + this->_connEnd[handle_ix]->_changed_connection = this->_connEnd[handle_ix]->ref.changedSignal().connect( + sigc::bind(sigc::ptr_fun(sp_conn_end_href_changed), this->_connEnd[handle_ix], owner, handle_ix)); } } SPConnEndPair::~SPConnEndPair() { - for (auto & handle_ix : this->_connEnd) { + for (auto &handle_ix : this->_connEnd) { delete handle_ix; handle_ix = nullptr; } @@ -54,7 +51,7 @@ SPConnEndPair::~SPConnEndPair() void SPConnEndPair::release() { - for (auto & handle_ix : this->_connEnd) { + for (auto &handle_ix : this->_connEnd) { handle_ix->_changed_connection.disconnect(); handle_ix->_delete_connection.disconnect(); handle_ix->_transformed_connection.disconnect(); @@ -86,8 +83,7 @@ void sp_conn_end_pair_build(SPObject *object) object->readAttr(SPAttr::CONNECTOR_CURVATURE); } - -static void avoid_conn_transformed(Geom::Affine const */*mp*/, SPItem *moved_item) +static void avoid_conn_transformed(Geom::Affine const * /*mp*/, SPItem *moved_item) { SPPath *path = SP_PATH(moved_item); if (path->connEndPair.isAutoRoutingConn()) { @@ -95,74 +91,71 @@ static void avoid_conn_transformed(Geom::Affine const */*mp*/, SPItem *moved_ite } } - void SPConnEndPair::setAttr(const SPAttr key, gchar const *const value) { switch (key) { - case SPAttr::CONNECTOR_TYPE: - if (value && (strcmp(value, "polyline") == 0 || strcmp(value, "orthogonal") == 0)) { - int new_conn_type = strcmp(value, "polyline") ? SP_CONNECTOR_ORTHOGONAL : SP_CONNECTOR_POLYLINE; - - if (!_connRef) { - _connType = new_conn_type; - Avoid::Router *router = _path->document->getRouter(); - _connRef = new Avoid::ConnRef(router); - _connRef->setRoutingType(new_conn_type == SP_CONNECTOR_POLYLINE ? - Avoid::ConnType_PolyLine : Avoid::ConnType_Orthogonal); - _transformed_connection = _path->connectTransformed(sigc::ptr_fun(&avoid_conn_transformed)); - } else if (new_conn_type != _connType) { - _connType = new_conn_type; - _connRef->setRoutingType(new_conn_type == SP_CONNECTOR_POLYLINE ? - Avoid::ConnType_PolyLine : Avoid::ConnType_Orthogonal); - sp_conn_reroute_path(_path); - } - } else { - _connType = SP_CONNECTOR_NOAVOID; + case SPAttr::CONNECTOR_TYPE: + if (value && (strcmp(value, "polyline") == 0 || strcmp(value, "orthogonal") == 0)) { + int new_conn_type = strcmp(value, "polyline") ? SP_CONNECTOR_ORTHOGONAL : SP_CONNECTOR_POLYLINE; + + if (!_connRef) { + _connType = new_conn_type; + Avoid::Router *router = _path->document->getRouter(); + _connRef = new Avoid::ConnRef(router); + _connRef->setRoutingType(new_conn_type == SP_CONNECTOR_POLYLINE ? Avoid::ConnType_PolyLine + : Avoid::ConnType_Orthogonal); + _transformed_connection = _path->connectTransformed(sigc::ptr_fun(&avoid_conn_transformed)); + } else if (new_conn_type != _connType) { + _connType = new_conn_type; + _connRef->setRoutingType(new_conn_type == SP_CONNECTOR_POLYLINE ? Avoid::ConnType_PolyLine + : Avoid::ConnType_Orthogonal); + sp_conn_reroute_path(_path); + } + } else { + _connType = SP_CONNECTOR_NOAVOID; - if (_connRef) { - _connRef->router()->deleteConnector(_connRef); - _connRef = nullptr; - _transformed_connection.disconnect(); + if (_connRef) { + _connRef->router()->deleteConnector(_connRef); + _connRef = nullptr; + _transformed_connection.disconnect(); + } } - } - break; - case SPAttr::CONNECTOR_CURVATURE: - if (value) { - _connCurvature = g_strtod(value, nullptr); - if (_connRef && _connRef->isInitialised()) { - // Redraw the connector, but only if it has been initialised. - sp_conn_reroute_path(_path); + break; + case SPAttr::CONNECTOR_CURVATURE: + if (value) { + _connCurvature = g_strtod(value, nullptr); + if (_connRef && _connRef->isInitialised()) { + // Redraw the connector, but only if it has been initialised. + sp_conn_reroute_path(_path); + } } - } - break; - case SPAttr::CONNECTION_START: - this->_connEnd[0]->setAttacherHref(value); - break; - case SPAttr::CONNECTION_START_POINT: - this->_connEnd[0]->setAttacherSubHref(value); - break; - case SPAttr::CONNECTION_END: - this->_connEnd[1]->setAttacherHref(value); - break; - case SPAttr::CONNECTION_END_POINT: - this->_connEnd[1]->setAttacherSubHref(value); - break; + break; + case SPAttr::CONNECTION_START: + this->_connEnd[0]->setAttacherHref(value); + break; + case SPAttr::CONNECTION_START_POINT: + this->_connEnd[0]->setAttacherSubHref(value); + break; + case SPAttr::CONNECTION_END: + this->_connEnd[1]->setAttacherHref(value); + break; + case SPAttr::CONNECTION_END_POINT: + this->_connEnd[1]->setAttacherSubHref(value); + break; } } void SPConnEndPair::writeRepr(Inkscape::XML::Node *const repr) const { - char const * const attrs[] = { - "inkscape:connection-start", "inkscape:connection-end"}; - char const * const point_attrs[] = { - "inkscape:connection-start-point", "inkscape:connection-end-point"}; + char const *const attrs[] = {"inkscape:connection-start", "inkscape:connection-end"}; + char const *const point_attrs[] = {"inkscape:connection-start-point", "inkscape:connection-end-point"}; for (unsigned handle_ix = 0; handle_ix < 2; ++handle_ix) { - const Inkscape::URI* U = this->_connEnd[handle_ix]->ref.getURI(); + const Inkscape::URI *U = this->_connEnd[handle_ix]->ref.getURI(); if (U) { auto str = U->str(); repr->setAttribute(attrs[handle_ix], str); } - const Inkscape::URI* P = this->_connEnd[handle_ix]->sub_ref.getURI(); + const Inkscape::URI *P = this->_connEnd[handle_ix]->sub_ref.getURI(); if (P) { auto str = P->str(); repr->setAttribute(point_attrs[handle_ix], str); @@ -170,29 +163,30 @@ void SPConnEndPair::writeRepr(Inkscape::XML::Node *const repr) const } if (_connType == SP_CONNECTOR_POLYLINE || _connType == SP_CONNECTOR_ORTHOGONAL) { repr->setAttribute("inkscape:connector-curvature", Glib::Ascii::dtostr(_connCurvature)); - repr->setAttribute("inkscape:connector-type", _connType == SP_CONNECTOR_POLYLINE ? "polyline" : "orthogonal" ); + repr->setAttribute("inkscape:connector-type", _connType == SP_CONNECTOR_POLYLINE ? "polyline" : "orthogonal"); } } -void SPConnEndPair::getAttachedItems(SPItem *h2attItem[2]) const { +void SPConnEndPair::getAttachedItems(SPItem *h2attItem[2]) const +{ for (unsigned h = 0; h < 2; ++h) { auto obj = this->_connEnd[h]->ref.getObject(); auto sub_obj = this->_connEnd[h]->sub_ref.getObject(); - if(sub_obj) { + if (sub_obj) { // For sub objects, we have to go fishing for the virtual/shadow // object which has the correct position for this use/symbol SPUse *use = dynamic_cast(obj); - if(use) { + if (use) { auto root = use->root(); bool found = false; - for (auto& child: root->children) { - if(!g_strcmp0(child.getAttribute("id"), sub_obj->getId())) { - h2attItem[h] = (SPItem *) &child; + for (auto &child : root->children) { + if (!g_strcmp0(child.getAttribute("id"), sub_obj->getId())) { + h2attItem[h] = (SPItem *)&child; found = true; } } - if(!found) { + if (!found) { g_warning("Couldn't find sub connector point!"); } } @@ -241,7 +235,7 @@ gdouble SPConnEndPair::getCurvature() const return _connCurvature; } -SPConnEnd** SPConnEndPair::getConnEnds() +SPConnEnd **SPConnEndPair::getConnEnds() { return _connEnd; } @@ -251,7 +245,6 @@ bool SPConnEndPair::isOrthogonal() const return _connType == SP_CONNECTOR_ORTHOGONAL; } - static void redrawConnectorCallback(void *ptr) { SPPath *path = SP_PATH(ptr); @@ -267,7 +260,6 @@ void SPConnEndPair::rerouteFromManipulation() sp_conn_reroute_path_immediate(_path); } - // Called from SPPath::update to initialise the endpoints. void SPConnEndPair::update() { @@ -291,7 +283,6 @@ void SPConnEndPair::_updateEndPoints() _connRef->setEndpoints(src, dst); } - bool SPConnEndPair::isAutoRoutingConn() { return _connType != SP_CONNECTOR_NOAVOID; @@ -304,47 +295,46 @@ void SPConnEndPair::makePathInvalid() _connRef->makePathInvalid(); } - // Redraws the curve along the recalculated route // Straight or curved void recreateCurve(SPCurve *curve, Avoid::ConnRef *connRef, const gdouble curvature) { g_assert(connRef != nullptr); - bool straight = curvature<1e-3; + bool straight = curvature < 1e-3; Avoid::PolyLine route = connRef->displayRoute(); - if (!straight) route = route.curvedPolyline(curvature); + if (!straight) + route = route.curvedPolyline(curvature); connRef->calcRouteDist(); curve->reset(); - curve->moveto( Geom::Point(route.ps[0].x, route.ps[0].y) ); + curve->moveto(Geom::Point(route.ps[0].x, route.ps[0].y)); int pn = route.size(); for (int i = 1; i < pn; ++i) { Geom::Point p(route.ps[i].x, route.ps[i].y); if (straight) { - curve->lineto( p ); + curve->lineto(p); } else { switch (route.ts[i]) { case 'M': - curve->moveto( p ); + curve->moveto(p); break; case 'L': - curve->lineto( p ); + curve->lineto(p); break; case 'C': - g_assert( i+2curveto( p, Geom::Point(route.ps[i+1].x, route.ps[i+1].y), - Geom::Point(route.ps[i+2].x, route.ps[i+2].y) ); - i+=2; + g_assert(i + 2 < pn); + curve->curveto(p, Geom::Point(route.ps[i + 1].x, route.ps[i + 1].y), + Geom::Point(route.ps[i + 2].x, route.ps[i + 2].y)); + i += 2; break; } } } } - void SPConnEndPair::tellLibavoidNewEndpoints(bool const processTransaction) { if (_connRef == nullptr || !isAutoRoutingConn()) { @@ -360,7 +350,6 @@ void SPConnEndPair::tellLibavoidNewEndpoints(bool const processTransaction) return; } - bool SPConnEndPair::reroutePathFromLibavoid() { if (_connRef == nullptr || !isAutoRoutingConn()) { @@ -378,7 +367,6 @@ bool SPConnEndPair::reroutePathFromLibavoid() return true; } - /* Local Variables: mode:c++ diff --git a/src/object/sp-conn-end-pair.h b/src/object/sp-conn-end-pair.h index 2391123504859069b876ebd8be217be291012a91..f5fc43faec365e98b7383e0d10ea242204c98e40 100644 --- a/src/object/sp-conn-end-pair.h +++ b/src/object/sp-conn-end-pair.h @@ -19,23 +19,25 @@ #include "3rdparty/adaptagrams/libavoid/connector.h" #include "attributes.h" - class SPConnEnd; class SPCurve; class SPPath; class SPItem; class SPObject; -namespace Geom { class Point; } +namespace Geom { +class Point; +} namespace Inkscape { namespace XML { class Node; } -} +} // namespace Inkscape extern void recreateCurve(SPCurve *curve, Avoid::ConnRef *connRef, double curvature); -class SPConnEndPair { +class SPConnEndPair +{ public: SPConnEndPair(SPPath *); ~SPConnEndPair(); @@ -45,7 +47,7 @@ public: void getAttachedItems(SPItem *[2]) const; void getEndpoints(Geom::Point endPts[]) const; double getCurvature() const; - SPConnEnd** getConnEnds(); + SPConnEnd **getConnEnds(); bool isOrthogonal() const; friend void recreateCurve(SPCurve *curve, Avoid::ConnRef *connRef, double curvature); void tellLibavoidNewEndpoints(bool const processTransaction = false); @@ -72,18 +74,16 @@ private: sigc::connection _transformed_connection; }; - void sp_conn_end_pair_build(SPObject *object); - // _connType options: -enum { - SP_CONNECTOR_NOAVOID, // Basic connector - a straight line. - SP_CONNECTOR_POLYLINE, // Object avoiding polyline. - SP_CONNECTOR_ORTHOGONAL // Object avoiding orthogonal polyline (only horizontal and vertical segments). +enum +{ + SP_CONNECTOR_NOAVOID, // Basic connector - a straight line. + SP_CONNECTOR_POLYLINE, // Object avoiding polyline. + SP_CONNECTOR_ORTHOGONAL // Object avoiding orthogonal polyline (only horizontal and vertical segments). }; - #endif /* !SEEN_SP_CONN_END_PAIR */ /* diff --git a/src/object/sp-conn-end.cpp b/src/object/sp-conn-end.cpp index a419ae1784cf663dd2f1aae24acaa76e6611970c..285bd4cf9218646ec9052d42a9c85431a3491337 100644 --- a/src/object/sp-conn-end.cpp +++ b/src/object/sp-conn-end.cpp @@ -10,18 +10,17 @@ #include "sp-conn-end.h" #include -#include #include +#include +#include "2geom/path-intersection.h" #include "bad-uri-exception.h" #include "display/curve.h" -#include "xml/repr.h" -#include "sp-path.h" -#include "uri.h" #include "document.h" #include "sp-item-group.h" -#include "2geom/path-intersection.h" - +#include "sp-path.h" +#include "uri.h" +#include "xml/repr.h" static void change_endpts(SPCurve *const curve, double const endPos[2]); @@ -35,35 +34,33 @@ SPConnEnd::SPConnEnd(SPObject *const owner) , _delete_connection() , _transformed_connection() , _group_connection() -{ -} +{} static SPObject const *get_nearest_common_ancestor(SPObject const *const obj, SPItem const *const objs[2]) { SPObject const *anc_sofar = obj; for (unsigned i = 0; i < 2; ++i) { - if ( objs[i] != nullptr ) { + if (objs[i] != nullptr) { anc_sofar = anc_sofar->nearestCommonAncestor(objs[i]); } } return anc_sofar; } - -static bool try_get_intersect_point_with_item_recursive(Geom::PathVector& conn_pv, SPItem* item, - const Geom::Affine& item_transform, double& intersect_pos) +static bool try_get_intersect_point_with_item_recursive(Geom::PathVector &conn_pv, SPItem *item, + const Geom::Affine &item_transform, double &intersect_pos) { double initial_pos = intersect_pos; // if this is a group... if (SP_IS_GROUP(item)) { - SPGroup* group = SP_GROUP(item); + SPGroup *group = SP_GROUP(item); // consider all first-order children double child_pos = 0.0; - std::vector g = sp_item_group_item_list(group); + std::vector g = sp_item_group_item_list(group); for (auto child_item : g) { - try_get_intersect_point_with_item_recursive(conn_pv, child_item, - item_transform * child_item->transform, child_pos); + try_get_intersect_point_with_item_recursive(conn_pv, child_item, item_transform * child_item->transform, + child_pos); if (intersect_pos < child_pos) intersect_pos = child_pos; } @@ -77,19 +74,20 @@ static bool try_get_intersect_point_with_item_recursive(Geom::PathVector& conn_p // make sure it has an associated curve auto item_curve = SPCurve::copy(shape->curve()); - if (!item_curve) return false; + if (!item_curve) + return false; // apply transformations (up to common ancestor) item_curve->transform(item_transform); - const Geom::PathVector& curve_pv = item_curve->get_pathvector(); + const Geom::PathVector &curve_pv = item_curve->get_pathvector(); Geom::CrossingSet cross = crossings(conn_pv, curve_pv); // iterate over all Crossings - //TODO: check correctness of the following code: inner loop uses loop variable + // TODO: check correctness of the following code: inner loop uses loop variable // with a name identical to the loop variable of the outer loop. Then rename. - for (const auto & cr : cross) { - for (const auto & cr_pt : cr) { - if ( intersect_pos < cr_pt.ta) + for (const auto &cr : cross) { + for (const auto &cr_pt : cr) { + if (intersect_pos < cr_pt.ta) intersect_pos = cr_pt.ta; } } @@ -97,14 +95,13 @@ static bool try_get_intersect_point_with_item_recursive(Geom::PathVector& conn_p return intersect_pos != initial_pos; } - // This function returns the outermost intersection point between the path (a connector) // and the item given. If the item is a group, then the component items are considered. // The transforms given should be to a common ancestor of both the path and item. // -static bool try_get_intersect_point_with_item(SPPath* conn, SPItem* item, - const Geom::Affine& item_transform, const Geom::Affine& conn_transform, - const bool at_start, double& intersect_pos) +static bool try_get_intersect_point_with_item(SPPath *conn, SPItem *item, const Geom::Affine &item_transform, + const Geom::Affine &conn_transform, const bool at_start, + double &intersect_pos) { // Copy the curve and apply transformations up to common ancestor. auto conn_curve = conn->curve()->copy(); @@ -137,7 +134,6 @@ static bool try_get_intersect_point_with_item(SPPath* conn, SPItem* item, return result; } - static void sp_conn_get_route_and_redraw(SPPath *const path, const bool updatePathRepr = true) { // Get the new route around obstacles. @@ -155,14 +151,13 @@ static void sp_conn_get_route_and_redraw(SPPath *const path, const bool updatePa // Set sensible values in case there the connector ends are not // attached to any shapes. Geom::PathVector conn_pv = path->curve()->get_pathvector(); - double endPos[2] = { 0.0, static_cast(conn_pv[0].size()) }; + double endPos[2] = {0.0, static_cast(conn_pv[0].size())}; for (unsigned h = 0; h < 2; ++h) { // Assume center point for all if (h2attItem[h]) { Geom::Affine h2i2anc = i2anc_affine(h2attItem[h], ancestor); - try_get_intersect_point_with_item(path, h2attItem[h], h2i2anc, path2anc, - (h == 0), endPos[h]); + try_get_intersect_point_with_item(path, h2attItem[h], h2i2anc, path2anc, (h == 0), endPos[h]); } } change_endpts(path->curve(), endPos); @@ -172,15 +167,13 @@ static void sp_conn_get_route_and_redraw(SPPath *const path, const bool updatePa } } - -static void sp_conn_end_shape_modified(SPObject */*moved_item*/, int /*flags*/, SPPath *const path) +static void sp_conn_end_shape_modified(SPObject * /*moved_item*/, int /*flags*/, SPPath *const path) { if (path->connEndPair.isAutoRoutingConn()) { path->connEndPair.tellLibavoidNewEndpoints(); } } - void sp_conn_reroute_path(SPPath *const path) { if (path->connEndPair.isAutoRoutingConn()) { @@ -188,7 +181,6 @@ void sp_conn_reroute_path(SPPath *const path) } } - void sp_conn_reroute_path_immediate(SPPath *const path) { if (path->connEndPair.isAutoRoutingConn()) { @@ -207,7 +199,6 @@ void sp_conn_redraw_path(SPPath *const path) sp_conn_get_route_and_redraw(path); } - static void change_endpts(SPCurve *const curve, double const endPos[2]) { // Use Geom::Path::portion to cut the curve at the end positions @@ -216,7 +207,7 @@ static void change_endpts(SPCurve *const curve, double const endPos[2]) curve->reset(); return; } - const Geom::Path& old_path = curve->get_pathvector()[0]; + const Geom::Path &old_path = curve->get_pathvector()[0]; Geom::PathVector new_path_vector; new_path_vector.push_back(old_path.portion(endPos[0], endPos[1])); curve->set_pathvector(new_path_vector); @@ -224,12 +215,10 @@ static void change_endpts(SPCurve *const curve, double const endPos[2]) static void sp_conn_end_deleted(SPObject *, SPObject *const owner, unsigned const handle_ix) { - char const * const attrs[] = { - "inkscape:connection-start", "inkscape:connection-end"}; + char const *const attrs[] = {"inkscape:connection-start", "inkscape:connection-end"}; owner->removeAttribute(attrs[handle_ix]); - char const * const point_attrs[] = { - "inkscape:connection-start-point", "inkscape:connection-end-point"}; + char const *const point_attrs[] = {"inkscape:connection-start-point", "inkscape:connection-end-point"}; owner->removeAttribute(point_attrs[handle_ix]); /* I believe this will trigger sp_conn_end_href_changed. */ } @@ -265,10 +254,8 @@ void SPConnEnd::setAttacherSubHref(gchar const *value) } } - - -void sp_conn_end_href_changed(SPObject */*old_ref*/, SPObject */*ref*/, - SPConnEnd *connEndPtr, SPPath *const path, unsigned const handle_ix) +void sp_conn_end_href_changed(SPObject * /*old_ref*/, SPObject * /*ref*/, SPConnEnd *connEndPtr, SPPath *const path, + unsigned const handle_ix) { g_return_if_fail(connEndPtr != nullptr); SPConnEnd &connEnd = *connEndPtr; @@ -279,26 +266,21 @@ void sp_conn_end_href_changed(SPObject */*old_ref*/, SPObject */*ref*/, if (connEnd.href) { SPObject *refobj = connEnd.ref.getObject(); if (refobj) { - connEnd._delete_connection - = refobj->connectDelete(sigc::bind(sigc::ptr_fun(&sp_conn_end_deleted), - path, handle_ix)); + connEnd._delete_connection = + refobj->connectDelete(sigc::bind(sigc::ptr_fun(&sp_conn_end_deleted), path, handle_ix)); // This allows the connector tool to dive into a group's children // And connect to their children's centers. SPObject *parent = refobj->parent; - if (SP_IS_GROUP(parent) && ! SP_IS_LAYER(parent)) { - connEnd._group_connection - = SP_ITEM(parent)->connectModified(sigc::bind(sigc::ptr_fun(&sp_conn_end_shape_modified), - path)); + if (SP_IS_GROUP(parent) && !SP_IS_LAYER(parent)) { + connEnd._group_connection = + SP_ITEM(parent)->connectModified(sigc::bind(sigc::ptr_fun(&sp_conn_end_shape_modified), path)); } - connEnd._transformed_connection - = SP_ITEM(refobj)->connectModified(sigc::bind(sigc::ptr_fun(&sp_conn_end_shape_modified), - path)); + connEnd._transformed_connection = + SP_ITEM(refobj)->connectModified(sigc::bind(sigc::ptr_fun(&sp_conn_end_shape_modified), path)); } } } - - /* Local Variables: mode:c++ diff --git a/src/object/sp-conn-end.h b/src/object/sp-conn-end.h index 1779a5b9b695b31eee22280b0710f9d2c4cbfc47..c7677d8b6ab5142b75e7b6dbc3cbf6b1ccc9b368 100644 --- a/src/object/sp-conn-end.h +++ b/src/object/sp-conn-end.h @@ -13,12 +13,13 @@ #include #include -#include "sp-use-reference.h" #include "conn-avoid-ref.h" +#include "sp-use-reference.h" class SPPath; -class SPConnEnd { +class SPConnEnd +{ public: SPConnEnd(SPObject *owner); @@ -44,23 +45,21 @@ public: /** A sigc connection for owning group transformed, used to do move compensation. */ sigc::connection _group_connection; - void setAttacherHref(char const * value); - void setAttacherSubHref(char const * value); - + void setAttacherHref(char const *value); + void setAttacherSubHref(char const *value); private: - SPConnEnd(SPConnEnd const &) = delete; // no copy + SPConnEnd(SPConnEnd const &) = delete; // no copy SPConnEnd &operator=(SPConnEnd const &) = delete; // no assign }; -void sp_conn_end_href_changed(SPObject *old_ref, SPObject *ref, - SPConnEnd *connEnd, SPPath *path, unsigned const handle_ix); +void sp_conn_end_href_changed(SPObject *old_ref, SPObject *ref, SPConnEnd *connEnd, SPPath *path, + unsigned const handle_ix); void sp_conn_reroute_path(SPPath *const path); void sp_conn_reroute_path_immediate(SPPath *const path); void sp_conn_redraw_path(SPPath *const path); void sp_conn_end_detach(SPObject *const owner, unsigned const handle_ix); - #endif /* !SEEN_SP_CONN_END */ /* diff --git a/src/object/sp-defs.cpp b/src/object/sp-defs.cpp index 6d67a2670c59fa5a040ee1f03ba00cf850f66cd1..7ed8b44f2d8eeeb17710adf12798bdf2eec7a82a 100644 --- a/src/object/sp-defs.cpp +++ b/src/object/sp-defs.cpp @@ -18,26 +18,30 @@ */ #include "sp-defs.h" -#include "xml/repr.h" + #include "document.h" +#include "xml/repr.h" -SPDefs::SPDefs() : SPObject() { -} +SPDefs::SPDefs() + : SPObject() +{} SPDefs::~SPDefs() = default; -void SPDefs::release() { - SPObject::release(); +void SPDefs::release() +{ + SPObject::release(); } -void SPDefs::update(SPCtx *ctx, guint flags) { +void SPDefs::update(SPCtx *ctx, guint flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } flags &= SP_OBJECT_MODIFIED_CASCADE; - std::vector l(this->childList(true)); - for(auto child : l){ + std::vector l(this->childList(true)); + for (auto child : l) { if (flags || (child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->updateDisplay(ctx, flags); } @@ -45,19 +49,20 @@ void SPDefs::update(SPCtx *ctx, guint flags) { } } -void SPDefs::modified(unsigned int flags) { +void SPDefs::modified(unsigned int flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } flags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for (auto child:l) { + for (auto child : l) { if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->emitModified(flags); } @@ -65,26 +70,26 @@ void SPDefs::modified(unsigned int flags) { } } -Inkscape::XML::Node* SPDefs::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPDefs::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if (flags & SP_OBJECT_WRITE_BUILD) { - if (!repr) { repr = xml_doc->createElement("svg:defs"); } std::vector l; - for (auto& child: children) { + for (auto &child : children) { Inkscape::XML::Node *crepr = child.updateRepr(xml_doc, nullptr, flags); if (crepr) { l.push_back(crepr); } } - for (auto i=l.rbegin();i!=l.rend();++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { + for (auto &child : children) { child.updateRepr(flags); } } diff --git a/src/object/sp-defs.h b/src/object/sp-defs.h index 54025bf0f42d4c797654b8eeafbeb6f44bc6f6b3..dc57c864858c22a5390d40961638ae8cc8b9afc5 100644 --- a/src/object/sp-defs.h +++ b/src/object/sp-defs.h @@ -16,19 +16,21 @@ #include "sp-object.h" -#define SP_DEFS(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_DEFS(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_DEFS(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_DEFS(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPDefs : public SPObject { +class SPDefs : public SPObject +{ public: - SPDefs(); - ~SPDefs() override; + SPDefs(); + ~SPDefs() override; protected: - void release() override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + void release() override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; #endif // !SEEN_SP_DEFS_H diff --git a/src/object/sp-desc.cpp b/src/object/sp-desc.cpp index 3b739c427fdb301e5e2930c7059c1b2feaa1e5ff..1ede5a5ddef03dc5abedb3b09517acef2e71a6b4 100644 --- a/src/object/sp-desc.cpp +++ b/src/object/sp-desc.cpp @@ -11,17 +11,20 @@ */ #include "sp-desc.h" + #include "xml/repr.h" -SPDesc::SPDesc() : SPObject() { -} +SPDesc::SPDesc() + : SPObject() +{} SPDesc::~SPDesc() = default; /** * Writes it's settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPDesc::write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) { +Inkscape::XML::Node *SPDesc::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ if (!repr) { repr = this->getRepr()->duplicate(doc); } diff --git a/src/object/sp-desc.h b/src/object/sp-desc.h index 8db0055b7635fe0d80c1e32ea66bdabb30c0096c..932d5850ec6c1b7e470622eedc1893e969949012 100644 --- a/src/object/sp-desc.h +++ b/src/object/sp-desc.h @@ -15,16 +15,17 @@ #include "sp-object.h" -#define SP_DESC(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_DESC(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_DESC(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_DESC(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPDesc : public SPObject { +class SPDesc : public SPObject +{ public: - SPDesc(); - ~SPDesc() override; + SPDesc(); + ~SPDesc() override; protected: - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif diff --git a/src/object/sp-dimensions.cpp b/src/object/sp-dimensions.cpp index a4d9585327cf6c4abba8e48f3efec0762124c756..ec2d229b42031fff9c67ec99d1ef84942f438760 100644 --- a/src/object/sp-dimensions.cpp +++ b/src/object/sp-dimensions.cpp @@ -15,11 +15,17 @@ */ #include "sp-dimensions.h" + #include "sp-item.h" void SPDimensions::calcDimsFromParentViewport(const SPItemCtx *ictx, bool assign_to_set) { -#define ASSIGN(field) { if (assign_to_set) { field._set = true; } } +#define ASSIGN(field) \ + { \ + if (assign_to_set) { \ + field._set = true; \ + } \ + } if (this->x.unit == SVGLength::PERCENT) { ASSIGN(x); this->x.computed = this->x.value * ictx->viewport.width(); diff --git a/src/object/sp-dimensions.h b/src/object/sp-dimensions.h index 2f2538c52d28deedd8bbcab9df7e563571fed9e7..db1a847ae795914d8d562973e963f3af66fa511f 100644 --- a/src/object/sp-dimensions.h +++ b/src/object/sp-dimensions.h @@ -17,8 +17,8 @@ class SPItemCtx; -class SPDimensions { - +class SPDimensions +{ public: SVGLength x; SVGLength y; diff --git a/src/object/sp-ellipse.cpp b/src/object/sp-ellipse.cpp index 5bba78e543d3dbcaeb7274b40103149bf6e15551..140c38cb333f18655ec7da64a7db5744c3879642 100644 --- a/src/object/sp-ellipse.cpp +++ b/src/object/sp-ellipse.cpp @@ -15,27 +15,26 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include - -#include "live_effects/effect.h" -#include "live_effects/lpeobject.h" -#include "live_effects/lpeobject-reference.h" +#include "sp-ellipse.h" #include <2geom/angle.h> #include <2geom/circle.h> #include <2geom/ellipse.h> #include <2geom/path-sink.h> +#include +#include #include "attributes.h" #include "display/curve.h" #include "document.h" +#include "live_effects/effect.h" +#include "live_effects/lpeobject-reference.h" +#include "live_effects/lpeobject.h" #include "preferences.h" #include "snap-candidate.h" -#include "sp-ellipse.h" #include "style.h" -#include "svg/svg.h" #include "svg/path-string.h" +#include "svg/svg.h" #define SP_2PI (2 * M_PI) @@ -45,18 +44,16 @@ SPGenericEllipse::SPGenericEllipse() , end(SP_2PI) , type(SP_GENERIC_ELLIPSE_UNDEFINED) , arc_type(SP_GENERIC_ELLIPSE_ARC_TYPE_ARC) -{ -} +{} -SPGenericEllipse::~SPGenericEllipse() -= default; +SPGenericEllipse::~SPGenericEllipse() = default; void SPGenericEllipse::build(SPDocument *document, Inkscape::XML::Node *repr) { // std::cout << "SPGenericEllipse::build: Entrance: " << this->type // << " (" << g_quark_to_string(repr->code()) << ")" << std::endl; - switch ( type ) { + switch (type) { case SP_GENERIC_ELLIPSE_ARC: this->readAttr(SPAttr::SODIPODI_CX); this->readAttr(SPAttr::SODIPODI_CY); @@ -107,87 +104,91 @@ void SPGenericEllipse::set(SPAttr key, gchar const *value) SVGLength t; switch (key) { - case SPAttr::CX: - case SPAttr::SODIPODI_CX: - if( t.read(value) ) cx = t; - cx.update( em, ex, w ); - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::CY: - case SPAttr::SODIPODI_CY: - if( t.read(value) ) cy = t; - cy.update( em, ex, h ); - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::RX: - case SPAttr::SODIPODI_RX: - if( t.read(value) && t.value > 0.0 ) rx = t; - rx.update( em, ex, w ); - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::RY: - case SPAttr::SODIPODI_RY: - if( t.read(value) && t.value > 0.0 ) ry = t; - ry.update( em, ex, h ); - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::R: - if( t.read(value) && t.value > 0.0 ) { - this->ry = this->rx = t; - } - rx.update( em, ex, d ); - ry.update( em, ex, d ); - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::SODIPODI_START: - if (value) { - sp_svg_number_read_d(value, &this->start); - } else { - this->start = 0; - } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::SODIPODI_END: - if (value) { - sp_svg_number_read_d(value, &this->end); - } else { - this->end = 2 * M_PI; - } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + case SPAttr::CX: + case SPAttr::SODIPODI_CX: + if (t.read(value)) + cx = t; + cx.update(em, ex, w); + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::SODIPODI_OPEN: - // This is only for reading in old files so rely on constructor to set default. - if (!value) { // Only set if not "true" - this->arc_type = SP_GENERIC_ELLIPSE_ARC_TYPE_SLICE; - } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::SODIPODI_ARC_TYPE: - // To read in old files that use 'open', we need to not set if value is null. - // We could also check inkscape version. - if (value) { - if (!strcmp(value,"arc")) { - this->arc_type = SP_GENERIC_ELLIPSE_ARC_TYPE_ARC; - } else if (!strcmp(value,"chord")) { - this->arc_type = SP_GENERIC_ELLIPSE_ARC_TYPE_CHORD; + case SPAttr::CY: + case SPAttr::SODIPODI_CY: + if (t.read(value)) + cy = t; + cy.update(em, ex, h); + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::RX: + case SPAttr::SODIPODI_RX: + if (t.read(value) && t.value > 0.0) + rx = t; + rx.update(em, ex, w); + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::RY: + case SPAttr::SODIPODI_RY: + if (t.read(value) && t.value > 0.0) + ry = t; + ry.update(em, ex, h); + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::R: + if (t.read(value) && t.value > 0.0) { + this->ry = this->rx = t; + } + rx.update(em, ex, d); + ry.update(em, ex, d); + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::SODIPODI_START: + if (value) { + sp_svg_number_read_d(value, &this->start); + } else { + this->start = 0; + } + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::SODIPODI_END: + if (value) { + sp_svg_number_read_d(value, &this->end); } else { + this->end = 2 * M_PI; + } + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::SODIPODI_OPEN: + // This is only for reading in old files so rely on constructor to set default. + if (!value) { // Only set if not "true" this->arc_type = SP_GENERIC_ELLIPSE_ARC_TYPE_SLICE; } - } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::SODIPODI_ARC_TYPE: + // To read in old files that use 'open', we need to not set if value is null. + // We could also check inkscape version. + if (value) { + if (!strcmp(value, "arc")) { + this->arc_type = SP_GENERIC_ELLIPSE_ARC_TYPE_ARC; + } else if (!strcmp(value, "chord")) { + this->arc_type = SP_GENERIC_ELLIPSE_ARC_TYPE_CHORD; + } else { + this->arc_type = SP_GENERIC_ELLIPSE_ARC_TYPE_SLICE; + } + } + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - default: - SPShape::set(key, value); - break; + default: + SPShape::set(key, value); + break; } } @@ -195,7 +196,7 @@ void SPGenericEllipse::update(SPCtx *ctx, guint flags) { // std::cout << "\nSPGenericEllipse::update: Entrance" << std::endl; if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - Geom::Rect const &viewbox = ((SPItemCtx const *) ctx)->viewport; + Geom::Rect const &viewbox = ((SPItemCtx const *)ctx)->viewport; double const dx = viewbox.width(); double const dy = viewbox.height(); @@ -222,9 +223,9 @@ Inkscape::XML::Node *SPGenericEllipse::write(Inkscape::XML::Document *xml_doc, I // << ")" << std::endl; GenericEllipseType new_type = SP_GENERIC_ELLIPSE_UNDEFINED; - if (_isSlice() || hasPathEffect() ) { + if (_isSlice() || hasPathEffect()) { new_type = SP_GENERIC_ELLIPSE_ARC; - } else if ( rx.computed == ry.computed ) { + } else if (rx.computed == ry.computed) { new_type = SP_GENERIC_ELLIPSE_CIRCLE; } else { new_type = SP_GENERIC_ELLIPSE_ELLIPSE; @@ -232,9 +233,7 @@ Inkscape::XML::Node *SPGenericEllipse::write(Inkscape::XML::Document *xml_doc, I // std::cout << " new_type: " << new_type << std::endl; if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { - - switch ( new_type ) { - + switch (new_type) { case SP_GENERIC_ELLIPSE_ARC: repr = xml_doc->createElement("svg:path"); break; @@ -273,7 +272,7 @@ Inkscape::XML::Node *SPGenericEllipse::write(Inkscape::XML::Document *xml_doc, I // << " rx: " << rx.write() << " " << rx.computed // << " ry: " << ry.write() << " " << ry.computed << std::endl; - switch ( type ) { + switch (type) { case SP_GENERIC_ELLIPSE_UNDEFINED: case SP_GENERIC_ELLIPSE_ARC: @@ -284,7 +283,6 @@ Inkscape::XML::Node *SPGenericEllipse::write(Inkscape::XML::Document *xml_doc, I repr->removeAttribute("r"); if (flags & SP_OBJECT_WRITE_EXT) { - repr->setAttribute("sodipodi:type", "arc"); sp_repr_set_svg_length(repr, "sodipodi:cx", cx); sp_repr_set_svg_length(repr, "sodipodi:cy", cy); @@ -296,7 +294,7 @@ Inkscape::XML::Node *SPGenericEllipse::write(Inkscape::XML::Document *xml_doc, I sp_repr_set_svg_double(repr, "sodipodi:start", start); sp_repr_set_svg_double(repr, "sodipodi:end", end); - switch ( arc_type ) { + switch (arc_type) { case SP_GENERIC_ELLIPSE_ARC_TYPE_SLICE: repr->removeAttribute("sodipodi:open"); // For backwards compat. repr->setAttribute("sodipodi:arc-type", "slice"); @@ -328,7 +326,7 @@ Inkscape::XML::Node *SPGenericEllipse::write(Inkscape::XML::Document *xml_doc, I case SP_GENERIC_ELLIPSE_CIRCLE: sp_repr_set_svg_length(repr, "cx", cx); sp_repr_set_svg_length(repr, "cy", cy); - sp_repr_set_svg_length(repr, "r", rx); + sp_repr_set_svg_length(repr, "r", rx); repr->removeAttribute("rx"); repr->removeAttribute("ry"); repr->removeAttribute("sodipodi:cx"); @@ -374,13 +372,12 @@ Inkscape::XML::Node *SPGenericEllipse::write(Inkscape::XML::Document *xml_doc, I const char *SPGenericEllipse::displayName() const { - - switch ( type ) { + switch (type) { case SP_GENERIC_ELLIPSE_UNDEFINED: case SP_GENERIC_ELLIPSE_ARC: if (_isSlice()) { - switch ( arc_type ) { + switch (arc_type) { case SP_GENERIC_ELLIPSE_ARC_TYPE_SLICE: return _("Slice"); break; @@ -412,7 +409,8 @@ void SPGenericEllipse::set_shape() { // std::cout << "SPGenericEllipse::set_shape: Entrance" << std::endl; if (hasBrokenPathEffect()) { - g_warning("The ellipse shape has unknown LPE on it! Convert to path to make it editable preserving the appearance; editing it as ellipse will remove the bad LPE"); + g_warning("The ellipse shape has unknown LPE on it! Convert to path to make it editable preserving the " + "appearance; editing it as ellipse will remove the bad LPE"); if (this->getRepr()->attribute("d")) { // unconditionally read the curve from d, if any, to preserve appearance @@ -433,19 +431,22 @@ void SPGenericEllipse::set_shape() if (!this->_isSlice()) { start = 0.0; - end = 2.0*M_PI; + end = 2.0 * M_PI; } double incr = end - start; // arc angle - if (incr < 0.0) incr += 2.0*M_PI; + if (incr < 0.0) + incr += 2.0 * M_PI; - int numsegs = 1 + int(incr*2.0/M_PI); // number of arc segments - if (numsegs > 4) numsegs = 4; + int numsegs = 1 + int(incr * 2.0 / M_PI); // number of arc segments + if (numsegs > 4) + numsegs = 4; - incr = incr/numsegs; // limit arc angle to less than 90 degrees + incr = incr / numsegs; // limit arc angle to less than 90 degrees Geom::Path path(Geom::Point::polar(start)); - Geom::EllipticalArc* arc; + Geom::EllipticalArc *arc; for (int seg = 0; seg < numsegs; seg++) { - arc = circle.arc(Geom::Point::polar(start + seg*incr), Geom::Point::polar(start + (seg + 0.5)*incr), Geom::Point::polar(start + (seg + 1.0)*incr)); + arc = circle.arc(Geom::Point::polar(start + seg * incr), Geom::Point::polar(start + (seg + 0.5) * incr), + Geom::Point::polar(start + (seg + 1.0) * incr)); path.append(*arc); delete arc; } @@ -455,7 +456,7 @@ void SPGenericEllipse::set_shape() pb.lineTo(Geom::Point(0, 0)); } - if ( !(this->arc_type == SP_GENERIC_ELLIPSE_ARC_TYPE_ARC) ) { + if (!(this->arc_type == SP_GENERIC_ELLIPSE_ARC_TYPE_ARC)) { pb.closePath(); } else { pb.flush(); @@ -470,9 +471,10 @@ void SPGenericEllipse::set_shape() // Stretching / moving the calculated shape to fit the actual dimensions. Geom::Affine aff = Geom::Scale(rx.computed, ry.computed) * Geom::Translate(cx.computed, cy.computed); c->transform(aff); - + /* Reset the shape's curve to the "original_curve" - * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in shape)*/ + * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in + * shape)*/ auto const before = this->curveBeforeLPE(); if (before && before->get_pathvector() != c->get_pathvector()) { setCurveBeforeLPE(std::move(c)); @@ -521,11 +523,11 @@ Geom::Affine SPGenericEllipse::set_transform(Geom::Affine const &xform) } if (this->rx._set) { - this->rx.scale( sw ); + this->rx.scale(sw); } if (this->ry._set) { - this->ry.scale( sh ); + this->ry.scale(sh); } /* Find start in item coords */ @@ -543,14 +545,15 @@ Geom::Affine SPGenericEllipse::set_transform(Geom::Affine const &xform) // Adjust gradient fill this->adjust_gradient(xform * ret.inverse()); - + return ret; } -void SPGenericEllipse::snappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const +void SPGenericEllipse::snappoints(std::vector &p, + Inkscape::SnapPreferences const *snapprefs) const { - // CPPIFY: is this call necessary? - const_cast(this)->normalize(); + // CPPIFY: is this call necessary? + const_cast(this)->normalize(); Geom::Affine const i2dt = this->i2dt_affine(); @@ -560,14 +563,14 @@ void SPGenericEllipse::snappoints(std::vector &p, for (double angle = 0; angle < SP_2PI; angle += M_PI_2) { if (Geom::AngleInterval(this->start, this->end, true).contains(angle)) { Geom::Point pt = this->getPointAtAngle(angle) * i2dt; - p.emplace_back(pt, Inkscape::SNAPSOURCE_ELLIPSE_QUADRANT_POINT, Inkscape::SNAPTARGET_ELLIPSE_QUADRANT_POINT); + p.emplace_back(pt, Inkscape::SNAPSOURCE_ELLIPSE_QUADRANT_POINT, + Inkscape::SNAPTARGET_ELLIPSE_QUADRANT_POINT); } } } double cx = this->cx.computed; double cy = this->cy.computed; - bool slice = this->_isSlice(); @@ -608,7 +611,8 @@ void SPGenericEllipse::modified(guint flags) SPShape::modified(flags); } -void SPGenericEllipse::update_patheffect(bool write) { +void SPGenericEllipse::update_patheffect(bool write) +{ SPShape::update_patheffect(write); } @@ -639,7 +643,7 @@ bool SPGenericEllipse::set_elliptical_path_attribute(Inkscape::XML::Node *repr) this->set_shape(); if (_curve) { - gchar* d = sp_svg_write_path(_curve->get_pathvector()); + gchar *d = sp_svg_write_path(_curve->get_pathvector()); repr->setAttribute("d", d); @@ -658,7 +662,7 @@ void SPGenericEllipse::position_set(gdouble x, gdouble y, gdouble rx, gdouble ry this->rx = rx; this->ry = ry; - Inkscape::Preferences * prefs = Inkscape::Preferences::get(); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); // those pref values are in degrees, while we want radians if (prefs->getDouble("/tools/shapes/arc/start", 0.0) != 0) { @@ -684,7 +688,8 @@ bool SPGenericEllipse::_isSlice() const /** Returns the ratio in which the vector from p0 to p1 is stretched by transform */ -gdouble SPGenericEllipse::vectorStretch(Geom::Point p0, Geom::Point p1, Geom::Affine xform) { +gdouble SPGenericEllipse::vectorStretch(Geom::Point p0, Geom::Point p1, Geom::Affine xform) +{ if (p0 == p1) { return 0; } @@ -692,52 +697,52 @@ gdouble SPGenericEllipse::vectorStretch(Geom::Point p0, Geom::Point p1, Geom::Af return (Geom::distance(p0 * xform, p1 * xform) / Geom::distance(p0, p1)); } -void SPGenericEllipse::setVisibleRx(gdouble rx) { +void SPGenericEllipse::setVisibleRx(gdouble rx) +{ if (rx == 0) { this->rx.unset(); } else { - this->rx = rx / SPGenericEllipse::vectorStretch( - Geom::Point(this->cx.computed + 1, this->cy.computed), - Geom::Point(this->cx.computed, this->cy.computed), - this->i2doc_affine()); + this->rx = rx / SPGenericEllipse::vectorStretch(Geom::Point(this->cx.computed + 1, this->cy.computed), + Geom::Point(this->cx.computed, this->cy.computed), + this->i2doc_affine()); } this->updateRepr(); } -void SPGenericEllipse::setVisibleRy(gdouble ry) { +void SPGenericEllipse::setVisibleRy(gdouble ry) +{ if (ry == 0) { this->ry.unset(); } else { - this->ry = ry / SPGenericEllipse::vectorStretch( - Geom::Point(this->cx.computed, this->cy.computed + 1), - Geom::Point(this->cx.computed, this->cy.computed), - this->i2doc_affine()); + this->ry = ry / SPGenericEllipse::vectorStretch(Geom::Point(this->cx.computed, this->cy.computed + 1), + Geom::Point(this->cx.computed, this->cy.computed), + this->i2doc_affine()); } this->updateRepr(); } -gdouble SPGenericEllipse::getVisibleRx() const { +gdouble SPGenericEllipse::getVisibleRx() const +{ if (!this->rx._set) { return 0; } - return this->rx.computed * SPGenericEllipse::vectorStretch( - Geom::Point(this->cx.computed + 1, this->cy.computed), - Geom::Point(this->cx.computed, this->cy.computed), - this->i2doc_affine()); + return this->rx.computed * SPGenericEllipse::vectorStretch(Geom::Point(this->cx.computed + 1, this->cy.computed), + Geom::Point(this->cx.computed, this->cy.computed), + this->i2doc_affine()); } -gdouble SPGenericEllipse::getVisibleRy() const { +gdouble SPGenericEllipse::getVisibleRy() const +{ if (!this->ry._set) { return 0; } - return this->ry.computed * SPGenericEllipse::vectorStretch( - Geom::Point(this->cx.computed, this->cy.computed + 1), - Geom::Point(this->cx.computed, this->cy.computed), - this->i2doc_affine()); + return this->ry.computed * SPGenericEllipse::vectorStretch(Geom::Point(this->cx.computed, this->cy.computed + 1), + Geom::Point(this->cx.computed, this->cy.computed), + this->i2doc_affine()); } /* diff --git a/src/object/sp-ellipse.h b/src/object/sp-ellipse.h index ab992e3eec792f31791683f2307dd0b1ac173368..22354bf830fcd919e88faf83fe07c72be4962af5 100644 --- a/src/object/sp-ellipse.h +++ b/src/object/sp-ellipse.h @@ -17,27 +17,30 @@ #ifndef SEEN_SP_ELLIPSE_H #define SEEN_SP_ELLIPSE_H -#include "svg/svg-length.h" #include "sp-shape.h" +#include "svg/svg-length.h" /* Common parent class */ -#define SP_GENERICELLIPSE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_GENERICELLIPSE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_GENERICELLIPSE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_GENERICELLIPSE(obj) (dynamic_cast((SPObject *)obj) != NULL) -enum GenericEllipseType { +enum GenericEllipseType +{ SP_GENERIC_ELLIPSE_UNDEFINED, // FIXME shouldn't exist SP_GENERIC_ELLIPSE_ARC, SP_GENERIC_ELLIPSE_CIRCLE, SP_GENERIC_ELLIPSE_ELLIPSE }; -enum GenericEllipseArcType { +enum GenericEllipseArcType +{ SP_GENERIC_ELLIPSE_ARC_TYPE_SLICE, // Default SP_GENERIC_ELLIPSE_ARC_TYPE_ARC, SP_GENERIC_ELLIPSE_ARC_TYPE_CHORD }; -class SPGenericEllipse : public SPShape { +class SPGenericEllipse : public SPShape +{ public: SPGenericEllipse(); ~SPGenericEllipse() override; @@ -62,14 +65,16 @@ public: void set(SPAttr key, char const *value) override; void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; const char *displayName() const override; void set_shape() override; void update_patheffect(bool write) override; Geom::Affine set_transform(Geom::Affine const &xform) override; - void snappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const override; + void snappoints(std::vector &p, + Inkscape::SnapPreferences const *snapprefs) const override; void modified(unsigned int flags) override; diff --git a/src/object/sp-factory.cpp b/src/object/sp-factory.cpp index f0d84afb25c6a84975fecbf8fc494955d8441615..a58ab2557f8b3156594da5064c2de2eb00e5f258 100644 --- a/src/object/sp-factory.cpp +++ b/src/object/sp-factory.cpp @@ -12,9 +12,10 @@ #include "sp-factory.h" // primary -#include "box3d.h" #include "box3d-side.h" +#include "box3d.h" #include "color-profile.h" +#include "live_effects/lpeobject.h" #include "persp3d.h" #include "sp-anchor.h" #include "sp-clippath.h" @@ -25,13 +26,13 @@ #include "sp-flowdiv.h" #include "sp-flowregion.h" #include "sp-flowtext.h" -#include "sp-font.h" #include "sp-font-face.h" -#include "sp-glyph.h" +#include "sp-font.h" #include "sp-glyph-kerning.h" +#include "sp-glyph.h" #include "sp-guide.h" -#include "sp-hatch.h" #include "sp-hatch-path.h" +#include "sp-hatch.h" #include "sp-image.h" #include "sp-line.h" #include "sp-linear-gradient.h" @@ -59,21 +60,20 @@ #include "sp-style-elem.h" #include "sp-switch.h" #include "sp-symbol.h" -#include "sp-tag.h" #include "sp-tag-use.h" +#include "sp-tag.h" #include "sp-text.h" #include "sp-textpath.h" #include "sp-title.h" #include "sp-tref.h" #include "sp-tspan.h" #include "sp-use.h" -#include "live_effects/lpeobject.h" // filters #include "filters/blend.h" #include "filters/colormatrix.h" -#include "filters/componenttransfer.h" #include "filters/componenttransfer-funcnode.h" +#include "filters/componenttransfer.h" #include "filters/composite.h" #include "filters/convolvematrix.h" #include "filters/diffuselighting.h" @@ -92,7 +92,7 @@ #include "filters/tile.h" #include "filters/turbulence.h" -SPObject *SPFactory::createObject(std::string const& id) +SPObject *SPFactory::createObject(std::string const &id) { SPObject *ret = nullptr; @@ -124,8 +124,7 @@ SPObject *SPFactory::createObject(std::string const& id) SPGenericEllipse *a = new SPGenericEllipse; a->type = SP_GENERIC_ELLIPSE_ARC; ret = a; - } - else if (id == "svg:filter") + } else if (id == "svg:filter") ret = new SPFilter; else if (id == "svg:flowDiv") ret = new SPFlowdiv; @@ -162,8 +161,7 @@ SPObject *SPFactory::createObject(std::string const& id) else if (id == "svg:hatchPath") { std::cerr << "Warning: has been renamed " << std::endl; ret = new SPHatchPath; - } - else if (id == "svg:image") + } else if (id == "svg:image") ret = new SPImage; else if (id == "svg:g") ret = new SPGroup; @@ -175,22 +173,19 @@ SPObject *SPFactory::createObject(std::string const& id) ret = new SPMarker; else if (id == "svg:mask") ret = new SPMask; - else if (id == "svg:mesh") { // SVG 2 old + else if (id == "svg:mesh") { // SVG 2 old ret = new SPMeshGradient; std::cerr << "Warning: has been renamed ." << std::endl; std::cerr << "Warning: has been repurposed as a shape that tightly wraps a ." << std::endl; - } - else if (id == "svg:meshGradient") { // SVG 2 old + } else if (id == "svg:meshGradient") { // SVG 2 old ret = new SPMeshGradient; std::cerr << "Warning: has been renamed " << std::endl; - } - else if (id == "svg:meshgradient") // SVG 2 + } else if (id == "svg:meshgradient") // SVG 2 ret = new SPMeshGradient; else if (id == "svg:meshPatch") { ret = new SPMeshpatch; std::cerr << "Warning: and have been renamed and " << std::endl; - } - else if (id == "svg:meshpatch") + } else if (id == "svg:meshpatch") ret = new SPMeshpatch; else if (id == "svg:meshRow") ret = new SPMeshrow; @@ -225,8 +220,7 @@ SPObject *SPFactory::createObject(std::string const& id) else if (id == "svg:solidColor") { ret = new SPSolidColor; std::cerr << "Warning: has been renamed " << std::endl; - } - else if (id == "svg:solidcolor") + } else if (id == "svg:solidcolor") ret = new SPSolidColor; else if (id == "spiral") ret = new SPSpiral; @@ -261,7 +255,6 @@ SPObject *SPFactory::createObject(std::string const& id) else if (id == "inkscape:path-effect") ret = new LivePathEffectObject; - // filters else if (id == "svg:feBlend") ret = new SPFeBlend; @@ -312,16 +305,16 @@ SPObject *SPFactory::createObject(std::string const& id) else if (id == "svg:feTurbulence") ret = new SPFeTurbulence; else if (id == "inkscape:grid") - ret = new SPObject; // TODO wtf + ret = new SPObject; // TODO wtf else if (id == "rdf:RDF") // no SP node yet - {} - else if (id == "inkscape:clipboard") // SP node not necessary - {} - else if (id == "inkscape:templateinfo" || id == "inkscape:_templateinfo") // metadata for templates - {} - else if (id.empty()) // comments - {} - else { + { + } else if (id == "inkscape:clipboard") // SP node not necessary + { + } else if (id == "inkscape:templateinfo" || id == "inkscape:_templateinfo") // metadata for templates + { + } else if (id.empty()) // comments + { + } else { fprintf(stderr, "WARNING: unknown type: %s\n", id.c_str()); } @@ -333,23 +326,23 @@ std::string NodeTraits::get_type_string(Inkscape::XML::Node const &node) std::string name; switch (node.type()) { - case Inkscape::XML::TEXT_NODE: - name = "string"; - break; + case Inkscape::XML::TEXT_NODE: + name = "string"; + break; - case Inkscape::XML::ELEMENT_NODE: { - char const *const sptype = node.attribute("sodipodi:type"); + case Inkscape::XML::ELEMENT_NODE: { + char const *const sptype = node.attribute("sodipodi:type"); - if (sptype) { - name = sptype; - } else { - name = node.name(); + if (sptype) { + name = sptype; + } else { + name = node.name(); + } + break; } - break; - } - default: - name = ""; - break; + default: + name = ""; + break; } return name; diff --git a/src/object/sp-factory.h b/src/object/sp-factory.h index f87d84a26b86560bd3e08d2110afea092706f4d8..1a858606dfa1466554cdb94055a1b3124f867249 100644 --- a/src/object/sp-factory.h +++ b/src/object/sp-factory.h @@ -20,13 +20,15 @@ namespace Inkscape { namespace XML { class Node; } -} +} // namespace Inkscape -struct SPFactory { - static SPObject *createObject(std::string const& id); +struct SPFactory +{ + static SPObject *createObject(std::string const &id); }; -struct NodeTraits { +struct NodeTraits +{ static std::string get_type_string(Inkscape::XML::Node const &node); }; diff --git a/src/object/sp-filter-reference.cpp b/src/object/sp-filter-reference.cpp index 66e5e127a4bae8d6ed26e57f1bc2bd034ed4e916..2064374bac240f5d265367e86fd3b5d06cd52666 100644 --- a/src/object/sp-filter-reference.cpp +++ b/src/object/sp-filter-reference.cpp @@ -7,18 +7,17 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "sp-filter.h" #include "sp-filter-reference.h" -bool -SPFilterReference::_acceptObject(SPObject *obj) const +#include "sp-filter.h" + +bool SPFilterReference::_acceptObject(SPObject *obj) const { return SP_IS_FILTER(obj) && URIReference::_acceptObject(obj); /* effic: Don't bother making this an inline function: _acceptObject is a virtual function, typically called from a context where the runtime type is not known at compile time. */ } - /* Local Variables: mode:c++ diff --git a/src/object/sp-filter-reference.h b/src/object/sp-filter-reference.h index 2230e0144467c5767ad6044bfbf79eba2e2813da..2b7e84af8ef3b40507d97d6ebbb2f849b0b6198c 100644 --- a/src/object/sp-filter-reference.h +++ b/src/object/sp-filter-reference.h @@ -10,20 +10,23 @@ #ifndef SEEN_SP_FILTER_REFERENCE_H #define SEEN_SP_FILTER_REFERENCE_H -#include "uri-references.h" #include "sp-filter.h" // Required for the static_cast. +#include "uri-references.h" class SPObject; class SPDocument; -class SPFilterReference : public Inkscape::URIReference { +class SPFilterReference : public Inkscape::URIReference +{ public: - SPFilterReference(SPObject *obj) : URIReference(obj) {} - SPFilterReference(SPDocument *doc) : URIReference(doc) {} + SPFilterReference(SPObject *obj) + : URIReference(obj) + {} + SPFilterReference(SPDocument *doc) + : URIReference(doc) + {} - SPFilter *getObject() const { - return static_cast(URIReference::getObject()); - } + SPFilter *getObject() const { return static_cast(URIReference::getObject()); } protected: bool _acceptObject(SPObject *obj) const override; diff --git a/src/object/sp-filter-units.h b/src/object/sp-filter-units.h index 7bdd1db28ac9d2f226798d776202899de5530513..7657f9576eaa0ceee4034c7f75095514727e971f 100644 --- a/src/object/sp-filter-units.h +++ b/src/object/sp-filter-units.h @@ -10,12 +10,12 @@ #ifndef SEEN_SP_FILTER_UNITS_H #define SEEN_SP_FILTER_UNITS_H -enum SPFilterUnits { +enum SPFilterUnits +{ SP_FILTER_UNITS_OBJECTBOUNDINGBOX, SP_FILTER_UNITS_USERSPACEONUSE }; - #endif /* !SEEN_SP_FILTER_UNITS_H */ /* diff --git a/src/object/sp-filter.cpp b/src/object/sp-filter.cpp index 28bfd3229fd267f6d0d394a403d4b44fa8983a54..8fc0498f66a1d634a4957bbf337d8d334f7df3cc 100644 --- a/src/object/sp-filter.cpp +++ b/src/object/sp-filter.cpp @@ -16,31 +16,34 @@ #include "sp-filter.h" -#include #include +#include +#include #include #include -#include - -#include "bad-uri-exception.h" #include "attributes.h" +#include "bad-uri-exception.h" #include "display/nr-filter.h" #include "document.h" -#include "sp-filter-reference.h" #include "filters/sp-filter-primitive.h" +#include "sp-filter-reference.h" #include "uri.h" #include "xml/repr.h" static void filter_ref_changed(SPObject *old_ref, SPObject *ref, SPFilter *filter); static void filter_ref_modified(SPObject *href, guint flags, SPFilter *filter); - SPFilter::SPFilter() - : SPObject(), filterUnits(SP_FILTER_UNITS_OBJECTBOUNDINGBOX), filterUnits_set(FALSE), - primitiveUnits(SP_FILTER_UNITS_USERSPACEONUSE), primitiveUnits_set(FALSE), - filterRes(NumberOptNumber()), - _renderer(nullptr), _image_name(new std::map), _image_number_next(0) + : SPObject() + , filterUnits(SP_FILTER_UNITS_OBJECTBOUNDINGBOX) + , filterUnits_set(FALSE) + , primitiveUnits(SP_FILTER_UNITS_USERSPACEONUSE) + , primitiveUnits_set(FALSE) + , filterRes(NumberOptNumber()) + , _renderer(nullptr) + , _image_name(new std::map) + , _image_number_next(0) { this->href = new SPFilterReference(this); this->href->changedSignal().connect(sigc::bind(sigc::ptr_fun(filter_ref_changed), this)); @@ -55,14 +58,14 @@ SPFilter::SPFilter() SPFilter::~SPFilter() = default; - /** * Reads the Inkscape::XML::Node, and initializes SPFilter variables. For this to get called, * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void SPFilter::build(SPDocument *document, Inkscape::XML::Node *repr) { - //Read values of key attributes from XML nodes into object. +void SPFilter::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + // Read values of key attributes from XML nodes into object. this->readAttr(SPAttr::STYLE); // struct not derived from SPItem, we need to do this ourselves. this->readAttr(SPAttr::FILTERUNITS); this->readAttr(SPAttr::PRIMITIVEUNITS); @@ -74,24 +77,25 @@ void SPFilter::build(SPDocument *document, Inkscape::XML::Node *repr) { this->readAttr(SPAttr::XLINK_HREF); this->_refcount = 0; - SPObject::build(document, repr); + SPObject::build(document, repr); -//is this necessary? + // is this necessary? document->addResource("filter", this); } /** * Drops any allocated memory. */ -void SPFilter::release() { +void SPFilter::release() +{ if (this->document) { // Unregister ourselves this->document->removeResource("filter", this); } -//TODO: release resources here + // TODO: release resources here - //release href + // release href if (this->href) { this->modified_connection.disconnect(); this->href->detach(); @@ -99,7 +103,8 @@ void SPFilter::release() { this->href = nullptr; } - for (std::map::const_iterator i = this->_image_name->begin() ; i != this->_image_name->end() ; ++i) { + for (std::map::const_iterator i = this->_image_name->begin(); i != this->_image_name->end(); + ++i) { g_free(i->first); } @@ -111,7 +116,8 @@ void SPFilter::release() { /** * Sets a specific value in the SPFilter. */ -void SPFilter::set(SPAttr key, gchar const *value) { +void SPFilter::set(SPAttr key, gchar const *value) +{ switch (key) { case SPAttr::FILTERUNITS: if (value) { @@ -179,37 +185,35 @@ void SPFilter::set(SPAttr key, gchar const *value) { break; default: // See if any parents need this value. - SPObject::set(key, value); + SPObject::set(key, value); break; } } - /** * Returns the number of references to the filter. */ -guint SPFilter::getRefCount() { - // NOTE: this is currently updated by sp_style_filter_ref_changed() in style.cpp - return _refcount; +guint SPFilter::getRefCount() +{ + // NOTE: this is currently updated by sp_style_filter_ref_changed() in style.cpp + return _refcount; } /** * Receives update notifications. */ -void SPFilter::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - - SPItemCtx *ictx = (SPItemCtx *) ctx; +void SPFilter::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { + SPItemCtx *ictx = (SPItemCtx *)ctx; // Do here since we know viewport (Bounding box case handled during rendering) // Note: This only works for root viewport since this routine is not called after // setting a new viewport. A true fix requires a strategy like SPItemView or SPMarkerView. - if(this->filterUnits == SP_FILTER_UNITS_USERSPACEONUSE) { + if (this->filterUnits == SP_FILTER_UNITS_USERSPACEONUSE) { this->calcDimsFromParentViewport(ictx, true); } /* do something to trigger redisplay, updates? */ - } // Update filter primitives in order to update filter primitive area @@ -217,12 +221,12 @@ void SPFilter::update(SPCtx *ctx, guint flags) { unsigned childflags = flags; if (flags & SP_OBJECT_MODIFIED_FLAG) { - childflags |= SP_OBJECT_PARENT_MODIFIED_FLAG; + childflags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } childflags &= SP_OBJECT_MODIFIED_CASCADE; - std::vector l(this->childList(true, SPObject::ActionUpdate)); - for(SPObject* child: l){ - if( SP_IS_FILTER_PRIMITIVE( child ) ) { + std::vector l(this->childList(true, SPObject::ActionUpdate)); + for (SPObject *child : l) { + if (SP_IS_FILTER_PRIMITIVE(child)) { child->updateDisplay(ctx, childflags); } sp_object_unref(child); @@ -234,7 +238,8 @@ void SPFilter::update(SPCtx *ctx, guint flags) { /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node* SPFilter::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFilter::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ // Original from sp-item-group.cpp if (flags & SP_OBJECT_WRITE_BUILD) { if (!repr) { @@ -242,7 +247,7 @@ Inkscape::XML::Node* SPFilter::write(Inkscape::XML::Document *doc, Inkscape::XML } std::vector l; - for (auto& child: children) { + for (auto &child : children) { Inkscape::XML::Node *crepr = child.updateRepr(doc, nullptr, flags); if (crepr) { @@ -250,12 +255,12 @@ Inkscape::XML::Node* SPFilter::write(Inkscape::XML::Document *doc, Inkscape::XML } } - for (auto i=l.rbegin();i!=l.rend();++i) { - repr->addChild(*i, nullptr); + for (auto i = l.rbegin(); i != l.rend(); ++i) { + repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { + for (auto &child : children) { child.updateRepr(flags); } } @@ -306,7 +311,7 @@ Inkscape::XML::Node* SPFilter::write(Inkscape::XML::Document *doc, Inkscape::XML repr->removeAttribute("height"); } - if (this->filterRes.getNumber()>=0) { + if (this->filterRes.getNumber() >= 0) { gchar *tmp = this->filterRes.getValueString(); repr->setAttribute("filterRes", tmp); g_free(tmp); @@ -324,28 +329,23 @@ Inkscape::XML::Node* SPFilter::write(Inkscape::XML::Document *doc, Inkscape::XML return repr; } - /** * Gets called when the filter is (re)attached to another filter. */ -static void -filter_ref_changed(SPObject *old_ref, SPObject *ref, SPFilter *filter) +static void filter_ref_changed(SPObject *old_ref, SPObject *ref, SPFilter *filter) { if (old_ref) { filter->modified_connection.disconnect(); } - if ( SP_IS_FILTER(ref) - && ref != filter ) - { - filter->modified_connection = - ref->connectModified(sigc::bind(sigc::ptr_fun(&filter_ref_modified), filter)); + if (SP_IS_FILTER(ref) && ref != filter) { + filter->modified_connection = ref->connectModified(sigc::bind(sigc::ptr_fun(&filter_ref_modified), filter)); } filter_ref_modified(ref, 0, filter); } -static void filter_ref_modified(SPObject */*href*/, guint /*flags*/, SPFilter *filter) +static void filter_ref_modified(SPObject * /*href*/, guint /*flags*/, SPFilter *filter) { filter->requestModified(SP_OBJECT_MODIFIED_FLAG); } @@ -353,8 +353,9 @@ static void filter_ref_modified(SPObject */*href*/, guint /*flags*/, SPFilter *f /** * Callback for child_added event. */ -void SPFilter::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { - SPObject::child_added(child, ref); +void SPFilter::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ + SPObject::child_added(child, ref); this->requestModified(SP_OBJECT_MODIFIED_FLAG); } @@ -362,10 +363,11 @@ void SPFilter::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) /** * Callback for remove_child event. */ -void SPFilter::remove_child(Inkscape::XML::Node *child) { - SPObject::remove_child(child); +void SPFilter::remove_child(Inkscape::XML::Node *child) +{ + SPObject::remove_child(child); - this->requestModified(SP_OBJECT_MODIFIED_FLAG); + this->requestModified(SP_OBJECT_MODIFIED_FLAG); } void SPFilter::build_renderer(Inkscape::Filters::Filter *nr_filter) @@ -383,33 +385,34 @@ void SPFilter::build_renderer(Inkscape::Filters::Filter *nr_filter) if (this->filterRes.getNumber() >= 0) { if (this->filterRes.getOptNumber() >= 0) { - nr_filter->set_resolution(this->filterRes.getNumber(), - this->filterRes.getOptNumber()); + nr_filter->set_resolution(this->filterRes.getNumber(), this->filterRes.getOptNumber()); } else { nr_filter->set_resolution(this->filterRes.getNumber()); } } nr_filter->clear_primitives(); - for(auto& primitive_obj: this->children) { + for (auto &primitive_obj : this->children) { if (SP_IS_FILTER_PRIMITIVE(&primitive_obj)) { SPFilterPrimitive *primitive = SP_FILTER_PRIMITIVE(&primitive_obj); g_assert(primitive != nullptr); -// if (((SPFilterPrimitiveClass*) G_OBJECT_GET_CLASS(primitive))->build_renderer) { -// ((SPFilterPrimitiveClass *) G_OBJECT_GET_CLASS(primitive))->build_renderer(primitive, nr_filter); -// } else { -// g_warning("Cannot build filter renderer: missing builder"); -// } // CPPIFY: => FilterPrimitive should be abstract. + // if (((SPFilterPrimitiveClass*) G_OBJECT_GET_CLASS(primitive))->build_renderer) { + // ((SPFilterPrimitiveClass *) G_OBJECT_GET_CLASS(primitive))->build_renderer(primitive, + // nr_filter); + // } else { + // g_warning("Cannot build filter renderer: missing builder"); + // } // CPPIFY: => FilterPrimitive should be abstract. primitive->build_renderer(nr_filter); } } } -int SPFilter::primitive_count() const { +int SPFilter::primitive_count() const +{ int count = 0; - for(const auto& primitive_obj: this->children) { + for (const auto &primitive_obj : this->children) { if (SP_IS_FILTER_PRIMITIVE(&primitive_obj)) { count++; } @@ -418,20 +421,24 @@ int SPFilter::primitive_count() const { return count; } -int SPFilter::get_image_name(gchar const *name) const { - std::map::iterator result = this->_image_name->find(const_cast(name)); - if (result == this->_image_name->end()) return -1; - else return (*result).second; +int SPFilter::get_image_name(gchar const *name) const +{ + std::map::iterator result = this->_image_name->find(const_cast(name)); + if (result == this->_image_name->end()) + return -1; + else + return (*result).second; } -int SPFilter::set_image_name(gchar const *name) { +int SPFilter::set_image_name(gchar const *name) +{ int value = this->_image_number_next; this->_image_number_next++; gchar *name_copy = strdup(name); - std::pair new_pair(name_copy, value); - const std::pair::iterator,bool> ret = this->_image_name->insert(new_pair); + std::pair new_pair(name_copy, value); + const std::pair::iterator, bool> ret = this->_image_name->insert(new_pair); if (ret.second == false) { - // The element is not inserted (because an element with the same key was already in the map) + // The element is not inserted (because an element with the same key was already in the map) // Therefore, free the memory allocated for the new entry: free(name_copy); @@ -440,7 +447,8 @@ int SPFilter::set_image_name(gchar const *name) { return value; } -gchar const *SPFilter::name_for_image(int const image) const { +gchar const *SPFilter::name_for_image(int const image) const +{ switch (image) { case Inkscape::Filters::NR_FILTER_SOURCEGRAPHIC: return "SourceGraphic"; @@ -465,9 +473,8 @@ gchar const *SPFilter::name_for_image(int const image) const { return nullptr; break; default: - for (std::map::const_iterator i - = this->_image_name->begin() ; - i != this->_image_name->end() ; ++i) { + for (std::map::const_iterator i = this->_image_name->begin(); + i != this->_image_name->end(); ++i) { if (i->second == image) { return i->first; } @@ -476,20 +483,18 @@ gchar const *SPFilter::name_for_image(int const image) const { return nullptr; } -Glib::ustring SPFilter::get_new_result_name() const { +Glib::ustring SPFilter::get_new_result_name() const +{ int largest = 0; - for(const auto& primitive_obj: this->children) { + for (const auto &primitive_obj : this->children) { if (SP_IS_FILTER_PRIMITIVE(&primitive_obj)) { const Inkscape::XML::Node *repr = primitive_obj.getRepr(); char const *result = repr->attribute("result"); int index; - if (result) - { - if (sscanf(result, "result%5d", &index) == 1) - { - if (index > largest) - { + if (result) { + if (sscanf(result, "result%5d", &index) == 1) { + if (index > largest) { largest = index; } } @@ -500,12 +505,11 @@ Glib::ustring SPFilter::get_new_result_name() const { return "result" + Glib::Ascii::dtostr(largest + 1); } -bool ltstr::operator()(const char* s1, const char* s2) const +bool ltstr::operator()(const char *s1, const char *s2) const { return strcmp(s1, s2) < 0; } - /* Local Variables: mode:c++ diff --git a/src/object/sp-filter.h b/src/object/sp-filter.h index 08129d1ce31cf1558c05586b5db6c551e451a8f8..261bb2a40188696bd19f045b93e44ef7e34797eb 100644 --- a/src/object/sp-filter.h +++ b/src/object/sp-filter.h @@ -18,12 +18,12 @@ #include "number-opt-number.h" #include "sp-dimensions.h" -#include "sp-object.h" #include "sp-filter-units.h" +#include "sp-object.h" #include "svg/svg-length.h" -#define SP_FILTER(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FILTER(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FILTER(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FILTER(obj) (dynamic_cast((SPObject *)obj) != NULL) #define SP_FILTER_FILTER_UNITS(f) (SP_FILTER(f)->filterUnits) #define SP_FILTER_PRIMITIVE_UNITS(f) (SP_FILTER(f)->primitiveUnits) @@ -31,16 +31,21 @@ namespace Inkscape { namespace Filters { class Filter; -} } +} +} // namespace Inkscape class SPFilterReference; class SPFilterPrimitive; -struct ltstr { - bool operator()(const char* s1, const char* s2) const; +struct ltstr +{ + bool operator()(const char *s1, const char *s2) const; }; -class SPFilter : public SPObject, public SPDimensions { +class SPFilter + : public SPObject + , public SPDimensions +{ public: SPFilter(); ~SPFilter() override; @@ -78,21 +83,21 @@ public: Inkscape::Filters::Filter *_renderer; - std::map* _image_name; + std::map *_image_name; int _image_number_next; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; void release() override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; - void set(SPAttr key, const char* value) override; + void set(SPAttr key, const char *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif /* !SP_FILTER_H_SEEN */ diff --git a/src/object/sp-flowdiv.cpp b/src/object/sp-flowdiv.cpp index 68729632a2f6ea70b5a7a32e31c621a9f9809ec1..973c08d034b3a9a5fbcda1983a6e7f081a78298b 100644 --- a/src/object/sp-flowdiv.cpp +++ b/src/object/sp-flowdiv.cpp @@ -10,21 +10,25 @@ /* */ -#include "xml/repr.h" #include "sp-flowdiv.h" -#include "sp-string.h" + #include "document.h" +#include "sp-string.h" +#include "xml/repr.h" -SPFlowdiv::SPFlowdiv() : SPItem() { -} +SPFlowdiv::SPFlowdiv() + : SPItem() +{} SPFlowdiv::~SPFlowdiv() = default; -void SPFlowdiv::release() { - SPItem::release(); +void SPFlowdiv::release() +{ + SPItem::release(); } -void SPFlowdiv::update(SPCtx *ctx, unsigned int flags) { +void SPFlowdiv::update(SPCtx *ctx, unsigned int flags) +{ SPItemCtx *ictx = reinterpret_cast(ctx); SPItemCtx cctx = *ictx; @@ -35,12 +39,12 @@ void SPFlowdiv::update(SPCtx *ctx, unsigned int flags) { childflags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for(auto child:l) { + for (auto child : l) { if (childflags || (child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { if (SP_IS_ITEM(child)) { SPItem const &chi = *SP_ITEM(child); @@ -58,7 +62,8 @@ void SPFlowdiv::update(SPCtx *ctx, unsigned int flags) { SPItem::update(ctx, flags); } -void SPFlowdiv::modified(unsigned int flags) { +void SPFlowdiv::modified(unsigned int flags) +{ SPItem::modified(flags); if (flags & SP_OBJECT_MODIFIED_FLAG) { @@ -68,12 +73,12 @@ void SPFlowdiv::modified(unsigned int flags) { flags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for(auto child:l) { + for (auto child : l) { if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->emitModified(flags); } @@ -81,52 +86,53 @@ void SPFlowdiv::modified(unsigned int flags) { } } +void SPFlowdiv::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ + this->_requireSVGVersion(Inkscape::Version(1, 2)); -void SPFlowdiv::build(SPDocument *doc, Inkscape::XML::Node *repr) { - this->_requireSVGVersion(Inkscape::Version(1, 2)); - - SPItem::build(doc, repr); + SPItem::build(doc, repr); } -void SPFlowdiv::set(SPAttr key, const gchar* value) { - SPItem::set(key, value); +void SPFlowdiv::set(SPAttr key, const gchar *value) +{ + SPItem::set(key, value); } - -Inkscape::XML::Node* SPFlowdiv::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - if ( flags & SP_OBJECT_WRITE_BUILD ) { - if ( repr == nullptr ) { +Inkscape::XML::Node *SPFlowdiv::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + if (flags & SP_OBJECT_WRITE_BUILD) { + if (repr == nullptr) { repr = xml_doc->createElement("svg:flowDiv"); } std::vector l; - for (auto& child: children) { - Inkscape::XML::Node* c_repr = nullptr; + for (auto &child : children) { + Inkscape::XML::Node *c_repr = nullptr; - if ( SP_IS_FLOWTSPAN (&child) ) { + if (SP_IS_FLOWTSPAN(&child)) { c_repr = child.updateRepr(xml_doc, nullptr, flags); - } else if ( SP_IS_FLOWPARA(&child) ) { + } else if (SP_IS_FLOWPARA(&child)) { c_repr = child.updateRepr(xml_doc, nullptr, flags); - } else if ( SP_IS_STRING(&child) ) { + } else if (SP_IS_STRING(&child)) { c_repr = xml_doc->createTextNode(SP_STRING(&child)->string.c_str()); } - if ( c_repr ) { + if (c_repr) { l.push_back(c_repr); } } - for (auto i=l.rbegin();i!=l.rend();++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { - if ( SP_IS_FLOWTSPAN (&child) ) { + for (auto &child : children) { + if (SP_IS_FLOWTSPAN(&child)) { child.updateRepr(flags); - } else if ( SP_IS_FLOWPARA(&child) ) { + } else if (SP_IS_FLOWPARA(&child)) { child.updateRepr(flags); - } else if ( SP_IS_STRING(&child) ) { + } else if (SP_IS_STRING(&child)) { child.getRepr()->setContent(SP_STRING(&child)->string.c_str()); } } @@ -137,21 +143,23 @@ Inkscape::XML::Node* SPFlowdiv::write(Inkscape::XML::Document *xml_doc, Inkscape return repr; } - /* * */ -SPFlowtspan::SPFlowtspan() : SPItem() { -} +SPFlowtspan::SPFlowtspan() + : SPItem() +{} SPFlowtspan::~SPFlowtspan() = default; -void SPFlowtspan::release() { - SPItem::release(); +void SPFlowtspan::release() +{ + SPItem::release(); } -void SPFlowtspan::update(SPCtx *ctx, unsigned int flags) { +void SPFlowtspan::update(SPCtx *ctx, unsigned int flags) +{ SPItemCtx *ictx = reinterpret_cast(ctx); SPItemCtx cctx = *ictx; @@ -161,12 +169,12 @@ void SPFlowtspan::update(SPCtx *ctx, unsigned int flags) { } childflags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for(auto child:l) { + for (auto child : l) { if (childflags || (child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { if (SP_IS_ITEM(child)) { SPItem const &chi = *SP_ITEM(child); @@ -184,7 +192,8 @@ void SPFlowtspan::update(SPCtx *ctx, unsigned int flags) { SPItem::update(ctx, flags); } -void SPFlowtspan::modified(unsigned int flags) { +void SPFlowtspan::modified(unsigned int flags) +{ SPItem::modified(flags); if (flags & SP_OBJECT_MODIFIED_FLAG) { @@ -193,12 +202,12 @@ void SPFlowtspan::modified(unsigned int flags) { flags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for(auto child:l) { + for (auto child : l) { if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->emitModified(flags); } @@ -206,49 +215,51 @@ void SPFlowtspan::modified(unsigned int flags) { } } - -void SPFlowtspan::build(SPDocument *doc, Inkscape::XML::Node *repr) { - SPItem::build(doc, repr); +void SPFlowtspan::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ + SPItem::build(doc, repr); } -void SPFlowtspan::set(SPAttr key, const gchar* value) { - SPItem::set(key, value); +void SPFlowtspan::set(SPAttr key, const gchar *value) +{ + SPItem::set(key, value); } -Inkscape::XML::Node *SPFlowtspan::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - if ( flags&SP_OBJECT_WRITE_BUILD ) { - if ( repr == nullptr ) { +Inkscape::XML::Node *SPFlowtspan::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + if (flags & SP_OBJECT_WRITE_BUILD) { + if (repr == nullptr) { repr = xml_doc->createElement("svg:flowSpan"); } std::vector l; - for (auto& child: children) { - Inkscape::XML::Node* c_repr = nullptr; + for (auto &child : children) { + Inkscape::XML::Node *c_repr = nullptr; - if ( SP_IS_FLOWTSPAN(&child) ) { + if (SP_IS_FLOWTSPAN(&child)) { c_repr = child.updateRepr(xml_doc, nullptr, flags); - } else if ( SP_IS_FLOWPARA(&child) ) { + } else if (SP_IS_FLOWPARA(&child)) { c_repr = child.updateRepr(xml_doc, nullptr, flags); - } else if ( SP_IS_STRING(&child) ) { + } else if (SP_IS_STRING(&child)) { c_repr = xml_doc->createTextNode(SP_STRING(&child)->string.c_str()); } - if ( c_repr ) { + if (c_repr) { l.push_back(c_repr); } } - for (auto i=l.rbegin();i!=l.rend();++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { - if ( SP_IS_FLOWTSPAN(&child) ) { + for (auto &child : children) { + if (SP_IS_FLOWTSPAN(&child)) { child.updateRepr(flags); - } else if ( SP_IS_FLOWPARA(&child) ) { + } else if (SP_IS_FLOWPARA(&child)) { child.updateRepr(flags); - } else if ( SP_IS_STRING(&child) ) { + } else if (SP_IS_STRING(&child)) { child.getRepr()->setContent(SP_STRING(&child)->string.c_str()); } } @@ -259,20 +270,22 @@ Inkscape::XML::Node *SPFlowtspan::write(Inkscape::XML::Document *xml_doc, Inksca return repr; } - /* * */ -SPFlowpara::SPFlowpara() : SPItem() { -} +SPFlowpara::SPFlowpara() + : SPItem() +{} SPFlowpara::~SPFlowpara() = default; -void SPFlowpara::release() { - SPItem::release(); +void SPFlowpara::release() +{ + SPItem::release(); } -void SPFlowpara::update(SPCtx *ctx, unsigned int flags) { +void SPFlowpara::update(SPCtx *ctx, unsigned int flags) +{ SPItemCtx *ictx = reinterpret_cast(ctx); SPItemCtx cctx = *ictx; @@ -285,12 +298,12 @@ void SPFlowpara::update(SPCtx *ctx, unsigned int flags) { flags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for(auto child:l) { + for (auto child : l) { if (flags || (child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { if (SP_IS_ITEM(child)) { SPItem const &chi = *SP_ITEM(child); @@ -305,7 +318,8 @@ void SPFlowpara::update(SPCtx *ctx, unsigned int flags) { } } -void SPFlowpara::modified(unsigned int flags) { +void SPFlowpara::modified(unsigned int flags) +{ SPItem::modified(flags); if (flags & SP_OBJECT_MODIFIED_FLAG) { @@ -315,12 +329,12 @@ void SPFlowpara::modified(unsigned int flags) { flags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for(auto child:l) { + for (auto child : l) { if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->emitModified(flags); } @@ -328,50 +342,52 @@ void SPFlowpara::modified(unsigned int flags) { } } - -void SPFlowpara::build(SPDocument *doc, Inkscape::XML::Node *repr) { - SPItem::build(doc, repr); +void SPFlowpara::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ + SPItem::build(doc, repr); } -void SPFlowpara::set(SPAttr key, const gchar* value) { - SPItem::set(key, value); +void SPFlowpara::set(SPAttr key, const gchar *value) +{ + SPItem::set(key, value); } -Inkscape::XML::Node *SPFlowpara::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - if ( flags&SP_OBJECT_WRITE_BUILD ) { - if ( repr == nullptr ) { - repr = xml_doc->createElement("svg:flowPara"); +Inkscape::XML::Node *SPFlowpara::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + if (flags & SP_OBJECT_WRITE_BUILD) { + if (repr == nullptr) { + repr = xml_doc->createElement("svg:flowPara"); } std::vector l; - for (auto& child: children) { - Inkscape::XML::Node* c_repr = nullptr; + for (auto &child : children) { + Inkscape::XML::Node *c_repr = nullptr; - if ( SP_IS_FLOWTSPAN(&child) ) { + if (SP_IS_FLOWTSPAN(&child)) { c_repr = child.updateRepr(xml_doc, nullptr, flags); - } else if ( SP_IS_FLOWPARA(&child) ) { + } else if (SP_IS_FLOWPARA(&child)) { c_repr = child.updateRepr(xml_doc, nullptr, flags); - } else if ( SP_IS_STRING(&child) ) { + } else if (SP_IS_STRING(&child)) { c_repr = xml_doc->createTextNode(SP_STRING(&child)->string.c_str()); } - if ( c_repr ) { + if (c_repr) { l.push_back(c_repr); } } - for (auto i=l.rbegin();i!=l.rend();++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { - if ( SP_IS_FLOWTSPAN(&child) ) { + for (auto &child : children) { + if (SP_IS_FLOWTSPAN(&child)) { child.updateRepr(flags); - } else if ( SP_IS_FLOWPARA(&child) ) { + } else if (SP_IS_FLOWPARA(&child)) { child.updateRepr(flags); - } else if ( SP_IS_STRING(&child) ) { + } else if (SP_IS_STRING(&child)) { child.getRepr()->setContent(SP_STRING(&child)->string.c_str()); } } @@ -382,33 +398,36 @@ Inkscape::XML::Node *SPFlowpara::write(Inkscape::XML::Document *xml_doc, Inkscap return repr; } - /* * */ -SPFlowline::SPFlowline() : SPObject() { -} +SPFlowline::SPFlowline() + : SPObject() +{} SPFlowline::~SPFlowline() = default; -void SPFlowline::release() { - SPObject::release(); +void SPFlowline::release() +{ + SPObject::release(); } -void SPFlowline::modified(unsigned int flags) { - SPObject::modified(flags); +void SPFlowline::modified(unsigned int flags) +{ + SPObject::modified(flags); - if (flags & SP_OBJECT_MODIFIED_FLAG) { - flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; - } + if (flags & SP_OBJECT_MODIFIED_FLAG) { + flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; + } - flags &= SP_OBJECT_MODIFIED_CASCADE; + flags &= SP_OBJECT_MODIFIED_CASCADE; } -Inkscape::XML::Node *SPFlowline::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - if ( flags & SP_OBJECT_WRITE_BUILD ) { - if ( repr == nullptr ) { +Inkscape::XML::Node *SPFlowline::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + if (flags & SP_OBJECT_WRITE_BUILD) { + if (repr == nullptr) { repr = xml_doc->createElement("svg:flowLine"); } } @@ -418,33 +437,36 @@ Inkscape::XML::Node *SPFlowline::write(Inkscape::XML::Document *xml_doc, Inkscap return repr; } - /* * */ -SPFlowregionbreak::SPFlowregionbreak() : SPObject() { -} +SPFlowregionbreak::SPFlowregionbreak() + : SPObject() +{} SPFlowregionbreak::~SPFlowregionbreak() = default; -void SPFlowregionbreak::release() { - SPObject::release(); +void SPFlowregionbreak::release() +{ + SPObject::release(); } -void SPFlowregionbreak::modified(unsigned int flags) { - SPObject::modified(flags); +void SPFlowregionbreak::modified(unsigned int flags) +{ + SPObject::modified(flags); - if (flags & SP_OBJECT_MODIFIED_FLAG) { - flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; - } + if (flags & SP_OBJECT_MODIFIED_FLAG) { + flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; + } - flags &= SP_OBJECT_MODIFIED_CASCADE; + flags &= SP_OBJECT_MODIFIED_CASCADE; } -Inkscape::XML::Node *SPFlowregionbreak::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - if ( flags & SP_OBJECT_WRITE_BUILD ) { - if ( repr == nullptr ) { +Inkscape::XML::Node *SPFlowregionbreak::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + if (flags & SP_OBJECT_WRITE_BUILD) { + if (repr == nullptr) { repr = xml_doc->createElement("svg:flowLine"); } } @@ -454,7 +476,6 @@ Inkscape::XML::Node *SPFlowregionbreak::write(Inkscape::XML::Document *xml_doc, return repr; } - /* Local Variables: mode:c++ diff --git a/src/object/sp-flowdiv.h b/src/object/sp-flowdiv.h index a54cb33895406ab85db806a7a6cae2e7de00da21..b9a0b02c388fc973ea2b87efb45bd345bd07bbd1 100644 --- a/src/object/sp-flowdiv.h +++ b/src/object/sp-flowdiv.h @@ -13,93 +13,103 @@ /* */ -#include "sp-object.h" #include "sp-item.h" +#include "sp-object.h" -#define SP_FLOWDIV(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FLOWDIV(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FLOWDIV(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FLOWDIV(obj) (dynamic_cast((SPObject *)obj) != NULL) -#define SP_FLOWTSPAN(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FLOWTSPAN(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FLOWTSPAN(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FLOWTSPAN(obj) (dynamic_cast((SPObject *)obj) != NULL) -#define SP_FLOWPARA(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FLOWPARA(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FLOWPARA(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FLOWPARA(obj) (dynamic_cast((SPObject *)obj) != NULL) -#define SP_FLOWLINE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FLOWLINE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FLOWLINE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FLOWLINE(obj) (dynamic_cast((SPObject *)obj) != NULL) -#define SP_FLOWREGIONBREAK(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FLOWREGIONBREAK(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FLOWREGIONBREAK(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FLOWREGIONBREAK(obj) (dynamic_cast((SPObject *)obj) != NULL) // these 3 are derivatives of SPItem to get the automatic style handling -class SPFlowdiv : public SPItem { +class SPFlowdiv : public SPItem +{ public: - SPFlowdiv(); - ~SPFlowdiv() override; + SPFlowdiv(); + ~SPFlowdiv() override; protected: - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; - - void set(SPAttr key, char const* value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void release() override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; + + void set(SPAttr key, char const *value) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; -class SPFlowtspan : public SPItem { +class SPFlowtspan : public SPItem +{ public: - SPFlowtspan(); - ~SPFlowtspan() override; + SPFlowtspan(); + ~SPFlowtspan() override; protected: - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; - - void set(SPAttr key, char const* value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void release() override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; + + void set(SPAttr key, char const *value) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; -class SPFlowpara : public SPItem { +class SPFlowpara : public SPItem +{ public: - SPFlowpara(); - ~SPFlowpara() override; + SPFlowpara(); + ~SPFlowpara() override; protected: - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; - - void set(SPAttr key, char const* value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void release() override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; + + void set(SPAttr key, char const *value) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; // these do not need any style -class SPFlowline : public SPObject { +class SPFlowline : public SPObject +{ public: - SPFlowline(); - ~SPFlowline() override; + SPFlowline(); + ~SPFlowline() override; protected: - void release() override; - void modified(unsigned int flags) override; + void release() override; + void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; -class SPFlowregionbreak : public SPObject { +class SPFlowregionbreak : public SPObject +{ public: - SPFlowregionbreak(); - ~SPFlowregionbreak() override; + SPFlowregionbreak(); + ~SPFlowregionbreak() override; protected: - void release() override; - void modified(unsigned int flags) override; + void release() override; + void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; #endif diff --git a/src/object/sp-flowregion.cpp b/src/object/sp-flowregion.cpp index fd6dcf69015a252744ddfe518e53085ac9b32047..66c272571db72d5d824c617a06e773b417566cc7 100644 --- a/src/object/sp-flowregion.cpp +++ b/src/object/sp-flowregion.cpp @@ -10,52 +10,53 @@ /* */ -#include +#include "sp-flowregion.h" +#include #include + #include "display/curve.h" +#include "document.h" +#include "livarot/Path.h" +#include "livarot/Shape.h" +#include "sp-desc.h" #include "sp-shape.h" #include "sp-text.h" +#include "sp-title.h" #include "sp-use.h" #include "style.h" -#include "document.h" -#include "sp-title.h" -#include "sp-desc.h" -#include "sp-flowregion.h" - -#include "livarot/Path.h" -#include "livarot/Shape.h" - - -static void GetDest(SPObject* child,Shape **computed); +static void GetDest(SPObject *child, Shape **computed); +SPFlowregion::SPFlowregion() + : SPItem() +{} -SPFlowregion::SPFlowregion() : SPItem() { -} - -SPFlowregion::~SPFlowregion() { - for (auto & it : this->computed) { +SPFlowregion::~SPFlowregion() +{ + for (auto &it : this->computed) { delete it; - } + } } -void SPFlowregion::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { - SPItem::child_added(child, ref); +void SPFlowregion::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ + SPItem::child_added(child, ref); - this->requestModified(SP_OBJECT_MODIFIED_FLAG); + this->requestModified(SP_OBJECT_MODIFIED_FLAG); } /* fixme: hide (Lauris) */ -void SPFlowregion::remove_child(Inkscape::XML::Node * child) { - SPItem::remove_child(child); +void SPFlowregion::remove_child(Inkscape::XML::Node *child) +{ + SPItem::remove_child(child); - this->requestModified(SP_OBJECT_MODIFIED_FLAG); + this->requestModified(SP_OBJECT_MODIFIED_FLAG); } - -void SPFlowregion::update(SPCtx *ctx, unsigned int flags) { +void SPFlowregion::update(SPCtx *ctx, unsigned int flags) +{ SPItemCtx *ictx = reinterpret_cast(ctx); SPItemCtx cctx = *ictx; @@ -65,14 +66,14 @@ void SPFlowregion::update(SPCtx *ctx, unsigned int flags) { } childflags &= SP_OBJECT_MODIFIED_CASCADE; - std::vectorl; + std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for (auto child:l) { + for (auto child : l) { g_assert(child != nullptr); SPItem *item = dynamic_cast(child); @@ -97,33 +98,34 @@ void SPFlowregion::update(SPCtx *ctx, unsigned int flags) { void SPFlowregion::UpdateComputed() { - for (auto & it : computed) { + for (auto &it : computed) { delete it; } computed.clear(); - for (auto& child: children) { + for (auto &child : children) { Shape *shape = nullptr; GetDest(&child, &shape); computed.push_back(shape); } } -void SPFlowregion::modified(guint flags) { +void SPFlowregion::modified(guint flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } flags &= SP_OBJECT_MODIFIED_CASCADE; - std::vectorl; + std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for (auto child:l) { + for (auto child : l) { g_assert(child != nullptr); if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { @@ -134,15 +136,16 @@ void SPFlowregion::modified(guint flags) { } } -Inkscape::XML::Node *SPFlowregion::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFlowregion::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if (flags & SP_OBJECT_WRITE_BUILD) { - if ( repr == nullptr ) { + if (repr == nullptr) { repr = xml_doc->createElement("svg:flowRegion"); } std::vector l; - for (auto& child: children) { - if ( !dynamic_cast(&child) && !dynamic_cast(&child) ) { + for (auto &child : children) { + if (!dynamic_cast(&child) && !dynamic_cast(&child)) { Inkscape::XML::Node *crepr = child.updateRepr(xml_doc, nullptr, flags); if (crepr) { @@ -156,8 +159,8 @@ Inkscape::XML::Node *SPFlowregion::write(Inkscape::XML::Document *xml_doc, Inksc Inkscape::GC::release(*i); } - for (auto& child: children) { - if ( !dynamic_cast(&child) && !dynamic_cast(&child) ) { + for (auto &child : children) { + if (!dynamic_cast(&child) && !dynamic_cast(&child)) { child.updateRepr(flags); } } @@ -165,43 +168,49 @@ Inkscape::XML::Node *SPFlowregion::write(Inkscape::XML::Document *xml_doc, Inksc SPItem::write(xml_doc, repr, flags); - this->UpdateComputed(); // copied from update(), see LP Bug 1339305 + this->UpdateComputed(); // copied from update(), see LP Bug 1339305 return repr; } -const char* SPFlowregion::displayName() const { - // TRANSLATORS: "Flow region" is an area where text is allowed to flow - return _("Flow Region"); +const char *SPFlowregion::displayName() const +{ + // TRANSLATORS: "Flow region" is an area where text is allowed to flow + return _("Flow Region"); } -SPFlowregionExclude::SPFlowregionExclude() : SPItem() { - this->computed = nullptr; +SPFlowregionExclude::SPFlowregionExclude() + : SPItem() +{ + this->computed = nullptr; } -SPFlowregionExclude::~SPFlowregionExclude() { +SPFlowregionExclude::~SPFlowregionExclude() +{ if (this->computed) { delete this->computed; this->computed = nullptr; } } -void SPFlowregionExclude::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { - SPItem::child_added(child, ref); +void SPFlowregionExclude::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ + SPItem::child_added(child, ref); - this->requestModified(SP_OBJECT_MODIFIED_FLAG); + this->requestModified(SP_OBJECT_MODIFIED_FLAG); } /* fixme: hide (Lauris) */ -void SPFlowregionExclude::remove_child(Inkscape::XML::Node * child) { - SPItem::remove_child(child); +void SPFlowregionExclude::remove_child(Inkscape::XML::Node *child) +{ + SPItem::remove_child(child); - this->requestModified(SP_OBJECT_MODIFIED_FLAG); + this->requestModified(SP_OBJECT_MODIFIED_FLAG); } - -void SPFlowregionExclude::update(SPCtx *ctx, unsigned int flags) { +void SPFlowregionExclude::update(SPCtx *ctx, unsigned int flags) +{ SPItemCtx *ictx = reinterpret_cast(ctx); SPItemCtx cctx = *ictx; @@ -215,12 +224,12 @@ void SPFlowregionExclude::update(SPCtx *ctx, unsigned int flags) { std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for(auto child:l) { + for (auto child : l) { g_assert(child != nullptr); if (flags || (child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { @@ -241,7 +250,6 @@ void SPFlowregionExclude::update(SPCtx *ctx, unsigned int flags) { this->UpdateComputed(); } - void SPFlowregionExclude::UpdateComputed() { if (computed) { @@ -249,26 +257,27 @@ void SPFlowregionExclude::UpdateComputed() computed = nullptr; } - for (auto& child: children) { + for (auto &child : children) { GetDest(&child, &computed); } } -void SPFlowregionExclude::modified(guint flags) { +void SPFlowregionExclude::modified(guint flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } flags &= SP_OBJECT_MODIFIED_CASCADE; - std::vector l; + std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for (auto child:l) { + for (auto child : l) { g_assert(child != nullptr); if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { @@ -279,15 +288,17 @@ void SPFlowregionExclude::modified(guint flags) { } } -Inkscape::XML::Node *SPFlowregionExclude::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFlowregionExclude::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + guint flags) +{ if (flags & SP_OBJECT_WRITE_BUILD) { - if ( repr == nullptr ) { + if (repr == nullptr) { repr = xml_doc->createElement("svg:flowRegionExclude"); } std::vector l; - for (auto& child: children) { + for (auto &child : children) { Inkscape::XML::Node *crepr = child.updateRepr(xml_doc, nullptr, flags); if (crepr) { @@ -295,13 +306,13 @@ Inkscape::XML::Node *SPFlowregionExclude::write(Inkscape::XML::Document *xml_doc } } - for (auto i = l.rbegin(); i != l.rend(); ++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { + for (auto &child : children) { child.updateRepr(flags); } } @@ -311,12 +322,13 @@ Inkscape::XML::Node *SPFlowregionExclude::write(Inkscape::XML::Document *xml_doc return repr; } -const char* SPFlowregionExclude::displayName() const { - /* TRANSLATORS: A region "cut out of" a flow region; text is not allowed to flow inside the - * flow excluded region. flowRegionExclude in SVG 1.2: see - * http://www.w3.org/TR/2004/WD-SVG12-20041027/flow.html#flowRegion-elem and - * http://www.w3.org/TR/2004/WD-SVG12-20041027/flow.html#flowRegionExclude-elem. */ - return _("Flow Excluded Region"); +const char *SPFlowregionExclude::displayName() const +{ + /* TRANSLATORS: A region "cut out of" a flow region; text is not allowed to flow inside the + * flow excluded region. flowRegionExclude in SVG 1.2: see + * http://www.w3.org/TR/2004/WD-SVG12-20041027/flow.html#flowRegion-elem and + * http://www.w3.org/TR/2004/WD-SVG12-20041027/flow.html#flowRegionExclude-elem. */ + return _("Flow Excluded Region"); } static void UnionShape(Shape *&base_shape, Shape const *add_shape) @@ -334,7 +346,7 @@ static void UnionShape(Shape *&base_shape, Shape const *add_shape) } } -static void GetDest(SPObject* child,Shape **computed) +static void GetDest(SPObject *child, Shape **computed) { auto item = dynamic_cast(child); if (item == nullptr) @@ -343,45 +355,45 @@ static void GetDest(SPObject* child,Shape **computed) std::unique_ptr curve; Geom::Affine tr_mat; - SPObject* u_child = child; + SPObject *u_child = child; SPUse *use = dynamic_cast(item); - if ( use ) { + if (use) { u_child = use->child; tr_mat = use->getRelativeTransform(child->parent); } else { tr_mat = item->transform; } SPShape *shape = dynamic_cast(u_child); - if ( shape ) { + if (shape) { if (!shape->curve()) { shape->set_shape(); } curve = SPCurve::copy(shape->curve()); } else { SPText *text = dynamic_cast(u_child); - if ( text ) { + if (text) { curve = text->getNormalizedBpath(); } } - if ( curve ) { - Path* temp=new Path; + if (curve) { + Path *temp = new Path; temp->LoadPathVector(curve->get_pathvector(), tr_mat, true); - Shape* n_shp=new Shape; - temp->Convert(0.25); - temp->Fill(n_shp,0); - Shape* uncross=new Shape; - SPStyle* style = u_child->style; - if ( style && style->fill_rule.computed == SP_WIND_RULE_EVENODD ) { - uncross->ConvertToShape(n_shp,fill_oddEven); - } else { - uncross->ConvertToShape(n_shp,fill_nonZero); - } - UnionShape(*computed, uncross); - delete uncross; - delete n_shp; - delete temp; - } + Shape *n_shp = new Shape; + temp->Convert(0.25); + temp->Fill(n_shp, 0); + Shape *uncross = new Shape; + SPStyle *style = u_child->style; + if (style && style->fill_rule.computed == SP_WIND_RULE_EVENODD) { + uncross->ConvertToShape(n_shp, fill_oddEven); + } else { + uncross->ConvertToShape(n_shp, fill_nonZero); + } + UnionShape(*computed, uncross); + delete uncross; + delete n_shp; + delete temp; + } } /* diff --git a/src/object/sp-flowregion.h b/src/object/sp-flowregion.h index f6731b138eeaf72609b9b595a11f4d5ed8a106b1..0dbc5dea4a127fe8eddefd047bf761d7ec62f078 100644 --- a/src/object/sp-flowregion.h +++ b/src/object/sp-flowregion.h @@ -15,48 +15,52 @@ #include "sp-item.h" -#define SP_FLOWREGION(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FLOWREGION(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FLOWREGION(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FLOWREGION(obj) (dynamic_cast((SPObject *)obj) != NULL) -#define SP_FLOWREGIONEXCLUDE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FLOWREGIONEXCLUDE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FLOWREGIONEXCLUDE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FLOWREGIONEXCLUDE(obj) (dynamic_cast((SPObject *)obj) != NULL) class Path; class Shape; class flow_dest; -class SPFlowregion : public SPItem { +class SPFlowregion : public SPItem +{ public: - SPFlowregion(); - ~SPFlowregion() override; - - std::vector computed; - - void UpdateComputed(); - - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node *child) override; - void update(SPCtx *ctx, unsigned int flags) override; - void modified(guint flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - const char* displayName() const override; + SPFlowregion(); + ~SPFlowregion() override; + + std::vector computed; + + void UpdateComputed(); + + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + const char *displayName() const override; }; -class SPFlowregionExclude : public SPItem { +class SPFlowregionExclude : public SPItem +{ public: - SPFlowregionExclude(); - ~SPFlowregionExclude() override; - - Shape *computed; - - void UpdateComputed(); - - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node *child) override; - void update(SPCtx *ctx, unsigned int flags) override; - void modified(guint flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - const char* displayName() const override; + SPFlowregionExclude(); + ~SPFlowregionExclude() override; + + Shape *computed; + + void UpdateComputed(); + + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + const char *displayName() const override; }; #endif diff --git a/src/object/sp-flowtext.cpp b/src/object/sp-flowtext.cpp index 8349e0853bcc44b8acdd27b2abf1bf699237aae2..f8518460e0ee9228f0081c7dacf3670a1df99f5a 100644 --- a/src/object/sp-flowtext.cpp +++ b/src/object/sp-flowtext.cpp @@ -10,61 +10,58 @@ /* */ -#include +#include "sp-flowtext.h" + #include +#include #include #include "attributes.h" -#include "xml/repr.h" -#include "style.h" -#include "inkscape.h" -#include "document.h" - #include "desktop.h" - -#include "text-tag-attributes.h" -#include "text-editing.h" - +#include "display/curve.h" +#include "display/drawing-text.h" +#include "document.h" +#include "inkscape.h" +#include "libnrtype/font-instance.h" +#include "livarot/Shape.h" #include "sp-flowdiv.h" #include "sp-flowregion.h" -#include "sp-flowtext.h" #include "sp-rect.h" #include "sp-string.h" #include "sp-text.h" #include "sp-use.h" +#include "style.h" +#include "text-editing.h" +#include "text-tag-attributes.h" +#include "xml/repr.h" -#include "libnrtype/font-instance.h" - -#include "livarot/Shape.h" - -#include "display/curve.h" -#include "display/drawing-text.h" - -SPFlowtext::SPFlowtext() : SPItem(), - par_indent(0), - _optimizeScaledText(false) -{ -} +SPFlowtext::SPFlowtext() + : SPItem() + , par_indent(0) + , _optimizeScaledText(false) +{} SPFlowtext::~SPFlowtext() = default; -void SPFlowtext::child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) { - SPItem::child_added(child, ref); +void SPFlowtext::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ + SPItem::child_added(child, ref); - this->requestModified(SP_OBJECT_MODIFIED_FLAG); + this->requestModified(SP_OBJECT_MODIFIED_FLAG); } - /* fixme: hide (Lauris) */ -void SPFlowtext::remove_child(Inkscape::XML::Node* child) { - SPItem::remove_child(child); +void SPFlowtext::remove_child(Inkscape::XML::Node *child) +{ + SPItem::remove_child(child); - this->requestModified(SP_OBJECT_MODIFIED_FLAG); + this->requestModified(SP_OBJECT_MODIFIED_FLAG); } -void SPFlowtext::update(SPCtx* ctx, unsigned int flags) { - SPItemCtx *ictx = (SPItemCtx *) ctx; +void SPFlowtext::update(SPCtx *ctx, unsigned int flags) +{ + SPItemCtx *ictx = (SPItemCtx *)ctx; SPItemCtx cctx = *ictx; unsigned childflags = flags; @@ -74,12 +71,12 @@ void SPFlowtext::update(SPCtx* ctx, unsigned int flags) { childflags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for (auto child:l) { + for (auto child : l) { g_assert(child != nullptr); if (childflags || (child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { @@ -112,20 +109,21 @@ void SPFlowtext::update(SPCtx* ctx, unsigned int flags) { } } -void SPFlowtext::modified(unsigned int flags) { +void SPFlowtext::modified(unsigned int flags) +{ SPObject *region = nullptr; if (flags & SP_OBJECT_MODIFIED_FLAG) { - flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; + flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } flags &= SP_OBJECT_MODIFIED_CASCADE; // FIXME: the below stanza is copied over from sp_text_modified, consider factoring it out - if (flags & ( SP_OBJECT_STYLE_MODIFIED_FLAG )) { + if (flags & (SP_OBJECT_STYLE_MODIFIED_FLAG)) { Geom::OptRect pbox = geometricBounds(); - for (SPItemView* v = display; v != nullptr; v = v->next) { + for (SPItemView *v = display; v != nullptr; v = v->next) { Inkscape::DrawingGroup *g = dynamic_cast(v->arenaitem); _clearFlow(g); g->setStyle(style); @@ -133,7 +131,7 @@ void SPFlowtext::modified(unsigned int flags) { } } - for (auto& o: children) { + for (auto &o : children) { if (dynamic_cast(&o)) { region = &o; break; @@ -147,25 +145,27 @@ void SPFlowtext::modified(unsigned int flags) { } } -void SPFlowtext::build(SPDocument* doc, Inkscape::XML::Node* repr) { +void SPFlowtext::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ this->_requireSVGVersion(Inkscape::Version(1, 2)); SPItem::build(doc, repr); - this->readAttr(SPAttr::LAYOUT_OPTIONS); // must happen after css has been read + this->readAttr(SPAttr::LAYOUT_OPTIONS); // must happen after css has been read } -void SPFlowtext::set(SPAttr key, const gchar* value) { +void SPFlowtext::set(SPAttr key, const gchar *value) +{ switch (key) { case SPAttr::LAYOUT_OPTIONS: { // deprecated attribute, read for backward compatibility only - //XML Tree being directly used while it shouldn't be. + // XML Tree being directly used while it shouldn't be. SPCSSAttr *opts = sp_repr_css_attr(this->getRepr(), "inkscape:layoutOptions"); { gchar const *val = sp_repr_css_property(opts, "justification", nullptr); if (val != nullptr && !this->style->text_align.set) { - if ( strcmp(val, "0") == 0 || strcmp(val, "false") == 0 ) { + if (strcmp(val, "0") == 0 || strcmp(val, "false") == 0) { this->style->text_align.value = SP_CSS_TEXT_ALIGN_LEFT; } else { this->style->text_align.value = SP_CSS_TEXT_ALIGN_JUSTIFY; @@ -184,18 +184,17 @@ void SPFlowtext::set(SPAttr key, const gchar* value) { } else { if ( strcmp(val, "better") == 0 ) { // knuth-plass, never worked for general cases group->algo = 2; - } else if ( strcmp(val, "simple") == 0 ) { // greedy, but allowed lines to be compressed by up to 20% if it would make them fit - group->algo = 1; - } else if ( strcmp(val, "default") == 0 ) { // the same one we use, a standard greedy - group->algo = 0; + } else if ( strcmp(val, "simple") == 0 ) { // greedy, but allowed lines to be compressed by up to + 20% if it would make them fit group->algo = 1; } else if ( strcmp(val, "default") == 0 ) { // the same + one we use, a standard greedy group->algo = 0; } } } */ - { // This would probably translate to padding-left, if SPStyle had it. + { // This would probably translate to padding-left, if SPStyle had it. gchar const *val = sp_repr_css_property(opts, "par-indent", nullptr); - if ( val == nullptr ) { + if (val == nullptr) { this->par_indent = 0.0; } else { this->par_indent = g_ascii_strtod(val, nullptr); @@ -208,51 +207,55 @@ void SPFlowtext::set(SPAttr key, const gchar* value) { } default: - SPItem::set(key, value); + SPItem::set(key, value); break; } } -Inkscape::XML::Node* SPFlowtext::write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) { - if ( flags & SP_OBJECT_WRITE_BUILD ) { - if ( repr == nullptr ) { +Inkscape::XML::Node *SPFlowtext::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ + if (flags & SP_OBJECT_WRITE_BUILD) { + if (repr == nullptr) { repr = doc->createElement("svg:flowRoot"); } std::vector l; - for (auto& child: children) { + for (auto &child : children) { Inkscape::XML::Node *c_repr = nullptr; - if ( dynamic_cast(&child) || dynamic_cast(&child) || dynamic_cast(&child) || dynamic_cast(&child)) { + if (dynamic_cast(&child) || dynamic_cast(&child) || + dynamic_cast(&child) || dynamic_cast(&child)) { c_repr = child.updateRepr(doc, nullptr, flags); } - if ( c_repr ) { + if (c_repr) { l.push_back(c_repr); } } - for (auto i=l.rbegin();i!=l.rend();++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { - if ( dynamic_cast(&child) || dynamic_cast(&child) || dynamic_cast(&child) || dynamic_cast(&child)) { + for (auto &child : children) { + if (dynamic_cast(&child) || dynamic_cast(&child) || + dynamic_cast(&child) || dynamic_cast(&child)) { child.updateRepr(flags); } } } - this->rebuildLayout(); // copied from update(), see LP Bug 1339305 + this->rebuildLayout(); // copied from update(), see LP Bug 1339305 SPItem::write(doc, repr, flags); return repr; } -Geom::OptRect SPFlowtext::bbox(Geom::Affine const &transform, SPItem::BBoxType type) const { +Geom::OptRect SPFlowtext::bbox(Geom::Affine const &transform, SPItem::BBoxType type) const +{ Geom::OptRect bbox = this->layout.bounds(transform); // Add stroke width @@ -265,18 +268,20 @@ Geom::OptRect SPFlowtext::bbox(Geom::Affine const &transform, SPItem::BBoxType t return bbox; } -void SPFlowtext::print(SPPrintContext *ctx) { +void SPFlowtext::print(SPPrintContext *ctx) +{ Geom::OptRect pbox, bbox, dbox; pbox = this->geometricBounds(); bbox = this->desktopVisualBounds(); - dbox = Geom::Rect::from_xywh(Geom::Point(0,0), this->document->getDimensions()); + dbox = Geom::Rect::from_xywh(Geom::Point(0, 0), this->document->getDimensions()); - Geom::Affine const ctm (this->i2dt_affine()); + Geom::Affine const ctm(this->i2dt_affine()); this->layout.print(ctx, pbox, dbox, bbox, ctm); } -const char* SPFlowtext::displayName() const { +const char *SPFlowtext::displayName() const +{ if (has_internal_frame()) { return _("Flowed Text"); } else { @@ -284,30 +289,35 @@ const char* SPFlowtext::displayName() const { } } -gchar* SPFlowtext::description() const { +gchar *SPFlowtext::description() const +{ int const nChars = layout.iteratorToCharIndex(layout.end()); char const *trunc = (layout.inputTruncated()) ? _(" [truncated]") : ""; return g_strdup_printf(ngettext("(%d character%s)", "(%d characters%s)", nChars), nChars, trunc); } -void SPFlowtext::snappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const { +void SPFlowtext::snappoints(std::vector &p, + Inkscape::SnapPreferences const *snapprefs) const +{ if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_TEXT_BASELINE)) { // Choose a point on the baseline for snapping from or to, with the horizontal position // of this point depending on the text alignment (left vs. right) - Inkscape::Text::Layout const *layout = te_get_layout((SPItem *) this); + Inkscape::Text::Layout const *layout = te_get_layout((SPItem *)this); if (layout != nullptr && layout->outputExists()) { boost::optional pt = layout->baselineAnchorPoint(); if (pt) { - p.emplace_back((*pt) * this->i2dt_affine(), Inkscape::SNAPSOURCE_TEXT_ANCHOR, Inkscape::SNAPTARGET_TEXT_ANCHOR); + p.emplace_back((*pt) * this->i2dt_affine(), Inkscape::SNAPSOURCE_TEXT_ANCHOR, + Inkscape::SNAPTARGET_TEXT_ANCHOR); } } } } -Inkscape::DrawingItem* SPFlowtext::show(Inkscape::Drawing &drawing, unsigned int /*key*/, unsigned int /*flags*/) { +Inkscape::DrawingItem *SPFlowtext::show(Inkscape::Drawing &drawing, unsigned int /*key*/, unsigned int /*flags*/) +{ Inkscape::DrawingGroup *flowed = new Inkscape::DrawingGroup(drawing); flowed->setPickChildren(false); flowed->setStyle(this->style); @@ -319,8 +329,9 @@ Inkscape::DrawingItem* SPFlowtext::show(Inkscape::Drawing &drawing, unsigned int return flowed; } -void SPFlowtext::hide(unsigned int key) { - for (SPItemView* v = this->display; v != nullptr; v = v->next) { +void SPFlowtext::hide(unsigned int key) +{ + for (SPItemView *v = this->display; v != nullptr; v = v->next) { if (v->key == key) { Inkscape::DrawingGroup *g = dynamic_cast(v->arenaitem); this->_clearFlow(g); @@ -328,34 +339,33 @@ void SPFlowtext::hide(unsigned int key) { } } - /* * */ -void SPFlowtext::_buildLayoutInput(SPObject *root, Shape const *exclusion_shape, std::list *shapes, SPObject **pending_line_break_object) +void SPFlowtext::_buildLayoutInput(SPObject *root, Shape const *exclusion_shape, std::list *shapes, + SPObject **pending_line_break_object) { Inkscape::Text::Layout::OptionalTextTagAttrs pi; bool with_indent = false; if (dynamic_cast(root) || dynamic_cast(root)) { - layout.wrap_mode = Inkscape::Text::Layout::WRAP_SHAPE_INSIDE; layout.strut.reset(); if (style) { - font_instance *font = font_factory::Default()->FaceFromStyle( style ); + font_instance *font = font_factory::Default()->FaceFromStyle(style); if (font) { font->FontMetrics(layout.strut.ascent, layout.strut.descent, layout.strut.xheight); font->Unref(); } layout.strut *= style->font_size.computed; - if (style->line_height.normal ) { - layout.strut.computeEffective( Inkscape::Text::Layout::LINE_HEIGHT_NORMAL ); + if (style->line_height.normal) { + layout.strut.computeEffective(Inkscape::Text::Layout::LINE_HEIGHT_NORMAL); } else if (style->line_height.unit == SP_CSS_UNIT_NONE) { - layout.strut.computeEffective( style->line_height.computed ); + layout.strut.computeEffective(style->line_height.computed); } else { - if( style->font_size.computed > 0.0 ) { - layout.strut.computeEffective( style->line_height.computed/style->font_size.computed ); + if (style->font_size.computed > 0.0) { + layout.strut.computeEffective(style->line_height.computed / style->font_size.computed); } } } @@ -389,7 +399,7 @@ void SPFlowtext::_buildLayoutInput(SPObject *root, Shape const *exclusion_shape, *pending_line_break_object = nullptr; } - for (auto& child: root->children) { + for (auto &child : root->children) { SPString *str = dynamic_cast(&child); if (str) { if (*pending_line_break_object) { @@ -408,27 +418,29 @@ void SPFlowtext::_buildLayoutInput(SPObject *root, Shape const *exclusion_shape, } else { SPFlowregion *region = dynamic_cast(&child); if (region) { - std::vector const &computed = region->computed; + std::vector const &computed = region->computed; for (auto it : computed) { shapes->push_back(Shape()); if (exclusion_shape->hasEdges()) { - shapes->back().Booleen(it, const_cast(exclusion_shape), bool_op_diff); + shapes->back().Booleen(it, const_cast(exclusion_shape), bool_op_diff); } else { shapes->back().Copy(it); } layout.appendWrapShape(&shapes->back()); } } - //Xml Tree is being directly used while it shouldn't be. + // Xml Tree is being directly used while it shouldn't be. else if (!dynamic_cast(&child) && !sp_repr_is_meta_element(child.getRepr())) { _buildLayoutInput(&child, exclusion_shape, shapes, pending_line_break_object); } } } - - if (dynamic_cast(root) && !root->hasChildren()) return; - if (dynamic_cast(root) || dynamic_cast(root) || dynamic_cast(root) || dynamic_cast(root)) { + if (dynamic_cast(root) && !root->hasChildren()) + return; + + if (dynamic_cast(root) || dynamic_cast(root) || + dynamic_cast(root) || dynamic_cast(root)) { if (!root->hasChildren()) { layout.appendText("", root->style, root); } @@ -436,15 +448,15 @@ void SPFlowtext::_buildLayoutInput(SPObject *root, Shape const *exclusion_shape, } } -Shape* SPFlowtext::_buildExclusionShape() const +Shape *SPFlowtext::_buildExclusionShape() const { Shape *shape = new Shape(); Shape *shape_temp = new Shape(); - for (auto& child: children) { + for (auto &child : children) { // RH: is it right that this shouldn't be recursive? - SPFlowregionExclude *c_child = dynamic_cast(const_cast(&child)); - if ( c_child && c_child->computed && c_child->computed->hasEdges() ) { + SPFlowregionExclude *c_child = dynamic_cast(const_cast(&child)); + if (c_child && c_child->computed && c_child->computed->hasEdges()) { if (shape->hasEdges()) { shape_temp->Booleen(shape, c_child->computed, bool_op_union); std::swap(shape, shape_temp); @@ -498,7 +510,7 @@ Inkscape::XML::Node *SPFlowtext::getAsText() sp_repr_set_svg_double(repr, "x", anchor_point[Geom::X]); sp_repr_set_svg_double(repr, "y", anchor_point[Geom::Y]); - for (Inkscape::Text::Layout::iterator it = this->layout.begin() ; it != this->layout.end() ; ) { + for (Inkscape::Text::Layout::iterator it = this->layout.begin(); it != this->layout.end();) { Inkscape::XML::Node *line_tspan = xml_doc->createElement("svg:tspan"); line_tspan->setAttribute("sodipodi:role", "line"); @@ -506,7 +518,6 @@ Inkscape::XML::Node *SPFlowtext::getAsText() it_line_end.nextStartOfLine(); while (it != it_line_end) { - Inkscape::XML::Node *span_tspan = xml_doc->createElement("svg:tspan"); Geom::Point anchor_point = this->layout.characterAnchorPoint(it); // use kerning to simulate justification and whatnot @@ -535,11 +546,13 @@ Inkscape::XML::Node *SPFlowtext::getAsText() attrs.dx[0] = 0.0; TextTagAttributes(attrs).writeTo(span_tspan); if (set_x) - sp_repr_set_svg_double(span_tspan, "x", anchor_point[Geom::X]); // FIXME: this will pick up the wrong end of counter-directional runs + sp_repr_set_svg_double(span_tspan, "x", anchor_point[Geom::X]); // FIXME: this will pick up the wrong + // end of counter-directional runs if (set_y) sp_repr_set_svg_double(span_tspan, "y", anchor_point[Geom::Y]); if (line_tspan->childCount() == 0) { - sp_repr_set_svg_double(line_tspan, "x", anchor_point[Geom::X]); // FIXME: this will pick up the wrong end of counter-directional runs + sp_repr_set_svg_double(line_tspan, "x", anchor_point[Geom::X]); // FIXME: this will pick up the wrong + // end of counter-directional runs sp_repr_set_svg_double(line_tspan, "y", anchor_point[Geom::Y]); } @@ -547,7 +560,8 @@ Inkscape::XML::Node *SPFlowtext::getAsText() Glib::ustring::iterator span_text_start_iter; this->layout.getSourceOfCharacter(it, &source_obj, &span_text_start_iter); - Glib::ustring style_text = (dynamic_cast(source_obj) ? source_obj->parent : source_obj)->style->write( SP_STYLE_FLAG_IFDIFF, SP_STYLE_SRC_UNSET, this->style); + Glib::ustring style_text = (dynamic_cast(source_obj) ? source_obj->parent : source_obj) + ->style->write(SP_STYLE_FLAG_IFDIFF, SP_STYLE_SRC_UNSET, this->style); span_tspan->setAttributeOrRemoveIfEmpty("style", style_text); SPString *str = dynamic_cast(source_obj); @@ -559,16 +573,18 @@ Inkscape::XML::Node *SPFlowtext::getAsText() if (span_end_obj != source_obj) { if (it_span_end == this->layout.end()) { span_text_end_iter = span_text_start_iter; - for (int i = this->layout.iteratorToCharIndex(it_span_end) - this->layout.iteratorToCharIndex(it) ; i ; --i) + for (int i = + this->layout.iteratorToCharIndex(it_span_end) - this->layout.iteratorToCharIndex(it); + i; --i) ++span_text_end_iter; } else - span_text_end_iter = string->end(); // spans will never straddle a source boundary + span_text_end_iter = string->end(); // spans will never straddle a source boundary } if (span_text_start_iter != span_text_end_iter) { Glib::ustring new_string; while (span_text_start_iter != span_text_end_iter) - new_string += *span_text_start_iter++; // grr. no substr() with iterators + new_string += *span_text_start_iter++; // grr. no substr() with iterators Inkscape::XML::Node *new_text = xml_doc->createTextNode(new_string.c_str()); span_tspan->appendChild(new_text); Inkscape::GC::release(new_text); @@ -597,7 +613,7 @@ SPItem *SPFlowtext::get_frame(SPItem const *after) SPItem *frame = nullptr; SPObject *region = nullptr; - for (auto& o: children) { + for (auto &o : children) { if (dynamic_cast(&o)) { region = &o; break; @@ -607,10 +623,10 @@ SPItem *SPFlowtext::get_frame(SPItem const *after) if (region) { bool past = false; - for (auto& o: region->children) { + for (auto &o : region->children) { SPItem *item = dynamic_cast(&o); if (item) { - if ( (after == nullptr) || past ) { + if ((after == nullptr) || past) { frame = item; } else { if (item == after) { @@ -621,7 +637,7 @@ SPItem *SPFlowtext::get_frame(SPItem const *after) } SPUse *use = dynamic_cast(frame); - if ( use ) { + if (use) { frame = use->get_original(); } } @@ -635,8 +651,7 @@ bool SPFlowtext::has_internal_frame() const return (frame && isAncestorOf(frame) && dynamic_cast(frame)); } - -SPItem *create_flowtext_with_internal_frame (SPDesktop *desktop, Geom::Point p0, Geom::Point p1) +SPItem *create_flowtext_with_internal_frame(SPDesktop *desktop, Geom::Point p0, Geom::Point p1) { SPDocument *doc = desktop->getDocument(); @@ -653,7 +668,8 @@ SPItem *create_flowtext_with_internal_frame (SPDesktop *desktop, Geom::Point p0, SPObject *region_object = doc->getObjectByRepr(region_repr); g_assert(dynamic_cast(region_object) != nullptr); - Inkscape::XML::Node *rect_repr = xml_doc->createElement("svg:rect"); // FIXME: use path!!! after rects are converted to use path + Inkscape::XML::Node *rect_repr = + xml_doc->createElement("svg:rect"); // FIXME: use path!!! after rects are converted to use path region_repr->appendChild(rect_repr); SPRect *rect = dynamic_cast(doc->getObjectByRepr(rect_repr)); @@ -667,8 +683,8 @@ SPItem *create_flowtext_with_internal_frame (SPDesktop *desktop, Geom::Point p0, Geom::Coord const y0 = MIN(p0[Y], p1[Y]); Geom::Coord const x1 = MAX(p0[X], p1[X]); Geom::Coord const y1 = MAX(p0[Y], p1[Y]); - Geom::Coord const w = x1 - x0; - Geom::Coord const h = y1 - y0; + Geom::Coord const w = x1 - x0; + Geom::Coord const h = y1 - y0; SPItem *item = dynamic_cast(desktop->currentLayer()); g_assert(item != nullptr); @@ -700,7 +716,8 @@ void SPFlowtext::fix_overflow_flowregion(bool inverse) if (flowregion) { object = dynamic_cast(flowregion); for (auto childshapes : object->childList(false)) { - Geom::Scale scale = Geom::Scale(1000); //200? maybe find better way to fix overglow issue removing new lines... + Geom::Scale scale = + Geom::Scale(1000); // 200? maybe find better way to fix overglow issue removing new lines... if (inverse) { scale = scale.inverse(); } @@ -711,24 +728,24 @@ void SPFlowtext::fix_overflow_flowregion(bool inverse) } } -Geom::Affine SPFlowtext::set_transform (Geom::Affine const &xform) +Geom::Affine SPFlowtext::set_transform(Geom::Affine const &xform) { - if ((this->_optimizeScaledText && !xform.withoutTranslation().isNonzeroUniformScale()) - || (!this->_optimizeScaledText && !xform.isNonzeroUniformScale())) { + if ((this->_optimizeScaledText && !xform.withoutTranslation().isNonzeroUniformScale()) || + (!this->_optimizeScaledText && !xform.isNonzeroUniformScale())) { this->_optimizeScaledText = false; return xform; } this->_optimizeScaledText = false; - + SPText *text = reinterpret_cast(this); - + double const ex = xform.descrim(); if (ex == 0) { return xform; } SPObject *region = nullptr; - for (auto& o: children) { + for (auto &o : children) { if (dynamic_cast(&o)) { region = &o; break; @@ -749,10 +766,10 @@ Geom::Affine SPFlowtext::set_transform (Geom::Affine const &xform) ret[3] /= ex; // Adjust font size - text->_adjustFontsizeRecursive (this, ex); + text->_adjustFontsizeRecursive(this, ex); // Adjust stroke width - this->adjust_stroke_width_recursive (ex); + this->adjust_stroke_width_recursive(ex); // Adjust pattern fill this->adjust_pattern(xform * ret.inverse()); diff --git a/src/object/sp-flowtext.h b/src/object/sp-flowtext.h index cacd1bae301014a0addce0c875c5ecf1ffb29500..8d5b268ac333eb80d1f94a098dd2b295b5caeb6c 100644 --- a/src/object/sp-flowtext.h +++ b/src/object/sp-flowtext.h @@ -14,16 +14,14 @@ */ #include <2geom/forward.h> +#include +#include "desktop.h" #include "libnrtype/Layout-TNG.h" #include "sp-item.h" -#include "desktop.h" - -#include - -#define SP_FLOWTEXT(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FLOWTEXT(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FLOWTEXT(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FLOWTEXT(obj) (dynamic_cast((SPObject *)obj) != NULL) namespace Inkscape { @@ -31,10 +29,11 @@ class DrawingGroup; } // namespace Inkscape -class SPFlowtext : public SPItem { +class SPFlowtext : public SPItem +{ public: - SPFlowtext(); - ~SPFlowtext() override; + SPFlowtext(); + ~SPFlowtext() override; /** Completely recalculates the layout. */ void rebuildLayout(); @@ -51,56 +50,57 @@ public: bool has_internal_frame() const; -//semiprivate: (need to be accessed by the C-style functions still) + // semiprivate: (need to be accessed by the C-style functions still) Inkscape::Text::Layout layout; /** discards the drawing objects representing this text. */ - void _clearFlow(Inkscape::DrawingGroup* in_arena); + void _clearFlow(Inkscape::DrawingGroup *in_arena); double par_indent; bool _optimizeScaledText; - /** Converts the text object to its component curves */ + /** Converts the text object to its component curves */ std::unique_ptr getNormalizedBpath() const; /** Optimize scaled flow text on next set_transform. */ - void optimizeScaledText() - {_optimizeScaledText = true;} + void optimizeScaledText() { _optimizeScaledText = true; } private: /** Recursively walks the xml tree adding tags and their contents. */ - void _buildLayoutInput(SPObject *root, Shape const *exclusion_shape, std::list *shapes, SPObject **pending_line_break_object); + void _buildLayoutInput(SPObject *root, Shape const *exclusion_shape, std::list *shapes, + SPObject **pending_line_break_object); /** calculates the union of all the \ children of this flowroot. */ - Shape* _buildExclusionShape() const; + Shape *_buildExclusionShape() const; public: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; - void set(SPAttr key, const char* value) override; - Geom::Affine set_transform(Geom::Affine const& xform) override; + void set(SPAttr key, const char *value) override; + Geom::Affine set_transform(Geom::Affine const &xform) override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; void fix_overflow_flowregion(bool inverse); - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; - Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; - void print(SPPrintContext *ctx) override; - const char* displayName() const override; - char* description() const override; - Inkscape::DrawingItem* show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; - void hide(unsigned int key) override; - void snappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const override; + Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; + void print(SPPrintContext *ctx) override; + const char *displayName() const override; + char *description() const override; + Inkscape::DrawingItem *show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; + void hide(unsigned int key) override; + void snappoints(std::vector &p, + Inkscape::SnapPreferences const *snapprefs) const override; }; -SPItem *create_flowtext_with_internal_frame (SPDesktop *desktop, Geom::Point p1, Geom::Point p2); +SPItem *create_flowtext_with_internal_frame(SPDesktop *desktop, Geom::Point p1, Geom::Point p2); #endif // SEEN_SP_ITEM_FLOWTEXT_H diff --git a/src/object/sp-font-face.cpp b/src/object/sp-font-face.cpp index 8d8b363215e7b5b2229a3d114c89b86404a492e9..dc830085bfa063363dd79f72b142152c159b39b1 100644 --- a/src/object/sp-font-face.cpp +++ b/src/object/sp-font-face.cpp @@ -15,248 +15,255 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "xml/repr.h" -#include "attributes.h" #include "sp-font-face.h" -#include "document.h" #include -static std::vector sp_read_fontFaceStyleType(gchar const *value){ +#include "attributes.h" +#include "document.h" +#include "xml/repr.h" + +static std::vector sp_read_fontFaceStyleType(gchar const *value) +{ std::vector v; - if (!value){ + if (!value) { v.push_back(SP_FONTFACE_STYLE_ALL); return v; } - if (strncmp(value, "all", 3) == 0){ + if (strncmp(value, "all", 3) == 0) { value += 3; - while(value[0]==',' || value[0]==' ') + while (value[0] == ',' || value[0] == ' ') value++; v.push_back(SP_FONTFACE_STYLE_ALL); return v; } - while(value[0]!='\0'){ - switch(value[0]){ + while (value[0] != '\0') { + switch (value[0]) { case 'n': - if (strncmp(value, "normal", 6) == 0){ + if (strncmp(value, "normal", 6) == 0) { v.push_back(SP_FONTFACE_STYLE_NORMAL); value += 6; } break; case 'i': - if (strncmp(value, "italic", 6) == 0){ + if (strncmp(value, "italic", 6) == 0) { v.push_back(SP_FONTFACE_STYLE_ITALIC); value += 6; } break; case 'o': - if (strncmp(value, "oblique", 7) == 0){ + if (strncmp(value, "oblique", 7) == 0) { v.push_back(SP_FONTFACE_STYLE_OBLIQUE); value += 7; } break; } - while(value[0]==',' || value[0]==' ') + while (value[0] == ',' || value[0] == ' ') value++; } return v; } -static std::vector sp_read_fontFaceVariantType(gchar const *value){ +static std::vector sp_read_fontFaceVariantType(gchar const *value) +{ std::vector v; - if (!value){ + if (!value) { v.push_back(SP_FONTFACE_VARIANT_NORMAL); return v; } - while(value[0]!='\0'){ - switch(value[0]){ + while (value[0] != '\0') { + switch (value[0]) { case 'n': - if (strncmp(value, "normal", 6) == 0){ + if (strncmp(value, "normal", 6) == 0) { v.push_back(SP_FONTFACE_VARIANT_NORMAL); value += 6; } break; case 's': - if (strncmp(value, "small-caps", 10) == 0){ + if (strncmp(value, "small-caps", 10) == 0) { v.push_back(SP_FONTFACE_VARIANT_SMALL_CAPS); value += 10; } break; } - while(value[0]==',' || value[0]==' ') + while (value[0] == ',' || value[0] == ' ') value++; } return v; } -static std::vector sp_read_fontFaceWeightType(gchar const *value){ +static std::vector sp_read_fontFaceWeightType(gchar const *value) +{ std::vector v; - if (!value){ + if (!value) { v.push_back(SP_FONTFACE_WEIGHT_ALL); return v; } - if (strncmp(value, "all", 3) == 0){ + if (strncmp(value, "all", 3) == 0) { value += 3; - while(value[0]==',' || value[0]==' ') + while (value[0] == ',' || value[0] == ' ') value++; v.push_back(SP_FONTFACE_WEIGHT_ALL); return v; } - while(value[0]!='\0'){ - switch(value[0]){ + while (value[0] != '\0') { + switch (value[0]) { case 'n': - if (strncmp(value, "normal", 6) == 0){ + if (strncmp(value, "normal", 6) == 0) { v.push_back(SP_FONTFACE_WEIGHT_NORMAL); value += 6; } break; case 'b': - if (strncmp(value, "bold", 4) == 0){ + if (strncmp(value, "bold", 4) == 0) { v.push_back(SP_FONTFACE_WEIGHT_BOLD); value += 4; } break; case '1': - if (strncmp(value, "100", 3) == 0){ + if (strncmp(value, "100", 3) == 0) { v.push_back(SP_FONTFACE_WEIGHT_100); value += 3; } break; case '2': - if (strncmp(value, "200", 3) == 0){ + if (strncmp(value, "200", 3) == 0) { v.push_back(SP_FONTFACE_WEIGHT_200); value += 3; } break; case '3': - if (strncmp(value, "300", 3) == 0){ + if (strncmp(value, "300", 3) == 0) { v.push_back(SP_FONTFACE_WEIGHT_300); value += 3; } break; case '4': - if (strncmp(value, "400", 3) == 0){ + if (strncmp(value, "400", 3) == 0) { v.push_back(SP_FONTFACE_WEIGHT_400); value += 3; } break; case '5': - if (strncmp(value, "500", 3) == 0){ + if (strncmp(value, "500", 3) == 0) { v.push_back(SP_FONTFACE_WEIGHT_500); value += 3; } break; case '6': - if (strncmp(value, "600", 3) == 0){ + if (strncmp(value, "600", 3) == 0) { v.push_back(SP_FONTFACE_WEIGHT_600); value += 3; } break; case '7': - if (strncmp(value, "700", 3) == 0){ + if (strncmp(value, "700", 3) == 0) { v.push_back(SP_FONTFACE_WEIGHT_700); value += 3; } break; case '8': - if (strncmp(value, "800", 3) == 0){ + if (strncmp(value, "800", 3) == 0) { v.push_back(SP_FONTFACE_WEIGHT_800); value += 3; } break; case '9': - if (strncmp(value, "900", 3) == 0){ + if (strncmp(value, "900", 3) == 0) { v.push_back(SP_FONTFACE_WEIGHT_900); value += 3; } break; } - while(value[0]==',' || value[0]==' ') + while (value[0] == ',' || value[0] == ' ') value++; } return v; } -static std::vector sp_read_fontFaceStretchType(gchar const *value){ +static std::vector sp_read_fontFaceStretchType(gchar const *value) +{ std::vector v; - if (!value){ + if (!value) { v.push_back(SP_FONTFACE_STRETCH_NORMAL); return v; } - if (strncmp(value, "all", 3) == 0){ + if (strncmp(value, "all", 3) == 0) { value += 3; - while(value[0]==',' || value[0]==' ') + while (value[0] == ',' || value[0] == ' ') value++; v.push_back(SP_FONTFACE_STRETCH_ALL); return v; } - while(value[0]!='\0'){ - switch(value[0]){ + while (value[0] != '\0') { + switch (value[0]) { case 'n': - if (strncmp(value, "normal", 6) == 0){ + if (strncmp(value, "normal", 6) == 0) { v.push_back(SP_FONTFACE_STRETCH_NORMAL); value += 6; } break; case 'u': - if (strncmp(value, "ultra-condensed", 15) == 0){ + if (strncmp(value, "ultra-condensed", 15) == 0) { v.push_back(SP_FONTFACE_STRETCH_ULTRA_CONDENSED); value += 15; } - if (strncmp(value, "ultra-expanded", 14) == 0){ + if (strncmp(value, "ultra-expanded", 14) == 0) { v.push_back(SP_FONTFACE_STRETCH_ULTRA_EXPANDED); value += 14; } break; case 'e': - if (strncmp(value, "expanded", 8) == 0){ + if (strncmp(value, "expanded", 8) == 0) { v.push_back(SP_FONTFACE_STRETCH_EXPANDED); value += 8; } - if (strncmp(value, "extra-condensed", 15) == 0){ + if (strncmp(value, "extra-condensed", 15) == 0) { v.push_back(SP_FONTFACE_STRETCH_EXTRA_CONDENSED); value += 15; } - if (strncmp(value, "extra-expanded", 14) == 0){ + if (strncmp(value, "extra-expanded", 14) == 0) { v.push_back(SP_FONTFACE_STRETCH_EXTRA_EXPANDED); value += 14; } break; case 'c': - if (strncmp(value, "condensed", 9) == 0){ + if (strncmp(value, "condensed", 9) == 0) { v.push_back(SP_FONTFACE_STRETCH_CONDENSED); value += 9; } break; case 's': - if (strncmp(value, "semi-condensed", 14) == 0){ + if (strncmp(value, "semi-condensed", 14) == 0) { v.push_back(SP_FONTFACE_STRETCH_SEMI_CONDENSED); value += 14; } - if (strncmp(value, "semi-expanded", 13) == 0){ + if (strncmp(value, "semi-expanded", 13) == 0) { v.push_back(SP_FONTFACE_STRETCH_SEMI_EXPANDED); value += 13; } break; } - while(value[0]==',' || value[0]==' ') + while (value[0] == ',' || value[0] == ' ') value++; } return v; } -SPFontFace::SPFontFace() : SPObject() { +SPFontFace::SPFontFace() + : SPObject() +{ std::vector style; style.push_back(SP_FONTFACE_STYLE_ALL); this->font_style = style; @@ -274,14 +281,14 @@ SPFontFace::SPFontFace() : SPObject() { this->font_stretch = stretch; this->font_family = nullptr; - //this->font_style = ; - //this->font_variant = ; - //this->font_weight = ; - //this->font_stretch = ; + // this->font_style = ; + // this->font_variant = ; + // this->font_weight = ; + // this->font_stretch = ; this->font_size = nullptr; - //this->unicode_range = ; + // this->unicode_range = ; this->units_per_em = 1000; - //this->panose_1 = ; + // this->panose_1 = ; this->stemv = 0; this->stemh = 0; this->slope = 0; @@ -310,68 +317,72 @@ SPFontFace::SPFontFace() : SPObject() { SPFontFace::~SPFontFace() = default; -void SPFontFace::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPObject::build(document, repr); - - this->readAttr(SPAttr::FONT_FAMILY); - this->readAttr(SPAttr::FONT_STYLE); - this->readAttr(SPAttr::FONT_VARIANT); - this->readAttr(SPAttr::FONT_WEIGHT); - this->readAttr(SPAttr::FONT_STRETCH); - this->readAttr(SPAttr::FONT_SIZE); - this->readAttr(SPAttr::UNICODE_RANGE); - this->readAttr(SPAttr::UNITS_PER_EM); - this->readAttr(SPAttr::PANOSE_1); - this->readAttr(SPAttr::STEMV); - this->readAttr(SPAttr::STEMH); - this->readAttr(SPAttr::SLOPE); - this->readAttr(SPAttr::CAP_HEIGHT); - this->readAttr(SPAttr::X_HEIGHT); - this->readAttr(SPAttr::ACCENT_HEIGHT); - this->readAttr(SPAttr::ASCENT); - this->readAttr(SPAttr::DESCENT); - this->readAttr(SPAttr::WIDTHS); - this->readAttr(SPAttr::BBOX); - this->readAttr(SPAttr::IDEOGRAPHIC); - this->readAttr(SPAttr::ALPHABETIC); - this->readAttr(SPAttr::MATHEMATICAL); - this->readAttr(SPAttr::HANGING); - this->readAttr(SPAttr::V_IDEOGRAPHIC); - this->readAttr(SPAttr::V_ALPHABETIC); - this->readAttr(SPAttr::V_MATHEMATICAL); - this->readAttr(SPAttr::V_HANGING); - this->readAttr(SPAttr::UNDERLINE_POSITION); - this->readAttr(SPAttr::UNDERLINE_THICKNESS); - this->readAttr(SPAttr::STRIKETHROUGH_POSITION); - this->readAttr(SPAttr::STRIKETHROUGH_THICKNESS); - this->readAttr(SPAttr::OVERLINE_POSITION); - this->readAttr(SPAttr::OVERLINE_THICKNESS); +void SPFontFace::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPObject::build(document, repr); + + this->readAttr(SPAttr::FONT_FAMILY); + this->readAttr(SPAttr::FONT_STYLE); + this->readAttr(SPAttr::FONT_VARIANT); + this->readAttr(SPAttr::FONT_WEIGHT); + this->readAttr(SPAttr::FONT_STRETCH); + this->readAttr(SPAttr::FONT_SIZE); + this->readAttr(SPAttr::UNICODE_RANGE); + this->readAttr(SPAttr::UNITS_PER_EM); + this->readAttr(SPAttr::PANOSE_1); + this->readAttr(SPAttr::STEMV); + this->readAttr(SPAttr::STEMH); + this->readAttr(SPAttr::SLOPE); + this->readAttr(SPAttr::CAP_HEIGHT); + this->readAttr(SPAttr::X_HEIGHT); + this->readAttr(SPAttr::ACCENT_HEIGHT); + this->readAttr(SPAttr::ASCENT); + this->readAttr(SPAttr::DESCENT); + this->readAttr(SPAttr::WIDTHS); + this->readAttr(SPAttr::BBOX); + this->readAttr(SPAttr::IDEOGRAPHIC); + this->readAttr(SPAttr::ALPHABETIC); + this->readAttr(SPAttr::MATHEMATICAL); + this->readAttr(SPAttr::HANGING); + this->readAttr(SPAttr::V_IDEOGRAPHIC); + this->readAttr(SPAttr::V_ALPHABETIC); + this->readAttr(SPAttr::V_MATHEMATICAL); + this->readAttr(SPAttr::V_HANGING); + this->readAttr(SPAttr::UNDERLINE_POSITION); + this->readAttr(SPAttr::UNDERLINE_THICKNESS); + this->readAttr(SPAttr::STRIKETHROUGH_POSITION); + this->readAttr(SPAttr::STRIKETHROUGH_THICKNESS); + this->readAttr(SPAttr::OVERLINE_POSITION); + this->readAttr(SPAttr::OVERLINE_THICKNESS); } /** * Callback for child_added event. */ -void SPFontFace::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { +void SPFontFace::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ SPObject::child_added(child, ref); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } - /** * Callback for remove_child event. */ -void SPFontFace::remove_child(Inkscape::XML::Node *child) { +void SPFontFace::remove_child(Inkscape::XML::Node *child) +{ SPObject::remove_child(child); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } -void SPFontFace::release() { - SPObject::release(); +void SPFontFace::release() +{ + SPObject::release(); } -void SPFontFace::set(SPAttr key, const gchar *value) { +void SPFontFace::set(SPAttr key, const gchar *value) +{ std::vector style; std::vector variant; std::vector weight; @@ -382,19 +393,19 @@ void SPFontFace::set(SPAttr key, const gchar *value) { if (this->font_family) { g_free(this->font_family); } - + this->font_family = g_strdup(value); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::FONT_STYLE: style = sp_read_fontFaceStyleType(value); - - if (this->font_style.size() != style.size()){ + + if (this->font_style.size() != style.size()) { this->font_style = style; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } else { - for (unsigned int i=0;ifont_style[i]){ + for (unsigned int i = 0; i < style.size(); i++) { + if (style[i] != this->font_style[i]) { this->font_style = style; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; @@ -404,13 +415,13 @@ void SPFontFace::set(SPAttr key, const gchar *value) { break; case SPAttr::FONT_VARIANT: variant = sp_read_fontFaceVariantType(value); - - if (this->font_variant.size() != variant.size()){ + + if (this->font_variant.size() != variant.size()) { this->font_variant = variant; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } else { - for (unsigned int i=0;ifont_variant[i]){ + for (unsigned int i = 0; i < variant.size(); i++) { + if (variant[i] != this->font_variant[i]) { this->font_variant = variant; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; @@ -420,13 +431,13 @@ void SPFontFace::set(SPAttr key, const gchar *value) { break; case SPAttr::FONT_WEIGHT: weight = sp_read_fontFaceWeightType(value); - - if (this->font_weight.size() != weight.size()){ + + if (this->font_weight.size() != weight.size()) { this->font_weight = weight; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } else { - for (unsigned int i=0;ifont_weight[i]){ + for (unsigned int i = 0; i < weight.size(); i++) { + if (weight[i] != this->font_weight[i]) { this->font_weight = weight; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; @@ -436,13 +447,13 @@ void SPFontFace::set(SPAttr key, const gchar *value) { break; case SPAttr::FONT_STRETCH: stretch = sp_read_fontFaceStretchType(value); - - if (this->font_stretch.size() != stretch.size()){ + + if (this->font_stretch.size() != stretch.size()) { this->font_stretch = stretch; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } else { - for (unsigned int i=0;ifont_stretch[i]){ + for (unsigned int i = 0; i < stretch.size(); i++) { + if (stretch[i] != this->font_stretch[i]) { this->font_stretch = stretch; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; @@ -450,238 +461,215 @@ void SPFontFace::set(SPAttr key, const gchar *value) { } } break; - case SPAttr::UNITS_PER_EM: - { + case SPAttr::UNITS_PER_EM: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->units_per_em){ + + if (number != this->units_per_em) { this->units_per_em = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::STEMV: - { + case SPAttr::STEMV: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->stemv){ + + if (number != this->stemv) { this->stemv = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::STEMH: - { + case SPAttr::STEMH: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->stemh){ + + if (number != this->stemh) { this->stemh = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::SLOPE: - { + case SPAttr::SLOPE: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->slope){ + + if (number != this->slope) { this->slope = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::CAP_HEIGHT: - { + case SPAttr::CAP_HEIGHT: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->cap_height){ + + if (number != this->cap_height) { this->cap_height = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::X_HEIGHT: - { + case SPAttr::X_HEIGHT: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->x_height){ + + if (number != this->x_height) { this->x_height = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::ACCENT_HEIGHT: - { + case SPAttr::ACCENT_HEIGHT: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->accent_height){ + + if (number != this->accent_height) { this->accent_height = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::ASCENT: - { + case SPAttr::ASCENT: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->ascent){ + + if (number != this->ascent) { this->ascent = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::DESCENT: - { + case SPAttr::DESCENT: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->descent){ + + if (number != this->descent) { this->descent = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::IDEOGRAPHIC: - { + case SPAttr::IDEOGRAPHIC: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->ideographic){ + + if (number != this->ideographic) { this->ideographic = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::ALPHABETIC: - { + case SPAttr::ALPHABETIC: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->alphabetic){ + + if (number != this->alphabetic) { this->alphabetic = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::MATHEMATICAL: - { + case SPAttr::MATHEMATICAL: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->mathematical){ + + if (number != this->mathematical) { this->mathematical = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::HANGING: - { + case SPAttr::HANGING: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->hanging){ + + if (number != this->hanging) { this->hanging = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::V_IDEOGRAPHIC: - { + case SPAttr::V_IDEOGRAPHIC: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->v_ideographic){ + + if (number != this->v_ideographic) { this->v_ideographic = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::V_ALPHABETIC: - { + case SPAttr::V_ALPHABETIC: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->v_alphabetic){ + + if (number != this->v_alphabetic) { this->v_alphabetic = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::V_MATHEMATICAL: - { + case SPAttr::V_MATHEMATICAL: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->v_mathematical){ + + if (number != this->v_mathematical) { this->v_mathematical = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::V_HANGING: - { + case SPAttr::V_HANGING: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->v_hanging){ + + if (number != this->v_hanging) { this->v_hanging = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::UNDERLINE_POSITION: - { + case SPAttr::UNDERLINE_POSITION: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->underline_position){ + + if (number != this->underline_position) { this->underline_position = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::UNDERLINE_THICKNESS: - { + case SPAttr::UNDERLINE_THICKNESS: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->underline_thickness){ + + if (number != this->underline_thickness) { this->underline_thickness = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::STRIKETHROUGH_POSITION: - { + case SPAttr::STRIKETHROUGH_POSITION: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->strikethrough_position){ + + if (number != this->strikethrough_position) { this->strikethrough_position = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::STRIKETHROUGH_THICKNESS: - { + case SPAttr::STRIKETHROUGH_THICKNESS: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->strikethrough_thickness){ + + if (number != this->strikethrough_thickness) { this->strikethrough_thickness = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::OVERLINE_POSITION: - { + case SPAttr::OVERLINE_POSITION: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->overline_position){ + + if (number != this->overline_position) { this->overline_position = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::OVERLINE_THICKNESS: - { + case SPAttr::OVERLINE_THICKNESS: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->overline_thickness){ + + if (number != this->overline_thickness) { this->overline_thickness = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } default: - SPObject::set(key, value); + SPObject::set(key, value); break; } } @@ -689,7 +677,8 @@ void SPFontFace::set(SPAttr key, const gchar *value) { /** * Receives update notifications. */ -void SPFontFace::update(SPCtx *ctx, guint flags) { +void SPFontFace::update(SPCtx *ctx, guint flags) +{ if (flags & (SP_OBJECT_MODIFIED_FLAG)) { this->readAttr(SPAttr::FONT_FAMILY); this->readAttr(SPAttr::FONT_STYLE); @@ -729,23 +718,24 @@ void SPFontFace::update(SPCtx *ctx, guint flags) { SPObject::update(ctx, flags); } -#define COPY_ATTR(rd,rs,key) (rd)->setAttribute((key), rs->attribute(key)); +#define COPY_ATTR(rd, rs, key) (rd)->setAttribute((key), rs->attribute(key)); -Inkscape::XML::Node* SPFontFace::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFontFace::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:font-face"); } - //TODO: - //sp_repr_set_svg_double(repr, "font-family", face->font_family); - //sp_repr_set_svg_double(repr, "font-style", face->font_style); - //sp_repr_set_svg_double(repr, "font-variant", face->font_variant); - //sp_repr_set_svg_double(repr, "font-weight", face->font_weight); - //sp_repr_set_svg_double(repr, "font-stretch", face->font_stretch); - //sp_repr_set_svg_double(repr, "font-size", face->font_size); - //sp_repr_set_svg_double(repr, "unicode-range", face->unicode_range); + // TODO: + // sp_repr_set_svg_double(repr, "font-family", face->font_family); + // sp_repr_set_svg_double(repr, "font-style", face->font_style); + // sp_repr_set_svg_double(repr, "font-variant", face->font_variant); + // sp_repr_set_svg_double(repr, "font-weight", face->font_weight); + // sp_repr_set_svg_double(repr, "font-stretch", face->font_stretch); + // sp_repr_set_svg_double(repr, "font-size", face->font_size); + // sp_repr_set_svg_double(repr, "unicode-range", face->unicode_range); sp_repr_set_svg_double(repr, "units-per-em", this->units_per_em); - //sp_repr_set_svg_double(repr, "panose-1", face->panose_1); + // sp_repr_set_svg_double(repr, "panose-1", face->panose_1); sp_repr_set_svg_double(repr, "stemv", this->stemv); sp_repr_set_svg_double(repr, "stemh", this->stemh); sp_repr_set_svg_double(repr, "slope", this->slope); @@ -754,8 +744,8 @@ Inkscape::XML::Node* SPFontFace::write(Inkscape::XML::Document *xml_doc, Inkscap sp_repr_set_svg_double(repr, "accent-height", this->accent_height); sp_repr_set_svg_double(repr, "ascent", this->ascent); sp_repr_set_svg_double(repr, "descent", this->descent); - //sp_repr_set_svg_double(repr, "widths", face->widths); - //sp_repr_set_svg_double(repr, "bbox", face->bbox); + // sp_repr_set_svg_double(repr, "widths", face->widths); + // sp_repr_set_svg_double(repr, "bbox", face->bbox); sp_repr_set_svg_double(repr, "ideographic", this->ideographic); sp_repr_set_svg_double(repr, "alphabetic", this->alphabetic); sp_repr_set_svg_double(repr, "mathematical", this->mathematical); @@ -772,7 +762,7 @@ Inkscape::XML::Node* SPFontFace::write(Inkscape::XML::Document *xml_doc, Inkscap sp_repr_set_svg_double(repr, "overline-thickness", this->overline_thickness); if (repr != this->getRepr()) { - // In all COPY_ATTR given below the XML tree is + // In all COPY_ATTR given below the XML tree is // being used directly while it shouldn't be. COPY_ATTR(repr, this->getRepr(), "font-family"); COPY_ATTR(repr, this->getRepr(), "font-style"); diff --git a/src/object/sp-font-face.h b/src/object/sp-font-face.h index 4d7a7b41553af2b5e7e377ee04c5bbb581a6f0f8..13506d1fbecf258f753939cb72050ca5bf2f76f8 100644 --- a/src/object/sp-font-face.h +++ b/src/object/sp-font-face.h @@ -21,64 +21,70 @@ #include "sp-object.h" -#define SP_FONTFACE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FONTFACE(obj) (dynamic_cast((SPObject*)obj) != NULL) - -enum FontFaceStyleType{ - SP_FONTFACE_STYLE_ALL, - SP_FONTFACE_STYLE_NORMAL, - SP_FONTFACE_STYLE_ITALIC, - SP_FONTFACE_STYLE_OBLIQUE +#define SP_FONTFACE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FONTFACE(obj) (dynamic_cast((SPObject *)obj) != NULL) + +enum FontFaceStyleType +{ + SP_FONTFACE_STYLE_ALL, + SP_FONTFACE_STYLE_NORMAL, + SP_FONTFACE_STYLE_ITALIC, + SP_FONTFACE_STYLE_OBLIQUE }; -enum FontFaceVariantType{ - SP_FONTFACE_VARIANT_NORMAL, - SP_FONTFACE_VARIANT_SMALL_CAPS +enum FontFaceVariantType +{ + SP_FONTFACE_VARIANT_NORMAL, + SP_FONTFACE_VARIANT_SMALL_CAPS }; -enum FontFaceWeightType{ - SP_FONTFACE_WEIGHT_ALL, - SP_FONTFACE_WEIGHT_NORMAL, - SP_FONTFACE_WEIGHT_BOLD, - SP_FONTFACE_WEIGHT_100, - SP_FONTFACE_WEIGHT_200, - SP_FONTFACE_WEIGHT_300, - SP_FONTFACE_WEIGHT_400, - SP_FONTFACE_WEIGHT_500, - SP_FONTFACE_WEIGHT_600, - SP_FONTFACE_WEIGHT_700, - SP_FONTFACE_WEIGHT_800, - SP_FONTFACE_WEIGHT_900 +enum FontFaceWeightType +{ + SP_FONTFACE_WEIGHT_ALL, + SP_FONTFACE_WEIGHT_NORMAL, + SP_FONTFACE_WEIGHT_BOLD, + SP_FONTFACE_WEIGHT_100, + SP_FONTFACE_WEIGHT_200, + SP_FONTFACE_WEIGHT_300, + SP_FONTFACE_WEIGHT_400, + SP_FONTFACE_WEIGHT_500, + SP_FONTFACE_WEIGHT_600, + SP_FONTFACE_WEIGHT_700, + SP_FONTFACE_WEIGHT_800, + SP_FONTFACE_WEIGHT_900 }; -enum FontFaceStretchType{ - SP_FONTFACE_STRETCH_ALL, - SP_FONTFACE_STRETCH_NORMAL, - SP_FONTFACE_STRETCH_ULTRA_CONDENSED, - SP_FONTFACE_STRETCH_EXTRA_CONDENSED, - SP_FONTFACE_STRETCH_CONDENSED, - SP_FONTFACE_STRETCH_SEMI_CONDENSED, - SP_FONTFACE_STRETCH_SEMI_EXPANDED, - SP_FONTFACE_STRETCH_EXPANDED, - SP_FONTFACE_STRETCH_EXTRA_EXPANDED, - SP_FONTFACE_STRETCH_ULTRA_EXPANDED +enum FontFaceStretchType +{ + SP_FONTFACE_STRETCH_ALL, + SP_FONTFACE_STRETCH_NORMAL, + SP_FONTFACE_STRETCH_ULTRA_CONDENSED, + SP_FONTFACE_STRETCH_EXTRA_CONDENSED, + SP_FONTFACE_STRETCH_CONDENSED, + SP_FONTFACE_STRETCH_SEMI_CONDENSED, + SP_FONTFACE_STRETCH_SEMI_EXPANDED, + SP_FONTFACE_STRETCH_EXPANDED, + SP_FONTFACE_STRETCH_EXTRA_EXPANDED, + SP_FONTFACE_STRETCH_ULTRA_EXPANDED }; -enum FontFaceUnicodeRangeType{ - FONTFACE_UNICODERANGE_FIXME_HERE, +enum FontFaceUnicodeRangeType +{ + FONTFACE_UNICODERANGE_FIXME_HERE, }; -class SPFontFace : public SPObject { +class SPFontFace : public SPObject +{ public: - SPFontFace(); - ~SPFontFace() override; + SPFontFace(); + ~SPFontFace() override; - char* font_family; + char *font_family; std::vector font_style; std::vector font_variant; std::vector font_weight; std::vector font_stretch; - char* font_size; + char *font_size; std::vector unicode_range; double units_per_em; std::vector panose_1; @@ -90,8 +96,8 @@ public: double accent_height; double ascent; double descent; - char* widths; - char* bbox; + char *widths; + char *bbox; double ideographic; double alphabetic; double mathematical; @@ -108,17 +114,17 @@ public: double overline_thickness; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; - void set(SPAttr key, const char* value) override; + void set(SPAttr key, const char *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif //#ifndef __SP_FONTFACE_H__ diff --git a/src/object/sp-font.cpp b/src/object/sp-font.cpp index a8a7d5c8ca3c02a08fbc1c60d1579d18113d0dd7..6f2c7e9fa8e7433f4efaaf553a7afd45c533cdae 100644 --- a/src/object/sp-font.cpp +++ b/src/object/sp-font.cpp @@ -11,22 +11,24 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "xml/repr.h" -#include "attributes.h" #include "sp-font.h" -#include "document.h" +#include "attributes.h" #include "display/nr-svgfonts.h" +#include "document.h" +#include "xml/repr.h" - -//I think we should have extra stuff here and in the set method in order to set default value as specified at http://www.w3.org/TR/SVG/fonts.html +// I think we should have extra stuff here and in the set method in order to set default value as specified at +// http://www.w3.org/TR/SVG/fonts.html // TODO determine better values and/or make these dynamic: double FNT_DEFAULT_ADV = 1024; // TODO determine proper default double FNT_DEFAULT_ASCENT = 768; // TODO determine proper default double FNT_UNITS_PER_EM = 1024; // TODO determine proper default -SPFont::SPFont() : SPObject() { +SPFont::SPFont() + : SPObject() +{ this->horiz_origin_x = 0; this->horiz_origin_y = 0; this->horiz_adv_x = FNT_DEFAULT_ADV; @@ -37,109 +39,107 @@ SPFont::SPFont() : SPObject() { SPFont::~SPFont() = default; -void SPFont::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPObject::build(document, repr); +void SPFont::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPObject::build(document, repr); - this->readAttr(SPAttr::HORIZ_ORIGIN_X); - this->readAttr(SPAttr::HORIZ_ORIGIN_Y); - this->readAttr(SPAttr::HORIZ_ADV_X); - this->readAttr(SPAttr::VERT_ORIGIN_X); - this->readAttr(SPAttr::VERT_ORIGIN_Y); - this->readAttr(SPAttr::VERT_ADV_Y); + this->readAttr(SPAttr::HORIZ_ORIGIN_X); + this->readAttr(SPAttr::HORIZ_ORIGIN_Y); + this->readAttr(SPAttr::HORIZ_ADV_X); + this->readAttr(SPAttr::VERT_ORIGIN_X); + this->readAttr(SPAttr::VERT_ORIGIN_Y); + this->readAttr(SPAttr::VERT_ADV_Y); - document->addResource("font", this); + document->addResource("font", this); } /** * Callback for child_added event. */ -void SPFont::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { +void SPFont::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ SPObject::child_added(child, ref); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } - /** * Callback for remove_child event. */ -void SPFont::remove_child(Inkscape::XML::Node* child) { +void SPFont::remove_child(Inkscape::XML::Node *child) +{ SPObject::remove_child(child); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } -void SPFont::release() { +void SPFont::release() +{ this->document->removeResource("font", this); SPObject::release(); } -void SPFont::set(SPAttr key, const gchar *value) { +void SPFont::set(SPAttr key, const gchar *value) +{ // TODO these are floating point, so some epsilon comparison would be good switch (key) { - case SPAttr::HORIZ_ORIGIN_X: - { + case SPAttr::HORIZ_ORIGIN_X: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - if (number != this->horiz_origin_x){ + if (number != this->horiz_origin_x) { this->horiz_origin_x = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::HORIZ_ORIGIN_Y: - { + case SPAttr::HORIZ_ORIGIN_Y: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - if (number != this->horiz_origin_y){ + if (number != this->horiz_origin_y) { this->horiz_origin_y = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::HORIZ_ADV_X: - { + case SPAttr::HORIZ_ADV_X: { double number = value ? g_ascii_strtod(value, nullptr) : FNT_DEFAULT_ADV; - if (number != this->horiz_adv_x){ + if (number != this->horiz_adv_x) { this->horiz_adv_x = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::VERT_ORIGIN_X: - { + case SPAttr::VERT_ORIGIN_X: { double number = value ? g_ascii_strtod(value, nullptr) : FNT_DEFAULT_ADV / 2.0; - if (number != this->vert_origin_x){ + if (number != this->vert_origin_x) { this->vert_origin_x = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::VERT_ORIGIN_Y: - { + case SPAttr::VERT_ORIGIN_Y: { double number = value ? g_ascii_strtod(value, nullptr) : FNT_DEFAULT_ASCENT; - if (number != this->vert_origin_y){ + if (number != this->vert_origin_y) { this->vert_origin_y = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::VERT_ADV_Y: - { + case SPAttr::VERT_ADV_Y: { double number = value ? g_ascii_strtod(value, nullptr) : FNT_UNITS_PER_EM; - if (number != this->vert_adv_y){ + if (number != this->vert_adv_y) { this->vert_adv_y = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } default: - SPObject::set(key, value); + SPObject::set(key, value); break; } } @@ -147,7 +147,8 @@ void SPFont::set(SPAttr key, const gchar *value) { /** * Receives update notifications. */ -void SPFont::update(SPCtx *ctx, guint flags) { +void SPFont::update(SPCtx *ctx, guint flags) +{ if (flags & (SP_OBJECT_MODIFIED_FLAG)) { this->readAttr(SPAttr::HORIZ_ORIGIN_X); this->readAttr(SPAttr::HORIZ_ORIGIN_Y); @@ -160,9 +161,10 @@ void SPFont::update(SPCtx *ctx, guint flags) { SPObject::update(ctx, flags); } -#define COPY_ATTR(rd,rs,key) (rd)->setAttribute((key), rs->attribute(key)); +#define COPY_ATTR(rd, rs, key) (rd)->setAttribute((key), rs->attribute(key)); -Inkscape::XML::Node* SPFont::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPFont::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:font"); } @@ -175,7 +177,7 @@ Inkscape::XML::Node* SPFont::write(Inkscape::XML::Document *xml_doc, Inkscape::X sp_repr_set_svg_double(repr, "vert-adv-y", this->vert_adv_y); if (repr != this->getRepr()) { - // All the below COPY_ATTR functions are directly using + // All the below COPY_ATTR functions are directly using // the XML Tree while they shouldn't COPY_ATTR(repr, this->getRepr(), "horiz-origin-x"); COPY_ATTR(repr, this->getRepr(), "horiz-origin-y"); diff --git a/src/object/sp-font.h b/src/object/sp-font.h index 8a3d181a98e229a8a24af076c7ae8ddd19870aa6..53a748344d5ccd21b325f51e076ee25111b3a142 100644 --- a/src/object/sp-font.h +++ b/src/object/sp-font.h @@ -15,13 +15,14 @@ #include "sp-object.h" -#define SP_FONT(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_FONT(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_FONT(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_FONT(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPFont : public SPObject { +class SPFont : public SPObject +{ public: - SPFont(); - ~SPFont() override; + SPFont(); + ~SPFont() override; double horiz_origin_x; double horiz_origin_y; @@ -31,17 +32,17 @@ public: double vert_adv_y; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif //#ifndef SP_FONT_H_SEEN diff --git a/src/object/sp-glyph-kerning.cpp b/src/object/sp-glyph-kerning.cpp index f92477368c9e6d11c3a5e2667a8b9a91da48de13..c7ac41ce34fd1afab5b2ba20c4b2c3edca406836 100644 --- a/src/object/sp-glyph-kerning.cpp +++ b/src/object/sp-glyph-kerning.cpp @@ -12,24 +12,23 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "xml/repr.h" -#include "attributes.h" #include "sp-glyph-kerning.h" -#include "document.h" #include +#include "attributes.h" +#include "document.h" +#include "xml/repr.h" -SPGlyphKerning::SPGlyphKerning() +SPGlyphKerning::SPGlyphKerning() : SPObject() -//TODO: correct these values: + // TODO: correct these values: , u1(nullptr) , g1(nullptr) , u2(nullptr) , g2(nullptr) , k(0) -{ -} +{} void SPGlyphKerning::build(SPDocument *document, Inkscape::XML::Node *repr) { @@ -47,7 +46,7 @@ void SPGlyphKerning::release() SPObject::release(); } -GlyphNames::GlyphNames(const gchar* value) +GlyphNames::GlyphNames(const gchar *value) { names = value ? g_strdup(value) : nullptr; } @@ -55,85 +54,79 @@ GlyphNames::GlyphNames(const gchar* value) GlyphNames::~GlyphNames() { if (names) { - g_free(names); + g_free(names); } } -bool GlyphNames::contains(const char* name) +bool GlyphNames::contains(const char *name) { if (!(this->names) || !name) { - return false; + return false; } - + std::istringstream is(this->names); std::string str; std::string s(name); - + while (is >> str) { if (str == s) { return true; } } - + return false; } void SPGlyphKerning::set(SPAttr key, const gchar *value) { switch (key) { - case SPAttr::U1: - { + case SPAttr::U1: { if (this->u1) { delete this->u1; } - + this->u1 = new UnicodeRange(value); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } - case SPAttr::U2: - { + case SPAttr::U2: { if (this->u2) { delete this->u2; } - + this->u2 = new UnicodeRange(value); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } - case SPAttr::G1: - { + case SPAttr::G1: { if (this->g1) { delete this->g1; } - + this->g1 = new GlyphNames(value); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } - case SPAttr::G2: - { + case SPAttr::G2: { if (this->g2) { delete this->g2; } - + this->g2 = new GlyphNames(value); this->requestModified(SP_OBJECT_MODIFIED_FLAG); - break; + break; } - case SPAttr::K: - { + case SPAttr::K: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->k){ + + if (number != this->k) { this->k = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - default: - { - SPObject::set(key, value); + default: { + SPObject::set(key, value); break; } } @@ -155,9 +148,9 @@ void SPGlyphKerning::update(SPCtx *ctx, guint flags) SPObject::update(ctx, flags); } -#define COPY_ATTR(rd,rs,key) (rd)->setAttribute((key), rs->attribute(key)); +#define COPY_ATTR(rd, rs, key) (rd)->setAttribute((key), rs->attribute(key)); -Inkscape::XML::Node* SPGlyphKerning::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +Inkscape::XML::Node *SPGlyphKerning::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:glyphkerning"); // fix this! diff --git a/src/object/sp-glyph-kerning.h b/src/object/sp-glyph-kerning.h index cf9aa0342808df818feb02e7425726d7a4588e93..7de2d913debec804f2a22869ba09c4e2449c4d6a 100644 --- a/src/object/sp-glyph-kerning.h +++ b/src/object/sp-glyph-kerning.h @@ -16,48 +16,53 @@ #include "sp-object.h" #include "unicoderange.h" -#define SP_HKERN(obj) (dynamic_cast(obj)) -#define SP_IS_HKERN(obj) (dynamic_cast(obj) != NULL) +#define SP_HKERN(obj) (dynamic_cast(obj)) +#define SP_IS_HKERN(obj) (dynamic_cast(obj) != NULL) -#define SP_VKERN(obj) (dynamic_cast(obj)) -#define SP_IS_VKERN(obj) (dynamic_cast(obj) != NULL) +#define SP_VKERN(obj) (dynamic_cast(obj)) +#define SP_IS_VKERN(obj) (dynamic_cast(obj) != NULL) // CPPIFY: These casting macros are buggy, as Vkern and Hkern aren't "real" classes. -class GlyphNames { -public: - GlyphNames(char const* value); +class GlyphNames +{ +public: + GlyphNames(char const *value); ~GlyphNames(); - bool contains(char const* name); + bool contains(char const *name); + private: - char* names; + char *names; }; -class SPGlyphKerning : public SPObject { +class SPGlyphKerning : public SPObject +{ public: SPGlyphKerning(); ~SPGlyphKerning() override = default; // FIXME encapsulation - UnicodeRange* u1; - GlyphNames* g1; - UnicodeRange* u2; - GlyphNames* g2; + UnicodeRange *u1; + GlyphNames *g1; + UnicodeRange *u2; + GlyphNames *g2; double k; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; void release() override; - void set(SPAttr key, char const* value) override; - void update(SPCtx* ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + void set(SPAttr key, char const *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; -class SPHkern : public SPGlyphKerning { +class SPHkern : public SPGlyphKerning +{ ~SPHkern() override = default; }; -class SPVkern : public SPGlyphKerning { +class SPVkern : public SPGlyphKerning +{ ~SPVkern() override = default; }; diff --git a/src/object/sp-glyph.cpp b/src/object/sp-glyph.cpp index 3a87d41206c864e4712ce469ed56d48947bbbcd3..8bf754bf63cdc2b5f20e2f3688963dcc8828e575 100644 --- a/src/object/sp-glyph.cpp +++ b/src/object/sp-glyph.cpp @@ -14,14 +14,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "xml/repr.h" -#include "attributes.h" #include "sp-glyph.h" + +#include "attributes.h" #include "document.h" +#include "xml/repr.h" SPGlyph::SPGlyph() - : SPObject() -//TODO: correct these values: + : SPObject() + // TODO: correct these values: , d(nullptr) , orientation(GLYPH_ORIENTATION_BOTH) , arabic_form(GLYPH_ARABIC_FORM_INITIAL) @@ -30,8 +31,7 @@ SPGlyph::SPGlyph() , vert_origin_x(0) , vert_origin_y(0) , vert_adv_y(0) -{ -} +{} void SPGlyph::build(SPDocument *document, Inkscape::XML::Node *repr) { @@ -49,47 +49,49 @@ void SPGlyph::build(SPDocument *document, Inkscape::XML::Node *repr) this->readAttr(SPAttr::VERT_ADV_Y); } -void SPGlyph::release() { +void SPGlyph::release() +{ SPObject::release(); } -static glyphArabicForm sp_glyph_read_arabic_form(gchar const *value){ +static glyphArabicForm sp_glyph_read_arabic_form(gchar const *value) +{ if (!value) { - return GLYPH_ARABIC_FORM_INITIAL; //TODO: verify which is the default default (for me, the spec is not clear) + return GLYPH_ARABIC_FORM_INITIAL; // TODO: verify which is the default default (for me, the spec is not clear) } - - switch(value[0]){ + + switch (value[0]) { case 'i': if (strncmp(value, "initial", 7) == 0) { - return GLYPH_ARABIC_FORM_INITIAL; + return GLYPH_ARABIC_FORM_INITIAL; } - + if (strncmp(value, "isolated", 8) == 0) { - return GLYPH_ARABIC_FORM_ISOLATED; + return GLYPH_ARABIC_FORM_ISOLATED; } break; case 'm': if (strncmp(value, "medial", 6) == 0) { - return GLYPH_ARABIC_FORM_MEDIAL; + return GLYPH_ARABIC_FORM_MEDIAL; } break; case 't': if (strncmp(value, "terminal", 8) == 0) { - return GLYPH_ARABIC_FORM_TERMINAL; + return GLYPH_ARABIC_FORM_TERMINAL; } break; } - - return GLYPH_ARABIC_FORM_INITIAL; //TODO: VERIFY DEFAULT! + + return GLYPH_ARABIC_FORM_INITIAL; // TODO: VERIFY DEFAULT! } static glyphOrientation sp_glyph_read_orientation(gchar const *value) { if (!value) { - return GLYPH_ORIENTATION_BOTH; + return GLYPH_ORIENTATION_BOTH; } - - switch(value[0]){ + + switch (value[0]) { case 'h': return GLYPH_ORIENTATION_HORIZONTAL; break; @@ -97,119 +99,108 @@ static glyphOrientation sp_glyph_read_orientation(gchar const *value) return GLYPH_ORIENTATION_VERTICAL; break; } - -//ERROR? TODO: VERIFY PROPER ERROR HANDLING + + // ERROR? TODO: VERIFY PROPER ERROR HANDLING return GLYPH_ORIENTATION_BOTH; } void SPGlyph::set(SPAttr key, const gchar *value) { switch (key) { - case SPAttr::UNICODE: - { + case SPAttr::UNICODE: { this->unicode.clear(); - + if (value) { - this->unicode.append(value); + this->unicode.append(value); } - + this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } - case SPAttr::GLYPH_NAME: - { + case SPAttr::GLYPH_NAME: { this->glyph_name.clear(); - + if (value) { - this->glyph_name.append(value); + this->glyph_name.append(value); } - + this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } - case SPAttr::D: - { + case SPAttr::D: { if (this->d) { - g_free(this->d); + g_free(this->d); } - + this->d = g_strdup(value); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } - case SPAttr::ORIENTATION: - { + case SPAttr::ORIENTATION: { glyphOrientation orient = sp_glyph_read_orientation(value); - - if (this->orientation != orient){ + + if (this->orientation != orient) { this->orientation = orient; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::ARABIC_FORM: - { + case SPAttr::ARABIC_FORM: { glyphArabicForm form = sp_glyph_read_arabic_form(value); - - if (this->arabic_form != form){ + + if (this->arabic_form != form) { this->arabic_form = form; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::LANG: - { + case SPAttr::LANG: { if (this->lang) { - g_free(this->lang); + g_free(this->lang); } - + this->lang = g_strdup(value); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } - case SPAttr::HORIZ_ADV_X: - { + case SPAttr::HORIZ_ADV_X: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->horiz_adv_x){ + + if (number != this->horiz_adv_x) { this->horiz_adv_x = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::VERT_ORIGIN_X: - { + case SPAttr::VERT_ORIGIN_X: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->vert_origin_x){ + + if (number != this->vert_origin_x) { this->vert_origin_x = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::VERT_ORIGIN_Y: - { + case SPAttr::VERT_ORIGIN_Y: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->vert_origin_y){ + + if (number != this->vert_origin_y) { this->vert_origin_y = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::VERT_ADV_Y: - { + case SPAttr::VERT_ADV_Y: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - - if (number != this->vert_adv_y){ + + if (number != this->vert_adv_y) { this->vert_adv_y = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - default: - { - SPObject::set(key, value); + default: { + SPObject::set(key, value); break; } } @@ -237,9 +228,9 @@ void SPGlyph::update(SPCtx *ctx, guint flags) SPObject::update(ctx, flags); } -#define COPY_ATTR(rd,rs,key) (rd)->setAttribute((key), rs->attribute(key)); +#define COPY_ATTR(rd, rs, key) (rd)->setAttribute((key), rs->attribute(key)); -Inkscape::XML::Node* SPGlyph::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +Inkscape::XML::Node *SPGlyph::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:glyph"); diff --git a/src/object/sp-glyph.h b/src/object/sp-glyph.h index 3d470fd7d57631b7b504436b5300dd5e859cb87b..29ec82ee8168d84225037eed40ac488c2fcc3396 100644 --- a/src/object/sp-glyph.h +++ b/src/object/sp-glyph.h @@ -13,17 +13,19 @@ #include "sp-object.h" -#define SP_GLYPH(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_GLYPH(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_GLYPH(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_GLYPH(obj) (dynamic_cast((SPObject *)obj) != NULL) -enum glyphArabicForm { +enum glyphArabicForm +{ GLYPH_ARABIC_FORM_INITIAL, GLYPH_ARABIC_FORM_MEDIAL, GLYPH_ARABIC_FORM_TERMINAL, GLYPH_ARABIC_FORM_ISOLATED, }; -enum glyphOrientation { +enum glyphOrientation +{ GLYPH_ORIENTATION_HORIZONTAL, GLYPH_ORIENTATION_VERTICAL, GLYPH_ORIENTATION_BOTH @@ -33,7 +35,8 @@ enum glyphOrientation { * SVG element */ -class SPGlyph : public SPObject { +class SPGlyph : public SPObject +{ public: SPGlyph(); ~SPGlyph() override = default; @@ -41,22 +44,21 @@ public: // FIXME encapsulation Glib::ustring unicode; Glib::ustring glyph_name; - char* d; + char *d; glyphOrientation orientation; glyphArabicForm arabic_form; - char* lang; + char *lang; double horiz_adv_x; double vert_origin_x; double vert_origin_y; double vert_adv_y; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; void release() override; - void set(SPAttr key, const char* value) override; - void update(SPCtx* ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; - + void set(SPAttr key, const char *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif // !SEEN_SP_GLYPH_H diff --git a/src/object/sp-gradient-reference.cpp b/src/object/sp-gradient-reference.cpp index 95bd594de74ff86c02978dc54229fea560d16e19..490553c1d75dad650ed68748562aaff95a4cb545 100644 --- a/src/object/sp-gradient-reference.cpp +++ b/src/object/sp-gradient-reference.cpp @@ -8,17 +8,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "sp-gradient-reference.h" + #include "sp-gradient.h" -bool -SPGradientReference::_acceptObject(SPObject *obj) const +bool SPGradientReference::_acceptObject(SPObject *obj) const { return SP_IS_GRADIENT(obj) && URIReference::_acceptObject(obj); /* effic: Don't bother making this an inline function: _acceptObject is a virtual function, typically called from a context where the runtime type is not known at compile time. */ } - /* Local Variables: mode:c++ diff --git a/src/object/sp-gradient-reference.h b/src/object/sp-gradient-reference.h index 925d559643c0f0ba0670cc7b6aba3972f44c4b44..97c1b1ed927d95443e1cc32ecdc8b3072dab6b0b 100644 --- a/src/object/sp-gradient-reference.h +++ b/src/object/sp-gradient-reference.h @@ -15,19 +15,19 @@ class SPGradient; class SPObject; -class SPGradientReference : public Inkscape::URIReference { +class SPGradientReference : public Inkscape::URIReference +{ public: - SPGradientReference(SPObject *obj) : URIReference(obj) {} + SPGradientReference(SPObject *obj) + : URIReference(obj) + {} - SPGradient *getObject() const { - return reinterpret_cast(URIReference::getObject()); - } + SPGradient *getObject() const { return reinterpret_cast(URIReference::getObject()); } protected: bool _acceptObject(SPObject *obj) const override; }; - #endif /* !SEEN_SP_GRADIENT_REFERENCE_H */ /* diff --git a/src/object/sp-gradient-spread.h b/src/object/sp-gradient-spread.h index 47ceee52bcda7554bdf4c8d6e9ff49c1702274ea..df601c0ea490f3ceb1b65cfd8bf42083245c7ca2 100644 --- a/src/object/sp-gradient-spread.h +++ b/src/object/sp-gradient-spread.h @@ -10,14 +10,14 @@ #ifndef SEEN_SP_GRADIENT_SPREAD_H #define SEEN_SP_GRADIENT_SPREAD_H -enum SPGradientSpread { +enum SPGradientSpread +{ SP_GRADIENT_SPREAD_PAD, SP_GRADIENT_SPREAD_REFLECT, SP_GRADIENT_SPREAD_REPEAT, SP_GRADIENT_SPREAD_UNDEFINED = INT_MAX }; - #endif /* !SEEN_SP_GRADIENT_SPREAD_H */ /* diff --git a/src/object/sp-gradient-units.h b/src/object/sp-gradient-units.h index 1a4335dc0597b570fd6c5b9ee7c346e8281e37c5..66d934b09eec88736be0745e6e2497f508ee820a 100644 --- a/src/object/sp-gradient-units.h +++ b/src/object/sp-gradient-units.h @@ -10,12 +10,12 @@ #ifndef SEEN_SP_GRADIENT_UNITS_H #define SEEN_SP_GRADIENT_UNITS_H -enum SPGradientUnits { +enum SPGradientUnits +{ SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX, SP_GRADIENT_UNITS_USERSPACEONUSE }; - #endif /* !SEEN_SP_GRADIENT_UNITS_H */ /* diff --git a/src/object/sp-gradient-vector.h b/src/object/sp-gradient-vector.h index 82721aa00c12b689d0e09f744feeaf61dd9ca39c..77aade9dd4b39dc3fac0ab540342dd553a467721 100644 --- a/src/object/sp-gradient-vector.h +++ b/src/object/sp-gradient-vector.h @@ -11,6 +11,7 @@ #define SEEN_SP_GRADIENT_VECTOR_H #include + #include "color.h" /** @@ -21,7 +22,8 @@ * property value of the gradient where currentColor appears, so we interpret currentColor before * copying from SPStop to SPGradientStop. */ -struct SPGradientStop { +struct SPGradientStop +{ double offset; SPColor color; float opacity; @@ -30,12 +32,12 @@ struct SPGradientStop { /** * The effective gradient vector, after copying stops from the referenced gradient if necessary. */ -struct SPGradientVector { +struct SPGradientVector +{ bool built; std::vector stops; }; - #endif /* !SEEN_SP_GRADIENT_VECTOR_H */ /* diff --git a/src/object/sp-gradient.cpp b/src/object/sp-gradient.cpp index 0236d80c478722ae7e6ae05d77c672a9b8d15939..e9a2a7e6209712e754a5677b9a568644df93b9e6 100644 --- a/src/object/sp-gradient.cpp +++ b/src/object/sp-gradient.cpp @@ -27,33 +27,27 @@ #include "sp-gradient.h" -#include -#include - #include <2geom/transforms.h> - #include - -#include +#include #include +#include +#include #include "attributes.h" #include "bad-uri-exception.h" +#include "display/cairo-utils.h" #include "document.h" #include "gradient-chemistry.h" - #include "sp-gradient-reference.h" #include "sp-linear-gradient.h" -#include "sp-radial-gradient.h" #include "sp-mesh-gradient.h" -#include "sp-mesh-row.h" #include "sp-mesh-patch.h" +#include "sp-mesh-row.h" +#include "sp-radial-gradient.h" #include "sp-stop.h" - -#include "display/cairo-utils.h" - -#include "svg/svg.h" #include "svg/css-ostringstream.h" +#include "svg/svg.h" bool SPGradient::hasStops() const { @@ -85,18 +79,17 @@ SPGradientSpread SPGradient::getSpread() const return spread; } -void SPGradient::setSwatch( bool swatch ) +void SPGradient::setSwatch(bool swatch) { - if ( swatch != isSwatch() ) { + if (swatch != isSwatch()) { this->swatch = swatch; // to make isSolid() work, this happens first - gchar const* paintVal = swatch ? (isSolid() ? "solid" : "gradient") : nullptr; - setAttribute( "inkscape:swatch", paintVal); + gchar const *paintVal = swatch ? (isSolid() ? "solid" : "gradient") : nullptr; + setAttribute("inkscape:swatch", paintVal); - requestModified( SP_OBJECT_MODIFIED_FLAG ); + requestModified(SP_OBJECT_MODIFIED_FLAG); } } - /** * return true if this gradient is "equivalent" to that gradient. * Equivalent meaning they have the same stop count, same stop colors and same stop opacity @@ -104,42 +97,50 @@ void SPGradient::setSwatch( bool swatch ) */ bool SPGradient::isEquivalent(SPGradient *that) { - //TODO Make this work for mesh gradients + // TODO Make this work for mesh gradients bool status = false; - - while(true){ // not really a loop, used to avoid deep nesting or multiple exit points from function - if (this->getStopCount() != that->getStopCount()) { break; } - if (this->hasStops() != that->hasStops()) { break; } - if (!this->getVector() || !that->getVector()) { break; } - if (this->isSwatch() != that->isSwatch()) { break; } - if ( this->isSwatch() ){ - // drop down to check stops. + + while (true) { // not really a loop, used to avoid deep nesting or multiple exit points from function + if (this->getStopCount() != that->getStopCount()) { + break; + } + if (this->hasStops() != that->hasStops()) { + break; } - else if ( - (SP_IS_LINEARGRADIENT(this) && SP_IS_LINEARGRADIENT(that)) || - (SP_IS_RADIALGRADIENT(this) && SP_IS_RADIALGRADIENT(that)) || - (SP_IS_MESHGRADIENT(this) && SP_IS_MESHGRADIENT(that))) { - if(!this->isAligned(that))break; + if (!this->getVector() || !that->getVector()) { + break; + } + if (this->isSwatch() != that->isSwatch()) { + break; } - else { break; } // this should never happen, some unhandled type of gradient + if (this->isSwatch()) { + // drop down to check stops. + } else if ((SP_IS_LINEARGRADIENT(this) && SP_IS_LINEARGRADIENT(that)) || + (SP_IS_RADIALGRADIENT(this) && SP_IS_RADIALGRADIENT(that)) || + (SP_IS_MESHGRADIENT(this) && SP_IS_MESHGRADIENT(that))) { + if (!this->isAligned(that)) + break; + } else { + break; + } // this should never happen, some unhandled type of gradient SPStop *as = this->getVector()->getFirstStop(); SPStop *bs = that->getVector()->getFirstStop(); bool effective = true; while (effective && (as && bs)) { - if (!as->getColor().isClose(bs->getColor(), 0.001) || - as->offset != bs->offset || as->getOpacity() != bs->getOpacity() ) { + if (!as->getColor().isClose(bs->getColor(), 0.001) || as->offset != bs->offset || + as->getOpacity() != bs->getOpacity()) { effective = false; break; - } - else { + } else { as = as->getNextStop(); bs = bs->getNextStop(); } } - if (!effective) break; + if (!effective) + break; status = true; break; @@ -155,67 +156,99 @@ bool SPGradient::isEquivalent(SPGradient *that) bool SPGradient::isAligned(SPGradient *that) { bool status = false; - - /* Some gradients have coordinates/other values specified, some don't. - yes/yes check the coordinates/other values - no/no aligned (because both have all default values) - yes/no not aligned - no/yes not aligned - It is NOT safe to just compare the computed values because if that field has - not been set the computed value could be full of garbage. - - In theory the yes/no and no/yes cases could be aligned if the specified value - matches the default value. - */ - - while(true){ // not really a loop, used to avoid deep nesting or multiple exit points from function - if(this->gradientTransform_set != that->gradientTransform_set) { break; } - if(this->gradientTransform_set && - (this->gradientTransform != that->gradientTransform)) { break; } + + /* Some gradients have coordinates/other values specified, some don't. + yes/yes check the coordinates/other values + no/no aligned (because both have all default values) + yes/no not aligned + no/yes not aligned + It is NOT safe to just compare the computed values because if that field has + not been set the computed value could be full of garbage. + + In theory the yes/no and no/yes cases could be aligned if the specified value + matches the default value. + */ + + while (true) { // not really a loop, used to avoid deep nesting or multiple exit points from function + if (this->gradientTransform_set != that->gradientTransform_set) { + break; + } + if (this->gradientTransform_set && (this->gradientTransform != that->gradientTransform)) { + break; + } if (SP_IS_LINEARGRADIENT(this) && SP_IS_LINEARGRADIENT(that)) { - SPLinearGradient *sg=SP_LINEARGRADIENT(this); - SPLinearGradient *tg=SP_LINEARGRADIENT(that); - - if( sg->x1._set != tg->x1._set) { break; } - if( sg->y1._set != tg->y1._set) { break; } - if( sg->x2._set != tg->x2._set) { break; } - if( sg->y2._set != tg->y2._set) { break; } - if( sg->x1._set && sg->y1._set && sg->x2._set && sg->y2._set) { - if( (sg->x1.computed != tg->x1.computed) || - (sg->y1.computed != tg->y1.computed) || - (sg->x2.computed != tg->x2.computed) || - (sg->y2.computed != tg->y2.computed) ) { break; } - } else if( sg->x1._set || sg->y1._set || sg->x2._set || sg->y2._set) { break; } // some mix of set and not set + SPLinearGradient *sg = SP_LINEARGRADIENT(this); + SPLinearGradient *tg = SP_LINEARGRADIENT(that); + + if (sg->x1._set != tg->x1._set) { + break; + } + if (sg->y1._set != tg->y1._set) { + break; + } + if (sg->x2._set != tg->x2._set) { + break; + } + if (sg->y2._set != tg->y2._set) { + break; + } + if (sg->x1._set && sg->y1._set && sg->x2._set && sg->y2._set) { + if ((sg->x1.computed != tg->x1.computed) || (sg->y1.computed != tg->y1.computed) || + (sg->x2.computed != tg->x2.computed) || (sg->y2.computed != tg->y2.computed)) { + break; + } + } else if (sg->x1._set || sg->y1._set || sg->x2._set || sg->y2._set) { + break; + } // some mix of set and not set // none set? assume aligned and fall through } else if (SP_IS_RADIALGRADIENT(this) && SP_IS_LINEARGRADIENT(that)) { - SPRadialGradient *sg=SP_RADIALGRADIENT(this); - SPRadialGradient *tg=SP_RADIALGRADIENT(that); - - if( sg->cx._set != tg->cx._set) { break; } - if( sg->cy._set != tg->cy._set) { break; } - if( sg->r._set != tg->r._set) { break; } - if( sg->fx._set != tg->fx._set) { break; } - if( sg->fy._set != tg->fy._set) { break; } - if( sg->cx._set && sg->cy._set && sg->fx._set && sg->fy._set && sg->r._set) { - if( (sg->cx.computed != tg->cx.computed) || - (sg->cy.computed != tg->cy.computed) || - (sg->r.computed != tg->r.computed ) || - (sg->fx.computed != tg->fx.computed) || - (sg->fy.computed != tg->fy.computed) ) { break; } - } else if( sg->cx._set || sg->cy._set || sg->fx._set || sg->fy._set || sg->r._set ) { break; } // some mix of set and not set + SPRadialGradient *sg = SP_RADIALGRADIENT(this); + SPRadialGradient *tg = SP_RADIALGRADIENT(that); + + if (sg->cx._set != tg->cx._set) { + break; + } + if (sg->cy._set != tg->cy._set) { + break; + } + if (sg->r._set != tg->r._set) { + break; + } + if (sg->fx._set != tg->fx._set) { + break; + } + if (sg->fy._set != tg->fy._set) { + break; + } + if (sg->cx._set && sg->cy._set && sg->fx._set && sg->fy._set && sg->r._set) { + if ((sg->cx.computed != tg->cx.computed) || (sg->cy.computed != tg->cy.computed) || + (sg->r.computed != tg->r.computed) || (sg->fx.computed != tg->fx.computed) || + (sg->fy.computed != tg->fy.computed)) { + break; + } + } else if (sg->cx._set || sg->cy._set || sg->fx._set || sg->fy._set || sg->r._set) { + break; + } // some mix of set and not set // none set? assume aligned and fall through } else if (SP_IS_MESHGRADIENT(this) && SP_IS_MESHGRADIENT(that)) { - SPMeshGradient *sg=SP_MESHGRADIENT(this); - SPMeshGradient *tg=SP_MESHGRADIENT(that); - - if( sg->x._set != !tg->x._set) { break; } - if( sg->y._set != !tg->y._set) { break; } - if( sg->x._set && sg->y._set) { - if( (sg->x.computed != tg->x.computed) || - (sg->y.computed != tg->y.computed) ) { break; } - } else if( sg->x._set || sg->y._set) { break; } // some mix of set and not set - // none set? assume aligned and fall through - } else { + SPMeshGradient *sg = SP_MESHGRADIENT(this); + SPMeshGradient *tg = SP_MESHGRADIENT(that); + + if (sg->x._set != !tg->x._set) { + break; + } + if (sg->y._set != !tg->y._set) { + break; + } + if (sg->x._set && sg->y._set) { + if ((sg->x.computed != tg->x.computed) || (sg->y.computed != tg->y.computed)) { + break; + } + } else if (sg->x._set || sg->y._set) { + break; + } // some mix of set and not set + // none set? assume aligned and fall through + } else { break; } status = true; @@ -227,12 +260,14 @@ bool SPGradient::isAligned(SPGradient *that) /* * Gradient */ -SPGradient::SPGradient() : SPPaintServer(), units(), - spread(), - ref(nullptr), - state(2), - vector() { - +SPGradient::SPGradient() + : SPPaintServer() + , units() + , spread() + , ref(nullptr) + , state(2) + , vector() +{ this->ref = new SPGradientReference(this); this->ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(SPGradient::gradientRefChanged), this)); @@ -266,19 +301,19 @@ SPGradient::~SPGradient() = default; void SPGradient::build(SPDocument *document, Inkscape::XML::Node *repr) { // Work-around in case a swatch had been marked for immediate collection: - if ( repr->attribute("inkscape:swatch") && repr->attribute("inkscape:collect") ) { + if (repr->attribute("inkscape:swatch") && repr->attribute("inkscape:collect")) { repr->removeAttribute("inkscape:collect"); } SPPaintServer::build(document, repr); - for (auto& ochild: children) { + for (auto &ochild : children) { if (SP_IS_STOP(&ochild)) { this->has_stops = TRUE; break; } if (SP_IS_MESHROW(&ochild)) { - for (auto& ochild2: ochild.children) { + for (auto &ochild2 : ochild.children) { if (SP_IS_MESHPATCH(&ochild2)) { this->has_patches = TRUE; break; @@ -305,7 +340,6 @@ void SPGradient::build(SPDocument *document, Inkscape::XML::Node *repr) */ void SPGradient::release() { - #ifdef SP_GRADIENT_VERBOSE g_print("Releasing this %s\n", this->getId()); #endif @@ -322,7 +356,7 @@ void SPGradient::release() this->ref = nullptr; } - //this->modified_connection.~connection(); + // this->modified_connection.~connection(); SPPaintServer::release(); } @@ -334,8 +368,8 @@ void SPGradient::set(SPAttr key, gchar const *value) { #ifdef OBJECT_TRACE std::stringstream temp; - temp << "SPGradient::set: " << key << " " << (value?value:"null"); - objectTrace( temp.str() ); + temp << "SPGradient::set: " << key << " " << (value ? value : "null"); + objectTrace(temp.str()); #endif switch (key) { @@ -400,8 +434,7 @@ void SPGradient::set(SPAttr key, gchar const *value) } break; - case SPAttr::INKSCAPE_SWATCH: - { + case SPAttr::INKSCAPE_SWATCH: { bool newVal = (value != nullptr); bool modified = false; @@ -412,10 +445,10 @@ void SPGradient::set(SPAttr key, gchar const *value) if (newVal) { // Might need to flip solid/gradient - Glib::ustring paintVal = ( this->hasStops() && (this->getStopCount() == 0) ) ? "solid" : "gradient"; + Glib::ustring paintVal = (this->hasStops() && (this->getStopCount() == 0)) ? "solid" : "gradient"; - if ( paintVal != value ) { - this->setAttribute( "inkscape:swatch", paintVal); + if (paintVal != value) { + this->setAttribute("inkscape:swatch", paintVal); modified = true; } } @@ -423,15 +456,14 @@ void SPGradient::set(SPAttr key, gchar const *value) if (modified) { this->requestModified(SP_OBJECT_MODIFIED_FLAG); } - } - break; + } break; default: SPPaintServer::set(key, value); break; } #ifdef OBJECT_TRACE - objectTrace( "SPGradient::set", false ); + objectTrace("SPGradient::set", false); #endif } @@ -443,10 +475,9 @@ void SPGradient::gradientRefChanged(SPObject *old_ref, SPObject *ref, SPGradient if (old_ref) { gr->modified_connection.disconnect(); } - if ( SP_IS_GRADIENT(ref) - && ref != gr ) - { - gr->modified_connection = ref->connectModified(sigc::bind<2>(sigc::ptr_fun(&SPGradient::gradientRefModified), gr)); + if (SP_IS_GRADIENT(ref) && ref != gr) { + gr->modified_connection = + ref->connectModified(sigc::bind<2>(sigc::ptr_fun(&SPGradient::gradientRefModified), gr)); } // Per SVG, all unset attributes must be inherited from linked gradient. @@ -474,16 +505,16 @@ void SPGradient::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *re SPPaintServer::child_added(child, ref); SPObject *ochild = this->get_child_by_repr(child); - if ( ochild && SP_IS_STOP(ochild) ) { + if (ochild && SP_IS_STOP(ochild)) { this->has_stops = TRUE; - if ( this->getStopCount() > 0 ) { - gchar const * attr = this->getAttribute("inkscape:swatch"); - if ( attr && strcmp(attr, "gradient") ) { - this->setAttribute( "inkscape:swatch", "gradient" ); + if (this->getStopCount() > 0) { + gchar const *attr = this->getAttribute("inkscape:swatch"); + if (attr && strcmp(attr, "gradient")) { + this->setAttribute("inkscape:swatch", "gradient"); } } } - if ( ochild && SP_IS_MESHROW(ochild) ) { + if (ochild && SP_IS_MESHROW(ochild)) { this->has_patches = TRUE; } @@ -502,13 +533,13 @@ void SPGradient::remove_child(Inkscape::XML::Node *child) this->has_stops = FALSE; this->has_patches = FALSE; - for (auto& ochild: children) { + for (auto &ochild : children) { if (SP_IS_STOP(&ochild)) { this->has_stops = TRUE; break; } if (SP_IS_MESHROW(&ochild)) { - for (auto& ochild2: ochild.children) { + for (auto &ochild2 : ochild.children) { if (SP_IS_MESHPATCH(&ochild2)) { this->has_patches = TRUE; break; @@ -520,11 +551,11 @@ void SPGradient::remove_child(Inkscape::XML::Node *child) } } - if ( this->getStopCount() == 0 ) { - gchar const * attr = this->getAttribute("inkscape:swatch"); + if (this->getStopCount() == 0) { + gchar const *attr = this->getAttribute("inkscape:swatch"); - if ( attr && strcmp(attr, "solid") ) { - this->setAttribute( "inkscape:swatch", "solid" ); + if (attr && strcmp(attr, "solid")) { + this->setAttribute("inkscape:swatch", "solid"); } } @@ -538,7 +569,7 @@ void SPGradient::remove_child(Inkscape::XML::Node *child) void SPGradient::modified(guint flags) { #ifdef OBJECT_TRACE - objectTrace( "SPGradient::modified" ); + objectTrace("SPGradient::modified"); #endif if (flags & SP_OBJECT_CHILD_MODIFIED_FLAG) { if (SP_IS_MESHGRADIENT(this)) { @@ -556,17 +587,18 @@ void SPGradient::modified(guint flags) } } - if (flags & SP_OBJECT_MODIFIED_FLAG) flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; + if (flags & SP_OBJECT_MODIFIED_FLAG) + flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; flags &= SP_OBJECT_MODIFIED_CASCADE; // FIXME: climb up the ladder of hrefs std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - - for (auto child:l) { + + for (auto child : l) { if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->emitModified(flags); } @@ -574,14 +606,14 @@ void SPGradient::modified(guint flags) } #ifdef OBJECT_TRACE - objectTrace( "SPGradient::modified", false ); + objectTrace("SPGradient::modified", false); #endif } -SPStop* SPGradient::getFirstStop() +SPStop *SPGradient::getFirstStop() { - SPStop* first = nullptr; - for (auto& ochild: children) { + SPStop *first = nullptr; + for (auto &ochild : children) { if (SP_IS_STOP(&ochild)) { first = SP_STOP(&ochild); break; @@ -594,7 +626,8 @@ int SPGradient::getStopCount() const { int count = 0; - for (SPStop *stop = const_cast(this)->getFirstStop(); stop && stop->getNextStop(); stop = stop->getNextStop()) { + for (SPStop *stop = const_cast(this)->getFirstStop(); stop && stop->getNextStop(); + stop = stop->getNextStop()) { count++; } @@ -607,7 +640,7 @@ int SPGradient::getStopCount() const Inkscape::XML::Node *SPGradient::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { #ifdef OBJECT_TRACE - objectTrace( "SPGradient::write" ); + objectTrace("SPGradient::write"); #endif SPPaintServer::write(xml_doc, repr, flags); @@ -615,7 +648,7 @@ Inkscape::XML::Node *SPGradient::write(Inkscape::XML::Document *xml_doc, Inkscap if (flags & SP_OBJECT_WRITE_BUILD) { std::vector l; - for (auto& child: children) { + for (auto &child : children) { Inkscape::XML::Node *crepr = child.updateRepr(xml_doc, nullptr, flags); if (crepr) { @@ -623,7 +656,7 @@ Inkscape::XML::Node *SPGradient::write(Inkscape::XML::Document *xml_doc, Inkscap } } - for (auto i=l.rbegin();i!=l.rend();++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } @@ -646,7 +679,7 @@ Inkscape::XML::Node *SPGradient::write(Inkscape::XML::Document *xml_doc, Inkscap } if ((flags & SP_OBJECT_WRITE_ALL) || this->gradientTransform_set) { - gchar *c=sp_svg_transform_write(this->gradientTransform); + gchar *c = sp_svg_transform_write(this->gradientTransform); repr->setAttribute("gradientTransform", c); g_free(c); } @@ -668,18 +701,18 @@ Inkscape::XML::Node *SPGradient::write(Inkscape::XML::Document *xml_doc, Inkscap } } - if ( (flags & SP_OBJECT_WRITE_EXT) && this->isSwatch() ) { - if ( this->isSolid() ) { - repr->setAttribute( "inkscape:swatch", "solid" ); + if ((flags & SP_OBJECT_WRITE_EXT) && this->isSwatch()) { + if (this->isSolid()) { + repr->setAttribute("inkscape:swatch", "solid"); } else { - repr->setAttribute( "inkscape:swatch", "gradient" ); + repr->setAttribute("inkscape:swatch", "gradient"); } } else { repr->removeAttribute("inkscape:swatch"); } #ifdef OBJECT_TRACE - objectTrace( "SPGradient::write", false ); + objectTrace("SPGradient::write", false); #endif return repr; } @@ -691,7 +724,7 @@ Inkscape::XML::Node *SPGradient::write(Inkscape::XML::Document *xml_doc, Inkscap */ void SPGradient::ensureVector() { - if ( !vector.built ) { + if (!vector.built) { rebuildVector(); } } @@ -703,8 +736,8 @@ void SPGradient::ensureVector() */ void SPGradient::ensureArray() { - //std::cout << "SPGradient::ensureArray()" << std::endl; - if ( !array.built ) { + // std::cout << "SPGradient::ensureArray()" << std::endl; + if (!array.built) { rebuildArray(); } } @@ -743,8 +776,7 @@ void SPGradient::setSpread(SPGradientSpread spread) * * \pre SP_IS_GRADIENT(src). */ -static SPGradient * -chase_hrefs(SPGradient *const src, bool (*match)(SPGradient const *)) +static SPGradient *chase_hrefs(SPGradient *const src, bool (*match)(SPGradient const *)) { g_return_val_if_fail(SP_IS_GRADIENT(src), NULL); @@ -767,7 +799,7 @@ chase_hrefs(SPGradient *const src, bool (*match)(SPGradient const *)) } do1 = !do1; - if ( p2 == p1 ) { + if (p2 == p1) { /* We've been here before, so return NULL to indicate that no matching gradient found * in the chain. */ return nullptr; @@ -802,16 +834,14 @@ static bool has_spread_set(SPGradient const *gr) /** * True if gradient has units set. */ -static bool -has_units_set(SPGradient const *gr) +static bool has_units_set(SPGradient const *gr) { return gr->isUnitsSet(); } - SPGradient *SPGradient::getVector(bool force_vector) { - SPGradient * src = chase_hrefs(this, has_stopsFN); + SPGradient *src = chase_hrefs(this, has_stopsFN); if (src == nullptr) { src = this; } @@ -824,7 +854,7 @@ SPGradient *SPGradient::getVector(bool force_vector) SPGradient *SPGradient::getArray(bool force_vector) { - SPGradient * src = chase_hrefs(this, has_patchesFN); + SPGradient *src = chase_hrefs(this, has_patchesFN); if (src == nullptr) { src = this; } @@ -839,9 +869,7 @@ SPGradient *SPGradient::getArray(bool force_vector) SPGradientSpread SPGradient::fetchSpread() { SPGradient const *src = chase_hrefs(this, has_spread_set); - return ( src - ? src->spread - : SP_GRADIENT_SPREAD_PAD ); // pad is the default + return (src ? src->spread : SP_GRADIENT_SPREAD_PAD); // pad is the default } /** @@ -852,29 +880,25 @@ SPGradientSpread SPGradient::fetchSpread() SPGradientUnits SPGradient::fetchUnits() { SPGradient const *src = chase_hrefs(this, has_units_set); - return ( src - ? src->units - : SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX ); // bbox is the default + return (src ? src->units : SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX); // bbox is the default } - /** * Clears the gradient's svg:stop children from its repr. */ -void -SPGradient::repr_clear_vector() +void SPGradient::repr_clear_vector() { Inkscape::XML::Node *repr = getRepr(); /* Collect stops from original repr */ std::vector l; - for (Inkscape::XML::Node *child = repr->firstChild() ; child != nullptr; child = child->next() ) { + for (Inkscape::XML::Node *child = repr->firstChild(); child != nullptr; child = child->next()) { if (!strcmp(child->name(), "svg:stop")) { l.push_back(child); } } /* Remove all stops */ - for (auto i=l.rbegin();i!=l.rend();++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { /** \todo * fixme: This should work, unless we make gradient * into generic group. @@ -887,8 +911,7 @@ SPGradient::repr_clear_vector() * Writes the gradient's internal vector (whether from its own stops, or * inherited from refs) into the gradient repr as svg:stop elements. */ -void -SPGradient::repr_write_vector() +void SPGradient::repr_write_vector() { Inkscape::XML::Document *xml_doc = document->getReprDoc(); Inkscape::XML::Node *repr = getRepr(); @@ -896,7 +919,7 @@ SPGradient::repr_write_vector() /* We have to be careful, as vector may be our own, so construct repr list at first */ std::vector l; - for (auto & stop : vector.stops) { + for (auto &stop : vector.stops) { Inkscape::CSSOStringStream os; Inkscape::XML::Node *child = xml_doc->createElement("svg:stop"); sp_repr_set_css_double(child, "offset", stop.offset); @@ -911,17 +934,16 @@ SPGradient::repr_write_vector() repr_clear_vector(); /* And insert new children from list */ - for (auto i=l.rbegin();i!=l.rend();++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { Inkscape::XML::Node *child = *i; repr->addChild(child, nullptr); Inkscape::GC::release(child); } } - -void SPGradient::gradientRefModified(SPObject */*href*/, guint /*flags*/, SPGradient *gradient) +void SPGradient::gradientRefModified(SPObject * /*href*/, guint /*flags*/, SPGradient *gradient) { - if ( gradient->invalidateVector() ) { + if (gradient->invalidateVector()) { gradient->requestModified(SP_OBJECT_MODIFIED_FLAG); // Conditional to avoid causing infinite loop if there's a cycle in the href chain. } @@ -959,9 +981,9 @@ bool SPGradient::invalidateArray() void SPGradient::rebuildVector() { gint len = 0; - for (auto& child: children) { + for (auto &child : children) { if (SP_IS_STOP(&child)) { - len ++; + len++; } } @@ -970,9 +992,9 @@ void SPGradient::rebuildVector() vector.stops.clear(); SPGradient *reffed = ref ? ref->getObject() : nullptr; - if ( !hasStops() && reffed ) { + if (!hasStops() && reffed) { /* Copy vector from referenced gradient */ - vector.built = true; // Prevent infinite recursion. + vector.built = true; // Prevent infinite recursion. reffed->ensureVector(); if (!reffed->vector.stops.empty()) { vector.built = reffed->vector.built; @@ -981,7 +1003,7 @@ void SPGradient::rebuildVector() } } - for (auto& child: children) { + for (auto &child : children) { if (SP_IS_STOP(&child)) { SPStop *stop = SP_STOP(&child); @@ -1017,14 +1039,14 @@ void SPGradient::rebuildVector() { SPGradientStop gstop; gstop.offset = 0.0; - gstop.color.set( 0x00000000 ); + gstop.color.set(0x00000000); gstop.opacity = 0.0; vector.stops.push_back(gstop); } { SPGradientStop gstop; gstop.offset = 1.0; - gstop.color.set( 0x00000000 ); + gstop.color.set(0x00000000); gstop.opacity = 0.0; vector.stops.push_back(gstop); } @@ -1058,87 +1080,69 @@ void SPGradient::rebuildArray() { // std::cout << "SPGradient::rebuildArray()" << std::endl; - if( !SP_IS_MESHGRADIENT(this) ) { - g_warning( "SPGradient::rebuildArray() called for non-mesh gradient" ); + if (!SP_IS_MESHGRADIENT(this)) { + g_warning("SPGradient::rebuildArray() called for non-mesh gradient"); return; } - array.read( SP_MESHGRADIENT( this ) ); + array.read(SP_MESHGRADIENT(this)); has_patches = array.patch_columns() > 0; } -Geom::Affine -SPGradient::get_g2d_matrix(Geom::Affine const &ctm, Geom::Rect const &bbox) const +Geom::Affine SPGradient::get_g2d_matrix(Geom::Affine const &ctm, Geom::Rect const &bbox) const { if (getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) { - return ( Geom::Scale(bbox.dimensions()) - * Geom::Translate(bbox.min()) - * Geom::Affine(ctm) ); + return (Geom::Scale(bbox.dimensions()) * Geom::Translate(bbox.min()) * Geom::Affine(ctm)); } else { return ctm; } } -Geom::Affine -SPGradient::get_gs2d_matrix(Geom::Affine const &ctm, Geom::Rect const &bbox) const +Geom::Affine SPGradient::get_gs2d_matrix(Geom::Affine const &ctm, Geom::Rect const &bbox) const { if (getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) { - return ( gradientTransform - * Geom::Scale(bbox.dimensions()) - * Geom::Translate(bbox.min()) - * Geom::Affine(ctm) ); + return (gradientTransform * Geom::Scale(bbox.dimensions()) * Geom::Translate(bbox.min()) * Geom::Affine(ctm)); } else { return gradientTransform * ctm; } } -void -SPGradient::set_gs2d_matrix(Geom::Affine const &ctm, - Geom::Rect const &bbox, Geom::Affine const &gs2d) +void SPGradient::set_gs2d_matrix(Geom::Affine const &ctm, Geom::Rect const &bbox, Geom::Affine const &gs2d) { gradientTransform = gs2d * ctm.inverse(); - if (getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX ) { - gradientTransform = ( gradientTransform - * Geom::Translate(-bbox.min()) - * Geom::Scale(bbox.dimensions()).inverse() ); + if (getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) { + gradientTransform = + (gradientTransform * Geom::Translate(-bbox.min()) * Geom::Scale(bbox.dimensions()).inverse()); } gradientTransform_set = TRUE; requestModified(SP_OBJECT_MODIFIED_FLAG); } - - - /* CAIRO RENDERING STUFF */ -void -sp_gradient_pattern_common_setup(cairo_pattern_t *cp, - SPGradient *gr, - Geom::OptRect const &bbox, - double opacity) +void sp_gradient_pattern_common_setup(cairo_pattern_t *cp, SPGradient *gr, Geom::OptRect const &bbox, double opacity) { // set spread type switch (gr->getSpread()) { - case SP_GRADIENT_SPREAD_REFLECT: - cairo_pattern_set_extend(cp, CAIRO_EXTEND_REFLECT); - break; - case SP_GRADIENT_SPREAD_REPEAT: - cairo_pattern_set_extend(cp, CAIRO_EXTEND_REPEAT); - break; - case SP_GRADIENT_SPREAD_PAD: - default: - cairo_pattern_set_extend(cp, CAIRO_EXTEND_PAD); - break; + case SP_GRADIENT_SPREAD_REFLECT: + cairo_pattern_set_extend(cp, CAIRO_EXTEND_REFLECT); + break; + case SP_GRADIENT_SPREAD_REPEAT: + cairo_pattern_set_extend(cp, CAIRO_EXTEND_REPEAT); + break; + case SP_GRADIENT_SPREAD_PAD: + default: + cairo_pattern_set_extend(cp, CAIRO_EXTEND_PAD); + break; } // add stops if (!SP_IS_MESHGRADIENT(gr)) { - for (auto & stop : gr->vector.stops) - { + for (auto &stop : gr->vector.stops) { // multiply stop opacity by paint opacity - cairo_pattern_add_color_stop_rgba(cp, stop.offset, - stop.color.v.c[0], stop.color.v.c[1], stop.color.v.c[2], stop.opacity * opacity); + cairo_pattern_add_color_stop_rgba(cp, stop.offset, stop.color.v.c[0], stop.color.v.c[1], stop.color.v.c[2], + stop.opacity * opacity); } } @@ -1151,8 +1155,7 @@ sp_gradient_pattern_common_setup(cairo_pattern_t *cp, ink_cairo_pattern_set_matrix(cp, gs2user.inverse()); } -cairo_pattern_t * -SPGradient::create_preview_pattern(double width) +cairo_pattern_t *SPGradient::create_preview_pattern(double width) { cairo_pattern_t *pat = nullptr; @@ -1161,24 +1164,22 @@ SPGradient::create_preview_pattern(double width) pat = cairo_pattern_create_linear(0, 0, width, 0); - for (auto & stop : vector.stops) - { - cairo_pattern_add_color_stop_rgba(pat, stop.offset, - stop.color.v.c[0], stop.color.v.c[1], stop.color.v.c[2], stop.opacity); + for (auto &stop : vector.stops) { + cairo_pattern_add_color_stop_rgba(pat, stop.offset, stop.color.v.c[0], stop.color.v.c[1], stop.color.v.c[2], + stop.opacity); } } else { - // For the moment, use the top row of nodes for preview. unsigned columns = array.patch_columns(); - double offset = 1.0/double(columns); + double offset = 1.0 / double(columns); pat = cairo_pattern_create_linear(0, 0, width, 0); - for (unsigned i = 0; i < columns+1; ++i) { - SPMeshNode* node = array.node( 0, i*3 ); - cairo_pattern_add_color_stop_rgba(pat, i*offset, - node->color.v.c[0], node->color.v.c[1], node->color.v.c[2], node->opacity); + for (unsigned i = 0; i < columns + 1; ++i) { + SPMeshNode *node = array.node(0, i * 3); + cairo_pattern_add_color_stop_rgba(pat, i * offset, node->color.v.c[0], node->color.v.c[1], + node->color.v.c[2], node->opacity); } } diff --git a/src/object/sp-gradient.h b/src/object/sp-gradient.h index 7d4d41f4f79c7f607890cbea01b639990711a519..8e05c7ecb95c9f8c4931b508de2907af269ff2d4 100644 --- a/src/object/sp-gradient.h +++ b/src/object/sp-gradient.h @@ -21,33 +21,36 @@ #include #include -#include "sp-paint-server.h" #include "sp-gradient-spread.h" #include "sp-gradient-units.h" #include "sp-gradient-vector.h" #include "sp-mesh-array.h" +#include "sp-paint-server.h" class SPGradientReference; class SPStop; -#define SP_GRADIENT(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_GRADIENT(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_GRADIENT(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_GRADIENT(obj) (dynamic_cast((SPObject *)obj) != NULL) -enum SPGradientType { +enum SPGradientType +{ SP_GRADIENT_TYPE_UNKNOWN, SP_GRADIENT_TYPE_LINEAR, SP_GRADIENT_TYPE_RADIAL, SP_GRADIENT_TYPE_MESH }; -enum SPGradientState { +enum SPGradientState +{ SP_GRADIENT_STATE_UNKNOWN, SP_GRADIENT_STATE_VECTOR, SP_GRADIENT_STATE_PRIVATE }; -enum GrPointType { - POINT_LG_BEGIN = 0, //start enum at 0 (for indexing into gr_knot_shapes array for example) +enum GrPointType +{ + POINT_LG_BEGIN = 0, // start enum at 0 (for indexing into gr_knot_shapes array for example) POINT_LG_END, POINT_LG_MID, POINT_RG_CENTER, @@ -66,7 +69,8 @@ enum GrPointType { namespace Inkscape { -enum PaintTarget { +enum PaintTarget +{ FOR_FILL, FOR_STROKE }; @@ -84,17 +88,18 @@ std::vector const &allPaintTargets(); * Implement spread, stops list * \todo fixme: Implement more here (Lauris) */ -class SPGradient : public SPPaintServer { +class SPGradient : public SPPaintServer +{ public: - SPGradient(); - ~SPGradient() override; + SPGradient(); + ~SPGradient() override; private: /** gradientUnits attribute */ SPGradientUnits units; unsigned int units_set : 1; -public: +public: /** gradientTransform attribute */ Geom::Affine gradientTransform; unsigned int gradientTransform_set : 1; @@ -116,7 +121,7 @@ public: /** State in Inkscape gradient system */ unsigned int state; - + /** Linear and Radial Gradients */ /** Composed vector */ @@ -126,7 +131,7 @@ public: bool hasStops() const; - SPStop* getFirstStop(); + SPStop *getFirstStop(); int getStopCount() const; bool isEquivalent(SPGradient *b); @@ -137,35 +142,33 @@ public: /** Composed array (for mesh gradients) */ SPMeshNodeArray array; SPMeshNodeArray array_smoothed; // Smoothed version of array - - bool hasPatches() const; + bool hasPatches() const; /** All Gradients **************/ bool isUnitsSet() const; SPGradientUnits getUnits() const; void setUnits(SPGradientUnits units); - bool isSpreadSet() const; SPGradientSpread getSpread() const; -/** - * Returns private vector of given gradient (the gradient at the end of the href chain which has - * stops), optionally normalizing it. - * - * \pre SP_IS_GRADIENT(gradient). - * \pre There exists a gradient in the chain that has stops. - */ + /** + * Returns private vector of given gradient (the gradient at the end of the href chain which has + * stops), optionally normalizing it. + * + * \pre SP_IS_GRADIENT(gradient). + * \pre There exists a gradient in the chain that has stops. + */ SPGradient *getVector(bool force_private = false); - /** - * Returns private mesh of given gradient (the gradient at the end of the href chain which has - * patches), optionally normalizing it. - */ + /** + * Returns private mesh of given gradient (the gradient at the end of the href chain which has + * patches), optionally normalizing it. + */ SPGradient *getArray(bool force_private = false); - //static GType getType(); + // static GType getType(); /** Forces vector to be built, if not present (i.e. changed) */ void ensureVector(); @@ -193,12 +196,9 @@ public: cairo_pattern_t *create_preview_pattern(double width); /** Transforms to/from gradient position space in given environment */ - Geom::Affine get_g2d_matrix(Geom::Affine const &ctm, - Geom::Rect const &bbox) const; - Geom::Affine get_gs2d_matrix(Geom::Affine const &ctm, - Geom::Rect const &bbox) const; - void set_gs2d_matrix(Geom::Affine const &ctm, Geom::Rect const &bbox, - Geom::Affine const &gs2d); + Geom::Affine get_g2d_matrix(Geom::Affine const &ctm, Geom::Rect const &bbox) const; + Geom::Affine get_gs2d_matrix(Geom::Affine const &ctm, Geom::Rect const &bbox) const; + void set_gs2d_matrix(Geom::Affine const &ctm, Geom::Rect const &bbox, Geom::Affine const &gs2d); private: bool invalidateVector(); @@ -210,7 +210,8 @@ protected: void build(SPDocument *document, Inkscape::XML::Node *repr) override; void release() override; void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; void remove_child(Inkscape::XML::Node *child) override; @@ -218,12 +219,7 @@ protected: void set(SPAttr key, char const *value) override; }; -void -sp_gradient_pattern_common_setup(cairo_pattern_t *cp, - SPGradient *gr, - Geom::OptRect const &bbox, - double opacity); - +void sp_gradient_pattern_common_setup(cairo_pattern_t *cp, SPGradient *gr, Geom::OptRect const &bbox, double opacity); #endif // SEEN_SP_GRADIENT_H diff --git a/src/object/sp-guide.cpp b/src/object/sp-guide.cpp index 486f80ce4dcc8e37836382dcd2d8628e99ef2abd..5c294fe4102e2ec44cec2c24f490de0c0df7e4f3 100644 --- a/src/object/sp-guide.cpp +++ b/src/object/sp-guide.cpp @@ -16,43 +16,38 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-guide.h" + #include #include -#include #include +#include #include "attributes.h" #include "desktop.h" +#include "display/guideline.h" #include "document-undo.h" #include "helper-fns.h" #include "inkscape.h" #include "remove-last.h" -#include "verbs.h" - -#include "sp-guide.h" #include "sp-item-notify-moveto.h" #include "sp-namedview.h" #include "sp-root.h" - -#include "display/guideline.h" - #include "svg/stringstream.h" #include "svg/svg-color.h" #include "svg/svg.h" - #include "ui/widget/canvas.h" - +#include "verbs.h" #include "xml/repr.h" using Inkscape::DocumentUndo; - SPGuide::SPGuide() : SPObject() , label(nullptr) , locked(false) - , normal_to_line(Geom::Point(0.,1.)) - , point_on_line(Geom::Point(0.,0.)) + , normal_to_line(Geom::Point(0., 1.)) + , point_on_line(Geom::Point(0., 0.)) , color(0x0000ff7f) , hicolor(0xff00007f) {} @@ -61,7 +56,7 @@ void SPGuide::setColor(guint32 c) { color = c; - for(auto view : this->views) { + for (auto view : this->views) { sp_guideline_set_color(view, this->color); } } @@ -82,7 +77,7 @@ void SPGuide::build(SPDocument *document, Inkscape::XML::Node *repr) void SPGuide::release() { - for(auto view : this->views) { + for (auto view : this->views) { sp_guideline_delete(view); } this->views.clear(); @@ -95,112 +90,113 @@ void SPGuide::release() SPObject::release(); } -void SPGuide::set(SPAttr key, const gchar *value) { +void SPGuide::set(SPAttr key, const gchar *value) +{ switch (key) { - case SPAttr::INKSCAPE_COLOR: - if (value) { - this->setColor(sp_svg_read_color(value, 0x0000ff00) | 0x7f); - } - break; - case SPAttr::INKSCAPE_LABEL: - // this->label already freed in sp_guideline_set_label (src/display/guideline.cpp) - // see bug #1498444, bug #1469514 - if (value) { - this->label = g_strdup(value); - } else { - this->label = nullptr; - } + case SPAttr::INKSCAPE_COLOR: + if (value) { + this->setColor(sp_svg_read_color(value, 0x0000ff00) | 0x7f); + } + break; + case SPAttr::INKSCAPE_LABEL: + // this->label already freed in sp_guideline_set_label (src/display/guideline.cpp) + // see bug #1498444, bug #1469514 + if (value) { + this->label = g_strdup(value); + } else { + this->label = nullptr; + } - this->set_label(this->label, false); - break; - case SPAttr::INKSCAPE_LOCKED: - if (value) { - this->set_locked(helperfns_read_bool(value, false), false); - } - break; - case SPAttr::ORIENTATION: - { - if (value && !strcmp(value, "horizontal")) { - /* Visual representation of a horizontal line, constrain vertically (y coordinate). */ - this->normal_to_line = Geom::Point(0., 1.); - } else if (value && !strcmp(value, "vertical")) { - this->normal_to_line = Geom::Point(1., 0.); - } else if (value) { - gchar ** strarray = g_strsplit(value, ",", 2); - double newx, newy; - unsigned int success = sp_svg_number_read_d(strarray[0], &newx); - success += sp_svg_number_read_d(strarray[1], &newy); - g_strfreev (strarray); - if (success == 2 && (fabs(newx) > 1e-6 || fabs(newy) > 1e-6)) { - Geom::Point direction(newx, newy); + this->set_label(this->label, false); + break; + case SPAttr::INKSCAPE_LOCKED: + if (value) { + this->set_locked(helperfns_read_bool(value, false), false); + } + break; + case SPAttr::ORIENTATION: { + if (value && !strcmp(value, "horizontal")) { + /* Visual representation of a horizontal line, constrain vertically (y coordinate). */ + this->normal_to_line = Geom::Point(0., 1.); + } else if (value && !strcmp(value, "vertical")) { + this->normal_to_line = Geom::Point(1., 0.); + } else if (value) { + gchar **strarray = g_strsplit(value, ",", 2); + double newx, newy; + unsigned int success = sp_svg_number_read_d(strarray[0], &newx); + success += sp_svg_number_read_d(strarray[1], &newy); + g_strfreev(strarray); + if (success == 2 && (fabs(newx) > 1e-6 || fabs(newy) > 1e-6)) { + Geom::Point direction(newx, newy); + + // stores inverted y-axis coordinates + if (document->is_yaxisdown()) { + direction[Geom::X] *= -1.0; + } - // stores inverted y-axis coordinates - if (document->is_yaxisdown()) { - direction[Geom::X] *= -1.0; + direction.normalize(); + this->normal_to_line = direction; + } else { + // default to vertical line for bad arguments + this->normal_to_line = Geom::Point(1., 0.); } - - direction.normalize(); - this->normal_to_line = direction; } else { // default to vertical line for bad arguments this->normal_to_line = Geom::Point(1., 0.); } - } else { - // default to vertical line for bad arguments - this->normal_to_line = Geom::Point(1., 0.); - } - this->set_normal(this->normal_to_line, false); - } - break; - case SPAttr::POSITION: - { - if (value) { - gchar ** strarray = g_strsplit(value, ",", 2); - double newx, newy; - unsigned int success = sp_svg_number_read_d(strarray[0], &newx); - success += sp_svg_number_read_d(strarray[1], &newy); - g_strfreev (strarray); - if (success == 2) { - // If root viewBox set, interpret guides in terms of viewBox (90/96) - SPRoot *root = document->getRoot(); - if( root->viewBox_set ) { - if(Geom::are_near((root->width.computed * root->viewBox.height()) / (root->viewBox.width() * root->height.computed), 1.0, Geom::EPSILON)) { - // for uniform scaling, try to reduce numerical error - double vbunit2px = (root->width.computed / root->viewBox.width() + root->height.computed / root->viewBox.height())/2.0; - newx = newx * vbunit2px; - newy = newy * vbunit2px; + this->set_normal(this->normal_to_line, false); + } break; + case SPAttr::POSITION: { + if (value) { + gchar **strarray = g_strsplit(value, ",", 2); + double newx, newy; + unsigned int success = sp_svg_number_read_d(strarray[0], &newx); + success += sp_svg_number_read_d(strarray[1], &newy); + g_strfreev(strarray); + if (success == 2) { + // If root viewBox set, interpret guides in terms of viewBox (90/96) + SPRoot *root = document->getRoot(); + if (root->viewBox_set) { + if (Geom::are_near((root->width.computed * root->viewBox.height()) / + (root->viewBox.width() * root->height.computed), + 1.0, Geom::EPSILON)) { + // for uniform scaling, try to reduce numerical error + double vbunit2px = (root->width.computed / root->viewBox.width() + + root->height.computed / root->viewBox.height()) / + 2.0; + newx = newx * vbunit2px; + newy = newy * vbunit2px; + } else { + newx = newx * root->width.computed / root->viewBox.width(); + newy = newy * root->height.computed / root->viewBox.height(); + } + } + this->point_on_line = Geom::Point(newx, newy); + } else if (success == 1) { + // before 0.46 style guideline definition. + const gchar *attr = this->getRepr()->attribute("orientation"); + if (attr && !strcmp(attr, "horizontal")) { + this->point_on_line = Geom::Point(0, newx); } else { - newx = newx * root->width.computed / root->viewBox.width(); - newy = newy * root->height.computed / root->viewBox.height(); + this->point_on_line = Geom::Point(newx, 0); } } - this->point_on_line = Geom::Point(newx, newy); - } else if (success == 1) { - // before 0.46 style guideline definition. - const gchar *attr = this->getRepr()->attribute("orientation"); - if (attr && !strcmp(attr, "horizontal")) { - this->point_on_line = Geom::Point(0, newx); - } else { - this->point_on_line = Geom::Point(newx, 0); - } - } - // stores inverted y-axis coordinates - if (document->is_yaxisdown()) { - this->point_on_line[Geom::Y] = document->getHeight().value("px") - this->point_on_line[Geom::Y]; + // stores inverted y-axis coordinates + if (document->is_yaxisdown()) { + this->point_on_line[Geom::Y] = document->getHeight().value("px") - this->point_on_line[Geom::Y]; + } + } else { + // default to (0,0) for bad arguments + this->point_on_line = Geom::Point(0, 0); } - } else { - // default to (0,0) for bad arguments - this->point_on_line = Geom::Point(0,0); - } - // update position in non-committing way - // fixme: perhaps we need to add an update method instead, and request_update here - this->moveto(this->point_on_line, false); - } - break; - default: - SPObject::set(key, value); - break; + // update position in non-committing way + // fixme: perhaps we need to add an update method instead, and request_update here + this->moveto(this->point_on_line, false); + } break; + default: + SPObject::set(key, value); + break; } } @@ -225,19 +221,22 @@ SPGuide *SPGuide::createSPGuide(SPDocument *doc, Geom::Point const &pt1, Geom::P n[Geom::X] *= -1.0; } - if( root->viewBox_set ) { + if (root->viewBox_set) { // check to see if scaling is uniform - if(Geom::are_near((root->viewBox.width() * root->height.computed) / (root->width.computed * root->viewBox.height()), 1.0, Geom::EPSILON)) { - double px2vbunit = (root->viewBox.width()/root->width.computed + root->viewBox.height()/root->height.computed)/2.0; + if (Geom::are_near((root->viewBox.width() * root->height.computed) / + (root->width.computed * root->viewBox.height()), + 1.0, Geom::EPSILON)) { + double px2vbunit = + (root->viewBox.width() / root->width.computed + root->viewBox.height() / root->height.computed) / 2.0; newx = newx * px2vbunit; newy = newy * px2vbunit; } else { - newx = newx * root->viewBox.width() / root->width.computed; + newx = newx * root->viewBox.width() / root->width.computed; newy = newy * root->viewBox.height() / root->height.computed; } } - sp_repr_set_point(repr, "position", Geom::Point( newx, newy )); + sp_repr_set_point(repr, "position", Geom::Point(newx, newy)); sp_repr_set_point(repr, "orientation", n); SPNamedView *namedview = sp_document_namedview(doc, nullptr); @@ -249,25 +248,28 @@ SPGuide *SPGuide::createSPGuide(SPDocument *doc, Geom::Point const &pt1, Geom::P } Inkscape::GC::release(repr); - SPGuide *guide= SP_GUIDE(doc->getObjectByRepr(repr)); + SPGuide *guide = SP_GUIDE(doc->getObjectByRepr(repr)); return guide; } -SPGuide *SPGuide::duplicate(){ - return SPGuide::createSPGuide(document, point_on_line, Geom::Point(point_on_line[Geom::X] + normal_to_line[Geom::Y],point_on_line[Geom::Y] - normal_to_line[Geom::X])); +SPGuide *SPGuide::duplicate() +{ + return SPGuide::createSPGuide(document, point_on_line, + Geom::Point(point_on_line[Geom::X] + normal_to_line[Geom::Y], + point_on_line[Geom::Y] - normal_to_line[Geom::X])); } -void sp_guide_pt_pairs_to_guides(SPDocument *doc, std::list > &pts) +void sp_guide_pt_pairs_to_guides(SPDocument *doc, std::list> &pts) { - for (auto & pt : pts) { + for (auto &pt : pts) { SPGuide::createSPGuide(doc, pt.first, pt.second); } } void sp_guide_create_guides_around_page(SPDesktop *dt) { - SPDocument *doc=dt->getDocument(); - std::list > pts; + SPDocument *doc = dt->getDocument(); + std::list> pts; Geom::Point A(0, 0); Geom::Point C(doc->getWidth().value("px"), doc->getHeight().value("px")); @@ -286,10 +288,10 @@ void sp_guide_create_guides_around_page(SPDesktop *dt) void sp_guide_delete_all_guides(SPDesktop *dt) { - SPDocument *doc=dt->getDocument(); + SPDocument *doc = dt->getDocument(); std::vector current = doc->getResourceList("guide"); - while (!current.empty()){ - SPGuide* guide = SP_GUIDE(*(current.begin())); + while (!current.empty()) { + SPGuide *guide = SP_GUIDE(*(current.begin())); sp_guide_remove(guide); current = doc->getResourceList("guide"); } @@ -302,7 +304,7 @@ void SPGuide::showSPGuide(SPCanvasGroup *group, GCallback handler) SPCanvasItem *item = sp_guideline_new(group, label, point_on_line, normal_to_line); sp_guideline_set_color(SP_GUIDELINE(item), color); sp_guideline_set_locked(SP_GUIDELINE(item), locked); - + g_signal_connect(G_OBJECT(item), "event", G_CALLBACK(handler), this); views.push_back(SP_GUIDELINE(item)); @@ -310,12 +312,12 @@ void SPGuide::showSPGuide(SPCanvasGroup *group, GCallback handler) void SPGuide::showSPGuide() { - for(std::vector::const_iterator it = this->views.begin(); it != this->views.end(); ++it) { + for (std::vector::const_iterator it = this->views.begin(); it != this->views.end(); ++it) { sp_canvas_item_show(SP_CANVAS_ITEM(*it)); - if((*it)->origin) { - sp_canvas_item_show(SP_CANVAS_ITEM((*it)->origin)); - } else { - //reposition to same place to show knots + if ((*it)->origin) { + sp_canvas_item_show(SP_CANVAS_ITEM((*it)->origin)); + } else { + // reposition to same place to show knots sp_guideline_set_position(*it, point_on_line); } } @@ -324,7 +326,7 @@ void SPGuide::showSPGuide() void SPGuide::hideSPGuide(Inkscape::UI::Widget::Canvas *canvas) { g_assert(canvas != nullptr); - for(std::vector::iterator it = this->views.begin(); it != this->views.end(); ++it) { + for (std::vector::iterator it = this->views.begin(); it != this->views.end(); ++it) { if (canvas == SP_CANVAS_ITEM(*it)->canvas) { sp_guideline_delete(*it); views.erase(it); @@ -337,7 +339,7 @@ void SPGuide::hideSPGuide(Inkscape::UI::Widget::Canvas *canvas) void SPGuide::hideSPGuide() { - for(std::vector::const_iterator it = this->views.begin(); it != this->views.end(); ++it) { + for (std::vector::const_iterator it = this->views.begin(); it != this->views.end(); ++it) { sp_canvas_item_hide(SP_CANVAS_ITEM(*it)); if ((*it)->origin) { sp_canvas_item_hide(SP_CANVAS_ITEM((*it)->origin)); @@ -349,7 +351,7 @@ void SPGuide::sensitize(Inkscape::UI::Widget::Canvas *canvas, bool sensitive) { g_assert(canvas != nullptr); - for(std::vector::const_iterator it = this->views.begin(); it != this->views.end(); ++it) { + for (std::vector::const_iterator it = this->views.begin(); it != this->views.end(); ++it) { if (canvas == SP_CANVAS_ITEM(*it)->canvas) { sp_guideline_set_sensitive(*it, sensitive); return; @@ -376,10 +378,10 @@ double SPGuide::getDistanceFrom(Geom::Point const &pt) const */ void SPGuide::moveto(Geom::Point const point_on_line, bool const commit) { - if(this->locked) { + if (this->locked) { return; } - for(auto view : this->views) { + for (auto view : this->views) { sp_guideline_set_position(view, point_on_line); } @@ -396,31 +398,35 @@ void SPGuide::moveto(Geom::Point const point_on_line, bool const commit) } SPRoot *root = document->getRoot(); - if( root->viewBox_set ) { + if (root->viewBox_set) { // check to see if scaling is uniform - if(Geom::are_near((root->viewBox.width() * root->height.computed) / (root->width.computed * root->viewBox.height()), 1.0, Geom::EPSILON)) { - double px2vbunit = (root->viewBox.width()/root->width.computed + root->viewBox.height()/root->height.computed)/2.0; + if (Geom::are_near((root->viewBox.width() * root->height.computed) / + (root->width.computed * root->viewBox.height()), + 1.0, Geom::EPSILON)) { + double px2vbunit = + (root->viewBox.width() / root->width.computed + root->viewBox.height() / root->height.computed) / + 2.0; newx = newx * px2vbunit; newy = newy * px2vbunit; } else { - newx = newx * root->viewBox.width() / root->width.computed; + newx = newx * root->viewBox.width() / root->width.computed; newy = newy * root->viewBox.height() / root->height.computed; } } - //XML Tree being used here directly while it shouldn't be. - sp_repr_set_point(getRepr(), "position", Geom::Point(newx, newy) ); + // XML Tree being used here directly while it shouldn't be. + sp_repr_set_point(getRepr(), "position", Geom::Point(newx, newy)); } -/* DISABLED CODE BECAUSE SPGuideAttachment IS NOT USE AT THE MOMENT (johan) - for (std::vector::const_iterator i(attached_items.begin()), - iEnd(attached_items.end()); - i != iEnd; ++i) - { - SPGuideAttachment const &att = *i; - sp_item_notify_moveto(*att.item, this, att.snappoint_ix, position, commit); - } -*/ + /* DISABLED CODE BECAUSE SPGuideAttachment IS NOT USE AT THE MOMENT (johan) + for (std::vector::const_iterator i(attached_items.begin()), + iEnd(attached_items.end()); + i != iEnd; ++i) + { + SPGuideAttachment const &att = *i; + sp_item_notify_moveto(*att.item, this, att.snappoint_ix, position, commit); + } + */ } /** @@ -430,17 +436,17 @@ void SPGuide::moveto(Geom::Point const point_on_line, bool const commit) */ void SPGuide::set_normal(Geom::Point const normal_to_line, bool const commit) { - if(this->locked) { + if (this->locked) { return; } - for(auto view : this->views) { + for (auto view : this->views) { sp_guideline_set_normal(view, normal_to_line); } /* Calling sp_repr_set_svg_point must precede calling sp_item_notify_moveto in the commit case, so that the guide's new position is available for sp_item_rm_unsatisfied_cns. */ if (commit) { - //XML Tree being used directly while it shouldn't be + // XML Tree being used directly while it shouldn't be auto normal = normal_to_line; // stores inverted y-axis coordinates @@ -451,29 +457,29 @@ void SPGuide::set_normal(Geom::Point const normal_to_line, bool const commit) sp_repr_set_point(getRepr(), "orientation", normal); } -/* DISABLED CODE BECAUSE SPGuideAttachment IS NOT USE AT THE MOMENT (johan) - for (std::vector::const_iterator i(attached_items.begin()), - iEnd(attached_items.end()); - i != iEnd; ++i) - { - SPGuideAttachment const &att = *i; - sp_item_notify_moveto(*att.item, this, att.snappoint_ix, position, commit); - } -*/ + /* DISABLED CODE BECAUSE SPGuideAttachment IS NOT USE AT THE MOMENT (johan) + for (std::vector::const_iterator i(attached_items.begin()), + iEnd(attached_items.end()); + i != iEnd; ++i) + { + SPGuideAttachment const &att = *i; + sp_item_notify_moveto(*att.item, this, att.snappoint_ix, position, commit); + } + */ } void SPGuide::set_color(const unsigned r, const unsigned g, const unsigned b, bool const commit) { this->color = (r << 24) | (g << 16) | (b << 8) | 0x7f; - if (! views.empty()) { + if (!views.empty()) { sp_guideline_set_color(views[0], this->color); } if (commit) { std::ostringstream os; os << "rgb(" << r << "," << g << "," << b << ")"; - //XML Tree being used directly while it shouldn't be + // XML Tree being used directly while it shouldn't be setAttribute("inkscape:color", os.str()); } } @@ -481,7 +487,7 @@ void SPGuide::set_color(const unsigned r, const unsigned g, const unsigned b, bo void SPGuide::set_locked(const bool locked, bool const commit) { this->locked = locked; - if ( !views.empty() ) { + if (!views.empty()) { sp_guideline_set_locked(views[0], locked); } @@ -490,14 +496,14 @@ void SPGuide::set_locked(const bool locked, bool const commit) } } -void SPGuide::set_label(const char* label, bool const commit) +void SPGuide::set_label(const char *label, bool const commit) { if (!views.empty()) { sp_guideline_set_label(views[0], label); } if (commit) { - //XML Tree being used directly while it shouldn't be + // XML Tree being used directly while it shouldn't be setAttribute("inkscape:label", label); } } @@ -508,13 +514,13 @@ void SPGuide::set_label(const char* label, bool const commit) * * The caller is responsible for freeing the string. */ -char* SPGuide::description(bool const verbose) const +char *SPGuide::description(bool const verbose) const { using Geom::X; using Geom::Y; char *descr = nullptr; - if ( !this->document ) { + if (!this->document) { // Guide has probably been deleted and no longer has an attached namedview. descr = g_strdup(_("Deleted")); } else { @@ -525,22 +531,23 @@ char* SPGuide::description(bool const verbose) const Glib::ustring position_string_x = x_q.string(namedview->display_units); Glib::ustring position_string_y = y_q.string(namedview->display_units); - gchar *shortcuts = g_strdup_printf("; %s", _("Shift+drag to rotate, Ctrl+drag to move origin, Del to delete")); + gchar *shortcuts = g_strdup_printf( + "; %s", _("Shift+drag to rotate, Ctrl+drag to move origin, Del to delete")); - if ( are_near(this->normal_to_line, Geom::Point(1., 0.)) || - are_near(this->normal_to_line, -Geom::Point(1., 0.)) ) { + if (are_near(this->normal_to_line, Geom::Point(1., 0.)) || + are_near(this->normal_to_line, -Geom::Point(1., 0.))) { descr = g_strdup_printf(_("vertical, at %s"), position_string_x.c_str()); - } else if ( are_near(this->normal_to_line, Geom::Point(0., 1.)) || - are_near(this->normal_to_line, -Geom::Point(0., 1.)) ) { + } else if (are_near(this->normal_to_line, Geom::Point(0., 1.)) || + are_near(this->normal_to_line, -Geom::Point(0., 1.))) { descr = g_strdup_printf(_("horizontal, at %s"), position_string_y.c_str()); } else { double const radians = this->angle(); double const degrees = Geom::deg_from_rad(radians); - int const degrees_int = (int) round(degrees); - descr = g_strdup_printf(_("at %d degrees, through (%s,%s)"), - degrees_int, position_string_x.c_str(), position_string_y.c_str()); + int const degrees_int = (int)round(degrees); + descr = g_strdup_printf(_("at %d degrees, through (%s,%s)"), degrees_int, position_string_x.c_str(), + position_string_y.c_str()); } - + if (verbose) { gchar *oldDescr = descr; descr = g_strconcat(oldDescr, shortcuts, NULL); @@ -558,15 +565,14 @@ void sp_guide_remove(SPGuide *guide) g_assert(SP_IS_GUIDE(guide)); for (std::vector::const_iterator i(guide->attached_items.begin()), - iEnd(guide->attached_items.end()); - i != iEnd; ++i) - { + iEnd(guide->attached_items.end()); + i != iEnd; ++i) { SPGuideAttachment const &att = *i; remove_last(att.item->constraints, SPGuideConstraint(guide, att.snappoint_ix)); } guide->attached_items.clear(); - //XML Tree being used directly while it shouldn't be. + // XML Tree being used directly while it shouldn't be. sp_repr_unparent(guide->getRepr()); } diff --git a/src/object/sp-guide.h b/src/object/sp-guide.h index cf075a29b9f506a3efa9bd08a3fd1569ec107cac..1e7ee51f35cbcb951cbf3f00499a1c45f1dca958 100644 --- a/src/object/sp-guide.h +++ b/src/object/sp-guide.h @@ -17,26 +17,27 @@ #include <2geom/point.h> #include -#include "sp-object.h" #include "sp-guide-attachment.h" +#include "sp-object.h" typedef unsigned int guint32; extern "C" { - typedef void (*GCallback) (); +typedef void (*GCallback)(); } class SPDesktop; struct SPCanvasGroup; struct SPGuideLine; -#define SP_GUIDE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_GUIDE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_GUIDE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_GUIDE(obj) (dynamic_cast((SPObject *)obj) != NULL) namespace Inkscape::UI::Widget { - class Canvas; +class Canvas; } /* Represents the constraint on p that dot(g.direction, p) == g.position. */ -class SPGuide : public SPObject { +class SPGuide : public SPObject +{ public: SPGuide(); ~SPGuide() override = default; @@ -53,8 +54,8 @@ public: void moveto(Geom::Point const point_on_line, bool const commit); void set_normal(Geom::Point const normal_to_line, bool const commit); - void set_label(const char* label, bool const commit); - char const* getLabel() const { return label; } + void set_label(const char *label, bool const commit); + char const *getLabel() const { return label; } void set_locked(const bool locked, bool const commit); bool getLocked() const { return locked; } @@ -72,31 +73,33 @@ public: bool isHorizontal() const { return (normal_to_line[Geom::X] == 0.); }; bool isVertical() const { return (normal_to_line[Geom::Y] == 0.); }; - char* description(bool const verbose = true) const; + char *description(bool const verbose = true) const; - double angle() const { return std::atan2( - normal_to_line[Geom::X], normal_to_line[Geom::Y] ); } + double angle() const { return std::atan2(-normal_to_line[Geom::X], normal_to_line[Geom::Y]); } double getDistanceFrom(Geom::Point const &pt) const; Geom::Point getPositionFrom(Geom::Point const &pt) const; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; void release() override; - void set(SPAttr key, const char* value) override; + void set(SPAttr key, const char *value) override; - char* label; - std::vector views; // contains an object of type SPGuideline (see display/guideline.cpp for definition) + char *label; + std::vector views; // contains an object of type SPGuideline (see display/guideline.cpp for + // definition) bool locked; Geom::Point normal_to_line; Geom::Point point_on_line; guint32 color; guint32 hicolor; + public: std::vector attached_items; // unused }; // These functions rightfully belong to SPDesktop. What gives?! -void sp_guide_pt_pairs_to_guides(SPDocument *doc, std::list > &pts); +void sp_guide_pt_pairs_to_guides(SPDocument *doc, std::list> &pts); void sp_guide_create_guides_around_page(SPDesktop *dt); void sp_guide_delete_all_guides(SPDesktop *dt); diff --git a/src/object/sp-hatch-path.cpp b/src/object/sp-hatch-path.cpp index e519720dbd2d56a7164f9f5daa2a486a73ecf221..dc580f4432e4d953978b0c12642865c9e2c0f109 100644 --- a/src/object/sp-hatch-path.cpp +++ b/src/object/sp-hatch-path.cpp @@ -13,35 +13,35 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "sp-hatch-path.h" + #include <2geom/path.h> +#include -#include "svg/svg.h" +#include "attributes.h" #include "display/cairo-utils.h" #include "display/curve.h" #include "display/drawing-context.h" +#include "display/drawing-shape.h" #include "display/drawing-surface.h" #include "display/drawing.h" -#include "display/drawing-shape.h" #include "helper/geom.h" -#include "attributes.h" #include "sp-item.h" -#include "sp-hatch-path.h" #include "svg/css-ostringstream.h" +#include "svg/svg.h" SPHatchPath::SPHatchPath() - : offset(), - _display(), - _curve(nullptr), - _continuous(false) + : offset() + , _display() + , _curve(nullptr) + , _continuous(false) { offset.unset(); } -SPHatchPath::~SPHatchPath() -= default; +SPHatchPath::~SPHatchPath() = default; -void SPHatchPath::build(SPDocument* doc, Inkscape::XML::Node* repr) +void SPHatchPath::build(SPDocument *doc, Inkscape::XML::Node *repr) { SPObject::build(doc, repr); @@ -54,7 +54,7 @@ void SPHatchPath::build(SPDocument* doc, Inkscape::XML::Node* repr) void SPHatchPath::release() { - for (auto & iter : _display) { + for (auto &iter : _display) { delete iter.arenaitem; iter.arenaitem = nullptr; } @@ -62,39 +62,38 @@ void SPHatchPath::release() SPObject::release(); } -void SPHatchPath::set(SPAttr key, const gchar* value) +void SPHatchPath::set(SPAttr key, const gchar *value) { switch (key) { - case SPAttr::D: - if (value) { - Geom::PathVector pv; - _readHatchPathVector(value, pv, _continuous); - _curve.reset(new SPCurve(pv)); - } else { - _curve.reset(nullptr); - } + case SPAttr::D: + if (value) { + Geom::PathVector pv; + _readHatchPathVector(value, pv, _continuous); + _curve.reset(new SPCurve(pv)); + } else { + _curve.reset(nullptr); + } - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::OFFSET: - offset.readOrUnset(value); - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + case SPAttr::OFFSET: + offset.readOrUnset(value); + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - default: - if (SP_ATTRIBUTE_IS_CSS(key)) { - style->clear(key); - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); - } else { - SPObject::set(key, value); - } - break; + default: + if (SP_ATTRIBUTE_IS_CSS(key)) { + style->clear(key); + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); + } else { + SPObject::set(key, value); + } + break; } } - -void SPHatchPath::update(SPCtx* ctx, unsigned int flags) +void SPHatchPath::update(SPCtx *ctx, unsigned int flags) { if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { flags &= ~SP_OBJECT_USER_MODIFIED_FLAG_B; @@ -102,20 +101,20 @@ void SPHatchPath::update(SPCtx* ctx, unsigned int flags) if (flags & (SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { if (style->stroke_width.unit == SP_CSS_UNIT_PERCENT) { - //TODO: Check specification + // TODO: Check specification SPItemCtx *ictx = static_cast(ctx); double const aw = (ictx) ? 1.0 / ictx->i2vp.descrim() : 1.0; style->stroke_width.computed = style->stroke_width.value * aw; - for (auto & iter : _display) { + for (auto &iter : _display) { iter.arenaitem->setStyle(style); } } } if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG)) { - for (auto & iter : _display) { + for (auto &iter : _display) { _updateView(iter); } } @@ -156,7 +155,7 @@ void SPHatchPath::hide(unsigned int key) void SPHatchPath::setStripExtents(unsigned int key, Geom::OptInterval const &extents) { - for (auto & iter : _display) { + for (auto &iter : _display) { if (iter.key == key) { iter.extents = extents; break; @@ -187,7 +186,7 @@ Geom::Interval SPHatchPath::bounds() const std::unique_ptr SPHatchPath::calculateRenderCurve(unsigned key) const { - for (const auto & iter : _display) { + for (const auto &iter : _display) { if (iter.key == key) { return _calculateRenderCurve(iter); } @@ -229,7 +228,7 @@ std::unique_ptr SPHatchPath::_calculateRenderCurve(View const &view) co if (!_curve) { calculated_curve->moveto(0, view.extents->min()); calculated_curve->lineto(0, view.extents->max()); - //TODO: if hatch has a dasharray defined, adjust line ends + // TODO: if hatch has a dasharray defined, adjust line ends } else { gdouble repeatLength = _repeatLength(); if (repeatLength > 0) { @@ -253,7 +252,6 @@ std::unique_ptr SPHatchPath::_calculateRenderCurve(View const &view) co return calculated_curve; } - void SPHatchPath::_readHatchPathVector(char const *str, Geom::PathVector &pathv, bool &continous_join) { if (!str) { @@ -277,9 +275,9 @@ void SPHatchPath::_readHatchPathVector(char const *str, Geom::PathVector &pathv, Glib::ustring str3 = Glib::ustring::compose("M%1,0 %2", stream.str(), str); Geom::PathVector pathv3 = sp_svg_read_pathv(str3.c_str()); - //Path can be composed of relative commands only. In this case final point - //coordinates would depend on first point position. If this happens, fall - //back to using 0,0 as first path point + // Path can be composed of relative commands only. In this case final point + // coordinates would depend on first point position. If this happens, fall + // back to using 0,0 as first path point if (pathv3.back().finalPoint().y() == pathv.back().finalPoint().y()) { pathv = pathv3; } @@ -288,11 +286,10 @@ void SPHatchPath::_readHatchPathVector(char const *str, Geom::PathVector &pathv, } SPHatchPath::View::View(Inkscape::DrawingShape *arenaitem, int key) - : arenaitem(arenaitem), - extents(), - key(key) -{ -} + : arenaitem(arenaitem) + , extents() + , key(key) +{} SPHatchPath::View::~View() { @@ -300,7 +297,6 @@ SPHatchPath::View::~View() arenaitem = nullptr; } - /* Local Variables: mode:c++ diff --git a/src/object/sp-hatch-path.h b/src/object/sp-hatch-path.h index dc625f0ea9b28aac40f72b1c1e434e2d25e9c9be..5b668c9f5e8fcf2276f4ffed35ecfba3485825fa 100644 --- a/src/object/sp-hatch-path.h +++ b/src/object/sp-hatch-path.h @@ -16,15 +16,15 @@ #ifndef SEEN_SP_HATCH_PATH_H #define SEEN_SP_HATCH_PATH_H -#include +#include <2geom/generic-interval.h> +#include <2geom/pathvector.h> #include #include +#include #include -#include <2geom/generic-interval.h> -#include <2geom/pathvector.h> -#include "svg/svg-length.h" #include "object/sp-object.h" +#include "svg/svg-length.h" class SPCurve; @@ -36,9 +36,10 @@ class Drawing; class DrawingShape; class DrawingItem; -} +} // namespace Inkscape -class SPHatchPath : public SPObject { +class SPHatchPath : public SPObject +{ public: SPHatchPath(); ~SPHatchPath() override; @@ -56,16 +57,17 @@ public: std::unique_ptr calculateRenderCurve(unsigned key) const; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; void release() override; - void set(SPAttr key, const gchar* value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void set(SPAttr key, const gchar *value) override; + void update(SPCtx *ctx, unsigned int flags) override; private: - class View { + class View + { public: View(Inkscape::DrawingShape *arenaitem, int key); - //Do not delete arenaitem in destructor. + // Do not delete arenaitem in destructor. ~View(); diff --git a/src/object/sp-hatch.cpp b/src/object/sp-hatch.cpp index 78bb8c78ac7a031aa41a8958169847b3eef1698f..7f1c9f89c386e4a36cffea657359b03cc1ef066a 100644 --- a/src/object/sp-hatch.cpp +++ b/src/object/sp-hatch.cpp @@ -15,44 +15,41 @@ #include "sp-hatch.h" -#include -#include - #include <2geom/transforms.h> +#include #include +#include #include "attributes.h" #include "bad-uri-exception.h" -#include "document.h" - #include "display/cairo-utils.h" #include "display/drawing-context.h" +#include "display/drawing-pattern.h" #include "display/drawing-surface.h" #include "display/drawing.h" -#include "display/drawing-pattern.h" - +#include "document.h" #include "sp-defs.h" #include "sp-hatch-path.h" #include "sp-item.h" - #include "svg/svg.h" SPHatch::SPHatch() - : SPPaintServer(), - href(), - ref(nullptr), // avoiding 'this' in initializer list - _hatchUnits(UNITS_OBJECTBOUNDINGBOX), - _hatchUnits_set(false), - _hatchContentUnits(UNITS_USERSPACEONUSE), - _hatchContentUnits_set(false), - _hatchTransform(Geom::identity()), - _hatchTransform_set(false), - _x(), - _y(), - _pitch(), - _rotate(), - _modified_connection(), - _display() + : SPPaintServer() + , href() + , ref(nullptr) + , // avoiding 'this' in initializer list + _hatchUnits(UNITS_OBJECTBOUNDINGBOX) + , _hatchUnits_set(false) + , _hatchContentUnits(UNITS_USERSPACEONUSE) + , _hatchContentUnits_set(false) + , _hatchTransform(Geom::identity()) + , _hatchTransform_set(false) + , _x() + , _y() + , _pitch() + , _rotate() + , _modified_connection() + , _display() { ref = new SPHatchReference(this); ref->changedSignal().connect(sigc::mem_fun(this, &SPHatch::_onRefChanged)); @@ -66,7 +63,7 @@ SPHatch::SPHatch() SPHatch::~SPHatch() = default; -void SPHatch::build(SPDocument* doc, Inkscape::XML::Node* repr) +void SPHatch::build(SPDocument *doc, Inkscape::XML::Node *repr) { SPPaintServer::build(doc, repr); @@ -92,7 +89,7 @@ void SPHatch::release() } std::vector children(hatchPaths()); - for (auto & view_iter : _display) { + for (auto &view_iter : _display) { for (auto child : children) { child->hide(view_iter.key); } @@ -110,14 +107,14 @@ void SPHatch::release() SPPaintServer::release(); } -void SPHatch::child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) +void SPHatch::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { SPObject::child_added(child, ref); SPHatchPath *path_child = dynamic_cast(document->getObjectByRepr(child)); if (path_child) { - for (auto & iter : _display) { + for (auto &iter : _display) { Geom::OptInterval extents = _calculateStripExtents(iter.bbox); Inkscape::DrawingItem *ac = path_child->show(iter.arenaitem->drawing(), iter.key, extents); @@ -127,117 +124,117 @@ void SPHatch::child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) } } } - //FIXME: notify all hatches that refer to this child set + // FIXME: notify all hatches that refer to this child set } -void SPHatch::set(SPAttr key, const gchar* value) +void SPHatch::set(SPAttr key, const gchar *value) { switch (key) { - case SPAttr::HATCHUNITS: - if (value) { - if (!strcmp(value, "userSpaceOnUse")) { - _hatchUnits = UNITS_USERSPACEONUSE; + case SPAttr::HATCHUNITS: + if (value) { + if (!strcmp(value, "userSpaceOnUse")) { + _hatchUnits = UNITS_USERSPACEONUSE; + } else { + _hatchUnits = UNITS_OBJECTBOUNDINGBOX; + } + + _hatchUnits_set = true; } else { - _hatchUnits = UNITS_OBJECTBOUNDINGBOX; + _hatchUnits_set = false; } - _hatchUnits_set = true; - } else { - _hatchUnits_set = false; - } + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + case SPAttr::HATCHCONTENTUNITS: + if (value) { + if (!strcmp(value, "userSpaceOnUse")) { + _hatchContentUnits = UNITS_USERSPACEONUSE; + } else { + _hatchContentUnits = UNITS_OBJECTBOUNDINGBOX; + } - case SPAttr::HATCHCONTENTUNITS: - if (value) { - if (!strcmp(value, "userSpaceOnUse")) { - _hatchContentUnits = UNITS_USERSPACEONUSE; + _hatchContentUnits_set = true; } else { - _hatchContentUnits = UNITS_OBJECTBOUNDINGBOX; + _hatchContentUnits_set = false; } - _hatchContentUnits_set = true; - } else { - _hatchContentUnits_set = false; - } + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + case SPAttr::HATCHTRANSFORM: { + Geom::Affine t; - case SPAttr::HATCHTRANSFORM: { - Geom::Affine t; + if (value && sp_svg_transform_read(value, &t)) { + _hatchTransform = t; + _hatchTransform_set = true; + } else { + _hatchTransform = Geom::identity(); + _hatchTransform_set = false; + } - if (value && sp_svg_transform_read(value, &t)) { - _hatchTransform = t; - _hatchTransform_set = true; - } else { - _hatchTransform = Geom::identity(); - _hatchTransform_set = false; + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; } + case SPAttr::X: + _x.readOrUnset(value); + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - } - case SPAttr::X: - _x.readOrUnset(value); - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::Y: - _y.readOrUnset(value); - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + case SPAttr::Y: + _y.readOrUnset(value); + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::PITCH: - _pitch.readOrUnset(value); - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + case SPAttr::PITCH: + _pitch.readOrUnset(value); + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::ROTATE: - _rotate.readOrUnset(value); - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + case SPAttr::ROTATE: + _rotate.readOrUnset(value); + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::XLINK_HREF: - if (value && href == value) { - // Href unchanged, do nothing. - } else { - href.clear(); + case SPAttr::XLINK_HREF: + if (value && href == value) { + // Href unchanged, do nothing. + } else { + href.clear(); - if (value) { - // First, set the href field; it's only used in the "unchanged" check above. - href = value; - // Now do the attaching, which emits the changed signal. if (value) { - try { - ref->attach(Inkscape::URI(value)); - } catch (Inkscape::BadURIException &e) { - g_warning("%s", e.what()); + // First, set the href field; it's only used in the "unchanged" check above. + href = value; + // Now do the attaching, which emits the changed signal. + if (value) { + try { + ref->attach(Inkscape::URI(value)); + } catch (Inkscape::BadURIException &e) { + g_warning("%s", e.what()); + ref->detach(); + } + } else { ref->detach(); } - } else { - ref->detach(); } } - } - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - default: - if (SP_ATTRIBUTE_IS_CSS(key)) { - style->clear(key); - requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); - } else { - SPPaintServer::set(key, value); - } - break; + default: + if (SP_ATTRIBUTE_IS_CSS(key)) { + style->clear(key); + requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); + } else { + SPPaintServer::set(key, value); + } + break; } } bool SPHatch::_hasHatchPatchChildren(SPHatch const *hatch) { - for (auto& child: hatch->children) { + for (auto &child : hatch->children) { SPHatchPath const *hatchPath = dynamic_cast(&child); if (hatchPath) { return true; @@ -246,13 +243,13 @@ bool SPHatch::_hasHatchPatchChildren(SPHatch const *hatch) return false; } -std::vector SPHatch::hatchPaths() +std::vector SPHatch::hatchPaths() { - std::vector list; + std::vector list; SPHatch *src = chase_hrefs(this, sigc::ptr_fun(&_hasHatchPatchChildren)); if (src) { - for (auto& child: src->children) { + for (auto &child : src->children) { SPHatchPath *hatchPath = dynamic_cast(&child); if (hatchPath) { list.push_back(hatchPath); @@ -262,14 +259,14 @@ std::vector SPHatch::hatchPaths() return list; } -std::vector SPHatch::hatchPaths() const +std::vector SPHatch::hatchPaths() const { - std::vector list; + std::vector list; SPHatch const *src = chase_hrefs(this, sigc::ptr_fun(&_hasHatchPatchChildren)); if (src) { - for (auto& child: src->children) { - SPHatchPath const *hatchPath = dynamic_cast(&child); + for (auto &child : src->children) { + SPHatchPath const *hatchPath = dynamic_cast(&child); if (hatchPath) { list.push_back(hatchPath); } @@ -280,8 +277,7 @@ std::vector SPHatch::hatchPaths() const // TODO: ::remove_child and ::order_changed handles - see SPPattern - -void SPHatch::update(SPCtx* ctx, unsigned int flags) +void SPHatch::update(SPCtx *ctx, unsigned int flags) { if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; @@ -294,20 +290,19 @@ void SPHatch::update(SPCtx* ctx, unsigned int flags) for (auto child : children) { sp_object_ref(child, nullptr); - for (auto & view_iter : _display) { + for (auto &view_iter : _display) { Geom::OptInterval strip_extents = _calculateStripExtents(view_iter.bbox); child->setStripExtents(view_iter.key, strip_extents); } if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { - child->updateDisplay(ctx, flags); } sp_object_unref(child, nullptr); } - for (auto & iter : _display) { + for (auto &iter : _display) { _updateView(iter); } } @@ -360,8 +355,7 @@ void SPHatch::_onRefChanged(SPObject *old_ref, SPObject *ref) newhatchPaths = new_shown->hatchPaths(); } if (old_shown != new_shown) { - - for (auto & iter : _display) { + for (auto &iter : _display) { Geom::OptInterval extents = _calculateStripExtents(iter.bbox); for (auto child : oldhatchPaths) { @@ -373,7 +367,6 @@ void SPHatch::_onRefChanged(SPObject *old_ref, SPObject *ref) if (cai) { iter.arenaitem->appendChild(cai); } - } } } @@ -382,17 +375,17 @@ void SPHatch::_onRefChanged(SPObject *old_ref, SPObject *ref) _onRefModified(ref, 0); } -void SPHatch::_onRefModified(SPObject */*ref*/, guint /*flags*/) +void SPHatch::_onRefModified(SPObject * /*ref*/, guint /*flags*/) { requestModified(SP_OBJECT_MODIFIED_FLAG); // Conditional to avoid causing infinite loop if there's a cycle in the href chain. } - SPHatch *SPHatch::rootHatch() { SPHatch *src = chase_hrefs(this, sigc::ptr_fun(&_hasHatchPatchChildren)); - return src ? src : this; // document is broken, we can't get to root; but at least we can return pat which is supposedly a valid hatch + return src ? src : this; // document is broken, we can't get to root; but at least we can return pat which is + // supposedly a valid hatch } // Access functions that look up fields up the chain of referenced hatchs and return the first one which is set @@ -569,7 +562,7 @@ bool SPHatch::isValid() const Inkscape::DrawingPattern *SPHatch::show(Inkscape::Drawing &drawing, unsigned int key, Geom::OptRect bbox) { Inkscape::DrawingPattern *ai = new Inkscape::DrawingPattern(drawing); - //TODO: set some debug flag to see DrawingPattern + // TODO: set some debug flag to see DrawingPattern _display.push_front(View(ai, key)); _display.front().bbox = bbox; @@ -583,7 +576,7 @@ Inkscape::DrawingPattern *SPHatch::show(Inkscape::Drawing &drawing, unsigned int } } - View& view = _display.front(); + View &view = _display.front(); _updateView(view); return ai; @@ -608,7 +601,6 @@ void SPHatch::hide(unsigned int key) g_assert_not_reached(); } - Geom::Interval SPHatch::bounds() const { Geom::Interval result; @@ -627,7 +619,7 @@ Geom::Interval SPHatch::bounds() const SPHatch::RenderInfo SPHatch::calculateRenderInfo(unsigned key) const { RenderInfo info; - for (const auto & iter : _display) { + for (const auto &iter : _display) { if (iter.key == key) { return _calculateRenderInfo(iter); } @@ -639,18 +631,16 @@ SPHatch::RenderInfo SPHatch::calculateRenderInfo(unsigned key) const void SPHatch::_updateView(View &view) { RenderInfo info = _calculateRenderInfo(view); - //The rendering of hatch overflow is implemented by repeated drawing - //of hatch paths over one strip. Within each iteration paths are moved by pitch value. - //The movement progresses from right to left. This gives the same result - //as drawing whole strips in left-to-right order. - + // The rendering of hatch overflow is implemented by repeated drawing + // of hatch paths over one strip. Within each iteration paths are moved by pitch value. + // The movement progresses from right to left. This gives the same result + // as drawing whole strips in left-to-right order. view.arenaitem->setChildTransform(info.child_transform); view.arenaitem->setPatternToUserTransform(info.pattern_to_user_transform); view.arenaitem->setTileRect(info.tile_rect); view.arenaitem->setStyle(style); - view.arenaitem->setOverflow(info.overflow_initial_transform, info.overflow_steps, - info.overflow_step_transform); + view.arenaitem->setOverflow(info.overflow_initial_transform, info.overflow_steps, info.overflow_step_transform); } SPHatch::RenderInfo SPHatch::_calculateRenderInfo(View const &view) const @@ -688,7 +678,8 @@ SPHatch::RenderInfo SPHatch::_calculateRenderInfo(View const &view) const } // Tile (hatch space) to user. - Geom::Affine ps2user = Geom::Translate(tile_x, tile_y) * Geom::Rotate::from_degrees(tile_rotate) * hatchTransform(); + Geom::Affine ps2user = + Geom::Translate(tile_x, tile_y) * Geom::Rotate::from_degrees(tile_rotate) * hatchTransform(); info.child_transform = content2ps; info.pattern_to_user_transform = ps2user; @@ -717,7 +708,7 @@ SPHatch::RenderInfo SPHatch::_calculateRenderInfo(View const &view) const return info; } -//calculates strip extents in content space +// calculates strip extents in content space Geom::OptInterval SPHatch::_calculateStripExtents(Geom::OptRect const &bbox) const { if (!bbox || (bbox->area() == 0)) { @@ -727,13 +718,14 @@ Geom::OptInterval SPHatch::_calculateStripExtents(Geom::OptRect const &bbox) con double tile_y = y(); double tile_rotate = rotate(); - Geom::Affine ps2user = Geom::Translate(tile_x, tile_y) * Geom::Rotate::from_degrees(tile_rotate) * hatchTransform(); + Geom::Affine ps2user = + Geom::Translate(tile_x, tile_y) * Geom::Rotate::from_degrees(tile_rotate) * hatchTransform(); Geom::Affine user2ps = ps2user.inverse(); Geom::Interval extents; for (int i = 0; i < 4; ++i) { Geom::Point corner = bbox->corner(i); - Geom::Point corner_ps = corner * user2ps; + Geom::Point corner_ps = corner * user2ps; if (i == 0 || corner_ps.y() < extents.min()) { extents.setMin(corner_ps.y()); } @@ -750,16 +742,16 @@ Geom::OptInterval SPHatch::_calculateStripExtents(Geom::OptRect const &bbox) con } } -cairo_pattern_t* SPHatch::pattern_new(cairo_t * /*base_ct*/, Geom::OptRect const &/*bbox*/, double /*opacity*/) +cairo_pattern_t *SPHatch::pattern_new(cairo_t * /*base_ct*/, Geom::OptRect const & /*bbox*/, double /*opacity*/) { - //this code should not be used - //it is however required by the fact that SPPaintServer::hatch_new is pure virtual + // this code should not be used + // it is however required by the fact that SPPaintServer::hatch_new is pure virtual return cairo_pattern_create_rgb(0.5, 0.5, 1.0); } void SPHatch::setBBox(unsigned int key, Geom::OptRect const &bbox) { - for (auto & iter : _display) { + for (auto &iter : _display) { if (iter.key == key) { iter.bbox = bbox; break; @@ -770,26 +762,23 @@ void SPHatch::setBBox(unsigned int key, Geom::OptRect const &bbox) // SPHatch::RenderInfo::RenderInfo() - : child_transform(), - pattern_to_user_transform(), - tile_rect(), - overflow_steps(0), - overflow_step_transform(), - overflow_initial_transform() -{ -} + : child_transform() + , pattern_to_user_transform() + , tile_rect() + , overflow_steps(0) + , overflow_step_transform() + , overflow_initial_transform() +{} -SPHatch::RenderInfo::~RenderInfo() -= default; +SPHatch::RenderInfo::~RenderInfo() = default; // SPHatch::View::View(Inkscape::DrawingPattern *arenaitem, int key) - : arenaitem(arenaitem), - bbox(), - key(key) -{ -} + : arenaitem(arenaitem) + , bbox() + , key(key) +{} SPHatch::View::~View() { diff --git a/src/object/sp-hatch.h b/src/object/sp-hatch.h index 903bc8e9b709760ba9baee97cd7745ae6a032f3c..b0854fb8b4d3f2792238607dff11c3c4294a9830 100644 --- a/src/object/sp-hatch.h +++ b/src/object/sp-hatch.h @@ -16,14 +16,14 @@ #ifndef SEEN_SP_HATCH_H #define SEEN_SP_HATCH_H -#include #include #include +#include #include -#include "svg/svg-length.h" -#include "svg/svg-angle.h" #include "sp-paint-server.h" +#include "svg/svg-angle.h" +#include "svg/svg-length.h" #include "uri-references.h" class SPHatchReference; @@ -40,19 +40,22 @@ namespace XML { class Node; } -} +} // namespace Inkscape #define SP_HATCH(obj) (dynamic_cast((SPObject *)obj)) #define SP_IS_HATCH(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPHatch : public SPPaintServer { +class SPHatch : public SPPaintServer +{ public: - enum HatchUnits { + enum HatchUnits + { UNITS_USERSPACEONUSE, UNITS_OBJECTBOUNDINGBOX }; - class RenderInfo { + class RenderInfo + { public: RenderInfo(); ~RenderInfo(); @@ -80,7 +83,7 @@ public: HatchUnits hatchUnits() const; HatchUnits hatchContentUnits() const; Geom::Affine const &hatchTransform() const; - SPHatch *rootHatch(); //TODO: const + SPHatch *rootHatch(); // TODO: const std::vector hatchPaths(); std::vector hatchPaths() const; @@ -92,25 +95,26 @@ public: Inkscape::DrawingPattern *show(Inkscape::Drawing &drawing, unsigned int key, Geom::OptRect bbox) override; void hide(unsigned int key) override; - cairo_pattern_t* pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) override; + cairo_pattern_t *pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) override; RenderInfo calculateRenderInfo(unsigned key) const; Geom::Interval bounds() const; void setBBox(unsigned int key, Geom::OptRect const &bbox) override; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; void release() override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void set(SPAttr key, const gchar* value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void set(SPAttr key, const gchar *value) override; + void update(SPCtx *ctx, unsigned int flags) override; void modified(unsigned int flags) override; private: - class View { + class View + { public: View(Inkscape::DrawingPattern *arenaitem, int key); - //Do not delete arenaitem in destructor. + // Do not delete arenaitem in destructor. ~View(); @@ -124,7 +128,7 @@ private: typedef std::list::iterator ViewIterator; typedef std::list::const_iterator ConstViewIterator; - static bool _hasHatchPatchChildren(SPHatch const* hatch); + static bool _hasHatchPatchChildren(SPHatch const *hatch); void _updateView(View &view); RenderInfo _calculateRenderInfo(View const &view) const; @@ -166,19 +170,18 @@ private: std::list _display; }; - -class SPHatchReference : public Inkscape::URIReference { +class SPHatchReference : public Inkscape::URIReference +{ public: - SPHatchReference (SPObject *obj) + SPHatchReference(SPObject *obj) : URIReference(obj) {} - SPHatch *getObject() const { - return reinterpret_cast(URIReference::getObject()); - } + SPHatch *getObject() const { return reinterpret_cast(URIReference::getObject()); } protected: - bool _acceptObject(SPObject *obj) const override { + bool _acceptObject(SPObject *obj) const override + { return dynamic_cast(obj) != nullptr && URIReference::_acceptObject(obj); } }; diff --git a/src/object/sp-image.cpp b/src/object/sp-image.cpp index c9fca4a90d02d00639b27f1dbb2d8fa010725d93..ba1a8b1c75a8234061d745dd55869ee0b121645b 100644 --- a/src/object/sp-image.cpp +++ b/src/object/sp-image.cpp @@ -15,43 +15,44 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include -#include -#include -#include -#include #include <2geom/rect.h> #include <2geom/transforms.h> -#include +#include +#include #include +#include +#include +#include +#include -#include "display/drawing-image.h" #include "display/cairo-utils.h" #include "display/curve.h" +#include "display/drawing-image.h" // Added for preserveAspectRatio support -- EAF #include "attributes.h" -#include "print.h" #include "document.h" -#include "sp-image.h" +#include "io/sys.h" +#include "preferences.h" +#include "print.h" #include "sp-clippath.h" +#include "sp-image.h" #include "xml/quote.h" -#include "preferences.h" -#include "io/sys.h" #if defined(HAVE_LIBLCMS2) +#include + #include "cms-system.h" #include "color-profile.h" -#include //#define DEBUG_LCMS #ifdef DEBUG_LCMS -#define DEBUG_MESSAGE(key, ...)\ -{\ - g_message( __VA_ARGS__ );\ -} +#define DEBUG_MESSAGE(key, ...) \ + { \ + g_message(__VA_ARGS__); \ + } #include #else #define DEBUG_MESSAGE(key, ...) @@ -70,43 +71,36 @@ static void sp_image_set_curve(SPImage *image); static Inkscape::Pixbuf *sp_image_repr_read_image(gchar const *href, gchar const *absref, gchar const *base, double svgdpi = 0); -static void sp_image_update_arenaitem (SPImage *img, Inkscape::DrawingImage *ai); -static void sp_image_update_canvas_image (SPImage *image); +static void sp_image_update_arenaitem(SPImage *img, Inkscape::DrawingImage *ai); +static void sp_image_update_canvas_image(SPImage *image); #ifdef DEBUG_LCMS extern guint update_in_progress; -#define DEBUG_MESSAGE_SCISLAC(key, ...) \ -{\ - Inkscape::Preferences *prefs = Inkscape::Preferences::get();\ - bool dump = prefs->getBool("/options/scislac/" #key);\ - bool dumpD = prefs->getBool("/options/scislac/" #key "D");\ - bool dumpD2 = prefs->getBool("/options/scislac/" #key "D2");\ - dumpD &&= ( (update_in_progress == 0) || dumpD2 );\ - if ( dump )\ - {\ - g_message( __VA_ARGS__ );\ -\ - }\ - if ( dumpD )\ - {\ - GtkWidget *dialog = gtk_message_dialog_new(NULL,\ - GTK_DIALOG_DESTROY_WITH_PARENT, \ - GTK_MESSAGE_INFO, \ - GTK_BUTTONS_OK, \ - __VA_ARGS__ \ - );\ - g_signal_connect_swapped(dialog, "response",\ - G_CALLBACK(gtk_widget_destroy), \ - dialog); \ - gtk_widget_show_all( dialog );\ - }\ -} +#define DEBUG_MESSAGE_SCISLAC(key, ...) \ + { \ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); \ + bool dump = prefs->getBool("/options/scislac/" #key); \ + bool dumpD = prefs->getBool("/options/scislac/" #key "D"); \ + bool dumpD2 = prefs->getBool("/options/scislac/" #key "D2"); \ + dumpD && = ((update_in_progress == 0) || dumpD2); \ + if (dump) { \ + g_message(__VA_ARGS__); \ + } \ + if (dumpD) { \ + GtkWidget *dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, \ + GTK_BUTTONS_OK, __VA_ARGS__); \ + g_signal_connect_swapped(dialog, "response", G_CALLBACK(gtk_widget_destroy), dialog); \ + gtk_widget_show_all(dialog); \ + } \ + } #else // DEBUG_LCMS #define DEBUG_MESSAGE_SCISLAC(key, ...) #endif // DEBUG_LCMS -SPImage::SPImage() : SPItem(), SPViewBox() { - +SPImage::SPImage() + : SPItem() + , SPViewBox() +{ this->x.unset(); this->y.unset(); this->width.unset(); @@ -128,7 +122,8 @@ SPImage::SPImage() : SPItem(), SPViewBox() { SPImage::~SPImage() = default; -void SPImage::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPImage::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPItem::build(document, repr); this->readAttr(SPAttr::XLINK_HREF); @@ -144,14 +139,15 @@ void SPImage::build(SPDocument *document, Inkscape::XML::Node *repr) { document->addResource("image", this); } -void SPImage::release() { +void SPImage::release() +{ if (this->document) { // Unregister ourselves this->document->removeResource("image", this); } if (this->href) { - g_free (this->href); + g_free(this->href); this->href = nullptr; } @@ -160,7 +156,7 @@ void SPImage::release() { #if defined(HAVE_LIBLCMS2) if (this->color_profile) { - g_free (this->color_profile); + g_free(this->color_profile); this->color_profile = nullptr; } #endif // defined(HAVE_LIBLCMS2) @@ -170,11 +166,12 @@ void SPImage::release() { SPItem::release(); } -void SPImage::set(SPAttr key, const gchar* value) { +void SPImage::set(SPAttr key, const gchar *value) +{ switch (key) { case SPAttr::XLINK_HREF: - g_free (this->href); - this->href = (value) ? g_strdup (value) : nullptr; + g_free(this->href); + this->href = (value) ? g_strdup(value) : nullptr; this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_IMAGE_HREF_MODIFIED_FLAG); break; @@ -219,22 +216,22 @@ void SPImage::set(SPAttr key, const gchar* value) { break; case SPAttr::PRESERVEASPECTRATIO: - set_preserveAspectRatio( value ); + set_preserveAspectRatio(value); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); break; #if defined(HAVE_LIBLCMS2) case SPAttr::COLOR_PROFILE: - if ( this->color_profile ) { - g_free (this->color_profile); + if (this->color_profile) { + g_free(this->color_profile); } - this->color_profile = (value) ? g_strdup (value) : nullptr; + this->color_profile = (value) ? g_strdup(value) : nullptr; - if ( value ) { - DEBUG_MESSAGE( lcmsFour, " color-profile set to '%s'", value ); + if (value) { + DEBUG_MESSAGE(lcmsFour, " color-profile set to '%s'", value); } else { - DEBUG_MESSAGE( lcmsFour, " color-profile cleared" ); + DEBUG_MESSAGE(lcmsFour, " color-profile cleared"); } // TODO check on this HREF_MODIFIED flag @@ -248,34 +245,33 @@ void SPImage::set(SPAttr key, const gchar* value) { break; } - sp_image_set_curve(this); //creates a curve at the image's boundary for snapping + sp_image_set_curve(this); // creates a curve at the image's boundary for snapping } // BLIP #if defined(HAVE_LIBLCMS2) -void SPImage::apply_profile(Inkscape::Pixbuf *pixbuf) { - +void SPImage::apply_profile(Inkscape::Pixbuf *pixbuf) +{ // TODO: this will prevent using MIME data when exporting. // Integrate color correction into loading. pixbuf->ensurePixelFormat(Inkscape::Pixbuf::PF_GDK); int imagewidth = pixbuf->width(); int imageheight = pixbuf->height(); - int rowstride = pixbuf->rowstride();; - guchar* px = pixbuf->pixels(); + int rowstride = pixbuf->rowstride(); + ; + guchar *px = pixbuf->pixels(); - if ( px ) { - DEBUG_MESSAGE( lcmsFive, "in 's sp_image_update. About to call colorprofile_get_handle()" ); + if (px) { + DEBUG_MESSAGE(lcmsFive, "in 's sp_image_update. About to call colorprofile_get_handle()"); guint profIntent = Inkscape::RENDERING_INTENT_UNKNOWN; - cmsHPROFILE prof = Inkscape::CMSSystem::getHandle( this->document, - &profIntent, - this->color_profile ); - if ( prof ) { - cmsProfileClassSignature profileClass = cmsGetDeviceClass( prof ); - if ( profileClass != cmsSigNamedColorClass ) { + cmsHPROFILE prof = Inkscape::CMSSystem::getHandle(this->document, &profIntent, this->color_profile); + if (prof) { + cmsProfileClassSignature profileClass = cmsGetDeviceClass(prof); + if (profileClass != cmsSigNamedColorClass) { int intent = INTENT_PERCEPTUAL; - - switch ( profIntent ) { + + switch (profIntent) { case Inkscape::RENDERING_INTENT_RELATIVE_COLORIMETRIC: intent = INTENT_RELATIVE_COLORIMETRIC; break; @@ -291,39 +287,35 @@ void SPImage::apply_profile(Inkscape::Pixbuf *pixbuf) { default: intent = INTENT_PERCEPTUAL; } - + cmsHPROFILE destProf = cmsCreate_sRGBProfile(); - cmsHTRANSFORM transf = cmsCreateTransform( prof, - TYPE_RGBA_8, - destProf, - TYPE_RGBA_8, - intent, 0 ); - if ( transf ) { - guchar* currLine = px; - for ( int y = 0; y < imageheight; y++ ) { + cmsHTRANSFORM transf = cmsCreateTransform(prof, TYPE_RGBA_8, destProf, TYPE_RGBA_8, intent, 0); + if (transf) { + guchar *currLine = px; + for (int y = 0; y < imageheight; y++) { // Since the types are the same size, we can do the transformation in-place - cmsDoTransform( transf, currLine, currLine, imagewidth ); + cmsDoTransform(transf, currLine, currLine, imagewidth); currLine += rowstride; } - cmsDeleteTransform( transf ); + cmsDeleteTransform(transf); } else { - DEBUG_MESSAGE( lcmsSix, "in 's sp_image_update. Unable to create LCMS transform." ); + DEBUG_MESSAGE(lcmsSix, "in 's sp_image_update. Unable to create LCMS transform."); } - cmsCloseProfile( destProf ); + cmsCloseProfile(destProf); } else { - DEBUG_MESSAGE( lcmsSeven, "in 's sp_image_update. Profile type is named color. Can't transform." ); + DEBUG_MESSAGE(lcmsSeven, "in 's sp_image_update. Profile type is named color. Can't transform."); } } else { - DEBUG_MESSAGE( lcmsEight, "in 's sp_image_update. No profile found." ); + DEBUG_MESSAGE(lcmsEight, "in 's sp_image_update. No profile found."); } } } #endif // defined(HAVE_LIBLCMS2) -void SPImage::update(SPCtx *ctx, unsigned int flags) { - +void SPImage::update(SPCtx *ctx, unsigned int flags) +{ SPDocument *doc = this->document; SPItem::update(ctx, flags); @@ -337,19 +329,21 @@ void SPImage::update(SPCtx *ctx, unsigned int flags) { svgdpi = atof(this->getRepr()->attribute("inkscape:svg-dpi")); } this->dpi = svgdpi; - pixbuf = sp_image_repr_read_image(this->getRepr()->attribute("xlink:href"), - this->getRepr()->attribute("sodipodi:absref"), doc->getDocumentBase(), svgdpi); + pixbuf = + sp_image_repr_read_image(this->getRepr()->attribute("xlink:href"), + this->getRepr()->attribute("sodipodi:absref"), doc->getDocumentBase(), svgdpi); if (pixbuf) { #if defined(HAVE_LIBLCMS2) - if ( this->color_profile ) apply_profile( pixbuf ); + if (this->color_profile) + apply_profile(pixbuf); #endif this->pixbuf = pixbuf; } } } - SPItemCtx *ictx = (SPItemCtx *) ctx; + SPItemCtx *ictx = (SPItemCtx *)ctx; // Why continue without a pixbuf? So we can display "Missing Image" png. // Eventually, we should properly support SVG image type (i.e. render it ourselves). @@ -379,22 +373,21 @@ void SPImage::update(SPCtx *ctx, unsigned int flags) { this->calcDimsFromParentViewport(ictx); // Image creates a new viewport - ictx->viewport= Geom::Rect::from_xywh( this->x.computed, this->y.computed, - this->width.computed, this->height.computed); - + ictx->viewport = + Geom::Rect::from_xywh(this->x.computed, this->y.computed, this->width.computed, this->height.computed); + this->clipbox = ictx->viewport; this->ox = this->x.computed; this->oy = this->y.computed; if (this->pixbuf) { - // Viewbox is either from SVG (not supported) or dimensions of pixbuf (PNG, JPG) - this->viewBox = Geom::Rect::from_xywh(0, 0, this->pixbuf->width(), this->pixbuf->height()); + this->viewBox = Geom::Rect::from_xywh(0, 0, this->pixbuf->width(), this->pixbuf->height()); this->viewBox_set = true; // SPItemCtx rctx = - get_rctx( ictx ); + get_rctx(ictx); this->ox = c2p[4]; this->oy = c2p[5]; @@ -402,11 +395,9 @@ void SPImage::update(SPCtx *ctx, unsigned int flags) { this->sy = c2p[3]; } - - // TODO: eliminate ox, oy, sx, sy - sp_image_update_canvas_image ((SPImage *) this); + sp_image_update_canvas_image((SPImage *)this); // don't crash with missing xlink:href attribute if (!this->pixbuf) { @@ -424,8 +415,7 @@ void SPImage::update(SPCtx *ctx, unsigned int flags) { double new_height = this->height.computed * proportion_pixbuf; sp_repr_set_svg_double(this->getRepr(), "width", new_height); } - } - else { + } else { if (proportion_pixbuf != proportion_image) { double new_width = this->width.computed * proportion_pixbuf; sp_repr_set_svg_double(this->getRepr(), "height", new_width); @@ -436,8 +426,9 @@ void SPImage::update(SPCtx *ctx, unsigned int flags) { this->prev_height = this->pixbuf->height(); } -void SPImage::modified(unsigned int flags) { -// SPItem::onModified(flags); +void SPImage::modified(unsigned int flags) +{ + // SPItem::onModified(flags); if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) { for (SPItemView *v = this->display; v != nullptr; v = v->next) { @@ -447,8 +438,8 @@ void SPImage::modified(unsigned int flags) { } } - -Inkscape::XML::Node *SPImage::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags ) { +Inkscape::XML::Node *SPImage::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:image"); } @@ -472,7 +463,7 @@ Inkscape::XML::Node *SPImage::write(Inkscape::XML::Document *xml_doc, Inkscape:: sp_repr_set_svg_double(repr, "height", this->height.computed); } repr->setAttribute("inkscape:svg-dpi", this->getRepr()->attribute("inkscape:svg-dpi")); - //XML Tree being used directly here while it shouldn't be... + // XML Tree being used directly here while it shouldn't be... repr->setAttribute("preserveAspectRatio", this->getRepr()->attribute("preserveAspectRatio")); #if defined(HAVE_LIBLCMS2) if (this->color_profile) { @@ -485,7 +476,8 @@ Inkscape::XML::Node *SPImage::write(Inkscape::XML::Document *xml_doc, Inkscape:: return repr; } -Geom::OptRect SPImage::bbox(Geom::Affine const &transform, SPItem::BBoxType /*type*/) const { +Geom::OptRect SPImage::bbox(Geom::Affine const &transform, SPItem::BBoxType /*type*/) const +{ Geom::OptRect bbox; if ((this->width.computed > 0.0) && (this->height.computed > 0.0)) { @@ -496,8 +488,9 @@ Geom::OptRect SPImage::bbox(Geom::Affine const &transform, SPItem::BBoxType /*ty return bbox; } -void SPImage::print(SPPrintContext *ctx) { - if (this->pixbuf && (this->width.computed > 0.0) && (this->height.computed > 0.0) ) { +void SPImage::print(SPPrintContext *ctx) +{ + if (this->pixbuf && (this->width.computed > 0.0) && (this->height.computed > 0.0)) { Inkscape::Pixbuf *pb = new Inkscape::Pixbuf(*this->pixbuf); pb->ensurePixelFormat(Inkscape::Pixbuf::PF_GDK); @@ -518,45 +511,38 @@ void SPImage::print(SPPrintContext *ctx) { } } -const char* SPImage::displayName() const { +const char *SPImage::displayName() const +{ return _("Image"); } -gchar* SPImage::description() const { +gchar *SPImage::description() const +{ char *href_desc; if (this->href) { - href_desc = (strncmp(this->href, "data:", 5) == 0) - ? g_strdup(_("embedded")) - : xml_quote_strdup(this->href); + href_desc = (strncmp(this->href, "data:", 5) == 0) ? g_strdup(_("embedded")) : xml_quote_strdup(this->href); } else { g_warning("Attempting to call strncmp() with a null pointer."); href_desc = g_strdup("(null_pointer)"); // we call g_free() on href_desc } - char *ret = ( this->pixbuf == nullptr - ? g_strdup_printf(_("[bad reference]: %s"), href_desc) - : g_strdup_printf(_("%d × %d: %s"), - this->pixbuf->width(), - this->pixbuf->height(), - href_desc) ); - - if (this->pixbuf == nullptr && - this->document) - { - Inkscape::Pixbuf * pb = nullptr; + char *ret = (this->pixbuf == nullptr ? g_strdup_printf(_("[bad reference]: %s"), href_desc) + : g_strdup_printf(_("%d × %d: %s"), this->pixbuf->width(), + this->pixbuf->height(), href_desc)); + + if (this->pixbuf == nullptr && this->document) { + Inkscape::Pixbuf *pb = nullptr; double svgdpi = 96; if (this->getRepr()->attribute("inkscape:svg-dpi")) { svgdpi = atof(this->getRepr()->attribute("inkscape:svg-dpi")); } pb = sp_image_repr_read_image(this->getRepr()->attribute("xlink:href"), - this->getRepr()->attribute("sodipodi:absref"), this->document->getDocumentBase(), svgdpi); + this->getRepr()->attribute("sodipodi:absref"), this->document->getDocumentBase(), + svgdpi); if (pb) { - ret = g_strdup_printf(_("%d × %d: %s"), - pb->width(), - pb->height(), - href_desc); + ret = g_strdup_printf(_("%d × %d: %s"), pb->width(), pb->height(), href_desc); delete pb; } } @@ -565,7 +551,8 @@ gchar* SPImage::description() const { return ret; } -Inkscape::DrawingItem* SPImage::show(Inkscape::Drawing &drawing, unsigned int /*key*/, unsigned int /*flags*/) { +Inkscape::DrawingItem *SPImage::show(Inkscape::Drawing &drawing, unsigned int /*key*/, unsigned int /*flags*/) +{ Inkscape::DrawingImage *ai = new Inkscape::DrawingImage(drawing); sp_image_update_arenaitem(this, ai); @@ -592,7 +579,7 @@ Inkscape::Pixbuf *sp_image_repr_read_image(gchar const *href, gchar const *absre Inkscape::Pixbuf *inkpb = nullptr; gchar const *filename = href; - + if (filename != nullptr) { if (g_ascii_strncasecmp(filename, "data:", 5) == 0) { /* data URI - embedded image */ @@ -623,10 +610,12 @@ Inkscape::Pixbuf *sp_image_repr_read_image(gchar const *href, gchar const *absre filename = absref; if (filename != nullptr) { // using absref is outside of SVG rules, so we must at least warn the user - if ( base != nullptr && href != nullptr ) { - g_warning (" did not resolve to a valid image file (base dir is %s), now trying sodipodi:absref=\"%s\"", href, base, absref); + if (base != nullptr && href != nullptr) { + g_warning(" did not resolve to a valid image file (base dir is %s), now trying " + "sodipodi:absref=\"%s\"", + href, base, absref); } else { - g_warning ("xlink:href did not resolve to a valid image file, now trying sodipodi:absref=\"%s\"", absref); + g_warning("xlink:href did not resolve to a valid image file, now trying sodipodi:absref=\"%s\"", absref); } inkpb = Inkscape::Pixbuf::create_from_file(filename, svgdpi); @@ -641,14 +630,13 @@ Inkscape::Pixbuf *sp_image_repr_read_image(gchar const *href, gchar const *absre /* It's included here so if it still does not does load, */ /* our libraries are broken! */ - g_assert (inkpb != nullptr); + g_assert(inkpb != nullptr); return inkpb; } /* We assert that realpixbuf is either NULL or identical size to pixbuf */ -static void -sp_image_update_arenaitem (SPImage *image, Inkscape::DrawingImage *ai) +static void sp_image_update_arenaitem(SPImage *image, Inkscape::DrawingImage *ai) { ai->setStyle(SP_OBJECT(image)->style); ai->setPixbuf(image->pixbuf); @@ -665,16 +653,17 @@ static void sp_image_update_canvas_image(SPImage *image) } } -void SPImage::snappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const { +void SPImage::snappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const +{ /* An image doesn't have any nodes to snap, but still we want to be able snap one image to another. Therefore we will create some snappoints at the corner, similar to a rect. If the image is rotated, then the snappoints will rotate with it. Again, just like a rect. */ if (this->getClipObject()) { - //We are looking at a clipped image: do not return any snappoints, as these might be - //far far away from the visible part from the clipped image - //TODO Do return snappoints, but only when within visual bounding box + // We are looking at a clipped image: do not return any snappoints, as these might be + // far far away from the visible part from the clipped image + // TODO Do return snappoints, but only when within visual bounding box } else { if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_IMG_CORNER)) { // The image has not been clipped: return its corners, which might be rotated for example @@ -683,7 +672,7 @@ void SPImage::snappoints(std::vector &p, Inkscape: double const x1 = x0 + this->width.computed; double const y1 = y0 + this->height.computed; - Geom::Affine const i2d (this->i2dt_affine ()); + Geom::Affine const i2d(this->i2dt_affine()); p.emplace_back(Geom::Point(x0, y0) * i2d, Inkscape::SNAPSOURCE_IMG_CORNER, Inkscape::SNAPTARGET_IMG_CORNER); p.emplace_back(Geom::Point(x0, y1) * i2d, Inkscape::SNAPSOURCE_IMG_CORNER, Inkscape::SNAPTARGET_IMG_CORNER); @@ -698,17 +687,17 @@ void SPImage::snappoints(std::vector &p, Inkscape: * Transform x, y, set x, y, clear translation */ -Geom::Affine SPImage::set_transform(Geom::Affine const &xform) { +Geom::Affine SPImage::set_transform(Geom::Affine const &xform) +{ /* Calculate position in parent coords. */ - Geom::Point pos( Geom::Point(this->x.computed, this->y.computed) * xform ); + Geom::Point pos(Geom::Point(this->x.computed, this->y.computed) * xform); /* This function takes care of translation and scaling, we return whatever parts we can't handle. */ Geom::Affine ret(Geom::Affine(xform).withoutTranslation()); - Geom::Point const scale(hypot(ret[0], ret[1]), - hypot(ret[2], ret[3])); + Geom::Point const scale(hypot(ret[0], ret[1]), hypot(ret[2], ret[3])); - if ( scale[Geom::X] > MAGIC_EPSILON ) { + if (scale[Geom::X] > MAGIC_EPSILON) { ret[0] /= scale[Geom::X]; ret[1] /= scale[Geom::X]; } else { @@ -716,7 +705,7 @@ Geom::Affine SPImage::set_transform(Geom::Affine const &xform) { ret[1] = 0.0; } - if ( scale[Geom::Y] > MAGIC_EPSILON ) { + if (scale[Geom::Y] > MAGIC_EPSILON) { ret[2] /= scale[Geom::Y]; ret[3] /= scale[Geom::Y]; } else { @@ -735,13 +724,14 @@ Geom::Affine SPImage::set_transform(Geom::Affine const &xform) { return ret; } -static void sp_image_set_curve( SPImage *image ) +static void sp_image_set_curve(SPImage *image) { - //create a curve at the image's boundary for snapping - if ((image->height.computed < MAGIC_EPSILON_TOO) || (image->width.computed < MAGIC_EPSILON_TOO) || (image->getClipObject())) { + // create a curve at the image's boundary for snapping + if ((image->height.computed < MAGIC_EPSILON_TOO) || (image->width.computed < MAGIC_EPSILON_TOO) || + (image->getClipObject())) { } else { Geom::OptRect rect = image->bbox(Geom::identity(), SPItem::VISUAL_BBOX); - + if (rect->isFinite()) { image->curve = SPCurve::new_from_rect(*rect, true); } @@ -770,7 +760,7 @@ void sp_embed_image(Inkscape::XML::Node *image_node, Inkscape::Pixbuf *pb) if (data == nullptr) { // if there is no supported MIME data, embed as PNG data_mimetype = "image/png"; - gdk_pixbuf_save_to_buffer(pb->getPixbufRaw(), reinterpret_cast(&data), &len, "png", nullptr, NULL); + gdk_pixbuf_save_to_buffer(pb->getPixbufRaw(), reinterpret_cast(&data), &len, "png", nullptr, NULL); free_data = true; } @@ -779,7 +769,7 @@ void sp_embed_image(Inkscape::XML::Node *image_node, Inkscape::Pixbuf *pb) gsize needed_size = len * 4 / 3 + len * 4 / (3 * 72) + 7; needed_size += 5 + 8 + data_mimetype.size(); // 5 bytes for data: + 8 for ;base64, - gchar *buffer = (gchar *) g_malloc(needed_size); + gchar *buffer = (gchar *)g_malloc(needed_size); gchar *buf_work = buffer; buf_work += g_sprintf(buffer, "data:%s;base64,", data_mimetype.c_str()); @@ -796,17 +786,18 @@ void sp_embed_image(Inkscape::XML::Node *image_node, Inkscape::Pixbuf *pb) image_node->setAttribute("xlink:href", buffer); g_free(buffer); - if (free_data) g_free(data); + if (free_data) + g_free(data); } void sp_embed_svg(Inkscape::XML::Node *image_node, std::string const &fn) { - if (!g_file_test(fn.c_str(), G_FILE_TEST_EXISTS)) { + if (!g_file_test(fn.c_str(), G_FILE_TEST_EXISTS)) { return; } GStatBuf stdir; int val = g_stat(fn.c_str(), &stdir); - if (val == 0 && stdir.st_mode & S_IFDIR){ + if (val == 0 && stdir.st_mode & S_IFDIR) { return; } @@ -817,7 +808,6 @@ void sp_embed_svg(Inkscape::XML::Node *image_node, std::string const &fn) GError *error = nullptr; if (g_file_get_contents(fn.c_str(), &data, &len, &error)) { - if (error != nullptr) { std::cerr << "Pixbuf::create_from_file: " << error->message << std::endl; std::cerr << " (" << fn << ")" << std::endl; @@ -826,13 +816,12 @@ void sp_embed_svg(Inkscape::XML::Node *image_node, std::string const &fn) std::string data_mimetype = "image/svg+xml"; - // Save base64 encoded data in image node // this formula taken from Glib docs gsize needed_size = len * 4 / 3 + len * 4 / (3 * 72) + 7; needed_size += 5 + 8 + data_mimetype.size(); // 5 bytes for data: + 8 for ;base64, - gchar *buffer = (gchar *) g_malloc(needed_size); + gchar *buffer = (gchar *)g_malloc(needed_size); gchar *buf_work = buffer; buf_work += g_sprintf(buffer, "data:%s;base64,", data_mimetype.c_str()); @@ -855,18 +844,18 @@ void sp_embed_svg(Inkscape::XML::Node *image_node, std::string const &fn) void SPImage::refresh_if_outdated() { - if ( href && pixbuf && pixbuf->modificationTime()) { + if (href && pixbuf && pixbuf->modificationTime()) { // It *might* change GStatBuf st; memset(&st, 0, sizeof(st)); int val = 0; - if (g_file_test (pixbuf->originalPath().c_str(), G_FILE_TEST_EXISTS)){ + if (g_file_test(pixbuf->originalPath().c_str(), G_FILE_TEST_EXISTS)) { val = g_stat(pixbuf->originalPath().c_str(), &st); } - if ( !val ) { + if (!val) { // stat call worked. Check time now - if ( st.st_mtime != pixbuf->modificationTime() ) { + if (st.st_mtime != pixbuf->modificationTime()) { requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_IMAGE_HREF_MODIFIED_FLAG); } } diff --git a/src/object/sp-image.h b/src/object/sp-image.h index 1cca325bb382cd596efad7b3ec04961db79818fa..3b32bcbc831c7b3fed8216ecbd861359f546aa58 100644 --- a/src/object/sp-image.h +++ b/src/object/sp-image.h @@ -16,26 +16,33 @@ #define SEEN_INKSCAPE_SP_IMAGE_H #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include -#include "svg/svg-length.h" + +#include "sp-dimensions.h" #include "sp-item.h" +#include "svg/svg-length.h" #include "viewbox.h" -#include "sp-dimensions.h" class SPCurve; #include -#define SP_IMAGE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_IMAGE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_IMAGE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_IMAGE(obj) (dynamic_cast((SPObject *)obj) != NULL) #define SP_IMAGE_HREF_MODIFIED_FLAG SP_OBJECT_USER_MODIFIED_FLAG_A -namespace Inkscape { class Pixbuf; } -class SPImage : public SPItem, public SPViewBox, public SPDimensions { +namespace Inkscape { +class Pixbuf; +} +class SPImage + : public SPItem + , public SPViewBox + , public SPDimensions +{ public: SPImage(); ~SPImage() override; @@ -57,17 +64,19 @@ public: void build(SPDocument *document, Inkscape::XML::Node *repr) override; void release() override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; void modified(unsigned int flags) override; Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; void print(SPPrintContext *ctx) override; - const char* displayName() const override; - char* description() const override; - Inkscape::DrawingItem* show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; - void snappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const override; + const char *displayName() const override; + char *description() const override; + Inkscape::DrawingItem *show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; + void snappoints(std::vector &p, + Inkscape::SnapPreferences const *snapprefs) const override; Geom::Affine set_transform(Geom::Affine const &transform) override; #if defined(HAVE_LIBLCMS2) diff --git a/src/object/sp-item-group.cpp b/src/object/sp-item-group.cpp index bc4c47f4b2d7ebe7030abddb47e1574f04e94cc5..9b271fadeb774096dfaacff94ccda16141b9dc00 100644 --- a/src/object/sp-item-group.cpp +++ b/src/object/sp-item-group.cpp @@ -15,64 +15,65 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include +#include #include #include "attributes.h" -#include "document.h" -#include "document-undo.h" -#include "selection-chemistry.h" -#include "verbs.h" - -#include "display/drawing-group.h" +#include "box3d.h" #include "display/curve.h" +#include "display/drawing-group.h" +#include "document-undo.h" +#include "document.h" #include "live_effects/effect.h" -#include "live_effects/lpeobject.h" #include "live_effects/lpeobject-reference.h" -#include "svg/svg.h" -#include "svg/css-ostringstream.h" -#include "xml/repr.h" -#include "xml/sp-css-attr.h" - -#include "box3d.h" +#include "live_effects/lpeobject.h" #include "persp3d.h" +#include "selection-chemistry.h" +#include "sp-clippath.h" #include "sp-defs.h" +#include "sp-desc.h" +#include "sp-flowtext.h" #include "sp-item-transform.h" -#include "sp-root.h" -#include "sp-rect.h" -#include "sp-offset.h" -#include "sp-clippath.h" #include "sp-mask.h" +#include "sp-offset.h" #include "sp-path.h" -#include "sp-use.h" -#include "sp-title.h" -#include "sp-desc.h" +#include "sp-rect.h" +#include "sp-root.h" #include "sp-switch.h" #include "sp-textpath.h" -#include "sp-flowtext.h" +#include "sp-title.h" +#include "sp-use.h" #include "style.h" +#include "svg/css-ostringstream.h" +#include "svg/svg.h" +#include "verbs.h" +#include "xml/repr.h" +#include "xml/sp-css-attr.h" using Inkscape::DocumentUndo; -static void sp_group_perform_patheffect(SPGroup *group, SPGroup *top_group, Inkscape::LivePathEffect::Effect *lpe, bool write); +static void sp_group_perform_patheffect(SPGroup *group, SPGroup *top_group, Inkscape::LivePathEffect::Effect *lpe, + bool write); -SPGroup::SPGroup() : SPLPEItem(), - _expanded(false), - _insert_bottom(false), - _layer_mode(SPGroup::GROUP) -{ -} +SPGroup::SPGroup() + : SPLPEItem() + , _expanded(false) + , _insert_bottom(false) + , _layer_mode(SPGroup::GROUP) +{} SPGroup::~SPGroup() = default; -void SPGroup::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPGroup::build(SPDocument *document, Inkscape::XML::Node *repr) +{ this->readAttr(SPAttr::INKSCAPE_GROUPMODE); SPLPEItem::build(document, repr); } -void SPGroup::release() { +void SPGroup::release() +{ if (this->_layer_mode == SPGroup::LAYER) { this->document->removeResource("layer", this); } @@ -80,34 +81,35 @@ void SPGroup::release() { SPLPEItem::release(); } -void SPGroup::child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) { +void SPGroup::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ SPLPEItem::child_added(child, ref); SPObject *last_child = this->lastChild(); if (last_child && last_child->getRepr() == child) { // optimization for the common special case where the child is being added at the end SPItem *item = dynamic_cast(last_child); - if ( item ) { + if (item) { /* TODO: this should be moved into SPItem somehow */ SPItemView *v; for (v = this->display; v != nullptr; v = v->next) { - Inkscape::DrawingItem *ac = item->invoke_show (v->arenaitem->drawing(), v->key, v->flags); + Inkscape::DrawingItem *ac = item->invoke_show(v->arenaitem->drawing(), v->key, v->flags); if (ac) { v->arenaitem->appendChild(ac); } } } - } else { // general case + } else { // general case SPItem *item = dynamic_cast(get_child_by_repr(child)); - if ( item ) { + if (item) { /* TODO: this should be moved into SPItem somehow */ SPItemView *v; unsigned position = item->pos_in_parent(); for (v = this->display; v != nullptr; v = v->next) { - Inkscape::DrawingItem *ac = item->invoke_show (v->arenaitem->drawing(), v->key, v->flags); + Inkscape::DrawingItem *ac = item->invoke_show(v->arenaitem->drawing(), v->key, v->flags); if (ac) { v->arenaitem->prependChild(ac); @@ -121,22 +123,23 @@ void SPGroup::child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) /* fixme: hide (Lauris) */ -void SPGroup::remove_child(Inkscape::XML::Node *child) { +void SPGroup::remove_child(Inkscape::XML::Node *child) +{ SPLPEItem::remove_child(child); this->requestModified(SP_OBJECT_MODIFIED_FLAG); } -void SPGroup::order_changed (Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref) +void SPGroup::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref) { SPLPEItem::order_changed(child, old_ref, new_ref); SPItem *item = dynamic_cast(get_child_by_repr(child)); - if ( item ) { + if (item) { /* TODO: this should be moved into SPItem somehow */ SPItemView *v; unsigned position = item->pos_in_parent(); - for ( v = item->display ; v != nullptr ; v = v->next ) { + for (v = item->display; v != nullptr; v = v->next) { v->arenaitem->setZOrder(position); } } @@ -144,21 +147,22 @@ void SPGroup::order_changed (Inkscape::XML::Node *child, Inkscape::XML::Node *ol this->requestModified(SP_OBJECT_MODIFIED_FLAG); } -void SPGroup::update(SPCtx *ctx, unsigned int flags) { +void SPGroup::update(SPCtx *ctx, unsigned int flags) +{ // std::cout << "SPGroup::update(): " << (getId()?getId():"null") << std::endl; SPItemCtx *ictx, cctx; - ictx = (SPItemCtx *) ctx; + ictx = (SPItemCtx *)ctx; cctx = *ictx; unsigned childflags = flags; if (flags & SP_OBJECT_MODIFIED_FLAG) { - childflags |= SP_OBJECT_PARENT_MODIFIED_FLAG; + childflags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } childflags &= SP_OBJECT_MODIFIED_CASCADE; - std::vector l=this->childList(true, SPObject::ActionUpdate); - for(auto child : l){ + std::vector l = this->childList(true, SPObject::ActionUpdate); + for (auto child : l) { if (childflags || (child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { SPItem *item = dynamic_cast(child); if (item) { @@ -182,7 +186,7 @@ void SPGroup::update(SPCtx *ctx, unsigned int flags) { if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) { for (SPItemView *v = this->display; v != nullptr; v = v->next) { Inkscape::DrawingGroup *group = dynamic_cast(v->arenaitem); - if( this->parent ) { + if (this->parent) { this->context_style = this->parent->context_style; } group->setStyle(this->style, this->context_style); @@ -190,8 +194,9 @@ void SPGroup::update(SPCtx *ctx, unsigned int flags) { } } -void SPGroup::modified(guint flags) { - //std::cout << "SPGroup::modified(): " << (getId()?getId():"null") << std::endl; +void SPGroup::modified(guint flags) +{ + // std::cout << "SPGroup::modified(): " << (getId()?getId():"null") << std::endl; SPLPEItem::modified(flags); if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; @@ -206,8 +211,8 @@ void SPGroup::modified(guint flags) { } } - std::vector l=this->childList(true); - for(auto child : l){ + std::vector l = this->childList(true); + for (auto child : l) { if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->emitModified(flags); } @@ -216,7 +221,8 @@ void SPGroup::modified(guint flags) { } } -Inkscape::XML::Node* SPGroup::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPGroup::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if (flags & SP_OBJECT_WRITE_BUILD) { std::vector l; @@ -228,8 +234,8 @@ Inkscape::XML::Node* SPGroup::write(Inkscape::XML::Document *xml_doc, Inkscape:: } } - for (auto& child: children) { - if ( !dynamic_cast(&child) && !dynamic_cast(&child) ) { + for (auto &child : children) { + if (!dynamic_cast(&child) && !dynamic_cast(&child)) { Inkscape::XML::Node *crepr = child.updateRepr(xml_doc, nullptr, flags); if (crepr) { @@ -237,25 +243,25 @@ Inkscape::XML::Node* SPGroup::write(Inkscape::XML::Document *xml_doc, Inkscape:: } } } - for (auto i=l.rbegin();i!=l.rend();++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { - if ( !dynamic_cast(&child) && !dynamic_cast(&child) ) { + for (auto &child : children) { + if (!dynamic_cast(&child) && !dynamic_cast(&child)) { child.updateRepr(flags); } } } - if ( flags & SP_OBJECT_WRITE_EXT ) { + if (flags & SP_OBJECT_WRITE_EXT) { const char *value; - if ( _layer_mode == SPGroup::LAYER ) { + if (_layer_mode == SPGroup::LAYER) { value = "layer"; - } else if ( _layer_mode == SPGroup::MASK_HELPER ) { + } else if (_layer_mode == SPGroup::MASK_HELPER) { value = "maskhelper"; - } else if ( flags & SP_OBJECT_WRITE_ALL ) { + } else if (flags & SP_OBJECT_WRITE_ALL) { value = "group"; } else { value = nullptr; @@ -274,8 +280,8 @@ Geom::OptRect SPGroup::bbox(Geom::Affine const &transform, SPItem::BBoxType bbox Geom::OptRect bbox; // TODO CPPIFY: replace this const_cast later - std::vector l = const_cast(this)->childList(false, SPObject::ActionBBox); - for(auto o : l){ + std::vector l = const_cast(this)->childList(false, SPObject::ActionBBox); + for (auto o : l) { SPItem *item = dynamic_cast(o); if (item && !item->isHidden()) { Geom::Affine const ct(item->transform * transform); @@ -286,8 +292,9 @@ Geom::OptRect SPGroup::bbox(Geom::Affine const &transform, SPItem::BBoxType bbox return bbox; } -void SPGroup::print(SPPrintContext *ctx) { - for(auto& child: children){ +void SPGroup::print(SPPrintContext *ctx) +{ + for (auto &child : children) { SPObject *o = &child; SPItem *item = dynamic_cast(o); if (item) { @@ -296,22 +303,24 @@ void SPGroup::print(SPPrintContext *ctx) { } } -const char *SPGroup::displayName() const { +const char *SPGroup::displayName() const +{ return _("Group"); } -gchar *SPGroup::description() const { +gchar *SPGroup::description() const +{ gint len = this->getItemCount(); - return g_strdup_printf( - ngettext(_("of %d object"), _("of %d objects"), len), len); + return g_strdup_printf(ngettext(_("of %d object"), _("of %d objects"), len), len); } -void SPGroup::set(SPAttr key, gchar const* value) { +void SPGroup::set(SPAttr key, gchar const *value) +{ switch (key) { case SPAttr::INKSCAPE_GROUPMODE: - if ( value && !strcmp(value, "layer") ) { + if (value && !strcmp(value, "layer")) { this->setLayerMode(SPGroup::LAYER); - } else if ( value && !strcmp(value, "maskhelper") ) { + } else if (value && !strcmp(value, "maskhelper")) { this->setLayerMode(SPGroup::MASK_HELPER); } else { this->setLayerMode(SPGroup::GROUP); @@ -324,13 +333,14 @@ void SPGroup::set(SPAttr key, gchar const* value) { } } -Inkscape::DrawingItem *SPGroup::show (Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) { +Inkscape::DrawingItem *SPGroup::show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) +{ // std::cout << "SPGroup::show(): " << (getId()?getId():"null") << std::endl; Inkscape::DrawingGroup *ai; ai = new Inkscape::DrawingGroup(drawing); ai->setPickChildren(this->effectiveLayerMode(key) == SPGroup::LAYER); - if( this->parent ) { + if (this->parent) { this->context_style = this->parent->context_style; } ai->setStyle(this->style, this->context_style); @@ -339,22 +349,22 @@ Inkscape::DrawingItem *SPGroup::show (Inkscape::Drawing &drawing, unsigned int k return ai; } -void SPGroup::hide (unsigned int key) { - std::vector l=this->childList(false, SPObject::ActionShow); - for(auto o : l){ +void SPGroup::hide(unsigned int key) +{ + std::vector l = this->childList(false, SPObject::ActionShow); + for (auto o : l) { SPItem *item = dynamic_cast(o); if (item) { item->invoke_hide(key); } } -// SPLPEItem::onHide(key); + // SPLPEItem::onHide(key); } - -void SPGroup::snappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const { - for (auto& o: children) - { +void SPGroup::snappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const +{ + for (auto &o : children) { SPItem const *item = dynamic_cast(&o); if (item) { item->getSnappoints(p, snapprefs); @@ -364,7 +374,8 @@ void SPGroup::snappoints(std::vector &p, Inkscape: void sp_item_group_ungroup_handle_clones(SPItem *parent, Geom::Affine const g) { - for(std::list::const_iterator refd=parent->hrefList.begin();refd!=parent->hrefList.end();++refd){ + for (std::list::const_iterator refd = parent->hrefList.begin(); refd != parent->hrefList.end(); + ++refd) { SPItem *citem = dynamic_cast(*refd); if (citem && !citem->cloned) { SPUse *useitem = dynamic_cast(citem); @@ -379,14 +390,14 @@ void sp_item_group_ungroup_handle_clones(SPItem *parent, Geom::Affine const g) } } -void -sp_recursive_scale_text_size(Inkscape::XML::Node *repr, double scale){ - for (Inkscape::XML::Node *child = repr->firstChild() ; child; child = child->next() ){ - if ( child) { +void sp_recursive_scale_text_size(Inkscape::XML::Node *repr, double scale) +{ + for (Inkscape::XML::Node *child = repr->firstChild(); child; child = child->next()) { + if (child) { sp_recursive_scale_text_size(child, scale); } } - SPCSSAttr * css = sp_repr_css_attr(repr,"style"); + SPCSSAttr *css = sp_repr_css_attr(repr, "style"); Glib::ustring element = g_quark_to_string(repr->code()); if ((css && element == "svg:text") || element == "svg:tspan") { gchar const *w = sp_repr_css_property(css, "font-size", nullptr); @@ -399,7 +410,7 @@ sp_recursive_scale_text_size(Inkscape::XML::Node *repr, double scale){ os << wd << units; // reattach units sp_repr_css_set_property(css, "font-size", os.str().c_str()); Glib::ustring css_str; - sp_repr_css_write_string(css,css_str); + sp_repr_css_write_string(css, css_str); repr->setAttributeOrRemoveIfEmpty("style", css_str); } } @@ -414,7 +425,7 @@ sp_recursive_scale_text_size(Inkscape::XML::Node *repr, double scale){ os << wd << units; // reattach units sp_repr_css_set_property(css, "letter-spacing", os.str().c_str()); Glib::ustring css_str; - sp_repr_css_write_string(css,css_str); + sp_repr_css_write_string(css, css_str); repr->setAttributeOrRemoveIfEmpty("style", css_str); } } @@ -429,13 +440,13 @@ sp_recursive_scale_text_size(Inkscape::XML::Node *repr, double scale){ os << wd << units; // reattach units sp_repr_css_set_property(css, "word-spacing", os.str().c_str()); Glib::ustring css_str; - sp_repr_css_write_string(css,css_str); + sp_repr_css_write_string(css, css_str); repr->setAttributeOrRemoveIfEmpty("style", css_str); } } gchar const *dx = repr->attribute("dx"); if (dx) { - gchar ** dxarray = g_strsplit(dx, " ", 0); + gchar **dxarray = g_strsplit(dx, " ", 0); Inkscape::SVGOStringStream dx_data; while (*dxarray != nullptr) { double pos; @@ -448,7 +459,7 @@ sp_recursive_scale_text_size(Inkscape::XML::Node *repr, double scale){ } gchar const *dy = repr->attribute("dy"); if (dy) { - gchar ** dyarray = g_strsplit(dy, " ", 0); + gchar **dyarray = g_strsplit(dy, " ", 0); Inkscape::SVGOStringStream dy_data; while (*dyarray != nullptr) { double pos; @@ -462,10 +473,9 @@ sp_recursive_scale_text_size(Inkscape::XML::Node *repr, double scale){ } } -void -sp_item_group_ungroup (SPGroup *group, std::vector &children, bool do_done) +void sp_item_group_ungroup(SPGroup *group, std::vector &children, bool do_done) { - g_return_if_fail (group != nullptr); + g_return_if_fail(group != nullptr); SPDocument *doc = group->document; SPRoot *root = doc->getRoot(); @@ -473,10 +483,8 @@ sp_item_group_ungroup (SPGroup *group, std::vector &children, bool do_d Inkscape::XML::Node *grepr = group->getRepr(); - g_return_if_fail (!strcmp (grepr->name(), "svg:g") - || !strcmp (grepr->name(), "svg:a") - || !strcmp (grepr->name(), "svg:switch") - || !strcmp (grepr->name(), "svg:svg")); + g_return_if_fail(!strcmp(grepr->name(), "svg:g") || !strcmp(grepr->name(), "svg:a") || + !strcmp(grepr->name(), "svg:switch") || !strcmp(grepr->name(), "svg:svg")); // this converts the gradient/pattern fill/stroke on the group, if any, to userSpaceOnUse group->adjust_paint_recursive(Geom::identity(), Geom::identity()); @@ -499,13 +507,13 @@ sp_item_group_ungroup (SPGroup *group, std::vector &children, bool do_d std::vector objects; Geom::Affine const g(group->transform); - for (auto& child: group->children) { + for (auto &child : group->children) { if (SPItem *citem = dynamic_cast(&child)) { sp_item_group_ungroup_handle_clones(citem, g); } } - for (auto& child: group->children) { + for (auto &child : group->children) { SPItem *citem = dynamic_cast(&child); if (citem) { /* Merging of style */ @@ -513,7 +521,7 @@ sp_item_group_ungroup (SPGroup *group, std::vector &children, bool do_d // it here _before_ the new transform is set, so as to use the pre-transform bbox citem->adjust_paint_recursive(Geom::identity(), Geom::identity()); - child.style->merge( group->style ); + child.style->merge(group->style); /* * fixme: We currently make no allowance for the case where child is cloned * and the group has any style settings. @@ -541,20 +549,20 @@ sp_item_group_ungroup (SPGroup *group, std::vector &children, bool do_d // Merging transform Geom::Affine ctrans = citem->transform * g; - // We should not apply the group's transformation to both a linked offset AND to its source - if (dynamic_cast(citem)) { // Do we have an offset at hand (whether it's dynamic or linked)? - SPItem *source = sp_offset_get_source(dynamic_cast(citem)); - // When dealing with a chain of linked offsets, the transformation of an offset will be - // tied to the transformation of the top-most source, not to any of the intermediate - // offsets. So let's find the top-most source - while (source != nullptr && dynamic_cast(source)) { - source = sp_offset_get_source(dynamic_cast(source)); - } - if (source != nullptr && // If true then we must be dealing with a linked offset ... - group->isAncestorOf(source) ) { // ... of which the source is in the same group - ctrans = citem->transform; // then we should apply the transformation of the group to the offset - } + // We should not apply the group's transformation to both a linked offset AND to its source + if (dynamic_cast(citem)) { // Do we have an offset at hand (whether it's dynamic or linked)? + SPItem *source = sp_offset_get_source(dynamic_cast(citem)); + // When dealing with a chain of linked offsets, the transformation of an offset will be + // tied to the transformation of the top-most source, not to any of the intermediate + // offsets. So let's find the top-most source + while (source != nullptr && dynamic_cast(source)) { + source = sp_offset_get_source(dynamic_cast(source)); + } + if (source != nullptr && // If true then we must be dealing with a linked offset ... + group->isAncestorOf(source)) { // ... of which the source is in the same group + ctrans = citem->transform; // then we should apply the transformation of the group to the offset } + } // FIXME: constructing a transform that would fully preserve the appearance of a // textpath if it is ungrouped with its path seems to be impossible in general @@ -566,11 +574,12 @@ sp_item_group_ungroup (SPGroup *group, std::vector &children, bool do_d // This is just a way to temporarily remember the transform in repr. When repr is // reattached outside of the group, the transform will be written more properly // (i.e. optimized into the object if the corresponding preference is set) - gchar *affinestr=sp_svg_transform_write(ctrans); - SPText * text = dynamic_cast(citem); + gchar *affinestr = sp_svg_transform_write(ctrans); + SPText *text = dynamic_cast(citem); if (text) { - //this causes a change in text-on-path appearance when there is a non-conformal transform, see bug #1594565 - SPTextPath * text_path = dynamic_cast(text->firstChild()); + // this causes a change in text-on-path appearance when there is a non-conformal transform, see bug + // #1594565 + SPTextPath *text_path = dynamic_cast(text->firstChild()); if (!text_path) { nrepr->setAttribute("transform", affinestr); } else { @@ -605,7 +614,7 @@ sp_item_group_ungroup (SPGroup *group, std::vector &children, bool do_d /* Step 3 - add nonitems */ if (!objects.empty()) { Inkscape::XML::Node *last_def = defs->getRepr()->lastChild(); - for (auto i=objects.rbegin();i!=objects.rend();++i) { + for (auto i = objects.rbegin(); i != objects.rend(); ++i) { Inkscape::XML::Node *repr = *i; if (!sp_repr_is_meta_element(repr)) { defs->getRepr()->addChild(repr, last_def); @@ -615,7 +624,7 @@ sp_item_group_ungroup (SPGroup *group, std::vector &children, bool do_d } /* Step 4 - add items */ - for (auto i=items.rbegin();i!=items.rend();++i) { + for (auto i = items.rbegin(); i != items.rend(); ++i) { Inkscape::XML::Node *repr = *i; // add item // restore position; since the items list was prepended (i.e. reverse), we now add @@ -627,7 +636,7 @@ sp_item_group_ungroup (SPGroup *group, std::vector &children, bool do_d if (item) { item->doWriteTransform(item->transform, nullptr, false); - children.insert(children.begin(),item); + children.insert(children.begin(), item); item->requestModified(SP_OBJECT_MODIFIED_FLAG); } else { g_assert_not_reached(); @@ -644,14 +653,14 @@ sp_item_group_ungroup (SPGroup *group, std::vector &children, bool do_d * some API for list aspect of SPGroup */ -std::vector sp_item_group_item_list(SPGroup * group) +std::vector sp_item_group_item_list(SPGroup *group) { - std::vector s; + std::vector s; g_return_val_if_fail(group != nullptr, s); - for (auto& o: group->children) { - if ( dynamic_cast(&o) ) { - s.push_back((SPItem*)&o); + for (auto &o : group->children) { + if (dynamic_cast(&o)) { + s.push_back((SPItem *)&o); } } return s; @@ -660,17 +669,18 @@ std::vector sp_item_group_item_list(SPGroup * group) SPObject *sp_item_group_get_child_by_name(SPGroup *group, SPObject *ref, const gchar *name) { SPObject *child = (ref) ? ref->getNext() : group->firstChild(); - while ( child && strcmp(child->getRepr()->name(), name) ) { + while (child && strcmp(child->getRepr()->name(), name)) { child = child->getNext(); } return child; } -void SPGroup::setLayerMode(LayerMode mode) { - if ( _layer_mode != mode ) { - if ( mode == LAYER ) { +void SPGroup::setLayerMode(LayerMode mode) +{ + if (_layer_mode != mode) { + if (mode == LAYER) { this->document->addResource("layer", this); - } else if ( _layer_mode == LAYER ) { + } else if (_layer_mode == LAYER) { this->document->removeResource("layer", this); } _layer_mode = mode; @@ -678,39 +688,44 @@ void SPGroup::setLayerMode(LayerMode mode) { } } -SPGroup::LayerMode SPGroup::layerDisplayMode(unsigned int dkey) const { +SPGroup::LayerMode SPGroup::layerDisplayMode(unsigned int dkey) const +{ std::map::const_iterator iter; iter = _display_modes.find(dkey); - if ( iter != _display_modes.end() ) { + if (iter != _display_modes.end()) { return (*iter).second; } else { return GROUP; } } -void SPGroup::setExpanded(bool isexpanded) { - if ( _expanded != isexpanded ){ +void SPGroup::setExpanded(bool isexpanded) +{ + if (_expanded != isexpanded) { _expanded = isexpanded; } } -void SPGroup::setInsertBottom(bool insertbottom) { - if ( _insert_bottom != insertbottom) { +void SPGroup::setInsertBottom(bool insertbottom) +{ + if (_insert_bottom != insertbottom) { _insert_bottom = insertbottom; } } -void SPGroup::setLayerDisplayMode(unsigned int dkey, SPGroup::LayerMode mode) { - if ( layerDisplayMode(dkey) != mode ) { +void SPGroup::setLayerDisplayMode(unsigned int dkey, SPGroup::LayerMode mode) +{ + if (layerDisplayMode(dkey) != mode) { _display_modes[dkey] = mode; _updateLayerMode(dkey); } } -void SPGroup::_updateLayerMode(unsigned int display_key) { +void SPGroup::_updateLayerMode(unsigned int display_key) +{ SPItemView *view; - for ( view = this->display ; view ; view = view->next ) { - if ( !display_key || view->key == display_key ) { + for (view = this->display; view; view = view->next) { + if (!display_key || view->key == display_key) { Inkscape::DrawingGroup *g = dynamic_cast(view->arenaitem); if (g) { g->setPickChildren(effectiveLayerMode(view->key) == SPGroup::LAYER); @@ -721,10 +736,10 @@ void SPGroup::_updateLayerMode(unsigned int display_key) { void SPGroup::translateChildItems(Geom::Translate const &tr) { - if ( hasChildren() ) { - for (auto& o: children) { + if (hasChildren()) { + for (auto &o : children) { SPItem *item = dynamic_cast(&o); - if ( item ) { + if (item) { item->move_rel(tr); } } @@ -734,15 +749,15 @@ void SPGroup::translateChildItems(Geom::Translate const &tr) // Recursively (or not) scale child items around a point void SPGroup::scaleChildItemsRec(Geom::Scale const &sc, Geom::Point const &p, bool noRecurse) { - if ( hasChildren() ) { - for (auto& o: children) { - if ( SPDefs *defs = dynamic_cast(&o) ) { // select symbols from defs, ignore clips, masks, patterns - for (auto& defschild: defs->children) { + if (hasChildren()) { + for (auto &o : children) { + if (SPDefs *defs = dynamic_cast(&o)) { // select symbols from defs, ignore clips, masks, patterns + for (auto &defschild : defs->children) { SPGroup *defsgroup = dynamic_cast(&defschild); if (defsgroup) defsgroup->scaleChildItemsRec(sc, p, false); } - } else if ( SPItem *item = dynamic_cast(&o) ) { + } else if (SPItem *item = dynamic_cast(&o)) { SPGroup *group = dynamic_cast(item); if (group && !dynamic_cast(item)) { /* Using recursion breaks clipping because transforms are applied @@ -753,7 +768,7 @@ void SPGroup::scaleChildItemsRec(Geom::Scale const &sc, Geom::Point const &p, bo involved with showing/modifying units. So offer both for use in different contexts. */ - if(noRecurse) { + if (noRecurse) { // used for EMF import Geom::Translate const s(p); Geom::Affine final = s.inverse() * sc * s; @@ -763,9 +778,9 @@ void SPGroup::scaleChildItemsRec(Geom::Scale const &sc, Geom::Point const &p, bo // Eliminate common rounding error affecting EMF/WMF input. // When the rounding error persists it converts the simple // transform=scale() to transform=matrix(). - if(std::abs(tAff[4]) < 1.0e-5 && std::abs(tAff[5]) < 1.0e-5){ - tAff[4] = 0.0; - tAff[5] = 0.0; + if (std::abs(tAff[4]) < 1.0e-5 && std::abs(tAff[5]) < 1.0e-5) { + tAff[4] = 0.0; + tAff[5] = 0.0; } item->doWriteTransform(tAff, nullptr, true); } else { @@ -775,90 +790,93 @@ void SPGroup::scaleChildItemsRec(Geom::Scale const &sc, Geom::Point const &p, bo sub_item = dynamic_cast(item->getClipObject()->firstChild()); } if (sub_item != nullptr) { - sub_item->doWriteTransform(sub_item->transform*sc, nullptr, true); + sub_item->doWriteTransform(sub_item->transform * sc, nullptr, true); } sub_item = nullptr; if (item->getMaskObject()) { sub_item = dynamic_cast(item->getMaskObject()->firstChild()); } if (sub_item != nullptr) { - sub_item->doWriteTransform(sub_item->transform*sc, nullptr, true); + sub_item->doWriteTransform(sub_item->transform * sc, nullptr, true); } - item->doWriteTransform(sc.inverse()*item->transform*sc, nullptr, true); + item->doWriteTransform(sc.inverse() * item->transform * sc, nullptr, true); group->scaleChildItemsRec(sc, p, false); } } else { -// Geom::OptRect bbox = item->desktopVisualBounds(); -// if (bbox) { // test not needed, this was causing a failure to scale and in the clipboard, see LP Bug 1365451 - // Scale item - Geom::Translate const s(p); - Geom::Affine final = s.inverse() * sc * s; - - gchar const *conn_type = nullptr; - SPText *text_item = dynamic_cast(item); - bool is_text_path = text_item && text_item->firstChild() && dynamic_cast(text_item->firstChild()); - if (is_text_path) { - text_item->optimizeTextpathText(); + // Geom::OptRect bbox = item->desktopVisualBounds(); + // if (bbox) { // test not needed, this was causing a failure to scale + // and in the clipboard, see LP Bug 1365451 + // Scale item + Geom::Translate const s(p); + Geom::Affine final = s.inverse() * sc * s; + + gchar const *conn_type = nullptr; + SPText *text_item = dynamic_cast(item); + bool is_text_path = + text_item && text_item->firstChild() && dynamic_cast(text_item->firstChild()); + if (is_text_path) { + text_item->optimizeTextpathText(); + } else { + SPFlowtext *flowText = dynamic_cast(item); + if (flowText) { + flowText->optimizeScaledText(); } else { - SPFlowtext *flowText = dynamic_cast(item); - if (flowText) { - flowText->optimizeScaledText(); - } else { - SPBox3D *box = dynamic_cast(item); - if (box) { - // Force recalculation from perspective - box->position_set(); - } else if (item->getAttribute("inkscape:connector-type") != nullptr - && (item->getAttribute("inkscape:connection-start") == nullptr - || item->getAttribute("inkscape:connection-end") == nullptr)) { - // Remove and store connector type for transform if disconnected - conn_type = item->getAttribute("inkscape:connector-type"); - item->removeAttribute("inkscape:connector-type"); - } + SPBox3D *box = dynamic_cast(item); + if (box) { + // Force recalculation from perspective + box->position_set(); + } else if (item->getAttribute("inkscape:connector-type") != nullptr && + (item->getAttribute("inkscape:connection-start") == nullptr || + item->getAttribute("inkscape:connection-end") == nullptr)) { + // Remove and store connector type for transform if disconnected + conn_type = item->getAttribute("inkscape:connector-type"); + item->removeAttribute("inkscape:connector-type"); } } + } - Persp3D *persp = dynamic_cast(item); - if (persp) { - persp->apply_affine_transformation(final); - } else if (is_text_path && !item->transform.isIdentity()) { - // Save and reset current transform - Geom::Affine tmp(item->transform); - item->transform = Geom::Affine(); - // Apply scale - item->set_i2d_affine(item->i2dt_affine() * sc); - item->doWriteTransform(item->transform, nullptr, true); - // Scale translation and restore original transform - tmp[4] *= sc[0]; - tmp[5] *= sc[1]; - item->doWriteTransform(tmp, nullptr, true); - } else if (dynamic_cast(item)) { - // calculate the matrix we need to apply to the clone - // to cancel its induced transform from its original - Geom::Affine move = final.inverse() * item->transform * final; - item->doWriteTransform(move, &move, true); - } else { - item->doWriteTransform(item->transform*sc, nullptr, true); - } + Persp3D *persp = dynamic_cast(item); + if (persp) { + persp->apply_affine_transformation(final); + } else if (is_text_path && !item->transform.isIdentity()) { + // Save and reset current transform + Geom::Affine tmp(item->transform); + item->transform = Geom::Affine(); + // Apply scale + item->set_i2d_affine(item->i2dt_affine() * sc); + item->doWriteTransform(item->transform, nullptr, true); + // Scale translation and restore original transform + tmp[4] *= sc[0]; + tmp[5] *= sc[1]; + item->doWriteTransform(tmp, nullptr, true); + } else if (dynamic_cast(item)) { + // calculate the matrix we need to apply to the clone + // to cancel its induced transform from its original + Geom::Affine move = final.inverse() * item->transform * final; + item->doWriteTransform(move, &move, true); + } else { + item->doWriteTransform(item->transform * sc, nullptr, true); + } - if (conn_type != nullptr) { - item->setAttribute("inkscape:connector-type", conn_type); - } + if (conn_type != nullptr) { + item->setAttribute("inkscape:connector-type", conn_type); + } - if (item->isCenterSet() && !(final.isTranslation() || final.isIdentity())) { - item->scaleCenter(sc); // All coordinates have been scaled, so also the center must be scaled - item->updateRepr(); - } -// } + if (item->isCenterSet() && !(final.isTranslation() || final.isIdentity())) { + item->scaleCenter(sc); // All coordinates have been scaled, so also the center must be scaled + item->updateRepr(); + } + // } } } } } } -gint SPGroup::getItemCount() const { +gint SPGroup::getItemCount() const +{ gint len = 0; - for (auto& child: children) { + for (auto &child : children) { if (dynamic_cast(&child)) { len++; } @@ -867,13 +885,14 @@ gint SPGroup::getItemCount() const { return len; } -void SPGroup::_showChildren (Inkscape::Drawing &drawing, Inkscape::DrawingItem *ai, unsigned int key, unsigned int flags) { +void SPGroup::_showChildren(Inkscape::Drawing &drawing, Inkscape::DrawingItem *ai, unsigned int key, unsigned int flags) +{ Inkscape::DrawingItem *ac = nullptr; - std::vector l=this->childList(false, SPObject::ActionShow); - for(auto o : l){ - SPItem * child = dynamic_cast(o); + std::vector l = this->childList(false, SPObject::ActionShow); + for (auto o : l) { + SPItem *child = dynamic_cast(o); if (child) { - ac = child->invoke_show (drawing, key, flags); + ac = child->invoke_show(drawing, key, flags); if (ac) { ai->appendChild(ac); } @@ -881,11 +900,12 @@ void SPGroup::_showChildren (Inkscape::Drawing &drawing, Inkscape::DrawingItem * } } -void SPGroup::update_patheffect(bool write) { +void SPGroup::update_patheffect(bool write) +{ #ifdef GROUP_VERBOSE g_message("sp_group_update_patheffect: %p\n", lpeitem); #endif - std::vector const item_list = sp_item_group_item_list(this); + std::vector const item_list = sp_item_group_item_list(this); for (auto sub_item : item_list) { if (sub_item) { @@ -913,18 +933,18 @@ void SPGroup::update_patheffect(bool write) { } } -static void -sp_group_perform_patheffect(SPGroup *group, SPGroup *top_group, Inkscape::LivePathEffect::Effect *lpe, bool write) +static void sp_group_perform_patheffect(SPGroup *group, SPGroup *top_group, Inkscape::LivePathEffect::Effect *lpe, + bool write) { - std::vector const item_list = sp_item_group_item_list(group); + std::vector const item_list = sp_item_group_item_list(group); for (auto sub_item : item_list) { SPGroup *sub_group = dynamic_cast(sub_item); if (sub_group) { sp_group_perform_patheffect(sub_group, top_group, lpe, write); } else { - SPShape* sub_shape = dynamic_cast(sub_item); - //SPPath* sub_path = dynamic_cast(sub_item); - SPItem* clipmaskto = dynamic_cast(sub_item); + SPShape *sub_shape = dynamic_cast(sub_item); + // SPPath* sub_path = dynamic_cast(sub_item); + SPItem *clipmaskto = dynamic_cast(sub_item); if (clipmaskto) { top_group->applyToClipPath(clipmaskto, lpe); top_group->applyToMask(clipmaskto, lpe); @@ -957,7 +977,7 @@ sp_group_perform_patheffect(SPGroup *group, SPGroup *top_group, Inkscape::LivePa } } else { // LPE was unsuccessful or doeffect stack return null. Read the old 'd'-attribute. - if (gchar const * value = repr->attribute("d")) { + if (gchar const *value = repr->attribute("d")) { Geom::PathVector pv = sp_svg_read_pathv(value); sub_shape->setCurve(std::make_unique(pv)); } @@ -966,7 +986,7 @@ sp_group_perform_patheffect(SPGroup *group, SPGroup *top_group, Inkscape::LivePa } } } - SPItem* clipmaskto = dynamic_cast(group); + SPItem *clipmaskto = dynamic_cast(group); if (clipmaskto) { top_group->applyToClipPath(clipmaskto, lpe); top_group->applyToMask(clipmaskto, lpe); diff --git a/src/object/sp-item-group.h b/src/object/sp-item-group.h index a8be40ffe1f016f62a816f14c4ad527df937c9d0..4388c875737eee01d1a86f2ad557abb6a23d7c61 100644 --- a/src/object/sp-item-group.h +++ b/src/object/sp-item-group.h @@ -15,12 +15,13 @@ */ #include + #include "sp-lpe-item.h" -#define SP_GROUP(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_GROUP(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_GROUP(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_GROUP(obj) (dynamic_cast((SPObject *)obj) != NULL) -#define SP_IS_LAYER(obj) (SP_IS_GROUP(obj) && SP_GROUP(obj)->layerMode() == SPGroup::LAYER) +#define SP_IS_LAYER(obj) (SP_IS_GROUP(obj) && SP_GROUP(obj)->layerMode() == SPGroup::LAYER) namespace Inkscape { @@ -29,12 +30,18 @@ class DrawingItem; } // namespace Inkscape -class SPGroup : public SPLPEItem { +class SPGroup : public SPLPEItem +{ public: - SPGroup(); - ~SPGroup() override; + SPGroup(); + ~SPGroup() override; - enum LayerMode { GROUP, LAYER, MASK_HELPER }; + enum LayerMode + { + GROUP, + LAYER, + MASK_HELPER + }; bool _expanded; bool _insert_bottom; @@ -46,12 +53,13 @@ public: bool expanded() const { return _expanded; } void setExpanded(bool isexpanded); - + bool insertBottom() const { return _insert_bottom; } void setInsertBottom(bool insertbottom); - LayerMode effectiveLayerMode(unsigned int display_key) const { - if ( _layer_mode == LAYER ) { + LayerMode effectiveLayerMode(unsigned int display_key) const + { + if (_layer_mode == LAYER) { return LAYER; } else { return layerDisplayMode(display_key); @@ -64,38 +72,40 @@ public: void scaleChildItemsRec(Geom::Scale const &sc, Geom::Point const &p, bool noRecurse); int getItemCount() const; - virtual void _showChildren (Inkscape::Drawing &drawing, Inkscape::DrawingItem *ai, unsigned int key, unsigned int flags); + virtual void _showChildren(Inkscape::Drawing &drawing, Inkscape::DrawingItem *ai, unsigned int key, + unsigned int flags); private: - void _updateLayerMode(unsigned int display_key=0); + void _updateLayerMode(unsigned int display_key = 0); public: void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; + void release() override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; void remove_child(Inkscape::XML::Node *child) override; void order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref) override; void update(SPCtx *ctx, unsigned int flags) override; void modified(unsigned int flags) override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType bboxtype) const override; void print(SPPrintContext *ctx) override; - const char* displayName() const override; + const char *displayName() const override; char *description() const override; - Inkscape::DrawingItem *show (Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; - void hide (unsigned int key) override; + Inkscape::DrawingItem *show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; + void hide(unsigned int key) override; - void snappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const override; + void snappoints(std::vector &p, + Inkscape::SnapPreferences const *snapprefs) const override; void update_patheffect(bool write) override; }; - /** * finds clones of a child of the group going out of the group; and inverse the group transform on its clones * Also called when moving objects between different layers @@ -105,12 +115,11 @@ public: */ void sp_item_group_ungroup_handle_clones(SPItem *parent, Geom::Affine const g); -void sp_item_group_ungroup (SPGroup *group, std::vector &children, bool do_done = true); - +void sp_item_group_ungroup(SPGroup *group, std::vector &children, bool do_done = true); -std::vector sp_item_group_item_list (SPGroup *group); +std::vector sp_item_group_item_list(SPGroup *group); -SPObject *sp_item_group_get_child_by_name (SPGroup *group, SPObject *ref, const char *name); +SPObject *sp_item_group_get_child_by_name(SPGroup *group, SPObject *ref, const char *name); #endif diff --git a/src/object/sp-item-rm-unsatisfied-cns.cpp b/src/object/sp-item-rm-unsatisfied-cns.cpp index 3b476e20d053b44615c620781955938655efa9b3..485345b2311bd96acc7f956ec335cf55bcef8ce5 100644 --- a/src/object/sp-item-rm-unsatisfied-cns.cpp +++ b/src/object/sp-item-rm-unsatisfied-cns.cpp @@ -8,13 +8,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "sp-item-rm-unsatisfied-cns.h" + #include <2geom/coord.h> +#include #include #include "remove-last.h" #include "sp-guide.h" -#include "sp-item-rm-unsatisfied-cns.h" void sp_item_rm_unsatisfied_cns(SPItem &item) { @@ -24,23 +25,21 @@ void sp_item_rm_unsatisfied_cns(SPItem &item) std::vector snappoints; item.getSnappoints(snappoints, nullptr); for (unsigned i = item.constraints.size(); i--;) { - g_assert( i < item.constraints.size() ); + g_assert(i < item.constraints.size()); SPGuideConstraint const &cn = item.constraints[i]; int const snappoint_ix = cn.snappoint_ix; - g_assert( snappoint_ix < int(snappoints.size()) ); + g_assert(snappoint_ix < int(snappoints.size())); if (!Geom::are_near(cn.g->getDistanceFrom(snappoints[snappoint_ix].getPoint()), 0, 1e-2)) { - remove_last(cn.g->attached_items, SPGuideAttachment(&item, cn.snappoint_ix)); - g_assert( i < item.constraints.size() ); + g_assert(i < item.constraints.size()); item.constraints.erase(item.constraints.begin() + i); } } } - /* Local Variables: mode:c++ diff --git a/src/object/sp-item-rm-unsatisfied-cns.h b/src/object/sp-item-rm-unsatisfied-cns.h index ac03b7425166bdb98edaf65edc224aee3c6ce396..081430b7a87a548dbc9edd56f836d2a581e6de95 100644 --- a/src/object/sp-item-rm-unsatisfied-cns.h +++ b/src/object/sp-item-rm-unsatisfied-cns.h @@ -14,7 +14,6 @@ class SPItem; void sp_item_rm_unsatisfied_cns(SPItem &item); - #endif // SEEN_SP_ITEM_RM_UNSATISFIED_CNS_H /* diff --git a/src/object/sp-item-transform.cpp b/src/object/sp-item-transform.cpp index e01571ef43fbe08aaad844a6d8d7ff2fe28bc75a..07fc1f24b994cbd469774e0a5bc644d5ca064e6b 100644 --- a/src/object/sp-item-transform.cpp +++ b/src/object/sp-item-transform.cpp @@ -15,53 +15,62 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <2geom/transforms.h> -#include "sp-item.h" #include "sp-item-transform.h" +#include <2geom/transforms.h> #include +#include "sp-item.h" + /** - * Calculate the affine transformation required to transform one visual bounding box into another, accounting for a uniform strokewidth. + * Calculate the affine transformation required to transform one visual bounding box into another, accounting for a + * uniform strokewidth. * - * PS: This function will only return accurate results for the visual bounding box of a selection of one or more objects, all having - * the same strokewidth. If the stroke width varies from object to object in this selection, then the function - * get_scale_transform_for_variable_stroke() should be called instead + * PS: This function will only return accurate results for the visual bounding box of a selection of one or more + * objects, all having the same strokewidth. If the stroke width varies from object to object in this selection, then + * the function get_scale_transform_for_variable_stroke() should be called instead * * When scaling or stretching an object using the selector, e.g. by dragging the handles or by entering a value, we will - * need to calculate the affine transformation for the old dimensions to the new dimensions. When using a geometric bounding - * box this is very straightforward, but when using a visual bounding box this become more tricky as we need to account for - * the strokewidth, which is either constant or scales width the area of the object. This function takes care of the calculation - * of the affine transformation: + * need to calculate the affine transformation for the old dimensions to the new dimensions. When using a geometric + * bounding box this is very straightforward, but when using a visual bounding box this become more tricky as we need to + * account for the strokewidth, which is either constant or scales width the area of the object. This function takes + * care of the calculation of the affine transformation: * @param bbox_visual Current visual bounding box * @param stroke_x Apparent strokewidth in horizontal direction * @param stroke_y Apparent strokewidth in vertical direction - * @param transform_stroke If true then the stroke will be scaled proportional to the square root of the area of the geometric bounding box + * @param transform_stroke If true then the stroke will be scaled proportional to the square root of the area of the + * geometric bounding box * @param preserve If true then the transform element will be preserved in XML, and evaluated after stroke is applied * @param x0 Coordinate of the target visual bounding box * @param y0 Coordinate of the target visual bounding box * @param x1 Coordinate of the target visual bounding box * @param y1 Coordinate of the target visual bounding box - * PS: we have to pass each coordinate individually, to find out if we are mirroring the object; Using a Geom::Rect() instead is - * not possible here because it will only allow for a positive width and height, and therefore cannot mirror + * PS: we have to pass each coordinate individually, to find out if we are mirroring the object; Using a Geom::Rect() + * instead is not possible here because it will only allow for a positive width and height, and therefore cannot mirror * @return */ -Geom::Affine get_scale_transform_for_uniform_stroke(Geom::Rect const &bbox_visual, gdouble stroke_x, gdouble stroke_y, bool transform_stroke, bool preserve, gdouble x0, gdouble y0, gdouble x1, gdouble y1) +Geom::Affine get_scale_transform_for_uniform_stroke(Geom::Rect const &bbox_visual, gdouble stroke_x, gdouble stroke_y, + bool transform_stroke, bool preserve, gdouble x0, gdouble y0, + gdouble x1, gdouble y1) { - Geom::Affine p2o = Geom::Translate (-bbox_visual.min()); - Geom::Affine o2n = Geom::Translate (x0, y0); + Geom::Affine p2o = Geom::Translate(-bbox_visual.min()); + Geom::Affine o2n = Geom::Translate(x0, y0); - Geom::Affine scale = Geom::Scale (1, 1); - Geom::Affine unbudge = Geom::Translate (0, 0); // moves the object(s) to compensate for the drift caused by stroke width change + Geom::Affine scale = Geom::Scale(1, 1); + Geom::Affine unbudge = + Geom::Translate(0, 0); // moves the object(s) to compensate for the drift caused by stroke width change - // 1) We start with a visual bounding box (w0, h0) which we want to transfer into another visual bounding box (w1, h1) - // 2) The stroke is r0, equal for all edges, if preserve transforms is false - // 3) Given this visual bounding box we can calculate the geometric bounding box by subtracting half the stroke from each side; + // 1) We start with a visual bounding box (w0, h0) which we want to transfer into another visual bounding box (w1, + // h1) 2) The stroke is r0, equal for all edges, if preserve transforms is false 3) Given this visual bounding box + // we can calculate the geometric bounding box by subtracting half the stroke from each side; // -> The width and height of the geometric bounding box will therefore be (w0 - 2*0.5*r0) and (h0 - 2*0.5*r0) - // 4) If preserve transforms is true, then stroke_x != stroke_y, since these are the apparent stroke widths, after transforming + // 4) If preserve transforms is true, then stroke_x != stroke_y, since these are the apparent stroke widths, after + // transforming - if ((stroke_x == Geom::infinity()) || (fabs(stroke_x) < 1e-6)) stroke_x = 0; - if ((stroke_y == Geom::infinity()) || (fabs(stroke_y) < 1e-6)) stroke_y = 0; + if ((stroke_x == Geom::infinity()) || (fabs(stroke_x) < 1e-6)) + stroke_x = 0; + if ((stroke_y == Geom::infinity()) || (fabs(stroke_y) < 1e-6)) + stroke_y = 0; gdouble w0 = bbox_visual.width(); // will return a value >= 0, as required further down the road gdouble h0 = bbox_visual.height(); @@ -74,22 +83,22 @@ Geom::Affine get_scale_transform_for_uniform_stroke(Geom::Rect const &bbox_visua // Here starts the calculation you've been waiting for; first do some preparation int flip_x = (w1 > 0) ? 1 : -1; int flip_y = (h1 > 0) ? 1 : -1; - + // w1 and h1 will be negative when mirroring, but if so then e.g. w1-r0 won't make sense // Therefore we will use the absolute values from this point on w1 = fabs(w1); h1 = fabs(h1); // w0 and h0 will always be positive due to the definition of the width() and height() methods. - // Check whether the stroke is negative; i.e. the geometric bounding box is larger than the visual bounding box, which - // occurs for example for clipped objects (see launchpad bug #811819) + // Check whether the stroke is negative; i.e. the geometric bounding box is larger than the visual bounding box, + // which occurs for example for clipped objects (see launchpad bug #811819) if (stroke_x < 0 || stroke_y < 0) { - Geom::Affine direct = Geom::Scale(flip_x * w1 / w0, flip_y* h1 / h0); // Scaling of the visual bounding box + Geom::Affine direct = Geom::Scale(flip_x * w1 / w0, flip_y * h1 / h0); // Scaling of the visual bounding box // How should we handle the stroke width scaling of clipped object? I don't know if we can/should handle this, // so for now we simply return the direct scaling return (p2o * direct * o2n); } - gdouble r0 = sqrt(stroke_x*stroke_y); // r0 is redundant, used only for those cases where stroke_x = stroke_y + gdouble r0 = sqrt(stroke_x * stroke_y); // r0 is redundant, used only for those cases where stroke_x = stroke_y // We will now try to calculate the affine transformation required to transform the first visual bounding box into // the second one, while accounting for strokewidth @@ -103,16 +112,18 @@ Geom::Affine get_scale_transform_for_uniform_stroke(Geom::Rect const &bbox_visua gdouble r1; if ((fabs(w0 - stroke_x) < 1e-6) || w1 == 0) { // We have a vertical line at hand - scale_y = h1/h0; + scale_y = h1 / h0; scale_x = transform_stroke ? 1 : scale_y; - unbudge *= Geom::Translate (-flip_x * 0.5 * (scale_x - 1.0) * w0, 0); - unbudge *= Geom::Translate ( flip_x * 0.5 * (w1 - w0), 0); // compensate for the fact that this operation cannot be performed + unbudge *= Geom::Translate(-flip_x * 0.5 * (scale_x - 1.0) * w0, 0); + unbudge *= Geom::Translate(flip_x * 0.5 * (w1 - w0), + 0); // compensate for the fact that this operation cannot be performed } else if ((fabs(h0 - stroke_y) < 1e-6) || h1 == 0) { // We have a horizontal line at hand - scale_x = w1/w0; + scale_x = w1 / w0; scale_y = transform_stroke ? 1 : scale_x; - unbudge *= Geom::Translate (0, -flip_y * 0.5 * (scale_y - 1.0) * h0); - unbudge *= Geom::Translate (0, flip_y * 0.5 * (h1 - h0)); // compensate for the fact that this operation cannot be performed - } else { // We have a true 2D object at hand + unbudge *= Geom::Translate(0, -flip_y * 0.5 * (scale_y - 1.0) * h0); + unbudge *= Geom::Translate(0, flip_y * 0.5 * (h1 - h0)); // compensate for the fact that this operation cannot + // be performed + } else { // We have a true 2D object at hand if (transform_stroke && !preserve) { /* Initial area of the geometric bounding box: A0 = (w0-r0)*(h0-r0) * Desired area of the geometric bounding box: A1 = (w1-r1)*(h1-r1) @@ -123,45 +134,48 @@ Geom::Affine get_scale_transform_for_uniform_stroke(Geom::Rect const &bbox_visua * * This is a quadratic equation in r1, of which the roots can be found using the ABC formula * */ - gdouble A = -w0*h0 + r0*(w0 + h0); - gdouble B = -(w1 + h1) * r0*r0; - gdouble C = w1 * h1 * r0*r0; - if (B*B - 4*A*C < 0) { + gdouble A = -w0 * h0 + r0 * (w0 + h0); + gdouble B = -(w1 + h1) * r0 * r0; + gdouble C = w1 * h1 * r0 * r0; + if (B * B - 4 * A * C < 0) { g_message("stroke scaling error : %d, %f, %f, %f, %f, %f", preserve, r0, w0, h0, w1, h1); } else { - r1 = -C/B; - if (!Geom::are_near(A*C/B/B, 0.0, Geom::EPSILON)) - r1 = fabs((-B - sqrt(B*B - 4*A*C))/(2*A)); + r1 = -C / B; + if (!Geom::are_near(A * C / B / B, 0.0, Geom::EPSILON)) + r1 = fabs((-B - sqrt(B * B - 4 * A * C)) / (2 * A)); // If w1 < 0 then the scale will be wrong if we just assume that scale_x = (w1 - r1)/(w0 - r0); // Therefore we here need the absolute values of w0, w1, h0, h1, and r0, as taken care of earlier - scale_x = (w1 - r1)/(w0 - r0); - scale_y = (h1 - r1)/(h0 - r0); - // Make sure that the lower-left corner of the visual bounding box stays where it is, even though the stroke width has changed - unbudge *= Geom::Translate (-flip_x * 0.5 * (r0 * scale_x - r1), -flip_y * 0.5 * (r0 * scale_y - r1)); + scale_x = (w1 - r1) / (w0 - r0); + scale_y = (h1 - r1) / (h0 - r0); + // Make sure that the lower-left corner of the visual bounding box stays where it is, even though the + // stroke width has changed + unbudge *= Geom::Translate(-flip_x * 0.5 * (r0 * scale_x - r1), -flip_y * 0.5 * (r0 * scale_y - r1)); } } else if (!transform_stroke && !preserve) { // scale the geometric bbox with constant stroke scale_x = (w1 - r0) / (w0 - r0); scale_y = (h1 - r0) / (h0 - r0); - unbudge *= Geom::Translate (-flip_x * 0.5 * r0 * (scale_x - 1), -flip_y * 0.5 * r0 * (scale_y - 1)); + unbudge *= Geom::Translate(-flip_x * 0.5 * r0 * (scale_x - 1), -flip_y * 0.5 * r0 * (scale_y - 1)); } else if (!transform_stroke) { // 'Preserve Transforms' was chosen. // geometric mean of stroke_x and stroke_y will be preserved // new_stroke_x = stroke_x*sqrt(scale_x/scale_y) // new_stroke_y = stroke_y*sqrt(scale_y/scale_x) // scale_x = (w1 - new_stroke_x)/(w0 - stroke_x) // scale_y = (h1 - new_stroke_y)/(h0 - stroke_y) - gdouble A = h1*(w0 - stroke_x); - gdouble B = (h0*stroke_x - w0*stroke_y); - gdouble C = -w1*(h0 - stroke_y); - gdouble Sx_div_Sy; // Sx_div_Sy = sqrt(scale_x/scale_y) - if (B*B - 4*A*C < 0) { - g_message("stroke scaling error : %d, %f, %f, %f, %f, %f, %f", preserve, stroke_x, stroke_y, w0, h0, w1, h1); + gdouble A = h1 * (w0 - stroke_x); + gdouble B = (h0 * stroke_x - w0 * stroke_y); + gdouble C = -w1 * (h0 - stroke_y); + gdouble Sx_div_Sy; // Sx_div_Sy = sqrt(scale_x/scale_y) + if (B * B - 4 * A * C < 0) { + g_message("stroke scaling error : %d, %f, %f, %f, %f, %f, %f", preserve, stroke_x, stroke_y, w0, h0, w1, + h1); } else { - Sx_div_Sy = (-B + sqrt(B*B - 4*A*C))/2/A; - scale_x = (w1 - stroke_x*Sx_div_Sy)/(w0 - stroke_x); - scale_y = (h1 - stroke_y/Sx_div_Sy)/(h0 - stroke_y); - unbudge *= Geom::Translate (-flip_x * 0.5 * stroke_x * scale_x * (1.0 - sqrt(1.0/scale_x/scale_y)), -flip_y * 0.5 * stroke_y * scale_y * (1.0 - sqrt(1.0/scale_x/scale_y))); + Sx_div_Sy = (-B + sqrt(B * B - 4 * A * C)) / 2 / A; + scale_x = (w1 - stroke_x * Sx_div_Sy) / (w0 - stroke_x); + scale_y = (h1 - stroke_y / Sx_div_Sy) / (h0 - stroke_y); + unbudge *= Geom::Translate(-flip_x * 0.5 * stroke_x * scale_x * (1.0 - sqrt(1.0 / scale_x / scale_y)), + -flip_y * 0.5 * stroke_y * scale_y * (1.0 - sqrt(1.0 / scale_x / scale_y))); } - } else { // 'Preserve Transforms' was chosen, and stroke is scaled + } else { // 'Preserve Transforms' was chosen, and stroke is scaled scale_x = w1 / w0; scale_y = h1 / h0; } @@ -174,43 +188,49 @@ Geom::Affine get_scale_transform_for_uniform_stroke(Geom::Rect const &bbox_visua } /** - * Calculate the affine transformation required to transform one visual bounding box into another, accounting for a VARIABLE strokewidth. + * Calculate the affine transformation required to transform one visual bounding box into another, accounting for a + * VARIABLE strokewidth. * - * Note: Please try to understand get_scale_transform_for_uniform_stroke() first, and read all it's comments carefully. This function - * (get_scale_transform_for_variable_stroke) is a bit different because it will allow for a strokewidth that's different for each - * side of the visual bounding box. Such a situation will arise when transforming the visual bounding box of a selection of objects, - * each having a different stroke width. In fact this function is a generalized version of get_scale_transform_for_uniform_stroke(), but - * will not (yet) replace it because it has not been tested as carefully, and because the old function is can serve as an introduction to - * understand the new one. + * Note: Please try to understand get_scale_transform_for_uniform_stroke() first, and read all it's comments carefully. + * This function (get_scale_transform_for_variable_stroke) is a bit different because it will allow for a strokewidth + * that's different for each side of the visual bounding box. Such a situation will arise when transforming the visual + * bounding box of a selection of objects, each having a different stroke width. In fact this function is a generalized + * version of get_scale_transform_for_uniform_stroke(), but will not (yet) replace it because it has not been tested as + * carefully, and because the old function is can serve as an introduction to understand the new one. * * When scaling or stretching an object using the selector, e.g. by dragging the handles or by entering a value, we will - * need to calculate the affine transformation for the old dimensions to the new dimensions. When using a geometric bounding - * box this is very straightforward, but when using a visual bounding box this become more tricky as we need to account for - * the strokewidth, which is either constant or scales width the area of the object. This function takes care of the calculation - * of the affine transformation: + * need to calculate the affine transformation for the old dimensions to the new dimensions. When using a geometric + * bounding box this is very straightforward, but when using a visual bounding box this become more tricky as we need to + * account for the strokewidth, which is either constant or scales width the area of the object. This function takes + * care of the calculation of the affine transformation: * * @param bbox_visual Current visual bounding box * @param bbox_geometric Current geometric bounding box (allows for calculating the strokewidth of each edge) - * @param transform_stroke If true then the stroke will be scaled proportional to the square root of the area of the geometric bounding box + * @param transform_stroke If true then the stroke will be scaled proportional to the square root of the area of the + * geometric bounding box * @param preserve If true then the transform element will be preserved in XML, and evaluated after stroke is applied * @param x0 Coordinate of the target visual bounding box * @param y0 Coordinate of the target visual bounding box * @param x1 Coordinate of the target visual bounding box * @param y1 Coordinate of the target visual bounding box - * PS: we have to pass each coordinate individually, to find out if we are mirroring the object; Using a Geom::Rect() instead is - * not possible here because it will only allow for a positive width and height, and therefore cannot mirror + * PS: we have to pass each coordinate individually, to find out if we are mirroring the object; Using a Geom::Rect() + * instead is not possible here because it will only allow for a positive width and height, and therefore cannot mirror * @return */ -Geom::Affine get_scale_transform_for_variable_stroke(Geom::Rect const &bbox_visual, Geom::Rect const &bbox_geom, bool transform_stroke, bool preserve, gdouble x0, gdouble y0, gdouble x1, gdouble y1) +Geom::Affine get_scale_transform_for_variable_stroke(Geom::Rect const &bbox_visual, Geom::Rect const &bbox_geom, + bool transform_stroke, bool preserve, gdouble x0, gdouble y0, + gdouble x1, gdouble y1) { - Geom::Affine p2o = Geom::Translate (-bbox_visual.min()); - Geom::Affine o2n = Geom::Translate (x0, y0); + Geom::Affine p2o = Geom::Translate(-bbox_visual.min()); + Geom::Affine o2n = Geom::Translate(x0, y0); - Geom::Affine scale = Geom::Scale (1, 1); - Geom::Affine unbudge = Geom::Translate (0, 0); // moves the object(s) to compensate for the drift caused by stroke width change + Geom::Affine scale = Geom::Scale(1, 1); + Geom::Affine unbudge = + Geom::Translate(0, 0); // moves the object(s) to compensate for the drift caused by stroke width change - // 1) We start with a visual bounding box (w0, h0) which we want to transfer into another visual bounding box (w1, h1) - // 2) We will also know the geometric bounding box, which can be used to calculate the strokewidth. The strokewidth will however + // 1) We start with a visual bounding box (w0, h0) which we want to transfer into another visual bounding box (w1, + // h1) 2) We will also know the geometric bounding box, which can be used to calculate the strokewidth. The + // strokewidth will however // be different for each of the four sides (left/right/top/bottom: r0l, r0r, r0t, r0b) gdouble w0 = bbox_visual.width(); // will return a value >= 0, as required further down the road @@ -223,10 +243,14 @@ Geom::Affine get_scale_transform_for_variable_stroke(Geom::Rect const &bbox_visu // We will now try to calculate the affine transformation required to transform the first visual bounding box into // the second one, while accounting for strokewidth - gdouble r0w = w0 - bbox_geom.width(); // r0w is the average strokewidth of the left and right edges, i.e. 0.5*(r0l + r0r) - gdouble r0h = h0 - bbox_geom.height(); // r0h is the average strokewidth of the top and bottom edges, i.e. 0.5*(r0t + r0b) - if ((r0w == Geom::infinity()) || (fabs(r0w) < 1e-6)) r0w = 0; - if ((r0h == Geom::infinity()) || (fabs(r0h) < 1e-6)) r0h = 0; + gdouble r0w = + w0 - bbox_geom.width(); // r0w is the average strokewidth of the left and right edges, i.e. 0.5*(r0l + r0r) + gdouble r0h = + h0 - bbox_geom.height(); // r0h is the average strokewidth of the top and bottom edges, i.e. 0.5*(r0t + r0b) + if ((r0w == Geom::infinity()) || (fabs(r0w) < 1e-6)) + r0w = 0; + if ((r0h == Geom::infinity()) || (fabs(r0h) < 1e-6)) + r0h = 0; int flip_x = (w1 > 0) ? 1 : -1; int flip_y = (h1 > 0) ? 1 : -1; @@ -241,20 +265,21 @@ Geom::Affine get_scale_transform_for_variable_stroke(Geom::Rect const &bbox_visu return Geom::Affine(); } - // Check whether the stroke is negative; i.e. the geometric bounding box is larger than the visual bounding box, which - // occurs for example for clipped objects (see launchpad bug #811819) + // Check whether the stroke is negative; i.e. the geometric bounding box is larger than the visual bounding box, + // which occurs for example for clipped objects (see launchpad bug #811819) if (r0w < 0 || r0h < 0) { - Geom::Affine direct = Geom::Scale(flip_x * w1 / w0, flip_y* h1 / h0); // Scaling of the visual bounding box + Geom::Affine direct = Geom::Scale(flip_x * w1 / w0, flip_y * h1 / h0); // Scaling of the visual bounding box // How should we handle the stroke width scaling of clipped object? I don't know if we can/should handle this, // so for now we simply return the direct scaling return (p2o * direct * o2n); } - // The calculation of the new strokewidth will only use the average stroke for each of the dimensions; To find the new stroke for each - // of the edges individually though, we will use the boundary condition that the ratio of the left/right strokewidth will not change due to the - // scaling. The same holds for the ratio of the top/bottom strokewidth. - gdouble stroke_ratio_w = fabs(r0w) < 1e-6 ? 1 : (bbox_geom[Geom::X].min() - bbox_visual[Geom::X].min())/r0w; - gdouble stroke_ratio_h = fabs(r0h) < 1e-6 ? 1 : (bbox_geom[Geom::Y].min() - bbox_visual[Geom::Y].min())/r0h; + // The calculation of the new strokewidth will only use the average stroke for each of the dimensions; To find the + // new stroke for each of the edges individually though, we will use the boundary condition that the ratio of the + // left/right strokewidth will not change due to the scaling. The same holds for the ratio of the top/bottom + // strokewidth. + gdouble stroke_ratio_w = fabs(r0w) < 1e-6 ? 1 : (bbox_geom[Geom::X].min() - bbox_visual[Geom::X].min()) / r0w; + gdouble stroke_ratio_h = fabs(r0h) < 1e-6 ? 1 : (bbox_geom[Geom::Y].min() - bbox_visual[Geom::Y].min()) / r0h; gdouble scale_x = 1; gdouble scale_y = 1; @@ -262,16 +287,18 @@ Geom::Affine get_scale_transform_for_variable_stroke(Geom::Rect const &bbox_visu gdouble r1w; if ((fabs(w0 - r0w) < 1e-6) || w1 == 0) { // We have a vertical line at hand - scale_y = h1/h0; + scale_y = h1 / h0; scale_x = transform_stroke ? 1 : scale_y; - unbudge *= Geom::Translate (-flip_x * 0.5 * (scale_x - 1.0) * w0, 0); - unbudge *= Geom::Translate ( flip_x * 0.5 * (w1 - w0), 0); // compensate for the fact that this operation cannot be performed + unbudge *= Geom::Translate(-flip_x * 0.5 * (scale_x - 1.0) * w0, 0); + unbudge *= Geom::Translate(flip_x * 0.5 * (w1 - w0), + 0); // compensate for the fact that this operation cannot be performed } else if ((fabs(h0 - r0h) < 1e-6) || h1 == 0) { // We have a horizontal line at hand - scale_x = w1/w0; + scale_x = w1 / w0; scale_y = transform_stroke ? 1 : scale_x; - unbudge *= Geom::Translate (0, -flip_y * 0.5 * (scale_y - 1.0) * h0); - unbudge *= Geom::Translate (0, flip_y * 0.5 * (h1 - h0)); // compensate for the fact that this operation cannot be performed - } else { // We have a true 2D object at hand + unbudge *= Geom::Translate(0, -flip_y * 0.5 * (scale_y - 1.0) * h0); + unbudge *= Geom::Translate(0, flip_y * 0.5 * (h1 - h0)); // compensate for the fact that this operation cannot + // be performed + } else { // We have a true 2D object at hand if (transform_stroke && !preserve) { /* Initial area of the geometric bounding box: A0 = (w0-r0w)*(h0-r0h) * Desired area of the geometric bounding box: A1 = (w1-r1w)*(h1-r1h) @@ -282,48 +309,55 @@ Geom::Affine get_scale_transform_for_variable_stroke(Geom::Rect const &bbox_visu * This leads to a quadratic equation in r1w, solved as follows: * */ - gdouble A = w0*h0 - r0h*w0 - r0w*h0; - gdouble B = r0h*w1 + r0w*h1; - gdouble C = -w1*h1; + gdouble A = w0 * h0 - r0h * w0 - r0w * h0; + gdouble B = r0h * w1 + r0w * h1; + gdouble C = -w1 * h1; - if (B*B - 4*A*C < 0) { - g_message("variable stroke scaling error : %d, %d, %f, %f, %f, %f, %f, %f", transform_stroke, preserve, r0w, r0h, w0, h0, w1, h1); + if (B * B - 4 * A * C < 0) { + g_message("variable stroke scaling error : %d, %d, %f, %f, %f, %f, %f, %f", transform_stroke, preserve, + r0w, r0h, w0, h0, w1, h1); } else { - gdouble det = -C/B; - if (!Geom::are_near(A*C/B/B, 0.0, Geom::EPSILON)) - det = (-B + sqrt(B*B - 4*A*C))/(2*A); - r1w = r0w*det; - r1h = r0h*det; + gdouble det = -C / B; + if (!Geom::are_near(A * C / B / B, 0.0, Geom::EPSILON)) + det = (-B + sqrt(B * B - 4 * A * C)) / (2 * A); + r1w = r0w * det; + r1h = r0h * det; // If w1 < 0 then the scale will be wrong if we just assume that scale_x = (w1 - r1)/(w0 - r0); // Therefore we here need the absolute values of w0, w1, h0, h1, and r0, as taken care of earlier - scale_x = (w1 - r1w)/(w0 - r0w); - scale_y = (h1 - r1h)/(h0 - r0h); - // Make sure that the lower-left corner of the visual bounding box stays where it is, even though the stroke width has changed - unbudge *= Geom::Translate (-flip_x * stroke_ratio_w * (r0w * scale_x - r1w), -flip_y * stroke_ratio_h * (r0h * scale_y - r1h)); + scale_x = (w1 - r1w) / (w0 - r0w); + scale_y = (h1 - r1h) / (h0 - r0h); + // Make sure that the lower-left corner of the visual bounding box stays where it is, even though the + // stroke width has changed + unbudge *= Geom::Translate(-flip_x * stroke_ratio_w * (r0w * scale_x - r1w), + -flip_y * stroke_ratio_h * (r0h * scale_y - r1h)); } } else if (!transform_stroke && !preserve) { // scale the geometric bbox with constant stroke scale_x = (w1 - r0w) / (w0 - r0w); scale_y = (h1 - r0h) / (h0 - r0h); - unbudge *= Geom::Translate (-flip_x * stroke_ratio_w * r0w * (scale_x - 1), -flip_y * stroke_ratio_h * r0h * (scale_y - 1)); + unbudge *= Geom::Translate(-flip_x * stroke_ratio_w * r0w * (scale_x - 1), + -flip_y * stroke_ratio_h * r0h * (scale_y - 1)); } else if (!transform_stroke) { // 'Preserve Transforms' was chosen. // geometric mean of r0w and r0h will be preserved // new_r0w = r0w*sqrt(scale_x/scale_y) // new_r0h = r0h*sqrt(scale_y/scale_x) // scale_x = (w1 - new_r0w)/(w0 - r0w) // scale_y = (h1 - new_r0h)/(h0 - r0h) - gdouble A = h1*(w0 - r0w); - gdouble B = (h0*r0w - w0*r0h); - gdouble C = -w1*(h0 - r0h); - gdouble Sx_div_Sy; // Sx_div_Sy = sqrt(scale_x/scale_y) - if (B*B - 4*A*C < 0) { - g_message("variable stroke scaling error : %d, %d, %f, %f, %f, %f, %f, %f", transform_stroke, preserve, r0w, r0h, w0, h0, w1, h1); + gdouble A = h1 * (w0 - r0w); + gdouble B = (h0 * r0w - w0 * r0h); + gdouble C = -w1 * (h0 - r0h); + gdouble Sx_div_Sy; // Sx_div_Sy = sqrt(scale_x/scale_y) + if (B * B - 4 * A * C < 0) { + g_message("variable stroke scaling error : %d, %d, %f, %f, %f, %f, %f, %f", transform_stroke, preserve, + r0w, r0h, w0, h0, w1, h1); } else { - Sx_div_Sy = (-B + sqrt(B*B - 4*A*C))/2/A; - scale_x = (w1 - r0w*Sx_div_Sy)/(w0 - r0w); - scale_y = (h1 - r0h/Sx_div_Sy)/(h0 - r0h); - unbudge *= Geom::Translate (-flip_x * stroke_ratio_w * r0w * scale_x * (1.0 - sqrt(1.0/scale_x/scale_y)), -flip_y * stroke_ratio_h * r0h * scale_y * (1.0 - sqrt(1.0/scale_x/scale_y))); + Sx_div_Sy = (-B + sqrt(B * B - 4 * A * C)) / 2 / A; + scale_x = (w1 - r0w * Sx_div_Sy) / (w0 - r0w); + scale_y = (h1 - r0h / Sx_div_Sy) / (h0 - r0h); + unbudge *= + Geom::Translate(-flip_x * stroke_ratio_w * r0w * scale_x * (1.0 - sqrt(1.0 / scale_x / scale_y)), + -flip_y * stroke_ratio_h * r0h * scale_y * (1.0 - sqrt(1.0 / scale_x / scale_y))); } - } else { // 'Preserve Transforms' was chosen, and stroke is scaled + } else { // 'Preserve Transforms' was chosen, and stroke is scaled scale_x = w1 / w0; scale_y = h1 / h0; } @@ -335,33 +369,35 @@ Geom::Affine get_scale_transform_for_variable_stroke(Geom::Rect const &bbox_visu return (p2o * scale * unbudge * o2n); } -Geom::Rect get_visual_bbox(Geom::OptRect const &initial_geom_bbox, Geom::Affine const &abs_affine, gdouble const initial_strokewidth, bool const transform_stroke) +Geom::Rect get_visual_bbox(Geom::OptRect const &initial_geom_bbox, Geom::Affine const &abs_affine, + gdouble const initial_strokewidth, bool const transform_stroke) { g_assert(initial_geom_bbox); - + // Find the new geometric bounding box; Do this by transforming each corner of // the initial geometric bounding box individually and fitting a new boundingbox - // around the transformerd corners - Geom::Point const p0 = Geom::Point(initial_geom_bbox->corner(0)) * abs_affine; + // around the transformerd corners + Geom::Point const p0 = Geom::Point(initial_geom_bbox->corner(0)) * abs_affine; Geom::Rect new_geom_bbox(p0, p0); - for (unsigned i = 1 ; i < 4 ; i++) { + for (unsigned i = 1; i < 4; i++) { new_geom_bbox.expandTo(Geom::Point(initial_geom_bbox->corner(i)) * abs_affine); } - Geom::Rect new_visual_bbox = new_geom_bbox; + Geom::Rect new_visual_bbox = new_geom_bbox; if (initial_strokewidth > 0 && initial_strokewidth < Geom::infinity()) { if (transform_stroke) { - // scale stroke by: sqrt (((w1-r0)/(w0-r0))*((h1-r0)/(h0-r0))) (for visual bboxes, see get_scale_transform_for_stroke) - // equals scaling by: sqrt ((w1/w0)*(h1/h0)) for geometrical bboxes - // equals scaling by: sqrt (area1/area0) for geometrical bboxes - gdouble const new_strokewidth = initial_strokewidth * sqrt (new_geom_bbox.area() / initial_geom_bbox->area()); - new_visual_bbox.expandBy(0.5 * new_strokewidth); + // scale stroke by: sqrt (((w1-r0)/(w0-r0))*((h1-r0)/(h0-r0))) (for visual bboxes, see + // get_scale_transform_for_stroke) equals scaling by: sqrt ((w1/w0)*(h1/h0)) for geometrical bboxes equals + // scaling by: sqrt (area1/area0) for geometrical bboxes + gdouble const new_strokewidth = + initial_strokewidth * sqrt(new_geom_bbox.area() / initial_geom_bbox->area()); + new_visual_bbox.expandBy(0.5 * new_strokewidth); } else { // Do not transform the stroke - new_visual_bbox.expandBy(0.5 * initial_strokewidth); + new_visual_bbox.expandBy(0.5 * initial_strokewidth); } } - + return new_visual_bbox; } diff --git a/src/object/sp-item-transform.h b/src/object/sp-item-transform.h index 4c74014094064957e0560886bac8ce83e24feba3..506ecb2cd334adfcdba8779cfede6c02d85ac36d 100644 --- a/src/object/sp-item-transform.h +++ b/src/object/sp-item-transform.h @@ -14,10 +14,14 @@ class SPItem; -Geom::Affine get_scale_transform_for_uniform_stroke (Geom::Rect const &bbox_visual, double stroke_x, double stroke_y, bool transform_stroke, bool preserve, double x0, double y0, double x1, double y1); -Geom::Affine get_scale_transform_for_variable_stroke (Geom::Rect const &bbox_visual, Geom::Rect const &bbox_geom, bool transform_stroke, bool preserve, double x0, double y0, double x1, double y1); -Geom::Rect get_visual_bbox (Geom::OptRect const &initial_geom_bbox, Geom::Affine const &abs_affine, double const initial_strokewidth, bool const transform_stroke); - +Geom::Affine get_scale_transform_for_uniform_stroke(Geom::Rect const &bbox_visual, double stroke_x, double stroke_y, + bool transform_stroke, bool preserve, double x0, double y0, + double x1, double y1); +Geom::Affine get_scale_transform_for_variable_stroke(Geom::Rect const &bbox_visual, Geom::Rect const &bbox_geom, + bool transform_stroke, bool preserve, double x0, double y0, + double x1, double y1); +Geom::Rect get_visual_bbox(Geom::OptRect const &initial_geom_bbox, Geom::Affine const &abs_affine, + double const initial_strokewidth, bool const transform_stroke); #endif // SEEN_SP_ITEM_TRANSFORM_H diff --git a/src/object/sp-item-update-cns.cpp b/src/object/sp-item-update-cns.cpp index 516fb67c7c19413b0ea42c9272051360b0db78d8..9c88c8bc59b5b2a8645e9f75ae1d95dfd1a2dd39 100644 --- a/src/object/sp-item-update-cns.cpp +++ b/src/object/sp-item-update-cns.cpp @@ -8,10 +8,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-item-update-cns.h" + #include -#include "satisfied-guide-cns.h" -#include "sp-item-update-cns.h" +#include "satisfied-guide-cns.h" #include "sp-guide.h" void sp_item_update_cns(SPItem &item, SPDesktop const &desktop) @@ -24,20 +25,14 @@ void sp_item_update_cns(SPItem &item, SPDesktop const &desktop) /* effic: It might be nice to avoid an n^2 algorithm, but in practice n will be small enough that it's still usually more efficient. */ - for (auto cn : found_cns) - { - if ( std::find(item.constraints.begin(), - item.constraints.end(), - cn) - == item.constraints.end() ) - { + for (auto cn : found_cns) { + if (std::find(item.constraints.begin(), item.constraints.end(), cn) == item.constraints.end()) { item.constraints.push_back(cn); cn.g->attached_items.emplace_back(&item, cn.snappoint_ix); } } } - /* Local Variables: mode:c++ diff --git a/src/object/sp-item-update-cns.h b/src/object/sp-item-update-cns.h index 3ff0d62622e1673748a268b2ff9094448e8ca781..12dcc16f9102b134126f944f167542efe14b2ac2 100644 --- a/src/object/sp-item-update-cns.h +++ b/src/object/sp-item-update-cns.h @@ -17,7 +17,6 @@ class SPItem; void sp_item_update_cns(SPItem &item, SPDesktop const &desktop); - #endif // SEEN_SP_ITEM_UPDATE_CNS_H /* diff --git a/src/object/sp-item.cpp b/src/object/sp-item.cpp index f175015b46d16b36d5f794e595cad4ffd1b662e4..fcc2cc0c73f0b78a35a71f9524d03deb291ebdac 100644 --- a/src/object/sp-item.cpp +++ b/src/object/sp-item.cpp @@ -17,20 +17,21 @@ #include +#include "attributes.h" #include "bad-uri-exception.h" -#include "svg/svg.h" -#include "print.h" +#include "conditions.h" +#include "conn-avoid-ref.h" +#include "desktop.h" #include "display/drawing-item.h" -#include "attributes.h" #include "document.h" - -#include "inkscape.h" -#include "desktop.h" -#include "gradient-chemistry.h" -#include "conn-avoid-ref.h" -#include "conditions.h" +#include "extract-uri.h" #include "filter-chemistry.h" - +#include "gradient-chemistry.h" +#include "inkscape.h" +#include "live_effects/effect.h" +#include "live_effects/lpeobject-reference.h" +#include "live_effects/lpeobject.h" +#include "print.h" #include "sp-clippath.h" #include "sp-desc.h" #include "sp-guide.h" @@ -45,31 +46,21 @@ #include "sp-textpath.h" #include "sp-title.h" #include "sp-use.h" - #include "style.h" +#include "svg/svg.h" #include "uri.h" - - #include "util/find-last-if.h" - -#include "extract-uri.h" - -#include "live_effects/lpeobject.h" -#include "live_effects/effect.h" -#include "live_effects/lpeobject-reference.h" - #include "util/units.h" #define noSP_ITEM_DEBUG_IDLE //#define OBJECT_TRACE -static SPItemView* sp_item_view_list_remove(SPItemView *list, - SPItemView *view); - - -SPItem::SPItem() : SPObject() { +static SPItemView *sp_item_view_list_remove(SPItemView *list, SPItemView *view); +SPItem::SPItem() + : SPObject() +{ sensitive = TRUE; bbox_valid = FALSE; @@ -98,9 +89,15 @@ SPItem::SPItem() : SPObject() { SPItem::~SPItem() = default; -SPClipPath *SPItem::getClipObject() const { return clip_ref ? clip_ref->getObject() : nullptr; } +SPClipPath *SPItem::getClipObject() const +{ + return clip_ref ? clip_ref->getObject() : nullptr; +} -SPMask *SPItem::getMaskObject() const { return mask_ref ? mask_ref->getObject() : nullptr; } +SPMask *SPItem::getMaskObject() const +{ + return mask_ref ? mask_ref->getObject() : nullptr; +} SPMaskReference &SPItem::getMaskRef() { @@ -130,15 +127,18 @@ SPAvoidRef &SPItem::getAvoidRef() return *avoidRef; } -bool SPItem::isVisibleAndUnlocked() const { +bool SPItem::isVisibleAndUnlocked() const +{ return (!isHidden() && !isLocked()); } -bool SPItem::isVisibleAndUnlocked(unsigned display_key) const { +bool SPItem::isVisibleAndUnlocked(unsigned display_key) const +{ return (!isHidden(display_key) && !isLocked()); } -bool SPItem::isLocked() const { +bool SPItem::isLocked() const +{ for (SPObject const *o = this; o != nullptr; o = o->parent) { SPItem const *item = dynamic_cast(o); if (item && !(item->sensitive)) { @@ -148,36 +148,37 @@ bool SPItem::isLocked() const { return false; } -void SPItem::setLocked(bool locked) { - setAttribute("sodipodi:insensitive", - ( locked ? "1" : nullptr )); +void SPItem::setLocked(bool locked) +{ + setAttribute("sodipodi:insensitive", (locked ? "1" : nullptr)); updateRepr(); document->_emitModified(); } -bool SPItem::isHidden() const { +bool SPItem::isHidden() const +{ if (!isEvaluated()) return true; return style->display.computed == SP_CSS_DISPLAY_NONE; } -void SPItem::setHidden(bool hide) { +void SPItem::setHidden(bool hide) +{ style->display.set = TRUE; - style->display.value = ( hide ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE ); + style->display.value = (hide ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE); style->display.computed = style->display.value; style->display.inherit = FALSE; updateRepr(); } -bool SPItem::isHidden(unsigned display_key) const { +bool SPItem::isHidden(unsigned display_key) const +{ if (!isEvaluated()) return true; - for ( SPItemView *view(display) ; view ; view = view->next ) { - if ( view->key == display_key ) { + for (SPItemView *view(display); view; view = view->next) { + if (view->key == display_key) { g_assert(view->arenaitem != nullptr); - for ( Inkscape::DrawingItem *arenaitem = view->arenaitem ; - arenaitem ; arenaitem = arenaitem->parent() ) - { + for (Inkscape::DrawingItem *arenaitem = view->arenaitem; arenaitem; arenaitem = arenaitem->parent()) { if (!arenaitem->visible()) { return true; } @@ -188,42 +189,42 @@ bool SPItem::isHidden(unsigned display_key) const { return true; } -bool SPItem::isHighlightSet() const { +bool SPItem::isHighlightSet() const +{ return _highlightColor != nullptr; } -guint32 SPItem::highlight_color() const { - if (_highlightColor) - { +guint32 SPItem::highlight_color() const +{ + if (_highlightColor) { return atoi(_highlightColor) | 0x00000000; - } - else { + } else { SPItem const *item = dynamic_cast(parent); - if (parent && (parent != this) && item) - { + if (parent && (parent != this) && item) { return item->highlight_color(); - } - else - { + } else { static Inkscape::Preferences *prefs = Inkscape::Preferences::get(); return prefs->getInt("/tools/nodes/highlight_color", 0xff0000ff); } } } -void SPItem::setEvaluated(bool evaluated) { +void SPItem::setEvaluated(bool evaluated) +{ _is_evaluated = evaluated; _evaluated_status = StatusSet; } -void SPItem::resetEvaluated() { - if ( StatusCalculated == _evaluated_status ) { +void SPItem::resetEvaluated() +{ + if (StatusCalculated == _evaluated_status) { _evaluated_status = StatusUnknown; bool oldValue = _is_evaluated; - if ( oldValue != isEvaluated() ) { + if (oldValue != isEvaluated()) { requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); } - } if ( StatusSet == _evaluated_status ) { + } + if (StatusSet == _evaluated_status) { SPSwitch *switchItem = dynamic_cast(parent); if (switchItem) { switchItem->resetChildEvaluated(); @@ -231,8 +232,9 @@ void SPItem::resetEvaluated() { } } -bool SPItem::isEvaluated() const { - if ( StatusUnknown == _evaluated_status ) { +bool SPItem::isEvaluated() const +{ + if (StatusUnknown == _evaluated_status) { _is_evaluated = sp_item_evaluate(this); _evaluated_status = StatusCalculated; } @@ -241,26 +243,27 @@ bool SPItem::isEvaluated() const { bool SPItem::isExplicitlyHidden() const { - return (style->display.set - && style->display.value == SP_CSS_DISPLAY_NONE); + return (style->display.set && style->display.value == SP_CSS_DISPLAY_NONE); } -void SPItem::setExplicitlyHidden(bool val) { +void SPItem::setExplicitlyHidden(bool val) +{ style->display.set = val; - style->display.value = ( val ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE ); + style->display.value = (val ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE); style->display.computed = style->display.value; updateRepr(); } -void SPItem::setCenter(Geom::Point const &object_centre) { +void SPItem::setCenter(Geom::Point const &object_centre) +{ document->ensureUpToDate(); // Copied from DocumentProperties::onDocUnitChange() gdouble viewscale = 1.0; Geom::Rect vb = this->document->getRoot()->viewBox; - if ( !vb.hasZeroArea() ) { + if (!vb.hasZeroArea()) { gdouble viewscale_w = this->document->getWidth().value("px") / vb.width(); - gdouble viewscale_h = this->document->getHeight().value("px")/ vb.height(); + gdouble viewscale_h = this->document->getHeight().value("px") / vb.height(); viewscale = std::min(viewscale_h, viewscale_w); } @@ -269,74 +272,79 @@ void SPItem::setCenter(Geom::Point const &object_centre) { if (bbox) { // object centre is document coordinates (i.e. in pixels), so we need to consider the viewbox // to translate to user units; transform_center_x/y is in user units - transform_center_x = (object_centre[Geom::X] - bbox->midpoint()[Geom::X])/viewscale; + transform_center_x = (object_centre[Geom::X] - bbox->midpoint()[Geom::X]) / viewscale; if (Geom::are_near(transform_center_x, 0)) // rounding error transform_center_x = 0; - transform_center_y = (object_centre[Geom::Y] - bbox->midpoint()[Geom::Y])/viewscale; + transform_center_y = (object_centre[Geom::Y] - bbox->midpoint()[Geom::Y]) / viewscale; if (Geom::are_near(transform_center_y, 0)) // rounding error transform_center_y = 0; } } -void -SPItem::unsetCenter() { +void SPItem::unsetCenter() +{ transform_center_x = 0; transform_center_y = 0; } -bool SPItem::isCenterSet() const { +bool SPItem::isCenterSet() const +{ return (transform_center_x != 0 || transform_center_y != 0); } // Get the item's transformation center in desktop coordinates (i.e. in pixels) -Geom::Point SPItem::getCenter() const { +Geom::Point SPItem::getCenter() const +{ document->ensureUpToDate(); // Copied from DocumentProperties::onDocUnitChange() gdouble viewscale = 1.0; Geom::Rect vb = this->document->getRoot()->viewBox; - if ( !vb.hasZeroArea() ) { + if (!vb.hasZeroArea()) { gdouble viewscale_w = this->document->getWidth().value("px") / vb.width(); - gdouble viewscale_h = this->document->getHeight().value("px")/ vb.height(); + gdouble viewscale_h = this->document->getHeight().value("px") / vb.height(); viewscale = std::min(viewscale_h, viewscale_w); } // FIXME this is seriously wrong Geom::OptRect bbox = desktopGeometricBounds(); if (bbox) { - // transform_center_x/y are stored in user units, so we have to take the viewbox into account to translate to document coordinates - return bbox->midpoint() + Geom::Point (transform_center_x*viewscale, transform_center_y*viewscale); + // transform_center_x/y are stored in user units, so we have to take the viewbox into account to translate to + // document coordinates + return bbox->midpoint() + Geom::Point(transform_center_x * viewscale, transform_center_y * viewscale); } else { return Geom::Point(0, 0); // something's wrong! } - } -void -SPItem::scaleCenter(Geom::Scale const &sc) { +void SPItem::scaleCenter(Geom::Scale const &sc) +{ transform_center_x *= sc[Geom::X]; transform_center_y *= sc[Geom::Y]; } namespace { -bool is_item(SPObject const &object) { +bool is_item(SPObject const &object) +{ return dynamic_cast(&object) != nullptr; } -} +} // namespace -void SPItem::raiseToTop() { +void SPItem::raiseToTop() +{ using Inkscape::Algorithms::find_last_if; auto topmost = find_last_if(++parent->children.iterator_to(*this), parent->children.end(), &is_item); if (topmost != parent->children.end()) { - getRepr()->parent()->changeOrder( getRepr(), topmost->getRepr() ); + getRepr()->parent()->changeOrder(getRepr(), topmost->getRepr()); } } -bool SPItem::raiseOne() { +bool SPItem::raiseOne() +{ auto next_higher = std::find_if(++parent->children.iterator_to(*this), parent->children.end(), &is_item); if (next_higher != parent->children.end()) { Inkscape::XML::Node *ref = next_higher->getRepr(); @@ -346,7 +354,8 @@ bool SPItem::raiseOne() { return false; } -bool SPItem::lowerOne() { +bool SPItem::lowerOne() +{ using Inkscape::Algorithms::find_last_if; auto next_lower = find_last_if(parent->children.begin(), parent->children.iterator_to(*this), &is_item); @@ -362,7 +371,8 @@ bool SPItem::lowerOne() { return false; } -void SPItem::lowerToBottom() { +void SPItem::lowerToBottom() +{ auto bottom = std::find_if(parent->children.begin(), parent->children.iterator_to(*this), &is_item); if (bottom != parent->children.iterator_to(*this)) { Inkscape::XML::Node *ref = nullptr; @@ -374,17 +384,17 @@ void SPItem::lowerToBottom() { } } -void SPItem::moveTo(SPItem *target, bool intoafter) { - - Inkscape::XML::Node *target_ref = ( target ? target->getRepr() : nullptr ); +void SPItem::moveTo(SPItem *target, bool intoafter) +{ + Inkscape::XML::Node *target_ref = (target ? target->getRepr() : nullptr); Inkscape::XML::Node *our_ref = getRepr(); if (!target_ref) { // Assume move to the "first" in the top node, find the top node intoafter = false; - SPObject* bottom = this->document->getObjectByRepr(our_ref->root())->firstChild(); - while(!dynamic_cast(bottom->getNext())){ - bottom = bottom->getNext(); + SPObject *bottom = this->document->getObjectByRepr(our_ref->root())->firstChild(); + while (!dynamic_cast(bottom->getNext())) { + bottom = bottom->getNext(); } target_ref = bottom->getRepr(); } @@ -408,8 +418,9 @@ void SPItem::moveTo(SPItem *target, bool intoafter) { } } -void SPItem::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPItem* object = this; +void SPItem::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPItem *object = this; object->readAttr(SPAttr::STYLE); object->readAttr(SPAttr::TRANSFORM); @@ -425,8 +436,9 @@ void SPItem::build(SPDocument *document, Inkscape::XML::Node *repr) { SPObject::build(document, repr); } -void SPItem::release() { - SPItem* item = this; +void SPItem::release() +{ + SPItem *item = this; // Note: do this here before the clip_ref is deleted, since calling // ensureUpToDate() for triggered routing may reference @@ -453,12 +465,13 @@ void SPItem::release() { item->display = sp_item_view_list_remove(item->display, item->display); } - //item->_transformed_signal.~signal(); + // item->_transformed_signal.~signal(); } -void SPItem::set(SPAttr key, gchar const* value) { +void SPItem::set(SPAttr key, gchar const *value) +{ SPItem *item = this; - SPItem* object = item; + SPItem *object = item; switch (key) { case SPAttr::TRANSFORM: { @@ -484,16 +497,14 @@ void SPItem::set(SPAttr key, gchar const* value) { } break; } - case SPAttr::SODIPODI_INSENSITIVE: - { + case SPAttr::SODIPODI_INSENSITIVE: { item->sensitive = !value; for (SPItemView *v = item->display; v != nullptr; v = v->next) { v->arenaitem->setSensitive(item->sensitive); } break; } - case SPAttr::INKSCAPE_HIGHLIGHT_COLOR: - { + case SPAttr::INKSCAPE_HIGHLIGHT_COLOR: { g_free(item->_highlightColor); if (value) { item->_highlightColor = g_strdup(value); @@ -526,11 +537,10 @@ void SPItem::set(SPAttr key, gchar const* value) { break; case SPAttr::SYSTEM_LANGUAGE: case SPAttr::REQUIRED_FEATURES: - case SPAttr::REQUIRED_EXTENSIONS: - { - item->resetEvaluated(); - // pass to default handler - } + case SPAttr::REQUIRED_EXTENSIONS: { + item->resetEvaluated(); + // pass to default handler + } default: if (SP_ATTRIBUTE_IS_CSS(key)) { style->clear(key); @@ -561,9 +571,7 @@ void SPItem::clip_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item) if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } - Inkscape::DrawingItem *ai = clipPath->show( - v->arenaitem->drawing(), - v->arenaitem->key()); + Inkscape::DrawingItem *ai = clipPath->show(v->arenaitem->drawing(), v->arenaitem->key()); v->arenaitem->setClip(ai); clipPath->setBBox(v->arenaitem->key(), bbox); clip->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); @@ -589,9 +597,7 @@ void SPItem::mask_ref_changed(SPObject *old_mask, SPObject *mask, SPItem *item) if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } - Inkscape::DrawingItem *ai = maskItem->sp_mask_show( - v->arenaitem->drawing(), - v->arenaitem->key()); + Inkscape::DrawingItem *ai = maskItem->sp_mask_show(v->arenaitem->drawing(), v->arenaitem->key()); v->arenaitem->setMask(ai); maskItem->sp_mask_set_bbox(v->arenaitem->key(), bbox); mask->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); @@ -599,10 +605,11 @@ void SPItem::mask_ref_changed(SPObject *old_mask, SPObject *mask, SPItem *item) } } -void SPItem::fill_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) { +void SPItem::fill_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) +{ SPPaintServer *old_fill_ps = dynamic_cast(old_ps); if (old_fill_ps) { - for (SPItemView *v =item->display; v != nullptr; v = v->next) { + for (SPItemView *v = item->display; v != nullptr; v = v->next) { old_fill_ps->hide(v->arenaitem->key()); } } @@ -614,8 +621,7 @@ void SPItem::fill_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) { if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } - Inkscape::DrawingPattern *pi = new_fill_ps->show( - v->arenaitem->drawing(), v->arenaitem->key(), bbox); + Inkscape::DrawingPattern *pi = new_fill_ps->show(v->arenaitem->drawing(), v->arenaitem->key(), bbox); v->arenaitem->setFillPattern(pi); if (pi) { new_fill_ps->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); @@ -624,10 +630,11 @@ void SPItem::fill_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) { } } -void SPItem::stroke_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) { +void SPItem::stroke_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) +{ SPPaintServer *old_stroke_ps = dynamic_cast(old_ps); if (old_stroke_ps) { - for (SPItemView *v =item->display; v != nullptr; v = v->next) { + for (SPItemView *v = item->display; v != nullptr; v = v->next) { old_stroke_ps->hide(v->arenaitem->key()); } } @@ -639,8 +646,7 @@ void SPItem::stroke_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } - Inkscape::DrawingPattern *pi = new_stroke_ps->show( - v->arenaitem->drawing(), v->arenaitem->key(), bbox); + Inkscape::DrawingPattern *pi = new_stroke_ps->show(v->arenaitem->drawing(), v->arenaitem->key(), bbox); v->arenaitem->setStrokePattern(pi); if (pi) { new_stroke_ps->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); @@ -649,8 +655,8 @@ void SPItem::stroke_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) } } -void SPItem::update(SPCtx* ctx, guint flags) { - +void SPItem::update(SPCtx *ctx, guint flags) +{ SPItemCtx const *ictx = reinterpret_cast(ctx); // Any of the modifications defined in sp-object.h might change bbox, @@ -659,9 +665,7 @@ void SPItem::update(SPCtx* ctx, guint flags) { viewport = ictx->viewport; // Cache viewport - if (flags & (SP_OBJECT_CHILD_MODIFIED_FLAG | - SP_OBJECT_MODIFIED_FLAG | - SP_OBJECT_STYLE_MODIFIED_FLAG) ) { + if (flags & (SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG)) { if (flags & SP_OBJECT_MODIFIED_FLAG) { for (SPItemView *v = display; v != nullptr; v = v->next) { v->arenaitem->setTransform(transform); @@ -671,7 +675,7 @@ void SPItem::update(SPCtx* ctx, guint flags) { SPClipPath *clip_path = clip_ref ? clip_ref->getObject() : nullptr; SPMask *mask = mask_ref ? mask_ref->getObject() : nullptr; - if ( clip_path || mask ) { + if (clip_path || mask) { Geom::OptRect bbox = geometricBounds(); if (clip_path) { for (SPItemView *v = display; v != nullptr; v = v->next) { @@ -688,9 +692,10 @@ void SPItem::update(SPCtx* ctx, guint flags) { if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) { for (SPItemView *v = display; v != nullptr; v = v->next) { v->arenaitem->setOpacity(SP_SCALE24_TO_FLOAT(style->opacity.value)); - v->arenaitem->setAntialiasing(style->shape_rendering.computed == SP_CSS_SHAPE_RENDERING_CRISPEDGES ? 0 : 2); - v->arenaitem->setIsolation( style->isolation.value ); - v->arenaitem->setBlendMode( style->mix_blend_mode.value ); + v->arenaitem->setAntialiasing(style->shape_rendering.computed == SP_CSS_SHAPE_RENDERING_CRISPEDGES ? 0 + : 2); + v->arenaitem->setIsolation(style->isolation.value); + v->arenaitem->setBlendMode(style->mix_blend_mode.value); v->arenaitem->setVisible(!isHidden()); } } @@ -702,7 +707,7 @@ void SPItem::update(SPCtx* ctx, guint flags) { do { if (itemview->arenaitem) itemview->arenaitem->setItemBounds(item_bbox); - } while ( (itemview = itemview->next) ); + } while ((itemview = itemview->next)); } // Update libavoid with item geometry (for connector routing). @@ -714,20 +719,21 @@ void SPItem::update(SPCtx* ctx, guint flags) { void SPItem::modified(unsigned int /*flags*/) { #ifdef OBJECT_TRACE - objectTrace( "SPItem::modified" ); - objectTrace( "SPItem::modified", false ); + objectTrace("SPItem::modified"); + objectTrace("SPItem::modified", false); #endif } -Inkscape::XML::Node* SPItem::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPItem::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ SPItem *item = this; - SPItem* object = item; + SPItem *object = item; // in the case of SP_OBJECT_WRITE_BUILD, the item should always be newly created, // so we need to add any children from the underlying object to the new repr if (flags & SP_OBJECT_WRITE_BUILD) { - std::vectorl; - for (auto& child: object->children) { + std::vector l; + for (auto &child : object->children) { if (dynamic_cast(&child) || dynamic_cast(&child)) { Inkscape::XML::Node *crepr = child.updateRepr(xml_doc, nullptr, flags); if (crepr) { @@ -735,12 +741,12 @@ Inkscape::XML::Node* SPItem::write(Inkscape::XML::Document *xml_doc, Inkscape::X } } } - for (auto i = l.rbegin(); i!= l.rend(); ++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: object->children) { + for (auto &child : object->children) { if (dynamic_cast(&child) || dynamic_cast(&child)) { child.updateRepr(flags); } @@ -752,32 +758,32 @@ Inkscape::XML::Node* SPItem::write(Inkscape::XML::Document *xml_doc, Inkscape::X g_free(c); if (flags & SP_OBJECT_WRITE_EXT) { - repr->setAttribute("sodipodi:insensitive", ( item->sensitive ? nullptr : "true" )); + repr->setAttribute("sodipodi:insensitive", (item->sensitive ? nullptr : "true")); if (item->transform_center_x != 0) - sp_repr_set_svg_double (repr, "inkscape:transform-center-x", item->transform_center_x); + sp_repr_set_svg_double(repr, "inkscape:transform-center-x", item->transform_center_x); else repr->removeAttribute("inkscape:transform-center-x"); if (item->transform_center_y != 0) { auto y = item->transform_center_y; y *= -document->yaxisdir(); - sp_repr_set_svg_double (repr, "inkscape:transform-center-y", y); + sp_repr_set_svg_double(repr, "inkscape:transform-center-y", y); } else repr->removeAttribute("inkscape:transform-center-y"); } - if (item->clip_ref){ + if (item->clip_ref) { if (item->clip_ref->getObject()) { auto value = item->clip_ref->getURI()->cssStr(); repr->setAttributeOrRemoveIfEmpty("clip-path", value); } } - if (item->mask_ref){ + if (item->mask_ref) { if (item->mask_ref->getObject()) { auto value = item->mask_ref->getURI()->cssStr(); repr->setAttributeOrRemoveIfEmpty("mask", value); } } - if (item->_highlightColor){ + if (item->_highlightColor) { repr->setAttribute("inkscape:highlight-color", item->_highlightColor); } else { repr->removeAttribute("inkscape:highlight-color"); @@ -789,9 +795,10 @@ Inkscape::XML::Node* SPItem::write(Inkscape::XML::Document *xml_doc, Inkscape::X } // CPPIFY: make pure virtual -Geom::OptRect SPItem::bbox(Geom::Affine const & /*transform*/, SPItem::BBoxType /*type*/) const { - //throw; - return Geom::OptRect(); +Geom::OptRect SPItem::bbox(Geom::Affine const & /*transform*/, SPItem::BBoxType /*type*/) const +{ + // throw; + return Geom::OptRect(); } Geom::OptRect SPItem::geometricBounds(Geom::Affine const &transform) const @@ -800,8 +807,8 @@ Geom::OptRect SPItem::geometricBounds(Geom::Affine const &transform) const // call the subclass method // CPPIFY - //bbox = this->bbox(transform, SPItem::GEOMETRIC_BBOX); - bbox = const_cast(this)->bbox(transform, SPItem::GEOMETRIC_BBOX); + // bbox = this->bbox(transform, SPItem::GEOMETRIC_BBOX); + bbox = const_cast(this)->bbox(transform, SPItem::GEOMETRIC_BBOX); return bbox; } @@ -813,13 +820,12 @@ Geom::OptRect SPItem::visualBounds(Geom::Affine const &transform, bool wfilter, Geom::OptRect bbox; - SPFilter *filter = style ? style->getFilter() : nullptr; if (filter && wfilter) { // call the subclass method - // CPPIFY - //bbox = this->bbox(Geom::identity(), SPItem::VISUAL_BBOX); - bbox = const_cast(this)->bbox(Geom::identity(), SPItem::GEOMETRIC_BBOX); // see LP Bug 1229971 + // CPPIFY + // bbox = this->bbox(Geom::identity(), SPItem::VISUAL_BBOX); + bbox = const_cast(this)->bbox(Geom::identity(), SPItem::GEOMETRIC_BBOX); // see LP Bug 1229971 // default filer area per the SVG spec: SVGLength x, y, w, h; @@ -862,18 +868,18 @@ Geom::OptRect SPItem::visualBounds(Geom::Affine const &transform, bool wfilter, *bbox *= transform; } else { // call the subclass method - // CPPIFY - //bbox = this->bbox(transform, SPItem::VISUAL_BBOX); - bbox = const_cast(this)->bbox(transform, SPItem::VISUAL_BBOX); + // CPPIFY + // bbox = this->bbox(transform, SPItem::VISUAL_BBOX); + bbox = const_cast(this)->bbox(transform, SPItem::VISUAL_BBOX); } if (clip_ref && clip_ref->getObject() && wclip) { SPItem *ownerItem = dynamic_cast(clip_ref->getOwner()); g_assert(ownerItem != nullptr); - ownerItem->bbox_valid = FALSE; // LP Bug 1349018 + ownerItem->bbox_valid = FALSE; // LP Bug 1349018 bbox.intersectWith(clip_ref->getObject()->geometricBounds(transform)); } if (mask_ref && mask_ref->getObject() && wmask) { - bbox_valid = false; // LP Bug 1349018 + bbox_valid = false; // LP Bug 1349018 bbox.intersectWith(mask_ref->getObject()->visualBounds(transform)); } @@ -898,8 +904,6 @@ Geom::OptRect SPItem::documentPreferredBounds() const } } - - Geom::OptRect SPItem::documentGeometricBounds() const { return geometricBounds(i2doc_affine()); @@ -954,13 +958,14 @@ Geom::OptRect SPItem::desktopBounds(BBoxType type) const } } -unsigned int SPItem::pos_in_parent() const { +unsigned int SPItem::pos_in_parent() const +{ g_assert(parent != nullptr); g_assert(SP_IS_OBJECT(parent)); unsigned int pos = 0; - for (auto& iter: parent->children) { + for (auto &iter : parent->children) { if (&iter == this) { return pos; } @@ -975,21 +980,24 @@ unsigned int SPItem::pos_in_parent() const { } // CPPIFY: make pure virtual, see below! -void SPItem::snappoints(std::vector & /*p*/, Inkscape::SnapPreferences const */*snapprefs*/) const { - //throw; +void SPItem::snappoints(std::vector & /*p*/, + Inkscape::SnapPreferences const * /*snapprefs*/) const +{ + // throw; } - /* This will only be called if the derived class doesn't override this. - * see for example sp_genericellipse_snappoints in sp-ellipse.cpp - * We don't know what shape we could be dealing with here, so we'll just - * do nothing - */ +/* This will only be called if the derived class doesn't override this. + * see for example sp_genericellipse_snappoints in sp-ellipse.cpp + * We don't know what shape we could be dealing with here, so we'll just + * do nothing + */ -void SPItem::getSnappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const +void SPItem::getSnappoints(std::vector &p, + Inkscape::SnapPreferences const *snapprefs) const { // Get the snappoints of the item - // CPPIFY - //this->snappoints(p, snapprefs); - const_cast(this)->snappoints(p, snapprefs); + // CPPIFY + // this->snappoints(p, snapprefs); + const_cast(this)->snappoints(p, snapprefs); // Get the snappoints at the item's center if (snapprefs != nullptr && snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_ROTATION_CENTER)) { @@ -999,21 +1007,23 @@ void SPItem::getSnappoints(std::vector &p, Inkscap // Get the snappoints of clipping paths and mask, if any std::list clips_and_masks; - if (clip_ref) clips_and_masks.push_back(clip_ref->getObject()); - if (mask_ref) clips_and_masks.push_back(mask_ref->getObject()); + if (clip_ref) + clips_and_masks.push_back(clip_ref->getObject()); + if (mask_ref) + clips_and_masks.push_back(mask_ref->getObject()); SPDesktop *desktop = SP_ACTIVE_DESKTOP; for (std::list::const_iterator o = clips_and_masks.begin(); o != clips_and_masks.end(); ++o) { if (*o) { // obj is a group object, the children are the actual clippers - for(auto& child: (*o)->children) { - SPItem *item = dynamic_cast(const_cast(&child)); + for (auto &child : (*o)->children) { + SPItem *item = dynamic_cast(const_cast(&child)); if (item) { std::vector p_clip_or_mask; // Please note the recursive call here! item->getSnappoints(p_clip_or_mask, snapprefs); // Take into account the transformation of the item being clipped or masked - for (const auto & p_orig : p_clip_or_mask) { + for (const auto &p_orig : p_clip_or_mask) { // All snappoints are in desktop coordinates, but the item's transformation is // in document coordinates. Hence the awkward construction below Geom::Point pt = desktop->dt2doc(p_orig.getPoint()) * i2dt_affine(); @@ -1026,79 +1036,84 @@ void SPItem::getSnappoints(std::vector &p, Inkscap } // CPPIFY: make pure virtual -void SPItem::print(SPPrintContext* /*ctx*/) { - //throw; +void SPItem::print(SPPrintContext * /*ctx*/) +{ + // throw; } void SPItem::invoke_print(SPPrintContext *ctx) { - if ( !isHidden() ) { - if (!transform.isIdentity() || style->opacity.value != SP_SCALE24_MAX) { - ctx->bind(transform, SP_SCALE24_TO_FLOAT(style->opacity.value)); - this->print(ctx); - ctx->release(); - } else { - this->print(ctx); - } + if (!isHidden()) { + if (!transform.isIdentity() || style->opacity.value != SP_SCALE24_MAX) { + ctx->bind(transform, SP_SCALE24_TO_FLOAT(style->opacity.value)); + this->print(ctx); + ctx->release(); + } else { + this->print(ctx); + } } } -const char* SPItem::displayName() const { +const char *SPItem::displayName() const +{ return _("Object"); } -gchar* SPItem::description() const { +gchar *SPItem::description() const +{ return g_strdup(""); } -gchar *SPItem::detailedDescription() const { - gchar* s = g_strdup_printf("%s %s", - this->displayName(), this->description()); +gchar *SPItem::detailedDescription() const +{ + gchar *s = g_strdup_printf("%s %s", this->displayName(), this->description()); - if (s && clip_ref && clip_ref->getObject()) { - gchar *snew = g_strdup_printf (_("%s; clipped"), s); - g_free (s); - s = snew; - } + if (s && clip_ref && clip_ref->getObject()) { + gchar *snew = g_strdup_printf(_("%s; clipped"), s); + g_free(s); + s = snew; + } - if (s && mask_ref && mask_ref->getObject()) { - gchar *snew = g_strdup_printf (_("%s; masked"), s); - g_free (s); - s = snew; - } + if (s && mask_ref && mask_ref->getObject()) { + gchar *snew = g_strdup_printf(_("%s; masked"), s); + g_free(s); + s = snew; + } - if ( style && style->filter.href && style->filter.href->getObject() ) { - const gchar *label = style->filter.href->getObject()->label(); - gchar *snew = nullptr; + if (style && style->filter.href && style->filter.href->getObject()) { + const gchar *label = style->filter.href->getObject()->label(); + gchar *snew = nullptr; - if (label) { - snew = g_strdup_printf (_("%s; filtered (%s)"), s, _(label)); - } else { - snew = g_strdup_printf (_("%s; filtered"), s); - } + if (label) { + snew = g_strdup_printf(_("%s; filtered (%s)"), s, _(label)); + } else { + snew = g_strdup_printf(_("%s; filtered"), s); + } - g_free (s); - s = snew; - } + g_free(s); + s = snew; + } - return s; + return s; } -bool SPItem::isFiltered() const { - return (style && style->filter.href && style->filter.href->getObject()); +bool SPItem::isFiltered() const +{ + return (style && style->filter.href && style->filter.href->getObject()); } - -SPObject* SPItem::isInMask() const { - SPObject* parent = this->parent; +SPObject *SPItem::isInMask() const +{ + SPObject *parent = this->parent; while (parent && !dynamic_cast(parent)) { parent = parent->parent; } return parent; } -SPObject* SPItem::isInClipPath() const { - SPObject* parent = this->parent; +SPObject *SPItem::isInClipPath() const +{ + SPObject *parent = this->parent; while (parent && !dynamic_cast(parent)) { parent = parent->parent; } @@ -1115,9 +1130,10 @@ unsigned SPItem::display_key_new(unsigned numkeys) } // CPPIFY: make pure virtual -Inkscape::DrawingItem* SPItem::show(Inkscape::Drawing& /*drawing*/, unsigned int /*key*/, unsigned int /*flags*/) { - //throw; - return nullptr; +Inkscape::DrawingItem *SPItem::show(Inkscape::Drawing & /*drawing*/, unsigned int /*key*/, unsigned int /*flags*/) +{ + // throw; + return nullptr; } Inkscape::DrawingItem *SPItem::invoke_show(Inkscape::Drawing &drawing, unsigned key, unsigned flags) @@ -1132,9 +1148,9 @@ Inkscape::DrawingItem *SPItem::invoke_show(Inkscape::Drawing &drawing, unsigned display = sp_item_view_new_prepend(display, this, flags, key, ai); ai->setTransform(transform); ai->setOpacity(SP_SCALE24_TO_FLOAT(style->opacity.value)); - ai->setIsolation( style->isolation.value ); - ai->setBlendMode( style->mix_blend_mode.value ); - //ai->setCompositeOperator( style->composite_op.value ); + ai->setIsolation(style->isolation.value); + ai->setBlendMode(style->mix_blend_mode.value); + // ai->setCompositeOperator( style->composite_op.value ); ai->setVisible(!isHidden()); ai->setSensitive(sensitive); if (clip_ref && clip_ref->getObject()) { @@ -1204,8 +1220,9 @@ Inkscape::DrawingItem *SPItem::invoke_show(Inkscape::Drawing &drawing, unsigned } // CPPIFY: make pure virtual -void SPItem::hide(unsigned int /*key*/) { - //throw; +void SPItem::hide(unsigned int /*key*/) +{ + // throw; } void SPItem::invoke_hide(unsigned key) @@ -1255,7 +1272,7 @@ void SPItem::adjust_pattern(Geom::Affine const &postmul, bool set, PaintServerTr if (fill && style && (style->fill.isPaintserver())) { SPObject *server = style->getFillPaintServer(); SPPattern *serverPatt = dynamic_cast(server); - if ( serverPatt ) { + if (serverPatt) { SPPattern *pattern = serverPatt->clone_if_necessary(this, "fill"); pattern->transform_multiply(postmul, set); } @@ -1265,7 +1282,7 @@ void SPItem::adjust_pattern(Geom::Affine const &postmul, bool set, PaintServerTr if (stroke && style && (style->stroke.isPaintserver())) { SPObject *server = style->getStrokePaintServer(); SPPattern *serverPatt = dynamic_cast(server); - if ( serverPatt ) { + if (serverPatt) { SPPattern *pattern = serverPatt->clone_if_necessary(this, "stroke"); pattern->transform_multiply(postmul, set); } @@ -1295,13 +1312,12 @@ void SPItem::adjust_hatch(Geom::Affine const &postmul, bool set, PaintServerTran } } -void SPItem::adjust_gradient( Geom::Affine const &postmul, bool set ) +void SPItem::adjust_gradient(Geom::Affine const &postmul, bool set) { - if ( style && style->fill.isPaintserver() ) { + if (style && style->fill.isPaintserver()) { SPPaintServer *server = style->getFillPaintServer(); SPGradient *serverGrad = dynamic_cast(server); - if ( serverGrad ) { - + if (serverGrad) { /** * \note Bbox units for a gradient are generally a bad idea because * with them, you cannot preserve the relative position of the @@ -1311,23 +1327,23 @@ void SPItem::adjust_gradient( Geom::Affine const &postmul, bool set ) * \todo FIXME: convert back to bbox units after transforming with * the item, so as to preserve the original units. */ - SPGradient *gradient = sp_gradient_convert_to_userspace( serverGrad, this, "fill" ); + SPGradient *gradient = sp_gradient_convert_to_userspace(serverGrad, this, "fill"); - sp_gradient_transform_multiply( gradient, postmul, set ); + sp_gradient_transform_multiply(gradient, postmul, set); } } - if ( style && style->stroke.isPaintserver() ) { + if (style && style->stroke.isPaintserver()) { SPPaintServer *server = style->getStrokePaintServer(); SPGradient *serverGrad = dynamic_cast(server); - if ( serverGrad ) { - SPGradient *gradient = sp_gradient_convert_to_userspace( serverGrad, this, "stroke"); - sp_gradient_transform_multiply( gradient, postmul, set ); + if (serverGrad) { + SPGradient *gradient = sp_gradient_convert_to_userspace(serverGrad, this, "stroke"); + sp_gradient_transform_multiply(gradient, postmul, set); } } } -void SPItem::adjust_stroke( gdouble ex ) +void SPItem::adjust_stroke(gdouble ex) { if (freeze_stroke_width) { return; @@ -1339,12 +1355,12 @@ void SPItem::adjust_stroke( gdouble ex ) style->stroke_width.computed *= ex; style->stroke_width.set = TRUE; - if ( !style->stroke_dasharray.values.empty() ) { - for (auto & value : style->stroke_dasharray.values) { - value.value *= ex; + if (!style->stroke_dasharray.values.empty()) { + for (auto &value : style->stroke_dasharray.values) { + value.value *= ex; value.computed *= ex; } - style->stroke_dashoffset.value *= ex; + style->stroke_dashoffset.value *= ex; style->stroke_dashoffset.computed *= ex; } @@ -1355,7 +1371,7 @@ void SPItem::adjust_stroke( gdouble ex ) /** * Find out the inverse of previous transform of an item (from its repr) */ -Geom::Affine sp_item_transform_repr (SPItem *item) +Geom::Affine sp_item_transform_repr(SPItem *item) { Geom::Affine t_old(Geom::identity()); gchar const *t_attr = item->getRepr()->attribute("transform"); @@ -1369,14 +1385,13 @@ Geom::Affine sp_item_transform_repr (SPItem *item) return t_old; } - void SPItem::adjust_stroke_width_recursive(double expansion) { - adjust_stroke (expansion); + adjust_stroke(expansion); -// A clone's child is the ghost of its original - we must not touch it, skip recursion - if ( !dynamic_cast(this) ) { - for (auto& o: children) { + // A clone's child is the ghost of its original - we must not touch it, skip recursion + if (!dynamic_cast(this)) { + for (auto &o : children) { SPItem *item = dynamic_cast(&o); if (item) { item->adjust_stroke_width_recursive(expansion); @@ -1389,9 +1404,9 @@ void SPItem::freeze_stroke_width_recursive(bool freeze) { freeze_stroke_width = freeze; -// A clone's child is the ghost of its original - we must not touch it, skip recursion - if ( !dynamic_cast(this) ) { - for (auto& o: children) { + // A clone's child is the ghost of its original - we must not touch it, skip recursion + if (!dynamic_cast(this)) { + for (auto &o : children) { SPItem *item = dynamic_cast(&o); if (item) { item->freeze_stroke_width_recursive(freeze); @@ -1403,15 +1418,14 @@ void SPItem::freeze_stroke_width_recursive(bool freeze) /** * Recursively adjust rx and ry of rects. */ -static void -sp_item_adjust_rects_recursive(SPItem *item, Geom::Affine advertized_transform) +static void sp_item_adjust_rects_recursive(SPItem *item, Geom::Affine advertized_transform) { SPRect *rect = dynamic_cast(item); if (rect) { - rect->compensateRxRy(advertized_transform); + rect->compensateRxRy(advertized_transform); } - for(auto& o: item->children) { + for (auto &o : item->children) { SPItem *itm = dynamic_cast(&o); if (itm) { sp_item_adjust_rects_recursive(itm, advertized_transform); @@ -1421,17 +1435,17 @@ sp_item_adjust_rects_recursive(SPItem *item, Geom::Affine advertized_transform) void SPItem::adjust_paint_recursive(Geom::Affine advertized_transform, Geom::Affine t_ancestors, PaintServerType type) { -// _Before_ full pattern/gradient transform: t_paint * t_item * t_ancestors -// _After_ full pattern/gradient transform: t_paint_new * t_item * t_ancestors * advertised_transform -// By equating these two expressions we get t_paint_new = t_paint * paint_delta, where: - Geom::Affine t_item = sp_item_transform_repr (this); + // _Before_ full pattern/gradient transform: t_paint * t_item * t_ancestors + // _After_ full pattern/gradient transform: t_paint_new * t_item * t_ancestors * advertised_transform + // By equating these two expressions we get t_paint_new = t_paint * paint_delta, where: + Geom::Affine t_item = sp_item_transform_repr(this); Geom::Affine paint_delta = t_item * t_ancestors * advertized_transform * t_ancestors.inverse() * t_item.inverse(); -// Within text, we do not fork gradients, and so must not recurse to avoid double compensation; -// also we do not recurse into clones, because a clone's child is the ghost of its original - -// we must not touch it + // Within text, we do not fork gradients, and so must not recurse to avoid double compensation; + // also we do not recurse into clones, because a clone's child is the ghost of its original - + // we must not touch it if (!(dynamic_cast(this) || dynamic_cast(this))) { - for (auto& o: children) { + for (auto &o : children) { SPItem *item = dynamic_cast(&o); if (item) { // At the level of the transformed item, t_ancestors is identity; @@ -1441,10 +1455,10 @@ void SPItem::adjust_paint_recursive(Geom::Affine advertized_transform, Geom::Aff } } -// We recursed into children first, and are now adjusting this object second; -// this is so that adjustments in a tree are done from leaves up to the root, -// and paintservers on leaves inheriting their values from ancestors could adjust themselves properly -// before ancestors themselves are adjusted, probably differently (bug 1286535) + // We recursed into children first, and are now adjusting this object second; + // this is so that adjustments in a tree are done from leaves up to the root, + // and paintservers on leaves inheriting their values from ancestors could adjust themselves properly + // before ancestors themselves are adjusted, probably differently (bug 1286535) switch (type) { case PATTERN: { @@ -1463,9 +1477,10 @@ void SPItem::adjust_paint_recursive(Geom::Affine advertized_transform, Geom::Aff // CPPIFY:: make pure virtual? // Not all SPItems must necessarily have a set transform method! -Geom::Affine SPItem::set_transform(Geom::Affine const &transform) { -// throw; - return transform; +Geom::Affine SPItem::set_transform(Geom::Affine const &transform) +{ + // throw; + return transform; } void SPItem::doWriteTransform(Geom::Affine const &transform, Geom::Affine const *adv, bool compensate) @@ -1475,25 +1490,25 @@ void SPItem::doWriteTransform(Geom::Affine const &transform, Geom::Affine const if (adv != nullptr) { advertized_transform = *adv; } else { - advertized_transform = sp_item_transform_repr (this).inverse() * transform; + advertized_transform = sp_item_transform_repr(this).inverse() * transform; } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (compensate) { - // recursively compensating for stroke scaling will not always work, because it can be scaled to zero or infinite - // from which we cannot ever recover by applying an inverse scale; therefore we temporarily block any changes - // to the strokewidth in such a case instead, and unblock these after the transformation - // (as reported in https://bugs.launchpad.net/inkscape/+bug/825840/comments/4) + // recursively compensating for stroke scaling will not always work, because it can be scaled to zero or + // infinite from which we cannot ever recover by applying an inverse scale; therefore we temporarily block any + // changes to the strokewidth in such a case instead, and unblock these after the transformation (as reported in + // https://bugs.launchpad.net/inkscape/+bug/825840/comments/4) if (!prefs->getBool("/options/transform/stroke", true)) { double const expansion = 1. / advertized_transform.descrim(); if (expansion < 1e-9 || expansion > 1e9) { freeze_stroke_width_recursive(true); - // This will only work if the item has a set_transform method (in this method adjust_stroke() will be called) - // We will still have to apply the inverse scaling to other items, not having a set_transform method - // such as ellipses and stars - // PS: We cannot use this freeze_stroke_width_recursive() trick in all circumstances. For example, it will - // break pasting objects within their group (because in such a case the transformation of the group will affect - // the strokewidth, and has to be compensated for. See https://bugs.launchpad.net/inkscape/+bug/959223/comments/10) + // This will only work if the item has a set_transform method (in this method adjust_stroke() will be + // called) We will still have to apply the inverse scaling to other items, not having a set_transform + // method such as ellipses and stars PS: We cannot use this freeze_stroke_width_recursive() trick in all + // circumstances. For example, it will break pasting objects within their group (because in such a case + // the transformation of the group will affect the strokewidth, and has to be compensated for. See + // https://bugs.launchpad.net/inkscape/+bug/959223/comments/10) } else { adjust_stroke_width_recursive(expansion); } @@ -1525,23 +1540,24 @@ void SPItem::doWriteTransform(Geom::Affine const &transform, Geom::Affine const } // endif(compensate) gint preserve = prefs->getBool("/options/preservetransform/value", false); - Geom::Affine transform_attr (transform); + Geom::Affine transform_attr(transform); // CPPIFY: check this code. // If onSetTransform is not overridden, CItem::onSetTransform will return the transform it was given as a parameter. // onSetTransform cannot be pure due to the fact that not all visible Items are transformable. - SPLPEItem * lpeitem = SP_LPE_ITEM(this); + SPLPEItem *lpeitem = SP_LPE_ITEM(this); if (lpeitem) { lpeitem->notifyTransform(transform); } if ( // run the object's set_transform (i.e. embed transform) only if: (dynamic_cast(this) && firstChild() && dynamic_cast(firstChild())) || - (!preserve && // user did not chose to preserve all transforms - (!clip_ref || !clip_ref->getObject()) && // the object does not have a clippath - (!mask_ref || !mask_ref->getObject()) && // the object does not have a mask - !(!transform.isTranslation() && style && style->getFilter())) // the object does not have a filter, or the transform is translation (which is supposed to not affect filters) - ) - { + (!preserve && // user did not chose to preserve all transforms + (!clip_ref || !clip_ref->getObject()) && // the object does not have a clippath + (!mask_ref || !mask_ref->getObject()) && // the object does not have a mask + !(!transform.isTranslation() && style && style->getFilter())) // the object does not have a filter, or the + // transform is translation (which is supposed to + // not affect filters) + ) { transform_attr = this->set_transform(transform); } if (freeze_stroke_width) { @@ -1549,7 +1565,8 @@ void SPItem::doWriteTransform(Geom::Affine const &transform, Geom::Affine const if (compensate) { if (!prefs->getBool("/options/transform/stroke", true)) { // Recursively compensate for stroke scaling, depending on user preference - // (As to why we need to do this, see the comment a few lines above near the freeze_stroke_width_recursive(true) call) + // (As to why we need to do this, see the comment a few lines above near the + // freeze_stroke_width_recursive(true) call) double const expansion = 1. / advertized_transform.descrim(); adjust_stroke_width_recursive(expansion); } @@ -1578,13 +1595,14 @@ void SPItem::doWriteTransform(Geom::Affine const &transform, Geom::Affine const } // CPPIFY: see below, do not make pure? -gint SPItem::event(SPEvent* /*event*/) { - return FALSE; +gint SPItem::event(SPEvent * /*event*/) +{ + return FALSE; } gint SPItem::emitEvent(SPEvent &event) { - return this->event(&event); + return this->event(&event); } void SPItem::set_item_transform(Geom::Affine const &transform_matrix) @@ -1598,18 +1616,18 @@ void SPItem::set_item_transform(Geom::Affine const &transform_matrix) } } -//void SPItem::convert_to_guides() const { +// void SPItem::convert_to_guides() const { // // CPPIFY: If not overridden, call SPItem::convert_to_guides() const, see below! // this->convert_to_guides(); //} - -Geom::Affine i2anc_affine(SPObject const *object, SPObject const *const ancestor) { +Geom::Affine i2anc_affine(SPObject const *object, SPObject const *const ancestor) +{ Geom::Affine ret(Geom::identity()); g_return_val_if_fail(object != nullptr, ret); /* stop at first non-renderable ancestor */ - while ( object != ancestor && dynamic_cast(object) ) { + while (object != ancestor && dynamic_cast(object)) { SPRoot const *root = dynamic_cast(object); if (root) { ret *= root->c2p; @@ -1623,14 +1641,15 @@ Geom::Affine i2anc_affine(SPObject const *object, SPObject const *const ancestor return ret; } -Geom::Affine -i2i_affine(SPObject const *src, SPObject const *dest) { +Geom::Affine i2i_affine(SPObject const *src, SPObject const *dest) +{ g_return_val_if_fail(src != nullptr && dest != nullptr, Geom::identity()); SPObject const *ancestor = src->nearestCommonAncestor(dest); return i2anc_affine(src, ancestor) * i2anc_affine(dest, ancestor).inverse(); } -Geom::Affine SPItem::getRelativeTransform(SPObject const *dest) const { +Geom::Affine SPItem::getRelativeTransform(SPObject const *dest) const +{ return i2i_affine(this, dest); } @@ -1656,11 +1675,10 @@ void SPItem::set_i2d_affine(Geom::Affine const &i2dt) dt2p = document->dt2doc(); } - Geom::Affine const i2p( i2dt * dt2p ); + Geom::Affine const i2p(i2dt * dt2p); set_item_transform(i2p); } - Geom::Affine SPItem::dt2i_affine() const { /* fixme: Implement the right way (Lauris) */ @@ -1669,7 +1687,8 @@ Geom::Affine SPItem::dt2i_affine() const /* Item views */ -SPItemView *SPItem::sp_item_view_new_prepend(SPItemView *list, SPItem *item, unsigned flags, unsigned key, Inkscape::DrawingItem *drawing_item) +SPItemView *SPItem::sp_item_view_new_prepend(SPItemView *list, SPItem *item, unsigned flags, unsigned key, + Inkscape::DrawingItem *drawing_item) { g_assert(item != nullptr); g_assert(dynamic_cast(item) != nullptr); @@ -1685,8 +1704,7 @@ SPItemView *SPItem::sp_item_view_new_prepend(SPItemView *list, SPItem *item, uns return new_view; } -static SPItemView* -sp_item_view_list_remove(SPItemView *list, SPItemView *view) +static SPItemView *sp_item_view_list_remove(SPItemView *list, SPItemView *view) { SPItemView *ret = list; if (view == list) { @@ -1694,7 +1712,8 @@ sp_item_view_list_remove(SPItemView *list, SPItemView *view) } else { SPItemView *prev; prev = list; - while (prev->next != view) prev = prev->next; + while (prev->next != view) + prev = prev->next; prev->next = view->next; } @@ -1706,8 +1725,8 @@ sp_item_view_list_remove(SPItemView *list, SPItemView *view) Inkscape::DrawingItem *SPItem::get_arenaitem(unsigned key) { - for ( SPItemView *iv = display ; iv ; iv = iv->next ) { - if ( iv->key == key ) { + for (SPItemView *iv = display; iv; iv = iv->next) { + if (iv->key == key) { return iv->arenaitem; } } @@ -1717,21 +1736,20 @@ Inkscape::DrawingItem *SPItem::get_arenaitem(unsigned key) int sp_item_repr_compare_position(SPItem const *first, SPItem const *second) { - return sp_repr_compare_position(first->getRepr(), - second->getRepr()); + return sp_repr_compare_position(first->getRepr(), second->getRepr()); } SPItem const *sp_item_first_item_child(SPObject const *obj) { - return sp_item_first_item_child( const_cast(obj) ); + return sp_item_first_item_child(const_cast(obj)); } SPItem *sp_item_first_item_child(SPObject *obj) { SPItem *child = nullptr; - for (auto& iter: obj->children) { + for (auto &iter : obj->children) { SPItem *tmp = dynamic_cast(&iter); - if ( tmp ) { + if (tmp) { child = tmp; break; } @@ -1739,17 +1757,18 @@ SPItem *sp_item_first_item_child(SPObject *obj) return child; } -void SPItem::convert_to_guides() const { +void SPItem::convert_to_guides() const +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int prefs_bbox = prefs->getInt("/tools/bounding_box", 0); Geom::OptRect bbox = (prefs_bbox == 0) ? desktopVisualBounds() : desktopGeometricBounds(); if (!bbox) { - g_warning ("Cannot determine item's bounding box during conversion to guides.\n"); + g_warning("Cannot determine item's bounding box during conversion to guides.\n"); return; } - std::list > pts; + std::list> pts; Geom::Point A((*bbox).min()); Geom::Point C((*bbox).max()); @@ -1810,7 +1829,7 @@ void SPItem::skew_rel(double skewX, double skewY) } } -void SPItem::move_rel( Geom::Translate const &tr) +void SPItem::move_rel(Geom::Translate const &tr) { set_i2d_affine(i2dt_affine() * tr); diff --git a/src/object/sp-item.h b/src/object/sp-item.h index 08b45f1b004052dd82dded0557e2a6be276849e3..c70b09662976b79f25c1cbd867589a41f82806dc 100644 --- a/src/object/sp-item.h +++ b/src/object/sp-item.h @@ -21,16 +21,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <2geom/forward.h> #include <2geom/affine.h> +#include <2geom/forward.h> #include <2geom/rect.h> #include -#include "sp-object.h" -#include "snap-preferences.h" #include "snap-candidate.h" +#include "snap-preferences.h" +#include "sp-object.h" -//class SPGuideConstraint; +// class SPGuideConstraint; #include "sp-guide-constraint.h" #include "xml/repr.h" @@ -53,12 +53,17 @@ namespace UI { namespace View { class SVGViewWidget; } -} -} +} // namespace UI +} // namespace Inkscape // TODO make a completely new function that transforms either the fill or // stroke of any SPItem without adding an extra parameter to adjust_pattern. -enum PaintServerTransform { TRANSFORM_BOTH, TRANSFORM_FILL, TRANSFORM_STROKE }; +enum PaintServerTransform +{ + TRANSFORM_BOTH, + TRANSFORM_FILL, + TRANSFORM_STROKE +}; /** * Event structure. @@ -71,10 +76,11 @@ enum PaintServerTransform { TRANSFORM_BOTH, TRANSFORM_FILL, TRANSFORM_STROKE }; * * GUI Code should not be here! */ -class SPEvent { - +class SPEvent +{ public: - enum Type { + enum Type + { INVALID, NONE, ACTIVATE, @@ -83,10 +89,11 @@ public: }; Type type; - Inkscape::UI::View::SVGViewWidget* view; + Inkscape::UI::View::SVGViewWidget *view; }; -class SPItemView { +class SPItemView +{ public: SPItemView *next; unsigned int flags; @@ -109,7 +116,8 @@ public: /** * Contains transformations to document/viewport and the viewport size. */ -class SPItemCtx : public SPCtx { +class SPItemCtx : public SPCtx +{ public: /** Item to document transformation */ Geom::Affine i2doc; @@ -121,18 +129,21 @@ public: Geom::Affine i2vp; }; -#define SP_ITEM(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_ITEM(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_ITEM(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_ITEM(obj) (dynamic_cast((SPObject *)obj) != NULL) /** * Base class for visual SVG elements. * SPItem is an abstract base class for all graphic (visible) SVG nodes. It * is a subclass of SPObject, with great deal of specific functionality. */ -class SPItem : public SPObject { +class SPItem : public SPObject +{ public: - enum BBoxType { - // legacy behavior: includes crude stroke, markers; excludes long miters, blur margin; is known to be wrong for caps + enum BBoxType + { + // legacy behavior: includes crude stroke, markers; excludes long miters, blur margin; is known to be wrong for + // caps APPROXIMATE_BBOX, // includes only the bare path bbox, no stroke, no nothing GEOMETRIC_BBOX, @@ -140,13 +151,18 @@ public: VISUAL_BBOX }; - enum PaintServerType { PATTERN, HATCH, GRADIENT }; + enum PaintServerType + { + PATTERN, + HATCH, + GRADIENT + }; SPItem(); ~SPItem() override; unsigned int sensitive : 1; - unsigned int stop_paint: 1; + unsigned int stop_paint : 1; mutable unsigned bbox_valid : 1; double transform_center_x; double transform_center_y; @@ -154,7 +170,7 @@ public: Geom::Affine transform; mutable Geom::OptRect doc_bbox; - Geom::Rect viewport; // Cache viewport information + Geom::Rect viewport; // Cache viewport information SPClipPath *getClipObject() const; SPMask *getMaskObject() const; @@ -164,14 +180,14 @@ public: SPAvoidRef &getAvoidRef(); - private: +private: SPClipPathReference *clip_ref; SPMaskReference *mask_ref; // Used for object-avoiding connectors SPAvoidRef *avoidRef; - public: +public: SPItemView *display; std::vector constraints; @@ -185,9 +201,7 @@ public: void setHidden(bool hidden); // Objects dialogue - bool isSensitive() const { - return sensitive; - }; + bool isSensitive() const { return sensitive; }; bool isHighlightSet() const; guint32 highlight_color() const; @@ -244,7 +258,8 @@ public: */ void moveTo(SPItem *target, bool intoafter); - sigc::connection connectTransformed(sigc::slot slot) { + sigc::connection connectTransformed(sigc::slot slot) + { return _transformed_signal.connect(slot); } @@ -313,9 +328,9 @@ public: */ bool isFiltered() const; - SPObject* isInMask() const; + SPObject *isInMask() const; - SPObject* isInClipPath() const; + SPObject *isInClipPath() const; void invoke_print(SPPrintContext *ctx); @@ -333,7 +348,8 @@ public: // Removed item from display tree. void invoke_hide(unsigned int key); - void getSnappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs=nullptr) const; + void getSnappoints(std::vector &p, + Inkscape::SnapPreferences const *snapprefs = nullptr) const; void adjust_pattern(/* Geom::Affine const &premul, */ Geom::Affine const &postmul, bool set = false, PaintServerTransform = TRANSFORM_BOTH); void adjust_hatch(/* Geom::Affine const &premul, */ Geom::Affine const &postmul, bool set = false, @@ -370,7 +386,7 @@ public: */ void set_item_transform(Geom::Affine const &transform_matrix); - int emitEvent (SPEvent &event); + int emitEvent(SPEvent &event); /** * Return the arenaitem corresponding to the given item in the display @@ -401,37 +417,42 @@ public: private: enum EvaluatedStatus { - StatusUnknown, StatusCalculated, StatusSet + StatusUnknown, + StatusCalculated, + StatusSet }; mutable bool _is_evaluated; mutable EvaluatedStatus _evaluated_status; - static SPItemView *sp_item_view_new_prepend(SPItemView *list, SPItem *item, unsigned flags, unsigned key, Inkscape::DrawingItem *arenaitem); + static SPItemView *sp_item_view_new_prepend(SPItemView *list, SPItem *item, unsigned flags, unsigned key, + Inkscape::DrawingItem *arenaitem); static void clip_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item); static void mask_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item); static void fill_ps_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item); static void stroke_ps_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item); public: - void rotate_rel(Geom::Rotate const &rotation); - void scale_rel(Geom::Scale const &scale); - void skew_rel(double skewX, double skewY); - void move_rel( Geom::Translate const &tr); - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; - void set(SPAttr key, char const* value) override; - void update(SPCtx *ctx, unsigned int flags) override; - void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - - virtual Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const; - virtual void print(SPPrintContext *ctx); - virtual const char* displayName() const; - virtual char* description() const; - virtual Inkscape::DrawingItem* show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags); - virtual void hide(unsigned int key); - virtual void snappoints(std::vector &p, Inkscape::SnapPreferences const *snapprefs) const; + void rotate_rel(Geom::Rotate const &rotation); + void scale_rel(Geom::Scale const &scale); + void skew_rel(double skewX, double skewY); + void move_rel(Geom::Translate const &tr); + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, char const *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + + virtual Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const; + virtual void print(SPPrintContext *ctx); + virtual const char *displayName() const; + virtual char *description() const; + virtual Inkscape::DrawingItem *show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags); + virtual void hide(unsigned int key); + virtual void snappoints(std::vector &p, + Inkscape::SnapPreferences const *snapprefs) const; virtual Geom::Affine set_transform(Geom::Affine const &transform); virtual void convert_to_guides() const; @@ -439,7 +460,6 @@ public: virtual int event(SPEvent *event); }; - // Utility /** @@ -450,7 +470,7 @@ Geom::Affine i2anc_affine(SPObject const *item, SPObject const *ancestor); Geom::Affine i2i_affine(SPObject const *src, SPObject const *dest); -Geom::Affine sp_item_transform_repr (SPItem *item); +Geom::Affine sp_item_transform_repr(SPItem *item); /* fixme: - these are evil, but OK */ @@ -458,13 +478,11 @@ int sp_item_repr_compare_position(SPItem const *first, SPItem const *second); inline bool sp_item_repr_compare_position_bool(SPObject const *first, SPObject const *second) { - return sp_repr_compare_position(((SPItem*)first)->getRepr(), - ((SPItem*)second)->getRepr())<0; + return sp_repr_compare_position(((SPItem *)first)->getRepr(), ((SPItem *)second)->getRepr()) < 0; } - -SPItem *sp_item_first_item_child (SPObject *obj); -SPItem const *sp_item_first_item_child (SPObject const *obj); +SPItem *sp_item_first_item_child(SPObject *obj); +SPItem const *sp_item_first_item_child(SPObject const *obj); #endif // SEEN_SP_ITEM_H diff --git a/src/object/sp-line.cpp b/src/object/sp-line.cpp index d0ae489600586a863a862c59c0510073325dd928..58d010dfa1d28d7925a8df9a9aa6fc95ee84af04 100644 --- a/src/object/sp-line.cpp +++ b/src/object/sp-line.cpp @@ -12,16 +12,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "attributes.h" -#include "style.h" #include "sp-line.h" -#include "sp-guide.h" -#include "display/curve.h" + #include + +#include "attributes.h" +#include "display/curve.h" #include "document.h" #include "inkscape.h" +#include "sp-guide.h" +#include "style.h" -SPLine::SPLine() : SPShape() { +SPLine::SPLine() + : SPShape() +{ this->x1.unset(); this->y1.unset(); this->x2.unset(); @@ -30,7 +34,8 @@ SPLine::SPLine() : SPShape() { SPLine::~SPLine() = default; -void SPLine::build(SPDocument * document, Inkscape::XML::Node * repr) { +void SPLine::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPShape::build(document, repr); this->readAttr(SPAttr::X1); @@ -39,7 +44,8 @@ void SPLine::build(SPDocument * document, Inkscape::XML::Node * repr) { this->readAttr(SPAttr::Y2); } -void SPLine::set(SPAttr key, const gchar* value) { +void SPLine::set(SPAttr key, const gchar *value) +{ /* fixme: we should really collect updates */ switch (key) { @@ -69,14 +75,15 @@ void SPLine::set(SPAttr key, const gchar* value) { } } -void SPLine::update(SPCtx *ctx, guint flags) { +void SPLine::update(SPCtx *ctx, guint flags) +{ if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { SPStyle const *style = this->style; - SPItemCtx const *ictx = (SPItemCtx const *) ctx; + SPItemCtx const *ictx = (SPItemCtx const *)ctx; double const w = ictx->viewport.width(); double const h = ictx->viewport.height(); double const em = style->font_size.computed; - double const ex = em * 0.5; // fixme: get from pango or libnrtype. + double const ex = em * 0.5; // fixme: get from pango or libnrtype. this->x1.update(em, ex, w); this->x2.update(em, ex, w); @@ -89,7 +96,8 @@ void SPLine::update(SPCtx *ctx, guint flags) { SPShape::update(ctx, flags); } -Inkscape::XML::Node* SPLine::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPLine::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:line"); } @@ -108,22 +116,24 @@ Inkscape::XML::Node* SPLine::write(Inkscape::XML::Document *xml_doc, Inkscape::X return repr; } -const char* SPLine::displayName() const { - return _("Line"); +const char *SPLine::displayName() const +{ + return _("Line"); } -void SPLine::convert_to_guides() const { +void SPLine::convert_to_guides() const +{ Geom::Point points[2]; Geom::Affine const i2dt(this->i2dt_affine()); - points[0] = Geom::Point(this->x1.computed, this->y1.computed)*i2dt; - points[1] = Geom::Point(this->x2.computed, this->y2.computed)*i2dt; + points[0] = Geom::Point(this->x1.computed, this->y1.computed) * i2dt; + points[1] = Geom::Point(this->x2.computed, this->y2.computed) * i2dt; SPGuide::createSPGuide(this->document, points[0], points[1]); } - -Geom::Affine SPLine::set_transform(Geom::Affine const &transform) { +Geom::Affine SPLine::set_transform(Geom::Affine const &transform) +{ Geom::Point points[2]; points[0] = Geom::Point(this->x1.computed, this->y1.computed); @@ -144,7 +154,8 @@ Geom::Affine SPLine::set_transform(Geom::Affine const &transform) { return Geom::identity(); } -void SPLine::set_shape() { +void SPLine::set_shape() +{ auto c = std::make_unique(); c->moveto(this->x1.computed, this->y1.computed); diff --git a/src/object/sp-line.h b/src/object/sp-line.h index 30e103ce84ba3d6f6fef2be732caa5b1c9c8b815..7a14cff115ed699708a02f7ca503c458dc6fccbd 100644 --- a/src/object/sp-line.h +++ b/src/object/sp-line.h @@ -1,5 +1,5 @@ // SPDX-License-Identifier: GPL-2.0-or-later -#ifndef SEEN_SP_LINE_H +#ifndef SEEN_SP_LINE_H #define SEEN_SP_LINE_H /* @@ -15,32 +15,34 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "svg/svg-length.h" #include "sp-shape.h" +#include "svg/svg-length.h" -#define SP_LINE(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_LINE(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_LINE(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_LINE(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPLine : public SPShape { +class SPLine : public SPShape +{ public: - SPLine(); - ~SPLine() override; + SPLine(); + ~SPLine() override; SVGLength x1; SVGLength y1; SVGLength x2; SVGLength y2; - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - void set(SPAttr key, char const* value) override; + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + void set(SPAttr key, char const *value) override; - const char* displayName() const override; - Geom::Affine set_transform(Geom::Affine const &transform) override; - void convert_to_guides() const override; - void update(SPCtx* ctx, unsigned int flags) override; + const char *displayName() const override; + Geom::Affine set_transform(Geom::Affine const &transform) override; + void convert_to_guides() const override; + void update(SPCtx *ctx, unsigned int flags) override; - void set_shape() override; + void set_shape() override; }; #endif // SEEN_SP_LINE_H diff --git a/src/object/sp-linear-gradient.cpp b/src/object/sp-linear-gradient.cpp index e86db446c32409c3408d809b36e23e2558a2e05d..9a3d1828180c8ad7f0f4b6ec1edb67492729b246 100644 --- a/src/object/sp-linear-gradient.cpp +++ b/src/object/sp-linear-gradient.cpp @@ -7,10 +7,10 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include - #include "sp-linear-gradient.h" +#include + #include "attributes.h" #include "style.h" #include "xml/repr.h" @@ -18,7 +18,9 @@ /* * Linear Gradient */ -SPLinearGradient::SPLinearGradient() : SPGradient() { +SPLinearGradient::SPLinearGradient() + : SPGradient() +{ this->x1.unset(SVGLength::PERCENT, 0.0, 0.0); this->y1.unset(SVGLength::PERCENT, 0.0, 0.0); this->x2.unset(SVGLength::PERCENT, 1.0, 1.0); @@ -27,7 +29,8 @@ SPLinearGradient::SPLinearGradient() : SPGradient() { SPLinearGradient::~SPLinearGradient() = default; -void SPLinearGradient::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPLinearGradient::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPGradient::build(document, repr); this->readAttr(SPAttr::X1); @@ -39,7 +42,8 @@ void SPLinearGradient::build(SPDocument *document, Inkscape::XML::Node *repr) { /** * Callback: set attribute. */ -void SPLinearGradient::set(SPAttr key, const gchar* value) { +void SPLinearGradient::set(SPAttr key, const gchar *value) +{ switch (key) { case SPAttr::X1: this->x1.readOrUnset(value, SVGLength::PERCENT, 0.0, 0.0); @@ -67,19 +71,17 @@ void SPLinearGradient::set(SPAttr key, const gchar* value) { } } -void -SPLinearGradient::update(SPCtx *ctx, guint flags) +void SPLinearGradient::update(SPCtx *ctx, guint flags) { // To do: Verify flags. if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - SPItemCtx const *ictx = reinterpret_cast(ctx); if (getUnits() == SP_GRADIENT_UNITS_USERSPACEONUSE) { double w = ictx->viewport.width(); double h = ictx->viewport.height(); double const em = style->font_size.computed; - double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. + double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. this->x1.update(em, ex, w); this->y1.update(em, ex, h); @@ -92,7 +94,8 @@ SPLinearGradient::update(SPCtx *ctx, guint flags) /** * Callback: write attributes to associated repr. */ -Inkscape::XML::Node* SPLinearGradient::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPLinearGradient::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:linearGradient"); } @@ -118,12 +121,12 @@ Inkscape::XML::Node* SPLinearGradient::write(Inkscape::XML::Document *xml_doc, I return repr; } -cairo_pattern_t* SPLinearGradient::pattern_new(cairo_t * /*ct*/, Geom::OptRect const &bbox, double opacity) { +cairo_pattern_t *SPLinearGradient::pattern_new(cairo_t * /*ct*/, Geom::OptRect const &bbox, double opacity) +{ this->ensureVector(); - cairo_pattern_t *cp = cairo_pattern_create_linear( - this->x1.computed, this->y1.computed, - this->x2.computed, this->y2.computed); + cairo_pattern_t *cp = + cairo_pattern_create_linear(this->x1.computed, this->y1.computed, this->x2.computed, this->y2.computed); sp_gradient_pattern_common_setup(cp, this, bbox, opacity); diff --git a/src/object/sp-linear-gradient.h b/src/object/sp-linear-gradient.h index abe8455513a936ccfe6700ce1ec40d6a6e906abc..4ae50ac44981313a312b71db9dee48e0631fb7e8 100644 --- a/src/object/sp-linear-gradient.h +++ b/src/object/sp-linear-gradient.h @@ -17,11 +17,12 @@ #include "sp-gradient.h" #include "svg/svg-length.h" -#define SP_LINEARGRADIENT(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_LINEARGRADIENT(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_LINEARGRADIENT(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_LINEARGRADIENT(obj) (dynamic_cast((SPObject *)obj) != NULL) /** Linear gradient. */ -class SPLinearGradient : public SPGradient { +class SPLinearGradient : public SPGradient +{ public: SPLinearGradient(); ~SPLinearGradient() override; @@ -31,13 +32,14 @@ public: SVGLength x2; SVGLength y2; - cairo_pattern_t* pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) override; + cairo_pattern_t *pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) override; protected: void build(SPDocument *document, Inkscape::XML::Node *repr) override; void set(SPAttr key, char const *value) override; void update(SPCtx *ctx, guint flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; #endif /* !SP_LINEAR_GRADIENT_H */ diff --git a/src/object/sp-lpe-item.cpp b/src/object/sp-lpe-item.cpp old mode 100755 new mode 100644 index bde56a06b3ff8124a825862e0a8b614ffd2f37f1..9f677ca5ac63dd74b59a292930dcfb2df1f397db --- a/src/object/sp-lpe-item.cpp +++ b/src/object/sp-lpe-item.cpp @@ -18,9 +18,8 @@ #include -#include "bad-uri-exception.h" - #include "attributes.h" +#include "bad-uri-exception.h" #include "desktop.h" #include "display/curve.h" #include "inkscape.h" @@ -48,22 +47,24 @@ static void lpeobject_ref_modified(SPObject *href, guint flags, SPLPEItem *lpeitem); static void sp_lpe_item_create_original_path_recursive(SPLPEItem *lpeitem); -static void sp_lpe_item_cleanup_original_path_recursive(SPLPEItem *lpeitem, bool keep_paths, bool force = false, bool is_clip_mask = false); +static void sp_lpe_item_cleanup_original_path_recursive(SPLPEItem *lpeitem, bool keep_paths, bool force = false, + bool is_clip_mask = false); typedef std::list HRefList; -static std::string patheffectlist_svg_string(PathEffectList const & list); -static std::string hreflist_svg_string(HRefList const & list); +static std::string patheffectlist_svg_string(PathEffectList const &list); +static std::string hreflist_svg_string(HRefList const &list); namespace { - void clear_path_effect_list(PathEffectList* const l) { - PathEffectList::iterator it = l->begin(); - while ( it != l->end()) { - (*it)->unlink(); - delete *it; - it = l->erase(it); - } +void clear_path_effect_list(PathEffectList *const l) +{ + PathEffectList::iterator it = l->begin(); + while (it != l->end()) { + (*it)->unlink(); + delete *it; + it = l->erase(it); } } +} // namespace SPLPEItem::SPLPEItem() : SPItem() @@ -72,22 +73,22 @@ SPLPEItem::SPLPEItem() , lpe_modified_connection_list(new std::list()) , current_path_effect(nullptr) , lpe_helperpaths() -{ -} +{} SPLPEItem::~SPLPEItem() = default; -void SPLPEItem::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPLPEItem::build(SPDocument *document, Inkscape::XML::Node *repr) +{ this->readAttr(SPAttr::INKSCAPE_PATH_EFFECT); SPItem::build(document, repr); } -void SPLPEItem::release() { +void SPLPEItem::release() +{ // disconnect all modified listeners: - for (auto & mod_it : *this->lpe_modified_connection_list) - { + for (auto &mod_it : *this->lpe_modified_connection_list) { mod_it.disconnect(); } @@ -102,59 +103,57 @@ void SPLPEItem::release() { SPItem::release(); } -void SPLPEItem::set(SPAttr key, gchar const* value) { +void SPLPEItem::set(SPAttr key, gchar const *value) +{ switch (key) { - case SPAttr::INKSCAPE_PATH_EFFECT: - { - this->current_path_effect = nullptr; + case SPAttr::INKSCAPE_PATH_EFFECT: { + this->current_path_effect = nullptr; - // Disable the path effects while populating the LPE list - sp_lpe_item_enable_path_effects(this, false); + // Disable the path effects while populating the LPE list + sp_lpe_item_enable_path_effects(this, false); - // disconnect all modified listeners: - for (auto & mod_it : *this->lpe_modified_connection_list) - { - mod_it.disconnect(); - } + // disconnect all modified listeners: + for (auto &mod_it : *this->lpe_modified_connection_list) { + mod_it.disconnect(); + } - this->lpe_modified_connection_list->clear(); - clear_path_effect_list(this->path_effect_list); - - // Parse the contents of "value" to rebuild the path effect reference list - if ( value ) { - std::istringstream iss(value); - std::string href; - - while (std::getline(iss, href, ';')) - { - Inkscape::LivePathEffect::LPEObjectReference *path_effect_ref = new Inkscape::LivePathEffect::LPEObjectReference(this); - - try { - path_effect_ref->link(href.c_str()); - } catch (Inkscape::BadURIException &e) { - g_warning("BadURIException when trying to find LPE: %s", e.what()); - path_effect_ref->unlink(); - delete path_effect_ref; - path_effect_ref = nullptr; - } + this->lpe_modified_connection_list->clear(); + clear_path_effect_list(this->path_effect_list); + + // Parse the contents of "value" to rebuild the path effect reference list + if (value) { + std::istringstream iss(value); + std::string href; + + while (std::getline(iss, href, ';')) { + Inkscape::LivePathEffect::LPEObjectReference *path_effect_ref = + new Inkscape::LivePathEffect::LPEObjectReference(this); + + try { + path_effect_ref->link(href.c_str()); + } catch (Inkscape::BadURIException &e) { + g_warning("BadURIException when trying to find LPE: %s", e.what()); + path_effect_ref->unlink(); + delete path_effect_ref; + path_effect_ref = nullptr; + } - this->path_effect_list->push_back(path_effect_ref); + this->path_effect_list->push_back(path_effect_ref); - if ( path_effect_ref->lpeobject && path_effect_ref->lpeobject->get_lpe() ) { - // connect modified-listener - this->lpe_modified_connection_list->push_back( - path_effect_ref->lpeobject->connectModified(sigc::bind(sigc::ptr_fun(&lpeobject_ref_modified), this)) ); - } else { - // something has gone wrong in finding the right patheffect. - g_warning("Unknown LPE type specified, LPE stack effectively disabled"); - // keep the effect in the lpestack, so the whole stack is effectively disabled but maintained - } + if (path_effect_ref->lpeobject && path_effect_ref->lpeobject->get_lpe()) { + // connect modified-listener + this->lpe_modified_connection_list->push_back(path_effect_ref->lpeobject->connectModified( + sigc::bind(sigc::ptr_fun(&lpeobject_ref_modified), this))); + } else { + // something has gone wrong in finding the right patheffect. + g_warning("Unknown LPE type specified, LPE stack effectively disabled"); + // keep the effect in the lpestack, so the whole stack is effectively disabled but maintained } } - - sp_lpe_item_enable_path_effects(this, true); } - break; + + sp_lpe_item_enable_path_effects(this, true); + } break; default: SPItem::set(key, value); @@ -162,24 +161,28 @@ void SPLPEItem::set(SPAttr key, gchar const* value) { } } -void SPLPEItem::update(SPCtx* ctx, unsigned int flags) { +void SPLPEItem::update(SPCtx *ctx, unsigned int flags) +{ SPItem::update(ctx, flags); // update the helperpaths of all LPEs applied to the item // TODO: re-add for the new node tool } -void SPLPEItem::modified(unsigned int flags) { - //stop update when modified and make the effect update on the LPE transform method if the effect require it - //if (SP_IS_GROUP(this) && (flags & SP_OBJECT_MODIFIED_FLAG) && (flags & SP_OBJECT_USER_MODIFIED_FLAG_B)) { +void SPLPEItem::modified(unsigned int flags) +{ + // stop update when modified and make the effect update on the LPE transform method if the effect require it + // if (SP_IS_GROUP(this) && (flags & SP_OBJECT_MODIFIED_FLAG) && (flags & SP_OBJECT_USER_MODIFIED_FLAG_B)) { // sp_lpe_item_update_patheffect(this, true, false); //} } -Inkscape::XML::Node* SPLPEItem::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPLPEItem::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if (flags & SP_OBJECT_WRITE_EXT) { - if ( hasPathEffect() ) { - repr->setAttributeOrRemoveIfEmpty("inkscape:path-effect", patheffectlist_svg_string(*this->path_effect_list)); + if (hasPathEffect()) { + repr->setAttributeOrRemoveIfEmpty("inkscape:path-effect", + patheffectlist_svg_string(*this->path_effect_list)); } else { repr->removeAttribute("inkscape:path-effect"); } @@ -193,8 +196,8 @@ Inkscape::XML::Node* SPLPEItem::write(Inkscape::XML::Document *xml_doc, Inkscape /** * returns true when LPE was successful. */ -bool SPLPEItem::performPathEffect(SPCurve *curve, SPShape *current, bool is_clip_or_mask) { - +bool SPLPEItem::performPathEffect(SPCurve *curve, SPShape *current, bool is_clip_or_mask) +{ if (!curve) { return false; } @@ -206,8 +209,9 @@ bool SPLPEItem::performPathEffect(SPCurve *curve, SPShape *current, bool is_clip LivePathEffectObject *lpeobj = lperef->lpeobject; if (!lpeobj) { /** \todo Investigate the cause of this. - * For example, this happens when copy pasting an object with LPE applied. Probably because the object is pasted while the effect is not yet pasted to defs, and cannot be found. - */ + * For example, this happens when copy pasting an object with LPE applied. Probably because the object + * is pasted while the effect is not yet pasted to defs, and cannot be found. + */ g_warning("SPLPEItem::performPathEffect - NULL lpeobj in list!"); return false; } @@ -227,7 +231,9 @@ bool SPLPEItem::performPathEffect(SPCurve *curve, SPShape *current, bool is_clip /** * returns true when LPE was successful. */ -bool SPLPEItem::performOnePathEffect(SPCurve *curve, SPShape *current, Inkscape::LivePathEffect::Effect *lpe, bool is_clip_or_mask) { +bool SPLPEItem::performOnePathEffect(SPCurve *curve, SPShape *current, Inkscape::LivePathEffect::Effect *lpe, + bool is_clip_or_mask) +{ if (!lpe) { /** \todo Investigate the cause of this. * Not sure, but I think this can happen when an unknown effect type is specified... @@ -241,7 +247,7 @@ bool SPLPEItem::performOnePathEffect(SPCurve *curve, SPShape *current, Inkscape: // yet, we don't alter the path return false; } - //if is not clip or mask or LPE apply to clip and mask + // if is not clip or mask or LPE apply to clip and mask if (!is_clip_or_mask || lpe->apply_to_clippath_and_mask) { lpe->setCurrentShape(current); if (!SP_IS_GROUP(this)) { @@ -263,17 +269,16 @@ bool SPLPEItem::performOnePathEffect(SPCurve *curve, SPShape *current, Inkscape: lpe->has_exception = false; } - catch (std::exception & e) { + catch (std::exception &e) { g_warning("Exception during LPE %s execution. \n %s", lpe->getName().c_str(), e.what()); if (SP_ACTIVE_DESKTOP && SP_ACTIVE_DESKTOP->messageStack()) { - SP_ACTIVE_DESKTOP->messageStack()->flash( Inkscape::WARNING_MESSAGE, - _("An exception occurred during execution of the Path Effect.") ); + SP_ACTIVE_DESKTOP->messageStack()->flash( + Inkscape::WARNING_MESSAGE, _("An exception occurred during execution of the Path Effect.")); } lpe->doOnException(this); return false; } - if (!SP_IS_GROUP(this)) { // To have processed the shape to doAfterEffect current->setCurveInsync(curve); @@ -343,22 +348,22 @@ void SPLPEItem::notifyTransform(Geom::Affine const &postmul) } // CPPIFY: make pure virtual -void SPLPEItem::update_patheffect(bool /*write*/) { - //throw; +void SPLPEItem::update_patheffect(bool /*write*/) +{ + // throw; } /** * Calls any registered handlers for the update_patheffect action */ -void -sp_lpe_item_update_patheffect (SPLPEItem *lpeitem, bool wholetree, bool write) +void sp_lpe_item_update_patheffect(SPLPEItem *lpeitem, bool wholetree, bool write) { #ifdef SHAPE_VERBOSE g_message("sp_lpe_item_update_patheffect: %p\n", lpeitem); #endif - g_return_if_fail (lpeitem != nullptr); - g_return_if_fail (SP_IS_OBJECT (lpeitem)); - g_return_if_fail (SP_IS_LPE_ITEM (lpeitem)); + g_return_if_fail(lpeitem != nullptr); + g_return_if_fail(SP_IS_OBJECT(lpeitem)); + g_return_if_fail(SP_IS_LPE_ITEM(lpeitem)); if (!lpeitem->pathEffectsEnabled()) return; @@ -367,124 +372,121 @@ sp_lpe_item_update_patheffect (SPLPEItem *lpeitem, bool wholetree, bool write) if (wholetree) { SPLPEItem *prev_parent = lpeitem; - SPLPEItem *parent = dynamic_cast(prev_parent->parent); + SPLPEItem *parent = dynamic_cast(prev_parent->parent); while (parent && parent->hasPathEffectRecursive()) { prev_parent = parent; - parent = dynamic_cast(prev_parent->parent); + parent = dynamic_cast(prev_parent->parent); } top = prev_parent; - } - else { + } else { top = lpeitem; } top->update_patheffect(write); } /** - * Gets called when any of the lpestack's lpeobject repr contents change: i.e. parameter change in any of the stacked LPEs + * Gets called when any of the lpestack's lpeobject repr contents change: i.e. parameter change in any of the stacked + * LPEs */ -static void -lpeobject_ref_modified(SPObject */*href*/, guint /*flags*/, SPLPEItem *lpeitem) +static void lpeobject_ref_modified(SPObject * /*href*/, guint /*flags*/, SPLPEItem *lpeitem) { #ifdef SHAPE_VERBOSE g_message("lpeobject_ref_modified"); #endif - sp_lpe_item_update_patheffect (lpeitem, true, true); + sp_lpe_item_update_patheffect(lpeitem, true, true); } -static void -sp_lpe_item_create_original_path_recursive(SPLPEItem *lpeitem) +static void sp_lpe_item_create_original_path_recursive(SPLPEItem *lpeitem) { g_return_if_fail(lpeitem != nullptr); SPClipPath *clip_path = SP_ITEM(lpeitem)->getClipObject(); - if(clip_path) { - std::vector clip_path_list = clip_path->childList(true); + if (clip_path) { + std::vector clip_path_list = clip_path->childList(true); for (auto iter : clip_path_list) { - SPLPEItem * clip_data = dynamic_cast(iter); + SPLPEItem *clip_data = dynamic_cast(iter); sp_lpe_item_create_original_path_recursive(clip_data); } } SPMask *mask_path = SP_ITEM(lpeitem)->getMaskObject(); - if(mask_path) { - std::vector mask_path_list = mask_path->childList(true); + if (mask_path) { + std::vector mask_path_list = mask_path->childList(true); for (auto iter : mask_path_list) { - SPLPEItem * mask_data = dynamic_cast(iter); + SPLPEItem *mask_data = dynamic_cast(iter); sp_lpe_item_create_original_path_recursive(mask_data); } } if (SP_IS_GROUP(lpeitem)) { - std::vector item_list = sp_item_group_item_list(SP_GROUP(lpeitem)); + std::vector item_list = sp_item_group_item_list(SP_GROUP(lpeitem)); for (auto subitem : item_list) { if (SP_IS_LPE_ITEM(subitem)) { sp_lpe_item_create_original_path_recursive(SP_LPE_ITEM(subitem)); } } - } else if (SPPath * path = dynamic_cast(lpeitem)) { + } else if (SPPath *path = dynamic_cast(lpeitem)) { Inkscape::XML::Node *pathrepr = path->getRepr(); - if ( !pathrepr->attribute("inkscape:original-d") ) { - if (gchar const * value = pathrepr->attribute("d")) { + if (!pathrepr->attribute("inkscape:original-d")) { + if (gchar const *value = pathrepr->attribute("d")) { Geom::PathVector pv = sp_svg_read_pathv(value); pathrepr->setAttribute("inkscape:original-d", value); path->setCurveBeforeLPE(std::make_unique(pv)); } } - } else if (SPShape * shape = dynamic_cast(lpeitem)) { + } else if (SPShape *shape = dynamic_cast(lpeitem)) { if (!shape->curveBeforeLPE()) { shape->setCurveBeforeLPE(shape->curve()); } } } -static void -sp_lpe_item_cleanup_original_path_recursive(SPLPEItem *lpeitem, bool keep_paths, bool force, bool is_clip_mask) +static void sp_lpe_item_cleanup_original_path_recursive(SPLPEItem *lpeitem, bool keep_paths, bool force, + bool is_clip_mask) { g_return_if_fail(lpeitem != nullptr); - SPItem *item = dynamic_cast(lpeitem); + SPItem *item = dynamic_cast(lpeitem); if (!item) { return; } - SPGroup *group = dynamic_cast(lpeitem); - SPShape *shape = dynamic_cast(lpeitem); - SPPath *path = dynamic_cast(lpeitem); + SPGroup *group = dynamic_cast(lpeitem); + SPShape *shape = dynamic_cast(lpeitem); + SPPath *path = dynamic_cast(lpeitem); SPClipPath *clip_path = item->getClipObject(); - if(clip_path) { - std::vector clip_path_list = clip_path->childList(true); + if (clip_path) { + std::vector clip_path_list = clip_path->childList(true); for (auto iter : clip_path_list) { - SPLPEItem* clip_data = dynamic_cast(iter); + SPLPEItem *clip_data = dynamic_cast(iter); if (clip_data) { - sp_lpe_item_cleanup_original_path_recursive(clip_data, keep_paths, lpeitem && !lpeitem->hasPathEffectRecursive(), true); + sp_lpe_item_cleanup_original_path_recursive(clip_data, keep_paths, + lpeitem && !lpeitem->hasPathEffectRecursive(), true); } } } SPMask *mask_path = item->getMaskObject(); - if(mask_path) { - std::vector mask_path_list = mask_path->childList(true); + if (mask_path) { + std::vector mask_path_list = mask_path->childList(true); for (auto iter : mask_path_list) { - SPLPEItem* mask_data = dynamic_cast(iter); + SPLPEItem *mask_data = dynamic_cast(iter); if (mask_data) { - sp_lpe_item_cleanup_original_path_recursive(mask_data, keep_paths, lpeitem && !lpeitem->hasPathEffectRecursive(), true); + sp_lpe_item_cleanup_original_path_recursive(mask_data, keep_paths, + lpeitem && !lpeitem->hasPathEffectRecursive(), true); } } } if (group) { - std::vector item_list = sp_item_group_item_list(SP_GROUP(lpeitem)); + std::vector item_list = sp_item_group_item_list(SP_GROUP(lpeitem)); for (auto iter : item_list) { - SPLPEItem* subitem = dynamic_cast(iter); + SPLPEItem *subitem = dynamic_cast(iter); if (subitem) { sp_lpe_item_cleanup_original_path_recursive(subitem, keep_paths); } } } else if (path) { Inkscape::XML::Node *repr = lpeitem->getRepr(); - if (repr->attribute("inkscape:original-d") && - !lpeitem->hasPathEffectRecursive() && - (!is_clip_mask || - ( is_clip_mask && force))) - { + if (repr->attribute("inkscape:original-d") && !lpeitem->hasPathEffectRecursive() && + (!is_clip_mask || (is_clip_mask && force))) { if (!keep_paths) { repr->setAttribute("d", repr->attribute("inkscape:original-d")); } @@ -504,16 +506,13 @@ sp_lpe_item_cleanup_original_path_recursive(SPLPEItem *lpeitem, bool keep_paths, if (c_lpe) { gchar *d_str = sp_svg_write_path(c_lpe->get_pathvector()); if (d_str) { - if (!lpeitem->hasPathEffectRecursive() && - (!is_clip_mask || - ( is_clip_mask && force))) - { + if (!lpeitem->hasPathEffectRecursive() && (!is_clip_mask || (is_clip_mask && force))) { if (!keep_paths) { repr->removeAttribute("d"); shape->setCurveBeforeLPE(nullptr); } else { - const char * id = repr->attribute("id"); - const char * style = repr->attribute("style"); + const char *id = repr->attribute("id"); + const char *style = repr->attribute("style"); // remember the position of the item gint pos = shape->getRepr()->position(); // remember parent @@ -527,9 +526,9 @@ sp_lpe_item_cleanup_original_path_recursive(SPLPEItem *lpeitem, bool keep_paths, // remember transformation gchar const *transform_str = shape->getRepr()->attribute("transform"); // Mask - gchar const *mask_str = (gchar *) shape->getRepr()->attribute("mask"); + gchar const *mask_str = (gchar *)shape->getRepr()->attribute("mask"); // Clip path - gchar const *clip_str = (gchar *) shape->getRepr()->attribute("clip-path"); + gchar const *clip_str = (gchar *)shape->getRepr()->attribute("clip-path"); /* Rotation center */ gchar const *transform_center_x = shape->getRepr()->attribute("inkscape:transform-center-x"); @@ -541,7 +540,7 @@ sp_lpe_item_cleanup_original_path_recursive(SPLPEItem *lpeitem, bool keep_paths, highlight_color = shape->highlight_color(); // It's going to resurrect, so we delete without notifying listeners. - SPDocument * doc = shape->document; + SPDocument *doc = shape->document; shape->deleteObject(false); Inkscape::XML::Document *xml_doc = doc->getReprDoc(); Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); @@ -559,13 +558,13 @@ sp_lpe_item_cleanup_original_path_recursive(SPLPEItem *lpeitem, bool keep_paths, repr->setAttribute("inkscape:transform-center-x", transform_center_x); // restore transform_center_y repr->setAttribute("inkscape:transform-center-y", transform_center_y); - //restore d + // restore d repr->setAttribute("d", d_str); - //restore style + // restore style repr->setAttribute("style", style); // add the new repr to the parent parent->appendChild(repr); - SPObject* newObj = doc->getObjectByRepr(repr); + SPObject *newObj = doc->getObjectByRepr(repr); if (title && newObj) { newObj->setTitle(title); g_free(title); @@ -575,7 +574,7 @@ sp_lpe_item_cleanup_original_path_recursive(SPLPEItem *lpeitem, bool keep_paths, g_free(desc); } if (highlight_color && newObj) { - SP_ITEM(newObj)->setHighlightColor( highlight_color ); + SP_ITEM(newObj)->setHighlightColor(highlight_color); } // move to the saved position repr->setPosition(pos > 0 ? pos : 0); @@ -604,19 +603,19 @@ void SPLPEItem::addPathEffect(std::string value, bool reset) // Add the new reference to the list of LPE references HRefList hreflist; - for (PathEffectList::const_iterator it = this->path_effect_list->begin(); it != this->path_effect_list->end(); ++it) - { - hreflist.push_back( std::string((*it)->lpeobject_href) ); + for (PathEffectList::const_iterator it = this->path_effect_list->begin(); it != this->path_effect_list->end(); + ++it) { + hreflist.push_back(std::string((*it)->lpeobject_href)); } - hreflist.push_back(value); // C++11: should be emplace_back std::move'd (also the reason why passed by value to addPathEffect) + hreflist.push_back(value); // C++11: should be emplace_back std::move'd (also the reason why passed by value to + // addPathEffect) this->setAttributeOrRemoveIfEmpty("inkscape:path-effect", hreflist_svg_string(hreflist)); // Make sure that ellipse is stored as - if( SP_IS_GENERICELLIPSE(this)) { - SP_GENERICELLIPSE(this)->write( this->getRepr()->document(), this->getRepr(), SP_OBJECT_WRITE_EXT ); + if (SP_IS_GENERICELLIPSE(this)) { + SP_GENERICELLIPSE(this)->write(this->getRepr()->document(), this->getRepr(), SP_OBJECT_WRITE_EXT); } - LivePathEffectObject *lpeobj = this->path_effect_list->back()->lpeobject; if (lpeobj && lpeobj->get_lpe()) { Inkscape::LivePathEffect::Effect *lpe = lpeobj->get_lpe(); @@ -633,7 +632,7 @@ void SPLPEItem::addPathEffect(std::string value, bool reset) lpe->doOnApply_impl(this); } - //Enable the path effects now that everything is ready to apply the new path effect + // Enable the path effects now that everything is ready to apply the new path effect sp_lpe_item_enable_path_effects(this, true); // Apply the path effect @@ -641,9 +640,9 @@ void SPLPEItem::addPathEffect(std::string value, bool reset) } } -void SPLPEItem::addPathEffect(LivePathEffectObject * new_lpeobj) +void SPLPEItem::addPathEffect(LivePathEffectObject *new_lpeobj) { - const gchar * repr_id = new_lpeobj->getRepr()->attribute("id"); + const gchar *repr_id = new_lpeobj->getRepr()->attribute("id"); gchar *hrefstr = g_strdup_printf("#%s", repr_id); this->addPathEffect(hrefstr, false); g_free(hrefstr); @@ -654,19 +653,19 @@ void SPLPEItem::addPathEffect(LivePathEffectObject * new_lpeobj) */ void SPLPEItem::removeCurrentPathEffect(bool keep_paths) { - Inkscape::LivePathEffect::LPEObjectReference* lperef = this->getCurrentLPEReference(); + Inkscape::LivePathEffect::LPEObjectReference *lperef = this->getCurrentLPEReference(); if (!lperef) { return; } - if (Inkscape::LivePathEffect::Effect* effect_ = this->getCurrentLPE()) { + if (Inkscape::LivePathEffect::Effect *effect_ = this->getCurrentLPE()) { effect_->keep_paths = keep_paths; effect_->doOnRemove(this); - this->path_effect_list->remove(lperef); //current lpe ref is always our 'own' pointer from the path_effect_list + this->path_effect_list->remove(lperef); // current lpe ref is always our 'own' pointer from the path_effect_list this->setAttributeOrRemoveIfEmpty("inkscape:path-effect", patheffectlist_svg_string(*this->path_effect_list)); if (!keep_paths) { // Make sure that ellipse is stored as or if possible. - if( SP_IS_GENERICELLIPSE(this)) { - SP_GENERICELLIPSE(this)->write( this->getRepr()->document(), this->getRepr(), SP_OBJECT_WRITE_EXT ); + if (SP_IS_GENERICELLIPSE(this)) { + SP_GENERICELLIPSE(this)->write(this->getRepr()->document(), this->getRepr(), SP_OBJECT_WRITE_EXT); } } sp_lpe_item_cleanup_original_path_recursive(this, keep_paths); @@ -690,7 +689,7 @@ void SPLPEItem::removeAllPathEffects(bool keep_paths) } LivePathEffectObject *lpeobj = lperef->lpeobject; if (lpeobj) { - Inkscape::LivePathEffect::Effect * lpe = lpeobj->get_lpe(); + Inkscape::LivePathEffect::Effect *lpe = lpeobj->get_lpe(); if (lpe) { lpe->keep_paths = keep_paths; lpe->doOnRemove(this); @@ -706,17 +705,16 @@ void SPLPEItem::removeAllPathEffects(bool keep_paths) } } sp_lpe_item_cleanup_original_path_recursive(this, keep_paths); - } void SPLPEItem::downCurrentPathEffect() { - Inkscape::LivePathEffect::LPEObjectReference* lperef = getCurrentLPEReference(); + Inkscape::LivePathEffect::LPEObjectReference *lperef = getCurrentLPEReference(); if (!lperef) return; PathEffectList new_list = *this->path_effect_list; - PathEffectList::iterator cur_it = find( new_list.begin(), new_list.end(), lperef ); + PathEffectList::iterator cur_it = find(new_list.begin(), new_list.end(), lperef); if (cur_it != new_list.end()) { PathEffectList::iterator down_it = cur_it; ++down_it; @@ -732,12 +730,12 @@ void SPLPEItem::downCurrentPathEffect() void SPLPEItem::upCurrentPathEffect() { - Inkscape::LivePathEffect::LPEObjectReference* lperef = getCurrentLPEReference(); + Inkscape::LivePathEffect::LPEObjectReference *lperef = getCurrentLPEReference(); if (!lperef) return; PathEffectList new_list = *this->path_effect_list; - PathEffectList::iterator cur_it = find( new_list.begin(), new_list.end(), lperef ); + PathEffectList::iterator cur_it = find(new_list.begin(), new_list.end(), lperef); if (cur_it != new_list.end() && cur_it != new_list.begin()) { PathEffectList::iterator up_it = cur_it; --up_it; @@ -768,19 +766,16 @@ bool SPLPEItem::hasBrokenPathEffect() const return false; } - - bool SPLPEItem::hasPathEffectOfType(int const type, bool is_ready) const { if (path_effect_list->empty()) { return false; } - for (PathEffectList::const_iterator it = path_effect_list->begin(); it != path_effect_list->end(); ++it) - { + for (PathEffectList::const_iterator it = path_effect_list->begin(); it != path_effect_list->end(); ++it) { LivePathEffectObject const *lpeobj = (*it)->lpeobject; if (lpeobj) { - Inkscape::LivePathEffect::Effect const* lpe = lpeobj->get_lpe(); + Inkscape::LivePathEffect::Effect const *lpe = lpeobj->get_lpe(); if (lpe && (lpe->effectType() == type)) { if (is_ready || lpe->isReady()) { return true; @@ -795,7 +790,7 @@ bool SPLPEItem::hasPathEffectOfType(int const type, bool is_ready) const /** * returns true when any LPE apply to clip or mask. */ -bool SPLPEItem::hasPathEffectOnClipOrMask(SPLPEItem * shape) const +bool SPLPEItem::hasPathEffectOnClipOrMask(SPLPEItem *shape) const { if (shape->hasPathEffectRecursive()) { return true; @@ -821,13 +816,12 @@ bool SPLPEItem::hasPathEffectOnClipOrMask(SPLPEItem * shape) const /** * returns true when any LPE apply to clip or mask. recursive mode */ -bool SPLPEItem::hasPathEffectOnClipOrMaskRecursive(SPLPEItem * shape) const +bool SPLPEItem::hasPathEffectOnClipOrMaskRecursive(SPLPEItem *shape) const { - SPLPEItem * parent_lpe_item = dynamic_cast(parent); + SPLPEItem *parent_lpe_item = dynamic_cast(parent); if (parent_lpe_item) { return hasPathEffectOnClipOrMask(shape) || parent_lpe_item->hasPathEffectOnClipOrMaskRecursive(shape); - } - else { + } else { return hasPathEffectOnClipOrMask(shape); } } @@ -852,25 +846,23 @@ bool SPLPEItem::hasPathEffect() const bool SPLPEItem::hasPathEffectRecursive() const { - SPLPEItem * parent_lpe_item = dynamic_cast(parent); + SPLPEItem *parent_lpe_item = dynamic_cast(parent); if (parent_lpe_item) { return hasPathEffect() || parent_lpe_item->hasPathEffectRecursive(); - } - else { + } else { return hasPathEffect(); } } -void -SPLPEItem::resetClipPathAndMaskLPE(bool fromrecurse) +void SPLPEItem::resetClipPathAndMaskLPE(bool fromrecurse) { if (fromrecurse) { - SPGroup* group = dynamic_cast(this); - SPShape* shape = dynamic_cast(this); + SPGroup *group = dynamic_cast(this); + SPShape *shape = dynamic_cast(this); if (group) { - std::vector item_list = sp_item_group_item_list(group); + std::vector item_list = sp_item_group_item_list(group); for (auto iter2 : item_list) { - SPLPEItem * subitem = dynamic_cast(iter2); + SPLPEItem *subitem = dynamic_cast(iter2); if (subitem) { subitem->resetClipPathAndMaskLPE(true); } @@ -888,15 +880,15 @@ SPLPEItem::resetClipPathAndMaskLPE(bool fromrecurse) return; } SPClipPath *clip_path = this->getClipObject(); - if(clip_path) { - std::vector clip_path_list = clip_path->childList(true); + if (clip_path) { + std::vector clip_path_list = clip_path->childList(true); for (auto iter : clip_path_list) { - SPGroup* group = dynamic_cast(iter); - SPShape* shape = dynamic_cast(iter); + SPGroup *group = dynamic_cast(iter); + SPShape *shape = dynamic_cast(iter); if (group) { - std::vector item_list = sp_item_group_item_list(group); + std::vector item_list = sp_item_group_item_list(group); for (auto iter2 : item_list) { - SPLPEItem * subitem = dynamic_cast(iter2); + SPLPEItem *subitem = dynamic_cast(iter2); if (subitem) { subitem->resetClipPathAndMaskLPE(true); } @@ -914,15 +906,15 @@ SPLPEItem::resetClipPathAndMaskLPE(bool fromrecurse) } } SPMask *mask = this->getMaskObject(); - if(mask) { - std::vector mask_list = mask->childList(true); + if (mask) { + std::vector mask_list = mask->childList(true); for (auto iter : mask_list) { - SPGroup* group = dynamic_cast(iter); - SPShape* shape = dynamic_cast(iter); + SPGroup *group = dynamic_cast(iter); + SPShape *shape = dynamic_cast(iter); if (group) { - std::vector item_list = sp_item_group_item_list(group); + std::vector item_list = sp_item_group_item_list(group); for (auto iter2 : item_list) { - SPLPEItem * subitem = dynamic_cast(iter2); + SPLPEItem *subitem = dynamic_cast(iter2); if (subitem) { subitem->resetClipPathAndMaskLPE(true); } @@ -941,44 +933,41 @@ SPLPEItem::resetClipPathAndMaskLPE(bool fromrecurse) } } -void -SPLPEItem::applyToClipPath(SPItem* to, Inkscape::LivePathEffect::Effect *lpe) +void SPLPEItem::applyToClipPath(SPItem *to, Inkscape::LivePathEffect::Effect *lpe) { if (lpe && !lpe->apply_to_clippath_and_mask) { return; } SPClipPath *clip_path = to->getClipObject(); - if(clip_path) { - std::vector clip_path_list = clip_path->childList(true); + if (clip_path) { + std::vector clip_path_list = clip_path->childList(true); for (auto clip_data : clip_path_list) { applyToClipPathOrMask(SP_ITEM(clip_data), to, lpe); } } } -void -SPLPEItem::applyToMask(SPItem* to, Inkscape::LivePathEffect::Effect *lpe) +void SPLPEItem::applyToMask(SPItem *to, Inkscape::LivePathEffect::Effect *lpe) { if (lpe && !lpe->apply_to_clippath_and_mask) { return; } SPMask *mask = to->getMaskObject(); - if(mask) { - std::vector mask_list = mask->childList(true); + if (mask) { + std::vector mask_list = mask->childList(true); for (auto mask_data : mask_list) { applyToClipPathOrMask(SP_ITEM(mask_data), to, lpe); } } } -void -SPLPEItem::applyToClipPathOrMask(SPItem *clip_mask, SPItem* to, Inkscape::LivePathEffect::Effect *lpe) +void SPLPEItem::applyToClipPathOrMask(SPItem *clip_mask, SPItem *to, Inkscape::LivePathEffect::Effect *lpe) { - SPGroup* group = dynamic_cast(clip_mask); - SPShape* shape = dynamic_cast(clip_mask); + SPGroup *group = dynamic_cast(clip_mask); + SPShape *shape = dynamic_cast(clip_mask); SPRoot *root = this->document->getRoot(); if (group) { - std::vector item_list = sp_item_group_item_list(group); + std::vector item_list = sp_item_group_item_list(group); for (auto subitem : item_list) { applyToClipPathOrMask(subitem, to, lpe); } @@ -995,11 +984,11 @@ SPLPEItem::applyToClipPathOrMask(SPItem *clip_mask, SPItem* to, Inkscape::LivePa } else { success = this->performPathEffect(c.get(), shape, true); } - } catch (std::exception & e) { + } catch (std::exception &e) { g_warning("Exception during LPE execution. \n %s", e.what()); if (SP_ACTIVE_DESKTOP && SP_ACTIVE_DESKTOP->messageStack()) { - SP_ACTIVE_DESKTOP->messageStack()->flash( Inkscape::WARNING_MESSAGE, - _("An exception occurred during execution of the Path Effect.") ); + SP_ACTIVE_DESKTOP->messageStack()->flash( + Inkscape::WARNING_MESSAGE, _("An exception occurred during execution of the Path Effect.")); } success = false; } @@ -1009,8 +998,8 @@ SPLPEItem::applyToClipPathOrMask(SPItem *clip_mask, SPItem* to, Inkscape::LivePa shape->setAttribute("d", str); g_free(str); } else { - // LPE was unsuccessful or doeffect stack return null.. Read the old 'd'-attribute. - if (gchar const * value = shape->getAttribute("d")) { + // LPE was unsuccessful or doeffect stack return null.. Read the old 'd'-attribute. + if (gchar const *value = shape->getAttribute("d")) { Geom::PathVector pv = sp_svg_read_pathv(value); shape->setCurve(std::make_unique(pv)); } @@ -1021,14 +1010,13 @@ SPLPEItem::applyToClipPathOrMask(SPItem *clip_mask, SPItem* to, Inkscape::LivePa } } -Inkscape::LivePathEffect::Effect* -SPLPEItem::getPathEffectOfType(int type) +Inkscape::LivePathEffect::Effect *SPLPEItem::getPathEffectOfType(int type) { PathEffectList path_effect_list(*this->path_effect_list); for (auto &lperef : path_effect_list) { LivePathEffectObject *lpeobj = lperef->lpeobject; if (lpeobj) { - Inkscape::LivePathEffect::Effect* lpe = lpeobj->get_lpe(); + Inkscape::LivePathEffect::Effect *lpe = lpeobj->get_lpe(); if (lpe && (lpe->effectType() == type)) { return lpe; } @@ -1037,8 +1025,7 @@ SPLPEItem::getPathEffectOfType(int type) return nullptr; } -Inkscape::LivePathEffect::Effect const* -SPLPEItem::getPathEffectOfType(int type) const +Inkscape::LivePathEffect::Effect const *SPLPEItem::getPathEffectOfType(int type) const { std::list::const_iterator i; for (i = path_effect_list->begin(); i != path_effect_list->end(); ++i) { @@ -1061,22 +1048,24 @@ void SPLPEItem::editNextParamOncanvas(SPDesktop *dt) } } -void SPLPEItem::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { +void SPLPEItem::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ SPItem::child_added(child, ref); if (this->hasPathEffectRecursive()) { SPObject *ochild = this->get_child_by_repr(child); - if ( ochild && SP_IS_LPE_ITEM(ochild) ) { + if (ochild && SP_IS_LPE_ITEM(ochild)) { sp_lpe_item_create_original_path_recursive(SP_LPE_ITEM(ochild)); } } } -void SPLPEItem::remove_child(Inkscape::XML::Node * child) { +void SPLPEItem::remove_child(Inkscape::XML::Node *child) +{ if (this->hasPathEffectRecursive()) { SPObject *ochild = this->get_child_by_repr(child); - if ( ochild && SP_IS_LPE_ITEM(ochild) ) { + if (ochild && SP_IS_LPE_ITEM(ochild)) { sp_lpe_item_cleanup_original_path_recursive(SP_LPE_ITEM(ochild), false); } } @@ -1084,13 +1073,12 @@ void SPLPEItem::remove_child(Inkscape::XML::Node * child) { SPItem::remove_child(child); } -static std::string patheffectlist_svg_string(PathEffectList const & list) +static std::string patheffectlist_svg_string(PathEffectList const &list) { HRefList hreflist; - for (auto it : list) - { - hreflist.push_back( std::string(it->lpeobject_href) ); // C++11: use emplace_back + for (auto it : list) { + hreflist.push_back(std::string(it->lpeobject_href)); // C++11: use emplace_back } return hreflist_svg_string(hreflist); @@ -1103,13 +1091,12 @@ static std::string patheffectlist_svg_string(PathEffectList const & list) * - populate the templist with the effects from the old list that you want to have and their order * - call this function with temp list as param */ -static std::string hreflist_svg_string(HRefList const & list) +static std::string hreflist_svg_string(HRefList const &list) { std::string r; bool semicolon_first = false; - for (const auto & it : list) - { + for (const auto &it : list) { if (semicolon_first) { r += ';'; } @@ -1134,7 +1121,7 @@ PathEffectList const SPLPEItem::getEffectList() const return *path_effect_list; } -Inkscape::LivePathEffect::LPEObjectReference* SPLPEItem::getCurrentLPEReference() +Inkscape::LivePathEffect::LPEObjectReference *SPLPEItem::getCurrentLPEReference() { if (!this->current_path_effect && !this->path_effect_list->empty()) { setCurrentPathEffect(this->path_effect_list->back()); @@ -1143,9 +1130,9 @@ Inkscape::LivePathEffect::LPEObjectReference* SPLPEItem::getCurrentLPEReference( return this->current_path_effect; } -Inkscape::LivePathEffect::Effect* SPLPEItem::getCurrentLPE() +Inkscape::LivePathEffect::Effect *SPLPEItem::getCurrentLPE() { - Inkscape::LivePathEffect::LPEObjectReference* lperef = getCurrentLPEReference(); + Inkscape::LivePathEffect::LPEObjectReference *lperef = getCurrentLPEReference(); if (lperef && lperef->lpeobject) return lperef->lpeobject->get_lpe(); @@ -1153,11 +1140,12 @@ Inkscape::LivePathEffect::Effect* SPLPEItem::getCurrentLPE() return nullptr; } -bool SPLPEItem::setCurrentPathEffect(Inkscape::LivePathEffect::LPEObjectReference* lperef) +bool SPLPEItem::setCurrentPathEffect(Inkscape::LivePathEffect::LPEObjectReference *lperef) { - for (auto & it : *path_effect_list) { + for (auto &it : *path_effect_list) { if (it->lpeobject_repr == lperef->lpeobject_repr) { - this->current_path_effect = it; // current_path_effect should always be a pointer from the path_effect_list ! + this->current_path_effect = + it; // current_path_effect should always be a pointer from the path_effect_list ! return true; } } @@ -1169,24 +1157,25 @@ bool SPLPEItem::setCurrentPathEffect(Inkscape::LivePathEffect::LPEObjectReferenc * Writes a new "inkscape:path-effect" string to xml, where the old_lpeobjects are substituted by the new ones. * Note that this method messes up the item's \c PathEffectList. */ -void SPLPEItem::replacePathEffects( std::vector const &old_lpeobjs, - std::vector const &new_lpeobjs ) +void SPLPEItem::replacePathEffects(std::vector const &old_lpeobjs, + std::vector const &new_lpeobjs) { HRefList hreflist; - for (PathEffectList::const_iterator it = this->path_effect_list->begin(); it != this->path_effect_list->end(); ++it) - { - LivePathEffectObject const * current_lpeobj = (*it)->lpeobject; - std::vector::const_iterator found_it(std::find(old_lpeobjs.begin(), old_lpeobjs.end(), current_lpeobj)); - - if ( found_it != old_lpeobjs.end() ) { - std::vector::difference_type found_index = std::distance (old_lpeobjs.begin(), found_it); - const gchar * repr_id = new_lpeobjs[found_index]->getRepr()->attribute("id"); + for (PathEffectList::const_iterator it = this->path_effect_list->begin(); it != this->path_effect_list->end(); + ++it) { + LivePathEffectObject const *current_lpeobj = (*it)->lpeobject; + std::vector::const_iterator found_it( + std::find(old_lpeobjs.begin(), old_lpeobjs.end(), current_lpeobj)); + + if (found_it != old_lpeobjs.end()) { + std::vector::difference_type found_index = + std::distance(old_lpeobjs.begin(), found_it); + const gchar *repr_id = new_lpeobjs[found_index]->getRepr()->attribute("id"); gchar *hrefstr = g_strdup_printf("#%s", repr_id); - hreflist.push_back( std::string(hrefstr) ); + hreflist.push_back(std::string(hrefstr)); g_free(hrefstr); - } - else { - hreflist.push_back( std::string((*it)->lpeobject_href) ); + } else { + hreflist.push_back(std::string((*it)->lpeobject_href)); } } @@ -1202,10 +1191,10 @@ void SPLPEItem::replacePathEffects( std::vector co bool SPLPEItem::forkPathEffectsIfNecessary(unsigned int nr_of_allowed_users, bool recursive) { bool forked = false; - SPGroup * group = dynamic_cast(this); + SPGroup *group = dynamic_cast(this); if (group && recursive) { - std::vector item_list = sp_item_group_item_list(group); - for (auto child:item_list) { + std::vector item_list = sp_item_group_item_list(group); + for (auto child : item_list) { SPLPEItem *lpeitem = dynamic_cast(child); if (lpeitem && lpeitem->forkPathEffectsIfNecessary(nr_of_allowed_users, recursive)) { forked = true; @@ -1213,7 +1202,7 @@ bool SPLPEItem::forkPathEffectsIfNecessary(unsigned int nr_of_allowed_users, boo } } - if ( this->hasPathEffect() ) { + if (this->hasPathEffect()) { // If one of the path effects is used by 2 or more items, fork it // so that each object has its own independent copy of the effect. // Note: replacing path effects messes up the path effect list @@ -1224,8 +1213,7 @@ bool SPLPEItem::forkPathEffectsIfNecessary(unsigned int nr_of_allowed_users, boo std::vector old_lpeobjs, new_lpeobjs; PathEffectList effect_list = this->getEffectList(); - for (auto & it : effect_list) - { + for (auto &it : effect_list) { LivePathEffectObject *lpeobj = it->lpeobject; if (lpeobj) { LivePathEffectObject *forked_lpeobj = lpeobj->fork_private_if_necessary(nr_of_allowed_users); @@ -1251,8 +1239,7 @@ void sp_lpe_item_enable_path_effects(SPLPEItem *lpeitem, bool enable) { if (enable) { lpeitem->path_effects_enabled++; - } - else { + } else { lpeitem->path_effects_enabled--; } } diff --git a/src/object/sp-lpe-item.h b/src/object/sp-lpe-item.h index 74d9baee1b2c4fa70da85d70b13f6a21175e6a02..9c5d1033ca83a75e1abebceffa0c6815d90d3ebb 100644 --- a/src/object/sp-lpe-item.h +++ b/src/object/sp-lpe-item.h @@ -17,71 +17,75 @@ #include #include + #include "sp-item.h" -#define SP_LPE_ITEM(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_LPE_ITEM(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_LPE_ITEM(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_LPE_ITEM(obj) (dynamic_cast((SPObject *)obj) != NULL) class LivePathEffectObject; class SPCurve; class SPShape; class SPDesktop; -namespace Inkscape{ - namespace Display { - class TemporaryItem; - } - namespace LivePathEffect{ - class LPEObjectReference; - class Effect; - } +namespace Inkscape { +namespace Display { +class TemporaryItem; } +namespace LivePathEffect { +class LPEObjectReference; +class Effect; +} // namespace LivePathEffect +} // namespace Inkscape typedef std::list PathEffectList; -class SPLPEItem : public SPItem { +class SPLPEItem : public SPItem +{ public: SPLPEItem(); ~SPLPEItem() override; int path_effects_enabled; - PathEffectList* path_effect_list; - std::list *lpe_modified_connection_list; // this list contains the connections for listening to lpeobject parameter changes - - Inkscape::LivePathEffect::LPEObjectReference* current_path_effect; - std::vector lpe_helperpaths; + PathEffectList *path_effect_list; + std::list *lpe_modified_connection_list; // this list contains the connections for listening to + // lpeobject parameter changes - void replacePathEffects( std::vector const &old_lpeobjs, - std::vector const &new_lpeobjs ); + Inkscape::LivePathEffect::LPEObjectReference *current_path_effect; + std::vector lpe_helperpaths; + void replacePathEffects(std::vector const &old_lpeobjs, + std::vector const &new_lpeobjs); - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; void release() override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; void modified(unsigned int flags) override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; virtual void update_patheffect(bool write); bool optimizeTransforms(); void notifyTransform(Geom::Affine const &postmul); bool performPathEffect(SPCurve *curve, SPShape *current, bool is_clip_or_mask = false); - bool performOnePathEffect(SPCurve *curve, SPShape *current, Inkscape::LivePathEffect::Effect *lpe, bool is_clip_or_mask = false); + bool performOnePathEffect(SPCurve *curve, SPShape *current, Inkscape::LivePathEffect::Effect *lpe, + bool is_clip_or_mask = false); bool pathEffectsEnabled() const; bool hasPathEffect() const; bool hasPathEffectOfType(int const type, bool is_ready = true) const; bool hasPathEffectRecursive() const; - bool hasPathEffectOnClipOrMask(SPLPEItem * shape) const; - bool hasPathEffectOnClipOrMaskRecursive(SPLPEItem * shape) const; - Inkscape::LivePathEffect::Effect* getPathEffectOfType(int type); - Inkscape::LivePathEffect::Effect const* getPathEffectOfType(int type) const; + bool hasPathEffectOnClipOrMask(SPLPEItem *shape) const; + bool hasPathEffectOnClipOrMaskRecursive(SPLPEItem *shape) const; + Inkscape::LivePathEffect::Effect *getPathEffectOfType(int type); + Inkscape::LivePathEffect::Effect const *getPathEffectOfType(int type) const; bool hasBrokenPathEffect() const; PathEffectList getEffectList(); @@ -89,22 +93,23 @@ public: void downCurrentPathEffect(); void upCurrentPathEffect(); - Inkscape::LivePathEffect::LPEObjectReference* getCurrentLPEReference(); - Inkscape::LivePathEffect::Effect* getCurrentLPE(); - bool setCurrentPathEffect(Inkscape::LivePathEffect::LPEObjectReference* lperef); + Inkscape::LivePathEffect::LPEObjectReference *getCurrentLPEReference(); + Inkscape::LivePathEffect::Effect *getCurrentLPE(); + bool setCurrentPathEffect(Inkscape::LivePathEffect::LPEObjectReference *lperef); void removeCurrentPathEffect(bool keep_paths); void removeAllPathEffects(bool keep_paths); void addPathEffect(std::string value, bool reset); - void addPathEffect(LivePathEffectObject * new_lpeobj); + void addPathEffect(LivePathEffectObject *new_lpeobj); void resetClipPathAndMaskLPE(bool fromrecurse = false); - void applyToMask(SPItem* to, Inkscape::LivePathEffect::Effect *lpe = nullptr); - void applyToClipPath(SPItem* to, Inkscape::LivePathEffect::Effect *lpe = nullptr); - void applyToClipPathOrMask(SPItem * clip_mask, SPItem* to, Inkscape::LivePathEffect::Effect *lpe = nullptr); + void applyToMask(SPItem *to, Inkscape::LivePathEffect::Effect *lpe = nullptr); + void applyToClipPath(SPItem *to, Inkscape::LivePathEffect::Effect *lpe = nullptr); + void applyToClipPathOrMask(SPItem *clip_mask, SPItem *to, Inkscape::LivePathEffect::Effect *lpe = nullptr); bool forkPathEffectsIfNecessary(unsigned int nr_of_allowed_users = 1, bool recursive = true); void editNextParamOncanvas(SPDesktop *dt); }; -void sp_lpe_item_update_patheffect (SPLPEItem *lpeitem, bool wholetree, bool write); // careful, class already has method with *very* similar name! +void sp_lpe_item_update_patheffect(SPLPEItem *lpeitem, bool wholetree, + bool write); // careful, class already has method with *very* similar name! void sp_lpe_item_enable_path_effects(SPLPEItem *lpeitem, bool enable); #endif /* !SP_LPE_ITEM_H_SEEN */ diff --git a/src/object/sp-marker-loc.h b/src/object/sp-marker-loc.h index 6b88d699912eb775ada4e04e15cafb732af20bb1..4f5d0ec5a65332abd53d28a38fcb1a077926489a 100644 --- a/src/object/sp-marker-loc.h +++ b/src/object/sp-marker-loc.h @@ -17,7 +17,8 @@ * * IMPORTANT: the code assumes that the locations have the values as written below! so don't change the values!!! */ -enum SPMarkerLoc { +enum SPMarkerLoc +{ SP_MARKER_LOC = 0, SP_MARKER_LOC_START = 1, SP_MARKER_LOC_MID = 2, @@ -25,7 +26,6 @@ enum SPMarkerLoc { SP_MARKER_LOC_QTY = 4 }; - #endif /* !SEEN_SP_MARKER_LOC_H */ /* diff --git a/src/object/sp-marker.cpp b/src/object/sp-marker.cpp index 81ff30f422123411b820aecb041470bce6af8da2..7257c2b08a5ddf326b703f9c7a94fd248a0c7bac 100644 --- a/src/object/sp-marker.cpp +++ b/src/object/sp-marker.cpp @@ -15,28 +15,29 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include -#include +#include "sp-marker.h" #include <2geom/affine.h> #include <2geom/transforms.h> -#include "svg/svg.h" -#include "display/drawing-group.h" -#include "xml/repr.h" +#include +#include + #include "attributes.h" +#include "display/drawing-group.h" #include "document.h" #include "preferences.h" - -#include "sp-marker.h" #include "sp-defs.h" +#include "svg/svg.h" +#include "xml/repr.h" -class SPMarkerView { - +class SPMarkerView +{ public: - - SPMarkerView() = default;; - ~SPMarkerView() { - for (auto & item : items) { + SPMarkerView() = default; + ; + ~SPMarkerView() + { + for (auto &item : items) { delete item; } items.clear(); @@ -44,18 +45,20 @@ public: std::vector items; }; -SPMarker::SPMarker() : SPGroup(), SPViewBox(), - markerUnits_set(0), - markerUnits(0), - refX(), - refY(), - markerWidth(), - markerHeight(), - orient_set(0), - orient_mode(MARKER_ORIENT_ANGLE) +SPMarker::SPMarker() + : SPGroup() + , SPViewBox() + , markerUnits_set(0) + , markerUnits(0) + , refX() + , refY() + , markerWidth() + , markerHeight() + , orient_set(0) + , orient_mode(MARKER_ORIENT_ANGLE) { // cppcheck-suppress useInitializationList - orient = 0; + orient = 0; } /** @@ -75,7 +78,8 @@ SPMarker::~SPMarker() = default; * * \see SPObject::build() */ -void SPMarker::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPMarker::build(SPDocument *document, Inkscape::XML::Node *repr) +{ this->readAttr(SPAttr::MARKERUNITS); this->readAttr(SPAttr::REFX); this->readAttr(SPAttr::REFY); @@ -89,7 +93,6 @@ void SPMarker::build(SPDocument *document, Inkscape::XML::Node *repr) { SPGroup::build(document, repr); } - /** * Removes, releases and unrefs all children of object * @@ -102,98 +105,98 @@ void SPMarker::build(SPDocument *document, Inkscape::XML::Node *repr) { * * \see SPObject::release() */ -void SPMarker::release() { - +void SPMarker::release() +{ std::map::iterator it; for (it = views_map.begin(); it != views_map.end(); ++it) { - SPGroup::hide( it->first ); + SPGroup::hide(it->first); } views_map.clear(); SPGroup::release(); } +void SPMarker::set(SPAttr key, const gchar *value) +{ + switch (key) { + case SPAttr::MARKERUNITS: + this->markerUnits_set = FALSE; + this->markerUnits = SP_MARKER_UNITS_STROKEWIDTH; + + if (value) { + if (!strcmp(value, "strokeWidth")) { + this->markerUnits_set = TRUE; + } else if (!strcmp(value, "userSpaceOnUse")) { + this->markerUnits = SP_MARKER_UNITS_USERSPACEONUSE; + this->markerUnits_set = TRUE; + } + } + + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); + break; -void SPMarker::set(SPAttr key, const gchar* value) { - switch (key) { - case SPAttr::MARKERUNITS: - this->markerUnits_set = FALSE; - this->markerUnits = SP_MARKER_UNITS_STROKEWIDTH; - - if (value) { - if (!strcmp (value, "strokeWidth")) { - this->markerUnits_set = TRUE; - } else if (!strcmp (value, "userSpaceOnUse")) { - this->markerUnits = SP_MARKER_UNITS_USERSPACEONUSE; - this->markerUnits_set = TRUE; - } - } - - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); - break; - - case SPAttr::REFX: - this->refX.readOrUnset(value); - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::REFY: - this->refY.readOrUnset(value); - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::MARKERWIDTH: - this->markerWidth.readOrUnset(value, SVGLength::NONE, 3.0, 3.0); - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::MARKERHEIGHT: - this->markerHeight.readOrUnset(value, SVGLength::NONE, 3.0, 3.0); - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::ORIENT: - this->orient_set = FALSE; - this->orient_mode = MARKER_ORIENT_ANGLE; - this->orient = 0.0; - - if (value) { - if (!strcmp (value, "auto")) { - this->orient_mode = MARKER_ORIENT_AUTO; - this->orient_set = TRUE; - } else if (!strcmp (value, "auto-start-reverse")) { - this->orient_mode = MARKER_ORIENT_AUTO_START_REVERSE; - this->orient_set = TRUE; - } else { - orient.readOrUnset(value); - if (orient._set) { - this->orient_mode = MARKER_ORIENT_ANGLE; - this->orient_set = orient._set; - } + case SPAttr::REFX: + this->refX.readOrUnset(value); + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::REFY: + this->refY.readOrUnset(value); + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::MARKERWIDTH: + this->markerWidth.readOrUnset(value, SVGLength::NONE, 3.0, 3.0); + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::MARKERHEIGHT: + this->markerHeight.readOrUnset(value, SVGLength::NONE, 3.0, 3.0); + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::ORIENT: + this->orient_set = FALSE; + this->orient_mode = MARKER_ORIENT_ANGLE; + this->orient = 0.0; + + if (value) { + if (!strcmp(value, "auto")) { + this->orient_mode = MARKER_ORIENT_AUTO; + this->orient_set = TRUE; + } else if (!strcmp(value, "auto-start-reverse")) { + this->orient_mode = MARKER_ORIENT_AUTO_START_REVERSE; + this->orient_set = TRUE; + } else { + orient.readOrUnset(value); + if (orient._set) { + this->orient_mode = MARKER_ORIENT_ANGLE; + this->orient_set = orient._set; } - } + } + } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::VIEWBOX: - set_viewBox( value ); + case SPAttr::VIEWBOX: + set_viewBox(value); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); break; - case SPAttr::PRESERVEASPECTRATIO: - set_preserveAspectRatio( value ); + case SPAttr::PRESERVEASPECTRATIO: + set_preserveAspectRatio(value); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); break; - default: - SPGroup::set(key, value); - break; - } + default: + SPGroup::set(key, value); + break; + } } -void SPMarker::update(SPCtx *ctx, guint flags) { - +void SPMarker::update(SPCtx *ctx, guint flags) +{ SPItemCtx ictx; // Copy parent context @@ -206,20 +209,20 @@ void SPMarker::update(SPCtx *ctx, guint flags) { // Set up viewport ictx.viewport = Geom::Rect::from_xywh(0, 0, this->markerWidth.computed, this->markerHeight.computed); - SPItemCtx rctx = get_rctx( &ictx ); + SPItemCtx rctx = get_rctx(&ictx); // Shift according to refX, refY - Geom::Point ref( this->refX.computed, this->refY.computed ); + Geom::Point ref(this->refX.computed, this->refY.computed); ref *= c2p; - this->c2p = this->c2p * Geom::Translate( -ref ); + this->c2p = this->c2p * Geom::Translate(-ref); // And invoke parent method - SPGroup::update((SPCtx *) &rctx, flags); + SPGroup::update((SPCtx *)&rctx, flags); // As last step set additional transform of drawing group std::map::iterator it; for (it = views_map.begin(); it != views_map.end(); ++it) { - for (auto & item : it->second.items) { + for (auto &item : it->second.items) { if (item) { Inkscape::DrawingGroup *g = dynamic_cast(item); g->setChildTransform(this->c2p); @@ -228,89 +231,92 @@ void SPMarker::update(SPCtx *ctx, guint flags) { } } -Inkscape::XML::Node* SPMarker::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { - repr = xml_doc->createElement("svg:marker"); - } - - if (this->markerUnits_set) { - if (this->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) { - repr->setAttribute("markerUnits", "strokeWidth"); - } else { - repr->setAttribute("markerUnits", "userSpaceOnUse"); - } - } else { - repr->removeAttribute("markerUnits"); - } - - if (this->refX._set) { - sp_repr_set_svg_double(repr, "refX", this->refX.computed); - } else { - repr->removeAttribute("refX"); - } - - if (this->refY._set) { - sp_repr_set_svg_double (repr, "refY", this->refY.computed); - } else { - repr->removeAttribute("refY"); - } - - if (this->markerWidth._set) { - sp_repr_set_svg_double (repr, "markerWidth", this->markerWidth.computed); - } else { - repr->removeAttribute("markerWidth"); - } - - if (this->markerHeight._set) { - sp_repr_set_svg_double (repr, "markerHeight", this->markerHeight.computed); - } else { - repr->removeAttribute("markerHeight"); - } - - if (this->orient_set) { - if (this->orient_mode == MARKER_ORIENT_AUTO) { - repr->setAttribute("orient", "auto"); - } else if (this->orient_mode == MARKER_ORIENT_AUTO_START_REVERSE) { - repr->setAttribute("orient", "auto-start-reverse"); - } else { - sp_repr_set_css_double(repr, "orient", this->orient.computed); - } - } else { - repr->removeAttribute("orient"); - } - - /* fixme: */ - //XML Tree being used directly here while it shouldn't be.... - repr->setAttribute("viewBox", this->getRepr()->attribute("viewBox")); - //XML Tree being used directly here while it shouldn't be.... - repr->setAttribute("preserveAspectRatio", this->getRepr()->attribute("preserveAspectRatio")); - - SPGroup::write(xml_doc, repr, flags); - - return repr; +Inkscape::XML::Node *SPMarker::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { + repr = xml_doc->createElement("svg:marker"); + } + + if (this->markerUnits_set) { + if (this->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) { + repr->setAttribute("markerUnits", "strokeWidth"); + } else { + repr->setAttribute("markerUnits", "userSpaceOnUse"); + } + } else { + repr->removeAttribute("markerUnits"); + } + + if (this->refX._set) { + sp_repr_set_svg_double(repr, "refX", this->refX.computed); + } else { + repr->removeAttribute("refX"); + } + + if (this->refY._set) { + sp_repr_set_svg_double(repr, "refY", this->refY.computed); + } else { + repr->removeAttribute("refY"); + } + + if (this->markerWidth._set) { + sp_repr_set_svg_double(repr, "markerWidth", this->markerWidth.computed); + } else { + repr->removeAttribute("markerWidth"); + } + + if (this->markerHeight._set) { + sp_repr_set_svg_double(repr, "markerHeight", this->markerHeight.computed); + } else { + repr->removeAttribute("markerHeight"); + } + + if (this->orient_set) { + if (this->orient_mode == MARKER_ORIENT_AUTO) { + repr->setAttribute("orient", "auto"); + } else if (this->orient_mode == MARKER_ORIENT_AUTO_START_REVERSE) { + repr->setAttribute("orient", "auto-start-reverse"); + } else { + sp_repr_set_css_double(repr, "orient", this->orient.computed); + } + } else { + repr->removeAttribute("orient"); + } + + /* fixme: */ + // XML Tree being used directly here while it shouldn't be.... + repr->setAttribute("viewBox", this->getRepr()->attribute("viewBox")); + // XML Tree being used directly here while it shouldn't be.... + repr->setAttribute("preserveAspectRatio", this->getRepr()->attribute("preserveAspectRatio")); + + SPGroup::write(xml_doc, repr, flags); + + return repr; } -Inkscape::DrawingItem* SPMarker::show(Inkscape::Drawing &/*drawing*/, unsigned int /*key*/, unsigned int /*flags*/) { +Inkscape::DrawingItem *SPMarker::show(Inkscape::Drawing & /*drawing*/, unsigned int /*key*/, unsigned int /*flags*/) +{ // Markers in tree are never shown directly even if outside of . - return nullptr; + return nullptr; } -Inkscape::DrawingItem* SPMarker::private_show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) { +Inkscape::DrawingItem *SPMarker::private_show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) +{ return SPGroup::show(drawing, key, flags); } -void SPMarker::hide(unsigned int key) { - // CPPIFY: correct? - SPGroup::hide(key); +void SPMarker::hide(unsigned int key) +{ + // CPPIFY: correct? + SPGroup::hide(key); } -Geom::OptRect SPMarker::bbox(Geom::Affine const &/*transform*/, SPItem::BBoxType /*type*/) const { - return Geom::OptRect(); +Geom::OptRect SPMarker::bbox(Geom::Affine const & /*transform*/, SPItem::BBoxType /*type*/) const +{ + return Geom::OptRect(); } -void SPMarker::print(SPPrintContext* /*ctx*/) { - -} +void SPMarker::print(SPPrintContext * /*ctx*/) {} /* fixme: Remove link if zero-sized (Lauris) */ @@ -327,12 +333,11 @@ void SPMarker::print(SPPrintContext* /*ctx*/) { */ // If marker views are always created in order, then this function could be eliminated // by doing the push_back in sp_marker_show_instance. -void -sp_marker_show_dimension (SPMarker *marker, unsigned int key, unsigned int size) +void sp_marker_show_dimension(SPMarker *marker, unsigned int key, unsigned int size) { std::map::iterator it = marker->views_map.find(key); if (it != marker->views_map.end()) { - if (it->second.items.size() != size ) { + if (it->second.items.size() != size) { // Need to change size of vector! (We should not really need to do this.) marker->hide(key); it->second.items.clear(); @@ -352,10 +357,8 @@ sp_marker_show_dimension (SPMarker *marker, unsigned int key, unsigned int size) * Shows an instance of a marker. This is called during sp_shape_update_marker_view() * show and transform a child item in the drawing for all views with the given key. */ -Inkscape::DrawingItem * -sp_marker_show_instance ( SPMarker *marker, Inkscape::DrawingItem *parent, - unsigned int key, unsigned int pos, - Geom::Affine const &base, float linewidth) +Inkscape::DrawingItem *sp_marker_show_instance(SPMarker *marker, Inkscape::DrawingItem *parent, unsigned int key, + unsigned int pos, Geom::Affine const &base, float linewidth) { // Do not show marker if linewidth == 0 and markerUnits == strokeWidth // otherwise Cairo will fail to render anything on the tile @@ -371,14 +374,13 @@ sp_marker_show_instance ( SPMarker *marker, Inkscape::DrawingItem *parent, } SPMarkerView *view = &(it->second); - if (pos >= view->items.size() ) { + if (pos >= view->items.size()) { // Position index too large, doesn't exist. return nullptr; } // If not already created if (view->items[pos] == nullptr) { - /* Parent class ::show method */ view->items[pos] = marker->private_show(parent->drawing(), key, SP_ITEM_REFERENCE_FLAGS); @@ -386,7 +388,8 @@ sp_marker_show_instance ( SPMarker *marker, Inkscape::DrawingItem *parent, /* fixme: Position (Lauris) */ parent->prependChild(view->items[pos]); Inkscape::DrawingGroup *g = dynamic_cast(view->items[pos]); - if (g) g->setChildTransform(marker->c2p); + if (g) + g->setChildTransform(marker->c2p); } } @@ -417,15 +420,14 @@ sp_marker_show_instance ( SPMarker *marker, Inkscape::DrawingItem *parent, * This replaces SPItem implementation because we have our own views * \param key SPMarkerView key to hide. */ -void -sp_marker_hide (SPMarker *marker, unsigned int key) +void sp_marker_hide(SPMarker *marker, unsigned int key) { marker->hide(key); marker->views_map.erase(key); } - -const gchar *generate_marker(std::vector &reprs, Geom::Rect bounds, SPDocument *document, Geom::Point center, Geom::Affine move) +const gchar *generate_marker(std::vector &reprs, Geom::Rect bounds, SPDocument *document, + Geom::Point center, Geom::Affine move) { Inkscape::XML::Document *xml_doc = document->getReprDoc(); Inkscape::XML::Node *defsrepr = document->getDefs()->getRepr(); @@ -435,7 +437,7 @@ const gchar *generate_marker(std::vector &reprs, Geom::Rec // Uncommenting this will make the marker fixed-size independent of stroke width. // Commented out for consistency with standard markers which scale when you change // stroke width: - //repr->setAttribute("markerUnits", "userSpaceOnUse"); + // repr->setAttribute("markerUnits", "userSpaceOnUse"); sp_repr_set_svg_double(repr, "markerWidth", bounds.dimensions()[Geom::X]); sp_repr_set_svg_double(repr, "markerHeight", bounds.dimensions()[Geom::Y]); @@ -448,11 +450,11 @@ const gchar *generate_marker(std::vector &reprs, Geom::Rec const gchar *mark_id = repr->attribute("id"); SPObject *mark_object = document->getObjectById(mark_id); - for (auto node : reprs){ + for (auto node : reprs) { SPItem *copy = SP_ITEM(mark_object->appendChildRepr(node)); Geom::Affine dup_transform; - if (!sp_svg_transform_read (node->attribute("transform"), &dup_transform)) + if (!sp_svg_transform_read(node->attribute("transform"), &dup_transform)) dup_transform = Geom::identity(); dup_transform *= move; @@ -473,7 +475,7 @@ SPObject *sp_marker_fork_if_necessary(SPObject *marker) gboolean colorStock = prefs->getBool("/options/markers/colorStockMarkers", true); gboolean colorCustom = prefs->getBool("/options/markers/colorCustomMarkers", false); const gchar *stock = marker->getRepr()->attribute("inkscape:isstock"); - gboolean isStock = (!stock || !strcmp(stock,"true")); + gboolean isStock = (!stock || !strcmp(stock, "true")); if (isStock ? !colorStock : !colorCustom) { return marker; diff --git a/src/object/sp-marker.h b/src/object/sp-marker.h index fc605104e86e2d05d2105423fb3c636b2c967def..1167272129a1e49ea785b638609f94630295611a 100644 --- a/src/object/sp-marker.h +++ b/src/object/sp-marker.h @@ -18,91 +18,94 @@ * Maybe we should merge them somehow (Lauris) */ -#define SP_TYPE_MARKER (sp_marker_get_type ()) -#define SP_MARKER(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_MARKER(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_TYPE_MARKER (sp_marker_get_type()) +#define SP_MARKER(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_MARKER(obj) (dynamic_cast((SPObject *)obj) != NULL) class SPMarkerView; -#include - -#include <2geom/rect.h> #include <2geom/affine.h> +#include <2geom/rect.h> +#include #include "enums.h" -#include "svg/svg-length.h" -#include "svg/svg-angle.h" #include "sp-item-group.h" +#include "svg/svg-angle.h" +#include "svg/svg-length.h" #include "uri-references.h" #include "viewbox.h" -enum markerOrient { - MARKER_ORIENT_ANGLE, - MARKER_ORIENT_AUTO, - MARKER_ORIENT_AUTO_START_REVERSE +enum markerOrient +{ + MARKER_ORIENT_ANGLE, + MARKER_ORIENT_AUTO, + MARKER_ORIENT_AUTO_START_REVERSE }; -class SPMarker : public SPGroup, public SPViewBox { +class SPMarker + : public SPGroup + , public SPViewBox +{ public: - SPMarker(); - ~SPMarker() override; - - /* units */ - unsigned int markerUnits_set : 1; - unsigned int markerUnits : 1; - - /* reference point */ - SVGLength refX; - SVGLength refY; - - /* dimensions */ - SVGLength markerWidth; - SVGLength markerHeight; - - /* orient */ - unsigned int orient_set : 1; - markerOrient orient_mode : 2; - SVGAngle orient; - - /* Private views indexed by key that corresponds to a - * particular marker type (start, mid, end) on a particular - * path. SPMarkerView is a wrapper for a vector of pointers to - * Inkscape::DrawingItem instances, one pointer for each - * rendered marker. - */ - std::map views_map; - - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; - void set(SPAttr key, gchar const* value) override; - void update(SPCtx *ctx, guint flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) override; - - Inkscape::DrawingItem* show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; - virtual Inkscape::DrawingItem* private_show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags); - void hide(unsigned int key) override; - - Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; - void print(SPPrintContext *ctx) override; + SPMarker(); + ~SPMarker() override; + + /* units */ + unsigned int markerUnits_set : 1; + unsigned int markerUnits : 1; + + /* reference point */ + SVGLength refX; + SVGLength refY; + + /* dimensions */ + SVGLength markerWidth; + SVGLength markerHeight; + + /* orient */ + unsigned int orient_set : 1; + markerOrient orient_mode : 2; + SVGAngle orient; + + /* Private views indexed by key that corresponds to a + * particular marker type (start, mid, end) on a particular + * path. SPMarkerView is a wrapper for a vector of pointers to + * Inkscape::DrawingItem instances, one pointer for each + * rendered marker. + */ + std::map views_map; + + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, gchar const *value) override; + void update(SPCtx *ctx, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) override; + + Inkscape::DrawingItem *show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; + virtual Inkscape::DrawingItem *private_show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags); + void hide(unsigned int key) override; + + Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; + void print(SPPrintContext *ctx) override; }; -class SPMarkerReference : public Inkscape::URIReference { - SPMarkerReference(SPObject *obj) : URIReference(obj) {} - SPMarker *getObject() const { - return static_cast(URIReference::getObject()); - } +class SPMarkerReference : public Inkscape::URIReference +{ + SPMarkerReference(SPObject *obj) + : URIReference(obj) + {} + SPMarker *getObject() const { return static_cast(URIReference::getObject()); } + protected: - bool _acceptObject(SPObject *obj) const override { - return SP_IS_MARKER(obj) && URIReference::_acceptObject(obj); - } + bool _acceptObject(SPObject *obj) const override { return SP_IS_MARKER(obj) && URIReference::_acceptObject(obj); } }; -void sp_marker_show_dimension (SPMarker *marker, unsigned int key, unsigned int size); -Inkscape::DrawingItem *sp_marker_show_instance (SPMarker *marker, Inkscape::DrawingItem *parent, - unsigned int key, unsigned int pos, - Geom::Affine const &base, float linewidth); -void sp_marker_hide (SPMarker *marker, unsigned int key); -const char *generate_marker (std::vector &reprs, Geom::Rect bounds, SPDocument *document, Geom::Point center, Geom::Affine move); +void sp_marker_show_dimension(SPMarker *marker, unsigned int key, unsigned int size); +Inkscape::DrawingItem *sp_marker_show_instance(SPMarker *marker, Inkscape::DrawingItem *parent, unsigned int key, + unsigned int pos, Geom::Affine const &base, float linewidth); +void sp_marker_hide(SPMarker *marker, unsigned int key); +const char *generate_marker(std::vector &reprs, Geom::Rect bounds, SPDocument *document, + Geom::Point center, Geom::Affine move); SPObject *sp_marker_fork_if_necessary(SPObject *marker); #endif diff --git a/src/object/sp-mask.cpp b/src/object/sp-mask.cpp index 9c9977694ceed090ffb0ffc58dedaf14663fd8b7..b74b5c25be1b4db700d1fee7617df593860ee242 100644 --- a/src/object/sp-mask.cpp +++ b/src/object/sp-mask.cpp @@ -12,51 +12,53 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-mask.h" + +#include <2geom/transforms.h> #include #include -#include <2geom/transforms.h> - -#include "display/drawing.h" -#include "display/drawing-group.h" -#include "xml/repr.h" -#include "enums.h" #include "attributes.h" +#include "display/drawing-group.h" +#include "display/drawing.h" #include "document.h" -#include "style.h" -#include "attributes.h" - +#include "enums.h" #include "sp-defs.h" #include "sp-item.h" -#include "sp-mask.h" +#include "style.h" +#include "xml/repr.h" -SPMaskView *sp_mask_view_new_prepend (SPMaskView *list, unsigned int key, Inkscape::DrawingItem *arenaitem); -SPMaskView *sp_mask_view_list_remove (SPMaskView *list, SPMaskView *view); +SPMaskView *sp_mask_view_new_prepend(SPMaskView *list, unsigned int key, Inkscape::DrawingItem *arenaitem); +SPMaskView *sp_mask_view_list_remove(SPMaskView *list, SPMaskView *view); -SPMask::SPMask() : SPObjectGroup() { - this->maskUnits_set = FALSE; - this->maskUnits = SP_CONTENT_UNITS_OBJECTBOUNDINGBOX; +SPMask::SPMask() + : SPObjectGroup() +{ + this->maskUnits_set = FALSE; + this->maskUnits = SP_CONTENT_UNITS_OBJECTBOUNDINGBOX; - this->maskContentUnits_set = FALSE; - this->maskContentUnits = SP_CONTENT_UNITS_USERSPACEONUSE; + this->maskContentUnits_set = FALSE; + this->maskContentUnits = SP_CONTENT_UNITS_USERSPACEONUSE; - this->display = nullptr; + this->display = nullptr; } SPMask::~SPMask() = default; -void SPMask::build(SPDocument* doc, Inkscape::XML::Node* repr) { - SPObjectGroup::build(doc, repr); +void SPMask::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ + SPObjectGroup::build(doc, repr); - this->readAttr(SPAttr::MASKUNITS); - this->readAttr(SPAttr::MASKCONTENTUNITS); - this->readAttr(SPAttr::STYLE); + this->readAttr(SPAttr::MASKUNITS); + this->readAttr(SPAttr::MASKCONTENTUNITS); + this->readAttr(SPAttr::STYLE); - /* Register ourselves */ - doc->addResource("mask", this); + /* Register ourselves */ + doc->addResource("mask", this); } -void SPMask::release() { +void SPMask::release() +{ if (this->document) { // Unregister ourselves this->document->removeResource("mask", this); @@ -70,49 +72,50 @@ void SPMask::release() { SPObjectGroup::release(); } -void SPMask::set(SPAttr key, const gchar* value) { - switch (key) { - case SPAttr::MASKUNITS: - this->maskUnits = SP_CONTENT_UNITS_OBJECTBOUNDINGBOX; - this->maskUnits_set = FALSE; - - if (value) { - if (!strcmp (value, "userSpaceOnUse")) { - this->maskUnits = SP_CONTENT_UNITS_USERSPACEONUSE; - this->maskUnits_set = TRUE; - } else if (!strcmp (value, "objectBoundingBox")) { - this->maskUnits_set = TRUE; - } - } - - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - case SPAttr::MASKCONTENTUNITS: - this->maskContentUnits = SP_CONTENT_UNITS_USERSPACEONUSE; - this->maskContentUnits_set = FALSE; - - if (value) { - if (!strcmp (value, "userSpaceOnUse")) { - this->maskContentUnits_set = TRUE; - } else if (!strcmp (value, "objectBoundingBox")) { - this->maskContentUnits = SP_CONTENT_UNITS_OBJECTBOUNDINGBOX; - this->maskContentUnits_set = TRUE; - } - } - - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - default: - SPObjectGroup::set(key, value); - break; - } +void SPMask::set(SPAttr key, const gchar *value) +{ + switch (key) { + case SPAttr::MASKUNITS: + this->maskUnits = SP_CONTENT_UNITS_OBJECTBOUNDINGBOX; + this->maskUnits_set = FALSE; + + if (value) { + if (!strcmp(value, "userSpaceOnUse")) { + this->maskUnits = SP_CONTENT_UNITS_USERSPACEONUSE; + this->maskUnits_set = TRUE; + } else if (!strcmp(value, "objectBoundingBox")) { + this->maskUnits_set = TRUE; + } + } + + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + case SPAttr::MASKCONTENTUNITS: + this->maskContentUnits = SP_CONTENT_UNITS_USERSPACEONUSE; + this->maskContentUnits_set = FALSE; + + if (value) { + if (!strcmp(value, "userSpaceOnUse")) { + this->maskContentUnits_set = TRUE; + } else if (!strcmp(value, "objectBoundingBox")) { + this->maskContentUnits = SP_CONTENT_UNITS_OBJECTBOUNDINGBOX; + this->maskContentUnits_set = TRUE; + } + } + + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + default: + SPObjectGroup::set(key, value); + break; + } } -Geom::OptRect -SPMask::geometricBounds(Geom::Affine const &transform) { +Geom::OptRect SPMask::geometricBounds(Geom::Affine const &transform) +{ Geom::OptRect bbox; - for (auto& i: children) { + for (auto &i : children) { if (SP_IS_ITEM(&i)) { Geom::OptRect tmp = SP_ITEM(&i)->geometricBounds(Geom::Affine(SP_ITEM(&i)->transform) * transform); bbox.unionWith(tmp); @@ -122,10 +125,10 @@ SPMask::geometricBounds(Geom::Affine const &transform) { return bbox; } -Geom::OptRect -SPMask::visualBounds(Geom::Affine const &transform) { +Geom::OptRect SPMask::visualBounds(Geom::Affine const &transform) +{ Geom::OptRect bbox; - for (auto& i: children) { + for (auto &i : children) { if (SP_IS_ITEM(&i)) { Geom::OptRect tmp = SP_ITEM(&i)->visualBounds(SP_ITEM(&i)->transform * transform); bbox.unionWith(tmp); @@ -135,31 +138,33 @@ SPMask::visualBounds(Geom::Affine const &transform) { return bbox; } -void SPMask::child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) { - /* Invoke SPObjectGroup implementation */ - SPObjectGroup::child_added(child, ref); - - /* Show new object */ - SPObject *ochild = this->document->getObjectByRepr(child); - - if (SP_IS_ITEM (ochild)) { - for (SPMaskView *v = this->display; v != nullptr; v = v->next) { - Inkscape::DrawingItem *ac = SP_ITEM (ochild)->invoke_show(v->arenaitem->drawing(), v->key, SP_ITEM_REFERENCE_FLAGS); - - if (ac) { - // @fixme must take position into account - v->arenaitem->prependChild(ac); - } - } - } -} +void SPMask::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ + /* Invoke SPObjectGroup implementation */ + SPObjectGroup::child_added(child, ref); + + /* Show new object */ + SPObject *ochild = this->document->getObjectByRepr(child); + if (SP_IS_ITEM(ochild)) { + for (SPMaskView *v = this->display; v != nullptr; v = v->next) { + Inkscape::DrawingItem *ac = + SP_ITEM(ochild)->invoke_show(v->arenaitem->drawing(), v->key, SP_ITEM_REFERENCE_FLAGS); -void SPMask::update(SPCtx* ctx, unsigned int flags) { + if (ac) { + // @fixme must take position into account + v->arenaitem->prependChild(ac); + } + } + } +} + +void SPMask::update(SPCtx *ctx, unsigned int flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } - + flags &= SP_OBJECT_MODIFIED_CASCADE; std::vector children = this->childList(true); @@ -168,13 +173,13 @@ void SPMask::update(SPCtx* ctx, unsigned int flags) { if (flags || (child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->updateDisplay(ctx, flags); } - + sp_object_unref(child); } for (SPMaskView *v = this->display; v != nullptr; v = v->next) { Inkscape::DrawingGroup *g = dynamic_cast(v->arenaitem); - + if (this->maskContentUnits == SP_CONTENT_UNITS_OBJECTBOUNDINGBOX && v->bbox) { Geom::Affine t = Geom::Scale(v->bbox->dimensions()); t.setTranslation(v->bbox->min()); @@ -185,11 +190,12 @@ void SPMask::update(SPCtx* ctx, unsigned int flags) { } } -void SPMask::modified(unsigned int flags) { +void SPMask::modified(unsigned int flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } - + flags &= SP_OBJECT_MODIFIED_CASCADE; std::vector children = this->childList(true); @@ -198,131 +204,133 @@ void SPMask::modified(unsigned int flags) { if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->emitModified(flags); } - + sp_object_unref(child); } } -Inkscape::XML::Node* SPMask::write(Inkscape::XML::Document* xml_doc, Inkscape::XML::Node* repr, guint flags) { - if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { - repr = xml_doc->createElement("svg:mask"); - } +Inkscape::XML::Node *SPMask::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { + repr = xml_doc->createElement("svg:mask"); + } - SPObjectGroup::write(xml_doc, repr, flags); + SPObjectGroup::write(xml_doc, repr, flags); - return repr; + return repr; } // Create a mask element (using passed elements), add it to -const gchar * -sp_mask_create (std::vector &reprs, SPDocument *document) +const gchar *sp_mask_create(std::vector &reprs, SPDocument *document) { Inkscape::XML::Node *defsrepr = document->getDefs()->getRepr(); Inkscape::XML::Document *xml_doc = document->getReprDoc(); Inkscape::XML::Node *repr = xml_doc->createElement("svg:mask"); repr->setAttribute("maskUnits", "userSpaceOnUse"); - + defsrepr->appendChild(repr); const gchar *mask_id = repr->attribute("id"); SPObject *mask_object = document->getObjectById(mask_id); - + for (auto node : reprs) { mask_object->appendChildRepr(node); } if (repr != defsrepr->lastChild()) defsrepr->changeOrder(repr, defsrepr->lastChild()); // workaround for bug 989084 - + Inkscape::GC::release(repr); return mask_id; } -Inkscape::DrawingItem *SPMask::sp_mask_show(Inkscape::Drawing &drawing, unsigned int key) { - g_return_val_if_fail (SP_IS_MASK (this), NULL); +Inkscape::DrawingItem *SPMask::sp_mask_show(Inkscape::Drawing &drawing, unsigned int key) +{ + g_return_val_if_fail(SP_IS_MASK(this), NULL); - Inkscape::DrawingGroup *ai = new Inkscape::DrawingGroup(drawing); - this->display = sp_mask_view_new_prepend (this->display, key, ai); + Inkscape::DrawingGroup *ai = new Inkscape::DrawingGroup(drawing); + this->display = sp_mask_view_new_prepend(this->display, key, ai); - for (auto& child: children) { - if (SP_IS_ITEM (&child)) { - Inkscape::DrawingItem *ac = SP_ITEM (&child)->invoke_show (drawing, key, SP_ITEM_REFERENCE_FLAGS); + for (auto &child : children) { + if (SP_IS_ITEM(&child)) { + Inkscape::DrawingItem *ac = SP_ITEM(&child)->invoke_show(drawing, key, SP_ITEM_REFERENCE_FLAGS); - if (ac) { - ai->appendChild(ac); - } - } - } + if (ac) { + ai->appendChild(ac); + } + } + } - if (this->maskContentUnits == SP_CONTENT_UNITS_OBJECTBOUNDINGBOX && this->display->bbox) { - Geom::Affine t = Geom::Scale(this->display->bbox->dimensions()); - t.setTranslation(this->display->bbox->min()); - ai->setChildTransform(t); - } + if (this->maskContentUnits == SP_CONTENT_UNITS_OBJECTBOUNDINGBOX && this->display->bbox) { + Geom::Affine t = Geom::Scale(this->display->bbox->dimensions()); + t.setTranslation(this->display->bbox->min()); + ai->setChildTransform(t); + } - return ai; + return ai; } -void SPMask::sp_mask_hide(unsigned int key) { - g_return_if_fail (SP_IS_MASK (this)); +void SPMask::sp_mask_hide(unsigned int key) +{ + g_return_if_fail(SP_IS_MASK(this)); - for (auto& child: children) { - if (SP_IS_ITEM (&child)) { - SP_ITEM(&child)->invoke_hide (key); - } - } + for (auto &child : children) { + if (SP_IS_ITEM(&child)) { + SP_ITEM(&child)->invoke_hide(key); + } + } - for (SPMaskView *v = this->display; v != nullptr; v = v->next) { - if (v->key == key) { - /* We simply unref and let item to manage this in handler */ - this->display = sp_mask_view_list_remove (this->display, v); - return; - } - } + for (SPMaskView *v = this->display; v != nullptr; v = v->next) { + if (v->key == key) { + /* We simply unref and let item to manage this in handler */ + this->display = sp_mask_view_list_remove(this->display, v); + return; + } + } - g_assert_not_reached (); + g_assert_not_reached(); } -void SPMask::sp_mask_set_bbox(unsigned int key, Geom::OptRect const &bbox) { - for (SPMaskView *v = this->display; v != nullptr; v = v->next) { - if (v->key == key) { - v->bbox = bbox; - break; - } - } +void SPMask::sp_mask_set_bbox(unsigned int key, Geom::OptRect const &bbox) +{ + for (SPMaskView *v = this->display; v != nullptr; v = v->next) { + if (v->key == key) { + v->bbox = bbox; + break; + } + } } /* Mask views */ -SPMaskView * -sp_mask_view_new_prepend (SPMaskView *list, unsigned int key, Inkscape::DrawingItem *arenaitem) +SPMaskView *sp_mask_view_new_prepend(SPMaskView *list, unsigned int key, Inkscape::DrawingItem *arenaitem) { - SPMaskView *new_mask_view = g_new (SPMaskView, 1); + SPMaskView *new_mask_view = g_new(SPMaskView, 1); - new_mask_view->next = list; - new_mask_view->key = key; - new_mask_view->arenaitem = arenaitem; - new_mask_view->bbox = Geom::OptRect(); + new_mask_view->next = list; + new_mask_view->key = key; + new_mask_view->arenaitem = arenaitem; + new_mask_view->bbox = Geom::OptRect(); - return new_mask_view; + return new_mask_view; } -SPMaskView * -sp_mask_view_list_remove (SPMaskView *list, SPMaskView *view) +SPMaskView *sp_mask_view_list_remove(SPMaskView *list, SPMaskView *view) { - if (view == list) { - list = list->next; - } else { - SPMaskView *prev; - prev = list; - while (prev->next != view) prev = prev->next; - prev->next = view->next; - } - - delete view->arenaitem; - g_free (view); - - return list; + if (view == list) { + list = list->next; + } else { + SPMaskView *prev; + prev = list; + while (prev->next != view) + prev = prev->next; + prev->next = view->next; + } + + delete view->arenaitem; + g_free(view); + + return list; } /* diff --git a/src/object/sp-mask.h b/src/object/sp-mask.h index b0a7f7e789822aaa61d036dd67aeaa343ffed7d9..4ba8423eff74336df7c0b0028bfc2da9a3da9fbc 100644 --- a/src/object/sp-mask.h +++ b/src/object/sp-mask.h @@ -15,70 +15,74 @@ */ #include <2geom/rect.h> + #include "sp-object-group.h" #include "uri-references.h" #include "xml/node.h" -#define SP_MASK(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_MASK(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_MASK(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_MASK(obj) (dynamic_cast((SPObject *)obj) != NULL) namespace Inkscape { class Drawing; class DrawingItem; - } // namespace Inkscape -struct SPMaskView { - SPMaskView *next; - unsigned int key; - Inkscape::DrawingItem *arenaitem; - Geom::OptRect bbox; +struct SPMaskView +{ + SPMaskView *next; + unsigned int key; + Inkscape::DrawingItem *arenaitem; + Geom::OptRect bbox; }; -class SPMask : public SPObjectGroup { +class SPMask : public SPObjectGroup +{ public: - SPMask(); - ~SPMask() override; + SPMask(); + ~SPMask() override; - unsigned int maskUnits_set : 1; - unsigned int maskUnits : 1; + unsigned int maskUnits_set : 1; + unsigned int maskUnits : 1; - unsigned int maskContentUnits_set : 1; - unsigned int maskContentUnits : 1; + unsigned int maskContentUnits_set : 1; + unsigned int maskContentUnits : 1; - SPMaskView *display; + SPMaskView *display; - Inkscape::DrawingItem *sp_mask_show(Inkscape::Drawing &drawing, unsigned int key); - void sp_mask_hide(unsigned int key); + Inkscape::DrawingItem *sp_mask_show(Inkscape::Drawing &drawing, unsigned int key); + void sp_mask_hide(unsigned int key); Geom::OptRect geometricBounds(Geom::Affine const &transform); - Geom::OptRect visualBounds(Geom::Affine const &transform) ; + Geom::OptRect visualBounds(Geom::Affine const &transform); - void sp_mask_set_bbox(unsigned int key, Geom::OptRect const &bbox); + void sp_mask_set_bbox(unsigned int key, Geom::OptRect const &bbox); protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; - void set(SPAttr key, const char* value) override; + void set(SPAttr key, const char *value) override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; -class SPMaskReference : public Inkscape::URIReference { +class SPMaskReference : public Inkscape::URIReference +{ public: - SPMaskReference(SPObject *obj) : URIReference(obj) {} - SPMask *getObject() const { - return static_cast(URIReference::getObject()); - } + SPMaskReference(SPObject *obj) + : URIReference(obj) + {} + SPMask *getObject() const { return static_cast(URIReference::getObject()); } + protected: /** * If the owner element of this reference (the element with <... mask="...">) @@ -86,20 +90,21 @@ protected: * \return false if obj is not a mask or if obj is a parent of this * reference's owner element. True otherwise. */ - bool _acceptObject(SPObject *obj) const override { - if (!SP_IS_MASK(obj)) { - return false; - } - SPObject * const owner = this->getOwner(); + bool _acceptObject(SPObject *obj) const override + { + if (!SP_IS_MASK(obj)) { + return false; + } + SPObject *const owner = this->getOwner(); if (!URIReference::_acceptObject(obj)) { - //XML Tree being used directly here while it shouldn't be... - Inkscape::XML::Node * const owner_repr = owner->getRepr(); - //XML Tree being used directly here while it shouldn't be... - Inkscape::XML::Node * const obj_repr = obj->getRepr(); - char const * owner_name = ""; - char const * owner_mask = ""; - char const * obj_name = ""; - char const * obj_id = ""; + // XML Tree being used directly here while it shouldn't be... + Inkscape::XML::Node *const owner_repr = owner->getRepr(); + // XML Tree being used directly here while it shouldn't be... + Inkscape::XML::Node *const obj_repr = obj->getRepr(); + char const *owner_name = ""; + char const *owner_mask = ""; + char const *obj_name = ""; + char const *obj_id = ""; if (owner_repr != nullptr) { owner_name = owner_repr->name(); owner_mask = owner_repr->attribute("mask"); @@ -109,15 +114,14 @@ protected: obj_id = obj_repr->attribute("id"); } printf("WARNING: Ignoring recursive mask reference " - "<%s mask=\"%s\"> in <%s id=\"%s\">", - owner_name, owner_mask, - obj_name, obj_id); + "<%s mask=\"%s\"> in <%s id=\"%s\">", + owner_name, owner_mask, obj_name, obj_id); return false; } return true; - } + } }; -const char *sp_mask_create (std::vector &reprs, SPDocument *document); +const char *sp_mask_create(std::vector &reprs, SPDocument *document); #endif // SEEN_SP_MASK_H diff --git a/src/object/sp-mesh-array.cpp b/src/object/sp-mesh-array.cpp index 3130f64947c14b5f8dd86969272259d39b1cb9b4..f5cea16a92ab2d53a97b8def3896d724aa7fcdba 100644 --- a/src/object/sp-mesh-array.cpp +++ b/src/object/sp-mesh-array.cpp @@ -42,18 +42,17 @@ #include // For color picking -#include "display/drawing.h" -#include "display/drawing-context.h" #include "display/cairo-utils.h" +#include "display/curve.h" +#include "display/drawing-context.h" +#include "display/drawing.h" #include "document.h" -#include "sp-root.h" - -#include "sp-mesh-gradient.h" #include "sp-mesh-array.h" -#include "sp-mesh-row.h" +#include "sp-mesh-gradient.h" #include "sp-mesh-patch.h" +#include "sp-mesh-row.h" +#include "sp-root.h" #include "sp-stop.h" -#include "display/curve.h" // For new mesh creation #include "preferences.h" @@ -67,40 +66,47 @@ #include "style.h" #include "svg/svg-color.h" - // Includes bezier-curve.h, ray.h, crossing.h -#include "2geom/line.h" - -#include "xml/repr.h" -#include #include +#include -enum { ROW, COL }; +#include "2geom/line.h" +#include "xml/repr.h" -SPMeshPatchI::SPMeshPatchI( std::vector > * n, int r, int c ) { +enum +{ + ROW, + COL +}; +SPMeshPatchI::SPMeshPatchI(std::vector> *n, int r, int c) +{ nodes = n; - row = r*3; // Convert from patch array to node array - col = c*3; + row = r * 3; // Convert from patch array to node array + col = c * 3; guint i = 0; - if( row != 0 ) i = 1; - for( ; i < 4; ++i ) { - if( nodes->size() < row+i+1 ) { - std::vector< SPMeshNode* > row; - nodes->push_back( row ); + if (row != 0) + i = 1; + for (; i < 4; ++i) { + if (nodes->size() < row + i + 1) { + std::vector row; + nodes->push_back(row); } guint j = 0; - if( col != 0 ) j = 1; - for( ; j < 4; ++j ) { - if( (*nodes)[row+i].size() < col+j+1 ){ - SPMeshNode* node = new SPMeshNode; + if (col != 0) + j = 1; + for (; j < 4; ++j) { + if ((*nodes)[row + i].size() < col + j + 1) { + SPMeshNode *node = new SPMeshNode; // Ensure all nodes know their type. node->node_type = MG_NODE_TYPE_HANDLE; - if( (i == 0 || i == 3) && (j == 0 || j == 3 ) ) node->node_type = MG_NODE_TYPE_CORNER; - if( (i == 1 || i == 2) && (j == 1 || j == 2 ) ) node->node_type = MG_NODE_TYPE_TENSOR; - (*nodes)[row+i].push_back( node ); + if ((i == 0 || i == 3) && (j == 0 || j == 3)) + node->node_type = MG_NODE_TYPE_CORNER; + if ((i == 1 || i == 2) && (j == 1 || j == 2)) + node->node_type = MG_NODE_TYPE_TENSOR; + (*nodes)[row + i].push_back(node); } } } @@ -109,110 +115,108 @@ SPMeshPatchI::SPMeshPatchI( std::vector > * n, int r, /** Returns point for side in proper order for patch */ -Geom::Point SPMeshPatchI::getPoint( guint s, guint pt ) { - - assert( s < 4 ); - assert( pt < 4 ); +Geom::Point SPMeshPatchI::getPoint(guint s, guint pt) +{ + assert(s < 4); + assert(pt < 4); Geom::Point p; - switch ( s ) { + switch (s) { case 0: - p = (*nodes)[ row ][ col+pt ]->p; + p = (*nodes)[row][col + pt]->p; break; case 1: - p = (*nodes)[ row+pt ][ col+3 ]->p; + p = (*nodes)[row + pt][col + 3]->p; break; case 2: - p = (*nodes)[ row+3 ][ col+3-pt ]->p; + p = (*nodes)[row + 3][col + 3 - pt]->p; break; case 3: - p = (*nodes)[ row+3-pt ][ col ]->p; + p = (*nodes)[row + 3 - pt][col]->p; break; } return p; - }; /** Returns vector of points for a side in proper order for a patch (clockwise order). */ -std::vector< Geom::Point > SPMeshPatchI::getPointsForSide( guint i ) { - - assert( i < 4 ); +std::vector SPMeshPatchI::getPointsForSide(guint i) +{ + assert(i < 4); - std::vector< Geom::Point> points; - points.push_back( getPoint( i, 0 ) ); - points.push_back( getPoint( i, 1 ) ); - points.push_back( getPoint( i, 2 ) ); - points.push_back( getPoint( i, 3 ) ); + std::vector points; + points.push_back(getPoint(i, 0)); + points.push_back(getPoint(i, 1)); + points.push_back(getPoint(i, 2)); + points.push_back(getPoint(i, 3)); return points; }; - /** Set point for side in proper order for patch */ -void SPMeshPatchI::setPoint( guint s, guint pt, Geom::Point p, bool set ) { - - assert( s < 4 ); - assert( pt < 4 ); +void SPMeshPatchI::setPoint(guint s, guint pt, Geom::Point p, bool set) +{ + assert(s < 4); + assert(pt < 4); NodeType node_type = MG_NODE_TYPE_CORNER; - if( pt == 1 || pt == 2 ) node_type = MG_NODE_TYPE_HANDLE; + if (pt == 1 || pt == 2) + node_type = MG_NODE_TYPE_HANDLE; - // std::cout << "SPMeshPatchI::setPoint: s: " << s + // std::cout << "SPMeshPatchI::setPoint: s: " << s // << " pt: " << pt // << " p: " << p // << " node_type: " << node_type // << " set: " << set // << " row: " << row // << " col: " << col << std::endl; - switch ( s ) { + switch (s) { case 0: - (*nodes)[ row ][ col+pt ]->p = p; - (*nodes)[ row ][ col+pt ]->set = set; - (*nodes)[ row ][ col+pt ]->node_type = node_type; + (*nodes)[row][col + pt]->p = p; + (*nodes)[row][col + pt]->set = set; + (*nodes)[row][col + pt]->node_type = node_type; break; case 1: - (*nodes)[ row+pt ][ col+3 ]->p = p; - (*nodes)[ row+pt ][ col+3 ]->set = set; - (*nodes)[ row+pt ][ col+3 ]->node_type = node_type; + (*nodes)[row + pt][col + 3]->p = p; + (*nodes)[row + pt][col + 3]->set = set; + (*nodes)[row + pt][col + 3]->node_type = node_type; break; case 2: - (*nodes)[ row+3 ][ col+3-pt ]->p = p; - (*nodes)[ row+3 ][ col+3-pt ]->set = set; - (*nodes)[ row+3 ][ col+3-pt ]->node_type = node_type; + (*nodes)[row + 3][col + 3 - pt]->p = p; + (*nodes)[row + 3][col + 3 - pt]->set = set; + (*nodes)[row + 3][col + 3 - pt]->node_type = node_type; break; case 3: - (*nodes)[ row+3-pt ][ col ]->p = p; - (*nodes)[ row+3-pt ][ col ]->set = set; - (*nodes)[ row+3-pt ][ col ]->node_type = node_type; + (*nodes)[row + 3 - pt][col]->p = p; + (*nodes)[row + 3 - pt][col]->set = set; + (*nodes)[row + 3 - pt][col]->node_type = node_type; break; } - }; /** Get path type for side (stored in handle nodes). */ -gchar SPMeshPatchI::getPathType( guint s ) { - - assert( s < 4 ); +gchar SPMeshPatchI::getPathType(guint s) +{ + assert(s < 4); gchar type = 'x'; - switch ( s ) { + switch (s) { case 0: - type = (*nodes)[ row ][ col+1 ]->path_type; + type = (*nodes)[row][col + 1]->path_type; break; case 1: - type = (*nodes)[ row+1 ][ col+3 ]->path_type; + type = (*nodes)[row + 1][col + 3]->path_type; break; case 2: - type = (*nodes)[ row+3 ][ col+2 ]->path_type; + type = (*nodes)[row + 3][col + 2]->path_type; break; case 3: - type = (*nodes)[ row+2 ][ col ]->path_type; + type = (*nodes)[row + 2][col]->path_type; break; } @@ -222,57 +226,56 @@ gchar SPMeshPatchI::getPathType( guint s ) { /** Set path type for side (stored in handle nodes). */ -void SPMeshPatchI::setPathType( guint s, gchar t ) { - - assert( s < 4 ); +void SPMeshPatchI::setPathType(guint s, gchar t) +{ + assert(s < 4); - switch ( s ) { + switch (s) { case 0: - (*nodes)[ row ][ col+1 ]->path_type = t; - (*nodes)[ row ][ col+2 ]->path_type = t; + (*nodes)[row][col + 1]->path_type = t; + (*nodes)[row][col + 2]->path_type = t; break; case 1: - (*nodes)[ row+1 ][ col+3 ]->path_type = t; - (*nodes)[ row+2 ][ col+3 ]->path_type = t; + (*nodes)[row + 1][col + 3]->path_type = t; + (*nodes)[row + 2][col + 3]->path_type = t; break; case 2: - (*nodes)[ row+3 ][ col+1 ]->path_type = t; - (*nodes)[ row+3 ][ col+2 ]->path_type = t; + (*nodes)[row + 3][col + 1]->path_type = t; + (*nodes)[row + 3][col + 2]->path_type = t; break; case 3: - (*nodes)[ row+1 ][ col ]->path_type = t; - (*nodes)[ row+2 ][ col ]->path_type = t; + (*nodes)[row + 1][col]->path_type = t; + (*nodes)[row + 2][col]->path_type = t; break; } - }; /** Set tensor control point for "corner" i. */ -void SPMeshPatchI::setTensorPoint( guint i, Geom::Point p ) { - - assert( i < 4 ); - switch ( i ) { +void SPMeshPatchI::setTensorPoint(guint i, Geom::Point p) +{ + assert(i < 4); + switch (i) { case 0: - (*nodes)[ row + 1 ][ col + 1 ]->p = p; - (*nodes)[ row + 1 ][ col + 1 ]->set = true; - (*nodes)[ row + 1 ][ col + 1 ]->node_type = MG_NODE_TYPE_TENSOR; + (*nodes)[row + 1][col + 1]->p = p; + (*nodes)[row + 1][col + 1]->set = true; + (*nodes)[row + 1][col + 1]->node_type = MG_NODE_TYPE_TENSOR; break; case 1: - (*nodes)[ row + 1 ][ col + 2 ]->p = p; - (*nodes)[ row + 1 ][ col + 2 ]->set = true; - (*nodes)[ row + 1 ][ col + 2 ]->node_type = MG_NODE_TYPE_TENSOR; + (*nodes)[row + 1][col + 2]->p = p; + (*nodes)[row + 1][col + 2]->set = true; + (*nodes)[row + 1][col + 2]->node_type = MG_NODE_TYPE_TENSOR; break; case 2: - (*nodes)[ row + 2 ][ col + 2 ]->p = p; - (*nodes)[ row + 2 ][ col + 2 ]->set = true; - (*nodes)[ row + 2 ][ col + 2 ]->node_type = MG_NODE_TYPE_TENSOR; + (*nodes)[row + 2][col + 2]->p = p; + (*nodes)[row + 2][col + 2]->set = true; + (*nodes)[row + 2][col + 2]->node_type = MG_NODE_TYPE_TENSOR; break; case 3: - (*nodes)[ row + 2 ][ col + 1 ]->p = p; - (*nodes)[ row + 2 ][ col + 1 ]->set = true; - (*nodes)[ row + 2 ][ col + 1 ]->node_type = MG_NODE_TYPE_TENSOR; + (*nodes)[row + 2][col + 1]->p = p; + (*nodes)[row + 2][col + 1]->set = true; + (*nodes)[row + 2][col + 1]->node_type = MG_NODE_TYPE_TENSOR; break; } } @@ -280,9 +283,10 @@ void SPMeshPatchI::setTensorPoint( guint i, Geom::Point p ) { /** Return if any tensor control point is set. */ -bool SPMeshPatchI::tensorIsSet() { - for( guint i = 0; i < 4; ++i ) { - if( tensorIsSet( i ) ) { +bool SPMeshPatchI::tensorIsSet() +{ + for (guint i = 0; i < 4; ++i) { + if (tensorIsSet(i)) { return true; } } @@ -292,23 +296,23 @@ bool SPMeshPatchI::tensorIsSet() { /** Return if tensor control point for "corner" i is set. */ -bool SPMeshPatchI::tensorIsSet( unsigned int i ) { - - assert( i < 4 ); +bool SPMeshPatchI::tensorIsSet(unsigned int i) +{ + assert(i < 4); bool set = false; - switch ( i ) { + switch (i) { case 0: - set = (*nodes)[ row + 1 ][ col + 1 ]->set; + set = (*nodes)[row + 1][col + 1]->set; break; case 1: - set = (*nodes)[ row + 1 ][ col + 2 ]->set; + set = (*nodes)[row + 1][col + 2]->set; break; case 2: - set = (*nodes)[ row + 2 ][ col + 2 ]->set; + set = (*nodes)[row + 2][col + 2]->set; break; case 3: - set = (*nodes)[ row + 2 ][ col + 1 ]->set; + set = (*nodes)[row + 2][col + 1]->set; break; } return set; @@ -318,15 +322,14 @@ bool SPMeshPatchI::tensorIsSet( unsigned int i ) { Return tensor control point for "corner" i. If not set, returns calculated (Coons) point. */ -Geom::Point SPMeshPatchI::getTensorPoint( guint k ) { - - assert( k < 4 ); +Geom::Point SPMeshPatchI::getTensorPoint(guint k) +{ + assert(k < 4); guint i = 0; guint j = 0; - - switch ( k ) { + switch (k) { case 0: i = 1; j = 1; @@ -346,10 +349,10 @@ Geom::Point SPMeshPatchI::getTensorPoint( guint k ) { } Geom::Point p; - if( (*nodes)[ row + i ][ col + j ]->set ) { - p = (*nodes)[ row + i ][ col + j ]->p; + if ((*nodes)[row + i][col + j]->set) { + p = (*nodes)[row + i][col + j]->p; } else { - p = coonsTensorPoint( k ); + p = coonsTensorPoint(k); } return p; } @@ -359,61 +362,52 @@ Geom::Point SPMeshPatchI::getTensorPoint( guint k ) { Formulas defined in PDF spec. Equivalent to 1/3 of side length from corner for square patch. */ -Geom::Point SPMeshPatchI::coonsTensorPoint( guint i ) { - +Geom::Point SPMeshPatchI::coonsTensorPoint(guint i) +{ Geom::Point t; Geom::Point p[4][4]; // Points in PDF notation - p[0][0] = getPoint( 0, 0 ); - p[0][1] = getPoint( 0, 1 ); - p[0][2] = getPoint( 0, 2 ); - p[0][3] = getPoint( 0, 3 ); - p[1][0] = getPoint( 3, 2 ); - p[1][3] = getPoint( 1, 1 ); - p[2][0] = getPoint( 3, 1 ); - p[2][3] = getPoint( 1, 2 ); - p[3][0] = getPoint( 2, 3 ); - p[3][1] = getPoint( 2, 2 ); - p[3][2] = getPoint( 2, 1 ); - p[3][3] = getPoint( 2, 0 ); - - switch ( i ) { + p[0][0] = getPoint(0, 0); + p[0][1] = getPoint(0, 1); + p[0][2] = getPoint(0, 2); + p[0][3] = getPoint(0, 3); + p[1][0] = getPoint(3, 2); + p[1][3] = getPoint(1, 1); + p[2][0] = getPoint(3, 1); + p[2][3] = getPoint(1, 2); + p[3][0] = getPoint(2, 3); + p[3][1] = getPoint(2, 2); + p[3][2] = getPoint(2, 1); + p[3][3] = getPoint(2, 0); + + switch (i) { case 0: - t = ( -4.0 * p[0][0] + - 6.0 * ( p[0][1] + p[1][0] ) + - -2.0 * ( p[0][3] + p[3][0] ) + - 3.0 * ( p[3][1] + p[1][3] ) + - -1.0 * p[3][3] ) / 9.0; + t = (-4.0 * p[0][0] + 6.0 * (p[0][1] + p[1][0]) + -2.0 * (p[0][3] + p[3][0]) + 3.0 * (p[3][1] + p[1][3]) + + -1.0 * p[3][3]) / + 9.0; break; case 1: - t = ( -4.0 * p[0][3] + - 6.0 * ( p[0][2] + p[1][3] ) + - -2.0 * ( p[0][0] + p[3][3] ) + - 3.0 * ( p[3][2] + p[1][0] ) + - -1.0 * p[3][0] ) / 9.0; + t = (-4.0 * p[0][3] + 6.0 * (p[0][2] + p[1][3]) + -2.0 * (p[0][0] + p[3][3]) + 3.0 * (p[3][2] + p[1][0]) + + -1.0 * p[3][0]) / + 9.0; break; case 2: - t = ( -4.0 * p[3][3] + - 6.0 * ( p[3][2] + p[2][3] ) + - -2.0 * ( p[3][0] + p[0][3] ) + - 3.0 * ( p[0][2] + p[2][0] ) + - -1.0 * p[0][0] ) / 9.0; + t = (-4.0 * p[3][3] + 6.0 * (p[3][2] + p[2][3]) + -2.0 * (p[3][0] + p[0][3]) + 3.0 * (p[0][2] + p[2][0]) + + -1.0 * p[0][0]) / + 9.0; break; case 3: - t = ( -4.0 * p[3][0] + - 6.0 * ( p[3][1] + p[2][0] ) + - -2.0 * ( p[3][3] + p[0][0] ) + - 3.0 * ( p[0][1] + p[2][3] ) + - -1.0 * p[0][3] ) / 9.0; + t = (-4.0 * p[3][0] + 6.0 * (p[3][1] + p[2][0]) + -2.0 * (p[3][3] + p[0][0]) + 3.0 * (p[0][1] + p[2][3]) + + -1.0 * p[0][3]) / + 9.0; break; default: - g_warning( "Impossible!" ); - + g_warning("Impossible!"); } return t; } @@ -421,33 +415,33 @@ Geom::Point SPMeshPatchI::coonsTensorPoint( guint i ) { /** Update default values for handle and tensor nodes. */ -void SPMeshPatchI::updateNodes() { - +void SPMeshPatchI::updateNodes() +{ // std::cout << "SPMeshPatchI::updateNodes: " << row << "," << col << std::endl; // Handles first (tensors require update handles). - for( guint i = 0; i < 4; ++i ) { - for( guint j = 0; j < 4; ++j ) { - if( (*nodes)[ row + i ][ col + j ]->set == false ) { - - if( (*nodes)[ row + i ][ col + j ]->node_type == MG_NODE_TYPE_HANDLE ) { - + for (guint i = 0; i < 4; ++i) { + for (guint j = 0; j < 4; ++j) { + if ((*nodes)[row + i][col + j]->set == false) { + if ((*nodes)[row + i][col + j]->node_type == MG_NODE_TYPE_HANDLE) { // If a handle is not set it is because the side is a line. // Set node points 1/3 of the way between corners. - if( i == 0 || i == 3 ) { - Geom::Point p0 = ( (*nodes)[ row + i ][ col ]->p ); - Geom::Point p3 = ( (*nodes)[ row + i ][ col + 3 ]->p ); - Geom::Point dp = (p3 - p0)/3.0; - if( j == 2 ) dp *= 2.0; - (*nodes)[ row + i ][ col + j ]->p = p0 + dp; + if (i == 0 || i == 3) { + Geom::Point p0 = ((*nodes)[row + i][col]->p); + Geom::Point p3 = ((*nodes)[row + i][col + 3]->p); + Geom::Point dp = (p3 - p0) / 3.0; + if (j == 2) + dp *= 2.0; + (*nodes)[row + i][col + j]->p = p0 + dp; } - if( j == 0 || j == 3 ) { - Geom::Point p0 = ( (*nodes)[ row ][ col + j ]->p ); - Geom::Point p3 = ( (*nodes)[ row + 3 ][ col + j ]->p ); - Geom::Point dp = (p3 - p0)/3.0; - if( i == 2 ) dp *= 2.0; - (*nodes)[ row + i ][ col + j ]->p = p0 + dp; + if (j == 0 || j == 3) { + Geom::Point p0 = ((*nodes)[row][col + j]->p); + Geom::Point p3 = ((*nodes)[row + 3][col + j]->p); + Geom::Point dp = (p3 - p0) / 3.0; + if (i == 2) + dp *= 2.0; + (*nodes)[row + i][col + j]->p = p0 + dp; } } } @@ -455,19 +449,20 @@ void SPMeshPatchI::updateNodes() { } // Update tensor nodes - for( guint i = 1; i < 3; ++i ) { - for( guint j = 1; j < 3; ++j ) { - if( (*nodes)[ row + i ][ col + j ]->set == false ) { - - (*nodes)[ row + i ][ col + j ]->node_type = MG_NODE_TYPE_TENSOR; + for (guint i = 1; i < 3; ++i) { + for (guint j = 1; j < 3; ++j) { + if ((*nodes)[row + i][col + j]->set == false) { + (*nodes)[row + i][col + j]->node_type = MG_NODE_TYPE_TENSOR; guint t = 0; - if( i == 1 && j == 2 ) t = 1; - if( i == 2 && j == 2 ) t = 2; - if( i == 2 && j == 1 ) t = 3; - (*nodes)[ row + i ][ col + j ]->p = coonsTensorPoint( t ); + if (i == 1 && j == 2) + t = 1; + if (i == 2 && j == 2) + t = 2; + if (i == 2 && j == 1) + t = 3; + (*nodes)[row + i][col + j]->p = coonsTensorPoint(t); // std::cout << "Update node: " << i << ", " << j << " " << coonsTensorPoint( t ) << std::endl; - } } } @@ -476,50 +471,48 @@ void SPMeshPatchI::updateNodes() { /** Return color for corner of patch. */ -SPColor SPMeshPatchI::getColor( guint i ) { - - assert( i < 4 ); +SPColor SPMeshPatchI::getColor(guint i) +{ + assert(i < 4); SPColor color; - switch ( i ) { + switch (i) { case 0: - color = (*nodes)[ row ][ col ]->color; + color = (*nodes)[row][col]->color; break; case 1: - color = (*nodes)[ row ][ col+3 ]->color; + color = (*nodes)[row][col + 3]->color; break; case 2: - color = (*nodes)[ row+3 ][ col+3 ]->color; + color = (*nodes)[row + 3][col + 3]->color; break; case 3: - color = (*nodes)[ row+3 ][ col ]->color; + color = (*nodes)[row + 3][col]->color; break; - } return color; - }; /** Set color for corner of patch. */ -void SPMeshPatchI::setColor( guint i, SPColor color ) { - - assert( i < 4 ); +void SPMeshPatchI::setColor(guint i, SPColor color) +{ + assert(i < 4); - switch ( i ) { + switch (i) { case 0: - (*nodes)[ row ][ col ]->color = color; - break; - case 1: - (*nodes)[ row ][ col+3 ]->color = color; - break; - case 2: - (*nodes)[ row+3 ][ col+3 ]->color = color; - break; - case 3: - (*nodes)[ row+3 ][ col ]->color = color; + (*nodes)[row][col]->color = color; + break; + case 1: + (*nodes)[row][col + 3]->color = color; + break; + case 2: + (*nodes)[row + 3][col + 3]->color = color; + break; + case 3: + (*nodes)[row + 3][col]->color = color; break; } }; @@ -527,137 +520,127 @@ void SPMeshPatchI::setColor( guint i, SPColor color ) { /** Return opacity for corner of patch. */ -gdouble SPMeshPatchI::getOpacity( guint i ) { - - assert( i < 4 ); +gdouble SPMeshPatchI::getOpacity(guint i) +{ + assert(i < 4); gdouble opacity = 0.0; - switch ( i ) { + switch (i) { case 0: - opacity = (*nodes)[ row ][ col ]->opacity; + opacity = (*nodes)[row][col]->opacity; break; case 1: - opacity = (*nodes)[ row ][ col+3 ]->opacity; + opacity = (*nodes)[row][col + 3]->opacity; break; case 2: - opacity = (*nodes)[ row+3 ][ col+3 ]->opacity; + opacity = (*nodes)[row + 3][col + 3]->opacity; break; case 3: - opacity = (*nodes)[ row+3 ][ col ]->opacity; + opacity = (*nodes)[row + 3][col]->opacity; break; } return opacity; }; - /** Set opacity for corner of patch. */ -void SPMeshPatchI::setOpacity( guint i, gdouble opacity ) { - - assert( i < 4 ); +void SPMeshPatchI::setOpacity(guint i, gdouble opacity) +{ + assert(i < 4); - switch ( i ) { + switch (i) { case 0: - (*nodes)[ row ][ col ]->opacity = opacity; - break; - case 1: - (*nodes)[ row ][ col+3 ]->opacity = opacity; - break; - case 2: - (*nodes)[ row+3 ][ col+3 ]->opacity = opacity; - break; - case 3: - (*nodes)[ row+3 ][ col ]->opacity = opacity; + (*nodes)[row][col]->opacity = opacity; + break; + case 1: + (*nodes)[row][col + 3]->opacity = opacity; + break; + case 2: + (*nodes)[row + 3][col + 3]->opacity = opacity; + break; + case 3: + (*nodes)[row + 3][col]->opacity = opacity; break; - } - }; - /** Return stop pointer for corner of patch. */ -SPStop* SPMeshPatchI::getStopPtr( guint i ) { - - assert( i < 4 ); +SPStop *SPMeshPatchI::getStopPtr(guint i) +{ + assert(i < 4); - SPStop* stop = nullptr; - switch ( i ) { + SPStop *stop = nullptr; + switch (i) { case 0: - stop = (*nodes)[ row ][ col ]->stop; + stop = (*nodes)[row][col]->stop; break; case 1: - stop = (*nodes)[ row ][ col+3 ]->stop; + stop = (*nodes)[row][col + 3]->stop; break; case 2: - stop = (*nodes)[ row+3 ][ col+3 ]->stop; + stop = (*nodes)[row + 3][col + 3]->stop; break; case 3: - stop = (*nodes)[ row+3 ][ col ]->stop; + stop = (*nodes)[row + 3][col]->stop; break; } return stop; }; - /** Set stop pointer for corner of patch. */ -void SPMeshPatchI::setStopPtr( guint i, SPStop* stop ) { - - assert( i < 4 ); +void SPMeshPatchI::setStopPtr(guint i, SPStop *stop) +{ + assert(i < 4); - switch ( i ) { + switch (i) { case 0: - (*nodes)[ row ][ col ]->stop = stop; - break; - case 1: - (*nodes)[ row ][ col+3 ]->stop = stop; - break; - case 2: - (*nodes)[ row+3 ][ col+3 ]->stop = stop; - break; - case 3: - (*nodes)[ row+3 ][ col ]->stop = stop; + (*nodes)[row][col]->stop = stop; + break; + case 1: + (*nodes)[row][col + 3]->stop = stop; + break; + case 2: + (*nodes)[row + 3][col + 3]->stop = stop; + break; + case 3: + (*nodes)[row + 3][col]->stop = stop; break; - } - }; - -SPMeshNodeArray::SPMeshNodeArray( SPMeshGradient *mg ) { - - read( mg ); - +SPMeshNodeArray::SPMeshNodeArray(SPMeshGradient *mg) +{ + read(mg); }; - // Copy constructor -SPMeshNodeArray::SPMeshNodeArray( const SPMeshNodeArray& rhs ) { - +SPMeshNodeArray::SPMeshNodeArray(const SPMeshNodeArray &rhs) +{ built = false; mg = nullptr; draggers_valid = false; nodes = rhs.nodes; // This only copies the pointers but it does size the vector of vectors. - for( unsigned i=0; i < nodes.size(); ++i ) { - for( unsigned j=0; j < nodes[i].size(); ++j ) { - nodes[i][j] = new SPMeshNode( *rhs.nodes[i][j] ); // Copy data. + for (unsigned i = 0; i < nodes.size(); ++i) { + for (unsigned j = 0; j < nodes[i].size(); ++j) { + nodes[i][j] = new SPMeshNode(*rhs.nodes[i][j]); // Copy data. } } }; - // Copy assignment operator -SPMeshNodeArray& SPMeshNodeArray::operator=( const SPMeshNodeArray& rhs ) { - - if( this == &rhs ) return *this; +SPMeshNodeArray &SPMeshNodeArray::operator=(const SPMeshNodeArray &rhs) +{ + if (this == &rhs) + return *this; clear(); // Clear any existing array. @@ -667,21 +650,21 @@ SPMeshNodeArray& SPMeshNodeArray::operator=( const SPMeshNodeArray& rhs ) { nodes = rhs.nodes; // This only copies the pointers but it does size the vector of vectors. - for( unsigned i=0; i < nodes.size(); ++i ) { - for( unsigned j=0; j < nodes[i].size(); ++j ) { - nodes[i][j] = new SPMeshNode( *rhs.nodes[i][j] ); // Copy data. + for (unsigned i = 0; i < nodes.size(); ++i) { + for (unsigned j = 0; j < nodes[i].size(); ++j) { + nodes[i][j] = new SPMeshNode(*rhs.nodes[i][j]); // Copy data. } } - + return *this; }; // Fill array with data from mesh objects. // Returns true of array's dimensions unchanged. -bool SPMeshNodeArray::read( SPMeshGradient *mg_in ) { - +bool SPMeshNodeArray::read(SPMeshGradient *mg_in) +{ mg = mg_in; - SPMeshGradient* mg_array = dynamic_cast(mg->getArray()); + SPMeshGradient *mg_array = dynamic_cast(mg->getArray()); if (!mg_array) { std::cerr << "SPMeshNodeArray::read: No mesh array!" << std::endl; return false; @@ -691,11 +674,11 @@ bool SPMeshNodeArray::read( SPMeshGradient *mg_in ) { // Count rows and columns, if unchanged reuse array to keep draggers valid. unsigned cols = 0; unsigned rows = 0; - for (auto& ro: mg_array->children) { + for (auto &ro : mg_array->children) { if (SP_IS_MESHROW(&ro)) { ++rows; - if (rows == 1 ) { - for (auto& po: ro.children) { + if (rows == 1) { + for (auto &po : ro.children) { if (SP_IS_MESHPATCH(&po)) { ++cols; } @@ -704,42 +687,38 @@ bool SPMeshNodeArray::read( SPMeshGradient *mg_in ) { } } bool same_size = true; - if (cols != patch_columns() || rows != patch_rows() ) { + if (cols != patch_columns() || rows != patch_rows()) { // Draggers will be invalidated. same_size = false; clear(); draggers_valid = false; } - Geom::Point current_p( mg->x.computed, mg->y.computed ); + Geom::Point current_p(mg->x.computed, mg->y.computed); // std::cout << "SPMeshNodeArray::read: p: " << current_p << std::endl; guint max_column = 0; guint irow = 0; // Corresponds to top of patch being read in. - for (auto& ro: mg_array->children) { - + for (auto &ro : mg_array->children) { if (SP_IS_MESHROW(&ro)) { - guint icolumn = 0; // Corresponds to left of patch being read in. - for (auto& po: ro.children) { - + for (auto &po : ro.children) { if (SP_IS_MESHPATCH(&po)) { - SPMeshpatch *patch = SP_MESHPATCH(&po); // std::cout << "SPMeshNodeArray::read: row size: " << nodes.size() << std::endl; - SPMeshPatchI new_patch( &nodes, irow, icolumn ); // Adds new nodes. + SPMeshPatchI new_patch(&nodes, irow, icolumn); // Adds new nodes. // std::cout << " after: " << nodes.size() << std::endl; gint istop = 0; // Only 'top' side defined for first row. - if( irow != 0 ) ++istop; + if (irow != 0) + ++istop; - for (auto& so: po.children) { + for (auto &so : po.children) { if (SP_IS_STOP(&so)) { - - if( istop > 3 ) { + if (istop > 3) { // std::cout << " Mesh Gradient: Too many stops: " << istop << std::endl; break; } @@ -747,85 +726,87 @@ bool SPMeshNodeArray::read( SPMeshGradient *mg_in ) { SPStop *stop = SP_STOP(&so); // Handle top of first row. - if( istop == 0 && icolumn == 0 ) { + if (istop == 0 && icolumn == 0) { // First patch in mesh. - new_patch.setPoint( 0, 0, current_p ); + new_patch.setPoint(0, 0, current_p); } // First point is always already defined by previous side (stop). - current_p = new_patch.getPoint( istop, 0 ); + current_p = new_patch.getPoint(istop, 0); // If side closes patch, then we read one less point. bool closed = false; - if( icolumn == 0 && istop == 3 ) closed = true; - if( icolumn > 0 && istop == 2 ) closed = true; - + if (icolumn == 0 && istop == 3) + closed = true; + if (icolumn > 0 && istop == 2) + closed = true; // Copy path and then replace commas by spaces so we can use stringstream to parse std::string path_string = stop->path_string->raw(); - std::replace(path_string.begin(),path_string.end(),',',' '); + std::replace(path_string.begin(), path_string.end(), ',', ' '); // std::cout << " path_string: " << path_string << std::endl; // std::cout << " current_p: " << current_p << std::endl; - std::stringstream os( path_string ); + std::stringstream os(path_string); // Determine type of path char path_type; os >> path_type; - new_patch.setPathType( istop, path_type ); + new_patch.setPathType(istop, path_type); gdouble x, y; Geom::Point p, dp; guint max; - switch ( path_type ) { + switch (path_type) { case 'l': - if( !closed ) { + if (!closed) { os >> x >> y; - if( !os.fail() ) { - dp = Geom::Point( x, y ); - new_patch.setPoint( istop, 3, current_p + dp ); + if (!os.fail()) { + dp = Geom::Point(x, y); + new_patch.setPoint(istop, 3, current_p + dp); } else { std::cerr << "Failed to read l" << std::endl; } } // To facilitate some side operations, set handles to 1/3 and // 2/3 distance between corner points but flag as unset. - p = new_patch.getPoint( istop, 3 ); - dp = (p - current_p)/3.0; // Calculate since may not be set if closed. + p = new_patch.getPoint(istop, 3); + dp = (p - current_p) / 3.0; // Calculate since may not be set if closed. // std::cout << " istop: " << istop // << " dp: " << dp // << " p: " << p // << " current_p: " << current_p // << std::endl; - new_patch.setPoint( istop, 1, current_p + dp, false ); - new_patch.setPoint( istop, 2, current_p + 2.0 * dp, false ); + new_patch.setPoint(istop, 1, current_p + dp, false); + new_patch.setPoint(istop, 2, current_p + 2.0 * dp, false); break; case 'L': - if( !closed ) { + if (!closed) { os >> x >> y; - if( !os.fail() ) { - p = Geom::Point( x, y ); - new_patch.setPoint( istop, 3, p ); + if (!os.fail()) { + p = Geom::Point(x, y); + new_patch.setPoint(istop, 3, p); } else { std::cerr << "Failed to read L" << std::endl; } } // To facilitate some side operations, set handles to 1/3 and // 2/3 distance between corner points but flag as unset. - p = new_patch.getPoint( istop, 3 ); - dp = (p - current_p)/3.0; - new_patch.setPoint( istop, 1, current_p + dp, false ); - new_patch.setPoint( istop, 2, current_p + 2.0 * dp, false ); + p = new_patch.getPoint(istop, 3); + dp = (p - current_p) / 3.0; + new_patch.setPoint(istop, 1, current_p + dp, false); + new_patch.setPoint(istop, 2, current_p + 2.0 * dp, false); break; case 'c': max = 4; - if( closed ) max = 3; - for( guint i = 1; i < max; ++i ) { + if (closed) + max = 3; + for (guint i = 1; i < max; ++i) { os >> x >> y; - if( !os.fail() ) { - p = Geom::Point( x, y ); + if (!os.fail()) { + p = Geom::Point(x, y); p += current_p; - new_patch.setPoint( istop, i, p ); + new_patch.setPoint(istop, i, p); } else { std::cerr << "Failed to read c: " << i << std::endl; } @@ -833,12 +814,13 @@ bool SPMeshNodeArray::read( SPMeshGradient *mg_in ) { break; case 'C': max = 4; - if( closed ) max = 3; - for( guint i = 1; i < max; ++i ) { + if (closed) + max = 3; + for (guint i = 1; i < max; ++i) { os >> x >> y; - if( !os.fail() ) { - p = Geom::Point( x, y ); - new_patch.setPoint( istop, i, p ); + if (!os.fail()) { + p = Geom::Point(x, y); + new_patch.setPoint(istop, i, p); } else { std::cerr << "Failed to read C: " << i << std::endl; } @@ -848,17 +830,17 @@ bool SPMeshNodeArray::read( SPMeshGradient *mg_in ) { // should not reach std::cerr << "Path Error: unhandled path type: " << path_type << std::endl; } - current_p = new_patch.getPoint( istop, 3 ); + current_p = new_patch.getPoint(istop, 3); // Color - if( (istop == 0 && irow == 0 && icolumn > 0) || (istop == 1 && irow > 0 ) ) { - // skip + if ((istop == 0 && irow == 0 && icolumn > 0) || (istop == 1 && irow > 0)) { + // skip } else { - SPColor color = stop->getColor(); - double opacity = stop->getOpacity(); - new_patch.setColor( istop, color ); - new_patch.setOpacity( istop, opacity ); - new_patch.setStopPtr( istop, stop ); + SPColor color = stop->getColor(); + double opacity = stop->getOpacity(); + new_patch.setColor(istop, color); + new_patch.setOpacity(istop, opacity); + new_patch.setStopPtr(istop, stop); } ++istop; } @@ -867,19 +849,19 @@ bool SPMeshNodeArray::read( SPMeshGradient *mg_in ) { // Read in tensor string after stops since tensor nodes defined relative to corner nodes. // Copy string and then replace commas by spaces so we can use stringstream to parse XXXX - if( patch->tensor_string ) { + if (patch->tensor_string) { std::string tensor_string = patch->tensor_string->raw(); - std::replace(tensor_string.begin(),tensor_string.end(),',',' '); + std::replace(tensor_string.begin(), tensor_string.end(), ',', ' '); // std::cout << " tensor_string: " << tensor_string << std::endl; - std::stringstream os( tensor_string ); - for( guint i = 0; i < 4; ++i ) { + std::stringstream os(tensor_string); + for (guint i = 0; i < 4; ++i) { double x = 0.0; double y = 0.0; os >> x >> y; - if( !os.fail() ) { - new_patch.setTensorPoint( i, new_patch.getPoint( i, 0 ) + Geom::Point( x, y ) ); + if (!os.fail()) { + new_patch.setTensorPoint(i, new_patch.getPoint(i, 0) + Geom::Point(x, y)); } else { std::cerr << "Failed to read p: " << i << std::endl; break; @@ -887,7 +869,8 @@ bool SPMeshNodeArray::read( SPMeshGradient *mg_in ) { } } ++icolumn; - if( max_column < icolumn ) max_column = icolumn; + if (max_column < icolumn) + max_column = icolumn; } } ++irow; @@ -895,18 +878,22 @@ bool SPMeshNodeArray::read( SPMeshGradient *mg_in ) { } // Insure we have a true array. - for(auto & node : nodes) { - node.resize( max_column * 3 + 1 ); + for (auto &node : nodes) { + node.resize(max_column * 3 + 1); } // Set node edge. - for( guint i = 0; i < nodes.size(); ++i ) { - for( guint j = 0; j < nodes[i].size(); ++j ) { + for (guint i = 0; i < nodes.size(); ++i) { + for (guint j = 0; j < nodes[i].size(); ++j) { nodes[i][j]->node_edge = MG_NODE_EDGE_NONE; - if( i == 0 ) nodes[i][j]->node_edge |= MG_NODE_EDGE_TOP; - if( i == nodes.size() - 1 ) nodes[i][j]->node_edge |= MG_NODE_EDGE_BOTTOM; - if( j == 0 ) nodes[i][j]->node_edge |= MG_NODE_EDGE_RIGHT; - if( j == nodes[i].size() - 1 ) nodes[i][j]->node_edge |= MG_NODE_EDGE_LEFT; + if (i == 0) + nodes[i][j]->node_edge |= MG_NODE_EDGE_TOP; + if (i == nodes.size() - 1) + nodes[i][j]->node_edge |= MG_NODE_EDGE_BOTTOM; + if (j == 0) + nodes[i][j]->node_edge |= MG_NODE_EDGE_RIGHT; + if (j == nodes[i].size() - 1) + nodes[i][j]->node_edge |= MG_NODE_EDGE_LEFT; } } @@ -921,14 +908,14 @@ bool SPMeshNodeArray::read( SPMeshGradient *mg_in ) { /** Write repr using our array. */ -void SPMeshNodeArray::write( SPMeshGradient *mg ) { - +void SPMeshNodeArray::write(SPMeshGradient *mg) +{ // std::cout << "SPMeshNodeArray::write: entrance:" << std::endl; // print(); using Geom::X; using Geom::Y; - SPMeshGradient* mg_array = dynamic_cast(mg->getArray()); + SPMeshGradient *mg_array = dynamic_cast(mg->getArray()); if (!mg_array) { // std::cerr << "SPMeshNodeArray::write: missing patches!" << std::endl; mg_array = mg; @@ -938,8 +925,8 @@ void SPMeshNodeArray::write( SPMeshGradient *mg ) { // deleteObject() method, which in turn calls sp_repr_unparent. Since iterators do not play // well with boost::intrusive::list (which ChildrenList derive from) we need to iterate over a // copy of the pointers to the objects. - std::vector children_pointers; - for (auto& row : mg_array->children) { + std::vector children_pointers; + for (auto &row : mg_array->children) { children_pointers.push_back(&row); } @@ -951,95 +938,81 @@ void SPMeshNodeArray::write( SPMeshGradient *mg ) { Inkscape::XML::Node *mesh = mg->getRepr(); Inkscape::XML::Node *mesh_array = mg_array->getRepr(); - SPMeshNodeArray* array = &(mg_array->array); - SPMeshPatchI patch0( &(array->nodes), 0, 0 ); - Geom::Point current_p = patch0.getPoint( 0, 0 ); // Side 0, point 0 + SPMeshNodeArray *array = &(mg_array->array); + SPMeshPatchI patch0(&(array->nodes), 0, 0); + Geom::Point current_p = patch0.getPoint(0, 0); // Side 0, point 0 - sp_repr_set_svg_double( mesh, "x", current_p[X] ); - sp_repr_set_svg_double( mesh, "y", current_p[Y] ); + sp_repr_set_svg_double(mesh, "x", current_p[X]); + sp_repr_set_svg_double(mesh, "y", current_p[Y]); - Geom::Point current_p2( mg->x.computed, mg->y.computed ); + Geom::Point current_p2(mg->x.computed, mg->y.computed); Inkscape::XML::Document *xml_doc = mesh->document(); guint rows = array->patch_rows(); - for( guint i = 0; i < rows; ++i ) { - + for (guint i = 0; i < rows; ++i) { // Write row Inkscape::XML::Node *row = xml_doc->createElement("svg:meshrow"); - mesh_array->appendChild( row ); // No attributes + mesh_array->appendChild(row); // No attributes guint columns = array->patch_columns(); - for( guint j = 0; j < columns; ++j ) { - + for (guint j = 0; j < columns; ++j) { // Write patch Inkscape::XML::Node *patch = xml_doc->createElement("svg:meshpatch"); - SPMeshPatchI patchi( &(array->nodes), i, j ); + SPMeshPatchI patchi(&(array->nodes), i, j); // Add tensor - if( patchi.tensorIsSet() ) { - + if (patchi.tensorIsSet()) { std::stringstream is; - for( guint k = 0; k < 4; ++k ) { - Geom::Point p = patchi.getTensorPoint( k ) - patchi.getPoint( k, 0 ); + for (guint k = 0; k < 4; ++k) { + Geom::Point p = patchi.getTensorPoint(k) - patchi.getPoint(k, 0); is << p[X] << "," << p[Y]; - if( k < 3 ) is << " "; + if (k < 3) + is << " "; } patch->setAttribute("tensor", is.str()); // std::cout << " SPMeshNodeArray::write: tensor: " << is.str() << std::endl; } - row->appendChild( patch ); + row->appendChild(patch); // Write sides - for( guint k = 0; k < 4; ++k ) { - + for (guint k = 0; k < 4; ++k) { // Only first row has top stop - if( k == 0 && i != 0 ) continue; + if (k == 0 && i != 0) + continue; // Only first column has left stop - if( k == 3 && j != 0 ) continue; + if (k == 3 && j != 0) + continue; Inkscape::XML::Node *stop = xml_doc->createElement("svg:stop"); // Add path std::stringstream is; - char path_type = patchi.getPathType( k ); + char path_type = patchi.getPathType(k); is << path_type; - std::vector< Geom::Point> p = patchi.getPointsForSide( k ); - current_p = patchi.getPoint( k, 0 ); + std::vector p = patchi.getPointsForSide(k); + current_p = patchi.getPoint(k, 0); - switch ( path_type ) { + switch (path_type) { case 'l': - is << " " - << ( p[3][X] - current_p[X] ) << "," - << ( p[3][Y] - current_p[Y] ); + is << " " << (p[3][X] - current_p[X]) << "," << (p[3][Y] - current_p[Y]); break; case 'L': - is << " " - << p[3][X] << "," - << p[3][Y]; + is << " " << p[3][X] << "," << p[3][Y]; break; case 'c': - is << " " - << ( p[1][X] - current_p[X] ) << "," - << ( p[1][Y] - current_p[Y] ) << " " - << ( p[2][X] - current_p[X] ) << "," - << ( p[2][Y] - current_p[Y] ) << " " - << ( p[3][X] - current_p[X] ) << "," - << ( p[3][Y] - current_p[Y] ); + is << " " << (p[1][X] - current_p[X]) << "," << (p[1][Y] - current_p[Y]) << " " + << (p[2][X] - current_p[X]) << "," << (p[2][Y] - current_p[Y]) << " " + << (p[3][X] - current_p[X]) << "," << (p[3][Y] - current_p[Y]); break; case 'C': - is << " " - << p[1][X] << "," - << p[1][Y] << " " - << p[2][X] << "," - << p[2][Y] << " " - << p[3][X] << "," - << p[3][Y]; + is << " " << p[1][X] << "," << p[1][Y] << " " << p[2][X] << "," << p[2][Y] << " " << p[3][X] + << "," << p[3][Y]; break; case 'z': case 'Z': @@ -1051,20 +1024,16 @@ void SPMeshNodeArray::write( SPMeshGradient *mg ) { stop->setAttribute("path", is.str()); // std::cout << "SPMeshNodeArray::write: path: " << is.str().c_str() << std::endl; // Add stop-color - if( ( k == 0 && i == 0 && j == 0 ) || - ( k == 1 && i == 0 ) || - ( k == 2 ) || - ( k == 3 && j == 0 ) ) { - + if ((k == 0 && i == 0 && j == 0) || (k == 1 && i == 0) || (k == 2) || (k == 3 && j == 0)) { // Why are we setting attribute and not style? - //stop->setAttribute("stop-color", patchi.getColor(k).toString() ); - //stop->setAttribute("stop-opacity", patchi.getOpacity(k) ); + // stop->setAttribute("stop-color", patchi.getColor(k).toString() ); + // stop->setAttribute("stop-opacity", patchi.getOpacity(k) ); Inkscape::CSSOStringStream os; os << "stop-color:" << patchi.getColor(k).toString() << ";stop-opacity:" << patchi.getOpacity(k); stop->setAttribute("style", os.str()); } - patch->appendChild( stop ); + patch->appendChild(stop); } } } @@ -1073,19 +1042,19 @@ void SPMeshNodeArray::write( SPMeshGradient *mg ) { /** * Find default color based on colors in existing fill. */ -static SPColor default_color( SPItem *item ) { - - SPColor color( 0.5, 0.0, 0.5 ); +static SPColor default_color(SPItem *item) +{ + SPColor color(0.5, 0.0, 0.5); - if ( item->style ) { - SPIPaint const &paint = ( item->style->fill ); // Could pick between style.fill/style.stroke - if ( paint.isColor() ) { + if (item->style) { + SPIPaint const &paint = (item->style->fill); // Could pick between style.fill/style.stroke + if (paint.isColor()) { color = paint.value.color; - } else if ( paint.isPaintserver() ) { + } else if (paint.isPaintserver()) { SPObject const *server = item->style->getFillPaintServer(); - if ( SP_IS_GRADIENT(server) && SP_GRADIENT(server)->getVector() ) { + if (SP_IS_GRADIENT(server) && SP_GRADIENT(server)->getVector()) { SPStop *firstStop = SP_GRADIENT(server)->getVector()->getFirstStop(); - if ( firstStop ) { + if (firstStop) { color = firstStop->getColor(); } } @@ -1100,16 +1069,16 @@ static SPColor default_color( SPItem *item ) { /** Create a default mesh. */ -void SPMeshNodeArray::create( SPMeshGradient *mg, SPItem *item, Geom::OptRect bbox ) { - +void SPMeshNodeArray::create(SPMeshGradient *mg, SPItem *item, Geom::OptRect bbox) +{ // std::cout << "SPMeshNodeArray::create: Entrance" << std::endl; - if( !bbox ) { + if (!bbox) { // Set default size to bounding box if size not given. std::cerr << "SPMeshNodeArray::create(): bbox empty" << std::endl; bbox = item->geometricBounds(); - if( !bbox ) { + if (!bbox) { std::cerr << "SPMeshNodeArray::create: ERROR: No bounding box!" << std::endl; return; } @@ -1117,7 +1086,7 @@ void SPMeshNodeArray::create( SPMeshGradient *mg, SPItem *item, Geom::OptRect bb Geom::Coord const width = bbox->dimensions()[Geom::X]; Geom::Coord const height = bbox->dimensions()[Geom::Y]; - Geom::Point center = bbox->midpoint(); + Geom::Point center = bbox->midpoint(); // Must keep repr and array in sync. We have two choices: // Build the repr first and then "read" it. @@ -1125,24 +1094,25 @@ void SPMeshNodeArray::create( SPMeshGradient *mg, SPItem *item, Geom::OptRect bb // We'll do the second. // Remove any existing mesh. We could choose to simply scale an existing mesh... - //clear(); + // clear(); // We get called twice when a new mesh is created...WHY? // return if we've already constructed the mesh. - if( !nodes.empty() ) return; + if (!nodes.empty()) + return; // Set 'gradientUnits'. Our calculations assume "userSpaceOnUse". Inkscape::XML::Node *repr = mg->getRepr(); repr->setAttribute("gradientUnits", "userSpaceOnUse"); // Get default color - SPColor color = default_color( item ); + SPColor color = default_color(item); // Set some corners to white so we can see the mesh. - SPColor white( 1.0, 1.0, 1.0 ); + SPColor white(1.0, 1.0, 1.0); if (color == white) { // If default color is white, set other color to black. - white = SPColor( 0.0, 0.0, 0.0 ); + white = SPColor(0.0, 0.0, 0.0); } // Get preferences @@ -1150,40 +1120,38 @@ void SPMeshNodeArray::create( SPMeshGradient *mg, SPItem *item, Geom::OptRect bb guint prows = prefs->getInt("/tools/mesh/mesh_rows", 1); guint pcols = prefs->getInt("/tools/mesh/mesh_cols", 1); - SPMeshGeometry mesh_type = - (SPMeshGeometry) prefs->getInt("/tools/mesh/mesh_geometry", SP_MESH_GEOMETRY_NORMAL); - - if( mesh_type == SP_MESH_GEOMETRY_CONICAL ) { + SPMeshGeometry mesh_type = (SPMeshGeometry)prefs->getInt("/tools/mesh/mesh_geometry", SP_MESH_GEOMETRY_NORMAL); + if (mesh_type == SP_MESH_GEOMETRY_CONICAL) { // Conical gradient.. for any shape/path using geometric bounding box. - gdouble rx = width/2.0; - gdouble ry = height/2.0; + gdouble rx = width / 2.0; + gdouble ry = height / 2.0; // Start and end angles gdouble start = 0.0; - gdouble end = 2.0 * M_PI; + gdouble end = 2.0 * M_PI; - if ( SP_IS_STAR( item ) ) { + if (SP_IS_STAR(item)) { // But if it is a star... use star parameters! - SPStar* star = SP_STAR( item ); + SPStar *star = SP_STAR(item); center = star->center; rx = star->r[0]; ry = star->r[0]; start = star->arg[0]; - end = start + 2.0 * M_PI; + end = start + 2.0 * M_PI; } - if ( SP_IS_GENERICELLIPSE( item ) ) { + if (SP_IS_GENERICELLIPSE(item)) { // For arcs use set start/stop - SPGenericEllipse* arc = SP_GENERICELLIPSE( item ); + SPGenericEllipse *arc = SP_GENERICELLIPSE(item); center[Geom::X] = arc->cx.computed; center[Geom::Y] = arc->cy.computed; rx = arc->rx.computed; ry = arc->ry.computed; start = arc->start; - end = arc->end; - if( end <= start ) { + end = arc->end; + if (end <= start) { end += 2.0 * M_PI; } } @@ -1191,25 +1159,25 @@ void SPMeshNodeArray::create( SPMeshGradient *mg, SPItem *item, Geom::OptRect bb // std::cout << " start: " << start << " end: " << end << std::endl; // IS THIS NECESSARY? - sp_repr_set_svg_double( repr, "x", center[Geom::X] + rx * cos(start) ); - sp_repr_set_svg_double( repr, "y", center[Geom::Y] + ry * sin(start) ); + sp_repr_set_svg_double(repr, "x", center[Geom::X] + rx * cos(start)); + sp_repr_set_svg_double(repr, "y", center[Geom::Y] + ry * sin(start)); guint sections = pcols; // If less sections, arc approximation error too great. (Check!) - if( sections < 4 ) sections = 4; + if (sections < 4) + sections = 4; double arc = (end - start) / (double)sections; // See: http://en.wikipedia.org/wiki/B%C3%A9zier_curve - gdouble kappa = 4.0/3.0 * tan(arc/4.0); + gdouble kappa = 4.0 / 3.0 * tan(arc / 4.0); gdouble lenx = rx * kappa; gdouble leny = ry * kappa; gdouble s = start; - for( guint i = 0; i < sections; ++i ) { - - SPMeshPatchI patch( &nodes, 0, i ); + for (guint i = 0; i < sections; ++i) { + SPMeshPatchI patch(&nodes, 0, i); gdouble x0 = center[Geom::X] + rx * cos(s); gdouble y0 = center[Geom::Y] + ry * sin(s); @@ -1222,53 +1190,49 @@ void SPMeshNodeArray::create( SPMeshGradient *mg, SPItem *item, Geom::OptRect bb gdouble x2 = x3 + lenx * sin(s); gdouble y2 = y3 - leny * cos(s); - patch.setPoint( 0, 0, Geom::Point( x0, y0 ) ); - patch.setPoint( 0, 1, Geom::Point( x1, y1 ) ); - patch.setPoint( 0, 2, Geom::Point( x2, y2 ) ); - patch.setPoint( 0, 3, Geom::Point( x3, y3 ) ); + patch.setPoint(0, 0, Geom::Point(x0, y0)); + patch.setPoint(0, 1, Geom::Point(x1, y1)); + patch.setPoint(0, 2, Geom::Point(x2, y2)); + patch.setPoint(0, 3, Geom::Point(x3, y3)); - patch.setPoint( 2, 0, center ); - patch.setPoint( 3, 0, center ); + patch.setPoint(2, 0, center); + patch.setPoint(3, 0, center); - for( guint k = 0; k < 4; ++k ) { - patch.setPathType( k, 'l' ); - patch.setColor( k, (i+k)%2 ? color : white ); - patch.setOpacity( k, 1.0 ); + for (guint k = 0; k < 4; ++k) { + patch.setPathType(k, 'l'); + patch.setColor(k, (i + k) % 2 ? color : white); + patch.setOpacity(k, 1.0); } - patch.setPathType( 0, 'c' ); + patch.setPathType(0, 'c'); // Set handle and tensor nodes. patch.updateNodes(); - } - split_row( 0, prows ); + split_row(0, prows); } else { - // Normal grid meshes - if( SP_IS_GENERICELLIPSE( item ) ) { - + if (SP_IS_GENERICELLIPSE(item)) { // std::cout << "We've got ourselves an arc!" << std::endl; - SPGenericEllipse* arc = SP_GENERICELLIPSE( item ); + SPGenericEllipse *arc = SP_GENERICELLIPSE(item); center[Geom::X] = arc->cx.computed; center[Geom::Y] = arc->cy.computed; gdouble rx = arc->rx.computed; gdouble ry = arc->ry.computed; - gdouble s = -3.0/2.0 * M_PI_2; - - sp_repr_set_svg_double( repr, "x", center[Geom::X] + rx * cos(s) ); - sp_repr_set_svg_double( repr, "y", center[Geom::Y] + ry * sin(s) ); + gdouble s = -3.0 / 2.0 * M_PI_2; - gdouble lenx = rx * 4*tan(M_PI_2/4)/3; - gdouble leny = ry * 4*tan(M_PI_2/4)/3; + sp_repr_set_svg_double(repr, "x", center[Geom::X] + rx * cos(s)); + sp_repr_set_svg_double(repr, "y", center[Geom::Y] + ry * sin(s)); - SPMeshPatchI patch( &nodes, 0, 0 ); - for( guint i = 0; i < 4; ++i ) { + gdouble lenx = rx * 4 * tan(M_PI_2 / 4) / 3; + gdouble leny = ry * 4 * tan(M_PI_2 / 4) / 3; + SPMeshPatchI patch(&nodes, 0, 0); + for (guint i = 0; i < 4; ++i) { gdouble x0 = center[Geom::X] + rx * cos(s); gdouble y0 = center[Geom::Y] + ry * sin(s); gdouble x1 = x0 + lenx * cos(s + M_PI_2); @@ -1280,105 +1244,101 @@ void SPMeshNodeArray::create( SPMeshGradient *mg, SPItem *item, Geom::OptRect bb gdouble x2 = x3 + lenx * cos(s - M_PI_2); gdouble y2 = y3 + leny * sin(s - M_PI_2); - Geom::Point p1( x1, y1 ); - Geom::Point p2( x2, y2 ); - Geom::Point p3( x3, y3 ); - patch.setPoint( i, 1, p1 ); - patch.setPoint( i, 2, p2 ); - patch.setPoint( i, 3, p3 ); + Geom::Point p1(x1, y1); + Geom::Point p2(x2, y2); + Geom::Point p3(x3, y3); + patch.setPoint(i, 1, p1); + patch.setPoint(i, 2, p2); + patch.setPoint(i, 3, p3); - patch.setPathType( i, 'c' ); + patch.setPathType(i, 'c'); - patch.setColor( i, i%2 ? color : white ); - patch.setOpacity( i, 1.0 ); + patch.setColor(i, i % 2 ? color : white); + patch.setOpacity(i, 1.0); } // Fill out tensor points patch.updateNodes(); - split_row( 0, prows ); - split_column( 0, pcols ); + split_row(0, prows); + split_column(0, pcols); // END Arc - } else if ( SP_IS_STAR( item ) ) { - + } else if (SP_IS_STAR(item)) { // Do simplest thing... assume star is not rounded or randomized. // (It should be easy to handle the rounded/randomized cases by making // the appropriate star class function public.) - SPStar* star = SP_STAR( item ); - guint sides = star->sides; + SPStar *star = SP_STAR(item); + guint sides = star->sides; // std::cout << "We've got ourselves an star! Sides: " << sides << std::endl; - Geom::Point p0 = sp_star_get_xy( star, SP_STAR_POINT_KNOT1, 0 ); - sp_repr_set_svg_double( repr, "x", p0[Geom::X] ); - sp_repr_set_svg_double( repr, "y", p0[Geom::Y] ); - - for( guint i = 0; i < sides; ++i ) { - - if( star->flatsided ) { - - SPMeshPatchI patch( &nodes, 0, i ); - - patch.setPoint( 0, 0, sp_star_get_xy( star, SP_STAR_POINT_KNOT1, i ) ); - guint ii = i+1; - if( ii == sides ) ii = 0; - patch.setPoint( 1, 0, sp_star_get_xy( star, SP_STAR_POINT_KNOT1, ii ) ); - patch.setPoint( 2, 0, star->center ); - patch.setPoint( 3, 0, star->center ); - - for( guint s = 0; s < 4; ++s ) { - patch.setPathType( s, 'l' ); - patch.setColor( s, (i+s)%2 ? color : white ); - patch.setOpacity( s, 1.0 ); + Geom::Point p0 = sp_star_get_xy(star, SP_STAR_POINT_KNOT1, 0); + sp_repr_set_svg_double(repr, "x", p0[Geom::X]); + sp_repr_set_svg_double(repr, "y", p0[Geom::Y]); + + for (guint i = 0; i < sides; ++i) { + if (star->flatsided) { + SPMeshPatchI patch(&nodes, 0, i); + + patch.setPoint(0, 0, sp_star_get_xy(star, SP_STAR_POINT_KNOT1, i)); + guint ii = i + 1; + if (ii == sides) + ii = 0; + patch.setPoint(1, 0, sp_star_get_xy(star, SP_STAR_POINT_KNOT1, ii)); + patch.setPoint(2, 0, star->center); + patch.setPoint(3, 0, star->center); + + for (guint s = 0; s < 4; ++s) { + patch.setPathType(s, 'l'); + patch.setColor(s, (i + s) % 2 ? color : white); + patch.setOpacity(s, 1.0); } // Set handle and tensor nodes. patch.updateNodes(); } else { - - SPMeshPatchI patch0( &nodes, 0, 2*i ); - - patch0.setPoint( 0, 0, sp_star_get_xy( star, SP_STAR_POINT_KNOT1, i ) ); - patch0.setPoint( 1, 0, sp_star_get_xy( star, SP_STAR_POINT_KNOT2, i ) ); - patch0.setPoint( 2, 0, star->center ); - patch0.setPoint( 3, 0, star->center ); - - guint ii = i+1; - if( ii == sides ) ii = 0; - - SPMeshPatchI patch1( &nodes, 0, 2*i+1 ); - - patch1.setPoint( 0, 0, sp_star_get_xy( star, SP_STAR_POINT_KNOT2, i ) ); - patch1.setPoint( 1, 0, sp_star_get_xy( star, SP_STAR_POINT_KNOT1, ii ) ); - patch1.setPoint( 2, 0, star->center ); - patch1.setPoint( 3, 0, star->center ); - - for( guint s = 0; s < 4; ++s ) { - patch0.setPathType( s, 'l' ); - patch0.setColor( s, s%2 ? color : white ); - patch0.setOpacity( s, 1.0 ); - patch1.setPathType( s, 'l' ); - patch1.setColor( s, s%2 ? white : color ); - patch1.setOpacity( s, 1.0 ); + SPMeshPatchI patch0(&nodes, 0, 2 * i); + + patch0.setPoint(0, 0, sp_star_get_xy(star, SP_STAR_POINT_KNOT1, i)); + patch0.setPoint(1, 0, sp_star_get_xy(star, SP_STAR_POINT_KNOT2, i)); + patch0.setPoint(2, 0, star->center); + patch0.setPoint(3, 0, star->center); + + guint ii = i + 1; + if (ii == sides) + ii = 0; + + SPMeshPatchI patch1(&nodes, 0, 2 * i + 1); + + patch1.setPoint(0, 0, sp_star_get_xy(star, SP_STAR_POINT_KNOT2, i)); + patch1.setPoint(1, 0, sp_star_get_xy(star, SP_STAR_POINT_KNOT1, ii)); + patch1.setPoint(2, 0, star->center); + patch1.setPoint(3, 0, star->center); + + for (guint s = 0; s < 4; ++s) { + patch0.setPathType(s, 'l'); + patch0.setColor(s, s % 2 ? color : white); + patch0.setOpacity(s, 1.0); + patch1.setPathType(s, 'l'); + patch1.setColor(s, s % 2 ? white : color); + patch1.setOpacity(s, 1.0); } // Set handle and tensor nodes. patch0.updateNodes(); patch1.updateNodes(); - } } - - //print(); - split_row( 0, prows ); - //split_column( 0, pcols ); + // print(); - } else { + split_row(0, prows); + // split_column( 0, pcols ); + } else { // Generic sp_repr_set_svg_double(repr, "x", bbox->min()[Geom::X]); @@ -1388,30 +1348,33 @@ void SPMeshNodeArray::create( SPMeshGradient *mg, SPItem *item, Geom::OptRect bb guint nrows = prows * 3 + 1; guint ncols = pcols * 3 + 1; - gdouble dx = width / (gdouble)(ncols-1.0); - gdouble dy = height / (gdouble)(nrows-1.0); + gdouble dx = width / (gdouble)(ncols - 1.0); + gdouble dy = height / (gdouble)(nrows - 1.0); - Geom::Point p0( mg->x.computed, mg->y.computed ); + Geom::Point p0(mg->x.computed, mg->y.computed); - for( guint i = 0; i < nrows; ++i ) { - std::vector< SPMeshNode* > row; - for( guint j = 0; j < ncols; ++j ) { - SPMeshNode* node = new SPMeshNode; - node->p = p0 + Geom::Point( j * dx, i * dy ); + for (guint i = 0; i < nrows; ++i) { + std::vector row; + for (guint j = 0; j < ncols; ++j) { + SPMeshNode *node = new SPMeshNode; + node->p = p0 + Geom::Point(j * dx, i * dy); node->node_edge = MG_NODE_EDGE_NONE; - if( i == 0 ) node->node_edge |= MG_NODE_EDGE_TOP; - if( i == nrows -1 ) node->node_edge |= MG_NODE_EDGE_BOTTOM; - if( j == 0 ) node->node_edge |= MG_NODE_EDGE_LEFT; - if( j == ncols -1 ) node->node_edge |= MG_NODE_EDGE_RIGHT; - - if( i%3 == 0 ) { - - if( j%3 == 0) { + if (i == 0) + node->node_edge |= MG_NODE_EDGE_TOP; + if (i == nrows - 1) + node->node_edge |= MG_NODE_EDGE_BOTTOM; + if (j == 0) + node->node_edge |= MG_NODE_EDGE_LEFT; + if (j == ncols - 1) + node->node_edge |= MG_NODE_EDGE_RIGHT; + + if (i % 3 == 0) { + if (j % 3 == 0) { // Corner node->node_type = MG_NODE_TYPE_CORNER; node->set = true; - node->color = (i+j)%2 ? color : white; + node->color = (i + j) % 2 ? color : white; node->opacity = 1.0; } else { @@ -1422,8 +1385,7 @@ void SPMeshNodeArray::create( SPMeshGradient *mg, SPItem *item, Geom::OptRect bb } } else { - - if( j%3 == 0) { + if (j % 3 == 0) { // Side node->node_type = MG_NODE_TYPE_HANDLE; node->set = true; @@ -1433,33 +1395,31 @@ void SPMeshNodeArray::create( SPMeshGradient *mg, SPItem *item, Geom::OptRect bb node->node_type = MG_NODE_TYPE_TENSOR; node->set = false; } - } - row.push_back( node ); + row.push_back(node); } - nodes.push_back( row ); + nodes.push_back(row); } // End normal } } // If conical - //print(); + // print(); // Write repr - write( mg ); + write(mg); } - /** Clear mesh gradient. */ -void SPMeshNodeArray::clear() { - - for(auto & node : nodes) { - for(auto & j : node) { - if( j ) { +void SPMeshNodeArray::clear() +{ + for (auto &node : nodes) { + for (auto &j : node) { + if (j) { delete j; } } @@ -1467,33 +1427,27 @@ void SPMeshNodeArray::clear() { nodes.clear(); }; - /** Print mesh gradient (for debugging). */ -void SPMeshNodeArray::print() { - for( guint i = 0; i < nodes.size(); ++i ) { +void SPMeshNodeArray::print() +{ + for (guint i = 0; i < nodes.size(); ++i) { std::cout << "New node row:" << std::endl; - for( guint j = 0; j < nodes[i].size(); ++j ) { - if( nodes[i][j] ) { + for (guint j = 0; j < nodes[i].size(); ++j) { + if (nodes[i][j]) { std::cout.width(4); - std::cout << " Node: " << i << "," << j << ": " - << nodes[i][j]->p - << " Node type: " << nodes[i][j]->node_type - << " Node edge: " << nodes[i][j]->node_edge - << " Set: " << nodes[i][j]->set - << " Path type: " << nodes[i][j]->path_type - << " Stop: " << nodes[i][j]->stop - << std::endl; + std::cout << " Node: " << i << "," << j << ": " << nodes[i][j]->p + << " Node type: " << nodes[i][j]->node_type << " Node edge: " << nodes[i][j]->node_edge + << " Set: " << nodes[i][j]->set << " Path type: " << nodes[i][j]->path_type + << " Stop: " << nodes[i][j]->stop << std::endl; } else { std::cout << "Error: missing mesh node." << std::endl; } } // Loop over patches - } // Loop over rows + } // Loop over rows }; - - /* double hermite( const double p0, const double p1, const double m0, const double m1, const double t ) { double t2 = t*t; @@ -1508,42 +1462,41 @@ double hermite( const double p0, const double p1, const double m0, const double } */ -class SPMeshSmoothCorner { - +class SPMeshSmoothCorner +{ public: - SPMeshSmoothCorner() { - for(auto & i : g) { - for( unsigned j = 0; j < 4; ++j ) { + SPMeshSmoothCorner() + { + for (auto &i : g) { + for (unsigned j = 0; j < 4; ++j) { i[j] = 0; } } } - + double g[3][8]; // 3 colors, 8 parameters: see enum. Geom::Point p; // Location of point }; // Find slope at point 1 given values at previous and next points // Return value is slope in user space -double find_slope1( const double &p0, const double &p1, const double &p2, - const double &d01, const double &d12 ) { - +double find_slope1(const double &p0, const double &p1, const double &p2, const double &d01, const double &d12) +{ double slope = 0; - if( d01 > 0 && d12 > 0 ) { - slope = 0.5 * ( (p1 - p0)/d01 + (p2 - p1)/d12 ); + if (d01 > 0 && d12 > 0) { + slope = 0.5 * ((p1 - p0) / d01 + (p2 - p1) / d12); - if( ( p0 > p1 && p1 < p2 ) || - ( p0 < p1 && p1 > p2 ) ) { + if ((p0 > p1 && p1 < p2) || (p0 < p1 && p1 > p2)) { // At minimum or maximum, use slope of zero slope = 0; } else { // Ensure we don't overshoot - if( fabs(slope) > fabs(3*(p1-p0)/d01) ) { - slope = 3*(p1-p0)/d01; + if (fabs(slope) > fabs(3 * (p1 - p0) / d01)) { + slope = 3 * (p1 - p0) / d01; } - if( fabs(slope) > fabs(3*(p2-p1)/d12) ) { - slope = 3*(p2-p1)/d12; + if (fabs(slope) > fabs(3 * (p2 - p1) / d12)) { + slope = 3 * (p2 - p1) / d12; } } } else { @@ -1552,7 +1505,6 @@ double find_slope1( const double &p0, const double &p1, const double &p2, return slope; }; - /* // Find slope at point 0 given values at previous and next points // TO DO: TAKE DISTANCE BETWEEN POINTS INTO ACCOUNT @@ -1584,110 +1536,108 @@ double find_slope2( double pmm, double ppm, double pmp, double ppp, double p0 ) */ // https://en.wikipedia.org/wiki/Bicubic_interpolation -void invert( const double v[16], double alpha[16] ) { - - const double A[16][16] = { - - { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, - { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, - {-3, 3, 0, 0, -2,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, - { 2,-2, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, - { 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, - { 0, 0, 0, 0, 0, 0, 0, 0, -3, 3, 0, 0, -2,-1, 0, 0 }, - { 0, 0, 0, 0, 0, 0, 0, 0, 2,-2, 0, 0, 1, 1, 0, 0 }, - {-3, 0, 3, 0, 0, 0, 0, 0, -2, 0,-1, 0, 0, 0, 0, 0 }, - { 0, 0, 0, 0, -3, 0, 3, 0, 0, 0, 0, 0, -2, 0,-1, 0 }, - { 9,-9,-9, 9, 6, 3,-6,-3, 6,-6, 3,-3, 4, 2, 2, 1 }, - {-6, 6, 6,-6, -3,-3, 3, 3, -4, 4,-2, 2, -2,-2,-1,-1 }, - { 2, 0,-2, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0 }, - { 0, 0, 0, 0, 2, 0,-2, 0, 0, 0, 0, 0, 1, 0, 1, 0 }, - {-6, 6, 6,-6, -4,-2, 4, 2, -3, 3,-3, 3, -2,-1,-2,-1 }, - { 4,-4,-4, 4, 2, 2,-2,-2, 2,-2, 2,-2, 1, 1, 1, 1 } - }; - - for( unsigned i = 0; i < 16; ++i ) { +void invert(const double v[16], double alpha[16]) +{ + const double A[16][16] = { + + {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {-3, 3, 0, 0, -2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {2, -2, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, -3, 3, 0, 0, -2, -1, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 2, -2, 0, 0, 1, 1, 0, 0}, + {-3, 0, 3, 0, 0, 0, 0, 0, -2, 0, -1, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, -3, 0, 3, 0, 0, 0, 0, 0, -2, 0, -1, 0}, + {9, -9, -9, 9, 6, 3, -6, -3, 6, -6, 3, -3, 4, 2, 2, 1}, + {-6, 6, 6, -6, -3, -3, 3, 3, -4, 4, -2, 2, -2, -2, -1, -1}, + {2, 0, -2, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 2, 0, -2, 0, 0, 0, 0, 0, 1, 0, 1, 0}, + {-6, 6, 6, -6, -4, -2, 4, 2, -3, 3, -3, 3, -2, -1, -2, -1}, + {4, -4, -4, 4, 2, 2, -2, -2, 2, -2, 2, -2, 1, 1, 1, 1}}; + + for (unsigned i = 0; i < 16; ++i) { alpha[i] = 0; - for( unsigned j = 0; j < 16; ++j ) { - alpha[i] += A[i][j]*v[j]; + for (unsigned j = 0; j < 16; ++j) { + alpha[i] += A[i][j] * v[j]; } } } -double sum( const double alpha[16], const double& x, const double& y ) { - +double sum(const double alpha[16], const double &x, const double &y) +{ double result = 0; - - double xx = x*x; + + double xx = x * x; double xxx = xx * x; - double yy = y*y; + double yy = y * y; double yyy = yy * y; - result += alpha[ 0 ]; - result += alpha[ 1 ] * x; - result += alpha[ 2 ] * xx; - result += alpha[ 3 ] * xxx; - result += alpha[ 4 ] * y; - result += alpha[ 5 ] * y * x; - result += alpha[ 6 ] * y * xx; - result += alpha[ 7 ] * y * xxx; - result += alpha[ 8 ] * yy; - result += alpha[ 9 ] * yy * x; - result += alpha[ 10 ] * yy * xx; - result += alpha[ 11 ] * yy * xxx; - result += alpha[ 12 ] * yyy; - result += alpha[ 13 ] * yyy * x; - result += alpha[ 14 ] * yyy * xx; - result += alpha[ 15 ] * yyy * xxx; - + result += alpha[0]; + result += alpha[1] * x; + result += alpha[2] * xx; + result += alpha[3] * xxx; + result += alpha[4] * y; + result += alpha[5] * y * x; + result += alpha[6] * y * xx; + result += alpha[7] * y * xxx; + result += alpha[8] * yy; + result += alpha[9] * yy * x; + result += alpha[10] * yy * xx; + result += alpha[11] * yy * xxx; + result += alpha[12] * yyy; + result += alpha[13] * yyy * x; + result += alpha[14] * yyy * xx; + result += alpha[15] * yyy * xxx; + return result; } /** Fill 'smooth' with a smoothed version of the array by subdividing each patch into smaller patches. */ -void SPMeshNodeArray::bicubic( SPMeshNodeArray* smooth, SPMeshType type ) { - - - *smooth = *this; // Deep copy via copy assignment constructor, smooth cleared before copy +void SPMeshNodeArray::bicubic(SPMeshNodeArray *smooth, SPMeshType type) +{ + *smooth = *this; // Deep copy via copy assignment constructor, smooth cleared before copy // std::cout << "SPMeshNodeArray::smooth2(): " << this->patch_rows() << " " << smooth->patch_columns() << std::endl; // std::cout << " " << smooth << " " << this << std::endl; // Find derivatives at corners // Create array of corner points - std::vector< std::vector > d; - d.resize( smooth->patch_rows() + 1 ); - for( unsigned i = 0; i < d.size(); ++i ) { - d[i].resize( smooth->patch_columns() + 1 ); - for( unsigned j = 0; j < d[i].size(); ++j ) { + std::vector> d; + d.resize(smooth->patch_rows() + 1); + for (unsigned i = 0; i < d.size(); ++i) { + d[i].resize(smooth->patch_columns() + 1); + for (unsigned j = 0; j < d[i].size(); ++j) { float rgb_color[3]; - this->nodes[ i*3 ][ j*3 ]->color.get_rgb_floatv(rgb_color); - d[i][j].g[0][0] = rgb_color[ 0 ]; - d[i][j].g[1][0] = rgb_color[ 1 ]; - d[i][j].g[2][0] = rgb_color[ 2 ]; - d[i][j].p = this->nodes[ i*3 ][ j*3 ]->p; + this->nodes[i * 3][j * 3]->color.get_rgb_floatv(rgb_color); + d[i][j].g[0][0] = rgb_color[0]; + d[i][j].g[1][0] = rgb_color[1]; + d[i][j].g[2][0] = rgb_color[2]; + d[i][j].p = this->nodes[i * 3][j * 3]->p; } } // Calculate interior derivatives - for( unsigned i = 0; i < d.size(); ++i ) { - for( unsigned j = 0; j < d[i].size(); ++j ) { - for( unsigned k = 0; k < 3; ++k ) { // Loop over colors + for (unsigned i = 0; i < d.size(); ++i) { + for (unsigned j = 0; j < d[i].size(); ++j) { + for (unsigned k = 0; k < 3; ++k) { // Loop over colors // dx - if( i != 0 && i != d.size()-1 ) { - double lm = Geom::distance( d[i-1][j].p, d[i][j].p ); - double lp = Geom::distance( d[i+1][j].p, d[i][j].p ); - d[i][j].g[k][1] = find_slope1( d[i-1][j].g[k][0], d[i][j].g[k][0], d[i+1][j].g[k][0], lm, lp ); + if (i != 0 && i != d.size() - 1) { + double lm = Geom::distance(d[i - 1][j].p, d[i][j].p); + double lp = Geom::distance(d[i + 1][j].p, d[i][j].p); + d[i][j].g[k][1] = find_slope1(d[i - 1][j].g[k][0], d[i][j].g[k][0], d[i + 1][j].g[k][0], lm, lp); } // dy - if( j != 0 && j != d[i].size()-1 ) { - double lm = Geom::distance( d[i][j-1].p, d[i][j].p ); - double lp = Geom::distance( d[i][j+1].p, d[i][j].p ); - d[i][j].g[k][2] = find_slope1( d[i][j-1].g[k][0], d[i][j].g[k][0], d[i][j+1].g[k][0], lm, lp ); + if (j != 0 && j != d[i].size() - 1) { + double lm = Geom::distance(d[i][j - 1].p, d[i][j].p); + double lp = Geom::distance(d[i][j + 1].p, d[i][j].p); + d[i][j].g[k][2] = find_slope1(d[i][j - 1].g[k][0], d[i][j].g[k][0], d[i][j + 1].g[k][0], lm, lp); } // dxdy if needed, need to take lengths into account @@ -1696,50 +1646,49 @@ void SPMeshNodeArray::bicubic( SPMeshNodeArray* smooth, SPMeshType type ) { // d[i-1][j+1].g[k][0], d[i-1][j-1].g[k][0], // d[i][j].g[k][0] ); // } - } } } - + // Calculate exterior derivatives // We need to do this after calculating interior derivatives as we need to already // have the non-exterior derivative calculated for finding the parabola. - for( unsigned j = 0; j< d[0].size(); ++j ) { - for( unsigned k = 0; k < 3; ++k ) { // Loop over colors + for (unsigned j = 0; j < d[0].size(); ++j) { + for (unsigned k = 0; k < 3; ++k) { // Loop over colors // Parabolic - double d0 = Geom::distance( d[1][j].p, d[0 ][j].p ); - if( d0 > 0 ) { - d[0][j].g[k][1] = 2.0*(d[1][j].g[k][0] - d[0 ][j].g[k][0])/d0 - d[1][j].g[k][1]; + double d0 = Geom::distance(d[1][j].p, d[0][j].p); + if (d0 > 0) { + d[0][j].g[k][1] = 2.0 * (d[1][j].g[k][0] - d[0][j].g[k][0]) / d0 - d[1][j].g[k][1]; } else { d[0][j].g[k][1] = 0; } - unsigned z = d.size()-1; - double dz = Geom::distance( d[z][j].p, d[z-1][j].p ); - if( dz > 0 ) { - d[z][j].g[k][1] = 2.0*(d[z][j].g[k][0] - d[z-1][j].g[k][0])/dz - d[z-1][j].g[k][1]; + unsigned z = d.size() - 1; + double dz = Geom::distance(d[z][j].p, d[z - 1][j].p); + if (dz > 0) { + d[z][j].g[k][1] = 2.0 * (d[z][j].g[k][0] - d[z - 1][j].g[k][0]) / dz - d[z - 1][j].g[k][1]; } else { d[z][j].g[k][1] = 0; } } } - for( unsigned i = 0; i< d.size(); ++i ) { - for( unsigned k = 0; k < 3; ++k ) { // Loop over colors + for (unsigned i = 0; i < d.size(); ++i) { + for (unsigned k = 0; k < 3; ++k) { // Loop over colors // Parabolic - double d0 = Geom::distance( d[i][1].p, d[i][0 ].p ); - if( d0 > 0 ) { - d[i][0].g[k][2] = 2.0*(d[i][1].g[k][0] - d[i][0 ].g[k][0])/d0 - d[i][1].g[k][2]; + double d0 = Geom::distance(d[i][1].p, d[i][0].p); + if (d0 > 0) { + d[i][0].g[k][2] = 2.0 * (d[i][1].g[k][0] - d[i][0].g[k][0]) / d0 - d[i][1].g[k][2]; } else { d[i][0].g[k][2] = 0; } - unsigned z = d[0].size()-1; - double dz = Geom::distance( d[i][z].p, d[i][z-1].p ); - if( dz > 0 ) { - d[i][z].g[k][2] = 2.0*(d[i][z].g[k][0] - d[i][z-1].g[k][0])/dz - d[i][z-1].g[k][2]; + unsigned z = d[0].size() - 1; + double dz = Geom::distance(d[i][z].p, d[i][z - 1].p); + if (dz > 0) { + d[i][z].g[k][2] = 2.0 * (d[i][z].g[k][0] - d[i][z - 1].g[k][0]) / dz - d[i][z - 1].g[k][2]; } else { d[i][z].g[k][2] = 0; } @@ -1747,74 +1696,72 @@ void SPMeshNodeArray::bicubic( SPMeshNodeArray* smooth, SPMeshType type ) { } // Leave outside corner cross-derivatives at zero. - + // Next split each patch into 8x8 smaller patches. - + // Split each row into eight rows. - // Must do it from end so inserted rows don't mess up indexing - for( int i = smooth->patch_rows() - 1; i >= 0; --i ) { - smooth->split_row( i, unsigned(8) ); + // Must do it from end so inserted rows don't mess up indexing + for (int i = smooth->patch_rows() - 1; i >= 0; --i) { + smooth->split_row(i, unsigned(8)); } // Split each column into eight columns. - // Must do it from end so inserted columns don't mess up indexing - for( int i = smooth->patch_columns() - 1; i >= 0; --i ) { - smooth->split_column( i, (unsigned)8 ); + // Must do it from end so inserted columns don't mess up indexing + for (int i = smooth->patch_columns() - 1; i >= 0; --i) { + smooth->split_column(i, (unsigned)8); } // Fill new patches - for( unsigned i = 0; i < this->patch_rows(); ++i ) { - for( unsigned j = 0; j < this->patch_columns(); ++j ) { - - double dx0 = Geom::distance( d[i ][j ].p, d[i+1][j ].p ); - double dx1 = Geom::distance( d[i ][j+1].p, d[i+1][j+1].p ); - double dy0 = Geom::distance( d[i ][j ].p, d[i ][j+1].p ); - double dy1 = Geom::distance( d[i+1][j ].p, d[i+1][j+1].p ); + for (unsigned i = 0; i < this->patch_rows(); ++i) { + for (unsigned j = 0; j < this->patch_columns(); ++j) { + double dx0 = Geom::distance(d[i][j].p, d[i + 1][j].p); + double dx1 = Geom::distance(d[i][j + 1].p, d[i + 1][j + 1].p); + double dy0 = Geom::distance(d[i][j].p, d[i][j + 1].p); + double dy1 = Geom::distance(d[i + 1][j].p, d[i + 1][j + 1].p); // Temp loop over 0..8 to get last column/row edges float r[3][9][9]; // result - for( unsigned m = 0; m < 3; ++m ) { - + for (unsigned m = 0; m < 3; ++m) { double v[16]; - v[ 0] = d[i ][j ].g[m][0]; - v[ 1] = d[i+1][j ].g[m][0]; - v[ 2] = d[i ][j+1].g[m][0]; - v[ 3] = d[i+1][j+1].g[m][0]; - v[ 4] = d[i ][j ].g[m][1]*dx0; - v[ 5] = d[i+1][j ].g[m][1]*dx0; - v[ 6] = d[i ][j+1].g[m][1]*dx1; - v[ 7] = d[i+1][j+1].g[m][1]*dx1; - v[ 8] = d[i ][j ].g[m][2]*dy0; - v[ 9] = d[i+1][j ].g[m][2]*dy1; - v[10] = d[i ][j+1].g[m][2]*dy0; - v[11] = d[i+1][j+1].g[m][2]*dy1; - v[12] = d[i ][j ].g[m][3]; - v[13] = d[i+1][j ].g[m][3]; - v[14] = d[i ][j+1].g[m][3]; - v[15] = d[i+1][j+1].g[m][3]; + v[0] = d[i][j].g[m][0]; + v[1] = d[i + 1][j].g[m][0]; + v[2] = d[i][j + 1].g[m][0]; + v[3] = d[i + 1][j + 1].g[m][0]; + v[4] = d[i][j].g[m][1] * dx0; + v[5] = d[i + 1][j].g[m][1] * dx0; + v[6] = d[i][j + 1].g[m][1] * dx1; + v[7] = d[i + 1][j + 1].g[m][1] * dx1; + v[8] = d[i][j].g[m][2] * dy0; + v[9] = d[i + 1][j].g[m][2] * dy1; + v[10] = d[i][j + 1].g[m][2] * dy0; + v[11] = d[i + 1][j + 1].g[m][2] * dy1; + v[12] = d[i][j].g[m][3]; + v[13] = d[i + 1][j].g[m][3]; + v[14] = d[i][j + 1].g[m][3]; + v[15] = d[i + 1][j + 1].g[m][3]; double alpha[16]; - invert( v, alpha ); - - for( unsigned k = 0; k < 9; ++k ) { - for( unsigned l = 0; l < 9; ++l ) { - double x = k/8.0; - double y = l/8.0; - r[m][k][l] = sum( alpha, x, y ); + invert(v, alpha); + + for (unsigned k = 0; k < 9; ++k) { + for (unsigned l = 0; l < 9; ++l) { + double x = k / 8.0; + double y = l / 8.0; + r[m][k][l] = sum(alpha, x, y); // Clamp to allowed values - if( r[m][k][l] > 1.0 ) + if (r[m][k][l] > 1.0) r[m][k][l] = 1.0; - if( r[m][k][l] < 0.0 ) + if (r[m][k][l] < 0.0) r[m][k][l] = 0.0; } } } // Loop over colors - for( unsigned k = 0; k < 9; ++k ) { - for( unsigned l = 0; l < 9; ++l ) { + for (unsigned k = 0; k < 9; ++k) { + for (unsigned l = 0; l < 9; ++l) { // Every third node is a corner node - smooth->nodes[ (i*8+k)*3 ][(j*8+l)*3 ]->color.set( r[0][k][l], r[1][k][l], r[2][k][l] ); + smooth->nodes[(i * 8 + k) * 3][(j * 8 + l) * 3]->color.set(r[0][k][l], r[1][k][l], r[2][k][l]); } } } @@ -1824,19 +1771,20 @@ void SPMeshNodeArray::bicubic( SPMeshNodeArray* smooth, SPMeshType type ) { /** Number of patch rows. */ -guint SPMeshNodeArray::patch_rows() { - - return nodes.size()/3; +guint SPMeshNodeArray::patch_rows() +{ + return nodes.size() / 3; } /** Number of patch columns. */ -guint SPMeshNodeArray::patch_columns() { +guint SPMeshNodeArray::patch_columns() +{ if (nodes.empty()) { return 0; } - return nodes[0].size()/3; + return nodes[0].size() / 3; } /** @@ -1846,8 +1794,8 @@ guint SPMeshNodeArray::patch_columns() { true if corners adjacent. n[] is array of nodes in top/bottom or left/right order. */ -bool SPMeshNodeArray::adjacent_corners( guint i, guint j, SPMeshNode* n[4] ) { - +bool SPMeshNodeArray::adjacent_corners(guint i, guint j, SPMeshNode *n[4]) +{ // This works as all corners have indices and they // are numbered in order by row and column (and // the node array is rectangular). @@ -1856,7 +1804,7 @@ bool SPMeshNodeArray::adjacent_corners( guint i, guint j, SPMeshNode* n[4] ) { guint c1 = i; guint c2 = j; - if( j < i ) { + if (j < i) { c1 = j; c2 = i; } @@ -1869,8 +1817,8 @@ bool SPMeshNodeArray::adjacent_corners( guint i, guint j, SPMeshNode* n[4] ) { guint ccol1 = c1 % ncorners; guint ccol2 = c2 % ncorners; - guint nrow = crow1 * 3; - guint ncol = ccol1 * 3; + guint nrow = crow1 * 3; + guint ncol = ccol1 * 3; // std::cout << " i: " << i // << " j: " << j @@ -1886,18 +1834,18 @@ bool SPMeshNodeArray::adjacent_corners( guint i, guint j, SPMeshNode* n[4] ) { // << std::endl; // Check for horizontal neighbors - if ( crow1 == crow2 && (ccol2 - ccol1) == 1 ) { + if (crow1 == crow2 && (ccol2 - ccol1) == 1) { adjacent = true; - for( guint k = 0; k < 4; ++k ) { - n[k] = nodes[nrow][ncol+k]; + for (guint k = 0; k < 4; ++k) { + n[k] = nodes[nrow][ncol + k]; } } // Check for vertical neighbors - if ( ccol1 == ccol2 && (crow2 - crow1) == 1 ) { + if (ccol1 == ccol2 && (crow2 - crow1) == 1) { adjacent = true; - for( guint k = 0; k < 4; ++k ) { - n[k] = nodes[nrow+k][ncol]; + for (guint k = 0; k < 4; ++k) { + n[k] = nodes[nrow + k][ncol]; } } @@ -1908,21 +1856,19 @@ bool SPMeshNodeArray::adjacent_corners( guint i, guint j, SPMeshNode* n[4] ) { Toggle sides between lineto and curve to if both corners selected. Input is a list of selected corner draggable indices. */ -guint SPMeshNodeArray::side_toggle( std::vector corners ) { - +guint SPMeshNodeArray::side_toggle(std::vector corners) +{ guint toggled = 0; - if( corners.size() < 2 ) return 0; - - for( guint i = 0; i < corners.size()-1; ++i ) { - for( guint j = i+1; j < corners.size(); ++j ) { - - SPMeshNode* n[4]; - if( adjacent_corners( corners[i], corners[j], n ) ) { + if (corners.size() < 2) + return 0; + for (guint i = 0; i < corners.size() - 1; ++i) { + for (guint j = i + 1; j < corners.size(); ++j) { + SPMeshNode *n[4]; + if (adjacent_corners(corners[i], corners[j], n)) { gchar path_type = n[1]->path_type; - switch (path_type) - { + switch (path_type) { case 'L': n[1]->path_type = 'C'; n[2]->path_type = 'C'; @@ -1936,14 +1882,14 @@ guint SPMeshNodeArray::side_toggle( std::vector corners ) { n[1]->set = true; n[2]->set = true; break; - + case 'C': { n[1]->path_type = 'L'; n[2]->path_type = 'L'; n[1]->set = false; n[2]->set = false; // 'L' acts as if handles are 1/3 of path length from corners. - Geom::Point dp = (n[3]->p - n[0]->p)/3.0; + Geom::Point dp = (n[3]->p - n[0]->p) / 3.0; n[1]->p = n[0]->p + dp; n[2]->p = n[3]->p - dp; break; @@ -1954,7 +1900,7 @@ guint SPMeshNodeArray::side_toggle( std::vector corners ) { n[1]->set = false; n[2]->set = false; // 'l' acts as if handles are 1/3 of path length from corners. - Geom::Point dp = (n[3]->p - n[0]->p)/3.0; + Geom::Point dp = (n[3]->p - n[0]->p) / 3.0; n[1]->p = n[0]->p + dp; n[2]->p = n[3]->p - dp; // std::cout << "Toggle sides: " @@ -1972,7 +1918,8 @@ guint SPMeshNodeArray::side_toggle( std::vector corners ) { } } } - if( toggled > 0 ) built = false; + if (toggled > 0) + built = false; return toggled; } @@ -1983,20 +1930,18 @@ guint SPMeshNodeArray::side_toggle( std::vector corners ) { * parallel to the other node's handle direction. This is the section of an ellipse that * corresponds to a quarter of a circle squished and then skewed. */ -guint SPMeshNodeArray::side_arc( std::vector corners ) { - - if( corners.size() < 2 ) return 0; +guint SPMeshNodeArray::side_arc(std::vector corners) +{ + if (corners.size() < 2) + return 0; guint arced = 0; - for( guint i = 0; i < corners.size()-1; ++i ) { - for( guint j = i+1; j < corners.size(); ++j ) { - - SPMeshNode* n[4]; - if( adjacent_corners( corners[i], corners[j], n ) ) { - + for (guint i = 0; i < corners.size() - 1; ++i) { + for (guint j = i + 1; j < corners.size(); ++j) { + SPMeshNode *n[4]; + if (adjacent_corners(corners[i], corners[j], n)) { gchar path_type = n[1]->path_type; - switch (path_type) - { + switch (path_type) { case 'L': case 'l': std::cerr << "SPMeshNodeArray::side_arc: Can't convert straight lines to arcs." << std::endl; @@ -2004,31 +1949,30 @@ guint SPMeshNodeArray::side_arc( std::vector corners ) { case 'C': case 'c': { + Geom::Ray ray1(n[0]->p, n[1]->p); + Geom::Ray ray2(n[3]->p, n[2]->p); + if (!are_parallel((Geom::Line)ray1, (Geom::Line)ray2)) { + Geom::OptCrossing crossing = intersection(ray1, ray2); - Geom::Ray ray1( n[0]->p, n[1]->p ); - Geom::Ray ray2( n[3]->p, n[2]->p ); - if( !are_parallel( (Geom::Line)ray1, (Geom::Line)ray2 ) ) { + if (crossing) { + Geom::Point intersection = ray1.pointAt((*crossing).ta); - Geom::OptCrossing crossing = intersection( ray1, ray2 ); - - if( crossing ) { - - Geom::Point intersection = ray1.pointAt( (*crossing).ta ); - - const double f = 4.0/3.0 * tan( M_PI/2.0/4.0 ); + const double f = 4.0 / 3.0 * tan(M_PI / 2.0 / 4.0); Geom::Point h1 = intersection - n[0]->p; Geom::Point h2 = intersection - n[3]->p; - n[1]->p = n[0]->p + f*h1; - n[2]->p = n[3]->p + f*h2; + n[1]->p = n[0]->p + f * h1; + n[2]->p = n[3]->p + f * h2; ++arced; } else { - std::cerr << "SPMeshNodeArray::side_arc: No crossing, can't turn into arc." << std::endl; + std::cerr << "SPMeshNodeArray::side_arc: No crossing, can't turn into arc." + << std::endl; } } else { - std::cerr << "SPMeshNodeArray::side_arc: Handles parallel, can't turn into arc." << std::endl; + std::cerr << "SPMeshNodeArray::side_arc: Handles parallel, can't turn into arc." + << std::endl; } break; } @@ -2038,7 +1982,8 @@ guint SPMeshNodeArray::side_arc( std::vector corners ) { } } } - if( arced > 0 ) built = false; + if (arced > 0) + built = false; return arced; } @@ -2046,36 +1991,32 @@ guint SPMeshNodeArray::side_arc( std::vector corners ) { Toggle sides between lineto and curve to if both corners selected. Input is a list of selected corner draggable indices. */ -guint SPMeshNodeArray::tensor_toggle( std::vector corners ) { - +guint SPMeshNodeArray::tensor_toggle(std::vector corners) +{ // std::cout << "SPMeshNodeArray::tensor_toggle" << std::endl; - if( corners.size() < 4 ) return 0; + if (corners.size() < 4) + return 0; guint toggled = 0; // Number of corners in a row of patches. guint ncorners = patch_columns() + 1; - for( guint i = 0; i < corners.size()-3; ++i ) { - for( guint j = i+1; j < corners.size()-2; ++j ) { - for( guint k = j+1; k < corners.size()-1; ++k ) { - for( guint l = k+1; l < corners.size(); ++l ) { - + for (guint i = 0; i < corners.size() - 3; ++i) { + for (guint j = i + 1; j < corners.size() - 2; ++j) { + for (guint k = j + 1; k < corners.size() - 1; ++k) { + for (guint l = k + 1; l < corners.size(); ++l) { guint c[4]; c[0] = corners[i]; c[1] = corners[j]; c[2] = corners[k]; c[3] = corners[l]; - std::sort( c, c+4 ); + std::sort(c, c + 4); // Check we have four corners of one patch selected - if( c[1]-c[0] == 1 && - c[3]-c[2] == 1 && - c[2]-c[0] == ncorners && - c[3]-c[1] == ncorners && - c[0] % ncorners < ncorners - 1 ) { - + if (c[1] - c[0] == 1 && c[3] - c[2] == 1 && c[2] - c[0] == ncorners && c[3] - c[1] == ncorners && + c[0] % ncorners < ncorners - 1) { // Patch guint prow = c[0] / ncorners; guint pcol = c[0] % ncorners; @@ -2097,21 +2038,21 @@ guint SPMeshNodeArray::tensor_toggle( std::vector corners ) { // << " pcol: " << pcol // << std::endl; - SPMeshPatchI patch( &nodes, prow, pcol ); + SPMeshPatchI patch(&nodes, prow, pcol); patch.updateNodes(); - if( patch.tensorIsSet() ) { + if (patch.tensorIsSet()) { // Unset tensor points - nodes[irow+1][jcol+1]->set = false; - nodes[irow+1][jcol+2]->set = false; - nodes[irow+2][jcol+1]->set = false; - nodes[irow+2][jcol+2]->set = false; + nodes[irow + 1][jcol + 1]->set = false; + nodes[irow + 1][jcol + 2]->set = false; + nodes[irow + 2][jcol + 1]->set = false; + nodes[irow + 2][jcol + 2]->set = false; } else { // Set tensor points - nodes[irow+1][jcol+1]->set = true; - nodes[irow+1][jcol+2]->set = true; - nodes[irow+2][jcol+1]->set = true; - nodes[irow+2][jcol+2]->set = true; + nodes[irow + 1][jcol + 1]->set = true; + nodes[irow + 1][jcol + 2]->set = true; + nodes[irow + 2][jcol + 1]->set = true; + nodes[irow + 2][jcol + 2]->set = true; } ++toggled; @@ -2120,7 +2061,8 @@ guint SPMeshNodeArray::tensor_toggle( std::vector corners ) { } } } - if( toggled > 0 ) built = false; + if (toggled > 0) + built = false; return toggled; } @@ -2128,8 +2070,8 @@ guint SPMeshNodeArray::tensor_toggle( std::vector corners ) { Attempts to smooth color transitions across corners. Input is a list of selected corner draggable indices. */ -guint SPMeshNodeArray::color_smooth( std::vector corners ) { - +guint SPMeshNodeArray::color_smooth(std::vector corners) +{ // std::cout << "SPMeshNodeArray::color_smooth" << std::endl; guint smoothed = 0; @@ -2141,43 +2083,38 @@ guint SPMeshNodeArray::color_smooth( std::vector corners ) { guint ncols = patch_columns() * 3 + 1; guint nrows = patch_rows() * 3 + 1; - for(unsigned int corner : corners) { - + for (unsigned int corner : corners) { // std::cout << "SPMeshNodeArray::color_smooth: " << i << " " << corner << std::endl; // Node row & col guint nrow = (corner / ncorners) * 3; guint ncol = (corner % ncorners) * 3; - SPMeshNode* n[7]; - for( guint s = 0; s < 2; ++s ) { - + SPMeshNode *n[7]; + for (guint s = 0; s < 2; ++s) { bool smooth = false; // Find neighboring nodes - if( s == 0 ) { - + if (s == 0) { // Horizontal - if( ncol > 2 && ncol+3 < ncols) { - for( guint j = 0; j < 7; ++j ) { - n[j] = nodes[ nrow ][ ncol - 3 + j ]; + if (ncol > 2 && ncol + 3 < ncols) { + for (guint j = 0; j < 7; ++j) { + n[j] = nodes[nrow][ncol - 3 + j]; } smooth = true; } } else { - // Vertical - if( nrow > 2 && nrow+3 < nrows) { - for( guint j = 0; j < 7; ++j ) { - n[j] = nodes[ nrow - 3 + j ][ ncol ]; + if (nrow > 2 && nrow + 3 < nrows) { + for (guint j = 0; j < 7; ++j) { + n[j] = nodes[nrow - 3 + j][ncol]; } smooth = true; } } - if( smooth ) { - + if (smooth) { // Let the smoothing begin // std::cout << " checking: " << ncol << " " << nrow << std::endl; @@ -2190,25 +2127,25 @@ guint SPMeshNodeArray::color_smooth( std::vector corners ) { SPColor color0 = n[0]->color; SPColor color3 = n[3]->color; SPColor color6 = n[6]->color; - + // Distance nodes from selected corner Geom::Point d[7]; - for( guint k = 0; k < 7; ++k ) { - d[k]= n[k]->p - n[3]->p; + for (guint k = 0; k < 7; ++k) { + d[k] = n[k]->p - n[3]->p; // std::cout << " d[" << k << "]: " << d[k].length() << std::endl; } double sdm = -1.0; // Slope Diff Max - guint cdm = 0; // Color Diff Max (Which color has the maximum difference in slopes) - for( guint c = 0; c < 3; ++c ) { - if( d[2].length() != 0.0 ) { + guint cdm = 0; // Color Diff Max (Which color has the maximum difference in slopes) + for (guint c = 0; c < 3; ++c) { + if (d[2].length() != 0.0) { slope[0][c] = (color3.v.c[c] - color0.v.c[c]) / d[2].length(); - } - if( d[4].length() != 0.0 ) { + } + if (d[4].length() != 0.0) { slope[1][c] = (color6.v.c[c] - color3.v.c[c]) / d[4].length(); } - slope_ave[c] = (slope[0][c]+slope[1][c]) / 2.0; - slope_diff[c] = (slope[0][c]-slope[1][c]); + slope_ave[c] = (slope[0][c] + slope[1][c]) / 2.0; + slope_diff[c] = (slope[0][c] - slope[1][c]); // std::cout << " color: " << c << " :" // << color0.v.c[c] << " " // << color3.v.c[c] << " " @@ -2221,34 +2158,36 @@ guint SPMeshNodeArray::color_smooth( std::vector corners ) { // << std::endl; // Find color with maximum difference - if( std::abs( slope_diff[c] ) > sdm ) { - sdm = std::abs( slope_diff[c] ); + if (std::abs(slope_diff[c]) > sdm) { + sdm = std::abs(slope_diff[c]); cdm = c; } } // std::cout << " cdm: " << cdm << std::endl; // Find new handle positions: - double length_left = d[0].length(); + double length_left = d[0].length(); double length_right = d[6].length(); - if( slope_ave[ cdm ] != 0.0 ) { - length_left = std::abs( (color3.v.c[cdm] - color0.v.c[cdm]) / slope_ave[ cdm ] ); - length_right = std::abs( (color6.v.c[cdm] - color3.v.c[cdm]) / slope_ave[ cdm ] ); + if (slope_ave[cdm] != 0.0) { + length_left = std::abs((color3.v.c[cdm] - color0.v.c[cdm]) / slope_ave[cdm]); + length_right = std::abs((color6.v.c[cdm] - color3.v.c[cdm]) / slope_ave[cdm]); } // Move closest handle a maximum of mid point... but don't shorten double max = 0.8; - if( length_left > max * d[0].length() && length_left > d[2].length() ) { + if (length_left > max * d[0].length() && length_left > d[2].length()) { std::cout << " Can't smooth left side" << std::endl; - length_left = std::max( max * d[0].length(), d[2].length() ); + length_left = std::max(max * d[0].length(), d[2].length()); } - if( length_right > max * d[6].length() && length_right > d[4].length() ) { + if (length_right > max * d[6].length() && length_right > d[4].length()) { std::cout << " Can't smooth right side" << std::endl; - length_right = std::max( max * d[6].length(), d[4].length() ); + length_right = std::max(max * d[6].length(), d[4].length()); } - if( d[2].length() != 0.0 ) d[2] *= length_left/d[2].length(); - if( d[4].length() != 0.0 ) d[4] *= length_right/d[4].length(); + if (d[2].length() != 0.0) + d[2] *= length_left / d[2].length(); + if (d[4].length() != 0.0) + d[4] *= length_right / d[4].length(); // std::cout << " length_left: " << length_left // << " d[0]: " << d[0].length() @@ -2262,18 +2201,18 @@ guint SPMeshNodeArray::color_smooth( std::vector corners ) { ++smoothed; } } - } - if( smoothed > 0 ) built = false; + if (smoothed > 0) + built = false; return smoothed; } /** Pick color from background for selected corners. */ -guint SPMeshNodeArray::color_pick( std::vector icorners, SPItem* item ) { - +guint SPMeshNodeArray::color_pick(std::vector icorners, SPItem *item) +{ // std::cout << "SPMeshNodeArray::color_pick" << std::endl; guint picked = 0; @@ -2295,8 +2234,8 @@ guint SPMeshNodeArray::color_pick( std::vector icorners, SPItem* item ) { pick_doc->getRoot()->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); pick_doc->ensureUpToDate(); - //gdouble pick_zoom = 1.0; // zoom; - //pick_drawing->root()->setTransform(Geom::Scale(pick_zoom)); + // gdouble pick_zoom = 1.0; // zoom; + // pick_drawing->root()->setTransform(Geom::Scale(pick_zoom)); pick_drawing->update(); // std::cout << " transform: " << std::endl; @@ -2307,7 +2246,7 @@ guint SPMeshNodeArray::color_pick( std::vector icorners, SPItem* item ) { // std::cout << item->i2dt_affine() << std::endl; // std::cout << " dt2i: " << std::endl; // std::cout << item->dt2i_affine() << std::endl; - SPGradient* gr = SP_GRADIENT( mg ); + SPGradient *gr = SP_GRADIENT(mg); // if( gr->gradientTransform_set ) { // std::cout << " gradient transform set: " << std::endl; // std::cout << gr->gradientTransform << std::endl; @@ -2316,9 +2255,8 @@ guint SPMeshNodeArray::color_pick( std::vector icorners, SPItem* item ) { // } // Do picking - for(unsigned int corner : icorners) { - - SPMeshNode* n = corners[ corner ]; + for (unsigned int corner : icorners) { + SPMeshNode *n = corners[corner]; // Region to average over Geom::Point p = n->p; @@ -2327,40 +2265,40 @@ guint SPMeshNodeArray::color_pick( std::vector icorners, SPItem* item ) { // std::cout << " after transform: p: " << p << std::endl; p *= item->i2doc_affine(); // std::cout << " after transform: p: " << p << std::endl; - + // If on edge, move inward - guint cols = patch_columns()+1; - guint rows = patch_rows()+1; + guint cols = patch_columns() + 1; + guint rows = patch_rows() + 1; guint col = corner % cols; guint row = corner / cols; - guint ncol = col * 3; - guint nrow = row * 3; + guint ncol = col * 3; + guint nrow = row * 3; const double size = 3.0; // Top edge - if( row == 0 ) { - Geom::Point dp = nodes[nrow+1][ncol]->p - p; - p += unit_vector( dp ) * size; + if (row == 0) { + Geom::Point dp = nodes[nrow + 1][ncol]->p - p; + p += unit_vector(dp) * size; } // Right edge - if( col == cols-1 ) { - Geom::Point dp = nodes[nrow][ncol-1]->p - p; - p += unit_vector( dp ) * size; + if (col == cols - 1) { + Geom::Point dp = nodes[nrow][ncol - 1]->p - p; + p += unit_vector(dp) * size; } // Bottom edge - if( row == rows-1 ) { - Geom::Point dp = nodes[nrow-1][ncol]->p - p; - p += unit_vector( dp ) * size; + if (row == rows - 1) { + Geom::Point dp = nodes[nrow - 1][ncol]->p - p; + p += unit_vector(dp) * size; } // Left edge - if( col == 0 ) { - Geom::Point dp = nodes[nrow][ncol+1]->p - p; - p += unit_vector( dp ) * size; + if (col == 0) { + Geom::Point dp = nodes[nrow][ncol + 1]->p - p; + p += unit_vector(dp) * size; } - Geom::Rect box( p[Geom::X]-size/2.0, p[Geom::Y]-size/2.0, - p[Geom::X]+size/2.0, p[Geom::Y]+size/2.0 ); + Geom::Rect box(p[Geom::X] - size / 2.0, p[Geom::Y] - size / 2.0, p[Geom::X] + size / 2.0, + p[Geom::Y] + size / 2.0); /* Item integer bbox in points */ Geom::IntRect ibox = box.roundOutwards(); @@ -2381,14 +2319,15 @@ guint SPMeshNodeArray::color_pick( std::vector icorners, SPItem* item ) { // << " G: " << G // << " B: " << B // << std::endl; - n->color.set( R, G, B ); + n->color.set(R, G, B); } pick_doc->getRoot()->invoke_hide(pick_visionkey); delete pick_drawing; picked = 1; // Picking always happens - if( picked > 0 ) built = false; + if (picked > 0) + built = false; return picked; } @@ -2396,18 +2335,18 @@ guint SPMeshNodeArray::color_pick( std::vector icorners, SPItem* item ) { Splits selected rows and/or columns in half (according to the path 't' parameter). Input is a list of selected corner draggable indices. */ -guint SPMeshNodeArray::insert( std::vector corners ) { - +guint SPMeshNodeArray::insert(std::vector corners) +{ guint inserted = 0; - if( corners.size() < 2 ) return 0; + if (corners.size() < 2) + return 0; std::set columns; std::set rows; - for( guint i = 0; i < corners.size()-1; ++i ) { - for( guint j = i+1; j < corners.size(); ++j ) { - + for (guint i = 0; i < corners.size() - 1; ++i) { + for (guint j = i + 1; j < corners.size(); ++j) { // This works as all corners have indices and they // are numbered in order by row and column (and // the node array is rectangular). @@ -2428,29 +2367,30 @@ guint SPMeshNodeArray::insert( std::vector corners ) { guint ccol2 = c2 % ncorners; // Check for horizontal neighbors - if ( crow1 == crow2 && (ccol2 - ccol1) == 1 ) { - columns.insert( ccol1 ); + if (crow1 == crow2 && (ccol2 - ccol1) == 1) { + columns.insert(ccol1); } - + // Check for vertical neighbors - if ( ccol1 == ccol2 && (crow2 - crow1) == 1 ) { - rows.insert( crow1 ); + if (ccol1 == ccol2 && (crow2 - crow1) == 1) { + rows.insert(crow1); } } } // Iterate backwards so column/row numbers are not invalidated. std::set::reverse_iterator rit; - for (rit=columns.rbegin(); rit != columns.rend(); ++rit) { - split_column( *rit, 0.5); + for (rit = columns.rbegin(); rit != columns.rend(); ++rit) { + split_column(*rit, 0.5); ++inserted; } - for (rit=rows.rbegin(); rit != rows.rend(); ++rit) { - split_row( *rit, 0.5); + for (rit = rows.rbegin(); rit != rows.rend(); ++rit) { + split_row(*rit, 0.5); ++inserted; } - if( inserted > 0 ) built = false; + if (inserted > 0) + built = false; return inserted; } @@ -2462,7 +2402,8 @@ guint SPMeshNodeArray::insert( std::vector corners ) { op: how other corners should be moved. Corner node must already have been moved! */ -void SPMeshNodeArray::update_handles( guint corner, std::vector< guint > /*selected*/, Geom::Point p_old, MeshNodeOperation /*op*/ ) +void SPMeshNodeArray::update_handles(guint corner, std::vector /*selected*/, Geom::Point p_old, + MeshNodeOperation /*op*/) { if (!draggers_valid) { std::cerr << "SPMeshNodeArray::update_handles: Draggers not valid!" << std::endl; @@ -2487,8 +2428,8 @@ void SPMeshNodeArray::update_handles( guint corner, std::vector< guint > /*selec guint ccol = corner % ncorners; // Find node row/column - guint nrow = crow * 3; - guint ncol = ccol * 3; + guint nrow = crow * 3; + guint ncol = ccol * 3; // std::cout << " mrow: " << mrow // << " mcol: " << mcol @@ -2512,10 +2453,14 @@ void SPMeshNodeArray::update_handles( guint corner, std::vector< guint > /*selec // STEP 1: ONLY DO DIRECT MOVE bool patch[4]; patch[0] = patch[1] = patch[2] = patch[3] = false; - if( ccol > 0 && crow > 0 ) patch[0] = true; - if( ccol < mcol && crow > 0 ) patch[1] = true; - if( ccol < mcol && crow < mrow ) patch[2] = true; - if( ccol > 0 && crow < mrow ) patch[3] = true; + if (ccol > 0 && crow > 0) + patch[0] = true; + if (ccol < mcol && crow > 0) + patch[1] = true; + if (ccol < mcol && crow < mrow) + patch[2] = true; + if (ccol > 0 && crow < mrow) + patch[3] = true; // std::cout << patch[0] << " " // << patch[1] << " " @@ -2523,56 +2468,55 @@ void SPMeshNodeArray::update_handles( guint corner, std::vector< guint > /*selec // << patch[3] << std::endl; // Move handles - if( patch[0] || patch[1] ) { - if( nodes[nrow-1][ncol]->path_type == 'l' || - nodes[nrow-1][ncol]->path_type == 'L' ) { - Geom::Point s = (nodes[nrow-3][ncol]->p - nodes[nrow][ncol]->p)/3.0; - nodes[nrow-1][ncol ]->p = nodes[nrow][ncol]->p + s; - nodes[nrow-2][ncol ]->p = nodes[nrow-3][ncol]->p - s; + if (patch[0] || patch[1]) { + if (nodes[nrow - 1][ncol]->path_type == 'l' || nodes[nrow - 1][ncol]->path_type == 'L') { + Geom::Point s = (nodes[nrow - 3][ncol]->p - nodes[nrow][ncol]->p) / 3.0; + nodes[nrow - 1][ncol]->p = nodes[nrow][ncol]->p + s; + nodes[nrow - 2][ncol]->p = nodes[nrow - 3][ncol]->p - s; } else { - nodes[nrow-1][ncol ]->p += dp; + nodes[nrow - 1][ncol]->p += dp; } } - if( patch[1] || patch[2] ) { - if( nodes[nrow ][ncol+1]->path_type == 'l' || - nodes[nrow ][ncol+1]->path_type == 'L' ) { - Geom::Point s = (nodes[nrow][ncol+3]->p - nodes[nrow][ncol]->p)/3.0; - nodes[nrow ][ncol+1]->p = nodes[nrow][ncol]->p + s; - nodes[nrow ][ncol+2]->p = nodes[nrow][ncol+3]->p - s; + if (patch[1] || patch[2]) { + if (nodes[nrow][ncol + 1]->path_type == 'l' || nodes[nrow][ncol + 1]->path_type == 'L') { + Geom::Point s = (nodes[nrow][ncol + 3]->p - nodes[nrow][ncol]->p) / 3.0; + nodes[nrow][ncol + 1]->p = nodes[nrow][ncol]->p + s; + nodes[nrow][ncol + 2]->p = nodes[nrow][ncol + 3]->p - s; } else { - nodes[nrow ][ncol+1]->p += dp; + nodes[nrow][ncol + 1]->p += dp; } } - if( patch[2] || patch[3] ) { - if( nodes[nrow+1][ncol ]->path_type == 'l' || - nodes[nrow+1][ncol ]->path_type == 'L' ) { - Geom::Point s = (nodes[nrow+3][ncol]->p - nodes[nrow][ncol]->p)/3.0; - nodes[nrow+1][ncol ]->p = nodes[nrow][ncol]->p + s; - nodes[nrow+2][ncol ]->p = nodes[nrow+3][ncol]->p - s; + if (patch[2] || patch[3]) { + if (nodes[nrow + 1][ncol]->path_type == 'l' || nodes[nrow + 1][ncol]->path_type == 'L') { + Geom::Point s = (nodes[nrow + 3][ncol]->p - nodes[nrow][ncol]->p) / 3.0; + nodes[nrow + 1][ncol]->p = nodes[nrow][ncol]->p + s; + nodes[nrow + 2][ncol]->p = nodes[nrow + 3][ncol]->p - s; } else { - nodes[nrow+1][ncol ]->p += dp; + nodes[nrow + 1][ncol]->p += dp; } } - if( patch[3] || patch[0] ) { - if( nodes[nrow ][ncol-1]->path_type == 'l' || - nodes[nrow ][ncol-1]->path_type == 'L' ) { - Geom::Point s = (nodes[nrow][ncol-3]->p - nodes[nrow][ncol]->p)/3.0; - nodes[nrow ][ncol-1]->p = nodes[nrow][ncol]->p + s; - nodes[nrow ][ncol-2]->p = nodes[nrow][ncol-3]->p - s; + if (patch[3] || patch[0]) { + if (nodes[nrow][ncol - 1]->path_type == 'l' || nodes[nrow][ncol - 1]->path_type == 'L') { + Geom::Point s = (nodes[nrow][ncol - 3]->p - nodes[nrow][ncol]->p) / 3.0; + nodes[nrow][ncol - 1]->p = nodes[nrow][ncol]->p + s; + nodes[nrow][ncol - 2]->p = nodes[nrow][ncol - 3]->p - s; } else { - nodes[nrow ][ncol-1]->p += dp; + nodes[nrow][ncol - 1]->p += dp; } } - // Move tensors - if( patch[0] ) nodes[nrow-1][ncol-1]->p += dp; - if( patch[1] ) nodes[nrow-1][ncol+1]->p += dp; - if( patch[2] ) nodes[nrow+1][ncol+1]->p += dp; - if( patch[3] ) nodes[nrow+1][ncol-1]->p += dp; + if (patch[0]) + nodes[nrow - 1][ncol - 1]->p += dp; + if (patch[1]) + nodes[nrow - 1][ncol + 1]->p += dp; + if (patch[2]) + nodes[nrow + 1][ncol + 1]->p += dp; + if (patch[3]) + nodes[nrow + 1][ncol - 1]->p += dp; // // Check if neighboring corners are selected. @@ -2588,28 +2532,28 @@ void SPMeshNodeArray::update_handles( guint corner, std::vector< guint > /*selec // do_scale_xp = false; // std::cout << " Not scaling x+" << std::endl; // } - // } + // } // if( ccol > 0 ) { // if( std::find( sc.begin(), sc.end(), point_i - 1 ) != sc.end() ) { // do_scale_xn = false; // std::cout << " Not scaling x-" << std::endl; // } - // } + // } // if( crow < mrow+1 ) { // if( std::find( sc.begin(), sc.end(), point_i + ncorners ) != sc.end() ) { // do_scale_yp = false; // std::cout << " Not scaling y+" << std::endl; // } - // } + // } // if( crow > 0 ) { // if( std::find( sc.begin(), sc.end(), point_i - ncorners ) != sc.end() ) { // do_scale_yn = false; // std::cout << " Not scaling y-" << std::endl; // } - // } + // } // // We have four patches to adjust... // for ( guint k = 0; k < 4; ++k ) { @@ -2695,20 +2639,17 @@ void SPMeshNodeArray::update_handles( guint corner, std::vector< guint > /*selec // // // // The goal is to preserve the direction of the handle! - // Geom::Point dsx_new = pnodes[0][3]->p - pnodes[0][0]->p; // New side x // Geom::Point dsy_new = pnodes[3][0]->p - pnodes[0][0]->p; // New side y // Geom::Point dsx_old = pnodes[0][3]->p - pcg_old; // Old side x // Geom::Point dsy_old = pnodes[3][0]->p - pcg_old; // Old side y - // double scale_factor_x = 1.0; // if( dsx_old.length() != 0.0 ) scale_factor_x = dsx_new.length()/dsx_old.length(); // double scale_factor_y = 1.0; // if( dsy_old.length() != 0.0 ) scale_factor_y = dsy_new.length()/dsy_old.length(); - // if( do_scalex && do_scaley ) { // // We have six point to move. @@ -2728,50 +2669,48 @@ void SPMeshNodeArray::update_handles( guint corner, std::vector< guint > /*selec // dp11 *= scale_factor_x; // pnodes[1][1] = pnodes[0][0] + dp11; - - // // P21 // Geom::Point dp21 = pnodes[2][1] - pnodes[3][0]; // dp21 *= scale_factor_x; // dp21 *= scale_factor_y; // pnodes[2][1] = pnodes[3][0] + dp21; - - // Geom::Point dsx1 = pnodes[0][1]->p - + // Geom::Point dsx1 = pnodes[0][1]->p - } std::unique_ptr SPMeshNodeArray::outline_path() const { auto outline = std::make_unique(); - if (nodes.empty() ) { + if (nodes.empty()) { std::cerr << "SPMeshNodeArray::outline_path: empty array!" << std::endl; return outline; } - outline->moveto( nodes[0][0]->p ); + outline->moveto(nodes[0][0]->p); int ncol = nodes[0].size(); int nrow = nodes.size(); // Top - for (int i = 1; i < ncol; i += 3 ) { - outline->curveto( nodes[0][i]->p, nodes[0][i+1]->p, nodes[0][i+2]->p); + for (int i = 1; i < ncol; i += 3) { + outline->curveto(nodes[0][i]->p, nodes[0][i + 1]->p, nodes[0][i + 2]->p); } // Right - for (int i = 1; i < nrow; i += 3 ) { - outline->curveto( nodes[i][ncol-1]->p, nodes[i+1][ncol-1]->p, nodes[i+2][ncol-1]->p); + for (int i = 1; i < nrow; i += 3) { + outline->curveto(nodes[i][ncol - 1]->p, nodes[i + 1][ncol - 1]->p, nodes[i + 2][ncol - 1]->p); } // Bottom (right to left) - for (int i = 1; i < ncol; i += 3 ) { - outline->curveto( nodes[nrow-1][ncol-i-1]->p, nodes[nrow-1][ncol-i-2]->p, nodes[nrow-1][ncol-i-3]->p); + for (int i = 1; i < ncol; i += 3) { + outline->curveto(nodes[nrow - 1][ncol - i - 1]->p, nodes[nrow - 1][ncol - i - 2]->p, + nodes[nrow - 1][ncol - i - 3]->p); } // Left (bottom to top) - for (int i = 1; i < nrow; i += 3 ) { - outline->curveto( nodes[nrow-i-1][0]->p, nodes[nrow-i-2][0]->p, nodes[nrow-i-3][0]->p); + for (int i = 1; i < nrow; i += 3) { + outline->curveto(nodes[nrow - i - 1][0]->p, nodes[nrow - i - 2][0]->p, nodes[nrow - i - 3][0]->p); } outline->closepath(); @@ -2779,23 +2718,23 @@ std::unique_ptr SPMeshNodeArray::outline_path() const return outline; } -void SPMeshNodeArray::transform(Geom::Affine const &m) { - +void SPMeshNodeArray::transform(Geom::Affine const &m) +{ for (int i = 0; i < nodes[0].size(); ++i) { - for (auto & node : nodes) { + for (auto &node : nodes) { node[i]->p *= m; } } } // Transform mesh to fill box. Return true if mesh transformed. -bool SPMeshNodeArray::fill_box(Geom::OptRect &box) { - +bool SPMeshNodeArray::fill_box(Geom::OptRect &box) +{ // If gradientTransfor is set (as happens when an object is transformed // with the "optimized" preferences set true), we need to remove it. if (mg->gradientTransform_set) { Geom::Affine gt = mg->gradientTransform; - transform( gt ); + transform(gt); mg->gradientTransform_set = false; mg->gradientTransform.setIdentity(); } @@ -2805,18 +2744,18 @@ bool SPMeshNodeArray::fill_box(Geom::OptRect &box) { if ((*mesh_bbox).width() == 0 || (*mesh_bbox).height() == 0) { return false; - } + } - double scale_x = (*box).width() /(*mesh_bbox).width() ; - double scale_y = (*box).height()/(*mesh_bbox).height(); + double scale_x = (*box).width() / (*mesh_bbox).width(); + double scale_y = (*box).height() / (*mesh_bbox).height(); Geom::Translate t1(-(*mesh_bbox).min()); - Geom::Scale scale(scale_x,scale_y); + Geom::Scale scale(scale_x, scale_y); Geom::Translate t2((*box).min()); Geom::Affine trans = t1 * scale * t2; - if (!trans.isIdentity() ) { + if (!trans.isIdentity()) { transform(trans); - write( mg ); + write(mg); mg->requestModified(SP_OBJECT_MODIFIED_FLAG); return true; } @@ -2830,137 +2769,144 @@ guint32 average_color(guint32 c1, guint32 c2, gdouble p); /** Split a row into n equal parts. */ -void SPMeshNodeArray::split_row( unsigned int row, unsigned int n ) { - +void SPMeshNodeArray::split_row(unsigned int row, unsigned int n) +{ double nn = n; - if( n > 1 ) split_row( row, (nn-1)/nn ); - if( n > 2 ) split_row( row, n-1 ); + if (n > 1) + split_row(row, (nn - 1) / nn); + if (n > 2) + split_row(row, n - 1); } /** Split a column into n equal parts. */ -void SPMeshNodeArray::split_column( unsigned int col, unsigned int n ) { - +void SPMeshNodeArray::split_column(unsigned int col, unsigned int n) +{ double nn = n; - if( n > 1 ) split_column( col, (nn-1)/nn ); - if( n > 2 ) split_column( col, n-1 ); + if (n > 1) + split_column(col, (nn - 1) / nn); + if (n > 2) + split_column(col, n - 1); } /** Split a row into two rows at coord (fraction of row height). */ -void SPMeshNodeArray::split_row( unsigned int row, double coord ) { - +void SPMeshNodeArray::split_row(unsigned int row, double coord) +{ // std::cout << "Splitting row: " << row << " at " << coord << std::endl; // print(); - assert( coord >= 0.0 && coord <= 1.0 ); - assert( row < patch_rows() ); + assert(coord >= 0.0 && coord <= 1.0); + assert(row < patch_rows()); built = false; // First step is to ensure that handle and tensor points are up-to-date if they are not set. // (We can't do this on the fly as we overwrite the necessary points to do the calculation // during the update.) - for( guint j = 0; j < patch_columns(); ++ j ) { - SPMeshPatchI patch( &nodes, row, j ); + for (guint j = 0; j < patch_columns(); ++j) { + SPMeshPatchI patch(&nodes, row, j); patch.updateNodes(); } // Add three new rows of empty nodes - for( guint i = 0; i < 3; ++i ) { - std::vector< SPMeshNode* > new_row; - for( guint j = 0; j < nodes[0].size(); ++j ) { - SPMeshNode* new_node = new SPMeshNode; - new_row.push_back( new_node ); + for (guint i = 0; i < 3; ++i) { + std::vector new_row; + for (guint j = 0; j < nodes[0].size(); ++j) { + SPMeshNode *new_node = new SPMeshNode; + new_row.push_back(new_node); } - nodes.insert( nodes.begin()+3*(row+1), new_row ); + nodes.insert(nodes.begin() + 3 * (row + 1), new_row); } guint i = 3 * row; // Convert from patch row to node row - for( guint j = 0; j < nodes[i].size(); ++j ) { - + for (guint j = 0; j < nodes[i].size(); ++j) { // std::cout << "Splitting row: column: " << j << std::endl; Geom::Point p[4]; - for( guint k = 0; k < 4; ++k ) { + for (guint k = 0; k < 4; ++k) { guint n = k; - if( k == 3 ) n = 6; // Bottom patch row has been shifted by new rows - p[k] = nodes[i+n][j]->p; + if (k == 3) + n = 6; // Bottom patch row has been shifted by new rows + p[k] = nodes[i + n][j]->p; // std::cout << p[k] << std::endl; } - Geom::BezierCurveN<3> b( p[0], p[1], p[2], p[3] ); + Geom::BezierCurveN<3> b(p[0], p[1], p[2], p[3]); - std::pair, Geom::BezierCurveN<3> > b_new = - b.subdivide( coord ); + std::pair, Geom::BezierCurveN<3>> b_new = b.subdivide(coord); // Update points - for( guint n = 0; n < 4; ++n ) { - nodes[i+n ][j]->p = b_new.first[n]; - nodes[i+n+3][j]->p = b_new.second[n]; + for (guint n = 0; n < 4; ++n) { + nodes[i + n][j]->p = b_new.first[n]; + nodes[i + n + 3][j]->p = b_new.second[n]; // std::cout << b_new.first[n] << " " << b_new.second[n] << std::endl; } - if( nodes[i][j]->node_type == MG_NODE_TYPE_CORNER ) { + if (nodes[i][j]->node_type == MG_NODE_TYPE_CORNER) { // We are splitting a side // Path type stored in handles. - gchar path_type = nodes[i+1][j]->path_type; - nodes[i+4][j]->path_type = path_type; - nodes[i+5][j]->path_type = path_type; - bool set = nodes[i+1][j]->set; - nodes[i+4][j]->set = set; - nodes[i+5][j]->set = set; - nodes[i+4][j]->node_type = MG_NODE_TYPE_HANDLE; - nodes[i+5][j]->node_type = MG_NODE_TYPE_HANDLE; + gchar path_type = nodes[i + 1][j]->path_type; + nodes[i + 4][j]->path_type = path_type; + nodes[i + 5][j]->path_type = path_type; + bool set = nodes[i + 1][j]->set; + nodes[i + 4][j]->set = set; + nodes[i + 5][j]->set = set; + nodes[i + 4][j]->node_type = MG_NODE_TYPE_HANDLE; + nodes[i + 5][j]->node_type = MG_NODE_TYPE_HANDLE; // Color stored in corners - guint c0 = nodes[i ][j]->color.toRGBA32( 1.0 ); - guint c1 = nodes[i+6][j]->color.toRGBA32( 1.0 ); - gdouble o0 = nodes[i ][j]->opacity; - gdouble o1 = nodes[i+6][j]->opacity; - guint cnew = average_color( c0, c1, coord ); + guint c0 = nodes[i][j]->color.toRGBA32(1.0); + guint c1 = nodes[i + 6][j]->color.toRGBA32(1.0); + gdouble o0 = nodes[i][j]->opacity; + gdouble o1 = nodes[i + 6][j]->opacity; + guint cnew = average_color(c0, c1, coord); gdouble onew = o0 * (1.0 - coord) + o1 * coord; - nodes[i+3][j]->color.set( cnew ); - nodes[i+3][j]->opacity = onew; - nodes[i+3][j]->node_type = MG_NODE_TYPE_CORNER; - nodes[i+3][j]->set = true; + nodes[i + 3][j]->color.set(cnew); + nodes[i + 3][j]->opacity = onew; + nodes[i + 3][j]->node_type = MG_NODE_TYPE_CORNER; + nodes[i + 3][j]->set = true; } else { // We are splitting a middle - bool set = nodes[i+1][j]->set || nodes[i+2][j]->set; - nodes[i+4][j]->set = set; - nodes[i+5][j]->set = set; - nodes[i+4][j]->node_type = MG_NODE_TYPE_TENSOR; - nodes[i+5][j]->node_type = MG_NODE_TYPE_TENSOR; + bool set = nodes[i + 1][j]->set || nodes[i + 2][j]->set; + nodes[i + 4][j]->set = set; + nodes[i + 5][j]->set = set; + nodes[i + 4][j]->node_type = MG_NODE_TYPE_TENSOR; + nodes[i + 5][j]->node_type = MG_NODE_TYPE_TENSOR; // Path type, if different, choose l -> L -> c -> C. - gchar path_type0 = nodes[i ][j]->path_type; - gchar path_type1 = nodes[i+6][j]->path_type; + gchar path_type0 = nodes[i][j]->path_type; + gchar path_type1 = nodes[i + 6][j]->path_type; gchar path_type = 'l'; - if( path_type0 == 'L' || path_type1 == 'L') path_type = 'L'; - if( path_type0 == 'c' || path_type1 == 'c') path_type = 'c'; - if( path_type0 == 'C' || path_type1 == 'C') path_type = 'C'; - nodes[i+3][j]->path_type = path_type; - nodes[i+3][j]->node_type = MG_NODE_TYPE_HANDLE; - if( path_type == 'c' || path_type == 'C' ) nodes[i+3][j]->set = true; - + if (path_type0 == 'L' || path_type1 == 'L') + path_type = 'L'; + if (path_type0 == 'c' || path_type1 == 'c') + path_type = 'c'; + if (path_type0 == 'C' || path_type1 == 'C') + path_type = 'C'; + nodes[i + 3][j]->path_type = path_type; + nodes[i + 3][j]->node_type = MG_NODE_TYPE_HANDLE; + if (path_type == 'c' || path_type == 'C') + nodes[i + 3][j]->set = true; } - nodes[i+3][j]->node_edge = MG_NODE_EDGE_NONE; - nodes[i+4][j]->node_edge = MG_NODE_EDGE_NONE; - nodes[i+5][j]->node_edge = MG_NODE_EDGE_NONE;; - if( j == 0 ) { - nodes[i+3][j]->node_edge |= MG_NODE_EDGE_LEFT; - nodes[i+4][j]->node_edge |= MG_NODE_EDGE_LEFT; - nodes[i+5][j]->node_edge |= MG_NODE_EDGE_LEFT; + nodes[i + 3][j]->node_edge = MG_NODE_EDGE_NONE; + nodes[i + 4][j]->node_edge = MG_NODE_EDGE_NONE; + nodes[i + 5][j]->node_edge = MG_NODE_EDGE_NONE; + ; + if (j == 0) { + nodes[i + 3][j]->node_edge |= MG_NODE_EDGE_LEFT; + nodes[i + 4][j]->node_edge |= MG_NODE_EDGE_LEFT; + nodes[i + 5][j]->node_edge |= MG_NODE_EDGE_LEFT; } - if( j == nodes[i].size() - 1 ) { - nodes[i+3][j]->node_edge |= MG_NODE_EDGE_RIGHT; - nodes[i+4][j]->node_edge |= MG_NODE_EDGE_RIGHT; - nodes[i+5][j]->node_edge |= MG_NODE_EDGE_RIGHT; + if (j == nodes[i].size() - 1) { + nodes[i + 3][j]->node_edge |= MG_NODE_EDGE_RIGHT; + nodes[i + 4][j]->node_edge |= MG_NODE_EDGE_RIGHT; + nodes[i + 5][j]->node_edge |= MG_NODE_EDGE_RIGHT; } } @@ -2968,116 +2914,115 @@ void SPMeshNodeArray::split_row( unsigned int row, double coord ) { // print(); } - - /** Split a column into two columns at coord (fraction of column width). */ -void SPMeshNodeArray::split_column( unsigned int col, double coord ) { - +void SPMeshNodeArray::split_column(unsigned int col, double coord) +{ // std::cout << "Splitting column: " << col << " at " << coord << std::endl; // print(); - assert( coord >= 0.0 && coord <= 1.0 ); - assert( col < patch_columns() ); + assert(coord >= 0.0 && coord <= 1.0); + assert(col < patch_columns()); built = false; // First step is to ensure that handle and tensor points are up-to-date if they are not set. // (We can't do this on the fly as we overwrite the necessary points to do the calculation // during the update.) - for( guint i = 0; i < patch_rows(); ++ i ) { - SPMeshPatchI patch( &nodes, i, col ); + for (guint i = 0; i < patch_rows(); ++i) { + SPMeshPatchI patch(&nodes, i, col); patch.updateNodes(); } guint j = 3 * col; // Convert from patch column to node column - for( guint i = 0; i < nodes.size(); ++i ) { - + for (guint i = 0; i < nodes.size(); ++i) { // std::cout << "Splitting column: row: " << i << std::endl; Geom::Point p[4]; - for( guint k = 0; k < 4; ++k ) { - p[k] = nodes[i][j+k]->p; + for (guint k = 0; k < 4; ++k) { + p[k] = nodes[i][j + k]->p; } - Geom::BezierCurveN<3> b( p[0], p[1], p[2], p[3] ); + Geom::BezierCurveN<3> b(p[0], p[1], p[2], p[3]); - std::pair, Geom::BezierCurveN<3> > b_new = - b.subdivide( coord ); + std::pair, Geom::BezierCurveN<3>> b_new = b.subdivide(coord); // Add three new nodes - for( guint n = 0; n < 3; ++n ) { - SPMeshNode* new_node = new SPMeshNode; - nodes[i].insert( nodes[i].begin()+j+3, new_node ); + for (guint n = 0; n < 3; ++n) { + SPMeshNode *new_node = new SPMeshNode; + nodes[i].insert(nodes[i].begin() + j + 3, new_node); } // Update points - for( guint n = 0; n < 4; ++n ) { - nodes[i][j+n]->p = b_new.first[n]; - nodes[i][j+n+3]->p = b_new.second[n]; + for (guint n = 0; n < 4; ++n) { + nodes[i][j + n]->p = b_new.first[n]; + nodes[i][j + n + 3]->p = b_new.second[n]; } - if( nodes[i][j]->node_type == MG_NODE_TYPE_CORNER ) { + if (nodes[i][j]->node_type == MG_NODE_TYPE_CORNER) { // We are splitting a side // Path type stored in handles. - gchar path_type = nodes[i][j+1]->path_type; - nodes[i][j+4]->path_type = path_type; - nodes[i][j+5]->path_type = path_type; - bool set = nodes[i][j+1]->set; - nodes[i][j+4]->set = set; - nodes[i][j+5]->set = set; - nodes[i][j+4]->node_type = MG_NODE_TYPE_HANDLE; - nodes[i][j+5]->node_type = MG_NODE_TYPE_HANDLE; + gchar path_type = nodes[i][j + 1]->path_type; + nodes[i][j + 4]->path_type = path_type; + nodes[i][j + 5]->path_type = path_type; + bool set = nodes[i][j + 1]->set; + nodes[i][j + 4]->set = set; + nodes[i][j + 5]->set = set; + nodes[i][j + 4]->node_type = MG_NODE_TYPE_HANDLE; + nodes[i][j + 5]->node_type = MG_NODE_TYPE_HANDLE; // Color stored in corners - guint c0 = nodes[i][j ]->color.toRGBA32( 1.0 ); - guint c1 = nodes[i][j+6]->color.toRGBA32( 1.0 ); - gdouble o0 = nodes[i][j ]->opacity; - gdouble o1 = nodes[i][j+6]->opacity; - guint cnew = average_color( c0, c1, coord ); + guint c0 = nodes[i][j]->color.toRGBA32(1.0); + guint c1 = nodes[i][j + 6]->color.toRGBA32(1.0); + gdouble o0 = nodes[i][j]->opacity; + gdouble o1 = nodes[i][j + 6]->opacity; + guint cnew = average_color(c0, c1, coord); gdouble onew = o0 * (1.0 - coord) + o1 * coord; - nodes[i][j+3]->color.set( cnew ); - nodes[i][j+3]->opacity = onew; - nodes[i][j+3]->node_type = MG_NODE_TYPE_CORNER; - nodes[i][j+3]->set = true; + nodes[i][j + 3]->color.set(cnew); + nodes[i][j + 3]->opacity = onew; + nodes[i][j + 3]->node_type = MG_NODE_TYPE_CORNER; + nodes[i][j + 3]->set = true; } else { // We are splitting a middle - bool set = nodes[i][j+1]->set || nodes[i][j+2]->set; - nodes[i][j+4]->set = set; - nodes[i][j+5]->set = set; - nodes[i][j+4]->node_type = MG_NODE_TYPE_TENSOR; - nodes[i][j+5]->node_type = MG_NODE_TYPE_TENSOR; + bool set = nodes[i][j + 1]->set || nodes[i][j + 2]->set; + nodes[i][j + 4]->set = set; + nodes[i][j + 5]->set = set; + nodes[i][j + 4]->node_type = MG_NODE_TYPE_TENSOR; + nodes[i][j + 5]->node_type = MG_NODE_TYPE_TENSOR; // Path type, if different, choose l -> L -> c -> C. - gchar path_type0 = nodes[i][j ]->path_type; - gchar path_type1 = nodes[i][j+6]->path_type; + gchar path_type0 = nodes[i][j]->path_type; + gchar path_type1 = nodes[i][j + 6]->path_type; gchar path_type = 'l'; - if( path_type0 == 'L' || path_type1 == 'L') path_type = 'L'; - if( path_type0 == 'c' || path_type1 == 'c') path_type = 'c'; - if( path_type0 == 'C' || path_type1 == 'C') path_type = 'C'; - nodes[i][j+3]->path_type = path_type; - nodes[i][j+3]->node_type = MG_NODE_TYPE_HANDLE; - if( path_type == 'c' || path_type == 'C' ) nodes[i][j+3]->set = true; - + if (path_type0 == 'L' || path_type1 == 'L') + path_type = 'L'; + if (path_type0 == 'c' || path_type1 == 'c') + path_type = 'c'; + if (path_type0 == 'C' || path_type1 == 'C') + path_type = 'C'; + nodes[i][j + 3]->path_type = path_type; + nodes[i][j + 3]->node_type = MG_NODE_TYPE_HANDLE; + if (path_type == 'c' || path_type == 'C') + nodes[i][j + 3]->set = true; } - nodes[i][j+3]->node_edge = MG_NODE_EDGE_NONE; - nodes[i][j+4]->node_edge = MG_NODE_EDGE_NONE; - nodes[i][j+5]->node_edge = MG_NODE_EDGE_NONE;; - if( i == 0 ) { - nodes[i][j+3]->node_edge |= MG_NODE_EDGE_TOP; - nodes[i][j+4]->node_edge |= MG_NODE_EDGE_TOP; - nodes[i][j+5]->node_edge |= MG_NODE_EDGE_TOP; + nodes[i][j + 3]->node_edge = MG_NODE_EDGE_NONE; + nodes[i][j + 4]->node_edge = MG_NODE_EDGE_NONE; + nodes[i][j + 5]->node_edge = MG_NODE_EDGE_NONE; + ; + if (i == 0) { + nodes[i][j + 3]->node_edge |= MG_NODE_EDGE_TOP; + nodes[i][j + 4]->node_edge |= MG_NODE_EDGE_TOP; + nodes[i][j + 5]->node_edge |= MG_NODE_EDGE_TOP; } - if( i == nodes.size() - 1 ) { - nodes[i][j+3]->node_edge |= MG_NODE_EDGE_BOTTOM; - nodes[i][j+4]->node_edge |= MG_NODE_EDGE_BOTTOM; - nodes[i][j+5]->node_edge |= MG_NODE_EDGE_BOTTOM; + if (i == nodes.size() - 1) { + nodes[i][j + 3]->node_edge |= MG_NODE_EDGE_BOTTOM; + nodes[i][j + 4]->node_edge |= MG_NODE_EDGE_BOTTOM; + nodes[i][j + 5]->node_edge |= MG_NODE_EDGE_BOTTOM; } - } // std::cout << "Splitting col: result:" << std::endl; diff --git a/src/object/sp-mesh-array.h b/src/object/sp-mesh-array.h index eb28a1265af6722a1916453c1d7cc3feda438685..58327e14179716254a3e89dcf7e5ab0fb1a76b02 100644 --- a/src/object/sp-mesh-array.h +++ b/src/object/sp-mesh-array.h @@ -17,7 +17,7 @@ be shared between two patches and the corners between up to four. The order of the points for each side always goes from left to right or top to bottom. - For sides 2 and 3 the points must be reversed when used (as in calls to cairo functions). + For sides 2 and 3 the points must be reversed when used (as in calls to cairo functions). Two patches: (C=corner, S=side, H=handle, T=tensor) @@ -41,182 +41,195 @@ */ #include <2geom/point.h> + #include "color.h" // For color picking -#include "sp-item.h" - #include -enum SPMeshType { - SP_MESH_TYPE_COONS, - SP_MESH_TYPE_BICUBIC +#include "sp-item.h" + +enum SPMeshType +{ + SP_MESH_TYPE_COONS, + SP_MESH_TYPE_BICUBIC }; -enum SPMeshGeometry { - SP_MESH_GEOMETRY_NORMAL, - SP_MESH_GEOMETRY_CONICAL +enum SPMeshGeometry +{ + SP_MESH_GEOMETRY_NORMAL, + SP_MESH_GEOMETRY_CONICAL }; -enum NodeType { - MG_NODE_TYPE_UNKNOWN, - MG_NODE_TYPE_CORNER, - MG_NODE_TYPE_HANDLE, - MG_NODE_TYPE_TENSOR +enum NodeType +{ + MG_NODE_TYPE_UNKNOWN, + MG_NODE_TYPE_CORNER, + MG_NODE_TYPE_HANDLE, + MG_NODE_TYPE_TENSOR }; // Is a node along an edge? -enum NodeEdge { - MG_NODE_EDGE_NONE, - MG_NODE_EDGE_TOP = 1, - MG_NODE_EDGE_LEFT = 2, - MG_NODE_EDGE_BOTTOM = 4, - MG_NODE_EDGE_RIGHT = 8 +enum NodeEdge +{ + MG_NODE_EDGE_NONE, + MG_NODE_EDGE_TOP = 1, + MG_NODE_EDGE_LEFT = 2, + MG_NODE_EDGE_BOTTOM = 4, + MG_NODE_EDGE_RIGHT = 8 }; -enum MeshCornerOperation { - MG_CORNER_SIDE_TOGGLE, - MG_CORNER_SIDE_ARC, - MG_CORNER_TENSOR_TOGGLE, - MG_CORNER_COLOR_SMOOTH, - MG_CORNER_COLOR_PICK, - MG_CORNER_INSERT +enum MeshCornerOperation +{ + MG_CORNER_SIDE_TOGGLE, + MG_CORNER_SIDE_ARC, + MG_CORNER_TENSOR_TOGGLE, + MG_CORNER_COLOR_SMOOTH, + MG_CORNER_COLOR_PICK, + MG_CORNER_INSERT }; -enum MeshNodeOperation { - MG_NODE_NO_SCALE, - MG_NODE_SCALE, - MG_NODE_SCALE_HANDLE +enum MeshNodeOperation +{ + MG_NODE_NO_SCALE, + MG_NODE_SCALE, + MG_NODE_SCALE_HANDLE }; class SPStop; -class SPMeshNode { +class SPMeshNode +{ public: - SPMeshNode() { - node_type = MG_NODE_TYPE_UNKNOWN; - node_edge = MG_NODE_EDGE_NONE; - set = false; - draggable = -1; - path_type = 'u'; - opacity = 0.0; - stop = nullptr; - } - NodeType node_type; - unsigned int node_edge; - bool set; - Geom::Point p; - unsigned int draggable; // index of on-screen node - char path_type; - SPColor color; - double opacity; - SPStop *stop; // Stop corresponding to node. + SPMeshNode() + { + node_type = MG_NODE_TYPE_UNKNOWN; + node_edge = MG_NODE_EDGE_NONE; + set = false; + draggable = -1; + path_type = 'u'; + opacity = 0.0; + stop = nullptr; + } + NodeType node_type; + unsigned int node_edge; + bool set; + Geom::Point p; + unsigned int draggable; // index of on-screen node + char path_type; + SPColor color; + double opacity; + SPStop *stop; // Stop corresponding to node. }; - // I for Internal to distinguish it from the Object class // This is a convenience class... -class SPMeshPatchI { - +class SPMeshPatchI +{ private: - std::vector > *nodes; - int row; - int col; + std::vector> *nodes; + int row; + int col; public: - SPMeshPatchI( std::vector > *n, int r, int c ); - Geom::Point getPoint( unsigned int side, unsigned int point ); - std::vector< Geom::Point > getPointsForSide( unsigned int i ); - void setPoint( unsigned int side, unsigned int point, Geom::Point p, bool set = true ); - char getPathType( unsigned int i ); - void setPathType( unsigned int, char t ); - Geom::Point getTensorPoint( unsigned int i ); - void setTensorPoint( unsigned int i, Geom::Point p ); - bool tensorIsSet(); - bool tensorIsSet( unsigned int i ); - Geom::Point coonsTensorPoint( unsigned int i ); - void updateNodes(); - SPColor getColor( unsigned int i ); - void setColor( unsigned int i, SPColor c ); - double getOpacity( unsigned int i ); - void setOpacity( unsigned int i, double o ); - SPStop* getStopPtr( unsigned int i ); - void setStopPtr( unsigned int i, SPStop* ); + SPMeshPatchI(std::vector> *n, int r, int c); + Geom::Point getPoint(unsigned int side, unsigned int point); + std::vector getPointsForSide(unsigned int i); + void setPoint(unsigned int side, unsigned int point, Geom::Point p, bool set = true); + char getPathType(unsigned int i); + void setPathType(unsigned int, char t); + Geom::Point getTensorPoint(unsigned int i); + void setTensorPoint(unsigned int i, Geom::Point p); + bool tensorIsSet(); + bool tensorIsSet(unsigned int i); + Geom::Point coonsTensorPoint(unsigned int i); + void updateNodes(); + SPColor getColor(unsigned int i); + void setColor(unsigned int i, SPColor c); + double getOpacity(unsigned int i); + void setOpacity(unsigned int i, double o); + SPStop *getStopPtr(unsigned int i); + void setStopPtr(unsigned int i, SPStop *); }; class SPMeshGradient; class SPCurve; // An array of mesh nodes. -class SPMeshNodeArray { - -// Should be private +class SPMeshNodeArray +{ + // Should be private public: - SPMeshGradient *mg; - std::vector< std::vector< SPMeshNode* > > nodes; + SPMeshGradient *mg; + std::vector> nodes; public: - // Draggables to nodes - bool draggers_valid; - std::vector< SPMeshNode* > corners; - std::vector< SPMeshNode* > handles; - std::vector< SPMeshNode* > tensors; + // Draggables to nodes + bool draggers_valid; + std::vector corners; + std::vector handles; + std::vector tensors; public: - - friend class SPMeshPatchI; - - SPMeshNodeArray() { built = false; mg = nullptr; draggers_valid = false; }; - SPMeshNodeArray( SPMeshGradient *mg ); - SPMeshNodeArray( const SPMeshNodeArray& rhs ); - SPMeshNodeArray& operator=(const SPMeshNodeArray& rhs); - - ~SPMeshNodeArray() { clear(); }; - bool built; - - bool read( SPMeshGradient *mg ); - void write( SPMeshGradient *mg ); - void create( SPMeshGradient *mg, SPItem *item, Geom::OptRect bbox ); - void clear(); - void print(); - - // Fill 'smooth' with a smoothed version by subdividing each patch. - void bicubic( SPMeshNodeArray* smooth, SPMeshType type); - - // Get size of patch - unsigned int patch_rows(); - unsigned int patch_columns(); - - SPMeshNode * node( unsigned int i, unsigned int j ) { return nodes[i][j]; } - - // Operations on corners - bool adjacent_corners( unsigned int i, unsigned int j, SPMeshNode* n[4] ); - unsigned int side_toggle( std::vector< unsigned int > ); - unsigned int side_arc( std::vector< unsigned int > ); - unsigned int tensor_toggle( std::vector< unsigned int > ); - unsigned int color_smooth( std::vector< unsigned int > ); - unsigned int color_pick( std::vector< unsigned int >, SPItem* ); - unsigned int insert( std::vector< unsigned int > ); - - // Update other nodes in response to a node move. - void update_handles( unsigned int corner, std::vector< unsigned int > selected_corners, Geom::Point old_p, MeshNodeOperation op ); - - // Return outline path - std::unique_ptr outline_path() const; - - // Transform array - void transform(Geom::Affine const &m); - - // Transform mesh to fill box. Return true if not identity transform. - bool fill_box(Geom::OptRect &box); - - // Find bounding box - // Geom::OptRect findBoundingBox(); - - void split_row( unsigned int i, unsigned int n ); - void split_column( unsigned int j, unsigned int n ); - void split_row( unsigned int i, double coord ); - void split_column( unsigned int j, double coord ); + friend class SPMeshPatchI; + + SPMeshNodeArray() + { + built = false; + mg = nullptr; + draggers_valid = false; + }; + SPMeshNodeArray(SPMeshGradient *mg); + SPMeshNodeArray(const SPMeshNodeArray &rhs); + SPMeshNodeArray &operator=(const SPMeshNodeArray &rhs); + + ~SPMeshNodeArray() { clear(); }; + bool built; + + bool read(SPMeshGradient *mg); + void write(SPMeshGradient *mg); + void create(SPMeshGradient *mg, SPItem *item, Geom::OptRect bbox); + void clear(); + void print(); + + // Fill 'smooth' with a smoothed version by subdividing each patch. + void bicubic(SPMeshNodeArray *smooth, SPMeshType type); + + // Get size of patch + unsigned int patch_rows(); + unsigned int patch_columns(); + + SPMeshNode *node(unsigned int i, unsigned int j) { return nodes[i][j]; } + + // Operations on corners + bool adjacent_corners(unsigned int i, unsigned int j, SPMeshNode *n[4]); + unsigned int side_toggle(std::vector); + unsigned int side_arc(std::vector); + unsigned int tensor_toggle(std::vector); + unsigned int color_smooth(std::vector); + unsigned int color_pick(std::vector, SPItem *); + unsigned int insert(std::vector); + + // Update other nodes in response to a node move. + void update_handles(unsigned int corner, std::vector selected_corners, Geom::Point old_p, + MeshNodeOperation op); + + // Return outline path + std::unique_ptr outline_path() const; + + // Transform array + void transform(Geom::Affine const &m); + + // Transform mesh to fill box. Return true if not identity transform. + bool fill_box(Geom::OptRect &box); + + // Find bounding box + // Geom::OptRect findBoundingBox(); + + void split_row(unsigned int i, unsigned int n); + void split_column(unsigned int j, unsigned int n); + void split_row(unsigned int i, double coord); + void split_column(unsigned int j, double coord); }; #endif /* !SEEN_SP_MESH_ARRAY_H */ diff --git a/src/object/sp-mesh-gradient.cpp b/src/object/sp-mesh-gradient.cpp index 500b9c1a860a04a412eab56a30eb68ba0a49ec42..6bf216d94c86e70c0ffb88d7a15e1a9f6dec123b 100644 --- a/src/object/sp-mesh-gradient.cpp +++ b/src/object/sp-mesh-gradient.cpp @@ -7,22 +7,26 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-mesh-gradient.h" + #include #include "attributes.h" #include "display/cairo-utils.h" -#include "sp-mesh-gradient.h" - /* * Mesh Gradient */ //#define MESH_DEBUG //#define OBJECT_TRACE -SPMeshGradient::SPMeshGradient() : SPGradient(), type( SP_MESH_TYPE_COONS ), type_set(false) { +SPMeshGradient::SPMeshGradient() + : SPGradient() + , type(SP_MESH_TYPE_COONS) + , type_set(false) +{ #ifdef OBJECT_TRACE - objectTrace( "SPMeshGradient::SPMeshGradient" ); + objectTrace("SPMeshGradient::SPMeshGradient"); #endif // Start coordinate of mesh @@ -30,20 +34,22 @@ SPMeshGradient::SPMeshGradient() : SPGradient(), type( SP_MESH_TYPE_COONS ), typ this->y.unset(SVGLength::NONE, 0.0, 0.0); #ifdef OBJECT_TRACE - objectTrace( "SPMeshGradient::SPMeshGradient", false ); + objectTrace("SPMeshGradient::SPMeshGradient", false); #endif } -SPMeshGradient::~SPMeshGradient() { +SPMeshGradient::~SPMeshGradient() +{ #ifdef OBJECT_TRACE - objectTrace( "SPMeshGradient::~SPMeshGradient (empty function)" ); - objectTrace( "SPMeshGradient::~SPMeshGradient", false ); + objectTrace("SPMeshGradient::~SPMeshGradient (empty function)"); + objectTrace("SPMeshGradient::~SPMeshGradient", false); #endif } -void SPMeshGradient::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPMeshGradient::build(SPDocument *document, Inkscape::XML::Node *repr) +{ #ifdef OBJECT_TRACE - objectTrace( "SPMeshGradient::build" ); + objectTrace("SPMeshGradient::build"); #endif SPGradient::build(document, repr); @@ -55,14 +61,14 @@ void SPMeshGradient::build(SPDocument *document, Inkscape::XML::Node *repr) { this->readAttr(SPAttr::TYPE); #ifdef OBJECT_TRACE - objectTrace( "SPMeshGradient::build", false ); + objectTrace("SPMeshGradient::build", false); #endif } - -void SPMeshGradient::set(SPAttr key, gchar const *value) { +void SPMeshGradient::set(SPAttr key, gchar const *value) +{ #ifdef OBJECT_TRACE - objectTrace( "SPMeshGradient::set" ); + objectTrace("SPMeshGradient::set"); #endif switch (key) { @@ -83,20 +89,20 @@ void SPMeshGradient::set(SPAttr key, gchar const *value) { break; case SPAttr::TYPE: - if (value) { - if (!strcmp(value, "coons")) { - this->type = SP_MESH_TYPE_COONS; - } else if (!strcmp(value, "bicubic")) { - this->type = SP_MESH_TYPE_BICUBIC; - } else { - std::cerr << "SPMeshGradient::set(): invalid value " << value << std::endl; - } - this->type_set = TRUE; - } else { - // std::cout << "SPMeshGradient::set() No value " << std::endl; - this->type = SP_MESH_TYPE_COONS; - this->type_set = FALSE; - } + if (value) { + if (!strcmp(value, "coons")) { + this->type = SP_MESH_TYPE_COONS; + } else if (!strcmp(value, "bicubic")) { + this->type = SP_MESH_TYPE_BICUBIC; + } else { + std::cerr << "SPMeshGradient::set(): invalid value " << value << std::endl; + } + this->type_set = TRUE; + } else { + // std::cout << "SPMeshGradient::set() No value " << std::endl; + this->type = SP_MESH_TYPE_COONS; + this->type_set = FALSE; + } this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; @@ -107,16 +113,17 @@ void SPMeshGradient::set(SPAttr key, gchar const *value) { } #ifdef OBJECT_TRACE - objectTrace( "SPMeshGradient::set", false ); + objectTrace("SPMeshGradient::set", false); #endif } /** * Write mesh gradient attributes to associated repr. */ -Inkscape::XML::Node* SPMeshGradient::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPMeshGradient::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ #ifdef OBJECT_TRACE - objectTrace( "SPMeshGradient::write", false ); + objectTrace("SPMeshGradient::write", false); #endif if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { @@ -124,147 +131,133 @@ Inkscape::XML::Node* SPMeshGradient::write(Inkscape::XML::Document *xml_doc, Ink } if ((flags & SP_OBJECT_WRITE_ALL) || this->x._set) { - sp_repr_set_svg_double(repr, "x", this->x.computed); + sp_repr_set_svg_double(repr, "x", this->x.computed); } if ((flags & SP_OBJECT_WRITE_ALL) || this->y._set) { - sp_repr_set_svg_double(repr, "y", this->y.computed); + sp_repr_set_svg_double(repr, "y", this->y.computed); } if ((flags & SP_OBJECT_WRITE_ALL) || this->type_set) { switch (this->type) { - case SP_MESH_TYPE_COONS: - repr->setAttribute("type", "coons"); - break; - case SP_MESH_TYPE_BICUBIC: - repr->setAttribute("type", "bicubic"); - break; - default: - // Do nothing - break; - } + case SP_MESH_TYPE_COONS: + repr->setAttribute("type", "coons"); + break; + case SP_MESH_TYPE_BICUBIC: + repr->setAttribute("type", "bicubic"); + break; + default: + // Do nothing + break; + } } SPGradient::write(xml_doc, repr, flags); #ifdef OBJECT_TRACE - objectTrace( "SPMeshGradient::write", false ); + objectTrace("SPMeshGradient::write", false); #endif return repr; } -cairo_pattern_t* SPMeshGradient::pattern_new(cairo_t * /*ct*/, - Geom::OptRect const &bbox, - double opacity) +cairo_pattern_t *SPMeshGradient::pattern_new(cairo_t * /*ct*/, Geom::OptRect const &bbox, double opacity) { - using Geom::X; - using Geom::Y; + using Geom::X; + using Geom::Y; #ifdef MESH_DEBUG - std::cout << "sp_meshgradient_create_pattern: " << (*bbox) << " " << opacity << std::endl; + std::cout << "sp_meshgradient_create_pattern: " << (*bbox) << " " << opacity << std::endl; #endif - this->ensureArray(); + this->ensureArray(); - cairo_pattern_t *cp = nullptr; + cairo_pattern_t *cp = nullptr; - SPMeshNodeArray* my_array = &array; + SPMeshNodeArray *my_array = &array; - if( type_set ) { - switch (type) { - case SP_MESH_TYPE_COONS: - // std::cout << "SPMeshGradient::pattern_new: Coons" << std::endl; - break; - case SP_MESH_TYPE_BICUBIC: - array.bicubic( &array_smoothed, type ); - my_array = &array_smoothed; - break; + if (type_set) { + switch (type) { + case SP_MESH_TYPE_COONS: + // std::cout << "SPMeshGradient::pattern_new: Coons" << std::endl; + break; + case SP_MESH_TYPE_BICUBIC: + array.bicubic(&array_smoothed, type); + my_array = &array_smoothed; + break; + } } - } - - cp = cairo_pattern_create_mesh(); - for( unsigned int i = 0; i < my_array->patch_rows(); ++i ) { - for( unsigned int j = 0; j < my_array->patch_columns(); ++j ) { + cp = cairo_pattern_create_mesh(); - SPMeshPatchI patch( &(my_array->nodes), i, j ); + for (unsigned int i = 0; i < my_array->patch_rows(); ++i) { + for (unsigned int j = 0; j < my_array->patch_columns(); ++j) { + SPMeshPatchI patch(&(my_array->nodes), i, j); - cairo_mesh_pattern_begin_patch( cp ); - cairo_mesh_pattern_move_to( cp, patch.getPoint( 0, 0 )[X], patch.getPoint( 0, 0 )[Y] ); + cairo_mesh_pattern_begin_patch(cp); + cairo_mesh_pattern_move_to(cp, patch.getPoint(0, 0)[X], patch.getPoint(0, 0)[Y]); - for( unsigned int k = 0; k < 4; ++k ) { + for (unsigned int k = 0; k < 4; ++k) { #ifdef DEBUG_MESH - std::cout << i << " " << j << " " - << patch.getPathType( k ) << " ("; - for( int p = 0; p < 4; ++p ) { - std::cout << patch.getPoint( k, p ); - } - std::cout << ") " - << patch.getColor( k ).toString() << std::endl; + std::cout << i << " " << j << " " << patch.getPathType(k) << " ("; + for (int p = 0; p < 4; ++p) { + std::cout << patch.getPoint(k, p); + } + std::cout << ") " << patch.getColor(k).toString() << std::endl; #endif - switch ( patch.getPathType( k ) ) { - case 'l': - case 'L': - case 'z': - case 'Z': - cairo_mesh_pattern_line_to( cp, - patch.getPoint( k, 3 )[X], - patch.getPoint( k, 3 )[Y] ); - break; - case 'c': - case 'C': - { - std::vector< Geom::Point > pts = patch.getPointsForSide( k ); - cairo_mesh_pattern_curve_to( cp, - pts[1][X], pts[1][Y], - pts[2][X], pts[2][Y], - pts[3][X], pts[3][Y] ); - break; - } - default: - // Shouldn't happen - std::cout << "sp_mesh_create_pattern: path error" << std::endl; - } - - if( patch.tensorIsSet(k) ) { - // Tensor point defined relative to corner. - Geom::Point t = patch.getTensorPoint(k); - cairo_mesh_pattern_set_control_point( cp, k, t[X], t[Y] ); - //std::cout << " sp_mesh_create_pattern: tensor " << k - // << " set to " << t << "." << std::endl; - } else { - // Geom::Point t = patch.coonsTensorPoint(k); - //std::cout << " sp_mesh_create_pattern: tensor " << k - // << " calculated as " << t << "." < pts = patch.getPointsForSide(k); + cairo_mesh_pattern_curve_to(cp, pts[1][X], pts[1][Y], pts[2][X], pts[2][Y], pts[3][X], + pts[3][Y]); + break; + } + default: + // Shouldn't happen + std::cout << "sp_mesh_create_pattern: path error" << std::endl; + } + + if (patch.tensorIsSet(k)) { + // Tensor point defined relative to corner. + Geom::Point t = patch.getTensorPoint(k); + cairo_mesh_pattern_set_control_point(cp, k, t[X], t[Y]); + // std::cout << " sp_mesh_create_pattern: tensor " << k + // << " set to " << t << "." << std::endl; + } else { + // Geom::Point t = patch.coonsTensorPoint(k); + // std::cout << " sp_mesh_create_pattern: tensor " << k + // << " calculated as " << t << "." <gradientTransform; - if (this->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) { - Geom::Affine bbox2user(bbox->width(), 0, 0, bbox->height(), bbox->left(), bbox->top()); - gs2user *= bbox2user; - } - ink_cairo_pattern_set_matrix(cp, gs2user.inverse()); - - /* - cairo_pattern_t *cp = cairo_pattern_create_radial( - rg->fx.computed, rg->fy.computed, 0, - rg->cx.computed, rg->cy.computed, rg->r.computed); - sp_gradient_pattern_common_setup(cp, gr, bbox, opacity); - */ - - return cp; + + // set pattern matrix + Geom::Affine gs2user = this->gradientTransform; + if (this->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) { + Geom::Affine bbox2user(bbox->width(), 0, 0, bbox->height(), bbox->left(), bbox->top()); + gs2user *= bbox2user; + } + ink_cairo_pattern_set_matrix(cp, gs2user.inverse()); + + /* + cairo_pattern_t *cp = cairo_pattern_create_radial( + rg->fx.computed, rg->fy.computed, 0, + rg->cx.computed, rg->cy.computed, rg->r.computed); + sp_gradient_pattern_common_setup(cp, gr, bbox, opacity); + */ + + return cp; } diff --git a/src/object/sp-mesh-gradient.h b/src/object/sp-mesh-gradient.h index 5951d0428b10fc74505dd62a12d2c798ab8cafd8..e3d460639dbf8ab083dcf0fdb4ff4aadb0fac3c2 100644 --- a/src/object/sp-mesh-gradient.h +++ b/src/object/sp-mesh-gradient.h @@ -14,28 +14,30 @@ * SPMeshGradient: SVG implementation. */ -#include "svg/svg-length.h" #include "sp-gradient.h" +#include "svg/svg-length.h" -#define SP_MESHGRADIENT(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_MESHGRADIENT(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_MESHGRADIENT(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_MESHGRADIENT(obj) (dynamic_cast((SPObject *)obj) != NULL) /** Mesh gradient. */ -class SPMeshGradient : public SPGradient { +class SPMeshGradient : public SPGradient +{ public: SPMeshGradient(); ~SPMeshGradient() override; - SVGLength x; // Upper left corner of meshgradient - SVGLength y; // Upper right corner of mesh + SVGLength x; // Upper left corner of meshgradient + SVGLength y; // Upper right corner of mesh SPMeshType type; bool type_set; - cairo_pattern_t* pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) override; + cairo_pattern_t *pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) override; protected: void build(SPDocument *document, Inkscape::XML::Node *repr) override; void set(SPAttr key, char const *value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; #endif /* !SP_MESH_GRADIENT_H */ diff --git a/src/object/sp-mesh-patch.cpp b/src/object/sp-mesh-patch.cpp index 3d1fdddf751b07a375854b74ed435f2ea26ca9dc..d8438db11f48b8bdd44591df8c142ff2889ab4c3 100644 --- a/src/object/sp-mesh-patch.cpp +++ b/src/object/sp-mesh-patch.cpp @@ -16,15 +16,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "sp-mesh-patch.h" -#include "style.h" #include "attributes.h" +#include "style.h" -SPMeshpatch* SPMeshpatch::getNextMeshpatch() +SPMeshpatch *SPMeshpatch::getNextMeshpatch() { SPMeshpatch *result = nullptr; - for (SPObject* obj = getNext(); obj && !result; obj = obj->getNext()) { + for (SPObject *obj = getNext(); obj && !result; obj = obj->getNext()) { if (SP_IS_MESHPATCH(obj)) { result = SP_MESHPATCH(obj); } @@ -33,14 +33,14 @@ SPMeshpatch* SPMeshpatch::getNextMeshpatch() return result; } -SPMeshpatch* SPMeshpatch::getPrevMeshpatch() +SPMeshpatch *SPMeshpatch::getPrevMeshpatch() { SPMeshpatch *result = nullptr; - for (SPObject* obj = getPrev(); obj; obj = obj->getPrev()) { + for (SPObject *obj = getPrev(); obj; obj = obj->getPrev()) { // The closest previous SPObject that is an SPMeshpatch *should* be ourself. if (SP_IS_MESHPATCH(obj)) { - SPMeshpatch* meshpatch = SP_MESHPATCH(obj); + SPMeshpatch *meshpatch = SP_MESHPATCH(obj); // Sanity check to ensure we have a proper sibling structure. if (meshpatch->getNextMeshpatch() == this) { result = meshpatch; @@ -54,30 +54,33 @@ SPMeshpatch* SPMeshpatch::getPrevMeshpatch() return result; } - /* * Mesh Patch */ -SPMeshpatch::SPMeshpatch() : SPObject() { +SPMeshpatch::SPMeshpatch() + : SPObject() +{ this->tensor_string = nullptr; } SPMeshpatch::~SPMeshpatch() = default; -void SPMeshpatch::build(SPDocument* doc, Inkscape::XML::Node* repr) { - SPObject::build(doc, repr); +void SPMeshpatch::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ + SPObject::build(doc, repr); - this->readAttr(SPAttr::TENSOR); + this->readAttr(SPAttr::TENSOR); } /** * Virtual build: set meshpatch attributes from its associated XML node. */ -void SPMeshpatch::set(SPAttr key, const gchar* value) { +void SPMeshpatch::set(SPAttr key, const gchar *value) +{ switch (key) { case SPAttr::TENSOR: { if (value) { - this->tensor_string = new Glib::ustring( value ); + this->tensor_string = new Glib::ustring(value); // std::cout << "sp_meshpatch_set: Tensor string: " << patch->tensor_string->c_str() << std::endl; } break; @@ -91,16 +94,16 @@ void SPMeshpatch::set(SPAttr key, const gchar* value) { /** * modified */ -void SPMeshpatch::modified(unsigned int flags) { - +void SPMeshpatch::modified(unsigned int flags) +{ flags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for (auto child:l) { + for (auto child : l) { if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->emitModified(flags); } @@ -108,11 +111,11 @@ void SPMeshpatch::modified(unsigned int flags) { } } - /** * Virtual set: set attribute to value. */ -Inkscape::XML::Node* SPMeshpatch::write(Inkscape::XML::Document* xml_doc, Inkscape::XML::Node* repr, guint flags) { +Inkscape::XML::Node *SPMeshpatch::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:meshpatch"); } diff --git a/src/object/sp-mesh-patch.h b/src/object/sp-mesh-patch.h index fd45e2ac4f7a785fde89869f4c72d01936e16365..3c4bd0056f6bbcb9c060784a300cd5d04c241661 100644 --- a/src/object/sp-mesh-patch.h +++ b/src/object/sp-mesh-patch.h @@ -14,28 +14,30 @@ */ #include + #include "sp-object.h" -#define SP_MESHPATCH(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_MESHPATCH(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_MESHPATCH(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_MESHPATCH(obj) (dynamic_cast((SPObject *)obj) != NULL) /** Gradient Meshpatch. */ -class SPMeshpatch : public SPObject { +class SPMeshpatch : public SPObject +{ public: SPMeshpatch(); ~SPMeshpatch() override; - SPMeshpatch* getNextMeshpatch(); - SPMeshpatch* getPrevMeshpatch(); - Glib::ustring * tensor_string; - //SVGLength tx[4]; // Tensor points - //SVGLength ty[4]; // Tensor points + SPMeshpatch *getNextMeshpatch(); + SPMeshpatch *getPrevMeshpatch(); + Glib::ustring *tensor_string; + // SVGLength tx[4]; // Tensor points + // SVGLength ty[4]; // Tensor points protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void set(SPAttr key, const char* value) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void set(SPAttr key, const char *value) override; void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif /* !SEEN_SP_MESHPATCH_H */ diff --git a/src/object/sp-mesh-row.cpp b/src/object/sp-mesh-row.cpp index 80f86b3ca08deb7889f7ee534f585ca8a2c4acb5..6c63fc267d1b26f97b2025f934cf4d03a2b7e5a1 100644 --- a/src/object/sp-mesh-row.cpp +++ b/src/object/sp-mesh-row.cpp @@ -16,13 +16,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "sp-mesh-row.h" + #include "style.h" -SPMeshrow* SPMeshrow::getNextMeshrow() +SPMeshrow *SPMeshrow::getNextMeshrow() { SPMeshrow *result = nullptr; - for (SPObject* obj = getNext(); obj && !result; obj = obj->getNext()) { + for (SPObject *obj = getNext(); obj && !result; obj = obj->getNext()) { if (SP_IS_MESHROW(obj)) { result = SP_MESHROW(obj); } @@ -31,14 +32,14 @@ SPMeshrow* SPMeshrow::getNextMeshrow() return result; } -SPMeshrow* SPMeshrow::getPrevMeshrow() +SPMeshrow *SPMeshrow::getPrevMeshrow() { SPMeshrow *result = nullptr; - for (SPObject* obj = getPrev(); obj; obj = obj->getPrev()) { + for (SPObject *obj = getPrev(); obj; obj = obj->getPrev()) { // The closest previous SPObject that is an SPMeshrow *should* be ourself. if (SP_IS_MESHROW(obj)) { - SPMeshrow* meshrow = SP_MESHROW(obj); + SPMeshrow *meshrow = SP_MESHROW(obj); // Sanity check to ensure we have a proper sibling structure. if (meshrow->getNextMeshrow() == this) { result = meshrow; @@ -52,39 +53,38 @@ SPMeshrow* SPMeshrow::getPrevMeshrow() return result; } - /* * Mesh Row */ -SPMeshrow::SPMeshrow() : SPObject() { -} +SPMeshrow::SPMeshrow() + : SPObject() +{} SPMeshrow::~SPMeshrow() = default; -void SPMeshrow::build(SPDocument* doc, Inkscape::XML::Node* repr) { - SPObject::build(doc, repr); +void SPMeshrow::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ + SPObject::build(doc, repr); } - /** * Virtual build: set meshrow attributes from its associated XML node. */ -void SPMeshrow::set(SPAttr /*key*/, const gchar* /*value*/) { -} +void SPMeshrow::set(SPAttr /*key*/, const gchar * /*value*/) {} /** * modified */ -void SPMeshrow::modified(unsigned int flags) { - +void SPMeshrow::modified(unsigned int flags) +{ flags &= SP_OBJECT_MODIFIED_CASCADE; std::vector l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child); l.push_back(&child); } - for (auto child:l) { + for (auto child : l) { if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->emitModified(flags); } @@ -92,11 +92,11 @@ void SPMeshrow::modified(unsigned int flags) { } } - /** * Virtual set: set attribute to value. */ -Inkscape::XML::Node* SPMeshrow::write(Inkscape::XML::Document* xml_doc, Inkscape::XML::Node* repr, guint flags) { +Inkscape::XML::Node *SPMeshrow::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:meshrow"); } diff --git a/src/object/sp-mesh-row.h b/src/object/sp-mesh-row.h index fa4bb582325ca7fbe52ca6f1002ac285da228e65..aa4e40c7780691e907ce8bd80b03f0f2ccce973c 100644 --- a/src/object/sp-mesh-row.h +++ b/src/object/sp-mesh-row.h @@ -14,23 +14,24 @@ #include "sp-object.h" -#define SP_MESHROW(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_MESHROW(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_MESHROW(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_MESHROW(obj) (dynamic_cast((SPObject *)obj) != NULL) /** Gradient Meshrow. */ -class SPMeshrow : public SPObject { +class SPMeshrow : public SPObject +{ public: SPMeshrow(); ~SPMeshrow() override; - SPMeshrow* getNextMeshrow(); - SPMeshrow* getPrevMeshrow(); + SPMeshrow *getNextMeshrow(); + SPMeshrow *getPrevMeshrow(); protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void set(SPAttr key, const char* value) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void set(SPAttr key, const char *value) override; void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif /* !SEEN_SP_MESHROW_H */ diff --git a/src/object/sp-metadata.cpp b/src/object/sp-metadata.cpp index a4efdec3ac5e4d19ea3f3d4f59cb6816869afc80..e92034501334660f0e319a0e9a5455be6443b7da 100644 --- a/src/object/sp-metadata.cpp +++ b/src/object/sp-metadata.cpp @@ -14,38 +14,40 @@ #include -#include "xml/node-iterators.h" #include "document.h" - #include "sp-item-group.h" #include "sp-root.h" +#include "xml/node-iterators.h" #define noDEBUG_METADATA #ifdef DEBUG_METADATA -# define debug(f, a...) { g_print("%s(%d) %s:", \ - __FILE__,__LINE__,__FUNCTION__); \ - g_print(f, ## a); \ - g_print("\n"); \ - } +#define debug(f, a...) \ + { \ + g_print("%s(%d) %s:", __FILE__, __LINE__, __FUNCTION__); \ + g_print(f, ##a); \ + g_print("\n"); \ + } #else -# define debug(f, a...) /**/ +#define debug(f, a...) /**/ #endif /* Metadata base class */ -SPMetadata::SPMetadata() : SPObject() { -} +SPMetadata::SPMetadata() + : SPObject() +{} SPMetadata::~SPMetadata() = default; namespace { -void strip_ids_recursively(Inkscape::XML::Node *node) { +void strip_ids_recursively(Inkscape::XML::Node *node) +{ using Inkscape::XML::NodeSiblingIterator; - if ( node->type() == Inkscape::XML::ELEMENT_NODE ) { + if (node->type() == Inkscape::XML::ELEMENT_NODE) { node->removeAttribute("id"); } - for ( NodeSiblingIterator iter=node->firstChild() ; iter ; ++iter ) { + for (NodeSiblingIterator iter = node->firstChild(); iter; ++iter) { strip_ids_recursively(iter); } } @@ -72,20 +74,20 @@ std::string corel_layer_get_label(SPGroup const &layer) } return ""; } -} - +} // namespace -void SPMetadata::build(SPDocument* doc, Inkscape::XML::Node* repr) { +void SPMetadata::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ using Inkscape::XML::NodeSiblingIterator; - debug("0x%08x",(unsigned int)this); + debug("0x%08x", (unsigned int)this); /* clean up our mess from earlier versions; elements under rdf:RDF should not * have id= attributes... */ static GQuark const rdf_root_name = g_quark_from_static_string("rdf:RDF"); - for ( NodeSiblingIterator iter=repr->firstChild() ; iter ; ++iter ) { - if ( (GQuark)iter->code() == rdf_root_name ) { + for (NodeSiblingIterator iter = repr->firstChild(); iter; ++iter) { + if ((GQuark)iter->code() == rdf_root_name) { strip_ids_recursively(iter); } } @@ -93,29 +95,29 @@ void SPMetadata::build(SPDocument* doc, Inkscape::XML::Node* repr) { SPObject::build(doc, repr); } -void SPMetadata::release() { - debug("0x%08x",(unsigned int)this); +void SPMetadata::release() +{ + debug("0x%08x", (unsigned int)this); // handle ourself SPObject::release(); } -void SPMetadata::set(SPAttr key, const gchar* value) { - debug("0x%08x %s(%u): '%s'",(unsigned int)this, - sp_attribute_name(key),key,value); +void SPMetadata::set(SPAttr key, const gchar *value) +{ + debug("0x%08x %s(%u): '%s'", (unsigned int)this, sp_attribute_name(key), key, value); // see if any parents need this value SPObject::set(key, value); } -void SPMetadata::update(SPCtx* /*ctx*/, unsigned int flags) { - debug("0x%08x",(unsigned int)this); - //SPMetadata *metadata = SP_METADATA(object); - - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { +void SPMetadata::update(SPCtx * /*ctx*/, unsigned int flags) +{ + debug("0x%08x", (unsigned int)this); + // SPMetadata *metadata = SP_METADATA(object); + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something? */ // Detect CorelDraw layers @@ -130,13 +132,14 @@ void SPMetadata::update(SPCtx* /*ctx*/, unsigned int flags) { } } -// SPObject::onUpdate(ctx, flags); + // SPObject::onUpdate(ctx, flags); } -Inkscape::XML::Node* SPMetadata::write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) { - debug("0x%08x",(unsigned int)this); +Inkscape::XML::Node *SPMetadata::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ + debug("0x%08x", (unsigned int)this); - if ( repr != this->getRepr() ) { + if (repr != this->getRepr()) { if (repr) { repr->mergeFrom(this->getRepr(), "id"); } else { @@ -156,16 +159,14 @@ SPMetadata *sp_document_metadata(SPDocument *document) { SPObject *nv; - g_return_val_if_fail (document != nullptr, NULL); + g_return_val_if_fail(document != nullptr, NULL); - nv = sp_item_group_get_child_by_name( document->getRoot(), nullptr, - "metadata"); - g_assert (nv != nullptr); + nv = sp_item_group_get_child_by_name(document->getRoot(), nullptr, "metadata"); + g_assert(nv != nullptr); return (SPMetadata *)nv; } - /* Local Variables: mode:c++ diff --git a/src/object/sp-metadata.h b/src/object/sp-metadata.h index ce235ce759e1b47e05cdf7c7555933ca7efe50c3..275a2dc91483331f0d136030d79af682356dcce7 100644 --- a/src/object/sp-metadata.h +++ b/src/object/sp-metadata.h @@ -17,24 +17,25 @@ /* Metadata base class */ -#define SP_METADATA(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_METADATA(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_METADATA(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_METADATA(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPMetadata : public SPObject { +class SPMetadata : public SPObject +{ public: - SPMetadata(); - ~SPMetadata() override; + SPMetadata(); + ~SPMetadata() override; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void set(SPAttr key, const char* value) override; - void update(SPCtx* ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + void set(SPAttr key, const char *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; -SPMetadata * sp_document_metadata (SPDocument *document); +SPMetadata *sp_document_metadata(SPDocument *document); #endif // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/object/sp-missing-glyph.cpp b/src/object/sp-missing-glyph.cpp index 4fa69034f09641d26a92bf123580a4280ea35605..c1a7f78d9def83f37d0cec5a0596e24af6216e4f 100644 --- a/src/object/sp-missing-glyph.cpp +++ b/src/object/sp-missing-glyph.cpp @@ -11,13 +11,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "xml/repr.h" -#include "attributes.h" #include "sp-missing-glyph.h" + +#include "attributes.h" #include "document.h" +#include "xml/repr.h" -SPMissingGlyph::SPMissingGlyph() : SPObject() { -//TODO: correct these values: +SPMissingGlyph::SPMissingGlyph() + : SPObject() +{ + // TODO: correct these values: this->d = nullptr; this->horiz_adv_x = 0; this->vert_origin_x = 0; @@ -27,7 +30,8 @@ SPMissingGlyph::SPMissingGlyph() : SPObject() { SPMissingGlyph::~SPMissingGlyph() = default; -void SPMissingGlyph::build(SPDocument* doc, Inkscape::XML::Node* repr) { +void SPMissingGlyph::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ SPObject::build(doc, repr); this->readAttr(SPAttr::D); @@ -37,15 +41,15 @@ void SPMissingGlyph::build(SPDocument* doc, Inkscape::XML::Node* repr) { this->readAttr(SPAttr::VERT_ADV_Y); } -void SPMissingGlyph::release() { - SPObject::release(); +void SPMissingGlyph::release() +{ + SPObject::release(); } - -void SPMissingGlyph::set(SPAttr key, const gchar* value) { +void SPMissingGlyph::set(SPAttr key, const gchar *value) +{ switch (key) { - case SPAttr::D: - { + case SPAttr::D: { if (this->d) { g_free(this->d); } @@ -53,79 +57,74 @@ void SPMissingGlyph::set(SPAttr key, const gchar* value) { this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; } - case SPAttr::HORIZ_ADV_X: - { + case SPAttr::HORIZ_ADV_X: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - if (number != this->horiz_adv_x){ + if (number != this->horiz_adv_x) { this->horiz_adv_x = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::VERT_ORIGIN_X: - { + case SPAttr::VERT_ORIGIN_X: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - if (number != this->vert_origin_x){ + if (number != this->vert_origin_x) { this->vert_origin_x = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::VERT_ORIGIN_Y: - { + case SPAttr::VERT_ORIGIN_Y: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - if (number != this->vert_origin_y){ + if (number != this->vert_origin_y) { this->vert_origin_y = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - case SPAttr::VERT_ADV_Y: - { + case SPAttr::VERT_ADV_Y: { double number = value ? g_ascii_strtod(value, nullptr) : 0; - if (number != this->vert_adv_y){ + if (number != this->vert_adv_y) { this->vert_adv_y = number; this->requestModified(SP_OBJECT_MODIFIED_FLAG); } break; } - default: - { + default: { SPObject::set(key, value); break; } } } -#define COPY_ATTR(rd,rs,key) (rd)->setAttribute((key), rs->attribute(key)); - -Inkscape::XML::Node* SPMissingGlyph::write(Inkscape::XML::Document* xml_doc, Inkscape::XML::Node* repr, guint flags) { - if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { - repr = xml_doc->createElement("svg:glyph"); - } +#define COPY_ATTR(rd, rs, key) (rd)->setAttribute((key), rs->attribute(key)); - /* I am commenting out this part because I am not certain how does it work. I will have to study it later. Juca - repr->setAttribute("d", glyph->d); - sp_repr_set_svg_double(repr, "horiz-adv-x", glyph->horiz_adv_x); - sp_repr_set_svg_double(repr, "vert-origin-x", glyph->vert_origin_x); - sp_repr_set_svg_double(repr, "vert-origin-y", glyph->vert_origin_y); - sp_repr_set_svg_double(repr, "vert-adv-y", glyph->vert_adv_y); - */ - if (repr != this->getRepr()) { +Inkscape::XML::Node *SPMissingGlyph::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { + repr = xml_doc->createElement("svg:glyph"); + } - // TODO - // All the COPY_ATTR functions below use - // XML Tree directly while they shouldn't. - COPY_ATTR(repr, this->getRepr(), "d"); - COPY_ATTR(repr, this->getRepr(), "horiz-adv-x"); - COPY_ATTR(repr, this->getRepr(), "vert-origin-x"); - COPY_ATTR(repr, this->getRepr(), "vert-origin-y"); - COPY_ATTR(repr, this->getRepr(), "vert-adv-y"); - } + /* I am commenting out this part because I am not certain how does it work. I will have to study it later. Juca + repr->setAttribute("d", glyph->d); + sp_repr_set_svg_double(repr, "horiz-adv-x", glyph->horiz_adv_x); + sp_repr_set_svg_double(repr, "vert-origin-x", glyph->vert_origin_x); + sp_repr_set_svg_double(repr, "vert-origin-y", glyph->vert_origin_y); + sp_repr_set_svg_double(repr, "vert-adv-y", glyph->vert_adv_y); + */ + if (repr != this->getRepr()) { + // TODO + // All the COPY_ATTR functions below use + // XML Tree directly while they shouldn't. + COPY_ATTR(repr, this->getRepr(), "d"); + COPY_ATTR(repr, this->getRepr(), "horiz-adv-x"); + COPY_ATTR(repr, this->getRepr(), "vert-origin-x"); + COPY_ATTR(repr, this->getRepr(), "vert-origin-y"); + COPY_ATTR(repr, this->getRepr(), "vert-adv-y"); + } - SPObject::write(xml_doc, repr, flags); + SPObject::write(xml_doc, repr, flags); - return repr; + return repr; } /* diff --git a/src/object/sp-missing-glyph.h b/src/object/sp-missing-glyph.h index bdab50b27d94f2937a1d81c736ed652c8dabb16b..dad38fcbbcd22a5aea702ce18ff13d7e53b69eb1 100644 --- a/src/object/sp-missing-glyph.h +++ b/src/object/sp-missing-glyph.h @@ -15,21 +15,22 @@ #include "sp-object.h" -#define SP_MISSING_GLYPH(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_MISSING_GLYPH(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_MISSING_GLYPH(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_MISSING_GLYPH(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPMissingGlyph : public SPObject { +class SPMissingGlyph : public SPObject +{ public: - SPMissingGlyph(); - ~SPMissingGlyph() override; + SPMissingGlyph(); + ~SPMissingGlyph() override; - char* d; + char *d; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; - void set(SPAttr key, char const* value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, char const *value) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; private: double horiz_adv_x; diff --git a/src/object/sp-namedview.cpp b/src/object/sp-namedview.cpp index 4e73cbda3fd5f1341753f483bac14e8e3c43e853..1324a1654d2d4e0e97d32fe7bee920da8b8b34a1 100644 --- a/src/object/sp-namedview.cpp +++ b/src/object/sp-namedview.cpp @@ -15,30 +15,30 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-namedview.h" + +#include <2geom/transforms.h> #include +#include #include -#include "event-log.h" -#include <2geom/transforms.h> -#include "display/canvas-grid.h" -#include "util/units.h" -#include "svg/svg-color.h" -#include "xml/repr.h" #include "attributes.h" -#include "document.h" -#include "document-undo.h" +#include "conn-avoid-ref.h" // for defaultConnSpacing. #include "desktop-events.h" +#include "desktop.h" +#include "display/canvas-grid.h" +#include "document-undo.h" +#include "document.h" #include "enums.h" -#include "ui/monitor.h" - +#include "event-log.h" +#include "preferences.h" #include "sp-guide.h" #include "sp-item-group.h" -#include "sp-namedview.h" -#include "preferences.h" -#include "desktop.h" -#include "conn-avoid-ref.h" // for defaultConnSpacing. #include "sp-root.h" -#include +#include "svg/svg-color.h" +#include "ui/monitor.h" +#include "util/units.h" +#include "xml/repr.h" using Inkscape::DocumentUndo; using Inkscape::Util::unit_table; @@ -51,16 +51,18 @@ using Inkscape::Util::unit_table; #define DEFAULTBORDERCOLOR 0x000000ff #define DEFAULTPAGECOLOR 0xffffff00 -static void sp_namedview_setup_guides(SPNamedView * nv); -static void sp_namedview_lock_guides(SPNamedView * nv); -static void sp_namedview_show_single_guide(SPGuide* guide, bool show); -static void sp_namedview_lock_single_guide(SPGuide* guide, bool show); +static void sp_namedview_setup_guides(SPNamedView *nv); +static void sp_namedview_lock_guides(SPNamedView *nv); +static void sp_namedview_show_single_guide(SPGuide *guide, bool show); +static void sp_namedview_lock_single_guide(SPGuide *guide, bool show); static gboolean sp_str_to_bool(const gchar *str); static gboolean sp_nv_read_opacity(const gchar *str, guint32 *color); -SPNamedView::SPNamedView() : SPObjectGroup(), snap_manager(this) { - +SPNamedView::SPNamedView() + : SPObjectGroup() + , snap_manager(this) +{ this->zoom = 0; this->guidecolor = 0; this->guidehicolor = 0; @@ -100,21 +102,22 @@ SPNamedView::SPNamedView() : SPObjectGroup(), snap_manager(this) { SPNamedView::~SPNamedView() = default; -static void sp_namedview_generate_old_grid(SPNamedView * /*nv*/, SPDocument *document, Inkscape::XML::Node *repr) { +static void sp_namedview_generate_old_grid(SPNamedView * /*nv*/, SPDocument *document, Inkscape::XML::Node *repr) +{ bool old_grid_settings_present = false; // set old settings - const char* gridspacingx = "1px"; - const char* gridspacingy = "1px"; - const char* gridoriginy = "0px"; - const char* gridoriginx = "0px"; - const char* gridempspacing = "5"; - const char* gridcolor = "#3f3fff"; - const char* gridempcolor = "#3f3fff"; - const char* gridopacity = "0.15"; - const char* gridempopacity = "0.38"; - - const char* value = nullptr; + const char *gridspacingx = "1px"; + const char *gridspacingy = "1px"; + const char *gridoriginy = "0px"; + const char *gridoriginx = "0px"; + const char *gridempspacing = "5"; + const char *gridcolor = "#3f3fff"; + const char *gridempcolor = "#3f3fff"; + const char *gridopacity = "0.15"; + const char *gridempopacity = "0.38"; + + const char *value = nullptr; if ((value = repr->attribute("gridoriginx"))) { gridoriginx = value; old_grid_settings_present = true; @@ -154,7 +157,8 @@ static void sp_namedview_generate_old_grid(SPNamedView * /*nv*/, SPDocument *doc if (old_grid_settings_present) { // generate new xy grid with the correct settings - // first create the child xml node, then hook it to repr. This order is important, to not set off listeners to repr before the new node is complete. + // first create the child xml node, then hook it to repr. This order is important, to not set off listeners to + // repr before the new node is complete. Inkscape::XML::Document *xml_doc = document->getReprDoc(); Inkscape::XML::Node *newnode = xml_doc->createElement("inkscape:grid"); @@ -184,11 +188,12 @@ static void sp_namedview_generate_old_grid(SPNamedView * /*nv*/, SPDocument *doc repr->removeAttribute("gridempopacity"); repr->removeAttribute("gridempspacing"); -// SPDocumentUndo::done(doc, SP_VERB_DIALOG_NAMEDVIEW, _("Create new grid from pre0.46 grid settings")); + // SPDocumentUndo::done(doc, SP_VERB_DIALOG_NAMEDVIEW, _("Create new grid from pre0.46 grid settings")); } } -void SPNamedView::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPNamedView::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPObjectGroup::build(document, repr); this->readAttr(SPAttr::INKSCAPE_DOCUMENT_UNITS); @@ -250,11 +255,11 @@ void SPNamedView::build(SPDocument *document, Inkscape::XML::Node *repr) { this->readAttr(SPAttr::INKSCAPE_LOCKGUIDES); /* Construct guideline list */ - for (auto& o: children) { + for (auto &o : children) { if (SP_IS_GUIDE(&o)) { - SPGuide * g = SP_GUIDE(&o); + SPGuide *g = SP_GUIDE(&o); this->guides.push_back(g); - //g_object_set(G_OBJECT(g), "color", nv->guidecolor, "hicolor", nv->guidehicolor, NULL); + // g_object_set(G_OBJECT(g), "color", nv->guidecolor, "hicolor", nv->guidehicolor, NULL); g->setColor(this->guidecolor); g->setHiColor(this->guidehicolor); g->readAttr(SPAttr::INKSCAPE_COLOR); @@ -265,25 +270,27 @@ void SPNamedView::build(SPDocument *document, Inkscape::XML::Node *repr) { sp_namedview_generate_old_grid(this, document, repr); } -void SPNamedView::release() { - this->guides.clear(); +void SPNamedView::release() +{ + this->guides.clear(); // delete grids: - for(auto grid : this->grids) + for (auto grid : this->grids) delete grid; this->grids.clear(); SPObjectGroup::release(); } -void SPNamedView::set(SPAttr key, const gchar* value) { +void SPNamedView::set(SPAttr key, const gchar *value) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool global_snapping = prefs->getBool("/options/snapdefault/value", true); switch (key) { - case SPAttr::VIEWONLY: + case SPAttr::VIEWONLY: this->editable = (!value); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::SHOWGUIDES: + case SPAttr::SHOWGUIDES: if (!value) { // show guides if not specified, for backwards compatibility this->showguides = TRUE; } else { @@ -292,7 +299,7 @@ void SPNamedView::set(SPAttr key, const gchar* value) { sp_namedview_setup_guides(this); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::SHOWGRIDS: + case SPAttr::SHOWGRIDS: if (!value) { // don't show grids if not specified, for backwards compatibility this->grids_visible = false; } else { @@ -300,247 +307,267 @@ void SPNamedView::set(SPAttr key, const gchar* value) { } this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::GRIDTOLERANCE: + case SPAttr::GRIDTOLERANCE: this->snap_manager.snapprefs.setGridTolerance(value ? g_ascii_strtod(value, nullptr) : 10000); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::GUIDETOLERANCE: + case SPAttr::GUIDETOLERANCE: this->snap_manager.snapprefs.setGuideTolerance(value ? g_ascii_strtod(value, nullptr) : 20); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::OBJECTTOLERANCE: + case SPAttr::OBJECTTOLERANCE: this->snap_manager.snapprefs.setObjectTolerance(value ? g_ascii_strtod(value, nullptr) : 20); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::GUIDECOLOR: + case SPAttr::GUIDECOLOR: this->guidecolor = (this->guidecolor & 0xff) | (DEFAULTGUIDECOLOR & 0xffffff00); if (value) { this->guidecolor = (this->guidecolor & 0xff) | sp_svg_read_color(value, this->guidecolor); } - for(auto guide : this->guides) { + for (auto guide : this->guides) { guide->setColor(this->guidecolor); guide->readAttr(SPAttr::INKSCAPE_COLOR); } this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::GUIDEOPACITY: + case SPAttr::GUIDEOPACITY: this->guidecolor = (this->guidecolor & 0xffffff00) | (DEFAULTGUIDECOLOR & 0xff); sp_nv_read_opacity(value, &this->guidecolor); - for(auto guide : this->guides) { + for (auto guide : this->guides) { guide->setColor(this->guidecolor); guide->readAttr(SPAttr::INKSCAPE_COLOR); } this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::GUIDEHICOLOR: + case SPAttr::GUIDEHICOLOR: this->guidehicolor = (this->guidehicolor & 0xff) | (DEFAULTGUIDEHICOLOR & 0xffffff00); if (value) { this->guidehicolor = (this->guidehicolor & 0xff) | sp_svg_read_color(value, this->guidehicolor); } - for(auto guide : this->guides) { - guide->setHiColor(this->guidehicolor); + for (auto guide : this->guides) { + guide->setHiColor(this->guidehicolor); } this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::GUIDEHIOPACITY: + case SPAttr::GUIDEHIOPACITY: this->guidehicolor = (this->guidehicolor & 0xffffff00) | (DEFAULTGUIDEHICOLOR & 0xff); sp_nv_read_opacity(value, &this->guidehicolor); - for(auto guide : this->guides) { - guide->setHiColor(this->guidehicolor); + for (auto guide : this->guides) { + guide->setHiColor(this->guidehicolor); } this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::SHOWBORDER: - this->showborder = (value) ? sp_str_to_bool (value) : TRUE; + case SPAttr::SHOWBORDER: + this->showborder = (value) ? sp_str_to_bool(value) : TRUE; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::BORDERLAYER: + case SPAttr::BORDERLAYER: this->borderlayer = SP_BORDER_LAYER_BOTTOM; - if (value && !strcasecmp(value, "true")) this->borderlayer = SP_BORDER_LAYER_TOP; + if (value && !strcasecmp(value, "true")) + this->borderlayer = SP_BORDER_LAYER_TOP; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::BORDERCOLOR: + case SPAttr::BORDERCOLOR: this->bordercolor = (this->bordercolor & 0xff) | (DEFAULTBORDERCOLOR & 0xffffff00); if (value) { - this->bordercolor = (this->bordercolor & 0xff) | sp_svg_read_color (value, this->bordercolor); + this->bordercolor = (this->bordercolor & 0xff) | sp_svg_read_color(value, this->bordercolor); } this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::BORDEROPACITY: + case SPAttr::BORDEROPACITY: this->bordercolor = (this->bordercolor & 0xffffff00) | (DEFAULTBORDERCOLOR & 0xff); sp_nv_read_opacity(value, &this->bordercolor); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::PAGECOLOR: + case SPAttr::PAGECOLOR: this->pagecolor = (this->pagecolor & 0xff) | (DEFAULTPAGECOLOR & 0xffffff00); if (value) { this->pagecolor = (this->pagecolor & 0xff) | sp_svg_read_color(value, this->pagecolor); } this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_PAGECHECKERBOARD: - this->pagecheckerboard = (value) ? sp_str_to_bool (value) : false; + case SPAttr::INKSCAPE_PAGECHECKERBOARD: + this->pagecheckerboard = (value) ? sp_str_to_bool(value) : false; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_PAGEOPACITY: + case SPAttr::INKSCAPE_PAGEOPACITY: this->pagecolor = (this->pagecolor & 0xffffff00) | (DEFAULTPAGECOLOR & 0xff); sp_nv_read_opacity(value, &this->pagecolor); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_PAGESHADOW: - this->pageshadow = value? atoi(value) : 2; // 2 is the default + case SPAttr::INKSCAPE_PAGESHADOW: + this->pageshadow = value ? atoi(value) : 2; // 2 is the default this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::SHOWPAGESHADOW: + case SPAttr::SHOWPAGESHADOW: this->showpageshadow = (value) ? sp_str_to_bool(value) : TRUE; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_ZOOM: + case SPAttr::INKSCAPE_ZOOM: this->zoom = value ? g_ascii_strtod(value, nullptr) : 0; // zero means not set this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_ROTATION: + case SPAttr::INKSCAPE_ROTATION: this->rotation = value ? g_ascii_strtod(value, nullptr) : 0; // zero means not set this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_CX: + case SPAttr::INKSCAPE_CX: this->cx = value ? g_ascii_strtod(value, nullptr) : HUGE_VAL; // HUGE_VAL means not set this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_CY: + case SPAttr::INKSCAPE_CY: this->cy = value ? g_ascii_strtod(value, nullptr) : HUGE_VAL; // HUGE_VAL means not set this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_WINDOW_WIDTH: - this->window_width = value? atoi(value) : -1; // -1 means not set + case SPAttr::INKSCAPE_WINDOW_WIDTH: + this->window_width = value ? atoi(value) : -1; // -1 means not set this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_WINDOW_HEIGHT: + case SPAttr::INKSCAPE_WINDOW_HEIGHT: this->window_height = value ? atoi(value) : -1; // -1 means not set this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_WINDOW_X: + case SPAttr::INKSCAPE_WINDOW_X: this->window_x = value ? atoi(value) : 0; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_WINDOW_Y: + case SPAttr::INKSCAPE_WINDOW_Y: this->window_y = value ? atoi(value) : 0; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_WINDOW_MAXIMIZED: + case SPAttr::INKSCAPE_WINDOW_MAXIMIZED: this->window_maximized = value ? atoi(value) : 0; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_GLOBAL: + case SPAttr::INKSCAPE_SNAP_GLOBAL: this->snap_manager.snapprefs.setSnapEnabledGlobally(value ? sp_str_to_bool(value) : global_snapping); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_BBOX: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_BBOX_CATEGORY, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_BBOX: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_BBOX_CATEGORY, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_NODE: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_NODE_CATEGORY, value ? sp_str_to_bool(value) : TRUE); + case SPAttr::INKSCAPE_SNAP_NODE: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_NODE_CATEGORY, + value ? sp_str_to_bool(value) : TRUE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_OTHERS: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_OTHERS_CATEGORY, value ? sp_str_to_bool(value) : TRUE); + case SPAttr::INKSCAPE_SNAP_OTHERS: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_OTHERS_CATEGORY, + value ? sp_str_to_bool(value) : TRUE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_ROTATION_CENTER: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_ROTATION_CENTER, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_ROTATION_CENTER: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_ROTATION_CENTER, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_GRID: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_GRID, value ? sp_str_to_bool(value) : TRUE); + case SPAttr::INKSCAPE_SNAP_GRID: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_GRID, + value ? sp_str_to_bool(value) : TRUE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_GUIDE: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_GUIDE, value ? sp_str_to_bool(value) : TRUE); + case SPAttr::INKSCAPE_SNAP_GUIDE: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_GUIDE, + value ? sp_str_to_bool(value) : TRUE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_NODE_SMOOTH: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_NODE_SMOOTH, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_NODE_SMOOTH: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_NODE_SMOOTH, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_LINE_MIDPOINT: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_LINE_MIDPOINT, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_LINE_MIDPOINT: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_LINE_MIDPOINT, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_OBJECT_MIDPOINT: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_OBJECT_MIDPOINT, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_OBJECT_MIDPOINT: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_OBJECT_MIDPOINT, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_TEXT_BASELINE: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_TEXT_BASELINE, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_TEXT_BASELINE: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_TEXT_BASELINE, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_BBOX_EDGE_MIDPOINT: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_BBOX_EDGE_MIDPOINT, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_BBOX_EDGE_MIDPOINT: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_BBOX_EDGE_MIDPOINT, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_BBOX_MIDPOINT: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_BBOX_MIDPOINT, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_BBOX_MIDPOINT: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_BBOX_MIDPOINT, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_PATH_INTERSECTION: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_PATH_INTERSECTION, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_PATH_INTERSECTION: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_PATH_INTERSECTION, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_PATH: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_PATH, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_PATH: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_PATH, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_PERP: + case SPAttr::INKSCAPE_SNAP_PERP: this->snap_manager.snapprefs.setSnapPerp(value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_TANG: + case SPAttr::INKSCAPE_SNAP_TANG: this->snap_manager.snapprefs.setSnapTang(value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_PATH_CLIP: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_PATH_CLIP, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_PATH_CLIP: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_PATH_CLIP, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_PATH_MASK: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_PATH_MASK, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_PATH_MASK: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_PATH_MASK, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_NODE_CUSP: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_NODE_CUSP, value ? sp_str_to_bool(value) : TRUE); + case SPAttr::INKSCAPE_SNAP_NODE_CUSP: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_NODE_CUSP, + value ? sp_str_to_bool(value) : TRUE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_BBOX_EDGE: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_BBOX_EDGE, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_BBOX_EDGE: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_BBOX_EDGE, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_BBOX_CORNER: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_BBOX_CORNER, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_BBOX_CORNER: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_BBOX_CORNER, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_SNAP_PAGE_BORDER: - this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_PAGE_BORDER, value ? sp_str_to_bool(value) : FALSE); + case SPAttr::INKSCAPE_SNAP_PAGE_BORDER: + this->snap_manager.snapprefs.setTargetSnappable(Inkscape::SNAPTARGET_PAGE_BORDER, + value ? sp_str_to_bool(value) : FALSE); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_CURRENT_LAYER: + case SPAttr::INKSCAPE_CURRENT_LAYER: this->default_layer_id = value ? g_quark_from_string(value) : 0; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_CONNECTOR_SPACING: - this->connector_spacing = value ? g_ascii_strtod(value, nullptr) : - defaultConnSpacing; + case SPAttr::INKSCAPE_CONNECTOR_SPACING: + this->connector_spacing = value ? g_ascii_strtod(value, nullptr) : defaultConnSpacing; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - case SPAttr::INKSCAPE_DOCUMENT_UNITS: { + case SPAttr::INKSCAPE_DOCUMENT_UNITS: { /* The default display unit if the document doesn't override this: e.g. for files saved as * `plain SVG', or non-inkscape files, or files created by an inkscape 0.40 & * earlier. @@ -554,68 +581,66 @@ void SPNamedView::set(SPAttr key, const gchar* value) { if (value && document->getRoot()->viewBox_set) { Inkscape::Util::Unit const *const req_unit = unit_table.getUnit(value); - if ( !unit_table.hasUnit(value) ) { + if (!unit_table.hasUnit(value)) { g_warning("Unrecognized unit `%s'", value); /* fixme: Document errors should be reported in the status bar or * the like (e.g. as per * http://www.w3.org/TR/SVG11/implnote.html#ErrorProcessing); g_log * should be only for programmer errors. */ - } else if ( req_unit->isAbsolute() ) { + } else if (req_unit->isAbsolute()) { new_unit = req_unit; } else { - g_warning("Document units must be absolute like `mm', `pt' or `px', but found `%s'", - value); + g_warning("Document units must be absolute like `mm', `pt' or `px', but found `%s'", value); /* fixme: Don't use g_log (see above). */ } } this->display_units = new_unit; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - } - case SPAttr::UNITS: { - // Only used in "Custom size" section of Document Properties dialog + } + case SPAttr::UNITS: { + // Only used in "Custom size" section of Document Properties dialog Inkscape::Util::Unit const *new_unit = nullptr; if (value) { Inkscape::Util::Unit const *const req_unit = unit_table.getUnit(value); - if ( !unit_table.hasUnit(value) ) { + if (!unit_table.hasUnit(value)) { g_warning("Unrecognized unit `%s'", value); /* fixme: Document errors should be reported in the status bar or * the like (e.g. as per * http://www.w3.org/TR/SVG11/implnote.html#ErrorProcessing); g_log * should be only for programmer errors. */ - } else if ( req_unit->isAbsolute() ) { + } else if (req_unit->isAbsolute()) { new_unit = req_unit; } else { - g_warning("Document units must be absolute like `mm', `pt' or `px', but found `%s'", - value); + g_warning("Document units must be absolute like `mm', `pt' or `px', but found `%s'", value); /* fixme: Don't use g_log (see above). */ } } this->page_size_units = new_unit; this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - } - case SPAttr::INKSCAPE_LOCKGUIDES: + } + case SPAttr::INKSCAPE_LOCKGUIDES: this->lockguides = value ? sp_str_to_bool(value) : FALSE; this->lockGuides(); this->requestModified(SP_OBJECT_MODIFIED_FLAG); break; - default: + default: SPObjectGroup::set(key, value); break; } } /** -* add a grid item from SVG-repr. Check if this namedview already has a gridobject for this one! If desktop=null, add grid-canvasitem to all desktops of this namedview, -* otherwise only add it to the specified desktop. -*/ -static Inkscape::CanvasGrid* -sp_namedview_add_grid(SPNamedView *nv, Inkscape::XML::Node *repr, SPDesktop *desktop) { - Inkscape::CanvasGrid* grid = nullptr; - //check if namedview already has an object for this grid - for(auto it : nv->grids) { + * add a grid item from SVG-repr. Check if this namedview already has a gridobject for this one! If desktop=null, add + * grid-canvasitem to all desktops of this namedview, otherwise only add it to the specified desktop. + */ +static Inkscape::CanvasGrid *sp_namedview_add_grid(SPNamedView *nv, Inkscape::XML::Node *repr, SPDesktop *desktop) +{ + Inkscape::CanvasGrid *grid = nullptr; + // check if namedview already has an object for this grid + for (auto it : nv->grids) { if (repr == it->repr) { grid = it; break; @@ -623,7 +648,7 @@ sp_namedview_add_grid(SPNamedView *nv, Inkscape::XML::Node *repr, SPDesktop *des } if (!grid) { - //create grid object + // create grid object Inkscape::GridType gridtype = Inkscape::CanvasGrid::getGridTypeFromSVGName(repr->attribute("type")); if (!nv->document) { g_warning("sp_namedview_add_grid - how come doc is null here?!"); @@ -634,41 +659,42 @@ sp_namedview_add_grid(SPNamedView *nv, Inkscape::XML::Node *repr, SPDesktop *des } if (!desktop) { - //add canvasitem to all desktops - for(auto view : nv->views) { + // add canvasitem to all desktops + for (auto view : nv->views) { grid->createCanvasItem(view); } } else { - //add canvasitem only for specified desktop + // add canvasitem only for specified desktop grid->createCanvasItem(desktop); } return grid; } -void SPNamedView::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { +void SPNamedView::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ SPObjectGroup::child_added(child, ref); if (!strcmp(child->name(), "inkscape:grid")) { sp_namedview_add_grid(this, child, nullptr); } else { SPObject *no = this->document->getObjectByRepr(child); - if ( !SP_IS_OBJECT(no) ) { + if (!SP_IS_OBJECT(no)) { return; } if (SP_IS_GUIDE(no)) { - SPGuide *g = (SPGuide *) no; + SPGuide *g = (SPGuide *)no; this->guides.push_back(g); - //g_object_set(G_OBJECT(g), "color", this->guidecolor, "hicolor", this->guidehicolor, NULL); + // g_object_set(G_OBJECT(g), "color", this->guidecolor, "hicolor", this->guidehicolor, NULL); g->setColor(this->guidecolor); g->setHiColor(this->guidehicolor); g->readAttr(SPAttr::INKSCAPE_COLOR); if (this->editable) { - for(auto view : this->views) { - g->SPGuide::showSPGuide(view->guides, (GCallback) sp_dt_guide_event); + for (auto view : this->views) { + g->SPGuide::showSPGuide(view->guides, (GCallback)sp_dt_guide_event); if (view->guides_active) { g->sensitize(view->getCanvas(), TRUE); @@ -681,31 +707,31 @@ void SPNamedView::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *r } } -void SPNamedView::remove_child(Inkscape::XML::Node *child) { +void SPNamedView::remove_child(Inkscape::XML::Node *child) +{ if (!strcmp(child->name(), "inkscape:grid")) { - for(std::vector::iterator it=this->grids.begin();it!=this->grids.end();++it ) { - if ( (*it)->repr == child ) { + for (std::vector::iterator it = this->grids.begin(); it != this->grids.end(); ++it) { + if ((*it)->repr == child) { delete (*it); this->grids.erase(it); break; } } } else { - for(std::vector::iterator it=this->guides.begin();it!=this->guides.end();++it ) { - if ( (*it)->getRepr() == child ) { - this->guides.erase(it); + for (std::vector::iterator it = this->guides.begin(); it != this->guides.end(); ++it) { + if ((*it)->getRepr() == child) { + this->guides.erase(it); break; - } + } } } SPObjectGroup::remove_child(child); } -Inkscape::XML::Node* SPNamedView::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - if ( ( flags & SP_OBJECT_WRITE_EXT ) && - repr != this->getRepr() ) - { +Inkscape::XML::Node *SPNamedView::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + if ((flags & SP_OBJECT_WRITE_EXT) && repr != this->getRepr()) { if (repr) { repr->mergeFrom(this->getRepr(), "id"); } else { @@ -718,8 +744,8 @@ Inkscape::XML::Node* SPNamedView::write(Inkscape::XML::Document *xml_doc, Inksca void SPNamedView::show(SPDesktop *desktop) { - for(auto guide : this->guides) { - guide->showSPGuide( desktop->guides, (GCallback) sp_dt_guide_event); + for (auto guide : this->guides) { + guide->showSPGuide(desktop->guides, (GCallback)sp_dt_guide_event); if (desktop->guides_active) { guide->sensitize(desktop->getCanvas(), TRUE); } @@ -731,7 +757,7 @@ void SPNamedView::show(SPDesktop *desktop) // generate grids specified in SVG: Inkscape::XML::Node *repr = this->getRepr(); if (repr) { - for (Inkscape::XML::Node * child = repr->firstChild() ; child != nullptr; child = child->next() ) { + for (Inkscape::XML::Node *child = repr->firstChild(); child != nullptr; child = child->next()) { if (!strcmp(child->name(), "inkscape:grid")) { sp_namedview_add_grid(this, child, desktop); } @@ -764,8 +790,7 @@ void sp_namedview_window_from_document(SPDesktop *desktop) gint py = prefs->getInt("/desktop/geometry/y", -1); gint full = prefs->getBool("/desktop/geometry/fullscreen"); gint maxed = prefs->getBool("/desktop/geometry/maximized"); - if (pw>0 && ph>0) { - + if (pw > 0 && ph > 0) { Gdk::Rectangle monitor_geometry = Inkscape::UI::get_monitor_geometry_at_point(px, py); pw = std::min(pw, monitor_geometry.get_width()); ph = std::min(ph, monitor_geometry.get_height()); @@ -789,7 +814,7 @@ void sp_namedview_window_from_document(SPDesktop *desktop) if (window_geometry == PREFS_WINDOW_GEOMETRY_FILE && !new_document) { Gdk::Rectangle monitor_geometry = Inkscape::UI::get_monitor_geometry_at_point(nv->window_x, nv->window_y); w = MIN(monitor_geometry.get_width(), nv->window_width); - h = MIN(monitor_geometry.get_height(), nv->window_height); + h = MIN(monitor_geometry.get_height(), nv->window_height); move_to_screen = true; } else if (default_size == PREFS_WINDOW_SIZE_LARGE) { Gdk::Rectangle monitor_geometry = Inkscape::UI::get_monitor_geometry_at_window(win->get_window()); @@ -801,7 +826,7 @@ void sp_namedview_window_from_document(SPDesktop *desktop) // don't set size (i.e. keep the gtk+ default, which will be the natural size) // unless gtk+ decided it would be a good idea to show a window that is larger than the screen Gdk::Rectangle monitor_geometry = Inkscape::UI::get_monitor_geometry_at_window(win->get_window()); - int monitor_width = monitor_geometry.get_width(); + int monitor_width = monitor_geometry.get_width(); int monitor_height = monitor_geometry.get_height(); int window_width, window_height; win->get_size(window_width, window_height); @@ -832,10 +857,9 @@ void sp_namedview_window_from_document(SPDesktop *desktop) void sp_namedview_zoom_and_view_from_document(SPDesktop *desktop) { SPNamedView *nv = desktop->namedview; - if (nv->zoom != 0 && nv->zoom != HUGE_VAL && !std::isnan(nv->zoom) - && nv->cx != HUGE_VAL && !std::isnan(nv->cx) - && nv->cy != HUGE_VAL && !std::isnan(nv->cy)) { - desktop->zoom_absolute_center_point( Geom::Point(nv->cx, nv->cy), nv->zoom ); + if (nv->zoom != 0 && nv->zoom != HUGE_VAL && !std::isnan(nv->zoom) && nv->cx != HUGE_VAL && !std::isnan(nv->cx) && + nv->cy != HUGE_VAL && !std::isnan(nv->cy)) { + desktop->zoom_absolute_center_point(Geom::Point(nv->cx, nv->cy), nv->zoom); } else if (desktop->getDocument()) { // document without saved zoom, zoom to its page desktop->zoom_page(); } @@ -843,17 +867,17 @@ void sp_namedview_zoom_and_view_from_document(SPDesktop *desktop) Geom::Point p; if (nv->cx != HUGE_VAL && !std::isnan(nv->cx) && nv->cy != HUGE_VAL && !std::isnan(nv->cy)) { p = Geom::Point(nv->cx, nv->cy); - }else{ + } else { p = desktop->current_center(); } desktop->rotate_absolute_keep_point(p, nv->rotation * M_PI / 180.0); } } -void SPNamedView::writeNewGrid(SPDocument *document,int gridtype) +void SPNamedView::writeNewGrid(SPDocument *document, int gridtype) { g_assert(this->getRepr() != nullptr); - Inkscape::CanvasGrid::writeNewGridToRepr(this->getRepr(),document,static_cast(gridtype)); + Inkscape::CanvasGrid::writeNewGridToRepr(this->getRepr(), document, static_cast(gridtype)); } bool SPNamedView::getSnapGlobal() const @@ -867,21 +891,21 @@ void SPNamedView::setSnapGlobal(bool v) sp_repr_set_boolean(this->getRepr(), "inkscape:snap-global", v); } -void sp_namedview_update_layers_from_document (SPDesktop *desktop) +void sp_namedview_update_layers_from_document(SPDesktop *desktop) { SPObject *layer = nullptr; SPDocument *document = desktop->doc(); SPNamedView *nv = desktop->namedview; - if ( nv->default_layer_id != 0 ) { + if (nv->default_layer_id != 0) { layer = document->getObjectById(g_quark_to_string(nv->default_layer_id)); } // don't use that object if it's not at least group - if ( !layer || !SP_IS_GROUP(layer) ) { + if (!layer || !SP_IS_GROUP(layer)) { layer = nullptr; } // if that didn't work out, look for the topmost layer if (!layer) { - for (auto& iter: document->getRoot()->children) { + for (auto &iter : document->getRoot()->children) { if (desktop->isLayer(&iter)) { layer = &iter; } @@ -935,39 +959,39 @@ void sp_namedview_document_from_window(SPDesktop *desktop) void SPNamedView::hide(SPDesktop const *desktop) { g_assert(desktop != nullptr); - g_assert(std::find(views.begin(),views.end(),desktop)!=views.end()); - for(auto & guide : this->guides) { + g_assert(std::find(views.begin(), views.end(), desktop) != views.end()); + for (auto &guide : this->guides) { guide->hideSPGuide(desktop->getCanvas()); } - views.erase(std::remove(views.begin(),views.end(),desktop),views.end()); + views.erase(std::remove(views.begin(), views.end(), desktop), views.end()); } -void SPNamedView::activateGuides(void* desktop, bool active) +void SPNamedView::activateGuides(void *desktop, bool active) { g_assert(desktop != nullptr); - g_assert(std::find(views.begin(),views.end(),desktop)!=views.end()); + g_assert(std::find(views.begin(), views.end(), desktop) != views.end()); - SPDesktop *dt = static_cast(desktop); - for(auto & guide : this->guides) { + SPDesktop *dt = static_cast(desktop); + for (auto &guide : this->guides) { guide->sensitize(dt->getCanvas(), active); } } static void sp_namedview_setup_guides(SPNamedView *nv) { - for(std::vector::iterator it=nv->guides.begin();it!=nv->guides.end();++it ) { + for (std::vector::iterator it = nv->guides.begin(); it != nv->guides.end(); ++it) { sp_namedview_show_single_guide(*it, nv->showguides); } } static void sp_namedview_lock_guides(SPNamedView *nv) { - for(std::vector::iterator it=nv->guides.begin();it!=nv->guides.end();++it ) { + for (std::vector::iterator it = nv->guides.begin(); it != nv->guides.end(); ++it) { sp_namedview_lock_single_guide(*it, nv->lockguides); } } -static void sp_namedview_show_single_guide(SPGuide* guide, bool show) +static void sp_namedview_show_single_guide(SPGuide *guide, bool show) { if (show) { guide->showSPGuide(); @@ -976,7 +1000,7 @@ static void sp_namedview_show_single_guide(SPGuide* guide, bool show) } } -static void sp_namedview_lock_single_guide(SPGuide* guide, bool locked) +static void sp_namedview_lock_single_guide(SPGuide *guide, bool locked) { guide->set_locked(locked, true); } @@ -1006,7 +1030,7 @@ void sp_namedview_toggle_guides(SPDocument *doc, SPNamedView *namedview) doc->setModifiedSinceSave(); } -void sp_namedview_guides_toggle_lock(SPDocument *doc, SPNamedView * namedview) +void sp_namedview_guides_toggle_lock(SPDocument *doc, SPNamedView *namedview) { unsigned int v; Inkscape::XML::Node *repr = namedview->getRepr(); @@ -1025,7 +1049,7 @@ void sp_namedview_guides_toggle_lock(SPDocument *doc, SPNamedView * namedview) doc->setModifiedSinceSave(); } -void sp_namedview_show_grids(SPNamedView * namedview, bool show, bool dirty_document) +void sp_namedview_show_grids(SPNamedView *namedview, bool show, bool dirty_document) { namedview->grids_visible = show; @@ -1066,9 +1090,7 @@ std::vector const SPNamedView::getViewList() const static gboolean sp_str_to_bool(const gchar *str) { if (str) { - if (!g_ascii_strcasecmp(str, "true") || - !g_ascii_strcasecmp(str, "yes") || - !g_ascii_strcasecmp(str, "y") || + if (!g_ascii_strcasecmp(str, "true") || !g_ascii_strcasecmp(str, "yes") || !g_ascii_strcasecmp(str, "y") || (atoi(str) != 0)) { return TRUE; } @@ -1090,7 +1112,7 @@ static gboolean sp_nv_read_opacity(const gchar *str, guint32 *color) } v = CLAMP(v, 0.0, 1.0); - *color = (*color & 0xffffff00) | (guint32) floor(v * 255.9999); + *color = (*color & 0xffffff00) | (guint32)floor(v * 255.9999); return TRUE; } @@ -1103,19 +1125,20 @@ SPNamedView *sp_document_namedview(SPDocument *document, const gchar *id) g_assert(nv != nullptr); if (id == nullptr) { - return (SPNamedView *) nv; + return (SPNamedView *)nv; } while (nv && strcmp(nv->getId(), id)) { nv = sp_item_group_get_child_by_name(document->getRoot(), nv, "sodipodi:namedview"); } - return (SPNamedView *) nv; + return (SPNamedView *)nv; } SPNamedView const *sp_document_namedview(SPDocument const *document, const gchar *id) { - return sp_document_namedview(const_cast(document), id); // use a const_cast here to avoid duplicating code + return sp_document_namedview(const_cast(document), + id); // use a const_cast here to avoid duplicating code } void SPNamedView::setGuides(bool v) @@ -1155,20 +1178,17 @@ void SPNamedView::lockGuides() * otherwise. Used for percentage margins. * \return the margin size in px, else 0.0 if anything is invalid. */ -double SPNamedView::getMarginLength(gchar const * const key, - Inkscape::Util::Unit const * const margin_units, - Inkscape::Util::Unit const * const return_units, - double const width, - double const height, - bool const use_width) +double SPNamedView::getMarginLength(gchar const *const key, Inkscape::Util::Unit const *const margin_units, + Inkscape::Util::Unit const *const return_units, double const width, + double const height, bool const use_width) { double value; static Inkscape::Util::Unit const *percent = unit_table.getUnit("%"); - if(!this->storeAsDouble(key,&value)) { + if (!this->storeAsDouble(key, &value)) { return 0.0; } if (*margin_units == *percent) { - return (use_width)? width * value : height * value; + return (use_width) ? width * value : height * value; } if (!margin_units->compatibleWith(return_units)) { return 0.0; @@ -1180,7 +1200,7 @@ double SPNamedView::getMarginLength(gchar const * const key, * Returns namedview's default unit. * If no default unit is set, "px" is returned */ -Inkscape::Util::Unit const * SPNamedView::getDisplayUnit() const +Inkscape::Util::Unit const *SPNamedView::getDisplayUnit() const { return display_units ? display_units : unit_table.getUnit("px"); } @@ -1188,9 +1208,9 @@ Inkscape::Util::Unit const * SPNamedView::getDisplayUnit() const /** * Returns the first grid it could find that isEnabled(). Returns NULL, if none is enabled */ -Inkscape::CanvasGrid * sp_namedview_get_first_enabled_grid(SPNamedView *namedview) +Inkscape::CanvasGrid *sp_namedview_get_first_enabled_grid(SPNamedView *namedview) { - for(auto grid : namedview->grids) { + for (auto grid : namedview->grids) { if (grid->isEnabled()) return grid; } @@ -1198,8 +1218,9 @@ Inkscape::CanvasGrid * sp_namedview_get_first_enabled_grid(SPNamedView *namedvie return nullptr; } -void SPNamedView::translateGuides(Geom::Translate const &tr) { - for(auto & it : this->guides) { +void SPNamedView::translateGuides(Geom::Translate const &tr) +{ + for (auto &it : this->guides) { SPGuide &guide = *it; Geom::Point point_on_line = guide.getPoint(); point_on_line *= tr; @@ -1207,19 +1228,20 @@ void SPNamedView::translateGuides(Geom::Translate const &tr) { } } -void SPNamedView::translateGrids(Geom::Translate const &tr) { - for(auto & grid : this->grids) { +void SPNamedView::translateGrids(Geom::Translate const &tr) +{ + for (auto &grid : this->grids) { grid->setOrigin(grid->origin * tr); } } -void SPNamedView::scrollAllDesktops(double dx, double dy, bool is_scrolling) { - for(auto & view : this->views) { +void SPNamedView::scrollAllDesktops(double dx, double dy, bool is_scrolling) +{ + for (auto &view : this->views) { view->scroll_relative_in_svg_coords(dx, dy, is_scrolling); } } - /* Local Variables: mode:c++ diff --git a/src/object/sp-namedview.h b/src/object/sp-namedview.h index 465a2d79b5dba4887fcb54667bfd547a4664363b..2de3e7ebc1148a2207c0cdf4ea68a24ec188eca3 100644 --- a/src/object/sp-namedview.h +++ b/src/object/sp-namedview.h @@ -15,34 +15,37 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#define SP_NAMEDVIEW(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_NAMEDVIEW(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_NAMEDVIEW(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_NAMEDVIEW(obj) (dynamic_cast((SPObject *)obj) != NULL) + +#include -#include "sp-object-group.h" -#include "snap.h" #include "document.h" +#include "snap.h" +#include "sp-object-group.h" #include "util/units.h" -#include namespace Inkscape { - class CanvasGrid; - namespace Util { - class Unit; - } +class CanvasGrid; +namespace Util { +class Unit; } +} // namespace Inkscape typedef unsigned int guint32; typedef guint32 GQuark; -enum { +enum +{ SP_BORDER_LAYER_BOTTOM, SP_BORDER_LAYER_TOP }; -class SPNamedView : public SPObjectGroup { +class SPNamedView : public SPObjectGroup +{ public: - SPNamedView(); - ~SPNamedView() override; + SPNamedView(); + ~SPNamedView() override; unsigned int editable : 1; unsigned int showguides : 1; @@ -67,8 +70,8 @@ public: bool grids_visible; Inkscape::Util::Unit const *display_units; // Units used for the UI (*not* the same as units of SVG coordinates) - Inkscape::Util::Unit const *page_size_units; // Only used in "Custom size" part of Document Properties dialog - + Inkscape::Util::Unit const *page_size_units; // Only used in "Custom size" part of Document Properties dialog + GQuark default_layer_id; double connector_spacing; @@ -86,16 +89,16 @@ public: void show(SPDesktop *desktop); void hide(SPDesktop const *desktop); - void activateGuides(void* desktop, bool active); + void activateGuides(void *desktop, bool active); char const *getName() const; unsigned int getViewCount(); std::vector const getViewList() const; - Inkscape::Util::Unit const * getDisplayUnit() const; + Inkscape::Util::Unit const *getDisplayUnit() const; void translateGuides(Geom::Translate const &translation); void translateGrids(Geom::Translate const &translation); void scrollAllDesktops(double dx, double dy, bool is_scrolling); - void writeNewGrid(SPDocument *document,int gridtype); + void writeNewGrid(SPDocument *document, int gridtype); bool getSnapGlobal() const; void setSnapGlobal(bool v); void setGuides(bool v); @@ -103,38 +106,38 @@ public: void lockGuides(); private: - double getMarginLength(gchar const * const key,Inkscape::Util::Unit const * const margin_units,Inkscape::Util::Unit const * const return_units,double const width,double const height,bool const use_width); + double getMarginLength(gchar const *const key, Inkscape::Util::Unit const *const margin_units, + Inkscape::Util::Unit const *const return_units, double const width, double const height, + bool const use_width); friend class SPDocument; protected: - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; - void set(SPAttr key, char const* value) override; + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, char const *value) override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; - SPNamedView *sp_document_namedview(SPDocument *document, char const *name); SPNamedView const *sp_document_namedview(SPDocument const *document, char const *name); void sp_namedview_window_from_document(SPDesktop *desktop); void sp_namedview_zoom_and_view_from_document(SPDesktop *desktop); void sp_namedview_document_from_window(SPDesktop *desktop); -void sp_namedview_update_layers_from_document (SPDesktop *desktop); +void sp_namedview_update_layers_from_document(SPDesktop *desktop); void sp_namedview_toggle_guides(SPDocument *doc, SPNamedView *namedview); void sp_namedview_guides_toggle_lock(SPDocument *doc, SPNamedView *namedview); void sp_namedview_show_grids(SPNamedView *namedview, bool show, bool dirty_document); -Inkscape::CanvasGrid * sp_namedview_get_first_enabled_grid(SPNamedView *namedview); - +Inkscape::CanvasGrid *sp_namedview_get_first_enabled_grid(SPNamedView *namedview); #endif /* !INKSCAPE_SP_NAMEDVIEW_H */ - /* Local Variables: mode:c++ diff --git a/src/object/sp-object-group.cpp b/src/object/sp-object-group.cpp index 09772872d1a818730c7f422319f4cbfed1a82c74..bd0334f766edad21d8e88a85711467d1d04abe4b 100644 --- a/src/object/sp-object-group.cpp +++ b/src/object/sp-object-group.cpp @@ -14,55 +14,59 @@ */ #include "sp-object-group.h" -#include "xml/repr.h" + #include "document.h" +#include "xml/repr.h" -SPObjectGroup::SPObjectGroup() : SPObject() { -} +SPObjectGroup::SPObjectGroup() + : SPObject() +{} SPObjectGroup::~SPObjectGroup() = default; -void SPObjectGroup::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { - SPObject::child_added(child, ref); +void SPObjectGroup::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ + SPObject::child_added(child, ref); - this->requestModified(SP_OBJECT_MODIFIED_FLAG); + this->requestModified(SP_OBJECT_MODIFIED_FLAG); } +void SPObjectGroup::remove_child(Inkscape::XML::Node *child) +{ + SPObject::remove_child(child); -void SPObjectGroup::remove_child(Inkscape::XML::Node *child) { - SPObject::remove_child(child); - - this->requestModified(SP_OBJECT_MODIFIED_FLAG); + this->requestModified(SP_OBJECT_MODIFIED_FLAG); } +void SPObjectGroup::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, + Inkscape::XML::Node *new_ref) +{ + SPObject::order_changed(child, old_ref, new_ref); -void SPObjectGroup::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref) { - SPObject::order_changed(child, old_ref, new_ref); - - this->requestModified(SP_OBJECT_MODIFIED_FLAG); + this->requestModified(SP_OBJECT_MODIFIED_FLAG); } - -Inkscape::XML::Node *SPObjectGroup::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPObjectGroup::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if (flags & SP_OBJECT_WRITE_BUILD) { if (!repr) { repr = xml_doc->createElement("svg:g"); } std::vector l; - for (auto& child: children) { + for (auto &child : children) { Inkscape::XML::Node *crepr = child.updateRepr(xml_doc, nullptr, flags); if (crepr) { l.push_back(crepr); } } - for (auto i=l.rbegin();i!=l.rend();++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { + for (auto &child : children) { child.updateRepr(flags); } } diff --git a/src/object/sp-object-group.h b/src/object/sp-object-group.h index 604c9ba6d9c38eea32d8f6482b9f1c10127f14fb..154fcb764d84cdb5d44db79986d3d54e155cded5 100644 --- a/src/object/sp-object-group.h +++ b/src/object/sp-object-group.h @@ -17,21 +17,23 @@ #include "sp-object.h" -#define SP_OBJECTGROUP(obj) (dynamic_cast((SPObject*)obj)) -#define SP_IS_OBJECTGROUP(obj) (dynamic_cast((SPObject*)obj) != NULL) +#define SP_OBJECTGROUP(obj) (dynamic_cast((SPObject *)obj)) +#define SP_IS_OBJECTGROUP(obj) (dynamic_cast((SPObject *)obj) != NULL) -class SPObjectGroup : public SPObject { +class SPObjectGroup : public SPObject +{ public: - SPObjectGroup(); - ~SPObjectGroup() override; + SPObjectGroup(); + ~SPObjectGroup() override; protected: - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; - void order_changed(Inkscape::XML::Node* child, Inkscape::XML::Node* old, Inkscape::XML::Node* new_repr) override; + void order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old, Inkscape::XML::Node *new_repr) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; #endif // SEEN_SP_OBJECTGROUP_H diff --git a/src/object/sp-object.cpp b/src/object/sp-object.cpp index 89e0da2329c7496c37307be3af1048c970346822..aa01f97a2e976b121543aabb5948092fd7d1fe4b 100644 --- a/src/object/sp-object.cpp +++ b/src/object/sp-object.cpp @@ -16,60 +16,56 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include #include #include #include -#include - -#include "helper/sp-marshal.h" -#include "xml/node-event-vector.h" -#include "attributes.h" #include "attribute-rel-util.h" +#include "attributes.h" #include "color-profile.h" +#include "debug/demangle.h" +#include "debug/event-tracker.h" +#include "debug/simple-event.h" #include "document.h" -#include "preferences.h" -#include "style.h" +#include "helper/sp-marshal.h" #include "live_effects/lpeobject.h" +#include "preferences.h" #include "sp-factory.h" #include "sp-paint-server.h" #include "sp-root.h" -#include "sp-style-elem.h" #include "sp-script.h" +#include "sp-style-elem.h" #include "streq.h" #include "strneq.h" -#include "xml/node-fns.h" -#include "debug/event-tracker.h" -#include "debug/simple-event.h" -#include "debug/demangle.h" +#include "style.h" #include "util/format.h" #include "util/longest-common-suffix.h" +#include "xml/node-event-vector.h" +#include "xml/node-fns.h" #define noSP_OBJECT_DEBUG_CASCADE #define noSP_OBJECT_DEBUG #ifdef SP_OBJECT_DEBUG -# define debug(f, a...) { g_print("%s(%d) %s:", \ - __FILE__,__LINE__,__FUNCTION__); \ - g_print(f, ## a); \ - g_print("\n"); \ - } +#define debug(f, a...) \ + { \ + g_print("%s(%d) %s:", __FILE__, __LINE__, __FUNCTION__); \ + g_print(f, ##a); \ + g_print("\n"); \ + } #else -# define debug(f, a...) /* */ +#define debug(f, a...) /* */ #endif // Define to enable indented tracing of SPObject. //#define OBJECT_TRACE unsigned SPObject::indent_level = 0; -Inkscape::XML::NodeEventVector object_event_vector = { - SPObject::repr_child_added, - SPObject::repr_child_removed, - SPObject::repr_attr_changed, - SPObject::repr_content_changed, - SPObject::repr_order_changed -}; +Inkscape::XML::NodeEventVector object_event_vector = {SPObject::repr_child_added, SPObject::repr_child_removed, + SPObject::repr_attr_changed, SPObject::repr_content_changed, + SPObject::repr_order_changed}; /** * A friend class used to set internal members on SPObject so as to not expose settors in SPObject's public API @@ -77,26 +73,27 @@ Inkscape::XML::NodeEventVector object_event_vector = { class SPObjectImpl { public: - -/** - * Null's the id member of an SPObject without attempting to free prior contents. - * - * @param[inout] obj Pointer to the object which's id shall be nulled. - */ - static void setIdNull( SPObject* obj ) { + /** + * Null's the id member of an SPObject without attempting to free prior contents. + * + * @param[inout] obj Pointer to the object which's id shall be nulled. + */ + static void setIdNull(SPObject *obj) + { if (obj) { obj->id = nullptr; } } -/** - * Sets the id member of an object, freeing any prior content. - * - * @param[inout] obj Pointer to the object which's id shall be set. - * @param[in] id New id - */ - static void setId( SPObject* obj, gchar const* id ) { - if (obj && (id != obj->id) ) { + /** + * Sets the id member of an object, freeing any prior content. + * + * @param[inout] obj Pointer to the object which's id shall be set. + * @param[in] id New id + */ + static void setId(SPObject *obj, gchar const *id) + { + if (obj && (id != obj->id)) { if (obj->id) { g_free(obj->id); obj->id = nullptr; @@ -112,14 +109,26 @@ public: * Constructor, sets all attributes to default values. */ SPObject::SPObject() - : cloned(0), clone_original(nullptr), uflags(0), mflags(0), hrefcount(0), _total_hrefcount(0), - document(nullptr), parent(nullptr), id(nullptr), repr(nullptr), refCount(1), hrefList(std::list()), - _successor(nullptr), _collection_policy(SPObject::COLLECT_WITH_PARENT), - _label(nullptr), _default_label(nullptr) + : cloned(0) + , clone_original(nullptr) + , uflags(0) + , mflags(0) + , hrefcount(0) + , _total_hrefcount(0) + , document(nullptr) + , parent(nullptr) + , id(nullptr) + , repr(nullptr) + , refCount(1) + , hrefList(std::list()) + , _successor(nullptr) + , _collection_policy(SPObject::COLLECT_WITH_PARENT) + , _label(nullptr) + , _default_label(nullptr) { - debug("id=%p, typename=%s",this, g_type_name_from_instance((GTypeInstance*)this)); + debug("id=%p, typename=%s", this, g_type_name_from_instance((GTypeInstance *)this)); - //used XML Tree here. + // used XML Tree here. this->getRepr(); // TODO check why this call is made SPObjectImpl::setIdNull(this); @@ -128,14 +137,15 @@ SPObject::SPObject() // vg, g, defs, desc, title, symbol, use, image, switch, path, rect, circle, ellipse, line, polyline, // polygon, text, tspan, tref, textPath, altGlyph, glyphRef, marker, linearGradient, radialGradient, // stop, pattern, clipPath, mask, filter, feImage, a, font, glyph, missing-glyph, foreignObject - this->style = new SPStyle( nullptr, this ); // Is it necessary to call with "this"? + this->style = new SPStyle(nullptr, this); // Is it necessary to call with "this"? this->context_style = nullptr; } /** * Destructor, frees the used memory and unreferences a potential successor of the object. */ -SPObject::~SPObject() { +SPObject::~SPObject() +{ g_free(this->_label); g_free(this->_default_label); @@ -150,11 +160,11 @@ SPObject::~SPObject() { parent->children.erase(parent->children.iterator_to(*this)); } - if( style == nullptr ) { + if (style == nullptr) { // style pointer could be NULL if unreffed too many times. // Conjecture: style pointer is never NULL. std::cerr << "SPObject::~SPObject(): style pointer is NULL" << std::endl; - } else if( style->refCount() > 1 ) { + } else if (style->refCount() > 1) { // Conjecture: style pointer should be unreffed by other classes before reaching here. // Conjecture is false for SPTSpan where ref is held by InputStreamTextSource. // As an additional note: @@ -163,27 +173,30 @@ SPObject::~SPObject() { // one for the one after, along with one for each corresponding DrawingText instance. // std::cerr << "SPObject::~SPObject(): someone else still holding ref to style" << std::endl; // - sp_style_unref( this->style ); + sp_style_unref(this->style); } else { delete this->style; } } // CPPIFY: make pure virtual -void SPObject::read_content() { - //throw; +void SPObject::read_content() +{ + // throw; } -void SPObject::update(SPCtx* /*ctx*/, unsigned int /*flags*/) { - //throw; +void SPObject::update(SPCtx * /*ctx*/, unsigned int /*flags*/) +{ + // throw; } -void SPObject::modified(unsigned int /*flags*/) { +void SPObject::modified(unsigned int /*flags*/) +{ #ifdef OBJECT_TRACE - objectTrace( "SPObject::modified (default) (empty function)" ); - objectTrace( "SPObject::modified (default)", false ); + objectTrace("SPObject::modified (default) (empty function)"); + objectTrace("SPObject::modified (default)", false); #endif - //throw; + // throw; } namespace { @@ -193,10 +206,11 @@ namespace Util = Inkscape::Util; typedef Debug::SimpleEvent BaseRefCountEvent; -class RefCountEvent : public BaseRefCountEvent { +class RefCountEvent : public BaseRefCountEvent +{ public: RefCountEvent(SPObject *object, int bias, char const *name) - : BaseRefCountEvent(name) + : BaseRefCountEvent(name) { _addProperty("object", Util::format("%p", object).pointer()); _addProperty("class", Debug::demangle(typeid(*object).name())); @@ -204,35 +218,39 @@ public: } }; -class RefEvent : public RefCountEvent { +class RefEvent : public RefCountEvent +{ public: RefEvent(SPObject *object) - : RefCountEvent(object, 1, "sp-object-ref") + : RefCountEvent(object, 1, "sp-object-ref") {} }; -class UnrefEvent : public RefCountEvent { +class UnrefEvent : public RefCountEvent +{ public: UnrefEvent(SPObject *object) - : RefCountEvent(object, -1, "sp-object-unref") + : RefCountEvent(object, -1, "sp-object-unref") {} }; -} +} // namespace -gchar const* SPObject::getId() const { +gchar const *SPObject::getId() const +{ return id; } -Inkscape::XML::Node * SPObject::getRepr() { +Inkscape::XML::Node *SPObject::getRepr() +{ return repr; } -Inkscape::XML::Node const* SPObject::getRepr() const{ +Inkscape::XML::Node const *SPObject::getRepr() const +{ return repr; } - SPObject *sp_object_ref(SPObject *object, SPObject *owner) { g_return_val_if_fail(object != nullptr, NULL); @@ -263,7 +281,7 @@ SPObject *sp_object_unref(SPObject *object, SPObject *owner) return nullptr; } -void SPObject::hrefObject(SPObject* owner) +void SPObject::hrefObject(SPObject *owner) { // if (owner) std::cout << " owner: " << *owner << std::endl; @@ -273,11 +291,11 @@ void SPObject::hrefObject(SPObject* owner) _updateTotalHRefCount(1); } - if(owner) + if (owner) hrefList.push_front(owner); } -void SPObject::unhrefObject(SPObject* owner) +void SPObject::unhrefObject(SPObject *owner) { g_return_if_fail(hrefcount > 0); @@ -287,20 +305,19 @@ void SPObject::unhrefObject(SPObject* owner) _updateTotalHRefCount(-1); - if(owner) + if (owner) hrefList.remove(owner); } -void SPObject::_updateTotalHRefCount(int increment) { +void SPObject::_updateTotalHRefCount(int increment) +{ SPObject *topmost_collectable = nullptr; - for ( SPObject *iter = this ; iter ; iter = iter->parent ) { + for (SPObject *iter = this; iter; iter = iter->parent) { iter->_total_hrefcount += increment; - if ( iter->_total_hrefcount < iter->hrefcount ) { + if (iter->_total_hrefcount < iter->hrefcount) { g_critical("HRefs overcounted"); } - if ( iter->_total_hrefcount == 0 && - iter->_collection_policy != COLLECT_WITH_PARENT ) - { + if (iter->_total_hrefcount == 0 && iter->_collection_policy != COLLECT_WITH_PARENT) { topmost_collectable = iter; } } @@ -309,11 +326,12 @@ void SPObject::_updateTotalHRefCount(int increment) { } } -bool SPObject::isAncestorOf(SPObject const *object) const { +bool SPObject::isAncestorOf(SPObject const *object) const +{ g_return_val_if_fail(object != nullptr, false); object = object->parent; while (object) { - if ( object == this ) { + if (object == this) { return true; } object = object->parent; @@ -323,22 +341,25 @@ bool SPObject::isAncestorOf(SPObject const *object) const { namespace { -bool same_objects(SPObject const &a, SPObject const &b) { +bool same_objects(SPObject const &a, SPObject const &b) +{ return &a == &b; } -} +} // namespace -SPObject const *SPObject::nearestCommonAncestor(SPObject const *object) const { +SPObject const *SPObject::nearestCommonAncestor(SPObject const *object) const +{ g_return_val_if_fail(object != nullptr, NULL); using Inkscape::Algorithms::longest_common_suffix; return longest_common_suffix(this, object, nullptr, &same_objects); } -static SPObject const *AncestorSon(SPObject const *obj, SPObject const *ancestor) { +static SPObject const *AncestorSon(SPObject const *obj, SPObject const *ancestor) +{ SPObject const *result = nullptr; - if ( obj && ancestor ) { + if (obj && ancestor) { if (obj->parent == ancestor) { result = obj; } else { @@ -354,7 +375,7 @@ int sp_object_compare_position(SPObject const *first, SPObject const *second) if (first != second) { SPObject const *ancestor = first->nearestCommonAncestor(second); // Need a common ancestor to be able to compare - if ( ancestor ) { + if (ancestor) { // we have an object and its ancestor (should not happen when sorting selection) if (ancestor == first) { result = 1; @@ -373,13 +394,14 @@ int sp_object_compare_position(SPObject const *first, SPObject const *second) return result; } -bool sp_object_compare_position_bool(SPObject const *first, SPObject const *second){ - return sp_object_compare_position(first,second)<0; +bool sp_object_compare_position_bool(SPObject const *first, SPObject const *second) +{ + return sp_object_compare_position(first, second) < 0; } - -SPObject *SPObject::appendChildRepr(Inkscape::XML::Node *repr) { - if ( !cloned ) { +SPObject *SPObject::appendChildRepr(Inkscape::XML::Node *repr) +{ + if (!cloned) { getRepr()->appendChild(repr); return document->getObjectByRepr(repr); } else { @@ -400,9 +422,10 @@ void SPObject::changeCSS(SPCSSAttr *css, gchar const *attr) sp_repr_css_change(this->getRepr(), css, attr); } -std::vector SPObject::childList(bool add_ref, Action) { - std::vector l; - for (auto& child: children) { +std::vector SPObject::childList(bool add_ref, Action) +{ + std::vector l; + for (auto &child : children) { if (add_ref) { sp_object_ref(&child); } @@ -411,11 +434,13 @@ std::vector SPObject::childList(bool add_ref, Action) { return l; } -gchar const *SPObject::label() const { +gchar const *SPObject::label() const +{ return _label; } -gchar const *SPObject::defaultLabel() const { +gchar const *SPObject::defaultLabel() const +{ if (_label) { return _label; } else { @@ -437,8 +462,8 @@ void SPObject::setLabel(gchar const *label) getRepr()->setAttribute("inkscape:label", label); } - -void SPObject::requestOrphanCollection() { +void SPObject::requestOrphanCollection() +{ g_return_if_fail(document != nullptr); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -447,7 +472,8 @@ void SPObject::requestOrphanCollection() { // leave it } else if (dynamic_cast(this)) { // leave it - } else if ((! prefs->getBool("/options/cleanupswatches/value", false)) && SP_IS_PAINT_SERVER(this) && static_cast(this)->isSwatch() ) { + } else if ((!prefs->getBool("/options/cleanupswatches/value", false)) && SP_IS_PAINT_SERVER(this) && + static_cast(this)->isSwatch()) { // leave it } else if (IS_COLORPROFILE(this)) { // leave it @@ -470,8 +496,9 @@ void SPObject::requestOrphanCollection() { } } -void SPObject::_sendDeleteSignalRecursive() { - for (auto& child: children) { +void SPObject::_sendDeleteSignalRecursive() +{ + for (auto &child : children) { child._delete_signal.emit(&child); child._sendDeleteSignalRecursive(); } @@ -480,7 +507,7 @@ void SPObject::_sendDeleteSignalRecursive() { void SPObject::deleteObject(bool propagate, bool propagate_descendants) { sp_object_ref(this, nullptr); - if ( SP_IS_LPE_ITEM(this) && SP_LPE_ITEM(this)->hasPathEffect()) { + if (SP_IS_LPE_ITEM(this) && SP_LPE_ITEM(this)->hasPathEffect()) { SP_LPE_ITEM(this)->removeAllPathEffects(false); } if (propagate) { @@ -489,7 +516,7 @@ void SPObject::deleteObject(bool propagate, bool propagate_descendants) if (propagate_descendants) { this->_sendDeleteSignalRecursive(); } - + Inkscape::XML::Node *repr = getRepr(); if (repr && repr->parent()) { sp_repr_unparent(repr); @@ -503,25 +530,25 @@ void SPObject::deleteObject(bool propagate, bool propagate_descendants) void SPObject::cropToObject(SPObject *except) { - std::vector toDelete; - for (auto& child: children) { + std::vector toDelete; + for (auto &child : children) { if (SP_IS_ITEM(&child)) { if (child.isAncestorOf(except)) { child.cropToObject(except); - } else if(&child != except) { + } else if (&child != except) { toDelete.push_back(&child); } } } - for (auto & i : toDelete) { + for (auto &i : toDelete) { i->deleteObject(true, true); } } void SPObject::attach(SPObject *object, SPObject *prev) { - //g_return_if_fail(parent != NULL); - //g_return_if_fail(SP_IS_OBJECT(parent)); + // g_return_if_fail(parent != NULL); + // g_return_if_fail(SP_IS_OBJECT(parent)); g_return_if_fail(object != nullptr); g_return_if_fail(SP_IS_OBJECT(object)); g_return_if_fail(!prev || SP_IS_OBJECT(prev)); @@ -542,7 +569,8 @@ void SPObject::attach(SPObject *object, SPObject *prev) object->xml_space.value = this->xml_space.value; } -void SPObject::reorder(SPObject* obj, SPObject* prev) { +void SPObject::reorder(SPObject *obj, SPObject *prev) +{ g_return_if_fail(obj != nullptr); g_return_if_fail(obj->parent); g_return_if_fail(obj->parent == this); @@ -559,8 +587,8 @@ void SPObject::reorder(SPObject* obj, SPObject* prev) { void SPObject::detach(SPObject *object) { - //g_return_if_fail(parent != NULL); - //g_return_if_fail(SP_IS_OBJECT(parent)); + // g_return_if_fail(parent != NULL); + // g_return_if_fail(SP_IS_OBJECT(parent)); g_return_if_fail(object != nullptr); g_return_if_fail(SP_IS_OBJECT(object)); g_return_if_fail(object->parent == this); @@ -580,9 +608,9 @@ SPObject *SPObject::get_child_by_repr(Inkscape::XML::Node *repr) SPObject *result = nullptr; if (children.size() > 0 && children.back().getRepr() == repr) { - result = &children.back(); // optimization for common scenario + result = &children.back(); // optimization for common scenario } else { - for (auto& child: children) { + for (auto &child : children) { if (child.getRepr() == repr) { result = &child; break; @@ -592,12 +620,13 @@ SPObject *SPObject::get_child_by_repr(Inkscape::XML::Node *repr) return result; } -void SPObject::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { - SPObject* object = this; +void SPObject::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ + SPObject *object = this; const std::string type_string = NodeTraits::get_type_string(*child); - SPObject* ochild = SPFactory::createObject(type_string); + SPObject *ochild = SPFactory::createObject(type_string); if (ochild == nullptr) { // Currently, there are many node types that do not have // corresponding classes in the SPObject tree. @@ -613,19 +642,21 @@ void SPObject::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) ochild->invoke_build(object->document, child, object->cloned); } -void SPObject::release() { - SPObject* object = this; - debug("id=%p, typename=%s", object, g_type_name_from_instance((GTypeInstance*)object)); - auto tmp = children | boost::adaptors::transformed([](SPObject& obj){return &obj;}); +void SPObject::release() +{ + SPObject *object = this; + debug("id=%p, typename=%s", object, g_type_name_from_instance((GTypeInstance *)object)); + auto tmp = children | boost::adaptors::transformed([](SPObject &obj) { return &obj; }); std::vector toRelease(tmp.begin(), tmp.end()); - for (auto& p: toRelease) { + for (auto &p : toRelease) { object->detach(p); } } -void SPObject::remove_child(Inkscape::XML::Node* child) { - debug("id=%p, typename=%s", this, g_type_name_from_instance((GTypeInstance*)this)); +void SPObject::remove_child(Inkscape::XML::Node *child) +{ + debug("id=%p, typename=%s", this, g_type_name_from_instance((GTypeInstance *)this)); SPObject *ochild = this->get_child_by_repr(child); @@ -635,8 +666,10 @@ void SPObject::remove_child(Inkscape::XML::Node* child) { } } -void SPObject::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node * /*old_ref*/, Inkscape::XML::Node *new_ref) { - SPObject* object = this; +void SPObject::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node * /*old_ref*/, + Inkscape::XML::Node *new_ref) +{ + SPObject *object = this; SPObject *ochild = object->get_child_by_repr(child); g_return_if_fail(ochild != nullptr); @@ -645,19 +678,19 @@ void SPObject::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node * / ochild->_position_changed_signal.emit(ochild); } -void SPObject::build(SPDocument *document, Inkscape::XML::Node *repr) { - +void SPObject::build(SPDocument *document, Inkscape::XML::Node *repr) +{ #ifdef OBJECT_TRACE - objectTrace( "SPObject::build" ); + objectTrace("SPObject::build"); #endif - SPObject* object = this; + SPObject *object = this; /* Nothing specific here */ - debug("id=%p, typename=%s", object, g_type_name_from_instance((GTypeInstance*)object)); + debug("id=%p, typename=%s", object, g_type_name_from_instance((GTypeInstance *)object)); object->readAttr(SPAttr::XML_SPACE); object->readAttr(SPAttr::LANG); - object->readAttr(SPAttr::XML_LANG); // "xml:lang" overrides "lang" per spec, read it last. + object->readAttr(SPAttr::XML_LANG); // "xml:lang" overrides "lang" per spec, read it last. object->readAttr(SPAttr::INKSCAPE_LABEL); object->readAttr(SPAttr::INKSCAPE_COLLECT); @@ -666,15 +699,15 @@ void SPObject::build(SPDocument *document, Inkscape::XML::Node *repr) { lang = object->parent->lang; } - if(object->cloned && (repr->attribute("id")) ) // The cases where this happens are when the "original" has no id. This happens - // if it is a SPString (a TextNode, e.g. in a ), or when importing - // stuff externally modified to have no id. + if (object->cloned && (repr->attribute("id"))) // The cases where this happens are when the "original" has no id. + // This happens if it is a SPString (a TextNode, e.g. in a <title>), + // or when importing stuff externally modified to have no id. object->clone_original = document->getObjectById(repr->attribute("id")); - for (Inkscape::XML::Node *rchild = repr->firstChild() ; rchild != nullptr; rchild = rchild->next()) { + for (Inkscape::XML::Node *rchild = repr->firstChild(); rchild != nullptr; rchild = rchild->next()) { const std::string typeString = NodeTraits::get_type_string(*rchild); - SPObject* child = SPFactory::createObject(typeString); + SPObject *child = SPFactory::createObject(typeString); if (child == nullptr) { // Currently, there are many node types that do not have // corresponding classes in the SPObject tree. @@ -689,19 +722,19 @@ void SPObject::build(SPDocument *document, Inkscape::XML::Node *repr) { } #ifdef OBJECT_TRACE - objectTrace( "SPObject::build", false ); + objectTrace("SPObject::build", false); #endif } void SPObject::invoke_build(SPDocument *document, Inkscape::XML::Node *repr, unsigned int cloned) { #ifdef OBJECT_TRACE - objectTrace( "SPObject::invoke_build" ); + objectTrace("SPObject::invoke_build"); #endif - debug("id=%p, typename=%s", this, g_type_name_from_instance((GTypeInstance*)this)); + debug("id=%p, typename=%s", this, g_type_name_from_instance((GTypeInstance *)this)); - //g_assert(object != NULL); - //g_assert(SP_IS_OBJECT(object)); + // g_assert(object != NULL); + // g_assert(SP_IS_OBJECT(object)); g_assert(document != nullptr); g_assert(repr != nullptr); @@ -721,7 +754,7 @@ void SPObject::invoke_build(SPDocument *document, Inkscape::XML::Node *repr, uns /* Invoke derived methods, if any */ this->build(document, repr); - if ( !cloned ) { + if (!cloned) { this->document->bindObjectToRepr(this->repr, this); if (Inkscape::XML::id_permitted(this->repr)) { @@ -754,39 +787,41 @@ void SPObject::invoke_build(SPDocument *document, Inkscape::XML::Node *repr, uns g_assert(this->getId() == nullptr); } - /* Signalling (should be connected AFTER processing derived methods */ sp_repr_add_listener(repr, &object_event_vector, this); #ifdef OBJECT_TRACE - objectTrace( "SPObject::invoke_build", false ); + objectTrace("SPObject::invoke_build", false); #endif } int SPObject::getIntAttribute(char const *key, int def) { - sp_repr_get_int(getRepr(),key,&def); + sp_repr_get_int(getRepr(), key, &def); return def; } -unsigned SPObject::getPosition(){ +unsigned SPObject::getPosition() +{ g_assert(this->repr); return repr->position(); } -void SPObject::appendChild(Inkscape::XML::Node *child) { +void SPObject::appendChild(Inkscape::XML::Node *child) +{ g_assert(this->repr); repr->appendChild(child); } -SPObject* SPObject::nthChild(unsigned index) { +SPObject *SPObject::nthChild(unsigned index) +{ g_assert(this->repr); if (hasChildren()) { - std::vector<SPObject*> l; + std::vector<SPObject *> l; unsigned counter = 0; - for (auto& child: children) { + for (auto &child : children) { if (counter == index) { return &child; } @@ -796,14 +831,15 @@ SPObject* SPObject::nthChild(unsigned index) { return nullptr; } -void SPObject::addChild(Inkscape::XML::Node *child, Inkscape::XML::Node * prev) +void SPObject::addChild(Inkscape::XML::Node *child, Inkscape::XML::Node *prev) { g_assert(this->repr); - repr->addChild(child,prev); + repr->addChild(child, prev); } -void SPObject::releaseReferences() { +void SPObject::releaseReferences() +{ g_assert(this->document); g_assert(this->repr); @@ -842,7 +878,6 @@ void SPObject::releaseReferences() { this->repr = nullptr; } - SPObject *SPObject::getPrev() { SPObject *prev = nullptr; @@ -852,7 +887,7 @@ SPObject *SPObject::getPrev() return prev; } -SPObject* SPObject::getNext() +SPObject *SPObject::getNext() { SPObject *next = nullptr; if (parent && !parent->children.empty() && &parent->children.back() != this) { @@ -861,47 +896,49 @@ SPObject* SPObject::getNext() return next; } -void SPObject::repr_child_added(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, gpointer data) +void SPObject::repr_child_added(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, + gpointer data) { SPObject *object = SP_OBJECT(data); object->child_added(child, ref); } -void SPObject::repr_child_removed(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node *child, Inkscape::XML::Node * /*ref*/, gpointer data) +void SPObject::repr_child_removed(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node *child, + Inkscape::XML::Node * /*ref*/, gpointer data) { SPObject *object = SP_OBJECT(data); object->remove_child(child); } -void SPObject::repr_order_changed(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node *child, Inkscape::XML::Node *old, Inkscape::XML::Node *newer, gpointer data) +void SPObject::repr_order_changed(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node *child, Inkscape::XML::Node *old, + Inkscape::XML::Node *newer, gpointer data) { SPObject *object = SP_OBJECT(data); object->order_changed(child, old, newer); } -void SPObject::set(SPAttr key, gchar const* value) { - +void SPObject::set(SPAttr key, gchar const *value) +{ #ifdef OBJECT_TRACE std::stringstream temp; - temp << "SPObject::set: " << key << " " << (value?value:"null"); - objectTrace( temp.str() ); + temp << "SPObject::set: " << key << " " << (value ? value : "null"); + objectTrace(temp.str()); #endif g_assert(key != SPAttr::INVALID); - SPObject* object = this; + SPObject *object = this; switch (key) { - case SPAttr::ID: - //XML Tree being used here. - if ( !object->cloned && object->getRepr()->type() == Inkscape::XML::ELEMENT_NODE ) { - SPDocument *document=object->document; - SPObject *conflict=nullptr; + // XML Tree being used here. + if (!object->cloned && object->getRepr()->type() == Inkscape::XML::ELEMENT_NODE) { + SPDocument *document = object->document; + SPObject *conflict = nullptr; gchar const *new_id = value; @@ -909,7 +946,7 @@ void SPObject::set(SPAttr key, gchar const* value) { conflict = document->getObjectById((char const *)new_id); } - if ( conflict && conflict != object ) { + if (conflict && conflict != object) { if (!document->isSeeking()) { sp_object_ref(conflict, nullptr); // give the conflicting object a new ID @@ -949,7 +986,7 @@ void SPObject::set(SPAttr key, gchar const* value) { break; case SPAttr::INKSCAPE_COLLECT: - if ( value && !std::strcmp(value, "always") ) { + if (value && !std::strcmp(value, "always")) { object->setCollectionPolicy(SPObject::ALWAYS_COLLECT); } else { object->setCollectionPolicy(SPObject::COLLECT_WITH_PARENT); @@ -986,7 +1023,7 @@ void SPObject::set(SPAttr key, gchar const* value) { break; case SPAttr::STYLE: - object->style->readFromObject( object ); + object->style->readFromObject(object); object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); break; @@ -994,14 +1031,14 @@ void SPObject::set(SPAttr key, gchar const* value) { break; } #ifdef OBJECT_TRACE - objectTrace( "SPObject::set", false ); + objectTrace("SPObject::set", false); #endif } void SPObject::setKeyValue(SPAttr key, gchar const *value) { - //g_assert(object != NULL); - //g_assert(SP_IS_OBJECT(object)); + // g_assert(object != NULL); + // g_assert(SP_IS_OBJECT(object)); this->set(key, value); } @@ -1020,11 +1057,11 @@ void SPObject::readAttr(SPAttr keyid) void SPObject::readAttr(gchar const *key) { - //g_assert(object != NULL); - //g_assert(SP_IS_OBJECT(object)); + // g_assert(object != NULL); + // g_assert(SP_IS_OBJECT(object)); g_assert(key != nullptr); - //XML Tree being used here. + // XML Tree being used here. g_assert(this->getRepr() != nullptr); auto keyid = sp_attribute_lookup(key); @@ -1036,7 +1073,8 @@ void SPObject::readAttr(gchar const *key) } } -void SPObject::repr_attr_changed(Inkscape::XML::Node * /*repr*/, gchar const *key, gchar const * /*oldval*/, gchar const * /*newval*/, bool is_interactive, gpointer data) +void SPObject::repr_attr_changed(Inkscape::XML::Node * /*repr*/, gchar const *key, gchar const * /*oldval*/, + gchar const * /*newval*/, bool is_interactive, gpointer data) { SPObject *object = SP_OBJECT(data); @@ -1049,7 +1087,8 @@ void SPObject::repr_attr_changed(Inkscape::XML::Node * /*repr*/, gchar const *ke } } -void SPObject::repr_content_changed(Inkscape::XML::Node * /*repr*/, gchar const * /*oldcontent*/, gchar const * /*newcontent*/, gpointer data) +void SPObject::repr_content_changed(Inkscape::XML::Node * /*repr*/, gchar const * /*oldcontent*/, + gchar const * /*newcontent*/, gpointer data) { SPObject *object = SP_OBJECT(data); @@ -1071,14 +1110,15 @@ static gchar const *sp_xml_get_space_string(unsigned int space) } } -Inkscape::XML::Node* SPObject::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPObject::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +{ #ifdef OBJECT_TRACE - objectTrace( "SPObject::write" ); + objectTrace("SPObject::write"); #endif if (!repr && (flags & SP_OBJECT_WRITE_BUILD)) { repr = this->getRepr()->duplicate(doc); - if (!( flags & SP_OBJECT_WRITE_EXT )) { + if (!(flags & SP_OBJECT_WRITE_EXT)) { repr->removeAttribute("inkscape:collect"); } } else if (repr) { @@ -1090,9 +1130,7 @@ Inkscape::XML::Node* SPObject::write(Inkscape::XML::Document *doc, Inkscape::XML repr->setAttribute("xml:space", xml_space); } - if ( flags & SP_OBJECT_WRITE_EXT && - this->collectionPolicy() == SPObject::ALWAYS_COLLECT ) - { + if (flags & SP_OBJECT_WRITE_EXT && this->collectionPolicy() == SPObject::ALWAYS_COLLECT) { repr->setAttribute("inkscape:collect", "always"); } else { repr->removeAttribute("inkscape:collect"); @@ -1100,20 +1138,19 @@ Inkscape::XML::Node* SPObject::write(Inkscape::XML::Document *doc, Inkscape::XML if (style) { // Write if property set by style attribute in this object - Glib::ustring s = - style->write(SP_STYLE_FLAG_IFSET | SP_STYLE_FLAG_IFSRC, SP_STYLE_SRC_STYLE_PROP); + Glib::ustring s = style->write(SP_STYLE_FLAG_IFSET | SP_STYLE_FLAG_IFSRC, SP_STYLE_SRC_STYLE_PROP); // Write style attributes (SP_STYLE_SRC_ATTRIBUTE) back to xml object bool any_written = false; auto properties = style->properties(); - for (auto * prop : properties) { - if(prop->shall_write(SP_STYLE_FLAG_IFSET | SP_STYLE_FLAG_IFSRC, SP_STYLE_SRC_ATTRIBUTE)) { + for (auto *prop : properties) { + if (prop->shall_write(SP_STYLE_FLAG_IFSET | SP_STYLE_FLAG_IFSRC, SP_STYLE_SRC_ATTRIBUTE)) { // WARNING: We don't know for sure if the css names are the same as the attribute names repr->setAttributeOrRemoveIfEmpty(prop->name(), prop->get_value()); any_written = true; } } - if(any_written) { + if (any_written) { // We need to ask the object to update the style and keep things in sync // see `case SPAttr::STYLE` above for how the style attr itself does this. style->readFromObject(this); @@ -1123,10 +1160,9 @@ Inkscape::XML::Node* SPObject::write(Inkscape::XML::Document *doc, Inkscape::XML // Check for valid attributes. This may be time consuming. // It is useful, though, for debugging Inkscape code. Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if( prefs->getBool("/options/svgoutput/check_on_editing") ) { - + if (prefs->getBool("/options/svgoutput/check_on_editing")) { unsigned int flags = sp_attribute_clean_get_prefs(); - Glib::ustring s_cleaned = sp_attribute_clean_style( repr, s.c_str(), flags ); + Glib::ustring s_cleaned = sp_attribute_clean_style(repr, s.c_str(), flags); } repr->setAttributeOrRemoveIfEmpty("style", s); @@ -1147,44 +1183,44 @@ Inkscape::XML::Node* SPObject::write(Inkscape::XML::Document *doc, Inkscape::XML } #ifdef OBJECT_TRACE - objectTrace( "SPObject::write", false ); + objectTrace("SPObject::write", false); #endif return repr; } -Inkscape::XML::Node * SPObject::updateRepr(unsigned int flags) +Inkscape::XML::Node *SPObject::updateRepr(unsigned int flags) { #ifdef OBJECT_TRACE - objectTrace( "SPObject::updateRepr 1" ); + objectTrace("SPObject::updateRepr 1"); #endif - if ( !cloned ) { + if (!cloned) { Inkscape::XML::Node *repr = getRepr(); if (repr) { #ifdef OBJECT_TRACE - objectTrace( "SPObject::updateRepr 1", false ); + objectTrace("SPObject::updateRepr 1", false); #endif return updateRepr(repr->document(), repr, flags); } else { g_critical("Attempt to update non-existent repr"); #ifdef OBJECT_TRACE - objectTrace( "SPObject::updateRepr 1", false ); + objectTrace("SPObject::updateRepr 1", false); #endif return nullptr; } } else { /* cloned objects have no repr */ #ifdef OBJECT_TRACE - objectTrace( "SPObject::updateRepr 1", false ); + objectTrace("SPObject::updateRepr 1", false); #endif return nullptr; } } -Inkscape::XML::Node * SPObject::updateRepr(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) +Inkscape::XML::Node *SPObject::updateRepr(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) { #ifdef OBJECT_TRACE - objectTrace( "SPObject::updateRepr 2" ); + objectTrace("SPObject::updateRepr 2"); #endif g_assert(doc != nullptr); @@ -1192,7 +1228,7 @@ Inkscape::XML::Node * SPObject::updateRepr(Inkscape::XML::Document *doc, Inkscap if (cloned) { /* cloned objects have no repr */ #ifdef OBJECT_TRACE - objectTrace( "SPObject::updateRepr 2", false ); + objectTrace("SPObject::updateRepr 2", false); #endif return nullptr; } @@ -1203,19 +1239,18 @@ Inkscape::XML::Node * SPObject::updateRepr(Inkscape::XML::Document *doc, Inkscap #ifdef OBJECT_TRACE Inkscape::XML::Node *node = write(doc, repr, flags); - objectTrace( "SPObject::updateRepr 2", false ); + objectTrace("SPObject::updateRepr 2", false); return node; #else return this->write(doc, repr, flags); #endif - } /* Modification */ void SPObject::requestDisplayUpdate(unsigned int flags) { - g_return_if_fail( this->document != nullptr ); + g_return_if_fail(this->document != nullptr); #ifndef NDEBUG // expect no nested update calls @@ -1232,19 +1267,19 @@ void SPObject::requestDisplayUpdate(unsigned int flags) g_return_if_fail(!((flags & SP_OBJECT_MODIFIED_FLAG) && (flags & SP_OBJECT_CHILD_MODIFIED_FLAG))); #ifdef OBJECT_TRACE - objectTrace( "SPObject::requestDisplayUpdate" ); + objectTrace("SPObject::requestDisplayUpdate"); #endif bool already_propagated = (!(this->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))); - //https://stackoverflow.com/a/7841333 - if ((this->uflags & flags) != flags ) { + // https://stackoverflow.com/a/7841333 + if ((this->uflags & flags) != flags) { this->uflags |= flags; } /* If requestModified has already been called on this object or one of its children, then we * don't need to set CHILD_MODIFIED on our ancestors because it's already been done. */ if (already_propagated) { - if(this->document) { + if (this->document) { if (parent) { parent->requestDisplayUpdate(SP_OBJECT_CHILD_MODIFIED_FLAG); } else { @@ -1254,9 +1289,8 @@ void SPObject::requestDisplayUpdate(unsigned int flags) } #ifdef OBJECT_TRACE - objectTrace( "SPObject::requestDisplayUpdate", false ); + objectTrace("SPObject::requestDisplayUpdate", false); #endif - } void SPObject::updateDisplay(SPCtx *ctx, unsigned int flags) @@ -1264,13 +1298,14 @@ void SPObject::updateDisplay(SPCtx *ctx, unsigned int flags) g_return_if_fail(!(flags & ~SP_OBJECT_MODIFIED_CASCADE)); #ifdef OBJECT_TRACE - objectTrace( "SPObject::updateDisplay" ); + objectTrace("SPObject::updateDisplay"); #endif assert(++(document->update_in_progress)); #ifdef SP_OBJECT_DEBUG_CASCADE - g_print("Update %s:%s %x %x %x\n", g_type_name_from_instance((GTypeInstance *) this), getId(), flags, this->uflags, this->mflags); + g_print("Update %s:%s %x %x %x\n", g_type_name_from_instance((GTypeInstance *)this), getId(), flags, this->uflags, + this->mflags); #endif /* Get this flags */ @@ -1288,34 +1323,32 @@ void SPObject::updateDisplay(SPCtx *ctx, unsigned int flags) */ if ((flags & SP_OBJECT_STYLE_MODIFIED_FLAG) && (flags & SP_OBJECT_PARENT_MODIFIED_FLAG)) { if (this->style && this->parent) { - style->cascade( this->parent->style ); + style->cascade(this->parent->style); } } - try - { + try { this->update(ctx, flags); - } - catch(...) - { + } catch (...) { /** \todo - * in case of catching an exception we need to inform the user somehow that the document is corrupted - * maybe by implementing an document flag documentOk - * or by a modal error dialog - */ - g_warning("SPObject::updateDisplay(SPCtx *ctx, unsigned int flags) : throw in ((SPObjectClass *) G_OBJECT_GET_CLASS(this))->update(this, ctx, flags);"); + * in case of catching an exception we need to inform the user somehow that the document is corrupted + * maybe by implementing an document flag documentOk + * or by a modal error dialog + */ + g_warning("SPObject::updateDisplay(SPCtx *ctx, unsigned int flags) : throw in ((SPObjectClass *) " + "G_OBJECT_GET_CLASS(this))->update(this, ctx, flags);"); } assert((document->update_in_progress)--); #ifdef OBJECT_TRACE - objectTrace( "SPObject::updateDisplay", false ); + objectTrace("SPObject::updateDisplay", false); #endif } void SPObject::requestModified(unsigned int flags) { - g_return_if_fail( this->document != nullptr ); + g_return_if_fail(this->document != nullptr); /* requestModified must be used only to set one of SP_OBJECT_MODIFIED_FLAG or * SP_OBJECT_CHILD_MODIFIED_FLAG */ @@ -1324,7 +1357,7 @@ void SPObject::requestModified(unsigned int flags) g_return_if_fail(!((flags & SP_OBJECT_MODIFIED_FLAG) && (flags & SP_OBJECT_CHILD_MODIFIED_FLAG))); #ifdef OBJECT_TRACE - objectTrace( "SPObject::requestModified" ); + objectTrace("SPObject::requestModified"); #endif bool already_propagated = (!(this->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))); @@ -1342,7 +1375,7 @@ void SPObject::requestModified(unsigned int flags) } } #ifdef OBJECT_TRACE - objectTrace( "SPObject::requestModified", false ); + objectTrace("SPObject::requestModified", false); #endif } @@ -1352,11 +1385,12 @@ void SPObject::emitModified(unsigned int flags) g_return_if_fail(!(flags & ~SP_OBJECT_MODIFIED_CASCADE)); #ifdef OBJECT_TRACE - objectTrace( "SPObject::emitModified", true, flags ); + objectTrace("SPObject::emitModified", true, flags); #endif #ifdef SP_OBJECT_DEBUG_CASCADE - g_print("Modified %s:%s %x %x %x\n", g_type_name_from_instance((GTypeInstance *) this), getId(), flags, this->uflags, this->mflags); + g_print("Modified %s:%s %x %x %x\n", g_type_name_from_instance((GTypeInstance *)this), getId(), flags, this->uflags, + this->mflags); #endif flags |= this->mflags; @@ -1373,7 +1407,7 @@ void SPObject::emitModified(unsigned int flags) sp_object_unref(this); #ifdef OBJECT_TRACE - objectTrace( "SPObject::emitModified", false ); + objectTrace("SPObject::emitModified", false); #endif } @@ -1386,7 +1420,7 @@ gchar const *SPObject::getTagName(SPException *ex) const } /// \todo fixme: Exception if object is NULL? */ - //XML Tree being used here. + // XML Tree being used here. return getRepr()->name(); } @@ -1399,43 +1433,39 @@ gchar const *SPObject::getAttribute(gchar const *key, SPException *ex) const } /// \todo fixme: Exception if object is NULL? */ - //XML Tree being used here. - return (gchar const *) getRepr()->attribute(key); + // XML Tree being used here. + return (gchar const *)getRepr()->attribute(key); } -void SPObject::setAttribute(Inkscape::Util::const_char_ptr key, - Inkscape::Util::const_char_ptr value, SPException *ex) +void SPObject::setAttribute(Inkscape::Util::const_char_ptr key, Inkscape::Util::const_char_ptr value, SPException *ex) { g_assert(this->repr != nullptr); /* If exception is not clear, return */ g_return_if_fail(SP_EXCEPTION_IS_OK(ex)); /// \todo fixme: Exception if object is NULL? */ - //XML Tree being used here. + // XML Tree being used here. getRepr()->setAttribute(key, value); } - void SPObject::removeAttribute(gchar const *key, SPException *ex) { /* If exception is not clear, return */ g_return_if_fail(SP_EXCEPTION_IS_OK(ex)); /// \todo fixme: Exception if object is NULL? */ - //XML Tree being used here. + // XML Tree being used here. getRepr()->removeAttribute(key); } -bool SPObject::storeAsDouble( gchar const *key, double *val ) const +bool SPObject::storeAsDouble(gchar const *key, double *val) const { - g_assert(this->getRepr()!= nullptr); - return sp_repr_get_double(((Inkscape::XML::Node *)(this->getRepr())),key,val); + g_assert(this->getRepr() != nullptr); + return sp_repr_get_double(((Inkscape::XML::Node *)(this->getRepr())), key, val); } /** Helper */ -gchar * -sp_object_get_unique_id(SPObject *object, - gchar const *id) +gchar *sp_object_get_unique_id(SPObject *object, gchar const *id) { static unsigned long count = 0; @@ -1443,7 +1473,7 @@ sp_object_get_unique_id(SPObject *object, count++; - //XML Tree being used here. + // XML Tree being used here. gchar const *name = object->getRepr()->name(); g_assert(name != nullptr); @@ -1460,23 +1490,24 @@ sp_object_get_unique_id(SPObject *object, size_t const name_len = std::strlen(name); size_t const buflen = name_len + (sizeof(count) * 10 / 4) + 1; - gchar *const buf = (gchar *) g_malloc(buflen); + gchar *const buf = (gchar *)g_malloc(buflen); std::memcpy(buf, name, name_len); gchar *const count_buf = buf + name_len; size_t const count_buflen = buflen - name_len; do { ++count; g_snprintf(count_buf, count_buflen, "%lu", count); - } while ( object->document->getObjectById(buf) != nullptr ); + } while (object->document->getObjectById(buf) != nullptr); return buf; } -void SPObject::_requireSVGVersion(Inkscape::Version version) { - for ( SPObject::ParentIterator iter=this ; iter ; ++iter ) { +void SPObject::_requireSVGVersion(Inkscape::Version version) +{ + for (SPObject::ParentIterator iter = this; iter; ++iter) { SPObject *object = iter; if (SP_IS_ROOT(object)) { SPRoot *root = SP_ROOT(object); - if ( root->version.svg < version ) { + if (root->version.svg < version) { root->version.svg = version; } } @@ -1498,7 +1529,7 @@ void SPObject::_requireSVGVersion(Inkscape::Version version) { be allowed with different localized strings. */ -gchar * SPObject::title() const +gchar *SPObject::title() const { return getTitleOrDesc("svg:title"); } @@ -1508,7 +1539,7 @@ bool SPObject::setTitle(gchar const *title, bool verbatim) return setTitleOrDesc(title, "svg:title", verbatim); } -gchar * SPObject::desc() const +gchar *SPObject::desc() const { return getTitleOrDesc("svg:desc"); } @@ -1518,14 +1549,14 @@ bool SPObject::setDesc(gchar const *desc, bool verbatim) return setTitleOrDesc(desc, "svg:desc", verbatim); } -char * SPObject::getTitleOrDesc(gchar const *svg_tagname) const +char *SPObject::getTitleOrDesc(gchar const *svg_tagname) const { char *result = nullptr; SPObject *elem = findFirstChild(svg_tagname); - if ( elem ) { - //This string copy could be avoided by changing - //the return type of SPObject::getTitleOrDesc - //to std::unique_ptr<Glib::ustring> + if (elem) { + // This string copy could be avoided by changing + // the return type of SPObject::getTitleOrDesc + // to std::unique_ptr<Glib::ustring> result = g_strdup(elem->textualContent().c_str()); } return result; @@ -1584,12 +1615,11 @@ bool SPObject::setTitleOrDesc(gchar const *value, gchar const *svg_tagname, bool repr->addChild(xml_elem, nullptr); elem = document->getObjectByRepr(xml_elem); Inkscape::GC::release(xml_elem); - } - else { + } else { // remove the current content of the 'text' or 'desc' element - auto tmp = elem->children | boost::adaptors::transformed([](SPObject& obj) { return &obj; }); - std::vector<SPObject*> vec(tmp.begin(), tmp.end()); - for (auto &child: vec) { + auto tmp = elem->children | boost::adaptors::transformed([](SPObject &obj) { return &obj; }); + std::vector<SPObject *> vec(tmp.begin(), tmp.end()); + for (auto &child : vec) { child->deleteObject(); } } @@ -1599,12 +1629,10 @@ bool SPObject::setTitleOrDesc(gchar const *value, gchar const *svg_tagname, bool return true; } -SPObject* SPObject::findFirstChild(gchar const *tagname) const +SPObject *SPObject::findFirstChild(gchar const *tagname) const { - for (auto& child: const_cast<SPObject*>(this)->children) - { - if (child.repr->type() == Inkscape::XML::ELEMENT_NODE && - !std::strcmp(child.repr->name(), tagname)) { + for (auto &child : const_cast<SPObject *>(this)->children) { + if (child.repr->type() == Inkscape::XML::ELEMENT_NODE && !std::strcmp(child.repr->name(), tagname)) { return &child; } } @@ -1615,14 +1643,12 @@ Glib::ustring SPObject::textualContent() const { Glib::ustring text; - for (auto& child: children) - { + for (auto &child : children) { Inkscape::XML::NodeType child_type = child.repr->type(); if (child_type == Inkscape::XML::ELEMENT_NODE) { text += child.textualContent(); - } - else if (child_type == Inkscape::XML::TEXT_NODE) { + } else if (child_type == Inkscape::XML::TEXT_NODE) { text += child.repr->content(); } } @@ -1630,7 +1656,7 @@ Glib::ustring SPObject::textualContent() const } // For debugging: Print SP tree structure. -void SPObject::recursivePrintTree( unsigned level ) +void SPObject::recursivePrintTree(unsigned level) { if (level == 0) { std::cout << "SP Object Tree" << std::endl; @@ -1639,24 +1665,24 @@ void SPObject::recursivePrintTree( unsigned level ) for (unsigned i = 0; i < level; ++i) { std::cout << " "; } - std::cout << (getId()?getId():"No object id") - << " clone: " << std::boolalpha << (bool)cloned + std::cout << (getId() ? getId() : "No object id") << " clone: " << std::boolalpha << (bool)cloned << " hrefcount: " << hrefcount << std::endl; - for (auto& child: children) { + for (auto &child : children) { child.recursivePrintTree(level + 1); } } // Function to allow tracing of program flow through SPObject and derived classes. // To trace function, add at entrance ('in' = true) and exit of function ('in' = false). -void SPObject::objectTrace( std::string text, bool in, unsigned flags ) { - if( in ) { +void SPObject::objectTrace(std::string text, bool in, unsigned flags) +{ + if (in) { for (unsigned i = 0; i < indent_level; ++i) { std::cout << " "; } std::cout << text << ":" << " entrance: " - << (id?id:"null") + << (id ? id : "null") // << " uflags: " << uflags // << " mflags: " << mflags // << " flags: " << flags @@ -1669,7 +1695,7 @@ void SPObject::objectTrace( std::string text, bool in, unsigned flags ) { } std::cout << text << ":" << " exit: " - << (id?id:"null") + << (id ? id : "null") // << " uflags: " << uflags // << " mflags: " << mflags // << " flags: " << flags @@ -1679,11 +1705,8 @@ void SPObject::objectTrace( std::string text, bool in, unsigned flags ) { std::ostream &operator<<(std::ostream &out, const SPObject &o) { - out << (o.getId()?o.getId():"No ID") - << " cloned: " << std::boolalpha << (bool)o.cloned - << " ref: " << o.refCount - << " href: " << o.hrefcount - << " total href: " << o._total_hrefcount; + out << (o.getId() ? o.getId() : "No ID") << " cloned: " << std::boolalpha << (bool)o.cloned + << " ref: " << o.refCount << " href: " << o.hrefcount << " total href: " << o._total_hrefcount; return out; } /* diff --git a/src/object/sp-object.h b/src/object/sp-object.h index 57643634241acdfb53fc05b9b93d24a7192e47f0..2f837a6a87070392758b9060399ff305be8e93cb 100644 --- a/src/object/sp-object.h +++ b/src/object/sp-object.h @@ -2,7 +2,6 @@ #ifndef SP_OBJECT_H_SEEN #define SP_OBJECT_H_SEEN - /* * Authors: * Lauris Kaplinski <lauris@kaplinski.com> @@ -17,13 +16,14 @@ */ #include <glibmm/ustring.h> + #include "util/const_char_ptr.h" /* SPObject flags */ class SPObject; -#define SP_OBJECT(obj) (dynamic_cast<SPObject*>((SPObject*)obj)) -#define SP_IS_OBJECT(obj) (dynamic_cast<const SPObject*>((SPObject*)obj) != NULL) +#define SP_OBJECT(obj) (dynamic_cast<SPObject *>((SPObject *)obj)) +#define SP_IS_OBJECT(obj) (dynamic_cast<const SPObject *>((SPObject *)obj) != NULL) /* Async modification flags */ #define SP_OBJECT_MODIFIED_FLAG (1 << 0) @@ -52,15 +52,16 @@ class SPObject; #define SP_OBJECT_WRITE_ALL (1 << 2) #define SP_OBJECT_WRITE_NO_CHILDREN (1 << 3) +#include <boost/intrusive/list.hpp> #include <cassert> #include <cstddef> #include <sigc++/connection.h> #include <sigc++/functors/slot.h> #include <sigc++/signal.h> #include <vector> -#include <boost/intrusive/list.hpp> -#include "version.h" + #include "util/forward-pointer-iterator.h" +#include "version.h" enum class SPAttr; @@ -71,14 +72,15 @@ namespace Inkscape { namespace XML { class Node; struct Document; -} -} +} // namespace XML +} // namespace Inkscape namespace Glib { - class ustring; +class ustring; } -enum SPExceptionType { +enum SPExceptionType +{ SP_NO_EXCEPTION, SP_INDEX_SIZE_ERR, SP_DOMSTRING_SIZE_ERR, @@ -98,19 +100,25 @@ enum SPExceptionType { }; /// An attempt to implement exceptions, unused? -struct SPException { +struct SPException +{ SPExceptionType code; }; -#define SP_EXCEPTION_INIT(ex) {(ex)->code = SP_NO_EXCEPTION;} +#define SP_EXCEPTION_INIT(ex) \ + { \ + (ex)->code = SP_NO_EXCEPTION; \ + } #define SP_EXCEPTION_IS_OK(ex) (!(ex) || ((ex)->code == SP_NO_EXCEPTION)) /// Unused -struct SPCtx { +struct SPCtx +{ unsigned int flags; }; -enum { +enum +{ SP_XML_SPACE_DEFAULT, SP_XML_SPACE_PRESERVE }; @@ -118,9 +126,12 @@ enum { class SPDocument; /// Internal class consisting of two bits. -class SPIXmlSpace { -public: - SPIXmlSpace(): set(0), value(SP_XML_SPACE_DEFAULT) {}; +class SPIXmlSpace +{ +public: + SPIXmlSpace() + : set(0) + , value(SP_XML_SPACE_DEFAULT){}; unsigned int set : 1; unsigned int value : 1; }; @@ -140,7 +151,7 @@ public: * \pre object points to real object * @todo need to move this to be a member of SPObject. */ -SPObject *sp_object_ref(SPObject *object, SPObject *owner=nullptr); +SPObject *sp_object_ref(SPObject *object, SPObject *owner = nullptr); /** * Decrease reference count of object, with possible debugging and @@ -151,7 +162,7 @@ SPObject *sp_object_ref(SPObject *object, SPObject *owner=nullptr); * \pre object points to real object * @todo need to move this to be a member of SPObject. */ -SPObject *sp_object_unref(SPObject *object, SPObject *owner=nullptr); +SPObject *sp_object_unref(SPObject *object, SPObject *owner = nullptr); /** * SPObject is an abstract base class of all of the document nodes at the @@ -170,9 +181,11 @@ SPObject *sp_object_unref(SPObject *object, SPObject *owner=nullptr); * provides document level functionality such as the undo stack, * dictionary and so on. Source: doc/architecture.txt */ -class SPObject { +class SPObject +{ public: - enum CollectionPolicy { + enum CollectionPolicy + { COLLECT_WITH_PARENT, ALWAYS_COLLECT }; @@ -186,40 +199,39 @@ public: unsigned int mflags : 8; SPIXmlSpace xml_space; Glib::ustring lang; - unsigned int hrefcount; /* number of xlink:href references */ + unsigned int hrefcount; /* number of xlink:href references */ unsigned int _total_hrefcount; /* our hrefcount + total descendants */ - SPDocument *document; /* Document we are part of */ - SPObject *parent; /* Our parent (only one allowed) */ + SPDocument *document; /* Document we are part of */ + SPObject *parent; /* Our parent (only one allowed) */ private: - SPObject(const SPObject&); - SPObject& operator=(const SPObject&); + SPObject(const SPObject &); + SPObject &operator=(const SPObject &); - char *id; /* Our very own unique id */ + char *id; /* Our very own unique id */ Inkscape::XML::Node *repr; /* Our xml representation */ public: int refCount; - std::list<SPObject*> hrefList; + std::list<SPObject *> hrefList; /** * Returns the objects current ID string. */ - char const* getId() const; + char const *getId() const; /** * Returns the XML representation of tree */ -//protected: - Inkscape::XML::Node * getRepr(); + // protected: + Inkscape::XML::Node *getRepr(); /** * Returns the XML representation of tree */ - Inkscape::XML::Node const* getRepr() const; + Inkscape::XML::Node const *getRepr() const; public: - /** * Cleans up an SPObject, releasing its references and * requesting that references to it be released @@ -233,9 +245,7 @@ public: * * @return the sigc::connection formed */ - sigc::connection connectRelease(sigc::slot<void, SPObject *> slot) { - return _release_signal.connect(slot); - } + sigc::connection connectRelease(sigc::slot<void, SPObject *> slot) { return _release_signal.connect(slot); } /** * Represents the style properties, whether from presentation attributes, the <tt>style</tt> @@ -256,17 +266,18 @@ public: SPStyle *context_style; /// Switch containing next() method. - struct ParentIteratorStrategy { - static SPObject const *next(SPObject const *object) { - return object->parent; - } + struct ParentIteratorStrategy + { + static SPObject const *next(SPObject const *object) { return object->parent; } }; typedef Inkscape::Util::ForwardPointerIterator<SPObject, ParentIteratorStrategy> ParentIterator; typedef Inkscape::Util::ForwardPointerIterator<SPObject const, ParentIteratorStrategy> ConstParentIterator; - bool isSiblingOf(SPObject const *object) const { - if (object == nullptr) return false; + bool isSiblingOf(SPObject const *object) const + { + if (object == nullptr) + return false; return this->parent && this->parent == object->parent; } @@ -288,7 +299,7 @@ public: */ SPObject *getPrev(); - bool hasChildren() const { return ( children.size() > 0 ); } + bool hasChildren() const { return (children.size() > 0); } SPObject *firstChild() { return children.empty() ? nullptr : &children.front(); } SPObject const *firstChild() const { return children.empty() ? nullptr : &children.front(); } @@ -299,13 +310,19 @@ public: SPObject *nthChild(unsigned index); SPObject const *nthChild(unsigned index) const; - enum Action { ActionGeneral, ActionBBox, ActionUpdate, ActionShow }; + enum Action + { + ActionGeneral, + ActionBBox, + ActionUpdate, + ActionShow + }; /** * Retrieves the children as a std vector object, optionally ref'ing the children * in the process, if add_ref is specified. */ - std::vector<SPObject*> childList(bool add_ref, Action action = ActionGeneral); + std::vector<SPObject *> childList(bool add_ref, Action action = ActionGeneral); /** * Append repr as child of this object. @@ -359,7 +376,7 @@ public: * description (if any) should be deleted. * The second argument is optional - @see setTitleOrDesc() below for details. */ - bool setDesc(char const *desc, bool verbatim=false); + bool setDesc(char const *desc, bool verbatim = false); /** * Set the policy under which this object will be orphan-collected. @@ -390,9 +407,7 @@ public: * * @see SPObject::collectionPolicy */ - void setCollectionPolicy(CollectionPolicy policy) { - _collection_policy = policy; - } + void setCollectionPolicy(CollectionPolicy policy) { _collection_policy = policy; } /** * Requests a later automatic call to collectOrphan(). @@ -415,8 +430,9 @@ public: * * @see SPObject::deleteObject */ - void collectOrphan() { - if ( _total_hrefcount == 0 ) { + void collectOrphan() + { + if (_total_hrefcount == 0) { deleteObject(false); } } @@ -430,7 +446,7 @@ public: * It keeps a list of "owners". * @param owner Used to track who uses this object. */ - void hrefObject(SPObject* owner = nullptr); + void hrefObject(SPObject *owner = nullptr); /** * Decrease weak refcount. @@ -440,12 +456,12 @@ public: * @param owner Used to track who uses this object. * \pre hrefcount>0 */ - void unhrefObject(SPObject* owner = nullptr); + void unhrefObject(SPObject *owner = nullptr); /** * Check if object is referenced by any other object. */ - bool isReferenced() { return ( _total_hrefcount > 0 ); } + bool isReferenced() { return (_total_hrefcount > 0); } /** * Deletes an object, unparenting it from its parent. @@ -465,15 +481,12 @@ public: * @param propagate Notify observers of this object and its children that they have been * deleted? */ - void deleteObject(bool propagate = true) - { - deleteObject(propagate, propagate); - } + void deleteObject(bool propagate = true) { deleteObject(propagate, propagate); } /** * Removes all children except for the given object, it's children and it's ancesstors. */ - void cropToObject(SPObject *except); + void cropToObject(SPObject *except); /** * Connects a slot to be called when an object is deleted. @@ -487,11 +500,10 @@ public: * * @see SPObject::deleteObject */ - sigc::connection connectDelete(sigc::slot<void, SPObject *> slot) { - return _delete_signal.connect(slot); - } + sigc::connection connectDelete(sigc::slot<void, SPObject *> slot) { return _delete_signal.connect(slot); } - sigc::connection connectPositionChanged(sigc::slot<void, SPObject *> slot) { + sigc::connection connectPositionChanged(sigc::slot<void, SPObject *> slot) + { return _position_changed_signal.connect(slot); } @@ -506,7 +518,8 @@ public: /** * Indicates that another object supercedes this one. */ - void setSuccessor(SPObject *successor) { + void setSuccessor(SPObject *successor) + { assert(successor != NULL); assert(_successor == NULL); assert(successor->_successor == NULL); @@ -632,9 +645,8 @@ public: * * @return the connection formed thereby */ - sigc::connection connectModified( - sigc::slot<void, SPObject *, unsigned int> slot - ) { + sigc::connection connectModified(sigc::slot<void, SPObject *, unsigned int> slot) + { return _modified_signal.connect(slot); } @@ -646,9 +658,7 @@ public: */ void _updateTotalHRefCount(int increment); - void _requireSVGVersion(unsigned major, unsigned minor) { - _requireSVGVersion(Inkscape::Version(major, minor)); - } + void _requireSVGVersion(unsigned major, unsigned minor) { _requireSVGVersion(Inkscape::Version(major, minor)); } /** * Lifts SVG version of all root objects to version. @@ -678,7 +688,7 @@ public: /** * In list of object's children, move object behind prev. */ - void reorder(SPObject* obj, SPObject *prev); + void reorder(SPObject *obj, SPObject *prev); /** * Remove object from parent's children, release and unref it. @@ -696,27 +706,25 @@ public: unsigned getPosition(); - char const * getAttribute(char const *name,SPException *ex=nullptr) const; + char const *getAttribute(char const *name, SPException *ex = nullptr) const; void appendChild(Inkscape::XML::Node *child); - void addChild(Inkscape::XML::Node *child,Inkscape::XML::Node *prev=nullptr); + void addChild(Inkscape::XML::Node *child, Inkscape::XML::Node *prev = nullptr); /** * Call virtual set() function of object. */ void setKeyValue(SPAttr key, char const *value); + void setAttribute(Inkscape::Util::const_char_ptr key, Inkscape::Util::const_char_ptr value, + SPException *ex = nullptr); - void setAttribute(Inkscape::Util::const_char_ptr key, - Inkscape::Util::const_char_ptr value, - SPException *ex=nullptr); - - void setAttributeOrRemoveIfEmpty(Inkscape::Util::const_char_ptr key, - Inkscape::Util::const_char_ptr value, - SPException *ex=nullptr) { - this->setAttribute(key.data(), - (value.data() == nullptr || value.data()[0]=='\0') ? nullptr : value.data(), ex); + void setAttributeOrRemoveIfEmpty(Inkscape::Util::const_char_ptr key, Inkscape::Util::const_char_ptr value, + SPException *ex = nullptr) + { + this->setAttribute(key.data(), (value.data() == nullptr || value.data()[0] == '\0') ? nullptr : value.data(), + ex); } /** @@ -727,13 +735,13 @@ public: char const *getTagName(SPException *ex) const; - void removeAttribute(char const *key, SPException *ex=nullptr); + void removeAttribute(char const *key, SPException *ex = nullptr); void setCSS(SPCSSAttr *css, char const *attr); void changeCSS(SPCSSAttr *css, char const *attr); - bool storeAsDouble( char const *key, double *val ) const; + bool storeAsDouble(char const *key, double *val) const; private: // Private member functions used in the definitions of setTitle(), @@ -768,13 +776,13 @@ private: * Consequently, the return value is a newly allocated string (or NULL), and * must be freed (using g_free()) by the caller. */ - char * getTitleOrDesc(char const *svg_tagname) const; + char *getTitleOrDesc(char const *svg_tagname) const; /** * Find the first child of this object with a given tag name, * and return it. Returns NULL if there is no matching child. */ - SPObject * findFirstChild(char const *tagname) const; + SPObject *findFirstChild(char const *tagname) const; /** * Return the full textual content of an element (typically all the @@ -789,65 +797,66 @@ public: /** * Callback for attr_changed node event. */ - static void repr_attr_changed(Inkscape::XML::Node *repr, char const *key, char const *oldval, char const *newval, bool is_interactive, void* data); + static void repr_attr_changed(Inkscape::XML::Node *repr, char const *key, char const *oldval, char const *newval, + bool is_interactive, void *data); /** * Callback for content_changed node event. */ - static void repr_content_changed(Inkscape::XML::Node *repr, char const *oldcontent, char const *newcontent, void* data); + static void repr_content_changed(Inkscape::XML::Node *repr, char const *oldcontent, char const *newcontent, + void *data); /** * Callback for child_added node event. */ - static void repr_child_added(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, void* data); + static void repr_child_added(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, + void *data); /** * Callback for remove_child node event. */ - static void repr_child_removed(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, void *data); + static void repr_child_removed(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, + void *data); /** * Callback for order_changed node event. * * \todo fixme: */ - static void repr_order_changed(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *old, Inkscape::XML::Node *newer, void* data); - + static void repr_order_changed(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *old, + Inkscape::XML::Node *newer, void *data); friend class SPObjectImpl; protected: - virtual void build(SPDocument* doc, Inkscape::XML::Node* repr); - virtual void release(); + virtual void build(SPDocument *doc, Inkscape::XML::Node *repr); + virtual void release(); - virtual void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref); - virtual void remove_child(Inkscape::XML::Node* child); + virtual void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref); + virtual void remove_child(Inkscape::XML::Node *child); - virtual void order_changed(Inkscape::XML::Node* child, Inkscape::XML::Node* old_repr, Inkscape::XML::Node* new_repr); + virtual void order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_repr, + Inkscape::XML::Node *new_repr); - virtual void set(SPAttr key, const char* value); + virtual void set(SPAttr key, const char *value); - virtual void update(SPCtx* ctx, unsigned int flags); - virtual void modified(unsigned int flags); + virtual void update(SPCtx *ctx, unsigned int flags); + virtual void modified(unsigned int flags); - virtual Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags); + virtual Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags); typedef boost::intrusive::list_member_hook<> ListHook; ListHook _child_hook; + public: - typedef boost::intrusive::list< - SPObject, - boost::intrusive::member_hook< - SPObject, - ListHook, - &SPObject::_child_hook - >> ChildrenList; + typedef boost::intrusive::list<SPObject, boost::intrusive::member_hook<SPObject, ListHook, &SPObject::_child_hook>> + ChildrenList; ChildrenList children; - virtual void read_content(); + virtual void read_content(); - void recursivePrintTree(unsigned level = 0); // For debugging + void recursivePrintTree(unsigned level = 0); // For debugging static unsigned indent_level; - void objectTrace( std::string, bool in=true, unsigned flags=0 ); + void objectTrace(std::string, bool in = true, unsigned flags = 0); }; std::ostream &operator<<(std::ostream &out, const SPObject &o); @@ -863,11 +872,10 @@ std::ostream &operator<<(std::ostream &out, const SPObject &o); */ int sp_object_compare_position(SPObject const *first, SPObject const *second); bool sp_object_compare_position_bool(SPObject const *first, SPObject const *second); -gchar * sp_object_get_unique_id(SPObject *object, gchar const *defid); +gchar *sp_object_get_unique_id(SPObject *object, gchar const *defid); #endif // SP_OBJECT_H_SEEN - /* Local Variables: mode:c++ diff --git a/src/object/sp-offset.cpp b/src/object/sp-offset.cpp index bf7dddb509407e745909cf333b3190978f4480d0..3dcbabeb66065916dc584e697be90922f9be0767 100644 --- a/src/object/sp-offset.cpp +++ b/src/object/sp-offset.cpp @@ -18,22 +18,19 @@ #include "sp-offset.h" #include <cstring> -#include <string> - #include <glibmm/i18n.h> +#include <string> -#include "bad-uri-exception.h" -#include "svg/svg.h" #include "attributes.h" +#include "bad-uri-exception.h" #include "display/curve.h" - +#include "enums.h" #include "livarot/Path.h" #include "livarot/Shape.h" - -#include "enums.h" #include "preferences.h" #include "sp-text.h" #include "sp-use-reference.h" +#include "svg/svg.h" #include "uri.h" class SPDocument; @@ -63,32 +60,33 @@ class SPDocument; * radius (look in shape-editor-knotholders). */ -static void refresh_offset_source(SPOffset* offset); +static void refresh_offset_source(SPOffset *offset); -static void sp_offset_start_listening(SPOffset *offset,SPObject* to); +static void sp_offset_start_listening(SPOffset *offset, SPObject *to); static void sp_offset_quit_listening(SPOffset *offset); static void sp_offset_href_changed(SPObject *old_ref, SPObject *ref, SPOffset *offset); static void sp_offset_move_compensate(Geom::Affine const *mp, SPItem *original, SPOffset *self); static void sp_offset_delete_self(SPObject *deleted, SPOffset *self); -static void sp_offset_source_modified (SPObject *iSource, guint flags, SPItem *item); - +static void sp_offset_source_modified(SPObject *iSource, guint flags, SPItem *item); // slow= source path->polygon->offset of polygon->polygon->path // fast= source path->offset of source path->polygon->path // fast is not mathematically correct, because computing the offset of a single // cubic bezier patch is not trivial; in particular, there are problems with holes // reappearing in offset when the radius becomes too large -//TODO: need fix for bug: #384688 with fix released in r.14156 -//but reverted because bug #1507049 seems has more priority. -static bool use_slow_but_correct_offset_method = false; +// TODO: need fix for bug: #384688 with fix released in r.14156 +// but reverted because bug #1507049 seems has more priority. +static bool use_slow_but_correct_offset_method = false; -SPOffset::SPOffset() : SPShape() { +SPOffset::SPOffset() + : SPShape() +{ this->rad = 1.0; this->original = nullptr; this->originalPath = nullptr; this->knotSet = false; - this->sourceDirty=false; - this->isUpdating=false; + this->sourceDirty = false; + this->isUpdating = false; // init various connections this->sourceHref = nullptr; this->sourceRepr = nullptr; @@ -96,10 +94,12 @@ SPOffset::SPOffset() : SPShape() { // set up the uri reference this->sourceRef = new SPUseReference(this); - this->_changed_connection = this->sourceRef->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_offset_href_changed), this)); + this->_changed_connection = + this->sourceRef->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_offset_href_changed), this)); } -SPOffset::~SPOffset() { +SPOffset::~SPOffset() +{ delete this->sourceRef; this->_modified_connection.disconnect(); @@ -108,15 +108,16 @@ SPOffset::~SPOffset() { this->_transformed_connection.disconnect(); } -void SPOffset::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPOffset::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPShape::build(document, repr); - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. if (this->getRepr()->attribute("inkscape:radius")) { this->readAttr(SPAttr::INKSCAPE_RADIUS); } else { - //XML Tree being used directly here (as object->getRepr) - //in all the below lines in the block while it shouldn't be. + // XML Tree being used directly here (as object->getRepr) + // in all the below lines in the block while it shouldn't be. gchar const *oldA = this->getRepr()->attribute("sodipodi:radius"); this->setAttribute("inkscape:radius", oldA); this->removeAttribute("sodipodi:radius"); @@ -141,12 +142,12 @@ void SPOffset::build(SPDocument *document, Inkscape::XML::Node *repr) { if (oldA) { size_t lA = strlen(oldA); - char *nA=(char*)malloc((1+lA+1)*sizeof(char)); + char *nA = (char *)malloc((1 + lA + 1) * sizeof(char)); - memcpy(nA+1,oldA,lA*sizeof(char)); + memcpy(nA + 1, oldA, lA * sizeof(char)); - nA[0]='#'; - nA[lA+1]=0; + nA[0] = '#'; + nA[lA + 1] = 0; this->setAttribute("xlink:href", nA); @@ -159,7 +160,8 @@ void SPOffset::build(SPDocument *document, Inkscape::XML::Node *repr) { } } -Inkscape::XML::Node* SPOffset::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPOffset::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:path"); } @@ -175,29 +177,29 @@ Inkscape::XML::Node* SPOffset::write(Inkscape::XML::Document *xml_doc, Inkscape: repr->setAttribute("inkscape:href", this->sourceHref); } - // Make sure the offset has curve if (_curve == nullptr) { this->set_shape(); } // write that curve to "d" - char *d = sp_svg_write_path (this->_curve->get_pathvector()); + char *d = sp_svg_write_path(this->_curve->get_pathvector()); repr->setAttribute("d", d); - g_free (d); + g_free(d); SPShape::write(xml_doc, repr, flags | SP_SHAPE_WRITE_PATH); return repr; } -void SPOffset::release() { +void SPOffset::release() +{ if (this->original) { - free (this->original); + free(this->original); } if (this->originalPath) { - delete ((Path *) this->originalPath); + delete ((Path *)this->originalPath); } this->original = nullptr; @@ -215,27 +217,27 @@ void SPOffset::release() { SPShape::release(); } -void SPOffset::set(SPAttr key, const gchar* value) { - if ( this->sourceDirty ) { - refresh_offset_source(this); +void SPOffset::set(SPAttr key, const gchar *value) +{ + if (this->sourceDirty) { + refresh_offset_source(this); } /* fixme: we should really collect updates */ - switch (key) - { + switch (key) { case SPAttr::INKSCAPE_ORIGINAL: case SPAttr::SODIPODI_ORIGINAL: if (value == nullptr) { } else { if (this->original) { - free (this->original); - delete ((Path *) this->originalPath); + free(this->original); + delete ((Path *)this->originalPath); this->original = nullptr; this->originalPath = nullptr; } - this->original = strdup (value); + this->original = strdup(value); Geom::PathVector pv = sp_svg_read_pathv(this->original); @@ -244,42 +246,42 @@ void SPOffset::set(SPAttr key, const gchar* value) { this->knotSet = false; - if ( this->isUpdating == false ) { - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + if (this->isUpdating == false) { + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } break; case SPAttr::INKSCAPE_RADIUS: case SPAttr::SODIPODI_RADIUS: - if (!sp_svg_length_read_computed_absolute (value, &this->rad)) { - if (fabs (this->rad) < 0.01) { + if (!sp_svg_length_read_computed_absolute(value, &this->rad)) { + if (fabs(this->rad) < 0.01) { this->rad = (this->rad < 0) ? -0.01 : 0.01; } this->knotSet = false; // knotset=false because it's not set from the context } - if ( this->isUpdating == false ) { - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + if (this->isUpdating == false) { + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } break; case SPAttr::INKSCAPE_HREF: case SPAttr::XLINK_HREF: - if ( value == nullptr ) { + if (value == nullptr) { sp_offset_quit_listening(this); - if ( this->sourceHref ) { - g_free(this->sourceHref); + if (this->sourceHref) { + g_free(this->sourceHref); } this->sourceHref = nullptr; this->sourceRef->detach(); } else { - if ( this->sourceHref && ( strcmp(value, this->sourceHref) == 0 ) ) { + if (this->sourceHref && (strcmp(value, this->sourceHref) == 0)) { } else { - if ( this->sourceHref ) { - g_free(this->sourceHref); + if (this->sourceHref) { + g_free(this->sourceHref); } this->sourceHref = g_strdup(value); @@ -293,65 +295,65 @@ void SPOffset::set(SPAttr key, const gchar* value) { } } break; - + default: SPShape::set(key, value); break; } } -void SPOffset::update(SPCtx *ctx, guint flags) { - this->isUpdating=true; // prevent sp_offset_set from requesting updates - - if ( this->sourceDirty ) { - refresh_offset_source(this); +void SPOffset::update(SPCtx *ctx, guint flags) +{ + this->isUpdating = true; // prevent sp_offset_set from requesting updates + + if (this->sourceDirty) { + refresh_offset_source(this); } - - if (flags & - (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - + + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { this->set_shape(); } - - this->isUpdating=false; + + this->isUpdating = false; SPShape::update(ctx, flags); } -const char* SPOffset::displayName() const { - if ( this->sourceHref ) { +const char *SPOffset::displayName() const +{ + if (this->sourceHref) { return _("Linked Offset"); } else { return _("Dynamic Offset"); } } -gchar* SPOffset::description() const { +gchar *SPOffset::description() const +{ // TRANSLATORS COMMENT: %s is either "outset" or "inset" depending on sign - return g_strdup_printf(_("%s by %f pt"), (this->rad >= 0) ? - _("outset") : _("inset"), fabs (this->rad)); + return g_strdup_printf(_("%s by %f pt"), (this->rad >= 0) ? _("outset") : _("inset"), fabs(this->rad)); } -void SPOffset::set_shape() { - if ( this->originalPath == nullptr ) { +void SPOffset::set_shape() +{ + if (this->originalPath == nullptr) { // oops : no path?! (the offset object should do harakiri) return; } #ifdef OFFSET_VERBOSE - g_print ("rad=%g\n", offset->rad); + g_print("rad=%g\n", offset->rad); #endif // au boulot - if ( fabs(this->rad) < 0.01 ) { + if (fabs(this->rad) < 0.01) { // grosso modo: 0 - // just put the source of this (almost-non-offsetted) object as being the actual offset, + // just put the source of this (almost-non-offsetted) object as being the actual offset, // no one will notice. it's also useless to compute the offset with a 0 radius - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. const char *res_d = this->getRepr()->attribute("inkscape:original"); - if ( res_d ) { + if (res_d) { Geom::PathVector pv = sp_svg_read_pathv(res_d); setCurveInsync(std::make_unique<SPCurve>(pv)); setCurveBeforeLPE(curve()); @@ -361,53 +363,47 @@ void SPOffset::set_shape() { } // extra paranoiac careful check. the preceding if () should take care of this case - if (fabs (this->rad) < 0.01) { - this->rad = (this->rad < 0) ? -0.01 : 0.01; + if (fabs(this->rad) < 0.01) { + this->rad = (this->rad < 0) ? -0.01 : 0.01; } Path *orig = new Path; - orig->Copy ((Path *)this->originalPath); + orig->Copy((Path *)this->originalPath); - if ( use_slow_but_correct_offset_method == false ) { + if (use_slow_but_correct_offset_method == false) { // version par outline Shape *theShape = new Shape; Shape *theRes = new Shape; Path *originaux[1]; Path *res = new Path; - res->SetBackData (false); + res->SetBackData(false); // and now: offset float o_width; - if (this->rad >= 0) - { + if (this->rad >= 0) { o_width = this->rad; - orig->OutsideOutline (res, o_width, join_round, butt_straight, 20.0); - } - else - { + orig->OutsideOutline(res, o_width, join_round, butt_straight, 20.0); + } else { o_width = -this->rad; - orig->OutsideOutline (res, -o_width, join_round, butt_straight, 20.0); + orig->OutsideOutline(res, -o_width, join_round, butt_straight, 20.0); } - if (o_width >= 1.0) - { + if (o_width >= 1.0) { // res->ConvertForOffset (1.0, orig, offset->rad); - res->ConvertWithBackData (1.0); - } - else - { + res->ConvertWithBackData(1.0); + } else { // res->ConvertForOffset (o_width, orig, offset->rad); - res->ConvertWithBackData (o_width); + res->ConvertWithBackData(o_width); } - res->Fill (theShape, 0); - theRes->ConvertToShape (theShape, fill_positive); + res->Fill(theShape, 0); + theRes->ConvertToShape(theShape, fill_positive); originaux[0] = res; - theRes->ConvertToForme (orig, 1, originaux); + theRes->ConvertToForme(orig, 1, originaux); Geom::OptRect bbox = this->documentVisualBounds(); - if ( bbox ) { + if (bbox) { gdouble size = L2(bbox->dimensions()); gdouble const exp = this->transform.descrim(); @@ -415,11 +411,10 @@ void SPOffset::set_shape() { size /= exp; } - orig->Coalesce (size * 0.001); - //g_print ("coa %g exp %g item %p\n", size * 0.001, exp, item); + orig->Coalesce(size * 0.001); + // g_print ("coa %g exp %g item %p\n", size * 0.001, exp, item); } - // if (o_width >= 1.0) // { // orig->Coalesce (0.1); // small treshhold, since we only want to get rid of small segments @@ -442,196 +437,194 @@ void SPOffset::set_shape() { Shape *theShape = new Shape; Shape *theRes = new Shape; - // and now: offset float o_width; - if (this->rad >= 0) - { + if (this->rad >= 0) { o_width = this->rad; - } - else - { + } else { o_width = -this->rad; } // one has to have a measure of the details - if (o_width >= 1.0) - { - orig->ConvertWithBackData (0.5); - } - else - { - orig->ConvertWithBackData (0.5*o_width); + if (o_width >= 1.0) { + orig->ConvertWithBackData(0.5); + } else { + orig->ConvertWithBackData(0.5 * o_width); } - orig->Fill (theShape, 0); - theRes->ConvertToShape (theShape, fill_positive); + orig->Fill(theShape, 0); + theRes->ConvertToShape(theShape, fill_positive); Path *originaux[1]; - originaux[0]=orig; + originaux[0] = orig; Path *res = new Path; - theRes->ConvertToForme (res, 1, originaux); + theRes->ConvertToForme(res, 1, originaux); - int nbPart=0; - Path** parts=res->SubPaths(nbPart,true); - char *holes=(char*)malloc(nbPart*sizeof(char)); + int nbPart = 0; + Path **parts = res->SubPaths(nbPart, true); + char *holes = (char *)malloc(nbPart * sizeof(char)); // we offset contours separately, because we can. // this way, we avoid doing a unique big ConvertToShape when dealing with big shapes with lots of holes { - Shape* onePart=new Shape; - Shape* oneCleanPart=new Shape; + Shape *onePart = new Shape; + Shape *oneCleanPart = new Shape; theShape->Reset(); - for (int i=0;i<nbPart;i++) { - double partSurf=parts[i]->Surface(); + for (int i = 0; i < nbPart; i++) { + double partSurf = parts[i]->Surface(); parts[i]->Convert(1.0); { // raffiner si besoin - double bL,bT,bR,bB; - parts[i]->PolylineBoundingBox(bL,bT,bR,bB); - double measure=((bR-bL)+(bB-bT))*0.5; - if ( measure < 10.0 ) { - parts[i]->Convert(0.02*measure); + double bL, bT, bR, bB; + parts[i]->PolylineBoundingBox(bL, bT, bR, bB); + double measure = ((bR - bL) + (bB - bT)) * 0.5; + if (measure < 10.0) { + parts[i]->Convert(0.02 * measure); } } - if ( partSurf < 0 ) { // inverse par rapport a la realite + if (partSurf < 0) { // inverse par rapport a la realite // plein - holes[i]=0; - parts[i]->Fill(oneCleanPart,0); - onePart->ConvertToShape(oneCleanPart,fill_positive); // there aren't intersections in that one, but maybe duplicate points and null edges - oneCleanPart->MakeOffset(onePart,this->rad,join_round,20.0); - onePart->ConvertToShape(oneCleanPart,fill_positive); + holes[i] = 0; + parts[i]->Fill(oneCleanPart, 0); + onePart->ConvertToShape(oneCleanPart, fill_positive); // there aren't intersections in that one, but + // maybe duplicate points and null edges + oneCleanPart->MakeOffset(onePart, this->rad, join_round, 20.0); + onePart->ConvertToShape(oneCleanPart, fill_positive); onePart->CalcBBox(); - double typicalSize=0.5*((onePart->rightX-onePart->leftX)+(onePart->bottomY-onePart->topY)); + double typicalSize = + 0.5 * ((onePart->rightX - onePart->leftX) + (onePart->bottomY - onePart->topY)); - if ( typicalSize < 0.05 ) { - typicalSize=0.05; + if (typicalSize < 0.05) { + typicalSize = 0.05; } - typicalSize*=0.01; + typicalSize *= 0.01; - if ( typicalSize > 1.0 ) { - typicalSize=1.0; + if (typicalSize > 1.0) { + typicalSize = 1.0; } - onePart->ConvertToForme (parts[i]); - parts[i]->ConvertEvenLines (typicalSize); - parts[i]->Simplify (typicalSize); + onePart->ConvertToForme(parts[i]); + parts[i]->ConvertEvenLines(typicalSize); + parts[i]->Simplify(typicalSize); - double nPartSurf=parts[i]->Surface(); + double nPartSurf = parts[i]->Surface(); - if ( nPartSurf >= 0 ) { + if (nPartSurf >= 0) { // inversion de la surface -> disparait delete parts[i]; - parts[i]=nullptr; + parts[i] = nullptr; } else { } -/* int firstP=theShape->nbPt; - for (int j=0;j<onePart->nbPt;j++) theShape->AddPoint(onePart->pts[j].x); - for (int j=0;j<onePart->nbAr;j++) theShape->AddEdge(firstP+onePart->aretes[j].st,firstP+onePart->aretes[j].en);*/ + /* int firstP=theShape->nbPt; + for (int j=0;j<onePart->nbPt;j++) theShape->AddPoint(onePart->pts[j].x); + for (int j=0;j<onePart->nbAr;j++) + theShape->AddEdge(firstP+onePart->aretes[j].st,firstP+onePart->aretes[j].en);*/ } else { // trou - holes[i]=1; - parts[i]->Fill(oneCleanPart,0,false,true,true); - onePart->ConvertToShape(oneCleanPart,fill_positive); - oneCleanPart->MakeOffset(onePart,-this->rad,join_round,20.0); - onePart->ConvertToShape(oneCleanPart,fill_positive); -// for (int j=0;j<onePart->nbAr;j++) onePart->Inverse(j); // pas oublier de reinverser + holes[i] = 1; + parts[i]->Fill(oneCleanPart, 0, false, true, true); + onePart->ConvertToShape(oneCleanPart, fill_positive); + oneCleanPart->MakeOffset(onePart, -this->rad, join_round, 20.0); + onePart->ConvertToShape(oneCleanPart, fill_positive); + // for (int j=0;j<onePart->nbAr;j++) onePart->Inverse(j); // pas oublier de reinverser onePart->CalcBBox(); - double typicalSize=0.5*((onePart->rightX-onePart->leftX)+(onePart->bottomY-onePart->topY)); + double typicalSize = + 0.5 * ((onePart->rightX - onePart->leftX) + (onePart->bottomY - onePart->topY)); - if ( typicalSize < 0.05 ) { - typicalSize=0.05; + if (typicalSize < 0.05) { + typicalSize = 0.05; } - typicalSize*=0.01; + typicalSize *= 0.01; - if ( typicalSize > 1.0 ) { - typicalSize=1.0; + if (typicalSize > 1.0) { + typicalSize = 1.0; } - onePart->ConvertToForme (parts[i]); - parts[i]->ConvertEvenLines (typicalSize); - parts[i]->Simplify (typicalSize); - double nPartSurf=parts[i]->Surface(); + onePart->ConvertToForme(parts[i]); + parts[i]->ConvertEvenLines(typicalSize); + parts[i]->Simplify(typicalSize); + double nPartSurf = parts[i]->Surface(); - if ( nPartSurf >= 0 ) { + if (nPartSurf >= 0) { // inversion de la surface -> disparait delete parts[i]; - parts[i]=nullptr; + parts[i] = nullptr; } else { } /* int firstP=theShape->nbPt; for (int j=0;j<onePart->nbPt;j++) theShape->AddPoint(onePart->pts[j].x); - for (int j=0;j<onePart->nbAr;j++) theShape->AddEdge(firstP+onePart->aretes[j].en,firstP+onePart->aretes[j].st);*/ + for (int j=0;j<onePart->nbAr;j++) + theShape->AddEdge(firstP+onePart->aretes[j].en,firstP+onePart->aretes[j].st);*/ } -// delete parts[i]; + // delete parts[i]; } -// theShape->MakeOffset(theRes,offset->rad,join_round,20.0); + // theShape->MakeOffset(theRes,offset->rad,join_round,20.0); delete onePart; delete oneCleanPart; } - if ( nbPart > 1 ) { + if (nbPart > 1) { theShape->Reset(); - for (int i=0;i<nbPart;i++) { - if ( parts[i] ) { + for (int i = 0; i < nbPart; i++) { + if (parts[i]) { parts[i]->ConvertWithBackData(1.0); - if ( holes[i] ) { - parts[i]->Fill(theShape,i,true,true,true); + if (holes[i]) { + parts[i]->Fill(theShape, i, true, true, true); } else { - parts[i]->Fill(theShape,i,true,true,false); + parts[i]->Fill(theShape, i, true, true, false); } } } - theRes->ConvertToShape (theShape, fill_positive); - theRes->ConvertToForme (orig,nbPart,parts); + theRes->ConvertToShape(theShape, fill_positive); + theRes->ConvertToForme(orig, nbPart, parts); - for (int i=0;i<nbPart;i++) { - if ( parts[i] ) { - delete parts[i]; - } + for (int i = 0; i < nbPart; i++) { + if (parts[i]) { + delete parts[i]; + } } - } else if ( nbPart == 1 ) { + } else if (nbPart == 1) { orig->Copy(parts[0]); - for (int i=0;i<nbPart;i++) { - if ( parts[i] ) { - delete parts[i]; - } + for (int i = 0; i < nbPart; i++) { + if (parts[i]) { + delete parts[i]; + } } } else { orig->Reset(); } -// theRes->ConvertToShape (theShape, fill_positive); -// theRes->ConvertToForme (orig); - -/* if (o_width >= 1.0) { - orig->ConvertEvenLines (1.0); - orig->Simplify (1.0); - } else { - orig->ConvertEvenLines (1.0*o_width); - orig->Simplify (1.0 * o_width); - }*/ - - if ( parts ) { - free(parts); + // theRes->ConvertToShape (theShape, fill_positive); + // theRes->ConvertToForme (orig); + + /* if (o_width >= 1.0) { + orig->ConvertEvenLines (1.0); + orig->Simplify (1.0); + } else { + orig->ConvertEvenLines (1.0*o_width); + orig->Simplify (1.0 * o_width); + }*/ + + if (parts) { + free(parts); } - if ( holes ) { - free(holes); + if (holes) { + free(holes); } delete res; @@ -641,16 +634,12 @@ void SPOffset::set_shape() { { char *res_d = nullptr; - if (orig->descr_cmd.size() <= 1) - { + if (orig->descr_cmd.size() <= 1) { // Aie.... nothing left. - res_d = strdup ("M 0 0 L 0 0 z"); - //printf("%s\n",res_d); - } - else - { - - res_d = orig->svg_dump_path (); + res_d = strdup("M 0 0 L 0 0 z"); + // printf("%s\n",res_d); + } else { + res_d = orig->svg_dump_path(); } delete orig; @@ -659,15 +648,16 @@ void SPOffset::set_shape() { setCurveInsync(std::make_unique<SPCurve>(pv)); setCurveBeforeLPE(curve()); - free (res_d); + free(res_d); } } -void SPOffset::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const { +void SPOffset::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, + Inkscape::SnapPreferences const *snapprefs) const +{ SPShape::snappoints(p, snapprefs); } - // utilitaires pour les poignees // used to get the distance to the shape: distance to polygon give the fabs(radius), we still need // the sign. for edges, it's easy to determine which side the point is on, for points of the polygon @@ -687,8 +677,7 @@ void SPOffset::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape * dot(A, rot90(B))*dot(C, rot90(B)) == -1. * -- njh */ -static bool -vectors_are_clockwise (Geom::Point A, Geom::Point B, Geom::Point C) +static bool vectors_are_clockwise(Geom::Point A, Geom::Point B, Geom::Point C) { using Geom::rot90; double ab_s = dot(A, rot90(B)); @@ -698,7 +687,7 @@ vectors_are_clockwise (Geom::Point A, Geom::Point B, Geom::Point C) double ca_s = dot(C, rot90(A)); double ca_c = dot(C, A); - double ab_a = acos (ab_c); + double ab_a = acos(ab_c); if (ab_c <= -1.0) { ab_a = M_PI; @@ -712,7 +701,7 @@ vectors_are_clockwise (Geom::Point A, Geom::Point B, Geom::Point C) ab_a = 2 * M_PI - ab_a; } - double bc_a = acos (bc_c); + double bc_a = acos(bc_c); if (bc_c <= -1.0) { bc_a = M_PI; @@ -726,7 +715,7 @@ vectors_are_clockwise (Geom::Point A, Geom::Point B, Geom::Point C) bc_a = 2 * M_PI - bc_a; } - double ca_a = acos (ca_c); + double ca_a = acos(ca_c); if (ca_c <= -1.0) { ca_a = M_PI; @@ -757,10 +746,9 @@ vectors_are_clockwise (Geom::Point A, Geom::Point B, Geom::Point C) * so result > 0 ==outset and result < 0 ==inset. thus result<0 means * 'px inside source'. */ -double -sp_offset_distance_to_original (SPOffset * offset, Geom::Point px) +double sp_offset_distance_to_original(SPOffset *offset, Geom::Point px) { - if (offset == nullptr || offset->originalPath == nullptr || ((Path *) offset->originalPath)->descr_cmd.size() <= 1) { + if (offset == nullptr || offset->originalPath == nullptr || ((Path *)offset->originalPath)->descr_cmd.size() <= 1) { return 1.0; } @@ -778,73 +766,59 @@ sp_offset_distance_to_original (SPOffset * offset, Geom::Point px) * delay of one context. */ // move - ((Path *) offset->originalPath)->Convert (1.0); - ((Path *) offset->originalPath)->Fill (theShape, 0); - theRes->ConvertToShape (theShape, fill_oddEven); - - if (theRes->numberOfEdges() <= 1) - { + ((Path *)offset->originalPath)->Convert(1.0); + ((Path *)offset->originalPath)->Fill(theShape, 0); + theRes->ConvertToShape(theShape, fill_oddEven); - } - else - { + if (theRes->numberOfEdges() <= 1) { + } else { double ptDist = -1.0; bool ptSet = false; double arDist = -1.0; bool arSet = false; // first get the minimum distance to the points - for (int i = 0; i < theRes->numberOfPoints(); i++) - { - if (theRes->getPoint(i).totalDegree() > 0) - { + for (int i = 0; i < theRes->numberOfPoints(); i++) { + if (theRes->getPoint(i).totalDegree() > 0) { Geom::Point nx = theRes->getPoint(i).x; - Geom::Point nxpx = px-nx; - double ndist = sqrt (dot(nxpx,nxpx)); + Geom::Point nxpx = px - nx; + double ndist = sqrt(dot(nxpx, nxpx)); - if (ptSet == false || fabs (ndist) < fabs (ptDist)) - { + if (ptSet == false || fabs(ndist) < fabs(ptDist)) { // we have a new minimum distance // now we need to wheck if px is inside or outside (for the sign) nx = px - theRes->getPoint(i).x; - double nlen = sqrt (dot(nx , nx)); + double nlen = sqrt(dot(nx, nx)); nx /= nlen; int pb, cb, fb; fb = theRes->getPoint(i).incidentEdge[LAST]; pb = theRes->getPoint(i).incidentEdge[LAST]; cb = theRes->getPoint(i).incidentEdge[FIRST]; - do - { + do { // one angle Geom::Point prx, nex; prx = theRes->getEdge(pb).dx; - nlen = sqrt (dot(prx, prx)); + nlen = sqrt(dot(prx, prx)); prx /= nlen; nex = theRes->getEdge(cb).dx; - nlen = sqrt (dot(nex , nex)); + nlen = sqrt(dot(nex, nex)); nex /= nlen; - if (theRes->getEdge(pb).en == i) - { + if (theRes->getEdge(pb).en == i) { prx = -prx; } - if (theRes->getEdge(cb).en == i) - { + if (theRes->getEdge(cb).en == i) { nex = -nex; } - if (vectors_are_clockwise (nex, nx, prx)) - { + if (vectors_are_clockwise(nex, nx, prx)) { // we're in that angle. set the sign, and exit that loop - if (theRes->getEdge(cb).st == i) - { + if (theRes->getEdge(cb).st == i) { ptDist = -ndist; ptSet = true; - } - else - { + } else { ptDist = ndist; ptSet = true; } @@ -852,7 +826,7 @@ sp_offset_distance_to_original (SPOffset * offset, Geom::Point px) } pb = cb; - cb = theRes->NextAt (i, cb); + cb = theRes->NextAt(i, cb); } while (cb >= 0 && pb >= 0 && pb != fb); @@ -861,25 +835,21 @@ sp_offset_distance_to_original (SPOffset * offset, Geom::Point px) } // loop over the edges to try to improve the distance - for (int i = 0; i < theRes->numberOfEdges(); i++) - { + for (int i = 0; i < theRes->numberOfEdges(); i++) { Geom::Point sx = theRes->getPoint(theRes->getEdge(i).st).x; Geom::Point ex = theRes->getPoint(theRes->getEdge(i).en).x; Geom::Point nx = ex - sx; - double len = sqrt (dot(nx,nx)); + double len = sqrt(dot(nx, nx)); - if (len > 0.0001) - { - Geom::Point pxsx=px-sx; - double ab = dot(nx,pxsx); + if (len > 0.0001) { + Geom::Point pxsx = px - sx; + double ab = dot(nx, pxsx); - if (ab > 0 && ab < len * len) - { + if (ab > 0 && ab < len * len) { // we're in the zone of influence of the segment double ndist = (cross(nx, pxsx)) / len; - if (arSet == false || fabs (ndist) < fabs (arDist)) - { + if (arSet == false || fabs(ndist) < fabs(arDist)) { arDist = ndist; arSet = true; } @@ -887,8 +857,7 @@ sp_offset_distance_to_original (SPOffset * offset, Geom::Point px) } } - if (arSet || ptSet) - { + if (arSet || ptSet) { if (arSet == false) { arDist = ptDist; } @@ -897,7 +866,7 @@ sp_offset_distance_to_original (SPOffset * offset, Geom::Point px) ptDist = arDist; } - if (fabs (ptDist) < fabs (arDist)) { + if (fabs(ptDist) < fabs(arDist)) { dist = ptDist; } else { dist = arDist; @@ -917,8 +886,7 @@ sp_offset_distance_to_original (SPOffset * offset, Geom::Point px) * * \return the topmost point on the offset. */ -void -sp_offset_top_point (SPOffset const * offset, Geom::Point *px) +void sp_offset_top_point(SPOffset const *offset, Geom::Point *px) { (*px) = Geom::Point(0, 0); @@ -926,17 +894,15 @@ sp_offset_top_point (SPOffset const * offset, Geom::Point *px) return; } - if (offset->knotSet) - { + if (offset->knotSet) { (*px) = offset->knot; return; } SPCurve const *curve = offset->curve(); - if (curve == nullptr) - { - const_cast<SPOffset*>(offset)->set_shape(); + if (curve == nullptr) { + const_cast<SPOffset *>(offset)->set_shape(); curve = offset->curve(); @@ -944,8 +910,7 @@ sp_offset_top_point (SPOffset const * offset, Geom::Point *px) return; } - if (curve->is_empty()) - { + if (curve->is_empty()) { return; } @@ -954,12 +919,11 @@ sp_offset_top_point (SPOffset const * offset, Geom::Point *px) Shape *theShape = new Shape; - finalPath->Convert (1.0); - finalPath->Fill (theShape, 0); + finalPath->Convert(1.0); + finalPath->Fill(theShape, 0); - if (theShape->hasPoints()) - { - theShape->SortPoints (); + if (theShape->hasPoints()) { + theShape->SortPoints(); *px = theShape->getPoint(0).x; } @@ -968,9 +932,9 @@ sp_offset_top_point (SPOffset const * offset, Geom::Point *px) } // the listening functions -static void sp_offset_start_listening(SPOffset *offset,SPObject* to) +static void sp_offset_start_listening(SPOffset *offset, SPObject *to) { - if ( to == nullptr ) { + if (to == nullptr) { return; } @@ -978,13 +942,15 @@ static void sp_offset_start_listening(SPOffset *offset,SPObject* to) offset->sourceRepr = to->getRepr(); offset->_delete_connection = to->connectDelete(sigc::bind(sigc::ptr_fun(&sp_offset_delete_self), offset)); - offset->_transformed_connection = SP_ITEM(to)->connectTransformed(sigc::bind(sigc::ptr_fun(&sp_offset_move_compensate), offset)); - offset->_modified_connection = to->connectModified(sigc::bind<2>(sigc::ptr_fun(&sp_offset_source_modified), offset)); + offset->_transformed_connection = + SP_ITEM(to)->connectTransformed(sigc::bind(sigc::ptr_fun(&sp_offset_move_compensate), offset)); + offset->_modified_connection = + to->connectModified(sigc::bind<2>(sigc::ptr_fun(&sp_offset_source_modified), offset)); } static void sp_offset_quit_listening(SPOffset *offset) { - if ( offset->sourceObject == nullptr ) { + if (offset->sourceObject == nullptr) { return; } @@ -996,8 +962,7 @@ static void sp_offset_quit_listening(SPOffset *offset) offset->sourceObject = nullptr; } -static void -sp_offset_href_changed(SPObject */*old_ref*/, SPObject */*ref*/, SPOffset *offset) +static void sp_offset_href_changed(SPObject * /*old_ref*/, SPObject * /*ref*/, SPOffset *offset) { sp_offset_quit_listening(offset); @@ -1005,15 +970,15 @@ sp_offset_href_changed(SPObject */*old_ref*/, SPObject */*ref*/, SPOffset *offse SPItem *refobj = offset->sourceRef->getObject(); if (refobj) { - sp_offset_start_listening(offset,refobj); + sp_offset_start_listening(offset, refobj); } - offset->sourceDirty=true; + offset->sourceDirty = true; offset->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } -static void sp_offset_move_compensate(Geom::Affine const *mp, SPItem */*original*/, SPOffset *self) +static void sp_offset_move_compensate(Geom::Affine const *mp, SPItem * /*original*/, SPOffset *self) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); guint mode = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_PARALLEL); @@ -1021,7 +986,7 @@ static void sp_offset_move_compensate(Geom::Affine const *mp, SPItem */*original Geom::Affine m(*mp); if (!(m.isTranslation()) || mode == SP_CLONE_COMPENSATION_NONE) { - self->sourceDirty=true; + self->sourceDirty = true; self->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); return; } @@ -1043,7 +1008,7 @@ static void sp_offset_move_compensate(Geom::Affine const *mp, SPItem */*original g_assert_not_reached(); } - self->sourceDirty=true; + self->sourceDirty = true; // commit the compensation self->transform *= offset_move; @@ -1051,8 +1016,7 @@ static void sp_offset_move_compensate(Geom::Affine const *mp, SPItem */*original self->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -static void -sp_offset_delete_self(SPObject */*deleted*/, SPOffset *offset) +static void sp_offset_delete_self(SPObject * /*deleted*/, SPOffset *offset) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); guint const mode = prefs->getInt("/options/cloneorphans/value", SP_CLONE_ORPHANS_UNLINK); @@ -1061,8 +1025,8 @@ sp_offset_delete_self(SPObject */*deleted*/, SPOffset *offset) // leave it be. just forget about the source sp_offset_quit_listening(offset); - if ( offset->sourceHref ) { - g_free(offset->sourceHref); + if (offset->sourceHref) { + g_free(offset->sourceHref); } offset->sourceHref = nullptr; @@ -1072,35 +1036,33 @@ sp_offset_delete_self(SPObject */*deleted*/, SPOffset *offset) } } -static void -sp_offset_source_modified (SPObject */*iSource*/, guint flags, SPItem *item) +static void sp_offset_source_modified(SPObject * /*iSource*/, guint flags, SPItem *item) { SPOffset *offset = SP_OFFSET(item); - offset->sourceDirty=true; + offset->sourceDirty = true; if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG)) { offset->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } -static void -refresh_offset_source(SPOffset* offset) +static void refresh_offset_source(SPOffset *offset) { - if ( offset == nullptr ) { - return; + if (offset == nullptr) { + return; } - offset->sourceDirty=false; + offset->sourceDirty = false; // le mauvais cas: pas d'attribut d => il faut verifier que c'est une SPShape puis prendre le contour // The bad case: no d attribute. Must check that it's an SPShape and then take the outline. - SPObject *refobj=offset->sourceObject; + SPObject *refobj = offset->sourceObject; - if ( refobj == nullptr ) { - return; + if (refobj == nullptr) { + return; } - SPItem *item = SP_ITEM (refobj); + SPItem *item = SP_ITEM(refobj); std::unique_ptr<SPCurve> curve; if (auto shape = dynamic_cast<SPShape const *>(item)) { @@ -1137,60 +1099,53 @@ refresh_offset_source(SPOffset* offset) Shape *theShape = new Shape; Shape *theRes = new Shape; - orig->ConvertWithBackData (1.0); - orig->Fill (theShape, 0); + orig->ConvertWithBackData(1.0); + orig->Fill(theShape, 0); - css = sp_repr_css_attr (offset->sourceRepr , "style"); - val = sp_repr_css_property (css, "fill-rule", nullptr); + css = sp_repr_css_attr(offset->sourceRepr, "style"); + val = sp_repr_css_property(css, "fill-rule", nullptr); - 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 (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); } Path *originaux[1]; originaux[0] = orig; Path *res = new Path; - theRes->ConvertToForme (res, 1, originaux); + theRes->ConvertToForme(res, 1, originaux); delete theShape; delete theRes; - char *res_d = res->svg_dump_path (); + char *res_d = res->svg_dump_path(); delete res; delete orig; // TODO fix: - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. offset->setAttribute("inkscape:original", res_d); - free (res_d); + free(res_d); } } -SPItem * -sp_offset_get_source (SPOffset *offset) +SPItem *sp_offset_get_source(SPOffset *offset) { if (offset && offset->sourceRef) { SPItem *refobj = offset->sourceRef->getObject(); - if (SP_IS_ITEM (refobj)) { - return (SPItem *) refobj; + if (SP_IS_ITEM(refobj)) { + return (SPItem *)refobj; } } return nullptr; } - /* Local Variables: mode:c++ diff --git a/src/object/sp-offset.h b/src/object/sp-offset.h index b0a08080fb5ff577273a4ade61ae4f58c97c7883..2d167d1633af5846f8cec8caaae57c079ba9a27e 100644 --- a/src/object/sp-offset.h +++ b/src/object/sp-offset.h @@ -17,8 +17,8 @@ #include "sp-shape.h" -#define SP_OFFSET(obj) (dynamic_cast<SPOffset*>((SPObject*)obj)) -#define SP_IS_OFFSET(obj) (dynamic_cast<const SPOffset*>((SPObject*)obj) != NULL) +#define SP_OFFSET(obj) (dynamic_cast<SPOffset *>((SPObject *)obj)) +#define SP_IS_OFFSET(obj) (dynamic_cast<const SPOffset *>((SPObject *)obj) != NULL) class SPUseReference; @@ -50,10 +50,11 @@ class SPUseReference; * points, or more precisely one control point, that's enough to define the * radius (look in shape-editor-knotholders). */ -class SPOffset : public SPShape { +class SPOffset : public SPShape +{ public: - SPOffset(); - ~SPOffset() override; + SPOffset(); + ~SPOffset() override; void *originalPath; ///< will be a livarot Path, just don't declare it here to please the gcc linker FIXME what? char *original; ///< SVG description of the source path @@ -66,33 +67,34 @@ public: bool sourceDirty; bool isUpdating; - char *sourceHref; - SPUseReference *sourceRef; - Inkscape::XML::Node *sourceRepr; ///< the repr associated with that id - SPObject *sourceObject; + char *sourceHref; + SPUseReference *sourceRef; + Inkscape::XML::Node *sourceRepr; ///< the repr associated with that id + SPObject *sourceObject; sigc::connection _modified_connection; sigc::connection _delete_connection; sigc::connection _changed_connection; sigc::connection _transformed_connection; - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void set(SPAttr key, char const* value) override; - void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned flags) override; - void release() override; + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void set(SPAttr key, char const *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned flags) override; + void release() override; - void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const override; - const char* displayName() const override; - char* description() const override; + void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, + Inkscape::SnapPreferences const *snapprefs) const override; + const char *displayName() const override; + char *description() const override; - void set_shape() override; + void set_shape() override; }; -double sp_offset_distance_to_original (SPOffset * offset, Geom::Point px); -void sp_offset_top_point (SPOffset const *offset, Geom::Point *px); +double sp_offset_distance_to_original(SPOffset *offset, Geom::Point px); +void sp_offset_top_point(SPOffset const *offset, Geom::Point *px); -SPItem *sp_offset_get_source (SPOffset *offset); +SPItem *sp_offset_get_source(SPOffset *offset); #endif diff --git a/src/object/sp-paint-server-reference.h b/src/object/sp-paint-server-reference.h index 4f496bab4ce46c314dc0d94fcef2db0a88637adb..9b10ff6b7aa355c2e3d7435af5e5875df0dd65ea 100644 --- a/src/object/sp-paint-server-reference.h +++ b/src/object/sp-paint-server-reference.h @@ -22,10 +22,15 @@ class SPDocument; class SPObject; class SPPaintServer; -class SPPaintServerReference : public Inkscape::URIReference { +class SPPaintServerReference : public Inkscape::URIReference +{ public: - SPPaintServerReference (SPObject *obj) : URIReference(obj) {} - SPPaintServerReference (SPDocument *doc) : URIReference(doc) {} + SPPaintServerReference(SPObject *obj) + : URIReference(obj) + {} + SPPaintServerReference(SPDocument *doc) + : URIReference(doc) + {} SPPaintServer *getObject() const; protected: diff --git a/src/object/sp-paint-server.cpp b/src/object/sp-paint-server.cpp index 1ec4db8413bb781e5acb284df13e6cddd1c913e0..8ee40706c035fad3ac6850b5d1d9b7d8cbf882ba 100644 --- a/src/object/sp-paint-server.cpp +++ b/src/object/sp-paint-server.cpp @@ -14,10 +14,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "sp-paint-server-reference.h" #include "sp-paint-server.h" #include "sp-gradient.h" +#include "sp-paint-server-reference.h" #include "xml/node.h" SPPaintServer *SPPaintServerReference::getObject() const @@ -30,8 +30,10 @@ bool SPPaintServerReference::_acceptObject(SPObject *obj) const return SP_IS_PAINT_SERVER(obj) && URIReference::_acceptObject(obj); } -SPPaintServer::SPPaintServer() : SPObject() { - this->swatch = false; +SPPaintServer::SPPaintServer() + : SPObject() +{ + this->swatch = false; } SPPaintServer::~SPPaintServer() = default; @@ -41,7 +43,6 @@ bool SPPaintServer::isSwatch() const return swatch; } - // TODO: So a solid brush is a gradient with a swatch and zero stops? // Should we derive a new class for that? Or at least make this method // virtual and move it out of the way? @@ -50,7 +51,7 @@ bool SPPaintServer::isSolid() const bool solid = false; if (swatch && SP_IS_GRADIENT(this)) { SPGradient *grad = SP_GRADIENT(this); - if ( grad->hasStops() && (grad->getStopCount() == 0) ) { + if (grad->hasStops() && (grad->getStopCount() == 0)) { solid = true; } } @@ -62,20 +63,17 @@ bool SPPaintServer::isValid() const return true; } -Inkscape::DrawingPattern *SPPaintServer::show(Inkscape::Drawing &/*drawing*/, unsigned int /*key*/, Geom::OptRect /*bbox*/) +Inkscape::DrawingPattern *SPPaintServer::show(Inkscape::Drawing & /*drawing*/, unsigned int /*key*/, + Geom::OptRect /*bbox*/) { return nullptr; } -void SPPaintServer::hide(unsigned int /*key*/) -{ -} +void SPPaintServer::hide(unsigned int /*key*/) {} -void SPPaintServer::setBBox(unsigned int /*key*/, Geom::OptRect const &/*bbox*/) -{ -} +void SPPaintServer::setBBox(unsigned int /*key*/, Geom::OptRect const & /*bbox*/) {} -cairo_pattern_t* SPPaintServer::pattern_new(cairo_t * /*ct*/, Geom::OptRect const &/*bbox*/, double /*opacity*/) +cairo_pattern_t *SPPaintServer::pattern_new(cairo_t * /*ct*/, Geom::OptRect const & /*bbox*/, double /*opacity*/) { return nullptr; } diff --git a/src/object/sp-paint-server.h b/src/object/sp-paint-server.h index 9e0617048e3701d09359da16bbf7cea2117d19be..73b7f4ca777d2635532a0c666fa8e8da2f61b0da 100644 --- a/src/object/sp-paint-server.h +++ b/src/object/sp-paint-server.h @@ -16,9 +16,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cairo.h> #include <2geom/rect.h> +#include <cairo.h> #include <sigc++/slot.h> + #include "sp-object.h" namespace Inkscape { @@ -26,29 +27,31 @@ namespace Inkscape { class Drawing; class DrawingPattern; -} +} // namespace Inkscape -#define SP_PAINT_SERVER(obj) (dynamic_cast<SPPaintServer*>((SPObject*)obj)) -#define SP_IS_PAINT_SERVER(obj) (dynamic_cast<const SPPaintServer*>((SPObject*)obj) != NULL) +#define SP_PAINT_SERVER(obj) (dynamic_cast<SPPaintServer *>((SPObject *)obj)) +#define SP_IS_PAINT_SERVER(obj) (dynamic_cast<const SPPaintServer *>((SPObject *)obj) != NULL) -class SPPaintServer : public SPObject { +class SPPaintServer : public SPObject +{ public: - SPPaintServer(); - ~SPPaintServer() override; + SPPaintServer(); + ~SPPaintServer() override; bool isSwatch() const; bool isSolid() const; virtual bool isValid() const; - //There are two ways to render a paint. The simple one is to create cairo_pattern_t structure - //on demand by pattern_new method. It is used for gradients. The other one is to add elements - //representing PaintServer in NR tree. It is used by hatches and patterns. - //Either pattern new or all three methods show, hide, setBBox need to be implemented - virtual Inkscape::DrawingPattern *show(Inkscape::Drawing &drawing, unsigned int key, Geom::OptRect bbox); // TODO check passing bbox by value. Looks suspicious. + // There are two ways to render a paint. The simple one is to create cairo_pattern_t structure + // on demand by pattern_new method. It is used for gradients. The other one is to add elements + // representing PaintServer in NR tree. It is used by hatches and patterns. + // Either pattern new or all three methods show, hide, setBBox need to be implemented + virtual Inkscape::DrawingPattern *show(Inkscape::Drawing &drawing, unsigned int key, + Geom::OptRect bbox); // TODO check passing bbox by value. Looks suspicious. virtual void hide(unsigned int key); virtual void setBBox(unsigned int key, Geom::OptRect const &bbox); - virtual cairo_pattern_t* pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity); + virtual cairo_pattern_t *pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity); protected: bool swatch; @@ -65,7 +68,8 @@ protected: * \pre SP_IS_GRADIENT(src). */ template <class PaintServer> -PaintServer *chase_hrefs(PaintServer *src, sigc::slot<bool, PaintServer const *> match) { +PaintServer *chase_hrefs(PaintServer *src, sigc::slot<bool, PaintServer const *> match) +{ /* Use a pair of pointers for detecting loops: p1 advances half as fast as p2. If there is a loop, then once p1 has entered the loop, we'll detect it the next time the distance between p1 and p2 is a multiple of the loop size. */ @@ -85,7 +89,7 @@ PaintServer *chase_hrefs(PaintServer *src, sigc::slot<bool, PaintServer const *> } do1 = !do1; - if ( p2 == p1 ) { + if (p2 == p1) { /* We've been here before, so return NULL to indicate that no matching gradient found * in the chain. */ return nullptr; diff --git a/src/object/sp-path.cpp b/src/object/sp-path.cpp index b839720e220b3eda08ef62a04c2122a0a54e78d0..19895980c1275f8ac63632d4b8c157298c35257d 100644 --- a/src/object/sp-path.cpp +++ b/src/object/sp-path.cpp @@ -16,32 +16,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-path.h" + +#include <2geom/curves.h> #include <glibmm/i18n.h> #include <glibmm/regex.h> +#include "attributes.h" +#include "desktop-style.h" +#include "desktop.h" +#include "display/curve.h" +#include "document.h" +#include "helper/geom-curves.h" +#include "inkscape.h" #include "live_effects/effect.h" -#include "live_effects/lpeobject.h" #include "live_effects/lpeobject-reference.h" +#include "live_effects/lpeobject.h" +#include "sp-guide.h" #include "sp-lpe-item.h" - -#include "display/curve.h" -#include <2geom/curves.h> -#include "helper/geom-curves.h" - +#include "style.h" #include "svg/svg.h" -#include "xml/repr.h" -#include "attributes.h" - -#include "sp-path.h" -#include "sp-guide.h" - -#include "document.h" -#include "desktop.h" - -#include "desktop-style.h" #include "ui/tools/tool-base.h" -#include "inkscape.h" -#include "style.h" +#include "xml/repr.h" #define noPATH_VERBOSE @@ -50,26 +46,27 @@ gint SPPath::nodesInPath() const return _curve ? _curve->nodes_in_path() : 0; } -const char* SPPath::displayName() const { +const char *SPPath::displayName() const +{ return _("Path"); } -gchar* SPPath::description() const { +gchar *SPPath::description() const +{ int count = this->nodesInPath(); char *lpe_desc = g_strdup(""); - + if (hasPathEffect()) { Glib::ustring s; - PathEffectList effect_list = this->getEffectList(); - - for (auto & it : effect_list) - { + PathEffectList effect_list = this->getEffectList(); + + for (auto &it : effect_list) { LivePathEffectObject *lpeobj = it->lpeobject; - + if (!lpeobj || !lpeobj->get_lpe()) { break; } - + if (s.empty()) { s = lpeobj->get_lpe()->getName(); } else { @@ -78,27 +75,26 @@ gchar* SPPath::description() const { } lpe_desc = g_strdup_printf(_(", path effect: %s"), s.c_str()); } - char *ret = g_strdup_printf(ngettext( - _("%i node%s"), _("%i nodes%s"), count), count, lpe_desc); + char *ret = g_strdup_printf(ngettext(_("%i node%s"), _("%i nodes%s"), count), count, lpe_desc); g_free(lpe_desc); return ret; } -void SPPath::convert_to_guides() const { +void SPPath::convert_to_guides() const +{ if (!this->_curve) { return; } - std::list<std::pair<Geom::Point, Geom::Point> > pts; + std::list<std::pair<Geom::Point, Geom::Point>> pts; Geom::Affine const i2dt(this->i2dt_affine()); - Geom::PathVector const & pv = this->_curve->get_pathvector(); - - for(const auto & pit : pv) { - for(Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_default(); ++cit) { + Geom::PathVector const &pv = this->_curve->get_pathvector(); + + for (const auto &pit : pv) { + for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_default(); ++cit) { // only add curves for straight line segments - if( is_straight_curve(*cit) ) - { + if (is_straight_curve(*cit)) { pts.emplace_back(cit->initialPoint() * i2dt, cit->finalPoint() * i2dt); } } @@ -107,12 +103,15 @@ void SPPath::convert_to_guides() const { sp_guide_pt_pairs_to_guides(this->document, pts); } -SPPath::SPPath() : SPShape(), connEndPair(this) { -} +SPPath::SPPath() + : SPShape() + , connEndPair(this) +{} SPPath::~SPPath() = default; -void SPPath::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPPath::build(SPDocument *document, Inkscape::XML::Node *repr) +{ /* Are these calls actually necessary? */ this->readAttr(SPAttr::MARKER); this->readAttr(SPAttr::MARKER_START); @@ -131,8 +130,7 @@ void SPPath::build(SPDocument *document, Inkscape::XML::Node *repr) { if (style->d.set && - (d_source == SP_STYLE_SRC_STYLE_PROP || d_source == SP_STYLE_SRC_STYLE_SHEET) ) { - + (d_source == SP_STYLE_SRC_STYLE_PROP || d_source == SP_STYLE_SRC_STYLE_SHEET)) { if (char const *d_val = style->d.value()) { // Chrome shipped with a different syntax for property vs attribute. // The SVG Working group decided to follow the Chrome syntax (which may @@ -147,22 +145,21 @@ void SPPath::build(SPDocument *document, Inkscape::XML::Node *repr) { regex->match(input, matchInfo); if (matchInfo.matches()) { - Glib::ustring value = matchInfo.fetch(1); + Glib::ustring value = matchInfo.fetch(1); Geom::PathVector pv = sp_svg_read_pathv(value.c_str()); auto curve = std::make_unique<SPCurve>(pv); if (curve) { - // Update curve setCurveInsync(std::move(curve)); // Convert from property to attribute (convert back on write) setAttributeOrRemoveIfEmpty("d", value); - SPCSSAttr *css = sp_repr_css_attr( getRepr(), "style"); - sp_repr_css_unset_property ( css, "d"); - sp_repr_css_set ( getRepr(), css, "style" ); - sp_repr_css_attr_unref ( css ); + SPCSSAttr *css = sp_repr_css_attr(getRepr(), "style"); + sp_repr_css_unset_property(css, "d"); + sp_repr_css_set(getRepr(), css, "style"); + sp_repr_css_attr_unref(css); style->d.style_src = SP_STYLE_SRC_ATTRIBUTE; } else { @@ -173,7 +170,6 @@ void SPPath::build(SPDocument *document, Inkscape::XML::Node *repr) { // If any if statement is false, do nothing... don't overwrite 'd' from attribute } - // this->readAttr(SPAttr::INKSCAPE_ORIGINAL_D); // bug #1299948 // Why we take the long way of doing this probably needs some explaining: // @@ -181,7 +177,7 @@ void SPPath::build(SPDocument *document, Inkscape::XML::Node *repr) { // will cause the path to actually _write to its repr_ in response to this. // This is bad, bad news if the attached effect refers to a path which // hasn't been constructed yet. - // + // // What will happen is the effect parameter will cause the effect to // recalculate with a completely different value due to the parameter being // "empty" -- even worse, an undo event might be created with the bad value, @@ -194,8 +190,7 @@ void SPPath::build(SPDocument *document, Inkscape::XML::Node *repr) { // plethora of issues with effects with linked parameters doing wild and // stupid things on new documents upon a mere undo. - if (gchar const* s = this->getRepr()->attribute("inkscape:original-d")) - { + if (gchar const *s = this->getRepr()->attribute("inkscape:original-d")) { // Write the value to _curve_before_lpe, do not recalculate effects Geom::PathVector pv = sp_svg_read_pathv(s); _curve_before_lpe.reset(new SPCurve(pv)); @@ -212,18 +207,20 @@ void SPPath::build(SPDocument *document, Inkscape::XML::Node *repr) { // I guess that didn't work, now we have nothing useful to write ("") if (d == nullptr) { - this->setKeyValue( sp_attribute_lookup("d"), ""); + this->setKeyValue(sp_attribute_lookup("d"), ""); } } } -void SPPath::release() { +void SPPath::release() +{ this->connEndPair.release(); SPShape::release(); } -void SPPath::set(SPAttr key, const gchar* value) { +void SPPath::set(SPAttr key, const gchar *value) +{ switch (key) { case SPAttr::INKSCAPE_ORIGINAL_D: if (value) { @@ -234,14 +231,14 @@ void SPPath::set(SPAttr key, const gchar* value) { if (!haslpe) { this->setCurveBeforeLPE(nullptr); } else { - //This happends on undo, fix bug:#1791784 + // This happends on undo, fix bug:#1791784 this->removeAllPathEffects(false); } } sp_lpe_item_update_patheffect(this, true, true); break; - case SPAttr::D: + case SPAttr::D: if (value) { Geom::PathVector pv = sp_svg_read_pathv(value); setCurve(std::make_unique<SPCurve>(pv)); @@ -282,13 +279,14 @@ void SPPath::set(SPAttr key, const gchar* value) { } } -Inkscape::XML::Node* SPPath::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPPath::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:path"); } #ifdef PATH_VERBOSE -g_message("sp_path_write writes 'd' attribute"); + g_message("sp_path_write writes 'd' attribute"); #endif if (this->_curve) { @@ -300,7 +298,7 @@ g_message("sp_path_write writes 'd' attribute"); } if (flags & SP_OBJECT_WRITE_EXT) { - if ( this->_curve_before_lpe != nullptr ) { + if (this->_curve_before_lpe != nullptr) { gchar *str = sp_svg_write_path(this->_curve_before_lpe->get_pathvector()); repr->setAttribute("inkscape:original-d", str); g_free(str); @@ -316,20 +314,24 @@ g_message("sp_path_write writes 'd' attribute"); return repr; } -void SPPath::update_patheffect(bool write) { +void SPPath::update_patheffect(bool write) +{ SPShape::update_patheffect(write); } -void SPPath::update(SPCtx *ctx, guint flags) { +void SPPath::update(SPCtx *ctx, guint flags) +{ if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - flags &= ~SP_OBJECT_USER_MODIFIED_FLAG_B; // since we change the description, it's not a "just translation" anymore + flags &= + ~SP_OBJECT_USER_MODIFIED_FLAG_B; // since we change the description, it's not a "just translation" anymore } SPShape::update(ctx, flags); this->connEndPair.update(); } -Geom::Affine SPPath::set_transform(Geom::Affine const &transform) { +Geom::Affine SPPath::set_transform(Geom::Affine const &transform) +{ if (!_curve) { // 0 nodes, nothing to transform return Geom::identity(); } diff --git a/src/object/sp-path.h b/src/object/sp-path.h index d491be34512027da18d9bc0ccaf1c07cec25c462..784a1e164160d55242795f7a8ebbd0735dc1a341 100644 --- a/src/object/sp-path.h +++ b/src/object/sp-path.h @@ -17,19 +17,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "sp-shape.h" #include "sp-conn-end-pair.h" +#include "sp-shape.h" #include "style-internal.h" // For SPStyleSrc class SPCurve; -#define SP_PATH(obj) (dynamic_cast<SPPath*>((SPObject*)obj)) -#define SP_IS_PATH(obj) (dynamic_cast<const SPPath*>((SPObject*)obj) != NULL) +#define SP_PATH(obj) (dynamic_cast<SPPath *>((SPObject *)obj)) +#define SP_IS_PATH(obj) (dynamic_cast<const SPPath *>((SPObject *)obj) != NULL) /** * SVG <path> implementation */ -class SPPath : public SPShape { +class SPPath : public SPShape +{ public: SPPath(); ~SPPath() override; @@ -40,18 +41,20 @@ public: void build(SPDocument *document, Inkscape::XML::Node *repr) override; void release() override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; - void set(SPAttr key, char const* value) override; + void set(SPAttr key, char const *value) override; void update_patheffect(bool write) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; - const char* displayName() const override; - char* description() const override; + const char *displayName() const override; + char *description() const override; Geom::Affine set_transform(Geom::Affine const &transform) override; void convert_to_guides() const override; + private: - SPStyleSrc d_source; // Source of 'd' value, saved for output. + SPStyleSrc d_source; // Source of 'd' value, saved for output. }; #endif // SEEN_SP_PATH_H diff --git a/src/object/sp-pattern.cpp b/src/object/sp-pattern.cpp index 8b1670c41e6fe8780385a95a0a013031eb67bc99..63d00142544e7f9b20847a567d725a1ce80a0183 100644 --- a/src/object/sp-pattern.cpp +++ b/src/object/sp-pattern.cpp @@ -15,27 +15,22 @@ #include "sp-pattern.h" +#include <2geom/transforms.h> #include <cstring> -#include <string> - #include <glibmm.h> - -#include <2geom/transforms.h> +#include <string> #include "attributes.h" #include "bad-uri-exception.h" -#include "document.h" - -#include "sp-defs.h" -#include "sp-factory.h" -#include "sp-item.h" - #include "display/cairo-utils.h" #include "display/drawing-context.h" +#include "display/drawing-group.h" #include "display/drawing-surface.h" #include "display/drawing.h" -#include "display/drawing-group.h" - +#include "document.h" +#include "sp-defs.h" +#include "sp-factory.h" +#include "sp-item.h" #include "svg/svg.h" SPPattern::SPPattern() @@ -106,14 +101,12 @@ void SPPattern::set(SPAttr key, const gchar *value) if (value) { if (!strcmp(value, "userSpaceOnUse")) { this->_pattern_units = UNITS_USERSPACEONUSE; - } - else { + } else { this->_pattern_units = UNITS_OBJECTBOUNDINGBOX; } this->_pattern_units_set = true; - } - else { + } else { this->_pattern_units_set = false; } @@ -124,14 +117,12 @@ void SPPattern::set(SPAttr key, const gchar *value) if (value) { if (!strcmp(value, "userSpaceOnUse")) { this->_pattern_content_units = UNITS_USERSPACEONUSE; - } - else { + } else { this->_pattern_content_units = UNITS_OBJECTBOUNDINGBOX; } this->_pattern_content_units_set = true; - } - else { + } else { this->_pattern_content_units_set = false; } @@ -144,8 +135,7 @@ void SPPattern::set(SPAttr key, const gchar *value) if (value && sp_svg_transform_read(value, &t)) { this->_pattern_transform = t; this->_pattern_transform_set = true; - } - else { + } else { this->_pattern_transform = Geom::identity(); this->_pattern_transform_set = false; } @@ -186,8 +176,7 @@ void SPPattern::set(SPAttr key, const gchar *value) case SPAttr::XLINK_HREF: if (value && this->href == value) { /* Href unchanged, do nothing. */ - } - else { + } else { this->href.clear(); if (value) { @@ -197,13 +186,11 @@ void SPPattern::set(SPAttr key, const gchar *value) if (value) { try { this->ref->attach(Inkscape::URI(value)); - } - catch (Inkscape::BadURIException &e) { + } catch (Inkscape::BadURIException &e) { g_warning("%s", e.what()); this->ref->detach(); } - } - else { + } else { this->ref->detach(); } } @@ -216,7 +203,6 @@ void SPPattern::set(SPAttr key, const gchar *value) } } - /* TODO: do we need a ::remove_child handler? */ /* fixme: We need ::order_changed handler too (Lauris) */ @@ -225,7 +211,7 @@ void SPPattern::_getChildren(std::list<SPObject *> &l) { for (SPPattern *pat_i = this; pat_i != nullptr; pat_i = pat_i->ref ? pat_i->ref->getObject() : nullptr) { if (pat_i->firstChild()) { // find the first one with children - for (auto& child: pat_i->children) { + for (auto &child : pat_i->children) { l.push_back(&child); } break; // do not go further up the chain if children are found @@ -313,7 +299,7 @@ guint SPPattern::_countHrefs(SPObject *o) const i++; } - for (auto& child: o->children) { + for (auto &child : o->children) { i += _countHrefs(&child); } @@ -362,8 +348,7 @@ void SPPattern::transform_multiply(Geom::Affine postmul, bool set) // otherwise the formula is much simpler if (set) { _pattern_transform = postmul; - } - else { + } else { _pattern_transform = getTransform() * postmul; } _pattern_transform_set = true; @@ -383,8 +368,8 @@ const gchar *SPPattern::produce(const std::vector<Inkscape::XML::Node *> &reprs, repr->setAttribute("patternUnits", "userSpaceOnUse"); sp_repr_set_svg_double(repr, "width", bounds.dimensions()[Geom::X]); sp_repr_set_svg_double(repr, "height", bounds.dimensions()[Geom::Y]); - //TODO: Maybe is better handle it in sp_svg_transform_write - if(transform != Geom::Affine()){ + // TODO: Maybe is better handle it in sp_svg_transform_write + if (transform != Geom::Affine()) { gchar *t = sp_svg_transform_write(transform); repr->setAttribute("patternTransform", t); g_free(t); @@ -419,8 +404,6 @@ SPPattern *SPPattern::rootPattern() // pattern } - - // Access functions that look up fields up the chain of referenced patterns and return the first one which is set // FIXME: all of them must use chase_hrefs the same as in SPGradient, to avoid lockup on circular refs @@ -501,7 +484,7 @@ Geom::OptRect SPPattern::viewbox() const bool SPPattern::_hasItemChildren() const { - for (auto& child: children) { + for (auto &child : children) { if (SP_IS_ITEM(&child)) { return true; } @@ -522,7 +505,6 @@ bool SPPattern::isValid() const cairo_pattern_t *SPPattern::pattern_new(cairo_t *base_ct, Geom::OptRect const &bbox, double opacity) { - bool needs_opacity = (1.0 - opacity) >= 1e-3; bool visible = opacity >= 1e-3; @@ -551,7 +533,7 @@ cairo_pattern_t *SPPattern::pattern_new(cairo_t *base_ct, Geom::OptRect const &b Inkscape::DrawingGroup *root = new Inkscape::DrawingGroup(drawing); drawing.setRoot(root); - for (auto& child: shown->children) { + for (auto &child : shown->children) { if (SP_IS_ITEM(&child)) { // for each item in pattern, show it on our drawing, add to the group, // and connect to the release signal in case the item gets deleted @@ -592,20 +574,16 @@ cairo_pattern_t *SPPattern::pattern_new(cairo_t *base_ct, Geom::OptRect const &b c2p.setIdentity(); apply_viewbox(pattern_tile); content2ps = c2p; - } - else { - + } else { // Content to bbox if (bbox && (patternContentUnits() == UNITS_OBJECTBOUNDINGBOX)) { content2ps = Geom::Affine(bbox->width(), 0.0, 0.0, bbox->height(), 0, 0); } } - // Tile (pattern space) to user. Geom::Affine ps2user = Geom::Translate(tile_x, tile_y) * getTransform(); - // Transform of object with pattern (includes screen scaling) cairo_matrix_t cm; cairo_get_matrix(base_ct, &cm); @@ -647,7 +625,7 @@ cairo_pattern_t *SPPattern::pattern_new(cairo_t *base_ct, Geom::OptRect const &b // Render drawing to pattern_surface via drawing context, this calls root->render // which is really DrawingItem->render(). drawing.render(dc, one_tile); - for (auto& child: shown->children) { + for (auto &child : shown->children) { if (SP_IS_ITEM(&child)) { SP_ITEM(&child)->invoke_hide(dkey); } @@ -677,7 +655,7 @@ cairo_pattern_t *SPPattern::pattern_new(cairo_t *base_ct, Geom::OptRect const &b int h = one_tile[Geom::Y].extent(); int m = raw_transform[4] / w; int n = raw_transform[5] / h; - raw_transform *= Geom::Translate( -m*w, -n*h ); + raw_transform *= Geom::Translate(-m * w, -n * h); cairo_pattern_t *cp = cairo_pattern_create_for_surface(pattern_surface.raw()); ink_cairo_pattern_set_matrix(cp, raw_transform); diff --git a/src/object/sp-pattern.h b/src/object/sp-pattern.h index 5c5eb36d4e68011b142651f9775355ff4e0f5b84..77cae514c6e58b9025daae2d34fa98df05c9b5d1 100644 --- a/src/object/sp-pattern.h +++ b/src/object/sp-pattern.h @@ -14,13 +14,13 @@ #ifndef SEEN_SP_PATTERN_H #define SEEN_SP_PATTERN_H -#include <list> #include <cstddef> #include <glibmm/ustring.h> +#include <list> #include <sigc++/connection.h> -#include "svg/svg-length.h" #include "sp-paint-server.h" +#include "svg/svg-length.h" #include "uri-references.h" #include "viewbox.h" @@ -32,14 +32,21 @@ namespace XML { class Node; } -} +} // namespace Inkscape #define SP_PATTERN(obj) (dynamic_cast<SPPattern *>((SPObject *)obj)) #define SP_IS_PATTERN(obj) (dynamic_cast<const SPPattern *>((SPObject *)obj) != NULL) -class SPPattern : public SPPaintServer, public SPViewBox { +class SPPattern + : public SPPaintServer + , public SPViewBox +{ public: - enum PatternUnits { UNITS_USERSPACEONUSE, UNITS_OBJECTBOUNDINGBOX }; + enum PatternUnits + { + UNITS_USERSPACEONUSE, + UNITS_OBJECTBOUNDINGBOX + }; SPPattern(); ~SPPattern() override; @@ -116,23 +123,17 @@ private: sigc::connection _modified_connection; }; - -class SPPatternReference : public Inkscape::URIReference { +class SPPatternReference : public Inkscape::URIReference +{ public: SPPatternReference(SPObject *obj) : URIReference(obj) - { - } + {} - SPPattern *getObject() const - { - return reinterpret_cast<SPPattern *>(URIReference::getObject()); - } + SPPattern *getObject() const { return reinterpret_cast<SPPattern *>(URIReference::getObject()); } protected: - bool _acceptObject(SPObject *obj) const override { - return SP_IS_PATTERN (obj)&& URIReference::_acceptObject(obj); - } + bool _acceptObject(SPObject *obj) const override { return SP_IS_PATTERN(obj) && URIReference::_acceptObject(obj); } }; #endif // SEEN_SP_PATTERN_H diff --git a/src/object/sp-polygon.cpp b/src/object/sp-polygon.cpp index f8dacfff39a6e6d17da8928f44217fd62eb13c7d..69a3fdc1fd77bc76b0bff1fbb7117bbff4310e5e 100644 --- a/src/object/sp-polygon.cpp +++ b/src/object/sp-polygon.cpp @@ -12,23 +12,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "attributes.h" #include "sp-polygon.h" -#include "display/curve.h" -#include <glibmm/i18n.h> + #include <2geom/curves.h> +#include <glibmm/i18n.h> + +#include "attributes.h" +#include "display/curve.h" +#include "document.h" #include "helper/geom-curves.h" #include "svg/stringstream.h" #include "xml/repr.h" -#include "document.h" -SPPolygon::SPPolygon() : SPShape() { -} +SPPolygon::SPPolygon() + : SPShape() +{} SPPolygon::~SPPolygon() = default; -void SPPolygon::build(SPDocument *document, Inkscape::XML::Node *repr) { - SPPolygon* object = this; +void SPPolygon::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + SPPolygon *object = this; SPShape::build(document, repr); @@ -40,14 +44,13 @@ void SPPolygon::build(SPDocument *document, Inkscape::XML::Node *repr) { * pathv may only contain paths with only straight line segments * Return value: points attribute string. */ -static gchar *sp_svg_write_polygon(Geom::PathVector const & pathv) +static gchar *sp_svg_write_polygon(Geom::PathVector const &pathv) { Inkscape::SVGOStringStream os; - for (const auto & pit : pathv) { + for (const auto &pit : pathv) { for (Geom::Path::const_iterator cit = pit.begin(); cit != pit.end_default(); ++cit) { - if ( is_straight_curve(*cit) ) - { + if (is_straight_curve(*cit)) { os << cit->finalPoint()[0] << "," << cit->finalPoint()[1] << " "; } else { g_error("sp_svg_write_polygon: polygon path contains non-straight line segments"); @@ -58,10 +61,11 @@ static gchar *sp_svg_write_polygon(Geom::PathVector const & pathv) return g_strdup(os.str().c_str()); } -Inkscape::XML::Node* SPPolygon::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPPolygon::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ // Tolerable workaround: we need to update the object's curve before we set points= // because it's out of sync when e.g. some extension attrs of the polygon or star are changed in XML editor - this->set_shape(); + this->set_shape(); if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:polygon"); @@ -80,7 +84,6 @@ Inkscape::XML::Node* SPPolygon::write(Inkscape::XML::Document *xml_doc, Inkscape return repr; } - static gboolean polygon_get_value(gchar const **p, gdouble *v) { while (**p != '\0' && (**p == ',' || **p == '\x20' || **p == '\x9' || **p == '\xD' || **p == '\xA')) { @@ -103,7 +106,8 @@ static gboolean polygon_get_value(gchar const **p, gdouble *v) return true; } -void SPPolygon::set(SPAttr key, const gchar* value) { +void SPPolygon::set(SPAttr key, const gchar *value) +{ switch (key) { case SPAttr::POINTS: { if (!value) { @@ -166,8 +170,9 @@ void SPPolygon::set(SPAttr key, const gchar* value) { } } -gchar* SPPolygon::description() const { - return g_strdup(_("<b>Polygon</b>")); +gchar *SPPolygon::description() const +{ + return g_strdup(_("<b>Polygon</b>")); } /* diff --git a/src/object/sp-polygon.h b/src/object/sp-polygon.h index d71ef8a43039b1eee4400ab069885df229183eb8..008f88095482ff066439eb23539740441e4a5ccc 100644 --- a/src/object/sp-polygon.h +++ b/src/object/sp-polygon.h @@ -16,21 +16,23 @@ #include "sp-shape.h" -#define SP_POLYGON(obj) (dynamic_cast<SPPolygon*>((SPObject*)obj)) -#define SP_IS_POLYGON(obj) (dynamic_cast<const SPPolygon*>((SPObject*)obj) != NULL) +#define SP_POLYGON(obj) (dynamic_cast<SPPolygon *>((SPObject *)obj)) +#define SP_IS_POLYGON(obj) (dynamic_cast<const SPPolygon *>((SPObject *)obj) != NULL) -class SPPolygon : public SPShape { +class SPPolygon : public SPShape +{ public: - SPPolygon(); - ~SPPolygon() override; + SPPolygon(); + ~SPPolygon() override; - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - void set(SPAttr key, char const* value) override; - char* description() const override; + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + void set(SPAttr key, char const *value) override; + char *description() const override; }; // made 'public' so that SPCurve can set it as friend: -void sp_polygon_set(SPObject *object, unsigned int key, char const*value); +void sp_polygon_set(SPObject *object, unsigned int key, char const *value); #endif diff --git a/src/object/sp-polyline.cpp b/src/object/sp-polyline.cpp index 2cc0982b4d7f4fdc0a6a8ff61640cee16de5eb55..cddfd2795b6e728b9a99e3a5f30bd89f494e051d 100644 --- a/src/object/sp-polyline.cpp +++ b/src/object/sp-polyline.cpp @@ -12,33 +12,38 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "attributes.h" #include "sp-polyline.h" -#include "display/curve.h" + #include <glibmm/i18n.h> -#include "xml/repr.h" + +#include "attributes.h" +#include "display/curve.h" #include "document.h" +#include "xml/repr.h" -SPPolyLine::SPPolyLine() : SPShape() { -} +SPPolyLine::SPPolyLine() + : SPShape() +{} SPPolyLine::~SPPolyLine() = default; -void SPPolyLine::build(SPDocument * document, Inkscape::XML::Node * repr) { +void SPPolyLine::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPShape::build(document, repr); this->readAttr(SPAttr::POINTS); } -void SPPolyLine::set(SPAttr key, const gchar* value) { +void SPPolyLine::set(SPAttr key, const gchar *value) +{ switch (key) { - case SPAttr::POINTS: { - const gchar * cptr; - char * eptr; + case SPAttr::POINTS: { + const gchar *cptr; + char *eptr; gboolean hascpt; if (!value) { - break; + break; } auto curve = std::make_unique<SPCurve>(); @@ -50,34 +55,36 @@ void SPPolyLine::set(SPAttr key, const gchar* value) { while (TRUE) { gdouble x, y; - while (*cptr != '\0' && (*cptr == ',' || *cptr == '\x20' || *cptr == '\x9' || *cptr == '\xD' || *cptr == '\xA')) { + while (*cptr != '\0' && + (*cptr == ',' || *cptr == '\x20' || *cptr == '\x9' || *cptr == '\xD' || *cptr == '\xA')) { cptr++; } if (!*cptr) { - break; + break; } - x = g_ascii_strtod (cptr, &eptr); + x = g_ascii_strtod(cptr, &eptr); if (eptr == cptr) { - break; + break; } cptr = eptr; - while (*cptr != '\0' && (*cptr == ',' || *cptr == '\x20' || *cptr == '\x9' || *cptr == '\xD' || *cptr == '\xA')) { + while (*cptr != '\0' && + (*cptr == ',' || *cptr == '\x20' || *cptr == '\x9' || *cptr == '\xD' || *cptr == '\xA')) { cptr++; } if (!*cptr) { - break; + break; } - y = g_ascii_strtod (cptr, &eptr); + y = g_ascii_strtod(cptr, &eptr); if (eptr == cptr) { - break; + break; } cptr = eptr; @@ -89,17 +96,18 @@ void SPPolyLine::set(SPAttr key, const gchar* value) { hascpt = TRUE; } } - + setCurve(std::move(curve)); break; - } - default: + } + default: SPShape::set(key, value); break; } } -Inkscape::XML::Node* SPPolyLine::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPPolyLine::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:polyline"); } @@ -113,11 +121,11 @@ Inkscape::XML::Node* SPPolyLine::write(Inkscape::XML::Document *xml_doc, Inkscap return repr; } -gchar* SPPolyLine::description() const { - return g_strdup(_("<b>Polyline</b>")); +gchar *SPPolyLine::description() const +{ + return g_strdup(_("<b>Polyline</b>")); } - /* Local Variables: mode:c++ diff --git a/src/object/sp-polyline.h b/src/object/sp-polyline.h index 94af258990ddb51c636ca8f4a554ff606b9466b2..351b35dc2b27dc29a7947c497bc8f23a33070a5e 100644 --- a/src/object/sp-polyline.h +++ b/src/object/sp-polyline.h @@ -12,19 +12,21 @@ #include "sp-shape.h" -#define SP_POLYLINE(obj) (dynamic_cast<SPPolyLine*>((SPObject*)obj)) -#define SP_IS_POLYLINE(obj) (dynamic_cast<const SPPolyLine*>((SPObject*)obj) != NULL) +#define SP_POLYLINE(obj) (dynamic_cast<SPPolyLine *>((SPObject *)obj)) +#define SP_IS_POLYLINE(obj) (dynamic_cast<const SPPolyLine *>((SPObject *)obj) != NULL) -class SPPolyLine : public SPShape { +class SPPolyLine : public SPShape +{ public: - SPPolyLine(); - ~SPPolyLine() override; + SPPolyLine(); + ~SPPolyLine() override; - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void set(SPAttr key, char const* value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void set(SPAttr key, char const *value) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; - char* description() const override; + char *description() const override; }; #endif // SEEN_SP_POLYLINE_H diff --git a/src/object/sp-radial-gradient.cpp b/src/object/sp-radial-gradient.cpp index 5b17ec3a8dce8c6d6bad66dca4554cf6a5e71474..cda8002dfe0a77505d462a487643a6bcba7c3702 100644 --- a/src/object/sp-radial-gradient.cpp +++ b/src/object/sp-radial-gradient.cpp @@ -7,20 +7,21 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cairo.h> - #include "sp-radial-gradient.h" +#include <2geom/transforms.h> +#include <cairo.h> + #include "attributes.h" #include "style.h" #include "xml/repr.h" -#include <2geom/transforms.h> - /* * Radial Gradient */ -SPRadialGradient::SPRadialGradient() : SPGradient() { +SPRadialGradient::SPRadialGradient() + : SPGradient() +{ this->cx.unset(SVGLength::PERCENT, 0.5, 0.5); this->cy.unset(SVGLength::PERCENT, 0.5, 0.5); this->r.unset(SVGLength::PERCENT, 0.5, 0.5); @@ -34,7 +35,8 @@ SPRadialGradient::~SPRadialGradient() = default; /** * Set radial gradient attributes from associated repr. */ -void SPRadialGradient::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPRadialGradient::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPGradient::build(document, repr); this->readAttr(SPAttr::CX); @@ -48,8 +50,8 @@ void SPRadialGradient::build(SPDocument *document, Inkscape::XML::Node *repr) { /** * Set radial gradient attribute. */ -void SPRadialGradient::set(SPAttr key, gchar const *value) { - +void SPRadialGradient::set(SPAttr key, gchar const *value) +{ switch (key) { case SPAttr::CX: if (!this->cx.read(value)) { @@ -114,20 +116,18 @@ void SPRadialGradient::set(SPAttr key, gchar const *value) { } } -void -SPRadialGradient::update(SPCtx *ctx, guint flags) +void SPRadialGradient::update(SPCtx *ctx, guint flags) { // To do: Verify flags. if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - SPItemCtx const *ictx = reinterpret_cast<SPItemCtx const *>(ctx); if (getUnits() == SP_GRADIENT_UNITS_USERSPACEONUSE) { double w = ictx->viewport.width(); double h = ictx->viewport.height(); - double d = sqrt ((w*w + h*h)/2.0); + double d = sqrt((w * w + h * h) / 2.0); double const em = style->font_size.computed; - double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. + double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. this->cx.update(em, ex, w); this->cy.update(em, ex, h); @@ -142,33 +142,34 @@ SPRadialGradient::update(SPCtx *ctx, guint flags) /** * Write radial gradient attributes to associated repr. */ -Inkscape::XML::Node* SPRadialGradient::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPRadialGradient::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:radialGradient"); } if ((flags & SP_OBJECT_WRITE_ALL) || this->cx._set) { - sp_repr_set_svg_double(repr, "cx", this->cx.computed); + sp_repr_set_svg_double(repr, "cx", this->cx.computed); } if ((flags & SP_OBJECT_WRITE_ALL) || this->cy._set) { - sp_repr_set_svg_double(repr, "cy", this->cy.computed); + sp_repr_set_svg_double(repr, "cy", this->cy.computed); } if ((flags & SP_OBJECT_WRITE_ALL) || this->r._set) { - sp_repr_set_svg_double(repr, "r", this->r.computed); + sp_repr_set_svg_double(repr, "r", this->r.computed); } if ((flags & SP_OBJECT_WRITE_ALL) || this->fx._set) { - sp_repr_set_svg_double(repr, "fx", this->fx.computed); + sp_repr_set_svg_double(repr, "fx", this->fx.computed); } if ((flags & SP_OBJECT_WRITE_ALL) || this->fy._set) { - sp_repr_set_svg_double(repr, "fy", this->fy.computed); + sp_repr_set_svg_double(repr, "fy", this->fy.computed); } if ((flags & SP_OBJECT_WRITE_ALL) || this->fr._set) { - sp_repr_set_svg_double(repr, "fr", this->fr.computed); + sp_repr_set_svg_double(repr, "fr", this->fr.computed); } SPGradient::write(xml_doc, repr, flags); @@ -176,7 +177,8 @@ Inkscape::XML::Node* SPRadialGradient::write(Inkscape::XML::Document *xml_doc, I return repr; } -cairo_pattern_t* SPRadialGradient::pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) { +cairo_pattern_t *SPRadialGradient::pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) +{ this->ensureVector(); Geom::Point focus(this->fx.computed, this->fy.computed); @@ -231,9 +233,8 @@ cairo_pattern_t* SPRadialGradient::pattern_new(cairo_t *ct, Geom::OptRect const scale *= 1.0 - 2.0 * tolerance / dl; } - cairo_pattern_t *cp = cairo_pattern_create_radial( - scale * d.x() + center.x(), scale * d.y() + center.y(), focusr, - center.x(), center.y(), radius); + cairo_pattern_t *cp = cairo_pattern_create_radial(scale * d.x() + center.x(), scale * d.y() + center.y(), focusr, + center.x(), center.y(), radius); sp_gradient_pattern_common_setup(cp, this, bbox, opacity); diff --git a/src/object/sp-radial-gradient.h b/src/object/sp-radial-gradient.h index 1f72b403434ed0bf3dda5dc4361795b10bb8204b..cedf342440bba6075a641e2297762cd034e5b763 100644 --- a/src/object/sp-radial-gradient.h +++ b/src/object/sp-radial-gradient.h @@ -20,11 +20,12 @@ typedef struct _cairo cairo_t; typedef struct _cairo_pattern cairo_pattern_t; -#define SP_RADIALGRADIENT(obj) (dynamic_cast<SPRadialGradient*>((SPObject*)obj)) -#define SP_IS_RADIALGRADIENT(obj) (dynamic_cast<const SPRadialGradient*>((SPObject*)obj) != NULL) +#define SP_RADIALGRADIENT(obj) (dynamic_cast<SPRadialGradient *>((SPObject *)obj)) +#define SP_IS_RADIALGRADIENT(obj) (dynamic_cast<const SPRadialGradient *>((SPObject *)obj) != NULL) /** Radial gradient. */ -class SPRadialGradient : public SPGradient { +class SPRadialGradient : public SPGradient +{ public: SPRadialGradient(); ~SPRadialGradient() override; @@ -36,13 +37,14 @@ public: SVGLength fy; SVGLength fr; // Focus radius. Added in SVG 2 - cairo_pattern_t* pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) override; + cairo_pattern_t *pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) override; protected: void build(SPDocument *document, Inkscape::XML::Node *repr) override; void set(SPAttr key, char const *value) override; void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; #endif /* !SP_RADIAL_GRADIENT_H */ diff --git a/src/object/sp-rect.cpp b/src/object/sp-rect.cpp index c0f1fefd4a7ebaec4bb68a16e5b1cc47a1e29a4d..817cb7b2423db143498a5e134d0d642d48161e43 100644 --- a/src/object/sp-rect.cpp +++ b/src/object/sp-rect.cpp @@ -12,30 +12,33 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "display/curve.h" +#include "sp-rect.h" + +#include <glibmm/i18n.h> -#include "inkscape.h" -#include "document.h" #include "attributes.h" -#include "style.h" -#include "sp-rect.h" -#include "sp-guide.h" +#include "display/curve.h" +#include "document.h" +#include "inkscape.h" #include "preferences.h" +#include "sp-guide.h" +#include "style.h" #include "svg/svg.h" -#include <glibmm/i18n.h> #define noRECT_VERBOSE //#define OBJECT_TRACE -SPRect::SPRect() : SPShape() { -} +SPRect::SPRect() + : SPShape() +{} SPRect::~SPRect() = default; -void SPRect::build(SPDocument* doc, Inkscape::XML::Node* repr) { +void SPRect::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ #ifdef OBJECT_TRACE - objectTrace( "SPRect::build" ); + objectTrace("SPRect::build"); #endif SPShape::build(doc, repr); @@ -48,16 +51,16 @@ void SPRect::build(SPDocument* doc, Inkscape::XML::Node* repr) { this->readAttr(SPAttr::RY); #ifdef OBJECT_TRACE - objectTrace( "SPRect::build", false ); + objectTrace("SPRect::build", false); #endif } -void SPRect::set(SPAttr key, gchar const *value) { - +void SPRect::set(SPAttr key, gchar const *value) +{ #ifdef OBJECT_TRACE std::stringstream temp; - temp << "SPRect::set: " << key << " " << (value?value:"null"); - objectTrace( temp.str() ); + temp << "SPRect::set: " << key << " " << (value ? value : "null"); + objectTrace(temp.str()); #endif /* fixme: We need real error processing some time */ @@ -71,45 +74,45 @@ void SPRect::set(SPAttr key, gchar const *value) { switch (key) { case SPAttr::X: this->x.readOrUnset(value); - this->x.update( em, ex, w ); + this->x.update(em, ex, w); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::Y: this->y.readOrUnset(value); - this->y.update( em, ex, h ); + this->y.update(em, ex, h); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::WIDTH: if (!this->width.read(value) || this->width.value < 0.0) { - this->width.unset(); + this->width.unset(); } - this->width.update( em, ex, w ); + this->width.update(em, ex, w); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::HEIGHT: if (!this->height.read(value) || this->height.value < 0.0) { - this->height.unset(); + this->height.unset(); } - this->height.update( em, ex, h ); + this->height.update(em, ex, h); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::RX: if (!this->rx.read(value) || this->rx.value <= 0.0) { - this->rx.unset(); + this->rx.unset(); } - this->rx.update( em, ex, w ); + this->rx.update(em, ex, w); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; case SPAttr::RY: if (!this->ry.read(value) || this->ry.value <= 0.0) { - this->ry.unset(); + this->ry.unset(); } - this->ry.update( em, ex, h ); + this->ry.update(em, ex, h); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; @@ -118,14 +121,14 @@ void SPRect::set(SPAttr key, gchar const *value) { break; } #ifdef OBJECT_TRACE - objectTrace( "SPRect::set", false ); + objectTrace("SPRect::set", false); #endif } -void SPRect::update(SPCtx* ctx, unsigned int flags) { - +void SPRect::update(SPCtx *ctx, unsigned int flags) +{ #ifdef OBJECT_TRACE - objectTrace( "SPRect::update", true, flags ); + objectTrace("SPRect::update", true, flags); #endif if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { @@ -134,7 +137,7 @@ void SPRect::update(SPCtx* ctx, unsigned int flags) { double const w = ictx->viewport.width(); double const h = ictx->viewport.height(); double const em = style->font_size.computed; - double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. + double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. this->x.update(em, ex, w); this->y.update(em, ex, h); @@ -144,19 +147,20 @@ void SPRect::update(SPCtx* ctx, unsigned int flags) { this->ry.update(em, ex, h); this->set_shape(); - flags &= ~SP_OBJECT_USER_MODIFIED_FLAG_B; // since we change the description, it's not a "just translation" anymore + flags &= + ~SP_OBJECT_USER_MODIFIED_FLAG_B; // since we change the description, it's not a "just translation" anymore } SPShape::update(ctx, flags); #ifdef OBJECT_TRACE - objectTrace( "SPRect::update", false, flags ); + objectTrace("SPRect::update", false, flags); #endif } -Inkscape::XML::Node * SPRect::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - +Inkscape::XML::Node *SPRect::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ #ifdef OBJECT_TRACE - objectTrace( "SPRect::write", true, flags ); + objectTrace("SPRect::write", true, flags); #endif if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { @@ -166,15 +170,15 @@ Inkscape::XML::Node * SPRect::write(Inkscape::XML::Document *xml_doc, Inkscape:: repr->setCodeUnsafe(g_quark_from_string("svg:path")); repr->setAttribute("sodipodi:type", "rect"); } - sp_repr_set_svg_length(repr, "width", this->width); + sp_repr_set_svg_length(repr, "width", this->width); sp_repr_set_svg_length(repr, "height", this->height); if (this->rx._set) { - sp_repr_set_svg_length(repr, "rx", this->rx); + sp_repr_set_svg_length(repr, "rx", this->rx); } if (this->ry._set) { - sp_repr_set_svg_length(repr, "ry", this->ry); + sp_repr_set_svg_length(repr, "ry", this->ry); } sp_repr_set_svg_length(repr, "x", this->x); @@ -188,19 +192,21 @@ Inkscape::XML::Node * SPRect::write(Inkscape::XML::Document *xml_doc, Inkscape:: SPShape::write(xml_doc, repr, flags); #ifdef OBJECT_TRACE - objectTrace( "SPRect::write", false, flags ); + objectTrace("SPRect::write", false, flags); #endif return repr; } -const char* SPRect::displayName() const { +const char *SPRect::displayName() const +{ return _("Rectangle"); } #define C1 0.554 -void SPRect::set_shape() { +void SPRect::set_shape() +{ if (hasBrokenPathEffect()) { g_warning("The rect shape has unknown LPE on it!"); @@ -214,8 +220,8 @@ void SPRect::set_shape() { return; } if ((this->height.computed < 1e-18) || (this->width.computed < 1e-18)) { - this->setCurveInsync(nullptr); - this->setCurveBeforeLPE(nullptr); + this->setCurveInsync(nullptr); + this->setCurveBeforeLPE(nullptr); return; } @@ -227,17 +233,9 @@ void SPRect::set_shape() { double const h = this->height.computed; double const w2 = w / 2; double const h2 = h / 2; - double const rx = std::min(( this->rx._set - ? this->rx.computed - : ( this->ry._set - ? this->ry.computed - : 0.0 ) ), + double const rx = std::min((this->rx._set ? this->rx.computed : (this->ry._set ? this->ry.computed : 0.0)), .5 * this->width.computed); - double const ry = std::min(( this->ry._set - ? this->ry.computed - : ( this->rx._set - ? this->rx.computed - : 0.0 ) ), + double const ry = std::min((this->ry._set ? this->ry.computed : (this->rx._set ? this->rx.computed : 0.0)), .5 * this->height.computed); /* TODO: Handle negative rx or ry as per * http://www.w3.org/TR/SVG11/shapes.html#RectElementRXAttribute once Inkscape has proper error @@ -251,25 +249,25 @@ void SPRect::set_shape() { c->moveto(x + rx, y); if (rx < w2) { - c->lineto(x + w - rx, y); + c->lineto(x + w - rx, y); } c->curveto(x + w - rx * (1 - C1), y, x + w, y + ry * (1 - C1), x + w, y + ry); if (ry < h2) { - c->lineto(x + w, y + h - ry); + c->lineto(x + w, y + h - ry); } c->curveto(x + w, y + h - ry * (1 - C1), x + w - rx * (1 - C1), y + h, x + w - rx, y + h); if (rx < w2) { - c->lineto(x + rx, y + h); + c->lineto(x + rx, y + h); } c->curveto(x + rx * (1 - C1), y + h, x, y + h - ry * (1 - C1), x, y + h - ry); if (ry < h2) { - c->lineto(x, y + ry); + c->lineto(x, y + ry); } c->curveto(x, y + ry * (1 - C1), x + rx * (1 - C1), y, x + rx, y); @@ -282,9 +280,9 @@ void SPRect::set_shape() { c->closepath(); - /* Reset the shape's curve to the "original_curve" - * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in shape)*/ + * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in + * shape)*/ auto const before = this->curveBeforeLPE(); if (before && before->get_pathvector() != c->get_pathvector()) { @@ -337,7 +335,8 @@ void SPRect::modified(guint flags) /* fixme: Think (Lauris) */ -void SPRect::setPosition(gdouble x, gdouble y, gdouble width, gdouble height) { +void SPRect::setPosition(gdouble x, gdouble y, gdouble width, gdouble height) +{ this->x = x; this->y = y; this->width = width; @@ -346,31 +345,35 @@ void SPRect::setPosition(gdouble x, gdouble y, gdouble width, gdouble height) { this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void SPRect::setRx(bool set, gdouble value) { +void SPRect::setRx(bool set, gdouble value) +{ this->rx._set = set; if (set) { - this->rx = value; + this->rx = value; } this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void SPRect::setRy(bool set, gdouble value) { +void SPRect::setRy(bool set, gdouble value) +{ this->ry._set = set; if (set) { - this->ry = value; + this->ry = value; } this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void SPRect::update_patheffect(bool write) { +void SPRect::update_patheffect(bool write) +{ SPShape::update_patheffect(write); } -Geom::Affine SPRect::set_transform(Geom::Affine const& xform) { +Geom::Affine SPRect::set_transform(Geom::Affine const &xform) +{ if (pathEffectsEnabled() && !optimizeTransforms()) { return xform; } @@ -400,15 +403,15 @@ Geom::Affine SPRect::set_transform(Geom::Affine const& xform) { } /* Preserve units */ - this->width.scale( sw ); - this->height.scale( sh ); + this->width.scale(sw); + this->height.scale(sh); if (this->rx._set) { - this->rx.scale( sw ); + this->rx.scale(sw); } if (this->ry._set) { - this->ry.scale( sh ); + this->ry.scale(sh); } /* Find start in item coords */ @@ -430,11 +433,11 @@ Geom::Affine SPRect::set_transform(Geom::Affine const& xform) { return ret; } - /** Returns the ratio in which the vector from p0 to p1 is stretched by transform */ -gdouble SPRect::vectorStretch(Geom::Point p0, Geom::Point p1, Geom::Affine xform) { +gdouble SPRect::vectorStretch(Geom::Point p0, Geom::Point p1, Geom::Affine xform) +{ if (p0 == p1) { return 0; } @@ -442,62 +445,62 @@ gdouble SPRect::vectorStretch(Geom::Point p0, Geom::Point p1, Geom::Affine xform return (Geom::distance(p0 * xform, p1 * xform) / Geom::distance(p0, p1)); } -void SPRect::setVisibleRx(gdouble rx) { +void SPRect::setVisibleRx(gdouble rx) +{ if (rx == 0) { this->rx.unset(); } else { - this->rx = rx / SPRect::vectorStretch( - Geom::Point(this->x.computed + 1, this->y.computed), - Geom::Point(this->x.computed, this->y.computed), - this->i2doc_affine()); + this->rx = rx / SPRect::vectorStretch(Geom::Point(this->x.computed + 1, this->y.computed), + Geom::Point(this->x.computed, this->y.computed), this->i2doc_affine()); } this->updateRepr(); } -void SPRect::setVisibleRy(gdouble ry) { +void SPRect::setVisibleRy(gdouble ry) +{ if (ry == 0) { - this->ry.unset(); + this->ry.unset(); } else { - this->ry = ry / SPRect::vectorStretch( - Geom::Point(this->x.computed, this->y.computed + 1), - Geom::Point(this->x.computed, this->y.computed), - this->i2doc_affine()); + this->ry = ry / SPRect::vectorStretch(Geom::Point(this->x.computed, this->y.computed + 1), + Geom::Point(this->x.computed, this->y.computed), this->i2doc_affine()); } this->updateRepr(); } -gdouble SPRect::getVisibleRx() const { +gdouble SPRect::getVisibleRx() const +{ if (!this->rx._set) { return 0; } - return this->rx.computed * SPRect::vectorStretch( - Geom::Point(this->x.computed + 1, this->y.computed), - Geom::Point(this->x.computed, this->y.computed), - this->i2doc_affine()); + return this->rx.computed * SPRect::vectorStretch(Geom::Point(this->x.computed + 1, this->y.computed), + Geom::Point(this->x.computed, this->y.computed), + this->i2doc_affine()); } -gdouble SPRect::getVisibleRy() const { +gdouble SPRect::getVisibleRy() const +{ if (!this->ry._set) { return 0; } - return this->ry.computed * SPRect::vectorStretch( - Geom::Point(this->x.computed, this->y.computed + 1), - Geom::Point(this->x.computed, this->y.computed), - this->i2doc_affine()); + return this->ry.computed * SPRect::vectorStretch(Geom::Point(this->x.computed, this->y.computed + 1), + Geom::Point(this->x.computed, this->y.computed), + this->i2doc_affine()); } -Geom::Rect SPRect::getRect() const { +Geom::Rect SPRect::getRect() const +{ Geom::Point p0 = Geom::Point(this->x.computed, this->y.computed); Geom::Point p2 = Geom::Point(this->x.computed + this->width.computed, this->y.computed + this->height.computed); return Geom::Rect(p0, p2); } -void SPRect::compensateRxRy(Geom::Affine xform) { +void SPRect::compensateRxRy(Geom::Affine xform) +{ if (this->rx.computed == 0 && this->ry.computed == 0) { return; // nothing to compensate } @@ -523,8 +526,8 @@ void SPRect::compensateRxRy(Geom::Affine xform) { this->rx = r / eX; this->ry = r / eY; } else { - this->rx = this->rx.computed / eX; - this->ry = this->ry.computed / eY; + this->rx = this->rx.computed / eX; + this->ry = this->ry.computed / eY; } // Note that a radius may end up larger than half-side if the rect is scaled down; @@ -532,47 +535,47 @@ void SPRect::compensateRxRy(Geom::Affine xform) { // and set_shape will take care of trimming too large radii when generating d= } -void SPRect::setVisibleWidth(gdouble width) { - this->width = width / SPRect::vectorStretch( - Geom::Point(this->x.computed + 1, this->y.computed), - Geom::Point(this->x.computed, this->y.computed), - this->i2doc_affine()); +void SPRect::setVisibleWidth(gdouble width) +{ + this->width = width / SPRect::vectorStretch(Geom::Point(this->x.computed + 1, this->y.computed), + Geom::Point(this->x.computed, this->y.computed), this->i2doc_affine()); this->updateRepr(); } -void SPRect::setVisibleHeight(gdouble height) { - this->height = height / SPRect::vectorStretch( - Geom::Point(this->x.computed, this->y.computed + 1), - Geom::Point(this->x.computed, this->y.computed), - this->i2doc_affine()); +void SPRect::setVisibleHeight(gdouble height) +{ + this->height = + height / SPRect::vectorStretch(Geom::Point(this->x.computed, this->y.computed + 1), + Geom::Point(this->x.computed, this->y.computed), this->i2doc_affine()); - this->updateRepr(); + this->updateRepr(); } -gdouble SPRect::getVisibleWidth() const { +gdouble SPRect::getVisibleWidth() const +{ if (!this->width._set) { return 0; } - return this->width.computed * SPRect::vectorStretch( - Geom::Point(this->x.computed + 1, this->y.computed), - Geom::Point(this->x.computed, this->y.computed), - this->i2doc_affine()); + return this->width.computed * SPRect::vectorStretch(Geom::Point(this->x.computed + 1, this->y.computed), + Geom::Point(this->x.computed, this->y.computed), + this->i2doc_affine()); } -gdouble SPRect::getVisibleHeight() const { +gdouble SPRect::getVisibleHeight() const +{ if (!this->height._set) { return 0; } - return this->height.computed * SPRect::vectorStretch( - Geom::Point(this->x.computed, this->y.computed + 1), - Geom::Point(this->x.computed, this->y.computed), - this->i2doc_affine()); + return this->height.computed * SPRect::vectorStretch(Geom::Point(this->x.computed, this->y.computed + 1), + Geom::Point(this->x.computed, this->y.computed), + this->i2doc_affine()); } -void SPRect::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const { +void SPRect::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const +{ /* This method overrides sp_shape_snappoints, which is the default for any shape. The default method returns all eight points along the path of a rounded rectangle, but not the real corners. Snapping the startpoint and endpoint of each rounded corner is not very useful and really confusing. Instead @@ -580,11 +583,12 @@ void SPRect::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape:: but it should be noted that this might be confusing in some cases with relatively large radii. With small radii though the user will easily understand which point is snapping. */ - Geom::Affine const i2dt (this->i2dt_affine ()); + Geom::Affine const i2dt(this->i2dt_affine()); Geom::Point p0 = Geom::Point(this->x.computed, this->y.computed) * i2dt; Geom::Point p1 = Geom::Point(this->x.computed, this->y.computed + this->height.computed) * i2dt; - Geom::Point p2 = Geom::Point(this->x.computed + this->width.computed, this->y.computed + this->height.computed) * i2dt; + Geom::Point p2 = + Geom::Point(this->x.computed + this->width.computed, this->y.computed + this->height.computed) * i2dt; Geom::Point p3 = Geom::Point(this->x.computed + this->width.computed, this->y.computed) * i2dt; if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_RECT_CORNER)) { @@ -595,33 +599,35 @@ void SPRect::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape:: } if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_LINE_MIDPOINT)) { - p.emplace_back((p0 + p1)/2, Inkscape::SNAPSOURCE_LINE_MIDPOINT, Inkscape::SNAPTARGET_LINE_MIDPOINT); - p.emplace_back((p1 + p2)/2, Inkscape::SNAPSOURCE_LINE_MIDPOINT, Inkscape::SNAPTARGET_LINE_MIDPOINT); - p.emplace_back((p2 + p3)/2, Inkscape::SNAPSOURCE_LINE_MIDPOINT, Inkscape::SNAPTARGET_LINE_MIDPOINT); - p.emplace_back((p3 + p0)/2, Inkscape::SNAPSOURCE_LINE_MIDPOINT, Inkscape::SNAPTARGET_LINE_MIDPOINT); + p.emplace_back((p0 + p1) / 2, Inkscape::SNAPSOURCE_LINE_MIDPOINT, Inkscape::SNAPTARGET_LINE_MIDPOINT); + p.emplace_back((p1 + p2) / 2, Inkscape::SNAPSOURCE_LINE_MIDPOINT, Inkscape::SNAPTARGET_LINE_MIDPOINT); + p.emplace_back((p2 + p3) / 2, Inkscape::SNAPSOURCE_LINE_MIDPOINT, Inkscape::SNAPTARGET_LINE_MIDPOINT); + p.emplace_back((p3 + p0) / 2, Inkscape::SNAPSOURCE_LINE_MIDPOINT, Inkscape::SNAPTARGET_LINE_MIDPOINT); } if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_OBJECT_MIDPOINT)) { - p.emplace_back((p0 + p2)/2, Inkscape::SNAPSOURCE_OBJECT_MIDPOINT, Inkscape::SNAPTARGET_OBJECT_MIDPOINT); + p.emplace_back((p0 + p2) / 2, Inkscape::SNAPSOURCE_OBJECT_MIDPOINT, Inkscape::SNAPTARGET_OBJECT_MIDPOINT); } } -void SPRect::convert_to_guides() const { +void SPRect::convert_to_guides() const +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (!prefs->getBool("/tools/shapes/rect/convertguides", true)) { - // Use bounding box instead of edges - SPShape::convert_to_guides(); + // Use bounding box instead of edges + SPShape::convert_to_guides(); return; } - std::list<std::pair<Geom::Point, Geom::Point> > pts; + std::list<std::pair<Geom::Point, Geom::Point>> pts; Geom::Affine const i2dt(this->i2dt_affine()); Geom::Point A1(Geom::Point(this->x.computed, this->y.computed) * i2dt); Geom::Point A2(Geom::Point(this->x.computed, this->y.computed + this->height.computed) * i2dt); - Geom::Point A3(Geom::Point(this->x.computed + this->width.computed, this->y.computed + this->height.computed) * i2dt); + Geom::Point A3(Geom::Point(this->x.computed + this->width.computed, this->y.computed + this->height.computed) * + i2dt); Geom::Point A4(Geom::Point(this->x.computed + this->width.computed, this->y.computed) * i2dt); pts.emplace_back(A1, A2); diff --git a/src/object/sp-rect.h b/src/object/sp-rect.h index 6c9b401140731c9ce4d081ebc30bec165b4cdcff..3d514f2d9b064b68a15da089c39c4a03716aee84 100644 --- a/src/object/sp-rect.h +++ b/src/object/sp-rect.h @@ -17,64 +17,67 @@ #include <2geom/forward.h> -#include "svg/svg-length.h" #include "sp-shape.h" +#include "svg/svg-length.h" -#define SP_RECT(obj) (dynamic_cast<SPRect*>((SPObject*)obj)) -#define SP_IS_RECT(obj) (dynamic_cast<const SPRect*>((SPObject*)obj) != NULL) +#define SP_RECT(obj) (dynamic_cast<SPRect *>((SPObject *)obj)) +#define SP_IS_RECT(obj) (dynamic_cast<const SPRect *>((SPObject *)obj) != NULL) -class SPRect : public SPShape { +class SPRect : public SPShape +{ public: - SPRect(); - ~SPRect() override; + SPRect(); + ~SPRect() override; - void setPosition(double x, double y, double width, double height); + void setPosition(double x, double y, double width, double height); - /* If SET if FALSE, VALUE is just ignored */ - void setRx(bool set, double value); - void setRy(bool set, double value); + /* If SET if FALSE, VALUE is just ignored */ + void setRx(bool set, double value); + void setRy(bool set, double value); - double getVisibleRx() const; - void setVisibleRx(double rx); + double getVisibleRx() const; + void setVisibleRx(double rx); - double getVisibleRy() const; - void setVisibleRy(double ry); + double getVisibleRy() const; + void setVisibleRy(double ry); - Geom::Rect getRect() const; + Geom::Rect getRect() const; - double getVisibleWidth() const; - void setVisibleWidth(double rx); + double getVisibleWidth() const; + void setVisibleWidth(double rx); - double getVisibleHeight() const; - void setVisibleHeight(double ry); + double getVisibleHeight() const; + void setVisibleHeight(double ry); - void compensateRxRy(Geom::Affine xform); + void compensateRxRy(Geom::Affine xform); - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; - void set(SPAttr key, char const *value) override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; - bool set_rect_path_attribute(Inkscape::XML::Node *repr); + void set(SPAttr key, char const *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; + bool set_rect_path_attribute(Inkscape::XML::Node *repr); - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - const char* displayName() const override; - void update_patheffect(bool write) override; - void set_shape() override; - Geom::Affine set_transform(Geom::Affine const& xform) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + const char *displayName() const override; + void update_patheffect(bool write) override; + void set_shape() override; + Geom::Affine set_transform(Geom::Affine const &xform) override; - void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const override; - void convert_to_guides() const override; + void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, + Inkscape::SnapPreferences const *snapprefs) const override; + void convert_to_guides() const override; - SVGLength x; - SVGLength y; - SVGLength width; - SVGLength height; - SVGLength rx; - SVGLength ry; + SVGLength x; + SVGLength y; + SVGLength width; + SVGLength height; + SVGLength rx; + SVGLength ry; private: - static double vectorStretch(Geom::Point p0, Geom::Point p1, Geom::Affine xform); + static double vectorStretch(Geom::Point p0, Geom::Point p1, Geom::Affine xform); }; #endif // SEEN_SP_RECT_H diff --git a/src/object/sp-root.cpp b/src/object/sp-root.cpp index ba0ce049052123951f670a3e4b40e21cd3285d1f..b94e2e40268116a754974ead43f2db553796156e 100644 --- a/src/object/sp-root.cpp +++ b/src/object/sp-root.cpp @@ -14,22 +14,25 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <string> +#include "sp-root.h" + #include <2geom/transforms.h> +#include <string> #include "attributes.h" -#include "print.h" +#include "display/drawing-group.h" #include "document.h" #include "inkscape-version.h" +#include "print.h" #include "sp-defs.h" -#include "sp-root.h" -#include "display/drawing-group.h" #include "svg/stringstream.h" #include "svg/svg.h" -#include "xml/repr.h" #include "util/units.h" +#include "xml/repr.h" -SPRoot::SPRoot() : SPGroup(), SPViewBox() +SPRoot::SPRoot() + : SPGroup() + , SPViewBox() { this->onload = nullptr; @@ -48,8 +51,7 @@ SPRoot::SPRoot() : SPGroup(), SPViewBox() this->defs = nullptr; } -SPRoot::~SPRoot() -= default; +SPRoot::~SPRoot() = default; void SPRoot::unset_x_and_y() { @@ -59,7 +61,7 @@ void SPRoot::unset_x_and_y() void SPRoot::build(SPDocument *document, Inkscape::XML::Node *repr) { - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. if (!this->getRepr()->attribute("version")) { repr->setAttribute("version", SVG_VERSION); } @@ -78,7 +80,7 @@ void SPRoot::build(SPDocument *document, Inkscape::XML::Node *repr) SPGroup::build(document, repr); // Search for first <defs> node - for (auto& o: children) { + for (auto &o : children) { if (SP_IS_DEFS(&o)) { this->defs = SP_DEFS(&o); break; @@ -96,74 +98,73 @@ void SPRoot::release() SPGroup::release(); } - void SPRoot::set(SPAttr key, const gchar *value) { switch (key) { - case SPAttr::VERSION: - if (!sp_version_from_string(value, &this->version.svg)) { - this->version.svg = this->original.svg; - } - break; + case SPAttr::VERSION: + if (!sp_version_from_string(value, &this->version.svg)) { + this->version.svg = this->original.svg; + } + break; - case SPAttr::INKSCAPE_VERSION: - if (!sp_version_from_string(value, &this->version.inkscape)) { - this->version.inkscape = this->original.inkscape; - } - break; + case SPAttr::INKSCAPE_VERSION: + if (!sp_version_from_string(value, &this->version.inkscape)) { + this->version.inkscape = this->original.inkscape; + } + break; - case SPAttr::X: - /* Valid for non-root SVG elements; ex, em not handled correctly. */ - if (!this->x.read(value)) { - this->x.unset(SVGLength::PERCENT, 0.0, 0.0); - } + case SPAttr::X: + /* Valid for non-root SVG elements; ex, em not handled correctly. */ + if (!this->x.read(value)) { + this->x.unset(SVGLength::PERCENT, 0.0, 0.0); + } - /* fixme: I am almost sure these do not require viewport flag (Lauris) */ - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); - break; + /* fixme: I am almost sure these do not require viewport flag (Lauris) */ + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); + break; - case SPAttr::Y: - /* Valid for non-root SVG elements; ex, em not handled correctly. */ - if (!this->y.read(value)) { - this->y.unset(SVGLength::PERCENT, 0.0, 0.0); - } + case SPAttr::Y: + /* Valid for non-root SVG elements; ex, em not handled correctly. */ + if (!this->y.read(value)) { + this->y.unset(SVGLength::PERCENT, 0.0, 0.0); + } - /* fixme: I am almost sure these do not require viewport flag (Lauris) */ - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); - break; + /* fixme: I am almost sure these do not require viewport flag (Lauris) */ + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); + break; - case SPAttr::WIDTH: - if (!this->width.read(value) || !(this->width.computed > 0.0)) { - this->width.unset(SVGLength::PERCENT, 1.0, 1.0); - } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); - break; + case SPAttr::WIDTH: + if (!this->width.read(value) || !(this->width.computed > 0.0)) { + this->width.unset(SVGLength::PERCENT, 1.0, 1.0); + } + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); + break; - case SPAttr::HEIGHT: - if (!this->height.read(value) || !(this->height.computed > 0.0)) { - this->height.unset(SVGLength::PERCENT, 1.0, 1.0); - } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); - break; - - case SPAttr::VIEWBOX: - set_viewBox( value ); - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); - break; - - case SPAttr::PRESERVEASPECTRATIO: - set_preserveAspectRatio( value ); - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); - break; - - case SPAttr::ONLOAD: - this->onload = (char *) value; - break; - - default: - /* Pass the set event to the parent */ - SPGroup::set(key, value); - break; + case SPAttr::HEIGHT: + if (!this->height.read(value) || !(this->height.computed > 0.0)) { + this->height.unset(SVGLength::PERCENT, 1.0, 1.0); + } + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); + break; + + case SPAttr::VIEWBOX: + set_viewBox(value); + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); + break; + + case SPAttr::PRESERVEASPECTRATIO: + set_preserveAspectRatio(value); + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); + break; + + case SPAttr::ONLOAD: + this->onload = (char *)value; + break; + + default: + /* Pass the set event to the parent */ + SPGroup::set(key, value); + break; } } @@ -175,11 +176,11 @@ void SPRoot::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) // NOTE: some XML nodes do not have corresponding SP objects, // for instance inkscape:clipboard used in the clipboard code. // See LP bug #1227827 - //g_assert (co != NULL || !strcmp("comment", child->name())); // comment repr node has no object + // g_assert (co != NULL || !strcmp("comment", child->name())); // comment repr node has no object if (co && SP_IS_DEFS(co)) { // We search for first <defs> node - it is not beautiful, but works - for (auto& c: children) { + for (auto &c : children) { if (SP_IS_DEFS(&c)) { this->defs = SP_DEFS(&c); break; @@ -194,7 +195,7 @@ void SPRoot::remove_child(Inkscape::XML::Node *child) SPObject *iter = nullptr; // We search for first remaining <defs> node - it is not beautiful, but works - for (auto& child: children) { + for (auto &child : children) { iter = &child; if (SP_IS_DEFS(iter) && (SPDefs *)iter != this->defs) { this->defs = (SPDefs *)iter; @@ -224,33 +225,31 @@ void SPRoot::setRootDimensions() * x, y are ignored. * initial viewport = (0 0 width height) */ - if( this->viewBox_set ) { - - if( this->width._set ) { + if (this->viewBox_set) { + if (this->width._set) { // Check if this is necessary if (this->width.unit == SVGLength::PERCENT) { - this->width.computed = this->width.value * this->viewBox.width(); + this->width.computed = this->width.value * this->viewBox.width(); } } else { - this->width.set( SVGLength::PX, this->viewBox.width(), this->viewBox.width() ); + this->width.set(SVGLength::PX, this->viewBox.width(), this->viewBox.width()); } - if( this->height._set ) { + if (this->height._set) { if (this->height.unit == SVGLength::PERCENT) { this->height.computed = this->height.value * this->viewBox.height(); } } else { - this->height.set(SVGLength::PX, this->viewBox.height(), this->viewBox.height() ); + this->height.set(SVGLength::PX, this->viewBox.height(), this->viewBox.height()); } } else { - - if( !this->width._set || this->width.unit == SVGLength::PERCENT) { - this->width.set( SVGLength::PX, 300, 300 ); // CSS/SVG default + if (!this->width._set || this->width.unit == SVGLength::PERCENT) { + this->width.set(SVGLength::PX, 300, 300); // CSS/SVG default } - if( !this->height._set || this->height.unit == SVGLength::PERCENT) { - this->height.set( SVGLength::PX, 150, 150 ); // CSS/SVG default + if (!this->height._set || this->height.unit == SVGLength::PERCENT) { + this->height.set(SVGLength::PX, 150, 150); // CSS/SVG default } } @@ -260,9 +259,9 @@ void SPRoot::setRootDimensions() void SPRoot::update(SPCtx *ctx, guint flags) { - SPItemCtx const *ictx = (SPItemCtx const *) ctx; + SPItemCtx const *ictx = (SPItemCtx const *)ctx; - if( !this->parent ) { + if (!this->parent) { this->setRootDimensions(); } @@ -277,12 +276,12 @@ void SPRoot::update(SPCtx *ctx, guint flags) // Calculate new viewport SPItemCtx rctx = *ictx; - rctx.viewport = Geom::Rect::from_xywh( this->x.computed, this->y.computed, - this->width.computed, this->height.computed ); - rctx = get_rctx( &rctx, Inkscape::Util::Quantity::convert(1, this->document->getDisplayUnit(), "px") ); + rctx.viewport = + Geom::Rect::from_xywh(this->x.computed, this->y.computed, this->width.computed, this->height.computed); + rctx = get_rctx(&rctx, Inkscape::Util::Quantity::convert(1, this->document->getDisplayUnit(), "px")); /* And invoke parent method */ - SPGroup::update((SPCtx *) &rctx, flags); + SPGroup::update((SPCtx *)&rctx, flags); /* As last step set additional transform of drawing group */ for (SPItemView *v = this->display; v != nullptr; v = v->next) { @@ -301,7 +300,6 @@ void SPRoot::modified(unsigned int flags) } } - Inkscape::XML::Node *SPRoot::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { @@ -336,8 +334,8 @@ Inkscape::XML::Node *SPRoot::write(Inkscape::XML::Document *xml_doc, Inkscape::X if (this->viewBox_set) { Inkscape::SVGOStringStream os; - os << this->viewBox.left() << " " << this->viewBox.top() << " " - << this->viewBox.width() << " " << this->viewBox.height(); + os << this->viewBox.left() << " " << this->viewBox.top() << " " << this->viewBox.width() << " " + << this->viewBox.height(); repr->setAttribute("viewBox", os.str()); } @@ -377,8 +375,9 @@ void SPRoot::print(SPPrintContext *ctx) ctx->release(); } -const char *SPRoot::displayName() const { - return "SVG"; // Do not translate +const char *SPRoot::displayName() const +{ + return "SVG"; // Do not translate } /* diff --git a/src/object/sp-root.h b/src/object/sp-root.h index 45873985e6e9c3c7aaf228da8ef12ea06a13de35..20b480ca07fb02c9bd171cadc541386d72cd1ef1 100644 --- a/src/object/sp-root.h +++ b/src/object/sp-root.h @@ -15,24 +15,29 @@ #ifndef SP_ROOT_H_SEEN #define SP_ROOT_H_SEEN -#include "version.h" -#include "svg/svg-length.h" +#include "sp-dimensions.h" #include "sp-item-group.h" +#include "svg/svg-length.h" +#include "version.h" #include "viewbox.h" -#include "sp-dimensions.h" -#define SP_ROOT(obj) (dynamic_cast<SPRoot*>((SPObject*)obj)) -#define SP_IS_ROOT(obj) (dynamic_cast<const SPRoot*>((SPObject*)obj) != NULL) +#define SP_ROOT(obj) (dynamic_cast<SPRoot *>((SPObject *)obj)) +#define SP_IS_ROOT(obj) (dynamic_cast<const SPRoot *>((SPObject *)obj) != NULL) class SPDefs; /** \<svg\> element */ -class SPRoot : public SPGroup, public SPViewBox, public SPDimensions { +class SPRoot + : public SPGroup + , public SPViewBox + , public SPDimensions +{ public: - SPRoot(); - ~SPRoot() override; + SPRoot(); + ~SPRoot() override; - struct { + struct + { Inkscape::Version svg; Inkscape::Version inkscape; } version, original; @@ -47,19 +52,21 @@ public: */ SPDefs *defs; - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; - void set(SPAttr key, char const* value) override; - void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, char const *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + + void modified(unsigned int flags) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; - void modified(unsigned int flags) override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; + Inkscape::DrawingItem *show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; + void print(SPPrintContext *ctx) override; + const char *displayName() const override; - Inkscape::DrawingItem* show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; - void print(SPPrintContext *ctx) override; - const char* displayName() const override; private: void unset_x_and_y(); void setRootDimensions(); diff --git a/src/object/sp-script.cpp b/src/object/sp-script.cpp index 7daaa5cdf51ed33761c74a675a478667ffe7642e..50b531d5be678d45b7d9b236b26c6a9f26e92ab0 100644 --- a/src/object/sp-script.cpp +++ b/src/object/sp-script.cpp @@ -13,18 +13,22 @@ */ #include "sp-script.h" + #include "attributes.h" -SPScript::SPScript() : SPObject() { - this->xlinkhref = nullptr; +SPScript::SPScript() + : SPObject() +{ + this->xlinkhref = nullptr; } SPScript::~SPScript() = default; -void SPScript::build(SPDocument* doc, Inkscape::XML::Node* repr) { +void SPScript::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ SPObject::build(doc, repr); - //Read values of key attributes from XML nodes into object. + // Read values of key attributes from XML nodes into object. this->readAttr(SPAttr::XLINK_HREF); doc->addResource("script", this); @@ -36,7 +40,8 @@ void SPScript::build(SPDocument* doc, Inkscape::XML::Node* repr) { * sp-object-repr.cpp's repr_name_entries array. */ -void SPScript::release() { +void SPScript::release() +{ if (this->document) { // Unregister ourselves this->document->removeResource("script", this); @@ -45,32 +50,30 @@ void SPScript::release() { SPObject::release(); } -void SPScript::update(SPCtx* /*ctx*/, unsigned int /*flags*/) { -} - - -void SPScript::modified(unsigned int /*flags*/) { -} +void SPScript::update(SPCtx * /*ctx*/, unsigned int /*flags*/) {} +void SPScript::modified(unsigned int /*flags*/) {} -void SPScript::set(SPAttr key, const gchar* value) { +void SPScript::set(SPAttr key, const gchar *value) +{ switch (key) { - case SPAttr::XLINK_HREF: + case SPAttr::XLINK_HREF: if (this->xlinkhref) { - g_free(this->xlinkhref); + g_free(this->xlinkhref); } this->xlinkhref = g_strdup(value); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; - default: + default: SPObject::set(key, value); break; } } -Inkscape::XML::Node* SPScript::write(Inkscape::XML::Document* /*doc*/, Inkscape::XML::Node* repr, guint /*flags*/) { - return repr; +Inkscape::XML::Node *SPScript::write(Inkscape::XML::Document * /*doc*/, Inkscape::XML::Node *repr, guint /*flags*/) +{ + return repr; } /* diff --git a/src/object/sp-script.h b/src/object/sp-script.h index 2281a5a43d4ee9aa5a4e04a70d96d6841371b09b..e9c28cb40200dbe8ec388511a77c68552ac9aa34 100644 --- a/src/object/sp-script.h +++ b/src/object/sp-script.h @@ -14,24 +14,25 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "sp-object.h" #include "document.h" +#include "sp-object.h" /* SPScript */ -class SPScript : public SPObject { +class SPScript : public SPObject +{ public: - SPScript(); - ~SPScript() override; + SPScript(); + ~SPScript() override; - char *xlinkhref; + char *xlinkhref; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; - void set(SPAttr key, char const* value) override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, char const *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif diff --git a/src/object/sp-shape-reference.cpp b/src/object/sp-shape-reference.cpp index a30e6d317435a432dd145980afd1ca9a58d20a0c..262337941f556aa4607dc6b75afa0c2610b4b1d1 100644 --- a/src/object/sp-shape-reference.cpp +++ b/src/object/sp-shape-reference.cpp @@ -6,6 +6,7 @@ */ #include "sp-shape-reference.h" + #include "object/sp-text.h" SPShapeReference::SPShapeReference(SPObject *obj) diff --git a/src/object/sp-shape-reference.h b/src/object/sp-shape-reference.h index 80fcb103a0c7d02d3190fc3b8f66862d92919733..8858e71dad3e7991b1b19a4908e894f2c47373b6 100644 --- a/src/object/sp-shape-reference.h +++ b/src/object/sp-shape-reference.h @@ -16,27 +16,23 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "uri-references.h" - #include "sp-object.h" #include "sp-shape.h" +#include "uri-references.h" class SPDocument; -class SPShapeReference : public Inkscape::URIReference { +class SPShapeReference : public Inkscape::URIReference +{ public: ~SPShapeReference() override; SPShapeReference(SPObject *obj); - SPShape *getObject() const { - return static_cast<SPShape *>(URIReference::getObject()); - } + SPShape *getObject() const { return static_cast<SPShape *>(URIReference::getObject()); } protected: - bool _acceptObject(SPObject *obj) const override { - return SP_IS_SHAPE(obj) && URIReference::_acceptObject(obj); - }; + bool _acceptObject(SPObject *obj) const override { return SP_IS_SHAPE(obj) && URIReference::_acceptObject(obj); }; - private: +private: void on_shape_modified(SPObject *, unsigned flags); sigc::connection _shape_modified_connection; diff --git a/src/object/sp-shape.cpp b/src/object/sp-shape.cpp index 0c86ea07ab6c8d6eaa1d9f95d912bc801cbc6f38..5b70def8c0e84ddcc6fd671f572aea6854af0dec 100644 --- a/src/object/sp-shape.cpp +++ b/src/object/sp-shape.cpp @@ -15,40 +15,39 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <2geom/path-intersection.h> +#include <2geom/pathvector.h> #include <2geom/rect.h> #include <2geom/transforms.h> -#include <2geom/pathvector.h> -#include <2geom/path-intersection.h> -#include "helper/geom.h" -#include "helper/geom-nodetype.h" - -#include <sigc++/functors/ptr_fun.h> #include <sigc++/adaptors/bind.h> +#include <sigc++/functors/ptr_fun.h> -#include "display/drawing-shape.h" +#include "attributes.h" #include "display/curve.h" -#include "print.h" +#include "display/drawing-shape.h" #include "document.h" -#include "style.h" +#include "helper/geom-nodetype.h" +#include "helper/geom.h" +#include "helper/mathfns.h" // for triangle_area() +#include "live_effects/lpeobject.h" +#include "path/path-outline.h" // For bound box calculation +#include "preferences.h" +#include "print.h" #include "sp-marker.h" -#include "sp-root.h" #include "sp-path.h" -#include "preferences.h" -#include "attributes.h" -#include "path/path-outline.h" // For bound box calculation - -#include "svg/svg.h" +#include "sp-root.h" +#include "style.h" #include "svg/path-string.h" -#include "live_effects/lpeobject.h" - -#include "helper/mathfns.h" // for triangle_area() +#include "svg/svg.h" #define noSHAPE_VERBOSE -static void sp_shape_update_marker_view (SPShape *shape, Inkscape::DrawingItem *ai); +static void sp_shape_update_marker_view(SPShape *shape, Inkscape::DrawingItem *ai); -SPShape::SPShape() : SPLPEItem() { - for (auto & i : this->_marker) { +SPShape::SPShape() + : SPLPEItem() +{ + for (auto &i : this->_marker) { i = nullptr; } @@ -56,22 +55,23 @@ SPShape::SPShape() : SPLPEItem() { this->_curve_before_lpe = nullptr; } -SPShape::~SPShape() { - for ( int i = 0 ; i < SP_MARKER_LOC_QTY ; i++ ) { +SPShape::~SPShape() +{ + for (int i = 0; i < SP_MARKER_LOC_QTY; i++) { this->_release_connect[i].disconnect(); this->_modified_connect[i].disconnect(); } } -void SPShape::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPShape::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPLPEItem::build(document, repr); - for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) { - sp_shape_set_marker (this, i, this->style->marker_ptrs[i]->value()); + for (int i = 0; i < SP_MARKER_LOC_QTY; i++) { + sp_shape_set_marker(this, i, this->style->marker_ptrs[i]->value()); } } - /** * Removes, releases and unrefs all children of object * @@ -82,10 +82,10 @@ void SPShape::build(SPDocument *document, Inkscape::XML::Node *repr) { * * \see SPObject::release() */ -void SPShape::release() { +void SPShape::release() +{ for (int i = 0; i < SP_MARKER_LOC_QTY; i++) { if (this->_marker[i]) { - for (SPItemView *v = this->display; v != nullptr; v = v->next) { sp_marker_hide(_marker[i], v->arenaitem->key() + i); } @@ -96,25 +96,27 @@ void SPShape::release() { _marker[i] = nullptr; } } - + _curve.reset(); - + _curve_before_lpe.reset(); SPLPEItem::release(); } -void SPShape::set(SPAttr key, const gchar* value) { - SPLPEItem::set(key, value); +void SPShape::set(SPAttr key, const gchar *value) +{ + SPLPEItem::set(key, value); } - -Inkscape::XML::Node* SPShape::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - SPLPEItem::write(xml_doc, repr, flags); - return repr; +Inkscape::XML::Node *SPShape::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + SPLPEItem::write(xml_doc, repr, flags); + return repr; } -void SPShape::update(SPCtx* ctx, guint flags) { +void SPShape::update(SPCtx *ctx, guint flags) +{ // Any update can change the bounding box, // so the cached version can no longer be used. // But the idle checker usually is just moving the objects around. @@ -129,17 +131,17 @@ void SPShape::update(SPCtx* ctx, guint flags) { * that the appropriate marker objects are present (or absent) to * match the style. */ - for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) { - sp_shape_set_marker (this, i, this->style->marker_ptrs[i]->value()); + for (int i = 0; i < SP_MARKER_LOC_QTY; i++) { + sp_shape_set_marker(this, i, this->style->marker_ptrs[i]->value()); } if (flags & (SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { if (this->style->stroke_width.unit == SP_CSS_UNIT_PERCENT) { - SPItemCtx *ictx = (SPItemCtx *) ctx; + SPItemCtx *ictx = (SPItemCtx *)ctx; double const aw = 1.0 / ictx->i2vp.descrim(); this->style->stroke_width.computed = this->style->stroke_width.value * aw; - for (SPItemView *v = ((SPItem *) (this))->display; v != nullptr; v = v->next) { + for (SPItemView *v = ((SPItem *)(this))->display; v != nullptr; v = v->next) { Inkscape::DrawingShape *sh = dynamic_cast<Inkscape::DrawingShape *>(v->arenaitem); if (hasMarkers()) { this->context_style = this->style; @@ -166,28 +168,25 @@ void SPShape::update(SPCtx* ctx, guint flags) { } } - if (this->hasMarkers ()) { - + if (this->hasMarkers()) { /* Dimension marker views */ for (SPItemView *v = this->display; v != nullptr; v = v->next) { if (!v->arenaitem->key()) { - v->arenaitem->setKey(SPItem::display_key_new (SP_MARKER_LOC_QTY)); + v->arenaitem->setKey(SPItem::display_key_new(SP_MARKER_LOC_QTY)); } - for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) { + for (int i = 0; i < SP_MARKER_LOC_QTY; i++) { if (_marker[i]) { - sp_marker_show_dimension(_marker[i], - v->arenaitem->key() + i, - numberOfMarkers(i)); + sp_marker_show_dimension(_marker[i], v->arenaitem->key() + i, numberOfMarkers(i)); } } } /* Update marker views */ for (SPItemView *v = this->display; v != nullptr; v = v->next) { - sp_shape_update_marker_view (this, v->arenaitem); + sp_shape_update_marker_view(this, v->arenaitem); } - + // Marker selector needs this here or marker previews are not rendered. for (SPItemView *v = this->display; v != nullptr; v = v->next) { Inkscape::DrawingShape *sh = dynamic_cast<Inkscape::DrawingShape *>(v->arenaitem); @@ -198,40 +197,38 @@ void SPShape::update(SPCtx* ctx, guint flags) { /* Update stroke/dashes for relative units. */ if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - SPItemCtx const *ictx = reinterpret_cast<SPItemCtx const *>(ctx); double const w = ictx->viewport.width(); double const h = ictx->viewport.height(); - double const d = sqrt(w*w + h*h) * M_SQRT1_2; // diagonal per SVG spec + double const d = sqrt(w * w + h * h) * M_SQRT1_2; // diagonal per SVG spec double const em = style->font_size.computed; - double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. + double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. if (style->stroke_width.unit == SP_CSS_UNIT_EM) { style->stroke_width.computed = style->stroke_width.value * em; - } - else if (style->stroke_width.unit == SP_CSS_UNIT_EX) { + } else if (style->stroke_width.unit == SP_CSS_UNIT_EX) { style->stroke_width.computed = style->stroke_width.value * ex; - } - else if (style->stroke_width.unit == SP_CSS_UNIT_PERCENT) { + } else if (style->stroke_width.unit == SP_CSS_UNIT_PERCENT) { style->stroke_width.computed = style->stroke_width.value * d; } if (style->stroke_dasharray.values.size() != 0) { - for (auto&& i: style->stroke_dasharray.values) { - if (i.unit == SP_CSS_UNIT_EM) i.computed = i.value * em; - else if (i.unit == SP_CSS_UNIT_EX) i.computed = i.value * ex; - else if (i.unit == SP_CSS_UNIT_PERCENT) i.computed = i.value * d; + for (auto &&i : style->stroke_dasharray.values) { + if (i.unit == SP_CSS_UNIT_EM) + i.computed = i.value * em; + else if (i.unit == SP_CSS_UNIT_EX) + i.computed = i.value * ex; + else if (i.unit == SP_CSS_UNIT_PERCENT) + i.computed = i.value * d; } } if (style->stroke_dashoffset.unit == SP_CSS_UNIT_EM) { style->stroke_dashoffset.computed = style->stroke_dashoffset.value * em; - } - else if (style->stroke_dashoffset.unit == SP_CSS_UNIT_EX) { + } else if (style->stroke_dashoffset.unit == SP_CSS_UNIT_EX) { style->stroke_dashoffset.computed = style->stroke_dashoffset.value * ex; - } - else if (style->stroke_dashoffset.unit == SP_CSS_UNIT_PERCENT) { + } else if (style->stroke_dashoffset.unit == SP_CSS_UNIT_PERCENT) { style->stroke_dashoffset.computed = style->stroke_dashoffset.value * d; } } @@ -253,11 +250,11 @@ void SPShape::update(SPCtx* ctx, guint flags) { * Reference for behaviour of zero-length segments: * http://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes */ -Geom::Affine sp_shape_marker_get_transform(Geom::Curve const & c1, Geom::Curve const & c2) +Geom::Affine sp_shape_marker_get_transform(Geom::Curve const &c1, Geom::Curve const &c2) { Geom::Point p = c1.pointAt(1); - Geom::Curve * c1_reverse = c1.reverse(); - Geom::Point tang1 = - c1_reverse->unitTangentAt(0); + Geom::Curve *c1_reverse = c1.reverse(); + Geom::Point tang1 = -c1_reverse->unitTangentAt(0); delete c1_reverse; Geom::Point tang2 = c2.unitTangentAt(0); @@ -266,7 +263,7 @@ Geom::Affine sp_shape_marker_get_transform(Geom::Curve const & c1, Geom::Curve c double ret_angle = .5 * (angle1 + angle2); - if ( fabs( angle2 - angle1 ) > M_PI ) { + if (fabs(angle2 - angle1) > M_PI) { /* ret_angle is in the middle of the larger of the two sectors between angle1 and * angle2, so flip it by 180degrees to force it to the middle of the smaller sector. * @@ -279,12 +276,12 @@ Geom::Affine sp_shape_marker_get_transform(Geom::Curve const & c1, Geom::Curve c return Geom::Rotate(ret_angle) * Geom::Translate(p); } -Geom::Affine sp_shape_marker_get_transform_at_start(Geom::Curve const & c) +Geom::Affine sp_shape_marker_get_transform_at_start(Geom::Curve const &c) { Geom::Point p = c.pointAt(0); Geom::Affine ret = Geom::Translate(p); - if ( !c.isDegenerate() ) { + if (!c.isDegenerate()) { Geom::Point tang = c.unitTangentAt(0); double const angle = Geom::atan2(tang); ret = Geom::Rotate(angle) * Geom::Translate(p); @@ -296,14 +293,14 @@ Geom::Affine sp_shape_marker_get_transform_at_start(Geom::Curve const & c) return ret; } -Geom::Affine sp_shape_marker_get_transform_at_end(Geom::Curve const & c) +Geom::Affine sp_shape_marker_get_transform_at_end(Geom::Curve const &c) { Geom::Point p = c.pointAt(1); Geom::Affine ret = Geom::Translate(p); - if ( !c.isDegenerate() ) { - Geom::Curve * c_reverse = c.reverse(); - Geom::Point tang = - c_reverse->unitTangentAt(0); + if (!c.isDegenerate()) { + Geom::Curve *c_reverse = c.reverse(); + Geom::Point tang = -c_reverse->unitTangentAt(0); delete c_reverse; double const angle = Geom::atan2(tang); ret = Geom::Rotate(angle) * Geom::Translate(p); @@ -322,8 +319,7 @@ Geom::Affine sp_shape_marker_get_transform_at_end(Geom::Curve const & c) * * @todo figure out what to do when both 'marker' and for instance 'marker-end' are set. */ -static void -sp_shape_update_marker_view(SPShape *shape, Inkscape::DrawingItem *ai) +static void sp_shape_update_marker_view(SPShape *shape, Inkscape::DrawingItem *ai) { // position arguments to sp_marker_show_instance, basically counts the amount of markers. int counter[4] = {0}; @@ -332,61 +328,60 @@ sp_shape_update_marker_view(SPShape *shape, Inkscape::DrawingItem *ai) return; Geom::PathVector const &pathv = shape->curve()->get_pathvector(); - if (pathv.empty()) return; + if (pathv.empty()) + return; // the first vertex should get a start marker, the last an end marker, and all the others a mid marker // see bug 456148 // START marker { - Geom::Affine const m (sp_shape_marker_get_transform_at_start(pathv.begin()->front())); - for (int i = 0; i < 2; i++) { // SP_MARKER_LOC and SP_MARKER_LOC_START - if ( shape->_marker[i] ) { + Geom::Affine const m(sp_shape_marker_get_transform_at_start(pathv.begin()->front())); + for (int i = 0; i < 2; i++) { // SP_MARKER_LOC and SP_MARKER_LOC_START + if (shape->_marker[i]) { Geom::Affine m_auto = m; // Reverse start marker if necessary. if (shape->_marker[i]->orient_mode == MARKER_ORIENT_AUTO_START_REVERSE) { - m_auto = Geom::Rotate::from_degrees( 180.0 ) * m; + m_auto = Geom::Rotate::from_degrees(180.0) * m; } - sp_marker_show_instance(shape->_marker[i], ai, - ai->key() + i, counter[i], m_auto, + sp_marker_show_instance(shape->_marker[i], ai, ai->key() + i, counter[i], m_auto, shape->style->stroke_width.computed); - counter[i]++; + counter[i]++; } } } // MID marker if (shape->_marker[SP_MARKER_LOC_MID] || shape->_marker[SP_MARKER_LOC]) { - for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) { + for (Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) { // START position - if ( path_it != pathv.begin() - && ! ((path_it == (pathv.end()-1)) && (path_it->size_default() == 0)) ) // if this is the last path and it is a moveto-only, don't draw mid marker there + if (path_it != pathv.begin() && + !((path_it == (pathv.end() - 1)) && (path_it->size_default() == 0))) // if this is the last path and it + // is a moveto-only, don't draw mid + // marker there { - Geom::Affine const m (sp_shape_marker_get_transform_at_start(path_it->front())); - for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID - if ( shape->_marker[i] ) { - sp_marker_show_instance(shape->_marker[i], ai, - ai->key() + i, counter[i], m, + Geom::Affine const m(sp_shape_marker_get_transform_at_start(path_it->front())); + for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID + if (shape->_marker[i]) { + sp_marker_show_instance(shape->_marker[i], ai, ai->key() + i, counter[i], m, shape->style->stroke_width.computed); - counter[i]++; + counter[i]++; } } } // MID position - if ( path_it->size_default() > 1) { - Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve - Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve - while (curve_it2 != path_it->end_default()) - { + if (path_it->size_default() > 1) { + Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve + Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve + while (curve_it2 != path_it->end_default()) { /* Put marker between curve_it1 and curve_it2. * Loop to end_default (so including closing segment), because when a path is closed, * there should be a midpoint marker between last segment and closing straight line segment */ - Geom::Affine const m (sp_shape_marker_get_transform(*curve_it1, *curve_it2)); - for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID + Geom::Affine const m(sp_shape_marker_get_transform(*curve_it1, *curve_it2)); + for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID if (shape->_marker[i]) { - sp_marker_show_instance(shape->_marker[i], ai, - ai->key() + i, counter[i], m, + sp_marker_show_instance(shape->_marker[i], ai, ai->key() + i, counter[i], m, shape->style->stroke_width.computed); counter[i]++; } @@ -397,13 +392,12 @@ sp_shape_update_marker_view(SPShape *shape, Inkscape::DrawingItem *ai) } } // END position - if ( path_it != (pathv.end()-1) && !path_it->empty()) { + if (path_it != (pathv.end() - 1) && !path_it->empty()) { Geom::Curve const &lastcurve = path_it->back_default(); Geom::Affine const m = sp_shape_marker_get_transform_at_end(lastcurve); - for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID + for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID if (shape->_marker[i]) { - sp_marker_show_instance(shape->_marker[i], ai, - ai->key() + i, counter[i], m, + sp_marker_show_instance(shape->_marker[i], ai, ai->key() + i, counter[i], m, shape->style->stroke_width.computed); counter[i]++; } @@ -413,7 +407,7 @@ sp_shape_update_marker_view(SPShape *shape, Inkscape::DrawingItem *ai) } // END marker - if ( shape->_marker[SP_MARKER_LOC_END] || shape->_marker[SP_MARKER_LOC] ) { + if (shape->_marker[SP_MARKER_LOC_END] || shape->_marker[SP_MARKER_LOC]) { /* Get reference to last curve in the path. * For moveto-only path, this returns the "closing line segment". */ Geom::Path const &path_last = pathv.back(); @@ -424,10 +418,9 @@ sp_shape_update_marker_view(SPShape *shape, Inkscape::DrawingItem *ai) Geom::Curve const &lastcurve = path_last[index]; Geom::Affine const m = sp_shape_marker_get_transform_at_end(lastcurve); - for (int i = 0; i < 4; i += 3) { // SP_MARKER_LOC and SP_MARKER_LOC_END + for (int i = 0; i < 4; i += 3) { // SP_MARKER_LOC and SP_MARKER_LOC_END if (shape->_marker[i]) { - sp_marker_show_instance(shape->_marker[i], ai, - ai->key() + i, counter[i], m, + sp_marker_show_instance(shape->_marker[i], ai, ai->key() + i, counter[i], m, shape->style->stroke_width.computed); counter[i]++; } @@ -435,7 +428,8 @@ sp_shape_update_marker_view(SPShape *shape, Inkscape::DrawingItem *ai) } } -void SPShape::modified(unsigned int flags) { +void SPShape::modified(unsigned int flags) +{ // std::cout << "SPShape::modified(): " << (getId()?getId():"null") << std::endl; SPLPEItem::modified(flags); @@ -461,7 +455,8 @@ void SPShape::modified(unsigned int flags) { } } -Geom::OptRect SPShape::bbox(Geom::Affine const &transform, SPItem::BBoxType bboxtype) const { +Geom::OptRect SPShape::bbox(Geom::Affine const &transform, SPItem::BBoxType bboxtype) const +{ // If the object is clipped, the update funcation that invalidates // the cache doesn't get called if the object is moved, so we need // to compare the transformations as well. @@ -488,13 +483,11 @@ Geom::OptRect SPShape::bbox(Geom::Affine const &transform, SPItem::BBoxType bbox Geom::OptRect SPShape::either_bbox(Geom::Affine const &transform, SPItem::BBoxType bboxtype, bool cache_is_valid, Geom::OptRect bbox_cache, Geom::Affine const &transform_cache) const { - Geom::OptRect bbox; // Return the cache if possible. auto delta = transform_cache.inverse() * transform; if (cache_is_valid && bbox_cache && delta.isTranslation()) { - // Don't re-adjust the cache if we haven't moved if (!delta.isNonzeroTranslation()) { return bbox_cache; @@ -504,20 +497,20 @@ Geom::OptRect SPShape::either_bbox(Geom::Affine const &transform, SPItem::BBoxTy } if (!this->_curve || this->_curve->get_pathvector().empty()) { - return bbox; + return bbox; } bbox = bounds_exact_transformed(this->_curve->get_pathvector(), transform); if (!bbox) { - return bbox; + return bbox; } if (bboxtype == SPItem::VISUAL_BBOX) { // convert the stroke to a path and calculate that path's geometric bbox if (!this->style->stroke.isNone()) { - Geom::PathVector *pathv = item_to_outline(this, true); // calculate bbox_only + Geom::PathVector *pathv = item_to_outline(this, true); // calculate bbox_only if (pathv) { bbox |= bounds_exact_transformed(*pathv, transform); @@ -526,20 +519,20 @@ Geom::OptRect SPShape::either_bbox(Geom::Affine const &transform, SPItem::BBoxTy } // Union with bboxes of the markers, if any - if ( this->hasMarkers() && !this->_curve->get_pathvector().empty() ) { + if (this->hasMarkers() && !this->_curve->get_pathvector().empty()) { /** \todo make code prettier! */ - Geom::PathVector const & pathv = this->_curve->get_pathvector(); + Geom::PathVector const &pathv = this->_curve->get_pathvector(); // START marker for (unsigned i = 0; i < 2; i++) { // SP_MARKER_LOC and SP_MARKER_LOC_START - if ( this->_marker[i] ) { - SPItem* marker_item = sp_item_first_item_child( _marker[i] ); + if (this->_marker[i]) { + SPItem *marker_item = sp_item_first_item_child(_marker[i]); if (marker_item) { Geom::Affine tr(sp_shape_marker_get_transform_at_start(pathv.begin()->front())); if (_marker[i]->orient_mode == MARKER_ORIENT_AUTO_START_REVERSE) { // Reverse start marker if necessary - tr = Geom::Rotate::from_degrees( 180.0 ) * tr; + tr = Geom::Rotate::from_degrees(180.0) * tr; } else if (_marker[i]->orient_mode == MARKER_ORIENT_ANGLE) { Geom::Point transl = tr.translation(); tr = Geom::Rotate::from_degrees(_marker[i]->orient.computed) * Geom::Translate(transl); @@ -560,21 +553,23 @@ Geom::OptRect SPShape::either_bbox(Geom::Affine const &transform, SPItem::BBoxTy // MID marker for (unsigned i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID - if ( !this->_marker[i] ) { - continue; + if (!this->_marker[i]) { + continue; } - SPMarker* marker = _marker[i]; - SPItem* marker_item = sp_item_first_item_child( marker ); + SPMarker *marker = _marker[i]; + SPItem *marker_item = sp_item_first_item_child(marker); - if ( !marker_item ) { - continue; + if (!marker_item) { + continue; } - for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) { + for (Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) { // START position - if ( path_it != pathv.begin() - && ! ((path_it == (pathv.end()-1)) && (path_it->size_default() == 0)) ) // if this is the last path and it is a moveto-only, there is no mid marker there + if (path_it != pathv.begin() && !((path_it == (pathv.end() - 1)) && + (path_it->size_default() == 0))) // if this is the last path and + // it is a moveto-only, there is + // no mid marker there { Geom::Affine tr(sp_shape_marker_get_transform_at_start(path_it->front())); @@ -592,18 +587,18 @@ Geom::OptRect SPShape::either_bbox(Geom::Affine const &transform, SPItem::BBoxTy } // MID position - if ( path_it->size_default() > 1) { - Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve - Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve + if (path_it->size_default() > 1) { + Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve + Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve - while (curve_it2 != path_it->end_default()) - { + while (curve_it2 != path_it->end_default()) { /* Put marker between curve_it1 and curve_it2. * Loop to end_default (so including closing segment), because when a path is closed, - * there should be a midpoint marker between last segment and closing straight line segment */ + * there should be a midpoint marker between last segment and closing straight line segment + */ - SPMarker* marker = _marker[i]; - SPItem* marker_item = sp_item_first_item_child( marker ); + SPMarker *marker = _marker[i]; + SPItem *marker_item = sp_item_first_item_child(marker); if (marker_item) { Geom::Affine tr(sp_shape_marker_get_transform(*curve_it1, *curve_it2)); @@ -627,7 +622,7 @@ Geom::OptRect SPShape::either_bbox(Geom::Affine const &transform, SPItem::BBoxTy } // END position - if ( path_it != (pathv.end()-1) && !path_it->empty()) { + if (path_it != (pathv.end() - 1) && !path_it->empty()) { Geom::Curve const &lastcurve = path_it->back_default(); Geom::Affine tr = sp_shape_marker_get_transform_at_end(lastcurve); @@ -648,9 +643,9 @@ Geom::OptRect SPShape::either_bbox(Geom::Affine const &transform, SPItem::BBoxTy // END marker for (unsigned i = 0; i < 4; i += 3) { // SP_MARKER_LOC and SP_MARKER_LOC_END - if ( _marker[i] ) { - SPMarker* marker = _marker[i]; - SPItem* marker_item = sp_item_first_item_child( marker ); + if (_marker[i]) { + SPMarker *marker = _marker[i]; + SPItem *marker_item = sp_item_first_item_child(marker); if (marker_item) { /* Get reference to last curve in the path. @@ -686,95 +681,96 @@ Geom::OptRect SPShape::either_bbox(Geom::Affine const &transform, SPItem::BBoxTy } } - return bbox; } -static void -sp_shape_print_invoke_marker_printing(SPObject *obj, Geom::Affine tr, SPStyle const *style, SPPrintContext *ctx) +static void sp_shape_print_invoke_marker_printing(SPObject *obj, Geom::Affine tr, SPStyle const *style, + SPPrintContext *ctx) { SPMarker *marker = SP_MARKER(obj); if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) { tr = Geom::Scale(style->stroke_width.computed) * tr; } - SPItem* marker_item = sp_item_first_item_child( marker ); + SPItem *marker_item = sp_item_first_item_child(marker); if (marker_item) { tr = marker_item->transform * marker->c2p * tr; Geom::Affine old_tr = marker_item->transform; marker_item->transform = tr; - marker_item->invoke_print (ctx); + marker_item->invoke_print(ctx); marker_item->transform = old_tr; } } -void SPShape::print(SPPrintContext* ctx) { - if (!this->_curve) { - return; +void SPShape::print(SPPrintContext *ctx) +{ + if (!this->_curve) { + return; } - Geom::PathVector const & pathv = this->_curve->get_pathvector(); - + Geom::PathVector const &pathv = this->_curve->get_pathvector(); + if (pathv.empty()) { - return; + return; } - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - gint add_comments = prefs->getBool("/printing/debug/add-label-comments"); - - if (add_comments) { - gchar * comment = g_strdup_printf("begin '%s'", this->defaultLabel()); - ctx->comment(comment); - g_free(comment); - } + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + gint add_comments = prefs->getBool("/printing/debug/add-label-comments"); + + if (add_comments) { + gchar *comment = g_strdup_printf("begin '%s'", this->defaultLabel()); + ctx->comment(comment); + g_free(comment); + } /* fixme: Think (Lauris) */ - Geom::OptRect pbox, dbox, bbox; + Geom::OptRect pbox, dbox, bbox; pbox = this->geometricBounds(); bbox = this->desktopVisualBounds(); - dbox = Geom::Rect::from_xywh(Geom::Point(0,0), this->document->getDimensions()); - + dbox = Geom::Rect::from_xywh(Geom::Point(0, 0), this->document->getDimensions()); + Geom::Affine const i2dt(this->i2dt_affine()); - SPStyle* style = this->style; + SPStyle *style = this->style; if (!style->fill.isNone()) { - ctx->fill (pathv, i2dt, style, pbox, dbox, bbox); + ctx->fill(pathv, i2dt, style, pbox, dbox, bbox); } if (!style->stroke.isNone()) { - ctx->stroke (pathv, i2dt, style, pbox, dbox, bbox); + ctx->stroke(pathv, i2dt, style, pbox, dbox, bbox); } /** \todo make code prettier */ // START marker - for (int i = 0; i < 2; i++) { // SP_MARKER_LOC and SP_MARKER_LOC_START - if ( this->_marker[i] ) { + for (int i = 0; i < 2; i++) { // SP_MARKER_LOC and SP_MARKER_LOC_START + if (this->_marker[i]) { Geom::Affine tr(sp_shape_marker_get_transform_at_start(pathv.begin()->front())); sp_shape_print_invoke_marker_printing(this->_marker[i], tr, style, ctx); } } - + // MID marker - for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID + for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID if (this->_marker[i]) { - for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) { + for (Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) { // START position - if ( path_it != pathv.begin() - && ! ((path_it == (pathv.end()-1)) && (path_it->size_default() == 0)) ) // if this is the last path and it is a moveto-only, there is no mid marker there + if (path_it != pathv.begin() && + !((path_it == (pathv.end() - 1)) && (path_it->size_default() == 0))) // if this is the last path and + // it is a moveto-only, there + // is no mid marker there { Geom::Affine tr(sp_shape_marker_get_transform_at_start(path_it->front())); sp_shape_print_invoke_marker_printing(this->_marker[i], tr, style, ctx); } - + // MID position - if ( path_it->size_default() > 1) { - Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve - Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve - - while (curve_it2 != path_it->end_default()) - { + if (path_it->size_default() > 1) { + Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve + Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve + + while (curve_it2 != path_it->end_default()) { /* Put marker between curve_it1 and curve_it2. * Loop to end_default (so including closing segment), because when a path is closed, * there should be a midpoint marker between last segment and closing straight line segment */ @@ -786,8 +782,8 @@ void SPShape::print(SPPrintContext* ctx) { ++curve_it2; } } - - if ( path_it != (pathv.end()-1) && !path_it->empty()) { + + if (path_it != (pathv.end() - 1) && !path_it->empty()) { Geom::Curve const &lastcurve = path_it->back_default(); Geom::Affine tr = sp_shape_marker_get_transform_at_end(lastcurve); sp_shape_print_invoke_marker_printing(this->_marker[i], tr, style, ctx); @@ -795,42 +791,42 @@ void SPShape::print(SPPrintContext* ctx) { } } } - + // END marker - if ( this->_marker[SP_MARKER_LOC_END] || this->_marker[SP_MARKER_LOC]) { + if (this->_marker[SP_MARKER_LOC_END] || this->_marker[SP_MARKER_LOC]) { /* Get reference to last curve in the path. * For moveto-only path, this returns the "closing line segment". */ Geom::Path const &path_last = pathv.back(); unsigned int index = path_last.size_default(); - + if (index > 0) { index--; } - + Geom::Curve const &lastcurve = path_last[index]; Geom::Affine tr = sp_shape_marker_get_transform_at_end(lastcurve); - for (int i = 0; i < 4; i += 3) { // SP_MARKER_LOC and SP_MARKER_LOC_END + for (int i = 0; i < 4; i += 3) { // SP_MARKER_LOC and SP_MARKER_LOC_END if (this->_marker[i]) { sp_shape_print_invoke_marker_printing(this->_marker[i], tr, style, ctx); } } } - if (add_comments) { - gchar * comment = g_strdup_printf("end '%s'", - this->defaultLabel()); - ctx->comment(comment); - g_free(comment); - } + if (add_comments) { + gchar *comment = g_strdup_printf("end '%s'", this->defaultLabel()); + ctx->comment(comment); + g_free(comment); + } } void SPShape::update_patheffect(bool write) { if (auto c_lpe = SPCurve::copy(curveForEdit())) { /* if a path has an lpeitem applied, then reset the curve to the _curve_before_lpe. - * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in shape)*/ + * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in + * shape)*/ this->setCurveInsync(c_lpe.get()); SPRoot *root = this->document->getRoot(); if (!sp_version_inside_range(root->version.inkscape, 0, 1, 0, 92)) { @@ -845,7 +841,7 @@ void SPShape::update_patheffect(bool write) this->applyToClipPath(this); this->applyToMask(this); } - } + } if (write && success) { Inkscape::XML::Node *repr = this->getRepr(); if (c_lpe != nullptr) { @@ -860,7 +856,8 @@ void SPShape::update_patheffect(bool write) } } -Inkscape::DrawingItem* SPShape::show(Inkscape::Drawing &drawing, unsigned int /*key*/, unsigned int /*flags*/) { +Inkscape::DrawingItem *SPShape::show(Inkscape::Drawing &drawing, unsigned int /*key*/, unsigned int /*flags*/) +{ // std::cout << "SPShape::show(): " << (getId()?getId():"null") << std::endl; Inkscape::DrawingShape *s = new Inkscape::DrawingShape(drawing); @@ -873,26 +870,24 @@ Inkscape::DrawingItem* SPShape::show(Inkscape::Drawing &drawing, unsigned int /* * that the appropriate marker objects are present (or absent) to * match the style. */ - for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) { - sp_shape_set_marker (this, i, this->style->marker_ptrs[i]->value()); + for (int i = 0; i < SP_MARKER_LOC_QTY; i++) { + sp_shape_set_marker(this, i, this->style->marker_ptrs[i]->value()); } if (has_markers) { /* provide key and dimension the marker views */ if (!s->key()) { - s->setKey(SPItem::display_key_new (SP_MARKER_LOC_QTY)); + s->setKey(SPItem::display_key_new(SP_MARKER_LOC_QTY)); } for (int i = 0; i < SP_MARKER_LOC_QTY; i++) { if (_marker[i]) { - sp_marker_show_dimension(_marker[i], - s->key() + i, - numberOfMarkers(i)); + sp_marker_show_dimension(_marker[i], s->key() + i, numberOfMarkers(i)); } } /* Update marker views */ - sp_shape_update_marker_view (this, s); + sp_shape_update_marker_view(this, s); this->context_style = this->style; s->setStyle(this->style, this->context_style); @@ -907,10 +902,11 @@ Inkscape::DrawingItem* SPShape::show(Inkscape::Drawing &drawing, unsigned int /* /** * Sets style, path, and paintbox. Updates marker views, including dimensions. */ -void SPShape::hide(unsigned int key) { +void SPShape::hide(unsigned int key) +{ for (int i = 0; i < SP_MARKER_LOC_QTY; ++i) { if (_marker[i]) { - for (SPItemView* v = display; v != nullptr; v = v->next) { + for (SPItemView *v = display; v != nullptr; v = v->next) { if (key == v->key) { sp_marker_hide(_marker[i], v->arenaitem->key() + i); } @@ -918,13 +914,13 @@ void SPShape::hide(unsigned int key) { } } - //SPLPEItem::onHide(key); + // SPLPEItem::onHide(key); } /** -* \param shape Shape. -* \return TRUE if the shape has any markers, or FALSE if not. -*/ + * \param shape Shape. + * \return TRUE if the shape has any markers, or FALSE if not. + */ int SPShape::hasMarkers() const { /* Note, we're ignoring 'marker' settings, which technically should apply for @@ -933,39 +929,32 @@ int SPShape::hasMarkers() const // Ignore markers for objects which are inside markers themselves. for (SPObject *parent = this->parent; parent != nullptr; parent = parent->parent) { - if (dynamic_cast<SPMarker *>(parent)) { - return 0; - } + if (dynamic_cast<SPMarker *>(parent)) { + return 0; + } } - return ( - this->_curve && - (this->_marker[SP_MARKER_LOC] || - this->_marker[SP_MARKER_LOC_START] || - this->_marker[SP_MARKER_LOC_MID] || - this->_marker[SP_MARKER_LOC_END]) - ); + return (this->_curve && (this->_marker[SP_MARKER_LOC] || this->_marker[SP_MARKER_LOC_START] || + this->_marker[SP_MARKER_LOC_MID] || this->_marker[SP_MARKER_LOC_END])); } - /** -* \param shape Shape. -* \param type Marker type (e.g. SP_MARKER_LOC_START) -* \return Number of markers that the shape has of this type. -*/ -int SPShape::numberOfMarkers(int type) const { - Geom::PathVector const & pathv = this->_curve->get_pathvector(); + * \param shape Shape. + * \param type Marker type (e.g. SP_MARKER_LOC_START) + * \return Number of markers that the shape has of this type. + */ +int SPShape::numberOfMarkers(int type) const +{ + Geom::PathVector const &pathv = this->_curve->get_pathvector(); if (pathv.size() == 0) { return 0; } - switch(type) { - - case SP_MARKER_LOC: - { - if ( this->_marker[SP_MARKER_LOC] ) { + switch (type) { + case SP_MARKER_LOC: { + if (this->_marker[SP_MARKER_LOC]) { guint n = 0; - for(const auto & path_it : pathv) { + for (const auto &path_it : pathv) { n += path_it.size_default() + 1; } return n; @@ -977,11 +966,10 @@ int SPShape::numberOfMarkers(int type) const { // there is only a start marker on the first path of a pathvector return this->_marker[SP_MARKER_LOC_START] ? 1 : 0; - case SP_MARKER_LOC_MID: - { - if ( this->_marker[SP_MARKER_LOC_MID] ) { + case SP_MARKER_LOC_MID: { + if (this->_marker[SP_MARKER_LOC_MID]) { guint n = 0; - for(const auto & path_it : pathv) { + for (const auto &path_it : pathv) { n += path_it.size_default() + 1; } n = (n > 1) ? (n - 2) : 0; // Minus the start and end marker, but never negative. @@ -992,8 +980,7 @@ int SPShape::numberOfMarkers(int type) const { } } - case SP_MARKER_LOC_END: - { + case SP_MARKER_LOC_END: { // there is only an end marker on the last path of a pathvector return this->_marker[SP_MARKER_LOC_END] ? 1 : 0; } @@ -1008,8 +995,7 @@ int SPShape::numberOfMarkers(int type) const { * releases it by calling sp_marker_hide. Also detaches signals * and unrefs the marker from the shape. */ -static void -sp_shape_marker_release (SPObject *marker, SPShape *shape) +static void sp_shape_marker_release(SPObject *marker, SPShape *shape) { SPItem *item = dynamic_cast<SPItem *>(shape); g_return_if_fail(item != nullptr); @@ -1033,8 +1019,7 @@ sp_shape_marker_release (SPObject *marker, SPShape *shape) /** * No-op. Exists for handling 'modified' messages */ -static void -sp_shape_marker_modified (SPObject */*marker*/, guint /*flags*/, SPItem */*item*/) +static void sp_shape_marker_modified(SPObject * /*marker*/, guint /*flags*/, SPItem * /*item*/) { /* I think mask does update automagically */ /* g_warning ("Item %s mask %s modified", item->getId(), mask->getId()); */ @@ -1047,8 +1032,7 @@ sp_shape_marker_modified (SPObject */*marker*/, guint /*flags*/, SPItem */*item* * registered at the given position, it is removed first. Then the * new marker is hrefed and its signals connected. */ -void -sp_shape_set_marker (SPObject *object, unsigned int key, const gchar *value) +void sp_shape_set_marker(SPObject *object, unsigned int key, const gchar *value) { SPShape *shape = dynamic_cast<SPShape *>(object); g_return_if_fail(shape != nullptr); @@ -1069,8 +1053,7 @@ sp_shape_set_marker (SPObject *object, unsigned int key, const gchar *value) /* Hide marker */ for (v = shape->display; v != nullptr; v = v->next) { - sp_marker_hide(shape->_marker[key], - v->arenaitem->key() + key); + sp_marker_hide(shape->_marker[key], v->arenaitem->key() + key); } /* Unref marker */ @@ -1080,15 +1063,18 @@ sp_shape_set_marker (SPObject *object, unsigned int key, const gchar *value) if (marker) { shape->_marker[key] = marker; shape->_marker[key]->hrefObject(object); - shape->_release_connect[key] = marker->connectRelease(sigc::bind<1>(sigc::ptr_fun(&sp_shape_marker_release), shape)); - shape->_modified_connect[key] = marker->connectModified(sigc::bind<2>(sigc::ptr_fun(&sp_shape_marker_modified), shape)); + shape->_release_connect[key] = + marker->connectRelease(sigc::bind<1>(sigc::ptr_fun(&sp_shape_marker_release), shape)); + shape->_modified_connect[key] = + marker->connectModified(sigc::bind<2>(sigc::ptr_fun(&sp_shape_marker_modified), shape)); } } } // CPPIFY: make pure virtual -void SPShape::set_shape() { - //throw; +void SPShape::set_shape() +{ + // throw; } /* Shape section */ @@ -1175,7 +1161,8 @@ SPCurve const *SPShape::curveForEdit() const return curve(); } -void SPShape::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const { +void SPShape::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const +{ if (this->_curve == nullptr) { return; } @@ -1186,31 +1173,33 @@ void SPShape::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape: return; } - Geom::Affine const i2dt (this->i2dt_affine ()); + Geom::Affine const i2dt(this->i2dt_affine()); if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_OBJECT_MIDPOINT)) { Geom::OptRect bbox = this->desktopVisualBounds(); if (bbox) { - p.emplace_back(bbox->midpoint(), Inkscape::SNAPSOURCE_OBJECT_MIDPOINT, Inkscape::SNAPTARGET_OBJECT_MIDPOINT); + p.emplace_back(bbox->midpoint(), Inkscape::SNAPSOURCE_OBJECT_MIDPOINT, + Inkscape::SNAPTARGET_OBJECT_MIDPOINT); } } - for(const auto & path_it : pathv) { + for (const auto &path_it : pathv) { if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_NODE_CUSP)) { // Add the first point of the path - p.emplace_back(path_it.initialPoint() * i2dt, Inkscape::SNAPSOURCE_NODE_CUSP, Inkscape::SNAPTARGET_NODE_CUSP); + p.emplace_back(path_it.initialPoint() * i2dt, Inkscape::SNAPSOURCE_NODE_CUSP, + Inkscape::SNAPTARGET_NODE_CUSP); } - Geom::Path::const_iterator curve_it1 = path_it.begin(); // incoming curve - Geom::Path::const_iterator curve_it2 = ++(path_it.begin()); // outgoing curve + Geom::Path::const_iterator curve_it1 = path_it.begin(); // incoming curve + Geom::Path::const_iterator curve_it2 = ++(path_it.begin()); // outgoing curve - while (curve_it1 != path_it.end_default()) - { + while (curve_it1 != path_it.end_default()) { // For each path: consider midpoints of line segments for snapping if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_LINE_MIDPOINT)) { - if (Geom::LineSegment const* line_segment = dynamic_cast<Geom::LineSegment const*>(&(*curve_it1))) { - p.emplace_back(Geom::middle_point(*line_segment) * i2dt, Inkscape::SNAPSOURCE_LINE_MIDPOINT, Inkscape::SNAPTARGET_LINE_MIDPOINT); + if (Geom::LineSegment const *line_segment = dynamic_cast<Geom::LineSegment const *>(&(*curve_it1))) { + p.emplace_back(Geom::middle_point(*line_segment) * i2dt, Inkscape::SNAPSOURCE_LINE_MIDPOINT, + Inkscape::SNAPTARGET_LINE_MIDPOINT); } } @@ -1218,7 +1207,8 @@ void SPShape::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape: if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_NODE_CUSP) && !path_it.closed()) { // Add the last point of the path, but only for open paths // (for closed paths the first and last point will coincide) - p.emplace_back((*curve_it1).finalPoint() * i2dt, Inkscape::SNAPSOURCE_NODE_CUSP, Inkscape::SNAPTARGET_NODE_CUSP); + p.emplace_back((*curve_it1).finalPoint() * i2dt, Inkscape::SNAPSOURCE_NODE_CUSP, + Inkscape::SNAPTARGET_NODE_CUSP); } } else { /* Test whether to add the node between curve_it1 and curve_it2. @@ -1226,27 +1216,29 @@ void SPShape::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape: Geom::NodeType nodetype = Geom::get_nodetype(*curve_it1, *curve_it2); - bool c1 = snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_NODE_CUSP) && (nodetype == Geom::NODE_CUSP || nodetype == Geom::NODE_NONE); - bool c2 = snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_NODE_SMOOTH) && (nodetype == Geom::NODE_SMOOTH || nodetype == Geom::NODE_SYMM); + bool c1 = snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_NODE_CUSP) && + (nodetype == Geom::NODE_CUSP || nodetype == Geom::NODE_NONE); + bool c2 = snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_NODE_SMOOTH) && + (nodetype == Geom::NODE_SMOOTH || nodetype == Geom::NODE_SYMM); if (c1 || c2) { Inkscape::SnapSourceType sst; Inkscape::SnapTargetType stt; switch (nodetype) { - case Geom::NODE_CUSP: - sst = Inkscape::SNAPSOURCE_NODE_CUSP; - stt = Inkscape::SNAPTARGET_NODE_CUSP; - break; - case Geom::NODE_SMOOTH: - case Geom::NODE_SYMM: - sst = Inkscape::SNAPSOURCE_NODE_SMOOTH; - stt = Inkscape::SNAPTARGET_NODE_SMOOTH; - break; - default: - sst = Inkscape::SNAPSOURCE_UNDEFINED; - stt = Inkscape::SNAPTARGET_UNDEFINED; - break; + case Geom::NODE_CUSP: + sst = Inkscape::SNAPSOURCE_NODE_CUSP; + stt = Inkscape::SNAPTARGET_NODE_CUSP; + break; + case Geom::NODE_SMOOTH: + case Geom::NODE_SYMM: + sst = Inkscape::SNAPSOURCE_NODE_SMOOTH; + stt = Inkscape::SNAPTARGET_NODE_SMOOTH; + break; + default: + sst = Inkscape::SNAPSOURCE_UNDEFINED; + stt = Inkscape::SNAPTARGET_UNDEFINED; + break; } p.emplace_back(curve_it1->finalPoint() * i2dt, sst, stt); @@ -1259,23 +1251,24 @@ void SPShape::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape: // Find the internal intersections of each path and consider these for snapping // (using "Method 1" as described in Inkscape::ObjectSnapper::_collectNodes()) - if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_PATH_INTERSECTION) || snapprefs->isSourceSnappable(Inkscape::SNAPSOURCE_PATH_INTERSECTION)) { + if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_PATH_INTERSECTION) || + snapprefs->isSourceSnappable(Inkscape::SNAPSOURCE_PATH_INTERSECTION)) { Geom::Crossings cs; try { cs = self_crossings(path_it); // This can be slow! if (!cs.empty()) { // There might be multiple intersections... - for (const auto & c : cs) { + for (const auto &c : cs) { Geom::Point p_ix = path_it.pointAt(c.ta); - p.emplace_back(p_ix * i2dt, Inkscape::SNAPSOURCE_PATH_INTERSECTION, Inkscape::SNAPTARGET_PATH_INTERSECTION); + p.emplace_back(p_ix * i2dt, Inkscape::SNAPSOURCE_PATH_INTERSECTION, + Inkscape::SNAPTARGET_PATH_INTERSECTION); } } } catch (Geom::RangeError &e) { // do nothing // The exception could be Geom::InfiniteSolutions: then no snappoints should be added } - } } } diff --git a/src/object/sp-shape.h b/src/object/sp-shape.h index fd39213099e7a1d9319ad808b4e339fbe8def6df..e1d3b711bcca3e84f50a7b2f1db6564cfa23a607 100644 --- a/src/object/sp-shape.h +++ b/src/object/sp-shape.h @@ -18,29 +18,31 @@ #include <2geom/forward.h> #include <cstddef> +#include <memory> #include <sigc++/connection.h> #include "sp-lpe-item.h" #include "sp-marker-loc.h" -#include <memory> - -#define SP_SHAPE(obj) (dynamic_cast<SPShape*>((SPObject*)obj)) -#define SP_IS_SHAPE(obj) (dynamic_cast<const SPShape*>((SPObject*)obj) != NULL) +#define SP_SHAPE(obj) (dynamic_cast<SPShape *>((SPObject *)obj)) +#define SP_IS_SHAPE(obj) (dynamic_cast<const SPShape *>((SPObject *)obj) != NULL) #define SP_SHAPE_WRITE_PATH (1 << 2) class SPDesktop; class SPMarker; -namespace Inkscape { class DrawingItem; } +namespace Inkscape { +class DrawingItem; +} /** * Base class for shapes, including <path> element */ -class SPShape : public SPLPEItem { +class SPShape : public SPLPEItem +{ public: - SPShape(); - ~SPShape() override; + SPShape(); + ~SPShape() override; SPCurve *curve(); SPCurve const *curve() const; @@ -59,8 +61,8 @@ public: void setCurveBeforeLPE(SPCurve const *new_curve); void setCurveBeforeLPE(std::unique_ptr<SPCurve> &&); - int hasMarkers () const; - int numberOfMarkers (int type) const; + int hasMarkers() const; + int numberOfMarkers(int type) const; // bbox cache mutable bool bbox_geom_cache_is_valid = false; @@ -76,37 +78,38 @@ protected: public: SPMarker *_marker[SP_MARKER_LOC_QTY]; - sigc::connection _release_connect [SP_MARKER_LOC_QTY]; - sigc::connection _modified_connect [SP_MARKER_LOC_QTY]; + sigc::connection _release_connect[SP_MARKER_LOC_QTY]; + sigc::connection _modified_connect[SP_MARKER_LOC_QTY]; - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void release() override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; - void set(SPAttr key, char const* value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + void set(SPAttr key, char const *value) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; - Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType bboxtype) const override; + Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType bboxtype) const override; Geom::OptRect either_bbox(Geom::Affine const &transform, SPItem::BBoxType bboxtype, bool cache_is_valid, Geom::OptRect bbox_cache, Geom::Affine const &transform_cache) const; - void print(SPPrintContext* ctx) override; + void print(SPPrintContext *ctx) override; - Inkscape::DrawingItem* show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; - void hide(unsigned int key) override; + Inkscape::DrawingItem *show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; + void hide(unsigned int key) override; - void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const override; + void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, + Inkscape::SnapPreferences const *snapprefs) const override; - virtual void set_shape(); - void update_patheffect(bool write) override; + virtual void set_shape(); + void update_patheffect(bool write) override; }; +void sp_shape_set_marker(SPObject *object, unsigned int key, const char *value); -void sp_shape_set_marker (SPObject *object, unsigned int key, const char *value); - -Geom::Affine sp_shape_marker_get_transform(Geom::Curve const & c1, Geom::Curve const & c2); -Geom::Affine sp_shape_marker_get_transform_at_start(Geom::Curve const & c); -Geom::Affine sp_shape_marker_get_transform_at_end(Geom::Curve const & c); +Geom::Affine sp_shape_marker_get_transform(Geom::Curve const &c1, Geom::Curve const &c2); +Geom::Affine sp_shape_marker_get_transform_at_start(Geom::Curve const &c); +Geom::Affine sp_shape_marker_get_transform_at_end(Geom::Curve const &c); #endif // SEEN_SP_SHAPE_H diff --git a/src/object/sp-solid-color.cpp b/src/object/sp-solid-color.cpp index 3682e52fc8f1d1c5f6bb0ce7ca5f6bf917777f20..f2486b7f69e46fe6ced2aff75ab799508824c7d8 100644 --- a/src/object/sp-solid-color.cpp +++ b/src/object/sp-solid-color.cpp @@ -9,23 +9,24 @@ * * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cairo.h> - #include "sp-solid-color.h" +#include <cairo.h> + #include "attributes.h" #include "style.h" - /* * Solid Color */ -SPSolidColor::SPSolidColor() : SPPaintServer() { -} +SPSolidColor::SPSolidColor() + : SPPaintServer() +{} SPSolidColor::~SPSolidColor() = default; -void SPSolidColor::build(SPDocument* doc, Inkscape::XML::Node* repr) { +void SPSolidColor::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ SPPaintServer::build(doc, repr); this->readAttr(SPAttr::STYLE); @@ -37,8 +38,8 @@ void SPSolidColor::build(SPDocument* doc, Inkscape::XML::Node* repr) { * Virtual build: set solidcolor attributes from its associated XML node. */ -void SPSolidColor::set(SPAttr key, const gchar* value) { - +void SPSolidColor::set(SPAttr key, const gchar *value) +{ if (SP_ATTRIBUTE_IS_CSS(key)) { style->clear(key); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); @@ -51,7 +52,8 @@ void SPSolidColor::set(SPAttr key, const gchar* value) { * Virtual set: set attribute to value. */ -Inkscape::XML::Node* SPSolidColor::write(Inkscape::XML::Document* xml_doc, Inkscape::XML::Node* repr, guint flags) { +Inkscape::XML::Node *SPSolidColor::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:solidColor"); } @@ -61,15 +63,15 @@ Inkscape::XML::Node* SPSolidColor::write(Inkscape::XML::Document* xml_doc, Inksc return repr; } -cairo_pattern_t* SPSolidColor::pattern_new(cairo_t * /*ct*/, Geom::OptRect const & /*bbox*/, double opacity) { - +cairo_pattern_t *SPSolidColor::pattern_new(cairo_t * /*ct*/, Geom::OptRect const & /*bbox*/, double opacity) +{ auto *c = &(this->style->solid_color); - cairo_pattern_t *cp = cairo_pattern_create_rgba ( c->value.color.v.c[0], c->value.color.v.c[1], c->value.color.v.c[2], SP_SCALE24_TO_FLOAT(this->style->solid_opacity.value) * opacity ); + cairo_pattern_t *cp = cairo_pattern_create_rgba(c->value.color.v.c[0], c->value.color.v.c[1], c->value.color.v.c[2], + SP_SCALE24_TO_FLOAT(this->style->solid_opacity.value) * opacity); return cp; } - /** * Virtual write: write object attributes to repr. */ diff --git a/src/object/sp-solid-color.h b/src/object/sp-solid-color.h index de30a5986f86700fe30aba9634b7e6e0d307d39e..e377ec569e3ebb0f953844a4a0bb95a1d2d2bd3f 100644 --- a/src/object/sp-solid-color.h +++ b/src/object/sp-solid-color.h @@ -18,21 +18,22 @@ typedef struct _cairo cairo_t; typedef struct _cairo_pattern cairo_pattern_t; -#define SP_SOLIDCOLOR(obj) (dynamic_cast<SPSolidColor*>((SPObject*)obj)) -#define SP_IS_SOLIDCOLOR(obj) (dynamic_cast<const SPSolidColor*>((SPObject*)obj) != NULL) +#define SP_SOLIDCOLOR(obj) (dynamic_cast<SPSolidColor *>((SPObject *)obj)) +#define SP_IS_SOLIDCOLOR(obj) (dynamic_cast<const SPSolidColor *>((SPObject *)obj) != NULL) /** Gradient SolidColor. */ -class SPSolidColor : public SPPaintServer { +class SPSolidColor : public SPPaintServer +{ public: SPSolidColor(); ~SPSolidColor() override; - cairo_pattern_t* pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) override; + cairo_pattern_t *pattern_new(cairo_t *ct, Geom::OptRect const &bbox, double opacity) override; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void set(SPAttr key, char const* value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void set(SPAttr key, char const *value) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #endif /* !SEEN_SP_SOLIDCOLOR_H */ diff --git a/src/object/sp-spiral.cpp b/src/object/sp-spiral.cpp index e300295fb43b40b557e544861df22e636dfde016..ee4406d32ddf019a066fb63c250d6348f3ef32fa 100644 --- a/src/object/sp-spiral.cpp +++ b/src/object/sp-spiral.cpp @@ -15,17 +15,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "live_effects/effect.h" -#include "svg/svg.h" -#include "attributes.h" +#include "sp-spiral.h" + #include <2geom/bezier-utils.h> #include <2geom/pathvector.h> -#include "display/curve.h" #include <glibmm/i18n.h> -#include "xml/repr.h" -#include "document.h" -#include "sp-spiral.h" +#include "attributes.h" +#include "display/curve.h" +#include "document.h" +#include "live_effects/effect.h" +#include "svg/svg.h" +#include "xml/repr.h" SPSpiral::SPSpiral() : SPShape() @@ -36,12 +37,12 @@ SPSpiral::SPSpiral() , rad(1) , arg(0) , t0(0) -{ -} +{} SPSpiral::~SPSpiral() = default; -void SPSpiral::build(SPDocument * document, Inkscape::XML::Node * repr) { +void SPSpiral::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPShape::build(document, repr); this->readAttr(SPAttr::SODIPODI_CX); @@ -53,7 +54,8 @@ void SPSpiral::build(SPDocument * document, Inkscape::XML::Node * repr) { this->readAttr(SPAttr::SODIPODI_T0); } -Inkscape::XML::Node* SPSpiral::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPSpiral::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:path"); } @@ -72,13 +74,13 @@ Inkscape::XML::Node* SPSpiral::write(Inkscape::XML::Document *xml_doc, Inkscape: sp_repr_set_svg_double(repr, "sodipodi:t0", this->t0); } - // make sure the curve is rebuilt with all up-to-date parameters - this->set_shape(); + // make sure the curve is rebuilt with all up-to-date parameters + this->set_shape(); // Nulls might be possible if this called iteratively if (!this->_curve) { - //g_warning("sp_spiral_write(): No path to copy\n"); - return nullptr; + // g_warning("sp_spiral_write(): No path to copy\n"); + return nullptr; } char *d = sp_svg_write_path(this->_curve->get_pathvector()); @@ -90,105 +92,107 @@ Inkscape::XML::Node* SPSpiral::write(Inkscape::XML::Document *xml_doc, Inkscape: return repr; } -void SPSpiral::set(SPAttr key, gchar const* value) { +void SPSpiral::set(SPAttr key, gchar const *value) +{ /// \todo fixme: we should really collect updates switch (key) { - case SPAttr::SODIPODI_CX: - if (!sp_svg_length_read_computed_absolute (value, &this->cx)) { - this->cx = 0.0; - } - - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::SODIPODI_CY: - if (!sp_svg_length_read_computed_absolute (value, &this->cy)) { - this->cy = 0.0; - } - - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::SODIPODI_EXPANSION: - if (value) { - /** \todo - * FIXME: check that value looks like a (finite) - * number. Create a routine that uses strtod, and - * accepts a default value (if strtod finds an error). - * N.B. atof/sscanf/strtod consider "nan" and "inf" - * to be valid numbers. - */ - this->exp = g_ascii_strtod (value, nullptr); - this->exp = CLAMP (this->exp, 0.0, 1000.0); - } else { - this->exp = 1.0; - } - - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::SODIPODI_REVOLUTION: - if (value) { - this->revo = g_ascii_strtod (value, nullptr); - this->revo = CLAMP (this->revo, 0.05, 1024.0); - } else { - this->revo = 3.0; - } - - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::SODIPODI_RADIUS: - if (!sp_svg_length_read_computed_absolute (value, &this->rad)) { - this->rad = MAX (this->rad, 0.001); - } - - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::SODIPODI_ARGUMENT: - if (value) { - this->arg = g_ascii_strtod (value, nullptr); - /** \todo - * FIXME: We still need some bounds on arg, for - * numerical reasons. E.g., we don't want inf or NaN, - * nor near-infinite numbers. I'm inclined to take - * modulo 2*pi. If so, then change the knot editors, - * which use atan2 - revo*2*pi, which typically - * results in very negative arg. - */ - } else { - this->arg = 0.0; - } - - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; - - case SPAttr::SODIPODI_T0: - if (value) { - this->t0 = g_ascii_strtod (value, nullptr); - this->t0 = CLAMP (this->t0, 0.0, 0.999); - /** \todo - * Have shared constants for the allowable bounds for - * attributes. There was a bug here where we used -1.0 - * as the minimum (which leads to NaN via, e.g., - * pow(-1.0, 0.5); see sp_spiral_get_xy for - * requirements. - */ - } else { - this->t0 = 0.0; - } + case SPAttr::SODIPODI_CX: + if (!sp_svg_length_read_computed_absolute(value, &this->cx)) { + this->cx = 0.0; + } + + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::SODIPODI_CY: + if (!sp_svg_length_read_computed_absolute(value, &this->cy)) { + this->cy = 0.0; + } + + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::SODIPODI_EXPANSION: + if (value) { + /** \todo + * FIXME: check that value looks like a (finite) + * number. Create a routine that uses strtod, and + * accepts a default value (if strtod finds an error). + * N.B. atof/sscanf/strtod consider "nan" and "inf" + * to be valid numbers. + */ + this->exp = g_ascii_strtod(value, nullptr); + this->exp = CLAMP(this->exp, 0.0, 1000.0); + } else { + this->exp = 1.0; + } + + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::SODIPODI_REVOLUTION: + if (value) { + this->revo = g_ascii_strtod(value, nullptr); + this->revo = CLAMP(this->revo, 0.05, 1024.0); + } else { + this->revo = 3.0; + } + + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::SODIPODI_RADIUS: + if (!sp_svg_length_read_computed_absolute(value, &this->rad)) { + this->rad = MAX(this->rad, 0.001); + } + + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::SODIPODI_ARGUMENT: + if (value) { + this->arg = g_ascii_strtod(value, nullptr); + /** \todo + * FIXME: We still need some bounds on arg, for + * numerical reasons. E.g., we don't want inf or NaN, + * nor near-infinite numbers. I'm inclined to take + * modulo 2*pi. If so, then change the knot editors, + * which use atan2 - revo*2*pi, which typically + * results in very negative arg. + */ + } else { + this->arg = 0.0; + } + + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; + + case SPAttr::SODIPODI_T0: + if (value) { + this->t0 = g_ascii_strtod(value, nullptr); + this->t0 = CLAMP(this->t0, 0.0, 0.999); + /** \todo + * Have shared constants for the allowable bounds for + * attributes. There was a bug here where we used -1.0 + * as the minimum (which leads to NaN via, e.g., + * pow(-1.0, 0.5); see sp_spiral_get_xy for + * requirements. + */ + } else { + this->t0 = 0.0; + } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - default: - SPShape::set(key, value); - break; + default: + SPShape::set(key, value); + break; } } -void SPSpiral::update(SPCtx *ctx, guint flags) { +void SPSpiral::update(SPCtx *ctx, guint flags) +{ if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { this->set_shape(); } @@ -196,14 +200,16 @@ void SPSpiral::update(SPCtx *ctx, guint flags) { SPShape::update(ctx, flags); } -const char* SPSpiral::displayName() const { +const char *SPSpiral::displayName() const +{ return _("Spiral"); } -gchar* SPSpiral::description() const { +gchar *SPSpiral::description() const +{ // TRANSLATORS: since turn count isn't an integer, please adjust the // string as needed to deal with an localized plural forms. - return g_strdup_printf (_("with %3f turns"), this->revo); + return g_strdup_printf(_("with %3f turns"), this->revo); } /** @@ -213,13 +219,15 @@ gchar* SPSpiral::description() const { * \pre is_unit_vector(*hat1). * \post is_unit_vector(*hat2). **/ -void SPSpiral::fitAndDraw(SPCurve* c, double dstep, Geom::Point darray[], Geom::Point const& hat1, Geom::Point& hat2, double* t) const { -#define BEZIER_SIZE 4 +void SPSpiral::fitAndDraw(SPCurve *c, double dstep, Geom::Point darray[], Geom::Point const &hat1, Geom::Point &hat2, + double *t) const +{ +#define BEZIER_SIZE 4 #define FITTING_MAX_BEZIERS 4 #define BEZIER_LENGTH (BEZIER_SIZE * FITTING_MAX_BEZIERS) - g_assert (dstep > 0); - g_assert (is_unit_vector (hat1)); + g_assert(dstep > 0); + g_assert(is_unit_vector(hat1)); Geom::Point bezier[BEZIER_LENGTH]; double d; @@ -234,21 +242,21 @@ void SPSpiral::fitAndDraw(SPCurve* c, double dstep, Geom::Point darray[], Geom:: i--; d += dstep; /** We mustn't increase dstep for subsequent values of - * i: for large spiral.exp values, rate of growth - * increases very rapidly. - */ - /** \todo - * Get the function itself to decide what value of d - * to use next: ensure that we move at least 0.25 * - * stroke width, for example. The derivative (as used - * for get_tangent before normalization) would be - * useful for estimating the appropriate d value. Or - * perhaps just start with a small dstep and scale by - * some small number until we move >= 0.25 * - * stroke_width. Must revert to the original dstep - * value for next iteration to avoid the problem - * mentioned above. - */ + * i: for large spiral.exp values, rate of growth + * increases very rapidly. + */ + /** \todo + * Get the function itself to decide what value of d + * to use next: ensure that we move at least 0.25 * + * stroke width, for example. The derivative (as used + * for get_tangent before normalization) would be + * useful for estimating the appropriate d value. Or + * perhaps just start with a small dstep and scale by + * some small number until we move >= 0.25 * + * stroke_width. Must revert to the original dstep + * value for next iteration to avoid the problem + * mentioned above. + */ } } @@ -258,30 +266,26 @@ void SPSpiral::fitAndDraw(SPCurve* c, double dstep, Geom::Point darray[], Geom:: hat2 = -this->getTangent(next_t); /** \todo - * We should use better algorithm to specify maximum error. - */ - depth = Geom::bezier_fit_cubic_full (bezier, nullptr, darray, SAMPLE_SIZE, - hat1, hat2, - SPIRAL_TOLERANCE*SPIRAL_TOLERANCE, - FITTING_MAX_BEZIERS); + * We should use better algorithm to specify maximum error. + */ + depth = Geom::bezier_fit_cubic_full(bezier, nullptr, darray, SAMPLE_SIZE, hat1, hat2, + SPIRAL_TOLERANCE * SPIRAL_TOLERANCE, FITTING_MAX_BEZIERS); g_assert(depth * BEZIER_SIZE <= gint(G_N_ELEMENTS(bezier))); #ifdef SPIRAL_DEBUG if (*t == spiral->t0 || *t == 1.0) - g_print ("[%s] depth=%d, dstep=%g, t0=%g, t=%g, arg=%g\n", - debug_state, depth, dstep, spiral->t0, *t, spiral->arg); + g_print("[%s] depth=%d, dstep=%g, t0=%g, t=%g, arg=%g\n", debug_state, depth, dstep, spiral->t0, *t, + spiral->arg); #endif if (depth != -1) { - for (i = 0; i < 4*depth; i += 4) { - c->curveto(bezier[i + 1], - bezier[i + 2], - bezier[i + 3]); + for (i = 0; i < 4 * depth; i += 4) { + c->curveto(bezier[i + 1], bezier[i + 2], bezier[i + 3]); } } else { #ifdef SPIRAL_VERBOSE - g_print ("cant_fit_cubic: t=%g\n", *t); + g_print("cant_fit_cubic: t=%g\n", *t); #endif for (i = 1; i < SAMPLE_SIZE; i++) c->lineto(darray[i]); @@ -289,12 +293,14 @@ void SPSpiral::fitAndDraw(SPCurve* c, double dstep, Geom::Point darray[], Geom:: *t = next_t; - g_assert (is_unit_vector (hat2)); + g_assert(is_unit_vector(hat2)); } -void SPSpiral::set_shape() { +void SPSpiral::set_shape() +{ if (hasBrokenPathEffect()) { - g_warning ("The spiral shape has unknown LPE on it! Convert to path to make it editable preserving the appearance; editing it as spiral will remove the bad LPE"); + g_warning("The spiral shape has unknown LPE on it! Convert to path to make it editable preserving the " + "appearance; editing it as spiral will remove the bad LPE"); if (this->getRepr()->attribute("d")) { // unconditionally read the curve from d, if any, to preserve appearance @@ -313,14 +319,8 @@ void SPSpiral::set_shape() { auto c = std::make_unique<SPCurve>(); #ifdef SPIRAL_VERBOSE - g_print ("cx=%g, cy=%g, exp=%g, revo=%g, rad=%g, arg=%g, t0=%g\n", - this->cx, - this->cy, - this->exp, - this->revo, - this->rad, - this->arg, - this->t0); + g_print("cx=%g, cy=%g, exp=%g, revo=%g, rad=%g, arg=%g, t0=%g\n", this->cx, this->cy, this->exp, this->revo, + this->rad, this->arg, this->t0); #endif /* Initial moveto. */ @@ -344,7 +344,8 @@ void SPSpiral::set_shape() { } /* Reset the shape's curve to the "original_curve" - * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in shape)*/ + * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in + * shape)*/ auto const before = this->curveBeforeLPE(); if (before && before->get_pathvector() != c->get_pathvector()) { @@ -365,23 +366,26 @@ void SPSpiral::set_shape() { /** * Set spiral properties and update display. */ -void SPSpiral::setPosition(gdouble cx, gdouble cy, gdouble exp, gdouble revo, gdouble rad, gdouble arg, gdouble t0) { +void SPSpiral::setPosition(gdouble cx, gdouble cy, gdouble exp, gdouble revo, gdouble rad, gdouble arg, gdouble t0) +{ /** \todo - * Consider applying CLAMP or adding in-bounds assertions for - * some of these parameters. - */ - this->cx = cx; - this->cy = cy; - this->exp = exp; - this->revo = revo; - this->rad = MAX (rad, 0.0); - this->arg = arg; - this->t0 = CLAMP(t0, 0.0, 0.999); + * Consider applying CLAMP or adding in-bounds assertions for + * some of these parameters. + */ + this->cx = cx; + this->cy = cy; + this->exp = exp; + this->revo = revo; + this->rad = MAX(rad, 0.0); + this->arg = arg; + this->t0 = CLAMP(t0, 0.0, 0.999); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void SPSpiral::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const { +void SPSpiral::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, + Inkscape::SnapPreferences const *snapprefs) const +{ // We will determine the spiral's midpoint ourselves, instead of trusting on the base class // Therefore snapping to object midpoints is temporarily disabled Inkscape::SnapPreferences local_snapprefs = *snapprefs; @@ -390,9 +394,10 @@ void SPSpiral::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape SPShape::snappoints(p, &local_snapprefs); if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_OBJECT_MIDPOINT)) { - Geom::Affine const i2dt (this->i2dt_affine ()); + Geom::Affine const i2dt(this->i2dt_affine()); - p.emplace_back(Geom::Point(this->cx, this->cy) * i2dt, Inkscape::SNAPSOURCE_OBJECT_MIDPOINT, Inkscape::SNAPTARGET_OBJECT_MIDPOINT); + p.emplace_back(Geom::Point(this->cx, this->cy) * i2dt, Inkscape::SNAPSOURCE_OBJECT_MIDPOINT, + Inkscape::SNAPTARGET_OBJECT_MIDPOINT); // This point is the start-point of the spiral, which is also returned when _snap_to_itemnode has been set // in the object snapper. In that case we will get a duplicate! } @@ -411,7 +416,7 @@ Geom::Affine SPSpiral::set_transform(Geom::Affine const &xform) return xform; } /* Calculate spiral start in parent coords. */ - Geom::Point pos( Geom::Point(this->cx, this->cy) * xform ); + Geom::Point pos(Geom::Point(this->cx, this->cy) * xform); /* This function takes care of translation and scaling, we return whatever parts we can't handle. */ @@ -450,7 +455,8 @@ Geom::Affine SPSpiral::set_transform(Geom::Affine const &xform) return ret; } -void SPSpiral::update_patheffect(bool write) { +void SPSpiral::update_patheffect(bool write) +{ SPShape::update_patheffect(write); } @@ -462,12 +468,13 @@ void SPSpiral::update_patheffect(bool write) { * than 1.0, though some callers go slightly beyond 1.0 for curve-fitting * purposes.) */ -Geom::Point SPSpiral::getXY(gdouble t) const { - g_assert (this->exp >= 0.0); +Geom::Point SPSpiral::getXY(gdouble t) const +{ + g_assert(this->exp >= 0.0); /* Otherwise we get NaN for t==0. */ - g_assert (this->exp <= 1000.0); + g_assert(this->exp <= 1000.0); /* Anything much more results in infinities. Even allowing 1000 is somewhat overkill. */ - g_assert (t >= 0.0); + g_assert(t >= 0.0); /* Any callers passing -ve t will have a bug for non-integral values of exp. */ double const rad = this->rad * pow(t, (double)this->exp); @@ -476,7 +483,6 @@ Geom::Point SPSpiral::getXY(gdouble t) const { return Geom::Point(rad * cos(arg) + this->cx, rad * sin(arg) + this->cy); } - /** * Returns the derivative of sp_spiral_get_xy with respect to t, * scaled to a unit vector. @@ -486,11 +492,12 @@ Geom::Point SPSpiral::getXY(gdouble t) const { * \pre p != NULL. * \post is_unit_vector(*p). */ -Geom::Point SPSpiral::getTangent(gdouble t) const { +Geom::Point SPSpiral::getTangent(gdouble t) const +{ Geom::Point ret(1.0, 0.0); - g_assert (t >= 0.0); - g_assert (this->exp >= 0.0); + g_assert(t >= 0.0); + g_assert(this->exp >= 0.0); /* See above for comments on these assertions. */ double const t_scaled = 2.0 * M_PI * this->revo * t; @@ -504,22 +511,21 @@ Geom::Point SPSpiral::getTangent(gdouble t) const { ret = Geom::Point(c, s); } else { Geom::Point unrotated(this->exp, t_scaled); - double const s_len = L2 (unrotated); - g_assert (s_len != 0); + double const s_len = L2(unrotated); + g_assert(s_len != 0); /** \todo - * Check that this isn't being too hopeful of the hypot - * function. E.g. test with numbers around 2**-1070 - * (denormalized numbers), preferably on a few different - * platforms. However, njh says that the usual implementation - * does handle both very big and very small numbers. - */ + * Check that this isn't being too hopeful of the hypot + * function. E.g. test with numbers around 2**-1070 + * (denormalized numbers), preferably on a few different + * platforms. However, njh says that the usual implementation + * does handle both very big and very small numbers. + */ unrotated /= s_len; /* ret = spiral->exp * (c, s) + t_scaled * (-s, c); alternatively ret = (spiral->exp, t_scaled) * (( c, s), (-s, c)).*/ - ret = Geom::Point(dot(unrotated, Geom::Point(c, -s)), - dot(unrotated, Geom::Point(s, c))); + ret = Geom::Point(dot(unrotated, Geom::Point(c, -s)), dot(unrotated, Geom::Point(s, c))); /* ret should already be approximately normalized: the matrix ((c, -s), (s, c)) is orthogonal (it just rotates by arg), and unrotated has been normalized, @@ -527,22 +533,23 @@ Geom::Point SPSpiral::getTangent(gdouble t) const { error in the above matrix multiplication. */ /** \todo - * I haven't checked how important it is for ret to be very - * near unit length; we could get rid of the below. - */ + * I haven't checked how important it is for ret to be very + * near unit length; we could get rid of the below. + */ ret.normalize(); /* Proof that ret length is non-zero: see above. (Should be near 1.) */ } - g_assert (is_unit_vector(ret)); + g_assert(is_unit_vector(ret)); return ret; } /** * Compute rad and/or arg for point on spiral. */ -void SPSpiral::getPolar(gdouble t, gdouble* rad, gdouble* arg) const { +void SPSpiral::getPolar(gdouble t, gdouble *rad, gdouble *arg) const +{ if (rad) { *rad = this->rad * pow(t, (double)this->exp); } @@ -555,7 +562,8 @@ void SPSpiral::getPolar(gdouble t, gdouble* rad, gdouble* arg) const { /** * Return true if spiral has properties that make it invalid. */ -bool SPSpiral::isInvalid() const { +bool SPSpiral::isInvalid() const +{ gdouble rad; this->getPolar(0.0, &rad, nullptr); diff --git a/src/object/sp-spiral.h b/src/object/sp-spiral.h index 34f2f104061c6b20113b2c85c39cdd85c8674f79..305da4c77d57fb0a3e065e23e063388dc291cb3c 100644 --- a/src/object/sp-spiral.h +++ b/src/object/sp-spiral.h @@ -16,17 +16,16 @@ #define noSPIRAL_VERBOSE -#define SP_EPSILON 1e-5 -#define SP_EPSILON_2 (SP_EPSILON * SP_EPSILON) -#define SP_HUGE 1e5 +#define SP_EPSILON 1e-5 +#define SP_EPSILON_2 (SP_EPSILON * SP_EPSILON) +#define SP_HUGE 1e5 #define SPIRAL_TOLERANCE 3.0 -#define SAMPLE_STEP (1.0/4.0) ///< step per 2PI -#define SAMPLE_SIZE 8 ///< sample size per one bezier +#define SAMPLE_STEP (1.0 / 4.0) ///< step per 2PI +#define SAMPLE_SIZE 8 ///< sample size per one bezier - -#define SP_SPIRAL(obj) (dynamic_cast<SPSpiral*>((SPObject*)obj)) -#define SP_IS_SPIRAL(obj) (dynamic_cast<const SPSpiral*>((SPObject*)obj) != NULL) +#define SP_SPIRAL(obj) (dynamic_cast<SPSpiral *>((SPObject *)obj)) +#define SP_IS_SPIRAL(obj) (dynamic_cast<const SPSpiral *>((SPObject *)obj) != NULL) /** * A spiral Shape. @@ -35,47 +34,51 @@ * \verbatim x(t) = rad * t^exp cos(2 * Pi * revo*t + arg) + cx y(t) = rad * t^exp sin(2 * Pi * revo*t + arg) + cy \endverbatim - * where spiral curve is drawn for {t | t0 <= t <= 1}. The rad and arg - * parameters can also be represented by transformation. + * where spiral curve is drawn for {t | t0 <= t <= 1}. The rad and arg + * parameters can also be represented by transformation. * * \todo Should I remove these attributes? */ -class SPSpiral : public SPShape { +class SPSpiral : public SPShape +{ public: - SPSpiral(); - ~SPSpiral() override; + SPSpiral(); + ~SPSpiral() override; - float cx, cy; - float exp; ///< Spiral expansion factor - float revo; ///< Spiral revolution factor - float rad; ///< Spiral radius - float arg; ///< Spiral argument - float t0; + float cx, cy; + float exp; ///< Spiral expansion factor + float revo; ///< Spiral revolution factor + float rad; ///< Spiral radius + float arg; ///< Spiral argument + float t0; - /* Lowlevel interface */ - void setPosition(double cx, double cy, double exp, double revo, double rad, double arg, double t0); - Geom::Affine set_transform(Geom::Affine const& xform) override; + /* Lowlevel interface */ + void setPosition(double cx, double cy, double exp, double revo, double rad, double arg, double t0); + Geom::Affine set_transform(Geom::Affine const &xform) override; - Geom::Point getXY(double t) const; + Geom::Point getXY(double t) const; - void getPolar(double t, double* rad, double* arg) const; + void getPolar(double t, double *rad, double *arg) const; - bool isInvalid() const; + bool isInvalid() const; - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - void update(SPCtx *ctx, unsigned int flags) override; - void set(SPAttr key, char const* value) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; + void set(SPAttr key, char const *value) override; - void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const override; - const char* displayName() const override; - char* description() const override; + void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, + Inkscape::SnapPreferences const *snapprefs) const override; + const char *displayName() const override; + char *description() const override; void update_patheffect(bool write) override; - void set_shape() override; + void set_shape() override; private: - Geom::Point getTangent(double t) const; - void fitAndDraw(SPCurve* c, double dstep, Geom::Point darray[], Geom::Point const& hat1, Geom::Point& hat2, double* t) const; + Geom::Point getTangent(double t) const; + void fitAndDraw(SPCurve *c, double dstep, Geom::Point darray[], Geom::Point const &hat1, Geom::Point &hat2, + double *t) const; }; #endif // SEEN_SP_SPIRAL_H diff --git a/src/object/sp-star.cpp b/src/object/sp-star.cpp index 404220df0cbfd1f6c76b41f55048163d817c8217..b7f8bb486acd164e53d44edcb2a6026aae8b2dac 100644 --- a/src/object/sp-star.cpp +++ b/src/object/sp-star.cpp @@ -14,36 +14,38 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-star.h" + #include <cstring> -#include <string> #include <glib.h> -#include "live_effects/effect.h" +#include <glibmm/i18n.h> +#include <string> -#include "svg/svg.h" #include "attributes.h" #include "display/curve.h" -#include "xml/repr.h" #include "document.h" +#include "live_effects/effect.h" +#include "svg/svg.h" +#include "xml/repr.h" -#include "sp-star.h" -#include <glibmm/i18n.h> - -SPStar::SPStar() : SPPolygon() , - sides(5), - center(0, 0), - flatsided(false), - rounded(0.0), - randomized(0.0) +SPStar::SPStar() + : SPPolygon() + , sides(5) + , center(0, 0) + , flatsided(false) + , rounded(0.0) + , randomized(0.0) { - this->r[0] = 1.0; - this->r[1] = 0.001; - this->arg[0] = this->arg[1] = 0.0; + this->r[0] = 1.0; + this->r[1] = 0.001; + this->arg[0] = this->arg[1] = 0.0; } SPStar::~SPStar() = default; -void SPStar::build(SPDocument * document, Inkscape::XML::Node * repr) { - // CPPIFY: see header file +void SPStar::build(SPDocument *document, Inkscape::XML::Node *repr) +{ + // CPPIFY: see header file SPShape::build(document, repr); this->readAttr(SPAttr::SODIPODI_CX); @@ -58,7 +60,8 @@ void SPStar::build(SPDocument * document, Inkscape::XML::Node * repr) { this->readAttr(SPAttr::INKSCAPE_RANDOMIZED); } -Inkscape::XML::Node* SPStar::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPStar::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:path"); } @@ -66,7 +69,7 @@ Inkscape::XML::Node* SPStar::write(Inkscape::XML::Document *xml_doc, Inkscape::X if (flags & SP_OBJECT_WRITE_EXT) { repr->setAttribute("sodipodi:type", "star"); sp_repr_set_boolean(repr, "inkscape:flatsided", this->flatsided); - sp_repr_set_int (repr, "sodipodi:sides", this->sides); + sp_repr_set_int(repr, "sodipodi:sides", this->sides); sp_repr_set_svg_double(repr, "sodipodi:cx", this->center[Geom::X]); sp_repr_set_svg_double(repr, "sodipodi:cy", this->center[Geom::Y]); sp_repr_set_svg_double(repr, "sodipodi:r1", this->r[0]); @@ -79,7 +82,7 @@ Inkscape::XML::Node* SPStar::write(Inkscape::XML::Document *xml_doc, Inkscape::X this->set_shape(); if (this->_curve) { - char *d = sp_svg_write_path (this->_curve->get_pathvector()); + char *d = sp_svg_write_path(this->_curve->get_pathvector()); repr->setAttribute("d", d); g_free(d); } else { @@ -91,130 +94,121 @@ Inkscape::XML::Node* SPStar::write(Inkscape::XML::Document *xml_doc, Inkscape::X return repr; } -void SPStar::set(SPAttr key, const gchar* value) { +void SPStar::set(SPAttr key, const gchar *value) +{ SVGLength::Unit unit; /* fixme: we should really collect updates */ switch (key) { - case SPAttr::SODIPODI_SIDES: - if (value) { - this->sides = atoi (value); - this->sides = CLAMP(this->sides, this->flatsided ? 3 : 2, 1024); - } else { - this->sides = 5; - } + case SPAttr::SODIPODI_SIDES: + if (value) { + this->sides = atoi(value); + this->sides = CLAMP(this->sides, this->flatsided ? 3 : 2, 1024); + } else { + this->sides = 5; + } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::SODIPODI_CX: - if (!sp_svg_length_read_ldd (value, &unit, nullptr, &this->center[Geom::X]) || - (unit == SVGLength::EM) || - (unit == SVGLength::EX) || - (unit == SVGLength::PERCENT)) { - this->center[Geom::X] = 0.0; - } + case SPAttr::SODIPODI_CX: + if (!sp_svg_length_read_ldd(value, &unit, nullptr, &this->center[Geom::X]) || (unit == SVGLength::EM) || + (unit == SVGLength::EX) || (unit == SVGLength::PERCENT)) { + this->center[Geom::X] = 0.0; + } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::SODIPODI_CY: - if (!sp_svg_length_read_ldd (value, &unit, nullptr, &this->center[Geom::Y]) || - (unit == SVGLength::EM) || - (unit == SVGLength::EX) || - (unit == SVGLength::PERCENT)) { - this->center[Geom::Y] = 0.0; - } + case SPAttr::SODIPODI_CY: + if (!sp_svg_length_read_ldd(value, &unit, nullptr, &this->center[Geom::Y]) || (unit == SVGLength::EM) || + (unit == SVGLength::EX) || (unit == SVGLength::PERCENT)) { + this->center[Geom::Y] = 0.0; + } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::SODIPODI_R1: - if (!sp_svg_length_read_ldd (value, &unit, nullptr, &this->r[0]) || - (unit == SVGLength::EM) || - (unit == SVGLength::EX) || - (unit == SVGLength::PERCENT)) { - this->r[0] = 1.0; - } + case SPAttr::SODIPODI_R1: + if (!sp_svg_length_read_ldd(value, &unit, nullptr, &this->r[0]) || (unit == SVGLength::EM) || + (unit == SVGLength::EX) || (unit == SVGLength::PERCENT)) { + this->r[0] = 1.0; + } - /* fixme: Need CLAMP (Lauris) */ - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + /* fixme: Need CLAMP (Lauris) */ + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::SODIPODI_R2: - if (!sp_svg_length_read_ldd (value, &unit, nullptr, &this->r[1]) || - (unit == SVGLength::EM) || - (unit == SVGLength::EX) || - (unit == SVGLength::PERCENT)) { - this->r[1] = 0.0; - } + case SPAttr::SODIPODI_R2: + if (!sp_svg_length_read_ldd(value, &unit, nullptr, &this->r[1]) || (unit == SVGLength::EM) || + (unit == SVGLength::EX) || (unit == SVGLength::PERCENT)) { + this->r[1] = 0.0; + } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - return; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + return; - case SPAttr::SODIPODI_ARG1: - if (value) { - this->arg[0] = g_ascii_strtod (value, nullptr); - } else { - this->arg[0] = 0.0; - } + case SPAttr::SODIPODI_ARG1: + if (value) { + this->arg[0] = g_ascii_strtod(value, nullptr); + } else { + this->arg[0] = 0.0; + } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::SODIPODI_ARG2: - if (value) { - this->arg[1] = g_ascii_strtod (value, nullptr); - } else { - this->arg[1] = 0.0; - } + case SPAttr::SODIPODI_ARG2: + if (value) { + this->arg[1] = g_ascii_strtod(value, nullptr); + } else { + this->arg[1] = 0.0; + } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::INKSCAPE_FLATSIDED: - if (value && !strcmp(value, "true")) { - this->flatsided = true; - this->sides = MAX(this->sides, 3); - } else { - this->flatsided = false; - } + case SPAttr::INKSCAPE_FLATSIDED: + if (value && !strcmp(value, "true")) { + this->flatsided = true; + this->sides = MAX(this->sides, 3); + } else { + this->flatsided = false; + } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::INKSCAPE_ROUNDED: - if (value) { - this->rounded = g_ascii_strtod (value, nullptr); - } else { - this->rounded = 0.0; - } + case SPAttr::INKSCAPE_ROUNDED: + if (value) { + this->rounded = g_ascii_strtod(value, nullptr); + } else { + this->rounded = 0.0; + } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - case SPAttr::INKSCAPE_RANDOMIZED: - if (value) { - this->randomized = g_ascii_strtod (value, nullptr); - } else { - this->randomized = 0.0; - } + case SPAttr::INKSCAPE_RANDOMIZED: + if (value) { + this->randomized = g_ascii_strtod(value, nullptr); + } else { + this->randomized = 0.0; + } - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - break; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + break; - default: - // CPPIFY: see header file - SPShape::set(key, value); - break; + default: + // CPPIFY: see header file + SPShape::set(key, value); + break; } } -void SPStar::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | - SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - +void SPStar::update(SPCtx *ctx, guint flags) +{ + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { this->set_shape(); } @@ -222,28 +216,27 @@ void SPStar::update(SPCtx *ctx, guint flags) { SPShape::update(ctx, flags); } - -const char* SPStar::displayName() const { +const char *SPStar::displayName() const +{ if (this->flatsided == false) return _("Star"); return _("Polygon"); } -gchar* SPStar::description() const { +gchar *SPStar::description() const +{ // while there will never be less than 2 or 3 vertices, we still need to // make calls to ngettext because the pluralization may be different // for various numbers >=3. The singular form is used as the index. - return g_strdup_printf (ngettext(_("with %d vertex"), _("with %d vertices"), - this->sides), this->sides); + return g_strdup_printf(ngettext(_("with %d vertex"), _("with %d vertices"), this->sides), this->sides); } /** Returns a unit-length vector at 90 degrees to the direction from o to n */ -static Geom::Point -rot90_rel (Geom::Point o, Geom::Point n) +static Geom::Point rot90_rel(Geom::Point o, Geom::Point n) { - return ((1/Geom::L2(n - o)) * Geom::Point ((n - o)[Geom::Y], (o - n)[Geom::X])); + return ((1 / Geom::L2(n - o)) * Geom::Point((n - o)[Geom::Y], (o - n)[Geom::X])); } /** @@ -252,15 +245,10 @@ Obvious (but acceptable for my purposes) limits to uniqueness: - returned value for x,y repeats for x+n*1024,y+n*1024 - returned value is unchanged when the point is moved by less than 1/1024 of px */ -static guint32 -point_unique_int (Geom::Point o) +static guint32 point_unique_int(Geom::Point o) { - return ((guint32) - 65536 * - (((int) floor (o[Geom::X] * 64)) % 1024 + ((int) floor (o[Geom::X] * 1024)) % 64) - + - (((int) floor (o[Geom::Y] * 64)) % 1024 + ((int) floor (o[Geom::Y] * 1024)) % 64) - ); + return ((guint32)65536 * (((int)floor(o[Geom::X] * 64)) % 1024 + ((int)floor(o[Geom::X] * 1024)) % 64) + + (((int)floor(o[Geom::Y] * 64)) % 1024 + ((int)floor(o[Geom::Y] * 1024)) % 64)); } /** @@ -268,54 +256,54 @@ Returns the next pseudorandom value using the Linear Congruential Generator algo with the parameters (m = 2^32, a = 69069, b = 1). These parameters give a full-period generator, i.e. it is guaranteed to go through all integers < 2^32 (see http://random.mat.sbg.ac.at/~charly/server/server.html) */ -static inline guint32 -lcg_next(guint32 const prev) +static inline guint32 lcg_next(guint32 const prev) { - return (guint32) ( 69069 * prev + 1 ); + return (guint32)(69069 * prev + 1); } /** Returns a random number in the range [-0.5, 0.5) from the given seed, stepping the given number of steps from the seed. */ -static double -rnd (guint32 const seed, unsigned steps) { +static double rnd(guint32 const seed, unsigned steps) +{ guint32 lcg = seed; - for (; steps > 0; steps --) - lcg = lcg_next (lcg); + for (; steps > 0; steps--) + lcg = lcg_next(lcg); - return ( lcg / 4294967296. ) - 0.5; + return (lcg / 4294967296.) - 0.5; } -static Geom::Point -sp_star_get_curvepoint (SPStar *star, SPStarPoint point, gint index, bool previ) +static Geom::Point sp_star_get_curvepoint(SPStar *star, SPStarPoint point, gint index, bool previ) { // the point whose neighboring curve handle we're calculating - Geom::Point o = sp_star_get_xy (star, point, index); + Geom::Point o = sp_star_get_xy(star, point, index); // indices of previous and next points - gint pi = (index > 0)? (index - 1) : (star->sides - 1); - gint ni = (index < star->sides - 1)? (index + 1) : 0; + gint pi = (index > 0) ? (index - 1) : (star->sides - 1); + gint ni = (index < star->sides - 1) ? (index + 1) : 0; // the other point type - SPStarPoint other = (point == SP_STAR_POINT_KNOT2? SP_STAR_POINT_KNOT1 : SP_STAR_POINT_KNOT2); + SPStarPoint other = (point == SP_STAR_POINT_KNOT2 ? SP_STAR_POINT_KNOT1 : SP_STAR_POINT_KNOT2); // the neighbors of o; depending on flatsided, they're either the same type (polygon) or the other type (star) - Geom::Point prev = (star->flatsided? sp_star_get_xy (star, point, pi) : sp_star_get_xy (star, other, point == SP_STAR_POINT_KNOT2? index : pi)); - Geom::Point next = (star->flatsided? sp_star_get_xy (star, point, ni) : sp_star_get_xy (star, other, point == SP_STAR_POINT_KNOT1? index : ni)); + Geom::Point prev = (star->flatsided ? sp_star_get_xy(star, point, pi) + : sp_star_get_xy(star, other, point == SP_STAR_POINT_KNOT2 ? index : pi)); + Geom::Point next = (star->flatsided ? sp_star_get_xy(star, point, ni) + : sp_star_get_xy(star, other, point == SP_STAR_POINT_KNOT1 ? index : ni)); // prev-next midpoint - Geom::Point mid = 0.5 * (prev + next); + Geom::Point mid = 0.5 * (prev + next); // point to which we direct the bissector of the curve handles; // it's far enough outside the star on the perpendicular to prev-next through mid - Geom::Point biss = mid + 100000 * rot90_rel (mid, next); + Geom::Point biss = mid + 100000 * rot90_rel(mid, next); // lengths of vectors to prev and next - gdouble prev_len = Geom::L2 (prev - o); - gdouble next_len = Geom::L2 (next - o); + gdouble prev_len = Geom::L2(prev - o); + gdouble next_len = Geom::L2(next - o); // unit-length vector perpendicular to o-biss - Geom::Point rot = rot90_rel (o, biss); + Geom::Point rot = rot90_rel(o, biss); // multiply rot by star->rounded coefficient and the distance to the star point; flip for next Geom::Point ret; @@ -330,14 +318,14 @@ sp_star_get_curvepoint (SPStar *star, SPStarPoint point, gint index, bool previ) return o + ret; } else { // the seed corresponding to the exact point - guint32 seed = point_unique_int (o); + guint32 seed = point_unique_int(o); // randomly rotate (by step 3 from the seed) and scale (by step 4) the vector - ret = ret * Geom::Affine (Geom::Rotate (star->randomized * M_PI * rnd (seed, 3))); - ret *= ( 1 + star->randomized * rnd (seed, 4)); + ret = ret * Geom::Affine(Geom::Rotate(star->randomized * M_PI * rnd(seed, 3))); + ret *= (1 + star->randomized * rnd(seed, 4)); // the randomized corner point - Geom::Point o_randomized = sp_star_get_xy (star, point, index, true); + Geom::Point o_randomized = sp_star_get_xy(star, point, index, true); return o_randomized + ret; } @@ -346,12 +334,14 @@ sp_star_get_curvepoint (SPStar *star, SPStarPoint point, gint index, bool previ) #define NEXT false #define PREV true -void SPStar::set_shape() { +void SPStar::set_shape() +{ // perhaps we should convert all our shapes into LPEs without source path // and with knotholders for parameters, then this situation will be handled automatically // by disabling the entire stack (including the shape LPE) if (hasBrokenPathEffect()) { - g_warning ("The star shape has unknown LPE on it! Convert to path to make it editable preserving the appearance; editing it as star will remove the bad LPE"); + g_warning("The star shape has unknown LPE on it! Convert to path to make it editable preserving the " + "appearance; editing it as star will remove the bad LPE"); if (this->getRepr()->attribute("d")) { // unconditionally read the curve from d, if any, to preserve appearance @@ -365,68 +355,69 @@ void SPStar::set_shape() { auto c = std::make_unique<SPCurve>(); - bool not_rounded = (fabs (this->rounded) < 1e-4); + bool not_rounded = (fabs(this->rounded) < 1e-4); // note that we pass randomized=true to sp_star_get_xy, because the curve must be randomized; // other places that call that function (e.g. the knotholder) need the exact point // draw 1st segment - c->moveto(sp_star_get_xy (this, SP_STAR_POINT_KNOT1, 0, true)); + c->moveto(sp_star_get_xy(this, SP_STAR_POINT_KNOT1, 0, true)); if (this->flatsided == false) { if (not_rounded) { - c->lineto(sp_star_get_xy (this, SP_STAR_POINT_KNOT2, 0, true)); + c->lineto(sp_star_get_xy(this, SP_STAR_POINT_KNOT2, 0, true)); } else { - c->curveto(sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT1, 0, NEXT), - sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT2, 0, PREV), - sp_star_get_xy (this, SP_STAR_POINT_KNOT2, 0, true)); + c->curveto(sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT1, 0, NEXT), + sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT2, 0, PREV), + sp_star_get_xy(this, SP_STAR_POINT_KNOT2, 0, true)); } } // draw all middle segments for (gint i = 1; i < sides; i++) { if (not_rounded) { - c->lineto(sp_star_get_xy (this, SP_STAR_POINT_KNOT1, i, true)); + c->lineto(sp_star_get_xy(this, SP_STAR_POINT_KNOT1, i, true)); } else { if (this->flatsided == false) { - c->curveto(sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT2, i - 1, NEXT), - sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT1, i, PREV), - sp_star_get_xy (this, SP_STAR_POINT_KNOT1, i, true)); + c->curveto(sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT2, i - 1, NEXT), + sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT1, i, PREV), + sp_star_get_xy(this, SP_STAR_POINT_KNOT1, i, true)); } else { - c->curveto(sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT1, i - 1, NEXT), - sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT1, i, PREV), - sp_star_get_xy (this, SP_STAR_POINT_KNOT1, i, true)); + c->curveto(sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT1, i - 1, NEXT), + sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT1, i, PREV), + sp_star_get_xy(this, SP_STAR_POINT_KNOT1, i, true)); } } if (this->flatsided == false) { if (not_rounded) { - c->lineto(sp_star_get_xy (this, SP_STAR_POINT_KNOT2, i, true)); + c->lineto(sp_star_get_xy(this, SP_STAR_POINT_KNOT2, i, true)); } else { - c->curveto(sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT1, i, NEXT), - sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT2, i, PREV), - sp_star_get_xy (this, SP_STAR_POINT_KNOT2, i, true)); + c->curveto(sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT1, i, NEXT), + sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT2, i, PREV), + sp_star_get_xy(this, SP_STAR_POINT_KNOT2, i, true)); } } } // draw last segment - if (!not_rounded) { - if (this->flatsided == false) { - c->curveto(sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT2, sides - 1, NEXT), - sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT1, 0, PREV), - sp_star_get_xy (this, SP_STAR_POINT_KNOT1, 0, true)); - } else { - c->curveto(sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT1, sides - 1, NEXT), - sp_star_get_curvepoint (this, SP_STAR_POINT_KNOT1, 0, PREV), - sp_star_get_xy (this, SP_STAR_POINT_KNOT1, 0, true)); - } - } + if (!not_rounded) { + if (this->flatsided == false) { + c->curveto(sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT2, sides - 1, NEXT), + sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT1, 0, PREV), + sp_star_get_xy(this, SP_STAR_POINT_KNOT1, 0, true)); + } else { + c->curveto(sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT1, sides - 1, NEXT), + sp_star_get_curvepoint(this, SP_STAR_POINT_KNOT1, 0, PREV), + sp_star_get_xy(this, SP_STAR_POINT_KNOT1, 0, true)); + } + } c->closepath(); /* Reset the shape's curve to the "original_curve" - * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in shape)*/ + * This is very important for LPEs to work properly! (the bbox might be recalculated depending on the curve in + * shape)*/ auto const before = this->curveBeforeLPE(); if (before && before->get_pathvector() != c->get_pathvector()) { @@ -444,22 +435,22 @@ void SPStar::set_shape() { setCurveInsync(std::move(c)); } -void -sp_star_position_set (SPStar *star, gint sides, Geom::Point center, gdouble r1, gdouble r2, gdouble arg1, gdouble arg2, bool isflat, double rounded, double randomized) +void sp_star_position_set(SPStar *star, gint sides, Geom::Point center, gdouble r1, gdouble r2, gdouble arg1, + gdouble arg2, bool isflat, double rounded, double randomized) { - g_return_if_fail (star != nullptr); - g_return_if_fail (SP_IS_STAR (star)); + g_return_if_fail(star != nullptr); + g_return_if_fail(SP_IS_STAR(star)); star->flatsided = isflat; star->center = center; - star->r[0] = MAX (r1, 0.001); + star->r[0] = MAX(r1, 0.001); if (isflat == false) { star->sides = CLAMP(sides, 2, 1024); star->r[1] = CLAMP(r2, 0.0, star->r[0]); } else { star->sides = CLAMP(sides, 3, 1024); - star->r[1] = CLAMP( r1*cos(M_PI/sides) ,0.0, star->r[0] ); + star->r[1] = CLAMP(r1 * cos(M_PI / sides), 0.0, star->r[0]); } star->arg[0] = arg1; @@ -469,7 +460,8 @@ sp_star_position_set (SPStar *star, gint sides, Geom::Point center, gdouble r1, star->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void SPStar::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const { +void SPStar::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const +{ // We will determine the star's midpoint ourselves, instead of trusting on the base class // Therefore snapping to object midpoints is temporarily disabled Inkscape::SnapPreferences local_snapprefs = *snapprefs; @@ -479,8 +471,8 @@ void SPStar::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape:: SPShape::snappoints(p, &local_snapprefs); if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_OBJECT_MIDPOINT)) { - Geom::Affine const i2dt (this->i2dt_affine ()); - p.emplace_back(this->center * i2dt,Inkscape::SNAPSOURCE_OBJECT_MIDPOINT, Inkscape::SNAPTARGET_OBJECT_MIDPOINT); + Geom::Affine const i2dt(this->i2dt_affine()); + p.emplace_back(this->center * i2dt, Inkscape::SNAPSOURCE_OBJECT_MIDPOINT, Inkscape::SNAPTARGET_OBJECT_MIDPOINT); } } @@ -496,7 +488,7 @@ Geom::Affine SPStar::set_transform(Geom::Affine const &xform) } /* Calculate star start in parent coords. */ - Geom::Point pos( this->center * xform ); + Geom::Point pos(this->center * xform); /* This function takes care of translation and scaling, we return whatever parts we can't handle. */ @@ -535,7 +527,8 @@ Geom::Affine SPStar::set_transform(Geom::Affine const &xform) return ret; } -void SPStar::update_patheffect(bool write) { +void SPStar::update_patheffect(bool write) +{ SPShape::update_patheffect(write); } @@ -549,10 +542,9 @@ void SPStar::update_patheffect(bool write) { * * Initial item coordinate system is same as document coordinate system. */ -Geom::Point -sp_star_get_xy (SPStar const *star, SPStarPoint point, gint index, bool randomized) +Geom::Point sp_star_get_xy(SPStar const *star, SPStarPoint point, gint index, bool randomized) { - gdouble darg = 2.0 * M_PI / (double) star->sides; + gdouble darg = 2.0 * M_PI / (double)star->sides; double arg = star->arg[point]; arg += index * darg; @@ -563,12 +555,13 @@ sp_star_get_xy (SPStar const *star, SPStarPoint point, gint index, bool randomiz // return the exact point return xy; } else { // randomize the point - // find out the seed, unique for this point so that randomization is the same so long as the original point is stationary - guint32 seed = point_unique_int (xy); + // find out the seed, unique for this point so that randomization is the same so long as the original point is + // stationary + guint32 seed = point_unique_int(xy); // the full range (corresponding to star->randomized == 1.0) is equal to the star's diameter - double range = 2 * MAX (star->r[0], star->r[1]); + double range = 2 * MAX(star->r[0], star->r[1]); // find out the random displacement; x is controlled by step 1 from the seed, y by the step 2 - Geom::Point shift (star->randomized * range * rnd (seed, 1), star->randomized * range * rnd (seed, 2)); + Geom::Point shift(star->randomized * range * rnd(seed, 1), star->randomized * range * rnd(seed, 2)); // add the shift to the exact point return xy + shift; } diff --git a/src/object/sp-star.h b/src/object/sp-star.h index 21936b119f309c4f2727995673850d00beeecbc1..9e91ecac62b44af37fa3c52116f36898d9156eb1 100644 --- a/src/object/sp-star.h +++ b/src/object/sp-star.h @@ -17,52 +17,54 @@ #include "sp-polygon.h" +#define SP_STAR(obj) (dynamic_cast<SPStar *>((SPObject *)obj)) +#define SP_IS_STAR(obj) (dynamic_cast<const SPStar *>((SPObject *)obj) != NULL) -#define SP_STAR(obj) (dynamic_cast<SPStar*>((SPObject*)obj)) -#define SP_IS_STAR(obj) (dynamic_cast<const SPStar*>((SPObject*)obj) != NULL) - -enum SPStarPoint { - SP_STAR_POINT_KNOT1, - SP_STAR_POINT_KNOT2 +enum SPStarPoint +{ + SP_STAR_POINT_KNOT1, + SP_STAR_POINT_KNOT2 }; -class SPStar : public SPPolygon { +class SPStar : public SPPolygon +{ public: - SPStar(); - ~SPStar() override; - - int sides; - - Geom::Point center; - double r[2]; - double arg[2]; - bool flatsided; - - double rounded; - double randomized; - -// CPPIFY: This derivation is a bit weird. -// parent_class = reinterpret_cast<SPShapeClass *>(g_type_class_ref(SP_TYPE_SHAPE)); -// So shouldn't star be derived from shape instead of polygon? -// What does polygon have that shape doesn't? - - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - void set(SPAttr key, char const* value) override; - void update(SPCtx* ctx, unsigned int flags) override; - - const char* displayName() const override; - char* description() const override; - void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const override; + SPStar(); + ~SPStar() override; + + int sides; + + Geom::Point center; + double r[2]; + double arg[2]; + bool flatsided; + + double rounded; + double randomized; + + // CPPIFY: This derivation is a bit weird. + // parent_class = reinterpret_cast<SPShapeClass *>(g_type_class_ref(SP_TYPE_SHAPE)); + // So shouldn't star be derived from shape instead of polygon? + // What does polygon have that shape doesn't? + + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + void set(SPAttr key, char const *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + + const char *displayName() const override; + char *description() const override; + void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, + Inkscape::SnapPreferences const *snapprefs) const override; void update_patheffect(bool write) override; - void set_shape() override; - Geom::Affine set_transform(Geom::Affine const& xform) override; + void set_shape() override; + Geom::Affine set_transform(Geom::Affine const &xform) override; }; -void sp_star_position_set (SPStar *star, int sides, Geom::Point center, double r1, double r2, double arg1, double arg2, bool isflat, double rounded, double randomized); - -Geom::Point sp_star_get_xy (SPStar const *star, SPStarPoint point, int index, bool randomized = false); - +void sp_star_position_set(SPStar *star, int sides, Geom::Point center, double r1, double r2, double arg1, double arg2, + bool isflat, double rounded, double randomized); +Geom::Point sp_star_get_xy(SPStar const *star, SPStarPoint point, int index, bool randomized = false); #endif diff --git a/src/object/sp-stop.cpp b/src/object/sp-stop.cpp index fba0640070aa6d3ef7173b3f8d8f4e842c2c8377..d6b5d0842eb923a847c6d33287608adcc134632a 100644 --- a/src/object/sp-stop.cpp +++ b/src/object/sp-stop.cpp @@ -14,24 +14,26 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "sp-stop.h" -#include "style.h" #include "attributes.h" #include "streq.h" -#include "svg/svg.h" -#include "svg/svg-color.h" +#include "style.h" #include "svg/css-ostringstream.h" +#include "svg/svg-color.h" +#include "svg/svg.h" -SPStop::SPStop() : SPObject() { +SPStop::SPStop() + : SPObject() +{ this->path_string = nullptr; this->offset = 0.0; } SPStop::~SPStop() = default; -void SPStop::build(SPDocument* doc, Inkscape::XML::Node* repr) { +void SPStop::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ SPObject::build(doc, repr); this->readAttr(SPAttr::STYLE); @@ -44,7 +46,8 @@ void SPStop::build(SPDocument* doc, Inkscape::XML::Node* repr) { * Virtual build: set stop attributes from its associated XML node. */ -void SPStop::set(SPAttr key, const gchar* value) { +void SPStop::set(SPAttr key, const gchar *value) +{ switch (key) { case SPAttr::OFFSET: { this->offset = sp_svg_read_percentage(value, 0.0); @@ -53,12 +56,12 @@ void SPStop::set(SPAttr key, const gchar* value) { } case SPAttr::STOP_PATH: { if (value) { - this->path_string = new Glib::ustring( value ); - //Geom::PathVector pv = sp_svg_read_pathv(value); - //SPCurve *curve = new SPCurve(pv); - //if( curve ) { - // std::cout << "Got Curve" << std::endl; - //curve->unref(); + this->path_string = new Glib::ustring(value); + // Geom::PathVector pv = sp_svg_read_pathv(value); + // SPCurve *curve = new SPCurve(pv); + // if( curve ) { + // std::cout << "Got Curve" << std::endl; + // curve->unref(); //} this->requestModified(SP_OBJECT_MODIFIED_FLAG); } @@ -84,12 +87,12 @@ void SPStop::modified(guint flags) } } - /** * Virtual set: set attribute to value. */ -Inkscape::XML::Node* SPStop::write(Inkscape::XML::Document* xml_doc, Inkscape::XML::Node* repr, guint flags) { +Inkscape::XML::Node *SPStop::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:stop"); } @@ -107,10 +110,11 @@ Inkscape::XML::Node* SPStop::write(Inkscape::XML::Document* xml_doc, Inkscape::X */ // A stop might have some non-stop siblings -SPStop* SPStop::getNextStop() { +SPStop *SPStop::getNextStop() +{ SPStop *result = nullptr; - for (SPObject* obj = getNext(); obj && !result; obj = obj->getNext()) { + for (SPObject *obj = getNext(); obj && !result; obj = obj->getNext()) { if (SP_IS_STOP(obj)) { result = SP_STOP(obj); } @@ -119,13 +123,14 @@ SPStop* SPStop::getNextStop() { return result; } -SPStop* SPStop::getPrevStop() { +SPStop *SPStop::getPrevStop() +{ SPStop *result = nullptr; - for (SPObject* obj = getPrev(); obj; obj = obj->getPrev()) { + for (SPObject *obj = getPrev(); obj; obj = obj->getPrev()) { // The closest previous SPObject that is an SPStop *should* be ourself. if (SP_IS_STOP(obj)) { - SPStop* stop = SP_STOP(obj); + SPStop *stop = SP_STOP(obj); // Sanity check to ensure we have a proper sibling structure. if (stop->getNextStop() == this) { result = stop; diff --git a/src/object/sp-stop.h b/src/object/sp-stop.h index b3065c6cf04d5827f0dfaab7719157c2efde888c..df59ca8ee828d270516ad75c608fd1768122d7d5 100644 --- a/src/object/sp-stop.h +++ b/src/object/sp-stop.h @@ -17,8 +17,8 @@ * Authors: */ -#include "sp-object.h" #include "color.h" +#include "sp-object.h" typedef unsigned int guint32; @@ -26,38 +26,38 @@ namespace Glib { class ustring; } -#define SP_STOP(obj) (dynamic_cast<SPStop*>((SPObject*)obj)) -#define SP_IS_STOP(obj) (dynamic_cast<const SPStop*>((SPObject*)obj) != NULL) +#define SP_STOP(obj) (dynamic_cast<SPStop *>((SPObject *)obj)) +#define SP_IS_STOP(obj) (dynamic_cast<const SPStop *>((SPObject *)obj) != NULL) /** Gradient stop. */ -class SPStop : public SPObject { +class SPStop : public SPObject +{ public: - SPStop(); - ~SPStop() override; + SPStop(); + ~SPStop() override; /// \todo fixme: Should be SPSVGPercentage float offset; bool currentColor; - Glib::ustring * path_string; - //SPCurve path; + Glib::ustring *path_string; + // SPCurve path; - SPStop* getNextStop(); - SPStop* getPrevStop(); + SPStop *getNextStop(); + SPStop *getPrevStop(); SPColor getColor() const; gfloat getOpacity() const; guint32 get_rgba32() const; protected: - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void set(SPAttr key, const char* value) override; - void modified(guint flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void set(SPAttr key, const char *value) override; + void modified(guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; - #endif /* !SEEN_SP_STOP_H */ /* diff --git a/src/object/sp-string.cpp b/src/object/sp-string.cpp index ee38bfd9636c59fb4a99058add7b673f5b523214..dcb8c85afbfe023b8a03c711d0e4905124de2b77 100644 --- a/src/object/sp-string.cpp +++ b/src/object/sp-string.cpp @@ -24,14 +24,16 @@ */ #include "sp-string.h" + #include "style.h" /*##################################################### # SPSTRING #####################################################*/ -SPString::SPString() : SPObject() { - +SPString::SPString() + : SPObject() +{ // This is dangerous but strings shouldn't have style. // delete (style); // style = nullptr; @@ -39,23 +41,23 @@ SPString::SPString() : SPObject() { SPString::~SPString() = default; -void SPString::build(SPDocument *doc, Inkscape::XML::Node *repr) { - +void SPString::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ read_content(); SPObject::build(doc, repr); } -void SPString::release() { +void SPString::release() +{ SPObject::release(); } - -void SPString::read_content() { - +void SPString::read_content() +{ string.clear(); - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. gchar const *xml_string = getRepr()->content(); // std::cout << ">" << (xml_string?xml_string:"Null") << "<" << std::endl; @@ -76,25 +78,25 @@ void SPString::read_content() { // See algorithms described in svg 1.1 section 10.15 bool collapse_space = true; - bool collapse_line = true; - bool is_css = false; + bool collapse_line = true; + bool is_css = false; // Strings don't have style, check parent for style - if( parent && parent->style ) { - if( parent->style->white_space.computed == SP_CSS_WHITE_SPACE_PRE || + if (parent && parent->style) { + if (parent->style->white_space.computed == SP_CSS_WHITE_SPACE_PRE || parent->style->white_space.computed == SP_CSS_WHITE_SPACE_PREWRAP || - parent->style->white_space.computed == SP_CSS_WHITE_SPACE_PRELINE ) { + parent->style->white_space.computed == SP_CSS_WHITE_SPACE_PRELINE) { collapse_line = false; } - if( parent->style->white_space.computed == SP_CSS_WHITE_SPACE_PRE || - parent->style->white_space.computed == SP_CSS_WHITE_SPACE_PREWRAP ) { + if (parent->style->white_space.computed == SP_CSS_WHITE_SPACE_PRE || + parent->style->white_space.computed == SP_CSS_WHITE_SPACE_PREWRAP) { collapse_space = false; } - if( parent->style->white_space.computed != SP_CSS_WHITE_SPACE_NORMAL ) { + if (parent->style->white_space.computed != SP_CSS_WHITE_SPACE_NORMAL) { is_css = true; // If white-space not normal, we assume white-space is set. } } - if( !is_css ) { + if (!is_css) { // SVG 2: Use 'xml:space' only if 'white-space' not 'normal'. if (xml_space.value == SP_XML_SPACE_PRESERVE) { collapse_space = false; @@ -102,8 +104,7 @@ void SPString::read_content() { } bool white_space = false; - for ( ; *xml_string ; xml_string = g_utf8_next_char(xml_string) ) { - + for (; *xml_string; xml_string = g_utf8_next_char(xml_string)) { gunichar c = g_utf8_get_char(xml_string); switch (c) { case 0xd: // Carriage return @@ -113,42 +114,44 @@ void SPString::read_content() { continue; break; case 0xa: // Line feed - if( collapse_line ) { - if( !is_css && collapse_space ) continue; // xml:space == 'default' strips LFs. - white_space = true; // Convert to space and collapse + if (collapse_line) { + if (!is_css && collapse_space) + continue; // xml:space == 'default' strips LFs. + white_space = true; // Convert to space and collapse } else { - string += c; // Preserve line feed + string += c; // Preserve line feed continue; } break; case '\t': // Tab - if( collapse_space ) { - white_space = true; // Convert to space and collapse + if (collapse_space) { + white_space = true; // Convert to space and collapse } else { - string += c; // Preserve tab + string += c; // Preserve tab continue; } break; case ' ': // Space - if( collapse_space ) { - white_space = true; // Collapse white space + if (collapse_space) { + white_space = true; // Collapse white space } else { - string += c; // Preserve space + string += c; // Preserve space continue; } break; default: - if( white_space && (!string.empty() || (getPrev() != nullptr))) { + if (white_space && (!string.empty() || (getPrev() != nullptr))) { string += ' '; } string += c; white_space = false; } // End switch - } // End loop + } // End loop // Insert white space at end if more text follows - if (white_space && getRepr()->next() != nullptr) { // can't use SPObject::getNext() when the SPObject tree is still being built + if (white_space && getRepr()->next() != nullptr) { // can't use SPObject::getNext() when the SPObject tree is still + // being built string += ' '; } @@ -156,15 +159,15 @@ void SPString::read_content() { requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void SPString::update(SPCtx * /*ctx*/, unsigned /*flags*/) { - +void SPString::update(SPCtx * /*ctx*/, unsigned /*flags*/) +{ // if (flags & (SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_MODIFIED_FLAG)) { // /* Parent style or we ourselves changed, so recalculate */ - // flags &= ~SP_OBJECT_USER_MODIFIED_FLAG_B; // won't be "just a transformation" anymore, we're going to recompute "x" and "y" attributes + // flags &= ~SP_OBJECT_USER_MODIFIED_FLAG_B; // won't be "just a transformation" anymore, we're going to + // recompute "x" and "y" attributes // } } - /* Local Variables: mode:c++ diff --git a/src/object/sp-string.h b/src/object/sp-string.h index 9714d10383e1afb52c8e93eeae86eae0b89a24fe..9be171277c8e7d30c08d6cd53c91c2150c579ee4 100644 --- a/src/object/sp-string.h +++ b/src/object/sp-string.h @@ -19,22 +19,23 @@ #include "sp-object.h" -#define SP_STRING(obj) (dynamic_cast<SPString*>((SPObject*)obj)) -#define SP_IS_STRING(obj) (dynamic_cast<const SPString*>((SPObject*)obj) != NULL) +#define SP_STRING(obj) (dynamic_cast<SPString *>((SPObject *)obj)) +#define SP_IS_STRING(obj) (dynamic_cast<const SPString *>((SPObject *)obj) != NULL) -class SPString : public SPObject { +class SPString : public SPObject +{ public: - SPString(); - ~SPString() override; + SPString(); + ~SPString() override; - Glib::ustring string; + Glib::ustring string; - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; - void read_content() override; + void read_content() override; - void update(SPCtx* ctx, unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; }; #endif diff --git a/src/object/sp-style-elem.cpp b/src/object/sp-style-elem.cpp index 347a573a9b70b23ebcaa25a39ec5570528d757cb..55673235906f9b207cf639045ef6cb26e3b16750 100644 --- a/src/object/sp-style-elem.cpp +++ b/src/object/sp-style-elem.cpp @@ -7,26 +7,31 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-style-elem.h" + #include <3rdparty/libcroco/cr-parser.h> -#include "xml/node-event-vector.h" -#include "xml/repr.h" + +#include "attributes.h" #include "document.h" -#include "sp-style-elem.h" #include "sp-root.h" -#include "attributes.h" #include "style.h" +#include "xml/node-event-vector.h" +#include "xml/repr.h" // For external style sheets -#include "io/resource.h" -#include <iostream> #include <fstream> +#include <iostream> + +#include "io/resource.h" // For font-rule #include "libnrtype/FontFactory.h" using Inkscape::XML::TEXT_NODE; -SPStyleElem::SPStyleElem() : SPObject() { +SPStyleElem::SPStyleElem() + : SPObject() +{ media_set_all(this->media); this->is_css = false; this->style_sheet = nullptr; @@ -34,7 +39,8 @@ SPStyleElem::SPStyleElem() : SPObject() { SPStyleElem::~SPStyleElem() = default; -void SPStyleElem::set(SPAttr key, const gchar* value) { +void SPStyleElem::set(SPAttr key, const gchar *value) +{ switch (key) { case SPAttr::TYPE: { if (!value) { @@ -44,9 +50,7 @@ void SPStyleElem::set(SPAttr key, const gchar* value) { } else { /* fixme: determine what whitespace is allowed. Will probably need to ask on SVG list; though the relevant RFC may give info on its lexer. */ - is_css = ( g_ascii_strncasecmp(value, "text/css", 8) == 0 - && ( value[8] == '\0' || - value[8] == ';' ) ); + is_css = (g_ascii_strncasecmp(value, "text/css", 8) == 0 && (value[8] == '\0' || value[8] == ';')); } break; } @@ -115,17 +119,16 @@ static void child_rm_cb(Inkscape::XML::Node *, Inkscape::XML::Node *child, Inksc /** * Callback for rearranging text nodes inside a <style> node */ -static void -child_order_changed_cb(Inkscape::XML::Node *, Inkscape::XML::Node *, - Inkscape::XML::Node *, Inkscape::XML::Node *, - void *const data) +static void child_order_changed_cb(Inkscape::XML::Node *, Inkscape::XML::Node *, Inkscape::XML::Node *, + Inkscape::XML::Node *, void *const data) { SPObject *obj = reinterpret_cast<SPObject *>(data); g_assert(data != nullptr); obj->read_content(); } -Inkscape::XML::Node* SPStyleElem::write(Inkscape::XML::Document* xml_doc, Inkscape::XML::Node* repr, guint flags) { +Inkscape::XML::Node *SPStyleElem::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:style"); } @@ -145,26 +148,27 @@ Inkscape::XML::Node* SPStyleElem::write(Inkscape::XML::Document* xml_doc, Inksca return repr; } - /** Returns the concatenation of the content of the text children of the specified object. */ -static Glib::ustring -concat_children(Inkscape::XML::Node const &repr) +static Glib::ustring concat_children(Inkscape::XML::Node const &repr) { Glib::ustring ret; // effic: Initialising ret to a reasonable starting size could speed things up. for (Inkscape::XML::Node const *rch = repr.firstChild(); rch != nullptr; rch = rch->next()) { - if ( rch->type() == TEXT_NODE ) { + if (rch->type() == TEXT_NODE) { ret += rch->content(); } } return ret; } - - /* Callbacks for SAC-style libcroco parser. */ -enum StmtType { NO_STMT, FONT_FACE_STMT, NORMAL_RULESET_STMT }; +enum StmtType +{ + NO_STMT, + FONT_FACE_STMT, + NORMAL_RULESET_STMT +}; struct ParseTmp { @@ -173,19 +177,17 @@ struct ParseTmp CRStatement *currStmt; SPDocument *const document; // Need file location for '@import' unsigned magic; - static unsigned const ParseTmp_magic = 0x23474397; // from /dev/urandom - - ParseTmp(CRStyleSheet *const stylesheet, SPDocument *const document) : - stylesheet(stylesheet), - stmtType(NO_STMT), - currStmt(nullptr), - document(document), - magic(ParseTmp_magic) - { } - - bool hasMagic() const { - return magic == ParseTmp_magic; - } + static unsigned const ParseTmp_magic = 0x23474397; // from /dev/urandom + + ParseTmp(CRStyleSheet *const stylesheet, SPDocument *const document) + : stylesheet(stylesheet) + , stmtType(NO_STMT) + , currStmt(nullptr) + , document(document) + , magic(ParseTmp_magic) + {} + + bool hasMagic() const { return magic == ParseTmp_magic; } ~ParseTmp() { @@ -194,15 +196,10 @@ struct ParseTmp } }; -CRParser* -parser_init(CRStyleSheet *const stylesheet, SPDocument *const document); +CRParser *parser_init(CRStyleSheet *const stylesheet, SPDocument *const document); -static void -import_style_cb (CRDocHandler *a_handler, - GList *a_media_list, - CRString *a_uri, - CRString *a_uri_default_ns, - CRParsingLocation *a_location) +static void import_style_cb(CRDocHandler *a_handler, GList *a_media_list, CRString *a_uri, CRString *a_uri_default_ns, + CRParsingLocation *a_location) { /* a_uri_default_ns is set to NULL and is unused by libcroco */ @@ -212,7 +209,7 @@ import_style_cb (CRDocHandler *a_handler, ParseTmp &parse_tmp = *static_cast<ParseTmp *>(a_handler->app_data); g_return_if_fail(parse_tmp.hasMagic()); - SPDocument* document = parse_tmp.document; + SPDocument *document = parse_tmp.document; if (!document) { std::cerr << "import_style_cb: No document!" << std::endl; return; @@ -223,14 +220,13 @@ import_style_cb (CRDocHandler *a_handler, } // Get file - auto import_file = - Inkscape::IO::Resource::get_filename (document->getDocumentURI(), a_uri->stryng->str); + auto import_file = Inkscape::IO::Resource::get_filename(document->getDocumentURI(), a_uri->stryng->str); // Parse file - CRStyleSheet *stylesheet = cr_stylesheet_new (nullptr); + CRStyleSheet *stylesheet = cr_stylesheet_new(nullptr); CRParser *parser = parser_init(stylesheet, document); CRStatus const parse_status = - cr_parser_parse_file (parser, reinterpret_cast<const guchar *>(import_file.c_str()), CR_UTF_8); + cr_parser_parse_file(parser, reinterpret_cast<const guchar *>(import_file.c_str()), CR_UTF_8); if (parse_status == CR_OK) { g_assert(parse_tmp.stylesheet); g_assert(parse_tmp.stylesheet != stylesheet); @@ -238,12 +234,12 @@ import_style_cb (CRDocHandler *a_handler, cr_stylesheet_append_import(parse_tmp.stylesheet, stylesheet); } else { std::cerr << "import_style_cb: Could not parse: " << import_file << std::endl; - cr_stylesheet_destroy (stylesheet); + cr_stylesheet_destroy(stylesheet); } // Need to delete ParseTmp created by parser_init() CRDocHandler *sac_handler = nullptr; - cr_parser_get_sac_handler (parser, &sac_handler); + cr_parser_get_sac_handler(parser, &sac_handler); ParseTmp *parse_new = reinterpret_cast<ParseTmp *>(sac_handler->app_data); cr_parser_destroy(parser); delete parse_new; @@ -263,17 +259,15 @@ import_style_result_cb (CRDocHandler *a_this, }; #endif -static void -start_selector_cb(CRDocHandler *a_handler, - CRSelector *a_sel_list) +static void start_selector_cb(CRDocHandler *a_handler, CRSelector *a_sel_list) { g_return_if_fail(a_handler && a_sel_list); g_return_if_fail(a_handler->app_data != nullptr); ParseTmp &parse_tmp = *static_cast<ParseTmp *>(a_handler->app_data); g_return_if_fail(parse_tmp.hasMagic()); - if ( (parse_tmp.currStmt != nullptr) - || (parse_tmp.stmtType != NO_STMT) ) { - g_warning("Expecting currStmt==NULL and stmtType==0 (NO_STMT) at start of ruleset, but found currStmt=%p, stmtType=%u", + if ((parse_tmp.currStmt != nullptr) || (parse_tmp.stmtType != NO_STMT)) { + g_warning("Expecting currStmt==NULL and stmtType==0 (NO_STMT) at start of ruleset, but found currStmt=%p, " + "stmtType=%u", static_cast<void *>(parse_tmp.currStmt), unsigned(parse_tmp.stmtType)); // fixme: Check whether we need to unref currStmt if non-NULL. } @@ -283,79 +277,62 @@ start_selector_cb(CRDocHandler *a_handler, parse_tmp.currStmt = ruleset; } -static void -end_selector_cb(CRDocHandler *a_handler, - CRSelector *a_sel_list) +static void end_selector_cb(CRDocHandler *a_handler, CRSelector *a_sel_list) { g_return_if_fail(a_handler && a_sel_list); g_return_if_fail(a_handler->app_data != nullptr); ParseTmp &parse_tmp = *static_cast<ParseTmp *>(a_handler->app_data); g_return_if_fail(parse_tmp.hasMagic()); CRStatement *const ruleset = parse_tmp.currStmt; - if (parse_tmp.stmtType == NORMAL_RULESET_STMT - && ruleset - && ruleset->type == RULESET_STMT - && ruleset->kind.ruleset->sel_list == a_sel_list) - { - parse_tmp.stylesheet->statements = cr_statement_append(parse_tmp.stylesheet->statements, - ruleset); + if (parse_tmp.stmtType == NORMAL_RULESET_STMT && ruleset && ruleset->type == RULESET_STMT && + ruleset->kind.ruleset->sel_list == a_sel_list) { + parse_tmp.stylesheet->statements = cr_statement_append(parse_tmp.stylesheet->statements, ruleset); } else { g_warning("Found stmtType=%u, stmt=%p, stmt.type=%u, ruleset.sel_list=%p, a_sel_list=%p.", - unsigned(parse_tmp.stmtType), - ruleset, - unsigned(ruleset->type), - ruleset->kind.ruleset->sel_list, + unsigned(parse_tmp.stmtType), ruleset, unsigned(ruleset->type), ruleset->kind.ruleset->sel_list, a_sel_list); } parse_tmp.currStmt = nullptr; parse_tmp.stmtType = NO_STMT; } -static void -start_font_face_cb(CRDocHandler *a_handler, - CRParsingLocation *) +static void start_font_face_cb(CRDocHandler *a_handler, CRParsingLocation *) { g_return_if_fail(a_handler->app_data != nullptr); ParseTmp &parse_tmp = *static_cast<ParseTmp *>(a_handler->app_data); g_return_if_fail(parse_tmp.hasMagic()); if (parse_tmp.stmtType != NO_STMT || parse_tmp.currStmt != nullptr) { - g_warning("Expecting currStmt==NULL and stmtType==0 (NO_STMT) at start of @font-face, but found currStmt=%p, stmtType=%u", + g_warning("Expecting currStmt==NULL and stmtType==0 (NO_STMT) at start of @font-face, but found currStmt=%p, " + "stmtType=%u", static_cast<void *>(parse_tmp.currStmt), unsigned(parse_tmp.stmtType)); // fixme: Check whether we need to unref currStmt if non-NULL. } - CRStatement *font_face_rule = cr_statement_new_at_font_face_rule (parse_tmp.stylesheet, nullptr); + CRStatement *font_face_rule = cr_statement_new_at_font_face_rule(parse_tmp.stylesheet, nullptr); g_return_if_fail(font_face_rule && font_face_rule->type == AT_FONT_FACE_RULE_STMT); parse_tmp.stmtType = FONT_FACE_STMT; parse_tmp.currStmt = font_face_rule; } -static void -end_font_face_cb(CRDocHandler *a_handler) +static void end_font_face_cb(CRDocHandler *a_handler) { g_return_if_fail(a_handler->app_data != nullptr); ParseTmp &parse_tmp = *static_cast<ParseTmp *>(a_handler->app_data); g_return_if_fail(parse_tmp.hasMagic()); CRStatement *const font_face_rule = parse_tmp.currStmt; - if (parse_tmp.stmtType == FONT_FACE_STMT - && font_face_rule - && font_face_rule->type == AT_FONT_FACE_RULE_STMT) - { - parse_tmp.stylesheet->statements = cr_statement_append(parse_tmp.stylesheet->statements, - font_face_rule); + if (parse_tmp.stmtType == FONT_FACE_STMT && font_face_rule && font_face_rule->type == AT_FONT_FACE_RULE_STMT) { + parse_tmp.stylesheet->statements = cr_statement_append(parse_tmp.stylesheet->statements, font_face_rule); } else { - g_warning("Found stmtType=%u, stmt=%p, stmt.type=%u.", - unsigned(parse_tmp.stmtType), - font_face_rule, + g_warning("Found stmtType=%u, stmt=%p, stmt.type=%u.", unsigned(parse_tmp.stmtType), font_face_rule, unsigned(font_face_rule->type)); } std::cout << "end_font_face_cb: font face rule limited support." << std::endl; - cr_declaration_dump (font_face_rule->kind.font_face_rule->decl_list, stdout, 2, TRUE); - printf ("\n"); + cr_declaration_dump(font_face_rule->kind.font_face_rule->decl_list, stdout, 2, TRUE); + printf("\n"); // Get document - SPDocument* document = parse_tmp.document; + SPDocument *document = parse_tmp.document; if (!document) { std::cerr << "end_font_face_cb: No document!" << std::endl; return; @@ -368,28 +345,19 @@ end_font_face_cb(CRDocHandler *a_handler) // Add ttf or otf fonts. CRDeclaration const *cur = nullptr; for (cur = font_face_rule->kind.font_face_rule->decl_list; cur; cur = cur->next) { - if (cur->property && - cur->property->stryng && - cur->property->stryng->str && - strcmp(cur->property->stryng->str, "src") == 0 ) { - - if (cur->value && - cur->value->content.str && - cur->value->content.str->stryng && + if (cur->property && cur->property->stryng && cur->property->stryng->str && + strcmp(cur->property->stryng->str, "src") == 0) { + if (cur->value && cur->value->content.str && cur->value->content.str->stryng && cur->value->content.str->stryng->str) { - Glib::ustring value = cur->value->content.str->stryng->str; - if (value.rfind("ttf") == (value.length() - 3) || - value.rfind("otf") == (value.length() - 3)) { - + if (value.rfind("ttf") == (value.length() - 3) || value.rfind("otf") == (value.length() - 3)) { // Get file - Glib::ustring ttf_file = - Inkscape::IO::Resource::get_filename (document->getDocumentURI(), value); + Glib::ustring ttf_file = Inkscape::IO::Resource::get_filename(document->getDocumentURI(), value); if (!ttf_file.empty()) { font_factory *factory = font_factory::Default(); - factory->AddFontFile( ttf_file.c_str() ); + factory->AddFontFile(ttf_file.c_str()); std::cout << "end_font_face_cb: Added font: " << ttf_file << std::endl; // FIX ME: Need to refresh font list. @@ -403,13 +371,10 @@ end_font_face_cb(CRDocHandler *a_handler) parse_tmp.currStmt = nullptr; parse_tmp.stmtType = NO_STMT; - } -static void -property_cb(CRDocHandler *const a_handler, - CRString *const a_name, - CRTerm *const a_value, gboolean const a_important) +static void property_cb(CRDocHandler *const a_handler, CRString *const a_name, CRTerm *const a_value, + gboolean const a_important) { // std::cout << "property_cb: Entrance: " << a_name->stryng->str << ": " << cr_term_to_string(a_value) << std::endl; g_return_if_fail(a_handler && a_name); @@ -420,34 +385,32 @@ property_cb(CRDocHandler *const a_handler, CRStatement *const ruleset = parse_tmp.currStmt; g_return_if_fail(ruleset); - CRDeclaration *const decl = cr_declaration_new (ruleset, cr_string_dup(a_name), a_value); + CRDeclaration *const decl = cr_declaration_new(ruleset, cr_string_dup(a_name), a_value); g_return_if_fail(decl); decl->important = a_important; switch (parse_tmp.stmtType) { - case NORMAL_RULESET_STMT: { - g_return_if_fail (ruleset->type == RULESET_STMT); - CRStatus const append_status = cr_statement_ruleset_append_decl (ruleset, decl); - g_return_if_fail (append_status == CR_OK); + g_return_if_fail(ruleset->type == RULESET_STMT); + CRStatus const append_status = cr_statement_ruleset_append_decl(ruleset, decl); + g_return_if_fail(append_status == CR_OK); break; } case FONT_FACE_STMT: { - g_return_if_fail (ruleset->type == AT_FONT_FACE_RULE_STMT); - CRDeclaration *new_decls = cr_declaration_append (ruleset->kind.font_face_rule->decl_list, decl); - g_return_if_fail (new_decls); + g_return_if_fail(ruleset->type == AT_FONT_FACE_RULE_STMT); + CRDeclaration *new_decls = cr_declaration_append(ruleset->kind.font_face_rule->decl_list, decl); + g_return_if_fail(new_decls); ruleset->kind.font_face_rule->decl_list = new_decls; break; } default: - g_warning ("property_cb: Unhandled stmtType: %u", parse_tmp.stmtType); + g_warning("property_cb: Unhandled stmtType: %u", parse_tmp.stmtType); return; } } -CRParser* -parser_init(CRStyleSheet *const stylesheet, SPDocument *const document) { - +CRParser *parser_init(CRStyleSheet *const stylesheet, SPDocument *const document) +{ ParseTmp *parse_tmp = new ParseTmp(stylesheet, document); CRDocHandler *sac_handler = cr_doc_handler_new(); @@ -459,21 +422,22 @@ parser_init(CRStyleSheet *const stylesheet, SPDocument *const document) { sac_handler->end_font_face = end_font_face_cb; sac_handler->property = property_cb; - CRParser *parser = cr_parser_new (nullptr); + CRParser *parser = cr_parser_new(nullptr); cr_parser_set_sac_handler(parser, sac_handler); return parser; } -void update_style_recursively( SPObject *object ) { +void update_style_recursively(SPObject *object) +{ if (object) { // std::cout << "update_style_recursively: " // << (object->getId()?object->getId():"null") << std::endl; if (object->style) { - object->style->readFromObject( object ); + object->style->readFromObject(object); } - for (auto& child : object->children) { - update_style_recursively( &child ); + for (auto &child : object->children) { + update_style_recursively(&child); } } } @@ -524,7 +488,8 @@ static void clear_style_sheet(SPStyleElem &self) self.style_sheet = nullptr; } -void SPStyleElem::read_content() { +void SPStyleElem::read_content() +{ // TODO On modification (observer callbacks), clearing and re-appending to // the cascade can change the positon of a stylesheet relative to other // sheets in the document. We need a better way to update a style sheet @@ -534,20 +499,20 @@ void SPStyleElem::read_content() { // First, create the style-sheet object and track it in this // element so that it can be edited. It'll be combined with // the document's style sheet later. - style_sheet = cr_stylesheet_new (nullptr); + style_sheet = cr_stylesheet_new(nullptr); CRParser *parser = parser_init(style_sheet, document); CRDocHandler *sac_handler = nullptr; - cr_parser_get_sac_handler (parser, &sac_handler); + cr_parser_get_sac_handler(parser, &sac_handler); ParseTmp *parse_tmp = reinterpret_cast<ParseTmp *>(sac_handler->app_data); - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. Glib::ustring const text = concat_children(*getRepr()); if (!(text.find_first_not_of(" \t\r\n") != std::string::npos)) { return; } CRStatus const parse_status = - cr_parser_parse_buf (parser, reinterpret_cast<const guchar *>(text.c_str()), text.bytes(), CR_UTF_8); + cr_parser_parse_buf(parser, reinterpret_cast<const guchar *>(text.c_str()), text.bytes(), CR_UTF_8); if (parse_status == CR_OK) { auto *cascade = document->getStyleCascade(); @@ -561,7 +526,7 @@ void SPStyleElem::read_content() { cr_stylesheet_append_stylesheet(topsheet, style_sheet); } } else { - cr_stylesheet_destroy (style_sheet); + cr_stylesheet_destroy(style_sheet); style_sheet = nullptr; if (parse_status != CR_PARSING_ERROR) { g_printerr("parsing error code=%u\n", unsigned(parse_status)); @@ -572,7 +537,7 @@ void SPStyleElem::read_content() { delete parse_tmp; // If style sheet has changed, we need to cascade the entire object tree, top down // Get root, read style, loop through children - update_style_recursively( (SPObject *)document->getRoot() ); + update_style_recursively((SPObject *)document->getRoot()); // cr_stylesheet_dump (document->getStyleSheet(), stdout); } @@ -584,7 +549,8 @@ static Inkscape::XML::NodeEventVector const nodeEventVector = { child_order_changed_cb, // order_changed }; -void SPStyleElem::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPStyleElem::build(SPDocument *document, Inkscape::XML::Node *repr) +{ read_content(); readAttr(SPAttr::TYPE); @@ -602,7 +568,8 @@ void SPStyleElem::build(SPDocument *document, Inkscape::XML::Node *repr) { SPObject::build(document, repr); } -void SPStyleElem::release() { +void SPStyleElem::release() +{ getRepr()->removeListenerByData(this); for (Inkscape::XML::Node *child = getRepr()->firstChild(); child != nullptr; child = child->next()) { child->removeListenerByData(this); @@ -613,7 +580,6 @@ void SPStyleElem::release() { SPObject::release(); } - /* Local Variables: mode:c++ diff --git a/src/object/sp-style-elem.h b/src/object/sp-style-elem.h index 5d5d80b06c00090bebd994d056f2e6aa227e58d3..b5265c1538e9628c9391d7a254765fbb54714df0 100644 --- a/src/object/sp-style-elem.h +++ b/src/object/sp-style-elem.h @@ -10,15 +10,15 @@ #ifndef INKSCAPE_SP_STYLE_ELEM_H #define INKSCAPE_SP_STYLE_ELEM_H -#include "sp-object.h" -#include "media.h" - +#include <3rdparty/libcroco/cr-statement.h> #include <memory> #include <vector> -#include <3rdparty/libcroco/cr-statement.h> +#include "media.h" +#include "sp-object.h" -class SPStyleElem : public SPObject { +class SPStyleElem : public SPObject +{ public: SPStyleElem(); ~SPStyleElem() override; @@ -31,15 +31,14 @@ public: std::vector<std::unique_ptr<SPStyle>> get_styles() const; - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void set(SPAttr key, char const* value) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void set(SPAttr key, char const *value) override; void read_content() override; void release() override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; - #endif /* !INKSCAPE_SP_STYLE_ELEM_H */ /* diff --git a/src/object/sp-switch.cpp b/src/object/sp-switch.cpp index 2f235ce9c7835eacae43362ff1037a993365bbb3..7c89e44b5f909ad2f1a04d049d4ee392ff9a9522 100644 --- a/src/object/sp-switch.cpp +++ b/src/object/sp-switch.cpp @@ -13,28 +13,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/i18n.h> - #include "sp-switch.h" -#include "display/drawing-group.h" -#include "conditions.h" +#include <glibmm/i18n.h> #include <sigc++/adaptors/bind.h> -SPSwitch::SPSwitch() : SPGroup() { +#include "conditions.h" +#include "display/drawing-group.h" + +SPSwitch::SPSwitch() + : SPGroup() +{ this->_cached_item = nullptr; } -SPSwitch::~SPSwitch() { +SPSwitch::~SPSwitch() +{ _releaseLastItem(_cached_item); } -SPObject *SPSwitch::_evaluateFirst() { +SPObject *SPSwitch::_evaluateFirst() +{ SPObject *first = nullptr; - for (auto& child: children) { + for (auto &child : children) { if (SP_IS_ITEM(&child) && sp_item_evaluate(SP_ITEM(&child))) { - first = &child; + first = &child; break; } } @@ -42,54 +46,59 @@ SPObject *SPSwitch::_evaluateFirst() { return first; } -std::vector<SPObject*> SPSwitch::_childList(bool add_ref, SPObject::Action action) { - if ( action != SPObject::ActionGeneral ) { +std::vector<SPObject *> SPSwitch::_childList(bool add_ref, SPObject::Action action) +{ + if (action != SPObject::ActionGeneral) { return this->childList(add_ref, action); } SPObject *child = _evaluateFirst(); - std::vector<SPObject*> x; + std::vector<SPObject *> x; if (nullptr == child) return x; if (add_ref) { - //g_object_ref (G_OBJECT (child)); - sp_object_ref(child); + // g_object_ref (G_OBJECT (child)); + sp_object_ref(child); } x.push_back(child); return x; } -const char *SPSwitch::displayName() const { +const char *SPSwitch::displayName() const +{ return _("Conditional Group"); } -gchar *SPSwitch::description() const { +gchar *SPSwitch::description() const +{ gint len = this->getItemCount(); - return g_strdup_printf( - ngettext(_("of <b>%d</b> object"), _("of <b>%d</b> objects"), len), len); + return g_strdup_printf(ngettext(_("of <b>%d</b> object"), _("of <b>%d</b> objects"), len), len); } -void SPSwitch::child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) { +void SPSwitch::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ SPGroup::child_added(child, ref); this->_reevaluate(true); } -void SPSwitch::remove_child(Inkscape::XML::Node *child) { +void SPSwitch::remove_child(Inkscape::XML::Node *child) +{ SPGroup::remove_child(child); this->_reevaluate(); } -void SPSwitch::order_changed (Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref) +void SPSwitch::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref) { SPGroup::order_changed(child, old_ref, new_ref); - this->_reevaluate(); + this->_reevaluate(); } -void SPSwitch::_reevaluate(bool /*add_to_drawing*/) { +void SPSwitch::_reevaluate(bool /*add_to_drawing*/) +{ SPObject *evaluated_child = _evaluateFirst(); if (!evaluated_child || _cached_item == evaluated_child) { return; @@ -97,14 +106,14 @@ void SPSwitch::_reevaluate(bool /*add_to_drawing*/) { _releaseLastItem(_cached_item); - std::vector<SPObject*> item_list = _childList(false, SPObject::ActionShow); - for ( std::vector<SPObject*>::const_reverse_iterator iter=item_list.rbegin();iter!=item_list.rend();++iter) { + std::vector<SPObject *> item_list = _childList(false, SPObject::ActionShow); + for (std::vector<SPObject *>::const_reverse_iterator iter = item_list.rbegin(); iter != item_list.rend(); ++iter) { SPObject *o = *iter; - if ( !SP_IS_ITEM (o) ) { + if (!SP_IS_ITEM(o)) { continue; } - SPItem * child = SP_ITEM(o); + SPItem *child = SP_ITEM(o); child->setEvaluated(o == evaluated_child); } @@ -128,18 +137,20 @@ void SPSwitch::_releaseLastItem(SPObject *obj) this->_cached_item = nullptr; } -void SPSwitch::_showChildren (Inkscape::Drawing &drawing, Inkscape::DrawingItem *ai, unsigned int key, unsigned int flags) { +void SPSwitch::_showChildren(Inkscape::Drawing &drawing, Inkscape::DrawingItem *ai, unsigned int key, + unsigned int flags) +{ SPObject *evaluated_child = this->_evaluateFirst(); - std::vector<SPObject*> l = this->_childList(false, SPObject::ActionShow); + std::vector<SPObject *> l = this->_childList(false, SPObject::ActionShow); - for ( std::vector<SPObject*>::const_reverse_iterator iter=l.rbegin();iter!=l.rend();++iter) { + for (std::vector<SPObject *>::const_reverse_iterator iter = l.rbegin(); iter != l.rend(); ++iter) { SPObject *o = *iter; - if (SP_IS_ITEM (o)) { - SPItem * child = SP_ITEM(o); + if (SP_IS_ITEM(o)) { + SPItem *child = SP_ITEM(o); child->setEvaluated(o == evaluated_child); - Inkscape::DrawingItem *ac = child->invoke_show (drawing, key, flags); + Inkscape::DrawingItem *ac = child->invoke_show(drawing, key, flags); if (ac) { ai->appendChild(ac); diff --git a/src/object/sp-switch.h b/src/object/sp-switch.h index 0aecd6010341305706177ebaba005a0143997bf5..40bf330c128f41740dc975291f9fd2b35d715623 100644 --- a/src/object/sp-switch.h +++ b/src/object/sp-switch.h @@ -18,19 +18,20 @@ #include "sp-item-group.h" +#define SP_SWITCH(obj) (dynamic_cast<SPSwitch *>((SPObject *)obj)) +#define SP_IS_SWITCH(obj) (dynamic_cast<const SPSwitch *>((SPObject *)obj) != NULL) -#define SP_SWITCH(obj) (dynamic_cast<SPSwitch*>((SPObject*)obj)) -#define SP_IS_SWITCH(obj) (dynamic_cast<const SPSwitch*>((SPObject*)obj) != NULL) - -class SPSwitch : public SPGroup { +class SPSwitch : public SPGroup +{ public: - SPSwitch(); - ~SPSwitch() override; + SPSwitch(); + ~SPSwitch() override; void resetChildEvaluated() { _reevaluate(); } - std::vector<SPObject*> _childList(bool add_ref, SPObject::Action action); - void _showChildren (Inkscape::Drawing &drawing, Inkscape::DrawingItem *ai, unsigned int key, unsigned int flags) override; + std::vector<SPObject *> _childList(bool add_ref, SPObject::Action action); + void _showChildren(Inkscape::Drawing &drawing, Inkscape::DrawingItem *ai, unsigned int key, + unsigned int flags) override; SPObject *_evaluateFirst(); void _reevaluate(bool add_to_arena = false); @@ -40,10 +41,10 @@ public: SPObject *_cached_item; sigc::connection _release_connection; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; void remove_child(Inkscape::XML::Node *child) override; void order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref) override; - const char* displayName() const override; + const char *displayName() const override; gchar *description() const override; }; diff --git a/src/object/sp-symbol.cpp b/src/object/sp-symbol.cpp index fa2f474052c530c34da1a01710c405c58b940078..6abaa899db8c6f2e73f3dce0e9d24c09b9cdbd11 100644 --- a/src/object/sp-symbol.cpp +++ b/src/object/sp-symbol.cpp @@ -12,70 +12,76 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <string> +#include "sp-symbol.h" #include <2geom/transforms.h> -#include "display/drawing-group.h" -#include "xml/repr.h" +#include <string> + #include "attributes.h" -#include "print.h" -#include "sp-symbol.h" +#include "display/drawing-group.h" #include "document.h" +#include "print.h" +#include "xml/repr.h" -SPSymbol::SPSymbol() : SPGroup(), SPViewBox() { -} +SPSymbol::SPSymbol() + : SPGroup() + , SPViewBox() +{} SPSymbol::~SPSymbol() = default; -void SPSymbol::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPSymbol::build(SPDocument *document, Inkscape::XML::Node *repr) +{ this->readAttr(SPAttr::VIEWBOX); this->readAttr(SPAttr::PRESERVEASPECTRATIO); SPGroup::build(document, repr); } -void SPSymbol::release() { - SPGroup::release(); +void SPSymbol::release() +{ + SPGroup::release(); } -void SPSymbol::set(SPAttr key, const gchar* value) { +void SPSymbol::set(SPAttr key, const gchar *value) +{ switch (key) { - case SPAttr::VIEWBOX: - set_viewBox( value ); - // std::cout << "Symbol: ViewBox: " << viewBox << std::endl; - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); - break; - - case SPAttr::PRESERVEASPECTRATIO: - set_preserveAspectRatio( value ); - // std::cout << "Symbol: Preserve aspect ratio: " << aspect_align << ", " << aspect_clip << std::endl; - this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); - break; - - default: - SPGroup::set(key, value); - break; + case SPAttr::VIEWBOX: + set_viewBox(value); + // std::cout << "Symbol: ViewBox: " << viewBox << std::endl; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); + break; + + case SPAttr::PRESERVEASPECTRATIO: + set_preserveAspectRatio(value); + // std::cout << "Symbol: Preserve aspect ratio: " << aspect_align << ", " << aspect_clip << std::endl; + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG); + break; + + default: + SPGroup::set(key, value); + break; } } -void SPSymbol::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { - SPGroup::child_added(child, ref); +void SPSymbol::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) +{ + SPGroup::child_added(child, ref); } - -void SPSymbol::update(SPCtx *ctx, guint flags) { +void SPSymbol::update(SPCtx *ctx, guint flags) +{ if (this->cloned) { - - SPItemCtx *ictx = (SPItemCtx *) ctx; - SPItemCtx rctx = get_rctx( ictx ); + SPItemCtx *ictx = (SPItemCtx *)ctx; + SPItemCtx rctx = get_rctx(ictx); // And invoke parent method - SPGroup::update((SPCtx *) &rctx, flags); + SPGroup::update((SPCtx *)&rctx, flags); // As last step set additional transform of drawing group for (SPItemView *v = this->display; v != nullptr; v = v->next) { - Inkscape::DrawingGroup *g = dynamic_cast<Inkscape::DrawingGroup *>(v->arenaitem); - g->setChildTransform(this->c2p); + Inkscape::DrawingGroup *g = dynamic_cast<Inkscape::DrawingGroup *>(v->arenaitem); + g->setChildTransform(this->c2p); } } else { // No-op @@ -83,20 +89,21 @@ void SPSymbol::update(SPCtx *ctx, guint flags) { } } -void SPSymbol::modified(unsigned int flags) { - SPGroup::modified(flags); +void SPSymbol::modified(unsigned int flags) +{ + SPGroup::modified(flags); } - -Inkscape::XML::Node* SPSymbol::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPSymbol::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:symbol"); } - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. repr->setAttribute("viewBox", this->getRepr()->attribute("viewBox")); - - //XML Tree being used directly here while it shouldn't be. + + // XML Tree being used directly here while it shouldn't be. repr->setAttribute("preserveAspectRatio", this->getRepr()->attribute("preserveAspectRatio")); SPGroup::write(xml_doc, repr, flags); @@ -104,7 +111,8 @@ Inkscape::XML::Node* SPSymbol::write(Inkscape::XML::Document *xml_doc, Inkscape: return repr; } -Inkscape::DrawingItem* SPSymbol::show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) { +Inkscape::DrawingItem *SPSymbol::show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) +{ Inkscape::DrawingItem *ai = nullptr; if (this->cloned) { @@ -112,36 +120,38 @@ Inkscape::DrawingItem* SPSymbol::show(Inkscape::Drawing &drawing, unsigned int k ai = SPGroup::show(drawing, key, flags); Inkscape::DrawingGroup *g = dynamic_cast<Inkscape::DrawingGroup *>(ai); - if (g) { - g->setChildTransform(this->c2p); - } + if (g) { + g->setChildTransform(this->c2p); + } } return ai; } -void SPSymbol::hide(unsigned int key) { +void SPSymbol::hide(unsigned int key) +{ if (this->cloned) { /* Cloned <symbol> is actually renderable */ SPGroup::hide(key); } } - -Geom::OptRect SPSymbol::bbox(Geom::Affine const &transform, SPItem::BBoxType type) const { +Geom::OptRect SPSymbol::bbox(Geom::Affine const &transform, SPItem::BBoxType type) const +{ Geom::OptRect bbox; // We don't need a bounding box for Symbols dialog when selecting // symbols. They have no canvas location. But cloned symbols are. if (this->cloned) { - Geom::Affine const a( this->c2p * transform ); - bbox = SPGroup::bbox(a, type); + Geom::Affine const a(this->c2p * transform); + bbox = SPGroup::bbox(a, type); } return bbox; } -void SPSymbol::print(SPPrintContext* ctx) { +void SPSymbol::print(SPPrintContext *ctx) +{ if (this->cloned) { // Cloned <symbol> is actually renderable @@ -149,7 +159,7 @@ void SPSymbol::print(SPPrintContext* ctx) { SPGroup::print(ctx); - ctx->release (); + ctx->release(); } } diff --git a/src/object/sp-symbol.h b/src/object/sp-symbol.h index 9cae46a9388b7f505d3f3037ec6f432237c1f186..472159e611b042b575b70d14033c473fe5302c79 100644 --- a/src/object/sp-symbol.h +++ b/src/object/sp-symbol.h @@ -19,31 +19,36 @@ */ #include <2geom/affine.h> + #include "sp-item-group.h" #include "viewbox.h" -#define SP_TYPE_SYMBOL (sp_symbol_get_type ()) -#define SP_SYMBOL(obj) (dynamic_cast<SPSymbol*>((SPObject*)obj)) -#define SP_IS_SYMBOL(obj) (dynamic_cast<const SPSymbol*>((SPObject*)obj) != NULL) +#define SP_TYPE_SYMBOL (sp_symbol_get_type()) +#define SP_SYMBOL(obj) (dynamic_cast<SPSymbol *>((SPObject *)obj)) +#define SP_IS_SYMBOL(obj) (dynamic_cast<const SPSymbol *>((SPObject *)obj) != NULL) -class SPSymbol : public SPGroup, public SPViewBox { +class SPSymbol + : public SPGroup + , public SPViewBox +{ public: - SPSymbol(); - ~SPSymbol() override; - - void build(SPDocument *document, Inkscape::XML::Node *repr) override; - void release() override; - void set(SPAttr key, char const* value) override; - void update(SPCtx *ctx, unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - - void modified(unsigned int flags) override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - - Inkscape::DrawingItem* show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; - void print(SPPrintContext *ctx) override; - Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; - void hide (unsigned int key) override; + SPSymbol(); + ~SPSymbol() override; + + void build(SPDocument *document, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, char const *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + + void modified(unsigned int flags) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + + Inkscape::DrawingItem *show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; + void print(SPPrintContext *ctx) override; + Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; + void hide(unsigned int key) override; }; #endif diff --git a/src/object/sp-tag-use-reference.cpp b/src/object/sp-tag-use-reference.cpp index 6b7bd9b56b26a7fa392d4c21264c0e00348a5a75..8fb5b0089b7d28955345fc8c51050b4ce6eb7952 100644 --- a/src/object/sp-tag-use-reference.cpp +++ b/src/object/sp-tag-use-reference.cpp @@ -18,8 +18,7 @@ #include "sp-text.h" #include "uri.h" - -bool SPTagUseReference::_acceptObject(SPObject * const obj) const +bool SPTagUseReference::_acceptObject(SPObject *const obj) const { if (SP_IS_ITEM(obj)) { return URIReference::_acceptObject(obj); @@ -28,18 +27,19 @@ bool SPTagUseReference::_acceptObject(SPObject * const obj) const } } - static void sp_usepath_href_changed(SPObject *old_ref, SPObject *ref, SPTagUsePath *offset); static void sp_usepath_delete_self(SPObject *deleted, SPTagUsePath *offset); -SPTagUsePath::SPTagUsePath(SPObject* i_owner):SPTagUseReference(i_owner) +SPTagUsePath::SPTagUsePath(SPObject *i_owner) + : SPTagUseReference(i_owner) { - owner=i_owner; - sourceDirty=false; + owner = i_owner; + sourceDirty = false; sourceHref = nullptr; sourceRepr = nullptr; sourceObject = nullptr; - _changed_connection = changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_usepath_href_changed), this)); // listening to myself, this should be virtual instead + _changed_connection = changedSignal().connect(sigc::bind( + sigc::ptr_fun(sp_usepath_href_changed), this)); // listening to myself, this should be virtual instead user_unlink = nullptr; } @@ -52,14 +52,13 @@ SPTagUsePath::~SPTagUsePath() unlink(); } -void -SPTagUsePath::link(char *to) +void SPTagUsePath::link(char *to) { - if ( to == nullptr ) { + if (to == nullptr) { quit_listening(); unlink(); } else { - if ( !sourceHref || ( strcmp(to, sourceHref) != 0 ) ) { + if (!sourceHref || (strcmp(to, sourceHref) != 0)) { g_free(sourceHref); sourceHref = g_strdup(to); try { @@ -75,18 +74,16 @@ SPTagUsePath::link(char *to) } } -void -SPTagUsePath::unlink() +void SPTagUsePath::unlink() { g_free(sourceHref); sourceHref = nullptr; detach(); } -void -SPTagUsePath::start_listening(SPObject* to) +void SPTagUsePath::start_listening(SPObject *to) { - if ( to == nullptr ) { + if (to == nullptr) { return; } sourceObject = to; @@ -94,10 +91,9 @@ SPTagUsePath::start_listening(SPObject* to) _delete_connection = to->connectDelete(sigc::bind(sigc::ptr_fun(&sp_usepath_delete_self), this)); } -void -SPTagUsePath::quit_listening() +void SPTagUsePath::quit_listening() { - if ( sourceObject == nullptr ) { + if (sourceObject == nullptr) { return; } _delete_connection.disconnect(); @@ -105,18 +101,16 @@ SPTagUsePath::quit_listening() sourceObject = nullptr; } -static void -sp_usepath_href_changed(SPObject */*old_ref*/, SPObject */*ref*/, SPTagUsePath *offset) +static void sp_usepath_href_changed(SPObject * /*old_ref*/, SPObject * /*ref*/, SPTagUsePath *offset) { offset->quit_listening(); SPItem *refobj = offset->getObject(); - if ( refobj ) { + if (refobj) { offset->start_listening(refobj); } } -static void -sp_usepath_delete_self(SPObject */*deleted*/, SPTagUsePath *offset) +static void sp_usepath_delete_self(SPObject * /*deleted*/, SPTagUsePath *offset) { offset->owner->deleteObject(); } diff --git a/src/object/sp-tag-use-reference.h b/src/object/sp-tag-use-reference.h index 85710a3169eff0cd4c63e387477cb03b75a5f0f3..547f3c02bcabeffe5047a57cecfce50e73e5d43e 100644 --- a/src/object/sp-tag-use-reference.h +++ b/src/object/sp-tag-use-reference.h @@ -11,56 +11,55 @@ */ #include <cstddef> -#include <sigc++/sigc++.h> #include <glib.h> +#include <sigc++/sigc++.h> -#include "sp-object.h" #include "sp-item.h" +#include "sp-object.h" #include "uri-references.h" namespace Inkscape { namespace XML { - class Node; +class Node; } -} - +} // namespace Inkscape -class SPTagUseReference : public Inkscape::URIReference { +class SPTagUseReference : public Inkscape::URIReference +{ public: - SPTagUseReference(SPObject *owner) : URIReference(owner) {} + SPTagUseReference(SPObject *owner) + : URIReference(owner) + {} - SPItem *getObject() const { - return static_cast<SPItem *>(URIReference::getObject()); - } + SPItem *getObject() const { return static_cast<SPItem *>(URIReference::getObject()); } protected: - bool _acceptObject(SPObject * const obj) const override; - + bool _acceptObject(SPObject *const obj) const override; }; - -class SPTagUsePath : public SPTagUseReference { +class SPTagUsePath : public SPTagUseReference +{ public: bool sourceDirty; - SPObject *owner; - gchar *sourceHref; + SPObject *owner; + gchar *sourceHref; Inkscape::XML::Node *sourceRepr; - SPObject *sourceObject; + SPObject *sourceObject; sigc::connection _delete_connection; sigc::connection _changed_connection; - SPTagUsePath(SPObject* i_owner); + SPTagUsePath(SPObject *i_owner); ~SPTagUsePath() override; - void link(char* to); + void link(char *to); void unlink(); - void start_listening(SPObject* to); + void start_listening(SPObject *to); void quit_listening(); void refresh_source(); - void (*user_unlink) (SPObject *user); + void (*user_unlink)(SPObject *user); }; #endif /* !SEEN_SP_USE_REFERENCE_H */ diff --git a/src/object/sp-tag-use.cpp b/src/object/sp-tag-use.cpp index e4e664b4ecc312cb49d93236ba6bc10013aeab43..c39ea56cb36bb76ee51a1c19cfded6cb1ca9edd2 100644 --- a/src/object/sp-tag-use.cpp +++ b/src/object/sp-tag-use.cpp @@ -14,34 +14,32 @@ #include "sp-tag-use.h" #include <cstring> -#include <string> - #include <glibmm/i18n.h> +#include <string> +#include "attributes.h" #include "bad-uri-exception.h" #include "display/drawing-group.h" -#include "attributes.h" #include "document.h" -#include "uri.h" -#include "xml/repr.h" #include "preferences.h" -#include "style.h" #include "sp-factory.h" #include "sp-symbol.h" #include "sp-tag-use-reference.h" +#include "style.h" +#include "uri.h" +#include "xml/repr.h" SPTagUse::SPTagUse() { href = nullptr; - //new (_changed_connection) sigc::connection; + // new (_changed_connection) sigc::connection; ref = new SPTagUseReference(this); - + _changed_connection = ref->changedSignal().connect(sigc::mem_fun(*this, &SPTagUse::href_changed)); } SPTagUse::~SPTagUse() { - if (child) { detach(child); child = nullptr; @@ -51,11 +49,10 @@ SPTagUse::~SPTagUse() delete ref; ref = nullptr; - _changed_connection.~connection(); //FIXME why? + _changed_connection.~connection(); // FIXME why? } -void -SPTagUse::build(SPDocument *document, Inkscape::XML::Node *repr) +void SPTagUse::build(SPDocument *document, Inkscape::XML::Node *repr) { SPObject::build(document, repr); readAttr(SPAttr::XLINK_HREF); @@ -65,10 +62,8 @@ SPTagUse::build(SPDocument *document, Inkscape::XML::Node *repr) // which will call sp_tag_use_href_changed, and that will take care of the child } -void -SPTagUse::release() +void SPTagUse::release() { - if (child) { detach(child); child = nullptr; @@ -84,13 +79,11 @@ SPTagUse::release() SPObject::release(); } -void -SPTagUse::set(SPAttr key, gchar const *value) +void SPTagUse::set(SPAttr key, gchar const *value) { - switch (key) { case SPAttr::XLINK_HREF: { - if ( value && href && ( strcmp(value, href) == 0 ) ) { + if (value && href && (strcmp(value, href) == 0)) { /* No change, do nothing. */ } else { g_free(href); @@ -114,20 +107,19 @@ SPTagUse::set(SPAttr key, gchar const *value) } default: - SPObject::set(key, value); + SPObject::set(key, value); break; } } -Inkscape::XML::Node * -SPTagUse::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +Inkscape::XML::Node *SPTagUse::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("inkscape:tagref"); } SPObject::write(xml_doc, repr, flags); - + if (ref->getURI()) { auto uri_string = ref->getURI()->str(); repr->setAttributeOrRemoveIfEmpty("xlink:href", uri_string); @@ -144,8 +136,8 @@ SPTagUse::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, gui * Note that the returned is the clone object, i.e. the child of an SPTagUse (of the argument one for * the trivial case) and not the "true original". */ - -SPItem * SPTagUse::root() + +SPItem *SPTagUse::root() { SPObject *orig = child; while (orig && SP_IS_TAG_USE(orig)) { @@ -156,28 +148,26 @@ SPItem * SPTagUse::root() return SP_ITEM(orig); } -void -SPTagUse::href_changed(SPObject */*old_ref*/, SPObject */*ref*/) +void SPTagUse::href_changed(SPObject * /*old_ref*/, SPObject * /*ref*/) { if (href) { SPItem *refobj = ref->getObject(); if (refobj) { Inkscape::XML::Node *childrepr = refobj->getRepr(); const std::string typeString = NodeTraits::get_type_string(*childrepr); - - SPObject* child_ = SPFactory::createObject(typeString); + + SPObject *child_ = SPFactory::createObject(typeString); if (child_) { child = child_; attach(child_, lastChild()); sp_object_unref(child_, nullptr); child_->invoke_build(this->document, childrepr, TRUE); - } } } } -SPItem * SPTagUse::get_original() +SPItem *SPTagUse::get_original() { SPItem *ref_ = nullptr; if (ref) { diff --git a/src/object/sp-tag-use.h b/src/object/sp-tag-use.h index 4b9e7985f59d8fcd832af642f17487a0a9bf24c4..8901ae508b61b2913a678836632fb62d0ed712cb 100644 --- a/src/object/sp-tag-use.h +++ b/src/object/sp-tag-use.h @@ -13,41 +13,42 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glib.h> #include <cstddef> +#include <glib.h> #include <sigc++/sigc++.h> -#include "svg/svg-length.h" -#include "sp-object.h" +#include "sp-object.h" +#include "svg/svg-length.h" -#define SP_TAG_USE(obj) (dynamic_cast<SPTagUse*> (obj)) -#define SP_IS_TAG_USE(obj) (dynamic_cast<SPTagUse*> (obj) != NULL) +#define SP_TAG_USE(obj) (dynamic_cast<SPTagUse *>(obj)) +#define SP_IS_TAG_USE(obj) (dynamic_cast<SPTagUse *>(obj) != NULL) class SPItem; class SPTagUse; class SPTagUseReference; -class SPTagUse : public SPObject { - +class SPTagUse : public SPObject +{ public: // item built from the original's repr (the visible clone) // relative to the SPUse itself, it is treated as a child, similar to a grouped item relative to its group SPObject *child; gchar *href; + public: SPTagUse(); ~SPTagUse() override; - + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; void set(SPAttr key, gchar const *value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; void release() override; - - virtual void href_changed(SPObject* old_ref, SPObject* ref); - - //virtual SPItem* unlink(); - virtual SPItem* get_original(); - virtual SPItem* root(); + + virtual void href_changed(SPObject *old_ref, SPObject *ref); + + // virtual SPItem* unlink(); + virtual SPItem *get_original(); + virtual SPItem *root(); // the reference to the original object SPTagUseReference *ref; diff --git a/src/object/sp-tag.cpp b/src/object/sp-tag.cpp index cad4b26d90f5a1900e0de67f979199959be1155d..b644c84c381492219fb301f378c04b8c25f4e1b0 100644 --- a/src/object/sp-tag.cpp +++ b/src/object/sp-tag.cpp @@ -11,19 +11,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "attributes.h" #include "sp-tag.h" -#include "xml/repr.h" + #include <cstring> +#include "attributes.h" +#include "xml/repr.h" + /* * Move this SPItem into or after another SPItem in the doc * \param target - the SPItem to move into or after * \param intoafter - move to after the target (false), move inside (sublayer) of the target (true) */ -void SPTag::moveTo(SPObject *target, gboolean intoafter) { - - Inkscape::XML::Node *target_ref = ( target ? target->getRepr() : nullptr ); +void SPTag::moveTo(SPObject *target, gboolean intoafter) +{ + Inkscape::XML::Node *target_ref = (target ? target->getRepr() : nullptr); Inkscape::XML::Node *our_ref = getRepr(); gboolean first = FALSE; @@ -60,8 +62,7 @@ void SPTag::moveTo(SPObject *target, gboolean intoafter) { * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ -void -SPTag::build(SPDocument *document, Inkscape::XML::Node *repr) +void SPTag::build(SPDocument *document, Inkscape::XML::Node *repr) { readAttr(SPAttr::INKSCAPE_EXPANDED); SPObject::build(document, repr); @@ -70,40 +71,34 @@ SPTag::build(SPDocument *document, Inkscape::XML::Node *repr) /** * Sets a specific value in the SPTag. */ -void -SPTag::set(SPAttr key, gchar const *value) +void SPTag::set(SPAttr key, gchar const *value) { - - switch (key) - { + switch (key) { case SPAttr::INKSCAPE_EXPANDED: - if ( value && !strcmp(value, "true") ) { + if (value && !strcmp(value, "true")) { setExpanded(true); } break; default: - SPObject::set(key, value); + SPObject::set(key, value); break; } } -void SPTag::setExpanded(bool isexpanded) { - //if ( _expanded != isexpanded ){ - _expanded = isexpanded; +void SPTag::setExpanded(bool isexpanded) +{ + // if ( _expanded != isexpanded ){ + _expanded = isexpanded; //} } /** * Receives update notifications. */ -void -SPTag::update(SPCtx *ctx, guint flags) +void SPTag::update(SPCtx *ctx, guint flags) { - if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { - + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) { /* do something to trigger redisplay, updates? */ - } SPObject::update(ctx, flags); } @@ -111,13 +106,12 @@ SPTag::update(SPCtx *ctx, guint flags) /** * Writes its settings to an incoming repr object, if any. */ -Inkscape::XML::Node * -SPTag::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) +Inkscape::XML::Node *SPTag::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = doc->createElement("inkscape:tag"); } - + // Inkscape-only object, not copied during an "plain SVG" dump: if (flags & SP_OBJECT_WRITE_EXT) { if (_expanded) { @@ -130,7 +124,6 @@ SPTag::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flag return repr; } - /* Local Variables: mode:c++ diff --git a/src/object/sp-tag.h b/src/object/sp-tag.h index cab89fd80cce81f6686cb7077c32afff64b7cd77..a51bac7f20a5cf5ce8d81778c023334e31440df3 100644 --- a/src/object/sp-tag.h +++ b/src/object/sp-tag.h @@ -17,22 +17,23 @@ /* Skeleton base class */ -#define SP_TAG(o) (dynamic_cast<SPTag*>(o)) -#define SP_IS_TAG(o) (dynamic_cast<SPTag*>(o) != NULL) +#define SP_TAG(o) (dynamic_cast<SPTag *>(o)) +#define SP_IS_TAG(o) (dynamic_cast<SPTag *>(o) != NULL) class SPTag; -class SPTag : public SPObject { +class SPTag : public SPObject +{ public: SPTag() = default; ~SPTag() override = default; - void build(SPDocument * doc, Inkscape::XML::Node *repr) override; - //virtual void release(); - void set(SPAttr key, const gchar* value) override; - void update(SPCtx * ctx, unsigned flags) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + // virtual void release(); + void set(SPAttr key, const gchar *value) override; + void update(SPCtx *ctx, unsigned flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; bool expanded() const { return _expanded; } void setExpanded(bool isexpanded); @@ -43,7 +44,6 @@ private: bool _expanded; }; - #endif /* !SP_SKELETON_H_SEEN */ /* diff --git a/src/object/sp-text.cpp b/src/object/sp-text.cpp index 74729be76481722ff70a2f4f7c72f95973d9fe14..fed96a582e2c0f2e151f50eb951cc4f94baeaf08 100644 --- a/src/object/sp-text.cpp +++ b/src/object/sp-text.cpp @@ -24,48 +24,46 @@ * */ -#include <2geom/affine.h> -#include <libnrtype/FontFactory.h> -#include <libnrtype/font-instance.h> +#include "sp-text.h" +#include <2geom/affine.h> #include <glibmm/i18n.h> #include <glibmm/regex.h> +#include <libnrtype/FontFactory.h> +#include <libnrtype/font-instance.h> -#include "svg/svg.h" -#include "display/drawing-text.h" #include "attributes.h" -#include "document.h" -#include "preferences.h" -#include "desktop.h" #include "desktop-style.h" -#include "sp-namedview.h" +#include "desktop.h" +#include "display/drawing-text.h" +#include "document.h" #include "inkscape.h" -#include "xml/quote.h" #include "mod360.h" - -#include "sp-title.h" +#include "preferences.h" #include "sp-desc.h" +#include "sp-flowregion.h" +#include "sp-namedview.h" #include "sp-rect.h" -#include "sp-text.h" - #include "sp-shape.h" #include "sp-textpath.h" +#include "sp-title.h" #include "sp-tref.h" #include "sp-tspan.h" -#include "sp-flowregion.h" - +#include "svg/svg.h" #include "text-editing.h" +#include "xml/quote.h" // For SVG 2 text flow +#include "display/curve.h" #include "livarot/Path.h" #include "livarot/Shape.h" -#include "display/curve.h" /*##################################################### # SPTEXT #####################################################*/ -SPText::SPText() : SPItem() { -} +SPText::SPText() + : SPItem() +{} SPText::~SPText() { @@ -74,7 +72,8 @@ SPText::~SPText() } }; -void SPText::build(SPDocument *doc, Inkscape::XML::Node *repr) { +void SPText::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ this->readAttr(SPAttr::X); this->readAttr(SPAttr::Y); this->readAttr(SPAttr::DX); @@ -86,15 +85,17 @@ void SPText::build(SPDocument *doc, Inkscape::XML::Node *repr) { this->readAttr(SPAttr::LENGTHADJUST); SPItem::build(doc, repr); css = nullptr; - this->readAttr(SPAttr::SODIPODI_LINESPACING); // has to happen after the styles are read + this->readAttr(SPAttr::SODIPODI_LINESPACING); // has to happen after the styles are read } -void SPText::release() { +void SPText::release() +{ SPItem::release(); } -void SPText::set(SPAttr key, const gchar* value) { - //std::cout << "SPText::set: " << sp_attribute_name( key ) << ": " << (value?value:"Null") << std::endl; +void SPText::set(SPAttr key, const gchar *value) +{ + // std::cout << "SPText::set: " << sp_attribute_name( key ) << ": " << (value?value:"Null") << std::endl; if (this->attributes.readSingleAttribute(key, value, style, &viewport)) { this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); @@ -107,7 +108,8 @@ void SPText::set(SPAttr key, const gchar* value) { this->style->line_height.inherit = FALSE; this->style->line_height.normal = FALSE; this->style->line_height.unit = SP_CSS_UNIT_PERCENT; - this->style->line_height.value = this->style->line_height.computed = sp_svg_read_percentage (value, 1.0); + this->style->line_height.value = this->style->line_height.computed = + sp_svg_read_percentage(value, 1.0); } // Remove deprecated attribute this->removeAttribute("sodipodi:linespacing"); @@ -122,21 +124,22 @@ void SPText::set(SPAttr key, const gchar* value) { } } -void SPText::child_added(Inkscape::XML::Node *rch, Inkscape::XML::Node *ref) { +void SPText::child_added(Inkscape::XML::Node *rch, Inkscape::XML::Node *ref) +{ SPItem::child_added(rch, ref); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_TEXT_CONTENT_MODIFIED_FLAG | SP_TEXT_LAYOUT_MODIFIED_FLAG); } -void SPText::remove_child(Inkscape::XML::Node *rch) { +void SPText::remove_child(Inkscape::XML::Node *rch) +{ SPItem::remove_child(rch); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_TEXT_CONTENT_MODIFIED_FLAG | SP_TEXT_LAYOUT_MODIFIED_FLAG); } - -void SPText::update(SPCtx *ctx, guint flags) { - +void SPText::update(SPCtx *ctx, guint flags) +{ unsigned childflags = (flags & SP_OBJECT_MODIFIED_CASCADE); if (flags & SP_OBJECT_MODIFIED_FLAG) { childflags |= SP_OBJECT_PARENT_MODIFIED_FLAG; @@ -144,12 +147,12 @@ void SPText::update(SPCtx *ctx, guint flags) { // Create temporary list of children std::vector<SPObject *> l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child, this); l.push_back(&child); } - for (auto child:l) { + for (auto child : l) { if (childflags || (child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { /* fixme: Do we need transform? */ child->updateDisplay(ctx, childflags); @@ -160,19 +163,15 @@ void SPText::update(SPCtx *ctx, guint flags) { // update ourselves after updating children SPItem::update(ctx, flags); - if (flags & ( SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_CHILD_MODIFIED_FLAG | - SP_TEXT_LAYOUT_MODIFIED_FLAG ) ) - { - + if (flags & (SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_TEXT_LAYOUT_MODIFIED_FLAG)) { SPItemCtx const *ictx = reinterpret_cast<SPItemCtx const *>(ctx); double const w = ictx->viewport.width(); double const h = ictx->viewport.height(); double const em = style->font_size.computed; - double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. + double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. - attributes.update( em, ex, w, h ); + attributes.update(em, ex, w, h); // Set inline_size computed value if necessary (i.e. if unit is %). if (has_inline_size()) { @@ -192,7 +191,7 @@ void SPText::update(SPCtx *ctx, guint flags) { Geom::OptRect paintbox = this->geometricBounds(); - for (SPItemView* v = this->display; v != nullptr; v = v->next) { + for (SPItemView *v = this->display; v != nullptr; v = v->next) { Inkscape::DrawingGroup *g = dynamic_cast<Inkscape::DrawingGroup *>(v->arenaitem); this->_clearFlow(g); g->setStyle(this->style, this->parent->style); @@ -202,8 +201,9 @@ void SPText::update(SPCtx *ctx, guint flags) { } } -void SPText::modified(guint flags) { -// SPItem::onModified(flags); +void SPText::modified(guint flags) +{ + // SPItem::onModified(flags); guint cflags = (flags & SP_OBJECT_MODIFIED_CASCADE); @@ -215,10 +215,10 @@ void SPText::modified(guint flags) { // style, but there's no easy way to access the drawing glyphs or texts corresponding to a // text this. Therefore we do here the same as in _update, that is, destroy all items // and create new ones. This is probably quite wasteful. - if (flags & ( SP_OBJECT_STYLE_MODIFIED_FLAG )) { + if (flags & (SP_OBJECT_STYLE_MODIFIED_FLAG)) { Geom::OptRect paintbox = this->geometricBounds(); - for (SPItemView* v = this->display; v != nullptr; v = v->next) { + for (SPItemView *v = this->display; v != nullptr; v = v->next) { Inkscape::DrawingGroup *g = dynamic_cast<Inkscape::DrawingGroup *>(v->arenaitem); this->_clearFlow(g); g->setStyle(this->style, this->parent->style); @@ -228,12 +228,12 @@ void SPText::modified(guint flags) { // Create temporary list of children std::vector<SPObject *> l; - for (auto& child: children) { + for (auto &child : children) { sp_object_ref(&child, this); l.push_back(&child); } - for (auto child:l) { + for (auto child : l) { if (cflags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { child->emitModified(cflags); } @@ -241,7 +241,8 @@ void SPText::modified(guint flags) { } } -Inkscape::XML::Node *SPText::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPText::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if (flags & SP_OBJECT_WRITE_BUILD) { if (!repr) { repr = xml_doc->createElement("svg:text"); @@ -249,7 +250,7 @@ Inkscape::XML::Node *SPText::write(Inkscape::XML::Document *xml_doc, Inkscape::X std::vector<Inkscape::XML::Node *> l; - for (auto& child: children) { + for (auto &child : children) { if (SP_IS_TITLE(&child) || SP_IS_DESC(&child)) { continue; } @@ -267,12 +268,12 @@ Inkscape::XML::Node *SPText::write(Inkscape::XML::Document *xml_doc, Inkscape::X } } - for (auto i=l.rbegin();i!=l.rend();++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { + for (auto &child : children) { if (SP_IS_TITLE(&child) || SP_IS_DESC(&child)) { continue; } @@ -292,8 +293,8 @@ Inkscape::XML::Node *SPText::write(Inkscape::XML::Document *xml_doc, Inkscape::X return repr; } - -Geom::OptRect SPText::bbox(Geom::Affine const &transform, SPItem::BBoxType type) const { +Geom::OptRect SPText::bbox(Geom::Affine const &transform, SPItem::BBoxType type) const +{ Geom::OptRect bbox = SP_TEXT(this)->layout.bounds(transform); // FIXME this code is incorrect @@ -305,7 +306,8 @@ Geom::OptRect SPText::bbox(Geom::Affine const &transform, SPItem::BBoxType type) return bbox; } -Inkscape::DrawingItem* SPText::show(Inkscape::Drawing &drawing, unsigned /*key*/, unsigned /*flags*/) { +Inkscape::DrawingItem *SPText::show(Inkscape::Drawing &drawing, unsigned /*key*/, unsigned /*flags*/) +{ Inkscape::DrawingGroup *flowed = new Inkscape::DrawingGroup(drawing); flowed->setPickChildren(false); flowed->setStyle(this->style, this->parent->style); @@ -316,9 +318,9 @@ Inkscape::DrawingItem* SPText::show(Inkscape::Drawing &drawing, unsigned /*key*/ return flowed; } - -void SPText::hide(unsigned int key) { - for (SPItemView* v = this->display; v != nullptr; v = v->next) { +void SPText::hide(unsigned int key) +{ + for (SPItemView *v = this->display; v != nullptr; v = v->next) { if (v->key == key) { Inkscape::DrawingGroup *g = dynamic_cast<Inkscape::DrawingGroup *>(v->arenaitem); this->_clearFlow(g); @@ -326,7 +328,8 @@ void SPText::hide(unsigned int key) { } } -const char* SPText::displayName() const { +const char *SPText::displayName() const +{ if (has_inline_size()) { return _("Auto-wrapped text"); } else if (has_shape_inside()) { @@ -336,8 +339,8 @@ const char* SPText::displayName() const { } } -gchar* SPText::description() const { - +gchar *SPText::description() const +{ SPStyle *style = this->style; char *n = xml_quote_strdup(style->font_family.value()); @@ -349,19 +352,19 @@ gchar* SPText::description() const { Glib::ustring xs = q.string(sp_style_get_css_unit_string(unit)); char const *trunc = ""; - Inkscape::Text::Layout const *layout = te_get_layout((SPItem *) this); + Inkscape::Text::Layout const *layout = te_get_layout((SPItem *)this); if (layout && layout->inputTruncated()) { trunc = _(" [truncated]"); } - char *ret = ( SP_IS_TEXT_TEXTPATH(this) - ? g_strdup_printf(_("on path%s (%s, %s)"), trunc, n, xs.c_str()) - : g_strdup_printf(_("%s (%s, %s)"), trunc, n, xs.c_str()) ); + char *ret = (SP_IS_TEXT_TEXTPATH(this) ? g_strdup_printf(_("on path%s (%s, %s)"), trunc, n, xs.c_str()) + : g_strdup_printf(_("%s (%s, %s)"), trunc, n, xs.c_str())); return ret; } -void SPText::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const { +void SPText::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const +{ if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_TEXT_BASELINE)) { // Choose a point on the baseline for snapping from or to, with the horizontal position // of this point depending on the text alignment (left vs. right) @@ -371,7 +374,8 @@ void SPText::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape:: boost::optional<Geom::Point> pt = layout->baselineAnchorPoint(); if (pt) { - p.emplace_back((*pt) * this->i2dt_affine(), Inkscape::SNAPSOURCE_TEXT_ANCHOR, Inkscape::SNAPTARGET_TEXT_ANCHOR); + p.emplace_back((*pt) * this->i2dt_affine(), Inkscape::SNAPSOURCE_TEXT_ANCHOR, + Inkscape::SNAPTARGET_TEXT_ANCHOR); } } } @@ -400,7 +404,8 @@ void SPText::show_shape_inside() } } -Geom::Affine SPText::set_transform(Geom::Affine const &xform) { +Geom::Affine SPText::set_transform(Geom::Affine const &xform) +{ // See if 'shape-inside' has rectangle Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs->getBool("/tools/text/use_svg2", true)) { @@ -410,7 +415,7 @@ Geom::Affine SPText::set_transform(Geom::Affine const &xform) { } // we cannot optimize textpath because changing its fontsize will break its match to the path - if (SP_IS_TEXT_TEXTPATH (this)) { + if (SP_IS_TEXT_TEXTPATH(this)) { if (!this->_optimizeTextpathText) { return xform; } else { @@ -428,12 +433,12 @@ Geom::Affine SPText::set_transform(Geom::Affine const &xform) { /* This function takes care of scaling & translation only, we return whatever parts we can't handle. */ -// TODO: pjrm tried to use fontsize_expansion(xform) here and it works for text in that font size -// is scaled more intuitively when scaling non-uniformly; however this necessitated using -// fontsize_expansion instead of expansion in other places too, where it was not appropriate -// (e.g. it broke stroke width on copy/pasting of style from horizontally stretched to vertically -// stretched shape). Using fontsize_expansion only here broke setting the style via font -// dialog. This needs to be investigated further. + // TODO: pjrm tried to use fontsize_expansion(xform) here and it works for text in that font size + // is scaled more intuitively when scaling non-uniformly; however this necessitated using + // fontsize_expansion instead of expansion in other places too, where it was not appropriate + // (e.g. it broke stroke width on copy/pasting of style from horizontally stretched to vertically + // stretched shape). Using fontsize_expansion only here broke setting the style via font + // dialog. This needs to be investigated further. double const ex = xform.descrim(); if (ex == 0) { return xform; @@ -446,13 +451,13 @@ Geom::Affine SPText::set_transform(Geom::Affine const &xform) { ret[3] /= ex; // Adjust x/y, dx/dy - this->_adjustCoordsRecursive (this, xform * ret.inverse(), ex); + this->_adjustCoordsRecursive(this, xform * ret.inverse(), ex); // Adjust font size - this->_adjustFontsizeRecursive (this, ex); + this->_adjustFontsizeRecursive(this, ex); // Adjust stroke width - this->adjust_stroke_width_recursive (ex); + this->adjust_stroke_width_recursive(ex); // Adjust pattern fill this->adjust_pattern(xform * ret.inverse()); @@ -463,15 +468,16 @@ Geom::Affine SPText::set_transform(Geom::Affine const &xform) { return ret; } -void SPText::print(SPPrintContext *ctx) { +void SPText::print(SPPrintContext *ctx) +{ Geom::OptRect pbox, bbox, dbox; pbox = this->geometricBounds(); bbox = this->desktopVisualBounds(); - dbox = Geom::Rect::from_xywh(Geom::Point(0,0), this->document->getDimensions()); + dbox = Geom::Rect::from_xywh(Geom::Point(0, 0), this->document->getDimensions()); - Geom::Affine const ctm (this->i2dt_affine()); + Geom::Affine const ctm(this->i2dt_affine()); - this->layout.print(ctx,pbox,dbox,bbox,ctm); + this->layout.print(ctx, pbox, dbox, bbox, ctm); } /* @@ -480,38 +486,34 @@ void SPText::print(SPPrintContext *ctx) { void SPText::_buildLayoutInit() { - layout.strut.reset(); layout.wrap_mode = Inkscape::Text::Layout::WRAP_NONE; // Default to SVG 1.1 if (style) { - // Strut - font_instance *font = font_factory::Default()->FaceFromStyle( style ); + font_instance *font = font_factory::Default()->FaceFromStyle(style); if (font) { font->FontMetrics(layout.strut.ascent, layout.strut.descent, layout.strut.xheight); font->Unref(); } layout.strut *= style->font_size.computed; - if (style->line_height.normal ) { - layout.strut.computeEffective( Inkscape::Text::Layout::LINE_HEIGHT_NORMAL ); + if (style->line_height.normal) { + layout.strut.computeEffective(Inkscape::Text::Layout::LINE_HEIGHT_NORMAL); } else if (style->line_height.unit == SP_CSS_UNIT_NONE) { - layout.strut.computeEffective( style->line_height.computed ); + layout.strut.computeEffective(style->line_height.computed); } else { - if( style->font_size.computed > 0.0 ) { - layout.strut.computeEffective( style->line_height.computed/style->font_size.computed ); + if (style->font_size.computed > 0.0) { + layout.strut.computeEffective(style->line_height.computed / style->font_size.computed); } } - // To do: follow SPItem clip_ref/mask_ref code - if (style->shape_inside.set ) { - + if (style->shape_inside.set) { layout.wrap_mode = Inkscape::Text::Layout::WRAP_SHAPE_INSIDE; // Find union of all exclusion shapes Shape *exclusion_shape = nullptr; - if(style->shape_subtract.set) { + if (style->shape_subtract.set) { exclusion_shape = _buildExclusionShape(); } @@ -519,62 +521,61 @@ void SPText::_buildLayoutInit() for (auto *href : style->shape_inside.hrefs) { auto shape = href->getObject(); - if ( shape ) { - - // This code adapted from sp-flowregion.cpp: GetDest() - if (!shape->curve()) { - shape->set_shape(); + if (shape) { + // This code adapted from sp-flowregion.cpp: GetDest() + if (!shape->curve()) { + shape->set_shape(); + } + SPCurve const *curve = shape->curve(); + + if (curve) { + Path *temp = new Path; + Path *padded = new Path; + temp->LoadPathVector(curve->get_pathvector(), shape->transform, true); + if (style->shape_padding.set) { + // std::cout << " padding: " << style->shape_padding.computed << std::endl; + temp->OutsideOutline(padded, style->shape_padding.computed, join_round, butt_straight, + 20.0); + } else { + // std::cout << " no padding" << std::endl; + padded->Copy(temp); } - SPCurve const *curve = shape->curve(); - - if ( curve ) { - Path *temp = new Path; - Path *padded = new Path; - temp->LoadPathVector( curve->get_pathvector(), shape->transform, true ); - if( style->shape_padding.set ) { - // std::cout << " padding: " << style->shape_padding.computed << std::endl; - temp->OutsideOutline ( padded, style->shape_padding.computed, join_round, butt_straight, 20.0 ); + padded->Convert(0.25); // Convert to polyline + Shape *sh = new Shape; + padded->Fill(sh, 0); + // for( unsigned i = 0; i < temp->pts.size(); ++i ) { + // std::cout << " ........ " << temp->pts[i].p << std::endl; + // } + // std::cout << " ...... shape: " << sh->numberOfPoints() << std::endl; + Shape *uncross = new Shape; + uncross->ConvertToShape(sh); + + // Subtract exclusion shape + if (style->shape_subtract.set) { + Shape *copy = new Shape; + if (exclusion_shape && exclusion_shape->hasEdges()) { + copy->Booleen(uncross, const_cast<Shape *>(exclusion_shape), bool_op_diff); } else { - // std::cout << " no padding" << std::endl; - padded->Copy( temp ); - } - padded->Convert( 0.25 ); // Convert to polyline - Shape* sh = new Shape; - padded->Fill( sh, 0 ); - // for( unsigned i = 0; i < temp->pts.size(); ++i ) { - // std::cout << " ........ " << temp->pts[i].p << std::endl; - // } - // std::cout << " ...... shape: " << sh->numberOfPoints() << std::endl; - Shape *uncross = new Shape; - uncross->ConvertToShape( sh ); - - // Subtract exclusion shape - if(style->shape_subtract.set) { - Shape *copy = new Shape; - if (exclusion_shape && exclusion_shape->hasEdges()) { - copy->Booleen(uncross, const_cast<Shape*>(exclusion_shape), bool_op_diff); - } else { - copy->Copy(uncross); - } - layout.appendWrapShape( copy ); - continue; + copy->Copy(uncross); } + layout.appendWrapShape(copy); + continue; + } - layout.appendWrapShape( uncross ); + layout.appendWrapShape(uncross); - delete temp; - delete padded; - delete sh; - // delete uncross; - } else { - std::cerr << "SPText::_buildLayoutInit(): Failed to get curve." << std::endl; - } + delete temp; + delete padded; + delete sh; + // delete uncross; + } else { + std::cerr << "SPText::_buildLayoutInit(): Failed to get curve." << std::endl; + } } } delete exclusion_shape; } else if (has_inline_size()) { - layout.wrap_mode = Inkscape::Text::Layout::WRAP_INLINE_SIZE; // If both shape_inside and inline_size are set, shape_inside wins out. @@ -597,22 +598,24 @@ void SPText::_buildLayoutInit() shape->AddEdge(v2, v3); shape->AddEdge(v3, v0); Shape *uncross = new Shape; - uncross->ConvertToShape( shape ); + uncross->ConvertToShape(shape); - layout.appendWrapShape( uncross ); + layout.appendWrapShape(uncross); delete shape; - } else if (style->white_space.value == SP_CSS_WHITE_SPACE_PRE || + } else if (style->white_space.value == SP_CSS_WHITE_SPACE_PRE || style->white_space.value == SP_CSS_WHITE_SPACE_PREWRAP || - style->white_space.value == SP_CSS_WHITE_SPACE_PRELINE ) { + style->white_space.value == SP_CSS_WHITE_SPACE_PRELINE) { layout.wrap_mode = Inkscape::Text::Layout::WRAP_WHITE_SPACE; } } // if (style) } -unsigned SPText::_buildLayoutInput(SPObject *object, Inkscape::Text::Layout::OptionalTextTagAttrs const &parent_optional_attrs, unsigned parent_attrs_offset, bool in_textpath) +unsigned SPText::_buildLayoutInput(SPObject *object, + Inkscape::Text::Layout::OptionalTextTagAttrs const &parent_optional_attrs, + unsigned parent_attrs_offset, bool in_textpath) { unsigned length = 0; unsigned child_attrs_offset = 0; @@ -623,13 +626,12 @@ unsigned SPText::_buildLayoutInput(SPObject *object, Inkscape::Text::Layout::Opt return 0; } - SPText* text_object = dynamic_cast<SPText*>(object); - SPTSpan* tspan_object = dynamic_cast<SPTSpan*>(object); - SPTRef* tref_object = dynamic_cast<SPTRef*>(object); - SPTextPath* textpath_object = dynamic_cast<SPTextPath*>(object); + SPText *text_object = dynamic_cast<SPText *>(object); + SPTSpan *tspan_object = dynamic_cast<SPTSpan *>(object); + SPTRef *tref_object = dynamic_cast<SPTRef *>(object); + SPTextPath *textpath_object = dynamic_cast<SPTextPath *>(object); if (text_object) { - bool use_xy = true; bool use_dxdyrotate = true; @@ -640,11 +642,11 @@ unsigned SPText::_buildLayoutInput(SPObject *object, Inkscape::Text::Layout::Opt use_dxdyrotate = false; } - text_object->attributes.mergeInto(&optional_attrs, parent_optional_attrs, parent_attrs_offset, use_xy, use_dxdyrotate); + text_object->attributes.mergeInto(&optional_attrs, parent_optional_attrs, parent_attrs_offset, use_xy, + use_dxdyrotate); // SVG 2 Text wrapping if (layout.wrap_mode == Inkscape::Text::Layout::WRAP_INLINE_SIZE) { - // For horizontal text: // 'x' is used to calculate the left/right edges of the rectangle but is not // needed later. If not deleted here, it will cause an incorrect positioning @@ -659,19 +661,21 @@ unsigned SPText::_buildLayoutInput(SPObject *object, Inkscape::Text::Layout::Opt // we've found 'x' and 'y' and then creating the Shape at the end.) if (is_horizontal()) { // Horizontal text - SVGLength* y = _getFirstYLength(); + SVGLength *y = _getFirstYLength(); if (y) { optional_attrs.y.push_back(*y); } else { - std::cerr << "SPText::_buildLayoutInput: No 'y' attribute value with horizontal 'inline-size'!" << std::endl; + std::cerr << "SPText::_buildLayoutInput: No 'y' attribute value with horizontal 'inline-size'!" + << std::endl; } } else { // Vertical text - SVGLength* x = _getFirstXLength(); + SVGLength *x = _getFirstXLength(); if (x) { optional_attrs.x.push_back(*x); } else { - std::cerr << "SPText::_buildLayoutInput: No 'x' attribute value with vertical 'inline-size'!" << std::endl; + std::cerr << "SPText::_buildLayoutInput: No 'x' attribute value with vertical 'inline-size'!" + << std::endl; } } } @@ -679,19 +683,18 @@ unsigned SPText::_buildLayoutInput(SPObject *object, Inkscape::Text::Layout::Opt // set textLength on the entire layout, see note in TNG-Layout.h if (text_object->attributes.getTextLength()->_set) { layout.textLength._set = true; - layout.textLength.value = text_object->attributes.getTextLength()->value; + layout.textLength.value = text_object->attributes.getTextLength()->value; layout.textLength.computed = text_object->attributes.getTextLength()->computed; - layout.textLength.unit = text_object->attributes.getTextLength()->unit; - layout.lengthAdjust = (Inkscape::Text::Layout::LengthAdjust) text_object->attributes.getLengthAdjust(); + layout.textLength.unit = text_object->attributes.getTextLength()->unit; + layout.lengthAdjust = (Inkscape::Text::Layout::LengthAdjust)text_object->attributes.getLengthAdjust(); } } else if (tspan_object) { - // x, y attributes are stripped from some tspans marked with role="line" as we do our own line layout. // This should be checked carefully, as it can undo line layout in imported SVG files. - bool use_xy = !in_textpath && - (tspan_object->role == SP_TSPAN_ROLE_UNSPECIFIED || !tspan_object->attributes.singleXYCoordinates()); + bool use_xy = !in_textpath && (tspan_object->role == SP_TSPAN_ROLE_UNSPECIFIED || + !tspan_object->attributes.singleXYCoordinates()); bool use_dxdyrotate = true; // SVG 2 Text wrapping: see comment above. @@ -701,14 +704,15 @@ unsigned SPText::_buildLayoutInput(SPObject *object, Inkscape::Text::Layout::Opt use_dxdyrotate = false; } - tspan_object->attributes.mergeInto(&optional_attrs, parent_optional_attrs, parent_attrs_offset, use_xy, use_dxdyrotate); + tspan_object->attributes.mergeInto(&optional_attrs, parent_optional_attrs, parent_attrs_offset, use_xy, + use_dxdyrotate); if (tspan_object->role != SP_TSPAN_ROLE_UNSPECIFIED) { // We are doing line wrapping using sodipodi:role="line". New lines have been stripped. // Insert paragraph break before text if not first tspan. SPObject *prev_object = object->getPrev(); - if (prev_object && dynamic_cast<SPTSpan*>(prev_object)) { + if (prev_object && dynamic_cast<SPTSpan *>(prev_object)) { if (!layout.inputExists()) { // Add an object to store style, needed even if there is no text. When does this happen? layout.appendText("", prev_object->style, prev_object, &optional_attrs); @@ -721,12 +725,12 @@ unsigned SPText::_buildLayoutInput(SPObject *object, Inkscape::Text::Layout::Opt layout.appendText("", object->style, object, &optional_attrs); } - length++; // interpreting line breaks as a character for the purposes of x/y/etc attributes - // is a liberal interpretation of the svg spec, but a strict reading would mean - // that if the first line is empty the second line would take its place at the - // start position. Very confusing. - // SVG 2 clarifies, attributes are matched to unicode input characters so line - // breaks do match to an x/y/etc attribute. + length++; // interpreting line breaks as a character for the purposes of x/y/etc attributes + // is a liberal interpretation of the svg spec, but a strict reading would mean + // that if the first line is empty the second line would take its place at the + // start position. Very confusing. + // SVG 2 clarifies, attributes are matched to unicode input characters so line + // breaks do match to an x/y/etc attribute. child_attrs_offset--; } } @@ -748,7 +752,7 @@ unsigned SPText::_buildLayoutInput(SPObject *object, Inkscape::Text::Layout::Opt } // Recurse - for (auto& child: object->children) { + for (auto &child : object->children) { SPString *str = dynamic_cast<SPString *>(&child); if (str) { Glib::ustring const &string = str->string; @@ -764,7 +768,7 @@ unsigned SPText::_buildLayoutInput(SPObject *object, Inkscape::Text::Layout::Opt return length; } -Shape* SPText::_buildExclusionShape() const +Shape *SPText::_buildExclusionShape() const { std::unique_ptr<Shape> result(new Shape()); // Union of all exclusion shapes std::unique_ptr<Shape> shape_temp(new Shape()); @@ -772,53 +776,51 @@ Shape* SPText::_buildExclusionShape() const for (auto *href : style->shape_subtract.hrefs) { auto shape = href->getObject(); - if ( shape ) { - // This code adapted from sp-flowregion.cpp: GetDest() - if (!shape->curve()) { - shape->set_shape(); - } - SPCurve const *curve = shape->curve(); + if (shape) { + // This code adapted from sp-flowregion.cpp: GetDest() + if (!shape->curve()) { + shape->set_shape(); + } + SPCurve const *curve = shape->curve(); - if ( curve ) { - Path *temp = new Path; - Path *margin = new Path; - temp->LoadPathVector( curve->get_pathvector(), shape->transform, true ); + if (curve) { + Path *temp = new Path; + Path *margin = new Path; + temp->LoadPathVector(curve->get_pathvector(), shape->transform, true); - if( shape->style->shape_margin.set ) { - temp->OutsideOutline ( margin, -shape->style->shape_margin.computed, join_round, butt_straight, 20.0 ); - } else { - margin->Copy( temp ); - } + if (shape->style->shape_margin.set) { + temp->OutsideOutline(margin, -shape->style->shape_margin.computed, join_round, butt_straight, 20.0); + } else { + margin->Copy(temp); + } - margin->Convert( 0.25 ); // Convert to polyline - Shape* sh = new Shape; - margin->Fill( sh, 0 ); + margin->Convert(0.25); // Convert to polyline + Shape *sh = new Shape; + margin->Fill(sh, 0); - Shape *uncross = new Shape; - uncross->ConvertToShape( sh ); + Shape *uncross = new Shape; + uncross->ConvertToShape(sh); - if (result->hasEdges()) { - shape_temp->Booleen(result.get(), uncross, bool_op_union); - std::swap(result, shape_temp); - } else { - result->Copy(uncross); - } + if (result->hasEdges()) { + shape_temp->Booleen(result.get(), uncross, bool_op_union); + std::swap(result, shape_temp); + } else { + result->Copy(uncross); } } + } } return result.release(); } - // SVG requires one to use the first x/y value found on a child element if x/y not given on text // element. TODO: Recurse. -SVGLength* -SPText::_getFirstXLength() +SVGLength *SPText::_getFirstXLength() { - SVGLength* x = attributes.getFirstXLength(); + SVGLength *x = attributes.getFirstXLength(); if (!x) { - for (auto& child: children) { + for (auto &child : children) { if (SP_IS_TSPAN(&child)) { SPTSpan *tspan = SP_TSPAN(&child); x = tspan->attributes.getFirstXLength(); @@ -830,14 +832,12 @@ SPText::_getFirstXLength() return x; } - -SVGLength* -SPText::_getFirstYLength() +SVGLength *SPText::_getFirstYLength() { - SVGLength* y = attributes.getFirstYLength(); + SVGLength *y = attributes.getFirstYLength(); if (!y) { - for (auto& child: children) { + for (auto &child : children) { if (SP_IS_TSPAN(&child)) { SPTSpan *tspan = SP_TSPAN(&child); y = tspan->attributes.getFirstYLength(); @@ -864,7 +864,7 @@ void SPText::rebuildLayout() layout.calculateFlow(); - for (auto& child: children) { + for (auto &child : children) { if (SP_IS_TEXTPATH(&child)) { SPTextPath const *textpath = SP_TEXTPATH(&child); if (textpath->originalPath != nullptr) { @@ -880,11 +880,10 @@ void SPText::rebuildLayout() #endif // set the x,y attributes on role:line spans - for (auto& child: children) { + for (auto &child : children) { if (SP_IS_TSPAN(&child)) { SPTSpan *tspan = SP_TSPAN(&child); - if ((tspan->role != SP_TSPAN_ROLE_UNSPECIFIED) - && tspan->attributes.singleXYCoordinates() ) { + if ((tspan->role != SP_TSPAN_ROLE_UNSPECIFIED) && tspan->attributes.singleXYCoordinates()) { Inkscape::Text::Layout::iterator iter = layout.sourceToIterator(tspan); Geom::Point anchor_point = layout.chunkAnchorPoint(iter); tspan->attributes.setFirstXY(anchor_point); @@ -894,7 +893,6 @@ void SPText::rebuildLayout() } } - void SPText::_adjustFontsizeRecursive(SPItem *item, double ex, bool is_root) { SPStyle *style = item->style; @@ -907,27 +905,24 @@ void SPText::_adjustFontsizeRecursive(SPItem *item, double ex, bool is_root) style->font_size.computed *= ex; style->letter_spacing.computed *= ex; style->word_spacing.computed *= ex; - if (style->line_height.unit != SP_CSS_UNIT_NONE && - style->line_height.unit != SP_CSS_UNIT_PERCENT && - style->line_height.unit != SP_CSS_UNIT_EM && - style->line_height.unit != SP_CSS_UNIT_EX) { + if (style->line_height.unit != SP_CSS_UNIT_NONE && style->line_height.unit != SP_CSS_UNIT_PERCENT && + style->line_height.unit != SP_CSS_UNIT_EM && style->line_height.unit != SP_CSS_UNIT_EX) { // No unit on 'line-height' property has special behavior. style->line_height.computed *= ex; } item->updateRepr(); } - for(auto& o: item->children) { + for (auto &o : item->children) { if (SP_IS_ITEM(&o)) _adjustFontsizeRecursive(SP_ITEM(&o), ex, false); } } -void -remove_newlines_recursive(SPObject* object, bool is_svg2) +void remove_newlines_recursive(SPObject *object, bool is_svg2) { // Replace '\n' by space. - SPString* string = dynamic_cast<SPString *>(object); + SPString *string = dynamic_cast<SPString *>(object); if (string) { static Glib::RefPtr<Glib::Regex> r = Glib::Regex::create("\n+"); string->string = r->replace(string->string, 0, " ", (Glib::RegexMatchFlags)0); @@ -939,17 +934,16 @@ remove_newlines_recursive(SPObject* object, bool is_svg2) } // Add space at end of a line if line is created by sodipodi:role="line". - SPTSpan* tspan = dynamic_cast<SPTSpan *>(object); - if (tspan && - tspan->role == SP_TSPAN_ROLE_LINE && - tspan->getNext() != nullptr && // Don't add space at end of last line. - !is_svg2) { // SVG2 uses newlines, should not have sodipodi:role. + SPTSpan *tspan = dynamic_cast<SPTSpan *>(object); + if (tspan && tspan->role == SP_TSPAN_ROLE_LINE && + tspan->getNext() != nullptr && // Don't add space at end of last line. + !is_svg2) { // SVG2 uses newlines, should not have sodipodi:role. std::vector<SPObject *> children = tspan->childList(false); // Find last string (could be more than one if there is tspan in the middle of a tspan). for (auto it = children.rbegin(); it != children.rend(); ++it) { - SPString* string = dynamic_cast<SPString *>(*it); + SPString *string = dynamic_cast<SPString *>(*it); if (string) { string->string += ' '; string->getRepr()->setContent(string->string.c_str()); @@ -960,8 +954,7 @@ remove_newlines_recursive(SPObject* object, bool is_svg2) } // Prepare multi-line text for putting on path. -void -SPText::remove_newlines() +void SPText::remove_newlines() { remove_newlines_recursive(this, has_shape_inside() || has_inline_size()); style->inline_size.clear(); @@ -973,7 +966,7 @@ void SPText::_adjustCoordsRecursive(SPItem *item, Geom::Affine const &m, double { if (SP_IS_TSPAN(item)) SP_TSPAN(item)->attributes.transform(m, ex, ex, is_root); - // it doesn't matter if we change the x,y for role=line spans because we'll just overwrite them anyway + // it doesn't matter if we change the x,y for role=line spans because we'll just overwrite them anyway else if (SP_IS_TEXT(item)) SP_TEXT(item)->attributes.transform(m, ex, ex, is_root); else if (SP_IS_TEXTPATH(item)) @@ -982,27 +975,26 @@ void SPText::_adjustCoordsRecursive(SPItem *item, Geom::Affine const &m, double SP_TREF(item)->attributes.transform(m, ex, ex, is_root); } else { g_warning("element is not text"); - return; + return; } - for(auto& o: item->children) { + for (auto &o : item->children) { if (SP_IS_ITEM(&o)) _adjustCoordsRecursive(SP_ITEM(&o), m, ex, false); } } - void SPText::_clearFlow(Inkscape::DrawingGroup *in_arena) { in_arena->clearChildren(); } - /** Remove 'x' and 'y' values on children (lines) or they will be interpreted as absolute positions * when 'inline-size' is removed. */ -void SPText::remove_svg11_fallback() { - for (auto& child: children) { +void SPText::remove_svg11_fallback() +{ + for (auto &child : children) { child.removeAttribute("x"); child.removeAttribute("y"); } @@ -1011,18 +1003,17 @@ void SPText::remove_svg11_fallback() { /** Convert new lines in 'inline-size' text to tspans with sodipodi:role="tspan". * Note sodipodi:role="tspan" will be removed in the future! */ -void SPText::newline_to_sodipodi() { - +void SPText::newline_to_sodipodi() +{ // New lines can come anywhere, we must search character-by-character. auto it = layout.begin(); while (it != layout.end()) { if (layout.characterAt(it) == '\n') { - // Delete newline ('\n'). iterator_pair pair; auto it_end = it; it_end.nextCharacter(); - sp_te_delete (this, it, it_end, pair); + sp_te_delete(this, it, it_end, pair); it = pair.first; // Insert newline (sodipodi:role="line"). @@ -1037,14 +1028,12 @@ void SPText::newline_to_sodipodi() { /** Convert tspans with sodipodi:role="tspans" to '\n'. * Note sodipodi:role="tspan" will be removed in the future! */ -void SPText::sodipodi_to_newline() { - +void SPText::sodipodi_to_newline() +{ // tspans with sodipodi:role="line" are only direct children of a <text> element. for (auto child : childList(false)) { - - auto tspan = dynamic_cast<SPTSpan *>(child); // Could have <desc> or <title>. + auto tspan = dynamic_cast<SPTSpan *>(child); // Could have <desc> or <title>. if (tspan && tspan->role == SP_TSPAN_ROLE_LINE) { - // Remove sodipodi:role attribute. tspan->removeAttribute("sodipodi:role"); tspan->updateRepr(); @@ -1094,26 +1083,26 @@ Geom::OptRect SPText::get_frame() if (has_inline_size()) { double inline_size = style->inline_size.computed; - //unsigned mode = style->writing_mode.computed; - unsigned anchor = style->text_anchor.computed; + // unsigned mode = style->writing_mode.computed; + unsigned anchor = style->text_anchor.computed; unsigned direction = style->direction.computed; if (is_horizontal()) { // horizontal frame = Geom::Rect::from_xywh(attributes.firstXY()[Geom::X], -100000, inline_size, 200000); if (anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { - frame *= Geom::Translate (-inline_size/2.0, 0 ); - } else if ( (direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_END ) || - (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_START) ) { - frame *= Geom::Translate (-inline_size, 0); + frame *= Geom::Translate(-inline_size / 2.0, 0); + } else if ((direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_END) || + (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_START)) { + frame *= Geom::Translate(-inline_size, 0); } } else { // vertical frame = Geom::Rect::from_xywh(-100000, attributes.firstXY()[Geom::Y], 200000, inline_size); if (anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { - frame *= Geom::Translate (0, -inline_size/2.0); + frame *= Geom::Translate(0, -inline_size / 2.0); } else if (anchor == SP_CSS_TEXT_ANCHOR_END) { - frame *= Geom::Translate (0, -inline_size); + frame *= Geom::Translate(0, -inline_size); } } @@ -1121,18 +1110,18 @@ Geom::OptRect SPText::get_frame() } else { // See if 'shape-inside' has rectangle - Inkscape::XML::Node* rectangle = get_first_rectangle(); + Inkscape::XML::Node *rectangle = get_first_rectangle(); if (rectangle) { double x = 0.0; double y = 0.0; double width = 0.0; double height = 0.0; - sp_repr_get_double (rectangle, "x", &x); - sp_repr_get_double (rectangle, "y", &y); - sp_repr_get_double (rectangle, "width", &width); - sp_repr_get_double (rectangle, "height", &height); - frame = Geom::Rect::from_xywh( x, y, width, height); + sp_repr_get_double(rectangle, "x", &x); + sp_repr_get_double(rectangle, "y", &y); + sp_repr_get_double(rectangle, "width", &width); + sp_repr_get_double(rectangle, "height", &height); + frame = Geom::Rect::from_xywh(x, y, width, height); opt_frame = frame; } } @@ -1141,13 +1130,12 @@ Geom::OptRect SPText::get_frame() } // Find the node of the first rectangle (if it exists) in 'shape-inside'. -Inkscape::XML::Node* SPText::get_first_rectangle() +Inkscape::XML::Node *SPText::get_first_rectangle() { if (style->shape_inside.set) { - for (auto *href : style->shape_inside.hrefs) { auto *shape = href->getObject(); - if (dynamic_cast<SPRect*>(shape)) { + if (dynamic_cast<SPRect *>(shape)) { auto *item = shape->getRepr(); g_return_val_if_fail(item, nullptr); assert(strncmp("svg:rect", item->name(), 8) == 0); @@ -1159,7 +1147,7 @@ Inkscape::XML::Node* SPText::get_first_rectangle() return nullptr; } -SPItem *create_text_with_inline_size (SPDesktop *desktop, Geom::Point p0, Geom::Point p1) +SPItem *create_text_with_inline_size(SPDesktop *desktop, Geom::Point p0, Geom::Point p1) { SPDocument *doc = desktop->getDocument(); @@ -1178,12 +1166,12 @@ SPItem *create_text_with_inline_size (SPDesktop *desktop, Geom::Point p0, Geom:: p0 *= SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); p1 *= SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); - sp_repr_set_svg_double( text_repr, "x", p0[Geom::X]); - sp_repr_set_svg_double( text_repr, "y", p0[Geom::Y]); + sp_repr_set_svg_double(text_repr, "x", p0[Geom::X]); + sp_repr_set_svg_double(text_repr, "y", p0[Geom::Y]); double inline_size = p1[Geom::X] - p0[Geom::X]; - text_object->style->inline_size.setDouble( inline_size ); + text_object->style->inline_size.setDouble(inline_size); text_object->style->inline_size.set = true; Inkscape::XML::Node *text_node = xml_doc->createTextNode(""); @@ -1202,7 +1190,7 @@ SPItem *create_text_with_inline_size (SPDesktop *desktop, Geom::Point p0, Geom:: return text_object; } -SPItem *create_text_with_rectangle (SPDesktop *desktop, Geom::Point p0, Geom::Point p1) +SPItem *create_text_with_rectangle(SPDesktop *desktop, Geom::Point p0, Geom::Point p1) { SPDocument *doc = desktop->getDocument(); @@ -1223,38 +1211,38 @@ SPItem *create_text_with_rectangle (SPDesktop *desktop, Geom::Point p0, Geom::Po // Create rectangle Inkscape::XML::Node *rect_repr = xml_doc->createElement("svg:rect"); - sp_repr_set_svg_double( rect_repr, "x", p0[Geom::X]); - sp_repr_set_svg_double( rect_repr, "y", p0[Geom::Y]); - sp_repr_set_svg_double( rect_repr, "width", abs(p1[Geom::X]-p0[Geom::X])); - sp_repr_set_svg_double( rect_repr, "height", abs(p1[Geom::Y]-p0[Geom::Y])); + sp_repr_set_svg_double(rect_repr, "x", p0[Geom::X]); + sp_repr_set_svg_double(rect_repr, "y", p0[Geom::Y]); + sp_repr_set_svg_double(rect_repr, "width", abs(p1[Geom::X] - p0[Geom::X])); + sp_repr_set_svg_double(rect_repr, "height", abs(p1[Geom::Y] - p0[Geom::Y])); // Find defs, if does not exist, create. - Inkscape::XML::Node *defs_repr = sp_repr_lookup_name (xml_doc->root(), "svg:defs"); + Inkscape::XML::Node *defs_repr = sp_repr_lookup_name(xml_doc->root(), "svg:defs"); if (defs_repr == nullptr) { defs_repr = xml_doc->createElement("svg:defs"); xml_doc->root()->addChild(defs_repr, nullptr); - } - else Inkscape::GC::anchor(defs_repr); + } else + Inkscape::GC::anchor(defs_repr); // Add rectangle to defs. defs_repr->addChild(rect_repr, nullptr); // Apply desktop style (do before adding "shape-inside"). sp_desktop_apply_style_tool(desktop, text_repr, "/tools/text", true); - SPCSSAttr *css = sp_repr_css_attr(text_repr, "style" ); + SPCSSAttr *css = sp_repr_css_attr(text_repr, "style"); Geom::Affine const local(text_object->i2doc_affine()); double const ex(local.descrim()); - if ( (ex != 0.0) && (ex != 1.0) ) { - sp_css_attr_scale(css, 1/ex); + if ((ex != 0.0) && (ex != 1.0)) { + sp_css_attr_scale(css, 1 / ex); } - sp_repr_css_set_property (css, "white-space", "pre"); // Respect new lines. + sp_repr_css_set_property(css, "white-space", "pre"); // Respect new lines. // Link rectangle to text std::string value("url(#"); value += rect_repr->attribute("id"); value += ")"; - sp_repr_css_set_property (css, "shape-inside", value.c_str()); + sp_repr_css_set_property(css, "shape-inside", value.c_str()); sp_repr_css_set(text_repr, css, "style"); sp_repr_css_attr_unref(css); @@ -1294,7 +1282,8 @@ SPItem *create_text_with_rectangle (SPDesktop *desktop, Geom::Point p0, Geom::Po // readSingleAttribute(SPAttr::LENGTHADJUST, node->attribute("lengthAdjust")); // } -bool TextTagAttributes::readSingleAttribute(SPAttr key, gchar const *value, SPStyle const *style, Geom::Rect const *viewport) +bool TextTagAttributes::readSingleAttribute(SPAttr key, gchar const *value, SPStyle const *style, + Geom::Rect const *viewport) { // std::cout << "TextTagAttributes::readSingleAttribute: key: " << key // << " value: " << (value?value:"Null") << std::endl; @@ -1302,37 +1291,52 @@ bool TextTagAttributes::readSingleAttribute(SPAttr key, gchar const *value, SPSt bool update_x = false; bool update_y = false; switch (key) { - case SPAttr::X: attr_vector = &attributes.x; update_x = true; break; - case SPAttr::Y: attr_vector = &attributes.y; update_y = true; break; - case SPAttr::DX: attr_vector = &attributes.dx; update_x = true; break; - case SPAttr::DY: attr_vector = &attributes.dy; update_y = true; break; - case SPAttr::ROTATE: attr_vector = &attributes.rotate; break; + case SPAttr::X: + attr_vector = &attributes.x; + update_x = true; + break; + case SPAttr::Y: + attr_vector = &attributes.y; + update_y = true; + break; + case SPAttr::DX: + attr_vector = &attributes.dx; + update_x = true; + break; + case SPAttr::DY: + attr_vector = &attributes.dy; + update_y = true; + break; + case SPAttr::ROTATE: + attr_vector = &attributes.rotate; + break; case SPAttr::TEXTLENGTH: attributes.textLength.readOrUnset(value); return true; break; case SPAttr::LENGTHADJUST: - attributes.lengthAdjust = (value && !strcmp(value, "spacingAndGlyphs")? - Inkscape::Text::Layout::LENGTHADJUST_SPACINGANDGLYPHS : - Inkscape::Text::Layout::LENGTHADJUST_SPACING); // default is "spacing" + attributes.lengthAdjust = (value && !strcmp(value, "spacingAndGlyphs") + ? Inkscape::Text::Layout::LENGTHADJUST_SPACINGANDGLYPHS + : Inkscape::Text::Layout::LENGTHADJUST_SPACING); // default is "spacing" return true; break; - default: return false; + default: + return false; } // FIXME: sp_svg_length_list_read() amalgamates repeated separators. This prevents unset values. *attr_vector = sp_svg_length_list_read(value); - if( (update_x || update_y) && style != nullptr && viewport != nullptr ) { + if ((update_x || update_y) && style != nullptr && viewport != nullptr) { double const w = viewport->width(); double const h = viewport->height(); double const em = style->font_size.computed; double const ex = em * 0.5; - for(auto & it : *attr_vector) { - if( update_x ) - it.update( em, ex, w ); - if( update_y ) - it.update( em, ex, h ); + for (auto &it : *attr_vector) { + if (update_x) + it.update(em, ex, w); + if (update_y) + it.update(em, ex, h); } } return true; @@ -1357,19 +1361,19 @@ void TextTagAttributes::writeTo(Inkscape::XML::Node *node) const } } -void TextTagAttributes::update( double em, double ex, double w, double h ) +void TextTagAttributes::update(double em, double ex, double w, double h) { - for(auto & it : attributes.x) { - it.update( em, ex, w ); + for (auto &it : attributes.x) { + it.update(em, ex, w); } - for(auto & it : attributes.y) { - it.update( em, ex, h ); + for (auto &it : attributes.y) { + it.update(em, ex, h); } - for(auto & it : attributes.dx) { - it.update( em, ex, w ); + for (auto &it : attributes.dx) { + it.update(em, ex, w); } - for(auto & it : attributes.dy) { - it.update( em, ex, h ); + for (auto &it : attributes.dy) { + it.update(em, ex, h); } } @@ -1381,7 +1385,8 @@ void TextTagAttributes::writeSingleAttributeLength(Inkscape::XML::Node *node, gc node->removeAttribute(key); } -void TextTagAttributes::writeSingleAttributeVector(Inkscape::XML::Node *node, gchar const *key, std::vector<SVGLength> const &attr_vector) +void TextTagAttributes::writeSingleAttributeVector(Inkscape::XML::Node *node, gchar const *key, + std::vector<SVGLength> const &attr_vector) { if (attr_vector.empty()) node->removeAttribute(key); @@ -1390,7 +1395,8 @@ void TextTagAttributes::writeSingleAttributeVector(Inkscape::XML::Node *node, gc // FIXME: this has no concept of unset values because sp_svg_length_list_read() can't read them back in for (auto it : attr_vector) { - if (!string.empty()) string += ' '; + if (!string.empty()) + string += ' '; string += it.write(); } node->setAttributeOrRemoveIfEmpty(key, string); @@ -1404,16 +1410,21 @@ bool TextTagAttributes::singleXYCoordinates() const bool TextTagAttributes::anyAttributesSet() const { - return !attributes.x.empty() || !attributes.y.empty() || !attributes.dx.empty() || !attributes.dy.empty() || !attributes.rotate.empty(); + return !attributes.x.empty() || !attributes.y.empty() || !attributes.dx.empty() || !attributes.dy.empty() || + !attributes.rotate.empty(); } Geom::Point TextTagAttributes::firstXY() const { Geom::Point point; - if (attributes.x.empty()) point[Geom::X] = 0.0; - else point[Geom::X] = attributes.x[0].computed; - if (attributes.y.empty()) point[Geom::Y] = 0.0; - else point[Geom::Y] = attributes.y[0].computed; + if (attributes.x.empty()) + point[Geom::X] = 0.0; + else + point[Geom::X] = attributes.x[0].computed; + if (attributes.y.empty()) + point[Geom::Y] = 0.0; + else + point[Geom::Y] = attributes.y[0].computed; return point; } @@ -1430,7 +1441,7 @@ void TextTagAttributes::setFirstXY(Geom::Point &point) attributes.y[0] = point[Geom::Y]; } -SVGLength* TextTagAttributes::getFirstXLength() +SVGLength *TextTagAttributes::getFirstXLength() { if (!attributes.x.empty()) { return &attributes.x[0]; @@ -1439,7 +1450,7 @@ SVGLength* TextTagAttributes::getFirstXLength() } } -SVGLength* TextTagAttributes::getFirstYLength() +SVGLength *TextTagAttributes::getFirstYLength() { if (!attributes.y.empty()) { return &attributes.y[0]; @@ -1452,15 +1463,18 @@ SVGLength* TextTagAttributes::getFirstYLength() // output: What will be sent to the rendering engine. // parent_attrs: Attributes collected from all ancestors. // parent_attrs_offset: Where this element fits into the parent_attrs. -// copy_xy: Should this elements x, y attributes contribute to output (can preserve set values but not use them... kind of strange). -// copy_dxdxrotate: Should this elements dx, dy, rotate attributes contribute to output. -void TextTagAttributes::mergeInto(Inkscape::Text::Layout::OptionalTextTagAttrs *output, Inkscape::Text::Layout::OptionalTextTagAttrs const &parent_attrs, unsigned parent_attrs_offset, bool copy_xy, bool copy_dxdyrotate) const -{ - mergeSingleAttribute(&output->x, parent_attrs.x, parent_attrs_offset, copy_xy ? &attributes.x : nullptr); - mergeSingleAttribute(&output->y, parent_attrs.y, parent_attrs_offset, copy_xy ? &attributes.y : nullptr); - mergeSingleAttribute(&output->dx, parent_attrs.dx, parent_attrs_offset, copy_dxdyrotate ? &attributes.dx : nullptr); - mergeSingleAttribute(&output->dy, parent_attrs.dy, parent_attrs_offset, copy_dxdyrotate ? &attributes.dy : nullptr); - mergeSingleAttribute(&output->rotate, parent_attrs.rotate, parent_attrs_offset, copy_dxdyrotate ? &attributes.rotate : nullptr); +// copy_xy: Should this elements x, y attributes contribute to output (can preserve set values but not use them... kind +// of strange). copy_dxdxrotate: Should this elements dx, dy, rotate attributes contribute to output. +void TextTagAttributes::mergeInto(Inkscape::Text::Layout::OptionalTextTagAttrs *output, + Inkscape::Text::Layout::OptionalTextTagAttrs const &parent_attrs, + unsigned parent_attrs_offset, bool copy_xy, bool copy_dxdyrotate) const +{ + mergeSingleAttribute(&output->x, parent_attrs.x, parent_attrs_offset, copy_xy ? &attributes.x : nullptr); + mergeSingleAttribute(&output->y, parent_attrs.y, parent_attrs_offset, copy_xy ? &attributes.y : nullptr); + mergeSingleAttribute(&output->dx, parent_attrs.dx, parent_attrs_offset, copy_dxdyrotate ? &attributes.dx : nullptr); + mergeSingleAttribute(&output->dy, parent_attrs.dy, parent_attrs_offset, copy_dxdyrotate ? &attributes.dy : nullptr); + mergeSingleAttribute(&output->rotate, parent_attrs.rotate, parent_attrs_offset, + copy_dxdyrotate ? &attributes.rotate : nullptr); if (attributes.textLength._set) { // only from current node, this is not inherited from parent output->textLength.value = attributes.textLength.value; output->textLength.computed = attributes.textLength.computed; @@ -1470,12 +1484,13 @@ void TextTagAttributes::mergeInto(Inkscape::Text::Layout::OptionalTextTagAttrs * } } -void TextTagAttributes::mergeSingleAttribute(std::vector<SVGLength> *output_list, std::vector<SVGLength> const &parent_list, unsigned parent_offset, std::vector<SVGLength> const *overlay_list) +void TextTagAttributes::mergeSingleAttribute(std::vector<SVGLength> *output_list, + std::vector<SVGLength> const &parent_list, unsigned parent_offset, + std::vector<SVGLength> const *overlay_list) { output_list->clear(); if (overlay_list == nullptr) { - if (parent_list.size() > parent_offset) - { + if (parent_list.size() > parent_offset) { output_list->reserve(parent_list.size() - parent_offset); std::copy(parent_list.begin() + parent_offset, parent_list.end(), std::back_inserter(*output_list)); } @@ -1499,7 +1514,8 @@ void TextTagAttributes::mergeSingleAttribute(std::vector<SVGLength> *output_list void TextTagAttributes::erase(unsigned start_index, unsigned n) { - if (n == 0) return; + if (n == 0) + return; if (!singleXYCoordinates()) { eraseSingleAttribute(&attributes.x, start_index, n); eraseSingleAttribute(&attributes.y, start_index, n); @@ -1511,7 +1527,8 @@ void TextTagAttributes::erase(unsigned start_index, unsigned n) void TextTagAttributes::eraseSingleAttribute(std::vector<SVGLength> *attr_vector, unsigned start_index, unsigned n) { - if (attr_vector->size() <= start_index) return; + if (attr_vector->size() <= start_index) + return; if (attr_vector->size() <= start_index + n) attr_vector->erase(attr_vector->begin() + start_index, attr_vector->end()); else @@ -1520,7 +1537,8 @@ void TextTagAttributes::eraseSingleAttribute(std::vector<SVGLength> *attr_vector void TextTagAttributes::insert(unsigned start_index, unsigned n) { - if (n == 0) return; + if (n == 0) + return; if (!singleXYCoordinates()) { insertSingleAttribute(&attributes.x, start_index, n, true); insertSingleAttribute(&attributes.y, start_index, n, true); @@ -1530,16 +1548,19 @@ void TextTagAttributes::insert(unsigned start_index, unsigned n) insertSingleAttribute(&attributes.rotate, start_index, n, false); } -void TextTagAttributes::insertSingleAttribute(std::vector<SVGLength> *attr_vector, unsigned start_index, unsigned n, bool is_xy) +void TextTagAttributes::insertSingleAttribute(std::vector<SVGLength> *attr_vector, unsigned start_index, unsigned n, + bool is_xy) { - if (attr_vector->size() <= start_index) return; + if (attr_vector->size() <= start_index) + return; SVGLength zero_length; zero_length = 0.0; attr_vector->insert(attr_vector->begin() + start_index, n, zero_length); if (is_xy) { - double begin = start_index == 0 ? (*attr_vector)[start_index + n].computed : (*attr_vector)[start_index - 1].computed; - double diff = ((*attr_vector)[start_index + n].computed - begin) / n; // n tested for nonzero in insert() - for (unsigned i = 0 ; i < n ; i++) + double begin = + start_index == 0 ? (*attr_vector)[start_index + n].computed : (*attr_vector)[start_index - 1].computed; + double diff = ((*attr_vector)[start_index + n].computed - begin) / n; // n tested for nonzero in insert() + for (unsigned i = 0; i < n; i++) (*attr_vector)[start_index + i] = begin + diff * i; } } @@ -1555,10 +1576,12 @@ void TextTagAttributes::split(unsigned index, TextTagAttributes *second) splitSingleAttribute(&attributes.rotate, index, &second->attributes.rotate, true); } -void TextTagAttributes::splitSingleAttribute(std::vector<SVGLength> *first_vector, unsigned index, std::vector<SVGLength> *second_vector, bool trimZeros) +void TextTagAttributes::splitSingleAttribute(std::vector<SVGLength> *first_vector, unsigned index, + std::vector<SVGLength> *second_vector, bool trimZeros) { second_vector->clear(); - if (first_vector->size() <= index) return; + if (first_vector->size() <= index) + return; second_vector->resize(first_vector->size() - index); std::copy(first_vector->begin() + index, first_vector->end(), second_vector->begin()); first_vector->resize(index); @@ -1581,7 +1604,9 @@ void TextTagAttributes::join(TextTagAttributes const &first, TextTagAttributes c joinSingleAttribute(&attributes.rotate, first.attributes.rotate, second.attributes.rotate, second_index); } -void TextTagAttributes::joinSingleAttribute(std::vector<SVGLength> *dest_vector, std::vector<SVGLength> const &first_vector, std::vector<SVGLength> const &second_vector, unsigned second_index) +void TextTagAttributes::joinSingleAttribute(std::vector<SVGLength> *dest_vector, + std::vector<SVGLength> const &first_vector, + std::vector<SVGLength> const &second_vector, unsigned second_index) { if (second_vector.empty()) *dest_vector = first_vector; @@ -1610,12 +1635,16 @@ void TextTagAttributes::transform(Geom::Affine const &matrix, double scale_x, do unsigned points_count = std::max(attributes.x.size(), attributes.y.size()); if (extend_zero_length && points_count < 1) points_count = 1; - for (unsigned i = 0 ; i < points_count ; i++) { + for (unsigned i = 0; i < points_count; i++) { Geom::Point point; - if (i < attributes.x.size()) point[Geom::X] = attributes.x[i].computed; - else point[Geom::X] = 0.0; - if (i < attributes.y.size()) point[Geom::Y] = attributes.y[i].computed; - else point[Geom::Y] = 0.0; + if (i < attributes.x.size()) + point[Geom::X] = attributes.x[i].computed; + else + point[Geom::X] = 0.0; + if (i < attributes.y.size()) + point[Geom::Y] = attributes.y[i].computed; + else + point[Geom::Y] = 0.0; point *= matrix; if (i < attributes.x.size()) attributes.x[i] = point[Geom::X]; @@ -1630,44 +1659,43 @@ void TextTagAttributes::transform(Geom::Affine const &matrix, double scale_x, do attributes.y[i] = point[Geom::Y]; } } - for (auto & it : attributes.dx) + for (auto &it : attributes.dx) it = it.computed * scale_x; - for (auto & it : attributes.dy) + for (auto &it : attributes.dy) it = it.computed * scale_y; } double TextTagAttributes::getDx(unsigned index) { - if( attributes.dx.empty()) { + if (attributes.dx.empty()) { return 0.0; } - if( index < attributes.dx.size() ) { + if (index < attributes.dx.size()) { return attributes.dx[index].computed; } else { return 0.0; // attributes.dx.back().computed; } } - double TextTagAttributes::getDy(unsigned index) { - if( attributes.dy.empty() ) { + if (attributes.dy.empty()) { return 0.0; } - if( index < attributes.dy.size() ) { + if (index < attributes.dy.size()) { return attributes.dy[index].computed; } else { return 0.0; // attributes.dy.back().computed; } } - void TextTagAttributes::addToDx(unsigned index, double delta) { SVGLength zero_length; zero_length = 0.0; - if (attributes.dx.size() < index + 1) attributes.dx.resize(index + 1, zero_length); + if (attributes.dx.size() < index + 1) + attributes.dx.resize(index + 1, zero_length); attributes.dx[index] = attributes.dx[index].computed + delta; } @@ -1676,7 +1704,8 @@ void TextTagAttributes::addToDy(unsigned index, double delta) SVGLength zero_length; zero_length = 0.0; - if (attributes.dy.size() < index + 1) attributes.dy.resize(index + 1, zero_length); + if (attributes.dy.size() < index + 1) + attributes.dy.resize(index + 1, zero_length); attributes.dy[index] = attributes.dy[index].computed + delta; } @@ -1686,28 +1715,29 @@ void TextTagAttributes::addToDxDy(unsigned index, Geom::Point const &adjust) zero_length = 0.0; if (adjust[Geom::X] != 0.0) { - if (attributes.dx.size() < index + 1) attributes.dx.resize(index + 1, zero_length); + if (attributes.dx.size() < index + 1) + attributes.dx.resize(index + 1, zero_length); attributes.dx[index] = attributes.dx[index].computed + adjust[Geom::X]; } if (adjust[Geom::Y] != 0.0) { - if (attributes.dy.size() < index + 1) attributes.dy.resize(index + 1, zero_length); + if (attributes.dy.size() < index + 1) + attributes.dy.resize(index + 1, zero_length); attributes.dy[index] = attributes.dy[index].computed + adjust[Geom::Y]; } } double TextTagAttributes::getRotate(unsigned index) { - if( attributes.rotate.empty() ) { + if (attributes.rotate.empty()) { return 0.0; } - if( index < attributes.rotate.size() ) { + if (index < attributes.rotate.size()) { return attributes.rotate[index].computed; } else { return attributes.rotate.back().computed; } } - void TextTagAttributes::addToRotate(unsigned index, double delta) { SVGLength zero_length; @@ -1722,7 +1752,6 @@ void TextTagAttributes::addToRotate(unsigned index, double delta) attributes.rotate[index] = mod360(attributes.rotate[index].computed + delta); } - void TextTagAttributes::setRotate(unsigned index, double angle) { SVGLength zero_length; @@ -1737,7 +1766,6 @@ void TextTagAttributes::setRotate(unsigned index, double angle) attributes.rotate[index] = mod360(angle); } - /* Local Variables: mode:c++ diff --git a/src/object/sp-text.h b/src/object/sp-text.h index b4f1641963a26a8419409b59d69f352608097360..6a579726f073cbfe62448b697b0f901a5c630fe2 100644 --- a/src/object/sp-text.h +++ b/src/object/sp-text.h @@ -15,32 +15,29 @@ */ #include <cstddef> +#include <memory> #include <sigc++/sigc++.h> #include "desktop.h" +#include "libnrtype/Layout-TNG.h" #include "sp-item.h" #include "sp-string.h" // Provides many other headers with SP_IS_STRING #include "text-tag-attributes.h" - -#include "libnrtype/Layout-TNG.h" - #include "xml/node-event-vector.h" -#include <memory> - -#define SP_TEXT(obj) (dynamic_cast<SPText*>((SPObject*)obj)) -#define SP_IS_TEXT(obj) (dynamic_cast<const SPText*>((SPObject*)obj) != NULL) +#define SP_TEXT(obj) (dynamic_cast<SPText *>((SPObject *)obj)) +#define SP_IS_TEXT(obj) (dynamic_cast<const SPText *>((SPObject *)obj) != NULL) /* Text specific flags */ #define SP_TEXT_CONTENT_MODIFIED_FLAG SP_OBJECT_USER_MODIFIED_FLAG_A #define SP_TEXT_LAYOUT_MODIFIED_FLAG SP_OBJECT_USER_MODIFIED_FLAG_A - /* SPText */ -class SPText : public SPItem { +class SPText : public SPItem +{ public: - SPText(); - ~SPText() override; + SPText(); + ~SPText() override; /** Converts the text object to its component curves */ std::unique_ptr<SPCurve> getNormalizedBpath() const; @@ -48,7 +45,7 @@ public: /** Completely recalculates the layout. */ void rebuildLayout(); - //semiprivate: (need to be accessed by the C-style functions still) + // semiprivate: (need to be accessed by the C-style functions still) TextTagAttributes attributes; Inkscape::Text::Layout layout; @@ -73,7 +70,6 @@ public: bool _optimizeTextpathText; private: - /** Initializes layout from <text> (i.e. this node). */ void _buildLayoutInit(); @@ -82,36 +78,39 @@ private: attributes and their inheritance rules, and secondly it keeps track of line breaks and makes sure both that they are assigned the correct SPObject and that we don't get a spurious extra one at the end of the flow. */ - unsigned _buildLayoutInput(SPObject *object, Inkscape::Text::Layout::OptionalTextTagAttrs const &parent_optional_attrs, unsigned parent_attrs_offset, bool in_textpath); + unsigned _buildLayoutInput(SPObject *object, + Inkscape::Text::Layout::OptionalTextTagAttrs const &parent_optional_attrs, + unsigned parent_attrs_offset, bool in_textpath); /** Union all exclusion shapes. */ - Shape* _buildExclusionShape() const; + Shape *_buildExclusionShape() const; /** Find first x/y values which may be in a descendent element. */ - SVGLength* _getFirstXLength(); - SVGLength* _getFirstYLength(); + SVGLength *_getFirstXLength(); + SVGLength *_getFirstYLength(); SPCSSAttr *css; - public: +public: /** Optimize textpath text on next set_transform. */ - void optimizeTextpathText() {_optimizeTextpathText = true;} + void optimizeTextpathText() { _optimizeTextpathText = true; } - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; void release() override; - void child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) override; - void remove_child(Inkscape::XML::Node* child) override; - void set(SPAttr key, const char* value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) override; + void remove_child(Inkscape::XML::Node *child) override; + void set(SPAttr key, const char *value) override; + void update(SPCtx *ctx, unsigned int flags) override; void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; void print(SPPrintContext *ctx) override; - const char* displayName() const override; - char* description() const override; - Inkscape::DrawingItem* show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; + const char *displayName() const override; + char *description() const override; + Inkscape::DrawingItem *show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; void hide(unsigned int key) override; - void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const override; + void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, + Inkscape::SnapPreferences const *snapprefs) const override; Geom::Affine set_transform(Geom::Affine const &transform) override; // For 'inline-size', need to also remove any 'x' and 'y' added by SVG 1.1 fallback. @@ -123,13 +122,13 @@ private: bool is_horizontal() const; bool has_inline_size() const; bool has_shape_inside() const; - Geom::OptRect get_frame(); // Gets inline-size or shape-inside frame. - Inkscape::XML::Node* get_first_rectangle(); // Gets first shape-inside rectangle (if it exists). - void remove_newlines(); // Removes newlines in text. + Geom::OptRect get_frame(); // Gets inline-size or shape-inside frame. + Inkscape::XML::Node *get_first_rectangle(); // Gets first shape-inside rectangle (if it exists). + void remove_newlines(); // Removes newlines in text. }; -SPItem *create_text_with_inline_size (SPDesktop *desktop, Geom::Point p0, Geom::Point p1); -SPItem *create_text_with_rectangle (SPDesktop *desktop, Geom::Point p0, Geom::Point p1); +SPItem *create_text_with_inline_size(SPDesktop *desktop, Geom::Point p0, Geom::Point p1); +SPItem *create_text_with_rectangle(SPDesktop *desktop, Geom::Point p0, Geom::Point p1); #endif diff --git a/src/object/sp-textpath.h b/src/object/sp-textpath.h index 545b142e556a4fc6411fdb24f21f6abba25646e5..ae44b399eed6c109a212e03e2ae9a825870e8fde 100644 --- a/src/object/sp-textpath.h +++ b/src/object/sp-textpath.h @@ -10,22 +10,24 @@ #ifndef INKSCAPE_SP_TEXTPATH_H #define INKSCAPE_SP_TEXTPATH_H -#include "svg/svg-length.h" #include "sp-item.h" #include "sp-text.h" +#include "svg/svg-length.h" class SPUsePath; class Path; -#define SP_TEXTPATH(obj) (dynamic_cast<SPTextPath*>((SPObject*)obj)) -#define SP_IS_TEXTPATH(obj) (dynamic_cast<const SPTextPath*>((SPObject*)obj) != NULL) +#define SP_TEXTPATH(obj) (dynamic_cast<SPTextPath *>((SPObject *)obj)) +#define SP_IS_TEXTPATH(obj) (dynamic_cast<const SPTextPath *>((SPObject *)obj) != NULL) -enum TextPathSide { +enum TextPathSide +{ SP_TEXT_PATH_SIDE_LEFT, SP_TEXT_PATH_SIDE_RIGHT }; -class SPTextPath : public SPItem { +class SPTextPath : public SPItem +{ public: SPTextPath(); ~SPTextPath() override; @@ -38,12 +40,12 @@ public: bool isUpdating; SPUsePath *sourcePath; - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; void release() override; - void set(SPAttr key, const char* value) override; - void update(SPCtx* ctx, unsigned int flags) override; + void set(SPAttr key, const char *value) override; + void update(SPCtx *ctx, unsigned int flags) override; void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; }; #define SP_IS_TEXT_TEXTPATH(obj) (SP_IS_TEXT(obj) && obj->firstChild() && SP_IS_TEXTPATH(obj->firstChild())) @@ -51,7 +53,6 @@ public: SPItem *sp_textpath_get_path_item(SPTextPath *tp); void sp_textpath_to_text(SPObject *tp); - #endif /* !INKSCAPE_SP_TEXTPATH_H */ /* diff --git a/src/object/sp-title.cpp b/src/object/sp-title.cpp index fe295e44122cd0eac85c7c8ce8e890b66d01a480..be6dc46f5221de0265b5c9875579ba2d744130d6 100644 --- a/src/object/sp-title.cpp +++ b/src/object/sp-title.cpp @@ -11,15 +11,18 @@ */ #include "sp-title.h" + #include "xml/repr.h" -SPTitle::SPTitle() : SPObject() { -} +SPTitle::SPTitle() + : SPObject() +{} SPTitle::~SPTitle() = default; -Inkscape::XML::Node* SPTitle::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - SPTitle* object = this; +Inkscape::XML::Node *SPTitle::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + SPTitle *object = this; if (!repr) { repr = object->getRepr()->duplicate(xml_doc); @@ -29,4 +32,3 @@ Inkscape::XML::Node* SPTitle::write(Inkscape::XML::Document *xml_doc, Inkscape:: return repr; } - diff --git a/src/object/sp-title.h b/src/object/sp-title.h index 77f4b88cbf948d5d2da42dfda5914889da0f1660..c05b3c63d1669b4fe2f9042bb7fc443905425117 100644 --- a/src/object/sp-title.h +++ b/src/object/sp-title.h @@ -15,15 +15,17 @@ #include "sp-object.h" -#define SP_TITLE(obj) (dynamic_cast<SPTitle*>((SPObject*)obj)) -#define SP_IS_TITLE(obj) (dynamic_cast<const SPTitle*>((SPObject*)obj) != NULL) +#define SP_TITLE(obj) (dynamic_cast<SPTitle *>((SPObject *)obj)) +#define SP_IS_TITLE(obj) (dynamic_cast<const SPTitle *>((SPObject *)obj) != NULL) -class SPTitle : public SPObject { +class SPTitle : public SPObject +{ public: - SPTitle(); - ~SPTitle() override; + SPTitle(); + ~SPTitle() override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; }; #endif diff --git a/src/object/sp-tref-reference.cpp b/src/object/sp-tref-reference.cpp index 798e74ad86252140874c251d654d56a12f0ab50b..f96b1debea1c1373ef01f55379c99aa0ea0abfe6 100644 --- a/src/object/sp-tref-reference.cpp +++ b/src/object/sp-tref-reference.cpp @@ -15,8 +15,7 @@ #include "sp-text.h" #include "sp-tref.h" - -bool SPTRefReference::_acceptObject(SPObject * const obj) const +bool SPTRefReference::_acceptObject(SPObject *const obj) const { SPObject *owner = getOwner(); if (SP_IS_TREF(owner)) @@ -25,7 +24,6 @@ bool SPTRefReference::_acceptObject(SPObject * const obj) const return false; } - void SPTRefReference::updateObserver() { SPObject *referred = getObject(); @@ -41,9 +39,8 @@ void SPTRefReference::updateObserver() } } - -void SPTRefReference::notifyChildAdded(Inkscape::XML::Node &/*node*/, Inkscape::XML::Node &/*child*/, - Inkscape::XML::Node */*prev*/) +void SPTRefReference::notifyChildAdded(Inkscape::XML::Node & /*node*/, Inkscape::XML::Node & /*child*/, + Inkscape::XML::Node * /*prev*/) { SPObject *owner = getOwner(); @@ -52,9 +49,8 @@ void SPTRefReference::notifyChildAdded(Inkscape::XML::Node &/*node*/, Inkscape:: } } - -void SPTRefReference::notifyChildRemoved(Inkscape::XML::Node &/*node*/, Inkscape::XML::Node &/*child*/, - Inkscape::XML::Node */*prev*/) +void SPTRefReference::notifyChildRemoved(Inkscape::XML::Node & /*node*/, Inkscape::XML::Node & /*child*/, + Inkscape::XML::Node * /*prev*/) { SPObject *owner = getOwner(); @@ -63,9 +59,8 @@ void SPTRefReference::notifyChildRemoved(Inkscape::XML::Node &/*node*/, Inkscape } } - -void SPTRefReference::notifyChildOrderChanged(Inkscape::XML::Node &/*node*/, Inkscape::XML::Node &/*child*/, - Inkscape::XML::Node */*old_prev*/, Inkscape::XML::Node */*new_prev*/) +void SPTRefReference::notifyChildOrderChanged(Inkscape::XML::Node & /*node*/, Inkscape::XML::Node & /*child*/, + Inkscape::XML::Node * /*old_prev*/, Inkscape::XML::Node * /*new_prev*/) { SPObject *owner = getOwner(); @@ -74,9 +69,7 @@ void SPTRefReference::notifyChildOrderChanged(Inkscape::XML::Node &/*node*/, Ink } } - -void SPTRefReference::notifyContentChanged(Inkscape::XML::Node &/*node*/, - Inkscape::Util::ptr_shared /*old_content*/, +void SPTRefReference::notifyContentChanged(Inkscape::XML::Node & /*node*/, Inkscape::Util::ptr_shared /*old_content*/, Inkscape::Util::ptr_shared /*new_content*/) { SPObject *owner = getOwner(); @@ -86,15 +79,13 @@ void SPTRefReference::notifyContentChanged(Inkscape::XML::Node &/*node*/, } } - -void SPTRefReference::notifyAttributeChanged(Inkscape::XML::Node &/*node*/, GQuark /*name*/, +void SPTRefReference::notifyAttributeChanged(Inkscape::XML::Node & /*node*/, GQuark /*name*/, Inkscape::Util::ptr_shared /*old_value*/, Inkscape::Util::ptr_shared /*new_value*/) { // Do nothing - tref only cares about textual content } - /* Local Variables: mode:c++ diff --git a/src/object/sp-tref-reference.h b/src/object/sp-tref-reference.h index f4c1c0fe07119b8bb264d9f81d97baecc9109a88..8272ea4346a3e30582686eccbe0a80e16f03869f 100644 --- a/src/object/sp-tref-reference.h +++ b/src/object/sp-tref-reference.h @@ -18,52 +18,53 @@ #include "sp-item.h" #include "uri-references.h" - #include "util/share.h" #include "xml/node-observer.h" #include "xml/subtree.h" typedef unsigned int GQuark; -class SPTRefReference : public Inkscape::URIReference, - public Inkscape::XML::NodeObserver { +class SPTRefReference + : public Inkscape::URIReference + , public Inkscape::XML::NodeObserver +{ public: - SPTRefReference(SPObject *owner) : URIReference(owner), subtreeObserved(nullptr) { + SPTRefReference(SPObject *owner) + : URIReference(owner) + , subtreeObserved(nullptr) + { updateObserver(); } - - ~SPTRefReference() override { + + ~SPTRefReference() override + { if (subtreeObserved) { subtreeObserved->removeObserver(*this); delete subtreeObserved; - } + } } - SPItem *getObject() const { - return static_cast<SPItem *>(URIReference::getObject()); - } - + SPItem *getObject() const { return static_cast<SPItem *>(URIReference::getObject()); } + void updateObserver(); - + ///////////////////////////////////////////////////////////////////// // Node Observer Functions // ----------------------- void notifyChildAdded(Inkscape::XML::Node &node, Inkscape::XML::Node &child, Inkscape::XML::Node *prev) override; void notifyChildRemoved(Inkscape::XML::Node &node, Inkscape::XML::Node &child, Inkscape::XML::Node *prev) override; - void notifyChildOrderChanged(Inkscape::XML::Node &node, Inkscape::XML::Node &child, - Inkscape::XML::Node *old_prev, Inkscape::XML::Node *new_prev) override; - void notifyContentChanged(Inkscape::XML::Node &node, - Inkscape::Util::ptr_shared old_content, - Inkscape::Util::ptr_shared new_content) override; - void notifyAttributeChanged(Inkscape::XML::Node &node, GQuark name, - Inkscape::Util::ptr_shared old_value, - Inkscape::Util::ptr_shared new_value) override; + void notifyChildOrderChanged(Inkscape::XML::Node &node, Inkscape::XML::Node &child, Inkscape::XML::Node *old_prev, + Inkscape::XML::Node *new_prev) override; + void notifyContentChanged(Inkscape::XML::Node &node, Inkscape::Util::ptr_shared old_content, + Inkscape::Util::ptr_shared new_content) override; + void notifyAttributeChanged(Inkscape::XML::Node &node, GQuark name, Inkscape::Util::ptr_shared old_value, + Inkscape::Util::ptr_shared new_value) override; ///////////////////////////////////////////////////////////////////// protected: - bool _acceptObject(SPObject * obj) const override; - - Inkscape::XML::Subtree *subtreeObserved; + bool _acceptObject(SPObject *obj) const override; + + Inkscape::XML::Subtree *subtreeObserved; }; #endif /* !SEEN_SP_TREF_REFERENCE_H */ diff --git a/src/object/sp-tref.cpp b/src/object/sp-tref.cpp index 04d5374c8e9a3a6a99cdf8ec44e0c1c5b0fc834f..819893c29d77a8595fcee73a1380e286c96e67b3 100644 --- a/src/object/sp-tref.cpp +++ b/src/object/sp-tref.cpp @@ -21,8 +21,8 @@ #include <glibmm/i18n.h> -#include "bad-uri-exception.h" #include "attributes.h" +#include "bad-uri-exception.h" #include "document.h" #include "sp-factory.h" #include "sp-text.h" @@ -31,24 +31,26 @@ //#define DEBUG_TREF #ifdef DEBUG_TREF -# define debug(f, a...) { g_message("%s(%d) %s:", \ - __FILE__,__LINE__,__FUNCTION__); \ - g_message(f, ## a); \ - g_message("\n"); \ - } +#define debug(f, a...) \ + { \ + g_message("%s(%d) %s:", __FILE__, __LINE__, __FUNCTION__); \ + g_message(f, ##a); \ + g_message("\n"); \ + } #else -# define debug(f, a...) /**/ +#define debug(f, a...) /**/ #endif - static void build_string_from_root(Inkscape::XML::Node *root, Glib::ustring *retString); /* TRef base class */ static void sp_tref_href_changed(SPObject *old_ref, SPObject *ref, SPTRef *tref); static void sp_tref_delete_self(SPObject *deleted, SPTRef *self); -SPTRef::SPTRef() : SPItem() { - this->stringChild = nullptr; +SPTRef::SPTRef() + : SPItem() +{ + this->stringChild = nullptr; this->href = nullptr; this->uriOriginalRef = new SPTRefReference(this); @@ -57,11 +59,13 @@ SPTRef::SPTRef() : SPItem() { this->uriOriginalRef->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_tref_href_changed), this)); } -SPTRef::~SPTRef() { - delete this->uriOriginalRef; +SPTRef::~SPTRef() +{ + delete this->uriOriginalRef; } -void SPTRef::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPTRef::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPItem::build(document, repr); this->readAttr(SPAttr::XLINK_HREF); @@ -72,8 +76,9 @@ void SPTRef::build(SPDocument *document, Inkscape::XML::Node *repr) { this->readAttr(SPAttr::ROTATE); } -void SPTRef::release() { - //this->attributes.~TextTagAttributes(); +void SPTRef::release() +{ + // this->attributes.~TextTagAttributes(); this->_delete_connection.disconnect(); this->_changed_connection.disconnect(); @@ -86,14 +91,14 @@ void SPTRef::release() { SPItem::release(); } -void SPTRef::set(SPAttr key, const gchar* value) { - debug("0x%p %s(%u): '%s'",this, - sp_attribute_name(key),key,value ? value : "<no value>"); +void SPTRef::set(SPAttr key, const gchar *value) +{ + debug("0x%p %s(%u): '%s'", this, sp_attribute_name(key), key, value ? value : "<no value>"); if (this->attributes.readSingleAttribute(key, value, style, &viewport)) { // x, y, dx, dy, rotate this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } else if (key == SPAttr::XLINK_HREF) { // xlink:href - if ( !value ) { + if (!value) { // No value g_free(this->href); this->href = nullptr; @@ -101,7 +106,7 @@ void SPTRef::set(SPAttr key, const gchar* value) { } else if ((this->href && strcmp(value, this->href) != 0) || (!this->href)) { // Value has changed - if ( this->href ) { + if (this->href) { g_free(this->href); this->href = nullptr; } @@ -111,7 +116,7 @@ void SPTRef::set(SPAttr key, const gchar* value) { try { this->uriOriginalRef->attach(Inkscape::URI(value)); this->uriOriginalRef->updateObserver(); - } catch ( Inkscape::BadURIException &e ) { + } catch (Inkscape::BadURIException &e) { g_warning("%s", e.what()); this->uriOriginalRef->detach(); } @@ -124,8 +129,9 @@ void SPTRef::set(SPAttr key, const gchar* value) { } } -void SPTRef::update(SPCtx *ctx, guint flags) { - debug("0x%p",this); +void SPTRef::update(SPCtx *ctx, guint flags) +{ + debug("0x%p", this); unsigned childflags = flags; if (flags & SP_OBJECT_MODIFIED_FLAG) { @@ -134,9 +140,9 @@ void SPTRef::update(SPCtx *ctx, guint flags) { childflags &= SP_OBJECT_MODIFIED_CASCADE; SPObject *child = this->stringChild; - + if (child) { - if ( childflags || ( child->uflags & SP_OBJECT_MODIFIED_FLAG )) { + if (childflags || (child->uflags & SP_OBJECT_MODIFIED_FLAG)) { child->updateDisplay(ctx, childflags); } } @@ -144,7 +150,8 @@ void SPTRef::update(SPCtx *ctx, guint flags) { SPItem::update(ctx, flags); } -void SPTRef::modified(unsigned int flags) { +void SPTRef::modified(unsigned int flags) +{ if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } @@ -152,20 +159,21 @@ void SPTRef::modified(unsigned int flags) { flags &= SP_OBJECT_MODIFIED_CASCADE; SPObject *child = this->stringChild; - + if (child) { sp_object_ref(child); - + if (flags || (child->mflags & SP_OBJECT_MODIFIED_FLAG)) { child->emitModified(flags); } - + sp_object_unref(child); } } -Inkscape::XML::Node* SPTRef::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { - debug("0x%p",this); +Inkscape::XML::Node *SPTRef::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ + debug("0x%p", this); if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:tref"); @@ -185,12 +193,13 @@ Inkscape::XML::Node* SPTRef::write(Inkscape::XML::Document *xml_doc, Inkscape::X return repr; } -Geom::OptRect SPTRef::bbox(Geom::Affine const &transform, SPItem::BBoxType type) const { +Geom::OptRect SPTRef::bbox(Geom::Affine const &transform, SPItem::BBoxType type) const +{ Geom::OptRect bbox; // find out the ancestor text which holds our layout SPObject const *parent_text = this; - while ( parent_text && !SP_IS_TEXT(parent_text) ) { + while (parent_text && !SP_IS_TEXT(parent_text)) { parent_text = parent_text->parent; } @@ -199,8 +208,9 @@ Geom::OptRect SPTRef::bbox(Geom::Affine const &transform, SPItem::BBoxType type) } // get the bbox of our portion of the layout - bbox = SP_TEXT(parent_text)->layout.bounds(transform, - sp_text_get_length_upto(parent_text, this), sp_text_get_length_upto(this, nullptr) - 1); + bbox = SP_TEXT(parent_text) + ->layout.bounds(transform, sp_text_get_length_upto(parent_text, this), + sp_text_get_length_upto(this, nullptr) - 1); // Add stroke width // FIXME this code is incorrect @@ -212,39 +222,37 @@ Geom::OptRect SPTRef::bbox(Geom::Affine const &transform, SPItem::BBoxType type) return bbox; } -const char* SPTRef::displayName() const { +const char *SPTRef::displayName() const +{ return _("Cloned Character Data"); } -gchar* SPTRef::description() const { +gchar *SPTRef::description() const +{ SPObject const *referred = this->getObjectReferredTo(); if (referred) { - char *child_desc; + char *child_desc; - if (SP_IS_ITEM(referred)) { - child_desc = SP_ITEM(referred)->detailedDescription(); - } else { - child_desc = g_strdup(""); - } + if (SP_IS_ITEM(referred)) { + child_desc = SP_ITEM(referred)->detailedDescription(); + } else { + child_desc = g_strdup(""); + } - char *ret = g_strdup_printf("%s%s", - (SP_IS_ITEM(referred) ? _(" from ") : ""), child_desc); - g_free(child_desc); + char *ret = g_strdup_printf("%s%s", (SP_IS_ITEM(referred) ? _(" from ") : ""), child_desc); + g_free(child_desc); - return ret; + return ret; } return g_strdup(_("[orphaned]")); } - /* For the sigc::connection changes (i.e. when the object being referred to changes) */ -static void -sp_tref_href_changed(SPObject */*old_ref*/, SPObject */*ref*/, SPTRef *tref) +static void sp_tref_href_changed(SPObject * /*old_ref*/, SPObject * /*ref*/, SPTRef *tref) { - if (tref) - { + if (tref) { // Save a pointer to the original object being referred to SPObject *refRoot = tref->getObjectReferredTo(); @@ -257,23 +265,19 @@ sp_tref_href_changed(SPObject */*old_ref*/, SPObject */*ref*/, SPTRef *tref) // Ensure that we are referring to a legitimate object if (tref->href && refRoot && sp_tref_reference_allowed(tref, refRoot)) { - // Update the text being referred to (will create a new string child) sp_tref_update_text(tref); // Restore the delete connection now that we're done messing with stuff tref->_delete_connection = refRoot->connectDelete(sigc::bind(sigc::ptr_fun(&sp_tref_delete_self), tref)); } - } } - /** * Delete the tref object */ -static void -sp_tref_delete_self(SPObject */*deleted*/, SPTRef *self) +static void sp_tref_delete_self(SPObject * /*deleted*/, SPTRef *self) { self->deleteObject(); } @@ -281,7 +285,7 @@ sp_tref_delete_self(SPObject */*deleted*/, SPTRef *self) /** * Return the object referred to via the URI reference */ -SPObject * SPTRef::getObjectReferredTo() +SPObject *SPTRef::getObjectReferredTo() { SPObject *referredObject = nullptr; @@ -295,7 +299,8 @@ SPObject * SPTRef::getObjectReferredTo() /** * Return the object referred to via the URI reference */ -SPObject const *SPTRef::getObjectReferredTo() const { +SPObject const *SPTRef::getObjectReferredTo() const +{ SPObject *referredObject = nullptr; if (uriOriginalRef) { @@ -305,12 +310,10 @@ SPObject const *SPTRef::getObjectReferredTo() const { return referredObject; } - /** * Returns true when the given tref is allowed to refer to a particular object */ -bool -sp_tref_reference_allowed(SPTRef *tref, SPObject *possible_ref) +bool sp_tref_reference_allowed(SPTRef *tref, SPObject *possible_ref) { bool allowed = false; @@ -330,49 +333,45 @@ sp_tref_reference_allowed(SPTRef *tref, SPObject *possible_ref) return allowed; } - /** * Returns true if a tref is fully contained in the confines of the given * iterators and layout (or if there is no tref). */ -bool -sp_tref_fully_contained(SPObject *start_item, Glib::ustring::iterator &start, - SPObject *end_item, Glib::ustring::iterator &end) +bool sp_tref_fully_contained(SPObject *start_item, Glib::ustring::iterator &start, SPObject *end_item, + Glib::ustring::iterator &end) { bool fully_contained = false; if (start_item && end_item) { - // If neither the beginning or the end is a tref then we return true (whether there // is a tref in the innards or not, because if there is one then it must be totally // contained) - if (!(SP_IS_STRING(start_item) && SP_IS_TREF(start_item->parent)) - && !(SP_IS_STRING(end_item) && SP_IS_TREF(end_item->parent))) { + if (!(SP_IS_STRING(start_item) && SP_IS_TREF(start_item->parent)) && + !(SP_IS_STRING(end_item) && SP_IS_TREF(end_item->parent))) { fully_contained = true; } // Both the beginning and end are trefs; but in this case, the string iterators // must be at the right places - else if ((SP_IS_STRING(start_item) && SP_IS_TREF(start_item->parent)) - && (SP_IS_STRING(end_item) && SP_IS_TREF(end_item->parent))) { - if (start == SP_STRING(start_item)->string.begin() - && end == SP_STRING(start_item)->string.end()) { + else if ((SP_IS_STRING(start_item) && SP_IS_TREF(start_item->parent)) && + (SP_IS_STRING(end_item) && SP_IS_TREF(end_item->parent))) { + if (start == SP_STRING(start_item)->string.begin() && end == SP_STRING(start_item)->string.end()) { fully_contained = true; } } // If the beginning is a string that is a child of a tref, the iterator has to be // at the beginning of the item - else if ((SP_IS_STRING(start_item) && SP_IS_TREF(start_item->parent)) - && !(SP_IS_STRING(end_item) && SP_IS_TREF(end_item->parent))) { + else if ((SP_IS_STRING(start_item) && SP_IS_TREF(start_item->parent)) && + !(SP_IS_STRING(end_item) && SP_IS_TREF(end_item->parent))) { if (start == SP_STRING(start_item)->string.begin()) { fully_contained = true; } } // Same, but the for the end - else if (!(SP_IS_STRING(start_item) && SP_IS_TREF(start_item->parent)) - && (SP_IS_STRING(end_item) && SP_IS_TREF(end_item->parent))) { + else if (!(SP_IS_STRING(start_item) && SP_IS_TREF(start_item->parent)) && + (SP_IS_STRING(end_item) && SP_IS_TREF(end_item->parent))) { if (end == SP_STRING(start_item)->string.end()) { fully_contained = true; } @@ -382,7 +381,6 @@ sp_tref_fully_contained(SPObject *start_item, Glib::ustring::iterator &start, return fully_contained; } - void sp_tref_update_text(SPTRef *tref) { if (tref) { @@ -410,25 +408,21 @@ void sp_tref_update_text(SPTRef *tref) } } - - /** * Using depth-first search, build up a string by concatenating all SPStrings * found in the tree starting at the root */ -static void -build_string_from_root(Inkscape::XML::Node *root, Glib::ustring *retString) +static void build_string_from_root(Inkscape::XML::Node *root, Glib::ustring *retString) { if (root && retString) { - // Stop and concatenate when a SPString is found if (root->type() == Inkscape::XML::TEXT_NODE) { *retString += (root->content()); debug("%s", retString->c_str()); - // Otherwise, continue searching down the tree (with the assumption that no children nodes - // of a SPString are actually legal) + // Otherwise, continue searching down the tree (with the assumption that no children nodes + // of a SPString are actually legal) } else { Inkscape::XML::Node *childNode; for (childNode = root->firstChild(); childNode; childNode = childNode->next()) { @@ -444,16 +438,14 @@ build_string_from_root(Inkscape::XML::Node *root, Glib::ustring *retString) * tree with the new tspan. * The code is based partially on sp_use_unlink */ -SPObject * -sp_tref_convert_to_tspan(SPObject *obj) +SPObject *sp_tref_convert_to_tspan(SPObject *obj) { - SPObject * new_tspan = nullptr; + SPObject *new_tspan = nullptr; //////////////////// // BASE CASE //////////////////// if (SP_IS_TREF(obj)) { - SPTRef *tref = SP_TREF(obj); if (tref && tref->stringChild) { @@ -475,11 +467,11 @@ sp_tref_convert_to_tspan(SPObject *obj) Inkscape::XML::Node *new_string_repr = tref->stringChild->getRepr()->duplicate(xml_doc); new_tspan_repr->addChild(new_string_repr, nullptr); - //SPObject * new_string_child = document->getObjectByRepr(new_string_repr); + // SPObject * new_string_child = document->getObjectByRepr(new_string_repr); // Merge style from the tref - new_tspan->style->merge( tref->style ); - new_tspan->style->cascade( new_tspan->parent->style ); + new_tspan->style->merge(tref->style); + new_tspan->style->cascade(new_tspan->parent->style); new_tspan->updateRepr(); // Hold onto our SPObject and repr for now. @@ -504,11 +496,11 @@ sp_tref_convert_to_tspan(SPObject *obj) //////////////////// else { std::vector<SPObject *> l; - for (auto& child: obj->children) { + for (auto &child : obj->children) { sp_object_ref(&child, obj); l.push_back(&child); } - for(auto child:l) { + for (auto child : l) { // Note that there may be more than one conversion happening here, so if it's not a // tref being passed into this function, the returned value can't be specifically known new_tspan = sp_tref_convert_to_tspan(child); @@ -520,7 +512,6 @@ sp_tref_convert_to_tspan(SPObject *obj) return new_tspan; } - /* Local Variables: mode:c++ diff --git a/src/object/sp-tref.h b/src/object/sp-tref.h index d86ea512ae922cbfdd413328a0fb599fc310f8a9..4d36d2d056287fd4b2a97edd9e64fad69a02c499 100644 --- a/src/object/sp-tref.h +++ b/src/object/sp-tref.h @@ -4,7 +4,7 @@ /** \file * SVG <tref> implementation, see sp-tref.cpp. - * + * * This file was created based on skeleton.h */ /* @@ -20,56 +20,55 @@ #include "sp-tref-reference.h" #include "text-tag-attributes.h" - /* tref base class */ -#define SP_TREF(obj) (dynamic_cast<SPTRef*>((SPObject*)obj)) -#define SP_IS_TREF(obj) (dynamic_cast<const SPTRef*>((SPObject*)obj) != NULL) +#define SP_TREF(obj) (dynamic_cast<SPTRef *>((SPObject *)obj)) +#define SP_IS_TREF(obj) (dynamic_cast<const SPTRef *>((SPObject *)obj) != NULL) -class SPTRef : public SPItem { +class SPTRef : public SPItem +{ public: - SPTRef(); - ~SPTRef() override; + SPTRef(); + ~SPTRef() override; // Attributes that are used in the same way they would be in a tspan TextTagAttributes attributes; - + // Text stored in the xlink:href attribute char *href; - + // URI reference to original object SPTRefReference *uriOriginalRef; - + // Shortcut pointer to the child of the tref (which is a copy // of the character data stored at and/or below the node // referenced by uriOriginalRef) SPObject *stringChild; - + // The sigc connections for various notifications sigc::connection _delete_connection; sigc::connection _changed_connection; - - SPObject * getObjectReferredTo(); + + SPObject *getObjectReferredTo(); SPObject const *getObjectReferredTo() const; - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; - void set(SPAttr key, char const* value) override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, guint flags) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, char const *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) override; - Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; - const char* displayName() const override; - char* description() const override; + Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; + const char *displayName() const override; + char *description() const override; }; void sp_tref_update_text(SPTRef *tref); bool sp_tref_reference_allowed(SPTRef *tref, SPObject *possible_ref); -bool sp_tref_fully_contained(SPObject *start_item, Glib::ustring::iterator &start, - SPObject *end_item, Glib::ustring::iterator &end); -SPObject * sp_tref_convert_to_tspan(SPObject *item); - +bool sp_tref_fully_contained(SPObject *start_item, Glib::ustring::iterator &start, SPObject *end_item, + Glib::ustring::iterator &end); +SPObject *sp_tref_convert_to_tspan(SPObject *item); #endif /* !SP_TREF_H */ diff --git a/src/object/sp-tspan.cpp b/src/object/sp-tspan.cpp index 13e2673c02b9b239ba2ff9fc21619f129c60c0db..023d0f72c76ad1462e2c499c2714df071bab8fd2 100644 --- a/src/object/sp-tspan.cpp +++ b/src/object/sp-tspan.cpp @@ -24,38 +24,37 @@ * */ +#include "sp-tspan.h" + #include <cstring> -#include <string> #include <glibmm/i18n.h> #include <glibmm/regex.h> +#include <string> #include "attributes.h" +#include "display/curve.h" #include "document.h" -#include "text-editing.h" - +#include "livarot/Path.h" #include "sp-textpath.h" #include "sp-tref.h" -#include "sp-tspan.h" #include "sp-use-reference.h" #include "style.h" - -#include "display/curve.h" - -#include "livarot/Path.h" - #include "svg/stringstream.h" - +#include "text-editing.h" /*##################################################### # SPTSPAN #####################################################*/ -SPTSpan::SPTSpan() : SPItem() { +SPTSpan::SPTSpan() + : SPItem() +{ this->role = SP_TSPAN_ROLE_UNSPECIFIED; } SPTSpan::~SPTSpan() = default; -void SPTSpan::build(SPDocument *doc, Inkscape::XML::Node *repr) { +void SPTSpan::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ this->readAttr(SPAttr::X); this->readAttr(SPAttr::Y); this->readAttr(SPAttr::DX); @@ -64,8 +63,8 @@ void SPTSpan::build(SPDocument *doc, Inkscape::XML::Node *repr) { // Strip sodipodi:role from SVG 2 flowed text. // this->role = SP_TSPAN_ROLE_UNSPECIFIED; - SPText* text = dynamic_cast<SPText *>(parent); - if (text && !(text->has_shape_inside()|| text->has_inline_size())) { + SPText *text = dynamic_cast<SPText *>(parent); + if (text && !(text->has_shape_inside() || text->has_inline_size())) { this->readAttr(SPAttr::SODIPODI_ROLE); } @@ -75,11 +74,13 @@ void SPTSpan::build(SPDocument *doc, Inkscape::XML::Node *repr) { SPItem::build(doc, repr); } -void SPTSpan::release() { +void SPTSpan::release() +{ SPItem::release(); } -void SPTSpan::set(SPAttr key, const gchar* value) { +void SPTSpan::set(SPAttr key, const gchar *value) +{ if (this->attributes.readSingleAttribute(key, value, style, &viewport)) { this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } else { @@ -91,12 +92,13 @@ void SPTSpan::set(SPAttr key, const gchar* value) { this->role = SP_TSPAN_ROLE_UNSPECIFIED; } break; - + case SPAttr::STYLE: if (value) { Glib::ustring style(value); Glib::RefPtr<Glib::Regex> regex = Glib::Regex::create("visibility\\s*:\\s*hidden;*"); - Glib::ustring stripped = regex->replace_literal(style, 0, "", static_cast<Glib::RegexMatchFlags >(0)); + Glib::ustring stripped = + regex->replace_literal(style, 0, "", static_cast<Glib::RegexMatchFlags>(0)); Inkscape::XML::Node *repr = getRepr(); repr->setAttributeOrRemoveIfEmpty("style", stripped); } @@ -108,70 +110,72 @@ void SPTSpan::set(SPAttr key, const gchar* value) { } } -void SPTSpan::update(SPCtx *ctx, guint flags) { +void SPTSpan::update(SPCtx *ctx, guint flags) +{ unsigned childflags = flags; if (flags & SP_OBJECT_MODIFIED_FLAG) { childflags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } childflags &= SP_OBJECT_MODIFIED_CASCADE; - for (auto& ochild: children) { - if ( flags || ( ochild.uflags & SP_OBJECT_MODIFIED_FLAG )) { - ochild.updateDisplay(ctx, childflags); + for (auto &ochild : children) { + if (flags || (ochild.uflags & SP_OBJECT_MODIFIED_FLAG)) { + ochild.updateDisplay(ctx, childflags); } } SPItem::update(ctx, flags); - if (flags & ( SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_CHILD_MODIFIED_FLAG | - SP_TEXT_LAYOUT_MODIFIED_FLAG ) ) - { + if (flags & (SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_TEXT_LAYOUT_MODIFIED_FLAG)) { SPItemCtx const *ictx = reinterpret_cast<SPItemCtx const *>(ctx); double const w = ictx->viewport.width(); double const h = ictx->viewport.height(); double const em = style->font_size.computed; - double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. + double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. - attributes.update( em, ex, w, h ); + attributes.update(em, ex, w, h); } } -void SPTSpan::modified(unsigned int flags) { -// SPItem::onModified(flags); +void SPTSpan::modified(unsigned int flags) +{ + // SPItem::onModified(flags); if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; } - + flags &= SP_OBJECT_MODIFIED_CASCADE; - for (auto& ochild: children) { + for (auto &ochild : children) { if (flags || (ochild.mflags & SP_OBJECT_MODIFIED_FLAG)) { ochild.emitModified(flags); } } } -Geom::OptRect SPTSpan::bbox(Geom::Affine const &transform, SPItem::BBoxType type) const { +Geom::OptRect SPTSpan::bbox(Geom::Affine const &transform, SPItem::BBoxType type) const +{ Geom::OptRect bbox; // find out the ancestor text which holds our layout SPObject const *parent_text = this; - + while (parent_text && !SP_IS_TEXT(parent_text)) { parent_text = parent_text->parent; } - + if (parent_text == nullptr) { return bbox; } // get the bbox of our portion of the layout - bbox = SP_TEXT(parent_text)->layout.bounds(transform, sp_text_get_length_upto(parent_text, this), sp_text_get_length_upto(this, nullptr) - 1); - + bbox = SP_TEXT(parent_text) + ->layout.bounds(transform, sp_text_get_length_upto(parent_text, this), + sp_text_get_length_upto(this, nullptr) - 1); + if (!bbox) { - return bbox; + return bbox; } // Add stroke width @@ -180,47 +184,48 @@ Geom::OptRect SPTSpan::bbox(Geom::Affine const &transform, SPItem::BBoxType type double scale = transform.descrim(); bbox->expandBy(0.5 * this->style->stroke_width.computed * scale); } - + return bbox; } -Inkscape::XML::Node* SPTSpan::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPTSpan::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:tspan"); } this->attributes.writeTo(repr); - if ( flags&SP_OBJECT_WRITE_BUILD ) { + if (flags & SP_OBJECT_WRITE_BUILD) { std::vector<Inkscape::XML::Node *> l; - for (auto& child: children) { - Inkscape::XML::Node* c_repr=nullptr; + for (auto &child : children) { + Inkscape::XML::Node *c_repr = nullptr; - if ( SP_IS_TSPAN(&child) || SP_IS_TREF(&child) ) { + if (SP_IS_TSPAN(&child) || SP_IS_TREF(&child)) { c_repr = child.updateRepr(xml_doc, nullptr, flags); - } else if ( SP_IS_TEXTPATH(&child) ) { - //c_repr = child.updateRepr(xml_doc, NULL, flags); // shouldn't happen - } else if ( SP_IS_STRING(&child) ) { + } else if (SP_IS_TEXTPATH(&child)) { + // c_repr = child.updateRepr(xml_doc, NULL, flags); // shouldn't happen + } else if (SP_IS_STRING(&child)) { c_repr = xml_doc->createTextNode(SP_STRING(&child)->string.c_str()); } - if ( c_repr ) { + if (c_repr) { l.push_back(c_repr); } } - for (auto i = l.rbegin(); i!= l.rend(); ++i) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild((*i), nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { - if ( SP_IS_TSPAN(&child) || SP_IS_TREF(&child) ) { + for (auto &child : children) { + if (SP_IS_TSPAN(&child) || SP_IS_TREF(&child)) { child.updateRepr(flags); - } else if ( SP_IS_TEXTPATH(&child) ) { - //c_repr = child->updateRepr(xml_doc, NULL, flags); // shouldn't happen - } else if ( SP_IS_STRING(&child) ) { + } else if (SP_IS_TEXTPATH(&child)) { + // c_repr = child->updateRepr(xml_doc, NULL, flags); // shouldn't happen + } else if (SP_IS_STRING(&child)) { child.getRepr()->setContent(SP_STRING(&child)->string.c_str()); } } @@ -231,32 +236,36 @@ Inkscape::XML::Node* SPTSpan::write(Inkscape::XML::Document *xml_doc, Inkscape:: return repr; } -const char* SPTSpan::displayName() const { +const char *SPTSpan::displayName() const +{ return _("Text Span"); } - /*##################################################### # SPTEXTPATH #####################################################*/ -void refresh_textpath_source(SPTextPath* offset); +void refresh_textpath_source(SPTextPath *offset); -SPTextPath::SPTextPath() : SPItem() { +SPTextPath::SPTextPath() + : SPItem() +{ this->startOffset._set = false; this->side = SP_TEXT_PATH_SIDE_LEFT; this->originalPath = nullptr; - this->isUpdating=false; + this->isUpdating = false; // set up the uri reference this->sourcePath = new SPUsePath(this); this->sourcePath->user_unlink = sp_textpath_to_text; } -SPTextPath::~SPTextPath() { - delete this->sourcePath; +SPTextPath::~SPTextPath() +{ + delete this->sourcePath; } -void SPTextPath::build(SPDocument *doc, Inkscape::XML::Node *repr) { +void SPTextPath::build(SPDocument *doc, Inkscape::XML::Node *repr) +{ this->readAttr(SPAttr::X); this->readAttr(SPAttr::Y); this->readAttr(SPAttr::DX); @@ -271,11 +280,12 @@ void SPTextPath::build(SPDocument *doc, Inkscape::XML::Node *repr) { SPItem::build(doc, repr); } -void SPTextPath::release() { - //this->attributes.~TextTagAttributes(); +void SPTextPath::release() +{ + // this->attributes.~TextTagAttributes(); if (this->originalPath) { - delete this->originalPath; + delete this->originalPath; } this->originalPath = nullptr; @@ -283,26 +293,26 @@ void SPTextPath::release() { SPItem::release(); } -void SPTextPath::set(SPAttr key, const gchar* value) { - +void SPTextPath::set(SPAttr key, const gchar *value) +{ if (this->attributes.readSingleAttribute(key, value, style, &viewport)) { this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } else { switch (key) { case SPAttr::XLINK_HREF: - this->sourcePath->link((char*)value); + this->sourcePath->link((char *)value); break; case SPAttr::SIDE: if (!value) { return; } - if (strncmp(value, "left", 4) == 0) + if (strncmp(value, "left", 4) == 0) side = SP_TEXT_PATH_SIDE_LEFT; else if (strncmp(value, "right", 5) == 0) side = SP_TEXT_PATH_SIDE_RIGHT; else { - std::cerr << "SPTextPath: Bad side value: " << (value?value:"null") << std::endl; + std::cerr << "SPTextPath: Bad side value: " << (value ? value : "null") << std::endl; side = SP_TEXT_PATH_SIDE_LEFT; } break; @@ -317,10 +327,11 @@ void SPTextPath::set(SPAttr key, const gchar* value) { } } -void SPTextPath::update(SPCtx *ctx, guint flags) { +void SPTextPath::update(SPCtx *ctx, guint flags) +{ this->isUpdating = true; - if ( this->sourcePath->sourceDirty ) { + if (this->sourcePath->sourceDirty) { refresh_textpath_source(this); } @@ -334,38 +345,34 @@ void SPTextPath::update(SPCtx *ctx, guint flags) { flags &= SP_OBJECT_MODIFIED_CASCADE; - for (auto& ochild: children) { - if ( flags || ( ochild.uflags & SP_OBJECT_MODIFIED_FLAG )) { + for (auto &ochild : children) { + if (flags || (ochild.uflags & SP_OBJECT_MODIFIED_FLAG)) { ochild.updateDisplay(ctx, flags); } } - if (flags & ( SP_OBJECT_STYLE_MODIFIED_FLAG | - SP_OBJECT_CHILD_MODIFIED_FLAG | - SP_TEXT_LAYOUT_MODIFIED_FLAG ) ) - { + if (flags & (SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_TEXT_LAYOUT_MODIFIED_FLAG)) { SPItemCtx const *ictx = reinterpret_cast<SPItemCtx const *>(ctx); double const w = ictx->viewport.width(); double const h = ictx->viewport.height(); double const em = style->font_size.computed; - double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. + double const ex = 0.5 * em; // fixme: get x height from pango or libnrtype. - attributes.update( em, ex, w, h ); + attributes.update(em, ex, w, h); } } - -void refresh_textpath_source(SPTextPath* tp) +void refresh_textpath_source(SPTextPath *tp) { - if ( tp == nullptr ) { - return; + if (tp == nullptr) { + return; } tp->sourcePath->refresh_source(); - tp->sourcePath->sourceDirty=false; + tp->sourcePath->sourceDirty = false; - if ( tp->sourcePath->originalPath ) { + if (tp->sourcePath->originalPath) { if (tp->originalPath) { delete tp->originalPath; } @@ -384,8 +391,9 @@ void refresh_textpath_source(SPTextPath* tp) } } -void SPTextPath::modified(unsigned int flags) { -// SPItem::onModified(flags); +void SPTextPath::modified(unsigned int flags) +{ + // SPItem::onModified(flags); if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; @@ -393,14 +401,15 @@ void SPTextPath::modified(unsigned int flags) { flags &= SP_OBJECT_MODIFIED_CASCADE; - for (auto& ochild: children) { + for (auto &ochild : children) { if (flags || (ochild.mflags & SP_OBJECT_MODIFIED_FLAG)) { ochild.emitModified(flags); } } } -Inkscape::XML::Node* SPTextPath::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPTextPath::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:textPath"); } @@ -413,7 +422,7 @@ Inkscape::XML::Node* SPTextPath::write(Inkscape::XML::Document *xml_doc, Inkscap if (this->startOffset._set) { if (this->startOffset.unit == SVGLength::PERCENT) { - Inkscape::SVGOStringStream os; + Inkscape::SVGOStringStream os; os << (this->startOffset.computed * 100.0) << "%"; this->setAttribute("startOffset", os.str()); } else { @@ -423,40 +432,40 @@ Inkscape::XML::Node* SPTextPath::write(Inkscape::XML::Document *xml_doc, Inkscap } } - if ( this->sourcePath->sourceHref ) { - repr->setAttribute("xlink:href", this->sourcePath->sourceHref); + if (this->sourcePath->sourceHref) { + repr->setAttribute("xlink:href", this->sourcePath->sourceHref); } - if ( flags & SP_OBJECT_WRITE_BUILD ) { + if (flags & SP_OBJECT_WRITE_BUILD) { std::vector<Inkscape::XML::Node *> l; - for (auto& child: children) { - Inkscape::XML::Node* c_repr=nullptr; + for (auto &child : children) { + Inkscape::XML::Node *c_repr = nullptr; - if ( SP_IS_TSPAN(&child) || SP_IS_TREF(&child) ) { + if (SP_IS_TSPAN(&child) || SP_IS_TREF(&child)) { c_repr = child.updateRepr(xml_doc, nullptr, flags); - } else if ( SP_IS_TEXTPATH(&child) ) { - //c_repr = child->updateRepr(xml_doc, NULL, flags); // shouldn't happen - } else if ( SP_IS_STRING(&child) ) { + } else if (SP_IS_TEXTPATH(&child)) { + // c_repr = child->updateRepr(xml_doc, NULL, flags); // shouldn't happen + } else if (SP_IS_STRING(&child)) { c_repr = xml_doc->createTextNode(SP_STRING(&child)->string.c_str()); } - if ( c_repr ) { + if (c_repr) { l.push_back(c_repr); } } - for( auto i = l.rbegin(); i != l.rend(); ++i ) { + for (auto i = l.rbegin(); i != l.rend(); ++i) { repr->addChild(*i, nullptr); Inkscape::GC::release(*i); } } else { - for (auto& child: children) { - if ( SP_IS_TSPAN(&child) || SP_IS_TREF(&child) ) { + for (auto &child : children) { + if (SP_IS_TSPAN(&child) || SP_IS_TREF(&child)) { child.updateRepr(flags); - } else if ( SP_IS_TEXTPATH(&child) ) { - //c_repr = child.updateRepr(xml_doc, NULL, flags); // shouldn't happen - } else if ( SP_IS_STRING(&child) ) { + } else if (SP_IS_TEXTPATH(&child)) { + // c_repr = child.updateRepr(xml_doc, NULL, flags); // shouldn't happen + } else if (SP_IS_STRING(&child)) { child.getRepr()->setContent(SP_STRING(&child)->string.c_str()); } } @@ -467,7 +476,6 @@ Inkscape::XML::Node* SPTextPath::write(Inkscape::XML::Document *xml_doc, Inkscap return repr; } - SPItem *sp_textpath_get_path_item(SPTextPath *tp) { if (tp && tp->sourcePath) { @@ -483,11 +491,11 @@ SPItem *sp_textpath_get_path_item(SPTextPath *tp) void sp_textpath_to_text(SPObject *tp) { SPObject *text = tp->parent; - + // make a list of textpath children std::vector<Inkscape::XML::Node *> tp_reprs; - for (auto& o: tp->children) { + for (auto &o : tp->children) { tp_reprs.push_back(o.getRepr()); } @@ -502,8 +510,8 @@ void sp_textpath_to_text(SPObject *tp) // set x/y on text (to be near where it was when on path) // Copied from Layout::fitToPathAlign - Path *path = dynamic_cast<SPTextPath*>(tp)->originalPath; - SVGLength const startOffset = dynamic_cast<SPTextPath*>(tp)->startOffset; + Path *path = dynamic_cast<SPTextPath *>(tp)->originalPath; + SVGLength const startOffset = dynamic_cast<SPTextPath *>(tp)->startOffset; double offset = 0.0; if (startOffset._set) { if (startOffset.unit == SVGLength::PERCENT) @@ -519,11 +527,10 @@ void sp_textpath_to_text(SPObject *tp) sp_repr_set_svg_double(text->getRepr(), "x", midpoint[Geom::X]); sp_repr_set_svg_double(text->getRepr(), "y", midpoint[Geom::Y]); - //remove textpath + // remove textpath tp->deleteObject(); } - /* Local Variables: mode:c++ diff --git a/src/object/sp-tspan.h b/src/object/sp-tspan.h index f1420da80fd5971dd07ca734dc5bb0dc884281be..da66960416d34365afb53d8d565d572d4ec3d9d5 100644 --- a/src/object/sp-tspan.h +++ b/src/object/sp-tspan.h @@ -17,32 +17,34 @@ #include "sp-item.h" #include "text-tag-attributes.h" -#define SP_TSPAN(obj) (dynamic_cast<SPTSpan*>((SPObject*)obj)) -#define SP_IS_TSPAN(obj) (dynamic_cast<const SPTSpan*>((SPObject*)obj) != NULL) +#define SP_TSPAN(obj) (dynamic_cast<SPTSpan *>((SPObject *)obj)) +#define SP_IS_TSPAN(obj) (dynamic_cast<const SPTSpan *>((SPObject *)obj) != NULL) -enum { +enum +{ SP_TSPAN_ROLE_UNSPECIFIED, SP_TSPAN_ROLE_PARAGRAPH, SP_TSPAN_ROLE_LINE }; -class SPTSpan : public SPItem { +class SPTSpan : public SPItem +{ public: - SPTSpan(); - ~SPTSpan() override; + SPTSpan(); + ~SPTSpan() override; unsigned int role : 2; TextTagAttributes attributes; - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; - void set(SPAttr key, const char* value) override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; - Inkscape::XML::Node* write(Inkscape::XML::Document* doc, Inkscape::XML::Node* repr, unsigned int flags) override; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, const char *value) override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, unsigned int flags) override; - Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; - const char* displayName() const override; + Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType type) const override; + const char *displayName() const override; }; #endif /* !INKSCAPE_SP_TSPAN_H */ diff --git a/src/object/sp-use-reference.cpp b/src/object/sp-use-reference.cpp index 4365cdff969fc4538b559f09de4472a3d79db939..ad084dfd843fc8d1f1d4cc1a4dcc5ac0056e4223 100644 --- a/src/object/sp-use-reference.cpp +++ b/src/object/sp-use-reference.cpp @@ -14,35 +14,35 @@ #include <string> #include "bad-uri-exception.h" -#include "enums.h" - #include "display/curve.h" +#include "enums.h" #include "livarot/Path.h" #include "preferences.h" #include "sp-shape.h" #include "sp-text.h" #include "uri.h" -bool SPUseReference::_acceptObject(SPObject * const obj) const +bool SPUseReference::_acceptObject(SPObject *const obj) const { return URIReference::_acceptObject(obj); } - static void sp_usepath_href_changed(SPObject *old_ref, SPObject *ref, SPUsePath *offset); static void sp_usepath_move_compensate(Geom::Affine const *mp, SPItem *original, SPUsePath *self); static void sp_usepath_delete_self(SPObject *deleted, SPUsePath *offset); static void sp_usepath_source_modified(SPObject *iSource, guint flags, SPUsePath *offset); -SPUsePath::SPUsePath(SPObject* i_owner):SPUseReference(i_owner) +SPUsePath::SPUsePath(SPObject *i_owner) + : SPUseReference(i_owner) { - owner=i_owner; + owner = i_owner; originalPath = nullptr; - sourceDirty=false; + sourceDirty = false; sourceHref = nullptr; sourceRepr = nullptr; sourceObject = nullptr; - _changed_connection = changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_usepath_href_changed), this)); // listening to myself, this should be virtual instead + _changed_connection = changedSignal().connect(sigc::bind( + sigc::ptr_fun(sp_usepath_href_changed), this)); // listening to myself, this should be virtual instead user_unlink = nullptr; } @@ -55,14 +55,13 @@ SPUsePath::~SPUsePath() unlink(); } -void -SPUsePath::link(char *to) +void SPUsePath::link(char *to) { - if ( to == nullptr ) { + if (to == nullptr) { quit_listening(); unlink(); } else { - if ( !sourceHref || ( strcmp(to, sourceHref) != 0 ) ) { + if (!sourceHref || (strcmp(to, sourceHref) != 0)) { g_free(sourceHref); sourceHref = g_strdup(to); try { @@ -78,31 +77,29 @@ SPUsePath::link(char *to) } } -void -SPUsePath::unlink() +void SPUsePath::unlink() { g_free(sourceHref); sourceHref = nullptr; detach(); } -void -SPUsePath::start_listening(SPObject* to) +void SPUsePath::start_listening(SPObject *to) { - if ( to == nullptr ) { + if (to == nullptr) { return; } sourceObject = to; sourceRepr = to->getRepr(); _delete_connection = to->connectDelete(sigc::bind(sigc::ptr_fun(&sp_usepath_delete_self), this)); - _transformed_connection = SP_ITEM(to)->connectTransformed(sigc::bind(sigc::ptr_fun(&sp_usepath_move_compensate), this)); + _transformed_connection = + SP_ITEM(to)->connectTransformed(sigc::bind(sigc::ptr_fun(&sp_usepath_move_compensate), this)); _modified_connection = to->connectModified(sigc::bind<2>(sigc::ptr_fun(&sp_usepath_source_modified), this)); } -void -SPUsePath::quit_listening() +void SPUsePath::quit_listening() { - if ( sourceObject == nullptr ) { + if (sourceObject == nullptr) { return; } _modified_connection.disconnect(); @@ -112,20 +109,18 @@ SPUsePath::quit_listening() sourceObject = nullptr; } -static void -sp_usepath_href_changed(SPObject */*old_ref*/, SPObject */*ref*/, SPUsePath *offset) +static void sp_usepath_href_changed(SPObject * /*old_ref*/, SPObject * /*ref*/, SPUsePath *offset) { offset->quit_listening(); SPItem *refobj = offset->getObject(); - if ( refobj ) { + if (refobj) { offset->start_listening(refobj); } - offset->sourceDirty=true; + offset->sourceDirty = true; offset->owner->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -static void -sp_usepath_move_compensate(Geom::Affine const *mp, SPItem *original, SPUsePath *self) +static void sp_usepath_move_compensate(Geom::Affine const *mp, SPItem *original, SPUsePath *self) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); guint mode = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_PARALLEL); @@ -167,8 +162,7 @@ sp_usepath_move_compensate(Geom::Affine const *mp, SPItem *original, SPUsePath * item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -static void -sp_usepath_delete_self(SPObject */*deleted*/, SPUsePath *offset) +static void sp_usepath_delete_self(SPObject * /*deleted*/, SPUsePath *offset) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); guint const mode = prefs->getInt("/options/cloneorphans/value", SP_CLONE_ORPHANS_UNLINK); @@ -184,8 +178,7 @@ sp_usepath_delete_self(SPObject */*deleted*/, SPUsePath *offset) } } -static void -sp_usepath_source_modified(SPObject */*iSource*/, guint /*flags*/, SPUsePath *offset) +static void sp_usepath_source_modified(SPObject * /*iSource*/, guint /*flags*/, SPUsePath *offset) { offset->sourceDirty = true; offset->owner->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); @@ -198,7 +191,8 @@ void SPUsePath::refresh_source() originalPath = nullptr; SPObject *refobj = sourceObject; - if ( refobj == nullptr ) return; + if (refobj == nullptr) + return; if (auto shape = dynamic_cast<SPShape const *>(refobj)) { originalPath = SPCurve::copy(shape->curve()); @@ -210,7 +204,6 @@ void SPUsePath::refresh_source() } } - /* Local Variables: mode:c++ diff --git a/src/object/sp-use-reference.h b/src/object/sp-use-reference.h index 96580be79e8709e28b18430b79f9f3669e284fff..fbbded4b721370203f9665bd185763248ef090ed 100644 --- a/src/object/sp-use-reference.h +++ b/src/object/sp-use-reference.h @@ -10,61 +10,59 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <memory> #include <sigc++/sigc++.h> #include "sp-item.h" #include "uri-references.h" -#include <memory> - class SPCurve; namespace Inkscape { namespace XML { class Node; } -} +} // namespace Inkscape - -class SPUseReference : public Inkscape::URIReference { +class SPUseReference : public Inkscape::URIReference +{ public: - SPUseReference(SPObject *owner) : URIReference(owner) {} + SPUseReference(SPObject *owner) + : URIReference(owner) + {} - SPItem *getObject() const { - return static_cast<SPItem *>(URIReference::getObject()); - } + SPItem *getObject() const { return static_cast<SPItem *>(URIReference::getObject()); } protected: - bool _acceptObject(SPObject * const obj) const override; - + bool _acceptObject(SPObject *const obj) const override; }; - -class SPUsePath : public SPUseReference { +class SPUsePath : public SPUseReference +{ public: std::unique_ptr<SPCurve> originalPath; bool sourceDirty; - SPObject *owner; - char *sourceHref; + SPObject *owner; + char *sourceHref; Inkscape::XML::Node *sourceRepr; - SPObject *sourceObject; + SPObject *sourceObject; sigc::connection _modified_connection; sigc::connection _delete_connection; sigc::connection _changed_connection; sigc::connection _transformed_connection; - SPUsePath(SPObject* i_owner); + SPUsePath(SPObject *i_owner); ~SPUsePath() override; - void link(char* to); + void link(char *to); void unlink(); - void start_listening(SPObject* to); + void start_listening(SPObject *to); void quit_listening(); void refresh_source(); - void (*user_unlink) (SPObject *user); + void (*user_unlink)(SPObject *user); }; #endif /* !SEEN_SP_USE_REFERENCE_H */ diff --git a/src/object/sp-use.cpp b/src/object/sp-use.cpp index d29060ef94b2ed15d32a94f8c3220b80e99ed250..f643e098bcef709096ceae8fa209b47af6961a50 100644 --- a/src/object/sp-use.cpp +++ b/src/object/sp-use.cpp @@ -14,57 +14,56 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> -#include <string> +#include "sp-use.h" #include <2geom/transforms.h> +#include <cstring> #include <glibmm/i18n.h> #include <glibmm/markup.h> +#include <string> +#include "attributes.h" #include "bad-uri-exception.h" #include "display/drawing-group.h" -#include "attributes.h" #include "document.h" +#include "preferences.h" +#include "print.h" #include "sp-clippath.h" -#include "sp-mask.h" #include "sp-factory.h" #include "sp-flowregion.h" -#include "uri.h" -#include "print.h" -#include "xml/repr.h" -#include "svg/svg.h" -#include "preferences.h" -#include "style.h" - -#include "sp-use.h" -#include "sp-symbol.h" +#include "sp-flowtext.h" +#include "sp-mask.h" #include "sp-root.h" -#include "sp-use-reference.h" #include "sp-shape.h" +#include "sp-symbol.h" #include "sp-text.h" -#include "sp-flowtext.h" +#include "sp-use-reference.h" +#include "style.h" +#include "svg/svg.h" +#include "uri.h" +#include "xml/repr.h" SPUse::SPUse() - : SPItem(), - SPDimensions(), - child(nullptr), - href(nullptr), - ref(new SPUseReference(this)), - _delete_connection(), - _changed_connection(), - _transformed_connection() + : SPItem() + , SPDimensions() + , child(nullptr) + , href(nullptr) + , ref(new SPUseReference(this)) + , _delete_connection() + , _changed_connection() + , _transformed_connection() { this->x.unset(); this->y.unset(); this->width.unset(SVGLength::PERCENT, 1.0, 1.0); this->height.unset(SVGLength::PERCENT, 1.0, 1.0); - this->_changed_connection = this->ref->changedSignal().connect( - sigc::hide(sigc::hide(sigc::mem_fun(this, &SPUse::href_changed))) - ); + this->_changed_connection = + this->ref->changedSignal().connect(sigc::hide(sigc::hide(sigc::mem_fun(this, &SPUse::href_changed)))); } -SPUse::~SPUse() { +SPUse::~SPUse() +{ if (this->child) { this->detach(this->child); this->child = nullptr; @@ -75,7 +74,8 @@ SPUse::~SPUse() { this->ref = nullptr; } -void SPUse::build(SPDocument *document, Inkscape::XML::Node *repr) { +void SPUse::build(SPDocument *document, Inkscape::XML::Node *repr) +{ SPItem::build(document, repr); this->readAttr(SPAttr::X); @@ -89,7 +89,8 @@ void SPUse::build(SPDocument *document, Inkscape::XML::Node *repr) { // which will call SPUse::href_changed, and that will take care of the child } -void SPUse::release() { +void SPUse::release() +{ if (this->child) { this->detach(this->child); this->child = nullptr; @@ -107,7 +108,8 @@ void SPUse::release() { SPItem::release(); } -void SPUse::set(SPAttr key, const gchar* value) { +void SPUse::set(SPAttr key, const gchar *value) +{ switch (key) { case SPAttr::X: this->x.readOrUnset(value); @@ -130,7 +132,7 @@ void SPUse::set(SPAttr key, const gchar* value) { break; case SPAttr::XLINK_HREF: { - if ( value && this->href && ( strcmp(value, this->href) == 0 ) ) { + if (value && this->href && (strcmp(value, this->href) == 0)) { /* No change, do nothing. */ } else { g_free(this->href); @@ -160,7 +162,8 @@ void SPUse::set(SPAttr key, const gchar* value) { } } -Inkscape::XML::Node* SPUse::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { +Inkscape::XML::Node *SPUse::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) +{ if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) { repr = xml_doc->createElement("svg:use"); } @@ -199,11 +202,12 @@ Inkscape::XML::Node* SPUse::write(Inkscape::XML::Document *xml_doc, Inkscape::XM return repr; } -Geom::OptRect SPUse::bbox(Geom::Affine const &transform, SPItem::BBoxType bboxtype) const { +Geom::OptRect SPUse::bbox(Geom::Affine const &transform, SPItem::BBoxType bboxtype) const +{ Geom::OptRect bbox; if (this->child) { - Geom::Affine const ct(child->transform * Geom::Translate(this->x.computed, this->y.computed) * transform ); + Geom::Affine const ct(child->transform * Geom::Translate(this->x.computed, this->y.computed) * transform); bbox = child->bounds(bboxtype, ct); } @@ -211,7 +215,8 @@ Geom::OptRect SPUse::bbox(Geom::Affine const &transform, SPItem::BBoxType bboxty return bbox; } -void SPUse::print(SPPrintContext* ctx) { +void SPUse::print(SPPrintContext *ctx) +{ bool translated = false; if ((this->x._set && this->x.computed != 0) || (this->y._set && this->y.computed != 0)) { @@ -229,7 +234,8 @@ void SPUse::print(SPPrintContext* ctx) { } } -const char* SPUse::displayName() const { +const char *SPUse::displayName() const +{ if (dynamic_cast<SPSymbol *>(child)) { return _("Symbol"); } else { @@ -237,13 +243,19 @@ const char* SPUse::displayName() const { } } -gchar* SPUse::description() const { +gchar *SPUse::description() const +{ if (child) { - if ( dynamic_cast<SPSymbol *>(child) ) { + if (dynamic_cast<SPSymbol *>(child)) { if (child->title()) { - return g_strdup_printf(_("called %s"), Glib::Markup::escape_text(Glib::ustring( g_dpgettext2(nullptr, "Symbol", child->title()))).c_str()); + return g_strdup_printf( + _("called %s"), + Glib::Markup::escape_text(Glib::ustring(g_dpgettext2(nullptr, "Symbol", child->title()))).c_str()); } else if (child->getAttribute("id")) { - return g_strdup_printf(_("called %s"), Glib::Markup::escape_text(Glib::ustring( g_dpgettext2(nullptr, "Symbol", child->getAttribute("id")))).c_str()); + return g_strdup_printf( + _("called %s"), + Glib::Markup::escape_text(Glib::ustring(g_dpgettext2(nullptr, "Symbol", child->getAttribute("id")))) + .c_str()); } else { return g_strdup_printf(_("called %s"), _("Unnamed Symbol")); } @@ -272,14 +284,14 @@ gchar* SPUse::description() const { } } -Inkscape::DrawingItem* SPUse::show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) { - +Inkscape::DrawingItem *SPUse::show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) +{ // std::cout << "SPUse::show: " << (getId()?getId():"null") << std::endl; Inkscape::DrawingGroup *ai = new Inkscape::DrawingGroup(drawing); ai->setPickChildren(false); this->context_style = this->style; ai->setStyle(this->style, this->context_style); - + if (this->child) { Inkscape::DrawingItem *ac = this->child->invoke_show(drawing, key, flags); @@ -294,15 +306,15 @@ Inkscape::DrawingItem* SPUse::show(Inkscape::Drawing &drawing, unsigned int key, return ai; } -void SPUse::hide(unsigned int key) { +void SPUse::hide(unsigned int key) +{ if (this->child) { this->child->invoke_hide(key); } -// SPItem::onHide(key); + // SPItem::onHide(key); } - /** * Returns the ultimate original of a SPUse (i.e. the first object in the chain of its originals * which is not an SPUse). If no original is found, NULL is returned (it is the responsibility @@ -311,7 +323,8 @@ void SPUse::hide(unsigned int key) { * Note that the returned is the clone object, i.e. the child of an SPUse (of the argument one for * the trivial case) and not the "true original". */ -SPItem *SPUse::root() { +SPItem *SPUse::root() +{ SPItem *orig = this->child; SPUse *use = dynamic_cast<SPUse *>(orig); @@ -323,15 +336,17 @@ SPItem *SPUse::root() { return orig; } -SPItem const *SPUse::root() const { - return const_cast<SPUse*>(this)->root(); +SPItem const *SPUse::root() const +{ + return const_cast<SPUse *>(this)->root(); } /** * Get the number of dereferences or calls to get_original() needed to get an object * which is not an svg:use. Returns -1 if there is no original object. */ -int SPUse::cloneDepth() const { +int SPUse::cloneDepth() const +{ unsigned depth = 1; SPItem *orig = this->child; @@ -351,11 +366,12 @@ int SPUse::cloneDepth() const { * Returns the effective transform that goes from the ultimate original to given SPUse, both ends * included. */ -Geom::Affine SPUse::get_root_transform() { - //track the ultimate source of a chain of uses +Geom::Affine SPUse::get_root_transform() +{ + // track the ultimate source of a chain of uses SPObject *orig = this->child; - std::vector<SPItem*> chain; + std::vector<SPItem *> chain; chain.push_back(this); while (dynamic_cast<SPUse *>(orig)) { @@ -368,12 +384,13 @@ Geom::Affine SPUse::get_root_transform() { // calculate the accumulated transform, starting from the original Geom::Affine t(Geom::identity()); - for (auto i=chain.rbegin(); i!=chain.rend(); ++i) { + for (auto i = chain.rbegin(); i != chain.rend(); ++i) { SPItem *i_tem = *i; // "An additional transformation translate(x,y) is appended to the end (i.e., // right-side) of the transform attribute on the generated 'g', where x and y - // represent the values of the x and y attributes on the 'use' element." - http://www.w3.org/TR/SVG11/struct.html#UseElement + // represent the values of the x and y attributes on the 'use' element." - + // http://www.w3.org/TR/SVG11/struct.html#UseElement SPUse *i_use = dynamic_cast<SPUse *>(i_tem); if (i_use) { if ((i_use->x._set && i_use->x.computed != 0) || (i_use->y._set && i_use->y.computed != 0)) { @@ -390,7 +407,8 @@ Geom::Affine SPUse::get_root_transform() { * Returns the transform that leads to the use from its immediate original. * Does not include the original's transform if any. */ -Geom::Affine SPUse::get_parent_transform() { +Geom::Affine SPUse::get_parent_transform() +{ Geom::Affine t(Geom::identity()); if ((this->x._set && this->x.computed != 0) || (this->y._set && this->y.computed != 0)) { @@ -406,7 +424,8 @@ Geom::Affine SPUse::get_parent_transform() { * that the clone stays unmoved or moves in parallel (depending on user setting) regardless of the * clone's transform. */ -void SPUse::move_compensate(Geom::Affine const *mp) { +void SPUse::move_compensate(Geom::Affine const *mp) +{ // the clone is orphaned; or this is not a real use, but a clone of another use; // we skip it, otherwise duplicate compensation will occur if (this->cloned) { @@ -429,35 +448,34 @@ void SPUse::move_compensate(Geom::Affine const *mp) { Geom::Affine clone_move = t.inverse() * m * t; // this is not a simple move, do not try to compensate - if (!(m.isTranslation())){ - //BUT move clippaths accordingly. - //if clone has a clippath, move it accordingly + if (!(m.isTranslation())) { + // BUT move clippaths accordingly. + // if clone has a clippath, move it accordingly if (getClipObject()) { for (auto &clip : getClipObject()->children) { - SPItem *item = (SPItem*) &clip; - if(item){ + SPItem *item = (SPItem *)&clip; + if (item) { item->transform *= m; Geom::Affine identity; item->doWriteTransform(item->transform, &identity); - } + } } } if (getMaskObject()) { for (auto &mask : getMaskObject()->children) { - SPItem *item = (SPItem*) &mask; - if(item){ + SPItem *item = (SPItem *)&mask; + if (item) { item->transform *= m; Geom::Affine identity; item->doWriteTransform(item->transform, &identity); - } + } } } return; } // restore item->transform field from the repr, in case it was changed by seltrans - this->readAttr (SPAttr::TRANSFORM); - + this->readAttr(SPAttr::TRANSFORM); // calculate the compensation matrix and the advertized movement matrix Geom::Affine advertized_move; @@ -471,36 +489,36 @@ void SPUse::move_compensate(Geom::Affine const *mp) { g_assert_not_reached(); } - //if clone has a clippath, move it accordingly + // if clone has a clippath, move it accordingly if (getClipObject()) { for (auto &clip : getClipObject()->children) { - SPItem *item = (SPItem*) &clip; - if(item){ + SPItem *item = (SPItem *)&clip; + if (item) { item->transform *= clone_move.inverse(); Geom::Affine identity; item->doWriteTransform(item->transform, &identity); - } + } } } if (getMaskObject()) { for (auto &mask : getMaskObject()->children) { - SPItem *item = (SPItem*) &mask; - if(item){ + SPItem *item = (SPItem *)&mask; + if (item) { item->transform *= clone_move.inverse(); Geom::Affine identity; item->doWriteTransform(item->transform, &identity); - } + } } } - // commit the compensation this->transform *= clone_move; this->doWriteTransform(this->transform, &advertized_move); this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void SPUse::href_changed() { +void SPUse::href_changed() +{ this->_delete_connection.disconnect(); this->_transformed_connection.disconnect(); @@ -515,7 +533,7 @@ void SPUse::href_changed() { if (refobj) { Inkscape::XML::Node *childrepr = refobj->getRepr(); - SPObject* obj = SPFactory::createObject(NodeTraits::get_type_string(*childrepr)); + SPObject *obj = SPFactory::createObject(NodeTraits::get_type_string(*childrepr)); SPItem *item = dynamic_cast<SPItem *>(obj); if (item) { @@ -538,18 +556,16 @@ void SPUse::href_changed() { g_warning("Tried to create svg:use from invalid object"); } - this->_delete_connection = refobj->connectDelete( - sigc::hide(sigc::mem_fun(this, &SPUse::delete_self)) - ); + this->_delete_connection = refobj->connectDelete(sigc::hide(sigc::mem_fun(this, &SPUse::delete_self))); - this->_transformed_connection = refobj->connectTransformed( - sigc::hide(sigc::mem_fun(this, &SPUse::move_compensate)) - ); + this->_transformed_connection = + refobj->connectTransformed(sigc::hide(sigc::mem_fun(this, &SPUse::move_compensate))); } } } -void SPUse::delete_self() { +void SPUse::delete_self() +{ // always delete uses which are used in flowtext if (parent && dynamic_cast<SPFlowregion *>(parent)) { deleteObject(); @@ -557,8 +573,7 @@ void SPUse::delete_self() { } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - guint const mode = prefs->getInt("/options/cloneorphans/value", - SP_CLONE_ORPHANS_UNLINK); + guint const mode = prefs->getInt("/options/cloneorphans/value", SP_CLONE_ORPHANS_UNLINK); if (mode == SP_CLONE_ORPHANS_UNLINK) { this->unlink(); @@ -567,9 +582,10 @@ void SPUse::delete_self() { } } -void SPUse::update(SPCtx *ctx, unsigned flags) { +void SPUse::update(SPCtx *ctx, unsigned flags) +{ // std::cout << "SPUse::update: " << (getId()?getId():"null") << std::endl; - SPItemCtx *ictx = (SPItemCtx *) ctx; + SPItemCtx *ictx = (SPItemCtx *)ctx; SPItemCtx cctx = *ictx; unsigned childflags = flags; @@ -588,11 +604,11 @@ void SPUse::update(SPCtx *ctx, unsigned flags) { sp_object_ref(this->child); // viewport is only changed if referencing a symbol or svg element - if( SP_IS_SYMBOL(this->child) || SP_IS_ROOT(this->child) ) { + if (SP_IS_SYMBOL(this->child) || SP_IS_ROOT(this->child)) { cctx.viewport = Geom::Rect::from_xywh(0, 0, this->width.computed, this->height.computed); cctx.i2vp = Geom::identity(); } - + if (childflags || (this->child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { SPItem const *chi = dynamic_cast<SPItem const *>(child); g_assert(chi != nullptr); @@ -622,7 +638,8 @@ void SPUse::update(SPCtx *ctx, unsigned flags) { } } -void SPUse::modified(unsigned int flags) { +void SPUse::modified(unsigned int flags) +{ // std::cout << "SPUse::modified: " << (getId()?getId():"null") << std::endl; if (flags & SP_OBJECT_MODIFIED_FLAG) { flags |= SP_OBJECT_PARENT_MODIFIED_FLAG; @@ -631,11 +648,11 @@ void SPUse::modified(unsigned int flags) { flags &= SP_OBJECT_MODIFIED_CASCADE; if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) { - for (SPItemView *v = this->display; v != nullptr; v = v->next) { - Inkscape::DrawingGroup *g = dynamic_cast<Inkscape::DrawingGroup *>(v->arenaitem); - this->context_style = this->style; - g->setStyle(this->style, this->context_style); - } + for (SPItemView *v = this->display; v != nullptr; v = v->next) { + Inkscape::DrawingGroup *g = dynamic_cast<Inkscape::DrawingGroup *>(v->arenaitem); + this->context_style = this->style; + g->setStyle(this->style, this->context_style); + } } if (child) { @@ -649,7 +666,8 @@ void SPUse::modified(unsigned int flags) { } } -SPItem *SPUse::unlink() { +SPItem *SPUse::unlink() +{ Inkscape::XML::Node *repr = this->getRepr(); if (!repr) { @@ -676,9 +694,9 @@ SPItem *SPUse::unlink() { // make a group, copy children copy = xml_doc->createElement("svg:g"); - for (Inkscape::XML::Node *child = orig->getRepr()->firstChild() ; child != nullptr; child = child->next()) { - Inkscape::XML::Node *newchild = child->duplicate(xml_doc); - copy->appendChild(newchild); + for (Inkscape::XML::Node *child = orig->getRepr()->firstChild(); child != nullptr; child = child->next()) { + Inkscape::XML::Node *newchild = child->duplicate(xml_doc); + copy->appendChild(newchild); } // viewBox transformation @@ -694,8 +712,8 @@ SPItem *SPUse::unlink() { SPObject *unlinked = document->getObjectByRepr(copy); // Merge style from the use. - unlinked->style->merge( this->style ); - unlinked->style->cascade( unlinked->parent->style ); + unlinked->style->merge(this->style); + unlinked->style->cascade(unlinked->parent->style); unlinked->updateRepr(); // Hold onto our SPObject and repr for now. @@ -734,17 +752,19 @@ SPItem *SPUse::unlink() { return item; } -SPItem *SPUse::get_original() { +SPItem *SPUse::get_original() +{ SPItem *ref = nullptr; - if (this->ref){ - ref = this->ref->getObject(); - } + if (this->ref) { + ref = this->ref->getObject(); + } return ref; } -void SPUse::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const { +void SPUse::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const +{ SPItem const *root = this->root(); if (!root) { @@ -754,7 +774,6 @@ void SPUse::snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::S root->snappoints(p, snapprefs); } - /* Local Variables: mode:c++ diff --git a/src/object/sp-use.h b/src/object/sp-use.h index 23922efd8722a43694fddfdd4824c0db53d9721b..aa1fa0ce3440c450c0793dc9252c6254ce600860 100644 --- a/src/object/sp-use.h +++ b/src/object/sp-use.h @@ -19,17 +19,20 @@ #include <cstddef> #include <sigc++/sigc++.h> -#include "svg/svg-length.h" +#include "enums.h" #include "sp-dimensions.h" #include "sp-item.h" -#include "enums.h" +#include "svg/svg-length.h" class SPUseReference; -class SPUse : public SPItem, public SPDimensions { +class SPUse + : public SPItem + , public SPDimensions +{ public: - SPUse(); - ~SPUse() override; + SPUse(); + ~SPUse() override; // item built from the original's repr (the visible clone) // relative to the SPUse itself, it is treated as a child, similar to a grouped item relative to its group @@ -48,29 +51,31 @@ public: // a sigc connection for transformed signal, used to do move compensation sigc::connection _transformed_connection; - void build(SPDocument* doc, Inkscape::XML::Node* repr) override; - void release() override; - void set(SPAttr key, char const *value) override; - Inkscape::XML::Node* write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, unsigned int flags) override; - void update(SPCtx* ctx, unsigned int flags) override; - void modified(unsigned int flags) override; - - Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType bboxtype) const override; - const char* displayName() const override; - char* description() const override; - void print(SPPrintContext *ctx) override; - Inkscape::DrawingItem* show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; - void hide(unsigned int key) override; - void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const override; - - SPItem *root(); - SPItem const *root() const; + void build(SPDocument *doc, Inkscape::XML::Node *repr) override; + void release() override; + void set(SPAttr key, char const *value) override; + Inkscape::XML::Node *write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, + unsigned int flags) override; + void update(SPCtx *ctx, unsigned int flags) override; + void modified(unsigned int flags) override; + + Geom::OptRect bbox(Geom::Affine const &transform, SPItem::BBoxType bboxtype) const override; + const char *displayName() const override; + char *description() const override; + void print(SPPrintContext *ctx) override; + Inkscape::DrawingItem *show(Inkscape::Drawing &drawing, unsigned int key, unsigned int flags) override; + void hide(unsigned int key) override; + void snappoints(std::vector<Inkscape::SnapCandidatePoint> &p, + Inkscape::SnapPreferences const *snapprefs) const override; + + SPItem *root(); + SPItem const *root() const; int cloneDepth() const; - SPItem *unlink(); - SPItem *get_original(); - Geom::Affine get_parent_transform(); - Geom::Affine get_root_transform(); + SPItem *unlink(); + SPItem *get_original(); + Geom::Affine get_parent_transform(); + Geom::Affine get_root_transform(); private: void href_changed(); diff --git a/src/object/uri-references.cpp b/src/object/uri-references.cpp index 64e4c8b1a72607b3a9442923c0268b633140140d..1b37190c7e9cd55903de2299271a656fc2531672 100644 --- a/src/object/uri-references.cpp +++ b/src/object/uri-references.cpp @@ -14,17 +14,17 @@ #include "uri-references.h" -#include <iostream> #include <cstring> - #include <glibmm/miscutils.h> -#include "live_effects/lpeobject.h" +#include <iostream> + #include "bad-uri-exception.h" #include "document.h" -#include "sp-object.h" -#include "uri.h" #include "extract-uri.h" +#include "live_effects/lpeobject.h" +#include "sp-object.h" #include "sp-tag-use.h" +#include "uri.h" namespace Inkscape { @@ -56,7 +56,7 @@ URIReference::~URIReference() * The main ideas here are: * (1) "If we are inside a clone, then we can accept if and only if our "original thing" can accept the reference" * (this caused problems when there are clones because a change in ids triggers signals for the object hrefing this id, - * but also its cloned reprs(descendants of <use> referencing an ancestor of the href'ing object)). + * but also its cloned reprs(descendants of <use> referencing an ancestor of the href'ing object)). * * (2) Once we have an (potential owner) object, it can accept a href to obj, iff the graph of objects where directed * edges are @@ -73,18 +73,20 @@ bool URIReference::_acceptObject(SPObject *obj) const // we go back following hrefList and parent to find if the object already references ourselves indirectly std::set<SPObject *> done; SPObject *owner = getOwner(); - //allow LPE as owner has any URI attached + // allow LPE as owner has any URI attached LivePathEffectObject *lpobj = dynamic_cast<LivePathEffectObject *>(obj); if (!owner || lpobj) return true; - + while (owner->cloned) { - if(!owner->clone_original)//happens when the clone is existing and linking to something, even before the original objects exists. - //for instance, it can happen when you paste a filtered object in a already cloned group: The construction of the - //clone representation of the filtered object will finish before the original object, so the cloned repr will - //have to _accept the filter even though the original does not exist yet. In that case, we'll accept iff the parent of the - //original can accept it: loops caused by other relations than parent-child would be prevented when created on their base object. - //Fixes bug 1636533. + if (!owner->clone_original) // happens when the clone is existing and linking to something, even before the + // original objects exists. for instance, it can happen when you paste a filtered + // object in a already cloned group: The construction of the clone representation of + // the filtered object will finish before the original object, so the cloned repr + // will have to _accept the filter even though the original does not exist yet. In + // that case, we'll accept iff the parent of the original can accept it: loops + // caused by other relations than parent-child would be prevented when created on + // their base object. Fixes bug 1636533. owner = owner->parent; else owner = owner->clone_original; @@ -251,8 +253,6 @@ void URIReference::_release(SPObject *obj) } /* namespace Inkscape */ - - SPObject *sp_css_uri_reference_resolve(SPDocument *document, const gchar *uri) { SPObject *ref = nullptr; diff --git a/src/object/uri-references.h b/src/object/uri-references.h index 2b891637c036b0e4538d908c8e17cc162dd86514..c3115ae073be1d46a9fb0a5dcf70be615773e58f 100644 --- a/src/object/uri-references.h +++ b/src/object/uri-references.h @@ -16,10 +16,10 @@ */ #include <cstddef> -#include <vector> #include <set> #include <sigc++/connection.h> #include <sigc++/trackable.h> +#include <vector> class SPObject; class SPDocument; @@ -37,7 +37,8 @@ class URI; * * @see SPObject */ -class URIReference : public sigc::trackable { +class URIReference : public sigc::trackable +{ public: /** * Constructor. @@ -49,7 +50,7 @@ public: URIReference(SPDocument *owner_document); /* Definition-less to prevent accidental use. */ - void operator=(URIReference const& ref) = delete; + void operator=(URIReference const &ref) = delete; /** * Destructor. Calls shutdown() if the reference has not been @@ -65,7 +66,7 @@ public: * * @param uri the URI to watch */ - void attach(URI const& uri); + void attach(URI const &uri); /** * Try to attach to a URI. Return false if URL is malformed and detach any @@ -104,9 +105,7 @@ public: * * @returns a signal */ - sigc::signal<void, SPObject *, SPObject *> changedSignal() { - return _changed_signal; - } + sigc::signal<void, SPObject *, SPObject *> changedSignal() { return _changed_signal; } /** * Returns a pointer to a URI containing the currently attached @@ -114,24 +113,21 @@ public: * * @returns the currently attached URI, or NULL */ - URI const* getURI() const { - return _uri; - } + URI const *getURI() const { return _uri; } /** * Returns true if there is currently an attached URI * * @returns true if there is an attached URI */ - bool isAttached() const { - return (bool)_uri; - } + bool isAttached() const { return (bool)_uri; } SPDocument *getOwnerDocument() { return _owner_document; } - SPObject *getOwnerObject() { return _owner; } + SPObject *getOwnerObject() { return _owner; } protected: virtual bool _acceptObject(SPObject *obj) const; + private: SPObject *_owner; SPDocument *_owner_document; @@ -146,14 +142,14 @@ private: void _release(SPObject *object); }; -} +} // namespace Inkscape /** * Resolves an item referenced by a URI in CSS form contained in "url(...)" */ -SPObject* sp_css_uri_reference_resolve( SPDocument *document, const char *uri ); +SPObject *sp_css_uri_reference_resolve(SPDocument *document, const char *uri); -SPObject *sp_uri_reference_resolve (SPDocument *document, const char *uri); +SPObject *sp_uri_reference_resolve(SPDocument *document, const char *uri); #endif // SEEN_SP_URI_REFERENCES_H diff --git a/src/object/uri.cpp b/src/object/uri.cpp index 05539a69e258c711e9c52abab57104151831e2e2..1dff59b67df0451db948fab3868afb828e7783c4 100644 --- a/src/object/uri.cpp +++ b/src/object/uri.cpp @@ -12,13 +12,12 @@ #include "uri.h" #include <cstring> - #include <giomm/contenttype.h> #include <giomm/file.h> #include <glibmm/base64.h> #include <glibmm/convert.h> -#include <glibmm/ustring.h> #include <glibmm/miscutils.h> +#include <glibmm/ustring.h> #include "bad-uri-exception.h" @@ -42,7 +41,8 @@ static bool uri_needs_escaping(char const *uri) return false; } -URI::URI() { +URI::URI() +{ init(xmlCreateURI()); } @@ -96,8 +96,7 @@ URI::URI(gchar const *preformed, char const *baseuri) URI::URI(char const *preformed, URI const &baseuri) : URI::URI(preformed, baseuri.str().c_str()) -{ -} +{} // From RFC 2396: // @@ -120,19 +119,23 @@ URI::URI(char const *preformed, URI const &baseuri) // // authority = server | reg_name -bool URI::isOpaque() const { +bool URI::isOpaque() const +{ return getOpaque() != nullptr; } -bool URI::isRelative() const { +bool URI::isRelative() const +{ return !_xmlURIPtr()->scheme; } -bool URI::isNetPath() const { +bool URI::isNetPath() const +{ return isRelative() && _xmlURIPtr()->server; } -bool URI::isRelativePath() const { +bool URI::isRelativePath() const +{ if (isRelative() && !_xmlURIPtr()->server) { const gchar *path = getPath(); return path && path[0] != '/'; @@ -140,7 +143,8 @@ bool URI::isRelativePath() const { return false; } -bool URI::isAbsolutePath() const { +bool URI::isAbsolutePath() const +{ if (isRelative() && !_xmlURIPtr()->server) { const gchar *path = getPath(); return path && path[0] == '/'; @@ -148,23 +152,28 @@ bool URI::isAbsolutePath() const { return false; } -const gchar *URI::getScheme() const { +const gchar *URI::getScheme() const +{ return (gchar *)_xmlURIPtr()->scheme; } -const gchar *URI::getPath() const { +const gchar *URI::getPath() const +{ return (gchar *)_xmlURIPtr()->path; } -const gchar *URI::getQuery() const { +const gchar *URI::getQuery() const +{ return (gchar *)_xmlURIPtr()->query; } -const gchar *URI::getFragment() const { +const gchar *URI::getFragment() const +{ return (gchar *)_xmlURIPtr()->fragment; } -const gchar *URI::getOpaque() const { +const gchar *URI::getOpaque() const +{ if (!isRelative() && !_xmlURIPtr()->server) { const gchar *path = getPath(); if (path && path[0] != '/') { @@ -187,10 +196,11 @@ std::string URI::toNativeFilename() const } /* TODO !!! proper error handling */ -URI URI::from_native_filename(gchar const *path) { +URI URI::from_native_filename(gchar const *path) +{ gchar *uri = g_filename_to_uri(path, nullptr, nullptr); URI result(uri); - g_free( uri ); + g_free(uri); return result; } @@ -446,7 +456,6 @@ std::string uri_to_iri(const char *uri) } // namespace Inkscape - /* Local Variables: mode:c++ diff --git a/src/object/uri.h b/src/object/uri.h index 381adec58cf3171d6f6aef9f71fe8d0ea91f3226..2c734b612387b70116184c5907b0c4bf6221b246 100644 --- a/src/object/uri.h +++ b/src/object/uri.h @@ -32,9 +32,9 @@ namespace Inkscape { * * Implementation detail: Immutable type, copies share a ref-counted data pointer. */ -class URI { +class URI +{ public: - /* Blank constructor */ URI(); @@ -172,9 +172,7 @@ public: * * @param baseuri Return a relative path if this URI shares protocol and host with @a baseuri */ - std::string cssStr(char const *baseuri = nullptr) const { - return "url(" + str(baseuri) + ")"; - } + std::string cssStr(char const *baseuri = nullptr) const { return "url(" + str(baseuri) + ")"; } /** * True if the scheme equals the given string (not case sensitive) @@ -200,7 +198,7 @@ private: */ std::string uri_to_iri(const char *uri); -} /* namespace Inkscape */ +} /* namespace Inkscape */ #endif diff --git a/src/object/viewbox.cpp b/src/object/viewbox.cpp index 06a6725988d5141febaca5dbb9c34854db8cde3a..740327abe90d553b3c01194f04bd264d7b6fc9b1 100644 --- a/src/object/viewbox.cpp +++ b/src/object/viewbox.cpp @@ -13,9 +13,10 @@ * */ +#include "viewbox.h" + #include <2geom/transforms.h> -#include "viewbox.h" #include "enums.h" #include "sp-item.h" @@ -26,143 +27,143 @@ SPViewBox::SPViewBox() , aspect_align(SP_ASPECT_XMID_YMID) // Default per spec , aspect_clip(SP_ASPECT_MEET) , c2p(Geom::identity()) -{ -} - -void SPViewBox::set_viewBox(const gchar* value) { - - if (value) { - gchar *eptr = const_cast<gchar*>(value); // const-cast necessary because of const-incorrect interface definition of g_ascii_strtod - - double x = g_ascii_strtod (eptr, &eptr); - - while (*eptr && ((*eptr == ',') || (*eptr == ' '))) { - eptr++; - } +{} - double y = g_ascii_strtod (eptr, &eptr); - - while (*eptr && ((*eptr == ',') || (*eptr == ' '))) { - eptr++; - } - - double width = g_ascii_strtod (eptr, &eptr); - - while (*eptr && ((*eptr == ',') || (*eptr == ' '))) { - eptr++; - } - - double height = g_ascii_strtod (eptr, &eptr); - - while (*eptr && ((*eptr == ',') || (*eptr == ' '))) { - eptr++; - } - - if ((width > 0) && (height > 0)) { - /* Set viewbox */ - this->viewBox = Geom::Rect::from_xywh(x, y, width, height); - this->viewBox_set = true; - } else { - this->viewBox_set = false; - } - } else { - this->viewBox_set = false; - } - - // The C++ way? -- not necessarily using iostreams - // std::string sv( value ); - // std::replace( sv.begin(), sv.end(), ',', ' '); - // std::stringstream ss( sv ); - // double x, y, width, height; - // ss >> x >> y >> width >> height; -} - -void SPViewBox::set_preserveAspectRatio(const gchar* value) { +void SPViewBox::set_viewBox(const gchar *value) +{ + if (value) { + gchar *eptr = const_cast<gchar *>(value); // const-cast necessary because of const-incorrect interface + // definition of g_ascii_strtod - /* Do setup before, so we can use break to escape */ - this->aspect_set = false; - this->aspect_align = SP_ASPECT_XMID_YMID; // Default per spec - this->aspect_clip = SP_ASPECT_MEET; + double x = g_ascii_strtod(eptr, &eptr); - if (value) { - const gchar *p = value; + while (*eptr && ((*eptr == ',') || (*eptr == ' '))) { + eptr++; + } - while (*p && (*p == 32)) { - p += 1; - } + double y = g_ascii_strtod(eptr, &eptr); - if (!*p) { - return; - } + while (*eptr && ((*eptr == ',') || (*eptr == ' '))) { + eptr++; + } - const gchar *e = p; + double width = g_ascii_strtod(eptr, &eptr); - while (*e && (*e != 32)) { - e += 1; - } + while (*eptr && ((*eptr == ',') || (*eptr == ' '))) { + eptr++; + } - int len = e - p; + double height = g_ascii_strtod(eptr, &eptr); - if (len > 8) { // Can't have buffer overflow as 8 < 256 - return; - } + while (*eptr && ((*eptr == ',') || (*eptr == ' '))) { + eptr++; + } - gchar c[256]; - memcpy (c, value, len); - - c[len] = 0; - - /* Now the actual part */ - unsigned int align = SP_ASPECT_NONE; - if (!strcmp (c, "none")) { - align = SP_ASPECT_NONE; - } else if (!strcmp (c, "xMinYMin")) { - align = SP_ASPECT_XMIN_YMIN; - } else if (!strcmp (c, "xMidYMin")) { - align = SP_ASPECT_XMID_YMIN; - } else if (!strcmp (c, "xMaxYMin")) { - align = SP_ASPECT_XMAX_YMIN; - } else if (!strcmp (c, "xMinYMid")) { - align = SP_ASPECT_XMIN_YMID; - } else if (!strcmp (c, "xMidYMid")) { - align = SP_ASPECT_XMID_YMID; - } else if (!strcmp (c, "xMaxYMid")) { - align = SP_ASPECT_XMAX_YMID; - } else if (!strcmp (c, "xMinYMax")) { - align = SP_ASPECT_XMIN_YMAX; - } else if (!strcmp (c, "xMidYMax")) { - align = SP_ASPECT_XMID_YMAX; - } else if (!strcmp (c, "xMaxYMax")) { - align = SP_ASPECT_XMAX_YMAX; + if ((width > 0) && (height > 0)) { + /* Set viewbox */ + this->viewBox = Geom::Rect::from_xywh(x, y, width, height); + this->viewBox_set = true; + } else { + this->viewBox_set = false; + } } else { - return; + this->viewBox_set = false; } - unsigned int clip = SP_ASPECT_MEET; - - while (*e && (*e == 32)) { - e += 1; - } + // The C++ way? -- not necessarily using iostreams + // std::string sv( value ); + // std::replace( sv.begin(), sv.end(), ',', ' '); + // std::stringstream ss( sv ); + // double x, y, width, height; + // ss >> x >> y >> width >> height; +} - if (*e) { - if (!strcmp (e, "meet")) { - clip = SP_ASPECT_MEET; - } else if (!strcmp (e, "slice")) { - clip = SP_ASPECT_SLICE; - } else { - return; - } +void SPViewBox::set_preserveAspectRatio(const gchar *value) +{ + /* Do setup before, so we can use break to escape */ + this->aspect_set = false; + this->aspect_align = SP_ASPECT_XMID_YMID; // Default per spec + this->aspect_clip = SP_ASPECT_MEET; + + if (value) { + const gchar *p = value; + + while (*p && (*p == 32)) { + p += 1; + } + + if (!*p) { + return; + } + + const gchar *e = p; + + while (*e && (*e != 32)) { + e += 1; + } + + int len = e - p; + + if (len > 8) { // Can't have buffer overflow as 8 < 256 + return; + } + + gchar c[256]; + memcpy(c, value, len); + + c[len] = 0; + + /* Now the actual part */ + unsigned int align = SP_ASPECT_NONE; + if (!strcmp(c, "none")) { + align = SP_ASPECT_NONE; + } else if (!strcmp(c, "xMinYMin")) { + align = SP_ASPECT_XMIN_YMIN; + } else if (!strcmp(c, "xMidYMin")) { + align = SP_ASPECT_XMID_YMIN; + } else if (!strcmp(c, "xMaxYMin")) { + align = SP_ASPECT_XMAX_YMIN; + } else if (!strcmp(c, "xMinYMid")) { + align = SP_ASPECT_XMIN_YMID; + } else if (!strcmp(c, "xMidYMid")) { + align = SP_ASPECT_XMID_YMID; + } else if (!strcmp(c, "xMaxYMid")) { + align = SP_ASPECT_XMAX_YMID; + } else if (!strcmp(c, "xMinYMax")) { + align = SP_ASPECT_XMIN_YMAX; + } else if (!strcmp(c, "xMidYMax")) { + align = SP_ASPECT_XMID_YMAX; + } else if (!strcmp(c, "xMaxYMax")) { + align = SP_ASPECT_XMAX_YMAX; + } else { + return; + } + + unsigned int clip = SP_ASPECT_MEET; + + while (*e && (*e == 32)) { + e += 1; + } + + if (*e) { + if (!strcmp(e, "meet")) { + clip = SP_ASPECT_MEET; + } else if (!strcmp(e, "slice")) { + clip = SP_ASPECT_SLICE; + } else { + return; + } + } + + this->aspect_set = true; + this->aspect_align = align; + this->aspect_clip = clip; } - - this->aspect_set = true; - this->aspect_align = align; - this->aspect_clip = clip; - } } // Apply scaling from viewbox -void SPViewBox::apply_viewbox(const Geom::Rect& in, double scale_none) { - +void SPViewBox::apply_viewbox(const Geom::Rect &in, double scale_none) +{ /* Determine actual viewbox in viewport coordinates */ // scale_none is the scale that would apply if the viewbox and page size are same size // it is passed here because it is a double-precision variable, while 'in' is originally float @@ -173,55 +174,55 @@ void SPViewBox::apply_viewbox(const Geom::Rect& in, double scale_none) { double scale_uniform = 1.0; // used only if scaling is uniform if (Geom::are_near(scale_x / scale_y, 1.0, Geom::EPSILON)) { - // scaling is already uniform, reduce numerical error - scale_uniform = (scale_x + scale_y)/2.0; - if (Geom::are_near(scale_uniform / scale_none, 1.0, Geom::EPSILON)) - scale_uniform = scale_none; // objects are same size, reduce numerical error - scale_x = scale_uniform; - scale_y = scale_uniform; + // scaling is already uniform, reduce numerical error + scale_uniform = (scale_x + scale_y) / 2.0; + if (Geom::are_near(scale_uniform / scale_none, 1.0, Geom::EPSILON)) + scale_uniform = scale_none; // objects are same size, reduce numerical error + scale_x = scale_uniform; + scale_y = scale_uniform; } else if (this->aspect_align != SP_ASPECT_NONE) { - // scaling is not uniform, but force it to be - scale_uniform = (this->aspect_clip == SP_ASPECT_MEET) ? MIN (scale_x, scale_y) : MAX (scale_x, scale_y); - scale_x = scale_uniform; - scale_y = scale_uniform; - double width = this->viewBox.width() * scale_uniform; - double height = this->viewBox.height() * scale_uniform; - - /* Now place viewbox to requested position */ - switch (this->aspect_align) { - case SP_ASPECT_XMIN_YMIN: - break; - case SP_ASPECT_XMID_YMIN: - x = 0.5 * (in.width() - width); - break; - case SP_ASPECT_XMAX_YMIN: - x = 1.0 * (in.width() - width); - break; - case SP_ASPECT_XMIN_YMID: - y = 0.5 * (in.height() - height); - break; - case SP_ASPECT_XMID_YMID: - x = 0.5 * (in.width() - width); - y = 0.5 * (in.height() - height); - break; - case SP_ASPECT_XMAX_YMID: - x = 1.0 * (in.width() - width); - y = 0.5 * (in.height() - height); - break; - case SP_ASPECT_XMIN_YMAX: - y = 1.0 * (in.height() - height); - break; - case SP_ASPECT_XMID_YMAX: - x = 0.5 * (in.width() - width); - y = 1.0 * (in.height() - height); - break; - case SP_ASPECT_XMAX_YMAX: - x = 1.0 * (in.width() - width); - y = 1.0 * (in.height() - height); - break; - default: - break; - } + // scaling is not uniform, but force it to be + scale_uniform = (this->aspect_clip == SP_ASPECT_MEET) ? MIN(scale_x, scale_y) : MAX(scale_x, scale_y); + scale_x = scale_uniform; + scale_y = scale_uniform; + double width = this->viewBox.width() * scale_uniform; + double height = this->viewBox.height() * scale_uniform; + + /* Now place viewbox to requested position */ + switch (this->aspect_align) { + case SP_ASPECT_XMIN_YMIN: + break; + case SP_ASPECT_XMID_YMIN: + x = 0.5 * (in.width() - width); + break; + case SP_ASPECT_XMAX_YMIN: + x = 1.0 * (in.width() - width); + break; + case SP_ASPECT_XMIN_YMID: + y = 0.5 * (in.height() - height); + break; + case SP_ASPECT_XMID_YMID: + x = 0.5 * (in.width() - width); + y = 0.5 * (in.height() - height); + break; + case SP_ASPECT_XMAX_YMID: + x = 1.0 * (in.width() - width); + y = 0.5 * (in.height() - height); + break; + case SP_ASPECT_XMIN_YMAX: + y = 1.0 * (in.height() - height); + break; + case SP_ASPECT_XMID_YMAX: + x = 0.5 * (in.width() - width); + y = 1.0 * (in.height() - height); + break; + case SP_ASPECT_XMAX_YMAX: + x = 1.0 * (in.width() - width); + y = 1.0 * (in.height() - height); + break; + default: + break; + } } /* Viewbox transform from scale and position */ @@ -239,30 +240,30 @@ void SPViewBox::apply_viewbox(const Geom::Rect& in, double scale_none) { this->c2p = q * this->c2p; } -SPItemCtx SPViewBox::get_rctx(const SPItemCtx* ictx, double scale_none) { - - /* Create copy of item context */ - SPItemCtx rctx = *ictx; +SPItemCtx SPViewBox::get_rctx(const SPItemCtx *ictx, double scale_none) +{ + /* Create copy of item context */ + SPItemCtx rctx = *ictx; - /* Calculate child to parent transformation */ - /* Apply parent translation (set up as viewport) */ - this->c2p = Geom::Translate(rctx.viewport.min()); + /* Calculate child to parent transformation */ + /* Apply parent translation (set up as viewport) */ + this->c2p = Geom::Translate(rctx.viewport.min()); - if (this->viewBox_set) { - // Adjusts c2p for viewbox - apply_viewbox( rctx.viewport, scale_none ); - } + if (this->viewBox_set) { + // Adjusts c2p for viewbox + apply_viewbox(rctx.viewport, scale_none); + } - rctx.i2doc = this->c2p * rctx.i2doc; + rctx.i2doc = this->c2p * rctx.i2doc; - /* If viewBox is set initialize child viewport */ - /* Otherwise it is already correct */ - if (this->viewBox_set) { - rctx.viewport = this->viewBox; - rctx.i2vp = Geom::identity(); - } + /* If viewBox is set initialize child viewport */ + /* Otherwise it is already correct */ + if (this->viewBox_set) { + rctx.viewport = this->viewBox; + rctx.i2vp = Geom::identity(); + } - return rctx; + return rctx; } /* diff --git a/src/object/viewbox.h b/src/object/viewbox.h index 42032d24e3bb7e9a518667f2e25c37c109f1812b..75a4b02006dbfb31afe794b47c8e84538309e466 100644 --- a/src/object/viewbox.h +++ b/src/object/viewbox.h @@ -21,31 +21,30 @@ class SPItemCtx; -class SPViewBox { - +class SPViewBox +{ public: - SPViewBox(); - - /* viewBox; */ - bool viewBox_set; - Geom::Rect viewBox; // Could use optrect + SPViewBox(); - /* preserveAspectRatio */ - bool aspect_set; - unsigned int aspect_align; // enum - unsigned int aspect_clip; // enum + /* viewBox; */ + bool viewBox_set; + Geom::Rect viewBox; // Could use optrect - /* Child to parent additional transform */ - Geom::Affine c2p; + /* preserveAspectRatio */ + bool aspect_set; + unsigned int aspect_align; // enum + unsigned int aspect_clip; // enum - void set_viewBox(const gchar* value); - void set_preserveAspectRatio(const gchar* value); + /* Child to parent additional transform */ + Geom::Affine c2p; - /* Adjusts c2p for viewbox */ - void apply_viewbox(const Geom::Rect& in, double scale_none = 1.0); + void set_viewBox(const gchar *value); + void set_preserveAspectRatio(const gchar *value); - SPItemCtx get_rctx( const SPItemCtx* ictx, double scale_none = 1.0); + /* Adjusts c2p for viewbox */ + void apply_viewbox(const Geom::Rect &in, double scale_none = 1.0); + SPItemCtx get_rctx(const SPItemCtx *ictx, double scale_none = 1.0); }; #endif diff --git a/src/path-chemistry.cpp b/src/path-chemistry.cpp index 727c706bb25a903e8a14252861d375cb548a9b07..da52959a5ebfd0b5f8fd7a44943478fa02af2315 100644 --- a/src/path-chemistry.cpp +++ b/src/path-chemistry.cpp @@ -15,83 +15,74 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> -#include <string> +#include "path-chemistry.h" +#include <cstring> #include <glibmm/i18n.h> - +#include <string> #include "desktop.h" +#include "display/curve.h" #include "document-undo.h" #include "document.h" #include "message-stack.h" -#include "path-chemistry.h" -#include "selection-chemistry.h" -#include "selection.h" -#include "text-editing.h" -#include "verbs.h" - -#include "display/curve.h" - #include "object/box3d.h" #include "object/object-set.h" #include "object/sp-flowtext.h" #include "object/sp-path.h" #include "object/sp-text.h" +#include "selection-chemistry.h" +#include "selection.h" #include "style.h" - -#include "ui/widget/canvas.h" // Disable drawing during ops - #include "svg/svg.h" - +#include "text-editing.h" +#include "ui/widget/canvas.h" // Disable drawing during ops +#include "verbs.h" #include "xml/repr.h" using Inkscape::DocumentUndo; using Inkscape::ObjectSet; - inline bool less_than_items(SPItem const *first, SPItem const *second) { - return sp_repr_compare_position(first->getRepr(), - second->getRepr())<0; + return sp_repr_compare_position(first->getRepr(), second->getRepr()) < 0; } -void -ObjectSet::combine(bool skip_undo) +void ObjectSet::combine(bool skip_undo) { - //Inkscape::Selection *selection = desktop->getSelection(); - //Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + // Inkscape::Selection *selection = desktop->getSelection(); + // Inkscape::Preferences *prefs = Inkscape::Preferences::get(); SPDocument *doc = document(); - std::vector<SPItem*> items_copy(items().begin(), items().end()); - + std::vector<SPItem *> items_copy(items().begin(), items().end()); + if (items_copy.size() < 1) { - if(desktop()) + if (desktop()) desktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to combine.")); return; } - if(desktop()){ + if (desktop()) { desktop()->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Combining paths...")); // set "busy" cursor desktop()->setWaitingCursor(); } - items_copy = sp_degroup_list (items_copy); // descend into any groups in selection + items_copy = sp_degroup_list(items_copy); // descend into any groups in selection - std::vector<SPItem*> to_paths; - for (std::vector<SPItem*>::const_reverse_iterator i = items_copy.rbegin(); i != items_copy.rend(); ++i) { + std::vector<SPItem *> to_paths; + for (std::vector<SPItem *>::const_reverse_iterator i = items_copy.rbegin(); i != items_copy.rend(); ++i) { if (!dynamic_cast<SPPath *>(*i) && !dynamic_cast<SPGroup *>(*i)) { to_paths.push_back(*i); } } - std::vector<Inkscape::XML::Node*> converted; + std::vector<Inkscape::XML::Node *> converted; bool did = sp_item_list_to_curves(to_paths, items_copy, converted); for (auto i : converted) - items_copy.push_back((SPItem*)doc->getObjectByRepr(i)); + items_copy.push_back((SPItem *)doc->getObjectByRepr(i)); - items_copy = sp_degroup_list (items_copy); // converting to path may have added more groups, descend again + items_copy = sp_degroup_list(items_copy); // converting to path may have added more groups, descend again - sort(items_copy.begin(),items_copy.end(),less_than_items); + sort(items_copy.begin(), items_copy.end(), less_than_items); assert(!items_copy.empty()); // cannot be NULL because of list length check at top of function // remember the position, id, transform and style of the topmost path, they will be assigned to the combined one @@ -101,14 +92,13 @@ ObjectSet::combine(bool skip_undo) std::unique_ptr<SPCurve> curve; SPItem *first = nullptr; - Inkscape::XML::Node *parent = nullptr; + Inkscape::XML::Node *parent = nullptr; if (did) { clear(); } - for (std::vector<SPItem*>::const_reverse_iterator i = items_copy.rbegin(); i != items_copy.rend(); ++i){ - + for (std::vector<SPItem *>::const_reverse_iterator i = items_copy.rbegin(); i != items_copy.rend(); ++i) { SPItem *item = *i; SPPath *path = dynamic_cast<SPPath *>(item); if (!path) { @@ -121,14 +111,14 @@ ObjectSet::combine(bool skip_undo) } auto c = SPCurve::copy(path->curveForEdit()); - if (first == nullptr) { // this is the topmost path + if (first == nullptr) { // this is the topmost path first = item; parent = first->getRepr()->parent(); position = first->getRepr()->position(); transform = first->getRepr()->attribute("transform"); // FIXME: merge styles of combined objects instead of using the first one's style path_effect = first->getRepr()->attribute("inkscape:path-effect"); - //c->transform(item->transform); + // c->transform(item->transform); curve = std::move(c); } else { c->transform(item->getRelativeTransform(first)); @@ -143,7 +133,6 @@ ObjectSet::combine(bool skip_undo) } } - if (did) { Inkscape::XML::Document *xml_doc = doc->getReprDoc(); Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); @@ -173,32 +162,31 @@ ObjectSet::combine(bool skip_undo) // move to the position of the topmost, reduced by the number of deleted items parent->addChildAtPos(repr, position > 0 ? position : 0); - if ( !skip_undo ) { - DocumentUndo::done(doc, SP_VERB_SELECTION_COMBINE, - _("Combine")); + if (!skip_undo) { + DocumentUndo::done(doc, SP_VERB_SELECTION_COMBINE, _("Combine")); } set(repr); Inkscape::GC::release(repr); } else { - if(desktop()) - desktop()->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No path(s)</b> to combine in the selection.")); + if (desktop()) + desktop()->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, + _("<b>No path(s)</b> to combine in the selection.")); } - if(desktop()) + if (desktop()) desktop()->clearWaitingCursor(); } -void -ObjectSet::breakApart(bool skip_undo) +void ObjectSet::breakApart(bool skip_undo) { if (isEmpty()) { - if(desktop()) + if (desktop()) desktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to break apart.")); return; } - if(desktop()){ + if (desktop()) { desktop()->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Breaking apart paths...")); // set "busy" cursor desktop()->setWaitingCursor(); @@ -208,9 +196,8 @@ ObjectSet::breakApart(bool skip_undo) bool did = false; - std::vector<SPItem*> itemlist(items().begin(), items().end()); - for (auto item : itemlist){ - + std::vector<SPItem *> itemlist(items().begin(), items().end()); + for (auto item : itemlist) { SPPath *path = dynamic_cast<SPPath *>(item); if (!path) { continue; @@ -234,12 +221,10 @@ ObjectSet::breakApart(bool skip_undo) // it's going to resurrect as one of the pieces, so we delete without advertisement item->deleteObject(false); - auto list = curve->split(); - std::vector<Inkscape::XML::Node*> reprs; + std::vector<Inkscape::XML::Node *> reprs; for (auto const &curve : list) { - Inkscape::XML::Node *repr = parent->document()->createElement("svg:path"); repr->setAttribute("style", style); @@ -253,7 +238,7 @@ ObjectSet::breakApart(bool skip_undo) str = sp_svg_transform_write(transform); repr->setAttribute("transform", str); g_free(str); - + // add the new repr to the parent // move to the saved position parent->addChildAtPos(repr, pos); @@ -278,13 +263,13 @@ ObjectSet::breakApart(bool skip_undo) } if (did) { - if ( !skip_undo ) { - DocumentUndo::done(document(), SP_VERB_SELECTION_BREAK_APART, - _("Break apart")); + if (!skip_undo) { + DocumentUndo::done(document(), SP_VERB_SELECTION_BREAK_APART, _("Break apart")); } } else { - if(desktop()) - desktop()->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No path(s)</b> to break apart in the selection.")); + if (desktop()) + desktop()->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, + _("<b>No path(s)</b> to break apart in the selection.")); } } @@ -292,10 +277,11 @@ void ObjectSet::toCurves(bool skip_undo) { if (isEmpty()) { if (desktop()) - desktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to path.")); + desktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>object(s)</b> to convert to path.")); return; } - + bool did = false; if (desktop()) { desktop()->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Converting objects to paths...")); @@ -306,9 +292,9 @@ void ObjectSet::toCurves(bool skip_undo) if (prefs->getBool("/options/pathoperationsunlink/value", true)) { unlinkRecursive(true); } - std::vector<SPItem*> selected(items().begin(), items().end()); - std::vector<Inkscape::XML::Node*> to_select; - std::vector<SPItem*> items(selected); + std::vector<SPItem *> selected(items().begin(), items().end()); + std::vector<Inkscape::XML::Node *> to_select; + std::vector<SPItem *> items(selected); did = sp_item_list_to_curves(items, selected, to_select); @@ -320,12 +306,12 @@ void ObjectSet::toCurves(bool skip_undo) if (desktop()) { desktop()->clearWaitingCursor(); } - if (did&& !skip_undo) { - DocumentUndo::done(document(), SP_VERB_OBJECT_TO_CURVE, - _("Object to path")); + if (did && !skip_undo) { + DocumentUndo::done(document(), SP_VERB_OBJECT_TO_CURVE, _("Object to path")); } else { - if(desktop()) - desktop()->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No objects</b> to convert to path in the selection.")); + if (desktop()) + desktop()->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, + _("<b>No objects</b> to convert to path in the selection.")); return; } } @@ -333,7 +319,6 @@ void ObjectSet::toCurves(bool skip_undo) /** Converts the selected items to LPEItems if they are not already so; e.g. SPRects) */ void ObjectSet::toLPEItems() { - if (isEmpty()) { return; } @@ -341,11 +326,10 @@ void ObjectSet::toLPEItems() if (prefs->getBool("/options/pathoperationsunlink/value", true)) { unlinkRecursive(true); } - std::vector<SPItem*> selected(items().begin(), items().end()); - std::vector<Inkscape::XML::Node*> to_select; + std::vector<SPItem *> selected(items().begin(), items().end()); + std::vector<Inkscape::XML::Node *> to_select; clear(); - std::vector<SPItem*> items(selected); - + std::vector<SPItem *> items(selected); sp_item_list_to_curves(items, selected, to_select, true); @@ -353,19 +337,18 @@ void ObjectSet::toLPEItems() addList(selected); } -bool -sp_item_list_to_curves(const std::vector<SPItem*> &items, std::vector<SPItem*>& selected, std::vector<Inkscape::XML::Node*> &to_select, bool skip_all_lpeitems) +bool sp_item_list_to_curves(const std::vector<SPItem *> &items, std::vector<SPItem *> &selected, + std::vector<Inkscape::XML::Node *> &to_select, bool skip_all_lpeitems) { bool did = false; - for (auto item : items){ + for (auto item : items) { g_assert(item != nullptr); SPDocument *document = item->document; SPGroup *group = dynamic_cast<SPGroup *>(item); - if ( skip_all_lpeitems && - dynamic_cast<SPLPEItem *>(item) && - !group ) // also convert objects in an SPGroup when skip_all_lpeitems is set. - { + if (skip_all_lpeitems && dynamic_cast<SPLPEItem *>(item) && !group) // also convert objects in an SPGroup when + // skip_all_lpeitems is set. + { continue; } @@ -373,9 +356,9 @@ sp_item_list_to_curves(const std::vector<SPItem*> &items, std::vector<SPItem*>& if (box) { // convert 3D box to ordinary group of paths; replace the old element in 'selected' with the new group Inkscape::XML::Node *repr = box->convert_to_group()->getRepr(); - + if (repr) { - to_select.insert(to_select.begin(),repr); + to_select.insert(to_select.begin(), repr); did = true; selected.erase(remove(selected.begin(), selected.end(), item), selected.end()); } @@ -384,7 +367,7 @@ sp_item_list_to_curves(const std::vector<SPItem*> &items, std::vector<SPItem*>& } // remember id char const *id = item->getRepr()->attribute("id"); - + SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(item); if (lpeitem) { lpeitem->removeAllPathEffects(true); @@ -392,14 +375,14 @@ sp_item_list_to_curves(const std::vector<SPItem*> &items, std::vector<SPItem*>& if (elemref != item) { selected.erase(remove(selected.begin(), selected.end(), item), selected.end()); if (elemref) { - //If the LPE item is a shape is converted to a path so we need to reupdate the item + // If the LPE item is a shape is converted to a path so we need to reupdate the item item = dynamic_cast<SPItem *>(elemref); selected.push_back(item); did = true; } } } - + SPPath *path = dynamic_cast<SPPath *>(item); if (path) { // remove connector attributes @@ -416,15 +399,14 @@ sp_item_list_to_curves(const std::vector<SPItem*> &items, std::vector<SPItem*>& } if (group) { - std::vector<SPItem*> item_list = sp_item_group_item_list(group); - - std::vector<Inkscape::XML::Node*> item_to_select; - std::vector<SPItem*> item_selected; - + std::vector<SPItem *> item_list = sp_item_group_item_list(group); + + std::vector<Inkscape::XML::Node *> item_to_select; + std::vector<SPItem *> item_selected; + if (sp_item_list_to_curves(item_list, item_selected, item_to_select)) did = true; - continue; } @@ -454,15 +436,14 @@ sp_item_list_to_curves(const std::vector<SPItem*> &items, std::vector<SPItem*>& /* Buglet: We don't re-add the (new version of the) object to the selection of any other * desktops where it was previously selected. */ - to_select.insert(to_select.begin(),repr); + to_select.insert(to_select.begin(), repr); Inkscape::GC::release(repr); } - + return did; } -Inkscape::XML::Node * -sp_selected_item_to_curved_repr(SPItem *item, guint32 /*text_grouping_policy*/) +Inkscape::XML::Node *sp_selected_item_to_curved_repr(SPItem *item, guint32 /*text_grouping_policy*/) { if (!item) return nullptr; @@ -474,11 +455,10 @@ sp_selected_item_to_curved_repr(SPItem *item, guint32 /*text_grouping_policy*/) Inkscape::XML::Node *g_repr = xml_doc->createElement("svg:g"); // Save original text for accessibility. - Glib::ustring original_text = sp_te_get_string_multiline( item, - te_get_layout(item)->begin(), - te_get_layout(item)->end() ); - if( original_text.size() > 0 ) { - g_repr->setAttributeOrRemoveIfEmpty("aria-label", original_text ); + Glib::ustring original_text = + sp_te_get_string_multiline(item, te_get_layout(item)->begin(), te_get_layout(item)->end()); + if (original_text.size() > 0) { + g_repr->setAttributeOrRemoveIfEmpty("aria-label", original_text); } g_repr->setAttribute("transform", item->getRepr()->attribute("transform")); @@ -487,7 +467,8 @@ sp_selected_item_to_curved_repr(SPItem *item, guint32 /*text_grouping_policy*/) /* Whole text's style */ Glib::ustring style_str = - item->style->write( SP_STYLE_FLAG_IFDIFF, SP_STYLE_SRC_UNSET, item->parent ? item->parent->style : nullptr); // TODO investigate possibility + item->style->write(SP_STYLE_FLAG_IFDIFF, SP_STYLE_SRC_UNSET, + item->parent ? item->parent->style : nullptr); // TODO investigate possibility g_repr->setAttributeOrRemoveIfEmpty("style", style_str); Inkscape::Text::Layout::iterator iter = te_get_layout(item)->begin(); @@ -503,15 +484,16 @@ sp_selected_item_to_curved_repr(SPItem *item, guint32 /*text_grouping_policy*/) if (!pos_obj) // no source for glyph, abort break; while (dynamic_cast<SPString const *>(pos_obj) && pos_obj->parent) { - pos_obj = pos_obj->parent; // SPStrings don't have style + pos_obj = pos_obj->parent; // SPStrings don't have style } - Glib::ustring style_str = - pos_obj->style->write( SP_STYLE_FLAG_IFDIFF, SP_STYLE_SRC_UNSET, pos_obj->parent ? pos_obj->parent->style : nullptr); // TODO investigate possibility + Glib::ustring style_str = pos_obj->style->write(SP_STYLE_FLAG_IFDIFF, SP_STYLE_SRC_UNSET, + pos_obj->parent ? pos_obj->parent->style + : nullptr); // TODO investigate possibility // get path from iter to iter_next: auto curve = te_get_layout(item)->convertToCurves(iter, iter_next); iter = iter_next; // shift to next glyph - if (!curve) { // error converting this glyph + if (!curve) { // error converting this glyph continue; } if (curve->is_empty()) { // whitespace glyph? @@ -552,8 +534,7 @@ sp_selected_item_to_curved_repr(SPItem *item, guint32 /*text_grouping_policy*/) // Prevent empty paths from being added to the document // otherwise we end up with zomby markup in the SVG file - if(curve->is_empty()) - { + if (curve->is_empty()) { return nullptr; } @@ -566,7 +547,8 @@ sp_selected_item_to_curved_repr(SPItem *item, guint32 /*text_grouping_policy*/) /* Style */ Glib::ustring style_str = - item->style->write( SP_STYLE_FLAG_IFDIFF, SP_STYLE_SRC_UNSET, item->parent ? item->parent->style : nullptr); // TODO investigate possibility + item->style->write(SP_STYLE_FLAG_IFDIFF, SP_STYLE_SRC_UNSET, + item->parent ? item->parent->style : nullptr); // TODO investigate possibility repr->setAttributeOrRemoveIfEmpty("style", style_str); /* Definition */ @@ -576,27 +558,23 @@ sp_selected_item_to_curved_repr(SPItem *item, guint32 /*text_grouping_policy*/) return repr; } - -void -ObjectSet::pathReverse() +void ObjectSet::pathReverse() { if (isEmpty()) { - if(desktop()) + if (desktop()) desktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to reverse.")); return; } - // set "busy" cursor - if(desktop()){ + if (desktop()) { desktop()->setWaitingCursor(); desktop()->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Reversing paths...")); } - - bool did = false; - for (auto i = items().begin(); i != items().end(); ++i){ + bool did = false; + for (auto i = items().begin(); i != items().end(); ++i) { SPPath *path = dynamic_cast<SPPath *>(*i); if (!path) { continue; @@ -607,7 +585,7 @@ ObjectSet::pathReverse() auto rcurve = path->curveForEdit()->create_reverse(); gchar *str = sp_svg_write_path(rcurve->get_pathvector()); - if ( path->hasPathEffectRecursive() ) { + if (path->hasPathEffectRecursive()) { path->setAttribute("inkscape:original-d", str); } else { path->setAttribute("d", str); @@ -616,24 +594,23 @@ ObjectSet::pathReverse() // reverse nodetypes order (Bug #179866) gchar *nodetypes = g_strdup(path->getRepr()->attribute("sodipodi:nodetypes")); - if ( nodetypes ) { + if (nodetypes) { path->setAttribute("sodipodi:nodetypes", g_strreverse(nodetypes)); g_free(nodetypes); } } - if(desktop()) + if (desktop()) desktop()->clearWaitingCursor(); if (did) { - DocumentUndo::done(document(), SP_VERB_SELECTION_REVERSE, - _("Reverse path")); + DocumentUndo::done(document(), SP_VERB_SELECTION_REVERSE, _("Reverse path")); } else { - if(desktop()) - desktop()->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to reverse in the selection.")); + if (desktop()) + desktop()->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, + _("<b>No paths</b> to reverse in the selection.")); } } - /** * Copy generic attributes, like those from the "Object Properties" dialog, * but also style and transformation center. @@ -682,7 +659,6 @@ static void ink_copy_generic_attributes( // } } - /** * Copy generic child elements, like those from the "Object Properties" dialog * (title and description) but also XML comments. @@ -715,7 +691,6 @@ static void ink_copy_generic_children( // } } - /** * Copy generic object properties, like: * - id @@ -740,7 +715,6 @@ void Inkscape::copy_object_properties( // ink_copy_generic_children(dest, src); } - /* Local Variables: mode:c++ diff --git a/src/path-chemistry.h b/src/path-chemistry.h index 304ca1ba9ff9f3681a58d223eb416f9917e35465..c70d56bdebb7a6ec7703d29ae8480ca3634cc9a9 100644 --- a/src/path-chemistry.h +++ b/src/path-chemistry.h @@ -31,14 +31,15 @@ void copy_object_properties(XML::Node *dest, XML::Node const *src); typedef unsigned int guint32; -//void sp_selected_path_combine (SPDesktop *desktop, bool skip_undo = false); -//void sp_selected_path_break_apart (SPDesktop *desktop, bool skip_undo = false); - //interactive=true only has an effect if desktop != NULL, i.e. if a GUI is available -//void sp_selected_path_to_curves (Inkscape::Selection *selection, SPDesktop *desktop, bool interactive = true); -//void sp_selected_to_lpeitems(ObjectSet *selection); +// void sp_selected_path_combine (SPDesktop *desktop, bool skip_undo = false); +// void sp_selected_path_break_apart (SPDesktop *desktop, bool skip_undo = false); +// interactive=true only has an effect if desktop != NULL, i.e. if a GUI is available +// void sp_selected_path_to_curves (Inkscape::Selection *selection, SPDesktop *desktop, bool interactive = true); +// void sp_selected_to_lpeitems(ObjectSet *selection); Inkscape::XML::Node *sp_selected_item_to_curved_repr(SPItem *item, guint32 text_grouping_policy); -//void sp_selected_path_reverse (SPDesktop *desktop); -bool sp_item_list_to_curves(const std::vector<SPItem*> &items, std::vector<SPItem*> &selected, std::vector<Inkscape::XML::Node*> &to_select, bool skip_all_lpeitems = false); +// void sp_selected_path_reverse (SPDesktop *desktop); +bool sp_item_list_to_curves(const std::vector<SPItem *> &items, std::vector<SPItem *> &selected, + std::vector<Inkscape::XML::Node *> &to_select, bool skip_all_lpeitems = false); #endif // SEEN_PATH_CHEMISTRY_H diff --git a/src/path-prefix.cpp b/src/path-prefix.cpp index e81e129c10e8b206807cbd48835ad3ae7de70a2b..0e737bab4e385e7a58739243d5ab54fd901b81ae 100644 --- a/src/path-prefix.cpp +++ b/src/path-prefix.cpp @@ -9,7 +9,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #ifdef _WIN32 @@ -79,7 +79,7 @@ char const *get_inkscape_datadir() inkscape_datadir = datadir.c_str(); -#if GLIB_CHECK_VERSION(2,58,0) +#if GLIB_CHECK_VERSION(2, 58, 0) inkscape_datadir = g_canonicalize_filename(inkscape_datadir, nullptr); #endif } diff --git a/src/path/path-boolop.cpp b/src/path/path-boolop.cpp index b6393a77b17246dd4153ebaac99453803bb8f5da..23a3838e26a12bf6b4564ab16ad43a6f3228022a 100644 --- a/src/path/path-boolop.cpp +++ b/src/path/path-boolop.cpp @@ -11,39 +11,30 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <vector> - -#include <glibmm/i18n.h> - -#include <2geom/svg-path-parser.h> // to get from SVG on boolean to Geom::Path - #include "path-boolop.h" -#include "path-util.h" - -#include "message-stack.h" -#include "path-chemistry.h" // copy_object_properties() -#include "verbs.h" -#include "helper/geom.h" // pathv_to_linear_and_cubic_beziers() +#include <2geom/svg-path-parser.h> // to get from SVG on boolean to Geom::Path +#include <glibmm/i18n.h> +#include <vector> +#include "helper/geom.h" // pathv_to_linear_and_cubic_beziers() #include "livarot/Path.h" #include "livarot/Shape.h" - +#include "message-stack.h" #include "object/sp-flowtext.h" #include "object/sp-shape.h" #include "object/sp-text.h" - -#include "ui/widget/canvas.h" // Disable drawing during op - +#include "path-chemistry.h" // copy_object_properties() +#include "path-util.h" #include "svg/svg.h" - +#include "ui/widget/canvas.h" // Disable drawing during op +#include "verbs.h" #include "xml/repr-sorting.h" using Inkscape::DocumentUndo; // fonctions utilitaires -bool -Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who) +bool Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who) { if (who == nullptr || a == nullptr) return false; @@ -52,42 +43,37 @@ Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who) return Ancetre(a->parent(), who); } - -bool Inkscape::ObjectSet::pathUnion(const bool skip_undo) { +bool Inkscape::ObjectSet::pathUnion(const bool skip_undo) +{ BoolOpErrors result = pathBoolOp(bool_op_union, skip_undo, false, SP_VERB_SELECTION_UNION, _("Union")); return DONE == result; } -bool -Inkscape::ObjectSet::pathIntersect(const bool skip_undo) +bool Inkscape::ObjectSet::pathIntersect(const bool skip_undo) { BoolOpErrors result = pathBoolOp(bool_op_inters, skip_undo, false, SP_VERB_SELECTION_INTERSECT, _("Intersection")); return DONE == result; } -bool -Inkscape::ObjectSet::pathDiff(const bool skip_undo) +bool Inkscape::ObjectSet::pathDiff(const bool skip_undo) { BoolOpErrors result = pathBoolOp(bool_op_diff, skip_undo, false, SP_VERB_SELECTION_DIFF, _("Difference")); return DONE == result; } -bool -Inkscape::ObjectSet::pathSymDiff(const bool skip_undo) +bool Inkscape::ObjectSet::pathSymDiff(const bool skip_undo) { BoolOpErrors result = pathBoolOp(bool_op_symdiff, skip_undo, false, SP_VERB_SELECTION_SYMDIFF, _("Exclusion")); return DONE == result; } -bool -Inkscape::ObjectSet::pathCut(const bool skip_undo) +bool Inkscape::ObjectSet::pathCut(const bool skip_undo) { BoolOpErrors result = pathBoolOp(bool_op_cut, skip_undo, false, SP_VERB_SELECTION_CUT, _("Division")); return DONE == result; } -bool -Inkscape::ObjectSet::pathSlice(const bool skip_undo) +bool Inkscape::ObjectSet::pathSlice(const bool skip_undo) { BoolOpErrors result = pathBoolOp(bool_op_slice, skip_undo, false, SP_VERB_SELECTION_SLICE, _("Cut path")); return DONE == result; @@ -95,8 +81,7 @@ Inkscape::ObjectSet::pathSlice(const bool skip_undo) // helper for printing error messages, regardless of whether we have a GUI or not // If desktop == NULL, errors will be shown on stderr -static void -boolop_display_error_message(SPDesktop *desktop, Glib::ustring const &msg) +static void boolop_display_error_message(SPDesktop *desktop, Glib::ustring const &msg) { if (desktop) { desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, msg); @@ -109,21 +94,21 @@ boolop_display_error_message(SPDesktop *desktop, Glib::ustring const &msg) // This is derived from sp_selected_path_boolop // take the source paths from the file, do the operation, delete the originals and add the results // fra,fra are fill_rules for PathVectors a,b -Geom::PathVector -sp_pathvector_boolop(Geom::PathVector const &pathva, Geom::PathVector const &pathvb, bool_op bop, fill_typ fra, fill_typ frb) -{ - +Geom::PathVector sp_pathvector_boolop(Geom::PathVector const &pathva, Geom::PathVector const &pathvb, bool_op bop, + fill_typ fra, fill_typ frb) +{ // extract the livarot Paths from the source objects // also get the winding rule specified in the style int nbOriginaux = 2; std::vector<Path *> originaux(nbOriginaux); std::vector<FillRule> origWind(nbOriginaux); - origWind[0]=fra; - origWind[1]=frb; + origWind[0] = fra; + origWind[1] = frb; Geom::PathVector patht; - // Livarot's outline of arcs is broken. So convert the path to linear and cubics only, for which the outline is created correctly. - originaux[0] = Path_for_pathvector(pathv_to_linear_and_cubic_beziers( pathva)); - originaux[1] = Path_for_pathvector(pathv_to_linear_and_cubic_beziers( pathvb)); + // Livarot's outline of arcs is broken. So convert the path to linear and cubics only, for which the outline is + // created correctly. + originaux[0] = Path_for_pathvector(pathv_to_linear_and_cubic_beziers(pathva)); + originaux[1] = Path_for_pathvector(pathv_to_linear_and_cubic_beziers(pathvb)); // some temporary instances, first Shape *theShapeA = new Shape; @@ -131,10 +116,10 @@ sp_pathvector_boolop(Geom::PathVector const &pathva, Geom::PathVector const &pat Shape *theShape = new Shape; Path *res = new Path; res->SetBackData(false); - Path::cut_position *toCut=nullptr; - int nbToCut=0; + Path::cut_position *toCut = nullptr; + int nbToCut = 0; - if ( bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff ) { + if (bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff) { // true boolean op // get the polygons of each path, with the winding rule specified, and apply the operation iteratively originaux[0]->ConvertWithBackData(0.1); @@ -148,10 +133,10 @@ sp_pathvector_boolop(Geom::PathVector const &pathva, Geom::PathVector const &pat originaux[1]->Fill(theShape, 1); theShapeB->ConvertToShape(theShape, origWind[1]); - + theShape->Booleen(theShapeB, theShapeA, bop); - } else if ( bop == bool_op_cut ) { + } else if (bop == bool_op_cut) { // cuts= sort of a bastard boolean operation, thus not the axact same modus operandi // technically, the cut path is not necessarily a polygon (thus has no winding rule) // it is just uncrossed, and cleaned from duplicate edges and points @@ -169,8 +154,12 @@ sp_pathvector_boolop(Geom::PathVector const &pathva, Geom::PathVector const &pat // left it at 1.0. Investigate replacing this by a combination of difference and // intersection of the same two paths. -- bb { - Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap; - int swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai; + Path *swap = originaux[0]; + originaux[0] = originaux[1]; + originaux[1] = swap; + int swai = origWind[0]; + origWind[0] = origWind[1]; + origWind[1] = (fill_typ)swai; } originaux[0]->ConvertWithBackData(0.1); @@ -180,14 +169,14 @@ sp_pathvector_boolop(Geom::PathVector const &pathva, Geom::PathVector const &pat originaux[1]->ConvertWithBackData(0.1); - originaux[1]->Fill(theShape, 1,false,false,false); //do not closeIfNeeded + originaux[1]->Fill(theShape, 1, false, false, false); // do not closeIfNeeded theShapeB->ConvertToShape(theShape, fill_justDont); // fill_justDont doesn't computes winding numbers // les elements arrivent en ordre inverse dans la liste theShape->Booleen(theShapeB, theShapeA, bool_op_cut, 1); - } else if ( bop == bool_op_slice ) { + } else if (bop == bool_op_slice) { // slice is not really a boolean operation // you just put the 2 shapes in a single polygon, uncross it // the points where the degree is > 2 are intersections @@ -196,53 +185,59 @@ sp_pathvector_boolop(Geom::PathVector const &pathva, Geom::PathVector const &pat // make new subpath at each one of these positions // inversion pour l'opÂŽration { - Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap; - int swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai; + Path *swap = originaux[0]; + originaux[0] = originaux[1]; + originaux[1] = swap; + int swai = origWind[0]; + origWind[0] = origWind[1]; + origWind[1] = (fill_typ)swai; } originaux[0]->ConvertWithBackData(1.0); - originaux[0]->Fill(theShapeA, 0,false,false,false); // don't closeIfNeeded + originaux[0]->Fill(theShapeA, 0, false, false, false); // don't closeIfNeeded originaux[1]->ConvertWithBackData(1.0); - originaux[1]->Fill(theShapeA, 1,true,false,false);// don't closeIfNeeded and just dump in the shape, don't reset it + originaux[1]->Fill(theShapeA, 1, true, false, + false); // don't closeIfNeeded and just dump in the shape, don't reset it theShape->ConvertToShape(theShapeA, fill_justDont); - if ( theShape->hasBackData() ) { + if (theShape->hasBackData()) { // should always be the case, but ya never know { for (int i = 0; i < theShape->numberOfPoints(); i++) { - if ( theShape->getPoint(i).totalDegree() > 2 ) { + if (theShape->getPoint(i).totalDegree() > 2) { // possibly an intersection // we need to check that at least one edge from the source path is incident to it // before we declare it's an intersection int cb = theShape->getPoint(i).incidentEdge[FIRST]; - int nbOrig=0; - int nbOther=0; - int piece=-1; - float t=0.0; - while ( cb >= 0 && cb < theShape->numberOfEdges() ) { - if ( theShape->ebData[cb].pathID == 0 ) { + int nbOrig = 0; + int nbOther = 0; + int piece = -1; + float t = 0.0; + while (cb >= 0 && cb < theShape->numberOfEdges()) { + if (theShape->ebData[cb].pathID == 0) { // the source has an edge incident to the point, get its position on the path - piece=theShape->ebData[cb].pieceID; - if ( theShape->getEdge(cb).st == i ) { - t=theShape->ebData[cb].tSt; + piece = theShape->ebData[cb].pieceID; + if (theShape->getEdge(cb).st == i) { + t = theShape->ebData[cb].tSt; } else { - t=theShape->ebData[cb].tEn; + t = theShape->ebData[cb].tEn; } nbOrig++; } - if ( theShape->ebData[cb].pathID == 1 ) nbOther++; // the cut is incident to this point - cb=theShape->NextAt(i, cb); + if (theShape->ebData[cb].pathID == 1) + nbOther++; // the cut is incident to this point + cb = theShape->NextAt(i, cb); } - if ( nbOrig > 0 && nbOther > 0 ) { + if (nbOrig > 0 && nbOther > 0) { // point incident to both path and cut: an intersection // note that you only keep one position on the source; you could have degenerate // cases where the source crosses itself at this point, and you wouyld miss an intersection - toCut=(Path::cut_position*)realloc(toCut, (nbToCut+1)*sizeof(Path::cut_position)); - toCut[nbToCut].piece=piece; - toCut[nbToCut].t=t; + toCut = (Path::cut_position *)realloc(toCut, (nbToCut + 1) * sizeof(Path::cut_position)); + toCut[nbToCut].piece = piece; + toCut[nbToCut].t = t; nbToCut++; } } @@ -251,27 +246,26 @@ sp_pathvector_boolop(Geom::PathVector const &pathva, Geom::PathVector const &pat { // i think it's useless now int i = theShape->numberOfEdges() - 1; - for (;i>=0;i--) { - if ( theShape->ebData[i].pathID == 1 ) { + for (; i >= 0; i--) { + if (theShape->ebData[i].pathID == 1) { theShape->SubEdge(i); } } } - } } - int* nesting=nullptr; - int* conts=nullptr; - int nbNest=0; + int *nesting = nullptr; + int *conts = nullptr; + int nbNest = 0; // pour compenser le swap juste avant - if ( bop == bool_op_slice ) { -// theShape->ConvertToForme(res, nbOriginaux, originaux, true); -// res->ConvertForcedToMoveTo(); + if (bop == bool_op_slice) { + // theShape->ConvertToForme(res, nbOriginaux, originaux, true); + // res->ConvertForcedToMoveTo(); res->Copy(originaux[0]); res->ConvertPositionsToMoveTo(nbToCut, toCut); // cut where you found intersections free(toCut); - } else if ( bop == bool_op_cut ) { + } else if (bop == bool_op_cut) { // il faut appeler pour desallouer PointData (pas vital, mais bon) // the Booleen() function did not deallocate the point_data array in theShape, because this // function needs it. @@ -289,17 +283,17 @@ sp_pathvector_boolop(Geom::PathVector const &pathva, Geom::PathVector const &pat delete originaux[1]; gchar *result_str = res->svg_dump_path(); - Geom::PathVector outres = Geom::parse_svg_path(result_str); + Geom::PathVector outres = Geom::parse_svg_path(result_str); g_free(result_str); delete res; return outres; } - // boolean operations on the desktop // take the source paths from the file, do the operation, delete the originals and add the results -BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, const bool checked, const unsigned int verb, const Glib::ustring description) +BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, const bool checked, + const unsigned int verb, const Glib::ustring description) { if (nullptr != desktop() && !checked) { SPDocument *doc = desktop()->getDocument(); @@ -308,44 +302,46 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, BoolOpErrors returnCode = ObjectSet::pathBoolOp(bop, true, true); desktop()->getCanvas()->set_drawing_disabled(false); - switch(returnCode) { - case ERR_TOO_LESS_PATHS_1: - boolop_display_error_message(desktop(), _("Select <b>at least 1 path</b> to perform a boolean union.")); - break; - case ERR_TOO_LESS_PATHS_2: - boolop_display_error_message(desktop(), _("Select <b>at least 2 paths</b> to perform a boolean operation.")); - break; - case ERR_NO_PATHS: - boolop_display_error_message(desktop(), _("One of the objects is <b>not a path</b>, cannot perform boolean operation.")); - break; - case ERR_Z_ORDER: - boolop_display_error_message(desktop(), _("Unable to determine the <b>z-order</b> of the objects selected for difference, XOR, division, or path cut.")); - break; - case DONE_NO_PATH: - if (!skip_undo) { - DocumentUndo::done(doc, SP_VERB_NONE, description); - } - break; - case DONE: - if (!skip_undo) { - DocumentUndo::done(doc, verb, description); - } - break; - case DONE_NO_ACTION: - // Do nothing (?) - break; + switch (returnCode) { + case ERR_TOO_LESS_PATHS_1: + boolop_display_error_message(desktop(), _("Select <b>at least 1 path</b> to perform a boolean union.")); + break; + case ERR_TOO_LESS_PATHS_2: + boolop_display_error_message(desktop(), + _("Select <b>at least 2 paths</b> to perform a boolean operation.")); + break; + case ERR_NO_PATHS: + boolop_display_error_message( + desktop(), _("One of the objects is <b>not a path</b>, cannot perform boolean operation.")); + break; + case ERR_Z_ORDER: + boolop_display_error_message(desktop(), _("Unable to determine the <b>z-order</b> of the objects " + "selected for difference, XOR, division, or path cut.")); + break; + case DONE_NO_PATH: + if (!skip_undo) { + DocumentUndo::done(doc, SP_VERB_NONE, description); + } + break; + case DONE: + if (!skip_undo) { + DocumentUndo::done(doc, verb, description); + } + break; + case DONE_NO_ACTION: + // Do nothing (?) + break; } return returnCode; } SPDocument *doc = document(); - std::vector<SPItem*> il(items().begin(), items().end()); + std::vector<SPItem *> il(items().begin(), items().end()); // allow union on a single object for the purpose of removing self overlapse (svn log, revision 13334) if (il.size() < 2 && bop != bool_op_union) { return ERR_TOO_LESS_PATHS_2; - } - else if (il.size() < 1) { + } else if (il.size() < 1) { return ERR_TOO_LESS_PATHS_1; } @@ -371,7 +367,6 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, // reverse order reverseOrderForOp = true; } else { - // objects are not in parent/child relationship; // find their lowest common ancestor Inkscape::XML::Node *parent = LCA(a, b); @@ -400,10 +395,8 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, // first check if all the input objects have shapes // otherwise bail out - for (auto item : il) - { - if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item) && !SP_IS_FLOWTEXT(item)) - { + for (auto item : il) { + if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item) && !SP_IS_FLOWTEXT(item)) { return ERR_NO_PATHS; } } @@ -416,8 +409,7 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, int curOrig; { curOrig = 0; - for (std::vector<SPItem*>::const_iterator l = il.begin(); l != il.end(); l++) - { + for (std::vector<SPItem *>::const_iterator l = il.begin(); l != il.end(); l++) { // apply live path effects prior to performing boolean operation if (SP_IS_LPE_ITEM(*l)) { SP_LPE_ITEM(*l)->removeAllPathEffects(true); @@ -426,17 +418,17 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, SPCSSAttr *css = sp_repr_css_attr(reinterpret_cast<SPObject *>(il[0])->getRepr(), "style"); gchar const *val = sp_repr_css_property(css, "fill-rule", nullptr); if (val && strcmp(val, "nonzero") == 0) { - origWind[curOrig]= fill_nonZero; + origWind[curOrig] = fill_nonZero; } else if (val && strcmp(val, "evenodd") == 0) { - origWind[curOrig]= fill_oddEven; + origWind[curOrig] = fill_oddEven; } else { - origWind[curOrig]= fill_nonZero; + origWind[curOrig] = fill_nonZero; } originaux[curOrig] = Path_for_item(*l, true, true); - if (originaux[curOrig] == nullptr || originaux[curOrig]->descr_cmd.size() <= 1) - { - for (int i = curOrig; i >= 0; i--) delete originaux[i]; + if (originaux[curOrig] == nullptr || originaux[curOrig]->descr_cmd.size() <= 1) { + for (int i = curOrig; i >= 0; i--) + delete originaux[i]; return DONE_NO_ACTION; } curOrig++; @@ -444,7 +436,7 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, } // reverse if needed // note that the selection list keeps its order - if ( reverseOrderForOp ) { + if (reverseOrderForOp) { std::swap(originaux[0], originaux[1]); std::swap(origWind[0], origWind[1]); } @@ -456,10 +448,10 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, Shape *theShape = new Shape; Path *res = new Path; res->SetBackData(false); - Path::cut_position *toCut=nullptr; - int nbToCut=0; + Path::cut_position *toCut = nullptr; + int nbToCut = 0; - if ( bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff ) { + if (bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff) { // true boolean op // get the polygons of each path, with the winding rule specified, and apply the operation iteratively originaux[0]->ConvertWithBackData(0.1); @@ -469,8 +461,9 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, theShapeA->ConvertToShape(theShape, origWind[0]); curOrig = 1; - for (std::vector<SPItem*>::const_iterator l = il.begin(); l != il.end(); l++){ - if(*l==il[0])continue; + for (std::vector<SPItem *>::const_iterator l = il.begin(); l != il.end(); l++) { + if (*l == il[0]) + continue; originaux[curOrig]->ConvertWithBackData(0.1); originaux[curOrig]->Fill(theShape, curOrig); @@ -498,9 +491,8 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, bool zeroB = theShapeB->numberOfEdges() == 0; if (zeroA || zeroB) { // We might need to do a swap. Apply the above rules depending on operation type. - bool resultIsB = ((bop == bool_op_union || bop == bool_op_symdiff) && zeroA) - || ((bop == bool_op_inters) && zeroB) - || (bop == bool_op_diff); + bool resultIsB = ((bop == bool_op_union || bop == bool_op_symdiff) && zeroA) || + ((bop == bool_op_inters) && zeroB) || (bop == bool_op_diff); if (resultIsB) { // Swap A and B to use B as the result Shape *swap = theShapeB; @@ -524,7 +516,7 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, theShapeA = swap; } - } else if ( bop == bool_op_cut ) { + } else if (bop == bool_op_cut) { // cuts= sort of a bastard boolean operation, thus not the axact same modus operandi // technically, the cut path is not necessarily a polygon (thus has no winding rule) // it is just uncrossed, and cleaned from duplicate edges and points @@ -542,8 +534,12 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, // left it at 1.0. Investigate replacing this by a combination of difference and // intersection of the same two paths. -- bb { - Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap; - int swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai; + Path *swap = originaux[0]; + originaux[0] = originaux[1]; + originaux[1] = swap; + int swai = origWind[0]; + origWind[0] = origWind[1]; + origWind[1] = (fill_typ)swai; } originaux[0]->ConvertWithBackData(1.0); @@ -554,16 +550,16 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, originaux[1]->ConvertWithBackData(1.0); if ((originaux[1]->pts.size() == 2) && originaux[1]->pts[0].isMoveTo && !originaux[1]->pts[1].isMoveTo) - originaux[1]->Fill(theShape, 1,false,true,false); // see LP Bug 177956 + originaux[1]->Fill(theShape, 1, false, true, false); // see LP Bug 177956 else - originaux[1]->Fill(theShape, 1,false,false,false); //do not closeIfNeeded + originaux[1]->Fill(theShape, 1, false, false, false); // do not closeIfNeeded theShapeB->ConvertToShape(theShape, fill_justDont); // fill_justDont doesn't computes winding numbers // les elements arrivent en ordre inverse dans la liste theShape->Booleen(theShapeB, theShapeA, bool_op_cut, 1); - } else if ( bop == bool_op_slice ) { + } else if (bop == bool_op_slice) { // slice is not really a boolean operation // you just put the 2 shapes in a single polygon, uncross it // the points where the degree is > 2 are intersections @@ -572,53 +568,59 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, // make new subpath at each one of these positions // inversion pour l'opÂŽration { - Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap; - int swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai; + Path *swap = originaux[0]; + originaux[0] = originaux[1]; + originaux[1] = swap; + int swai = origWind[0]; + origWind[0] = origWind[1]; + origWind[1] = (fill_typ)swai; } originaux[0]->ConvertWithBackData(1.0); - originaux[0]->Fill(theShapeA, 0,false,false,false); // don't closeIfNeeded + originaux[0]->Fill(theShapeA, 0, false, false, false); // don't closeIfNeeded originaux[1]->ConvertWithBackData(1.0); - originaux[1]->Fill(theShapeA, 1,true,false,false);// don't closeIfNeeded and just dump in the shape, don't reset it + originaux[1]->Fill(theShapeA, 1, true, false, + false); // don't closeIfNeeded and just dump in the shape, don't reset it theShape->ConvertToShape(theShapeA, fill_justDont); - if ( theShape->hasBackData() ) { + if (theShape->hasBackData()) { // should always be the case, but ya never know { for (int i = 0; i < theShape->numberOfPoints(); i++) { - if ( theShape->getPoint(i).totalDegree() > 2 ) { + if (theShape->getPoint(i).totalDegree() > 2) { // possibly an intersection // we need to check that at least one edge from the source path is incident to it // before we declare it's an intersection int cb = theShape->getPoint(i).incidentEdge[FIRST]; - int nbOrig=0; - int nbOther=0; - int piece=-1; - float t=0.0; - while ( cb >= 0 && cb < theShape->numberOfEdges() ) { - if ( theShape->ebData[cb].pathID == 0 ) { + int nbOrig = 0; + int nbOther = 0; + int piece = -1; + float t = 0.0; + while (cb >= 0 && cb < theShape->numberOfEdges()) { + if (theShape->ebData[cb].pathID == 0) { // the source has an edge incident to the point, get its position on the path - piece=theShape->ebData[cb].pieceID; - if ( theShape->getEdge(cb).st == i ) { - t=theShape->ebData[cb].tSt; + piece = theShape->ebData[cb].pieceID; + if (theShape->getEdge(cb).st == i) { + t = theShape->ebData[cb].tSt; } else { - t=theShape->ebData[cb].tEn; + t = theShape->ebData[cb].tEn; } nbOrig++; } - if ( theShape->ebData[cb].pathID == 1 ) nbOther++; // the cut is incident to this point - cb=theShape->NextAt(i, cb); + if (theShape->ebData[cb].pathID == 1) + nbOther++; // the cut is incident to this point + cb = theShape->NextAt(i, cb); } - if ( nbOrig > 0 && nbOther > 0 ) { + if (nbOrig > 0 && nbOther > 0) { // point incident to both path and cut: an intersection // note that you only keep one position on the source; you could have degenerate // cases where the source crosses itself at this point, and you wouyld miss an intersection - toCut=(Path::cut_position*)realloc(toCut, (nbToCut+1)*sizeof(Path::cut_position)); - toCut[nbToCut].piece=piece; - toCut[nbToCut].t=t; + toCut = (Path::cut_position *)realloc(toCut, (nbToCut + 1) * sizeof(Path::cut_position)); + toCut[nbToCut].piece = piece; + toCut[nbToCut].t = t; nbToCut++; } } @@ -627,27 +629,26 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, { // i think it's useless now int i = theShape->numberOfEdges() - 1; - for (;i>=0;i--) { - if ( theShape->ebData[i].pathID == 1 ) { + for (; i >= 0; i--) { + if (theShape->ebData[i].pathID == 1) { theShape->SubEdge(i); } } } - } } - int* nesting=nullptr; - int* conts=nullptr; - int nbNest=0; + int *nesting = nullptr; + int *conts = nullptr; + int nbNest = 0; // pour compenser le swap juste avant - if ( bop == bool_op_slice ) { -// theShape->ConvertToForme(res, nbOriginaux, originaux, true); -// res->ConvertForcedToMoveTo(); + if (bop == bool_op_slice) { + // theShape->ConvertToForme(res, nbOriginaux, originaux, true); + // res->ConvertForcedToMoveTo(); res->Copy(originaux[0]); res->ConvertPositionsToMoveTo(nbToCut, toCut); // cut where you found intersections free(toCut); - } else if ( bop == bool_op_cut ) { + } else if (bop == bool_op_cut) { // il faut appeler pour desallouer PointData (pas vital, mais bon) // the Booleen() function did not deallocate the point_data array in theShape, because this // function needs it. @@ -661,12 +662,12 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, delete theShape; delete theShapeA; delete theShapeB; - for (int i = 0; i < nbOriginaux; i++) delete originaux[i]; + for (int i = 0; i < nbOriginaux; i++) + delete originaux[i]; - if (res->descr_cmd.size() <= 1) - { + if (res->descr_cmd.size() <= 1) { // only one command, presumably a moveto: it isn't a path - for (auto l : il){ + for (auto l : il) { l->deleteObject(); } clear(); @@ -677,7 +678,7 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, // get the source path object SPObject *source; - if ( bop == bool_op_diff || bop == bool_op_cut || bop == bool_op_slice ) { + if (bop == bool_op_diff || bop == bool_op_cut || bop == bool_op_slice) { if (reverseOrderForOp) { source = il[0]; } else { @@ -685,16 +686,16 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, } } else { // find out the bottom object - std::vector<Inkscape::XML::Node*> sorted(xmlNodes().begin(), xmlNodes().end()); + std::vector<Inkscape::XML::Node *> sorted(xmlNodes().begin(), xmlNodes().end()); - sort(sorted.begin(),sorted.end(),sp_repr_compare_position_bool); + sort(sorted.begin(), sorted.end(), sp_repr_compare_position_bool); source = doc->getObjectByRepr(sorted.front()); } // adjust style properties that depend on a possible transform in the source object in order // to get a correct style attribute for the new path - SPItem* item_source = SP_ITEM(source); + SPItem *item_source = SP_ITEM(source); Geom::Affine i2doc(item_source->i2doc_affine()); item_source->adjust_stroke(i2doc.descrim()); item_source->adjust_pattern(i2doc); @@ -707,7 +708,7 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, Inkscape::XML::Node *parent = repr_source->parent(); // remove source paths clear(); - for (auto l : il){ + for (auto l : il) { if (l != item_source) { // delete the object for real, so that its clones can take appropriate action l->deleteObject(); @@ -716,34 +717,36 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, // premultiply by the inverse of parent's repr SPItem *parent_item = SP_ITEM(doc->getObjectByRepr(parent)); - Geom::Affine local (parent_item->i2doc_affine()); + Geom::Affine local(parent_item->i2doc_affine()); gchar *transform = sp_svg_transform_write(local.inverse()); // now that we have the result, add it on the canvas - if ( bop == bool_op_cut || bop == bool_op_slice ) { - int nbRP=0; - Path** resPath; - if ( bop == bool_op_slice ) { + if (bop == bool_op_cut || bop == bool_op_slice) { + int nbRP = 0; + Path **resPath; + if (bop == bool_op_slice) { // there are moveto's at each intersection, but it's still one unique path // so break it down and add each subpath independently // we could call break_apart to do this, but while we have the description... - resPath=res->SubPaths(nbRP, false); + resPath = res->SubPaths(nbRP, false); } else { // cut operation is a bit wicked: you need to keep holes // that's why you needed the nesting // ConvertToFormeNested() dumped all the subpath in a single Path "res", so we need // to get the path for each part of the polygon. that's why you need the nesting info: // to know in which subpath to add a subpath - resPath=res->SubPathsWithNesting(nbRP, true, nbNest, nesting, conts); + resPath = res->SubPathsWithNesting(nbRP, true, nbNest, nesting, conts); // cleaning - if ( conts ) free(conts); - if ( nesting ) free(nesting); + if (conts) + free(conts); + if (nesting) + free(nesting); } // add all the pieces resulting from cut or slice - std::vector <Inkscape::XML::Node*> selection; - for (int i=0;i<nbRP;i++) { + std::vector<Inkscape::XML::Node *> selection; + for (int i = 0; i < nbRP; i++) { gchar *d = resPath[i]->svg_dump_path(); Inkscape::XML::Document *xml_doc = doc->getReprDoc(); @@ -784,7 +787,8 @@ BoolOpErrors Inkscape::ObjectSet::pathBoolOp(bool_op bop, const bool skip_undo, delete resPath[i]; } setReprList(selection); - if ( resPath ) free(resPath); + if (resPath) + free(resPath); } else { gchar *d = res->svg_dump_path(); diff --git a/src/path/path-boolop.h b/src/path/path-boolop.h index 59c53f79255367c17c8912ffb7eac3c02b0a9599..586000951ea5573b2a69faa44094f9a1c7b844ff 100644 --- a/src/path/path-boolop.h +++ b/src/path/path-boolop.h @@ -11,10 +11,12 @@ #define PATH_BOOLOP_H #include <2geom/path.h> -#include "livarot/Path.h" // FillRule -#include "object/object-set.h" // bool_op -Geom::PathVector sp_pathvector_boolop(Geom::PathVector const &pathva, Geom::PathVector const &pathvb, bool_op bop, FillRule fra, FillRule frb); +#include "livarot/Path.h" // FillRule +#include "object/object-set.h" // bool_op + +Geom::PathVector sp_pathvector_boolop(Geom::PathVector const &pathva, Geom::PathVector const &pathvb, bool_op bop, + FillRule fra, FillRule frb); #endif // PATH_BOOLOP_H diff --git a/src/path/path-object-set.cpp b/src/path/path-object-set.cpp index 18b89cf23ffeae8f3d1a1b0d50a1f13cd53c9e54..bad41223cd385a2ea4bd6d962822c60f8ea86525 100644 --- a/src/path/path-object-set.cpp +++ b/src/path/path-object-set.cpp @@ -14,71 +14,68 @@ #include <glibmm/i18n.h> +#include "attribute-rel-util.h" #include "document-undo.h" #include "message-stack.h" - -#include "attribute-rel-util.h" - #include "object/object-set.h" #include "path/path-outline.h" #include "path/path-simplify.h" using Inkscape::ObjectSet; -bool -ObjectSet::strokesToPaths(bool legacy, bool skip_undo) +bool ObjectSet::strokesToPaths(bool legacy, bool skip_undo) { - if (desktop() && isEmpty()) { - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>stroked path(s)</b> to convert stroke to path.")); - return false; - } - - // Need to turn on stroke scaling to ensure stroke is scaled when transformed! - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool scale_stroke = prefs->getBool("/options/transform/stroke", true); - prefs->setBool("/options/transform/stroke", true); - - bool did = false; - - std::vector<SPItem *> my_items(items().begin(), items().end()); - - for (auto item : my_items) { - Inkscape::XML::Node *new_node = item_to_paths(item, legacy); - if (new_node) { - remove (item); // Remove from selection. - SPObject* new_item = document()->getObjectByRepr(new_node); - - // Markers don't inherit properties from outside the - // marker. When converted to paths objects they need to be - // protected from inheritance. This is why (probably) the stroke - // to path code uses SP_STYLE_FLAG_ALWAYS when defining the - // style of the fill and stroke during the conversion. This - // means the style contains every possible property. Once we've - // finished the stroke to path conversion, we can eliminate - // unneeded properties from the style element. - sp_attribute_clean_recursive(new_node, SP_ATTRCLEAN_STYLE_REMOVE | SP_ATTRCLEAN_DEFAULT_REMOVE); - - add(new_item); // Add to selection. - did = true; + if (desktop() && isEmpty()) { + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>stroked path(s)</b> to convert stroke to path.")); + return false; + } + + // Need to turn on stroke scaling to ensure stroke is scaled when transformed! + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + bool scale_stroke = prefs->getBool("/options/transform/stroke", true); + prefs->setBool("/options/transform/stroke", true); + + bool did = false; + + std::vector<SPItem *> my_items(items().begin(), items().end()); + + for (auto item : my_items) { + Inkscape::XML::Node *new_node = item_to_paths(item, legacy); + if (new_node) { + remove(item); // Remove from selection. + SPObject *new_item = document()->getObjectByRepr(new_node); + + // Markers don't inherit properties from outside the + // marker. When converted to paths objects they need to be + // protected from inheritance. This is why (probably) the stroke + // to path code uses SP_STYLE_FLAG_ALWAYS when defining the + // style of the fill and stroke during the conversion. This + // means the style contains every possible property. Once we've + // finished the stroke to path conversion, we can eliminate + // unneeded properties from the style element. + sp_attribute_clean_recursive(new_node, SP_ATTRCLEAN_STYLE_REMOVE | SP_ATTRCLEAN_DEFAULT_REMOVE); + + add(new_item); // Add to selection. + did = true; + } } - } - // Reset - prefs->setBool("/options/transform/stroke", scale_stroke); + // Reset + prefs->setBool("/options/transform/stroke", scale_stroke); - if (desktop() && !did) { - desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection.")); - } + if (desktop() && !did) { + desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection.")); + } - if (did && !skip_undo) { - Inkscape::DocumentUndo::done(document(), SP_VERB_NONE, _("Convert stroke to path")); - } + if (did && !skip_undo) { + Inkscape::DocumentUndo::done(document(), SP_VERB_NONE, _("Convert stroke to path")); + } - return did; + return did; } -bool -ObjectSet::simplifyPaths(bool skip_undo) +bool ObjectSet::simplifyPaths(bool skip_undo) { if (desktop() && isEmpty()) { desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to simplify.")); @@ -87,7 +84,7 @@ ObjectSet::simplifyPaths(bool skip_undo) Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double threshold = prefs->getDouble("/options/simplifythreshold/value", 0.003); - bool justCoalesce = prefs->getBool( "/options/simplifyjustcoalesce/value", false); + bool justCoalesce = prefs->getBool("/options/simplifyjustcoalesce/value", false); // Keep track of accelerated simplify static gint64 previous_time = 0; @@ -98,9 +95,8 @@ ObjectSet::simplifyPaths(bool skip_undo) // Was the previous call to this function recent? (<0.5 sec) if (previous_time > 0 && current_time - previous_time < 500000) { - // add to the threshold 1/2 of its original value - multiply += 0.5; + multiply += 0.5; threshold *= multiply; } else { @@ -130,15 +126,17 @@ ObjectSet::simplifyPaths(bool skip_undo) } if (pathsSimplified > 0 && !skip_undo) { - DocumentUndo::done(document(), SP_VERB_SELECTION_SIMPLIFY, _("Simplify")); + DocumentUndo::done(document(), SP_VERB_SELECTION_SIMPLIFY, _("Simplify")); } if (desktop()) { desktop()->clearWaitingCursor(); if (pathsSimplified > 0) { - desktop()->messageStack()->flashF(Inkscape::NORMAL_MESSAGE, _("<b>%d</b> paths simplified."), pathsSimplified); + desktop()->messageStack()->flashF(Inkscape::NORMAL_MESSAGE, _("<b>%d</b> paths simplified."), + pathsSimplified); } else { - desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection.")); + desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, + _("<b>No paths</b> to simplify in the selection.")); } } diff --git a/src/path/path-offset.cpp b/src/path/path-offset.cpp index b35a420af0bd3d2802793c91980fe06b0c2f3748..bd186f57006f6aa576fa6877c137b11ecc3a0280 100644 --- a/src/path/path-offset.cpp +++ b/src/path/path-offset.cpp @@ -15,26 +15,21 @@ * contains lots of stitched pieces of path-chemistry.c */ -#include <vector> - -#include <glibmm/i18n.h> - #include "path-offset.h" -#include "path-util.h" -#include "message-stack.h" -#include "path-chemistry.h" // copy_object_properties() -#include "selection.h" +#include <glibmm/i18n.h> +#include <vector> #include "display/curve.h" - #include "livarot/Path.h" #include "livarot/Shape.h" - +#include "message-stack.h" #include "object/sp-flowtext.h" #include "object/sp-path.h" #include "object/sp-text.h" - +#include "path-chemistry.h" // copy_object_properties() +#include "path-util.h" +#include "selection.h" #include "style.h" #define MIN_OFFSET 0.01 @@ -44,16 +39,14 @@ using Inkscape::DocumentUndo; void sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset); void sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool updating); -void -sp_selected_path_offset(SPDesktop *desktop) +void sp_selected_path_offset(SPDesktop *desktop) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double prefOffset = prefs->getDouble("/options/defaultoffsetwidth/value", 1.0, "px"); sp_selected_path_do_offset(desktop, true, prefOffset); } -void -sp_selected_path_inset(SPDesktop *desktop) +void sp_selected_path_inset(SPDesktop *desktop) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double prefOffset = prefs->getDouble("/options/defaultoffsetwidth/value", 1.0, "px"); @@ -61,19 +54,16 @@ sp_selected_path_inset(SPDesktop *desktop) sp_selected_path_do_offset(desktop, false, prefOffset); } -void -sp_selected_path_offset_screen(SPDesktop *desktop, double pixels) +void sp_selected_path_offset_screen(SPDesktop *desktop, double pixels) { - sp_selected_path_do_offset(desktop, true, pixels / desktop->current_zoom()); + sp_selected_path_do_offset(desktop, true, pixels / desktop->current_zoom()); } -void -sp_selected_path_inset_screen(SPDesktop *desktop, double pixels) +void sp_selected_path_inset_screen(SPDesktop *desktop, double pixels) { - sp_selected_path_do_offset(desktop, false, pixels / desktop->current_zoom()); + sp_selected_path_do_offset(desktop, false, pixels / desktop->current_zoom()); } - void sp_selected_path_create_offset_object_zero(SPDesktop *desktop) { sp_selected_path_create_offset_object(desktop, 0, false); @@ -115,7 +105,8 @@ void sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool if (!text->getNormalizedBpath()) return; } else { - desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset.")); + desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, + _("Selected object is <b>not a path</b>, cannot inset/outset.")); return; } @@ -141,8 +132,7 @@ void sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool } Path *orig = Path_for_item(item, true, false); - if (orig == nullptr) - { + if (orig == nullptr) { return; } @@ -158,16 +148,11 @@ void sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool SPCSSAttr *css = sp_repr_css_attr(item->getRepr(), "style"); gchar const *val = sp_repr_css_property(css, "fill-rule", nullptr); - if (val && strcmp(val, "nonzero") == 0) - { + if (val && strcmp(val, "nonzero") == 0) { theRes->ConvertToShape(theShape, fill_nonZero); - } - else if (val && strcmp(val, "evenodd") == 0) - { + } else if (val && strcmp(val, "evenodd") == 0) { theRes->ConvertToShape(theShape, fill_oddEven); - } - else - { + } else { theRes->ConvertToShape(theShape, fill_nonZero); } @@ -179,15 +164,12 @@ void sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool delete theRes; } - if (res->descr_cmd.size() <= 1) - { + if (res->descr_cmd.size() <= 1) { // pas vraiment de points sur le resultat // donc il ne reste rien - DocumentUndo::done(desktop->getDocument(), - (updating ? SP_VERB_SELECTION_LINKED_OFFSET - : SP_VERB_SELECTION_DYNAMIC_OFFSET), - (updating ? _("Create linked offset") - : _("Create dynamic offset"))); + DocumentUndo::done(desktop->getDocument(), + (updating ? SP_VERB_SELECTION_LINKED_OFFSET : SP_VERB_SELECTION_DYNAMIC_OFFSET), + (updating ? _("Create linked offset") : _("Create dynamic offset"))); selection->clear(); delete res; @@ -207,25 +189,20 @@ void sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool } repr->setAttribute("sodipodi:type", "inkscape:offset"); - sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0 - ? o_width - : expand < 0 - ? -o_width - : 0 )); + sp_repr_set_svg_double(repr, "inkscape:radius", (expand > 0 ? o_width : expand < 0 ? -o_width : 0)); gchar *str = res->svg_dump_path(); repr->setAttribute("inkscape:original", str); g_free(str); str = nullptr; - if ( updating ) { - - //XML Tree being used directly here while it shouldn't be + if (updating) { + // XML Tree being used directly here while it shouldn't be item->doWriteTransform(transform); char const *id = item->getRepr()->attribute("id"); char const *uri = g_strdup_printf("#%s", id); repr->setAttribute("xlink:href", uri); - g_free((void *) uri); + g_free((void *)uri); } else { repr->removeAttribute("inkscape:href"); // delete original @@ -238,7 +215,7 @@ void sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool SPItem *nitem = reinterpret_cast<SPItem *>(desktop->getDocument()->getObjectByRepr(repr)); - if ( !updating ) { + if (!updating) { // apply the transform to the offset nitem->doWriteTransform(transform); } @@ -252,11 +229,9 @@ void sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool selection->set(nitem); } - DocumentUndo::done(desktop->getDocument(), - (updating ? SP_VERB_SELECTION_LINKED_OFFSET - : SP_VERB_SELECTION_DYNAMIC_OFFSET), - (updating ? _("Create linked offset") - : _("Create dynamic offset"))); + DocumentUndo::done(desktop->getDocument(), + (updating ? SP_VERB_SELECTION_LINKED_OFFSET : SP_VERB_SELECTION_DYNAMIC_OFFSET), + (updating ? _("Create linked offset") : _("Create dynamic offset"))); delete res; delete orig; @@ -268,8 +243,7 @@ void sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool * @param expand True if offset expands, False if it shrinks paths * @param prefOffset Size of offset in pixels */ -void -sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset) +void sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset) { Inkscape::Selection *selection = desktop->getSelection(); @@ -279,8 +253,8 @@ sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset) } bool did = false; - std::vector<SPItem*> il(selection->items().begin(), selection->items().end()); - for (auto item : il){ + std::vector<SPItem *> il(selection->items().begin(), selection->items().end()); + for (auto item : il) { if (auto shape = dynamic_cast<SPShape const *>(item)) { if (!shape->curve()) continue; @@ -302,7 +276,7 @@ sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset) float o_width = 0; float o_miter = 0; JoinType o_join = join_straight; - //ButtType o_butt = butt_straight; + // ButtType o_butt = butt_straight; { SPStyle *i_style = item->style; @@ -346,54 +320,46 @@ sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset) SPCSSAttr *css = sp_repr_css_attr(item->getRepr(), "style"); gchar const *val = sp_repr_css_property(css, "fill-rule", nullptr); - if (val && strcmp(val, "nonzero") == 0) - { + if (val && strcmp(val, "nonzero") == 0) { theRes->ConvertToShape(theShape, fill_nonZero); - } - else if (val && strcmp(val, "evenodd") == 0) - { + } else if (val && strcmp(val, "evenodd") == 0) { theRes->ConvertToShape(theShape, fill_oddEven); - } - else - { + } else { theRes->ConvertToShape(theShape, fill_nonZero); } // et maintenant: offset // methode inexacte -/* Path *originaux[1]; - originaux[0] = orig; - theRes->ConvertToForme(res, 1, originaux); - - if (expand) { - res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter); - } else { - res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter); - } - - orig->ConvertWithBackData(1.0); - orig->Fill(theShape, 0); - theRes->ConvertToShape(theShape, fill_positive); - originaux[0] = orig; - theRes->ConvertToForme(res, 1, originaux); - - if (o_width >= 0.5) { - // res->Coalesce(1.0); - res->ConvertEvenLines(1.0); - res->Simplify(1.0); - } else { - // res->Coalesce(o_width); - res->ConvertEvenLines(1.0*o_width); - res->Simplify(1.0 * o_width); - } */ + /* Path *originaux[1]; + originaux[0] = orig; + theRes->ConvertToForme(res, 1, originaux); + + if (expand) { + res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter); + } else { + res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter); + } + + orig->ConvertWithBackData(1.0); + orig->Fill(theShape, 0); + theRes->ConvertToShape(theShape, fill_positive); + originaux[0] = orig; + theRes->ConvertToForme(res, 1, originaux); + + if (o_width >= 0.5) { + // res->Coalesce(1.0); + res->ConvertEvenLines(1.0); + res->Simplify(1.0); + } else { + // res->Coalesce(o_width); + res->ConvertEvenLines(1.0*o_width); + res->Simplify(1.0 * o_width); + } */ // methode par makeoffset - if (expand) - { + if (expand) { theShape->MakeOffset(theRes, o_width, o_join, o_miter); - } - else - { + } else { theShape->MakeOffset(theRes, -o_width, o_join, o_miter); } theRes->ConvertToShape(theShape, fill_positive); @@ -437,7 +403,7 @@ sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset) // move to the saved position parent->addChildAtPos(repr, pos); - SPItem *newitem = (SPItem *) desktop->getDocument()->getObjectByRepr(repr); + SPItem *newitem = (SPItem *)desktop->getDocument()->getObjectByRepr(repr); // reapply the transform newitem->doWriteTransform(transform); @@ -452,8 +418,7 @@ sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset) } if (did) { - DocumentUndo::done(desktop->getDocument(), - (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET), + DocumentUndo::done(desktop->getDocument(), (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET), (expand ? _("Outset path") : _("Inset path"))); } else { desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection.")); diff --git a/src/path/path-offset.h b/src/path/path-offset.h index d4996bcbe7ed3db82a8f82407f123fd185200369..b662185f7e4e0748b293775270084866d58b05a8 100644 --- a/src/path/path-offset.h +++ b/src/path/path-offset.h @@ -15,17 +15,17 @@ class SPDesktop; // offset/inset of a curve // takes the fill-rule in consideration // offset amount is the stroke-width of the curve -void sp_selected_path_offset (SPDesktop *desktop); -void sp_selected_path_offset_screen (SPDesktop *desktop, double pixels); -void sp_selected_path_inset (SPDesktop *desktop); -void sp_selected_path_inset_screen (SPDesktop *desktop, double pixels); -void sp_selected_path_create_offset (SPDesktop *desktop); -void sp_selected_path_create_inset (SPDesktop *desktop); -void sp_selected_path_create_updating_offset (SPDesktop *desktop); -void sp_selected_path_create_updating_inset (SPDesktop *desktop); +void sp_selected_path_offset(SPDesktop *desktop); +void sp_selected_path_offset_screen(SPDesktop *desktop, double pixels); +void sp_selected_path_inset(SPDesktop *desktop); +void sp_selected_path_inset_screen(SPDesktop *desktop, double pixels); +void sp_selected_path_create_offset(SPDesktop *desktop); +void sp_selected_path_create_inset(SPDesktop *desktop); +void sp_selected_path_create_updating_offset(SPDesktop *desktop); +void sp_selected_path_create_updating_inset(SPDesktop *desktop); -void sp_selected_path_create_offset_object_zero (SPDesktop *desktop); -void sp_selected_path_create_updating_offset_object_zero (SPDesktop *desktop); +void sp_selected_path_create_offset_object_zero(SPDesktop *desktop); +void sp_selected_path_create_updating_offset_object_zero(SPDesktop *desktop); #endif // PATH_OFFSET_H diff --git a/src/path/path-outline.cpp b/src/path/path-outline.cpp index 2535b99b3cd9dec4739f820fbb39033727a46285..9842d2578e2918ef5d26b83dc32b52e0027d2d24 100644 --- a/src/path/path-outline.cpp +++ b/src/path/path-outline.cpp @@ -20,24 +20,19 @@ #include <vector> -#include "path-chemistry.h" // Should be moved to path directory -#include "message-stack.h" // Should be removed. -#include "selection.h" -#include "style.h" - -#include "display/curve.h" // Should be moved to path directory - -#include "helper/geom.h" // pathv_to_linear_and_cubic() - +#include "display/curve.h" // Should be moved to path directory +#include "helper/geom.h" // pathv_to_linear_and_cubic() #include "livarot/LivarotDefs.h" #include "livarot/Path.h" #include "livarot/Shape.h" - +#include "message-stack.h" // Should be removed. #include "object/sp-item.h" #include "object/sp-marker.h" #include "object/sp-shape.h" #include "object/sp-text.h" - +#include "path-chemistry.h" // Should be moved to path directory +#include "selection.h" +#include "style.h" #include "svg/svg.h" /** @@ -46,11 +41,10 @@ * bbox_only==true skips cleaning up the stroke path. * Encapsulates use of livarot. */ -bool -item_find_paths(const SPItem *item, Geom::PathVector& fill, Geom::PathVector& stroke, bool bbox_only = false) +bool item_find_paths(const SPItem *item, Geom::PathVector &fill, Geom::PathVector &stroke, bool bbox_only = false) { - const SPShape *shape = dynamic_cast<const SPShape*>(item); - const SPText *text = dynamic_cast<const SPText*>(item); + const SPShape *shape = dynamic_cast<const SPShape *>(item); + const SPText *text = dynamic_cast<const SPText *>(item); if (!shape && !text) { return false; @@ -94,7 +88,7 @@ item_find_paths(const SPItem *item, Geom::PathVector& fill, Geom::PathVector& st // Livarot's outline of arcs is broken. So convert the path to linear and cubics only, for // which the outline is created correctly. - Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( fill ); + Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(fill); SPStyle *style = item->style; @@ -158,12 +152,12 @@ item_find_paths(const SPItem *item, Geom::PathVector& fill, Geom::PathVector& st offset->ConvertWithBackData(1.0); // Approximate by polyline - Shape *theShape = new Shape; + Shape *theShape = new Shape; offset->Fill(theShape, 0); // Convert polyline to shape, step 1. Shape *theOffset = new Shape; theOffset->ConvertToShape(theShape, fill_positive); // Create an intersection free polygon (theOffset), step2. - theOffset->ConvertToForme(origin, 1, &offset); // Turn shape into contour (stored in origin). + theOffset->ConvertToForme(origin, 1, &offset); // Turn shape into contour (stored in origin). stroke = origin->MakePathVector(); // Note origin was replaced above by stroke! } @@ -176,11 +170,10 @@ item_find_paths(const SPItem *item, Geom::PathVector& fill, Geom::PathVector& st return true; } - // ======================== Item to Outline ===================== // -static -void item_to_outline_add_marker_child( SPItem const *item, Geom::Affine marker_transform, Geom::PathVector* pathv_in ) +static void item_to_outline_add_marker_child(SPItem const *item, Geom::Affine marker_transform, + Geom::PathVector *pathv_in) { Geom::Affine tr(marker_transform); tr = item->transform * tr; @@ -188,16 +181,16 @@ void item_to_outline_add_marker_child( SPItem const *item, Geom::Affine marker_t // note: a marker child item can be an item group! if (SP_IS_GROUP(item)) { // recurse through all childs: - for (auto& o: item->children) { - if ( SP_IS_ITEM(&o) ) { + for (auto &o : item->children) { + if (SP_IS_ITEM(&o)) { item_to_outline_add_marker_child(SP_ITEM(&o), tr, pathv_in); } } } else { - Geom::PathVector* marker_pathv = item_to_outline(item); + Geom::PathVector *marker_pathv = item_to_outline(item); if (marker_pathv) { - for (const auto & j : *marker_pathv) { + for (const auto &j : *marker_pathv) { pathv_in->push_back(j * tr); } delete marker_pathv; @@ -205,11 +198,10 @@ void item_to_outline_add_marker_child( SPItem const *item, Geom::Affine marker_t } } -static -void item_to_outline_add_marker( SPObject const *marker_object, Geom::Affine marker_transform, - Geom::Scale stroke_scale, Geom::PathVector* pathv_in ) +static void item_to_outline_add_marker(SPObject const *marker_object, Geom::Affine marker_transform, + Geom::Scale stroke_scale, Geom::PathVector *pathv_in) { - SPMarker const * marker = SP_MARKER(marker_object); + SPMarker const *marker = SP_MARKER(marker_object); Geom::Affine tr(marker_transform); if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) { @@ -218,13 +210,14 @@ void item_to_outline_add_marker( SPObject const *marker_object, Geom::Affine mar // total marker transform tr = marker->c2p * tr; - SPItem const * marker_item = sp_item_first_item_child(marker_object); // why only consider the first item? can a marker only consist of a single item (that may be a group)? + SPItem const *marker_item = + sp_item_first_item_child(marker_object); // why only consider the first item? can a marker only consist of a + // single item (that may be a group)? if (marker_item) { item_to_outline_add_marker_child(marker_item, tr, pathv_in); } } - /** * Returns a pathvector that is the outline of the stroked item, with markers. * item must be an SPShape or an SPText. @@ -232,10 +225,10 @@ void item_to_outline_add_marker( SPObject const *marker_object, Geom::Affine mar * TODO: See if SPShape::either_bbox's union with markers is the same as one would get * with bbox_only false. */ -Geom::PathVector* item_to_outline(SPItem const *item, bool exclude_markers) +Geom::PathVector *item_to_outline(SPItem const *item, bool exclude_markers) { - Geom::PathVector fill; // Used for locating markers. - Geom::PathVector stroke; // Used for creating outline (and finding bbox). + Geom::PathVector fill; // Used for locating markers. + Geom::PathVector stroke; // Used for creating outline (and finding bbox). item_find_paths(item, fill, stroke, true); // Skip cleaning up stroke shape. Geom::PathVector *ret_pathv = nullptr; @@ -258,44 +251,44 @@ Geom::PathVector* item_to_outline(SPItem const *item, bool exclude_markers) const SPShape *shape = dynamic_cast<const SPShape *>(item); if (shape && shape->hasMarkers()) { - SPStyle *style = shape->style; Geom::Scale scale(style->stroke_width.computed); // START marker - for (int i = 0; i < 2; i++) { // SP_MARKER_LOC and SP_MARKER_LOC_START - if ( SPObject *marker_obj = shape->_marker[i] ) { - Geom::Affine const m (sp_shape_marker_get_transform_at_start(fill.front().front())); - item_to_outline_add_marker( marker_obj, m, scale, ret_pathv ); + for (int i = 0; i < 2; i++) { // SP_MARKER_LOC and SP_MARKER_LOC_START + if (SPObject *marker_obj = shape->_marker[i]) { + Geom::Affine const m(sp_shape_marker_get_transform_at_start(fill.front().front())); + item_to_outline_add_marker(marker_obj, m, scale, ret_pathv); } } // MID marker - for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID + for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID SPObject *midmarker_obj = shape->_marker[i]; - if (!midmarker_obj) continue; - for(Geom::PathVector::const_iterator path_it = fill.begin(); path_it != fill.end(); ++path_it) { - + if (!midmarker_obj) + continue; + for (Geom::PathVector::const_iterator path_it = fill.begin(); path_it != fill.end(); ++path_it) { // START position - if ( path_it != fill.begin() && - ! ((path_it == (fill.end()-1)) && (path_it->size_default() == 0)) ) // if this is the last path and it is a moveto-only, there is no mid marker there + if (path_it != fill.begin() && + !((path_it == (fill.end() - 1)) && (path_it->size_default() == 0))) // if this is the last path and + // it is a moveto-only, there is + // no mid marker there { - Geom::Affine const m (sp_shape_marker_get_transform_at_start(path_it->front())); - item_to_outline_add_marker( midmarker_obj, m, scale, ret_pathv); + Geom::Affine const m(sp_shape_marker_get_transform_at_start(path_it->front())); + item_to_outline_add_marker(midmarker_obj, m, scale, ret_pathv); } // MID position if (path_it->size_default() > 1) { - Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve - Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve - while (curve_it2 != path_it->end_default()) - { + Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve + Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve + while (curve_it2 != path_it->end_default()) { /* Put marker between curve_it1 and curve_it2. * Loop to end_default (so including closing segment), because when a path is closed, * there should be a midpoint marker between last segment and closing straight line segment */ - Geom::Affine const m (sp_shape_marker_get_transform(*curve_it1, *curve_it2)); - item_to_outline_add_marker( midmarker_obj, m, scale, ret_pathv); + Geom::Affine const m(sp_shape_marker_get_transform(*curve_it1, *curve_it2)); + item_to_outline_add_marker(midmarker_obj, m, scale, ret_pathv); ++curve_it1; ++curve_it2; @@ -303,17 +296,17 @@ Geom::PathVector* item_to_outline(SPItem const *item, bool exclude_markers) } // END position - if ( path_it != (fill.end()-1) && !path_it->empty()) { + if (path_it != (fill.end() - 1) && !path_it->empty()) { Geom::Curve const &lastcurve = path_it->back_default(); Geom::Affine const m = sp_shape_marker_get_transform_at_end(lastcurve); - item_to_outline_add_marker( midmarker_obj, m, scale, ret_pathv ); + item_to_outline_add_marker(midmarker_obj, m, scale, ret_pathv); } } } // END marker - for (int i = 0; i < 4; i += 3) { // SP_MARKER_LOC and SP_MARKER_LOC_END - if ( SPObject *marker_obj = shape->_marker[i] ) { + for (int i = 0; i < 4; i += 3) { // SP_MARKER_LOC and SP_MARKER_LOC_END + if (SPObject *marker_obj = shape->_marker[i]) { /* Get reference to last curve in the path. * For moveto-only path, this returns the "closing line segment". */ Geom::Path const &path_last = fill.back(); @@ -324,7 +317,7 @@ Geom::PathVector* item_to_outline(SPItem const *item, bool exclude_markers) Geom::Curve const &lastcurve = path_last[index]; Geom::Affine const m = sp_shape_marker_get_transform_at_end(lastcurve); - item_to_outline_add_marker( marker_obj, m, scale, ret_pathv ); + item_to_outline_add_marker(marker_obj, m, scale, ret_pathv); } } } @@ -332,18 +325,14 @@ Geom::PathVector* item_to_outline(SPItem const *item, bool exclude_markers) return ret_pathv; } - - // ========================= Stroke to Path ====================== // -static -void item_to_paths_add_marker( SPObject *marker_object, Geom::Affine marker_transform, - Geom::Scale stroke_scale, - Inkscape::XML::Node *g_repr, Inkscape::XML::Document *xml_doc, - SPDocument * doc, bool legacy) +static void item_to_paths_add_marker(SPObject *marker_object, Geom::Affine marker_transform, Geom::Scale stroke_scale, + Inkscape::XML::Node *g_repr, Inkscape::XML::Document *xml_doc, SPDocument *doc, + bool legacy) { - SPMarker* marker = SP_MARKER (marker_object); - SPItem* marker_item = sp_item_first_item_child(marker_object); + SPMarker *marker = SP_MARKER(marker_object); + SPItem *marker_item = sp_item_first_item_child(marker_object); if (!marker_item) { return; } @@ -359,7 +348,7 @@ void item_to_paths_add_marker( SPObject *marker_object, Geom::Affine marker_tran if (marker_item->getRepr()) { Inkscape::XML::Node *m_repr = marker_item->getRepr()->duplicate(xml_doc); g_repr->addChildAtPos(m_repr, 0); - SPItem *marker_item = (SPItem *) doc->getObjectByRepr(m_repr); + SPItem *marker_item = (SPItem *)doc->getObjectByRepr(m_repr); marker_item->doWriteTransform(tr); if (!legacy) { item_to_paths(marker_item, legacy); @@ -367,7 +356,6 @@ void item_to_paths_add_marker( SPObject *marker_object, Geom::Affine marker_tran } } - /* * Find an outline that represents an item. * If not legacy, items are already converted to paths (see verbs.cpp). @@ -378,8 +366,7 @@ void item_to_paths_add_marker( SPObject *marker_object, Geom::Affine marker_tran * * The return value is only used externally to update a selection. */ -Inkscape::XML::Node* -item_to_paths(SPItem *item, bool legacy) +Inkscape::XML::Node *item_to_paths(SPItem *item, bool legacy) { SPLPEItem *lpeitem = SP_LPE_ITEM(item); if (lpeitem) { @@ -391,7 +378,7 @@ item_to_paths(SPItem *item, bool legacy) if (legacy) { return nullptr; } - std::vector<SPItem*> const item_list = sp_item_group_item_list(group); + std::vector<SPItem *> const item_list = sp_item_group_item_list(group); bool did = false; for (auto subitem : item_list) { if (item_to_paths(subitem, legacy)) { @@ -407,7 +394,7 @@ item_to_paths(SPItem *item, bool legacy) } // As written, only shapes are handled. We bail on text early. - SPShape* shape = dynamic_cast<SPShape *>(item); + SPShape *shape = dynamic_cast<SPShape *>(item); if (!shape) { return nullptr; } @@ -429,17 +416,17 @@ item_to_paths(SPItem *item, bool legacy) // Stroke SPCSSAttr *ncss = sp_css_attr_from_style(style, SP_STYLE_FLAG_ALWAYS); - gchar const *s_val = sp_repr_css_property(ncss, "stroke", nullptr); - gchar const *s_opac = sp_repr_css_property(ncss, "stroke-opacity", nullptr); - gchar const *opacity = sp_repr_css_property(ncss, "opacity", nullptr); // Also for markers - gchar const *filter = sp_repr_css_property(ncss, "filter", nullptr); // Also for markers + gchar const *s_val = sp_repr_css_property(ncss, "stroke", nullptr); + gchar const *s_opac = sp_repr_css_property(ncss, "stroke-opacity", nullptr); + gchar const *opacity = sp_repr_css_property(ncss, "opacity", nullptr); // Also for markers + gchar const *filter = sp_repr_css_property(ncss, "filter", nullptr); // Also for markers sp_repr_css_set_property(ncss, "stroke", "none"); sp_repr_css_set_property(ncss, "filter", nullptr); sp_repr_css_set_property(ncss, "opacity", nullptr); sp_repr_css_set_property(ncss, "stroke-opacity", "1.0"); sp_repr_css_set_property(ncss, "fill", s_val); - if ( s_opac ) { + if (s_opac) { sp_repr_css_set_property(ncss, "fill-opacity", s_opac); } else { sp_repr_css_set_property(ncss, "fill-opacity", "1.0"); @@ -466,7 +453,7 @@ item_to_paths(SPItem *item, bool legacy) // Remember parent Inkscape::XML::Node *parent = item->getRepr()->parent(); - SPDocument * doc = item->document; + SPDocument *doc = item->document; Inkscape::XML::Document *xml_doc = doc->getReprDoc(); // Create a group to put everything in. @@ -497,7 +484,7 @@ item_to_paths(SPItem *item, bool legacy) fill = xml_doc->createElement("svg:path"); sp_repr_css_change(fill, ncsf, "style"); - gchar *str = sp_svg_write_path( fill_path ); + gchar *str = sp_svg_write_path(fill_path); fill->setAttribute("d", str); g_free(str); } @@ -516,41 +503,40 @@ item_to_paths(SPItem *item, bool legacy) } // START marker - for (int i = 0; i < 2; i++) { // SP_MARKER_LOC and SP_MARKER_LOC_START - if ( SPObject *marker_obj = shape->_marker[i] ) { - Geom::Affine const m (sp_shape_marker_get_transform_at_start(fill_path.front().front())); - item_to_paths_add_marker( marker_obj, m, scale, - markers, xml_doc, doc, legacy); + for (int i = 0; i < 2; i++) { // SP_MARKER_LOC and SP_MARKER_LOC_START + if (SPObject *marker_obj = shape->_marker[i]) { + Geom::Affine const m(sp_shape_marker_get_transform_at_start(fill_path.front().front())); + item_to_paths_add_marker(marker_obj, m, scale, markers, xml_doc, doc, legacy); } } // MID marker - for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID + for (int i = 0; i < 3; i += 2) { // SP_MARKER_LOC and SP_MARKER_LOC_MID SPObject *midmarker_obj = shape->_marker[i]; - if (!midmarker_obj) continue; // TODO use auto below - for(Geom::PathVector::const_iterator path_it = fill_path.begin(); path_it != fill_path.end(); ++path_it) { - + if (!midmarker_obj) + continue; // TODO use auto below + for (Geom::PathVector::const_iterator path_it = fill_path.begin(); path_it != fill_path.end(); ++path_it) { // START position - if ( path_it != fill_path.begin() && - ! ((path_it == (fill_path.end()-1)) && (path_it->size_default() == 0)) ) // if this is the last path and it is a moveto-only, there is no mid marker there + if (path_it != fill_path.begin() && !((path_it == (fill_path.end() - 1)) && + (path_it->size_default() == 0))) // if this is the last path and + // it is a moveto-only, there is + // no mid marker there { - Geom::Affine const m (sp_shape_marker_get_transform_at_start(path_it->front())); - item_to_paths_add_marker( midmarker_obj, m, scale, - markers, xml_doc, doc, legacy); + Geom::Affine const m(sp_shape_marker_get_transform_at_start(path_it->front())); + item_to_paths_add_marker(midmarker_obj, m, scale, markers, xml_doc, doc, legacy); } // MID position if (path_it->size_default() > 1) { - Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve - Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve + Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve + Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve while (curve_it2 != path_it->end_default()) { /* Put marker between curve_it1 and curve_it2. * Loop to end_default (so including closing segment), because when a path is closed, * there should be a midpoint marker between last segment and closing straight line segment */ - Geom::Affine const m (sp_shape_marker_get_transform(*curve_it1, *curve_it2)); - item_to_paths_add_marker( midmarker_obj, m, scale, - markers, xml_doc, doc, legacy); + Geom::Affine const m(sp_shape_marker_get_transform(*curve_it1, *curve_it2)); + item_to_paths_add_marker(midmarker_obj, m, scale, markers, xml_doc, doc, legacy); ++curve_it1; ++curve_it2; @@ -558,18 +544,17 @@ item_to_paths(SPItem *item, bool legacy) } // END position - if ( path_it != (fill_path.end()-1) && !path_it->empty()) { + if (path_it != (fill_path.end() - 1) && !path_it->empty()) { Geom::Curve const &lastcurve = path_it->back_default(); Geom::Affine const m = sp_shape_marker_get_transform_at_end(lastcurve); - item_to_paths_add_marker( midmarker_obj, m, scale, - markers, xml_doc, doc, legacy); + item_to_paths_add_marker(midmarker_obj, m, scale, markers, xml_doc, doc, legacy); } } } // END marker - for (int i = 0; i < 4; i += 3) { // SP_MARKER_LOC and SP_MARKER_LOC_END - if ( SPObject *marker_obj = shape->_marker[i] ) { + for (int i = 0; i < 4; i += 3) { // SP_MARKER_LOC and SP_MARKER_LOC_END + if (SPObject *marker_obj = shape->_marker[i]) { /* Get reference to last curve in the path. * For moveto-only path, this returns the "closing line segment". */ Geom::Path const &path_last = fill_path.back(); @@ -580,103 +565,101 @@ item_to_paths(SPItem *item, bool legacy) Geom::Curve const &lastcurve = path_last[index]; Geom::Affine const m = sp_shape_marker_get_transform_at_end(lastcurve); - item_to_paths_add_marker( marker_obj, m, scale, - markers, xml_doc, doc, legacy); + item_to_paths_add_marker(marker_obj, m, scale, markers, xml_doc, doc, legacy); } } } gchar const *paint_order = sp_repr_css_property(ncss, "paint-order", nullptr); SPIPaintOrder temp; - temp.read( paint_order ); + temp.read(paint_order); bool unique = false; if ((!fill && !markers) || (!fill && !stroke) || (!markers && !stroke)) { unique = true; } if (temp.layer[0] != SP_CSS_PAINT_ORDER_NORMAL && !legacy && !unique) { - if (temp.layer[0] == SP_CSS_PAINT_ORDER_FILL) { if (temp.layer[1] == SP_CSS_PAINT_ORDER_STROKE) { - if ( fill ) { + if (fill) { g_repr->appendChild(fill); } - if ( stroke ) { + if (stroke) { g_repr->appendChild(stroke); } - if ( markers ) { + if (markers) { markers->setPosition(2); } } else { - if ( fill ) { + if (fill) { g_repr->appendChild(fill); } - if ( markers ) { + if (markers) { markers->setPosition(1); } - if ( stroke ) { + if (stroke) { g_repr->appendChild(stroke); } } } else if (temp.layer[0] == SP_CSS_PAINT_ORDER_STROKE) { if (temp.layer[1] == SP_CSS_PAINT_ORDER_FILL) { - if ( stroke ) { + if (stroke) { g_repr->appendChild(stroke); } - if ( fill ) { + if (fill) { g_repr->appendChild(fill); } - if ( markers ) { + if (markers) { markers->setPosition(2); } } else { - if ( stroke ) { + if (stroke) { g_repr->appendChild(stroke); } - if ( markers ) { + if (markers) { markers->setPosition(1); } - if ( fill ) { + if (fill) { g_repr->appendChild(fill); } } } else { if (temp.layer[1] == SP_CSS_PAINT_ORDER_STROKE) { - if ( markers ) { + if (markers) { markers->setPosition(0); } - if ( stroke ) { + if (stroke) { g_repr->appendChild(stroke); } - if ( fill ) { + if (fill) { g_repr->appendChild(fill); } } else { - if ( markers ) { + if (markers) { markers->setPosition(0); } - if ( fill ) { + if (fill) { g_repr->appendChild(fill); } - if ( stroke ) { + if (stroke) { g_repr->appendChild(stroke); } } } } else if (!unique) { - if ( fill ) { + if (fill) { g_repr->appendChild(fill); } - if ( stroke ) { + if (stroke) { g_repr->appendChild(stroke); } - if ( markers ) { + if (markers) { markers->setPosition(2); } } bool did = false; - if( fill || stroke || markers ) { + if (fill || stroke || markers) { did = true; } @@ -684,11 +667,11 @@ item_to_paths(SPItem *item, bool legacy) if (!fill && !markers && did) { out = stroke; - } else if (!fill && !stroke && did) { + } else if (!fill && !stroke && did) { out = markers; - } else if (!markers && !stroke && did) { + } else if (!markers && !stroke && did) { out = fill; - } else if(did) { + } else if (did) { out = g_repr; } diff --git a/src/path/path-outline.h b/src/path/path-outline.h index 31556f3b9348be4eb0d07a26d734604ad2514144..7e444d8869611ea17cc0e14102e467ecf44105eb 100644 --- a/src/path/path-outline.h +++ b/src/path/path-outline.h @@ -20,31 +20,30 @@ class SPDesktop; class SPItem; namespace Geom { - class PathVector; +class PathVector; } namespace Inkscape { namespace XML { - class Node; -} +class Node; } +} // namespace Inkscape /** * Find an outline that represents an item. */ -Geom::PathVector* item_to_outline (SPItem const *item, bool exclude_markers = false); +Geom::PathVector *item_to_outline(SPItem const *item, bool exclude_markers = false); /** * Replace item by path objects (a.k.a. stroke to path). */ -Inkscape::XML::Node* item_to_paths(SPItem *item, bool legacy = false); +Inkscape::XML::Node *item_to_paths(SPItem *item, bool legacy = false); /** * Replace selected items by path objects (a.k.a. stroke to >path). * TODO: remove desktop dependency. */ -void selection_to_paths (SPDesktop *desktop, bool legacy = false); - +void selection_to_paths(SPDesktop *desktop, bool legacy = false); #endif // SEEN_PATH_OUTLINE_H diff --git a/src/path/path-simplify.cpp b/src/path/path-simplify.cpp index 7bc7ddf1a3b24ae76e057f254e908a66d0b9f986..3656d2b09ceb3fd8ef51df1a54bafda0ef19766c 100644 --- a/src/path/path-simplify.cpp +++ b/src/path/path-simplify.cpp @@ -14,37 +14,34 @@ #ifdef HAVE_CONFIG_H #endif -#include <vector> - #include "path-simplify.h" -#include "path-util.h" -#include "document-undo.h" -#include "preferences.h" +#include <vector> +#include "document-undo.h" #include "livarot/Path.h" - #include "object/sp-item-group.h" #include "object/sp-path.h" +#include "path-util.h" +#include "preferences.h" using Inkscape::DocumentUndo; // Return number of paths simplified (can be greater than one if group). -int -path_simplify(SPItem *item, float threshold, bool justCoalesce, double size) +int path_simplify(SPItem *item, float threshold, bool justCoalesce, double size) { - //If this is a group, do the children instead - SPGroup* group = dynamic_cast<SPGroup *>(item); + // If this is a group, do the children instead + SPGroup *group = dynamic_cast<SPGroup *>(item); if (group) { int pathsSimplified = 0; - std::vector<SPItem*> items = sp_item_group_item_list(group); + std::vector<SPItem *> items = sp_item_group_item_list(group); for (auto item : items) { pathsSimplified += path_simplify(item, threshold, justCoalesce, size); } return pathsSimplified; } - SPPath* path = dynamic_cast<SPPath *>(item); + SPPath *path = dynamic_cast<SPPath *>(item); if (!path) { return 0; } @@ -82,7 +79,7 @@ path_simplify(SPItem *item, float threshold, bool justCoalesce, double size) return 0; } - if ( justCoalesce ) { + if (justCoalesce) { orig->Coalesce(threshold * size); } else { orig->ConvertEvenLines(threshold * size); @@ -106,7 +103,8 @@ path_simplify(SPItem *item, float threshold, bool justCoalesce, double size) item->doWriteTransform(transform); // clean up - if (orig) delete orig; + if (orig) + delete orig; return 1; } diff --git a/src/path/path-util.cpp b/src/path/path-util.cpp index b3f5fefe5d0cfcf6d6edabb98a95e6e92d205bdd..2e3a60e8bf2293fb201ecd17ff007ec793c680da 100644 --- a/src/path/path-util.cpp +++ b/src/path/path-util.cpp @@ -14,26 +14,22 @@ #ifdef HAVE_CONFIG_H #endif -#include <vector> - #include "path-util.h" -#include "text-editing.h" +#include <vector> +#include "display/curve.h" #include "livarot/Path.h" #include "livarot/Shape.h" - #include "object/sp-flowtext.h" #include "object/sp-image.h" #include "object/sp-marker.h" #include "object/sp-path.h" #include "object/sp-text.h" - -#include "display/curve.h" +#include "text-editing.h" // derived from Path_for_item -Path * -Path_for_pathvector(Geom::PathVector const &epathv) +Path *Path_for_pathvector(Geom::PathVector const &epathv) { /*std::cout << "converting to Livarot path" << std::endl; @@ -46,8 +42,7 @@ Path_for_pathvector(Geom::PathVector const &epathv) return dest; } -Path * -Path_for_item(SPItem *item, bool doTransformation, bool transformFull) +Path *Path_for_item(SPItem *item, bool doTransformation, bool transformFull) { std::unique_ptr<SPCurve> curve = curve_for_item(item); @@ -66,7 +61,7 @@ Path_for_item(SPItem *item, bool doTransformation, bool transformFull) std::cout << wr.str() << std::endl;*/ Path *dest = new Path; - dest->LoadPathVector(*pathv); + dest->LoadPathVector(*pathv); delete pathv; /*gchar *str = dest->svg_dump_path(); @@ -79,17 +74,16 @@ Path_for_item(SPItem *item, bool doTransformation, bool transformFull) /** * Obtains an item's Path before the LPE stack has been applied. */ -Path * -Path_for_item_before_LPE(SPItem *item, bool doTransformation, bool transformFull) +Path *Path_for_item_before_LPE(SPItem *item, bool doTransformation, bool transformFull) { std::unique_ptr<SPCurve> curve = curve_for_item_before_LPE(item); if (curve == nullptr) return nullptr; - + Geom::PathVector *pathv = pathvector_for_curve(item, curve.get(), doTransformation, transformFull, Geom::identity(), Geom::identity()); - + Path *dest = new Path; dest->LoadPathVector(*pathv); delete pathv; @@ -97,19 +91,19 @@ Path_for_item_before_LPE(SPItem *item, bool doTransformation, bool transformFull return dest; } -/* +/* * NOTE: Returns empty pathvector if curve == NULL * TODO: see if calling this method can be optimized. All the pathvector copying might be slow. */ -Geom::PathVector* -pathvector_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull, Geom::Affine extraPreAffine, Geom::Affine extraPostAffine) +Geom::PathVector *pathvector_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull, + Geom::Affine extraPreAffine, Geom::Affine extraPostAffine) { if (curve == nullptr) return nullptr; - Geom::PathVector *dest = new Geom::PathVector; + Geom::PathVector *dest = new Geom::PathVector; *dest = curve->get_pathvector(); // Make a copy; must be freed by the caller! - + if (doTransformation) { if (transformFull) { *dest *= extraPreAffine * item->i2doc_affine() * extraPostAffine; @@ -124,14 +118,15 @@ pathvector_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool t } /** - * Obtains an item's curve. For SPPath, it is the path *before* LPE. For SPShapes other than path, it is the path *after* LPE. - * So the result is somewhat ill-defined, and probably this method should not be used... See curve_for_item_before_LPE. + * Obtains an item's curve. For SPPath, it is the path *before* LPE. For SPShapes other than path, it is the path + * *after* LPE. So the result is somewhat ill-defined, and probably this method should not be used... See + * curve_for_item_before_LPE. */ std::unique_ptr<SPCurve> curve_for_item(SPItem *item) { - if (!item) + if (!item) return nullptr; - + std::unique_ptr<SPCurve> curve; if (auto path = dynamic_cast<SPPath const *>(item)) { @@ -152,9 +147,9 @@ std::unique_ptr<SPCurve> curve_for_item(SPItem *item) */ std::unique_ptr<SPCurve> curve_for_item_before_LPE(SPItem *item) { - if (!item) + if (!item) return nullptr; - + std::unique_ptr<SPCurve> curve; if (auto shape = dynamic_cast<SPShape const *>(item)) { @@ -170,7 +165,7 @@ std::unique_ptr<SPCurve> curve_for_item_before_LPE(SPItem *item) boost::optional<Path::cut_position> get_nearest_position_on_Path(Path *path, Geom::Point p, unsigned seg) { - //get nearest position on path + // get nearest position on path Path::cut_position pos = path->PointToCurvilignPosition(p, seg); return pos; } @@ -182,7 +177,6 @@ Geom::Point get_point_on_Path(Path *path, int piece, double t) return p; } - /* Local Variables: mode:c++ diff --git a/src/path/path-util.h b/src/path/path-util.h index b6596a497b89248ae5862a4c51452aba95019448..bebadd7ba613defb45b46fcded36f6adb50fe046 100644 --- a/src/path/path-util.h +++ b/src/path/path-util.h @@ -12,18 +12,18 @@ #include <2geom/forward.h> #include <2geom/path.h> +#include <memory> #include "livarot/Path.h" -#include <memory> - class SPCurve; class SPItem; Path *Path_for_pathvector(Geom::PathVector const &pathv); Path *Path_for_item(SPItem *item, bool doTransformation, bool transformFull = true); Path *Path_for_item_before_LPE(SPItem *item, bool doTransformation, bool transformFull = true); -Geom::PathVector* pathvector_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull, Geom::Affine extraPreAffine, Geom::Affine extraPostAffine); +Geom::PathVector *pathvector_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull, + Geom::Affine extraPreAffine, Geom::Affine extraPostAffine); std::unique_ptr<SPCurve> curve_for_item(SPItem *item); std::unique_ptr<SPCurve> curve_for_item_before_LPE(SPItem *item); boost::optional<Path::cut_position> get_nearest_position_on_Path(Path *path, Geom::Point p, unsigned seg = 0); diff --git a/src/perspective-line.cpp b/src/perspective-line.cpp index afa3278e1c858919cd62983d046c4adceaa1caaf..e8f98c5b4b2c83474f9f0493107bcbaf5d4127e8 100644 --- a/src/perspective-line.cpp +++ b/src/perspective-line.cpp @@ -14,21 +14,21 @@ namespace Box3D { -PerspectiveLine::PerspectiveLine (Geom::Point const &pt, Proj::Axis const axis, Persp3D const *persp) : - Line (pt, persp->get_VP(axis).affine(), true) +PerspectiveLine::PerspectiveLine(Geom::Point const &pt, Proj::Axis const axis, Persp3D const *persp) + : Line(pt, persp->get_VP(axis).affine(), true) { - g_assert (persp != nullptr); + g_assert(persp != nullptr); if (!persp->get_VP(axis).is_finite()) { Proj::Pt2 vp(persp->get_VP(axis)); this->set_direction(Geom::Point(vp[Proj::X], vp[Proj::Y])); } this->vp_dir = axis; - this->persp = persp; + this->persp = persp; } -} // namespace Box3D - +} // namespace Box3D + /* Local Variables: mode:c++ diff --git a/src/perspective-line.h b/src/perspective-line.h index 9146b3eecf86024ec6db5f51e15c3026f5413b18..c4782379e3e4234d1251950eeb0c9c7df33ecf71 100644 --- a/src/perspective-line.h +++ b/src/perspective-line.h @@ -19,25 +19,24 @@ class SPDesktop; namespace Box3D { -class PerspectiveLine : public Box3D::Line { +class PerspectiveLine : public Box3D::Line +{ public: - /** + /** * Create a perspective line starting at 'pt' and pointing in the direction of the * vanishing point corresponding to 'axis'. If the VP has style VP_FINITE then the * PL runs through it; otherwise it has the direction specified by the v_dir vector * of the VP. */ - PerspectiveLine (Geom::Point const &pt, Proj::Axis const axis, Persp3D const *persp); + PerspectiveLine(Geom::Point const &pt, Proj::Axis const axis, Persp3D const *persp); private: Proj::Axis vp_dir; // direction of the associated VP Persp3D const *persp; }; - } // namespace Box3D - #endif /* !SEEN_PERSPECTIVE_LINE_H */ /* diff --git a/src/preferences-skeleton.h b/src/preferences-skeleton.h index ecdad7409b649450d8bcd7b2c253c5f7c63978c7..abb9a99c38828f625eae1fd634876957e3064e3e 100644 --- a/src/preferences-skeleton.h +++ b/src/preferences-skeleton.h @@ -23,7 +23,7 @@ * and special handling has to be added to the preferences class to update * obsolete versions the user might have. */ static char const preferences_skeleton[] = -R"=====( + R"=====( <inkscape version="1" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"> @@ -490,14 +490,8 @@ R"=====( // calligraphy presets. // Note: actual translation is done in CalligraphyToolbar::build_presets_list(), we just // mark the strings as translatable here (see GitLab issue 128): -Glib::ustring calligraphy_name_array[] = { - _("Dip pen"), - _("Marker"), - _("Brush"), - _("Wiggly"), - _("Splotchy"), - _("Tracing") -}; +Glib::ustring calligraphy_name_array[] = {_("Dip pen"), _("Marker"), _("Brush"), + _("Wiggly"), _("Splotchy"), _("Tracing")}; #endif /* !SEEN_PREFERENCES_SKELETON_H */ diff --git a/src/preferences.cpp b/src/preferences.cpp index c6a761ecf685ffa9f02583192b3fad706334825b..0a686d6baef16929742b5ede7601a28601c63588 100644 --- a/src/preferences.cpp +++ b/src/preferences.cpp @@ -11,23 +11,25 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "preferences.h" + #include <cstring> #include <ctime> -#include <sstream> -#include <utility> -#include <glibmm/fileutils.h> +#include <glib/gstdio.h> #include <glibmm/convert.h> +#include <glibmm/fileutils.h> #include <glibmm/i18n.h> -#include <glib/gstdio.h> -#include "preferences.h" -#include "preferences-skeleton.h" -#include "inkscape.h" -#include "xml/node-observer.h" -#include "xml/node-iterators.h" -#include "xml/attribute-record.h" -#include "util/units.h" +#include <sstream> +#include <utility> + #include "attribute-rel-util.h" +#include "inkscape.h" #include "io/resource.h" +#include "preferences-skeleton.h" +#include "util/units.h" +#include "xml/attribute-record.h" +#include "xml/node-iterators.h" +#include "xml/node-observer.h" #define PREFERENCES_FILE_NAME "preferences.xml" @@ -35,14 +37,14 @@ using Inkscape::Util::unit_table; namespace Inkscape { -static Inkscape::XML::Document *loadImpl( std::string const& prefsFilename, Glib::ustring & errMsg ); -static void migrateDetails( Inkscape::XML::Document *from, Inkscape::XML::Document *to ); +static Inkscape::XML::Document *loadImpl(std::string const &prefsFilename, Glib::ustring &errMsg); +static void migrateDetails(Inkscape::XML::Document *from, Inkscape::XML::Document *to); static Inkscape::XML::Document *migrateFromDoc = nullptr; // cachedRawValue prefixes for encoding nullptr -static Glib::ustring const RAWCACHE_CODE_NULL {"N"}; -static Glib::ustring const RAWCACHE_CODE_VALUE {"V"}; +static Glib::ustring const RAWCACHE_CODE_NULL{"N"}; +static Glib::ustring const RAWCACHE_CODE_VALUE{"V"}; // private inner class definition @@ -52,14 +54,16 @@ static Glib::ustring const RAWCACHE_CODE_VALUE {"V"}; * This is an XML node observer that watches for changes in the XML document storing the preferences. * It is used to implement preference observers. */ -class Preferences::PrefNodeObserver : public XML::NodeObserver { +class Preferences::PrefNodeObserver : public XML::NodeObserver +{ public: - PrefNodeObserver(Observer &o, Glib::ustring filter) : - _observer(o), - _filter(std::move(filter)) + PrefNodeObserver(Observer &o, Glib::ustring filter) + : _observer(o) + , _filter(std::move(filter)) {} ~PrefNodeObserver() override = default; void notifyAttributeChanged(XML::Node &node, GQuark name, Util::ptr_shared, Util::ptr_shared) override; + private: Observer &_observer; Glib::ustring const _filter; @@ -99,7 +103,6 @@ void Preferences::_loadDefaults() // No maximise for Quartz, see lp:1302627 setInt("/options/defaultwindowsize/value", -1); #endif - } /** @@ -141,7 +144,7 @@ void Preferences::_load() } // create some subdirectories for user stuff char const *user_dirs[] = {"extensions", "fonts", "icons", "keys", "palettes", "templates", nullptr}; - for (int i=0; user_dirs[i]; ++i) { + for (int i = 0; user_dirs[i]; ++i) { // XXX Why are we doing this here? shouldn't this be an IO load item? char *dir = Inkscape::IO::Resource::profile_path(user_dirs[i]); if (!g_file_test(dir, G_FILE_TEST_EXISTS)) @@ -154,14 +157,14 @@ void Preferences::_load() //_reportError(Glib::ustring::compose(_("Failed to create the preferences file %1."), // Glib::filename_to_utf8(_prefs_filename)), not_saved); gchar *msg = g_strdup_printf(_("Failed to create the preferences file %s."), - Glib::filename_to_utf8(_prefs_filename).c_str()); + Glib::filename_to_utf8(_prefs_filename).c_str()); _reportError(msg, not_saved); g_free(msg); return; } - if ( migrateFromDoc ) { - migrateDetails( migrateFromDoc, _prefs_doc ); + if (migrateFromDoc) { + migrateDetails(migrateFromDoc, _prefs_doc); } // The prefs file was just created. @@ -172,9 +175,9 @@ void Preferences::_load() // Yes, the pref file exists. Glib::ustring errMsg; - Inkscape::XML::Document *prefs_read = loadImpl( _prefs_filename, errMsg ); + Inkscape::XML::Document *prefs_read = loadImpl(_prefs_filename, errMsg); - if ( prefs_read ) { + if (prefs_read) { // Merge the loaded prefs with defaults. _prefs_doc->root()->mergeFrom(prefs_read->root(), "id"); Inkscape::GC::release(prefs_read); @@ -185,22 +188,23 @@ void Preferences::_load() } //_reportError(msg, not_saved); -static Inkscape::XML::Document *loadImpl( std::string const& prefsFilename, Glib::ustring & errMsg ) +static Inkscape::XML::Document *loadImpl(std::string const &prefsFilename, Glib::ustring &errMsg) { // 2. Is it a regular file? if (!g_file_test(prefsFilename.c_str(), G_FILE_TEST_IS_REGULAR)) { gchar *msg = g_strdup_printf(_("The preferences file %s is not a regular file."), - Glib::filename_to_utf8(prefsFilename).c_str()); + Glib::filename_to_utf8(prefsFilename).c_str()); errMsg = msg; g_free(msg); return nullptr; } // 3. Is the file readable? - gchar *prefs_xml = nullptr; gsize len = 0; + gchar *prefs_xml = nullptr; + gsize len = 0; if (!g_file_get_contents(prefsFilename.c_str(), &prefs_xml, &len, nullptr)) { gchar *msg = g_strdup_printf(_("The preferences file %s could not be read."), - Glib::filename_to_utf8(prefsFilename).c_str()); + Glib::filename_to_utf8(prefsFilename).c_str()); errMsg = msg; g_free(msg); return nullptr; @@ -211,7 +215,7 @@ static Inkscape::XML::Document *loadImpl( std::string const& prefsFilename, Glib g_free(prefs_xml); if (!prefs_read) { gchar *msg = g_strdup_printf(_("The preferences file %s is not a valid XML document."), - Glib::filename_to_utf8(prefsFilename).c_str()); + Glib::filename_to_utf8(prefsFilename).c_str()); errMsg = msg; g_free(msg); return nullptr; @@ -220,7 +224,7 @@ static Inkscape::XML::Document *loadImpl( std::string const& prefsFilename, Glib // 5. Basic sanity check: does the root element have a correct name? if (strcmp(prefs_read->root()->name(), "inkscape")) { gchar *msg = g_strdup_printf(_("The file %s is not a valid Inkscape preferences file."), - Glib::filename_to_utf8(prefsFilename).c_str()); + Glib::filename_to_utf8(prefsFilename).c_str()); errMsg = msg; g_free(msg); Inkscape::GC::release(prefs_read); @@ -230,7 +234,7 @@ static Inkscape::XML::Document *loadImpl( std::string const& prefsFilename, Glib return prefs_read; } -static void migrateDetails( Inkscape::XML::Document *from, Inkscape::XML::Document *to ) +static void migrateDetails(Inkscape::XML::Document *from, Inkscape::XML::Document *to) { // TODO pull in additional prefs with more granularity to->root()->mergeFrom(from->root(), "id"); @@ -267,19 +271,20 @@ void Preferences::save() */ void Preferences::reset() { - time_t sptime = time (nullptr); - struct tm *sptm = localtime (&sptime); + time_t sptime = time(nullptr); + struct tm *sptm = localtime(&sptime); gchar sptstr[256]; strftime(sptstr, 256, "%Y_%m_%d_%H_%M_%S", sptm); char *new_name = g_strdup_printf("%s_%s.xml", _prefs_filename.c_str(), sptstr); - if (g_file_test(_prefs_filename.c_str(), G_FILE_TEST_EXISTS)) { - //int retcode = g_unlink (_prefs_filename.c_str()); - int retcode = g_rename (_prefs_filename.c_str(), new_name ); - if (retcode == 0) g_warning("%s %s.", _("Preferences file was backed up to"), new_name); - else g_warning("%s", _("There was an error trying to reset the preferences file.")); + // int retcode = g_unlink (_prefs_filename.c_str()); + int retcode = g_rename(_prefs_filename.c_str(), new_name); + if (retcode == 0) + g_warning("%s %s.", _("Preferences file was backed up to"), new_name); + else + g_warning("%s", _("There was an error trying to reset the preferences file.")); } g_free(new_name); @@ -291,10 +296,10 @@ void Preferences::reset() save(); } -bool Preferences::getLastError( Glib::ustring& primary, Glib::ustring& secondary ) +bool Preferences::getLastError(Glib::ustring &primary, Glib::ustring &secondary) { bool result = _hasError; - if ( _hasError ) { + if (_hasError) { primary = _lastErrPrimary; secondary = _lastErrSecondary; _hasError = false; @@ -323,7 +328,8 @@ std::vector<Preferences::Entry> Preferences::getAllEntries(Glib::ustring const & // argh - purge this Util::List nonsense from XML classes fast Inkscape::Util::List<Inkscape::XML::AttributeRecord const> alist = node->attributeList(); for (; alist; ++alist) { - temp.push_back( Entry(path + '/' + g_quark_to_string(alist->key), static_cast<void const*>(alist->value.pointer())) ); + temp.push_back( + Entry(path + '/' + g_quark_to_string(alist->key), static_cast<void const *>(alist->value.pointer()))); } } return temp; @@ -372,7 +378,7 @@ void Preferences::setBool(Glib::ustring const &pref_path, bool value) /// @todo Boolean values should be stored as "true" and "false", /// but this is not possible due to an interaction with event contexts. /// Investigate this in depth. - _setRawValue(pref_path, ( value ? "1" : "0" )); + _setRawValue(pref_path, (value ? "1" : "0")); } /** @@ -383,7 +389,8 @@ void Preferences::setBool(Glib::ustring const &pref_path, bool value) */ void Preferences::setPoint(Glib::ustring const &pref_path, Geom::Point value) { - _setRawValue(pref_path, Glib::ustring::compose("%1",value[Geom::X]) + "," + Glib::ustring::compose("%1",value[Geom::Y])); + _setRawValue(pref_path, + Glib::ustring::compose("%1", value[Geom::X]) + "," + Glib::ustring::compose("%1", value[Geom::Y])); } /** @@ -394,7 +401,7 @@ void Preferences::setPoint(Glib::ustring const &pref_path, Geom::Point value) */ void Preferences::setInt(Glib::ustring const &pref_path, int value) { - _setRawValue(pref_path, Glib::ustring::compose("%1",value)); + _setRawValue(pref_path, Glib::ustring::compose("%1", value)); } /** @@ -405,7 +412,7 @@ void Preferences::setInt(Glib::ustring const &pref_path, int value) */ void Preferences::setUInt(Glib::ustring const &pref_path, unsigned int value) { - _setRawValue(pref_path, Glib::ustring::compose("%1",value)); + _setRawValue(pref_path, Glib::ustring::compose("%1", value)); } /** @@ -416,7 +423,7 @@ void Preferences::setUInt(Glib::ustring const &pref_path, unsigned int value) */ void Preferences::setDouble(Glib::ustring const &pref_path, double value) { - _setRawValue(pref_path, Glib::ustring::compose("%1",value)); + _setRawValue(pref_path, Glib::ustring::compose("%1", value)); } /** @@ -428,7 +435,7 @@ void Preferences::setDouble(Glib::ustring const &pref_path, double value) */ void Preferences::setDoubleUnit(Glib::ustring const &pref_path, double value, Glib::ustring const &unit_abbr) { - Glib::ustring str = Glib::ustring::compose("%1%2",value,unit_abbr); + Glib::ustring str = Glib::ustring::compose("%1%2", value, unit_abbr); _setRawValue(pref_path, str); } @@ -475,21 +482,22 @@ void Preferences::mergeStyle(Glib::ustring const &pref_path, SPCSSAttr *style) void Preferences::remove(Glib::ustring const &pref_path) { auto it = cachedRawValue.find(pref_path.c_str()); - if (it != cachedRawValue.end()) cachedRawValue.erase(it); + if (it != cachedRawValue.end()) + cachedRawValue.erase(it); Inkscape::XML::Node *node = _getNode(pref_path, false); if (node && node->parent()) { node->parent()->removeChild(node); - } else { //Handle to remove also attributes in path not only the container node + } else { // Handle to remove also attributes in path not only the container node // verify path - g_assert( pref_path.at(0) == '/' ); - if (_prefs_doc == nullptr){ + g_assert(pref_path.at(0) == '/'); + if (_prefs_doc == nullptr) { return; } node = _prefs_doc->root(); Inkscape::XML::Node *child = nullptr; gchar **splits = g_strsplit(pref_path.c_str(), "/", 0); - if ( splits ) { + if (splits) { for (int part_i = 0; splits[part_i]; ++part_i) { // skip empty path segments if (!splits[part_i][0]) { @@ -518,17 +526,19 @@ void Preferences::remove(Glib::ustring const &pref_path) class Preferences::_ObserverData { public: - _ObserverData(Inkscape::XML::Node *node, bool isAttr) : _node(node), _is_attr(isAttr) {} + _ObserverData(Inkscape::XML::Node *node, bool isAttr) + : _node(node) + , _is_attr(isAttr) + {} Inkscape::XML::Node *_node; ///< Node at which the wrapping PrefNodeObserver is registered - bool _is_attr; ///< Whether this Observer watches a single attribute + bool _is_attr; ///< Whether this Observer watches a single attribute }; -Preferences::Observer::Observer(Glib::ustring path) : - observed_path(std::move(path)), - _data(nullptr) -{ -} +Preferences::Observer::Observer(Glib::ustring path) + : observed_path(std::move(path)) + , _data(nullptr) +{} Preferences::Observer::~Observer() { @@ -537,11 +547,12 @@ Preferences::Observer::~Observer() prefs->removeObserver(*this); } -void Preferences::PrefNodeObserver::notifyAttributeChanged(XML::Node &node, GQuark name, Util::ptr_shared, Util::ptr_shared new_value) +void Preferences::PrefNodeObserver::notifyAttributeChanged(XML::Node &node, GQuark name, Util::ptr_shared, + Util::ptr_shared new_value) { // filter out attributes we don't watch gchar const *attr_name = g_quark_to_string(name); - if ( _filter.empty() || (_filter == attr_name) ) { + if (_filter.empty() || (_filter == attr_name)) { _ObserverData *d = Preferences::_get_pref_observer_data(_observer); Glib::ustring notify_path = _observer.observed_path; @@ -552,11 +563,12 @@ void Preferences::PrefNodeObserver::notifyAttributeChanged(XML::Node &node, GQua // walk the XML tree, saving each of the id attributes in a vector // we terminate when we hit the observer's attachment node, because the path to this node // is already stored in notify_path - for (XML::NodeParentIterator n = &node; static_cast<XML::Node*>(n) != d->_node; ++n) { + for (XML::NodeParentIterator n = &node; static_cast<XML::Node *>(n) != d->_node; ++n) { path_fragments.push_back(n->attribute("id")); } // assemble the elements into a path - for (std::vector<gchar const *>::reverse_iterator i = path_fragments.rbegin(); i != path_fragments.rend(); ++i) { + for (std::vector<gchar const *>::reverse_iterator i = path_fragments.rbegin(); i != path_fragments.rend(); + ++i) { notify_path.push_back('/'); notify_path.append(*i); } @@ -566,7 +578,7 @@ void Preferences::PrefNodeObserver::notifyAttributeChanged(XML::Node &node, GQua notify_path.append(attr_name); } - Entry const val = Preferences::_create_pref_value(notify_path, static_cast<void const*>(new_value.pointer())); + Entry const val = Preferences::_create_pref_value(notify_path, static_cast<void const *>(new_value.pointer())); _observer.notify(val); } } @@ -574,14 +586,16 @@ void Preferences::PrefNodeObserver::notifyAttributeChanged(XML::Node &node, GQua /** * Find the XML node to observe. */ -XML::Node *Preferences::_findObserverNode(Glib::ustring const &pref_path, Glib::ustring &node_key, Glib::ustring &attr_key, bool create) +XML::Node *Preferences::_findObserverNode(Glib::ustring const &pref_path, Glib::ustring &node_key, + Glib::ustring &attr_key, bool create) { // first assume that the last path element is an entry. _keySplit(pref_path, node_key, attr_key); // find the node corresponding to the "directory". Inkscape::XML::Node *node = _getNode(node_key, create), *child; - if (!node) return node; + if (!node) + return node; for (child = node->firstChild(); child; child = child->next()) { // If there is a node with id corresponding to the attr key, @@ -600,7 +614,7 @@ XML::Node *Preferences::_findObserverNode(Glib::ustring const &pref_path, Glib:: void Preferences::addObserver(Observer &o) { // prevent adding the same observer twice - if ( _observer_map.find(&o) == _observer_map.end() ) { + if (_observer_map.find(&o) == _observer_map.end()) { Glib::ustring node_key, attr_key; Inkscape::XML::Node *node; node = _findObserverNode(o.observed_path, node_key, attr_key, true); @@ -612,9 +626,9 @@ void Preferences::addObserver(Observer &o) // if we watch a single pref, we want to receive notifications only for a single node if (o._data->_is_attr) { - node->addObserver( *(_observer_map[&o]) ); + node->addObserver(*(_observer_map[&o])); } else { - node->addSubtreeObserver( *(_observer_map[&o]) ); + node->addSubtreeObserver(*(_observer_map[&o])); } } } @@ -638,7 +652,6 @@ void Preferences::removeObserver(Observer &o) } } - /** * Get the XML node corresponding to the given pref key. * @@ -653,18 +666,18 @@ void Preferences::removeObserver(Observer &o) Inkscape::XML::Node *Preferences::_getNode(Glib::ustring const &pref_key, bool create) { // verify path - g_assert( pref_key.at(0) == '/' ); + g_assert(pref_key.at(0) == '/'); // No longer necessary, can cause problems with input devices which have a dot in the name // g_assert( pref_key.find('.') == Glib::ustring::npos ); - if (_prefs_doc == nullptr){ + if (_prefs_doc == nullptr) { return nullptr; } Inkscape::XML::Node *node = _prefs_doc->root(); Inkscape::XML::Node *child = nullptr; gchar **splits = g_strsplit(pref_key.c_str(), "/", 0); - if ( splits ) { + if (splits) { for (int part_i = 0; splits[part_i]; ++part_i) { // skip empty path segments if (!splits[part_i][0]) { @@ -685,7 +698,7 @@ Inkscape::XML::Node *Preferences::_getNode(Glib::ustring const &pref_key, bool c if (!child) { if (create) { // create the rest of the key - while(splits[part_i]) { + while (splits[part_i]) { child = node->document()->createElement("group"); child->setAttribute("id", splits[part_i]); node->appendChild(child); @@ -713,7 +726,7 @@ Inkscape::XML::Node *Preferences::_getNode(Glib::ustring const &pref_key, bool c void Preferences::_getRawValue(Glib::ustring const &path, gchar const *&result) { // will return empty string if `path` was not in the cache yet - auto& cacheref = cachedRawValue[path.c_str()]; + auto &cacheref = cachedRawValue[path.c_str()]; // check in cache first if (_initialized && !cacheref.empty()) { @@ -731,11 +744,11 @@ void Preferences::_getRawValue(Glib::ustring const &path, gchar const *&result) // retrieve the attribute Inkscape::XML::Node *node = _getNode(node_key, false); - if ( node == nullptr ) { + if (node == nullptr) { result = nullptr; } else { gchar const *attr = node->attribute(attr_key.c_str()); - if ( attr == nullptr ) { + if (attr == nullptr) { result = nullptr; } else { result = attr; @@ -770,10 +783,11 @@ void Preferences::_setRawValue(Glib::ustring const &path, Glib::ustring const &v bool Preferences::_extractBool(Entry const &v) { - if (v.cached_bool) return v.value_bool; + if (v.cached_bool) + return v.value_bool; v.cached_bool = true; gchar const *s = static_cast<gchar const *>(v._value); - if ( !s[0] || !strcmp(s, "0") || !strcmp(s, "false") ) { + if (!s[0] || !strcmp(s, "0") || !strcmp(s, "false")) { return false; } else { v.value_bool = true; @@ -783,25 +797,27 @@ bool Preferences::_extractBool(Entry const &v) Geom::Point Preferences::_extractPoint(Entry const &v) { - if (v.cached_point) return v.value_point; + if (v.cached_point) + return v.value_point; v.cached_point = true; gchar const *s = static_cast<gchar const *>(v._value); - gchar ** strarray = g_strsplit(s, ",", 2); + gchar **strarray = g_strsplit(s, ",", 2); double newx = atoi(strarray[0]); double newy = atoi(strarray[1]); - g_strfreev (strarray); + g_strfreev(strarray); return Geom::Point(newx, newy); } int Preferences::_extractInt(Entry const &v) { - if (v.cached_int) return v.value_int; + if (v.cached_int) + return v.value_int; v.cached_int = true; gchar const *s = static_cast<gchar const *>(v._value); - if ( !strcmp(s, "true") ) { + if (!strcmp(s, "true")) { v.value_int = 1; return true; - } else if ( !strcmp(s, "false") ) { + } else if (!strcmp(s, "false")) { v.value_int = 0; return false; } else { @@ -828,7 +844,8 @@ int Preferences::_extractInt(Entry const &v) unsigned int Preferences::_extractUInt(Entry const &v) { - if (v.cached_uint) return v.value_uint; + if (v.cached_uint) + return v.value_uint; v.cached_uint = true; gchar const *s = static_cast<gchar const *>(v._value); @@ -848,7 +865,8 @@ unsigned int Preferences::_extractUInt(Entry const &v) double Preferences::_extractDouble(Entry const &v) { - if (v.cached_double) return v.value_double; + if (v.cached_double) + return v.value_double; v.cached_double = true; gchar const *s = static_cast<gchar const *>(v._value); v.value_double = g_ascii_strtod(s, nullptr); @@ -864,7 +882,9 @@ double Preferences::_extractDouble(Entry const &v, Glib::ustring const &requeste // no unit specified, don't do conversion return val; } - return val * (unit_table.getUnit(unit)->factor / unit_table.getUnit(requested_unit)->factor); /// \todo rewrite using Quantity class, so the standard code handles unit conversion + return val * (unit_table.getUnit(unit)->factor / + unit_table.getUnit(requested_unit)->factor); /// \todo rewrite using Quantity class, so the standard + /// code handles unit conversion } Glib::ustring Preferences::_extractString(Entry const &v) @@ -874,12 +894,13 @@ Glib::ustring Preferences::_extractString(Entry const &v) Glib::ustring Preferences::_extractUnit(Entry const &v) { - if (v.cached_unit) return v.value_unit; + if (v.cached_unit) + return v.value_unit; v.cached_unit = true; v.value_unit = ""; gchar const *str = static_cast<gchar const *>(v._value); gchar const *e; - g_ascii_strtod(str, (char **) &e); + g_ascii_strtod(str, (char **)&e); if (e == str) { return ""; } @@ -895,7 +916,8 @@ Glib::ustring Preferences::_extractUnit(Entry const &v) guint32 Preferences::_extractColor(Entry const &v) { - if (v.cached_color) return v.value_color; + if (v.cached_color) + return v.value_color; v.cached_color = true; gchar const *s = static_cast<gchar const *>(v._value); std::istringstream hr(s); @@ -912,10 +934,11 @@ guint32 Preferences::_extractColor(Entry const &v) SPCSSAttr *Preferences::_extractStyle(Entry const &v) { - if (v.cached_style) return v.value_style; + if (v.cached_style) + return v.value_style; v.cached_style = true; SPCSSAttr *style = sp_repr_css_attr_new(); - sp_repr_css_attr_add_from_string(style, static_cast<gchar const*>(v._value)); + sp_repr_css_attr_add_from_string(style, static_cast<gchar const *>(v._value)); v.value_style = style; return style; } @@ -956,15 +979,14 @@ Preferences::Entry const Preferences::_create_pref_value(Glib::ustring const &pa return Entry(path, ptr); } -void Preferences::setErrorHandler(ErrorReporter* handler) +void Preferences::setErrorHandler(ErrorReporter *handler) { _errorHandler = handler; } void Preferences::unload(bool save) { - if (_instance) - { + if (_instance) { if (save) { _instance->save(); } @@ -980,7 +1002,6 @@ Glib::ustring Preferences::getPrefsFilename() const Preferences *Preferences::_instance = nullptr; - } // namespace Inkscape /* diff --git a/src/preferences.h b/src/preferences.h index 557bf943a17b5f68b129287ed8f8f18ef1d32ca2..d9fe5163049732cd31bd0c4f835ff487747de080 100644 --- a/src/preferences.h +++ b/src/preferences.h @@ -14,15 +14,15 @@ #ifndef INKSCAPE_PREFSTORE_H #define INKSCAPE_PREFSTORE_H -#include <climits> +#include <2geom/point.h> #include <cfloat> +#include <climits> #include <glibmm/ustring.h> #include <map> #include <memory> #include <unordered_map> #include <utility> #include <vector> -#include <2geom/point.h> #include "xml/repr.h" @@ -31,10 +31,11 @@ typedef unsigned int guint32; namespace Inkscape { -class ErrorReporter { +class ErrorReporter +{ public: virtual ~ErrorReporter() = default; - virtual void handleError(Glib::ustring const& primary, Glib::ustring const& secondary ) const = 0; + virtual void handleError(Glib::ustring const &primary, Glib::ustring const &secondary) const = 0; }; /** @@ -58,7 +59,8 @@ public: * In future, this will be a virtual base from which specific backends * derive (e.g. GConf, flat XML file...) */ -class Preferences { +class Preferences +{ class _ObserverData; public: @@ -75,11 +77,11 @@ public: * If you want to watch for changes in the preferences, you'll have to * derive a class from this one and override the notify() method. */ - class Observer { + class Observer + { friend class Preferences; public: - /** * Constructor. * @@ -111,10 +113,10 @@ public: Glib::ustring const observed_path; ///< Path which the observer watches private: - std::unique_ptr<_ObserverData> _data; ///< additional data used by the implementation while the observer is active + std::unique_ptr<_ObserverData> _data; ///< additional data used by the implementation while the observer is + ///< active }; - /** * Data type representing a typeless value of a preference. * @@ -123,8 +125,9 @@ public: * any preference using the Preferences class invalidates this object, * so use its get methods before doing so. */ - class Entry { - friend class Preferences; // Preferences class has to access _value + class Entry + { + friend class Preferences; // Preferences class has to access _value public: ~Entry() = default; Entry() @@ -137,7 +140,8 @@ public: , cached_double(false) , cached_unit(false) , cached_color(false) - , cached_style(false) {} // needed to enable use in maps + , cached_style(false) + {} // needed to enable use in maps Entry(Entry const &other) = default; /** @@ -152,21 +156,21 @@ public: * * @param def Default value if the preference is not set. */ - inline bool getBool(bool def=false) const; + inline bool getBool(bool def = false) const; /** * Interpret the preference as an point. * * @param def Default value if the preference is not set. */ - inline Geom::Point getPoint(Geom::Point def=Geom::Point()) const; + inline Geom::Point getPoint(Geom::Point def = Geom::Point()) const; /** * Interpret the preference as an integer. * * @param def Default value if the preference is not set. */ - inline int getInt(int def=0) const; + inline int getInt(int def = 0) const; /** * Interpret the preference as a limited integer. @@ -179,22 +183,23 @@ public: * @param min Minimum value allowed to return. * @param max Maximum value allowed to return. */ - inline int getIntLimited(int def=0, int min=INT_MIN, int max=INT_MAX) const; + inline int getIntLimited(int def = 0, int min = INT_MIN, int max = INT_MAX) const; /** * Interpret the preference as an unsigned integer. * * @param def Default value if the preference is not set. */ - inline unsigned int getUInt(unsigned int def=0) const; + inline unsigned int getUInt(unsigned int def = 0) const; /** * Interpret the preference as a floating point value. * * @param def Default value if the preference is not set. - * @param unit Specifies the unit of the returned result. Will be ignored when equal to "". If the preference has no unit set, the default unit will be assumed. + * @param unit Specifies the unit of the returned result. Will be ignored when equal to "". If the preference + * has no unit set, the default unit will be assumed. */ - inline double getDouble(double def=0.0, Glib::ustring const &unit = "") const; + inline double getDouble(double def = 0.0, Glib::ustring const &unit = "") const; /** * Interpret the preference as a limited floating point value. @@ -205,9 +210,11 @@ public: * @param def Default value if the preference is not set. * @param min Minimum value allowed to return. * @param max Maximum value allowed to return. - * @param unit Specifies the unit of the returned result. Will be ignored when equal to "". If the preference has no unit set, the default unit will be assumed. + * @param unit Specifies the unit of the returned result. Will be ignored when equal to "". If the preference + * has no unit set, the default unit will be assumed. */ - inline double getDoubleLimited(double def=0.0, double min=DBL_MIN, double max=DBL_MAX, Glib::ustring const &unit = "") const; + inline double getDoubleLimited(double def = 0.0, double min = DBL_MIN, double max = DBL_MAX, + Glib::ustring const &unit = "") const; /** * Interpret the preference as an UTF-8 string. @@ -216,7 +223,7 @@ public: */ inline Glib::ustring getString() const; - /** + /** * Interpret the preference as a number followed by a unit (without space), and return this unit string. */ inline Glib::ustring getUnit() const; @@ -255,6 +262,7 @@ public: * E.g. For "/options/some_group/some_option" it will return "some_option". */ Glib::ustring getEntryName() const; + private: Entry(Glib::ustring path, void const *v) : _pref_path(std::move(path)) @@ -266,7 +274,8 @@ public: , cached_double(false) , cached_unit(false) , cached_color(false) - , cached_style(false) {} + , cached_style(false) + {} Glib::ustring _pref_path; void const *_value; @@ -278,7 +287,7 @@ public: mutable double value_double; mutable Glib::ustring value_unit; mutable guint32 value_color; - mutable SPCSSAttr* value_style; + mutable SPCSSAttr *value_style; mutable bool cached_bool; mutable bool cached_point; @@ -327,7 +336,7 @@ public: * * @return True if an error has occurred since last checking, false otherwise. */ - bool getLastError( Glib::ustring& primary, Glib::ustring& secondary ); + bool getLastError(Glib::ustring &primary, Glib::ustring &secondary); /** * @name Iterate over directories and entries. @@ -362,9 +371,7 @@ public: * @param pref_path Path to the retrieved preference. * @param def The default value to return if the preference is not set. */ - bool getBool(Glib::ustring const &pref_path, bool def=false) { - return getEntry(pref_path).getBool(def); - } + bool getBool(Glib::ustring const &pref_path, bool def = false) { return getEntry(pref_path).getBool(def); } /** * Retrieve a point. @@ -372,7 +379,8 @@ public: * @param pref_path Path to the retrieved preference. * @param def The default value to return if the preference is not set. */ - Geom::Point getPoint(Glib::ustring const &pref_path, Geom::Point def=Geom::Point()) { + Geom::Point getPoint(Glib::ustring const &pref_path, Geom::Point def = Geom::Point()) + { return getEntry(pref_path).getPoint(def); } @@ -382,9 +390,7 @@ public: * @param pref_path Path to the retrieved preference. * @param def The default value to return if the preference is not set. */ - int getInt(Glib::ustring const &pref_path, int def=0) { - return getEntry(pref_path).getInt(def); - } + int getInt(Glib::ustring const &pref_path, int def = 0) { return getEntry(pref_path).getInt(def); } /** * Retrieve a limited integer. @@ -397,7 +403,8 @@ public: * @param min Minimum value to return. * @param max Maximum value to return. */ - int getIntLimited(Glib::ustring const &pref_path, int def=0, int min=INT_MIN, int max=INT_MAX) { + int getIntLimited(Glib::ustring const &pref_path, int def = 0, int min = INT_MIN, int max = INT_MAX) + { return getEntry(pref_path).getIntLimited(def, min, max); } @@ -407,7 +414,8 @@ public: * @param pref_path Path to the retrieved preference. * @param def The default value to return if the preference is not set. */ - unsigned int getUInt(Glib::ustring const &pref_path, unsigned int def=0) { + unsigned int getUInt(Glib::ustring const &pref_path, unsigned int def = 0) + { return getEntry(pref_path).getUInt(def); } @@ -417,7 +425,8 @@ public: * @param pref_path Path to the retrieved preference. * @param def The default value to return if the preference is not set. */ - double getDouble(Glib::ustring const &pref_path, double def=0.0, Glib::ustring const &unit = "") { + double getDouble(Glib::ustring const &pref_path, double def = 0.0, Glib::ustring const &unit = "") + { return getEntry(pref_path).getDouble(def, unit); } @@ -431,9 +440,12 @@ public: * @param def The default value to return if the preference is not set. * @param min Minimum value to return. * @param max Maximum value to return. - * @param unit Specifies the unit of the returned result. Will be ignored when equal to "". If the preference has no unit set, the default unit will be assumed. + * @param unit Specifies the unit of the returned result. Will be ignored when equal to "". If the preference has no + * unit set, the default unit will be assumed. */ - double getDoubleLimited(Glib::ustring const &pref_path, double def=0.0, double min=DBL_MIN, double max=DBL_MAX, Glib::ustring const &unit = "") { + double getDoubleLimited(Glib::ustring const &pref_path, double def = 0.0, double min = DBL_MIN, + double max = DBL_MAX, Glib::ustring const &unit = "") + { return getEntry(pref_path).getDoubleLimited(def, min, max, unit); } @@ -442,20 +454,17 @@ public: * * @param pref_path Path to the retrieved preference. */ - Glib::ustring getString(Glib::ustring const &pref_path) { - return getEntry(pref_path).getString(); - } + Glib::ustring getString(Glib::ustring const &pref_path) { return getEntry(pref_path).getString(); } /** * Retrieve the unit string. * * @param pref_path Path to the retrieved preference. */ - Glib::ustring getUnit(Glib::ustring const &pref_path) { - return getEntry(pref_path).getUnit(); - } + Glib::ustring getUnit(Glib::ustring const &pref_path) { return getEntry(pref_path).getUnit(); } - guint32 getColor(Glib::ustring const &pref_path, guint32 def=0x000000ff) { + guint32 getColor(Glib::ustring const &pref_path, guint32 def = 0x000000ff) + { return getEntry(pref_path).getColor(def); } @@ -465,9 +474,7 @@ public: * @param pref_path Path to the retrieved preference. * @return A CSS style that has to be unrefed after use. */ - SPCSSAttr *getStyle(Glib::ustring const &pref_path) { - return getEntry(pref_path).getStyle(); - } + SPCSSAttr *getStyle(Glib::ustring const &pref_path) { return getEntry(pref_path).getStyle(); } /** * Retrieve an inherited CSS style. @@ -479,9 +486,7 @@ public: * @param pref_path Path to the retrieved preference. * @return An inherited CSS style that has to be unrefed after use. */ - SPCSSAttr *getInheritedStyle(Glib::ustring const &pref_path) { - return getEntry(pref_path).getInheritedStyle(); - } + SPCSSAttr *getInheritedStyle(Glib::ustring const &pref_path) { return getEntry(pref_path).getInheritedStyle(); } /** * Retrieve a preference entry without specifying its type. @@ -489,7 +494,6 @@ public: Entry const getEntry(Glib::ustring const &pref_path); /*@}*/ - /** * Get the preferences file name in UTF-8. */ @@ -577,18 +581,18 @@ public: * @{ */ - /** * Access the singleton Preferences object. */ - static Preferences *get() { + static Preferences *get() + { if (!_instance) { _instance = new Preferences(); } return _instance; } - void setErrorHandler(ErrorReporter* handler); + void setErrorHandler(ErrorReporter *handler); /** * Unload all preferences. @@ -599,7 +603,7 @@ public: * will reinstate it, so you shouldn't. Pass false as the parameter * to suppress automatic saving. */ - static void unload(bool save=true); + static void unload(bool save = true); /*@}*/ /** @@ -636,17 +640,18 @@ private: void _setRawValue(Glib::ustring const &path, Glib::ustring const &value); void _reportError(Glib::ustring const &, Glib::ustring const &); void _keySplit(Glib::ustring const &pref_path, Glib::ustring &node_key, Glib::ustring &attr_key); - XML::Node *_getNode(Glib::ustring const &pref_path, bool create=false); - XML::Node *_findObserverNode(Glib::ustring const &pref_path, Glib::ustring &node_key, Glib::ustring &attr_key, bool create); - - std::string _prefs_filename; ///< Full filename (with directory) of the prefs file - Glib::ustring _lastErrPrimary; ///< Last primary error message, if any. - Glib::ustring _lastErrSecondary; ///< Last secondary error message, if any. - XML::Document *_prefs_doc = nullptr; ///< XML document storing all the preferences + XML::Node *_getNode(Glib::ustring const &pref_path, bool create = false); + XML::Node *_findObserverNode(Glib::ustring const &pref_path, Glib::ustring &node_key, Glib::ustring &attr_key, + bool create); + + std::string _prefs_filename; ///< Full filename (with directory) of the prefs file + Glib::ustring _lastErrPrimary; ///< Last primary error message, if any. + Glib::ustring _lastErrSecondary; ///< Last secondary error message, if any. + XML::Document *_prefs_doc = nullptr; ///< XML document storing all the preferences ErrorReporter *_errorHandler = nullptr; ///< Pointer to object reporting errors. - bool _writable = false; ///< Will the preferences be saved at exit? - bool _hasError = false; ///< Indication that some error has occurred; - bool _initialized = false; ///< Is this instance fully initialized? Caching should be avoided before. + bool _writable = false; ///< Will the preferences be saved at exit? + bool _hasError = false; ///< Indication that some error has occurred; + bool _initialized = false; ///< Is this instance fully initialized? Caching should be avoided before. std::unordered_map<std::string, Glib::ustring> cachedRawValue; /// Wrapper class for XML node observers @@ -662,8 +667,8 @@ private: static Preferences *_instance; -friend class PrefNodeObserver; -friend class Entry; + friend class PrefNodeObserver; + friend class Entry; }; /* Trivial inline Preferences::Entry functions. @@ -705,7 +710,7 @@ inline int Preferences::Entry::getIntLimited(int def, int min, int max) const return def; } else { int val = Inkscape::Preferences::get()->_extractInt(*this); - return ( val >= min && val <= max ? val : def ); + return (val >= min && val <= max ? val : def); } } @@ -740,7 +745,7 @@ inline double Preferences::Entry::getDoubleLimited(double def, double min, doubl } else { val = Inkscape::Preferences::get()->_extractDouble(*this, unit); } - return ( val >= min && val <= max ? val : def ); + return (val >= min && val <= max ? val : def); } } diff --git a/src/print.cpp b/src/print.cpp index 6e9c85f7a97aa864b5696b7e0653b1a4540398b8..7cd003411cb4f071a0510c2dad8434dbcedacdf2 100644 --- a/src/print.cpp +++ b/src/print.cpp @@ -23,78 +23,65 @@ #include "print.h" #include "desktop.h" -#include "document.h" -#include "inkscape.h" - #include "display/drawing-item.h" #include "display/drawing.h" - +#include "document.h" #include "extension/print.h" #include "extension/system.h" - +#include "inkscape.h" #include "object/sp-item.h" #include "object/sp-root.h" - #include "ui/dialog/print.h" - -unsigned int -SPPrintContext::bind(Geom::Affine const &transform, float opacity) +unsigned int SPPrintContext::bind(Geom::Affine const &transform, float opacity) { return module->bind(transform, opacity); } -unsigned int -SPPrintContext::release() +unsigned int SPPrintContext::release() { return module->release(); } -unsigned int -SPPrintContext::comment(char const *comment) +unsigned int SPPrintContext::comment(char const *comment) { return module->comment(comment); } -unsigned int -SPPrintContext::fill(Geom::PathVector const &pathv, Geom::Affine const &ctm, SPStyle const *style, - Geom::OptRect const &pbox, Geom::OptRect const &dbox, Geom::OptRect const &bbox) +unsigned int SPPrintContext::fill(Geom::PathVector const &pathv, Geom::Affine const &ctm, SPStyle const *style, + Geom::OptRect const &pbox, Geom::OptRect const &dbox, Geom::OptRect const &bbox) { return module->fill(pathv, ctm, style, pbox, dbox, bbox); } -unsigned int -SPPrintContext::stroke(Geom::PathVector const &pathv, Geom::Affine const &ctm, SPStyle const *style, - Geom::OptRect const &pbox, Geom::OptRect const &dbox, Geom::OptRect const &bbox) +unsigned int SPPrintContext::stroke(Geom::PathVector const &pathv, Geom::Affine const &ctm, SPStyle const *style, + Geom::OptRect const &pbox, Geom::OptRect const &dbox, Geom::OptRect const &bbox) { return module->stroke(pathv, ctm, style, pbox, dbox, bbox); } -unsigned int -SPPrintContext::image_R8G8B8A8_N(guchar *px, unsigned int w, unsigned int h, unsigned int rs, - Geom::Affine const &transform, SPStyle const *style) +unsigned int SPPrintContext::image_R8G8B8A8_N(guchar *px, unsigned int w, unsigned int h, unsigned int rs, + Geom::Affine const &transform, SPStyle const *style) { return module->image(px, w, h, rs, transform, style); } -unsigned int SPPrintContext::text(char const *text, Geom::Point p, - SPStyle const *style) +unsigned int SPPrintContext::text(char const *text, Geom::Point p, SPStyle const *style) { return module->text(text, p, style); } /* UI */ -void -sp_print_document(Gtk::Window& parentWindow, SPDocument *doc) +void sp_print_document(Gtk::Window &parentWindow, SPDocument *doc) { doc->ensureUpToDate(); // Build arena - SPItem *base = doc->getRoot(); + SPItem *base = doc->getRoot(); // Run print dialog - Inkscape::UI::Dialog::Print printop(doc,base); + Inkscape::UI::Dialog::Print printop(doc, base); Gtk::PrintOperationResult res = printop.run(Gtk::PRINT_OPERATION_ACTION_PRINT_DIALOG, parentWindow); (void)res; // TODO handle this } @@ -110,7 +97,7 @@ void sp_print_document_to_file(SPDocument *doc, gchar const *filename) mod->set_param_string("destination", (gchar *)filename); -/* Start */ + /* Start */ context.module = mod; /* fixme: This has to go into module constructor somehow */ /* Create new drawing */ @@ -127,13 +114,12 @@ void sp_print_document_to_file(SPDocument *doc, gchar const *filename) (mod->base)->invoke_hide(mod->dkey); mod->base = nullptr; mod->root = nullptr; // should be deleted by invoke_hide -/* end */ + /* end */ mod->set_param_string("destination", oldoutput); g_free(oldoutput); } - /* Local Variables: mode:c++ diff --git a/src/print.h b/src/print.h index e983469a8ede7fda4567caae08e34f93eacbf7a7..19adeb910b147a4890737a04db668d0af9e7e434 100644 --- a/src/print.h +++ b/src/print.h @@ -37,7 +37,8 @@ class Print; } // namespace Extension } // namespace Inkscape -struct SPPrintContext { +struct SPPrintContext +{ Inkscape::Extension::Print *module; unsigned int bind(Geom::Affine const &transform, float opacity); @@ -51,18 +52,15 @@ struct SPPrintContext { unsigned int image_R8G8B8A8_N(unsigned char *px, unsigned int w, unsigned int h, unsigned int rs, Geom::Affine const &transform, SPStyle const *style); - unsigned int text(char const *text, Geom::Point p, - SPStyle const *style); + unsigned int text(char const *text, Geom::Point p, SPStyle const *style); void get_param(char *name, bool *value); }; - /* UI */ -void sp_print_document(Gtk::Window& parentWindow, SPDocument *doc); +void sp_print_document(Gtk::Window &parentWindow, SPDocument *doc); void sp_print_document_to_file(SPDocument *doc, char const *filename); - #endif /* !PRINT_H_INKSCAPE */ /* diff --git a/src/profile-manager.cpp b/src/profile-manager.cpp index b092980ec8d780707c860658b998bc4de27af415..041b98b70a164b06e110ca77bdcc404b7b6793a7 100644 --- a/src/profile-manager.cpp +++ b/src/profile-manager.cpp @@ -8,23 +8,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "profile-manager.h" + #include <algorithm> #include <cstring> -#include "profile-manager.h" - #include "document.h" - #include "object/color-profile.h" - namespace Inkscape { -ProfileManager::ProfileManager(SPDocument *document) : - _doc(document), - _knownProfiles() +ProfileManager::ProfileManager(SPDocument *document) + : _doc(document) + , _knownProfiles() { - _resource_connection = _doc->connectResourcesChanged( "iccprofile", sigc::mem_fun(*this, &ProfileManager::_resourcesChanged) ); + _resource_connection = + _doc->connectResourcesChanged("iccprofile", sigc::mem_fun(*this, &ProfileManager::_resourcesChanged)); } ProfileManager::~ProfileManager() @@ -35,49 +34,49 @@ ProfileManager::~ProfileManager() void ProfileManager::_resourcesChanged() { - std::vector<SPObject*> newList; + std::vector<SPObject *> newList; if (_doc) { - std::vector<SPObject *> current = _doc->getResourceList( "iccprofile" ); + std::vector<SPObject *> current = _doc->getResourceList("iccprofile"); newList = current; } - sort( newList.begin(), newList.end() ); + sort(newList.begin(), newList.end()); - std::vector<SPObject*> diff1; - std::set_difference( _knownProfiles.begin(), _knownProfiles.end(), newList.begin(), newList.end(), - std::insert_iterator<std::vector<SPObject*> >(diff1, diff1.begin()) ); + std::vector<SPObject *> diff1; + std::set_difference(_knownProfiles.begin(), _knownProfiles.end(), newList.begin(), newList.end(), + std::insert_iterator<std::vector<SPObject *>>(diff1, diff1.begin())); - std::vector<SPObject*> diff2; - std::set_difference( newList.begin(), newList.end(), _knownProfiles.begin(), _knownProfiles.end(), - std::insert_iterator<std::vector<SPObject*> >(diff2, diff2.begin()) ); + std::vector<SPObject *> diff2; + std::set_difference(newList.begin(), newList.end(), _knownProfiles.begin(), _knownProfiles.end(), + std::insert_iterator<std::vector<SPObject *>>(diff2, diff2.begin())); - if ( !diff1.empty() ) { - for ( std::vector<SPObject*>::iterator it = diff1.begin(); it < diff1.end(); ++it ) { - SPObject* tmp = *it; - _knownProfiles.erase( remove(_knownProfiles.begin(), _knownProfiles.end(), tmp), _knownProfiles.end() ); - if ( includes(tmp) ) { + if (!diff1.empty()) { + for (std::vector<SPObject *>::iterator it = diff1.begin(); it < diff1.end(); ++it) { + SPObject *tmp = *it; + _knownProfiles.erase(remove(_knownProfiles.begin(), _knownProfiles.end(), tmp), _knownProfiles.end()); + if (includes(tmp)) { _removeOne(tmp); } } } - if ( !diff2.empty() ) { - for ( std::vector<SPObject*>::iterator it = diff2.begin(); it < diff2.end(); ++it ) { - SPObject* tmp = *it; + if (!diff2.empty()) { + for (std::vector<SPObject *>::iterator it = diff2.begin(); it < diff2.end(); ++it) { + SPObject *tmp = *it; _knownProfiles.push_back(tmp); _addOne(tmp); } - sort( _knownProfiles.begin(), _knownProfiles.end() ); + sort(_knownProfiles.begin(), _knownProfiles.end()); } } -ColorProfile* ProfileManager::find(gchar const* name) +ColorProfile *ProfileManager::find(gchar const *name) { - ColorProfile* match = nullptr; - if ( name ) { + ColorProfile *match = nullptr; + if (name) { unsigned int howMany = childCount(nullptr); - for ( unsigned int index = 0; index < howMany; index++ ) { + for (unsigned int index = 0; index < howMany; index++) { SPObject *obj = nthChildOf(nullptr, index); - ColorProfile* prof = reinterpret_cast<ColorProfile*>(obj); + ColorProfile *prof = reinterpret_cast<ColorProfile *>(obj); if (prof && (prof->name && !strcmp(name, prof->name))) { match = prof; break; @@ -87,8 +86,7 @@ ColorProfile* ProfileManager::find(gchar const* name) return match; } -} - +} // namespace Inkscape /* Local Variables: diff --git a/src/profile-manager.h b/src/profile-manager.h index 66655d171f33f2ced2f758edaea296f89922d1f8..4564e686ecb521d2647977102e98851928875c85 100644 --- a/src/profile-manager.h +++ b/src/profile-manager.h @@ -21,14 +21,15 @@ namespace Inkscape { class ColorProfile; -class ProfileManager : public DocumentSubset, - public GC::Finalized +class ProfileManager + : public DocumentSubset + , public GC::Finalized { public: ProfileManager(SPDocument *document); ~ProfileManager() override; - ColorProfile* find(char const* name); + ColorProfile *find(char const *name); private: ProfileManager(ProfileManager const &) = delete; // no copy @@ -36,12 +37,12 @@ private: void _resourcesChanged(); - SPDocument* _doc; + SPDocument *_doc; sigc::connection _resource_connection; - std::vector<SPObject*> _knownProfiles; + std::vector<SPObject *> _knownProfiles; }; -} +} // namespace Inkscape #endif // SEEN_INKSCAPE_PROFILE_MANAGER_H diff --git a/src/proj_pt.cpp b/src/proj_pt.cpp index db9827f63fa29b63dcf04545c23fd95b3fa483ac..84de9cd341615f88411ca48b831ddee3aa17d4cc 100644 --- a/src/proj_pt.cpp +++ b/src/proj_pt.cpp @@ -10,36 +10,38 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "proj_pt.h" + #include <glib.h> -#include "proj_pt.h" #include "svg/stringstream.h" namespace Proj { -Pt2::Pt2(const char *coord_str) { +Pt2::Pt2(const char *coord_str) +{ if (!coord_str) { pt[0] = 0.0; pt[1] = 0.0; pt[2] = 1.0; - g_warning ("Coordinate string is empty. Creating default Pt2\n"); + g_warning("Coordinate string is empty. Creating default Pt2\n"); return; } char **coords = g_strsplit(coord_str, ":", 0); if (coords[0] == nullptr || coords[1] == nullptr || coords[2] == nullptr) { - g_strfreev (coords); - g_warning ("Malformed coordinate string.\n"); + g_strfreev(coords); + g_warning("Malformed coordinate string.\n"); return; } pt[0] = g_ascii_strtod(coords[0], nullptr); pt[1] = g_ascii_strtod(coords[1], nullptr); pt[2] = g_ascii_strtod(coords[2], nullptr); - g_strfreev (coords); + g_strfreev(coords); } -void -Pt2::normalize() { +void Pt2::normalize() +{ if (fabs(pt[2]) < 1E-6 || pt[2] == 1.0) return; pt[0] /= pt[2]; @@ -47,37 +49,35 @@ Pt2::normalize() { pt[2] = 1.0; } -Geom::Point -Pt2::affine() { - if (fabs(pt[2]) < epsilon) { - return Geom::Point (Geom::infinity(), Geom::infinity()); - } - return Geom::Point (pt[0]/pt[2], pt[1]/pt[2]); +Geom::Point Pt2::affine() +{ + if (fabs(pt[2]) < epsilon) { + return Geom::Point(Geom::infinity(), Geom::infinity()); + } + return Geom::Point(pt[0] / pt[2], pt[1] / pt[2]); } -char * -Pt2::coord_string() { +char *Pt2::coord_string() +{ Inkscape::SVGOStringStream os; - os << pt[0] << " : " - << pt[1] << " : " - << pt[2]; + os << pt[0] << " : " << pt[1] << " : " << pt[2]; return g_strdup(os.str().c_str()); } -Pt3::Pt3(const char *coord_str) { +Pt3::Pt3(const char *coord_str) +{ if (!coord_str) { pt[0] = 0.0; pt[1] = 0.0; pt[2] = 0.0; pt[3] = 1.0; - g_warning ("Coordinate string is empty. Creating default Pt2\n"); + g_warning("Coordinate string is empty. Creating default Pt2\n"); return; } char **coords = g_strsplit(coord_str, ":", 0); - if (coords[0] == nullptr || coords[1] == nullptr || - coords[2] == nullptr || coords[3] == nullptr) { - g_strfreev (coords); - g_warning ("Malformed coordinate string.\n"); + if (coords[0] == nullptr || coords[1] == nullptr || coords[2] == nullptr || coords[3] == nullptr) { + g_strfreev(coords); + g_warning("Malformed coordinate string.\n"); return; } @@ -87,8 +87,8 @@ Pt3::Pt3(const char *coord_str) { pt[3] = g_ascii_strtod(coords[3], nullptr); } -void -Pt3::normalize() { +void Pt3::normalize() +{ if (fabs(pt[3]) < 1E-6 || pt[3] == 1.0) return; pt[0] /= pt[3]; @@ -97,13 +97,10 @@ Pt3::normalize() { pt[3] = 1.0; } -char * -Pt3::coord_string() { +char *Pt3::coord_string() +{ Inkscape::SVGOStringStream os; - os << pt[0] << " : " - << pt[1] << " : " - << pt[2] << " : " - << pt[3]; + os << pt[0] << " : " << pt[1] << " : " << pt[2] << " : " << pt[3]; return g_strdup(os.str().c_str()); } diff --git a/src/proj_pt.h b/src/proj_pt.h index 1d1ec473d620889cd00bade80f52c21293813279..bc194ae646f23bbdc2f64dea47f40593db757544 100644 --- a/src/proj_pt.h +++ b/src/proj_pt.h @@ -21,59 +21,80 @@ namespace Proj { const double epsilon = 1E-6; // TODO: Catch the case when the constructors are called with only zeros -class Pt2 { +class Pt2 +{ public: - Pt2 () { pt[0] = 0; pt[1] = 0; pt[2] = 1.0; } // we default to (0 : 0 : 1) - Pt2 (double x, double y, double w) { pt[0] = x; pt[1] = y; pt[2] = w; } - Pt2 (Geom::Point const &point) { pt[0] = point[Geom::X]; pt[1] = point[Geom::Y]; pt[2] = 1; } - Pt2 (const char *coord_str); + Pt2() + { + pt[0] = 0; + pt[1] = 0; + pt[2] = 1.0; + } // we default to (0 : 0 : 1) + Pt2(double x, double y, double w) + { + pt[0] = x; + pt[1] = y; + pt[2] = w; + } + Pt2(Geom::Point const &point) + { + pt[0] = point[Geom::X]; + pt[1] = point[Geom::Y]; + pt[2] = 1; + } + Pt2(const char *coord_str); - inline double operator[] (unsigned int index) const { - if (index > 2) { return Geom::infinity(); } + inline double operator[](unsigned int index) const + { + if (index > 2) { + return Geom::infinity(); + } return pt[index]; } - inline double &operator[] (unsigned int index) { + inline double &operator[](unsigned int index) + { // FIXME: How should we handle wrong indices? - //if (index > 2) { return Geom::infinity(); } + // if (index > 2) { return Geom::infinity(); } return pt[index]; } - inline bool operator== (Pt2 &rhs) { + inline bool operator==(Pt2 &rhs) + { normalize(); rhs.normalize(); - return (fabs(pt[0] - rhs.pt[0]) < epsilon && - fabs(pt[1] - rhs.pt[1]) < epsilon && + return (fabs(pt[0] - rhs.pt[0]) < epsilon && fabs(pt[1] - rhs.pt[1]) < epsilon && fabs(pt[2] - rhs.pt[2]) < epsilon); } - inline bool operator!= (Pt2 &rhs) { - return !((*this) == rhs); - } + inline bool operator!=(Pt2 &rhs) { return !((*this) == rhs); } /*** For convenience, we define addition/subtraction etc. as "affine" operators (i.e., the result for finite points is the same as if the affine points were added ***/ - inline Pt2 operator+(Pt2 &rhs) const { - Pt2 result (*this); + inline Pt2 operator+(Pt2 &rhs) const + { + Pt2 result(*this); result.normalize(); rhs.normalize(); - for ( unsigned i = 0 ; i < 2 ; ++i ) { + for (unsigned i = 0; i < 2; ++i) { result.pt[i] += rhs.pt[i]; } return result; } - inline Pt2 operator-(Pt2 &rhs) const { - Pt2 result (*this); + inline Pt2 operator-(Pt2 &rhs) const + { + Pt2 result(*this); result.normalize(); rhs.normalize(); - for ( unsigned i = 0 ; i < 2 ; ++i ) { + for (unsigned i = 0; i < 2; ++i) { result.pt[i] -= rhs.pt[i]; } return result; } - inline Pt2 operator*(double const s) const { - Pt2 result (*this); + inline Pt2 operator*(double const s) const + { + Pt2 result(*this); result.normalize(); - for ( unsigned i = 0 ; i < 2 ; ++i ) { + for (unsigned i = 0; i < 2; ++i) { result.pt[i] *= s; } return result; @@ -83,73 +104,92 @@ public: Geom::Point affine(); inline bool is_finite() { return pt[2] != 0; } // FIXME: Should we allow for some tolerance? char *coord_string(); - inline void print(char const *s) const { printf ("%s(%8.2f : %8.2f : %8.2f)\n", s, pt[0], pt[1], pt[2]); } + inline void print(char const *s) const { printf("%s(%8.2f : %8.2f : %8.2f)\n", s, pt[0], pt[1], pt[2]); } private: double pt[3]; }; - -class Pt3 { +class Pt3 +{ public: - Pt3 () { pt[0] = 0; pt[1] = 0; pt[2] = 0; pt[3] = 1.0; } // we default to (0 : 0 : 0 : 1) - Pt3 (double x, double y, double z, double w) { pt[0] = x; pt[1] = y; pt[2] = z; pt[3] = w; } - Pt3 (const char *coord_str); + Pt3() + { + pt[0] = 0; + pt[1] = 0; + pt[2] = 0; + pt[3] = 1.0; + } // we default to (0 : 0 : 0 : 1) + Pt3(double x, double y, double z, double w) + { + pt[0] = x; + pt[1] = y; + pt[2] = z; + pt[3] = w; + } + Pt3(const char *coord_str); - inline bool operator== (Pt3 &rhs) { + inline bool operator==(Pt3 &rhs) + { normalize(); rhs.normalize(); - return (fabs(pt[0] - rhs.pt[0]) < epsilon && - fabs(pt[1] - rhs.pt[1]) < epsilon && - fabs(pt[2] - rhs.pt[2]) < epsilon && - fabs(pt[3] - rhs.pt[3]) < epsilon); + return (fabs(pt[0] - rhs.pt[0]) < epsilon && fabs(pt[1] - rhs.pt[1]) < epsilon && + fabs(pt[2] - rhs.pt[2]) < epsilon && fabs(pt[3] - rhs.pt[3]) < epsilon); } /*** For convenience, we define addition/subtraction etc. as "affine" operators (i.e., the result for finite points is the same as if the affine points were added ***/ - inline Pt3 operator+(Pt3 &rhs) const { + inline Pt3 operator+(Pt3 &rhs) const + { Pt3 result(*this); result.normalize(); rhs.normalize(); - for ( unsigned i = 0 ; i < 3 ; ++i ) { + for (unsigned i = 0; i < 3; ++i) { result.pt[i] += rhs.pt[i]; } return result; } - inline Pt3 operator-(Pt3 &rhs) const { - Pt3 result (*this); + inline Pt3 operator-(Pt3 &rhs) const + { + Pt3 result(*this); result.normalize(); rhs.normalize(); - for ( unsigned i = 0 ; i < 3 ; ++i ) { + for (unsigned i = 0; i < 3; ++i) { result.pt[i] -= rhs.pt[i]; } return result; } - inline Pt3 operator*(double const s) const { - Pt3 result (*this); + inline Pt3 operator*(double const s) const + { + Pt3 result(*this); result.normalize(); - for ( unsigned i = 0 ; i < 3 ; ++i ) { + for (unsigned i = 0; i < 3; ++i) { result.pt[i] *= s; } return result; } - inline double operator[] (unsigned int index) const { - if (index > 3) { return Geom::infinity(); } + inline double operator[](unsigned int index) const + { + if (index > 3) { + return Geom::infinity(); + } return pt[index]; } - inline double &operator[] (unsigned int index) { + inline double &operator[](unsigned int index) + { // FIXME: How should we handle wrong indices? - //if (index > 3) { return Geom::infinity(); } + // if (index > 3) { return Geom::infinity(); } return pt[index]; } void normalize(); inline bool is_finite() { return pt[3] != 0; } // FIXME: Should we allow for some tolerance? char *coord_string(); - inline void print(char const *s) const { - printf ("%s(%8.2f : %8.2f : %8.2f : %8.2f)\n", s, pt[0], pt[1], pt[2], pt[3]); + inline void print(char const *s) const + { + printf("%s(%8.2f : %8.2f : %8.2f : %8.2f)\n", s, pt[0], pt[1], pt[2], pt[3]); } private: diff --git a/src/pure-transform.cpp b/src/pure-transform.cpp index 847bbdbfa0927087d6eb21f3dce9cccaec6e3918..6809c1134edb7db1b22fb6241bd3cb993a7cf47e 100644 --- a/src/pure-transform.cpp +++ b/src/pure-transform.cpp @@ -11,21 +11,24 @@ */ #include "pure-transform.h" + #include "snap.h" namespace Inkscape { -void PureTransform::snap(::SnapManager *sm, std::vector<Inkscape::SnapCandidatePoint> const &points, Geom::Point const &pointer) { +void PureTransform::snap(::SnapManager *sm, std::vector<Inkscape::SnapCandidatePoint> const &points, + Geom::Point const &pointer) +{ std::vector<Inkscape::SnapCandidatePoint> transformed_points; Geom::Rect bbox; long source_num = 0; for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); ++i) { - /* Work out the transformed version of this point */ - Geom::Point transformed = getTransformedPoint(*i); // _transformPoint(*i, transformation_type, transformation, origin, dim, uniform); + Geom::Point transformed = + getTransformedPoint(*i); // _transformPoint(*i, transformation_type, transformation, origin, dim, uniform); // add the current transformed point to the box hulling all transformed points if (i == points.begin()) { @@ -34,7 +37,8 @@ void PureTransform::snap(::SnapManager *sm, std::vector<Inkscape::SnapCandidateP bbox.expandTo(transformed); } - transformed_points.emplace_back(transformed, (*i).getSourceType(), source_num, Inkscape::SNAPTARGET_UNDEFINED, Geom::OptRect()); + transformed_points.emplace_back(transformed, (*i).getSourceType(), source_num, Inkscape::SNAPTARGET_UNDEFINED, + Geom::OptRect()); source_num++; } @@ -52,7 +56,6 @@ void PureTransform::snap(::SnapManager *sm, std::vector<Inkscape::SnapCandidateP bool first_free_snap = true; for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); ++i) { - // If we have a collection of SnapCandidatePoints, with mixed constrained snapping and free snapping // requirements (this can happen when scaling, see PureScale::snap()), then freeSnap might never see the // SnapCandidatePoint with source_num == 0. The freeSnap() method in the object snapper depends on this, @@ -65,7 +68,8 @@ void PureTransform::snap(::SnapManager *sm, std::vector<Inkscape::SnapCandidateP first_free_snap = false; } - Inkscape::SnappedPoint snapped_point = snap(sm, *j, (*i).getPoint(), bbox); // Calls the snap() method of the derived classes + Inkscape::SnappedPoint snapped_point = + snap(sm, *j, (*i).getPoint(), bbox); // Calls the snap() method of the derived classes snapped_point.setPointerDistance(Geom::L2(pointer - (*i).getPoint())); @@ -87,7 +91,7 @@ void PureTransform::snap(::SnapManager *sm, std::vector<Inkscape::SnapCandidateP // in case of a free snap we might have use for the transformed point, so let's return that // point, whether it's constrained or not - if (best_snapped_point.isOtherSnapBetter(snapped_point, true) ) { + if (best_snapped_point.isOtherSnapBetter(snapped_point, true)) { // .. so we must keep track of the best non-snapped constrained point.. but what // is the best? There is no best, or is there? We cannot compare on snapped distance // because neither has snapped, and both have their snapped distance set to infinity. @@ -108,7 +112,7 @@ void PureTransform::snap(::SnapManager *sm, std::vector<Inkscape::SnapCandidateP } /* The current best transformation */ - //Geom::Point best_transformation = getResult(best_original_point, best_snapped_point); + // Geom::Point best_transformation = getResult(best_original_point, best_snapped_point); storeTransform(best_original_point, best_snapped_point); Geom::Coord best_metric = best_snapped_point.getSnapDistance(); @@ -118,15 +122,13 @@ void PureTransform::snap(::SnapManager *sm, std::vector<Inkscape::SnapCandidateP best_snapped_point.setSnapDistance(best_metric < 1e6 ? best_metric : Geom::infinity()); } - - - - -Geom::Point PureTranslate::getTransformedPoint(SnapCandidatePoint const &p) const { +Geom::Point PureTranslate::getTransformedPoint(SnapCandidatePoint const &p) const +{ return p.getPoint() + _vector; } -void PureTranslate::storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) { +void PureTranslate::storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) +{ /* Consider the case in which a box is almost aligned with a grid in both * horizontal and vertical directions. The distance to the intersection of * the grid lines will always be larger then the distance to a single grid @@ -141,11 +143,15 @@ void PureTranslate::storeTransform(SnapCandidatePoint const &original_point, Sna _vector_snapped = snapped_point.getPoint() - original_point.getPoint(); } -SnappedPoint PureTranslate::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point /*pt_orig*/, Geom::OptRect const &bbox_to_snap) const { +SnappedPoint PureTranslate::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point /*pt_orig*/, + Geom::OptRect const &bbox_to_snap) const +{ return sm->freeSnap(p, bbox_to_snap); } -SnappedPoint PureTranslateConstrained::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const { +SnappedPoint PureTranslateConstrained::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const +{ // Calculate a constraint dedicated for this specific point // When doing a constrained translation, all points will move in the same direction, i.e. // either horizontally or vertically. The lines along which they move are therefore all @@ -155,42 +161,44 @@ SnappedPoint PureTranslateConstrained::snap(::SnapManager *sm, SnapCandidatePoin return sm->constrainedSnap(p, dedicated_constraint, bbox_to_snap); } - - - - -Geom::Point PureScale::getTransformedPoint(SnapCandidatePoint const &p) const { +Geom::Point PureScale::getTransformedPoint(SnapCandidatePoint const &p) const +{ return (p.getPoint() - _origin) * _scale + _origin; } -void PureScale::storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) { +void PureScale::storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) +{ _scale_snapped = Geom::Scale(Geom::infinity(), Geom::infinity()); // If this point *i is horizontally or vertically aligned with // the origin of the scaling, then it will scale purely in X or Y // We can therefore only calculate the scaling in this direction // and the scaling factor for the other direction should remain // untouched (unless scaling is uniform of course) - Geom::Point const a = snapped_point.getPoint() - _origin; // vector to snapped point + Geom::Point const a = snapped_point.getPoint() - _origin; // vector to snapped point Geom::Point const b = original_point.getPoint() - _origin; // vector to original point (not the transformed point!) for (int index = 0; index < 2; index++) { if (fabs(b[index]) > 1e-4) { // if SCALING CAN occur in this direction - if (fabs(fabs(a[index]/b[index]) - fabs(_scale[index])) > 1e-7) { // if SNAPPING DID occur in this direction - _scale_snapped[index] = a[index] / b[index]; // then calculate it! - // _scale_snapped will be (1,1) if we haven't snapped, because the snapped point equals the original point + if (fabs(fabs(a[index] / b[index]) - fabs(_scale[index])) > 1e-7) { // if SNAPPING DID occur in this + // direction + _scale_snapped[index] = a[index] / b[index]; // then calculate it! + // _scale_snapped will be (1,1) if we haven't snapped, because the snapped point equals the original + // point } // we might have left result[1-index] = Geom::infinity() if scaling didn't occur in the other direction } } if (_scale_snapped == Geom::Scale(Geom::infinity(), Geom::infinity())) { - // This point must have been at the origin, so we cannot possibly snap; it won't scale (i.e. won't move while dragging) + // This point must have been at the origin, so we cannot possibly snap; it won't scale (i.e. won't move while + // dragging) snapped_point.setSnapDistance(Geom::infinity()); snapped_point.setSecondSnapDistance(Geom::infinity()); return; } if (_uniform) { - // Lock the scaling the be uniform, but keep the sign such that we don't change which quadrant we have dragged into + // Lock the scaling the be uniform, but keep the sign such that we don't change which quadrant we have dragged + // into if (fabs(_scale_snapped[0]) < fabs(_scale_snapped[1])) { _scale_snapped[1] = fabs(_scale_snapped[0]) * Geom::sgn(_scale[1]); } else { @@ -214,12 +222,15 @@ void PureScale::storeTransform(SnapCandidatePoint const &original_point, Snapped // When scaling, a point aligned either horizontally or vertically with the origin can only // move in that specific direction; therefore it should only snap in that direction, so this // then becomes a constrained snap; otherwise we can use a free snap; -SnappedPoint PureScale::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const { +SnappedPoint PureScale::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const +{ Geom::Point const b = (pt_orig - _origin); // vector to original point (not the transformed point!) bool const c1 = fabs(b[Geom::X]) < 1e-6; bool const c2 = fabs(b[Geom::Y]) < 1e-6; if ((c1 || c2) && !(c1 && c2)) { - Geom::Point cvec; cvec[c1] = 1.; + Geom::Point cvec; + cvec[c1] = 1.; Snapper::SnapConstraint dedicated_constraint = Inkscape::Snapper::SnapConstraint(_origin, cvec); return sm->constrainedSnap(p, dedicated_constraint, bbox_to_snap); } else { @@ -227,7 +238,9 @@ SnappedPoint PureScale::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geo } } -SnappedPoint PureScaleConstrained::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const { +SnappedPoint PureScaleConstrained::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const +{ // When constrained scaling, only uniform scaling is supported. // When uniformly scaling, each point will have its own unique constraint line, // running from the scaling origin to the original untransformed point. We will @@ -237,11 +250,8 @@ SnappedPoint PureScaleConstrained::snap(::SnapManager *sm, SnapCandidatePoint co return sm->constrainedSnap(p, dedicated_constraint, bbox_to_snap); } - - - - -Geom::Point PureStretchConstrained::getTransformedPoint(SnapCandidatePoint const &p) const { +Geom::Point PureStretchConstrained::getTransformedPoint(SnapCandidatePoint const &p) const +{ Geom::Scale s(1, 1); if (_uniform) s[Geom::X] = s[Geom::Y] = _magnitude; @@ -252,7 +262,9 @@ Geom::Point PureStretchConstrained::getTransformedPoint(SnapCandidatePoint const return ((p.getPoint() - _origin) * s) + _origin; } -SnappedPoint PureStretchConstrained::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const { +SnappedPoint PureStretchConstrained::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const +{ Snapper::SnapConstraint dedicated_constraint; if (_uniform) { // When uniformly stretching, each point will have its own unique constraint line, @@ -261,25 +273,27 @@ SnappedPoint PureStretchConstrained::snap(::SnapManager *sm, SnapCandidatePoint Geom::Point b = pt_orig - _origin; dedicated_constraint = Inkscape::Snapper::SnapConstraint(_origin, b); // dedicated constraint } else { - Geom::Point cvec; cvec[_direction] = 1.; + Geom::Point cvec; + cvec[_direction] = 1.; dedicated_constraint = Inkscape::Snapper::SnapConstraint(pt_orig, cvec); } return sm->constrainedSnap(p, dedicated_constraint, bbox_to_snap); } -void PureStretchConstrained::storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) { - Geom::Point const a = snapped_point.getPoint() - _origin; // vector to snapped point +void PureStretchConstrained::storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) +{ + Geom::Point const a = snapped_point.getPoint() - _origin; // vector to snapped point Geom::Point const b = original_point.getPoint() - _origin; // vector to original point (not the transformed point!) _stretch_snapped = Geom::Scale(Geom::infinity(), Geom::infinity()); if (fabs(b[_direction]) > 1e-4) { // if STRETCHING will occur for this point _stretch_snapped[_direction] = a[_direction] / b[_direction]; - _stretch_snapped[1-_direction] = _uniform ? _stretch_snapped[_direction] : 1; + _stretch_snapped[1 - _direction] = _uniform ? _stretch_snapped[_direction] : 1; } else { // STRETCHING might occur for this point, but only when the stretching is uniform - if (_uniform && fabs(b[1-_direction]) > 1e-4) { - _stretch_snapped[1-_direction] = a[1-_direction] / b[1-_direction]; - _stretch_snapped[_direction] = _stretch_snapped[1-_direction]; + if (_uniform && fabs(b[1 - _direction]) > 1e-4) { + _stretch_snapped[1 - _direction] = a[1 - _direction] / b[1 - _direction]; + _stretch_snapped[_direction] = _stretch_snapped[1 - _direction]; } } @@ -290,21 +304,21 @@ void PureStretchConstrained::storeTransform(SnapCandidatePoint const &original_p snapped_point.setSecondSnapDistance(Geom::infinity()); } - - - - -Geom::Point PureSkewConstrained::getTransformedPoint(SnapCandidatePoint const &p) const { +Geom::Point PureSkewConstrained::getTransformedPoint(SnapCandidatePoint const &p) const +{ Geom::Point transformed; // Apply the skew factor - transformed[_direction] = (p.getPoint())[_direction] + _skew * ((p.getPoint())[1 - _direction] - _origin[1 - _direction]); + transformed[_direction] = + (p.getPoint())[_direction] + _skew * ((p.getPoint())[1 - _direction] - _origin[1 - _direction]); // While skewing, mirroring and scaling (by integer multiples) in the opposite direction is also allowed. // Apply that scale factor here - transformed[1-_direction] = (p.getPoint() - _origin)[1 - _direction] * _scale + _origin[1 - _direction]; + transformed[1 - _direction] = (p.getPoint() - _origin)[1 - _direction] * _scale + _origin[1 - _direction]; return transformed; } -SnappedPoint PureSkewConstrained::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const { +SnappedPoint PureSkewConstrained::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const +{ // Snapping the nodes of the bounding box of a selection that is being transformed, will only work if // the transformation of the bounding box is equal to the transformation of the individual nodes. This is // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew, @@ -313,29 +327,31 @@ SnappedPoint PureSkewConstrained::snap(::SnapManager *sm, SnapCandidatePoint con g_assert(!(p.getSourceType() & Inkscape::SNAPSOURCE_BBOX_CATEGORY)); Geom::Point constraint_vector; - constraint_vector[1-_direction] = 0.0; + constraint_vector[1 - _direction] = 0.0; constraint_vector[_direction] = 1.0; return sm->constrainedSnap(p, Inkscape::Snapper::SnapConstraint(constraint_vector), bbox_to_snap); } -void PureSkewConstrained::storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) { +void PureSkewConstrained::storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) +{ Geom::Point const b = original_point.getPoint() - _origin; // vector to original point (not the transformed point!) - _skew_snapped = (snapped_point.getPoint()[_direction] - (original_point.getPoint())[_direction]) / b[1 - _direction]; // skew factor + _skew_snapped = (snapped_point.getPoint()[_direction] - (original_point.getPoint())[_direction]) / + b[1 - _direction]; // skew factor // Store the metric for this transformation as a virtual distance snapped_point.setSnapDistance(std::abs(_skew_snapped - _skew)); snapped_point.setSecondSnapDistance(Geom::infinity()); } - - - -Geom::Point PureRotateConstrained::getTransformedPoint(SnapCandidatePoint const &p) const { +Geom::Point PureRotateConstrained::getTransformedPoint(SnapCandidatePoint const &p) const +{ return (p.getPoint() - _origin) * Geom::Rotate(_angle) + _origin; } -SnappedPoint PureRotateConstrained::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const { +SnappedPoint PureRotateConstrained::snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const +{ // Snapping the nodes of the bounding box of a selection that is being transformed, will only work if // the transformation of the bounding box is equal to the transformation of the individual nodes. This is // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew, @@ -350,9 +366,11 @@ SnappedPoint PureRotateConstrained::snap(::SnapManager *sm, SnapCandidatePoint c return sm->constrainedSnap(p, dedicated_constraint, bbox_to_snap); } -void PureRotateConstrained::storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) { +void PureRotateConstrained::storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) +{ Geom::Point const a = snapped_point.getPoint() - _origin; // vector to snapped point - Geom::Point const b = (original_point.getPoint() - _origin); // vector to original point (not the transformed point!) + Geom::Point const b = + (original_point.getPoint() - _origin); // vector to original point (not the transformed point!) // a is vector to snapped point; b is vector to original point; now lets calculate angle between a and b _angle_snapped = atan2(Geom::dot(Geom::rot90(b), a), Geom::dot(b, a)); if (Geom::L2(b) < 1e-9) { // points too close to the rotation center will not move. Don't try to snap these @@ -368,7 +386,6 @@ void PureRotateConstrained::storeTransform(SnapCandidatePoint const &original_po snapped_point.setSnapDistance(fabs(_angle_snapped - _angle)); } snapped_point.setSecondSnapDistance(Geom::infinity()); - } -} +} // namespace Inkscape diff --git a/src/pure-transform.h b/src/pure-transform.h index 6c5c7b589c1813805421967dff503a76c12f47c8..b6cdc2fc236eb21cedcda1ba165647344510a78f 100644 --- a/src/pure-transform.h +++ b/src/pure-transform.h @@ -16,23 +16,27 @@ #define SEEN_PURE_TRANSFORM_H #include <glib.h> // for g_warning + #include "snapper.h" // for SnapConstraint class SnapManager; namespace Inkscape { -class PureTransform { - +class PureTransform +{ protected: - virtual SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const = 0; + virtual SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const = 0; virtual Geom::Point getTransformedPoint(SnapCandidatePoint const &p) const = 0; virtual void storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) = 0; public: - //PureTransform(); - virtual ~PureTransform() = default;; -// virtual PureTransform * clone () const = 0; // https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Virtual_Constructor + // PureTransform(); + virtual ~PureTransform() = default; + ; + // virtual PureTransform * clone () const = 0; // + // https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Virtual_Constructor // Snap a group of points SnappedPoint best_snapped_point; @@ -41,189 +45,209 @@ public: // ************************************************************************************************************** -class PureTranslate: public PureTransform { - +class PureTranslate : public PureTransform +{ protected: Geom::Point _vector; Geom::Point _vector_snapped; - SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const override; + SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const override; Geom::Point getTransformedPoint(SnapCandidatePoint const &p) const override; void storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) override; public: -// PureTranslate(); // Default constructor -// PureTranslate(PureTranslate const &); // Copy constructor - ~PureTranslate() override = default;; - PureTranslate(Geom::Point vector = Geom::Point()) : _vector(vector), _vector_snapped(vector) {} + // PureTranslate(); // Default constructor + // PureTranslate(PureTranslate const &); // Copy constructor + ~PureTranslate() override = default; + ; + PureTranslate(Geom::Point vector = Geom::Point()) + : _vector(vector) + , _vector_snapped(vector) + {} - Geom::Point getTranslationSnapped() {return _vector_snapped;} -// PureTranslate * clone () const {return new PureTranslate(*this);} + Geom::Point getTranslationSnapped() { return _vector_snapped; } + // PureTranslate * clone () const {return new PureTranslate(*this);} }; - -class PureTranslateConstrained: public PureTranslate { - +class PureTranslateConstrained : public PureTranslate +{ protected: Geom::Dim2 _direction; - SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const override; + SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const override; public: - ~PureTranslateConstrained() override = default;; - PureTranslateConstrained(Geom::Coord displacement, Geom::Dim2 direction): - PureTranslate() { - _vector[direction] = displacement; - _vector[1-direction] = 0.0; - _direction = direction; - } + ~PureTranslateConstrained() override = default; + ; + PureTranslateConstrained(Geom::Coord displacement, Geom::Dim2 direction) + : PureTranslate() + { + _vector[direction] = displacement; + _vector[1 - direction] = 0.0; + _direction = direction; + } // PureTranslateConstrained * clone () const {return new PureTranslateConstrained(*this);} }; // ************************************************************************************************************** -class PureScale: public PureTransform { - +class PureScale : public PureTransform +{ protected: Geom::Scale _scale; Geom::Scale _scale_snapped; Geom::Point _origin; - bool _uniform; + bool _uniform; - SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const override; + SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const override; Geom::Point getTransformedPoint(SnapCandidatePoint const &p) const override; void storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) override; public: -// PureScale(); // Default constructor -// PureScale(PureScale const &); // Copy constructor - ~PureScale() override = default;; - - PureScale(Geom::Scale scale, Geom::Point origin, bool uniform) : - _scale (scale), - _scale_snapped (scale), - _origin (origin), - _uniform (uniform) + // PureScale(); // Default constructor + // PureScale(PureScale const &); // Copy constructor + ~PureScale() override = default; + ; + + PureScale(Geom::Scale scale, Geom::Point origin, bool uniform) + : _scale(scale) + , _scale_snapped(scale) + , _origin(origin) + , _uniform(uniform) {} - Geom::Scale getScaleSnapped() {return _scale_snapped;} -// PureScale * clone () const {return new PureScale (*this);} + Geom::Scale getScaleSnapped() { return _scale_snapped; } + // PureScale * clone () const {return new PureScale (*this);} }; -class PureScaleConstrained: public PureScale { -//Magnitude of the scale components will be the same, but the sign could still be different () +class PureScaleConstrained : public PureScale +{ + // Magnitude of the scale components will be the same, but the sign could still be different () protected: - SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const override; + SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const override; public: - ~PureScaleConstrained() override = default;; - PureScaleConstrained(Geom::Scale scale, Geom::Point origin): - PureScale(scale, origin, true) {}; // Non-uniform constrained scaling is not supported + ~PureScaleConstrained() override = default; + ; + PureScaleConstrained(Geom::Scale scale, Geom::Point origin) + : PureScale(scale, origin, true){}; // Non-uniform constrained scaling is not supported -// PureScaleConstrained * clone () const {return new PureScaleConstrained(*this);} + // PureScaleConstrained * clone () const {return new PureScaleConstrained(*this);} }; // ************************************************************************************************************** -class PureStretchConstrained: public PureTransform { -// A stretch is always implicitly constrained +class PureStretchConstrained : public PureTransform +{ + // A stretch is always implicitly constrained protected: Geom::Coord _magnitude; Geom::Scale _stretch_snapped; Geom::Point _origin; - Geom::Dim2 _direction; - bool _uniform; + Geom::Dim2 _direction; + bool _uniform; - SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const override; + SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const override; Geom::Point getTransformedPoint(SnapCandidatePoint const &p) const override; void storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) override; public: - ~PureStretchConstrained() override = default;; - PureStretchConstrained(Geom::Coord magnitude, Geom::Point origin, Geom::Dim2 direction, bool uniform) : - _magnitude (magnitude), - _stretch_snapped (Geom::Scale(magnitude, magnitude)), - _origin (origin), - _direction (direction), - _uniform (uniform) + ~PureStretchConstrained() override = default; + ; + PureStretchConstrained(Geom::Coord magnitude, Geom::Point origin, Geom::Dim2 direction, bool uniform) + : _magnitude(magnitude) + , _stretch_snapped(Geom::Scale(magnitude, magnitude)) + , _origin(origin) + , _direction(direction) + , _uniform(uniform) { if (not uniform) { - _stretch_snapped[1-direction] = 1.0; + _stretch_snapped[1 - direction] = 1.0; } } - Geom::Scale getStretchSnapped() {return _stretch_snapped;} - Geom::Coord getMagnitude() {return _magnitude;} - Geom::Coord getMagnitudeSnapped() {return _stretch_snapped[_direction];} + Geom::Scale getStretchSnapped() { return _stretch_snapped; } + Geom::Coord getMagnitude() { return _magnitude; } + Geom::Coord getMagnitudeSnapped() { return _stretch_snapped[_direction]; } -// PureStretchConstrained * clone () const {return new PureStretchConstrained(*this);} + // PureStretchConstrained * clone () const {return new PureStretchConstrained(*this);} }; // ************************************************************************************************************** -class PureSkewConstrained: public PureTransform { -// A skew is always implicitly constrained +class PureSkewConstrained : public PureTransform +{ + // A skew is always implicitly constrained protected: Geom::Coord _skew; Geom::Coord _skew_snapped; Geom::Coord _scale; Geom::Point _origin; - Geom::Dim2 _direction; + Geom::Dim2 _direction; - SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const override; + SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const override; Geom::Point getTransformedPoint(SnapCandidatePoint const &p) const override; void storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) override; public: - ~PureSkewConstrained() override = default;; - PureSkewConstrained(Geom::Coord skew, Geom::Coord scale, Geom::Point origin, Geom::Dim2 direction) : - _skew (skew), - _skew_snapped (skew), - _scale (scale), - _origin (origin), - _direction (direction) - {}; - - Geom::Coord getSkewSnapped() {return _skew_snapped;} - -// PureSkewConstrained * clone () const {return new PureSkewConstrained(*this);} + ~PureSkewConstrained() override = default; + ; + PureSkewConstrained(Geom::Coord skew, Geom::Coord scale, Geom::Point origin, Geom::Dim2 direction) + : _skew(skew) + , _skew_snapped(skew) + , _scale(scale) + , _origin(origin) + , _direction(direction){}; + + Geom::Coord getSkewSnapped() { return _skew_snapped; } + + // PureSkewConstrained * clone () const {return new PureSkewConstrained(*this);} }; // ************************************************************************************************************** -class PureRotateConstrained: public PureTransform { -// A rotation is always implicitly constrained, so we will hide the constructor by making it protected; devs should use PureRotateConstrained instead -// It's _constraint member variable though will be empty +class PureRotateConstrained : public PureTransform +{ + // A rotation is always implicitly constrained, so we will hide the constructor by making it protected; devs should + // use PureRotateConstrained instead It's _constraint member variable though will be empty protected: - double _angle; // in radians - double _angle_snapped; + double _angle; // in radians + double _angle_snapped; Geom::Point _origin; - bool _uniform; + bool _uniform; - SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, Geom::OptRect const &bbox_to_snap) const override; + SnappedPoint snap(::SnapManager *sm, SnapCandidatePoint const &p, Geom::Point pt_orig, + Geom::OptRect const &bbox_to_snap) const override; Geom::Point getTransformedPoint(SnapCandidatePoint const &p) const override; void storeTransform(SnapCandidatePoint const &original_point, SnappedPoint &snapped_point) override; public: -// PureRotate(); // Default constructor -// PureRotate(PureRotate const &); // Copy constructor - ~PureRotateConstrained() override = default;; - - PureRotateConstrained(double angle, Geom::Point origin) : - _angle (angle), // in radians! - _angle_snapped (angle), - _origin (origin), - _uniform (true) // We do not yet allow for simultaneous rotation and scaling + // PureRotate(); // Default constructor + // PureRotate(PureRotate const &); // Copy constructor + ~PureRotateConstrained() override = default; + ; + + PureRotateConstrained(double angle, Geom::Point origin) + : _angle(angle) + , // in radians! + _angle_snapped(angle) + , _origin(origin) + , _uniform(true) // We do not yet allow for simultaneous rotation and scaling {} - double getAngleSnapped() {return _angle_snapped;} + double getAngleSnapped() { return _angle_snapped; } -// PureRotate * clone () const {return new PureRotate(*this);} + // PureRotate * clone () const {return new PureRotate(*this);} }; -} +} // namespace Inkscape #endif // !SEEN_PURE_TRANSFORM_H - diff --git a/src/rdf.cpp b/src/rdf.cpp index 563776a19b80ca288aef3adfa75efc832f71f3f1..3a680f8124620e27e63456f48364be3de96191ec 100644 --- a/src/rdf.cpp +++ b/src/rdf.cpp @@ -15,13 +15,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "inkscape.h" -#include "preferences.h" #include "rdf.h" +#include "inkscape.h" #include "object/sp-item-group.h" #include "object/sp-root.h" - +#include "preferences.h" #include "xml/repr.h" /* @@ -225,18 +224,17 @@ struct rdf_license_t rdf_licenses [] = { }; // clang-format on -#define XML_TAG_NAME_SVG "svg:svg" +#define XML_TAG_NAME_SVG "svg:svg" #define XML_TAG_NAME_METADATA "svg:metadata" -#define XML_TAG_NAME_RDF "rdf:RDF" -#define XML_TAG_NAME_WORK "cc:Work" -#define XML_TAG_NAME_LICENSE "cc:License" +#define XML_TAG_NAME_RDF "rdf:RDF" +#define XML_TAG_NAME_WORK "cc:Work" +#define XML_TAG_NAME_LICENSE "cc:License" // Note the lowercase L! -#define XML_TAG_NAME_LICENSE_PROP "cc:license" - +#define XML_TAG_NAME_LICENSE_PROP "cc:license" // Remember when using the "title" and "tip" elements to pass them through // the localization functions when you use them! -struct rdf_work_entity_t rdf_work_entities [] = { +struct rdf_work_entity_t rdf_work_entities[] = { // clang-format off { "title", N_("Title:"), "dc:title", RDF_CONTENT, N_("A name given to the resource"), RDF_FORMAT_LINE, RDF_EDIT_GENERIC, @@ -308,7 +306,6 @@ struct rdf_work_entity_t rdf_work_entities [] = { // clang-format on }; - // Simple start of C++-ification: class RDFImpl { @@ -317,22 +314,22 @@ public: * Some implementations do not put RDF stuff inside <metadata>, * so we need to check for it and add it if we don't see it. */ - static void ensureParentIsMetadata( SPDocument *doc, Inkscape::XML::Node *node ); + static void ensureParentIsMetadata(SPDocument *doc, Inkscape::XML::Node *node); - static Inkscape::XML::Node const *getRdfRootRepr( SPDocument const * doc ); - static Inkscape::XML::Node *ensureRdfRootRepr( SPDocument * doc ); + static Inkscape::XML::Node const *getRdfRootRepr(SPDocument const *doc); + static Inkscape::XML::Node *ensureRdfRootRepr(SPDocument *doc); - static Inkscape::XML::Node const *getXmlRepr( SPDocument const * doc, gchar const * name ); - static Inkscape::XML::Node *getXmlRepr( SPDocument * doc, gchar const * name ); - static Inkscape::XML::Node *ensureXmlRepr( SPDocument * doc, gchar const * name ); + static Inkscape::XML::Node const *getXmlRepr(SPDocument const *doc, gchar const *name); + static Inkscape::XML::Node *getXmlRepr(SPDocument *doc, gchar const *name); + static Inkscape::XML::Node *ensureXmlRepr(SPDocument *doc, gchar const *name); - static Inkscape::XML::Node const *getWorkRepr( SPDocument const * doc, gchar const * name ); - static Inkscape::XML::Node *ensureWorkRepr( SPDocument * doc, gchar const * name ); + static Inkscape::XML::Node const *getWorkRepr(SPDocument const *doc, gchar const *name); + static Inkscape::XML::Node *ensureWorkRepr(SPDocument *doc, gchar const *name); - static const gchar *getWorkEntity(SPDocument const * doc, struct rdf_work_entity_t & entity); - static unsigned int setWorkEntity(SPDocument * doc, struct rdf_work_entity_t & entity, gchar const * text); + static const gchar *getWorkEntity(SPDocument const *doc, struct rdf_work_entity_t &entity); + static unsigned int setWorkEntity(SPDocument *doc, struct rdf_work_entity_t &entity, gchar const *text); - static void setDefaults( SPDocument * doc ); + static void setDefaults(SPDocument *doc); /** * Pull the text out of an RDF entity, depends on how it's stored. @@ -342,15 +339,14 @@ public: * @param entity The desired RDF/Work entity * */ - static const gchar *getReprText( Inkscape::XML::Node const * repr, struct rdf_work_entity_t const & entity ); + static const gchar *getReprText(Inkscape::XML::Node const *repr, struct rdf_work_entity_t const &entity); - static unsigned int setReprText( Inkscape::XML::Node * repr, - struct rdf_work_entity_t const & entity, - gchar const * text ); + static unsigned int setReprText(Inkscape::XML::Node *repr, struct rdf_work_entity_t const &entity, + gchar const *text); static struct rdf_license_t *getLicense(SPDocument *document); - static void setLicense(SPDocument * doc, struct rdf_license_t const * license); + static void setLicense(SPDocument *doc, struct rdf_license_t const *license); }; /** @@ -360,13 +356,15 @@ public: * @param name The desired RDF/Work entity * */ -struct rdf_work_entity_t *rdf_find_entity(gchar const * name) +struct rdf_work_entity_t *rdf_find_entity(gchar const *name) { struct rdf_work_entity_t *entity; - for (entity=rdf_work_entities; entity->name; entity++) { - if (strcmp(entity->name,name)==0) break; + for (entity = rdf_work_entities; entity->name; entity++) { + if (strcmp(entity->name, name) == 0) + break; } - if (entity->name) return entity; + if (entity->name) + return entity; return nullptr; } @@ -488,30 +486,33 @@ rdf_string(struct rdf_t * rdf) } */ - -const gchar *RDFImpl::getReprText( Inkscape::XML::Node const * repr, struct rdf_work_entity_t const & entity ) +const gchar *RDFImpl::getReprText(Inkscape::XML::Node const *repr, struct rdf_work_entity_t const &entity) { - g_return_val_if_fail (repr != nullptr, NULL); - static gchar * bag = nullptr; - gchar * holder = nullptr; + g_return_val_if_fail(repr != nullptr, NULL); + static gchar *bag = nullptr; + gchar *holder = nullptr; - Inkscape::XML::Node const * temp = nullptr; + Inkscape::XML::Node const *temp = nullptr; switch (entity.datatype) { case RDF_CONTENT: temp = repr->firstChild(); - if ( temp == nullptr ) return nullptr; + if (temp == nullptr) + return nullptr; return temp->content(); case RDF_AGENT: - temp = sp_repr_lookup_name ( repr, "cc:Agent", 1 ); - if ( temp == nullptr ) return nullptr; + temp = sp_repr_lookup_name(repr, "cc:Agent", 1); + if (temp == nullptr) + return nullptr; - temp = sp_repr_lookup_name ( temp, "dc:title", 1 ); - if ( temp == nullptr ) return nullptr; + temp = sp_repr_lookup_name(temp, "dc:title", 1); + if (temp == nullptr) + return nullptr; temp = temp->firstChild(); - if ( temp == nullptr ) return nullptr; + if (temp == nullptr) + return nullptr; return temp->content(); @@ -523,30 +524,28 @@ const gchar *RDFImpl::getReprText( Inkscape::XML::Node const * repr, struct rdf_ case RDF_BAG: /* clear the static string. yucky. */ - if (bag) g_free(bag); + if (bag) + g_free(bag); bag = nullptr; - temp = sp_repr_lookup_name ( repr, "rdf:Bag", 1 ); - if ( temp == nullptr ) { + temp = sp_repr_lookup_name(repr, "rdf:Bag", 1); + if (temp == nullptr) { /* backwards compatible: read contents */ temp = repr->firstChild(); - if ( temp == nullptr ) return nullptr; + if (temp == nullptr) + return nullptr; return temp->content(); } - for ( temp = temp->firstChild() ; - temp ; - temp = temp->next() ) { - if (!strcmp(temp->name(),"rdf:li") && - temp->firstChild()) { - const gchar * str = temp->firstChild()->content(); + for (temp = temp->firstChild(); temp; temp = temp->next()) { + if (!strcmp(temp->name(), "rdf:li") && temp->firstChild()) { + const gchar *str = temp->firstChild()->content(); if (bag) { holder = bag; bag = g_strconcat(holder, ", ", str, NULL); g_free(holder); - } - else { + } else { bag = g_strdup(str); } } @@ -559,21 +558,19 @@ const gchar *RDFImpl::getReprText( Inkscape::XML::Node const * repr, struct rdf_ return nullptr; } -unsigned int RDFImpl::setReprText( Inkscape::XML::Node * repr, - struct rdf_work_entity_t const & entity, - gchar const * text ) +unsigned int RDFImpl::setReprText(Inkscape::XML::Node *repr, struct rdf_work_entity_t const &entity, gchar const *text) { - g_return_val_if_fail ( repr != nullptr, 0); - g_return_val_if_fail ( text != nullptr, 0); - gchar * str = nullptr; - gchar** strlist = nullptr; + g_return_val_if_fail(repr != nullptr, 0); + g_return_val_if_fail(text != nullptr, 0); + gchar *str = nullptr; + gchar **strlist = nullptr; int i; - Inkscape::XML::Node * temp=nullptr; - Inkscape::XML::Node * parent=repr; + Inkscape::XML::Node *temp = nullptr; + Inkscape::XML::Node *parent = repr; - Inkscape::XML::Document * xmldoc = parent->document(); - g_return_val_if_fail (xmldoc != nullptr, FALSE); + Inkscape::XML::Document *xmldoc = parent->document(); + g_return_val_if_fail(xmldoc != nullptr, FALSE); // set document's title element to the RDF title if (!strcmp(entity.name, "title")) { @@ -586,35 +583,34 @@ unsigned int RDFImpl::setReprText( Inkscape::XML::Node * repr, switch (entity.datatype) { case RDF_CONTENT: temp = parent->firstChild(); - if ( temp == nullptr ) { - temp = xmldoc->createTextNode( text ); - g_return_val_if_fail (temp != nullptr, FALSE); + if (temp == nullptr) { + temp = xmldoc->createTextNode(text); + g_return_val_if_fail(temp != nullptr, FALSE); parent->appendChild(temp); Inkscape::GC::release(temp); return TRUE; - } - else { + } else { temp->setContent(text); return TRUE; } case RDF_AGENT: - temp = sp_repr_lookup_name ( parent, "cc:Agent", 1 ); - if ( temp == nullptr ) { - temp = xmldoc->createElement ( "cc:Agent" ); - g_return_val_if_fail (temp != nullptr, FALSE); + temp = sp_repr_lookup_name(parent, "cc:Agent", 1); + if (temp == nullptr) { + temp = xmldoc->createElement("cc:Agent"); + g_return_val_if_fail(temp != nullptr, FALSE); parent->appendChild(temp); Inkscape::GC::release(temp); } parent = temp; - temp = sp_repr_lookup_name ( parent, "dc:title", 1 ); - if ( temp == nullptr ) { - temp = xmldoc->createElement ( "dc:title" ); - g_return_val_if_fail (temp != nullptr, FALSE); + temp = sp_repr_lookup_name(parent, "dc:title", 1); + if (temp == nullptr) { + temp = xmldoc->createElement("dc:title"); + g_return_val_if_fail(temp != nullptr, FALSE); parent->appendChild(temp); Inkscape::GC::release(temp); @@ -622,22 +618,21 @@ unsigned int RDFImpl::setReprText( Inkscape::XML::Node * repr, parent = temp; temp = parent->firstChild(); - if ( temp == nullptr ) { - temp = xmldoc->createTextNode( text ); - g_return_val_if_fail (temp != nullptr, FALSE); + if (temp == nullptr) { + temp = xmldoc->createTextNode(text); + g_return_val_if_fail(temp != nullptr, FALSE); parent->appendChild(temp); Inkscape::GC::release(temp); return TRUE; - } - else { + } else { temp->setContent(text); - return TRUE; + return TRUE; } case RDF_RESOURCE: - parent->setAttribute("rdf:resource", text ); + parent->setAttribute("rdf:resource", text); return true; case RDF_XML: @@ -645,15 +640,15 @@ unsigned int RDFImpl::setReprText( Inkscape::XML::Node * repr, case RDF_BAG: /* find/create the rdf:Bag item */ - temp = sp_repr_lookup_name ( parent, "rdf:Bag", 1 ); - if ( temp == nullptr ) { + temp = sp_repr_lookup_name(parent, "rdf:Bag", 1); + if (temp == nullptr) { /* backward compatibility: drop the dc:subject contents */ - while ( (temp = parent->firstChild()) ) { + while ((temp = parent->firstChild())) { parent->removeChild(temp); } - temp = xmldoc->createElement ( "rdf:Bag" ); - g_return_val_if_fail (temp != nullptr, FALSE); + temp = xmldoc->createElement("rdf:Bag"); + g_return_val_if_fail(temp != nullptr, FALSE); parent->appendChild(temp); Inkscape::GC::release(temp); @@ -661,27 +656,27 @@ unsigned int RDFImpl::setReprText( Inkscape::XML::Node * repr, parent = temp; /* toss all the old list items */ - while ( (temp = parent->firstChild()) ) { + while ((temp = parent->firstChild())) { parent->removeChild(temp); } /* chop our list up on commas */ - strlist = g_strsplit( text, ",", 0); + strlist = g_strsplit(text, ",", 0); for (i = 0; (str = strlist[i]); i++) { - temp = xmldoc->createElement ( "rdf:li" ); - g_return_val_if_fail (temp != nullptr, 0); + temp = xmldoc->createElement("rdf:li"); + g_return_val_if_fail(temp != nullptr, 0); parent->appendChild(temp); Inkscape::GC::release(temp); - Inkscape::XML::Node * child = xmldoc->createTextNode( g_strstrip(str) ); - g_return_val_if_fail (child != nullptr, 0); + Inkscape::XML::Node *child = xmldoc->createTextNode(g_strstrip(str)); + g_return_val_if_fail(child != nullptr, 0); temp->appendChild(child); Inkscape::GC::release(child); } - g_strfreev( strlist ); + g_strfreev(strlist); return 1; @@ -691,65 +686,65 @@ unsigned int RDFImpl::setReprText( Inkscape::XML::Node * repr, return 0; } -void RDFImpl::ensureParentIsMetadata( SPDocument *doc, Inkscape::XML::Node *node ) +void RDFImpl::ensureParentIsMetadata(SPDocument *doc, Inkscape::XML::Node *node) { - if ( !node ) { + if (!node) { g_critical("Null node passed to ensureParentIsMetadata()."); - } else if ( !node->parent() ) { - g_critical( "No parent node when verifying <metadata> placement." ); + } else if (!node->parent()) { + g_critical("No parent node when verifying <metadata> placement."); } else { - Inkscape::XML::Node * currentParent = node->parent(); - if ( strcmp( currentParent->name(), XML_TAG_NAME_METADATA ) != 0 ) { - Inkscape::XML::Node * metadata = doc->getReprDoc()->createElement( XML_TAG_NAME_METADATA ); - if ( !metadata ) { + Inkscape::XML::Node *currentParent = node->parent(); + if (strcmp(currentParent->name(), XML_TAG_NAME_METADATA) != 0) { + Inkscape::XML::Node *metadata = doc->getReprDoc()->createElement(XML_TAG_NAME_METADATA); + if (!metadata) { g_critical("Unable to create metadata element."); } else { // attach the metadata node - currentParent->appendChild( metadata ); - Inkscape::GC::release( metadata ); + currentParent->appendChild(metadata); + Inkscape::GC::release(metadata); // move the node into it - Inkscape::GC::anchor( node ); - sp_repr_unparent( node ); - metadata->appendChild( node ); - Inkscape::GC::release( node ); + Inkscape::GC::anchor(node); + sp_repr_unparent(node); + metadata->appendChild(node); + Inkscape::GC::release(node); } } } } -Inkscape::XML::Node const *RDFImpl::getRdfRootRepr( SPDocument const * doc ) +Inkscape::XML::Node const *RDFImpl::getRdfRootRepr(SPDocument const *doc) { Inkscape::XML::Node const *rdf = nullptr; - if ( !doc ) { + if (!doc) { g_critical("Null doc passed to getRdfRootRepr()"); - } else if ( !doc->getReprDoc() ) { + } else if (!doc->getReprDoc()) { g_critical("XML doc is null."); } else { - rdf = sp_repr_lookup_name( doc->getReprDoc(), XML_TAG_NAME_RDF ); + rdf = sp_repr_lookup_name(doc->getReprDoc(), XML_TAG_NAME_RDF); } return rdf; } -Inkscape::XML::Node *RDFImpl::ensureRdfRootRepr( SPDocument * doc ) +Inkscape::XML::Node *RDFImpl::ensureRdfRootRepr(SPDocument *doc) { Inkscape::XML::Node *rdf = nullptr; - if ( !doc ) { + if (!doc) { g_critical("Null doc passed to ensureRdfRootRepr()"); - } else if ( !doc->getReprDoc() ) { + } else if (!doc->getReprDoc()) { g_critical("XML doc is null."); } else { - rdf = sp_repr_lookup_name( doc->getReprDoc(), XML_TAG_NAME_RDF ); - if ( !rdf ) { - Inkscape::XML::Node * svg = sp_repr_lookup_name( doc->getReprRoot(), XML_TAG_NAME_SVG ); - if ( !svg ) { + rdf = sp_repr_lookup_name(doc->getReprDoc(), XML_TAG_NAME_RDF); + if (!rdf) { + Inkscape::XML::Node *svg = sp_repr_lookup_name(doc->getReprRoot(), XML_TAG_NAME_SVG); + if (!svg) { g_critical("Unable to locate svg element."); } else { - Inkscape::XML::Node * parent = sp_repr_lookup_name( svg, XML_TAG_NAME_METADATA, 1); - if ( parent == nullptr ) { - parent = doc->getReprDoc()->createElement( XML_TAG_NAME_METADATA ); - if ( !parent ) { + Inkscape::XML::Node *parent = sp_repr_lookup_name(svg, XML_TAG_NAME_METADATA, 1); + if (parent == nullptr) { + parent = doc->getReprDoc()->createElement(XML_TAG_NAME_METADATA); + if (!parent) { g_critical("Unable to create metadata element"); } else { svg->appendChild(parent); @@ -757,11 +752,11 @@ Inkscape::XML::Node *RDFImpl::ensureRdfRootRepr( SPDocument * doc ) } } - if ( parent && !parent->document() ) { + if (parent && !parent->document()) { g_critical("Parent has no document"); - } else if ( parent ) { - rdf = parent->document()->createElement( XML_TAG_NAME_RDF ); - if ( !rdf ) { + } else if (parent) { + rdf = parent->document()->createElement(XML_TAG_NAME_RDF); + if (!rdf) { g_critical("Unable to create root RDF element."); } else { parent->appendChild(rdf); @@ -772,57 +767,57 @@ Inkscape::XML::Node *RDFImpl::ensureRdfRootRepr( SPDocument * doc ) } } - if ( rdf ) { - ensureParentIsMetadata( doc, rdf ); + if (rdf) { + ensureParentIsMetadata(doc, rdf); } return rdf; } -Inkscape::XML::Node const *RDFImpl::getXmlRepr( SPDocument const * doc, gchar const * name ) +Inkscape::XML::Node const *RDFImpl::getXmlRepr(SPDocument const *doc, gchar const *name) { - Inkscape::XML::Node const * xml = nullptr; - if ( !doc ) { + Inkscape::XML::Node const *xml = nullptr; + if (!doc) { g_critical("Null doc passed to getXmlRepr()"); - } else if ( !doc->getReprDoc() ) { + } else if (!doc->getReprDoc()) { g_critical("XML doc is null."); } else if (!name) { g_critical("Null name passed to getXmlRepr()"); } else { - Inkscape::XML::Node const * rdf = getRdfRootRepr( doc ); - if ( rdf ) { - xml = sp_repr_lookup_name( rdf, name ); + Inkscape::XML::Node const *rdf = getRdfRootRepr(doc); + if (rdf) { + xml = sp_repr_lookup_name(rdf, name); } } return xml; } -Inkscape::XML::Node *RDFImpl::getXmlRepr( SPDocument * doc, gchar const * name ) +Inkscape::XML::Node *RDFImpl::getXmlRepr(SPDocument *doc, gchar const *name) { - Inkscape::XML::Node const *xml = getXmlRepr( const_cast<SPDocument const *>(doc), name ); + Inkscape::XML::Node const *xml = getXmlRepr(const_cast<SPDocument const *>(doc), name); return const_cast<Inkscape::XML::Node *>(xml); } -Inkscape::XML::Node *RDFImpl::ensureXmlRepr( SPDocument * doc, gchar const * name ) +Inkscape::XML::Node *RDFImpl::ensureXmlRepr(SPDocument *doc, gchar const *name) { - Inkscape::XML::Node * xml = nullptr; - if ( !doc ) { + Inkscape::XML::Node *xml = nullptr; + if (!doc) { g_critical("Null doc passed to ensureXmlRepr()"); - } else if ( !doc->getReprDoc() ) { + } else if (!doc->getReprDoc()) { g_critical("XML doc is null."); } else if (!name) { g_critical("Null name passed to ensureXmlRepr()"); } else { - Inkscape::XML::Node * rdf = ensureRdfRootRepr( doc ); - if ( rdf ) { - xml = sp_repr_lookup_name( rdf, name ); - if ( !xml ) { - xml = doc->getReprDoc()->createElement( name ); - if ( !xml ) { + Inkscape::XML::Node *rdf = ensureRdfRootRepr(doc); + if (rdf) { + xml = sp_repr_lookup_name(rdf, name); + if (!xml) { + xml = doc->getReprDoc()->createElement(name); + if (!xml) { g_critical("Unable to create xml element <%s>.", name); } else { - xml->setAttribute("rdf:about", "" ); + xml->setAttribute("rdf:about", ""); rdf->appendChild(xml); Inkscape::GC::release(xml); @@ -833,41 +828,41 @@ Inkscape::XML::Node *RDFImpl::ensureXmlRepr( SPDocument * doc, gchar const * nam return xml; } -Inkscape::XML::Node const *RDFImpl::getWorkRepr( SPDocument const * doc, gchar const * name ) +Inkscape::XML::Node const *RDFImpl::getWorkRepr(SPDocument const *doc, gchar const *name) { - Inkscape::XML::Node const * item = nullptr; - if ( !doc ) { + Inkscape::XML::Node const *item = nullptr; + if (!doc) { g_critical("Null doc passed to getWorkRepr()"); - } else if ( !doc->getReprDoc() ) { + } else if (!doc->getReprDoc()) { g_critical("XML doc is null."); } else if (!name) { g_critical("Null name passed to getWorkRepr()"); } else { - Inkscape::XML::Node const* work = getXmlRepr( doc, XML_TAG_NAME_WORK ); - if ( work ) { - item = sp_repr_lookup_name( work, name, 1 ); + Inkscape::XML::Node const *work = getXmlRepr(doc, XML_TAG_NAME_WORK); + if (work) { + item = sp_repr_lookup_name(work, name, 1); } } return item; } -Inkscape::XML::Node *RDFImpl::ensureWorkRepr( SPDocument * doc, gchar const * name ) +Inkscape::XML::Node *RDFImpl::ensureWorkRepr(SPDocument *doc, gchar const *name) { - Inkscape::XML::Node * item = nullptr; - if ( !doc ) { + Inkscape::XML::Node *item = nullptr; + if (!doc) { g_critical("Null doc passed to ensureWorkRepr()"); - } else if ( !doc->getReprDoc() ) { + } else if (!doc->getReprDoc()) { g_critical("XML doc is null."); } else if (!name) { g_critical("Null name passed to ensureWorkRepr()"); } else { - Inkscape::XML::Node * work = ensureXmlRepr( doc, XML_TAG_NAME_WORK ); - if ( work ) { - item = sp_repr_lookup_name( work, name, 1 ); - if ( !item ) { - //printf("missing XML '%s'\n",name); - item = doc->getReprDoc()->createElement( name ); - if ( !item ) { + Inkscape::XML::Node *work = ensureXmlRepr(doc, XML_TAG_NAME_WORK); + if (work) { + item = sp_repr_lookup_name(work, name, 1); + if (!item) { + // printf("missing XML '%s'\n",name); + item = doc->getReprDoc()->createElement(name); + if (!item) { g_critical("Unable to create xml element <%s>", name); } else { work->appendChild(item); @@ -879,30 +874,29 @@ Inkscape::XML::Node *RDFImpl::ensureWorkRepr( SPDocument * doc, gchar const * na return item; } - // Public API: -const gchar *rdf_get_work_entity(SPDocument const * doc, struct rdf_work_entity_t * entity) +const gchar *rdf_get_work_entity(SPDocument const *doc, struct rdf_work_entity_t *entity) { const gchar *result = nullptr; - if ( !doc ) { + if (!doc) { g_critical("Null doc passed to rdf_get_work_entity()"); - } else if ( entity ) { - //g_message("want '%s'\n",entity->title); + } else if (entity) { + // g_message("want '%s'\n",entity->title); - result = RDFImpl::getWorkEntity( doc, *entity ); + result = RDFImpl::getWorkEntity(doc, *entity); - //g_message("found '%s' == '%s'\n", entity->title, result ); + // g_message("found '%s' == '%s'\n", entity->title, result ); } return result; } -const gchar *RDFImpl::getWorkEntity(SPDocument const * doc, struct rdf_work_entity_t & entity) +const gchar *RDFImpl::getWorkEntity(SPDocument const *doc, struct rdf_work_entity_t &entity) { gchar const *result = nullptr; - Inkscape::XML::Node const * item = getWorkRepr( doc, entity.tag ); - if ( item ) { - result = getReprText( item, entity ); + Inkscape::XML::Node const *item = getWorkRepr(doc, entity.tag); + if (item) { + result = getReprText(item, entity); // TODO note that this is the location that used to set the title if needed. Ensure code it not required. } @@ -910,20 +904,19 @@ const gchar *RDFImpl::getWorkEntity(SPDocument const * doc, struct rdf_work_enti } // Public API: -unsigned int rdf_set_work_entity(SPDocument * doc, struct rdf_work_entity_t * entity, - const gchar * text) +unsigned int rdf_set_work_entity(SPDocument *doc, struct rdf_work_entity_t *entity, const gchar *text) { unsigned int result = 0; - if ( !doc ) { + if (!doc) { g_critical("Null doc passed to rdf_set_work_entity()"); - } else if ( entity ) { - result = RDFImpl::setWorkEntity( doc, *entity, text ); + } else if (entity) { + result = RDFImpl::setWorkEntity(doc, *entity, text); } return result; } -unsigned int RDFImpl::setWorkEntity(SPDocument * doc, struct rdf_work_entity_t & entity, const gchar * text) +unsigned int RDFImpl::setWorkEntity(SPDocument *doc, struct rdf_work_entity_t &entity, const gchar *text) { int result = 0; if (!text || !text[0]) { @@ -944,63 +937,56 @@ unsigned int RDFImpl::setWorkEntity(SPDocument * doc, struct rdf_work_entity_t & text); */ - Inkscape::XML::Node * item = ensureWorkRepr( doc, entity.tag ); - if ( !item ) { + Inkscape::XML::Node *item = ensureWorkRepr(doc, entity.tag); + if (!item) { g_critical("Unable to get work element"); } else { - result = setReprText( item, entity, text ); + result = setReprText(item, entity, text); } return result; } - #undef DEBUG_MATCH -static bool -rdf_match_license(Inkscape::XML::Node const *repr, struct rdf_license_t const *license) +static bool rdf_match_license(Inkscape::XML::Node const *repr, struct rdf_license_t const *license) { - g_assert ( repr != nullptr ); - g_assert ( license != nullptr ); + g_assert(repr != nullptr); + g_assert(license != nullptr); - bool result=TRUE; + bool result = TRUE; #ifdef DEBUG_MATCH - printf("checking against '%s'\n",license->name); + printf("checking against '%s'\n", license->name); #endif int count = 0; - for (struct rdf_double_t const *details = license->details; - details->name; details++ ) { + for (struct rdf_double_t const *details = license->details; details->name; details++) { count++; } - bool * matched = (bool*)calloc(count,sizeof(bool)); - - for (Inkscape::XML::Node const *current = repr->firstChild(); - current; - current = current->next() ) { + bool *matched = (bool *)calloc(count, sizeof(bool)); - gchar const * attr = current->attribute("rdf:resource"); - if ( attr == nullptr ) continue; + for (Inkscape::XML::Node const *current = repr->firstChild(); current; current = current->next()) { + gchar const *attr = current->attribute("rdf:resource"); + if (attr == nullptr) + continue; #ifdef DEBUG_MATCH printf("\texamining '%s' => '%s'\n", current->name(), attr); #endif - bool found_match=FALSE; - for (int i=0; i<count; i++) { + bool found_match = FALSE; + for (int i = 0; i < count; i++) { // skip already matched items - if (matched[i]) continue; + if (matched[i]) + continue; #ifdef DEBUG_MATCH printf("\t\t'%s' vs '%s'\n", current->name(), license->details[i].name); printf("\t\t'%s' vs '%s'\n", attr, license->details[i].resource); #endif - if (!strcmp( current->name(), - license->details[i].name ) && - !strcmp( attr, - license->details[i].resource )) { - matched[i]=TRUE; - found_match=TRUE; + if (!strcmp(current->name(), license->details[i].name) && !strcmp(attr, license->details[i].resource)) { + matched[i] = TRUE; + found_match = TRUE; #ifdef DEBUG_MATCH printf("\t\tgood!\n"); #endif @@ -1010,20 +996,21 @@ rdf_match_license(Inkscape::XML::Node const *repr, struct rdf_license_t const *l if (!found_match) { // if we checked each known item of the license // and didn't find it, we must abort - result=FALSE; + result = FALSE; #ifdef DEBUG_MATCH - printf("\t\tno '%s' element matched XML (bong)!\n",license->name); + printf("\t\tno '%s' element matched XML (bong)!\n", license->name); #endif break; } } #ifdef DEBUG_MATCH - if (result) printf("\t\tall XML found matching elements!\n"); + if (result) + printf("\t\tall XML found matching elements!\n"); #endif - for (int i=0; result && i<count; i++) { + for (int i = 0; result && i < count; i++) { // scan looking for an unmatched item - if (matched[i]==0) { - result=FALSE; + if (matched[i] == 0) { + result = FALSE; #ifdef DEBUG_MATCH printf("\t\tnot all '%s' elements used to match (bong)!\n", license->name); #endif @@ -1031,13 +1018,14 @@ rdf_match_license(Inkscape::XML::Node const *repr, struct rdf_license_t const *l } #ifdef DEBUG_MATCH - printf("\t\tall '%s' elements used to match!\n",license->name); + printf("\t\tall '%s' elements used to match!\n", license->name); #endif free(matched); #ifdef DEBUG_MATCH - if (result) printf("matched '%s'\n",license->name); + if (result) + printf("matched '%s'\n", license->name); #endif return result; } @@ -1061,10 +1049,10 @@ struct rdf_license_t *RDFImpl::getLicense(SPDocument *document) } const gchar *uri = getWorkEntity(document, *entity); - struct rdf_license_t * license_by_uri = nullptr; + struct rdf_license_t *license_by_uri = nullptr; if (uri != nullptr) { - for (struct rdf_license_t * license = rdf_licenses; license->name; license++) { + for (struct rdf_license_t *license = rdf_licenses; license->name; license++) { if (g_strcmp0(uri, license->uri) == 0) { license_by_uri = license; break; @@ -1079,12 +1067,12 @@ struct rdf_license_t *RDFImpl::getLicense(SPDocument *document) // sp_metadata_build() then the right place to put the call to sort out // any RDF mess? - struct rdf_license_t * license_by_properties = nullptr; + struct rdf_license_t *license_by_properties = nullptr; - Inkscape::XML::Node const *repr = getXmlRepr( document, XML_TAG_NAME_LICENSE ); + Inkscape::XML::Node const *repr = getXmlRepr(document, XML_TAG_NAME_LICENSE); if (repr) { - for ( struct rdf_license_t * license = rdf_licenses; license->name; license++ ) { - if ( rdf_match_license( repr, license ) ) { + for (struct rdf_license_t *license = rdf_licenses; license->name; license++) { + if (rdf_match_license(repr, license)) { license_by_properties = license; break; } @@ -1098,12 +1086,8 @@ struct rdf_license_t *RDFImpl::getLicense(SPDocument *document) g_warning("Mismatch between %s and %s metadata:\n" "%s value URI: %s (using this one!)\n" "%s derived URI: %s", - XML_TAG_NAME_LICENSE_PROP, - XML_TAG_NAME_LICENSE, - XML_TAG_NAME_LICENSE_PROP, - license_by_uri->uri, - XML_TAG_NAME_LICENSE, - license_by_properties->uri); + XML_TAG_NAME_LICENSE_PROP, XML_TAG_NAME_LICENSE, XML_TAG_NAME_LICENSE_PROP, license_by_uri->uri, + XML_TAG_NAME_LICENSE, license_by_properties->uri); } // Reset license structure to match so the document is consistent @@ -1111,19 +1095,16 @@ struct rdf_license_t *RDFImpl::getLicense(SPDocument *document) setLicense(document, license_by_uri); return license_by_uri; - } - else if (license_by_uri != nullptr) { + } else if (license_by_uri != nullptr) { // Only cc:license property, set structure for backward compatibility setLicense(document, license_by_uri); return license_by_uri; - } - else if (license_by_properties != nullptr) { + } else if (license_by_properties != nullptr) { // Only cc:License structure // TODO: this could be a user-visible warning too - g_warning("No %s metadata found, derived license URI from %s: %s", - XML_TAG_NAME_LICENSE_PROP, XML_TAG_NAME_LICENSE, - license_by_properties->uri); + g_warning("No %s metadata found, derived license URI from %s: %s", XML_TAG_NAME_LICENSE_PROP, + XML_TAG_NAME_LICENSE, license_by_properties->uri); // Set license property to match setWorkEntity(document, *entity, license_by_properties->uri); @@ -1136,12 +1117,12 @@ struct rdf_license_t *RDFImpl::getLicense(SPDocument *document) } // Public API: -void rdf_set_license(SPDocument * doc, struct rdf_license_t const * license) +void rdf_set_license(SPDocument *doc, struct rdf_license_t const *license) { - RDFImpl::setLicense( doc, license ); + RDFImpl::setLicense(doc, license); } -void RDFImpl::setLicense(SPDocument * doc, struct rdf_license_t const * license) +void RDFImpl::setLicense(SPDocument *doc, struct rdf_license_t const *license) { // When basing license check on only the license URI (see fix for // https://bugs.launchpad.net/inkscape/+bug/372427 above) we should @@ -1149,27 +1130,27 @@ void RDFImpl::setLicense(SPDocument * doc, struct rdf_license_t const * license) // compatibility with older versions. // drop old license section - Inkscape::XML::Node * repr = getXmlRepr( doc, XML_TAG_NAME_LICENSE ); + Inkscape::XML::Node *repr = getXmlRepr(doc, XML_TAG_NAME_LICENSE); if (repr) { sp_repr_unparent(repr); } - if ( !license ) { + if (!license) { // All done - } else if ( !doc->getReprDoc() ) { + } else if (!doc->getReprDoc()) { g_critical("XML doc is null."); } else { // build new license section - repr = ensureXmlRepr( doc, XML_TAG_NAME_LICENSE ); - g_assert( repr ); + repr = ensureXmlRepr(doc, XML_TAG_NAME_LICENSE); + g_assert(repr); - repr->setAttribute("rdf:about", license->uri ); + repr->setAttribute("rdf:about", license->uri); - for (struct rdf_double_t const * detail = license->details; detail->name; detail++) { - Inkscape::XML::Node * child = doc->getReprDoc()->createElement( detail->name ); - g_assert ( child != nullptr ); + for (struct rdf_double_t const *detail = license->details; detail->name; detail++) { + Inkscape::XML::Node *child = doc->getReprDoc()->createElement(detail->name); + g_assert(child != nullptr); - child->setAttribute("rdf:resource", detail->resource ); + child->setAttribute("rdf:resource", detail->resource); repr->appendChild(child); Inkscape::GC::release(child); } @@ -1177,15 +1158,14 @@ void RDFImpl::setLicense(SPDocument * doc, struct rdf_license_t const * license) } // Public API: -void rdf_set_defaults( SPDocument * doc ) +void rdf_set_defaults(SPDocument *doc) { - RDFImpl::setDefaults( doc ); - + RDFImpl::setDefaults(doc); } -void RDFImpl::setDefaults( SPDocument * doc ) +void RDFImpl::setDefaults(SPDocument *doc) { - g_assert( doc != nullptr ); + g_assert(doc != nullptr); // Used to add hard coded defaults here } @@ -1204,18 +1184,17 @@ void rdf_add_from_preferences(SPDocument *doc) // If there is already some metadata in the doc (from a template) don't add default metadata for (struct rdf_work_entity_t *entity = rdf_work_entities; entity && entity->name; entity++) { - if ( entity->editable == RDF_EDIT_GENERIC && - rdf_get_work_entity (doc, entity)) { + if (entity->editable == RDF_EDIT_GENERIC && rdf_get_work_entity(doc, entity)) { return; } } // Put the metadata from user preferences into the doc for (struct rdf_work_entity_t *entity = rdf_work_entities; entity && entity->name; entity++) { - if ( entity->editable == RDF_EDIT_GENERIC ) { + if (entity->editable == RDF_EDIT_GENERIC) { Glib::ustring text = prefs->getString(PREFS_METADATA + Glib::ustring(entity->name)); if (text.length() > 0) { - rdf_set_work_entity (doc, entity, text.c_str()); + rdf_set_work_entity(doc, entity, text.c_str()); } } } diff --git a/src/rdf.h b/src/rdf.h index f5abda0a32a6e3842622143a88f697bdd6a72bbd..2b5e190f2d212d1700d34eb22260a23e3563246d 100644 --- a/src/rdf.h +++ b/src/rdf.h @@ -13,15 +13,17 @@ #define SEEN_RDF_H #include <glibmm/i18n.h> + #include "document.h" -#define PREFS_METADATA "/metadata/rdf/" +#define PREFS_METADATA "/metadata/rdf/" // yeah, it's not a triple yet... /** * \brief Holds license name/resource doubles for rdf_license_t entries */ -struct rdf_double_t { +struct rdf_double_t +{ char const *name; char const *resource; }; @@ -29,19 +31,21 @@ struct rdf_double_t { /** * \brief Holds license name and RDF information */ -struct rdf_license_t { - char const *name; /* localized name of this license */ - char const *uri; /* URL for the RDF/Work/license element */ +struct rdf_license_t +{ + char const *name; /* localized name of this license */ + char const *uri; /* URL for the RDF/Work/license element */ struct rdf_double_t *details; /* the license details */ -// char const *fragment; /* XML contents for the RDF/License tag */ + // char const *fragment; /* XML contents for the RDF/License tag */ }; -extern rdf_license_t rdf_licenses []; +extern rdf_license_t rdf_licenses[]; /** * \brief Describes how a given RDF entity is stored in XML */ -enum RDFType { +enum RDFType +{ RDF_CONTENT, // direct between-XML-tags content RDF_AGENT, // requires the "Agent" hierarchy before doing content RDF_RESOURCE, // stored in "rdf:resource" element @@ -52,89 +56,90 @@ enum RDFType { /** * \brief Describes how a given RDF entity should be edited */ -enum RDF_Format { - RDF_FORMAT_LINE, // uses single line data (GtkEntry) - RDF_FORMAT_MULTILINE, // uses multiline data (GtkTextView) - RDF_FORMAT_SPECIAL // uses some other edit methods +enum RDF_Format +{ + RDF_FORMAT_LINE, // uses single line data (GtkEntry) + RDF_FORMAT_MULTILINE, // uses multiline data (GtkTextView) + RDF_FORMAT_SPECIAL // uses some other edit methods }; -enum RDF_Editable { - RDF_EDIT_GENERIC, // editable via generic widgets - RDF_EDIT_SPECIAL, // special widgets are needed - RDF_EDIT_HARDCODED // isn't editable +enum RDF_Editable +{ + RDF_EDIT_GENERIC, // editable via generic widgets + RDF_EDIT_SPECIAL, // special widgets are needed + RDF_EDIT_HARDCODED // isn't editable }; /** * \brief Holds known RDF/Work tags */ -struct rdf_work_entity_t { - char const *name; /* unique name of this entity for internal reference */ - char const *title; /* localized title of this entity for data entry */ - char const *tag; /* namespace tag for the RDF/Work element */ - RDFType datatype; /* how to extract/inject the RDF information */ - char const *tip; /* tool tip to explain the meaning of the entity */ - RDF_Format format; /* in what format is this data edited? */ - RDF_Editable editable;/* in what way is the data editable? */ +struct rdf_work_entity_t +{ + char const *name; /* unique name of this entity for internal reference */ + char const *title; /* localized title of this entity for data entry */ + char const *tag; /* namespace tag for the RDF/Work element */ + RDFType datatype; /* how to extract/inject the RDF information */ + char const *tip; /* tool tip to explain the meaning of the entity */ + RDF_Format format; /* in what format is this data edited? */ + RDF_Editable editable; /* in what way is the data editable? */ }; -extern rdf_work_entity_t rdf_work_entities []; +extern rdf_work_entity_t rdf_work_entities[]; /** * \brief Generic collection of RDF information for the RDF debug function */ -struct rdf_t { - char* work_title; - char* work_date; - char* work_creator; - char* work_owner; - char* work_publisher; - char* work_type; - char* work_source; - char* work_subject; - char* work_description; - struct rdf_license_t* license; +struct rdf_t +{ + char *work_title; + char *work_date; + char *work_creator; + char *work_owner; + char *work_publisher; + char *work_type; + char *work_source; + char *work_subject; + char *work_description; + struct rdf_license_t *license; }; -struct rdf_work_entity_t * rdf_find_entity(char const * name); +struct rdf_work_entity_t *rdf_find_entity(char const *name); /** * \brief Retrieves a known RDF/Work entity's contents from the document XML by name * \return A pointer to the entity's static contents as a string, or NULL if no entity exists * \param entity The desired RDF/Work entity - * + * */ -const gchar * rdf_get_work_entity(SPDocument const * doc, - struct rdf_work_entity_t * entity); +const gchar *rdf_get_work_entity(SPDocument const *doc, struct rdf_work_entity_t *entity); /** * \brief Stores a string into a named RDF/Work entity in the document XML * \param entity The desired RDF/Work entity to replace * \param string The string to replace the entity contents with - * + * */ -unsigned int rdf_set_work_entity(SPDocument * doc, - struct rdf_work_entity_t * entity, - const char * text); +unsigned int rdf_set_work_entity(SPDocument *doc, struct rdf_work_entity_t *entity, const char *text); /** * \brief Attempts to match and retrieve a known RDF/License from the document XML * \return A pointer to the static RDF license structure - * + * */ -struct rdf_license_t * rdf_get_license(SPDocument *doc); +struct rdf_license_t *rdf_get_license(SPDocument *doc); /** * \brief Stores an RDF/License XML in the document XML * \param document Which document to update - * \param license The desired RDF/License structure to store; NULL drops old license, so can be used for proprietary license. - * + * \param license The desired RDF/License structure to store; NULL drops old license, so can be used for + * proprietary license. + * */ -void rdf_set_license(SPDocument * doc, - struct rdf_license_t const * license); +void rdf_set_license(SPDocument *doc, struct rdf_license_t const *license); -void rdf_set_defaults ( SPDocument * doc ); +void rdf_set_defaults(SPDocument *doc); -void rdf_add_from_preferences ( SPDocument *doc ); +void rdf_add_from_preferences(SPDocument *doc); #endif // SEEN_RDF_H diff --git a/src/remove-last.h b/src/remove-last.h index b67721d351efc7e93955c85ed11fc9e1f31de42a..e5a6434bab28a8f75262b5bd150b87787d46b435 100644 --- a/src/remove-last.h +++ b/src/remove-last.h @@ -11,21 +11,19 @@ #define __REMOVE_LAST_H__ #include <algorithm> -#include <vector> #include <glib.h> +#include <vector> -template<class T> +template <class T> inline void remove_last(std::vector<T> &seq, T const &elem) { typename std::vector<T>::reverse_iterator i(find(seq.rbegin(), seq.rend(), elem)); - g_assert( i != seq.rend() ); + g_assert(i != seq.rend()); seq.erase(i.base()); } - #endif /* !__REMOVE_LAST_H__ */ - /* Local Variables: mode:c++ diff --git a/src/removeoverlap.cpp b/src/removeoverlap.cpp index 8b3064bd98933ae7626685ba96d5a12e92c15e03..e29a5cef088d783751ed56261e748236b02cd48b 100644 --- a/src/removeoverlap.cpp +++ b/src/removeoverlap.cpp @@ -12,47 +12,53 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <utility> +#include "removeoverlap.h" #include <2geom/transforms.h> - -#include "removeoverlap.h" +#include <utility> #include "libvpsc/rectangle.h" - -#include "object/sp-item.h" #include "object/sp-item-transform.h" - +#include "object/sp-item.h" using vpsc::Rectangle; namespace { -struct Record { - SPItem * item; +struct Record +{ + SPItem *item; Geom::Point midpoint; - Rectangle * vspc_rect; + Rectangle *vspc_rect; - Record() : item(nullptr), vspc_rect(nullptr) {} - Record(SPItem * i, Geom::Point m, Rectangle * r) - : item(i), midpoint(m), vspc_rect(r) {} + Record() + : item(nullptr) + , vspc_rect(nullptr) + {} + Record(SPItem *i, Geom::Point m, Rectangle *r) + : item(i) + , midpoint(m) + , vspc_rect(r) + {} }; -} +} // namespace /** -* Takes a list of inkscape items and moves them as little as possible -* such that rectangular bounding boxes are separated by at least xGap -* horizontally and yGap vertically -*/ -void removeoverlap(std::vector<SPItem*> const & items, double const xGap, double const yGap) { - std::vector<SPItem*> selected = items; + * Takes a list of inkscape items and moves them as little as possible + * such that rectangular bounding boxes are separated by at least xGap + * horizontally and yGap vertically + */ +void removeoverlap(std::vector<SPItem *> const &items, double const xGap, double const yGap) +{ + std::vector<SPItem *> selected = items; std::vector<Record> records; - std::vector<Rectangle*> rs; + std::vector<Rectangle *> rs; Geom::Point const gap(xGap, yGap); - for (SPItem * item: selected) { - using Geom::X; using Geom::Y; + for (SPItem *item : selected) { + using Geom::X; + using Geom::Y; Geom::OptRect item_box(item->desktopVisualBounds()); if (item_box) { Geom::Point min(item_box->min() - .5 * gap); @@ -68,7 +74,7 @@ void removeoverlap(std::vector<SPItem*> const & items, double const xGap, double if (max[Y] < min[Y]) { min[Y] = max[Y] = (min[Y] + max[Y]) / 2.; } - Rectangle * vspc_rect = new Rectangle(min[X], max[X], min[Y], max[Y]); + Rectangle *vspc_rect = new Rectangle(min[X], max[X], min[Y], max[Y]); records.emplace_back(item, item_box->midpoint(), vspc_rect); rs.push_back(vspc_rect); } @@ -76,7 +82,7 @@ void removeoverlap(std::vector<SPItem*> const & items, double const xGap, double if (!rs.empty()) { removeoverlaps(rs); } - for (Record & rec: records) { + for (Record &rec : records) { Geom::Point const curr = rec.midpoint; Geom::Point const dest(rec.vspc_rect->getCentreX(), rec.vspc_rect->getCentreY()); rec.item->move_rel(Geom::Translate(dest - curr)); diff --git a/src/removeoverlap.h b/src/removeoverlap.h index 619b091a540e77accecd735d0e7e70def109d405..6e11d5dfcca679282b35c3d823a7b8cf94ccf46b 100644 --- a/src/removeoverlap.h +++ b/src/removeoverlap.h @@ -18,6 +18,6 @@ class SPItem; -void removeoverlap(std::vector<SPItem*> const &items, double xGap, double yGap); +void removeoverlap(std::vector<SPItem *> const &items, double xGap, double yGap); #endif // SEEN_REMOVEOVERLAP_H diff --git a/src/rubberband.cpp b/src/rubberband.cpp index 3f37e58fc4100a9816500895b270bece5a77d2d3..cac187f03bb3b673bec9c1ee8fa1a015a29a05eb 100644 --- a/src/rubberband.cpp +++ b/src/rubberband.cpp @@ -11,19 +11,21 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "display/sodipodi-ctrlrect.h" -#include "desktop.h" - #include "rubberband.h" + +#include "desktop.h" #include "display/canvas-bpath.h" #include "display/curve.h" - +#include "display/sodipodi-ctrlrect.h" #include "ui/widget/canvas.h" // Forced redraws Inkscape::Rubberband *Inkscape::Rubberband::_instance = nullptr; Inkscape::Rubberband::Rubberband(SPDesktop *dt) - : _desktop(dt), _rect(nullptr), _touchpath(nullptr), _started(false) + : _desktop(dt) + , _rect(nullptr) + , _touchpath(nullptr) + , _started(false) { _points.clear(); _mode = RUBBERBAND_MODE_RECT; @@ -44,7 +46,6 @@ void Inkscape::Rubberband::delete_canvas_items() } } - void Inkscape::Rubberband::start(SPDesktop *d, Geom::Point const &p) { _points.clear(); @@ -76,7 +77,7 @@ void Inkscape::Rubberband::stop() void Inkscape::Rubberband::move(Geom::Point const &p) { - if (!_started) + if (!_started) return; _end = p; @@ -87,11 +88,11 @@ void Inkscape::Rubberband::move(Geom::Point const &p) // we want the points to be at most 0.5 screen pixels apart, // so that we don't lose anything small; // if they are farther apart, we interpolate more points - if (!_points.empty() && Geom::L2(next-_points.back()) > 0.5) { + if (!_points.empty() && Geom::L2(next - _points.back()) > 0.5) { Geom::Point prev = _points.back(); - int subdiv = 2 * (int) round(Geom::L2(next-prev) + 0.5); - for (int i = 1; i <= subdiv; i ++) { - _points.push_back(prev + ((double)i/subdiv) * (next - prev)); + int subdiv = 2 * (int)round(Geom::L2(next - prev) + 0.5); + for (int i = 1; i <= subdiv; i++) { + _points.push_back(prev + ((double)i / subdiv) * (next - prev)); } } else { _points.push_back(next); @@ -112,7 +113,8 @@ void Inkscape::Rubberband::move(Geom::Point const &p) } else if (_mode == RUBBERBAND_MODE_TOUCHPATH) { if (_touchpath == nullptr) { _touchpath = sp_canvas_bpath_new(_desktop->getSketch(), nullptr); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(_touchpath), 0xff0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(_touchpath), 0xff0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, + SP_STROKE_LINECAP_BUTT); sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(_touchpath), 0, SP_WIND_RULE_NONZERO); } sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(_touchpath), _touchpath_curve); @@ -123,7 +125,7 @@ void Inkscape::Rubberband::move(Geom::Point const &p) } } -void Inkscape::Rubberband::setMode(int mode) +void Inkscape::Rubberband::setMode(int mode) { _mode = mode; } diff --git a/src/rubberband.h b/src/rubberband.h index 3521339ff2f64a8c5daa7894b219378eb33a1acf..72b200ab1e03b1174d083261b83b4ab659cc86ed 100644 --- a/src/rubberband.h +++ b/src/rubberband.h @@ -23,13 +23,13 @@ class SPCurve; class SPDesktop; struct SPCanvasItem; -enum { +enum +{ RUBBERBAND_MODE_RECT, RUBBERBAND_MODE_TOUCHPATH }; -namespace Inkscape -{ +namespace Inkscape { /** * Rubberbanding selector. @@ -37,25 +37,23 @@ namespace Inkscape class Rubberband { public: - void start(SPDesktop *desktop, Geom::Point const &p); void move(Geom::Point const &p); Geom::OptRect getRectangle() const; void stop(); bool is_started(); - inline int getMode() {return _mode;} - inline std::vector<Geom::Point> getPoints() {return _points;} + inline int getMode() { return _mode; } + inline std::vector<Geom::Point> getPoints() { return _points; } void setMode(int mode); - static Rubberband* get(SPDesktop *desktop); + static Rubberband *get(SPDesktop *desktop); private: - Rubberband(SPDesktop *desktop); - static Rubberband* _instance; - + static Rubberband *_instance; + SPDesktop *_desktop; Geom::Point _start; Geom::Point _end; @@ -72,7 +70,7 @@ private: int _mode; }; -} +} // namespace Inkscape #endif // SEEN_RUBBERBAND_H diff --git a/src/satisfied-guide-cns.cpp b/src/satisfied-guide-cns.cpp index 5eb2a1dfbc697f1f12631d0e167d54e73af4c85a..03de4df44447681668ac7516130d3d24ea8361aa 100644 --- a/src/satisfied-guide-cns.cpp +++ b/src/satisfied-guide-cns.cpp @@ -8,21 +8,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <2geom/coord.h> - #include "satisfied-guide-cns.h" -#include "desktop.h" +#include <2geom/coord.h> +#include "desktop.h" #include "object/sp-guide.h" #include "object/sp-namedview.h" -void satisfied_guide_cns(SPDesktop const &desktop, - std::vector<Inkscape::SnapCandidatePoint> const &snappoints, +void satisfied_guide_cns(SPDesktop const &desktop, std::vector<Inkscape::SnapCandidatePoint> const &snappoints, std::vector<SPGuideConstraint> &cns) { SPNamedView const &nv = *desktop.getNamedView(); - for(auto guide : nv.guides) { + for (auto guide : nv.guides) { SPGuide &g = *guide; for (unsigned int i = 0; i < snappoints.size(); ++i) { if (Geom::are_near(g.getDistanceFrom(snappoints[i].getPoint()), 0, 1e-2)) { @@ -32,7 +30,6 @@ void satisfied_guide_cns(SPDesktop const &desktop, } } - /* Local Variables: mode:c++ diff --git a/src/satisfied-guide-cns.h b/src/satisfied-guide-cns.h index 575009ffb506b8cffcd4e33eb999458f8b6c131f..69a5dc6df587c8da4fdbf0ee0075374f60938647 100644 --- a/src/satisfied-guide-cns.h +++ b/src/satisfied-guide-cns.h @@ -18,11 +18,9 @@ class SPDesktop; class SPGuideConstraint; -void satisfied_guide_cns(SPDesktop const &desktop, - std::vector<Inkscape::SnapCandidatePoint> const &snappoints, +void satisfied_guide_cns(SPDesktop const &desktop, std::vector<Inkscape::SnapCandidatePoint> const &snappoints, std::vector<SPGuideConstraint> &cns); - #endif // SEEN_SATISFIED_GUIDE_CNS_H /* diff --git a/src/selcue.cpp b/src/selcue.cpp index b1d30bc515d5a89813e95a8ec3f5a11cadf94569..c5d56d1ca8e7c4d88567b9060984b9b22e7e9c5d 100644 --- a/src/selcue.cpp +++ b/src/selcue.cpp @@ -15,23 +15,19 @@ #include "selcue.h" #include "desktop.h" -#include "selection.h" -#include "text-editing.h" - #include "display/sodipodi-ctrl.h" #include "display/sodipodi-ctrlrect.h" #include "display/sp-canvas-util.h" - #include "libnrtype/Layout-TNG.h" - #include "object/sp-flowtext.h" #include "object/sp-text.h" +#include "selection.h" +#include "text-editing.h" -Inkscape::SelCue::BoundingBoxPrefsObserver::BoundingBoxPrefsObserver(SelCue &sel_cue) : - Observer("/tools/bounding_box"), - _sel_cue(sel_cue) -{ -} +Inkscape::SelCue::BoundingBoxPrefsObserver::BoundingBoxPrefsObserver(SelCue &sel_cue) + : Observer("/tools/bounding_box") + , _sel_cue(sel_cue) +{} void Inkscape::SelCue::BoundingBoxPrefsObserver::notify(Preferences::Entry const &val) { @@ -39,20 +35,18 @@ void Inkscape::SelCue::BoundingBoxPrefsObserver::notify(Preferences::Entry const } Inkscape::SelCue::SelCue(SPDesktop *desktop) - : _desktop(desktop), - _bounding_box_prefs_observer(*this) + : _desktop(desktop) + , _bounding_box_prefs_observer(*this) { _selection = _desktop->getSelection(); - _sel_changed_connection = _selection->connectChanged( - sigc::hide(sigc::mem_fun(*this, &Inkscape::SelCue::_newItemBboxes)) - ); + _sel_changed_connection = + _selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &Inkscape::SelCue::_newItemBboxes))); { - void(SelCue::*modifiedSignal)() = &SelCue::_updateItemBboxes; - _sel_modified_connection = _selection->connectModified( - sigc::hide(sigc::hide(sigc::mem_fun(*this, modifiedSignal))) - ); + void (SelCue::*modifiedSignal)() = &SelCue::_updateItemBboxes; + _sel_modified_connection = + _selection->connectModified(sigc::hide(sigc::hide(sigc::mem_fun(*this, modifiedSignal)))); } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -65,12 +59,12 @@ Inkscape::SelCue::~SelCue() _sel_changed_connection.disconnect(); _sel_modified_connection.disconnect(); - for (auto & _item_bboxe : _item_bboxes) { + for (auto &_item_bboxe : _item_bboxes) { sp_canvas_item_destroy(_item_bboxe); } _item_bboxes.clear(); - for (auto & _text_baseline : _text_baselines) { + for (auto &_text_baseline : _text_baselines) { sp_canvas_item_destroy(_text_baseline); } _text_baselines.clear(); @@ -98,20 +92,19 @@ void Inkscape::SelCue::_updateItemBboxes(Inkscape::Preferences *prefs) void Inkscape::SelCue::_updateItemBboxes(gint mode, int prefs_bbox) { auto items = _selection->items(); - if (_item_bboxes.size() != (unsigned int) boost::distance(items)) { + if (_item_bboxes.size() != (unsigned int)boost::distance(items)) { _newItemBboxes(); return; } int bcount = 0; - auto ll= _selection->items(); + auto ll = _selection->items(); for (auto l = ll.begin(); l != ll.end(); ++l) { SPItem *item = *l; - SPCanvasItem* box = _item_bboxes[bcount ++]; + SPCanvasItem *box = _item_bboxes[bcount++]; if (box) { - Geom::OptRect const b = (prefs_bbox == 0) ? - item->desktopVisualBounds() : item->desktopGeometricBounds(); + Geom::OptRect const b = (prefs_bbox == 0) ? item->desktopVisualBounds() : item->desktopGeometricBounds(); if (b) { sp_canvas_item_show(box); @@ -129,10 +122,9 @@ void Inkscape::SelCue::_updateItemBboxes(gint mode, int prefs_bbox) _newTextBaselines(); } - void Inkscape::SelCue::_newItemBboxes() { - for (auto & _item_bboxe : _item_bboxes) { + for (auto &_item_bboxe : _item_bboxes) { sp_canvas_item_destroy(_item_bboxe); } _item_bboxes.clear(); @@ -146,37 +138,27 @@ void Inkscape::SelCue::_newItemBboxes() g_return_if_fail(_selection != nullptr); int prefs_bbox = prefs->getBool("/tools/bounding_box"); - - auto ll= _selection->items(); + + auto ll = _selection->items(); for (auto l = ll.begin(); l != ll.end(); ++l) { SPItem *item = *l; - Geom::OptRect const b = (prefs_bbox == 0) ? - item->desktopVisualBounds() : item->desktopGeometricBounds(); + Geom::OptRect const b = (prefs_bbox == 0) ? item->desktopVisualBounds() : item->desktopGeometricBounds(); - SPCanvasItem* box = nullptr; + SPCanvasItem *box = nullptr; if (b) { if (mode == MARK) { - box = sp_canvas_item_new(_desktop->getControls(), - SP_TYPE_CTRL, - "mode", SP_CTRL_MODE_XOR, - "shape", SP_CTRL_SHAPE_DIAMOND, - "size", 6, - "filled", TRUE, - "fill_color", 0x000000ff, - "stroked", FALSE, - "stroke_color", 0x000000ff, - NULL); + box = sp_canvas_item_new(_desktop->getControls(), SP_TYPE_CTRL, "mode", SP_CTRL_MODE_XOR, "shape", + SP_CTRL_SHAPE_DIAMOND, "size", 6, "filled", TRUE, "fill_color", 0x000000ff, + "stroked", FALSE, "stroke_color", 0x000000ff, NULL); sp_canvas_item_show(box); SP_CTRL(box)->moveto(Geom::Point(b->min()[Geom::X], b->max()[Geom::Y])); sp_canvas_item_move_to_z(box, 0); // just low enough to not get in the way of other draggable knots } else if (mode == BBOX) { - box = sp_canvas_item_new(_desktop->getControls(), - SP_TYPE_CTRLRECT, - nullptr); + box = sp_canvas_item_new(_desktop->getControls(), SP_TYPE_CTRLRECT, nullptr); SP_CTRLRECT(box)->setRectangle(*b); SP_CTRLRECT(box)->setColor(0xffffffa0, false, 0); @@ -198,28 +180,24 @@ void Inkscape::SelCue::_newItemBboxes() void Inkscape::SelCue::_newTextBaselines() { - for (auto & _text_baseline : _text_baselines) { + for (auto &_text_baseline : _text_baselines) { sp_canvas_item_destroy(_text_baseline); } _text_baselines.clear(); auto ll = _selection->items(); - for (auto l=ll.begin();l!=ll.end();++l) { + for (auto l = ll.begin(); l != ll.end(); ++l) { SPItem *item = *l; - SPCanvasItem* baseline_point = nullptr; + SPCanvasItem *baseline_point = nullptr; if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item)) { // visualize baseline Inkscape::Text::Layout const *layout = te_get_layout(item); if (layout != nullptr && layout->outputExists()) { boost::optional<Geom::Point> pt = layout->baselineAnchorPoint(); if (pt) { - baseline_point = sp_canvas_item_new(_desktop->getControls(), SP_TYPE_CTRL, - "mode", SP_CTRL_MODE_XOR, - "size", 5, - "filled", 0, - "stroked", 1, - "stroke_color", 0x000000ff, - NULL); + baseline_point = + sp_canvas_item_new(_desktop->getControls(), SP_TYPE_CTRL, "mode", SP_CTRL_MODE_XOR, "size", 5, + "filled", 0, "stroked", 1, "stroke_color", 0x000000ff, NULL); sp_canvas_item_show(baseline_point); SP_CTRL(baseline_point)->moveto((*pt) * item->i2dt_affine()); @@ -229,7 +207,7 @@ void Inkscape::SelCue::_newTextBaselines() } if (baseline_point) { - _text_baselines.push_back(baseline_point); + _text_baselines.push_back(baseline_point); } } } diff --git a/src/selcue.h b/src/selcue.h index 74a7443213f8de0ba1958195099c1a55207d7b3a..a5911c2fe0bafd3a539354f903f788fbe95cf6f1 100644 --- a/src/selcue.h +++ b/src/selcue.h @@ -16,12 +16,11 @@ #include <cstddef> #include <list> - #include <sigc++/sigc++.h> #include "preferences.h" -class SPDesktop; +class SPDesktop; struct SPCanvasItem; namespace Inkscape { @@ -34,14 +33,15 @@ public: SelCue(SPDesktop *desktop); ~SelCue(); - enum Type { + enum Type + { NONE, MARK, BBOX }; private: - class BoundingBoxPrefsObserver: public Preferences::Observer + class BoundingBoxPrefsObserver : public Preferences::Observer { public: BoundingBoxPrefsObserver(SelCue &sel_cue); @@ -65,16 +65,15 @@ private: Selection *_selection; sigc::connection _sel_changed_connection; sigc::connection _sel_modified_connection; - std::vector<SPCanvasItem*> _item_bboxes; - std::vector<SPCanvasItem*> _text_baselines; + std::vector<SPCanvasItem *> _item_bboxes; + std::vector<SPCanvasItem *> _text_baselines; BoundingBoxPrefsObserver _bounding_box_prefs_observer; }; -} - -#endif +} // namespace Inkscape +#endif /* Local Variables: diff --git a/src/selection-chemistry.cpp b/src/selection-chemistry.cpp index b0c3af00af67dfa38dbc3d60b82dfcf528fc480c..ca267c1a0012c49778f73c3cebf07eb0dfeabae4 100644 --- a/src/selection-chemistry.cpp +++ b/src/selection-chemistry.cpp @@ -22,48 +22,36 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "selection-chemistry.h" + #include <boost/range/adaptor/reversed.hpp> #include <cstring> #include <glibmm/i18n.h> +#include <gtkmm/clipboard.h> #include <map> #include <string> -#include <gtkmm/clipboard.h> - -#include "selection-chemistry.h" - -#include "file.h" #include "display/canvas-bpath.h" +#include "file.h" // TODO FIXME: This should be moved into preference repr SPCycleType SP_CYCLING = SP_CYCLE_FOCUS; - #include "context-fns.h" #include "desktop-style.h" #include "desktop.h" +#include "display/cairo-utils.h" +#include "display/curve.h" #include "document-undo.h" #include "gradient-drag.h" +#include "helper/png-write.h" +#include "io/resource.h" #include "layer-fns.h" #include "layer-manager.h" #include "layer-model.h" -#include "message-stack.h" -#include "path-chemistry.h" -#include "selection.h" -#include "text-editing.h" -#include "text-chemistry.h" -#include "verbs.h" - -#include "display/cairo-utils.h" -#include "display/curve.h" - -#include "helper/png-write.h" - -#include "io/resource.h" - #include "live_effects/effect.h" #include "live_effects/parameter/originalpath.h" - +#include "message-stack.h" #include "object/box3d.h" #include "object/object-set.h" #include "object/persp3d.h" @@ -96,11 +84,13 @@ SPCycleType SP_CYCLING = SP_CYCLE_FOCUS; #include "object/sp-tref.h" #include "object/sp-tspan.h" #include "object/sp-use.h" +#include "path-chemistry.h" +#include "selection.h" #include "style.h" - #include "svg/svg-color.h" #include "svg/svg.h" - +#include "text-chemistry.h" +#include "text-editing.h" #include "ui/clipboard.h" #include "ui/tool/control-point-selection.h" #include "ui/tool/multi-path-manipulator.h" @@ -110,14 +100,14 @@ SPCycleType SP_CYCLING = SP_CYCLE_FOCUS; #include "ui/tools/gradient-tool.h" #include "ui/tools/node-tool.h" #include "ui/tools/text-tool.h" -#include "ui/widget/canvas.h" // is_dragging() - +#include "ui/widget/canvas.h" // is_dragging() +#include "verbs.h" #include "xml/rebase-hrefs.h" #include "xml/simple-document.h" -using Inkscape::DocumentUndo; using Geom::X; using Geom::Y; +using Inkscape::DocumentUndo; using Inkscape::UI::Tools::NodeTool; using namespace Inkscape; @@ -125,17 +115,14 @@ using namespace Inkscape; because the layer manipulation code uses them. It should be rewritten specifically for that purpose. */ - // helper for printing error messages, regardless of whether we have a GUI or not // If desktop == NULL, errors will be shown on stderr -static void -selection_display_message(SPDesktop *desktop, Inkscape::MessageType msgType, Glib::ustring const &msg) +static void selection_display_message(SPDesktop *desktop, Inkscape::MessageType msgType, Glib::ustring const &msg) { if (desktop) { desktop->messageStack()->flash(msgType, msg); } else { - if (msgType == Inkscape::IMMEDIATE_MESSAGE || - msgType == Inkscape::WARNING_MESSAGE || + if (msgType == Inkscape::IMMEDIATE_MESSAGE || msgType == Inkscape::WARNING_MESSAGE || msgType == Inkscape::ERROR_MESSAGE) { g_printerr("%s\n", msg.c_str()); } @@ -147,7 +134,7 @@ namespace Inkscape { void SelectionHelper::selectAll(SPDesktop *dt) { if (tools_isactive(dt, TOOLS_NODES)) { - NodeTool *nt = static_cast<NodeTool*>(dt->event_context); + NodeTool *nt = static_cast<NodeTool *>(dt->event_context); if (!nt->_multipath->empty()) { nt->_multipath->selectSubpaths(); return; @@ -159,7 +146,7 @@ void SelectionHelper::selectAll(SPDesktop *dt) void SelectionHelper::selectAllInAll(SPDesktop *dt) { if (tools_isactive(dt, TOOLS_NODES)) { - NodeTool *nt = static_cast<NodeTool*>(dt->event_context); + NodeTool *nt = static_cast<NodeTool *>(dt->event_context); nt->_selected_nodes->selectAll(); } else { sp_edit_select_all_in_all_layers(dt); @@ -170,7 +157,7 @@ void SelectionHelper::selectNone(SPDesktop *dt) { NodeTool *nt = nullptr; if (tools_isactive(dt, TOOLS_NODES)) { - nt = static_cast<NodeTool*>(dt->event_context); + nt = static_cast<NodeTool *>(dt->event_context); } if (nt && !nt->_selected_nodes->empty()) { @@ -211,7 +198,7 @@ void SelectionHelper::selectSameObjectType(SPDesktop *dt) void SelectionHelper::invert(SPDesktop *dt) { if (tools_isactive(dt, TOOLS_NODES)) { - NodeTool *nt = static_cast<NodeTool*>(dt->event_context); + NodeTool *nt = static_cast<NodeTool *>(dt->event_context); nt->_multipath->invertSelectionInSubpaths(); } else { sp_edit_invert(dt); @@ -221,7 +208,7 @@ void SelectionHelper::invert(SPDesktop *dt) void SelectionHelper::invertAllInAll(SPDesktop *dt) { if (tools_isactive(dt, TOOLS_NODES)) { - NodeTool *nt = static_cast<NodeTool*>(dt->event_context); + NodeTool *nt = static_cast<NodeTool *>(dt->event_context); nt->_selected_nodes->invertSelection(); } else { sp_edit_invert_in_all_layers(dt); @@ -232,7 +219,7 @@ void SelectionHelper::reverse(SPDesktop *dt) { // TODO make this a virtual method of event context! if (tools_isactive(dt, TOOLS_NODES)) { - NodeTool *nt = static_cast<NodeTool*>(dt->event_context); + NodeTool *nt = static_cast<NodeTool *>(dt->event_context); nt->_multipath->reverseSubpaths(); } else { dt->getSelection()->pathReverse(); @@ -243,10 +230,9 @@ void SelectionHelper::selectNext(SPDesktop *dt) { Inkscape::UI::Tools::ToolBase *ec = dt->event_context; if (tools_isactive(dt, TOOLS_NODES)) { - NodeTool *nt = static_cast<NodeTool*>(dt->event_context); + NodeTool *nt = static_cast<NodeTool *>(dt->event_context); nt->_multipath->shiftSelection(1); - } else if (tools_isactive(dt, TOOLS_GRADIENT) - && ec->_grdrag->isNonEmpty()) { + } else if (tools_isactive(dt, TOOLS_GRADIENT) && ec->_grdrag->isNonEmpty()) { Inkscape::UI::Tools::sp_gradient_context_select_next(ec); } else { sp_selection_item_next(dt); @@ -257,10 +243,9 @@ void SelectionHelper::selectPrev(SPDesktop *dt) { Inkscape::UI::Tools::ToolBase *ec = dt->event_context; if (tools_isactive(dt, TOOLS_NODES)) { - NodeTool *nt = static_cast<NodeTool*>(dt->event_context); + NodeTool *nt = static_cast<NodeTool *>(dt->event_context); nt->_multipath->shiftSelection(-1); - } else if (tools_isactive(dt, TOOLS_GRADIENT) - && ec->_grdrag->isNonEmpty()) { + } else if (tools_isactive(dt, TOOLS_GRADIENT) && ec->_grdrag->isNonEmpty()) { Inkscape::UI::Tools::sp_gradient_context_select_prev(ec); } else { sp_selection_item_prev(dt); @@ -272,21 +257,18 @@ void SelectionHelper::selectPrev(SPDesktop *dt) */ void SelectionHelper::fixSelection(SPDesktop *dt) { - if(!dt) + if (!dt) return; Inkscape::Selection *selection = dt->getSelection(); - std::vector<SPItem*> items ; + std::vector<SPItem *> items; auto selList = selection->items(); - for(auto i = boost::rbegin(selList); i != boost::rend(selList); ++i) { + for (auto i = boost::rbegin(selList); i != boost::rend(selList); ++i) { SPItem *item = *i; - if( item && - !dt->isLayer(item) && - (!item->isLocked())) - { + if (item && !dt->isLayer(item) && (!item->isLocked())) { items.push_back(item); } } @@ -296,12 +278,12 @@ void SelectionHelper::fixSelection(SPDesktop *dt) } // namespace Inkscape - /** * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t', * then prepends the copy to 'clip'. */ -static void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Affine full_t, std::vector<Inkscape::XML::Node*> &clip, Inkscape::XML::Document* xml_doc) +static void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Affine full_t, + std::vector<Inkscape::XML::Node *> &clip, Inkscape::XML::Document *xml_doc) { Inkscape::XML::Node *copy = repr->duplicate(xml_doc); @@ -313,18 +295,19 @@ static void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Affine full_t // write the complete accumulated transform passed to us // (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(full_t); + gchar *affinestr = sp_svg_transform_write(full_t); copy->setAttribute("transform", affinestr); g_free(affinestr); - clip.insert(clip.begin(),copy); + clip.insert(clip.begin(), copy); } -static void sp_selection_copy_impl(std::vector<SPItem*> const &items, std::vector<Inkscape::XML::Node*> &clip, Inkscape::XML::Document* xml_doc) +static void sp_selection_copy_impl(std::vector<SPItem *> const &items, std::vector<Inkscape::XML::Node *> &clip, + Inkscape::XML::Document *xml_doc) { // Sort items: - std::vector<SPItem*> sorted_items(items); - sort(sorted_items.begin(),sorted_items.end(),sp_object_compare_position_bool); + std::vector<SPItem *> sorted_items(items); + sort(sorted_items.begin(), sorted_items.end(), sp_object_compare_position_bool); // Copy item reprs: for (auto item : sorted_items) { @@ -334,18 +317,19 @@ static void sp_selection_copy_impl(std::vector<SPItem*> const &items, std::vecto g_assert_not_reached(); } } - reverse(clip.begin(),clip.end()); + reverse(clip.begin(), clip.end()); } // TODO check if parent parameter should be changed to SPItem, of if the code should handle non-items. -static std::vector<Inkscape::XML::Node*> sp_selection_paste_impl(SPDocument *doc, SPObject *parent, std::vector<Inkscape::XML::Node*> &clip) +static std::vector<Inkscape::XML::Node *> sp_selection_paste_impl(SPDocument *doc, SPObject *parent, + std::vector<Inkscape::XML::Node *> &clip) { Inkscape::XML::Document *xml_doc = doc->getReprDoc(); SPItem *parentItem = dynamic_cast<SPItem *>(parent); g_assert(parentItem != nullptr); - std::vector<Inkscape::XML::Node*> copied; + std::vector<Inkscape::XML::Node *> copied; // add objects to document for (auto repr : clip) { Inkscape::XML::Node *copy = repr->duplicate(xml_doc); @@ -359,7 +343,7 @@ static std::vector<Inkscape::XML::Node*> sp_selection_paste_impl(SPDocument *doc 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); + gchar *affinestr = sp_svg_transform_write(item_t); copy->setAttribute("transform", affinestr); g_free(affinestr); } @@ -371,7 +355,8 @@ static std::vector<Inkscape::XML::Node*> sp_selection_paste_impl(SPDocument *doc return copied; } -static void sp_selection_delete_impl(std::vector<SPItem*> const &items, bool propagate = true, bool propagate_descendants = true) +static void sp_selection_delete_impl(std::vector<SPItem *> const &items, bool propagate = true, + bool propagate_descendants = true) { for (auto item : items) { sp_object_ref(item, nullptr); @@ -382,25 +367,23 @@ static void sp_selection_delete_impl(std::vector<SPItem*> const &items, bool pro } } - void ObjectSet::deleteItems() { - if(desktop() && tools_isactive(desktop(), TOOLS_TEXT)){ - if (Inkscape::UI::Tools::sp_text_delete_selection(desktop()->event_context)) { - DocumentUndo::done(desktop()->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Delete text")); + if (desktop() && tools_isactive(desktop(), TOOLS_TEXT)) { + if (Inkscape::UI::Tools::sp_text_delete_selection(desktop()->event_context)) { + DocumentUndo::done(desktop()->getDocument(), SP_VERB_CONTEXT_TEXT, _("Delete text")); return; - } + } } - if (isEmpty()) { - selection_display_message(desktop(),Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted.")); + if (isEmpty()) { + selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted.")); return; } - std::vector<SPItem*> selected(items().begin(), items().end()); + std::vector<SPItem *> selected(items().begin(), items().end()); clear(); sp_selection_delete_impl(selected); - if(SPDesktop *d = desktop()){ + if (SPDesktop *d = desktop()) { d->currentLayer()->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); /* a tool may have set up private information in it's selection context @@ -409,23 +392,19 @@ void ObjectSet::deleteItems() * associated selection context. For example: deleting an object * while moving it around the canvas. */ - tools_switch( d, tools_active( d ) ); + tools_switch(d, tools_active(d)); } - if(document()) - DocumentUndo::done(document(), SP_VERB_EDIT_DELETE, - _("Delete")); - + if (document()) + DocumentUndo::done(document(), SP_VERB_EDIT_DELETE, _("Delete")); } - - static void add_ids_recursive(std::vector<const gchar *> &ids, SPObject *obj) { if (obj) { ids.push_back(obj->getId()); if (dynamic_cast<SPGroup *>(obj)) { - for (auto& child: obj->children) { + for (auto &child : obj->children) { add_ids_recursive(ids, &child); } } @@ -434,26 +413,26 @@ static void add_ids_recursive(std::vector<const gchar *> &ids, SPObject *obj) void ObjectSet::duplicate(bool suppressDone, bool duplicateLayer) { - if(duplicateLayer && !desktop() ){ - //TODO: understand why layer management is tied to desktop and not to document. + if (duplicateLayer && !desktop()) { + // TODO: understand why layer management is tied to desktop and not to document. return; } SPDocument *doc = document(); - if(!doc) + if (!doc) return; - Inkscape::XML::Document* xml_doc = doc->getReprDoc(); + Inkscape::XML::Document *xml_doc = doc->getReprDoc(); // check if something is selected if (isEmpty() && !duplicateLayer) { - selection_display_message(desktop(),Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate.")); + selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate.")); return; } - std::vector<Inkscape::XML::Node*> reprs(xmlNodes().begin(), xmlNodes().end()); + std::vector<Inkscape::XML::Node *> reprs(xmlNodes().begin(), xmlNodes().end()); - if(duplicateLayer){ + if (duplicateLayer) { reprs.clear(); reprs.push_back(desktop()->currentLayer()->getRepr()); } @@ -462,7 +441,7 @@ void ObjectSet::duplicate(bool suppressDone, bool duplicateLayer) // sorting items from different parents sorts each parent's subset without possibly mixing // them, just what we need - sort(reprs.begin(),reprs.end(),sp_repr_compare_position_bool); + sort(reprs.begin(), reprs.end(), sp_repr_compare_position_bool); std::vector<const gchar *> old_ids; std::vector<const gchar *> new_ids; @@ -472,16 +451,16 @@ void ObjectSet::duplicate(bool suppressDone, bool duplicateLayer) // check ref-d shapes, split in defs|internal|external // add external & defs to reprs - auto text_refs = text_categorize_refs(doc, reprs.begin(), reprs.end(), - static_cast<text_ref_t>(TEXT_REF_DEF | TEXT_REF_EXTERNAL | TEXT_REF_INTERNAL)); + auto text_refs = text_categorize_refs( + doc, reprs.begin(), reprs.end(), static_cast<text_ref_t>(TEXT_REF_DEF | TEXT_REF_EXTERNAL | TEXT_REF_INTERNAL)); for (auto const &ref : text_refs) { if (ref.second == TEXT_REF_DEF || ref.second == TEXT_REF_EXTERNAL) { reprs.push_back(doc->getObjectById(ref.first)->getRepr()); } } - std::vector<Inkscape::XML::Node*> copies; - for(auto old_repr : reprs) { + std::vector<Inkscape::XML::Node *> copies; + for (auto old_repr : reprs) { Inkscape::XML::Node *parent = old_repr->parent(); Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc); @@ -519,7 +498,7 @@ void ObjectSet::duplicate(bool suppressDone, bool duplicateLayer) text_relink_refs(text_refs, reprs.begin(), reprs.end(), copies.begin()); // copies contains def nodes, we don't want that in our selection - std::vector<Inkscape::XML::Node*> newsel; + std::vector<Inkscape::XML::Node *> newsel; if (!duplicateLayer) { // compute newsel, by removing def nodes from copies for (auto node : copies) { @@ -530,7 +509,6 @@ void ObjectSet::duplicate(bool suppressDone, bool duplicateLayer) } if (relink_clones) { - g_assert(old_ids.size() == new_ids.size()); for (unsigned int i = 0; i < old_ids.size(); i++) { @@ -547,7 +525,8 @@ void ObjectSet::duplicate(bool suppressDone, bool duplicateLayer) for (unsigned int j = 0; j < old_ids.size(); j++) { if (!strcmp(orig->getId(), old_ids[j])) { // we have both orig and clone in selection, relink - // std::cout << id << " old, its ori: " << orig->getId() << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n"; + // std::cout << id << " old, its ori: " << orig->getId() << "; will relink:" << new_ids[i] << " + // to " << new_ids[j] << "\n"; SPObject *new_clone = doc->getObjectById(new_ids[i]); new_clone->setAttribute("xlink:href", Glib::ustring("#") + new_ids[j]); new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); @@ -556,17 +535,20 @@ void ObjectSet::duplicate(bool suppressDone, bool duplicateLayer) } else if (offset) { gchar *source_href = offset->sourceHref; for (guint j = 0; j < old_ids.size(); j++) { - if (source_href && source_href[0]=='#' && !strcmp(source_href+1, old_ids[j])) { + if (source_href && source_href[0] == '#' && !strcmp(source_href + 1, old_ids[j])) { doc->getObjectById(new_ids[i])->setAttribute("xlink:href", Glib::ustring("#") + new_ids[j]); } } } else if (text) { SPTextPath *textpath = dynamic_cast<SPTextPath *>(text->firstChild()); - if (!textpath) continue; + if (!textpath) + continue; const gchar *source_href = sp_textpath_get_path_item(textpath)->getId(); for (guint j = 0; j < old_ids.size(); j++) { if (!strcmp(source_href, old_ids[j])) { - doc->getObjectById(new_ids[i])->firstChild()->setAttribute("xlink:href", Glib::ustring("#") + new_ids[j]); + doc->getObjectById(new_ids[i]) + ->firstChild() + ->setAttribute("xlink:href", Glib::ustring("#") + new_ids[j]); } } } else if (path) { @@ -575,10 +557,10 @@ void ObjectSet::duplicate(bool suppressDone, bool duplicateLayer) const char *old_end = old_clone->getAttribute("inkscape:connection-end"); SPObject *new_clone = doc->getObjectById(new_ids[i]); for (guint j = 0; j < old_ids.size(); j++) { - if(old_start == Glib::ustring("#") + old_ids[j]) { + if (old_start == Glib::ustring("#") + old_ids[j]) { new_clone->setAttribute("inkscape:connection-start", Glib::ustring("#") + new_ids[j]); } - if(old_end == Glib::ustring("#") + old_ids[j]) { + if (old_end == Glib::ustring("#") + old_ids[j]) { new_clone->setAttribute("inkscape:connection-end", Glib::ustring("#") + new_ids[j]); } } @@ -587,17 +569,15 @@ void ObjectSet::duplicate(bool suppressDone, bool duplicateLayer) } } - - if ( !suppressDone ) { - DocumentUndo::done(document(), SP_VERB_EDIT_DUPLICATE, - _("Duplicate")); + if (!suppressDone) { + DocumentUndo::done(document(), SP_VERB_EDIT_DUPLICATE, _("Duplicate")); } - if(!duplicateLayer) + if (!duplicateLayer) setReprList(newsel); - else{ - SPObject* new_layer = doc->getObjectByRepr(copies[0]); - gchar* name = g_strdup_printf(_("%s copy"), new_layer->label()); - desktop()->layer_manager->renameLayer( new_layer, name, TRUE ); + else { + SPObject *new_layer = doc->getObjectByRepr(copies[0]); + gchar *name = g_strdup_printf(_("%s copy"), new_layer->label()); + desktop()->layer_manager->renameLayer(new_layer, name, TRUE); g_free(name); } } @@ -612,14 +592,13 @@ void sp_edit_clear_all(Inkscape::Selection *selection) SPGroup *group = dynamic_cast<SPGroup *>(selection->layers()->currentLayer()); g_return_if_fail(group != nullptr); - std::vector<SPItem*> items = sp_item_group_item_list(group); + std::vector<SPItem *> items = sp_item_group_item_list(group); - for(auto & item : items){ + for (auto &item : items) { item->deleteObject(); } - DocumentUndo::done(doc, SP_VERB_EDIT_CLEAR_ALL, - _("Delete all")); + DocumentUndo::done(doc, SP_VERB_EDIT_CLEAR_ALL, _("Delete all")); } /* @@ -632,18 +611,15 @@ void sp_edit_clear_all(Inkscape::Selection *selection) * onlysensitive - TRUE includes only non-locked items * ingroups - TRUE to recursively get grouped items children */ -std::vector<SPItem*> &get_all_items(std::vector<SPItem*> &list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, bool ingroups, std::vector<SPItem*> const &exclude) +std::vector<SPItem *> &get_all_items(std::vector<SPItem *> &list, SPObject *from, SPDesktop *desktop, bool onlyvisible, + bool onlysensitive, bool ingroups, std::vector<SPItem *> const &exclude) { - for (auto& child: from->children) { + for (auto &child : from->children) { SPItem *item = dynamic_cast<SPItem *>(&child); - if (item && - !desktop->isLayer(item) && - (!onlysensitive || !item->isLocked()) && + if (item && !desktop->isLayer(item) && (!onlysensitive || !item->isLocked()) && (!onlyvisible || !desktop->itemIsHidden(item)) && - (exclude.empty() || exclude.end() == std::find(exclude.begin(), exclude.end(), &child)) - ) - { - list.insert(list.begin(),item); + (exclude.empty() || exclude.end() == std::find(exclude.begin(), exclude.end(), &child))) { + list.insert(list.begin(), item); } if (ingroups || (item && desktop->isLayer(item))) { @@ -664,13 +640,14 @@ static void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool i g_return_if_fail(dynamic_cast<SPGroup *>(dt->currentLayer())); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER); + PrefsSelectionContext inlayer = + (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER); bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true); bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true); - std::vector<SPItem*> items ; + std::vector<SPItem *> items; - std::vector<SPItem*> exclude; + std::vector<SPItem *> exclude; if (invert) { exclude.insert(exclude.end(), selection->items().begin(), selection->items().end()); } @@ -680,42 +657,41 @@ static void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool i switch (inlayer) { case PREFS_SELECTION_LAYER: { - if ( (onlysensitive && dynamic_cast<SPItem *>(dt->currentLayer())->isLocked()) || - (onlyvisible && dt->itemIsHidden(dynamic_cast<SPItem *>(dt->currentLayer()))) ) - return; + if ((onlysensitive && dynamic_cast<SPItem *>(dt->currentLayer())->isLocked()) || + (onlyvisible && dt->itemIsHidden(dynamic_cast<SPItem *>(dt->currentLayer())))) + return; - std::vector<SPItem*> all_items = sp_item_group_item_list(dynamic_cast<SPGroup *>(dt->currentLayer())); + std::vector<SPItem *> all_items = sp_item_group_item_list(dynamic_cast<SPGroup *>(dt->currentLayer())); - for (std::vector<SPItem*>::const_reverse_iterator i=all_items.rbegin();i!=all_items.rend();++i) { - SPItem *item = *i; + for (std::vector<SPItem *>::const_reverse_iterator i = all_items.rbegin(); i != all_items.rend(); ++i) { + SPItem *item = *i; - if (item && (!onlysensitive || !item->isLocked())) { - if (!onlyvisible || !dt->itemIsHidden(item)) { - if (!dt->isLayer(item)) { - if (!invert || exclude.end() == std::find(exclude.begin(),exclude.end(),item)) { - items.push_back(item); // leave it in the list + if (item && (!onlysensitive || !item->isLocked())) { + if (!onlyvisible || !dt->itemIsHidden(item)) { + if (!dt->isLayer(item)) { + if (!invert || exclude.end() == std::find(exclude.begin(), exclude.end(), item)) { + items.push_back(item); // leave it in the list + } } } } } - } break; } case PREFS_SELECTION_LAYER_RECURSIVE: { - std::vector<SPItem*> x; + std::vector<SPItem *> x; items = get_all_items(x, dt->currentLayer(), dt, onlyvisible, onlysensitive, FALSE, exclude); break; } default: { - std::vector<SPItem*> x; + std::vector<SPItem *> x; items = get_all_items(x, dt->currentRoot(), dt, onlyvisible, onlysensitive, FALSE, exclude); break; - } + } } selection->setList(items); - } void sp_edit_select_all(SPDesktop *desktop) @@ -738,9 +714,10 @@ void sp_edit_invert_in_all_layers(SPDesktop *desktop) sp_edit_select_all_full(desktop, true, true); } -Inkscape::XML::Node* ObjectSet::group() { +Inkscape::XML::Node *ObjectSet::group() +{ SPDocument *doc = document(); - if(!doc) + if (!doc) return nullptr; if (isEmpty()) { selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group.")); @@ -749,7 +726,7 @@ Inkscape::XML::Node* ObjectSet::group() { Inkscape::XML::Document *xml_doc = doc->getReprDoc(); Inkscape::XML::Node *group = xml_doc->createElement("svg:g"); - std::vector<Inkscape::XML::Node*> p(xmlNodes().begin(), xmlNodes().end()); + std::vector<Inkscape::XML::Node *> p(xmlNodes().begin(), xmlNodes().end()); std::sort(p.begin(), p.end(), sp_repr_compare_position_bool); this->clear(); @@ -757,18 +734,19 @@ Inkscape::XML::Node* ObjectSet::group() { gint topmost = p.back()->position(); Inkscape::XML::Node *topmost_parent = p.back()->parent(); - for(auto current : p){ + for (auto current : p) { if (current->parent() == topmost_parent) { Inkscape::XML::Node *spnew = current->duplicate(xml_doc); sp_repr_unparent(current); group->appendChild(spnew); Inkscape::GC::release(spnew); - topmost --; // only reduce count for those items deleted from topmost_parent - } else { // move it to topmost_parent first - std::vector<Inkscape::XML::Node*> temp_clip; + topmost--; // only reduce count for those items deleted from topmost_parent + } else { // move it to topmost_parent first + std::vector<Inkscape::XML::Node *> temp_clip; - // At this point, current may already have no item, due to its being a clone whose original is already moved away - // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform + // At this point, current may already have no item, due to its being a clone whose original is already moved + // away So we copy it artificially calculating the transform from its repr->attr("transform") and the parent + // transform gchar const *t_str = current->attribute("transform"); Geom::Affine item_t(Geom::identity()); if (t_str) @@ -785,8 +763,10 @@ Inkscape::XML::Node* ObjectSet::group() { sp_repr_unparent(current); // paste into topmost_parent (temporarily) - std::vector<Inkscape::XML::Node*> copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), temp_clip); - if (!temp_clip.empty())temp_clip.clear() ; + std::vector<Inkscape::XML::Node *> copied = + sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), temp_clip); + if (!temp_clip.empty()) + temp_clip.clear(); if (!copied.empty()) { // if success, // take pasted object (now in topmost_parent) Inkscape::XML::Node *in_topmost = copied.back(); @@ -806,62 +786,60 @@ Inkscape::XML::Node* ObjectSet::group() { topmost_parent->addChildAtPos(group, topmost + 1); set(doc->getObjectByRepr(group)); - DocumentUndo::done(doc, SP_VERB_SELECTION_GROUP, - C_("Verb", "Group")); + DocumentUndo::done(doc, SP_VERB_SELECTION_GROUP, C_("Verb", "Group")); return group; } - -static bool clone_depth_descending(gconstpointer a, gconstpointer b) { +static bool clone_depth_descending(gconstpointer a, gconstpointer b) +{ SPUse *use_a = static_cast<SPUse *>(const_cast<gpointer>(a)); SPUse *use_b = static_cast<SPUse *>(const_cast<gpointer>(b)); int depth_a = use_a->cloneDepth(); int depth_b = use_b->cloneDepth(); - return (depth_a==depth_b)?(a<b):(depth_a>depth_b); + return (depth_a == depth_b) ? (a < b) : (depth_a > depth_b); } -void ObjectSet::popFromGroup(){ +void ObjectSet::popFromGroup() +{ if (isEmpty()) { - selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("<b>No objects selected</b> to pop out of group.")); + selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, + _("<b>No objects selected</b> to pop out of group.")); return; } auto item = items().begin(); // leaving this because it will be useful for - // future implementation of complex pop ungrouping + // future implementation of complex pop ungrouping SPItem *obj = *item; - SPItem *parent_group = static_cast<SPItem*>(obj->parent); + SPItem *parent_group = static_cast<SPItem *>(obj->parent); if (!SP_IS_GROUP(parent_group) || SP_IS_LAYER(parent_group)) { selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("Selection <b>not in a group</b>.")); return; } if (parent_group->firstChild()->getNext() == nullptr) { - std::vector<SPItem*> children; - sp_item_group_ungroup(static_cast<SPGroup*>(parent_group), children, false); - } - else { + std::vector<SPItem *> children; + sp_item_group_ungroup(static_cast<SPGroup *>(parent_group), children, false); + } else { toNextLayer(true); } parent_group->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - if(document()) - DocumentUndo::done(document(), SP_VERB_SELECTION_UNGROUP_POP_SELECTION, - _("Pop selection from group")); - + if (document()) + DocumentUndo::done(document(), SP_VERB_SELECTION_UNGROUP_POP_SELECTION, _("Pop selection from group")); } static void ungroup_impl(ObjectSet *set) { - std::set<SPObject*> groups(set->groups().begin(),set->groups().end()); + std::set<SPObject *> groups(set->groups().begin(), set->groups().end()); - std::vector<SPItem*> new_select; + std::vector<SPItem *> new_select; auto old_select = set->items(); - std::vector<SPItem*> items(old_select.begin(), old_select.end()); + std::vector<SPItem *> items(old_select.begin(), old_select.end()); // If any of the clones refer to the groups, unlink them and replace them with successors // in the items list. - std::vector<SPUse*> clones_to_unlink; + std::vector<SPUse *> clones_to_unlink; for (auto item : items) { SPUse *use = dynamic_cast<SPUse *>(item); @@ -870,7 +848,7 @@ static void ungroup_impl(ObjectSet *set) original = dynamic_cast<SPUse *>(original)->get_original(); } - if (groups.find(original) != groups.end()) { + if (groups.find(original) != groups.end()) { clones_to_unlink.push_back(use); } } @@ -878,23 +856,23 @@ static void ungroup_impl(ObjectSet *set) // Unlink clones beginning from those with highest clone depth. // This way we can be sure than no additional automatic unlinking happens, // and the items in the list remain valid - std::sort(clones_to_unlink.begin(),clones_to_unlink.end(),clone_depth_descending); + std::sort(clones_to_unlink.begin(), clones_to_unlink.end(), clone_depth_descending); - for (auto use:clones_to_unlink) { - std::vector<SPItem*>::iterator items_node = std::find(items.begin(),items.end(), use); + for (auto use : clones_to_unlink) { + std::vector<SPItem *>::iterator items_node = std::find(items.begin(), items.end(), use); *items_node = use->unlink(); } // do the actual work - for (auto & item : items) { + for (auto &item : items) { SPItem *obj = item; // ungroup only the groups marked earlier if (groups.find(item) != groups.end()) { - std::vector<SPItem*> children; + std::vector<SPItem *> children; sp_item_group_ungroup(dynamic_cast<SPGroup *>(obj), children, false); // add the items resulting from ungrouping to the selection - new_select.insert(new_select.end(),children.begin(),children.end()); + new_select.insert(new_select.end(), children.begin(), children.end()); item = NULL; // zero out the original pointer, which is no longer valid } else { // if not a group, keep in the selection @@ -908,30 +886,29 @@ static void ungroup_impl(ObjectSet *set) void ObjectSet::ungroup() { if (isEmpty()) { - if(desktop()) + if (desktop()) selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup.")); return; } if (boost::distance(groups()) == 0) { - if(desktop()) - selection_display_message(desktop(), Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection.")); + if (desktop()) + selection_display_message(desktop(), Inkscape::ERROR_MESSAGE, + _("<b>No groups</b> to ungroup in the selection.")); return; } ungroup_impl(this); - if(document()) - DocumentUndo::done(document(), SP_VERB_SELECTION_UNGROUP, - _("Ungroup")); + if (document()) + DocumentUndo::done(document(), SP_VERB_SELECTION_UNGROUP, _("Ungroup")); } // TODO replace it with ObjectSet::degroup_list /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */ -std::vector<SPItem*> -sp_degroup_list(std::vector<SPItem*> &items) +std::vector<SPItem *> sp_degroup_list(std::vector<SPItem *> &items) { - std::vector<SPItem*> out; + std::vector<SPItem *> out; bool has_groups = false; for (auto item : items) { SPGroup *group = dynamic_cast<SPGroup *>(item); @@ -939,7 +916,7 @@ sp_degroup_list(std::vector<SPItem*> &items) out.push_back(item); } else { has_groups = true; - std::vector<SPItem*> members = sp_item_group_item_list(group); + std::vector<SPItem *> members = sp_item_group_item_list(group); for (auto member : members) { out.push_back(member); } @@ -954,10 +931,8 @@ sp_degroup_list(std::vector<SPItem*> &items) return out; } - /** If items in the list have a common parent, return it, otherwise return NULL */ -static SPGroup * -sp_item_list_common_parent_group(const SPItemRange &items) +static SPGroup *sp_item_list_common_parent_group(const SPItemRange &items) { if (items.empty()) { return nullptr; @@ -967,8 +942,9 @@ sp_item_list_common_parent_group(const SPItemRange &items) if (!dynamic_cast<SPGroup *>(parent)) { return nullptr; } - for (auto item=items.begin();item!=items.end();++item) { - if((*item)==items.front())continue; + for (auto item = items.begin(); item != items.end(); ++item) { + if ((*item) == items.front()) + continue; if ((*item)->parent != parent) { return nullptr; } @@ -978,8 +954,7 @@ sp_item_list_common_parent_group(const SPItemRange &items) } /** Finds out the minimum common bbox of the selected items. */ -static Geom::OptRect -enclose_items(std::vector<SPItem*> const &items) +static Geom::OptRect enclose_items(std::vector<SPItem *> const &items) { g_assert(!items.empty()); @@ -994,32 +969,34 @@ enclose_items(std::vector<SPItem*> const &items) static SPObject *prev_sibling(SPObject *child) { SPObject *prev = nullptr; - if ( child && dynamic_cast<SPGroup *>(child->parent) ) { + if (child && dynamic_cast<SPGroup *>(child->parent)) { prev = child->getPrev(); } return prev; } -void ObjectSet::raise(bool skip_undo){ - - if(isEmpty()){ +void ObjectSet::raise(bool skip_undo) +{ + if (isEmpty()) { selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise.")); return; } SPGroup const *group = sp_item_list_common_parent_group(items()); if (!group) { - if(desktop()) - selection_display_message(desktop(), Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>.")); + if (desktop()) + selection_display_message( + desktop(), Inkscape::ERROR_MESSAGE, + _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>.")); return; } - std::vector<SPItem*> items_copy(items().begin(), items().end()); + std::vector<SPItem *> items_copy(items().begin(), items().end()); Inkscape::XML::Node *grepr = const_cast<Inkscape::XML::Node *>(items_copy.front()->parent->getRepr()); /* Construct reverse-ordered list of selected children. */ - std::vector<SPItem*> rev(items_copy); - sort(rev.begin(),rev.end(),sp_item_repr_compare_position_bool); + std::vector<SPItem *> rev(items_copy); + sort(rev.begin(), rev.end(), sp_item_repr_compare_position_bool); // Determine the common bbox of the selected items. Geom::OptRect selected = enclose_items(items_copy); @@ -1033,9 +1010,9 @@ void ObjectSet::raise(bool skip_undo){ SPItem *newItem = dynamic_cast<SPItem *>(newref); if (newItem) { Geom::OptRect newref_bbox = newItem->documentVisualBounds(); - if ( newref_bbox && selected->intersects(*newref_bbox) ) { + if (newref_bbox && selected->intersects(*newref_bbox)) { // AND if it's not one of our selected objects, - if ( std::find(items_copy.begin(),items_copy.end(),newref)==items_copy.end()) { + if (std::find(items_copy.begin(), items_copy.end(), newref) == items_copy.end()) { // move the selected object after that sibling grepr->changeOrder(child->getRepr(), newref->getRepr()); } @@ -1045,63 +1022,64 @@ void ObjectSet::raise(bool skip_undo){ } } } - if(document() && !skip_undo) + if (document() && !skip_undo) DocumentUndo::done(document(), SP_VERB_SELECTION_RAISE, - //TRANSLATORS: "Raise" means "to raise an object" in the undo history - C_("Undo action", "Raise")); + // TRANSLATORS: "Raise" means "to raise an object" in the undo history + C_("Undo action", "Raise")); } - -void ObjectSet::raiseToTop(bool skip_undo) { - if(isEmpty()){ +void ObjectSet::raiseToTop(bool skip_undo) +{ + if (isEmpty()) { selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise.")); return; } SPGroup const *group = sp_item_list_common_parent_group(items()); if (!group) { - selection_display_message(desktop(), Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>.")); + selection_display_message(desktop(), Inkscape::ERROR_MESSAGE, + _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>.")); return; } - - std::vector<Inkscape::XML::Node*> rl(xmlNodes().begin(), xmlNodes().end()); - sort(rl.begin(),rl.end(),sp_repr_compare_position_bool); + std::vector<Inkscape::XML::Node *> rl(xmlNodes().begin(), xmlNodes().end()); + sort(rl.begin(), rl.end(), sp_repr_compare_position_bool); for (auto repr : rl) { repr->setPosition(-1); } if (document() && !skip_undo) { - DocumentUndo::done(document(), SP_VERB_SELECTION_TO_FRONT, - _("Raise to top")); + DocumentUndo::done(document(), SP_VERB_SELECTION_TO_FRONT, _("Raise to top")); } } -void ObjectSet::lower(bool skip_undo){ - if(isEmpty()){ +void ObjectSet::lower(bool skip_undo) +{ + if (isEmpty()) { selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower.")); return; } SPGroup const *group = sp_item_list_common_parent_group(items()); if (!group) { - selection_display_message(desktop(), Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>.")); + selection_display_message(desktop(), Inkscape::ERROR_MESSAGE, + _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>.")); return; } - std::vector<SPItem*> items_copy(items().begin(), items().end()); + std::vector<SPItem *> items_copy(items().begin(), items().end()); Inkscape::XML::Node *grepr = const_cast<Inkscape::XML::Node *>(items_copy.front()->parent->getRepr()); // Determine the common bbox of the selected items. Geom::OptRect selected = enclose_items(items_copy); /* Construct direct-ordered list of selected children. */ - std::vector<SPItem*> rev(items_copy); - sort(rev.begin(),rev.end(),sp_item_repr_compare_position_bool); + std::vector<SPItem *> rev(items_copy); + sort(rev.begin(), rev.end(), sp_item_repr_compare_position_bool); // Iterate over all objects in the selection (starting from top). if (selected) { - for (std::vector<SPItem*>::const_reverse_iterator item=rev.rbegin();item!=rev.rend();++item) { + for (std::vector<SPItem *>::const_reverse_iterator item = rev.rbegin(); item != rev.rend(); ++item) { SPObject *child = *item; // for each selected object, find the prev sibling for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) { @@ -1109,9 +1087,9 @@ void ObjectSet::lower(bool skip_undo){ SPItem *newItem = dynamic_cast<SPItem *>(newref); if (newItem) { Geom::OptRect ref_bbox = newItem->documentVisualBounds(); - if ( ref_bbox && selected->intersects(*ref_bbox) ) { + if (ref_bbox && selected->intersects(*ref_bbox)) { // AND if it's not one of our selected objects, - if (items_copy.end()==std::find(items_copy.begin(),items_copy.end(),newref)) { + if (items_copy.end() == std::find(items_copy.begin(), items_copy.end(), newref)) { // move the selected object before that sibling SPObject *put_after = prev_sibling(newref); if (put_after) @@ -1125,39 +1103,41 @@ void ObjectSet::lower(bool skip_undo){ } } } - if(document() && !skip_undo) + if (document() && !skip_undo) DocumentUndo::done(document(), SP_VERB_SELECTION_LOWER, - //TRANSLATORS: "Lower" means "to lower an object" in the undo history - C_("Undo action", "Lower")); + // TRANSLATORS: "Lower" means "to lower an object" in the undo history + C_("Undo action", "Lower")); } - -void ObjectSet::lowerToBottom(bool skip_undo){ - if(!document()) +void ObjectSet::lowerToBottom(bool skip_undo) +{ + if (!document()) return; if (isEmpty()) { - selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom.")); + selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, + _("Select <b>object(s)</b> to lower to bottom.")); return; } SPGroup const *group = sp_item_list_common_parent_group(items()); if (!group) { - selection_display_message(desktop(), Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>.")); + selection_display_message(desktop(), Inkscape::ERROR_MESSAGE, + _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>.")); return; } - std::vector<Inkscape::XML::Node*> rl(xmlNodes().begin(), xmlNodes().end()); - sort(rl.begin(),rl.end(),sp_repr_compare_position_bool); + std::vector<Inkscape::XML::Node *> rl(xmlNodes().begin(), xmlNodes().end()); + sort(rl.begin(), rl.end(), sp_repr_compare_position_bool); - for (std::vector<Inkscape::XML::Node*>::const_reverse_iterator l=rl.rbegin();l!=rl.rend();++l) { + for (std::vector<Inkscape::XML::Node *>::const_reverse_iterator l = rl.rbegin(); l != rl.rend(); ++l) { gint minpos; SPObject *pp; Inkscape::XML::Node *repr = (*l); pp = document()->getObjectByRepr(repr->parent()); minpos = 0; g_assert(dynamic_cast<SPGroup *>(pp)); - for (auto& pc: pp->children) { - if(dynamic_cast<SPItem *>(&pc)) { + for (auto &pc : pp->children) { + if (dynamic_cast<SPItem *>(&pc)) { break; } minpos += 1; @@ -1165,75 +1145,78 @@ void ObjectSet::lowerToBottom(bool skip_undo){ repr->setPosition(minpos); } if (document() && !skip_undo) { - DocumentUndo::done(document(), SP_VERB_SELECTION_TO_BACK, - _("Lower to bottom")); + DocumentUndo::done(document(), SP_VERB_SELECTION_TO_BACK, _("Lower to bottom")); } } -void ObjectSet::stackUp(bool skip_undo) { +void ObjectSet::stackUp(bool skip_undo) +{ if (isEmpty()) { selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to stack up.")); return; } - std::vector<SPItem*> selection(items().begin(), items().end()); + std::vector<SPItem *> selection(items().begin(), items().end()); sort(selection.begin(), selection.end(), sp_item_repr_compare_position_bool); - for (auto item: selection | boost::adaptors::reversed) { + for (auto item : selection | boost::adaptors::reversed) { if (!item->raiseOne()) { // stop if top was reached - if(document() && !skip_undo) + if (document() && !skip_undo) DocumentUndo::cancel(document()); selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("We hit top.")); return; } } - if(document() && !skip_undo) + if (document() && !skip_undo) DocumentUndo::done(document(), SP_VERB_SELECTION_STACK_UP, - //TRANSLATORS: undo history: "stack up" means to raise an object of its ordinal position by 1 - C_("Undo action", "stack up")); + // TRANSLATORS: undo history: "stack up" means to raise an object of its ordinal position by + // 1 + C_("Undo action", "stack up")); } -void ObjectSet::stackDown(bool skip_undo) { +void ObjectSet::stackDown(bool skip_undo) +{ if (isEmpty()) { selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to stack down.")); return; } - std::vector<SPItem*> selection(items().begin(), items().end()); + std::vector<SPItem *> selection(items().begin(), items().end()); sort(selection.begin(), selection.end(), sp_item_repr_compare_position_bool); - for (auto item: selection) { + for (auto item : selection) { if (!item->lowerOne()) { // stop if bottom was reached - if(document() && !skip_undo) + if (document() && !skip_undo) DocumentUndo::cancel(document()); selection_display_message(desktop(), Inkscape::WARNING_MESSAGE, _("We hit bottom.")); return; } } - if(document() && !skip_undo) + if (document() && !skip_undo) DocumentUndo::done(document(), SP_VERB_SELECTION_STACK_DOWN, - //TRANSLATORS: undo history: "stack down" means to lower an object of its ordinal position by 1 - C_("Undo action", "stack down")); + // TRANSLATORS: undo history: "stack down" means to lower an object of its ordinal position + // by 1 + C_("Undo action", "stack down")); } -void -sp_undo(SPDesktop *desktop, SPDocument *) +void sp_undo(SPDesktop *desktop, SPDocument *) { // No re/undo while dragging, too dangerous. - if (desktop->getCanvas()->is_dragging()) return; + if (desktop->getCanvas()->is_dragging()) + return; if (!DocumentUndo::undo(desktop->getDocument())) { desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo.")); } } -void -sp_redo(SPDesktop *desktop, SPDocument *) +void sp_redo(SPDesktop *desktop, SPDocument *) { // No re/undo while dragging, too dangerous. - if (desktop->getCanvas()->is_dragging()) return; + if (desktop->getCanvas()->is_dragging()) + return; if (!DocumentUndo::redo(desktop->getDocument())) { desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo.")); @@ -1249,8 +1232,7 @@ void ObjectSet::cut() /** * \pre item != NULL */ -SPCSSAttr * -take_style_from_item(SPObject *object) +SPCSSAttr *take_style_from_item(SPObject *object) { // CPPIFY: // This function should only take SPItems, but currently SPString is not an Item. @@ -1265,8 +1247,8 @@ take_style_from_item(SPObject *object) // if this is a text with exactly one tspan child, merge the style of that tspan as well // If this is a group, merge the style of its topmost (last) child with style auto list = object->children | boost::adaptors::reversed; - for (auto& element: list) { - if (element.style ) { + for (auto &element : list) { + if (element.style) { SPCSSAttr *temp = sp_css_attr_from_object(&element, SP_STYLE_FLAG_IFSET); if (temp) { sp_repr_css_merge(css, temp); @@ -1280,12 +1262,12 @@ take_style_from_item(SPObject *object) // Remove black-listed properties (those that should not be used in a default style) css = sp_css_attr_unset_blacklist(css); - if (!(dynamic_cast<SPText *>(object) || dynamic_cast<SPTSpan *>(object) || dynamic_cast<SPTRef *>(object) || dynamic_cast<SPString *>(object))) { + if (!(dynamic_cast<SPText *>(object) || dynamic_cast<SPTSpan *>(object) || dynamic_cast<SPTRef *>(object) || + dynamic_cast<SPString *>(object))) { // do not copy text properties from non-text objects, it's confusing css = sp_css_attr_unset_text(css); } - SPItem *item = dynamic_cast<SPItem *>(object); if (item) { // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive @@ -1324,16 +1306,14 @@ void ObjectSet::pastePathEffect() { Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); if (cm->pastePathEffect(this)) { - DocumentUndo::done(document(), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT, - _("Paste live path effect")); + DocumentUndo::done(document(), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT, _("Paste live path effect")); } } - static void sp_selection_remove_livepatheffect_impl(SPItem *item) { - if ( SPLPEItem *lpeitem = dynamic_cast<SPLPEItem*>(item) ) { - if ( lpeitem->hasPathEffect() ) { + if (SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(item)) { + if (lpeitem->hasPathEffect()) { lpeitem->removeAllPathEffects(false); } } @@ -1341,33 +1321,31 @@ static void sp_selection_remove_livepatheffect_impl(SPItem *item) void ObjectSet::removeLPE() { - // check if something is selected if (isEmpty()) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>object(s)</b> to remove live path effects from.")); return; } - auto list= items(); - for (auto itemlist=list.begin();itemlist!=list.end();++itemlist) { + auto list = items(); + for (auto itemlist = list.begin(); itemlist != list.end(); ++itemlist) { SPItem *item = *itemlist; sp_selection_remove_livepatheffect_impl(item); - } - if(document()) - DocumentUndo::done(document(), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT, - _("Remove live path effect")); + if (document()) + DocumentUndo::done(document(), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT, _("Remove live path effect")); } void ObjectSet::removeFilter() { - // check if something is selected if (isEmpty()) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>object(s)</b> to remove filters from.")); return; } @@ -1375,18 +1353,15 @@ void ObjectSet::removeFilter() sp_repr_css_unset_property(css, "filter"); sp_desktop_set_style(this, desktop(), css); sp_repr_css_attr_unref(css); - if(document()) - DocumentUndo::done(document(), SP_VERB_EDIT_REMOVE_FILTER, - _("Remove filter")); + if (document()) + DocumentUndo::done(document(), SP_VERB_EDIT_REMOVE_FILTER, _("Remove filter")); } - void ObjectSet::pasteSize(bool apply_x, bool apply_y) { Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); if (cm->pasteSize(this, false, apply_x, apply_y)) { - DocumentUndo::done(document(), SP_VERB_EDIT_PASTE_SIZE, - _("Paste size")); + DocumentUndo::done(document(), SP_VERB_EDIT_PASTE_SIZE, _("Paste size")); } } @@ -1394,8 +1369,7 @@ void ObjectSet::pasteSizeSeparately(bool apply_x, bool apply_y) { Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); if (cm->pasteSize(this, true, apply_x, apply_y)) { - DocumentUndo::done(document(), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY, - _("Paste size separately")); + DocumentUndo::done(document(), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY, _("Paste size separately")); } } @@ -1403,24 +1377,23 @@ void ObjectSet::pasteSizeSeparately(bool apply_x, bool apply_y) * Ensures that the clones of objects are not modified when moving objects between layers. * Calls the same function as ungroup */ -void sp_selection_change_layer_maintain_clones(std::vector<SPItem*> const &items,SPObject *where) +void sp_selection_change_layer_maintain_clones(std::vector<SPItem *> const &items, SPObject *where) { for (auto item : items) { if (item) { SPItem *oldparent = dynamic_cast<SPItem *>(item->parent); SPItem *newparent = dynamic_cast<SPItem *>(where); sp_item_group_ungroup_handle_clones(item, - (oldparent->i2doc_affine()) - *((newparent->i2doc_affine()).inverse())); + (oldparent->i2doc_affine()) * ((newparent->i2doc_affine()).inverse())); } } } void ObjectSet::toNextLayer(bool skip_undo) { - if(!desktop()) + if (!desktop()) return; - SPDesktop *dt=desktop(); //TODO make it desktop-independent + SPDesktop *dt = desktop(); // TODO make it desktop-independent // check if something is selected if (isEmpty()) { @@ -1428,18 +1401,19 @@ void ObjectSet::toNextLayer(bool skip_undo) return; } - std::vector<SPItem*> items_copy(items().begin(), items().end()); + std::vector<SPItem *> items_copy(items().begin(), items().end()); bool no_more = false; // Set to true, if no more layers above - SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); + SPObject *next = Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); if (next) { clear(); - sp_selection_change_layer_maintain_clones(items_copy,next); - std::vector<Inkscape::XML::Node*> temp_clip; + sp_selection_change_layer_maintain_clones(items_copy, next); + std::vector<Inkscape::XML::Node *> temp_clip; sp_selection_copy_impl(items_copy, temp_clip, dt->doc()->getReprDoc()); sp_selection_delete_impl(items_copy, false, false); - next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers - std::vector<Inkscape::XML::Node*> copied; + next = + Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers + std::vector<Inkscape::XML::Node *> copied; if (next) { copied = sp_selection_paste_impl(dt->getDocument(), next, temp_clip); } else { @@ -1447,10 +1421,10 @@ void ObjectSet::toNextLayer(bool skip_undo) no_more = true; } setReprList(copied); - if (next) dt->setCurrentLayer(next); - if ( !skip_undo ) { - DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_MOVE_TO_NEXT, - _("Raise to next layer")); + if (next) + dt->setCurrentLayer(next); + if (!skip_undo) { + DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_MOVE_TO_NEXT, _("Raise to next layer")); } } else { no_more = true; @@ -1459,14 +1433,13 @@ void ObjectSet::toNextLayer(bool skip_undo) if (no_more) { dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above.")); } - } void ObjectSet::toPrevLayer(bool skip_undo) { - if(!desktop()) + if (!desktop()) return; - SPDesktop *dt=desktop(); //TODO make it desktop-independent + SPDesktop *dt = desktop(); // TODO make it desktop-independent // check if something is selected if (isEmpty()) { @@ -1474,29 +1447,31 @@ void ObjectSet::toPrevLayer(bool skip_undo) return; } - std::vector<SPItem*> items_copy(items().begin(), items().end()); + std::vector<SPItem *> items_copy(items().begin(), items().end()); bool no_more = false; // Set to true, if no more layers below - SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); + SPObject *next = Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); if (next) { clear(); - sp_selection_change_layer_maintain_clones(items_copy,next); - std::vector<Inkscape::XML::Node*> temp_clip; - sp_selection_copy_impl(items_copy, temp_clip, dt->doc()->getReprDoc()); // we're in the same doc, so no need to copy defs + sp_selection_change_layer_maintain_clones(items_copy, next); + std::vector<Inkscape::XML::Node *> temp_clip; + sp_selection_copy_impl(items_copy, temp_clip, + dt->doc()->getReprDoc()); // we're in the same doc, so no need to copy defs sp_selection_delete_impl(items_copy, false, false); - next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers - std::vector<Inkscape::XML::Node*> copied; + next = Inkscape::previous_layer(dt->currentRoot(), + dt->currentLayer()); // Fixes bug 1482973: crash while moving layers + std::vector<Inkscape::XML::Node *> copied; if (next) { copied = sp_selection_paste_impl(dt->getDocument(), next, temp_clip); } else { copied = sp_selection_paste_impl(dt->getDocument(), dt->currentLayer(), temp_clip); no_more = true; } - setReprList( copied); - if (next) dt->setCurrentLayer(next); - if ( !skip_undo ) { - DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_MOVE_TO_PREV, - _("Lower to previous layer")); + setReprList(copied); + if (next) + dt->setCurrentLayer(next); + if (!skip_undo) { + DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_MOVE_TO_PREV, _("Lower to previous layer")); } } else { no_more = true; @@ -1509,46 +1484,46 @@ void ObjectSet::toPrevLayer(bool skip_undo) void ObjectSet::toLayer(SPObject *moveto, bool skip_undo) { - if(!document()) + if (!document()) return; SPDesktop *dt = desktop(); // check if something is selected if (isEmpty()) { - if(dt) + if (dt) dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move.")); return; } - std::vector<SPItem*> items_copy(items().begin(), items().end()); + std::vector<SPItem *> items_copy(items().begin(), items().end()); if (moveto) { clear(); - sp_selection_change_layer_maintain_clones(items_copy,moveto); - std::vector<Inkscape::XML::Node*> temp_clip; - sp_selection_copy_impl(items_copy, temp_clip, document()->getReprDoc()); // we're in the same doc, so no need to copy defs + sp_selection_change_layer_maintain_clones(items_copy, moveto); + std::vector<Inkscape::XML::Node *> temp_clip; + sp_selection_copy_impl(items_copy, temp_clip, + document()->getReprDoc()); // we're in the same doc, so no need to copy defs sp_selection_delete_impl(items_copy, false, false); - std::vector<Inkscape::XML::Node*> copied = sp_selection_paste_impl(document(), moveto, temp_clip); + std::vector<Inkscape::XML::Node *> copied = sp_selection_paste_impl(document(), moveto, temp_clip); setReprList(copied); - if (!temp_clip.empty()) temp_clip.clear(); - if (moveto && dt) dt->setCurrentLayer(moveto); - if ( !skip_undo ) { - DocumentUndo::done(document(), SP_VERB_LAYER_MOVE_TO, - _("Move selection to layer")); + if (!temp_clip.empty()) + temp_clip.clear(); + if (moveto && dt) + dt->setCurrentLayer(moveto); + if (!skip_undo) { + DocumentUndo::done(document(), SP_VERB_LAYER_MOVE_TO, _("Move selection to layer")); } } } -static bool -object_set_contains_original(SPItem *item, ObjectSet *set) +static bool object_set_contains_original(SPItem *item, ObjectSet *set) { bool contains_original = false; SPItem *item_use = item; SPItem *item_use_first = item; SPUse *use = dynamic_cast<SPUse *>(item_use); - while (use && item_use && !contains_original) - { + while (use && item_use && !contains_original) { item_use = use->get_original(); use = dynamic_cast<SPUse *>(item_use); contains_original |= set->includes(item_use); @@ -1566,13 +1541,11 @@ object_set_contains_original(SPItem *item, ObjectSet *set) return contains_original; } - -static bool -object_set_contains_both_clone_and_original(ObjectSet *set) +static bool object_set_contains_both_clone_and_original(ObjectSet *set) { bool clone_with_original = false; auto items = set->items(); - for (auto l=items.begin();l!=items.end() ;++l) { + for (auto l = items.begin(); l != items.end(); ++l) { SPItem *item = *l; if (item) { clone_with_original |= object_set_contains_original(item, set); @@ -1590,8 +1563,7 @@ that case, items are already in the new position, but the repr is in the old, an then simply updates the repr from item->transform. */ -void ObjectSet::applyAffine(Geom::Affine const &affine, bool set_i2d, bool compensate, - bool adjust_transf_center) +void ObjectSet::applyAffine(Geom::Affine const &affine, bool set_i2d, bool compensate, bool adjust_transf_center) { if (isEmpty()) return; @@ -1601,16 +1573,16 @@ void ObjectSet::applyAffine(Geom::Affine const &affine, bool set_i2d, bool compe Persp3D *persp; Persp3D *transf_persp; std::list<Persp3D *> plist = perspList(); - for (auto & i : plist) { - persp = (Persp3D *) i; + for (auto &i : plist) { + persp = (Persp3D *)i; - if (!persp->has_all_boxes_in_selection (this)) { + if (!persp->has_all_boxes_in_selection(this)) { std::list<SPBox3D *> selboxes = box3DList(persp); // create a new perspective as a copy of the current one and link the selected boxes to it - transf_persp = Persp3D::create_xml_element (persp->document, persp->perspective_impl); + transf_persp = Persp3D::create_xml_element(persp->document, persp->perspective_impl); - for (auto & selboxe : selboxes) + for (auto &selboxe : selboxes) selboxe->switch_perspectives(persp, transf_persp); } else { transf_persp = persp; @@ -1619,22 +1591,22 @@ void ObjectSet::applyAffine(Geom::Affine const &affine, bool set_i2d, bool compe transf_persp->apply_affine_transformation(affine); } auto items_copy = items(); - for (auto l=items_copy.begin();l!=items_copy.end() ;++l) { + for (auto l = items_copy.begin(); l != items_copy.end(); ++l) { SPItem *item = *l; - if( dynamic_cast<SPRoot *>(item) ) { + if (dynamic_cast<SPRoot *>(item)) { // An SVG element cannot have a transform. We could change 'x' and 'y' in response // to a translation... but leave that for another day. - if(desktop()) + if (desktop()) desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Cannot transform an embedded SVG.")); break; } - Geom::Point old_center(0,0); + Geom::Point old_center(0, 0); if (set_i2d && item->isCenterSet()) old_center = item->getCenter(); -#if 0 /* Re-enable this once persistent guides have a graphical indication. +#if 0 /* Re-enable this once persistent guides have a graphical indication. \ At the time of writing, this is the only place to re-enable. */ sp_item_update_cns(*item, desktop()); #endif @@ -1643,14 +1615,19 @@ void ObjectSet::applyAffine(Geom::Affine const &affine, bool set_i2d, bool compe bool transform_clone_with_original = object_set_contains_original(item, this); // ...both a text-on-path and its path? - bool transform_textpath_with_path = ((dynamic_cast<SPText *>(item) && item->firstChild() && dynamic_cast<SPTextPath *>(item->firstChild())) - && includes( sp_textpath_get_path_item(dynamic_cast<SPTextPath *>(item->firstChild())) )); + bool transform_textpath_with_path = + ((dynamic_cast<SPText *>(item) && item->firstChild() && dynamic_cast<SPTextPath *>(item->firstChild())) && + includes(sp_textpath_get_path_item(dynamic_cast<SPTextPath *>(item->firstChild())))); // ...both a flowtext and its frame? - bool transform_flowtext_with_frame = (dynamic_cast<SPFlowtext *>(item) && includes( dynamic_cast<SPFlowtext *>(item)->get_frame(nullptr))); // (only the first frame is checked so far) + bool transform_flowtext_with_frame = + (dynamic_cast<SPFlowtext *>(item) && includes(dynamic_cast<SPFlowtext *>(item)->get_frame( + nullptr))); // (only the first frame is checked so far) // ...both an offset and its source? - bool transform_offset_with_source = (dynamic_cast<SPOffset *>(item) && dynamic_cast<SPOffset *>(item)->sourceHref) && includes( sp_offset_get_source(dynamic_cast<SPOffset *>(item)) ); + bool transform_offset_with_source = + (dynamic_cast<SPOffset *>(item) && dynamic_cast<SPOffset *>(item)->sourceHref) && + includes(sp_offset_get_source(dynamic_cast<SPOffset *>(item))); // If we're moving a connector, we want to detach it // from shapes that aren't part of the selection, but @@ -1689,11 +1666,11 @@ void ObjectSet::applyAffine(Geom::Affine const &affine, bool set_i2d, bool compe } else if (transform_flowtext_with_frame) { // apply the inverse of the region's transform to the <use> so that the flow remains // the same (even though the output itself gets transformed) - for (auto& region: item->children) { + for (auto ®ion : item->children) { if (dynamic_cast<SPFlowregion *>(®ion) || dynamic_cast<SPFlowregionExclude *>(®ion)) { - for (auto& itm: region.children) { + for (auto &itm : region.children) { SPUse *use = dynamic_cast<SPUse *>(&itm); - if ( use ) { + if (use) { use->doWriteTransform(item->transform.inverse(), nullptr, compensate); } } @@ -1741,13 +1718,13 @@ void ObjectSet::applyAffine(Geom::Affine const &affine, bool set_i2d, bool compe item->doWriteTransform(move, &move, compensate); } else if (prefs_unmoved) { - //if (dynamic_cast<SPUse *>(sp_use_get_original(dynamic_cast<SPUse *>(item)))) + // if (dynamic_cast<SPUse *>(sp_use_get_original(dynamic_cast<SPUse *>(item)))) // clone_move = Geom::identity(); Geom::Affine move = result * clone_move; item->doWriteTransform(move, &t, compensate); } - } else if (transform_offset_with_source && (prefs_parallel || prefs_unmoved) && affine.isTranslation()){ + } else if (transform_offset_with_source && (prefs_parallel || prefs_unmoved) && affine.isTranslation()) { Geom::Affine parent = item->transform; Geom::Affine offset_move = parent.inverse() * t * parent; @@ -1772,7 +1749,8 @@ void ObjectSet::applyAffine(Geom::Affine const &affine, bool set_i2d, bool compe item->doWriteTransform(item->transform, nullptr, compensate); } - if (adjust_transf_center) { // The transformation center should not be touched in case of pasting or importing, which is allowed by this if clause + if (adjust_transf_center) { // The transformation center should not be touched in case of pasting or importing, + // which is allowed by this if clause // if we're moving the actual object, not just updating the repr, we can transform the // center by the same matrix (only necessary for non-translations) if (set_i2d && item->isCenterSet() && !(affine.isTranslation() || affine.isIdentity())) { @@ -1786,32 +1764,30 @@ void ObjectSet::applyAffine(Geom::Affine const &affine, bool set_i2d, bool compe void ObjectSet::removeTransform() { auto items = xmlNodes(); - for (auto l=items.begin();l!=items.end() ;++l) { + for (auto l = items.begin(); l != items.end(); ++l) { (*l)->removeAttribute("transform"); } - if(document()) - DocumentUndo::done(document(), SP_VERB_OBJECT_FLATTEN, - _("Remove transform")); + if (document()) + DocumentUndo::done(document(), SP_VERB_OBJECT_FLATTEN, _("Remove transform")); } -void ObjectSet::setScaleAbsolute(double x0, double x1,double y0, double y1) +void ObjectSet::setScaleAbsolute(double x0, double x1, double y0, double y1) { if (isEmpty()) return; Geom::OptRect bbox = visualBounds(); - if ( !bbox ) { + if (!bbox) { return; } Geom::Translate const p2o(-bbox->min()); - Geom::Scale const newSize(x1 - x0, - y1 - y0); - Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() ); + Geom::Scale const newSize(x1 - x0, y1 - y0); + Geom::Scale const scale(newSize * Geom::Scale(bbox->dimensions()).inverse()); Geom::Translate const o2n(x0, y0); - Geom::Affine const final( p2o * scale * o2n ); + Geom::Affine const final(p2o * scale * o2n); applyAffine(final); } @@ -1823,20 +1799,19 @@ void ObjectSet::setScaleRelative(Geom::Point const &align, Geom::Scale const &sc Geom::OptRect bbox = visualBounds(); - if ( !bbox ) { + if (!bbox) { return; } - // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway - if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6 || - bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 ) - { + // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later + // anyway + if (bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6 || bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6) { return; } Geom::Translate const n2d(-align); Geom::Translate const d2n(align); - Geom::Affine const final( n2d * scale * d2n ); + Geom::Affine const final(n2d * scale * d2n); applyAffine(final); } @@ -1845,7 +1820,7 @@ void ObjectSet::rotateRelative(Geom::Point const ¢er, double angle_degrees) Geom::Translate const d2n(center); Geom::Translate const n2d(-center); Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees)); - Geom::Affine const final( Geom::Affine(n2d) * rotate * d2n ); + Geom::Affine const final(Geom::Affine(n2d) * rotate * d2n); applyAffine(final); } @@ -1853,10 +1828,8 @@ void ObjectSet::skewRelative(Geom::Point const &align, double dx, double dy) { Geom::Translate const d2n(align); Geom::Translate const n2d(-align); - Geom::Affine const skew(1, dy, - dx, 1, - 0, 0); - Geom::Affine const final( n2d * skew * d2n ); + Geom::Affine const skew(1, dy, dx, 1, 0, 0); + Geom::Affine const final(n2d * skew * d2n); applyAffine(final); } @@ -1880,8 +1853,9 @@ void ObjectSet::rotate90(bool ccw) auto items_copy = items(); double y_dir = document() ? document()->yaxisdir() : 1; - Geom::Rotate const rot_90(Geom::Point(0, ccw ? -y_dir : y_dir)); // pos. or neg. rotation, depending on the value of ccw - for (auto l=items_copy.begin();l!=items_copy.end() ;++l) { + Geom::Rotate const rot_90(Geom::Point(0, ccw ? -y_dir : y_dir)); // pos. or neg. rotation, depending on the value of + // ccw + for (auto l = items_copy.begin(); l != items_copy.end(); ++l) { SPItem *item = *l; if (item) { item->rotate_rel(rot_90); @@ -1891,8 +1865,7 @@ void ObjectSet::rotate90(bool ccw) } if (document()) - DocumentUndo::done(document(), - ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW, + DocumentUndo::done(document(), ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW, ccw ? _("Rotate 90\xc2\xb0 CCW") : _("Rotate 90\xc2\xb0 CW")); } @@ -1908,12 +1881,8 @@ void ObjectSet::rotate(gdouble const angle_degrees) rotateRelative(*center_, angle_degrees); if (document()) - DocumentUndo::maybeDone(document(), - ( ( angle_degrees > 0 ) - ? "selector:rotate:ccw" - : "selector:rotate:cw" ), - SP_VERB_CONTEXT_SELECT, - _("Rotate")); + DocumentUndo::maybeDone(document(), ((angle_degrees > 0) ? "selector:rotate:ccw" : "selector:rotate:cw"), + SP_VERB_CONTEXT_SELECT, _("Rotate")); } /* @@ -1938,45 +1907,41 @@ void sp_select_same_fill_stroke_style(SPDesktop *desktop, gboolean fill, gboolea bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true); bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true); bool ingroups = TRUE; - std::vector<SPItem*> x,y; - std::vector<SPItem*> all_list = get_all_items(x, desktop->currentRoot(), desktop, onlyvisible, onlysensitive, ingroups, y); - std::vector<SPItem*> all_matches; + std::vector<SPItem *> x, y; + std::vector<SPItem *> all_list = + get_all_items(x, desktop->currentRoot(), desktop, onlyvisible, onlysensitive, ingroups, y); + std::vector<SPItem *> all_matches; Inkscape::Selection *selection = desktop->getSelection(); auto items = selection->items(); - std::vector<SPItem*> tmp; + std::vector<SPItem *> tmp; for (auto iter : all_list) { - if(!SP_IS_GROUP(iter)){ + if (!SP_IS_GROUP(iter)) { tmp.push_back(iter); } } - all_list=tmp; + all_list = tmp; - for (auto sel_iter=items.begin();sel_iter!=items.end();++sel_iter) { + for (auto sel_iter = items.begin(); sel_iter != items.end(); ++sel_iter) { SPItem *sel = *sel_iter; - std::vector<SPItem*> matches = all_list; + std::vector<SPItem *> matches = all_list; if (fill && stroke && style) { matches = sp_get_same_style(sel, matches); - } - else if (fill) { + } else if (fill) { matches = sp_get_same_style(sel, matches, SP_FILL_COLOR); - } - else if (stroke) { + } else if (stroke) { matches = sp_get_same_style(sel, matches, SP_STROKE_COLOR); + } else if (style) { + matches = sp_get_same_style(sel, matches, SP_STROKE_STYLE_ALL); } - else if (style) { - matches = sp_get_same_style(sel, matches,SP_STROKE_STYLE_ALL); - } - all_matches.insert(all_matches.end(), matches.begin(),matches.end()); + all_matches.insert(all_matches.end(), matches.begin(), matches.end()); } selection->clear(); selection->setList(all_matches); - } - /* * Selects all the visible items with the same object type as the items in the current selection * @@ -1989,19 +1954,19 @@ void sp_select_same_object_type(SPDesktop *desktop) return; } - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true); bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true); bool ingroups = TRUE; - std::vector<SPItem*> x,y; - std::vector<SPItem*> all_list = get_all_items(x, desktop->currentRoot(), desktop, onlyvisible, onlysensitive, ingroups, y); - std::vector<SPItem*> matches = all_list; + std::vector<SPItem *> x, y; + std::vector<SPItem *> all_list = + get_all_items(x, desktop->currentRoot(), desktop, onlyvisible, onlysensitive, ingroups, y); + std::vector<SPItem *> matches = all_list; Inkscape::Selection *selection = desktop->getSelection(); - auto items= selection->items(); - for (auto sel_iter=items.begin();sel_iter!=items.end();++sel_iter) { + auto items = selection->items(); + for (auto sel_iter = items.begin(); sel_iter != items.end(); ++sel_iter) { SPItem *sel = *sel_iter; if (sel) { matches = sp_get_same_object_type(sel, matches); @@ -2012,23 +1977,21 @@ void sp_select_same_object_type(SPDesktop *desktop) selection->clear(); selection->setList(matches); - } - - /* * Find all items in src list that have the same fill or stroke style as sel * Return the list of matching items */ -std::vector<SPItem*> sp_get_same_fill_or_stroke_color(SPItem *sel, std::vector<SPItem*> &src, SPSelectStrokeStyleType type) +std::vector<SPItem *> sp_get_same_fill_or_stroke_color(SPItem *sel, std::vector<SPItem *> &src, + SPSelectStrokeStyleType type) { - std::vector<SPItem*> matches ; + std::vector<SPItem *> matches; gboolean match = false; SPIPaint *sel_paint = sel->style->getFillOrStroke(type == SP_FILL_COLOR); - for (std::vector<SPItem*>::const_reverse_iterator i=src.rbegin();i!=src.rend();++i) { + for (std::vector<SPItem *>::const_reverse_iterator i = src.rbegin(); i != src.rend(); ++i) { SPItem *iter = *i; if (iter) { SPIPaint *iter_paint = iter->style->getFillOrStroke(type == SP_FILL_COLOR); @@ -2037,17 +2000,17 @@ std::vector<SPItem*> sp_get_same_fill_or_stroke_color(SPItem *sel, std::vector<S && (sel_paint->value.color.toRGBA32(1.0) == iter_paint->value.color.toRGBA32(1.0))) { match = true; } else if (sel_paint->isPaintserver() && iter_paint->isPaintserver()) { - SPPaintServer *sel_server = (type == SP_FILL_COLOR) ? sel->style->getFillPaintServer() : sel->style->getStrokePaintServer(); SPPaintServer *iter_server = (type == SP_FILL_COLOR) ? iter->style->getFillPaintServer() : iter->style->getStrokePaintServer(); if ((dynamic_cast<SPLinearGradient *>(sel_server) || dynamic_cast<SPRadialGradient *>(sel_server) || - (dynamic_cast<SPGradient *>(sel_server) && dynamic_cast<SPGradient *>(sel_server)->getVector()->isSwatch())) - && + (dynamic_cast<SPGradient *>(sel_server) && + dynamic_cast<SPGradient *>(sel_server)->getVector()->isSwatch())) && (dynamic_cast<SPLinearGradient *>(iter_server) || dynamic_cast<SPRadialGradient *>(iter_server) || - (dynamic_cast<SPGradient *>(iter_server) && dynamic_cast<SPGradient *>(iter_server)->getVector()->isSwatch()))) { + (dynamic_cast<SPGradient *>(iter_server) && + dynamic_cast<SPGradient *>(iter_server)->getVector()->isSwatch()))) { SPGradient *sel_vector = dynamic_cast<SPGradient *>(sel_server)->getVector(); SPGradient *iter_vector = dynamic_cast<SPGradient *>(iter_server)->getVector(); if (sel_vector == iter_vector) { @@ -2078,16 +2041,16 @@ std::vector<SPItem*> sp_get_same_fill_or_stroke_color(SPItem *sel, std::vector<S return matches; } -static bool item_type_match (SPItem *i, SPItem *j) +static bool item_type_match(SPItem *i, SPItem *j) { - if ( dynamic_cast<SPRect *>(i)) { - return ( dynamic_cast<SPRect *>(j) ); + if (dynamic_cast<SPRect *>(i)) { + return (dynamic_cast<SPRect *>(j)); } else if (dynamic_cast<SPGenericEllipse *>(i)) { return (dynamic_cast<SPGenericEllipse *>(j)); } else if (dynamic_cast<SPStar *>(i) || dynamic_cast<SPPolygon *>(i)) { - return (dynamic_cast<SPStar *>(j) || dynamic_cast<SPPolygon *>(j)) ; + return (dynamic_cast<SPStar *>(j) || dynamic_cast<SPPolygon *>(j)); } else if (dynamic_cast<SPSpiral *>(i)) { return (dynamic_cast<SPSpiral *>(j)); @@ -2095,21 +2058,22 @@ static bool item_type_match (SPItem *i, SPItem *j) } else if (dynamic_cast<SPPath *>(i) || dynamic_cast<SPLine *>(i) || dynamic_cast<SPPolyLine *>(i)) { return (dynamic_cast<SPPath *>(j) || dynamic_cast<SPLine *>(j) || dynamic_cast<SPPolyLine *>(j)); - } else if (dynamic_cast<SPText *>(i) || dynamic_cast<SPFlowtext *>(i) || dynamic_cast<SPTSpan *>(i) || dynamic_cast<SPTRef *>(i) || dynamic_cast<SPString *>(i)) { - return (dynamic_cast<SPText *>(j) || dynamic_cast<SPFlowtext *>(j) || dynamic_cast<SPTSpan *>(j) || dynamic_cast<SPTRef *>(j) || dynamic_cast<SPString *>(j)); + } else if (dynamic_cast<SPText *>(i) || dynamic_cast<SPFlowtext *>(i) || dynamic_cast<SPTSpan *>(i) || + dynamic_cast<SPTRef *>(i) || dynamic_cast<SPString *>(i)) { + return (dynamic_cast<SPText *>(j) || dynamic_cast<SPFlowtext *>(j) || dynamic_cast<SPTSpan *>(j) || + dynamic_cast<SPTRef *>(j) || dynamic_cast<SPString *>(j)); - } else if (dynamic_cast<SPUse *>(i)) { - return (dynamic_cast<SPUse *>(j)) ; + } else if (dynamic_cast<SPUse *>(i)) { + return (dynamic_cast<SPUse *>(j)); } else if (dynamic_cast<SPImage *>(i)) { return (dynamic_cast<SPImage *>(j)); - } else if (dynamic_cast<SPOffset *>(i) && dynamic_cast<SPOffset *>(i)->sourceHref) { // Linked offset + } else if (dynamic_cast<SPOffset *>(i) && dynamic_cast<SPOffset *>(i)->sourceHref) { // Linked offset return (dynamic_cast<SPOffset *>(j) && dynamic_cast<SPOffset *>(j)->sourceHref); - } else if (dynamic_cast<SPOffset *>(i) && !dynamic_cast<SPOffset *>(i)->sourceHref) { // Dynamic offset + } else if (dynamic_cast<SPOffset *>(i) && !dynamic_cast<SPOffset *>(i)->sourceHref) { // Dynamic offset return (dynamic_cast<SPOffset *>(j) && !dynamic_cast<SPOffset *>(j)->sourceHref); - } return false; @@ -2119,11 +2083,11 @@ static bool item_type_match (SPItem *i, SPItem *j) * Find all items in src list that have the same object type as sel by type * Return the list of matching items */ -std::vector<SPItem*> sp_get_same_object_type(SPItem *sel, std::vector<SPItem*> &src) +std::vector<SPItem *> sp_get_same_object_type(SPItem *sel, std::vector<SPItem *> &src) { - std::vector<SPItem*> matches; + std::vector<SPItem *> matches; - for (std::vector<SPItem*>::const_reverse_iterator i=src.rbegin();i!=src.rend();++i) { + for (std::vector<SPItem *>::const_reverse_iterator i = src.rbegin(); i != src.rend(); ++i) { SPItem *item = *i; if (item && item_type_match(sel, item) && !item->cloned) { matches.push_back(item); @@ -2136,9 +2100,9 @@ std::vector<SPItem*> sp_get_same_object_type(SPItem *sel, std::vector<SPItem*> & * Find all items in src list that have the same stroke style as sel by type * Return the list of matching items */ -std::vector<SPItem*> sp_get_same_style(SPItem *sel, std::vector<SPItem*> &src, SPSelectStrokeStyleType type) +std::vector<SPItem *> sp_get_same_style(SPItem *sel, std::vector<SPItem *> &src, SPSelectStrokeStyleType type) { - std::vector<SPItem*> matches; + std::vector<SPItem *> matches; bool match = false; SPStyle *sel_style = sel->style; @@ -2154,27 +2118,27 @@ std::vector<SPItem*> sp_get_same_style(SPItem *sel, std::vector<SPItem*> &src, S * Stroke width needs to handle transformations, so call this function * to get the transformed stroke width */ - std::vector<SPItem*> objects; + std::vector<SPItem *> objects; SPStyle *sel_style_for_width = nullptr; - if (type == SP_STROKE_STYLE_WIDTH || type == SP_STROKE_STYLE_ALL || type==SP_STYLE_ALL ) { + if (type == SP_STROKE_STYLE_WIDTH || type == SP_STROKE_STYLE_ALL || type == SP_STYLE_ALL) { objects.push_back(sel); sel_style_for_width = new SPStyle(SP_ACTIVE_DOCUMENT); - objects_query_strokewidth (objects, sel_style_for_width); + objects_query_strokewidth(objects, sel_style_for_width); } bool match_g; for (auto iter : src) { if (iter) { - match_g=true; + match_g = true; SPStyle *iter_style = iter->style; match = true; - if (type == SP_STROKE_STYLE_WIDTH|| type == SP_STROKE_STYLE_ALL|| type==SP_STYLE_ALL) { + if (type == SP_STROKE_STYLE_WIDTH || type == SP_STROKE_STYLE_ALL || type == SP_STYLE_ALL) { match = (sel_style->stroke_width.set == iter_style->stroke_width.set); if (sel_style->stroke_width.set && iter_style->stroke_width.set) { - std::vector<SPItem*> objects; - objects.insert(objects.begin(),iter); + std::vector<SPItem *> objects; + objects.insert(objects.begin(), iter); SPStyle tmp_style(SP_ACTIVE_DOCUMENT); - objects_query_strokewidth (objects, &tmp_style); + objects_query_strokewidth(objects, &tmp_style); if (sel_style_for_width) { match = (sel_style_for_width->stroke_width.computed == tmp_style.stroke_width.computed); @@ -2182,19 +2146,18 @@ std::vector<SPItem*> sp_get_same_style(SPItem *sel, std::vector<SPItem*> &src, S } } match_g = match_g && match; - if (type == SP_STROKE_STYLE_DASHES|| type == SP_STROKE_STYLE_ALL || type==SP_STYLE_ALL) { + if (type == SP_STROKE_STYLE_DASHES || type == SP_STROKE_STYLE_ALL || type == SP_STYLE_ALL) { match = (sel_style->stroke_dasharray.set == iter_style->stroke_dasharray.set); if (sel_style->stroke_dasharray.set && iter_style->stroke_dasharray.set) { match = (sel_style->stroke_dasharray == iter_style->stroke_dasharray); } } match_g = match_g && match; - if (type == SP_STROKE_STYLE_MARKERS|| type == SP_STROKE_STYLE_ALL|| type==SP_STYLE_ALL) { + if (type == SP_STROKE_STYLE_MARKERS || type == SP_STROKE_STYLE_ALL || type == SP_STYLE_ALL) { match = true; - int len = sizeof(sel_style->marker)/sizeof(SPIString); + int len = sizeof(sel_style->marker) / sizeof(SPIString); for (int i = 0; i < len; i++) { - if (g_strcmp0(sel_style->marker_ptrs[i]->value(), - iter_style->marker_ptrs[i]->value())) { + if (g_strcmp0(sel_style->marker_ptrs[i]->value(), iter_style->marker_ptrs[i]->value())) { match = false; break; } @@ -2202,22 +2165,23 @@ std::vector<SPItem*> sp_get_same_style(SPItem *sel, std::vector<SPItem*> &src, S } match_g = match_g && match; if (match_g) { - while (iter->cloned) iter=dynamic_cast<SPItem *>(iter->parent); - matches.insert(matches.begin(),iter); + while (iter->cloned) + iter = dynamic_cast<SPItem *>(iter->parent); + matches.insert(matches.begin(), iter); } } else { g_assert_not_reached(); } } - if( sel_style_for_width != nullptr ) delete sel_style_for_width; + if (sel_style_for_width != nullptr) + delete sel_style_for_width; return matches; } // helper function: -static -Geom::Point -cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){ +static Geom::Point cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p) +{ Geom::Point m = r.midpoint(); unsigned i = 0; if (p[X] < m[X]) { @@ -2230,17 +2194,18 @@ cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){ } /** -\param angle the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object +\param angle the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated +object */ void ObjectSet::rotateScreen(double angle) { - if (isEmpty()||!desktop()) + if (isEmpty() || !desktop()) return; Geom::OptRect bbox = visualBounds(); boost::optional<Geom::Point> center_ = center(); - if ( !bbox || !center_ ) { + if (!bbox || !center_) { return; } @@ -2252,12 +2217,8 @@ void ObjectSet::rotateScreen(double angle) rotateRelative(*center_, zangle); - DocumentUndo::maybeDone(document(), - ( (angle > 0) - ? "selector:rotate:ccw" - : "selector:rotate:cw" ), - SP_VERB_CONTEXT_SELECT, - _("Rotate by pixels")); + DocumentUndo::maybeDone(document(), ((angle > 0) ? "selector:rotate:ccw" : "selector:rotate:cw"), + SP_VERB_CONTEXT_SELECT, _("Rotate by pixels")); } void ObjectSet::scale(double grow) @@ -2274,7 +2235,7 @@ void ObjectSet::scale(double grow) // you can't scale "do nizhe pola" (below zero) double const max_len = bbox->maxExtent(); - if ( max_len + grow <= 1e-3 ) { + if (max_len + grow <= 1e-3) { return; } @@ -2282,18 +2243,14 @@ void ObjectSet::scale(double grow) setScaleRelative(center_, Geom::Scale(times, times)); if (document()) { - DocumentUndo::maybeDone(document(), - ( (grow > 0) - ? "selector:scale:larger" - : "selector:scale:smaller" ), - SP_VERB_CONTEXT_SELECT, - _("Scale")); + DocumentUndo::maybeDone(document(), ((grow > 0) ? "selector:scale:larger" : "selector:scale:smaller"), + SP_VERB_CONTEXT_SELECT, _("Scale")); } } void ObjectSet::scaleScreen(double grow_pixels) { - if(!desktop()) + if (!desktop()) return; scale(grow_pixels / desktop()->current_zoom()); } @@ -2311,8 +2268,7 @@ void ObjectSet::scaleTimes(double times) Geom::Point const center_(sel_bbox->midpoint()); setScaleRelative(center_, Geom::Scale(times, times)); - DocumentUndo::done(document(), SP_VERB_CONTEXT_SELECT, - _("Scale by whole factor")); + DocumentUndo::done(document(), SP_VERB_CONTEXT_SELECT, _("Scale by whole factor")); } void ObjectSet::move(double dx, double dy) @@ -2325,14 +2281,12 @@ void ObjectSet::move(double dx, double dy) if (document()) { if (dx == 0) { - DocumentUndo::maybeDone(document(), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, - _("Move vertically")); + DocumentUndo::maybeDone(document(), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, _("Move vertically")); } else if (dy == 0) { DocumentUndo::maybeDone(document(), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, _("Move horizontally")); } else { - DocumentUndo::done(document(), SP_VERB_CONTEXT_SELECT, - _("Move")); + DocumentUndo::done(document(), SP_VERB_CONTEXT_SELECT, _("Move")); } } } @@ -2351,20 +2305,17 @@ void ObjectSet::moveScreen(double dx, double dy) SPDocument *doc = document(); if (dx == 0) { - DocumentUndo::maybeDone(doc, "selector:move:vertical", SP_VERB_CONTEXT_SELECT, - _("Move vertically by pixels")); + DocumentUndo::maybeDone(doc, "selector:move:vertical", SP_VERB_CONTEXT_SELECT, _("Move vertically by pixels")); } else if (dy == 0) { DocumentUndo::maybeDone(doc, "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, _("Move horizontally by pixels")); } else { - DocumentUndo::done(doc, SP_VERB_CONTEXT_SELECT, - _("Move")); + DocumentUndo::done(doc, SP_VERB_CONTEXT_SELECT, _("Move")); } } - - -struct Forward { +struct Forward +{ typedef SPObject *Iterator; static Iterator children(SPObject *o) { return o->firstChild(); } @@ -2373,33 +2324,31 @@ struct Forward { static SPObject *object(Iterator i) { return i; } static Iterator next(Iterator i) { return i->getNext(); } - static bool isNull(Iterator i) {return (!i);} + static bool isNull(Iterator i) { return (!i); } }; -struct ListReverse { +struct ListReverse +{ typedef std::list<SPObject *> *Iterator; - static Iterator children(SPObject *o) { - return make_list(o, nullptr); - } - static Iterator siblings_after(SPObject *o) { - return make_list(o->parent, o); - } - static void dispose(Iterator i) { - delete i; - } + static Iterator children(SPObject *o) { return make_list(o, nullptr); } + static Iterator siblings_after(SPObject *o) { return make_list(o->parent, o); } + static void dispose(Iterator i) { delete i; } - static SPObject *object(Iterator i) { - return *(i->begin()); + static SPObject *object(Iterator i) { return *(i->begin()); } + static Iterator next(Iterator i) + { + i->pop_front(); + return i; } - static Iterator next(Iterator i) { i->pop_front(); return i; } - static bool isNull(Iterator i) {return i->empty();} + static bool isNull(Iterator i) { return i->empty(); } private: - static std::list<SPObject *> *make_list(SPObject *object, SPObject *limit) { + static std::list<SPObject *> *make_list(SPObject *object, SPObject *limit) + { auto list = new std::list<SPObject *>; - for (auto &child: object->children) { + for (auto &child : object->children) { if (&child == limit) { break; } @@ -2409,19 +2358,17 @@ private: } }; - - template <typename D> -SPItem *next_item(SPDesktop *desktop, std::vector<SPObject *> &path, SPObject *root, - bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive) +SPItem *next_item(SPDesktop *desktop, std::vector<SPObject *> &path, SPObject *root, bool only_in_viewport, + PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive) { typename D::Iterator children; typename D::Iterator iter; - SPItem *found=nullptr; + SPItem *found = nullptr; if (!path.empty()) { - SPObject *object=path.back(); + SPObject *object = path.back(); path.pop_back(); g_assert(object->parent == root); if (desktop->isLayer(object)) { @@ -2432,8 +2379,8 @@ SPItem *next_item(SPDesktop *desktop, std::vector<SPObject *> &path, SPObject *r iter = children = D::children(root); } - while ( !D::isNull(iter) && !found ) { - SPObject *object=D::object(iter); + while (!D::isNull(iter) && !found) { + SPObject *object = D::object(iter); if (desktop->isLayer(object)) { if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers std::vector<SPObject *> empt; @@ -2441,12 +2388,9 @@ SPItem *next_item(SPDesktop *desktop, std::vector<SPObject *> &path, SPObject *r } } else { SPItem *item = dynamic_cast<SPItem *>(object); - if ( item && - ( !only_in_viewport || desktop->isWithinViewport(item) ) && - ( !onlyvisible || !desktop->itemIsHidden(item)) && - ( !onlysensitive || !item->isLocked()) && - !desktop->isLayer(item) ) - { + if (item && (!only_in_viewport || desktop->isWithinViewport(item)) && + (!onlyvisible || !desktop->itemIsHidden(item)) && (!onlysensitive || !item->isLocked()) && + !desktop->isLayer(item)) { found = item; } } @@ -2458,23 +2402,20 @@ SPItem *next_item(SPDesktop *desktop, std::vector<SPObject *> &path, SPObject *r return found; } - template <typename D> -SPItem *next_item_from_list(SPDesktop *desktop, std::vector<SPItem*> const &items, - SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive) +SPItem *next_item_from_list(SPDesktop *desktop, std::vector<SPItem *> const &items, SPObject *root, + bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive) { - SPObject *current=root; - for(auto item : items) { - if ( root->isAncestorOf(item) && - ( !only_in_viewport || desktop->isWithinViewport(item) ) ) - { + SPObject *current = root; + for (auto item : items) { + if (root->isAncestorOf(item) && (!only_in_viewport || desktop->isWithinViewport(item))) { current = item; break; } } std::vector<SPObject *> path; - while ( current != root ) { + while (current != root) { path.push_back(current); current = current->parent; } @@ -2491,14 +2432,14 @@ SPItem *next_item_from_list(SPDesktop *desktop, std::vector<SPItem*> const &item return next; } -void -sp_selection_item_next(SPDesktop *desktop) +void sp_selection_item_next(SPDesktop *desktop) { g_return_if_fail(desktop != nullptr); Inkscape::Selection *selection = desktop->getSelection(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER); + PrefsSelectionContext inlayer = + (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER); bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true); bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true); @@ -2510,18 +2451,18 @@ sp_selection_item_next(SPDesktop *desktop) } std::vector<SPItem *> vec(selection->items().begin(), selection->items().end()); - SPItem *item=next_item_from_list<Forward>(desktop, vec, root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive); + SPItem *item = next_item_from_list<Forward>(desktop, vec, root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, + onlyvisible, onlysensitive); if (item) { selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer); - if ( SP_CYCLING == SP_CYCLE_FOCUS ) { + if (SP_CYCLING == SP_CYCLE_FOCUS) { scroll_to_show_item(desktop, item); } } } -void -sp_selection_item_prev(SPDesktop *desktop) +void sp_selection_item_prev(SPDesktop *desktop) { SPDocument *document = desktop->getDocument(); g_return_if_fail(document != nullptr); @@ -2529,7 +2470,8 @@ sp_selection_item_prev(SPDesktop *desktop) Inkscape::Selection *selection = desktop->getSelection(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER); + PrefsSelectionContext inlayer = + (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER); bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true); bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true); @@ -2541,24 +2483,26 @@ sp_selection_item_prev(SPDesktop *desktop) } std::vector<SPItem *> vec(selection->items().begin(), selection->items().end()); - SPItem *item=next_item_from_list<ListReverse>(desktop, vec, root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive); + SPItem *item = next_item_from_list<ListReverse>(desktop, vec, root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, + onlyvisible, onlysensitive); if (item) { selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer); - if ( SP_CYCLING == SP_CYCLE_FOCUS ) { + if (SP_CYCLING == SP_CYCLE_FOCUS) { scroll_to_show_item(desktop, item); } } } -void sp_selection_next_patheffect_param(SPDesktop * dt) +void sp_selection_next_patheffect_param(SPDesktop *dt) { - if (!dt) return; + if (!dt) + return; Inkscape::Selection *selection = dt->getSelection(); - if ( selection && !selection->isEmpty() ) { + if (selection && !selection->isEmpty()) { SPItem *item = selection->singleItem(); - if ( SPLPEItem *lpeitem = dynamic_cast<SPLPEItem*>(item) ) { + if (SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(item)) { if (lpeitem->hasPathEffect()) { lpeitem->editNextParamOncanvas(dt); } else { @@ -2587,9 +2531,6 @@ void ObjectSet::editMask(bool /*clip*/) return; } - - - /** * If \a item is not entirely visible then adjust visible area to centre on the centre on of * \a item. @@ -2599,12 +2540,12 @@ void scroll_to_show_item(SPDesktop *desktop, SPItem *item) auto dbox = desktop->get_display_area(); Geom::OptRect sbox = item->desktopVisualBounds(); - if ( sbox && dbox.contains(*sbox) == false ) { + if (sbox && dbox.contains(*sbox) == false) { Geom::Point const s_dt = sbox->midpoint(); Geom::Point const s_w = desktop->d2w(s_dt); Geom::Point const d_dt = dbox.midpoint(); Geom::Point const d_w = desktop->d2w(d_dt); - Geom::Point const moved_w( d_w - s_w ); + Geom::Point const moved_w(d_w - s_w); desktop->scroll_relative(moved_w); } } @@ -2619,21 +2560,21 @@ void ObjectSet::clone() // check if something is selected if (isEmpty()) { - if(desktop()) + if (desktop()) desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone.")); return; } - std::vector<Inkscape::XML::Node*> reprs(xmlNodes().begin(), xmlNodes().end()); + std::vector<Inkscape::XML::Node *> reprs(xmlNodes().begin(), xmlNodes().end()); clear(); // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need - sort(reprs.begin(),reprs.end(),sp_repr_compare_position_bool); + sort(reprs.begin(), reprs.end(), sp_repr_compare_position_bool); - std::vector<Inkscape::XML::Node*> newsel; + std::vector<Inkscape::XML::Node *> newsel; - for(auto sel_repr : reprs){ + for (auto sel_repr : reprs) { Inkscape::XML::Node *parent = sel_repr->parent(); Inkscape::XML::Node *clone = xml_doc->createElement("svg:use"); @@ -2653,8 +2594,7 @@ void ObjectSet::clone() Inkscape::GC::release(clone); } - DocumentUndo::done(document(), SP_VERB_EDIT_CLONE, - C_("Action", "Clone")); + DocumentUndo::done(document(), SP_VERB_EDIT_CLONE, C_("Action", "Clone")); setReprList(newsel); } @@ -2662,7 +2602,7 @@ void ObjectSet::clone() void ObjectSet::relink() { if (isEmpty()) { - if(desktop()) + if (desktop()) desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink.")); return; } @@ -2670,16 +2610,17 @@ void ObjectSet::relink() Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); auto newid = cm->getFirstObjectID(); if (newid.empty()) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Copy an <b>object</b> to clipboard to relink clones to.")); return; } auto newref = "#" + newid; // Get a copy of current selection. bool relinked = false; - auto items_= items(); - for (auto i=items_.begin();i!=items_.end();++i){ + auto items_ = items(); + for (auto i = items_.begin(); i != items_.end(); ++i) { SPItem *item = *i; if (dynamic_cast<SPUse *>(item)) { @@ -2690,29 +2631,28 @@ void ObjectSet::relink() } if (!relinked) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, + _("<b>No clones to relink</b> in the selection.")); } else { - DocumentUndo::done(document(), SP_VERB_EDIT_UNLINK_CLONE, - _("Relink clone")); + DocumentUndo::done(document(), SP_VERB_EDIT_UNLINK_CLONE, _("Relink clone")); } } - bool ObjectSet::unlink(const bool skip_undo) { if (isEmpty()) { - if(desktop()) + if (desktop()) desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink.")); return false; } // Get a copy of current selection. - std::vector<SPItem*> new_select; + std::vector<SPItem *> new_select; bool unlinked = false; std::vector<SPItem *> items_(items().begin(), items().end()); - for (auto i=items_.rbegin();i!=items_.rend();++i){ + for (auto i = items_.rbegin(); i != items_.rend(); ++i) { SPItem *item = *i; ObjectSet tmp_set(document()); @@ -2722,17 +2662,17 @@ bool ObjectSet::unlink(const bool skip_undo) if (clip_obj) { SPUse *clipuse = dynamic_cast<SPUse *>(clip_obj); if (clipuse) { - tmp_set.unsetMask(true,true); + tmp_set.unsetMask(true, true); unlinked = tmp_set.unlink(true) || unlinked; - tmp_set.setMask(true,false,true); + tmp_set.setMask(true, false, true); } new_select.push_back(tmp_set.singleItem()); } else if (mask_obj) { SPUse *maskuse = dynamic_cast<SPUse *>(mask_obj); if (maskuse) { - tmp_set.unsetMask(false,true); + tmp_set.unsetMask(false, true); unlinked = tmp_set.unlink(true) || unlinked; - tmp_set.setMask(false,false,true); + tmp_set.setMask(false, false, true); } new_select.push_back(tmp_set.singleItem()); } else { @@ -2779,43 +2719,44 @@ bool ObjectSet::unlink(const bool skip_undo) setList(new_select); } if (!unlinked) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, + _("<b>No clones to unlink</b> in the selection.")); } if (!skip_undo) { - DocumentUndo::done(document(), SP_VERB_EDIT_UNLINK_CLONE, - _("Unlink clone")); + DocumentUndo::done(document(), SP_VERB_EDIT_UNLINK_CLONE, _("Unlink clone")); } return unlinked; } -bool ObjectSet::unlinkRecursive(const bool skip_undo) { - if (isEmpty()){ +bool ObjectSet::unlinkRecursive(const bool skip_undo) +{ + if (isEmpty()) { if (desktop()) desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink.")); return false; } bool unlinked = false; ObjectSet tmp_set(document()); - std::vector<SPItem*> items_(items().begin(), items().end()); - for (auto& it:items_) { + std::vector<SPItem *> items_(items().begin(), items().end()); + for (auto &it : items_) { tmp_set.set(it); unlinked = tmp_set.unlink(true) || unlinked; it = tmp_set.singleItem(); if (SP_IS_GROUP(it)) { - std::vector<SPObject*> c = it->childList(false); + std::vector<SPObject *> c = it->childList(false); tmp_set.setList(c); unlinked = tmp_set.unlinkRecursive(true) || unlinked; } } if (!unlinked) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, + _("<b>No clones to unlink</b> in the selection.")); } if (!skip_undo) { - DocumentUndo::done(document(), SP_VERB_EDIT_UNLINK_CLONE_RECURSIVE, - _("Unlink clone recursively")); + DocumentUndo::done(document(), SP_VERB_EDIT_UNLINK_CLONE_RECURSIVE, _("Unlink clone recursively")); } setList(items_); return unlinked; @@ -2825,13 +2766,15 @@ void ObjectSet::cloneOriginal() { SPItem *item = singleItem(); - gchar const *error = _("Select a <b>clone</b> to go to its original. Select a <b>linked offset</b> to go to its source. Select a <b>text on path</b> to go to the path. Select a <b>flowed text</b> to go to its frame."); + gchar const *error = + _("Select a <b>clone</b> to go to its original. Select a <b>linked offset</b> to go to its source. Select a " + "<b>text on path</b> to go to the path. Select a <b>flowed text</b> to go to its frame."); // Check if other than two objects are selected - auto items_= items(); + auto items_ = items(); if (boost::distance(items_) != 1 || !item) { - if(desktop()) + if (desktop()) desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, error); return; } @@ -2859,21 +2802,25 @@ void ObjectSet::cloneOriginal() } if (original == nullptr) { // it's an object that we don't know what to do with - if(desktop()) + if (desktop()) desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, error); return; } if (!original) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)")); + if (desktop()) + desktop()->messageStack()->flash( + Inkscape::ERROR_MESSAGE, + _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)")); return; } for (SPObject *o = original; o && !dynamic_cast<SPRoot *>(o); o = o->parent) { if (dynamic_cast<SPDefs *>(o)) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in <defs>)")); + if (desktop()) + desktop()->messageStack()->flash( + Inkscape::ERROR_MESSAGE, + _("The object you're trying to select is <b>not visible</b> (it is in <defs>)")); return; } } @@ -2884,14 +2831,15 @@ void ObjectSet::cloneOriginal() if (highlight) { Geom::OptRect a = item->desktopVisualBounds(); Geom::OptRect b = original->desktopVisualBounds(); - if ( a && b && desktop()) { + if (a && b && desktop()) { // draw a flashing line between the objects auto curve = std::make_unique<SPCurve>(); curve->moveto(a->midpoint()); curve->lineto(b->midpoint()); SPCanvasItem *canvasitem = sp_canvas_bpath_new(desktop()->getTempGroup(), curve.get()); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, + SP_STROKE_LINECAP_BUTT, 5, 3); sp_canvas_item_show(canvasitem); desktop()->add_temporary_canvasitem(canvasitem, 1000); } @@ -2906,16 +2854,15 @@ void ObjectSet::cloneOriginal() } /** -* This applies the Fill Between Many LPE, and has it refer to the selection. -*/ + * This applies the Fill Between Many LPE, and has it refer to the selection. + */ void ObjectSet::cloneOriginalPathLPE(bool allow_transforms) { - Inkscape::SVGOStringStream os; - SPObject * firstItem = nullptr; - auto items_= items(); + SPObject *firstItem = nullptr; + auto items_ = items(); bool multiple = false; - for (auto i=items_.begin();i!=items_.end();++i){ + for (auto i = items_.begin(); i != items_.end(); ++i) { if (SP_IS_SHAPE(*i) || SP_IS_TEXT(*i)) { if (firstItem) { os << "|"; @@ -2937,9 +2884,9 @@ void ObjectSet::cloneOriginalPathLPE(bool allow_transforms) lpe_repr->setAttribute("applied", "true"); } else { lpe_repr->setAttribute("effect", "clone_original"); - lpe_repr->setAttribute("linkeditem", ((Glib::ustring)"#" + (Glib::ustring)firstItem->getId())); + lpe_repr->setAttribute("linkeditem", ((Glib::ustring) "#" + (Glib::ustring)firstItem->getId())); } - gchar const *method_str = allow_transforms ? "d" : "bsplinespiro"; + gchar const *method_str = allow_transforms ? "d" : "bsplinespiro"; lpe_repr->setAttribute("method", method_str); gchar const *allow_transforms_str = allow_transforms ? "true" : "false"; lpe_repr->setAttribute("allow_transforms", allow_transforms_str); @@ -2969,7 +2916,7 @@ void ObjectSet::cloneOriginalPathLPE(bool allow_transforms) } } else { - if(desktop()) + if (desktop()) desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select path(s) to fill.")); } } @@ -2992,13 +2939,13 @@ void ObjectSet::toMarker(bool apply) doc->ensureUpToDate(); Geom::OptRect r = visualBounds(); boost::optional<Geom::Point> c = center(); - if ( !r || !c ) { + if (!r || !c) { return; } Geom::Point center = (*c) * doc->dt2doc(); - std::vector<SPItem*> items_(items().begin(), items().end()); + std::vector<SPItem *> items_(items().begin(), items().end()); // bottommost object, after sorting SPObject *parent = items_.front()->parent; @@ -3014,8 +2961,8 @@ void ObjectSet::toMarker(bool apply) } // Create a list of duplicates, to be pasted inside marker element. - std::vector<Inkscape::XML::Node*> repr_copies; - for (std::vector<SPItem*>::const_reverse_iterator i=items_.rbegin();i!=items_.rend();++i){ + std::vector<Inkscape::XML::Node *> repr_copies; + for (std::vector<SPItem *>::const_reverse_iterator i = items_.rbegin(); i != items_.rend(); ++i) { Inkscape::XML::Node *dup = (*i)->getRepr()->duplicate(xml_doc); repr_copies.push_back(dup); } @@ -3025,7 +2972,7 @@ void ObjectSet::toMarker(bool apply) if (apply) { // Delete objects so that their clones don't get alerted; // the objects will be restored inside the marker element. - for (auto item : items_){ + for (auto item : items_) { item->deleteObject(false); } } @@ -3043,17 +2990,15 @@ void ObjectSet::toMarker(bool apply) // restore compensation setting prefs->setInt("/options/clonecompensation/value", saved_compensation); - - - DocumentUndo::done(doc, SP_VERB_EDIT_SELECTION_2_MARKER, - _("Objects to marker")); + DocumentUndo::done(doc, SP_VERB_EDIT_SELECTION_2_MARKER, _("Objects to marker")); } -static void sp_selection_to_guides_recursive(SPItem *item, bool wholegroups) { +static void sp_selection_to_guides_recursive(SPItem *item, bool wholegroups) +{ SPGroup *group = dynamic_cast<SPGroup *>(item); if (group && !dynamic_cast<SPBox3D *>(item) && !wholegroups) { - std::vector<SPItem*> items=sp_item_group_item_list(group); - for (auto item : items){ + std::vector<SPItem *> items = sp_item_group_item_list(group); + for (auto item : items) { sp_selection_to_guides_recursive(item, wholegroups); } } else { @@ -3065,11 +3010,12 @@ void ObjectSet::toGuides() { SPDocument *doc = document(); // we need to copy the list because it gets reset when objects are deleted - std::vector<SPItem*> items_(items().begin(), items().end()); + std::vector<SPItem *> items_(items().begin(), items().end()); if (isEmpty()) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>object(s)</b> to convert to guides.")); return; } @@ -3081,7 +3027,7 @@ void ObjectSet::toGuides() // and its entry in the selection list is invalid (crash). // Therefore: first convert all, then delete all. - for (auto item : items_){ + for (auto item : items_) { sp_selection_to_guides_recursive(item, wholegroups); } @@ -3115,20 +3061,20 @@ void ObjectSet::toGuides() */ void ObjectSet::toSymbol() { - SPDocument *doc = document(); Inkscape::XML::Document *xml_doc = doc->getReprDoc(); // Check if something is selected. if (isEmpty()) { - if (desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>objects</b> to convert to symbol.")); - return; + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>objects</b> to convert to symbol.")); + return; } doc->ensureUpToDate(); - std::vector<SPObject*> items_(objects().begin(), objects().end()); - sort(items_.begin(),items_.end(),sp_object_compare_position_bool); + std::vector<SPObject *> items_(objects().begin(), objects().end()); + sort(items_.begin(), items_.end(), sp_object_compare_position_bool); // Keep track of parent, this is where <use> will be inserted. Inkscape::XML::Node *the_first_repr = items_[0]->getRepr(); @@ -3138,17 +3084,16 @@ void ObjectSet::toSymbol() bool single_group = false; SPGroup *the_group = nullptr; Geom::Affine transform; - if( items_.size() == 1 ) { + if (items_.size() == 1) { SPObject *object = items_[0]; the_group = dynamic_cast<SPGroup *>(object); - if ( the_group ) { + if (the_group) { single_group = true; - if( !sp_svg_transform_read( object->getAttribute("transform"), &transform )) + if (!sp_svg_transform_read(object->getAttribute("transform"), &transform)) transform = Geom::identity(); - if( transform.isTranslation() ) { - + if (transform.isTranslation()) { // Create new list from group children. items_ = object->childList(false); @@ -3156,7 +3101,8 @@ void ObjectSet::toSymbol() // without disturbing clones. // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); + int saved_compensation = + prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); // Remove transform on group, updating clones. @@ -3176,11 +3122,11 @@ void ObjectSet::toSymbol() defsrepr->appendChild(symbol_repr); bool settitle = false; // For a single group, copy relevant attributes. - if( single_group ) { + if (single_group) { Glib::ustring id = the_group->getAttribute("id"); - symbol_repr->setAttribute("style", the_group->getAttribute("style")); + symbol_repr->setAttribute("style", the_group->getAttribute("style")); - gchar * title = the_group->title(); + gchar *title = the_group->title(); if (title) { symbol_repr->addChildAtPos(title_repr, 0); title_repr->appendChild(xml_doc->createTextNode(title)); @@ -3188,7 +3134,7 @@ void ObjectSet::toSymbol() } g_free(title); - gchar * desc = the_group->desc(); + gchar *desc = the_group->desc(); if (desc) { Inkscape::XML::Node *desc_repr = xml_doc->createElement("svg:desc"); desc_repr->setContent(desc); @@ -3197,7 +3143,7 @@ void ObjectSet::toSymbol() Inkscape::GC::release(desc_repr); } g_free(desc); - symbol_repr->setAttribute("class", the_group->getAttribute("class")); + symbol_repr->setAttribute("class", the_group->getAttribute("class")); the_group->setAttribute("id", id + "_transform"); symbol_repr->setAttribute("id", id); @@ -3209,17 +3155,16 @@ void ObjectSet::toSymbol() the_group->getAttribute("inkscape:transform-center-y")); the_group->removeAttribute("style"); - } // Move selected items to new <symbol> - for (std::vector<SPObject*>::const_reverse_iterator i=items_.rbegin();i!=items_.rend();++i){ - gchar* title = (*i)->title(); + for (std::vector<SPObject *>::const_reverse_iterator i = items_.rbegin(); i != items_.rend(); ++i) { + gchar *title = (*i)->title(); if (!single_group && !settitle && title) { symbol_repr->addChildAtPos(title_repr, 0); title_repr->appendChild(xml_doc->createTextNode(title)); Inkscape::GC::release(title_repr); - gchar * desc = (*i)->desc(); + gchar *desc = (*i)->desc(); if (desc) { Inkscape::XML::Node *desc_repr = xml_doc->createElement("svg:desc"); desc_repr->appendChild(xml_doc->createTextNode(desc)); @@ -3235,20 +3180,20 @@ void ObjectSet::toSymbol() symbol_repr->addChild(repr, nullptr); } - if( single_group && transform.isTranslation() ) { + if (single_group && transform.isTranslation()) { the_group->deleteObject(true); } // Create <use> pointing to new symbol (to replace the moved objects). Inkscape::XML::Node *clone = xml_doc->createElement("svg:use"); - clone->setAttribute("xlink:href", Glib::ustring("#")+symbol_repr->attribute("id")); + clone->setAttribute("xlink:href", Glib::ustring("#") + symbol_repr->attribute("id")); the_parent_repr->appendChild(clone); - if( single_group && transform.isTranslation() ) { - if( !transform.isIdentity() ) { - gchar *c = sp_svg_transform_write( transform ); + if (single_group && transform.isTranslation()) { + if (!transform.isIdentity()) { + gchar *c = sp_svg_transform_write(transform); clone->setAttribute("transform", c); g_free(c); } @@ -3272,18 +3217,20 @@ void ObjectSet::unSymbol() Inkscape::XML::Document *xml_doc = doc->getReprDoc(); // Check if something is selected. if (isEmpty()) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>symbol</b> to extract objects from.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select a <b>symbol</b> to extract objects from.")); return; } - SPObject* symbol = single(); + SPObject *symbol = single(); // Make sure we have only one object in selection. // Require that we really have a <symbol>. - if( symbol == nullptr || !dynamic_cast<SPSymbol *>( symbol )) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select only one <b>symbol</b> in Symbol dialog to convert to group.")); + if (symbol == nullptr || !dynamic_cast<SPSymbol *>(symbol)) { + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select only one <b>symbol</b> in Symbol dialog to convert to group.")); return; } @@ -3291,45 +3238,40 @@ void ObjectSet::unSymbol() // Create new <g> and insert in current layer Inkscape::XML::Node *group = xml_doc->createElement("svg:g"); - //TODO: Better handle if no desktop, currently go to defs without it - if(desktop()) { + // TODO: Better handle if no desktop, currently go to defs without it + if (desktop()) { desktop()->currentLayer()->getRepr()->appendChild(group); } else { symbol->parent->getRepr()->appendChild(group); } // Move all children of symbol to group - std::vector<SPObject*> children = symbol->childList(false); + std::vector<SPObject *> children = symbol->childList(false); // Converting a group to a symbol inserts a group for non-translational transform. // In converting a symbol back to a group we strip out the inserted group (or any other // group that only adds a transform to the symbol content). - if( children.size() == 1 ) { + if (children.size() == 1) { SPObject *object = children[0]; - if ( dynamic_cast<SPGroup *>( object ) ) { - if( object->getAttribute("style") == nullptr || - object->getAttribute("class") == nullptr ) { - + if (dynamic_cast<SPGroup *>(object)) { + if (object->getAttribute("style") == nullptr || object->getAttribute("class") == nullptr) { group->setAttribute("transform", object->getAttribute("transform")); children = object->childList(false); } } } - for (std::vector<SPObject*>::const_reverse_iterator i=children.rbegin();i!=children.rend();++i){ + for (std::vector<SPObject *>::const_reverse_iterator i = children.rbegin(); i != children.rend(); ++i) { Inkscape::XML::Node *repr = (*i)->getRepr(); repr->parent()->removeChild(repr); - group->addChild(repr,nullptr); + group->addChild(repr, nullptr); } // Copy relevant attributes group->setAttribute("style", symbol->getAttribute("style")); group->setAttribute("class", symbol->getAttribute("class")); group->setAttribute("title", symbol->getAttribute("title")); - group->setAttribute("inkscape:transform-center-x", - symbol->getAttribute("inkscape:transform-center-x")); - group->setAttribute("inkscape:transform-center-y", - symbol->getAttribute("inkscape:transform-center-y")); - + group->setAttribute("inkscape:transform-center-x", symbol->getAttribute("inkscape:transform-center-x")); + group->setAttribute("inkscape:transform-center-y", symbol->getAttribute("inkscape:transform-center-y")); // Need to delete <symbol>; all <use> elements that referenced <symbol> should // auto-magically reference <g> (if <symbol> deleted after setting <g> 'id'). @@ -3364,18 +3306,17 @@ void ObjectSet::tile(bool apply) doc->ensureUpToDate(); Geom::OptRect r = visualBounds(); - if ( !r ) { + if (!r) { return; } - std::vector<SPItem*> items_(items().begin(), items().end()); + std::vector<SPItem *> items_(items().begin(), items().end()); - sort(items_.begin(),items_.end(),sp_object_compare_position_bool); + sort(items_.begin(), items_.end(), sp_object_compare_position_bool); // bottommost object, after sorting SPObject *parent = items_[0]->parent; - Geom::Affine parent_transform; { SPItem *parentItem = dynamic_cast<SPItem *>(parent); @@ -3390,8 +3331,8 @@ void ObjectSet::tile(bool apply) gint pos = items_[0]->getRepr()->position(); // create a list of duplicates - std::vector<Inkscape::XML::Node*> repr_copies; - for (auto item : items_){ + std::vector<Inkscape::XML::Node *> repr_copies; + for (auto item : items_) { Inkscape::XML::Node *dup = item->getRepr()->duplicate(xml_doc); repr_copies.push_back(dup); } @@ -3400,7 +3341,7 @@ void ObjectSet::tile(bool apply) if (apply) { // delete objects so that their clones don't get alerted; this object will be restored shortly - for (auto item : items_){ + for (auto item : items_) { item->deleteObject(false); } } @@ -3412,10 +3353,9 @@ void ObjectSet::tile(bool apply) int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); - Geom::Affine move = Geom::Translate(- bbox.min()); - gchar const *pat_id = SPPattern::produce(repr_copies, bbox, doc, - move.inverse() /* patternTransform */, - parent_transform * move); + Geom::Affine move = Geom::Translate(-bbox.min()); + gchar const *pat_id = + SPPattern::produce(repr_copies, bbox, doc, move.inverse() /* patternTransform */, parent_transform * move); // restore compensation setting prefs->setInt("/options/clonecompensation/value", saved_compensation); @@ -3445,30 +3385,28 @@ void ObjectSet::tile(bool apply) set(rectangle); } - - DocumentUndo::done(doc, SP_VERB_EDIT_TILE, - _("Objects to pattern")); + DocumentUndo::done(doc, SP_VERB_EDIT_TILE, _("Objects to pattern")); } void ObjectSet::untile() { - SPDocument *doc = document(); Inkscape::XML::Document *xml_doc = doc->getReprDoc(); // check if something is selected if (isEmpty()) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select an <b>object with pattern fill</b> to extract objects from.")); return; } - std::vector<SPItem*> new_select; + std::vector<SPItem *> new_select; bool did = false; - std::vector<SPItem*> items_(items().begin(), items().end()); - for (std::vector<SPItem*>::const_reverse_iterator i=items_.rbegin();i!=items_.rend();++i){ + std::vector<SPItem *> items_(items().begin(), items().end()); + for (std::vector<SPItem *>::const_reverse_iterator i = items_.rbegin(); i != items_.rend(); ++i) { SPItem *item = *i; SPStyle *style = item->style; @@ -3490,19 +3428,19 @@ void ObjectSet::untile() Geom::Affine pat_transform = basePat->getTransform(); pat_transform *= item->transform; - for (auto& child: pattern->children) { + for (auto &child : pattern->children) { if (dynamic_cast<SPItem *>(&child)) { Inkscape::XML::Node *copy = child.getRepr()->duplicate(xml_doc); SPItem *i = dynamic_cast<SPItem *>(item->parent->appendChildRepr(copy)); - // FIXME: relink clones to the new canvas objects - // use SPObject::setid when mental finishes it to steal ids of + // FIXME: relink clones to the new canvas objects + // use SPObject::setid when mental finishes it to steal ids of // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work) doc->ensureUpToDate(); if (i) { - Geom::Affine transform( i->transform * pat_transform ); + Geom::Affine transform(i->transform * pat_transform); i->doWriteTransform(transform); new_select.push_back(i); @@ -3518,11 +3456,10 @@ void ObjectSet::untile() } if (!did) { - if(desktop()) + if (desktop()) desktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection.")); } else { - DocumentUndo::done(document(), SP_VERB_EDIT_UNTILE, - _("Pattern to objects")); + DocumentUndo::done(document(), SP_VERB_EDIT_UNTILE, _("Pattern to objects")); setList(new_select); } } @@ -3538,17 +3475,16 @@ void ObjectSet::getExportHints(Glib::ustring &filename, float *xdpi, float *ydpi bool xdpi_search = TRUE; bool ydpi_search = TRUE; - for (auto i=reprlst.begin();filename_search&&xdpi_search&&ydpi_search&&i!=reprlst.end();++i){ + for (auto i = reprlst.begin(); filename_search && xdpi_search && ydpi_search && i != reprlst.end(); ++i) { gchar const *dpi_string; Inkscape::XML::Node *repr = *i; if (filename_search) { - const gchar* tmp = repr->attribute("inkscape:export-filename"); - if (tmp){ + const gchar *tmp = repr->attribute("inkscape:export-filename"); + if (tmp) { filename = tmp; filename_search = FALSE; - } - else{ + } else { filename.clear(); } } @@ -3573,15 +3509,12 @@ void ObjectSet::getExportHints(Glib::ustring &filename, float *xdpi, float *ydpi void sp_document_get_export_hints(SPDocument *doc, Glib::ustring &filename, float *xdpi, float *ydpi) { - Inkscape::XML::Node * repr = doc->getReprRoot(); + Inkscape::XML::Node *repr = doc->getReprRoot(); - const gchar* tmp = repr->attribute("inkscape:export-filename"); - if(tmp) - { + const gchar *tmp = repr->attribute("inkscape:export-filename"); + if (tmp) { filename = tmp; - } - else - { + } else { filename.clear(); } gchar const *dpi_string = repr->attribute("inkscape:export-xdpi"); @@ -3597,17 +3530,17 @@ void sp_document_get_export_hints(SPDocument *doc, Glib::ustring &filename, floa void ObjectSet::createBitmapCopy() { - SPDocument *doc = document(); Inkscape::XML::Document *xml_doc = doc->getReprDoc(); // check if something is selected if (isEmpty()) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>object(s)</b> to make a bitmap copy.")); return; } - if(desktop()){ + if (desktop()) { desktop()->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap...")); // set "busy" cursor desktop()->setWaitingCursor(); @@ -3617,33 +3550,31 @@ void ObjectSet::createBitmapCopy() doc->ensureUpToDate(); Geom::OptRect bbox = documentBounds(SPItem::VISUAL_BBOX); if (!bbox) { - if(desktop()) + if (desktop()) desktop()->clearWaitingCursor(); return; // exceptional situation, so not bother with a translatable error message, just quit quietly } // List of the items to show; all others will be hidden - std::vector<SPItem*> items_(items().begin(), items().end()); + std::vector<SPItem *> items_(items().begin(), items().end()); // Sort items so that the topmost comes last - sort(items_.begin(),items_.end(),sp_item_repr_compare_position_bool); + sort(items_.begin(), items_.end(), sp_item_repr_compare_position_bool); // Generate a random value from the current time (you may create bitmap from the same object(s) // multiple times, and this is done so that they don't clash) guint current = guint(g_get_monotonic_time() % 1024); // Create the filename. - gchar *const basename = g_strdup_printf("%s-%s-%u.png", - doc->getDocumentName(), - items_[0]->getRepr()->attribute("id"), - current); + gchar *const basename = + g_strdup_printf("%s-%s-%u.png", doc->getDocumentName(), items_[0]->getRepr()->attribute("id"), current); // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters, // digits, and a few other chars, with "_" g_strcanon(basename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_'); // Build the complete path by adding document base dir, if set, otherwise home dir gchar *directory = nullptr; - if ( doc->getDocumentURI() ) { - directory = g_path_get_dirname( doc->getDocumentURI() ); + if (doc->getDocumentURI()) { + directory = g_path_get_dirname(doc->getDocumentURI()); } if (directory == nullptr) { directory = Inkscape::IO::Resource::homedir_path(nullptr); @@ -3651,7 +3582,7 @@ void ObjectSet::createBitmapCopy() gchar *filepath = g_build_filename(directory, basename, NULL); g_free(directory); - //g_print("%s\n", filepath); + // g_print("%s\n", filepath); // Remember parent and z-order of the topmost one gint pos = items_.back()->getRepr()->position(); @@ -3689,8 +3620,8 @@ void ObjectSet::createBitmapCopy() } // The width and height of the bitmap in pixels - unsigned width = (unsigned) floor(bbox->width() * Inkscape::Util::Quantity::convert(res, "px", "in")); - unsigned height =(unsigned) floor(bbox->height() * Inkscape::Util::Quantity::convert(res, "px", "in")); + unsigned width = (unsigned)floor(bbox->width() * Inkscape::Util::Quantity::convert(res, "px", "in")); + unsigned height = (unsigned)floor(bbox->height() * Inkscape::Util::Quantity::convert(res, "px", "in")); // Find out if we have to run an external filter gchar const *run = nullptr; @@ -3738,13 +3669,9 @@ void ObjectSet::createBitmapCopy() // TODO: avoid roundtrip via file // Do the export - sp_export_png_file(doc, filepath, - bbox->min()[Geom::X], bbox->min()[Geom::Y], - bbox->max()[Geom::X], bbox->max()[Geom::Y], - width, height, res, res, - (guint32) 0xffffff00, - nullptr, nullptr, - true, /*bool force_overwrite,*/ + sp_export_png_file(doc, filepath, bbox->min()[Geom::X], bbox->min()[Geom::Y], bbox->max()[Geom::X], + bbox->max()[Geom::Y], width, height, res, res, (guint32)0xffffff00, nullptr, nullptr, + true, /*bool force_overwrite,*/ items_); // Run filter, if any @@ -3752,7 +3679,7 @@ void ObjectSet::createBitmapCopy() g_print("Running external filter: %s\n", run); int result = system(run); - if(result == -1) + if (result == -1) g_warning("Could not run external filter: %s\n", run); } @@ -3761,7 +3688,7 @@ void ObjectSet::createBitmapCopy() if (pb) { // Create the repr for the image // TODO: avoid unnecessary roundtrip between data URI and decoded pixbuf - Inkscape::XML::Node * repr = xml_doc->createElement("svg:image"); + Inkscape::XML::Node *repr = xml_doc->createElement("svg:image"); sp_embed_image(repr, pb); if (res == Inkscape::Util::Quantity::convert(1, "in", "px")) { // for default 96 dpi, snap it to pixel grid sp_repr_set_svg_double(repr, "width", width); @@ -3772,7 +3699,7 @@ void ObjectSet::createBitmapCopy() } // Write transform - gchar *c=sp_svg_transform_write(t); + gchar *c = sp_svg_transform_write(t); repr->setAttribute("transform", c); g_free(c); @@ -3788,10 +3715,9 @@ void ObjectSet::createBitmapCopy() delete pb; // Complete undoable transaction - DocumentUndo::done(doc, SP_VERB_SELECTION_CREATE_BITMAP, - _("Create bitmap")); + DocumentUndo::done(doc, SP_VERB_SELECTION_CREATE_BITMAP, _("Create bitmap")); } - if(desktop()) + if (desktop()) desktop()->clearWaitingCursor(); g_free(basename); @@ -3806,18 +3732,19 @@ void ObjectSet::createBitmapCopy() void ObjectSet::setClipGroup() { - SPDocument* doc = document(); + SPDocument *doc = document(); Inkscape::XML::Document *xml_doc = doc->getReprDoc(); if (isEmpty()) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>object(s)</b> to create clippath or mask from.")); return; } - std::vector<Inkscape::XML::Node*> p(xmlNodes().begin(), xmlNodes().end()); + std::vector<Inkscape::XML::Node *> p(xmlNodes().begin(), xmlNodes().end()); - sort(p.begin(),p.end(),sp_repr_compare_position_bool); + sort(p.begin(), p.end(), sp_repr_compare_position_bool); clear(); @@ -3827,18 +3754,19 @@ void ObjectSet::setClipGroup() Inkscape::XML::Node *inner = xml_doc->createElement("svg:g"); inner->setAttribute("inkscape:label", "Clip"); - for(auto current : p){ + for (auto current : p) { if (current->parent() == topmost_parent) { Inkscape::XML::Node *spnew = current->duplicate(xml_doc); sp_repr_unparent(current); inner->appendChild(spnew); Inkscape::GC::release(spnew); - topmost --; // only reduce count for those items deleted from topmost_parent - } else { // move it to topmost_parent first - std::vector<Inkscape::XML::Node*> temp_clip; + topmost--; // only reduce count for those items deleted from topmost_parent + } else { // move it to topmost_parent first + std::vector<Inkscape::XML::Node *> temp_clip; - // At this point, current may already have no item, due to its being a clone whose original is already moved away - // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform + // At this point, current may already have no item, due to its being a clone whose original is already moved + // away So we copy it artificially calculating the transform from its repr->attr("transform") and the parent + // transform gchar const *t_str = current->attribute("transform"); Geom::Affine item_t(Geom::identity()); if (t_str) @@ -3855,7 +3783,8 @@ void ObjectSet::setClipGroup() sp_repr_unparent(current); // paste into topmost_parent (temporarily) - std::vector<Inkscape::XML::Node*> copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), temp_clip); + std::vector<Inkscape::XML::Node *> copied = + sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), temp_clip); if (!copied.empty()) { // if success, // take pasted object (now in topmost_parent) Inkscape::XML::Node *in_topmost = copied.back(); @@ -3882,12 +3811,12 @@ void ObjectSet::setClipGroup() clone->setAttribute("inkscape:transform-center-x", inner->attribute("inkscape:transform-center-x")); clone->setAttribute("inkscape:transform-center-y", inner->attribute("inkscape:transform-center-y")); - std::vector<Inkscape::XML::Node*> templist; + std::vector<Inkscape::XML::Node *> templist; templist.push_back(clone); // add the new clone to the top of the original's parent gchar const *mask_id = SPClipPath::create(templist, doc); - char* tmp = g_strdup_printf("url(#%s)", mask_id); + char *tmp = g_strdup_printf("url(#%s)", mask_id); outer->setAttribute("clip-path", tmp); g_free(tmp); @@ -3906,9 +3835,9 @@ void ObjectSet::setClipGroup() * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask * */ - void ObjectSet::setMask(bool apply_clip_path, bool apply_to_layer, bool skip_undo) +void ObjectSet::setMask(bool apply_clip_path, bool apply_to_layer, bool skip_undo) { - if(!desktop() && apply_to_layer) + if (!desktop() && apply_to_layer) return; SPDocument *doc = document(); @@ -3916,13 +3845,15 @@ void ObjectSet::setClipGroup() // check if something is selected bool is_empty = isEmpty(); - if ( apply_to_layer && is_empty) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from.")); + if (apply_to_layer && is_empty) { + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>object(s)</b> to create clippath or mask from.")); return; - } else if (!apply_to_layer && ( is_empty || boost::distance(items())==1 )) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to.")); + } else if (!apply_to_layer && (is_empty || boost::distance(items()) == 1)) { + if (desktop()) + desktop()->messageStack()->flash( + Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to.")); return; } @@ -3939,7 +3870,7 @@ void ObjectSet::setClipGroup() // Comment out this section because we don't need it, I think. // Also updated comment code to work correctly if indeed it's needed. // To reactivate, remove the next line and uncomment the section. - std::vector<SPItem*> items_(items().begin(), items().end()); + std::vector<SPItem *> items_(items().begin(), items().end()); /* std::vector<SPItem*> items_prerect_(items().begin(), items().end()); std::vector<SPItem*> items_; @@ -3957,16 +3888,16 @@ void ObjectSet::setClipGroup() } clear(); */ - sort(items_.begin(),items_.end(),sp_object_compare_position_bool); + sort(items_.begin(), items_.end(), sp_object_compare_position_bool); // See lp bug #542004 clear(); // create a list of duplicates - std::vector<std::pair<Inkscape::XML::Node*, Geom::Affine>> mask_items; - std::vector<SPItem*> apply_to_items; - std::vector<SPItem*> items_to_delete; - std::vector<SPItem*> items_to_select; + std::vector<std::pair<Inkscape::XML::Node *, Geom::Affine>> mask_items; + std::vector<SPItem *> apply_to_items; + std::vector<SPItem *> items_to_delete; + std::vector<SPItem *> items_to_select; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool topmost = prefs->getBool("/options/maskobject/topmost", true); @@ -3978,22 +3909,19 @@ void ObjectSet::setClipGroup() apply_to_items.push_back(SP_ITEM(desktop()->currentLayer())); } - for (std::vector<SPItem*>::const_iterator i=items_.begin();i!=items_.end();++i) { - if((!topmost && !apply_to_layer && *i == items_.front()) - || (topmost && !apply_to_layer && *i == items_.back()) - || apply_to_layer){ - + for (std::vector<SPItem *>::const_iterator i = items_.begin(); i != items_.end(); ++i) { + if ((!topmost && !apply_to_layer && *i == items_.front()) || + (topmost && !apply_to_layer && *i == items_.back()) || apply_to_layer) { Inkscape::XML::Node *dup = (*i)->getRepr()->duplicate(xml_doc); mask_items.emplace_back(dup, (*i)->i2doc_affine()); if (remove_original) { items_to_delete.push_back(*i); - } - else { + } else { items_to_select.push_back(*i); } continue; - }else{ + } else { apply_to_items.push_back(*i); items_to_select.push_back(*i); } @@ -4004,7 +3932,7 @@ void ObjectSet::setClipGroup() if (grouping == PREFS_MASKOBJECT_GROUPING_ALL) { // group all those objects into one group // and apply mask to that - ObjectSet* set = new ObjectSet(document()); + ObjectSet *set = new ObjectSet(document()); set->add(apply_to_items.begin(), apply_to_items.end()); items_to_select.clear(); @@ -4014,9 +3942,9 @@ void ObjectSet::setClipGroup() // apply clip/mask only to newly created group apply_to_items.clear(); - apply_to_items.push_back(dynamic_cast<SPItem*>(doc->getObjectByRepr(group))); + apply_to_items.push_back(dynamic_cast<SPItem *>(doc->getObjectByRepr(group))); - items_to_select.push_back((SPItem*)(doc->getObjectByRepr(group))); + items_to_select.push_back((SPItem *)(doc->getObjectByRepr(group))); delete set; Inkscape::GC::release(group); @@ -4025,13 +3953,12 @@ void ObjectSet::setClipGroup() items_to_select.clear(); } - gchar const *attributeName = apply_clip_path ? "clip-path" : "mask"; - for (std::vector<SPItem*>::const_reverse_iterator i = apply_to_items.rbegin(); i != apply_to_items.rend(); ++i) { + for (std::vector<SPItem *>::const_reverse_iterator i = apply_to_items.rbegin(); i != apply_to_items.rend(); ++i) { SPItem *item = reinterpret_cast<SPItem *>(*i); - std::vector<Inkscape::XML::Node*> mask_items_dup; - std::map<Inkscape::XML::Node*, Geom::Affine> dup_transf; - for (auto & mask_item : mask_items) { + std::vector<Inkscape::XML::Node *> mask_items_dup; + std::map<Inkscape::XML::Node *, Geom::Affine> dup_transf; + for (auto &mask_item : mask_items) { Inkscape::XML::Node *dup = (mask_item.first)->duplicate(xml_doc); mask_items_dup.push_back(dup); dup_transf[dup] = mask_item.second; @@ -4055,7 +3982,7 @@ void ObjectSet::setClipGroup() // Apply clip/mask to group instead apply_mask_to = group; - items_to_select.push_back((SPItem*)doc->getObjectByRepr(group)); + items_to_select.push_back((SPItem *)doc->getObjectByRepr(group)); Inkscape::GC::release(spnew); Inkscape::GC::release(group); } @@ -4069,18 +3996,17 @@ void ObjectSet::setClipGroup() // inverted object transform should be applied to a mask object, // as mask is calculated in user space (after applying transform) - for (auto & it : mask_items_dup) { + for (auto &it : mask_items_dup) { SPItem *clip_item = SP_ITEM(doc->getObjectByRepr(it)); clip_item->doWriteTransform(dup_transf[it]); clip_item->doWriteTransform(clip_item->transform * item->i2doc_affine().inverse()); } apply_mask_to->setAttribute(attributeName, Glib::ustring("url(#") + mask_id + ')'); - } for (auto i : items_to_delete) { - SPObject *item = reinterpret_cast<SPObject*>(i); + SPObject *item = reinterpret_cast<SPObject *>(i); item->deleteObject(false); items_to_select.erase(std::remove(items_to_select.begin(), items_to_select.end(), item), items_to_select.end()); } @@ -4095,14 +4021,16 @@ void ObjectSet::setClipGroup() } } -void ObjectSet::unsetMask(const bool apply_clip_path, const bool skip_undo) { +void ObjectSet::unsetMask(const bool apply_clip_path, const bool skip_undo) +{ SPDocument *doc = document(); Inkscape::XML::Document *xml_doc = doc->getReprDoc(); // check if something is selected if (isEmpty()) { - if(desktop()) - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from.")); + if (desktop()) + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>object(s)</b> to remove clippath or mask from.")); return; } @@ -4112,18 +4040,17 @@ void ObjectSet::unsetMask(const bool apply_clip_path, const bool skip_undo) { doc->ensureUpToDate(); gchar const *attributeName = apply_clip_path ? "clip-path" : "mask"; - std::map<SPObject*,SPItem*> referenced_objects; + std::map<SPObject *, SPItem *> referenced_objects; - std::vector<SPItem*> items_(items().begin(), items().end()); + std::vector<SPItem *> items_(items().begin(), items().end()); clear(); std::vector<SPGroup *> items_to_ungroup; - std::vector<SPItem*> items_to_select(items_); - + std::vector<SPItem *> items_to_select(items_); // SPObject* refers to a group containing the clipped path or mask itself, // whereas SPItem* refers to the item being clipped or masked - for (auto i : items_){ + for (auto i : items_) { if (remove_original) { // remember referenced mask/clippath, so orphaned masks can be moved back to document SPItem *item = i; @@ -4145,22 +4072,21 @@ void ObjectSet::unsetMask(const bool apply_clip_path, const bool skip_undo) { SPGroup *group = dynamic_cast<SPGroup *>(i); if (ungroup_masked && group) { - // if we had previously enclosed masked object in group, - // add it to list so we can ungroup it later - - // ungroup only groups we created when setting clip/mask - if (group->layerMode() == SPGroup::MASK_HELPER) { - items_to_ungroup.push_back(group); - } + // if we had previously enclosed masked object in group, + // add it to list so we can ungroup it later + // ungroup only groups we created when setting clip/mask + if (group->layerMode() == SPGroup::MASK_HELPER) { + items_to_ungroup.push_back(group); + } } } // restore mask objects into a document - for (auto & referenced_object : referenced_objects) { + for (auto &referenced_object : referenced_objects) { SPObject *obj = referenced_object.first; // Group containing the clipped paths or masks std::vector<Inkscape::XML::Node *> items_to_move; - for (auto& child: obj->children) { + for (auto &child : obj->children) { // Collect all clipped paths and masks within a single group Inkscape::XML::Node *copy = child.getRepr()->duplicate(xml_doc); if (copy->attribute("inkscape:original-d") && copy->attribute("inkscape:path-effect")) { @@ -4185,7 +4111,7 @@ void ObjectSet::unsetMask(const bool apply_clip_path, const bool skip_undo) { Inkscape::XML::Node *ref_repr = referenced_object.second->getRepr(); // Iterate through all clipped paths / masks - for (auto i=items_to_move.rbegin();i!=items_to_move.rend();++i) { + for (auto i = items_to_move.rbegin(); i != items_to_move.rend(); ++i) { Inkscape::XML::Node *repr = *i; // insert into parent, restore pos @@ -4205,13 +4131,14 @@ void ObjectSet::unsetMask(const bool apply_clip_path, const bool skip_undo) { } // ungroup marked groups added when setting mask - for (auto i=items_to_ungroup.rbegin();i!=items_to_ungroup.rend();++i) { + for (auto i = items_to_ungroup.rbegin(); i != items_to_ungroup.rend(); ++i) { SPGroup *group = *i; if (group) { - items_to_select.erase(std::remove(items_to_select.begin(), items_to_select.end(), group), items_to_select.end()); - std::vector<SPItem*> children; + items_to_select.erase(std::remove(items_to_select.begin(), items_to_select.end(), group), + items_to_select.end()); + std::vector<SPItem *> children; sp_item_group_ungroup(group, children, false); - items_to_select.insert(items_to_select.end(),children.rbegin(),children.rend()); + items_to_select.insert(items_to_select.end(), children.rbegin(), children.rend()); } else { g_assert_not_reached(); } @@ -4238,16 +4165,15 @@ bool ObjectSet::fitCanvas(bool with_margins, bool skip_undo) g_return_val_if_fail(document() != nullptr, false); if (isEmpty()) { - if(desktop()) + if (desktop()) desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to.")); return false; } Geom::OptRect const bbox = documentBounds(SPItem::VISUAL_BBOX); if (bbox) { document()->fitToRect(*bbox, with_margins); - if(!skip_undo) - DocumentUndo::done(document(), SP_VERB_FIT_CANVAS_TO_SELECTION, - _("Fit Page to Selection")); + if (!skip_undo) + DocumentUndo::done(document(), SP_VERB_FIT_CANVAS_TO_SELECTION, _("Fit Page to Selection")); return true; } else { return false; @@ -4264,24 +4190,23 @@ void ObjectSet::swapFillStroke() SPPaintServer *server; Glib::ustring _paintserver_id; - auto list= items(); - for (auto itemlist=list.begin();itemlist!=list.end();++itemlist) { + auto list = items(); + for (auto itemlist = list.begin(); itemlist != list.end(); ++itemlist) { SPItem *item = *itemlist; - SPCSSAttr *css = sp_repr_css_attr_new (); + SPCSSAttr *css = sp_repr_css_attr_new(); _paintserver_id.clear(); paint = &(item->style->fill); if (paint->set && paint->isNone()) - sp_repr_css_set_property (css, "stroke", "none"); + sp_repr_css_set_property(css, "stroke", "none"); else if (paint->set && paint->isColor()) { - guint32 color = paint->value.color.toRGBA32(SP_SCALE24_TO_FLOAT (item->style->fill_opacity.value)); + guint32 color = paint->value.color.toRGBA32(SP_SCALE24_TO_FLOAT(item->style->fill_opacity.value)); gchar c[64]; - sp_svg_write_color (c, sizeof(c), color); - sp_repr_css_set_property (css, "stroke", c); - } - else if (!paint->set) - sp_repr_css_unset_property (css, "stroke"); + sp_svg_write_color(c, sizeof(c), color); + sp_repr_css_set_property(css, "stroke", c); + } else if (!paint->set) + sp_repr_css_unset_property(css, "stroke"); else if (paint->set && paint->isPaintserver()) { server = SP_STYLE_FILL_SERVER(item->style); if (server) { @@ -4289,22 +4214,21 @@ void ObjectSet::swapFillStroke() _paintserver_id += "url(#"; _paintserver_id += srepr->attribute("id"); _paintserver_id += ")"; - sp_repr_css_set_property (css, "stroke", _paintserver_id.c_str()); + sp_repr_css_set_property(css, "stroke", _paintserver_id.c_str()); } } _paintserver_id.clear(); paint = &(item->style->stroke); if (paint->set && paint->isNone()) - sp_repr_css_set_property (css, "fill", "none"); + sp_repr_css_set_property(css, "fill", "none"); else if (paint->set && paint->isColor()) { - guint32 color = paint->value.color.toRGBA32(SP_SCALE24_TO_FLOAT (item->style->stroke_opacity.value)); + guint32 color = paint->value.color.toRGBA32(SP_SCALE24_TO_FLOAT(item->style->stroke_opacity.value)); gchar c[64]; - sp_svg_write_color (c, sizeof(c), color); - sp_repr_css_set_property (css, "fill", c); - } - else if (!paint->set) - sp_repr_css_unset_property (css, "fill"); + sp_svg_write_color(c, sizeof(c), color); + sp_repr_css_set_property(css, "fill", c); + } else if (!paint->set) + sp_repr_css_unset_property(css, "fill"); else if (paint->set && paint->isPaintserver()) { server = SP_STYLE_STROKE_SERVER(item->style); if (server) { @@ -4312,16 +4236,15 @@ void ObjectSet::swapFillStroke() _paintserver_id += "url(#"; _paintserver_id += srepr->attribute("id"); _paintserver_id += ")"; - sp_repr_css_set_property (css, "fill", _paintserver_id.c_str()); + sp_repr_css_set_property(css, "fill", _paintserver_id.c_str()); } } sp_desktop_apply_css_recursive(item, css, true); - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); } - DocumentUndo::done(document(), SP_VERB_EDIT_SWAP_FILL_STROKE, - _("Swap fill and stroke of an object")); + DocumentUndo::done(document(), SP_VERB_EDIT_SWAP_FILL_STROKE, _("Swap fill and stroke of an object")); } /** @@ -4340,23 +4263,24 @@ void ObjectSet::fillBetweenMany() { if (isEmpty()) { if (desktop()) { - desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to create fill between.")); + desktop()->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>path(s)</b> to create fill between.")); } return; } - SPDocument *doc = document(); - SPObject *defs = doc->getDefs(); + SPDocument *doc = document(); + SPObject *defs = doc->getDefs(); SPObject *effect = nullptr; Inkscape::XML::Node *effectRepr = doc->getReprDoc()->createElement("inkscape:path-effect"); - Inkscape::XML::Node *fillRepr = doc->getReprDoc()->createElement("svg:path"); + Inkscape::XML::Node *fillRepr = doc->getReprDoc()->createElement("svg:path"); Glib::ustring acc; Glib::ustring pathTarget; - for (auto&& item : items()) { + for (auto &&item : items()) { // Force-assign id if there is none present if (!item->getId()) { gchar *id = sp_object_get_unique_id(item, nullptr); @@ -4384,9 +4308,9 @@ void ObjectSet::fillBetweenMany() fillRepr->setAttribute("d", "M 0,0"); // Get bottommost element in selection to create fill underneath - auto&& items_ = std::vector<SPObject*>(items().begin(), items().end()); + auto &&items_ = std::vector<SPObject *>(items().begin(), items().end()); SPObject *first = *std::min_element(items_.begin(), items_.end(), sp_object_compare_position_bool); - SPObject *prev = first->getPrev(); + SPObject *prev = first->getPrev(); first->parent->addChild(fillRepr, prev ? prev->getRepr() : nullptr); @@ -4402,8 +4326,7 @@ void ObjectSet::fillBetweenMany() * \param with_margins margins defined in the xml under <sodipodi:namedview> * "fit-margin-..." attributes. See SPDocument::fitToRect. */ -bool -fit_canvas_to_drawing(SPDocument *doc, bool with_margins) +bool fit_canvas_to_drawing(SPDocument *doc, bool with_margins) { g_return_val_if_fail(doc != nullptr, false); @@ -4418,12 +4341,10 @@ fit_canvas_to_drawing(SPDocument *doc, bool with_margins) } } -void -verb_fit_canvas_to_drawing(SPDesktop *desktop) +void verb_fit_canvas_to_drawing(SPDesktop *desktop) { if (fit_canvas_to_drawing(desktop->getDocument())) { - DocumentUndo::done(desktop->getDocument(), SP_VERB_FIT_CANVAS_TO_DRAWING, - _("Fit Page to Drawing")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_FIT_CANVAS_TO_DRAWING, _("Fit Page to Drawing")); } } @@ -4432,23 +4353,24 @@ verb_fit_canvas_to_drawing(SPDesktop *desktop) * "fit-margin-..." attributes. See SPDocument::fitToRect and * ui/dialog/page-sizer. */ -void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) { +void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) +{ g_return_if_fail(desktop != nullptr); SPDocument *doc = desktop->getDocument(); g_return_if_fail(doc != nullptr); g_return_if_fail(desktop->selection != nullptr); - bool const changed = ( desktop->selection->isEmpty() - ? fit_canvas_to_drawing(doc, true) - : desktop->selection->fitCanvas(true,true)); + bool const changed = + (desktop->selection->isEmpty() ? fit_canvas_to_drawing(doc, true) : desktop->selection->fitCanvas(true, true)); if (changed) { DocumentUndo::done(desktop->getDocument(), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING, _("Fit Page to Selection or Drawing")); } }; -static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) { +static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) +{ // don't operate on layers { SPItem *item = dynamic_cast<SPItem *>(root); @@ -4456,8 +4378,8 @@ static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDes f(item, desktop); } } - for (auto& child: root->children) { - //don't recurse into locked layers + for (auto &child : root->children) { + // don't recurse into locked layers SPItem *item = dynamic_cast<SPItem *>(&child); if (!(item && desktop->isLayer(item) && item->isLocked())) { itemtree_map(f, &child, desktop); @@ -4465,20 +4387,24 @@ static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDes } } -static void unlock(SPItem *item, SPDesktop */*desktop*/) { +static void unlock(SPItem *item, SPDesktop * /*desktop*/) +{ if (item->isLocked()) { item->setLocked(FALSE); } } -static void unhide(SPItem *item, SPDesktop *desktop) { +static void unhide(SPItem *item, SPDesktop *desktop) +{ if (desktop->itemIsHidden(item)) { item->setExplicitlyHidden(FALSE); } } -static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) { - if (!dt) return; +static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) +{ + if (!dt) + return; SPObject *root; if (layer_only) { @@ -4490,23 +4416,26 @@ static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool la itemtree_map(f, root, dt); } -void unlock_all(SPDesktop *dt) { +void unlock_all(SPDesktop *dt) +{ process_all(&unlock, dt, true); } -void unlock_all_in_all_layers(SPDesktop *dt) { +void unlock_all_in_all_layers(SPDesktop *dt) +{ process_all(&unlock, dt, false); } -void unhide_all(SPDesktop *dt) { +void unhide_all(SPDesktop *dt) +{ process_all(&unhide, dt, true); } -void unhide_all_in_all_layers(SPDesktop *dt) { +void unhide_all_in_all_layers(SPDesktop *dt) +{ process_all(&unhide, dt, false); } - /* Local Variables: mode:c++ diff --git a/src/selection-chemistry.h b/src/selection-chemistry.h index 771066b817fc2c0b7855604eded3118e80669b1a..c303d4b7ee77e43ec9aff8fd5de34d7c3442d354 100644 --- a/src/selection-chemistry.h +++ b/src/selection-chemistry.h @@ -19,8 +19,8 @@ */ #include <2geom/forward.h> -#include <vector> #include <glibmm/ustring.h> +#include <vector> class SPCSSAttr; class SPDesktop; @@ -34,53 +34,53 @@ class Selection; class ObjectSet; namespace LivePathEffect { - class PathParam; +class PathParam; } - class SelectionHelper { - public: - static void selectAll(SPDesktop *desktop); - static void selectAllInAll(SPDesktop *desktop); - static void selectNone(SPDesktop *desktop); - static void selectSameFillStroke(SPDesktop *dt); - static void selectSameFillColor(SPDesktop *dt); - static void selectSameStrokeColor(SPDesktop *dt); - static void selectSameStrokeStyle(SPDesktop *dt); - static void selectSameObjectType(SPDesktop *dt); - static void invert(SPDesktop *desktop); - static void invertAllInAll(SPDesktop *desktop); - static void reverse(SPDesktop *dt); - static void selectNext(SPDesktop *desktop); - static void selectPrev(SPDesktop *desktop); - static void fixSelection(SPDesktop *desktop); - }; +class SelectionHelper +{ +public: + static void selectAll(SPDesktop *desktop); + static void selectAllInAll(SPDesktop *desktop); + static void selectNone(SPDesktop *desktop); + static void selectSameFillStroke(SPDesktop *dt); + static void selectSameFillColor(SPDesktop *dt); + static void selectSameStrokeColor(SPDesktop *dt); + static void selectSameStrokeStyle(SPDesktop *dt); + static void selectSameObjectType(SPDesktop *dt); + static void invert(SPDesktop *desktop); + static void invertAllInAll(SPDesktop *desktop); + static void reverse(SPDesktop *dt); + static void selectNext(SPDesktop *desktop); + static void selectPrev(SPDesktop *desktop); + static void fixSelection(SPDesktop *desktop); +}; } // namespace Inkscape void sp_edit_clear_all(Inkscape::Selection *selection); void sp_edit_select_all(SPDesktop *desktop); -void sp_edit_select_all_in_all_layers (SPDesktop *desktop); -void sp_edit_invert (SPDesktop *desktop); -void sp_edit_invert_in_all_layers (SPDesktop *desktop); - +void sp_edit_select_all_in_all_layers(SPDesktop *desktop); +void sp_edit_invert(SPDesktop *desktop); +void sp_edit_invert_in_all_layers(SPDesktop *desktop); -SPCSSAttr *take_style_from_item (SPObject *object); +SPCSSAttr *take_style_from_item(SPObject *object); void sp_selection_paste(SPDesktop *desktop, bool in_place); -void sp_set_style_clipboard (SPCSSAttr *css); +void sp_set_style_clipboard(SPCSSAttr *css); +void sp_selection_item_next(SPDesktop *desktop); +void sp_selection_item_prev(SPDesktop *desktop); -void sp_selection_item_next (SPDesktop *desktop); -void sp_selection_item_prev (SPDesktop *desktop); +void sp_selection_next_patheffect_param(SPDesktop *dt); -void sp_selection_next_patheffect_param(SPDesktop * dt); +// void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip); -//void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip); - -enum SPSelectStrokeStyleType { - SP_FILL_COLOR = 0, - SP_STROKE_COLOR = 1, +enum SPSelectStrokeStyleType +{ + SP_FILL_COLOR = 0, + SP_STROKE_COLOR = 1, SP_STROKE_STYLE_WIDTH = 2, SP_STROKE_STYLE_DASHES = 3, SP_STROKE_STYLE_MARKERS = 4, @@ -91,15 +91,16 @@ enum SPSelectStrokeStyleType { void sp_select_same_fill_stroke_style(SPDesktop *desktop, gboolean fill, gboolean strok, gboolean style); void sp_select_same_object_type(SPDesktop *desktop); -std::vector<SPItem*> sp_get_same_style(SPItem *sel, std::vector<SPItem*> &src, SPSelectStrokeStyleType type=SP_STYLE_ALL); -std::vector<SPItem*> sp_get_same_object_type(SPItem *sel, std::vector<SPItem*> &src); +std::vector<SPItem *> sp_get_same_style(SPItem *sel, std::vector<SPItem *> &src, + SPSelectStrokeStyleType type = SP_STYLE_ALL); +std::vector<SPItem *> sp_get_same_object_type(SPItem *sel, std::vector<SPItem *> &src); void scroll_to_show_item(SPDesktop *desktop, SPItem *item); -void sp_undo (SPDesktop *desktop, SPDocument *doc); -void sp_redo (SPDesktop *desktop, SPDocument *doc); +void sp_undo(SPDesktop *desktop, SPDocument *doc); +void sp_redo(SPDesktop *desktop, SPDocument *doc); -void sp_document_get_export_hints (SPDocument * doc, Glib::ustring &filename, float *xdpi, float *ydpi); +void sp_document_get_export_hints(SPDocument *doc, Glib::ustring &filename, float *xdpi, float *ydpi); bool fit_canvas_to_drawing(SPDocument *, bool with_margins = false); void verb_fit_canvas_to_drawing(SPDesktop *); @@ -110,20 +111,19 @@ void unlock_all_in_all_layers(SPDesktop *dt); void unhide_all(SPDesktop *dt); void unhide_all_in_all_layers(SPDesktop *dt); -std::vector<SPItem*> &get_all_items(std::vector<SPItem*> &list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, bool ingroups, std::vector<SPItem*> const &exclude); +std::vector<SPItem *> &get_all_items(std::vector<SPItem *> &list, SPObject *from, SPDesktop *desktop, bool onlyvisible, + bool onlysensitive, bool ingroups, std::vector<SPItem *> const &exclude); -std::vector<SPItem*> sp_degroup_list (std::vector<SPItem*> &items); +std::vector<SPItem *> sp_degroup_list(std::vector<SPItem *> &items); /* selection cycling */ enum SPCycleType { SP_CYCLE_SIMPLE, SP_CYCLE_VISIBLE, // cycle only visible items - SP_CYCLE_FOCUS // readjust visible area to view selected item + SP_CYCLE_FOCUS // readjust visible area to view selected item }; - - // TODO FIXME: This should be moved into preference repr extern SPCycleType SP_CYCLING; diff --git a/src/selection-describer.cpp b/src/selection-describer.cpp index 526d5269edcc68d44f33d504040526570b74373d..af0fc4adf3bc404b6fd94845bce6f9b351c8ce90 100644 --- a/src/selection-describer.cpp +++ b/src/selection-describer.cpp @@ -13,18 +13,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "selection-describer.h" + +#include <glibmm/i18n.h> #include <memory> #include <set> #include <utility> -#include <glibmm/i18n.h> - -#include "selection-describer.h" - -#include "layer-model.h" -#include "selection.h" #include "desktop.h" - +#include "layer-model.h" #include "object/sp-flowtext.h" #include "object/sp-image.h" #include "object/sp-offset.h" @@ -32,11 +29,11 @@ #include "object/sp-symbol.h" #include "object/sp-textpath.h" #include "object/sp-use.h" - +#include "selection.h" #include "xml/quote.h" // Returns a list of terms for the items to be used in the statusbar -char* collect_terms (const std::vector<SPItem*> &items) +char *collect_terms(const std::vector<SPItem *> &items) { std::set<Glib::ustring> check; std::stringstream ss; @@ -55,10 +52,10 @@ char* collect_terms (const std::vector<SPItem*> &items) } // Returns the number of terms in the list -static int count_terms (const std::vector<SPItem*> &items) +static int count_terms(const std::vector<SPItem *> &items) { std::set<Glib::ustring> check; - int count=0; + int count = 0; for (auto item : items) { if (item && item->displayName()) { Glib::ustring term(item->displayName()); @@ -71,9 +68,9 @@ static int count_terms (const std::vector<SPItem*> &items) } // Returns the number of filtered items in the list -static int count_filtered (const std::vector<SPItem*> &items) +static int count_filtered(const std::vector<SPItem *> &items) { - int count=0; + int count = 0; for (auto item : items) { if (item) { count += item->isFiltered(); @@ -82,17 +79,16 @@ static int count_filtered (const std::vector<SPItem*> &items) return count; } - namespace Inkscape { -SelectionDescriber::SelectionDescriber(Inkscape::Selection *selection, std::shared_ptr<MessageStack> stack, char *when_selected, char *when_nothing) - : _context(std::move(stack)), - _when_selected (when_selected), - _when_nothing (when_nothing) +SelectionDescriber::SelectionDescriber(Inkscape::Selection *selection, std::shared_ptr<MessageStack> stack, + char *when_selected, char *when_nothing) + : _context(std::move(stack)) + , _when_selected(when_selected) + , _when_nothing(when_nothing) { - _selection_changed_connection = new sigc::connection ( - selection->connectChanged( - sigc::mem_fun(*this, &SelectionDescriber::_updateMessageFromSelection))); + _selection_changed_connection = new sigc::connection( + selection->connectChanged(sigc::mem_fun(*this, &SelectionDescriber::_updateMessageFromSelection))); _updateMessageFromSelection(selection); } @@ -102,8 +98,9 @@ SelectionDescriber::~SelectionDescriber() delete _selection_changed_connection; } -void SelectionDescriber::_updateMessageFromSelection(Inkscape::Selection *selection) { - std::vector<SPItem*> items(selection->items().begin(), selection->items().end()); +void SelectionDescriber::_updateMessageFromSelection(Inkscape::Selection *selection) +{ + std::vector<SPItem *> items(selection->items().begin(), selection->items().end()); if (items.empty()) { // no items _context.set(Inkscape::NORMAL_MESSAGE, _when_nothing); @@ -117,7 +114,7 @@ void SelectionDescriber::_updateMessageFromSelection(Inkscape::Selection *select gchar *layer_name; if (layer == root) { layer_name = g_strdup(_("root")); - } else if(!layer) { + } else if (!layer) { layer_name = g_strdup(_("none")); } else { char const *layer_label; @@ -164,47 +161,44 @@ void SelectionDescriber::_updateMessageFromSelection(Inkscape::Selection *select else in_phrase = g_strdup_printf(_(" in unnamed group (%s)"), layer_name); } else { - in_phrase = g_strdup_printf(ngettext(" in <b>%i</b> parent (%s)", " in <b>%i</b> parents (%s)", num_parents), num_parents, layer_name); + in_phrase = + g_strdup_printf(ngettext(" in <b>%i</b> parent (%s)", " in <b>%i</b> parents (%s)", num_parents), + num_parents, layer_name); } } else { - in_phrase = g_strdup_printf(ngettext(" in <b>%i</b> layer", " in <b>%i</b> layers", num_layers), num_layers); + in_phrase = + g_strdup_printf(ngettext(" in <b>%i</b> layer", " in <b>%i</b> layers", num_layers), num_layers); } - g_free (layer_name); - g_free (parent_name); + g_free(layer_name); + g_free(parent_name); - if (items.size()==1) { // one item + if (items.size() == 1) { // one item char *item_desc = item->detailedDescription(); bool isUse = dynamic_cast<SPUse *>(item) != nullptr; if (isUse && dynamic_cast<SPSymbol *>(item->firstChild())) { - _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s. %s.", - item_desc, in_phrase, + _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s. %s.", item_desc, in_phrase, _("Convert symbol to group to edit"), _when_selected); } else if (dynamic_cast<SPSymbol *>(item)) { - _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s.", - item_desc, in_phrase, + _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s.", item_desc, in_phrase, _("Remove from symbols tray to edit symbol")); } else { SPOffset *offset = (isUse) ? nullptr : dynamic_cast<SPOffset *>(item); if (isUse || (offset && offset->sourceHref)) { - _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s. %s.", - item_desc, in_phrase, + _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s. %s.", item_desc, in_phrase, _("Use <b>Shift+D</b> to look up original"), _when_selected); } else { SPText *text = dynamic_cast<SPText *>(item); if (text && text->firstChild() && dynamic_cast<SPText *>(text->firstChild())) { - _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s. %s.", - item_desc, in_phrase, + _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s. %s.", item_desc, in_phrase, _("Use <b>Shift+D</b> to look up path"), _when_selected); } else { SPFlowtext *flowtext = dynamic_cast<SPFlowtext *>(item); if (flowtext && !flowtext->has_internal_frame()) { - _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s. %s.", - item_desc, in_phrase, + _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s. %s.", item_desc, in_phrase, _("Use <b>Shift+D</b> to look up frame"), _when_selected); } else { - _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s.", - item_desc, in_phrase, _when_selected); + _context.setF(Inkscape::NORMAL_MESSAGE, "%s%s. %s.", item_desc, in_phrase, _when_selected); } } } @@ -213,22 +207,21 @@ void SelectionDescriber::_updateMessageFromSelection(Inkscape::Selection *select g_free(item_desc); } else { // multiple items int objcount = items.size(); - char *terms = collect_terms (items); + char *terms = collect_terms(items); int n_terms = count_terms(items); - - gchar *objects_str = g_strdup_printf(ngettext( - "<b>%1$i</b> objects selected of type %2$s", - "<b>%1$i</b> objects selected of types %2$s", n_terms), - objcount, terms); + + gchar *objects_str = g_strdup_printf(ngettext("<b>%1$i</b> objects selected of type %2$s", + "<b>%1$i</b> objects selected of types %2$s", n_terms), + objcount, terms); g_free(terms); // indicate all, some, or none filtered gchar *filt_str = nullptr; - int n_filt = count_filtered(items); //all filtered + int n_filt = count_filtered(items); // all filtered if (n_filt) { - filt_str = g_strdup_printf(ngettext("; <i>%d filtered object</i> ", - "; <i>%d filtered objects</i> ", n_filt), n_filt); + filt_str = g_strdup_printf( + ngettext("; <i>%d filtered object</i> ", "; <i>%d filtered objects</i> ", n_filt), n_filt); } else { filt_str = g_strdup(""); } @@ -248,7 +241,7 @@ void SelectionDescriber::_updateMessageFromSelection(Inkscape::Selection *select } } -} +} // namespace Inkscape /* Local Variables: diff --git a/src/selection-describer.h b/src/selection-describer.h index 259f5b2337f02e514de4144c5ecc82bc3bada7bd..96216a64acd80a1eea1a953fd65672f9324a1299 100644 --- a/src/selection-describer.h +++ b/src/selection-describer.h @@ -16,6 +16,7 @@ #include <cstddef> #include <memory> #include <sigc++/sigc++.h> + #include "message-context.h" namespace Inkscape { @@ -23,9 +24,11 @@ namespace Inkscape { class MessageStack; class Selection; -class SelectionDescriber : public sigc::trackable { +class SelectionDescriber : public sigc::trackable +{ public: - SelectionDescriber(Inkscape::Selection *selection, std::shared_ptr<MessageStack> stack, char *when_selected, char *when_nothing); + SelectionDescriber(Inkscape::Selection *selection, std::shared_ptr<MessageStack> stack, char *when_selected, + char *when_nothing); ~SelectionDescriber(); private: @@ -38,7 +41,7 @@ private: char *_when_nothing; }; -} +} // namespace Inkscape #endif diff --git a/src/selection.cpp b/src/selection.cpp index 2b701a43fd0d676b9d6a0c017b39798925f1089f..3cf415bb9da4754b1f4d700fa739d319c9d186ea 100644 --- a/src/selection.cpp +++ b/src/selection.cpp @@ -22,33 +22,33 @@ #ifdef HAVE_CONFIG_H #endif -#include "inkscape.h" -#include "preferences.h" #include "desktop.h" #include "document.h" -#include "ui/tools/node-tool.h" -#include "ui/tool/multi-path-manipulator.h" -#include "ui/tool/path-manipulator.h" -#include "ui/tool/control-point-selection.h" -#include "object/sp-path.h" +#include "inkscape.h" #include "object/sp-defs.h" +#include "object/sp-path.h" #include "object/sp-shape.h" +#include "preferences.h" +#include "ui/tool/control-point-selection.h" +#include "ui/tool/multi-path-manipulator.h" +#include "ui/tool/path-manipulator.h" +#include "ui/tools/node-tool.h" #include "xml/repr.h" #define SP_SELECTION_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE + 1) namespace Inkscape { -Selection::Selection(LayerModel *layers, SPDesktop *desktop): - ObjectSet(desktop), - _layers(layers), - _selection_context(nullptr), - _flags(0), - _idle(0) -{ -} +Selection::Selection(LayerModel *layers, SPDesktop *desktop) + : ObjectSet(desktop) + , _layers(layers) + , _selection_context(nullptr) + , _flags(0) + , _idle(0) +{} -Selection::~Selection() { +Selection::~Selection() +{ _layers = nullptr; if (_idle) { g_source_remove(_idle); @@ -62,10 +62,12 @@ Selection::~Selection() { /* Handler for selected objects "modified" signal */ -void Selection::_schedule_modified(SPObject */*obj*/, guint flags) { +void Selection::_schedule_modified(SPObject * /*obj*/, guint flags) +{ if (!this->_idle) { /* Request handling to be run in _idle loop */ - this->_idle = g_idle_add_full(SP_SELECTION_UPDATE_PRIORITY, GSourceFunc(&Selection::_emit_modified), this, nullptr); + this->_idle = + g_idle_add_full(SP_SELECTION_UPDATE_PRIORITY, GSourceFunc(&Selection::_emit_modified), this, nullptr); } /* Collect all flags */ @@ -85,17 +87,20 @@ gboolean Selection::_emit_modified(Selection *selection) return FALSE; } -void Selection::_emitModified(guint flags) { +void Selection::_emitModified(guint flags) +{ INKSCAPE.selection_modified(this, flags); _modified_signal.emit(this, flags); } -void Selection::_emitChanged(bool persist_selection_context/* = false */) { +void Selection::_emitChanged(bool persist_selection_context /* = false */) +{ if (persist_selection_context) { if (nullptr == _selection_context) { _selection_context = _layers->currentLayer(); sp_object_ref(_selection_context, nullptr); - _context_release_connection = _selection_context->connectRelease(sigc::mem_fun(*this, &Selection::_releaseContext)); + _context_release_connection = + _selection_context->connectRelease(sigc::mem_fun(*this, &Selection::_releaseContext)); } } else { _releaseContext(_selection_context); @@ -116,25 +121,28 @@ void Selection::_releaseContext(SPObject *obj) _selection_context = nullptr; } -SPObject *Selection::activeContext() { +SPObject *Selection::activeContext() +{ if (nullptr != _selection_context) return _selection_context; return _layers->currentLayer(); } -std::vector<Inkscape::SnapCandidatePoint> Selection::getSnapPoints(SnapPreferences const *snapprefs) const { +std::vector<Inkscape::SnapCandidatePoint> Selection::getSnapPoints(SnapPreferences const *snapprefs) const +{ std::vector<Inkscape::SnapCandidatePoint> p; - if (snapprefs != nullptr){ + if (snapprefs != nullptr) { SnapPreferences snapprefs_dummy = *snapprefs; // create a local copy of the snapping prefs - snapprefs_dummy.setTargetSnappable(Inkscape::SNAPTARGET_ROTATION_CENTER, false); // locally disable snapping to the item center + snapprefs_dummy.setTargetSnappable(Inkscape::SNAPTARGET_ROTATION_CENTER, + false); // locally disable snapping to the item center auto items = const_cast<Selection *>(this)->items(); for (auto iter = items.begin(); iter != items.end(); ++iter) { SPItem *this_item = *iter; this_item->getSnappoints(p, &snapprefs_dummy); - //Include the transformation origin for snapping - //For a selection or group only the overall center is considered, not for each item individually + // Include the transformation origin for snapping + // For a selection or group only the overall center is considered, not for each item individually if (snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_ROTATION_CENTER)) { p.emplace_back(this_item->getCenter(), SNAPSOURCE_ROTATION_CENTER); } @@ -144,16 +152,18 @@ std::vector<Inkscape::SnapCandidatePoint> Selection::getSnapPoints(SnapPreferenc return p; } -SPObject *Selection::_objectForXMLNode(Inkscape::XML::Node *repr) const { +SPObject *Selection::_objectForXMLNode(Inkscape::XML::Node *repr) const +{ g_return_val_if_fail(repr != nullptr, NULL); SPObject *object = _layers->getDocument()->getObjectByRepr(repr); assert(object == _layers->getDocument()->getObjectById(repr->attribute("id"))); return object; } -size_t Selection::numberOfLayers() { +size_t Selection::numberOfLayers() +{ auto items = this->items(); - std::set<SPObject*> layers; + std::set<SPObject *> layers; for (auto iter = items.begin(); iter != items.end(); ++iter) { SPObject *layer = _layers->layerForObject(*iter); layers.insert(layer); @@ -162,9 +172,10 @@ size_t Selection::numberOfLayers() { return layers.size(); } -size_t Selection::numberOfParents() { +size_t Selection::numberOfParents() +{ auto items = this->items(); - std::set<SPObject*> parents; + std::set<SPObject *> parents; for (auto iter = items.begin(); iter != items.end(); ++iter) { SPObject *parent = (*iter)->parent; parents.insert(parent); @@ -172,35 +183,37 @@ size_t Selection::numberOfParents() { return parents.size(); } -void Selection::_emitSignals() { +void Selection::_emitSignals() +{ _emitChanged(); } -void Selection::_connectSignals(SPObject *object) { +void Selection::_connectSignals(SPObject *object) +{ _modified_connections[object] = object->connectModified(sigc::mem_fun(*this, &Selection::_schedule_modified)); } -void Selection::_releaseSignals(SPObject *object) { +void Selection::_releaseSignals(SPObject *object) +{ _modified_connections[object].disconnect(); _modified_connections.erase(object); } -void -Selection::emptyBackup(){ +void Selection::emptyBackup() +{ _selected_ids.clear(); _seldata.clear(); params.clear(); } -void -Selection::setBackup () +void Selection::setBackup() { SPDesktop *desktop = this->desktop(); Inkscape::UI::Tools::NodeTool *tool = nullptr; if (desktop) { Inkscape::UI::Tools::ToolBase *ec = desktop->event_context; if (INK_IS_NODE_TOOL(ec)) { - tool = static_cast<Inkscape::UI::Tools::NodeTool*>(ec); + tool = static_cast<Inkscape::UI::Tools::NodeTool *>(ec); } } _selected_ids.clear(); @@ -215,47 +228,49 @@ Selection::setBackup () params.push_back(selected_id); _selected_ids.emplace_back(item->getId()); } - if(tool){ + if (tool) { Inkscape::UI::ControlPointSelection *cps = tool->_selected_nodes; std::list<Inkscape::UI::SelectableControlPoint *> points_list = cps->_points_list; - for (auto & i : points_list) { - Inkscape::UI::Node *node = dynamic_cast<Inkscape::UI::Node*>(i); + for (auto &i : points_list) { + Inkscape::UI::Node *node = dynamic_cast<Inkscape::UI::Node *>(i); if (node) { std::string id = node->nodeList().subpathList().pm().item()->getId(); int sp = 0; bool found_sp = false; - for(Inkscape::UI::SubpathList::iterator i = node->nodeList().subpathList().begin(); i != node->nodeList().subpathList().end(); ++i,++sp){ - if(&**i == &(node->nodeList())){ + for (Inkscape::UI::SubpathList::iterator i = node->nodeList().subpathList().begin(); + i != node->nodeList().subpathList().end(); ++i, ++sp) { + if (&**i == &(node->nodeList())) { found_sp = true; break; } } - int nl=0; + int nl = 0; bool found_nl = false; - for (Inkscape::UI::NodeList::iterator j = node->nodeList().begin(); j != node->nodeList().end(); ++j, ++nl){ - if(&*j==node){ + for (Inkscape::UI::NodeList::iterator j = node->nodeList().begin(); j != node->nodeList().end(); + ++j, ++nl) { + if (&*j == node) { found_nl = true; break; } } std::ostringstream ss; - ss<< "--selected-nodes=" << id << ":" << sp << ":" << nl; + ss << "--selected-nodes=" << id << ":" << sp << ":" << nl; Glib::ustring selected_nodes = ss.str(); - if(found_nl && found_sp) { - _seldata.emplace_back(id,std::make_pair(sp,nl)); + if (found_nl && found_sp) { + _seldata.emplace_back(id, std::make_pair(sp, nl)); params.push_back(selected_nodes); } else { - g_warning("Something went wrong while trying to pass selected nodes to extension. Please report a bug."); + g_warning( + "Something went wrong while trying to pass selected nodes to extension. Please report a bug."); } } } - }//end add selected nodes + } // end add selected nodes } -void -Selection::restoreBackup() +void Selection::restoreBackup() { SPDesktop *desktop = this->desktop(); SPDocument *document = SP_ACTIVE_DOCUMENT; @@ -263,14 +278,14 @@ Selection::restoreBackup() if (desktop) { Inkscape::UI::Tools::ToolBase *ec = desktop->event_context; if (INK_IS_NODE_TOOL(ec)) { - tool = static_cast<Inkscape::UI::Tools::NodeTool*>(ec); + tool = static_cast<Inkscape::UI::Tools::NodeTool *>(ec); } } clear(); std::vector<std::string>::iterator it = _selected_ids.begin(); - for (; it!= _selected_ids.end(); ++it){ - SPItem * item = dynamic_cast<SPItem *>(document->getObjectById(it->c_str())); - SPDefs * defs = document->getDefs(); + for (; it != _selected_ids.end(); ++it) { + SPItem *item = dynamic_cast<SPItem *>(document->getObjectById(it->c_str())); + SPDefs *defs = document->getDefs(); if (item && !defs->isAncestorOf(item)) { add(item); } @@ -280,16 +295,16 @@ Selection::restoreBackup() cps->selectAll(); std::list<Inkscape::UI::SelectableControlPoint *> points_list = cps->_points_list; cps->clear(); - Inkscape::UI::Node * node = dynamic_cast<Inkscape::UI::Node*>(*points_list.begin()); + Inkscape::UI::Node *node = dynamic_cast<Inkscape::UI::Node *>(*points_list.begin()); if (node) { Inkscape::UI::SubpathList sp = node->nodeList().subpathList(); - for (auto & l : _seldata) { + for (auto &l : _seldata) { gint sp_count = 0; for (Inkscape::UI::SubpathList::iterator j = sp.begin(); j != sp.end(); ++j, ++sp_count) { - if(sp_count == l.second.first) { + if (sp_count == l.second.first) { gint nt_count = 0; for (Inkscape::UI::NodeList::iterator k = (*j)->begin(); k != (*j)->end(); ++k, ++nt_count) { - if(nt_count == l.second.second) { + if (nt_count == l.second.second) { cps->insert(k.ptr()); break; } @@ -303,8 +318,7 @@ Selection::restoreBackup() } } - -} +} // namespace Inkscape /* Local Variables: diff --git a/src/selection.h b/src/selection.h index f6d09346c06a1040213d1ccd6e41896cad1fbfc6..208e4f775da073a60a4d5d9116d1d07d6fec3f7c 100644 --- a/src/selection.h +++ b/src/selection.h @@ -16,23 +16,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <vector> -#include <map> #include <cstddef> +#include <map> #include <sigc++/sigc++.h> +#include <vector> -#include "inkgc/gc-managed.h" -#include "gc-finalized.h" #include "gc-anchored.h" +#include "gc-finalized.h" +#include "inkgc/gc-managed.h" #include "object/object-set.h" - namespace Inkscape { class LayerModel; namespace XML { class Node; } -} +} // namespace Inkscape namespace Inkscape { @@ -53,12 +52,14 @@ namespace Inkscape { * It also implements its own asynchronous notification signals that * UI elements can listen to. */ -class Selection : public Inkscape::GC::Managed<>, - public Inkscape::GC::Finalized, - public Inkscape::GC::Anchored, - public ObjectSet +class Selection + : public Inkscape::GC::Managed<> + , public Inkscape::GC::Finalized + , public Inkscape::GC::Anchored + , public ObjectSet { -friend class ObjectSet; + friend class ObjectSet; + public: /** * Constructs an selection object, bound to a particular @@ -97,20 +98,16 @@ public: * * @param the xml node of the item to add */ - void add(XML::Node *repr) { - add(_objectForXMLNode(repr)); - } + void add(XML::Node *repr) { add(_objectForXMLNode(repr)); } - using ObjectSet::set; + using ObjectSet::set; /** * Set the selection to an XML node's SPObject. * * @param repr the xml node of the item to select */ - void set(XML::Node *repr) { - set(_objectForXMLNode(repr)); - } + void set(XML::Node *repr) { set(_objectForXMLNode(repr)); } using ObjectSet::remove; @@ -121,18 +118,14 @@ public: * * @param repr the xml node of the item to remove */ - void remove(XML::Node *repr) { - remove(_objectForXMLNode(repr)); - } + void remove(XML::Node *repr) { remove(_objectForXMLNode(repr)); } using ObjectSet::includes; /** * Returns true if the given item is selected. */ - bool includes(XML::Node *repr) { - return includes(_objectForXMLNode(repr)); - } + bool includes(XML::Node *repr) { return includes(_objectForXMLNode(repr)); } /** Returns the number of layers in which there are selected objects. */ size_t numberOfLayers(); @@ -157,10 +150,8 @@ public: * * @return the resulting connection */ - void emitModified(){ _emitModified(this->_flags); }; - sigc::connection connectChanged(sigc::slot<void, Selection *> const &slot) { - return _changed_signal.connect(slot); - } + void emitModified() { _emitModified(this->_flags); }; + sigc::connection connectChanged(sigc::slot<void, Selection *> const &slot) { return _changed_signal.connect(slot); } sigc::connection connectChangedFirst(sigc::slot<void, Selection *> const &slot) { return _changed_signal.slots().insert(_changed_signal.slots().begin(), slot); @@ -206,8 +197,8 @@ public: protected: void _emitSignals() override; - void _connectSignals(SPObject* object) override; - void _releaseSignals(SPObject* object) override; + void _connectSignals(SPObject *object) override; + void _releaseSignals(SPObject *object) override; private: /** Issues modification notification signals. */ @@ -225,10 +216,10 @@ private: void _releaseContext(SPObject *obj); LayerModel *_layers; - SPObject* _selection_context; + SPObject *_selection_context; unsigned int _flags; unsigned int _idle; - std::vector<std::pair<std::string, std::pair<int, int> > > _seldata; + std::vector<std::pair<std::string, std::pair<int, int>>> _seldata; std::vector<std::string> _selected_ids; std::map<SPObject *, sigc::connection> _modified_connections; sigc::connection _context_release_connection; @@ -237,7 +228,7 @@ private: sigc::signal<void, Selection *, unsigned int> _modified_signal; }; -} +} // namespace Inkscape #endif /* diff --git a/src/seltrans-handles.cpp b/src/seltrans-handles.cpp index 1600842b7048639ecee846260c276af58a2122c9..1b978c6abf84e7f40b445dd10fc0dc261a7fa676 100644 --- a/src/seltrans-handles.cpp +++ b/src/seltrans-handles.cpp @@ -15,14 +15,20 @@ #endif SPSelTransTypeInfo const handtypes[] = { - { DEF_COLOR, N_("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center") }, - { DEF_COLOR, N_("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center") }, - { DEF_COLOR, N_("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side") }, - { DEF_COLOR, N_("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner") }, - { CEN_COLOR, N_("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center") }, - { DEF_COLOR, N_("<b>Align</b> objects to the side clicked; <b>Shift</b> click to invert side; <b>Ctrl</b> to group whole selection.") }, - { DEF_COLOR, N_("<b>Align</b> objects to center; <b>Shift</b> click to center vertically instead of horizontally.") } -}; + {DEF_COLOR, N_("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to " + "scale around rotation center")}, + {DEF_COLOR, N_("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around " + "rotation center")}, + {DEF_COLOR, + N_("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side")}, + {DEF_COLOR, N_("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the " + "opposite corner")}, + {CEN_COLOR, + N_("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center")}, + {DEF_COLOR, N_("<b>Align</b> objects to the side clicked; <b>Shift</b> click to invert side; <b>Ctrl</b> to group " + "whole selection.")}, + {DEF_COLOR, + N_("<b>Align</b> objects to center; <b>Shift</b> click to center vertically instead of horizontally.")}}; SPSelTransHandle const hands[] = { // clang-format off diff --git a/src/seltrans-handles.h b/src/seltrans-handles.h index 9811b13caefabf7436ef2236f1eeaa5ad8c71b65..ccbf3210a546dc944e6c418a433c4c577e7867cf 100644 --- a/src/seltrans-handles.h +++ b/src/seltrans-handles.h @@ -22,14 +22,15 @@ typedef unsigned int guint32; namespace Inkscape { - class SelTrans; +class SelTrans; } // Colours are RRGGBBAA: FILL, OVER&DRAG, STROKE, OVER&DRAG -guint32 const DEF_COLOR[] = { 0x000000ff, 0x00ff6600, 0x000000ff, 0x000000ff }; -guint32 const CEN_COLOR[] = { 0x00000000, 0x00000000, 0x000000ff, 0xff0000b0 }; +guint32 const DEF_COLOR[] = {0x000000ff, 0x00ff6600, 0x000000ff, 0x000000ff}; +guint32 const CEN_COLOR[] = {0x00000000, 0x00000000, 0x000000ff, 0xff0000b0}; -enum SPSelTransType { +enum SPSelTransType +{ HANDLE_STRETCH, HANDLE_SCALE, HANDLE_SKEW, @@ -67,21 +68,23 @@ const int AlignHandleToVerb = -13; // Offset for moving from Left click to Shift Click const int AlignShiftVerb = 9; -struct SPSelTransTypeInfo { - guint32 const *color; - char const *tip; +struct SPSelTransTypeInfo +{ + guint32 const *color; + char const *tip; }; // One per handle type in order extern SPSelTransTypeInfo const handtypes[7]; struct SPSelTransHandle; -struct SPSelTransHandle { - SPSelTransType type; - SPAnchorType anchor; - GdkCursorType cursor; - unsigned int control; - gdouble x, y; +struct SPSelTransHandle +{ + SPSelTransType type; + SPAnchorType anchor; + GdkCursorType cursor; + unsigned int control; + gdouble x, y; }; // These are 4 * each handle type + 1 for center int const NUMHANDS = 26; diff --git a/src/seltrans.cpp b/src/seltrans.cpp index 96e6b2c94a2e2063fda172835dd56ae0da91e3a0..9b2d1d6cc1265b48a66f2f006b6e42d59a6226f0 100644 --- a/src/seltrans.cpp +++ b/src/seltrans.cpp @@ -15,61 +15,56 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> -#include <string> +#include "seltrans.h" +#include <2geom/transforms.h> +#include <cstring> #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> - -#include <2geom/transforms.h> - -#include "seltrans.h" +#include <string> #include "desktop-style.h" #include "desktop.h" +#include "display/guideline.h" +#include "display/snap-indicator.h" +#include "display/sodipodi-ctrl.h" +#include "display/sp-ctrlline.h" #include "document-undo.h" #include "document.h" +#include "helper/action.h" #include "knot.h" #include "message-stack.h" #include "mod360.h" +#include "object/sp-item-transform.h" +#include "object/sp-namedview.h" +#include "object/sp-root.h" #include "pure-transform.h" #include "selection-chemistry.h" #include "selection.h" #include "seltrans-handles.h" -#include "verbs.h" - -#include "display/snap-indicator.h" -#include "display/sodipodi-ctrl.h" -#include "display/sp-ctrlline.h" -#include "display/guideline.h" - -#include "helper/action.h" - -#include "object/sp-item-transform.h" -#include "object/sp-namedview.h" -#include "object/sp-root.h" - #include "ui/control-manager.h" #include "ui/tools/select-tool.h" +#include "verbs.h" using Inkscape::ControlManager; using Inkscape::DocumentUndo; -static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, SPSelTransHandle const* data); -static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, SPSelTransHandle const* data); -static void sp_sel_trans_handle_click(SPKnot *knot, guint state, SPSelTransHandle const* data); -static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point const &position, guint32 state, SPSelTransHandle const* data); +static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, SPSelTransHandle const *data); +static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, SPSelTransHandle const *data); +static void sp_sel_trans_handle_click(SPKnot *knot, guint state, SPSelTransHandle const *data); +static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point const &position, guint32 state, + SPSelTransHandle const *data); static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *p, guint state, SPSelTransHandle const *data); extern GdkPixbuf *handles[]; -static gboolean sp_sel_trans_handle_event(SPKnot *knot, GdkEvent *event, SPSelTransHandle const*) +static gboolean sp_sel_trans_handle_event(SPKnot *knot, GdkEvent *event, SPSelTransHandle const *) { switch (event->type) { case GDK_MOTION_NOTIFY: break; case GDK_KEY_PRESS: - if (Inkscape::UI::Tools::get_latin_keyval (&event->key) == GDK_KEY_space) { + if (Inkscape::UI::Tools::get_latin_keyval(&event->key) == GDK_KEY_space) { /* stamping mode: both mode(show content and outline) operation with knot */ if (!SP_KNOT_IS_GRABBED(knot)) { return FALSE; @@ -87,40 +82,38 @@ static gboolean sp_sel_trans_handle_event(SPKnot *knot, GdkEvent *event, SPSelTr return FALSE; } -Inkscape::SelTrans::BoundingBoxPrefsObserver::BoundingBoxPrefsObserver(SelTrans &sel_trans) : - Observer("/tools/bounding_box"), - _sel_trans(sel_trans) -{ -} +Inkscape::SelTrans::BoundingBoxPrefsObserver::BoundingBoxPrefsObserver(SelTrans &sel_trans) + : Observer("/tools/bounding_box") + , _sel_trans(sel_trans) +{} void Inkscape::SelTrans::BoundingBoxPrefsObserver::notify(Preferences::Entry const &val) { _sel_trans._boundingBoxPrefsChanged(static_cast<int>(val.getBool())); } -Inkscape::SelTrans::SelTrans(SPDesktop *desktop) : - _desktop(desktop), - _selcue(desktop), - _state(STATE_SCALE), - _show(SHOW_CONTENT), - _grabbed(false), - _show_handles(true), - _bbox(), - _visual_bbox(), - _absolute_affine(Geom::Scale(1,1)), - _opposite(Geom::Point(0,0)), - _opposite_for_specpoints(Geom::Point(0,0)), - _opposite_for_bboxpoints(Geom::Point(0,0)), - _origin_for_specpoints(Geom::Point(0,0)), - _origin_for_bboxpoints(Geom::Point(0,0)), - _stamp_cache(std::vector<SPItem*>()), - _message_context(desktop->messageStack()), - _bounding_box_prefs_observer(*this) +Inkscape::SelTrans::SelTrans(SPDesktop *desktop) + : _desktop(desktop) + , _selcue(desktop) + , _state(STATE_SCALE) + , _show(SHOW_CONTENT) + , _grabbed(false) + , _show_handles(true) + , _bbox() + , _visual_bbox() + , _absolute_affine(Geom::Scale(1, 1)) + , _opposite(Geom::Point(0, 0)) + , _opposite_for_specpoints(Geom::Point(0, 0)) + , _opposite_for_bboxpoints(Geom::Point(0, 0)) + , _origin_for_specpoints(Geom::Point(0, 0)) + , _origin_for_bboxpoints(Geom::Point(0, 0)) + , _stamp_cache(std::vector<SPItem *>()) + , _message_context(desktop->messageStack()) + , _bounding_box_prefs_observer(*this) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int prefs_bbox = prefs->getBool("/tools/bounding_box"); - _snap_bbox_type = !prefs_bbox ? - SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; + _snap_bbox_type = !prefs_bbox ? SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; g_return_if_fail(desktop != nullptr); @@ -134,47 +127,26 @@ Inkscape::SelTrans::SelTrans(SPDesktop *desktop) : _selection = desktop->getSelection(); - _norm = sp_canvas_item_new(desktop->getControls(), - SP_TYPE_CTRL, - "anchor", SP_ANCHOR_CENTER, - "mode", SP_CTRL_MODE_XOR, - "shape", SP_CTRL_SHAPE_BITMAP, - "size", 13, - "filled", TRUE, - "fill_color", 0x00000000, - "stroked", TRUE, - "stroke_color", 0xff0000b0, - "pixbuf", handles[12], - NULL); - - _grip = sp_canvas_item_new(desktop->getControls(), - SP_TYPE_CTRL, - "anchor", SP_ANCHOR_CENTER, - "mode", SP_CTRL_MODE_XOR, - "shape", SP_CTRL_SHAPE_CROSS, - "size", 7, - "filled", TRUE, - "fill_color", 0xffffff7f, - "stroked", TRUE, - "stroke_color", 0xff0000b0, - "pixbuf", handles[12], - NULL); + _norm = + sp_canvas_item_new(desktop->getControls(), SP_TYPE_CTRL, "anchor", SP_ANCHOR_CENTER, "mode", SP_CTRL_MODE_XOR, + "shape", SP_CTRL_SHAPE_BITMAP, "size", 13, "filled", TRUE, "fill_color", 0x00000000, + "stroked", TRUE, "stroke_color", 0xff0000b0, "pixbuf", handles[12], NULL); + + _grip = sp_canvas_item_new(desktop->getControls(), SP_TYPE_CTRL, "anchor", SP_ANCHOR_CENTER, "mode", + SP_CTRL_MODE_XOR, "shape", SP_CTRL_SHAPE_CROSS, "size", 7, "filled", TRUE, "fill_color", + 0xffffff7f, "stroked", TRUE, "stroke_color", 0xff0000b0, "pixbuf", handles[12], NULL); sp_canvas_item_hide(_grip); sp_canvas_item_hide(_norm); - for (auto & i : _l) { + for (auto &i : _l) { i = ControlManager::getManager().createControlLine(desktop->getControls()); sp_canvas_item_hide(i); } - _sel_changed_connection = _selection->connectChanged( - sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged) - ); + _sel_changed_connection = _selection->connectChanged(sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged)); - _sel_modified_connection = _selection->connectModified( - sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified) - ); + _sel_modified_connection = _selection->connectModified(sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified)); _all_snap_sources_iter = _all_snap_sources_sorted.end(); @@ -186,7 +158,7 @@ Inkscape::SelTrans::~SelTrans() _sel_changed_connection.disconnect(); _sel_modified_connection.disconnect(); - for (auto & knot : knots) { + for (auto &knot : knots) { knot_unref(knot); knot = nullptr; } @@ -199,14 +171,14 @@ Inkscape::SelTrans::~SelTrans() sp_canvas_item_destroy(_grip); _grip = nullptr; } - for (auto & i : _l) { + for (auto &i : _l) { if (i) { sp_canvas_item_destroy(i); i = nullptr; } } - for (auto & _item : _items) { + for (auto &_item : _items) { sp_object_unref(_item, nullptr); } @@ -225,7 +197,7 @@ void Inkscape::SelTrans::increaseState() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool show_align = prefs->getBool("/dialogs/align/oncanvas", false); - + if (_state == STATE_SCALE) { _state = STATE_ROTATE; } else if (_state == STATE_ROTATE && show_align) { @@ -245,8 +217,8 @@ void Inkscape::SelTrans::setCenter(Geom::Point const &p) _center_is_set = true; // Write the new center position into all selected items - auto items= _desktop->selection->items(); - for (auto iter=items.begin();iter!=items.end(); ++iter) { + auto items = _desktop->selection->items(); + for (auto iter = items.begin(); iter != items.end(); ++iter) { SPItem *it = SP_ITEM(*iter); it->setCenter(p); // only set the value; updating repr and document_done will be done once, on ungrab @@ -275,9 +247,9 @@ void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool s return; } - auto items= _desktop->selection->items(); - for (auto iter=items.begin();iter!=items.end(); ++iter) { - SPItem *it = static_cast<SPItem*>(sp_object_ref(*iter, nullptr)); + auto items = _desktop->selection->items(); + for (auto iter = items.begin(); iter != items.end(); ++iter) { + SPItem *it = static_cast<SPItem *>(sp_object_ref(*iter, nullptr)); _items.push_back(it); _items_const.push_back(it); _items_affines.push_back(it->i2dt_affine()); @@ -336,13 +308,14 @@ void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool s bool c = m.snapprefs.isTargetSnappable(SNAPTARGET_BBOX_CORNER); bool mp = m.snapprefs.isTargetSnappable(SNAPTARGET_BBOX_MIDPOINT); bool emp = m.snapprefs.isTargetSnappable(SNAPTARGET_BBOX_EDGE_MIDPOINT); - // Preferably we'd use the bbox of each selected item, but for example 50 items will produce at least 200 bbox points, - // which might make Inkscape crawl(see the comment a few lines above). In that case we will use the bbox of the selection as a whole + // Preferably we'd use the bbox of each selected item, but for example 50 items will produce at least 200 bbox + // points, which might make Inkscape crawl(see the comment a few lines above). In that case we will use the bbox + // of the selection as a whole bool c1 = (_items.size() > 0) && (_items.size() < 50); bool c2 = prefs->getBool("/options/snapclosestonly/value", false); if (translating && (c1 || c2)) { // Get the bounding box points for each item in the selection - for (auto & _item : _items) { + for (auto &_item : _items) { Geom::OptRect b = _item->desktopBounds(_snap_bbox_type); getBBoxPoints(b, &_bbox_points, false, c, emp, mp); } @@ -359,9 +332,10 @@ void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool s // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points // These distinct "opposites" are needed in the snapmanager to avoid bugs such as LP167905 (in which // a box is caught between two guides) - _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * Geom::Scale(1-x, 1-y); + _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * Geom::Scale(1 - x, 1 - y); if (snap_points_bbox) { - _opposite_for_specpoints = (*snap_points_bbox).min() + (*snap_points_bbox).dimensions() * Geom::Scale(1-x, 1-y); + _opposite_for_specpoints = + (*snap_points_bbox).min() + (*snap_points_bbox).dimensions() * Geom::Scale(1 - x, 1 - y); } else { _opposite_for_specpoints = _opposite_for_bboxpoints; } @@ -381,7 +355,7 @@ void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool s } if (_show == SHOW_OUTLINE) { - for (auto & i : _l) + for (auto &i : _l) sp_canvas_item_show(i); } @@ -394,29 +368,30 @@ void Inkscape::SelTrans::transform(Geom::Affine const &rel_affine, Geom::Point c g_return_if_fail(_grabbed); g_return_if_fail(!_empty); - Geom::Affine const affine( Geom::Translate(-norm) * rel_affine * Geom::Translate(norm) ); + Geom::Affine const affine(Geom::Translate(-norm) * rel_affine * Geom::Translate(norm)); if (_show == SHOW_CONTENT) { // update the content for (unsigned i = 0; i < _items.size(); i++) { SPItem &item = *_items[i]; - if( SP_IS_ROOT(&item) ) { + if (SP_IS_ROOT(&item)) { _desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Cannot transform an embedded SVG.")); break; } Geom::Affine const &prev_transform = _items_affines[i]; item.set_i2d_affine(prev_transform * affine); - // The new affine will only have been applied if the transformation is different from the previous one, see SPItem::set_item_transform + // The new affine will only have been applied if the transformation is different from the previous one, see + // SPItem::set_item_transform } } else { if (_bbox) { Geom::Point p[4]; /* update the outline */ - for (unsigned i = 0 ; i < 4 ; i++) { + for (unsigned i = 0; i < 4; i++) { p[i] = _bbox->corner(i) * affine; } - for (unsigned i = 0 ; i < 4 ; i++) { - _l[i]->setCoords(p[i], p[(i+1)%4]); + for (unsigned i = 0; i < 4; i++) { + _l[i]->setCoords(p[i], p[(i + 1) % 4]); } } } @@ -437,7 +412,7 @@ void Inkscape::SelTrans::ungrab() Inkscape::Selection *selection = _desktop->getSelection(); _updateVolatileState(); - for (auto & _item : _items) { + for (auto &_item : _items) { sp_object_unref(_item, nullptr); } @@ -445,10 +420,10 @@ void Inkscape::SelTrans::ungrab() sp_canvas_item_hide(_grip); if (_show == SHOW_OUTLINE) { - for (auto & i : _l) + for (auto &i : _l) sp_canvas_item_hide(i); } - if(!_stamp_cache.empty()){ + if (!_stamp_cache.empty()) { _stamp_cache.clear(); } @@ -456,7 +431,8 @@ void Inkscape::SelTrans::ungrab() if (!_empty && _changed) { if (!_current_relative_affine.isIdentity()) { // we can have a identity affine - // when trying to stretch a perfectly vertical line in horizontal direction, which will not be allowed by the handles; + // when trying to stretch a perfectly vertical line in horizontal direction, which will not be allowed by + // the handles; selection->applyAffine(_current_relative_affine, (_show == SHOW_OUTLINE) ? true : false); if (_center) { @@ -471,7 +447,7 @@ void Inkscape::SelTrans::ungrab() for (unsigned i = 0; i < _items_centers.size(); i++) { SPItem *currentItem = _items[i]; if (currentItem->isCenterSet()) { // only if it's already set - currentItem->setCenter (_items_centers[i] * _current_relative_affine); + currentItem->setCenter(_items_centers[i] * _current_relative_affine); currentItem->updateRepr(); } } @@ -487,33 +463,27 @@ void Inkscape::SelTrans::ungrab() // when trying to stretch a perfectly vertical line in horizontal direction, which will not be allowed // by the handles; this would be identified as a (zero) translation by isTranslation() if (_current_relative_affine.isTranslation()) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, - _("Move")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, _("Move")); } else if (_current_relative_affine.withoutTranslation().isScale()) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, - _("Scale")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, _("Scale")); } else if (_current_relative_affine.withoutTranslation().isRotation()) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, - _("Rotate")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, _("Rotate")); } else { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, - _("Skew")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, _("Skew")); } } else { _updateHandles(); } } else { - if (_center_is_set) { // we were dragging center; update reprs and commit undoable action - auto items= _desktop->selection->items(); - for (auto iter=items.begin();iter!=items.end(); ++iter) { + auto items = _desktop->selection->items(); + for (auto iter = items.begin(); iter != items.end(); ++iter) { SPItem *it = *iter; it->updateRepr(); } - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, - _("Set center")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, _("Set center")); } _items.clear(); @@ -532,14 +502,14 @@ void Inkscape::SelTrans::stamp() Inkscape::Selection *selection = _desktop->getSelection(); bool fixup = !_grabbed; - if ( fixup && !_stamp_cache.empty() ) { + if (fixup && !_stamp_cache.empty()) { // TODO - give a proper fix. Simple temporary work-around for the grab() issue _stamp_cache.clear(); } /* stamping mode */ if (!_empty) { - std::vector<SPItem*> l; + std::vector<SPItem *> l; if (!_stamp_cache.empty()) { l = _stamp_cache; } else { @@ -549,7 +519,7 @@ void Inkscape::SelTrans::stamp() _stamp_cache = l; } - for(auto original_item : l) { + for (auto original_item : l) { Inkscape::XML::Node *original_repr = original_item->getRepr(); // remember parent @@ -560,12 +530,12 @@ void Inkscape::SelTrans::stamp() // add the new repr to the parent parent->addChild(copy_repr, original_repr->prev()); - SPItem *copy_item = (SPItem *) _desktop->getDocument()->getObjectByRepr(copy_repr); + SPItem *copy_item = (SPItem *)_desktop->getDocument()->getObjectByRepr(copy_repr); Geom::Affine const *new_affine; if (_show == SHOW_OUTLINE) { Geom::Affine const i2d(original_item->i2dt_affine()); - Geom::Affine const i2dnew( i2d * _current_relative_affine ); + Geom::Affine const i2dnew(i2d * _current_relative_affine); copy_item->set_i2d_affine(i2dnew); new_affine = ©_item->transform; } else { @@ -574,21 +544,20 @@ void Inkscape::SelTrans::stamp() copy_item->doWriteTransform(*new_affine); - if ( copy_item->isCenterSet() && _center ) { + if (copy_item->isCenterSet() && _center) { copy_item->setCenter(*_center * _current_relative_affine); } Inkscape::GC::release(copy_repr); - SPLPEItem * lpeitem = dynamic_cast<SPLPEItem *>(copy_item); - if(lpeitem && lpeitem->hasPathEffectRecursive()) { + SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(copy_item); + if (lpeitem && lpeitem->hasPathEffectRecursive()) { lpeitem->forkPathEffectsIfNecessary(1); sp_lpe_item_update_patheffect(lpeitem, true, true); } } - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, - _("Stamp")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, _("Stamp")); } - if ( fixup && !_stamp_cache.empty() ) { + if (fixup && !_stamp_cache.empty()) { // TODO - give a proper fix. Simple temporary work-around for the grab() issue _stamp_cache.clear(); } @@ -596,10 +565,10 @@ void Inkscape::SelTrans::stamp() void Inkscape::SelTrans::_updateHandles() { - for (auto & knot : knots) + for (auto &knot : knots) knot->hide(); - if ( !_show_handles || _empty ) + if (!_show_handles || _empty) return; if (!_center_is_set) { @@ -607,12 +576,12 @@ void Inkscape::SelTrans::_updateHandles() _center_is_set = true; } - if ( _state == STATE_SCALE ) { + if (_state == STATE_SCALE) { _showHandles(HANDLE_STRETCH); _showHandles(HANDLE_SCALE); - } else if(_state == STATE_ALIGN) { - _showHandles(HANDLE_ALIGN); - _showHandles(HANDLE_CENTER_ALIGN); + } else if (_state == STATE_ALIGN) { + _showHandles(HANDLE_ALIGN); + _showHandles(HANDLE_CENTER_ALIGN); } else { _showHandles(HANDLE_SKEW); _showHandles(HANDLE_ROTATE); @@ -629,7 +598,7 @@ void Inkscape::SelTrans::_updateVolatileState() return; } - //Update the bboxes + // Update the bboxes _bbox = selection->bounds(_snap_bbox_type); _visual_bbox = selection->visualBounds(); @@ -661,7 +630,7 @@ void Inkscape::SelTrans::_showHandles(SPSelTransType type) // This controls the center handle's position, because the default can // be moved and needs to be remembered. - if( type == HANDLE_CENTER && _center ) + if (type == HANDLE_CENTER && _center) knots[i]->moveto(*_center); } } @@ -691,57 +660,54 @@ void Inkscape::SelTrans::_makeHandles() } } -static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, SPSelTransHandle const* data) +static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, SPSelTransHandle const *data) { - SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab( - knot, state, *(SPSelTransHandle const *) data - ); + SP_SELECT_CONTEXT(knot->desktop->event_context) + ->_seltrans->handleGrab(knot, state, *(SPSelTransHandle const *)data); } -static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const* /*data*/) +static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const * /*data*/) { SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab(); } -static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point const& position, guint state, SPSelTransHandle const *data) +static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point const &position, guint state, + SPSelTransHandle const *data) { Geom::Point pos = position; - SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent( - knot, &pos, state, *(SPSelTransHandle const *) data - ); + SP_SELECT_CONTEXT(knot->desktop->event_context) + ->_seltrans->handleNewEvent(knot, &pos, state, *(SPSelTransHandle const *)data); } -static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const *data) +static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *position, guint state, + SPSelTransHandle const *data) { - return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest( - knot, position, state, *(SPSelTransHandle const *) data - ); + return SP_SELECT_CONTEXT(knot->desktop->event_context) + ->_seltrans->handleRequest(knot, position, state, *(SPSelTransHandle const *)data); } -static void sp_sel_trans_handle_click(SPKnot *knot, guint state, SPSelTransHandle const* data) +static void sp_sel_trans_handle_click(SPKnot *knot, guint state, SPSelTransHandle const *data) { - SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick( - knot, state, *(SPSelTransHandle const *) data - ); + SP_SELECT_CONTEXT(knot->desktop->event_context) + ->_seltrans->handleClick(knot, state, *(SPSelTransHandle const *)data); } -void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle) +void Inkscape::SelTrans::handleClick(SPKnot * /*knot*/, guint state, SPSelTransHandle const &handle) { switch (handle.type) { case HANDLE_CENTER: if (state & GDK_SHIFT_MASK) { // Unset the center position for all selected items - auto items = _desktop->selection->items(); - for (auto iter=items.begin();iter!=items.end(); ++iter) { + auto items = _desktop->selection->items(); + for (auto iter = items.begin(); iter != items.end(); ++iter) { SPItem *it = *iter; it->unsetCenter(); it->updateRepr(); - _center_is_set = false; // center has changed + _center_is_set = false; // center has changed _updateHandles(); } - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, - _("Reset center")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SELECT, _("Reset center")); } break; case HANDLE_ALIGN: @@ -759,26 +725,20 @@ void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHan // Forcing handles visibility must be done after grab() to be effective switch (handle.type) { case HANDLE_CENTER: - g_object_set(G_OBJECT(_grip), - "shape", SP_CTRL_SHAPE_BITMAP, - "size", 13, - NULL); + g_object_set(G_OBJECT(_grip), "shape", SP_CTRL_SHAPE_BITMAP, "size", 13, NULL); sp_canvas_item_hide(_norm); sp_canvas_item_show(_grip); break; default: - g_object_set(G_OBJECT(_grip), - "shape", SP_CTRL_SHAPE_CROSS, - "size", 7, - NULL); + g_object_set(G_OBJECT(_grip), "shape", SP_CTRL_SHAPE_CROSS, "size", 7, NULL); sp_canvas_item_show(_norm); sp_canvas_item_show(_grip); break; } } - -void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle) +void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, guint state, + SPSelTransHandle const &handle) { if (!SP_KNOT_IS_GRABBED(knot)) { return; @@ -786,8 +746,8 @@ void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, gui // in case items have been unhooked from the document, don't // try to continue processing events for them. - for (auto & _item : _items) { - if ( !_item->document ) { + for (auto &_item : _items) { + if (!_item->document) { return; } } @@ -813,8 +773,8 @@ void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, gui } } - -gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle) +gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, guint state, + SPSelTransHandle const &handle) { if (!SP_KNOT_IS_GRABBED(knot)) return TRUE; @@ -847,15 +807,13 @@ gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, return TRUE; } - -void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/) +void Inkscape::SelTrans::_selChanged(Inkscape::Selection * /*selection*/) { if (!_grabbed) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); // reread in case it changed on the fly: int prefs_bbox = prefs->getBool("/tools/bounding_box"); - _snap_bbox_type = !prefs_bbox ? - SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; + _snap_bbox_type = !prefs_bbox ? SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; _updateVolatileState(); _current_relative_affine.setIdentity(); @@ -864,7 +822,7 @@ void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/) } } -void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/) +void Inkscape::SelTrans::_selModified(Inkscape::Selection * /*selection*/, guint /*flags*/) { if (!_grabbed) { _updateVolatileState(); @@ -873,7 +831,7 @@ void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint // reset internal flag _changed = false; - _center_is_set = false; // center(s) may have changed + _center_is_set = false; // center(s) may have changed _updateHandles(); } @@ -881,8 +839,7 @@ void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint void Inkscape::SelTrans::_boundingBoxPrefsChanged(int prefs_bbox) { - _snap_bbox_type = !prefs_bbox ? - SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; + _snap_bbox_type = !prefs_bbox ? SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; _updateVolatileState(); _updateHandles(); @@ -895,14 +852,11 @@ void Inkscape::SelTrans::_boundingBoxPrefsChanged(int prefs_bbox) /** Returns -1 or 1 according to the sign of x. Returns 1 for 0 and NaN. */ static double sign(double const x) { - return ( x < 0 - ? -1 - : 1 ); + return (x < 0 ? -1 : 1); } gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state) { - // Calculate the scale factors, which can be either visual or geometric // depending on which type of bbox is currently being used (see preferences -> selector tool) Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin); @@ -911,15 +865,15 @@ gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state) Geom::Point pt_geom = _getGeomHandlePos(pt); Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints); - _absolute_affine = Geom::identity(); //Initialize the scaler + _absolute_affine = Geom::identity(); // Initialize the scaler if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider // We're scaling either the visual or the geometric bbox here (see the comment above) - for ( unsigned int i = 0 ; i < 2 ; i++ ) { + for (unsigned int i = 0; i < 2; i++) { if (fabs(default_scale[i]) > 1) { default_scale[i] = round(default_scale[i]); } else if (default_scale[i] != 0) { - default_scale[i] = 1/round(1/(MIN(default_scale[i], 10))); + default_scale[i] = 1 / round(1 / (MIN(default_scale[i], 10))); } } // Update the knot position @@ -927,9 +881,9 @@ gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state) // When scaling by an integer, snapping is not needed } else { // In all other cases we should try to snap now - Inkscape::PureScale *bb, *sn; + Inkscape::PureScale *bb, *sn; - if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) { + if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive("lock")) { // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y]. // // The aspect-ratio must be locked before snapping @@ -957,7 +911,7 @@ gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state) m.unSetup(); // These lines below are duplicated in stretchRequest - //TODO: Eliminate this code duplication + // TODO: Eliminate this code duplication if (bb->best_snapped_point.getSnapped() || sn->best_snapped_point.getSnapped()) { if (bb->best_snapped_point.getSnapped()) { if (!bb->best_snapped_point.isOtherSnapBetter(sn->best_snapped_point, false)) { @@ -1022,13 +976,13 @@ gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints); geom_scale[perp] = 1; - _absolute_affine = Geom::identity(); //Initialize the scaler + _absolute_affine = Geom::identity(); // Initialize the scaler if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider if (fabs(default_scale[axis]) > 1) { default_scale[axis] = round(default_scale[axis]); } else if (default_scale[axis] != 0) { - default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10))); + default_scale[axis] = 1 / round(1 / (MIN(default_scale[axis], 10))); } // Calculate the new transformation and update the handle position pt = _calcAbsAffineDefault(default_scale); @@ -1041,8 +995,10 @@ gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom bool symmetrical = state & GDK_CONTROL_MASK; - Inkscape::PureStretchConstrained bb = Inkscape::PureStretchConstrained(Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical); - Inkscape::PureStretchConstrained sn = Inkscape::PureStretchConstrained(Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical); + Inkscape::PureStretchConstrained bb = Inkscape::PureStretchConstrained( + Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical); + Inkscape::PureStretchConstrained sn = Inkscape::PureStretchConstrained( + Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical); m.snapTransformed(_bbox_points, _point, bb); m.snapTransformed(_snap_points, _point, sn); @@ -1154,7 +1110,7 @@ gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::P // Due to the limited resolution though (see above), we'd better use a relative error here if (_bbox) { Geom::Coord d = (*_bbox).dimensions()[dim_a]; - if (fabs(initial_delta[dim_a]/d) < 1e-4) { + if (fabs(initial_delta[dim_a] / d) < 1e-4) { return false; } } @@ -1194,14 +1150,16 @@ gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::P SnapManager &m = _desktop->namedview->snap_manager; m.setup(_desktop, false, _items_const); - // When skewing, we cannot snap the corners of the bounding box, see the comment in PureSkewConstrained for details - Inkscape::PureSkewConstrained sn = Inkscape::PureSkewConstrained(skew[dim_a], scale[dim_a], _origin, Geom::Dim2(dim_b)); + // When skewing, we cannot snap the corners of the bounding box, see the comment in PureSkewConstrained for + // details + Inkscape::PureSkewConstrained sn = + Inkscape::PureSkewConstrained(skew[dim_a], scale[dim_a], _origin, Geom::Dim2(dim_b)); m.snapTransformed(_snap_points, _point, sn); if (sn.best_snapped_point.getSnapped()) { // We snapped something, so change the skew to reflect it skew[dim_a] = sn.getSkewSnapped(); - _desktop->snapindicator->set_new_snaptarget(sn.best_snapped_point); + _desktop->snapindicator->set_new_snaptarget(sn.best_snapped_point); } else { _desktop->snapindicator->remove_snaptarget(); } @@ -1215,14 +1173,14 @@ gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::P // Calculate the relative affine _relative_affine = Geom::identity(); - _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a]; - _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a]; - _relative_affine[2*(dim_b) + (dim_a)] = 0; - _relative_affine[2*(dim_b) + (dim_b)] = 1; + _relative_affine[2 * dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a]; + _relative_affine[2 * dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a]; + _relative_affine[2 * (dim_b) + (dim_a)] = 0; + _relative_affine[2 * (dim_b) + (dim_b)] = 1; for (int i = 0; i < 2; i++) { - if (fabs(_relative_affine[3*i]) < 1e-15) { - _relative_affine[3*i] = 1e-15; + if (fabs(_relative_affine[3 * i]) < 1e-15) { + _relative_affine[3 * i] = 1e-15; } } @@ -1231,8 +1189,7 @@ gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::P _message_context.setF(Inkscape::IMMEDIATE_MESSAGE, // TRANSLATORS: don't modify the first ";" // (it will NOT be displayed as ";" - only the second one will be) - _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), - degrees); + _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), degrees); return TRUE; } @@ -1252,33 +1209,37 @@ gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state) // rotate affine in rotate Geom::Point const d1 = _point - _origin; - Geom::Point const d2 = pt - _origin; + Geom::Point const d2 = pt - _origin; Geom::Coord const h1 = Geom::L2(d1); // initial radius - if (h1 < 1e-15) return FALSE; - Geom::Point q1 = d1 / h1; // normalized initial vector to handle + if (h1 < 1e-15) + return FALSE; + Geom::Point q1 = d1 / h1; // normalized initial vector to handle Geom::Coord const h2 = Geom::L2(d2); // new radius - if (fabs(h2) < 1e-15) return FALSE; + if (fabs(h2) < 1e-15) + return FALSE; Geom::Point q2 = d2 / h2; // normalized new vector to handle Geom::Rotate r1(q1); Geom::Rotate r2(q2); - double radians = atan2(Geom::dot(Geom::rot90(d1), d2), Geom::dot(d1, d2));; + double radians = atan2(Geom::dot(Geom::rot90(d1), d2), Geom::dot(d1, d2)); + ; if (state & GDK_CONTROL_MASK) { // Snap to defined angle increments double cos_t = Geom::dot(q1, q2); double sin_t = Geom::dot(Geom::rot90(q1), q2); radians = atan2(sin_t, cos_t); if (snaps) { - radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 ); + radians = (M_PI / snaps) * floor(radians * snaps / M_PI + .5); } - r1 = Geom::Rotate(0); //q1 = Geom::Point(1, 0); - r2 = Geom::Rotate(radians); //q2 = Geom::Point(cos(radians), sin(radians)); + r1 = Geom::Rotate(0); // q1 = Geom::Point(1, 0); + r2 = Geom::Rotate(radians); // q2 = Geom::Point(cos(radians), sin(radians)); } else { SnapManager &m = _desktop->namedview->snap_manager; m.setup(_desktop, false, _items_const); - // When rotating, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapRotate" for details + // When rotating, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapRotate" for + // details Inkscape::PureRotateConstrained sn = Inkscape::PureRotateConstrained(radians, _origin); m.snapTransformed(_snap_points, _point, sn); m.unSetup(); @@ -1292,10 +1253,8 @@ gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state) } else { _desktop->snapindicator->remove_snaptarget(); } - } - // Calculate the relative affine _relative_affine = r2 * r1.inverse(); @@ -1328,10 +1287,11 @@ gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state) std::vector<Inkscape::Snapper::SnapConstraint> constraints; constraints.emplace_back(_point, Geom::Point(1, 0)); constraints.emplace_back(_point, Geom::Point(0, 1)); - Inkscape::SnappedPoint sp = m.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(pt, Inkscape::SNAPSOURCE_ROTATION_CENTER), constraints, state & GDK_SHIFT_MASK); + Inkscape::SnappedPoint sp = + m.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(pt, Inkscape::SNAPSOURCE_ROTATION_CENTER), + constraints, state & GDK_SHIFT_MASK); pt = sp.getPoint(); - } - else { + } else { if (!(state & GDK_SHIFT_MASK)) { // Shift disables snapping m.freeSnapReturnByRef(pt, Inkscape::SNAPSOURCE_ROTATION_CENTER); } @@ -1344,8 +1304,7 @@ gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state) Inkscape::Util::Quantity y_q = Inkscape::Util::Quantity(pt[Geom::Y], "px"); Glib::ustring xs(x_q.string(_desktop->namedview->display_units)); Glib::ustring ys(y_q.string(_desktop->namedview->display_units)); - _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), - xs.c_str(), ys.c_str()); + _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs.c_str(), ys.c_str()); return TRUE; } @@ -1361,13 +1320,13 @@ void Inkscape::SelTrans::align(guint state, SPSelTransHandle const &handle) } else { verb_id = AlignVerb[handle.control + AlignHandleToVerb]; } - if(verb_id >= 0) { + if (verb_id >= 0) { prefs->setBool("/dialogs/align/sel-as-groups", (state & GDK_CONTROL_MASK) != 0); prefs->setInt("/dialogs/align/align-to", 6); - Inkscape::Verb *verb = Inkscape::Verb::get( verb_id ); - g_assert( verb != NULL ); - SPAction *action = verb->get_action((Inkscape::UI::View::View *) this->_desktop); - sp_action_perform (action, NULL); + Inkscape::Verb *verb = Inkscape::Verb::get(verb_id); + g_assert(verb != NULL); + SPAction *action = verb->get_action((Inkscape::UI::View::View *)this->_desktop); + sp_action_perform(action, NULL); } // Set the special align point and settings back to nothing so we don't interfere @@ -1380,24 +1339,22 @@ void Inkscape::SelTrans::align(guint state, SPSelTransHandle const &handle) * */ - - -void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/) +void Inkscape::SelTrans::stretch(SPSelTransHandle const & /*handle*/, Geom::Point & /*pt*/, guint /*state*/) { transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0 } -void Inkscape::SelTrans::scale(Geom::Point &/*pt*/, guint /*state*/) +void Inkscape::SelTrans::scale(Geom::Point & /*pt*/, guint /*state*/) { transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0 } -void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/) +void Inkscape::SelTrans::skew(SPSelTransHandle const & /*handle*/, Geom::Point & /*pt*/, guint /*state*/) { transform(_relative_affine, _origin); } -void Inkscape::SelTrans::rotate(Geom::Point &/*pt*/, guint /*state*/) +void Inkscape::SelTrans::rotate(Geom::Point & /*pt*/, guint /*state*/) { transform(_relative_affine, _origin); } @@ -1421,11 +1378,11 @@ void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state) } } - if (alt) {// Alt pressed means: move only by integer multiples of the grid spacing + if (alt) { // Alt pressed means: move only by integer multiples of the grid spacing m.setup(_desktop, true, _items_const); dxy = m.multipleOfGridPitch(dxy, _point); m.unSetup(); - } else if (!shift) { //!shift: with snapping + } else if (!shift) { //! shift: with snapping /* We're snapping to things, possibly with a constraint to horizontal or ** vertical movement. Obtain a list of possible translations and then ** pick the smallest. @@ -1465,8 +1422,8 @@ void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state) m.unSetup(); /*g_get_current_time(&endtime); - double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0; - std::cout << "Time spent snapping: " << elapsed << std::endl; */ + double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - + starttime.tv_usec))) / 1000.0; std::cout << "Time spent snapping: " << elapsed << std::endl; */ /* Pick one */ Inkscape::SnappedPoint best_snapped_point; @@ -1517,15 +1474,16 @@ void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state) Glib::ustring xs(x_q.string(_desktop->namedview->display_units)); Glib::ustring ys(y_q.string(_desktop->namedview->display_units)); _message_context.setF(Inkscape::NORMAL_MESSAGE, - _("<b>Move</b> by %s, %s; with <b>Ctrl</b> to restrict to horizontal/vertical; with <b>Shift</b> to disable snapping"), - xs.c_str(), ys.c_str()); + _("<b>Move</b> by %s, %s; with <b>Ctrl</b> to restrict to horizontal/vertical; with " + "<b>Shift</b> to disable snapping"), + xs.c_str(), ys.c_str()); } // Given a location of a handle at the visual bounding box, find the corresponding location at the // geometrical bounding box Geom::Point Inkscape::SelTrans::_getGeomHandlePos(Geom::Point const &visual_handle_pos) { - if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) { + if (_snap_bbox_type == SPItem::GEOMETRIC_BBOX) { // When the selector tool is using geometric bboxes, then the handle is already // located at one of the geometric bbox corners return visual_handle_pos; @@ -1541,22 +1499,26 @@ Geom::Point Inkscape::SelTrans::_getGeomHandlePos(Geom::Point const &visual_hand Geom::Rect new_bbox = Geom::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box // Please note that the new_bbox might in fact be just a single line, for example when stretching (in // which case the handle and origin will be aligned vertically or horizontally) - Geom::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * Geom::Scale(new_bbox.dimensions()).inverse(); + Geom::Point normalized_handle_pos = + (visual_handle_pos - new_bbox.min()) * Geom::Scale(new_bbox.dimensions()).inverse(); // Calculate the absolute affine while taking into account the scaling of the stroke width Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool transform_stroke = prefs->getBool("/options/transform/stroke", true); bool preserve = prefs->getBool("/options/preservetransform/value", false); - Geom::Affine abs_affine = get_scale_transform_for_uniform_stroke (*_bbox, _strokewidth, _strokewidth, transform_stroke, preserve, - new_bbox.min()[Geom::X], new_bbox.min()[Geom::Y], new_bbox.max()[Geom::X], new_bbox.max()[Geom::Y]); + Geom::Affine abs_affine = get_scale_transform_for_uniform_stroke( + *_bbox, _strokewidth, _strokewidth, transform_stroke, preserve, new_bbox.min()[Geom::X], + new_bbox.min()[Geom::Y], new_bbox.max()[Geom::X], new_bbox.max()[Geom::Y]); // Calculate the scaled geometrical bbox Geom::Rect new_geom_bbox = Geom::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine); // Find the location of the handle on this new geometrical bbox - return normalized_handle_pos * Geom::Scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle + return normalized_handle_pos * Geom::Scale(new_geom_bbox.dimensions()) + + new_geom_bbox.min(); // new position of the geometric handle } -Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, bool const skew) +Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, + Geom::Point const &origin, bool const skew) { // Work out the new scale factors for the bbox @@ -1565,10 +1527,10 @@ Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::P Geom::Point const offset = new_point - initial_point; Geom::Scale scale(1, 1); - for ( unsigned int i = 0 ; i < 2 ; i++ ) { - if ( fabs(initial_delta[i]) > 1e-6 ) { + for (unsigned int i = 0; i < 2; i++) { + if (fabs(initial_delta[i]) > 1e-6) { if (skew) { - scale[i] = offset[1-i] / initial_delta[i]; + scale[i] = offset[1 - i] / initial_delta[i]; } else { scale[i] = new_delta[i] / initial_delta[i]; } @@ -1590,7 +1552,7 @@ Geom::Point Inkscape::SelTrans::_calcAbsAffineDefault(Geom::Scale const default_ gdouble stroke_x = 0; gdouble stroke_y = 0; - if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) { + if (_snap_bbox_type != SPItem::GEOMETRIC_BBOX) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); transform_stroke = prefs->getBool("/options/transform/stroke", true); preserve = prefs->getBool("/options/preservetransform/value", false); @@ -1598,18 +1560,20 @@ Geom::Point Inkscape::SelTrans::_calcAbsAffineDefault(Geom::Scale const default_ stroke_y = _visual_bbox->height() - _geometric_bbox->height(); } - _absolute_affine = get_scale_transform_for_uniform_stroke (*_visual_bbox, stroke_x, stroke_y, transform_stroke, preserve, - new_bbox_min[Geom::X], new_bbox_min[Geom::Y], new_bbox_max[Geom::X], new_bbox_max[Geom::Y]); + _absolute_affine = get_scale_transform_for_uniform_stroke(*_visual_bbox, stroke_x, stroke_y, transform_stroke, + preserve, new_bbox_min[Geom::X], new_bbox_min[Geom::Y], + new_bbox_max[Geom::X], new_bbox_max[Geom::Y]); // return the new handle position - return ( _point - _origin ) * default_scale + _origin; + return (_point - _origin) * default_scale + _origin; } // Only for scaling/stretching Geom::Point Inkscape::SelTrans::_calcAbsAffineGeom(Geom::Scale const geom_scale) { _relative_affine = Geom::Affine(geom_scale); - _absolute_affine = Geom::Translate(-_origin_for_specpoints) * _relative_affine * Geom::Translate(_origin_for_specpoints); + _absolute_affine = + Geom::Translate(-_origin_for_specpoints) * _relative_affine * Geom::Translate(_origin_for_specpoints); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool const transform_stroke = prefs->getBool("/options/transform/stroke", true); @@ -1631,7 +1595,8 @@ void Inkscape::SelTrans::_keepClosestPointOnly(Geom::Point const &p) SnapManager const &m = _desktop->namedview->snap_manager; // If we're not going to snap nodes, then we might just as well get rid of their snappoints right away - if (!(m.snapprefs.isTargetSnappable(SNAPTARGET_NODE_CATEGORY, SNAPTARGET_OTHERS_CATEGORY) || m.snapprefs.isAnyDatumSnappable())) { + if (!(m.snapprefs.isTargetSnappable(SNAPTARGET_NODE_CATEGORY, SNAPTARGET_OTHERS_CATEGORY) || + m.snapprefs.isAnyDatumSnappable())) { _snap_points.clear(); } @@ -1644,7 +1609,7 @@ void Inkscape::SelTrans::_keepClosestPointOnly(Geom::Point const &p) _all_snap_sources_sorted.insert(_all_snap_sources_sorted.end(), _bbox_points.begin(), _bbox_points.end()); // Calculate and store the distance to the reference point for each snap candidate point - for(auto & i : _all_snap_sources_sorted) { + for (auto &i : _all_snap_sources_sorted) { i.setDistance(Geom::L2(i.getPoint() - p)); } @@ -1662,7 +1627,6 @@ void Inkscape::SelTrans::_keepClosestPointOnly(Geom::Point const &p) _snap_points.push_back(_all_snap_sources_sorted.front()); } } - } // TODO: This code is duplicated in transform-handle-set.cpp; fix this! void Inkscape::SelTrans::getNextClosestPoint(bool reverse) diff --git a/src/seltrans.h b/src/seltrans.h index dadef62ef050ad71799c6c4d4ef7e8144f0fc90e..95fca6b788cd817790586846674f1cdb68344d5c 100644 --- a/src/seltrans.h +++ b/src/seltrans.h @@ -16,33 +16,33 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <2geom/point.h> #include <2geom/affine.h> +#include <2geom/point.h> #include <2geom/rect.h> #include <cstddef> #include <sigc++/sigc++.h> #include <vector> +#include "display/guideline.h" #include "knot.h" #include "message-context.h" -#include "seltrans-handles.h" -#include "selcue.h" - #include "object/sp-item.h" -#include "display/guideline.h" +#include "selcue.h" +#include "seltrans-handles.h" -class SPKnot; -class SPDesktop; +class SPKnot; +class SPDesktop; struct SPCanvasItem; struct SPCtrlLine; struct SPSelTransHandle; namespace Inkscape { -Geom::Scale calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, bool const skew = false); +Geom::Scale calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, + bool const skew = false); namespace XML { - class Node; +class Node; } class SelTrans @@ -82,23 +82,15 @@ public: SHOW_OUTLINE }; - void setShow(Show s) { - _show = s; - } - bool isEmpty() { - return _empty; - } - bool isGrabbed() { - return _grabbed; - } - bool centerIsVisible() { - return ( SP_KNOT_IS_VISIBLE (knots[0]) ); - } + void setShow(Show s) { _show = s; } + bool isEmpty() { return _empty; } + bool isGrabbed() { return _grabbed; } + bool centerIsVisible() { return (SP_KNOT_IS_VISIBLE(knots[0])); } void getNextClosestPoint(bool reverse); private: - class BoundingBoxPrefsObserver: public Preferences::Observer + class BoundingBoxPrefsObserver : public Preferences::Observer { public: BoundingBoxPrefsObserver(SelTrans &sel_trans); @@ -123,10 +115,11 @@ private: Geom::Point _calcAbsAffineGeom(Geom::Scale const geom_scale); void _keepClosestPointOnly(Geom::Point const &p); - enum State { - STATE_SCALE, //scale or stretch - STATE_ROTATE, //rotate or skew - STATE_ALIGN //on canvas align + enum State + { + STATE_SCALE, // scale or stretch + STATE_ROTATE, // rotate or skew + STATE_ALIGN // on canvas align }; SPDesktop *_desktop; @@ -178,7 +171,7 @@ private: boost::optional<Geom::Point> _center; bool _center_is_set; ///< we've already set _center, no need to reread it from items - int _center_handle; + int _center_handle; SPKnot *knots[NUMHANDS]; SPCanvasItem *_norm; @@ -186,10 +179,10 @@ private: SPCtrlLine *_l[4]; unsigned int _sel_changed_id; unsigned int _sel_modified_id; - std::vector<SPItem*> _stamp_cache; + std::vector<SPItem *> _stamp_cache; - Geom::Point _origin; ///< position of origin for transforms - Geom::Point _point; ///< original position of the knot being used for the current transform + Geom::Point _origin; ///< position of origin for transforms + Geom::Point _point; ///< original position of the knot being used for the current transform Geom::Point _point_geom; ///< original position of the knot being used for the current transform Inkscape::MessageContext _message_context; sigc::connection _sel_changed_connection; @@ -197,11 +190,10 @@ private: BoundingBoxPrefsObserver _bounding_box_prefs_observer; }; -} +} // namespace Inkscape #endif // SEEN_SELTRANS_H - /* Local Variables: mode:c++ diff --git a/src/shortcuts.cpp b/src/shortcuts.cpp index e801b9bb4f2b0b4b36c654ff354ec58486accaef..048682adeb338727fbe91e833d9e5f46ec6757f0 100644 --- a/src/shortcuts.cpp +++ b/src/shortcuts.cpp @@ -26,40 +26,39 @@ * option) any later version. */ -#include <vector> -#include <cstring> -#include <string> -#include <map> - #include "shortcuts.h" + +#include <cstring> #include <gdk/gdkkeysyms.h> #include <gdkmm/display.h> -#include <gtk/gtk.h> - -#include <glibmm/i18n.h> #include <glibmm/convert.h> +#include <glibmm/i18n.h> #include <glibmm/miscutils.h> +#include <gtk/gtk.h> +#include <map> +#include <string> +#include <vector> +#include "desktop.h" +#include "document.h" #include "helper/action.h" +#include "inkscape.h" #include "io/dir-util.h" -#include "io/sys.h" #include "io/resource.h" +#include "io/sys.h" +#include "path-prefix.h" +#include "preferences.h" +#include "ui/dialog/filedialog.h" +#include "ui/tools/tool-base.h" #include "verbs.h" #include "xml/node-iterators.h" #include "xml/repr.h" -#include "document.h" -#include "preferences.h" -#include "ui/tools/tool-base.h" -#include "inkscape.h" -#include "desktop.h" -#include "path-prefix.h" -#include "ui/dialog/filedialog.h" using namespace Inkscape; using namespace Inkscape::IO::Resource; -static bool try_shortcuts_file(char const *filename, bool const is_user_set=false); -static void read_shortcuts_file(char const *filename, bool const is_user_set=false); +static bool try_shortcuts_file(char const *filename, bool const is_user_set = false); +static void read_shortcuts_file(char const *filename, bool const is_user_set = false); static void _read_shortcuts_file(XML::Node const *root, bool const is_user_set); unsigned int sp_shortcut_get_key(unsigned int const shortcut); @@ -67,8 +66,7 @@ GdkModifierType sp_shortcut_get_modifiers(unsigned int const shortcut); /* Returns true if action was performed */ -bool -sp_shortcut_invoke(unsigned int shortcut, Inkscape::UI::View::View *view) +bool sp_shortcut_invoke(unsigned int shortcut, Inkscape::UI::View::View *view) { Inkscape::Verb *verb = sp_shortcut_get_verb(shortcut); if (verb) { @@ -81,13 +79,13 @@ sp_shortcut_invoke(unsigned int shortcut, Inkscape::UI::View::View *view) return false; } -static std::map<unsigned int, Inkscape::Verb * > *verbs = nullptr; +static std::map<unsigned int, Inkscape::Verb *> *verbs = nullptr; static std::map<Inkscape::Verb *, unsigned int> *primary_shortcuts = nullptr; static std::map<Inkscape::Verb *, unsigned int> *user_shortcuts = nullptr; void sp_shortcut_init() { - verbs = new std::map<unsigned int, Inkscape::Verb * >(); + verbs = new std::map<unsigned int, Inkscape::Verb *>(); primary_shortcuts = new std::map<Inkscape::Verb *, unsigned int>(); user_shortcuts = new std::map<Inkscape::Verb *, unsigned int>(); @@ -102,7 +100,7 @@ void sp_shortcut_init() reason = "No key file set in preferences"; } else { reason = "Unable to read key file set in preferences"; - + bool absolute = Glib::path_is_absolute(shortcutfile); if (absolute) { success = try_shortcuts_file(shortcutfile.c_str()); @@ -131,14 +129,16 @@ void sp_shortcut_init() success = try_shortcuts_file(get_path(SYSTEM, KEYS, "inkscape.xml")); } if (!success) { - g_warning("Could not load any keyboard shortcut file (including fallbacks to 'default.xml' and 'inkscape.xml')."); + g_warning( + "Could not load any keyboard shortcut file (including fallbacks to 'default.xml' and 'inkscape.xml')."); } // load shortcuts adjusted by user try_shortcuts_file(get_path(USER, KEYS, "default.xml"), true); } -static bool try_shortcuts_file(char const *filename, bool const is_user_set) { +static bool try_shortcuts_file(char const *filename, bool const is_user_set) +{ using Inkscape::IO::file_test; /* ah, if only we had an exception to catch... (permission, forgiveness) */ @@ -173,13 +173,14 @@ static bool try_shortcuts_file(char const *filename, bool const is_user_set) { * - sp_shortcut_get_for_event() - get an existing shortcut for a key event * (they correctly handle the packing of modifier keys into the keyval) */ -guint sp_shortcut_translate_event(GdkEventKey const *event, guint *effective_modifiers) { +guint sp_shortcut_translate_event(GdkEventKey const *event, guint *effective_modifiers) +{ guint keyval = 0; guint initial_modifiers = event->state; guint consumed_modifiers = 0; guint remaining_modifiers = 0; - guint resulting_modifiers = 0; // remaining modifiers encoded in high-bit mask + guint resulting_modifiers = 0; // remaining modifiers encoded in high-bit mask keyval = Inkscape::UI::Tools::get_latin_keyval(event, &consumed_modifiers); @@ -192,12 +193,12 @@ guint sp_shortcut_translate_event(GdkEventKey const *event, guint *effective_mod } remaining_modifiers = initial_modifiers & ~consumed_modifiers; - resulting_modifiers = ( remaining_modifiers & GDK_SHIFT_MASK ? SP_SHORTCUT_SHIFT_MASK : 0 ) | - ( remaining_modifiers & GDK_CONTROL_MASK ? SP_SHORTCUT_CONTROL_MASK : 0 ) | - ( remaining_modifiers & GDK_SUPER_MASK ? SP_SHORTCUT_SUPER_MASK : 0 ) | - ( remaining_modifiers & GDK_HYPER_MASK ? SP_SHORTCUT_HYPER_MASK : 0 ) | - ( remaining_modifiers & GDK_META_MASK ? SP_SHORTCUT_META_MASK : 0 ) | - ( remaining_modifiers & GDK_MOD1_MASK ? SP_SHORTCUT_ALT_MASK : 0 ); + resulting_modifiers = (remaining_modifiers & GDK_SHIFT_MASK ? SP_SHORTCUT_SHIFT_MASK : 0) | + (remaining_modifiers & GDK_CONTROL_MASK ? SP_SHORTCUT_CONTROL_MASK : 0) | + (remaining_modifiers & GDK_SUPER_MASK ? SP_SHORTCUT_SUPER_MASK : 0) | + (remaining_modifiers & GDK_HYPER_MASK ? SP_SHORTCUT_HYPER_MASK : 0) | + (remaining_modifiers & GDK_META_MASK ? SP_SHORTCUT_META_MASK : 0) | + (remaining_modifiers & GDK_MOD1_MASK ? SP_SHORTCUT_ALT_MASK : 0); *effective_modifiers = resulting_modifiers; return keyval; @@ -206,13 +207,15 @@ guint sp_shortcut_translate_event(GdkEventKey const *event, guint *effective_mod /* * Returns a new Inkscape shortcut parsed from a key event. */ -unsigned int sp_shortcut_get_from_event(GdkEventKey const *event) { +unsigned int sp_shortcut_get_from_event(GdkEventKey const *event) +{ guint effective_modifiers; sp_shortcut_translate_event(event, &effective_modifiers); // return the actual keyval and the corresponding modifiers for creating the shortcut - // we must not return the translated keyval, otherwise we end up with illegal shortcuts like "Shift+9" instead of "(" + // we must not return the translated keyval, otherwise we end up with illegal shortcuts like "Shift+9" instead of + // "(" return (event->keyval) | effective_modifiers; } @@ -220,7 +223,8 @@ unsigned int sp_shortcut_get_from_event(GdkEventKey const *event) { * Returns a new Inkscape shortcut parsed from a key event. * (equivalent to sp_shortcut_get_from_event() but accepts the arguments of Gtk::CellRendererAccel::signal_accel_edited) */ -unsigned int sp_shortcut_get_from_gdk_event(guint accel_key, Gdk::ModifierType accel_mods, guint hardware_keycode) { +unsigned int sp_shortcut_get_from_gdk_event(guint accel_key, Gdk::ModifierType accel_mods, guint hardware_keycode) +{ GdkEventKey event; event.keyval = accel_key; event.state = accel_mods; @@ -233,7 +237,8 @@ unsigned int sp_shortcut_get_from_gdk_event(guint accel_key, Gdk::ModifierType a * Returns the Inkscape-internal integral shortcut representation for a key event. * Use this to compare the received key event to known shortcuts. */ -unsigned int sp_shortcut_get_for_event(GdkEventKey const *event) { +unsigned int sp_shortcut_get_for_event(GdkEventKey const *event) +{ guint keyval; guint effective_modifiers; @@ -243,8 +248,8 @@ unsigned int sp_shortcut_get_for_event(GdkEventKey const *event) { return keyval | effective_modifiers; } -Glib::ustring sp_shortcut_to_label(unsigned int const shortcut) { - +Glib::ustring sp_shortcut_to_label(unsigned int const shortcut) +{ Glib::ustring modifiers = ""; if (shortcut & SP_SHORTCUT_CONTROL_MASK) @@ -260,9 +265,8 @@ Glib::ustring sp_shortcut_to_label(unsigned int const shortcut) { if (shortcut & SP_SHORTCUT_META_MASK) modifiers += "Meta,"; - if(modifiers.length() > 0 && - modifiers.find(',',modifiers.length()-1)!=modifiers.npos) { - modifiers.erase(modifiers.length()-1, 1); + if (modifiers.length() > 0 && modifiers.find(',', modifiers.length() - 1) != modifiers.npos) { + modifiers.erase(modifiers.length() - 1, 1); } return modifiers; @@ -272,23 +276,21 @@ Glib::ustring sp_shortcut_to_label(unsigned int const shortcut) { * REmove all shortucts from the users file */ -void sp_shortcuts_delete_all_from_file() { - - +void sp_shortcuts_delete_all_from_file() +{ char const *filename = get_path(USER, KEYS, "default.xml"); - XML::Document *doc=sp_repr_read_file(filename, nullptr); + XML::Document *doc = sp_repr_read_file(filename, nullptr); if (!doc) { g_warning("Unable to read keys file %s", filename); return; } - XML::Node *root=doc->root(); + XML::Node *root = doc->root(); g_return_if_fail(!strcmp(root->name(), "keys")); - XML::Node *iter=root->firstChild(); + XML::Node *iter = root->firstChild(); while (iter) { - if (strcmp(iter->name(), "bind")) { // some unknown element, do not complain iter = iter->next(); @@ -297,21 +299,19 @@ void sp_shortcuts_delete_all_from_file() { // Delete node sp_repr_unparent(iter); - iter=root->firstChild(); + iter = root->firstChild(); } - sp_repr_save_file(doc, filename, nullptr); GC::release(doc); } -Inkscape::XML::Document *sp_shortcut_create_template_file(char const *filename) { - - gchar const *buffer = - "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> " - "<keys name=\"My custom shortcuts\">" - "</keys>"; +Inkscape::XML::Document *sp_shortcut_create_template_file(char const *filename) +{ + gchar const *buffer = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> " + "<keys name=\"My custom shortcuts\">" + "</keys>"; Inkscape::XML::Document *doc = sp_repr_read_mem(buffer, strlen(buffer), nullptr); sp_repr_save_file(doc, filename, nullptr); @@ -323,15 +323,17 @@ Inkscape::XML::Document *sp_shortcut_create_template_file(char const *filename) * Get a list of keyboard shortcut files names and paths from the system and users paths * Don't add the users custom keyboards file */ -void sp_shortcut_get_file_names(std::vector<Glib::ustring> *names, std::vector<Glib::ustring> *paths) { +void sp_shortcut_get_file_names(std::vector<Glib::ustring> *names, std::vector<Glib::ustring> *paths) +{ using namespace Inkscape::IO::Resource; std::vector<Glib::ustring> filenames = get_filenames(SYSTEM, KEYS, {".xml"}); - std::vector<Glib::ustring> filenames_user = get_filenames(USER, KEYS, {".xml"}, {"default.xml"}); // exclude default.xml as it only includes the user's modifications + std::vector<Glib::ustring> filenames_user = get_filenames( + USER, KEYS, {".xml"}, {"default.xml"}); // exclude default.xml as it only includes the user's modifications filenames.insert(filenames.end(), filenames_user.begin(), filenames_user.end()); std::vector<std::pair<Glib::ustring, Glib::ustring>> names_and_paths; - for(auto &filename: filenames) { + for (auto &filename : filenames) { Glib::ustring label = Glib::path_get_basename(filename); Glib::ustring filename_relative = sp_relative_path_from_path(filename, std::string(get_path(SYSTEM, KEYS))); @@ -342,9 +344,9 @@ void sp_shortcut_get_file_names(std::vector<Glib::ustring> *names, std::vector<G } // Get the "key name" from the root element of each file - XML::Node *root=doc->root(); + XML::Node *root = doc->root(); if (!strcmp(root->name(), "keys")) { - gchar const *name=root->attribute("name"); + gchar const *name = root->attribute("name"); if (name) { label = Glib::ustring(name) + " (" + label + ")"; } @@ -356,25 +358,25 @@ void sp_shortcut_get_file_names(std::vector<Glib::ustring> *names, std::vector<G } Inkscape::GC::release(doc); } - - // sort by name + + // sort by name std::sort(names_and_paths.begin(), names_and_paths.end(), - [](std::pair<Glib::ustring, Glib::ustring> pair1, std::pair<Glib::ustring, Glib::ustring> pair2) { - return Glib::path_get_basename(pair1.first).compare(Glib::path_get_basename(pair2.first)) < 0; - }); - auto it_default = std::find_if(names_and_paths.begin(), names_and_paths.end(), - [](std::pair<Glib::ustring, Glib::ustring>& pair) { - return !Glib::path_get_basename(pair.second).compare("default.xml"); - }); + [](std::pair<Glib::ustring, Glib::ustring> pair1, std::pair<Glib::ustring, Glib::ustring> pair2) { + return Glib::path_get_basename(pair1.first).compare(Glib::path_get_basename(pair2.first)) < 0; + }); + auto it_default = + std::find_if(names_and_paths.begin(), names_and_paths.end(), [](std::pair<Glib::ustring, Glib::ustring> &pair) { + return !Glib::path_get_basename(pair.second).compare("default.xml"); + }); if (it_default != names_and_paths.end()) { - std::rotate(names_and_paths.begin(), it_default, it_default+1); + std::rotate(names_and_paths.begin(), it_default, it_default + 1); } // transform pairs to output vectors - std::transform(names_and_paths.begin(),names_and_paths.end(), std::back_inserter(*names), - [](const std::pair<Glib::ustring, Glib::ustring>& pair) { return pair.first; }); - std::transform(names_and_paths.begin(),names_and_paths.end(), std::back_inserter(*paths), - [](const std::pair<Glib::ustring, Glib::ustring>& pair) { return pair.second; }); + std::transform(names_and_paths.begin(), names_and_paths.end(), std::back_inserter(*names), + [](const std::pair<Glib::ustring, Glib::ustring> &pair) { return pair.first; }); + std::transform(names_and_paths.begin(), names_and_paths.end(), std::back_inserter(*paths), + [](const std::pair<Glib::ustring, Glib::ustring> &pair) { return pair.second; }); } Glib::ustring sp_shortcut_get_file_path() @@ -384,16 +386,16 @@ Glib::ustring sp_shortcut_get_file_path() Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring attr = prefs->getString("/dialogs/save_export/path"); - if (!attr.empty()) open_path = attr; + 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))) + if (!Inkscape::IO::file_test(open_path.c_str(), (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) open_path = ""; if (open_path.empty()) { /* Grab document directory */ - const gchar* docURI = SP_ACTIVE_DOCUMENT->getDocumentURI(); + const gchar *docURI = SP_ACTIVE_DOCUMENT->getDocumentURI(); if (docURI) { open_path = Glib::path_get_dirname(docURI); open_path.append(G_DIR_SEPARATOR_S); @@ -401,8 +403,7 @@ Glib::ustring sp_shortcut_get_file_path() } //# If no open path, default to our home directory - if (open_path.empty()) - { + if (open_path.empty()) { open_path = g_get_home_dir(); open_path.append(G_DIR_SEPARATOR_S); } @@ -410,7 +411,7 @@ Glib::ustring sp_shortcut_get_file_path() return open_path; } -//static Inkscape::UI::Dialog::FileSaveDialog * saveDialog = NULL; +// static Inkscape::UI::Dialog::FileSaveDialog * saveDialog = NULL; void sp_shortcut_file_export() { @@ -420,18 +421,10 @@ void sp_shortcut_file_export() SPDesktop *desktop = SP_ACTIVE_DESKTOP; Glib::ustring filename; - Inkscape::UI::Dialog::FileSaveDialog *saveDialog = - Inkscape::UI::Dialog::FileSaveDialog::create( - *(desktop->getToplevel()), - open_path, - Inkscape::UI::Dialog::CUSTOM_TYPE, - _("Select a filename for exporting"), - "", - "", - Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS - ); + Inkscape::UI::Dialog::FileSaveDialog *saveDialog = Inkscape::UI::Dialog::FileSaveDialog::create( + *(desktop->getToplevel()), open_path, Inkscape::UI::Dialog::CUSTOM_TYPE, _("Select a filename for exporting"), + "", "", Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS); saveDialog->addFileType(_("Inkscape shortcuts (*.xml)"), ".xml"); - bool success = saveDialog->show(); if (!success) { @@ -448,18 +441,14 @@ void sp_shortcut_file_export() delete saveDialog; } -bool sp_shortcut_file_import() { - +bool sp_shortcut_file_import() +{ Glib::ustring open_path = sp_shortcut_get_file_path(); SPDesktop *desktop = SP_ACTIVE_DESKTOP; - Inkscape::UI::Dialog::FileOpenDialog *importFileDialog = - Inkscape::UI::Dialog::FileOpenDialog::create( - *desktop->getToplevel(), - open_path, - Inkscape::UI::Dialog::CUSTOM_TYPE, - _("Select a file to import")); + Inkscape::UI::Dialog::FileOpenDialog *importFileDialog = Inkscape::UI::Dialog::FileOpenDialog::create( + *desktop->getToplevel(), open_path, Inkscape::UI::Dialog::CUSTOM_TYPE, _("Select a file to import")); importFileDialog->addFilterMenu(_("Inkscape shortcuts (*.xml)"), "*.xml"); //# Show the dialog @@ -478,9 +467,9 @@ bool sp_shortcut_file_import() { return true; } -void sp_shortcut_file_import_do(char const *importname) { - - XML::Document *doc=sp_repr_read_file(importname, nullptr); +void sp_shortcut_file_import_do(char const *importname) +{ + XML::Document *doc = sp_repr_read_file(importname, nullptr); if (!doc) { g_warning("Unable to read keyboard shortcut file %s", importname); return; @@ -494,11 +483,11 @@ void sp_shortcut_file_import_do(char const *importname) { sp_shortcut_init(); } -void sp_shortcut_file_export_do(char const *exportname) { - +void sp_shortcut_file_export_do(char const *exportname) +{ char const *filename = get_path(USER, KEYS, "default.xml"); - XML::Document *doc=sp_repr_read_file(filename, nullptr); + XML::Document *doc = sp_repr_read_file(filename, nullptr); if (!doc) { g_warning("Unable to read keyboard shortcut file %s", filename); return; @@ -514,21 +503,22 @@ void sp_shortcut_file_export_do(char const *exportname) { * @param addshift - when true addthe Shifg modifier to the non-display element * * Shortcut file consists of pairs of bind elements : - * Element (a) is used for shortcut display in menus (display="True") and contains the gdk_keyval_name of the shortcut key - * Element (b) is used in shortcut lookup and contains an uppercase version of the gdk_keyval_name, - * or a gdk_keyval_name name and the "Shift" modifier for Shift altered hardware code keys (see get_latin_keyval() for explanation) + * Element (a) is used for shortcut display in menus (display="True") and contains the gdk_keyval_name of the shortcut + * key Element (b) is used in shortcut lookup and contains an uppercase version of the gdk_keyval_name, or a + * gdk_keyval_name name and the "Shift" modifier for Shift altered hardware code keys (see get_latin_keyval() for + * explanation) */ -void sp_shortcut_delete_from_file(char const * /*action*/, unsigned int const shortcut) { - +void sp_shortcut_delete_from_file(char const * /*action*/, unsigned int const shortcut) +{ char const *filename = get_path(USER, KEYS, "default.xml"); - XML::Document *doc=sp_repr_read_file(filename, nullptr); + XML::Document *doc = sp_repr_read_file(filename, nullptr); if (!doc) { g_warning("Unable to read keyboard shortcut file %s", filename); return; } - gchar *key = gdk_keyval_name (sp_shortcut_get_key(shortcut)); + gchar *key = gdk_keyval_name(sp_shortcut_get_key(shortcut)); std::string modifiers = sp_shortcut_to_label(shortcut & (SP_SHORTCUT_MODIFIER_MASK)); if (!key) { @@ -536,20 +526,19 @@ void sp_shortcut_delete_from_file(char const * /*action*/, unsigned int const sh return; } - //g_message("Removing key %s, mods %s action %s", key, modifiers.c_str(), action); + // g_message("Removing key %s, mods %s action %s", key, modifiers.c_str(), action); - XML::Node *root=doc->root(); + XML::Node *root = doc->root(); g_return_if_fail(!strcmp(root->name(), "keys")); - XML::Node *iter=root->firstChild(); + XML::Node *iter = root->firstChild(); while (iter) { - if (strcmp(iter->name(), "bind")) { // some unknown element, do not complain iter = iter->next(); continue; } - gchar const *verb_name=iter->attribute("action"); + gchar const *verb_name = iter->attribute("action"); if (!verb_name) { iter = iter->next(); continue; @@ -570,8 +559,8 @@ void sp_shortcut_delete_from_file(char const * /*action*/, unsigned int const sh gchar const *modifiers_string = iter->attribute("modifiers"); if ((modifiers_string && !strcmp(modifiers.c_str(), modifiers_string)) || - (!modifiers_string && modifiers.empty())) { - //Looks like a match + (!modifiers_string && modifiers.empty())) { + // Looks like a match // Delete node sp_repr_unparent(iter); iter = root->firstChild(); @@ -583,14 +572,13 @@ void sp_shortcut_delete_from_file(char const * /*action*/, unsigned int const sh sp_repr_save_file(doc, filename, nullptr); GC::release(doc); - } -void sp_shortcut_add_to_file(char const *action, unsigned int const shortcut) { - +void sp_shortcut_add_to_file(char const *action, unsigned int const shortcut) +{ char const *filename = get_path(USER, KEYS, "default.xml"); - XML::Document *doc=sp_repr_read_file(filename, nullptr); + XML::Document *doc = sp_repr_read_file(filename, nullptr); if (!doc) { g_warning("Unable to read keyboard shortcut file %s, creating ....", filename); doc = sp_shortcut_create_template_file(filename); @@ -600,7 +588,7 @@ void sp_shortcut_add_to_file(char const *action, unsigned int const shortcut) { } } - gchar *key = gdk_keyval_name (sp_shortcut_get_key(shortcut)); + gchar *key = gdk_keyval_name(sp_shortcut_get_key(shortcut)); std::string modifiers = sp_shortcut_to_label(shortcut & (SP_SHORTCUT_MODIFIER_MASK)); if (!key) { @@ -608,7 +596,7 @@ void sp_shortcut_add_to_file(char const *action, unsigned int const shortcut) { return; } - //g_message("Adding key %s, mods %s action %s", key, modifiers.c_str(), action); + // g_message("Adding key %s, mods %s action %s", key, modifiers.c_str(), action); // Add node Inkscape::XML::Node *newnode; @@ -633,16 +621,16 @@ void sp_shortcut_add_to_file(char const *action, unsigned int const shortcut) { sp_repr_save_file(doc, filename, nullptr); GC::release(doc); - } -static void read_shortcuts_file(char const *filename, bool const is_user_set) { - XML::Document *doc=sp_repr_read_file(filename, nullptr); +static void read_shortcuts_file(char const *filename, bool const is_user_set) +{ + XML::Document *doc = sp_repr_read_file(filename, nullptr); if (!doc) { g_warning("Unable to read keys file %s", filename); return; } - XML::Node const *root=doc->root(); + XML::Node const *root = doc->root(); _read_shortcuts_file(root, is_user_set); GC::release(doc); @@ -651,47 +639,48 @@ static void read_shortcuts_file(char const *filename, bool const is_user_set) { static void _read_shortcuts_file(XML::Node const *root, bool const is_user_set) { g_return_if_fail(!strcmp(root->name(), "keys")); - XML::NodeConstSiblingIterator iter=root->firstChild(); - for ( ; iter ; ++iter ) { + XML::NodeConstSiblingIterator iter = root->firstChild(); + for (; iter; ++iter) { if (!strcmp(iter->name(), "bind")) { - bool is_primary = iter->attribute("display") && strcmp(iter->attribute("display"), "false") && strcmp(iter->attribute("display"), "0"); + bool is_primary = iter->attribute("display") && strcmp(iter->attribute("display"), "false") && + strcmp(iter->attribute("display"), "0"); - gchar const *verb_name=iter->attribute("action"); + gchar const *verb_name = iter->attribute("action"); if (!verb_name) { g_warning("Missing verb name (action= attribute) for shortcut"); continue; } - Inkscape::Verb *verb=Inkscape::Verb::getbyid(verb_name); + Inkscape::Verb *verb = Inkscape::Verb::getbyid(verb_name); if (!verb #ifndef WITH_GSPELL - && strcmp(verb_name, "DialogSpellcheck") != 0 + && strcmp(verb_name, "DialogSpellcheck") != 0 #endif - ) { + ) { g_warning("Unknown verb name: %s", verb_name); continue; } - gchar const *keyval_name=iter->attribute("key"); + gchar const *keyval_name = iter->attribute("key"); if (!keyval_name || !*keyval_name) { // that's ok, it's just listed for reference without assignment, skip it continue; } - guint keyval=gdk_keyval_from_name(keyval_name); + guint keyval = gdk_keyval_from_name(keyval_name); if (keyval == GDK_KEY_VoidSymbol || keyval == 0) { g_warning("Unknown keyval %s for %s", keyval_name, verb_name); continue; } - guint modifiers=0; + guint modifiers = 0; - gchar const *modifiers_string=iter->attribute("modifiers"); + gchar const *modifiers_string = iter->attribute("modifiers"); if (modifiers_string) { - gchar const *iter=modifiers_string; + gchar const *iter = modifiers_string; while (*iter) { - size_t length=strcspn(iter, ","); - gchar *mod=g_strndup(iter, length); + size_t length = strcspn(iter, ","); + gchar *mod = g_strndup(iter, length); if (!strcmp(mod, "Control") || !strcmp(mod, "Ctrl")) { modifiers |= SP_SHORTCUT_CONTROL_MASK; } else if (!strcmp(mod, "Shift")) { @@ -707,9 +696,9 @@ static void _read_shortcuts_file(XML::Node const *root, bool const is_user_set) } else if (!strcmp(mod, "Primary")) { auto display = Gdk::Display::get_default(); if (display) { - GdkKeymap* keymap = display->get_keymap(); + GdkKeymap *keymap = display->get_keymap(); GdkModifierType mod = - gdk_keymap_get_modifier_mask (keymap, GDK_MODIFIER_INTENT_PRIMARY_ACCELERATOR); + gdk_keymap_get_modifier_mask(keymap, GDK_MODIFIER_INTENT_PRIMARY_ACCELERATOR); gdk_keymap_add_virtual_modifiers(keymap, &mod); if (mod & GDK_CONTROL_MASK) modifiers |= SP_SHORTCUT_CONTROL_MASK; @@ -727,7 +716,8 @@ static void _read_shortcuts_file(XML::Node const *root, bool const is_user_set) } g_free(mod); iter += length; - if (*iter) iter++; + if (*iter) + iter++; } } @@ -745,33 +735,30 @@ static void _read_shortcuts_file(XML::Node const *root, bool const is_user_set) * (Removes any existing binding for the given shortcut, including appropriately * adjusting sp_shortcut_get_primary if necessary.)* */ -void -sp_shortcut_unset(unsigned int const shortcut) +void sp_shortcut_unset(unsigned int const shortcut) { - if (!verbs) sp_shortcut_init(); + if (!verbs) + sp_shortcut_init(); Inkscape::Verb *verb = (*verbs)[shortcut]; /* Maintain the invariant that sp_shortcut_get_primary(v) returns either 0 or a valid shortcut for v. */ if (verb) { - (*verbs)[shortcut] = nullptr; unsigned int const old_primary = (*primary_shortcuts)[verb]; if (old_primary == shortcut) { (*primary_shortcuts)[verb] = 0; } - } } -GtkAccelGroup * -sp_shortcut_get_accel_group() +GtkAccelGroup *sp_shortcut_get_accel_group() { static GtkAccelGroup *accel_group = nullptr; if (!accel_group) { - accel_group = gtk_accel_group_new (); + accel_group = gtk_accel_group_new(); } return accel_group; @@ -781,8 +768,7 @@ sp_shortcut_get_accel_group() * Adds a gtk accelerator to a widget * Used to display the keyboard shortcuts in the main menu items */ -void -sp_shortcut_add_accelerator(GtkWidget *item, unsigned int const shortcut) +void sp_shortcut_add_accelerator(GtkWidget *item, unsigned int const shortcut) { if (shortcut == GDK_KEY_VoidSymbol) { return; @@ -790,33 +776,24 @@ sp_shortcut_add_accelerator(GtkWidget *item, unsigned int const shortcut) unsigned int accel_key = sp_shortcut_get_key(shortcut); if (accel_key > 0) { - gtk_widget_add_accelerator (item, - "activate", - sp_shortcut_get_accel_group(), - accel_key, - sp_shortcut_get_modifiers(shortcut), - GTK_ACCEL_VISIBLE); + gtk_widget_add_accelerator(item, "activate", sp_shortcut_get_accel_group(), accel_key, + sp_shortcut_get_modifiers(shortcut), GTK_ACCEL_VISIBLE); } } - -unsigned int -sp_shortcut_get_key(unsigned int const shortcut) +unsigned int sp_shortcut_get_key(unsigned int const shortcut) { return (shortcut & (~SP_SHORTCUT_MODIFIER_MASK)); } -GdkModifierType -sp_shortcut_get_modifiers(unsigned int const shortcut) +GdkModifierType sp_shortcut_get_modifiers(unsigned int const shortcut) { - return static_cast<GdkModifierType>( - ((shortcut & SP_SHORTCUT_SHIFT_MASK) ? GDK_SHIFT_MASK : 0) | - ((shortcut & SP_SHORTCUT_CONTROL_MASK) ? GDK_CONTROL_MASK : 0) | - ((shortcut & SP_SHORTCUT_SUPER_MASK) ? GDK_SUPER_MASK : 0) | - ((shortcut & SP_SHORTCUT_HYPER_MASK) ? GDK_HYPER_MASK : 0) | - ((shortcut & SP_SHORTCUT_META_MASK) ? GDK_META_MASK : 0) | - ((shortcut & SP_SHORTCUT_ALT_MASK) ? GDK_MOD1_MASK : 0) - ); + return static_cast<GdkModifierType>(((shortcut & SP_SHORTCUT_SHIFT_MASK) ? GDK_SHIFT_MASK : 0) | + ((shortcut & SP_SHORTCUT_CONTROL_MASK) ? GDK_CONTROL_MASK : 0) | + ((shortcut & SP_SHORTCUT_SUPER_MASK) ? GDK_SUPER_MASK : 0) | + ((shortcut & SP_SHORTCUT_HYPER_MASK) ? GDK_HYPER_MASK : 0) | + ((shortcut & SP_SHORTCUT_META_MASK) ? GDK_META_MASK : 0) | + ((shortcut & SP_SHORTCUT_ALT_MASK) ? GDK_MOD1_MASK : 0)); } /** @@ -829,10 +806,11 @@ sp_shortcut_get_modifiers(unsigned int const shortcut) * \post sp_shortcut_get_verb(shortcut) == verb. * \post !is_primary or sp_shortcut_get_primary(verb) == shortcut. */ -void -sp_shortcut_set(unsigned int const shortcut, Inkscape::Verb *const verb, bool const is_primary, bool const is_user_set) +void sp_shortcut_set(unsigned int const shortcut, Inkscape::Verb *const verb, bool const is_primary, + bool const is_user_set) { - if (!verbs) sp_shortcut_init(); + if (!verbs) + sp_shortcut_init(); Inkscape::Verb *old_verb = (*verbs)[shortcut]; (*verbs)[shortcut] = verb; @@ -853,10 +831,10 @@ sp_shortcut_set(unsigned int const shortcut, Inkscape::Verb *const verb, bool co } } -Inkscape::Verb * -sp_shortcut_get_verb(unsigned int shortcut) +Inkscape::Verb *sp_shortcut_get_verb(unsigned int shortcut) { - if (!verbs) sp_shortcut_init(); + if (!verbs) + sp_shortcut_init(); return (*verbs)[shortcut]; } @@ -866,7 +844,7 @@ unsigned int sp_shortcut_get_primary(Inkscape::Verb *verb) if (!primary_shortcuts) { sp_shortcut_init(); } - + if (primary_shortcuts->count(verb)) { result = (*primary_shortcuts)[verb]; } @@ -888,7 +866,8 @@ bool sp_shortcut_is_user_set(Inkscape::Verb *verb) gchar *sp_shortcut_get_label(unsigned int shortcut) { - // The comment below was copied from the function sp_ui_shortcut_string in interface.cpp (which was subsequently removed) + // The comment below was copied from the function sp_ui_shortcut_string in interface.cpp (which was subsequently + // removed) /* TODO: This function shouldn't exist. Our callers should use GtkAccelLabel instead of * a generic GtkLabel containing this string, and should call gtk_widget_add_accelerator. * Will probably need to change sp_shortcut_invoke callers. @@ -899,9 +878,7 @@ gchar *sp_shortcut_get_label(unsigned int shortcut) */ gchar *result = nullptr; if (shortcut != GDK_KEY_VoidSymbol) { - result = gtk_accelerator_get_label( - sp_shortcut_get_key(shortcut), - sp_shortcut_get_modifiers(shortcut)); + result = gtk_accelerator_get_label(sp_shortcut_get_key(shortcut), sp_shortcut_get_modifiers(shortcut)); } return result; } diff --git a/src/shortcuts.h b/src/shortcuts.h index ab41be8b83478834ed281eef8c7fef5f92124c72..f92ca90a562d6a228708c9ecc777d3eb4f368259 100644 --- a/src/shortcuts.h +++ b/src/shortcuts.h @@ -19,22 +19,21 @@ * This code is in public domain */ -#include <vector> -#include <gdkmm/types.h> #include <gdk/gdk.h> - +#include <gdkmm/types.h> +#include <vector> typedef struct _GtkAccelGroup GtkAccelGroup; -typedef struct _GtkWidget GtkWidget; +typedef struct _GtkWidget GtkWidget; namespace Inkscape { - class Verb; - namespace UI { - namespace View { - class View; - } - } +class Verb; +namespace UI { +namespace View { +class View; } +} // namespace UI +} // namespace Inkscape /* We define high-bit mask for packing into single int */ @@ -44,24 +43,28 @@ namespace Inkscape { #define SP_SHORTCUT_SUPER_MASK GDK_MODIFIER_RESERVED_23_MASK #define SP_SHORTCUT_HYPER_MASK GDK_MODIFIER_RESERVED_24_MASK #define SP_SHORTCUT_META_MASK GDK_MODIFIER_RESERVED_25_MASK -#define SP_SHORTCUT_MODIFIER_MASK (SP_SHORTCUT_SHIFT_MASK|SP_SHORTCUT_CONTROL_MASK|SP_SHORTCUT_ALT_MASK|SP_SHORTCUT_SUPER_MASK|SP_SHORTCUT_HYPER_MASK|SP_SHORTCUT_META_MASK) - +#define SP_SHORTCUT_MODIFIER_MASK \ + (SP_SHORTCUT_SHIFT_MASK | SP_SHORTCUT_CONTROL_MASK | SP_SHORTCUT_ALT_MASK | SP_SHORTCUT_SUPER_MASK | \ + SP_SHORTCUT_HYPER_MASK | SP_SHORTCUT_META_MASK) /* Returns true if action was performed */ -bool sp_shortcut_invoke (unsigned int shortcut, Inkscape::UI::View::View *view); +bool sp_shortcut_invoke(unsigned int shortcut, Inkscape::UI::View::View *view); void sp_shortcut_init(); -Inkscape::Verb * sp_shortcut_get_verb (unsigned int shortcut); -unsigned int sp_shortcut_get_primary (Inkscape::Verb * verb); // Returns GDK_VoidSymbol if no shortcut is found. -char* sp_shortcut_get_label (unsigned int shortcut); // Returns the human readable form of the shortcut (or NULL), for example Shift+Ctrl+F. Free the returned string with g_free. -void sp_shortcut_set(unsigned int const shortcut, Inkscape::Verb *const verb, bool const is_primary, bool const is_user_set=false); +Inkscape::Verb *sp_shortcut_get_verb(unsigned int shortcut); +unsigned int sp_shortcut_get_primary(Inkscape::Verb *verb); // Returns GDK_VoidSymbol if no shortcut is found. +char *sp_shortcut_get_label(unsigned int shortcut); // Returns the human readable form of the shortcut (or NULL), for + // example Shift+Ctrl+F. Free the returned string with g_free. +void sp_shortcut_set(unsigned int const shortcut, Inkscape::Verb *const verb, bool const is_primary, + bool const is_user_set = false); void sp_shortcut_unset(unsigned int const shortcut); void sp_shortcut_add_to_file(char const *action, unsigned int const shortcut); void sp_shortcut_delete_from_file(char const *action, unsigned int const shortcut); void sp_shortcuts_delete_all_from_file(); Glib::ustring sp_shortcut_to_label(unsigned int const shortcut); unsigned int sp_shortcut_get_from_event(GdkEventKey const *event); -unsigned int sp_shortcut_get_from_gdk_event(unsigned int accel_key, Gdk::ModifierType accel_mods, unsigned int hardware_keycode); +unsigned int sp_shortcut_get_from_gdk_event(unsigned int accel_key, Gdk::ModifierType accel_mods, + unsigned int hardware_keycode); unsigned int sp_shortcut_get_for_event(GdkEventKey const *event); void sp_shortcut_get_file_names(std::vector<Glib::ustring> *names, std::vector<Glib::ustring> *paths); bool sp_shortcut_is_user_set(Inkscape::Verb *verb); diff --git a/src/snap-candidate.h b/src/snap-candidate.h index 4854fbabec2f47f405c148ac0998decdedac521b..1a9be4776be59aadeac25dfd5febf8664151e6e5 100644 --- a/src/snap-candidate.h +++ b/src/snap-candidate.h @@ -30,66 +30,71 @@ namespace Inkscape { class SnapCandidatePoint { public: - SnapCandidatePoint() = default;; // only needed / used for resizing() of a vector in seltrans.cpp; do not use uninitialized instances! - - SnapCandidatePoint(Geom::Point const &point, Inkscape::SnapSourceType const source, long const source_num, Inkscape::SnapTargetType const target, Geom::OptRect bbox) - : _point(point), - _source_type(source), - _target_type(target), - _source_num(source_num), - _target_bbox(std::move(bbox)), - _dist() - { - }; - - SnapCandidatePoint(Geom::Point const &point, Inkscape::SnapSourceType const source, Inkscape::SnapTargetType const target) - : _point(point), - _source_type(source), - _target_type(target), - _target_bbox(Geom::OptRect()), - _dist() + SnapCandidatePoint() = default; + ; // only needed / used for resizing() of a vector in seltrans.cpp; do not use uninitialized instances! + + SnapCandidatePoint(Geom::Point const &point, Inkscape::SnapSourceType const source, long const source_num, + Inkscape::SnapTargetType const target, Geom::OptRect bbox) + : _point(point) + , _source_type(source) + , _target_type(target) + , _source_num(source_num) + , _target_bbox(std::move(bbox)) + , _dist(){}; + + SnapCandidatePoint(Geom::Point const &point, Inkscape::SnapSourceType const source, + Inkscape::SnapTargetType const target) + : _point(point) + , _source_type(source) + , _target_type(target) + , _target_bbox(Geom::OptRect()) + , _dist() { _source_num = -1; } SnapCandidatePoint(Geom::Point const &point, Inkscape::SnapSourceType const source) - : _point(point), - _source_type(source), - _target_type(Inkscape::SNAPTARGET_UNDEFINED), - _source_num(-1), - _target_bbox(Geom::OptRect()), - _dist() + : _point(point) + , _source_type(source) + , _target_type(Inkscape::SNAPTARGET_UNDEFINED) + , _source_num(-1) + , _target_bbox(Geom::OptRect()) + , _dist(){}; + + inline Geom::Point const &getPoint() const { return _point; } + inline Inkscape::SnapSourceType getSourceType() const { return _source_type; } + inline Inkscape::SnapTargetType getTargetType() const { return _target_type; } + bool isSingleHandle() const { - }; - - inline Geom::Point const & getPoint() const {return _point;} - inline Inkscape::SnapSourceType getSourceType() const {return _source_type;} - inline Inkscape::SnapTargetType getTargetType() const {return _target_type;} - bool isSingleHandle() const {return (_source_type == SNAPSOURCE_NODE_HANDLE || _source_type == SNAPSOURCE_OTHER_HANDLE) && _source_num == -1;} + return (_source_type == SNAPSOURCE_NODE_HANDLE || _source_type == SNAPSOURCE_OTHER_HANDLE) && _source_num == -1; + } - inline long getSourceNum() const {return _source_num;} - void setSourceNum(long num) {_source_num = num;} + inline long getSourceNum() const { return _source_num; } + void setSourceNum(long num) { _source_num = num; } - void setDistance(Geom::Coord dist) {_dist = dist;} - Geom::Coord getDistance() { return _dist;} + void setDistance(Geom::Coord dist) { _dist = dist; } + Geom::Coord getDistance() { return _dist; } void addOrigin(Geom::Point pt) { _origins_and_vectors.emplace_back(pt, false); } void addVector(Geom::Point v) { _origins_and_vectors.emplace_back(v, true); } - std::vector<std::pair<Geom::Point, bool> > const & getOriginsAndVectors() const {return _origins_and_vectors;} + std::vector<std::pair<Geom::Point, bool>> const &getOriginsAndVectors() const { return _origins_and_vectors; } - bool operator <(const SnapCandidatePoint &other) const { return _dist < other._dist; } // Needed for sorting the SnapCandidatePoints - inline Geom::OptRect const getTargetBBox() const {return _target_bbox;} + bool operator<(const SnapCandidatePoint &other) const + { + return _dist < other._dist; + } // Needed for sorting the SnapCandidatePoints + inline Geom::OptRect const getTargetBBox() const { return _target_bbox; } private: // Coordinates of the point Geom::Point _point; // For perpendicular or tangential snapping of a ROTATING line we need to know its (stationary) starting point. // In case of editing with the node tool, a node can be connected to two lines simultaneously, in which case we - // need to consider two starting points; Therefore a vector containing multiple starting points is used here. However, - // for perpendicular or tangential snapping of a TRANSLATING line we need to know its direction vector instead. This - // vector will be stored in the same way as the starting point is, i.e. as a Geom::Point. A boolean is paired to this - // point, which is true for vectors but false for origins - std::vector<std::pair<Geom::Point, bool> > _origins_and_vectors; + // need to consider two starting points; Therefore a vector containing multiple starting points is used here. + // However, for perpendicular or tangential snapping of a TRANSLATING line we need to know its direction vector + // instead. This vector will be stored in the same way as the starting point is, i.e. as a Geom::Point. A boolean is + // paired to this point, which is true for vectors but false for origins + std::vector<std::pair<Geom::Point, bool>> _origins_and_vectors; // If this SnapCandidatePoint is a snap source, then _source_type must be defined. If it // is a snap target, then _target_type must be defined. If it's yet unknown whether it will @@ -97,7 +102,7 @@ private: Inkscape::SnapSourceType _source_type; Inkscape::SnapTargetType _target_type; - //Sequence number of the source point within the set of points that is to be snapped. + // Sequence number of the source point within the set of points that is to be snapped. // - Starts counting at zero, but only if there might be more points following (e.g. in the selector tool) // - Minus one (-1) if we're sure that we have only a single point long _source_num; @@ -113,34 +118,39 @@ private: class SnapCandidateItem { public: - SnapCandidateItem(SPItem* item, bool clip_or_mask, Geom::Affine additional_affine) - : item(item), clip_or_mask(clip_or_mask), additional_affine(additional_affine) {} - ~SnapCandidateItem() = default;; + SnapCandidateItem(SPItem *item, bool clip_or_mask, Geom::Affine additional_affine) + : item(item) + , clip_or_mask(clip_or_mask) + , additional_affine(additional_affine) + {} + ~SnapCandidateItem() = default; + ; - SPItem* item; // An item that is to be considered for snapping to - bool clip_or_mask; // If true, then item refers to a clipping path or a mask + SPItem *item; // An item that is to be considered for snapping to + bool clip_or_mask; // If true, then item refers to a clipping path or a mask /* To find out the absolute position of a clipping path or mask, we not only need to know * the transformation of the clipping path or mask itself, but also the transformation of * the object to which the clip or mask is being applied; that transformation is stored here */ Geom::Affine additional_affine; -} -; +}; class SnapCandidatePath { - public: - SnapCandidatePath(Geom::PathVector* path, SnapTargetType target, Geom::OptRect bbox, bool edited = false) - : path_vector(path), target_type(target), target_bbox(std::move(bbox)), currently_being_edited(edited) {}; - ~SnapCandidatePath() = default;; - - Geom::PathVector* path_vector; + SnapCandidatePath(Geom::PathVector *path, SnapTargetType target, Geom::OptRect bbox, bool edited = false) + : path_vector(path) + , target_type(target) + , target_bbox(std::move(bbox)) + , currently_being_edited(edited){}; + ~SnapCandidatePath() = default; + ; + + Geom::PathVector *path_vector; SnapTargetType target_type; Geom::OptRect target_bbox; bool currently_being_edited; // true for the path that's currently being edited in the node tool (if any) - }; } // end of namespace Inkscape #endif /* !SEEN_SNAP_CANDIDATE_H */ diff --git a/src/snap-enums.h b/src/snap-enums.h index 321963b08722544f82857523437254255e3a4dc0..f53823beb443f4b50edc097af5f3b5d95d2b6277 100644 --- a/src/snap-enums.h +++ b/src/snap-enums.h @@ -15,7 +15,8 @@ namespace Inkscape { /** * enumerations of snap source types and snap target types. */ -enum SnapSourceType { // When adding source types here, then also update Inkscape::SnapPreferences::source2target! +enum SnapSourceType +{ // When adding source types here, then also update Inkscape::SnapPreferences::source2target! SNAPSOURCE_UNDEFINED = 0, //------------------------------------------------------------------- // Bbox points can be located at the edge of the stroke (for visual bboxes); they will therefore not snap @@ -28,7 +29,8 @@ enum SnapSourceType { // When adding source types here, then also update Inkscap //------------------------------------------------------------------- // For the same reason, nodes will not snap to bbox points SNAPSOURCE_NODE_CATEGORY = 32, // will be used as a flag and must therefore be a power of two - SNAPSOURCE_NODE_SMOOTH, // Symmetrical nodes are also considered to be smooth; there's no dedicated type for symm. nodes + SNAPSOURCE_NODE_SMOOTH, // Symmetrical nodes are also considered to be smooth; there's no dedicated type for symm. + // nodes SNAPSOURCE_NODE_CUSP, SNAPSOURCE_LINE_MIDPOINT, SNAPSOURCE_PATH_INTERSECTION, @@ -36,8 +38,8 @@ enum SnapSourceType { // When adding source types here, then also update Inkscap SNAPSOURCE_CONVEX_HULL_CORNER, SNAPSOURCE_ELLIPSE_QUADRANT_POINT, SNAPSOURCE_NODE_HANDLE, // eg. nodes in the path editor, handles of stars or rectangles, etc. (tied to a stroke) - //------------------------------------------------------------------- - // Other points (e.g. guides) will snap to both bounding boxes and nodes + //------------------------------------------------------------------- + // Other points (e.g. guides) will snap to both bounding boxes and nodes SNAPSOURCE_DATUMS_CATEGORY = 64, // will be used as a flag and must therefore be a power of two SNAPSOURCE_GUIDE, SNAPSOURCE_GUIDE_ORIGIN, @@ -49,10 +51,11 @@ enum SnapSourceType { // When adding source types here, then also update Inkscap SNAPSOURCE_IMG_CORNER, SNAPSOURCE_TEXT_ANCHOR, SNAPSOURCE_OTHER_HANDLE, // eg. the handle of a gradient or of a connector (ie not being tied to a stroke) - SNAPSOURCE_GRID_PITCH, // eg. when pasting or alt-dragging in the selector tool; not really a snap source + SNAPSOURCE_GRID_PITCH, // eg. when pasting or alt-dragging in the selector tool; not really a snap source }; -enum SnapTargetType { +enum SnapTargetType +{ SNAPTARGET_UNDEFINED = 0, //------------------------------------------------------------------- SNAPTARGET_BBOX_CATEGORY = 16, // will be used as a flag and must therefore be a power of two. Also, @@ -67,7 +70,7 @@ enum SnapTargetType { SNAPTARGET_NODE_SMOOTH, SNAPTARGET_NODE_CUSP, SNAPTARGET_LINE_MIDPOINT, - SNAPTARGET_PATH, // If path targets are added here, then also add them to the list in findBestSnap() + SNAPTARGET_PATH, // If path targets are added here, then also add them to the list in findBestSnap() SNAPTARGET_PATH_PERPENDICULAR, SNAPTARGET_PATH_TANGENTIAL, SNAPTARGET_PATH_INTERSECTION, @@ -75,7 +78,7 @@ enum SnapTargetType { SNAPTARGET_PATH_CLIP, SNAPTARGET_PATH_MASK, SNAPTARGET_ELLIPSE_QUADRANT_POINT, // this corner is at the center of the stroke - SNAPTARGET_RECT_CORNER, // of a rectangle, so this corner is at the center of the stroke + SNAPTARGET_RECT_CORNER, // of a rectangle, so this corner is at the center of the stroke //------------------------------------------------------------------- SNAPTARGET_DATUMS_CATEGORY = 64, // will be used as a flag and must therefore be a power of two SNAPTARGET_GRID, @@ -101,5 +104,5 @@ enum SnapTargetType { SNAPTARGET_MAX_ENUM_VALUE }; -} +} // namespace Inkscape #endif /* SNAPENUMS_H_ */ diff --git a/src/snap-preferences.cpp b/src/snap-preferences.cpp index 876293aca5cf117816ce751fcdc43fb1e41644b3..e9376410874fca3f68541f589842892ba570d8a4 100644 --- a/src/snap-preferences.cpp +++ b/src/snap-preferences.cpp @@ -12,12 +12,12 @@ #include "inkscape.h" -Inkscape::SnapPreferences::SnapPreferences() : - _snap_enabled_globally(true), - _snap_postponed_globally(false), - _strict_snapping(true), - _snap_perp(false), - _snap_tang(false) +Inkscape::SnapPreferences::SnapPreferences() + : _snap_enabled_globally(true) + , _snap_postponed_globally(false) + , _strict_snapping(true) + , _snap_perp(false) + , _snap_tang(false) { // Check for powers of two; see the comments in snap-enums.h g_assert((SNAPTARGET_BBOX_CATEGORY != 0) && !(SNAPTARGET_BBOX_CATEGORY & (SNAPTARGET_BBOX_CATEGORY - 1))); @@ -25,7 +25,7 @@ Inkscape::SnapPreferences::SnapPreferences() : g_assert((SNAPTARGET_DATUMS_CATEGORY != 0) && !(SNAPTARGET_DATUMS_CATEGORY & (SNAPTARGET_DATUMS_CATEGORY - 1))); g_assert((SNAPTARGET_OTHERS_CATEGORY != 0) && !(SNAPTARGET_OTHERS_CATEGORY & (SNAPTARGET_OTHERS_CATEGORY - 1))); - for (int & _active_snap_target : _active_snap_targets) { + for (int &_active_snap_target : _active_snap_targets) { _active_snap_target = -1; } } @@ -37,15 +37,15 @@ bool Inkscape::SnapPreferences::isAnyDatumSnappable() const bool Inkscape::SnapPreferences::isAnyCategorySnappable() const { - return isTargetSnappable(SNAPTARGET_NODE_CATEGORY, SNAPTARGET_BBOX_CATEGORY, SNAPTARGET_OTHERS_CATEGORY) || isTargetSnappable(SNAPTARGET_GUIDE, SNAPTARGET_GRID, SNAPTARGET_PAGE_BORDER); + return isTargetSnappable(SNAPTARGET_NODE_CATEGORY, SNAPTARGET_BBOX_CATEGORY, SNAPTARGET_OTHERS_CATEGORY) || + isTargetSnappable(SNAPTARGET_GUIDE, SNAPTARGET_GRID, SNAPTARGET_PAGE_BORDER); } -void Inkscape::SnapPreferences::_mapTargetToArrayIndex(Inkscape::SnapTargetType &target, bool &always_on, bool &group_on) const +void Inkscape::SnapPreferences::_mapTargetToArrayIndex(Inkscape::SnapTargetType &target, bool &always_on, + bool &group_on) const { - if (target == SNAPTARGET_BBOX_CATEGORY || - target == SNAPTARGET_NODE_CATEGORY || - target == SNAPTARGET_OTHERS_CATEGORY || - target == SNAPTARGET_DATUMS_CATEGORY) { + if (target == SNAPTARGET_BBOX_CATEGORY || target == SNAPTARGET_NODE_CATEGORY || + target == SNAPTARGET_OTHERS_CATEGORY || target == SNAPTARGET_DATUMS_CATEGORY) { // These main targets should be handled separately, because otherwise we might call isTargetSnappable() // for them (to check whether the corresponding group is on) which would lead to an infinite recursive loop always_on = (target == SNAPTARGET_DATUMS_CATEGORY); @@ -54,12 +54,16 @@ void Inkscape::SnapPreferences::_mapTargetToArrayIndex(Inkscape::SnapTargetType } if (target & SNAPTARGET_BBOX_CATEGORY) { - group_on = isTargetSnappable(SNAPTARGET_BBOX_CATEGORY); // Only if the group with bbox sources/targets has been enabled, then we might snap to any of the bbox targets + group_on = + isTargetSnappable(SNAPTARGET_BBOX_CATEGORY); // Only if the group with bbox sources/targets has been + // enabled, then we might snap to any of the bbox targets return; } if (target & SNAPTARGET_NODE_CATEGORY) { - group_on = isTargetSnappable(SNAPTARGET_NODE_CATEGORY); // Only if the group with path/node sources/targets has been enabled, then we might snap to any of the nodes/paths + group_on = + isTargetSnappable(SNAPTARGET_NODE_CATEGORY); // Only if the group with path/node sources/targets has been + // enabled, then we might snap to any of the nodes/paths switch (target) { case SNAPTARGET_RECT_CORNER: target = SNAPTARGET_NODE_CUSP; @@ -84,8 +88,8 @@ void Inkscape::SnapPreferences::_mapTargetToArrayIndex(Inkscape::SnapTargetType if (target & SNAPTARGET_DATUMS_CATEGORY) { group_on = true; // These snap targets cannot be disabled as part of a disabled group; switch (target) { - // Some snap targets don't have their own toggle. These targets are called "secondary targets". We will re-map - // them to their cousin which does have a toggle, and which is called a "primary target" + // Some snap targets don't have their own toggle. These targets are called "secondary targets". We will + // re-map them to their cousin which does have a toggle, and which is called a "primary target" case SNAPTARGET_GRID_INTERSECTION: case SNAPTARGET_GRID_PERPENDICULAR: target = SNAPTARGET_GRID; @@ -118,12 +122,13 @@ void Inkscape::SnapPreferences::_mapTargetToArrayIndex(Inkscape::SnapTargetType } if (target & SNAPTARGET_OTHERS_CATEGORY) { - // Only if the group with "other" snap sources/targets has been enabled, then we might snap to any of those targets + // Only if the group with "other" snap sources/targets has been enabled, then we might snap to any of those + // targets // ... but this doesn't hold for the page border, grids, and guides group_on = isTargetSnappable(SNAPTARGET_OTHERS_CATEGORY); switch (target) { - // Some snap targets don't have their own toggle. These targets are called "secondary targets". We will re-map - // them to their cousin which does have a toggle, and which is called a "primary target" + // Some snap targets don't have their own toggle. These targets are called "secondary targets". We will + // re-map them to their cousin which does have a toggle, and which is called a "primary target" case SNAPTARGET_TEXT_ANCHOR: target = SNAPTARGET_TEXT_BASELINE; break; @@ -151,7 +156,7 @@ void Inkscape::SnapPreferences::_mapTargetToArrayIndex(Inkscape::SnapTargetType return; } - if (target == SNAPTARGET_UNDEFINED ) { + if (target == SNAPTARGET_UNDEFINED) { g_warning("Snap-preferences warning: Undefined snaptarget (#%i)", target); } else { g_warning("Snap-preferences warning: Snaptarget not handled (#%i)", target); @@ -168,12 +173,17 @@ void Inkscape::SnapPreferences::setTargetSnappable(Inkscape::SnapTargetType cons if (always_on) { // If true, then this snap target is always active and cannot be toggled // Catch coding errors - g_warning("Snap-preferences warning: Trying to enable/disable a snap target (#%i) that's always on by definition", index); + g_warning( + "Snap-preferences warning: Trying to enable/disable a snap target (#%i) that's always on by definition", + index); } else { if (index == target) { // I.e. if it has not been re-mapped, then we have a primary target at hand _active_snap_targets[index] = enabled; - } else { // If it has been re-mapped though, then this target does not have its own toggle button and should therefore not be set - g_warning("Snap-preferences warning: Trying to enable/disable a secondary snap target (#%i); only primary targets can be set", index); + } else { // If it has been re-mapped though, then this target does not have its own toggle button and should + // therefore not be set + g_warning("Snap-preferences warning: Trying to enable/disable a secondary snap target (#%i); only primary " + "targets can be set", + index); } } } @@ -186,15 +196,16 @@ bool Inkscape::SnapPreferences::isTargetSnappable(Inkscape::SnapTargetType const _mapTargetToArrayIndex(index, always_on, group_on); - if (group_on) { // If true, then this snap target is in a snap group that has been enabled (e.g. bbox group, nodes/paths group, or "others" group + if (group_on) { // If true, then this snap target is in a snap group that has been enabled (e.g. bbox group, + // nodes/paths group, or "others" group if (always_on) { // If true, then this snap target is always active and cannot be toggled return true; } else { if (_active_snap_targets[index] == -1) { // Catch coding errors g_warning("Snap-preferences warning: Using an uninitialized snap target setting (#%i)", index); - // This happens if setTargetSnappable() has not been called for this parameter, e.g. from within sp_namedview_set, - // or if this target index doesn't exist at all + // This happens if setTargetSnappable() has not been called for this parameter, e.g. from within + // sp_namedview_set, or if this target index doesn't exist at all } return _active_snap_targets[index]; } @@ -203,26 +214,42 @@ bool Inkscape::SnapPreferences::isTargetSnappable(Inkscape::SnapTargetType const } } -bool Inkscape::SnapPreferences::isTargetSnappable(Inkscape::SnapTargetType const target1, Inkscape::SnapTargetType const target2) const { +bool Inkscape::SnapPreferences::isTargetSnappable(Inkscape::SnapTargetType const target1, + Inkscape::SnapTargetType const target2) const +{ return isTargetSnappable(target1) || isTargetSnappable(target2); } -bool Inkscape::SnapPreferences::isTargetSnappable(Inkscape::SnapTargetType const target1, Inkscape::SnapTargetType const target2, Inkscape::SnapTargetType const target3) const { +bool Inkscape::SnapPreferences::isTargetSnappable(Inkscape::SnapTargetType const target1, + Inkscape::SnapTargetType const target2, + Inkscape::SnapTargetType const target3) const +{ return isTargetSnappable(target1) || isTargetSnappable(target2) || isTargetSnappable(target3); } -bool Inkscape::SnapPreferences::isTargetSnappable(Inkscape::SnapTargetType const target1, Inkscape::SnapTargetType const target2, Inkscape::SnapTargetType const target3, Inkscape::SnapTargetType const target4) const { - return isTargetSnappable(target1) || isTargetSnappable(target2) || isTargetSnappable(target3) || isTargetSnappable(target4); +bool Inkscape::SnapPreferences::isTargetSnappable(Inkscape::SnapTargetType const target1, + Inkscape::SnapTargetType const target2, + Inkscape::SnapTargetType const target3, + Inkscape::SnapTargetType const target4) const +{ + return isTargetSnappable(target1) || isTargetSnappable(target2) || isTargetSnappable(target3) || + isTargetSnappable(target4); } -bool Inkscape::SnapPreferences::isTargetSnappable(Inkscape::SnapTargetType const target1, Inkscape::SnapTargetType const target2, Inkscape::SnapTargetType const target3, Inkscape::SnapTargetType const target4, Inkscape::SnapTargetType const target5) const { - return isTargetSnappable(target1) || isTargetSnappable(target2) || isTargetSnappable(target3) || isTargetSnappable(target4) || isTargetSnappable(target5); +bool Inkscape::SnapPreferences::isTargetSnappable(Inkscape::SnapTargetType const target1, + Inkscape::SnapTargetType const target2, + Inkscape::SnapTargetType const target3, + Inkscape::SnapTargetType const target4, + Inkscape::SnapTargetType const target5) const +{ + return isTargetSnappable(target1) || isTargetSnappable(target2) || isTargetSnappable(target3) || + isTargetSnappable(target4) || isTargetSnappable(target5); } bool Inkscape::SnapPreferences::isSnapButtonEnabled(Inkscape::SnapTargetType const target) const { bool always_on = false; // Only needed as a dummy - bool group_on = false; // Only needed as a dummy + bool group_on = false; // Only needed as a dummy Inkscape::SnapTargetType index = target; _mapTargetToArrayIndex(index, always_on, group_on); @@ -230,13 +257,17 @@ bool Inkscape::SnapPreferences::isSnapButtonEnabled(Inkscape::SnapTargetType con if (_active_snap_targets[index] == -1) { // Catch coding errors g_warning("Snap-preferences warning: Using an uninitialized snap target setting (#%i)", index); - // This happens if setTargetSnappable() has not been called for this parameter, e.g. from within sp_namedview_set, - // or if this target index doesn't exist at all + // This happens if setTargetSnappable() has not been called for this parameter, e.g. from within + // sp_namedview_set, or if this target index doesn't exist at all } else { - if (index == target) { // I.e. if it has not been re-mapped, then we have a primary target at hand, which does have its own toggle button + if (index == target) { // I.e. if it has not been re-mapped, then we have a primary target at hand, which does + // have its own toggle button return _active_snap_targets[index]; - } else { // If it has been re-mapped though, then this target does not have its own toggle button and therefore the button status cannot be read - g_warning("Snap-preferences warning: Trying to determine the button status of a secondary snap target (#%i); However, only primary targets have a button", index); + } else { // If it has been re-mapped though, then this target does not have its own toggle button and therefore + // the button status cannot be read + g_warning("Snap-preferences warning: Trying to determine the button status of a secondary snap target " + "(#%i); However, only primary targets have a button", + index); } } @@ -245,8 +276,7 @@ bool Inkscape::SnapPreferences::isSnapButtonEnabled(Inkscape::SnapTargetType con Inkscape::SnapTargetType Inkscape::SnapPreferences::source2target(Inkscape::SnapSourceType source) const { - switch (source) - { + switch (source) { case SNAPSOURCE_UNDEFINED: return SNAPTARGET_UNDEFINED; case SNAPSOURCE_BBOX_CATEGORY: @@ -306,7 +336,6 @@ bool Inkscape::SnapPreferences::isSourceSnappable(Inkscape::SnapSourceType const return isTargetSnappable(source2target(source)); } - /* Local Variables: mode:c++ diff --git a/src/snap-preferences.h b/src/snap-preferences.h index 4c0bc02ae08583ef620485f902beb485ae896c05..77ac2ca50198ea625f989fe7ba65a07a7e242506 100644 --- a/src/snap-preferences.h +++ b/src/snap-preferences.h @@ -13,8 +13,7 @@ #include "snap-enums.h" -namespace Inkscape -{ +namespace Inkscape { /** * Storing of snapping preferences. @@ -26,9 +25,13 @@ public: void setTargetSnappable(Inkscape::SnapTargetType const target, bool enabled); bool isTargetSnappable(Inkscape::SnapTargetType const target) const; bool isTargetSnappable(Inkscape::SnapTargetType const target1, Inkscape::SnapTargetType const target2) const; - bool isTargetSnappable(Inkscape::SnapTargetType const target1, Inkscape::SnapTargetType const target2, Inkscape::SnapTargetType const target3) const; - bool isTargetSnappable(Inkscape::SnapTargetType const target1, Inkscape::SnapTargetType const target2, Inkscape::SnapTargetType const target3, Inkscape::SnapTargetType const target4) const; - bool isTargetSnappable(Inkscape::SnapTargetType const target1, Inkscape::SnapTargetType const target2, Inkscape::SnapTargetType const target3, Inkscape::SnapTargetType const target4, Inkscape::SnapTargetType const target5) const; + bool isTargetSnappable(Inkscape::SnapTargetType const target1, Inkscape::SnapTargetType const target2, + Inkscape::SnapTargetType const target3) const; + bool isTargetSnappable(Inkscape::SnapTargetType const target1, Inkscape::SnapTargetType const target2, + Inkscape::SnapTargetType const target3, Inkscape::SnapTargetType const target4) const; + bool isTargetSnappable(Inkscape::SnapTargetType const target1, Inkscape::SnapTargetType const target2, + Inkscape::SnapTargetType const target3, Inkscape::SnapTargetType const target4, + Inkscape::SnapTargetType const target5) const; bool isSnapButtonEnabled(Inkscape::SnapTargetType const target) const; SnapTargetType source2target(SnapSourceType source) const; @@ -37,55 +40,57 @@ public: bool isAnyDatumSnappable() const; // Needed because we cannot toggle the datum snap targets as a group bool isAnyCategorySnappable() const; - void setSnapEnabledGlobally(bool enabled) {_snap_enabled_globally = enabled;} - bool getSnapEnabledGlobally() const {return _snap_enabled_globally;} + void setSnapEnabledGlobally(bool enabled) { _snap_enabled_globally = enabled; } + bool getSnapEnabledGlobally() const { return _snap_enabled_globally; } - void setSnapPostponedGlobally(bool postponed) {_snap_postponed_globally = postponed;} - bool getSnapPostponedGlobally() const {return _snap_postponed_globally;} + void setSnapPostponedGlobally(bool postponed) { _snap_postponed_globally = postponed; } + bool getSnapPostponedGlobally() const { return _snap_postponed_globally; } - bool getStrictSnapping() const {return _strict_snapping;} + bool getStrictSnapping() const { return _strict_snapping; } - bool getSnapPerp() const {return _snap_perp;} - bool getSnapTang() const {return _snap_tang;} - void setSnapPerp(bool enabled) {_snap_perp = enabled;} - void setSnapTang(bool enabled) {_snap_tang = enabled;} + bool getSnapPerp() const { return _snap_perp; } + bool getSnapTang() const { return _snap_tang; } + void setSnapPerp(bool enabled) { _snap_perp = enabled; } + void setSnapTang(bool enabled) { _snap_tang = enabled; } - double getGridTolerance() const {return _grid_tolerance;} - double getGuideTolerance() const {return _guide_tolerance;} - double getObjectTolerance() const {return _object_tolerance;} + double getGridTolerance() const { return _grid_tolerance; } + double getGuideTolerance() const { return _guide_tolerance; } + double getObjectTolerance() const { return _object_tolerance; } - void setGridTolerance(double val) {_grid_tolerance = val;} - void setGuideTolerance(double val) {_guide_tolerance = val;} - void setObjectTolerance(double val) {_object_tolerance = val;} + void setGridTolerance(double val) { _grid_tolerance = val; } + void setGuideTolerance(double val) { _guide_tolerance = val; } + void setObjectTolerance(double val) { _object_tolerance = val; } private: - /** * Map snap target to array index. * - * The status of each snap toggle (in the snap toolbar) is stored as a boolean value in an array. This method returns the position - * of relevant boolean in that array, for any given type of snap target. For most snap targets, the enumerated value of that targets - * matches the position in the array (primary snap targets). This however does not hold for snap targets which don't have their own - * toggle button (secondary snap targets). + * The status of each snap toggle (in the snap toolbar) is stored as a boolean value in an array. This method + * returns the position of relevant boolean in that array, for any given type of snap target. For most snap targets, + * the enumerated value of that targets matches the position in the array (primary snap targets). This however does + * not hold for snap targets which don't have their own toggle button (secondary snap targets). * * PS: - * - For snap sources, just pass the corresponding snap target instead (each snap source should have a twin snap target, but not vice versa) + * - For snap sources, just pass the corresponding snap target instead (each snap source should have a twin snap + * target, but not vice versa) * - All parameters are passed by reference, and will be overwritten * - * @param target Stores the enumerated snap target, which can be modified to correspond to the array index of this snap target. + * @param target Stores the enumerated snap target, which can be modified to correspond to the array index of this + * snap target. * @param always_on If true, then this snap target is always active and cannot be toggled. - * @param group_on If true, then this snap target is in a snap group that has been enabled (e.g. bbox group, nodes/paths group, or "others" group. + * @param group_on If true, then this snap target is in a snap group that has been enabled (e.g. bbox group, + * nodes/paths group, or "others" group. */ void _mapTargetToArrayIndex(Inkscape::SnapTargetType &target, bool &always_on, bool &group_on) const; int _active_snap_targets[Inkscape::SNAPTARGET_MAX_ENUM_VALUE]; - bool _snap_enabled_globally; // Toggles ALL snapping + bool _snap_enabled_globally; // Toggles ALL snapping bool _snap_postponed_globally; // Hold all snapping temporarily when the mouse is moving fast - //If enabled, then bbox corners will only snap to bboxes, - //and nodes will only snap to nodes and paths. We will not - //snap bbox corners to nodes, or nodes to bboxes. + // If enabled, then bbox corners will only snap to bboxes, + // and nodes will only snap to nodes and paths. We will not + // snap bbox corners to nodes, or nodes to bboxes. //(snapping to grids and guides is not affected by this) bool _strict_snapping; @@ -97,7 +102,7 @@ private: double _object_tolerance; }; -} +} // namespace Inkscape #endif /*SNAPPREFERENCES_H_*/ /* diff --git a/src/snap.cpp b/src/snap.cpp index acc6008415f76d75fe76778c2d5faa7f5df37449..82e1dc0930acdf0c116267dd48983457c18cc776 100644 --- a/src/snap.cpp +++ b/src/snap.cpp @@ -16,42 +16,36 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <utility> -#include <vector> +#include "snap.h" #include <2geom/transforms.h> - -#include "snap.h" +#include <utility> +#include <vector> #include "desktop.h" -#include "inkscape.h" -#include "pure-transform.h" - #include "display/canvas-grid.h" #include "display/snap-indicator.h" - #include "helper/mathfns.h" - -#include "object/sp-namedview.h" +#include "inkscape.h" #include "object/sp-guide.h" - +#include "object/sp-namedview.h" +#include "pure-transform.h" #include "ui/tools/tool-base.h" -using Inkscape::Util::round_to_upper_multiple_plus; using Inkscape::Util::round_to_lower_multiple_plus; +using Inkscape::Util::round_to_upper_multiple_plus; -SnapManager::SnapManager(SPNamedView const *v) : - guide(this, 0), - object(this, 0), - snapprefs(), - _named_view(v), - _rotation_center_source_items(std::vector<SPItem*>()), - _guide_to_ignore(nullptr), - _desktop(nullptr), - _snapindicator(true), - _unselected_nodes(nullptr) -{ -} +SnapManager::SnapManager(SPNamedView const *v) + : guide(this, 0) + , object(this, 0) + , snapprefs() + , _named_view(v) + , _rotation_center_source_items(std::vector<SPItem *>()) + , _guide_to_ignore(nullptr) + , _desktop(nullptr) + , _snapindicator(true) + , _unselected_nodes(nullptr) +{} SnapManager::SnapperList SnapManager::getSnappers() const { @@ -70,7 +64,7 @@ SnapManager::SnapperList SnapManager::getGridSnappers() const SnapperList s; if (_desktop && _desktop->gridsEnabled() && snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_GRID)) { - for(auto grid : _named_view->grids) { + for (auto grid : _named_view->grids) { s.push_back(grid->snapper); } } @@ -80,12 +74,12 @@ SnapManager::SnapperList SnapManager::getGridSnappers() const bool SnapManager::someSnapperMightSnap(bool immediately) const { - if ( !snapprefs.getSnapEnabledGlobally() ) { + if (!snapprefs.getSnapEnabledGlobally()) { return false; } // If we're asking if some snapper might snap RIGHT NOW (without the snap being postponed)... - if ( immediately && snapprefs.getSnapPostponedGlobally() ) { + if (immediately && snapprefs.getSnapPostponedGlobally()) { return false; } @@ -100,7 +94,7 @@ bool SnapManager::someSnapperMightSnap(bool immediately) const bool SnapManager::gridSnapperMightSnap() const { - if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) { + if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally()) { return false; } @@ -113,16 +107,15 @@ bool SnapManager::gridSnapperMightSnap() const return (i != s.end()); } -void SnapManager::freeSnapReturnByRef(Geom::Point &p, - Inkscape::SnapSourceType const source_type, +void SnapManager::freeSnapReturnByRef(Geom::Point &p, Inkscape::SnapSourceType const source_type, Geom::OptRect const &bbox_to_snap) const { - Inkscape::SnappedPoint const s = freeSnap(Inkscape::SnapCandidatePoint(p, source_type, Inkscape::SNAPTARGET_PATH), bbox_to_snap); + Inkscape::SnappedPoint const s = + freeSnap(Inkscape::SnapCandidatePoint(p, source_type, Inkscape::SNAPTARGET_PATH), bbox_to_snap); s.getPointIfSnapped(p); } -Inkscape::SnappedPoint SnapManager::freeSnap(Inkscape::SnapCandidatePoint const &p, - Geom::OptRect const &bbox_to_snap, +Inkscape::SnappedPoint SnapManager::freeSnap(Inkscape::SnapCandidatePoint const &p, Geom::OptRect const &bbox_to_snap, bool to_paths_only) const { if (!someSnapperMightSnap()) { @@ -174,7 +167,7 @@ Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t, Geom::Point c // Cannot use getGridSnappers() because we need both the grids AND their snappers // Therefore we iterate through all grids manually for (auto grid : _named_view->grids) { - const Inkscape::Snapper* snapper = grid->snapper; + const Inkscape::Snapper *snapper = grid->snapper; if (snapper && snapper->ThisSnapperMightSnap()) { // To find the nearest multiple of the grid pitch for a given translation t, we // will use the grid snapper. Simply snapping the value t to the grid will do, but @@ -183,11 +176,13 @@ Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t, Geom::Point c Geom::Point const t_offset = t + grid->origin; IntermSnapResults isr; // Only the first three parameters are being used for grid snappers - snapper->freeSnap(isr, Inkscape::SnapCandidatePoint(t_offset, Inkscape::SNAPSOURCE_GRID_PITCH),Geom::OptRect(), nullptr, nullptr); + snapper->freeSnap(isr, Inkscape::SnapCandidatePoint(t_offset, Inkscape::SNAPSOURCE_GRID_PITCH), + Geom::OptRect(), nullptr, nullptr); // Find the best snap for this grid, including intersections of the grid-lines bool old_val = _snapindicator; _snapindicator = false; - Inkscape::SnappedPoint s = findBestSnap(Inkscape::SnapCandidatePoint(t_offset, Inkscape::SNAPSOURCE_GRID_PITCH), isr, false, true); + Inkscape::SnappedPoint s = findBestSnap( + Inkscape::SnapCandidatePoint(t_offset, Inkscape::SNAPSOURCE_GRID_PITCH), isr, false, true); _snapindicator = old_val; if (s.getSnapped() && (s.getSnapDistance() < nearest_distance)) { // use getSnapDistance() instead of getWeightedDistance() here because the pointer's position @@ -210,12 +205,12 @@ Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t, Geom::Point c return t; } -void SnapManager::constrainedSnapReturnByRef(Geom::Point &p, - Inkscape::SnapSourceType const source_type, +void SnapManager::constrainedSnapReturnByRef(Geom::Point &p, Inkscape::SnapSourceType const source_type, Inkscape::Snapper::SnapConstraint const &constraint, Geom::OptRect const &bbox_to_snap) const { - Inkscape::SnappedPoint const s = constrainedSnap(Inkscape::SnapCandidatePoint(p, source_type), constraint, bbox_to_snap); + Inkscape::SnappedPoint const s = + constrainedSnap(Inkscape::SnapCandidatePoint(p, source_type), constraint, bbox_to_snap); p = s.getPoint(); // If we didn't snap, then we will return the point projected onto the constraint } @@ -226,7 +221,9 @@ Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapCandidatePoint // First project the mouse pointer onto the constraint Geom::Point pp = constraint.projection(p.getPoint()); - Inkscape::SnappedPoint no_snap = Inkscape::SnappedPoint(pp, p.getSourceType(), p.getSourceNum(), Inkscape::SNAPTARGET_CONSTRAINT, Geom::infinity(), 0, false, true, false); + Inkscape::SnappedPoint no_snap = + Inkscape::SnappedPoint(pp, p.getSourceType(), p.getSourceNum(), Inkscape::SNAPTARGET_CONSTRAINT, + Geom::infinity(), 0, false, true, false); if (!someSnapperMightSnap()) { // Always return point on constraint @@ -240,7 +237,8 @@ Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapCandidatePoint // Snapping the mouse pointer instead of the constrained position of the knot allows // to snap to things which don't intersect with the constraint line; this is basically // then just a freesnap with the constraint applied afterwards - // We'll only do this if we're dragging a single handle, and for example not when transforming an object in the selector tool + // We'll only do this if we're dragging a single handle, and for example not when transforming an object in the + // selector tool result = freeSnap(p, bbox_to_snap); if (result.getSnapped()) { // only change the snap indicator if we really snapped to something @@ -262,7 +260,6 @@ Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapCandidatePoint result = findBestSnap(p, isr, true); - if (result.getSnapped()) { // only change the snap indicator if we really snapped to something if (_snapindicator && _desktop) { @@ -279,17 +276,18 @@ Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapCandidatePoint * \param p Source point to be snapped * \param constraints List of directions or lines along which snapping must occur * \param dont_snap If true then we will only apply the constraint, without snapping - * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation + * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same + * transformation */ - -Inkscape::SnappedPoint SnapManager::multipleConstrainedSnaps(Inkscape::SnapCandidatePoint const &p, - std::vector<Inkscape::Snapper::SnapConstraint> const &constraints, - bool dont_snap, - Geom::OptRect const &bbox_to_snap) const +Inkscape::SnappedPoint +SnapManager::multipleConstrainedSnaps(Inkscape::SnapCandidatePoint const &p, + std::vector<Inkscape::Snapper::SnapConstraint> const &constraints, bool dont_snap, + Geom::OptRect const &bbox_to_snap) const { - - Inkscape::SnappedPoint no_snap = Inkscape::SnappedPoint(p.getPoint(), p.getSourceType(), p.getSourceNum(), Inkscape::SNAPTARGET_CONSTRAINT, Geom::infinity(), 0, false, true, false); + Inkscape::SnappedPoint no_snap = + Inkscape::SnappedPoint(p.getPoint(), p.getSourceType(), p.getSourceNum(), Inkscape::SNAPTARGET_CONSTRAINT, + Geom::infinity(), 0, false, true, false); if (constraints.size() == 0) { return no_snap; } @@ -299,7 +297,7 @@ Inkscape::SnappedPoint SnapManager::multipleConstrainedSnaps(Inkscape::SnapCandi // Project the mouse pointer on each of the constraints std::vector<Geom::Point> projections; - for (const auto & constraint : constraints) { + for (const auto &constraint : constraints) { // Project the mouse pointer onto the constraint; In case we don't snap then we will // return the projection onto the constraint, such that the constraint is always enforced Geom::Point pp = constraint.projection(p.getPoint()); @@ -308,14 +306,14 @@ Inkscape::SnappedPoint SnapManager::multipleConstrainedSnaps(Inkscape::SnapCandi // Select the closest constraint no_snap.setPoint(projections.front()); - Inkscape::Snapper::SnapConstraint cc = constraints.front(); //closest constraint + Inkscape::Snapper::SnapConstraint cc = constraints.front(); // closest constraint std::vector<Inkscape::Snapper::SnapConstraint>::const_iterator c = constraints.begin(); std::vector<Geom::Point>::iterator pp = projections.begin(); for (; pp != projections.end(); ++pp) { if (Geom::L2(*pp - p.getPoint()) < Geom::L2(no_snap.getPoint() - p.getPoint())) { no_snap.setPoint(*pp); // Remember the projection onto the closest constraint - cc = *c; // Remember the closest constraint itself + cc = *c; // Remember the closest constraint itself } ++c; } @@ -334,14 +332,15 @@ Inkscape::SnappedPoint SnapManager::multipleConstrainedSnaps(Inkscape::SnapCandi // Snapping the mouse pointer instead of the constrained position of the knot allows // to snap to things which don't intersect with the constraint line; this is basically // then just a freesnap with the constraint applied afterwards - // We'll only to this if we're dragging a single handle, and for example not when transforming an object in the selector tool + // We'll only to this if we're dragging a single handle, and for example not when transforming an object in the + // selector tool result = freeSnap(p, bbox_to_snap); // Now apply the constraint afterwards result.setPoint(cc.projection(result.getPoint())); } else { // Try to snap along the closest constraint for (auto snapper : snappers) { - snapper->constrainedSnap(isr, p, bbox_to_snap, cc, &_items_to_ignore,_unselected_nodes); + snapper->constrainedSnap(isr, p, bbox_to_snap, cc, &_items_to_ignore, _unselected_nodes); } result = findBestSnap(p, isr, true); } @@ -350,9 +349,8 @@ Inkscape::SnappedPoint SnapManager::multipleConstrainedSnaps(Inkscape::SnapCandi } Inkscape::SnappedPoint SnapManager::constrainedAngularSnap(Inkscape::SnapCandidatePoint const &p, - boost::optional<Geom::Point> const &p_ref, - Geom::Point const &o, - unsigned const snaps) const + boost::optional<Geom::Point> const &p_ref, + Geom::Point const &o, unsigned const snaps) const { Inkscape::SnappedPoint sp; if (snaps > 0) { // 0 means no angular snapping @@ -373,10 +371,10 @@ Inkscape::SnappedPoint SnapManager::constrainedAngularSnap(Inkscape::SnapCandida // Now do the snapping... std::vector<Inkscape::Snapper::SnapConstraint> constraints; - constraints.emplace_back(Geom::Line(o, angle_ceil - M_PI/2)); - constraints.emplace_back(Geom::Line(o, angle_floor - M_PI/2)); + constraints.emplace_back(Geom::Line(o, angle_ceil - M_PI / 2)); + constraints.emplace_back(Geom::Line(o, angle_floor - M_PI / 2)); sp = multipleConstrainedSnaps(p, constraints); // Constraints will always be applied, even if we didn't snap - if (!sp.getSnapped()) { // If we haven't snapped then we only had the constraint applied; + if (!sp.getSnapped()) { // If we haven't snapped then we only had the constraint applied; sp.setTarget(Inkscape::SNAPTARGET_CONSTRAINED_ANGLE); } } else { @@ -388,11 +386,13 @@ Inkscape::SnappedPoint SnapManager::constrainedAngularSnap(Inkscape::SnapCandida void SnapManager::guideFreeSnap(Geom::Point &p, Geom::Point &origin_or_vector, bool origin, bool freeze_angle) const { if (freeze_angle && origin) { - g_warning("Dear developer, when snapping guides you shouldn't ask me to freeze the guide's vector when you haven't specified one"); + g_warning("Dear developer, when snapping guides you shouldn't ask me to freeze the guide's vector when you " + "haven't specified one"); // You've supplied me with an origin instead of a vector } - if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() || !snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_GUIDE)) { + if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() || + !snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_GUIDE)) { return; } @@ -415,8 +415,8 @@ void SnapManager::guideFreeSnap(Geom::Point &p, Geom::Point &origin_or_vector, b s.getPointIfSnapped(p); if (!freeze_angle && s.getSnapped()) { - if (!Geom::are_near(s.getTangent(), Geom::Point(0,0))) { // If the tangent has been set ... - origin_or_vector = Geom::rot90(s.getTangent()); // then use it to update the normal of the guide + if (!Geom::are_near(s.getTangent(), Geom::Point(0, 0))) { // If the tangent has been set ... + origin_or_vector = Geom::rot90(s.getTangent()); // then use it to update the normal of the guide // PS: The tangent might not have been set if we snapped for example to a node } } @@ -424,7 +424,8 @@ void SnapManager::guideFreeSnap(Geom::Point &p, Geom::Point &origin_or_vector, b void SnapManager::guideConstrainedSnap(Geom::Point &p, SPGuide const &guideline) const { - if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() || !snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_GUIDE)) { + if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() || + !snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_GUIDE)) { return; } @@ -442,11 +443,8 @@ void SnapManager::guideConstrainedSnap(Geom::Point &p, SPGuide const &guideline) s.getPointIfSnapped(p); } -void SnapManager::snapTransformed( - std::vector<Inkscape::SnapCandidatePoint> const &points, - Geom::Point const &pointer, - Inkscape::PureTransform &transform - ) +void SnapManager::snapTransformed(std::vector<Inkscape::SnapCandidatePoint> const &points, Geom::Point const &pointer, + Inkscape::PureTransform &transform) { /* We have a list of points, which we are proposing to transform in some way. We need to see ** if any of these points, when transformed, snap to anything. If they do, we return the @@ -478,15 +476,13 @@ void SnapManager::snapTransformed( } if (points.size() == 1) { - displaySnapsource(Inkscape::SnapCandidatePoint(transform.best_snapped_point.getPoint(), points.at(0).getSourceType())); + displaySnapsource( + Inkscape::SnapCandidatePoint(transform.best_snapped_point.getPoint(), points.at(0).getSourceType())); } } -Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint const &p, - IntermSnapResults const &isr, - bool constrained, - bool allowOffScreen, - bool to_path_only) const +Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint const &p, IntermSnapResults const &isr, + bool constrained, bool allowOffScreen, bool to_path_only) const { g_assert(_desktop != nullptr); @@ -510,8 +506,8 @@ Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint co for (std::list<Inkscape::SnappedLine>::const_iterator i = isr.grid_lines.begin(); i != isr.grid_lines.end(); i++) { _desktop->snapindicator->set_new_debugging_point((*i).getPoint()); } - for (std::list<Inkscape::SnappedLine>::const_iterator i = isr.guide_lines.begin(); i != isr.guide_lines.end(); i++) { - _desktop->snapindicator->set_new_debugging_point((*i).getPoint()); + for (std::list<Inkscape::SnappedLine>::const_iterator i = isr.guide_lines.begin(); i != isr.guide_lines.end(); i++) + { _desktop->snapindicator->set_new_debugging_point((*i).getPoint()); } */ @@ -526,8 +522,8 @@ Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint co // search for the closest snapped curve Inkscape::SnappedCurve closestCurve; - // We might have collected the paths only to snap to their intersection, without the intention to snap to the paths themselves - // Therefore we explicitly check whether the paths should be considered as snap targets themselves + // We might have collected the paths only to snap to their intersection, without the intention to snap to the paths + // themselves Therefore we explicitly check whether the paths should be considered as snap targets themselves bool exclude_paths = !snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_PATH); if (getClosestCurve(isr.curves, closestCurve, exclude_paths)) { sp_list.emplace_back(closestCurve); @@ -564,7 +560,8 @@ Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint co if (snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_PATH_GUIDE_INTERSECTION)) { // search for the closest snapped intersection of a guide with a curve Inkscape::SnappedPoint closestCurveGuideIntersection; - if (getClosestIntersectionCL(isr.curves, isr.guide_lines, p.getPoint(), closestCurveGuideIntersection, _desktop->dt2doc())) { + if (getClosestIntersectionCL(isr.curves, isr.guide_lines, p.getPoint(), closestCurveGuideIntersection, + _desktop->dt2doc())) { closestCurveGuideIntersection.setSource(p.getSourceType()); sp_list.push_back(closestCurveGuideIntersection); } @@ -605,14 +602,10 @@ Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint co while (i != sp_list.end()) { Inkscape::SnapTargetType t = (*i).getTarget(); - if (t == Inkscape::SNAPTARGET_LINE_MIDPOINT || - t == Inkscape::SNAPTARGET_PATH || - t == Inkscape::SNAPTARGET_PATH_PERPENDICULAR || - t == Inkscape::SNAPTARGET_PATH_TANGENTIAL || - t == Inkscape::SNAPTARGET_PATH_INTERSECTION || - t == Inkscape::SNAPTARGET_PATH_GUIDE_INTERSECTION || - t == Inkscape::SNAPTARGET_PATH_CLIP || - t == Inkscape::SNAPTARGET_PATH_MASK || + if (t == Inkscape::SNAPTARGET_LINE_MIDPOINT || t == Inkscape::SNAPTARGET_PATH || + t == Inkscape::SNAPTARGET_PATH_PERPENDICULAR || t == Inkscape::SNAPTARGET_PATH_TANGENTIAL || + t == Inkscape::SNAPTARGET_PATH_INTERSECTION || t == Inkscape::SNAPTARGET_PATH_GUIDE_INTERSECTION || + t == Inkscape::SNAPTARGET_PATH_CLIP || t == Inkscape::SNAPTARGET_PATH_MASK || t == Inkscape::SNAPTARGET_ELLIPSE_QUADRANT_POINT) { ++i; } else { @@ -625,9 +618,10 @@ Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint co Inkscape::SnappedPoint bestSnappedPoint(p.getPoint()); // std::cout << "Finding the best snap..." << std::endl; for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); ++i) { - // std::cout << "sp = " << (*i).getPoint() << " | source = " << (*i).getSource() << " | target = " << (*i).getTarget(); + // std::cout << "sp = " << (*i).getPoint() << " | source = " << (*i).getSource() << " | target = " << + // (*i).getTarget(); bool onScreen = _desktop->get_display_area().contains((*i).getPoint()); - if (onScreen || allowOffScreen) { // Only snap to points which are not off the screen + if (onScreen || allowOffScreen) { // Only snap to points which are not off the screen if ((*i).getSnapDistance() <= (*i).getTolerance()) { // Only snap to points within snapping range // if it's the first point, or if it is closer than the best snapped point so far if (i == sp_list.begin() || bestSnappedPoint.isOtherSnapBetter(*i, false)) { @@ -648,19 +642,18 @@ Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint co } } - // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << " | dist = " << bestSnappedPoint.getSnapDistance() << std::endl; + // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << " | dist = " << + // bestSnappedPoint.getSnapDistance() << std::endl; return bestSnappedPoint; } -void SnapManager::setup(SPDesktop const *desktop, - bool snapindicator, - SPItem const *item_to_ignore, - std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes, - SPGuide *guide_to_ignore) +void SnapManager::setup(SPDesktop const *desktop, bool snapindicator, SPItem const *item_to_ignore, + std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes, SPGuide *guide_to_ignore) { g_assert(desktop != nullptr); if (_desktop != nullptr) { - g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly held invalid pointers"); + g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly " + "held invalid pointers"); } _items_to_ignore.clear(); if (item_to_ignore) { @@ -673,15 +666,13 @@ void SnapManager::setup(SPDesktop const *desktop, _rotation_center_source_items.clear(); } -void SnapManager::setup(SPDesktop const *desktop, - bool snapindicator, - std::vector<SPItem const *> &items_to_ignore, - std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes, - SPGuide *guide_to_ignore) +void SnapManager::setup(SPDesktop const *desktop, bool snapindicator, std::vector<SPItem const *> &items_to_ignore, + std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes, SPGuide *guide_to_ignore) { g_assert(desktop != nullptr); if (_desktop != nullptr) { - g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly held invalid pointers"); + g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly " + "held invalid pointers"); } _items_to_ignore = items_to_ignore; _desktop = desktop; @@ -692,15 +683,15 @@ void SnapManager::setup(SPDesktop const *desktop, } /// Setup, taking the list of items to ignore from the desktop's selection. -void SnapManager::setupIgnoreSelection(SPDesktop const *desktop, - bool snapindicator, - std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes, - SPGuide *guide_to_ignore) +void SnapManager::setupIgnoreSelection(SPDesktop const *desktop, bool snapindicator, + std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes, + SPGuide *guide_to_ignore) { g_assert(desktop != nullptr); if (_desktop != nullptr) { // Someone has been naughty here! This is dangerous - g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly held invalid pointers"); + g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly " + "held invalid pointers"); } _desktop = desktop; _snapindicator = snapindicator; @@ -711,7 +702,7 @@ void SnapManager::setupIgnoreSelection(SPDesktop const *desktop, Inkscape::Selection *sel = _desktop->selection; auto items = sel->items(); - for (auto i=items.begin();i!=items.end();++i) { + for (auto i = items.begin(); i != items.end(); ++i) { _items_to_ignore.push_back(*i); } } @@ -721,7 +712,7 @@ SPDocument *SnapManager::getDocument() const return _named_view->document; } -//Geom::Point SnapManager::_transformPoint(Inkscape::SnapCandidatePoint const &p, +// Geom::Point SnapManager::_transformPoint(Inkscape::SnapCandidatePoint const &p, // Transformation const transformation_type, // Geom::Point const &transformation, // Geom::Point const &origin, @@ -735,8 +726,8 @@ SPDocument *SnapManager::getDocument() const // transformed = p.getPoint() + transformation; // break; // case SCALE: -// transformed = (p.getPoint() - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + origin; -// break; +// transformed = (p.getPoint() - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + +// origin; break; // case STRETCH: // { // Geom::Scale s(1, 1); @@ -773,7 +764,8 @@ SPDocument *SnapManager::getDocument() const * @param point_type Category of points to which the source point belongs: node, guide or bounding box * @param p The transformed position of the source point, paired with an identifier of the type of the snap source. */ -void SnapManager::displaySnapsource(Inkscape::SnapCandidatePoint const &p) const { +void SnapManager::displaySnapsource(Inkscape::SnapCandidatePoint const &p) const +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs->getBool("/options/snapclosestonly/value")) { Inkscape::SnapSourceType t = p.getSourceType(); @@ -782,7 +774,9 @@ void SnapManager::displaySnapsource(Inkscape::SnapCandidatePoint const &p) const bool p_is_other = (t & Inkscape::SNAPSOURCE_OTHERS_CATEGORY) || (t & Inkscape::SNAPSOURCE_DATUMS_CATEGORY); g_assert(_desktop != nullptr); - if (snapprefs.getSnapEnabledGlobally() && (p_is_other || (p_is_a_node && snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_NODE_CATEGORY)) || (p_is_a_bbox && snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_BBOX_CATEGORY)))) { + if (snapprefs.getSnapEnabledGlobally() && + (p_is_other || (p_is_a_node && snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_NODE_CATEGORY)) || + (p_is_a_bbox && snapprefs.isTargetSnappable(Inkscape::SNAPTARGET_BBOX_CATEGORY)))) { _desktop->snapindicator->set_new_snapsource(p); } else { _desktop->snapindicator->remove_snapsource(); diff --git a/src/snap.h b/src/snap.h index 886bfcafa48cc00dbac6631dd051ef226a5401a3..025896137e709ae7d3aeabb4358220c57ec6e929 100644 --- a/src/snap.h +++ b/src/snap.h @@ -24,9 +24,9 @@ #include "object-snapper.h" #include "snap-preferences.h" - // Guides -enum SPGuideDragType { // used both here and in desktop-events.cpp +enum SPGuideDragType +{ // used both here and in desktop-events.cpp SP_DRAG_TRANSLATE, SP_DRAG_ROTATE, SP_DRAG_MOVE_ORIGIN, @@ -38,10 +38,9 @@ class SPGuide; class SPNamedView; namespace Inkscape { - class PureTransform; +class PureTransform; } - /** * Class to coordinate snapping operations. * @@ -52,7 +51,7 @@ namespace Inkscape { * when looking for snap target candidates, and toggling of the snap indicator), and it provides * many different methods for snapping queries (free snapping vs. constrained snapping, * returning the result by reference or through a return statement, etc.) - * + * * Each SPNamedView has one of these. It offers methods to snap points to whatever * snappers are defined (e.g. grid, guides etc.). It also allows callers to snap * points which have undergone some transformation (e.g. translation, scaling etc.) @@ -63,7 +62,7 @@ namespace Inkscape { * (this class), which keeps some data about objects in the document and answers queries * of the type "given this point and type of transformation, what is the best place * to snap to?". - * + * * The second is in event-context.cpp and implements the snapping timeout. Whenever a motion * events happens over the canvas, it stores it for later use and initiates a timeout. * This timeout is discarded whenever a new motion event occurs. When the timeout expires, @@ -75,7 +74,8 @@ namespace Inkscape { class SnapManager { public: - enum Transformation { + enum Transformation + { TRANSLATE, SCALE, STRETCH, @@ -90,7 +90,7 @@ public: */ SnapManager(SPNamedView const *v); - typedef std::list<const Inkscape::Snapper*> SnapperList; + typedef std::list<const Inkscape::Snapper *> SnapperList; /** * Return true if any snapping might occur, whether its to grids, guides or objects. @@ -112,11 +112,9 @@ public: /** * Convenience shortcut when there is only one item to ignore. */ - void setup(SPDesktop const *desktop, - bool snapindicator = true, - SPItem const *item_to_ignore = nullptr, - std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes = nullptr, - SPGuide *guide_to_ignore = nullptr); + void setup(SPDesktop const *desktop, bool snapindicator = true, SPItem const *item_to_ignore = nullptr, + std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes = nullptr, + SPGuide *guide_to_ignore = nullptr); /** * Prepare the snap manager for the actual snapping, which includes building a list of snap targets @@ -126,35 +124,37 @@ public: * whereas this one will take a list of items to ignore * * @param desktop Reference to the desktop to which this snap manager is attached. - * @param snapindicator If true then a snap indicator will be displayed automatically (when enabled in the preferences). - * @param items_to_ignore These items will not be snapped to, e.g. the items that are currently being dragged. This avoids "self-snapping". + * @param snapindicator If true then a snap indicator will be displayed automatically (when enabled in the + * preferences). + * @param items_to_ignore These items will not be snapped to, e.g. the items that are currently being dragged. This + * avoids "self-snapping". * @param unselected_nodes Stationary nodes of the path that is currently being edited in the node tool and * that can be snapped too. Nodes not in this list will not be snapped to, to avoid "self-snapping". Of each * unselected node both the position (Geom::Point) and the type (Inkscape::SnapTargetType) will be stored. * @param guide_to_ignore Guide that is currently being dragged and should not be snapped to. */ - void setup(SPDesktop const *desktop, - bool snapindicator, - std::vector<SPItem const *> &items_to_ignore, + void setup(SPDesktop const *desktop, bool snapindicator, std::vector<SPItem const *> &items_to_ignore, std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes = nullptr, SPGuide *guide_to_ignore = nullptr); - void setupIgnoreSelection(SPDesktop const *desktop, - bool snapindicator = true, + void setupIgnoreSelection(SPDesktop const *desktop, bool snapindicator = true, std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes = nullptr, SPGuide *guide_to_ignore = nullptr); - void unSetup() {_rotation_center_source_items.clear(); - _guide_to_ignore = nullptr; - _desktop = nullptr; - _unselected_nodes = nullptr;} + void unSetup() + { + _rotation_center_source_items.clear(); + _guide_to_ignore = nullptr; + _desktop = nullptr; + _unselected_nodes = nullptr; + } // If we're dragging a rotation center, then setRotationCenterSource() stores the parent item // of this rotation center; this reference is used to make sure that we do not snap a rotation // center to itself // NOTE: Must be called after calling setup(), not before! - void setRotationCenterSource(const std::vector<SPItem*> &items) {_rotation_center_source_items = items;} - const std::vector<SPItem*> &getRotationCenterSource() {return _rotation_center_source_items;} + void setRotationCenterSource(const std::vector<SPItem *> &items) { _rotation_center_source_items = items; } + const std::vector<SPItem *> &getRotationCenterSource() { return _rotation_center_source_items; } // freeSnapReturnByRef() is preferred over freeSnap(), because it only returns a // point if snapping has occurred (by overwriting p); otherwise p is untouched @@ -179,12 +179,13 @@ public: * 2) Only to be used when a single source point is to be snapped; it assumes * that source_num = 0, which is inefficient when snapping sets our source points * - * @param p Current position of the snap source; will be overwritten by the position of the snap target if snapping has occurred. + * @param p Current position of the snap source; will be overwritten by the position of the snap target if snapping + * has occurred. * @param source_type Detailed description of the source type, will be used by the snap indicator. - * @param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation. + * @param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same + * transformation. */ - void freeSnapReturnByRef(Geom::Point &p, - Inkscape::SnapSourceType const source_type, + void freeSnapReturnByRef(Geom::Point &p, Inkscape::SnapSourceType const source_type, Geom::OptRect const &bbox_to_snap = Geom::OptRect()) const; /** @@ -199,10 +200,12 @@ public: * although only once for each set of points * * @param p Source point to be snapped. - * @param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation. - * @param to_path_only Only snap to points on a path, such as path intersections with itself or with grids/guides. This is used for - * example when adding nodes to a path. We will not snap for example to grid intersections - * @return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics. + * @param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same + * transformation. + * @param to_path_only Only snap to points on a path, such as path intersections with itself or with grids/guides. + * This is used for example when adding nodes to a path. We will not snap for example to grid intersections + * @return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various + * metrics. */ Inkscape::SnappedPoint freeSnap(Inkscape::SnapCandidatePoint const &p, Geom::OptRect const &bbox_to_snap = Geom::OptRect(), @@ -257,13 +260,14 @@ public: * that source_num = 0, which is inefficient when snapping sets our source points * - * @param p Current position of the snap source; will be overwritten by the position of the snap target if snapping has occurred. + * @param p Current position of the snap source; will be overwritten by the position of the snap target if snapping + has occurred. * @param source_type Detailed description of the source type, will be used by the snap indicator. * @param constraint The direction or line along which snapping must occur. - * @param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation. + * @param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same + transformation. */ - void constrainedSnapReturnByRef(Geom::Point &p, - Inkscape::SnapSourceType const source_type, + void constrainedSnapReturnByRef(Geom::Point &p, Inkscape::SnapSourceType const source_type, Inkscape::Snapper::SnapConstraint const &constraint, Geom::OptRect const &bbox_to_snap = Geom::OptRect()) const; @@ -282,7 +286,8 @@ public: * * @param p Source point to be snapped. * @param constraint The direction or line along which snapping must occur. - * @param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation. + * @param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same + * transformation. */ Inkscape::SnappedPoint constrainedSnap(Inkscape::SnapCandidatePoint const &p, Inkscape::Snapper::SnapConstraint const &constraint, @@ -303,25 +308,27 @@ public: * @param p Source point to be snapped. * @param p_ref Optional original point, relative to which the angle should be calculated. If empty then * the angle will be calculated relative to the y-axis. - * @param snaps Number of angular increments per PI radians; E.g. if snaps = 2 then we will snap every PI/2 = 90 degrees. + * @param snaps Number of angular increments per PI radians; E.g. if snaps = 2 then we will snap every PI/2 = 90 + * degrees. */ Inkscape::SnappedPoint constrainedAngularSnap(Inkscape::SnapCandidatePoint const &p, - boost::optional<Geom::Point> const &p_ref, - Geom::Point const &o, - unsigned const snaps) const; + boost::optional<Geom::Point> const &p_ref, Geom::Point const &o, + unsigned const snaps) const; /** * Wrapper method to make snapping of the guide origin a bit easier (i.e. simplifies the calling code). * * PS: SnapManager::setup() must have been called before calling this method, * - * @param p Current position of the point on the guide that is to be snapped; will be overwritten by the position of the snap target if snapping has occurred. - * @param origin_or_vector Data used for tangential and perpendicular snapping. When rotating a guide the origin of the rotation is specified here, whereas when - * dragging a guide its vector is specified here + * @param p Current position of the point on the guide that is to be snapped; will be overwritten by the position of + * the snap target if snapping has occurred. + * @param origin_or_vector Data used for tangential and perpendicular snapping. When rotating a guide the origin of + * the rotation is specified here, whereas when dragging a guide its vector is specified here * @param origin If true then origin_or_vector contains an origin, other it contains a vector - * @param freeze_angle If true (in which case origin is false), then the vector specified in origin_or_vector will not be touched, i.e. the guide will - * in all circumstances keep its angle. Otherwise the vector in origin_or_vector can be updated, meaning that the guide might take on the angle of a curve that - * has been snapped too tangentially or perpendicularly + * @param freeze_angle If true (in which case origin is false), then the vector specified in origin_or_vector will + * not be touched, i.e. the guide will in all circumstances keep its angle. Otherwise the vector in origin_or_vector + * can be updated, meaning that the guide might take on the angle of a curve that has been snapped too tangentially + * or perpendicularly */ void guideFreeSnap(Geom::Point &p, Geom::Point &origin_or_vector, bool origin, bool freeze_angle) const; @@ -330,13 +337,14 @@ public: * * PS: SnapManager::setup() must have been called before calling this method, * - * @param p Current position of the point on the guide that is to be snapped; will be overwritten by the position of the snap target if snapping has occurred. + * @param p Current position of the point on the guide that is to be snapped; will be overwritten by the position of + * the snap target if snapping has occurred. * @param guideline The guide that is currently being dragged */ void guideConstrainedSnap(Geom::Point &p, SPGuide const &guideline) const; - Inkscape::GuideSnapper guide; ///< guide snapper - Inkscape::ObjectSnapper object; ///< snapper to other objects + Inkscape::GuideSnapper guide; ///< guide snapper + Inkscape::ObjectSnapper object; ///< snapper to other objects Inkscape::SnapPreferences snapprefs; /** @@ -365,12 +373,12 @@ public: */ SnapperList getGridSnappers() const; - SPDesktop const *getDesktop() const {return _desktop;} - SPNamedView const *getNamedView() const {return _named_view;} + SPDesktop const *getDesktop() const { return _desktop; } + SPNamedView const *getNamedView() const { return _named_view; } SPDocument *getDocument() const; - SPGuide const *getGuideToIgnore() const {return _guide_to_ignore;} + SPGuide const *getGuideToIgnore() const { return _guide_to_ignore; } - bool getSnapIndicator() const {return _snapindicator;} + bool getSnapIndicator() const { return _snapindicator; } /** * Given a set of possible snap targets, find the best target (which is not necessarily @@ -379,12 +387,16 @@ public: * @param p Source point to be snapped. * @param isr A structure holding all snap targets that have been found so far. * @param constrained True if the snap is constrained, e.g. for stretching or for purely horizontal translation. - * @param allowOffScreen If true, then snapping to points which are off the screen is allowed (needed for example when pasting to the grid). - * @param to_path_only Only snap to points on a path, such as path intersections with itself or with grids/guides. This is used for - * example when adding nodes to a path. We will not snap for example to grid intersections - * @return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics. + * @param allowOffScreen If true, then snapping to points which are off the screen is allowed (needed for example + * when pasting to the grid). + * @param to_path_only Only snap to points on a path, such as path intersections with itself or with grids/guides. + * This is used for example when adding nodes to a path. We will not snap for example to grid intersections + * @return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various + * metrics. */ - Inkscape::SnappedPoint findBestSnap(Inkscape::SnapCandidatePoint const &p, IntermSnapResults const &isr, bool constrained, bool allowOffScreen = false, bool to_paths_only = false) const; + Inkscape::SnappedPoint findBestSnap(Inkscape::SnapCandidatePoint const &p, IntermSnapResults const &isr, + bool constrained, bool allowOffScreen = false, + bool to_paths_only = false) const; /** * Mark the location of the snap source (not the snap target!) on the canvas by drawing a symbol. @@ -409,25 +421,32 @@ public: * If no snap has occurred and we're asked for a constrained snap then the constraint * will be applied nevertheless * - * @param points Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source. - * @param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed). + * @param points Collection of points to snap (snap sources), at their untransformed position, all points undergoing + * the same transformation. Paired with an identifier of the type of the snap source. + * @param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still + * untransformed). * @param transform Describes the type of transformation, it's parameters, and any additional constraints */ - void snapTransformed(std::vector<Inkscape::SnapCandidatePoint> const &points, - Geom::Point const &pointer, - Inkscape::PureTransform &transform); + void snapTransformed(std::vector<Inkscape::SnapCandidatePoint> const &points, Geom::Point const &pointer, + Inkscape::PureTransform &transform); protected: SPNamedView const *_named_view; private: - std::vector<SPItem const *> _items_to_ignore; ///< Items that should not be snapped to, for example the items that are currently being dragged. Set using the setup() method - std::vector<SPItem*> _rotation_center_source_items; // to avoid snapping a rotation center to itself - SPGuide *_guide_to_ignore; ///< A guide that should not be snapped to, e.g. the guide that is currently being dragged + std::vector<SPItem const *> _items_to_ignore; ///< Items that should not be snapped to, for example the items that + ///< are currently being dragged. Set using the setup() method + std::vector<SPItem *> _rotation_center_source_items; // to avoid snapping a rotation center to itself + SPGuide *_guide_to_ignore; ///< A guide that should not be snapped to, e.g. the guide that is currently being + ///< dragged SPDesktop const *_desktop; bool _snapindicator; ///< When true, an indicator will be drawn at the position that was being snapped to - std::vector<Inkscape::SnapCandidatePoint> *_unselected_nodes; ///< Nodes of the path that is currently being edited and which have not been selected and which will therefore be stationary. Only these nodes will be considered for snapping to. Of each unselected node both the position (Geom::Point) and the type (Inkscape::SnapTargetType) will be stored - + std::vector<Inkscape::SnapCandidatePoint> *_unselected_nodes; ///< Nodes of the path that is currently being edited + ///< and which have not been selected and which will + ///< therefore be stationary. Only these nodes will be + ///< considered for snapping to. Of each unselected + ///< node both the position (Geom::Point) and the type + ///< (Inkscape::SnapTargetType) will be stored }; #endif // !SEEN_SNAP_H diff --git a/src/snapped-curve.cpp b/src/snapped-curve.cpp index 70ad72ee0767bdfb271f6fca783d9d51def31a3b..c91d757d527ca2882c67bf4264c1aad20c53441d 100644 --- a/src/snapped-curve.cpp +++ b/src/snapped-curve.cpp @@ -10,9 +10,14 @@ */ #include "snapped-curve.h" + #include <2geom/path-intersection.h> -Inkscape::SnappedCurve::SnappedCurve(Geom::Point const &snapped_point, Geom::Point const &tangent, int num_path, int num_segm, Geom::Coord const &snapped_distance, Geom::Coord const &snapped_tolerance, bool const &always_snap, bool const &fully_constrained, Geom::Curve const *curve, SnapSourceType source, long source_num, SnapTargetType target, Geom::OptRect target_bbox) +Inkscape::SnappedCurve::SnappedCurve(Geom::Point const &snapped_point, Geom::Point const &tangent, int num_path, + int num_segm, Geom::Coord const &snapped_distance, + Geom::Coord const &snapped_tolerance, bool const &always_snap, + bool const &fully_constrained, Geom::Curve const *curve, SnapSourceType source, + long source_num, SnapTargetType target, Geom::OptRect target_bbox) { _num_path = num_path; _num_segm = num_segm; @@ -44,8 +49,8 @@ Inkscape::SnappedCurve::SnappedCurve() _second_distance = Geom::infinity(); _second_tolerance = 1; _second_always_snap = false; - _point = Geom::Point(0,0); - _tangent = Geom::Point(0,0); + _point = Geom::Point(0, 0); + _tangent = Geom::Point(0, 0); _at_intersection = false; _fully_constrained = false; _source = SNAPSOURCE_UNDEFINED; @@ -54,10 +59,10 @@ Inkscape::SnappedCurve::SnappedCurve() _target_bbox = Geom::OptRect(); } -Inkscape::SnappedCurve::~SnappedCurve() -= default; +Inkscape::SnappedCurve::~SnappedCurve() = default; -Inkscape::SnappedPoint Inkscape::SnappedCurve::intersect(SnappedCurve const &curve, Geom::Point const &p, Geom::Affine dt2doc) const +Inkscape::SnappedPoint Inkscape::SnappedCurve::intersect(SnappedCurve const &curve, Geom::Point const &p, + Geom::Affine dt2doc) const { // Calculate the intersections of two curves, which are both within snapping range, and // return only the closest intersection @@ -70,17 +75,21 @@ Inkscape::SnappedPoint Inkscape::SnappedCurve::intersect(SnappedCurve const &cur // There might be multiple intersections: find the closest Geom::Coord best_dist = Geom::infinity(); Geom::Point best_p = Geom::Point(Geom::infinity(), Geom::infinity()); - for (const auto & c : cs) { + for (const auto &c : cs) { Geom::Point p_ix = this->_curve->pointAt(c.ta); Geom::Coord dist = Geom::distance(p_ix, p); // Test if we have two segments (curves) from the same path.. if (this->_num_path == curve._num_path) { // Never try to intersect a segment with itself - if (this->_num_segm == curve._num_segm) continue; - // Two subsequent segments (curves) in a path will have a common node; this node is not considered to be an intersection - if (this->_num_segm == curve._num_segm + 1 && c.ta == 0 && c.tb == 1) continue; - if (this->_num_segm + 1 == curve._num_segm && c.ta == 1 && c.tb == 0) continue; + if (this->_num_segm == curve._num_segm) + continue; + // Two subsequent segments (curves) in a path will have a common node; this node is not considered to be + // an intersection + if (this->_num_segm == curve._num_segm + 1 && c.ta == 0 && c.tb == 1) + continue; + if (this->_num_segm + 1 == curve._num_segm && c.ta == 1 && c.tb == 0) + continue; } if (dist < best_dist) { @@ -97,20 +106,26 @@ Inkscape::SnappedPoint Inkscape::SnappedCurve::intersect(SnappedCurve const &cur // The intersection should in fact be returned in desktop coordinates best_p = best_p * dt2doc; - Geom::Coord primaryDist = use_this_as_primary ? Geom::L2(best_p - this->getPoint()) : Geom::L2(best_p - curve.getPoint()); - Geom::Coord secondaryDist = use_this_as_primary ? Geom::L2(best_p - curve.getPoint()) : Geom::L2(best_p - this->getPoint()); + Geom::Coord primaryDist = + use_this_as_primary ? Geom::L2(best_p - this->getPoint()) : Geom::L2(best_p - curve.getPoint()); + Geom::Coord secondaryDist = + use_this_as_primary ? Geom::L2(best_p - curve.getPoint()) : Geom::L2(best_p - this->getPoint()); // TODO: Investigate whether it is possible to use document coordinates everywhere // in the snapper code. Only the mouse position should be in desktop coordinates, I guess. // All paths are already in document coords and we are certainly not going to change THAT. - return SnappedPoint(best_p, Inkscape::SNAPSOURCE_UNDEFINED, primaryC->getSourceNum(), Inkscape::SNAPTARGET_PATH_INTERSECTION, primaryDist, primaryC->getTolerance(), primaryC->getAlwaysSnap(), true, false, true, - secondaryDist, secondaryC->getTolerance(), secondaryC->getAlwaysSnap()); + return SnappedPoint(best_p, Inkscape::SNAPSOURCE_UNDEFINED, primaryC->getSourceNum(), + Inkscape::SNAPTARGET_PATH_INTERSECTION, primaryDist, primaryC->getTolerance(), + primaryC->getAlwaysSnap(), true, false, true, secondaryDist, secondaryC->getTolerance(), + secondaryC->getAlwaysSnap()); } // No intersection - return SnappedPoint(Geom::Point(Geom::infinity(), Geom::infinity()), SNAPSOURCE_UNDEFINED, 0, SNAPTARGET_UNDEFINED, Geom::infinity(), 0, false, false, false, false, Geom::infinity(), 0, false); + return SnappedPoint(Geom::Point(Geom::infinity(), Geom::infinity()), SNAPSOURCE_UNDEFINED, 0, SNAPTARGET_UNDEFINED, + Geom::infinity(), 0, false, false, false, false, Geom::infinity(), 0, false); } -Inkscape::SnappedPoint Inkscape::SnappedCurve::intersect(SnappedLine const &line, Geom::Point const &p, Geom::Affine dt2doc) const +Inkscape::SnappedPoint Inkscape::SnappedCurve::intersect(SnappedLine const &line, Geom::Point const &p, + Geom::Affine dt2doc) const { // Calculate the intersections of a curve with a line, which are both within snapping range, and // return only the closest intersection @@ -119,19 +134,20 @@ Inkscape::SnappedPoint Inkscape::SnappedCurve::intersect(SnappedLine const &line // closest, as there might be multiple intersections of a single curve with a line // 1) get a Geom::Line object from the SnappedLine - // 2) convert to document coordinates (line and p are in desktop coordinates, but the curves are in document coordinate) - // 3) create a Geom::LineSegment (i.e. a curve), because we cannot use a Geom::Line for calculating intersections + // 2) convert to document coordinates (line and p are in desktop coordinates, but the curves are in document + // coordinate) 3) create a Geom::LineSegment (i.e. a curve), because we cannot use a Geom::Line for calculating + // intersections // (for this we will create a 2e6 pixels long linesegment, with t running from -1e6 to 1e6; this should be long // enough for any practical purpose) Geom::LineSegment line_segm = line.getLine().transformed(dt2doc).segment(-1e6, 1e6); // - const Geom::Curve *line_as_curve = dynamic_cast<Geom::Curve const*>(&line_segm); + const Geom::Curve *line_as_curve = dynamic_cast<Geom::Curve const *>(&line_segm); Geom::Crossings cs = crossings(*(this->_curve), *line_as_curve); if (cs.size() > 0) { // There might be multiple intersections: find the closest Geom::Coord best_dist = Geom::infinity(); Geom::Point best_p = Geom::Point(Geom::infinity(), Geom::infinity()); - for (const auto & c : cs) { + for (const auto &c : cs) { Geom::Point p_ix = this->_curve->pointAt(c.ta); Geom::Coord dist = Geom::distance(p_ix, p); @@ -147,21 +163,23 @@ Inkscape::SnappedPoint Inkscape::SnappedCurve::intersect(SnappedLine const &line // Now we've found the closest intersection, return it as a SnappedPoint if (_distance < line.getSnapDistance()) { // curve is the closest, so this is our primary snap target - return SnappedPoint(best_p, Inkscape::SNAPSOURCE_UNDEFINED, this->getSourceNum(), Inkscape::SNAPTARGET_PATH_GUIDE_INTERSECTION, - Geom::L2(best_p - this->getPoint()), this->getTolerance(), this->getAlwaysSnap(), true, false, true, - Geom::L2(best_p - line.getPoint()), line.getTolerance(), line.getAlwaysSnap()); + return SnappedPoint(best_p, Inkscape::SNAPSOURCE_UNDEFINED, this->getSourceNum(), + Inkscape::SNAPTARGET_PATH_GUIDE_INTERSECTION, Geom::L2(best_p - this->getPoint()), + this->getTolerance(), this->getAlwaysSnap(), true, false, true, + Geom::L2(best_p - line.getPoint()), line.getTolerance(), line.getAlwaysSnap()); } else { - return SnappedPoint(best_p, Inkscape::SNAPSOURCE_UNDEFINED, line.getSourceNum(), Inkscape::SNAPTARGET_PATH_GUIDE_INTERSECTION, - Geom::L2(best_p - line.getPoint()), line.getTolerance(), line.getAlwaysSnap(), true, false, true, - Geom::L2(best_p - this->getPoint()), this->getTolerance(), this->getAlwaysSnap()); + return SnappedPoint(best_p, Inkscape::SNAPSOURCE_UNDEFINED, line.getSourceNum(), + Inkscape::SNAPTARGET_PATH_GUIDE_INTERSECTION, Geom::L2(best_p - line.getPoint()), + line.getTolerance(), line.getAlwaysSnap(), true, false, true, + Geom::L2(best_p - this->getPoint()), this->getTolerance(), this->getAlwaysSnap()); } } // No intersection - return SnappedPoint(Geom::Point(Geom::infinity(), Geom::infinity()), SNAPSOURCE_UNDEFINED, 0, SNAPTARGET_UNDEFINED, Geom::infinity(), 0, false, false, false, false, Geom::infinity(), 0, false); + return SnappedPoint(Geom::Point(Geom::infinity(), Geom::infinity()), SNAPSOURCE_UNDEFINED, 0, SNAPTARGET_UNDEFINED, + Geom::infinity(), 0, false, false, false, false, Geom::infinity(), 0, false); } - // search for the closest snapped line bool getClosestCurve(std::list<Inkscape::SnappedCurve> const &list, Inkscape::SnappedCurve &result, bool exclude_paths) { @@ -181,17 +199,20 @@ bool getClosestCurve(std::list<Inkscape::SnappedCurve> const &list, Inkscape::Sn } // search for the closest intersection of two snapped curves, which are both member of the same collection -bool getClosestIntersectionCS(std::list<Inkscape::SnappedCurve> const &list, Geom::Point const &p, Inkscape::SnappedPoint &result, Geom::Affine dt2doc) +bool getClosestIntersectionCS(std::list<Inkscape::SnappedCurve> const &list, Geom::Point const &p, + Inkscape::SnappedPoint &result, Geom::Affine dt2doc) { bool success = false; for (std::list<Inkscape::SnappedCurve>::const_iterator i = list.begin(); i != list.end(); ++i) { - if ((*i).getTarget() != Inkscape::SNAPTARGET_BBOX_EDGE) { // We don't support snapping to intersections of bboxes, + if ((*i).getTarget() != Inkscape::SNAPTARGET_BBOX_EDGE) { // We don't support snapping to intersections of + // bboxes, // as this would require two bboxes two be flashed in the snap indicator std::list<Inkscape::SnappedCurve>::const_iterator j = i; ++j; for (; j != list.end(); ++j) { - if ((*j).getTarget() != Inkscape::SNAPTARGET_BBOX_EDGE) { // We don't support snapping to intersections of bboxes + if ((*j).getTarget() != Inkscape::SNAPTARGET_BBOX_EDGE) { // We don't support snapping to intersections + // of bboxes Inkscape::SnappedPoint sp = (*i).intersect(*j, p, dt2doc); if (sp.getAtIntersection()) { // if it's the first point @@ -200,7 +221,8 @@ bool getClosestIntersectionCS(std::list<Inkscape::SnappedCurve> const &list, Geo bool const c2 = sp.getSnapDistance() < result.getSnapDistance(); // or, if it's just as close then look at the other distance // (only relevant for snapped points which are at an intersection) - bool const c3 = (sp.getSnapDistance() == result.getSnapDistance()) && (sp.getSecondSnapDistance() < result.getSecondSnapDistance()); + bool const c3 = (sp.getSnapDistance() == result.getSnapDistance()) && + (sp.getSecondSnapDistance() < result.getSecondSnapDistance()); // then prefer this point over the previous one if (c1 || c2 || c3) { result = sp; @@ -216,15 +238,18 @@ bool getClosestIntersectionCS(std::list<Inkscape::SnappedCurve> const &list, Geo } // search for the closest intersection of two snapped curves, which are member of two different collections -bool getClosestIntersectionCL(std::list<Inkscape::SnappedCurve> const &curve_list, std::list<Inkscape::SnappedLine> const &line_list, Geom::Point const &p, Inkscape::SnappedPoint &result, Geom::Affine dt2doc) +bool getClosestIntersectionCL(std::list<Inkscape::SnappedCurve> const &curve_list, + std::list<Inkscape::SnappedLine> const &line_list, Geom::Point const &p, + Inkscape::SnappedPoint &result, Geom::Affine dt2doc) { bool success = false; - for (const auto & i : curve_list) { + for (const auto &i : curve_list) { if (i.getTarget() != Inkscape::SNAPTARGET_BBOX_EDGE) { // We don't support snapping to intersections of bboxes, // as this would require two bboxes two be flashed in the snap indicator - for (const auto & j : line_list) { - if (j.getTarget() != Inkscape::SNAPTARGET_BBOX_EDGE) { // We don't support snapping to intersections of bboxes + for (const auto &j : line_list) { + if (j.getTarget() != Inkscape::SNAPTARGET_BBOX_EDGE) { // We don't support snapping to intersections of + // bboxes Inkscape::SnappedPoint sp = i.intersect(j, p, dt2doc); if (sp.getAtIntersection()) { // if it's the first point @@ -233,7 +258,8 @@ bool getClosestIntersectionCL(std::list<Inkscape::SnappedCurve> const &curve_lis bool const c2 = sp.getSnapDistance() < result.getSnapDistance(); // or, if it's just as close then look at the other distance // (only relevant for snapped points which are at an intersection) - bool const c3 = (sp.getSnapDistance() == result.getSnapDistance()) && (sp.getSecondSnapDistance() < result.getSecondSnapDistance()); + bool const c3 = (sp.getSnapDistance() == result.getSnapDistance()) && + (sp.getSecondSnapDistance() < result.getSecondSnapDistance()); // then prefer this point over the previous one if (c1 || c2 || c3) { result = sp; diff --git a/src/snapped-curve.h b/src/snapped-curve.h index bbbfb09d4538e92449e146775140077d0f389897..a14be4b4c825d63afbd0eb264d09287c745f1c1c 100644 --- a/src/snapped-curve.h +++ b/src/snapped-curve.h @@ -13,11 +13,11 @@ */ #include <2geom/forward.h> -#include <vector> #include <list> +#include <vector> -#include "snapped-point.h" #include "snapped-line.h" +#include "snapped-point.h" namespace Inkscape { @@ -26,23 +26,31 @@ class SnappedCurve : public SnappedPoint { public: SnappedCurve(); - SnappedCurve(Geom::Point const &snapped_point, Geom::Point const &tangent, int num_path, int num_segm, Geom::Coord const &snapped_distance, Geom::Coord const &snapped_tolerance, bool const &always_snap, bool const &fully_constrained, Geom::Curve const *curve, SnapSourceType source, long source_num, SnapTargetType target, Geom::OptRect target_bbox); + SnappedCurve(Geom::Point const &snapped_point, Geom::Point const &tangent, int num_path, int num_segm, + Geom::Coord const &snapped_distance, Geom::Coord const &snapped_tolerance, bool const &always_snap, + bool const &fully_constrained, Geom::Curve const *curve, SnapSourceType source, long source_num, + SnapTargetType target, Geom::OptRect target_bbox); ~SnappedCurve(); - Inkscape::SnappedPoint intersect(SnappedCurve const &curve, Geom::Point const &p, Geom::Affine dt2doc) const; //intersect with another SnappedCurve - Inkscape::SnappedPoint intersect(SnappedLine const &line, Geom::Point const &p, Geom::Affine dt2doc) const; //intersect with a SnappedLine + Inkscape::SnappedPoint intersect(SnappedCurve const &curve, Geom::Point const &p, + Geom::Affine dt2doc) const; // intersect with another SnappedCurve + Inkscape::SnappedPoint intersect(SnappedLine const &line, Geom::Point const &p, + Geom::Affine dt2doc) const; // intersect with a SnappedLine private: Geom::Curve const *_curve; - int _num_path; // Unique id of the path to which this segment belongs too - int _num_segm; // Sequence number of this segment in the path + int _num_path; // Unique id of the path to which this segment belongs too + int _num_segm; // Sequence number of this segment in the path }; -} - -bool getClosestCurve(std::list<Inkscape::SnappedCurve> const &list, Inkscape::SnappedCurve &result, bool exclude_paths = false); -bool getClosestIntersectionCS(std::list<Inkscape::SnappedCurve> const &list, Geom::Point const &p, Inkscape::SnappedPoint &result, Geom::Affine dt2doc); -bool getClosestIntersectionCL(std::list<Inkscape::SnappedCurve> const &list1, std::list<Inkscape::SnappedLine> const &list2, Geom::Point const &p, Inkscape::SnappedPoint &result, Geom::Affine dt2doc); +} // namespace Inkscape +bool getClosestCurve(std::list<Inkscape::SnappedCurve> const &list, Inkscape::SnappedCurve &result, + bool exclude_paths = false); +bool getClosestIntersectionCS(std::list<Inkscape::SnappedCurve> const &list, Geom::Point const &p, + Inkscape::SnappedPoint &result, Geom::Affine dt2doc); +bool getClosestIntersectionCL(std::list<Inkscape::SnappedCurve> const &list1, + std::list<Inkscape::SnappedLine> const &list2, Geom::Point const &p, + Inkscape::SnappedPoint &result, Geom::Affine dt2doc); #endif /* !SEEN_SNAPPEDCURVE_H */ diff --git a/src/snapped-line.cpp b/src/snapped-line.cpp index 8ac63edbbdc258d888623be3ee3cf50ddc2a4feb..88583e6e2cdbaacd357d4f3beb5aee7cece361d2 100644 --- a/src/snapped-line.cpp +++ b/src/snapped-line.cpp @@ -11,8 +11,13 @@ #include "snapped-line.h" -Inkscape::SnappedLineSegment::SnappedLineSegment(Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, SnapTargetType const &target, Geom::Coord const &snapped_tolerance, bool const &always_snap, Geom::Point const &start_point_of_line, Geom::Point const &end_point_of_line) - : _start_point_of_line(start_point_of_line), _end_point_of_line(end_point_of_line) +Inkscape::SnappedLineSegment::SnappedLineSegment(Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, + SnapTargetType const &target, Geom::Coord const &snapped_tolerance, + bool const &always_snap, Geom::Point const &start_point_of_line, + Geom::Point const &end_point_of_line) + : _start_point_of_line(start_point_of_line) + , _end_point_of_line(end_point_of_line) { _point = snapped_point; _source = source; @@ -29,7 +34,7 @@ Inkscape::SnappedLineSegment::SnappedLineSegment(Geom::Point const &snapped_poin Inkscape::SnappedLineSegment::SnappedLineSegment() { - _point = Geom::Point(0,0); + _point = Geom::Point(0, 0); _source = SNAPSOURCE_UNDEFINED; _source_num = -1; _target = SNAPTARGET_UNDEFINED; @@ -42,19 +47,14 @@ Inkscape::SnappedLineSegment::SnappedLineSegment() _second_always_snap = false; } - -Inkscape::SnappedLineSegment::~SnappedLineSegment() -= default; +Inkscape::SnappedLineSegment::~SnappedLineSegment() = default; Inkscape::SnappedPoint Inkscape::SnappedLineSegment::intersect(SnappedLineSegment const &line) const { Geom::OptCrossing inters = Geom::OptCrossing(); // empty by default - try - { + try { inters = Geom::intersection(getLineSegment(), line.getLineSegment()); - } - catch (Geom::InfiniteSolutions &e) - { + } catch (Geom::InfiniteSolutions &e) { // We're probably dealing with parallel lines, so they don't really cross inters = Geom::OptCrossing(); } @@ -64,31 +64,37 @@ Inkscape::SnappedPoint Inkscape::SnappedLineSegment::intersect(SnappedLineSegmen /* If a snapper has been told to "always snap", then this one should be preferred * over the other, if that other one has not been told so. (The preferred snapper * will be labeled "primary" below) - */ - bool const c1 = this->getAlwaysSnap() && !line.getAlwaysSnap(); //do not use _tolerance directly! + */ + bool const c1 = this->getAlwaysSnap() && !line.getAlwaysSnap(); // do not use _tolerance directly! /* If neither or both have been told to "always snap", then cast a vote based on * the snapped distance. For this we should consider the distance to the snapped * line, not the distance to the intersection. * See the comment in Inkscape::SnappedLine::intersect - */ + */ bool const c2 = _distance < line.getSnapDistance(); bool const use_this_as_primary = c1 || c2; Inkscape::SnappedLineSegment const *primarySLS = use_this_as_primary ? this : &line; Inkscape::SnappedLineSegment const *secondarySLS = use_this_as_primary ? &line : this; - Geom::Coord primaryDist = use_this_as_primary ? Geom::L2(inters_pt - this->getPoint()) : Geom::L2(inters_pt - line.getPoint()); - Geom::Coord secondaryDist = use_this_as_primary ? Geom::L2(inters_pt - line.getPoint()) : Geom::L2(inters_pt - this->getPoint()); - return SnappedPoint(inters_pt, SNAPSOURCE_UNDEFINED, primarySLS->getSourceNum(), SNAPTARGET_PATH_INTERSECTION, primaryDist, primarySLS->getTolerance(), primarySLS->getAlwaysSnap(), true, false, true, - secondaryDist, secondarySLS->getTolerance(), secondarySLS->getAlwaysSnap()); + Geom::Coord primaryDist = + use_this_as_primary ? Geom::L2(inters_pt - this->getPoint()) : Geom::L2(inters_pt - line.getPoint()); + Geom::Coord secondaryDist = + use_this_as_primary ? Geom::L2(inters_pt - line.getPoint()) : Geom::L2(inters_pt - this->getPoint()); + return SnappedPoint(inters_pt, SNAPSOURCE_UNDEFINED, primarySLS->getSourceNum(), SNAPTARGET_PATH_INTERSECTION, + primaryDist, primarySLS->getTolerance(), primarySLS->getAlwaysSnap(), true, false, true, + secondaryDist, secondarySLS->getTolerance(), secondarySLS->getAlwaysSnap()); } // No intersection - return SnappedPoint(Geom::Point(Geom::infinity(), Geom::infinity()), SNAPSOURCE_UNDEFINED, 0, SNAPTARGET_UNDEFINED, Geom::infinity(), 0, false, false, false, false, Geom::infinity(), 0, false); + return SnappedPoint(Geom::Point(Geom::infinity(), Geom::infinity()), SNAPSOURCE_UNDEFINED, 0, SNAPTARGET_UNDEFINED, + Geom::infinity(), 0, false, false, false, false, Geom::infinity(), 0, false); }; - - -Inkscape::SnappedLine::SnappedLine(Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, SnapTargetType const &target, Geom::Coord const &snapped_tolerance, bool const &always_snap, Geom::Point const &normal_to_line, Geom::Point const &point_on_line) - : _normal_to_line(normal_to_line), _point_on_line(point_on_line) +Inkscape::SnappedLine::SnappedLine(Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, SnapTargetType const &target, + Geom::Coord const &snapped_tolerance, bool const &always_snap, + Geom::Point const &normal_to_line, Geom::Point const &point_on_line) + : _normal_to_line(normal_to_line) + , _point_on_line(point_on_line) { _source = source; _source_num = source_num; @@ -105,8 +111,8 @@ Inkscape::SnappedLine::SnappedLine(Geom::Point const &snapped_point, Geom::Coord Inkscape::SnappedLine::SnappedLine() { - _normal_to_line = Geom::Point(0,0); - _point_on_line = Geom::Point(0,0); + _normal_to_line = Geom::Point(0, 0); + _point_on_line = Geom::Point(0, 0); _source = SNAPSOURCE_UNDEFINED; _source_num = -1; _target = SNAPTARGET_UNDEFINED; @@ -116,12 +122,11 @@ Inkscape::SnappedLine::SnappedLine() _second_distance = Geom::infinity(); _second_tolerance = 1; _second_always_snap = false; - _point = Geom::Point(0,0); + _point = Geom::Point(0, 0); _at_intersection = false; } -Inkscape::SnappedLine::~SnappedLine() -= default; +Inkscape::SnappedLine::~SnappedLine() = default; Inkscape::SnappedPoint Inkscape::SnappedLine::intersect(SnappedLine const &line) const { @@ -130,12 +135,9 @@ Inkscape::SnappedPoint Inkscape::SnappedLine::intersect(SnappedLine const &line) // The point of intersection should be considered for snapping, but might be outside the snapping range Geom::OptCrossing inters = Geom::OptCrossing(); // empty by default - try - { + try { inters = Geom::intersection(getLine(), line.getLine()); - } - catch (Geom::InfiniteSolutions &e) - { + } catch (Geom::InfiniteSolutions &e) { // We're probably dealing with parallel lines, so they don't really cross inters = Geom::OptCrossing(); } @@ -145,7 +147,7 @@ Inkscape::SnappedPoint Inkscape::SnappedLine::intersect(SnappedLine const &line) /* If a snapper has been told to "always snap", then this one should be preferred * over the other, if that other one has not been told so. (The preferred snapper * will be labelled "primary" below) - */ + */ bool const c1 = this->getAlwaysSnap() && !line.getAlwaysSnap(); /* If neither or both have been told to "always snap", then cast a vote based on * the snapped distance. For this we should consider the distance to the snapped @@ -155,16 +157,21 @@ Inkscape::SnappedPoint Inkscape::SnappedLine::intersect(SnappedLine const &line) bool const use_this_as_primary = c1 || c2; Inkscape::SnappedLine const *primarySL = use_this_as_primary ? this : &line; Inkscape::SnappedLine const *secondarySL = use_this_as_primary ? &line : this; - Geom::Coord primaryDist = use_this_as_primary ? Geom::L2(inters_pt - this->getPoint()) : Geom::L2(inters_pt - line.getPoint()); - Geom::Coord secondaryDist = use_this_as_primary ? Geom::L2(inters_pt - line.getPoint()) : Geom::L2(inters_pt - this->getPoint()); - return SnappedPoint(inters_pt, Inkscape::SNAPSOURCE_UNDEFINED, primarySL->getSourceNum(), Inkscape::SNAPTARGET_UNDEFINED, primaryDist, primarySL->getTolerance(), primarySL->getAlwaysSnap(), true, false, true, - secondaryDist, secondarySL->getTolerance(), secondarySL->getAlwaysSnap()); + Geom::Coord primaryDist = + use_this_as_primary ? Geom::L2(inters_pt - this->getPoint()) : Geom::L2(inters_pt - line.getPoint()); + Geom::Coord secondaryDist = + use_this_as_primary ? Geom::L2(inters_pt - line.getPoint()) : Geom::L2(inters_pt - this->getPoint()); + return SnappedPoint(inters_pt, Inkscape::SNAPSOURCE_UNDEFINED, primarySL->getSourceNum(), + Inkscape::SNAPTARGET_UNDEFINED, primaryDist, primarySL->getTolerance(), + primarySL->getAlwaysSnap(), true, false, true, secondaryDist, secondarySL->getTolerance(), + secondarySL->getAlwaysSnap()); // The type of the snap target is yet undefined, as we cannot tell whether // we're snapping to grid or the guide lines; must be set by on a higher level } // No intersection - return SnappedPoint(Geom::Point(Geom::infinity(), Geom::infinity()), SNAPSOURCE_UNDEFINED, 0, SNAPTARGET_UNDEFINED, Geom::infinity(), 0, false, false, false, false, Geom::infinity(), 0, false); + return SnappedPoint(Geom::Point(Geom::infinity(), Geom::infinity()), SNAPSOURCE_UNDEFINED, 0, SNAPTARGET_UNDEFINED, + Geom::infinity(), 0, false, false, false, false, Geom::infinity(), 0, false); } // search for the closest snapped line segment @@ -194,12 +201,13 @@ bool getClosestIntersectionSLS(std::list<Inkscape::SnappedLineSegment> const &li Inkscape::SnappedPoint sp = (*i).intersect(*j); if (sp.getAtIntersection()) { // if it's the first point - bool const c1 = !success; + bool const c1 = !success; // or, if it's closer bool const c2 = sp.getSnapDistance() < result.getSnapDistance(); // or, if it's just then look at the other distance // (only relevant for snapped points which are at an intersection - bool const c3 = (sp.getSnapDistance() == result.getSnapDistance()) && (sp.getSecondSnapDistance() < result.getSecondSnapDistance()); + bool const c3 = (sp.getSnapDistance() == result.getSnapDistance()) && + (sp.getSecondSnapDistance() < result.getSecondSnapDistance()); // then prefer this point over the previous one if (c1 || c2 || c3) { result = sp; @@ -239,12 +247,13 @@ bool getClosestIntersectionSL(std::list<Inkscape::SnappedLine> const &list, Inks Inkscape::SnappedPoint sp = (*i).intersect(*j); if (sp.getAtIntersection()) { // if it's the first point - bool const c1 = !success; + bool const c1 = !success; // or, if it's closer bool const c2 = sp.getSnapDistance() < result.getSnapDistance(); // or, if it's just then look at the other distance // (only relevant for snapped points which are at an intersection - bool const c3 = (sp.getSnapDistance() == result.getSnapDistance()) && (sp.getSecondSnapDistance() < result.getSecondSnapDistance()); + bool const c3 = (sp.getSnapDistance() == result.getSnapDistance()) && + (sp.getSecondSnapDistance() < result.getSecondSnapDistance()); // then prefer this point over the previous one if (c1 || c2 || c3) { result = sp; @@ -258,21 +267,23 @@ bool getClosestIntersectionSL(std::list<Inkscape::SnappedLine> const &list, Inks } // search for the closest intersection of two snapped lines, which are in two different collections -bool getClosestIntersectionSL(std::list<Inkscape::SnappedLine> const &list1, std::list<Inkscape::SnappedLine> const &list2, Inkscape::SnappedPoint &result) +bool getClosestIntersectionSL(std::list<Inkscape::SnappedLine> const &list1, + std::list<Inkscape::SnappedLine> const &list2, Inkscape::SnappedPoint &result) { bool success = false; - for (const auto & i : list1) { - for (const auto & j : list2) { + for (const auto &i : list1) { + for (const auto &j : list2) { Inkscape::SnappedPoint sp = i.intersect(j); if (sp.getAtIntersection()) { // if it's the first point - bool const c1 = !success; + bool const c1 = !success; // or, if it's closer bool const c2 = sp.getSnapDistance() < result.getSnapDistance(); // or, if it's just then look at the other distance // (only relevant for snapped points which are at an intersection - bool const c3 = (sp.getSnapDistance() == result.getSnapDistance()) && (sp.getSecondSnapDistance() < result.getSecondSnapDistance()); + bool const c3 = (sp.getSnapDistance() == result.getSnapDistance()) && + (sp.getSecondSnapDistance() < result.getSecondSnapDistance()); // then prefer this point over the previous one if (c1 || c2 || c3) { result = sp; diff --git a/src/snapped-line.h b/src/snapped-line.h index eda197cfc718365e4b6eec9b96ee9e5d5f9ff32e..e7a40c4e4b240e624c95ef7c045c9ae49312267d 100644 --- a/src/snapped-line.h +++ b/src/snapped-line.h @@ -12,57 +12,61 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <vector> #include <list> +#include <vector> + #include "snapped-point.h" -namespace Inkscape -{ +namespace Inkscape { /// Class describing the result of an attempt to snap to a line segment. class SnappedLineSegment : public SnappedPoint { public: SnappedLineSegment(); - SnappedLineSegment(Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, SnapTargetType const &target, Geom::Coord const &snapped_tolerance,bool const &always_snap, Geom::Point const &start_point_of_line, Geom::Point const &end_point_of_line); + SnappedLineSegment(Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, + SnapSourceType const &source, long source_num, SnapTargetType const &target, + Geom::Coord const &snapped_tolerance, bool const &always_snap, + Geom::Point const &start_point_of_line, Geom::Point const &end_point_of_line); ~SnappedLineSegment(); - Inkscape::SnappedPoint intersect(SnappedLineSegment const &line) const; //intersect with another SnappedLineSegment - Geom::LineSegment getLineSegment() const {return Geom::LineSegment(_start_point_of_line, _end_point_of_line);} + Inkscape::SnappedPoint intersect(SnappedLineSegment const &line) const; // intersect with another SnappedLineSegment + Geom::LineSegment getLineSegment() const { return Geom::LineSegment(_start_point_of_line, _end_point_of_line); } private: Geom::Point _start_point_of_line; Geom::Point _end_point_of_line; }; - /// Class describing the result of an attempt to snap to a line. class SnappedLine : public SnappedPoint { public: SnappedLine(); - SnappedLine(Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, long source_num, SnapTargetType const &target, Geom::Coord const &snapped_tolerance, bool const &always_snap, Geom::Point const &normal_to_line, Geom::Point const &point_on_line); + SnappedLine(Geom::Point const &snapped_point, Geom::Coord const &snapped_distance, SnapSourceType const &source, + long source_num, SnapTargetType const &target, Geom::Coord const &snapped_tolerance, + bool const &always_snap, Geom::Point const &normal_to_line, Geom::Point const &point_on_line); ~SnappedLine(); - Inkscape::SnappedPoint intersect(SnappedLine const &line) const; //intersect with another SnappedLine + Inkscape::SnappedPoint intersect(SnappedLine const &line) const; // intersect with another SnappedLine // This line is described by this equation: // a*x + b*y = c <-> nx*px + ny+py = c <-> n.p = c - Geom::Point getNormal() const {return _normal_to_line;} // n = (nx, ny) - Geom::Point getPointOnLine() const {return _point_on_line;} // p = (px, py) - Geom::Coord getConstTerm() const {return dot(_normal_to_line, _point_on_line);} // c = n.p = nx*px + ny*py; - Geom::Line getLine() const {return Geom::Line(_point_on_line, _point_on_line + Geom::rot90(_normal_to_line));} + Geom::Point getNormal() const { return _normal_to_line; } // n = (nx, ny) + Geom::Point getPointOnLine() const { return _point_on_line; } // p = (px, py) + Geom::Coord getConstTerm() const { return dot(_normal_to_line, _point_on_line); } // c = n.p = nx*px + ny*py; + Geom::Line getLine() const { return Geom::Line(_point_on_line, _point_on_line + Geom::rot90(_normal_to_line)); } private: Geom::Point _normal_to_line; Geom::Point _point_on_line; }; -} +} // namespace Inkscape bool getClosestSLS(std::list<Inkscape::SnappedLineSegment> const &list, Inkscape::SnappedLineSegment &result); bool getClosestIntersectionSLS(std::list<Inkscape::SnappedLineSegment> const &list, Inkscape::SnappedPoint &result); bool getClosestSL(std::list<Inkscape::SnappedLine> const &list, Inkscape::SnappedLine &result); bool getClosestIntersectionSL(std::list<Inkscape::SnappedLine> const &list, Inkscape::SnappedPoint &result); -bool getClosestIntersectionSL(std::list<Inkscape::SnappedLine> const &list1, std::list<Inkscape::SnappedLine> const &list2, Inkscape::SnappedPoint &result); - +bool getClosestIntersectionSL(std::list<Inkscape::SnappedLine> const &list1, + std::list<Inkscape::SnappedLine> const &list2, Inkscape::SnappedPoint &result); #endif /* !SEEN_SNAPPEDLINE_H */ diff --git a/src/snapped-point.cpp b/src/snapped-point.cpp index 6ef67881ab0e75a7ba20852e41f3bacbc9ce93d0..73677c0fbb9eaac3e103e2752820e58817916d5d 100644 --- a/src/snapped-point.cpp +++ b/src/snapped-point.cpp @@ -10,115 +10,123 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <utility> #include "snapped-point.h" + +#include <utility> + #include "preferences.h" // overloaded constructor -Inkscape::SnappedPoint::SnappedPoint(Geom::Point const &p, SnapSourceType const &source, long source_num, SnapTargetType const &target, Geom::Coord const &d, Geom::Coord const &t, bool const &a, bool const &constrained_snap, bool const &fully_constrained, Geom::OptRect target_bbox) : - _point(p), - _tangent(Geom::Point(0,0)), - _source(source), - _source_num(source_num), - _target(target), - _at_intersection (false), - _constrained_snap (constrained_snap), - _fully_constrained (fully_constrained), - _distance(d), - _tolerance(std::max(t,1.0)),// tolerance should never be smaller than 1 px, as it is used for normalization in isOtherSnapBetter. We don't want a division by zero. - _always_snap(a), - _second_distance (Geom::infinity()), - _second_tolerance (1), - _second_always_snap (false), - _target_bbox(std::move(target_bbox)), - _pointer_distance (Geom::infinity()) -{ -} +Inkscape::SnappedPoint::SnappedPoint(Geom::Point const &p, SnapSourceType const &source, long source_num, + SnapTargetType const &target, Geom::Coord const &d, Geom::Coord const &t, + bool const &a, bool const &constrained_snap, bool const &fully_constrained, + Geom::OptRect target_bbox) + : _point(p) + , _tangent(Geom::Point(0, 0)) + , _source(source) + , _source_num(source_num) + , _target(target) + , _at_intersection(false) + , _constrained_snap(constrained_snap) + , _fully_constrained(fully_constrained) + , _distance(d) + , _tolerance(std::max(t, 1.0)) + , // tolerance should never be smaller than 1 px, as it is used for normalization in isOtherSnapBetter. We don't + // want a division by zero. + _always_snap(a) + , _second_distance(Geom::infinity()) + , _second_tolerance(1) + , _second_always_snap(false) + , _target_bbox(std::move(target_bbox)) + , _pointer_distance(Geom::infinity()) +{} -Inkscape::SnappedPoint::SnappedPoint(Inkscape::SnapCandidatePoint const &p, SnapTargetType const &target, Geom::Coord const &d, Geom::Coord const &t, bool const &a, bool const &constrained_snap, bool const &fully_constrained) : - _point (p.getPoint()), - _tangent (Geom::Point(0,0)), - _source (p.getSourceType()), - _source_num (p.getSourceNum()), - _target(target), - _at_intersection (false), - _constrained_snap (constrained_snap), - _fully_constrained (fully_constrained), - _distance(d), - _tolerance(std::max(t,1.0)), - _always_snap(a), - _second_distance (Geom::infinity()), - _second_tolerance (1), - _second_always_snap (false), - _target_bbox (p.getTargetBBox()), - _pointer_distance (Geom::infinity()) -{ -} +Inkscape::SnappedPoint::SnappedPoint(Inkscape::SnapCandidatePoint const &p, SnapTargetType const &target, + Geom::Coord const &d, Geom::Coord const &t, bool const &a, + bool const &constrained_snap, bool const &fully_constrained) + : _point(p.getPoint()) + , _tangent(Geom::Point(0, 0)) + , _source(p.getSourceType()) + , _source_num(p.getSourceNum()) + , _target(target) + , _at_intersection(false) + , _constrained_snap(constrained_snap) + , _fully_constrained(fully_constrained) + , _distance(d) + , _tolerance(std::max(t, 1.0)) + , _always_snap(a) + , _second_distance(Geom::infinity()) + , _second_tolerance(1) + , _second_always_snap(false) + , _target_bbox(p.getTargetBBox()) + , _pointer_distance(Geom::infinity()) +{} -Inkscape::SnappedPoint::SnappedPoint(Geom::Point const &p, SnapSourceType const &source, long source_num, SnapTargetType const &target, Geom::Coord const &d, Geom::Coord const &t, bool const &a, bool const &at_intersection, bool const &constrained_snap, bool const &fully_constrained, Geom::Coord const &d2, Geom::Coord const &t2, bool const &a2) : - _point(p), - _tangent (Geom::Point(0,0)), - _source(source), - _source_num(source_num), - _target(target), - _at_intersection(at_intersection), - _constrained_snap(constrained_snap), - _fully_constrained(fully_constrained), - _distance(d), - _tolerance(std::max(t,1.0)), - _always_snap(a), - _second_distance(d2), - _second_tolerance(std::max(t2,1.0)), - _second_always_snap(a2), +Inkscape::SnappedPoint::SnappedPoint(Geom::Point const &p, SnapSourceType const &source, long source_num, + SnapTargetType const &target, Geom::Coord const &d, Geom::Coord const &t, + bool const &a, bool const &at_intersection, bool const &constrained_snap, + bool const &fully_constrained, Geom::Coord const &d2, Geom::Coord const &t2, + bool const &a2) + : _point(p) + , _tangent(Geom::Point(0, 0)) + , _source(source) + , _source_num(source_num) + , _target(target) + , _at_intersection(at_intersection) + , _constrained_snap(constrained_snap) + , _fully_constrained(fully_constrained) + , _distance(d) + , _tolerance(std::max(t, 1.0)) + , _always_snap(a) + , _second_distance(d2) + , _second_tolerance(std::max(t2, 1.0)) + , _second_always_snap(a2) + , // tolerance should never be smaller than 1 px, as it is used for normalization in // isOtherSnapBetter. We don't want a division by zero. - _target_bbox (Geom::OptRect()), - _pointer_distance (Geom::infinity()) -{ -} + _target_bbox(Geom::OptRect()) + , _pointer_distance(Geom::infinity()) +{} -Inkscape::SnappedPoint::SnappedPoint(): - _point (Geom::Point(0,0)), - _tangent (Geom::Point(0,0)), - _source (SNAPSOURCE_UNDEFINED), - _source_num (-1), - _target (SNAPTARGET_UNDEFINED), - _at_intersection (false), - _constrained_snap (false), - _fully_constrained (false), - _distance (Geom::infinity()), - _tolerance (1), - _always_snap (false), - _second_distance (Geom::infinity()), - _second_tolerance (1), - _second_always_snap (false), - _target_bbox (Geom::OptRect()), - _pointer_distance (Geom::infinity()) -{ -} +Inkscape::SnappedPoint::SnappedPoint() + : _point(Geom::Point(0, 0)) + , _tangent(Geom::Point(0, 0)) + , _source(SNAPSOURCE_UNDEFINED) + , _source_num(-1) + , _target(SNAPTARGET_UNDEFINED) + , _at_intersection(false) + , _constrained_snap(false) + , _fully_constrained(false) + , _distance(Geom::infinity()) + , _tolerance(1) + , _always_snap(false) + , _second_distance(Geom::infinity()) + , _second_tolerance(1) + , _second_always_snap(false) + , _target_bbox(Geom::OptRect()) + , _pointer_distance(Geom::infinity()) +{} -Inkscape::SnappedPoint::SnappedPoint(Geom::Point const &p): - _point (p), - _tangent (Geom::Point(0,0)), - _source (SNAPSOURCE_UNDEFINED), - _source_num (-1), - _target (SNAPTARGET_UNDEFINED), - _at_intersection (false), - _constrained_snap (false), - _fully_constrained (false), - _distance (Geom::infinity()), - _tolerance (1), - _always_snap (false), - _second_distance (Geom::infinity()), - _second_tolerance (1), - _second_always_snap (false), - _target_bbox (Geom::OptRect()), - _pointer_distance (Geom::infinity()) -{ -} +Inkscape::SnappedPoint::SnappedPoint(Geom::Point const &p) + : _point(p) + , _tangent(Geom::Point(0, 0)) + , _source(SNAPSOURCE_UNDEFINED) + , _source_num(-1) + , _target(SNAPTARGET_UNDEFINED) + , _at_intersection(false) + , _constrained_snap(false) + , _fully_constrained(false) + , _distance(Geom::infinity()) + , _tolerance(1) + , _always_snap(false) + , _second_distance(Geom::infinity()) + , _second_tolerance(1) + , _second_always_snap(false) + , _target_bbox(Geom::OptRect()) + , _pointer_distance(Geom::infinity()) +{} -Inkscape::SnappedPoint::~SnappedPoint() -= default; +Inkscape::SnappedPoint::~SnappedPoint() = default; void Inkscape::SnappedPoint::getPointIfSnapped(Geom::Point &p) const { @@ -126,7 +134,7 @@ void Inkscape::SnappedPoint::getPointIfSnapped(Geom::Point &p) const if (getSnapped()) { // then return the snapped point by overwriting p p = _point; - } //otherwise p will be left untouched; this way the caller doesn't have to check whether we've snapped + } // otherwise p will be left untouched; this way the caller doesn't have to check whether we've snapped } // search for the closest snapped point @@ -146,7 +154,6 @@ bool getClosestSP(std::list<Inkscape::SnappedPoint> const &list, Inkscape::Snapp bool Inkscape::SnappedPoint::isOtherSnapBetter(Inkscape::SnappedPoint const &other_one, bool weighted) const { - if (getSnapped() && !other_one.getSnapped()) { return false; } @@ -177,16 +184,17 @@ bool Inkscape::SnappedPoint::isOtherSnapBetter(Inkscape::SnappedPoint const &oth // have that distance set. If not, then this is a bug. Either "weighted" must be set to false, or the // mouse pointer distance must be set. g_assert(dist_pointer_this != Geom::infinity() || dist_pointer_other != Geom::infinity()); - // The snap distance will always be smaller than the tolerance set for the snapper. The pointer distance can - // however be very large. To compare these in a fair way, we will have to normalize these metrics first - // The closest pointer distance will be normalized to 1.0; the other one will be > 1.0 - // The snap distance will be normalized to 1.0 if it's equal to the snapper tolerance + // The snap distance will always be smaller than the tolerance set for the snapper. The pointer distance + // can however be very large. To compare these in a fair way, we will have to normalize these metrics + // first The closest pointer distance will be normalized to 1.0; the other one will be > 1.0 The snap + // distance will be normalized to 1.0 if it's equal to the snapper tolerance double const norm_p = std::min(dist_pointer_this, dist_pointer_other) + 1; - // make sure norm_p is never too close to zero (e.g. when snapping the bbox-corner that was grabbed), by incr. with 1 + // make sure norm_p is never too close to zero (e.g. when snapping the bbox-corner that was grabbed), by + // incr. with 1 double const norm_t_other = std::min(50.0, other_one.getTolerance()); double const norm_t_this = std::min(50.0, getTolerance()); - dist_other = w * dist_pointer_other / norm_p + (1-w) * dist_other / norm_t_other; - dist_this = w * dist_pointer_this / norm_p + (1-w) * dist_this / norm_t_this; + dist_other = w * dist_pointer_other / norm_p + (1 - w) * dist_other / norm_t_other; + dist_this = w * dist_pointer_this / norm_p + (1 - w) * dist_this / norm_t_this; } } } @@ -206,29 +214,36 @@ bool Inkscape::SnappedPoint::isOtherSnapBetter(Inkscape::SnappedPoint const &oth bool c2 = other_one.getAlwaysSnap() && !getAlwaysSnap(); // But in no case fall back from a snapper with "always snap" on to one with "always snap" off bool c2n = !other_one.getAlwaysSnap() && getAlwaysSnap(); - // or, if we have a fully constrained snappoint (e.g. to a node or an intersection), while the previous one was only partly constrained (e.g. to a line) - bool c3 = (other_one.getFullyConstrained() && !other_one.getConstrainedSnap()) && !getFullyConstrained(); // Do not consider constrained snaps here, because these will always be fully constrained anyway + // or, if we have a fully constrained snappoint (e.g. to a node or an intersection), while the previous one was only + // partly constrained (e.g. to a line) + bool c3 = (other_one.getFullyConstrained() && !other_one.getConstrainedSnap()) && + !getFullyConstrained(); // Do not consider constrained snaps here, because these will always be fully + // constrained anyway // But in no case fall back; (has less priority than c3n, so it is allowed to fall back when c3 is true, see below) bool c3n = !other_one.getFullyConstrained() && (getFullyConstrained() && !getConstrainedSnap()); // When both are fully constrained AND coincident, then prefer nodes over intersections - bool d = other_one.getFullyConstrained() && getFullyConstrained() && (Geom::L2(other_one.getPoint() - getPoint()) < 1e-9); + bool d = other_one.getFullyConstrained() && getFullyConstrained() && + (Geom::L2(other_one.getPoint() - getPoint()) < 1e-9); bool c4 = d && !other_one.getAtIntersection() && getAtIntersection(); // But don't fall back... bool c4n = d && other_one.getAtIntersection() && !getAtIntersection(); // or, if it's just as close then consider the second distance ... bool c5a = (dist_other == dist_this); - bool c5b = (other_one.getSecondSnapDistance() < getSecondSnapDistance()) && (getSecondSnapDistance() < Geom::infinity()); + bool c5b = + (other_one.getSecondSnapDistance() < getSecondSnapDistance()) && (getSecondSnapDistance() < Geom::infinity()); // ... or prefer free snaps over constrained snaps bool c5c = !other_one.getConstrainedSnap() && getConstrainedSnap(); bool other_is_better = (c1 || c2 || c3 || c4 || (c5a && (c5b || c5c))) && !c2n && (!c3n || c2) && !c4n; /* - std::cout << other_one.getPoint() << " (Other one, dist = " << dist_other << ") vs. " << getPoint() << " (this one, dist = " << dist_this << ") ---> "; - std::cout << "c1 = " << c1 << " | c2 = " << c2 << " | c2n = " << c2n << " | c3 = " << c3 << " | c3n = " << c3n << " | c4 = " << c4 << " | c4n = " << c4n << " | c5a = " << c5a << " | c5b = " << c5b << " | c5c = " << c5c << std::endl; - std::cout << "Other one provides a better snap: " << other_is_better << std::endl; + std::cout << other_one.getPoint() << " (Other one, dist = " << dist_other << ") vs. " << getPoint() << " (this one, + dist = " << dist_this << ") ---> "; std::cout << "c1 = " << c1 << " | c2 = " << c2 << " | c2n = " << c2n << " | c3 = + " << c3 << " | c3n = " << c3n << " | c4 = " << c4 << " | c4n = " << c4n << " | c5a = " << c5a << " | c5b = " << c5b + << " | c5c = " << c5c << std::endl; std::cout << "Other one provides a better snap: " << other_is_better << + std::endl; */ return other_is_better; diff --git a/src/snapped-point.h b/src/snapped-point.h index 75b5472ccc9bdb7aeb8c0cc27810e84d68ac328d..da56a5762005521ef020a8d45f5fc4c23851f731 100644 --- a/src/snapped-point.h +++ b/src/snapped-point.h @@ -19,31 +19,35 @@ #include "snap-candidate.h" -namespace Inkscape -{ +namespace Inkscape { /// Class describing the result of an attempt to snap. class SnappedPoint { - public: SnappedPoint(); SnappedPoint(Geom::Point const &p); - SnappedPoint(Geom::Point const &p, SnapSourceType const &source, long source_num, SnapTargetType const &target, Geom::Coord const &d, Geom::Coord const &t, bool const &a, bool const &at_intersection, bool const &constrained_snap, bool const &fully_constrained, Geom::Coord const &d2, Geom::Coord const &t2, bool const &a2); - SnappedPoint(Geom::Point const &p, SnapSourceType const &source, long source_num, SnapTargetType const &target, Geom::Coord const &d, Geom::Coord const &t, bool const &a, bool const &constrained_snap, bool const &fully_constrained, Geom::OptRect target_bbox = Geom::OptRect()); - SnappedPoint(SnapCandidatePoint const &p, SnapTargetType const &target, Geom::Coord const &d, Geom::Coord const &t, bool const &a, bool const &constrained_snap, bool const &fully_constrained); + SnappedPoint(Geom::Point const &p, SnapSourceType const &source, long source_num, SnapTargetType const &target, + Geom::Coord const &d, Geom::Coord const &t, bool const &a, bool const &at_intersection, + bool const &constrained_snap, bool const &fully_constrained, Geom::Coord const &d2, + Geom::Coord const &t2, bool const &a2); + SnappedPoint(Geom::Point const &p, SnapSourceType const &source, long source_num, SnapTargetType const &target, + Geom::Coord const &d, Geom::Coord const &t, bool const &a, bool const &constrained_snap, + bool const &fully_constrained, Geom::OptRect target_bbox = Geom::OptRect()); + SnappedPoint(SnapCandidatePoint const &p, SnapTargetType const &target, Geom::Coord const &d, Geom::Coord const &t, + bool const &a, bool const &constrained_snap, bool const &fully_constrained); ~SnappedPoint(); - Geom::Coord getSnapDistance() const {return _distance;} - void setSnapDistance(Geom::Coord const d) {_distance = d;} - Geom::Coord getTolerance() const {return _tolerance;} - bool getAlwaysSnap() const {return _always_snap;} - Geom::Coord getSecondSnapDistance() const {return _second_distance;} - void setSecondSnapDistance(Geom::Coord const d) {_second_distance = d;} - Geom::Coord getSecondTolerance() const {return _second_tolerance;} - bool getSecondAlwaysSnap() const {return _second_always_snap;} - Geom::Coord getPointerDistance() const {return _pointer_distance;} - void setPointerDistance(Geom::Coord const d) {_pointer_distance = d;} + Geom::Coord getSnapDistance() const { return _distance; } + void setSnapDistance(Geom::Coord const d) { _distance = d; } + Geom::Coord getTolerance() const { return _tolerance; } + bool getAlwaysSnap() const { return _always_snap; } + Geom::Coord getSecondSnapDistance() const { return _second_distance; } + void setSecondSnapDistance(Geom::Coord const d) { _second_distance = d; } + Geom::Coord getSecondTolerance() const { return _second_tolerance; } + bool getSecondAlwaysSnap() const { return _second_always_snap; } + Geom::Coord getPointerDistance() const { return _pointer_distance; } + void setPointerDistance(Geom::Coord const d) { _pointer_distance = d; } /* This is the preferred method to find out which point we have snapped * to, because it only returns a point if snapping has actually occurred @@ -59,21 +63,21 @@ public: * constrainedSnap that also enforces projection onto the constraint (in * which case you need the new point anyway, even if we didn't snap) */ - Geom::Point getPoint() const {return _point;} - void setPoint(Geom::Point const &p) {_point = p;} - Geom::Point getTangent() const {return _tangent;} - - bool getAtIntersection() const {return _at_intersection;} - bool getFullyConstrained() const {return _fully_constrained;} - bool getConstrainedSnap() const {return _constrained_snap;} - bool getSnapped() const {return _distance < Geom::infinity();} - void setTarget(SnapTargetType const target) {_target = target;} - SnapTargetType getTarget() const {return _target;} - void setTargetBBox(Geom::OptRect const target) {_target_bbox = target;} - Geom::OptRect const getTargetBBox() const {return _target_bbox;} - void setSource(SnapSourceType const source) {_source = source;} - SnapSourceType getSource() const {return _source;} - long getSourceNum() const {return _source_num;} + Geom::Point getPoint() const { return _point; } + void setPoint(Geom::Point const &p) { _point = p; } + Geom::Point getTangent() const { return _tangent; } + + bool getAtIntersection() const { return _at_intersection; } + bool getFullyConstrained() const { return _fully_constrained; } + bool getConstrainedSnap() const { return _constrained_snap; } + bool getSnapped() const { return _distance < Geom::infinity(); } + void setTarget(SnapTargetType const target) { _target = target; } + SnapTargetType getTarget() const { return _target; } + void setTargetBBox(Geom::OptRect const target) { _target_bbox = target; } + Geom::OptRect const getTargetBBox() const { return _target_bbox; } + void setSource(SnapSourceType const source) { _source = source; } + SnapSourceType getSource() const { return _source; } + long getSourceNum() const { return _source_num; } bool isOtherSnapBetter(SnappedPoint const &other_one, bool weighted) const; @@ -95,15 +99,17 @@ public: }*/ protected: - Geom::Point _point; // Location of the snapped point - Geom::Point _tangent; // Tangent of the curve we snapped to, at the snapped point + Geom::Point _point; // Location of the snapped point + Geom::Point _tangent; // Tangent of the curve we snapped to, at the snapped point SnapSourceType _source; // Describes what snapped - long _source_num; // Sequence number of the source point that snapped, if that point is part of a set of points. (starting at zero if we might have a set of points; -1 if we only have a single point) - SnapTargetType _target; // Describes to what we've snapped to - bool _at_intersection; // If true, the snapped point is at an intersection - bool _constrained_snap; // If true, then the snapped point was found when looking for a constrained snap + long _source_num; // Sequence number of the source point that snapped, if that point is part of a set of points. + // (starting at zero if we might have a set of points; -1 if we only have a single point) + SnapTargetType _target; // Describes to what we've snapped to + bool _at_intersection; // If true, the snapped point is at an intersection + bool _constrained_snap; // If true, then the snapped point was found when looking for a constrained snap bool _fully_constrained; // When snapping for example to a node, then the snap will be "fully constrained". - // When snapping to a line however, the snap is only partly constrained (i.e. only in one dimension) + // When snapping to a line however, the snap is only partly constrained (i.e. only in one + // dimension) /* Distance from original point to snapped point. If the snapped point is at an intersection of e.g. two lines, then this is the distance to the closest @@ -123,11 +129,12 @@ protected: bool _second_always_snap; /* The bounding box we've snapped to (when applicable); will be used by the snapindicator */ Geom::OptRect _target_bbox; - /* Distance from the un-transformed point to the mouse pointer, measured at the point in time when dragging started */ + /* Distance from the un-transformed point to the mouse pointer, measured at the point in time when dragging started + */ Geom::Coord _pointer_distance; }; -}// end of namespace Inkscape +} // end of namespace Inkscape bool getClosestSP(std::list<Inkscape::SnappedPoint> const &list, Inkscape::SnappedPoint &result); diff --git a/src/snapper.cpp b/src/snapper.cpp index f879153a830ea071b9d4489e335126412ba4b120..d9d7c5fe791d8c29b6ca276514bc19314d28fbed 100644 --- a/src/snapper.cpp +++ b/src/snapper.cpp @@ -10,19 +10,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glib.h> // g_assert - #include "snapper.h" +#include <glib.h> // g_assert + /** * Construct new Snapper for named view. * @param nv Named view. * @param d Snap tolerance. */ -Inkscape::Snapper::Snapper(SnapManager *sm, Geom::Coord const /*t*/) : - _snapmanager(sm), - _snap_enabled(true), - _snap_visible_only(true) +Inkscape::Snapper::Snapper(SnapManager *sm, Geom::Coord const /*t*/) + : _snapmanager(sm) + , _snap_enabled(true) + , _snap_visible_only(true) { g_assert(_snapmanager != nullptr); } diff --git a/src/snapper.h b/src/snapper.h index 662d2827f584fa49d569a84bf6f31f90546b9580..5ba9076b5343043245433b5d4917ff9220041ea3 100644 --- a/src/snapper.h +++ b/src/snapper.h @@ -18,11 +18,12 @@ #include <list> #include "snap-candidate.h" -#include "snapped-point.h" -#include "snapped-line.h" #include "snapped-curve.h" +#include "snapped-line.h" +#include "snapped-point.h" -struct IntermSnapResults { +struct IntermSnapResults +{ std::list<Inkscape::SnappedPoint> points; std::list<Inkscape::SnappedLine> grid_lines; std::list<Inkscape::SnappedLine> guide_lines; @@ -32,35 +33,34 @@ struct IntermSnapResults { class SnapManager; class SPItem; -namespace Inkscape -{ +namespace Inkscape { /// Parent for classes that can snap points to something class Snapper { public: - //Snapper() {} //does not seem to be used somewhere + // Snapper() {} //does not seem to be used somewhere Snapper(SnapManager *sm, ::Geom::Coord const t); virtual ~Snapper() = default; - virtual Geom::Coord getSnapperTolerance() const = 0; //returns the tolerance of the snapper in screen pixels (i.e. independent of zoom) - virtual bool getSnapperAlwaysSnap() const = 0; //if true, then the snapper will always snap, regardless of its tolerance + virtual Geom::Coord getSnapperTolerance() const = 0; // returns the tolerance of the snapper in screen pixels (i.e. + // independent of zoom) + virtual bool getSnapperAlwaysSnap() const = 0; // if true, then the snapper will always snap, regardless of its + // tolerance /** - * \return true if this Snapper will snap at least one kind of point. - */ - virtual bool ThisSnapperMightSnap() const {return _snap_enabled;} // will likely be overridden by derived classes + * \return true if this Snapper will snap at least one kind of point. + */ + virtual bool ThisSnapperMightSnap() const { return _snap_enabled; } // will likely be overridden by derived classes // These four methods are only used for grids, for which snapping can be enabled individually void setEnabled(bool s); void setSnapVisibleOnly(bool s); - bool getEnabled() const {return _snap_enabled;} - bool getSnapVisibleOnly() const {return _snap_visible_only;} + bool getEnabled() const { return _snap_enabled; } + bool getSnapVisibleOnly() const { return _snap_visible_only; } - virtual void freeSnap(IntermSnapResults &/*isr*/, - Inkscape::SnapCandidatePoint const &/*p*/, - Geom::OptRect const &/*bbox_to_snap*/, - std::vector<SPItem const *> const */*it*/, - std::vector<SnapCandidatePoint> */*unselected_nodes*/) const {}; + virtual void freeSnap(IntermSnapResults & /*isr*/, Inkscape::SnapCandidatePoint const & /*p*/, + Geom::OptRect const & /*bbox_to_snap*/, std::vector<SPItem const *> const * /*it*/, + std::vector<SnapCandidatePoint> * /*unselected_nodes*/) const {}; // Class for storing the constraint for constrained snapping; can be // - a line (infinite line with origin, running through _point pointing in _direction) @@ -70,33 +70,71 @@ public: class SnapConstraint { private: - enum SnapConstraintType {LINE, DIRECTION, CIRCLE, UNDEFINED}; + enum SnapConstraintType + { + LINE, + DIRECTION, + CIRCLE, + UNDEFINED + }; public: // Constructs a direction constraint, e.g. horizontal or vertical but without a specified point - SnapConstraint(Geom::Point const &d) : _point(), _direction(d), _radius(0), _type(DIRECTION) {} + SnapConstraint(Geom::Point const &d) + : _point() + , _direction(d) + , _radius(0) + , _type(DIRECTION) + {} // Constructs a linear constraint - SnapConstraint(Geom::Point const &p, Geom::Point const &d) : _point(p), _direction(d), _radius(0), _type(LINE) {} + SnapConstraint(Geom::Point const &p, Geom::Point const &d) + : _point(p) + , _direction(d) + , _radius(0) + , _type(LINE) + {} // Orthogonal version - SnapConstraint(Geom::Point const &p, Geom::Dim2 const &d) : _point(p), _direction(), _radius(0), _type(LINE) {_direction[d] = 1.;} - SnapConstraint(Geom::Line const &l) : _point(l.origin()), _direction(l.versor()), _radius(0), _type(LINE) {} + SnapConstraint(Geom::Point const &p, Geom::Dim2 const &d) + : _point(p) + , _direction() + , _radius(0) + , _type(LINE) + { + _direction[d] = 1.; + } + SnapConstraint(Geom::Line const &l) + : _point(l.origin()) + , _direction(l.versor()) + , _radius(0) + , _type(LINE) + {} // Constructs a circular constraint - SnapConstraint(Geom::Point const &p, Geom::Point const &d, Geom::Coord const &r) : _point(p), _direction(d), _radius(r), _type(CIRCLE) {} + SnapConstraint(Geom::Point const &p, Geom::Point const &d, Geom::Coord const &r) + : _point(p) + , _direction(d) + , _radius(r) + , _type(CIRCLE) + {} // Undefined, or empty constraint - SnapConstraint() : _point(), _direction(), _radius(0), _type(UNDEFINED) {} + SnapConstraint() + : _point() + , _direction() + , _radius(0) + , _type(UNDEFINED) + {} - bool hasPoint() const {return _type != DIRECTION && _type != UNDEFINED;} + bool hasPoint() const { return _type != DIRECTION && _type != UNDEFINED; } - Geom::Point getPoint() const { + Geom::Point getPoint() const + { assert(_type != DIRECTION && _type != UNDEFINED); return _point; } - Geom::Point getDirection() const { - return _direction; - } + Geom::Point getDirection() const { return _direction; } - Geom::Coord getRadius() const { + Geom::Coord getRadius() const + { assert(_type == CIRCLE); return _radius; } @@ -106,18 +144,20 @@ public: bool isDirection() const { return _type == DIRECTION; } bool isUndefined() const { return _type == UNDEFINED; } - Geom::Point projection(Geom::Point const &p) const { // returns the projection of p on this constraint + Geom::Point projection(Geom::Point const &p) const + { // returns the projection of p on this constraint if (_type == CIRCLE) { // project on to a circular constraint Geom::Point v_orig = p - _point; Geom::Coord l = Geom::L2(v_orig); if (l > 0) { - return _point + _radius * v_orig/l; // Length of _direction is equal to the radius + return _point + _radius * v_orig / l; // Length of _direction is equal to the radius } else { - // point to be projected is exactly at the center of the circle, so any point on the circle is a projection + // point to be projected is exactly at the center of the circle, so any point on the circle is a + // projection return _point + Geom::Point(_radius, 0); } - } else if (_type != UNDEFINED){ + } else if (_type != UNDEFINED) { // project on to a linear constraint Geom::Point const p1_on_cl = (_type == LINE) ? _point : p; Geom::Point const p2_on_cl = p1_on_cl + _direction; @@ -135,12 +175,10 @@ public: SnapConstraintType _type; }; - virtual void constrainedSnap(IntermSnapResults &/*isr*/, - Inkscape::SnapCandidatePoint const &/*p*/, - Geom::OptRect const &/*bbox_to_snap*/, - SnapConstraint const &/*c*/, - std::vector<SPItem const *> const */*it*/, - std::vector<SnapCandidatePoint> */*unselected_nodes*/) const {}; + virtual void constrainedSnap(IntermSnapResults & /*isr*/, Inkscape::SnapCandidatePoint const & /*p*/, + Geom::OptRect const & /*bbox_to_snap*/, SnapConstraint const & /*c*/, + std::vector<SPItem const *> const * /*it*/, + std::vector<SnapCandidatePoint> * /*unselected_nodes*/) const {}; protected: SnapManager *_snapmanager; @@ -150,7 +188,7 @@ protected: bool _snap_visible_only; }; -} +} // namespace Inkscape #endif /* !SEEN_SNAPPER_H */ diff --git a/src/sp-cursor.cpp b/src/sp-cursor.cpp index dd8a300531a00dd00b59acb3245292639259196b..9079c81e032d69b32095d1f73561965a054b4a88 100644 --- a/src/sp-cursor.cpp +++ b/src/sp-cursor.cpp @@ -17,40 +17,44 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-cursor.h" + #include <cstring> #include <gdk/gdk.h> #include <map> #include <sstream> #include "color.h" -#include "sp-cursor.h" -static void free_cursor_data(unsigned char *pixels, void* /*data*/) { - delete [] reinterpret_cast<guint32*>(pixels); +static void free_cursor_data(unsigned char *pixels, void * /*data*/) +{ + delete[] reinterpret_cast<guint32 *>(pixels); } -struct RGBA { +struct RGBA +{ guchar v[4]; - RGBA() { + RGBA() + { v[0] = 0; v[1] = 0; v[2] = 0; v[3] = 0; } - RGBA(guchar r, guchar g, guchar b, guchar a) { + RGBA(guchar r, guchar g, guchar b, guchar a) + { v[0] = r; v[1] = g; v[2] = b; v[3] = a; } - operator guint32() const { - guint32 result = (static_cast<guint32>(v[0]) << 0) - | (static_cast<guint32>(v[1]) << 8) - | (static_cast<guint32>(v[2]) << 16) - | (static_cast<guint32>(v[3]) << 24); + operator guint32() const + { + guint32 result = (static_cast<guint32>(v[0]) << 0) | (static_cast<guint32>(v[1]) << 8) | + (static_cast<guint32>(v[2]) << 16) | (static_cast<guint32>(v[3]) << 24); return result; } }; @@ -67,7 +71,7 @@ GdkCursor *sp_cursor_from_xpm(char const *const *xpm, guint32 fill, guint32 stro int pix = 0; int hot_x = 0; int hot_y = 0; - std::stringstream ss (std::stringstream::in | std::stringstream::out); + std::stringstream ss(std::stringstream::in | std::stringstream::out); ss << xpm[0]; ss >> height; ss >> width; @@ -75,15 +79,14 @@ GdkCursor *sp_cursor_from_xpm(char const *const *xpm, guint32 fill, guint32 stro ss >> pix; ss >> hot_x; ss >> hot_y; - + if (gdk_display_supports_cursor_alpha(display) && gdk_display_supports_cursor_color(display)) { std::map<char, RGBA> colorMap; for (int i = 0; i < colors; i++) { - char const *p = xpm[1 + i]; - g_assert(*p >=0); - unsigned char const ccode = (guchar) *p; + g_assert(*p >= 0); + unsigned char const ccode = (guchar)*p; p++; while (isspace(*p)) { @@ -95,9 +98,11 @@ GdkCursor *sp_cursor_from_xpm(char const *const *xpm, guint32 fill, guint32 stro } if (strcmp(p, "Fill") == 0) { - colorMap[ccode] = RGBA(SP_RGBA32_R_U(fill), SP_RGBA32_G_U(fill), SP_RGBA32_B_U(fill), SP_RGBA32_A_U(fill)); + colorMap[ccode] = + RGBA(SP_RGBA32_R_U(fill), SP_RGBA32_G_U(fill), SP_RGBA32_B_U(fill), SP_RGBA32_A_U(fill)); } else if (strcmp(p, "Stroke") == 0) { - colorMap[ccode] = RGBA(SP_RGBA32_R_U(stroke), SP_RGBA32_G_U(stroke), SP_RGBA32_B_U(stroke), SP_RGBA32_A_U(stroke)); + colorMap[ccode] = + RGBA(SP_RGBA32_R_U(stroke), SP_RGBA32_G_U(stroke), SP_RGBA32_B_U(stroke), SP_RGBA32_A_U(stroke)); } else if (p[0] == '#') { GdkRGBA color; if (gdk_rgba_parse(&color, p)) { @@ -122,17 +127,19 @@ GdkCursor *sp_cursor_from_xpm(char const *const *xpm, guint32 fill, guint32 stro #if G_BYTE_ORDER == G_BIG_ENDIAN for (int i = 0, n = width * height; i < n; i++) { guint32 v = pixmap_buffer[i]; - pixmap_buffer[i] = ((v & 0xFF) << 24) | (((v >> 8) & 0xFF) << 16) | (((v >> 16) & 0xFF) << 8) | ((v >> 24) & 0xFF); + pixmap_buffer[i] = + ((v & 0xFF) << 24) | (((v >> 8) & 0xFF) << 16) | (((v >> 16) & 0xFF) << 8) | ((v >> 24) & 0xFF); } #endif - pixbuf = gdk_pixbuf_new_from_data(reinterpret_cast<guchar*>(pixmap_buffer), GDK_COLORSPACE_RGB, TRUE, 8, width, height, width * sizeof(guint32), free_cursor_data, nullptr); + pixbuf = gdk_pixbuf_new_from_data(reinterpret_cast<guchar *>(pixmap_buffer), GDK_COLORSPACE_RGB, TRUE, 8, width, + height, width * sizeof(guint32), free_cursor_data, nullptr); } else { - pixbuf = gdk_pixbuf_new_from_xpm_data((const gchar **)xpm); + pixbuf = gdk_pixbuf_new_from_xpm_data((const gchar **)xpm); } if (pixbuf != nullptr) { - cursor = gdk_cursor_new_from_pixbuf(display, pixbuf, hot_x, hot_y); + cursor = gdk_cursor_new_from_pixbuf(display, pixbuf, hot_x, hot_y); g_object_unref(pixbuf); } else { g_warning("Failed to load cursor from xpm!"); diff --git a/src/sp-cursor.h b/src/sp-cursor.h index 5dbf441cee1061acbfb771bb5ee8f85681ced23b..0c2f5646d61cee61733e1ba725843b48a2cb4e64 100644 --- a/src/sp-cursor.h +++ b/src/sp-cursor.h @@ -13,7 +13,7 @@ typedef unsigned int guint32; typedef struct _GdkCursor GdkCursor; -GdkCursor* sp_cursor_from_xpm(char const *const *xpm, guint32 fill=0, guint32 stroke=0); +GdkCursor *sp_cursor_from_xpm(char const *const *xpm, guint32 fill = 0, guint32 stroke = 0); #endif diff --git a/src/sp-guide-attachment.h b/src/sp-guide-attachment.h index 05d43a270aa25f373f2b6f0e15c434fd1a3e2c60..024ff9eab1ff59d3be18341e1e2dee3ba9d9e641 100644 --- a/src/sp-guide-attachment.h +++ b/src/sp-guide-attachment.h @@ -12,30 +12,26 @@ #include "object/sp-item.h" -class SPGuideAttachment { +class SPGuideAttachment +{ public: SPItem *item; int snappoint_ix; public: - SPGuideAttachment() : - item(static_cast<SPItem *>(nullptr)), - snappoint_ix(0) - { } - - SPGuideAttachment(SPItem *i, int s) : - item(i), - snappoint_ix(s) - { } - - bool operator==(SPGuideAttachment const &o) const { - return ( ( item == o.item ) - && ( snappoint_ix == o.snappoint_ix ) ); - } - - bool operator!=(SPGuideAttachment const &o) const { - return !(*this == o); - } + SPGuideAttachment() + : item(static_cast<SPItem *>(nullptr)) + , snappoint_ix(0) + {} + + SPGuideAttachment(SPItem *i, int s) + : item(i) + , snappoint_ix(s) + {} + + bool operator==(SPGuideAttachment const &o) const { return ((item == o.item) && (snappoint_ix == o.snappoint_ix)); } + + bool operator!=(SPGuideAttachment const &o) const { return !(*this == o); } }; #endif // SEEN_SP_GUIDE_ATTACHMENT_H diff --git a/src/sp-guide-constraint.h b/src/sp-guide-constraint.h index 578f392fb7ca9724885fad824729a13c88171319..104a02d8b6fc32b53228b9c24dc7535f85716b0d 100644 --- a/src/sp-guide-constraint.h +++ b/src/sp-guide-constraint.h @@ -12,30 +12,26 @@ class SPGuide; -class SPGuideConstraint { +class SPGuideConstraint +{ public: SPGuide *g; int snappoint_ix; public: - explicit SPGuideConstraint() : - g(static_cast<SPGuide *>(nullptr)), - snappoint_ix(0) - { } - - explicit SPGuideConstraint(SPGuide *g, int snappoint_ix) : - g(g), - snappoint_ix(snappoint_ix) - { } - - bool operator==(SPGuideConstraint const &o) const { - return ( ( g == o.g ) - && ( snappoint_ix == o.snappoint_ix ) ); - } - - bool operator!=(SPGuideConstraint const &o) const { - return !( *this == o ); - } + explicit SPGuideConstraint() + : g(static_cast<SPGuide *>(nullptr)) + , snappoint_ix(0) + {} + + explicit SPGuideConstraint(SPGuide *g, int snappoint_ix) + : g(g) + , snappoint_ix(snappoint_ix) + {} + + bool operator==(SPGuideConstraint const &o) const { return ((g == o.g) && (snappoint_ix == o.snappoint_ix)); } + + bool operator!=(SPGuideConstraint const &o) const { return !(*this == o); } }; #endif // SEEN_SP_GUIDE_CONSTRAINT_H diff --git a/src/sp-item-notify-moveto.cpp b/src/sp-item-notify-moveto.cpp index 57e44f45aac8f61f0ad26ec846f7fcb426c309f5..6962653a9e041c5d5d37611bff273ad11102de19 100644 --- a/src/sp-item-notify-moveto.cpp +++ b/src/sp-item-notify-moveto.cpp @@ -11,16 +11,20 @@ * Implementation of sp_item_notify_moveto(). */ +#include "sp-item-notify-moveto.h" + #include <2geom/transforms.h> #include <vector> -#include "sp-item-notify-moveto.h" - #include "object/sp-guide.h" -#include "object/sp-item.h" #include "object/sp-item-rm-unsatisfied-cns.h" +#include "object/sp-item.h" -#define return_if_fail(test) if (!(test)) { printf("WARNING: assertion '%s' failed", #test); return; } +#define return_if_fail(test) \ + if (!(test)) { \ + printf("WARNING: assertion '%s' failed", #test); \ + return; \ + } /** * Called by sp_guide_moveto to indicate that the guide line corresponding to g has been moved, and @@ -28,18 +32,18 @@ * * \pre exist [cn in item.constraints] g eq cn.g. */ -void sp_item_notify_moveto(SPItem &item, SPGuide const &mv_g, int const snappoint_ix, - double const position, bool const commit) +void sp_item_notify_moveto(SPItem &item, SPGuide const &mv_g, int const snappoint_ix, double const position, + bool const commit) { return_if_fail(SP_IS_ITEM(&item)); - return_if_fail( unsigned(snappoint_ix) < 8 ); - Geom::Point const dir( mv_g.getNormal() ); + return_if_fail(unsigned(snappoint_ix) < 8); + Geom::Point const dir(mv_g.getNormal()); double const dir_lensq(dot(dir, dir)); - return_if_fail( dir_lensq != 0 ); + return_if_fail(dir_lensq != 0); std::vector<Inkscape::SnapCandidatePoint> snappoints; item.getSnappoints(snappoints, nullptr); - return_if_fail( snappoint_ix < int(snappoints.size()) ); + return_if_fail(snappoint_ix < int(snappoints.size())); double const pos0 = dot(dir, snappoints[snappoint_ix].getPoint()); /// \todo effic: skip if mv_g is already satisfied. @@ -52,8 +56,7 @@ void sp_item_notify_moveto(SPItem &item, SPGuide const &mv_g, int const snappoin pos0 + s * dot(dir, dir) = position. s * lensq(dir) = position - pos0. s = (position - pos0) / dot(dir, dir). */ - Geom::Translate const tr( ( position - pos0 ) - * ( dir / dir_lensq ) ); + Geom::Translate const tr((position - pos0) * (dir / dir_lensq)); item.set_i2d_affine(item.i2dt_affine() * tr); /// \todo Reget snappoints, check satisfied. @@ -76,7 +79,6 @@ void sp_item_notify_moveto(SPItem &item, SPGuide const &mv_g, int const snappoin } } - /* Local Variables: mode:c++ diff --git a/src/sp-item-notify-moveto.h b/src/sp-item-notify-moveto.h index d256f39e8eb34c3d186509f6e5bda29767ffe960..afb65573a50fb5be9ace28d3146f7a2775fec587 100644 --- a/src/sp-item-notify-moveto.h +++ b/src/sp-item-notify-moveto.h @@ -13,13 +13,10 @@ class SPItem; class SPGuide; -void sp_item_notify_moveto(SPItem &item, SPGuide const &g, int const snappoint_ix, - double position, bool const commit); - +void sp_item_notify_moveto(SPItem &item, SPGuide const &g, int const snappoint_ix, double position, bool const commit); #endif // SEEN_SP_ITEM_NOTIFY_MOVETO_H - /* Local Variables: mode:c++ diff --git a/src/streq.h b/src/streq.h index 0ffd83d4eb0436967e2766e7dad4bffbd49a8cc0..2e04d733fb65b4178eaa9fb056a123afd8e40b46 100644 --- a/src/streq.h +++ b/src/streq.h @@ -13,17 +13,14 @@ #include <cstring> /** Convenience/readability wrapper for strcmp(a,b)==0. */ -inline bool -streq(char const *a, char const *b) +inline bool streq(char const *a, char const *b) { return std::strcmp(a, b) == 0; } -struct streq_rel { - bool operator()(char const *a, char const *b) const - { - return (std::strcmp(a, b) == 0); - } +struct streq_rel +{ + bool operator()(char const *a, char const *b) const { return (std::strcmp(a, b) == 0); } }; #endif /* !INKSCAPE_STREQ_H */ diff --git a/src/strneq.h b/src/strneq.h index 1f153d2d273a263ae1c0446e703ada2c92c57174..c9c866fc44777a48de11c9013c1b26fb4dcf006e 100644 --- a/src/strneq.h +++ b/src/strneq.h @@ -13,13 +13,11 @@ #include <cstring> /** Convenience/readability wrapper for strncmp(a,b,n)==0. */ -inline bool -strneq(char const *a, char const *b, size_t n) +inline bool strneq(char const *a, char const *b, size_t n) { return std::strncmp(a, b, n) == 0; } - #endif /* !INKSCAPE_STRNEQ_H */ /* diff --git a/src/style-enums.h b/src/style-enums.h index 669ed6e6a0e9ee97782d7a9b4e9d04279ad784df..a3026412f52617f51c46d4415d0347b7ed9f954e 100644 --- a/src/style-enums.h +++ b/src/style-enums.h @@ -20,32 +20,33 @@ /* fill-rule */ /* clip-rule */ -enum SPWindRule : std::uint_least8_t { +enum SPWindRule : std::uint_least8_t +{ SP_WIND_RULE_NONZERO, SP_WIND_RULE_INTERSECT, SP_WIND_RULE_EVENODD, SP_WIND_RULE_POSITIVE }; - - /* stroke-linejoin */ -enum SPStrokeJoinType : std::uint_least8_t { +enum SPStrokeJoinType : std::uint_least8_t +{ SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINEJOIN_ROUND, SP_STROKE_LINEJOIN_BEVEL }; /* stroke-linecap */ -enum SPStrokeCapType : std::uint_least8_t { +enum SPStrokeCapType : std::uint_least8_t +{ SP_STROKE_LINECAP_BUTT, SP_STROKE_LINECAP_ROUND, SP_STROKE_LINECAP_SQUARE }; - /* SPFontStyle */ -enum SPCSSFontSize : std::int_least8_t { +enum SPCSSFontSize : std::int_least8_t +{ SP_CSS_FONT_SIZE_XX_SMALL, SP_CSS_FONT_SIZE_X_SMALL, SP_CSS_FONT_SIZE_SMALL, @@ -57,18 +58,21 @@ enum SPCSSFontSize : std::int_least8_t { SP_CSS_FONT_SIZE_LARGER }; -enum SPCSSFontStyle : std::uint_least8_t { +enum SPCSSFontStyle : std::uint_least8_t +{ SP_CSS_FONT_STYLE_NORMAL, SP_CSS_FONT_STYLE_ITALIC, SP_CSS_FONT_STYLE_OBLIQUE }; -enum SPCSSFontVariant : std::uint_least8_t { +enum SPCSSFontVariant : std::uint_least8_t +{ SP_CSS_FONT_VARIANT_NORMAL, SP_CSS_FONT_VARIANT_SMALL_CAPS }; -enum SPCSSFontWeight : std::int_least8_t { +enum SPCSSFontWeight : std::int_least8_t +{ SP_CSS_FONT_WEIGHT_100, SP_CSS_FONT_WEIGHT_200, SP_CSS_FONT_WEIGHT_300, @@ -84,7 +88,8 @@ enum SPCSSFontWeight : std::int_least8_t { SP_CSS_FONT_WEIGHT_BOLDER }; -enum SPCSSFontStretch : std::int_least8_t { +enum SPCSSFontStretch : std::int_least8_t +{ SP_CSS_FONT_STRETCH_ULTRA_CONDENSED, SP_CSS_FONT_STRETCH_EXTRA_CONDENSED, SP_CSS_FONT_STRETCH_CONDENSED, @@ -99,50 +104,55 @@ enum SPCSSFontStretch : std::int_least8_t { }; // Can select more than one -enum SPCSSFontVariantLigatures : std::uint_least8_t { - SP_CSS_FONT_VARIANT_LIGATURES_NONE = 0, - SP_CSS_FONT_VARIANT_LIGATURES_COMMON = 1, - SP_CSS_FONT_VARIANT_LIGATURES_DISCRETIONARY = 2, - SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL = 4, - SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL = 8, - SP_CSS_FONT_VARIANT_LIGATURES_NORMAL = 9, // Special case - SP_CSS_FONT_VARIANT_LIGATURES_NOCOMMON = 16, +enum SPCSSFontVariantLigatures : std::uint_least8_t +{ + SP_CSS_FONT_VARIANT_LIGATURES_NONE = 0, + SP_CSS_FONT_VARIANT_LIGATURES_COMMON = 1, + SP_CSS_FONT_VARIANT_LIGATURES_DISCRETIONARY = 2, + SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL = 4, + SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL = 8, + SP_CSS_FONT_VARIANT_LIGATURES_NORMAL = 9, // Special case + SP_CSS_FONT_VARIANT_LIGATURES_NOCOMMON = 16, SP_CSS_FONT_VARIANT_LIGATURES_NODISCRETIONARY = 32, - SP_CSS_FONT_VARIANT_LIGATURES_NOHISTORICAL = 64, - SP_CSS_FONT_VARIANT_LIGATURES_NOCONTEXTUAL = 128 + SP_CSS_FONT_VARIANT_LIGATURES_NOHISTORICAL = 64, + SP_CSS_FONT_VARIANT_LIGATURES_NOCONTEXTUAL = 128 }; -enum SPCSSFontVariantPosition : std::uint_least8_t { +enum SPCSSFontVariantPosition : std::uint_least8_t +{ SP_CSS_FONT_VARIANT_POSITION_NORMAL = 1, - SP_CSS_FONT_VARIANT_POSITION_SUB = 2, - SP_CSS_FONT_VARIANT_POSITION_SUPER = 4 + SP_CSS_FONT_VARIANT_POSITION_SUB = 2, + SP_CSS_FONT_VARIANT_POSITION_SUPER = 4 }; -enum SPCSSFontVariantCaps : std::uint_least8_t { - SP_CSS_FONT_VARIANT_CAPS_NORMAL = 1, - SP_CSS_FONT_VARIANT_CAPS_SMALL = 2, - SP_CSS_FONT_VARIANT_CAPS_ALL_SMALL = 4, - SP_CSS_FONT_VARIANT_CAPS_PETITE = 8, - SP_CSS_FONT_VARIANT_CAPS_ALL_PETITE = 16, - SP_CSS_FONT_VARIANT_CAPS_UNICASE = 32, - SP_CSS_FONT_VARIANT_CAPS_TITLING = 64 +enum SPCSSFontVariantCaps : std::uint_least8_t +{ + SP_CSS_FONT_VARIANT_CAPS_NORMAL = 1, + SP_CSS_FONT_VARIANT_CAPS_SMALL = 2, + SP_CSS_FONT_VARIANT_CAPS_ALL_SMALL = 4, + SP_CSS_FONT_VARIANT_CAPS_PETITE = 8, + SP_CSS_FONT_VARIANT_CAPS_ALL_PETITE = 16, + SP_CSS_FONT_VARIANT_CAPS_UNICASE = 32, + SP_CSS_FONT_VARIANT_CAPS_TITLING = 64 }; // Can select more than one (see spec) -enum SPCSSFontVariantNumeric : std::uint_least8_t { - SP_CSS_FONT_VARIANT_NUMERIC_NORMAL = 0, - SP_CSS_FONT_VARIANT_NUMERIC_LINING_NUMS = 1, - SP_CSS_FONT_VARIANT_NUMERIC_OLDSTYLE_NUMS = 2, - SP_CSS_FONT_VARIANT_NUMERIC_PROPORTIONAL_NUMS = 4, - SP_CSS_FONT_VARIANT_NUMERIC_TABULAR_NUMS = 8, - SP_CSS_FONT_VARIANT_NUMERIC_DIAGONAL_FRACTIONS = 16, - SP_CSS_FONT_VARIANT_NUMERIC_STACKED_FRACTIONS = 32, - SP_CSS_FONT_VARIANT_NUMERIC_ORDINAL = 64, - SP_CSS_FONT_VARIANT_NUMERIC_SLASHED_ZERO = 128 +enum SPCSSFontVariantNumeric : std::uint_least8_t +{ + SP_CSS_FONT_VARIANT_NUMERIC_NORMAL = 0, + SP_CSS_FONT_VARIANT_NUMERIC_LINING_NUMS = 1, + SP_CSS_FONT_VARIANT_NUMERIC_OLDSTYLE_NUMS = 2, + SP_CSS_FONT_VARIANT_NUMERIC_PROPORTIONAL_NUMS = 4, + SP_CSS_FONT_VARIANT_NUMERIC_TABULAR_NUMS = 8, + SP_CSS_FONT_VARIANT_NUMERIC_DIAGONAL_FRACTIONS = 16, + SP_CSS_FONT_VARIANT_NUMERIC_STACKED_FRACTIONS = 32, + SP_CSS_FONT_VARIANT_NUMERIC_ORDINAL = 64, + SP_CSS_FONT_VARIANT_NUMERIC_SLASHED_ZERO = 128 }; // Quite complicated... (see spec) -enum SPCSSFontVariantAlternates : std::uint_least8_t { +enum SPCSSFontVariantAlternates : std::uint_least8_t +{ SP_CSS_FONT_VARIANT_ALTERNATES_NORMAL, SP_CSS_FONT_VARIANT_ALTERNATES_HISTORICAL_FORMS, SP_CSS_FONT_VARIANT_ALTERNATES_STYLISTIC, @@ -154,20 +164,22 @@ enum SPCSSFontVariantAlternates : std::uint_least8_t { }; // Can select more than one (see spec) -enum SPCSSFontVariantEastAsian : std::uint_least16_t { - SP_CSS_FONT_VARIANT_EAST_ASIAN_NORMAL = 0, - SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS78 = 1, - SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS83 = 2, - SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS90 = 4, - SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS04 = 8, - SP_CSS_FONT_VARIANT_EAST_ASIAN_SIMPLIFIED = 16, - SP_CSS_FONT_VARIANT_EAST_ASIAN_TRADITIONAL = 32, - SP_CSS_FONT_VARIANT_EAST_ASIAN_FULL_WIDTH = 64, - SP_CSS_FONT_VARIANT_EAST_ASIAN_PROPORTIONAL_WIDTH = 128, - SP_CSS_FONT_VARIANT_EAST_ASIAN_RUBY = 256 -}; - -enum SPCSSTextAlign : std::uint_least8_t { +enum SPCSSFontVariantEastAsian : std::uint_least16_t +{ + SP_CSS_FONT_VARIANT_EAST_ASIAN_NORMAL = 0, + SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS78 = 1, + SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS83 = 2, + SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS90 = 4, + SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS04 = 8, + SP_CSS_FONT_VARIANT_EAST_ASIAN_SIMPLIFIED = 16, + SP_CSS_FONT_VARIANT_EAST_ASIAN_TRADITIONAL = 32, + SP_CSS_FONT_VARIANT_EAST_ASIAN_FULL_WIDTH = 64, + SP_CSS_FONT_VARIANT_EAST_ASIAN_PROPORTIONAL_WIDTH = 128, + SP_CSS_FONT_VARIANT_EAST_ASIAN_RUBY = 256 +}; + +enum SPCSSTextAlign : std::uint_least8_t +{ SP_CSS_TEXT_ALIGN_START, SP_CSS_TEXT_ALIGN_END, SP_CSS_TEXT_ALIGN_LEFT, @@ -177,19 +189,22 @@ enum SPCSSTextAlign : std::uint_least8_t { // also <string> is allowed, but only within table calls }; -enum SPCSSTextTransform : std::uint_least8_t { +enum SPCSSTextTransform : std::uint_least8_t +{ SP_CSS_TEXT_TRANSFORM_CAPITALIZE, SP_CSS_TEXT_TRANSFORM_UPPERCASE, SP_CSS_TEXT_TRANSFORM_LOWERCASE, SP_CSS_TEXT_TRANSFORM_NONE }; -enum SPCSSDirection : std::uint_least8_t { +enum SPCSSDirection : std::uint_least8_t +{ SP_CSS_DIRECTION_LTR, SP_CSS_DIRECTION_RTL }; -enum SPCSSWritingMode : std::uint_least8_t { +enum SPCSSWritingMode : std::uint_least8_t +{ SP_CSS_WRITING_MODE_LR_TB, SP_CSS_WRITING_MODE_RL_TB, SP_CSS_WRITING_MODE_TB_RL, @@ -197,19 +212,22 @@ enum SPCSSWritingMode : std::uint_least8_t { }; // CSS WRITING MODES 3 -enum SPCSSTextOrientation : std::uint_least8_t { +enum SPCSSTextOrientation : std::uint_least8_t +{ SP_CSS_TEXT_ORIENTATION_MIXED, SP_CSS_TEXT_ORIENTATION_UPRIGHT, SP_CSS_TEXT_ORIENTATION_SIDEWAYS }; -enum SPTextAnchor : std::uint_least8_t { +enum SPTextAnchor : std::uint_least8_t +{ SP_CSS_TEXT_ANCHOR_START, SP_CSS_TEXT_ANCHOR_MIDDLE, SP_CSS_TEXT_ANCHOR_END }; -enum SPWhiteSpace : std::uint_least8_t { +enum SPWhiteSpace : std::uint_least8_t +{ SP_CSS_WHITE_SPACE_NORMAL, SP_CSS_WHITE_SPACE_PRE, SP_CSS_WHITE_SPACE_NOWRAP, @@ -218,7 +236,8 @@ enum SPWhiteSpace : std::uint_least8_t { }; // Not complete list -enum SPCSSBaseline : std::uint_least8_t { +enum SPCSSBaseline : std::uint_least8_t +{ SP_CSS_BASELINE_AUTO, SP_CSS_BASELINE_ALPHABETIC, SP_CSS_BASELINE_IDEOGRAPHIC, @@ -228,22 +247,25 @@ enum SPCSSBaseline : std::uint_least8_t { SP_CSS_BASELINE_MIDDLE, SP_CSS_BASELINE_TEXT_BEFORE_EDGE, SP_CSS_BASELINE_TEXT_AFTER_EDGE, - SP_CSS_BASELINE_SIZE // Size of enum, keep last. + SP_CSS_BASELINE_SIZE // Size of enum, keep last. }; - -enum SPCSSBaselineShift : std::uint_least8_t { + +enum SPCSSBaselineShift : std::uint_least8_t +{ SP_CSS_BASELINE_SHIFT_BASELINE, SP_CSS_BASELINE_SHIFT_SUB, SP_CSS_BASELINE_SHIFT_SUPER }; -enum SPVisibility : std::uint_least8_t { +enum SPVisibility : std::uint_least8_t +{ SP_CSS_VISIBILITY_HIDDEN, SP_CSS_VISIBILITY_COLLAPSE, SP_CSS_VISIBILITY_VISIBLE }; -enum SPOverflow : std::uint_least8_t { +enum SPOverflow : std::uint_least8_t +{ SP_CSS_OVERFLOW_VISIBLE, SP_CSS_OVERFLOW_HIDDEN, SP_CSS_OVERFLOW_SCROLL, @@ -251,7 +273,8 @@ enum SPOverflow : std::uint_least8_t { }; /// \todo more display types -enum SPCSSDisplay : std::uint_least8_t { +enum SPCSSDisplay : std::uint_least8_t +{ SP_CSS_DISPLAY_NONE, SP_CSS_DISPLAY_INLINE, SP_CSS_DISPLAY_BLOCK, @@ -271,12 +294,14 @@ enum SPCSSDisplay : std::uint_least8_t { SP_CSS_DISPLAY_TABLE_CAPTION }; -enum SPIsolation : std::uint_least8_t { +enum SPIsolation : std::uint_least8_t +{ SP_CSS_ISOLATION_AUTO, SP_CSS_ISOLATION_ISOLATE }; -enum SPBlendMode : std::uint_least8_t { +enum SPBlendMode : std::uint_least8_t +{ SP_CSS_BLEND_NORMAL, SP_CSS_BLEND_MULTIPLY, SP_CSS_BLEND_SCREEN, @@ -296,25 +321,29 @@ enum SPBlendMode : std::uint_least8_t { SP_CSS_BLEND_ENDMODE }; -enum SPEnableBackground : std::uint_least8_t { +enum SPEnableBackground : std::uint_least8_t +{ SP_CSS_BACKGROUND_ACCUMULATE, SP_CSS_BACKGROUND_NEW }; -enum SPColorInterpolation : std::uint_least8_t { +enum SPColorInterpolation : std::uint_least8_t +{ SP_CSS_COLOR_INTERPOLATION_AUTO, SP_CSS_COLOR_INTERPOLATION_SRGB, SP_CSS_COLOR_INTERPOLATION_LINEARRGB }; -enum SPColorRendering : std::uint_least8_t { +enum SPColorRendering : std::uint_least8_t +{ SP_CSS_COLOR_RENDERING_AUTO, SP_CSS_COLOR_RENDERING_OPTIMIZESPEED, SP_CSS_COLOR_RENDERING_OPTIMIZEQUALITY }; /* Last two are CSS4 Image values... for the momement prefaced with -inkscape. */ -enum SPImageRendering : std::uint_least8_t { +enum SPImageRendering : std::uint_least8_t +{ SP_CSS_IMAGE_RENDERING_AUTO, SP_CSS_IMAGE_RENDERING_OPTIMIZESPEED, SP_CSS_IMAGE_RENDERING_OPTIMIZEQUALITY, @@ -322,143 +351,116 @@ enum SPImageRendering : std::uint_least8_t { SP_CSS_IMAGE_RENDERING_PIXELATED }; -enum SPShapeRendering : std::uint_least8_t { +enum SPShapeRendering : std::uint_least8_t +{ SP_CSS_SHAPE_RENDERING_AUTO, SP_CSS_SHAPE_RENDERING_OPTIMIZESPEED, SP_CSS_SHAPE_RENDERING_CRISPEDGES, SP_CSS_SHAPE_RENDERING_GEOMETRICPRECISION }; -enum SPTextRendering : std::uint_least8_t { +enum SPTextRendering : std::uint_least8_t +{ SP_CSS_TEXT_RENDERING_AUTO, SP_CSS_TEXT_RENDERING_OPTIMIZESPEED, SP_CSS_TEXT_RENDERING_OPTIMIZELEGIBILITY, SP_CSS_TEXT_RENDERING_GEOMETRICPRECISION }; -enum SPVectorEffect : std::uint_least8_t { - SP_VECTOR_EFFECT_NONE = 0, - SP_VECTOR_EFFECT_NON_SCALING_STROKE = 1, - SP_VECTOR_EFFECT_NON_SCALING_SIZE = 2, - SP_VECTOR_EFFECT_NON_ROTATION = 4, - SP_VECTOR_EFFECT_FIXED_POSITION = 8 +enum SPVectorEffect : std::uint_least8_t +{ + SP_VECTOR_EFFECT_NONE = 0, + SP_VECTOR_EFFECT_NON_SCALING_STROKE = 1, + SP_VECTOR_EFFECT_NON_SCALING_SIZE = 2, + SP_VECTOR_EFFECT_NON_ROTATION = 4, + SP_VECTOR_EFFECT_FIXED_POSITION = 8 }; -struct SPStyleEnum { +struct SPStyleEnum +{ char const *key; int value; }; -static SPStyleEnum const enum_fill_rule[] = { - {"nonzero", SP_WIND_RULE_NONZERO}, - {"evenodd", SP_WIND_RULE_EVENODD}, - {nullptr, -1} -}; +static SPStyleEnum const enum_fill_rule[] = {{"nonzero", SP_WIND_RULE_NONZERO}, + {"evenodd", SP_WIND_RULE_EVENODD}, + {nullptr, -1}}; -static SPStyleEnum const enum_stroke_linejoin[] = { - {"miter", SP_STROKE_LINEJOIN_MITER}, - {"round", SP_STROKE_LINEJOIN_ROUND}, - {"bevel", SP_STROKE_LINEJOIN_BEVEL}, - {nullptr, -1} -}; +static SPStyleEnum const enum_stroke_linejoin[] = {{"miter", SP_STROKE_LINEJOIN_MITER}, + {"round", SP_STROKE_LINEJOIN_ROUND}, + {"bevel", SP_STROKE_LINEJOIN_BEVEL}, + {nullptr, -1}}; -static SPStyleEnum const enum_stroke_linecap[] = { - {"butt", SP_STROKE_LINECAP_BUTT}, - {"round", SP_STROKE_LINECAP_ROUND}, - {"square", SP_STROKE_LINECAP_SQUARE}, - {nullptr, -1} -}; +static SPStyleEnum const enum_stroke_linecap[] = {{"butt", SP_STROKE_LINECAP_BUTT}, + {"round", SP_STROKE_LINECAP_ROUND}, + {"square", SP_STROKE_LINECAP_SQUARE}, + {nullptr, -1}}; -static SPStyleEnum const enum_font_style[] = { - {"normal", SP_CSS_FONT_STYLE_NORMAL}, - {"italic", SP_CSS_FONT_STYLE_ITALIC}, - {"oblique", SP_CSS_FONT_STYLE_OBLIQUE}, - {nullptr, -1} -}; +static SPStyleEnum const enum_font_style[] = {{"normal", SP_CSS_FONT_STYLE_NORMAL}, + {"italic", SP_CSS_FONT_STYLE_ITALIC}, + {"oblique", SP_CSS_FONT_STYLE_OBLIQUE}, + {nullptr, -1}}; static SPStyleEnum const enum_font_size[] = { - {"xx-small", SP_CSS_FONT_SIZE_XX_SMALL}, - {"x-small", SP_CSS_FONT_SIZE_X_SMALL}, - {"small", SP_CSS_FONT_SIZE_SMALL}, - {"medium", SP_CSS_FONT_SIZE_MEDIUM}, - {"large", SP_CSS_FONT_SIZE_LARGE}, - {"x-large", SP_CSS_FONT_SIZE_X_LARGE}, - {"xx-large", SP_CSS_FONT_SIZE_XX_LARGE}, - {"smaller", SP_CSS_FONT_SIZE_SMALLER}, - {"larger", SP_CSS_FONT_SIZE_LARGER}, - {nullptr, -1} -}; + {"xx-small", SP_CSS_FONT_SIZE_XX_SMALL}, {"x-small", SP_CSS_FONT_SIZE_X_SMALL}, + {"small", SP_CSS_FONT_SIZE_SMALL}, {"medium", SP_CSS_FONT_SIZE_MEDIUM}, + {"large", SP_CSS_FONT_SIZE_LARGE}, {"x-large", SP_CSS_FONT_SIZE_X_LARGE}, + {"xx-large", SP_CSS_FONT_SIZE_XX_LARGE}, {"smaller", SP_CSS_FONT_SIZE_SMALLER}, + {"larger", SP_CSS_FONT_SIZE_LARGER}, {nullptr, -1}}; -static SPStyleEnum const enum_font_variant[] = { - {"normal", SP_CSS_FONT_VARIANT_NORMAL}, - {"small-caps", SP_CSS_FONT_VARIANT_SMALL_CAPS}, - {nullptr, -1} -}; +static SPStyleEnum const enum_font_variant[] = {{"normal", SP_CSS_FONT_VARIANT_NORMAL}, + {"small-caps", SP_CSS_FONT_VARIANT_SMALL_CAPS}, + {nullptr, -1}}; static SPStyleEnum const enum_font_weight[] = { - {"100", SP_CSS_FONT_WEIGHT_100}, - {"200", SP_CSS_FONT_WEIGHT_200}, - {"300", SP_CSS_FONT_WEIGHT_300}, - {"400", SP_CSS_FONT_WEIGHT_400}, - {"500", SP_CSS_FONT_WEIGHT_500}, - {"600", SP_CSS_FONT_WEIGHT_600}, - {"700", SP_CSS_FONT_WEIGHT_700}, - {"800", SP_CSS_FONT_WEIGHT_800}, - {"900", SP_CSS_FONT_WEIGHT_900}, - {"normal", SP_CSS_FONT_WEIGHT_NORMAL}, - {"bold", SP_CSS_FONT_WEIGHT_BOLD}, - {"lighter", SP_CSS_FONT_WEIGHT_LIGHTER}, - {"bolder", SP_CSS_FONT_WEIGHT_BOLDER}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_font_stretch[] = { - {"ultra-condensed", SP_CSS_FONT_STRETCH_ULTRA_CONDENSED}, - {"extra-condensed", SP_CSS_FONT_STRETCH_EXTRA_CONDENSED}, - {"condensed", SP_CSS_FONT_STRETCH_CONDENSED}, - {"semi-condensed", SP_CSS_FONT_STRETCH_SEMI_CONDENSED}, - {"normal", SP_CSS_FONT_STRETCH_NORMAL}, - {"semi-expanded", SP_CSS_FONT_STRETCH_SEMI_EXPANDED}, - {"expanded", SP_CSS_FONT_STRETCH_EXPANDED}, - {"extra-expanded", SP_CSS_FONT_STRETCH_EXTRA_EXPANDED}, - {"ultra-expanded", SP_CSS_FONT_STRETCH_ULTRA_EXPANDED}, - {"narrower", SP_CSS_FONT_STRETCH_NARROWER}, - {"wider", SP_CSS_FONT_STRETCH_WIDER}, - {nullptr, -1} -}; + {"100", SP_CSS_FONT_WEIGHT_100}, {"200", SP_CSS_FONT_WEIGHT_200}, + {"300", SP_CSS_FONT_WEIGHT_300}, {"400", SP_CSS_FONT_WEIGHT_400}, + {"500", SP_CSS_FONT_WEIGHT_500}, {"600", SP_CSS_FONT_WEIGHT_600}, + {"700", SP_CSS_FONT_WEIGHT_700}, {"800", SP_CSS_FONT_WEIGHT_800}, + {"900", SP_CSS_FONT_WEIGHT_900}, {"normal", SP_CSS_FONT_WEIGHT_NORMAL}, + {"bold", SP_CSS_FONT_WEIGHT_BOLD}, {"lighter", SP_CSS_FONT_WEIGHT_LIGHTER}, + {"bolder", SP_CSS_FONT_WEIGHT_BOLDER}, {nullptr, -1}}; + +static SPStyleEnum const enum_font_stretch[] = {{"ultra-condensed", SP_CSS_FONT_STRETCH_ULTRA_CONDENSED}, + {"extra-condensed", SP_CSS_FONT_STRETCH_EXTRA_CONDENSED}, + {"condensed", SP_CSS_FONT_STRETCH_CONDENSED}, + {"semi-condensed", SP_CSS_FONT_STRETCH_SEMI_CONDENSED}, + {"normal", SP_CSS_FONT_STRETCH_NORMAL}, + {"semi-expanded", SP_CSS_FONT_STRETCH_SEMI_EXPANDED}, + {"expanded", SP_CSS_FONT_STRETCH_EXPANDED}, + {"extra-expanded", SP_CSS_FONT_STRETCH_EXTRA_EXPANDED}, + {"ultra-expanded", SP_CSS_FONT_STRETCH_ULTRA_EXPANDED}, + {"narrower", SP_CSS_FONT_STRETCH_NARROWER}, + {"wider", SP_CSS_FONT_STRETCH_WIDER}, + {nullptr, -1}}; static SPStyleEnum const enum_font_variant_ligatures[] = { - {"none", SP_CSS_FONT_VARIANT_LIGATURES_NONE}, - {"common-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_COMMON}, - {"discretionary-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_DISCRETIONARY}, - {"historical-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL}, - {"contextual", SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL}, - {"normal", SP_CSS_FONT_VARIANT_LIGATURES_NORMAL}, - {"no-common-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_NOCOMMON}, - {"no-discretionary-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_NODISCRETIONARY}, - {"no-historical-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_NOHISTORICAL}, - {"no-contextual", SP_CSS_FONT_VARIANT_LIGATURES_NOCONTEXTUAL}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_font_variant_position[] = { - {"normal", SP_CSS_FONT_VARIANT_POSITION_NORMAL}, - {"sub", SP_CSS_FONT_VARIANT_POSITION_SUB}, - {"super", SP_CSS_FONT_VARIANT_POSITION_SUPER}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_font_variant_caps[] = { - {"normal", SP_CSS_FONT_VARIANT_CAPS_NORMAL}, - {"small-caps", SP_CSS_FONT_VARIANT_CAPS_SMALL}, - {"all-small-caps", SP_CSS_FONT_VARIANT_CAPS_ALL_SMALL}, - {"petite-caps", SP_CSS_FONT_VARIANT_CAPS_PETITE}, - {"all-petite-caps", SP_CSS_FONT_VARIANT_CAPS_ALL_PETITE}, - {"unicase", SP_CSS_FONT_VARIANT_CAPS_UNICASE}, - {"titling-caps", SP_CSS_FONT_VARIANT_CAPS_TITLING}, - {nullptr, -1} -}; - + {"none", SP_CSS_FONT_VARIANT_LIGATURES_NONE}, + {"common-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_COMMON}, + {"discretionary-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_DISCRETIONARY}, + {"historical-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL}, + {"contextual", SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL}, + {"normal", SP_CSS_FONT_VARIANT_LIGATURES_NORMAL}, + {"no-common-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_NOCOMMON}, + {"no-discretionary-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_NODISCRETIONARY}, + {"no-historical-ligatures", SP_CSS_FONT_VARIANT_LIGATURES_NOHISTORICAL}, + {"no-contextual", SP_CSS_FONT_VARIANT_LIGATURES_NOCONTEXTUAL}, + {nullptr, -1}}; + +static SPStyleEnum const enum_font_variant_position[] = {{"normal", SP_CSS_FONT_VARIANT_POSITION_NORMAL}, + {"sub", SP_CSS_FONT_VARIANT_POSITION_SUB}, + {"super", SP_CSS_FONT_VARIANT_POSITION_SUPER}, + {nullptr, -1}}; + +static SPStyleEnum const enum_font_variant_caps[] = {{"normal", SP_CSS_FONT_VARIANT_CAPS_NORMAL}, + {"small-caps", SP_CSS_FONT_VARIANT_CAPS_SMALL}, + {"all-small-caps", SP_CSS_FONT_VARIANT_CAPS_ALL_SMALL}, + {"petite-caps", SP_CSS_FONT_VARIANT_CAPS_PETITE}, + {"all-petite-caps", SP_CSS_FONT_VARIANT_CAPS_ALL_PETITE}, + {"unicase", SP_CSS_FONT_VARIANT_CAPS_UNICASE}, + {"titling-caps", SP_CSS_FONT_VARIANT_CAPS_TITLING}, + {nullptr, -1}}; + static SPStyleEnum const enum_font_variant_numeric[] = { {"normal", SP_CSS_FONT_VARIANT_NUMERIC_NORMAL}, {"lining-nums", SP_CSS_FONT_VARIANT_NUMERIC_LINING_NUMS}, @@ -469,9 +471,8 @@ static SPStyleEnum const enum_font_variant_numeric[] = { {"stacked-fractions", SP_CSS_FONT_VARIANT_NUMERIC_STACKED_FRACTIONS}, {"ordinal", SP_CSS_FONT_VARIANT_NUMERIC_ORDINAL}, {"slashed-zero", SP_CSS_FONT_VARIANT_NUMERIC_SLASHED_ZERO}, - {nullptr, -1} -}; - + {nullptr, -1}}; + static SPStyleEnum const enum_font_variant_alternates[] = { {"normal", SP_CSS_FONT_VARIANT_ALTERNATES_NORMAL}, {"historical-forms", SP_CSS_FONT_VARIANT_ALTERNATES_HISTORICAL_FORMS}, @@ -481,8 +482,7 @@ static SPStyleEnum const enum_font_variant_alternates[] = { {"swash", SP_CSS_FONT_VARIANT_ALTERNATES_SWASH}, {"ornaments", SP_CSS_FONT_VARIANT_ALTERNATES_ORNAMENTS}, {"annotation", SP_CSS_FONT_VARIANT_ALTERNATES_ANNOTATION}, - {nullptr, -1} -}; + {nullptr, -1}}; static SPStyleEnum const enum_font_variant_east_asian[] = { {"normal", SP_CSS_FONT_VARIANT_EAST_ASIAN_NORMAL}, @@ -495,48 +495,35 @@ static SPStyleEnum const enum_font_variant_east_asian[] = { {"full-width", SP_CSS_FONT_VARIANT_EAST_ASIAN_FULL_WIDTH}, {"proportional-width", SP_CSS_FONT_VARIANT_EAST_ASIAN_PROPORTIONAL_WIDTH}, {"ruby", SP_CSS_FONT_VARIANT_EAST_ASIAN_RUBY}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_text_align[] = { - {"start", SP_CSS_TEXT_ALIGN_START}, - {"end", SP_CSS_TEXT_ALIGN_END}, - {"left", SP_CSS_TEXT_ALIGN_LEFT}, - {"right", SP_CSS_TEXT_ALIGN_RIGHT}, - {"center", SP_CSS_TEXT_ALIGN_CENTER}, - {"justify", SP_CSS_TEXT_ALIGN_JUSTIFY}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_text_transform[] = { - {"capitalize", SP_CSS_TEXT_TRANSFORM_CAPITALIZE}, - {"uppercase", SP_CSS_TEXT_TRANSFORM_UPPERCASE}, - {"lowercase", SP_CSS_TEXT_TRANSFORM_LOWERCASE}, - {"none", SP_CSS_TEXT_TRANSFORM_NONE}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_text_anchor[] = { - {"start", SP_CSS_TEXT_ANCHOR_START}, - {"middle", SP_CSS_TEXT_ANCHOR_MIDDLE}, - {"end", SP_CSS_TEXT_ANCHOR_END}, - {nullptr, -1} -}; + {nullptr, -1}}; + +static SPStyleEnum const enum_text_align[] = {{"start", SP_CSS_TEXT_ALIGN_START}, + {"end", SP_CSS_TEXT_ALIGN_END}, + {"left", SP_CSS_TEXT_ALIGN_LEFT}, + {"right", SP_CSS_TEXT_ALIGN_RIGHT}, + {"center", SP_CSS_TEXT_ALIGN_CENTER}, + {"justify", SP_CSS_TEXT_ALIGN_JUSTIFY}, + {nullptr, -1}}; + +static SPStyleEnum const enum_text_transform[] = {{"capitalize", SP_CSS_TEXT_TRANSFORM_CAPITALIZE}, + {"uppercase", SP_CSS_TEXT_TRANSFORM_UPPERCASE}, + {"lowercase", SP_CSS_TEXT_TRANSFORM_LOWERCASE}, + {"none", SP_CSS_TEXT_TRANSFORM_NONE}, + {nullptr, -1}}; + +static SPStyleEnum const enum_text_anchor[] = {{"start", SP_CSS_TEXT_ANCHOR_START}, + {"middle", SP_CSS_TEXT_ANCHOR_MIDDLE}, + {"end", SP_CSS_TEXT_ANCHOR_END}, + {nullptr, -1}}; static SPStyleEnum const enum_white_space[] = { - {"normal", SP_CSS_WHITE_SPACE_NORMAL }, - {"pre", SP_CSS_WHITE_SPACE_PRE }, - {"nowrap", SP_CSS_WHITE_SPACE_NOWRAP }, - {"pre-wrap", SP_CSS_WHITE_SPACE_PREWRAP}, - {"pre-line", SP_CSS_WHITE_SPACE_PRELINE}, - {nullptr, -1} -}; + {"normal", SP_CSS_WHITE_SPACE_NORMAL}, {"pre", SP_CSS_WHITE_SPACE_PRE}, + {"nowrap", SP_CSS_WHITE_SPACE_NOWRAP}, {"pre-wrap", SP_CSS_WHITE_SPACE_PREWRAP}, + {"pre-line", SP_CSS_WHITE_SPACE_PRELINE}, {nullptr, -1}}; -static SPStyleEnum const enum_direction[] = { - {"ltr", SP_CSS_DIRECTION_LTR}, - {"rtl", SP_CSS_DIRECTION_RTL}, - {nullptr, -1} -}; +static SPStyleEnum const enum_direction[] = {{"ltr", SP_CSS_DIRECTION_LTR}, + {"rtl", SP_CSS_DIRECTION_RTL}, + {nullptr, -1}}; static SPStyleEnum const enum_writing_mode[] = { /* Note that using the same enumerator for lr as lr-tb means we write as lr-tb even if the @@ -557,164 +544,129 @@ static SPStyleEnum const enum_writing_mode[] = { {"horizontal-tb", SP_CSS_WRITING_MODE_LR_TB}, // This is correct, 'direction' distinguishes between 'lr' and 'rl'. {"vertical-rl", SP_CSS_WRITING_MODE_TB_RL}, {"vertical-lr", SP_CSS_WRITING_MODE_TB_LR}, - {nullptr, -1} -}; + {nullptr, -1}}; // CSS WRITING MODES 3 -static SPStyleEnum const enum_text_orientation[] = { - {"mixed", SP_CSS_TEXT_ORIENTATION_MIXED}, // Default - {"upright", SP_CSS_TEXT_ORIENTATION_UPRIGHT}, - {"sideways", SP_CSS_TEXT_ORIENTATION_SIDEWAYS}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_baseline[] = { - {"auto", SP_CSS_BASELINE_AUTO}, // Default - {"alphabetic", SP_CSS_BASELINE_ALPHABETIC}, - {"ideographic", SP_CSS_BASELINE_IDEOGRAPHIC}, - {"hanging", SP_CSS_BASELINE_HANGING}, - {"mathematical", SP_CSS_BASELINE_MATHEMATICAL}, - {"central", SP_CSS_BASELINE_CENTRAL}, - {"middle", SP_CSS_BASELINE_MIDDLE}, - {"text-before-edge", SP_CSS_BASELINE_TEXT_BEFORE_EDGE}, - {"text-after-edge", SP_CSS_BASELINE_TEXT_AFTER_EDGE}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_baseline_shift[] = { - {"baseline", SP_CSS_BASELINE_SHIFT_BASELINE}, - {"sub", SP_CSS_BASELINE_SHIFT_SUB}, - {"super", SP_CSS_BASELINE_SHIFT_SUPER}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_visibility[] = { - {"hidden", SP_CSS_VISIBILITY_HIDDEN}, - {"collapse", SP_CSS_VISIBILITY_COLLAPSE}, - {"visible", SP_CSS_VISIBILITY_VISIBLE}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_overflow[] = { - {"visible", SP_CSS_OVERFLOW_VISIBLE}, - {"hidden", SP_CSS_OVERFLOW_HIDDEN}, - {"scroll", SP_CSS_OVERFLOW_SCROLL}, - {"auto", SP_CSS_OVERFLOW_AUTO}, - {nullptr, -1} -}; +static SPStyleEnum const enum_text_orientation[] = {{"mixed", SP_CSS_TEXT_ORIENTATION_MIXED}, // Default + {"upright", SP_CSS_TEXT_ORIENTATION_UPRIGHT}, + {"sideways", SP_CSS_TEXT_ORIENTATION_SIDEWAYS}, + {nullptr, -1}}; + +static SPStyleEnum const enum_baseline[] = {{"auto", SP_CSS_BASELINE_AUTO}, // Default + {"alphabetic", SP_CSS_BASELINE_ALPHABETIC}, + {"ideographic", SP_CSS_BASELINE_IDEOGRAPHIC}, + {"hanging", SP_CSS_BASELINE_HANGING}, + {"mathematical", SP_CSS_BASELINE_MATHEMATICAL}, + {"central", SP_CSS_BASELINE_CENTRAL}, + {"middle", SP_CSS_BASELINE_MIDDLE}, + {"text-before-edge", SP_CSS_BASELINE_TEXT_BEFORE_EDGE}, + {"text-after-edge", SP_CSS_BASELINE_TEXT_AFTER_EDGE}, + {nullptr, -1}}; + +static SPStyleEnum const enum_baseline_shift[] = {{"baseline", SP_CSS_BASELINE_SHIFT_BASELINE}, + {"sub", SP_CSS_BASELINE_SHIFT_SUB}, + {"super", SP_CSS_BASELINE_SHIFT_SUPER}, + {nullptr, -1}}; + +static SPStyleEnum const enum_visibility[] = {{"hidden", SP_CSS_VISIBILITY_HIDDEN}, + {"collapse", SP_CSS_VISIBILITY_COLLAPSE}, + {"visible", SP_CSS_VISIBILITY_VISIBLE}, + {nullptr, -1}}; + +static SPStyleEnum const enum_overflow[] = {{"visible", SP_CSS_OVERFLOW_VISIBLE}, + {"hidden", SP_CSS_OVERFLOW_HIDDEN}, + {"scroll", SP_CSS_OVERFLOW_SCROLL}, + {"auto", SP_CSS_OVERFLOW_AUTO}, + {nullptr, -1}}; // CSS Compositing and Blending Level 1 -static SPStyleEnum const enum_isolation[] = { - {"auto", SP_CSS_ISOLATION_AUTO}, - {"isolate", SP_CSS_ISOLATION_ISOLATE}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_blend_mode[] = { - {"normal", SP_CSS_BLEND_NORMAL}, - {"multiply", SP_CSS_BLEND_MULTIPLY}, - {"screen", SP_CSS_BLEND_SCREEN}, - {"darken", SP_CSS_BLEND_DARKEN}, - {"lighten", SP_CSS_BLEND_LIGHTEN}, - {"overlay", SP_CSS_BLEND_OVERLAY}, - {"color-dodge", SP_CSS_BLEND_COLORDODGE}, - {"color-burn", SP_CSS_BLEND_COLORBURN}, - {"hard-light", SP_CSS_BLEND_HARDLIGHT}, - {"soft-light", SP_CSS_BLEND_SOFTLIGHT}, - {"difference", SP_CSS_BLEND_DIFFERENCE}, - {"exclusion", SP_CSS_BLEND_EXCLUSION}, - {"hue", SP_CSS_BLEND_HUE}, - {"saturation", SP_CSS_BLEND_SATURATION}, - {"color", SP_CSS_BLEND_COLOR}, - {"luminosity", SP_CSS_BLEND_LUMINOSITY}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_display[] = { - {"none", SP_CSS_DISPLAY_NONE}, - {"inline", SP_CSS_DISPLAY_INLINE}, - {"block", SP_CSS_DISPLAY_BLOCK}, - {"list-item", SP_CSS_DISPLAY_LIST_ITEM}, - {"run-in", SP_CSS_DISPLAY_RUN_IN}, - {"compact", SP_CSS_DISPLAY_COMPACT}, - {"marker", SP_CSS_DISPLAY_MARKER}, - {"table", SP_CSS_DISPLAY_TABLE}, - {"inline-table", SP_CSS_DISPLAY_INLINE_TABLE}, - {"table-row-group", SP_CSS_DISPLAY_TABLE_ROW_GROUP}, - {"table-header-group", SP_CSS_DISPLAY_TABLE_HEADER_GROUP}, - {"table-footer-group", SP_CSS_DISPLAY_TABLE_FOOTER_GROUP}, - {"table-row", SP_CSS_DISPLAY_TABLE_ROW}, - {"table-column-group", SP_CSS_DISPLAY_TABLE_COLUMN_GROUP}, - {"table-column", SP_CSS_DISPLAY_TABLE_COLUMN}, - {"table-cell", SP_CSS_DISPLAY_TABLE_CELL}, - {"table-caption", SP_CSS_DISPLAY_TABLE_CAPTION}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_shape_rendering[] = { - {"auto", SP_CSS_SHAPE_RENDERING_AUTO}, - {"optimizeSpeed", SP_CSS_SHAPE_RENDERING_OPTIMIZESPEED}, - {"crispEdges", SP_CSS_SHAPE_RENDERING_CRISPEDGES}, - {"geometricPrecision", SP_CSS_SHAPE_RENDERING_GEOMETRICPRECISION}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_color_rendering[] = { - {"auto", SP_CSS_COLOR_RENDERING_AUTO}, - {"optimizeSpeed", SP_CSS_COLOR_RENDERING_OPTIMIZESPEED}, - {"optimizeQuality", SP_CSS_COLOR_RENDERING_OPTIMIZEQUALITY}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_image_rendering[] = { - {"auto", SP_CSS_IMAGE_RENDERING_AUTO}, - {"optimizeSpeed", SP_CSS_IMAGE_RENDERING_OPTIMIZESPEED}, - {"optimizeQuality", SP_CSS_IMAGE_RENDERING_OPTIMIZEQUALITY}, - {"crisp-edges", SP_CSS_IMAGE_RENDERING_CRISPEDGES}, - {"pixelated", SP_CSS_IMAGE_RENDERING_PIXELATED}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_text_rendering[] = { - {"auto", SP_CSS_TEXT_RENDERING_AUTO}, - {"optimizeSpeed", SP_CSS_TEXT_RENDERING_OPTIMIZESPEED}, - {"optimizeLegibility", SP_CSS_TEXT_RENDERING_OPTIMIZELEGIBILITY}, - {"geometricPrecision", SP_CSS_TEXT_RENDERING_GEOMETRICPRECISION}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_enable_background[] = { - {"accumulate", SP_CSS_BACKGROUND_ACCUMULATE}, - {"new", SP_CSS_BACKGROUND_NEW}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_clip_rule[] = { - {"nonzero", SP_WIND_RULE_NONZERO}, - {"evenodd", SP_WIND_RULE_EVENODD}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_color_interpolation[] = { - {"auto", SP_CSS_COLOR_INTERPOLATION_AUTO}, - {"sRGB", SP_CSS_COLOR_INTERPOLATION_SRGB}, - {"linearRGB", SP_CSS_COLOR_INTERPOLATION_LINEARRGB}, - {nullptr, -1} -}; - -static SPStyleEnum const enum_vector_effect[] = { - {"none", SP_VECTOR_EFFECT_NONE}, - {"non-scaling-stroke", SP_VECTOR_EFFECT_NON_SCALING_STROKE}, - {"non-scaling-size", SP_VECTOR_EFFECT_NON_SCALING_SIZE}, - {"non-rotation", SP_VECTOR_EFFECT_NON_ROTATION}, - {"fixed-position", SP_VECTOR_EFFECT_FIXED_POSITION}, - {nullptr, -1} -}; - +static SPStyleEnum const enum_isolation[] = {{"auto", SP_CSS_ISOLATION_AUTO}, + {"isolate", SP_CSS_ISOLATION_ISOLATE}, + {nullptr, -1}}; + +static SPStyleEnum const enum_blend_mode[] = {{"normal", SP_CSS_BLEND_NORMAL}, + {"multiply", SP_CSS_BLEND_MULTIPLY}, + {"screen", SP_CSS_BLEND_SCREEN}, + {"darken", SP_CSS_BLEND_DARKEN}, + {"lighten", SP_CSS_BLEND_LIGHTEN}, + {"overlay", SP_CSS_BLEND_OVERLAY}, + {"color-dodge", SP_CSS_BLEND_COLORDODGE}, + {"color-burn", SP_CSS_BLEND_COLORBURN}, + {"hard-light", SP_CSS_BLEND_HARDLIGHT}, + {"soft-light", SP_CSS_BLEND_SOFTLIGHT}, + {"difference", SP_CSS_BLEND_DIFFERENCE}, + {"exclusion", SP_CSS_BLEND_EXCLUSION}, + {"hue", SP_CSS_BLEND_HUE}, + {"saturation", SP_CSS_BLEND_SATURATION}, + {"color", SP_CSS_BLEND_COLOR}, + {"luminosity", SP_CSS_BLEND_LUMINOSITY}, + {nullptr, -1}}; + +static SPStyleEnum const enum_display[] = {{"none", SP_CSS_DISPLAY_NONE}, + {"inline", SP_CSS_DISPLAY_INLINE}, + {"block", SP_CSS_DISPLAY_BLOCK}, + {"list-item", SP_CSS_DISPLAY_LIST_ITEM}, + {"run-in", SP_CSS_DISPLAY_RUN_IN}, + {"compact", SP_CSS_DISPLAY_COMPACT}, + {"marker", SP_CSS_DISPLAY_MARKER}, + {"table", SP_CSS_DISPLAY_TABLE}, + {"inline-table", SP_CSS_DISPLAY_INLINE_TABLE}, + {"table-row-group", SP_CSS_DISPLAY_TABLE_ROW_GROUP}, + {"table-header-group", SP_CSS_DISPLAY_TABLE_HEADER_GROUP}, + {"table-footer-group", SP_CSS_DISPLAY_TABLE_FOOTER_GROUP}, + {"table-row", SP_CSS_DISPLAY_TABLE_ROW}, + {"table-column-group", SP_CSS_DISPLAY_TABLE_COLUMN_GROUP}, + {"table-column", SP_CSS_DISPLAY_TABLE_COLUMN}, + {"table-cell", SP_CSS_DISPLAY_TABLE_CELL}, + {"table-caption", SP_CSS_DISPLAY_TABLE_CAPTION}, + {nullptr, -1}}; + +static SPStyleEnum const enum_shape_rendering[] = {{"auto", SP_CSS_SHAPE_RENDERING_AUTO}, + {"optimizeSpeed", SP_CSS_SHAPE_RENDERING_OPTIMIZESPEED}, + {"crispEdges", SP_CSS_SHAPE_RENDERING_CRISPEDGES}, + {"geometricPrecision", SP_CSS_SHAPE_RENDERING_GEOMETRICPRECISION}, + {nullptr, -1}}; + +static SPStyleEnum const enum_color_rendering[] = {{"auto", SP_CSS_COLOR_RENDERING_AUTO}, + {"optimizeSpeed", SP_CSS_COLOR_RENDERING_OPTIMIZESPEED}, + {"optimizeQuality", SP_CSS_COLOR_RENDERING_OPTIMIZEQUALITY}, + {nullptr, -1}}; + +static SPStyleEnum const enum_image_rendering[] = {{"auto", SP_CSS_IMAGE_RENDERING_AUTO}, + {"optimizeSpeed", SP_CSS_IMAGE_RENDERING_OPTIMIZESPEED}, + {"optimizeQuality", SP_CSS_IMAGE_RENDERING_OPTIMIZEQUALITY}, + {"crisp-edges", SP_CSS_IMAGE_RENDERING_CRISPEDGES}, + {"pixelated", SP_CSS_IMAGE_RENDERING_PIXELATED}, + {nullptr, -1}}; + +static SPStyleEnum const enum_text_rendering[] = {{"auto", SP_CSS_TEXT_RENDERING_AUTO}, + {"optimizeSpeed", SP_CSS_TEXT_RENDERING_OPTIMIZESPEED}, + {"optimizeLegibility", SP_CSS_TEXT_RENDERING_OPTIMIZELEGIBILITY}, + {"geometricPrecision", SP_CSS_TEXT_RENDERING_GEOMETRICPRECISION}, + {nullptr, -1}}; + +static SPStyleEnum const enum_enable_background[] = {{"accumulate", SP_CSS_BACKGROUND_ACCUMULATE}, + {"new", SP_CSS_BACKGROUND_NEW}, + {nullptr, -1}}; + +static SPStyleEnum const enum_clip_rule[] = {{"nonzero", SP_WIND_RULE_NONZERO}, + {"evenodd", SP_WIND_RULE_EVENODD}, + {nullptr, -1}}; + +static SPStyleEnum const enum_color_interpolation[] = {{"auto", SP_CSS_COLOR_INTERPOLATION_AUTO}, + {"sRGB", SP_CSS_COLOR_INTERPOLATION_SRGB}, + {"linearRGB", SP_CSS_COLOR_INTERPOLATION_LINEARRGB}, + {nullptr, -1}}; + +static SPStyleEnum const enum_vector_effect[] = {{"none", SP_VECTOR_EFFECT_NONE}, + {"non-scaling-stroke", SP_VECTOR_EFFECT_NON_SCALING_STROKE}, + {"non-scaling-size", SP_VECTOR_EFFECT_NON_SCALING_SIZE}, + {"non-rotation", SP_VECTOR_EFFECT_NON_ROTATION}, + {"fixed-position", SP_VECTOR_EFFECT_FIXED_POSITION}, + {nullptr, -1}}; #endif // SEEN_SP_STYLE_ENUMS_H - /* Local Variables: mode:c++ diff --git a/src/style-internal.cpp b/src/style-internal.cpp index eab0ff834f4563dbd5c8f5eae40b5626ae830baf..bb3d3374db4b90d814aaa79748d7b042fb9d6169 100644 --- a/src/style-internal.cpp +++ b/src/style-internal.cpp @@ -23,32 +23,29 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/regex.h> - #include "style-internal.h" -#include "style.h" + +#include <glibmm/regex.h> #include "bad-uri-exception.h" #include "extract-uri.h" #include "inkscape.h" +#include "object/sp-text.h" #include "preferences.h" #include "streq.h" #include "strneq.h" - -#include "object/sp-text.h" - -#include "svg/svg.h" -#include "svg/svg-color.h" +#include "style.h" #include "svg/css-ostringstream.h" - +#include "svg/svg-color.h" +#include "svg/svg.h" #include "util/units.h" // TODO REMOVE OR MAKE MEMBER FUNCTIONS -void sp_style_fill_paint_server_ref_changed( SPObject *old_ref, SPObject *ref, SPStyle *style); +void sp_style_fill_paint_server_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style); void sp_style_stroke_paint_server_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style); -void sp_style_filter_ref_changed( SPObject *old_ref, SPObject *ref, SPStyle *style); +void sp_style_filter_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style); void sp_style_set_ipaint_to_uri(SPStyle *style, SPIPaint *paint, const Inkscape::URI *uri, SPDocument *document); -void sp_style_set_ipaint_to_uri_string (SPStyle *style, SPIPaint *paint, const gchar *uri); +void sp_style_set_ipaint_to_uri_string(SPStyle *style, SPIPaint *paint, const gchar *uri); using Inkscape::CSSOStringStream; @@ -67,12 +64,11 @@ Glib::ustring const &SPIBase::name() const // Standard criteria for writing a property // dfp == different from parent -inline bool should_write( guint const flags, bool set, bool dfp, bool src) { - +inline bool should_write(guint const flags, bool set, bool dfp, bool src) +{ bool should_write = false; - if ( ((flags & SP_STYLE_FLAG_ALWAYS) && src) || - ((flags & SP_STYLE_FLAG_IFSET) && set && src) || - ((flags & SP_STYLE_FLAG_IFDIFF) && set && src && dfp)) { + if (((flags & SP_STYLE_FLAG_ALWAYS) && src) || ((flags & SP_STYLE_FLAG_IFSET) && set && src) || + ((flags & SP_STYLE_FLAG_IFDIFF) && set && src && dfp)) { should_write = true; } return should_write; @@ -91,7 +87,7 @@ inline bool should_write( guint const flags, bool set, bool dfp, bool src) { bool SPIBase::shall_write(guint const flags, SPStyleSrc const &style_src_req, SPIBase const *const base) const { // Is this class different from the SPIBase given, this is used in Object-to-Path - SPIBase const *const my_base = dynamic_cast<const SPIBase*>(base); + SPIBase const *const my_base = dynamic_cast<const SPIBase *>(base); bool dfp = (!inherits || !my_base || (my_base != this)); // Different from parent bool src = (style_src_req == style_src || !(flags & SP_STYLE_FLAG_IFSRC)); return should_write(flags, set, dfp, src); @@ -111,14 +107,13 @@ const Glib::ustring SPIBase::write(guint const flags, SPStyleSrc const &style_sr { if (shall_write(flags, style_src_req, base)) { auto value = this->get_value(); - if ( !value.empty() ) { + if (!value.empty()) { return (name() + ":" + value + important_str() + ";"); } } return Glib::ustring(""); } - /** * If str.endswith("!important") then assign stripped = str[:-10].rstrip() and return true. * Otherwise, leave stripped unmodified and return false. @@ -172,15 +167,14 @@ void SPIBase::readIfUnset(gchar const *str, SPStyleSrc source) } } - // SPIFloat ------------------------------------------------------------- -void -SPIFloat::read( gchar const *str ) { - - if( !str ) return; +void SPIFloat::read(gchar const *str) +{ + if (!str) + return; - if ( !strcmp(str, "inherit") ) { + if (!strcmp(str, "inherit")) { set = true; inherit = true; } else { @@ -195,27 +189,29 @@ SPIFloat::read( gchar const *str ) { const Glib::ustring SPIFloat::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); + if (this->inherit) + return Glib::ustring("inherit"); return Glib::ustring::format(this->value); } -void -SPIFloat::cascade( const SPIBase* const parent ) { - if( const SPIFloat* p = dynamic_cast<const SPIFloat*>(parent) ) { - if( (inherits && !set) || inherit ) value = p->value; +void SPIFloat::cascade(const SPIBase *const parent) +{ + if (const SPIFloat *p = dynamic_cast<const SPIFloat *>(parent)) { + if ((inherits && !set) || inherit) + value = p->value; } else { std::cerr << "SPIFloat::cascade(): Incorrect parent type" << std::endl; } } -void -SPIFloat::merge( const SPIBase* const parent ) { - if( const SPIFloat* p = dynamic_cast<const SPIFloat*>(parent) ) { - if( inherits ) { - if( (!set || inherit) && p->set && !(p->inherit) ) { - set = p->set; +void SPIFloat::merge(const SPIBase *const parent) +{ + if (const SPIFloat *p = dynamic_cast<const SPIFloat *>(parent)) { + if (inherits) { + if ((!set || inherit) && p->set && !(p->inherit)) { + set = p->set; inherit = p->inherit; - value = p->value; + value = p->value; } } } else { @@ -223,25 +219,23 @@ SPIFloat::merge( const SPIBase* const parent ) { } } -bool -SPIFloat::operator==(const SPIBase& rhs) { - if( const SPIFloat* r = dynamic_cast<const SPIFloat*>(&rhs) ) { +bool SPIFloat::operator==(const SPIBase &rhs) +{ + if (const SPIFloat *r = dynamic_cast<const SPIFloat *>(&rhs)) { return (value == r->value && SPIBase::operator==(rhs)); } else { return false; } } - - // SPIScale24 ----------------------------------------------------------- -void -SPIScale24::read( gchar const *str ) { - - if( !str ) return; +void SPIScale24::read(gchar const *str) +{ + if (!str) + return; - if ( !strcmp(str, "inherit") ) { + if (!strcmp(str, "inherit")) { set = true; inherit = true; } else { @@ -250,46 +244,49 @@ SPIScale24::read( gchar const *str ) { set = true; inherit = false; value_in = CLAMP(value_in, 0.0, 1.0); - value = SP_SCALE24_FROM_FLOAT( value_in ); + value = SP_SCALE24_FROM_FLOAT(value_in); } } } const Glib::ustring SPIScale24::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); + if (this->inherit) + return Glib::ustring("inherit"); return Glib::ustring::format(SP_SCALE24_TO_FLOAT(this->value)); } -void -SPIScale24::cascade( const SPIBase* const parent ) { - if( const SPIScale24* p = dynamic_cast<const SPIScale24*>(parent) ) { - if( (inherits && !set) || inherit ) value = p->value; +void SPIScale24::cascade(const SPIBase *const parent) +{ + if (const SPIScale24 *p = dynamic_cast<const SPIScale24 *>(parent)) { + if ((inherits && !set) || inherit) + value = p->value; } else { std::cerr << "SPIScale24::cascade(): Incorrect parent type" << std::endl; } } -void -SPIScale24::merge( const SPIBase* const parent ) { - if( const SPIScale24* p = dynamic_cast<const SPIScale24*>(parent) ) { - if( inherits ) { - if( (!set || inherit) && p->set && !(p->inherit) ) { - set = p->set; +void SPIScale24::merge(const SPIBase *const parent) +{ + if (const SPIScale24 *p = dynamic_cast<const SPIScale24 *>(parent)) { + if (inherits) { + if ((!set || inherit) && p->set && !(p->inherit)) { + set = p->set; inherit = p->inherit; - value = p->value; + value = p->value; } } else { // Needed only for 'opacity' and 'stop-opacity' which do not inherit. See comment at bottom of file. if (id() != SPAttr::OPACITY && id() != SPAttr::STOP_OPACITY) std::cerr << "SPIScale24::merge: unhandled property: " << name() << std::endl; - if( !set || (!inherit && value == SP_SCALE24_MAX) ) { + if (!set || (!inherit && value == SP_SCALE24_MAX)) { value = p->value; set = (value != SP_SCALE24_MAX); } else { - if( inherit ) value = p->value; // Insures child is up-to-date - value = SP_SCALE24_MUL( value, p->value ); - inherit = (inherit && p->inherit && (p->value == 0 || p->value == SP_SCALE24_MAX) ); + if (inherit) + value = p->value; // Insures child is up-to-date + value = SP_SCALE24_MUL(value, p->value); + inherit = (inherit && p->inherit && (p->value == 0 || p->value == SP_SCALE24_MAX)); set = (inherit || value < SP_SCALE24_MAX); } } @@ -298,23 +295,21 @@ SPIScale24::merge( const SPIBase* const parent ) { } } -bool -SPIScale24::operator==(const SPIBase& rhs) { - if( const SPIScale24* r = dynamic_cast<const SPIScale24*>(&rhs) ) { +bool SPIScale24::operator==(const SPIBase &rhs) +{ + if (const SPIScale24 *r = dynamic_cast<const SPIScale24 *>(&rhs)) { return (value == r->value && SPIBase::operator==(rhs)); } else { return false; } } - - // SPILength ------------------------------------------------------------ -void -SPILength::read( gchar const *str ) { - - if( !str ) return; +void SPILength::read(gchar const *str) +{ + if (!str) + return; if (!strcmp(str, "inherit")) { set = true; @@ -326,11 +321,10 @@ SPILength::read( gchar const *str ) { gchar *e; /** \todo fixme: Move this to standard place (Lauris) */ value_tmp = g_ascii_strtod(str, &e); - if ( !std::isfinite(value_tmp) ) { // fix for bug lp:935157 + if (!std::isfinite(value_tmp)) { // fix for bug lp:935157 return; } - if ((gchar const *) e != str) { - + if ((gchar const *)e != str) { value = value_tmp; if (!*e) { /* Userspace */ @@ -359,7 +353,7 @@ SPILength::read( gchar const *str ) { } else if (!strcmp(e, "em")) { /* EM square */ unit = SP_CSS_UNIT_EM; - if( style ) { + if (style) { computed = value * style->font_size.computed; } else { computed = value * SPIFontSize::font_size_default; @@ -367,7 +361,7 @@ SPILength::read( gchar const *str ) { } else if (!strcmp(e, "ex")) { /* ex square */ unit = SP_CSS_UNIT_EX; - if( style ) { + if (style) { computed = value * style->font_size.computed * 0.5; // FIXME } else { computed = value * SPIFontSize::font_size_default * 0.5; @@ -378,7 +372,7 @@ SPILength::read( gchar const *str ) { value = value * 0.01; if (id() == SPAttr::LINE_HEIGHT) { // See: http://www.w3.org/TR/CSS2/visudet.html#propdef-line-height - if( style ) { + if (style) { computed = value * style->font_size.computed; } else { computed = value * SPIFontSize::font_size_default; @@ -396,7 +390,8 @@ SPILength::read( gchar const *str ) { const Glib::ustring SPILength::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); + if (this->inherit) + return Glib::ustring("inherit"); auto value = this->computed; auto unit_out = Glib::ustring(""); switch (this->unit) { @@ -429,12 +424,12 @@ const Glib::ustring SPILength::get_value() const return Glib::ustring::format(value) + unit_out; } -void -SPILength::cascade( const SPIBase* const parent ) { - if( const SPILength* p = dynamic_cast<const SPILength*>(parent) ) { - if( (inherits && !set) || inherit ) { - unit = p->unit; - value = p->value; +void SPILength::cascade(const SPIBase *const parent) +{ + if (const SPILength *p = dynamic_cast<const SPILength *>(parent)) { + if ((inherits && !set) || inherit) { + unit = p->unit; + value = p->value; computed = p->computed; } else { // Recalculate based on new font-size, font-family inherited from parent @@ -454,15 +449,15 @@ SPILength::cascade( const SPIBase* const parent ) { } } -void -SPILength::merge( const SPIBase* const parent ) { - if( const SPILength* p = dynamic_cast<const SPILength*>(parent) ) { - if( inherits ) { - if( (!set || inherit) && p->set && !(p->inherit) ) { - set = p->set; - inherit = p->inherit; - unit = p->unit; - value = p->value; +void SPILength::merge(const SPIBase *const parent) +{ + if (const SPILength *p = dynamic_cast<const SPILength *>(parent)) { + if (inherits) { + if ((!set || inherit) && p->set && !(p->inherit)) { + set = p->set; + inherit = p->inherit; + unit = p->unit; + value = p->value; computed = p->computed; // Fix up so values are correct @@ -475,8 +470,8 @@ SPILength::merge( const SPIBase* const parent ) { * Get x height from libnrtype or pango. */ if (!std::isfinite(value)) { - value = computed; - unit = SP_CSS_UNIT_NONE; + value = computed; + unit = SP_CSS_UNIT_NONE; } break; @@ -513,21 +508,27 @@ const Glib::ustring SPILength::toString(bool wname) const return os.str(); } -bool -SPILength::operator==(const SPIBase& rhs) { - if( const SPILength* r = dynamic_cast<const SPILength*>(&rhs) ) { - - if( unit != r->unit ) return false; +bool SPILength::operator==(const SPIBase &rhs) +{ + if (const SPILength *r = dynamic_cast<const SPILength *>(&rhs)) { + if (unit != r->unit) + return false; // If length depends on external parameter, lengths cannot be equal. - if (unit == SP_CSS_UNIT_EM) return false; - if (unit == SP_CSS_UNIT_EX) return false; - if (unit == SP_CSS_UNIT_PERCENT) return false; - if (r->unit == SP_CSS_UNIT_EM) return false; - if (r->unit == SP_CSS_UNIT_EX) return false; - if (r->unit == SP_CSS_UNIT_PERCENT) return false; + if (unit == SP_CSS_UNIT_EM) + return false; + if (unit == SP_CSS_UNIT_EX) + return false; + if (unit == SP_CSS_UNIT_PERCENT) + return false; + if (r->unit == SP_CSS_UNIT_EM) + return false; + if (r->unit == SP_CSS_UNIT_EX) + return false; + if (r->unit == SP_CSS_UNIT_PERCENT) + return false; - return (computed == r->computed ); + return (computed == r->computed); } else { return false; } @@ -535,73 +536,77 @@ SPILength::operator==(const SPIBase& rhs) { // SPILengthOrNormal ---------------------------------------------------- -void -SPILengthOrNormal::read( gchar const *str ) { - - if( !str ) return; +void SPILengthOrNormal::read(gchar const *str) +{ + if (!str) + return; - if ( !strcmp(str, "normal") ) { + if (!strcmp(str, "normal")) { set = true; inherit = false; unit = SP_CSS_UNIT_NONE; value = computed = 0.0; normal = true; } else { - SPILength::read( str ); + SPILength::read(str); normal = false; } }; const Glib::ustring SPILengthOrNormal::get_value() const { - if (this->normal) return Glib::ustring("normal"); + if (this->normal) + return Glib::ustring("normal"); return SPILength::get_value(); } -void -SPILengthOrNormal::cascade( const SPIBase* const parent ) { - if( const SPILengthOrNormal* p = dynamic_cast<const SPILengthOrNormal*>(parent) ) { - if( (inherits && !set) || inherit ) { - normal = p->normal; +void SPILengthOrNormal::cascade(const SPIBase *const parent) +{ + if (const SPILengthOrNormal *p = dynamic_cast<const SPILengthOrNormal *>(parent)) { + if ((inherits && !set) || inherit) { + normal = p->normal; } - SPILength::cascade( parent ); + SPILength::cascade(parent); } else { std::cerr << "SPILengthOrNormal::cascade(): Incorrect parent type" << std::endl; } } -void -SPILengthOrNormal::merge( const SPIBase* const parent ) { - if( const SPILengthOrNormal* p = dynamic_cast<const SPILengthOrNormal*>(parent) ) { - if( inherits ) { - if( (!set || inherit) && p->set && !(p->inherit) ) { +void SPILengthOrNormal::merge(const SPIBase *const parent) +{ + if (const SPILengthOrNormal *p = dynamic_cast<const SPILengthOrNormal *>(parent)) { + if (inherits) { + if ((!set || inherit) && p->set && !(p->inherit)) { normal = p->normal; - SPILength::merge( parent ); + SPILength::merge(parent); } } } } -bool -SPILengthOrNormal::operator==(const SPIBase& rhs) { - if( const SPILengthOrNormal* r = dynamic_cast<const SPILengthOrNormal*>(&rhs) ) { - if( normal && r->normal ) { return true; } - if( normal != r->normal ) { return false; } +bool SPILengthOrNormal::operator==(const SPIBase &rhs) +{ + if (const SPILengthOrNormal *r = dynamic_cast<const SPILengthOrNormal *>(&rhs)) { + if (normal && r->normal) { + return true; + } + if (normal != r->normal) { + return false; + } return SPILength::operator==(rhs); } else { return false; } } - // SPIFontVariationSettings ---------------------------------------------------- -void -SPIFontVariationSettings::read( gchar const *str ) { - - if( !str ) return; +void SPIFontVariationSettings::read(gchar const *str) +{ + if (!str) + return; - if ( !strcmp(str, "normal") ) { + if (!strcmp(str, "normal")) { set = true; inherit = false; normal = true; @@ -609,7 +614,6 @@ SPIFontVariationSettings::read( gchar const *str ) { return; } - std::vector<Glib::ustring> tokens = Glib::Regex::split_simple(",", str); // Match a pattern of a CSS <string> of length 4, whitespace, CSS <number>. @@ -621,11 +625,11 @@ SPIFontVariationSettings::read( gchar const *str ) { Glib::RefPtr<Glib::Regex> regex = Glib::Regex::create("\"(\\w{4})\"\\s+([-+]?\\d*\\.?\\d+([eE][-+]?\\d+)?)"); Glib::MatchInfo matchInfo; - for (auto token: tokens) { + for (auto token : tokens) { regex->match(token, matchInfo); if (matchInfo.matches()) { float value = std::stod(matchInfo.fetch(2)); - axes.insert(std::pair<Glib::ustring,float>(matchInfo.fetch(1), value)); + axes.insert(std::pair<Glib::ustring, float>(matchInfo.fetch(1), value)); } } @@ -638,46 +642,52 @@ SPIFontVariationSettings::read( gchar const *str ) { const Glib::ustring SPIFontVariationSettings::get_value() const { - if (this->normal) return Glib::ustring("normal"); + if (this->normal) + return Glib::ustring("normal"); auto ret = Glib::ustring(""); - for(auto it: axes) { + for (auto it : axes) { ret += "'" + it.first + "' " + Glib::ustring::format(it.second) + ", "; } - if (!ret.empty()) ret.erase(ret.size() - 2); + if (!ret.empty()) + ret.erase(ret.size() - 2); return ret; } -void -SPIFontVariationSettings::cascade( const SPIBase* const parent ) { - if( const SPIFontVariationSettings* p = dynamic_cast<const SPIFontVariationSettings*>(parent) ) { - if( !set || inherit ) { // Always inherits - normal = p->normal; +void SPIFontVariationSettings::cascade(const SPIBase *const parent) +{ + if (const SPIFontVariationSettings *p = dynamic_cast<const SPIFontVariationSettings *>(parent)) { + if (!set || inherit) { // Always inherits + normal = p->normal; axes.clear(); - axes = p->axes; + axes = p->axes; } } else { std::cerr << "SPIFontVariationSettings::cascade(): Incorrect parent type" << std::endl; } } -void -SPIFontVariationSettings::merge( const SPIBase* const parent ) { - if( const SPIFontVariationSettings* p = dynamic_cast<const SPIFontVariationSettings*>(parent) ) { +void SPIFontVariationSettings::merge(const SPIBase *const parent) +{ + if (const SPIFontVariationSettings *p = dynamic_cast<const SPIFontVariationSettings *>(parent)) { // if( inherits ) { 'font-variation-settings' always inherits. - if( (!set || inherit) && p->set && !(p->inherit) ) { - set = p->set; + if ((!set || inherit) && p->set && !(p->inherit)) { + set = p->set; inherit = p->inherit; - normal = p->normal; - axes = p->axes; + normal = p->normal; + axes = p->axes; } } } -bool -SPIFontVariationSettings::operator==(const SPIBase& rhs) { - if( const SPIFontVariationSettings* r = dynamic_cast<const SPIFontVariationSettings*>(&rhs) ) { - if( normal && r->normal ) { return true; } - if( normal != r->normal ) { return false; } +bool SPIFontVariationSettings::operator==(const SPIBase &rhs) +{ + if (const SPIFontVariationSettings *r = dynamic_cast<const SPIFontVariationSettings *>(&rhs)) { + if (normal && r->normal) { + return true; + } + if (normal != r->normal) { + return false; + } return axes == r->axes; } else { return false; @@ -685,11 +695,10 @@ SPIFontVariationSettings::operator==(const SPIBase& rhs) { } // Generate a string useful for passing to Pango, etc. -const Glib::ustring -SPIFontVariationSettings::toString() const { - +const Glib::ustring SPIFontVariationSettings::toString() const +{ Inkscape::CSSOStringStream os; - for (const auto & axe : axes){ + for (const auto &axe : axes) { os << axe.first << "=" << axe.second << ","; } @@ -704,37 +713,158 @@ SPIFontVariationSettings::toString() const { // Helpers for SPIEnum ----------------------------------------------------- // The default exists to satisfy linking of derived classes but must never be called -template <typename T> static SPStyleEnum const *get_enums() { g_assert_not_reached(); return nullptr; } - -template <> SPStyleEnum const *get_enums<SPBlendMode>() { return enum_blend_mode; } -template <> SPStyleEnum const *get_enums<SPColorInterpolation>() { return enum_color_interpolation; } -template <> SPStyleEnum const *get_enums<SPColorRendering>() { return enum_color_rendering; } -template <> SPStyleEnum const *get_enums<SPCSSBaseline>() { return enum_baseline; } -template <> SPStyleEnum const *get_enums<SPCSSDirection>() { return enum_direction; } -template <> SPStyleEnum const *get_enums<SPCSSDisplay>() { return enum_display; } -template <> SPStyleEnum const *get_enums<SPCSSFontVariantAlternates>() { return enum_font_variant_alternates; } -template <> SPStyleEnum const *get_enums<SPCSSTextAlign>() { return enum_text_align; } -template <> SPStyleEnum const *get_enums<SPCSSTextOrientation>() { return enum_text_orientation; } -template <> SPStyleEnum const *get_enums<SPCSSTextTransform>() { return enum_text_transform; } -template <> SPStyleEnum const *get_enums<SPCSSWritingMode>() { return enum_writing_mode; } -template <> SPStyleEnum const *get_enums<SPEnableBackground>() { return enum_enable_background; } -template <> SPStyleEnum const *get_enums<SPImageRendering>() { return enum_image_rendering; } -template <> SPStyleEnum const *get_enums<SPIsolation>() { return enum_isolation; } -template <> SPStyleEnum const *get_enums<SPOverflow>() { return enum_overflow; } -template <> SPStyleEnum const *get_enums<SPShapeRendering>() { return enum_shape_rendering; } -template <> SPStyleEnum const *get_enums<SPStrokeCapType>() { return enum_stroke_linecap; } -template <> SPStyleEnum const *get_enums<SPStrokeJoinType>() { return enum_stroke_linejoin; } -template <> SPStyleEnum const *get_enums<SPTextAnchor>() { return enum_text_anchor; } -template <> SPStyleEnum const *get_enums<SPTextRendering>() { return enum_text_rendering; } -template <> SPStyleEnum const *get_enums<SPVisibility>() { return enum_visibility; } -template <> SPStyleEnum const *get_enums<SPWhiteSpace>() { return enum_white_space; } -template <> SPStyleEnum const *get_enums<SPWindRule>() { return enum_clip_rule; } -template <> SPStyleEnum const *get_enums<SPCSSFontStyle>() { return enum_font_style; } -template <> SPStyleEnum const *get_enums<SPCSSFontVariant>() { return enum_font_variant; } -template <> SPStyleEnum const *get_enums<SPCSSFontWeight>() { return enum_font_weight; } -template <> SPStyleEnum const *get_enums<SPCSSFontStretch>() { return enum_font_stretch; } -template <> SPStyleEnum const *get_enums<SPCSSFontVariantPosition>() { return enum_font_variant_position; } -template <> SPStyleEnum const *get_enums<SPCSSFontVariantCaps>() { return enum_font_variant_caps; } +template <typename T> +static SPStyleEnum const *get_enums() +{ + g_assert_not_reached(); + return nullptr; +} + +template <> +SPStyleEnum const *get_enums<SPBlendMode>() +{ + return enum_blend_mode; +} +template <> +SPStyleEnum const *get_enums<SPColorInterpolation>() +{ + return enum_color_interpolation; +} +template <> +SPStyleEnum const *get_enums<SPColorRendering>() +{ + return enum_color_rendering; +} +template <> +SPStyleEnum const *get_enums<SPCSSBaseline>() +{ + return enum_baseline; +} +template <> +SPStyleEnum const *get_enums<SPCSSDirection>() +{ + return enum_direction; +} +template <> +SPStyleEnum const *get_enums<SPCSSDisplay>() +{ + return enum_display; +} +template <> +SPStyleEnum const *get_enums<SPCSSFontVariantAlternates>() +{ + return enum_font_variant_alternates; +} +template <> +SPStyleEnum const *get_enums<SPCSSTextAlign>() +{ + return enum_text_align; +} +template <> +SPStyleEnum const *get_enums<SPCSSTextOrientation>() +{ + return enum_text_orientation; +} +template <> +SPStyleEnum const *get_enums<SPCSSTextTransform>() +{ + return enum_text_transform; +} +template <> +SPStyleEnum const *get_enums<SPCSSWritingMode>() +{ + return enum_writing_mode; +} +template <> +SPStyleEnum const *get_enums<SPEnableBackground>() +{ + return enum_enable_background; +} +template <> +SPStyleEnum const *get_enums<SPImageRendering>() +{ + return enum_image_rendering; +} +template <> +SPStyleEnum const *get_enums<SPIsolation>() +{ + return enum_isolation; +} +template <> +SPStyleEnum const *get_enums<SPOverflow>() +{ + return enum_overflow; +} +template <> +SPStyleEnum const *get_enums<SPShapeRendering>() +{ + return enum_shape_rendering; +} +template <> +SPStyleEnum const *get_enums<SPStrokeCapType>() +{ + return enum_stroke_linecap; +} +template <> +SPStyleEnum const *get_enums<SPStrokeJoinType>() +{ + return enum_stroke_linejoin; +} +template <> +SPStyleEnum const *get_enums<SPTextAnchor>() +{ + return enum_text_anchor; +} +template <> +SPStyleEnum const *get_enums<SPTextRendering>() +{ + return enum_text_rendering; +} +template <> +SPStyleEnum const *get_enums<SPVisibility>() +{ + return enum_visibility; +} +template <> +SPStyleEnum const *get_enums<SPWhiteSpace>() +{ + return enum_white_space; +} +template <> +SPStyleEnum const *get_enums<SPWindRule>() +{ + return enum_clip_rule; +} +template <> +SPStyleEnum const *get_enums<SPCSSFontStyle>() +{ + return enum_font_style; +} +template <> +SPStyleEnum const *get_enums<SPCSSFontVariant>() +{ + return enum_font_variant; +} +template <> +SPStyleEnum const *get_enums<SPCSSFontWeight>() +{ + return enum_font_weight; +} +template <> +SPStyleEnum const *get_enums<SPCSSFontStretch>() +{ + return enum_font_stretch; +} +template <> +SPStyleEnum const *get_enums<SPCSSFontVariantPosition>() +{ + return enum_font_variant_position; +} +template <> +SPStyleEnum const *get_enums<SPCSSFontVariantCaps>() +{ + return enum_font_variant_caps; +} // SPIEnum -------------------------------------------------------------- @@ -760,10 +890,10 @@ void SPIEnum<SPCSSFontWeight>::update_computed() template <typename T> void SPIEnum<T>::read(gchar const *str) { + if (!str) + return; - if( !str ) return; - - if( !strcmp(str, "inherit") ) { + if (!strcmp(str, "inherit")) { set = true; inherit = true; } else { @@ -786,10 +916,11 @@ void SPIEnum<T>::read(gchar const *str) template <typename T> const Glib::ustring SPIEnum<T>::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); + if (this->inherit) + return Glib::ustring("inherit"); auto const *enums = get_enums<T>(); for (unsigned i = 0; enums[i].key; ++i) { - if (enums[i].value == static_cast< gint > (this->value) ) { + if (enums[i].value == static_cast<gint>(this->value)) { return Glib::ustring(enums[i].key); } } @@ -824,7 +955,7 @@ template <typename T> void SPIEnum<T>::cascade(const SPIBase *const parent) { if (const auto *p = dynamic_cast<const SPIEnum<T> *>(parent)) { - if( inherits && (!set || inherit) ) { + if (inherits && (!set || inherit)) { computed = p->computed; } else { // type-specialized subroutine @@ -869,12 +1000,12 @@ template <typename T> void SPIEnum<T>::merge(const SPIBase *const parent) { if (const auto *p = dynamic_cast<const SPIEnum<T> *>(parent)) { - if( inherits ) { - if( p->set && !p->inherit ) { - if( !set || inherit ) { - set = p->set; - inherit = p->inherit; - value = p->value; + if (inherits) { + if (p->set && !p->inherit) { + if (!set || inherit) { + set = p->set; + inherit = p->inherit; + value = p->value; computed = p->computed; // Different from value for font-weight and font-stretch } else { // type-specialized subroutine @@ -895,7 +1026,6 @@ bool SPIEnum<T>::operator==(const SPIBase &rhs) } } - #if 0 // SPIEnumBits ---------------------------------------------------------- // Used for 'font-variant-xxx' @@ -936,33 +1066,33 @@ const Glib::ustring SPIEnumBits::get_value() const // SPILigatures ----------------------------------------------------- // Used for 'font-variant-ligatures' -void -SPILigatures::read( gchar const *str ) { - - if( !str ) return; +void SPILigatures::read(gchar const *str) +{ + if (!str) + return; value = SP_CSS_FONT_VARIANT_LIGATURES_NORMAL; - if( !strcmp(str, "inherit") ) { + if (!strcmp(str, "inherit")) { set = true; inherit = true; - } else if (!strcmp(str, "normal" )) { + } else if (!strcmp(str, "normal")) { // Defaults for TrueType inherit = false; set = true; - } else if (!strcmp(str, "none" )) { + } else if (!strcmp(str, "none")) { value = SP_CSS_FONT_VARIANT_LIGATURES_NONE; inherit = false; set = true; } else { // We need to parse in order - std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s+", str ); + std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s+", str); auto const *enums = enum_font_variant_ligatures; - for(auto & token : tokens) { - for (unsigned j = 0; enums[j].key; ++j ) { - if (token.compare( enums[j].key ) == 0 ) { + for (auto &token : tokens) { + for (unsigned j = 0; enums[j].key; ++j) { + if (token.compare(enums[j].key) == 0) { set = true; inherit = false; - if( enums[j].value < SP_CSS_FONT_VARIANT_LIGATURES_NOCOMMON ) { + if (enums[j].value < SP_CSS_FONT_VARIANT_LIGATURES_NOCOMMON) { // Turn on value |= enums[j].value; } else { @@ -980,17 +1110,20 @@ SPILigatures::read( gchar const *str ) { const Glib::ustring SPILigatures::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); - if (this->value == SP_CSS_FONT_VARIANT_LIGATURES_NONE) return Glib::ustring("none"); - if (this->value == SP_CSS_FONT_VARIANT_LIGATURES_NORMAL) return Glib::ustring("normal"); + if (this->inherit) + return Glib::ustring("inherit"); + if (this->value == SP_CSS_FONT_VARIANT_LIGATURES_NONE) + return Glib::ustring("none"); + if (this->value == SP_CSS_FONT_VARIANT_LIGATURES_NORMAL) + return Glib::ustring("normal"); auto ret = Glib::ustring(""); if (!(value & SP_CSS_FONT_VARIANT_LIGATURES_COMMON)) ret += "no-common-ligatures "; if (value & SP_CSS_FONT_VARIANT_LIGATURES_DISCRETIONARY) ret += "discretionary-ligatures "; - if (value & SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL ) + if (value & SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL) ret += "historical-ligatures "; - if ( !(value & SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL) ) + if (!(value & SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL)) ret += "no-contextual "; ret.erase(ret.size() - 1); return ret; @@ -998,32 +1131,32 @@ const Glib::ustring SPILigatures::get_value() const // SPINumeric ----------------------------------------------------- // Used for 'font-variant-numeric' -void -SPINumeric::read( gchar const *str ) { - - if( !str ) return; +void SPINumeric::read(gchar const *str) +{ + if (!str) + return; value = SP_CSS_FONT_VARIANT_NUMERIC_NORMAL; - if( !strcmp(str, "inherit") ) { + if (!strcmp(str, "inherit")) { set = true; inherit = true; - } else if (!strcmp(str, "normal" )) { + } else if (!strcmp(str, "normal")) { // Defaults for TrueType inherit = false; set = true; } else { // We need to parse in order - std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s+", str ); + std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s+", str); auto const *enums = enum_font_variant_numeric; - for(auto & token : tokens) { - for (unsigned j = 0; enums[j].key; ++j ) { - if (token.compare( enums[j].key ) == 0 ) { + for (auto &token : tokens) { + for (unsigned j = 0; enums[j].key; ++j) { + if (token.compare(enums[j].key) == 0) { set = true; inherit = false; - value |= enums[j].value; + value |= enums[j].value; // Must switch off incompatible value - switch (enums[j].value ) { + switch (enums[j].value) { case SP_CSS_FONT_VARIANT_NUMERIC_LINING_NUMS: value &= ~SP_CSS_FONT_VARIANT_NUMERIC_OLDSTYLE_NUMS; break; @@ -1065,14 +1198,17 @@ SPINumeric::read( gchar const *str ) { /* FIXME:: This whole class is bogus and should be an SPIBitEnum TODO */ const Glib::ustring SPINumeric::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); - if (this->value == 0) return Glib::ustring("normal"); + if (this->inherit) + return Glib::ustring("inherit"); + if (this->value == 0) + return Glib::ustring("normal"); auto ret = Glib::ustring(""); auto enums = enum_font_variant_numeric; for (unsigned i = 1; enums[i].key; ++i) { // Bitmap is shifted by 1 because normal is zero if (this->value & (1 << (i - 1))) { - if (!ret.empty()) ret += " "; + if (!ret.empty()) + ret += " "; ret += enums[i].key; } } @@ -1081,31 +1217,31 @@ const Glib::ustring SPINumeric::get_value() const // SPIEastAsian --------------------------------------------------- // Used for 'font-variant-east-asian' -void -SPIEastAsian::read( gchar const *str ) { - - if( !str ) return; +void SPIEastAsian::read(gchar const *str) +{ + if (!str) + return; value = SP_CSS_FONT_VARIANT_EAST_ASIAN_NORMAL; - if( !strcmp(str, "inherit") ) { + if (!strcmp(str, "inherit")) { set = true; inherit = true; - } else if (!strcmp(str, "normal" )) { + } else if (!strcmp(str, "normal")) { // Defaults for TrueType inherit = false; set = true; } else { // We need to parse in order - std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s+", str ); + std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s+", str); auto const *enums = enum_font_variant_east_asian; - for(auto & token : tokens) { - for (unsigned j = 0; enums[j].key; ++j ) { - if (token.compare( enums[j].key ) == 0 ) { + for (auto &token : tokens) { + for (unsigned j = 0; enums[j].key; ++j) { + if (token.compare(enums[j].key) == 0) { set = true; inherit = false; // Must switch off incompatible value (turn on correct one below) - switch (enums[j].value ) { + switch (enums[j].value) { case SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS78: case SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS83: case SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS90: @@ -1137,7 +1273,7 @@ SPIEastAsian::read( gchar const *str ) { break; } - value |= enums[j].value; + value |= enums[j].value; } } } @@ -1147,13 +1283,16 @@ SPIEastAsian::read( gchar const *str ) { const Glib::ustring SPIEastAsian::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); - if (this->value == 0) return Glib::ustring("normal"); + if (this->inherit) + return Glib::ustring("inherit"); + if (this->value == 0) + return Glib::ustring("normal"); auto ret = Glib::ustring(""); auto enums = enum_font_variant_east_asian; for (unsigned i = 0; enums[i].key; ++i) { if (this->value & (1 << i)) { - if (!ret.empty()) ret += " "; + if (!ret.empty()) + ret += " "; ret += enums[i].key; } } @@ -1162,10 +1301,10 @@ const Glib::ustring SPIEastAsian::get_value() const // SPIString ------------------------------------------------------------ -void -SPIString::read( gchar const *str ) { - - if( !str ) return; +void SPIString::read(gchar const *str) +{ + if (!str) + return; clear(); @@ -1185,11 +1324,11 @@ SPIString::read( gchar const *str ) { if (id() == SPAttr::FONT_FAMILY) { // Family names may be quoted in CSS, internally we use unquoted names. str_temp = str; - css_font_family_unquote( str_temp ); + css_font_family_unquote(str_temp); str = str_temp.c_str(); } else if (id() == SPAttr::INKSCAPE_FONT_SPEC) { str_temp = str; - css_unquote( str_temp ); + css_unquote(str_temp); str = str_temp.c_str(); } @@ -1198,7 +1337,6 @@ SPIString::read( gchar const *str ) { } } - /** * Value as it should be written to CSS representation, including quotes if needed. */ @@ -1238,18 +1376,17 @@ char const *SPIString::get_default_value() const } } - -void -SPIString::clear() { +void SPIString::clear() +{ SPIBase::clear(); g_free(_value); _value = nullptr; } -void -SPIString::cascade( const SPIBase* const parent ) { - if( const SPIString* p = dynamic_cast<const SPIString*>(parent) ) { - if( inherits && (!set || inherit) ) { +void SPIString::cascade(const SPIBase *const parent) +{ + if (const SPIString *p = dynamic_cast<const SPIString *>(parent)) { + if (inherits && (!set || inherit)) { g_free(_value); _value = g_strdup(p->_value); } @@ -1258,12 +1395,12 @@ SPIString::cascade( const SPIBase* const parent ) { } } -void -SPIString::merge( const SPIBase* const parent ) { - if( const SPIString* p = dynamic_cast<const SPIString*>(parent) ) { - if( inherits ) { - if( (!set || inherit) && p->set && !(p->inherit) ) { - set = p->set; +void SPIString::merge(const SPIBase *const parent) +{ + if (const SPIString *p = dynamic_cast<const SPIString *>(parent)) { + if (inherits) { + if ((!set || inherit) && p->set && !(p->inherit)) { + set = p->set; inherit = p->inherit; g_free(_value); _value = g_strdup(p->_value); @@ -1272,50 +1409,47 @@ SPIString::merge( const SPIBase* const parent ) { } } -bool -SPIString::operator==(const SPIBase& rhs) { - if( const SPIString* r = dynamic_cast<const SPIString*>(&rhs) ) { +bool SPIString::operator==(const SPIBase &rhs) +{ + if (const SPIString *r = dynamic_cast<const SPIString *>(&rhs)) { return g_strcmp0(_value, r->_value) == 0 && SPIBase::operator==(rhs); } else { return false; } } - // SPIShapes ------------------------------------------------------------ -SPIShapes::~SPIShapes() { +SPIShapes::~SPIShapes() +{ hrefs_clear(); } SPIShapes::SPIShapes() : SPIString(false) -{ -} +{} - -//SPIShapes::~SPIShapes() { +// SPIShapes::~SPIShapes() { // clear(); // Will segfault if called here. Seems to be already cleared. //} - // Used to add/remove listeners for text wrapped in shapes. // Note: this is done differently than for patterns, etc. where presentation attributes can be used. // 'shape-inside' and 'shape-subtract' are only properties. -void -SPIShapes::read( gchar const *str) { - +void SPIShapes::read(gchar const *str) +{ if (!style) { std::cerr << "SPIShapes::read: no style!" << std::endl; return; } - if( !str ) return; + if (!str) + return; SPIString::read(str); // The object/repr this property is connected to.. - SPObject* object = style->object; + SPObject *object = style->object; if (!object) { std::cout << " No object" << std::endl; return; @@ -1326,7 +1460,7 @@ SPIShapes::read( gchar const *str) { // Add new listeners std::vector<Glib::ustring> shapes_url = Glib::Regex::split_simple(" ", str); for (auto shape_url : shapes_url) { - if ( shape_url.compare(0,5,"url(#") != 0 || shape_url.compare(shape_url.size()-1,1,")") != 0 ){ + if (shape_url.compare(0, 5, "url(#") != 0 || shape_url.compare(shape_url.size() - 1, 1, ")") != 0) { std::cerr << "SPIShapes::read: Invalid shape value: " << shape_url << std::endl; } else { auto uri = extract_uri(shape_url.c_str()); // Do before we erase "url(#" @@ -1344,9 +1478,8 @@ SPIShapes::read( gchar const *str) { } } -void -SPIShapes::clear() { - +void SPIShapes::clear() +{ SPIBase::clear(); hrefs_clear(); @@ -1366,23 +1499,24 @@ void SPIShapes::hrefs_clear() // (The last three have yet to be implemented.) // CSS3: 'currentcolor' is allowed value and is equal to inherit for the 'color' property. // FIXME: We should preserve named colors, hsl colors, etc. -void SPIColor::read( gchar const *str ) { - - if( !str ) return; +void SPIColor::read(gchar const *str) +{ + if (!str) + return; set = false; inherit = false; currentcolor = false; - if ( !strcmp(str, "inherit") ) { + if (!strcmp(str, "inherit")) { set = true; inherit = true; - } else if ( !strcmp(str, "currentColor") ) { + } else if (!strcmp(str, "currentColor")) { set = true; currentcolor = true; if (id() == SPAttr::COLOR) { - inherit = true; // CSS3 + inherit = true; // CSS3 } else { - setColor( style->color.value.color ); + setColor(style->color.value.color); } } else { guint32 const rgb0 = sp_svg_read_color(str, 0xff); @@ -1396,50 +1530,50 @@ void SPIColor::read( gchar const *str ) { const Glib::ustring SPIColor::get_value() const { // currentcolor goes first to handle special case for 'color' property - if (this->currentcolor) return Glib::ustring("currentColor"); - if (this->inherit) return Glib::ustring("inherit"); + if (this->currentcolor) + return Glib::ustring("currentColor"); + if (this->inherit) + return Glib::ustring("inherit"); return this->value.color.toString(); } -void -SPIColor::cascade( const SPIBase* const parent ) { - if( const SPIColor* p = dynamic_cast<const SPIColor*>(parent) ) { - if( (inherits && !set) || inherit) { // FIXME verify for 'color' - if( !(inherit && currentcolor) ) currentcolor = p->currentcolor; - setColor( p->value.color ); +void SPIColor::cascade(const SPIBase *const parent) +{ + if (const SPIColor *p = dynamic_cast<const SPIColor *>(parent)) { + if ((inherits && !set) || inherit) { // FIXME verify for 'color' + if (!(inherit && currentcolor)) + currentcolor = p->currentcolor; + setColor(p->value.color); } else { // Add CSS4 Color: Lighter, Darker } } else { std::cerr << "SPIColor::cascade(): Incorrect parent type" << std::endl; } - } -void -SPIColor::merge( const SPIBase* const parent ) { - if( const SPIColor* p = dynamic_cast<const SPIColor*>(parent) ) { - if( inherits ) { - if( (!set || inherit) && p->set && !(p->inherit) ) { - set = p->set; - inherit = p->inherit; - currentcolor = p->currentcolor; - value.color = p->value.color; +void SPIColor::merge(const SPIBase *const parent) +{ + if (const SPIColor *p = dynamic_cast<const SPIColor *>(parent)) { + if (inherits) { + if ((!set || inherit) && p->set && !(p->inherit)) { + set = p->set; + inherit = p->inherit; + currentcolor = p->currentcolor; + value.color = p->value.color; } } } } -bool -SPIColor::operator==(const SPIBase& rhs) { - if( const SPIColor* r = dynamic_cast<const SPIColor*>(&rhs) ) { - - if ( (this->currentcolor != r->currentcolor ) || - (this->value.color != r->value.color ) || - (this->value.color.icc != r->value.color.icc ) || - (this->value.color.icc && r->value.color.icc && - this->value.color.icc->colorProfile != r->value.color.icc->colorProfile && - this->value.color.icc->colors != r->value.color.icc->colors ) ) { +bool SPIColor::operator==(const SPIBase &rhs) +{ + if (const SPIColor *r = dynamic_cast<const SPIColor *>(&rhs)) { + if ((this->currentcolor != r->currentcolor) || (this->value.color != r->value.color) || + (this->value.color.icc != r->value.color.icc) || + (this->value.color.icc && r->value.color.icc && + this->value.color.icc->colorProfile != r->value.color.icc->colorProfile && + this->value.color.icc->colors != r->value.color.icc->colors)) { return false; } @@ -1450,8 +1584,6 @@ SPIColor::operator==(const SPIBase& rhs) { } } - - // SPIPaint ------------------------------------------------------------- // Paint is used for 'fill' and 'stroke'. SPIPaint perhaps should be derived from SPIColor. @@ -1460,8 +1592,9 @@ SPIColor::operator==(const SPIBase& rhs) { // find the object for creating an href (this is done through document but should be done // directly so document not needed.. FIXME). -SPIPaint::~SPIPaint() { - if( value.href ) { +SPIPaint::~SPIPaint() +{ + if (value.href) { clear(); delete value.href; value.href = nullptr; @@ -1473,9 +1606,8 @@ SPIPaint::~SPIPaint() { * * \pre paint == \&style.fill || paint == \&style.stroke. */ -void -SPIPaint::read( gchar const *str ) { - +void SPIPaint::read(gchar const *str) +{ // std::cout << "SPIPaint::read: Entrance: " << " |" << (str?str:"null") << "|" << std::endl; // if( style ) { // std::cout << " document: " << (void*)style->document << std::endl; @@ -1485,9 +1617,10 @@ SPIPaint::read( gchar const *str ) { // << " document: " << (style->object->document?"yes":"no") << std::endl; // } - if(!str ) return; + if (!str) + return; - reset( false ); // Do not init + reset(false); // Do not init // Is this necessary? while (g_ascii_isspace(*str)) { @@ -1500,13 +1633,12 @@ SPIPaint::read( gchar const *str ) { } else { // Read any URL first. The other values can be stand-alone or backup to the URL. - if ( strneq(str, "url", 3) ) { - + if (strneq(str, "url", 3)) { // FIXME: THE FOLLOWING CODE SHOULD BE PUT IN A PRIVATE FUNCTION FOR REUSE auto uri = extract_uri(str, &str); // std::string - if(uri.empty()) { + if (uri.empty()) { std::cerr << "SPIPaint::read: url is empty or invalid" << std::endl; - } else if (!style ) { + } else if (!style) { std::cerr << "SPIPaint::read: url with empty SPStyle pointer" << std::endl; } else { set = true; @@ -1514,7 +1646,6 @@ SPIPaint::read( gchar const *str ) { // Create href if not done already if (!value.href) { - if (style->object) { value.href = new SPPaintServerReference(style->object); } else if (document) { @@ -1525,9 +1656,11 @@ SPIPaint::read( gchar const *str ) { } if (this == &style->fill) { - style->fill_ps_changed_connection = value.href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_fill_paint_server_ref_changed), style)); + style->fill_ps_changed_connection = value.href->changedSignal().connect( + sigc::bind(sigc::ptr_fun(sp_style_fill_paint_server_ref_changed), style)); } else { - style->stroke_ps_changed_connection = value.href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_stroke_paint_server_ref_changed), style)); + style->stroke_ps_changed_connection = value.href->changedSignal().connect( + sigc::bind(sigc::ptr_fun(sp_style_stroke_paint_server_ref_changed), style)); } } @@ -1536,7 +1669,7 @@ SPIPaint::read( gchar const *str ) { } } - while ( g_ascii_isspace(*str) ) { + while (g_ascii_isspace(*str)) { ++str; } @@ -1544,14 +1677,14 @@ SPIPaint::read( gchar const *str ) { set = true; paintOrigin = SP_CSS_PAINT_ORIGIN_CURRENT_COLOR; if (style) { - setColor( style->color.value.color ); + setColor(style->color.value.color); } else { // Normally an SPIPaint is part of an SPStyle and the value of 'color' is // available. SPIPaint can be used 'stand-alone' (e.g. to parse color values) in // which case a value of 'currentColor' is meaningless, thus we shouldn't reach // here. std::cerr << "SPIPaint::read(): value is 'currentColor' but 'color' not available." << std::endl; - setColor( 0 ); + setColor(0); } } else if (streq(str, "context-fill")) { set = true; @@ -1565,15 +1698,15 @@ SPIPaint::read( gchar const *str ) { } else { guint32 const rgb0 = sp_svg_read_color(str, &str, 0xff); if (rgb0 != 0xff) { - setColor( rgb0 ); + setColor(rgb0); set = true; while (g_ascii_isspace(*str)) { ++str; } if (strneq(str, "icc-color(", 10)) { - SVGICCColor* tmp = new SVGICCColor(); - if ( ! sp_svg_read_icc_color( str, &str, tmp ) ) { + SVGICCColor *tmp = new SVGICCColor(); + if (!sp_svg_read_icc_color(str, &str, tmp)) { delete tmp; tmp = nullptr; } @@ -1586,46 +1719,52 @@ SPIPaint::read( gchar const *str ) { // Stand-alone read (Legacy read()), used multiple places, e.g. sp-stop.cpp // This function should not be necessary. FIXME -void -SPIPaint::read( gchar const *str, SPStyle &style_in, SPDocument *document_in ) { +void SPIPaint::read(gchar const *str, SPStyle &style_in, SPDocument *document_in) +{ style = &style_in; style->document = document_in; - read( str ); + read(str); } const Glib::ustring SPIPaint::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); - if (this->noneSet) return Glib::ustring("none"); + if (this->inherit) + return Glib::ustring("inherit"); + if (this->noneSet) + return Glib::ustring("none"); // url must go first as other values can serve as fallbacks auto ret = Glib::ustring(""); if (this->value.href && this->value.href->getURI()) { ret += this->value.href->getURI()->cssStr(); } - switch(this->paintOrigin) { + switch (this->paintOrigin) { case SP_CSS_PAINT_ORIGIN_CURRENT_COLOR: - if (!ret.empty()) ret += " "; + if (!ret.empty()) + ret += " "; ret += "currentColor"; break; case SP_CSS_PAINT_ORIGIN_CONTEXT_FILL: - if (!ret.empty()) ret += " "; + if (!ret.empty()) + ret += " "; ret += "context-fill"; break; case SP_CSS_PAINT_ORIGIN_CONTEXT_STROKE: - if (!ret.empty()) ret += " "; + if (!ret.empty()) + ret += " "; ret += "context-stroke"; break; case SP_CSS_PAINT_ORIGIN_NORMAL: if (this->colorSet) { char color_buf[8]; sp_svg_write_color(color_buf, sizeof(color_buf), this->value.color.toRGBA32(0)); - if (!ret.empty()) ret += " "; + if (!ret.empty()) + ret += " "; ret += color_buf; } if (this->value.color.icc) { ret += " icc-color("; ret += this->value.color.icc->colorProfile; - for(auto i: this->value.color.icc->colors) { + for (auto i : this->value.color.icc->colors) { ret += ", " + Glib::ustring::format(i); } ret += ")"; @@ -1635,27 +1774,26 @@ const Glib::ustring SPIPaint::get_value() const return ret; } -void -SPIPaint::clear() { +void SPIPaint::clear() +{ // std::cout << "SPIPaint::clear(): " << name << std::endl; - reset( true ); // Reset and Init + reset(true); // Reset and Init } -void -SPIPaint::reset( bool init ) { - +void SPIPaint::reset(bool init) +{ // std::cout << "SPIPaint::reset(): " << name << " " << init << std::endl; SPIBase::clear(); paintOrigin = SP_CSS_PAINT_ORIGIN_NORMAL; colorSet = false; noneSet = false; - value.color.set( false ); - if (value.href){ + value.color.set(false); + if (value.href) { if (value.href->getObject()) { value.href->detach(); } } - if( init ) { + if (init) { if (id() == SPAttr::FILL) { // 'black' is default for 'fill' setColor(0.0, 0.0, 0.0); @@ -1665,83 +1803,77 @@ SPIPaint::reset( bool init ) { } } -void -SPIPaint::cascade( const SPIBase* const parent ) { - +void SPIPaint::cascade(const SPIBase *const parent) +{ // std::cout << "SPIPaint::cascade" << std::endl; - if( const SPIPaint* p = dynamic_cast<const SPIPaint*>(parent) ) { - if (!set || inherit) { // Always inherits + if (const SPIPaint *p = dynamic_cast<const SPIPaint *>(parent)) { + if (!set || inherit) { // Always inherits - reset( false ); // Do not init + reset(false); // Do not init - if( p->isPaintserver() ) { - if( p->value.href) { + if (p->isPaintserver()) { + if (p->value.href) { // Why can we use p->document ? - sp_style_set_ipaint_to_uri( style, this, p->value.href->getURI(), p->value.href->getOwnerDocument()); + sp_style_set_ipaint_to_uri(style, this, p->value.href->getURI(), p->value.href->getOwnerDocument()); } else { std::cerr << "SPIPaint::cascade: Expected paint server not found." << std::endl; } - } else if( p->isColor() ) { - setColor( p->value.color ); - } else if( p->isNoneSet() ) { + } else if (p->isColor()) { + setColor(p->value.color); + } else if (p->isNoneSet()) { noneSet = true; - } else if( p->paintOrigin == SP_CSS_PAINT_ORIGIN_CURRENT_COLOR ) { + } else if (p->paintOrigin == SP_CSS_PAINT_ORIGIN_CURRENT_COLOR) { paintOrigin = SP_CSS_PAINT_ORIGIN_CURRENT_COLOR; - setColor( style->color.value.color ); - } else if( isNone() ) { + setColor(style->color.value.color); + } else if (isNone()) { // } else { g_assert_not_reached(); } } else { - if( paintOrigin == SP_CSS_PAINT_ORIGIN_CURRENT_COLOR ) { + if (paintOrigin == SP_CSS_PAINT_ORIGIN_CURRENT_COLOR) { // Update in case color value changed. - setColor( style->color.value.color ); + setColor(style->color.value.color); } } } else { std::cerr << "SPIPaint::cascade(): Incorrect parent type" << std::endl; } - } -void -SPIPaint::merge( const SPIBase* const parent ) { - if( const SPIPaint* p = dynamic_cast<const SPIPaint*>(parent) ) { +void SPIPaint::merge(const SPIBase *const parent) +{ + if (const SPIPaint *p = dynamic_cast<const SPIPaint *>(parent)) { // if( inherits ) { Paint always inherits - if( (!set || inherit) && p->set && !(p->inherit) ) { - this->cascade( parent ); // Must call before setting 'set' - set = p->set; + if ((!set || inherit) && p->set && !(p->inherit)) { + this->cascade(parent); // Must call before setting 'set' + set = p->set; inherit = p->inherit; } } } -bool -SPIPaint::operator==(const SPIBase& rhs) { - - if( const SPIPaint* r = dynamic_cast<const SPIPaint*>(&rhs) ) { - - if ( (this->isColor() != r->isColor() ) || - (this->isPaintserver() != r->isPaintserver() ) || - (this->paintOrigin != r->paintOrigin ) ) { +bool SPIPaint::operator==(const SPIBase &rhs) +{ + if (const SPIPaint *r = dynamic_cast<const SPIPaint *>(&rhs)) { + if ((this->isColor() != r->isColor()) || (this->isPaintserver() != r->isPaintserver()) || + (this->paintOrigin != r->paintOrigin)) { return false; } - if ( this->isPaintserver() ) { - if( this->value.href == nullptr || r->value.href == nullptr || - this->value.href->getObject() != r->value.href->getObject() ) { + if (this->isPaintserver()) { + if (this->value.href == nullptr || r->value.href == nullptr || + this->value.href->getObject() != r->value.href->getObject()) { return false; } } - if ( this->isColor() ) { - if ( (this->value.color != r->value.color ) || - (this->value.color.icc != r->value.color.icc ) || - (this->value.color.icc && r->value.color.icc && - this->value.color.icc->colorProfile != r->value.color.icc->colorProfile && - this->value.color.icc->colors != r->value.color.icc->colors ) ) { + if (this->isColor()) { + if ((this->value.color != r->value.color) || (this->value.color.icc != r->value.color.icc) || + (this->value.color.icc && r->value.color.icc && + this->value.color.icc->colorProfile != r->value.color.icc->colorProfile && + this->value.color.icc->colors != r->value.color.icc->colors)) { return false; } } @@ -1753,14 +1885,12 @@ SPIPaint::operator==(const SPIBase& rhs) { } } - - // SPIPaintOrder -------------------------------------------------------- -void -SPIPaintOrder::read( gchar const *str ) { - - if( !str ) return; +void SPIPaintOrder::read(gchar const *str) +{ + if (!str) + return; g_free(value); set = false; @@ -1778,21 +1908,21 @@ SPIPaintOrder::read( gchar const *str ) { layer_set[0] = true; } else { // This certainly can be done more efficiently - gchar** c = g_strsplit(value, " ", PAINT_ORDER_LAYERS + 1); + gchar **c = g_strsplit(value, " ", PAINT_ORDER_LAYERS + 1); bool used[3] = {false, false, false}; unsigned int i = 0; - for( ; i < PAINT_ORDER_LAYERS; ++i ) { - if( c[i] ) { + for (; i < PAINT_ORDER_LAYERS; ++i) { + if (c[i]) { layer_set[i] = false; - if( !strcmp( c[i], "fill")) { + if (!strcmp(c[i], "fill")) { layer[i] = SP_CSS_PAINT_ORDER_FILL; layer_set[i] = true; used[0] = true; - } else if( !strcmp( c[i], "stroke")) { + } else if (!strcmp(c[i], "stroke")) { layer[i] = SP_CSS_PAINT_ORDER_STROKE; layer_set[i] = true; used[1] = true; - } else if( !strcmp( c[i], "markers")) { + } else if (!strcmp(c[i], "markers")) { layer[i] = SP_CSS_PAINT_ORDER_MARKER; layer_set[i] = true; used[2] = true; @@ -1807,17 +1937,17 @@ SPIPaintOrder::read( gchar const *str ) { g_strfreev(c); // Fill out rest of the layers using the default order - if( !used[0] && i < PAINT_ORDER_LAYERS ) { + if (!used[0] && i < PAINT_ORDER_LAYERS) { layer[i] = SP_CSS_PAINT_ORDER_FILL; layer_set[i] = false; ++i; } - if( !used[1] && i < PAINT_ORDER_LAYERS ) { + if (!used[1] && i < PAINT_ORDER_LAYERS) { layer[i] = SP_CSS_PAINT_ORDER_STROKE; layer_set[i] = false; ++i; } - if( !used[2] && i < PAINT_ORDER_LAYERS ) { + if (!used[2] && i < PAINT_ORDER_LAYERS) { layer[i] = SP_CSS_PAINT_ORDER_MARKER; layer_set[i] = false; } @@ -1827,15 +1957,17 @@ SPIPaintOrder::read( gchar const *str ) { const Glib::ustring SPIPaintOrder::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); + if (this->inherit) + return Glib::ustring("inherit"); auto ret = Glib::ustring(""); - for( unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i ) { + for (unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i) { if (layer_set[i]) { - if (!ret.empty()) ret += " "; + if (!ret.empty()) + ret += " "; switch (this->layer[i]) { case SP_CSS_PAINT_ORDER_NORMAL: ret += "normal"; - assert( i == 0 ); + assert(i == 0); break; case SP_CSS_PAINT_ORDER_FILL: ret += "fill"; @@ -1854,15 +1986,15 @@ const Glib::ustring SPIPaintOrder::get_value() const return ret; } -void -SPIPaintOrder::cascade( const SPIBase* const parent ) { - if( const SPIPaintOrder* p = dynamic_cast<const SPIPaintOrder*>(parent) ) { - if (!set || inherit) { // Always inherits - for( unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i ) { - layer[i] = p->layer[i]; +void SPIPaintOrder::cascade(const SPIBase *const parent) +{ + if (const SPIPaintOrder *p = dynamic_cast<const SPIPaintOrder *>(parent)) { + if (!set || inherit) { // Always inherits + for (unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i) { + layer[i] = p->layer[i]; layer_set[i] = p->layer_set[i]; } - g_free( value ); + g_free(value); value = g_strdup(p->value); } } else { @@ -1870,25 +2002,26 @@ SPIPaintOrder::cascade( const SPIBase* const parent ) { } } -void -SPIPaintOrder::merge( const SPIBase* const parent ) { - if( const SPIPaintOrder* p = dynamic_cast<const SPIPaintOrder*>(parent) ) { +void SPIPaintOrder::merge(const SPIBase *const parent) +{ + if (const SPIPaintOrder *p = dynamic_cast<const SPIPaintOrder *>(parent)) { // if( inherits ) { PaintOrder always inherits - if( (!set || inherit) && p->set && !(p->inherit) ) { - this->cascade( parent ); // Must call be setting 'set' - set = p->set; + if ((!set || inherit) && p->set && !(p->inherit)) { + this->cascade(parent); // Must call be setting 'set' + set = p->set; inherit = p->inherit; } } } -bool -SPIPaintOrder::operator==(const SPIBase& rhs) { - if( const SPIPaintOrder* r = dynamic_cast<const SPIPaintOrder*>(&rhs) ) { - if( layer[0] == SP_CSS_PAINT_ORDER_NORMAL && - r->layer[0] == SP_CSS_PAINT_ORDER_NORMAL ) return SPIBase::operator==(rhs); - for (unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i ) { - if( layer[i] != r->layer[i] ) return false; +bool SPIPaintOrder::operator==(const SPIBase &rhs) +{ + if (const SPIPaintOrder *r = dynamic_cast<const SPIPaintOrder *>(&rhs)) { + if (layer[0] == SP_CSS_PAINT_ORDER_NORMAL && r->layer[0] == SP_CSS_PAINT_ORDER_NORMAL) + return SPIBase::operator==(rhs); + for (unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i) { + if (layer[i] != r->layer[i]) + return false; } return SPIBase::operator==(rhs); } else { @@ -1896,26 +2029,25 @@ SPIPaintOrder::operator==(const SPIBase& rhs) { } } - - // SPIFilter ------------------------------------------------------------ -SPIFilter::~SPIFilter() { - if( href ) { +SPIFilter::~SPIFilter() +{ + if (href) { clear(); delete href; href = nullptr; } } -void -SPIFilter::read( gchar const *str ) { - - if( !str ) return; +void SPIFilter::read(gchar const *str) +{ + if (!str) + return; clear(); - if ( streq(str, "inherit") ) { + if (streq(str, "inherit")) { set = true; inherit = true; } else if (streq(str, "none")) { @@ -1937,7 +2069,7 @@ SPIFilter::read( gchar const *str ) { href = new SPFilterReference(style->object); } // Do we have href now? - if ( href ) { + if (href) { href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_filter_ref_changed), style)); } else { std::cerr << "SPIFilter::read(): Could not allocate 'href'" << std::endl; @@ -1960,26 +2092,27 @@ SPIFilter::read( gchar const *str ) { const Glib::ustring SPIFilter::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); - if (this->href) return this->href->getURI()->cssStr(); + if (this->inherit) + return Glib::ustring("inherit"); + if (this->href) + return this->href->getURI()->cssStr(); return Glib::ustring(""); } -void -SPIFilter::clear() { - +void SPIFilter::clear() +{ SPIBase::clear(); - if( href ) { - if( href->getObject() ) { + if (href) { + if (href->getObject()) { href->detach(); } } } -void -SPIFilter::cascade( const SPIBase* const parent ) { - if( const SPIFilter* p = dynamic_cast<const SPIFilter*>(parent) ) { - if( inherit ) { // Only inherits if 'inherit' true/ +void SPIFilter::cascade(const SPIBase *const parent) +{ + if (const SPIFilter *p = dynamic_cast<const SPIFilter *>(parent)) { + if (inherit) { // Only inherits if 'inherit' true/ // FIXME: This is rather unlikely so ignore for now. (void)p; std::cerr << "SPIFilter::cascade: value 'inherit' not supported." << std::endl; @@ -1991,30 +2124,30 @@ SPIFilter::cascade( const SPIBase* const parent ) { } } -void -SPIFilter::merge( const SPIBase* const parent ) { - if( const SPIFilter* p = dynamic_cast<const SPIFilter*>(parent) ) { +void SPIFilter::merge(const SPIBase *const parent) +{ + if (const SPIFilter *p = dynamic_cast<const SPIFilter *>(parent)) { // The "correct" thing to do is to combine the filter primitives. // The next best thing is to keep any filter on this object. If there // is no filter on this object, then use any filter on the parent. - if( (!set || inherit) && p->href && p->href->getObject() ) { // is the getObject() needed? - set = p->set; + if ((!set || inherit) && p->href && p->href->getObject()) { // is the getObject() needed? + set = p->set; inherit = p->inherit; - if( href ) { + if (href) { // If we already have an href, use it (unlikely but heck...) - if( href->getObject() ) { + if (href->getObject()) { href->detach(); } } else { // If we don't have an href, create it - if( style->document ) { // FIXME + if (style->document) { // FIXME href = new SPFilterReference(style->document); - //href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_filter_ref_changed), style)); + // href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_filter_ref_changed), style)); } else if (style->object) { href = new SPFilterReference(style->object); } } - if( href ) { + if (href) { // If we now have an href, try to attach parent filter try { href->attach(*p->href->getURI()); @@ -2028,9 +2161,9 @@ SPIFilter::merge( const SPIBase* const parent ) { } // FIXME -bool -SPIFilter::operator==(const SPIBase& rhs) { - if( const SPIFilter* r = dynamic_cast<const SPIFilter*>(&rhs) ) { +bool SPIFilter::operator==(const SPIBase &rhs) +{ + if (const SPIFilter *r = dynamic_cast<const SPIFilter *>(&rhs)) { (void)r; return true; } else { @@ -2038,25 +2171,23 @@ SPIFilter::operator==(const SPIBase& rhs) { } } - - // SPIDashArray --------------------------------------------------------- -void -SPIDashArray::read( gchar const *str ) { - - if( !str ) return; +void SPIDashArray::read(gchar const *str) +{ + if (!str) + return; set = true; - if( strcmp( str, "inherit") == 0 ) { + if (strcmp(str, "inherit") == 0) { inherit = true; return; } values.clear(); - if( strcmp(str, "none") == 0) { + if (strcmp(str, "none") == 0) { return; } @@ -2080,33 +2211,37 @@ SPIDashArray::read( gchar const *str ) { const Glib::ustring SPIDashArray::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); - if (this->values.empty()) return Glib::ustring("none"); + if (this->inherit) + return Glib::ustring("inherit"); + if (this->values.empty()) + return Glib::ustring("none"); auto ret = Glib::ustring(""); - for(auto value: this->values) { - if (!ret.empty()) ret += ", "; + for (auto value : this->values) { + if (!ret.empty()) + ret += ", "; ret += value.toString(); } return ret; } -void -SPIDashArray::cascade( const SPIBase* const parent ) { - if( const SPIDashArray* p = dynamic_cast<const SPIDashArray*>(parent) ) { - if( !set || inherit ) values = p->values; // Always inherits +void SPIDashArray::cascade(const SPIBase *const parent) +{ + if (const SPIDashArray *p = dynamic_cast<const SPIDashArray *>(parent)) { + if (!set || inherit) + values = p->values; // Always inherits } else { std::cerr << "SPIDashArray::cascade(): Incorrect parent type" << std::endl; } } -void -SPIDashArray::merge( const SPIBase* const parent ) { - if( const SPIDashArray* p = dynamic_cast<const SPIDashArray*>(parent) ) { - if( inherits ) { - if( (!set || inherit) && p->set && !(p->inherit) ) { - set = p->set; +void SPIDashArray::merge(const SPIBase *const parent) +{ + if (const SPIDashArray *p = dynamic_cast<const SPIDashArray *>(parent)) { + if (inherits) { + if ((!set || inherit) && p->set && !(p->inherit)) { + set = p->set; inherit = p->inherit; - values = p->values; + values = p->values; } } } else { @@ -2114,8 +2249,8 @@ SPIDashArray::merge( const SPIBase* const parent ) { } } -bool -SPIDashArray::operator==(const SPIBase& rhs) { +bool SPIDashArray::operator==(const SPIBase &rhs) +{ if (const SPIDashArray *r = dynamic_cast<const SPIDashArray *>(&rhs)) { if (values.size() != r->values.size()) { return false; @@ -2129,17 +2264,16 @@ SPIDashArray::operator==(const SPIBase& rhs) { return SPIBase::operator==(rhs); } - // SPIFontSize ---------------------------------------------------------- /** Indexed by SP_CSS_FONT_SIZE_blah. These seem a bit small */ float const SPIFontSize::font_size_table[] = {6.0, 8.0, 10.0, 12.0, 14.0, 18.0, 24.0}; float const SPIFontSize::font_size_default = 12.0; -void -SPIFontSize::read( gchar const *str ) { - - if( !str ) return; +void SPIFontSize::read(gchar const *str) +{ + if (!str) + return; if (!strcmp(str, "inherit")) { set = true; @@ -2160,19 +2294,21 @@ SPIFontSize::read( gchar const *str ) { } else { SPILength length; length.set = false; - length.read( str ); - if( length.set ) { - set = true; - inherit = length.inherit; - unit = length.unit; - value = length.value; + length.read(str); + if (length.set) { + set = true; + inherit = length.inherit; + unit = length.unit; + value = length.value; computed = length.computed; - /* Set a minimum font size to something much smaller than should ever (ever!) be encountered in a real file. - If a bad SVG file is encountered and this is zero odd things - might happen because the inverse is used in some scaling actions. + /* Set a minimum font size to something much smaller than should ever (ever!) be encountered in a real + file. If a bad SVG file is encountered and this is zero odd things might happen because the inverse is + used in some scaling actions. */ - if ( computed <= 1.0e-32 ) { computed = 1.0e-32; } - if( unit == SP_CSS_UNIT_PERCENT ) { + if (computed <= 1.0e-32) { + computed = 1.0e-32; + } + if (unit == SP_CSS_UNIT_PERCENT) { type = SP_FONT_SIZE_PERCENTAGE; } else { type = SP_FONT_SIZE_LENGTH; @@ -2184,15 +2320,17 @@ SPIFontSize::read( gchar const *str ) { const Glib::ustring SPIFontSize::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); + if (this->inherit) + return Glib::ustring("inherit"); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int unit = prefs->getInt("/options/font/unitType", SP_CSS_UNIT_PT); auto ret = Glib::ustring(""); switch (this->type) { case SP_FONT_SIZE_LITERAL: for (unsigned i = 0; enum_font_size[i].key; i++) { - if (enum_font_size[i].value == static_cast< gint > (this->literal) ) { - if (!ret.empty()) ret += " "; + if (enum_font_size[i].value == static_cast<gint>(this->literal)) { + if (!ret.empty()) + ret += " "; ret += enum_font_size[i].key; } } @@ -2212,29 +2350,29 @@ const Glib::ustring SPIFontSize::get_value() const return ret; } -void -SPIFontSize::cascade( const SPIBase* const parent ) { - if( const SPIFontSize* p = dynamic_cast<const SPIFontSize*>(parent) ) { - if( !set || inherit ) { // Always inherits - computed = p->computed;value = p->value; - +void SPIFontSize::cascade(const SPIBase *const parent) +{ + if (const SPIFontSize *p = dynamic_cast<const SPIFontSize *>(parent)) { + if (!set || inherit) { // Always inherits + computed = p->computed; + value = p->value; - // Calculate computed based on parent as needed - } else if( type == SP_FONT_SIZE_LITERAL ) { - if( literal < SP_CSS_FONT_SIZE_SMALLER ) { - computed = font_size_table[ literal ]; - } else if( literal == SP_CSS_FONT_SIZE_SMALLER ) { + // Calculate computed based on parent as needed + } else if (type == SP_FONT_SIZE_LITERAL) { + if (literal < SP_CSS_FONT_SIZE_SMALLER) { + computed = font_size_table[literal]; + } else if (literal == SP_CSS_FONT_SIZE_SMALLER) { computed = p->computed / 1.2; - } else if( literal == SP_CSS_FONT_SIZE_LARGER ) { + } else if (literal == SP_CSS_FONT_SIZE_LARGER) { computed = p->computed * 1.2; } else { std::cerr << "SPIFontSize::cascade: Illegal literal value" << std::endl; } - } else if( type == SP_FONT_SIZE_PERCENTAGE ) { + } else if (type == SP_FONT_SIZE_PERCENTAGE) { // Percentage for font size is relative to parent computed (rather than viewport) computed = p->computed * value; - } else if( type == SP_FONT_SIZE_LENGTH ) { - switch ( unit ) { + } else if (type == SP_FONT_SIZE_LENGTH) { + switch (unit) { case SP_CSS_UNIT_EM: /* Relative to parent font size */ computed = p->computed * value; @@ -2252,15 +2390,16 @@ SPIFontSize::cascade( const SPIBase* const parent ) { If a bad SVG file is encountered and this is zero odd things might happen because the inverse is used in some scaling actions. */ - if ( computed <= 1.0e-32 ) { computed = 1.0e-32; } + if (computed <= 1.0e-32) { + computed = 1.0e-32; + } } else { std::cerr << "SPIFontSize::cascade(): Incorrect parent type" << std::endl; } } -double -SPIFontSize::relative_fraction() const { - +double SPIFontSize::relative_fraction() const +{ switch (type) { case SP_FONT_SIZE_LITERAL: { switch (literal) { @@ -2279,7 +2418,7 @@ SPIFontSize::relative_fraction() const { return value; case SP_FONT_SIZE_LENGTH: { - switch (unit ) { + switch (unit) { case SP_CSS_UNIT_EM: return value; @@ -2294,48 +2433,42 @@ SPIFontSize::relative_fraction() const { g_assert_not_reached(); } -void -SPIFontSize::merge( const SPIBase* const parent ) { - if( const SPIFontSize* p = dynamic_cast<const SPIFontSize*>(parent) ) { - if( p->set && !(p->inherit) ) { +void SPIFontSize::merge(const SPIBase *const parent) +{ + if (const SPIFontSize *p = dynamic_cast<const SPIFontSize *>(parent)) { + if (p->set && !(p->inherit)) { // Parent has definined font-size - if( (!set || inherit) ) { + if ((!set || inherit)) { // Computed value same as parent - set = p->set; - inherit = p->inherit; - type = p->type; - unit = p->unit; - literal = p->literal; - value = p->value; + set = p->set; + inherit = p->inherit; + type = p->type; + unit = p->unit; + literal = p->literal; + value = p->value; computed = p->computed; // Just to be sure - } else if ( type == SP_FONT_SIZE_LENGTH && - unit != SP_CSS_UNIT_EM && - unit != SP_CSS_UNIT_EX ) { + } else if (type == SP_FONT_SIZE_LENGTH && unit != SP_CSS_UNIT_EM && unit != SP_CSS_UNIT_EX) { // Absolute size, computed value already set - } else if ( type == SP_FONT_SIZE_LITERAL && - literal < SP_CSS_FONT_SIZE_SMALLER ) { + } else if (type == SP_FONT_SIZE_LITERAL && literal < SP_CSS_FONT_SIZE_SMALLER) { // Absolute size, computed value already set - //g_assert( literal < G_N_ELEMENTS(font_size_table) ); - g_assert( computed == font_size_table[literal] ); + // g_assert( literal < G_N_ELEMENTS(font_size_table) ); + g_assert(computed == font_size_table[literal]); } else { // Relative size - double const child_frac( relative_fraction() ); + double const child_frac(relative_fraction()); set = true; inherit = false; computed = p->computed * child_frac; - if ( ( p->type == SP_FONT_SIZE_LITERAL && - p->literal < SP_CSS_FONT_SIZE_SMALLER ) || - ( p->type == SP_FONT_SIZE_LENGTH && - p->unit != SP_CSS_UNIT_EM && - p->unit != SP_CSS_UNIT_EX ) ) { + if ((p->type == SP_FONT_SIZE_LITERAL && p->literal < SP_CSS_FONT_SIZE_SMALLER) || + (p->type == SP_FONT_SIZE_LENGTH && p->unit != SP_CSS_UNIT_EM && p->unit != SP_CSS_UNIT_EX)) { // Parent absolute size type = SP_FONT_SIZE_LENGTH; } else { // Parent relative size - double const parent_frac( p->relative_fraction() ); - if( type == SP_FONT_SIZE_LENGTH ) { + double const parent_frac(p->relative_fraction()); + if (type == SP_FONT_SIZE_LENGTH) { // ex/em value *= parent_frac; } else { @@ -2344,11 +2477,13 @@ SPIFontSize::merge( const SPIBase* const parent ) { } } } // Relative size - /* Set a minimum font size to something much smaller than should ever (ever!) be encountered in a real file. - If a bad SVG file is encountered and this is zero odd things - might happen because the inverse is used in some scaling actions. + /* Set a minimum font size to something much smaller than should ever (ever!) be encountered in a real + file. If a bad SVG file is encountered and this is zero odd things might happen because the inverse is + used in some scaling actions. */ - if ( computed <= 1.0e-32 ) { computed = 1.0e-32; } + if (computed <= 1.0e-32) { + computed = 1.0e-32; + } } // Parent set and not inherit } else { std::cerr << "SPIFontSize::merge(): Incorrect parent type" << std::endl; @@ -2356,16 +2491,24 @@ SPIFontSize::merge( const SPIBase* const parent ) { } // What about different SVG units? -bool -SPIFontSize::operator==(const SPIBase& rhs) { - if( const SPIFontSize* r = dynamic_cast<const SPIFontSize*>(&rhs) ) { - if( type != r->type ) { return false;} - if( type == SP_FONT_SIZE_LENGTH ) { - if( computed != r->computed ) { return false;} - } else if (type == SP_FONT_SIZE_LITERAL ) { - if( literal != r->literal ) { return false;} +bool SPIFontSize::operator==(const SPIBase &rhs) +{ + if (const SPIFontSize *r = dynamic_cast<const SPIFontSize *>(&rhs)) { + if (type != r->type) { + return false; + } + if (type == SP_FONT_SIZE_LENGTH) { + if (computed != r->computed) { + return false; + } + } else if (type == SP_FONT_SIZE_LITERAL) { + if (literal != r->literal) { + return false; + } } else { - if( value != r->value ) { return false;} + if (value != r->value) { + return false; + } } return SPIBase::operator==(rhs); } else { @@ -2373,79 +2516,75 @@ SPIFontSize::operator==(const SPIBase& rhs) { } } - - // SPIFont ---------------------------------------------------------- -void -SPIFont::read( gchar const *str ) { - - if( !str ) return; +void SPIFont::read(gchar const *str) +{ + if (!str) + return; - if( !style ) { + if (!style) { std::cerr << "SPIFont::read(): style is void" << std::endl; return; } - if ( !strcmp(str, "inherit") ) { + if (!strcmp(str, "inherit")) { set = true; inherit = true; } else { - // Break string into white space separated tokens - std::stringstream os( str ); + std::stringstream os(str); Glib::ustring param; while (os >> param) { - // CSS is case insensitive but we're comparing against lowercase strings Glib::ustring lparam = param.lowercase(); - if (lparam == "/" ) { + if (lparam == "/") { // line_height follows... note: font-size already read os >> param; lparam = param.lowercase(); - style->line_height.readIfUnset( lparam.c_str() ); + style->line_height.readIfUnset(lparam.c_str()); } else { // Try to parse each property in turn decltype(style->font_style) test_style; - test_style.read( lparam.c_str() ); - if( test_style.set ) { + test_style.read(lparam.c_str()); + if (test_style.set) { style->font_style = test_style; continue; } // font-variant (Note: only CSS2.1 value small-caps is valid in shortcut.) decltype(style->font_variant) test_variant; - test_variant.read( lparam.c_str() ); - if( test_variant.set ) { + test_variant.read(lparam.c_str()); + if (test_variant.set) { style->font_variant = test_variant; continue; } // font-weight decltype(style->font_weight) test_weight; - test_weight.read( lparam.c_str() ); - if( test_weight.set ) { + test_weight.read(lparam.c_str()); + if (test_weight.set) { style->font_weight = test_weight; continue; } // font-stretch (added in CSS 3 Fonts) decltype(style->font_stretch) test_stretch; - test_stretch.read( lparam.c_str() ); - if( test_stretch.set ) { + test_stretch.read(lparam.c_str()); + if (test_stretch.set) { style->font_stretch = test_stretch; continue; } // font-size decltype(style->font_size) test_size; - test_size.read( lparam.c_str() ); - if( test_size.set ) { + test_size.read(lparam.c_str()); + if (test_size.set) { style->font_size = test_size; continue; } @@ -2457,9 +2596,9 @@ SPIFont::read( gchar const *str ) { // The rest must be font-family... std::string str_s = str; // Why this extra step? - std::string family = str_s.substr( str_s.find( param ) ); + std::string family = str_s.substr(str_s.find(param)); - style->font_family.readIfUnset( family.c_str() ); + style->font_family.readIfUnset(family.c_str()); // Everything in shorthand is set per CSS rules, this works since // properties are read backwards from end to start. @@ -2478,7 +2617,8 @@ SPIFont::read( gchar const *str ) { const Glib::ustring SPIFont::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); + if (this->inherit) + return Glib::ustring("inherit"); // At the moment, do nothing. We could add a preference to write out // 'font' shorthand rather than longhand properties. /* SPIFontSize const *const my_base = dynamic_cast<const SPIFontSize*>(base); @@ -2501,23 +2641,21 @@ const Glib::ustring SPIFont::get_value() const // } // Does nothing... -bool -SPIFont::operator==(const SPIBase& rhs) { - if( /* const SPIFont* r = */ dynamic_cast<const SPIFont*>(&rhs) ) { +bool SPIFont::operator==(const SPIBase &rhs) +{ + if (/* const SPIFont* r = */ dynamic_cast<const SPIFont *>(&rhs)) { return SPIBase::operator==(rhs); } else { return false; } } - - // SPIBaselineShift ----------------------------------------------------- -void -SPIBaselineShift::read( gchar const *str ) { - - if( !str ) return; +void SPIBaselineShift::read(gchar const *str) +{ + if (!str) + return; if (!strcmp(str, "inherit")) { set = true; @@ -2537,13 +2675,13 @@ SPIBaselineShift::read( gchar const *str ) { return; } else { SPILength length; - length.read( str ); - set = length.set; - inherit = length.inherit; - unit = length.unit; - value = length.value; + length.read(str); + set = length.set; + inherit = length.inherit; + unit = length.unit; + value = length.value; computed = length.computed; - if( unit == SP_CSS_UNIT_PERCENT ) { + if (unit == SP_CSS_UNIT_PERCENT) { type = SP_BASELINE_SHIFT_PERCENTAGE; } else { type = SP_BASELINE_SHIFT_LENGTH; @@ -2554,19 +2692,21 @@ SPIBaselineShift::read( gchar const *str ) { const Glib::ustring SPIBaselineShift::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); + if (this->inherit) + return Glib::ustring("inherit"); auto ret = Glib::ustring(""); switch (this->type) { case SP_BASELINE_SHIFT_LITERAL: for (unsigned i = 0; enum_baseline_shift[i].key; i++) { - if (enum_baseline_shift[i].value == static_cast< gint > (this->literal) ) { - if (!ret.empty()) ret += " "; + if (enum_baseline_shift[i].value == static_cast<gint>(this->literal)) { + if (!ret.empty()) + ret += " "; ret += enum_baseline_shift[i].key; } } break; case SP_BASELINE_SHIFT_LENGTH: - if( this->unit == SP_CSS_UNIT_EM || this->unit == SP_CSS_UNIT_EX ) { + if (this->unit == SP_CSS_UNIT_EM || this->unit == SP_CSS_UNIT_EX) { ret += Glib::ustring::format(this->value); ret += (this->unit == SP_CSS_UNIT_EM ? "em" : "ex"); } else { @@ -2580,25 +2720,25 @@ const Glib::ustring SPIBaselineShift::get_value() const return ret; } -void -SPIBaselineShift::cascade( const SPIBase* const parent ) { - if( const SPIBaselineShift* p = dynamic_cast<const SPIBaselineShift*>(parent) ) { +void SPIBaselineShift::cascade(const SPIBase *const parent) +{ + if (const SPIBaselineShift *p = dynamic_cast<const SPIBaselineShift *>(parent)) { SPIFontSize *pfont_size = &(p->style->font_size); - g_assert( pfont_size != nullptr ); + g_assert(pfont_size != nullptr); - if( !set || inherit ) { - computed = p->computed; // Shift relative to parent shift, corrected below + if (!set || inherit) { + computed = p->computed; // Shift relative to parent shift, corrected below } else if (type == SP_BASELINE_SHIFT_LITERAL) { - if( literal == SP_CSS_BASELINE_SHIFT_BASELINE ) { + if (literal == SP_CSS_BASELINE_SHIFT_BASELINE) { computed = 0; // No change - } else if (literal == SP_CSS_BASELINE_SHIFT_SUB ) { + } else if (literal == SP_CSS_BASELINE_SHIFT_SUB) { // Should use subscript position from font relative to alphabetic baseline // OpenOffice, Adobe: -0.33, Word -0.14, LaTex about -0.2. computed = -0.2 * pfont_size->computed; - } else if (literal == SP_CSS_BASELINE_SHIFT_SUPER ) { + } else if (literal == SP_CSS_BASELINE_SHIFT_SUPER) { // Should use superscript position from font relative to alphabetic baseline // OpenOffice, Adobe: 0.33, Word 0.35, LaTex about 0.45. - computed = 0.4 * pfont_size->computed; + computed = 0.4 * pfont_size->computed; } else { /* Illegal value */ } @@ -2629,13 +2769,13 @@ SPIBaselineShift::cascade( const SPIBase* const parent ) { // This was not defined in the legacy C code, it needs some serious thinking (but is low priority). // FIX ME -void -SPIBaselineShift::merge( const SPIBase* const parent ) { - if( const SPIBaselineShift* p = dynamic_cast<const SPIBaselineShift*>(parent) ) { - if( (!set || inherit) && p->set && !(p->inherit) ) { - set = p->set; +void SPIBaselineShift::merge(const SPIBase *const parent) +{ + if (const SPIBaselineShift *p = dynamic_cast<const SPIBaselineShift *>(parent)) { + if ((!set || inherit) && p->set && !(p->inherit)) { + set = p->set; inherit = p->inherit; - value = p->value; + value = p->value; } } else { std::cerr << "SPIBaselineShift::merge(): Incorrect parent type" << std::endl; @@ -2643,16 +2783,20 @@ SPIBaselineShift::merge( const SPIBase* const parent ) { } // This is not used but we have it for completeness, it has not been tested. -bool -SPIBaselineShift::operator==(const SPIBase& rhs) { - if( const SPIBaselineShift* r = dynamic_cast<const SPIBaselineShift*>(&rhs) ) { - if( type != r->type ) return false; - if( type == SP_BASELINE_SHIFT_LENGTH ) { - if( computed != r->computed ) return false; - } else if ( type == SP_BASELINE_SHIFT_LITERAL ) { - if( literal != r->literal ) return false; +bool SPIBaselineShift::operator==(const SPIBase &rhs) +{ + if (const SPIBaselineShift *r = dynamic_cast<const SPIBaselineShift *>(&rhs)) { + if (type != r->type) + return false; + if (type == SP_BASELINE_SHIFT_LENGTH) { + if (computed != r->computed) + return false; + } else if (type == SP_BASELINE_SHIFT_LITERAL) { + if (literal != r->literal) + return false; } else { - if( value != r->value ) return false; + if (value != r->value) + return false; } return SPIBase::operator==(rhs); } else { @@ -2660,286 +2804,313 @@ SPIBaselineShift::operator==(const SPIBase& rhs) { } } -bool -SPIBaselineShift::isZero() const { - if( type == SP_BASELINE_SHIFT_LITERAL ) { - if( literal == SP_CSS_BASELINE_SHIFT_BASELINE ) return true; +bool SPIBaselineShift::isZero() const +{ + if (type == SP_BASELINE_SHIFT_LITERAL) { + if (literal == SP_CSS_BASELINE_SHIFT_BASELINE) + return true; } else { - if( value == 0.0 ) return true; + if (value == 0.0) + return true; } return false; } - - // SPITextDecorationLine ------------------------------------------------ -void -SPITextDecorationLine::read( gchar const *str ) { - - if( !str ) return; +void SPITextDecorationLine::read(gchar const *str) +{ + if (!str) + return; if (!strcmp(str, "inherit")) { - set = true; - inherit = true; + set = true; + inherit = true; } else if (!strcmp(str, "none")) { - set = true; - inherit = false; - underline = false; - overline = false; + set = true; + inherit = false; + underline = false; + overline = false; line_through = false; - blink = false; + blink = false; } else { - bool found_one = false; - bool hit_one = false; + bool found_one = false; + bool hit_one = false; // CSS 2 keywords - bool found_underline = false; - bool found_overline = false; + bool found_underline = false; + bool found_overline = false; bool found_line_through = false; - bool found_blink = false; + bool found_blink = false; // This method ignores inlineid keys and extra delimiters, so " ,,, blink hello" will set // blink and ignore hello const gchar *hstr = str; while (true) { - if (*str == ' ' || *str == ',' || *str == '\0'){ + if (*str == ' ' || *str == ',' || *str == '\0') { int slen = str - hstr; // CSS 2 keywords - while(true){ // not really a loop, used to avoid a goto + while (true) { // not really a loop, used to avoid a goto hit_one = true; // most likely we will - if ((slen == 9) && strneq(hstr, "underline", slen)){ found_underline = true; break; } - if ((slen == 8) && strneq(hstr, "overline", slen)){ found_overline = true; break; } - if ((slen == 12) && strneq(hstr, "line-through", slen)){ found_line_through = true; break; } - if ((slen == 5) && strneq(hstr, "blink", slen)){ found_blink = true; break; } - if ((slen == 4) && strneq(hstr, "none", slen)){ break; } + if ((slen == 9) && strneq(hstr, "underline", slen)) { + found_underline = true; + break; + } + if ((slen == 8) && strneq(hstr, "overline", slen)) { + found_overline = true; + break; + } + if ((slen == 12) && strneq(hstr, "line-through", slen)) { + found_line_through = true; + break; + } + if ((slen == 5) && strneq(hstr, "blink", slen)) { + found_blink = true; + break; + } + if ((slen == 4) && strneq(hstr, "none", slen)) { + break; + } hit_one = false; // whatever this thing is, we do not recognize it break; } found_one |= hit_one; - if(*str == '\0')break; + if (*str == '\0') + break; hstr = str + 1; } str++; } if (found_one) { - set = true; - inherit = false; - underline = found_underline; - overline = found_overline; + set = true; + inherit = false; + underline = found_underline; + overline = found_overline; line_through = found_line_through; - blink = found_blink; - } - else { - set = false; - inherit = false; + blink = found_blink; + } else { + set = false; + inherit = false; } } } const Glib::ustring SPITextDecorationLine::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); + if (this->inherit) + return Glib::ustring("inherit"); auto ret = Glib::ustring(""); - if (this->underline) ret += " underline"; - if (this->overline) ret += " overline"; - if (this->line_through) ret += " line-through"; - if (this->blink) ret += " blink"; // Deprecated - if (ret.empty()) ret += "none"; + if (this->underline) + ret += " underline"; + if (this->overline) + ret += " overline"; + if (this->line_through) + ret += " line-through"; + if (this->blink) + ret += " blink"; // Deprecated + if (ret.empty()) + ret += "none"; return ret; } -void -SPITextDecorationLine::cascade( const SPIBase* const parent ) { - if( const SPITextDecorationLine* p = dynamic_cast<const SPITextDecorationLine*>(parent) ) { - if( inherits && (!set || inherit) ) { - underline = p->underline; - overline = p->overline; +void SPITextDecorationLine::cascade(const SPIBase *const parent) +{ + if (const SPITextDecorationLine *p = dynamic_cast<const SPITextDecorationLine *>(parent)) { + if (inherits && (!set || inherit)) { + underline = p->underline; + overline = p->overline; line_through = p->line_through; - blink = p->blink; + blink = p->blink; } } else { std::cerr << "SPITextDecorationLine::cascade(): Incorrect parent type" << std::endl; } } -void -SPITextDecorationLine::merge( const SPIBase* const parent ) { - if( const SPITextDecorationLine* p = dynamic_cast<const SPITextDecorationLine*>(parent) ) { - if( inherits ) { // Always inherits... but special rules? - if( (!set || inherit) && p->set && !(p->inherit) ) { - set = p->set; - inherit = p->inherit; - underline = p->underline; - overline = p->overline; +void SPITextDecorationLine::merge(const SPIBase *const parent) +{ + if (const SPITextDecorationLine *p = dynamic_cast<const SPITextDecorationLine *>(parent)) { + if (inherits) { // Always inherits... but special rules? + if ((!set || inherit) && p->set && !(p->inherit)) { + set = p->set; + inherit = p->inherit; + underline = p->underline; + overline = p->overline; line_through = p->line_through; - blink = p->blink; + blink = p->blink; } } } } -bool -SPITextDecorationLine::operator==(const SPIBase& rhs) { - if( const SPITextDecorationLine* r = dynamic_cast<const SPITextDecorationLine*>(&rhs) ) { - return - (underline == r->underline ) && - (overline == r->overline ) && - (line_through == r->line_through ) && - (blink == r->blink ) && - SPIBase::operator==(rhs); +bool SPITextDecorationLine::operator==(const SPIBase &rhs) +{ + if (const SPITextDecorationLine *r = dynamic_cast<const SPITextDecorationLine *>(&rhs)) { + return (underline == r->underline) && (overline == r->overline) && (line_through == r->line_through) && + (blink == r->blink) && SPIBase::operator==(rhs); } else { return false; } } - - // SPITextDecorationStyle ----------------------------------------------- -void -SPITextDecorationStyle::read( gchar const *str ) { - - if( !str ) return; +void SPITextDecorationStyle::read(gchar const *str) +{ + if (!str) + return; - set = false; - inherit = false; + set = false; + inherit = false; - solid = true; // Default - isdouble = false; - dotted = false; - dashed = false; - wavy = false; + solid = true; // Default + isdouble = false; + dotted = false; + dashed = false; + wavy = false; if (!strcmp(str, "inherit")) { - set = true; - inherit = true; - solid = false; + set = true; + inherit = true; + solid = false; } else { // note, these are CSS 3 keywords - bool found_solid = false; - bool found_double = false; - bool found_dotted = false; - bool found_dashed = false; - bool found_wavy = false; - bool found_one = false; + bool found_solid = false; + bool found_double = false; + bool found_dotted = false; + bool found_dashed = false; + bool found_wavy = false; + bool found_one = false; // this method ignores inlineid keys and extra delimiters, so " ,,, style hello" will set style and ignore hello // if more than one style is present, the first is used const gchar *hstr = str; while (true) { - if (*str == ' ' || *str == ',' || *str == '\0'){ + if (*str == ' ' || *str == ',' || *str == '\0') { int slen = str - hstr; - if ( (slen == 5) && strneq(hstr, "solid", slen)){ found_solid = true; found_one = true; break; } - else if ((slen == 6) && strneq(hstr, "double", slen)){ found_double = true; found_one = true; break; } - else if ((slen == 6) && strneq(hstr, "dotted", slen)){ found_dotted = true; found_one = true; break; } - else if ((slen == 6) && strneq(hstr, "dashed", slen)){ found_dashed = true; found_one = true; break; } - else if ((slen == 4) && strneq(hstr, "wavy", slen)){ found_wavy = true; found_one = true; break; } - if(*str == '\0')break; // nothing more to test + if ((slen == 5) && strneq(hstr, "solid", slen)) { + found_solid = true; + found_one = true; + break; + } else if ((slen == 6) && strneq(hstr, "double", slen)) { + found_double = true; + found_one = true; + break; + } else if ((slen == 6) && strneq(hstr, "dotted", slen)) { + found_dotted = true; + found_one = true; + break; + } else if ((slen == 6) && strneq(hstr, "dashed", slen)) { + found_dashed = true; + found_one = true; + break; + } else if ((slen == 4) && strneq(hstr, "wavy", slen)) { + found_wavy = true; + found_one = true; + break; + } + if (*str == '\0') + break; // nothing more to test hstr = str + 1; } str++; } - if(found_one){ - set = true; - solid = found_solid; - isdouble = found_double; - dotted = found_dotted; - dashed = found_dashed; - wavy = found_wavy; - } - else { - set = false; - inherit = false; + if (found_one) { + set = true; + solid = found_solid; + isdouble = found_double; + dotted = found_dotted; + dashed = found_dashed; + wavy = found_wavy; + } else { + set = false; + inherit = false; } } } const Glib::ustring SPITextDecorationStyle::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); - if (this->solid) return Glib::ustring("solid"); - if (this->isdouble) return Glib::ustring("double"); - if (this->dotted) return Glib::ustring("dotted"); - if (this->dashed) return Glib::ustring("dashed"); - if (this->wavy) return Glib::ustring("wavy"); + if (this->inherit) + return Glib::ustring("inherit"); + if (this->solid) + return Glib::ustring("solid"); + if (this->isdouble) + return Glib::ustring("double"); + if (this->dotted) + return Glib::ustring("dotted"); + if (this->dashed) + return Glib::ustring("dashed"); + if (this->wavy) + return Glib::ustring("wavy"); g_error("SPITextDecorationStyle::write(): No valid value for property"); return Glib::ustring(""); } -void -SPITextDecorationStyle::cascade( const SPIBase* const parent ) { - if( const SPITextDecorationStyle* p = dynamic_cast<const SPITextDecorationStyle*>(parent) ) { - if( inherits && (!set || inherit) ) { - solid = p->solid; - isdouble = p->isdouble; - dotted = p->dotted; - dashed = p->dashed; - wavy = p->wavy; +void SPITextDecorationStyle::cascade(const SPIBase *const parent) +{ + if (const SPITextDecorationStyle *p = dynamic_cast<const SPITextDecorationStyle *>(parent)) { + if (inherits && (!set || inherit)) { + solid = p->solid; + isdouble = p->isdouble; + dotted = p->dotted; + dashed = p->dashed; + wavy = p->wavy; } } else { std::cerr << "SPITextDecorationStyle::cascade(): Incorrect parent type" << std::endl; } } -void -SPITextDecorationStyle::merge( const SPIBase* const parent ) { - if( const SPITextDecorationStyle* p = dynamic_cast<const SPITextDecorationStyle*>(parent) ) { - if( inherits ) { // Always inherits... but special rules? - if( (!set || inherit) && p->set && !(p->inherit) ) { - set = p->set; - inherit = p->inherit; - solid = p->solid; - isdouble = p->isdouble; - dotted = p->dotted; - dashed = p->dashed; - wavy = p->wavy; +void SPITextDecorationStyle::merge(const SPIBase *const parent) +{ + if (const SPITextDecorationStyle *p = dynamic_cast<const SPITextDecorationStyle *>(parent)) { + if (inherits) { // Always inherits... but special rules? + if ((!set || inherit) && p->set && !(p->inherit)) { + set = p->set; + inherit = p->inherit; + solid = p->solid; + isdouble = p->isdouble; + dotted = p->dotted; + dashed = p->dashed; + wavy = p->wavy; } } } } -bool -SPITextDecorationStyle::operator==(const SPIBase& rhs) { - if( const SPITextDecorationStyle* r = dynamic_cast<const SPITextDecorationStyle*>(&rhs) ) { - return - (solid == r->solid ) && - (isdouble == r->isdouble ) && - (dotted == r->dotted ) && - (dashed == r->dashed ) && - (wavy == r->wavy ) && - SPIBase::operator==(rhs); +bool SPITextDecorationStyle::operator==(const SPIBase &rhs) +{ + if (const SPITextDecorationStyle *r = dynamic_cast<const SPITextDecorationStyle *>(&rhs)) { + return (solid == r->solid) && (isdouble == r->isdouble) && (dotted == r->dotted) && (dashed == r->dashed) && + (wavy == r->wavy) && SPIBase::operator==(rhs); } else { return false; } } - - // TextDecorationColor is handled by SPIPaint (should be SPIColor), default value is "currentColor" // FIXME - - // SPITextDecoration ---------------------------------------------------- -void -SPITextDecoration::read( gchar const *str ) { - - if( !str ) return; +void SPITextDecoration::read(gchar const *str) +{ + if (!str) + return; bool is_css3 = false; decltype(style->text_decoration_line) test_line; - test_line.read( str ); - if( test_line.set ) { + test_line.read(str); + if (test_line.set) { style->text_decoration_line = test_line; } decltype(style->text_decoration_style) test_style; - test_style.read( str ); - if( test_style.set ) { + test_style.read(str); + if (test_style.set) { style->text_decoration_style = test_style; is_css3 = true; } @@ -2949,28 +3120,29 @@ SPITextDecoration::read( gchar const *str ) { // This could certainly be designed better decltype(style->text_decoration_color) test_color; - test_color.setStylePointer( style ); - test_color.read( "currentColor" ); // Default value + test_color.setStylePointer(style); + test_color.read("currentColor"); // Default value test_color.set = false; const gchar *hstr = str; while (true) { - if (*str == ' ' || *str == ',' || *str == '\0'){ + if (*str == ' ' || *str == ',' || *str == '\0') { int slen = str - hstr; - gchar *frag = g_strndup(hstr,slen+1); // only send one piece at a time, since keywords may be intermixed + gchar *frag = g_strndup(hstr, slen + 1); // only send one piece at a time, since keywords may be intermixed - if( strcmp( frag, "none" ) != 0 ) { // 'none' not allowed - test_color.read( frag ); + if (strcmp(frag, "none") != 0) { // 'none' not allowed + test_color.read(frag); } free(frag); - if( test_color.set ) { + if (test_color.set) { style->text_decoration_color = test_color; is_css3 = true; break; } - test_color.read( "currentColor" ); // Default value + test_color.read("currentColor"); // Default value test_color.set = false; - if( *str == '\0' )break; + if (*str == '\0') + break; hstr = str + 1; } str++; @@ -2978,14 +3150,14 @@ SPITextDecoration::read( gchar const *str ) { // If we read a style or color then we have CSS3 which require any non-set values to be // set to their default values. - if( is_css3 ) { + if (is_css3) { style->text_decoration_line.set = true; style->text_decoration_style.set = true; style->text_decoration_color.set = true; } // If we set text_decoration_line, then update style_td (for CSS2 text-decoration) - if( style->text_decoration_line.set ) { + if (style->text_decoration_line.set) { style_td = style; } } @@ -2994,53 +3166,50 @@ SPITextDecoration::read( gchar const *str ) { // This is required until all SVG renderers support CSS3 'text-decoration' const Glib::ustring SPITextDecoration::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); + if (this->inherit) + return Glib::ustring("inherit"); return style->text_decoration_line.get_value(); } -const Glib::ustring -SPITextDecoration::write( guint const flags, SPStyleSrc const &style_src_req, SPIBase const *const base) const { - SPITextDecoration const *const my_base = dynamic_cast<const SPITextDecoration*>(base); - if ( (flags & SP_STYLE_FLAG_ALWAYS) || - ((flags & SP_STYLE_FLAG_IFSET) && style->text_decoration_line.set) || - ((flags & SP_STYLE_FLAG_IFDIFF) && style->text_decoration_line.set - && (!my_base->style->text_decoration_line.set || - style->text_decoration_line != my_base->style->text_decoration_line ))) - { +const Glib::ustring SPITextDecoration::write(guint const flags, SPStyleSrc const &style_src_req, + SPIBase const *const base) const +{ + SPITextDecoration const *const my_base = dynamic_cast<const SPITextDecoration *>(base); + if ((flags & SP_STYLE_FLAG_ALWAYS) || ((flags & SP_STYLE_FLAG_IFSET) && style->text_decoration_line.set) || + ((flags & SP_STYLE_FLAG_IFDIFF) && style->text_decoration_line.set && + (!my_base->style->text_decoration_line.set || + style->text_decoration_line != my_base->style->text_decoration_line))) { return (name() + ":" + this->get_value() + important_str() + ";"); } return Glib::ustring(""); } -void -SPITextDecoration::cascade( const SPIBase* const parent ) { - if( const SPITextDecoration* p = dynamic_cast<const SPITextDecoration*>(parent) ) { - if( style_td == nullptr ) { +void SPITextDecoration::cascade(const SPIBase *const parent) +{ + if (const SPITextDecoration *p = dynamic_cast<const SPITextDecoration *>(parent)) { + if (style_td == nullptr) { style_td = p->style_td; } } else { std::cerr << "SPITextDecoration::cascade(): Incorrect parent type" << std::endl; } - } -void -SPITextDecoration::merge( const SPIBase* const parent ) { - if( const SPITextDecoration* p = dynamic_cast<const SPITextDecoration*>(parent) ) { - if( style_td == nullptr ) { +void SPITextDecoration::merge(const SPIBase *const parent) +{ + if (const SPITextDecoration *p = dynamic_cast<const SPITextDecoration *>(parent)) { + if (style_td == nullptr) { style_td = p->style_td; } } else { std::cerr << "SPITextDecoration::merge(): Incorrect parent type" << std::endl; } - } // Use CSS2 value -bool -SPITextDecoration::operator==(const SPIBase& rhs) { - if( const SPITextDecoration* r = dynamic_cast<const SPITextDecoration*>(&rhs) ) { - return (style->text_decoration_line == r->style->text_decoration_line && - SPIBase::operator==(rhs)); +bool SPITextDecoration::operator==(const SPIBase &rhs) +{ + if (const SPITextDecoration *r = dynamic_cast<const SPITextDecoration *>(&rhs)) { + return (style->text_decoration_line == r->style->text_decoration_line && SPIBase::operator==(rhs)); } else { return false; } @@ -3048,57 +3217,71 @@ SPITextDecoration::operator==(const SPIBase& rhs) { // SPIVectorEffect ------------------------------------------------ -void -SPIVectorEffect::read( gchar const *str ) { - - if( !str ) return; +void SPIVectorEffect::read(gchar const *str) +{ + if (!str) + return; if (!strcmp(str, "none")) { - set = true; - stroke = false; - size = false; - rotate = false; - fixed = false; + set = true; + stroke = false; + size = false; + rotate = false; + fixed = false; } else { - bool found_one = false; - bool hit_one = false; + bool found_one = false; + bool hit_one = false; - bool found_stroke = false; - bool found_size = false; - bool found_rotate = false; - bool found_fixed = false; + bool found_stroke = false; + bool found_size = false; + bool found_rotate = false; + bool found_fixed = false; const gchar *hstr = str; while (true) { - if (*str == ' ' || *str == ',' || *str == '\0'){ + if (*str == ' ' || *str == ',' || *str == '\0') { int slen = str - hstr; - while(true){ // not really a loop, used to avoid a goto + while (true) { // not really a loop, used to avoid a goto hit_one = true; // most likely we will - if ((slen == 18) && strneq(hstr, "non-scaling-stroke", slen)){ found_stroke = true; break; } - if ((slen == 16) && strneq(hstr, "non-scaling-size", slen)){ found_size = true; break; } - if ((slen == 12) && strneq(hstr, "non-rotation", slen)){ found_rotate = true; break; } - if ((slen == 14) && strneq(hstr, "fixed-position", slen)){ found_fixed = true; break; } - if ((slen == 4) && strneq(hstr, "none", slen)){ break; } + if ((slen == 18) && strneq(hstr, "non-scaling-stroke", slen)) { + found_stroke = true; + break; + } + if ((slen == 16) && strneq(hstr, "non-scaling-size", slen)) { + found_size = true; + break; + } + if ((slen == 12) && strneq(hstr, "non-rotation", slen)) { + found_rotate = true; + break; + } + if ((slen == 14) && strneq(hstr, "fixed-position", slen)) { + found_fixed = true; + break; + } + if ((slen == 4) && strneq(hstr, "none", slen)) { + break; + } hit_one = false; // whatever this thing is, we do not recognize it break; } found_one |= hit_one; - if(*str == '\0')break; + if (*str == '\0') + break; hstr = str + 1; } str++; } if (found_one) { - set = true; - stroke = found_stroke; - size = found_size; - rotate = found_rotate; - fixed = found_fixed; - } - else { - set = false; + set = true; + stroke = found_stroke; + size = found_size; + rotate = found_rotate; + fixed = found_fixed; + } else { + set = false; } } @@ -3111,12 +3294,17 @@ SPIVectorEffect::read( gchar const *str ) { const Glib::ustring SPIVectorEffect::get_value() const { - if (this->inherit) return Glib::ustring("inherit"); + if (this->inherit) + return Glib::ustring("inherit"); auto ret = Glib::ustring(""); - if (this->stroke) ret += " non-scaling-stroke"; - if (this->size) ret += " non-scaling-size"; - if (this->rotate) ret += " non-rotation"; - if (this->fixed) ret += " fixed-position"; + if (this->stroke) + ret += " non-scaling-stroke"; + if (this->size) + ret += " non-scaling-size"; + if (this->rotate) + ret += " non-rotation"; + if (this->fixed) + ret += " fixed-position"; if (ret.empty()) { ret += "none"; } else { @@ -3134,21 +3322,16 @@ const Glib::ustring SPIVectorEffect::get_value() const // SPIVectorEffect::merge( const SPIBase* const parent ) { // } -bool -SPIVectorEffect::operator==(const SPIBase& rhs) { - if( const SPIVectorEffect* r = dynamic_cast<const SPIVectorEffect*>(&rhs) ) { - return - (stroke == r->stroke) && - (size == r->size ) && - (rotate == r->rotate) && - (fixed == r->fixed ) && - SPIBase::operator==(rhs); +bool SPIVectorEffect::operator==(const SPIBase &rhs) +{ + if (const SPIVectorEffect *r = dynamic_cast<const SPIVectorEffect *>(&rhs)) { + return (stroke == r->stroke) && (size == r->size) && (rotate == r->rotate) && (fixed == r->fixed) && + SPIBase::operator==(rhs); } else { return false; } } - // template instantiation template class SPIEnum<SPBlendMode>; template class SPIEnum<SPColorInterpolation>; @@ -3182,8 +3365,6 @@ template class SPIEnum<SPCSSFontWeight>; template class SPIEnum<uint_least16_t>; template class SPIEnum<uint_least8_t>; - - /* ---------------------------- NOTES ----------------------------- */ /* @@ -3228,7 +3409,6 @@ template class SPIEnum<uint_least8_t>; * product. */ - /* Local Variables: mode:c++ diff --git a/src/style-internal.h b/src/style-internal.h index fa6cab23af16915bb718febfe73a1cdc153227aa..8d22eded6d735556609679b13b89b8a0441f5465 100644 --- a/src/style-internal.h +++ b/src/style-internal.h @@ -18,34 +18,29 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <map> #include <utility> #include <vector> -#include <map> #include "attributes.h" -#include "style-enums.h" - #include "color.h" - -#include "object/sp-marker-loc.h" -#include "object/sp-filter.h" #include "object/sp-filter-reference.h" +#include "object/sp-filter.h" +#include "object/sp-marker-loc.h" #include "object/sp-paint-server-reference.h" #include "object/sp-shape-reference.h" - #include "object/uri.h" - +#include "style-enums.h" #include "svg/svg-icc-color.h" - #include "xml/repr.h" +static const unsigned SP_STYLE_FLAG_ALWAYS(1 << 2); +static const unsigned SP_STYLE_FLAG_IFSET(1 << 0); +static const unsigned SP_STYLE_FLAG_IFDIFF(1 << 1); +static const unsigned SP_STYLE_FLAG_IFSRC(1 << 3); // If source matches -static const unsigned SP_STYLE_FLAG_ALWAYS (1 << 2); -static const unsigned SP_STYLE_FLAG_IFSET (1 << 0); -static const unsigned SP_STYLE_FLAG_IFDIFF (1 << 1); -static const unsigned SP_STYLE_FLAG_IFSRC (1 << 3); // If source matches - -enum SPStyleSrc { +enum SPStyleSrc +{ SP_STYLE_SRC_UNSET, SP_STYLE_SRC_ATTRIBUTE, // fill="red" SP_STYLE_SRC_STYLE_PROP, // style="fill:red" @@ -59,7 +54,7 @@ enum SPStyleSrc { * Overview: * Style can be obtained (in order of precedence) [CHECK] * 1. "style" property in an element (style="fill:red"). - * 2. Style sheet, internal or external (<style> rect {fill:red;}</style>). + * 2. Style sheet, internal or external (<style> rect {fill:red;}</style>). * 3. Attributes in an element (fill="red"). * 4. Parent's style. * A later property overrides an earlier property. This is implemented by @@ -81,7 +76,7 @@ enum SPStyleSrc { * * An explicitly set value (including 'inherit') has a 'true' "set" flag. * The "value" is either explicitly set or inherited. - * The "computed" value (if present) is calculated from "value" and some other input. + * The "computed" value (if present) is calculated from "value" and some other input. * * Functions: * write(): Write a property and its value to a string. @@ -126,84 +121,73 @@ enum SPStyleSrc { /// Virtual base class for all SPStyle internal classes class SPIBase { - public: SPIBase(bool inherits_ = true) - : inherits(inherits_), - set(false), - inherit(false), - important(false), - style_src(SP_STYLE_SRC_STYLE_PROP), // Default to property, see bug 1662285. - style(nullptr) + : inherits(inherits_) + , set(false) + , inherit(false) + , important(false) + , style_src(SP_STYLE_SRC_STYLE_PROP) + , // Default to property, see bug 1662285. + style(nullptr) {} - virtual ~SPIBase() - = default; + virtual ~SPIBase() = default; - virtual void read( gchar const *str ) = 0; + virtual void read(gchar const *str) = 0; virtual void readIfUnset(gchar const *str, SPStyleSrc source = SP_STYLE_SRC_STYLE_PROP); - Glib::ustring important_str() const { - return Glib::ustring(important ? " !important" : ""); - } + Glib::ustring important_str() const { return Glib::ustring(important ? " !important" : ""); } - virtual void readAttribute( Inkscape::XML::Node *repr ) { + virtual void readAttribute(Inkscape::XML::Node *repr) + { readIfUnset(repr->attribute(name().c_str()), SP_STYLE_SRC_ATTRIBUTE); } virtual const Glib::ustring get_value() const = 0; - bool shall_write( guint const flags = SP_STYLE_FLAG_IFSET, - SPStyleSrc const &style_src_req = SP_STYLE_SRC_STYLE_PROP, - SPIBase const *const base = nullptr ) const; - virtual const Glib::ustring write( guint const flags = SP_STYLE_FLAG_IFSET, - SPStyleSrc const &style_src_req = SP_STYLE_SRC_STYLE_PROP, - SPIBase const *const base = nullptr ) const; - virtual void clear() { - set = false, inherit = false, important = false; - } + bool shall_write(guint const flags = SP_STYLE_FLAG_IFSET, SPStyleSrc const &style_src_req = SP_STYLE_SRC_STYLE_PROP, + SPIBase const *const base = nullptr) const; + virtual const Glib::ustring write(guint const flags = SP_STYLE_FLAG_IFSET, + SPStyleSrc const &style_src_req = SP_STYLE_SRC_STYLE_PROP, + SPIBase const *const base = nullptr) const; + virtual void clear() { set = false, inherit = false, important = false; } - virtual void cascade( const SPIBase* const parent ) = 0; - virtual void merge( const SPIBase* const parent ) = 0; + virtual void cascade(const SPIBase *const parent) = 0; + virtual void merge(const SPIBase *const parent) = 0; - virtual void setStylePointer( SPStyle *style_in ) { - style = style_in; - } + virtual void setStylePointer(SPStyle *style_in) { style = style_in; } // Explicit assignment operator required due to templates. - SPIBase& operator=(const SPIBase& rhs) = default; + SPIBase &operator=(const SPIBase &rhs) = default; // Check apples being compared to apples - virtual bool operator==(const SPIBase& rhs) { - return id() == rhs.id(); - } + virtual bool operator==(const SPIBase &rhs) { return id() == rhs.id(); } - virtual bool operator!=(const SPIBase& rhs) { - return !(*this == rhs); - } + virtual bool operator!=(const SPIBase &rhs) { return !(*this == rhs); } virtual SPAttr id() const { return SPAttr::INVALID; } Glib::ustring const &name() const; - // To do: make private + // To do: make private public: - bool inherits : 1; // Property inherits by default from parent. - bool set : 1; // Property has been explicitly set (vs. inherited). - bool inherit : 1; // Property value set to 'inherit'. - bool important : 1; // Property rule 'important' has been explicitly set. + bool inherits : 1; // Property inherits by default from parent. + bool set : 1; // Property has been explicitly set (vs. inherited). + bool inherit : 1; // Property value set to 'inherit'. + bool important : 1; // Property rule 'important' has been explicitly set. SPStyleSrc style_src : 2; // Source (attribute, style attribute, style-sheet). - // To do: make private after g_asserts removed + // To do: make private after g_asserts removed public: - SPStyle* style; // Used by SPIPaint, SPIFilter... to find values of other properties + SPStyle *style; // Used by SPIPaint, SPIFilter... to find values of other properties }; - /** * Decorator which overrides SPIBase::id() */ template <SPAttr Id, class Base> -class TypedSPI : public Base { - public: +class TypedSPI : public Base +{ +public: using Base::Base; /** @@ -219,36 +203,33 @@ class TypedSPI : public Base { Base const *upcast() const { return static_cast<Base const *>(this); } }; - /// Float type internal to SPStyle. (Only 'stroke-miterlimit') class SPIFloat : public SPIBase { - public: - SPIFloat(float value_default = 0.0 ) - : value(value_default), - value_default(value_default) + SPIFloat(float value_default = 0.0) + : value(value_default) + , value_default(value_default) {} ~SPIFloat() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); value = value_default; } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIFloat& operator=(const SPIFloat& rhs) = default; + SPIFloat &operator=(const SPIFloat &rhs) = default; - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - // To do: make private + // To do: make private public: float value = 0.0; @@ -278,54 +259,50 @@ private: * colours and opacities, to be safe from rounding bugs. */ static const unsigned SP_SCALE24_MAX = 0xff0000; -#define SP_SCALE24_TO_FLOAT(v) ((double) (v) / SP_SCALE24_MAX) -#define SP_SCALE24_FROM_FLOAT(v) unsigned(((v) * SP_SCALE24_MAX) + .5) +#define SP_SCALE24_TO_FLOAT(v) ((double)(v) / SP_SCALE24_MAX) +#define SP_SCALE24_FROM_FLOAT(v) unsigned(((v)*SP_SCALE24_MAX) + .5) /** Returns a scale24 for the product of two scale24 values. */ #define SP_SCALE24_MUL(_v1, _v2) unsigned((double)(_v1) * (_v2) / SP_SCALE24_MAX + .5) - /// 24 bit data type internal to SPStyle. // Used only for opacity, fill-opacity, stroke-opacity. -// Opacity does not inherit but stroke-opacity and fill-opacity do. +// Opacity does not inherit but stroke-opacity and fill-opacity do. class SPIScale24 : public SPIBase { static unsigned get_default() { return SP_SCALE24_MAX; } public: - SPIScale24(bool inherits = true ) - : SPIBase(inherits), - value(get_default()) + SPIScale24(bool inherits = true) + : SPIBase(inherits) + , value(get_default()) {} - ~SPIScale24() override - = default; + ~SPIScale24() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); value = get_default(); } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIScale24& operator=(const SPIScale24& rhs) = default; - - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + SPIScale24 &operator=(const SPIScale24 &rhs) = default; + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - // To do: make private + // To do: make private public: unsigned value : 24; }; - -enum SPCSSUnit { +enum SPCSSUnit +{ SP_CSS_UNIT_NONE, SP_CSS_UNIT_PX, SP_CSS_UNIT_PT, @@ -338,46 +315,42 @@ enum SPCSSUnit { SP_CSS_UNIT_PERCENT }; - /// Length type internal to SPStyle. // Needs access to 'font-size' and 'font-family' for computed values. // Used for 'stroke-width' 'stroke-dash-offset' ('none' not handled), text-indent class SPILength : public SPIBase { - public: SPILength(float value = 0) - : unit(SP_CSS_UNIT_NONE), - value(value), - computed(value), - value_default(value) + : unit(SP_CSS_UNIT_NONE) + , value(value) + , computed(value) + , value_default(value) {} - ~SPILength() override - = default; + ~SPILength() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); unit = SP_CSS_UNIT_NONE, value = value_default; computed = value_default; } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPILength& operator=(const SPILength& rhs) = default; + SPILength &operator=(const SPILength &rhs) = default; - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } void setDouble(double v); virtual const Glib::ustring toString(bool wname = false) const; // To do: make private - public: +public: unsigned unit : 4; float value = 0.f; float computed = 0.f; @@ -386,133 +359,123 @@ private: float value_default = 0.f; }; - /// Extended length type internal to SPStyle. // Used for: line-height, letter-spacing, word-spacing class SPILengthOrNormal : public SPILength { - public: SPILengthOrNormal(float value = 0) - : SPILength(value), - normal(true) + : SPILength(value) + , normal(true) {} - ~SPILengthOrNormal() override - = default; + ~SPILengthOrNormal() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPILength::clear(); normal = true; } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPILengthOrNormal& operator=(const SPILengthOrNormal& rhs) = default; + SPILengthOrNormal &operator=(const SPILengthOrNormal &rhs) = default; - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - // To do: make private + // To do: make private public: bool normal : 1; }; - /// Extended length type internal to SPStyle. // Used for: font-variation-settings class SPIFontVariationSettings : public SPIBase { - public: SPIFontVariationSettings() : normal(true) {} - ~SPIFontVariationSettings() override - = default; + ~SPIFontVariationSettings() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); axes.clear(); normal = true; } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIFontVariationSettings& operator=(const SPIFontVariationSettings& rhs) { + SPIFontVariationSettings &operator=(const SPIFontVariationSettings &rhs) + { SPIBase::operator=(rhs); axes = rhs.axes; normal = rhs.normal; return *this; } - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } virtual const Glib::ustring toString() const; - // To do: make private + // To do: make private public: bool normal : 1; bool inherit : 1; std::map<Glib::ustring, float> axes; }; - /// Enum type internal to SPStyle. // Used for many properties. 'font-stretch' and 'font-weight' must be special cased. template <typename T> class SPIEnum : public SPIBase { - public: - SPIEnum(T value = T(), bool inherits = true) : - SPIBase(inherits), - value(value), - value_default(value) + SPIEnum(T value = T(), bool inherits = true) + : SPIBase(inherits) + , value(value) + , value_default(value) { update_computed(); } - ~SPIEnum() override - = default; + ~SPIEnum() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); value = value_default; update_computed(); } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIEnum& operator=(const SPIEnum& rhs) { + SPIEnum &operator=(const SPIEnum &rhs) + { SPIBase::operator=(rhs); - value = rhs.value; - computed = rhs.computed; - value_default = rhs.value_default; + value = rhs.value; + computed = rhs.computed; + value_default = rhs.value_default; return *this; } - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - // To do: make private + // To do: make private public: T value{}; T computed{}; @@ -530,7 +493,6 @@ private: void update_value_merge(SPIEnum<T> const &, T, T); }; - #if 0 /// SPIEnum w/ bits, allows values with multiple key words. class SPIEnumBits : public SPIEnum @@ -549,7 +511,6 @@ public: }; #endif - /// SPIEnum w/ extra bits. The 'font-variants-ligatures' property is a complete mess that needs /// special handling. For OpenType fonts the values 'common-ligatures', 'contextual', /// 'no-discretionary-ligatures', and 'no-historical-ligatures' are not useful but we still must be @@ -557,63 +518,53 @@ public: using _SPCSSFontVariantLigatures_int = typename std::underlying_type<SPCSSFontVariantLigatures>::type; class SPILigatures : public SPIEnum<_SPCSSFontVariantLigatures_int> { - public: - SPILigatures() : - SPIEnum<_SPCSSFontVariantLigatures_int>(SP_CSS_FONT_VARIANT_LIGATURES_NORMAL) + SPILigatures() + : SPIEnum<_SPCSSFontVariantLigatures_int>(SP_CSS_FONT_VARIANT_LIGATURES_NORMAL) {} - ~SPILigatures() override - = default; + ~SPILigatures() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; }; - /// SPIEnum w/ extra bits. The 'font-variants-numeric' property is a complete mess that needs /// special handling. Multiple key words can be specified, some exclusive of others. using _SPCSSFontVariantNumeric_int = typename std::underlying_type<SPCSSFontVariantNumeric>::type; class SPINumeric : public SPIEnum<_SPCSSFontVariantNumeric_int> { - public: - SPINumeric() : - SPIEnum<_SPCSSFontVariantNumeric_int>(SP_CSS_FONT_VARIANT_NUMERIC_NORMAL) + SPINumeric() + : SPIEnum<_SPCSSFontVariantNumeric_int>(SP_CSS_FONT_VARIANT_NUMERIC_NORMAL) {} - ~SPINumeric() override - = default; + ~SPINumeric() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; }; - /// SPIEnum w/ extra bits. The 'font-variants-east-asian' property is a complete mess that needs /// special handling. Multiple key words can be specified, some exclusive of others. using _SPCSSFontVariantEastAsian_int = typename std::underlying_type<SPCSSFontVariantEastAsian>::type; class SPIEastAsian : public SPIEnum<_SPCSSFontVariantEastAsian_int> { - public: - SPIEastAsian() : - SPIEnum<_SPCSSFontVariantEastAsian_int>(SP_CSS_FONT_VARIANT_EAST_ASIAN_NORMAL) + SPIEastAsian() + : SPIEnum<_SPCSSFontVariantEastAsian_int>(SP_CSS_FONT_VARIANT_EAST_ASIAN_NORMAL) {} - ~SPIEastAsian() override - = default; + ~SPIEastAsian() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; }; - /// String type internal to SPStyle. // Used for 'marker', ..., 'font', 'font-family', 'inkscape-font-specification' class SPIString : public SPIBase { - public: SPIString(bool inherits = true) : SPIBase(inherits) @@ -621,17 +572,16 @@ public: SPIString(const SPIString &rhs) { *this = rhs; } - ~SPIString() override { - g_free(_value); - } + ~SPIString() override { g_free(_value); } - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; void clear() override; // TODO check about value and value_default - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIString& operator=(const SPIString& rhs) { + SPIString &operator=(const SPIString &rhs) + { if (this == &rhs) { return *this; } @@ -641,15 +591,13 @@ public: return *this; } - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } //! Get value if set, or inherited value, or default value (may be NULL) char const *value() const; - private: +private: char const *get_default_value() const; gchar *_value = nullptr; @@ -666,7 +614,7 @@ public: ~SPIShapes() override; SPIShapes(); SPIShapes(const SPIShapes &) = delete; // Copying causes problems with hrefs. - void read( gchar const *str ) override; + void read(gchar const *str) override; void clear() override; public: @@ -676,7 +624,6 @@ public: /// Color type internal to SPStyle, FIXME Add string value to store SVG named color. class SPIColor : public SPIBase { - public: SPIColor(bool inherits = true) : SPIBase(inherits) @@ -685,150 +632,149 @@ public: value.color.set(0); } - ~SPIColor() override - = default; + ~SPIColor() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); value.color.set(0); } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIColor& operator=(const SPIColor& rhs) { + SPIColor &operator=(const SPIColor &rhs) + { SPIBase::operator=(rhs); currentcolor = rhs.currentcolor; - value.color = rhs.value.color; + value.color = rhs.value.color; return *this; } - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - void setColor( float r, float g, float b ) { - value.color.set( r, g, b ); - } + void setColor(float r, float g, float b) { value.color.set(r, g, b); } - void setColor( guint32 val ) { - value.color.set( val ); - } + void setColor(guint32 val) { value.color.set(val); } - void setColor( SPColor const& color ) { - value.color = color; - } + void setColor(SPColor const &color) { value.color = color; } public: bool currentcolor : 1; // FIXME: remove structure and derive SPIPaint from this class. - struct { - SPColor color; + struct + { + SPColor color; } value; }; - - -#define SP_STYLE_FILL_SERVER(s) ((const_cast<SPStyle *> (s))->getFillPaintServer()) -#define SP_STYLE_STROKE_SERVER(s) ((const_cast<SPStyle *> (s))->getStrokePaintServer()) +#define SP_STYLE_FILL_SERVER(s) ((const_cast<SPStyle *>(s))->getFillPaintServer()) +#define SP_STYLE_STROKE_SERVER(s) ((const_cast<SPStyle *>(s))->getStrokePaintServer()) // SVG 2 -enum SPPaintOrigin { +enum SPPaintOrigin +{ SP_CSS_PAINT_ORIGIN_NORMAL, SP_CSS_PAINT_ORIGIN_CURRENT_COLOR, SP_CSS_PAINT_ORIGIN_CONTEXT_FILL, SP_CSS_PAINT_ORIGIN_CONTEXT_STROKE }; - /// Paint type internal to SPStyle. class SPIPaint : public SPIBase { - public: SPIPaint() - : paintOrigin(SP_CSS_PAINT_ORIGIN_NORMAL), - colorSet(false), - noneSet(false) { + : paintOrigin(SP_CSS_PAINT_ORIGIN_NORMAL) + , colorSet(false) + , noneSet(false) + { value.href = nullptr; clear(); } - ~SPIPaint() override; // Clear and delete href. - void read( gchar const *str ) override; - virtual void read( gchar const *str, SPStyle &style, SPDocument *document = nullptr); + ~SPIPaint() override; // Clear and delete href. + void read(gchar const *str) override; + virtual void read(gchar const *str, SPStyle &style, SPDocument *document = nullptr); const Glib::ustring get_value() const override; void clear() override; - virtual void reset( bool init ); // Used internally when reading or cascading - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + virtual void reset(bool init); // Used internally when reading or cascading + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIPaint& operator=(const SPIPaint& rhs) { + SPIPaint &operator=(const SPIPaint &rhs) + { SPIBase::operator=(rhs); - paintOrigin = rhs.paintOrigin; - colorSet = rhs.colorSet; - noneSet = rhs.noneSet; - value.color = rhs.value.color; - value.href = rhs.value.href; + paintOrigin = rhs.paintOrigin; + colorSet = rhs.colorSet; + noneSet = rhs.noneSet; + value.color = rhs.value.color; + value.href = rhs.value.href; return *this; } - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - bool isSameType( SPIPaint const & other ) const { - return (isPaintserver() == other.isPaintserver()) && (colorSet == other.colorSet) && (paintOrigin == other.paintOrigin); + bool isSameType(SPIPaint const &other) const + { + return (isPaintserver() == other.isPaintserver()) && (colorSet == other.colorSet) && + (paintOrigin == other.paintOrigin); } - bool isNoneSet() const { - return noneSet; - } + bool isNoneSet() const { return noneSet; } - bool isNone() const { + bool isNone() const + { return !colorSet && !isPaintserver() && (paintOrigin == SP_CSS_PAINT_ORIGIN_NORMAL); } // TODO refine - bool isColor() const { - return colorSet && !isPaintserver(); - } + bool isColor() const { return colorSet && !isPaintserver(); } - bool isPaintserver() const { - return value.href && value.href->getObject() != nullptr; - } + bool isPaintserver() const { return value.href && value.href->getObject() != nullptr; } - void setColor( float r, float g, float b ) { - value.color.set( r, g, b ); colorSet = true; + void setColor(float r, float g, float b) + { + value.color.set(r, g, b); + colorSet = true; } - void setColor( guint32 val ) { - value.color.set( val ); colorSet = true; + void setColor(guint32 val) + { + value.color.set(val); + colorSet = true; } - void setColor( SPColor const& color ) { - value.color = color; colorSet = true; + void setColor(SPColor const &color) + { + value.color = color; + colorSet = true; } - void setNone() {noneSet = true; colorSet=false;} + void setNone() + { + noneSet = true; + colorSet = false; + } - // To do: make private + // To do: make private public: SPPaintOrigin paintOrigin : 2; bool colorSet : 1; bool noneSet : 1; - struct { - SPPaintServerReference *href; - SPColor color; + struct + { + SPPaintServerReference *href; + SPColor color; } value; }; - // SVG 2 -enum SPPaintOrderLayer { +enum SPPaintOrderLayer +{ SP_CSS_PAINT_ORDER_NORMAL, SP_CSS_PAINT_ORDER_FILL, SP_CSS_PAINT_ORDER_STROKE, @@ -845,123 +791,109 @@ const size_t PAINT_ORDER_LAYERS = 3; /// Paint order type internal to SPStyle class SPIPaintOrder : public SPIBase { - public: - SPIPaintOrder() { - this->clear(); - } + SPIPaintOrder() { this->clear(); } SPIPaintOrder(const SPIPaintOrder &rhs) { *this = rhs; } - ~SPIPaintOrder() override { - g_free( value ); - } + ~SPIPaintOrder() override { g_free(value); } - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); - for( unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i ) { - layer[i] = SP_CSS_PAINT_ORDER_NORMAL; + for (unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i) { + layer[i] = SP_CSS_PAINT_ORDER_NORMAL; layer_set[i] = false; } g_free(value); value = nullptr; } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIPaintOrder& operator=(const SPIPaintOrder& rhs) { + SPIPaintOrder &operator=(const SPIPaintOrder &rhs) + { if (this == &rhs) { return *this; } SPIBase::operator=(rhs); - for( unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i ) { - layer[i] = rhs.layer[i]; + for (unsigned i = 0; i < PAINT_ORDER_LAYERS; ++i) { + layer[i] = rhs.layer[i]; layer_set[i] = rhs.layer_set[i]; } g_free(value); - value = g_strdup(rhs.value); + value = g_strdup(rhs.value); return *this; } - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } - + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - // To do: make private + // To do: make private public: SPPaintOrderLayer layer[PAINT_ORDER_LAYERS]; bool layer_set[PAINT_ORDER_LAYERS]; gchar *value = nullptr; // Raw string }; - /// Filter type internal to SPStyle class SPIDashArray : public SPIBase { - public: SPIDashArray() = default; - ~SPIDashArray() override - = default; + ~SPIDashArray() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); values.clear(); } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIDashArray& operator=(const SPIDashArray& rhs) = default; + SPIDashArray &operator=(const SPIDashArray &rhs) = default; - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - // To do: make private, change double to SVGLength + // To do: make private, change double to SVGLength public: - std::vector<SPILength> values; + std::vector<SPILength> values; }; /// Filter type internal to SPStyle class SPIFilter : public SPIBase { - public: SPIFilter() : SPIBase(false) {} ~SPIFilter() override; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; void clear() override; - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIFilter& operator=(const SPIFilter& rhs) = default; + SPIFilter &operator=(const SPIFilter &rhs) = default; - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - // To do: make private + // To do: make private public: SPFilterReference *href = nullptr; }; - - -enum { +enum +{ SP_FONT_SIZE_LITERAL, SP_FONT_SIZE_LENGTH, SP_FONT_SIZE_PERCENTAGE @@ -970,37 +902,32 @@ enum { /// Fontsize type internal to SPStyle (also used by libnrtype/Layout-TNG-Input.cpp). class SPIFontSize : public SPIBase { - public: - SPIFontSize() { - this->clear(); - } + SPIFontSize() { this->clear(); } - ~SPIFontSize() override - = default; + ~SPIFontSize() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); - type = SP_FONT_SIZE_LITERAL, unit = SP_CSS_UNIT_NONE, - literal = SP_CSS_FONT_SIZE_MEDIUM, value = 12.0, computed = 12.0; + type = SP_FONT_SIZE_LITERAL, unit = SP_CSS_UNIT_NONE, literal = SP_CSS_FONT_SIZE_MEDIUM, value = 12.0, + computed = 12.0; } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIFontSize& operator=(const SPIFontSize& rhs) = default; + SPIFontSize &operator=(const SPIFontSize &rhs) = default; - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } public: static float const font_size_default; - // To do: make private + // To do: make private public: unsigned type : 2; unsigned unit : 4; @@ -1013,39 +940,30 @@ private: static float const font_size_table[]; }; - /// Font type internal to SPStyle ('font' shorthand) class SPIFont : public SPIBase { - public: SPIFont() = default; - ~SPIFont() override - = default; + ~SPIFont() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { - SPIBase::clear(); - } + void clear() override { SPIBase::clear(); } - void cascade( const SPIBase* const /*parent*/ ) override - {} // Done in dependent properties + void cascade(const SPIBase *const /*parent*/) override {} // Done in dependent properties - void merge( const SPIBase* const /*parent*/ ) override - {} + void merge(const SPIBase *const /*parent*/) override {} - SPIFont& operator=(const SPIFont& rhs) = default; + SPIFont &operator=(const SPIFont &rhs) = default; - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } }; - -enum { +enum +{ SP_BASELINE_SHIFT_LITERAL, SP_BASELINE_SHIFT_LENGTH, SP_BASELINE_SHIFT_PERCENTAGE @@ -1054,42 +972,40 @@ enum { /// Baseline shift type internal to SPStyle. (This is actually just like SPIFontSize) class SPIBaselineShift : public SPIBase { - public: SPIBaselineShift() - : SPIBase(false) { + : SPIBase(false) + { this->clear(); } - ~SPIBaselineShift() override - = default; + ~SPIBaselineShift() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); - type=SP_BASELINE_SHIFT_LITERAL, unit=SP_CSS_UNIT_NONE, - literal = SP_CSS_BASELINE_SHIFT_BASELINE, value = 0.0, computed = 0.0; + type = SP_BASELINE_SHIFT_LITERAL, unit = SP_CSS_UNIT_NONE, literal = SP_CSS_BASELINE_SHIFT_BASELINE, + value = 0.0, computed = 0.0; } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPIBaselineShift& operator=(const SPIBaselineShift& rhs) = default; + SPIBaselineShift &operator=(const SPIBaselineShift &rhs) = default; // This is not used but we have it for completeness, it has not been tested. - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } bool isZero() const; - // To do: make private + // To do: make private public: unsigned type : 2; unsigned unit : 4; - unsigned literal: 2; + unsigned literal : 2; float value; // Can be negative float computed; }; @@ -1101,81 +1017,69 @@ public: /// Text decoration line type internal to SPStyle. THIS SHOULD BE A GENERIC CLASS class SPITextDecorationLine : public SPIBase { - public: - SPITextDecorationLine() { - this->clear(); - } + SPITextDecorationLine() { this->clear(); } - ~SPITextDecorationLine() override - = default; + ~SPITextDecorationLine() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); underline = false, overline = false, line_through = false, blink = false; } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPITextDecorationLine& operator=(const SPITextDecorationLine& rhs) = default; + SPITextDecorationLine &operator=(const SPITextDecorationLine &rhs) = default; - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - // To do: make private + // To do: make private public: bool underline : 1; bool overline : 1; bool line_through : 1; - bool blink : 1; // "Conforming user agents are not required to support this value." yay! + bool blink : 1; // "Conforming user agents are not required to support this value." yay! }; // CSS3 2.2 /// Text decoration style type internal to SPStyle. THIS SHOULD JUST BE SPIEnum! class SPITextDecorationStyle : public SPIBase { - public: - SPITextDecorationStyle() { - this->clear(); - } + SPITextDecorationStyle() { this->clear(); } - ~SPITextDecorationStyle() override - = default; + ~SPITextDecorationStyle() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); solid = true, isdouble = false, dotted = false, dashed = false, wavy = false; } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPITextDecorationStyle& operator=(const SPITextDecorationStyle& rhs) = default; + SPITextDecorationStyle &operator=(const SPITextDecorationStyle &rhs) = default; - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - // To do: make private + // To do: make private public: bool solid : 1; - bool isdouble : 1; // cannot use "double" as it is a reserved keyword + bool isdouble : 1; // cannot use "double" as it is a reserved keyword bool dotted : 1; bool dashed : 1; bool wavy : 1; }; - - // This class reads in both CSS2 and CSS3 'text-decoration' property. It passes the line, style, // and color parts to the appropriate CSS3 long-hand classes for reading and storing values. When // writing out data, we write all four properties, with 'text-decoration' being written out with @@ -1185,60 +1089,57 @@ public: /// Text decoration type internal to SPStyle. class SPITextDecoration : public SPIBase { - public: SPITextDecoration() = default; - ~SPITextDecoration() override - = default; + ~SPITextDecoration() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - const Glib::ustring write( guint const flags = SP_STYLE_FLAG_IFSET, - SPStyleSrc const &style_src_req = SP_STYLE_SRC_STYLE_PROP, - SPIBase const *const base = nullptr ) const override; - void clear() override { + const Glib::ustring write(guint const flags = SP_STYLE_FLAG_IFSET, + SPStyleSrc const &style_src_req = SP_STYLE_SRC_STYLE_PROP, + SPIBase const *const base = nullptr) const override; + void clear() override + { SPIBase::clear(); style_td = nullptr; } - void cascade( const SPIBase* const parent ) override; - void merge( const SPIBase* const parent ) override; + void cascade(const SPIBase *const parent) override; + void merge(const SPIBase *const parent) override; - SPITextDecoration& operator=(const SPITextDecoration& rhs) { + SPITextDecoration &operator=(const SPITextDecoration &rhs) + { SPIBase::operator=(rhs); return *this; } // Use CSS2 value - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } public: - SPStyle* style_td = nullptr; // Style to be used for drawing CSS2 text decorations + SPStyle *style_td = nullptr; // Style to be used for drawing CSS2 text decorations }; - // These are used to implement text_decoration. The values are not saved to or read from SVG file -struct SPITextDecorationData { - float phase_length; // length along text line,used for phase for dot/dash/wavy - bool tspan_line_start; // is first span on a line - bool tspan_line_end; // is last span on a line - float tspan_width; // from libnrtype, when it calculates spans - float ascender; // the rest from tspan's font - float descender; - float underline_thickness; - float underline_position; - float line_through_thickness; - float line_through_position; +struct SPITextDecorationData +{ + float phase_length; // length along text line,used for phase for dot/dash/wavy + bool tspan_line_start; // is first span on a line + bool tspan_line_end; // is last span on a line + float tspan_width; // from libnrtype, when it calculates spans + float ascender; // the rest from tspan's font + float descender; + float underline_thickness; + float underline_position; + float line_through_thickness; + float line_through_position; }; /// Vector Effects. THIS SHOULD BE A GENERIC CLASS class SPIVectorEffect : public SPIBase { - public: SPIVectorEffect() : SPIBase(false) @@ -1246,41 +1147,38 @@ public: this->clear(); } - ~SPIVectorEffect() override - = default; + ~SPIVectorEffect() override = default; - void read( gchar const *str ) override; + void read(gchar const *str) override; const Glib::ustring get_value() const override; - void clear() override { + void clear() override + { SPIBase::clear(); stroke = false; - size = false; + size = false; rotate = false; - fixed = false; + fixed = false; } // Does not inherit - void cascade( const SPIBase* const parent ) override {}; - void merge( const SPIBase* const parent ) override {}; + void cascade(const SPIBase *const parent) override{}; + void merge(const SPIBase *const parent) override{}; - SPIVectorEffect& operator=(const SPIVectorEffect& rhs) = default; + SPIVectorEffect &operator=(const SPIVectorEffect &rhs) = default; - bool operator==(const SPIBase& rhs) override; - bool operator!=(const SPIBase& rhs) override { - return !(*this == rhs); - } + bool operator==(const SPIBase &rhs) override; + bool operator!=(const SPIBase &rhs) override { return !(*this == rhs); } - // To do: make private + // To do: make private public: bool stroke : 1; - bool size : 1; + bool size : 1; bool rotate : 1; - bool fixed : 1; + bool fixed : 1; }; #endif // SEEN_SP_STYLE_INTERNAL_H - /* Local Variables: mode:c++ diff --git a/src/style.cpp b/src/style.cpp index 4c04fb190df36f638bdbf05fb1ef17fdbdce50db..384327f1fac93bcada8516516dde5fe7e6a50180 100644 --- a/src/style.cpp +++ b/src/style.cpp @@ -22,30 +22,24 @@ #include "style.h" +#include <algorithm> #include <cstring> +#include <glibmm/regex.h> #include <string> -#include <algorithm> #include <unordered_map> #include <vector> -#include <glibmm/regex.h> - +#include "3rdparty/libcroco/cr-sel-eng.h" #include "attributes.h" #include "bad-uri-exception.h" #include "document.h" -#include "preferences.h" - -#include "3rdparty/libcroco/cr-sel-eng.h" - #include "object/sp-paint-server.h" #include "object/uri-references.h" #include "object/uri.h" - +#include "preferences.h" #include "svg/css-ostringstream.h" #include "svg/svg.h" - #include "util/units.h" - #include "xml/croco-node-iface.h" #include "xml/simple-document.h" @@ -75,11 +69,13 @@ static CRSelEng *sp_repr_sel_eng(); * Helper class for SPStyle property member lookup by SPAttr or * by name, and for iterating over ordered members. */ -class SPStylePropHelper { - SPStylePropHelper() { -#define REGISTER_PROPERTY(id, member, name) \ - g_assert(decltype(SPStyle::member)::static_id() == id); \ - _register(reinterpret_cast<SPIBasePtr>(&SPStyle::member), id) /* name unused */ +class SPStylePropHelper +{ + SPStylePropHelper() + { +#define REGISTER_PROPERTY(id, member, name) \ + g_assert(decltype(SPStyle::member)::static_id() == id); \ + _register(reinterpret_cast<SPIBasePtr>(&SPStyle::member), id) /* name unused */ // SVG 2: Attributes promoted to properties REGISTER_PROPERTY(SPAttr::D, d, "d"); @@ -149,7 +145,8 @@ class SPStylePropHelper { REGISTER_PROPERTY(SPAttr::MIX_BLEND_MODE, mix_blend_mode, "mix-blend-mode"); REGISTER_PROPERTY(SPAttr::COLOR_INTERPOLATION, color_interpolation, "color-interpolation"); - REGISTER_PROPERTY(SPAttr::COLOR_INTERPOLATION_FILTERS, color_interpolation_filters, "color-interpolation-filters"); + REGISTER_PROPERTY(SPAttr::COLOR_INTERPOLATION_FILTERS, color_interpolation_filters, + "color-interpolation-filters"); REGISTER_PROPERTY(SPAttr::SOLID_COLOR, solid_color, "solid-color"); REGISTER_PROPERTY(SPAttr::SOLID_OPACITY, solid_opacity, "solid-opacity"); @@ -190,13 +187,14 @@ class SPStylePropHelper { } // this is a singleton, copy not allowed - SPStylePropHelper(SPStylePropHelper const&) = delete; -public: + SPStylePropHelper(SPStylePropHelper const &) = delete; +public: /** * Singleton instance */ - static SPStylePropHelper &instance() { + static SPStylePropHelper &instance() + { static SPStylePropHelper _instance; return _instance; } @@ -204,7 +202,8 @@ public: /** * Get property pointer by enum */ - SPIBase *get(SPStyle *style, SPAttr id) { + SPIBase *get(SPStyle *style, SPAttr id) + { auto it = m_id_map.find(id); if (it != m_id_map.end()) { return _get(style, it->second); @@ -215,15 +214,14 @@ public: /** * Get property pointer by name */ - SPIBase *get(SPStyle *style, const std::string &name) { - return get(style, sp_attribute_lookup(name.c_str())); - } + SPIBase *get(SPStyle *style, const std::string &name) { return get(style, sp_attribute_lookup(name.c_str())); } /** * Get a vector of property pointers * \todo provide iterator instead */ - std::vector<SPIBase *> get_vector(SPStyle *style) { + std::vector<SPIBase *> get_vector(SPStyle *style) + { std::vector<SPIBase *> v; v.reserve(m_vector.size()); for (auto ptr : m_vector) { @@ -235,7 +233,8 @@ public: private: SPIBase *_get(SPStyle *style, SPIBasePtr ptr) { return &(style->*ptr); } - void _register(SPIBasePtr ptr, SPAttr id) { + void _register(SPIBasePtr ptr, SPAttr id) + { m_vector.push_back(ptr); if (id != SPAttr::INVALID) { @@ -252,7 +251,8 @@ auto &_prop_helper = SPStylePropHelper::instance(); // C++11 allows one constructor to call another... might be useful. The original C code // had separate calls to create SPStyle, one with only SPDocument and the other with only // SPObject as parameters. -SPStyle::SPStyle(SPDocument *document_in, SPObject *object_in) : +SPStyle::SPStyle(SPDocument *document_in, SPObject *object_in) + : // Unimplemented SVG 1.1: alignment-baseline, clip, clip-path, color-profile, cursor, // dominant-baseline, flood-color, flood-opacity, font-size-adjust, @@ -269,121 +269,164 @@ SPStyle::SPStyle(SPDocument *document_in, SPObject *object_in) : // font-family // font-specification - // SVG 2 attributes promoted to properties. (When geometry properties are added, move after font.) - d( false), // SPIString Not inherited! + d(false) + , // SPIString Not inherited! // Font related properties and 'font' shorthand - font_style( SP_CSS_FONT_STYLE_NORMAL), - font_variant( SP_CSS_FONT_VARIANT_NORMAL), - font_weight( SP_CSS_FONT_WEIGHT_NORMAL), - font_stretch( SP_CSS_FONT_STRETCH_NORMAL), - font_size(), - line_height( 1.25 ), // SPILengthOrNormal - font_family( ), // SPIString w/default - font(), // SPIFont - font_specification( ), // SPIString + font_style(SP_CSS_FONT_STYLE_NORMAL) + , font_variant(SP_CSS_FONT_VARIANT_NORMAL) + , font_weight(SP_CSS_FONT_WEIGHT_NORMAL) + , font_stretch(SP_CSS_FONT_STRETCH_NORMAL) + , font_size() + , line_height(1.25) + , // SPILengthOrNormal + font_family() + , // SPIString w/default + font() + , // SPIFont + font_specification() + , // SPIString // Font variants (Features) - font_variant_ligatures( ), - font_variant_position( SP_CSS_FONT_VARIANT_POSITION_NORMAL), - font_variant_caps( SP_CSS_FONT_VARIANT_CAPS_NORMAL), - font_variant_numeric( ), - font_variant_alternates(SP_CSS_FONT_VARIANT_ALTERNATES_NORMAL), - font_variant_east_asian(), - font_feature_settings( ), + font_variant_ligatures() + , font_variant_position(SP_CSS_FONT_VARIANT_POSITION_NORMAL) + , font_variant_caps(SP_CSS_FONT_VARIANT_CAPS_NORMAL) + , font_variant_numeric() + , font_variant_alternates(SP_CSS_FONT_VARIANT_ALTERNATES_NORMAL) + , font_variant_east_asian() + , font_feature_settings() + , // Variable Fonts - font_variation_settings(), // SPIFontVariationSettings + font_variation_settings() + , // SPIFontVariationSettings // Text related properties - text_indent( ), // SPILength - text_align( SP_CSS_TEXT_ALIGN_START), - - letter_spacing( ), // SPILengthOrNormal - word_spacing( ), // SPILengthOrNormal - text_transform( SP_CSS_TEXT_TRANSFORM_NONE), - - direction( SP_CSS_DIRECTION_LTR), - writing_mode( SP_CSS_WRITING_MODE_LR_TB), - text_orientation( SP_CSS_TEXT_ORIENTATION_MIXED), - dominant_baseline( SP_CSS_BASELINE_AUTO), - baseline_shift(), - text_anchor( SP_CSS_TEXT_ANCHOR_START), - white_space( SP_CSS_WHITE_SPACE_NORMAL), + text_indent() + , // SPILength + text_align(SP_CSS_TEXT_ALIGN_START) + , + + letter_spacing() + , // SPILengthOrNormal + word_spacing() + , // SPILengthOrNormal + text_transform(SP_CSS_TEXT_TRANSFORM_NONE) + , + + direction(SP_CSS_DIRECTION_LTR) + , writing_mode(SP_CSS_WRITING_MODE_LR_TB) + , text_orientation(SP_CSS_TEXT_ORIENTATION_MIXED) + , dominant_baseline(SP_CSS_BASELINE_AUTO) + , baseline_shift() + , text_anchor(SP_CSS_TEXT_ANCHOR_START) + , white_space(SP_CSS_WHITE_SPACE_NORMAL) + , // SVG 2 Text Wrapping - shape_inside( ), // SPIString - shape_subtract( ), // SPIString - shape_padding( ), // SPILength for now - shape_margin( ), // SPILength for now - inline_size( ), // SPILength for now - - text_decoration(), - text_decoration_line(), - text_decoration_style(), - text_decoration_color( ), // SPIColor - text_decoration_fill( ), // SPIPaint - text_decoration_stroke( ), // SPIPaint + shape_inside() + , // SPIString + shape_subtract() + , // SPIString + shape_padding() + , // SPILength for now + shape_margin() + , // SPILength for now + inline_size() + , // SPILength for now + + text_decoration() + , text_decoration_line() + , text_decoration_style() + , text_decoration_color() + , // SPIColor + text_decoration_fill() + , // SPIPaint + text_decoration_stroke() + , // SPIPaint // General visual properties - clip_rule( SP_WIND_RULE_NONZERO), - display( SP_CSS_DISPLAY_INLINE, false), - overflow( SP_CSS_OVERFLOW_VISIBLE, false), - visibility( SP_CSS_VISIBILITY_VISIBLE), - opacity( false), + clip_rule(SP_WIND_RULE_NONZERO) + , display(SP_CSS_DISPLAY_INLINE, false) + , overflow(SP_CSS_OVERFLOW_VISIBLE, false) + , visibility(SP_CSS_VISIBILITY_VISIBLE) + , opacity(false) + , - isolation( SP_CSS_ISOLATION_AUTO), - mix_blend_mode( SP_CSS_BLEND_NORMAL), + isolation(SP_CSS_ISOLATION_AUTO) + , mix_blend_mode(SP_CSS_BLEND_NORMAL) + , - paint_order(), // SPIPaintOrder + paint_order() + , // SPIPaintOrder // Color properties - color( ), // SPIColor - color_interpolation( SP_CSS_COLOR_INTERPOLATION_SRGB), - color_interpolation_filters(SP_CSS_COLOR_INTERPOLATION_LINEARRGB), + color() + , // SPIColor + color_interpolation(SP_CSS_COLOR_INTERPOLATION_SRGB) + , color_interpolation_filters(SP_CSS_COLOR_INTERPOLATION_LINEARRGB) + , // Solid color properties - solid_color( ), // SPIColor - solid_opacity( ), + solid_color() + , // SPIColor + solid_opacity() + , // Vector effects - vector_effect(), + vector_effect() + , // Fill properties - fill( ), // SPIPaint - fill_opacity( ), - fill_rule( SP_WIND_RULE_NONZERO), + fill() + , // SPIPaint + fill_opacity() + , fill_rule(SP_WIND_RULE_NONZERO) + , // Stroke properites - stroke( ), // SPIPaint - stroke_width( 1.0), // SPILength - stroke_linecap( SP_STROKE_LINECAP_BUTT), - stroke_linejoin( SP_STROKE_LINEJOIN_MITER), - stroke_miterlimit( 4), // SPIFloat (only use of float!) - stroke_dasharray(), // SPIDashArray - stroke_dashoffset( ), // SPILength for now - - stroke_opacity( ), - - marker( ), // SPIString - marker_start( ), // SPIString - marker_mid( ), // SPIString - marker_end( ), // SPIString + stroke() + , // SPIPaint + stroke_width(1.0) + , // SPILength + stroke_linecap(SP_STROKE_LINECAP_BUTT) + , stroke_linejoin(SP_STROKE_LINEJOIN_MITER) + , stroke_miterlimit(4) + , // SPIFloat (only use of float!) + stroke_dasharray() + , // SPIDashArray + stroke_dashoffset() + , // SPILength for now + + stroke_opacity() + , + + marker() + , // SPIString + marker_start() + , // SPIString + marker_mid() + , // SPIString + marker_end() + , // SPIString // Filter properties - filter(), - enable_background( SP_CSS_BACKGROUND_ACCUMULATE, false), + filter() + , enable_background(SP_CSS_BACKGROUND_ACCUMULATE, false) + , // Rendering hint properties - color_rendering( SP_CSS_COLOR_RENDERING_AUTO), - image_rendering( SP_CSS_IMAGE_RENDERING_AUTO), - shape_rendering( SP_CSS_SHAPE_RENDERING_AUTO), - text_rendering( SP_CSS_TEXT_RENDERING_AUTO), + color_rendering(SP_CSS_COLOR_RENDERING_AUTO) + , image_rendering(SP_CSS_IMAGE_RENDERING_AUTO) + , shape_rendering(SP_CSS_SHAPE_RENDERING_AUTO) + , text_rendering(SP_CSS_TEXT_RENDERING_AUTO) + , // Stop color and opacity - stop_color( false), // SPIColor, does not inherit - stop_opacity( false) // Does not inherit + stop_color(false) + , // SPIColor, does not inherit + stop_opacity(false) // Does not inherit { // std::cout << "SPStyle::SPStyle( SPDocument ): Entrance: (" << _count << ")" << std::endl; // std::cout << " Document: " << (document_in?"present":"null") << std::endl; @@ -413,11 +456,10 @@ SPStyle::SPStyle(SPDocument *document_in, SPObject *object_in) : cloned = false; object = object_in; - if( object ) { - g_assert( SP_IS_OBJECT(object) ); + if (object) { + g_assert(SP_IS_OBJECT(object)); document = object->document; - release_connection = - object->connectRelease(sigc::bind<1>(sigc::ptr_fun(&sp_style_object_release), this)); + release_connection = object->connectRelease(sigc::bind<1>(sigc::ptr_fun(&sp_style_object_release), this)); cloned = object->cloned; @@ -426,48 +468,47 @@ SPStyle::SPStyle(SPDocument *document_in, SPObject *object_in) : } // 'font' shorthand requires access to included properties. - font.setStylePointer( this ); + font.setStylePointer(this); // Properties that depend on 'font-size' for calculating lengths. - baseline_shift.setStylePointer( this ); - text_indent.setStylePointer( this ); - line_height.setStylePointer( this ); - letter_spacing.setStylePointer( this ); - word_spacing.setStylePointer( this ); - stroke_width.setStylePointer( this ); - stroke_dashoffset.setStylePointer( this ); - shape_padding.setStylePointer( this ); - shape_margin.setStylePointer( this ); - inline_size.setStylePointer( this ); + baseline_shift.setStylePointer(this); + text_indent.setStylePointer(this); + line_height.setStylePointer(this); + letter_spacing.setStylePointer(this); + word_spacing.setStylePointer(this); + stroke_width.setStylePointer(this); + stroke_dashoffset.setStylePointer(this); + shape_padding.setStylePointer(this); + shape_margin.setStylePointer(this); + inline_size.setStylePointer(this); // Properties that depend on 'color' - text_decoration_color.setStylePointer( this ); - fill.setStylePointer( this ); - stroke.setStylePointer( this ); + text_decoration_color.setStylePointer(this); + fill.setStylePointer(this); + stroke.setStylePointer(this); // color.setStylePointer( this ); // Doesn't need reference to self // 'text_decoration' shorthand requires access to included properties. - text_decoration.setStylePointer( this ); + text_decoration.setStylePointer(this); // SPIPaint, SPIFilter needs access to 'this' (SPStyle) // for setting up signals... 'fill', 'stroke' already done - filter.setStylePointer( this ); - shape_inside.setStylePointer( this ); - shape_subtract.setStylePointer( this ); + filter.setStylePointer(this); + shape_inside.setStylePointer(this); + shape_subtract.setStylePointer(this); // Used to iterate over markers - marker_ptrs[SP_MARKER_LOC] = ▮ + marker_ptrs[SP_MARKER_LOC] = ▮ marker_ptrs[SP_MARKER_LOC_START] = &marker_start; - marker_ptrs[SP_MARKER_LOC_MID] = &marker_mid; - marker_ptrs[SP_MARKER_LOC_END] = &marker_end; - + marker_ptrs[SP_MARKER_LOC_MID] = &marker_mid; + marker_ptrs[SP_MARKER_LOC_END] = &marker_end; // This might be too resource hungary... but for now it possible to loop over properties _properties = _prop_helper.get_vector(this); } -SPStyle::~SPStyle() { - +SPStyle::~SPStyle() +{ // std::cout << "SPStyle::~SPStyle" << std::endl; --_count; // Poor man's memory leak detector. @@ -493,16 +534,19 @@ SPStyle::~SPStyle() { // SPStyle when it is constructed and deletes it when it is destructed. The refcount is // incremented and decremented only in the files: display/drawing-item.cpp, // display/nr-filter-primitive.cpp, and libnrtype/Layout-TNG-Input.cpp. - if( _refcount > 1 ) { + if (_refcount > 1) { std::cerr << "SPStyle::~SPStyle: ref count greater than 1! " << _refcount << std::endl; } // std::cout << "SPStyle::~SPStyle(): Exit\n" << std::endl; } -const std::vector<SPIBase *> SPStyle::properties() { return this->_properties; } +const std::vector<SPIBase *> SPStyle::properties() +{ + return this->_properties; +} -void -SPStyle::clear(SPAttr id) { +void SPStyle::clear(SPAttr id) +{ SPIBase *p = _prop_helper.get(this, id); if (p) { p->clear(); @@ -511,9 +555,9 @@ SPStyle::clear(SPAttr id) { } } -void -SPStyle::clear() { - for (auto * p : _properties) { +void SPStyle::clear() +{ + for (auto *p : _properties) { p->clear(); } @@ -542,20 +586,20 @@ SPStyle::clear() { filter.href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_filter_ref_changed), this)); fill.value.href = new SPPaintServerReference(document); - fill_ps_changed_connection = fill.value.href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_fill_paint_server_ref_changed), this)); + fill_ps_changed_connection = fill.value.href->changedSignal().connect( + sigc::bind(sigc::ptr_fun(sp_style_fill_paint_server_ref_changed), this)); stroke.value.href = new SPPaintServerReference(document); - stroke_ps_changed_connection = stroke.value.href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_stroke_paint_server_ref_changed), this)); + stroke_ps_changed_connection = stroke.value.href->changedSignal().connect( + sigc::bind(sigc::ptr_fun(sp_style_stroke_paint_server_ref_changed), this)); } cloned = false; - } // Matches void sp_style_read(SPStyle *style, SPObject *object, Inkscape::XML::Node *repr) -void -SPStyle::read( SPObject *object, Inkscape::XML::Node *repr ) { - +void SPStyle::read(SPObject *object, Inkscape::XML::Node *repr) +{ // std::cout << "SPstyle::read( SPObject, Inkscape::XML::Node ): Entrance: " // << (object?(object->getId()?object->getId():"id null"):"object null") << " " // << (repr?(repr->name()?repr->name():"no name"):"repr null") @@ -578,35 +622,35 @@ SPStyle::read( SPObject *object, Inkscape::XML::Node *repr ) { /* 1. Style attribute */ // std::cout << " MERGING STYLE ATTRIBUTE" << std::endl; gchar const *val = repr->attribute("style"); - if( val != nullptr && *val ) { - _mergeString( val ); + if (val != nullptr && *val) { + _mergeString(val); } /* 2 Style sheet */ if (object) { - _mergeObjectStylesheet( object ); + _mergeObjectStylesheet(object); } /* 3 Presentation attributes */ - for (auto * p : _properties) { + for (auto *p : _properties) { // Shorthands are not allowed as presentation properites. Note: text-decoration and // font-variant are converted to shorthands in CSS 3 but can still be read as a // non-shorthand for compatibility with older renders, so they should not be in this list. if (p->id() != SPAttr::FONT && p->id() != SPAttr::MARKER) { - p->readAttribute( repr ); + p->readAttribute(repr); } } /* 4 Cascade from parent */ - if( object ) { - if( object->parent ) { - cascade( object->parent->style ); + if (object) { + if (object->parent) { + cascade(object->parent->style); } - } else if( repr->parent() ) { // When does this happen? + } else if (repr->parent()) { // When does this happen? // std::cout << "SPStyle::read(): reading via repr->parent()" << std::endl; SPStyle *parent = new SPStyle(); - parent->read( nullptr, repr->parent() ); - cascade( parent ); + parent->read(nullptr, repr->parent()); + cascade(parent); delete parent; } } @@ -618,9 +662,8 @@ SPStyle::read( SPObject *object, Inkscape::XML::Node *repr ) { * 2. Load current effective object style * 3. Load i attributes from immediate parent (which has to be up-to-date) */ -void -SPStyle::readFromObject( SPObject *object ) { - +void SPStyle::readFromObject(SPObject *object) +{ // std::cout << "SPStyle::readFromObject: "<< (object->getId()?object->getId():"null")<< std::endl; g_return_if_fail(object != nullptr); @@ -629,16 +672,15 @@ SPStyle::readFromObject( SPObject *object ) { Inkscape::XML::Node *repr = object->getRepr(); g_return_if_fail(repr != nullptr); - read( object, repr ); + read(object, repr); } /** * Read style properties from preferences. * @param path Preferences directory from which the style should be read */ -void -SPStyle::readFromPrefs(Glib::ustring const &path) { - +void SPStyle::readFromPrefs(Glib::ustring const &path) +{ g_return_if_fail(!path.empty()); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -649,11 +691,11 @@ SPStyle::readFromPrefs(Glib::ustring const &path) { Inkscape::XML::Node *tempnode = tempdoc->createElement("prefs"); std::vector<Inkscape::Preferences::Entry> attrs = prefs->getAllEntries(path); - for (auto & attr : attrs) { + for (auto &attr : attrs) { tempnode->setAttribute(attr.getEntryName(), attr.getString()); } - read( nullptr, tempnode ); + read(nullptr, tempnode); Inkscape::GC::release(tempnode); Inkscape::GC::release(tempdoc); @@ -661,9 +703,8 @@ SPStyle::readFromPrefs(Glib::ustring const &path) { } // Matches sp_style_merge_property(SPStyle *style, gint id, gchar const *val) -void -SPStyle::readIfUnset(SPAttr id, gchar const *val, SPStyleSrc const &source ) { - +void SPStyle::readIfUnset(SPAttr id, gchar const *val, SPStyleSrc const &source) +{ // std::cout << "SPStyle::readIfUnset: Entrance: " << id << ": " << (val?val:"null") << std::endl; // To Do: If it is not too slow, use std::map instead of std::vector inorder to remove switch() // (looking up SPAttr::xxxx already uses a hash). @@ -681,7 +722,7 @@ SPStyle::readIfUnset(SPAttr id, gchar const *val, SPStyleSrc const &source ) { */ g_warning_once("attribute 'clip-path' given as CSS"); - //XML Tree being directly used here. + // XML Tree being directly used here. if (object) { object->setAttribute("clip-path", val); } @@ -691,19 +732,20 @@ SPStyle::readIfUnset(SPAttr id, gchar const *val, SPStyleSrc const &source ) { * See comment for SPAttr::CLIP_PATH */ g_warning_once("attribute 'mask' given as CSS"); - - //XML Tree being directly used here. + + // XML Tree being directly used here. if (object) { object->setAttribute("mask", val); } return; case SPAttr::FILTER: - if( !filter.inherit ) filter.readIfUnset( val, source ); + if (!filter.inherit) + filter.readIfUnset(val, source); return; case SPAttr::COLOR_INTERPOLATION: // We read it but issue warning - color_interpolation.readIfUnset( val, source ); - if( color_interpolation.value != SP_CSS_COLOR_INTERPOLATION_SRGB ) { + color_interpolation.readIfUnset(val, source); + if (color_interpolation.value != SP_CSS_COLOR_INTERPOLATION_SRGB) { g_warning("Inkscape currently only supports color-interpolation = sRGB"); } return; @@ -757,23 +799,22 @@ bool SPStyle::isSet(SPAttr id) * \pre base. * \post ret != NULL. */ -Glib::ustring -SPStyle::write( guint const flags, SPStyleSrc const &style_src_req, SPStyle const *const base ) const { - +Glib::ustring SPStyle::write(guint const flags, SPStyleSrc const &style_src_req, SPStyle const *const base) const +{ // std::cout << "SPStyle::write: flags: " << flags << std::endl; Glib::ustring style_string; - for(std::vector<SPIBase*>::size_type i = 0; i != _properties.size(); ++i) { - if( base != nullptr ) { - style_string += _properties[i]->write( flags, style_src_req, base->_properties[i] ); + for (std::vector<SPIBase *>::size_type i = 0; i != _properties.size(); ++i) { + if (base != nullptr) { + style_string += _properties[i]->write(flags, style_src_req, base->_properties[i]); } else { - style_string += _properties[i]->write( flags, style_src_req, nullptr ); + style_string += _properties[i]->write(flags, style_src_req, nullptr); } } // Remove trailing ';' - if( style_string.size() > 0 ) { - style_string.erase( style_string.size() - 1 ); + if (style_string.size() > 0) { + style_string.erase(style_string.size() - 1); } return style_string; } @@ -790,11 +831,11 @@ SPStyle::write( guint const flags, SPStyleSrc const &style_src_req, SPStyle cons * * \pre \a parent's computed values are already up-to-date. */ -void -SPStyle::cascade( SPStyle const *const parent ) { +void SPStyle::cascade(SPStyle const *const parent) +{ // std::cout << "SPStyle::cascade: " << (object->getId()?object->getId():"null") << std::endl; - for(std::vector<SPIBase*>::size_type i = 0; i != _properties.size(); ++i) { - _properties[i]->cascade( parent->_properties[i] ); + for (std::vector<SPIBase *>::size_type i = 0; i != _properties.size(); ++i) { + _properties[i]->cascade(parent->_properties[i]); } } @@ -816,86 +857,82 @@ SPStyle::cascade( SPStyle const *const parent ) { * \pre \a parent's computed values are already up-to-date. * (\a style's computed values needn't be up-to-date.) */ -void -SPStyle::merge( SPStyle const *const parent ) { +void SPStyle::merge(SPStyle const *const parent) +{ // std::cout << "SPStyle::merge" << std::endl; - for(std::vector<SPIBase*>::size_type i = 0; i != _properties.size(); ++i) { - _properties[i]->merge( parent->_properties[i] ); + for (std::vector<SPIBase *>::size_type i = 0; i != _properties.size(); ++i) { + _properties[i]->merge(parent->_properties[i]); } } /** * Parses a style="..." string and merges it with an existing SPStyle. */ -void -SPStyle::mergeString( gchar const *const p ) { - _mergeString( p ); +void SPStyle::mergeString(gchar const *const p) +{ + _mergeString(p); } /** - * Append an existing css statement into this style, used in css editing - * always appends declarations as STYLE_SHEET properties. - */ -void -SPStyle::mergeStatement( CRStatement *statement ) { + * Append an existing css statement into this style, used in css editing + * always appends declarations as STYLE_SHEET properties. + */ +void SPStyle::mergeStatement(CRStatement *statement) +{ if (statement->type != RULESET_STMT) { return; } CRDeclaration *decl_list = nullptr; - cr_statement_ruleset_get_declarations (statement, &decl_list); + cr_statement_ruleset_get_declarations(statement, &decl_list); if (decl_list) { _mergeDeclList(decl_list, SP_STYLE_SRC_STYLE_SHEET); } } // Mostly for unit testing -bool -SPStyle::operator==(const SPStyle& rhs) { - +bool SPStyle::operator==(const SPStyle &rhs) +{ // Uncomment for testing // for(std::vector<SPIBase*>::size_type i = 0; i != _properties.size(); ++i) { // if( *_properties[i] != *rhs._properties[i]) // std::cout << _properties[i]->name << ": " - // << _properties[i]->write(SP_STYLE_FLAG_ALWAYS,NULL) << " " + // << _properties[i]->write(SP_STYLE_FLAG_ALWAYS,NULL) << " " // << rhs._properties[i]->write(SP_STYLE_FLAG_ALWAYS,NULL) // << (*_properties[i] == *rhs._properties[i]) << std::endl; // } - for(std::vector<SPIBase*>::size_type i = 0; i != _properties.size(); ++i) { - if( *_properties[i] != *rhs._properties[i]) return false; + for (std::vector<SPIBase *>::size_type i = 0; i != _properties.size(); ++i) { + if (*_properties[i] != *rhs._properties[i]) + return false; } return true; } -void -SPStyle::_mergeString( gchar const *const p ) { - +void SPStyle::_mergeString(gchar const *const p) +{ // std::cout << "SPStyle::_mergeString: " << (p?p:"null") << std::endl; - CRDeclaration *const decl_list - = cr_declaration_parse_list_from_buf(reinterpret_cast<guchar const *>(p), CR_UTF_8); + CRDeclaration *const decl_list = cr_declaration_parse_list_from_buf(reinterpret_cast<guchar const *>(p), CR_UTF_8); if (decl_list) { - _mergeDeclList( decl_list, SP_STYLE_SRC_STYLE_PROP ); + _mergeDeclList(decl_list, SP_STYLE_SRC_STYLE_PROP); cr_declaration_destroy(decl_list); } } -void -SPStyle::_mergeDeclList( CRDeclaration const *const decl_list, SPStyleSrc const &source ) { - +void SPStyle::_mergeDeclList(CRDeclaration const *const decl_list, SPStyleSrc const &source) +{ // std::cout << "SPStyle::_mergeDeclList" << std::endl; // In reverse order, as later declarations to take precedence over earlier ones. // (Properties are only set if not previously set. See: // Ref: http://www.w3.org/TR/REC-CSS2/cascade.html#cascading-order point 4.) if (decl_list->next) { - _mergeDeclList( decl_list->next, source ); + _mergeDeclList(decl_list->next, source); } - _mergeDecl( decl_list, source ); + _mergeDecl(decl_list, source); } -void -SPStyle::_mergeDecl( CRDeclaration const *const decl, SPStyleSrc const &source ) { - +void SPStyle::_mergeDecl(CRDeclaration const *const decl, SPStyleSrc const &source) +{ // std::cout << "SPStyle::_mergeDecl" << std::endl; auto prop_idx = sp_attribute_lookup(decl->property->stryng->str); @@ -920,23 +957,21 @@ SPStyle::_mergeDecl( CRDeclaration const *const decl, SPStyleSrc const &source } } -void -SPStyle::_mergeProps( CRPropList *const props ) { - +void SPStyle::_mergeProps(CRPropList *const props) +{ // std::cout << "SPStyle::_mergeProps" << std::endl; // In reverse order, as later declarations to take precedence over earlier ones. if (props) { - _mergeProps( cr_prop_list_get_next( props ) ); + _mergeProps(cr_prop_list_get_next(props)); CRDeclaration *decl = nullptr; cr_prop_list_get_decl(props, &decl); - _mergeDecl( decl, SP_STYLE_SRC_STYLE_SHEET ); + _mergeDecl(decl, SP_STYLE_SRC_STYLE_SHEET); } } -void -SPStyle::_mergeObjectStylesheet( SPObject const *const object ) { - +void SPStyle::_mergeObjectStylesheet(SPObject const *const object) +{ // std::cout << "SPStyle::_mergeObjectStylesheet: " << (object->getId()?object->getId():"null") << std::endl; static CRSelEng *sel_eng = nullptr; @@ -946,12 +981,9 @@ SPStyle::_mergeObjectStylesheet( SPObject const *const object ) { CRPropList *props = nullptr; - //XML Tree being directly used here while it shouldn't be. - CRStatus status = - cr_sel_eng_get_matched_properties_from_cascade(sel_eng, - object->document->getStyleCascade(), - object->getRepr(), - &props); + // XML Tree being directly used here while it shouldn't be. + CRStatus status = cr_sel_eng_get_matched_properties_from_cascade(sel_eng, object->document->getStyleCascade(), + object->getRepr(), &props); g_return_if_fail(status == CR_OK); /// \todo Check what errors can occur, and handle them properly. if (props) { @@ -960,18 +992,17 @@ SPStyle::_mergeObjectStylesheet( SPObject const *const object ) { } } -std::string -SPStyle::getFontFeatureString() { - +std::string SPStyle::getFontFeatureString() +{ std::string feature_string; - if ( !(font_variant_ligatures.value & SP_CSS_FONT_VARIANT_LIGATURES_COMMON) ) + if (!(font_variant_ligatures.value & SP_CSS_FONT_VARIANT_LIGATURES_COMMON)) feature_string += "liga 0, clig 0, "; - if ( font_variant_ligatures.value & SP_CSS_FONT_VARIANT_LIGATURES_DISCRETIONARY ) + if (font_variant_ligatures.value & SP_CSS_FONT_VARIANT_LIGATURES_DISCRETIONARY) feature_string += "dlig, "; - if ( font_variant_ligatures.value & SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL ) + if (font_variant_ligatures.value & SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL) feature_string += "hlig, "; - if ( !(font_variant_ligatures.value & SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL) ) + if (!(font_variant_ligatures.value & SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL)) feature_string += "calt 0, "; switch (font_variant_position.value) { @@ -1002,40 +1033,40 @@ SPStyle::getFontFeatureString() { feature_string += "titl, "; } - if ( font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_LINING_NUMS ) + if (font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_LINING_NUMS) feature_string += "lnum, "; - if ( font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_OLDSTYLE_NUMS ) + if (font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_OLDSTYLE_NUMS) feature_string += "onum, "; - if ( font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_PROPORTIONAL_NUMS ) + if (font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_PROPORTIONAL_NUMS) feature_string += "pnum, "; - if ( font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_TABULAR_NUMS ) + if (font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_TABULAR_NUMS) feature_string += "tnum, "; - if ( font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_DIAGONAL_FRACTIONS ) + if (font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_DIAGONAL_FRACTIONS) feature_string += "frac, "; - if ( font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_STACKED_FRACTIONS ) + if (font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_STACKED_FRACTIONS) feature_string += "afrc, "; - if ( font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_ORDINAL ) + if (font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_ORDINAL) feature_string += "ordn, "; - if ( font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_SLASHED_ZERO ) + if (font_variant_numeric.value & SP_CSS_FONT_VARIANT_NUMERIC_SLASHED_ZERO) feature_string += "zero, "; - if( font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS78 ) + if (font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS78) feature_string += "jp78, "; - if( font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS83 ) + if (font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS83) feature_string += "jp83, "; - if( font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS90 ) + if (font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS90) feature_string += "jp90, "; - if( font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS04 ) + if (font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS04) feature_string += "jp04, "; - if( font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_SIMPLIFIED ) + if (font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_SIMPLIFIED) feature_string += "smpl, "; - if( font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_TRADITIONAL ) + if (font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_TRADITIONAL) feature_string += "trad, "; - if( font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_FULL_WIDTH ) + if (font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_FULL_WIDTH) feature_string += "fwid, "; - if( font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_PROPORTIONAL_WIDTH ) + if (font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_PROPORTIONAL_WIDTH) feature_string += "pwid, "; - if( font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_RUBY ) + if (font_variant_east_asian.value & SP_CSS_FONT_VARIANT_EAST_ASIAN_RUBY) feature_string += "ruby, "; char const *val = font_feature_settings.value(); @@ -1055,13 +1086,11 @@ SPStyle::getFontFeatureString() { return feature_string; } - // Internal /** * Release callback. */ -static void -sp_style_object_release(SPObject *object, SPStyle *style) +static void sp_style_object_release(SPObject *object, SPStyle *style) { (void)object; // TODO style->object = nullptr; @@ -1071,13 +1100,11 @@ sp_style_object_release(SPObject *object, SPStyle *style) /** * Emit style modified signal on style's object if the filter changed. */ -static void -sp_style_filter_ref_modified(SPObject *obj, guint flags, SPStyle *style) +static void sp_style_filter_ref_modified(SPObject *obj, guint flags, SPStyle *style) { (void)flags; // TODO - SPFilter *filter=static_cast<SPFilter *>(obj); - if (style->getFilter() == filter) - { + SPFilter *filter = static_cast<SPFilter *>(obj); + if (style->getFilter() == filter) { if (style->object) { style->object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); } @@ -1088,18 +1115,16 @@ sp_style_filter_ref_modified(SPObject *obj, guint flags, SPStyle *style) /** * Gets called when the filter is (re)attached to the style */ -void -sp_style_filter_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style) +void sp_style_filter_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style) { if (old_ref) { - (dynamic_cast<SPFilter *>( old_ref ))->_refcount--; + (dynamic_cast<SPFilter *>(old_ref))->_refcount--; style->filter_modified_connection.disconnect(); } - if ( SP_IS_FILTER(ref)) - { - (dynamic_cast<SPFilter *>( ref ))->_refcount++; + if (SP_IS_FILTER(ref)) { + (dynamic_cast<SPFilter *>(ref))->_refcount++; style->filter_modified_connection = - ref->connectModified(sigc::bind(sigc::ptr_fun(&sp_style_filter_ref_modified), style)); + ref->connectModified(sigc::bind(sigc::ptr_fun(&sp_style_filter_ref_modified), style)); } sp_style_filter_ref_modified(ref, 0, style); @@ -1109,15 +1134,12 @@ sp_style_filter_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style) * Emit style modified signal on style's object if server is style's fill * or stroke paint server. */ -static void -sp_style_paint_server_ref_modified(SPObject *obj, guint flags, SPStyle *style) +static void sp_style_paint_server_ref_modified(SPObject *obj, guint flags, SPStyle *style) { (void)flags; // TODO SPPaintServer *server = static_cast<SPPaintServer *>(obj); - if ((style->fill.isPaintserver()) - && style->getFillPaintServer() == server) - { + if ((style->fill.isPaintserver()) && style->getFillPaintServer() == server) { if (style->object) { /** \todo * fixme: I do not know, whether it is optimal - we are @@ -1129,9 +1151,7 @@ sp_style_paint_server_ref_modified(SPObject *obj, guint flags, SPStyle *style) */ style->object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); } - } else if ((style->stroke.isPaintserver()) - && style->getStrokePaintServer() == server) - { + } else if ((style->stroke.isPaintserver()) && style->getStrokePaintServer() == server) { if (style->object) { /// \todo fixme: style->object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); @@ -1144,15 +1164,14 @@ sp_style_paint_server_ref_modified(SPObject *obj, guint flags, SPStyle *style) /** * Gets called when the paintserver is (re)attached to the style */ -void -sp_style_fill_paint_server_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style) +void sp_style_fill_paint_server_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style) { if (old_ref) { style->fill_ps_modified_connection.disconnect(); } if (SP_IS_PAINT_SERVER(ref)) { style->fill_ps_modified_connection = - ref->connectModified(sigc::bind(sigc::ptr_fun(&sp_style_paint_server_ref_modified), style)); + ref->connectModified(sigc::bind(sigc::ptr_fun(&sp_style_paint_server_ref_modified), style)); } style->signal_fill_ps_changed.emit(old_ref, ref); @@ -1162,15 +1181,14 @@ sp_style_fill_paint_server_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle /** * Gets called when the paintserver is (re)attached to the style */ -void -sp_style_stroke_paint_server_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style) +void sp_style_stroke_paint_server_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style) { if (old_ref) { style->stroke_ps_modified_connection.disconnect(); } if (SP_IS_PAINT_SERVER(ref)) { style->stroke_ps_modified_connection = - ref->connectModified(sigc::bind(sigc::ptr_fun(&sp_style_paint_server_ref_modified), style)); + ref->connectModified(sigc::bind(sigc::ptr_fun(&sp_style_paint_server_ref_modified), style)); } style->signal_stroke_ps_changed.emit(old_ref, ref); @@ -1181,8 +1199,7 @@ sp_style_stroke_paint_server_ref_changed(SPObject *old_ref, SPObject *ref, SPSty /** * Increase refcount of style. */ -SPStyle * -sp_style_ref(SPStyle *style) +SPStyle *sp_style_ref(SPStyle *style) { g_return_val_if_fail(style != nullptr, NULL); @@ -1195,8 +1212,7 @@ sp_style_ref(SPStyle *style) /** * Decrease refcount of style with possible destruction. */ -SPStyle * -sp_style_unref(SPStyle *style) +SPStyle *sp_style_unref(SPStyle *style) { g_return_val_if_fail(style != nullptr, NULL); if (style->style_unref() < 1) { @@ -1206,8 +1222,7 @@ sp_style_unref(SPStyle *style) return style; } -static CRSelEng * -sp_repr_sel_eng() +static CRSelEng *sp_repr_sel_eng() { CRSelEng *const ret = cr_sel_eng_new(); cr_sel_eng_set_node_iface(ret, &Inkscape::XML::croco_node_iface); @@ -1231,11 +1246,9 @@ sp_repr_sel_eng() // The following functions should be incorporated into SPIPaint. FIXME // Called in: style.cpp, style-internal.cpp -void -sp_style_set_ipaint_to_uri(SPStyle *style, SPIPaint *paint, const Inkscape::URI *uri, SPDocument *document) +void sp_style_set_ipaint_to_uri(SPStyle *style, SPIPaint *paint, const Inkscape::URI *uri, SPDocument *document) { if (!paint->value.href) { - if (style->object) { // Should not happen as href should have been created in SPIPaint. (TODO: Removed code duplication.) paint->value.href = new SPPaintServerReference(style->object); @@ -1250,14 +1263,16 @@ sp_style_set_ipaint_to_uri(SPStyle *style, SPIPaint *paint, const Inkscape::URI } if (paint == &style->fill) { - style->fill_ps_changed_connection = paint->value.href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_fill_paint_server_ref_changed), style)); + style->fill_ps_changed_connection = paint->value.href->changedSignal().connect( + sigc::bind(sigc::ptr_fun(sp_style_fill_paint_server_ref_changed), style)); } else { - style->stroke_ps_changed_connection = paint->value.href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_stroke_paint_server_ref_changed), style)); + style->stroke_ps_changed_connection = paint->value.href->changedSignal().connect( + sigc::bind(sigc::ptr_fun(sp_style_stroke_paint_server_ref_changed), style)); } } - if (paint->value.href){ - if (paint->value.href->getObject()){ + if (paint->value.href) { + if (paint->value.href->getObject()) { paint->value.href->detach(); } @@ -1271,8 +1286,7 @@ sp_style_set_ipaint_to_uri(SPStyle *style, SPIPaint *paint, const Inkscape::URI } // Called in: style.cpp, style-internal.cpp -void -sp_style_set_ipaint_to_uri_string (SPStyle *style, SPIPaint *paint, const gchar *uri) +void sp_style_set_ipaint_to_uri_string(SPStyle *style, SPIPaint *paint, const gchar *uri) { try { const Inkscape::URI IURI(uri); @@ -1289,25 +1303,34 @@ void sp_style_set_to_uri(SPStyle *style, bool isfill, Inkscape::URI const *uri) } // Called in: widgets/font-selector.cpp, widgets/text-toolbar.cpp, ui/dialog/text-edit.cpp -gchar const * -sp_style_get_css_unit_string(int unit) +gchar const *sp_style_get_css_unit_string(int unit) { // specify px by default, see inkscape bug 1221626, mozilla bug 234789 // This is a problematic fix as some properties (e.g. 'line-height') have // different behaviour if there is no unit. switch (unit) { - - case SP_CSS_UNIT_NONE: return "px"; - case SP_CSS_UNIT_PX: return "px"; - case SP_CSS_UNIT_PT: return "pt"; - case SP_CSS_UNIT_PC: return "pc"; - case SP_CSS_UNIT_MM: return "mm"; - case SP_CSS_UNIT_CM: return "cm"; - case SP_CSS_UNIT_IN: return "in"; - case SP_CSS_UNIT_EM: return "em"; - case SP_CSS_UNIT_EX: return "ex"; - case SP_CSS_UNIT_PERCENT: return "%"; - default: return "px"; + case SP_CSS_UNIT_NONE: + return "px"; + case SP_CSS_UNIT_PX: + return "px"; + case SP_CSS_UNIT_PT: + return "pt"; + case SP_CSS_UNIT_PC: + return "pc"; + case SP_CSS_UNIT_MM: + return "mm"; + case SP_CSS_UNIT_CM: + return "cm"; + case SP_CSS_UNIT_IN: + return "in"; + case SP_CSS_UNIT_EM: + return "em"; + case SP_CSS_UNIT_EX: + return "ex"; + case SP_CSS_UNIT_PERCENT: + return "%"; + default: + return "px"; } return "px"; } @@ -1316,8 +1339,7 @@ sp_style_get_css_unit_string(int unit) /* * Convert a size in pixels into another CSS unit size */ -double -sp_style_css_size_px_to_units(double size, int unit, double font_size) +double sp_style_css_size_px_to_units(double size, int unit, double font_size) { double unit_size = size; @@ -1327,17 +1349,36 @@ sp_style_css_size_px_to_units(double size, int unit, double font_size) } switch (unit) { - - case SP_CSS_UNIT_NONE: unit_size = size; break; - case SP_CSS_UNIT_PX: unit_size = size; break; - case SP_CSS_UNIT_PT: unit_size = Inkscape::Util::Quantity::convert(size, "px", "pt"); break; - case SP_CSS_UNIT_PC: unit_size = Inkscape::Util::Quantity::convert(size, "px", "pc"); break; - case SP_CSS_UNIT_MM: unit_size = Inkscape::Util::Quantity::convert(size, "px", "mm"); break; - case SP_CSS_UNIT_CM: unit_size = Inkscape::Util::Quantity::convert(size, "px", "cm"); break; - case SP_CSS_UNIT_IN: unit_size = Inkscape::Util::Quantity::convert(size, "px", "in"); break; - case SP_CSS_UNIT_EM: unit_size = size / font_size; break; - case SP_CSS_UNIT_EX: unit_size = size * 2.0 / font_size ; break; - case SP_CSS_UNIT_PERCENT: unit_size = size * 100.0 / font_size; break; + case SP_CSS_UNIT_NONE: + unit_size = size; + break; + case SP_CSS_UNIT_PX: + unit_size = size; + break; + case SP_CSS_UNIT_PT: + unit_size = Inkscape::Util::Quantity::convert(size, "px", "pt"); + break; + case SP_CSS_UNIT_PC: + unit_size = Inkscape::Util::Quantity::convert(size, "px", "pc"); + break; + case SP_CSS_UNIT_MM: + unit_size = Inkscape::Util::Quantity::convert(size, "px", "mm"); + break; + case SP_CSS_UNIT_CM: + unit_size = Inkscape::Util::Quantity::convert(size, "px", "cm"); + break; + case SP_CSS_UNIT_IN: + unit_size = Inkscape::Util::Quantity::convert(size, "px", "in"); + break; + case SP_CSS_UNIT_EM: + unit_size = size / font_size; + break; + case SP_CSS_UNIT_EX: + unit_size = size * 2.0 / font_size; + break; + case SP_CSS_UNIT_PERCENT: + unit_size = size * 100.0 / font_size; + break; default: g_warning("sp_style_get_css_font_size_units conversion to %d not implemented.", unit); @@ -1351,25 +1392,24 @@ sp_style_css_size_px_to_units(double size, int unit, double font_size) /* * Convert a size in a CSS unit size to pixels */ -double -sp_style_css_size_units_to_px(double size, int unit, double font_size) +double sp_style_css_size_units_to_px(double size, int unit, double font_size) { if (unit == SP_CSS_UNIT_PX) { return size; } - //g_message("sp_style_css_size_units_to_px %f %d = %f px", size, unit, out); - return size * (size / sp_style_css_size_px_to_units(size, unit, font_size));; + // g_message("sp_style_css_size_units_to_px %f %d = %f px", size, unit, out); + return size * (size / sp_style_css_size_px_to_units(size, unit, font_size)); + ; } - // FIXME: Everything below this line belongs in a different file - css-chemistry? -void -sp_style_set_property_url (SPObject *item, gchar const *property, SPObject *linked, bool recursive) +void sp_style_set_property_url(SPObject *item, gchar const *property, SPObject *linked, bool recursive) { Inkscape::XML::Node *repr = item->getRepr(); - if (repr == nullptr) return; + if (repr == nullptr) + return; SPCSSAttr *css = sp_repr_css_attr_new(); if (linked) { @@ -1393,13 +1433,10 @@ sp_style_set_property_url (SPObject *item, gchar const *property, SPObject *link * \pre flags in {IFSET, ALWAYS}. * Only used by sp_css_attr_from_object() and in splivarot.cpp - sp_item_path_outline(). */ -SPCSSAttr * -sp_css_attr_from_style(SPStyle const *const style, guint const flags) +SPCSSAttr *sp_css_attr_from_style(SPStyle const *const style, guint const flags) { g_return_val_if_fail(style != nullptr, NULL); - g_return_val_if_fail(((flags & SP_STYLE_FLAG_IFSET) || - (flags & SP_STYLE_FLAG_ALWAYS)), - NULL); + g_return_val_if_fail(((flags & SP_STYLE_FLAG_IFSET) || (flags & SP_STYLE_FLAG_ALWAYS)), NULL); Glib::ustring style_str = style->write(flags); SPCSSAttr *css = sp_repr_css_attr_new(); sp_repr_css_attr_add_from_string(css, style_str.c_str()); @@ -1414,10 +1451,8 @@ sp_css_attr_from_style(SPStyle const *const style, guint const flags) */ SPCSSAttr *sp_css_attr_from_object(SPObject *object, guint const flags) { - g_return_val_if_fail(((flags == SP_STYLE_FLAG_IFSET) || - (flags == SP_STYLE_FLAG_ALWAYS) ), - NULL); - SPCSSAttr * result = nullptr; + g_return_val_if_fail(((flags == SP_STYLE_FLAG_IFSET) || (flags == SP_STYLE_FLAG_ALWAYS)), NULL); + SPCSSAttr *result = nullptr; if (object->style) { result = sp_css_attr_from_style(object->style, flags); } @@ -1428,8 +1463,7 @@ SPCSSAttr *sp_css_attr_from_object(SPObject *object, guint const flags) /** * Unset any text-related properties */ -SPCSSAttr * -sp_css_attr_unset_text(SPCSSAttr *css) +SPCSSAttr *sp_css_attr_unset_text(SPCSSAttr *css) { sp_repr_css_set_property(css, "font", nullptr); sp_repr_css_set_property(css, "-inkscape-font-specification", nullptr); @@ -1456,8 +1490,8 @@ sp_css_attr_unset_text(SPCSSAttr *css) sp_repr_css_set_property(css, "shape-padding", nullptr); sp_repr_css_set_property(css, "shape-margin", nullptr); sp_repr_css_set_property(css, "inline-size", nullptr); - sp_repr_css_set_property(css, "kerning", nullptr); // not implemented yet - sp_repr_css_set_property(css, "dominant-baseline", nullptr); // not implemented yet + sp_repr_css_set_property(css, "kerning", nullptr); // not implemented yet + sp_repr_css_set_property(css, "dominant-baseline", nullptr); // not implemented yet sp_repr_css_set_property(css, "alignment-baseline", nullptr); // not implemented yet sp_repr_css_set_property(css, "baseline-shift", nullptr); @@ -1482,41 +1516,39 @@ sp_css_attr_unset_text(SPCSSAttr *css) * Unset properties that should not be set for default tool style. * This list needs to be reviewed. */ -SPCSSAttr * -sp_css_attr_unset_blacklist(SPCSSAttr *css) +SPCSSAttr *sp_css_attr_unset_blacklist(SPCSSAttr *css) { - sp_repr_css_set_property(css, "color", nullptr); - sp_repr_css_set_property(css, "clip-rule", nullptr); - sp_repr_css_set_property(css, "d", nullptr); - sp_repr_css_set_property(css, "display", nullptr); - sp_repr_css_set_property(css, "overflow", nullptr); - sp_repr_css_set_property(css, "visibility", nullptr); - sp_repr_css_set_property(css, "isolation", nullptr); - sp_repr_css_set_property(css, "mix-blend-mode", nullptr); + sp_repr_css_set_property(css, "color", nullptr); + sp_repr_css_set_property(css, "clip-rule", nullptr); + sp_repr_css_set_property(css, "d", nullptr); + sp_repr_css_set_property(css, "display", nullptr); + sp_repr_css_set_property(css, "overflow", nullptr); + sp_repr_css_set_property(css, "visibility", nullptr); + sp_repr_css_set_property(css, "isolation", nullptr); + sp_repr_css_set_property(css, "mix-blend-mode", nullptr); sp_repr_css_set_property(css, "color-interpolation", nullptr); sp_repr_css_set_property(css, "color-interpolation-filters", nullptr); - sp_repr_css_set_property(css, "solid-color", nullptr); - sp_repr_css_set_property(css, "solid-opacity", nullptr); - sp_repr_css_set_property(css, "fill-rule", nullptr); - sp_repr_css_set_property(css, "color-rendering", nullptr); - sp_repr_css_set_property(css, "image-rendering", nullptr); - sp_repr_css_set_property(css, "shape-rendering", nullptr); - sp_repr_css_set_property(css, "text-rendering", nullptr); - sp_repr_css_set_property(css, "enable-background", nullptr); + sp_repr_css_set_property(css, "solid-color", nullptr); + sp_repr_css_set_property(css, "solid-opacity", nullptr); + sp_repr_css_set_property(css, "fill-rule", nullptr); + sp_repr_css_set_property(css, "color-rendering", nullptr); + sp_repr_css_set_property(css, "image-rendering", nullptr); + sp_repr_css_set_property(css, "shape-rendering", nullptr); + sp_repr_css_set_property(css, "text-rendering", nullptr); + sp_repr_css_set_property(css, "enable-background", nullptr); return css; } // Called in style.cpp -static bool -is_url(char const *p) +static bool is_url(char const *p) { if (p == nullptr) return false; -/** \todo - * FIXME: I'm not sure if this applies to SVG as well, but CSS2 says any URIs - * in property values must start with 'url('. - */ + /** \todo + * FIXME: I'm not sure if this applies to SVG as well, but CSS2 says any URIs + * in property values must start with 'url('. + */ return (g_ascii_strncasecmp(p, "url(", 4) == 0); } @@ -1527,21 +1559,31 @@ is_url(char const *p) * Used for storing style that will be reused across documents when carrying * the referenced defs is impractical. */ -SPCSSAttr * -sp_css_attr_unset_uris(SPCSSAttr *css) +SPCSSAttr *sp_css_attr_unset_uris(SPCSSAttr *css) { -// All properties that may hold <uri> or <paint> according to SVG 1.1 - if (is_url(sp_repr_css_property(css, "clip-path", nullptr))) sp_repr_css_set_property(css, "clip-path", nullptr); - if (is_url(sp_repr_css_property(css, "color-profile", nullptr))) sp_repr_css_set_property(css, "color-profile", nullptr); - if (is_url(sp_repr_css_property(css, "cursor", nullptr))) sp_repr_css_set_property(css, "cursor", nullptr); - if (is_url(sp_repr_css_property(css, "filter", nullptr))) sp_repr_css_set_property(css, "filter", nullptr); - if (is_url(sp_repr_css_property(css, "marker", nullptr))) sp_repr_css_set_property(css, "marker", nullptr); - if (is_url(sp_repr_css_property(css, "marker-start", nullptr))) sp_repr_css_set_property(css, "marker-start", nullptr); - if (is_url(sp_repr_css_property(css, "marker-mid", nullptr))) sp_repr_css_set_property(css, "marker-mid", nullptr); - if (is_url(sp_repr_css_property(css, "marker-end", nullptr))) sp_repr_css_set_property(css, "marker-end", nullptr); - if (is_url(sp_repr_css_property(css, "mask", nullptr))) sp_repr_css_set_property(css, "mask", nullptr); - if (is_url(sp_repr_css_property(css, "fill", nullptr))) sp_repr_css_set_property(css, "fill", nullptr); - if (is_url(sp_repr_css_property(css, "stroke", nullptr))) sp_repr_css_set_property(css, "stroke", nullptr); + // All properties that may hold <uri> or <paint> according to SVG 1.1 + if (is_url(sp_repr_css_property(css, "clip-path", nullptr))) + sp_repr_css_set_property(css, "clip-path", nullptr); + if (is_url(sp_repr_css_property(css, "color-profile", nullptr))) + sp_repr_css_set_property(css, "color-profile", nullptr); + if (is_url(sp_repr_css_property(css, "cursor", nullptr))) + sp_repr_css_set_property(css, "cursor", nullptr); + if (is_url(sp_repr_css_property(css, "filter", nullptr))) + sp_repr_css_set_property(css, "filter", nullptr); + if (is_url(sp_repr_css_property(css, "marker", nullptr))) + sp_repr_css_set_property(css, "marker", nullptr); + if (is_url(sp_repr_css_property(css, "marker-start", nullptr))) + sp_repr_css_set_property(css, "marker-start", nullptr); + if (is_url(sp_repr_css_property(css, "marker-mid", nullptr))) + sp_repr_css_set_property(css, "marker-mid", nullptr); + if (is_url(sp_repr_css_property(css, "marker-end", nullptr))) + sp_repr_css_set_property(css, "marker-end", nullptr); + if (is_url(sp_repr_css_property(css, "mask", nullptr))) + sp_repr_css_set_property(css, "mask", nullptr); + if (is_url(sp_repr_css_property(css, "fill", nullptr))) + sp_repr_css_set_property(css, "fill", nullptr); + if (is_url(sp_repr_css_property(css, "stroke", nullptr))) + sp_repr_css_set_property(css, "stroke", nullptr); return css; } @@ -1550,15 +1592,14 @@ sp_css_attr_unset_uris(SPCSSAttr *css) /** * Scale a single-value property. */ -static void -sp_css_attr_scale_property_single(SPCSSAttr *css, gchar const *property, - double ex, bool only_with_units = false) +static void sp_css_attr_scale_property_single(SPCSSAttr *css, gchar const *property, double ex, + bool only_with_units = false) { gchar const *w = sp_repr_css_property(css, property, nullptr); if (w) { gchar *units = nullptr; double wd = g_ascii_strtod(w, &units) * ex; - if (w == units) {// nothing converted, non-numeric value + if (w == units) { // nothing converted, non-numeric value return; } if (only_with_units && (units == nullptr || *units == '\0' || *units == '%' || *units == 'e')) { @@ -1576,8 +1617,7 @@ sp_css_attr_scale_property_single(SPCSSAttr *css, gchar const *property, /** * Scale a list-of-values property. */ -static void -sp_css_attr_scale_property_list(SPCSSAttr *css, gchar const *property, double ex) +static void sp_css_attr_scale_property_list(SPCSSAttr *css, gchar const *property, double ex) { gchar const *string = sp_repr_css_property(css, property, nullptr); if (string) { @@ -1590,7 +1630,7 @@ sp_css_attr_scale_property_list(SPCSSAttr *css, gchar const *property, double ex break; gchar *units = nullptr; double wd = g_ascii_strtod(w, &units) * ex; - if (w == units) {// nothing converted, non-numeric value ("none" or "inherit"); do nothing + if (w == units) { // nothing converted, non-numeric value ("none" or "inherit"); do nothing g_strfreev(a); return; } @@ -1605,16 +1645,15 @@ sp_css_attr_scale_property_list(SPCSSAttr *css, gchar const *property, double ex } } -// Called in: text-editing.cpp, +// Called in: text-editing.cpp, /** * Scale any properties that may hold <length> by ex. */ -SPCSSAttr * -sp_css_attr_scale(SPCSSAttr *css, double ex) +SPCSSAttr *sp_css_attr_scale(SPCSSAttr *css, double ex) { sp_css_attr_scale_property_single(css, "baseline-shift", ex); sp_css_attr_scale_property_single(css, "stroke-width", ex); - sp_css_attr_scale_property_list (css, "stroke-dasharray", ex); + sp_css_attr_scale_property_list(css, "stroke-dasharray", ex); sp_css_attr_scale_property_single(css, "stroke-dashoffset", ex); sp_css_attr_scale_property_single(css, "font-size", ex, true); sp_css_attr_scale_property_single(css, "kerning", ex); @@ -1625,20 +1664,18 @@ sp_css_attr_scale(SPCSSAttr *css, double ex) return css; } - /** * Quote and/or escape string for writing to CSS, changing strings in place. * See: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier */ -void -css_quote(Glib::ustring &val) +void css_quote(Glib::ustring &val) { Glib::ustring out; bool quote = false; // Can't wait for C++11! - for( Glib::ustring::iterator it = val.begin(); it != val.end(); ++it) { - if(g_ascii_isalnum(*it) || *it=='-' || *it=='_' || *it > 0xA0) { + for (Glib::ustring::iterator it = val.begin(); it != val.end(); ++it) { + if (g_ascii_isalnum(*it) || *it == '-' || *it == '_' || *it > 0xA0) { out += *it; } else if (*it == '\'') { // Single quotes require escaping and quotes. @@ -1651,53 +1688,47 @@ css_quote(Glib::ustring &val) out += *it; quote = true; } - if( it == val.begin() && !g_ascii_isalpha(*it) ) { + if (it == val.begin() && !g_ascii_isalpha(*it)) { // A non-ASCII/non-alpha initial value on any identifier needs quotes. // (Actually it's a bit more complicated but as it never hurts to quote...) quote = true; } } - if( quote ) { - out.insert( out.begin(), '\'' ); + if (quote) { + out.insert(out.begin(), '\''); out += '\''; } val = out; } - /** * Quote font names in font-family lists, changing string in place. * We use unquoted names internally but some need to be quoted in CSS. */ -void -css_font_family_quote(Glib::ustring &val) +void css_font_family_quote(Glib::ustring &val) { - std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s*,\\s*", val ); + std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s*,\\s*", val); val.erase(); - for(auto & token : tokens) { - css_quote( token ); + for (auto &token : tokens) { + css_quote(token); val += token + ", "; } - if( val.size() > 1 ) - val.erase( val.size() - 2 ); // Remove trailing ", " + if (val.size() > 1) + val.erase(val.size() - 2); // Remove trailing ", " } - // Called in style-internal.cpp, xml/repr-css.cpp /** * Remove paired single and double quotes from a string, changing string in place. */ -void -css_unquote(Glib::ustring &val) +void css_unquote(Glib::ustring &val) { - if( val.size() > 1 && - ( (val[0] == '"' && val[val.size()-1] == '"' ) || - (val[0] == '\'' && val[val.size()-1] == '\'' ) ) ) { - - val.erase( 0, 1 ); - val.erase( val.size()-1 ); - } + if (val.size() > 1 && + ((val[0] == '"' && val[val.size() - 1] == '"') || (val[0] == '\'' && val[val.size() - 1] == '\''))) { + val.erase(0, 1); + val.erase(val.size() - 1); + } } // Called in style-internal.cpp, text-toolbar.cpp @@ -1706,18 +1737,17 @@ css_unquote(Glib::ustring &val) * changing string in place. * We use unquoted family names internally but CSS sometimes uses quoted names. */ -void -css_font_family_unquote(Glib::ustring &val) +void css_font_family_unquote(Glib::ustring &val) { - std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s*,\\s*", val ); + std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s*,\\s*", val); val.erase(); - for(auto & token : tokens) { - css_unquote( token ); + for (auto &token : tokens) { + css_unquote(token); val += token + ", "; } - if( val.size() > 1 ) - val.erase( val.size() - 2 ); // Remove trailing ", " + if (val.size() > 1) + val.erase(val.size() - 2); // Remove trailing ", " } /* diff --git a/src/style.h b/src/style.h index 051ebb908a62b0c7f8d5458ecf365187d5bd19c6..4051632032099b8cb28b128332abb46cb90c29ee 100644 --- a/src/style.h +++ b/src/style.h @@ -18,14 +18,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "style-enums.h" -#include "style-internal.h" - -#include <sigc++/connection.h> #include <iostream> +#include <sigc++/connection.h> #include <vector> + #include "3rdparty/libcroco/cr-declaration.h" #include "3rdparty/libcroco/cr-prop-list.h" +#include "style-enums.h" +#include "style-internal.h" enum class SPAttr; @@ -36,15 +36,13 @@ namespace Inkscape { namespace XML { class Node; } -} - +} // namespace Inkscape /// An SVG style object. -class SPStyle { - +class SPStyle +{ public: - - SPStyle(SPDocument *document = nullptr, SPObject *object = nullptr);// document is ignored if valid object given + SPStyle(SPDocument *document = nullptr, SPObject *object = nullptr); // document is ignored if valid object given ~SPStyle(); const std::vector<SPIBase *> properties(); void clear(); @@ -53,32 +51,40 @@ public: void readFromObject(SPObject *object); void readFromPrefs(Glib::ustring const &path); bool isSet(SPAttr id); - void readIfUnset(SPAttr id, char const *val, SPStyleSrc const &source = SP_STYLE_SRC_STYLE_PROP ); - Glib::ustring write( unsigned int const flags = SP_STYLE_FLAG_IFSET, - SPStyleSrc const &style_src_req = SP_STYLE_SRC_STYLE_PROP, - SPStyle const *const base = nullptr ) const; - void cascade( SPStyle const *const parent ); - void merge( SPStyle const *const parent ); - void mergeString( char const *const p ); - void mergeStatement( CRStatement *statement ); - bool operator==(const SPStyle& rhs); - - int style_ref() { ++_refcount; return _refcount; } - int style_unref() { --_refcount; return _refcount; } + void readIfUnset(SPAttr id, char const *val, SPStyleSrc const &source = SP_STYLE_SRC_STYLE_PROP); + Glib::ustring write(unsigned int const flags = SP_STYLE_FLAG_IFSET, + SPStyleSrc const &style_src_req = SP_STYLE_SRC_STYLE_PROP, + SPStyle const *const base = nullptr) const; + void cascade(SPStyle const *const parent); + void merge(SPStyle const *const parent); + void mergeString(char const *const p); + void mergeStatement(CRStatement *statement); + bool operator==(const SPStyle &rhs); + + int style_ref() + { + ++_refcount; + return _refcount; + } + int style_unref() + { + --_refcount; + return _refcount; + } int refCount() { return _refcount; } private: - void _mergeString( char const *const p ); - void _mergeDeclList( CRDeclaration const *const decl_list, SPStyleSrc const &source ); - void _mergeDecl( CRDeclaration const *const decl, SPStyleSrc const &source ); - void _mergeProps( CRPropList *const props ); - void _mergeObjectStylesheet( SPObject const *const object ); + void _mergeString(char const *const p); + void _mergeDeclList(CRDeclaration const *const decl_list, SPStyleSrc const &source); + void _mergeDecl(CRDeclaration const *const decl, SPStyleSrc const &source); + void _mergeProps(CRPropList *const props); + void _mergeObjectStylesheet(SPObject const *const object); private: int _refcount; static int _count; // Poor man's leak detector -// FIXME: Make private + // FIXME: Make private public: /** Object we are attached to */ SPObject *object; @@ -94,7 +100,6 @@ private: using T = TypedSPI<Id, Base>; public: - /* ----------------------- THE PROPERTIES ------------------------- */ /* Match order in style.cpp. */ @@ -190,7 +195,8 @@ public: /** CSS 3 2.1, 2.2, 2.3 */ /** Not done yet, test_decoration3 = css3 2.4*/ T<SPAttr::TEXT_DECORATION_LINE, SPITextDecorationLine> text_decoration_line; - T<SPAttr::TEXT_DECORATION_STYLE, SPITextDecorationStyle> text_decoration_style; // SPIEnum? Only one can be set at time. + T<SPAttr::TEXT_DECORATION_STYLE, SPITextDecorationStyle> text_decoration_style; // SPIEnum? Only one can be set at + // time. T<SPAttr::TEXT_DECORATION_COLOR, SPIColor> text_decoration_color; T<SPAttr::TEXT_DECORATION_FILL, SPIPaint> text_decoration_fill; T<SPAttr::TEXT_DECORATION_STROKE, SPIPaint> text_decoration_stroke; @@ -266,7 +272,7 @@ public: T<SPAttr::MARKER_START, SPIString> marker_start; T<SPAttr::MARKER_MID, SPIString> marker_mid; T<SPAttr::MARKER_END, SPIString> marker_end; - SPIString* marker_ptrs[SP_MARKER_LOC_QTY]; + SPIString *marker_ptrs[SP_MARKER_LOC_QTY]; /* Filter effects ------------------------ */ @@ -319,17 +325,23 @@ public: */ sigc::signal<void, SPObject *, SPObject *> signal_stroke_ps_changed; - SPFilter *getFilter() { return (filter.href) ? filter.href->getObject() : nullptr; } - SPFilter const *getFilter() const { return (filter.href) ? filter.href->getObject() : nullptr; } + SPFilter *getFilter() { return (filter.href) ? filter.href->getObject() : nullptr; } + SPFilter const *getFilter() const { return (filter.href) ? filter.href->getObject() : nullptr; } Inkscape::URI const *getFilterURI() const { return (filter.href) ? filter.href->getURI() : nullptr; } - SPPaintServer *getFillPaintServer() { return (fill.value.href) ? fill.value.href->getObject() : nullptr; } - SPPaintServer const *getFillPaintServer() const { return (fill.value.href) ? fill.value.href->getObject() : nullptr; } - Inkscape::URI const *getFillURI() const { return (fill.value.href) ? fill.value.href->getURI() : nullptr; } + SPPaintServer *getFillPaintServer() { return (fill.value.href) ? fill.value.href->getObject() : nullptr; } + SPPaintServer const *getFillPaintServer() const + { + return (fill.value.href) ? fill.value.href->getObject() : nullptr; + } + Inkscape::URI const *getFillURI() const { return (fill.value.href) ? fill.value.href->getURI() : nullptr; } - SPPaintServer *getStrokePaintServer() { return (stroke.value.href) ? stroke.value.href->getObject() : nullptr; } - SPPaintServer const *getStrokePaintServer() const { return (stroke.value.href) ? stroke.value.href->getObject() : nullptr; } - Inkscape::URI const *getStrokeURI() const { return (stroke.value.href) ? stroke.value.href->getURI() : nullptr; } + SPPaintServer *getStrokePaintServer() { return (stroke.value.href) ? stroke.value.href->getObject() : nullptr; } + SPPaintServer const *getStrokePaintServer() const + { + return (stroke.value.href) ? stroke.value.href->getObject() : nullptr; + } + Inkscape::URI const *getStrokeURI() const { return (stroke.value.href) ? stroke.value.href->getURI() : nullptr; } /** * Return a font feature string useful for Pango. @@ -339,7 +351,7 @@ public: /** * Get either the fill or the stroke property */ - SPIPaint *getFillOrStroke(bool fill_) { return fill_ ? fill.upcast() : stroke.upcast(); } + SPIPaint *getFillOrStroke(bool fill_) { return fill_ ? fill.upcast() : stroke.upcast(); } SPIPaint const *getFillOrStroke(bool fill_) const { return fill_ ? fill.upcast() : stroke.upcast(); } }; @@ -349,14 +361,13 @@ SPStyle *sp_style_unref(SPStyle *style); // SPStyle::unref(); void sp_style_set_to_uri(SPStyle *style, bool isfill, Inkscape::URI const *uri); // ? -char const *sp_style_get_css_unit_string(int unit); // No change? +char const *sp_style_get_css_unit_string(int unit); // No change? #define SP_CSS_FONT_SIZE_DEFAULT 12.0 double sp_style_css_size_px_to_units(double size, int unit, double font_size = SP_CSS_FONT_SIZE_DEFAULT); // No change? double sp_style_css_size_units_to_px(double size, int unit, double font_size = SP_CSS_FONT_SIZE_DEFAULT); // No change? - -SPCSSAttr *sp_css_attr_from_style (SPStyle const *const style, unsigned int flags); +SPCSSAttr *sp_css_attr_from_style(SPStyle const *const style, unsigned int flags); SPCSSAttr *sp_css_attr_from_object(SPObject *object, unsigned int flags = SP_STYLE_FLAG_IFSET); SPCSSAttr *sp_css_attr_unset_text(SPCSSAttr *css); SPCSSAttr *sp_css_attr_unset_blacklist(SPCSSAttr *css); @@ -365,18 +376,17 @@ SPCSSAttr *sp_css_attr_scale(SPCSSAttr *css, double ex); void sp_style_unset_property_attrs(SPObject *o); -void sp_style_set_property_url (SPObject *item, char const *property, SPObject *linked, bool recursive); +void sp_style_set_property_url(SPObject *item, char const *property, SPObject *linked, bool recursive); -void css_quote( Glib::ustring &val ); // Add quotes around CSS values -void css_unquote( Glib::ustring &val ); // Remove quotes from CSS values (style-internal.cpp, xml/repr-css.cpp) -void css_font_family_quote( Glib::ustring &val ); // style-internal.cpp, text-toolbar.cpp -void css_font_family_unquote( Glib::ustring &val ); // style-internal.cpp, text-toolbar.cpp +void css_quote(Glib::ustring &val); // Add quotes around CSS values +void css_unquote(Glib::ustring &val); // Remove quotes from CSS values (style-internal.cpp, xml/repr-css.cpp) +void css_font_family_quote(Glib::ustring &val); // style-internal.cpp, text-toolbar.cpp +void css_font_family_unquote(Glib::ustring &val); // style-internal.cpp, text-toolbar.cpp Glib::ustring css2_escape_quote(char const *val); #endif // SEEN_SP_STYLE_H - /* Local Variables: mode:c++ @@ -387,4 +397,3 @@ Glib::ustring css2_escape_quote(char const *val); End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - diff --git a/src/svg/css-ostringstream.cpp b/src/svg/css-ostringstream.cpp index 96e9abb6717c70cc67e5005759ea39f923df56cd..436e9232cbda5e60f0e0a15edf816737013b2409 100644 --- a/src/svg/css-ostringstream.cpp +++ b/src/svg/css-ostringstream.cpp @@ -8,8 +8,9 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "svg/css-ostringstream.h" -#include "svg/strip-trailing-zeros.h" + #include "preferences.h" +#include "svg/strip-trailing-zeros.h" Inkscape::CSSOStringStream::CSSOStringStream() { @@ -34,26 +35,48 @@ Inkscape::CSSOStringStream &Inkscape::CSSOStringStream::operator<<(double d) return *this; } - char buf[32]; // haven't thought about how much is really required. + char buf[32]; // haven't thought about how much is really required. switch (precision()) { - case 9: g_ascii_formatd(buf, sizeof(buf), "%.9f", d); break; - case 8: g_ascii_formatd(buf, sizeof(buf), "%.8f", d); break; - case 7: g_ascii_formatd(buf, sizeof(buf), "%.7f", d); break; - case 6: g_ascii_formatd(buf, sizeof(buf), "%.6f", d); break; - case 5: g_ascii_formatd(buf, sizeof(buf), "%.5f", d); break; - case 4: g_ascii_formatd(buf, sizeof(buf), "%.4f", d); break; - case 3: g_ascii_formatd(buf, sizeof(buf), "%.3f", d); break; - case 2: g_ascii_formatd(buf, sizeof(buf), "%.2f", d); break; - case 1: g_ascii_formatd(buf, sizeof(buf), "%.1f", d); break; - case 0: g_ascii_formatd(buf, sizeof(buf), "%.0f", d); break; - case 10: default: g_ascii_formatd(buf, sizeof(buf), "%.10f", d); break; + case 9: + g_ascii_formatd(buf, sizeof(buf), "%.9f", d); + break; + case 8: + g_ascii_formatd(buf, sizeof(buf), "%.8f", d); + break; + case 7: + g_ascii_formatd(buf, sizeof(buf), "%.7f", d); + break; + case 6: + g_ascii_formatd(buf, sizeof(buf), "%.6f", d); + break; + case 5: + g_ascii_formatd(buf, sizeof(buf), "%.5f", d); + break; + case 4: + g_ascii_formatd(buf, sizeof(buf), "%.4f", d); + break; + case 3: + g_ascii_formatd(buf, sizeof(buf), "%.3f", d); + break; + case 2: + g_ascii_formatd(buf, sizeof(buf), "%.2f", d); + break; + case 1: + g_ascii_formatd(buf, sizeof(buf), "%.1f", d); + break; + case 0: + g_ascii_formatd(buf, sizeof(buf), "%.0f", d); + break; + case 10: + default: + g_ascii_formatd(buf, sizeof(buf), "%.10f", d); + break; } auto &os = *this; os << strip_trailing_zeros(buf); return os; } - /* Local Variables: mode:c++ diff --git a/src/svg/css-ostringstream.h b/src/svg/css-ostringstream.h index 5a34b7c103b4e5061a895e95c78c0bb254d5db94..0be23ff7c2971f716d1678955075895803b8f7b7 100644 --- a/src/svg/css-ostringstream.h +++ b/src/svg/css-ostringstream.h @@ -19,7 +19,8 @@ namespace Inkscape { * A thin wrapper around std::ostringstream, but writing floating point numbers in the format * required by CSS: `.' as decimal separator, no `e' notation, no nan or inf. */ -class CSSOStringStream { +class CSSOStringStream +{ private: std::ostringstream ostr; @@ -37,21 +38,14 @@ public: CSSOStringStream &operator<<(double); - std::string str() const { - return ostr.str(); - } + std::string str() const { return ostr.str(); } - std::streamsize precision() const { - return ostr.precision(); - } + std::streamsize precision() const { return ostr.precision(); } - std::streamsize precision(std::streamsize p) { - return ostr.precision(p); - } + std::streamsize precision(std::streamsize p) { return ostr.precision(p); } }; -} - +} // namespace Inkscape #endif /* !SVG_CSS_OSTRINGSTREAM_H_INKSCAPE */ diff --git a/src/svg/path-string.cpp b/src/svg/path-string.cpp index 95771ce08cf09429019b03dd0f57e5e4fc245e88..8c6d8433d818b1385960832692af57218d607f2f 100644 --- a/src/svg/path-string.cpp +++ b/src/svg/path-string.cpp @@ -12,12 +12,13 @@ */ #include "svg/path-string.h" + +#include "preferences.h" #include "svg/stringstream.h" #include "svg/svg.h" -#include "preferences.h" -// 1<=numericprecision<=16, doubles are only accurate upto (slightly less than) 16 digits (and less than one digit doesn't make sense) -// Please note that these constants are used to allocate sufficient space to hold serialized numbers +// 1<=numericprecision<=16, doubles are only accurate upto (slightly less than) 16 digits (and less than one digit +// doesn't make sense) Please note that these constants are used to allocate sufficient space to hold serialized numbers static int const minprec = 1; static int const maxprec = 16; @@ -25,35 +26,39 @@ int Inkscape::SVG::PathString::numericprecision; int Inkscape::SVG::PathString::minimumexponent; Inkscape::SVG::PATHSTRING_FORMAT Inkscape::SVG::PathString::format; -Inkscape::SVG::PathString::PathString() : - force_repeat_commands(!Inkscape::Preferences::get()->getBool("/options/svgoutput/disable_optimizations" ) && Inkscape::Preferences::get()->getBool("/options/svgoutput/forcerepeatcommands")) +Inkscape::SVG::PathString::PathString() + : force_repeat_commands(!Inkscape::Preferences::get()->getBool("/options/svgoutput/disable_optimizations") && + Inkscape::Preferences::get()->getBool("/options/svgoutput/forcerepeatcommands")) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - format = (PATHSTRING_FORMAT)prefs->getIntLimited("/options/svgoutput/pathstring_format", 1, 0, PATHSTRING_FORMAT_SIZE - 1 ); - numericprecision = std::max<int>(minprec,std::min<int>(maxprec, prefs->getInt("/options/svgoutput/numericprecision", 8))); + format = (PATHSTRING_FORMAT)prefs->getIntLimited("/options/svgoutput/pathstring_format", 1, 0, + PATHSTRING_FORMAT_SIZE - 1); + numericprecision = + std::max<int>(minprec, std::min<int>(maxprec, prefs->getInt("/options/svgoutput/numericprecision", 8))); minimumexponent = prefs->getInt("/options/svgoutput/minimumexponent", -8); } // For absolute and relative paths... the entire path is kept in the "tail". // For optimized path, at a switch between absolute and relative, add tail to commonbase. -void Inkscape::SVG::PathString::_appendOp(char abs_op, char rel_op) { +void Inkscape::SVG::PathString::_appendOp(char abs_op, char rel_op) +{ bool abs_op_repeated = _abs_state.prevop == abs_op && !force_repeat_commands; bool rel_op_repeated = _rel_state.prevop == rel_op && !force_repeat_commands; // For absolute and relative paths... do nothing. switch (format) { case PATHSTRING_ABSOLUTE: - if ( !abs_op_repeated ) _abs_state.appendOp(abs_op); + if (!abs_op_repeated) + _abs_state.appendOp(abs_op); break; case PATHSTRING_RELATIVE: - if ( !rel_op_repeated ) _rel_state.appendOp(rel_op); + if (!rel_op_repeated) + _rel_state.appendOp(rel_op); break; - case PATHSTRING_OPTIMIZE: - { + case PATHSTRING_OPTIMIZE: { unsigned int const abs_added_size = abs_op_repeated ? 0 : 2; unsigned int const rel_added_size = rel_op_repeated ? 0 : 2; - if ( _rel_state.str.size()+2 < _abs_state.str.size()+abs_added_size ) { - + if (_rel_state.str.size() + 2 < _abs_state.str.size() + abs_added_size) { // Store common prefix commonbase += _rel_state.str; _rel_state.str.clear(); @@ -65,8 +70,7 @@ void Inkscape::SVG::PathString::_appendOp(char abs_op, char rel_op) { // _rel_state.str.size()+2 < _abs_state.str.size()+abs_added_size // _rel_state.str.size()+rel_added_size < _abs_state.str.size()+2 // _abs_state.str.size()+2 > _rel_state.str.size()+rel_added_size - } else if ( _abs_state.str.size()+2 < _rel_state.str.size()+rel_added_size ) { - + } else if (_abs_state.str.size() + 2 < _rel_state.str.size() + rel_added_size) { // Store common prefix commonbase += _abs_state.str; _abs_state.str.clear(); @@ -75,33 +79,38 @@ void Inkscape::SVG::PathString::_appendOp(char abs_op, char rel_op) { _abs_state.switches++; rel_op_repeated = false; } - if ( !abs_op_repeated ) _abs_state.appendOp(abs_op); - if ( !rel_op_repeated ) _rel_state.appendOp(rel_op); - } - break; + if (!abs_op_repeated) + _abs_state.appendOp(abs_op); + if (!rel_op_repeated) + _rel_state.appendOp(rel_op); + } break; default: std::cout << "Better not be here!" << std::endl; } } -void Inkscape::SVG::PathString::State::append(Geom::Coord v) { +void Inkscape::SVG::PathString::State::append(Geom::Coord v) +{ str += ' '; appendNumber(v); } -void Inkscape::SVG::PathString::State::append(Geom::Point p) { +void Inkscape::SVG::PathString::State::append(Geom::Point p) +{ str += ' '; appendNumber(p[Geom::X]); str += ','; appendNumber(p[Geom::Y]); } -void Inkscape::SVG::PathString::State::append(Geom::Coord v, Geom::Coord& rv) { +void Inkscape::SVG::PathString::State::append(Geom::Coord v, Geom::Coord &rv) +{ str += ' '; appendNumber(v, rv); } -void Inkscape::SVG::PathString::State::append(Geom::Point p, Geom::Point &rp) { +void Inkscape::SVG::PathString::State::append(Geom::Point p, Geom::Point &rp) +{ str += ' '; appendNumber(p[Geom::X], rp[Geom::X]); str += ','; @@ -114,48 +123,61 @@ void Inkscape::SVG::PathString::State::append(Geom::Point p, Geom::Point &rp) { // than the absolute value). // NOTE: This assumes v and r are already rounded (this includes flushing to zero if they are < 10^minexp) -void Inkscape::SVG::PathString::State::appendRelativeCoord(Geom::Coord v, Geom::Coord r) { - int const minexp = minimumexponent-numericprecision+1; - int const digitsEnd = (int)floor(log10(std::min(fabs(v),fabs(r)))) - numericprecision; // Position just beyond the last significant digit of the smallest (in absolute sense) number - double const roundeddiff = floor((v-r)*pow(10.,-digitsEnd-1)+.5); - int const numDigits = (int)floor(log10(fabs(roundeddiff)))+1; // Number of digits in roundeddiff +void Inkscape::SVG::PathString::State::appendRelativeCoord(Geom::Coord v, Geom::Coord r) +{ + int const minexp = minimumexponent - numericprecision + 1; + int const digitsEnd = + (int)floor(log10(std::min(fabs(v), fabs(r)))) - + numericprecision; // Position just beyond the last significant digit of the smallest (in absolute sense) number + double const roundeddiff = floor((v - r) * pow(10., -digitsEnd - 1) + .5); + int const numDigits = (int)floor(log10(fabs(roundeddiff))) + 1; // Number of digits in roundeddiff if (r == 0) { appendNumber(v, numericprecision, minexp); } else if (v == 0) { appendNumber(-r, numericprecision, minexp); - } else if (numDigits>0) { - appendNumber(v-r, numDigits, minexp); + } else if (numDigits > 0) { + appendNumber(v - r, numDigits, minexp); } else { // This assumes the input numbers are already rounded to 'precision' digits str += '0'; } } -void Inkscape::SVG::PathString::State::appendRelative(Geom::Point p, Geom::Point r) { +void Inkscape::SVG::PathString::State::appendRelative(Geom::Point p, Geom::Point r) +{ str += ' '; appendRelativeCoord(p[Geom::X], r[Geom::X]); str += ','; appendRelativeCoord(p[Geom::Y], r[Geom::Y]); } -void Inkscape::SVG::PathString::State::appendRelative(Geom::Coord v, Geom::Coord r) { +void Inkscape::SVG::PathString::State::appendRelative(Geom::Coord v, Geom::Coord r) +{ str += ' '; appendRelativeCoord(v, r); } -void Inkscape::SVG::PathString::State::appendNumber(double v, int precision, int minexp) { - size_t const reserve = precision+1+1+1+1+3; // Just large enough to hold the maximum number of digits plus a sign, a period, the letter 'e', another sign and three digits for the exponent +void Inkscape::SVG::PathString::State::appendNumber(double v, int precision, int minexp) +{ + size_t const reserve = + precision + 1 + 1 + 1 + 1 + 3; // Just large enough to hold the maximum number of digits plus a sign, a period, + // the letter 'e', another sign and three digits for the exponent size_t const oldsize = str.size(); str.append(reserve, (char)0); - char* begin_of_num = const_cast<char*>(str.data()+oldsize); // Slightly evil, I know (but std::string should be storing its data in one big block of memory, so...) + char *begin_of_num = + const_cast<char *>(str.data() + oldsize); // Slightly evil, I know (but std::string should be storing its data + // in one big block of memory, so...) size_t added = sp_svg_number_write_de(begin_of_num, reserve, v, precision, minexp); - str.resize(oldsize+added); // remove any trailing characters + str.resize(oldsize + added); // remove any trailing characters } -void Inkscape::SVG::PathString::State::appendNumber(double v, double &rv, int precision, int minexp) { +void Inkscape::SVG::PathString::State::appendNumber(double v, double &rv, int precision, int minexp) +{ size_t const oldsize = str.size(); appendNumber(v, precision, minexp); - char* begin_of_num = const_cast<char*>(str.data()+oldsize); // Slightly evil, I know (but std::string should be storing its data in one big block of memory, so...) + char *begin_of_num = + const_cast<char *>(str.data() + oldsize); // Slightly evil, I know (but std::string should be storing its data + // in one big block of memory, so...) sp_svg_number_read_d(begin_of_num, &rv); } diff --git a/src/svg/path-string.h b/src/svg/path-string.h index 53080ba32be827034f71d67343417640a9c6bec3..acf5e34411f95e70424b413fc6704d51e0a8d9d7 100644 --- a/src/svg/path-string.h +++ b/src/svg/path-string.h @@ -25,98 +25,96 @@ namespace Inkscape { namespace SVG { // Relative vs. absolute coordinates -enum PATHSTRING_FORMAT { - PATHSTRING_ABSOLUTE, // Use only absolute coordinates - PATHSTRING_RELATIVE, // Use only relative coordinates - PATHSTRING_OPTIMIZE, // Optimize for path string length +enum PATHSTRING_FORMAT +{ + PATHSTRING_ABSOLUTE, // Use only absolute coordinates + PATHSTRING_RELATIVE, // Use only relative coordinates + PATHSTRING_OPTIMIZE, // Optimize for path string length PATHSTRING_FORMAT_SIZE }; /** * Builder for SVG path strings. */ -class PathString { +class PathString +{ public: PathString(); // default copy // default assign - std::string const &string() { + std::string const &string() + { std::string const &t = tail(); - final.reserve(commonbase.size()+t.size()); + final.reserve(commonbase.size() + t.size()); final = commonbase; final += tail(); // std::cout << " final: " << final << std::endl; return final; } - operator std::string const &() { - return string(); - } + operator std::string const &() { return string(); } - operator Glib::ustring const () const { - return commonbase + tail(); - } + operator Glib::ustring const() const { return commonbase + tail(); } - char const *c_str() { - return string().c_str(); - } + char const *c_str() { return string().c_str(); } - PathString &moveTo(Geom::Coord x, Geom::Coord y) { - return moveTo(Geom::Point(x, y)); - } + PathString &moveTo(Geom::Coord x, Geom::Coord y) { return moveTo(Geom::Point(x, y)); } - PathString &moveTo(Geom::Point p) { - _appendOp('M','m'); + PathString &moveTo(Geom::Point p) + { + _appendOp('M', 'm'); _appendPoint(p, true); _initial_point = _current_point; return *this; } - PathString &lineTo(Geom::Coord x, Geom::Coord y) { - return lineTo(Geom::Point(x, y)); - } + PathString &lineTo(Geom::Coord x, Geom::Coord y) { return lineTo(Geom::Point(x, y)); } - PathString &lineTo(Geom::Point p) { - _appendOp('L','l'); + PathString &lineTo(Geom::Point p) + { + _appendOp('L', 'l'); _appendPoint(p, true); return *this; } - PathString &horizontalLineTo(Geom::Coord x) { - _appendOp('H','h'); + PathString &horizontalLineTo(Geom::Coord x) + { + _appendOp('H', 'h'); _appendX(x, true); return *this; } - PathString &verticalLineTo(Geom::Coord y) { - _appendOp('V','v'); + PathString &verticalLineTo(Geom::Coord y) + { + _appendOp('V', 'v'); _appendY(y, true); return *this; } - PathString &quadTo(Geom::Coord cx, Geom::Coord cy, Geom::Coord x, Geom::Coord y) { + PathString &quadTo(Geom::Coord cx, Geom::Coord cy, Geom::Coord x, Geom::Coord y) + { return quadTo(Geom::Point(cx, cy), Geom::Point(x, y)); } - PathString &quadTo(Geom::Point c, Geom::Point p) { - _appendOp('Q','q'); + PathString &quadTo(Geom::Point c, Geom::Point p) + { + _appendOp('Q', 'q'); _appendPoint(c, false); _appendPoint(p, true); return *this; } - PathString &curveTo(Geom::Coord x0, Geom::Coord y0, - Geom::Coord x1, Geom::Coord y1, - Geom::Coord x, Geom::Coord y) + PathString &curveTo(Geom::Coord x0, Geom::Coord y0, Geom::Coord x1, Geom::Coord y1, Geom::Coord x, Geom::Coord y) { return curveTo(Geom::Point(x0, y0), Geom::Point(x1, y1), Geom::Point(x, y)); } - PathString &curveTo(Geom::Point c0, Geom::Point c1, Geom::Point p) { - _appendOp('C','c'); + PathString &curveTo(Geom::Point c0, Geom::Point c1, Geom::Point p) + { + _appendOp('C', 'c'); _appendPoint(c0, false); _appendPoint(c1, false); _appendPoint(p, true); @@ -126,12 +124,10 @@ public: /** * \param rot the angle in degrees */ - PathString &arcTo(Geom::Coord rx, Geom::Coord ry, Geom::Coord rot, - bool large_arc, bool sweep, - Geom::Point p) + PathString &arcTo(Geom::Coord rx, Geom::Coord ry, Geom::Coord rot, bool large_arc, bool sweep, Geom::Point p) { - _appendOp('A','a'); - _appendValue(Geom::Point(rx,ry)); + _appendOp('A', 'a'); + _appendValue(Geom::Point(rx, ry)); _appendValue(rot); _appendFlag(large_arc); _appendFlag(sweep); @@ -139,8 +135,8 @@ public: return *this; } - PathString &closePath() { - + PathString &closePath() + { _abs_state.appendOp('Z'); _rel_state.appendOp('z'); @@ -149,71 +145,92 @@ public: } private: - void _appendOp(char abs_op, char rel_op); - void _appendFlag(bool flag) { + void _appendFlag(bool flag) + { _abs_state.append(flag); _rel_state.append(flag); } - void _appendValue(Geom::Coord v) { + void _appendValue(Geom::Coord v) + { _abs_state.append(v); _rel_state.append(v); } - void _appendValue(Geom::Point p) { + void _appendValue(Geom::Point p) + { _abs_state.append(p); _rel_state.append(p); } - void _appendX(Geom::Coord x, bool sc) { + void _appendX(Geom::Coord x, bool sc) + { double rx; _abs_state.append(x, rx); _rel_state.appendRelative(rx, _current_point[Geom::X]); - if (sc) _current_point[Geom::X] = rx; + if (sc) + _current_point[Geom::X] = rx; } - void _appendY(Geom::Coord y, bool sc) { + void _appendY(Geom::Coord y, bool sc) + { double ry; _abs_state.append(y, ry); _rel_state.appendRelative(ry, _current_point[Geom::Y]); - if (sc) _current_point[Geom::Y] = ry; + if (sc) + _current_point[Geom::Y] = ry; } - void _appendPoint(Geom::Point p, bool sc) { + void _appendPoint(Geom::Point p, bool sc) + { Geom::Point rp; _abs_state.append(p, rp); _rel_state.appendRelative(rp, _current_point); - if (sc) _current_point = rp; + if (sc) + _current_point = rp; } - struct State { - State() { prevop = 0; switches = 0; } + struct State + { + State() + { + prevop = 0; + switches = 0; + } - void appendOp(char op) { - if (prevop != 0) str += ' '; + void appendOp(char op) + { + if (prevop != 0) + str += ' '; str += op; - prevop = ( op == 'M' ? 'L' : op == 'm' ? 'l' : op ); + prevop = (op == 'M' ? 'L' : op == 'm' ? 'l' : op); } - void append(bool flag) { + void append(bool flag) + { str += ' '; - str += ( flag ? '1' : '0' ); + str += (flag ? '1' : '0'); } void append(Geom::Coord v); void append(Geom::Point v); - void append(Geom::Coord v, Geom::Coord& rv); - void append(Geom::Point p, Geom::Point& rp); + void append(Geom::Coord v, Geom::Coord &rv); + void append(Geom::Point p, Geom::Point &rp); void appendRelative(Geom::Coord v, Geom::Coord r); void appendRelative(Geom::Point p, Geom::Point r); - bool operator<=(const State& s) const { - if ( str.size() < s.str.size() ) return true; - if ( str.size() > s.str.size() ) return false; - if ( switches < s.switches ) return true; - if ( switches > s.switches ) return false; + bool operator<=(const State &s) const + { + if (str.size() < s.str.size()) + return true; + if (str.size() > s.str.size()) + return false; + if (switches < s.switches) + return true; + if (switches > s.switches) + return false; return true; } @@ -224,8 +241,8 @@ private: char prevop; private: - void appendNumber(double v, int precision=numericprecision, int minexp=minimumexponent); - void appendNumber(double v, double &rv, int precision=numericprecision, int minexp=minimumexponent); + void appendNumber(double v, int precision = numericprecision, int minexp = minimumexponent); + void appendNumber(double v, double &rv, int precision = numericprecision, int minexp = minimumexponent); void appendRelativeCoord(Geom::Coord v, Geom::Coord r); } _abs_state, _rel_state; // State with the last operator being an absolute/relative operator @@ -237,10 +254,11 @@ private: // to cause a quadratic time complexity (in the number of characters/operators) std::string commonbase; std::string final; - std::string const &tail() const { - return ( (format == PATHSTRING_ABSOLUTE) || - (format == PATHSTRING_OPTIMIZE && _abs_state <= _rel_state ) ? - _abs_state.str : _rel_state.str ); + std::string const &tail() const + { + return ((format == PATHSTRING_ABSOLUTE) || (format == PATHSTRING_OPTIMIZE && _abs_state <= _rel_state) + ? _abs_state.str + : _rel_state.str); } static PATHSTRING_FORMAT format; @@ -249,9 +267,9 @@ private: static int minimumexponent; }; -} +} // namespace SVG -} +} // namespace Inkscape #endif /* diff --git a/src/svg/stringstream.cpp b/src/svg/stringstream.cpp index 59f84a234fd1c8c7dec179169dee5d1668cfb953..f3142b6bc9b9a396d7c0a483084c6ac6fefec229 100644 --- a/src/svg/stringstream.cpp +++ b/src/svg/stringstream.cpp @@ -8,10 +8,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "svg/stringstream.h" -#include "svg/strip-trailing-zeros.h" -#include "preferences.h" + #include <2geom/point.h> +#include "preferences.h" +#include "svg/strip-trailing-zeros.h" + Inkscape::SVGOStringStream::SVGOStringStream() { /* These two are probably unnecessary now that we provide our own operator<< for float and @@ -26,8 +28,7 @@ Inkscape::SVGOStringStream::SVGOStringStream() ostr.precision(prefs->getInt("/options/svgoutput/numericprecision", 8)); } -Inkscape::SVGOStringStream & -Inkscape::SVGOStringStream::operator<<(double d) +Inkscape::SVGOStringStream &Inkscape::SVGOStringStream::operator<<(double d) { auto &os = *this; @@ -49,15 +50,15 @@ Inkscape::SVGOStringStream::operator<<(double d) return os; } -Inkscape::SVGOStringStream & -Inkscape::SVGOStringStream::operator<<(Geom::Point const & p) +Inkscape::SVGOStringStream &Inkscape::SVGOStringStream::operator<<(Geom::Point const &p) { auto &os = *this; os << p[0] << ',' << p[1]; return os; } -Inkscape::SVGIStringStream::SVGIStringStream():std::istringstream() +Inkscape::SVGIStringStream::SVGIStringStream() + : std::istringstream() { this->imbue(std::locale::classic()); this->setf(std::ios::showpoint); @@ -69,7 +70,8 @@ Inkscape::SVGIStringStream::SVGIStringStream():std::istringstream() this->precision(prefs->getInt("/options/svgoutput/numericprecision", 8)); } -Inkscape::SVGIStringStream::SVGIStringStream(const std::string& str):std::istringstream(str) +Inkscape::SVGIStringStream::SVGIStringStream(const std::string &str) + : std::istringstream(str) { this->imbue(std::locale::classic()); this->setf(std::ios::showpoint); @@ -81,7 +83,6 @@ Inkscape::SVGIStringStream::SVGIStringStream(const std::string& str):std::istrin this->precision(prefs->getInt("/options/svgoutput/numericprecision", 8)); } - /* Local Variables: mode:c++ diff --git a/src/svg/stringstream.h b/src/svg/stringstream.h index f5a7e954335012af18414ee09acea150773eb2f8..0a4e230a43572e5a223ca3e39efb6f40c5282f7c 100644 --- a/src/svg/stringstream.h +++ b/src/svg/stringstream.h @@ -10,15 +10,15 @@ #ifndef INKSCAPE_STRINGSTREAM_H #define INKSCAPE_STRINGSTREAM_H +#include <2geom/forward.h> #include <sstream> #include <string> #include <type_traits> -#include <2geom/forward.h> - namespace Inkscape { -class SVGOStringStream { +class SVGOStringStream +{ private: std::ostringstream ostr; @@ -38,43 +38,29 @@ public: SVGOStringStream &operator<<(double); SVGOStringStream &operator<<(Geom::Point const &); - std::string str() const { - return ostr.str(); - } - - void str (std::string &s) { - ostr.str(s); - } + std::string str() const { return ostr.str(); } - std::streamsize precision() const { - return ostr.precision(); - } + void str(std::string &s) { ostr.str(s); } - std::streamsize precision(std::streamsize p) { - return ostr.precision(p); - } + std::streamsize precision() const { return ostr.precision(); } - std::ios::fmtflags setf(std::ios::fmtflags fmtfl) { - return ostr.setf(fmtfl); - } + std::streamsize precision(std::streamsize p) { return ostr.precision(p); } - std::ios::fmtflags setf(std::ios::fmtflags fmtfl, std::ios::fmtflags mask) { - return ostr.setf(fmtfl, mask); - } + std::ios::fmtflags setf(std::ios::fmtflags fmtfl) { return ostr.setf(fmtfl); } - void unsetf(std::ios::fmtflags mask) { - ostr.unsetf(mask); - } -}; + std::ios::fmtflags setf(std::ios::fmtflags fmtfl, std::ios::fmtflags mask) { return ostr.setf(fmtfl, mask); } -class SVGIStringStream:public std::istringstream { + void unsetf(std::ios::fmtflags mask) { ostr.unsetf(mask); } +}; +class SVGIStringStream : public std::istringstream +{ public: SVGIStringStream(); SVGIStringStream(const std::string &str); }; -} +} // namespace Inkscape #endif diff --git a/src/svg/strip-trailing-zeros.cpp b/src/svg/strip-trailing-zeros.cpp index 8abe4fa3df9227fbaefdda90bf0d0839a256e1e8..d6fe8dfca022df62cc7b653eaa83d7f0d6d01176 100644 --- a/src/svg/strip-trailing-zeros.cpp +++ b/src/svg/strip-trailing-zeros.cpp @@ -8,14 +8,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "svg/strip-trailing-zeros.h" + #include <cstring> -#include <string> #include <glib.h> +#include <string> -#include "svg/strip-trailing-zeros.h" - -std::string -strip_trailing_zeros(std::string str) +std::string strip_trailing_zeros(std::string str) { std::string::size_type p_ix = str.find('.'); if (p_ix != std::string::npos) { @@ -24,24 +23,17 @@ strip_trailing_zeros(std::string str) * Default to avoiding `e', e.g. using sprintf(str, "%17f", d). Add a new function that * allows use of `e' and use that function only where the spec allows it. */ - std::string::size_type nz_ix = str.find_last_not_of('0', (e_ix == std::string::npos - ? e_ix - : e_ix - 1)); + std::string::size_type nz_ix = str.find_last_not_of('0', (e_ix == std::string::npos ? e_ix : e_ix - 1)); if (nz_ix == std::string::npos || nz_ix < p_ix || nz_ix >= e_ix) { g_error("have `.' but couldn't find non-0"); } else { - str.erase(str.begin() + (nz_ix == p_ix - ? p_ix - : nz_ix + 1), - (e_ix == std::string::npos - ? str.end() - : str.begin() + e_ix)); + str.erase(str.begin() + (nz_ix == p_ix ? p_ix : nz_ix + 1), + (e_ix == std::string::npos ? str.end() : str.begin() + e_ix)); } } return str; } - /* Local Variables: mode:c++ diff --git a/src/svg/strip-trailing-zeros.h b/src/svg/strip-trailing-zeros.h index 1c5f537d4d148a6e77ac846758b520d8712a07a2..dae1c9ef15cab177c93fc8badb9f8f44c0401e30 100644 --- a/src/svg/strip-trailing-zeros.h +++ b/src/svg/strip-trailing-zeros.h @@ -14,7 +14,6 @@ std::string strip_trailing_zeros(std::string str); - #endif /* !SVG_STRIP_TRAILING_ZEROS_H_SEEN */ /* diff --git a/src/svg/svg-affine-parser.cpp b/src/svg/svg-affine-parser.cpp index 4f44898b94a1d283341ed04e300d59cd7b4e3e39..ede9d6827884cd9d29e8104d88a45fbfaa20e731 100644 --- a/src/svg/svg-affine-parser.cpp +++ b/src/svg/svg-affine-parser.cpp @@ -18,974 +18,342 @@ * sed -i 's/(true)/(true)/' svg-affine-parser.cpp */ -#include <string> -#include <glib.h> #include <2geom/transforms.h> -#include "svg.h" -#include "preferences.h" +#include <glib.h> +#include <string> +#include "preferences.h" +#include "svg.h" #line 29 "svg-affine-parser.cpp" static const char _svg_transform_actions[] = { - 0, 1, 0, 1, 8, 1, 11, 1, - 12, 1, 14, 1, 15, 1, 16, 2, - 0, 8, 2, 1, 7, 2, 2, 7, - 2, 3, 7, 2, 4, 7, 2, 5, - 7, 2, 6, 7, 2, 9, 10, 2, - 12, 0, 2, 12, 13, 3, 1, 7, - 14, 3, 2, 7, 14, 3, 3, 7, - 14, 3, 4, 7, 14, 3, 5, 7, - 14, 3, 6, 7, 14, 3, 12, 1, - 7, 3, 12, 2, 7, 3, 12, 3, - 7, 3, 12, 4, 7, 3, 12, 5, - 7, 3, 12, 6, 7 -}; + 0, 1, 0, 1, 8, 1, 11, 1, 12, 1, 14, 1, 15, 1, 16, 2, 0, 8, 2, 1, 7, 2, 2, 7, 2, 3, 7, 2, 4, 7, 2, + 5, 7, 2, 6, 7, 2, 9, 10, 2, 12, 0, 2, 12, 13, 3, 1, 7, 14, 3, 2, 7, 14, 3, 3, 7, 14, 3, 4, 7, 14, 3, + 5, 7, 14, 3, 6, 7, 14, 3, 12, 1, 7, 3, 12, 2, 7, 3, 12, 3, 7, 3, 12, 4, 7, 3, 12, 5, 7, 3, 12, 6, 7}; static const short _svg_transform_key_offsets[] = { - 0, 0, 1, 2, 3, 4, 5, 10, - 19, 22, 24, 36, 46, 49, 51, 63, - 73, 76, 78, 90, 100, 103, 105, 117, - 127, 130, 132, 144, 154, 157, 159, 168, - 173, 181, 182, 183, 184, 185, 186, 191, - 200, 203, 205, 217, 227, 230, 232, 244, - 254, 257, 259, 271, 281, 284, 286, 298, - 308, 311, 313, 325, 335, 338, 340, 349, - 354, 358, 360, 367, 377, 386, 390, 392, - 402, 414, 423, 427, 429, 439, 451, 460, - 464, 466, 476, 488, 497, 501, 503, 513, - 525, 534, 538, 540, 550, 562, 563, 564, - 565, 566, 567, 572, 581, 584, 586, 599, - 610, 613, 615, 627, 637, 640, 642, 651, - 656, 660, 662, 669, 679, 688, 692, 694, - 704, 716, 725, 729, 731, 742, 755, 757, - 758, 759, 760, 765, 774, 777, 779, 792, - 803, 806, 808, 817, 822, 826, 828, 835, - 845, 854, 858, 860, 871, 884, 885, 886, - 888, 893, 902, 905, 907, 916, 921, 925, - 927, 934, 944, 949, 958, 961, 963, 972, - 977, 981, 983, 990, 1000, 1001, 1002, 1003, - 1004, 1005, 1006, 1007, 1008, 1013, 1022, 1025, - 1027, 1040, 1051, 1054, 1056, 1065, 1070, 1074, - 1076, 1083, 1093, 1102, 1106, 1108, 1119, 1132, - 1136, 1138, 1145, 1155, 1164, 1168, 1170, 1180, - 1192, 1201, 1205, 1207, 1217, 1229, 1238, 1242, - 1244, 1254, 1266, 1275, 1279, 1281, 1291, 1303, - 1312, 1316, 1318, 1328, 1340, 1341, 1342, 1343, - 1344, 1345, 1350, 1359, 1362, 1364, 1377, 1388, - 1391, 1393, 1405, 1415, 1418, 1420, 1429, 1434, - 1438, 1440, 1447, 1457, 1466, 1470, 1472, 1482, - 1494, 1503, 1507, 1509, 1520, 1533, 1535, 1536, - 1537, 1538, 1543, 1552, 1555, 1557, 1570, 1581, - 1584, 1586, 1595, 1600, 1604, 1606, 1613, 1623, - 1632, 1636, 1638, 1649, 1662, 1663, 1664, 1666, - 1671, 1680, 1683, 1685, 1694, 1699, 1703, 1705, - 1712, 1722, 1727, 1736, 1739, 1741, 1750, 1755, - 1759, 1761, 1768, 1778, 1779, 1780, 1781, 1782, - 1783, 1784, 1785, 1786, 1791, 1800, 1803, 1805, - 1818, 1829, 1832, 1834, 1843, 1848, 1852, 1854, - 1861, 1871, 1880, 1884, 1886, 1897, 1910, 1918, - 1926, 1931, 1940, 1945, 1950, 1955, 1960 -}; + 0, 0, 1, 2, 3, 4, 5, 10, 19, 22, 24, 36, 46, 49, 51, 63, 73, 76, 78, + 90, 100, 103, 105, 117, 127, 130, 132, 144, 154, 157, 159, 168, 173, 181, 182, 183, 184, 185, + 186, 191, 200, 203, 205, 217, 227, 230, 232, 244, 254, 257, 259, 271, 281, 284, 286, 298, 308, + 311, 313, 325, 335, 338, 340, 349, 354, 358, 360, 367, 377, 386, 390, 392, 402, 414, 423, 427, + 429, 439, 451, 460, 464, 466, 476, 488, 497, 501, 503, 513, 525, 534, 538, 540, 550, 562, 563, + 564, 565, 566, 567, 572, 581, 584, 586, 599, 610, 613, 615, 627, 637, 640, 642, 651, 656, 660, + 662, 669, 679, 688, 692, 694, 704, 716, 725, 729, 731, 742, 755, 757, 758, 759, 760, 765, 774, + 777, 779, 792, 803, 806, 808, 817, 822, 826, 828, 835, 845, 854, 858, 860, 871, 884, 885, 886, + 888, 893, 902, 905, 907, 916, 921, 925, 927, 934, 944, 949, 958, 961, 963, 972, 977, 981, 983, + 990, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1013, 1022, 1025, 1027, 1040, 1051, 1054, 1056, 1065, + 1070, 1074, 1076, 1083, 1093, 1102, 1106, 1108, 1119, 1132, 1136, 1138, 1145, 1155, 1164, 1168, 1170, 1180, 1192, + 1201, 1205, 1207, 1217, 1229, 1238, 1242, 1244, 1254, 1266, 1275, 1279, 1281, 1291, 1303, 1312, 1316, 1318, 1328, + 1340, 1341, 1342, 1343, 1344, 1345, 1350, 1359, 1362, 1364, 1377, 1388, 1391, 1393, 1405, 1415, 1418, 1420, 1429, + 1434, 1438, 1440, 1447, 1457, 1466, 1470, 1472, 1482, 1494, 1503, 1507, 1509, 1520, 1533, 1535, 1536, 1537, 1538, + 1543, 1552, 1555, 1557, 1570, 1581, 1584, 1586, 1595, 1600, 1604, 1606, 1613, 1623, 1632, 1636, 1638, 1649, 1662, + 1663, 1664, 1666, 1671, 1680, 1683, 1685, 1694, 1699, 1703, 1705, 1712, 1722, 1727, 1736, 1739, 1741, 1750, 1755, + 1759, 1761, 1768, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1791, 1800, 1803, 1805, 1818, 1829, 1832, + 1834, 1843, 1848, 1852, 1854, 1861, 1871, 1880, 1884, 1886, 1897, 1910, 1918, 1926, 1931, 1940, 1945, 1950, 1955, + 1960}; static const char _svg_transform_trans_keys[] = { - 97, 116, 114, 105, 120, 13, 32, 40, - 9, 10, 13, 32, 43, 45, 46, 9, - 10, 48, 57, 46, 48, 57, 48, 57, - 13, 32, 44, 46, 69, 101, 9, 10, - 43, 45, 48, 57, 13, 32, 44, 46, - 9, 10, 43, 45, 48, 57, 46, 48, - 57, 48, 57, 13, 32, 44, 46, 69, - 101, 9, 10, 43, 45, 48, 57, 13, - 32, 44, 46, 9, 10, 43, 45, 48, - 57, 46, 48, 57, 48, 57, 13, 32, - 44, 46, 69, 101, 9, 10, 43, 45, - 48, 57, 13, 32, 44, 46, 9, 10, - 43, 45, 48, 57, 46, 48, 57, 48, - 57, 13, 32, 44, 46, 69, 101, 9, - 10, 43, 45, 48, 57, 13, 32, 44, - 46, 9, 10, 43, 45, 48, 57, 46, - 48, 57, 48, 57, 13, 32, 44, 46, - 69, 101, 9, 10, 43, 45, 48, 57, - 13, 32, 44, 46, 9, 10, 43, 45, - 48, 57, 46, 48, 57, 48, 57, 13, - 32, 41, 69, 101, 9, 10, 48, 57, - 13, 32, 41, 9, 10, 13, 32, 109, - 114, 115, 116, 9, 10, 97, 116, 114, - 105, 120, 13, 32, 40, 9, 10, 13, - 32, 43, 45, 46, 9, 10, 48, 57, - 46, 48, 57, 48, 57, 13, 32, 44, - 46, 69, 101, 9, 10, 43, 45, 48, - 57, 13, 32, 44, 46, 9, 10, 43, - 45, 48, 57, 46, 48, 57, 48, 57, - 13, 32, 44, 46, 69, 101, 9, 10, - 43, 45, 48, 57, 13, 32, 44, 46, - 9, 10, 43, 45, 48, 57, 46, 48, - 57, 48, 57, 13, 32, 44, 46, 69, - 101, 9, 10, 43, 45, 48, 57, 13, - 32, 44, 46, 9, 10, 43, 45, 48, - 57, 46, 48, 57, 48, 57, 13, 32, - 44, 46, 69, 101, 9, 10, 43, 45, - 48, 57, 13, 32, 44, 46, 9, 10, - 43, 45, 48, 57, 46, 48, 57, 48, - 57, 13, 32, 44, 46, 69, 101, 9, - 10, 43, 45, 48, 57, 13, 32, 44, - 46, 9, 10, 43, 45, 48, 57, 46, - 48, 57, 48, 57, 13, 32, 41, 69, - 101, 9, 10, 48, 57, 13, 32, 41, - 9, 10, 43, 45, 48, 57, 48, 57, - 13, 32, 41, 9, 10, 48, 57, 13, - 32, 41, 46, 69, 101, 9, 10, 48, - 57, 13, 32, 43, 45, 46, 9, 10, - 48, 57, 43, 45, 48, 57, 48, 57, - 13, 32, 44, 46, 9, 10, 43, 45, - 48, 57, 13, 32, 44, 46, 69, 101, - 9, 10, 43, 45, 48, 57, 13, 32, - 43, 45, 46, 9, 10, 48, 57, 43, - 45, 48, 57, 48, 57, 13, 32, 44, - 46, 9, 10, 43, 45, 48, 57, 13, - 32, 44, 46, 69, 101, 9, 10, 43, - 45, 48, 57, 13, 32, 43, 45, 46, - 9, 10, 48, 57, 43, 45, 48, 57, - 48, 57, 13, 32, 44, 46, 9, 10, - 43, 45, 48, 57, 13, 32, 44, 46, - 69, 101, 9, 10, 43, 45, 48, 57, - 13, 32, 43, 45, 46, 9, 10, 48, - 57, 43, 45, 48, 57, 48, 57, 13, - 32, 44, 46, 9, 10, 43, 45, 48, - 57, 13, 32, 44, 46, 69, 101, 9, - 10, 43, 45, 48, 57, 13, 32, 43, - 45, 46, 9, 10, 48, 57, 43, 45, - 48, 57, 48, 57, 13, 32, 44, 46, - 9, 10, 43, 45, 48, 57, 13, 32, - 44, 46, 69, 101, 9, 10, 43, 45, - 48, 57, 111, 116, 97, 116, 101, 13, - 32, 40, 9, 10, 13, 32, 43, 45, - 46, 9, 10, 48, 57, 46, 48, 57, - 48, 57, 13, 32, 41, 44, 46, 69, - 101, 9, 10, 43, 45, 48, 57, 13, - 32, 41, 44, 46, 9, 10, 43, 45, - 48, 57, 46, 48, 57, 48, 57, 13, - 32, 44, 46, 69, 101, 9, 10, 43, - 45, 48, 57, 13, 32, 44, 46, 9, - 10, 43, 45, 48, 57, 46, 48, 57, - 48, 57, 13, 32, 41, 69, 101, 9, - 10, 48, 57, 13, 32, 41, 9, 10, - 43, 45, 48, 57, 48, 57, 13, 32, - 41, 9, 10, 48, 57, 13, 32, 41, - 46, 69, 101, 9, 10, 48, 57, 13, - 32, 43, 45, 46, 9, 10, 48, 57, - 43, 45, 48, 57, 48, 57, 13, 32, - 44, 46, 9, 10, 43, 45, 48, 57, - 13, 32, 44, 46, 69, 101, 9, 10, - 43, 45, 48, 57, 13, 32, 43, 45, - 46, 9, 10, 48, 57, 43, 45, 48, - 57, 48, 57, 13, 32, 41, 44, 46, - 9, 10, 43, 45, 48, 57, 13, 32, - 41, 44, 46, 69, 101, 9, 10, 43, - 45, 48, 57, 99, 107, 97, 108, 101, - 13, 32, 40, 9, 10, 13, 32, 43, - 45, 46, 9, 10, 48, 57, 46, 48, - 57, 48, 57, 13, 32, 41, 44, 46, - 69, 101, 9, 10, 43, 45, 48, 57, - 13, 32, 41, 44, 46, 9, 10, 43, - 45, 48, 57, 46, 48, 57, 48, 57, - 13, 32, 41, 69, 101, 9, 10, 48, - 57, 13, 32, 41, 9, 10, 43, 45, - 48, 57, 48, 57, 13, 32, 41, 9, - 10, 48, 57, 13, 32, 41, 46, 69, - 101, 9, 10, 48, 57, 13, 32, 43, - 45, 46, 9, 10, 48, 57, 43, 45, - 48, 57, 48, 57, 13, 32, 41, 44, - 46, 9, 10, 43, 45, 48, 57, 13, - 32, 41, 44, 46, 69, 101, 9, 10, - 43, 45, 48, 57, 101, 119, 88, 89, - 13, 32, 40, 9, 10, 13, 32, 43, - 45, 46, 9, 10, 48, 57, 46, 48, - 57, 48, 57, 13, 32, 41, 69, 101, - 9, 10, 48, 57, 13, 32, 41, 9, - 10, 43, 45, 48, 57, 48, 57, 13, - 32, 41, 9, 10, 48, 57, 13, 32, - 41, 46, 69, 101, 9, 10, 48, 57, - 13, 32, 40, 9, 10, 13, 32, 43, - 45, 46, 9, 10, 48, 57, 46, 48, - 57, 48, 57, 13, 32, 41, 69, 101, - 9, 10, 48, 57, 13, 32, 41, 9, - 10, 43, 45, 48, 57, 48, 57, 13, - 32, 41, 9, 10, 48, 57, 13, 32, - 41, 46, 69, 101, 9, 10, 48, 57, - 114, 97, 110, 115, 108, 97, 116, 101, - 13, 32, 40, 9, 10, 13, 32, 43, - 45, 46, 9, 10, 48, 57, 46, 48, - 57, 48, 57, 13, 32, 41, 44, 46, - 69, 101, 9, 10, 43, 45, 48, 57, - 13, 32, 41, 44, 46, 9, 10, 43, - 45, 48, 57, 46, 48, 57, 48, 57, - 13, 32, 41, 69, 101, 9, 10, 48, - 57, 13, 32, 41, 9, 10, 43, 45, - 48, 57, 48, 57, 13, 32, 41, 9, - 10, 48, 57, 13, 32, 41, 46, 69, - 101, 9, 10, 48, 57, 13, 32, 43, - 45, 46, 9, 10, 48, 57, 43, 45, - 48, 57, 48, 57, 13, 32, 41, 44, - 46, 9, 10, 43, 45, 48, 57, 13, - 32, 41, 44, 46, 69, 101, 9, 10, - 43, 45, 48, 57, 43, 45, 48, 57, - 48, 57, 13, 32, 41, 9, 10, 48, - 57, 13, 32, 41, 46, 69, 101, 9, - 10, 48, 57, 13, 32, 43, 45, 46, - 9, 10, 48, 57, 43, 45, 48, 57, - 48, 57, 13, 32, 44, 46, 9, 10, - 43, 45, 48, 57, 13, 32, 44, 46, - 69, 101, 9, 10, 43, 45, 48, 57, - 13, 32, 43, 45, 46, 9, 10, 48, - 57, 43, 45, 48, 57, 48, 57, 13, - 32, 44, 46, 9, 10, 43, 45, 48, - 57, 13, 32, 44, 46, 69, 101, 9, - 10, 43, 45, 48, 57, 13, 32, 43, - 45, 46, 9, 10, 48, 57, 43, 45, - 48, 57, 48, 57, 13, 32, 44, 46, - 9, 10, 43, 45, 48, 57, 13, 32, - 44, 46, 69, 101, 9, 10, 43, 45, - 48, 57, 13, 32, 43, 45, 46, 9, - 10, 48, 57, 43, 45, 48, 57, 48, - 57, 13, 32, 44, 46, 9, 10, 43, - 45, 48, 57, 13, 32, 44, 46, 69, - 101, 9, 10, 43, 45, 48, 57, 13, - 32, 43, 45, 46, 9, 10, 48, 57, - 43, 45, 48, 57, 48, 57, 13, 32, - 44, 46, 9, 10, 43, 45, 48, 57, - 13, 32, 44, 46, 69, 101, 9, 10, - 43, 45, 48, 57, 111, 116, 97, 116, - 101, 13, 32, 40, 9, 10, 13, 32, - 43, 45, 46, 9, 10, 48, 57, 46, - 48, 57, 48, 57, 13, 32, 41, 44, - 46, 69, 101, 9, 10, 43, 45, 48, - 57, 13, 32, 41, 44, 46, 9, 10, - 43, 45, 48, 57, 46, 48, 57, 48, - 57, 13, 32, 44, 46, 69, 101, 9, - 10, 43, 45, 48, 57, 13, 32, 44, - 46, 9, 10, 43, 45, 48, 57, 46, - 48, 57, 48, 57, 13, 32, 41, 69, - 101, 9, 10, 48, 57, 13, 32, 41, - 9, 10, 43, 45, 48, 57, 48, 57, - 13, 32, 41, 9, 10, 48, 57, 13, - 32, 41, 46, 69, 101, 9, 10, 48, - 57, 13, 32, 43, 45, 46, 9, 10, - 48, 57, 43, 45, 48, 57, 48, 57, - 13, 32, 44, 46, 9, 10, 43, 45, - 48, 57, 13, 32, 44, 46, 69, 101, - 9, 10, 43, 45, 48, 57, 13, 32, - 43, 45, 46, 9, 10, 48, 57, 43, - 45, 48, 57, 48, 57, 13, 32, 41, - 44, 46, 9, 10, 43, 45, 48, 57, - 13, 32, 41, 44, 46, 69, 101, 9, - 10, 43, 45, 48, 57, 99, 107, 97, - 108, 101, 13, 32, 40, 9, 10, 13, - 32, 43, 45, 46, 9, 10, 48, 57, - 46, 48, 57, 48, 57, 13, 32, 41, - 44, 46, 69, 101, 9, 10, 43, 45, - 48, 57, 13, 32, 41, 44, 46, 9, - 10, 43, 45, 48, 57, 46, 48, 57, - 48, 57, 13, 32, 41, 69, 101, 9, - 10, 48, 57, 13, 32, 41, 9, 10, - 43, 45, 48, 57, 48, 57, 13, 32, - 41, 9, 10, 48, 57, 13, 32, 41, - 46, 69, 101, 9, 10, 48, 57, 13, - 32, 43, 45, 46, 9, 10, 48, 57, - 43, 45, 48, 57, 48, 57, 13, 32, - 41, 44, 46, 9, 10, 43, 45, 48, - 57, 13, 32, 41, 44, 46, 69, 101, - 9, 10, 43, 45, 48, 57, 101, 119, - 88, 89, 13, 32, 40, 9, 10, 13, - 32, 43, 45, 46, 9, 10, 48, 57, - 46, 48, 57, 48, 57, 13, 32, 41, - 69, 101, 9, 10, 48, 57, 13, 32, - 41, 9, 10, 43, 45, 48, 57, 48, - 57, 13, 32, 41, 9, 10, 48, 57, - 13, 32, 41, 46, 69, 101, 9, 10, - 48, 57, 13, 32, 40, 9, 10, 13, - 32, 43, 45, 46, 9, 10, 48, 57, - 46, 48, 57, 48, 57, 13, 32, 41, - 69, 101, 9, 10, 48, 57, 13, 32, - 41, 9, 10, 43, 45, 48, 57, 48, - 57, 13, 32, 41, 9, 10, 48, 57, - 13, 32, 41, 46, 69, 101, 9, 10, - 48, 57, 114, 97, 110, 115, 108, 97, - 116, 101, 13, 32, 40, 9, 10, 13, - 32, 43, 45, 46, 9, 10, 48, 57, - 46, 48, 57, 48, 57, 13, 32, 41, - 44, 46, 69, 101, 9, 10, 43, 45, - 48, 57, 13, 32, 41, 44, 46, 9, - 10, 43, 45, 48, 57, 46, 48, 57, - 48, 57, 13, 32, 41, 69, 101, 9, - 10, 48, 57, 13, 32, 41, 9, 10, - 43, 45, 48, 57, 48, 57, 13, 32, - 41, 9, 10, 48, 57, 13, 32, 41, - 46, 69, 101, 9, 10, 48, 57, 13, - 32, 43, 45, 46, 9, 10, 48, 57, - 43, 45, 48, 57, 48, 57, 13, 32, - 41, 44, 46, 9, 10, 43, 45, 48, - 57, 13, 32, 41, 44, 46, 69, 101, - 9, 10, 43, 45, 48, 57, 13, 32, - 109, 114, 115, 116, 9, 10, 13, 32, - 109, 114, 115, 116, 9, 10, 13, 32, - 44, 9, 10, 13, 32, 44, 109, 114, - 115, 116, 9, 10, 13, 32, 44, 9, - 10, 13, 32, 44, 9, 10, 13, 32, - 44, 9, 10, 13, 32, 44, 9, 10, - 13, 32, 44, 9, 10, 0 -}; + 97, 116, 114, 105, 120, 13, 32, 40, 9, 10, 13, 32, 43, 45, 46, 9, 10, 48, 57, 46, 48, 57, 48, + 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, + 46, 48, 57, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 9, 10, + 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, + 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, + 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, 44, 46, 69, 101, + 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, + 41, 69, 101, 9, 10, 48, 57, 13, 32, 41, 9, 10, 13, 32, 109, 114, 115, 116, 9, 10, 97, 116, 114, + 105, 120, 13, 32, 40, 9, 10, 13, 32, 43, 45, 46, 9, 10, 48, 57, 46, 48, 57, 48, 57, 13, 32, + 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, + 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, + 57, 46, 48, 57, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 9, + 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, + 32, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, + 45, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, 69, 101, + 9, 10, 48, 57, 13, 32, 41, 9, 10, 43, 45, 48, 57, 48, 57, 13, 32, 41, 9, 10, 48, 57, 13, + 32, 41, 46, 69, 101, 9, 10, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, 48, 57, 48, + 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, + 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, 48, 57, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, + 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, + 43, 45, 48, 57, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 69, 101, 9, + 10, 43, 45, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, 48, 57, 48, 57, 13, 32, 44, + 46, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 43, 45, + 46, 9, 10, 48, 57, 43, 45, 48, 57, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, + 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 111, 116, 97, 116, 101, 13, 32, 40, 9, 10, 13, 32, 43, + 45, 46, 9, 10, 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, 44, 46, 69, 101, 9, 10, 43, 45, 48, + 57, 13, 32, 41, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, 44, 46, 69, 101, + 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, + 41, 69, 101, 9, 10, 48, 57, 13, 32, 41, 9, 10, 43, 45, 48, 57, 48, 57, 13, 32, 41, 9, 10, + 48, 57, 13, 32, 41, 46, 69, 101, 9, 10, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, + 48, 57, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, + 45, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, 48, 57, 48, 57, 13, 32, 41, 44, 46, + 9, 10, 43, 45, 48, 57, 13, 32, 41, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 99, 107, 97, 108, + 101, 13, 32, 40, 9, 10, 13, 32, 43, 45, 46, 9, 10, 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, + 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 41, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, + 57, 48, 57, 13, 32, 41, 69, 101, 9, 10, 48, 57, 13, 32, 41, 9, 10, 43, 45, 48, 57, 48, 57, + 13, 32, 41, 9, 10, 48, 57, 13, 32, 41, 46, 69, 101, 9, 10, 48, 57, 13, 32, 43, 45, 46, 9, + 10, 48, 57, 43, 45, 48, 57, 48, 57, 13, 32, 41, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, 41, + 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 101, 119, 88, 89, 13, 32, 40, 9, 10, 13, 32, 43, 45, + 46, 9, 10, 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, 69, 101, 9, 10, 48, 57, 13, 32, 41, 9, + 10, 43, 45, 48, 57, 48, 57, 13, 32, 41, 9, 10, 48, 57, 13, 32, 41, 46, 69, 101, 9, 10, 48, + 57, 13, 32, 40, 9, 10, 13, 32, 43, 45, 46, 9, 10, 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, + 69, 101, 9, 10, 48, 57, 13, 32, 41, 9, 10, 43, 45, 48, 57, 48, 57, 13, 32, 41, 9, 10, 48, + 57, 13, 32, 41, 46, 69, 101, 9, 10, 48, 57, 114, 97, 110, 115, 108, 97, 116, 101, 13, 32, 40, 9, + 10, 13, 32, 43, 45, 46, 9, 10, 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, 44, 46, 69, 101, 9, + 10, 43, 45, 48, 57, 13, 32, 41, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, + 41, 69, 101, 9, 10, 48, 57, 13, 32, 41, 9, 10, 43, 45, 48, 57, 48, 57, 13, 32, 41, 9, 10, + 48, 57, 13, 32, 41, 46, 69, 101, 9, 10, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, + 48, 57, 48, 57, 13, 32, 41, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, 41, 44, 46, 69, 101, 9, + 10, 43, 45, 48, 57, 43, 45, 48, 57, 48, 57, 13, 32, 41, 9, 10, 48, 57, 13, 32, 41, 46, 69, + 101, 9, 10, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, 48, 57, 48, 57, 13, 32, 44, + 46, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 43, 45, + 46, 9, 10, 48, 57, 43, 45, 48, 57, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, + 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, 48, 57, + 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, + 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, 48, 57, 48, 57, 13, 32, 44, 46, 9, 10, 43, + 45, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, + 57, 43, 45, 48, 57, 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 69, 101, + 9, 10, 43, 45, 48, 57, 111, 116, 97, 116, 101, 13, 32, 40, 9, 10, 13, 32, 43, 45, 46, 9, 10, + 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, 32, 41, + 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, + 48, 57, 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, 69, 101, 9, + 10, 48, 57, 13, 32, 41, 9, 10, 43, 45, 48, 57, 48, 57, 13, 32, 41, 9, 10, 48, 57, 13, 32, + 41, 46, 69, 101, 9, 10, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, 48, 57, 48, 57, + 13, 32, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 13, + 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, 48, 57, 48, 57, 13, 32, 41, 44, 46, 9, 10, 43, 45, + 48, 57, 13, 32, 41, 44, 46, 69, 101, 9, 10, 43, 45, 48, 57, 99, 107, 97, 108, 101, 13, 32, 40, + 9, 10, 13, 32, 43, 45, 46, 9, 10, 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, 44, 46, 69, 101, + 9, 10, 43, 45, 48, 57, 13, 32, 41, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, + 32, 41, 69, 101, 9, 10, 48, 57, 13, 32, 41, 9, 10, 43, 45, 48, 57, 48, 57, 13, 32, 41, 9, + 10, 48, 57, 13, 32, 41, 46, 69, 101, 9, 10, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, + 45, 48, 57, 48, 57, 13, 32, 41, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, 41, 44, 46, 69, 101, + 9, 10, 43, 45, 48, 57, 101, 119, 88, 89, 13, 32, 40, 9, 10, 13, 32, 43, 45, 46, 9, 10, 48, + 57, 46, 48, 57, 48, 57, 13, 32, 41, 69, 101, 9, 10, 48, 57, 13, 32, 41, 9, 10, 43, 45, 48, + 57, 48, 57, 13, 32, 41, 9, 10, 48, 57, 13, 32, 41, 46, 69, 101, 9, 10, 48, 57, 13, 32, 40, + 9, 10, 13, 32, 43, 45, 46, 9, 10, 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, 69, 101, 9, 10, + 48, 57, 13, 32, 41, 9, 10, 43, 45, 48, 57, 48, 57, 13, 32, 41, 9, 10, 48, 57, 13, 32, 41, + 46, 69, 101, 9, 10, 48, 57, 114, 97, 110, 115, 108, 97, 116, 101, 13, 32, 40, 9, 10, 13, 32, 43, + 45, 46, 9, 10, 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, 44, 46, 69, 101, 9, 10, 43, 45, 48, + 57, 13, 32, 41, 44, 46, 9, 10, 43, 45, 48, 57, 46, 48, 57, 48, 57, 13, 32, 41, 69, 101, 9, + 10, 48, 57, 13, 32, 41, 9, 10, 43, 45, 48, 57, 48, 57, 13, 32, 41, 9, 10, 48, 57, 13, 32, + 41, 46, 69, 101, 9, 10, 48, 57, 13, 32, 43, 45, 46, 9, 10, 48, 57, 43, 45, 48, 57, 48, 57, + 13, 32, 41, 44, 46, 9, 10, 43, 45, 48, 57, 13, 32, 41, 44, 46, 69, 101, 9, 10, 43, 45, 48, + 57, 13, 32, 109, 114, 115, 116, 9, 10, 13, 32, 109, 114, 115, 116, 9, 10, 13, 32, 44, 9, 10, 13, + 32, 44, 109, 114, 115, 116, 9, 10, 13, 32, 44, 9, 10, 13, 32, 44, 9, 10, 13, 32, 44, 9, 10, + 13, 32, 44, 9, 10, 13, 32, 44, 9, 10, 0}; static const char _svg_transform_single_lengths[] = { - 0, 1, 1, 1, 1, 1, 3, 5, - 1, 0, 6, 4, 1, 0, 6, 4, - 1, 0, 6, 4, 1, 0, 6, 4, - 1, 0, 6, 4, 1, 0, 5, 3, - 6, 1, 1, 1, 1, 1, 3, 5, - 1, 0, 6, 4, 1, 0, 6, 4, - 1, 0, 6, 4, 1, 0, 6, 4, - 1, 0, 6, 4, 1, 0, 5, 3, - 2, 0, 3, 6, 5, 2, 0, 4, - 6, 5, 2, 0, 4, 6, 5, 2, - 0, 4, 6, 5, 2, 0, 4, 6, - 5, 2, 0, 4, 6, 1, 1, 1, - 1, 1, 3, 5, 1, 0, 7, 5, - 1, 0, 6, 4, 1, 0, 5, 3, - 2, 0, 3, 6, 5, 2, 0, 4, - 6, 5, 2, 0, 5, 7, 2, 1, - 1, 1, 3, 5, 1, 0, 7, 5, - 1, 0, 5, 3, 2, 0, 3, 6, - 5, 2, 0, 5, 7, 1, 1, 2, - 3, 5, 1, 0, 5, 3, 2, 0, - 3, 6, 3, 5, 1, 0, 5, 3, - 2, 0, 3, 6, 1, 1, 1, 1, - 1, 1, 1, 1, 3, 5, 1, 0, - 7, 5, 1, 0, 5, 3, 2, 0, - 3, 6, 5, 2, 0, 5, 7, 2, - 0, 3, 6, 5, 2, 0, 4, 6, - 5, 2, 0, 4, 6, 5, 2, 0, - 4, 6, 5, 2, 0, 4, 6, 5, - 2, 0, 4, 6, 1, 1, 1, 1, - 1, 3, 5, 1, 0, 7, 5, 1, - 0, 6, 4, 1, 0, 5, 3, 2, - 0, 3, 6, 5, 2, 0, 4, 6, - 5, 2, 0, 5, 7, 2, 1, 1, - 1, 3, 5, 1, 0, 7, 5, 1, - 0, 5, 3, 2, 0, 3, 6, 5, - 2, 0, 5, 7, 1, 1, 2, 3, - 5, 1, 0, 5, 3, 2, 0, 3, - 6, 3, 5, 1, 0, 5, 3, 2, - 0, 3, 6, 1, 1, 1, 1, 1, - 1, 1, 1, 3, 5, 1, 0, 7, - 5, 1, 0, 5, 3, 2, 0, 3, - 6, 5, 2, 0, 5, 7, 6, 6, - 3, 7, 3, 3, 3, 3, 3 -}; + 0, 1, 1, 1, 1, 1, 3, 5, 1, 0, 6, 4, 1, 0, 6, 4, 1, 0, 6, 4, 1, 0, 6, 4, 1, 0, 6, 4, 1, 0, 5, 3, 6, 1, 1, 1, 1, 1, 3, + 5, 1, 0, 6, 4, 1, 0, 6, 4, 1, 0, 6, 4, 1, 0, 6, 4, 1, 0, 6, 4, 1, 0, 5, 3, 2, 0, 3, 6, 5, 2, 0, 4, 6, 5, 2, 0, 4, 6, + 5, 2, 0, 4, 6, 5, 2, 0, 4, 6, 5, 2, 0, 4, 6, 1, 1, 1, 1, 1, 3, 5, 1, 0, 7, 5, 1, 0, 6, 4, 1, 0, 5, 3, 2, 0, 3, 6, 5, + 2, 0, 4, 6, 5, 2, 0, 5, 7, 2, 1, 1, 1, 3, 5, 1, 0, 7, 5, 1, 0, 5, 3, 2, 0, 3, 6, 5, 2, 0, 5, 7, 1, 1, 2, 3, 5, 1, 0, + 5, 3, 2, 0, 3, 6, 3, 5, 1, 0, 5, 3, 2, 0, 3, 6, 1, 1, 1, 1, 1, 1, 1, 1, 3, 5, 1, 0, 7, 5, 1, 0, 5, 3, 2, 0, 3, 6, 5, + 2, 0, 5, 7, 2, 0, 3, 6, 5, 2, 0, 4, 6, 5, 2, 0, 4, 6, 5, 2, 0, 4, 6, 5, 2, 0, 4, 6, 5, 2, 0, 4, 6, 1, 1, 1, 1, 1, 3, + 5, 1, 0, 7, 5, 1, 0, 6, 4, 1, 0, 5, 3, 2, 0, 3, 6, 5, 2, 0, 4, 6, 5, 2, 0, 5, 7, 2, 1, 1, 1, 3, 5, 1, 0, 7, 5, 1, 0, + 5, 3, 2, 0, 3, 6, 5, 2, 0, 5, 7, 1, 1, 2, 3, 5, 1, 0, 5, 3, 2, 0, 3, 6, 3, 5, 1, 0, 5, 3, 2, 0, 3, 6, 1, 1, 1, 1, 1, + 1, 1, 1, 3, 5, 1, 0, 7, 5, 1, 0, 5, 3, 2, 0, 3, 6, 5, 2, 0, 5, 7, 6, 6, 3, 7, 3, 3, 3, 3, 3}; static const char _svg_transform_range_lengths[] = { - 0, 0, 0, 0, 0, 0, 1, 2, - 1, 1, 3, 3, 1, 1, 3, 3, - 1, 1, 3, 3, 1, 1, 3, 3, - 1, 1, 3, 3, 1, 1, 2, 1, - 1, 0, 0, 0, 0, 0, 1, 2, - 1, 1, 3, 3, 1, 1, 3, 3, - 1, 1, 3, 3, 1, 1, 3, 3, - 1, 1, 3, 3, 1, 1, 2, 1, - 1, 1, 2, 2, 2, 1, 1, 3, - 3, 2, 1, 1, 3, 3, 2, 1, - 1, 3, 3, 2, 1, 1, 3, 3, - 2, 1, 1, 3, 3, 0, 0, 0, - 0, 0, 1, 2, 1, 1, 3, 3, - 1, 1, 3, 3, 1, 1, 2, 1, - 1, 1, 2, 2, 2, 1, 1, 3, - 3, 2, 1, 1, 3, 3, 0, 0, - 0, 0, 1, 2, 1, 1, 3, 3, - 1, 1, 2, 1, 1, 1, 2, 2, - 2, 1, 1, 3, 3, 0, 0, 0, - 1, 2, 1, 1, 2, 1, 1, 1, - 2, 2, 1, 2, 1, 1, 2, 1, - 1, 1, 2, 2, 0, 0, 0, 0, - 0, 0, 0, 0, 1, 2, 1, 1, - 3, 3, 1, 1, 2, 1, 1, 1, - 2, 2, 2, 1, 1, 3, 3, 1, - 1, 2, 2, 2, 1, 1, 3, 3, - 2, 1, 1, 3, 3, 2, 1, 1, - 3, 3, 2, 1, 1, 3, 3, 2, - 1, 1, 3, 3, 0, 0, 0, 0, - 0, 1, 2, 1, 1, 3, 3, 1, - 1, 3, 3, 1, 1, 2, 1, 1, - 1, 2, 2, 2, 1, 1, 3, 3, - 2, 1, 1, 3, 3, 0, 0, 0, - 0, 1, 2, 1, 1, 3, 3, 1, - 1, 2, 1, 1, 1, 2, 2, 2, - 1, 1, 3, 3, 0, 0, 0, 1, - 2, 1, 1, 2, 1, 1, 1, 2, - 2, 1, 2, 1, 1, 2, 1, 1, - 1, 2, 2, 0, 0, 0, 0, 0, - 0, 0, 0, 1, 2, 1, 1, 3, - 3, 1, 1, 2, 1, 1, 1, 2, - 2, 2, 1, 1, 3, 3, 1, 1, - 1, 1, 1, 1, 1, 1, 1 -}; + 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 2, 1, 1, 0, 0, 0, 0, 0, 1, + 2, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1, 3, 3, 2, 1, 1, 3, 3, + 2, 1, 1, 3, 3, 2, 1, 1, 3, 3, 2, 1, 1, 3, 3, 0, 0, 0, 0, 0, 1, 2, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 2, 1, 1, 1, 2, 2, 2, + 1, 1, 3, 3, 2, 1, 1, 3, 3, 0, 0, 0, 0, 1, 2, 1, 1, 3, 3, 1, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1, 3, 3, 0, 0, 0, 1, 2, 1, 1, + 2, 1, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 3, 3, 1, 1, 2, 1, 1, 1, 2, 2, 2, + 1, 1, 3, 3, 1, 1, 2, 2, 2, 1, 1, 3, 3, 2, 1, 1, 3, 3, 2, 1, 1, 3, 3, 2, 1, 1, 3, 3, 2, 1, 1, 3, 3, 0, 0, 0, 0, 0, 1, + 2, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1, 3, 3, 2, 1, 1, 3, 3, 0, 0, 0, 0, 1, 2, 1, 1, 3, 3, 1, 1, + 2, 1, 1, 1, 2, 2, 2, 1, 1, 3, 3, 0, 0, 0, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 0, 0, 0, 0, 0, + 0, 0, 0, 1, 2, 1, 1, 3, 3, 1, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1}; static const short _svg_transform_index_offsets[] = { - 0, 0, 2, 4, 6, 8, 10, 15, - 23, 26, 28, 38, 46, 49, 51, 61, - 69, 72, 74, 84, 92, 95, 97, 107, - 115, 118, 120, 130, 138, 141, 143, 151, - 156, 164, 166, 168, 170, 172, 174, 179, - 187, 190, 192, 202, 210, 213, 215, 225, - 233, 236, 238, 248, 256, 259, 261, 271, - 279, 282, 284, 294, 302, 305, 307, 315, - 320, 324, 326, 332, 341, 349, 353, 355, - 363, 373, 381, 385, 387, 395, 405, 413, - 417, 419, 427, 437, 445, 449, 451, 459, - 469, 477, 481, 483, 491, 501, 503, 505, - 507, 509, 511, 516, 524, 527, 529, 540, - 549, 552, 554, 564, 572, 575, 577, 585, - 590, 594, 596, 602, 611, 619, 623, 625, - 633, 643, 651, 655, 657, 666, 677, 680, - 682, 684, 686, 691, 699, 702, 704, 715, - 724, 727, 729, 737, 742, 746, 748, 754, - 763, 771, 775, 777, 786, 797, 799, 801, - 804, 809, 817, 820, 822, 830, 835, 839, - 841, 847, 856, 861, 869, 872, 874, 882, - 887, 891, 893, 899, 908, 910, 912, 914, - 916, 918, 920, 922, 924, 929, 937, 940, - 942, 953, 962, 965, 967, 975, 980, 984, - 986, 992, 1001, 1009, 1013, 1015, 1024, 1035, - 1039, 1041, 1047, 1056, 1064, 1068, 1070, 1078, - 1088, 1096, 1100, 1102, 1110, 1120, 1128, 1132, - 1134, 1142, 1152, 1160, 1164, 1166, 1174, 1184, - 1192, 1196, 1198, 1206, 1216, 1218, 1220, 1222, - 1224, 1226, 1231, 1239, 1242, 1244, 1255, 1264, - 1267, 1269, 1279, 1287, 1290, 1292, 1300, 1305, - 1309, 1311, 1317, 1326, 1334, 1338, 1340, 1348, - 1358, 1366, 1370, 1372, 1381, 1392, 1395, 1397, - 1399, 1401, 1406, 1414, 1417, 1419, 1430, 1439, - 1442, 1444, 1452, 1457, 1461, 1463, 1469, 1478, - 1486, 1490, 1492, 1501, 1512, 1514, 1516, 1519, - 1524, 1532, 1535, 1537, 1545, 1550, 1554, 1556, - 1562, 1571, 1576, 1584, 1587, 1589, 1597, 1602, - 1606, 1608, 1614, 1623, 1625, 1627, 1629, 1631, - 1633, 1635, 1637, 1639, 1644, 1652, 1655, 1657, - 1668, 1677, 1680, 1682, 1690, 1695, 1699, 1701, - 1707, 1716, 1724, 1728, 1730, 1739, 1750, 1758, - 1766, 1771, 1780, 1785, 1790, 1795, 1800 -}; + 0, 0, 2, 4, 6, 8, 10, 15, 23, 26, 28, 38, 46, 49, 51, 61, 69, 72, 74, + 84, 92, 95, 97, 107, 115, 118, 120, 130, 138, 141, 143, 151, 156, 164, 166, 168, 170, 172, + 174, 179, 187, 190, 192, 202, 210, 213, 215, 225, 233, 236, 238, 248, 256, 259, 261, 271, 279, + 282, 284, 294, 302, 305, 307, 315, 320, 324, 326, 332, 341, 349, 353, 355, 363, 373, 381, 385, + 387, 395, 405, 413, 417, 419, 427, 437, 445, 449, 451, 459, 469, 477, 481, 483, 491, 501, 503, + 505, 507, 509, 511, 516, 524, 527, 529, 540, 549, 552, 554, 564, 572, 575, 577, 585, 590, 594, + 596, 602, 611, 619, 623, 625, 633, 643, 651, 655, 657, 666, 677, 680, 682, 684, 686, 691, 699, + 702, 704, 715, 724, 727, 729, 737, 742, 746, 748, 754, 763, 771, 775, 777, 786, 797, 799, 801, + 804, 809, 817, 820, 822, 830, 835, 839, 841, 847, 856, 861, 869, 872, 874, 882, 887, 891, 893, + 899, 908, 910, 912, 914, 916, 918, 920, 922, 924, 929, 937, 940, 942, 953, 962, 965, 967, 975, + 980, 984, 986, 992, 1001, 1009, 1013, 1015, 1024, 1035, 1039, 1041, 1047, 1056, 1064, 1068, 1070, 1078, 1088, + 1096, 1100, 1102, 1110, 1120, 1128, 1132, 1134, 1142, 1152, 1160, 1164, 1166, 1174, 1184, 1192, 1196, 1198, 1206, + 1216, 1218, 1220, 1222, 1224, 1226, 1231, 1239, 1242, 1244, 1255, 1264, 1267, 1269, 1279, 1287, 1290, 1292, 1300, + 1305, 1309, 1311, 1317, 1326, 1334, 1338, 1340, 1348, 1358, 1366, 1370, 1372, 1381, 1392, 1395, 1397, 1399, 1401, + 1406, 1414, 1417, 1419, 1430, 1439, 1442, 1444, 1452, 1457, 1461, 1463, 1469, 1478, 1486, 1490, 1492, 1501, 1512, + 1514, 1516, 1519, 1524, 1532, 1535, 1537, 1545, 1550, 1554, 1556, 1562, 1571, 1576, 1584, 1587, 1589, 1597, 1602, + 1606, 1608, 1614, 1623, 1625, 1627, 1629, 1631, 1633, 1635, 1637, 1639, 1644, 1652, 1655, 1657, 1668, 1677, 1680, + 1682, 1690, 1695, 1699, 1701, 1707, 1716, 1724, 1728, 1730, 1739, 1750, 1758, 1766, 1771, 1780, 1785, 1790, 1795, + 1800}; static const short _svg_transform_indicies[] = { - 1, 0, 2, 0, 3, 0, 4, 0, - 5, 0, 5, 5, 6, 5, 0, 6, - 6, 7, 7, 8, 6, 9, 0, 10, - 11, 0, 12, 0, 13, 13, 15, 16, - 17, 17, 13, 14, 12, 0, 18, 18, - 20, 21, 18, 19, 22, 0, 23, 24, - 0, 25, 0, 26, 26, 28, 29, 30, - 30, 26, 27, 25, 0, 31, 31, 33, - 34, 31, 32, 35, 0, 36, 37, 0, - 38, 0, 39, 39, 41, 42, 43, 43, - 39, 40, 38, 0, 44, 44, 46, 47, - 44, 45, 48, 0, 49, 50, 0, 51, - 0, 52, 52, 54, 55, 56, 56, 52, - 53, 51, 0, 57, 57, 59, 60, 57, - 58, 61, 0, 62, 63, 0, 64, 0, - 65, 65, 67, 68, 69, 69, 65, 66, - 64, 0, 70, 70, 72, 73, 70, 71, - 74, 0, 75, 76, 0, 77, 0, 78, - 78, 79, 80, 80, 78, 77, 0, 81, - 81, 82, 81, 0, 84, 84, 85, 86, - 87, 88, 84, 83, 89, 83, 90, 83, - 91, 83, 92, 83, 93, 83, 93, 93, - 94, 93, 83, 94, 94, 95, 95, 96, - 94, 97, 83, 98, 99, 83, 100, 83, - 101, 101, 103, 104, 105, 105, 101, 102, - 100, 83, 106, 106, 108, 109, 106, 107, - 110, 83, 111, 112, 83, 113, 83, 114, - 114, 116, 117, 118, 118, 114, 115, 113, - 83, 119, 119, 121, 122, 119, 120, 123, - 83, 124, 125, 83, 126, 83, 127, 127, - 129, 130, 131, 131, 127, 128, 126, 83, - 132, 132, 134, 135, 132, 133, 136, 83, - 137, 138, 83, 139, 83, 140, 140, 142, - 143, 144, 144, 140, 141, 139, 83, 145, - 145, 147, 148, 145, 146, 149, 83, 150, - 151, 83, 152, 83, 153, 153, 155, 156, - 157, 157, 153, 154, 152, 83, 158, 158, - 160, 161, 158, 159, 162, 83, 163, 164, - 83, 165, 83, 166, 166, 79, 167, 167, - 166, 165, 83, 168, 168, 82, 168, 83, - 169, 169, 170, 83, 170, 83, 166, 166, - 79, 166, 170, 83, 166, 166, 79, 165, - 167, 167, 166, 164, 83, 160, 160, 159, - 159, 161, 160, 162, 83, 171, 171, 172, - 83, 172, 83, 153, 153, 155, 156, 153, - 154, 172, 83, 153, 153, 155, 152, 157, - 157, 153, 154, 151, 83, 147, 147, 146, - 146, 148, 147, 149, 83, 173, 173, 174, - 83, 174, 83, 140, 140, 142, 143, 140, - 141, 174, 83, 140, 140, 142, 139, 144, - 144, 140, 141, 138, 83, 134, 134, 133, - 133, 135, 134, 136, 83, 175, 175, 176, - 83, 176, 83, 127, 127, 129, 130, 127, - 128, 176, 83, 127, 127, 129, 126, 131, - 131, 127, 128, 125, 83, 121, 121, 120, - 120, 122, 121, 123, 83, 177, 177, 178, - 83, 178, 83, 114, 114, 116, 117, 114, - 115, 178, 83, 114, 114, 116, 113, 118, - 118, 114, 115, 112, 83, 108, 108, 107, - 107, 109, 108, 110, 83, 179, 179, 180, - 83, 180, 83, 101, 101, 103, 104, 101, - 102, 180, 83, 101, 101, 103, 100, 105, - 105, 101, 102, 99, 83, 181, 83, 182, - 83, 183, 83, 184, 83, 185, 83, 185, - 185, 186, 185, 83, 186, 186, 187, 187, - 188, 186, 189, 83, 190, 191, 83, 192, - 83, 193, 193, 194, 196, 197, 198, 198, - 193, 195, 192, 83, 199, 199, 200, 202, - 203, 199, 201, 204, 83, 205, 206, 83, - 207, 83, 208, 208, 210, 211, 212, 212, - 208, 209, 207, 83, 213, 213, 215, 216, - 213, 214, 217, 83, 218, 219, 83, 220, - 83, 221, 221, 194, 222, 222, 221, 220, - 83, 223, 223, 200, 223, 83, 224, 224, - 225, 83, 225, 83, 221, 221, 194, 221, - 225, 83, 221, 221, 194, 220, 222, 222, - 221, 219, 83, 215, 215, 214, 214, 216, - 215, 217, 83, 226, 226, 227, 83, 227, - 83, 208, 208, 210, 211, 208, 209, 227, - 83, 208, 208, 210, 207, 212, 212, 208, - 209, 206, 83, 202, 202, 201, 201, 203, - 202, 204, 83, 228, 228, 229, 83, 229, - 83, 193, 193, 194, 196, 197, 193, 195, - 229, 83, 193, 193, 194, 196, 192, 198, - 198, 193, 195, 191, 83, 230, 231, 83, - 232, 83, 233, 83, 234, 83, 234, 234, - 235, 234, 83, 235, 235, 236, 236, 237, - 235, 238, 83, 239, 240, 83, 241, 83, - 242, 242, 243, 245, 246, 247, 247, 242, - 244, 241, 83, 248, 248, 249, 251, 252, - 248, 250, 253, 83, 254, 255, 83, 256, - 83, 257, 257, 243, 258, 258, 257, 256, - 83, 259, 259, 249, 259, 83, 260, 260, - 261, 83, 261, 83, 257, 257, 243, 257, - 261, 83, 257, 257, 243, 256, 258, 258, - 257, 255, 83, 251, 251, 250, 250, 252, - 251, 253, 83, 262, 262, 263, 83, 263, - 83, 242, 242, 243, 245, 246, 242, 244, - 263, 83, 242, 242, 243, 245, 241, 247, - 247, 242, 244, 240, 83, 264, 83, 265, - 83, 266, 267, 83, 266, 266, 268, 266, - 83, 268, 268, 269, 269, 270, 268, 271, - 83, 272, 273, 83, 274, 83, 275, 275, - 276, 277, 277, 275, 274, 83, 278, 278, - 279, 278, 83, 280, 280, 281, 83, 281, - 83, 275, 275, 276, 275, 281, 83, 275, - 275, 276, 274, 277, 277, 275, 273, 83, - 267, 267, 282, 267, 83, 282, 282, 283, - 283, 284, 282, 285, 83, 286, 287, 83, - 288, 83, 289, 289, 290, 291, 291, 289, - 288, 83, 292, 292, 293, 292, 83, 294, - 294, 295, 83, 295, 83, 289, 289, 290, - 289, 295, 83, 289, 289, 290, 288, 291, - 291, 289, 287, 83, 296, 83, 297, 83, - 298, 83, 299, 83, 300, 83, 301, 83, - 302, 83, 303, 83, 303, 303, 304, 303, - 83, 304, 304, 305, 305, 306, 304, 307, - 83, 308, 309, 83, 310, 83, 311, 311, - 312, 314, 315, 316, 316, 311, 313, 310, - 83, 317, 317, 318, 320, 321, 317, 319, - 322, 83, 323, 324, 83, 325, 83, 326, - 326, 312, 327, 327, 326, 325, 83, 328, - 328, 318, 328, 83, 329, 329, 330, 83, - 330, 83, 326, 326, 312, 326, 330, 83, - 326, 326, 312, 325, 327, 327, 326, 324, - 83, 320, 320, 319, 319, 321, 320, 322, - 83, 331, 331, 332, 83, 332, 83, 311, - 311, 312, 314, 315, 311, 313, 332, 83, - 311, 311, 312, 314, 310, 316, 316, 311, - 313, 309, 83, 333, 333, 334, 0, 334, - 0, 78, 78, 79, 78, 334, 0, 78, - 78, 79, 77, 80, 80, 78, 76, 0, - 72, 72, 71, 71, 73, 72, 74, 0, - 335, 335, 336, 0, 336, 0, 65, 65, - 67, 68, 65, 66, 336, 0, 65, 65, - 67, 64, 69, 69, 65, 66, 63, 0, - 59, 59, 58, 58, 60, 59, 61, 0, - 337, 337, 338, 0, 338, 0, 52, 52, - 54, 55, 52, 53, 338, 0, 52, 52, - 54, 51, 56, 56, 52, 53, 50, 0, - 46, 46, 45, 45, 47, 46, 48, 0, - 339, 339, 340, 0, 340, 0, 39, 39, - 41, 42, 39, 40, 340, 0, 39, 39, - 41, 38, 43, 43, 39, 40, 37, 0, - 33, 33, 32, 32, 34, 33, 35, 0, - 341, 341, 342, 0, 342, 0, 26, 26, - 28, 29, 26, 27, 342, 0, 26, 26, - 28, 25, 30, 30, 26, 27, 24, 0, - 20, 20, 19, 19, 21, 20, 22, 0, - 343, 343, 344, 0, 344, 0, 13, 13, - 15, 16, 13, 14, 344, 0, 13, 13, - 15, 12, 17, 17, 13, 14, 11, 0, - 345, 0, 346, 0, 347, 0, 348, 0, - 349, 0, 349, 349, 350, 349, 0, 350, - 350, 351, 351, 352, 350, 353, 0, 354, - 355, 0, 356, 0, 357, 357, 194, 359, - 360, 361, 361, 357, 358, 356, 0, 362, - 362, 200, 364, 365, 362, 363, 366, 0, - 367, 368, 0, 369, 0, 370, 370, 372, - 373, 374, 374, 370, 371, 369, 0, 375, - 375, 377, 378, 375, 376, 379, 0, 380, - 381, 0, 382, 0, 383, 383, 194, 384, - 384, 383, 382, 0, 385, 385, 200, 385, - 0, 386, 386, 387, 0, 387, 0, 383, - 383, 194, 383, 387, 0, 383, 383, 194, - 382, 384, 384, 383, 381, 0, 377, 377, - 376, 376, 378, 377, 379, 0, 388, 388, - 389, 0, 389, 0, 370, 370, 372, 373, - 370, 371, 389, 0, 370, 370, 372, 369, - 374, 374, 370, 371, 368, 0, 364, 364, - 363, 363, 365, 364, 366, 0, 390, 390, - 391, 0, 391, 0, 357, 357, 194, 359, - 360, 357, 358, 391, 0, 357, 357, 194, - 359, 356, 361, 361, 357, 358, 355, 0, - 392, 393, 0, 394, 0, 395, 0, 396, - 0, 396, 396, 397, 396, 0, 397, 397, - 398, 398, 399, 397, 400, 0, 401, 402, - 0, 403, 0, 404, 404, 243, 406, 407, - 408, 408, 404, 405, 403, 0, 409, 409, - 249, 411, 412, 409, 410, 413, 0, 414, - 415, 0, 416, 0, 417, 417, 243, 418, - 418, 417, 416, 0, 419, 419, 249, 419, - 0, 420, 420, 421, 0, 421, 0, 417, - 417, 243, 417, 421, 0, 417, 417, 243, - 416, 418, 418, 417, 415, 0, 411, 411, - 410, 410, 412, 411, 413, 0, 422, 422, - 423, 0, 423, 0, 404, 404, 243, 406, - 407, 404, 405, 423, 0, 404, 404, 243, - 406, 403, 408, 408, 404, 405, 402, 0, - 424, 0, 425, 0, 426, 427, 0, 426, - 426, 428, 426, 0, 428, 428, 429, 429, - 430, 428, 431, 0, 432, 433, 0, 434, - 0, 435, 435, 276, 436, 436, 435, 434, - 0, 437, 437, 279, 437, 0, 438, 438, - 439, 0, 439, 0, 435, 435, 276, 435, - 439, 0, 435, 435, 276, 434, 436, 436, - 435, 433, 0, 427, 427, 440, 427, 0, - 440, 440, 441, 441, 442, 440, 443, 0, - 444, 445, 0, 446, 0, 447, 447, 290, - 448, 448, 447, 446, 0, 449, 449, 293, - 449, 0, 450, 450, 451, 0, 451, 0, - 447, 447, 290, 447, 451, 0, 447, 447, - 290, 446, 448, 448, 447, 445, 0, 452, - 0, 453, 0, 454, 0, 455, 0, 456, - 0, 457, 0, 458, 0, 459, 0, 459, - 459, 460, 459, 0, 460, 460, 461, 461, - 462, 460, 463, 0, 464, 465, 0, 466, - 0, 467, 467, 312, 469, 470, 471, 471, - 467, 468, 466, 0, 472, 472, 318, 474, - 475, 472, 473, 476, 0, 477, 478, 0, - 479, 0, 480, 480, 312, 481, 481, 480, - 479, 0, 482, 482, 318, 482, 0, 483, - 483, 484, 0, 484, 0, 480, 480, 312, - 480, 484, 0, 480, 480, 312, 479, 481, - 481, 480, 478, 0, 474, 474, 473, 473, - 475, 474, 476, 0, 485, 485, 486, 0, - 486, 0, 467, 467, 312, 469, 470, 467, - 468, 486, 0, 467, 467, 312, 469, 466, - 471, 471, 467, 468, 465, 0, 487, 487, - 489, 490, 491, 492, 487, 488, 487, 487, - 489, 490, 491, 492, 487, 0, 494, 494, - 495, 494, 493, 497, 497, 84, 85, 86, - 87, 88, 497, 496, 499, 499, 500, 499, - 498, 502, 502, 503, 502, 501, 505, 505, - 506, 505, 504, 508, 508, 509, 508, 507, - 511, 511, 512, 511, 510, 0 -}; + 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 5, 5, 6, 5, 0, 6, 6, 7, 7, 8, 6, 9, 0, + 10, 11, 0, 12, 0, 13, 13, 15, 16, 17, 17, 13, 14, 12, 0, 18, 18, 20, 21, 18, 19, 22, 0, + 23, 24, 0, 25, 0, 26, 26, 28, 29, 30, 30, 26, 27, 25, 0, 31, 31, 33, 34, 31, 32, 35, 0, + 36, 37, 0, 38, 0, 39, 39, 41, 42, 43, 43, 39, 40, 38, 0, 44, 44, 46, 47, 44, 45, 48, 0, + 49, 50, 0, 51, 0, 52, 52, 54, 55, 56, 56, 52, 53, 51, 0, 57, 57, 59, 60, 57, 58, 61, 0, + 62, 63, 0, 64, 0, 65, 65, 67, 68, 69, 69, 65, 66, 64, 0, 70, 70, 72, 73, 70, 71, 74, 0, + 75, 76, 0, 77, 0, 78, 78, 79, 80, 80, 78, 77, 0, 81, 81, 82, 81, 0, 84, 84, 85, 86, 87, + 88, 84, 83, 89, 83, 90, 83, 91, 83, 92, 83, 93, 83, 93, 93, 94, 93, 83, 94, 94, 95, 95, 96, + 94, 97, 83, 98, 99, 83, 100, 83, 101, 101, 103, 104, 105, 105, 101, 102, 100, 83, 106, 106, 108, 109, 106, + 107, 110, 83, 111, 112, 83, 113, 83, 114, 114, 116, 117, 118, 118, 114, 115, 113, 83, 119, 119, 121, 122, 119, + 120, 123, 83, 124, 125, 83, 126, 83, 127, 127, 129, 130, 131, 131, 127, 128, 126, 83, 132, 132, 134, 135, 132, + 133, 136, 83, 137, 138, 83, 139, 83, 140, 140, 142, 143, 144, 144, 140, 141, 139, 83, 145, 145, 147, 148, 145, + 146, 149, 83, 150, 151, 83, 152, 83, 153, 153, 155, 156, 157, 157, 153, 154, 152, 83, 158, 158, 160, 161, 158, + 159, 162, 83, 163, 164, 83, 165, 83, 166, 166, 79, 167, 167, 166, 165, 83, 168, 168, 82, 168, 83, 169, 169, + 170, 83, 170, 83, 166, 166, 79, 166, 170, 83, 166, 166, 79, 165, 167, 167, 166, 164, 83, 160, 160, 159, 159, + 161, 160, 162, 83, 171, 171, 172, 83, 172, 83, 153, 153, 155, 156, 153, 154, 172, 83, 153, 153, 155, 152, 157, + 157, 153, 154, 151, 83, 147, 147, 146, 146, 148, 147, 149, 83, 173, 173, 174, 83, 174, 83, 140, 140, 142, 143, + 140, 141, 174, 83, 140, 140, 142, 139, 144, 144, 140, 141, 138, 83, 134, 134, 133, 133, 135, 134, 136, 83, 175, + 175, 176, 83, 176, 83, 127, 127, 129, 130, 127, 128, 176, 83, 127, 127, 129, 126, 131, 131, 127, 128, 125, 83, + 121, 121, 120, 120, 122, 121, 123, 83, 177, 177, 178, 83, 178, 83, 114, 114, 116, 117, 114, 115, 178, 83, 114, + 114, 116, 113, 118, 118, 114, 115, 112, 83, 108, 108, 107, 107, 109, 108, 110, 83, 179, 179, 180, 83, 180, 83, + 101, 101, 103, 104, 101, 102, 180, 83, 101, 101, 103, 100, 105, 105, 101, 102, 99, 83, 181, 83, 182, 83, 183, + 83, 184, 83, 185, 83, 185, 185, 186, 185, 83, 186, 186, 187, 187, 188, 186, 189, 83, 190, 191, 83, 192, 83, + 193, 193, 194, 196, 197, 198, 198, 193, 195, 192, 83, 199, 199, 200, 202, 203, 199, 201, 204, 83, 205, 206, 83, + 207, 83, 208, 208, 210, 211, 212, 212, 208, 209, 207, 83, 213, 213, 215, 216, 213, 214, 217, 83, 218, 219, 83, + 220, 83, 221, 221, 194, 222, 222, 221, 220, 83, 223, 223, 200, 223, 83, 224, 224, 225, 83, 225, 83, 221, 221, + 194, 221, 225, 83, 221, 221, 194, 220, 222, 222, 221, 219, 83, 215, 215, 214, 214, 216, 215, 217, 83, 226, 226, + 227, 83, 227, 83, 208, 208, 210, 211, 208, 209, 227, 83, 208, 208, 210, 207, 212, 212, 208, 209, 206, 83, 202, + 202, 201, 201, 203, 202, 204, 83, 228, 228, 229, 83, 229, 83, 193, 193, 194, 196, 197, 193, 195, 229, 83, 193, + 193, 194, 196, 192, 198, 198, 193, 195, 191, 83, 230, 231, 83, 232, 83, 233, 83, 234, 83, 234, 234, 235, 234, + 83, 235, 235, 236, 236, 237, 235, 238, 83, 239, 240, 83, 241, 83, 242, 242, 243, 245, 246, 247, 247, 242, 244, + 241, 83, 248, 248, 249, 251, 252, 248, 250, 253, 83, 254, 255, 83, 256, 83, 257, 257, 243, 258, 258, 257, 256, + 83, 259, 259, 249, 259, 83, 260, 260, 261, 83, 261, 83, 257, 257, 243, 257, 261, 83, 257, 257, 243, 256, 258, + 258, 257, 255, 83, 251, 251, 250, 250, 252, 251, 253, 83, 262, 262, 263, 83, 263, 83, 242, 242, 243, 245, 246, + 242, 244, 263, 83, 242, 242, 243, 245, 241, 247, 247, 242, 244, 240, 83, 264, 83, 265, 83, 266, 267, 83, 266, + 266, 268, 266, 83, 268, 268, 269, 269, 270, 268, 271, 83, 272, 273, 83, 274, 83, 275, 275, 276, 277, 277, 275, + 274, 83, 278, 278, 279, 278, 83, 280, 280, 281, 83, 281, 83, 275, 275, 276, 275, 281, 83, 275, 275, 276, 274, + 277, 277, 275, 273, 83, 267, 267, 282, 267, 83, 282, 282, 283, 283, 284, 282, 285, 83, 286, 287, 83, 288, 83, + 289, 289, 290, 291, 291, 289, 288, 83, 292, 292, 293, 292, 83, 294, 294, 295, 83, 295, 83, 289, 289, 290, 289, + 295, 83, 289, 289, 290, 288, 291, 291, 289, 287, 83, 296, 83, 297, 83, 298, 83, 299, 83, 300, 83, 301, 83, + 302, 83, 303, 83, 303, 303, 304, 303, 83, 304, 304, 305, 305, 306, 304, 307, 83, 308, 309, 83, 310, 83, 311, + 311, 312, 314, 315, 316, 316, 311, 313, 310, 83, 317, 317, 318, 320, 321, 317, 319, 322, 83, 323, 324, 83, 325, + 83, 326, 326, 312, 327, 327, 326, 325, 83, 328, 328, 318, 328, 83, 329, 329, 330, 83, 330, 83, 326, 326, 312, + 326, 330, 83, 326, 326, 312, 325, 327, 327, 326, 324, 83, 320, 320, 319, 319, 321, 320, 322, 83, 331, 331, 332, + 83, 332, 83, 311, 311, 312, 314, 315, 311, 313, 332, 83, 311, 311, 312, 314, 310, 316, 316, 311, 313, 309, 83, + 333, 333, 334, 0, 334, 0, 78, 78, 79, 78, 334, 0, 78, 78, 79, 77, 80, 80, 78, 76, 0, 72, 72, + 71, 71, 73, 72, 74, 0, 335, 335, 336, 0, 336, 0, 65, 65, 67, 68, 65, 66, 336, 0, 65, 65, 67, + 64, 69, 69, 65, 66, 63, 0, 59, 59, 58, 58, 60, 59, 61, 0, 337, 337, 338, 0, 338, 0, 52, 52, + 54, 55, 52, 53, 338, 0, 52, 52, 54, 51, 56, 56, 52, 53, 50, 0, 46, 46, 45, 45, 47, 46, 48, + 0, 339, 339, 340, 0, 340, 0, 39, 39, 41, 42, 39, 40, 340, 0, 39, 39, 41, 38, 43, 43, 39, 40, + 37, 0, 33, 33, 32, 32, 34, 33, 35, 0, 341, 341, 342, 0, 342, 0, 26, 26, 28, 29, 26, 27, 342, + 0, 26, 26, 28, 25, 30, 30, 26, 27, 24, 0, 20, 20, 19, 19, 21, 20, 22, 0, 343, 343, 344, 0, + 344, 0, 13, 13, 15, 16, 13, 14, 344, 0, 13, 13, 15, 12, 17, 17, 13, 14, 11, 0, 345, 0, 346, + 0, 347, 0, 348, 0, 349, 0, 349, 349, 350, 349, 0, 350, 350, 351, 351, 352, 350, 353, 0, 354, 355, 0, + 356, 0, 357, 357, 194, 359, 360, 361, 361, 357, 358, 356, 0, 362, 362, 200, 364, 365, 362, 363, 366, 0, 367, + 368, 0, 369, 0, 370, 370, 372, 373, 374, 374, 370, 371, 369, 0, 375, 375, 377, 378, 375, 376, 379, 0, 380, + 381, 0, 382, 0, 383, 383, 194, 384, 384, 383, 382, 0, 385, 385, 200, 385, 0, 386, 386, 387, 0, 387, 0, + 383, 383, 194, 383, 387, 0, 383, 383, 194, 382, 384, 384, 383, 381, 0, 377, 377, 376, 376, 378, 377, 379, 0, + 388, 388, 389, 0, 389, 0, 370, 370, 372, 373, 370, 371, 389, 0, 370, 370, 372, 369, 374, 374, 370, 371, 368, + 0, 364, 364, 363, 363, 365, 364, 366, 0, 390, 390, 391, 0, 391, 0, 357, 357, 194, 359, 360, 357, 358, 391, + 0, 357, 357, 194, 359, 356, 361, 361, 357, 358, 355, 0, 392, 393, 0, 394, 0, 395, 0, 396, 0, 396, 396, + 397, 396, 0, 397, 397, 398, 398, 399, 397, 400, 0, 401, 402, 0, 403, 0, 404, 404, 243, 406, 407, 408, 408, + 404, 405, 403, 0, 409, 409, 249, 411, 412, 409, 410, 413, 0, 414, 415, 0, 416, 0, 417, 417, 243, 418, 418, + 417, 416, 0, 419, 419, 249, 419, 0, 420, 420, 421, 0, 421, 0, 417, 417, 243, 417, 421, 0, 417, 417, 243, + 416, 418, 418, 417, 415, 0, 411, 411, 410, 410, 412, 411, 413, 0, 422, 422, 423, 0, 423, 0, 404, 404, 243, + 406, 407, 404, 405, 423, 0, 404, 404, 243, 406, 403, 408, 408, 404, 405, 402, 0, 424, 0, 425, 0, 426, 427, + 0, 426, 426, 428, 426, 0, 428, 428, 429, 429, 430, 428, 431, 0, 432, 433, 0, 434, 0, 435, 435, 276, 436, + 436, 435, 434, 0, 437, 437, 279, 437, 0, 438, 438, 439, 0, 439, 0, 435, 435, 276, 435, 439, 0, 435, 435, + 276, 434, 436, 436, 435, 433, 0, 427, 427, 440, 427, 0, 440, 440, 441, 441, 442, 440, 443, 0, 444, 445, 0, + 446, 0, 447, 447, 290, 448, 448, 447, 446, 0, 449, 449, 293, 449, 0, 450, 450, 451, 0, 451, 0, 447, 447, + 290, 447, 451, 0, 447, 447, 290, 446, 448, 448, 447, 445, 0, 452, 0, 453, 0, 454, 0, 455, 0, 456, 0, + 457, 0, 458, 0, 459, 0, 459, 459, 460, 459, 0, 460, 460, 461, 461, 462, 460, 463, 0, 464, 465, 0, 466, + 0, 467, 467, 312, 469, 470, 471, 471, 467, 468, 466, 0, 472, 472, 318, 474, 475, 472, 473, 476, 0, 477, 478, + 0, 479, 0, 480, 480, 312, 481, 481, 480, 479, 0, 482, 482, 318, 482, 0, 483, 483, 484, 0, 484, 0, 480, + 480, 312, 480, 484, 0, 480, 480, 312, 479, 481, 481, 480, 478, 0, 474, 474, 473, 473, 475, 474, 476, 0, 485, + 485, 486, 0, 486, 0, 467, 467, 312, 469, 470, 467, 468, 486, 0, 467, 467, 312, 469, 466, 471, 471, 467, 468, + 465, 0, 487, 487, 489, 490, 491, 492, 487, 488, 487, 487, 489, 490, 491, 492, 487, 0, 494, 494, 495, 494, 493, + 497, 497, 84, 85, 86, 87, 88, 497, 496, 499, 499, 500, 499, 498, 502, 502, 503, 502, 501, 505, 505, 506, 505, + 504, 508, 508, 509, 508, 507, 511, 511, 512, 511, 510, 0}; static const short _svg_transform_trans_targs[] = { - 334, 2, 3, 4, 5, 6, 7, 8, - 9, 227, 9, 227, 10, 11, 12, 223, - 13, 224, 11, 12, 223, 13, 222, 13, - 222, 14, 15, 16, 218, 17, 219, 15, - 16, 218, 17, 217, 17, 217, 18, 19, - 20, 213, 21, 214, 19, 20, 213, 21, - 212, 21, 212, 22, 23, 24, 208, 25, - 209, 23, 24, 208, 25, 207, 25, 207, - 26, 27, 28, 203, 29, 204, 27, 28, - 203, 29, 202, 29, 202, 30, 31, 336, - 199, 31, 336, 334, 32, 33, 93, 126, - 172, 34, 35, 36, 37, 38, 39, 40, - 41, 92, 41, 92, 42, 43, 44, 88, - 45, 89, 43, 44, 88, 45, 87, 45, - 87, 46, 47, 48, 83, 49, 84, 47, - 48, 83, 49, 82, 49, 82, 50, 51, - 52, 78, 53, 79, 51, 52, 78, 53, - 77, 53, 77, 54, 55, 56, 73, 57, - 74, 55, 56, 73, 57, 72, 57, 72, - 58, 59, 60, 68, 61, 69, 59, 60, - 68, 61, 67, 61, 67, 62, 63, 64, - 63, 65, 66, 70, 71, 75, 76, 80, - 81, 85, 86, 90, 91, 94, 95, 96, - 97, 98, 99, 100, 101, 125, 101, 125, - 102, 103, 338, 104, 121, 105, 122, 103, - 338, 104, 121, 105, 120, 105, 120, 106, - 107, 108, 116, 109, 117, 107, 108, 116, - 109, 115, 109, 115, 110, 111, 112, 111, - 113, 114, 118, 119, 123, 124, 127, 149, - 128, 129, 130, 131, 132, 133, 148, 133, - 148, 134, 135, 339, 136, 144, 137, 145, - 135, 339, 136, 144, 137, 143, 137, 143, - 138, 139, 140, 139, 141, 142, 146, 147, - 150, 151, 152, 162, 153, 154, 155, 161, - 155, 161, 156, 157, 340, 158, 157, 340, - 159, 160, 163, 164, 165, 171, 165, 171, - 166, 167, 341, 168, 167, 341, 169, 170, - 173, 174, 175, 176, 177, 178, 179, 180, - 181, 182, 183, 198, 183, 198, 184, 185, - 342, 186, 194, 187, 195, 185, 342, 186, - 194, 187, 193, 187, 193, 188, 189, 190, - 189, 191, 192, 196, 197, 200, 201, 205, - 206, 210, 211, 215, 216, 220, 221, 225, - 226, 229, 230, 231, 232, 233, 234, 235, - 236, 260, 236, 260, 237, 238, 239, 256, - 240, 257, 238, 239, 256, 240, 255, 240, - 255, 241, 242, 243, 251, 244, 252, 242, - 243, 251, 244, 250, 244, 250, 245, 246, - 247, 246, 248, 249, 253, 254, 258, 259, - 262, 284, 263, 264, 265, 266, 267, 268, - 283, 268, 283, 269, 270, 271, 279, 272, - 280, 270, 271, 279, 272, 278, 272, 278, - 273, 274, 275, 274, 276, 277, 281, 282, - 285, 286, 287, 297, 288, 289, 290, 296, - 290, 296, 291, 292, 293, 292, 294, 295, - 298, 299, 300, 306, 300, 306, 301, 302, - 303, 302, 304, 305, 308, 309, 310, 311, - 312, 313, 314, 315, 316, 317, 318, 333, - 318, 333, 319, 320, 321, 329, 322, 330, - 320, 321, 329, 322, 328, 322, 328, 323, - 324, 325, 324, 326, 327, 331, 332, 335, - 0, 1, 228, 261, 307, 334, 337, 32, - 334, 337, 334, 337, 32, 334, 337, 32, - 334, 337, 32, 334, 337, 32, 334, 337, - 32 -}; + 334, 2, 3, 4, 5, 6, 7, 8, 9, 227, 9, 227, 10, 11, 12, 223, 13, 224, 11, 12, 223, 13, 222, + 13, 222, 14, 15, 16, 218, 17, 219, 15, 16, 218, 17, 217, 17, 217, 18, 19, 20, 213, 21, 214, 19, 20, + 213, 21, 212, 21, 212, 22, 23, 24, 208, 25, 209, 23, 24, 208, 25, 207, 25, 207, 26, 27, 28, 203, 29, + 204, 27, 28, 203, 29, 202, 29, 202, 30, 31, 336, 199, 31, 336, 334, 32, 33, 93, 126, 172, 34, 35, 36, + 37, 38, 39, 40, 41, 92, 41, 92, 42, 43, 44, 88, 45, 89, 43, 44, 88, 45, 87, 45, 87, 46, 47, + 48, 83, 49, 84, 47, 48, 83, 49, 82, 49, 82, 50, 51, 52, 78, 53, 79, 51, 52, 78, 53, 77, 53, + 77, 54, 55, 56, 73, 57, 74, 55, 56, 73, 57, 72, 57, 72, 58, 59, 60, 68, 61, 69, 59, 60, 68, + 61, 67, 61, 67, 62, 63, 64, 63, 65, 66, 70, 71, 75, 76, 80, 81, 85, 86, 90, 91, 94, 95, 96, + 97, 98, 99, 100, 101, 125, 101, 125, 102, 103, 338, 104, 121, 105, 122, 103, 338, 104, 121, 105, 120, 105, 120, + 106, 107, 108, 116, 109, 117, 107, 108, 116, 109, 115, 109, 115, 110, 111, 112, 111, 113, 114, 118, 119, 123, 124, + 127, 149, 128, 129, 130, 131, 132, 133, 148, 133, 148, 134, 135, 339, 136, 144, 137, 145, 135, 339, 136, 144, 137, + 143, 137, 143, 138, 139, 140, 139, 141, 142, 146, 147, 150, 151, 152, 162, 153, 154, 155, 161, 155, 161, 156, 157, + 340, 158, 157, 340, 159, 160, 163, 164, 165, 171, 165, 171, 166, 167, 341, 168, 167, 341, 169, 170, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, 198, 183, 198, 184, 185, 342, 186, 194, 187, 195, 185, 342, 186, 194, 187, + 193, 187, 193, 188, 189, 190, 189, 191, 192, 196, 197, 200, 201, 205, 206, 210, 211, 215, 216, 220, 221, 225, 226, + 229, 230, 231, 232, 233, 234, 235, 236, 260, 236, 260, 237, 238, 239, 256, 240, 257, 238, 239, 256, 240, 255, 240, + 255, 241, 242, 243, 251, 244, 252, 242, 243, 251, 244, 250, 244, 250, 245, 246, 247, 246, 248, 249, 253, 254, 258, + 259, 262, 284, 263, 264, 265, 266, 267, 268, 283, 268, 283, 269, 270, 271, 279, 272, 280, 270, 271, 279, 272, 278, + 272, 278, 273, 274, 275, 274, 276, 277, 281, 282, 285, 286, 287, 297, 288, 289, 290, 296, 290, 296, 291, 292, 293, + 292, 294, 295, 298, 299, 300, 306, 300, 306, 301, 302, 303, 302, 304, 305, 308, 309, 310, 311, 312, 313, 314, 315, + 316, 317, 318, 333, 318, 333, 319, 320, 321, 329, 322, 330, 320, 321, 329, 322, 328, 322, 328, 323, 324, 325, 324, + 326, 327, 331, 332, 335, 0, 1, 228, 261, 307, 334, 337, 32, 334, 337, 334, 337, 32, 334, 337, 32, 334, 337, + 32, 334, 337, 32, 334, 337, 32}; static const char _svg_transform_trans_actions[] = { - 13, 0, 0, 0, 0, 0, 0, 3, - 3, 3, 0, 0, 0, 1, 15, 1, - 15, 0, 0, 3, 0, 3, 3, 0, - 0, 0, 1, 15, 1, 15, 0, 0, - 3, 0, 3, 3, 0, 0, 0, 1, - 15, 1, 15, 0, 0, 3, 0, 3, - 3, 0, 0, 0, 1, 15, 1, 15, - 0, 0, 3, 0, 3, 3, 0, 0, - 0, 1, 15, 1, 15, 0, 0, 3, - 0, 3, 3, 0, 0, 0, 1, 39, - 0, 0, 7, 11, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 3, - 3, 3, 0, 0, 0, 1, 15, 1, - 15, 0, 0, 3, 0, 3, 3, 0, - 0, 0, 1, 15, 1, 15, 0, 0, - 3, 0, 3, 3, 0, 0, 0, 1, - 15, 1, 15, 0, 0, 3, 0, 3, - 3, 0, 0, 0, 1, 15, 1, 15, - 0, 0, 3, 0, 3, 3, 0, 0, - 0, 1, 15, 1, 15, 0, 0, 3, - 0, 3, 3, 0, 0, 0, 1, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 3, 3, 3, 0, 0, - 0, 1, 39, 15, 1, 15, 0, 0, - 7, 3, 0, 3, 3, 0, 0, 0, - 1, 15, 1, 15, 0, 0, 3, 0, - 3, 3, 0, 0, 0, 1, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 3, 3, 3, 0, - 0, 0, 1, 39, 15, 1, 15, 0, - 0, 7, 3, 0, 3, 3, 0, 0, - 0, 1, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 3, 3, 3, - 0, 0, 0, 1, 39, 0, 0, 7, - 0, 0, 0, 3, 3, 3, 0, 0, - 0, 1, 39, 0, 0, 7, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 3, 3, 3, 0, 0, 0, 1, - 39, 15, 1, 15, 0, 0, 7, 3, - 0, 3, 3, 0, 0, 0, 1, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 3, - 3, 3, 0, 0, 0, 1, 15, 1, - 15, 0, 0, 3, 0, 3, 3, 0, - 0, 0, 1, 15, 1, 15, 0, 0, - 3, 0, 3, 3, 0, 0, 0, 1, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 3, 3, - 3, 0, 0, 0, 1, 15, 1, 15, - 0, 0, 3, 0, 3, 3, 0, 0, - 0, 1, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 3, 3, 3, - 0, 0, 0, 1, 0, 0, 0, 0, - 0, 3, 3, 3, 0, 0, 0, 1, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 3, 3, 3, - 0, 0, 0, 1, 15, 1, 15, 0, - 0, 3, 0, 3, 3, 0, 0, 0, - 1, 0, 0, 0, 0, 0, 0, 42, - 0, 0, 0, 0, 0, 65, 89, 33, - 9, 7, 53, 77, 24, 49, 73, 21, - 57, 81, 27, 61, 85, 30, 45, 69, - 18 -}; + 13, 0, 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 1, 15, 1, 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 15, 1, + 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 15, 1, 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 15, 1, 15, 0, 0, + 3, 0, 3, 3, 0, 0, 0, 1, 15, 1, 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 39, 0, 0, 7, 11, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 1, 15, 1, 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 15, + 1, 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 15, 1, 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 15, 1, 15, 0, + 0, 3, 0, 3, 3, 0, 0, 0, 1, 15, 1, 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 1, 39, 15, 1, 15, 0, 0, 7, 3, 0, + 3, 3, 0, 0, 0, 1, 15, 1, 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 1, 39, 15, 1, 15, 0, 0, 7, 3, 0, 3, 3, 0, 0, 0, 1, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 1, 39, 0, 0, 7, 0, 0, 0, 3, 3, 3, 0, 0, 0, 1, + 39, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 1, 39, 15, 1, 15, 0, 0, 7, + 3, 0, 3, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 3, 3, 3, 0, 0, 0, 1, 15, 1, 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 15, 1, 15, 0, 0, 3, + 0, 3, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 1, 15, + 1, 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, + 1, 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, + 0, 0, 0, 1, 15, 1, 15, 0, 0, 3, 0, 3, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 0, 0, + 65, 89, 33, 9, 7, 53, 77, 24, 49, 73, 21, 57, 81, 27, 61, 85, 30, 45, 69, 18}; static const char _svg_transform_to_state_actions[] = { - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 36, 0, - 0, 0, 0, 0, 0, 0, 0 -}; + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0}; static const char _svg_transform_from_state_actions[] = { - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 5, 0, - 0, 0, 0, 0, 0, 0, 0 -}; + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0}; static const short _svg_transform_eof_trans[] = { - 0, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 84, - 84, 84, 84, 84, 84, 84, 84, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 0, 1, - 494, 497, 499, 502, 505, 508, 511 -}; + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, + 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, + 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, + 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, + 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, + 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, + 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 494, 497, 499, 502, 505, 508, 511}; static const int svg_transform_start = 334; static const int svg_transform_first_final = 334; static const int svg_transform_en_main = 334; - #line 28 "svg-affine-parser.rl" - // https://www.w3.org/TR/css-transforms-1/#svg-syntax bool sp_svg_transform_read(gchar const *str, Geom::Affine *transform) { @@ -993,8 +361,8 @@ bool sp_svg_transform_read(gchar const *str, Geom::Affine *transform) return false; std::vector<double> params; - Geom::Affine final_transform (Geom::identity()); - Geom::Affine tmp_transform (Geom::identity()); + Geom::Affine final_transform(Geom::identity()); + Geom::Affine tmp_transform(Geom::identity()); int cs; const char *p = str; const char *pe = p + strlen(p) + 1; @@ -1004,213 +372,242 @@ bool sp_svg_transform_read(gchar const *str, Geom::Affine *transform) char const *te = pe; int act = 0; - #line 1007 "svg-affine-parser.cpp" - { - cs = svg_transform_start; - ts = 0; - te = 0; - act = 0; - } + { + cs = svg_transform_start; + ts = 0; + te = 0; + act = 0; + } #line 1015 "svg-affine-parser.cpp" - { - int _klen; - unsigned int _trans; - const char *_acts; - unsigned int _nacts; - const char *_keys; - - if ( p == pe ) - goto _test_eof; - if ( cs == 0 ) - goto _out; -_resume: - _acts = _svg_transform_actions + _svg_transform_from_state_actions[cs]; - _nacts = (unsigned int) *_acts++; - while ( _nacts-- > 0 ) { - switch ( *_acts++ ) { - case 11: + { + int _klen; + unsigned int _trans; + const char *_acts; + unsigned int _nacts; + const char *_keys; + + if (p == pe) + goto _test_eof; + if (cs == 0) + goto _out; + _resume: + _acts = _svg_transform_actions + _svg_transform_from_state_actions[cs]; + _nacts = (unsigned int)*_acts++; + while (_nacts-- > 0) { + switch (*_acts++) { + case 11: #line 1 "NONE" - {ts = p;} - break; + { + ts = p; + } break; #line 1036 "svg-affine-parser.cpp" - } - } - - _keys = _svg_transform_trans_keys + _svg_transform_key_offsets[cs]; - _trans = _svg_transform_index_offsets[cs]; - - _klen = _svg_transform_single_lengths[cs]; - if ( _klen > 0 ) { - const char *_lower = _keys; - const char *_mid; - const char *_upper = _keys + _klen - 1; - while (true) { - if ( _upper < _lower ) - break; - - _mid = _lower + ((_upper-_lower) >> 1); - if ( (*p) < *_mid ) - _upper = _mid - 1; - else if ( (*p) > *_mid ) - _lower = _mid + 1; - else { - _trans += (unsigned int)(_mid - _keys); - goto _match; - } - } - _keys += _klen; - _trans += _klen; - } - - _klen = _svg_transform_range_lengths[cs]; - if ( _klen > 0 ) { - const char *_lower = _keys; - const char *_mid; - const char *_upper = _keys + (_klen<<1) - 2; - while (true) { - if ( _upper < _lower ) - break; - - _mid = _lower + (((_upper-_lower) >> 1) & ~1); - if ( (*p) < _mid[0] ) - _upper = _mid - 2; - else if ( (*p) > _mid[1] ) - _lower = _mid + 2; - else { - _trans += (unsigned int)((_mid - _keys)>>1); - goto _match; - } - } - _trans += _klen; - } - -_match: - _trans = _svg_transform_indicies[_trans]; -_eof_trans: - cs = _svg_transform_trans_targs[_trans]; - - if ( _svg_transform_trans_actions[_trans] == 0 ) - goto _again; - - _acts = _svg_transform_actions + _svg_transform_trans_actions[_trans]; - _nacts = (unsigned int) *_acts++; - while ( _nacts-- > 0 ) - { - switch ( *_acts++ ) - { - case 0: + } + } + + _keys = _svg_transform_trans_keys + _svg_transform_key_offsets[cs]; + _trans = _svg_transform_index_offsets[cs]; + + _klen = _svg_transform_single_lengths[cs]; + if (_klen > 0) { + const char *_lower = _keys; + const char *_mid; + const char *_upper = _keys + _klen - 1; + while (true) { + if (_upper < _lower) + break; + + _mid = _lower + ((_upper - _lower) >> 1); + if ((*p) < *_mid) + _upper = _mid - 1; + else if ((*p) > *_mid) + _lower = _mid + 1; + else { + _trans += (unsigned int)(_mid - _keys); + goto _match; + } + } + _keys += _klen; + _trans += _klen; + } + + _klen = _svg_transform_range_lengths[cs]; + if (_klen > 0) { + const char *_lower = _keys; + const char *_mid; + const char *_upper = _keys + (_klen << 1) - 2; + while (true) { + if (_upper < _lower) + break; + + _mid = _lower + (((_upper - _lower) >> 1) & ~1); + if ((*p) < _mid[0]) + _upper = _mid - 2; + else if ((*p) > _mid[1]) + _lower = _mid + 2; + else { + _trans += (unsigned int)((_mid - _keys) >> 1); + goto _match; + } + } + _trans += _klen; + } + + _match: + _trans = _svg_transform_indicies[_trans]; + _eof_trans: + cs = _svg_transform_trans_targs[_trans]; + + if (_svg_transform_trans_actions[_trans] == 0) + goto _again; + + _acts = _svg_transform_actions + _svg_transform_trans_actions[_trans]; + _nacts = (unsigned int)*_acts++; + while (_nacts-- > 0) { + switch (*_acts++) { + case 0: #line 49 "svg-affine-parser.rl" - { - std::string buf(start_num, p); - params.push_back(g_ascii_strtod(buf.c_str(), NULL)); - } - break; - case 1: + { + std::string buf(start_num, p); + params.push_back(g_ascii_strtod(buf.c_str(), NULL)); + } break; + case 1: #line 54 "svg-affine-parser.rl" - { tmp_transform = Geom::Translate(params[0], params.size() == 1 ? 0 : params[1]); } - break; - case 2: + { + tmp_transform = Geom::Translate(params[0], params.size() == 1 ? 0 : params[1]); + } break; + case 2: #line 55 "svg-affine-parser.rl" - { tmp_transform = Geom::Scale(params[0], params.size() == 1 ? params[0] : params[1]); } - break; - case 3: + { + tmp_transform = Geom::Scale(params[0], params.size() == 1 ? params[0] : params[1]); + } break; + case 3: #line 56 "svg-affine-parser.rl" - { - if (params.size() == 1) - tmp_transform = Geom::Rotate(Geom::rad_from_deg(params[0])); - else { - tmp_transform = Geom::Translate(-params[1], -params[2]) * - Geom::Rotate(Geom::rad_from_deg(params[0])) * - Geom::Translate(params[1], params[2]); - } - } - break; - case 4: + { + if (params.size() == 1) + tmp_transform = Geom::Rotate(Geom::rad_from_deg(params[0])); + else { + tmp_transform = Geom::Translate(-params[1], -params[2]) * + Geom::Rotate(Geom::rad_from_deg(params[0])) * + Geom::Translate(params[1], params[2]); + } + } break; + case 4: #line 65 "svg-affine-parser.rl" - { tmp_transform = Geom::Affine(1, 0, tan(params[0] * M_PI / 180.0), 1, 0, 0); } - break; - case 5: + { + tmp_transform = Geom::Affine(1, 0, tan(params[0] * M_PI / 180.0), 1, 0, 0); + } break; + case 5: #line 66 "svg-affine-parser.rl" - { tmp_transform = Geom::Affine(1, tan(params[0] * M_PI / 180.0), 0, 1, 0, 0); } - break; - case 6: + { + tmp_transform = Geom::Affine(1, tan(params[0] * M_PI / 180.0), 0, 1, 0, 0); + } break; + case 6: #line 67 "svg-affine-parser.rl" - { tmp_transform = Geom::Affine(params[0], params[1], params[2], params[3], params[4], params[5]);} - break; - case 7: + { + tmp_transform = Geom::Affine(params[0], params[1], params[2], params[3], params[4], params[5]); + } break; + case 7: #line 68 "svg-affine-parser.rl" - {params.clear(); final_transform = tmp_transform * final_transform ;} - break; - case 8: + { + params.clear(); + final_transform = tmp_transform * final_transform; + } break; + case 8: #line 82 "svg-affine-parser.rl" - {start_num = p;} - break; - case 12: + { + start_num = p; + } break; + case 12: #line 1 "NONE" - {te = p+1;} - break; - case 13: + { + te = p + 1; + } break; + case 13: #line 69 "svg-affine-parser.rl" - {act = 1;} - break; - case 14: + { + act = 1; + } break; + case 14: #line 69 "svg-affine-parser.rl" - {te = p;p--;{ *transform = final_transform; return true;}} - break; - case 15: + { + te = p; + p--; + { + *transform = final_transform; + return true; + } + } break; + case 15: #line 69 "svg-affine-parser.rl" - {{p = ((te))-1;}{ *transform = final_transform; return true;}} - break; - case 16: + { + { + p = ((te)) - 1; + } + { + *transform = final_transform; + return true; + } + } break; + case 16: #line 1 "NONE" - { switch( act ) { - case 0: - {{cs = 0;goto _again;}} - break; - case 1: - {{p = ((te))-1;} *transform = final_transform; return true;} - break; - } - } - break; + { + switch (act) { + case 0: { + { + cs = 0; + goto _again; + } + } break; + case 1: { + { + p = ((te)) - 1; + } + *transform = final_transform; + return true; + } break; + } + } break; #line 1177 "svg-affine-parser.cpp" - } - } - -_again: - _acts = _svg_transform_actions + _svg_transform_to_state_actions[cs]; - _nacts = (unsigned int) *_acts++; - while ( _nacts-- > 0 ) { - switch ( *_acts++ ) { - case 9: + } + } + + _again: + _acts = _svg_transform_actions + _svg_transform_to_state_actions[cs]; + _nacts = (unsigned int)*_acts++; + while (_nacts-- > 0) { + switch (*_acts++) { + case 9: #line 1 "NONE" - {ts = 0;} - break; - case 10: + { + ts = 0; + } break; + case 10: #line 1 "NONE" - {act = 0;} - break; + { + act = 0; + } break; #line 1194 "svg-affine-parser.cpp" - } - } - - if ( cs == 0 ) - goto _out; - if ( ++p != pe ) - goto _resume; - _test_eof: {} - if ( p == eof ) - { - if ( _svg_transform_eof_trans[cs] > 0 ) { - _trans = _svg_transform_eof_trans[cs] - 1; - goto _eof_trans; - } - } - - _out: {} - } + } + } + + if (cs == 0) + goto _out; + if (++p != pe) + goto _resume; + _test_eof : { + } + if (p == eof) { + if (_svg_transform_eof_trans[cs] > 0) { + _trans = _svg_transform_eof_trans[cs] - 1; + goto _eof_trans; + } + } + + _out : { + } + } #line 112 "svg-affine-parser.rl" diff --git a/src/svg/svg-affine-test.h b/src/svg/svg-affine-test.h index fcb9db04876d5cff5c76da12bac81f70e4b37108..8b4e906666e0fff1d4e71afe88552ea96b93a3e9 100644 --- a/src/svg/svg-affine-test.h +++ b/src/svg/svg-affine-test.h @@ -7,30 +7,32 @@ * Copyright (C) 2017 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cxxtest/TestSuite.h> - -#include "svg/svg.h" -#include "streq.h" #include <2geom/affine.h> #include <algorithm> +#include <cxxtest/TestSuite.h> #include <glib.h> #include <iostream> #include <math.h> #include <utility> +#include "streq.h" +#include "svg/svg.h" + class SvgAffineTest : public CxxTest::TestSuite { private: - struct test_t { - char const * str; + struct test_t + { + char const *str; Geom::Affine matrix; }; - struct approx_equal_pred { + struct approx_equal_pred + { bool operator()(Geom::Affine const &ref, Geom::Affine const &cm) const { double maxabsdiff = 0; - for(size_t i=0; i<6; i++) { - maxabsdiff = std::max(std::abs(ref[i]-cm[i]), maxabsdiff); + for (size_t i = 0; i < 6; i++) { + maxabsdiff = std::max(std::abs(ref[i] - cm[i]), maxabsdiff); } return maxabsdiff < 1e-14; } @@ -40,37 +42,31 @@ private: static test_t const read_scale_tests[3]; static test_t const read_rotate_tests[4]; static test_t const read_skew_tests[3]; - static char const * const read_fail_tests[25]; + static char const *const read_fail_tests[25]; static test_t const write_matrix_tests[2]; static test_t const write_translate_tests[3]; static test_t const write_scale_tests[3]; static test_t const write_rotate_tests[3]; static test_t const write_skew_tests[3]; + public: - SvgAffineTest() { - } + SvgAffineTest() {} -// createSuite and destroySuite get us per-suite setup and teardown -// without us having to worry about static initialization order, etc. + // createSuite and destroySuite get us per-suite setup and teardown + // without us having to worry about static initialization order, etc. static SvgAffineTest *createSuite() { return new SvgAffineTest(); } - static void destroySuite( SvgAffineTest *suite ) { delete suite; } + static void destroySuite(SvgAffineTest *suite) { delete suite; } void testReadIdentity() { - char const* strs[] = { - //0, - "", - "matrix(1,0,0,1,0,0)", - "translate(0,0)", - "scale(1,1)", - "rotate(0,0,0)", - "skewX(0)", - "skewY(0)"}; + char const *strs[] = { + // 0, + "", "matrix(1,0,0,1,0,0)", "translate(0,0)", "scale(1,1)", "rotate(0,0,0)", "skewX(0)", "skewY(0)"}; size_t n = G_N_ELEMENTS(strs); - for(size_t i=0; i<n; i++) { + for (size_t i = 0; i < n; i++) { Geom::Affine cm; - TSM_ASSERT(strs[i] , sp_svg_transform_read(strs[i], &cm)); - TSM_ASSERT_EQUALS(strs[i] , Geom::identity() , cm); + TSM_ASSERT(strs[i], sp_svg_transform_read(strs[i], &cm)); + TSM_ASSERT_EQUALS(strs[i], Geom::identity(), cm); } } @@ -83,139 +79,144 @@ public: void testReadMatrix() { - for(size_t i=0; i<G_N_ELEMENTS(read_matrix_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(read_matrix_tests); i++) { Geom::Affine cm; - TSM_ASSERT(read_matrix_tests[i].str , sp_svg_transform_read(read_matrix_tests[i].str, &cm)); - TSM_ASSERT_RELATION(read_matrix_tests[i].str , approx_equal_pred , read_matrix_tests[i].matrix , cm); + TSM_ASSERT(read_matrix_tests[i].str, sp_svg_transform_read(read_matrix_tests[i].str, &cm)); + TSM_ASSERT_RELATION(read_matrix_tests[i].str, approx_equal_pred, read_matrix_tests[i].matrix, cm); } } void testReadTranslate() { - for(size_t i=0; i<G_N_ELEMENTS(read_translate_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(read_translate_tests); i++) { Geom::Affine cm; - TSM_ASSERT(read_translate_tests[i].str , sp_svg_transform_read(read_translate_tests[i].str, &cm)); - TSM_ASSERT_RELATION(read_translate_tests[i].str , approx_equal_pred , read_translate_tests[i].matrix , cm); + TSM_ASSERT(read_translate_tests[i].str, sp_svg_transform_read(read_translate_tests[i].str, &cm)); + TSM_ASSERT_RELATION(read_translate_tests[i].str, approx_equal_pred, read_translate_tests[i].matrix, cm); } } void testReadScale() { - for(size_t i=0; i<G_N_ELEMENTS(read_scale_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(read_scale_tests); i++) { Geom::Affine cm; - TSM_ASSERT(read_scale_tests[i].str , sp_svg_transform_read(read_scale_tests[i].str, &cm)); - TSM_ASSERT_RELATION(read_scale_tests[i].str , approx_equal_pred , read_scale_tests[i].matrix , cm); + TSM_ASSERT(read_scale_tests[i].str, sp_svg_transform_read(read_scale_tests[i].str, &cm)); + TSM_ASSERT_RELATION(read_scale_tests[i].str, approx_equal_pred, read_scale_tests[i].matrix, cm); } } void testReadRotate() { - for(size_t i=0; i<G_N_ELEMENTS(read_rotate_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(read_rotate_tests); i++) { Geom::Affine cm; - TSM_ASSERT(read_rotate_tests[i].str , sp_svg_transform_read(read_rotate_tests[i].str, &cm)); - TSM_ASSERT_RELATION(read_rotate_tests[i].str , approx_equal_pred , read_rotate_tests[i].matrix , cm); + TSM_ASSERT(read_rotate_tests[i].str, sp_svg_transform_read(read_rotate_tests[i].str, &cm)); + TSM_ASSERT_RELATION(read_rotate_tests[i].str, approx_equal_pred, read_rotate_tests[i].matrix, cm); } } void testReadSkew() { - for(size_t i=0; i<G_N_ELEMENTS(read_skew_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(read_skew_tests); i++) { Geom::Affine cm; - TSM_ASSERT(read_skew_tests[i].str , sp_svg_transform_read(read_skew_tests[i].str, &cm)); - TSM_ASSERT_RELATION(read_skew_tests[i].str , approx_equal_pred , read_skew_tests[i].matrix , cm); + TSM_ASSERT(read_skew_tests[i].str, sp_svg_transform_read(read_skew_tests[i].str, &cm)); + TSM_ASSERT_RELATION(read_skew_tests[i].str, approx_equal_pred, read_skew_tests[i].matrix, cm); } } void testWriteMatrix() { - for(size_t i=0; i<G_N_ELEMENTS(write_matrix_tests); i++) { - char * str = sp_svg_transform_write(write_matrix_tests[i].matrix); - TS_ASSERT_RELATION(streq_rel , str , write_matrix_tests[i].str); + for (size_t i = 0; i < G_N_ELEMENTS(write_matrix_tests); i++) { + char *str = sp_svg_transform_write(write_matrix_tests[i].matrix); + TS_ASSERT_RELATION(streq_rel, str, write_matrix_tests[i].str); g_free(str); } } void testWriteTranslate() { - for(size_t i=0; i<G_N_ELEMENTS(write_translate_tests); i++) { - char * str = sp_svg_transform_write(write_translate_tests[i].matrix); - TS_ASSERT_RELATION(streq_rel , str , write_translate_tests[i].str); + for (size_t i = 0; i < G_N_ELEMENTS(write_translate_tests); i++) { + char *str = sp_svg_transform_write(write_translate_tests[i].matrix); + TS_ASSERT_RELATION(streq_rel, str, write_translate_tests[i].str); g_free(str); } } void testWriteScale() { - for(size_t i=0; i<G_N_ELEMENTS(write_scale_tests); i++) { - char * str = sp_svg_transform_write(write_scale_tests[i].matrix); - TS_ASSERT_RELATION(streq_rel , str , write_scale_tests[i].str); + for (size_t i = 0; i < G_N_ELEMENTS(write_scale_tests); i++) { + char *str = sp_svg_transform_write(write_scale_tests[i].matrix); + TS_ASSERT_RELATION(streq_rel, str, write_scale_tests[i].str); g_free(str); } } void testWriteRotate() { - for(size_t i=0; i<G_N_ELEMENTS(write_rotate_tests); i++) { - char * str = sp_svg_transform_write(write_rotate_tests[i].matrix); - TS_ASSERT_RELATION(streq_rel , str , write_rotate_tests[i].str); + for (size_t i = 0; i < G_N_ELEMENTS(write_rotate_tests); i++) { + char *str = sp_svg_transform_write(write_rotate_tests[i].matrix); + TS_ASSERT_RELATION(streq_rel, str, write_rotate_tests[i].str); g_free(str); } } void testWriteSkew() { - for(size_t i=0; i<G_N_ELEMENTS(write_skew_tests); i++) { - char * str = sp_svg_transform_write(write_skew_tests[i].matrix); - TS_ASSERT_RELATION(streq_rel , str , write_skew_tests[i].str); + for (size_t i = 0; i < G_N_ELEMENTS(write_skew_tests); i++) { + char *str = sp_svg_transform_write(write_skew_tests[i].matrix); + TS_ASSERT_RELATION(streq_rel, str, write_skew_tests[i].str); g_free(str); } } void testReadConcatenation() { - // NOTE: According to the SVG specification (see the syntax at http://www.w3.org/TR/SVG/coords.html#TransformAttribute - // there should be 1 or more comma-wsp sequences between transforms... This doesn't make sense and it seems - // likely that instead of a + they meant a ? (zero or one comma-wsp sequences). - char const * str = "skewY(17)skewX(9)translate(7,13)scale(2)rotate(13)translate(3,5)"; - Geom::Affine ref(2.0199976232558053, 1.0674773585906016, -0.14125199392774669, 1.9055550612095459, 14.412730624347654, 28.499820929377454); // Precomputed using Mathematica + // NOTE: According to the SVG specification (see the syntax at + // http://www.w3.org/TR/SVG/coords.html#TransformAttribute + // there should be 1 or more comma-wsp sequences between transforms... This doesn't make sense and it + // seems likely that instead of a + they meant a ? (zero or one comma-wsp sequences). + char const *str = "skewY(17)skewX(9)translate(7,13)scale(2)rotate(13)translate(3,5)"; + Geom::Affine ref(2.0199976232558053, 1.0674773585906016, -0.14125199392774669, 1.9055550612095459, + 14.412730624347654, 28.499820929377454); // Precomputed using Mathematica Geom::Affine cm; TS_ASSERT(sp_svg_transform_read(str, &cm)); - TS_ASSERT_RELATION(approx_equal_pred , ref , cm); + TS_ASSERT_RELATION(approx_equal_pred, ref, cm); } void testReadFailures() { - for(size_t i=0; i<G_N_ELEMENTS(read_fail_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(read_fail_tests); i++) { Geom::Affine cm; - TSM_ASSERT(read_fail_tests[i] , !sp_svg_transform_read(read_fail_tests[i], &cm)); + TSM_ASSERT(read_fail_tests[i], !sp_svg_transform_read(read_fail_tests[i], &cm)); } } }; -static double const DEGREE = M_PI/180.; +static double const DEGREE = M_PI / 180.; SvgAffineTest::test_t const SvgAffineTest::read_matrix_tests[3] = { - {"matrix(0,0,0,0,0,0)",Geom::Affine(0,0,0,0,0,0)}, - {" matrix(1,2,3,4,5,6)",Geom::Affine(1,2,3,4,5,6)}, - {"matrix (1 2 -3,-4,5e6,-6e-7)",Geom::Affine(1,2,-3,-4,5e6,-6e-7)}}; + {"matrix(0,0,0,0,0,0)", Geom::Affine(0, 0, 0, 0, 0, 0)}, + {" matrix(1,2,3,4,5,6)", Geom::Affine(1, 2, 3, 4, 5, 6)}, + {"matrix (1 2 -3,-4,5e6,-6e-7)", Geom::Affine(1, 2, -3, -4, 5e6, -6e-7)}}; SvgAffineTest::test_t const SvgAffineTest::read_translate_tests[3] = { - {"translate(1)",Geom::Affine(1,0,0,1,1,0)}, - {"translate(1,1)",Geom::Affine(1,0,0,1,1,1)}, - {"translate(-1e3 .123e2)",Geom::Affine(1,0,0,1,-1e3,.123e2)}}; + {"translate(1)", Geom::Affine(1, 0, 0, 1, 1, 0)}, + {"translate(1,1)", Geom::Affine(1, 0, 0, 1, 1, 1)}, + {"translate(-1e3 .123e2)", Geom::Affine(1, 0, 0, 1, -1e3, .123e2)}}; SvgAffineTest::test_t const SvgAffineTest::read_scale_tests[3] = { - {"scale(2)",Geom::Affine(2,0,0,2,0,0)}, - {"scale(2,3)",Geom::Affine(2,0,0,3,0,0)}, - {"scale(0.1e-2 -.475e0)",Geom::Affine(0.1e-2,0,0,-.475e0,0,0)}}; + {"scale(2)", Geom::Affine(2, 0, 0, 2, 0, 0)}, + {"scale(2,3)", Geom::Affine(2, 0, 0, 3, 0, 0)}, + {"scale(0.1e-2 -.475e0)", Geom::Affine(0.1e-2, 0, 0, -.475e0, 0, 0)}}; SvgAffineTest::test_t const SvgAffineTest::read_rotate_tests[4] = { - {"rotate(13 )",Geom::Affine(cos(13.*DEGREE),sin(13.*DEGREE),-sin(13.*DEGREE),cos(13.*DEGREE),0,0)}, - {"rotate(-13)",Geom::Affine(cos(-13.*DEGREE),sin(-13.*DEGREE),-sin(-13.*DEGREE),cos(-13.*DEGREE),0,0)}, - {"rotate(373)",Geom::Affine(cos(13.*DEGREE),sin(13.*DEGREE),-sin(13.*DEGREE),cos(13.*DEGREE),0,0)}, - {"rotate(13,7,11)",Geom::Affine(cos(13.*DEGREE),sin(13.*DEGREE),-sin(13.*DEGREE),cos(13.*DEGREE),(1-cos(13.*DEGREE))*7+sin(13.*DEGREE)*11,(1-cos(13.*DEGREE))*11-sin(13.*DEGREE)*7)}}; + {"rotate(13 )", Geom::Affine(cos(13. * DEGREE), sin(13. * DEGREE), -sin(13. * DEGREE), cos(13. * DEGREE), 0, 0)}, + {"rotate(-13)", + Geom::Affine(cos(-13. * DEGREE), sin(-13. * DEGREE), -sin(-13. * DEGREE), cos(-13. * DEGREE), 0, 0)}, + {"rotate(373)", Geom::Affine(cos(13. * DEGREE), sin(13. * DEGREE), -sin(13. * DEGREE), cos(13. * DEGREE), 0, 0)}, + {"rotate(13,7,11)", Geom::Affine(cos(13. * DEGREE), sin(13. * DEGREE), -sin(13. * DEGREE), cos(13. * DEGREE), + (1 - cos(13. * DEGREE)) * 7 + sin(13. * DEGREE) * 11, + (1 - cos(13. * DEGREE)) * 11 - sin(13. * DEGREE) * 7)}}; SvgAffineTest::test_t const SvgAffineTest::read_skew_tests[3] = { - {"skewX( 30)",Geom::Affine(1,0,tan(30.*DEGREE),1,0,0)}, - {"skewX(-30)",Geom::Affine(1,0,tan(-30.*DEGREE),1,0,0)}, - {"skewY(390)",Geom::Affine(1,tan(30.*DEGREE),0,1,0,0)}}; -char const * const SvgAffineTest::read_fail_tests[25] = { + {"skewX( 30)", Geom::Affine(1, 0, tan(30. * DEGREE), 1, 0, 0)}, + {"skewX(-30)", Geom::Affine(1, 0, tan(-30. * DEGREE), 1, 0, 0)}, + {"skewY(390)", Geom::Affine(1, tan(30. * DEGREE), 0, 1, 0, 0)}}; +char const *const SvgAffineTest::read_fail_tests[25] = { "matrix((1,2,3,4,5,6)", "matrix((1,2,3,4,5,6))", "matrix(1,2,3,4,5,6))", @@ -243,24 +244,28 @@ char const * const SvgAffineTest::read_fail_tests[25] = { "skewY(1,2)"}; SvgAffineTest::test_t const SvgAffineTest::write_matrix_tests[2] = { - {"matrix(1,2,3,4,5,6)",Geom::Affine(1,2,3,4,5,6)}, - {"matrix(-1,2123,3,0.4,1e-8,1e20)",Geom::Affine(-1,2.123e3,3+1e-14,0.4,1e-8,1e20)}}; + {"matrix(1,2,3,4,5,6)", Geom::Affine(1, 2, 3, 4, 5, 6)}, + {"matrix(-1,2123,3,0.4,1e-8,1e20)", Geom::Affine(-1, 2.123e3, 3 + 1e-14, 0.4, 1e-8, 1e20)}}; SvgAffineTest::test_t const SvgAffineTest::write_translate_tests[3] = { - {"translate(1,1)",Geom::Affine(1,0,0,1,1,1)}, - {"translate(1)",Geom::Affine(1,0,0,1,1,0)}, - {"translate(-1345,0.123)",Geom::Affine(1,0,0,1,-1.345e3,.123)}}; -SvgAffineTest::test_t const SvgAffineTest::write_scale_tests[3] = { - {"scale(0)",Geom::Affine(0,0,0,0,0,0)}, - {"scale(7)",Geom::Affine(7,0,0,7,0,0)}, - {"scale(2,3)",Geom::Affine(2,0,0,3,0,0)}}; + {"translate(1,1)", Geom::Affine(1, 0, 0, 1, 1, 1)}, + {"translate(1)", Geom::Affine(1, 0, 0, 1, 1, 0)}, + {"translate(-1345,0.123)", Geom::Affine(1, 0, 0, 1, -1.345e3, .123)}}; +SvgAffineTest::test_t const SvgAffineTest::write_scale_tests[3] = {{"scale(0)", Geom::Affine(0, 0, 0, 0, 0, 0)}, + {"scale(7)", Geom::Affine(7, 0, 0, 7, 0, 0)}, + {"scale(2,3)", Geom::Affine(2, 0, 0, 3, 0, 0)}}; SvgAffineTest::test_t const SvgAffineTest::write_rotate_tests[3] = { - {"rotate(13)",Geom::Affine(cos(13.*DEGREE),sin(13.*DEGREE),-sin(13.*DEGREE),cos(13.*DEGREE),0,0)}, - {"rotate(-13,7,11)",Geom::Affine(cos(-13.*DEGREE),sin(-13.*DEGREE),-sin(-13.*DEGREE),cos(-13.*DEGREE),(1-cos(-13.*DEGREE))*7+sin(-13.*DEGREE)*11,(1-cos(-13.*DEGREE))*11-sin(-13.*DEGREE)*7)}, - {"rotate(-34.5,6.7,89)",Geom::Affine(cos(-34.5*DEGREE),sin(-34.5*DEGREE),-sin(-34.5*DEGREE),cos(-34.5*DEGREE),(1-cos(-34.5*DEGREE))*6.7+sin(-34.5*DEGREE)*89,(1-cos(-34.5*DEGREE))*89-sin(-34.5*DEGREE)*6.7)}}; + {"rotate(13)", Geom::Affine(cos(13. * DEGREE), sin(13. * DEGREE), -sin(13. * DEGREE), cos(13. * DEGREE), 0, 0)}, + {"rotate(-13,7,11)", Geom::Affine(cos(-13. * DEGREE), sin(-13. * DEGREE), -sin(-13. * DEGREE), cos(-13. * DEGREE), + (1 - cos(-13. * DEGREE)) * 7 + sin(-13. * DEGREE) * 11, + (1 - cos(-13. * DEGREE)) * 11 - sin(-13. * DEGREE) * 7)}, + {"rotate(-34.5,6.7,89)", + Geom::Affine(cos(-34.5 * DEGREE), sin(-34.5 * DEGREE), -sin(-34.5 * DEGREE), cos(-34.5 * DEGREE), + (1 - cos(-34.5 * DEGREE)) * 6.7 + sin(-34.5 * DEGREE) * 89, + (1 - cos(-34.5 * DEGREE)) * 89 - sin(-34.5 * DEGREE) * 6.7)}}; SvgAffineTest::test_t const SvgAffineTest::write_skew_tests[3] = { - {"skewX(30)",Geom::Affine(1,0,tan(30.*DEGREE),1,0,0)}, - {"skewX(-30)",Geom::Affine(1,0,tan(-30.*DEGREE),1,0,0)}, - {"skewY(30)",Geom::Affine(1,tan(30.*DEGREE),0,1,0,0)}}; + {"skewX(30)", Geom::Affine(1, 0, tan(30. * DEGREE), 1, 0, 0)}, + {"skewX(-30)", Geom::Affine(1, 0, tan(-30. * DEGREE), 1, 0, 0)}, + {"skewY(30)", Geom::Affine(1, tan(30. * DEGREE), 0, 1, 0, 0)}}; /* Local Variables: diff --git a/src/svg/svg-affine.cpp b/src/svg/svg-affine.cpp index 8bc28860694f6aef1ca5b062daa67edd2a64296f..6ce8d83f0994f9a32d04b73bdb68441baf973250 100644 --- a/src/svg/svg-affine.cpp +++ b/src/svg/svg-affine.cpp @@ -12,17 +12,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> -#include <string> -#include <cstdlib> +#include <2geom/transforms.h> #include <cstdio> +#include <cstdlib> +#include <cstring> #include <glib.h> -#include <2geom/transforms.h> -#include "svg.h" +#include <string> + #include "preferences.h" +#include "svg.h" -gchar * -sp_svg_transform_write(Geom::Affine const &transform) +gchar *sp_svg_transform_write(Geom::Affine const &transform) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -33,16 +33,15 @@ sp_svg_transform_write(Geom::Affine const &transform) // Special case: when all fields of the affine are zero, // the optimized transformation is scale(0) - if (transform[0] == 0 && transform[1] == 0 && transform[2] == 0 && - transform[3] == 0 && transform[4] == 0 && transform[5] == 0) - { + if (transform[0] == 0 && transform[1] == 0 && transform[2] == 0 && transform[3] == 0 && transform[4] == 0 && + transform[5] == 0) { return g_strdup("scale(0)"); } // FIXME legacy C code! // the function sp_svg_number_write_de is stopping me from using a proper C++ string - gchar c[256]; // string buffer + gchar c[256]; // string buffer unsigned p = 0; // position in the buffer if (transform.isIdentity()) { @@ -50,29 +49,29 @@ sp_svg_transform_write(Geom::Affine const &transform) return nullptr; } else if (transform.isScale()) { // We are more or less a uniform scale - strcpy (c + p, "scale("); + strcpy(c + p, "scale("); p += 6; - p += sp_svg_number_write_de( c + p, sizeof(c) - p, transform[0], prec, min_exp ); + p += sp_svg_number_write_de(c + p, sizeof(c) - p, transform[0], prec, min_exp); if (Geom::are_near(transform[0], transform[3], e)) { c[p++] = ')'; c[p] = '\000'; } else { c[p++] = ','; - p += sp_svg_number_write_de( c + p, sizeof(c) - p, transform[3], prec, min_exp ); + p += sp_svg_number_write_de(c + p, sizeof(c) - p, transform[3], prec, min_exp); c[p++] = ')'; c[p] = '\000'; } } else if (transform.isTranslation()) { // We are more or less a pure translation - strcpy (c + p, "translate("); + strcpy(c + p, "translate("); p += 10; - p += sp_svg_number_write_de( c + p, sizeof(c) - p, transform[4], prec, min_exp ); + p += sp_svg_number_write_de(c + p, sizeof(c) - p, transform[4], prec, min_exp); if (Geom::are_near(transform[5], 0.0, e)) { c[p++] = ')'; c[p] = '\000'; } else { c[p++] = ','; - p += sp_svg_number_write_de( c + p, sizeof(c) - p, transform[5], prec, min_exp ); + p += sp_svg_number_write_de(c + p, sizeof(c) - p, transform[5], prec, min_exp); c[p++] = ')'; c[p] = '\000'; } @@ -98,13 +97,13 @@ sp_svg_transform_write(Geom::Affine const &transform) p += sp_svg_number_write_de(c + p, sizeof(c) - p, angle, prec, min_exp); c[p++] = ','; - Geom::Affine const& m = transform; - double tx = (m[2]*m[5]+m[4]-m[4]*m[3]) / (1-m[3]-m[0]+m[0]*m[3]-m[2]*m[1]); + Geom::Affine const &m = transform; + double tx = (m[2] * m[5] + m[4] - m[4] * m[3]) / (1 - m[3] - m[0] + m[0] * m[3] - m[2] * m[1]); p += sp_svg_number_write_de(c + p, sizeof(c) - p, tx, prec, min_exp); c[p++] = ','; - double ty = (m[1]*tx + m[5]) / (1 - m[3]); + double ty = (m[1] * tx + m[5]) / (1 - m[3]); p += sp_svg_number_write_de(c + p, sizeof(c) - p, ty, prec, min_exp); c[p++] = ')'; @@ -130,19 +129,19 @@ sp_svg_transform_write(Geom::Affine const &transform) c[p++] = ')'; c[p] = '\000'; } else { - strcpy (c + p, "matrix("); + strcpy(c + p, "matrix("); p += 7; - p += sp_svg_number_write_de( c + p, sizeof(c) - p, transform[0], prec, min_exp ); + p += sp_svg_number_write_de(c + p, sizeof(c) - p, transform[0], prec, min_exp); c[p++] = ','; - p += sp_svg_number_write_de( c + p, sizeof(c) - p, transform[1], prec, min_exp ); + p += sp_svg_number_write_de(c + p, sizeof(c) - p, transform[1], prec, min_exp); c[p++] = ','; - p += sp_svg_number_write_de( c + p, sizeof(c) - p, transform[2], prec, min_exp ); + p += sp_svg_number_write_de(c + p, sizeof(c) - p, transform[2], prec, min_exp); c[p++] = ','; - p += sp_svg_number_write_de( c + p, sizeof(c) - p, transform[3], prec, min_exp ); + p += sp_svg_number_write_de(c + p, sizeof(c) - p, transform[3], prec, min_exp); c[p++] = ','; - p += sp_svg_number_write_de( c + p, sizeof(c) - p, transform[4], prec, min_exp ); + p += sp_svg_number_write_de(c + p, sizeof(c) - p, transform[4], prec, min_exp); c[p++] = ','; - p += sp_svg_number_write_de( c + p, sizeof(c) - p, transform[5], prec, min_exp ); + p += sp_svg_number_write_de(c + p, sizeof(c) - p, transform[5], prec, min_exp); c[p++] = ')'; c[p] = '\000'; } @@ -151,9 +150,7 @@ sp_svg_transform_write(Geom::Affine const &transform) return g_strdup(c); } - -gchar * -sp_svg_transform_write(Geom::Affine const *transform) +gchar *sp_svg_transform_write(Geom::Affine const *transform) { return sp_svg_transform_write(*transform); } diff --git a/src/svg/svg-angle.cpp b/src/svg/svg-angle.cpp index e82d0de457a9e1930790da29ce73f6b91420ea62..24f411bab2ad71e338830711658c88aa1ece8c96 100644 --- a/src/svg/svg-angle.cpp +++ b/src/svg/svg-angle.cpp @@ -13,14 +13,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "svg/svg-angle.h" + #include <cstring> -#include <string> #include <glib.h> +#include <string> -#include "svg/svg-angle.h" #include "util/units.h" - static bool sp_svg_angle_read_lff(gchar const *str, SVGAngle::Unit &unit, float &val, float &computed); SVGAngle::SVGAngle() @@ -28,8 +28,7 @@ SVGAngle::SVGAngle() , unit(NONE) , value(0) , computed(0) -{ -} +{} /* Angle */ @@ -54,14 +53,16 @@ bool SVGAngle::read(gchar const *str) return true; } -void SVGAngle::unset(SVGAngle::Unit u, float v, float c) { +void SVGAngle::unset(SVGAngle::Unit u, float v, float c) +{ _set = false; unit = u; value = v; computed = c; } -void SVGAngle::readOrUnset(gchar const *str, Unit u, float v, float c) { +void SVGAngle::readOrUnset(gchar const *str, Unit u, float v, float c) +{ if (!read(str)) { unset(u, v, c); } @@ -74,7 +75,7 @@ static bool sp_svg_angle_read_lff(gchar const *str, SVGAngle::Unit &unit, float } gchar const *e; - float const v = g_ascii_strtod(str, (char **) &e); + float const v = g_ascii_strtod(str, (char **)&e); if (e == str) { return false; } diff --git a/src/svg/svg-angle.h b/src/svg/svg-angle.h index 6ed59153abeec55642a82be156318f87e2b28f8e..56801715a0a3ca622f29a96a472232281dd69679 100644 --- a/src/svg/svg-angle.h +++ b/src/svg/svg-angle.h @@ -23,7 +23,8 @@ class SVGAngle public: SVGAngle(); - enum Unit { + enum Unit + { NONE, DEG, GRAD, @@ -44,7 +45,8 @@ public: // The value in degrees. float computed; - float operator=(float v) { + float operator=(float v) + { _set = true; unit = NONE; value = computed = v; diff --git a/src/svg/svg-color.cpp b/src/svg/svg-color.cpp index 1c8c021d3c3f0c4c83e0eaa47d927e2277742b0e..582ba0175d6ba47f8e6ada517cdfa0bf1ab71727 100644 --- a/src/svg/svg-color.cpp +++ b/src/svg/svg-color.cpp @@ -13,39 +13,38 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include <cstdlib> +#include <cerrno> +#include <cmath> #include <cstdio> // sprintf +#include <cstdlib> #include <cstring> -#include <string> -#include <cmath> #include <glib.h> // g_assert -#include <cerrno> - #include <map> +#include <string> +#include "color.h" #include "colorspace.h" -#include "strneq.h" #include "preferences.h" +#include "strneq.h" #include "svg-color.h" #include "svg-icc-color.h" - -#include "color.h" #if defined(HAVE_LIBLCMS2) #include <vector> -#include "object/color-profile.h" #include "document.h" #include "inkscape.h" +#include "object/color-profile.h" #include "profile-manager.h" #endif // defined(HAVE_LIBLCMS2) #include "cms-system.h" -struct SPSVGColor { +struct SPSVGColor +{ unsigned long rgb; const std::string name; }; @@ -53,156 +52,154 @@ struct SPSVGColor { /* * These are the colors defined in the SVG standard */ -static SPSVGColor const sp_svg_color_named[] = { - { 0xF0F8FF, "aliceblue" }, - { 0xFAEBD7, "antiquewhite" }, - { 0x00FFFF, "aqua" }, - { 0x7FFFD4, "aquamarine" }, - { 0xF0FFFF, "azure" }, - { 0xF5F5DC, "beige" }, - { 0xFFE4C4, "bisque" }, - { 0x000000, "black" }, - { 0xFFEBCD, "blanchedalmond" }, - { 0x0000FF, "blue" }, - { 0x8A2BE2, "blueviolet" }, - { 0xA52A2A, "brown" }, - { 0xDEB887, "burlywood" }, - { 0x5F9EA0, "cadetblue" }, - { 0x7FFF00, "chartreuse" }, - { 0xD2691E, "chocolate" }, - { 0xFF7F50, "coral" }, - { 0x6495ED, "cornflowerblue" }, - { 0xFFF8DC, "cornsilk" }, - { 0xDC143C, "crimson" }, - { 0x00FFFF, "cyan" }, - { 0x00008B, "darkblue" }, - { 0x008B8B, "darkcyan" }, - { 0xB8860B, "darkgoldenrod" }, - { 0xA9A9A9, "darkgray" }, - { 0x006400, "darkgreen" }, - { 0xA9A9A9, "darkgrey" }, - { 0xBDB76B, "darkkhaki" }, - { 0x8B008B, "darkmagenta" }, - { 0x556B2F, "darkolivegreen" }, - { 0xFF8C00, "darkorange" }, - { 0x9932CC, "darkorchid" }, - { 0x8B0000, "darkred" }, - { 0xE9967A, "darksalmon" }, - { 0x8FBC8F, "darkseagreen" }, - { 0x483D8B, "darkslateblue" }, - { 0x2F4F4F, "darkslategray" }, - { 0x2F4F4F, "darkslategrey" }, - { 0x00CED1, "darkturquoise" }, - { 0x9400D3, "darkviolet" }, - { 0xFF1493, "deeppink" }, - { 0x00BFFF, "deepskyblue" }, - { 0x696969, "dimgray" }, - { 0x696969, "dimgrey" }, - { 0x1E90FF, "dodgerblue" }, - { 0xB22222, "firebrick" }, - { 0xFFFAF0, "floralwhite" }, - { 0x228B22, "forestgreen" }, - { 0xFF00FF, "fuchsia" }, - { 0xDCDCDC, "gainsboro" }, - { 0xF8F8FF, "ghostwhite" }, - { 0xFFD700, "gold" }, - { 0xDAA520, "goldenrod" }, - { 0x808080, "gray" }, - { 0x808080, "grey" }, - { 0x008000, "green" }, - { 0xADFF2F, "greenyellow" }, - { 0xF0FFF0, "honeydew" }, - { 0xFF69B4, "hotpink" }, - { 0xCD5C5C, "indianred" }, - { 0x4B0082, "indigo" }, - { 0xFFFFF0, "ivory" }, - { 0xF0E68C, "khaki" }, - { 0xE6E6FA, "lavender" }, - { 0xFFF0F5, "lavenderblush" }, - { 0x7CFC00, "lawngreen" }, - { 0xFFFACD, "lemonchiffon" }, - { 0xADD8E6, "lightblue" }, - { 0xF08080, "lightcoral" }, - { 0xE0FFFF, "lightcyan" }, - { 0xFAFAD2, "lightgoldenrodyellow" }, - { 0xD3D3D3, "lightgray" }, - { 0x90EE90, "lightgreen" }, - { 0xD3D3D3, "lightgrey" }, - { 0xFFB6C1, "lightpink" }, - { 0xFFA07A, "lightsalmon" }, - { 0x20B2AA, "lightseagreen" }, - { 0x87CEFA, "lightskyblue" }, - { 0x778899, "lightslategray" }, - { 0x778899, "lightslategrey" }, - { 0xB0C4DE, "lightsteelblue" }, - { 0xFFFFE0, "lightyellow" }, - { 0x00FF00, "lime" }, - { 0x32CD32, "limegreen" }, - { 0xFAF0E6, "linen" }, - { 0xFF00FF, "magenta" }, - { 0x800000, "maroon" }, - { 0x66CDAA, "mediumaquamarine" }, - { 0x0000CD, "mediumblue" }, - { 0xBA55D3, "mediumorchid" }, - { 0x9370DB, "mediumpurple" }, - { 0x3CB371, "mediumseagreen" }, - { 0x7B68EE, "mediumslateblue" }, - { 0x00FA9A, "mediumspringgreen" }, - { 0x48D1CC, "mediumturquoise" }, - { 0xC71585, "mediumvioletred" }, - { 0x191970, "midnightblue" }, - { 0xF5FFFA, "mintcream" }, - { 0xFFE4E1, "mistyrose" }, - { 0xFFE4B5, "moccasin" }, - { 0xFFDEAD, "navajowhite" }, - { 0x000080, "navy" }, - { 0xFDF5E6, "oldlace" }, - { 0x808000, "olive" }, - { 0x6B8E23, "olivedrab" }, - { 0xFFA500, "orange" }, - { 0xFF4500, "orangered" }, - { 0xDA70D6, "orchid" }, - { 0xEEE8AA, "palegoldenrod" }, - { 0x98FB98, "palegreen" }, - { 0xAFEEEE, "paleturquoise" }, - { 0xDB7093, "palevioletred" }, - { 0xFFEFD5, "papayawhip" }, - { 0xFFDAB9, "peachpuff" }, - { 0xCD853F, "peru" }, - { 0xFFC0CB, "pink" }, - { 0xDDA0DD, "plum" }, - { 0xB0E0E6, "powderblue" }, - { 0x800080, "purple" }, - { 0x663399, "rebeccapurple" }, - { 0xFF0000, "red" }, - { 0xBC8F8F, "rosybrown" }, - { 0x4169E1, "royalblue" }, - { 0x8B4513, "saddlebrown" }, - { 0xFA8072, "salmon" }, - { 0xF4A460, "sandybrown" }, - { 0x2E8B57, "seagreen" }, - { 0xFFF5EE, "seashell" }, - { 0xA0522D, "sienna" }, - { 0xC0C0C0, "silver" }, - { 0x87CEEB, "skyblue" }, - { 0x6A5ACD, "slateblue" }, - { 0x708090, "slategray" }, - { 0x708090, "slategrey" }, - { 0xFFFAFA, "snow" }, - { 0x00FF7F, "springgreen" }, - { 0x4682B4, "steelblue" }, - { 0xD2B48C, "tan" }, - { 0x008080, "teal" }, - { 0xD8BFD8, "thistle" }, - { 0xFF6347, "tomato" }, - { 0x40E0D0, "turquoise" }, - { 0xEE82EE, "violet" }, - { 0xF5DEB3, "wheat" }, - { 0xFFFFFF, "white" }, - { 0xF5F5F5, "whitesmoke" }, - { 0xFFFF00, "yellow" }, - { 0x9ACD32, "yellowgreen" } -}; +static SPSVGColor const sp_svg_color_named[] = {{0xF0F8FF, "aliceblue"}, + {0xFAEBD7, "antiquewhite"}, + {0x00FFFF, "aqua"}, + {0x7FFFD4, "aquamarine"}, + {0xF0FFFF, "azure"}, + {0xF5F5DC, "beige"}, + {0xFFE4C4, "bisque"}, + {0x000000, "black"}, + {0xFFEBCD, "blanchedalmond"}, + {0x0000FF, "blue"}, + {0x8A2BE2, "blueviolet"}, + {0xA52A2A, "brown"}, + {0xDEB887, "burlywood"}, + {0x5F9EA0, "cadetblue"}, + {0x7FFF00, "chartreuse"}, + {0xD2691E, "chocolate"}, + {0xFF7F50, "coral"}, + {0x6495ED, "cornflowerblue"}, + {0xFFF8DC, "cornsilk"}, + {0xDC143C, "crimson"}, + {0x00FFFF, "cyan"}, + {0x00008B, "darkblue"}, + {0x008B8B, "darkcyan"}, + {0xB8860B, "darkgoldenrod"}, + {0xA9A9A9, "darkgray"}, + {0x006400, "darkgreen"}, + {0xA9A9A9, "darkgrey"}, + {0xBDB76B, "darkkhaki"}, + {0x8B008B, "darkmagenta"}, + {0x556B2F, "darkolivegreen"}, + {0xFF8C00, "darkorange"}, + {0x9932CC, "darkorchid"}, + {0x8B0000, "darkred"}, + {0xE9967A, "darksalmon"}, + {0x8FBC8F, "darkseagreen"}, + {0x483D8B, "darkslateblue"}, + {0x2F4F4F, "darkslategray"}, + {0x2F4F4F, "darkslategrey"}, + {0x00CED1, "darkturquoise"}, + {0x9400D3, "darkviolet"}, + {0xFF1493, "deeppink"}, + {0x00BFFF, "deepskyblue"}, + {0x696969, "dimgray"}, + {0x696969, "dimgrey"}, + {0x1E90FF, "dodgerblue"}, + {0xB22222, "firebrick"}, + {0xFFFAF0, "floralwhite"}, + {0x228B22, "forestgreen"}, + {0xFF00FF, "fuchsia"}, + {0xDCDCDC, "gainsboro"}, + {0xF8F8FF, "ghostwhite"}, + {0xFFD700, "gold"}, + {0xDAA520, "goldenrod"}, + {0x808080, "gray"}, + {0x808080, "grey"}, + {0x008000, "green"}, + {0xADFF2F, "greenyellow"}, + {0xF0FFF0, "honeydew"}, + {0xFF69B4, "hotpink"}, + {0xCD5C5C, "indianred"}, + {0x4B0082, "indigo"}, + {0xFFFFF0, "ivory"}, + {0xF0E68C, "khaki"}, + {0xE6E6FA, "lavender"}, + {0xFFF0F5, "lavenderblush"}, + {0x7CFC00, "lawngreen"}, + {0xFFFACD, "lemonchiffon"}, + {0xADD8E6, "lightblue"}, + {0xF08080, "lightcoral"}, + {0xE0FFFF, "lightcyan"}, + {0xFAFAD2, "lightgoldenrodyellow"}, + {0xD3D3D3, "lightgray"}, + {0x90EE90, "lightgreen"}, + {0xD3D3D3, "lightgrey"}, + {0xFFB6C1, "lightpink"}, + {0xFFA07A, "lightsalmon"}, + {0x20B2AA, "lightseagreen"}, + {0x87CEFA, "lightskyblue"}, + {0x778899, "lightslategray"}, + {0x778899, "lightslategrey"}, + {0xB0C4DE, "lightsteelblue"}, + {0xFFFFE0, "lightyellow"}, + {0x00FF00, "lime"}, + {0x32CD32, "limegreen"}, + {0xFAF0E6, "linen"}, + {0xFF00FF, "magenta"}, + {0x800000, "maroon"}, + {0x66CDAA, "mediumaquamarine"}, + {0x0000CD, "mediumblue"}, + {0xBA55D3, "mediumorchid"}, + {0x9370DB, "mediumpurple"}, + {0x3CB371, "mediumseagreen"}, + {0x7B68EE, "mediumslateblue"}, + {0x00FA9A, "mediumspringgreen"}, + {0x48D1CC, "mediumturquoise"}, + {0xC71585, "mediumvioletred"}, + {0x191970, "midnightblue"}, + {0xF5FFFA, "mintcream"}, + {0xFFE4E1, "mistyrose"}, + {0xFFE4B5, "moccasin"}, + {0xFFDEAD, "navajowhite"}, + {0x000080, "navy"}, + {0xFDF5E6, "oldlace"}, + {0x808000, "olive"}, + {0x6B8E23, "olivedrab"}, + {0xFFA500, "orange"}, + {0xFF4500, "orangered"}, + {0xDA70D6, "orchid"}, + {0xEEE8AA, "palegoldenrod"}, + {0x98FB98, "palegreen"}, + {0xAFEEEE, "paleturquoise"}, + {0xDB7093, "palevioletred"}, + {0xFFEFD5, "papayawhip"}, + {0xFFDAB9, "peachpuff"}, + {0xCD853F, "peru"}, + {0xFFC0CB, "pink"}, + {0xDDA0DD, "plum"}, + {0xB0E0E6, "powderblue"}, + {0x800080, "purple"}, + {0x663399, "rebeccapurple"}, + {0xFF0000, "red"}, + {0xBC8F8F, "rosybrown"}, + {0x4169E1, "royalblue"}, + {0x8B4513, "saddlebrown"}, + {0xFA8072, "salmon"}, + {0xF4A460, "sandybrown"}, + {0x2E8B57, "seagreen"}, + {0xFFF5EE, "seashell"}, + {0xA0522D, "sienna"}, + {0xC0C0C0, "silver"}, + {0x87CEEB, "skyblue"}, + {0x6A5ACD, "slateblue"}, + {0x708090, "slategray"}, + {0x708090, "slategrey"}, + {0xFFFAFA, "snow"}, + {0x00FF7F, "springgreen"}, + {0x4682B4, "steelblue"}, + {0xD2B48C, "tan"}, + {0x008080, "teal"}, + {0xD8BFD8, "thistle"}, + {0xFF6347, "tomato"}, + {0x40E0D0, "turquoise"}, + {0xEE82EE, "violet"}, + {0xF5DEB3, "wheat"}, + {0xFFFFFF, "white"}, + {0xF5F5F5, "whitesmoke"}, + {0xFFFF00, "yellow"}, + {0x9ACD32, "yellowgreen"}}; static std::map<std::string, unsigned long> sp_svg_create_color_hash(); @@ -216,9 +213,12 @@ static guint32 internal_sp_svg_read_color(gchar const *str, gchar const **end_pt static std::map<std::string, unsigned long> colors; guint32 val = 0; - if (str == nullptr) return def; - while ((*str <= ' ') && *str) str++; - if (!*str) return def; + if (str == nullptr) + return def; + while ((*str <= ' ') && *str) + str++; + if (!*str) + return def; if (str[0] == '#') { gint i; @@ -236,9 +236,7 @@ static guint32 internal_sp_svg_read_color(gchar const *str, gchar const **end_pt } /* handle #rgb case */ if (i == 1 + 3) { - val = ((val & 0xf00) << 8) | - ((val & 0x0f0) << 4) | - (val & 0x00f); + val = ((val & 0xf00) << 8) | ((val & 0x0f0) << 4) | (val & 0x00f); val |= val << 4; } else if (i != 1 + 6) { /* must be either 3 or 6 digits. */ @@ -252,12 +250,13 @@ static guint32 internal_sp_svg_read_color(gchar const *str, gchar const **end_pt gchar *s, *e; gdouble r, g, b; - s = (gchar *) str + 4; + s = (gchar *)str + 4; hasp = false; hasd = false; r = g_ascii_strtod(s, &e); - if (s == e) return def; + if (s == e) + return def; s = e; if (*s == '%') { hasp = true; @@ -265,12 +264,16 @@ static guint32 internal_sp_svg_read_color(gchar const *str, gchar const **end_pt } else { hasd = true; } - while (*s && g_ascii_isspace(*s)) s += 1; - if (*s != ',') return def; + while (*s && g_ascii_isspace(*s)) + s += 1; + if (*s != ',') + return def; s += 1; - while (*s && g_ascii_isspace(*s)) s += 1; + while (*s && g_ascii_isspace(*s)) + s += 1; g = g_ascii_strtod(s, &e); - if (s == e) return def; + if (s == e) + return def; s = e; if (*s == '%') { hasp = true; @@ -278,12 +281,16 @@ static guint32 internal_sp_svg_read_color(gchar const *str, gchar const **end_pt } else { hasd = true; } - while (*s && g_ascii_isspace(*s)) s += 1; - if (*s != ',') return def; + while (*s && g_ascii_isspace(*s)) + s += 1; + if (*s != ',') + return def; s += 1; - while (*s && g_ascii_isspace(*s)) s += 1; + while (*s && g_ascii_isspace(*s)) + s += 1; b = g_ascii_strtod(s, &e); - if (s == e) return def; + if (s == e) + return def; s = e; if (*s == '%') { hasp = true; @@ -291,12 +298,14 @@ static guint32 internal_sp_svg_read_color(gchar const *str, gchar const **end_pt } else { hasd = true; } - while(*s && g_ascii_isspace(*s)) s += 1; + while (*s && g_ascii_isspace(*s)) + s += 1; if (*s != ')') { return def; } ++s; - if (hasp && hasd) return def; + if (hasp && hasd) + return def; if (hasp) { val = static_cast<guint>(floor(CLAMP(r, 0.0, 100.0) * 2.559999)) << 24; val |= (static_cast<guint>(floor(CLAMP(g, 0.0, 100.0) * 2.559999)) << 16); @@ -311,44 +320,55 @@ static guint32 internal_sp_svg_read_color(gchar const *str, gchar const **end_pt } return val; } else if (strneq(str, "hsl(", 4)) { - - gchar *ptr = (gchar *) str + 4; + gchar *ptr = (gchar *)str + 4; gchar *e; // ptr after read double h = g_ascii_strtod(ptr, &e); // Read h (0-360) - if (ptr == e) return def; // Read failed + if (ptr == e) + return def; // Read failed ptr = e; - while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space - if (*ptr != ',') return def; // Need comma + while (*ptr && g_ascii_isspace(*ptr)) + ptr += 1; // Remove any white space + if (*ptr != ',') + return def; // Need comma ptr += 1; - while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space + while (*ptr && g_ascii_isspace(*ptr)) + ptr += 1; // Remove any white space double s = g_ascii_strtod(ptr, &e); // Read s (percent) - if (ptr == e) return def; // Read failed + if (ptr == e) + return def; // Read failed ptr = e; - while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space - if (*ptr != '%') return def; // Need % + while (*ptr && g_ascii_isspace(*ptr)) + ptr += 1; // Remove any white space + if (*ptr != '%') + return def; // Need % ptr += 1; - while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space - if (*ptr != ',') return def; // Need comma + while (*ptr && g_ascii_isspace(*ptr)) + ptr += 1; // Remove any white space + if (*ptr != ',') + return def; // Need comma ptr += 1; - while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space + while (*ptr && g_ascii_isspace(*ptr)) + ptr += 1; // Remove any white space double l = g_ascii_strtod(ptr, &e); // Read l (percent) - if (ptr == e) return def; // Read failed + if (ptr == e) + return def; // Read failed ptr = e; - while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space - if (*ptr != '%') return def; // Need % + while (*ptr && g_ascii_isspace(*ptr)) + ptr += 1; // Remove any white space + if (*ptr != '%') + return def; // Need % ptr += 1; if (end_ptr) { *end_ptr = ptr; } - // Normalize to 0..1 h /= 360.0; s /= 100.0; @@ -356,9 +376,9 @@ static guint32 internal_sp_svg_read_color(gchar const *str, gchar const **end_pt gfloat rgb[3]; - SPColor::hsl_to_rgb_floatv( rgb, h, s, l ); + SPColor::hsl_to_rgb_floatv(rgb, h, s, l); - val = static_cast<guint>(floor(CLAMP(rgb[0], 0.0, 1.0) * 255.9999)) << 24; + val = static_cast<guint>(floor(CLAMP(rgb[0], 0.0, 1.0) * 255.9999)) << 24; val |= (static_cast<guint>(floor(CLAMP(rgb[1], 0.0, 1.0) * 255.9999)) << 16); val |= (static_cast<guint>(floor(CLAMP(rgb[2], 0.0, 1.0) * 255.9999)) << 8); return val; @@ -375,14 +395,14 @@ static guint32 internal_sp_svg_read_color(gchar const *str, gchar const **end_pt break; } c[i] = g_ascii_tolower(str[i]); - if (!str[i]) break; + if (!str[i]) + break; } c[31] = '\0'; if (colors.count(std::string(c))) { val = colors[std::string(c)]; - } - else { + } else { return def; } if (end_ptr) { @@ -399,27 +419,23 @@ guint32 sp_svg_read_color(gchar const *str, gchar const **end_ptr, guint32 dfl) * this check wrapper. */ gchar const *end = str; guint32 const ret = internal_sp_svg_read_color(str, &end, dfl); - g_assert(((ret == dfl) && (end == str)) - || (((ret & 0xff) == 0) - && (str < end))); + g_assert(((ret == dfl) && (end == str)) || (((ret & 0xff) == 0) && (str < end))); if (str < end) { - gchar *buf = (gchar *) g_malloc(end + 1 - str); + gchar *buf = (gchar *)g_malloc(end + 1 - str); memcpy(buf, str, end - str); buf[end - str] = '\0'; gchar const *buf_end = buf; guint32 const check = internal_sp_svg_read_color(buf, &buf_end, 1); - g_assert(check == ret - && buf_end - buf == end - str); + g_assert(check == ret && buf_end - buf == end - str); g_free(buf); - if ( end_ptr ) { + if (end_ptr) { *end_ptr = end; } } return ret; } - /** * Converts an RGB colour expressed in form 0x00rrggbb to a CSS/SVG representation of that colour. * The result is valid even in SVG Tiny or non-SVG CSS. @@ -439,30 +455,59 @@ static void rgb24_to_css(char *const buf, unsigned const rgb24) switch (rgb24) { /* Extracted mechanically from the table at * http://www.w3.org/TR/REC-html40/types.html#h-6.5 .*/ - case 0x000000: src = "black"; break; - case 0xc0c0c0: src = "silver"; break; - case 0x808080: src = "gray"; break; - case 0xffffff: src = "white"; break; - case 0x800000: src = "maroon"; break; - case 0xff0000: src = "red"; break; - case 0x800080: src = "purple"; break; - case 0xff00ff: src = "fuchsia"; break; - case 0x008000: src = "green"; break; - case 0x00ff00: src = "lime"; break; - case 0x808000: src = "olive"; break; - case 0xffff00: src = "yellow"; break; - case 0x000080: src = "navy"; break; - case 0x0000ff: src = "blue"; break; - case 0x008080: src = "teal"; break; - case 0x00ffff: src = "aqua"; break; + case 0x000000: + src = "black"; + break; + case 0xc0c0c0: + src = "silver"; + break; + case 0x808080: + src = "gray"; + break; + case 0xffffff: + src = "white"; + break; + case 0x800000: + src = "maroon"; + break; + case 0xff0000: + src = "red"; + break; + case 0x800080: + src = "purple"; + break; + case 0xff00ff: + src = "fuchsia"; + break; + case 0x008000: + src = "green"; + break; + case 0x00ff00: + src = "lime"; + break; + case 0x808000: + src = "olive"; + break; + case 0xffff00: + src = "yellow"; + break; + case 0x000080: + src = "navy"; + break; + case 0x0000ff: + src = "blue"; + break; + case 0x008080: + src = "teal"; + break; + case 0x00ffff: + src = "aqua"; + break; default: { if ((rgb24 & 0xf0f0f) * 0x11 == rgb24) { /* Can use the shorter three-digit form #rgb instead of #rrggbb. */ - std::sprintf(buf, "#%x%x%x", - (rgb24 >> 16) & 0xf, - (rgb24 >> 8) & 0xf, - rgb24 & 0xf); + std::sprintf(buf, "#%x%x%x", (rgb24 >> 16) & 0xf, (rgb24 >> 8) & 0xf, rgb24 & 0xf); } else { std::sprintf(buf, "#%06x", rgb24); } @@ -489,20 +534,19 @@ void sp_svg_write_color(gchar *buf, unsigned const buflen, guint32 const rgba32) Inkscape::Preferences *prefs = Inkscape::Preferences::get(); unsigned const rgb24 = rgba32 >> 8; - if ( prefs->getBool("/options/svgoutput/usenamedcolors") && - !prefs->getBool("/options/svgoutput/disable_optimizations" )) { + if (prefs->getBool("/options/svgoutput/usenamedcolors") && + !prefs->getBool("/options/svgoutput/disable_optimizations")) { rgb24_to_css(buf, rgb24); } else { g_snprintf(buf, buflen, "#%06x", rgb24); } } -static std::map<std::string, unsigned long> -sp_svg_create_color_hash() +static std::map<std::string, unsigned long> sp_svg_create_color_hash() { std::map<std::string, unsigned long> colors; - for (const auto & i : sp_svg_color_named) { + for (const auto &i : sp_svg_color_named) { colors[i.name] = i.rgb; } return colors; @@ -510,18 +554,18 @@ sp_svg_create_color_hash() #if defined(HAVE_LIBLCMS2) -void icc_color_to_sRGB(SVGICCColor* icc, guchar* r, guchar* g, guchar* b) +void icc_color_to_sRGB(SVGICCColor *icc, guchar *r, guchar *g, guchar *b) { if (icc) { g_message("profile name: %s", icc->colorProfile.c_str()); - Inkscape::ColorProfile* prof = SP_ACTIVE_DOCUMENT->getProfileManager()->find(icc->colorProfile.c_str()); - if ( prof ) { - guchar color_out[4] = {0,0,0,0}; + Inkscape::ColorProfile *prof = SP_ACTIVE_DOCUMENT->getProfileManager()->find(icc->colorProfile.c_str()); + if (prof) { + guchar color_out[4] = {0, 0, 0, 0}; cmsHTRANSFORM trans = prof->getTransfToSRGB8(); - if ( trans ) { - std::vector<colorspace::Component> comps = colorspace::getColorSpaceInfo( prof ); + if (trans) { + std::vector<colorspace::Component> comps = colorspace::getColorSpaceInfo(prof); - size_t count = Inkscape::CMSSystem::getChannelCount( prof ); + size_t count = Inkscape::CMSSystem::getChannelCount(prof); size_t cap = std::min(count, comps.size()); guchar color_in[4]; for (size_t i = 0; i < cap; i++) { @@ -529,8 +573,8 @@ void icc_color_to_sRGB(SVGICCColor* icc, guchar* r, guchar* g, guchar* b) g_message("input[%d]: %d", (int)i, (int)color_in[i]); } - Inkscape::CMSSystem::doTransform( trans, color_in, color_out, 1 ); -g_message("transform to sRGB done"); + Inkscape::CMSSystem::doTransform(trans, color_in, color_out, 1); + g_message("transform to sRGB done"); } *r = color_out[0]; *g = color_out[1]; @@ -538,69 +582,66 @@ g_message("transform to sRGB done"); } } } -#endif //defined(HAVE_LIBLCMS2) +#endif // defined(HAVE_LIBLCMS2) /* * Some discussion at http://markmail.org/message/bhfvdfptt25kgtmj * Allowed ASCII first characters: ':', 'A'-'Z', '_', 'a'-'z' * Allowed ASCII remaining chars add: '-', '.', '0'-'9', */ -bool sp_svg_read_icc_color( gchar const *str, gchar const **end_ptr, SVGICCColor* dest ) +bool sp_svg_read_icc_color(gchar const *str, gchar const **end_ptr, SVGICCColor *dest) { bool good = true; - if ( end_ptr ) { + if (end_ptr) { *end_ptr = str; } - if ( dest ) { + if (dest) { dest->colorProfile.clear(); dest->colors.clear(); } - if ( !str ) { + if (!str) { // invalid input good = false; } else { - while ( g_ascii_isspace(*str) ) { + while (g_ascii_isspace(*str)) { str++; } - good = strneq( str, "icc-color(", 10 ); + good = strneq(str, "icc-color(", 10); - if ( good ) { + if (good) { str += 10; - while ( g_ascii_isspace(*str) ) { + while (g_ascii_isspace(*str)) { str++; } - if ( !g_ascii_isalpha(*str) - && ( !(0x080 & *str) ) - && (*str != '_') - && (*str != ':') ) { + if (!g_ascii_isalpha(*str) && (!(0x080 & *str)) && (*str != '_') && (*str != ':')) { // Name must start with a certain type of character good = false; } else { - while ( g_ascii_isdigit(*str) || g_ascii_isalpha(*str) - || (*str == '-') || (*str == ':') || (*str == '_') || (*str == '.') ) { - if ( dest ) { + while (g_ascii_isdigit(*str) || g_ascii_isalpha(*str) || (*str == '-') || (*str == ':') || + (*str == '_') || (*str == '.')) { + if (dest) { dest->colorProfile += *str; } str++; } - while ( g_ascii_isspace(*str) || *str == ',' ) { + while (g_ascii_isspace(*str) || *str == ',') { str++; } } } - if ( good ) { - while ( *str && *str != ')' ) { - if ( g_ascii_isdigit(*str) || *str == '.' || *str == '-' || *str == '+') { - gchar* endPtr = nullptr; - gdouble dbl = g_ascii_strtod( str, &endPtr ); - if ( !errno ) { - if ( dest ) { - dest->colors.push_back( dbl ); + if (good) { + while (*str && *str != ')') { + if (g_ascii_isdigit(*str) || *str == '.' || *str == '-' || *str == '+') { + gchar *endPtr = nullptr; + gdouble dbl = g_ascii_strtod(str, &endPtr); + if (!errno) { + if (dest) { + dest->colors.push_back(dbl); } str = endPtr; } else { @@ -608,7 +649,7 @@ bool sp_svg_read_icc_color( gchar const *str, gchar const **end_ptr, SVGICCColor break; } - while ( g_ascii_isspace(*str) || *str == ',' ) { + while (g_ascii_isspace(*str) || *str == ',') { str++; } } else { @@ -618,20 +659,20 @@ bool sp_svg_read_icc_color( gchar const *str, gchar const **end_ptr, SVGICCColor } // We need to have ended on a closing parenthesis - if ( good ) { - while ( g_ascii_isspace(*str) ) { + if (good) { + while (g_ascii_isspace(*str)) { str++; } good &= (*str == ')'); } } - if ( good ) { - if ( end_ptr ) { + if (good) { + if (end_ptr) { *end_ptr = str; } } else { - if ( dest ) { + if (dest) { dest->colorProfile.clear(); dest->colors.clear(); } @@ -640,13 +681,11 @@ bool sp_svg_read_icc_color( gchar const *str, gchar const **end_ptr, SVGICCColor return good; } - -bool sp_svg_read_icc_color( gchar const *str, SVGICCColor* dest ) +bool sp_svg_read_icc_color(gchar const *str, SVGICCColor *dest) { return sp_svg_read_icc_color(str, nullptr, dest); } - /* Local Variables: mode:c++ diff --git a/src/svg/svg-color.h b/src/svg/svg-color.h index 6b1cc02a91be970dce503d4cf6faa78fd174d162..d77054bdae479457fa7cba0c3dc6a883cdef0531 100644 --- a/src/svg/svg-color.h +++ b/src/svg/svg-color.h @@ -17,8 +17,8 @@ guint32 sp_svg_read_color(char const *str, unsigned int dfl); guint32 sp_svg_read_color(char const *str, char const **end_ptr, guint32 def); void sp_svg_write_color(char *buf, unsigned int buflen, unsigned int rgba32); -bool sp_svg_read_icc_color( char const *str, char const **end_ptr, SVGICCColor* dest ); -bool sp_svg_read_icc_color( char const *str, SVGICCColor* dest ); -void icc_color_to_sRGB(SVGICCColor* dest, unsigned char* r, unsigned char* g, unsigned char* b); +bool sp_svg_read_icc_color(char const *str, char const **end_ptr, SVGICCColor *dest); +bool sp_svg_read_icc_color(char const *str, SVGICCColor *dest); +void icc_color_to_sRGB(SVGICCColor *dest, unsigned char *r, unsigned char *g, unsigned char *b); #endif /* !SVG_SVG_COLOR_H_SEEN */ diff --git a/src/svg/svg-icc-color.h b/src/svg/svg-icc-color.h index 2a1f89ef7d5cb72740e7485dcb5937e38df3b675..abd6918a8196883f2dc946d30de417d3380510ac 100644 --- a/src/svg/svg-icc-color.h +++ b/src/svg/svg-icc-color.h @@ -18,12 +18,12 @@ * * Referenced by SPIPaint. */ -struct SVGICCColor { +struct SVGICCColor +{ std::string colorProfile; std::vector<double> colors; }; - #endif /* !SVG_ICC_COLOR_H_SEEN */ /* diff --git a/src/svg/svg-length-test.h b/src/svg/svg-length-test.h index da73d9ce291506774faccea06eef145477691480..81caad9db08e76421c8cf9975bb6c8c0fe4808ac 100644 --- a/src/svg/svg-length-test.h +++ b/src/svg/svg-length-test.h @@ -8,111 +8,118 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include <cxxtest/TestSuite.h> - -#include "svg/svg-length.h" #include <glib.h> #include <utility> +#include "svg/svg-length.h" + // function internal to svg-length.cpp: gchar const *sp_svg_length_get_css_units(SVGLength::Unit unit); class SvgLengthTest : public CxxTest::TestSuite { private: - struct test_t { - char const* str; SVGLength::Unit unit; float value; float computed; + struct test_t + { + char const *str; + SVGLength::Unit unit; + float value; + float computed; }; - struct testd_t { - char const* str; double val; int prec; int minexp; + struct testd_t + { + char const *str; + double val; + int prec; + int minexp; }; static test_t const absolute_tests[12]; static test_t const relative_tests[3]; - static char const * fail_tests[8]; + static char const *fail_tests[8]; public: - SvgLengthTest() { - } + SvgLengthTest() {} -// createSuite and destroySuite get us per-suite setup and teardown -// without us having to worry about static initialization order, etc. + // createSuite and destroySuite get us per-suite setup and teardown + // without us having to worry about static initialization order, etc. static SvgLengthTest *createSuite() { return new SvgLengthTest(); } - static void destroySuite( SvgLengthTest *suite ) { delete suite; } + static void destroySuite(SvgLengthTest *suite) { delete suite; } void testRead() { - for(size_t i=0; i<G_N_ELEMENTS(absolute_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(absolute_tests); i++) { SVGLength len; - TSM_ASSERT(absolute_tests[i].str , len.read(absolute_tests[i].str)); - TSM_ASSERT_EQUALS(absolute_tests[i].str , len.unit , absolute_tests[i].unit); - TSM_ASSERT_EQUALS(absolute_tests[i].str , len.value , absolute_tests[i].value); - TSM_ASSERT_EQUALS(absolute_tests[i].str , len.computed , absolute_tests[i].computed); + TSM_ASSERT(absolute_tests[i].str, len.read(absolute_tests[i].str)); + TSM_ASSERT_EQUALS(absolute_tests[i].str, len.unit, absolute_tests[i].unit); + TSM_ASSERT_EQUALS(absolute_tests[i].str, len.value, absolute_tests[i].value); + TSM_ASSERT_EQUALS(absolute_tests[i].str, len.computed, absolute_tests[i].computed); } - for(size_t i=0; i<G_N_ELEMENTS(relative_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(relative_tests); i++) { SVGLength len; - TSM_ASSERT(relative_tests[i].str , len.read(relative_tests[i].str)); - len.update(7,13,19); - TSM_ASSERT_EQUALS(relative_tests[i].str , len.unit , relative_tests[i].unit); - TSM_ASSERT_EQUALS(relative_tests[i].str , len.value , relative_tests[i].value); - TSM_ASSERT_EQUALS(relative_tests[i].str , len.computed , relative_tests[i].computed); + TSM_ASSERT(relative_tests[i].str, len.read(relative_tests[i].str)); + len.update(7, 13, 19); + TSM_ASSERT_EQUALS(relative_tests[i].str, len.unit, relative_tests[i].unit); + TSM_ASSERT_EQUALS(relative_tests[i].str, len.value, relative_tests[i].value); + TSM_ASSERT_EQUALS(relative_tests[i].str, len.computed, relative_tests[i].computed); } - for(size_t i=0; i<G_N_ELEMENTS(fail_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(fail_tests); i++) { SVGLength len; - TSM_ASSERT(fail_tests[i] , !len.read(fail_tests[i])); + TSM_ASSERT(fail_tests[i], !len.read(fail_tests[i])); } } void testReadOrUnset() { - for(size_t i=0; i<G_N_ELEMENTS(absolute_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(absolute_tests); i++) { SVGLength len; len.readOrUnset(absolute_tests[i].str); - TSM_ASSERT_EQUALS(absolute_tests[i].str , len.unit , absolute_tests[i].unit); - TSM_ASSERT_EQUALS(absolute_tests[i].str , len.value , absolute_tests[i].value); - TSM_ASSERT_EQUALS(absolute_tests[i].str , len.computed , absolute_tests[i].computed); + TSM_ASSERT_EQUALS(absolute_tests[i].str, len.unit, absolute_tests[i].unit); + TSM_ASSERT_EQUALS(absolute_tests[i].str, len.value, absolute_tests[i].value); + TSM_ASSERT_EQUALS(absolute_tests[i].str, len.computed, absolute_tests[i].computed); } - for(size_t i=0; i<G_N_ELEMENTS(relative_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(relative_tests); i++) { SVGLength len; len.readOrUnset(relative_tests[i].str); - len.update(7,13,19); - TSM_ASSERT_EQUALS(relative_tests[i].str , len.unit , relative_tests[i].unit); - TSM_ASSERT_EQUALS(relative_tests[i].str , len.value , relative_tests[i].value); - TSM_ASSERT_EQUALS(relative_tests[i].str , len.computed , relative_tests[i].computed); + len.update(7, 13, 19); + TSM_ASSERT_EQUALS(relative_tests[i].str, len.unit, relative_tests[i].unit); + TSM_ASSERT_EQUALS(relative_tests[i].str, len.value, relative_tests[i].value); + TSM_ASSERT_EQUALS(relative_tests[i].str, len.computed, relative_tests[i].computed); } - for(size_t i=0; i<G_N_ELEMENTS(fail_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(fail_tests); i++) { SVGLength len; len.readOrUnset(fail_tests[i], SVGLength::INCH, 123, 456); - TSM_ASSERT_EQUALS(fail_tests[i] , len.unit , SVGLength::INCH); - TSM_ASSERT_EQUALS(fail_tests[i] , len.value , 123); - TSM_ASSERT_EQUALS(fail_tests[i] , len.computed , 456); + TSM_ASSERT_EQUALS(fail_tests[i], len.unit, SVGLength::INCH); + TSM_ASSERT_EQUALS(fail_tests[i], len.value, 123); + TSM_ASSERT_EQUALS(fail_tests[i], len.computed, 456); } } void testReadAbsolute() { - for(size_t i=0; i<G_N_ELEMENTS(absolute_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(absolute_tests); i++) { SVGLength len; - TSM_ASSERT(absolute_tests[i].str , len.readAbsolute(absolute_tests[i].str)); - TSM_ASSERT_EQUALS(absolute_tests[i].str , len.unit , absolute_tests[i].unit); - TSM_ASSERT_EQUALS(absolute_tests[i].str , len.value , absolute_tests[i].value); - TSM_ASSERT_EQUALS(absolute_tests[i].str , len.computed , absolute_tests[i].computed); + TSM_ASSERT(absolute_tests[i].str, len.readAbsolute(absolute_tests[i].str)); + TSM_ASSERT_EQUALS(absolute_tests[i].str, len.unit, absolute_tests[i].unit); + TSM_ASSERT_EQUALS(absolute_tests[i].str, len.value, absolute_tests[i].value); + TSM_ASSERT_EQUALS(absolute_tests[i].str, len.computed, absolute_tests[i].computed); } - for(size_t i=0; i<G_N_ELEMENTS(relative_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(relative_tests); i++) { SVGLength len; - TSM_ASSERT(relative_tests[i].str , !len.readAbsolute(relative_tests[i].str)); + TSM_ASSERT(relative_tests[i].str, !len.readAbsolute(relative_tests[i].str)); } - for(size_t i=0; i<G_N_ELEMENTS(fail_tests); i++) { + for (size_t i = 0; i < G_N_ELEMENTS(fail_tests); i++) { SVGLength len; - TSM_ASSERT(fail_tests[i] , !len.readAbsolute(fail_tests[i])); + TSM_ASSERT(fail_tests[i], !len.readAbsolute(fail_tests[i])); } } void testEnumMappedToString() { - for ( int i = (static_cast<int>(SVGLength::NONE) + 1); i <= static_cast<int>(SVGLength::LAST_UNIT); i++ ) { + for (int i = (static_cast<int>(SVGLength::NONE) + 1); i <= static_cast<int>(SVGLength::LAST_UNIT); i++) { SVGLength::Unit target = static_cast<SVGLength::Unit>(i); // PX is a special case where we don't have a unit string - if ( (target != SVGLength::PX) ) { - gchar const* val = sp_svg_length_get_css_units(target); + if ((target != SVGLength::PX)) { + gchar const *val = sp_svg_length_get_css_units(target); TSM_ASSERT_DIFFERS(i, val, ""); } } @@ -121,11 +128,11 @@ public: // Ensure that all unit suffix strings used are allowed by SVG void testStringsAreValidSVG() { - gchar const* valid[] = {"", "em", "ex", "px", "pt", "pc", "cm", "mm", "in", "%"}; + gchar const *valid[] = {"", "em", "ex", "px", "pt", "pc", "cm", "mm", "in", "%"}; std::set<std::string> validStrings(valid, valid + G_N_ELEMENTS(valid)); - for ( int i = (static_cast<int>(SVGLength::NONE) + 1); i <= static_cast<int>(SVGLength::LAST_UNIT); i++ ) { + for (int i = (static_cast<int>(SVGLength::NONE) + 1); i <= static_cast<int>(SVGLength::LAST_UNIT); i++) { SVGLength::Unit target = static_cast<SVGLength::Unit>(i); - gchar const* val = sp_svg_length_get_css_units(target); + gchar const *val = sp_svg_length_get_css_units(target); TSM_ASSERT(i, validStrings.find(std::string(val)) != validStrings.end()); } } @@ -134,11 +141,11 @@ public: void testValidSVGStringsSupported() { // Note that "px" is omitted from the list, as it will be assumed to be so if not explicitly set. - gchar const* valid[] = {"em", "ex", "pt", "pc", "cm", "mm", "in", "%"}; + gchar const *valid[] = {"em", "ex", "pt", "pc", "cm", "mm", "in", "%"}; std::set<std::string> validStrings(valid, valid + G_N_ELEMENTS(valid)); - for ( int i = (static_cast<int>(SVGLength::NONE) + 1); i <= static_cast<int>(SVGLength::LAST_UNIT); i++ ) { + for (int i = (static_cast<int>(SVGLength::NONE) + 1); i <= static_cast<int>(SVGLength::LAST_UNIT); i++) { SVGLength::Unit target = static_cast<SVGLength::Unit>(i); - gchar const* val = sp_svg_length_get_css_units(target); + gchar const *val = sp_svg_length_get_css_units(target); std::set<std::string>::iterator iter = validStrings.find(std::string(val)); if (iter != validStrings.end()) { validStrings.erase(iter); @@ -154,10 +161,11 @@ public: {"761.9", 761.92918978947023, 4, -8}, }; - for ( size_t i = 0; i < G_N_ELEMENTS(precTests); i++ ) { + for (size_t i = 0; i < G_N_ELEMENTS(precTests); i++) { char buf[256] = {0}; memset(buf, 0xCC, sizeof(buf)); // Make it easy to detect an overrun. - unsigned int retval = sp_svg_number_write_de( buf, sizeof(buf), precTests[i].val, precTests[i].prec, precTests[i].minexp ); + unsigned int retval = + sp_svg_number_write_de(buf, sizeof(buf), precTests[i].val, precTests[i].prec, precTests[i].minexp); TSM_ASSERT_EQUALS("Number of chars written", retval, strlen(precTests[i].str)); TSM_ASSERT_EQUALS("Numeric string written", std::string(buf), std::string(precTests[i].str)); TSM_ASSERT_EQUALS(std::string("Buffer overrun ") + precTests[i].str, '\xCC', buf[retval + 1]); @@ -181,14 +189,14 @@ SvgLengthTest::test_t const SvgLengthTest::absolute_tests[12] = { {"1.2345678mm", SVGLength::MM , 1.2345678, 1.2345678f*96.0/25.4}, // TODO: More precise constants? (a 7 digit constant when the default precision is 8 digits?) {"123.45678cm", SVGLength::CM , 123.45678 , 123.45678f*96.0/2.54}, // Note that svg_length_read is casting the result from g_ascii_strtod to float. {"73.162987in", SVGLength::INCH, 73.162987 , 73.162987f*96.0/1.00}}; - // clang-format on +// clang-format on SvgLengthTest::test_t const SvgLengthTest::relative_tests[3] = { // clang-format off {"123em", SVGLength::EM, 123, 123. * 7.}, {"123ex", SVGLength::EX, 123, 123. * 13.}, {"123%", SVGLength::PERCENT, 1.23, 1.23 * 19.}}; - // clang-format on -char const * SvgLengthTest::fail_tests[8] = { +// clang-format on +char const *SvgLengthTest::fail_tests[8] = { // clang-format off "123 px", "123e", @@ -198,7 +206,7 @@ char const * SvgLengthTest::fail_tests[8] = { "--123", "", "px"}; - // clang-format on +// clang-format on /* Local Variables: diff --git a/src/svg/svg-length.cpp b/src/svg/svg-length.cpp index a84c38bd4fa6ff20c68eb784d67c175b87cfef19..8e45cd7a8ef84e50928652f793fc5b15aa2c1f4b 100644 --- a/src/svg/svg-length.cpp +++ b/src/svg/svg-length.cpp @@ -13,19 +13,20 @@ #include <cmath> #include <cstring> -#include <string> #include <glib.h> #include <iostream> +#include <string> #include <vector> -#include "svg.h" #include "stringstream.h" +#include "svg.h" #include "util/units.h" -static unsigned sp_svg_length_read_lff(gchar const *str, SVGLength::Unit *unit, float *val, float *computed, char **next); +static unsigned sp_svg_length_read_lff(gchar const *str, SVGLength::Unit *unit, float *val, float *computed, + char **next); #ifndef MAX -# define MAX(a,b) ((a < b) ? (b) : (a)) +#define MAX(a, b) ((a < b) ? (b) : (a)) #endif unsigned int sp_svg_number_read_f(gchar const *str, float *val) @@ -36,7 +37,7 @@ unsigned int sp_svg_number_read_f(gchar const *str, float *val) char *e; float const v = g_ascii_strtod(str, &e); - if ((gchar const *) e == str) { + if ((gchar const *)e == str) { return 0; } @@ -52,7 +53,7 @@ unsigned int sp_svg_number_read_d(gchar const *str, double *val) char *e; double const v = g_ascii_strtod(str, &e); - if ((gchar const *) e == str) { + if ((gchar const *)e == str) { return 0; } @@ -90,7 +91,7 @@ static unsigned int sp_svg_number_write_i(gchar *buf, int bufLen, int val) uval = (unsigned int)val; } - p += sp_svg_number_write_ui(buf+p, uval); + p += sp_svg_number_write_ui(buf + p, uval); return p; } @@ -109,7 +110,7 @@ static unsigned sp_svg_number_write_d(gchar *buf, int bufLen, double val, unsign /* Determine number of integral digits */ int idigits = 0; if (val >= 1.0) { - idigits = (int) floor(log10(val)) + 1; + idigits = (int)floor(log10(val)) + 1; } /* Determine the actual number of fractional digits */ @@ -121,11 +122,11 @@ static unsigned sp_svg_number_write_d(gchar *buf, int bufLen, double val, unsign double fval = val - dival; /* Write integra */ if (idigits > (int)tprec) { - i += sp_svg_number_write_ui(buf + i, (unsigned int)floor(dival/pow(10.0, idigits-tprec) + .5)); - for(unsigned int j=0; j<(unsigned int)idigits-tprec; j++) { - buf[i+j] = '0'; + i += sp_svg_number_write_ui(buf + i, (unsigned int)floor(dival / pow(10.0, idigits - tprec) + .5)); + for (unsigned int j = 0; j < (unsigned int)idigits - tprec; j++) { + buf[i + j] = '0'; } - i += idigits-tprec; + i += idigits - tprec; } else { i += sp_svg_number_write_ui(buf + i, (unsigned int)dival); } @@ -136,13 +137,13 @@ static unsigned sp_svg_number_write_d(gchar *buf, int bufLen, double val, unsign fval *= 10.0; dival = floor(fval); fval -= dival; - int const int_dival = (int) dival; + int const int_dival = (int)dival; buf[i++] = '0' + int_dival; if (int_dival != 0) { end_i = i; } fprec -= 1; - } while(fprec > 0 && fval > 0.0); + } while (fprec > 0 && fval > 0.0); } buf[end_i] = 0; return end_i; @@ -154,11 +155,12 @@ unsigned int sp_svg_number_write_de(gchar *buf, int bufLen, double val, unsigned if (val == 0.0 || eval < min_exp) { return sp_svg_number_write_ui(buf, 0); } - unsigned int maxnumdigitsWithoutExp = // This doesn't include the sign because it is included in either representation - eval<0?tprec+(unsigned int)-eval+1: - eval+1<(int)tprec?tprec+1: - (unsigned int)eval+1; - unsigned int maxnumdigitsWithExp = tprec + ( eval<0 ? 4 : 3 ); // It's not necessary to take larger exponents into account, because then maxnumdigitsWithoutExp is DEFINITELY larger + unsigned int maxnumdigitsWithoutExp = // This doesn't include the sign because it is included in either + // representation + eval < 0 ? tprec + (unsigned int)-eval + 1 : eval + 1 < (int)tprec ? tprec + 1 : (unsigned int)eval + 1; + unsigned int maxnumdigitsWithExp = + tprec + (eval < 0 ? 4 : 3); // It's not necessary to take larger exponents into account, because then + // maxnumdigitsWithoutExp is DEFINITELY larger if (maxnumdigitsWithoutExp <= maxnumdigitsWithExp) { return sp_svg_number_write_d(buf, bufLen, val, tprec, 0); } else { @@ -175,8 +177,7 @@ SVGLength::SVGLength() , unit(NONE) , value(0) , computed(0) -{ -} +{} /* Length */ @@ -235,7 +236,6 @@ bool SVGLength::readAbsolute(gchar const *str) return true; } - unsigned int sp_svg_length_read_computed_absolute(gchar const *str, float *length) { if (!str) { @@ -267,17 +267,15 @@ std::vector<SVGLength> sp_svg_length_list_read(gchar const *str) SVGLength::Unit unit; float value; float computed; - char *next = (char *) str; + char *next = (char *)str; std::vector<SVGLength> list; while (sp_svg_length_read_lff(next, &unit, &value, &computed, &next)) { - SVGLength length; length.set(unit, value, computed); list.push_back(length); - while (next && *next && - (*next == ',' || *next == ' ' || *next == '\n' || *next == '\r' || *next == '\t')) { + while (next && *next && (*next == ',' || *next == ' ' || *next == '\n' || *next == '\r' || *next == '\t')) { // the list can be comma- or space-separated, but we will be generous and accept // a mix, including newlines and tabs next++; @@ -291,21 +289,22 @@ std::vector<SVGLength> sp_svg_length_list_read(gchar const *str) return list; } +#define UVAL(a, b) (((unsigned int)(a) << 8) | (unsigned int)(b)) -#define UVAL(a,b) (((unsigned int) (a) << 8) | (unsigned int) (b)) - -static unsigned sp_svg_length_read_lff(gchar const *str, SVGLength::Unit *unit, float *val, float *computed, char **next) +static unsigned sp_svg_length_read_lff(gchar const *str, SVGLength::Unit *unit, float *val, float *computed, + char **next) { -/* note: this function is sometimes fed a string with several consecutive numbers, e.g. by sp_svg_length_list_read. -So after the number, the string does not necessarily have a \0 or a unit, it might also contain a space or comma and then the next number! -*/ + /* note: this function is sometimes fed a string with several consecutive numbers, e.g. by sp_svg_length_list_read. + So after the number, the string does not necessarily have a \0 or a unit, it might also contain a space or comma and + then the next number! + */ if (!str) { return 0; } gchar const *e; - float const v = g_ascii_strtod(str, (char **) &e); + float const v = g_ascii_strtod(str, (char **)&e); if (e == str) { return 0; } @@ -342,7 +341,7 @@ So after the number, the string does not necessarily have a \0 or a unit, it mig *computed = v * 0.01; } if (next) { - *next = (char *) e + 1; + *next = (char *)e + 1; } return 1; } else if (g_ascii_isspace(e[0]) && e[1] && g_ascii_isalpha(e[1])) { @@ -359,7 +358,7 @@ So after the number, the string does not necessarily have a \0 or a unit, it mig *computed = v; } if (next) { - *next = (char *) e; + *next = (char *)e; } return 1; } @@ -369,7 +368,7 @@ So after the number, the string does not necessarily have a \0 or a unit, it mig * percentage units are done. */ unsigned int const uval = UVAL(e[0], e[1]); switch (uval) { - case UVAL('p','x'): + case UVAL('p', 'x'): if (unit) { *unit = SVGLength::PX; } @@ -377,7 +376,7 @@ So after the number, the string does not necessarily have a \0 or a unit, it mig *computed = v; } break; - case UVAL('p','t'): + case UVAL('p', 't'): if (unit) { *unit = SVGLength::PT; } @@ -385,7 +384,7 @@ So after the number, the string does not necessarily have a \0 or a unit, it mig *computed = Inkscape::Util::Quantity::convert(v, "pt", "px"); } break; - case UVAL('p','c'): + case UVAL('p', 'c'): if (unit) { *unit = SVGLength::PC; } @@ -393,7 +392,7 @@ So after the number, the string does not necessarily have a \0 or a unit, it mig *computed = Inkscape::Util::Quantity::convert(v, "pc", "px"); } break; - case UVAL('m','m'): + case UVAL('m', 'm'): if (unit) { *unit = SVGLength::MM; } @@ -401,7 +400,7 @@ So after the number, the string does not necessarily have a \0 or a unit, it mig *computed = Inkscape::Util::Quantity::convert(v, "mm", "px"); } break; - case UVAL('c','m'): + case UVAL('c', 'm'): if (unit) { *unit = SVGLength::CM; } @@ -409,7 +408,7 @@ So after the number, the string does not necessarily have a \0 or a unit, it mig *computed = Inkscape::Util::Quantity::convert(v, "cm", "px"); } break; - case UVAL('i','n'): + case UVAL('i', 'n'): if (unit) { *unit = SVGLength::INCH; } @@ -417,12 +416,12 @@ So after the number, the string does not necessarily have a \0 or a unit, it mig *computed = Inkscape::Util::Quantity::convert(v, "in", "px"); } break; - case UVAL('e','m'): + case UVAL('e', 'm'): if (unit) { *unit = SVGLength::EM; } break; - case UVAL('e','x'): + case UVAL('e', 'x'): if (unit) { *unit = SVGLength::EX; } @@ -436,7 +435,7 @@ So after the number, the string does not necessarily have a \0 or a unit, it mig *val = v; } if (next) { - *next = (char *) e + 2; + *next = (char *)e + 2; } return 1; } @@ -471,7 +470,7 @@ void SVGLength::set(SVGLength::Unit u, float v) _set = true; unit = u; Glib::ustring hack("px"); - switch( unit ) { + switch (unit) { case NONE: case PX: case EM: @@ -497,7 +496,7 @@ void SVGLength::set(SVGLength::Unit u, float v) break; } value = v; - computed = Inkscape::Util::Quantity::convert(v, hack, "px"); + computed = Inkscape::Util::Quantity::convert(v, hack, "px"); } void SVGLength::set(SVGLength::Unit u, float v, float c) @@ -557,16 +556,26 @@ double sp_svg_read_percentage(char const *str, double def) gchar const *sp_svg_length_get_css_units(SVGLength::Unit unit) { switch (unit) { - case SVGLength::NONE: return ""; - case SVGLength::PX: return ""; - case SVGLength::PT: return "pt"; - case SVGLength::PC: return "pc"; - case SVGLength::MM: return "mm"; - case SVGLength::CM: return "cm"; - case SVGLength::INCH: return "in"; - case SVGLength::EM: return "em"; - case SVGLength::EX: return "ex"; - case SVGLength::PERCENT: return "%"; + case SVGLength::NONE: + return ""; + case SVGLength::PX: + return ""; + case SVGLength::PT: + return "pt"; + case SVGLength::PC: + return "pc"; + case SVGLength::MM: + return "mm"; + case SVGLength::CM: + return "cm"; + case SVGLength::INCH: + return "in"; + case SVGLength::EM: + return "em"; + case SVGLength::EX: + return "ex"; + case SVGLength::PERCENT: + return "%"; } return ""; } @@ -579,14 +588,13 @@ std::string sp_svg_length_write_with_units(SVGLength const &length) { Inkscape::SVGOStringStream os; if (length.unit == SVGLength::PERCENT) { - os << 100*length.value << sp_svg_length_get_css_units(length.unit); + os << 100 * length.value << sp_svg_length_get_css_units(length.unit); } else { os << length.value << sp_svg_length_get_css_units(length.unit); } return os.str(); } - void SVGLength::readOrUnset(gchar const *str, Unit u, float v, float c) { if (!read(str)) { @@ -594,7 +602,6 @@ void SVGLength::readOrUnset(gchar const *str, Unit u, float v, float c) } } - /* Local Variables: mode:c++ diff --git a/src/svg/svg-length.h b/src/svg/svg-length.h index 17e04a2ad9bf8482f3a12f292ff68189140ea0f3..20137bddd85b94969d02ee6dd7f1b4d21c1794c7 100644 --- a/src/svg/svg-length.h +++ b/src/svg/svg-length.h @@ -18,11 +18,13 @@ /** * SVG length type */ -class SVGLength { +class SVGLength +{ public: SVGLength(); - enum Unit { + enum Unit + { NONE, PX, PT, @@ -48,7 +50,8 @@ public: // The value in pixels (value * pixels/unit). float computed; - float operator=(float v) { + float operator=(float v) + { _set = true; unit = NONE; value = computed = v; @@ -60,10 +63,10 @@ public: bool readAbsolute(char const *str); std::string write() const; // To set 'v' use '=' - void set(Unit u, float v); // Sets computed value based on u and v. + void set(Unit u, float v); // Sets computed value based on u and v. void set(Unit u, float v, float c); // Sets all three values. void unset(Unit u = NONE, float v = 0, float c = 0); - void scale(double scale); // Scales length (value, computed), leaving unit alone. + void scale(double scale); // Scales length (value, computed), leaving unit alone. void update(double em, double ex, double scale); // Updates computed value }; diff --git a/src/svg/svg-path-geom-test.h b/src/svg/svg-path-geom-test.h index acfcc287aa6b4a57500f7113abec5d62555a5b03..8c4584b64b93b328d7a1870dcc70565f5fecee2e 100644 --- a/src/svg/svg-path-geom-test.h +++ b/src/svg/svg-path-geom-test.h @@ -8,16 +8,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include <cxxtest/TestSuite.h> +#include <glib.h> +#include <stdio.h> +#include <string> +#include <vector> + #include "2geom/coord.h" #include "2geom/curves.h" #include "2geom/pathvector.h" -#include "svg/svg.h" #include "preferences.h" #include "streq.h" -#include <stdio.h> -#include <string> -#include <vector> -#include <glib.h> +#include "svg/svg.h" class SvgPathGeomTest : public CxxTest::TestSuite { @@ -31,8 +32,10 @@ private: Geom::PathVector rectanglepvopen; Geom::PathVector rectanglepvclosed; Geom::PathVector rectanglepvclosed2; + public: - SvgPathGeomTest() { + SvgPathGeomTest() + { // Lots of ways to define the same rectangle rectanglesAbsoluteClosed.push_back("M 1,2 L 4,2 L 4,8 L 1,8 z"); rectanglesAbsoluteClosed.push_back("M 1,2 4,2 4,8 1,8 z"); @@ -52,344 +55,365 @@ public: rectanglesRelativeClosed2.push_back("m 1,2 l 3,0 l 0,6 l -3,0 l 0,-6 z"); rectanglesRelativeClosed2.push_back("m 1,2 3,0 0,6 -3,0 0,-6 z"); rectanglesRelativeClosed2.push_back("m 1,2 h 3 v 6 h -3 v -6 z"); - rectanglepvopen.push_back(Geom::Path(Geom::Point(1,2))); - rectanglepvopen.back().append(Geom::LineSegment(Geom::Point(1,2),Geom::Point(4,2))); - rectanglepvopen.back().append(Geom::LineSegment(Geom::Point(4,2),Geom::Point(4,8))); - rectanglepvopen.back().append(Geom::LineSegment(Geom::Point(4,8),Geom::Point(1,8))); - rectanglepvopen.back().append(Geom::LineSegment(Geom::Point(1,8),Geom::Point(1,2))); - rectanglepvclosed.push_back(Geom::Path(Geom::Point(1,2))); - rectanglepvclosed.back().append(Geom::LineSegment(Geom::Point(1,2),Geom::Point(4,2))); - rectanglepvclosed.back().append(Geom::LineSegment(Geom::Point(4,2),Geom::Point(4,8))); - rectanglepvclosed.back().append(Geom::LineSegment(Geom::Point(4,8),Geom::Point(1,8))); + rectanglepvopen.push_back(Geom::Path(Geom::Point(1, 2))); + rectanglepvopen.back().append(Geom::LineSegment(Geom::Point(1, 2), Geom::Point(4, 2))); + rectanglepvopen.back().append(Geom::LineSegment(Geom::Point(4, 2), Geom::Point(4, 8))); + rectanglepvopen.back().append(Geom::LineSegment(Geom::Point(4, 8), Geom::Point(1, 8))); + rectanglepvopen.back().append(Geom::LineSegment(Geom::Point(1, 8), Geom::Point(1, 2))); + rectanglepvclosed.push_back(Geom::Path(Geom::Point(1, 2))); + rectanglepvclosed.back().append(Geom::LineSegment(Geom::Point(1, 2), Geom::Point(4, 2))); + rectanglepvclosed.back().append(Geom::LineSegment(Geom::Point(4, 2), Geom::Point(4, 8))); + rectanglepvclosed.back().append(Geom::LineSegment(Geom::Point(4, 8), Geom::Point(1, 8))); rectanglepvclosed.back().close(); - rectanglepvclosed2.push_back(Geom::Path(Geom::Point(1,2))); - rectanglepvclosed2.back().append(Geom::LineSegment(Geom::Point(1,2),Geom::Point(4,2))); - rectanglepvclosed2.back().append(Geom::LineSegment(Geom::Point(4,2),Geom::Point(4,8))); - rectanglepvclosed2.back().append(Geom::LineSegment(Geom::Point(4,8),Geom::Point(1,8))); - rectanglepvclosed2.back().append(Geom::LineSegment(Geom::Point(1,8),Geom::Point(1,2))); + rectanglepvclosed2.push_back(Geom::Path(Geom::Point(1, 2))); + rectanglepvclosed2.back().append(Geom::LineSegment(Geom::Point(1, 2), Geom::Point(4, 2))); + rectanglepvclosed2.back().append(Geom::LineSegment(Geom::Point(4, 2), Geom::Point(4, 8))); + rectanglepvclosed2.back().append(Geom::LineSegment(Geom::Point(4, 8), Geom::Point(1, 8))); + rectanglepvclosed2.back().append(Geom::LineSegment(Geom::Point(1, 8), Geom::Point(1, 2))); rectanglepvclosed2.back().close(); // TODO: Also test some (smooth) cubic/quadratic beziers and elliptical arcs // TODO: Should we make it mandatory that h/v in the path data results in a H/VLineSegment? // If so, the tests should be modified to reflect this. } -// createSuite and destroySuite get us per-suite setup and teardown -// without us having to worry about static initialization order, etc. + // createSuite and destroySuite get us per-suite setup and teardown + // without us having to worry about static initialization order, etc. static SvgPathGeomTest *createSuite() { return new SvgPathGeomTest(); } - static void destroySuite( SvgPathGeomTest *suite ) { delete suite; } + static void destroySuite(SvgPathGeomTest *suite) { delete suite; } void testReadRectanglesAbsoluteClosed() { - for(size_t i=0; i<rectanglesAbsoluteClosed.size(); i++) { + for (size_t i = 0; i < rectanglesAbsoluteClosed.size(); i++) { Geom::PathVector pv = sp_svg_read_pathv(rectanglesAbsoluteClosed[i].c_str()); - TSM_ASSERT(rectanglesAbsoluteClosed[i].c_str(), bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(rectanglesAbsoluteClosed[i].c_str(), bpathEqual(pv, rectanglepvclosed)); } } void testReadRectanglesRelativeClosed() { - for(size_t i=0; i<rectanglesRelativeClosed.size(); i++) { + for (size_t i = 0; i < rectanglesRelativeClosed.size(); i++) { Geom::PathVector pv = sp_svg_read_pathv(rectanglesRelativeClosed[i].c_str()); - TSM_ASSERT(rectanglesRelativeClosed[i].c_str(), bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(rectanglesRelativeClosed[i].c_str(), bpathEqual(pv, rectanglepvclosed)); } } void testReadRectanglesAbsoluteOpen() { - for(size_t i=0; i<rectanglesAbsoluteOpen.size(); i++) { + for (size_t i = 0; i < rectanglesAbsoluteOpen.size(); i++) { Geom::PathVector pv = sp_svg_read_pathv(rectanglesAbsoluteOpen[i].c_str()); - TSM_ASSERT(rectanglesAbsoluteOpen[i].c_str(), bpathEqual(pv,rectanglepvopen)); + TSM_ASSERT(rectanglesAbsoluteOpen[i].c_str(), bpathEqual(pv, rectanglepvopen)); } } void testReadRectanglesRelativeOpen() { - for(size_t i=0; i<rectanglesRelativeOpen.size(); i++) { + for (size_t i = 0; i < rectanglesRelativeOpen.size(); i++) { Geom::PathVector pv = sp_svg_read_pathv(rectanglesRelativeOpen[i].c_str()); - TSM_ASSERT(rectanglesRelativeOpen[i].c_str(), bpathEqual(pv,rectanglepvopen)); + TSM_ASSERT(rectanglesRelativeOpen[i].c_str(), bpathEqual(pv, rectanglepvopen)); } } void testReadRectanglesAbsoluteClosed2() { - for(size_t i=0; i<rectanglesAbsoluteClosed2.size(); i++) { + for (size_t i = 0; i < rectanglesAbsoluteClosed2.size(); i++) { Geom::PathVector pv = sp_svg_read_pathv(rectanglesAbsoluteClosed2[i].c_str()); - TSM_ASSERT(rectanglesAbsoluteClosed2[i].c_str(), bpathEqual(pv,rectanglepvclosed2)); + TSM_ASSERT(rectanglesAbsoluteClosed2[i].c_str(), bpathEqual(pv, rectanglepvclosed2)); } } void testReadRectanglesRelativeClosed2() { - for(size_t i=0; i<rectanglesRelativeClosed2.size(); i++) { + for (size_t i = 0; i < rectanglesRelativeClosed2.size(); i++) { Geom::PathVector pv = sp_svg_read_pathv(rectanglesRelativeClosed2[i].c_str()); - TSM_ASSERT(rectanglesRelativeClosed2[i].c_str(), bpathEqual(pv,rectanglepvclosed2)); + TSM_ASSERT(rectanglesRelativeClosed2[i].c_str(), bpathEqual(pv, rectanglepvclosed2)); } } void testReadConcatenatedPaths() { - // Note that finalPoint doesn't actually return the final point of the path, just the last given point... (but since this might be intentional and we're not testing lib2geom here, we just specify the final point explicitly + // Note that finalPoint doesn't actually return the final point of the path, just the last given point... (but + // since this might be intentional and we're not testing lib2geom here, we just specify the final point + // explicitly Geom::PathVector pv_good; pv_good.push_back(rectanglepvclosed.back()); - pv_good.push_back(rectanglepvopen.back() * Geom::Translate(1,2)/* * Geom::Translate(pv_good[0].finalPoint())*/); - pv_good.push_back(rectanglepvclosed.back() * Geom::Translate(2,4)/* *Geom::Translate(pv_good[1].finalPoint())*/); + pv_good.push_back(rectanglepvopen.back() * + Geom::Translate(1, 2) /* * Geom::Translate(pv_good[0].finalPoint())*/); + pv_good.push_back(rectanglepvclosed.back() * + Geom::Translate(2, 4) /* *Geom::Translate(pv_good[1].finalPoint())*/); pv_good.push_back(rectanglepvopen.back()); pv_good[0].close(); pv_good[1].close(false); pv_good[2].close(); pv_good[3].close(false); - std::string path_str = rectanglesAbsoluteClosed[0] + rectanglesRelativeOpen[0] + rectanglesRelativeClosed[0] + rectanglesAbsoluteOpen[0]; + std::string path_str = rectanglesAbsoluteClosed[0] + rectanglesRelativeOpen[0] + rectanglesRelativeClosed[0] + + rectanglesAbsoluteOpen[0]; Geom::PathVector pv = sp_svg_read_pathv(path_str.c_str()); - TS_ASSERT(bpathEqual(pv,pv_good)); + TS_ASSERT(bpathEqual(pv, pv_good)); } - void testReadZeroLengthSubpaths() { + void testReadZeroLengthSubpaths() + { // Per the SVG 1.1 specification (section F5) zero-length subpaths are relevant Geom::PathVector pv_good; - pv_good.push_back(Geom::Path(Geom::Point(0,0))); - pv_good.push_back(Geom::Path(Geom::Point(1,1))); - pv_good.back().append(Geom::LineSegment(Geom::Point(1,1),Geom::Point(2,2))); - pv_good.push_back(Geom::Path(Geom::Point(3,3))); + pv_good.push_back(Geom::Path(Geom::Point(0, 0))); + pv_good.push_back(Geom::Path(Geom::Point(1, 1))); + pv_good.back().append(Geom::LineSegment(Geom::Point(1, 1), Geom::Point(2, 2))); + pv_good.push_back(Geom::Path(Geom::Point(3, 3))); pv_good.back().close(); - pv_good.push_back(Geom::Path(Geom::Point(4,4))); - pv_good.back().append(Geom::LineSegment(Geom::Point(4,4),Geom::Point(5,5))); + pv_good.push_back(Geom::Path(Geom::Point(4, 4))); + pv_good.back().append(Geom::LineSegment(Geom::Point(4, 4), Geom::Point(5, 5))); pv_good.back().close(); - pv_good.push_back(Geom::Path(Geom::Point(6,6))); - { // Test absolute version - char const * path_str = "M 0,0 M 1,1 L 2,2 M 3,3 z M 4,4 L 5,5 z M 6,6"; + pv_good.push_back(Geom::Path(Geom::Point(6, 6))); + { // Test absolute version + char const *path_str = "M 0,0 M 1,1 L 2,2 M 3,3 z M 4,4 L 5,5 z M 6,6"; Geom::PathVector pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,pv_good)); + TSM_ASSERT(path_str, bpathEqual(pv, pv_good)); } - { // Test relative version - char const * path_str = "m 0,0 m 1,1 l 1,1 m 1,1 z m 1,1 l 1,1 z m 2,2"; + { // Test relative version + char const *path_str = "m 0,0 m 1,1 l 1,1 m 1,1 z m 1,1 l 1,1 z m 2,2"; Geom::PathVector pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,pv_good)); + TSM_ASSERT(path_str, bpathEqual(pv, pv_good)); } } - void testReadImplicitMoveto() { - TS_WARN("Currently lib2geom (/libnr) has no way of specifying the difference between 'M 0,0 ... z M 0,0 L 1,0' and 'M 0,0 ... z L 1,0', the SVG specification does state that these should be handled differently with respect to markers however, see the description of the 'orient' attribute of the 'marker' element."); + void testReadImplicitMoveto() + { + TS_WARN( + "Currently lib2geom (/libnr) has no way of specifying the difference between 'M 0,0 ... z M 0,0 L 1,0' and " + "'M 0,0 ... z L 1,0', the SVG specification does state that these should be handled differently with " + "respect to markers however, see the description of the 'orient' attribute of the 'marker' element."); Geom::PathVector pv_good; - pv_good.push_back(Geom::Path(Geom::Point(1,1))); - pv_good.back().append(Geom::LineSegment(Geom::Point(1,1),Geom::Point(2,2))); + pv_good.push_back(Geom::Path(Geom::Point(1, 1))); + pv_good.back().append(Geom::LineSegment(Geom::Point(1, 1), Geom::Point(2, 2))); pv_good.back().close(); - pv_good.push_back(Geom::Path(Geom::Point(1,1))); - pv_good.back().append(Geom::LineSegment(Geom::Point(1,1),Geom::Point(3,3))); + pv_good.push_back(Geom::Path(Geom::Point(1, 1))); + pv_good.back().append(Geom::LineSegment(Geom::Point(1, 1), Geom::Point(3, 3))); pv_good.back().close(); - { // Test absolute version - char const * path_str = "M 1,1 L 2,2 z L 3,3 z"; + { // Test absolute version + char const *path_str = "M 1,1 L 2,2 z L 3,3 z"; Geom::PathVector pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,pv_good)); + TSM_ASSERT(path_str, bpathEqual(pv, pv_good)); } - { // Test relative version - char const * path_str = "M 1,1 l 1,1 z l 2,2 z"; + { // Test relative version + char const *path_str = "M 1,1 l 1,1 z l 2,2 z"; Geom::PathVector pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,pv_good)); + TSM_ASSERT(path_str, bpathEqual(pv, pv_good)); } } - void testReadFloatingPoint() { + void testReadFloatingPoint() + { Geom::PathVector pv_good1; - pv_good1.push_back(Geom::Path(Geom::Point(.01,.02))); - pv_good1.back().append(Geom::LineSegment(Geom::Point(.01,.02),Geom::Point(.04,.02))); - pv_good1.back().append(Geom::LineSegment(Geom::Point(.04,.02),Geom::Point(1.5,1.6))); - pv_good1.back().append(Geom::LineSegment(Geom::Point(1.5,1.6),Geom::Point(.01,.08))); - pv_good1.back().append(Geom::LineSegment(Geom::Point(.01,.08),Geom::Point(.01,.02))); + pv_good1.push_back(Geom::Path(Geom::Point(.01, .02))); + pv_good1.back().append(Geom::LineSegment(Geom::Point(.01, .02), Geom::Point(.04, .02))); + pv_good1.back().append(Geom::LineSegment(Geom::Point(.04, .02), Geom::Point(1.5, 1.6))); + pv_good1.back().append(Geom::LineSegment(Geom::Point(1.5, 1.6), Geom::Point(.01, .08))); + pv_good1.back().append(Geom::LineSegment(Geom::Point(.01, .08), Geom::Point(.01, .02))); pv_good1.back().close(); - { // Test decimals - char const * path_str = "M .01,.02 L.04.02 L1.5,1.6L0.01,0.08 .01.02 z"; + { // Test decimals + char const *path_str = "M .01,.02 L.04.02 L1.5,1.6L0.01,0.08 .01.02 z"; Geom::PathVector pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,pv_good1)); + TSM_ASSERT(path_str, bpathEqual(pv, pv_good1)); } Geom::PathVector pv_good2; - pv_good2.push_back(Geom::Path(Geom::Point(.01,.02))); - pv_good2.back().append(Geom::LineSegment(Geom::Point(.01,.02),Geom::Point(.04,.02))); - pv_good2.back().append(Geom::LineSegment(Geom::Point(.04,.02),Geom::Point(1.5,1.6))); - pv_good2.back().append(Geom::LineSegment(Geom::Point(1.5,1.6),Geom::Point(.01,.08))); + pv_good2.push_back(Geom::Path(Geom::Point(.01, .02))); + pv_good2.back().append(Geom::LineSegment(Geom::Point(.01, .02), Geom::Point(.04, .02))); + pv_good2.back().append(Geom::LineSegment(Geom::Point(.04, .02), Geom::Point(1.5, 1.6))); + pv_good2.back().append(Geom::LineSegment(Geom::Point(1.5, 1.6), Geom::Point(.01, .08))); pv_good2.back().close(); - { // Test exponent - char const * path_str = "M 1e-2,.2e-1 L 0.004e1,0.0002e+2 L0150E-2,1.6e0L1.0e-2,80e-3 z"; + { // Test exponent + char const *path_str = "M 1e-2,.2e-1 L 0.004e1,0.0002e+2 L0150E-2,1.6e0L1.0e-2,80e-3 z"; Geom::PathVector pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,pv_good2)); + TSM_ASSERT(path_str, bpathEqual(pv, pv_good2)); } } - void testReadImplicitSeparation() { + void testReadImplicitSeparation() + { // Coordinates need not be separated by whitespace if they can still be read unambiguously Geom::PathVector pv_good; - pv_good.push_back(Geom::Path(Geom::Point(.1,.2))); - pv_good.back().append(Geom::LineSegment(Geom::Point(.1,.2),Geom::Point(.4,.2))); - pv_good.back().append(Geom::LineSegment(Geom::Point(.4,.2),Geom::Point(.4,.8))); - pv_good.back().append(Geom::LineSegment(Geom::Point(.4,.8),Geom::Point(.1,.8))); + pv_good.push_back(Geom::Path(Geom::Point(.1, .2))); + pv_good.back().append(Geom::LineSegment(Geom::Point(.1, .2), Geom::Point(.4, .2))); + pv_good.back().append(Geom::LineSegment(Geom::Point(.4, .2), Geom::Point(.4, .8))); + pv_good.back().append(Geom::LineSegment(Geom::Point(.4, .8), Geom::Point(.1, .8))); pv_good.back().close(); - { // Test absolute - char const * path_str = "M .1.2+0.4.2e0.4e0+8e-1.1.8 z"; + { // Test absolute + char const *path_str = "M .1.2+0.4.2e0.4e0+8e-1.1.8 z"; Geom::PathVector pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,pv_good)); + TSM_ASSERT(path_str, bpathEqual(pv, pv_good)); } - { // Test relative - char const * path_str = "m .1.2+0.3.0e0.0e0+6e-1-.3.0 z"; + { // Test relative + char const *path_str = "m .1.2+0.3.0e0.0e0+6e-1-.3.0 z"; Geom::PathVector pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,pv_good)); + TSM_ASSERT(path_str, bpathEqual(pv, pv_good)); } } - void testReadErrorMisplacedCharacter() { - char const * path_str; + void testReadErrorMisplacedCharacter() + { + char const *path_str; Geom::PathVector pv; // Comma in the wrong place (commas may only appear between parameters) path_str = "M 1,2 4,2 4,8 1,8 z , m 13,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // Comma in the wrong place (commas may only appear between parameters) path_str = "M 1,2 4,2 4,8 1,8 z m,13,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // Period in the wrong place (no numbers after a 'z') path_str = "M 1,2 4,2 4,8 1,8 z . m 13,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // Sign in the wrong place (no numbers after a 'z') path_str = "M 1,2 4,2 4,8 1,8 z + - m 13,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // Digit in the wrong place (no numbers after a 'z') path_str = "M 1,2 4,2 4,8 1,8 z 9809 m 13,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // Digit in the wrong place (no numbers after a 'z') path_str = "M 1,2 4,2 4,8 1,8 z 9809 876 m 13,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); } - void testReadErrorUnrecognizedCharacter() { - char const * path_str; + void testReadErrorUnrecognizedCharacter() + { + char const *path_str; Geom::PathVector pv; // Unrecognized character path_str = "M 1,2 4,2 4,8 1,8 z&m 13,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // Unrecognized character path_str = "M 1,2 4,2 4,8 1,8 z m &13,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); } - void testReadErrorTypo() { - char const * path_str; + void testReadErrorTypo() + { + char const *path_str; Geom::PathVector pv; // Typo path_str = "M 1,2 4,2 4,8 1,8 z j 13,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // Typo path_str = "M 1,2 4,2 4,8 1,8 L 1,2 x m 13,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvopen)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvopen)); } - void testReadErrorIllformedNumbers() { - char const * path_str; + void testReadErrorIllformedNumbers() + { + char const *path_str; Geom::PathVector pv; // Double exponent path_str = "M 1,2 4,2 4,8 1,8 z m 13e4e5,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // Double sign path_str = "M 1,2 4,2 4,8 1,8 z m +-13,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // Double sign path_str = "M 1,2 4,2 4,8 1,8 z m 13e+-12,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // No digit path_str = "M 1,2 4,2 4,8 1,8 z m .e12,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // No digit path_str = "M 1,2 4,2 4,8 1,8 z m .,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // No digit path_str = "M 1,2 4,2 4,8 1,8 z m +,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // No digit path_str = "M 1,2 4,2 4,8 1,8 z m +.e+,15"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); } - void testReadErrorJunk() { - char const * path_str; + void testReadErrorJunk() + { + char const *path_str; Geom::PathVector pv; // Junk path_str = "M 1,2 4,2 4,8 1,8 z j 357 hkjh.,34e34 90ih6kj4 h5k6vlh4N.,6,45wikuyi3yere..3487 m 13,23"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); } - void testReadErrorStopReading() { - char const * path_str; + void testReadErrorStopReading() + { + char const *path_str; Geom::PathVector pv; // Unrecognized parameter path_str = "M 1,2 4,2 4,8 1,8 z m #$%,23,34"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // Invalid parameter path_str = "M 1,2 4,2 4,8 1,8 z m #$%,23,34"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // Illformed parameter path_str = "M 1,2 4,2 4,8 1,8 z m +-12,23,34"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvclosed)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvclosed)); // "Third" parameter path_str = "M 1,2 4,2 4,8 1,8 1,2,3 M 12,23"; pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(path_str, bpathEqual(pv,rectanglepvopen)); + TSM_ASSERT(path_str, bpathEqual(pv, rectanglepvopen)); } - void testRoundTrip() { + void testRoundTrip() + { // This is the easiest way to (also) test writing path data, as a path can be written in more than one way. Geom::PathVector pv; Geom::PathVector new_pv; std::string org_path_str; - char * path_str; + char *path_str; // Rectangle (closed) org_path_str = rectanglesAbsoluteClosed[0]; pv = sp_svg_read_pathv(org_path_str.c_str()); path_str = sp_svg_write_path(pv); new_pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(org_path_str.c_str(), bpathEqual(pv,new_pv)); + TSM_ASSERT(org_path_str.c_str(), bpathEqual(pv, new_pv)); g_free(path_str); // Rectangle (open) org_path_str = rectanglesAbsoluteOpen[0]; pv = sp_svg_read_pathv(org_path_str.c_str()); path_str = sp_svg_write_path(pv); new_pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(org_path_str.c_str(), bpathEqual(pv,new_pv)); + TSM_ASSERT(org_path_str.c_str(), bpathEqual(pv, new_pv)); g_free(path_str); // Concatenated rectangles - org_path_str = rectanglesAbsoluteClosed[0] + rectanglesRelativeOpen[0] + rectanglesRelativeClosed[0] + rectanglesAbsoluteOpen[0]; + org_path_str = rectanglesAbsoluteClosed[0] + rectanglesRelativeOpen[0] + rectanglesRelativeClosed[0] + + rectanglesAbsoluteOpen[0]; pv = sp_svg_read_pathv(org_path_str.c_str()); path_str = sp_svg_write_path(pv); new_pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(org_path_str.c_str(), bpathEqual(pv,new_pv)); + TSM_ASSERT(org_path_str.c_str(), bpathEqual(pv, new_pv)); g_free(path_str); // Zero-length subpaths org_path_str = "M 0,0 M 1,1 L 2,2 M 3,3 z M 4,4 L 5,5 z M 6,6"; pv = sp_svg_read_pathv(org_path_str.c_str()); path_str = sp_svg_write_path(pv); new_pv = sp_svg_read_pathv(path_str); - TSM_ASSERT(org_path_str.c_str(), bpathEqual(pv,new_pv)); + TSM_ASSERT(org_path_str.c_str(), bpathEqual(pv, new_pv)); g_free(path_str); // Floating-point - org_path_str = "M .01,.02 L 0.04,0.02 L.04,.08L0.01,0.08 z""M 1e-2,.2e-1 L 0.004e1,0.0002e+2 L04E-2,.08e0L1.0e-2,80e-3 z"; + org_path_str = "M .01,.02 L 0.04,0.02 L.04,.08L0.01,0.08 z" + "M 1e-2,.2e-1 L 0.004e1,0.0002e+2 L04E-2,.08e0L1.0e-2,80e-3 z"; pv = sp_svg_read_pathv(org_path_str.c_str()); path_str = sp_svg_write_path(pv); new_pv = sp_svg_read_pathv(path_str); @@ -397,110 +421,129 @@ public: g_free(path_str); } - void testMinexpPrecision() { + void testMinexpPrecision() + { Geom::PathVector pv; - char * path_str; + char *path_str; // Default values Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setBool("/options/svgoutput/allowrelativecoordinates", true); prefs->setBool("/options/svgoutput/forcerepeatcommands", false); prefs->setInt("/options/svgoutput/numericprecision", 8); prefs->setInt("/options/svgoutput/minimumexponent", -8); - pv = sp_svg_read_pathv("M 123456781,1.23456781e-8 L 123456782,1.23456782e-8 L 123456785,1.23456785e-8 L 10123456400,1.23456785e-8 L 123456789,1.23456789e-8 L 123456789,101.234564e-8 L 123456789,1.23456789e-8"); + pv = sp_svg_read_pathv( + "M 123456781,1.23456781e-8 L 123456782,1.23456782e-8 L 123456785,1.23456785e-8 L 10123456400,1.23456785e-8 " + "L 123456789,1.23456789e-8 L 123456789,101.234564e-8 L 123456789,1.23456789e-8"); path_str = sp_svg_write_path(pv); - TS_ASSERT_RELATION( streq_rel , "m 123456780,1.2345678e-8 0,0 10,1e-15 9999999210,0 -9999999210,0 0,9.99999921e-7 0,-9.99999921e-7" , path_str ); + TS_ASSERT_RELATION( + streq_rel, + "m 123456780,1.2345678e-8 0,0 10,1e-15 9999999210,0 -9999999210,0 0,9.99999921e-7 0,-9.99999921e-7", + path_str); g_free(path_str); } private: - bool bpathEqual(Geom::PathVector const &a, Geom::PathVector const &b, double eps = 1e-16) { + bool bpathEqual(Geom::PathVector const &a, Geom::PathVector const &b, double eps = 1e-16) + { if (a.size() != b.size()) { char temp[100]; - sprintf(temp, "PathVectors not the same size: %u != %u", static_cast<unsigned int>(a.size()),static_cast<unsigned int>( b.size())); + sprintf(temp, "PathVectors not the same size: %u != %u", static_cast<unsigned int>(a.size()), + static_cast<unsigned int>(b.size())); TS_FAIL(temp); return false; } - for(size_t i=0; i<a.size(); i++) { + for (size_t i = 0; i < a.size(); i++) { Geom::Path const &pa = a[i]; Geom::Path const &pb = b[i]; if (pa.closed() && !pb.closed()) { char temp[100]; - sprintf(temp, "Left subpath is closed, right subpath is open. Subpath: %u", static_cast<unsigned int>(i)); + sprintf(temp, "Left subpath is closed, right subpath is open. Subpath: %u", + static_cast<unsigned int>(i)); TS_FAIL(temp); return false; } if (!pa.closed() && pb.closed()) { char temp[100]; - sprintf(temp, "Right subpath is closed, left subpath is open. Subpath: %u", static_cast<unsigned int>(i)); + sprintf(temp, "Right subpath is closed, left subpath is open. Subpath: %u", + static_cast<unsigned int>(i)); TS_FAIL(temp); return false; } if (pa.size() != pb.size()) { char temp[100]; - sprintf(temp, "Not the same number of segments: %u != %u, subpath: %u", static_cast<unsigned int>(pa.size()), static_cast<unsigned int>(pb.size()), static_cast<unsigned int>(i)); + sprintf(temp, "Not the same number of segments: %u != %u, subpath: %u", + static_cast<unsigned int>(pa.size()), static_cast<unsigned int>(pb.size()), + static_cast<unsigned int>(i)); TS_FAIL(temp); return false; } - for(size_t j=0; j<pa.size(); j++) { - Geom::Curve const* ca = &pa[j]; - Geom::Curve const* cb = &pb[j]; - if (typeid(*ca) == typeid(*cb)) - { - if(Geom::LineSegment const *la = dynamic_cast<Geom::LineSegment const*>(ca)) - { - Geom::LineSegment const *lb = dynamic_cast<Geom::LineSegment const*>(cb); - if (!Geom::are_near((*la)[0],(*lb)[0], eps)) { + for (size_t j = 0; j < pa.size(); j++) { + Geom::Curve const *ca = &pa[j]; + Geom::Curve const *cb = &pb[j]; + if (typeid(*ca) == typeid(*cb)) { + if (Geom::LineSegment const *la = dynamic_cast<Geom::LineSegment const *>(ca)) { + Geom::LineSegment const *lb = dynamic_cast<Geom::LineSegment const *>(cb); + if (!Geom::are_near((*la)[0], (*lb)[0], eps)) { char temp[200]; - sprintf(temp, "Different start of segment: (%g,%g) != (%g,%g), subpath: %u, segment: %u", (*la)[0][Geom::X], (*la)[0][Geom::Y], (*lb)[0][Geom::X], (*lb)[0][Geom::Y], static_cast<unsigned int>(i), static_cast<unsigned int>(j)); + sprintf(temp, "Different start of segment: (%g,%g) != (%g,%g), subpath: %u, segment: %u", + (*la)[0][Geom::X], (*la)[0][Geom::Y], (*lb)[0][Geom::X], (*lb)[0][Geom::Y], + static_cast<unsigned int>(i), static_cast<unsigned int>(j)); TS_FAIL(temp); return false; } - if (!Geom::are_near((*la)[1],(*lb)[1], eps)) { + if (!Geom::are_near((*la)[1], (*lb)[1], eps)) { char temp[200]; - sprintf(temp, "Different end of segment: (%g,%g) != (%g,%g), subpath: %u, segment: %u", (*la)[1][Geom::X], (*la)[1][Geom::Y], (*lb)[1][Geom::X], (*lb)[1][Geom::Y], static_cast<unsigned int>(i), static_cast<unsigned int>(j)); + sprintf(temp, "Different end of segment: (%g,%g) != (%g,%g), subpath: %u, segment: %u", + (*la)[1][Geom::X], (*la)[1][Geom::Y], (*lb)[1][Geom::X], (*lb)[1][Geom::Y], + static_cast<unsigned int>(i), static_cast<unsigned int>(j)); TS_FAIL(temp); return false; } - } - else if(Geom::CubicBezier const *la = dynamic_cast<Geom::CubicBezier const*>(ca)) - { - Geom::CubicBezier const *lb = dynamic_cast<Geom::CubicBezier const*>(cb); - if (!Geom::are_near((*la)[0],(*lb)[0], eps)) { + } else if (Geom::CubicBezier const *la = dynamic_cast<Geom::CubicBezier const *>(ca)) { + Geom::CubicBezier const *lb = dynamic_cast<Geom::CubicBezier const *>(cb); + if (!Geom::are_near((*la)[0], (*lb)[0], eps)) { char temp[200]; - sprintf(temp, "Different start of segment: (%g,%g) != (%g,%g), subpath: %u, segment: %u", (*la)[0][Geom::X], (*la)[0][Geom::Y], (*lb)[0][Geom::X], (*lb)[0][Geom::Y], static_cast<unsigned int>(i), static_cast<unsigned int>(j)); + sprintf(temp, "Different start of segment: (%g,%g) != (%g,%g), subpath: %u, segment: %u", + (*la)[0][Geom::X], (*la)[0][Geom::Y], (*lb)[0][Geom::X], (*lb)[0][Geom::Y], + static_cast<unsigned int>(i), static_cast<unsigned int>(j)); TS_FAIL(temp); return false; } - if (!Geom::are_near((*la)[1],(*lb)[1], eps)) { + if (!Geom::are_near((*la)[1], (*lb)[1], eps)) { char temp[200]; - sprintf(temp, "Different 1st control point: (%g,%g) != (%g,%g), subpath: %u, segment: %u", (*la)[1][Geom::X], (*la)[1][Geom::Y], (*lb)[1][Geom::X], (*lb)[1][Geom::Y], static_cast<unsigned int>(i), static_cast<unsigned int>(j)); + sprintf(temp, "Different 1st control point: (%g,%g) != (%g,%g), subpath: %u, segment: %u", + (*la)[1][Geom::X], (*la)[1][Geom::Y], (*lb)[1][Geom::X], (*lb)[1][Geom::Y], + static_cast<unsigned int>(i), static_cast<unsigned int>(j)); TS_FAIL(temp); return false; } - if (!Geom::are_near((*la)[2],(*lb)[2], eps)) { + if (!Geom::are_near((*la)[2], (*lb)[2], eps)) { char temp[200]; - sprintf(temp, "Different 2nd control point: (%g,%g) != (%g,%g), subpath: %u, segment: %u", (*la)[2][Geom::X], (*la)[2][Geom::Y], (*lb)[2][Geom::X], (*lb)[2][Geom::Y], static_cast<unsigned int>(i), static_cast<unsigned int>(j)); + sprintf(temp, "Different 2nd control point: (%g,%g) != (%g,%g), subpath: %u, segment: %u", + (*la)[2][Geom::X], (*la)[2][Geom::Y], (*lb)[2][Geom::X], (*lb)[2][Geom::Y], + static_cast<unsigned int>(i), static_cast<unsigned int>(j)); TS_FAIL(temp); return false; } - if (!Geom::are_near((*la)[3],(*lb)[3], eps)) { + if (!Geom::are_near((*la)[3], (*lb)[3], eps)) { char temp[200]; - sprintf(temp, "Different end of segment: (%g,%g) != (%g,%g), subpath: %u, segment: %u", (*la)[3][Geom::X], (*la)[3][Geom::Y], (*lb)[3][Geom::X], (*lb)[3][Geom::Y], static_cast<unsigned int>(i), static_cast<unsigned int>(j)); + sprintf(temp, "Different end of segment: (%g,%g) != (%g,%g), subpath: %u, segment: %u", + (*la)[3][Geom::X], (*la)[3][Geom::Y], (*lb)[3][Geom::X], (*lb)[3][Geom::Y], + static_cast<unsigned int>(i), static_cast<unsigned int>(j)); TS_FAIL(temp); return false; } - } - else - { + } else { char temp[200]; - sprintf(temp, "Unknown curve type: %s, subpath: %u, segment: %u", typeid(*ca).name(), static_cast<unsigned int>(i), static_cast<unsigned int>(j)); + sprintf(temp, "Unknown curve type: %s, subpath: %u, segment: %u", typeid(*ca).name(), + static_cast<unsigned int>(i), static_cast<unsigned int>(j)); TS_FAIL(temp); } - } - else // not same type + } else // not same type { char temp[200]; - sprintf(temp, "Different curve types: %s != %s, subpath: %u, segment: %u", typeid(*ca).name(), typeid(*cb).name(), static_cast<unsigned int>(i), static_cast<unsigned int>(j)); + sprintf(temp, "Different curve types: %s != %s, subpath: %u, segment: %u", typeid(*ca).name(), + typeid(*cb).name(), static_cast<unsigned int>(i), static_cast<unsigned int>(j)); TS_FAIL(temp); return false; } @@ -510,7 +553,6 @@ private: } }; - /* Local Variables: mode:c++ diff --git a/src/svg/svg-path.cpp b/src/svg/svg-path.cpp index 1414d69725f37c37e5bd533faca0580f787b8cdc..a7c5dafe45418eb405bf262ddebc6422f6c3ea88 100644 --- a/src/svg/svg-path.cpp +++ b/src/svg/svg-path.cpp @@ -16,29 +16,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> -#include <string> -#include <glib.h> // g_assert() - -#include <2geom/pathvector.h> #include <2geom/curves.h> -#include <2geom/sbasis-to-bezier.h> #include <2geom/path-sink.h> +#include <2geom/pathvector.h> +#include <2geom/sbasis-to-bezier.h> #include <2geom/svg-path-parser.h> +#include <cstring> +#include <glib.h> // g_assert() +#include <string> -#include "svg/svg.h" #include "svg/path-string.h" +#include "svg/svg.h" /* * Parses the path in str. When an error is found in the pathstring, this method * returns a truncated path up to where the error was found in the pathstring. * Returns an empty PathVector when str==NULL */ -Geom::PathVector sp_svg_read_pathv(char const * str) +Geom::PathVector sp_svg_read_pathv(char const *str) { Geom::PathVector pathv; if (!str) - return pathv; // return empty pathvector when str == NULL + return pathv; // return empty pathvector when str == NULL Geom::PathBuilder builder(pathv); Geom::SVGPathParser parser(builder); @@ -46,59 +45,56 @@ Geom::PathVector sp_svg_read_pathv(char const * str) try { parser.parse(str); - } - catch (Geom::SVGPathParseError &e) { + } catch (Geom::SVGPathParseError &e) { builder.flush(); // This warning is extremely annoying when testing - //g_warning("Malformed SVG path, truncated path up to where error was found.\n Input path=\"%s\"\n Parsed path=\"%s\"", str, sp_svg_write_path(pathv)); + // g_warning("Malformed SVG path, truncated path up to where error was found.\n Input path=\"%s\"\n Parsed + // path=\"%s\"", str, sp_svg_write_path(pathv)); } return pathv; } -static void sp_svg_write_curve(Inkscape::SVG::PathString & str, Geom::Curve const * c) { +static void sp_svg_write_curve(Inkscape::SVG::PathString &str, Geom::Curve const *c) +{ // TODO: this code needs to removed and replaced by appropriate path sink - if(Geom::LineSegment const *line_segment = dynamic_cast<Geom::LineSegment const *>(c)) { + if (Geom::LineSegment const *line_segment = dynamic_cast<Geom::LineSegment const *>(c)) { // don't serialize stitch segments if (!dynamic_cast<Geom::Path::StitchSegment const *>(c)) { if (line_segment->initialPoint()[Geom::X] == line_segment->finalPoint()[Geom::X]) { - str.verticalLineTo( line_segment->finalPoint()[Geom::Y] ); + str.verticalLineTo(line_segment->finalPoint()[Geom::Y]); } else if (line_segment->initialPoint()[Geom::Y] == line_segment->finalPoint()[Geom::Y]) { - str.horizontalLineTo( line_segment->finalPoint()[Geom::X] ); + str.horizontalLineTo(line_segment->finalPoint()[Geom::X]); } else { - str.lineTo( (*line_segment)[1][0], (*line_segment)[1][1] ); + str.lineTo((*line_segment)[1][0], (*line_segment)[1][1]); } } - } - else if(Geom::QuadraticBezier const *quadratic_bezier = dynamic_cast<Geom::QuadraticBezier const *>(c)) { - str.quadTo( (*quadratic_bezier)[1][0], (*quadratic_bezier)[1][1], - (*quadratic_bezier)[2][0], (*quadratic_bezier)[2][1] ); - } - else if(Geom::CubicBezier const *cubic_bezier = dynamic_cast<Geom::CubicBezier const *>(c)) { - str.curveTo( (*cubic_bezier)[1][0], (*cubic_bezier)[1][1], - (*cubic_bezier)[2][0], (*cubic_bezier)[2][1], - (*cubic_bezier)[3][0], (*cubic_bezier)[3][1] ); - } - else if(Geom::EllipticalArc const *elliptical_arc = dynamic_cast<Geom::EllipticalArc const *>(c)) { - str.arcTo( elliptical_arc->ray(Geom::X), elliptical_arc->ray(Geom::Y), - Geom::deg_from_rad(elliptical_arc->rotationAngle()), - elliptical_arc->largeArc(), elliptical_arc->sweep(), - elliptical_arc->finalPoint() ); - } else { - //this case handles sbasis as well as all other curve types + } else if (Geom::QuadraticBezier const *quadratic_bezier = dynamic_cast<Geom::QuadraticBezier const *>(c)) { + str.quadTo((*quadratic_bezier)[1][0], (*quadratic_bezier)[1][1], (*quadratic_bezier)[2][0], + (*quadratic_bezier)[2][1]); + } else if (Geom::CubicBezier const *cubic_bezier = dynamic_cast<Geom::CubicBezier const *>(c)) { + str.curveTo((*cubic_bezier)[1][0], (*cubic_bezier)[1][1], (*cubic_bezier)[2][0], (*cubic_bezier)[2][1], + (*cubic_bezier)[3][0], (*cubic_bezier)[3][1]); + } else if (Geom::EllipticalArc const *elliptical_arc = dynamic_cast<Geom::EllipticalArc const *>(c)) { + str.arcTo(elliptical_arc->ray(Geom::X), elliptical_arc->ray(Geom::Y), + Geom::deg_from_rad(elliptical_arc->rotationAngle()), elliptical_arc->largeArc(), + elliptical_arc->sweep(), elliptical_arc->finalPoint()); + } else { + // this case handles sbasis as well as all other curve types Geom::Path sbasis_path = Geom::cubicbezierpath_from_sbasis(c->toSBasis(), 0.1); - //recurse to convert the new path resulting from the sbasis to svgd - for(const auto & iter : sbasis_path) { + // recurse to convert the new path resulting from the sbasis to svgd + for (const auto &iter : sbasis_path) { sp_svg_write_curve(str, &iter); } } } -static void sp_svg_write_path(Inkscape::SVG::PathString & str, Geom::Path const & p) { - str.moveTo( p.initialPoint()[0], p.initialPoint()[1] ); +static void sp_svg_write_path(Inkscape::SVG::PathString &str, Geom::Path const &p) +{ + str.moveTo(p.initialPoint()[0], p.initialPoint()[1]); - for(Geom::Path::const_iterator cit = p.begin(); cit != p.end_open(); ++cit) { + for (Geom::Path::const_iterator cit = p.begin(); cit != p.end_open(); ++cit) { sp_svg_write_curve(str, &(*cit)); } @@ -107,17 +103,19 @@ static void sp_svg_write_path(Inkscape::SVG::PathString & str, Geom::Path const } } -gchar * sp_svg_write_path(Geom::PathVector const &p) { +gchar *sp_svg_write_path(Geom::PathVector const &p) +{ Inkscape::SVG::PathString str; - for(const auto & pit : p) { + for (const auto &pit : p) { sp_svg_write_path(str, pit); } return g_strdup(str.c_str()); } -gchar * sp_svg_write_path(Geom::Path const &p) { +gchar *sp_svg_write_path(Geom::Path const &p) +{ Inkscape::SVG::PathString str; sp_svg_write_path(str, p); diff --git a/src/svg/svg.h b/src/svg/svg.h index a65bdf26c0513c474e0cd60ce31fc9eb213b98cf..189f749744ffdf602ed24060a7cf4d5eb4509f0f 100644 --- a/src/svg/svg.h +++ b/src/svg/svg.h @@ -13,12 +13,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <vector> +#include <2geom/forward.h> #include <cstring> #include <string> +#include <vector> #include "svg/svg-length.h" -#include <2geom/forward.h> /* Generic */ @@ -29,13 +29,13 @@ * Return FALSE and let val untouched on error */ -unsigned int sp_svg_number_read_f( const char *str, float *val ); -unsigned int sp_svg_number_read_d( const char *str, double *val ); +unsigned int sp_svg_number_read_f(const char *str, float *val); +unsigned int sp_svg_number_read_d(const char *str, double *val); /* * No buffer overflow checking is done, so better wrap them if needed */ -unsigned int sp_svg_number_write_de( char *buf, int bufLen, double val, unsigned int tprec, int min_exp ); +unsigned int sp_svg_number_write_de(char *buf, int bufLen, double val, unsigned int tprec, int min_exp); /* Length */ @@ -48,9 +48,9 @@ unsigned int sp_svg_number_write_de( char *buf, int bufLen, double val, unsigned * Any return value pointer can be NULL */ -unsigned int sp_svg_length_read_computed_absolute( const char *str, float *length ); -std::vector<SVGLength> sp_svg_length_list_read( const char *str ); -unsigned int sp_svg_length_read_ldd( const char *str, SVGLength::Unit *unit, double *value, double *computed ); +unsigned int sp_svg_length_read_computed_absolute(const char *str, float *length); +std::vector<SVGLength> sp_svg_length_list_read(const char *str); +unsigned int sp_svg_length_read_ldd(const char *str, SVGLength::Unit *unit, double *value, double *computed); std::string sp_svg_length_write_with_units(SVGLength const &length); @@ -59,13 +59,13 @@ bool sp_svg_transform_read(char const *str, Geom::Affine *transform); char *sp_svg_transform_write(Geom::Affine const &transform); char *sp_svg_transform_write(Geom::Affine const *transform); -double sp_svg_read_percentage( const char * str, double def ); +double sp_svg_read_percentage(const char *str, double def); /* NB! As paths can be long, we use here dynamic string */ -Geom::PathVector sp_svg_read_pathv( char const * str ); -char * sp_svg_write_path( Geom::PathVector const &p ); -char * sp_svg_write_path( Geom::Path const &p ); +Geom::PathVector sp_svg_read_pathv(char const *str); +char *sp_svg_write_path(Geom::PathVector const &p); +char *sp_svg_write_path(Geom::Path const &p); #endif // SEEN_SP_SVG_H diff --git a/src/svg/test-stubs.cpp b/src/svg/test-stubs.cpp index b511c7e887971b2a8fb24bc6da28f93a0f2fb817..ebcdf5b98457ce1c93d63b6e59038ef81d7707f1 100644 --- a/src/svg/test-stubs.cpp +++ b/src/svg/test-stubs.cpp @@ -10,24 +10,23 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "svg/test-stubs.h" + #include <map> #include <string> -std::map<std::string,long long int> int_prefs; +std::map<std::string, long long int> int_prefs; -void -prefs_set_int_attribute(gchar const *path, gchar const *attr, long long int val) +void prefs_set_int_attribute(gchar const *path, gchar const *attr, long long int val) { int_prefs[std::string(path) + '/' + std::string(attr)] = val; } -long long int -prefs_get_int_attribute(gchar const *path, gchar const *attr, long long int def) +long long int prefs_get_int_attribute(gchar const *path, gchar const *attr, long long int def) { - std::map<std::string,long long int>::const_iterator it=int_prefs.find(std::string(path) + '/' + std::string(attr)); - long long int ret = it==int_prefs.end() ? def : it->second; + std::map<std::string, long long int>::const_iterator it = + int_prefs.find(std::string(path) + '/' + std::string(attr)); + long long int ret = it == int_prefs.end() ? def : it->second; return ret; } diff --git a/src/syseq.h b/src/syseq.h index 3bd09f1068351b02b082e7e5d0556963049f4ed1..a506a96515a9bb10d49ba215eaf64cdd4879461f 100644 --- a/src/syseq.h +++ b/src/syseq.h @@ -14,21 +14,23 @@ */ #include <algorithm> -#include <iostream> +#include <cmath> #include <iomanip> +#include <iostream> #include <vector> -#include <cmath> namespace SysEq { -enum SolutionKind { +enum SolutionKind +{ unique = 0, ambiguous, no_solution, solution_exists // FIXME: remove this; does not yield enough information }; -inline void explain(SolutionKind sol) { +inline void explain(SolutionKind sol) +{ switch (sol) { case SysEq::unique: std::cout << "unique" << std::endl; @@ -45,30 +47,23 @@ inline void explain(SolutionKind sol) { } } -inline double -determinant3x3 (double A[3][3]) { - return (A[0][0]*A[1][1]*A[2][2] + - A[0][1]*A[1][2]*A[2][0] + - A[0][2]*A[1][0]*A[2][1] - - A[0][0]*A[1][2]*A[2][1] - - A[0][1]*A[1][0]*A[2][2] - - A[0][2]*A[1][1]*A[2][0]); +inline double determinant3x3(double A[3][3]) +{ + return (A[0][0] * A[1][1] * A[2][2] + A[0][1] * A[1][2] * A[2][0] + A[0][2] * A[1][0] * A[2][1] - + A[0][0] * A[1][2] * A[2][1] - A[0][1] * A[1][0] * A[2][2] - A[0][2] * A[1][1] * A[2][0]); } /* Determinant of the 3x3 matrix having a, b, and c as columns */ -inline double -determinant3v (const double a[3], const double b[3], const double c[3]) { - return (a[0]*b[1]*c[2] + - a[1]*b[2]*c[0] + - a[2]*b[0]*c[1] - - a[0]*b[2]*c[1] - - a[1]*b[0]*c[2] - - a[2]*b[1]*c[0]); +inline double determinant3v(const double a[3], const double b[3], const double c[3]) +{ + return (a[0] * b[1] * c[2] + a[1] * b[2] * c[0] + a[2] * b[0] * c[1] - a[0] * b[2] * c[1] - a[1] * b[0] * c[2] - + a[2] * b[1] * c[0]); } /* Copy the elements of A into B */ template <int S, int T> -inline void copy_mat(double A[S][T], double B[S][T]) { +inline void copy_mat(double A[S][T], double B[S][T]) +{ for (int i = 0; i < S; ++i) { for (int j = 0; j < T; ++j) { B[i][j] = A[i][j]; @@ -77,19 +72,22 @@ inline void copy_mat(double A[S][T], double B[S][T]) { } template <int S, int T> -inline void print_mat (const double A[S][T]) { +inline void print_mat(const double A[S][T]) +{ std::cout.setf(std::ios::left, std::ios::internal); for (int i = 0; i < S; ++i) { for (int j = 0; j < T; ++j) { - printf ("%8.2f ", A[i][j]); + printf("%8.2f ", A[i][j]); } - std::cout << std::endl;; - } + std::cout << std::endl; + ; + } } /* Multiplication of two matrices */ template <int S, int U, int T> -inline void multiply(double A[S][U], double B[U][T], double res[S][T]) { +inline void multiply(double A[S][U], double B[U][T], double res[S][T]) +{ for (int i = 0; i < S; ++i) { for (int j = 0; j < T; ++j) { double sum = 0; @@ -106,7 +104,8 @@ inline void multiply(double A[S][U], double B[U][T], double res[S][T]) { * multiplication function we would always have to write v[i][0] for elements of the vector. */ template <int S, int T> -inline void multiply(double A[S][T], double v[T], double res[S]) { +inline void multiply(double A[S][T], double v[T], double res[S]) +{ for (int i = 0; i < S; ++i) { double sum = 0; for (int k = 0; k < T; ++k) { @@ -122,11 +121,12 @@ inline void multiply(double A[S][T], double v[T], double res[S]) { // instead of double[S][T]. This would allow us to avoid templates. Would the performance degrade? /* - * Find the element of maximal absolute value in row i that + * Find the element of maximal absolute value in row i that * does not lie in one of the columns given in avoid_cols. */ template <int S, int T> -static int find_pivot(const double A[S][T], unsigned int i, std::vector<int> const &avoid_cols) { +static int find_pivot(const double A[S][T], unsigned int i, std::vector<int> const &avoid_cols) +{ if (i >= S) { return -1; } @@ -149,42 +149,48 @@ static int find_pivot(const double A[S][T], unsigned int i, std::vector<int> con * two vectors). */ template <int S, int T> -static void gauss_jordan_step (double A[S][T], int row, int col) { +static void gauss_jordan_step(double A[S][T], int row, int col) +{ double piv = A[row][col]; // pivot element /* adapt the entries of the matrix, first outside the pivot row/column */ for (int k = 0; k < S; ++k) { - if (k == row) continue; + if (k == row) + continue; for (int l = 0; l < T; ++l) { - if (l == col) continue; + if (l == col) + continue; A[k][l] -= A[k][col] * A[row][l] / piv; } } /* now adapt the pivot column ... */ for (int k = 0; k < S; ++k) { - if (k == row) continue; - A[k][col] /= piv; + if (k == row) + continue; + A[k][col] /= piv; } /* and the pivot row */ for (int l = 0; l < T; ++l) { - if (l == col) continue; - A[row][l] /= -piv; + if (l == col) + continue; + A[row][l] /= -piv; } /* finally, set the element at the pivot position itself */ - A[row][col] = 1/piv; + A[row][col] = 1 / piv; } /* * Perform Gauss-Jordan elimination on the matrix A, optionally avoiding a given column during pivot search */ template <int S, int T> -static std::vector<int> gauss_jordan (double A[S][T], int avoid_col = -1) { +static std::vector<int> gauss_jordan(double A[S][T], int avoid_col = -1) +{ std::vector<int> cols_used; if (avoid_col != -1) { - cols_used.push_back (avoid_col); + cols_used.push_back(avoid_col); } for (int i = 0; i < S; ++i) { /* for each row find a pivot element of maximal absolute value, skipping the columns that were used before */ - int col = find_pivot<S,T>(A, i, cols_used); + int col = find_pivot<S, T>(A, i, cols_used); cols_used.push_back(col); if (col == -1) { // no non-zero elements in the row @@ -192,7 +198,7 @@ static std::vector<int> gauss_jordan (double A[S][T], int avoid_col = -1) { } /* if pivot search was successful we can perform a Gauss-Jordan step */ - gauss_jordan_step<S,T> (A, i, col); + gauss_jordan_step<S, T>(A, i, col); } if (avoid_col != -1) { // since the columns that were used will be needed later on, we need to clean up the column vector @@ -203,13 +209,14 @@ static std::vector<int> gauss_jordan (double A[S][T], int avoid_col = -1) { /* compute the modified value that x[index] needs to assume so that in the end we have x[index]/x[T-1] = val */ template <int S, int T> -static double projectify (std::vector<int> const &cols, const double B[S][T], const double x[T], - const int index, const double val) { +static double projectify(std::vector<int> const &cols, const double B[S][T], const double x[T], const int index, + const double val) +{ double val_proj = 0.0; if (index != -1) { int c = -1; for (int i = 0; i < S; ++i) { - if (cols[i] == T-1) { + if (cols[i] == T - 1) { c = i; break; } @@ -221,7 +228,8 @@ static double projectify (std::vector<int> const &cols, const double B[S][T], co double sp = 0; for (int j = 0; j < T; ++j) { - if (j == index) continue; + if (j == index) + continue; sp += B[c][j] * x[j]; } double mu = 1 - val * B[c][index]; @@ -229,7 +237,7 @@ static double projectify (std::vector<int> const &cols, const double B[S][T], co std::cout << "No solution since adapted value is too close to zero" << std::endl; return SysEq::no_solution; } - val_proj = sp*val/mu; + val_proj = sp * val / mu; } else { val_proj = val; // FIXME: Is this correct? } @@ -251,12 +259,14 @@ static double projectify (std::vector<int> const &cols, const double B[S][T], co * Remark: We don't need this but it would be relatively simple to let the calling function * prescripe the value of _multiple_ components of the solution vector instead of only a single one. */ -template <int S, int T> SolutionKind gaussjord_solve (double A[S][T], double x[T], double v[S], - int index = -1, double val = 0.0, bool proj = false) { +template <int S, int T> +SolutionKind gaussjord_solve(double A[S][T], double x[T], double v[S], int index = -1, double val = 0.0, + bool proj = false) +{ double B[S][T]; - //copy_mat<S,T>(A,B); - SysEq::copy_mat<S,T>(A,B); - std::vector<int> cols = gauss_jordan<S,T>(B, index); + // copy_mat<S,T>(A,B); + SysEq::copy_mat<S, T>(A, B); + std::vector<int> cols = gauss_jordan<S, T>(B, index); if (std::find(cols.begin(), cols.end(), -1) != cols.end()) { // pivot search failed for some row so the system is not solvable return SysEq::no_solution; @@ -277,7 +287,7 @@ template <int S, int T> SolutionKind gaussjord_solve (double A[S][T], double x[T } // we need to adapt the value if we are in the "projective case" (see above) - double val_new = (proj ? projectify<S,T>(cols, B, x, index, val) : val); + double val_new = (proj ? projectify<S, T>(cols, B, x, index, val) : val); if (index >= 0 && index < T) { // we want the specified coefficient of the solution vector to have a given value @@ -289,7 +299,7 @@ template <int S, int T> SolutionKind gaussjord_solve (double A[S][T], double x[T * afterwards copy the result back to x */ double w[S]; - SysEq::multiply<S,T>(B,x,w); // initializes w + SysEq::multiply<S, T>(B, x, w); // initializes w for (int j = 0; j < S; ++j) { x[cols[j]] = w[j]; } diff --git a/src/text-chemistry-impl.h b/src/text-chemistry-impl.h index 71352f767d4eef517fdbe7259038e165d6858f63..c370722fd77c497d9209faa0f78ddac308bb3eb2 100644 --- a/src/text-chemistry-impl.h +++ b/src/text-chemistry-impl.h @@ -13,23 +13,26 @@ */ #include <algorithm> + +#include "document.h" #include "style.h" #include "xml/node.h" -#include "document.h" -Glib::ustring text_relink_shapes_str(gchar const *prop, - std::map<Glib::ustring, Glib::ustring> const &old_to_new); +Glib::ustring text_relink_shapes_str(gchar const *prop, std::map<Glib::ustring, Glib::ustring> const &old_to_new); -inline Inkscape::XML::Node *text_obj_or_node_to_node(SPObject *obj) { +inline Inkscape::XML::Node *text_obj_or_node_to_node(SPObject *obj) +{ return obj->getRepr(); } -inline Inkscape::XML::Node *text_obj_or_node_to_node(Inkscape::XML::Node *node) { +inline Inkscape::XML::Node *text_obj_or_node_to_node(Inkscape::XML::Node *node) +{ return node; } -template<typename InIter> -text_refs_t text_categorize_refs(SPDocument *doc, InIter begin, InIter end, text_ref_t which) { +template <typename InIter> +text_refs_t text_categorize_refs(SPDocument *doc, InIter begin, InIter end, text_ref_t which) +{ text_refs_t res; std::set<Glib::ustring> int_ext; auto idVisitor = [which, &res, &int_ext](SPShapeReference *href) { @@ -48,25 +51,24 @@ text_refs_t text_categorize_refs(SPDocument *doc, InIter begin, InIter end, text // Visit all shape references, detect the refs, and put internal and // external ids in int_ext. for (auto it = begin; it != end; ++it) { - sp_repr_visit_descendants( - text_obj_or_node_to_node(*it), - [doc, &int_ext, &idVisitor](Inkscape::XML::Node *crnt) { - if (!(crnt->name() && strcmp("svg:text", crnt->name()) == 0)) { - return true; - } - - auto crnt_obj = doc->getObjectByRepr(crnt); - assert(crnt_obj == doc->getObjectById(crnt->attribute("id"))); - { - const auto &inside_ids = crnt_obj->style->shape_inside.hrefs; - std::for_each(inside_ids.begin(), inside_ids.end(), idVisitor); - - const auto &subtract_ids = crnt_obj->style->shape_subtract.hrefs; - std::for_each(subtract_ids.begin(), subtract_ids.end(), idVisitor); - } - // Do not recurse into svg:text elements children - return false; - }); + sp_repr_visit_descendants(text_obj_or_node_to_node(*it), + [doc, &int_ext, &idVisitor](Inkscape::XML::Node *crnt) { + if (!(crnt->name() && strcmp("svg:text", crnt->name()) == 0)) { + return true; + } + + auto crnt_obj = doc->getObjectByRepr(crnt); + assert(crnt_obj == doc->getObjectById(crnt->attribute("id"))); + { + const auto &inside_ids = crnt_obj->style->shape_inside.hrefs; + std::for_each(inside_ids.begin(), inside_ids.end(), idVisitor); + + const auto &subtract_ids = crnt_obj->style->shape_subtract.hrefs; + std::for_each(subtract_ids.begin(), subtract_ids.end(), idVisitor); + } + // Do not recurse into svg:text elements children + return false; + }); } if (!(which & (TEXT_REF_INTERNAL | TEXT_REF_EXTERNAL))) { @@ -77,10 +79,7 @@ text_refs_t text_categorize_refs(SPDocument *doc, InIter begin, InIter end, text // Visit all root elements, recursively and see which ones are in int_ext, // therefore discovering the internal ids. for (auto it = begin; it != end; ++it) { - sp_repr_visit_descendants( - text_obj_or_node_to_node(*it), - [which, &res, &int_ext](Inkscape::XML::Node *crnt) { - + sp_repr_visit_descendants(text_obj_or_node_to_node(*it), [which, &res, &int_ext](Inkscape::XML::Node *crnt) { auto id = crnt->attribute("id"); auto find_iter = id ? int_ext.find(id) : int_ext.end(); if (find_iter != int_ext.end()) { @@ -106,8 +105,9 @@ text_refs_t text_categorize_refs(SPDocument *doc, InIter begin, InIter end, text return res; } -template<typename InIterOrig, typename InIterCopy> -void text_relink_refs(text_refs_t const &refs, InIterOrig origBegin, InIterOrig origEnd, InIterCopy copyBegin) { +template <typename InIterOrig, typename InIterCopy> +void text_relink_refs(text_refs_t const &refs, InIterOrig origBegin, InIterOrig origEnd, InIterCopy copyBegin) +{ // get all ids of text refs std::set<Glib::ustring> all_refs; for (auto const &ref : refs) { @@ -117,35 +117,31 @@ void text_relink_refs(text_refs_t const &refs, InIterOrig origBegin, InIterOrig // find a mapping from old ids to new ids std::map<Glib::ustring, Glib::ustring> old_to_new; for (auto itOrig = origBegin, itCopy = copyBegin; itOrig != origEnd; ++itOrig, ++itCopy) { - sp_repr_visit_descendants( - text_obj_or_node_to_node(*itOrig), - text_obj_or_node_to_node(*itCopy), - [&all_refs, &old_to_new](Inkscape::XML::Node *a, Inkscape::XML::Node *b) { - if (a->attribute("id") && all_refs.find(a->attribute("id")) != all_refs.end()) { - old_to_new[a->attribute("id")] = b->attribute("id"); - return false; - } - return true; - }); + sp_repr_visit_descendants(text_obj_or_node_to_node(*itOrig), text_obj_or_node_to_node(*itCopy), + [&all_refs, &old_to_new](Inkscape::XML::Node *a, Inkscape::XML::Node *b) { + if (a->attribute("id") && all_refs.find(a->attribute("id")) != all_refs.end()) { + old_to_new[a->attribute("id")] = b->attribute("id"); + return false; + } + return true; + }); } if (all_refs.size() != old_to_new.size()) { std::cerr << "text_relink_refs: Failed to match all references! all:" << all_refs.size() - << " matched:" << old_to_new.size() << std::endl; + << " matched:" << old_to_new.size() << std::endl; } // relink references for (auto itOrig = origBegin, itCopy = copyBegin; itOrig != origEnd; ++itOrig, ++itCopy) { - sp_repr_visit_descendants( - text_obj_or_node_to_node(*itCopy), - [&old_to_new](Inkscape::XML::Node *crnt) { + sp_repr_visit_descendants(text_obj_or_node_to_node(*itCopy), [&old_to_new](Inkscape::XML::Node *crnt) { if (strcmp("svg:text", crnt->name()) == 0) { - SPCSSAttr* css = sp_repr_css_attr (crnt, "style"); + SPCSSAttr *css = sp_repr_css_attr(crnt, "style"); for (auto &&prop : {"shape-inside", "shape-subtract"}) { if (auto prop_str = sp_repr_css_property(css, prop, nullptr)) { sp_repr_css_set_property(css, prop, text_relink_shapes_str(prop_str, old_to_new).c_str()); } } - sp_repr_css_set (crnt, css, "style"); + sp_repr_css_set(crnt, css, "style"); return false; } return true; diff --git a/src/text-chemistry.cpp b/src/text-chemistry.cpp index b1f599635e2e7deb8d5ea09fffc004d722642725..9170c974e66b3a0327dd35768734fe890c7379f6 100644 --- a/src/text-chemistry.cpp +++ b/src/text-chemistry.cpp @@ -12,21 +12,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "text-chemistry.h" + #include <cstring> -#include <string> #include <glibmm/i18n.h> #include <glibmm/regex.h> - +#include <string> #include "desktop.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" #include "message-stack.h" -#include "text-chemistry.h" -#include "text-editing.h" -#include "verbs.h" - #include "object/sp-flowdiv.h" #include "object/sp-flowregion.h" #include "object/sp-flowtext.h" @@ -34,35 +31,33 @@ #include "object/sp-textpath.h" #include "object/sp-tspan.h" #include "style.h" - +#include "text-editing.h" +#include "verbs.h" #include "xml/repr.h" using Inkscape::DocumentUndo; -static SPItem * -text_or_flowtext_in_selection(Inkscape::Selection *selection) +static SPItem *text_or_flowtext_in_selection(Inkscape::Selection *selection) { auto items = selection->items(); - for(auto i=items.begin();i!=items.end();++i){ + for (auto i = items.begin(); i != items.end(); ++i) { if (SP_IS_TEXT(*i) || SP_IS_FLOWTEXT(*i)) return *i; } return nullptr; } -static SPItem * -shape_in_selection(Inkscape::Selection *selection) +static SPItem *shape_in_selection(Inkscape::Selection *selection) { auto items = selection->items(); - for(auto i=items.begin();i!=items.end();++i){ + for (auto i = items.begin(); i != items.end(); ++i) { if (SP_IS_SHAPE(*i)) return *i; } return nullptr; } -void -text_put_on_path() +void text_put_on_path() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; if (!desktop) @@ -76,38 +71,43 @@ text_put_on_path() Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); if (!text || !shape || boost::distance(selection->items()) != 2) { - desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>a text and a path</b> to put text on path.")); + desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>a text and a path</b> to put text on path.")); return; } if (SP_IS_TEXT_TEXTPATH(text)) { - desktop->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, _("This text object is <b>already put on a path</b>. Remove it from the path first. Use <b>Shift+D</b> to look up its path.")); + desktop->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, + _("This text object is <b>already put on a path</b>. Remove it from the path " + "first. Use <b>Shift+D</b> to look up its path.")); return; } if (SP_IS_RECT(shape)) { // rect is the only SPShape which is not <path> yet, and thus SVG forbids us from putting text on it - desktop->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot put text on a rectangle in this version. Convert rectangle to path first.")); + desktop->getMessageStack()->flash( + Inkscape::ERROR_MESSAGE, + _("You cannot put text on a rectangle in this version. Convert rectangle to path first.")); return; } // if a flowed text is selected, convert it to a regular text object if (SP_IS_FLOWTEXT(text)) { - if (!SP_FLOWTEXT(text)->layout.outputExists()) { - desktop->getMessageStack()-> - flash(Inkscape::WARNING_MESSAGE, - _("The flowed text(s) must be <b>visible</b> in order to be put on a path.")); + desktop->getMessageStack()->flash( + Inkscape::WARNING_MESSAGE, + _("The flowed text(s) must be <b>visible</b> in order to be put on a path.")); } Inkscape::XML::Node *repr = SP_FLOWTEXT(text)->getAsText(); - if (!repr) return; + if (!repr) + return; Inkscape::XML::Node *parent = text->getRepr()->parent(); parent->appendChild(repr); - SPItem *new_item = (SPItem *) desktop->getDocument()->getObjectByRepr(repr); + SPItem *new_item = (SPItem *)desktop->getDocument()->getObjectByRepr(repr); new_item->doWriteTransform(text->transform); new_item->updateRepr(); @@ -130,12 +130,12 @@ text_put_on_path() Inkscape::Text::Layout::Alignment text_alignment = layout->paragraphAlignment(layout->begin()); // remove transform from text, but recursively scale text's fontsize by the expansion - SP_TEXT(text)->_adjustFontsizeRecursive (text, text->transform.descrim()); + SP_TEXT(text)->_adjustFontsizeRecursive(text, text->transform.descrim()); text->removeAttribute("transform"); // make a list of text children std::vector<Inkscape::XML::Node *> text_reprs; - for(auto& o: text->children) { + for (auto &o : text->children) { text_reprs.push_back(o.getRepr()); } @@ -152,7 +152,7 @@ text_put_on_path() } text->getRepr()->addChild(textpath, nullptr); - for (auto i=text_reprs.rbegin();i!=text_reprs.rend();++i) { + for (auto i = text_reprs.rbegin(); i != text_reprs.rend(); ++i) { // Make a copy of each text child Inkscape::XML::Node *copy = (*i)->duplicate(xml_doc); // We cannot have multiline in textpath, so remove line attrs from tspans @@ -171,25 +171,24 @@ text_put_on_path() text->removeAttribute("x"); text->removeAttribute("y"); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Put text on path")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Put text on path")); } -void -text_remove_from_path() +void text_remove_from_path() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; Inkscape::Selection *selection = desktop->getSelection(); if (selection->isEmpty()) { - desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>a text on path</b> to remove it from path.")); + desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>a text on path</b> to remove it from path.")); return; } bool did = false; auto items = selection->items(); - for(auto i=items.begin();i!=items.end();++i){ + for (auto i = items.begin(); i != items.end(); ++i) { SPObject *obj = *i; if (SP_IS_TEXT_TEXTPATH(obj)) { @@ -204,15 +203,13 @@ text_remove_from_path() if (!did) { desktop->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No texts-on-paths</b> in the selection.")); } else { - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Remove text from path")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Remove text from path")); std::vector<SPItem *> vec(selection->items().begin(), selection->items().end()); selection->setList(vec); // reselect to update statusbar description } } -static void -text_remove_all_kerns_recursively(SPObject *o) +static void text_remove_all_kerns_recursively(SPObject *o) { o->removeAttribute("dx"); o->removeAttribute("dy"); @@ -232,15 +229,14 @@ text_remove_all_kerns_recursively(SPObject *o) g_strfreev(xa_comma); } - for (auto& i: o->children) { + for (auto &i : o->children) { text_remove_all_kerns_recursively(&i); i.requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_TEXT_LAYOUT_MODIFIED_FLAG); } } -//FIXME: must work with text selection -void -text_remove_all_kerns() +// FIXME: must work with text selection +void text_remove_all_kerns() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; @@ -254,7 +250,7 @@ text_remove_all_kerns() bool did = false; auto items = selection->items(); - for(auto i=items.begin();i!=items.end();++i){ + for (auto i = items.begin(); i != items.end(); ++i) { SPObject *obj = *i; if (!SP_IS_TEXT(obj) && !SP_IS_TSPAN(obj) && !SP_IS_FLOWTEXT(obj)) { @@ -269,13 +265,11 @@ text_remove_all_kerns() if (!did) { desktop->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>text(s)</b> to remove kerns from.")); } else { - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Remove manual kerns")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Remove manual kerns")); } } -void -text_flow_into_shape() +void text_flow_into_shape() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; if (!desktop) @@ -290,7 +284,9 @@ text_flow_into_shape() SPItem *shape = shape_in_selection(selection); if (!text || !shape || boost::distance(selection->items()) < 2) { - desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>a text</b> and one or more <b>paths or shapes</b> to flow text into frame.")); + desktop->getMessageStack()->flash( + Inkscape::WARNING_MESSAGE, + _("Select <b>a text</b> and one or more <b>paths or shapes</b> to flow text into frame.")); return; } @@ -299,7 +295,6 @@ text_flow_into_shape() // SVG 2 Text if (SP_IS_TEXT(text)) { - // Make list of all shapes. Glib::ustring shape_inside; auto items = selection->items(); @@ -313,19 +308,17 @@ text_flow_into_shape() // Remove extra space at end. if (shape_inside.length() > 1) { - shape_inside.erase (shape_inside.length() - 1); + shape_inside.erase(shape_inside.length() - 1); } // Set 'shape-inside' property. - SPCSSAttr* css = sp_repr_css_attr (text->getRepr(), "style"); - sp_repr_css_set_property (css, "shape-inside", shape_inside.c_str()); - sp_repr_css_set_property (css, "white-space", "pre"); // Respect new lines. - sp_repr_css_set (text->getRepr(), css, "style"); + SPCSSAttr *css = sp_repr_css_attr(text->getRepr(), "style"); + sp_repr_css_set_property(css, "shape-inside", shape_inside.c_str()); + sp_repr_css_set_property(css, "white-space", "pre"); // Respect new lines. + sp_repr_css_set(text->getRepr(), css, "style"); } - DocumentUndo::done(doc, SP_VERB_CONTEXT_TEXT, - _("Flow text into shape")); - + DocumentUndo::done(doc, SP_VERB_CONTEXT_TEXT, _("Flow text into shape")); } else { // SVG 1.2 Flowed Text @@ -351,9 +344,9 @@ text_flow_into_shape() /* Add clones */ auto items = selection->items(); - for(auto i=items.begin();i!=items.end();++i){ + for (auto i = items.begin(); i != items.end(); ++i) { SPItem *item = *i; - if (SP_IS_SHAPE(item)){ + if (SP_IS_SHAPE(item)) { Inkscape::XML::Node *clone = xml_doc->createElement("svg:use"); clone->setAttribute("x", "0"); clone->setAttribute("y", "0"); @@ -375,14 +368,15 @@ text_flow_into_shape() Inkscape::Text::Layout const *layout = te_get_layout(text); Glib::ustring text_ustring = sp_te_get_string_multiline(text, layout->begin(), layout->end()); - Inkscape::XML::Node *text_repr = xml_doc->createTextNode(text_ustring.c_str()); // FIXME: transfer all formatting! and convert newlines into flowParas! + Inkscape::XML::Node *text_repr = xml_doc->createTextNode( + text_ustring.c_str()); // FIXME: transfer all formatting! and convert newlines into flowParas! para_repr->appendChild(text_repr); Inkscape::GC::release(para_repr); Inkscape::GC::release(text_repr); } else { // reflow an already flowed text, preserving paras - for(auto& o: text->children) { + for (auto &o : text->children) { if (SP_IS_FLOWPARA(&o)) { Inkscape::XML::Node *para_repr = o.getRepr()->duplicate(xml_doc); root_repr->appendChild(para_repr); @@ -391,23 +385,20 @@ text_flow_into_shape() Inkscape::GC::release(para_repr); } } - } - - text->deleteObject(true); + } - DocumentUndo::done(doc, SP_VERB_CONTEXT_TEXT, - _("Flow text into shape")); + text->deleteObject(true); - desktop->getSelection()->set(SP_ITEM(root_object)); + DocumentUndo::done(doc, SP_VERB_CONTEXT_TEXT, _("Flow text into shape")); - Inkscape::GC::release(root_repr); - Inkscape::GC::release(region_repr); + desktop->getSelection()->set(SP_ITEM(root_object)); + Inkscape::GC::release(root_repr); + Inkscape::GC::release(region_repr); } } -void -text_unflow () +void text_unflow() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; if (!desktop) @@ -423,17 +414,15 @@ text_unflow () return; } - std::vector<SPItem*> new_objs; + std::vector<SPItem *> new_objs; std::vector<SPItem *> old_objs; auto items = selection->items(); for (auto i : items) { - SPFlowtext *flowtext = dynamic_cast<SPFlowtext *>(i); SPText *text = dynamic_cast<SPText *>(i); if (flowtext) { - // we discard transform when unflowing, but we must preserve expansion which is visible as // font size multiplier double ex = (flowtext->transform).descrim(); @@ -463,7 +452,8 @@ text_unflow () rtspan->setAttribute("sodipodi:role", "line"); // otherwise, why bother creating the tspan? rtext->addChild(rtspan, nullptr); - Inkscape::XML::Node *text_repr = xml_doc->createTextNode(text_string.c_str()); // FIXME: transfer all formatting!!! + Inkscape::XML::Node *text_repr = + xml_doc->createTextNode(text_string.c_str()); // FIXME: transfer all formatting!!! rtspan->appendChild(text_repr); flowtext->parent->getRepr()->appendChild(rtext); @@ -480,10 +470,8 @@ text_unflow () Inkscape::GC::release(rtspan); Inkscape::GC::release(text_repr); - } else if (text){ - + } else if (text) { if (text->has_shape_inside()) { - Inkscape::XML::Node *rtext = text->getRepr(); // Position unflowed text near shape. @@ -505,7 +493,7 @@ text_unflow () // We'll also remove temporarily 'sodipodi:role' (which shouldn't be // necessary later). for (auto j : text->childList(false)) { - SPTSpan* tspan = dynamic_cast<SPTSpan *>(j); + SPTSpan *tspan = dynamic_cast<SPTSpan *>(j); if (tspan) { tspan->getRepr()->removeAttribute("x"); tspan->getRepr()->removeAttribute("y"); @@ -518,7 +506,6 @@ text_unflow () // For flowtext objects. if (new_objs.size() != 0) { - // Update selection selection->clear(); reverse(new_objs.begin(), new_objs.end()); @@ -530,30 +517,26 @@ text_unflow () } } - DocumentUndo::done(doc, SP_VERB_CONTEXT_TEXT, - _("Unflow flowed text")); + DocumentUndo::done(doc, SP_VERB_CONTEXT_TEXT, _("Unflow flowed text")); } -void -flowtext_to_text() +void flowtext_to_text() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; Inkscape::Selection *selection = desktop->getSelection(); if (selection->isEmpty()) { - desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, - _("Select <b>flowed text(s)</b> to convert.")); + desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>flowed text(s)</b> to convert.")); return; } bool did = false; bool ignored = false; - std::vector<Inkscape::XML::Node*> reprs; - std::vector<SPItem*> items(selection->items().begin(), selection->items().end()); - for(auto item : items){ - + std::vector<Inkscape::XML::Node *> reprs; + std::vector<SPItem *> items(selection->items().begin(), selection->items().end()); + for (auto item : items) { if (!SP_IS_FLOWTEXT(item)) continue; @@ -564,7 +547,8 @@ flowtext_to_text() Inkscape::XML::Node *repr = SP_FLOWTEXT(item)->getAsText(); - if (!repr) break; + if (!repr) + break; did = true; @@ -582,26 +566,21 @@ flowtext_to_text() } if (did) { - DocumentUndo::done(desktop->getDocument(), - SP_VERB_OBJECT_FLOWTEXT_TO_TEXT, - _("Convert flowed text to text")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_OBJECT_FLOWTEXT_TO_TEXT, _("Convert flowed text to text")); selection->setReprList(reprs); } else if (ignored) { // no message for (did && ignored) because it is immediately overwritten - desktop->getMessageStack()-> - flash(Inkscape::ERROR_MESSAGE, - _("Flowed text(s) must be <b>visible</b> in order to be converted.")); + desktop->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, + _("Flowed text(s) must be <b>visible</b> in order to be converted.")); } else { - desktop->getMessageStack()-> - flash(Inkscape::ERROR_MESSAGE, - _("<b>No flowed text(s)</b> to convert in the selection.")); + desktop->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, + _("<b>No flowed text(s)</b> to convert in the selection.")); } - } - -Glib::ustring text_relink_shapes_str(gchar const *prop, std::map<Glib::ustring, Glib::ustring> const &old_to_new) { +Glib::ustring text_relink_shapes_str(gchar const *prop, std::map<Glib::ustring, Glib::ustring> const &old_to_new) +{ std::vector<Glib::ustring> shapes_url = Glib::Regex::split_simple(" ", prop); Glib::ustring res; for (auto shape_url : shapes_url) { diff --git a/src/text-chemistry.h b/src/text-chemistry.h index 5d2df62c8be7b9614adc41a5b90290e0b8bfd241..937804634ca4de0a93bd6f1cf7a7c8edd7cb87e2 100644 --- a/src/text-chemistry.h +++ b/src/text-chemistry.h @@ -15,9 +15,9 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <glibmm/ustring.h> #include <utility> #include <vector> -#include <glibmm/ustring.h> class SPDocument; @@ -27,13 +27,17 @@ void text_remove_all_kerns(); void text_flow_into_shape(); void text_unflow(); void flowtext_to_text(); -enum text_ref_t { TEXT_REF_DEF = 0x1, TEXT_REF_EXTERNAL = 0x2, TEXT_REF_INTERNAL = 0x4, }; +enum text_ref_t +{ + TEXT_REF_DEF = 0x1, + TEXT_REF_EXTERNAL = 0x2, + TEXT_REF_INTERNAL = 0x4, +}; using text_refs_t = std::vector<std::pair<Glib::ustring, text_ref_t>>; -template<typename InIter> +template <typename InIter> text_refs_t text_categorize_refs(SPDocument *doc, InIter begin, InIter end, text_ref_t which); -template<typename InIterOrig, typename InIterCopy> -void text_relink_refs(text_refs_t const &refs, - InIterOrig origBegin, InIterOrig origEnd, InIterCopy copyBegin); +template <typename InIterOrig, typename InIterCopy> +void text_relink_refs(text_refs_t const &refs, InIterOrig origBegin, InIterOrig origEnd, InIterCopy copyBegin); #include "text-chemistry-impl.h" diff --git a/src/text-editing.cpp b/src/text-editing.cpp index 1b59af1feb4d6f5ea89bd154533e57561fa50bc7..608bd7d32f326ca09a0a380deb67e6bb6c6e5c06 100644 --- a/src/text-editing.cpp +++ b/src/text-editing.cpp @@ -16,27 +16,25 @@ #ifdef HAVE_CONFIG_H #endif +#include "text-editing.h" + #include <cstring> -#include <string> #include <glibmm/i18n.h> +#include <string> #include "desktop.h" #include "document.h" #include "inkscape.h" #include "message-stack.h" -#include "text-editing.h" - -#include "object/sp-textpath.h" -#include "object/sp-flowtext.h" #include "object/sp-flowdiv.h" #include "object/sp-flowregion.h" +#include "object/sp-flowtext.h" #include "object/sp-item-group.h" +#include "object/sp-textpath.h" #include "object/sp-tref.h" #include "object/sp-tspan.h" #include "style.h" - #include "util/units.h" - #include "xml/attribute-record.h" #include "xml/sp-css-attr.h" @@ -45,21 +43,21 @@ static void move_child_nodes(Inkscape::XML::Node *from_repr, Inkscape::XML::Node static bool tidy_xml_tree_recursively(SPObject *root, bool has_text_decoration); -Inkscape::Text::Layout const * te_get_layout (SPItem const *item) +Inkscape::Text::Layout const *te_get_layout(SPItem const *item) { if (SP_IS_TEXT(item)) { return &(SP_TEXT(item)->layout); - } else if (SP_IS_FLOWTEXT (item)) { + } else if (SP_IS_FLOWTEXT(item)) { return &(SP_FLOWTEXT(item)->layout); } return nullptr; } -static void te_update_layout_now (SPItem *item) +static void te_update_layout_now(SPItem *item) { if (SP_IS_TEXT(item)) SP_TEXT(item)->rebuildLayout(); - else if (SP_IS_FLOWTEXT (item)) + else if (SP_IS_FLOWTEXT(item)) SP_FLOWTEXT(item)->rebuildLayout(); item->updateRepr(); } @@ -67,13 +65,13 @@ static void te_update_layout_now (SPItem *item) void te_update_layout_now_recursive(SPItem *item) { if (SP_IS_GROUP(item)) { - std::vector<SPItem*> item_list = sp_item_group_item_list(SP_GROUP(item)); - for(auto list_item : item_list){ + std::vector<SPItem *> item_list = sp_item_group_item_list(SP_GROUP(item)); + for (auto list_item : item_list) { te_update_layout_now_recursive(list_item); } } else if (SP_IS_TEXT(item)) SP_TEXT(item)->rebuildLayout(); - else if (SP_IS_FLOWTEXT (item)) + else if (SP_IS_FLOWTEXT(item)) SP_FLOWTEXT(item)->rebuildLayout(); item->updateRepr(); } @@ -90,7 +88,7 @@ bool sp_te_input_is_empty(SPObject const *item) if (SP_IS_STRING(item)) { empty = SP_STRING(item)->string.empty(); } else { - for (auto& child: item->children) { + for (auto &child : item->children) { if (!sp_te_input_is_empty(&child)) { empty = false; break; @@ -100,10 +98,9 @@ bool sp_te_input_is_empty(SPObject const *item) return empty; } -Inkscape::Text::Layout::iterator -sp_te_get_position_by_coords (SPItem const *item, Geom::Point const &i_p) +Inkscape::Text::Layout::iterator sp_te_get_position_by_coords(SPItem const *item, Geom::Point const &i_p) { - Geom::Affine im (item->i2dt_affine ()); + Geom::Affine im(item->i2dt_affine()); im = im.inverse(); Geom::Point p = i_p * im; @@ -111,7 +108,9 @@ sp_te_get_position_by_coords (SPItem const *item, Geom::Point const &i_p) return layout->getNearestCursorPositionTo(p); } -std::vector<Geom::Point> sp_te_create_selection_quads(SPItem const *item, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, Geom::Affine const &transform) +std::vector<Geom::Point> sp_te_create_selection_quads(SPItem const *item, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, + Geom::Affine const &transform) { if (start == end) return std::vector<Geom::Point>(); @@ -122,23 +121,25 @@ std::vector<Geom::Point> sp_te_create_selection_quads(SPItem const *item, Inksca return layout->createSelectionShape(start, end, transform); } -void -sp_te_get_cursor_coords (SPItem const *item, Inkscape::Text::Layout::iterator const &position, Geom::Point &p0, Geom::Point &p1) +void sp_te_get_cursor_coords(SPItem const *item, Inkscape::Text::Layout::iterator const &position, Geom::Point &p0, + Geom::Point &p1) { Inkscape::Text::Layout const *layout = te_get_layout(item); double height, rotation; layout->queryCursorShape(position, p0, height, rotation); - p1 = Geom::Point(p0[Geom::X] + height * sin(rotation), p0[Geom::Y] - height * cos(rotation)); // valgrind warns that rotation is not initialized here. Why is to be seen in queryCursorShape + p1 = Geom::Point(p0[Geom::X] + height * sin(rotation), + p0[Geom::Y] - height * cos(rotation)); // valgrind warns that rotation is not initialized here. Why + // is to be seen in queryCursorShape } -SPStyle const * sp_te_style_at_position(SPItem const *text, Inkscape::Text::Layout::iterator const &position) +SPStyle const *sp_te_style_at_position(SPItem const *text, Inkscape::Text::Layout::iterator const &position) { SPObject const *pos_obj = sp_te_object_at_position(text, position); SPStyle *result = (pos_obj) ? pos_obj->style : nullptr; return result; } -SPObject const * sp_te_object_at_position(SPItem const *text, Inkscape::Text::Layout::iterator const &position) +SPObject const *sp_te_object_at_position(SPItem const *text, Inkscape::Text::Layout::iterator const &position) { Inkscape::Text::Layout const *layout = te_get_layout(text); if (layout == nullptr) { @@ -151,7 +152,7 @@ SPObject const * sp_te_object_at_position(SPItem const *text, Inkscape::Text::La pos_obj = text; } while (pos_obj->style == nullptr) { - pos_obj = pos_obj->parent; // not interested in SPStrings + pos_obj = pos_obj->parent; // not interested in SPStrings } return pos_obj; } @@ -171,40 +172,35 @@ char * dump_hexy(const gchar * utf8) } */ -Inkscape::Text::Layout::iterator sp_te_replace(SPItem *item, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, gchar const *utf8) +Inkscape::Text::Layout::iterator sp_te_replace(SPItem *item, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, gchar const *utf8) { iterator_pair pair; sp_te_delete(item, start, end, pair); return sp_te_insert(item, pair.first, utf8); } - /* ***************************************************************************************************/ // I N S E R T I N G T E X T static bool is_line_break_object(SPObject const *object) { bool is_line_break = false; - + if (object) { - if (SP_IS_TEXT(object) - || (SP_IS_TSPAN(object) && SP_TSPAN(object)->role != SP_TSPAN_ROLE_UNSPECIFIED) - || SP_IS_TEXTPATH(object) - || SP_IS_FLOWDIV(object) - || SP_IS_FLOWPARA(object) - || SP_IS_FLOWLINE(object) - || SP_IS_FLOWREGIONBREAK(object)) { - + if (SP_IS_TEXT(object) || (SP_IS_TSPAN(object) && SP_TSPAN(object)->role != SP_TSPAN_ROLE_UNSPECIFIED) || + SP_IS_TEXTPATH(object) || SP_IS_FLOWDIV(object) || SP_IS_FLOWPARA(object) || SP_IS_FLOWLINE(object) || + SP_IS_FLOWREGIONBREAK(object)) { is_line_break = true; } } - + return is_line_break; } /** returns the attributes for an object, or NULL if it isn't a text, tspan, tref, or textpath. */ -static TextTagAttributes* attributes_for_object(SPObject *object) +static TextTagAttributes *attributes_for_object(SPObject *object) { if (SP_IS_TSPAN(object)) return &SP_TSPAN(object)->attributes; @@ -217,10 +213,12 @@ static TextTagAttributes* attributes_for_object(SPObject *object) return nullptr; } -static const char * span_name_for_text_object(SPObject const *object) +static const char *span_name_for_text_object(SPObject const *object) { - if (SP_IS_TEXT(object)) return "svg:tspan"; - else if (SP_IS_FLOWTEXT(object)) return "svg:flowSpan"; + if (SP_IS_TEXT(object)) + return "svg:tspan"; + else if (SP_IS_FLOWTEXT(object)) + return "svg:flowSpan"; return nullptr; } @@ -234,8 +232,8 @@ unsigned sp_text_get_length(SPObject const *item) if (is_line_break_object(item)) { length++; } - - for (auto& child: item->children) { + + for (auto &child : item->children) { if (SP_IS_STRING(&child)) { length += SP_STRING(&child)->string.length(); } else { @@ -243,7 +241,7 @@ unsigned sp_text_get_length(SPObject const *item) } } } - + return length; } @@ -251,11 +249,11 @@ unsigned sp_text_get_length_upto(SPObject const *item, SPObject const *upto) { unsigned length = 0; - // The string is the lowest level and the length can be counted directly. + // The string is the lowest level and the length can be counted directly. if (SP_IS_STRING(item)) { return SP_STRING(item)->string.length(); } - + // Take care of new lines... if (is_line_break_object(item) && !SP_IS_TEXT(item)) { if (item != item->parent->firstChild()) { @@ -263,17 +261,16 @@ unsigned sp_text_get_length_upto(SPObject const *item, SPObject const *upto) length++; } } - + // Count the length of the children - for (auto& child: item->children) { + for (auto &child : item->children) { if (upto && &child == upto) { // hit upto, return immediately return length; } if (SP_IS_STRING(&child)) { length += SP_STRING(&child)->string.length(); - } - else { + } else { if (upto && child.isAncestorOf(upto)) { // upto is below us, recurse and break loop length += sp_text_get_length_upto(&child, upto); @@ -287,15 +284,17 @@ unsigned sp_text_get_length_upto(SPObject const *item, SPObject const *upto) return length; } -static Inkscape::XML::Node* duplicate_node_without_children(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node const *old_node) +static Inkscape::XML::Node *duplicate_node_without_children(Inkscape::XML::Document *xml_doc, + Inkscape::XML::Node const *old_node) { switch (old_node->type()) { case Inkscape::XML::ELEMENT_NODE: { Inkscape::XML::Node *new_node = xml_doc->createElement(old_node->name()); Inkscape::Util::List<Inkscape::XML::AttributeRecord const> attributes = old_node->attributeList(); GQuark const id_key = g_quark_from_string("id"); - for ( ; attributes ; attributes++) { - if (attributes->key == id_key) continue; + for (; attributes; attributes++) { + if (attributes->key == id_key) + continue; new_node->setAttribute(g_quark_to_string(attributes->key), attributes->value); } return new_node; @@ -311,7 +310,7 @@ static Inkscape::XML::Node* duplicate_node_without_children(Inkscape::XML::Docum return xml_doc->createPI(old_node->name(), old_node->content()); case Inkscape::XML::DOCUMENT_NODE: - return nullptr; // this had better never happen + return nullptr; // this had better never happen } return nullptr; } @@ -321,7 +320,7 @@ to \a item at the same level. */ static unsigned sum_sibling_text_lengths_before(SPObject const *item) { unsigned char_index = 0; - for (auto& sibling: item->parent->children) { + for (auto &sibling : item->parent->children) { if (&sibling == item) { break; } @@ -346,7 +345,7 @@ will be the new leaf which represents the copy of \a split_obj and extends down the tree with new elements all the way to the common root which is the parent of the first line break node encountered. */ -static SPObject* split_text_object_tree_at(SPObject *split_obj, unsigned char_index) +static SPObject *split_text_object_tree_at(SPObject *split_obj, unsigned char_index) { Inkscape::XML::Document *xml_doc = split_obj->document->getReprDoc(); if (is_line_break_object(split_obj)) { @@ -355,9 +354,7 @@ static SPObject* split_text_object_tree_at(SPObject *split_obj, unsigned char_in Inkscape::GC::release(new_node); split_attributes(split_obj, split_obj->getNext(), char_index); return split_obj->getNext(); - } else if (!SP_IS_TSPAN(split_obj) && - !SP_IS_FLOWTSPAN(split_obj) && - !SP_IS_STRING(split_obj)) { + } else if (!SP_IS_TSPAN(split_obj) && !SP_IS_FLOWTSPAN(split_obj) && !SP_IS_STRING(split_obj)) { std::cerr << "split_text_object_tree_at: Illegal split object type! (Illegal document structure.)" << std::endl; return nullptr; } @@ -382,7 +379,7 @@ static SPObject* split_text_object_tree_at(SPObject *split_obj, unsigned char_in split_obj = split_obj->getNext(); while (split_obj) { Inkscape::XML::Node *move_repr = split_obj->getRepr(); - SPObject *next_obj = split_obj->getNext(); // this is about to become invalidated by removeChild() + SPObject *next_obj = split_obj->getNext(); // this is about to become invalidated by removeChild() Inkscape::GC::anchor(move_repr); split_obj->parent->getRepr()->removeChild(move_repr); duplicate_obj->getRepr()->appendChild(move_repr); @@ -397,21 +394,20 @@ static SPObject* split_text_object_tree_at(SPObject *split_obj, unsigned char_in object. If the position is in the middle of a span, the XML tree must be chopped in two such that the line can be created at the root of the text element. Returns an iterator pointing just after the inserted break. */ -Inkscape::Text::Layout::iterator sp_te_insert_line (SPItem *item, Inkscape::Text::Layout::iterator &position) +Inkscape::Text::Layout::iterator sp_te_insert_line(SPItem *item, Inkscape::Text::Layout::iterator &position) { // Disable newlines in a textpath; TODO: maybe on Enter in a textpath, separate it into two // texpaths attached to the same path, with a vertical shift - if (SP_IS_TEXT_TEXTPATH (item) || SP_IS_TREF(item)) + if (SP_IS_TEXT_TEXTPATH(item) || SP_IS_TREF(item)) return position; - + Inkscape::Text::Layout const *layout = te_get_layout(item); // If this is plain SVG 1.1 text object without a tspan with sodipodi:role="line", we need // to wrap it or our custom line breaking code won't work! bool need_to_wrap = false; - SPText* text_object = dynamic_cast<SPText *>(item); + SPText *text_object = dynamic_cast<SPText *>(item); if (text_object && !text_object->has_shape_inside() && !text_object->has_inline_size()) { - need_to_wrap = true; for (auto child : item->childList(false)) { auto tspan = dynamic_cast<SPTSpan *>(child); @@ -423,7 +419,6 @@ Inkscape::Text::Layout::iterator sp_te_insert_line (SPItem *item, Inkscape::Text } if (need_to_wrap) { - // We'll need to rebuild layout, so store character postion: int char_index = layout->iteratorToCharIndex(position); @@ -444,7 +439,7 @@ Inkscape::Text::Layout::iterator sp_te_insert_line (SPItem *item, Inkscape::Text } } - SPDesktop *desktop = SP_ACTIVE_DESKTOP; + SPDesktop *desktop = SP_ACTIVE_DESKTOP; SPObject *split_obj = nullptr; Glib::ustring::iterator split_text_iter; @@ -453,14 +448,14 @@ Inkscape::Text::Layout::iterator sp_te_insert_line (SPItem *item, Inkscape::Text } if (split_obj == nullptr || is_line_break_object(split_obj)) { - - if (split_obj == nullptr) split_obj = item->lastChild(); + if (split_obj == nullptr) + split_obj = item->lastChild(); if (SP_IS_TREF(split_obj)) { desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, tref_edit_message); return position; } - + if (split_obj) { Inkscape::XML::Document *xml_doc = split_obj->document->getReprDoc(); Inkscape::XML::Node *new_node = duplicate_node_without_children(xml_doc, split_obj->getRepr()); @@ -471,7 +466,6 @@ Inkscape::Text::Layout::iterator sp_te_insert_line (SPItem *item, Inkscape::Text } } else if (SP_IS_STRING(split_obj)) { - // If the parent is a tref, editing on this particular string is disallowed. if (SP_IS_TREF(split_obj->parent)) { desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, tref_edit_message); @@ -480,7 +474,7 @@ Inkscape::Text::Layout::iterator sp_te_insert_line (SPItem *item, Inkscape::Text Glib::ustring *string = &SP_STRING(split_obj)->string; unsigned char_index = 0; - for (Glib::ustring::iterator it = string->begin() ; it != split_text_iter ; ++it) + for (Glib::ustring::iterator it = string->begin(); it != split_text_iter; ++it) char_index++; // we need to split the entire text tree into two @@ -491,7 +485,7 @@ Inkscape::Text::Layout::iterator sp_te_insert_line (SPItem *item, Inkscape::Text } SPString *new_string = SP_STRING(object); - new_string->getRepr()->setContent(&*split_text_iter.base()); // a little ugly + new_string->getRepr()->setContent(&*split_text_iter.base()); // a little ugly string->erase(split_text_iter, string->end()); split_obj->getRepr()->setContent(string->c_str()); // TODO: if the split point was at the beginning of a span we have a whole load of empty elements to clean up @@ -507,7 +501,7 @@ Inkscape::Text::Layout::iterator sp_te_insert_line (SPItem *item, Inkscape::Text } /** finds the first SPString after the given position, including children, excluding parents */ -static SPString* sp_te_seek_next_string_recursive(SPObject *start_obj) +static SPString *sp_te_seek_next_string_recursive(SPObject *start_obj) { while (start_obj) { if (start_obj->hasChildren()) { @@ -521,7 +515,7 @@ static SPString* sp_te_seek_next_string_recursive(SPObject *start_obj) } start_obj = start_obj->getNext(); if (is_line_break_object(start_obj)) { - break; // don't cross line breaks + break; // don't cross line breaks } } return nullptr; @@ -535,16 +529,17 @@ static void insert_into_spstring(SPString *string_item, Glib::ustring::iterator unsigned char_count = g_utf8_strlen(utf8, -1); Glib::ustring *string = &SP_STRING(string_item)->string; - for (Glib::ustring::iterator it = string->begin() ; it != iter_at ; ++it) + for (Glib::ustring::iterator it = string->begin(); it != iter_at; ++it) char_index++; string->replace(iter_at, iter_at, utf8); SPObject *parent_item = string_item; - for ( ; ; ) { + for (;;) { char_index += sum_sibling_text_lengths_before(parent_item); parent_item = parent_item->parent; TextTagAttributes *attributes = attributes_for_object(parent_item); - if (!attributes) break; + if (!attributes) + break; attributes->insert(char_index, char_count); } } @@ -552,14 +547,14 @@ static void insert_into_spstring(SPString *string_item, Glib::ustring::iterator /** Inserts the given text into a text or flowroot object. Line breaks cannot be inserted using this function, see sp_te_insert_line(). Returns an iterator pointing just after the inserted text. */ -Inkscape::Text::Layout::iterator -sp_te_insert(SPItem *item, Inkscape::Text::Layout::iterator const &position, gchar const *utf8) +Inkscape::Text::Layout::iterator sp_te_insert(SPItem *item, Inkscape::Text::Layout::iterator const &position, + gchar const *utf8) { - if (!g_utf8_validate(utf8,-1,nullptr)) { + if (!g_utf8_validate(utf8, -1, nullptr)) { g_warning("Trying to insert invalid utf8"); return position; } - + SPDesktop *desktop = SP_ACTIVE_DESKTOP; Inkscape::Text::Layout const *layout = te_get_layout(item); @@ -577,15 +572,16 @@ sp_te_insert(SPItem *item, Inkscape::Text::Layout::iterator const &position, gch desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, tref_edit_message); return position; } - + // Now the simple case can begin... - if (!cursor_at_start){ + if (!cursor_at_start) { ++iter_text; } SPString *string_item = SP_STRING(source_obj); insert_into_spstring(string_item, cursor_at_end ? string_item->string.end() : iter_text, utf8); } else { - // the not-so-simple case where we're at a line break or other control char; add to the next child/sibling SPString + // the not-so-simple case where we're at a line break or other control char; add to the next child/sibling + // SPString Inkscape::XML::Document *xml_doc = item->getRepr()->document(); if (cursor_at_start) { source_obj = item; @@ -608,7 +604,7 @@ sp_te_insert(SPItem *item, Inkscape::Text::Layout::iterator const &position, gch } else source_obj = source_obj->getNext(); - if (source_obj) { // never fails + if (source_obj) { // never fails SPString *string_item = sp_te_seek_next_string_recursive(source_obj); if (string_item == nullptr) { // need to add an SPString in this (pathological) case @@ -623,8 +619,9 @@ sp_te_insert(SPItem *item, Inkscape::Text::Layout::iterator const &position, gch desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, tref_edit_message); return position; } - - insert_into_spstring(string_item, cursor_at_end ? string_item->string.end() : string_item->string.begin(), utf8); + + insert_into_spstring(string_item, cursor_at_end ? string_item->string.end() : string_item->string.begin(), + utf8); } } @@ -634,7 +631,6 @@ sp_te_insert(SPItem *item, Inkscape::Text::Layout::iterator const &position, gch return layout->charIndexToIterator(char_index + g_utf8_strlen(utf8, -1)); } - /* ***************************************************************************************************/ // D E L E T I N G T E X T @@ -647,15 +643,17 @@ static void move_child_nodes(Inkscape::XML::Node *from_repr, Inkscape::XML::Node Inkscape::XML::Node *child = prepend ? from_repr->lastChild() : from_repr->firstChild(); Inkscape::GC::anchor(child); from_repr->removeChild(child); - if (prepend) to_repr->addChild(child, nullptr); - else to_repr->appendChild(child); + if (prepend) + to_repr->addChild(child, nullptr); + else + to_repr->appendChild(child); Inkscape::GC::release(child); } } /** returns the object in the tree which is the closest ancestor of both \a one and \a two. It will never return anything higher than \a text. */ -static SPObject* get_common_ancestor(SPObject *text, SPObject *one, SPObject *two) +static SPObject *get_common_ancestor(SPObject *text, SPObject *one, SPObject *two) { if (one == nullptr || two == nullptr) return text; @@ -683,11 +681,11 @@ static void move_to_end_of_paragraph(SPObject **para_obj, Glib::ustring::iterato /** delete the line break pointed to by \a item by merging its children into the next suitable object and deleting \a item. Returns the object after the ones that have just been moved and sets \a next_is_sibling accordingly. */ -static SPObject* delete_line_break(SPObject *root, SPObject *item, bool *next_is_sibling) +static SPObject *delete_line_break(SPObject *root, SPObject *item, bool *next_is_sibling) { Inkscape::XML::Node *this_repr = item->getRepr(); SPObject *next_item = nullptr; - unsigned moved_char_count = sp_text_get_length(item) - 1; // the -1 is because it's going to count the line break + unsigned moved_char_count = sp_text_get_length(item) - 1; // the -1 is because it's going to count the line break /* some sample cases (the div is the item to be deleted, the * represents where to put the new span): <div></div><p>*text</p> @@ -711,7 +709,8 @@ static SPObject* delete_line_break(SPObject *root, SPObject *item, bool *next_is SPObject *new_parent_item; if (SP_IS_STRING(following_item)) { new_parent_item = following_item->parent; - new_parent_item->getRepr()->addChild(new_span_repr, following_item->getPrev() ? following_item->getPrev()->getRepr() : nullptr); + new_parent_item->getRepr()->addChild( + new_span_repr, following_item->getPrev() ? following_item->getPrev()->getRepr() : nullptr); next_item = following_item; *next_is_sibling = true; } else { @@ -732,7 +731,7 @@ static SPObject* delete_line_break(SPObject *root, SPObject *item, bool *next_is SPCSSAttr *this_node_attrs = sp_repr_css_attr(this_repr, "style"); SPCSSAttr *this_node_attrs_inherited = sp_repr_css_attr_inherited(this_repr, "style"); Inkscape::Util::List<Inkscape::XML::AttributeRecord const> attrs = dest_node_attrs->attributeList(); - for ( ; attrs ; attrs++) { + for (; attrs; attrs++) { gchar const *key = g_quark_to_string(attrs->key); gchar const *this_attr = this_node_attrs_inherited->attribute(key); if ((this_attr == nullptr || strcmp(attrs->value, this_attr)) && this_node_attrs->attribute(key) == nullptr) @@ -753,23 +752,24 @@ static SPObject* delete_line_break(SPObject *root, SPObject *item, bool *next_is /** erases the given characters from the given string and deletes the corresponding x/y/dx/dy/rotate attributes from all its parents. */ -static void erase_from_spstring(SPString *string_item, Glib::ustring::iterator iter_from, Glib::ustring::iterator iter_to) +static void erase_from_spstring(SPString *string_item, Glib::ustring::iterator iter_from, + Glib::ustring::iterator iter_to) { unsigned char_index = 0; unsigned char_count = 0; Glib::ustring *string = &SP_STRING(string_item)->string; - for (Glib::ustring::iterator it = string->begin() ; it != iter_from ; ++it){ + for (Glib::ustring::iterator it = string->begin(); it != iter_from; ++it) { char_index++; } - for (Glib::ustring::iterator it = iter_from ; it != iter_to ; ++it){ + for (Glib::ustring::iterator it = iter_from; it != iter_to; ++it) { char_count++; } string->erase(iter_from, iter_to); string_item->getRepr()->setContent(string->c_str()); SPObject *parent_item = string_item; - for ( ; ; ) { + for (;;) { char_index += sum_sibling_text_lengths_before(parent_item); parent_item = parent_item->parent; TextTagAttributes *attributes = attributes_for_object(parent_item); @@ -787,31 +787,31 @@ quite a complicated operation, partly due to the cleanup that is done if all the text in a subobject has been deleted, and partly due to the difficulty of figuring out what is a line break and how to delete one. Returns the real start and ending iterators based on the situation. */ -bool -sp_te_delete (SPItem *item, Inkscape::Text::Layout::iterator const &start, - Inkscape::Text::Layout::iterator const &end, iterator_pair &iter_pair) +bool sp_te_delete(SPItem *item, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, iterator_pair &iter_pair) { bool success = false; iter_pair.first = start; iter_pair.second = end; - - if (start == end) return success; - + + if (start == end) + return success; + if (start > end) { iter_pair.first = end; iter_pair.second = start; } - + SPDesktop *desktop = SP_ACTIVE_DESKTOP; - + Inkscape::Text::Layout const *layout = te_get_layout(item); SPObject *start_item = nullptr, *end_item = nullptr; Glib::ustring::iterator start_text_iter, end_text_iter; layout->getSourceOfCharacter(iter_pair.first, &start_item, &start_text_iter); layout->getSourceOfCharacter(iter_pair.second, &end_item, &end_text_iter); if (start_item == nullptr) { - return success; // start is at end of text + return success; // start is at end of text } if (is_line_break_object(start_item)) { move_to_end_of_paragraph(&start_item, &start_text_iter); @@ -827,11 +827,12 @@ sp_te_delete (SPItem *item, Inkscape::Text::Layout::iterator const &start, bool has_text_decoration = false; gchar const *root_style = (item)->getRepr()->attribute("style"); - if(root_style && strstr(root_style,"text-decoration"))has_text_decoration = true; + if (root_style && strstr(root_style, "text-decoration")) + has_text_decoration = true; if (start_item == end_item) { // the quick case where we're deleting stuff all from the same string - if (SP_IS_STRING(start_item)) { // always true (if it_start != it_end anyway) + if (SP_IS_STRING(start_item)) { // always true (if it_start != it_end anyway) // If the parent is a tref, editing on this particular string is disallowed. if (SP_IS_TREF(start_item->parent)) { desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, tref_edit_message); @@ -851,7 +852,7 @@ sp_te_delete (SPItem *item, Inkscape::Text::Layout::iterator const &start, desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, tref_edit_message); break; } - + Glib::ustring *string = &SP_STRING(sub_item)->string; erase_from_spstring(SP_STRING(sub_item), string->begin(), end_text_iter); success = true; @@ -883,14 +884,16 @@ sp_te_delete (SPItem *item, Inkscape::Text::Layout::iterator const &start, next_item = delete_line_break(item, sub_item, &is_sibling); sub_item = next_item; - if (is_sibling) break; + if (is_sibling) + break; // no more siblings, go up a parent } while (sub_item != item && sub_item != end_item); } } } - while (tidy_xml_tree_recursively(common_ancestor, has_text_decoration)){}; + while (tidy_xml_tree_recursively(common_ancestor, has_text_decoration)) { + }; te_update_layout_now(item); item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); layout->validateIterator(&iter_pair.first); @@ -898,7 +901,6 @@ sp_te_delete (SPItem *item, Inkscape::Text::Layout::iterator const &start, return success; } - /* ***************************************************************************************************/ // P L A I N T E X T F U N C T I O N S @@ -909,7 +911,7 @@ static void sp_te_get_ustring_multiline(SPObject const *root, Glib::ustring *str if (*pending_line_break) { *string += '\n'; } - for (auto& child: root->children) { + for (auto &child : root->children) { if (SP_IS_STRING(&child)) { *string += SP_STRING(&child)->string; } else { @@ -923,8 +925,7 @@ static void sp_te_get_ustring_multiline(SPObject const *root, Glib::ustring *str /** Gets a text-only representation of the given text or flowroot object, replacing line break elements with '\n'. The return value must be free()d. */ -Glib::ustring -sp_te_get_string_multiline (SPItem const *text) +Glib::ustring sp_te_get_string_multiline(SPItem const *text) { Glib::ustring string; bool pending_line_break = false; @@ -938,10 +939,11 @@ sp_te_get_string_multiline (SPItem const *text) /** Gets a text-only representation of the characters in a text or flowroot object from \a start to \a end only. Line break elements are replaced with '\n'. */ -Glib::ustring -sp_te_get_string_multiline (SPItem const *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end) +Glib::ustring sp_te_get_string_multiline(SPItem const *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end) { - if (start == end) return ""; + if (start == end) + return ""; Inkscape::Text::Layout::iterator first, last; if (start < end) { first = start; @@ -953,7 +955,7 @@ sp_te_get_string_multiline (SPItem const *text, Inkscape::Text::Layout::iterator Inkscape::Text::Layout const *layout = te_get_layout(text); Glib::ustring result; // not a particularly fast piece of code. I'll optimise it if people start to notice. - for ( ; first < last ; first.nextCharacter()) { + for (; first < last; first.nextCharacter()) { SPObject *char_item = nullptr; Glib::ustring::iterator text_iter; layout->getSourceOfCharacter(first, &char_item, &text_iter); @@ -966,17 +968,16 @@ sp_te_get_string_multiline (SPItem const *text, Inkscape::Text::Layout::iterator return result; } -void -sp_te_set_repr_text_multiline(SPItem *text, gchar const *str) +void sp_te_set_repr_text_multiline(SPItem *text, gchar const *str) { - g_return_if_fail (text != nullptr); - g_return_if_fail (SP_IS_TEXT(text) || SP_IS_FLOWTEXT(text)); + g_return_if_fail(text != nullptr); + g_return_if_fail(SP_IS_TEXT(text) || SP_IS_FLOWTEXT(text)); Inkscape::XML::Document *xml_doc = text->getRepr()->document(); Inkscape::XML::Node *repr; SPObject *object; bool is_textpath = false; - if (SP_IS_TEXT_TEXTPATH (text)) { + if (SP_IS_TEXT_TEXTPATH(text)) { repr = text->firstChild()->getRepr(); object = text->firstChild(); is_textpath = true; @@ -988,10 +989,10 @@ sp_te_set_repr_text_multiline(SPItem *text, gchar const *str) if (!str) { str = ""; } - gchar *content = g_strdup (str); + gchar *content = g_strdup(str); repr->setContent(""); - for (auto& child: object->childList(false)) { + for (auto &child : object->childList(false)) { if (!SP_IS_FLOWREGION(child) && !SP_IS_FLOWREGIONEXCLUDE(child)) { repr->removeChild(child->getRepr()); } @@ -999,11 +1000,13 @@ sp_te_set_repr_text_multiline(SPItem *text, gchar const *str) gchar *p = content; while (p) { - gchar *e = strchr (p, '\n'); + gchar *e = strchr(p, '\n'); if (is_textpath) { - if (e) *e = ' '; // no lines for textpath, replace newlines with spaces + if (e) + *e = ' '; // no lines for textpath, replace newlines with spaces } else { - if (e) *e = '\0'; + if (e) + *e = '\0'; Inkscape::XML::Node *rtspan; if (SP_IS_TEXT(text)) { // create a tspan for each line rtspan = xml_doc->createElement("svg:tspan"); @@ -1025,7 +1028,7 @@ sp_te_set_repr_text_multiline(SPItem *text, gchar const *str) Inkscape::GC::release(rstr); } - g_free (content); + g_free(content); } /* ***************************************************************************************************/ @@ -1033,11 +1036,11 @@ sp_te_set_repr_text_multiline(SPItem *text, gchar const *str) /** Returns the attributes block and the character index within that block which represents the iterator \a position. */ -TextTagAttributes* -text_tag_attributes_at_position(SPItem *item, Inkscape::Text::Layout::iterator const &position, unsigned *char_index) +TextTagAttributes *text_tag_attributes_at_position(SPItem *item, Inkscape::Text::Layout::iterator const &position, + unsigned *char_index) { if (item == nullptr || char_index == nullptr || !SP_IS_TEXT(item)) { - return nullptr; // flowtext doesn't support kerning yet + return nullptr; // flowtext doesn't support kerning yet } SPText *text = SP_TEXT(item); @@ -1050,36 +1053,39 @@ text_tag_attributes_at_position(SPItem *item, Inkscape::Text::Layout::iterator c } Glib::ustring *string = &SP_STRING(source_item)->string; *char_index = sum_sibling_text_lengths_before(source_item); - for (Glib::ustring::iterator it = string->begin() ; it != source_text_iter ; ++it) { + for (Glib::ustring::iterator it = string->begin(); it != source_text_iter; ++it) { ++*char_index; } return attributes_for_object(source_item->parent); } -void -sp_te_adjust_kerning_screen (SPItem *item, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, Geom::Point by) +void sp_te_adjust_kerning_screen(SPItem *item, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, Geom::Point by) { // divide increment by zoom // divide increment by matrix expansion gdouble factor = 1 / desktop->current_zoom(); - Geom::Affine t (item->i2doc_affine()); + Geom::Affine t(item->i2doc_affine()); factor = factor / t.descrim(); by = factor * by; unsigned char_index; TextTagAttributes *attributes = text_tag_attributes_at_position(item, std::min(start, end), &char_index); - if (attributes) attributes->addToDxDy(char_index, by); + if (attributes) + attributes->addToDxDy(char_index, by); if (start != end) { attributes = text_tag_attributes_at_position(item, std::max(start, end), &char_index); - if (attributes) attributes->addToDxDy(char_index, -by); + if (attributes) + attributes->addToDxDy(char_index, -by); } item->updateRepr(); item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void sp_te_adjust_dx(SPItem *item, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop * /*desktop*/, double delta) +void sp_te_adjust_dx(SPItem *item, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop * /*desktop*/, double delta) { unsigned char_index = 0; TextTagAttributes *attributes = text_tag_attributes_at_position(item, std::min(start, end), &char_index); @@ -1097,7 +1103,8 @@ void sp_te_adjust_dx(SPItem *item, Inkscape::Text::Layout::iterator const &start item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void sp_te_adjust_dy(SPItem *item, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop * /*desktop*/, double delta) +void sp_te_adjust_dy(SPItem *item, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop * /*desktop*/, double delta) { unsigned char_index = 0; TextTagAttributes *attributes = text_tag_attributes_at_position(item, std::min(start, end), &char_index); @@ -1115,37 +1122,41 @@ void sp_te_adjust_dy(SPItem *item, Inkscape::Text::Layout::iterator const &start item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void -sp_te_adjust_rotation_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, gdouble pixels) +void sp_te_adjust_rotation_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, gdouble pixels) { // divide increment by zoom // divide increment by matrix expansion gdouble factor = 1 / desktop->current_zoom(); - Geom::Affine t (text->i2doc_affine()); + Geom::Affine t(text->i2doc_affine()); factor = factor / t.descrim(); Inkscape::Text::Layout const *layout = te_get_layout(text); - if (layout == nullptr) return; + if (layout == nullptr) + return; SPObject *source_item = nullptr; layout->getSourceOfCharacter(std::min(start, end), &source_item); if (source_item == nullptr) { return; } - gdouble degrees = (180/M_PI) * atan2(pixels, source_item->parent->style->font_size.computed / factor); + gdouble degrees = (180 / M_PI) * atan2(pixels, source_item->parent->style->font_size.computed / factor); sp_te_adjust_rotation(text, start, end, desktop, degrees); } -void -sp_te_adjust_rotation(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop */*desktop*/, gdouble degrees) +void sp_te_adjust_rotation(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop * /*desktop*/, gdouble degrees) { unsigned char_index; TextTagAttributes *attributes = text_tag_attributes_at_position(text, std::min(start, end), &char_index); - if (attributes == nullptr) return; + if (attributes == nullptr) + return; if (start != end) { - for (Inkscape::Text::Layout::iterator it = std::min(start, end) ; it != std::max(start, end) ; it.nextCharacter()) { + for (Inkscape::Text::Layout::iterator it = std::min(start, end); it != std::max(start, end); + it.nextCharacter()) { attributes = text_tag_attributes_at_position(text, it, &char_index); - if (attributes) attributes->addToRotate(char_index, degrees); + if (attributes) + attributes->addToRotate(char_index, degrees); } } else attributes->addToRotate(char_index, degrees); @@ -1154,13 +1165,15 @@ sp_te_adjust_rotation(SPItem *text, Inkscape::Text::Layout::iterator const &star text->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void sp_te_set_rotation(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop */*desktop*/, gdouble degrees) +void sp_te_set_rotation(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop * /*desktop*/, gdouble degrees) { unsigned char_index = 0; TextTagAttributes *attributes = text_tag_attributes_at_position(text, std::min(start, end), &char_index); if (attributes != nullptr) { if (start != end) { - for (Inkscape::Text::Layout::iterator it = std::min(start, end) ; it != std::max(start, end) ; it.nextCharacter()) { + for (Inkscape::Text::Layout::iterator it = std::min(start, end); it != std::max(start, end); + it.nextCharacter()) { attributes = text_tag_attributes_at_position(text, it, &char_index); if (attributes) { attributes->setRotate(char_index, degrees); @@ -1175,11 +1188,12 @@ void sp_te_set_rotation(SPItem *text, Inkscape::Text::Layout::iterator const &st } } -void -sp_te_adjust_tspan_letterspacing_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, gdouble by) +void sp_te_adjust_tspan_letterspacing_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, + gdouble by) { - g_return_if_fail (text != nullptr); - g_return_if_fail (SP_IS_TEXT(text) || SP_IS_FLOWTEXT(text)); + g_return_if_fail(text != nullptr); + g_return_if_fail(SP_IS_TEXT(text) || SP_IS_FLOWTEXT(text)); Inkscape::Text::Layout const *layout = te_get_layout(text); @@ -1188,7 +1202,7 @@ sp_te_adjust_tspan_letterspacing_screen(SPItem *text, Inkscape::Text::Layout::it unsigned nb_let; layout->getSourceOfCharacter(std::min(start, end), &source_obj); - if (source_obj == nullptr) { // end of text + if (source_obj == nullptr) { // end of text source_obj = text->lastChild(); } if (SP_IS_STRING(source_obj)) { @@ -1213,7 +1227,7 @@ sp_te_adjust_tspan_letterspacing_screen(SPItem *text, Inkscape::Text::Layout::it } if (start == end) { - while (!is_line_break_object(source_obj)) { // move up the tree so we apply to the closest paragraph + while (!is_line_break_object(source_obj)) { // move up the tree so we apply to the closest paragraph source_obj = source_obj->parent; } nb_let = sp_text_get_length(source_obj); @@ -1224,9 +1238,7 @@ sp_te_adjust_tspan_letterspacing_screen(SPItem *text, Inkscape::Text::Layout::it // divide increment by zoom and by the number of characters in the line, // so that the entire line is expanded by by pixels, no matter what its length gdouble const zoom = desktop->current_zoom(); - gdouble const zby = (by - / (zoom * (nb_let > 1 ? nb_let - 1 : 1)) - / SP_ITEM(source_obj)->i2doc_affine().descrim()); + gdouble const zby = (by / (zoom * (nb_let > 1 ? nb_let - 1 : 1)) / SP_ITEM(source_obj)->i2doc_affine().descrim()); val += zby; if (start == end) { @@ -1258,15 +1270,15 @@ sp_te_adjust_tspan_letterspacing_screen(SPItem *text, Inkscape::Text::Layout::it } // Only used for page-up and page-down and sp_te_adjust_linespacing_screen -double -sp_te_get_average_linespacing (SPItem *text) +double sp_te_get_average_linespacing(SPItem *text) { Inkscape::Text::Layout const *layout = te_get_layout(text); if (!layout) return 0; unsigned line_count = layout->lineIndex(layout->end()); - double all_lines_height = layout->characterAnchorPoint(layout->end())[Geom::Y] - layout->characterAnchorPoint(layout->begin())[Geom::Y]; + double all_lines_height = + layout->characterAnchorPoint(layout->end())[Geom::Y] - layout->characterAnchorPoint(layout->begin())[Geom::Y]; double average_line_height = all_lines_height / (line_count == 0 ? 1 : line_count); return average_line_height; } @@ -1275,16 +1287,13 @@ sp_te_get_average_linespacing (SPItem *text) * If top_level is true then objects without 'line-height' set or withwill get a set value, * otherwise objects that inherit line-height will not get onw=e. */ -void -sp_te_adjust_line_height (SPObject *object, double amount, double average, bool top_level = true) { - +void sp_te_adjust_line_height(SPObject *object, double amount, double average, bool top_level = true) +{ SPStyle *style = object->style; // Always set if top level true. // Also set if line_height is set to a non-zero value. - if (top_level || - (style->line_height.set && !style->line_height.inherit && style->line_height.computed != 0)){ - + if (top_level || (style->line_height.set && !style->line_height.inherit && style->line_height.computed != 0)) { // Scale default values if (!style->line_height.set || style->line_height.inherit || style->line_height.normal) { style->line_height.set = TRUE; @@ -1295,7 +1304,6 @@ sp_te_adjust_line_height (SPObject *object, double amount, double average, bool } switch (style->line_height.unit) { - case SP_CSS_UNIT_NONE: default: // Multiplier-type units, stored in computed @@ -1308,7 +1316,6 @@ sp_te_adjust_line_height (SPObject *object, double amount, double average, bool style->line_height.value = style->line_height.computed; break; - // Relative units, stored in value case SP_CSS_UNIT_EM: case SP_CSS_UNIT_EX: @@ -1320,7 +1327,6 @@ sp_te_adjust_line_height (SPObject *object, double amount, double average, bool } break; - // Absolute units case SP_CSS_UNIT_PX: style->line_height.computed += amount; @@ -1350,23 +1356,24 @@ sp_te_adjust_line_height (SPObject *object, double amount, double average, bool object->updateRepr(); } - std::vector<SPObject*> children = object->childList(false); - for (auto child: children) { - sp_te_adjust_line_height (child, amount, average, false); + std::vector<SPObject *> children = object->childList(false); + for (auto child : children) { + sp_te_adjust_line_height(child, amount, average, false); } } -void -sp_te_adjust_linespacing_screen (SPItem *text, Inkscape::Text::Layout::iterator const &/*start*/, Inkscape::Text::Layout::iterator const &/*end*/, SPDesktop *desktop, gdouble by) +void sp_te_adjust_linespacing_screen(SPItem *text, Inkscape::Text::Layout::iterator const & /*start*/, + Inkscape::Text::Layout::iterator const & /*end*/, SPDesktop *desktop, gdouble by) { // TODO: use start and end iterators to delineate the area to be affected - g_return_if_fail (text != nullptr); - g_return_if_fail (SP_IS_TEXT(text) || SP_IS_FLOWTEXT(text)); + g_return_if_fail(text != nullptr); + g_return_if_fail(SP_IS_TEXT(text) || SP_IS_FLOWTEXT(text)); Inkscape::Text::Layout const *layout = te_get_layout(text); - double average_line_height = sp_te_get_average_linespacing (text); - if (fabs(average_line_height) < 0.001) average_line_height = 0.001; + double average_line_height = sp_te_get_average_linespacing(text); + if (fabs(average_line_height) < 0.001) + average_line_height = 0.001; // divide increment by zoom and by the number of lines, // so that the entire object is expanded by by pixels @@ -1380,28 +1387,26 @@ sp_te_adjust_linespacing_screen (SPItem *text, Inkscape::Text::Layout::iterator Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gint mode = prefs->getInt("/tools/text/line_spacing_mode", 0); if (mode == 0) { // Adaptive: <text> line-spacing is zero, only scale children. - std::vector<SPObject*> children = text->childList(false); - for (auto child: children) { - sp_te_adjust_line_height (child, zby, average_line_height, false); + std::vector<SPObject *> children = text->childList(false); + for (auto child : children) { + sp_te_adjust_line_height(child, zby, average_line_height, false); } } else { - sp_te_adjust_line_height (text, zby, average_line_height, true); + sp_te_adjust_line_height(text, zby, average_line_height, true); } text->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_TEXT_LAYOUT_MODIFIED_FLAG); } - /* ***************************************************************************************************/ // S T Y L E A P P L I C A T I O N - /** converts an iterator to a character index, mainly because ustring::substr() doesn't have a version that takes iterators as parameters. */ static unsigned char_index_of_iterator(Glib::ustring const &string, Glib::ustring::const_iterator text_iter) { unsigned n = 0; - for (Glib::ustring::const_iterator it = string.begin() ; it != string.end() && it != text_iter ; ++it) + for (Glib::ustring::const_iterator it = string.begin(); it != string.end() && it != text_iter; ++it) n++; return n; } @@ -1435,7 +1440,7 @@ static bool objects_have_equal_style(SPObject const *parent, SPObject const *chi // requires that the computed value is inherited, not the specified value. g_assert(parent->isAncestorOf(child)); - Glib::ustring parent_style = parent->style->write( SP_STYLE_FLAG_ALWAYS ); + Glib::ustring parent_style = parent->style->write(SP_STYLE_FLAG_ALWAYS); // we have to write parent_style then read it again, because some properties format their values // differently depending on whether they're set or not (*cough*dash-offset*cough*) @@ -1459,7 +1464,7 @@ static bool objects_have_equal_style(SPObject const *parent, SPObject const *chi child_spstyle.mergeString(child_style_construction.c_str()); Glib::ustring child_style = child_spstyle.write(SP_STYLE_FLAG_ALWAYS); - bool equal = (child_style == parent_style); // Glib::ustring overloads == operator + bool equal = (child_style == parent_style); // Glib::ustring overloads == operator return equal; } @@ -1470,13 +1475,13 @@ in one but not the other. */ static bool css_attrs_are_equal(SPCSSAttr const *first, SPCSSAttr const *second) { Inkscape::Util::List<Inkscape::XML::AttributeRecord const> attrs = first->attributeList(); - for ( ; attrs ; attrs++) { + for (; attrs; attrs++) { gchar const *other_attr = second->attribute(g_quark_to_string(attrs->key)); if (other_attr == nullptr || strcmp(attrs->value, other_attr)) return false; } attrs = second->attributeList(); - for ( ; attrs ; attrs++) { + for (; attrs; attrs++) { gchar const *other_attr = first->attribute(g_quark_to_string(attrs->key)); if (other_attr == nullptr || strcmp(attrs->value, other_attr)) return false; @@ -1489,19 +1494,20 @@ Annoyingly similar to sp_desktop_apply_css_recursive(), except without the transform stuff. */ static void apply_css_recursive(SPObject *o, SPCSSAttr const *css) { - sp_repr_css_change(o->getRepr(), const_cast<SPCSSAttr*>(css), "style"); + sp_repr_css_change(o->getRepr(), const_cast<SPCSSAttr *>(css), "style"); - for (auto& child: o->children) { - if (sp_repr_css_property(const_cast<SPCSSAttr*>(css), "opacity", nullptr) != nullptr) { + for (auto &child : o->children) { + if (sp_repr_css_property(const_cast<SPCSSAttr *>(css), "opacity", nullptr) != nullptr) { // Unset properties which are accumulating and thus should not be set recursively. - // For example, setting opacity 0.5 on a group recursively would result in the visible opacity of 0.25 for an item in the group. + // For example, setting opacity 0.5 on a group recursively would result in the visible opacity of 0.25 for + // an item in the group. SPCSSAttr *css_recurse = sp_repr_css_attr_new(); - sp_repr_css_merge(css_recurse, const_cast<SPCSSAttr*>(css)); + sp_repr_css_merge(css_recurse, const_cast<SPCSSAttr *>(css)); sp_repr_css_set_property(css_recurse, "opacity", nullptr); apply_css_recursive(&child, css_recurse); sp_repr_css_attr_unref(css_recurse); } else { - apply_css_recursive(&child, const_cast<SPCSSAttr*>(css)); + apply_css_recursive(&child, const_cast<SPCSSAttr *>(css)); } } } @@ -1511,19 +1517,22 @@ which are between \a start_item and \a end_item, creating spans as necessary. If \a start_item or \a end_item are NULL then the style is applied to all objects to the beginning or end respectively. \a span_object_name is the name of the xml for a text span (ie tspan or flowspan). */ -static void recursively_apply_style(SPObject *common_ancestor, SPCSSAttr const *css, SPObject *start_item, Glib::ustring::iterator start_text_iter, SPObject *end_item, Glib::ustring::iterator end_text_iter, char const *span_object_name) +static void recursively_apply_style(SPObject *common_ancestor, SPCSSAttr const *css, SPObject *start_item, + Glib::ustring::iterator start_text_iter, SPObject *end_item, + Glib::ustring::iterator end_text_iter, char const *span_object_name) { bool passed_start = start_item == nullptr ? true : false; Inkscape::XML::Document *xml_doc = common_ancestor->document->getReprDoc(); - for (SPObject *child = common_ancestor->firstChild() ; child ; child = child->getNext()) { + for (SPObject *child = common_ancestor->firstChild(); child; child = child->getNext()) { if (start_item == child) { passed_start = true; } if (passed_start) { if (end_item && child->isAncestorOf(end_item)) { - recursively_apply_style(child, css, nullptr, start_text_iter, end_item, end_text_iter, span_object_name); + recursively_apply_style(child, css, nullptr, start_text_iter, end_item, end_text_iter, + span_object_name); break; } // apply style @@ -1535,7 +1544,8 @@ static void recursively_apply_style(SPObject *common_ancestor, SPCSSAttr const * bool surround_entire_string = true; Inkscape::XML::Node *child_span = xml_doc->createElement(span_object_name); - sp_repr_css_set(child_span, const_cast<SPCSSAttr*>(css), "style"); // better hope that prototype wasn't nonconst for a good reason + sp_repr_css_set(child_span, const_cast<SPCSSAttr *>(css), + "style"); // better hope that prototype wasn't nonconst for a good reason SPObject *prev_item = child->getPrev(); Inkscape::XML::Node *prev_repr = prev_item ? prev_item->getRepr() : nullptr; @@ -1546,11 +1556,13 @@ static void recursively_apply_style(SPObject *common_ancestor, SPCSSAttr const * unsigned start_char_index = char_index_of_iterator(string_item->string, start_text_iter); unsigned end_char_index = char_index_of_iterator(string_item->string, end_text_iter); - Inkscape::XML::Node *text_before = xml_doc->createTextNode(string_item->string.substr(0, start_char_index).c_str()); + Inkscape::XML::Node *text_before = + xml_doc->createTextNode(string_item->string.substr(0, start_char_index).c_str()); common_ancestor->getRepr()->addChild(text_before, prev_repr); common_ancestor->getRepr()->addChild(child_span, text_before); Inkscape::GC::release(text_before); - Inkscape::XML::Node *text_in_span = xml_doc->createTextNode(string_item->string.substr(start_char_index, end_char_index - start_char_index).c_str()); + Inkscape::XML::Node *text_in_span = xml_doc->createTextNode( + string_item->string.substr(start_char_index, end_char_index - start_char_index).c_str()); child_span->appendChild(text_in_span); Inkscape::GC::release(text_in_span); child->getRepr()->setContent(string_item->string.substr(end_char_index).c_str()); @@ -1561,7 +1573,8 @@ static void recursively_apply_style(SPObject *common_ancestor, SPCSSAttr const * unsigned end_char_index = char_index_of_iterator(string_item->string, end_text_iter); common_ancestor->getRepr()->addChild(child_span, prev_repr); - Inkscape::XML::Node *text_in_span = xml_doc->createTextNode(string_item->string.substr(0, end_char_index).c_str()); + Inkscape::XML::Node *text_in_span = + xml_doc->createTextNode(string_item->string.substr(0, end_char_index).c_str()); child_span->appendChild(text_in_span); Inkscape::GC::release(text_in_span); child->getRepr()->setContent(string_item->string.substr(end_char_index).c_str()); @@ -1569,11 +1582,13 @@ static void recursively_apply_style(SPObject *common_ancestor, SPCSSAttr const * // eg "abcDEF" -> "abc"<span>"DEF"</span> unsigned start_char_index = char_index_of_iterator(string_item->string, start_text_iter); - Inkscape::XML::Node *text_before = xml_doc->createTextNode(string_item->string.substr(0, start_char_index).c_str()); + Inkscape::XML::Node *text_before = + xml_doc->createTextNode(string_item->string.substr(0, start_char_index).c_str()); common_ancestor->getRepr()->addChild(text_before, prev_repr); common_ancestor->getRepr()->addChild(child_span, text_before); Inkscape::GC::release(text_before); - Inkscape::XML::Node *text_in_span = xml_doc->createTextNode(string_item->string.substr(start_char_index).c_str()); + Inkscape::XML::Node *text_in_span = + xml_doc->createTextNode(string_item->string.substr(start_char_index).c_str()); child_span->appendChild(text_in_span); Inkscape::GC::release(text_in_span); child->deleteObject(); @@ -1593,15 +1608,16 @@ static void recursively_apply_style(SPObject *common_ancestor, SPCSSAttr const * } Inkscape::GC::release(child_span); - } else if (child != end_item) { // not a string and we're applying to the entire object. This is easy + } else if (child != end_item) { // not a string and we're applying to the entire object. This is easy apply_css_recursive(child, css); } - } else { // !passed_start + } else { // !passed_start if (child->isAncestorOf(start_item)) { - recursively_apply_style(child, css, start_item, start_text_iter, end_item, end_text_iter, span_object_name); + recursively_apply_style(child, css, start_item, start_text_iter, end_item, end_text_iter, + span_object_name); if (end_item && child->isAncestorOf(end_item)) - break; // only happens when start_item == end_item (I think) + break; // only happens when start_item == end_item (I think) passed_start = true; } } @@ -1619,14 +1635,14 @@ a string can never be an ancestor. eg: <span><span>*ABC</span>DEFghi</span> where * is the \a item. We would like * to point to the inner span because we can apply style to that whole span. */ -static SPObject* ascend_while_first(SPObject *item, Glib::ustring::iterator text_iter, SPObject *common_ancestor) +static SPObject *ascend_while_first(SPObject *item, Glib::ustring::iterator text_iter, SPObject *common_ancestor) { if (item == common_ancestor) return item; if (SP_IS_STRING(item)) if (text_iter != SP_STRING(item)->string.begin()) return item; - for ( ; ; ) { + for (;;) { SPObject *parent = item->parent; if (parent == common_ancestor) { break; @@ -1639,16 +1655,13 @@ static SPObject* ascend_while_first(SPObject *item, Glib::ustring::iterator text return item; } - /** empty spans: abc<span></span>def -> abcdef */ static bool tidy_operator_empty_spans(SPObject **item, bool /*has_text_decoration*/) { bool result = false; - if ( !(*item)->hasChildren() - && !is_line_break_object(*item) - && !(SP_IS_STRING(*item) && !SP_STRING(*item)->string.empty()) - ) { + if (!(*item)->hasChildren() && !is_line_break_object(*item) && + !(SP_IS_STRING(*item) && !SP_STRING(*item)->string.empty())) { SPObject *next = (*item)->getNext(); (*item)->deleteObject(); *item = next; @@ -1662,7 +1675,7 @@ static bool tidy_operator_empty_spans(SPObject **item, bool /*has_text_decoratio the repeated strings will be merged by another operator. */ static bool tidy_operator_inexplicable_spans(SPObject **item, bool /*has_text_decoration*/) { - //XML Tree being directly used here while it shouldn't be. + // XML Tree being directly used here while it shouldn't be. if (*item && sp_repr_is_meta_element((*item)->getRepr())) { return false; } @@ -1699,12 +1712,14 @@ static bool tidy_operator_repeated_spans(SPObject **item, bool /*has_text_decora { SPObject *first = *item; SPObject *second = first->getNext(); - if (second == nullptr) return false; + if (second == nullptr) + return false; Inkscape::XML::Node *first_repr = first->getRepr(); Inkscape::XML::Node *second_repr = second->getRepr(); - if (first_repr->type() != second_repr->type()) return false; + if (first_repr->type() != second_repr->type()) + return false; if (SP_IS_STRING(first) && SP_IS_STRING(second)) { // also amalgamate consecutive SPStrings into one @@ -1715,13 +1730,16 @@ static bool tidy_operator_repeated_spans(SPObject **item, bool /*has_text_decora } // merge consecutive spans with identical styles into one - if (first_repr->type() != Inkscape::XML::ELEMENT_NODE) return false; - if (strcmp(first_repr->name(), second_repr->name()) != 0) return false; - if (is_line_break_object(second)) return false; + if (first_repr->type() != Inkscape::XML::ELEMENT_NODE) + return false; + if (strcmp(first_repr->name(), second_repr->name()) != 0) + return false; + if (is_line_break_object(second)) + return false; gchar const *first_style = first_repr->attribute("style"); gchar const *second_style = second_repr->attribute("style"); - if (!((first_style == nullptr && second_style == nullptr) - || (first_style != nullptr && second_style != nullptr && !strcmp(first_style, second_style)))) + if (!((first_style == nullptr && second_style == nullptr) || + (first_style != nullptr && second_style != nullptr && !strcmp(first_style, second_style)))) return false; // all our tests passed: do the merge @@ -1806,7 +1824,7 @@ static bool redundant_double_nesting_processor(SPObject **item, SPObject *child, child->getRepr()->removeChild(move_repr); (*item)->parent->getRepr()->addChild(move_repr, insert_after_repr); Inkscape::GC::release(move_repr); - insert_after_repr = move_repr; // I think this will stay valid long enough. It's garbage collected these days. + insert_after_repr = move_repr; // I think this will stay valid long enough. It's garbage collected these days. } child->deleteObject(); return true; @@ -1821,8 +1839,10 @@ below, and I'm not yet convinced that the result of that operation will be tidier in all cases. */ static bool tidy_operator_redundant_double_nesting(SPObject **item, bool /*has_text_decoration*/) { - if (!(*item)->hasChildren()) return false; - if ((*item)->firstChild() == (*item)->lastChild()) return false; // this is excessive nesting, done above + if (!(*item)->hasChildren()) + return false; + if ((*item)->firstChild() == (*item)->lastChild()) + return false; // this is excessive nesting, done above if (redundant_double_nesting_processor(item, (*item)->firstChild(), true)) return true; if (redundant_double_nesting_processor(item, (*item)->lastChild(), false)) @@ -1837,13 +1857,18 @@ static bool redundant_semi_nesting_processor(SPObject **item, SPObject *child, b { if (SP_IS_FLOWREGION(child) || SP_IS_FLOWREGIONEXCLUDE(child)) return false; - if (SP_IS_STRING(child)) return false; - if (is_line_break_object(child)) return false; - if (is_line_break_object(*item)) return false; + if (SP_IS_STRING(child)) + return false; + if (is_line_break_object(child)) + return false; + if (is_line_break_object(*item)) + return false; TextTagAttributes *attrs = attributes_for_object(child); - if (attrs && attrs->anyAttributesSet()) return false; + if (attrs && attrs->anyAttributesSet()) + return false; attrs = attributes_for_object(*item); - if (attrs && attrs->anyAttributesSet()) return false; + if (attrs && attrs->anyAttributesSet()) + return false; SPCSSAttr *css_child_and_item = sp_repr_css_attr_new(); SPCSSAttr *css_child_only = sp_repr_css_attr_new(); @@ -1859,7 +1884,8 @@ static bool redundant_semi_nesting_processor(SPObject **item, SPObject *child, b bool equal = css_attrs_are_equal(css_child_only, css_child_and_item); sp_repr_css_attr_unref(css_child_and_item); sp_repr_css_attr_unref(css_child_only); - if (!equal) return false; + if (!equal) + return false; Inkscape::XML::Document *xml_doc = (*item)->getRepr()->document(); Inkscape::XML::Node *new_span = xml_doc->createElement((*item)->getRepr()->name()); @@ -1882,8 +1908,10 @@ test this by applying a colour to a region, then a different colour to a partially-overlapping region. */ static bool tidy_operator_redundant_semi_nesting(SPObject **item, bool /*has_text_decoration*/) { - if (!(*item)->hasChildren()) return false; - if ((*item)->firstChild() == (*item)->lastChild()) return false; // this is redundant nesting, done above + if (!(*item)->hasChildren()) + return false; + if ((*item)->firstChild() == (*item)->lastChild()) + return false; // this is redundant nesting, done above if (redundant_semi_nesting_processor(item, (*item)->firstChild(), true)) return true; if (redundant_semi_nesting_processor(item, (*item)->lastChild(), false)) @@ -1891,12 +1919,11 @@ static bool tidy_operator_redundant_semi_nesting(SPObject **item, bool /*has_tex return false; } - -/* tidy_operator_styled_whitespace commented out: not only did it have bugs, - * but it did *not* preserve the rendering: spaces in different font sizes, - * for instance, have different width, so moving them out of tspans changes +/* tidy_operator_styled_whitespace commented out: not only did it have bugs, + * but it did *not* preserve the rendering: spaces in different font sizes, + * for instance, have different width, so moving them out of tspans changes * the document. cf https://bugs.launchpad.net/inkscape/+bug/1477723 -*/ + */ #if 0 /** helper for tidy_operator_styled_whitespace(), finds the last string object @@ -2005,18 +2032,14 @@ out if this is so. */ static bool tidy_xml_tree_recursively(SPObject *root, bool has_text_decoration) { gchar const *root_style = (root)->getRepr()->attribute("style"); - if(root_style && strstr(root_style,"text-decoration"))has_text_decoration = true; - static bool (* const tidy_operators[])(SPObject**, bool) = { - tidy_operator_empty_spans, - tidy_operator_inexplicable_spans, - tidy_operator_repeated_spans, - tidy_operator_excessive_nesting, - tidy_operator_redundant_double_nesting, - tidy_operator_redundant_semi_nesting - }; + if (root_style && strstr(root_style, "text-decoration")) + has_text_decoration = true; + static bool (*const tidy_operators[])(SPObject **, bool) = { + tidy_operator_empty_spans, tidy_operator_inexplicable_spans, tidy_operator_repeated_spans, + tidy_operator_excessive_nesting, tidy_operator_redundant_double_nesting, tidy_operator_redundant_semi_nesting}; bool changes = false; - for (SPObject *child = root->firstChild() ; child != nullptr ; ) { + for (SPObject *child = root->firstChild(); child != nullptr;) { if (SP_IS_FLOWREGION(child) || SP_IS_FLOWREGIONEXCLUDE(child) || SP_IS_TREF(child)) { child = child->getNext(); continue; @@ -2026,7 +2049,7 @@ static bool tidy_xml_tree_recursively(SPObject *root, bool has_text_decoration) } unsigned i; - for (i = 0 ; i < sizeof(tidy_operators) / sizeof(tidy_operators[0]) ; i++) { + for (i = 0; i < sizeof(tidy_operators) / sizeof(tidy_operators[0]); i++) { if (tidy_operators[i](&child, has_text_decoration)) { changes = true; break; @@ -2042,10 +2065,12 @@ static bool tidy_xml_tree_recursively(SPObject *root, bool has_text_decoration) /** Applies the given CSS fragment to the characters of the given text or flowtext object between \a start and \a end, creating or removing span elements as necessary and optimal. */ -void sp_te_apply_style(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPCSSAttr const *css) +void sp_te_apply_style(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPCSSAttr const *css) { // in the comments in the code below, capital letters are inside the application region, lowercase are outside - if (start == end) return; + if (start == end) + return; Inkscape::Text::Layout::iterator first, last; if (start < end) { first = start; @@ -2060,7 +2085,7 @@ void sp_te_apply_style(SPItem *text, Inkscape::Text::Layout::iterator const &sta layout->getSourceOfCharacter(first, &start_item, &start_text_iter); layout->getSourceOfCharacter(last, &end_item, &end_text_iter); if (start_item == nullptr) { - return; // start is at end of text + return; // start is at end of text } if (is_line_break_object(start_item)) { start_item = start_item->getNext(); @@ -2071,16 +2096,14 @@ void sp_te_apply_style(SPItem *text, Inkscape::Text::Layout::iterator const &sta if (end_item == nullptr) { end_item = text; } - - + /* Special case: With a tref, we only want to change its style when the whole * string is selected, in which case the style can be applied directly to the * tref node. If only part of the tref's string child is selected, just return. */ - + if (!sp_tref_fully_contained(start_item, start_text_iter, end_item, end_text_iter)) { - return; - } + } /* stage 1: applying the style. Go up to the closest common ancestor of start and end and then semi-recursively apply the style to all the @@ -2095,19 +2118,19 @@ void sp_te_apply_style(SPItem *text, Inkscape::Text::Layout::iterator const &sta // bug #168370 (consider parent transform and viewBox) // snipplet copied from desktop-style.cpp sp_desktop_apply_css_recursive(...) SPCSSAttr *css_set = sp_repr_css_attr_new(); - sp_repr_css_merge(css_set, const_cast<SPCSSAttr*>(css)); + sp_repr_css_merge(css_set, const_cast<SPCSSAttr *>(css)); { Geom::Affine const local(SP_ITEM(common_ancestor)->i2doc_affine()); double const ex(local.descrim()); - if ( ( ex != 0. ) - && ( ex != 1. ) ) { - sp_css_attr_scale(css_set, 1/ex); + if ((ex != 0.) && (ex != 1.)) { + sp_css_attr_scale(css_set, 1 / ex); } } start_item = ascend_while_first(start_item, start_text_iter, common_ancestor); end_item = ascend_while_first(end_item, end_text_iter, common_ancestor); - recursively_apply_style(common_ancestor, css_set, start_item, start_text_iter, end_item, end_text_iter, span_name_for_text_object(text)); + recursively_apply_style(common_ancestor, css_set, start_item, start_text_iter, end_item, end_text_iter, + span_name_for_text_object(text)); sp_repr_css_attr_unref(css_set); /* stage 2: cleanup the xml tree (of which there are multiple passes) */ @@ -2124,29 +2147,24 @@ void sp_te_apply_style(SPItem *text, Inkscape::Text::Layout::iterator const &sta roundtrippability. */ bool has_text_decoration = false; gchar const *root_style = (text)->getRepr()->attribute("style"); - if(root_style && strstr(root_style,"text-decoration")) has_text_decoration = true; - while (tidy_xml_tree_recursively(common_ancestor, has_text_decoration)){}; + if (root_style && strstr(root_style, "text-decoration")) + has_text_decoration = true; + while (tidy_xml_tree_recursively(common_ancestor, has_text_decoration)) { + }; // if we only modified subobjects this won't have been automatically sent text->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); } -bool is_part_of_text_subtree (SPObject *obj) +bool is_part_of_text_subtree(SPObject *obj) { - return (SP_IS_TSPAN(obj) - || SP_IS_TEXT(obj) - || SP_IS_FLOWTEXT(obj) - || SP_IS_FLOWTSPAN(obj) - || SP_IS_FLOWDIV(obj) - || SP_IS_FLOWPARA(obj) - || SP_IS_FLOWLINE(obj) - || SP_IS_FLOWREGIONBREAK(obj)); + return (SP_IS_TSPAN(obj) || SP_IS_TEXT(obj) || SP_IS_FLOWTEXT(obj) || SP_IS_FLOWTSPAN(obj) || SP_IS_FLOWDIV(obj) || + SP_IS_FLOWPARA(obj) || SP_IS_FLOWLINE(obj) || SP_IS_FLOWREGIONBREAK(obj)); } -bool is_top_level_text_object (SPObject *obj) +bool is_top_level_text_object(SPObject *obj) { - return (SP_IS_TEXT(obj) - || SP_IS_FLOWTEXT(obj)); + return (SP_IS_TEXT(obj) || SP_IS_FLOWTEXT(obj)); } bool has_visible_text(SPObject *obj) @@ -2156,7 +2174,7 @@ bool has_visible_text(SPObject *obj) if (SP_IS_STRING(obj) && !SP_STRING(obj)->string.empty()) { hasVisible = true; // maybe we should also check that it's not all whitespace? } else { - for (auto& child: obj->children) { + for (auto &child : obj->children) { if (has_visible_text(const_cast<SPObject *>(&child))) { hasVisible = true; break; diff --git a/src/text-editing.h b/src/text-editing.h index 2c5a9675ced61d109bb5d8b89bee4e3582e960da..9a40321e3c8a5484491bb664a83ab11d1c4eb40c 100644 --- a/src/text-editing.h +++ b/src/text-editing.h @@ -14,7 +14,8 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <utility> // std::pair +#include <utility> // std::pair + #include "libnrtype/Layout-TNG.h" #include "text-tag-attributes.h" @@ -24,10 +25,9 @@ class SPItem; class SPObject; class SPStyle; -typedef std::pair<Inkscape::Text::Layout::iterator, Inkscape::Text::Layout::iterator> iterator_pair; - +typedef std::pair<Inkscape::Text::Layout::iterator, Inkscape::Text::Layout::iterator> iterator_pair; -Inkscape::Text::Layout const * te_get_layout (SPItem const *item); +Inkscape::Text::Layout const *te_get_layout(SPItem const *item); void te_update_layout_now_recursive(SPItem *item); @@ -45,41 +45,58 @@ unsigned sp_text_get_length(SPObject const *item); \a item, before and not including \a upto. Also adds 1 for each line break encountered. */ unsigned sp_text_get_length_upto(SPObject const *item, SPObject const *upto); -std::vector<Geom::Point> sp_te_create_selection_quads(SPItem const *item, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, Geom::Affine const &transform); +std::vector<Geom::Point> sp_te_create_selection_quads(SPItem const *item, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, + Geom::Affine const &transform); -Inkscape::Text::Layout::iterator sp_te_get_position_by_coords (SPItem const *item, Geom::Point const &i_p); -void sp_te_get_cursor_coords (SPItem const *item, Inkscape::Text::Layout::iterator const &position, Geom::Point &p0, Geom::Point &p1); -double sp_te_get_average_linespacing (SPItem *text); +Inkscape::Text::Layout::iterator sp_te_get_position_by_coords(SPItem const *item, Geom::Point const &i_p); +void sp_te_get_cursor_coords(SPItem const *item, Inkscape::Text::Layout::iterator const &position, Geom::Point &p0, + Geom::Point &p1); +double sp_te_get_average_linespacing(SPItem *text); -SPStyle const * sp_te_style_at_position(SPItem const *text, Inkscape::Text::Layout::iterator const &position); -SPObject const * sp_te_object_at_position(SPItem const *text, Inkscape::Text::Layout::iterator const &position); +SPStyle const *sp_te_style_at_position(SPItem const *text, Inkscape::Text::Layout::iterator const &position); +SPObject const *sp_te_object_at_position(SPItem const *text, Inkscape::Text::Layout::iterator const &position); -Inkscape::Text::Layout::iterator sp_te_insert(SPItem *item, Inkscape::Text::Layout::iterator const &position, char const *utf8); -Inkscape::Text::Layout::iterator sp_te_replace(SPItem *item, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, char const *utf8); -Inkscape::Text::Layout::iterator sp_te_insert_line (SPItem *text, Inkscape::Text::Layout::iterator &position); -bool sp_te_delete (SPItem *item, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, iterator_pair &iter_pair); +Inkscape::Text::Layout::iterator sp_te_insert(SPItem *item, Inkscape::Text::Layout::iterator const &position, + char const *utf8); +Inkscape::Text::Layout::iterator sp_te_replace(SPItem *item, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, char const *utf8); +Inkscape::Text::Layout::iterator sp_te_insert_line(SPItem *text, Inkscape::Text::Layout::iterator &position); +bool sp_te_delete(SPItem *item, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, iterator_pair &iter_pair); Glib::ustring sp_te_get_string_multiline(SPItem const *text); -Glib::ustring sp_te_get_string_multiline(SPItem const *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end); +Glib::ustring sp_te_get_string_multiline(SPItem const *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end); void sp_te_set_repr_text_multiline(SPItem *text, char const *str); -TextTagAttributes* -text_tag_attributes_at_position(SPItem *item, Inkscape::Text::Layout::iterator const &position, unsigned *char_index); - -void sp_te_adjust_kerning_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, Geom::Point by); -void sp_te_adjust_dx (SPItem *item, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double delta); -void sp_te_adjust_dy (SPItem *item, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double delta); - -void sp_te_adjust_rotation_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double pixels); -void sp_te_adjust_rotation(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double degrees); -void sp_te_set_rotation(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double degrees); - -void sp_te_adjust_tspan_letterspacing_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double by); -void sp_te_adjust_linespacing_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double by); -void sp_te_apply_style(SPItem *text, Inkscape::Text::Layout::iterator const &start, Inkscape::Text::Layout::iterator const &end, SPCSSAttr const *css); - -bool is_part_of_text_subtree (SPObject *obj); -bool is_top_level_text_object (SPObject *obj); -bool has_visible_text (SPObject *obj); +TextTagAttributes *text_tag_attributes_at_position(SPItem *item, Inkscape::Text::Layout::iterator const &position, + unsigned *char_index); + +void sp_te_adjust_kerning_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, Geom::Point by); +void sp_te_adjust_dx(SPItem *item, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double delta); +void sp_te_adjust_dy(SPItem *item, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double delta); + +void sp_te_adjust_rotation_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double pixels); +void sp_te_adjust_rotation(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double degrees); +void sp_te_set_rotation(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double degrees); + +void sp_te_adjust_tspan_letterspacing_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, + double by); +void sp_te_adjust_linespacing_screen(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPDesktop *desktop, double by); +void sp_te_apply_style(SPItem *text, Inkscape::Text::Layout::iterator const &start, + Inkscape::Text::Layout::iterator const &end, SPCSSAttr const *css); + +bool is_part_of_text_subtree(SPObject *obj); +bool is_top_level_text_object(SPObject *obj); +bool has_visible_text(SPObject *obj); #endif // SEEN_SP_TEXT_EDITING_H diff --git a/src/text-tag-attributes.h b/src/text-tag-attributes.h index b02605982ec5bbc21ab038546a39e55493067dce..051c7a481bdbb47c215e09c962b3bbf2432a89c1 100644 --- a/src/text-tag-attributes.h +++ b/src/text-tag-attributes.h @@ -15,9 +15,10 @@ #ifndef INKSCAPE_TEXT_TAG_ATTRIBUTES_H #define INKSCAPE_TEXT_TAG_ATTRIBUTES_H +#include <glib.h> #include <utility> #include <vector> -#include <glib.h> + #include "libnrtype/Layout-TNG.h" #include "svg/svg-length.h" @@ -25,14 +26,16 @@ namespace Inkscape { namespace XML { class Node; } -} +} // namespace Inkscape enum class SPAttr; -class TextTagAttributes { +class TextTagAttributes +{ public: TextTagAttributes() = default; TextTagAttributes(Inkscape::Text::Layout::OptionalTextTagAttrs attrs) - : attributes(std::move(attrs)) {} + : attributes(std::move(attrs)) + {} /// Fill in all the fields of #attributes from the given node. void readFrom(Inkscape::XML::Node const *node); @@ -45,7 +48,7 @@ public: void writeTo(Inkscape::XML::Node *node) const; /// Update relative values - void update( double em, double ex, double w, double h ); + void update(double em, double ex, double w, double h); /** For tspan role=line elements we should not use the set x,y coordinates since that would overrule the values calculated by the @@ -66,7 +69,9 @@ public: be used. Basically, the algorithm is that if a child attribute exists that will be used, otherwise the parent attribute will be used, otherwise the vector will end. textLength is never merged with parent. */ - void mergeInto(Inkscape::Text::Layout::OptionalTextTagAttrs *output, Inkscape::Text::Layout::OptionalTextTagAttrs const &parent_attrs, unsigned parent_attrs_offset, bool copy_xy, bool copy_dxdyrotate) const; + void mergeInto(Inkscape::Text::Layout::OptionalTextTagAttrs *output, + Inkscape::Text::Layout::OptionalTextTagAttrs const &parent_attrs, unsigned parent_attrs_offset, + bool copy_xy, bool copy_dxdyrotate) const; /** Deletes all the values from all the vectors beginning at \a start_index and extending for \a n fields. This is what you want @@ -139,10 +144,10 @@ public: void setFirstXY(Geom::Point &point); /** Gets first value in the x vector as an SVGLength. Not guaranteed to remain valid. */ - SVGLength* getFirstXLength(); + SVGLength *getFirstXLength(); /** Gets first value in the y vector as an SVGLength. Not guaranteed to remain valid. */ - SVGLength* getFirstYLength(); + SVGLength *getFirstYLength(); SVGLength *getTextLength() { return &(attributes.textLength); } int getLengthAdjust() { return attributes.lengthAdjust; } @@ -154,7 +159,8 @@ private: /** Does the reverse of readSingleAttribute(), converting a vector<> to its SVG string representation and writing it in to \a node. Used by writeTo(). */ - static void writeSingleAttributeVector(Inkscape::XML::Node *node, gchar const *key, std::vector<SVGLength> const &attr_vector); + static void writeSingleAttributeVector(Inkscape::XML::Node *node, gchar const *key, + std::vector<SVGLength> const &attr_vector); /** Writes a single length value to \a node. Used by writeTo(). */ @@ -163,22 +169,25 @@ private: /** Does mergeInto() for one member of #attributes. If \a overlay_list is NULL then it does a simple copy of parent elements, starting at \a parent_offset. */ - static void mergeSingleAttribute(std::vector<SVGLength> *output_list, std::vector<SVGLength> const &parent_list, unsigned parent_offset, std::vector<SVGLength> const *overlay_list = nullptr); + static void mergeSingleAttribute(std::vector<SVGLength> *output_list, std::vector<SVGLength> const &parent_list, + unsigned parent_offset, std::vector<SVGLength> const *overlay_list = nullptr); /// Does the work for erase(). static void eraseSingleAttribute(std::vector<SVGLength> *attr_vector, unsigned start_index, unsigned n); /// Does the work for insert(). - static void insertSingleAttribute(std::vector<SVGLength> *attr_vector, unsigned start_index, unsigned n, bool is_xy); + static void insertSingleAttribute(std::vector<SVGLength> *attr_vector, unsigned start_index, unsigned n, + bool is_xy); /// Does the work for split(). - static void splitSingleAttribute(std::vector<SVGLength> *first_vector, unsigned index, std::vector<SVGLength> *second_vector, bool trimZeros); + static void splitSingleAttribute(std::vector<SVGLength> *first_vector, unsigned index, + std::vector<SVGLength> *second_vector, bool trimZeros); /// Does the work for join(). - static void joinSingleAttribute(std::vector<SVGLength> *dest_vector, std::vector<SVGLength> const &first_vector, std::vector<SVGLength> const &second_vector, unsigned second_index); + static void joinSingleAttribute(std::vector<SVGLength> *dest_vector, std::vector<SVGLength> const &first_vector, + std::vector<SVGLength> const &second_vector, unsigned second_index); }; - #endif /* !INKSCAPE_TEXT_TAG_ATTRIBUTES_H */ /* diff --git a/src/trace/autotrace/inkscape-autotrace.cpp b/src/trace/autotrace/inkscape-autotrace.cpp index dd8c37c59e16283a4c42adfec250c326c45ce642..afeb75fc7c8719ae5095b34390a60857234e6396 100644 --- a/src/trace/autotrace/inkscape-autotrace.cpp +++ b/src/trace/autotrace/inkscape-autotrace.cpp @@ -22,19 +22,16 @@ extern "C" { #include <glibmm/i18n.h> #include <gtkmm/main.h> +#include <inkscape.h> #include <iomanip> - -#include "trace/filterset.h" -#include "trace/imagemap-gdk.h" -#include "trace/quantize.h" +#include <svg/path-string.h> #include "desktop.h" #include "message-stack.h" -#include <inkscape.h> - #include "object/sp-path.h" - -#include <svg/path-string.h> +#include "trace/filterset.h" +#include "trace/imagemap-gdk.h" +#include "trace/quantize.h" using Glib::ustring; @@ -52,17 +49,18 @@ namespace Trace { namespace Autotrace { -static guchar* to_3channels(GdkPixbuf* input) { +static guchar *to_3channels(GdkPixbuf *input) +{ int imgsize = gdk_pixbuf_get_height(input) * gdk_pixbuf_get_width(input); - guchar *out = (guchar*)malloc(3 * imgsize); - int x=0; - guchar* pix = gdk_pixbuf_get_pixels (input); - int rs = gdk_pixbuf_get_rowstride (input); - for(int row=0;row<gdk_pixbuf_get_height(input);row++) { - for (int col=0;col<gdk_pixbuf_get_width(input);col++) { + guchar *out = (guchar *)malloc(3 * imgsize); + int x = 0; + guchar *pix = gdk_pixbuf_get_pixels(input); + int rs = gdk_pixbuf_get_rowstride(input); + for (int row = 0; row < gdk_pixbuf_get_height(input); row++) { + for (int col = 0; col < gdk_pixbuf_get_width(input); col++) { guchar alpha = *(pix + row * rs + col * 4 + 3); guchar white = 255 - alpha; - for(int chan=0;chan<3;chan++) { + for (int chan = 0; chan < 3; chan++) { // guchar *pnew = (pix + row * rs + col * 3 + chan); guchar *pold = (pix + row * rs + col * 4 + chan); out[x++] = (guchar)(((int)(*pold) * (int)alpha / 256) + white); @@ -72,7 +70,6 @@ static guchar* to_3channels(GdkPixbuf* input) { return out; } - /** * */ @@ -83,23 +80,28 @@ AutotraceTracingEngine::AutotraceTracingEngine() { /* get default parameters */ opts = at_fitting_opts_new(); - opts->background_color = at_color_new(255,255,255); + opts->background_color = at_color_new(255, 255, 255); autotrace_init(); } -AutotraceTracingEngine::~AutotraceTracingEngine() { at_fitting_opts_free(opts); } - - +AutotraceTracingEngine::~AutotraceTracingEngine() +{ + at_fitting_opts_free(opts); +} // TODO -Glib::RefPtr<Gdk::Pixbuf> AutotraceTracingEngine::preview(Glib::RefPtr<Gdk::Pixbuf> thePixbuf) { - //auto x = thePixbuf.copy(); - guchar *pb = to_3channels(thePixbuf->gobj()); - return Gdk::Pixbuf::create_from_data(pb, thePixbuf->get_colorspace(), false, 8, thePixbuf->get_width(), thePixbuf->get_height(), (thePixbuf->get_width()*3)); - +Glib::RefPtr<Gdk::Pixbuf> AutotraceTracingEngine::preview(Glib::RefPtr<Gdk::Pixbuf> thePixbuf) +{ + // auto x = thePixbuf.copy(); + guchar *pb = to_3channels(thePixbuf->gobj()); + return Gdk::Pixbuf::create_from_data(pb, thePixbuf->get_colorspace(), false, 8, thePixbuf->get_width(), + thePixbuf->get_height(), (thePixbuf->get_width() * 3)); } -int test_cancel (void* keepGoing){return !(* ((int*)keepGoing));} +int test_cancel(void *keepGoing) +{ + return !(*((int *)keepGoing)); +} /** * This is the working method of this interface, and all @@ -111,25 +113,24 @@ std::vector<TracingEngineResult> AutotraceTracingEngine::trace(Glib::RefPtr<Gdk: { GdkPixbuf *pb1 = pixbuf->gobj(); guchar *pb = to_3channels(pb1); - + at_bitmap *bitmap = -// at_bitmap_new(gdk_pixbuf_get_width(pb), gdk_pixbuf_get_height(pb), gdk_pixbuf_get_n_channels(pb)); -// bitmap->bitmap = gdk_pixbuf_get_pixels(pb); - at_bitmap_new(gdk_pixbuf_get_width(pb1), gdk_pixbuf_get_height(pb1), 3); + // at_bitmap_new(gdk_pixbuf_get_width(pb), gdk_pixbuf_get_height(pb), gdk_pixbuf_get_n_channels(pb)); + // bitmap->bitmap = gdk_pixbuf_get_pixels(pb); + at_bitmap_new(gdk_pixbuf_get_width(pb1), gdk_pixbuf_get_height(pb1), 3); bitmap->bitmap = pb; - + at_splines_type *splines = at_splines_new_full(bitmap, opts, NULL, NULL, NULL, NULL, test_cancel, &keepGoing); // at_output_write_func wfunc = at_output_get_handler_by_suffix("svg"); // at_spline_writer *wfunc = at_output_get_handler_by_suffix("svg"); - int height = splines->height; // const at_splines_type spline = *splines; at_spline_list_array_type spline = *splines; unsigned this_list; at_spline_list_type list; - at_color last_color = { 0, 0, 0 }; + at_color last_color = {0, 0, 0}; std::stringstream theStyle; std::stringstream thePath; @@ -172,8 +173,7 @@ std::vector<TracingEngineResult> AutotraceTracingEngine::trace(Glib::RefPtr<Gdk: if (SPLINE_DEGREE(s) == AT_LINEARTYPE) { thePath << "L" << END_POINT(s).x << " " << height - END_POINT(s).y; nNodes++; - } - else { + } else { thePath << "C" << CONTROL1(s).x << " " << height - CONTROL1(s).y << " " << CONTROL2(s).x << " " << height - CONTROL2(s).y << " " << END_POINT(s).x << " " << height - END_POINT(s).y; nNodes++; @@ -195,7 +195,6 @@ std::vector<TracingEngineResult> AutotraceTracingEngine::trace(Glib::RefPtr<Gdk: return res; } - /** * Abort the thread that is executing getPathDataFromPixbuf() */ @@ -205,8 +204,6 @@ void AutotraceTracingEngine::abort() keepGoing = 0; } - - } // namespace Autotrace } // namespace Trace } // namespace Inkscape diff --git a/src/trace/autotrace/inkscape-autotrace.h b/src/trace/autotrace/inkscape-autotrace.h index f12eb35d8c92a516f33b85f03ad69c844ce85cd3..edfcc2ee845ddf4b2decaf1f2c29ca99c3486a7b 100644 --- a/src/trace/autotrace/inkscape-autotrace.h +++ b/src/trace/autotrace/inkscape-autotrace.h @@ -17,19 +17,24 @@ #ifndef __INKSCAPE_AUTOTRACE_H__ #define __INKSCAPE_AUTOTRACE_H__ -#include "3rdparty/autotrace/autotrace.h" #include <trace/trace.h> +#include "3rdparty/autotrace/autotrace.h" + namespace Inkscape { namespace Trace { namespace Autotrace { -enum TraceType { TRACE_CENTERLINE, TRACE_OUTLINE }; - -class AutotraceTracingEngine : public TracingEngine { - - public: +enum TraceType +{ + TRACE_CENTERLINE, + TRACE_OUTLINE +}; + +class AutotraceTracingEngine : public TracingEngine +{ +public: /** * */ @@ -40,7 +45,6 @@ class AutotraceTracingEngine : public TracingEngine { */ ~AutotraceTracingEngine() override; - /** * Sets/gets parameters */ @@ -69,7 +73,7 @@ class AutotraceTracingEngine : public TracingEngine { */ int keepGoing; - //private: + // private: // autotrace_param_t *autotraceParams; TraceType traceType; at_fitting_opts_type *opts; @@ -79,16 +83,12 @@ class AutotraceTracingEngine : public TracingEngine { }; // class AutotraceTracingEngine - - } // namespace Autotrace } // namespace Trace } // namespace Inkscape - #endif //__INKSCAPE_POTRACE_H__ - /* Local Variables: mode:c++ diff --git a/src/trace/depixelize/inkscape-depixelize.cpp b/src/trace/depixelize/inkscape-depixelize.cpp index eba1af055709dfb463a9b29d2df6bdf2ef715aee..f7cb560599a2feecd14d9220c5401dcad1659fde 100644 --- a/src/trace/depixelize/inkscape-depixelize.cpp +++ b/src/trace/depixelize/inkscape-depixelize.cpp @@ -18,33 +18,28 @@ #include "inkscape-depixelize.h" #include <glibmm/i18n.h> -#include <gtkmm/main.h> #include <gtkmm.h> +#include <gtkmm/main.h> #include <iomanip> +#include <svg/path-string.h> +#include <svg/svg-color.h> +#include <svg/svg.h> #include "desktop.h" -#include "message-stack.h" +#include "display/cairo-templates.h" #include "helper/geom.h" +#include "message-stack.h" #include "object/sp-path.h" - -#include "display/cairo-templates.h" - -#include <svg/path-string.h> -#include <svg/svg.h> -#include <svg/svg-color.h> #include "svg/css-ostringstream.h" using Glib::ustring; - - namespace Inkscape { namespace Trace { namespace Depixelize { - /** * */ @@ -55,8 +50,6 @@ DepixelizeTracingEngine::DepixelizeTracingEngine() params = new ::Tracer::Kopf2011::Options(); } - - DepixelizeTracingEngine::DepixelizeTracingEngine(TraceType traceType, double curves, int islands, int sparsePixels, double sparseMultiplier) : keepGoing(1) @@ -76,7 +69,10 @@ DepixelizeTracingEngine::DepixelizeTracingEngine(TraceType traceType, double cur 1, 256); } -DepixelizeTracingEngine::~DepixelizeTracingEngine() { delete params; } +DepixelizeTracingEngine::~DepixelizeTracingEngine() +{ + delete params; +} std::vector<TracingEngineResult> DepixelizeTracingEngine::trace(Glib::RefPtr<Gdk::Pixbuf> pixbuf) { @@ -86,9 +82,9 @@ std::vector<TracingEngineResult> DepixelizeTracingEngine::trace(Glib::RefPtr<Gdk "\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; -// TODO + // if (dialog.run() != Gtk::RESPONSE_OK) + // return; + // TODO } ::Tracer::Splines splines; @@ -101,15 +97,13 @@ std::vector<TracingEngineResult> DepixelizeTracingEngine::trace(Glib::RefPtr<Gdk std::vector<TracingEngineResult> res; for (::Tracer::Splines::const_iterator it = splines.begin(), end = splines.end(); it != end; ++it) { - 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]))); + 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]))); Inkscape::CSSOStringStream osalpha; osalpha << float(it->rgba[3]) / 255.; - gchar* style = g_strdup_printf("fill:%s;fill-opacity:%s;", b, osalpha.str().c_str()); + gchar *style = g_strdup_printf("fill:%s;fill-opacity:%s;", b, osalpha.str().c_str()); printf("%s\n", style); TracingEngineResult r(style, sp_svg_write_path(it->pathVector), count_pathvector_nodes(it->pathVector)); res.push_back(r); @@ -118,10 +112,15 @@ std::vector<TracingEngineResult> DepixelizeTracingEngine::trace(Glib::RefPtr<Gdk return res; } -void DepixelizeTracingEngine::abort() { keepGoing = 0; } - -Glib::RefPtr<Gdk::Pixbuf> DepixelizeTracingEngine::preview(Glib::RefPtr<Gdk::Pixbuf> pixbuf) { return pixbuf; } +void DepixelizeTracingEngine::abort() +{ + keepGoing = 0; +} +Glib::RefPtr<Gdk::Pixbuf> DepixelizeTracingEngine::preview(Glib::RefPtr<Gdk::Pixbuf> pixbuf) +{ + return pixbuf; +} } // namespace Depixelize } // namespace Trace diff --git a/src/trace/depixelize/inkscape-depixelize.h b/src/trace/depixelize/inkscape-depixelize.h index 228e72448387b0a427e93264206fa5eac83bb367..1f2277d3e475f678a5c28e2924d9bd21369a5ef0 100644 --- a/src/trace/depixelize/inkscape-depixelize.h +++ b/src/trace/depixelize/inkscape-depixelize.h @@ -15,6 +15,7 @@ #define __INKSCAPE_DEPIXTRACE_H__ #include <trace/trace.h> + #include "3rdparty/libdepixelize/kopftracer2011.h" struct GrayMap_def; @@ -27,17 +28,14 @@ namespace Trace { namespace Depixelize { enum TraceType - { +{ TRACE_VORONOI, TRACE_BSPLINES - }; - +}; class DepixelizeTracingEngine : public TracingEngine { - - public: - +public: /** * */ @@ -55,8 +53,7 @@ class DepixelizeTracingEngine : public TracingEngine * return the path data that is compatible with the d="" attribute * of an SVG <path> element. */ - std::vector<TracingEngineResult> trace( - Glib::RefPtr<Gdk::Pixbuf> pixbuf) override; + std::vector<TracingEngineResult> trace(Glib::RefPtr<Gdk::Pixbuf> pixbuf) override; /** * Abort the thread that is executing getPathDataFromPixbuf() @@ -76,17 +73,13 @@ class DepixelizeTracingEngine : public TracingEngine ::Tracer::Kopf2011::Options *params; TraceType traceType; -};//class PotraceTracingEngine - - - -} // namespace Depixelize -} // namespace Trace -} // namespace Inkscape - +}; // class PotraceTracingEngine -#endif //__INKSCAPE_TRACE_H__ +} // namespace Depixelize +} // namespace Trace +} // namespace Inkscape +#endif //__INKSCAPE_TRACE_H__ /* Local Variables: diff --git a/src/trace/filterset.cpp b/src/trace/filterset.cpp index fae6d66a649e1f040d0812b26c89918272b25e07..d1679d818762d790c99554d6023d873512cf2e13 100644 --- a/src/trace/filterset.cpp +++ b/src/trace/filterset.cpp @@ -11,11 +11,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "filterset.h" + #include <cstdio> #include <cstdlib> #include "imagemap-gdk.h" -#include "filterset.h" #include "quantize.h" /*######################################################################### @@ -25,196 +26,145 @@ /** * */ -static int gaussMatrix[] = -{ - 2, 4, 5, 4, 2, - 4, 9, 12, 9, 4, - 5, 12, 15, 12, 5, - 4, 9, 12, 9, 4, - 2, 4, 5, 4, 2 -}; - +static int gaussMatrix[] = {2, 4, 5, 4, 2, 4, 9, 12, 9, 4, 5, 12, 15, 12, 5, 4, 9, 12, 9, 4, 2, 4, 5, 4, 2}; /** * */ GrayMap *grayMapGaussian(GrayMap *me) { - int width = me->width; + int width = me->width; int height = me->height; int firstX = 2; - int lastX = width-3; + int lastX = width - 3; int firstY = 2; - int lastY = height-3; + int lastY = height - 3; GrayMap *newGm = GrayMapCreate(width, height); if (!newGm) return nullptr; - for (int y = 0 ; y<height ; y++) - { - for (int x = 0 ; x<width ; x++) - { - /* image boundaries */ - if (x<firstX || x>lastX || y<firstY || y>lastY) - { + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + /* image boundaries */ + if (x < firstX || x > lastX || y < firstY || y > lastY) { newGm->setPixel(newGm, x, y, me->getPixel(me, x, y)); continue; - } + } /* all other pixels */ int gaussIndex = 0; unsigned long sum = 0; - for (int i= y-2 ; i<=y+2 ; i++) - { - for (int j= x-2; j<=x+2 ; j++) - { + for (int i = y - 2; i <= y + 2; i++) { + for (int j = x - 2; j <= x + 2; j++) { int weight = gaussMatrix[gaussIndex++]; sum += me->getPixel(me, j, i) * weight; - } - } + } + } sum /= 159; - newGm->setPixel(newGm, x, y, sum); - } - } + newGm->setPixel(newGm, x, y, sum); + } + } return newGm; } - - - - /** * */ RgbMap *rgbMapGaussian(RgbMap *me) { - int width = me->width; + int width = me->width; int height = me->height; int firstX = 2; - int lastX = width-3; + int lastX = width - 3; int firstY = 2; - int lastY = height-3; + int lastY = height - 3; RgbMap *newGm = RgbMapCreate(width, height); if (!newGm) return nullptr; - for (int y = 0 ; y<height ; y++) - { - for (int x = 0 ; x<width ; x++) - { - /* image boundaries */ - if (x<firstX || x>lastX || y<firstY || y>lastY) - { + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + /* image boundaries */ + if (x < firstX || x > lastX || y < firstY || y > lastY) { newGm->setPixelRGB(newGm, x, y, me->getPixel(me, x, y)); continue; - } + } /* all other pixels */ int gaussIndex = 0; - int sumR = 0; - int sumG = 0; - int sumB = 0; - for (int i= y-2 ; i<=y+2 ; i++) - { - for (int j= x-2; j<=x+2 ; j++) - { + int sumR = 0; + int sumG = 0; + int sumB = 0; + for (int i = y - 2; i <= y + 2; i++) { + for (int j = x - 2; j <= x + 2; j++) { int weight = gaussMatrix[gaussIndex++]; RGB rgb = me->getPixel(me, j, i); sumR += weight * (int)rgb.r; sumG += weight * (int)rgb.g; sumB += weight * (int)rgb.b; - } - } + } + } RGB rout; - rout.r = ( sumR / 159 ) & 0xff; - rout.g = ( sumG / 159 ) & 0xff; - rout.b = ( sumB / 159 ) & 0xff; - newGm->setPixelRGB(newGm, x, y, rout); - } - } + rout.r = (sumR / 159) & 0xff; + rout.g = (sumG / 159) & 0xff; + rout.b = (sumB / 159) & 0xff; + newGm->setPixelRGB(newGm, x, y, rout); + } + } return newGm; - } - - - /*######################################################################### ### C A N N Y E D G E D E T E C T I O N #########################################################################*/ +static int sobelX[] = {-1, 0, 1, -2, 0, 2, -1, 0, 1}; -static int sobelX[] = -{ - -1, 0, 1 , - -2, 0, 2 , - -1, 0, 1 -}; - -static int sobelY[] = -{ - 1, 2, 1 , - 0, 0, 0 , - -1, -2, -1 -}; - - +static int sobelY[] = {1, 2, 1, 0, 0, 0, -1, -2, -1}; /** * Perform Sobel convolution on a GrayMap */ -static GrayMap *grayMapSobel(GrayMap *gm, - double dLowThreshold, double dHighThreshold) +static GrayMap *grayMapSobel(GrayMap *gm, double dLowThreshold, double dHighThreshold) { - int width = gm->width; + int width = gm->width; int height = gm->height; int firstX = 1; - int lastX = width-2; + int lastX = width - 2; int firstY = 1; - int lastY = height-2; + int lastY = height - 2; GrayMap *newGm = GrayMapCreate(width, height); if (!newGm) return nullptr; - for (int y = 0 ; y<height ; y++) - { - for (int x = 0 ; x<width ; x++) - { + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { unsigned long sum = 0; - /* image boundaries */ - if (x<firstX || x>lastX || y<firstY || y>lastY) - { + /* image boundaries */ + if (x < firstX || x > lastX || y < firstY || y > lastY) { sum = 0; - } - else - { + } else { /* ### SOBEL FILTERING #### */ long sumX = 0; long sumY = 0; int sobelIndex = 0; - for (int i= y-1 ; i<=y+1 ; i++) - { - for (int j= x-1; j<=x+1 ; j++) - { - sumX += gm->getPixel(gm, j, i) * - sobelX[sobelIndex++]; - } - } + for (int i = y - 1; i <= y + 1; i++) { + for (int j = x - 1; j <= x + 1; j++) { + sumX += gm->getPixel(gm, j, i) * sobelX[sobelIndex++]; + } + } sobelIndex = 0; - for (int i= y-1 ; i<=y+1 ; i++) - { - for (int j= x-1; j<=x+1 ; j++) - { - sumY += gm->getPixel(gm, j, i) * - sobelY[sobelIndex++]; - } - } + for (int i = y - 1; i <= y + 1; i++) { + for (int j = x - 1; j <= x + 1; j++) { + sumY += gm->getPixel(gm, j, i) * sobelY[sobelIndex++]; + } + } /*### GET VALUE ### */ sum = abs(sumX) + abs(sumY); @@ -256,22 +206,19 @@ static GrayMap *grayMapSobel(GrayMap *gm, #else /*### GET EDGE DIRECTION (fast way) ### */ int edgeDirection = 0; /*x,y=0*/ - if (sumX==0) - { - if (sumY!=0) + if (sumX == 0) { + if (sumY != 0) edgeDirection = 90; - } - else - { - /*long slope = sumY*1024/sumX;*/ - long slope = (sumY << 10)/sumX; - if (slope > 2472 || slope< -2472) /*tan(67.5)*1024*/ - edgeDirection = 90; - else if (slope > 414) /*tan(22.5)*1024*/ - edgeDirection = 45; - else if (slope < -414) /*-tan(22.5)*1024*/ - edgeDirection = 135; - } + } else { + /*long slope = sumY*1024/sumX;*/ + long slope = (sumY << 10) / sumX; + if (slope > 2472 || slope < -2472) /*tan(67.5)*1024*/ + edgeDirection = 90; + else if (slope > 414) /*tan(22.5)*1024*/ + edgeDirection = 45; + else if (slope < -414) /*-tan(22.5)*1024*/ + edgeDirection = 135; + } #endif /* printf("%ld %ld %f %d\n", sumX, sumY, orient, edgeDirection); */ @@ -279,79 +226,62 @@ static GrayMap *grayMapSobel(GrayMap *gm, /*### Get two adjacent pixels in edge direction ### */ unsigned long leftPixel; unsigned long rightPixel; - if (edgeDirection == 0) - { - leftPixel = gm->getPixel(gm, x-1, y); - rightPixel = gm->getPixel(gm, x+1, y); - } - else if (edgeDirection == 45) - { - leftPixel = gm->getPixel(gm, x-1, y+1); - rightPixel = gm->getPixel(gm, x+1, y-1); - } - else if (edgeDirection == 90) - { - leftPixel = gm->getPixel(gm, x, y-1); - rightPixel = gm->getPixel(gm, x, y+1); - } - else /*135 */ - { - leftPixel = gm->getPixel(gm, x-1, y-1); - rightPixel = gm->getPixel(gm, x+1, y+1); - } + if (edgeDirection == 0) { + leftPixel = gm->getPixel(gm, x - 1, y); + rightPixel = gm->getPixel(gm, x + 1, y); + } else if (edgeDirection == 45) { + leftPixel = gm->getPixel(gm, x - 1, y + 1); + rightPixel = gm->getPixel(gm, x + 1, y - 1); + } else if (edgeDirection == 90) { + leftPixel = gm->getPixel(gm, x, y - 1); + rightPixel = gm->getPixel(gm, x, y + 1); + } else /*135 */ + { + leftPixel = gm->getPixel(gm, x - 1, y - 1); + rightPixel = gm->getPixel(gm, x + 1, y + 1); + } /*### Compare current value to adjacent pixels ### */ /*### if less that either, suppress it ### */ if (sum < leftPixel || sum < rightPixel) sum = 0; - else - { - unsigned long highThreshold = - (unsigned long)(dHighThreshold * 765.0); - unsigned long lowThreshold = - (unsigned long)(dLowThreshold * 765.0); + else { + unsigned long highThreshold = (unsigned long)(dHighThreshold * 765.0); + unsigned long lowThreshold = (unsigned long)(dLowThreshold * 765.0); if (sum >= highThreshold) sum = 765; /* EDGE. 3*255 this needs to be settable */ else if (sum < lowThreshold) sum = 0; /* NONEDGE */ - else - { - if ( gm->getPixel(gm, x-1, y-1)> highThreshold || - gm->getPixel(gm, x , y-1)> highThreshold || - gm->getPixel(gm, x+1, y-1)> highThreshold || - gm->getPixel(gm, x-1, y )> highThreshold || - gm->getPixel(gm, x+1, y )> highThreshold || - gm->getPixel(gm, x-1, y+1)> highThreshold || - gm->getPixel(gm, x , y+1)> highThreshold || - gm->getPixel(gm, x+1, y+1)> highThreshold) + else { + if (gm->getPixel(gm, x - 1, y - 1) > highThreshold || + gm->getPixel(gm, x, y - 1) > highThreshold || + gm->getPixel(gm, x + 1, y - 1) > highThreshold || + gm->getPixel(gm, x - 1, y) > highThreshold || gm->getPixel(gm, x + 1, y) > highThreshold || + gm->getPixel(gm, x - 1, y + 1) > highThreshold || + gm->getPixel(gm, x, y + 1) > highThreshold || + gm->getPixel(gm, x + 1, y + 1) > highThreshold) sum = 765; /* EDGE fix me too */ else sum = 0; /* NONEDGE */ - } } + } - - }/* else */ - if (sum==0) /* invert light & dark */ + } /* else */ + if (sum == 0) /* invert light & dark */ sum = 765; else sum = 0; newGm->setPixel(newGm, x, y, sum); - }/* for (x) */ - }/* for (y) */ + } /* for (x) */ + } /* for (y) */ return newGm; } - - - - /** * */ -GrayMap * -grayMapCanny(GrayMap *gm, double lowThreshold, double highThreshold) +GrayMap *grayMapCanny(GrayMap *gm, double lowThreshold, double highThreshold) { if (!gm) return nullptr; @@ -364,8 +294,6 @@ grayMapCanny(GrayMap *gm, double lowThreshold, double highThreshold) return cannyGm; } - - /*######################################################################### ### Q U A N T I Z A T I O N #########################################################################*/ @@ -375,48 +303,34 @@ grayMapCanny(GrayMap *gm, double lowThreshold, double highThreshold) */ GrayMap *quantizeBand(RgbMap *rgbMap, int nrColors) { - RgbMap *gaussMap = rgbMapGaussian(rgbMap); - //gaussMap->writePPM(gaussMap, "rgbgauss.ppm"); + // gaussMap->writePPM(gaussMap, "rgbgauss.ppm"); IndexedMap *qMap = rgbMapQuantize(gaussMap, nrColors); - //qMap->writePPM(qMap, "rgbquant.ppm"); + // qMap->writePPM(qMap, "rgbquant.ppm"); gaussMap->destroy(gaussMap); GrayMap *gm = GrayMapCreate(rgbMap->width, rgbMap->height); // RGB is quantized. There should now be a small set of (R+G+B) - for (int y=0 ; y<qMap->height ; y++) - { - for (int x=0 ; x<qMap->width ; x++) - { + for (int y = 0; y < qMap->height; y++) { + for (int x = 0; x < qMap->width; x++) { RGB rgb = qMap->getPixelValue(qMap, x, y); int sum = rgb.r + rgb.g + rgb.b; if (sum & 1) sum = 765; else sum = 0; - // printf("%d %d %d : %d\n", rgb.r, rgb.g, rgb.b, index); + // printf("%d %d %d : %d\n", rgb.r, rgb.g, rgb.b, index); gm->setPixel(gm, x, y, sum); - } } + } qMap->destroy(qMap); return gm; } - /*######################################################################### ### E N D O F F I L E #########################################################################*/ - - - - - - - - - - diff --git a/src/trace/filterset.h b/src/trace/filterset.h index d8da650de40bc161c9c3fa45b7c76f545de72e60..5c7746339bbe9ba9c027bd5db79cc52d16d92071 100644 --- a/src/trace/filterset.h +++ b/src/trace/filterset.h @@ -14,10 +14,10 @@ #ifndef __FILTERSET_H__ #define __FILTERSET_H__ -#include "imagemap.h" - #include <gdk-pixbuf/gdk-pixbuf.h> +#include "imagemap.h" + #ifdef __cplusplus extern "C" { #endif @@ -35,21 +35,17 @@ RgbMap *rgbMapGaussian(RgbMap *rgbmap); /** * */ -GrayMap *grayMapCanny(GrayMap *gmap, - double lowThreshold, double highThreshold); +GrayMap *grayMapCanny(GrayMap *gmap, double lowThreshold, double highThreshold); /** * */ GrayMap *quantizeBand(RgbMap *rgbmap, int nrColors); - - #ifdef __cplusplus } #endif - #endif /* __FILTERSET_H__ */ /*######################################################################### diff --git a/src/trace/imagemap-gdk.cpp b/src/trace/imagemap-gdk.cpp index d1c1c4ed560bf9b41e69ff9cf313bcfd066cc090..ca7abdfee3bfce03314f563a0d3f31474ad45ab5 100644 --- a/src/trace/imagemap-gdk.cpp +++ b/src/trace/imagemap-gdk.cpp @@ -7,10 +7,9 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstdlib> - #include "imagemap-gdk.h" +#include <cstdlib> /*######################################################################### ## G R A Y M A P @@ -21,33 +20,31 @@ GrayMap *gdkPixbufToGrayMap(GdkPixbuf *buf) if (!buf) return nullptr; - int width = gdk_pixbuf_get_width(buf); - int height = gdk_pixbuf_get_height(buf); + int width = gdk_pixbuf_get_width(buf); + int height = gdk_pixbuf_get_height(buf); guchar *pixdata = gdk_pixbuf_get_pixels(buf); - int rowstride = gdk_pixbuf_get_rowstride(buf); - int n_channels = gdk_pixbuf_get_n_channels(buf); + int rowstride = gdk_pixbuf_get_rowstride(buf); + int n_channels = gdk_pixbuf_get_n_channels(buf); GrayMap *grayMap = GrayMapCreate(width, height); if (!grayMap) return nullptr; //### Fill in the odd cells with RGB values - int x,y; - int row = 0; - for (y=0 ; y<height ; y++) - { + int x, y; + int row = 0; + for (y = 0; y < height; y++) { guchar *p = pixdata + row; - for (x=0 ; x<width ; x++) - { + for (x = 0; x < width; x++) { int alpha = (int)p[3]; - int white = 3 * (255-alpha); - unsigned long sample = (int)p[0] + (int)p[1] +(int)p[2]; + int white = 3 * (255 - alpha); + unsigned long sample = (int)p[0] + (int)p[1] + (int)p[2]; unsigned long bright = sample * alpha / 256 + white; grayMap->setPixel(grayMap, x, y, bright); p += n_channels; - } - row += rowstride; } + row += rowstride; + } return grayMap; } @@ -57,38 +54,32 @@ GdkPixbuf *grayMapToGdkPixbuf(GrayMap *grayMap) if (!grayMap) return nullptr; - guchar *pixdata = (guchar *) - malloc(sizeof(guchar) * grayMap->width * grayMap->height * 3); + guchar *pixdata = (guchar *)malloc(sizeof(guchar) * grayMap->width * grayMap->height * 3); if (!pixdata) return nullptr; int n_channels = 3; - int rowstride = grayMap->width * 3; + int rowstride = grayMap->width * 3; - GdkPixbuf *buf = gdk_pixbuf_new_from_data(pixdata, GDK_COLORSPACE_RGB, - 0, 8, grayMap->width, grayMap->height, - rowstride, (GdkPixbufDestroyNotify)g_free, nullptr); + GdkPixbuf *buf = gdk_pixbuf_new_from_data(pixdata, GDK_COLORSPACE_RGB, 0, 8, grayMap->width, grayMap->height, + rowstride, (GdkPixbufDestroyNotify)g_free, nullptr); //### Fill in the odd cells with RGB values - int x,y; - int row = 0; - for (y=0 ; y<grayMap->height ; y++) - { + int x, y; + int row = 0; + for (y = 0; y < grayMap->height; y++) { guchar *p = pixdata + row; - for (x=0 ; x<grayMap->width ; x++) - { + for (x = 0; x < grayMap->width; x++) { unsigned long pix = grayMap->getPixel(grayMap, x, y) / 3; p[0] = p[1] = p[2] = (guchar)(pix & 0xff); p += n_channels; - } - row += rowstride; } + row += rowstride; + } return buf; } - - /*######################################################################### ## P A C K E D P I X E L M A P #########################################################################*/ @@ -98,40 +89,40 @@ PackedPixelMap *gdkPixbufToPackedPixelMap(GdkPixbuf *buf) if (!buf) return nullptr; - int width = gdk_pixbuf_get_width(buf); - int height = gdk_pixbuf_get_height(buf); + int width = gdk_pixbuf_get_width(buf); + int height = gdk_pixbuf_get_height(buf); guchar *pixdata = gdk_pixbuf_get_pixels(buf); - int rowstride = gdk_pixbuf_get_rowstride(buf); - int n_channels = gdk_pixbuf_get_n_channels(buf); + int rowstride = gdk_pixbuf_get_rowstride(buf); + int n_channels = gdk_pixbuf_get_n_channels(buf); PackedPixelMap *ppMap = PackedPixelMapCreate(width, height); if (!ppMap) return nullptr; //### Fill in the cells with RGB values - int x,y; - int row = 0; - for (y=0 ; y<height ; y++) - { + int x, y; + int row = 0; + for (y = 0; y < height; y++) { guchar *p = pixdata + row; - for (x=0 ; x<width ; x++) - { + for (x = 0; x < width; x++) { int alpha = (int)p[3]; int white = 255 - alpha; - int r = (int)p[0]; r = r * alpha / 256 + white; - int g = (int)p[1]; g = g * alpha / 256 + white; - int b = (int)p[2]; b = b * alpha / 256 + white; + int r = (int)p[0]; + r = r * alpha / 256 + white; + int g = (int)p[1]; + g = g * alpha / 256 + white; + int b = (int)p[2]; + b = b * alpha / 256 + white; ppMap->setPixel(ppMap, x, y, r, g, b); p += n_channels; - } - row += rowstride; } + row += rowstride; + } return ppMap; } - /*######################################################################### ## R G B M A P #########################################################################*/ @@ -141,79 +132,73 @@ RgbMap *gdkPixbufToRgbMap(GdkPixbuf *buf) if (!buf) return nullptr; - int width = gdk_pixbuf_get_width(buf); - int height = gdk_pixbuf_get_height(buf); + int width = gdk_pixbuf_get_width(buf); + int height = gdk_pixbuf_get_height(buf); guchar *pixdata = gdk_pixbuf_get_pixels(buf); - int rowstride = gdk_pixbuf_get_rowstride(buf); - int n_channels = gdk_pixbuf_get_n_channels(buf); + int rowstride = gdk_pixbuf_get_rowstride(buf); + int n_channels = gdk_pixbuf_get_n_channels(buf); RgbMap *rgbMap = RgbMapCreate(width, height); if (!rgbMap) return nullptr; //### Fill in the cells with RGB values - int x,y; - int row = 0; - for (y=0 ; y<height ; y++) - { + int x, y; + int row = 0; + for (y = 0; y < height; y++) { guchar *p = pixdata + row; - for (x=0 ; x<width ; x++) - { + for (x = 0; x < width; x++) { int alpha = (int)p[3]; int white = 255 - alpha; - int r = (int)p[0]; r = r * alpha / 256 + white; - int g = (int)p[1]; g = g * alpha / 256 + white; - int b = (int)p[2]; b = b * alpha / 256 + white; + int r = (int)p[0]; + r = r * alpha / 256 + white; + int g = (int)p[1]; + g = g * alpha / 256 + white; + int b = (int)p[2]; + b = b * alpha / 256 + white; rgbMap->setPixel(rgbMap, x, y, r, g, b); p += n_channels; - } - row += rowstride; } + row += rowstride; + } return rgbMap; } - - /*######################################################################### ## I N D E X E D M A P #########################################################################*/ - GdkPixbuf *indexedMapToGdkPixbuf(IndexedMap *iMap) { if (!iMap) return nullptr; - guchar *pixdata = (guchar *) - malloc(sizeof(guchar) * iMap->width * iMap->height * 3); + guchar *pixdata = (guchar *)malloc(sizeof(guchar) * iMap->width * iMap->height * 3); if (!pixdata) return nullptr; int n_channels = 3; - int rowstride = iMap->width * 3; + int rowstride = iMap->width * 3; - GdkPixbuf *buf = gdk_pixbuf_new_from_data(pixdata, GDK_COLORSPACE_RGB, - 0, 8, iMap->width, iMap->height, - rowstride, (GdkPixbufDestroyNotify)g_free, nullptr); + GdkPixbuf *buf = gdk_pixbuf_new_from_data(pixdata, GDK_COLORSPACE_RGB, 0, 8, iMap->width, iMap->height, rowstride, + (GdkPixbufDestroyNotify)g_free, nullptr); //### Fill in the cells with RGB values - int x,y; - int row = 0; - for (y=0 ; y<iMap->height ; y++) - { + int x, y; + int row = 0; + for (y = 0; y < iMap->height; y++) { guchar *p = pixdata + row; - for (x=0 ; x<iMap->width ; x++) - { + for (x = 0; x < iMap->width; x++) { RGB rgb = iMap->getPixelValue(iMap, x, y); p[0] = rgb.r & 0xff; p[1] = rgb.g & 0xff; p[2] = rgb.b & 0xff; p += n_channels; - } - row += rowstride; } + row += rowstride; + } return buf; } diff --git a/src/trace/imagemap-gdk.h b/src/trace/imagemap-gdk.h index d0eaf237728c4d546c274ff0d6fc46bc6f81ec36..f61c2f3b86ef7491f46a7be36ae943b4b3cff717 100644 --- a/src/trace/imagemap-gdk.h +++ b/src/trace/imagemap-gdk.h @@ -11,23 +11,21 @@ #define __GRAYMAP_GDK_H__ #ifndef TRUE -#define TRUE 1 +#define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif -#include "imagemap.h" - #include <gdk-pixbuf/gdk-pixbuf.h> +#include "imagemap.h" + /*######################################################################### ### I M A G E M A P --- GDK #########################################################################*/ - - #ifdef __cplusplus extern "C" { #endif @@ -38,12 +36,10 @@ PackedPixelMap *gdkPixbufToPackedPixelMap(GdkPixbuf *buf); RgbMap *gdkPixbufToRgbMap(GdkPixbuf *buf); GdkPixbuf *indexedMapToGdkPixbuf(IndexedMap *iMap); - #ifdef __cplusplus } #endif - #endif /* __GRAYMAP_GDK_H__ */ /*######################################################################### diff --git a/src/trace/imagemap.cpp b/src/trace/imagemap.cpp index 796575a443dd3f10a7ba43d9ce436236b43408b4..6da440b9d664989af76dff7e8adc9416d0259b43 100644 --- a/src/trace/imagemap.cpp +++ b/src/trace/imagemap.cpp @@ -7,20 +7,19 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstdlib> - #include "imagemap.h" +#include <cstdlib> + #include "io/sys.h" /*######################################################################### ### G R A Y M A P #########################################################################*/ - static void gSetPixel(GrayMap *me, int x, int y, unsigned long val) { - if (val>765) + if (val > 765) val = 765; unsigned long *pix = me->rows[y] + x; *pix = val; @@ -32,7 +31,6 @@ static unsigned long gGetPixel(GrayMap *me, int x, int y) return *pix; } - static int gWritePPM(GrayMap *me, char *fileName) { if (!fileName) @@ -44,22 +42,19 @@ static int gWritePPM(GrayMap *me, char *fileName) fprintf(f, "P6 %d %d 255\n", me->width, me->height); - for (int y=0 ; y<me->height; y++) - { - for (int x=0 ; x<me->width ; x++) - { - unsigned long pix = me->getPixel(me, x, y) / 3; - unsigned char pixb = (unsigned char) (pix & 0xff); + for (int y = 0; y < me->height; y++) { + for (int x = 0; x < me->width; x++) { + unsigned long pix = me->getPixel(me, x, y) / 3; + unsigned char pixb = (unsigned char)(pix & 0xff); fputc(pixb, f); fputc(pixb, f); fputc(pixb, f); - } } + } fclose(f); return TRUE; } - static void gDestroy(GrayMap *me) { if (me->pixels) @@ -71,62 +66,49 @@ static void gDestroy(GrayMap *me) GrayMap *GrayMapCreate(int width, int height) { - GrayMap *me = (GrayMap *)malloc(sizeof(GrayMap)); if (!me) return nullptr; /** methods **/ - me->setPixel = gSetPixel; - me->getPixel = gGetPixel; - me->writePPM = gWritePPM; - me->destroy = gDestroy; + me->setPixel = gSetPixel; + me->getPixel = gGetPixel; + me->writePPM = gWritePPM; + me->destroy = gDestroy; /** fields **/ - me->width = width; + me->width = width; me->height = height; - me->pixels = (unsigned long *) - malloc(sizeof(unsigned long) * width * height); - if (!me->pixels) - { + me->pixels = (unsigned long *)malloc(sizeof(unsigned long) * width * height); + if (!me->pixels) { free(me); return nullptr; - } - me->rows = (unsigned long **) - malloc(sizeof(unsigned long *) * height); - if (!me->rows) - { + } + me->rows = (unsigned long **)malloc(sizeof(unsigned long *) * height); + if (!me->rows) { free(me->pixels); free(me); return nullptr; - } + } unsigned long *row = me->pixels; - for (int i=0 ; i<height ; i++) - { + for (int i = 0; i < height; i++) { me->rows[i] = row; row += width; - } + } return me; } - - - - /*######################################################################### ### P A C K E D P I X E L M A P #########################################################################*/ - - static void ppSetPixel(PackedPixelMap *me, int x, int y, int r, int g, int b) { unsigned long *pix = me->rows[y] + x; - *pix = (((unsigned long)r)<<16 & 0xff0000L) | - (((unsigned long)g)<< 8 & 0x00ff00L) | - (((unsigned long)b) & 0x0000ffL); + *pix = (((unsigned long)r) << 16 & 0xff0000L) | (((unsigned long)g) << 8 & 0x00ff00L) | + (((unsigned long)b) & 0x0000ffL); } static void ppSetPixelLong(PackedPixelMap *me, int x, int y, unsigned long rgb) @@ -141,8 +123,6 @@ static unsigned long ppGetPixel(PackedPixelMap *me, int x, int y) return *pix; } - - static int ppWritePPM(PackedPixelMap *me, char *fileName) { if (!fileName) @@ -154,24 +134,21 @@ static int ppWritePPM(PackedPixelMap *me, char *fileName) fprintf(f, "P6 %d %d 255\n", me->width, me->height); - for (int y=0 ; y<me->height; y++) - { - for (int x=0 ; x<me->width ; x++) - { + for (int y = 0; y < me->height; y++) { + for (int x = 0; x < me->width; x++) { unsigned long rgb = me->getPixel(me, x, y); - unsigned char r = (unsigned char) ((rgb>>16) & 0xff); - unsigned char g = (unsigned char) ((rgb>> 8) & 0xff); - unsigned char b = (unsigned char) ((rgb ) & 0xff); + unsigned char r = (unsigned char)((rgb >> 16) & 0xff); + unsigned char g = (unsigned char)((rgb >> 8) & 0xff); + unsigned char b = (unsigned char)((rgb)&0xff); fputc(r, f); fputc(g, f); fputc(b, f); - } } + } fclose(f); return TRUE; } - static void ppDestroy(PackedPixelMap *me) { if (me->pixels) @@ -181,56 +158,47 @@ static void ppDestroy(PackedPixelMap *me) free(me); } - - PackedPixelMap *PackedPixelMapCreate(int width, int height) { - PackedPixelMap *me = (PackedPixelMap *)malloc(sizeof(PackedPixelMap)); if (!me) return nullptr; /** methods **/ - me->setPixel = ppSetPixel; + me->setPixel = ppSetPixel; me->setPixelLong = ppSetPixelLong; - me->getPixel = ppGetPixel; - me->writePPM = ppWritePPM; - me->destroy = ppDestroy; - + me->getPixel = ppGetPixel; + me->writePPM = ppWritePPM; + me->destroy = ppDestroy; /** fields **/ - me->width = width; + me->width = width; me->height = height; - me->pixels = (unsigned long *) malloc(sizeof(unsigned long) * width * height); - if (!me->pixels){ + me->pixels = (unsigned long *)malloc(sizeof(unsigned long) * width * height); + if (!me->pixels) { free(me); return nullptr; } - me->rows = (unsigned long **) malloc(sizeof(unsigned long *) * height); - if (!me->rows){ - free(me->pixels); //allocated as me->pixels is not NULL here: see previous check + me->rows = (unsigned long **)malloc(sizeof(unsigned long *) * height); + if (!me->rows) { + free(me->pixels); // allocated as me->pixels is not NULL here: see previous check free(me); return nullptr; } - + unsigned long *row = me->pixels; - for (int i=0 ; i<height ; i++) - { + for (int i = 0; i < height; i++) { me->rows[i] = row; row += width; - } + } return me; } - - /*######################################################################### ### R G B M A P #########################################################################*/ - - static void rSetPixel(RgbMap *me, int x, int y, int r, int g, int b) { RGB *pix = me->rows[y] + x; @@ -251,8 +219,6 @@ static RGB rGetPixel(RgbMap *me, int x, int y) return *pix; } - - static int rWritePPM(RgbMap *me, char *fileName) { if (!fileName) @@ -264,67 +230,60 @@ static int rWritePPM(RgbMap *me, char *fileName) fprintf(f, "P6 %d %d 255\n", me->width, me->height); - for (int y=0 ; y<me->height; y++) - { - for (int x=0 ; x<me->width ; x++) - { + for (int y = 0; y < me->height; y++) { + for (int x = 0; x < me->width; x++) { RGB rgb = me->getPixel(me, x, y); fputc(rgb.r, f); fputc(rgb.g, f); fputc(rgb.b, f); - } } + } fclose(f); return TRUE; } - static void rDestroy(RgbMap *me) { - if (me->pixels){ + if (me->pixels) { free(me->pixels); } - if (me->rows){ + if (me->rows) { free(me->rows); } free(me); } - - RgbMap *RgbMapCreate(int width, int height) { - RgbMap *me = (RgbMap *)malloc(sizeof(RgbMap)); - if (!me){ + if (!me) { return nullptr; } - + /** methods **/ - me->setPixel = rSetPixel; + me->setPixel = rSetPixel; me->setPixelRGB = rSetPixelRGB; - me->getPixel = rGetPixel; - me->writePPM = rWritePPM; - me->destroy = rDestroy; - + me->getPixel = rGetPixel; + me->writePPM = rWritePPM; + me->destroy = rDestroy; /** fields **/ - me->width = width; + me->width = width; me->height = height; - me->pixels = (RGB *) malloc(sizeof(RGB) * width * height); - if (!me->pixels){ + me->pixels = (RGB *)malloc(sizeof(RGB) * width * height); + if (!me->pixels) { free(me); return nullptr; } - me->rows = (RGB **) malloc(sizeof(RGB *) * height); - if (!me->rows){ - free(me->pixels); //allocated as me->pixels is not NULL here: see previous check + me->rows = (RGB **)malloc(sizeof(RGB *) * height); + if (!me->rows) { + free(me->pixels); // allocated as me->pixels is not NULL here: see previous check free(me); return nullptr; } RGB *row = me->pixels; - for (int i=0 ; i<height ; i++){ + for (int i = 0; i < height; i++) { me->rows[i] = row; row += width; } @@ -332,22 +291,16 @@ RgbMap *RgbMapCreate(int width, int height) return me; } - - - /*######################################################################### ### I N D E X E D M A P #########################################################################*/ - - static void iSetPixel(IndexedMap *me, int x, int y, unsigned int index) { unsigned int *pix = me->rows[y] + x; *pix = index; } - static unsigned int iGetPixel(IndexedMap *me, int x, int y) { unsigned int *pix = me->rows[y] + x; @@ -357,12 +310,10 @@ static unsigned int iGetPixel(IndexedMap *me, int x, int y) static RGB iGetPixelValue(IndexedMap *me, int x, int y) { unsigned int *pix = me->rows[y] + x; - RGB rgb = me->clut[((*pix)&0xff)]; + RGB rgb = me->clut[((*pix) & 0xff)]; return rgb; } - - static int iWritePPM(IndexedMap *me, char *fileName) { if (!fileName) @@ -374,66 +325,59 @@ static int iWritePPM(IndexedMap *me, char *fileName) fprintf(f, "P6 %d %d 255\n", me->width, me->height); - for (int y=0 ; y<me->height; y++) - { - for (int x=0 ; x<me->width ; x++) - { + for (int y = 0; y < me->height; y++) { + for (int x = 0; x < me->width; x++) { RGB rgb = me->getPixelValue(me, x, y); fputc(rgb.r, f); fputc(rgb.g, f); fputc(rgb.b, f); - } } + } fclose(f); return TRUE; } - static void iDestroy(IndexedMap *me) { - if (me->pixels){ + if (me->pixels) { free(me->pixels); } - if (me->rows){ + if (me->rows) { free(me->rows); } free(me); } - - IndexedMap *IndexedMapCreate(int width, int height) { - IndexedMap *me = (IndexedMap *)malloc(sizeof(IndexedMap)); if (!me) return nullptr; /** methods **/ - me->setPixel = iSetPixel; - me->getPixel = iGetPixel; + me->setPixel = iSetPixel; + me->getPixel = iGetPixel; me->getPixelValue = iGetPixelValue; - me->writePPM = iWritePPM; - me->destroy = iDestroy; - + me->writePPM = iWritePPM; + me->destroy = iDestroy; /** fields **/ - me->width = width; + me->width = width; me->height = height; - me->pixels = (unsigned int *) malloc(sizeof(unsigned int) * width * height); - if (!me->pixels){ + me->pixels = (unsigned int *)malloc(sizeof(unsigned int) * width * height); + if (!me->pixels) { free(me); return nullptr; } - me->rows = (unsigned int **) malloc(sizeof(unsigned int *) * height); - if (!me->rows){ - free(me->pixels); //allocated as me->pixels is not NULL here: see previous check + me->rows = (unsigned int **)malloc(sizeof(unsigned int *) * height); + if (!me->rows) { + free(me->pixels); // allocated as me->pixels is not NULL here: see previous check free(me); return nullptr; } unsigned int *row = me->pixels; - for (int i=0 ; i<height ; i++){ + for (int i = 0; i < height; i++) { me->rows[i] = row; row += width; } @@ -442,18 +386,13 @@ IndexedMap *IndexedMapCreate(int width, int height) RGB rgb; rgb.r = rgb.g = rgb.b = 0; - for (auto & i : me->clut){ + for (auto &i : me->clut) { i = rgb; } return me; } - - - - - /*######################################################################### ### E N D O F F I L E #########################################################################*/ diff --git a/src/trace/imagemap.h b/src/trace/imagemap.h index 9da057a5b72c30d2fc36fc8c471886326dcaac40..d595257924d22deba453da5f3b8fa15e2950ade8 100644 --- a/src/trace/imagemap.h +++ b/src/trace/imagemap.h @@ -11,19 +11,17 @@ #define __IMAGEMAP_H__ #ifndef TRUE -#define TRUE 1 +#define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif - /*######################################################################### ### G R A Y M A P #########################################################################*/ - typedef struct GrayMap_def GrayMap; #define GRAYMAP_BLACK 0 @@ -34,7 +32,6 @@ typedef struct GrayMap_def GrayMap; */ struct GrayMap_def { - /*################# ### METHODS #################*/ @@ -54,15 +51,11 @@ struct GrayMap_def */ int (*writePPM)(GrayMap *me, char *fileName); - - /** * */ void (*destroy)(GrayMap *me); - - /*################# ### FIELDS #################*/ @@ -86,7 +79,6 @@ struct GrayMap_def * Pointer to the beginning of each row */ unsigned long **rows; - }; #ifdef __cplusplus @@ -99,14 +91,10 @@ GrayMap *GrayMapCreate(int width, int height); } #endif - - - /*######################################################################### ### P A C K E D P I X E L M A P #########################################################################*/ - typedef struct PackedPixelMap_def PackedPixelMap; /** @@ -114,7 +102,6 @@ typedef struct PackedPixelMap_def PackedPixelMap; */ struct PackedPixelMap_def { - /*################# ### METHODS #################*/ @@ -124,33 +111,26 @@ struct PackedPixelMap_def */ void (*setPixel)(PackedPixelMap *me, int x, int y, int r, int g, int b); - /** * */ void (*setPixelLong)(PackedPixelMap *me, int x, int y, unsigned long rgb); - /** * */ unsigned long (*getPixel)(PackedPixelMap *me, int x, int y); - /** * */ int (*writePPM)(PackedPixelMap *me, char *fileName); - - /** * */ void (*destroy)(PackedPixelMap *me); - - /*################# ### FIELDS #################*/ @@ -174,12 +154,8 @@ struct PackedPixelMap_def * Pointers to the beginning of each row of pixels */ unsigned long **rows; - - }; - - #ifdef __cplusplus extern "C" { #endif @@ -190,8 +166,6 @@ PackedPixelMap *PackedPixelMapCreate(int width, int height); } #endif - - /*######################################################################### ### R G B M A P #########################################################################*/ @@ -203,8 +177,6 @@ struct RGB unsigned char b; }; - - typedef struct RgbMap_def RgbMap; /** @@ -212,7 +184,6 @@ typedef struct RgbMap_def RgbMap; */ struct RgbMap_def { - /*################# ### METHODS #################*/ @@ -222,7 +193,6 @@ struct RgbMap_def */ void (*setPixel)(RgbMap *me, int x, int y, int r, int g, int b); - /** * */ @@ -238,15 +208,11 @@ struct RgbMap_def */ int (*writePPM)(RgbMap *me, char *fileName); - - /** * */ void (*destroy)(RgbMap *me); - - /*################# ### FIELDS #################*/ @@ -270,11 +236,8 @@ struct RgbMap_def * Pointers to the beginning of each row of pixels */ RGB **rows; - }; - - #ifdef __cplusplus extern "C" { #endif @@ -285,14 +248,10 @@ RgbMap *RgbMapCreate(int width, int height); } #endif - - - /*######################################################################### ### I N D E X E D M A P #########################################################################*/ - typedef struct IndexedMap_def IndexedMap; /** @@ -300,7 +259,6 @@ typedef struct IndexedMap_def IndexedMap; */ struct IndexedMap_def { - /*################# ### METHODS #################*/ @@ -310,7 +268,6 @@ struct IndexedMap_def */ void (*setPixel)(IndexedMap *me, int x, int y, unsigned int index); - /** * */ @@ -326,15 +283,11 @@ struct IndexedMap_def */ int (*writePPM)(IndexedMap *me, char *fileName); - - /** * */ void (*destroy)(IndexedMap *me); - - /*################# ### FIELDS #################*/ @@ -368,11 +321,8 @@ struct IndexedMap_def * Color look up table */ RGB clut[256]; - }; - - #ifdef __cplusplus extern "C" { #endif @@ -383,9 +333,6 @@ IndexedMap *IndexedMapCreate(int width, int height); } #endif - - - #endif /* __IMAGEMAP_H__ */ /*######################################################################### diff --git a/src/trace/pool.h b/src/trace/pool.h index a6fed5950c663f6e7f27302bc08010445630a09f..f475fb8eb7feb4dc68ccf90b5ec607f35bb933a0 100644 --- a/src/trace/pool.h +++ b/src/trace/pool.h @@ -55,65 +55,62 @@ #include <cstdlib> template <typename T> -class pool { - - public: - - pool() - { - cblock = 0; - size = sizeof(T) > sizeof(void *) ? sizeof(T) : sizeof(void *); - next = nullptr; - for (auto & k : block) { - k = nullptr; - } - } - - ~pool() - { - for (int k = 0; k < cblock; k++) { - free(block[k]); - } - } - - T *draw() - { - if (!next) addblock(); - void *p = next; - next = *(void **)p; - return (T *) p; - } - - void drop(T *p) - { - *(void **)p = next; - next = (void *) p; - } - - private: - - int size; - int cblock; - void *block[64]; //enough to store unlimited number of objects, if 64 is changed: see constructor too - void *next; - - void addblock() +class pool +{ +public: + pool() { - int i = cblock++; - int blocksize = 1 << (6 + (i/2)); - //printf("pool allocating block: %d (size:%d)...", i, blocksize);//debug - block[i] = (void *)malloc(blocksize * size); - if (!block[i]) throw std::bad_alloc(); - char *p = (char *)block[i]; - for (int k = 0; k < blocksize - 1; k++) - { - *(void**)p = (void *)(p + size); - p += size; - } - *(void **)p = next; - next = block[i]; - //printf("done\n");//debug + cblock = 0; + size = sizeof(T) > sizeof(void *) ? sizeof(T) : sizeof(void *); + next = nullptr; + for (auto &k : block) { + k = nullptr; + } } -}; + ~pool() + { + for (int k = 0; k < cblock; k++) { + free(block[k]); + } + } + T *draw() + { + if (!next) + addblock(); + void *p = next; + next = *(void **)p; + return (T *)p; + } + + void drop(T *p) + { + *(void **)p = next; + next = (void *)p; + } + +private: + int size; + int cblock; + void *block[64]; // enough to store unlimited number of objects, if 64 is changed: see constructor too + void *next; + + void addblock() + { + int i = cblock++; + int blocksize = 1 << (6 + (i / 2)); + // printf("pool allocating block: %d (size:%d)...", i, blocksize);//debug + block[i] = (void *)malloc(blocksize * size); + if (!block[i]) + throw std::bad_alloc(); + char *p = (char *)block[i]; + for (int k = 0; k < blocksize - 1; k++) { + *(void **)p = (void *)(p + size); + p += size; + } + *(void **)p = next; + next = block[i]; + // printf("done\n");//debug + } +}; diff --git a/src/trace/potrace/bitmap.h b/src/trace/potrace/bitmap.h index bb50b2dffa1d56b7a91a6ead254127e07c2e7910..3328433721bd1fb37ce7b787cb62e23f9196fa97 100644 --- a/src/trace/potrace/bitmap.h +++ b/src/trace/potrace/bitmap.h @@ -9,10 +9,10 @@ #ifndef BITMAP_H #define BITMAP_H -#include <cstring> -#include <cstdlib> #include <cerrno> #include <cstddef> +#include <cstdlib> +#include <cstring> /* The bitmap type is defined in potracelib.h */ #include "potracelib.h" @@ -26,16 +26,16 @@ /* some measurements */ #define BM_WORDSIZE ((int)sizeof(potrace_word)) -#define BM_WORDBITS (8*BM_WORDSIZE) -#define BM_HIBIT (((potrace_word)1)<<(BM_WORDBITS-1)) +#define BM_WORDBITS (8 * BM_WORDSIZE) +#define BM_HIBIT (((potrace_word)1) << (BM_WORDBITS - 1)) #define BM_ALLBITS (~(potrace_word)0) /* macros for accessing pixel at index (x,y). U* macros omit the bounds check. */ -#define bm_scanline(bm, y) ((bm)->map + (ptrdiff_t)(y)*(ptrdiff_t)(bm)->dy) -#define bm_index(bm, x, y) (&bm_scanline(bm, y)[(x)/BM_WORDBITS]) -#define bm_mask(x) (BM_HIBIT >> ((x) & (BM_WORDBITS-1))) +#define bm_scanline(bm, y) ((bm)->map + (ptrdiff_t)(y) * (ptrdiff_t)(bm)->dy) +#define bm_index(bm, x, y) (&bm_scanline(bm, y)[(x) / BM_WORDBITS]) +#define bm_mask(x) (BM_HIBIT >> ((x) & (BM_WORDBITS - 1))) #define bm_range(x, a) ((int)(x) >= 0 && (int)(x) < (a)) #define bm_safe(bm, x, y) (bm_range(x, (bm)->w) && bm_range(y, (bm)->h)) #define BM_UGET(bm, x, y) ((*bm_index(bm, x, y) & bm_mask(x)) != 0) @@ -50,68 +50,73 @@ #define BM_PUT(bm, x, y, b) (bm_safe(bm, x, y) ? BM_UPUT(bm, x, y, b) : 0) /* free the given bitmap. Leaves errno untouched. */ -static inline void bm_free(potrace_bitmap_t *bm) { - if (bm) { - free(bm->map); - } - free(bm); +static inline void bm_free(potrace_bitmap_t *bm) +{ + if (bm) { + free(bm->map); + } + free(bm); } /* return new un-initialized bitmap. NULL with errno on error. Assumes w, h >= 0. */ -static inline potrace_bitmap_t *bm_new(int w, int h) { - potrace_bitmap_t *bm; - int dy = w == 0 ? 0 : (w - 1) / BM_WORDBITS + 1; - ptrdiff_t size = (ptrdiff_t)dy * (ptrdiff_t)h * (ptrdiff_t)BM_WORDSIZE; - - /* check for overflow error */ - if (size < 0 || (h != 0 && dy != 0 && size / h / dy != BM_WORDSIZE)) { - errno = ENOMEM; - return nullptr; - } - - bm = (potrace_bitmap_t *) malloc(sizeof(potrace_bitmap_t)); - if (!bm) { - return nullptr; - } - bm->w = w; - bm->h = h; - bm->dy = dy; - bm->map = (potrace_word *) malloc(size); - if (!bm->map) { - free(bm); - return nullptr; - } - return bm; +static inline potrace_bitmap_t *bm_new(int w, int h) +{ + potrace_bitmap_t *bm; + int dy = w == 0 ? 0 : (w - 1) / BM_WORDBITS + 1; + ptrdiff_t size = (ptrdiff_t)dy * (ptrdiff_t)h * (ptrdiff_t)BM_WORDSIZE; + + /* check for overflow error */ + if (size < 0 || (h != 0 && dy != 0 && size / h / dy != BM_WORDSIZE)) { + errno = ENOMEM; + return nullptr; + } + + bm = (potrace_bitmap_t *)malloc(sizeof(potrace_bitmap_t)); + if (!bm) { + return nullptr; + } + bm->w = w; + bm->h = h; + bm->dy = dy; + bm->map = (potrace_word *)malloc(size); + if (!bm->map) { + free(bm); + return nullptr; + } + return bm; } /* clear the given bitmap. Set all bits to c. */ -static inline void bm_clear(potrace_bitmap_t *bm, int c) { - /* Note: if the bitmap was created with bm_new, then it is - guaranteed that size will fit into the ptrdiff_t type. */ - ptrdiff_t size = (ptrdiff_t)bm->dy * (ptrdiff_t)bm->h * (ptrdiff_t)BM_WORDSIZE; - memset(bm->map, c ? -1 : 0, size); +static inline void bm_clear(potrace_bitmap_t *bm, int c) +{ + /* Note: if the bitmap was created with bm_new, then it is + guaranteed that size will fit into the ptrdiff_t type. */ + ptrdiff_t size = (ptrdiff_t)bm->dy * (ptrdiff_t)bm->h * (ptrdiff_t)BM_WORDSIZE; + memset(bm->map, c ? -1 : 0, size); } /* duplicate the given bitmap. Return NULL on error with errno set. */ -static inline potrace_bitmap_t *bm_dup(const potrace_bitmap_t *bm) { - potrace_bitmap_t *bm1 = bm_new(bm->w, bm->h); - ptrdiff_t size = (ptrdiff_t)bm->dy * (ptrdiff_t)bm->h * (ptrdiff_t)BM_WORDSIZE; - if (!bm1) { - return nullptr; - } - memcpy(bm1->map, bm->map, size); - return bm1; +static inline potrace_bitmap_t *bm_dup(const potrace_bitmap_t *bm) +{ + potrace_bitmap_t *bm1 = bm_new(bm->w, bm->h); + ptrdiff_t size = (ptrdiff_t)bm->dy * (ptrdiff_t)bm->h * (ptrdiff_t)BM_WORDSIZE; + if (!bm1) { + return nullptr; + } + memcpy(bm1->map, bm->map, size); + return bm1; } /* invert the given bitmap. */ -static inline void bm_invert(potrace_bitmap_t *bm) { - ptrdiff_t i; - ptrdiff_t size = (ptrdiff_t)bm->dy * (ptrdiff_t)bm->h; - - for (i = 0; i < size; i++) { - bm->map[i] ^= BM_ALLBITS; - } +static inline void bm_invert(potrace_bitmap_t *bm) +{ + ptrdiff_t i; + ptrdiff_t size = (ptrdiff_t)bm->dy * (ptrdiff_t)bm->h; + + for (i = 0; i < size; i++) { + bm->map[i] ^= BM_ALLBITS; + } } #endif /* BITMAP_H */ diff --git a/src/trace/potrace/inkscape-potrace.cpp b/src/trace/potrace/inkscape-potrace.cpp index 6c8f760f4e09df132a472260162c7ac3387dee34..65852f63c72985f6175baa2960b2413a321b20fb 100644 --- a/src/trace/potrace/inkscape-potrace.cpp +++ b/src/trace/potrace/inkscape-potrace.cpp @@ -19,33 +19,28 @@ #include <glibmm/i18n.h> #include <gtkmm/main.h> +#include <inkscape.h> #include <iomanip> +#include <svg/path-string.h> -#include "trace/filterset.h" -#include "trace/quantize.h" -#include "trace/imagemap-gdk.h" - -#include <inkscape.h> +#include "bitmap.h" #include "desktop.h" #include "message-stack.h" - #include "object/sp-path.h" - -#include <svg/path-string.h> -#include "bitmap.h" +#include "trace/filterset.h" +#include "trace/imagemap-gdk.h" +#include "trace/quantize.h" using Glib::ustring; static void updateGui() { - //## Allow the GUI to update - Gtk::Main::iteration(false); //at least once, non-blocking - while( Gtk::Main::events_pending() ) - Gtk::Main::iteration(); - + //## Allow the GUI to update + Gtk::Main::iteration(false); // at least once, non-blocking + while (Gtk::Main::events_pending()) + Gtk::Main::iteration(); } - static void potraceStatusCallback(double /*progress*/, void *userData) /* callback fn */ { updateGui(); @@ -53,44 +48,41 @@ static void potraceStatusCallback(double /*progress*/, void *userData) /* callba if (!userData) return; - //g_message("progress: %f\n", progress); + // g_message("progress: %f\n", progress); - //Inkscape::Trace::Potrace::PotraceTracingEngine *engine = + // Inkscape::Trace::Potrace::PotraceTracingEngine *engine = // (Inkscape::Trace::Potrace::PotraceTracingEngine *)userData; } - namespace { -ustring twohex( int value ) +ustring twohex(int value) { return ustring::format(std::hex, std::setfill(L'0'), std::setw(2), value); } } // namespace - -//required by potrace +// required by potrace namespace Inkscape { namespace Trace { namespace Potrace { - /** * */ -PotraceTracingEngine::PotraceTracingEngine() : - keepGoing(1), - traceType(TRACE_BRIGHTNESS), - invert(false), - quantizationNrColors(8), - brightnessThreshold(0.45), - brightnessFloor(0), - cannyHighThreshold(0.65), - multiScanNrColors(8), - multiScanStack(true), - multiScanSmooth(false), - multiScanRemoveBackground(false) +PotraceTracingEngine::PotraceTracingEngine() + : keepGoing(1) + , traceType(TRACE_BRIGHTNESS) + , invert(false) + , quantizationNrColors(8) + , brightnessThreshold(0.45) + , brightnessFloor(0) + , cannyHighThreshold(0.65) + , multiScanNrColors(8) + , multiScanStack(true) + , multiScanSmooth(false) + , multiScanRemoveBackground(false) { /* get default parameters */ potraceParams = potrace_param_default(); @@ -98,60 +90,65 @@ PotraceTracingEngine::PotraceTracingEngine() : potraceParams->progress.data = (void *)this; } -PotraceTracingEngine::PotraceTracingEngine(TraceType traceType, bool invert, int quantizationNrColors, double brightnessThreshold, double brightnessFloor, double cannyHighThreshold, int multiScanNrColors, bool multiScanStack, bool multiScanSmooth, bool multiScanRemoveBackground) : - keepGoing(1), traceType(traceType), invert(invert), quantizationNrColors(quantizationNrColors), brightnessThreshold(brightnessThreshold), brightnessFloor(brightnessFloor), cannyHighThreshold(cannyHighThreshold), multiScanNrColors(multiScanNrColors) , multiScanStack(multiScanStack), multiScanSmooth(multiScanSmooth), multiScanRemoveBackground(multiScanRemoveBackground) +PotraceTracingEngine::PotraceTracingEngine(TraceType traceType, bool invert, int quantizationNrColors, + double brightnessThreshold, double brightnessFloor, + double cannyHighThreshold, int multiScanNrColors, bool multiScanStack, + bool multiScanSmooth, bool multiScanRemoveBackground) + : keepGoing(1) + , traceType(traceType) + , invert(invert) + , quantizationNrColors(quantizationNrColors) + , brightnessThreshold(brightnessThreshold) + , brightnessFloor(brightnessFloor) + , cannyHighThreshold(cannyHighThreshold) + , multiScanNrColors(multiScanNrColors) + , multiScanStack(multiScanStack) + , multiScanSmooth(multiScanSmooth) + , multiScanRemoveBackground(multiScanRemoveBackground) { potraceParams = potrace_param_default(); potraceParams->progress.callback = potraceStatusCallback; potraceParams->progress.data = (void *)this; } - PotraceTracingEngine::~PotraceTracingEngine() { potrace_param_free(potraceParams); } - - - struct Point { double x; double y; }; - /** * Check a point against a list of points to see if it * has already occurred. */ static bool hasPoint(std::vector<Point> &points, double x, double y) { - for (auto p : points) - { + for (auto p : points) { if (p.x == x && p.y == y) return true; - } + } return false; } - /** * Recursively descend the potrace_path_t node tree, writing paths in SVG * format into the output stream. The Point vector is used to prevent * redundant paths. Returns number of paths processed. */ -static long writePaths(PotraceTracingEngine *engine, potrace_path_t *plist, - Inkscape::SVG::PathString& data, std::vector<Point> &points) +static long writePaths(PotraceTracingEngine *engine, potrace_path_t *plist, Inkscape::SVG::PathString &data, + std::vector<Point> &points) { long nodeCount = 0L; potrace_path_t *node; - for (node=plist; node ; node=node->sibling) - { + for (node = plist; node; node = node->sibling) { potrace_curve_t *curve = &(node->curve); - //g_message("node->fm:%d\n", node->fm); + // g_message("node->fm:%d\n", node->fm); if (!curve->n) continue; const potrace_dpoint_t *pt = curve->c[curve->n - 1]; @@ -161,23 +158,20 @@ static long writePaths(PotraceTracingEngine *engine, potrace_path_t *plist, double y1 = 0.0; double x2 = pt[2].x; double y2 = pt[2].y; - //Have we been here already? - if (hasPoint(points, x2, y2)) - { - //g_message("duplicate point: (%f,%f)\n", x2, y2); + // Have we been here already? + if (hasPoint(points, x2, y2)) { + // g_message("duplicate point: (%f,%f)\n", x2, y2); continue; - } - else - { + } else { Point p; - p.x = x2; p.y = y2; + p.x = x2; + p.y = y2; points.push_back(p); - } + } data.moveTo(x2, y2); nodeCount++; - for (int i=0 ; i<curve->n ; i++) - { + for (int i = 0; i < curve->n; i++) { if (!engine->keepGoing) return 0L; pt = curve->c[i]; @@ -187,33 +181,29 @@ static long writePaths(PotraceTracingEngine *engine, potrace_path_t *plist, y1 = pt[1].y; x2 = pt[2].x; y2 = pt[2].y; - switch (curve->tag[i]) - { + switch (curve->tag[i]) { case POTRACE_CORNER: data.lineTo(x1, y1).lineTo(x2, y2); - break; + break; case POTRACE_CURVETO: data.curveTo(x0, y0, x1, y1, x2, y2); - break; + break; default: - break; - } - nodeCount++; + break; } + nodeCount++; + } data.closePath(); - for (potrace_path_t *child=node->childlist; child ; child=child->sibling) - { + for (potrace_path_t *child = node->childlist; child; child = child->sibling) { nodeCount += writePaths(engine, child, data, points); - } } + } return nodeCount; - } - -static GrayMap *filter(PotraceTracingEngine &engine, GdkPixbuf * pixbuf) +static GrayMap *filter(PotraceTracingEngine &engine, GdkPixbuf *pixbuf) { if (!pixbuf) return nullptr; @@ -221,73 +211,60 @@ static GrayMap *filter(PotraceTracingEngine &engine, GdkPixbuf * pixbuf) GrayMap *newGm = nullptr; /*### Color quantization -- banding ###*/ - if (engine.traceType == TRACE_QUANT) - { + if (engine.traceType == TRACE_QUANT) { RgbMap *rgbmap = gdkPixbufToRgbMap(pixbuf); - //rgbMap->writePPM(rgbMap, "rgb.ppm"); - newGm = quantizeBand(rgbmap, - engine.quantizationNrColors); + // rgbMap->writePPM(rgbMap, "rgb.ppm"); + newGm = quantizeBand(rgbmap, engine.quantizationNrColors); rgbmap->destroy(rgbmap); - //return newGm; - } + // return newGm; + } /*### Brightness threshold ###*/ - else if ( engine.traceType == TRACE_BRIGHTNESS || - engine.traceType == TRACE_BRIGHTNESS_MULTI ) - { + else if (engine.traceType == TRACE_BRIGHTNESS || engine.traceType == TRACE_BRIGHTNESS_MULTI) { GrayMap *gm = gdkPixbufToGrayMap(pixbuf); newGm = GrayMapCreate(gm->width, gm->height); - double floor = 3.0 * - ( engine.brightnessFloor * 256.0 ); - double cutoff = 3.0 * - ( engine.brightnessThreshold * 256.0 ); - for (int y=0 ; y<gm->height ; y++) - { - for (int x=0 ; x<gm->width ; x++) - { + double floor = 3.0 * (engine.brightnessFloor * 256.0); + double cutoff = 3.0 * (engine.brightnessThreshold * 256.0); + for (int y = 0; y < gm->height; y++) { + for (int x = 0; x < gm->width; x++) { double brightness = (double)gm->getPixel(gm, x, y); if (brightness >= floor && brightness < cutoff) - newGm->setPixel(newGm, x, y, GRAYMAP_BLACK); //black pixel + newGm->setPixel(newGm, x, y, GRAYMAP_BLACK); // black pixel else - newGm->setPixel(newGm, x, y, GRAYMAP_WHITE); //white pixel - } + newGm->setPixel(newGm, x, y, GRAYMAP_WHITE); // white pixel } + } gm->destroy(gm); - //newGm->writePPM(newGm, "brightness.ppm"); - //return newGm; - } + // newGm->writePPM(newGm, "brightness.ppm"); + // return newGm; + } /*### Canny edge detection ###*/ - else if (engine.traceType == TRACE_CANNY) - { + else if (engine.traceType == TRACE_CANNY) { GrayMap *gm = gdkPixbufToGrayMap(pixbuf); newGm = grayMapCanny(gm, 0.1, engine.cannyHighThreshold); gm->destroy(gm); - //newGm->writePPM(newGm, "canny.ppm"); - //return newGm; - } + // newGm->writePPM(newGm, "canny.ppm"); + // return newGm; + } /*### Do I invert the image? ###*/ - if (newGm && engine.invert) - { - for (int y=0 ; y<newGm->height ; y++) - { - for (int x=0 ; x<newGm->width ; x++) - { + if (newGm && engine.invert) { + for (int y = 0; y < newGm->height; y++) { + for (int x = 0; x < newGm->width; x++) { unsigned long brightness = newGm->getPixel(newGm, x, y); brightness = 765 - brightness; newGm->setPixel(newGm, x, y, brightness); - } } } + } - return newGm;//none of the above + return newGm; // none of the above } - -static IndexedMap *filterIndexed(PotraceTracingEngine &engine, GdkPixbuf * pixbuf) +static IndexedMap *filterIndexed(PotraceTracingEngine &engine, GdkPixbuf *pixbuf) { if (!pixbuf) return nullptr; @@ -295,76 +272,59 @@ static IndexedMap *filterIndexed(PotraceTracingEngine &engine, GdkPixbuf * pixbu IndexedMap *newGm = nullptr; RgbMap *gm = gdkPixbufToRgbMap(pixbuf); - if (engine.multiScanSmooth) - { + if (engine.multiScanSmooth) { RgbMap *gaussMap = rgbMapGaussian(gm); newGm = rgbMapQuantize(gaussMap, engine.multiScanNrColors); gaussMap->destroy(gaussMap); - } - else - { + } else { newGm = rgbMapQuantize(gm, engine.multiScanNrColors); - } + } gm->destroy(gm); - if (engine.traceType == TRACE_QUANT_MONO) - { - //Turn to grays - for (int i=0 ; i<newGm->nrColors ; i++) - { + if (engine.traceType == TRACE_QUANT_MONO) { + // Turn to grays + for (int i = 0; i < newGm->nrColors; i++) { RGB rgb = newGm->clut[i]; int grayVal = (rgb.r + rgb.g + rgb.b) / 3; rgb.r = rgb.g = rgb.b = grayVal; newGm->clut[i] = rgb; - } } + } return newGm; } - - - -Glib::RefPtr<Gdk::Pixbuf> -PotraceTracingEngine::preview(Glib::RefPtr<Gdk::Pixbuf> thePixbuf) +Glib::RefPtr<Gdk::Pixbuf> PotraceTracingEngine::preview(Glib::RefPtr<Gdk::Pixbuf> thePixbuf) { GdkPixbuf *pixbuf = thePixbuf->gobj(); - if ( traceType == TRACE_QUANT_COLOR || - traceType == TRACE_QUANT_MONO ) - { + if (traceType == TRACE_QUANT_COLOR || traceType == TRACE_QUANT_MONO) { IndexedMap *gm = filterIndexed(*this, pixbuf); if (!gm) return Glib::RefPtr<Gdk::Pixbuf>(nullptr); - Glib::RefPtr<Gdk::Pixbuf> newBuf = - Glib::wrap(indexedMapToGdkPixbuf(gm), false); + Glib::RefPtr<Gdk::Pixbuf> newBuf = Glib::wrap(indexedMapToGdkPixbuf(gm), false); gm->destroy(gm); return newBuf; - } - else - { + } else { GrayMap *gm = filter(*this, pixbuf); if (!gm) return Glib::RefPtr<Gdk::Pixbuf>(nullptr); - Glib::RefPtr<Gdk::Pixbuf> newBuf = - Glib::wrap(grayMapToGdkPixbuf(gm), false); + Glib::RefPtr<Gdk::Pixbuf> newBuf = Glib::wrap(grayMapToGdkPixbuf(gm), false); gm->destroy(gm); return newBuf; - } + } } - //*This is the core inkscape-to-potrace binding std::string PotraceTracingEngine::grayMapToPath(GrayMap *grayMap, long *nodeCount) { - if (!keepGoing) - { + if (!keepGoing) { g_warning("aborted"); return ""; } @@ -373,14 +333,11 @@ std::string PotraceTracingEngine::grayMapToPath(GrayMap *grayMap, long *nodeCoun bm_clear(potraceBitmap, 0); //##Read the data out of the GrayMap - for (int y=0 ; y<grayMap->height ; y++) - { - for (int x=0 ; x<grayMap->width ; x++) - { - BM_UPUT(potraceBitmap, x, y, - grayMap->getPixel(grayMap, x, y) ? 0 : 1); - } + for (int y = 0; y < grayMap->height; y++) { + for (int x = 0; x < grayMap->width; x++) { + BM_UPUT(potraceBitmap, x, y, grayMap->getPixel(grayMap, x, y) ? 0 : 1); } + } //##Debug /* @@ -390,18 +347,16 @@ std::string PotraceTracingEngine::grayMapToPath(GrayMap *grayMap, long *nodeCoun */ /* trace a bitmap*/ - potrace_state_t *potraceState = potrace_trace(potraceParams, - potraceBitmap); + potrace_state_t *potraceState = potrace_trace(potraceParams, potraceBitmap); //## Free the Potrace bitmap bm_free(potraceBitmap); - if (!keepGoing) - { + if (!keepGoing) { g_warning("aborted"); potrace_state_free(potraceState); return ""; - } + } Inkscape::SVG::PathString data; @@ -415,26 +370,23 @@ std::string PotraceTracingEngine::grayMapToPath(GrayMap *grayMap, long *nodeCoun if (!keepGoing) return ""; - if ( nodeCount) + if (nodeCount) *nodeCount = thisNodeCount; return data.string(); } - - /** * This is called for a single scan */ -std::vector<TracingEngineResult> PotraceTracingEngine::traceSingle(GdkPixbuf * thePixbuf) +std::vector<TracingEngineResult> PotraceTracingEngine::traceSingle(GdkPixbuf *thePixbuf) { - std::vector<TracingEngineResult> results; if (!thePixbuf) return results; - brightnessFloor = 0.0; //important to set this + brightnessFloor = 0.0; // important to set this GrayMap *grayMap = filter(*this, thePixbuf); if (!grayMap) @@ -447,31 +399,29 @@ std::vector<TracingEngineResult> PotraceTracingEngine::traceSingle(GdkPixbuf * t char const *style = "fill:#000000"; - //g_message("### GOT '%s' \n", d); + // g_message("### GOT '%s' \n", d); TracingEngineResult result(style, d, nodeCount); results.push_back(result); return results; } - /** * This allows routines that already generate GrayMaps to skip image filtering, * increasing performance. */ std::vector<TracingEngineResult> PotraceTracingEngine::traceGrayMap(GrayMap *grayMap) { - std::vector<TracingEngineResult> results; - brightnessFloor = 0.0; //important to set this + brightnessFloor = 0.0; // important to set this long nodeCount = 0L; std::string d = grayMapToPath(grayMap, &nodeCount); char const *style = "fill:#000000"; - //g_message("### GOT '%s' \n", d); + // g_message("### GOT '%s' \n", d); TracingEngineResult result(style, d, nodeCount); results.push_back(result); @@ -481,35 +431,34 @@ std::vector<TracingEngineResult> PotraceTracingEngine::traceGrayMap(GrayMap *gra /** * Called for multiple-scanning algorithms */ -std::vector<TracingEngineResult> PotraceTracingEngine::traceBrightnessMulti(GdkPixbuf * thePixbuf) +std::vector<TracingEngineResult> PotraceTracingEngine::traceBrightnessMulti(GdkPixbuf *thePixbuf) { std::vector<TracingEngineResult> results; - if ( thePixbuf ) { - double low = 0.2; //bottom of range - double high = 0.9; //top of range - double delta = (high - low ) / ((double)multiScanNrColors); + if (thePixbuf) { + double low = 0.2; // bottom of range + double high = 0.9; // top of range + double delta = (high - low) / ((double)multiScanNrColors); - brightnessFloor = 0.0; //Set bottom to black + brightnessFloor = 0.0; // Set bottom to black int traceCount = 0; - for ( brightnessThreshold = low ; - brightnessThreshold <= high ; - brightnessThreshold += delta) { + for (brightnessThreshold = low; brightnessThreshold <= high; brightnessThreshold += delta) { GrayMap *grayMap = filter(*this, thePixbuf); - if ( grayMap ) { + if (grayMap) { long nodeCount = 0L; std::string d = grayMapToPath(grayMap, &nodeCount); grayMap->destroy(grayMap); - if ( !d.empty() ) { + if (!d.empty()) { //### get style info int grayVal = (int)(256.0 * brightnessThreshold); - ustring style = ustring::compose("fill-opacity:1.0;fill:#%1%2%3", twohex(grayVal), twohex(grayVal), twohex(grayVal) ); + ustring style = ustring::compose("fill-opacity:1.0;fill:#%1%2%3", twohex(grayVal), twohex(grayVal), + twohex(grayVal)); - //g_message("### GOT '%s' \n", style.c_str()); + // g_message("### GOT '%s' \n", style.c_str()); TracingEngineResult result(style.raw(), d, nodeCount); results.push_back(result); @@ -535,34 +484,33 @@ std::vector<TracingEngineResult> PotraceTracingEngine::traceBrightnessMulti(GdkP return results; } - /** * Quantization */ -std::vector<TracingEngineResult> PotraceTracingEngine::traceQuant(GdkPixbuf * thePixbuf) +std::vector<TracingEngineResult> PotraceTracingEngine::traceQuant(GdkPixbuf *thePixbuf) { std::vector<TracingEngineResult> results; if (thePixbuf) { IndexedMap *iMap = filterIndexed(*this, thePixbuf); - if ( iMap ) { - //Create and clear a gray map + if (iMap) { + // Create and clear a gray map GrayMap *gm = GrayMapCreate(iMap->width, iMap->height); - for (int row=0 ; row<gm->height ; row++) { - for (int col=0 ; col<gm->width ; col++) { + for (int row = 0; row < gm->height; row++) { + for (int col = 0; col < gm->width; col++) { gm->setPixel(gm, col, row, GRAYMAP_WHITE); } } - for (int colorIndex=0 ; colorIndex<iMap->nrColors ; colorIndex++) { + for (int colorIndex = 0; colorIndex < iMap->nrColors; colorIndex++) { // Make a gray map for each color index - for (int row=0 ; row<iMap->height ; row++) { - for (int col=0 ; col<iMap->width ; col++) { - int indx = (int) iMap->getPixel(iMap, col, row); + for (int row = 0; row < iMap->height; row++) { + for (int col = 0; col < iMap->width; col++) { + int indx = (int)iMap->getPixel(iMap, col, row); if (indx == colorIndex) { - gm->setPixel(gm, col, row, GRAYMAP_BLACK); //black + gm->setPixel(gm, col, row, GRAYMAP_BLACK); // black } else if (!multiScanStack) { - gm->setPixel(gm, col, row, GRAYMAP_WHITE); //white + gm->setPixel(gm, col, row, GRAYMAP_WHITE); // white } } } @@ -571,12 +519,12 @@ std::vector<TracingEngineResult> PotraceTracingEngine::traceQuant(GdkPixbuf * th long nodeCount = 0L; std::string d = grayMapToPath(gm, &nodeCount); - if ( !d.empty() ) { + if (!d.empty()) { //### get style info RGB rgb = iMap->clut[colorIndex]; - ustring style = ustring::compose("fill:#%1%2%3", twohex(rgb.r), twohex(rgb.g), twohex(rgb.b) ); + ustring style = ustring::compose("fill:#%1%2%3", twohex(rgb.r), twohex(rgb.g), twohex(rgb.b)); - //g_message("### GOT '%s' \n", style.c_str()); + // g_message("### GOT '%s' \n", style.c_str()); TracingEngineResult result(style.raw(), d, nodeCount); results.push_back(result); @@ -586,7 +534,7 @@ std::vector<TracingEngineResult> PotraceTracingEngine::traceQuant(GdkPixbuf * th desktop->getMessageStack()->flash(Inkscape::NORMAL_MESSAGE, msg); } } - }// for colorIndex + } // for colorIndex gm->destroy(gm); iMap->destroy(iMap); @@ -601,53 +549,40 @@ std::vector<TracingEngineResult> PotraceTracingEngine::traceQuant(GdkPixbuf * th return results; } - /** * This is the working method of this interface, and all * implementing classes. Take a GdkPixbuf, trace it, and * return the path data that is compatible with the d="" attribute * of an SVG <path> element. */ -std::vector<TracingEngineResult> -PotraceTracingEngine::trace(Glib::RefPtr<Gdk::Pixbuf> pixbuf) +std::vector<TracingEngineResult> PotraceTracingEngine::trace(Glib::RefPtr<Gdk::Pixbuf> pixbuf) { - GdkPixbuf *thePixbuf = pixbuf->gobj(); - //Set up for messages - keepGoing = 1; + // Set up for messages + keepGoing = 1; - if ( traceType == TRACE_QUANT_COLOR || - traceType == TRACE_QUANT_MONO ) - { + if (traceType == TRACE_QUANT_COLOR || traceType == TRACE_QUANT_MONO) { return traceQuant(thePixbuf); - } - else if ( traceType == TRACE_BRIGHTNESS_MULTI ) - { + } else if (traceType == TRACE_BRIGHTNESS_MULTI) { return traceBrightnessMulti(thePixbuf); - } - else - { + } else { return traceSingle(thePixbuf); - } + } } - /** * Abort the thread that is executing getPathDataFromPixbuf() */ void PotraceTracingEngine::abort() { - //g_message("PotraceTracingEngine::abort()\n"); + // g_message("PotraceTracingEngine::abort()\n"); keepGoing = 0; } - - - -} // namespace Potrace -} // namespace Trace -} // namespace Inkscape +} // namespace Potrace +} // namespace Trace +} // namespace Inkscape /* Local Variables: diff --git a/src/trace/potrace/inkscape-potrace.h b/src/trace/potrace/inkscape-potrace.h index 1385521f1667123eda435c994b79618a3262d6b6..0129f29dd9889e3412446fdd08675b973a142174 100644 --- a/src/trace/potrace/inkscape-potrace.h +++ b/src/trace/potrace/inkscape-potrace.h @@ -18,8 +18,8 @@ #ifndef __INKSCAPE_POTRACE_H__ #define __INKSCAPE_POTRACE_H__ -#include <trace/trace.h> #include <potracelib.h> +#include <trace/trace.h> struct GrayMap_def; typedef GrayMap_def GrayMap; @@ -31,26 +31,25 @@ namespace Trace { namespace Potrace { enum TraceType - { +{ TRACE_BRIGHTNESS, TRACE_BRIGHTNESS_MULTI, TRACE_CANNY, TRACE_QUANT, TRACE_QUANT_COLOR, TRACE_QUANT_MONO - }; - +}; class PotraceTracingEngine : public TracingEngine { - - public: - +public: /** * */ PotraceTracingEngine(); - PotraceTracingEngine(TraceType traceType, bool invert, int quantizationNrColors, double brightnessThreshold, double brightnessFloor, double cannyHighThreshold, int multiScanNrColors, bool multiScanStack, bool multiScanSmooth, bool multiScanRemoveBackground); + PotraceTracingEngine(TraceType traceType, bool invert, int quantizationNrColors, double brightnessThreshold, + double brightnessFloor, double cannyHighThreshold, int multiScanNrColors, bool multiScanStack, + bool multiScanSmooth, bool multiScanRemoveBackground); /** * @@ -63,8 +62,7 @@ class PotraceTracingEngine : public TracingEngine * return the path data that is compatible with the d="" attribute * of an SVG <path> element. */ - std::vector<TracingEngineResult> trace( - Glib::RefPtr<Gdk::Pixbuf> pixbuf) override; + std::vector<TracingEngineResult> trace(Glib::RefPtr<Gdk::Pixbuf> pixbuf) override; /** * Abort the thread that is executing getPathDataFromPixbuf() @@ -81,7 +79,7 @@ class PotraceTracingEngine : public TracingEngine */ int keepGoing; - std::vector<TracingEngineResult>traceGrayMap(GrayMap *grayMap); + std::vector<TracingEngineResult> traceGrayMap(GrayMap *grayMap); potrace_param_t *potraceParams; TraceType traceType; @@ -94,40 +92,35 @@ class PotraceTracingEngine : public TracingEngine //## brightness items double brightnessThreshold; - double brightnessFloor; //usually 0.0 + double brightnessFloor; // usually 0.0 //## canny items double cannyHighThreshold; //## Color-->multiscan quantization int multiScanNrColors; - bool multiScanStack; //do we tile or stack? - bool multiScanSmooth;//do we use gaussian filter? - bool multiScanRemoveBackground; //do we remove the bottom trace? - - private: + bool multiScanStack; // do we tile or stack? + bool multiScanSmooth; // do we use gaussian filter? + bool multiScanRemoveBackground; // do we remove the bottom trace? + +private: /** * This is the actual wrapper of the call to Potrace. nodeCount * returns the count of nodes created. May be NULL if ignored. */ std::string grayMapToPath(GrayMap *gm, long *nodeCount); - std::vector<TracingEngineResult>traceBrightnessMulti(GdkPixbuf *pixbuf); - std::vector<TracingEngineResult>traceQuant(GdkPixbuf *pixbuf); - std::vector<TracingEngineResult>traceSingle(GdkPixbuf *pixbuf); - - -};//class PotraceTracingEngine - - - -} // namespace Potrace -} // namespace Trace -} // namespace Inkscape + std::vector<TracingEngineResult> traceBrightnessMulti(GdkPixbuf *pixbuf); + std::vector<TracingEngineResult> traceQuant(GdkPixbuf *pixbuf); + std::vector<TracingEngineResult> traceSingle(GdkPixbuf *pixbuf); +}; // class PotraceTracingEngine -#endif //__INKSCAPE_POTRACE_H__ +} // namespace Potrace +} // namespace Trace +} // namespace Inkscape +#endif //__INKSCAPE_POTRACE_H__ /* Local Variables: diff --git a/src/trace/quantize.cpp b/src/trace/quantize.cpp index 93dbb354328a8386ba66b3e47711b96d86b5f38e..9108f296ef0195829f08384c62de82a421ef71bf 100644 --- a/src/trace/quantize.cpp +++ b/src/trace/quantize.cpp @@ -10,14 +10,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "quantize.h" + #include <cassert> #include <cstdio> #include <cstdlib> #include <new> -#include "pool.h" #include "imagemap.h" -#include "quantize.h" +#include "pool.h" typedef struct Ocnode_def Ocnode; @@ -146,18 +147,20 @@ struct Ocnode_def inline RGB operator>>(RGB rgb, int s) { - RGB res; - res.r = rgb.r >> s; res.g = rgb.g >> s; res.b = rgb.b >> s; - return res; + RGB res; + res.r = rgb.r >> s; + res.g = rgb.g >> s; + res.b = rgb.b >> s; + return res; } inline bool operator==(RGB rgb1, RGB rgb2) { - return (rgb1.r == rgb2.r && rgb1.g == rgb2.g && rgb1.b == rgb2.b); + return (rgb1.r == rgb2.r && rgb1.g == rgb2.g && rgb1.b == rgb2.b); } inline int childIndex(RGB rgb) { - return (((rgb.r)&1)<<2) | (((rgb.g)&1)<<1) | (((rgb.b)&1)); + return (((rgb.r) & 1) << 2) | (((rgb.g) & 1) << 1) | (((rgb.b) & 1)); } /** @@ -169,23 +172,25 @@ inline Ocnode *ocnodeNew(pool<Ocnode> *pool) node->ref = nullptr; node->parent = nullptr; node->nchild = 0; - for (auto & i : node->child) i = nullptr; + for (auto &i : node->child) + i = nullptr; node->mi = 0; return node; } -inline void ocnodeFree(pool<Ocnode> *pool, Ocnode *node) { +inline void ocnodeFree(pool<Ocnode> *pool, Ocnode *node) +{ pool->drop(node); } - /** * free a full octree */ static void octreeDelete(pool<Ocnode> *pool, Ocnode *node) { - if (!node) return; - for (auto & i : node->child) + if (!node) + return; + for (auto &i : node->child) octreeDelete(pool, i); ocnodeFree(pool, node); } @@ -231,7 +236,9 @@ static void ocnodeLeaf(pool<Ocnode> *pool, Ocnode **ref, RGB rgb) Ocnode *node = ocnodeNew(pool); node->width = 0; node->rgb = rgb; - node->rs = rgb.r; node->gs = rgb.g; node->bs = rgb.b; + node->rs = rgb.r; + node->gs = rgb.g; + node->bs = rgb.b; node->weight = 1; node->nleaf = 1; node->mi = 0; @@ -245,59 +252,73 @@ static void ocnodeLeaf(pool<Ocnode> *pool, Ocnode **ref, RGB rgb) static int octreeMerge(pool<Ocnode> *pool, Ocnode *parent, Ocnode **ref, Ocnode *node1, Ocnode *node2) { assert(ref); - if (!node1 && !node2) return 0; + if (!node1 && !node2) + return 0; assert(node1 != node2); - if (parent && !*ref) parent->nchild++; - if (!node1) - { - *ref = node2; node2->ref = ref; node2->parent = parent; + if (parent && !*ref) + parent->nchild++; + if (!node1) { + *ref = node2; + node2->ref = ref; + node2->parent = parent; return node2->nleaf; - } - if (!node2) - { - *ref = node1; node1->ref = ref; node1->parent = parent; + } + if (!node2) { + *ref = node1; + node1->ref = ref; + node1->parent = parent; return node1->nleaf; - } + } int dwitdth = node1->width - node2->width; - if (dwitdth > 0 && node1->rgb == node2->rgb >> dwitdth) + if (dwitdth > 0 && node1->rgb == node2->rgb >> dwitdth) { + // place node2 below node1 { - //place node2 below node1 - { *ref = node1; node1->ref = ref; node1->parent = parent; } + *ref = node1; + node1->ref = ref; + node1->parent = parent; + } int i = childIndex(node2->rgb >> (dwitdth - 1)); - node1->rs += node2->rs; node1->gs += node2->gs; node1->bs += node2->bs; + node1->rs += node2->rs; + node1->gs += node2->gs; + node1->bs += node2->bs; node1->weight += node2->weight; - node1->mi = 0; - if (node1->child[i]) node1->nleaf -= node1->child[i]->nleaf; - node1->nleaf += - octreeMerge(pool, node1, &node1->child[i], node1->child[i], node2); + node1->mi = 0; + if (node1->child[i]) + node1->nleaf -= node1->child[i]->nleaf; + node1->nleaf += octreeMerge(pool, node1, &node1->child[i], node1->child[i], node2); return node1->nleaf; - } - else if (dwitdth < 0 && node2->rgb == node1->rgb >> (-dwitdth)) + } else if (dwitdth < 0 && node2->rgb == node1->rgb >> (-dwitdth)) { + // place node1 below node2 { - //place node1 below node2 - { *ref = node2; node2->ref = ref; node2->parent = parent; } + *ref = node2; + node2->ref = ref; + node2->parent = parent; + } int i = childIndex(node1->rgb >> (-dwitdth - 1)); - node2->rs += node1->rs; node2->gs += node1->gs; node2->bs += node1->bs; + node2->rs += node1->rs; + node2->gs += node1->gs; + node2->bs += node1->bs; node2->weight += node1->weight; - node2->mi = 0; - if (node2->child[i]) node2->nleaf -= node2->child[i]->nleaf; - node2->nleaf += - octreeMerge(pool, node2, &node2->child[i], node2->child[i], node1); + node2->mi = 0; + if (node2->child[i]) + node2->nleaf -= node2->child[i]->nleaf; + node2->nleaf += octreeMerge(pool, node2, &node2->child[i], node2->child[i], node1); return node2->nleaf; - } - else - { - //nodes have either no intersection or the same root + } else { + // nodes have either no intersection or the same root Ocnode *newnode; newnode = ocnodeNew(pool); newnode->rs = node1->rs + node2->rs; newnode->gs = node1->gs + node2->gs; newnode->bs = node1->bs + node2->bs; newnode->weight = node1->weight + node2->weight; - { *ref = newnode; newnode->ref = ref; newnode->parent = parent; } - if (dwitdth == 0 && node1->rgb == node2->rgb) - { - //merge the nodes in <newnode> + { + *ref = newnode; + newnode->ref = ref; + newnode->parent = parent; + } + if (dwitdth == 0 && node1->rgb == node2->rgb) { + // merge the nodes in <newnode> newnode->width = node1->width; // == node2->width newnode->rgb = node1->rgb; // == node2->rgb newnode->nchild = 0; @@ -306,25 +327,25 @@ static int octreeMerge(pool<Ocnode> *pool, Ocnode *parent, Ocnode **ref, Ocnode newnode->nleaf = 1; else for (int i = 0; i < 8; i++) - if (node1->child[i] || node2->child[i]) - newnode->nleaf += - octreeMerge(pool, newnode, &newnode->child[i], - node1->child[i], node2->child[i]); - ocnodeFree(pool, node1); ocnodeFree(pool, node2); + if (node1->child[i] || node2->child[i]) + newnode->nleaf += + octreeMerge(pool, newnode, &newnode->child[i], node1->child[i], node2->child[i]); + ocnodeFree(pool, node1); + ocnodeFree(pool, node2); return newnode->nleaf; - } - else - { - //use <newnode> as a fork node with children <node1> and <node2> - int newwidth = - node1->width > node2->width ? node1->width : node2->width; + } else { + // use <newnode> as a fork node with children <node1> and <node2> + int newwidth = node1->width > node2->width ? node1->width : node2->width; RGB rgb1 = node1->rgb >> (newwidth - node1->width); RGB rgb2 = node2->rgb >> (newwidth - node2->width); - //according to the previous tests <rgb1> != <rgb2> before the loop - while (!(rgb1 == rgb2)) - { rgb1 = rgb1 >> 1; rgb2 = rgb2 >> 1; newwidth++; }; + // according to the previous tests <rgb1> != <rgb2> before the loop + while (!(rgb1 == rgb2)) { + rgb1 = rgb1 >> 1; + rgb2 = rgb2 >> 1; + newwidth++; + }; newnode->width = newwidth; - newnode->rgb = rgb1; // == rgb2 + newnode->rgb = rgb1; // == rgb2 newnode->nchild = 2; newnode->nleaf = node1->nleaf + node2->nleaf; int i1 = childIndex(node1->rgb >> (newwidth - node1->width - 1)); @@ -336,8 +357,8 @@ static int octreeMerge(pool<Ocnode> *pool, Ocnode *parent, Ocnode **ref, Ocnode node2->ref = &newnode->child[i2]; newnode->child[i2] = node2; return newnode->nleaf; - } } + } } /** @@ -345,8 +366,7 @@ static int octreeMerge(pool<Ocnode> *pool, Ocnode *parent, Ocnode **ref, Ocnode */ static inline void ocnodeMi(Ocnode *node) { - node->mi = node->parent ? - node->weight << (2 * node->parent->width) : 0; + node->mi = node->parent ? node->weight << (2 * node->parent->width) : 0; } /** @@ -357,64 +377,58 @@ static inline void ocnodeMi(Ocnode *node) static void ocnodeStrip(pool<Ocnode> *pool, Ocnode **ref, int *count, unsigned long lvl) { Ocnode *node = *ref; - if (!count || !node) return; + if (!count || !node) + return; assert(ref == node->ref); if (node->nchild == 0) // leaf node - { - if (!node->mi) ocnodeMi(node); //mi generation may be required - if (node->mi > lvl) return; //leaf is above strip level + { + if (!node->mi) + ocnodeMi(node); // mi generation may be required + if (node->mi > lvl) + return; // leaf is above strip level ocnodeFree(pool, node); *ref = nullptr; (*count)--; - } - else - { - if (node->mi && node->mi > lvl) //node is above strip level + } else { + if (node->mi && node->mi > lvl) // node is above strip level return; node->nchild = 0; node->nleaf = 0; node->mi = 0; Ocnode **lonelychild = nullptr; - for (auto & i : node->child) if (i) - { - ocnodeStrip(pool, &i, count, lvl); - if (i) - { - lonelychild = &i; - node->nchild++; - node->nleaf += i->nleaf; - if (!node->mi || node->mi > i->mi) - node->mi = i->mi; + for (auto &i : node->child) + if (i) { + ocnodeStrip(pool, &i, count, lvl); + if (i) { + lonelychild = &i; + node->nchild++; + node->nleaf += i->nleaf; + if (!node->mi || node->mi > i->mi) + node->mi = i->mi; } } - // tree adjustments - if (node->nchild == 0) - { + // tree adjustments + if (node->nchild == 0) { (*count)++; node->nleaf = 1; - ocnodeMi(node); - } - else if (node->nchild == 1) - { - if ((*lonelychild)->nchild == 0) - { - //remove the <lonelychild> leaf under a 1 child node + ocnodeMi(node); + } else if (node->nchild == 1) { + if ((*lonelychild)->nchild == 0) { + // remove the <lonelychild> leaf under a 1 child node node->nchild = 0; node->nleaf = 1; - ocnodeMi(node); + ocnodeMi(node); ocnodeFree(pool, *lonelychild); *lonelychild = nullptr; - } - else - { - //make a bridge to <lonelychild> over a 1 child node + } else { + // make a bridge to <lonelychild> over a 1 child node (*lonelychild)->parent = node->parent; (*lonelychild)->ref = ref; ocnodeFree(pool, node); *ref = *lonelychild; - } } } + } } /** @@ -422,48 +436,45 @@ static void ocnodeStrip(pool<Ocnode> *pool, Ocnode **ref, int *count, unsigned l */ static void octreePrune(pool<Ocnode> *pool, Ocnode **ref, int ncolor) { - assert(ref); - assert(ncolor > 0); - //printf("pruning down to %d colors:\n", ncolor);//debug - int n = (*ref)->nleaf - ncolor; - if (!*ref || n <= 0) return; - while (n > 0) - { - //printf("removals to go: %10d\t", n);//debug - //printf("current prune impact: %10lu\n", (*ref)->mi);//debug - //calling strip with global minimum impact of the tree - ocnodeStrip(pool, ref, &n, (*ref)->mi); - } + assert(ref); + assert(ncolor > 0); + // printf("pruning down to %d colors:\n", ncolor);//debug + int n = (*ref)->nleaf - ncolor; + if (!*ref || n <= 0) + return; + while (n > 0) { + // printf("removals to go: %10d\t", n);//debug + // printf("current prune impact: %10lu\n", (*ref)->mi);//debug + // calling strip with global minimum impact of the tree + ocnodeStrip(pool, ref, &n, (*ref)->mi); + } } /** * build an octree associated to the area of a color map <rgbmap>, * included in the specified (x1,y1)--(x2,y2) rectangle. */ -static void octreeBuildArea(pool<Ocnode> *pool, RgbMap *rgbmap, Ocnode **ref, - int x1, int y1, int x2, int y2, int ncolor) +static void octreeBuildArea(pool<Ocnode> *pool, RgbMap *rgbmap, Ocnode **ref, int x1, int y1, int x2, int y2, + int ncolor) { int dx = x2 - x1, dy = y2 - y1; - int xm = x1 + dx/2, ym = y1 + dy/2; + int xm = x1 + dx / 2, ym = y1 + dy / 2; Ocnode *ref1 = nullptr; Ocnode *ref2 = nullptr; if (dx == 1 && dy == 1) ocnodeLeaf(pool, ref, rgbmap->getPixel(rgbmap, x1, y1)); - else if (dx > dy) - { - octreeBuildArea(pool, rgbmap, &ref1, x1, y1, xm, y2, ncolor); - octreeBuildArea(pool, rgbmap, &ref2, xm, y1, x2, y2, ncolor); - octreeMerge(pool, nullptr, ref, ref1, ref2); - } - else - { - octreeBuildArea(pool, rgbmap, &ref1, x1, y1, x2, ym, ncolor); - octreeBuildArea(pool, rgbmap, &ref2, x1, ym, x2, y2, ncolor); - octreeMerge(pool, nullptr, ref, ref1, ref2); - } + else if (dx > dy) { + octreeBuildArea(pool, rgbmap, &ref1, x1, y1, xm, y2, ncolor); + octreeBuildArea(pool, rgbmap, &ref2, xm, y1, x2, y2, ncolor); + octreeMerge(pool, nullptr, ref, ref1, ref2); + } else { + octreeBuildArea(pool, rgbmap, &ref1, x1, y1, x2, ym, ncolor); + octreeBuildArea(pool, rgbmap, &ref2, x1, ym, x2, y2, ncolor); + octreeMerge(pool, nullptr, ref, ref1, ref2); + } - //octreePrune(ref, 2*ncolor); - //affects result quality for almost same performance :/ + // octreePrune(ref, 2*ncolor); + // affects result quality for almost same performance :/ } /** @@ -472,17 +483,14 @@ static void octreeBuildArea(pool<Ocnode> *pool, RgbMap *rgbmap, Ocnode **ref, */ static Ocnode *octreeBuild(pool<Ocnode> *pool, RgbMap *rgbmap, int ncolor) { - //create the octree + // create the octree Ocnode *node = nullptr; - octreeBuildArea(pool, - rgbmap, &node, - 0, 0, rgbmap->width, rgbmap->height, ncolor - ); + octreeBuildArea(pool, rgbmap, &node, 0, 0, rgbmap->width, rgbmap->height, ncolor); - //prune the octree + // prune the octree octreePrune(pool, &node, ncolor); - //octreePrint(node);//debug + // octreePrint(node);//debug return node; } @@ -492,16 +500,15 @@ static Ocnode *octreeBuild(pool<Ocnode> *pool, RgbMap *rgbmap, int ncolor) */ static void octreeIndex(Ocnode *node, RGB *rgbpal, int *index) { - if (!node) return; - if (node->nchild == 0) - { + if (!node) + return; + if (node->nchild == 0) { rgbpal[*index].r = node->rs / node->weight; rgbpal[*index].g = node->gs / node->weight; rgbpal[*index].b = node->bs / node->weight; (*index)++; - } - else - for (auto & i : node->child) + } else + for (auto &i : node->child) if (i) octreeIndex(i, rgbpal, index); } @@ -511,10 +518,8 @@ static void octreeIndex(Ocnode *node, RGB *rgbpal, int *index) */ static int distRGB(RGB rgb1, RGB rgb2) { - return - (rgb1.r - rgb2.r) * (rgb1.r - rgb2.r) - + (rgb1.g - rgb2.g) * (rgb1.g - rgb2.g) - + (rgb1.b - rgb2.b) * (rgb1.b - rgb2.b); + return (rgb1.r - rgb2.r) * (rgb1.r - rgb2.r) + (rgb1.g - rgb2.g) * (rgb1.g - rgb2.g) + + (rgb1.b - rgb2.b) * (rgb1.b - rgb2.b); } /** @@ -522,14 +527,16 @@ static int distRGB(RGB rgb1, RGB rgb2) */ static int findRGB(RGB *rgbpal, int ncolor, RGB rgb) { - //assert(ncolor > 0); - //assert(rgbpal); + // assert(ncolor > 0); + // assert(rgbpal); int index = -1, dist = 0; - for (int k = 0; k < ncolor; k++) - { + for (int k = 0; k < ncolor; k++) { int d = distRGB(rgbpal[k], rgb); - if (index == -1 || d < dist) { dist = d; index = k; } + if (index == -1 || d < dist) { + dist = d; + index = k; } + } return index; } @@ -557,12 +564,11 @@ IndexedMap *rgbMapQuantize(RgbMap *rgbmap, int ncolor) Ocnode *tree = nullptr; try { tree = octreeBuild(&pool, rgbmap, ncolor); - } - catch (std::bad_alloc &ex) { - //should do smthg else? + } catch (std::bad_alloc &ex) { + // should do smthg else? } - if ( tree ) { + if (tree) { RGB *rgbpal = new RGB[ncolor]; int indexes = 0; octreeIndex(tree, rgbpal, &indexes); diff --git a/src/trace/siox.cpp b/src/trace/siox.cpp index 12d7c20a8b0ea5e2b013afd4fe1bf875902edac7..52f2c9aac14c72d661bed60f9f55c1b603009544 100644 --- a/src/trace/siox.cpp +++ b/src/trace/siox.cpp @@ -8,20 +8,15 @@ */ #include "siox.h" +#include <algorithm> #include <cmath> #include <cstdarg> -#include <map> -#include <algorithm> #include <cstdlib> +#include <map> +namespace org { -namespace org -{ - -namespace siox -{ - - +namespace siox { //######################################################################## //# C L A B @@ -32,88 +27,84 @@ namespace siox */ static unsigned long getRGB(int a, int r, int g, int b) { - if (a<0) a=0; - else if (a>255) a=255; - - if (r<0) r=0; - else if (r>255) r=255; - - if (g<0) g=0; - else if (g>255) g=255; - - if (b<0) b=0; - else if (b>255) b=255; - - return (a<<24)|(r<<16)|(g<<8)|b; + if (a < 0) + a = 0; + else if (a > 255) + a = 255; + + if (r < 0) + r = 0; + else if (r > 255) + r = 255; + + if (g < 0) + g = 0; + else if (g > 255) + g = 255; + + if (b < 0) + b = 0; + else if (b > 255) + b = 255; + + return (a << 24) | (r << 16) | (g << 8) | b; } - - /** * Convert float A, R, G, B values (0.0-1.0) into an pixel value. */ static unsigned long getRGB(float a, float r, float g, float b) { - return getRGB((int)(a * 256.0), - (int)(r * 256.0), - (int)(g * 256.0), - (int)(b * 256.0)); + return getRGB((int)(a * 256.0), (int)(r * 256.0), (int)(g * 256.0), (int)(b * 256.0)); } - - //######################################### //# Root approximations for large speedup. //# By njh! //######################################### static const int ROOT_TAB_SIZE = 16; -static float cbrt_table[ROOT_TAB_SIZE +1]; +static float cbrt_table[ROOT_TAB_SIZE + 1]; double CieLab::cbrt(double x) { - double y = cbrt_table[int(x*ROOT_TAB_SIZE )]; // assuming x \in [0, 1] - y = (2.0 * y + x/(y*y))/3.0; - y = (2.0 * y + x/(y*y))/3.0; // polish twice + double y = cbrt_table[int(x * ROOT_TAB_SIZE)]; // assuming x \in [0, 1] + y = (2.0 * y + x / (y * y)) / 3.0; + y = (2.0 * y + x / (y * y)) / 3.0; // polish twice return y; } -static float qn_table[ROOT_TAB_SIZE +1]; +static float qn_table[ROOT_TAB_SIZE + 1]; double CieLab::qnrt(double x) { - double y = qn_table[int(x*ROOT_TAB_SIZE )]; // assuming x \in [0, 1] - double Y = y*y; - y = (4.0*y + x/(Y*Y))/5.0; - Y = y*y; - y = (4.0*y + x/(Y*Y))/5.0; // polish twice + double y = qn_table[int(x * ROOT_TAB_SIZE)]; // assuming x \in [0, 1] + double Y = y * y; + y = (4.0 * y + x / (Y * Y)) / 5.0; + Y = y * y; + y = (4.0 * y + x / (Y * Y)) / 5.0; // polish twice return y; } double CieLab::pow24(double x) { - double onetwo = x*qnrt(x); - return onetwo*onetwo; + double onetwo = x * qnrt(x); + return onetwo * onetwo; } - static bool _clab_inited_ = false; void CieLab::init() { - if (!_clab_inited_) - { - cbrt_table[0] = pow(float(1)/float(ROOT_TAB_SIZE*2), 0.3333); - qn_table[0] = pow(float(1)/float(ROOT_TAB_SIZE*2), 0.2); - for(int i = 1; i < ROOT_TAB_SIZE +1; i++) - { - cbrt_table[i] = pow(float(i)/float(ROOT_TAB_SIZE), 0.3333); - qn_table[i] = pow(float(i)/float(ROOT_TAB_SIZE), 0.2); - } - _clab_inited_ = true; + if (!_clab_inited_) { + cbrt_table[0] = pow(float(1) / float(ROOT_TAB_SIZE * 2), 0.3333); + qn_table[0] = pow(float(1) / float(ROOT_TAB_SIZE * 2), 0.2); + for (int i = 1; i < ROOT_TAB_SIZE + 1; i++) { + cbrt_table[i] = pow(float(i) / float(ROOT_TAB_SIZE), 0.3333); + qn_table[i] = pow(float(i) / float(ROOT_TAB_SIZE), 0.2); } + _clab_inited_ = true; + } } - - /** * Construct this CieLab from a packed-pixel ARGB value */ @@ -121,30 +112,30 @@ CieLab::CieLab(unsigned long rgb) { init(); - int ir = (rgb>>16) & 0xff; - int ig = (rgb>> 8) & 0xff; - int ib = (rgb ) & 0xff; + int ir = (rgb >> 16) & 0xff; + int ig = (rgb >> 8) & 0xff; + int ib = (rgb)&0xff; float fr = ((float)ir) / 255.0; float fg = ((float)ig) / 255.0; float fb = ((float)ib) / 255.0; - //printf("fr:%f fg:%f fb:%f\n", fr, fg, fb); + // printf("fr:%f fg:%f fb:%f\n", fr, fg, fb); if (fr > 0.04045) - //fr = (float) pow((fr + 0.055) / 1.055, 2.4); - fr = (float) pow24((fr + 0.055) / 1.055); + // fr = (float) pow((fr + 0.055) / 1.055, 2.4); + fr = (float)pow24((fr + 0.055) / 1.055); else fr = fr / 12.92; if (fg > 0.04045) - //fg = (float) pow((fg + 0.055) / 1.055, 2.4); - fg = (float) pow24((fg + 0.055) / 1.055); + // fg = (float) pow((fg + 0.055) / 1.055, 2.4); + fg = (float)pow24((fg + 0.055) / 1.055); else fg = fg / 12.92; if (fb > 0.04045) - //fb = (float) pow((fb + 0.055) / 1.055, 2.4); - fb = (float) pow24((fb + 0.055) / 1.055); + // fb = (float) pow((fb + 0.055) / 1.055, 2.4); + fb = (float)pow24((fb + 0.055) / 1.055); else fb = fb / 12.92; @@ -157,22 +148,22 @@ CieLab::CieLab(unsigned long rgb) float vy = y; float vz = z / 1.08883; - //printf("vx:%f vy:%f vz:%f\n", vx, vy, vz); + // printf("vx:%f vy:%f vz:%f\n", vx, vy, vz); if (vx > 0.008856) - //vx = (float) pow(vx, 0.3333); - vx = (float) cbrt(vx); + // vx = (float) pow(vx, 0.3333); + vx = (float)cbrt(vx); else vx = (7.787 * vx) + (16.0 / 116.0); if (vy > 0.008856) - //vy = (float) pow(vy, 0.3333); - vy = (float) cbrt(vy); + // vy = (float) pow(vy, 0.3333); + vy = (float)cbrt(vy); else vy = (7.787 * vy) + (16.0 / 116.0); if (vz > 0.008856) - //vz = (float) pow(vz, 0.3333); - vz = (float) cbrt(vz); + // vz = (float) pow(vz, 0.3333); + vz = (float)cbrt(vz); else vz = (7.787 * vz) + (16.0 / 116.0); @@ -182,8 +173,6 @@ CieLab::CieLab(unsigned long rgb) B = 200.0 * (vy - vz); } - - /** * Return this CieLab's value converted to a packed-pixel ARGB value */ @@ -212,12 +201,12 @@ unsigned long CieLab::toRGB() else vz = (vz - 16.0 / 116.0) / 7.787; - vx *= 0.95047; //use white = D65 + vx *= 0.95047; // use white = D65 vz *= 1.08883; - float vr =(float)(vx * 3.2406 + vy * -1.5372 + vz * -0.4986); - float vg =(float)(vx * -0.9689 + vy * 1.8758 + vz * 0.0415); - float vb =(float)(vx * 0.0557 + vy * -0.2040 + vz * 1.0570); + float vr = (float)(vx * 3.2406 + vy * -1.5372 + vz * -0.4986); + float vg = (float)(vx * -0.9689 + vy * 1.8758 + vz * 0.0415); + float vb = (float)(vx * 0.0557 + vy * -0.2040 + vz * 1.0570); if (vr > 0.0031308) vr = (float)(1.055 * pow(vr, (1.0 / 2.4)) - 0.055); @@ -237,13 +226,12 @@ unsigned long CieLab::toRGB() return getRGB(0.0, vr, vg, vb); } - /** * Squared Euclidian distance between this and another color */ float CieLab::diffSq(const CieLab &other) { - float sum=0.0; + float sum = 0.0; sum += (L - other.L) * (L - other.L); sum += (A - other.A) * (A - other.A); sum += (B - other.B) * (B - other.B); @@ -262,18 +250,15 @@ float CieLab::diffSq(unsigned int rgb1, unsigned int rgb2) return euclid; } - /** * Computes squared euclidian distance in CieLab space for two colors * given as RGB values. */ float CieLab::diff(unsigned int rgb0, unsigned int rgb1) { - return (float) sqrt(diffSq(rgb0, rgb1)); + return (float)sqrt(diffSq(rgb0, rgb1)); } - - //######################################################################## //# T U P E L //######################################################################## @@ -283,44 +268,38 @@ float CieLab::diff(unsigned int rgb0, unsigned int rgb1) * in background and foreground and the index to the centroids in each * signature for a given color. */ -class Tupel { +class Tupel +{ public: - Tupel() - { - minBgDist = 0.0f; + { + minBgDist = 0.0f; indexMinBg = 0; - minFgDist = 0.0f; + minFgDist = 0.0f; indexMinFg = 0; - } - Tupel(float minBgDistArg, long indexMinBgArg, - float minFgDistArg, long indexMinFgArg) - { - minBgDist = minBgDistArg; + } + Tupel(float minBgDistArg, long indexMinBgArg, float minFgDistArg, long indexMinFgArg) + { + minBgDist = minBgDistArg; indexMinBg = indexMinBgArg; - minFgDist = minFgDistArg; + minFgDist = minFgDistArg; indexMinFg = indexMinFgArg; - } + } Tupel(const Tupel &other) - { - minBgDist = other.minBgDist; + { + minBgDist = other.minBgDist; indexMinBg = other.indexMinBg; - minFgDist = other.minFgDist; + minFgDist = other.minFgDist; indexMinFg = other.indexMinFg; - } - Tupel &operator=(const Tupel &other) - = default; - virtual ~Tupel() - = default; + } + Tupel &operator=(const Tupel &other) = default; + virtual ~Tupel() = default; float minBgDist; - long indexMinBg; + long indexMinBg; float minFgDist; - long indexMinFg; - - }; - - + long indexMinFg; +}; //######################################################################## //# S I O X I M A G E @@ -340,7 +319,7 @@ SioxImage::SioxImage(unsigned int widthArg, unsigned int heightArg) SioxImage::SioxImage(const SioxImage &other) { pixdata = nullptr; - cmdata = nullptr; + cmdata = nullptr; assign(other); } @@ -353,14 +332,15 @@ SioxImage &SioxImage::operator=(const SioxImage &other) return *this; } - /** * Clean up after use. */ SioxImage::~SioxImage() { - if (pixdata) delete[] pixdata; - if (cmdata) delete[] cmdata; + if (pixdata) + delete[] pixdata; + if (cmdata) + delete[] cmdata; } /** @@ -372,7 +352,7 @@ void SioxImage::error(const char *fmt, ...) va_list args; va_start(args, fmt); vsnprintf(msgbuf, 255, fmt, args); - va_end(args) ; + va_end(args); #ifdef HAVE_GLIB g_warning("SioxImage error: %s\n", msgbuf); #else @@ -380,7 +360,6 @@ void SioxImage::error(const char *fmt, ...) #endif } - /** * Returns true if the previous operation on this image * was successful, else false. @@ -400,21 +379,16 @@ void SioxImage::setValid(bool val) valid = val; } - /** * Set a pixel at the x,y coordinates to the given value. * If the coordinates are out of range, do nothing. */ -void SioxImage::setPixel(unsigned int x, - unsigned int y, - unsigned int pixval) +void SioxImage::setPixel(unsigned int x, unsigned int y, unsigned int pixval) { - if (x >= width || y >= height) - { - error("setPixel: out of bounds (%d,%d)/(%d,%d)", - x, y, width, height); + if (x >= width || y >= height) { + error("setPixel: out of bounds (%d,%d)/(%d,%d)", x, y, width, height); return; - } + } unsigned long offset = width * y + x; pixdata[offset] = pixval; } @@ -423,40 +397,28 @@ void SioxImage::setPixel(unsigned int x, * Set a pixel at the x,y coordinates to the given r, g, b values. * If the coordinates are out of range, do nothing. */ -void SioxImage::setPixel(unsigned int x, unsigned int y, - unsigned int a, - unsigned int r, - unsigned int g, - unsigned int b) +void SioxImage::setPixel(unsigned int x, unsigned int y, unsigned int a, unsigned int r, unsigned int g, unsigned int b) { - if (x >= width || y >= height) - { - error("setPixel: out of bounds (%d,%d)/(%d,%d)", - x, y, width, height); + if (x >= width || y >= height) { + error("setPixel: out of bounds (%d,%d)/(%d,%d)", x, y, width, height); return; - } + } unsigned long offset = width * y + x; - unsigned int pixval = ((a << 24) & 0xff000000) | - ((r << 16) & 0x00ff0000) | - ((g << 8) & 0x0000ff00) | - ((b ) & 0x000000ff); + unsigned int pixval = + ((a << 24) & 0xff000000) | ((r << 16) & 0x00ff0000) | ((g << 8) & 0x0000ff00) | ((b)&0x000000ff); pixdata[offset] = pixval; } - - /** * Get a pixel at the x,y coordinates given. If * the coordinates are out of range, return 0; */ unsigned int SioxImage::getPixel(unsigned int x, unsigned int y) { - if (x >= width || y >= height) - { - error("getPixel: out of bounds (%d,%d)/(%d,%d)", - x, y, width, height); + if (x >= width || y >= height) { + error("getPixel: out of bounds (%d,%d)/(%d,%d)", x, y, width, height); return 0L; - } + } unsigned long offset = width * y + x; return pixdata[offset]; } @@ -473,16 +435,12 @@ unsigned int *SioxImage::getImageData() * Set a confidence value at the x,y coordinates to the given value. * If the coordinates are out of range, do nothing. */ -void SioxImage::setConfidence(unsigned int x, - unsigned int y, - float confval) +void SioxImage::setConfidence(unsigned int x, unsigned int y, float confval) { - if (x >= width || y >= height) - { - error("setConfidence: out of bounds (%d,%d)/(%d,%d)", - x, y, width, height); + if (x >= width || y >= height) { + error("setConfidence: out of bounds (%d,%d)/(%d,%d)", x, y, width, height); return; - } + } unsigned long offset = width * y + x; cmdata[offset] = confval; } @@ -493,12 +451,10 @@ void SioxImage::setConfidence(unsigned int x, */ float SioxImage::getConfidence(unsigned int x, unsigned int y) { - if (x >= width || y >= height) - { - g_warning("getConfidence: out of bounds (%d,%d)/(%d,%d)", - x, y, width, height); + if (x >= width || y >= height) { + g_warning("getConfidence: out of bounds (%d,%d)/(%d,%d)", x, y, width, height); return 0.0; - } + } unsigned long offset = width * y + x; return cmdata[offset]; } @@ -511,7 +467,6 @@ float *SioxImage::getConfidenceData() return cmdata; } - /** * Return the width of this image */ @@ -533,17 +488,16 @@ int SioxImage::getHeight() */ void SioxImage::init(unsigned int widthArg, unsigned int heightArg) { - valid = true; - width = widthArg; - height = heightArg; + valid = true; + width = widthArg; + height = heightArg; imageSize = width * height; - pixdata = new unsigned int[imageSize]; - cmdata = new float[imageSize]; - for (unsigned long i=0 ; i<imageSize ; i++) - { + pixdata = new unsigned int[imageSize]; + cmdata = new float[imageSize]; + for (unsigned long i = 0; i < imageSize; i++) { pixdata[i] = 0; - cmdata[i] = 0.0; - } + cmdata[i] = 0.0; + } } /** @@ -551,53 +505,49 @@ void SioxImage::init(unsigned int widthArg, unsigned int heightArg) */ void SioxImage::assign(const SioxImage &other) { - if (pixdata) delete[] pixdata; - if (cmdata) delete[] cmdata; - valid = other.valid; - width = other.width; - height = other.height; + if (pixdata) + delete[] pixdata; + if (cmdata) + delete[] cmdata; + valid = other.valid; + width = other.width; + height = other.height; imageSize = width * height; - pixdata = new unsigned int[imageSize]; - cmdata = new float[imageSize]; - for (unsigned long i=0 ; i<imageSize ; i++) - { + pixdata = new unsigned int[imageSize]; + cmdata = new float[imageSize]; + for (unsigned long i = 0; i < imageSize; i++) { pixdata[i] = other.pixdata[i]; - cmdata[i] = other.cmdata[i]; - } + cmdata[i] = other.cmdata[i]; + } } - /** * Write the image to a PPM file */ bool SioxImage::writePPM(const std::string &fileName) { - FILE *f = fopen(fileName.c_str(), "wb"); if (!f) return false; fprintf(f, "P6 %u %u 255\n", width, height); - for (unsigned int y=0 ; y<height; y++) - { - for (unsigned int x=0 ; x<width ; x++) - { + for (unsigned int y = 0; y < height; y++) { + for (unsigned int x = 0; x < width; x++) { unsigned int rgb = getPixel(x, y); - //unsigned int alpha = (rgb>>24) & 0xff; - unsigned int r = ((rgb>>16) & 0xff); - unsigned int g = ((rgb>> 8) & 0xff); - unsigned int b = ((rgb ) & 0xff); - fputc((unsigned char) r, f); - fputc((unsigned char) g, f); - fputc((unsigned char) b, f); - } + // unsigned int alpha = (rgb>>24) & 0xff; + unsigned int r = ((rgb >> 16) & 0xff); + unsigned int g = ((rgb >> 8) & 0xff); + unsigned int b = ((rgb)&0xff); + fputc((unsigned char)r, f); + fputc((unsigned char)g, f); + fputc((unsigned char)b, f); } + } fclose(f); return true; } - #ifdef HAVE_GLIB /** @@ -608,36 +558,31 @@ SioxImage::SioxImage(GdkPixbuf *buf) if (!buf) return; - unsigned int width = gdk_pixbuf_get_width(buf); + unsigned int width = gdk_pixbuf_get_width(buf); unsigned int height = gdk_pixbuf_get_height(buf); - init(width, height); //DO THIS NOW!! - + init(width, height); // DO THIS NOW!! - guchar *pixldata = gdk_pixbuf_get_pixels(buf); - int rowstride = gdk_pixbuf_get_rowstride(buf); - int n_channels = gdk_pixbuf_get_n_channels(buf); + guchar *pixldata = gdk_pixbuf_get_pixels(buf); + int rowstride = gdk_pixbuf_get_rowstride(buf); + int n_channels = gdk_pixbuf_get_n_channels(buf); //### Fill in the cells with RGB values - int row = 0; - for (unsigned int y=0 ; y<height ; y++) - { + int row = 0; + for (unsigned int y = 0; y < height; y++) { guchar *p = pixldata + row; - for (unsigned int x=0 ; x<width ; x++) - { - int r = (int)p[0]; - int g = (int)p[1]; - int b = (int)p[2]; + for (unsigned int x = 0; x < width; x++) { + int r = (int)p[0]; + int g = (int)p[1]; + int b = (int)p[2]; int alpha = (int)p[3]; setPixel(x, y, alpha, r, g, b); p += n_channels; - } - row += rowstride; } - + row += rowstride; + } } - /** * Create a GdkPixbuf from this image */ @@ -646,45 +591,36 @@ GdkPixbuf *SioxImage::getGdkPixbuf() bool has_alpha = true; int n_channels = has_alpha ? 4 : 3; - guchar *pixdata = (guchar *) - malloc(sizeof(guchar) * width * height * n_channels); + guchar *pixdata = (guchar *)malloc(sizeof(guchar) * width * height * n_channels); if (!pixdata) return nullptr; - int rowstride = width * n_channels; + int rowstride = width * n_channels; - GdkPixbuf *buf = gdk_pixbuf_new_from_data(pixdata, - GDK_COLORSPACE_RGB, - has_alpha, 8, width, height, - rowstride, (GdkPixbufDestroyNotify)free, nullptr); + GdkPixbuf *buf = gdk_pixbuf_new_from_data(pixdata, GDK_COLORSPACE_RGB, has_alpha, 8, width, height, rowstride, + (GdkPixbufDestroyNotify)free, nullptr); //### Fill in the cells with RGB values - int row = 0; - for (unsigned int y=0 ; y < height ; y++) - { + int row = 0; + for (unsigned int y = 0; y < height; y++) { guchar *p = pixdata + row; - for (unsigned x=0 ; x < width ; x++) - { + for (unsigned x = 0; x < width; x++) { unsigned int rgb = getPixel(x, y); - p[0] = (rgb >> 16) & 0xff;//r - p[1] = (rgb >> 8) & 0xff;//g - p[2] = (rgb ) & 0xff;//b - if ( n_channels > 3 ) - { - p[3] = (rgb >> 24) & 0xff;//a - } - p += n_channels; + p[0] = (rgb >> 16) & 0xff; // r + p[1] = (rgb >> 8) & 0xff; // g + p[2] = (rgb)&0xff; // b + if (n_channels > 3) { + p[3] = (rgb >> 24) & 0xff; // a } - row += rowstride; + p += n_channels; } + row += rowstride; + } return buf; } #endif /* GLIB */ - - - //######################################################################## //# S I O X //######################################################################## @@ -696,40 +632,40 @@ GdkPixbuf *SioxImage::getGdkPixbuf() /** * Confidence corresponding to a certain foreground region (equals one). */ -const float Siox::CERTAIN_FOREGROUND_CONFIDENCE=1.0f; +const float Siox::CERTAIN_FOREGROUND_CONFIDENCE = 1.0f; /** * Confidence for a region likely being foreground. */ -const float Siox::FOREGROUND_CONFIDENCE=0.8f; +const float Siox::FOREGROUND_CONFIDENCE = 0.8f; /** * Confidence for foreground or background type being equally likely. */ -const float Siox::UNKNOWN_REGION_CONFIDENCE=0.5f; +const float Siox::UNKNOWN_REGION_CONFIDENCE = 0.5f; /** * Confidence for a region likely being background. */ -const float Siox::BACKGROUND_CONFIDENCE=0.1f; +const float Siox::BACKGROUND_CONFIDENCE = 0.1f; /** * Confidence corresponding to a certain background reagion (equals zero). */ -const float Siox::CERTAIN_BACKGROUND_CONFIDENCE=0.0f; +const float Siox::CERTAIN_BACKGROUND_CONFIDENCE = 0.0f; /** * Construct a Siox engine */ -Siox::Siox() : - sioxObserver(nullptr), - keepGoing(true), - width(0), - height(0), - pixelCount(0), - image(nullptr), - cm(nullptr), - labelField(nullptr) +Siox::Siox() + : sioxObserver(nullptr) + , keepGoing(true) + , width(0) + , height(0) + , pixelCount(0) + , image(nullptr) + , cm(nullptr) + , labelField(nullptr) { init(); } @@ -737,20 +673,19 @@ Siox::Siox() : /** * Construct a Siox engine */ -Siox::Siox(SioxObserver *observer) : - sioxObserver(observer), - keepGoing(true), - width(0), - height(0), - pixelCount(0), - image(nullptr), - cm(nullptr), - labelField(nullptr) +Siox::Siox(SioxObserver *observer) + : sioxObserver(observer) + , keepGoing(true) + , width(0) + , height(0) + , pixelCount(0) + , image(nullptr) + , cm(nullptr) + , labelField(nullptr) { init(); } - /** * */ @@ -759,7 +694,6 @@ Siox::~Siox() cleanup(); } - /** * Error logging */ @@ -769,7 +703,7 @@ void Siox::error(const char *fmt, ...) va_list args; va_start(args, fmt); vsnprintf(msgbuf, 255, fmt, args); - va_end(args) ; + va_end(args); #ifdef HAVE_GLIB g_warning("Siox error: %s\n", msgbuf); #else @@ -786,7 +720,7 @@ void Siox::trace(const char *fmt, ...) va_list args; va_start(args, fmt); vsnprintf(msgbuf, 255, fmt, args); - va_end(args) ; + va_end(args); #ifdef HAVE_GLIB g_message("Siox: %s\n", msgbuf); #else @@ -794,8 +728,6 @@ void Siox::trace(const char *fmt, ...) #endif } - - /** * Progress reporting */ @@ -806,24 +738,19 @@ bool Siox::progressReport(float percentCompleted) bool ret = sioxObserver->progress(percentCompleted); - if (!ret) - { - trace("User selected abort"); - keepGoing = false; - } + if (!ret) { + trace("User selected abort"); + keepGoing = false; + } return ret; } - - - /** * Extract the foreground of the original image, according * to the values in the confidence matrix. */ -SioxImage Siox::extractForeground(const SioxImage &originalImage, - unsigned int backgroundFillColor) +SioxImage Siox::extractForeground(const SioxImage &originalImage, unsigned int backgroundFillColor) { trace("### Start"); @@ -833,11 +760,11 @@ SioxImage Siox::extractForeground(const SioxImage &originalImage, SioxImage workImage = originalImage; //# fetch some info from the image - width = workImage.getWidth(); - height = workImage.getHeight(); + width = workImage.getWidth(); + height = workImage.getHeight(); pixelCount = width * height; - image = workImage.getImageData(); - cm = workImage.getConfidenceData(); + image = workImage.getImageData(); + cm = workImage.getConfidenceData(); labelField = new int[pixelCount]; trace("### Creating signatures"); @@ -846,8 +773,7 @@ SioxImage Siox::extractForeground(const SioxImage &originalImage, std::vector<CieLab> knownBg; std::vector<CieLab> knownFg; CieLab *imageClab = new CieLab[pixelCount]; - for (unsigned long i=0 ; i<pixelCount ; i++) - { + for (unsigned long i = 0; i < pixelCount; i++) { float conf = cm[i]; unsigned int pix = image[i]; CieLab lab(pix); @@ -856,7 +782,7 @@ SioxImage Siox::extractForeground(const SioxImage &originalImage, knownBg.push_back(lab); else if (conf >= FOREGROUND_CONFIDENCE) knownFg.push_back(lab); - } + } /* std::vector<CieLab> imageClab; @@ -874,69 +800,61 @@ SioxImage Siox::extractForeground(const SioxImage &originalImage, } */ - if (!progressReport(10.0)) - { + if (!progressReport(10.0)) { error("User aborted"); workImage.setValid(false); delete[] imageClab; delete[] labelField; return workImage; - } - - trace("knownBg:%u knownFg:%u", static_cast<unsigned int>(knownBg.size()), static_cast<unsigned int>(knownFg.size())); + } + trace("knownBg:%u knownFg:%u", static_cast<unsigned int>(knownBg.size()), + static_cast<unsigned int>(knownFg.size())); - std::vector<CieLab> bgSignature ; - if (!colorSignature(knownBg, bgSignature, 3)) - { + std::vector<CieLab> bgSignature; + if (!colorSignature(knownBg, bgSignature, 3)) { error("Could not create background signature"); workImage.setValid(false); delete[] imageClab; delete[] labelField; return workImage; - } + } - if (!progressReport(30.0)) - { + if (!progressReport(30.0)) { error("User aborted"); workImage.setValid(false); delete[] imageClab; delete[] labelField; return workImage; - } - + } - std::vector<CieLab> fgSignature ; - if (!colorSignature(knownFg, fgSignature, 3)) - { + std::vector<CieLab> fgSignature; + if (!colorSignature(knownFg, fgSignature, 3)) { error("Could not create foreground signature"); workImage.setValid(false); delete[] imageClab; delete[] labelField; return workImage; - } + } - //trace("### bgSignature:%d", bgSignature.size()); + // trace("### bgSignature:%d", bgSignature.size()); - if (bgSignature.empty()) - { + if (bgSignature.empty()) { // segmentation impossible error("Signature size is < 1. Segmentation is impossible"); workImage.setValid(false); delete[] imageClab; delete[] labelField; return workImage; - } + } - if (!progressReport(30.0)) - { + if (!progressReport(30.0)) { error("User aborted"); workImage.setValid(false); delete[] imageClab; delete[] labelField; return workImage; - } - + } // classify using color signatures, // classification cached in hashmap for drb and speedup purposes @@ -946,138 +864,115 @@ SioxImage Siox::extractForeground(const SioxImage &originalImage, unsigned int progressResolution = pixelCount / 10; - for (unsigned int i=0; i<pixelCount; i++) - { - if (i % progressResolution == 0) - { - float progress = - 30.0 + 60.0 * (float)i / (float)pixelCount; - //trace("### progress:%f", progress); - if (!progressReport(progress)) - { + for (unsigned int i = 0; i < pixelCount; i++) { + if (i % progressResolution == 0) { + float progress = 30.0 + 60.0 * (float)i / (float)pixelCount; + // trace("### progress:%f", progress); + if (!progressReport(progress)) { error("User aborted"); delete[] imageClab; delete[] labelField; workImage.setValid(false); return workImage; - } } + } - if (cm[i] >= FOREGROUND_CONFIDENCE) - { + if (cm[i] >= FOREGROUND_CONFIDENCE) { cm[i] = CERTAIN_FOREGROUND_CONFIDENCE; - } - else if (cm[i] <= BACKGROUND_CONFIDENCE) - { + } else if (cm[i] <= BACKGROUND_CONFIDENCE) { cm[i] = CERTAIN_BACKGROUND_CONFIDENCE; - } - else // somewhere in between - { + } else // somewhere in between + { bool isBackground = true; std::map<unsigned int, Tupel>::iterator iter = hs.find(i); - if (iter != hs.end()) //found - { - Tupel tupel = iter->second; + if (iter != hs.end()) // found + { + Tupel tupel = iter->second; isBackground = tupel.minBgDist <= tupel.minFgDist; - } - else - { - CieLab lab = imageClab[i]; - float minBg = lab.diffSq(bgSignature[0]); + } else { + CieLab lab = imageClab[i]; + float minBg = lab.diffSq(bgSignature[0]); int minIndex = 0; - for (unsigned int j=1; j<bgSignature.size() ; j++) - { + for (unsigned int j = 1; j < bgSignature.size(); j++) { float d = lab.diffSq(bgSignature[j]); - if (d<minBg) - { - minBg = d; + if (d < minBg) { + minBg = d; minIndex = j; - } } - Tupel tupel(0.0f, 0, 0.0f, 0); - tupel.minBgDist = minBg; + } + Tupel tupel(0.0f, 0, 0.0f, 0); + tupel.minBgDist = minBg; tupel.indexMinBg = minIndex; - float minFg = 1.0e6f; - minIndex = -1; - for (unsigned int j = 0 ; j < fgSignature.size() ; j++) - { + float minFg = 1.0e6f; + minIndex = -1; + for (unsigned int j = 0; j < fgSignature.size(); j++) { float d = lab.diffSq(fgSignature[j]); - if (d < minFg) - { - minFg = d; + if (d < minFg) { + minFg = d; minIndex = j; - } } - tupel.minFgDist = minFg; + } + tupel.minFgDist = minFg; tupel.indexMinFg = minIndex; - if (fgSignature.empty()) - { + if (fgSignature.empty()) { isBackground = (minBg <= clusterSize); // remove next line to force behaviour of old algorithm - //error("foreground signature does not exist"); - //delete[] labelField; - //workImage.setValid(false); - //return workImage; - } - else - { + // error("foreground signature does not exist"); + // delete[] labelField; + // workImage.setValid(false); + // return workImage; + } else { isBackground = minBg < minFg; - } - hs[image[i]] = tupel; } + hs[image[i]] = tupel; + } if (isBackground) cm[i] = CERTAIN_BACKGROUND_CONFIDENCE; else cm[i] = CERTAIN_FOREGROUND_CONFIDENCE; - } } - + } delete[] imageClab; trace("### postProcessing"); - //#### postprocessing smooth(cm, width, height, 0.333f, 0.333f, 0.333f); // average normalizeMatrix(cm, pixelCount); erode(cm, width, height); - keepOnlyLargeComponents(UNKNOWN_REGION_CONFIDENCE, 1.0/*sizeFactorToKeep*/); + keepOnlyLargeComponents(UNKNOWN_REGION_CONFIDENCE, 1.0 /*sizeFactorToKeep*/); - //for (int i=0; i < 2/*smoothness*/; i++) + // for (int i=0; i < 2/*smoothness*/; i++) // smooth(cm, width, height, 0.333f, 0.333f, 0.333f); // average normalizeMatrix(cm, pixelCount); - for (unsigned int i=0; i < pixelCount; i++) - { + for (unsigned int i = 0; i < pixelCount; i++) { if (cm[i] >= UNKNOWN_REGION_CONFIDENCE) cm[i] = CERTAIN_FOREGROUND_CONFIDENCE; else cm[i] = CERTAIN_BACKGROUND_CONFIDENCE; - } + } - keepOnlyLargeComponents(UNKNOWN_REGION_CONFIDENCE, 1.5/*sizeFactorToKeep*/); + keepOnlyLargeComponents(UNKNOWN_REGION_CONFIDENCE, 1.5 /*sizeFactorToKeep*/); fillColorRegions(); dilate(cm, width, height); - if (!progressReport(100.0)) - { + if (!progressReport(100.0)) { error("User aborted"); delete[] labelField; workImage.setValid(false); return workImage; - } - + } //#### We are done. Now clear everything but the background - for (unsigned long i = 0; i<pixelCount ; i++) - { + for (unsigned long i = 0; i < pixelCount; i++) { float conf = cm[i]; if (conf < FOREGROUND_CONFIDENCE) image[i] = backgroundFillColor; - } + } delete[] labelField; @@ -1086,8 +981,6 @@ SioxImage Siox::extractForeground(const SioxImage &originalImage, return workImage; } - - //############## //## PRIVATE //############## @@ -1110,66 +1003,52 @@ void Siox::init() clusterSize = sqrEuclidianDist(limits, 3, negLimits); } - /** * Clean up any debris from processing. */ -void Siox::cleanup() -{ -} - - - +void Siox::cleanup() {} /** * Stage 1 of the color signature work. 'dims' will be either * 2 for grays, or 3 for colors */ -void Siox::colorSignatureStage1(CieLab *points, - unsigned int leftBase, - unsigned int rightBase, - unsigned int recursionDepth, - unsigned int *clusterCount, - const unsigned int dims) +void Siox::colorSignatureStage1(CieLab *points, unsigned int leftBase, unsigned int rightBase, + unsigned int recursionDepth, unsigned int *clusterCount, const unsigned int dims) { - unsigned int currentDim = recursionDepth % dims; CieLab point = points[leftBase]; float min = point(currentDim); float max = min; - for (unsigned int i = leftBase + 1; i < rightBase ; i++) - { + for (unsigned int i = leftBase + 1; i < rightBase; i++) { point = points[i]; float curval = point(currentDim); - if (curval < min) min = curval; - if (curval > max) max = curval; - } + if (curval < min) + min = curval; + if (curval > max) + max = curval; + } - //Do the Rubner-rule split (sounds like a dance) - if (max - min > limits[currentDim]) - { - float pivotPoint = (min + max) / 2.0; //average - unsigned int left = leftBase; + // Do the Rubner-rule split (sounds like a dance) + if (max - min > limits[currentDim]) { + float pivotPoint = (min + max) / 2.0; // average + unsigned int left = leftBase; unsigned int right = rightBase - 1; //# partition points according to the dimension - while (true) - { - while ( true ) - { + while (true) { + while (true) { point = points[left]; if (point(currentDim) > pivotPoint) break; left++; - } - while ( true ) - { + } + while (true) { point = points[right]; if (point(currentDim) <= pivotPoint) break; right--; - } + } if (left > right) break; @@ -1180,46 +1059,35 @@ void Siox::colorSignatureStage1(CieLab *points, left++; right--; - } + } //# Recurse and create sub-trees - colorSignatureStage1(points, leftBase, left, - recursionDepth + 1, clusterCount, dims); - colorSignatureStage1(points, left, rightBase, - recursionDepth + 1, clusterCount, dims); - } - else - { - //create a leaf + colorSignatureStage1(points, leftBase, left, recursionDepth + 1, clusterCount, dims); + colorSignatureStage1(points, left, rightBase, recursionDepth + 1, clusterCount, dims); + } else { + // create a leaf CieLab newpoint; newpoint.C = rightBase - leftBase; - for (; leftBase < rightBase ; leftBase++) - { + for (; leftBase < rightBase; leftBase++) { newpoint.add(points[leftBase]); - } + } - //printf("clusters:%d\n", *clusters); + // printf("clusters:%d\n", *clusters); if (newpoint.C != 0) newpoint.mul(1.0 / (float)newpoint.C); points[*clusterCount] = newpoint; (*clusterCount)++; - } + } } - - /** * Stage 2 of the color signature work */ -void Siox::colorSignatureStage2(CieLab *points, - unsigned int leftBase, - unsigned int rightBase, - unsigned int recursionDepth, - unsigned int *clusterCount, - const float threshold, +void Siox::colorSignatureStage2(CieLab *points, unsigned int leftBase, unsigned int rightBase, + unsigned int recursionDepth, unsigned int *clusterCount, const float threshold, const unsigned int dims) { unsigned int currentDim = recursionDepth % dims; @@ -1227,38 +1095,35 @@ void Siox::colorSignatureStage2(CieLab *points, float min = point(currentDim); float max = min; - for (unsigned int i = leftBase+ 1; i < rightBase; i++) - { + for (unsigned int i = leftBase + 1; i < rightBase; i++) { point = points[i]; float curval = point(currentDim); - if (curval < min) min = curval; - if (curval > max) max = curval; - } + if (curval < min) + min = curval; + if (curval > max) + max = curval; + } - //Do the Rubner-rule split (sounds like a dance) - if (max - min > limits[currentDim]) - { - float pivotPoint = (min + max) / 2.0; //average - unsigned int left = leftBase; + // Do the Rubner-rule split (sounds like a dance) + if (max - min > limits[currentDim]) { + float pivotPoint = (min + max) / 2.0; // average + unsigned int left = leftBase; unsigned int right = rightBase - 1; //# partition points according to the dimension - while (true) - { - while ( true ) - { + while (true) { + while (true) { point = points[left]; if (point(currentDim) > pivotPoint) break; left++; - } - while ( true ) - { + } + while (true) { point = points[right]; if (point(currentDim) <= pivotPoint) break; right--; - } + } if (left > right) break; @@ -1269,23 +1134,18 @@ void Siox::colorSignatureStage2(CieLab *points, left++; right--; - } + } //# Recurse and create sub-trees - colorSignatureStage2(points, leftBase, left, - recursionDepth + 1, clusterCount, threshold, dims); - colorSignatureStage2(points, left, rightBase, - recursionDepth + 1, clusterCount, threshold, dims); - } - else - { + colorSignatureStage2(points, leftBase, left, recursionDepth + 1, clusterCount, threshold, dims); + colorSignatureStage2(points, left, rightBase, recursionDepth + 1, clusterCount, threshold, dims); + } else { //### Create a leaf unsigned int sum = 0; for (unsigned int i = leftBase; i < rightBase; i++) sum += points[i].C; - if ((float)sum >= threshold) - { + if ((float)sum >= threshold) { float scale = (float)(rightBase - leftBase); CieLab newpoint; @@ -1296,34 +1156,27 @@ void Siox::colorSignatureStage2(CieLab *points, newpoint.mul(1.0 / scale); points[*clusterCount] = newpoint; (*clusterCount)++; - } - } + } + } } - - /** * Main color signature method */ -bool Siox::colorSignature(const std::vector<CieLab> &inputVec, - std::vector<CieLab> &result, - const unsigned int dims) +bool Siox::colorSignature(const std::vector<CieLab> &inputVec, std::vector<CieLab> &result, const unsigned int dims) { - unsigned int length = inputVec.size(); if (length < 1) // no error. just don't do anything return true; - CieLab *input = new CieLab [length]; + CieLab *input = new CieLab[length]; - if (!input) - { + if (!input) { error("Could not allocate buffer for signature"); return false; } - for (unsigned int i=0 ; i < length ; i++) - { + for (unsigned int i = 0; i < length; i++) { input[i] = inputVec[i]; } @@ -1334,8 +1187,7 @@ bool Siox::colorSignature(const std::vector<CieLab> &inputVec, colorSignatureStage2(input, 0, stage1length, 0, &stage2length, length * 0.001, dims); result.clear(); - for (unsigned int i=0 ; i < stage2length ; i++) - { + for (unsigned int i = 0; i < stage2length; i++) { result.push_back(input[i]); } @@ -1344,43 +1196,35 @@ bool Siox::colorSignature(const std::vector<CieLab> &inputVec, return true; } - - /** * */ -void Siox::keepOnlyLargeComponents(float threshold, - double sizeFactorToKeep) +void Siox::keepOnlyLargeComponents(float threshold, double sizeFactorToKeep) { - for (unsigned long idx = 0 ; idx<pixelCount ; idx++) + for (unsigned long idx = 0; idx < pixelCount; idx++) labelField[idx] = -1; int curlabel = 0; - int maxregion= 0; - int maxblob = 0; + int maxregion = 0; + int maxblob = 0; // slow but easy to understand: std::vector<int> labelSizes; - for (unsigned long i=0 ; i<pixelCount ; i++) - { + for (unsigned long i = 0; i < pixelCount; i++) { int regionCount = 0; - if (labelField[i] == -1 && cm[i] >= threshold) - { + if (labelField[i] == -1 && cm[i] >= threshold) { regionCount = depthFirstSearch(i, threshold, curlabel++); labelSizes.push_back(regionCount); - } + } - if (regionCount>maxregion) - { + if (regionCount > maxregion) { maxregion = regionCount; - maxblob = curlabel-1; - } + maxblob = curlabel - 1; } + } - for (unsigned int i=0 ; i<pixelCount ; i++) - { - if (labelField[i] != -1) - { + for (unsigned int i = 0; i < pixelCount; i++) { + if (labelField[i] != -1) { // remove if the component is to small if (labelSizes[labelField[i]] * sizeFactorToKeep < maxregion) cm[i] = CERTAIN_BACKGROUND_CONFIDENCE; @@ -1388,35 +1232,28 @@ void Siox::keepOnlyLargeComponents(float threshold, // add maxblob always to foreground if (labelField[i] == maxblob) cm[i] = CERTAIN_FOREGROUND_CONFIDENCE; - } } - + } } - - -int Siox::depthFirstSearch(int startPos, - float threshold, int curLabel) +int Siox::depthFirstSearch(int startPos, float threshold, int curLabel) { // stores positions of labeled pixels, where the neighbours // should still be checked for processing: - //trace("startPos:%d threshold:%f curLabel:%d", + // trace("startPos:%d threshold:%f curLabel:%d", // startPos, threshold, curLabel); std::vector<int> pixelsToVisit; int componentSize = 0; - if (labelField[startPos]==-1 && cm[startPos]>=threshold) - { + if (labelField[startPos] == -1 && cm[startPos] >= threshold) { labelField[startPos] = curLabel; componentSize++; pixelsToVisit.push_back(startPos); - } - + } - while (!pixelsToVisit.empty()) - { + while (!pixelsToVisit.empty()) { int pos = pixelsToVisit[pixelsToVisit.size() - 1]; pixelsToVisit.erase(pixelsToVisit.end() - 1); unsigned int x = pos % width; @@ -1424,122 +1261,100 @@ int Siox::depthFirstSearch(int startPos, // check all four neighbours int left = pos - 1; - if (((int)x)-1>=0 && labelField[left]==-1 && cm[left]>=threshold) - { - labelField[left]=curLabel; + if (((int)x) - 1 >= 0 && labelField[left] == -1 && cm[left] >= threshold) { + labelField[left] = curLabel; componentSize++; pixelsToVisit.push_back(left); - } + } int right = pos + 1; - if (x+1 < width && labelField[right]==-1 && cm[right]>=threshold) - { - labelField[right]=curLabel; + if (x + 1 < width && labelField[right] == -1 && cm[right] >= threshold) { + labelField[right] = curLabel; componentSize++; pixelsToVisit.push_back(right); - } + } int top = pos - width; - if (((int)y)-1>=0 && labelField[top]==-1 && cm[top]>=threshold) - { - labelField[top]=curLabel; + if (((int)y) - 1 >= 0 && labelField[top] == -1 && cm[top] >= threshold) { + labelField[top] = curLabel; componentSize++; pixelsToVisit.push_back(top); - } + } int bottom = pos + width; - if (y+1 < height && labelField[bottom]==-1 - && cm[bottom]>=threshold) - { - labelField[bottom]=curLabel; + if (y + 1 < height && labelField[bottom] == -1 && cm[bottom] >= threshold) { + labelField[bottom] = curLabel; componentSize++; pixelsToVisit.push_back(bottom); - } - } + } return componentSize; } - - /** * */ void Siox::fillColorRegions() { - for (unsigned long idx = 0 ; idx<pixelCount ; idx++) + for (unsigned long idx = 0; idx < pixelCount; idx++) labelField[idx] = -1; - //int maxRegion=0; // unused now + // int maxRegion=0; // unused now std::vector<int> pixelsToVisit; - for (unsigned long i=0; i<pixelCount; i++) - { // for all pixels - if (labelField[i]!=-1 || cm[i]<UNKNOWN_REGION_CONFIDENCE) - { + for (unsigned long i = 0; i < pixelCount; i++) { // for all pixels + if (labelField[i] != -1 || cm[i] < UNKNOWN_REGION_CONFIDENCE) { continue; // already visited or bg - } + } - unsigned int origColor = image[i]; - unsigned long curLabel = i+1; - labelField[i] = curLabel; - cm[i] = CERTAIN_FOREGROUND_CONFIDENCE; + unsigned int origColor = image[i]; + unsigned long curLabel = i + 1; + labelField[i] = curLabel; + cm[i] = CERTAIN_FOREGROUND_CONFIDENCE; // int componentSize = 1; pixelsToVisit.push_back(i); // depth first search to fill region - while (!pixelsToVisit.empty()) - { + while (!pixelsToVisit.empty()) { int pos = pixelsToVisit[pixelsToVisit.size() - 1]; pixelsToVisit.erase(pixelsToVisit.end() - 1); - unsigned int x=pos % width; - unsigned int y=pos / width; + unsigned int x = pos % width; + unsigned int y = pos / width; // check all four neighbours - int left = pos-1; - if (((int)x)-1 >= 0 && labelField[left] == -1 - && CieLab::diff(image[left], origColor)<1.0) - { - labelField[left]=curLabel; - cm[left]=CERTAIN_FOREGROUND_CONFIDENCE; + int left = pos - 1; + if (((int)x) - 1 >= 0 && labelField[left] == -1 && CieLab::diff(image[left], origColor) < 1.0) { + labelField[left] = curLabel; + cm[left] = CERTAIN_FOREGROUND_CONFIDENCE; // ++componentSize; pixelsToVisit.push_back(left); - } - int right = pos+1; - if (x+1 < width && labelField[right]==-1 - && CieLab::diff(image[right], origColor)<1.0) - { - labelField[right]=curLabel; - cm[right]=CERTAIN_FOREGROUND_CONFIDENCE; + } + int right = pos + 1; + if (x + 1 < width && labelField[right] == -1 && CieLab::diff(image[right], origColor) < 1.0) { + labelField[right] = curLabel; + cm[right] = CERTAIN_FOREGROUND_CONFIDENCE; // ++componentSize; pixelsToVisit.push_back(right); - } + } int top = pos - width; - if (((int)y)-1>=0 && labelField[top]==-1 - && CieLab::diff(image[top], origColor)<1.0) - { - labelField[top]=curLabel; - cm[top]=CERTAIN_FOREGROUND_CONFIDENCE; + if (((int)y) - 1 >= 0 && labelField[top] == -1 && CieLab::diff(image[top], origColor) < 1.0) { + labelField[top] = curLabel; + cm[top] = CERTAIN_FOREGROUND_CONFIDENCE; // ++componentSize; pixelsToVisit.push_back(top); - } + } int bottom = pos + width; - if (y+1 < height && labelField[bottom]==-1 - && CieLab::diff(image[bottom], origColor)<1.0) - { - labelField[bottom]=curLabel; - cm[bottom]=CERTAIN_FOREGROUND_CONFIDENCE; + if (y + 1 < height && labelField[bottom] == -1 && CieLab::diff(image[bottom], origColor) < 1.0) { + labelField[bottom] = curLabel; + cm[bottom] = CERTAIN_FOREGROUND_CONFIDENCE; // ++componentSize; pixelsToVisit.push_back(bottom); - } } - //if (componentSize>maxRegion) { + } + // if (componentSize>maxRegion) { // maxRegion=componentSize; //} - } + } } - - - /** * Applies the morphological dilate operator. * @@ -1547,46 +1362,37 @@ void Siox::fillColorRegions() */ void Siox::dilate(float *cm, int xres, int yres) { - - for (int y=0; y<yres; y++) - { - for (int x=0; x<xres-1; x++) - { - int idx=(y*xres)+x; - if (cm[idx+1]>cm[idx]) - cm[idx]=cm[idx+1]; - } + for (int y = 0; y < yres; y++) { + for (int x = 0; x < xres - 1; x++) { + int idx = (y * xres) + x; + if (cm[idx + 1] > cm[idx]) + cm[idx] = cm[idx + 1]; } + } - for (int y=0; y<yres; y++) - { - for (int x=xres-1; x>=1; x--) - { - int idx=(y*xres)+x; - if (cm[idx-1]>cm[idx]) - cm[idx]=cm[idx-1]; - } + for (int y = 0; y < yres; y++) { + for (int x = xres - 1; x >= 1; x--) { + int idx = (y * xres) + x; + if (cm[idx - 1] > cm[idx]) + cm[idx] = cm[idx - 1]; } + } - for (int y=0; y<yres-1; y++) - { - for (int x=0; x<xres; x++) - { - int idx=(y*xres)+x; - if (cm[((y+1)*xres)+x] > cm[idx]) - cm[idx]=cm[((y+1)*xres)+x]; - } + for (int y = 0; y < yres - 1; y++) { + for (int x = 0; x < xres; x++) { + int idx = (y * xres) + x; + if (cm[((y + 1) * xres) + x] > cm[idx]) + cm[idx] = cm[((y + 1) * xres) + x]; } + } - for (int y=yres-1; y>=1; y--) - { - for (int x=0; x<xres; x++) - { - int idx=(y*xres)+x; - if (cm[((y-1)*xres)+x] > cm[idx]) - cm[idx]=cm[((y-1)*xres)+x]; - } + for (int y = yres - 1; y >= 1; y--) { + for (int x = 0; x < xres; x++) { + int idx = (y * xres) + x; + if (cm[((y - 1) * xres) + x] > cm[idx]) + cm[idx] = cm[((y - 1) * xres) + x]; } + } } /** @@ -1594,62 +1400,53 @@ void Siox::dilate(float *cm, int xres, int yres) */ void Siox::erode(float *cm, int xres, int yres) { - for (int y=0; y<yres; y++) - { - for (int x=0; x<xres-1; x++) - { - int idx=(y*xres)+x; - if (cm[idx+1] < cm[idx]) - cm[idx]=cm[idx+1]; - } + for (int y = 0; y < yres; y++) { + for (int x = 0; x < xres - 1; x++) { + int idx = (y * xres) + x; + if (cm[idx + 1] < cm[idx]) + cm[idx] = cm[idx + 1]; } - for (int y=0; y<yres; y++) - { - for (int x=xres-1; x>=1; x--) - { - int idx=(y*xres)+x; - if (cm[idx-1] < cm[idx]) - cm[idx]=cm[idx-1]; - } + } + for (int y = 0; y < yres; y++) { + for (int x = xres - 1; x >= 1; x--) { + int idx = (y * xres) + x; + if (cm[idx - 1] < cm[idx]) + cm[idx] = cm[idx - 1]; } - for (int y=0; y<yres-1; y++) - { - for (int x=0; x<xres; x++) - { - int idx=(y*xres)+x; - if (cm[((y+1)*xres)+x] < cm[idx]) - cm[idx]=cm[((y+1)*xres)+x]; - } + } + for (int y = 0; y < yres - 1; y++) { + for (int x = 0; x < xres; x++) { + int idx = (y * xres) + x; + if (cm[((y + 1) * xres) + x] < cm[idx]) + cm[idx] = cm[((y + 1) * xres) + x]; } - for (int y=yres-1; y>=1; y--) - { - for (int x=0; x<xres; x++) - { - int idx=(y*xres)+x; - if (cm[((y-1)*xres)+x] < cm[idx]) - cm[idx]=cm[((y-1)*xres)+x]; - } + } + for (int y = yres - 1; y >= 1; y--) { + for (int x = 0; x < xres; x++) { + int idx = (y * xres) + x; + if (cm[((y - 1) * xres) + x] < cm[idx]) + cm[idx] = cm[((y - 1) * xres) + x]; } + } } - - /** * Normalizes the matrix to values to [0..1]. */ void Siox::normalizeMatrix(float *cm, int cmSize) { - float max= -1000000.0f; - for (int i=0; i<cmSize; i++) - if (cm[i] > max) max=cm[i]; + float max = -1000000.0f; + for (int i = 0; i < cmSize; i++) + if (cm[i] > max) + max = cm[i]; - //good to use STL, but max() is not iterative - //float max = *std::max(cm, cm + cmSize); + // good to use STL, but max() is not iterative + // float max = *std::max(cm, cm + cmSize); - if (max<=0.0 || max==1.0) + if (max <= 0.0 || max == 1.0) return; - float alpha=1.00f/max; + float alpha = 1.00f / max; premultiplyMatrix(alpha, cm, cmSize); } @@ -1658,8 +1455,8 @@ void Siox::normalizeMatrix(float *cm, int cmSize) */ void Siox::premultiplyMatrix(float alpha, float *cm, int cmSize) { - for (int i=0; i<cmSize; i++) - cm[i]=alpha*cm[i]; + for (int i = 0; i < cmSize; i++) + cm[i] = alpha * cm[i]; } /** @@ -1668,41 +1465,32 @@ void Siox::premultiplyMatrix(float alpha, float *cm, int cmSize) * In the standard case confidence matrix entries are between 0...1 and * the weight factors sum up to 1. */ -void Siox::smooth(float *cm, int xres, int yres, - float f1, float f2, float f3) +void Siox::smooth(float *cm, int xres, int yres, float f1, float f2, float f3) { - for (int y=0; y<yres; y++) - { - for (int x=0; x<xres-2; x++) - { - int idx=(y*xres)+x; - cm[idx]=f1*cm[idx]+f2*cm[idx+1]+f3*cm[idx+2]; - } + for (int y = 0; y < yres; y++) { + for (int x = 0; x < xres - 2; x++) { + int idx = (y * xres) + x; + cm[idx] = f1 * cm[idx] + f2 * cm[idx + 1] + f3 * cm[idx + 2]; } - for (int y=0; y<yres; y++) - { - for (int x=xres-1; x>=2; x--) - { - int idx=(y*xres)+x; - cm[idx]=f3*cm[idx-2]+f2*cm[idx-1]+f1*cm[idx]; - } + } + for (int y = 0; y < yres; y++) { + for (int x = xres - 1; x >= 2; x--) { + int idx = (y * xres) + x; + cm[idx] = f3 * cm[idx - 2] + f2 * cm[idx - 1] + f1 * cm[idx]; } - for (int y=0; y<yres-2; y++) - { - for (int x=0; x<xres; x++) - { - int idx=(y*xres)+x; - cm[idx]=f1*cm[idx]+f2*cm[((y+1)*xres)+x]+f3*cm[((y+2)*xres)+x]; - } + } + for (int y = 0; y < yres - 2; y++) { + for (int x = 0; x < xres; x++) { + int idx = (y * xres) + x; + cm[idx] = f1 * cm[idx] + f2 * cm[((y + 1) * xres) + x] + f3 * cm[((y + 2) * xres) + x]; } - for (int y=yres-1; y>=2; y--) - { - for (int x=0; x<xres; x++) - { - int idx=(y*xres)+x; - cm[idx]=f3*cm[((y-2)*xres)+x]+f2*cm[((y-1)*xres)+x]+f1*cm[idx]; - } + } + for (int y = yres - 1; y >= 2; y--) { + for (int x = 0; x < xres; x++) { + int idx = (y * xres) + x; + cm[idx] = f3 * cm[((y - 2) * xres) + x] + f2 * cm[((y - 1) * xres) + x] + f1 * cm[idx]; } + } } /** @@ -1710,24 +1498,17 @@ void Siox::smooth(float *cm, int xres, int yres, */ float Siox::sqrEuclidianDist(float *p, int pSize, float *q) { - float sum=0.0; - for (int i=0; i<pSize; i++) - { + float sum = 0.0; + for (int i = 0; i < pSize; i++) { float v = p[i] - q[i]; - sum += v*v; - } + sum += v * v; + } return sum; } - - - - - } // namespace siox } // namespace org //######################################################################## //# E N D O F F I L E //######################################################################## - diff --git a/src/trace/siox.h b/src/trace/siox.h index e6012e9531046220ca0b388a20ee24494e417789..ad9a17797355058fc1c5486fdaff05453df25edc 100644 --- a/src/trace/siox.h +++ b/src/trace/siox.h @@ -26,17 +26,13 @@ #define HAVE_GLIB #ifdef HAVE_GLIB -#include <glib.h> #include <gdk-pixbuf/gdk-pixbuf.h> +#include <glib.h> #endif +namespace org { -namespace org -{ - -namespace siox -{ - +namespace siox { //######################################################################## //# C L A B @@ -48,103 +44,98 @@ namespace siox class CieLab { public: - /** * */ CieLab() - { + { init(); C = 0; L = A = B = 0.0f; - } - + } /** * */ CieLab(unsigned long rgb); - /** * */ CieLab(float lArg, float aArg, float bArg) - { + { init(); C = 0; L = lArg; A = aArg; B = bArg; - } - + } /** * */ CieLab(const CieLab &other) - { + { init(); C = other.C; L = other.L; A = other.A; B = other.B; - } - + } /** * */ CieLab &operator=(const CieLab &other) - { + { init(); C = other.C; L = other.L; A = other.A; B = other.B; return *this; - } + } /** * */ - virtual ~CieLab() - = default; + virtual ~CieLab() = default; /** * Retrieve a CieLab value via index. */ virtual float operator()(unsigned int index) - { - if (index==0) return L; - else if (index==1) return A; - else if (index==2) return B; - else return 0; - } - + { + if (index == 0) + return L; + else if (index == 1) + return A; + else if (index == 2) + return B; + else + return 0; + } /** * */ virtual void add(const CieLab &other) - { + { C += other.C; L += other.L; A += other.A; B += other.B; - } - + } /** * */ virtual void mul(float scale) - { + { L *= scale; A *= scale; B *= scale; - } - + } /** * @@ -183,23 +174,18 @@ public: */ static float diff(unsigned int rgb0, unsigned int rgb1); - unsigned int C; float L; float A; float B; private: - /** * */ void init(); - - }; - //######################################################################## //# S I O X I M A G E //######################################################################## @@ -211,7 +197,6 @@ private: class SioxImage { public: - /** * Create an image with the given width and height */ @@ -249,18 +234,13 @@ public: * Set a pixel at the x,y coordinates to the given value. * If the coordinates are out of range, do nothing. */ - virtual void setPixel(unsigned int x, - unsigned int y, - unsigned int pixval); + virtual void setPixel(unsigned int x, unsigned int y, unsigned int pixval); /** * Set a pixel at the x,y coordinates to the given r, g, b values. * If the coordinates are out of range, do nothing. */ - virtual void setPixel(unsigned int x, unsigned int y, - unsigned int a, - unsigned int r, - unsigned int g, + virtual void setPixel(unsigned int x, unsigned int y, unsigned int a, unsigned int r, unsigned int g, unsigned int b); /** @@ -269,7 +249,6 @@ public: */ virtual unsigned int getPixel(unsigned int x, unsigned int y); - /** * Return the image data buffer */ @@ -279,9 +258,7 @@ public: * Set a confidence value at the x,y coordinates to the given value. * If the coordinates are out of range, do nothing. */ - virtual void setConfidence(unsigned int x, - unsigned int y, - float conf); + virtual void setConfidence(unsigned int x, unsigned int y, float conf); /** * Get a confidence value at the x,y coordinates given. If @@ -309,8 +286,6 @@ public: */ bool writePPM(const std::string &fileName); - - #ifdef HAVE_GLIB /** @@ -328,9 +303,7 @@ public: #endif private: - - SioxImage() - = default; + SioxImage() = default; /** * Assign values to that of another @@ -361,16 +334,12 @@ private: float *cmdata; private: - /** * Error logging */ - void error(const char *fmt, ...) G_GNUC_PRINTF(2,3); - + void error(const char *fmt, ...) G_GNUC_PRINTF(2, 3); }; - - //######################################################################## //# S I O X O B S E R V E R //######################################################################## @@ -383,46 +352,38 @@ class Siox; class SioxObserver { public: - /** * Constructor. Context can point to anything, and is usually * used to point to a C++ object or C state object, to delegate * callback processing to something else. Use NULL to ignore. */ - SioxObserver(void *contextArg) : context(nullptr) - { context = contextArg; } + SioxObserver(void *contextArg) + : context(nullptr) + { + context = contextArg; + } /** * Destructor */ - virtual ~SioxObserver() - = default; + virtual ~SioxObserver() = default; /** * Informs the observer how much has been completed. * Return false if the processing should be aborted. */ - virtual bool progress(float /*percentCompleted*/) - { - return true; - } + virtual bool progress(float /*percentCompleted*/) { return true; } /** * Send an error string to the Observer. Processing will * be halted. */ - virtual void error(const std::string &/*msg*/) - { - } + virtual void error(const std::string & /*msg*/) {} protected: - void *context; - }; - - //######################################################################## //# S I O X //######################################################################## @@ -433,7 +394,6 @@ protected: class Siox { public: - /** * Confidence corresponding to a certain foreground region (equals one). */ @@ -481,11 +441,9 @@ public: * backgroundFillColor is any ARGB color, such as 0xffffff (white) * or 0x000000 (black) */ - virtual SioxImage extractForeground(const SioxImage &originalImage, - unsigned int backgroundFillColor); + virtual SioxImage extractForeground(const SioxImage &originalImage, unsigned int backgroundFillColor); private: - SioxObserver *sioxObserver; /** @@ -528,7 +486,6 @@ private: */ int *labelField; - /** * Our signature limits */ @@ -553,55 +510,42 @@ private: /** * Error logging */ - void error(const char *fmt, ...) G_GNUC_PRINTF(2,3); + void error(const char *fmt, ...) G_GNUC_PRINTF(2, 3); /** * Trace logging */ - void trace(const char *fmt, ...) G_GNUC_PRINTF(2,3); + void trace(const char *fmt, ...) G_GNUC_PRINTF(2, 3); /** * Stage 1 of the color signature work. 'dims' will be either * 2 for grays, or 3 for colors */ - void colorSignatureStage1(CieLab *points, - unsigned int leftBase, - unsigned int rightBase, - unsigned int recursionDepth, - unsigned int *clusters, - const unsigned int dims); + void colorSignatureStage1(CieLab *points, unsigned int leftBase, unsigned int rightBase, + unsigned int recursionDepth, unsigned int *clusters, const unsigned int dims); /** * Stage 2 of the color signature work */ - void colorSignatureStage2(CieLab *points, - unsigned int leftBase, - unsigned int rightBase, - unsigned int recursionDepth, - unsigned int *clusters, - const float threshold, + void colorSignatureStage2(CieLab *points, unsigned int leftBase, unsigned int rightBase, + unsigned int recursionDepth, unsigned int *clusters, const float threshold, const unsigned int dims); /** * Main color signature method */ - bool colorSignature(const std::vector<CieLab> &inputVec, - std::vector<CieLab> &result, - const unsigned int dims); - + bool colorSignature(const std::vector<CieLab> &inputVec, std::vector<CieLab> &result, const unsigned int dims); /** * */ - void keepOnlyLargeComponents(float threshold, - double sizeFactorToKeep); + void keepOnlyLargeComponents(float threshold, double sizeFactorToKeep); /** * */ int depthFirstSearch(int startPos, float threshold, int curLabel); - /** * */ @@ -632,19 +576,14 @@ private: /** * Blurs confidence matrix with a given symmetrically weighted kernel. */ - void smooth(float *cm, int xres, int yres, - float f1, float f2, float f3); + void smooth(float *cm, int xres, int yres, float f1, float f2, float f3); /** * Squared Euclidian distance of p and q. */ float sqrEuclidianDist(float *p, int pSize, float *q); - }; - - - } // namespace siox } // namespace org diff --git a/src/trace/trace.cpp b/src/trace/trace.cpp index 4ffff867fd8745268902e1c31bbf05a335f6bf66..1821066701988c5f5442d091a119c597e3f3fe3d 100644 --- a/src/trace/trace.cpp +++ b/src/trace/trace.cpp @@ -13,59 +13,51 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "trace/potrace/inkscape-potrace.h" - -#include "inkscape.h" -#include "desktop.h" - -#include "document.h" -#include "document-undo.h" -#include "message-stack.h" +#include <2geom/transforms.h> #include <glibmm/i18n.h> #include <gtkmm/main.h> -#include "selection.h" -#include "xml/repr.h" -#include "xml/attribute-record.h" -#include <2geom/transforms.h> -#include "verbs.h" +#include "desktop.h" #include "display/cairo-utils.h" -#include "display/drawing.h" #include "display/drawing-shape.h" - +#include "display/drawing.h" +#include "document-undo.h" +#include "document.h" +#include "imagemap-gdk.h" +#include "inkscape.h" +#include "message-stack.h" +#include "object/sp-image.h" #include "object/sp-item.h" #include "object/sp-shape.h" -#include "object/sp-image.h" - +#include "selection.h" #include "siox.h" -#include "imagemap-gdk.h" +#include "trace/potrace/inkscape-potrace.h" +#include "verbs.h" +#include "xml/attribute-record.h" +#include "xml/repr.h" namespace Inkscape { namespace Trace { SPImage *Tracer::getSelectedSPImage() { - SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if (!desktop) - { + if (!desktop) { g_warning("Trace: No active desktop"); return nullptr; - } + } Inkscape::MessageStack *msgStack = desktop->getMessageStack(); Inkscape::Selection *sel = desktop->getSelection(); - if (!sel) - { + if (!sel) { char *msg = _("Select an <b>image</b> to trace"); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); - //g_warning(msg); + // g_warning(msg); return nullptr; - } + } - if (sioxEnabled) - { + if (sioxEnabled) { SPImage *img = nullptr; auto list = sel->items(); std::vector<SPItem *> items; @@ -76,129 +68,107 @@ SPImage *Tracer::getSelectedSPImage() them as bottom-to-top so that we can discover the image and any SPItems above it */ - for (auto i=list.begin() ; list.end()!=i ; ++i) - { - if (!SP_IS_ITEM(*i)) - { + for (auto i = list.begin(); list.end() != i; ++i) { + if (!SP_IS_ITEM(*i)) { continue; - } + } SPItem *item = *i; items.insert(items.begin(), item); - } + } std::vector<SPItem *>::iterator iter; - for (iter = items.begin() ; iter!= items.end() ; ++iter) - { + for (iter = items.begin(); iter != items.end(); ++iter) { SPItem *item = *iter; - if (SP_IS_IMAGE(item)) + if (SP_IS_IMAGE(item)) { + if (img) // we want only one { - if (img) //we want only one - { char *msg = _("Select only one <b>image</b> to trace"); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); return nullptr; - } - img = SP_IMAGE(item); } - else // if (img) //# items -after- the image in tree (above it in Z) - { - if (SP_IS_SHAPE(item)) - { + img = SP_IMAGE(item); + } else // if (img) //# items -after- the image in tree (above it in Z) + { + if (SP_IS_SHAPE(item)) { SPShape *shape = SP_SHAPE(item); sioxShapes.push_back(shape); - } } } + } - if (!img || sioxShapes.size() < 1) - { + if (!img || sioxShapes.size() < 1) { char *msg = _("Select one image and one or more shapes above it"); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); return nullptr; - } - return img; } - else - //### SIOX not enabled. We want exactly one image selected - { + return img; + } else + //### SIOX not enabled. We want exactly one image selected + { SPItem *item = sel->singleItem(); - if (!item) - { - char *msg = _("Select an <b>image</b> to trace"); //same as above + if (!item) { + char *msg = _("Select an <b>image</b> to trace"); // same as above msgStack->flash(Inkscape::ERROR_MESSAGE, msg); - //g_warning(msg); + // g_warning(msg); return nullptr; - } + } - if (!SP_IS_IMAGE(item)) - { + if (!SP_IS_IMAGE(item)) { char *msg = _("Select an <b>image</b> to trace"); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); - //g_warning(msg); + // g_warning(msg); return nullptr; - } + } SPImage *img = SP_IMAGE(item); return img; - } - + } } - - typedef org::siox::SioxImage SioxImage; typedef org::siox::SioxObserver SioxObserver; typedef org::siox::Siox Siox; - class TraceSioxObserver : public SioxObserver { public: - /** * */ - TraceSioxObserver (void *contextArg) : - SioxObserver(contextArg) - {} + TraceSioxObserver(void *contextArg) + : SioxObserver(contextArg) + {} /** * */ - ~TraceSioxObserver () override - = default; + ~TraceSioxObserver() override = default; /** * Informs the observer how much has been completed. * Return false if the processing should be aborted. */ bool progress(float /*percentCompleted*/) override - { - //Tracer *tracer = (Tracer *)context; + { + // Tracer *tracer = (Tracer *)context; //## Allow the GUI to update - Gtk::Main::iteration(false); //at least once, non-blocking - while( Gtk::Main::events_pending() ) + Gtk::Main::iteration(false); // at least once, non-blocking + while (Gtk::Main::events_pending()) Gtk::Main::iteration(); return true; - } + } /** * Send an error string to the Observer. Processing will * be halted. */ - void error(const std::string &/*msg*/) override - { - //Tracer *tracer = (Tracer *)context; - } - - + void error(const std::string & /*msg*/) override + { + // Tracer *tracer = (Tracer *)context; + } }; - - - - -Glib::RefPtr<Gdk::Pixbuf> Tracer::sioxProcessImage(SPImage *img, Glib::RefPtr<Gdk::Pixbuf>origPixbuf) +Glib::RefPtr<Gdk::Pixbuf> Tracer::sioxProcessImage(SPImage *img, Glib::RefPtr<Gdk::Pixbuf> origPixbuf) { if (!sioxEnabled) return origPixbuf; @@ -206,133 +176,117 @@ Glib::RefPtr<Gdk::Pixbuf> Tracer::sioxProcessImage(SPImage *img, Glib::RefPtr<Gd if (origPixbuf == lastOrigPixbuf) return lastSioxPixbuf; - //g_message("siox: start"); + // g_message("siox: start"); - //Convert from gdk, so a format we know. By design, the pixel - //format in PackedPixelMap is identical to what is needed by SIOX + // Convert from gdk, so a format we know. By design, the pixel + // format in PackedPixelMap is identical to what is needed by SIOX SioxImage simage(origPixbuf->gobj()); SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if (!desktop) - { + if (!desktop) { g_warning("%s", _("Trace: No active desktop")); return Glib::RefPtr<Gdk::Pixbuf>(nullptr); - } + } Inkscape::MessageStack *msgStack = desktop->getMessageStack(); Inkscape::Selection *sel = desktop->getSelection(); - if (!sel) - { + if (!sel) { char *msg = _("Select an <b>image</b> to trace"); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); - //g_warning(msg); + // g_warning(msg); return Glib::RefPtr<Gdk::Pixbuf>(nullptr); - } + } Inkscape::DrawingItem *aImg = img->get_arenaitem(desktop->dkey); - //g_message("img: %d %d %d %d\n", aImg->bbox.x0, aImg->bbox.y0, + // g_message("img: %d %d %d %d\n", aImg->bbox.x0, aImg->bbox.y0, // aImg->bbox.x1, aImg->bbox.y1); - double width = aImg->geometricBounds()->width(); + double width = aImg->geometricBounds()->width(); double height = aImg->geometricBounds()->height(); - double iwidth = simage.getWidth(); + double iwidth = simage.getWidth(); double iheight = simage.getHeight(); - double iwscale = width / iwidth; + double iwscale = width / iwidth; double ihscale = height / iheight; std::vector<Inkscape::DrawingItem *> arenaItems; std::vector<SPShape *>::iterator iter; - for (iter = sioxShapes.begin() ; iter!=sioxShapes.end() ; ++iter) - { + for (iter = sioxShapes.begin(); iter != sioxShapes.end(); ++iter) { SPItem *item = *iter; Inkscape::DrawingItem *aItem = item->get_arenaitem(desktop->dkey); arenaItems.push_back(aItem); - } + } - //g_message("%d arena items\n", arenaItems.size()); + // g_message("%d arena items\n", arenaItems.size()); - //PackedPixelMap *dumpMap = PackedPixelMapCreate( + // PackedPixelMap *dumpMap = PackedPixelMapCreate( // simage.getWidth(), simage.getHeight()); - //g_message("siox: start selection"); + // g_message("siox: start selection"); - for (int row=0 ; row<iheight ; row++) - { - double ypos = aImg->geometricBounds()->top() + ihscale * (double) row; - for (int col=0 ; col<simage.getWidth() ; col++) - { - //Get absolute X,Y position + for (int row = 0; row < iheight; row++) { + double ypos = aImg->geometricBounds()->top() + ihscale * (double)row; + for (int col = 0; col < simage.getWidth(); col++) { + // Get absolute X,Y position double xpos = aImg->geometricBounds()->left() + iwscale * (double)col; Geom::Point point(xpos, ypos); point *= aImg->transform(); - //point *= imgMat; - //point = desktop->doc2dt(point); - //g_message("x:%f y:%f\n", point[0], point[1]); + // point *= imgMat; + // point = desktop->doc2dt(point); + // g_message("x:%f y:%f\n", point[0], point[1]); bool weHaveAHit = false; std::vector<Inkscape::DrawingItem *>::iterator aIter; - for (aIter = arenaItems.begin() ; aIter!=arenaItems.end() ; ++aIter) - { + for (aIter = arenaItems.begin(); aIter != arenaItems.end(); ++aIter) { Inkscape::DrawingItem *arenaItem = *aIter; arenaItem->drawing().update(); - if (arenaItem->pick(point, 1.0f, 1)) - { + if (arenaItem->pick(point, 1.0f, 1)) { weHaveAHit = true; break; - } } + } - if (weHaveAHit) - { - //g_message("hit!\n"); - //dumpMap->setPixelLong(dumpMap, col, row, 0L); - simage.setConfidence(col, row, - Siox::UNKNOWN_REGION_CONFIDENCE); - } - else - { - //g_message("miss!\n"); - //dumpMap->setPixelLong(dumpMap, col, row, + if (weHaveAHit) { + // g_message("hit!\n"); + // dumpMap->setPixelLong(dumpMap, col, row, 0L); + simage.setConfidence(col, row, Siox::UNKNOWN_REGION_CONFIDENCE); + } else { + // g_message("miss!\n"); + // dumpMap->setPixelLong(dumpMap, col, row, // simage.getPixel(col, row)); - simage.setConfidence(col, row, - Siox::CERTAIN_BACKGROUND_CONFIDENCE); - } + simage.setConfidence(col, row, Siox::CERTAIN_BACKGROUND_CONFIDENCE); } } + } - //g_message("siox: selection done"); + // g_message("siox: selection done"); - //dumpMap->writePPM(dumpMap, "siox1.ppm"); - //dumpMap->destroy(dumpMap); + // dumpMap->writePPM(dumpMap, "siox1.ppm"); + // dumpMap->destroy(dumpMap); //## ok we have our pixel buf TraceSioxObserver observer(this); Siox sengine(&observer); SioxImage result = sengine.extractForeground(simage, 0xffffff); - if (!result.isValid()) - { + if (!result.isValid()) { g_warning("%s", _("Invalid SIOX result")); return Glib::RefPtr<Gdk::Pixbuf>(nullptr); - } + } - //result.writePPM("siox2.ppm"); + // result.writePPM("siox2.ppm"); Glib::RefPtr<Gdk::Pixbuf> newPixbuf = Glib::wrap(result.getGdkPixbuf()); - //g_message("siox: done"); + // g_message("siox: done"); lastSioxPixbuf = newPixbuf; return newPixbuf; } - Glib::RefPtr<Gdk::Pixbuf> Tracer::getSelectedImage() { - - SPImage *img = getSelectedSPImage(); if (!img) return Glib::RefPtr<Gdk::Pixbuf>(nullptr); @@ -343,37 +297,24 @@ Glib::RefPtr<Gdk::Pixbuf> Tracer::getSelectedImage() GdkPixbuf *raw_pb = img->pixbuf->getPixbufRaw(false); GdkPixbuf *trace_pb = gdk_pixbuf_copy(raw_pb); if (img->pixbuf->pixelFormat() == Inkscape::Pixbuf::PF_CAIRO) { - convert_pixels_argb32_to_pixbuf( - gdk_pixbuf_get_pixels(trace_pb), - gdk_pixbuf_get_width(trace_pb), - gdk_pixbuf_get_height(trace_pb), - gdk_pixbuf_get_rowstride(trace_pb)); + convert_pixels_argb32_to_pixbuf(gdk_pixbuf_get_pixels(trace_pb), gdk_pixbuf_get_width(trace_pb), + gdk_pixbuf_get_height(trace_pb), gdk_pixbuf_get_rowstride(trace_pb)); } Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(trace_pb, false); - if (sioxEnabled) - { - Glib::RefPtr<Gdk::Pixbuf> sioxPixbuf = - sioxProcessImage(img, pixbuf); - if (!sioxPixbuf) - { + if (sioxEnabled) { + Glib::RefPtr<Gdk::Pixbuf> sioxPixbuf = sioxProcessImage(img, pixbuf); + if (!sioxPixbuf) { return pixbuf; - } - else - { + } else { return sioxPixbuf; - } } - else - { + } else { return pixbuf; - } - + } } - - //######################################################################### //# T R A C E //######################################################################### @@ -383,7 +324,6 @@ void Tracer::enableSiox(bool enable) sioxEnabled = enable; } - void Tracer::traceThread() { //## Remember. NEVER leave this method without setting @@ -394,83 +334,73 @@ void Tracer::traceThread() keepGoing = true; SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if (!desktop) - { + if (!desktop) { g_warning("Trace: No active desktop\n"); return; - } + } Inkscape::MessageStack *msgStack = desktop->getMessageStack(); Inkscape::Selection *selection = desktop->getSelection(); - if (!SP_ACTIVE_DOCUMENT) - { + if (!SP_ACTIVE_DOCUMENT) { char *msg = _("Trace: No active document"); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); - //g_warning(msg); + // g_warning(msg); engine = nullptr; return; - } + } SPDocument *doc = SP_ACTIVE_DOCUMENT; doc->ensureUpToDate(); - SPImage *img = getSelectedSPImage(); - if (!img) - { + if (!img) { engine = nullptr; return; - } + } GdkPixbuf *trace_pb = gdk_pixbuf_copy(img->pixbuf->getPixbufRaw(false)); if (img->pixbuf->pixelFormat() == Inkscape::Pixbuf::PF_CAIRO) { - convert_pixels_argb32_to_pixbuf( - gdk_pixbuf_get_pixels(trace_pb), - gdk_pixbuf_get_width(trace_pb), - gdk_pixbuf_get_height(trace_pb), - gdk_pixbuf_get_rowstride(trace_pb)); + convert_pixels_argb32_to_pixbuf(gdk_pixbuf_get_pixels(trace_pb), gdk_pixbuf_get_width(trace_pb), + gdk_pixbuf_get_height(trace_pb), gdk_pixbuf_get_rowstride(trace_pb)); } Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(trace_pb, false); pixbuf = sioxProcessImage(img, pixbuf); - if (!pixbuf) - { + if (!pixbuf) { char *msg = _("Trace: Image has no bitmap data"); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); - //g_warning(msg); + // g_warning(msg); engine = nullptr; return; - } + } msgStack->flash(Inkscape::NORMAL_MESSAGE, _("Trace: Starting trace...")); desktop->updateCanvasNow(); - std::vector<TracingEngineResult> results = - engine->trace(pixbuf); - //printf("nrPaths:%d\n", results.size()); + std::vector<TracingEngineResult> results = engine->trace(pixbuf); + // printf("nrPaths:%d\n", results.size()); int nrPaths = results.size(); //### Check if we should stop - if (!keepGoing || nrPaths<1) - { + if (!keepGoing || nrPaths < 1) { engine = nullptr; return; - } + } //### Get pointers to the <image> and its parent - //XML Tree being used directly here while it shouldn't be. - Inkscape::XML::Node *imgRepr = SP_OBJECT(img)->getRepr(); - Inkscape::XML::Node *par = imgRepr->parent(); + // XML Tree being used directly here while it shouldn't be. + Inkscape::XML::Node *imgRepr = SP_OBJECT(img)->getRepr(); + Inkscape::XML::Node *par = imgRepr->parent(); //### Get some information for the new transform() - double x = 0.0; - double y = 0.0; - double width = 0.0; + double x = 0.0; + double y = 0.0; + double width = 0.0; double height = 0.0; - double dval = 0.0; + double dval = 0.0; if (sp_repr_get_double(imgRepr, "x", &dval)) x = dval; @@ -482,10 +412,10 @@ void Tracer::traceThread() if (sp_repr_get_double(imgRepr, "height", &dval)) height = dval; - double iwidth = (double)pixbuf->get_width(); + double iwidth = (double)pixbuf->get_width(); double iheight = (double)pixbuf->get_height(); - double iwscale = width / iwidth; + double iwscale = width / iwidth; double ihscale = height / iheight; Geom::Translate trans(x, y); @@ -495,28 +425,25 @@ void Tracer::traceThread() Geom::Affine tf(scal * trans); tf *= img->transform; - //#OK. Now let's start making new nodes Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); Inkscape::XML::Node *groupRepr = nullptr; //# if more than 1, make a <g>roup of <path>s - if (nrPaths > 1) - { + if (nrPaths > 1) { groupRepr = xml_doc->createElement("svg:g"); par->addChild(groupRepr, imgRepr); - } + } long totalNodeCount = 0L; - for (auto result : results) - { + for (auto result : results) { totalNodeCount += result.getNodeCount(); Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path"); pathRepr->setAttributeOrRemoveIfEmpty("style", result.getStyle()); - pathRepr->setAttributeOrRemoveIfEmpty("d", result.getPathData()); + pathRepr->setAttributeOrRemoveIfEmpty("d", result.getPathData()); if (nrPaths > 1) groupRepr->addChild(pathRepr, nullptr); @@ -525,26 +452,23 @@ void Tracer::traceThread() //### Apply the transform from the image to the new shape SPObject *reprobj = doc->getObjectByRepr(pathRepr); - if (reprobj) - { + if (reprobj) { SPItem *newItem = SP_ITEM(reprobj); newItem->doWriteTransform(tf); - } - if (nrPaths == 1) - { + } + if (nrPaths == 1) { selection->clear(); selection->add(pathRepr); - } - Inkscape::GC::release(pathRepr); } + Inkscape::GC::release(pathRepr); + } // If we have a group, then focus on, then forget it - if (nrPaths > 1) - { + if (nrPaths > 1) { selection->clear(); selection->add(groupRepr); Inkscape::GC::release(groupRepr); - } + } //## inform the document, so we can undo DocumentUndo::done(doc, SP_VERB_SELECTION_TRACE, _("Trace bitmap")); @@ -554,60 +478,42 @@ void Tracer::traceThread() char *msg = g_strdup_printf(_("Trace: Done. %ld nodes created"), totalNodeCount); msgStack->flash(Inkscape::NORMAL_MESSAGE, msg); g_free(msg); - } - - - - void Tracer::trace(TracingEngine *theEngine) { - //Check if we are already running + // Check if we are already running if (engine) return; engine = theEngine; #if HAVE_THREADS - //Ensure that thread support is running + // Ensure that thread support is running if (!Glib::thread_supported()) Glib::thread_init(); - //Create our thread and run it - Glib::Thread::create( - sigc::mem_fun(*this, &Tracer::traceThread), false); + // Create our thread and run it + Glib::Thread::create(sigc::mem_fun(*this, &Tracer::traceThread), false); #else traceThread(); #endif - } - - - - void Tracer::abort() { - //## Inform Trace's working thread keepGoing = false; - if (engine) - { + if (engine) { engine->abort(); - } - + } } - - } // namespace Trace } // namespace Inkscape - //######################################################################### //# E N D O F F I L E //######################################################################### - diff --git a/src/trace/trace.h b/src/trace/trace.h index ddc4b961f47f5ab1211b67a3f026b298ad288716..db349fcc7894f160a716499769298ab04acb1cab 100644 --- a/src/trace/trace.h +++ b/src/trace/trace.h @@ -10,10 +10,9 @@ #ifndef SEEN_TRACE_H #define SEEN_TRACE_H -# include <cstring> - -#include <glibmm/refptr.h> +#include <cstring> #include <gdkmm/pixbuf.h> +#include <glibmm/refptr.h> #include <utility> #include <vector> @@ -25,98 +24,80 @@ namespace Inkscape { namespace Trace { - - /** * */ class TracingEngineResult { - public: - /** * */ - TracingEngineResult(std::string theStyle, - std::string thePathData, - long theNodeCount) : - style(std::move(theStyle)), - pathData(std::move(thePathData)), - nodeCount(theNodeCount) - {} + TracingEngineResult(std::string theStyle, std::string thePathData, long theNodeCount) + : style(std::move(theStyle)) + , pathData(std::move(thePathData)) + , nodeCount(theNodeCount) + {} - TracingEngineResult(const TracingEngineResult &other) - { assign(other); } + TracingEngineResult(const TracingEngineResult &other) { assign(other); } virtual TracingEngineResult &operator=(const TracingEngineResult &other) - { assign(other); return *this; } - + { + assign(other); + return *this; + } /** * */ - virtual ~TracingEngineResult() - = default; - + virtual ~TracingEngineResult() = default; /** * */ - std::string getStyle() - { return style; } + std::string getStyle() { return style; } /** * */ - std::string getPathData() - { return pathData; } + std::string getPathData() { return pathData; } /** * */ - long getNodeCount() - { return nodeCount; } + long getNodeCount() { return nodeCount; } private: - void assign(const TracingEngineResult &other) - { + { style = other.style; pathData = other.pathData; nodeCount = other.nodeCount; - } + } std::string style; std::string pathData; long nodeCount; - }; - - /** * A generic interface for plugging different * autotracers into Inkscape. */ class TracingEngine { - - public: - +public: /** * */ - TracingEngine() - = default; + TracingEngine() = default; /** * */ - virtual ~TracingEngine() - = default; + virtual ~TracingEngine() = default; /** * This is the working method of this interface, and all @@ -125,25 +106,14 @@ class TracingEngine * compatible with the d="" attribute * of an SVG <path> element. */ - virtual std::vector<TracingEngineResult> trace( - Glib::RefPtr<Gdk::Pixbuf> /*pixbuf*/) = 0; + virtual std::vector<TracingEngineResult> trace(Glib::RefPtr<Gdk::Pixbuf> /*pixbuf*/) = 0; /** * Abort the thread that is executing getPathDataFromPixbuf() */ virtual void abort() = 0; - - -};//class TracingEngine - - - - - - - - +}; // class TracingEngine /** * This simple class allows a generic wrapper around a given @@ -153,27 +123,20 @@ class TracingEngine */ class Tracer { - public: - - /** * */ Tracer() - { - engine = nullptr; - sioxEnabled = false; - } - - + { + engine = nullptr; + sioxEnabled = false; + } /** * */ - ~Tracer() - = default; - + ~Tracer() = default; /** * A convenience method to allow other software to 'see' the @@ -188,7 +151,6 @@ public: */ void trace(TracingEngine *engine); - /** * Abort the thread that is executing convertImageToPath() */ @@ -199,9 +161,7 @@ public: */ void enableSiox(bool enable); - private: - /** * This is the single path code that is called by its counterpart above. * Threaded method that does single bitmap--->path conversion. @@ -239,20 +199,14 @@ private: Glib::RefPtr<Gdk::Pixbuf> lastSioxPixbuf; Glib::RefPtr<Gdk::Pixbuf> lastOrigPixbuf; -};//class Tracer - - - +}; // class Tracer } // namespace Trace } // namespace Inkscape - - #endif // SEEN_TRACE_H //######################################################################### //# E N D O F F I L E //######################################################################### - diff --git a/src/transf_mat_3x4.cpp b/src/transf_mat_3x4.cpp index 391783b68fa4fe4c0b9f58f2a2089831a3b729b9..2cc9980bb60763f2b14c140d9cbad3b965d88a31 100644 --- a/src/transf_mat_3x4.cpp +++ b/src/transf_mat_3x4.cpp @@ -11,13 +11,16 @@ */ #include "transf_mat_3x4.h" + #include <2geom/affine.h> + #include "svg/stringstream.h" #include "syseq.h" namespace Proj { -TransfMat3x4::TransfMat3x4 () { +TransfMat3x4::TransfMat3x4() +{ for (unsigned int i = 0; i < 3; ++i) { for (unsigned int j = 0; j < 4; ++j) { tmat[i][j] = (i == j ? 1 : 0); // or should we initialize all values with 0? does it matter at all? @@ -25,7 +28,8 @@ TransfMat3x4::TransfMat3x4 () { } } -TransfMat3x4::TransfMat3x4 (Proj::Pt2 vp_x, Proj::Pt2 vp_y, Proj::Pt2 vp_z, Proj::Pt2 origin) { +TransfMat3x4::TransfMat3x4(Proj::Pt2 vp_x, Proj::Pt2 vp_y, Proj::Pt2 vp_z, Proj::Pt2 origin) +{ for (unsigned int i = 0; i < 3; ++i) { tmat[i][0] = vp_x[i]; tmat[i][1] = vp_y[i]; @@ -34,7 +38,8 @@ TransfMat3x4::TransfMat3x4 (Proj::Pt2 vp_x, Proj::Pt2 vp_y, Proj::Pt2 vp_z, Proj } } -TransfMat3x4::TransfMat3x4(TransfMat3x4 const &rhs) { +TransfMat3x4::TransfMat3x4(TransfMat3x4 const &rhs) +{ for (unsigned int i = 0; i < 3; ++i) { for (unsigned int j = 0; j < 4; ++j) { tmat[i][j] = rhs.tmat[i][j]; @@ -42,76 +47,73 @@ TransfMat3x4::TransfMat3x4(TransfMat3x4 const &rhs) { } } -Pt2 -TransfMat3x4::column (Proj::Axis axis) const { - return Proj::Pt2 (tmat[0][axis], tmat[1][axis], tmat[2][axis]); +Pt2 TransfMat3x4::column(Proj::Axis axis) const +{ + return Proj::Pt2(tmat[0][axis], tmat[1][axis], tmat[2][axis]); } - -Pt2 -TransfMat3x4::image (Pt3 const &point) { + +Pt2 TransfMat3x4::image(Pt3 const &point) +{ double x = tmat[0][0] * point[0] + tmat[0][1] * point[1] + tmat[0][2] * point[2] + tmat[0][3] * point[3]; double y = tmat[1][0] * point[0] + tmat[1][1] * point[1] + tmat[1][2] * point[2] + tmat[1][3] * point[3]; double w = tmat[2][0] * point[0] + tmat[2][1] * point[1] + tmat[2][2] * point[2] + tmat[2][3] * point[3]; - return Pt2 (x, y, w); + return Pt2(x, y, w); } -Pt3 -TransfMat3x4::preimage (Geom::Point const &pt, double coord, Proj::Axis axis) { +Pt3 TransfMat3x4::preimage(Geom::Point const &pt, double coord, Proj::Axis axis) +{ const double init_val = std::numeric_limits<double>::quiet_NaN(); - double x[4] = { init_val, init_val, init_val, init_val }; - double v[3] = { pt[Geom::X], pt[Geom::Y], 1.0 }; - int index = (int) axis; + double x[4] = {init_val, init_val, init_val, init_val}; + double v[3] = {pt[Geom::X], pt[Geom::Y], 1.0}; + int index = (int)axis; - SysEq::SolutionKind sol = SysEq::gaussjord_solve<3,4>(tmat, x, v, index, coord, true); + SysEq::SolutionKind sol = SysEq::gaussjord_solve<3, 4>(tmat, x, v, index, coord, true); if (sol != SysEq::unique) { if (sol == SysEq::no_solution) { - g_print ("No solution. Please investigate.\n"); + g_print("No solution. Please investigate.\n"); } else { - g_print ("Infinitely many solutions. Please investigate.\n"); + g_print("Infinitely many solutions. Please investigate.\n"); } } return Pt3(x[0], x[1], x[2], x[3]); } - -void -TransfMat3x4::set_image_pt (Proj::Axis axis, Proj::Pt2 const &pt) { + +void TransfMat3x4::set_image_pt(Proj::Axis axis, Proj::Pt2 const &pt) +{ // FIXME: Do we need to adapt the coordinates in any way or can we just use them as they are? for (int i = 0; i < 3; ++i) { tmat[i][axis] = pt[i]; } } -void -TransfMat3x4::toggle_finite (Proj::Axis axis) { - g_return_if_fail (axis != Proj::W); +void TransfMat3x4::toggle_finite(Proj::Axis axis) +{ + g_return_if_fail(axis != Proj::W); if (has_finite_image(axis)) { - Geom::Point dir (column(axis).affine()); - Geom::Point origin (column(Proj::W).affine()); + Geom::Point dir(column(axis).affine()); + Geom::Point origin(column(Proj::W).affine()); dir -= origin; - set_column (axis, Proj::Pt2(dir[Geom::X], dir[Geom::Y], 0)); + set_column(axis, Proj::Pt2(dir[Geom::X], dir[Geom::Y], 0)); } else { - Proj::Pt2 dir (column(axis)); - Proj::Pt2 origin (column(Proj::W).affine()); + Proj::Pt2 dir(column(axis)); + Proj::Pt2 origin(column(Proj::W).affine()); dir = dir + origin; dir[2] = 1.0; - set_column (axis, dir); + set_column(axis, dir); } } -gchar * -TransfMat3x4::pt_to_str (Proj::Axis axis) { +gchar *TransfMat3x4::pt_to_str(Proj::Axis axis) +{ Inkscape::SVGOStringStream os; - os << tmat[0][axis] << " : " - << tmat[1][axis] << " : " - << tmat[2][axis]; + os << tmat[0][axis] << " : " << tmat[1][axis] << " : " << tmat[2][axis]; return g_strdup(os.str().c_str()); } /* Check for equality (with a small tolerance epsilon) */ -bool -TransfMat3x4::operator==(const TransfMat3x4 &rhs) const +bool TransfMat3x4::operator==(const TransfMat3x4 &rhs) const { // Should we allow a certain tolerance or "normalize" the matrices first? for (int i = 0; i < 3; ++i) { @@ -126,13 +128,13 @@ TransfMat3x4::operator==(const TransfMat3x4 &rhs) const /* Multiply a projective matrix by an affine matrix (by only multiplying the 'affine part' of the * projective matrix) */ -TransfMat3x4 -TransfMat3x4::operator*(Geom::Affine const &A) const { +TransfMat3x4 TransfMat3x4::operator*(Geom::Affine const &A) const +{ TransfMat3x4 ret; for (int j = 0; j < 4; ++j) { - ret.tmat[0][j] = A[0]*tmat[0][j] + A[2]*tmat[1][j] + A[4]*tmat[2][j]; - ret.tmat[1][j] = A[1]*tmat[0][j] + A[3]*tmat[1][j] + A[5]*tmat[2][j]; + ret.tmat[0][j] = A[0] * tmat[0][j] + A[2] * tmat[1][j] + A[4] * tmat[2][j]; + ret.tmat[1][j] = A[1] * tmat[0][j] + A[3] * tmat[1][j] + A[5] * tmat[2][j]; ret.tmat[2][j] = tmat[2][j]; } @@ -141,14 +143,14 @@ TransfMat3x4::operator*(Geom::Affine const &A) const { // FIXME: Shouldn't rather operator* call operator*= for efficiency? (Because in operator*= // there is in principle no need to create a temporary object, which happens in the assignment) -TransfMat3x4 & -TransfMat3x4::operator*=(Geom::Affine const &A) { +TransfMat3x4 &TransfMat3x4::operator*=(Geom::Affine const &A) +{ *this = *this * A; return *this; } -void -TransfMat3x4::copy_tmat(double rhs[3][4]) { +void TransfMat3x4::copy_tmat(double rhs[3][4]) +{ for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) { rhs[i][j] = tmat[i][j]; @@ -156,26 +158,25 @@ TransfMat3x4::copy_tmat(double rhs[3][4]) { } } -void -TransfMat3x4::print () const { - g_print ("Transformation matrix:\n"); - for (const auto & i : tmat) { - g_print (" "); - for (double j : i) { - g_print ("%8.2f ", j); +void TransfMat3x4::print() const +{ + g_print("Transformation matrix:\n"); + for (const auto &i : tmat) { + g_print(" "); + for (double j : i) { + g_print("%8.2f ", j); + } + g_print("\n"); } - g_print ("\n"); - } } -void -TransfMat3x4::normalize_column (Proj::Axis axis) { +void TransfMat3x4::normalize_column(Proj::Axis axis) +{ Proj::Pt2 new_col(column(axis)); new_col.normalize(); set_image_pt(axis, new_col); } - } // namespace Proj /* diff --git a/src/transf_mat_3x4.h b/src/transf_mat_3x4.h index 20096e50dee356922e4c887c3d304890830e1e59..5c0f76375bfac4a5dc991d64873f3dcf383987cb 100644 --- a/src/transf_mat_3x4.h +++ b/src/transf_mat_3x4.h @@ -13,39 +13,43 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "proj_pt.h" #include "axis-manip.h" +#include "proj_pt.h" namespace Proj { -class TransfMat3x4 { +class TransfMat3x4 +{ public: TransfMat3x4(); TransfMat3x4(Pt2 vp_x, Pt2 vp_y, Pt2 vp_z, Pt2 origin); TransfMat3x4(TransfMat3x4 const &rhs); - Pt2 column (Proj::Axis axis) const; - Pt2 image (Pt3 const &point); - Pt3 preimage (Geom::Point const &pt, double coord = 0, Axis = Z); - void set_image_pt (Proj::Axis axis, Proj::Pt2 const &pt); - void toggle_finite (Proj::Axis axis); - double get_infinite_angle (Proj::Axis axis) { + Pt2 column(Proj::Axis axis) const; + Pt2 image(Pt3 const &point); + Pt3 preimage(Geom::Point const &pt, double coord = 0, Axis = Z); + void set_image_pt(Proj::Axis axis, Proj::Pt2 const &pt); + void toggle_finite(Proj::Axis axis); + double get_infinite_angle(Proj::Axis axis) + { if (has_finite_image(axis)) { return Geom::infinity(); } Pt2 vp(column(axis)); - return Geom::atan2(Geom::Point(vp[0], vp[1])) * 180.0/M_PI; + return Geom::atan2(Geom::Point(vp[0], vp[1])) * 180.0 / M_PI; } - void set_infinite_direction (Proj::Axis axis, double angle) { // angle is in degrees - if (tmat[2][axis] != 0) return; // don't set directions for finite VPs + void set_infinite_direction(Proj::Axis axis, double angle) + { // angle is in degrees + if (tmat[2][axis] != 0) + return; // don't set directions for finite VPs - double a = angle * M_PI/180; + double a = angle * M_PI / 180; Geom::Point pt(tmat[0][axis], tmat[1][axis]); double rad = Geom::L2(pt); - set_image_pt(axis, Proj::Pt2(cos (a) * rad, sin (a) * rad, 0.0)); + set_image_pt(axis, Proj::Pt2(cos(a) * rad, sin(a) * rad, 0.0)); } - inline bool has_finite_image (Proj::Axis axis) { return (tmat[2][axis] != 0.0); } + inline bool has_finite_image(Proj::Axis axis) { return (tmat[2][axis] != 0.0); } - char * pt_to_str (Proj::Axis axis); + char *pt_to_str(Proj::Axis axis); bool operator==(const TransfMat3x4 &rhs) const; TransfMat3x4 operator*(Geom::Affine const &A) const; @@ -57,8 +61,9 @@ public: private: // FIXME: Is changing a single column allowed when a projective coordinate system is specified!?!?! - void normalize_column (Proj::Axis axis); - inline void set_column (Proj::Axis axis, Proj::Pt2 pt) { + void normalize_column(Proj::Axis axis); + inline void set_column(Proj::Axis axis, Proj::Pt2 pt) + { tmat[0][axis] = pt[0]; tmat[1][axis] = pt[1]; tmat[2][axis] = pt[2]; diff --git a/src/ui/cache/svg_preview_cache.cpp b/src/ui/cache/svg_preview_cache.cpp index d6a35fba8d638088df81ce19a4231d176653f5ec..707b3050fbcf6ff4c3340e7e8ef604cc8745db1f 100644 --- a/src/ui/cache/svg_preview_cache.cpp +++ b/src/ui/cache/svg_preview_cache.cpp @@ -16,22 +16,19 @@ * */ -#include <gtk/gtk.h> +#include "ui/cache/svg_preview_cache.h" #include <2geom/transforms.h> - -#include "selection.h" -#include "inkscape.h" +#include <gtk/gtk.h> #include "display/cairo-utils.h" #include "display/drawing-context.h" #include "display/drawing-item.h" #include "display/drawing.h" +#include "inkscape.h" +#include "selection.h" - -#include "ui/cache/svg_preview_cache.h" - -GdkPixbuf* render_pixbuf(Inkscape::Drawing &drawing, double scale_factor, Geom::Rect const &dbox, unsigned psize) +GdkPixbuf *render_pixbuf(Inkscape::Drawing &drawing, double scale_factor, Geom::Rect const &dbox, unsigned psize) { drawing.root()->setTransform(Geom::Scale(scale_factor)); @@ -44,21 +41,19 @@ GdkPixbuf* render_pixbuf(Inkscape::Drawing &drawing, double scale_factor, Geom:: int height = ibox.height(); int dx = psize; int dy = psize; - dx = (dx - width)/2; // watch out for size, since 'unsigned'-'signed' can cause problems if the result is negative - dy = (dy - height)/2; + dx = (dx - width) / 2; // watch out for size, since 'unsigned'-'signed' can cause problems if the result is negative + dy = (dy - height) / 2; - Geom::IntRect area = Geom::IntRect::from_xywh( - ibox.min() - Geom::IntPoint(dx, dy), Geom::IntPoint(psize, psize)); + Geom::IntRect area = Geom::IntRect::from_xywh(ibox.min() - Geom::IntPoint(dx, dy), Geom::IntPoint(psize, psize)); /* Render */ - cairo_surface_t *s = cairo_image_surface_create( - CAIRO_FORMAT_ARGB32, psize, psize); + cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, psize, psize); Inkscape::DrawingContext dc(s, area.min()); drawing.render(dc, area, Inkscape::DrawingItem::RENDER_BYPASS_CACHE); cairo_surface_flush(s); - GdkPixbuf* pixbuf = ink_pixbuf_create_from_cairo_surface(s); + GdkPixbuf *pixbuf = ink_pixbuf_create_from_cairo_surface(s); return pixbuf; } @@ -66,46 +61,48 @@ namespace Inkscape { namespace UI { namespace Cache { -SvgPreview::SvgPreview() -= default; +SvgPreview::SvgPreview() = default; SvgPreview::~SvgPreview() { - for (auto & i : _pixmap_cache) - { + for (auto &i : _pixmap_cache) { g_object_unref(i.second); i.second = NULL; } } -Glib::ustring SvgPreview::cache_key(gchar const *uri, gchar const *name, unsigned psize) const { +Glib::ustring SvgPreview::cache_key(gchar const *uri, gchar const *name, unsigned psize) const +{ Glib::ustring key; - key += (uri!=nullptr) ? uri : ""; + key += (uri != nullptr) ? uri : ""; key += ":"; - key += (name!=nullptr) ? name : "unknown"; + key += (name != nullptr) ? name : "unknown"; key += ":"; key += psize; return key; } -GdkPixbuf* SvgPreview::get_preview_from_cache(const Glib::ustring& key) { +GdkPixbuf *SvgPreview::get_preview_from_cache(const Glib::ustring &key) +{ std::map<Glib::ustring, GdkPixbuf *>::iterator found = _pixmap_cache.find(key); - if ( found != _pixmap_cache.end() ) { + if (found != _pixmap_cache.end()) { return found->second; } return nullptr; } -void SvgPreview::set_preview_in_cache(const Glib::ustring& key, GdkPixbuf* px) { +void SvgPreview::set_preview_in_cache(const Glib::ustring &key, GdkPixbuf *px) +{ g_object_ref(px); _pixmap_cache[key] = px; } -GdkPixbuf* SvgPreview::get_preview(const gchar* uri, const gchar* id, Inkscape::DrawingItem */*root*/, - double /*scale_factor*/, unsigned int psize) { +GdkPixbuf *SvgPreview::get_preview(const gchar *uri, const gchar *id, Inkscape::DrawingItem * /*root*/, + double /*scale_factor*/, unsigned int psize) +{ // First try looking up the cached preview in the cache map Glib::ustring key = cache_key(uri, id, psize); - GdkPixbuf* px = get_preview_from_cache(key); + GdkPixbuf *px = get_preview_from_cache(key); if (px == nullptr) { /* @@ -116,19 +113,19 @@ GdkPixbuf* SvgPreview::get_preview(const gchar* uri, const gchar* id, Inkscape:: return px; } -void SvgPreview::remove_preview_from_cache(const Glib::ustring& key) { +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() ) { + if (found != _pixmap_cache.end()) { g_object_unref(found->second); found->second = NULL; _pixmap_cache.erase(key); } } - -} -} -} +} // namespace Cache +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/cache/svg_preview_cache.h b/src/ui/cache/svg_preview_cache.h index 19c454894dbb9b5d367fc4685df82a92717ad504..d8eac9c727d736e45a9f8d16b871d9212c54c730 100644 --- a/src/ui/cache/svg_preview_cache.h +++ b/src/ui/cache/svg_preview_cache.h @@ -10,10 +10,10 @@ #ifndef SEEN_INKSCAPE_UI_SVG_PREVIEW_CACHE_H #define SEEN_INKSCAPE_UI_SVG_PREVIEW_CACHE_H -#include <map> +#include <2geom/rect.h> #include <gdk-pixbuf/gdk-pixbuf.h> #include <glibmm/ustring.h> -#include <2geom/rect.h> +#include <map> namespace Inkscape { @@ -22,34 +22,33 @@ class DrawingItem; } // namespace Inkscape - -GdkPixbuf* render_pixbuf(Inkscape::Drawing &drawing, double scale_factor, const Geom::Rect& dbox, unsigned psize); +GdkPixbuf *render_pixbuf(Inkscape::Drawing &drawing, double scale_factor, const Geom::Rect &dbox, unsigned psize); namespace Inkscape { namespace UI { namespace Cache { -class SvgPreview { - protected: - std::map<Glib::ustring, GdkPixbuf*> _pixmap_cache; +class SvgPreview +{ +protected: + std::map<Glib::ustring, GdkPixbuf *> _pixmap_cache; - public: +public: SvgPreview(); ~SvgPreview(); Glib::ustring cache_key(gchar const *uri, gchar const *name, unsigned psize) const; - 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); + 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 }; // namespace UI }; // namespace Inkscape - - #endif // SEEN_INKSCAPE_UI_SVG_PREVIEW_CACHE_H /* Local Variables: @@ -61,5 +60,3 @@ class SvgPreview { End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - - diff --git a/src/ui/clipboard.cpp b/src/ui/clipboard.cpp index bd541c0d435b994ff734b38c47dffeae3feb3187..4f0638eb942804446c6fac792436b0aff7954192 100644 --- a/src/ui/clipboard.cpp +++ b/src/ui/clipboard.cpp @@ -14,48 +14,39 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/clipboard.h" + #include <giomm/application.h> #include <gtkmm/clipboard.h> -#include "ui/clipboard.h" // TODO: reduce header bloat if possible -#include "file.h" // for file_import, used in _pasteImage -#include <glibmm/i18n.h> +#include <2geom/transforms.h> #include <glib/gstdio.h> // for g_file_set_contents etc., used in _onGet and paste -#include "inkgc/gc-core.h" -#include "xml/repr.h" -#include "xml/sp-css-attr.h" -#include "inkscape.h" -#include "desktop.h" +#include <glibmm/i18n.h> +#include "context-fns.h" #include "desktop-style.h" // for sp_desktop_set_style, used in _pasteStyle +#include "desktop.h" #include "document.h" -#include "message-stack.h" -#include "context-fns.h" -#include "ui/tools/dropper-tool.h" // used in copy() #include "extension/db.h" // extension database +#include "extension/find_extension_by_mime.h" #include "extension/input.h" #include "extension/output.h" -#include "selection-chemistry.h" -#include <2geom/transforms.h> +#include "file.h" // for file_import, used in _pasteImage #include "gradient-drag.h" -#include "live_effects/lpeobject.h" +#include "helper/png-write.h" +#include "inkgc/gc-core.h" +#include "inkscape.h" #include "live_effects/lpeobject-reference.h" +#include "live_effects/lpeobject.h" #include "live_effects/parameter/path.h" -#include "ui/tools/text-tool.h" -#include "text-editing.h" -#include "text-chemistry.h" -#include "ui/tools-switch.h" -#include "path-chemistry.h" -#include "util/units.h" -#include "helper/png-write.h" -#include "extension/find_extension_by_mime.h" - +#include "message-stack.h" #include "object/box3d.h" #include "object/persp3d.h" #include "object/sp-clippath.h" #include "object/sp-defs.h" +#include "object/sp-flowtext.h" #include "object/sp-gradient-reference.h" #include "object/sp-hatch.h" #include "object/sp-item-transform.h" @@ -67,14 +58,22 @@ #include "object/sp-rect.h" #include "object/sp-root.h" #include "object/sp-shape.h" -#include "object/sp-flowtext.h" #include "object/sp-textpath.h" #include "object/sp-use.h" +#include "path-chemistry.h" +#include "selection-chemistry.h" #include "style.h" - -#include "svg/svg.h" // for sp_svg_transform_write, used in _copySelection #include "svg/css-ostringstream.h" // used in copy #include "svg/svg-color.h" +#include "svg/svg.h" // for sp_svg_transform_write, used in _copySelection +#include "text-chemistry.h" +#include "text-editing.h" +#include "ui/tools-switch.h" +#include "ui/tools/dropper-tool.h" // used in copy() +#include "ui/tools/text-tool.h" +#include "util/units.h" +#include "xml/repr.h" +#include "xml/sp-css-attr.h" /// Made up mimetype to represent Gdk::Pixbuf clipboard contents. #define CLIPBOARD_GDK_PIXBUF_TARGET "image/x-gdk-pixbuf" @@ -88,22 +87,23 @@ namespace Inkscape { namespace UI { - /** * Default implementation of the clipboard manager. */ -class ClipboardManagerImpl : public ClipboardManager { +class ClipboardManagerImpl : public ClipboardManager +{ public: void copy(ObjectSet *set) override; void copyPathParameter(Inkscape::LivePathEffect::PathParam *) override; - void copySymbol(Inkscape::XML::Node* symbol, gchar const* style, bool user_symbol) override; + void copySymbol(Inkscape::XML::Node *symbol, gchar const *style, bool user_symbol) override; bool paste(SPDesktop *desktop, bool in_place) override; bool pasteStyle(ObjectSet *set) override; bool pasteSize(ObjectSet *set, bool separately, bool apply_x, bool apply_y) override; bool pastePathEffect(ObjectSet *set) override; - Glib::ustring getPathParameter(SPDesktop* desktop) override; + Glib::ustring getPathParameter(SPDesktop *desktop) override; Glib::ustring getShapeOrTextObjectId(SPDesktop *desktop) override; - std::vector<Glib::ustring> getElementsOfType(SPDesktop *desktop, gchar const* type = "*", gint maxdepth = -1) override; + std::vector<Glib::ustring> getElementsOfType(SPDesktop *desktop, gchar const *type = "*", + gint maxdepth = -1) override; Glib::ustring getFirstObjectID() override; ClipboardManagerImpl(); @@ -132,7 +132,8 @@ private: void _createInternalClipboard(); void _discardInternalClipboard(); Inkscape::XML::Node *_createClipNode(); - Geom::Scale _getScale(SPDesktop *desktop, Geom::Point const &min, Geom::Point const &max, Geom::Rect const &obj_rect, bool apply_x, bool apply_y); + Geom::Scale _getScale(SPDesktop *desktop, Geom::Point const &min, Geom::Point const &max, + Geom::Rect const &obj_rect, bool apply_x, bool apply_y); Glib::ustring _getBestTarget(); void _setClipboardTargets(); void _setClipboardColor(guint32); @@ -140,34 +141,32 @@ private: // private properites std::unique_ptr<SPDocument> _clipboardSPDoc; ///< Document that stores the clipboard until someone requests it - Inkscape::XML::Node *_defs; ///< Reference to the clipboard document's defs node - Inkscape::XML::Node *_root; ///< Reference to the clipboard's root node - Inkscape::XML::Node *_clipnode; ///< The node that holds extra information - Inkscape::XML::Document *_doc; ///< Reference to the clipboard's Inkscape::XML::Document - std::set<SPItem*> cloned_elements; - std::vector<SPCSSAttr*> te_selected_style; + Inkscape::XML::Node *_defs; ///< Reference to the clipboard document's defs node + Inkscape::XML::Node *_root; ///< Reference to the clipboard's root node + Inkscape::XML::Node *_clipnode; ///< The node that holds extra information + Inkscape::XML::Document *_doc; ///< Reference to the clipboard's Inkscape::XML::Document + std::set<SPItem *> cloned_elements; + std::vector<SPCSSAttr *> te_selected_style; std::vector<unsigned> te_selected_style_positions; int nr_blocks = 0; unsigned copied_style_length = 0; - // we need a way to copy plain text AND remember its style; // the standard _clipnode is only available in an SVG tree, hence this special storage SPCSSAttr *_text_style; ///< Style copied along with plain text fragment - Glib::RefPtr<Gtk::Clipboard> _clipboard; ///< Handle to the system wide clipboard - for convenience + Glib::RefPtr<Gtk::Clipboard> _clipboard; ///< Handle to the system wide clipboard - for convenience std::list<Glib::ustring> _preferred_targets; ///< List of supported clipboard targets }; - ClipboardManagerImpl::ClipboardManagerImpl() - : _clipboardSPDoc(nullptr), - _defs(nullptr), - _root(nullptr), - _clipnode(nullptr), - _doc(nullptr), - _text_style(nullptr), - _clipboard( Gtk::Clipboard::get() ) + : _clipboardSPDoc(nullptr) + , _defs(nullptr) + , _root(nullptr) + , _clipnode(nullptr) + , _doc(nullptr) + , _text_style(nullptr) + , _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 @@ -192,16 +191,14 @@ ClipboardManagerImpl::ClipboardManagerImpl() } } - ClipboardManagerImpl::~ClipboardManagerImpl() = default; - /** * Copy selection contents to the clipboard. */ void ClipboardManagerImpl::copy(ObjectSet *set) { - if ( set->desktop() ) { + if (set->desktop()) { SPDesktop *desktop = set->desktop(); // Special case for when the gradient dragger is active - copies gradient color @@ -259,31 +256,30 @@ void ClipboardManagerImpl::copy(ObjectSet *set) return; } } - if (set->isEmpty()) { // check whether something is selected + if (set->isEmpty()) { // check whether something is selected _userWarn(set->desktop(), _("Nothing was copied.")); return; } _discardInternalClipboard(); - _createInternalClipboard(); // construct a new clipboard document - _copySelection(set); // copy all items in the selection to the internal clipboard + _createInternalClipboard(); // construct a new clipboard document + _copySelection(set); // copy all items in the selection to the internal clipboard fit_canvas_to_drawing(_clipboardSPDoc.get()); _setClipboardTargets(); } - /** * Copy a Live Path Effect path parameter to the clipboard. * @param pp The path parameter to store in the clipboard. */ void ClipboardManagerImpl::copyPathParameter(Inkscape::LivePathEffect::PathParam *pp) { - if ( pp == nullptr ) { + if (pp == nullptr) { return; } - gchar *svgd = sp_svg_write_path( pp->get_pathvector() ); - if ( svgd == nullptr || *svgd == '\0' ) { + gchar *svgd = sp_svg_write_path(pp->get_pathvector()); + if (svgd == nullptr || *svgd == '\0') { return; } @@ -304,10 +300,10 @@ 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, bool user_symbol) +void ClipboardManagerImpl::copySymbol(Inkscape::XML::Node *symbol, gchar const *style, bool user_symbol) { - //std::cout << "ClipboardManagerImpl::copySymbol" << std::endl; - if ( symbol == nullptr ) { + // std::cout << "ClipboardManagerImpl::copySymbol" << std::endl; + if (symbol == nullptr) { return; } @@ -321,7 +317,7 @@ void ClipboardManagerImpl::copySymbol(Inkscape::XML::Node* symbol, gchar const* Glib::ustring symbol_name = repr->attribute("id"); symbol_name += "_inkscape_duplicate"; - repr->setAttribute("id", symbol_name); + repr->setAttribute("id", symbol_name); _defs->appendChild(repr); Glib::ustring id("#"); @@ -341,19 +337,19 @@ void ClipboardManagerImpl::copySymbol(Inkscape::XML::Node* symbol, gchar const* } Inkscape::XML::Node *use = _doc->createElement("svg:use"); - use->setAttribute("xlink:href", id ); + use->setAttribute("xlink:href", id); // Set a default style in <use> rather than <symbol> so it can be changed. - use->setAttribute("style", style ); + use->setAttribute("style", style); if (!Geom::are_near(scale_units, 1.0, Geom::EPSILON)) { - gchar *transform_str = sp_svg_transform_write(Geom::Scale(1.0/scale_units)); + gchar *transform_str = sp_svg_transform_write(Geom::Scale(1.0 / scale_units)); use->setAttribute("transform", transform_str); g_free(transform_str); } _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)); + 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.get()); _setClipboardTargets(); @@ -366,10 +362,10 @@ void ClipboardManagerImpl::copySymbol(Inkscape::XML::Node* symbol, gchar const* bool ClipboardManagerImpl::paste(SPDesktop *desktop, bool in_place) { // do any checking whether we really are able to paste before requesting the contents - if ( desktop == nullptr ) { + if (desktop == nullptr) { return false; } - if ( Inkscape::have_viable_layer(desktop, desktop->getMessageStack()) == false ) { + if (Inkscape::have_viable_layer(desktop, desktop->getMessageStack()) == false) { return false; } @@ -380,17 +376,17 @@ bool ClipboardManagerImpl::paste(SPDesktop *desktop, bool in_place) // TODO: Handle x-special/gnome-copied-files and text/uri-list to support pasting files // if there is an image on the clipboard, paste it - if ( target == CLIPBOARD_GDK_PIXBUF_TARGET ) { + if (target == CLIPBOARD_GDK_PIXBUF_TARGET) { return _pasteImage(desktop->doc()); } // if there's only text, paste it into a selected text object or create a new one - if ( target == CLIPBOARD_TEXT_TARGET ) { + if (target == CLIPBOARD_TEXT_TARGET) { return _pasteText(desktop); } // otherwise, use the import extensions auto tempdoc = _retrieveClipboard(target); - if ( tempdoc == nullptr ) { + if (tempdoc == nullptr) { _userWarn(desktop, _("Nothing on the clipboard.")); return false; } @@ -406,7 +402,7 @@ bool ClipboardManagerImpl::paste(SPDesktop *desktop, bool in_place) Glib::ustring ClipboardManagerImpl::getFirstObjectID() { auto tempdoc = _retrieveClipboard("image/x-inkscape-svg"); - if ( tempdoc == nullptr ) { + if (tempdoc == nullptr) { return {}; } @@ -417,15 +413,9 @@ Glib::ustring ClipboardManagerImpl::getFirstObjectID() } Inkscape::XML::Node *ch = root->firstChild(); - while (ch != nullptr && - strcmp(ch->name(), "svg:g") && - strcmp(ch->name(), "svg:path") && - strcmp(ch->name(), "svg:use") && - strcmp(ch->name(), "svg:text") && - strcmp(ch->name(), "svg:image") && - strcmp(ch->name(), "svg:rect") && - strcmp(ch->name(), "svg:ellipse") - ) { + while (ch != nullptr && strcmp(ch->name(), "svg:g") && strcmp(ch->name(), "svg:path") && + strcmp(ch->name(), "svg:use") && strcmp(ch->name(), "svg:text") && strcmp(ch->name(), "svg:image") && + strcmp(ch->name(), "svg:rect") && strcmp(ch->name(), "svg:ellipse")) { ch = ch->next(); } @@ -439,7 +429,6 @@ Glib::ustring ClipboardManagerImpl::getFirstObjectID() return {}; } - /** * Implements the Paste Style action. */ @@ -456,7 +445,7 @@ bool ClipboardManagerImpl::pasteStyle(ObjectSet *set) } auto tempdoc = _retrieveClipboard("image/x-inkscape-svg"); - if ( tempdoc == nullptr ) { + if (tempdoc == nullptr) { // no document, but we can try _text_style if (_text_style) { sp_desktop_set_style(set, set->desktop(), _text_style); @@ -477,15 +466,13 @@ bool ClipboardManagerImpl::pasteStyle(ObjectSet *set) SPCSSAttr *style = sp_repr_css_attr(clipnode, "style"); sp_desktop_set_style(set, set->desktop(), style); pasted = true; - } - else { + } else { _userWarn(set->desktop(), _("No style on the clipboard.")); } return pasted; } - /** * Resize the selection or each object in the selection to match the clipboard's size. * @param separately Whether to scale each object in the selection separately @@ -498,20 +485,20 @@ bool ClipboardManagerImpl::pasteSize(ObjectSet *set, bool separately, bool apply return false; // pointless parameters } -/* if ( desktop == NULL ) { - return false; - } - Inkscape::Selection *selection = desktop->getSelection();*/ + /* if ( desktop == NULL ) { + return false; + } + Inkscape::Selection *selection = desktop->getSelection();*/ if (set->isEmpty()) { - if(set->desktop()) + if (set->desktop()) _userWarn(set->desktop(), _("Select <b>object(s)</b> to paste size to.")); return false; } // FIXME: actually, this should accept arbitrary documents auto tempdoc = _retrieveClipboard("image/x-inkscape-svg"); - if ( tempdoc == nullptr ) { - if(set->desktop()) + if (tempdoc == nullptr) { + if (set->desktop()) _userWarn(set->desktop(), _("No size on the clipboard.")); return false; } @@ -527,12 +514,12 @@ bool ClipboardManagerImpl::pasteSize(ObjectSet *set, bool separately, bool apply // resize each object in the selection if (separately) { - auto itemlist= set->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = set->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (item) { Geom::OptRect obj_size = item->desktopVisualBounds(); - if ( obj_size ) { + if (obj_size) { item->scale_rel(_getScale(set->desktop(), min, max, *obj_size, apply_x, apply_y)); } } else { @@ -543,9 +530,9 @@ bool ClipboardManagerImpl::pasteSize(ObjectSet *set, bool separately, bool apply // resize the selection as a whole else { Geom::OptRect sel_size = set->visualBounds(); - if ( sel_size ) { + if (sel_size) { set->setScaleRelative(sel_size->midpoint(), - _getScale(set->desktop(), min, max, *sel_size, apply_x, apply_y)); + _getScale(set->desktop(), min, max, *sel_size, apply_x, apply_y)); } } pasted = true; @@ -553,7 +540,6 @@ bool ClipboardManagerImpl::pasteSize(ObjectSet *set, bool separately, bool apply return pasted; } - /** * Applies a path effect from the clipboard to the selected path. */ @@ -562,28 +548,28 @@ bool ClipboardManagerImpl::pastePathEffect(ObjectSet *set) /** @todo FIXME: pastePathEffect crashes when moving the path with the applied effect, segfaulting in fork_private_if_necessary(). */ - if ( set->desktop() == nullptr ) { + if (set->desktop() == nullptr) { return false; } - //Inkscape::Selection *selection = desktop->getSelection(); + // Inkscape::Selection *selection = desktop->getSelection(); if (!set || set->isEmpty()) { _userWarn(set->desktop(), _("Select <b>object(s)</b> to paste live path effect to.")); return false; } auto tempdoc = _retrieveClipboard("image/x-inkscape-svg"); - if ( tempdoc ) { + if (tempdoc) { Inkscape::XML::Node *root = tempdoc->getReprRoot(); Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1); - if ( clipnode ) { + if (clipnode) { gchar const *effectstack = clipnode->attribute("inkscape:path-effect"); - if ( effectstack ) { + if (effectstack) { set->document()->importDefs(tempdoc.get()); // make sure all selected items are converted to paths first (i.e. rectangles) set->toLPEItems(); - auto itemlist= set->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = set->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; _applyPathEffect(item, effectstack); } @@ -598,21 +584,20 @@ bool ClipboardManagerImpl::pastePathEffect(ObjectSet *set) return false; } - /** * Get LPE path data from the clipboard. * @return The retrieved path data (contents of the d attribute), or "" if no path was found */ -Glib::ustring ClipboardManagerImpl::getPathParameter(SPDesktop* desktop) +Glib::ustring ClipboardManagerImpl::getPathParameter(SPDesktop *desktop) { auto tempdoc = _retrieveClipboard(); // any target will do here - if ( tempdoc == nullptr ) { + if (tempdoc == nullptr) { _userWarn(desktop, _("Nothing on the clipboard.")); return ""; } Inkscape::XML::Node *root = tempdoc->getReprRoot(); Inkscape::XML::Node *path = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth - if ( path == nullptr ) { + if (path == nullptr) { _userWarn(desktop, _("Clipboard does not contain a path.")); return ""; } @@ -620,7 +605,6 @@ Glib::ustring ClipboardManagerImpl::getPathParameter(SPDesktop* desktop) return svgd ? svgd : ""; } - /** * Get object id of a shape or text item from the clipboard. * @return The retrieved id string (contents of the id attribute), or "" if no shape or text item was found. @@ -634,7 +618,7 @@ Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId(SPDesktop *desktop) // clip path or mask, not the original path! auto tempdoc = _retrieveClipboard(); // any target will do here - if ( tempdoc == nullptr ) { + if (tempdoc == nullptr) { _userWarn(desktop, _("Nothing on the clipboard.")); return ""; } @@ -644,7 +628,7 @@ Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId(SPDesktop *desktop) root->removeChild(tempdoc->getDefs()->getRepr()); Inkscape::XML::Node *repr = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth - if ( repr == nullptr ) { + if (repr == nullptr) { repr = sp_repr_lookup_name(root, "svg:text", -1); } if (repr == nullptr) { @@ -657,8 +641,7 @@ Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId(SPDesktop *desktop) repr = sp_repr_lookup_name(root, "svg:circle", -1); } - - if ( repr == nullptr ) { + if (repr == nullptr) { _userWarn(desktop, _("Clipboard does not contain a path.")); return ""; } @@ -671,11 +654,11 @@ Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId(SPDesktop *desktop) * @return A vector containing all IDs or empty if no shape or text item was found. * type. Set to "*" to retrieve all elements of the types vector inside, feel free to populate more */ -std::vector<Glib::ustring> ClipboardManagerImpl::getElementsOfType(SPDesktop *desktop, gchar const* type, gint maxdepth) +std::vector<Glib::ustring> ClipboardManagerImpl::getElementsOfType(SPDesktop *desktop, gchar const *type, gint maxdepth) { std::vector<Glib::ustring> result; auto tempdoc = _retrieveClipboard(); // any target will do here - if ( tempdoc == nullptr ) { + if (tempdoc == nullptr) { _userWarn(desktop, _("Nothing on the clipboard.")); return result; } @@ -684,19 +667,20 @@ std::vector<Glib::ustring> ClipboardManagerImpl::getElementsOfType(SPDesktop *de // 1293979: strip out the defs of the document root->removeChild(tempdoc->getDefs()->getRepr()); std::vector<Inkscape::XML::Node const *> reprs; - if (strcmp(type, "*") == 0){ - //TODO:Fill vector with all possible elements + if (strcmp(type, "*") == 0) { + // TODO:Fill vector with all possible elements std::vector<Glib::ustring> types; - types.push_back((Glib::ustring)"svg:path"); - types.push_back((Glib::ustring)"svg:circle"); - types.push_back((Glib::ustring)"svg:rect"); - types.push_back((Glib::ustring)"svg:ellipse"); - types.push_back((Glib::ustring)"svg:text"); - types.push_back((Glib::ustring)"svg:use"); - types.push_back((Glib::ustring)"svg:g"); - types.push_back((Glib::ustring)"svg:image"); + types.push_back((Glib::ustring) "svg:path"); + types.push_back((Glib::ustring) "svg:circle"); + types.push_back((Glib::ustring) "svg:rect"); + types.push_back((Glib::ustring) "svg:ellipse"); + types.push_back((Glib::ustring) "svg:text"); + types.push_back((Glib::ustring) "svg:use"); + types.push_back((Glib::ustring) "svg:g"); + types.push_back((Glib::ustring) "svg:image"); for (auto type_elem : types) { - std::vector<Inkscape::XML::Node const *> reprs_found = sp_repr_lookup_name_many(root, type_elem.c_str(), maxdepth); // unlimited search depth + std::vector<Inkscape::XML::Node const *> reprs_found = + sp_repr_lookup_name_many(root, type_elem.c_str(), maxdepth); // unlimited search depth reprs.insert(reprs.end(), reprs_found.begin(), reprs_found.end()); } } else { @@ -705,8 +689,9 @@ std::vector<Glib::ustring> ClipboardManagerImpl::getElementsOfType(SPDesktop *de for (auto node : reprs) { result.emplace_back(node->attribute("id")); } - if ( result.empty() ) { - _userWarn(desktop, (Glib::ustring::compose(_("Clipboard does not contain any objects of type \"%1\"."), type)).c_str()); + if (result.empty()) { + _userWarn(desktop, + (Glib::ustring::compose(_("Clipboard does not contain any objects of type \"%1\"."), type)).c_str()); return result; } return result; @@ -718,9 +703,9 @@ std::vector<Glib::ustring> ClipboardManagerImpl::getElementsOfType(SPDesktop *de void ClipboardManagerImpl::_copySelection(ObjectSet *selection) { // copy the defs used by all items - auto itemlist= selection->items(); + auto itemlist = selection->items(); cloned_elements.clear(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (item) { _copyUsedDefs(item); @@ -730,35 +715,34 @@ void ClipboardManagerImpl::_copySelection(ObjectSet *selection) } // copy the representation of the items - std::vector<SPObject*> sorted_items(itemlist.begin(), itemlist.end()); + std::vector<SPObject *> sorted_items(itemlist.begin(), itemlist.end()); { // Get external text references and add them to sorted_items - auto ext_refs = text_categorize_refs(selection->document(), - sorted_items.begin(), sorted_items.end(), - TEXT_REF_EXTERNAL); + auto ext_refs = + text_categorize_refs(selection->document(), sorted_items.begin(), sorted_items.end(), TEXT_REF_EXTERNAL); for (auto const &ext_ref : ext_refs) { sorted_items.push_back(selection->document()->getObjectById(ext_ref.first)); } } sort(sorted_items.begin(), sorted_items.end(), sp_object_compare_position_bool); - //remove already copied elements from cloned_elements - std::vector<SPItem*>tr; - for(auto cloned_element : cloned_elements){ - if(std::find(sorted_items.begin(),sorted_items.end(),cloned_element)!=sorted_items.end()) + // remove already copied elements from cloned_elements + std::vector<SPItem *> tr; + for (auto cloned_element : cloned_elements) { + if (std::find(sorted_items.begin(), sorted_items.end(), cloned_element) != sorted_items.end()) tr.push_back(cloned_element); } - for(auto & it : tr){ + for (auto &it : tr) { cloned_elements.erase(it); } - sorted_items.insert(sorted_items.end(),cloned_elements.begin(),cloned_elements.end()); - for(auto sorted_item : sorted_items){ - SPItem *item = dynamic_cast<SPItem*>(sorted_item); + sorted_items.insert(sorted_items.end(), cloned_elements.begin(), cloned_elements.end()); + for (auto sorted_item : sorted_items) { + SPItem *item = dynamic_cast<SPItem *>(sorted_item); if (item) { Inkscape::XML::Node *obj = item->getRepr(); Inkscape::XML::Node *obj_copy; - if(cloned_elements.find(item)==cloned_elements.end()) + if (cloned_elements.find(item) == cloned_elements.end()) obj_copy = _copyNode(obj, _doc, _root); else obj_copy = _copyNode(obj, _doc, _clipnode); @@ -773,19 +757,26 @@ void ClipboardManagerImpl::_copySelection(ObjectSet *selection) sp_repr_css_set(obj_copy, css, "style"); sp_repr_css_attr_unref(css); - Geom::Affine transform=item->i2doc_affine(); + Geom::Affine transform = item->i2doc_affine(); // write the complete accumulated transform passed to us // (we're dealing with unattached representations, so we write to their attributes // instead of using sp_item_set_transform) - SPUse *use=dynamic_cast<SPUse *>(item); - if( use && use->get_original() && use->get_original()->parent) { - if (selection->includes(use->get_original())){ //we are copying something whose parent is also copied (!) - obj_copy->setAttribute("transform", sp_svg_transform_write( ((SPItem*)(use->get_original()->parent))->i2doc_affine().inverse() * transform)); + SPUse *use = dynamic_cast<SPUse *>(item); + if (use && use->get_original() && use->get_original()->parent) { + if (selection->includes(use->get_original())) { // we are copying something whose parent is also copied + // (!) + obj_copy->setAttribute( + "transform", + sp_svg_transform_write(((SPItem *)(use->get_original()->parent))->i2doc_affine().inverse() * + transform)); } else { // original is not copied obj_copy->setAttribute("transform-with-parent", sp_svg_transform_write(transform)); - obj_copy->setAttribute("transform", sp_svg_transform_write( ((SPItem*)(use->get_original()->parent))->i2doc_affine().inverse() * transform)); + obj_copy->setAttribute( + "transform", + sp_svg_transform_write(((SPItem *)(use->get_original()->parent))->i2doc_affine().inverse() * + transform)); } } else obj_copy->setAttribute("transform", sp_svg_transform_write(transform)); @@ -803,7 +794,7 @@ void ClipboardManagerImpl::_copySelection(ObjectSet *selection) } // copy path effect from the first path if (object) { - gchar const *effect =object->getRepr()->attribute("inkscape:path-effect"); + gchar const *effect = object->getRepr()->attribute("inkscape:path-effect"); if (effect) { _clipnode->setAttribute("inkscape:path-effect", effect); } @@ -815,18 +806,16 @@ void ClipboardManagerImpl::_copySelection(ObjectSet *selection) sp_repr_set_point(_clipnode, "min", size->min()); sp_repr_set_point(_clipnode, "max", size->max()); } - } - /** * Recursively copy all the definitions used by a given item to the clipboard defs. */ void ClipboardManagerImpl::_copyUsedDefs(SPItem *item) { - SPUse *use=dynamic_cast<SPUse *>(item); + SPUse *use = dynamic_cast<SPUse *>(item); if (use && use->get_original()) { - if(cloned_elements.insert(use->get_original()).second) + if (cloned_elements.insert(use->get_original()).second) _copyUsedDefs(use->get_original()); } @@ -835,7 +824,7 @@ void ClipboardManagerImpl::_copyUsedDefs(SPItem *item) if (style && (style->fill.isPaintserver())) { SPPaintServer *server = item->style->getFillPaintServer(); - if ( dynamic_cast<SPLinearGradient *>(server) || dynamic_cast<SPRadialGradient *>(server) ) { + if (dynamic_cast<SPLinearGradient *>(server) || dynamic_cast<SPRadialGradient *>(server)) { _copyGradient(dynamic_cast<SPGradient *>(server)); } SPPattern *pattern = dynamic_cast<SPPattern *>(server); @@ -849,7 +838,7 @@ void ClipboardManagerImpl::_copyUsedDefs(SPItem *item) } if (style && (style->stroke.isPaintserver())) { SPPaintServer *server = item->style->getStrokePaintServer(); - if ( dynamic_cast<SPLinearGradient *>(server) || dynamic_cast<SPRadialGradient *>(server) ) { + if (dynamic_cast<SPLinearGradient *>(server) || dynamic_cast<SPRadialGradient *>(server)) { _copyGradient(dynamic_cast<SPGradient *>(server)); } SPPattern *pattern = dynamic_cast<SPPattern *>(server); @@ -865,7 +854,7 @@ void ClipboardManagerImpl::_copyUsedDefs(SPItem *item) // For shapes, copy all of the shape's markers SPShape *shape = dynamic_cast<SPShape *>(item); if (shape) { - for (auto & i : shape->_marker) { + for (auto &i : shape->_marker) { if (i) { _copyNode(i->getRepr(), _doc, _defs); } @@ -888,9 +877,8 @@ void ClipboardManagerImpl::_copyUsedDefs(SPItem *item) _copyTextPath(textpath); } if (text) { - for (auto &&shape_prop_ptr : { - reinterpret_cast<SPIShapes SPStyle::*>(&SPStyle::shape_inside), - reinterpret_cast<SPIShapes SPStyle::*>(&SPStyle::shape_subtract) }) { + for (auto &&shape_prop_ptr : {reinterpret_cast<SPIShapes SPStyle::*>(&SPStyle::shape_inside), + reinterpret_cast<SPIShapes SPStyle::*>(&SPStyle::shape_subtract)}) { for (auto *href : (text->style->*shape_prop_ptr).hrefs) { auto shape_obj = href->getObject(); if (!shape_obj) @@ -910,14 +898,14 @@ void ClipboardManagerImpl::_copyUsedDefs(SPItem *item) } // Copy mask objects if (SPObject *mask = item->getMaskObject()) { - _copyNode(mask->getRepr(), _doc, _defs); - // recurse into the mask for its gradients etc. - for(auto& o: mask->children) { - SPItem *childItem = dynamic_cast<SPItem *>(&o); - if (childItem) { - _copyUsedDefs(childItem); - } + _copyNode(mask->getRepr(), _doc, _defs); + // recurse into the mask for its gradients etc. + for (auto &o : mask->children) { + SPItem *childItem = dynamic_cast<SPItem *>(&o); + if (childItem) { + _copyUsedDefs(childItem); } + } } // Copy filters @@ -932,18 +920,18 @@ void ClipboardManagerImpl::_copyUsedDefs(SPItem *item) SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(item); if (lpeitem) { if (lpeitem->hasPathEffect()) { - PathEffectList path_effect_list( *lpeitem->path_effect_list); + PathEffectList path_effect_list(*lpeitem->path_effect_list); for (auto &lperef : path_effect_list) { LivePathEffectObject *lpeobj = lperef->lpeobject; if (lpeobj) { - _copyNode(lpeobj->getRepr(), _doc, _defs); + _copyNode(lpeobj->getRepr(), _doc, _defs); } } } } // recurse - for(auto& o: item->children) { + for (auto &o : item->children) { SPItem *childItem = dynamic_cast<SPItem *>(&o); if (childItem) { _copyUsedDefs(childItem); @@ -959,16 +947,14 @@ void ClipboardManagerImpl::_copyGradient(SPGradient *gradient) while (gradient) { // climb up the refs, copying each one in the chain _copyNode(gradient->getRepr(), _doc, _defs); - if (gradient->ref){ + if (gradient->ref) { gradient = gradient->ref->getObject(); - } - else { + } else { gradient = nullptr; } } } - /** * Copy a single pattern to the clipboard document's defs element. */ @@ -979,16 +965,15 @@ void ClipboardManagerImpl::_copyPattern(SPPattern *pattern) _copyNode(pattern->getRepr(), _doc, _defs); // items in the pattern may also use gradients and other patterns, so recurse - for (auto& child: pattern->children) { + for (auto &child : pattern->children) { SPItem *childItem = dynamic_cast<SPItem *>(&child); if (childItem) { _copyUsedDefs(childItem); } } - if (pattern->ref){ + if (pattern->ref) { pattern = pattern->ref->getObject(); - } - else{ + } else { pattern = nullptr; } } @@ -1017,7 +1002,6 @@ void ClipboardManagerImpl::_copyHatch(SPHatch *hatch) } } - /** * Copy a text path to the clipboard's defs element. */ @@ -1029,12 +1013,11 @@ void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp) } // textpaths that aren't in defs (on the canvas) shouldn't be copied because if // both objects are being copied already, this ends up stealing the refs id. - if(path->parent && SP_IS_DEFS(path->parent)) { + if (path->parent && SP_IS_DEFS(path->parent)) { _copyIgnoreDup(path->getRepr(), _doc, _defs); } } - /** * Copy a single XML node from one document to another. * @param node The node to be copied @@ -1042,7 +1025,8 @@ void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp) * @param parent The node in the target document which will become the parent of the copied node * @return Pointer to the copied node */ -Inkscape::XML::Node *ClipboardManagerImpl::_copyNode(Inkscape::XML::Node *node, Inkscape::XML::Document *target_doc, Inkscape::XML::Node *parent) +Inkscape::XML::Node *ClipboardManagerImpl::_copyNode(Inkscape::XML::Node *node, Inkscape::XML::Document *target_doc, + Inkscape::XML::Node *parent) { Inkscape::XML::Node *dup = node->duplicate(target_doc); parent->appendChild(dup); @@ -1050,7 +1034,9 @@ Inkscape::XML::Node *ClipboardManagerImpl::_copyNode(Inkscape::XML::Node *node, return dup; } -Inkscape::XML::Node *ClipboardManagerImpl::_copyIgnoreDup(Inkscape::XML::Node *node, Inkscape::XML::Document *target_doc, Inkscape::XML::Node *parent) +Inkscape::XML::Node *ClipboardManagerImpl::_copyIgnoreDup(Inkscape::XML::Node *node, + Inkscape::XML::Document *target_doc, + Inkscape::XML::Node *parent) { if (sp_repr_lookup_child(_root, "id", node->attribute("id"))) { // node already copied @@ -1062,13 +1048,12 @@ Inkscape::XML::Node *ClipboardManagerImpl::_copyIgnoreDup(Inkscape::XML::Node *n return dup; } - /** * Retrieve a bitmap image from the clipboard and paste it into the active document. */ bool ClipboardManagerImpl::_pasteImage(SPDocument *doc) { - if ( doc == nullptr ) { + if (doc == nullptr) { return false; } @@ -1086,7 +1071,7 @@ bool ClipboardManagerImpl::_pasteImage(SPDocument *doc) prefs->setBool("/dialogs/import/ask", false); png->set_gui(false); - gchar *filename = g_build_filename( g_get_user_cache_dir(), "inkscape-clipboard-import", NULL ); + gchar *filename = g_build_filename(g_get_user_cache_dir(), "inkscape-clipboard-import", NULL); img->save(filename, "png"); file_import(doc, filename, png); g_free(filename); @@ -1102,7 +1087,7 @@ bool ClipboardManagerImpl::_pasteImage(SPDocument *doc) */ bool ClipboardManagerImpl::_pasteText(SPDesktop *desktop) { - if ( desktop == nullptr ) { + if (desktop == nullptr) { return false; } @@ -1111,81 +1096,80 @@ bool ClipboardManagerImpl::_pasteText(SPDesktop *desktop) return Inkscape::UI::Tools::sp_text_paste_inline(desktop->event_context); } return false; - /* return false; - //apply the saved style to pasted text - Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get(); - Glib::ustring const clip_text = refClipboard->wait_for_text(); - Glib::ustring text(clip_text); - if(text.length() == copied_style_length) + /* return false; + //apply the saved style to pasted text + Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get(); + Glib::ustring const clip_text = refClipboard->wait_for_text(); + Glib::ustring text(clip_text); + if(text.length() == copied_style_length) + { + Inkscape::UI::Tools::TextTool *tc = SP_TEXT_CONTEXT(desktop->event_context); + // we realy only want to inherit container style (to act as 0.92 and faster performance) + // maybe for 1.0 we can make a special type of clipboard + // that handle layout or maybe we can use the last desktop text style + // so I comment unneded code. + Inkscape::Text::Layout const *layout = te_get_layout(tc->text); + Inkscape::Text::Layout::iterator it_next; + Inkscape::Text::Layout::iterator it = tc->text_sel_end; + SPText *textitem = dynamic_cast<SPText *>(tc->text); + if (textitem) { + textitem->rebuildLayout(); + } + SPFlowtext *flowtext = dynamic_cast<SPFlowtext *>(tc->text); + if (flowtext) { + flowtext->rebuildLayout(); + } + // we realy only want to inherit container style + SPCSSAttr *css = take_style_from_item(tc->text); + for (int i = 0; i < nr_blocks; ++i) { - Inkscape::UI::Tools::TextTool *tc = SP_TEXT_CONTEXT(desktop->event_context); - // we realy only want to inherit container style (to act as 0.92 and faster performance) - // maybe for 1.0 we can make a special type of clipboard - // that handle layout or maybe we can use the last desktop text style - // so I comment unneded code. - Inkscape::Text::Layout const *layout = te_get_layout(tc->text); - Inkscape::Text::Layout::iterator it_next; - Inkscape::Text::Layout::iterator it = tc->text_sel_end; - SPText *textitem = dynamic_cast<SPText *>(tc->text); - if (textitem) { - textitem->rebuildLayout(); - } - SPFlowtext *flowtext = dynamic_cast<SPFlowtext *>(tc->text); - if (flowtext) { - flowtext->rebuildLayout(); - } - // we realy only want to inherit container style - SPCSSAttr *css = take_style_from_item(tc->text); - for (int i = 0; i < nr_blocks; ++i) - { - gchar const *w = sp_repr_css_property(css, "font-size", "0px"); - - // Don't set font-size if it wasn't set. - if (w && strcmp(w, "0px") != 0) { - sp_repr_css_set_property(te_selected_style[i], "font-size", w); - } - } + gchar const *w = sp_repr_css_property(css, "font-size", "0px"); - for (unsigned int i = 0; i < text.length(); ++i) - it.prevCharacter(); + // Don't set font-size if it wasn't set. + if (w && strcmp(w, "0px") != 0) { + sp_repr_css_set_property(te_selected_style[i], "font-size", w); + } + } - it_next = layout->charIndexToIterator(layout->iteratorToCharIndex(it)); + for (unsigned int i = 0; i < text.length(); ++i) + it.prevCharacter(); - for (int i = 0; i < nr_blocks; ++i) - { - for (unsigned int j = te_selected_style_positions[i]; j < te_selected_style_positions[i+1]; ++j) - it_next.nextCharacter(); + it_next = layout->charIndexToIterator(layout->iteratorToCharIndex(it)); - // sp_te_apply_style(tc->text, it, it_next, te_selected_style[i]); - te_update_layout_now_recursive(tc->text); - tc->text_sel_end = it; - for (unsigned int j = te_selected_style_positions[i]; j < te_selected_style_positions[i+1]; ++j) - it.nextCharacter(); - } + for (int i = 0; i < nr_blocks; ++i) + { + for (unsigned int j = te_selected_style_positions[i]; j < te_selected_style_positions[i+1]; ++j) + it_next.nextCharacter(); + + // sp_te_apply_style(tc->text, it, it_next, te_selected_style[i]); + te_update_layout_now_recursive(tc->text); + tc->text_sel_end = it; + for (unsigned int j = te_selected_style_positions[i]; j < te_selected_style_positions[i+1]; ++j) + it.nextCharacter(); } - return true; - - } - // old(try to parse the text as a color and, if successful, apply it as the current style) - // we realy only want to inherit container style - // maybe for 1.0 we can make a special type of clipboard - // that handle layout or maybe we can use the last desktop text style - SPCSSAttr *css = sp_repr_css_attr_parse_color_to_fill(_clipboard->wait_for_text()); - if (css) { - sp_desktop_set_style(desktop, css); - return true; } - return false; - */ -} + return true; +} +// old(try to parse the text as a color and, if successful, apply it as the current style) +// we realy only want to inherit container style +// maybe for 1.0 we can make a special type of clipboard +// that handle layout or maybe we can use the last desktop text style +SPCSSAttr *css = sp_repr_css_attr_parse_color_to_fill(_clipboard->wait_for_text()); +if (css) { + sp_desktop_set_style(desktop, css); + return true; +} +return false; +*/ +} /** * Applies a pasted path effect to a given item. */ void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effectstack) { - if ( item == nullptr ) { + if (item == nullptr) { return; } @@ -1193,8 +1177,7 @@ void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effectsta if (lpeitem && effectstack) { std::istringstream iss(effectstack); std::string href; - while (std::getline(iss, href, ';')) - { + while (std::getline(iss, href, ';')) { SPObject *obj = sp_uri_reference_resolve(_clipboardSPDoc.get(), href.c_str()); if (!obj) { return; @@ -1209,7 +1192,6 @@ void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effectsta } } - /** * Retrieve the clipboard contents as a document. * @return Clipboard contents converted to SPDocument, or NULL if no suitable content was present @@ -1217,30 +1199,30 @@ void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effectsta std::unique_ptr<SPDocument> ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_target) { Glib::ustring best_target; - if ( required_target == "" ) { + if (required_target == "") { best_target = _getBestTarget(); } else { best_target = required_target; } - if ( best_target == "" ) { + if (best_target == "") { return nullptr; } // FIXME: Temporary hack until we add memory input. // Save the clipboard contents to some file, then read it - gchar *filename = g_build_filename( g_get_user_cache_dir(), "inkscape-clipboard-import", NULL ); + gchar *filename = g_build_filename(g_get_user_cache_dir(), "inkscape-clipboard-import", NULL); bool file_saved = false; Glib::ustring target = best_target; #ifdef _WIN32 - if (best_target == "CF_ENHMETAFILE" || best_target == "WCF_ENHMETAFILE") - { // Try to save clipboard data as en emf file (using win32 api) + 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); if (hglb) { - HENHMETAFILE hemf = CopyEnhMetaFile((HENHMETAFILE) hglb, filename); + HENHMETAFILE hemf = CopyEnhMetaFile((HENHMETAFILE)hglb, filename); if (hemf) { file_saved = true; target = "image/x-emf"; @@ -1253,20 +1235,21 @@ std::unique_ptr<SPDocument> ClipboardManagerImpl::_retrieveClipboard(Glib::ustri #endif if (!file_saved) { - if ( !_clipboard->wait_is_target_available(best_target) ) { + if (!_clipboard->wait_is_target_available(best_target)) { return nullptr; } // doing this synchronously makes better sense // TODO: use another method because this one is badly broken imo. - // from documentation: "Returns: A SelectionData object, which will be invalid if retrieving the given target failed." - // I don't know how to check whether an object is 'valid' or not, unusable if that's not possible... + // from documentation: "Returns: A SelectionData object, which will be invalid if retrieving the given target + // failed." I don't know how to check whether an object is 'valid' or not, unusable if that's not possible... Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target); - target = sel.get_target(); // this can crash if the result was invalid of last function. No way to check for this :( + target = + sel.get_target(); // this can crash if the result was invalid of last function. No way to check for this :( // FIXME: Temporary hack until we add memory input. // Save the clipboard contents to some file, then read it - g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), nullptr); + g_file_set_contents(filename, (const gchar *)sel.get_data(), sel.get_length(), nullptr); } // there is no specific plain SVG input extension, so if we can paste the Inkscape SVG format, @@ -1282,9 +1265,9 @@ std::unique_ptr<SPDocument> ClipboardManagerImpl::_retrieveClipboard(Glib::ustri Inkscape::Extension::DB::InputList inlist; Inkscape::Extension::db.get_input_list(inlist); Inkscape::Extension::DB::InputList::const_iterator in = inlist.begin(); - for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in) { + for (; in != inlist.end() && target != (*in)->get_mimetype(); ++in) { }; - if ( in == inlist.end() ) { + if (in == inlist.end()) { return nullptr; // this shouldn't happen unless _getBestTarget returns something bogus } @@ -1299,7 +1282,6 @@ std::unique_ptr<SPDocument> ClipboardManagerImpl::_retrieveClipboard(Glib::ustri return std::unique_ptr<SPDocument>(tempdoc); } - /** * Callback called when some other application requests data from Inkscape. * @@ -1323,29 +1305,28 @@ void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/) Inkscape::Extension::DB::OutputList outlist; Inkscape::Extension::db.get_output_list(outlist); Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin(); - for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out) { + for (; out != outlist.end() && target != (*out)->get_mimetype(); ++out) { }; - if ( out == outlist.end() && target != "image/png") { + if (out == outlist.end() && target != "image/png") { return; // this also shouldn't happen } // FIXME: Temporary hack until we add support for memory output. // Save to a temporary file, read it back and then set the clipboard contents - gchar *filename = g_build_filename( g_get_user_cache_dir(), "inkscape-clipboard-export", NULL ); + gchar *filename = g_build_filename(g_get_user_cache_dir(), "inkscape-clipboard-export", NULL); gchar *data = nullptr; gsize len; try { - if (out == outlist.end() && target == "image/png") - { + if (out == outlist.end() && target == "image/png") { gdouble dpi = Inkscape::Util::Quantity::convert(1, "in", "px"); guint32 bgcolor = 0x00000000; - Geom::Point origin (_clipboardSPDoc->getRoot()->x.computed, _clipboardSPDoc->getRoot()->y.computed); + 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() + 0.5); - unsigned long int height = (unsigned long int) (area.height() + 0.5); + unsigned long int width = (unsigned long int)(area.width() + 0.5); + unsigned long int height = (unsigned long int)(area.height() + 0.5); // read from namedview Inkscape::XML::Node *nv = _clipboardSPDoc->getReprNamedView(); @@ -1357,23 +1338,20 @@ void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/) sp_repr_get_double(nv, "inkscape:pageopacity", &opacity); bgcolor |= SP_COLOR_F_TO_U(opacity); } - std::vector<SPItem*> x; + std::vector<SPItem *> x; sp_export_png_file(_clipboardSPDoc.get(), filename, area, width, height, dpi, dpi, bgcolor, nullptr, nullptr, true, x); - } - else - { + } else { if (!(*out)->loaded()) { // Need to load the extension. (*out)->set_state(Inkscape::Extension::Extension::STATE_LOADED); } - (*out)->save(_clipboardSPDoc.get(), filename, true); } g_file_get_contents(filename, &data, &len, nullptr); - sel.set(8, (guint8 const *) data, len); + sel.set(8, (guint8 const *)data, len); } catch (...) { } @@ -1382,7 +1360,6 @@ void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/) g_free(data); } - /** * Callback when someone else takes the clipboard. * @@ -1395,15 +1372,14 @@ void ClipboardManagerImpl::_onClear() //_discardInternalClipboard(); } - /** * Creates an internal clipboard document from scratch. */ void ClipboardManagerImpl::_createInternalClipboard() { - if ( _clipboardSPDoc == nullptr ) { + if (_clipboardSPDoc == nullptr) { _clipboardSPDoc.reset(SPDocument::createNewDoc(nullptr, false, true)); - //g_assert( _clipboardSPDoc != NULL ); + // g_assert( _clipboardSPDoc != NULL ); _defs = _clipboardSPDoc->getDefs()->getRepr(); _doc = _clipboardSPDoc->getReprDoc(); _root = _clipboardSPDoc->getReprRoot(); @@ -1424,13 +1400,12 @@ void ClipboardManagerImpl::_createInternalClipboard() } } - /** * Deletes the internal clipboard document. */ void ClipboardManagerImpl::_discardInternalClipboard() { - if ( _clipboardSPDoc != nullptr ) { + if (_clipboardSPDoc != nullptr) { _clipboardSPDoc = nullptr; _defs = nullptr; _doc = nullptr; @@ -1439,11 +1414,11 @@ void ClipboardManagerImpl::_discardInternalClipboard() } } - /** * Get the scale to resize an item, based on the command and desktop state. */ -Geom::Scale ClipboardManagerImpl::_getScale(SPDesktop *desktop, Geom::Point const &min, Geom::Point const &max, Geom::Rect const &obj_rect, bool apply_x, bool apply_y) +Geom::Scale ClipboardManagerImpl::_getScale(SPDesktop *desktop, Geom::Point const &min, Geom::Point const &max, + Geom::Rect const &obj_rect, bool apply_x, bool apply_y) { double scale_x = 1.0; double scale_y = 1.0; @@ -1468,7 +1443,6 @@ Geom::Scale ClipboardManagerImpl::_getScale(SPDesktop *desktop, Geom::Point cons return Geom::Scale(scale_x, scale_y); } - /** * Find the most suitable clipboard target. */ @@ -1484,15 +1458,13 @@ Glib::ustring ClipboardManagerImpl::_getBestTarget() g_message("End clipboard targets\n"); //*/ - for (auto & _preferred_target : _preferred_targets) - { - if ( std::find(targets.begin(), targets.end(), _preferred_target) != targets.end() ) { + for (auto &_preferred_target : _preferred_targets) { + if (std::find(targets.begin(), targets.end(), _preferred_target) != targets.end()) { return _preferred_target; } } #ifdef _WIN32 - if (OpenClipboard(NULL)) - { // If both bitmap and metafile are present, pick the one that was exported first. + if (OpenClipboard(NULL)) { // If both bitmap and metafile are present, pick the one that was exported first. UINT format = EnumClipboardFormats(0); while (format) { if (format == CF_ENHMETAFILE || format == CF_DIB || format == CF_BITMAP) { @@ -1524,7 +1496,6 @@ Glib::ustring ClipboardManagerImpl::_getBestTarget() return ""; } - /** * Set the clipboard targets to reflect the mimetypes Inkscape can output. */ @@ -1535,11 +1506,11 @@ void ClipboardManagerImpl::_setClipboardTargets() std::vector<Gtk::TargetEntry> target_list; bool plaintextSet = false; - for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) { - if ( !(*out)->deactivated() ) { + for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin(); out != outlist.end(); ++out) { + if (!(*out)->deactivated()) { Glib::ustring mime = (*out)->get_mimetype(); if (mime != CLIPBOARD_TEXT_TARGET) { - if ( !plaintextSet && (mime.find("svg") == Glib::ustring::npos) ) { + if (!plaintextSet && (mime.find("svg") == Glib::ustring::npos)) { target_list.emplace_back(CLIPBOARD_TEXT_TARGET); plaintextSet = true; } @@ -1550,11 +1521,10 @@ void ClipboardManagerImpl::_setClipboardTargets() // Add PNG export explicitly since there is no extension for this... // On Windows, GTK will also present this as a CF_DIB/CF_BITMAP - target_list.emplace_back( "image/png" ); + target_list.emplace_back("image/png"); - _clipboard->set(target_list, - sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet), - sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear)); + _clipboard->set(target_list, sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet), + sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear)); #ifdef _WIN32 // If the "image/x-emf" target handled by the emf extension would be @@ -1569,18 +1539,18 @@ void ClipboardManagerImpl::_setClipboardTargets() // If possible make it delayed rendering by using GTK API only. if (OpenClipboard(NULL)) { - if ( _clipboardSPDoc != NULL ) { + if (_clipboardSPDoc != NULL) { const Glib::ustring target = "image/x-emf"; Inkscape::Extension::DB::OutputList outlist; Inkscape::Extension::db.get_output_list(outlist); Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin(); - for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out) { + for (; out != outlist.end() && target != (*out)->get_mimetype(); ++out) { } - if ( out != outlist.end() ) { + if (out != outlist.end()) { // FIXME: Temporary hack until we add support for memory output. // Save to a temporary file, read it back and then set the clipboard contents - gchar *filename = g_build_filename( g_get_user_cache_dir(), "inkscape-clipboard-export.emf", NULL ); + gchar *filename = g_build_filename(g_get_user_cache_dir(), "inkscape-clipboard-export.emf", NULL); try { (*out)->save(_clipboardSPDoc.get(), filename); @@ -1600,7 +1570,6 @@ void ClipboardManagerImpl::_setClipboardTargets() #endif } - /** * Set the string representation of a 32-bit RGBA color as the clipboard contents. */ @@ -1611,13 +1580,12 @@ void ClipboardManagerImpl::_setClipboardColor(guint32 color) _clipboard->set_text(colorstr); } - /** * Put a notification on the message stack. */ void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg) { - if(desktop) + if (desktop) desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, msg); } @@ -1631,15 +1599,15 @@ ClipboardManager::ClipboardManager() = default; ClipboardManager::~ClipboardManager() = default; ClipboardManager *ClipboardManager::get() { - if ( _instance == nullptr ) { + if (_instance == nullptr) { _instance = new ClipboardManagerImpl; } return _instance; } +} // namespace UI } // namespace Inkscape -} // namespace IO /* Local Variables: diff --git a/src/ui/clipboard.h b/src/ui/clipboard.h index 4815f52cd8d374ecd885c6924ad3cc79a59b170d..c7fe02140512abd632abb47b9c541e53e4a2aaa6 100644 --- a/src/ui/clipboard.h +++ b/src/ui/clipboard.h @@ -21,8 +21,12 @@ class SPDesktop; namespace Inkscape { class ObjectSet; -namespace XML { class Node; } -namespace LivePathEffect { class PathParam; } +namespace XML { +class Node; +} +namespace LivePathEffect { +class PathParam; +} namespace UI { @@ -36,31 +40,35 @@ namespace UI { * data required (i.e. style, size, Live Path Effects parameters, etc.) */ -class ClipboardManager { +class ClipboardManager +{ public: virtual void copy(ObjectSet *set) = 0; virtual void copyPathParameter(Inkscape::LivePathEffect::PathParam *) = 0; - virtual void copySymbol(Inkscape::XML::Node* symbol, gchar const* style, bool user_symbol = true) = 0; + virtual void copySymbol(Inkscape::XML::Node *symbol, gchar const *style, bool user_symbol = true) = 0; virtual bool paste(SPDesktop *desktop, bool in_place = false) = 0; virtual bool pasteStyle(ObjectSet *set) = 0; virtual bool pasteSize(ObjectSet *set, bool separately, bool apply_x, bool apply_y) = 0; virtual bool pastePathEffect(ObjectSet *set) = 0; - virtual Glib::ustring getPathParameter(SPDesktop* desktop) = 0; + virtual Glib::ustring getPathParameter(SPDesktop *desktop) = 0; virtual Glib::ustring getShapeOrTextObjectId(SPDesktop *desktop) = 0; - virtual std::vector<Glib::ustring> getElementsOfType(SPDesktop *desktop, gchar const* type = "*", gint maxdepth = -1) = 0; + virtual std::vector<Glib::ustring> getElementsOfType(SPDesktop *desktop, gchar const *type = "*", + gint maxdepth = -1) = 0; virtual Glib::ustring getFirstObjectID() = 0; static ClipboardManager *get(); + protected: ClipboardManager(); // singleton virtual ~ClipboardManager(); + private: - ClipboardManager(const ClipboardManager &) = delete; ///< no copy + ClipboardManager(const ClipboardManager &) = delete; ///< no copy ClipboardManager &operator=(const ClipboardManager &) = delete; ///< no assign static ClipboardManager *_instance; }; -} // namespace IO +} // namespace UI } // namespace Inkscape #endif diff --git a/src/ui/contextmenu.cpp b/src/ui/contextmenu.cpp index 2c6ec6be5d351b07ec420f7f3f7e5cf698dac073..467dd5f11a4f80450e1db76ac519ba6c3926e2c1 100644 --- a/src/ui/contextmenu.cpp +++ b/src/ui/contextmenu.cpp @@ -25,50 +25,44 @@ #include <glibmm/convert.h> #include <glibmm/i18n.h> #include <glibmm/miscutils.h> - #include <gtkmm/box.h> #include <gtkmm/cssprovider.h> #include <gtkmm/image.h> #include <gtkmm/separatormenuitem.h> #include "desktop.h" -#include "document.h" #include "document-undo.h" -#include "inkscape.h" -#include "message-context.h" -#include "message-stack.h" -#include "selection.h" -#include "selection-chemistry.h" -#include "shortcuts.h" - +#include "document.h" #include "helper/action-context.h" #include "helper/action.h" -#include "ui/icon-loader.h" - #include "include/gtkmm_version.h" - +#include "inkscape.h" #include "live_effects/lpe-powerclip.h" #include "live_effects/lpe-powermask.h" - +#include "message-context.h" +#include "message-stack.h" #include "object/sp-anchor.h" #include "object/sp-clippath.h" #include "object/sp-image.h" #include "object/sp-mask.h" #include "object/sp-shape.h" #include "object/sp-text.h" - +#include "selection-chemistry.h" +#include "selection.h" +#include "shortcuts.h" #include "ui/dialog/dialog-manager.h" #include "ui/dialog/layer-properties.h" +#include "ui/icon-loader.h" #include "verbs.h" using Inkscape::DocumentUndo; static bool temporarily_block_actions = false; -ContextMenu::ContextMenu(SPDesktop *desktop, SPItem *item) : - _item(item), - MIGroup(), - MIParent(_("Go to parent")) +ContextMenu::ContextMenu(SPDesktop *desktop, SPItem *item) + : _item(item) + , MIGroup() + , MIParent(_("Go to parent")) { _object = static_cast<SPObject *>(item); _desktop = desktop; @@ -86,9 +80,10 @@ ContextMenu::ContextMenu(SPDesktop *desktop, SPItem *item) : AppendItemFromVerb(Inkscape::Verb::get(SP_VERB_EDIT_DUPLICATE), show_icons); AppendItemFromVerb(Inkscape::Verb::get(SP_VERB_EDIT_DELETE), show_icons); - positionOfLastDialog = 10; // 9 in front + 1 for the separator in the next if; used to position the dialog menu entries below each other + positionOfLastDialog = 10; // 9 in front + 1 for the separator in the next if; used to position the dialog menu + // entries below each other /* Item menu */ - if (item!=nullptr) { + if (item != nullptr) { AddSeparator(); MakeObjectMenu(); } @@ -96,82 +91,85 @@ ContextMenu::ContextMenu(SPDesktop *desktop, SPItem *item) : /* Lock/Unock Hide/Unhide*/ auto point_doc = _desktop->point() * _desktop->dt2doc(); Geom::Rect b(point_doc, point_doc + Geom::Point(1, 1)); - std::vector< SPItem * > down_items = _desktop->getDocument()->getItemsPartiallyInBox( _desktop->dkey, b, true, true, true, true); + std::vector<SPItem *> down_items = + _desktop->getDocument()->getItemsPartiallyInBox(_desktop->dkey, b, true, true, true, true); bool has_down_hidden = false; bool has_down_locked = false; - for(auto & down_item : down_items){ - if(down_item->isHidden()) { + for (auto &down_item : down_items) { + if (down_item->isHidden()) { has_down_hidden = true; } - if(down_item->isLocked()) { + if (down_item->isLocked()) { has_down_locked = true; } } - Gtk::MenuItem* mi; + Gtk::MenuItem *mi; - mi = Gtk::manage(new Gtk::MenuItem(_("Hide Selected Objects"),true)); + mi = Gtk::manage(new Gtk::MenuItem(_("Hide Selected Objects"), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::HideSelected)); if (_desktop->selection->isEmpty()) { mi->set_sensitive(false); } mi->show(); - append(*mi);//insert(*mi,positionOfLastDialog++); + append(*mi); // insert(*mi,positionOfLastDialog++); - mi = Gtk::manage(new Gtk::MenuItem(_("Unhide Objects Below"),true)); - mi->signal_activate().connect(sigc::bind<std::vector< SPItem * > >(sigc::mem_fun(*this, &ContextMenu::UnHideBelow), down_items)); + mi = Gtk::manage(new Gtk::MenuItem(_("Unhide Objects Below"), true)); + mi->signal_activate().connect( + sigc::bind<std::vector<SPItem *>>(sigc::mem_fun(*this, &ContextMenu::UnHideBelow), down_items)); if (!has_down_hidden) { mi->set_sensitive(false); } mi->show(); - append(*mi);//insert(*mi,positionOfLastDialog++); + append(*mi); // insert(*mi,positionOfLastDialog++); - mi = Gtk::manage(new Gtk::MenuItem(_("Lock Selected Objects"),true)); + mi = Gtk::manage(new Gtk::MenuItem(_("Lock Selected Objects"), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::LockSelected)); if (_desktop->selection->isEmpty()) { mi->set_sensitive(false); } mi->show(); - append(*mi);//insert(*mi,positionOfLastDialog++); + append(*mi); // insert(*mi,positionOfLastDialog++); - mi = Gtk::manage(new Gtk::MenuItem(_("Unlock Objects Below"),true)); - mi->signal_activate().connect(sigc::bind<std::vector< SPItem * > >(sigc::mem_fun(*this, &ContextMenu::UnLockBelow), down_items)); + mi = Gtk::manage(new Gtk::MenuItem(_("Unlock Objects Below"), true)); + mi->signal_activate().connect( + sigc::bind<std::vector<SPItem *>>(sigc::mem_fun(*this, &ContextMenu::UnLockBelow), down_items)); if (!has_down_locked) { mi->set_sensitive(false); } mi->show(); - append(*mi);//insert(*mi,positionOfLastDialog++); + append(*mi); // insert(*mi,positionOfLastDialog++); /* layer menu */ - SPGroup *group=nullptr; + SPGroup *group = nullptr; if (item) { if (SP_IS_GROUP(item)) { group = SP_GROUP(item); - } else if ( item != _desktop->currentRoot() && SP_IS_GROUP(item->parent) ) { + } else if (item != _desktop->currentRoot() && SP_IS_GROUP(item->parent)) { group = SP_GROUP(item->parent); } } - if (( group && group != _desktop->currentLayer() ) || - ( _desktop->currentLayer() != _desktop->currentRoot() && _desktop->currentLayer()->parent != _desktop->currentRoot() ) ) { + if ((group && group != _desktop->currentLayer()) || (_desktop->currentLayer() != _desktop->currentRoot() && + _desktop->currentLayer()->parent != _desktop->currentRoot())) { AddSeparator(); } - if ( group && group != _desktop->currentLayer() ) { + if (group && group != _desktop->currentLayer()) { /* TRANSLATORS: #%1 is the id of the group e.g. <g id="#g7">, not a number. */ - MIGroup.set_label (Glib::ustring::compose(_("Enter group #%1"), group->getId())); + MIGroup.set_label(Glib::ustring::compose(_("Enter group #%1"), group->getId())); _MIGroup_group = group; - MIGroup.signal_activate().connect(sigc::bind(sigc::mem_fun(*this, &ContextMenu::EnterGroup),&MIGroup)); + MIGroup.signal_activate().connect(sigc::bind(sigc::mem_fun(*this, &ContextMenu::EnterGroup), &MIGroup)); MIGroup.show(); append(MIGroup); } - if ( _desktop->currentLayer() != _desktop->currentRoot() ) { - if ( _desktop->currentLayer()->parent != _desktop->currentRoot() ) { + if (_desktop->currentLayer() != _desktop->currentRoot()) { + if (_desktop->currentLayer()->parent != _desktop->currentRoot()) { MIParent.signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::LeaveGroup)); MIParent.show(); append(MIParent); /* Pop selection out of group */ - Gtk::MenuItem* miu = Gtk::manage(new Gtk::MenuItem(_("_Pop selection out of group"), true)); + Gtk::MenuItem *miu = Gtk::manage(new Gtk::MenuItem(_("_Pop selection out of group"), true)); miu->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::ActivateUngroupPopSelection)); miu->show(); append(*miu); @@ -181,18 +179,17 @@ ContextMenu::ContextMenu(SPDesktop *desktop, SPItem *item) : signal_map().connect(sigc::mem_fun(*this, &ContextMenu::ShiftIcons)); } -ContextMenu::~ContextMenu(void) -= default; +ContextMenu::~ContextMenu(void) = default; -Gtk::SeparatorMenuItem* ContextMenu::AddSeparator() +Gtk::SeparatorMenuItem *ContextMenu::AddSeparator() { - Gtk::SeparatorMenuItem* sep = Gtk::manage(new Gtk::SeparatorMenuItem()); + Gtk::SeparatorMenuItem *sep = Gtk::manage(new Gtk::SeparatorMenuItem()); sep->show(); append(*sep); return sep; } -void ContextMenu::EnterGroup(Gtk::MenuItem* mi) +void ContextMenu::EnterGroup(Gtk::MenuItem *mi) { _desktop->setCurrentLayer(_MIGroup_group); _desktop->selection->clear(); @@ -206,23 +203,23 @@ void ContextMenu::LeaveGroup() void ContextMenu::LockSelected() { auto itemlist = _desktop->selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end(); ++i) { - (*i)->setLocked(true); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { + (*i)->setLocked(true); } } void ContextMenu::HideSelected() { - auto itemlist =_desktop->selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end(); ++i) { - (*i)->setHidden(true); + auto itemlist = _desktop->selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { + (*i)->setHidden(true); } } void ContextMenu::UnLockBelow(std::vector<SPItem *> items) { _desktop->selection->clear(); - for(auto & item : items) { + for (auto &item : items) { if (item->isLocked()) { item->setLocked(false); _desktop->selection->add(item); @@ -233,7 +230,7 @@ void ContextMenu::UnLockBelow(std::vector<SPItem *> items) void ContextMenu::UnHideBelow(std::vector<SPItem *> items) { _desktop->selection->clear(); - for(auto & item : items) { + for (auto &item : items) { if (item->isHidden()) { item->setHidden(false); _desktop->selection->add(item); @@ -248,27 +245,23 @@ void ContextMenu::UnHideBelow(std::vector<SPItem *> items) * of global "right-clicked position" variable for actions to * investigate when they're called. */ -static void -context_menu_item_on_my_activate(void */*object*/, SPAction *action) +static void context_menu_item_on_my_activate(void * /*object*/, SPAction *action) { if (!temporarily_block_actions) { sp_action_perform(action, nullptr); } } -static void -context_menu_item_on_my_select(void */*object*/, SPAction *action) +static void context_menu_item_on_my_select(void * /*object*/, SPAction *action) { sp_action_get_view(action)->tipsMessageContext()->set(Inkscape::NORMAL_MESSAGE, action->tip); } -static void -context_menu_item_on_my_deselect(void */*object*/, SPAction *action) +static void context_menu_item_on_my_deselect(void * /*object*/, SPAction *action) { sp_action_get_view(action)->tipsMessageContext()->clear(); } - // TODO: Update this to allow radio items to be used void ContextMenu::AppendItemFromVerb(Inkscape::Verb *verb, bool show_icon) { @@ -295,7 +288,7 @@ void ContextMenu::AppendItemFromVerb(Inkscape::Verb *verb, bool show_icon) // If there is an image associated with the action, then we can add it as an icon for the menu item if (show_icon && action->image) { - item->set_name("ImageMenuItem"); // custom name to identify our "ImageMenuItems" + item->set_name("ImageMenuItem"); // custom name to identify our "ImageMenuItems" auto const icon = Gtk::manage(sp_get_icon_image(action->image, Gtk::ICON_SIZE_MENU)); // create a box to hold icon and label as GtkMenuItem derives from GtkBin and can only hold one child @@ -316,9 +309,9 @@ void ContextMenu::AppendItemFromVerb(Inkscape::Verb *verb, bool show_icon) } item->set_events(Gdk::KEY_PRESS_MASK); - item->signal_activate().connect(sigc::bind(sigc::ptr_fun(context_menu_item_on_my_activate),item,action)); - item->signal_select().connect(sigc::bind(sigc::ptr_fun(context_menu_item_on_my_select),item,action)); - item->signal_deselect().connect(sigc::bind(sigc::ptr_fun(context_menu_item_on_my_deselect),item,action)); + item->signal_activate().connect(sigc::bind(sigc::ptr_fun(context_menu_item_on_my_activate), item, action)); + item->signal_select().connect(sigc::bind(sigc::ptr_fun(context_menu_item_on_my_select), item, action)); + item->signal_deselect().connect(sigc::bind(sigc::ptr_fun(context_menu_item_on_my_deselect), item, action)); item->show_all(); append(*item); @@ -352,20 +345,20 @@ void ContextMenu::MakeObjectMenu() } } -void ContextMenu::MakeItemMenu () +void ContextMenu::MakeItemMenu() { - Gtk::MenuItem* mi; + Gtk::MenuItem *mi; /* Item dialog */ - mi = Gtk::manage(new Gtk::MenuItem(_("_Object Properties..."),true)); + mi = Gtk::manage(new Gtk::MenuItem(_("_Object Properties..."), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::ItemProperties)); mi->show(); - append(*mi);//insert(*mi,positionOfLastDialog++); + append(*mi); // insert(*mi,positionOfLastDialog++); AddSeparator(); /* Select item */ - if (Inkscape::Verb::getbyid( "org.inkscape.follow_link" )) { + if (Inkscape::Verb::getbyid("org.inkscape.follow_link")) { mi = Gtk::manage(new Gtk::MenuItem(_("_Select This"), true)); if (_desktop->selection->includes(_item)) { mi->set_sensitive(FALSE); @@ -376,7 +369,6 @@ void ContextMenu::MakeItemMenu () append(*mi); } - mi = Gtk::manage(new Gtk::MenuItem(_("Select Same"))); mi->show(); Gtk::Menu *select_same_submenu = Gtk::manage(new Gtk::Menu()); @@ -438,8 +430,8 @@ void ContextMenu::MakeItemMenu () mi->show(); append(*mi); - bool ClipRefOK=false; - bool MaskRefOK=false; + bool ClipRefOK = false; + bool MaskRefOK = false; if (_item && _item->getClipObject()) { ClipRefOK = true; } @@ -469,7 +461,7 @@ void ContextMenu::MakeItemMenu () append(*mi); /*SSet Clip Group */ - mi = Gtk::manage(new Gtk::MenuItem(_("Create Clip G_roup"),true)); + mi = Gtk::manage(new Gtk::MenuItem(_("Create Clip G_roup"), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::CreateGroupClip)); mi->set_sensitive(TRUE); mi->show(); @@ -550,8 +542,6 @@ void ContextMenu::ItemMoveTo() Inkscape::UI::Dialogs::LayerPropertiesDialog::showMove(_desktop, _desktop->currentLayer()); } - - void ContextMenu::ItemCreateLink() { Inkscape::XML::Document *xml_doc = _desktop->doc()->getReprDoc(); @@ -596,7 +586,6 @@ void ContextMenu::SetClip() _desktop->selection->setMask(true, false); } - void ContextMenu::ReleaseClip() { Inkscape::LivePathEffect::sp_remove_powerclip(_desktop->selection); @@ -606,7 +595,7 @@ void ContextMenu::ReleaseClip() void ContextMenu::MakeGroupMenu() { /* Ungroup */ - Gtk::MenuItem* mi = Gtk::manage(new Gtk::MenuItem(_("_Ungroup"), true)); + Gtk::MenuItem *mi = Gtk::manage(new Gtk::MenuItem(_("_Ungroup"), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::ActivateUngroup)); mi->show(); append(*mi); @@ -619,9 +608,9 @@ void ContextMenu::ActivateGroup() void ContextMenu::ActivateUngroup() { - std::vector<SPItem*> children; + std::vector<SPItem *> children; - sp_item_group_ungroup(static_cast<SPGroup*>(_item), children); + sp_item_group_ungroup(static_cast<SPGroup *>(_item), children); _desktop->selection->setList(children); } @@ -630,16 +619,15 @@ void ContextMenu::ActivateUngroupPopSelection() _desktop->selection->popFromGroup(); } - void ContextMenu::MakeAnchorMenu() { - Gtk::MenuItem* mi; + Gtk::MenuItem *mi; /* Link dialog */ mi = Gtk::manage(new Gtk::MenuItem(_("Link _Properties..."), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::AnchorLinkProperties)); mi->show(); - insert(*mi,positionOfLastDialog++); + insert(*mi, positionOfLastDialog++); /* Select item */ mi = Gtk::manage(new Gtk::MenuItem(_("_Follow Link"), true)); @@ -661,12 +649,11 @@ void ContextMenu::AnchorLinkProperties() void ContextMenu::AnchorLinkFollow() { - if (_desktop->selection->isEmpty()) { _desktop->selection->set(_item); } // Opening the selected links with a python extension - Inkscape::Verb *verb = Inkscape::Verb::getbyid( "org.inkscape.follow_link" ); + Inkscape::Verb *verb = Inkscape::Verb::getbyid("org.inkscape.follow_link"); if (verb) { SPAction *action = verb->get_action(Inkscape::ActionContext(_desktop)); if (action) { @@ -677,14 +664,14 @@ void ContextMenu::AnchorLinkFollow() void ContextMenu::AnchorLinkRemove() { - std::vector<SPItem*> children; - sp_item_group_ungroup(static_cast<SPAnchor*>(_item), children, false); + std::vector<SPItem *> children; + sp_item_group_ungroup(static_cast<SPAnchor *>(_item), children, false); Inkscape::DocumentUndo::done(_desktop->doc(), SP_VERB_NONE, _("Remove link")); } -void ContextMenu::MakeImageMenu () +void ContextMenu::MakeImageMenu() { - Gtk::MenuItem* mi; + Gtk::MenuItem *mi; Inkscape::XML::Node *ir = _object->getRepr(); const gchar *href = ir->attribute("xlink:href"); @@ -692,45 +679,45 @@ void ContextMenu::MakeImageMenu () mi = Gtk::manage(new Gtk::MenuItem(_("Image _Properties..."), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::ImageProperties)); mi->show(); - insert(*mi,positionOfLastDialog++); + insert(*mi, positionOfLastDialog++); /* Edit externally */ mi = Gtk::manage(new Gtk::MenuItem(_("Edit Externally..."), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::ImageEdit)); mi->show(); - insert(*mi,positionOfLastDialog++); - if ( (!href) || ((strncmp(href, "data:", 5) == 0)) ) { - mi->set_sensitive( FALSE ); + insert(*mi, positionOfLastDialog++); + if ((!href) || ((strncmp(href, "data:", 5) == 0))) { + mi->set_sensitive(FALSE); } /* Trace Bitmap */ mi = Gtk::manage(new Gtk::MenuItem(_("_Trace Bitmap..."), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::ImageTraceBitmap)); mi->show(); - insert(*mi,positionOfLastDialog++); + insert(*mi, positionOfLastDialog++); if (_desktop->selection->isEmpty()) { mi->set_sensitive(FALSE); } /* Embed image */ - if (Inkscape::Verb::getbyid( "org.inkscape.filter.selected.embed_image" )) { + if (Inkscape::Verb::getbyid("org.inkscape.filter.selected.embed_image")) { mi = Gtk::manage(new Gtk::MenuItem(C_("Context menu", "Embed Image"))); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::ImageEmbed)); mi->show(); - insert(*mi,positionOfLastDialog++); - if ( (!href) || ((strncmp(href, "data:", 5) == 0)) ) { - mi->set_sensitive( FALSE ); + insert(*mi, positionOfLastDialog++); + if ((!href) || ((strncmp(href, "data:", 5) == 0))) { + mi->set_sensitive(FALSE); } } /* Extract image */ - if (Inkscape::Verb::getbyid( "org.inkscape.filter.extract_image" )) { + if (Inkscape::Verb::getbyid("org.inkscape.filter.extract_image")) { mi = Gtk::manage(new Gtk::MenuItem(C_("Context menu", "Extract Image..."))); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::ImageExtract)); mi->show(); - insert(*mi,positionOfLastDialog++); - if ( (!href) || ((strncmp(href, "data:", 5) != 0)) ) { - mi->set_sensitive( FALSE ); + insert(*mi, positionOfLastDialog++); + if ((!href) || ((strncmp(href, "data:", 5) != 0))) { + mi->set_sensitive(FALSE); } } } @@ -740,23 +727,22 @@ void ContextMenu::ImageProperties() _desktop->_dlg_mgr->showDialog("ObjectAttributes"); } -Glib::ustring ContextMenu::getImageEditorName(bool is_svg) { +Glib::ustring ContextMenu::getImageEditorName(bool is_svg) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring value; if (!is_svg) { Glib::ustring choices = prefs->getString("/options/bitmapeditor/value"); if (!choices.empty()) { value = choices; - } - else { + } else { value = "gimp"; } } else { Glib::ustring choices = prefs->getString("/options/svgeditor/value"); if (!choices.empty()) { value = choices; - } - else { + } else { value = "inkscape"; } } @@ -769,7 +755,7 @@ void ContextMenu::ImageEdit() _desktop->selection->set(_item); } - GError* errThing = nullptr; + GError *errThing = nullptr; Glib::ustring bmpeditor = getImageEditorName(); Glib::ustring cmdline = bmpeditor; std::string name; @@ -780,9 +766,11 @@ void ContextMenu::ImageEdit() // not Windows command interpreter rules. Thus we need to enclose the // executable path with single quotes. int index = cmdline.find(".exe"); - if ( index < 0 ) index = cmdline.find(".bat"); - if ( index < 0 ) index = cmdline.find(".com"); - if ( index >= 0 ) { + if (index < 0) + index = cmdline.find(".bat"); + if (index < 0) + index = cmdline.find(".com"); + if (index >= 0) { Glib::ustring editorBin = cmdline.substr(0, index + 4).c_str(); Glib::ustring args = cmdline.substr(index + 4, cmdline.length()).c_str(); editorBin.insert(0, "'"); @@ -796,16 +784,16 @@ void ContextMenu::ImageEdit() } #endif - auto itemlist= _desktop->selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = _desktop->selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { Inkscape::XML::Node *ir = (*i)->getRepr(); const gchar *href = ir->attribute("xlink:href"); - if (strncmp (href,"file:",5) == 0) { - // URI to filename conversion - name = Glib::filename_from_uri(href); + if (strncmp(href, "file:", 5) == 0) { + // URI to filename conversion + name = Glib::filename_from_uri(href); } else { - name.append(href); + name.append(href); } if (Glib::path_is_absolute(name)) { @@ -815,9 +803,7 @@ void ContextMenu::ImageEdit() } else { fullname = Glib::build_filename(Glib::get_current_dir(), name); } - if (name.substr(name.find_last_of(".") + 1) == "SVG" || - name.substr(name.find_last_of(".") + 1) == "svg" ) - { + if (name.substr(name.find_last_of(".") + 1) == "SVG" || name.substr(name.find_last_of(".") + 1) == "svg") { cmdline.erase(0, bmpeditor.length()); Glib::ustring svgeditor = getImageEditorName(true); cmdline = svgeditor.append(cmdline); @@ -827,11 +813,11 @@ void ContextMenu::ImageEdit() cmdline.append("'"); } - //g_warning("##Command line: %s\n", cmdline.c_str()); + // g_warning("##Command line: %s\n", cmdline.c_str()); g_spawn_command_line_async(cmdline.c_str(), &errThing); - if ( errThing ) { + if (errThing) { g_warning("Problem launching editor (%d). %s", errThing->code, errThing->message); (_desktop->messageStack())->flash(Inkscape::ERROR_MESSAGE, errThing->message); g_error_free(errThing); @@ -850,7 +836,7 @@ void ContextMenu::ImageEmbed() _desktop->selection->set(_item); } - Inkscape::Verb *verb = Inkscape::Verb::getbyid( "org.inkscape.filter.selected.embed_image" ); + Inkscape::Verb *verb = Inkscape::Verb::getbyid("org.inkscape.filter.selected.embed_image"); if (verb) { SPAction *action = verb->get_action(Inkscape::ActionContext(_desktop)); if (action) { @@ -865,7 +851,7 @@ void ContextMenu::ImageExtract() _desktop->selection->set(_item); } - Inkscape::Verb *verb = Inkscape::Verb::getbyid( "org.inkscape.filter.extract_image" ); + Inkscape::Verb *verb = Inkscape::Verb::getbyid("org.inkscape.filter.extract_image"); if (verb) { SPAction *action = verb->get_action(Inkscape::ActionContext(_desktop)); if (action) { @@ -874,15 +860,15 @@ void ContextMenu::ImageExtract() } } -void ContextMenu::MakeShapeMenu () +void ContextMenu::MakeShapeMenu() { - Gtk::MenuItem* mi; + Gtk::MenuItem *mi; /* Item dialog */ mi = Gtk::manage(new Gtk::MenuItem(_("_Fill and Stroke..."), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::FillSettings)); mi->show(); - insert(*mi,positionOfLastDialog++); + insert(*mi, positionOfLastDialog++); } void ContextMenu::FillSettings() @@ -894,32 +880,32 @@ void ContextMenu::FillSettings() _desktop->_dlg_mgr->showDialog("FillAndStroke"); } -void ContextMenu::MakeTextMenu () +void ContextMenu::MakeTextMenu() { - Gtk::MenuItem* mi; + Gtk::MenuItem *mi; /* Fill and Stroke dialog */ mi = Gtk::manage(new Gtk::MenuItem(_("_Fill and Stroke..."), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::FillSettings)); mi->show(); - insert(*mi,positionOfLastDialog++); + insert(*mi, positionOfLastDialog++); /* Edit Text dialog */ mi = Gtk::manage(new Gtk::MenuItem(_("_Text and Font..."), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::TextSettings)); mi->show(); - insert(*mi,positionOfLastDialog++); + insert(*mi, positionOfLastDialog++); #if WITH_GSPELL /* Spellcheck dialog */ mi = Gtk::manage(new Gtk::MenuItem(_("Check Spellin_g..."), true)); mi->signal_activate().connect(sigc::mem_fun(*this, &ContextMenu::SpellcheckSettings)); mi->show(); - insert(*mi,positionOfLastDialog++); + insert(*mi, positionOfLastDialog++); #endif } -void ContextMenu::TextSettings () +void ContextMenu::TextSettings() { if (_desktop->selection->isEmpty()) { _desktop->selection->set(_item); @@ -928,7 +914,7 @@ void ContextMenu::TextSettings () _desktop->_dlg_mgr->showDialog("TextFont"); } -void ContextMenu::SpellcheckSettings () +void ContextMenu::SpellcheckSettings() { #if WITH_GSPELL if (_desktop->selection->isEmpty()) { @@ -960,7 +946,7 @@ void ContextMenu::ShiftIcons() // get the first MenuItem with an image (i.e. "ImageMenuItem" as named below) std::vector<Gtk::Widget *> children = get_children(); - for (auto child: children) { + for (auto child : children) { if (child->get_name() == "ImageMenuItem") { menuitem = static_cast<Gtk::MenuItem *>(child); content = static_cast<Gtk::Box *>(menuitem->get_child()); diff --git a/src/ui/contextmenu.h b/src/ui/contextmenu.h index 918053312e16581da56d17754fecf66ad626717a..1b110599884a2bfca608050bdab56d0f017840fa 100644 --- a/src/ui/contextmenu.h +++ b/src/ui/contextmenu.h @@ -34,183 +34,184 @@ class Verb; /** * Implements the Inkscape context menu. - * + * * For the context menu implementation, the ContextMenu class stores the object * that was selected in a private data member. This should be fairly safe to do * and a pointer to the SPItem as well as SPObject class are kept. * All callbacks of the context menu entries are implemented as private * functions. - * - * @todo add callbacks to destroy the context menu when it is closed (=key or mouse button pressed out of the scope of the context menu) + * + * @todo add callbacks to destroy the context menu when it is closed (=key or mouse button pressed out of the scope of + * the context menu) */ class ContextMenu : public Gtk::Menu { - public: - /** - * The ContextMenu constructor contains all code to create and show the - * menu entries (aka child widgets). - * - * @param desktop pointer to the desktop the user is currently working on. - * @param item SPItem pointer to the object selected at the time the ContextMenu is created. - */ - ContextMenu(SPDesktop *desktop, SPItem *item); - ~ContextMenu() override; - - /** - * install CSS to shift menu icons into the space reserved for toggles (i.e. check and radio items) - * - * TODO: This should be private but we already re-use this code in ui/interface.cpp which is not c++ified yet. - * In future ContextMenu and the (to be created) class for the menu bar should then be derived from one common base class. - */ - void ShiftIcons(); - private: - SPItem *_item; // pointer to the object selected at the time the ContextMenu is created - SPObject *_object; // pointer to the object selected at the time the ContextMenu is created - SPDesktop *_desktop; //pointer to the desktop the user was currently working on at the time the ContextMenu is created - - int positionOfLastDialog; - - Gtk::MenuItem MIGroup; //menu entry to enter a group - SPObject *_MIGroup_group; // Group to enter when MIGroup is activated - Gtk::MenuItem MIParent; //menu entry to leave a group - - /** - * auxiliary function that adds a separator line in the context menu - */ - Gtk::SeparatorMenuItem* AddSeparator(); - - /** - * Appends a custom menu UI from a verb. - * - * c++ified version of sp_ui_menu_append_item. - * @see sp_ui_menu_append_item_from_verb and synchronize/drop that function when c++ifying other code in interface.cpp - * - * @param show_icon True if an icon should be displayed before the menu item's label - * - */ - void AppendItemFromVerb(Inkscape::Verb *verb, bool show_icon = false); - - /** - * main function which is responsible for creating the context sensitive menu items, - * calls subfunctions below to create the menu entry widgets. - */ - void MakeObjectMenu (); - /** - * creates menu entries for an SP_TYPE_ITEM object - */ - void MakeItemMenu (); - /** - * creates menu entries for a grouped object - */ - void MakeGroupMenu (); - /** - * creates menu entries for an anchor object - */ - void MakeAnchorMenu (); - /** - * creates menu entries for a bitmap image object - */ - void MakeImageMenu (); - /** - * creates menu entries for a shape object - */ - void MakeShapeMenu (); - /** - * creates menu entries for a text object - */ - void MakeTextMenu (); - - void EnterGroup(Gtk::MenuItem* mi); - void LeaveGroup(); - void LockSelected(); - void HideSelected(); - void UnLockBelow(std::vector<SPItem *> items); - void UnHideBelow(std::vector<SPItem *> items); - ////////////////////////////////////////// - //callbacks for the context menu entries of an SP_TYPE_ITEM object - void ItemProperties(); - void ItemSelectThis(); - void ItemMoveTo(); - void SelectSameFillStroke(); - void SelectSameFillColor(); - void SelectSameStrokeColor(); - void SelectSameStrokeStyle(); - void SelectSameObjectType(); - void ItemCreateLink(); - void CreateGroupClip(); - void SetMask(); - void ReleaseMask(); - void SetClip(); - void ReleaseClip(); - ////////////////////////////////////////// - - - /** - * callback, is executed on clicking the anchor "Group" and "Ungroup" menu entry - */ - void ActivateUngroupPopSelection(); - void ActivateUngroup(); - void ActivateGroup(); - - void AnchorLinkProperties(); - /** - * placeholder for callback to be executed on clicking the anchor "Follow link" context menu entry - * @todo add code to follow link externally - */ - void AnchorLinkFollow(); - - /** - * callback, is executed on clicking the anchor "Link remove" menu entry - */ - void AnchorLinkRemove(); - - - /** - * callback, opens the image properties dialog and is executed on clicking the context menu entry with similar name - */ - void ImageProperties(); - - /** - * callback, is executed on clicking the image "Edit Externally" menu entry - */ - void ImageEdit(); - - /** - * auxiliary function that loads the external image editor name from the settings. - */ - Glib::ustring getImageEditorName(bool is_svg = false); - - /** - * callback, is executed on clicking the "Embed Image" menu entry - */ - void ImageEmbed(); - - /** - * callback, is executed on clicking the "Trace Bitmap" menu entry - */ - void ImageTraceBitmap(); - - /** - * callback, is executed on clicking the "Extract Image" menu entry - */ - void ImageExtract(); - - - /** - * callback, is executed on clicking the "Fill and Stroke" menu entry - */ - void FillSettings(); - - - /** - * callback, is executed on clicking the "Text and Font" menu entry - */ - void TextSettings(); - - /** - * callback, is executed on clicking the "Check spelling" menu entry - */ - void SpellcheckSettings(); +public: + /** + * The ContextMenu constructor contains all code to create and show the + * menu entries (aka child widgets). + * + * @param desktop pointer to the desktop the user is currently working on. + * @param item SPItem pointer to the object selected at the time the ContextMenu is created. + */ + ContextMenu(SPDesktop *desktop, SPItem *item); + ~ContextMenu() override; + + /** + * install CSS to shift menu icons into the space reserved for toggles (i.e. check and radio items) + * + * TODO: This should be private but we already re-use this code in ui/interface.cpp which is not c++ified yet. + * In future ContextMenu and the (to be created) class for the menu bar should then be derived from one common + * base class. + */ + void ShiftIcons(); + +private: + SPItem *_item; // pointer to the object selected at the time the ContextMenu is created + SPObject *_object; // pointer to the object selected at the time the ContextMenu is created + SPDesktop *_desktop; // pointer to the desktop the user was currently working on at the time the ContextMenu is + // created + + int positionOfLastDialog; + + Gtk::MenuItem MIGroup; // menu entry to enter a group + SPObject *_MIGroup_group; // Group to enter when MIGroup is activated + Gtk::MenuItem MIParent; // menu entry to leave a group + + /** + * auxiliary function that adds a separator line in the context menu + */ + Gtk::SeparatorMenuItem *AddSeparator(); + + /** + * Appends a custom menu UI from a verb. + * + * c++ified version of sp_ui_menu_append_item. + * @see sp_ui_menu_append_item_from_verb and synchronize/drop that function when c++ifying other code in + * interface.cpp + * + * @param show_icon True if an icon should be displayed before the menu item's label + * + */ + void AppendItemFromVerb(Inkscape::Verb *verb, bool show_icon = false); + + /** + * main function which is responsible for creating the context sensitive menu items, + * calls subfunctions below to create the menu entry widgets. + */ + void MakeObjectMenu(); + /** + * creates menu entries for an SP_TYPE_ITEM object + */ + void MakeItemMenu(); + /** + * creates menu entries for a grouped object + */ + void MakeGroupMenu(); + /** + * creates menu entries for an anchor object + */ + void MakeAnchorMenu(); + /** + * creates menu entries for a bitmap image object + */ + void MakeImageMenu(); + /** + * creates menu entries for a shape object + */ + void MakeShapeMenu(); + /** + * creates menu entries for a text object + */ + void MakeTextMenu(); + + void EnterGroup(Gtk::MenuItem *mi); + void LeaveGroup(); + void LockSelected(); + void HideSelected(); + void UnLockBelow(std::vector<SPItem *> items); + void UnHideBelow(std::vector<SPItem *> items); + ////////////////////////////////////////// + // callbacks for the context menu entries of an SP_TYPE_ITEM object + void ItemProperties(); + void ItemSelectThis(); + void ItemMoveTo(); + void SelectSameFillStroke(); + void SelectSameFillColor(); + void SelectSameStrokeColor(); + void SelectSameStrokeStyle(); + void SelectSameObjectType(); + void ItemCreateLink(); + void CreateGroupClip(); + void SetMask(); + void ReleaseMask(); + void SetClip(); + void ReleaseClip(); + ////////////////////////////////////////// + + /** + * callback, is executed on clicking the anchor "Group" and "Ungroup" menu entry + */ + void ActivateUngroupPopSelection(); + void ActivateUngroup(); + void ActivateGroup(); + + void AnchorLinkProperties(); + /** + * placeholder for callback to be executed on clicking the anchor "Follow link" context menu entry + * @todo add code to follow link externally + */ + void AnchorLinkFollow(); + + /** + * callback, is executed on clicking the anchor "Link remove" menu entry + */ + void AnchorLinkRemove(); + + /** + * callback, opens the image properties dialog and is executed on clicking the context menu entry with similar name + */ + void ImageProperties(); + + /** + * callback, is executed on clicking the image "Edit Externally" menu entry + */ + void ImageEdit(); + + /** + * auxiliary function that loads the external image editor name from the settings. + */ + Glib::ustring getImageEditorName(bool is_svg = false); + + /** + * callback, is executed on clicking the "Embed Image" menu entry + */ + void ImageEmbed(); + + /** + * callback, is executed on clicking the "Trace Bitmap" menu entry + */ + void ImageTraceBitmap(); + + /** + * callback, is executed on clicking the "Extract Image" menu entry + */ + void ImageExtract(); + + /** + * callback, is executed on clicking the "Fill and Stroke" menu entry + */ + void FillSettings(); + + /** + * callback, is executed on clicking the "Text and Font" menu entry + */ + void TextSettings(); + + /** + * callback, is executed on clicking the "Check spelling" menu entry + */ + void SpellcheckSettings(); }; #endif // SEEN_CONTEXT_MENU_H diff --git a/src/ui/control-manager.cpp b/src/ui/control-manager.cpp index 0330b5be37340350e23ee727038804303fb3cddb..29e67835bc820834641daa2cdd5ee9b261d7076f 100644 --- a/src/ui/control-manager.cpp +++ b/src/ui/control-manager.cpp @@ -13,20 +13,20 @@ #include "control-manager.h" #include <algorithm> -#include <set> - #include <glib-object.h> +#include <set> #include "display/sodipodi-ctrl.h" // for SP_TYPE_CTRL -#include "display/sp-ctrlline.h" #include "display/sp-ctrlcurve.h" +#include "display/sp-ctrlline.h" #include "preferences.h" using Inkscape::ControlFlags; namespace { -// Note: The following operator overloads are local to this file at the moment to discourage flag manipulation elsewhere. +// Note: The following operator overloads are local to this file at the moment to discourage flag manipulation +// elsewhere. /* ControlFlags operator |(ControlFlags lhs, ControlFlags rhs) { @@ -34,17 +34,17 @@ ControlFlags operator |(ControlFlags lhs, ControlFlags rhs) } */ -ControlFlags operator &(ControlFlags lhs, ControlFlags 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) +ControlFlags operator^(ControlFlags lhs, ControlFlags rhs) { return static_cast<ControlFlags>(static_cast<int>(lhs) ^ static_cast<int>(rhs)); } -ControlFlags& operator ^=(ControlFlags &lhs, ControlFlags rhs) +ControlFlags &operator^=(ControlFlags &lhs, ControlFlags rhs) { lhs = lhs ^ rhs; return lhs; @@ -90,10 +90,14 @@ private: class PrefListener : public Inkscape::Preferences::Observer { public: - PrefListener(ControlManagerImpl &manager) : Inkscape::Preferences::Observer("/options/grabsize/value"), _mgr(manager) {} + PrefListener(ControlManagerImpl &manager) + : Inkscape::Preferences::Observer("/options/grabsize/value") + , _mgr(manager) + {} ~PrefListener() override = default; - void notify(Inkscape::Preferences::Entry const &val) override { + void notify(Inkscape::Preferences::Entry const &val) override + { int size = val.getIntLimited(3, 1, 7); _mgr.setControlSize(size); } @@ -101,27 +105,26 @@ private: ControlManagerImpl &_mgr; }; - ControlManager &_manager; sigc::signal<void> _sizeChangedSignal; PrefListener _prefHook; int _size; // Size from the grabsize preference int _resize; // Way size should change from grabsize std::vector<SPCanvasItem *> _itemList; - std::map<Inkscape::ControlType, std::vector<unsigned int> > _sizeTable; + std::map<Inkscape::ControlType, std::vector<unsigned int>> _sizeTable; std::map<Inkscape::ControlType, GType> _typeTable; std::map<Inkscape::ControlType, SPCtrlShapeType> _ctrlToShape; std::set<Inkscape::ControlType> _resizeOnSelect; }; -ControlManagerImpl::ControlManagerImpl(ControlManager &manager) : - _manager(manager), - _sizeChangedSignal(), - _prefHook(*this), - _size(3), - _resize(3), - _itemList(), - _sizeTable() +ControlManagerImpl::ControlManagerImpl(ControlManager &manager) + : _manager(manager) + , _sizeChangedSignal() + , _prefHook(*this) + , _size(3) + , _resize(3) + , _itemList() + , _sizeTable() { _typeTable[CTRL_TYPE_UNKNOWN] = SP_TYPE_CTRL; _typeTable[CTRL_TYPE_LPE] = SP_TYPE_CTRL; @@ -156,9 +159,9 @@ ControlManagerImpl::ControlManagerImpl(ControlManager &manager) : // ------- // The size of the controls is determined by the grabsize preference; see the "Handle size" parameter in - // the input/output group, on the "input devices" tab; this parameter ranges from 1 to 7; When selecting a control, we - // increase the size by an additional 2 pixels, if _resizeOnSelect is true (see setSelected()) - + // the input/output group, on the "input devices" tab; this parameter ranges from 1 to 7; When selecting a control, + // we increase the size by an additional 2 pixels, if _resizeOnSelect is true (see setSelected()) + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->addObserver(_prefHook); @@ -193,20 +196,22 @@ ControlManagerImpl::ControlManagerImpl(ControlManager &manager) : } { unsigned int sizes[] = {3, 5, 7, 9, 11, 13, 15}; - _sizeTable[CTRL_TYPE_NODE_SMOOTH] = std::vector<unsigned int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); - _sizeTable[CTRL_TYPE_NODE_SYMETRICAL] = std::vector<unsigned int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); + _sizeTable[CTRL_TYPE_NODE_SMOOTH] = + std::vector<unsigned int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); + _sizeTable[CTRL_TYPE_NODE_SYMETRICAL] = + std::vector<unsigned int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); } { unsigned int sizes[] = {1, 1, 1, 1, 1, 1, 1}; - _sizeTable[CTRL_TYPE_INVISIPOINT] = std::vector<unsigned int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); + _sizeTable[CTRL_TYPE_INVISIPOINT] = + std::vector<unsigned int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); } { - unsigned int sizes[] = { 5, 7, 9, 11, 13, 15, 17 }; + unsigned int sizes[] = {5, 7, 9, 11, 13, 15, 17}; _sizeTable[CTRL_TYPE_LPE] = std::vector<unsigned int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); } } - void ControlManagerImpl::setControlSize(int size, bool force) { if ((size < 1) || (size > 7)) { @@ -214,8 +219,7 @@ void ControlManagerImpl::setControlSize(int size, bool force) } else if (force || (size != _size)) { _size = size; - for (auto & it : _itemList) - { + for (auto &it : _itemList) { if (it) { updateItem(it); } @@ -229,44 +233,25 @@ SPCanvasItem *ControlManagerImpl::createControl(SPCanvasGroup *parent, ControlTy { SPCanvasItem *item = nullptr; unsigned int targetSize = _sizeTable[type][_size - 1]; - switch (type) - { + switch (type) { case CTRL_TYPE_ADJ_HANDLE: - item = sp_canvas_item_new(parent, SP_TYPE_CTRL, - "shape",SP_CTRL_SHAPE_CIRCLE, - "size", targetSize, - "filled", 1, - "fill_color", 0xffffff7f, - "stroked", 1, - "stroke_color", 0x0000ff7f, - NULL); + item = sp_canvas_item_new(parent, SP_TYPE_CTRL, "shape", SP_CTRL_SHAPE_CIRCLE, "size", targetSize, "filled", + 1, "fill_color", 0xffffff7f, "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", 0xffffff7f, - "stroked", 1, - "stroke_color", 0x000000ff, - NULL); + item = sp_canvas_item_new(parent, SP_TYPE_CTRL, "size", targetSize, "filled", 1, "fill_color", 0xffffff7f, + "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: - { + 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); + item = sp_canvas_item_new(parent, SP_TYPE_CTRL, "shape", shape, "size", targetSize, NULL); break; } case CTRL_TYPE_INVISIPOINT: - item = sp_canvas_item_new(parent, SP_TYPE_CTRL, - "shape", SP_CTRL_SHAPE_SQUARE, - "size", targetSize, - NULL); + item = sp_canvas_item_new(parent, SP_TYPE_CTRL, "shape", SP_CTRL_SHAPE_SQUARE, "size", targetSize, NULL); break; case CTRL_TYPE_UNKNOWN: case CTRL_TYPE_LPE: @@ -281,7 +266,7 @@ SPCanvasItem *ControlManagerImpl::createControl(SPCanvasGroup *parent, ControlTy void ControlManagerImpl::track(SPCanvasItem *item) { - g_object_weak_ref( G_OBJECT(item), ControlManagerImpl::thingFinalized, this ); + g_object_weak_ref(G_OBJECT(item), ControlManagerImpl::thingFinalized, this); _itemList.push_back(item); @@ -329,7 +314,7 @@ bool ControlManagerImpl::setControlResize(SPCanvasItem *item, int ctrlResize) // or guides, which are 1 px wide. It is not possible to accurately center a control to them if the // control has an even width). ctrlResize should therefore be an even number, such that the sum (targetSize) // is also odd - if(item) { + if (item) { item->ctrlResize = ctrlResize; unsigned int targetSize = _sizeTable[item->ctrlType][_size - 1] + item->ctrlResize; g_object_set(item, "size", targetSize, NULL); @@ -365,26 +350,21 @@ void ControlManagerImpl::thingFinalized(gpointer data, GObject *wasObj) void ControlManagerImpl::thingFinalized(GObject *wasObj) { SPCanvasItem *wasItem = reinterpret_cast<SPCanvasItem *>(wasObj); - if (wasItem) - { + if (wasItem) { std::vector<SPCanvasItem *>::iterator it = std::find(_itemList.begin(), _itemList.end(), wasItem); - if (it != _itemList.end()) - { + if (it != _itemList.end()) { _itemList.erase(it); } } } - // ---------------------------------------------------- -ControlManager::ControlManager() : - _impl(new ControlManagerImpl(*this)) -{ -} +ControlManager::ControlManager() + : _impl(new ControlManagerImpl(*this)) +{} -ControlManager::~ControlManager() -= default; +ControlManager::~ControlManager() = default; ControlManager &ControlManager::getManager() { @@ -393,7 +373,6 @@ ControlManager &ControlManager::getManager() return instance; } - SPCanvasItem *ControlManager::createControl(SPCanvasGroup *parent, ControlType type) { return _impl->createControl(parent, type); @@ -405,14 +384,16 @@ SPCtrlLine *ControlManager::createControlLine(SPCanvasGroup *parent, CtrlLineTyp 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->setRgba32((type == CTLINE_PRIMARY) + ? LINE_COLOR_PRIMARY + : (type == CTLINE_SECONDARY) ? LINE_COLOR_SECONDARY : LINE_COLOR_TERTIARY); line->setCoords(0, 0, 0, 0); } return line; } -SPCtrlLine *ControlManager::createControlLine(SPCanvasGroup *parent, Geom::Point const &p1, Geom::Point const &p2, CtrlLineType type) +SPCtrlLine *ControlManager::createControlLine(SPCanvasGroup *parent, Geom::Point const &p1, Geom::Point const &p2, + CtrlLineType type) { SPCtrlLine *line = createControlLine(parent, type); if (line) { @@ -421,14 +402,16 @@ SPCtrlLine *ControlManager::createControlLine(SPCanvasGroup *parent, Geom::Point 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 *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, nullptr)); 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->setRgba32((type == CTLINE_PRIMARY) + ? LINE_COLOR_PRIMARY + : (type == CTLINE_SECONDARY) ? LINE_COLOR_SECONDARY : LINE_COLOR_TERTIARY); line->setCoords(p0, p1, p2, p3); } return line; diff --git a/src/ui/control-manager.h b/src/ui/control-manager.h index 12ac19ae70c82003176f2c4b6a76026bbad0d2dd..0dc4c188956f9bbd3197a9339070110f50d9e2ee 100644 --- a/src/ui/control-manager.h +++ b/src/ui/control-manager.h @@ -22,8 +22,7 @@ struct SPCanvasItem; struct SPCtrlLine; struct SPCtrlCurve; -namespace Geom -{ +namespace Geom { class Point; @@ -31,19 +30,18 @@ class Point; namespace Inkscape { -enum CtrlLineType { +enum CtrlLineType +{ CTLINE_PRIMARY, CTLINE_SECONDARY, CTLINE_TERTIARY, }; - class ControlManagerImpl; class ControlManager { public: - static ControlManager &getManager(); ~ControlManager(); @@ -54,9 +52,11 @@ public: SPCtrlLine *createControlLine(SPCanvasGroup *parent, CtrlLineType type = CTLINE_PRIMARY); - SPCtrlLine *createControlLine(SPCanvasGroup *parent, Geom::Point const &p1, Geom::Point const &p2, 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); + 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); diff --git a/src/ui/control-types.h b/src/ui/control-types.h index 896ccf8eeb306ab4e81b68dfc79f3a77e5d5d8a1..27f9ddf67cf9262b432c992f0c702c4184cda3e2 100644 --- a/src/ui/control-types.h +++ b/src/ui/control-types.h @@ -11,11 +11,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -namespace Inkscape -{ +namespace Inkscape { // Rough initial set. Most likely needs refinement. -enum ControlType { +enum ControlType +{ CTRL_TYPE_UNKNOWN, CTRL_TYPE_ADJ_HANDLE, CTRL_TYPE_ANCHOR, @@ -35,7 +35,8 @@ enum ControlType { /** * Flags for internal representation/tracking. */ -enum ControlFlags { +enum ControlFlags +{ CTRL_FLAG_NORMAL = 0, CTRL_FLAG_ACTIVE = 1 << 0, CTRL_FLAG_PRELIGHT = 1 << 1, diff --git a/src/ui/desktop/menubar.cpp b/src/ui/desktop/menubar.cpp index 7bc80387b95181fb8f15f46c1039771412d12670..3e637d7158e1ebe5e13b40b78bed7fa99654687f 100644 --- a/src/ui/desktop/menubar.cpp +++ b/src/ui/desktop/menubar.cpp @@ -18,26 +18,21 @@ * */ -#include <gtkmm.h> #include <glibmm/i18n.h> - +#include <gtkmm.h> #include <iostream> -#include "inkscape.h" +#include "helper/action-context.h" +#include "helper/action.h" #include "inkscape-application.h" // Open recent - +#include "inkscape.h" #include "message-context.h" -#include "shortcuts.h" - -#include "helper/action.h" -#include "helper/action-context.h" - #include "object/sp-namedview.h" - +#include "shortcuts.h" #include "ui/contextmenu.h" // Shift to make room for icons #include "ui/icon-loader.h" +#include "ui/uxmanager.h" // To Do: Convert to actions #include "ui/view/view.h" -#include "ui/uxmanager.h" // To Do: Convert to actions #ifdef GDK_WINDOWING_QUARTZ #include <gtkosxapplication.h> @@ -48,7 +43,6 @@ std::vector<std::pair<std::pair<unsigned int, Gtk::MenuItem *>, Inkscape::UI::View::View *>> menuitems; unsigned int lastverb = -1; - /** * Get menu item (if it was registered in `menuitems`) */ @@ -79,15 +73,13 @@ static gboolean sync_menubar(gpointer = nullptr) #endif // Sets tip -static void -select_action(SPAction *action) +static void select_action(SPAction *action) { sp_action_get_view(action)->tipsMessageContext()->set(Inkscape::NORMAL_MESSAGE, action->tip); } // Clears tip -static void -deselect_action(SPAction *action) +static void deselect_action(SPAction *action) { sp_action_get_view(action)->tipsMessageContext()->clear(); } @@ -132,23 +124,23 @@ static void set_menuitems(unsigned int emitting_verb, bool value) } // Change label name (used in the Undo/Redo menu items). -static void -set_name(Glib::ustring const &name, Gtk::MenuItem* menuitem) +static void set_name(Glib::ustring const &name, Gtk::MenuItem *menuitem) { if (menuitem) { - Gtk::Widget* widget = menuitem->get_child(); + Gtk::Widget *widget = menuitem->get_child(); // Label is either child of menuitem - Gtk::Label* label = dynamic_cast<Gtk::Label*>(widget); + Gtk::Label *label = dynamic_cast<Gtk::Label *>(widget); // Or wrapped inside a box which is a child of menuitem (if with icon). if (!label) { - Gtk::Box* box = dynamic_cast<Gtk::Box*>(widget); + Gtk::Box *box = dynamic_cast<Gtk::Box *>(widget); if (box) { - std::vector<Gtk::Widget*> children = box->get_children(); - for (auto child: children) { - label = dynamic_cast<Gtk::Label*>(child); - if (label) break; + std::vector<Gtk::Widget *> children = box->get_children(); + for (auto child : children) { + label = dynamic_cast<Gtk::Label *>(child); + if (label) + break; } } } @@ -169,22 +161,18 @@ set_name(Glib::ustring const &name, Gtk::MenuItem* menuitem) * * TODO: This code is called everytime a menu is opened. We can certainly find a way to call it once. */ -static void -shift_icons(Gtk::Menu* menu) +static void shift_icons(Gtk::Menu *menu) { - ContextMenu *contextmenu = static_cast<ContextMenu*>(menu); + ContextMenu *contextmenu = static_cast<ContextMenu *>(menu); contextmenu->ShiftIcons(); } // ================= MenuItem ==================== -Gtk::MenuItem* -build_menu_item_from_verb(SPAction* action, - bool show_icon, - bool radio = false, - Gtk::RadioMenuItem::Group *group = nullptr) +Gtk::MenuItem *build_menu_item_from_verb(SPAction *action, bool show_icon, bool radio = false, + Gtk::RadioMenuItem::Group *group = nullptr) { - Gtk::MenuItem* menuitem = nullptr; + Gtk::MenuItem *menuitem = nullptr; if (radio) { menuitem = Gtk::manage(new Gtk::RadioMenuItem(*group)); @@ -192,34 +180,33 @@ build_menu_item_from_verb(SPAction* action, menuitem = Gtk::manage(new Gtk::MenuItem()); } - Gtk::AccelLabel* label = Gtk::manage(new Gtk::AccelLabel(action->name, true)); + Gtk::AccelLabel *label = Gtk::manage(new Gtk::AccelLabel(action->name, true)); label->set_xalign(0.0); label->set_accel_widget(*menuitem); - sp_shortcut_add_accelerator((GtkWidget*)menuitem->gobj(), sp_shortcut_get_primary(action->verb)); + sp_shortcut_add_accelerator((GtkWidget *)menuitem->gobj(), sp_shortcut_get_primary(action->verb)); // If there is an image associated with the action, we can add it as an icon for the menu item. if (show_icon && action->image) { - menuitem->set_name("ImageMenuItem"); // custom name to identify our "ImageMenuItems" - Gtk::Image* image = Gtk::manage(sp_get_icon_image(action->image, Gtk::ICON_SIZE_MENU)); + menuitem->set_name("ImageMenuItem"); // custom name to identify our "ImageMenuItems" + Gtk::Image *image = Gtk::manage(sp_get_icon_image(action->image, Gtk::ICON_SIZE_MENU)); // Create a box to hold icon and label as Gtk::MenuItem derives from GtkBin and can // only hold one child Gtk::Box *box = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL)); box->pack_start(*image, false, false, 0); - box->pack_start(*label, true, true, 0); + box->pack_start(*label, true, true, 0); menuitem->add(*box); } else { menuitem->add(*label); } menuitem->signal_activate().connect( - sigc::bind<Gtk::MenuItem*, SPAction*>(sigc::ptr_fun(&item_activate), menuitem, action)); - menuitem->signal_select().connect( sigc::bind<SPAction*>(sigc::ptr_fun(&select_action), action)); - menuitem->signal_deselect().connect(sigc::bind<SPAction*>(sigc::ptr_fun(&deselect_action), action)); + sigc::bind<Gtk::MenuItem *, SPAction *>(sigc::ptr_fun(&item_activate), menuitem, action)); + menuitem->signal_select().connect(sigc::bind<SPAction *>(sigc::ptr_fun(&select_action), action)); + menuitem->signal_deselect().connect(sigc::bind<SPAction *>(sigc::ptr_fun(&deselect_action), action)); action->signal_set_sensitive.connect( - sigc::bind<0>(sigc::ptr_fun(>k_widget_set_sensitive), (GtkWidget*)menuitem->gobj())); - action->signal_set_name.connect( - sigc::bind<Gtk::MenuItem*>(sigc::ptr_fun(&set_name), menuitem)); + sigc::bind<0>(sigc::ptr_fun(>k_widget_set_sensitive), (GtkWidget *)menuitem->gobj())); + action->signal_set_name.connect(sigc::bind<Gtk::MenuItem *>(sigc::ptr_fun(&set_name), menuitem)); // initialize sensitivity with verb default sp_action_set_sensitive(action, action->verb->get_default_sensitive()); @@ -249,13 +236,12 @@ bool getStateFromPref(SPDesktop *dt, Glib::ustring item) } // I wonder if this can be done without hard coding names. -static void -checkitem_update(Gtk::CheckMenuItem* menuitem, SPAction* action) +static void checkitem_update(Gtk::CheckMenuItem *menuitem, SPAction *action) { bool active = false; if (action && action->id) { Glib::ustring id = action->id; - SPDesktop* dt = static_cast<SPDesktop*>(sp_action_get_view(action)); + SPDesktop *dt = static_cast<SPDesktop *>(sp_action_get_view(action)); if (id == "ToggleGrid") { active = dt->gridsEnabled(); @@ -269,11 +255,9 @@ checkitem_update(Gtk::CheckMenuItem* menuitem, SPAction* action) } else if (id == "ToggleRotationLock") { active = dt->get_rotation_lock(); - } - else if (id == "ViewCmsToggle") { + } else if (id == "ViewCmsToggle") { active = dt->colorProfAdjustEnabled(); - } - else if (id == "ViewSplitModeToggle") { + } else if (id == "ViewSplitModeToggle") { active = dt->splitMode(); } else if (id == "ViewXRayToggle") { @@ -298,14 +282,14 @@ checkitem_update(Gtk::CheckMenuItem* menuitem, SPAction* action) active = getStateFromPref(dt, "scrollbars"); } else if (id == "TogglePalette") { - active = getStateFromPref(dt, "panels"); // Rename? + active = getStateFromPref(dt, "panels"); // Rename? } else if (id == "ToggleStatusbar") { active = getStateFromPref(dt, "statusbar"); } else if (id == "FlipHorizontal") { active = dt->is_flipped(SPDesktop::FLIP_HORIZONTAL); - + } else if (id == "FlipVertical") { active = dt->is_flipped(SPDesktop::FLIP_VERTICAL); @@ -319,8 +303,7 @@ checkitem_update(Gtk::CheckMenuItem* menuitem, SPAction* action) } } -static Gtk::CheckMenuItem* -build_menu_check_item_from_verb(SPAction* action) +static Gtk::CheckMenuItem *build_menu_check_item_from_verb(SPAction *action) { // This does not work for some reason! // Gtk::CheckMenuItem* menuitem = Gtk::manage(new Gtk::CheckMenuItem(action->name, true)); @@ -328,23 +311,21 @@ build_menu_check_item_from_verb(SPAction* action) GtkWidget *item = gtk_check_menu_item_new_with_mnemonic(action->name); sp_shortcut_add_accelerator(item, sp_shortcut_get_primary(action->verb)); - Gtk::CheckMenuItem* menuitem = Gtk::manage(Glib::wrap(GTK_CHECK_MENU_ITEM(item))); + Gtk::CheckMenuItem *menuitem = Gtk::manage(Glib::wrap(GTK_CHECK_MENU_ITEM(item))); // Set initial state before connecting signals. checkitem_update(menuitem, action); menuitem->signal_toggled().connect( - sigc::bind<Gtk::CheckMenuItem*, SPAction*>(sigc::ptr_fun(&item_activate), menuitem, action)); - menuitem->signal_select().connect( sigc::bind<SPAction*>(sigc::ptr_fun(&select_action), action)); - menuitem->signal_deselect().connect(sigc::bind<SPAction*>(sigc::ptr_fun(&deselect_action), action)); + sigc::bind<Gtk::CheckMenuItem *, SPAction *>(sigc::ptr_fun(&item_activate), menuitem, action)); + menuitem->signal_select().connect(sigc::bind<SPAction *>(sigc::ptr_fun(&select_action), action)); + menuitem->signal_deselect().connect(sigc::bind<SPAction *>(sigc::ptr_fun(&deselect_action), action)); return menuitem; } - // ================= Tasks Submenu ============== -static void -task_activated(SPDesktop* dt, int number) +static void task_activated(SPDesktop *dt, int number) { Inkscape::UI::UXManager::getInstance()->setTask(dt, number); @@ -355,69 +336,59 @@ task_activated(SPDesktop* dt, int number) } // Sets tip -static void -select_task(SPDesktop* dt, Glib::ustring tip) +static void select_task(SPDesktop *dt, Glib::ustring tip) { dt->tipsMessageContext()->set(Inkscape::NORMAL_MESSAGE, tip.c_str()); } // Clears tip -static void -deselect_task(SPDesktop* dt) +static void deselect_task(SPDesktop *dt) { dt->tipsMessageContext()->clear(); } -static void -add_tasks(Gtk::MenuShell* menu, SPDesktop* dt) +static void add_tasks(Gtk::MenuShell *menu, SPDesktop *dt) { - const Glib::ustring data[3][2] = { - { C_("Interface setup", "Default"), _("Default interface setup") }, - { C_("Interface setup", "Custom"), _("Setup for custom task") }, - { C_("Interface setup", "Wide"), _("Setup for widescreen work") } - }; + const Glib::ustring data[3][2] = {{C_("Interface setup", "Default"), _("Default interface setup")}, + {C_("Interface setup", "Custom"), _("Setup for custom task")}, + {C_("Interface setup", "Wide"), _("Setup for widescreen work")}}; int active = Inkscape::UI::UXManager::getInstance()->getDefaultTask(dt); Gtk::RadioMenuItem::Group group; for (unsigned int i = 0; i < 3; ++i) { - - Gtk::RadioMenuItem* menuitem = Gtk::manage(new Gtk::RadioMenuItem(group, data[i][0])); + Gtk::RadioMenuItem *menuitem = Gtk::manage(new Gtk::RadioMenuItem(group, data[i][0])); if (menuitem) { if (active == i) { menuitem->set_active(true); } - menuitem->signal_toggled().connect( - sigc::bind<SPDesktop*, int>(sigc::ptr_fun(&task_activated), dt, i)); + menuitem->signal_toggled().connect(sigc::bind<SPDesktop *, int>(sigc::ptr_fun(&task_activated), dt, i)); menuitem->signal_select().connect( - sigc::bind<SPDesktop*, Glib::ustring>(sigc::ptr_fun(&select_task), dt, data[i][1])); - menuitem->signal_deselect().connect( - sigc::bind<SPDesktop*>(sigc::ptr_fun(&deselect_task),dt)); + sigc::bind<SPDesktop *, Glib::ustring>(sigc::ptr_fun(&select_task), dt, data[i][1])); + menuitem->signal_deselect().connect(sigc::bind<SPDesktop *>(sigc::ptr_fun(&deselect_task), dt)); menu->append(*menuitem); } } } - -static void -sp_recent_open(Gtk::RecentChooser* recentchooser) +static void sp_recent_open(Gtk::RecentChooser *recentchooser) { Glib::ustring uri = recentchooser->get_current_uri(); Glib::RefPtr<Gio::File> file = Gio::File::create_for_uri(uri.raw()); - ConcreteInkscapeApplication<Gtk::Application>* app = &(ConcreteInkscapeApplication<Gtk::Application>::get_instance()); + ConcreteInkscapeApplication<Gtk::Application> *app = + &(ConcreteInkscapeApplication<Gtk::Application>::get_instance()); app->create_window(file); } // =================== Main Menu ================ // Recursively build menu and submenus. -void -build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::View* view, bool show_icons = true) +void build_menu(Gtk::MenuShell *menu, Inkscape::XML::Node *xml, Inkscape::UI::View::View *view, bool show_icons = true) { if (menu == nullptr) { std::cerr << "build_menu: menu is nullptr" << std::endl; @@ -436,16 +407,14 @@ build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::V Gtk::RadioMenuItem::Group group; for (auto menu_ptr = xml; menu_ptr != nullptr; menu_ptr = menu_ptr->next()) { - if (menu_ptr->name()) { - // show menu icons for current item? bool show_icons_curr = show_icons; - if (show_icons_pref == 1) { // show all icons per global pref + if (show_icons_pref == 1) { // show all icons per global pref show_icons_curr = true; - } else if (show_icons_pref == -1) { // hide all icons per global pref + } else if (show_icons_pref == -1) { // hide all icons per global pref show_icons_curr = false; - } else { // set according to 'show-icons' attribute in theme's XML file; value is fully inherited + } else { // set according to 'show-icons' attribute in theme's XML file; value is fully inherited const char *str = menu_ptr->attribute("show-icons"); if (str) { Glib::ustring ustr = str; @@ -454,8 +423,8 @@ build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::V } else if (ustr == "false") { show_icons_curr = false; } else { - std::cerr << "build_menu: invalid value for 'show-icons' (use 'true' or 'false')." - << ustr << std::endl; + std::cerr << "build_menu: invalid value for 'show-icons' (use 'true' or 'false')." << ustr + << std::endl; } } } @@ -474,14 +443,13 @@ build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::V continue; } - Gtk::MenuItem* menuitem = Gtk::manage(new Gtk::MenuItem(_(name), true)); - Gtk::Menu* submenu = Gtk::manage(new Gtk::Menu()); + Gtk::MenuItem *menuitem = Gtk::manage(new Gtk::MenuItem(_(name), true)); + Gtk::Menu *submenu = Gtk::manage(new Gtk::Menu()); build_menu(submenu, menu_ptr->firstChild(), view, show_icons_curr); menuitem->set_submenu(*submenu); menu->append(*menuitem); - submenu->signal_map().connect( - sigc::bind<Gtk::Menu*>(sigc::ptr_fun(&shift_icons), submenu)); + submenu->signal_map().connect(sigc::bind<Gtk::Menu *>(sigc::ptr_fun(&shift_icons), submenu)); continue; } @@ -507,14 +475,13 @@ build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::V Inkscape::Verb *verb = Inkscape::Verb::getbyid(verb_name.c_str()); if (verb != nullptr && verb->get_code() != SP_VERB_NONE) { - #ifdef GDK_WINDOWING_QUARTZ if (verb->get_code() == SP_VERB_FILE_QUIT) { continue; } #endif - SPAction* action = verb->get_action(Inkscape::ActionContext(view)); + SPAction *action = verb->get_action(Inkscape::ActionContext(view)); if (menu_ptr->attribute("check") != nullptr) { Gtk::MenuItem *menuitem = build_menu_check_item_from_verb(action); if (menuitem) { @@ -524,10 +491,10 @@ build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::V menu->append(*menuitem); } } else if (menu_ptr->attribute("radio") != nullptr) { - Gtk::MenuItem* menuitem = build_menu_item_from_verb(action, show_icons_curr, true, &group); + Gtk::MenuItem *menuitem = build_menu_item_from_verb(action, show_icons_curr, true, &group); if (menuitem) { if (menu_ptr->attribute("default") != nullptr) { - auto radiomenuitem = dynamic_cast<Gtk::RadioMenuItem*>(menuitem); + auto radiomenuitem = dynamic_cast<Gtk::RadioMenuItem *>(menuitem); if (radiomenuitem) { radiomenuitem->set_active(true); } @@ -538,7 +505,7 @@ build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::V menu->append(*menuitem); } } else { - Gtk::MenuItem* menuitem = build_menu_item_from_verb(action, show_icons_curr); + Gtk::MenuItem *menuitem = build_menu_item_from_verb(action, show_icons_curr); if (menuitem) { menu->append(*menuitem); } @@ -555,9 +522,9 @@ build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::V } } else if (true #ifndef WITH_GSPELL - && strcmp(verb_name.c_str(), "DialogSpellcheck") != 0 + && strcmp(verb_name.c_str(), "DialogSpellcheck") != 0 #endif - ) { + ) { std::cerr << "build_menu: no verb with id: " << verb_name << std::endl; } } @@ -567,12 +534,11 @@ build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::V // This is used only for wide-screen vs non-wide-screen displays. // The code should be rewritten to use actions like everything else here. if (name == "task-checkboxes") { - add_tasks(menu, static_cast<SPDesktop*>(view)); + add_tasks(menu, static_cast<SPDesktop *>(view)); continue; } if (name == "recent-file-list") { - // Filter recent files to those already opened in Inkscape. Glib::RefPtr<Gtk::RecentFilter> recentfilter = Gtk::RecentFilter::create(); recentfilter->add_application(g_get_prgname()); @@ -582,7 +548,7 @@ build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::V recentfilter->add_application("inkscape.exe"); #endif - Gtk::RecentChooserMenu* recentchoosermenu = Gtk::manage(new Gtk::RecentChooserMenu()); + Gtk::RecentChooserMenu *recentchoosermenu = Gtk::manage(new Gtk::RecentChooserMenu()); int max = Inkscape::Preferences::get()->getInt("/options/maxrecentdocuments/value"); recentchoosermenu->set_limit(max); recentchoosermenu->set_sort_type(Gtk::RECENT_SORT_MRU); // Sort most recent first. @@ -590,24 +556,22 @@ build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::V recentchoosermenu->set_show_not_found(false); recentchoosermenu->add_filter(recentfilter); recentchoosermenu->signal_item_activated().connect( - sigc::bind<Gtk::RecentChooserMenu*>(sigc::ptr_fun(&sp_recent_open), recentchoosermenu)); + sigc::bind<Gtk::RecentChooserMenu *>(sigc::ptr_fun(&sp_recent_open), recentchoosermenu)); - Gtk::MenuItem* menuitem = Gtk::manage(new Gtk::MenuItem(_("Open _Recent"), true)); + Gtk::MenuItem *menuitem = Gtk::manage(new Gtk::MenuItem(_("Open _Recent"), true)); menuitem->set_submenu(*recentchoosermenu); menu->append(*menuitem); continue; } if (name == "separator") { - Gtk::MenuItem* menuitem = Gtk::manage(new Gtk::SeparatorMenuItem()); + Gtk::MenuItem *menuitem = Gtk::manage(new Gtk::SeparatorMenuItem()); menu->append(*menuitem); continue; } // Comments and items handled elsewhere. - if (name == "comment" || - name == "filters-list" || - name == "effects-list" ) { + if (name == "comment" || name == "filters-list" || name == "effects-list") { continue; } @@ -619,16 +583,14 @@ build_menu(Gtk::MenuShell* menu, Inkscape::XML::Node* xml, Inkscape::UI::View::V } } -Gtk::MenuBar* -build_menubar(Inkscape::UI::View::View* view) +Gtk::MenuBar *build_menubar(Inkscape::UI::View::View *view) { - Gtk::MenuBar* menubar = Gtk::manage(new Gtk::MenuBar()); + Gtk::MenuBar *menubar = Gtk::manage(new Gtk::MenuBar()); build_menu(menubar, INKSCAPE.get_menus()->parent(), view); SP_ACTIVE_DESKTOP->_menu_update.connect(sigc::ptr_fun(&set_menuitems)); return menubar; } - /* Local Variables: mode:c++ diff --git a/src/ui/desktop/menubar.h b/src/ui/desktop/menubar.h index 065fb673bf790e2a42a03bf4b741670ae5ecd94d..7e72fedb238ebbb728297e4a9056e05898080549 100644 --- a/src/ui/desktop/menubar.h +++ b/src/ui/desktop/menubar.h @@ -18,20 +18,20 @@ */ namespace Gtk { - class MenuBar; - class MenuItem; -} +class MenuBar; +class MenuItem; +} // namespace Gtk namespace Inkscape { namespace UI { namespace View { - class View; -} -} +class View; } +} // namespace UI +} // namespace Inkscape bool getStateFromPref(SPDesktop *dt, Glib::ustring item); -Gtk::MenuBar* build_menubar(Inkscape::UI::View::View* view); +Gtk::MenuBar *build_menubar(Inkscape::UI::View::View *view); Gtk::MenuItem *get_menu_item_for_verb(unsigned int verb, Inkscape::UI::View::View *); #endif // SEEN_DESKTOP_MENUBAR_H diff --git a/src/ui/dialog-events.cpp b/src/ui/dialog-events.cpp index 3b9b6cde2e01e60a97d5bab72f4c0500b03f627c..1c74a2ab5648522545e2fd3e207b4b0b4f3f6156 100644 --- a/src/ui/dialog-events.cpp +++ b/src/ui/dialog-events.cpp @@ -12,44 +12,42 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/dialog-events.h" + #include <gtkmm/entry.h> #include <gtkmm/window.h> #include "desktop.h" -#include "inkscape.h" #include "include/macros.h" -#include "ui/dialog-events.h" +#include "inkscape.h" #include "ui/tools/tool-base.h" - /** * Remove focus from window to whoever it is transient for. */ void sp_dialog_defocus_cpp(Gtk::Window *win) { - //find out the document window we're transient for + // find out the document window we're transient for Gtk::Window *w = win->get_transient_for(); - //switch to it + // switch to it if (w) { w->present(); } } -void -sp_dialog_defocus (GtkWindow *win) +void sp_dialog_defocus(GtkWindow *win) { GtkWindow *w; - //find out the document window we're transient for + // find out the document window we're transient for w = gtk_window_get_transient_for(GTK_WINDOW(win)); - //switch to it + // switch to it if (w) { - gtk_window_present (w); + gtk_window_present(w); } } - /** * Callback to defocus a widget's parent dialog. */ @@ -58,41 +56,31 @@ void sp_dialog_defocus_callback_cpp(Gtk::Entry *e) sp_dialog_defocus_cpp(dynamic_cast<Gtk::Window *>(e->get_toplevel())); } -void -sp_dialog_defocus_callback (GtkWindow * /*win*/, gpointer data) +void sp_dialog_defocus_callback(GtkWindow * /*win*/, gpointer data) { - sp_dialog_defocus( GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(data))) ); + sp_dialog_defocus(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(data)))); } - - -void -sp_dialog_defocus_on_enter_cpp (Gtk::Entry *e) +void sp_dialog_defocus_on_enter_cpp(Gtk::Entry *e) { e->signal_activate().connect(sigc::bind(sigc::ptr_fun(&sp_dialog_defocus_callback_cpp), e)); } -void -sp_dialog_defocus_on_enter (GtkWidget *w) +void sp_dialog_defocus_on_enter(GtkWidget *w) { - g_signal_connect ( G_OBJECT (w), "activate", - G_CALLBACK (sp_dialog_defocus_callback), w ); + g_signal_connect(G_OBJECT(w), "activate", G_CALLBACK(sp_dialog_defocus_callback), w); } - - -gboolean -sp_dialog_event_handler (GtkWindow *win, GdkEvent *event, gpointer data) +gboolean sp_dialog_event_handler(GtkWindow *win, GdkEvent *event, gpointer data) { gboolean ret = FALSE; switch (event->type) { - case GDK_KEY_PRESS: - switch (Inkscape::UI::Tools::get_latin_keyval (&event->key)) { + switch (Inkscape::UI::Tools::get_latin_keyval(&event->key)) { case GDK_KEY_Escape: - sp_dialog_defocus (win); + sp_dialog_defocus(win); ret = TRUE; break; case GDK_KEY_F4: @@ -100,7 +88,6 @@ sp_dialog_event_handler (GtkWindow *win, GdkEvent *event, gpointer data) case GDK_KEY_W: // close dialog if (MOD__CTRL_ONLY(event)) { - /* this code sends a delete_event to the dialog, * instead of just destroying it, so that the * dialog can do some housekeeping, such as remember @@ -109,11 +96,11 @@ sp_dialog_event_handler (GtkWindow *win, GdkEvent *event, gpointer data) GdkEventAny event; GtkWidget *widget = GTK_WIDGET(win); event.type = GDK_DELETE; - event.window = gtk_widget_get_window (widget); + event.window = gtk_widget_get_window(widget); event.send_event = TRUE; - g_object_ref (G_OBJECT (event.window)); - gtk_main_do_event(reinterpret_cast<GdkEvent*>(&event)); - g_object_unref (G_OBJECT (event.window)); + g_object_ref(G_OBJECT(event.window)); + gtk_main_do_event(reinterpret_cast<GdkEvent *>(&event)); + g_object_unref(G_OBJECT(event.window)); ret = TRUE; } @@ -121,16 +108,12 @@ sp_dialog_event_handler (GtkWindow *win, GdkEvent *event, gpointer data) default: // pass keypress to the canvas break; } - default: - ; + default:; } return ret; - } - - /** * Make the argument dialog transient to the currently active document * window. @@ -138,12 +121,12 @@ sp_dialog_event_handler (GtkWindow *win, GdkEvent *event, gpointer data) void sp_transientize(GtkWidget *dialog) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); -#ifndef _WIN32 // FIXME: Temporary Win32 special code to enable transient dialogs +#ifndef _WIN32 // FIXME: Temporary Win32 special code to enable transient dialogs // _set_skip_taskbar_hint makes transient dialogs NON-transient! When dialogs // are made transient (_set_transient_for), they are already removed from // the taskbar in Win32. - if (prefs->getBool( "/options/dialogsskiptaskbar/value")) { - gtk_window_set_skip_taskbar_hint (GTK_WINDOW (dialog), TRUE); + if (prefs->getBool("/options/dialogsskiptaskbar/value")) { + gtk_window_set_skip_taskbar_hint(GTK_WINDOW(dialog), TRUE); } #endif @@ -154,26 +137,23 @@ void sp_transientize(GtkWidget *dialog) #endif if (transient_policy) { + // if there's an active document window, attach dialog to it as a transient: - // if there's an active document window, attach dialog to it as a transient: - - if ( SP_ACTIVE_DESKTOP ) - { - SP_ACTIVE_DESKTOP->setWindowTransient (dialog, transient_policy); + if (SP_ACTIVE_DESKTOP) { + SP_ACTIVE_DESKTOP->setWindowTransient(dialog, transient_policy); } } } // end of sp_transientize() -void on_transientize (SPDesktop *desktop, win_data *wd ) +void on_transientize(SPDesktop *desktop, win_data *wd) { - sp_transientize_callback (desktop, wd); + sp_transientize_callback(desktop, wd); } -void -sp_transientize_callback ( SPDesktop *desktop, win_data *wd ) +void sp_transientize_callback(SPDesktop *desktop, win_data *wd) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - gint transient_policy = prefs->getIntLimited( "/options/transientpolicy/value", 1, 0, 2); + gint transient_policy = prefs->getIntLimited("/options/transientpolicy/value", 1, 0, 2); #ifdef _WIN32 // Win32 special code to enable transient dialogs transient_policy = 1; @@ -182,49 +162,43 @@ sp_transientize_callback ( SPDesktop *desktop, win_data *wd ) if (!transient_policy) return; - if (wd->win) - { - desktop->setWindowTransient (wd->win, transient_policy); + if (wd->win) { + desktop->setWindowTransient(wd->win, transient_policy); } } -void on_dialog_hide (GtkWidget *w) +void on_dialog_hide(GtkWidget *w) { if (w) - gtk_widget_hide (w); + gtk_widget_hide(w); } -void on_dialog_unhide (GtkWidget *w) +void on_dialog_unhide(GtkWidget *w) { if (w) - gtk_widget_show (w); + gtk_widget_show(w); } -gboolean -sp_dialog_hide(GObject * /*object*/, gpointer data) +gboolean sp_dialog_hide(GObject * /*object*/, gpointer data) { GtkWidget *dlg = GTK_WIDGET(data); if (dlg) - gtk_widget_hide (dlg); + gtk_widget_hide(dlg); return TRUE; } - - -gboolean -sp_dialog_unhide(GObject * /*object*/, gpointer data) +gboolean sp_dialog_unhide(GObject * /*object*/, gpointer data) { GtkWidget *dlg = GTK_WIDGET(data); if (dlg) - gtk_widget_show (dlg); + gtk_widget_show(dlg); return TRUE; } - /* Local Variables: mode:c++ diff --git a/src/ui/dialog-events.h b/src/ui/dialog-events.h index 7bc7483784fae286798b0bd641322309cf55b200..70254bdda89d88cd5814c7245304bfbc9af51f98 100644 --- a/src/ui/dialog-events.h +++ b/src/ui/dialog-events.h @@ -14,53 +14,49 @@ #define SEEN_DIALOG_EVENTS_H #include <gtk/gtk.h> - + /* * event callback can only accept one argument, but we need two, * hence this struct. * each dialog has a local static copy: - * win is the dialog window - * stop is the transientize semaphore: when 0, retransientizing this dialog + * win is the dialog window + * stop is the transientize semaphore: when 0, retransientizing this dialog * is allowed */ namespace Gtk { class Window; class Entry; -} +} // namespace Gtk class SPDesktop; - -struct win_data { + +struct win_data +{ GtkWidget *win; guint stop; }; +gboolean sp_dialog_event_handler(GtkWindow *win, GdkEvent *event, gpointer data); -gboolean sp_dialog_event_handler ( GtkWindow *win, - GdkEvent *event, - gpointer data ); - -void sp_dialog_defocus_cpp (Gtk::Window *win); +void sp_dialog_defocus_cpp(Gtk::Window *win); void sp_dialog_defocus_callback_cpp(Gtk::Entry *e); void sp_dialog_defocus_on_enter_cpp(Gtk::Entry *e); -void sp_dialog_defocus ( GtkWindow *win ); -void sp_dialog_defocus_callback ( GtkWindow *win, gpointer data ); -void sp_dialog_defocus_on_enter ( GtkWidget *w ); -void sp_transientize ( GtkWidget *win ); +void sp_dialog_defocus(GtkWindow *win); +void sp_dialog_defocus_callback(GtkWindow *win, gpointer data); +void sp_dialog_defocus_on_enter(GtkWidget *w); +void sp_transientize(GtkWidget *win); -void on_transientize ( SPDesktop *desktop, - win_data *wd ); +void on_transientize(SPDesktop *desktop, win_data *wd); -void sp_transientize_callback ( SPDesktop *desktop, - win_data *wd ); +void sp_transientize_callback(SPDesktop *desktop, win_data *wd); -void on_dialog_hide (GtkWidget *w); -void on_dialog_unhide (GtkWidget *w); +void on_dialog_hide(GtkWidget *w); +void on_dialog_unhide(GtkWidget *w); -//gboolean sp_dialog_hide (GObject *object, gpointer data); -//gboolean sp_dialog_unhide (GObject *object, gpointer data); +// gboolean sp_dialog_hide (GObject *object, gpointer data); +// gboolean sp_dialog_unhide (GObject *object, gpointer data); #endif diff --git a/src/ui/dialog/about.cpp b/src/ui/dialog/about.cpp index 5f3038b72cd86740b224b660fe76f344b4d52e9f..8b271f49ae4310459bf9207e10a9ae8f8429de32 100644 --- a/src/ui/dialog/about.cpp +++ b/src/ui/dialog/about.cpp @@ -7,17 +7,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <string> +#include "about.h" + #include <fstream> #include <streambuf> +#include <string> -#include "about.h" #include "document.h" #include "inkscape-version.h" - #include "io/resource.h" #include "ui/view/svg-view-widget.h" - #include "util/units.h" using namespace Inkscape::IO; @@ -30,17 +29,19 @@ namespace Dialog { static Gtk::Window *window = nullptr; static Gtk::Notebook *tabs = nullptr; -void close_about_screen() { +void close_about_screen() +{ window->hide(); } -void copy_version() { +void copy_version() +{ auto clipboard = Gtk::Clipboard::get(); clipboard->set_text(Inkscape::version_string); } -void AboutDialog::show_about() { - - if(!window) { +void AboutDialog::show_about() +{ + if (!window) { // Load glade file here Glib::ustring gladefile = Resource::get_filename(Resource::UIS, "inkscape-about.glade"); Glib::RefPtr<Gtk::Builder> builder; @@ -52,19 +53,19 @@ void AboutDialog::show_about() { } builder->get_widget("about-screen-window", window); builder->get_widget("tabs", tabs); - if(!tabs || !window) { + if (!tabs || !window) { g_error("Window or tabs in glade file are missing or do not have the right ids."); return; } // Automatic signal handling (requires -rdynamic compile flag) - //gtk_builder_connect_signals(builder->gobj(), NULL); + // gtk_builder_connect_signals(builder->gobj(), NULL); // When automatic handling fails Gtk::Button *version; builder->get_widget("version", version); - if(version) { + if (version) { version->set_label(Inkscape::version_string); - version->signal_clicked().connect( sigc::ptr_fun(©_version) ); + version->signal_clicked().connect(sigc::ptr_fun(©_version)); } // Render the about screen image via inkscape SPDocument @@ -72,10 +73,10 @@ void AboutDialog::show_about() { SPDocument *doc = SPDocument::createNewDoc(filename.c_str(), TRUE); // Bind glade's container to our SVGViewWidget class - if(doc) { - //SVGViewWidget *viewer; - //builder->get_widget_derived("image-container", viewer, doc); - //Gtk::manage(viewer); + if (doc) { + // SVGViewWidget *viewer; + // builder->get_widget_derived("image-container", viewer, doc); + // Gtk::manage(viewer); auto viewer = Gtk::manage(new Inkscape::UI::View::SVGViewWidget(doc)); double width = doc->getWidth().value("px"); double height = doc->getHeight().value("px"); @@ -94,39 +95,35 @@ void AboutDialog::show_about() { Gtk::TextView *authors; builder->get_widget("credits-authors", authors); - if(authors) { + if (authors) { std::ifstream fn(Resource::get_filename(Resource::DOCS, "AUTHORS")); - std::string str((std::istreambuf_iterator<char>(fn)), - std::istreambuf_iterator<char>()); + std::string str((std::istreambuf_iterator<char>(fn)), std::istreambuf_iterator<char>()); authors->get_buffer()->set_text(str.c_str()); } Gtk::TextView *translators; builder->get_widget("credits-translators", translators); - if(translators) { + if (translators) { std::ifstream fn(Resource::get_filename(Resource::DOCS, "TRANSLATORS")); - std::string str((std::istreambuf_iterator<char>(fn)), - std::istreambuf_iterator<char>()); + std::string str((std::istreambuf_iterator<char>(fn)), std::istreambuf_iterator<char>()); translators->get_buffer()->set_text(str.c_str()); } Gtk::TextView *license; builder->get_widget("license-text", license); - if(license) { + if (license) { std::ifstream fn(Resource::get_filename(Resource::DOCS, "LICENSE")); - std::string str((std::istreambuf_iterator<char>(fn)), - std::istreambuf_iterator<char>()); + std::string str((std::istreambuf_iterator<char>(fn)), std::istreambuf_iterator<char>()); license->get_buffer()->set_text(str.c_str()); } } - if(window) { + if (window) { window->show(); tabs->set_current_page(0); } else { g_error("About screen window couldn't be loaded. Missing window id in glade file."); } } - } // namespace Dialog } // namespace UI diff --git a/src/ui/dialog/about.h b/src/ui/dialog/about.h index b6d792379de469f904e31423c0acde9e1f841886..221dc9fbf48e9973cc842054286e34ae68046a58 100644 --- a/src/ui/dialog/about.h +++ b/src/ui/dialog/about.h @@ -17,12 +17,12 @@ namespace Inkscape { namespace UI { namespace Dialog { -class AboutDialog { - - public: +class AboutDialog +{ +public: static void show_about(); - private: +private: }; } // namespace Dialog diff --git a/src/ui/dialog/align-and-distribute.cpp b/src/ui/dialog/align-and-distribute.cpp index da7c007a89af612d699622bab765f2076cde5212..90e48c09812fd0ba8facdbfc5a6893b63b26c93e 100644 --- a/src/ui/dialog/align-and-distribute.cpp +++ b/src/ui/dialog/align-and-distribute.cpp @@ -17,30 +17,24 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/i18n.h> +#include "align-and-distribute.h" #include <2geom/transforms.h> - +#include <glibmm/i18n.h> #include <utility> -#include "align-and-distribute.h" - #include "desktop.h" #include "document-undo.h" #include "document.h" #include "graphlayout.h" #include "inkscape.h" -#include "preferences.h" -#include "removeoverlap.h" -#include "text-editing.h" -#include "unclump.h" -#include "verbs.h" - #include "object/sp-flowtext.h" #include "object/sp-item-transform.h" #include "object/sp-root.h" #include "object/sp-text.h" - +#include "preferences.h" +#include "removeoverlap.h" +#include "text-editing.h" #include "ui/icon-loader.h" #include "ui/icon-names.h" #include "ui/tool/control-point-selection.h" @@ -48,6 +42,8 @@ #include "ui/tools-switch.h" #include "ui/tools/node-tool.h" #include "ui/widget/spinbutton.h" +#include "unclump.h" +#include "verbs.h" namespace Inkscape { namespace UI { @@ -55,112 +51,108 @@ namespace Dialog { /////////helper classes////////////////////////////////// -Action::Action(Glib::ustring id, - const Glib::ustring &tiptext, - guint row, guint column, - Gtk::Grid &parent, - AlignAndDistribute &dialog): - _dialog(dialog), - _id(std::move(id)), - _parent(parent) +Action::Action(Glib::ustring id, const Glib::ustring &tiptext, guint row, guint column, Gtk::Grid &parent, + AlignAndDistribute &dialog) + : _dialog(dialog) + , _id(std::move(id)) + , _parent(parent) { - Gtk::Image* pIcon = Gtk::manage(new Gtk::Image()); + Gtk::Image *pIcon = Gtk::manage(new Gtk::Image()); pIcon = sp_get_icon_image(_id, Gtk::ICON_SIZE_LARGE_TOOLBAR); - Gtk::Button * pButton = Gtk::manage(new Gtk::Button()); + 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->signal_clicked().connect(sigc::mem_fun(*this, &Action::on_button_click)); pButton->set_tooltip_text(tiptext); parent.attach(*pButton, column, row, 1, 1); } - void ActionAlign::do_node_action(Inkscape::UI::Tools::NodeTool *nt, int verb) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int prev_pref = prefs->getInt("/dialogs/align/align-nodes-to"); - switch(verb){ + switch (verb) { case SP_VERB_ALIGN_HORIZONTAL_LEFT: - prefs->setInt("/dialogs/align/align-nodes-to", MIN_NODE ); + prefs->setInt("/dialogs/align/align-nodes-to", MIN_NODE); nt->_multipath->alignNodes(Geom::Y); break; case SP_VERB_ALIGN_HORIZONTAL_CENTER: nt->_multipath->alignNodes(Geom::Y); break; case SP_VERB_ALIGN_HORIZONTAL_RIGHT: - prefs->setInt("/dialogs/align/align-nodes-to", MAX_NODE ); + prefs->setInt("/dialogs/align/align-nodes-to", MAX_NODE); nt->_multipath->alignNodes(Geom::Y); break; case SP_VERB_ALIGN_VERTICAL_TOP: - prefs->setInt("/dialogs/align/align-nodes-to", MAX_NODE ); + prefs->setInt("/dialogs/align/align-nodes-to", MAX_NODE); nt->_multipath->alignNodes(Geom::X); break; case SP_VERB_ALIGN_VERTICAL_CENTER: nt->_multipath->alignNodes(Geom::X); break; case SP_VERB_ALIGN_VERTICAL_BOTTOM: - prefs->setInt("/dialogs/align/align-nodes-to", MIN_NODE ); + prefs->setInt("/dialogs/align/align-nodes-to", MIN_NODE); nt->_multipath->alignNodes(Geom::X); break; case SP_VERB_ALIGN_BOTH_CENTER: nt->_multipath->alignNodes(Geom::X); nt->_multipath->alignNodes(Geom::Y); break; - default:return; + default: + return; } - prefs->setInt("/dialogs/align/align-nodes-to", prev_pref ); + prefs->setInt("/dialogs/align/align-nodes-to", prev_pref); } void ActionAlign::do_action(SPDesktop *desktop, int index) { Inkscape::Selection *selection = desktop->getSelection(); - if (!selection) return; + if (!selection) + return; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool sel_as_group = prefs->getBool("/dialogs/align/sel-as-groups"); - std::vector<SPItem*> selected(selection->items().begin(), selection->items().end()); - if (selected.empty()) return; + std::vector<SPItem *> selected(selection->items().begin(), selection->items().end()); + if (selected.empty()) + return; Coeffs a = _allCoeffs[index]; // copy SPItem *focus = nullptr; Geom::OptRect b = Geom::OptRect(); - Selection::CompareSize horiz = (a.mx0 != 0.0) || (a.mx1 != 0.0) - ? Selection::VERTICAL : Selection::HORIZONTAL; + Selection::CompareSize horiz = (a.mx0 != 0.0) || (a.mx1 != 0.0) ? Selection::VERTICAL : Selection::HORIZONTAL; - switch (AlignTarget(prefs->getInt("/dialogs/align/align-to", 6))) - { - case LAST: - focus = SP_ITEM(selected.back()); - break; - case FIRST: - focus = SP_ITEM(selected.front()); - break; - case BIGGEST: - focus = selection->largestItem(horiz); - break; - case SMALLEST: - focus = selection->smallestItem(horiz); - break; - case PAGE: - b = desktop->getDocument()->preferredBounds(); - break; - case DRAWING: - b = desktop->getDocument()->getRoot()->desktopPreferredBounds(); - break; - case SELECTION: - b = selection->preferredBounds(); - break; - default: - g_assert_not_reached (); - break; + switch (AlignTarget(prefs->getInt("/dialogs/align/align-to", 6))) { + case LAST: + focus = SP_ITEM(selected.back()); + break; + case FIRST: + focus = SP_ITEM(selected.front()); + break; + case BIGGEST: + focus = selection->largestItem(horiz); + break; + case SMALLEST: + focus = selection->smallestItem(horiz); + break; + case PAGE: + b = desktop->getDocument()->preferredBounds(); + break; + case DRAWING: + b = desktop->getDocument()->getRoot()->desktopPreferredBounds(); + break; + case SELECTION: + b = selection->preferredBounds(); + break; + default: + g_assert_not_reached(); + break; }; - if(focus) + if (focus) b = focus->desktopPreferredBounds(); g_return_if_fail(b); @@ -187,17 +179,16 @@ void ActionAlign::do_action(SPDesktop *desktop, int index) } } - //Move each item in the selected list separately + // Move each item in the selected list separately bool changed = false; - for (auto item : selected) - { - desktop->getDocument()->ensureUpToDate(); + for (auto item : selected) { + desktop->getDocument()->ensureUpToDate(); if (!sel_as_group) b = (item)->desktopPreferredBounds(); if (b && (!focus || (item) != 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 ); + Geom::Point const mp_rel(mp - sp); if (LInfty(mp_rel) > 1e-9) { item->move_rel(Geom::Translate(mp_rel)); changed = true; @@ -206,12 +197,10 @@ void ActionAlign::do_action(SPDesktop *desktop, int index) } if (changed) { - DocumentUndo::done( desktop->getDocument() , SP_VERB_DIALOG_ALIGN_DISTRIBUTE, - _("Align")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, _("Align")); } } - ActionAlign::Coeffs const ActionAlign::_allCoeffs[19] = { {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}, @@ -231,15 +220,14 @@ ActionAlign::Coeffs const ActionAlign::_allCoeffs[19] = { {1., 0., 1., 0., 0., 1., 0., 1., SP_VERB_ALIGN_BOTH_TOP_RIGHT_TO_ANCHOR}, {1., 0., 0., 1., 0., 1., 1., 0., SP_VERB_ALIGN_BOTH_BOTTOM_RIGHT_TO_ANCHOR}, {0., 1., 0., 1., 1., 0., 1., 0., SP_VERB_ALIGN_BOTH_BOTTOM_LEFT_TO_ANCHOR}, - {.5, .5, .5, .5, .5, .5, .5, .5, SP_VERB_ALIGN_BOTH_CENTER} -}; + {.5, .5, .5, .5, .5, .5, .5, .5, SP_VERB_ALIGN_BOTH_CENTER}}; void ActionAlign::do_verb_action(SPDesktop *desktop, int verb) { Inkscape::UI::Tools::ToolBase *event_context = desktop->getEventContext(); if (INK_IS_NODE_TOOL(event_context)) { Inkscape::UI::Tools::NodeTool *nt = INK_NODE_TOOL(event_context); - if(!nt->_selected_nodes->empty()){ + if (!nt->_selected_nodes->empty()) { do_node_action(nt, verb); return; } @@ -247,9 +235,9 @@ void ActionAlign::do_verb_action(SPDesktop *desktop, int verb) do_action(desktop, verb_to_coeff(verb)); } -int ActionAlign::verb_to_coeff(int verb) { - - for(guint i = 0; i < G_N_ELEMENTS(_allCoeffs); i++) { +int ActionAlign::verb_to_coeff(int verb) +{ + for (guint i = 0; i < G_N_ELEMENTS(_allCoeffs); i++) { if (_allCoeffs[i].verb_id == verb) { return i; } @@ -258,58 +246,57 @@ int ActionAlign::verb_to_coeff(int verb) { return -1; } -BBoxSort::BBoxSort(SPItem *pItem, Geom::Rect const &bounds, Geom::Dim2 orientation, double kBegin, double kEnd) : - item(pItem), - bbox (bounds) +BBoxSort::BBoxSort(SPItem *pItem, Geom::Rect const &bounds, Geom::Dim2 orientation, double kBegin, double kEnd) + : item(pItem) + , bbox(bounds) { - anchor = kBegin * bbox.min()[orientation] + kEnd * bbox.max()[orientation]; + anchor = kBegin * bbox.min()[orientation] + kEnd * bbox.max()[orientation]; } BBoxSort::BBoxSort(const BBoxSort &rhs) - //NOTE : this copy ctor is called O(sort) when sorting the vector - //this is bad. The vector should be a vector of pointers. - //But I'll wait the bohem GC before doing that -= default; + // NOTE : this copy ctor is called O(sort) when sorting the vector + // this is bad. The vector should be a vector of pointers. + // But I'll wait the bohem GC before doing that + = default; -bool operator< (const BBoxSort &a, const BBoxSort &b) +bool operator<(const BBoxSort &a, const BBoxSort &b) { return (a.anchor < b.anchor); } -class ActionDistribute : public Action { -public : - ActionDistribute(const Glib::ustring &id, - const Glib::ustring &tiptext, - guint row, guint column, - AlignAndDistribute &dialog, - bool onInterSpace, - Geom::Dim2 orientation, - double kBegin, double kEnd - ): - Action(id, tiptext, row, column, - dialog.distribute_table(), dialog), - _dialog(dialog), - _onInterSpace(onInterSpace), - _orientation(orientation), - _kBegin(kBegin), - _kEnd( kEnd) +class ActionDistribute : public Action +{ +public: + ActionDistribute(const Glib::ustring &id, const Glib::ustring &tiptext, guint row, guint column, + AlignAndDistribute &dialog, bool onInterSpace, Geom::Dim2 orientation, double kBegin, double kEnd) + : Action(id, tiptext, row, column, dialog.distribute_table(), dialog) + , _dialog(dialog) + , _onInterSpace(onInterSpace) + , _orientation(orientation) + , _kBegin(kBegin) + , _kEnd(kEnd) {} -private : - void on_button_click() override { - //Retrieve selected objects +private: + void on_button_click() override + { + // Retrieve selected objects SPDesktop *desktop = _dialog.getDesktop(); - if (!desktop) return; + if (!desktop) + return; Inkscape::Selection *selection = desktop->getSelection(); - if (!selection) return; + if (!selection) + return; - std::vector<SPItem*> selected(selection->items().begin(), selection->items().end()); - if (selected.empty()) return; + std::vector<SPItem *> selected(selection->items().begin(), selection->items().end()); + if (selected.empty()) + return; - //Check 2 or more selected objects - std::vector<SPItem*>::iterator second(selected.begin()); + // Check 2 or more selected objects + std::vector<SPItem *>::iterator second(selected.begin()); ++second; - if (second == selected.end()) return; + if (second == selected.end()) + return; double kBegin = _kBegin; double kEnd = _kEnd; @@ -320,14 +307,14 @@ private : Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int prefs_bbox = prefs->getBool("/tools/bounding_box"); - std::vector< BBoxSort > sorted; - for (auto item : selected){ + std::vector<BBoxSort> sorted; + for (auto item : selected) { Geom::OptRect bbox = !prefs_bbox ? (item)->desktopVisualBounds() : (item)->desktopGeometricBounds(); if (bbox) { sorted.emplace_back(item, *bbox, _orientation, kBegin, kEnd); } } - //sort bbox by anchors + // sort bbox by anchors std::stable_sort(sorted.begin(), sorted.end()); // see comment in ActionAlign above @@ -336,24 +323,18 @@ private : unsigned int len = sorted.size(); bool changed = false; - if (_onInterSpace) - { - //overall bboxes span - float dist = (sorted.back().bbox.max()[_orientation] - - sorted.front().bbox.min()[_orientation]); - //space eaten by bboxes + if (_onInterSpace) { + // overall bboxes span + float dist = (sorted.back().bbox.max()[_orientation] - sorted.front().bbox.min()[_orientation]); + // space eaten by bboxes float span = 0; - for (unsigned int i = 0; i < len; i++) - { + for (unsigned int i = 0; i < len; i++) { span += sorted[i].bbox[_orientation].extent(); } - //new distance between each bbox + // new distance between each bbox float step = (dist - span) / (len - 1); float pos = sorted.front().bbox.min()[_orientation]; - for ( std::vector<BBoxSort> ::iterator it (sorted.begin()); - it < sorted.end(); - ++it ) - { + for (std::vector<BBoxSort>::iterator it(sorted.begin()); it < sorted.end(); ++it) { if (!Geom::are_near(pos, it->bbox.min()[_orientation], 1e-6)) { Geom::Point t(0.0, 0.0); t[_orientation] = pos - it->bbox.min()[_orientation]; @@ -363,25 +344,22 @@ private : pos += it->bbox[_orientation].extent(); pos += step; } - } - else - { - //overall anchor span + } else { + // overall anchor span float dist = sorted.back().anchor - sorted.front().anchor; - //distance between anchors + // distance between anchors float step = dist / (len - 1); - for ( unsigned int i = 0; i < len ; i ++ ) - { - BBoxSort & it(sorted[i]); - //new anchor position + for (unsigned int i = 0; i < len; i++) { + BBoxSort &it(sorted[i]); + // new anchor position float pos = sorted.front().anchor + i * step; - //Don't move if we are really close + // Don't move if we are really close if (!Geom::are_near(pos, it.anchor, 1e-6)) { - //Compute translation + // Compute translation Geom::Point t(0.0, 0.0); t[_orientation] = pos - it.anchor; - //translate + // translate it.item->move_rel(Geom::Translate(t)); changed = true; } @@ -392,8 +370,7 @@ private : prefs->setInt("/options/clonecompensation/value", saved_compensation); if (changed) { - DocumentUndo::done( desktop->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, - _("Distribute")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, _("Distribute")); } } guint _index; @@ -403,36 +380,32 @@ private : double _kBegin; double _kEnd; - }; - -class ActionNode : public Action { -public : - ActionNode(const Glib::ustring &id, - const Glib::ustring &tiptext, - guint column, - AlignAndDistribute &dialog, - Geom::Dim2 orientation, bool distribute): - Action(id, tiptext, 0, column, - dialog.nodes_table(), dialog), - _orientation(orientation), - _distribute(distribute) +class ActionNode : public Action +{ +public: + ActionNode(const Glib::ustring &id, const Glib::ustring &tiptext, guint column, AlignAndDistribute &dialog, + Geom::Dim2 orientation, bool distribute) + : Action(id, tiptext, 0, column, dialog.nodes_table(), dialog) + , _orientation(orientation) + , _distribute(distribute) {} -private : +private: Geom::Dim2 _orientation; bool _distribute; - void on_button_click() override { + void on_button_click() override + { if (!_dialog.getDesktop()) { - return; + return; } Inkscape::UI::Tools::ToolBase *event_context = _dialog.getDesktop()->getEventContext(); if (!INK_IS_NODE_TOOL(event_context)) { - return; + return; } Inkscape::UI::Tools::NodeTool *nt = INK_NODE_TOOL(event_context); @@ -445,7 +418,8 @@ private : } }; -class ActionRemoveOverlaps : public Action { +class ActionRemoveOverlaps : public Action +{ private: Gtk::Label removeOverlapXGapLabel; Gtk::Label removeOverlapYGapLabel; @@ -453,13 +427,9 @@ private: Inkscape::UI::Widget::SpinButton removeOverlapYGap; public: - ActionRemoveOverlaps(Glib::ustring const &id, - Glib::ustring const &tiptext, - guint row, - guint column, - AlignAndDistribute &dialog) : - Action(id, tiptext, row, column + 4, - dialog.removeOverlap_table(), dialog) + ActionRemoveOverlaps(Glib::ustring const &id, Glib::ustring const &tiptext, guint row, guint column, + AlignAndDistribute &dialog) + : Action(id, tiptext, row, column + 4, dialog.removeOverlap_table(), dialog) { dialog.removeOverlap_table().set_column_spacing(3); @@ -469,7 +439,7 @@ public: removeOverlapXGap.set_range(-1000.0, 1000.0); removeOverlapXGap.set_value(0); removeOverlapXGap.set_tooltip_text(_("Minimum horizontal gap (in px units) between bounding boxes")); - //TRANSLATORS: "H:" stands for horizontal gap + // TRANSLATORS: "H:" stands for horizontal gap removeOverlapXGapLabel.set_text_with_mnemonic(C_("Gap", "_H:")); removeOverlapXGapLabel.set_mnemonic_widget(removeOverlapXGap); @@ -484,15 +454,16 @@ public: removeOverlapYGapLabel.set_mnemonic_widget(removeOverlapYGap); dialog.removeOverlap_table().attach(removeOverlapXGapLabel, column, row, 1, 1); - dialog.removeOverlap_table().attach(removeOverlapXGap, column+1, row, 1, 1); - dialog.removeOverlap_table().attach(removeOverlapYGapLabel, column+2, row, 1, 1); - dialog.removeOverlap_table().attach(removeOverlapYGap, column+3, row, 1, 1); + dialog.removeOverlap_table().attach(removeOverlapXGap, column + 1, row, 1, 1); + dialog.removeOverlap_table().attach(removeOverlapYGapLabel, column + 2, row, 1, 1); + dialog.removeOverlap_table().attach(removeOverlapYGap, column + 3, row, 1, 1); } -private : +private: void on_button_click() override { - if (!_dialog.getDesktop()) return; + if (!_dialog.getDesktop()) + return; // see comment in ActionAlign above Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -509,26 +480,23 @@ private : // restore compensation setting prefs->setInt("/options/clonecompensation/value", saved_compensation); - DocumentUndo::done(_dialog.getDesktop()->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, - _("Remove overlaps")); + DocumentUndo::done(_dialog.getDesktop()->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, _("Remove overlaps")); } }; -class ActionGraphLayout : public Action { +class ActionGraphLayout : public Action +{ public: - ActionGraphLayout(Glib::ustring const &id, - Glib::ustring const &tiptext, - guint row, - guint column, - AlignAndDistribute &dialog) : - Action(id, tiptext, row, column, - dialog.rearrange_table(), dialog) + ActionGraphLayout(Glib::ustring const &id, Glib::ustring const &tiptext, guint row, guint column, + AlignAndDistribute &dialog) + : Action(id, tiptext, row, column, dialog.rearrange_table(), dialog) {} -private : +private: void on_button_click() override { - if (!_dialog.getDesktop()) return; + if (!_dialog.getDesktop()) + return; // see comment in ActionAlign above Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -546,32 +514,31 @@ private : } }; -class ActionExchangePositions : public Action { +class ActionExchangePositions : public Action +{ public: - enum SortOrder { - None, - ZOrder, - Clockwise + enum SortOrder + { + None, + ZOrder, + Clockwise }; - ActionExchangePositions(Glib::ustring const &id, - Glib::ustring const &tiptext, - guint row, - guint column, - AlignAndDistribute &dialog, SortOrder order = None) : - Action(id, tiptext, row, column, - dialog.rearrange_table(), dialog), - sortOrder(order) - {}; - + ActionExchangePositions(Glib::ustring const &id, Glib::ustring const &tiptext, guint row, guint column, + AlignAndDistribute &dialog, SortOrder order = None) + : Action(id, tiptext, row, column, dialog.rearrange_table(), dialog) + , sortOrder(order){}; -private : +private: const SortOrder sortOrder; static boost::optional<Geom::Point> center; - static bool sort_compare(const SPItem * a,const SPItem * b) { - if (a == nullptr) return false; - if (b == nullptr) return true; + static bool sort_compare(const SPItem *a, const SPItem *b) + { + if (a == nullptr) + return false; + if (b == nullptr) + return true; if (center) { Geom::Point point_a = a->getCenter() - (*center); Geom::Point point_b = b->getCenter() - (*center); @@ -581,28 +548,33 @@ private : double dt_yaxisdir = SP_ACTIVE_DESKTOP ? SP_ACTIVE_DESKTOP->yaxisdir() : 1; angle_a *= -dt_yaxisdir; angle_b *= -dt_yaxisdir; - if (angle_a != angle_b) return (angle_a < angle_b); + if (angle_a != angle_b) + return (angle_a < angle_b); // Second criteria: Sort according to the distance the center point Geom::Coord length_a = point_a.length(); Geom::Coord length_b = point_b.length(); - if (length_a != length_b) return (length_a > length_b); + if (length_a != length_b) + return (length_a > length_b); } // Last criteria: Sort according to the z-coordinate - return sp_item_repr_compare_position(a,b)<0; + return sp_item_repr_compare_position(a, b) < 0; } void on_button_click() override { SPDesktop *desktop = _dialog.getDesktop(); - if (!desktop) return; + if (!desktop) + return; Inkscape::Selection *selection = desktop->getSelection(); - if (!selection) return; + if (!selection) + return; - std::vector<SPItem*> selected(selection->items().begin(), selection->items().end()); + std::vector<SPItem *> selected(selection->items().begin(), selection->items().end()); - //Check 2 or more selected objects - if (selected.size() < 2) return; + // Check 2 or more selected objects + if (selected.size() < 2) + return; // see comment in ActionAlign above Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -610,23 +582,22 @@ private : prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); // sort the list - if (sortOrder != None) { - if (sortOrder == Clockwise) { - center = selection->center(); - } else { // sorting by ZOrder is outomatically done by not setting the center - center.reset(); - } - sort(selected.begin(),selected.end(),sort_compare); - } - - Geom::Point p1 = selected.back()->getCenter(); - for (SPItem *item : selected) - { - Geom::Point p2 = item->getCenter(); - Geom::Point delta = p1 - p2; - item->move_rel(Geom::Translate(delta[Geom::X],delta[Geom::Y] )); - p1 = p2; - } + if (sortOrder != None) { + if (sortOrder == Clockwise) { + center = selection->center(); + } else { // sorting by ZOrder is outomatically done by not setting the center + center.reset(); + } + sort(selected.begin(), selected.end(), sort_compare); + } + + Geom::Point p1 = selected.back()->getCenter(); + for (SPItem *item : selected) { + Geom::Point p2 = item->getCenter(); + Geom::Point delta = p1 - p2; + item->move_rel(Geom::Translate(delta[Geom::X], delta[Geom::Y])); + p1 = p2; + } // restore compensation setting prefs->setInt("/options/clonecompensation/value", saved_compensation); @@ -639,63 +610,61 @@ private : // instantiate the private static member boost::optional<Geom::Point> ActionExchangePositions::center; -class ActionUnclump : public Action { -public : - ActionUnclump(const Glib::ustring &id, - const Glib::ustring &tiptext, - guint row, - guint column, - AlignAndDistribute &dialog): - Action(id, tiptext, row, column, - dialog.rearrange_table(), dialog) +class ActionUnclump : public Action +{ +public: + ActionUnclump(const Glib::ustring &id, const Glib::ustring &tiptext, guint row, guint column, + AlignAndDistribute &dialog) + : Action(id, tiptext, row, column, dialog.rearrange_table(), dialog) {} -private : +private: void on_button_click() override { - if (!_dialog.getDesktop()) return; + if (!_dialog.getDesktop()) + return; // see comment in ActionAlign above Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); auto tmp = _dialog.getDesktop()->getSelection()->items(); - std::vector<SPItem*> x(tmp.begin(), tmp.end()); - unclump (x); + std::vector<SPItem *> x(tmp.begin(), tmp.end()); + unclump(x); // restore compensation setting prefs->setInt("/options/clonecompensation/value", saved_compensation); - DocumentUndo::done(_dialog.getDesktop()->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, - _("Unclump")); + DocumentUndo::done(_dialog.getDesktop()->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, _("Unclump")); } }; -class ActionRandomize : public Action { -public : - ActionRandomize(const Glib::ustring &id, - const Glib::ustring &tiptext, - guint row, - guint column, - AlignAndDistribute &dialog): - Action(id, tiptext, row, column, - dialog.rearrange_table(), dialog) +class ActionRandomize : public Action +{ +public: + ActionRandomize(const Glib::ustring &id, const Glib::ustring &tiptext, guint row, guint column, + AlignAndDistribute &dialog) + : Action(id, tiptext, row, column, dialog.rearrange_table(), dialog) {} -private : +private: void on_button_click() override { SPDesktop *desktop = _dialog.getDesktop(); - if (!desktop) return; + if (!desktop) + return; Inkscape::Selection *selection = desktop->getSelection(); - if (!selection) return; + if (!selection) + return; - std::vector<SPItem*> selected(selection->items().begin(), selection->items().end()); - if (selected.empty()) return; + std::vector<SPItem *> selected(selection->items().begin(), selection->items().end()); + if (selected.empty()) + return; - //Check 2 or more selected objects - if (selected.size() < 2) return; + // Check 2 or more selected objects + if (selected.size() < 2) + return; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int prefs_bbox = prefs->getBool("/tools/bounding_box"); @@ -715,18 +684,19 @@ private : int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); - for (auto item : selected) - { - desktop->getDocument()->ensureUpToDate(); + for (auto item : selected) { + desktop->getDocument()->ensureUpToDate(); Geom::OptRect item_box = !prefs_bbox ? (item)->desktopVisualBounds() : (item)->desktopGeometricBounds(); if (item_box) { // find new center, staying within bbox - double x = _dialog.randomize_bbox->min()[Geom::X] + (*item_box)[Geom::X].extent() /2 + - g_random_double_range (0, (*_dialog.randomize_bbox)[Geom::X].extent() - (*item_box)[Geom::X].extent()); - double y = _dialog.randomize_bbox->min()[Geom::Y] + (*item_box)[Geom::Y].extent()/2 + - g_random_double_range (0, (*_dialog.randomize_bbox)[Geom::Y].extent() - (*item_box)[Geom::Y].extent()); + double x = _dialog.randomize_bbox->min()[Geom::X] + (*item_box)[Geom::X].extent() / 2 + + g_random_double_range(0, (*_dialog.randomize_bbox)[Geom::X].extent() - + (*item_box)[Geom::X].extent()); + double y = _dialog.randomize_bbox->min()[Geom::Y] + (*item_box)[Geom::Y].extent() / 2 + + g_random_double_range(0, (*_dialog.randomize_bbox)[Geom::Y].extent() - + (*item_box)[Geom::Y].extent()); // displacement is the new center minus old: - Geom::Point t = Geom::Point (x, y) - 0.5*(item_box->max() + item_box->min()); + Geom::Point t = Geom::Point(x, y) - 0.5 * (item_box->max() + item_box->min()); item->move_rel(Geom::Translate(t)); } } @@ -734,8 +704,7 @@ private : // restore compensation setting prefs->setInt("/options/clonecompensation/value", saved_compensation); - DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, - _("Randomize positions")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, _("Randomize positions")); } }; @@ -744,80 +713,82 @@ struct Baselines SPItem *_item; Geom::Point _base; Geom::Dim2 _orientation; - Baselines(SPItem *item, Geom::Point base, Geom::Dim2 orientation) : - _item (item), - _base (base), - _orientation (orientation) + Baselines(SPItem *item, Geom::Point base, Geom::Dim2 orientation) + : _item(item) + , _base(base) + , _orientation(orientation) {} }; -static 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]); } -class ActionBaseline : public Action { -public : - ActionBaseline(const Glib::ustring &id, - const Glib::ustring &tiptext, - guint row, - guint column, - AlignAndDistribute &dialog, - Gtk::Grid &table, - Geom::Dim2 orientation, bool distribute): - Action(id, tiptext, row, column, - table, dialog), - _orientation(orientation), - _distribute(distribute) +class ActionBaseline : public Action +{ +public: + ActionBaseline(const Glib::ustring &id, const Glib::ustring &tiptext, guint row, guint column, + AlignAndDistribute &dialog, Gtk::Grid &table, Geom::Dim2 orientation, bool distribute) + : Action(id, tiptext, row, column, table, dialog) + , _orientation(orientation) + , _distribute(distribute) {} -private : +private: Geom::Dim2 _orientation; bool _distribute; void on_button_click() override { SPDesktop *desktop = _dialog.getDesktop(); - if (!desktop) return; + if (!desktop) + return; Inkscape::Selection *selection = desktop->getSelection(); - if (!selection) return; + if (!selection) + return; - std::vector<SPItem*> selected(selection->items().begin(), selection->items().end()); + std::vector<SPItem *> selected(selection->items().begin(), selection->items().end()); - //Check 2 or more selected objects - if (selected.size() < 2) return; + // Check 2 or more selected objects + if (selected.size() < 2) + return; - Geom::Point b_min = Geom::Point (HUGE_VAL, HUGE_VAL); - Geom::Point b_max = Geom::Point (-HUGE_VAL, -HUGE_VAL); + Geom::Point b_min = Geom::Point(HUGE_VAL, HUGE_VAL); + Geom::Point b_max = Geom::Point(-HUGE_VAL, -HUGE_VAL); std::vector<Baselines> sorted; - for (auto item : selected) - { - if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT (item)) { + for (auto item : selected) { + if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item)) { Inkscape::Text::Layout const *layout = te_get_layout(item); boost::optional<Geom::Point> pt = layout->baselineAnchorPoint(); if (pt) { Geom::Point base = *pt * (item)->i2dt_affine(); - if (base[Geom::X] < b_min[Geom::X]) b_min[Geom::X] = base[Geom::X]; - if (base[Geom::Y] < b_min[Geom::Y]) b_min[Geom::Y] = base[Geom::Y]; - if (base[Geom::X] > b_max[Geom::X]) b_max[Geom::X] = base[Geom::X]; - if (base[Geom::Y] > b_max[Geom::Y]) b_max[Geom::Y] = base[Geom::Y]; - Baselines b (item, base, _orientation); + if (base[Geom::X] < b_min[Geom::X]) + b_min[Geom::X] = base[Geom::X]; + if (base[Geom::Y] < b_min[Geom::Y]) + b_min[Geom::Y] = base[Geom::Y]; + if (base[Geom::X] > b_max[Geom::X]) + b_max[Geom::X] = base[Geom::X]; + if (base[Geom::Y] > b_max[Geom::Y]) + b_max[Geom::Y] = base[Geom::Y]; + Baselines b(item, base, _orientation); sorted.push_back(b); } } } - if (sorted.size() <= 1) return; + if (sorted.size() <= 1) + return; - //sort baselines + // sort baselines std::stable_sort(sorted.begin(), sorted.end()); bool changed = false; if (_distribute) { - double step = (b_max[_orientation] - b_min[_orientation])/(sorted.size() - 1); + double step = (b_max[_orientation] - b_min[_orientation]) / (sorted.size() - 1); for (unsigned int i = 0; i < sorted.size(); i++) { SPItem *item = sorted[i]._item; Geom::Point base = sorted[i]._base; @@ -829,18 +800,17 @@ private : if (changed) { DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, - _("Distribute text baselines")); + _("Distribute text baselines")); } - } else { //align + } else { // align Geom::Point ref_point; SPItem *focus = nullptr; Geom::OptRect b = Geom::OptRect(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - switch (AlignTarget(prefs->getInt("/dialogs/align/align-to", 6))) - { + switch (AlignTarget(prefs->getInt("/dialogs/align/align-to", 6))) { case LAST: focus = SP_ITEM(selected.back()); break; @@ -863,13 +833,13 @@ private : b = selection->preferredBounds(); break; default: - g_assert_not_reached (); + g_assert_not_reached(); break; }; - if(focus) { - if (SP_IS_TEXT (focus) || SP_IS_FLOWTEXT (focus)) { - ref_point = *(te_get_layout(focus)->baselineAnchorPoint())*(focus->i2dt_affine()); + if (focus) { + if (SP_IS_TEXT(focus) || SP_IS_FLOWTEXT(focus)) { + ref_point = *(te_get_layout(focus)->baselineAnchorPoint()) * (focus->i2dt_affine()); } else { ref_point = focus->desktopPreferredBounds()->min(); } @@ -877,9 +847,8 @@ private : ref_point = b->min(); } - for (auto item : selected) - { - if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT (item)) { + for (auto item : selected) { + if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item)) { Inkscape::Text::Layout const *layout = te_get_layout(item); boost::optional<Geom::Point> pt = layout->baselineAnchorPoint(); if (pt) { @@ -893,15 +862,12 @@ private : } if (changed) { - DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, - _("Align text baselines")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, _("Align text baselines")); } } } }; - - static void on_tool_changed(AlignAndDistribute *daad) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; @@ -909,7 +875,6 @@ static void on_tool_changed(AlignAndDistribute *daad) daad->setMode(tools_active(desktop) == TOOLS_NODES); else daad->setMode(false); - } static void on_selection_changed(AlignAndDistribute *daad) @@ -919,150 +884,107 @@ static void on_selection_changed(AlignAndDistribute *daad) ///////////////////////////////////////////////////////// - - - AlignAndDistribute::AlignAndDistribute() - : UI::Widget::Panel("/dialogs/align", SP_VERB_DIALOG_ALIGN_DISTRIBUTE), - randomize_bbox(), - _alignFrame(_("Align")), - _distributeFrame(_("Distribute")), - _rearrangeFrame(_("Rearrange")), - _removeOverlapFrame(_("Remove overlaps")), - _nodesFrame(_("Nodes")), - _alignTable(), - _distributeTable(), - _rearrangeTable(), - _removeOverlapTable(), - _nodesTable(), - _anchorLabel(_("Relative to: ")), - _anchorLabelNode(_("Relative to: ")) + : UI::Widget::Panel("/dialogs/align", SP_VERB_DIALOG_ALIGN_DISTRIBUTE) + , randomize_bbox() + , _alignFrame(_("Align")) + , _distributeFrame(_("Distribute")) + , _rearrangeFrame(_("Rearrange")) + , _removeOverlapFrame(_("Remove overlaps")) + , _nodesFrame(_("Nodes")) + , _alignTable() + , _distributeTable() + , _rearrangeTable() + , _removeOverlapTable() + , _nodesTable() + , _anchorLabel(_("Relative to: ")) + , _anchorLabelNode(_("Relative to: ")) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - //Instantiate the align buttons + // Instantiate the align buttons addAlignButton(INKSCAPE_ICON("align-horizontal-right-to-anchor"), - _("Align right edges of objects to the left edge of the anchor"), - 0, 0); - addAlignButton(INKSCAPE_ICON("align-horizontal-left"), - _("Align left edges"), - 0, 1); - addAlignButton(INKSCAPE_ICON("align-horizontal-center"), - _("Center on vertical axis"), - 0, 2); - addAlignButton(INKSCAPE_ICON("align-horizontal-right"), - _("Align right sides"), - 0, 3); + _("Align right edges of objects to the left edge of the anchor"), 0, 0); + addAlignButton(INKSCAPE_ICON("align-horizontal-left"), _("Align left edges"), 0, 1); + addAlignButton(INKSCAPE_ICON("align-horizontal-center"), _("Center on vertical axis"), 0, 2); + addAlignButton(INKSCAPE_ICON("align-horizontal-right"), _("Align right sides"), 0, 3); addAlignButton(INKSCAPE_ICON("align-horizontal-left-to-anchor"), - _("Align left edges of objects to the right edge of the anchor"), - 0, 4); + _("Align left edges of objects to the right edge of the anchor"), 0, 4); addAlignButton(INKSCAPE_ICON("align-vertical-bottom-to-anchor"), - _("Align bottom edges of objects to the top edge of the anchor"), - 1, 0); - addAlignButton(INKSCAPE_ICON("align-vertical-top"), - _("Align top edges"), - 1, 1); - addAlignButton(INKSCAPE_ICON("align-vertical-center"), - _("Center on horizontal axis"), - 1, 2); - addAlignButton(INKSCAPE_ICON("align-vertical-bottom"), - _("Align bottom edges"), - 1, 3); + _("Align bottom edges of objects to the top edge of the anchor"), 1, 0); + addAlignButton(INKSCAPE_ICON("align-vertical-top"), _("Align top edges"), 1, 1); + addAlignButton(INKSCAPE_ICON("align-vertical-center"), _("Center on horizontal axis"), 1, 2); + addAlignButton(INKSCAPE_ICON("align-vertical-bottom"), _("Align bottom edges"), 1, 3); addAlignButton(INKSCAPE_ICON("align-vertical-top-to-anchor"), - _("Align top edges of objects to the bottom edge of the anchor"), - 1, 4); - - //Baseline aligns - addBaselineButton(INKSCAPE_ICON("align-horizontal-baseline"), - _("Align baseline anchors of texts horizontally"), - 0, 5, this->align_table(), Geom::X, false); - addBaselineButton(INKSCAPE_ICON("align-vertical-baseline"), - _("Align baselines of texts"), - 1, 5, this->align_table(), Geom::Y, false); - - //The distribute buttons - addDistributeButton(INKSCAPE_ICON("distribute-horizontal-gaps"), - _("Make horizontal gaps between objects equal"), - 0, 4, true, Geom::X, .5, .5); - - addDistributeButton(INKSCAPE_ICON("distribute-horizontal-left"), - _("Distribute left edges equidistantly"), - 0, 1, false, Geom::X, 1., 0.); + _("Align top edges of objects to the bottom edge of the anchor"), 1, 4); + + // Baseline aligns + addBaselineButton(INKSCAPE_ICON("align-horizontal-baseline"), _("Align baseline anchors of texts horizontally"), 0, + 5, this->align_table(), Geom::X, false); + addBaselineButton(INKSCAPE_ICON("align-vertical-baseline"), _("Align baselines of texts"), 1, 5, + this->align_table(), Geom::Y, false); + + // The distribute buttons + addDistributeButton(INKSCAPE_ICON("distribute-horizontal-gaps"), _("Make horizontal gaps between objects equal"), 0, + 4, true, Geom::X, .5, .5); + + addDistributeButton(INKSCAPE_ICON("distribute-horizontal-left"), _("Distribute left edges equidistantly"), 0, 1, + false, Geom::X, 1., 0.); addDistributeButton(INKSCAPE_ICON("distribute-horizontal-center"), - _("Distribute centers equidistantly horizontally"), - 0, 2, false, Geom::X, .5, .5); - addDistributeButton(INKSCAPE_ICON("distribute-horizontal-right"), - _("Distribute right edges equidistantly"), - 0, 3, false, Geom::X, 0., 1.); - - addDistributeButton(INKSCAPE_ICON("distribute-vertical-gaps"), - _("Make vertical gaps between objects equal"), - 1, 4, true, Geom::Y, .5, .5); - - addDistributeButton(INKSCAPE_ICON("distribute-vertical-top"), - _("Distribute top edges equidistantly"), - 1, 1, false, Geom::Y, 0, 1); - addDistributeButton(INKSCAPE_ICON("distribute-vertical-center"), - _("Distribute centers equidistantly vertically"), + _("Distribute centers equidistantly horizontally"), 0, 2, false, Geom::X, .5, .5); + addDistributeButton(INKSCAPE_ICON("distribute-horizontal-right"), _("Distribute right edges equidistantly"), 0, 3, + false, Geom::X, 0., 1.); + + addDistributeButton(INKSCAPE_ICON("distribute-vertical-gaps"), _("Make vertical gaps between objects equal"), 1, 4, + true, Geom::Y, .5, .5); + + addDistributeButton(INKSCAPE_ICON("distribute-vertical-top"), _("Distribute top edges equidistantly"), 1, 1, false, + Geom::Y, 0, 1); + addDistributeButton(INKSCAPE_ICON("distribute-vertical-center"), _("Distribute centers equidistantly vertically"), 1, 2, false, Geom::Y, .5, .5); - addDistributeButton(INKSCAPE_ICON("distribute-vertical-bottom"), - _("Distribute bottom edges equidistantly"), - 1, 3, false, Geom::Y, 1., 0.); + addDistributeButton(INKSCAPE_ICON("distribute-vertical-bottom"), _("Distribute bottom edges equidistantly"), 1, 3, + false, Geom::Y, 1., 0.); - //Baseline distribs + // Baseline distribs addBaselineButton(INKSCAPE_ICON("distribute-horizontal-baseline"), - _("Distribute baseline anchors of texts horizontally"), - 0, 5, this->distribute_table(), Geom::X, true); - addBaselineButton(INKSCAPE_ICON("distribute-vertical-baseline"), - _("Distribute baselines of texts vertically"), - 1, 5, this->distribute_table(), Geom::Y, true); + _("Distribute baseline anchors of texts horizontally"), 0, 5, this->distribute_table(), Geom::X, + true); + addBaselineButton(INKSCAPE_ICON("distribute-vertical-baseline"), _("Distribute baselines of texts vertically"), 1, + 5, this->distribute_table(), Geom::Y, true); // Rearrange - //Graph Layout - addGraphLayoutButton(INKSCAPE_ICON("distribute-graph"), - _("Nicely arrange selected connector network"), - 0, 0); + // Graph Layout + addGraphLayoutButton(INKSCAPE_ICON("distribute-graph"), _("Nicely arrange selected connector network"), 0, 0); addExchangePositionsButton(INKSCAPE_ICON("exchange-positions"), - _("Exchange positions of selected objects - selection order"), - 0, 1); + _("Exchange positions of selected objects - selection order"), 0, 1); addExchangePositionsByZOrderButton(INKSCAPE_ICON("exchange-positions-zorder"), - _("Exchange positions of selected objects - stacking order"), - 0, 2); + _("Exchange positions of selected objects - stacking order"), 0, 2); addExchangePositionsClockwiseButton(INKSCAPE_ICON("exchange-positions-clockwise"), - _("Exchange positions of selected objects - clockwise rotate"), - 0, 3); - - //Randomize & Unclump - addRandomizeButton(INKSCAPE_ICON("distribute-randomize"), - _("Randomize centers in both dimensions"), - 0, 4); - addUnclumpButton(INKSCAPE_ICON("distribute-unclump"), - _("Unclump objects: try to equalize edge-to-edge distances"), - 0, 5); - - //Remove overlaps + _("Exchange positions of selected objects - clockwise rotate"), 0, 3); + + // Randomize & Unclump + addRandomizeButton(INKSCAPE_ICON("distribute-randomize"), _("Randomize centers in both dimensions"), 0, 4); + addUnclumpButton(INKSCAPE_ICON("distribute-unclump"), _("Unclump objects: try to equalize edge-to-edge distances"), + 0, 5); + + // Remove overlaps addRemoveOverlapsButton(INKSCAPE_ICON("distribute-remove-overlaps"), - _("Move objects as little as possible so that their bounding boxes do not overlap"), - 0, 0); + _("Move objects as little as possible so that their bounding boxes do not overlap"), 0, 0); - //Node Mode buttons + // Node Mode buttons // NOTE: "align nodes vertically" means "move nodes vertically until they align on a common // _horizontal_ line". This is analogous to what the "align-vertical-center" icon means. // There is no doubt some ambiguity. For this reason the descriptions are different. - addNodeButton(INKSCAPE_ICON("align-vertical-node"), - _("Align selected nodes to a common horizontal line"), - 0, Geom::X, false); - addNodeButton(INKSCAPE_ICON("align-horizontal-node"), - _("Align selected nodes to a common vertical line"), - 1, Geom::Y, false); - addNodeButton(INKSCAPE_ICON("distribute-horizontal-node"), - _("Distribute selected nodes horizontally"), - 2, Geom::X, true); - addNodeButton(INKSCAPE_ICON("distribute-vertical-node"), - _("Distribute selected nodes vertically"), - 3, Geom::Y, true); - - //Rest of the widgetry + addNodeButton(INKSCAPE_ICON("align-vertical-node"), _("Align selected nodes to a common horizontal line"), 0, + Geom::X, false); + addNodeButton(INKSCAPE_ICON("align-horizontal-node"), _("Align selected nodes to a common vertical line"), 1, + Geom::Y, false); + addNodeButton(INKSCAPE_ICON("distribute-horizontal-node"), _("Distribute selected nodes horizontally"), 2, Geom::X, + true); + addNodeButton(INKSCAPE_ICON("distribute-vertical-node"), _("Distribute selected nodes vertically"), 3, Geom::Y, + true); + + // Rest of the widgetry _combo.append(_("Last selected")); _combo.append(_("First selected")); @@ -1082,7 +1004,7 @@ AlignAndDistribute::AlignAndDistribute() _comboNode.set_active(prefs->getInt("/dialogs/align/align-nodes-to", 2)); _comboNode.signal_changed().connect(sigc::mem_fun(*this, &AlignAndDistribute::on_node_ref_change)); - Gtk::Image* selgrp_icon = Gtk::manage(new Gtk::Image()); + Gtk::Image *selgrp_icon = Gtk::manage(new Gtk::Image()); selgrp_icon = sp_get_icon_image("align-sel-as-group", Gtk::ICON_SIZE_LARGE_TOOLBAR); _selgrp.add(*selgrp_icon); @@ -1097,7 +1019,7 @@ AlignAndDistribute::AlignAndDistribute() _anchorBoxNode.pack_end(_comboNode, false, false); _anchorBoxNode.pack_end(_anchorLabelNode, false, false); - Gtk::Image* oncanvas_icon = Gtk::manage(new Gtk::Image()); + Gtk::Image *oncanvas_icon = Gtk::manage(new Gtk::Image()); oncanvas_icon = sp_get_icon_image("align-on-canvas", Gtk::ICON_SIZE_LARGE_TOOLBAR); _oncanvas.add(*oncanvas_icon); @@ -1121,7 +1043,6 @@ AlignAndDistribute::AlignAndDistribute() _alignBoxNode.pack_start(_anchorBoxNode, false, false); _alignBoxNode.pack_start(_nodesTableBox); - _alignFrame.add(_alignBox); _distributeFrame.add(_distributeTableBox); _rearrangeFrame.add(_rearrangeTableBox); @@ -1139,21 +1060,23 @@ AlignAndDistribute::AlignAndDistribute() contents->pack_start(_removeOverlapFrame, Gtk::PACK_SHRINK); contents->pack_start(_nodesFrame, Gtk::PACK_SHRINK); - //Connect to the global tool change signal - _toolChangeConn = INKSCAPE.signal_eventcontext_set.connect(sigc::hide<0>(sigc::bind(sigc::ptr_fun(&on_tool_changed), this))); + // Connect to the global tool change signal + _toolChangeConn = + INKSCAPE.signal_eventcontext_set.connect(sigc::hide<0>(sigc::bind(sigc::ptr_fun(&on_tool_changed), this))); // Connect to the global selection change, to invalidate cached randomize_bbox - _selChangeConn = INKSCAPE.signal_selection_changed.connect(sigc::hide<0>(sigc::bind(sigc::ptr_fun(&on_selection_changed), this))); + _selChangeConn = INKSCAPE.signal_selection_changed.connect( + sigc::hide<0>(sigc::bind(sigc::ptr_fun(&on_selection_changed), this))); randomize_bbox = Geom::OptRect(); show_all_children(); - on_tool_changed (this); // set current mode + on_tool_changed(this); // set current mode } AlignAndDistribute::~AlignAndDistribute() { - for (auto & it : _actionList) { + for (auto &it : _actionList) { delete it; } @@ -1161,44 +1084,45 @@ AlignAndDistribute::~AlignAndDistribute() _selChangeConn.disconnect(); } - -void AlignAndDistribute::on_ref_change(){ +void AlignAndDistribute::on_ref_change() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setInt("/dialogs/align/align-to", _combo.get_active_row_number()); - //Make blink the master + // Make blink the master } -void AlignAndDistribute::on_node_ref_change(){ +void AlignAndDistribute::on_node_ref_change() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setInt("/dialogs/align/align-nodes-to", _comboNode.get_active_row_number()); - //Make blink the master + // Make blink the master } -void AlignAndDistribute::on_selgrp_toggled(){ +void AlignAndDistribute::on_selgrp_toggled() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setInt("/dialogs/align/sel-as-groups", _selgrp.get_active()); - //Make blink the master + // Make blink the master } -void AlignAndDistribute::on_oncanvas_toggled(){ +void AlignAndDistribute::on_oncanvas_toggled() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setInt("/dialogs/align/oncanvas", _oncanvas.get_active()); - //Make blink the master + // Make blink the master } void AlignAndDistribute::setMode(bool nodeEdit) { - //Act on widgets used in node mode - void ( Gtk::Widget::*mNode) () = nodeEdit ? - &Gtk::Widget::show_all : &Gtk::Widget::hide; + // Act on widgets used in node mode + 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; + // Act on widgets used in selection mode + void (Gtk::Widget::*mSel)() = nodeEdit ? &Gtk::Widget::hide : &Gtk::Widget::show_all; ((_alignFrame).*(mSel))(); ((_distributeFrame).*(mSel))(); @@ -1206,108 +1130,68 @@ void AlignAndDistribute::setMode(bool nodeEdit) ((_removeOverlapFrame).*(mSel))(); ((_nodesFrame).*(mNode))(); _getContents()->queue_resize(); - } -void AlignAndDistribute::addAlignButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col) +void AlignAndDistribute::addAlignButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col) { - _actionList.push_back( - new ActionAlign( - id, tiptext, row, col, - *this , col + row * 5)); + _actionList.push_back(new ActionAlign(id, tiptext, row, col, *this, col + row * 5)); } -void AlignAndDistribute::addDistributeButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col, bool onInterSpace, - Geom::Dim2 orientation, float kBegin, float kEnd) +void AlignAndDistribute::addDistributeButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col, + bool onInterSpace, Geom::Dim2 orientation, float kBegin, float kEnd) { - _actionList.push_back( - new ActionDistribute( - id, tiptext, row, col, *this , - onInterSpace, orientation, - kBegin, kEnd - ) - ); + _actionList.push_back(new ActionDistribute(id, tiptext, row, col, *this, onInterSpace, orientation, kBegin, kEnd)); } -void AlignAndDistribute::addNodeButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint col, Geom::Dim2 orientation, bool distribute) +void AlignAndDistribute::addNodeButton(const Glib::ustring &id, const Glib::ustring tiptext, guint col, + Geom::Dim2 orientation, bool distribute) { - _actionList.push_back( - new ActionNode( - id, tiptext, col, - *this, orientation, distribute)); + _actionList.push_back(new ActionNode(id, tiptext, col, *this, orientation, distribute)); } -void AlignAndDistribute::addRemoveOverlapsButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col) +void AlignAndDistribute::addRemoveOverlapsButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, + guint col) { - _actionList.push_back( - new ActionRemoveOverlaps( - id, tiptext, row, col, *this) - ); + _actionList.push_back(new ActionRemoveOverlaps(id, tiptext, row, col, *this)); } -void AlignAndDistribute::addGraphLayoutButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col) +void AlignAndDistribute::addGraphLayoutButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, + guint col) { - _actionList.push_back( - new ActionGraphLayout( - id, tiptext, row, col, *this) - ); + _actionList.push_back(new ActionGraphLayout(id, tiptext, row, col, *this)); } -void AlignAndDistribute::addExchangePositionsButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col) +void AlignAndDistribute::addExchangePositionsButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, + guint col) { - _actionList.push_back( - new ActionExchangePositions( - id, tiptext, row, col, *this) - ); + _actionList.push_back(new ActionExchangePositions(id, tiptext, row, col, *this)); } void AlignAndDistribute::addExchangePositionsByZOrderButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col) + guint row, guint col) { - _actionList.push_back( - new ActionExchangePositions( - id, tiptext, row, col, *this, ActionExchangePositions::ZOrder) - ); + _actionList.push_back(new ActionExchangePositions(id, tiptext, row, col, *this, ActionExchangePositions::ZOrder)); } void AlignAndDistribute::addExchangePositionsClockwiseButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col) + guint row, guint col) { _actionList.push_back( - new ActionExchangePositions( - id, tiptext, row, col, *this, ActionExchangePositions::Clockwise) - ); + new ActionExchangePositions(id, tiptext, row, col, *this, ActionExchangePositions::Clockwise)); } -void AlignAndDistribute::addUnclumpButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col) +void AlignAndDistribute::addUnclumpButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col) { - _actionList.push_back( - new ActionUnclump( - id, tiptext, row, col, *this) - ); + _actionList.push_back(new ActionUnclump(id, tiptext, row, col, *this)); } -void AlignAndDistribute::addRandomizeButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col) +void AlignAndDistribute::addRandomizeButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col) { - _actionList.push_back( - new ActionRandomize( - id, tiptext, row, col, *this) - ); + _actionList.push_back(new ActionRandomize(id, tiptext, row, col, *this)); } -void AlignAndDistribute::addBaselineButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col, Gtk::Grid &table, Geom::Dim2 orientation, bool distribute) +void AlignAndDistribute::addBaselineButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col, + Gtk::Grid &table, Geom::Dim2 orientation, bool distribute) { - _actionList.push_back( - new ActionBaseline( - id, tiptext, row, col, - *this, table, orientation, distribute)); + _actionList.push_back(new ActionBaseline(id, tiptext, row, col, *this, table, orientation, distribute)); } } // namespace Dialog diff --git a/src/ui/dialog/align-and-distribute.h b/src/ui/dialog/align-and-distribute.h index 052ef7021d61a1aecac6d68ab0a9e21d0c6b66c0..eb1ff861aa195bb9e4cd1d767523dd07db4b635e 100644 --- a/src/ui/dialog/align-and-distribute.h +++ b/src/ui/dialog/align-and-distribute.h @@ -16,81 +16,66 @@ #ifndef INKSCAPE_UI_DIALOG_ALIGN_AND_DISTRIBUTE_H #define INKSCAPE_UI_DIALOG_ALIGN_AND_DISTRIBUTE_H -#include <list> -#include "ui/widget/panel.h" -#include "ui/widget/frame.h" - -#include <gtkmm/frame.h> -#include <gtkmm/comboboxtext.h> -#include <gtkmm/label.h> #include <gtkmm/checkbutton.h> +#include <gtkmm/comboboxtext.h> +#include <gtkmm/frame.h> #include <gtkmm/grid.h> +#include <gtkmm/label.h> +#include <list> #include "2geom/rect.h" +#include "ui/widget/frame.h" +#include "ui/widget/panel.h" class SPItem; namespace Inkscape { namespace UI { -namespace Tools{ +namespace Tools { class NodeTool; } namespace Dialog { class Action; - -class AlignAndDistribute : public Widget::Panel { +class AlignAndDistribute : public Widget::Panel +{ public: AlignAndDistribute(); ~AlignAndDistribute() override; static AlignAndDistribute &getInstance() { return *new AlignAndDistribute(); } - Gtk::Grid &align_table(){return _alignTable;} - Gtk::Grid &distribute_table(){return _distributeTable;} - Gtk::Grid &rearrange_table(){return _rearrangeTable;} - Gtk::Grid &removeOverlap_table(){return _removeOverlapTable;} - Gtk::Grid &nodes_table(){return _nodesTable;} + Gtk::Grid &align_table() { return _alignTable; } + Gtk::Grid &distribute_table() { return _distributeTable; } + Gtk::Grid &rearrange_table() { return _rearrangeTable; } + Gtk::Grid &removeOverlap_table() { return _removeOverlapTable; } + Gtk::Grid &nodes_table() { return _nodesTable; } void setMode(bool nodeEdit); Geom::OptRect randomize_bbox; protected: - void on_ref_change(); void on_node_ref_change(); void on_selgrp_toggled(); void on_oncanvas_toggled(); - void addDistributeButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col, bool onInterSpace, - Geom::Dim2 orientation, float kBegin, float kEnd); - void addAlignButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col); - void addNodeButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint col, Geom::Dim2 orientation, bool distribute); - void addRemoveOverlapsButton(const Glib::ustring &id, - const Glib::ustring tiptext, - guint row, guint col); - void addGraphLayoutButton(const Glib::ustring &id, - const Glib::ustring tiptext, - guint row, guint col); - void addExchangePositionsButton(const Glib::ustring &id, - const Glib::ustring tiptext, - guint row, guint col); - void addExchangePositionsByZOrderButton(const Glib::ustring &id, - const Glib::ustring tiptext, - guint row, guint col); - void addExchangePositionsClockwiseButton(const Glib::ustring &id, - const Glib::ustring tiptext, - guint row, guint col); - void addUnclumpButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col); - void addRandomizeButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col); - void addBaselineButton(const Glib::ustring &id, const Glib::ustring tiptext, - guint row, guint col, Gtk::Grid &table, Geom::Dim2 orientation, bool distribute); + void addDistributeButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col, + bool onInterSpace, Geom::Dim2 orientation, float kBegin, float kEnd); + void addAlignButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col); + void addNodeButton(const Glib::ustring &id, const Glib::ustring tiptext, guint col, Geom::Dim2 orientation, + bool distribute); + void addRemoveOverlapsButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col); + void addGraphLayoutButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col); + void addExchangePositionsButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col); + void addExchangePositionsByZOrderButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col); + void addExchangePositionsClockwiseButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, + guint col); + void addUnclumpButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col); + void addRandomizeButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col); + void addBaselineButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col, Gtk::Grid &table, + Geom::Dim2 orientation, bool distribute); std::list<Action *> _actionList; UI::Widget::Frame _alignFrame, _distributeFrame, _rearrangeFrame, _removeOverlapFrame, _nodesFrame; @@ -115,12 +100,12 @@ protected: SPDesktop *_desktop; sigc::connection _toolChangeConn; sigc::connection _selChangeConn; + private: AlignAndDistribute(AlignAndDistribute const &d) = delete; - AlignAndDistribute& operator=(AlignAndDistribute const &d) = delete; + AlignAndDistribute &operator=(AlignAndDistribute const &d) = delete; }; - struct BBoxSort { SPItem *item; @@ -129,48 +114,57 @@ struct BBoxSort BBoxSort(SPItem *pItem, Geom::Rect const &bounds, Geom::Dim2 orientation, double kBegin, double kEnd); BBoxSort(const BBoxSort &rhs); }; -bool operator< (const BBoxSort &a, const BBoxSort &b); - +bool operator<(const BBoxSort &a, const BBoxSort &b); -class Action { -public : - - enum AlignTarget { LAST=0, FIRST, BIGGEST, SMALLEST, PAGE, DRAWING, SELECTION }; - enum AlignTargetNode { LAST_NODE=0, FIRST_NODE, MID_NODE, MIN_NODE, MAX_NODE }; - Action(Glib::ustring id, - const Glib::ustring &tiptext, - guint row, guint column, - Gtk::Grid &parent, +class Action +{ +public: + enum AlignTarget + { + LAST = 0, + FIRST, + BIGGEST, + SMALLEST, + PAGE, + DRAWING, + SELECTION + }; + enum AlignTargetNode + { + LAST_NODE = 0, + FIRST_NODE, + MID_NODE, + MIN_NODE, + MAX_NODE + }; + Action(Glib::ustring id, const Glib::ustring &tiptext, guint row, guint column, Gtk::Grid &parent, AlignAndDistribute &dialog); - virtual ~Action()= default; + virtual ~Action() = default; AlignAndDistribute &_dialog; -private : - virtual void on_button_click(){} +private: + virtual void on_button_click() {} Glib::ustring _id; Gtk::Grid &_parent; }; - -class ActionAlign : public Action { -public : - struct Coeffs { - double mx0, mx1, my0, my1; - double sx0, sx1, sy0, sy1; - int verb_id; +class ActionAlign : public Action +{ +public: + struct Coeffs + { + double mx0, mx1, my0, my1; + double sx0, sx1, sy0, sy1; + int verb_id; }; - 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) + 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) {} /* @@ -179,13 +173,13 @@ public : static void do_verb_action(SPDesktop *desktop, int verb); static int verb_to_coeff(int verb); -private : - - - void on_button_click() override { - //Retrieve selected objects +private: + void on_button_click() override + { + // Retrieve selected objects SPDesktop *desktop = _dialog.getDesktop(); - if (!desktop) return; + if (!desktop) + return; do_action(desktop, _index); } @@ -197,10 +191,8 @@ private : AlignAndDistribute &_dialog; static const Coeffs _allCoeffs[19]; - }; - } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/arrange-tab.h b/src/ui/dialog/arrange-tab.h index 42e141ea05d719e6526af81f06891482e03074bb..f0df4317b6634281b03c20a84d356a2fff5dc6d9 100644 --- a/src/ui/dialog/arrange-tab.h +++ b/src/ui/dialog/arrange-tab.h @@ -26,20 +26,21 @@ namespace Dialog { class ArrangeTab : public Gtk::VBox { public: - ArrangeTab() = default;; - ~ArrangeTab() override = default;; - - /** - * Do the actual work! This method is invoked to actually arrange the - * selection - */ - virtual void arrange() = 0; + ArrangeTab() = default; + ; + ~ArrangeTab() override = default; + ; + + /** + * Do the actual work! This method is invoked to actually arrange the + * selection + */ + virtual void arrange() = 0; }; -} //namespace Dialog -} //namespace UI -} //namespace Inkscape - +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif /* INKSCAPE_UI_DIALOG_ARRANGE_TAB_H */ diff --git a/src/ui/dialog/attrdialog.cpp b/src/ui/dialog/attrdialog.cpp index 65c949ec4bb14f5d18261cae9cfd3dd8eb2eee4e..e869e4a18e51e140888042b94b14396714d96083 100644 --- a/src/ui/dialog/attrdialog.cpp +++ b/src/ui/dialog/attrdialog.cpp @@ -12,20 +12,19 @@ #include "attrdialog.h" -#include "verbs.h" -#include "selection.h" +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> + #include "document-undo.h" #include "message-context.h" #include "message-stack.h" +#include "selection.h" #include "style.h" #include "ui/icon-loader.h" #include "ui/widget/iconrenderer.h" - -#include "xml/node-event-vector.h" +#include "verbs.h" #include "xml/attribute-record.h" - -#include <gdk/gdkkeysyms.h> -#include <glibmm/i18n.h> +#include "xml/node-event-vector.h" /** * Return true if `node` is a text or comment node @@ -41,20 +40,14 @@ static bool is_text_or_comment_node(Inkscape::XML::Node const &node) } } -static void on_attr_changed (Inkscape::XML::Node * repr, - const gchar * name, - const gchar * /*old_value*/, - const gchar * new_value, - bool /*is_interactive*/, - gpointer data) +static void on_attr_changed(Inkscape::XML::Node *repr, const gchar *name, const gchar * /*old_value*/, + const gchar *new_value, bool /*is_interactive*/, gpointer data) { ATTR_DIALOG(data)->onAttrChanged(repr, name, new_value); } -static void on_content_changed (Inkscape::XML::Node * repr, - gchar const * oldcontent, - gchar const * newcontent, - gpointer data) +static void on_content_changed(Inkscape::XML::Node *repr, gchar const *oldcontent, gchar const *newcontent, + gpointer data) { auto self = ATTR_DIALOG(data); auto buffer = self->_content_tv->get_buffer(); @@ -66,11 +59,10 @@ static void on_content_changed (Inkscape::XML::Node * repr, } Inkscape::XML::NodeEventVector _repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - on_attr_changed, - on_content_changed, /* content_changed */ - nullptr /* order_changed */ + nullptr, /* child_added */ + nullptr, /* child_removed */ + on_attr_changed, on_content_changed, /* content_changed */ + nullptr /* order_changed */ }; namespace Inkscape { @@ -118,7 +110,7 @@ AttrDialog::AttrDialog() _store = Gtk::ListStore::create(_attrColumns); _treeView.set_model(_store); - Inkscape::UI::Widget::IconRenderer * addRenderer = manage(new Inkscape::UI::Widget::IconRenderer()); + Inkscape::UI::Widget::IconRenderer *addRenderer = manage(new Inkscape::UI::Widget::IconRenderer()); addRenderer->add_icon("edit-delete"); _treeView.append_column("", *addRenderer); @@ -294,7 +286,6 @@ static Glib::ustring prepare_rendervalue(const char *value) return renderval; } - /** * @brief AttrDialog::~AttrDialog * Class destructor @@ -313,7 +304,6 @@ void AttrDialog::startNameEdit(Gtk::CellEditable *cell, const Glib::ustring &pat entry->signal_key_press_event().connect(sigc::bind(sigc::mem_fun(*this, &AttrDialog::onNameKeyPressed), entry)); } - gboolean sp_show_attr_pop(gpointer data) { AttrDialog *attrdialog = reinterpret_cast<AttrDialog *>(data); @@ -379,7 +369,7 @@ void AttrDialog::popClosed() * @param desktop * This function sets the 'desktop' for the CSS pane. */ -void AttrDialog::setDesktop(SPDesktop* desktop) +void AttrDialog::setDesktop(SPDesktop *desktop) { setRepr(nullptr); _desktop = desktop; @@ -389,9 +379,10 @@ void AttrDialog::setDesktop(SPDesktop* desktop) * @brief AttrDialog::setRepr * Set the internal xml object that I'm working on right now. */ -void AttrDialog::setRepr(Inkscape::XML::Node * repr) +void AttrDialog::setRepr(Inkscape::XML::Node *repr) { - if ( repr == _repr ) return; + if (repr == _repr) + return; if (_repr) { _store->clear(); _repr->removeListenerByData(this); @@ -400,7 +391,7 @@ void AttrDialog::setRepr(Inkscape::XML::Node * repr) } _repr = repr; if (repr) { - Inkscape::GC::anchor(_repr); + Inkscape::GC::anchor(_repr); _repr->addListener(&_repr_events, this); _repr->synthesizeEvents(&_repr_events, this); @@ -443,7 +434,7 @@ void AttrDialog::attr_reset_context(gint attr) * @brief AttrDialog::onAttrChanged * This is called when the XML has an updated attribute */ -void AttrDialog::onAttrChanged(Inkscape::XML::Node *repr, const gchar * name, const gchar * new_value) +void AttrDialog::onAttrChanged(Inkscape::XML::Node *repr, const gchar *name, const gchar *new_value) { if (_updating) { return; @@ -452,12 +443,11 @@ void AttrDialog::onAttrChanged(Inkscape::XML::Node *repr, const gchar * name, co if (new_value) { renderval = prepare_rendervalue(new_value); } - for(auto iter: this->_store->children()) - { + for (auto iter : this->_store->children()) { Gtk::TreeModel::Row row = *iter; Glib::ustring col_name = row[_attrColumns._attributeName]; - if(name == col_name) { - if(new_value) { + if (name == col_name) { + if (new_value) { row[_attrColumns._attributeValue] = new_value; row[_attrColumns._attributeValueRender] = renderval; new_value = nullptr; // Don't make a new one @@ -481,7 +471,7 @@ void AttrDialog::onAttrChanged(Inkscape::XML::Node *repr, const gchar * name, co */ bool AttrDialog::onAttrCreate(GdkEventButton *event) { - if(event->type == GDK_BUTTON_RELEASE && event->button == 1 && this->_repr) { + if (event->type == GDK_BUTTON_RELEASE && event->button == 1 && this->_repr) { Gtk::TreeIter iter = _store->prepend(); Gtk::TreeModel::Path path = (Gtk::TreeModel::Path)iter; _treeView.set_cursor(path, *_nameCol, true); @@ -519,12 +509,11 @@ void AttrDialog::onAttrDelete(Glib::ustring path) bool AttrDialog::onKeyPressed(GdkEventKey *event) { bool ret = false; - if(this->_repr) { + if (this->_repr) { auto selection = this->_treeView.get_selection(); Gtk::TreeModel::Row row = *(selection->get_selected()); Gtk::TreeIter iter = *(selection->get_selected()); - switch (event->keyval) - { + switch (event->keyval) { case GDK_KEY_Delete: case GDK_KEY_KP_Delete: { // Create new attribute (repeat code, fold into above event!) @@ -537,8 +526,7 @@ bool AttrDialog::onKeyPressed(GdkEventKey *event) ret = true; } break; case GDK_KEY_plus: - case GDK_KEY_Insert: - { + case GDK_KEY_Insert: { // Create new attribute (repeat code, fold into above event!) Gtk::TreeIter iter = this->_store->prepend(); Gtk::TreeModel::Path path = (Gtk::TreeModel::Path)iter; @@ -575,7 +563,6 @@ bool AttrDialog::onNameKeyPressed(GdkEventKey *event, Gtk::Entry *entry) return ret; } - bool AttrDialog::onValueKeyPressed(GdkEventKey *event, Gtk::Entry *entry) { g_debug("StyleDialog::_onValueKeyPressed"); @@ -612,12 +599,12 @@ gboolean sp_attrdialog_store_move_to_next(gpointer data) * @return * Called when the name is edited in the TreeView editable column */ -void AttrDialog::nameEdited (const Glib::ustring& path, const Glib::ustring& name) +void AttrDialog::nameEdited(const Glib::ustring &path, const Glib::ustring &name) { Gtk::TreeIter iter = *_store->get_iter(path); _modelpath = (Gtk::TreeModel::Path)iter; Gtk::TreeModel::Row row = *iter; - if(row && this->_repr) { + if (row && this->_repr) { Glib::ustring old_name = row[_attrColumns._attributeName]; if (old_name == name) { g_timeout_add(50, &sp_attrdialog_store_move_to_next, this); @@ -635,7 +622,7 @@ void AttrDialog::nameEdited (const Glib::ustring& path, const Glib::ustring& nam return; } } - if(std::any_of(name.begin(), name.end(), isspace)) { + if (std::any_of(name.begin(), name.end(), isspace)) { return; } // Copy old value and remove old name @@ -682,20 +669,21 @@ void AttrDialog::valueCanceledPop() * @return * Called when the value is edited in the TreeView editable column */ -void AttrDialog::valueEdited (const Glib::ustring& path, const Glib::ustring& value) +void AttrDialog::valueEdited(const Glib::ustring &path, const Glib::ustring &value) { Gtk::TreeModel::Row row = *_store->get_iter(path); - if(row && this->_repr) { + if (row && this->_repr) { Glib::ustring name = row[_attrColumns._attributeName]; Glib::ustring old_value = row[_attrColumns._attributeValue]; if (old_value == value) { return; } - if(name.empty()) return; + if (name.empty()) + return; { _repr->setAttributeOrRemoveIfEmpty(name, value); } - if(!value.empty()) { + if (!value.empty()) { row[_attrColumns._attributeValue] = value; Glib::ustring renderval = prepare_rendervalue(value.c_str()); row[_attrColumns._attributeValueRender] = renderval; diff --git a/src/ui/dialog/attrdialog.h b/src/ui/dialog/attrdialog.h index d1ac0a91bb70ca8dad557f997f4fdd2092b0a064..b1898bf3de9b8a867faba7fe3594e3965f7d46a1 100644 --- a/src/ui/dialog/attrdialog.h +++ b/src/ui/dialog/attrdialog.h @@ -13,8 +13,6 @@ #ifndef SEEN_UI_DIALOGS_ATTRDIALOG_H #define SEEN_UI_DIALOGS_ATTRDIALOG_H -#include "desktop.h" -#include "message.h" #include <gtkmm/dialog.h> #include <gtkmm/liststore.h> #include <gtkmm/popover.h> @@ -23,7 +21,10 @@ #include <gtkmm/treeview.h> #include <ui/widget/panel.h> -#define ATTR_DIALOG(obj) (dynamic_cast<Inkscape::UI::Dialog::AttrDialog*>((Inkscape::UI::Dialog::AttrDialog*)obj)) +#include "desktop.h" +#include "message.h" + +#define ATTR_DIALOG(obj) (dynamic_cast<Inkscape::UI::Dialog::AttrDialog *>((Inkscape::UI::Dialog::AttrDialog *)obj)) namespace Inkscape { class MessageStack; @@ -45,12 +46,14 @@ public: static AttrDialog &getInstance() { return *new AttrDialog(); } // Data structure - class AttrColumns : public Gtk::TreeModel::ColumnRecord { + class AttrColumns : public Gtk::TreeModel::ColumnRecord + { public: - AttrColumns() { - add(_attributeName); - add(_attributeValue); - add(_attributeValueRender); + AttrColumns() + { + add(_attributeName); + add(_attributeValue); + add(_attributeValueRender); } Gtk::TreeModelColumn<Glib::ustring> _attributeName; Gtk::TreeModelColumn<Glib::ustring> _attributeValue; @@ -88,15 +91,15 @@ public: Gtk::HBox _buttonBox; Gtk::Button _buttonAddAttribute; // Variables - Inkscape - SPDesktop* _desktop; - Inkscape::XML::Node* _repr; + SPDesktop *_desktop; + Inkscape::XML::Node *_repr; Gtk::HBox status_box; Gtk::Label status; bool _updating; // Helper functions - void setDesktop(SPDesktop* desktop) override; - void setRepr(Inkscape::XML::Node * repr); + void setDesktop(SPDesktop *desktop) override; + void setRepr(Inkscape::XML::Node *repr); void setUndo(Glib::ustring const &event_description); /** * Sets the XML status bar, depending on which attr is selected. @@ -108,7 +111,7 @@ public: * Signal handlers */ sigc::connection _message_changed_connection; - void onAttrChanged(Inkscape::XML::Node *repr, const gchar * name, const gchar * new_value); + void onAttrChanged(Inkscape::XML::Node *repr, const gchar *name, const gchar *new_value); bool onNameKeyPressed(GdkEventKey *event, Gtk::Entry *entry); bool onValueKeyPressed(GdkEventKey *event, Gtk::Entry *entry); void onAttrDelete(Glib::ustring path); @@ -124,7 +127,6 @@ public: void valueEditedPop(); }; - } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/behavior.h b/src/ui/dialog/behavior.h index 1b6c7c75f80cc429beca18b3c47570a8851ea509..53dbe159d60f08a3b303d26de3c44164667b7b2f 100644 --- a/src/ui/dialog/behavior.h +++ b/src/ui/dialog/behavior.h @@ -13,8 +13,8 @@ #ifndef INKSCAPE_UI_DIALOG_BEHAVIOR_H #define INKSCAPE_UI_DIALOG_BEHAVIOR_H -#include <gtkmm/button.h> #include <gtkmm/box.h> +#include <gtkmm/button.h> class SPDesktop; @@ -36,50 +36,49 @@ Behavior *create(Dialog &dialog) return T::create(dialog); } - -class Behavior { - +class Behavior +{ public: virtual ~Behavior() = default; /** Gtk::Dialog methods */ - virtual operator Gtk::Widget&() =0; - virtual GtkWidget *gobj() =0; - virtual void present() =0; - virtual Gtk::Box *get_vbox() =0; - virtual void show() =0; - virtual void hide() =0; - virtual void show_all_children() =0; - virtual void resize(int width, int height) =0; - virtual void move(int x, int y) =0; - virtual void set_position(Gtk::WindowPosition) =0; - virtual void set_size_request(int width, int height) =0; - virtual void size_request(Gtk::Requisition &requisition) =0; - virtual void get_position(int &x, int &y) =0; - virtual void get_size(int &width, int &height) =0; - virtual void set_title(Glib::ustring title) =0; - virtual void set_sensitive(bool sensitive) =0; + virtual operator Gtk::Widget &() = 0; + virtual GtkWidget *gobj() = 0; + virtual void present() = 0; + virtual Gtk::Box *get_vbox() = 0; + virtual void show() = 0; + virtual void hide() = 0; + virtual void show_all_children() = 0; + virtual void resize(int width, int height) = 0; + virtual void move(int x, int y) = 0; + virtual void set_position(Gtk::WindowPosition) = 0; + virtual void set_size_request(int width, int height) = 0; + virtual void size_request(Gtk::Requisition &requisition) = 0; + virtual void get_position(int &x, int &y) = 0; + virtual void get_size(int &width, int &height) = 0; + virtual void set_title(Glib::ustring title) = 0; + virtual void set_sensitive(bool sensitive) = 0; /** Gtk::Dialog signal proxies */ - virtual Glib::SignalProxy0<void> signal_show() =0; - virtual Glib::SignalProxy0<void> signal_hide() =0; - virtual Glib::SignalProxy1<bool, GdkEventAny *> signal_delete_event() =0; + virtual Glib::SignalProxy0<void> signal_show() = 0; + virtual Glib::SignalProxy0<void> signal_hide() = 0; + virtual Glib::SignalProxy1<bool, GdkEventAny *> signal_delete_event() = 0; /** Custom signal handlers */ - virtual void onHideF12() =0; - virtual void onShowF12() =0; - virtual void onShutdown() =0; - virtual void onDesktopActivated(SPDesktop *desktop) =0; + virtual void onHideF12() = 0; + virtual void onShowF12() = 0; + virtual void onShutdown() = 0; + virtual void onDesktopActivated(SPDesktop *desktop) = 0; protected: Behavior(Dialog &dialog) - : _dialog (dialog) - { } - - Dialog& _dialog; //< reference to the owner + : _dialog(dialog) + {} + + Dialog &_dialog; //< reference to the owner private: - Behavior() = delete; // no constructor without params + Behavior() = delete; // no constructor without params Behavior(const Behavior &) = delete; // no copy Behavior &operator=(const Behavior &) = delete; // no assign }; @@ -89,8 +88,7 @@ private: } // namespace UI } // namespace Inkscape - -#endif //INKSCAPE_UI_DIALOG_BEHAVIOR_H +#endif // INKSCAPE_UI_DIALOG_BEHAVIOR_H /* Local Variables: diff --git a/src/ui/dialog/calligraphic-profile-rename.cpp b/src/ui/dialog/calligraphic-profile-rename.cpp index 604ac7f70bac7161cedf69ff8ca47c146bf12662..93e767a02bec189cfb9d7480409c0add597b023f 100644 --- a/src/ui/dialog/calligraphic-profile-rename.cpp +++ b/src/ui/dialog/calligraphic-profile-rename.cpp @@ -15,6 +15,7 @@ */ #include "calligraphic-profile-rename.h" + #include <glibmm/i18n.h> #include <gtkmm/grid.h> @@ -24,9 +25,9 @@ namespace Inkscape { namespace UI { namespace Dialog { -CalligraphicProfileRename::CalligraphicProfileRename() : - _layout_table(Gtk::manage(new Gtk::Grid())), - _applied(false) +CalligraphicProfileRename::CalligraphicProfileRename() + : _layout_table(Gtk::manage(new Gtk::Grid())) + , _applied(false) { set_title(_("Edit profile")); @@ -60,15 +61,12 @@ CalligraphicProfileRename::CalligraphicProfileRename() : _apply_button.set_label(_("_Save")); _apply_button.set_can_default(); - _close_button.signal_clicked() - .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)); + _close_button.signal_clicked().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)); - signal_delete_event().connect( sigc::bind_return( - sigc::hide(sigc::mem_fun(*this, &CalligraphicProfileRename::_close)), true ) ); + 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); @@ -103,8 +101,8 @@ void CalligraphicProfileRename::_close() void CalligraphicProfileRename::show(SPDesktop *desktop, const Glib::ustring profile_name) { CalligraphicProfileRename &dial = instance(); - dial._applied=false; - dial._deleted=false; + dial._applied = false; + dial._deleted = false; dial.set_modal(true); dial._profile_name = profile_name; @@ -119,10 +117,10 @@ void CalligraphicProfileRename::show(SPDesktop *desktop, const Glib::ustring pro dial._delete_button.set_visible(true); } - desktop->setWindowTransient (dial.gobj()); + desktop->setWindowTransient(dial.gobj()); dial.property_destroy_with_parent() = true; // dial.Gtk::Dialog::show(); - //dial.present(); + // dial.present(); dial.run(); } diff --git a/src/ui/dialog/calligraphic-profile-rename.h b/src/ui/dialog/calligraphic-profile-rename.h index 195275b9b2aae70ba5c735c7594ee8f5015df8ee..0bd56d22b31927bee162c0aca0d47dfecab0b2c8 100644 --- a/src/ui/dialog/calligraphic-profile-rename.h +++ b/src/ui/dialog/calligraphic-profile-rename.h @@ -25,50 +25,45 @@ class SPDesktop; namespace Inkscape { namespace UI { namespace Dialog { - -class CalligraphicProfileRename : public Gtk::Dialog { + +class CalligraphicProfileRename : public Gtk::Dialog +{ public: CalligraphicProfileRename(); ~CalligraphicProfileRename() override = default; - Glib::ustring getName() const { - return "CalligraphicProfileRename"; - } - + Glib::ustring getName() const { return "CalligraphicProfileRename"; } + 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; - } + static bool applied() { return instance()._applied; } + static bool deleted() { return instance()._deleted; } + static Glib::ustring getProfileName() { return instance()._profile_name; } protected: void _close(); void _apply(); void _delete(); - Gtk::Label _profile_name_label; - Gtk::Entry _profile_name_entry; - Gtk::Grid* _layout_table; + Gtk::Label _profile_name_label; + Gtk::Entry _profile_name_entry; + Gtk::Grid *_layout_table; - Gtk::Button _close_button; - Gtk::Button _delete_button; - Gtk::Button _apply_button; + 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() + { static CalligraphicProfileRename instance_; return instance_; } - CalligraphicProfileRename(CalligraphicProfileRename const &) = delete; // no copy + CalligraphicProfileRename(CalligraphicProfileRename const &) = delete; // no copy CalligraphicProfileRename &operator=(CalligraphicProfileRename const &) = delete; // no assign }; - + } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/clonetiler.cpp b/src/ui/dialog/clonetiler.cpp index 99f5837af3cb0f3b26bf9a7c1f47a2f6764be26b..17f6d288f2bf8d195deba6c3db7ead65b3496405 100644 --- a/src/ui/dialog/clonetiler.cpp +++ b/src/ui/dialog/clonetiler.cpp @@ -17,8 +17,8 @@ #include "clonetiler.h" +#include <2geom/transforms.h> #include <glibmm/i18n.h> - #include <gtkmm/adjustment.h> #include <gtkmm/checkbutton.h> #include <gtkmm/combobox.h> @@ -28,34 +28,27 @@ #include <gtkmm/radiobutton.h> #include <gtkmm/sizegroup.h> -#include <2geom/transforms.h> - #include "desktop.h" +#include "display/cairo-utils.h" +#include "display/drawing-context.h" +#include "display/drawing.h" #include "document-undo.h" #include "document.h" #include "filter-chemistry.h" #include "inkscape.h" #include "message-stack.h" -#include "unclump.h" -#include "verbs.h" - -#include "display/cairo-utils.h" -#include "display/drawing-context.h" -#include "display/drawing.h" - -#include "ui/icon-loader.h" - #include "object/sp-item.h" #include "object/sp-namedview.h" #include "object/sp-root.h" #include "object/sp-use.h" - +#include "svg/svg-color.h" +#include "svg/svg.h" +#include "ui/icon-loader.h" #include "ui/icon-names.h" #include "ui/widget/spinbutton.h" #include "ui/widget/unit-menu.h" - -#include "svg/svg-color.h" -#include "svg/svg.h" +#include "unclump.h" +#include "verbs.h" using Inkscape::DocumentUndo; using Inkscape::Util::unit_table; @@ -68,10 +61,12 @@ namespace Widget { * Simple extension of Gtk::CheckButton, which adds a flag * to indicate whether the box should be unticked when reset */ -class CheckButtonInternal : public Gtk::CheckButton { - private: +class CheckButtonInternal : public Gtk::CheckButton +{ +private: bool _uncheckable = false; - public: + +public: CheckButtonInternal() = default; CheckButtonInternal(const Glib::ustring &label) @@ -81,7 +76,7 @@ class CheckButtonInternal : public Gtk::CheckButton { void set_uncheckable(const bool val = true) { _uncheckable = val; } bool get_uncheckable() const { return _uncheckable; } }; -} +} // namespace Widget namespace Dialog { @@ -95,13 +90,13 @@ static unsigned trace_visionkey; static gdouble trace_zoom; static SPDocument *trace_doc = nullptr; -CloneTiler::CloneTiler () : - UI::Widget::Panel("/dialogs/clonetiler/", SP_VERB_DIALOG_CLONETILER), - table_row_labels(nullptr) +CloneTiler::CloneTiler() + : UI::Widget::Panel("/dialogs/clonetiler/", SP_VERB_DIALOG_CLONETILER) + , table_row_labels(nullptr) { Gtk::Box *contents = _getContents(); contents->set_spacing(0); - + { auto prefs = Inkscape::Preferences::get(); @@ -114,17 +109,17 @@ CloneTiler::CloneTiler () : nb = Gtk::manage(new Gtk::Notebook()); mainbox->pack_start(*nb, false, false, 0); - // Symmetry { auto vb = new_tab(nb, _("_Symmetry")); - /* TRANSLATORS: For the following 17 symmetry groups, see + /* TRANSLATORS: For the following 17 symmetry groups, see * http://www.bib.ulb.ac.be/coursmath/doc/17.htm (visual examples); * http://www.clarku.edu/~djoyce/wallpaper/seventeen.html (English vocabulary); or * http://membres.lycos.fr/villemingerard/Geometri/Sym1D.htm (French vocabulary). */ - struct SymGroups { + struct SymGroups + { gint group; Glib::ustring label; } const sym_groups[] = { @@ -158,11 +153,10 @@ CloneTiler::CloneTiler () : // Hack to add markup support auto cell_list = gtk_cell_layout_get_cells(GTK_CELL_LAYOUT(combo->gobj())); - gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo->gobj()), - GTK_CELL_RENDERER(cell_list->data), - "markup", 0, NULL); + gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo->gobj()), GTK_CELL_RENDERER(cell_list->data), "markup", + 0, NULL); - for (const auto & sg : sym_groups) { + for (const auto &sg : sym_groups) { // Add the description of the symgroup to a new row combo->append(sg.label); } @@ -179,74 +173,67 @@ CloneTiler::CloneTiler () : { auto vb = new_tab(nb, _("S_hift")); - auto table = table_x_y_rand (3); + auto table = table_x_y_rand(3); vb->pack_start(*table, false, false, 0); // X { auto l = Gtk::manage(new Gtk::Label("")); - // TRANSLATORS: "shift" means: the tiles will be shifted (offset) horizontally by this amount - // xgettext:no-c-format + // TRANSLATORS: "shift" means: the tiles will be shifted (offset) horizontally by this amount + // xgettext:no-c-format l->set_markup(_("<b>Shift X:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 2, 1); + table_attach(table, l, 1, 2, 1); } { - auto l = spinbox ( + auto l = spinbox( // xgettext:no-c-format - _("Horizontal shift per row (in % of tile width)"), "shiftx_per_j", - -10000, 10000, "%"); - table_attach (table, l, 0, 2, 2); + _("Horizontal shift per row (in % of tile width)"), "shiftx_per_j", -10000, 10000, "%"); + table_attach(table, l, 0, 2, 2); } { - auto l = spinbox ( + auto l = spinbox( // xgettext:no-c-format - _("Horizontal shift per column (in % of tile width)"), "shiftx_per_i", - -10000, 10000, "%"); - table_attach (table, l, 0, 2, 3); + _("Horizontal shift per column (in % of tile width)"), "shiftx_per_i", -10000, 10000, "%"); + table_attach(table, l, 0, 2, 3); } { - auto l = spinbox (_("Randomize the horizontal shift by this percentage"), "shiftx_rand", - 0, 1000, "%"); - table_attach (table, l, 0, 2, 4); + auto l = spinbox(_("Randomize the horizontal shift by this percentage"), "shiftx_rand", 0, 1000, "%"); + table_attach(table, l, 0, 2, 4); } // Y { auto l = Gtk::manage(new Gtk::Label("")); - // TRANSLATORS: "shift" means: the tiles will be shifted (offset) vertically by this amount - // xgettext:no-c-format + // TRANSLATORS: "shift" means: the tiles will be shifted (offset) vertically by this amount + // xgettext:no-c-format l->set_markup(_("<b>Shift Y:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 3, 1); + table_attach(table, l, 1, 3, 1); } { - auto l = spinbox ( + auto l = spinbox( // xgettext:no-c-format - _("Vertical shift per row (in % of tile height)"), "shifty_per_j", - -10000, 10000, "%"); - table_attach (table, l, 0, 3, 2); + _("Vertical shift per row (in % of tile height)"), "shifty_per_j", -10000, 10000, "%"); + table_attach(table, l, 0, 3, 2); } { - auto l = spinbox ( + auto l = spinbox( // xgettext:no-c-format - _("Vertical shift per column (in % of tile height)"), "shifty_per_i", - -10000, 10000, "%"); - table_attach (table, l, 0, 3, 3); + _("Vertical shift per column (in % of tile height)"), "shifty_per_i", -10000, 10000, "%"); + table_attach(table, l, 0, 3, 3); } { - auto l = spinbox ( - _("Randomize the vertical shift by this percentage"), "shifty_rand", - 0, 1000, "%"); - table_attach (table, l, 0, 3, 4); + auto l = spinbox(_("Randomize the vertical shift by this percentage"), "shifty_rand", 0, 1000, "%"); + table_attach(table, l, 0, 3, 4); } // Exponent @@ -255,21 +242,19 @@ CloneTiler::CloneTiler () : l->set_markup(_("<b>Exponent:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 4, 1); + table_attach(table, l, 1, 4, 1); } { - auto l = spinbox ( - _("Whether rows are spaced evenly (1), converge (<1) or diverge (>1)"), "shifty_exp", - 0, 10, "", true); - table_attach (table, l, 0, 4, 2); + auto l = spinbox(_("Whether rows are spaced evenly (1), converge (<1) or diverge (>1)"), "shifty_exp", + 0, 10, "", true); + table_attach(table, l, 0, 4, 2); } { - auto l = spinbox ( - _("Whether columns are spaced evenly (1), converge (<1) or diverge (>1)"), "shiftx_exp", - 0, 10, "", true); - table_attach (table, l, 0, 4, 3); + auto l = spinbox(_("Whether columns are spaced evenly (1), converge (<1) or diverge (>1)"), + "shiftx_exp", 0, 10, "", true); + table_attach(table, l, 0, 4, 3); } { // alternates @@ -278,17 +263,17 @@ CloneTiler::CloneTiler () : l->set_markup(_("<small>Alternate:</small>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 5, 1); + table_attach(table, l, 1, 5, 1); } { - auto l = checkbox (_("Alternate the sign of shifts for each row"), "shifty_alternate"); - table_attach (table, l, 0, 5, 2); + auto l = checkbox(_("Alternate the sign of shifts for each row"), "shifty_alternate"); + table_attach(table, l, 0, 5, 2); } { - auto l = checkbox (_("Alternate the sign of shifts for each column"), "shiftx_alternate"); - table_attach (table, l, 0, 5, 3); + auto l = checkbox(_("Alternate the sign of shifts for each column"), "shiftx_alternate"); + table_attach(table, l, 0, 5, 3); } { // Cumulate @@ -297,17 +282,17 @@ CloneTiler::CloneTiler () : l->set_markup(_("<small>Cumulate:</small>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 6, 1); + table_attach(table, l, 1, 6, 1); } { - auto l = checkbox (_("Cumulate the shifts for each row"), "shifty_cumulate"); - table_attach (table, l, 0, 6, 2); + auto l = checkbox(_("Cumulate the shifts for each row"), "shifty_cumulate"); + table_attach(table, l, 0, 6, 2); } { - auto l = checkbox (_("Cumulate the shifts for each column"), "shiftx_cumulate"); - table_attach (table, l, 0, 6, 3); + auto l = checkbox(_("Cumulate the shifts for each column"), "shiftx_cumulate"); + table_attach(table, l, 0, 6, 3); } { // Exclude tile width and height in shift @@ -316,22 +301,20 @@ CloneTiler::CloneTiler () : l->set_markup(_("<small>Exclude tile:</small>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 7, 1); + table_attach(table, l, 1, 7, 1); } { - auto l = checkbox (_("Exclude tile height in shift"), "shifty_excludeh"); - table_attach (table, l, 0, 7, 2); + auto l = checkbox(_("Exclude tile height in shift"), "shifty_excludeh"); + table_attach(table, l, 0, 7, 2); } { - auto l = checkbox (_("Exclude tile width in shift"), "shiftx_excludew"); - table_attach (table, l, 0, 7, 3); + auto l = checkbox(_("Exclude tile width in shift"), "shiftx_excludew"); + table_attach(table, l, 0, 7, 3); } - } - // Scale { auto vb = new_tab(nb, _("Sc_ale")); @@ -345,29 +328,26 @@ CloneTiler::CloneTiler () : l->set_markup(_("<b>Scale X:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 2, 1); + table_attach(table, l, 1, 2, 1); } { - auto l = spinbox ( + auto l = spinbox( // xgettext:no-c-format - _("Horizontal scale per row (in % of tile width)"), "scalex_per_j", - -100, 1000, "%"); - table_attach (table, l, 0, 2, 2); + _("Horizontal scale per row (in % of tile width)"), "scalex_per_j", -100, 1000, "%"); + table_attach(table, l, 0, 2, 2); } { - auto l = spinbox ( + auto l = spinbox( // xgettext:no-c-format - _("Horizontal scale per column (in % of tile width)"), "scalex_per_i", - -100, 1000, "%"); - table_attach (table, l, 0, 2, 3); + _("Horizontal scale per column (in % of tile width)"), "scalex_per_i", -100, 1000, "%"); + table_attach(table, l, 0, 2, 3); } { - auto l = spinbox (_("Randomize the horizontal scale by this percentage"), "scalex_rand", - 0, 1000, "%"); - table_attach (table, l, 0, 2, 4); + auto l = spinbox(_("Randomize the horizontal scale by this percentage"), "scalex_rand", 0, 1000, "%"); + table_attach(table, l, 0, 2, 4); } // Y @@ -376,29 +356,26 @@ CloneTiler::CloneTiler () : l->set_markup(_("<b>Scale Y:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 3, 1); + table_attach(table, l, 1, 3, 1); } { - auto l = spinbox ( + auto l = spinbox( // xgettext:no-c-format - _("Vertical scale per row (in % of tile height)"), "scaley_per_j", - -100, 1000, "%"); - table_attach (table, l, 0, 3, 2); + _("Vertical scale per row (in % of tile height)"), "scaley_per_j", -100, 1000, "%"); + table_attach(table, l, 0, 3, 2); } { - auto l = spinbox ( + auto l = spinbox( // xgettext:no-c-format - _("Vertical scale per column (in % of tile height)"), "scaley_per_i", - -100, 1000, "%"); - table_attach (table, l, 0, 3, 3); + _("Vertical scale per column (in % of tile height)"), "scaley_per_i", -100, 1000, "%"); + table_attach(table, l, 0, 3, 3); } { - auto l = spinbox (_("Randomize the vertical scale by this percentage"), "scaley_rand", - 0, 1000, "%"); - table_attach (table, l, 0, 3, 4); + auto l = spinbox(_("Randomize the vertical scale by this percentage"), "scaley_rand", 0, 1000, "%"); + table_attach(table, l, 0, 3, 4); } // Exponent @@ -407,19 +384,19 @@ CloneTiler::CloneTiler () : l->set_markup(_("<b>Exponent:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 4, 1); + table_attach(table, l, 1, 4, 1); } { - auto l = spinbox (_("Whether row scaling is uniform (1), converge (<1) or diverge (>1)"), "scaley_exp", - 0, 10, "", true); - table_attach (table, l, 0, 4, 2); + auto l = spinbox(_("Whether row scaling is uniform (1), converge (<1) or diverge (>1)"), "scaley_exp", + 0, 10, "", true); + table_attach(table, l, 0, 4, 2); } { - auto l = spinbox (_("Whether column scaling is uniform (1), converge (<1) or diverge (>1)"), "scalex_exp", - 0, 10, "", true); - table_attach (table, l, 0, 4, 3); + auto l = spinbox(_("Whether column scaling is uniform (1), converge (<1) or diverge (>1)"), + "scalex_exp", 0, 10, "", true); + table_attach(table, l, 0, 4, 3); } // Logarithmic (as in logarithmic spiral) @@ -428,19 +405,19 @@ CloneTiler::CloneTiler () : l->set_markup(_("<b>Base:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 5, 1); + table_attach(table, l, 1, 5, 1); } { - auto l = spinbox (_("Base for a logarithmic spiral: not used (0), converge (<1), or diverge (>1)"), "scaley_log", - 0, 10, "", false); - table_attach (table, l, 0, 5, 2); + auto l = spinbox(_("Base for a logarithmic spiral: not used (0), converge (<1), or diverge (>1)"), + "scaley_log", 0, 10, "", false); + table_attach(table, l, 0, 5, 2); } { - auto l = spinbox (_("Base for a logarithmic spiral: not used (0), converge (<1), or diverge (>1)"), "scalex_log", - 0, 10, "", false); - table_attach (table, l, 0, 5, 3); + auto l = spinbox(_("Base for a logarithmic spiral: not used (0), converge (<1), or diverge (>1)"), + "scalex_log", 0, 10, "", false); + table_attach(table, l, 0, 5, 3); } { // alternates @@ -449,17 +426,17 @@ CloneTiler::CloneTiler () : l->set_markup(_("<small>Alternate:</small>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 6, 1); + table_attach(table, l, 1, 6, 1); } { - auto l = checkbox (_("Alternate the sign of scales for each row"), "scaley_alternate"); - table_attach (table, l, 0, 6, 2); + auto l = checkbox(_("Alternate the sign of scales for each row"), "scaley_alternate"); + table_attach(table, l, 0, 6, 2); } { - auto l = checkbox (_("Alternate the sign of scales for each column"), "scalex_alternate"); - table_attach (table, l, 0, 6, 3); + auto l = checkbox(_("Alternate the sign of scales for each column"), "scalex_alternate"); + table_attach(table, l, 0, 6, 3); } { // Cumulate @@ -468,27 +445,25 @@ CloneTiler::CloneTiler () : l->set_markup(_("<small>Cumulate:</small>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 7, 1); + table_attach(table, l, 1, 7, 1); } { - auto l = checkbox (_("Cumulate the scales for each row"), "scaley_cumulate"); - table_attach (table, l, 0, 7, 2); + auto l = checkbox(_("Cumulate the scales for each row"), "scaley_cumulate"); + table_attach(table, l, 0, 7, 2); } { - auto l = checkbox (_("Cumulate the scales for each column"), "scalex_cumulate"); - table_attach (table, l, 0, 7, 3); + auto l = checkbox(_("Cumulate the scales for each column"), "scalex_cumulate"); + table_attach(table, l, 0, 7, 3); } - } - // Rotation { auto vb = new_tab(nb, _("_Rotation")); - auto table = table_x_y_rand (1); + auto table = table_x_y_rand(1); vb->pack_start(*table, false, false, 0); // Angle @@ -497,29 +472,26 @@ CloneTiler::CloneTiler () : l->set_markup(_("<b>Angle:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 2, 1); + table_attach(table, l, 1, 2, 1); } { - auto l = spinbox ( + auto l = spinbox( // xgettext:no-c-format - _("Rotate tiles by this angle for each row"), "rotate_per_j", - -180, 180, "°"); - table_attach (table, l, 0, 2, 2); + _("Rotate tiles by this angle for each row"), "rotate_per_j", -180, 180, "°"); + table_attach(table, l, 0, 2, 2); } { - auto l = spinbox ( + auto l = spinbox( // xgettext:no-c-format - _("Rotate tiles by this angle for each column"), "rotate_per_i", - -180, 180, "°"); - table_attach (table, l, 0, 2, 3); + _("Rotate tiles by this angle for each column"), "rotate_per_i", -180, 180, "°"); + table_attach(table, l, 0, 2, 3); } { - auto l = spinbox (_("Randomize the rotation angle by this percentage"), "rotate_rand", - 0, 100, "%"); - table_attach (table, l, 0, 2, 4); + auto l = spinbox(_("Randomize the rotation angle by this percentage"), "rotate_rand", 0, 100, "%"); + table_attach(table, l, 0, 2, 4); } { // alternates @@ -528,17 +500,17 @@ CloneTiler::CloneTiler () : l->set_markup(_("<small>Alternate:</small>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 3, 1); + table_attach(table, l, 1, 3, 1); } { - auto l = checkbox (_("Alternate the rotation direction for each row"), "rotate_alternatej"); - table_attach (table, l, 0, 3, 2); + auto l = checkbox(_("Alternate the rotation direction for each row"), "rotate_alternatej"); + table_attach(table, l, 0, 3, 2); } { - auto l = checkbox (_("Alternate the rotation direction for each column"), "rotate_alternatei"); - table_attach (table, l, 0, 3, 3); + auto l = checkbox(_("Alternate the rotation direction for each column"), "rotate_alternatei"); + table_attach(table, l, 0, 3, 3); } { // Cumulate @@ -547,22 +519,20 @@ CloneTiler::CloneTiler () : l->set_markup(_("<small>Cumulate:</small>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 4, 1); + table_attach(table, l, 1, 4, 1); } { - auto l = checkbox (_("Cumulate the rotation for each row"), "rotate_cumulatej"); - table_attach (table, l, 0, 4, 2); + auto l = checkbox(_("Cumulate the rotation for each row"), "rotate_cumulatej"); + table_attach(table, l, 0, 4, 2); } { - auto l = checkbox (_("Cumulate the rotation for each column"), "rotate_cumulatei"); - table_attach (table, l, 0, 4, 3); + auto l = checkbox(_("Cumulate the rotation for each column"), "rotate_cumulatei"); + table_attach(table, l, 0, 4, 3); } - } - // Blur and opacity { auto vb = new_tab(nb, _("_Blur & opacity")); @@ -570,32 +540,28 @@ CloneTiler::CloneTiler () : auto table = table_x_y_rand(1); vb->pack_start(*table, false, false, 0); - // Blur { auto l = Gtk::manage(new Gtk::Label("")); l->set_markup(_("<b>Blur:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 2, 1); + table_attach(table, l, 1, 2, 1); } { - auto l = spinbox (_("Blur tiles by this percentage for each row"), "blur_per_j", - 0, 100, "%"); - table_attach (table, l, 0, 2, 2); + auto l = spinbox(_("Blur tiles by this percentage for each row"), "blur_per_j", 0, 100, "%"); + table_attach(table, l, 0, 2, 2); } { - auto l = spinbox (_("Blur tiles by this percentage for each column"), "blur_per_i", - 0, 100, "%"); - table_attach (table, l, 0, 2, 3); + auto l = spinbox(_("Blur tiles by this percentage for each column"), "blur_per_i", 0, 100, "%"); + table_attach(table, l, 0, 2, 3); } { - auto l = spinbox (_("Randomize the tile blur by this percentage"), "blur_rand", - 0, 100, "%"); - table_attach (table, l, 0, 2, 4); + auto l = spinbox(_("Randomize the tile blur by this percentage"), "blur_rand", 0, 100, "%"); + table_attach(table, l, 0, 2, 4); } { // alternates @@ -604,46 +570,43 @@ CloneTiler::CloneTiler () : l->set_markup(_("<small>Alternate:</small>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 3, 1); + table_attach(table, l, 1, 3, 1); } { - auto l = checkbox (_("Alternate the sign of blur change for each row"), "blur_alternatej"); - table_attach (table, l, 0, 3, 2); + auto l = checkbox(_("Alternate the sign of blur change for each row"), "blur_alternatej"); + table_attach(table, l, 0, 3, 2); } { - auto l = checkbox (_("Alternate the sign of blur change for each column"), "blur_alternatei"); - table_attach (table, l, 0, 3, 3); + auto l = checkbox(_("Alternate the sign of blur change for each column"), "blur_alternatei"); + table_attach(table, l, 0, 3, 3); } - - // Dissolve { auto l = Gtk::manage(new Gtk::Label("")); l->set_markup(_("<b>Opacity:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 4, 1); + table_attach(table, l, 1, 4, 1); } { - auto l = spinbox (_("Decrease tile opacity by this percentage for each row"), "opacity_per_j", - 0, 100, "%"); - table_attach (table, l, 0, 4, 2); + auto l = + spinbox(_("Decrease tile opacity by this percentage for each row"), "opacity_per_j", 0, 100, "%"); + table_attach(table, l, 0, 4, 2); } { - auto l = spinbox (_("Decrease tile opacity by this percentage for each column"), "opacity_per_i", - 0, 100, "%"); - table_attach (table, l, 0, 4, 3); + auto l = spinbox(_("Decrease tile opacity by this percentage for each column"), "opacity_per_i", 0, 100, + "%"); + table_attach(table, l, 0, 4, 3); } { - auto l = spinbox (_("Randomize the tile opacity by this percentage"), "opacity_rand", - 0, 100, "%"); - table_attach (table, l, 0, 4, 4); + auto l = spinbox(_("Randomize the tile opacity by this percentage"), "opacity_rand", 0, 100, "%"); + table_attach(table, l, 0, 4, 4); } { // alternates @@ -652,21 +615,20 @@ CloneTiler::CloneTiler () : l->set_markup(_("<small>Alternate:</small>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 5, 1); + table_attach(table, l, 1, 5, 1); } { - auto l = checkbox (_("Alternate the sign of opacity change for each row"), "opacity_alternatej"); - table_attach (table, l, 0, 5, 2); + auto l = checkbox(_("Alternate the sign of opacity change for each row"), "opacity_alternatej"); + table_attach(table, l, 0, 5, 2); } { - auto l = checkbox (_("Alternate the sign of opacity change for each column"), "opacity_alternatei"); - table_attach (table, l, 0, 5, 3); + auto l = checkbox(_("Alternate the sign of opacity change for each column"), "opacity_alternatei"); + table_attach(table, l, 0, 5, 3); } } - // Color { auto vb = new_tab(nb, _("Co_lor")); @@ -678,16 +640,21 @@ CloneTiler::CloneTiler () : auto l = Gtk::manage(new Gtk::Label(_("Initial color: "))); hb->pack_start(*l, false, false, 0); - guint32 rgba = 0x000000ff | sp_svg_read_color (prefs->getString(prefs_path + "initial_color").data(), 0x000000ff); - color_picker = new Inkscape::UI::Widget::ColorPicker (*new Glib::ustring(_("Initial color of tiled clones")), *new Glib::ustring(_("Initial color for clones (works only if the original has unset fill or stroke or on spray tool in copy mode)")), rgba, false); - color_changed_connection = color_picker->connectChanged(sigc::mem_fun(*this, &CloneTiler::on_picker_color_changed)); + guint32 rgba = + 0x000000ff | sp_svg_read_color(prefs->getString(prefs_path + "initial_color").data(), 0x000000ff); + color_picker = new Inkscape::UI::Widget::ColorPicker( + *new Glib::ustring(_("Initial color of tiled clones")), + *new Glib::ustring(_("Initial color for clones (works only if the original has unset fill or " + "stroke or on spray tool in copy mode)")), + rgba, false); + color_changed_connection = + color_picker->connectChanged(sigc::mem_fun(*this, &CloneTiler::on_picker_color_changed)); hb->pack_start(*color_picker, false, false, 0); vb->pack_start(*hb, false, false, 0); } - auto table = table_x_y_rand(3); vb->pack_start(*table, false, false, 0); @@ -697,53 +664,50 @@ CloneTiler::CloneTiler () : l->set_markup(_("<b>H:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 2, 1); + table_attach(table, l, 1, 2, 1); } { - auto l = spinbox (_("Change the tile hue by this percentage for each row"), "hue_per_j", - -100, 100, "%"); - table_attach (table, l, 0, 2, 2); + auto l = spinbox(_("Change the tile hue by this percentage for each row"), "hue_per_j", -100, 100, "%"); + table_attach(table, l, 0, 2, 2); } { - auto l = spinbox (_("Change the tile hue by this percentage for each column"), "hue_per_i", - -100, 100, "%"); - table_attach (table, l, 0, 2, 3); + auto l = + spinbox(_("Change the tile hue by this percentage for each column"), "hue_per_i", -100, 100, "%"); + table_attach(table, l, 0, 2, 3); } { - auto l = spinbox (_("Randomize the tile hue by this percentage"), "hue_rand", - 0, 100, "%"); - table_attach (table, l, 0, 2, 4); + auto l = spinbox(_("Randomize the tile hue by this percentage"), "hue_rand", 0, 100, "%"); + table_attach(table, l, 0, 2, 4); } - // Saturation { auto l = Gtk::manage(new Gtk::Label("")); l->set_markup(_("<b>S:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 3, 1); + table_attach(table, l, 1, 3, 1); } { - auto l = spinbox (_("Change the color saturation by this percentage for each row"), "saturation_per_j", - -100, 100, "%"); - table_attach (table, l, 0, 3, 2); + auto l = spinbox(_("Change the color saturation by this percentage for each row"), "saturation_per_j", + -100, 100, "%"); + table_attach(table, l, 0, 3, 2); } { - auto l = spinbox (_("Change the color saturation by this percentage for each column"), "saturation_per_i", - -100, 100, "%"); - table_attach (table, l, 0, 3, 3); + auto l = spinbox(_("Change the color saturation by this percentage for each column"), + "saturation_per_i", -100, 100, "%"); + table_attach(table, l, 0, 3, 3); } { - auto l = spinbox (_("Randomize the color saturation by this percentage"), "saturation_rand", - 0, 100, "%"); - table_attach (table, l, 0, 3, 4); + auto l = + spinbox(_("Randomize the color saturation by this percentage"), "saturation_rand", 0, 100, "%"); + table_attach(table, l, 0, 3, 4); } // Lightness @@ -752,233 +716,246 @@ CloneTiler::CloneTiler () : l->set_markup(_("<b>L:</b>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 4, 1); + table_attach(table, l, 1, 4, 1); } { - auto l = spinbox (_("Change the color lightness by this percentage for each row"), "lightness_per_j", - -100, 100, "%"); - table_attach (table, l, 0, 4, 2); + auto l = spinbox(_("Change the color lightness by this percentage for each row"), "lightness_per_j", + -100, 100, "%"); + table_attach(table, l, 0, 4, 2); } { - auto l = spinbox (_("Change the color lightness by this percentage for each column"), "lightness_per_i", - -100, 100, "%"); - table_attach (table, l, 0, 4, 3); + auto l = spinbox(_("Change the color lightness by this percentage for each column"), "lightness_per_i", + -100, 100, "%"); + table_attach(table, l, 0, 4, 3); } { - auto l = spinbox (_("Randomize the color lightness by this percentage"), "lightness_rand", - 0, 100, "%"); - table_attach (table, l, 0, 4, 4); + auto l = spinbox(_("Randomize the color lightness by this percentage"), "lightness_rand", 0, 100, "%"); + table_attach(table, l, 0, 4, 4); } - { // alternates auto l = Gtk::manage(new Gtk::Label("")); l->set_markup(_("<small>Alternate:</small>")); l->set_xalign(0.0); table_row_labels->add_widget(*l); - table_attach (table, l, 1, 5, 1); + table_attach(table, l, 1, 5, 1); } { - auto l = checkbox (_("Alternate the sign of color changes for each row"), "color_alternatej"); - table_attach (table, l, 0, 5, 2); + auto l = checkbox(_("Alternate the sign of color changes for each row"), "color_alternatej"); + table_attach(table, l, 0, 5, 2); } { - auto l = checkbox (_("Alternate the sign of color changes for each column"), "color_alternatei"); - table_attach (table, l, 0, 5, 3); + auto l = checkbox(_("Alternate the sign of color changes for each column"), "color_alternatei"); + table_attach(table, l, 0, 5, 3); } - } // Trace { auto vb = new_tab(nb, _("_Trace")); - { - auto hb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, VB_MARGIN)); - hb->set_border_width(4); - hb->set_homogeneous(false); - vb->pack_start(*hb, false, false, 0); - - _b = Gtk::manage(new UI::Widget::CheckButtonInternal(_("Trace the drawing under the clones/sprayed items"))); - _b->set_uncheckable(); - bool old = prefs->getBool(prefs_path + "dotrace"); - _b->set_active(old); - _b->set_tooltip_text(_("For each clone/sprayed item, pick a value from the drawing in its location and apply it")); - hb->pack_start(*_b, false, false, 0); - _b->signal_toggled().connect(sigc::mem_fun(*this, &CloneTiler::do_pick_toggled)); - } - - { - auto vvb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL, 0)); - vvb->set_homogeneous(false); - vb->pack_start(*vvb, false, false, 0); - _dotrace = vvb; - { - auto frame = Gtk::manage(new Gtk::Frame(_("1. Pick from the drawing:"))); - vvb->pack_start(*frame, false, false, 0); - - auto table = Gtk::manage(new Gtk::Grid()); - table->set_row_spacing(4); - table->set_column_spacing(6); - table->set_border_width(4); - frame->add(*table); - - Gtk::RadioButtonGroup rb_group; - { - auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, _("Color"))); - radio->set_tooltip_text(_("Pick the visible color and opacity")); - table_attach(table, radio, 0.0, 1, 1); - radio->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_COLOR)); - radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_COLOR); - } - { - auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, _("Opacity"))); - radio->set_tooltip_text(_("Pick the total accumulated opacity")); - table_attach (table, radio, 0.0, 2, 1); - radio->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_OPACITY)); - radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_OPACITY); - } - { - auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, _("R"))); - radio->set_tooltip_text(_("Pick the Red component of the color")); - table_attach (table, radio, 0.0, 1, 2); - radio->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_R)); - radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_R); - } - { - auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, _("G"))); - radio->set_tooltip_text(_("Pick the Green component of the color")); - table_attach (table, radio, 0.0, 2, 2); - radio->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_G)); - radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_G); - } - { - auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, _("B"))); - radio->set_tooltip_text(_("Pick the Blue component of the color")); - table_attach (table, radio, 0.0, 3, 2); - radio->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_B)); - radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_B); - } - { - auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, C_("Clonetiler color hue", "H"))); - radio->set_tooltip_text(_("Pick the hue of the color")); - table_attach (table, radio, 0.0, 1, 3); - radio->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_H)); - radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_H); - } - { - auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, C_("Clonetiler color saturation", "S"))); - radio->set_tooltip_text(_("Pick the saturation of the color")); - table_attach (table, radio, 0.0, 2, 3); - radio->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_S)); - radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_S); - } - { - auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, C_("Clonetiler color lightness", "L"))); - radio->set_tooltip_text(_("Pick the lightness of the color")); - table_attach (table, radio, 0.0, 3, 3); - radio->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_L)); - radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_L); - } + auto hb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, VB_MARGIN)); + hb->set_border_width(4); + hb->set_homogeneous(false); + vb->pack_start(*hb, false, false, 0); + _b = Gtk::manage( + new UI::Widget::CheckButtonInternal(_("Trace the drawing under the clones/sprayed items"))); + _b->set_uncheckable(); + bool old = prefs->getBool(prefs_path + "dotrace"); + _b->set_active(old); + _b->set_tooltip_text( + _("For each clone/sprayed item, pick a value from the drawing in its location and apply it")); + hb->pack_start(*_b, false, false, 0); + _b->signal_toggled().connect(sigc::mem_fun(*this, &CloneTiler::do_pick_toggled)); } { - auto frame = Gtk::manage(new Gtk::Frame(_("2. Tweak the picked value:"))); - vvb->pack_start(*frame, false, false, VB_MARGIN); - - auto table = Gtk::manage(new Gtk::Grid()); - table->set_row_spacing(4); - table->set_column_spacing(6); - table->set_border_width(4); - frame->add(*table); - - { - auto l = Gtk::manage(new Gtk::Label("")); - l->set_markup(_("Gamma-correct:")); - table_attach (table, l, 1.0, 1, 1); - } - { - auto l = spinbox (_("Shift the mid-range of the picked value upwards (>0) or downwards (<0)"), "gamma_picked", - -10, 10, ""); - table_attach (table, l, 0.0, 1, 2); - } + auto vvb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL, 0)); + vvb->set_homogeneous(false); + vb->pack_start(*vvb, false, false, 0); + _dotrace = vvb; { - auto l = Gtk::manage(new Gtk::Label("")); - l->set_markup(_("Randomize:")); - table_attach (table, l, 1.0, 1, 3); - } - { - auto l = spinbox (_("Randomize the picked value by this percentage"), "rand_picked", - 0, 100, "%"); - table_attach (table, l, 0.0, 1, 4); + auto frame = Gtk::manage(new Gtk::Frame(_("1. Pick from the drawing:"))); + vvb->pack_start(*frame, false, false, 0); + + auto table = Gtk::manage(new Gtk::Grid()); + table->set_row_spacing(4); + table->set_column_spacing(6); + table->set_border_width(4); + frame->add(*table); + + Gtk::RadioButtonGroup rb_group; + { + auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, _("Color"))); + radio->set_tooltip_text(_("Pick the visible color and opacity")); + table_attach(table, radio, 0.0, 1, 1); + radio->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_COLOR)); + radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_COLOR); + } + { + auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, _("Opacity"))); + radio->set_tooltip_text(_("Pick the total accumulated opacity")); + table_attach(table, radio, 0.0, 2, 1); + radio->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_OPACITY)); + radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_OPACITY); + } + { + auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, _("R"))); + radio->set_tooltip_text(_("Pick the Red component of the color")); + table_attach(table, radio, 0.0, 1, 2); + radio->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_R)); + radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_R); + } + { + auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, _("G"))); + radio->set_tooltip_text(_("Pick the Green component of the color")); + table_attach(table, radio, 0.0, 2, 2); + radio->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_G)); + radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_G); + } + { + auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, _("B"))); + radio->set_tooltip_text(_("Pick the Blue component of the color")); + table_attach(table, radio, 0.0, 3, 2); + radio->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_B)); + radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_B); + } + { + auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, C_("Clonetiler color hue", "H"))); + radio->set_tooltip_text(_("Pick the hue of the color")); + table_attach(table, radio, 0.0, 1, 3); + radio->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_H)); + radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_H); + } + { + auto radio = + Gtk::manage(new Gtk::RadioButton(rb_group, C_("Clonetiler color saturation", "S"))); + radio->set_tooltip_text(_("Pick the saturation of the color")); + table_attach(table, radio, 0.0, 2, 3); + radio->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_S)); + radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_S); + } + { + auto radio = Gtk::manage(new Gtk::RadioButton(rb_group, C_("Clonetiler color lightness", "L"))); + radio->set_tooltip_text(_("Pick the lightness of the color")); + table_attach(table, radio, 0.0, 3, 3); + radio->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_switched), PICK_L)); + radio->set_active(prefs->getInt(prefs_path + "pick", 0) == PICK_L); + } } { - auto l = Gtk::manage(new Gtk::Label("")); - l->set_markup(_("Invert:")); - table_attach (table, l, 1.0, 2, 1); - } - { - auto l = checkbox (_("Invert the picked value"), "invert_picked"); - table_attach (table, l, 0.0, 2, 2); - } - } - - { - auto frame = Gtk::manage(new Gtk::Frame(_("3. Apply the value to the clones':"))); - vvb->pack_start(*frame, false, false, 0); + auto frame = Gtk::manage(new Gtk::Frame(_("2. Tweak the picked value:"))); + vvb->pack_start(*frame, false, false, VB_MARGIN); + + auto table = Gtk::manage(new Gtk::Grid()); + table->set_row_spacing(4); + table->set_column_spacing(6); + table->set_border_width(4); + frame->add(*table); + + { + auto l = Gtk::manage(new Gtk::Label("")); + l->set_markup(_("Gamma-correct:")); + table_attach(table, l, 1.0, 1, 1); + } + { + auto l = spinbox(_("Shift the mid-range of the picked value upwards (>0) or downwards (<0)"), + "gamma_picked", -10, 10, ""); + table_attach(table, l, 0.0, 1, 2); + } - auto table = Gtk::manage(new Gtk::Grid()); - table->set_row_spacing(4); - table->set_column_spacing(6); - table->set_border_width(4); - frame->add(*table); + { + auto l = Gtk::manage(new Gtk::Label("")); + l->set_markup(_("Randomize:")); + table_attach(table, l, 1.0, 1, 3); + } + { + auto l = + spinbox(_("Randomize the picked value by this percentage"), "rand_picked", 0, 100, "%"); + table_attach(table, l, 0.0, 1, 4); + } - { - auto b = Gtk::manage(new Gtk::CheckButton(_("Presence"))); - bool old = prefs->getBool(prefs_path + "pick_to_presence", true); - b->set_active(old); - b->set_tooltip_text(_("Each clone is created with the probability determined by the picked value in that point")); - table_attach (table, b, 0.0, 1, 1); - b->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_to), b, "pick_to_presence")); + { + auto l = Gtk::manage(new Gtk::Label("")); + l->set_markup(_("Invert:")); + table_attach(table, l, 1.0, 2, 1); + } + { + auto l = checkbox(_("Invert the picked value"), "invert_picked"); + table_attach(table, l, 0.0, 2, 2); + } } { - auto b = Gtk::manage(new Gtk::CheckButton(_("Size"))); - bool old = prefs->getBool(prefs_path + "pick_to_size"); - b->set_active(old); - b->set_tooltip_text(_("Each clone's size is determined by the picked value in that point")); - table_attach (table, b, 0.0, 2, 1); - b->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_to), b, "pick_to_size")); - } + auto frame = Gtk::manage(new Gtk::Frame(_("3. Apply the value to the clones':"))); + vvb->pack_start(*frame, false, false, 0); + + auto table = Gtk::manage(new Gtk::Grid()); + table->set_row_spacing(4); + table->set_column_spacing(6); + table->set_border_width(4); + frame->add(*table); + + { + auto b = Gtk::manage(new Gtk::CheckButton(_("Presence"))); + bool old = prefs->getBool(prefs_path + "pick_to_presence", true); + b->set_active(old); + b->set_tooltip_text(_( + "Each clone is created with the probability determined by the picked value in that point")); + table_attach(table, b, 0.0, 1, 1); + b->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_to), b, "pick_to_presence")); + } - { - auto b = Gtk::manage(new Gtk::CheckButton(_("Color"))); - bool old = prefs->getBool(prefs_path + "pick_to_color", false); - b->set_active(old); - b->set_tooltip_text(_("Each clone is painted by the picked color (the original must have unset fill or stroke)")); - table_attach (table, b, 0.0, 1, 2); - b->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_to), b, "pick_to_color")); - } + { + auto b = Gtk::manage(new Gtk::CheckButton(_("Size"))); + bool old = prefs->getBool(prefs_path + "pick_to_size"); + b->set_active(old); + b->set_tooltip_text(_("Each clone's size is determined by the picked value in that point")); + table_attach(table, b, 0.0, 2, 1); + b->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_to), b, "pick_to_size")); + } - { - auto b = Gtk::manage(new Gtk::CheckButton(_("Opacity"))); - bool old = prefs->getBool(prefs_path + "pick_to_opacity", false); - b->set_active(old); - b->set_tooltip_text(_("Each clone's opacity is determined by the picked value in that point")); - table_attach (table, b, 0.0, 2, 2); - b->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_to), b, "pick_to_opacity")); + { + auto b = Gtk::manage(new Gtk::CheckButton(_("Color"))); + bool old = prefs->getBool(prefs_path + "pick_to_color", false); + b->set_active(old); + b->set_tooltip_text(_( + "Each clone is painted by the picked color (the original must have unset fill or stroke)")); + table_attach(table, b, 0.0, 1, 2); + b->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_to), b, "pick_to_color")); + } + + { + auto b = Gtk::manage(new Gtk::CheckButton(_("Opacity"))); + bool old = prefs->getBool(prefs_path + "pick_to_opacity", false); + b->set_active(old); + b->set_tooltip_text(_("Each clone's opacity is determined by the picked value in that point")); + table_attach(table, b, 0.0, 2, 2); + b->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::pick_to), b, "pick_to_opacity")); + } } + vvb->set_sensitive(prefs->getBool(prefs_path + "dotrace")); } - vvb->set_sensitive(prefs->getBool(prefs_path + "dotrace")); - } } { @@ -1004,14 +981,15 @@ CloneTiler::CloneTiler () : { auto a = Gtk::Adjustment::create(0.0, 1, 500, 1, 10, 0); int value = prefs->getInt(prefs_path + "jmax", 2); - a->set_value (value); + a->set_value(value); auto sb = new Inkscape::UI::Widget::SpinButton(a, 1.0, 0); - sb->set_tooltip_text (_("How many rows in the tiling")); - sb->set_width_chars (7); + sb->set_tooltip_text(_("How many rows in the tiling")); + sb->set_width_chars(7); _rowscols->pack_start(*sb, true, true, 0); - a->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::xy_changed), a, "jmax")); + a->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::xy_changed), a, "jmax")); } { @@ -1023,14 +1001,15 @@ CloneTiler::CloneTiler () : { auto a = Gtk::Adjustment::create(0.0, 1, 500, 1, 10, 0); int value = prefs->getInt(prefs_path + "imax", 2); - a->set_value (value); + a->set_value(value); auto sb = new Inkscape::UI::Widget::SpinButton(a, 1.0, 0); - sb->set_tooltip_text (_("How many columns in the tiling")); - sb->set_width_chars (7); + sb->set_tooltip_text(_("How many columns in the tiling")); + sb->set_width_chars(7); _rowscols->pack_start(*sb, true, true, 0); - a->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::xy_changed), a, "imax")); + a->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &CloneTiler::xy_changed), a, "imax")); } table_attach(table, _rowscols, 0.0, 1, 2); @@ -1052,12 +1031,12 @@ CloneTiler::CloneTiler () : double value = prefs->getDouble(prefs_path + "fillwidth", 50.0); Inkscape::Util::Unit const *unit = unit_menu->getUnit(); gdouble const units = Inkscape::Util::Quantity::convert(value, "px", unit); - fill_width->set_value (units); + fill_width->set_value(units); auto e = new Inkscape::UI::Widget::SpinButton(fill_width, 1.0, 2); - e->set_tooltip_text (_("Width of the rectangle to be filled")); - e->set_width_chars (7); - e->set_digits (4); + e->set_tooltip_text(_("Width of the rectangle to be filled")); + e->set_width_chars(7); + e->set_digits(4); _widthheight->pack_start(*e, true, true, 0); fill_width->signal_value_changed().connect(sigc::mem_fun(*this, &CloneTiler::fill_width_changed)); } @@ -1074,19 +1053,18 @@ CloneTiler::CloneTiler () : double value = prefs->getDouble(prefs_path + "fillheight", 50.0); Inkscape::Util::Unit const *unit = unit_menu->getUnit(); gdouble const units = Inkscape::Util::Quantity::convert(value, "px", unit); - fill_height->set_value (units); + fill_height->set_value(units); auto e = new Inkscape::UI::Widget::SpinButton(fill_height, 1.0, 2); - e->set_tooltip_text (_("Height of the rectangle to be filled")); - e->set_width_chars (7); - e->set_digits (4); + e->set_tooltip_text(_("Height of the rectangle to be filled")); + e->set_width_chars(7); + e->set_digits(4); _widthheight->pack_start(*e, true, true, 0); fill_height->signal_value_changed().connect(sigc::mem_fun(*this, &CloneTiler::fill_height_changed)); } _widthheight->pack_start(*unit_menu, true, true, 0); table_attach(table, _widthheight, 0.0, 2, 2); - } // Switch @@ -1106,20 +1084,20 @@ CloneTiler::CloneTiler () : radio->set_tooltip_text(_("Fill the specified width and height with the tiling")); table_attach(table, radio, 0.0, 2, 1); radio->signal_toggled().connect(sigc::mem_fun(*this, &CloneTiler::switch_to_fill)); - + if (prefs->getBool(prefs_path + "fillrect")) { radio->set_active(true); } } } - // Use saved pos { auto hb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, VB_MARGIN)); mainbox->pack_start(*hb, false, false, 0); - _cb_keep_bbox = Gtk::manage(new UI::Widget::CheckButtonInternal(_("Use saved size and position of the tile"))); + _cb_keep_bbox = + Gtk::manage(new UI::Widget::CheckButtonInternal(_("Use saved size and position of the tile"))); auto keepbbox = prefs->getBool(prefs_path + "keepbbox", true); _cb_keep_bbox->set_active(keepbbox); _cb_keep_bbox->set_tooltip_text(_("Pretend that the size and position of the tile are the same " @@ -1181,8 +1159,10 @@ CloneTiler::CloneTiler () : // connect to global selection changed signal (so we can change desktops) and // external_change (so we're not fooled by undo) - selectChangedConn = INKSCAPE.signal_selection_changed.connect(sigc::mem_fun(*this, &CloneTiler::change_selection)); - externChangedConn = INKSCAPE.signal_external_change.connect(sigc::mem_fun(*this, &CloneTiler::external_change)); + selectChangedConn = + INKSCAPE.signal_selection_changed.connect(sigc::mem_fun(*this, &CloneTiler::change_selection)); + externChangedConn = + INKSCAPE.signal_external_change.connect(sigc::mem_fun(*this, &CloneTiler::external_change)); // update now change_selection(SP_ACTIVE_DESKTOP->getSelection()); @@ -1191,7 +1171,8 @@ CloneTiler::CloneTiler () : { auto b = Gtk::manage(new Gtk::Button(_(" R_eset "), true)); // TRANSLATORS: "change" is a noun here - b->set_tooltip_text(_("Reset all shifts, scales, rotates, opacity and color changes in the dialog to zero")); + b->set_tooltip_text( + _("Reset all shifts, scales, rotates, opacity and color changes in the dialog to zero")); b->signal_clicked().connect(sigc::mem_fun(*this, &CloneTiler::reset)); hb->pack_start(*b, false, false, 0); } @@ -1203,10 +1184,10 @@ CloneTiler::CloneTiler () : show_all(); } -CloneTiler::~CloneTiler () +CloneTiler::~CloneTiler() { - //subselChangedConn.disconnect(); - //selectModifiedConn.disconnect(); + // subselChangedConn.disconnect(); + // selectModifiedConn.disconnect(); selectChangedConn.disconnect(); externChangedConn.disconnect(); color_changed_connection.disconnect(); @@ -1250,9 +1231,9 @@ void CloneTiler::change_selection(Inkscape::Selection *selection) guint n = number_of_clones(selection->singleItem()); if (n > 0) { _buttons_on_tiles->set_sensitive(true); - gchar *sta = g_strdup_printf (_("<small>Object has <b>%d</b> tiled clones.</small>"), n); + gchar *sta = g_strdup_printf(_("<small>Object has <b>%d</b> tiled clones.</small>"), n); _status->set_markup(sta); - g_free (sta); + g_free(sta); } else { _buttons_on_tiles->set_sensitive(false); _status->set_markup(_("<small>Object has no tiled clones.</small>")); @@ -1272,55 +1253,42 @@ Geom::Affine CloneTiler::get_transform( int i, int j, // center, width, height of the tile - double cx, double cy, - double w, double h, + double cx, double cy, double w, double h, // values from the dialog: // Shift - double shiftx_per_i, double shifty_per_i, - double shiftx_per_j, double shifty_per_j, - double shiftx_rand, double shifty_rand, - double shiftx_exp, double shifty_exp, - int shiftx_alternate, int shifty_alternate, - int shiftx_cumulate, int shifty_cumulate, - int shiftx_excludew, int shifty_excludeh, + double shiftx_per_i, double shifty_per_i, double shiftx_per_j, double shifty_per_j, double shiftx_rand, + double shifty_rand, double shiftx_exp, double shifty_exp, int shiftx_alternate, int shifty_alternate, + int shiftx_cumulate, int shifty_cumulate, int shiftx_excludew, int shifty_excludeh, // Scale - double scalex_per_i, double scaley_per_i, - double scalex_per_j, double scaley_per_j, - double scalex_rand, double scaley_rand, - double scalex_exp, double scaley_exp, - double scalex_log, double scaley_log, - int scalex_alternate, int scaley_alternate, - int scalex_cumulate, int scaley_cumulate, + double scalex_per_i, double scaley_per_i, double scalex_per_j, double scaley_per_j, double scalex_rand, + double scaley_rand, double scalex_exp, double scaley_exp, double scalex_log, double scaley_log, + int scalex_alternate, int scaley_alternate, int scalex_cumulate, int scaley_cumulate, // Rotation - double rotate_per_i, double rotate_per_j, - double rotate_rand, - int rotate_alternatei, int rotate_alternatej, - int rotate_cumulatei, int rotate_cumulatej - ) + double rotate_per_i, double rotate_per_j, double rotate_rand, int rotate_alternatei, int rotate_alternatej, + int rotate_cumulatei, int rotate_cumulatej) { - // Shift (in units of tile width or height) ------------- double delta_shifti = 0.0; double delta_shiftj = 0.0; - if( shiftx_alternate ) { - delta_shifti = (double)(i%2); + if (shiftx_alternate) { + delta_shifti = (double)(i % 2); } else { - if( shiftx_cumulate ) { // Should the delta shifts be cumulative (i.e. 1, 1+2, 1+2+3, ...) - delta_shifti = (double)(i*i); + if (shiftx_cumulate) { // Should the delta shifts be cumulative (i.e. 1, 1+2, 1+2+3, ...) + delta_shifti = (double)(i * i); } else { delta_shifti = (double)i; } } - if( shifty_alternate ) { - delta_shiftj = (double)(j%2); + if (shifty_alternate) { + delta_shiftj = (double)(j % 2); } else { - if( shifty_cumulate ) { - delta_shiftj = (double)(j*j); + if (shifty_cumulate) { + delta_shiftj = (double)(j * j); } else { delta_shiftj = (double)j; } @@ -1329,13 +1297,14 @@ Geom::Affine CloneTiler::get_transform( // Random shift, only calculate if non-zero. double delta_shiftx_rand = 0.0; double delta_shifty_rand = 0.0; - if( shiftx_rand != 0.0 ) delta_shiftx_rand = shiftx_rand * g_random_double_range (-1, 1); - if( shifty_rand != 0.0 ) delta_shifty_rand = shifty_rand * g_random_double_range (-1, 1); - + if (shiftx_rand != 0.0) + delta_shiftx_rand = shiftx_rand * g_random_double_range(-1, 1); + if (shifty_rand != 0.0) + delta_shifty_rand = shifty_rand * g_random_double_range(-1, 1); // Delta shift (units of tile width/height) - double di = shiftx_per_i * delta_shifti + shiftx_per_j * delta_shiftj + delta_shiftx_rand; - double dj = shifty_per_i * delta_shifti + shifty_per_j * delta_shiftj + delta_shifty_rand; + double di = shiftx_per_i * delta_shifti + shiftx_per_j * delta_shiftj + delta_shiftx_rand; + double dj = shifty_per_i * delta_shifti + shifty_per_j * delta_shiftj + delta_shifty_rand; // Shift in actual x and y, used below double dx = w * di; @@ -1345,8 +1314,10 @@ Geom::Affine CloneTiler::get_transform( double shiftj = dj; // Include tile width and height in shift if required - if( !shiftx_excludew ) shifti += i; - if( !shifty_excludeh ) shiftj += j; + if (!shiftx_excludew) + shifti += i; + if (!shifty_excludeh) + shiftj += j; // Add exponential shift if necessary double shifti_sign = (shifti > 0.0) ? 1.0 : -1.0; @@ -1355,34 +1326,35 @@ Geom::Affine CloneTiler::get_transform( shiftj = shiftj_sign * pow(fabs(shiftj), shifty_exp); // Final shift - Geom::Affine rect_translate (Geom::Translate (w * shifti, h * shiftj)); + Geom::Affine rect_translate(Geom::Translate(w * shifti, h * shiftj)); // Rotation (in degrees) ------------ double delta_rotationi = 0.0; double delta_rotationj = 0.0; - if( rotate_alternatei ) { - delta_rotationi = (double)(i%2); + if (rotate_alternatei) { + delta_rotationi = (double)(i % 2); } else { - if( rotate_cumulatei ) { - delta_rotationi = (double)(i*i + i)/2.0; + if (rotate_cumulatei) { + delta_rotationi = (double)(i * i + i) / 2.0; } else { delta_rotationi = (double)i; } } - if( rotate_alternatej ) { - delta_rotationj = (double)(j%2); + if (rotate_alternatej) { + delta_rotationj = (double)(j % 2); } else { - if( rotate_cumulatej ) { - delta_rotationj = (double)(j*j + j)/2.0; + if (rotate_cumulatej) { + delta_rotationj = (double)(j * j + j) / 2.0; } else { delta_rotationj = (double)j; } } double delta_rotate_rand = 0.0; - if( rotate_rand != 0.0 ) delta_rotate_rand = rotate_rand * 180.0 * g_random_double_range (-1, 1); + if (rotate_rand != 0.0) + delta_rotate_rand = rotate_rand * 180.0 * g_random_double_range(-1, 1); double dr = rotate_per_i * delta_rotationi + rotate_per_j * delta_rotationj + delta_rotate_rand; @@ -1390,21 +1362,21 @@ Geom::Affine CloneTiler::get_transform( double delta_scalei = 0.0; double delta_scalej = 0.0; - if( scalex_alternate ) { - delta_scalei = (double)(i%2); + if (scalex_alternate) { + delta_scalei = (double)(i % 2); } else { - if( scalex_cumulate ) { // Should the delta scales be cumulative (i.e. 1, 1+2, 1+2+3, ...) - delta_scalei = (double)(i*i + i)/2.0; + if (scalex_cumulate) { // Should the delta scales be cumulative (i.e. 1, 1+2, 1+2+3, ...) + delta_scalei = (double)(i * i + i) / 2.0; } else { delta_scalei = (double)i; } } - if( scaley_alternate ) { - delta_scalej = (double)(j%2); + if (scaley_alternate) { + delta_scalej = (double)(j % 2); } else { - if( scaley_cumulate ) { - delta_scalej = (double)(j*j + j)/2.0; + if (scaley_cumulate) { + delta_scalej = (double)(j * j + j) / 2.0; } else { delta_scalej = (double)j; } @@ -1413,456 +1385,476 @@ Geom::Affine CloneTiler::get_transform( // Random scale, only calculate if non-zero. double delta_scalex_rand = 0.0; double delta_scaley_rand = 0.0; - if( scalex_rand != 0.0 ) delta_scalex_rand = scalex_rand * g_random_double_range (-1, 1); - if( scaley_rand != 0.0 ) delta_scaley_rand = scaley_rand * g_random_double_range (-1, 1); + if (scalex_rand != 0.0) + delta_scalex_rand = scalex_rand * g_random_double_range(-1, 1); + if (scaley_rand != 0.0) + delta_scaley_rand = scaley_rand * g_random_double_range(-1, 1); // But if random factors are same, scale x and y proportionally - if( scalex_rand == scaley_rand ) delta_scalex_rand = delta_scaley_rand; + if (scalex_rand == scaley_rand) + delta_scalex_rand = delta_scaley_rand; // Total delta scale - double scalex = 1.0 + scalex_per_i * delta_scalei + scalex_per_j * delta_scalej + delta_scalex_rand; - double scaley = 1.0 + scaley_per_i * delta_scalei + scaley_per_j * delta_scalej + delta_scaley_rand; + double scalex = 1.0 + scalex_per_i * delta_scalei + scalex_per_j * delta_scalej + delta_scalex_rand; + double scaley = 1.0 + scaley_per_i * delta_scalei + scaley_per_j * delta_scalej + delta_scaley_rand; - if( scalex < 0.0 ) scalex = 0.0; - if( scaley < 0.0 ) scaley = 0.0; + if (scalex < 0.0) + scalex = 0.0; + if (scaley < 0.0) + scaley = 0.0; // Add exponential scale if necessary - if ( scalex_exp != 1.0 ) scalex = pow( scalex, scalex_exp ); - if ( scaley_exp != 1.0 ) scaley = pow( scaley, scaley_exp ); + if (scalex_exp != 1.0) + scalex = pow(scalex, scalex_exp); + if (scaley_exp != 1.0) + scaley = pow(scaley, scaley_exp); // Add logarithmic factor if necessary - if ( scalex_log > 0.0 ) scalex = pow( scalex_log, scalex - 1.0 ); - if ( scaley_log > 0.0 ) scaley = pow( scaley_log, scaley - 1.0 ); + if (scalex_log > 0.0) + scalex = pow(scalex_log, scalex - 1.0); + if (scaley_log > 0.0) + scaley = pow(scaley_log, scaley - 1.0); // Alternative using rotation angle - //if ( scalex_log != 1.0 ) scalex *= pow( scalex_log, M_PI*dr/180 ); - //if ( scaley_log != 1.0 ) scaley *= pow( scaley_log, M_PI*dr/180 ); - + // if ( scalex_log != 1.0 ) scalex *= pow( scalex_log, M_PI*dr/180 ); + // if ( scaley_log != 1.0 ) scaley *= pow( scaley_log, M_PI*dr/180 ); // Calculate transformation matrices, translating back to "center of tile" (rotation center) before transforming - Geom::Affine drot_c = Geom::Translate(-cx, -cy) * Geom::Rotate (M_PI*dr/180) * Geom::Translate(cx, cy); + Geom::Affine drot_c = Geom::Translate(-cx, -cy) * Geom::Rotate(M_PI * dr / 180) * Geom::Translate(cx, cy); - Geom::Affine dscale_c = Geom::Translate(-cx, -cy) * Geom::Scale (scalex, scaley) * Geom::Translate(cx, cy); + Geom::Affine dscale_c = Geom::Translate(-cx, -cy) * Geom::Scale(scalex, scaley) * Geom::Translate(cx, cy); Geom::Affine d_s_r = dscale_c * drot_c; - Geom::Affine rotate_180_c = Geom::Translate(-cx, -cy) * Geom::Rotate (M_PI) * Geom::Translate(cx, cy); - - Geom::Affine rotate_90_c = Geom::Translate(-cx, -cy) * Geom::Rotate (-M_PI/2) * Geom::Translate(cx, cy); - Geom::Affine rotate_m90_c = Geom::Translate(-cx, -cy) * Geom::Rotate ( M_PI/2) * Geom::Translate(cx, cy); + Geom::Affine rotate_180_c = Geom::Translate(-cx, -cy) * Geom::Rotate(M_PI) * Geom::Translate(cx, cy); - Geom::Affine rotate_120_c = Geom::Translate(-cx, -cy) * Geom::Rotate (-2*M_PI/3) * Geom::Translate(cx, cy); - Geom::Affine rotate_m120_c = Geom::Translate(-cx, -cy) * Geom::Rotate ( 2*M_PI/3) * Geom::Translate(cx, cy); + Geom::Affine rotate_90_c = Geom::Translate(-cx, -cy) * Geom::Rotate(-M_PI / 2) * Geom::Translate(cx, cy); + Geom::Affine rotate_m90_c = Geom::Translate(-cx, -cy) * Geom::Rotate(M_PI / 2) * Geom::Translate(cx, cy); - Geom::Affine rotate_60_c = Geom::Translate(-cx, -cy) * Geom::Rotate (-M_PI/3) * Geom::Translate(cx, cy); - Geom::Affine rotate_m60_c = Geom::Translate(-cx, -cy) * Geom::Rotate ( M_PI/3) * Geom::Translate(cx, cy); + Geom::Affine rotate_120_c = Geom::Translate(-cx, -cy) * Geom::Rotate(-2 * M_PI / 3) * Geom::Translate(cx, cy); + Geom::Affine rotate_m120_c = Geom::Translate(-cx, -cy) * Geom::Rotate(2 * M_PI / 3) * Geom::Translate(cx, cy); - Geom::Affine flip_x = Geom::Translate(-cx, -cy) * Geom::Scale (-1, 1) * Geom::Translate(cx, cy); - Geom::Affine flip_y = Geom::Translate(-cx, -cy) * Geom::Scale (1, -1) * Geom::Translate(cx, cy); + Geom::Affine rotate_60_c = Geom::Translate(-cx, -cy) * Geom::Rotate(-M_PI / 3) * Geom::Translate(cx, cy); + Geom::Affine rotate_m60_c = Geom::Translate(-cx, -cy) * Geom::Rotate(M_PI / 3) * Geom::Translate(cx, cy); + Geom::Affine flip_x = Geom::Translate(-cx, -cy) * Geom::Scale(-1, 1) * Geom::Translate(cx, cy); + Geom::Affine flip_y = Geom::Translate(-cx, -cy) * Geom::Scale(1, -1) * Geom::Translate(cx, cy); // Create tile with required symmetry - const double cos60 = cos(M_PI/3); - const double sin60 = sin(M_PI/3); - const double cos30 = cos(M_PI/6); - const double sin30 = sin(M_PI/6); + const double cos60 = cos(M_PI / 3); + const double sin60 = sin(M_PI / 3); + const double cos30 = cos(M_PI / 6); + const double sin30 = sin(M_PI / 6); switch (type) { - - case TILE_P1: - return d_s_r * rect_translate; - break; - - case TILE_P2: - if (i % 2 == 0) { - return d_s_r * rect_translate; - } else { - return d_s_r * rotate_180_c * rect_translate; - } - break; - - case TILE_PM: - if (i % 2 == 0) { + case TILE_P1: return d_s_r * rect_translate; - } else { - return d_s_r * flip_x * rect_translate; - } - break; + break; - case TILE_PG: - if (j % 2 == 0) { - return d_s_r * rect_translate; - } else { - return d_s_r * flip_x * rect_translate; - } - break; - - case TILE_CM: - if ((i + j) % 2 == 0) { - return d_s_r * rect_translate; - } else { - return d_s_r * flip_x * rect_translate; - } - break; + case TILE_P2: + if (i % 2 == 0) { + return d_s_r * rect_translate; + } else { + return d_s_r * rotate_180_c * rect_translate; + } + break; - case TILE_PMM: - if (j % 2 == 0) { + case TILE_PM: if (i % 2 == 0) { return d_s_r * rect_translate; } else { return d_s_r * flip_x * rect_translate; } - } else { - if (i % 2 == 0) { - return d_s_r * flip_y * rect_translate; + break; + + case TILE_PG: + if (j % 2 == 0) { + return d_s_r * rect_translate; } else { - return d_s_r * flip_x * flip_y * rect_translate; + return d_s_r * flip_x * rect_translate; } - } - break; + break; - case TILE_PMG: - if (j % 2 == 0) { - if (i % 2 == 0) { + case TILE_CM: + if ((i + j) % 2 == 0) { return d_s_r * rect_translate; } else { - return d_s_r * rotate_180_c * rect_translate; + return d_s_r * flip_x * rect_translate; } - } else { - if (i % 2 == 0) { - return d_s_r * flip_y * rect_translate; + break; + + case TILE_PMM: + if (j % 2 == 0) { + if (i % 2 == 0) { + return d_s_r * rect_translate; + } else { + return d_s_r * flip_x * rect_translate; + } } else { - return d_s_r * rotate_180_c * flip_y * rect_translate; + if (i % 2 == 0) { + return d_s_r * flip_y * rect_translate; + } else { + return d_s_r * flip_x * flip_y * rect_translate; + } } - } - break; + break; - case TILE_PGG: - if (j % 2 == 0) { - if (i % 2 == 0) { - return d_s_r * rect_translate; + case TILE_PMG: + if (j % 2 == 0) { + if (i % 2 == 0) { + return d_s_r * rect_translate; + } else { + return d_s_r * rotate_180_c * rect_translate; + } } else { - return d_s_r * flip_y * rect_translate; + if (i % 2 == 0) { + return d_s_r * flip_y * rect_translate; + } else { + return d_s_r * rotate_180_c * flip_y * rect_translate; + } } - } else { - if (i % 2 == 0) { - return d_s_r * rotate_180_c * rect_translate; + break; + + case TILE_PGG: + if (j % 2 == 0) { + if (i % 2 == 0) { + return d_s_r * rect_translate; + } else { + return d_s_r * flip_y * rect_translate; + } } else { - return d_s_r * rotate_180_c * flip_y * rect_translate; + if (i % 2 == 0) { + return d_s_r * rotate_180_c * rect_translate; + } else { + return d_s_r * rotate_180_c * flip_y * rect_translate; + } } - } - break; + break; - case TILE_CMM: - if (j % 4 == 0) { - if (i % 2 == 0) { - return d_s_r * rect_translate; + case TILE_CMM: + if (j % 4 == 0) { + if (i % 2 == 0) { + return d_s_r * rect_translate; + } else { + return d_s_r * flip_x * rect_translate; + } + } else if (j % 4 == 1) { + if (i % 2 == 0) { + return d_s_r * flip_y * rect_translate; + } else { + return d_s_r * flip_x * flip_y * rect_translate; + } + } else if (j % 4 == 2) { + if (i % 2 == 1) { + return d_s_r * rect_translate; + } else { + return d_s_r * flip_x * rect_translate; + } } else { - return d_s_r * flip_x * rect_translate; + if (i % 2 == 1) { + return d_s_r * flip_y * rect_translate; + } else { + return d_s_r * flip_x * flip_y * rect_translate; + } } - } else if (j % 4 == 1) { - if (i % 2 == 0) { - return d_s_r * flip_y * rect_translate; + break; + + case TILE_P4: { + Geom::Affine ori( + Geom::Translate((w + h) * pow((i / 2), shiftx_exp) + dx, (h + w) * pow((j / 2), shifty_exp) + dy)); + Geom::Affine dia1(Geom::Translate(w / 2 + h / 2, -h / 2 + w / 2)); + Geom::Affine dia2(Geom::Translate(-w / 2 + h / 2, h / 2 + w / 2)); + if (j % 2 == 0) { + if (i % 2 == 0) { + return d_s_r * ori; + } else { + return d_s_r * rotate_m90_c * dia1 * ori; + } } else { - return d_s_r * flip_x * flip_y * rect_translate; + if (i % 2 == 0) { + return d_s_r * rotate_90_c * dia2 * ori; + } else { + return d_s_r * rotate_180_c * dia1 * dia2 * ori; + } } - } else if (j % 4 == 2) { - if (i % 2 == 1) { - return d_s_r * rect_translate; + } break; + + case TILE_P4M: { + double max = MAX(w, h); + Geom::Affine ori(Geom::Translate((max + max) * pow((i / 4), shiftx_exp) + dx, + (max + max) * pow((j / 2), shifty_exp) + dy)); + Geom::Affine dia1(Geom::Translate(w / 2 - h / 2, h / 2 - w / 2)); + Geom::Affine dia2(Geom::Translate(-h / 2 + w / 2, w / 2 - h / 2)); + if (j % 2 == 0) { + if (i % 4 == 0) { + return d_s_r * ori; + } else if (i % 4 == 1) { + return d_s_r * flip_y * rotate_m90_c * dia1 * ori; + } else if (i % 4 == 2) { + return d_s_r * rotate_m90_c * dia1 * Geom::Translate(h, 0) * ori; + } else if (i % 4 == 3) { + return d_s_r * flip_x * Geom::Translate(w, 0) * ori; + } } else { - return d_s_r * flip_x * rect_translate; + if (i % 4 == 0) { + return d_s_r * flip_y * Geom::Translate(0, h) * ori; + } else if (i % 4 == 1) { + return d_s_r * rotate_90_c * dia2 * Geom::Translate(0, h) * ori; + } else if (i % 4 == 2) { + return d_s_r * flip_y * rotate_90_c * dia2 * Geom::Translate(h, 0) * Geom::Translate(0, h) * ori; + } else if (i % 4 == 3) { + return d_s_r * flip_y * flip_x * Geom::Translate(w, 0) * Geom::Translate(0, h) * ori; + } } - } else { - if (i % 2 == 1) { - return d_s_r * flip_y * rect_translate; + } break; + + case TILE_P4G: { + double max = MAX(w, h); + Geom::Affine ori( + Geom::Translate((max + max) * pow((i / 4), shiftx_exp) + dx, (max + max) * pow(j, shifty_exp) + dy)); + Geom::Affine dia1(Geom::Translate(w / 2 + h / 2, h / 2 - w / 2)); + Geom::Affine dia2(Geom::Translate(-h / 2 + w / 2, w / 2 + h / 2)); + if (((i / 4) + j) % 2 == 0) { + if (i % 4 == 0) { + return d_s_r * ori; + } else if (i % 4 == 1) { + return d_s_r * rotate_m90_c * dia1 * ori; + } else if (i % 4 == 2) { + return d_s_r * rotate_90_c * dia2 * ori; + } else if (i % 4 == 3) { + return d_s_r * rotate_180_c * dia1 * dia2 * ori; + } } else { - return d_s_r * flip_x * flip_y * rect_translate; + if (i % 4 == 0) { + return d_s_r * flip_y * Geom::Translate(0, h) * ori; + } else if (i % 4 == 1) { + return d_s_r * flip_y * rotate_m90_c * dia1 * Geom::Translate(-h, 0) * ori; + } else if (i % 4 == 2) { + return d_s_r * flip_y * rotate_90_c * dia2 * Geom::Translate(h, 0) * ori; + } else if (i % 4 == 3) { + return d_s_r * flip_x * Geom::Translate(w, 0) * ori; + } } - } - break; - - case TILE_P4: - { - Geom::Affine ori (Geom::Translate ((w + h) * pow((i/2), shiftx_exp) + dx, (h + w) * pow((j/2), shifty_exp) + dy)); - Geom::Affine dia1 (Geom::Translate (w/2 + h/2, -h/2 + w/2)); - Geom::Affine dia2 (Geom::Translate (-w/2 + h/2, h/2 + w/2)); - if (j % 2 == 0) { - if (i % 2 == 0) { + } break; + + case TILE_P3: { + double width; + double height; + Geom::Affine dia1; + Geom::Affine dia2; + if (w > h) { + width = w + w * cos60; + height = 2 * w * sin60; + dia1 = Geom::Affine(Geom::Translate(w / 2 + w / 2 * cos60, -(w / 2 * sin60))); + dia2 = dia1 * Geom::Affine(Geom::Translate(0, 2 * (w / 2 * sin60))); + } else { + width = h * cos(M_PI / 6); + height = h; + dia1 = Geom::Affine(Geom::Translate(h / 2 * cos30, -(h / 2 * sin30))); + dia2 = dia1 * Geom::Affine(Geom::Translate(0, h / 2)); + } + Geom::Affine ori(Geom::Translate(width * pow((2 * (i / 3) + j % 2), shiftx_exp) + dx, + (height / 2) * pow(j, shifty_exp) + dy)); + if (i % 3 == 0) { return d_s_r * ori; + } else if (i % 3 == 1) { + return d_s_r * rotate_m120_c * dia1 * ori; + } else if (i % 3 == 2) { + return d_s_r * rotate_120_c * dia2 * ori; + } + } break; + + case TILE_P31M: { + Geom::Affine ori; + Geom::Affine dia1; + Geom::Affine dia2; + Geom::Affine dia3; + Geom::Affine dia4; + if (w > h) { + ori = Geom::Affine(Geom::Translate(w * pow((i / 6) + 0.5 * (j % 2), shiftx_exp) + dx, + (w * cos30) * pow(j, shifty_exp) + dy)); + dia1 = Geom::Affine(Geom::Translate(0, h / 2) * Geom::Translate(w / 2, 0) * + Geom::Translate(w / 2 * cos60, -w / 2 * sin60) * + Geom::Translate(-h / 2 * cos30, -h / 2 * sin30)); + dia2 = dia1 * Geom::Affine(Geom::Translate(h * cos30, h * sin30)); + dia3 = dia2 * Geom::Affine(Geom::Translate(0, 2 * (w / 2 * sin60 - h / 2 * sin30))); + dia4 = dia3 * Geom::Affine(Geom::Translate(-h * cos30, h * sin30)); } else { - return d_s_r * rotate_m90_c * dia1 * ori; + ori = Geom::Affine(Geom::Translate(2 * h * cos30 * pow((i / 6 + 0.5 * (j % 2)), shiftx_exp) + dx, + (2 * h - h * sin30) * pow(j, shifty_exp) + dy)); + dia1 = Geom::Affine(Geom::Translate(0, -h / 2) * Geom::Translate(h / 2 * cos30, h / 2 * sin30)); + dia2 = dia1 * Geom::Affine(Geom::Translate(h * cos30, h * sin30)); + dia3 = dia2 * Geom::Affine(Geom::Translate(0, h / 2)); + dia4 = dia3 * Geom::Affine(Geom::Translate(-h * cos30, h * sin30)); + } + if (i % 6 == 0) { + return d_s_r * ori; + } else if (i % 6 == 1) { + return d_s_r * flip_y * rotate_m120_c * dia1 * ori; + } else if (i % 6 == 2) { + return d_s_r * rotate_m120_c * dia2 * ori; + } else if (i % 6 == 3) { + return d_s_r * flip_y * rotate_120_c * dia3 * ori; + } else if (i % 6 == 4) { + return d_s_r * rotate_120_c * dia4 * ori; + } else if (i % 6 == 5) { + return d_s_r * flip_y * Geom::Translate(0, h) * ori; } - } else { - if (i % 2 == 0) { - return d_s_r * rotate_90_c * dia2 * ori; + } break; + + case TILE_P3M1: { + double width; + double height; + Geom::Affine dia1; + Geom::Affine dia2; + Geom::Affine dia3; + Geom::Affine dia4; + if (w > h) { + width = w + w * cos60; + height = 2 * w * sin60; + dia1 = Geom::Affine(Geom::Translate(0, h / 2) * Geom::Translate(w / 2, 0) * + Geom::Translate(w / 2 * cos60, -w / 2 * sin60) * + Geom::Translate(-h / 2 * cos30, -h / 2 * sin30)); + dia2 = dia1 * Geom::Affine(Geom::Translate(h * cos30, h * sin30)); + dia3 = dia2 * Geom::Affine(Geom::Translate(0, 2 * (w / 2 * sin60 - h / 2 * sin30))); + dia4 = dia3 * Geom::Affine(Geom::Translate(-h * cos30, h * sin30)); } else { - return d_s_r * rotate_180_c * dia1 * dia2 * ori; - } - } - } - break; - - case TILE_P4M: - { - double max = MAX(w, h); - Geom::Affine ori (Geom::Translate ((max + max) * pow((i/4), shiftx_exp) + dx, (max + max) * pow((j/2), shifty_exp) + dy)); - Geom::Affine dia1 (Geom::Translate ( w/2 - h/2, h/2 - w/2)); - Geom::Affine dia2 (Geom::Translate (-h/2 + w/2, w/2 - h/2)); - if (j % 2 == 0) { - if (i % 4 == 0) { + width = 2 * h * cos(M_PI / 6); + height = 2 * h; + dia1 = Geom::Affine(Geom::Translate(0, -h / 2) * Geom::Translate(h / 2 * cos30, h / 2 * sin30)); + dia2 = dia1 * Geom::Affine(Geom::Translate(h * cos30, h * sin30)); + dia3 = dia2 * Geom::Affine(Geom::Translate(0, h / 2)); + dia4 = dia3 * Geom::Affine(Geom::Translate(-h * cos30, h * sin30)); + } + Geom::Affine ori(Geom::Translate(width * pow((2 * (i / 6) + j % 2), shiftx_exp) + dx, + (height / 2) * pow(j, shifty_exp) + dy)); + if (i % 6 == 0) { return d_s_r * ori; - } else if (i % 4 == 1) { - return d_s_r * flip_y * rotate_m90_c * dia1 * ori; - } else if (i % 4 == 2) { - return d_s_r * rotate_m90_c * dia1 * Geom::Translate (h, 0) * ori; - } else if (i % 4 == 3) { - return d_s_r * flip_x * Geom::Translate (w, 0) * ori; - } - } else { - if (i % 4 == 0) { + } else if (i % 6 == 1) { + return d_s_r * flip_y * rotate_m120_c * dia1 * ori; + } else if (i % 6 == 2) { + return d_s_r * rotate_m120_c * dia2 * ori; + } else if (i % 6 == 3) { + return d_s_r * flip_y * rotate_120_c * dia3 * ori; + } else if (i % 6 == 4) { + return d_s_r * rotate_120_c * dia4 * ori; + } else if (i % 6 == 5) { return d_s_r * flip_y * Geom::Translate(0, h) * ori; - } else if (i % 4 == 1) { - return d_s_r * rotate_90_c * dia2 * Geom::Translate(0, h) * ori; - } else if (i % 4 == 2) { - return d_s_r * flip_y * rotate_90_c * dia2 * Geom::Translate(h, 0) * Geom::Translate(0, h) * ori; - } else if (i % 4 == 3) { - return d_s_r * flip_y * flip_x * Geom::Translate(w, 0) * Geom::Translate(0, h) * ori; } - } - } - break; - - case TILE_P4G: - { - double max = MAX(w, h); - Geom::Affine ori (Geom::Translate ((max + max) * pow((i/4), shiftx_exp) + dx, (max + max) * pow(j, shifty_exp) + dy)); - Geom::Affine dia1 (Geom::Translate ( w/2 + h/2, h/2 - w/2)); - Geom::Affine dia2 (Geom::Translate (-h/2 + w/2, w/2 + h/2)); - if (((i/4) + j) % 2 == 0) { - if (i % 4 == 0) { + } break; + + case TILE_P6: { + Geom::Affine ori; + Geom::Affine dia1; + Geom::Affine dia2; + Geom::Affine dia3; + Geom::Affine dia4; + Geom::Affine dia5; + if (w > h) { + ori = Geom::Affine(Geom::Translate(w * pow((2 * (i / 6) + (j % 2)), shiftx_exp) + dx, + (2 * w * sin60) * pow(j, shifty_exp) + dy)); + dia1 = Geom::Affine(Geom::Translate(w / 2 * cos60, -w / 2 * sin60)); + dia2 = dia1 * Geom::Affine(Geom::Translate(w / 2, 0)); + dia3 = dia2 * Geom::Affine(Geom::Translate(w / 2 * cos60, w / 2 * sin60)); + dia4 = dia3 * Geom::Affine(Geom::Translate(-w / 2 * cos60, w / 2 * sin60)); + dia5 = dia4 * Geom::Affine(Geom::Translate(-w / 2, 0)); + } else { + ori = Geom::Affine(Geom::Translate(2 * h * cos30 * pow((i / 6 + 0.5 * (j % 2)), shiftx_exp) + dx, + (h + h * sin30) * pow(j, shifty_exp) + dy)); + dia1 = Geom::Affine(Geom::Translate(-w / 2, -h / 2) * Geom::Translate(h / 2 * cos30, -h / 2 * sin30) * + Geom::Translate(w / 2 * cos60, w / 2 * sin60)); + dia2 = dia1 * Geom::Affine(Geom::Translate(-w / 2 * cos60, -w / 2 * sin60) * + Geom::Translate(h / 2 * cos30, -h / 2 * sin30) * + Geom::Translate(h / 2 * cos30, h / 2 * sin30) * + Geom::Translate(-w / 2 * cos60, w / 2 * sin60)); + dia3 = + dia2 * Geom::Affine(Geom::Translate(w / 2 * cos60, -w / 2 * sin60) * + Geom::Translate(h / 2 * cos30, h / 2 * sin30) * Geom::Translate(-w / 2, h / 2)); + dia4 = dia3 * dia1.inverse(); + dia5 = dia3 * dia2.inverse(); + } + if (i % 6 == 0) { return d_s_r * ori; - } else if (i % 4 == 1) { - return d_s_r * rotate_m90_c * dia1 * ori; - } else if (i % 4 == 2) { - return d_s_r * rotate_90_c * dia2 * ori; - } else if (i % 4 == 3) { - return d_s_r * rotate_180_c * dia1 * dia2 * ori; - } - } else { - if (i % 4 == 0) { - return d_s_r * flip_y * Geom::Translate (0, h) * ori; - } else if (i % 4 == 1) { - return d_s_r * flip_y * rotate_m90_c * dia1 * Geom::Translate (-h, 0) * ori; - } else if (i % 4 == 2) { - return d_s_r * flip_y * rotate_90_c * dia2 * Geom::Translate (h, 0) * ori; - } else if (i % 4 == 3) { - return d_s_r * flip_x * Geom::Translate (w, 0) * ori; + } else if (i % 6 == 1) { + return d_s_r * rotate_m60_c * dia1 * ori; + } else if (i % 6 == 2) { + return d_s_r * rotate_m120_c * dia2 * ori; + } else if (i % 6 == 3) { + return d_s_r * rotate_180_c * dia3 * ori; + } else if (i % 6 == 4) { + return d_s_r * rotate_120_c * dia4 * ori; + } else if (i % 6 == 5) { + return d_s_r * rotate_60_c * dia5 * ori; + } + } break; + + case TILE_P6M: { + Geom::Affine ori; + Geom::Affine dia1, dia2, dia3, dia4, dia5, dia6, dia7, dia8, dia9, dia10; + if (w > h) { + ori = Geom::Affine(Geom::Translate(w * pow((2 * (i / 12) + (j % 2)), shiftx_exp) + dx, + (2 * w * sin60) * pow(j, shifty_exp) + dy)); + dia1 = Geom::Affine(Geom::Translate(w / 2, h / 2) * Geom::Translate(-w / 2 * cos60, -w / 2 * sin60) * + Geom::Translate(-h / 2 * cos30, h / 2 * sin30)); + dia2 = dia1 * Geom::Affine(Geom::Translate(h * cos30, -h * sin30)); + dia3 = + dia2 * Geom::Affine(Geom::Translate(-h / 2 * cos30, h / 2 * sin30) * Geom::Translate(w * cos60, 0) * + Geom::Translate(-h / 2 * cos30, -h / 2 * sin30)); + dia4 = dia3 * Geom::Affine(Geom::Translate(h * cos30, h * sin30)); + dia5 = dia4 * + Geom::Affine(Geom::Translate(-h / 2 * cos30, -h / 2 * sin30) * + Geom::Translate(-w / 2 * cos60, w / 2 * sin60) * Geom::Translate(w / 2, -h / 2)); + dia6 = dia5 * Geom::Affine(Geom::Translate(0, h)); + dia7 = dia6 * dia1.inverse(); + dia8 = dia6 * dia2.inverse(); + dia9 = dia6 * dia3.inverse(); + dia10 = dia6 * dia4.inverse(); + } else { + ori = Geom::Affine(Geom::Translate(4 * h * cos30 * pow((i / 12 + 0.5 * (j % 2)), shiftx_exp) + dx, + (2 * h + 2 * h * sin30) * pow(j, shifty_exp) + dy)); + dia1 = Geom::Affine(Geom::Translate(-w / 2, -h / 2) * Geom::Translate(h / 2 * cos30, -h / 2 * sin30) * + Geom::Translate(w / 2 * cos60, w / 2 * sin60)); + dia2 = dia1 * Geom::Affine(Geom::Translate(h * cos30, -h * sin30)); + dia3 = + dia2 * Geom::Affine(Geom::Translate(-w / 2 * cos60, -w / 2 * sin60) * + Geom::Translate(h * cos30, 0) * Geom::Translate(-w / 2 * cos60, w / 2 * sin60)); + dia4 = dia3 * Geom::Affine(Geom::Translate(h * cos30, h * sin30)); + dia5 = + dia4 * Geom::Affine(Geom::Translate(w / 2 * cos60, -w / 2 * sin60) * + Geom::Translate(h / 2 * cos30, h / 2 * sin30) * Geom::Translate(-w / 2, h / 2)); + dia6 = dia5 * Geom::Affine(Geom::Translate(0, h)); + dia7 = dia6 * dia1.inverse(); + dia8 = dia6 * dia2.inverse(); + dia9 = dia6 * dia3.inverse(); + dia10 = dia6 * dia4.inverse(); + } + if (i % 12 == 0) { + return d_s_r * ori; + } else if (i % 12 == 1) { + return d_s_r * flip_y * rotate_m60_c * dia1 * ori; + } else if (i % 12 == 2) { + return d_s_r * rotate_m60_c * dia2 * ori; + } else if (i % 12 == 3) { + return d_s_r * flip_y * rotate_m120_c * dia3 * ori; + } else if (i % 12 == 4) { + return d_s_r * rotate_m120_c * dia4 * ori; + } else if (i % 12 == 5) { + return d_s_r * flip_x * dia5 * ori; + } else if (i % 12 == 6) { + return d_s_r * flip_x * flip_y * dia6 * ori; + } else if (i % 12 == 7) { + return d_s_r * flip_y * rotate_120_c * dia7 * ori; + } else if (i % 12 == 8) { + return d_s_r * rotate_120_c * dia8 * ori; + } else if (i % 12 == 9) { + return d_s_r * flip_y * rotate_60_c * dia9 * ori; + } else if (i % 12 == 10) { + return d_s_r * rotate_60_c * dia10 * ori; + } else if (i % 12 == 11) { + return d_s_r * flip_y * Geom::Translate(0, h) * ori; } - } - } - break; - - case TILE_P3: - { - double width; - double height; - Geom::Affine dia1; - Geom::Affine dia2; - if (w > h) { - width = w + w * cos60; - height = 2 * w * sin60; - dia1 = Geom::Affine (Geom::Translate (w/2 + w/2 * cos60, -(w/2 * sin60))); - dia2 = dia1 * Geom::Affine (Geom::Translate (0, 2 * (w/2 * sin60))); - } else { - width = h * cos (M_PI/6); - height = h; - dia1 = Geom::Affine (Geom::Translate (h/2 * cos30, -(h/2 * sin30))); - dia2 = dia1 * Geom::Affine (Geom::Translate (0, h/2)); - } - Geom::Affine ori (Geom::Translate (width * pow((2*(i/3) + j%2), shiftx_exp) + dx, (height/2) * pow(j, shifty_exp) + dy)); - if (i % 3 == 0) { - return d_s_r * ori; - } else if (i % 3 == 1) { - return d_s_r * rotate_m120_c * dia1 * ori; - } else if (i % 3 == 2) { - return d_s_r * rotate_120_c * dia2 * ori; - } - } - break; + } break; - case TILE_P31M: - { - Geom::Affine ori; - Geom::Affine dia1; - Geom::Affine dia2; - Geom::Affine dia3; - Geom::Affine dia4; - if (w > h) { - ori = Geom::Affine(Geom::Translate (w * pow((i/6) + 0.5*(j%2), shiftx_exp) + dx, (w * cos30) * pow(j, shifty_exp) + dy)); - dia1 = Geom::Affine (Geom::Translate (0, h/2) * Geom::Translate (w/2, 0) * Geom::Translate (w/2 * cos60, -w/2 * sin60) * Geom::Translate (-h/2 * cos30, -h/2 * sin30) ); - dia2 = dia1 * Geom::Affine (Geom::Translate (h * cos30, h * sin30)); - dia3 = dia2 * Geom::Affine (Geom::Translate (0, 2 * (w/2 * sin60 - h/2 * sin30))); - dia4 = dia3 * Geom::Affine (Geom::Translate (-h * cos30, h * sin30)); - } else { - ori = Geom::Affine (Geom::Translate (2*h * cos30 * pow((i/6 + 0.5*(j%2)), shiftx_exp) + dx, (2*h - h * sin30) * pow(j, shifty_exp) + dy)); - dia1 = Geom::Affine (Geom::Translate (0, -h/2) * Geom::Translate (h/2 * cos30, h/2 * sin30)); - dia2 = dia1 * Geom::Affine (Geom::Translate (h * cos30, h * sin30)); - dia3 = dia2 * Geom::Affine (Geom::Translate (0, h/2)); - dia4 = dia3 * Geom::Affine (Geom::Translate (-h * cos30, h * sin30)); - } - if (i % 6 == 0) { - return d_s_r * ori; - } else if (i % 6 == 1) { - return d_s_r * flip_y * rotate_m120_c * dia1 * ori; - } else if (i % 6 == 2) { - return d_s_r * rotate_m120_c * dia2 * ori; - } else if (i % 6 == 3) { - return d_s_r * flip_y * rotate_120_c * dia3 * ori; - } else if (i % 6 == 4) { - return d_s_r * rotate_120_c * dia4 * ori; - } else if (i % 6 == 5) { - return d_s_r * flip_y * Geom::Translate(0, h) * ori; - } - } - break; - - case TILE_P3M1: - { - double width; - double height; - Geom::Affine dia1; - Geom::Affine dia2; - Geom::Affine dia3; - Geom::Affine dia4; - if (w > h) { - width = w + w * cos60; - height = 2 * w * sin60; - dia1 = Geom::Affine (Geom::Translate (0, h/2) * Geom::Translate (w/2, 0) * Geom::Translate (w/2 * cos60, -w/2 * sin60) * Geom::Translate (-h/2 * cos30, -h/2 * sin30) ); - dia2 = dia1 * Geom::Affine (Geom::Translate (h * cos30, h * sin30)); - dia3 = dia2 * Geom::Affine (Geom::Translate (0, 2 * (w/2 * sin60 - h/2 * sin30))); - dia4 = dia3 * Geom::Affine (Geom::Translate (-h * cos30, h * sin30)); - } else { - width = 2 * h * cos (M_PI/6); - height = 2 * h; - dia1 = Geom::Affine (Geom::Translate (0, -h/2) * Geom::Translate (h/2 * cos30, h/2 * sin30)); - dia2 = dia1 * Geom::Affine (Geom::Translate (h * cos30, h * sin30)); - dia3 = dia2 * Geom::Affine (Geom::Translate (0, h/2)); - dia4 = dia3 * Geom::Affine (Geom::Translate (-h * cos30, h * sin30)); - } - Geom::Affine ori (Geom::Translate (width * pow((2*(i/6) + j%2), shiftx_exp) + dx, (height/2) * pow(j, shifty_exp) + dy)); - if (i % 6 == 0) { - return d_s_r * ori; - } else if (i % 6 == 1) { - return d_s_r * flip_y * rotate_m120_c * dia1 * ori; - } else if (i % 6 == 2) { - return d_s_r * rotate_m120_c * dia2 * ori; - } else if (i % 6 == 3) { - return d_s_r * flip_y * rotate_120_c * dia3 * ori; - } else if (i % 6 == 4) { - return d_s_r * rotate_120_c * dia4 * ori; - } else if (i % 6 == 5) { - return d_s_r * flip_y * Geom::Translate(0, h) * ori; - } - } - break; - - case TILE_P6: - { - Geom::Affine ori; - Geom::Affine dia1; - Geom::Affine dia2; - Geom::Affine dia3; - Geom::Affine dia4; - Geom::Affine dia5; - if (w > h) { - ori = Geom::Affine(Geom::Translate (w * pow((2*(i/6) + (j%2)), shiftx_exp) + dx, (2*w * sin60) * pow(j, shifty_exp) + dy)); - dia1 = Geom::Affine (Geom::Translate (w/2 * cos60, -w/2 * sin60)); - dia2 = dia1 * Geom::Affine (Geom::Translate (w/2, 0)); - dia3 = dia2 * Geom::Affine (Geom::Translate (w/2 * cos60, w/2 * sin60)); - dia4 = dia3 * Geom::Affine (Geom::Translate (-w/2 * cos60, w/2 * sin60)); - dia5 = dia4 * Geom::Affine (Geom::Translate (-w/2, 0)); - } else { - ori = Geom::Affine(Geom::Translate (2*h * cos30 * pow((i/6 + 0.5*(j%2)), shiftx_exp) + dx, (h + h * sin30) * pow(j, shifty_exp) + dy)); - dia1 = Geom::Affine (Geom::Translate (-w/2, -h/2) * Geom::Translate (h/2 * cos30, -h/2 * sin30) * Geom::Translate (w/2 * cos60, w/2 * sin60)); - dia2 = dia1 * Geom::Affine (Geom::Translate (-w/2 * cos60, -w/2 * sin60) * Geom::Translate (h/2 * cos30, -h/2 * sin30) * Geom::Translate (h/2 * cos30, h/2 * sin30) * Geom::Translate (-w/2 * cos60, w/2 * sin60)); - dia3 = dia2 * Geom::Affine (Geom::Translate (w/2 * cos60, -w/2 * sin60) * Geom::Translate (h/2 * cos30, h/2 * sin30) * Geom::Translate (-w/2, h/2)); - dia4 = dia3 * dia1.inverse(); - dia5 = dia3 * dia2.inverse(); - } - if (i % 6 == 0) { - return d_s_r * ori; - } else if (i % 6 == 1) { - return d_s_r * rotate_m60_c * dia1 * ori; - } else if (i % 6 == 2) { - return d_s_r * rotate_m120_c * dia2 * ori; - } else if (i % 6 == 3) { - return d_s_r * rotate_180_c * dia3 * ori; - } else if (i % 6 == 4) { - return d_s_r * rotate_120_c * dia4 * ori; - } else if (i % 6 == 5) { - return d_s_r * rotate_60_c * dia5 * ori; - } - } - break; - - case TILE_P6M: - { - - Geom::Affine ori; - Geom::Affine dia1, dia2, dia3, dia4, dia5, dia6, dia7, dia8, dia9, dia10; - if (w > h) { - ori = Geom::Affine(Geom::Translate (w * pow((2*(i/12) + (j%2)), shiftx_exp) + dx, (2*w * sin60) * pow(j, shifty_exp) + dy)); - dia1 = Geom::Affine (Geom::Translate (w/2, h/2) * Geom::Translate (-w/2 * cos60, -w/2 * sin60) * Geom::Translate (-h/2 * cos30, h/2 * sin30)); - dia2 = dia1 * Geom::Affine (Geom::Translate (h * cos30, -h * sin30)); - dia3 = dia2 * Geom::Affine (Geom::Translate (-h/2 * cos30, h/2 * sin30) * Geom::Translate (w * cos60, 0) * Geom::Translate (-h/2 * cos30, -h/2 * sin30)); - dia4 = dia3 * Geom::Affine (Geom::Translate (h * cos30, h * sin30)); - dia5 = dia4 * Geom::Affine (Geom::Translate (-h/2 * cos30, -h/2 * sin30) * Geom::Translate (-w/2 * cos60, w/2 * sin60) * Geom::Translate (w/2, -h/2)); - dia6 = dia5 * Geom::Affine (Geom::Translate (0, h)); - dia7 = dia6 * dia1.inverse(); - dia8 = dia6 * dia2.inverse(); - dia9 = dia6 * dia3.inverse(); - dia10 = dia6 * dia4.inverse(); - } else { - ori = Geom::Affine(Geom::Translate (4*h * cos30 * pow((i/12 + 0.5*(j%2)), shiftx_exp) + dx, (2*h + 2*h * sin30) * pow(j, shifty_exp) + dy)); - dia1 = Geom::Affine (Geom::Translate (-w/2, -h/2) * Geom::Translate (h/2 * cos30, -h/2 * sin30) * Geom::Translate (w/2 * cos60, w/2 * sin60)); - dia2 = dia1 * Geom::Affine (Geom::Translate (h * cos30, -h * sin30)); - dia3 = dia2 * Geom::Affine (Geom::Translate (-w/2 * cos60, -w/2 * sin60) * Geom::Translate (h * cos30, 0) * Geom::Translate (-w/2 * cos60, w/2 * sin60)); - dia4 = dia3 * Geom::Affine (Geom::Translate (h * cos30, h * sin30)); - dia5 = dia4 * Geom::Affine (Geom::Translate (w/2 * cos60, -w/2 * sin60) * Geom::Translate (h/2 * cos30, h/2 * sin30) * Geom::Translate (-w/2, h/2)); - dia6 = dia5 * Geom::Affine (Geom::Translate (0, h)); - dia7 = dia6 * dia1.inverse(); - dia8 = dia6 * dia2.inverse(); - dia9 = dia6 * dia3.inverse(); - dia10 = dia6 * dia4.inverse(); - } - if (i % 12 == 0) { - return d_s_r * ori; - } else if (i % 12 == 1) { - return d_s_r * flip_y * rotate_m60_c * dia1 * ori; - } else if (i % 12 == 2) { - return d_s_r * rotate_m60_c * dia2 * ori; - } else if (i % 12 == 3) { - return d_s_r * flip_y * rotate_m120_c * dia3 * ori; - } else if (i % 12 == 4) { - return d_s_r * rotate_m120_c * dia4 * ori; - } else if (i % 12 == 5) { - return d_s_r * flip_x * dia5 * ori; - } else if (i % 12 == 6) { - return d_s_r * flip_x * flip_y * dia6 * ori; - } else if (i % 12 == 7) { - return d_s_r * flip_y * rotate_120_c * dia7 * ori; - } else if (i % 12 == 8) { - return d_s_r * rotate_120_c * dia8 * ori; - } else if (i % 12 == 9) { - return d_s_r * flip_y * rotate_60_c * dia9 * ori; - } else if (i % 12 == 10) { - return d_s_r * rotate_60_c * dia10 * ori; - } else if (i % 12 == 11) { - return d_s_r * flip_y * Geom::Translate (0, h) * ori; - } - } - break; - - default: - break; + default: + break; } return Geom::identity(); @@ -1878,12 +1870,10 @@ bool CloneTiler::is_a_clone_of(SPObject *tile, SPObject *obj) id_href = g_strdup_printf("#%s", obj_repr->attribute("id")); } - if (dynamic_cast<SPUse *>(tile) && - tile->getRepr()->attribute("xlink:href") && + if (dynamic_cast<SPUse *>(tile) && tile->getRepr()->attribute("xlink:href") && (!id_href || !strcmp(id_href, tile->getRepr()->attribute("xlink:href"))) && tile->getRepr()->attribute("inkscape:tiled-clone-of") && - (!id_href || !strcmp(id_href, tile->getRepr()->attribute("inkscape:tiled-clone-of")))) - { + (!id_href || !strcmp(id_href, tile->getRepr()->attribute("inkscape:tiled-clone-of")))) { result = true; } else { result = false; @@ -1900,12 +1890,12 @@ void CloneTiler::trace_hide_tiled_clones_recursively(SPObject *from) if (!trace_drawing) return; - for (auto& o: from->children) { + for (auto &o : from->children) { SPItem *item = dynamic_cast<SPItem *>(&o); if (item && is_a_clone_of(&o, nullptr)) { item->invoke_hide(trace_visionkey); // FIXME: hide each tiled clone's original too! } - trace_hide_tiled_clones_recursively (&o); + trace_hide_tiled_clones_recursively(&o); } } @@ -1948,7 +1938,7 @@ guint32 CloneTiler::trace_pick(Geom::Rect box) ink_cairo_surface_average_color(s, R, G, B, A); cairo_surface_destroy(s); - return SP_RGBA32_F_COMPOSE (R, G, B, A); + return SP_RGBA32_F_COMPOSE(R, G, B, A); } void CloneTiler::trace_finish() @@ -1972,27 +1962,27 @@ void CloneTiler::unclump() // check if something is selected if (selection->isEmpty() || boost::distance(selection->items()) > 1) { - desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>one object</b> whose tiled clones to unclump.")); + desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>one object</b> whose tiled clones to unclump.")); return; } auto obj = selection->singleItem(); auto parent = obj->parent; - std::vector<SPItem*> to_unclump; // not including the original + std::vector<SPItem *> to_unclump; // not including the original - for (auto& child: parent->children) { - if (is_a_clone_of (&child, obj)) { - to_unclump.push_back((SPItem*)&child); + for (auto &child : parent->children) { + if (is_a_clone_of(&child, obj)) { + to_unclump.push_back((SPItem *)&child); } } desktop->getDocument()->ensureUpToDate(); - reverse(to_unclump.begin(),to_unclump.end()); - ::unclump (to_unclump); + reverse(to_unclump.begin(), to_unclump.end()); + ::unclump(to_unclump); - DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_CLONETILER, - _("Unclump tiled clones")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_CLONETILER, _("Unclump tiled clones")); } guint CloneTiler::number_of_clones(SPObject *obj) @@ -2001,16 +1991,16 @@ guint CloneTiler::number_of_clones(SPObject *obj) guint n = 0; - for (auto& child: parent->children) { - if (is_a_clone_of (&child, obj)) { - n ++; + for (auto &child : parent->children) { + if (is_a_clone_of(&child, obj)) { + n++; } } return n; } -void CloneTiler::remove(bool do_undo/* = true*/) +void CloneTiler::remove(bool do_undo /* = true*/) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; if (desktop == nullptr) { @@ -2021,30 +2011,30 @@ void CloneTiler::remove(bool do_undo/* = true*/) // check if something is selected if (selection->isEmpty() || boost::distance(selection->items()) > 1) { - desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>one object</b> whose tiled clones to remove.")); + desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>one object</b> whose tiled clones to remove.")); return; } SPObject *obj = selection->singleItem(); SPObject *parent = obj->parent; -// remove old tiling + // remove old tiling std::vector<SPObject *> to_delete; - for (auto& child: parent->children) { - if (is_a_clone_of (&child, obj)) { + for (auto &child : parent->children) { + if (is_a_clone_of(&child, obj)) { to_delete.push_back(&child); } } - for (auto obj:to_delete) { + for (auto obj : to_delete) { g_assert(obj != nullptr); obj->deleteObject(); } - change_selection (selection); + change_selection(selection); if (do_undo) { - DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_CLONETILER, - _("Delete tiled clones")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_CLONETILER, _("Delete tiled clones")); } } @@ -2056,13 +2046,10 @@ Geom::Rect CloneTiler::transform_rect(Geom::Rect const &r, Geom::Affine const &m Geom::Point const p2 = r.corner(2) * m; Geom::Point const p3 = r.corner(3) * m; Geom::Point const p4 = r.corner(4) * m; - return Geom::Rect( - Geom::Point( - std::min(std::min(p1[X], p2[X]), std::min(p3[X], p4[X])), - std::min(std::min(p1[Y], p2[Y]), std::min(p3[Y], p4[Y]))), - Geom::Point( - std::max(std::max(p1[X], p2[X]), std::max(p3[X], p4[X])), - std::max(std::max(p1[Y], p2[Y]), std::max(p3[Y], p4[Y])))); + return Geom::Rect(Geom::Point(std::min(std::min(p1[X], p2[X]), std::min(p3[X], p4[X])), + std::min(std::min(p1[Y], p2[Y]), std::min(p3[Y], p4[Y]))), + Geom::Point(std::max(std::max(p1[X], p2[X]), std::max(p3[X], p4[X])), + std::max(std::max(p1[Y], p2[Y]), std::max(p3[Y], p4[Y])))); } /** @@ -2071,15 +2058,14 @@ probability of being displaced. */ double CloneTiler::randomize01(double val, double rand) { - double base = MIN (val - rand, 1 - 2*rand); + double base = MIN(val - rand, 1 - 2 * rand); if (base < 0) { base = 0; } - val = base + g_random_double_range (0, MIN (2 * rand, 1 - base)); + val = base + g_random_double_range(0, MIN(2 * rand, 1 - base)); return CLAMP(val, 0, 1); // this should be unnecessary with the above provisions, but just in case... } - void CloneTiler::apply() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; @@ -2097,7 +2083,9 @@ void CloneTiler::apply() // Check if more than one object is selected. if (boost::distance(selection->items()) > 1) { - desktop->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, _("If you want to clone several objects, <b>group</b> them and <b>clone the group</b>.")); + desktop->getMessageStack()->flash( + Inkscape::ERROR_MESSAGE, + _("If you want to clone several objects, <b>group</b> them and <b>clone the group</b>.")); return; } @@ -2127,82 +2115,82 @@ void CloneTiler::apply() double shifty_per_i = 0.01 * prefs->getDoubleLimited(prefs_path + "shifty_per_i", 0, -10000, 10000); double shiftx_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "shiftx_per_j", 0, -10000, 10000); double shifty_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "shifty_per_j", 0, -10000, 10000); - double shiftx_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "shiftx_rand", 0, 0, 1000); - double shifty_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "shifty_rand", 0, 0, 1000); - double shiftx_exp = prefs->getDoubleLimited(prefs_path + "shiftx_exp", 1, 0, 10); - double shifty_exp = prefs->getDoubleLimited(prefs_path + "shifty_exp", 1, 0, 10); - bool shiftx_alternate = prefs->getBool(prefs_path + "shiftx_alternate"); - bool shifty_alternate = prefs->getBool(prefs_path + "shifty_alternate"); - bool shiftx_cumulate = prefs->getBool(prefs_path + "shiftx_cumulate"); - bool shifty_cumulate = prefs->getBool(prefs_path + "shifty_cumulate"); - bool shiftx_excludew = prefs->getBool(prefs_path + "shiftx_excludew"); - bool shifty_excludeh = prefs->getBool(prefs_path + "shifty_excludeh"); + double shiftx_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "shiftx_rand", 0, 0, 1000); + double shifty_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "shifty_rand", 0, 0, 1000); + double shiftx_exp = prefs->getDoubleLimited(prefs_path + "shiftx_exp", 1, 0, 10); + double shifty_exp = prefs->getDoubleLimited(prefs_path + "shifty_exp", 1, 0, 10); + bool shiftx_alternate = prefs->getBool(prefs_path + "shiftx_alternate"); + bool shifty_alternate = prefs->getBool(prefs_path + "shifty_alternate"); + bool shiftx_cumulate = prefs->getBool(prefs_path + "shiftx_cumulate"); + bool shifty_cumulate = prefs->getBool(prefs_path + "shifty_cumulate"); + bool shiftx_excludew = prefs->getBool(prefs_path + "shiftx_excludew"); + bool shifty_excludeh = prefs->getBool(prefs_path + "shifty_excludeh"); double scalex_per_i = 0.01 * prefs->getDoubleLimited(prefs_path + "scalex_per_i", 0, -100, 1000); double scaley_per_i = 0.01 * prefs->getDoubleLimited(prefs_path + "scaley_per_i", 0, -100, 1000); double scalex_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "scalex_per_j", 0, -100, 1000); double scaley_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "scaley_per_j", 0, -100, 1000); - double scalex_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "scalex_rand", 0, 0, 1000); - double scaley_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "scaley_rand", 0, 0, 1000); - double scalex_exp = prefs->getDoubleLimited(prefs_path + "scalex_exp", 1, 0, 10); - double scaley_exp = prefs->getDoubleLimited(prefs_path + "scaley_exp", 1, 0, 10); - double scalex_log = prefs->getDoubleLimited(prefs_path + "scalex_log", 0, 0, 10); - double scaley_log = prefs->getDoubleLimited(prefs_path + "scaley_log", 0, 0, 10); - bool scalex_alternate = prefs->getBool(prefs_path + "scalex_alternate"); - bool scaley_alternate = prefs->getBool(prefs_path + "scaley_alternate"); - bool scalex_cumulate = prefs->getBool(prefs_path + "scalex_cumulate"); - bool scaley_cumulate = prefs->getBool(prefs_path + "scaley_cumulate"); - - double rotate_per_i = prefs->getDoubleLimited(prefs_path + "rotate_per_i", 0, -180, 180); - double rotate_per_j = prefs->getDoubleLimited(prefs_path + "rotate_per_j", 0, -180, 180); - double rotate_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "rotate_rand", 0, 0, 100); - bool rotate_alternatei = prefs->getBool(prefs_path + "rotate_alternatei"); - bool rotate_alternatej = prefs->getBool(prefs_path + "rotate_alternatej"); - bool rotate_cumulatei = prefs->getBool(prefs_path + "rotate_cumulatei"); - bool rotate_cumulatej = prefs->getBool(prefs_path + "rotate_cumulatej"); - - double blur_per_i = 0.01 * prefs->getDoubleLimited(prefs_path + "blur_per_i", 0, 0, 100); - double blur_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "blur_per_j", 0, 0, 100); - bool blur_alternatei = prefs->getBool(prefs_path + "blur_alternatei"); - bool blur_alternatej = prefs->getBool(prefs_path + "blur_alternatej"); - double blur_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "blur_rand", 0, 0, 100); + double scalex_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "scalex_rand", 0, 0, 1000); + double scaley_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "scaley_rand", 0, 0, 1000); + double scalex_exp = prefs->getDoubleLimited(prefs_path + "scalex_exp", 1, 0, 10); + double scaley_exp = prefs->getDoubleLimited(prefs_path + "scaley_exp", 1, 0, 10); + double scalex_log = prefs->getDoubleLimited(prefs_path + "scalex_log", 0, 0, 10); + double scaley_log = prefs->getDoubleLimited(prefs_path + "scaley_log", 0, 0, 10); + bool scalex_alternate = prefs->getBool(prefs_path + "scalex_alternate"); + bool scaley_alternate = prefs->getBool(prefs_path + "scaley_alternate"); + bool scalex_cumulate = prefs->getBool(prefs_path + "scalex_cumulate"); + bool scaley_cumulate = prefs->getBool(prefs_path + "scaley_cumulate"); + + double rotate_per_i = prefs->getDoubleLimited(prefs_path + "rotate_per_i", 0, -180, 180); + double rotate_per_j = prefs->getDoubleLimited(prefs_path + "rotate_per_j", 0, -180, 180); + double rotate_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "rotate_rand", 0, 0, 100); + bool rotate_alternatei = prefs->getBool(prefs_path + "rotate_alternatei"); + bool rotate_alternatej = prefs->getBool(prefs_path + "rotate_alternatej"); + bool rotate_cumulatei = prefs->getBool(prefs_path + "rotate_cumulatei"); + bool rotate_cumulatej = prefs->getBool(prefs_path + "rotate_cumulatej"); + + double blur_per_i = 0.01 * prefs->getDoubleLimited(prefs_path + "blur_per_i", 0, 0, 100); + double blur_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "blur_per_j", 0, 0, 100); + bool blur_alternatei = prefs->getBool(prefs_path + "blur_alternatei"); + bool blur_alternatej = prefs->getBool(prefs_path + "blur_alternatej"); + double blur_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "blur_rand", 0, 0, 100); double opacity_per_i = 0.01 * prefs->getDoubleLimited(prefs_path + "opacity_per_i", 0, 0, 100); double opacity_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "opacity_per_j", 0, 0, 100); - bool opacity_alternatei = prefs->getBool(prefs_path + "opacity_alternatei"); - bool opacity_alternatej = prefs->getBool(prefs_path + "opacity_alternatej"); - double opacity_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "opacity_rand", 0, 0, 100); - - Glib::ustring initial_color = prefs->getString(prefs_path + "initial_color"); - double hue_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "hue_per_j", 0, -100, 100); - double hue_per_i = 0.01 * prefs->getDoubleLimited(prefs_path + "hue_per_i", 0, -100, 100); - double hue_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "hue_rand", 0, 0, 100); + bool opacity_alternatei = prefs->getBool(prefs_path + "opacity_alternatei"); + bool opacity_alternatej = prefs->getBool(prefs_path + "opacity_alternatej"); + double opacity_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "opacity_rand", 0, 0, 100); + + Glib::ustring initial_color = prefs->getString(prefs_path + "initial_color"); + double hue_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "hue_per_j", 0, -100, 100); + double hue_per_i = 0.01 * prefs->getDoubleLimited(prefs_path + "hue_per_i", 0, -100, 100); + double hue_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "hue_rand", 0, 0, 100); double saturation_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "saturation_per_j", 0, -100, 100); double saturation_per_i = 0.01 * prefs->getDoubleLimited(prefs_path + "saturation_per_i", 0, -100, 100); - double saturation_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "saturation_rand", 0, 0, 100); - double lightness_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "lightness_per_j", 0, -100, 100); - double lightness_per_i = 0.01 * prefs->getDoubleLimited(prefs_path + "lightness_per_i", 0, -100, 100); - double lightness_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "lightness_rand", 0, 0, 100); - bool color_alternatej = prefs->getBool(prefs_path + "color_alternatej"); - bool color_alternatei = prefs->getBool(prefs_path + "color_alternatei"); - - int type = prefs->getInt(prefs_path + "symmetrygroup", 0); - bool keepbbox = prefs->getBool(prefs_path + "keepbbox", true); - int imax = prefs->getInt(prefs_path + "imax", 2); - int jmax = prefs->getInt(prefs_path + "jmax", 2); - - bool fillrect = prefs->getBool(prefs_path + "fillrect"); - double fillwidth = scale_units*prefs->getDoubleLimited(prefs_path + "fillwidth", 50, 0, 1e6); - double fillheight = scale_units*prefs->getDoubleLimited(prefs_path + "fillheight", 50, 0, 1e6); - - bool dotrace = prefs->getBool(prefs_path + "dotrace"); - int pick = prefs->getInt(prefs_path + "pick"); - bool pick_to_presence = prefs->getBool(prefs_path + "pick_to_presence"); - bool pick_to_size = prefs->getBool(prefs_path + "pick_to_size"); - bool pick_to_color = prefs->getBool(prefs_path + "pick_to_color"); - bool pick_to_opacity = prefs->getBool(prefs_path + "pick_to_opacity"); + double saturation_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "saturation_rand", 0, 0, 100); + double lightness_per_j = 0.01 * prefs->getDoubleLimited(prefs_path + "lightness_per_j", 0, -100, 100); + double lightness_per_i = 0.01 * prefs->getDoubleLimited(prefs_path + "lightness_per_i", 0, -100, 100); + double lightness_rand = 0.01 * prefs->getDoubleLimited(prefs_path + "lightness_rand", 0, 0, 100); + bool color_alternatej = prefs->getBool(prefs_path + "color_alternatej"); + bool color_alternatei = prefs->getBool(prefs_path + "color_alternatei"); + + int type = prefs->getInt(prefs_path + "symmetrygroup", 0); + bool keepbbox = prefs->getBool(prefs_path + "keepbbox", true); + int imax = prefs->getInt(prefs_path + "imax", 2); + int jmax = prefs->getInt(prefs_path + "jmax", 2); + + bool fillrect = prefs->getBool(prefs_path + "fillrect"); + double fillwidth = scale_units * prefs->getDoubleLimited(prefs_path + "fillwidth", 50, 0, 1e6); + double fillheight = scale_units * prefs->getDoubleLimited(prefs_path + "fillheight", 50, 0, 1e6); + + bool dotrace = prefs->getBool(prefs_path + "dotrace"); + int pick = prefs->getInt(prefs_path + "pick"); + bool pick_to_presence = prefs->getBool(prefs_path + "pick_to_presence"); + bool pick_to_size = prefs->getBool(prefs_path + "pick_to_size"); + bool pick_to_color = prefs->getBool(prefs_path + "pick_to_color"); + bool pick_to_opacity = prefs->getBool(prefs_path + "pick_to_opacity"); double rand_picked = 0.01 * prefs->getDoubleLimited(prefs_path + "rand_picked", 0, 0, 100); - bool invert_picked = prefs->getBool(prefs_path + "invert_picked"); + bool invert_picked = prefs->getBool(prefs_path + "invert_picked"); double gamma_picked = prefs->getDoubleLimited(prefs_path + "gamma_picked", 0, -10, 10); SPItem *item = dynamic_cast<SPItem *>(obj); @@ -2216,35 +2204,29 @@ void CloneTiler::apply() double x0 = 0; double y0 = 0; - if (keepbbox && - obj_repr->attribute("inkscape:tile-w") && - obj_repr->attribute("inkscape:tile-h") && - obj_repr->attribute("inkscape:tile-x0") && - obj_repr->attribute("inkscape:tile-y0") && - obj_repr->attribute("inkscape:tile-cx") && - obj_repr->attribute("inkscape:tile-cy")) { - + if (keepbbox && obj_repr->attribute("inkscape:tile-w") && obj_repr->attribute("inkscape:tile-h") && + obj_repr->attribute("inkscape:tile-x0") && obj_repr->attribute("inkscape:tile-y0") && + obj_repr->attribute("inkscape:tile-cx") && obj_repr->attribute("inkscape:tile-cy")) { double cx = 0; double cy = 0; - sp_repr_get_double (obj_repr, "inkscape:tile-cx", &cx); - sp_repr_get_double (obj_repr, "inkscape:tile-cy", &cy); - center = Geom::Point (cx, cy); - - sp_repr_get_double (obj_repr, "inkscape:tile-w", &w); - sp_repr_get_double (obj_repr, "inkscape:tile-h", &h); - sp_repr_get_double (obj_repr, "inkscape:tile-x0", &x0); - sp_repr_get_double (obj_repr, "inkscape:tile-y0", &y0); + sp_repr_get_double(obj_repr, "inkscape:tile-cx", &cx); + sp_repr_get_double(obj_repr, "inkscape:tile-cy", &cy); + center = Geom::Point(cx, cy); + + sp_repr_get_double(obj_repr, "inkscape:tile-w", &w); + sp_repr_get_double(obj_repr, "inkscape:tile-h", &h); + sp_repr_get_double(obj_repr, "inkscape:tile-x0", &x0); + sp_repr_get_double(obj_repr, "inkscape:tile-y0", &y0); } else { bool prefs_bbox = prefs->getBool("/tools/bounding_box", false); - SPItem::BBoxType bbox_type = ( !prefs_bbox ? - SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX ); + SPItem::BBoxType bbox_type = (!prefs_bbox ? SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX); Geom::OptRect r = item->documentBounds(bbox_type); if (r) { - w = scale_units*r->dimensions()[Geom::X]; - h = scale_units*r->dimensions()[Geom::Y]; - x0 = scale_units*r->min()[Geom::X]; - y0 = scale_units*r->min()[Geom::Y]; - center = scale_units*desktop->dt2doc(item->getCenter()); + w = scale_units * r->dimensions()[Geom::X]; + h = scale_units * r->dimensions()[Geom::Y]; + x0 = scale_units * r->min()[Geom::X]; + y0 = scale_units * r->min()[Geom::Y]; + center = scale_units * desktop->dt2doc(item->getCenter()); sp_repr_set_svg_double(obj_repr, "inkscape:tile-cx", center[Geom::X]); sp_repr_set_svg_double(obj_repr, "inkscape:tile-cy", center[Geom::Y]); @@ -2260,46 +2242,32 @@ void CloneTiler::apply() } Geom::Point cur(0, 0); - Geom::Rect bbox_original (Geom::Point (x0, y0), Geom::Point (x0 + w, y0 + h)); - double perimeter_original = (w + h)/4; + Geom::Rect bbox_original(Geom::Point(x0, y0), Geom::Point(x0 + w, y0 + h)); + double perimeter_original = (w + h) / 4; // The integers i and j are reserved for tile column and row. // The doubles x and y are used for coordinates - for (int i = 0; - fillrect? - (fabs(cur[Geom::X]) < fillwidth && i < 200) // prevent "freezing" with too large fillrect, arbitrarily limit rows - : (i < imax); - i ++) { - for (int j = 0; - fillrect? - (fabs(cur[Geom::Y]) < fillheight && j < 200) // prevent "freezing" with too large fillrect, arbitrarily limit cols - : (j < jmax); - j ++) { - + for (int i = 0; fillrect ? (fabs(cur[Geom::X]) < fillwidth && i < 200) // prevent "freezing" with too large + // fillrect, arbitrarily limit rows + : (i < imax); + i++) { + for (int j = 0; fillrect ? (fabs(cur[Geom::Y]) < fillheight && j < 200) // prevent "freezing" with too large + // fillrect, arbitrarily limit cols + : (j < jmax); + j++) { // Note: We create a clone at 0,0 too, right over the original, in case our clones are colored // Get transform from symmetry, shift, scale, rotation - Geom::Affine orig_t = get_transform (type, i, j, center[Geom::X], center[Geom::Y], w, h, - shiftx_per_i, shifty_per_i, - shiftx_per_j, shifty_per_j, - shiftx_rand, shifty_rand, - shiftx_exp, shifty_exp, - shiftx_alternate, shifty_alternate, - shiftx_cumulate, shifty_cumulate, - shiftx_excludew, shifty_excludeh, - scalex_per_i, scaley_per_i, - scalex_per_j, scaley_per_j, - scalex_rand, scaley_rand, - scalex_exp, scaley_exp, - scalex_log, scaley_log, - scalex_alternate, scaley_alternate, - scalex_cumulate, scaley_cumulate, - rotate_per_i, rotate_per_j, - rotate_rand, - rotate_alternatei, rotate_alternatej, - rotate_cumulatei, rotate_cumulatej ); - Geom::Affine parent_transform = (((SPItem*)item->parent)->i2doc_affine())*(item->document->getRoot()->c2p.inverse()); - Geom::Affine t = parent_transform*orig_t*parent_transform.inverse(); + Geom::Affine orig_t = get_transform( + type, i, j, center[Geom::X], center[Geom::Y], w, h, shiftx_per_i, shifty_per_i, shiftx_per_j, + shifty_per_j, shiftx_rand, shifty_rand, shiftx_exp, shifty_exp, shiftx_alternate, shifty_alternate, + shiftx_cumulate, shifty_cumulate, shiftx_excludew, shifty_excludeh, scalex_per_i, scaley_per_i, + scalex_per_j, scaley_per_j, scalex_rand, scaley_rand, scalex_exp, scaley_exp, scalex_log, scaley_log, + scalex_alternate, scaley_alternate, scalex_cumulate, scaley_cumulate, rotate_per_i, rotate_per_j, + rotate_rand, rotate_alternatei, rotate_alternatej, rotate_cumulatei, rotate_cumulatej); + Geom::Affine parent_transform = + (((SPItem *)item->parent)->i2doc_affine()) * (item->document->getRoot()->c2p.inverse()); + Geom::Affine t = parent_transform * orig_t * parent_transform.inverse(); cur = center * t - center; if (fillrect) { if ((cur[Geom::X] > fillwidth) || (cur[Geom::Y] > fillheight)) { // off limits @@ -2307,109 +2275,114 @@ void CloneTiler::apply() } } - gchar color_string[32]; *color_string = 0; + gchar color_string[32]; + *color_string = 0; // Color tab if (!initial_color.empty()) { - guint32 rgba = sp_svg_read_color (initial_color.data(), 0x000000ff); + guint32 rgba = sp_svg_read_color(initial_color.data(), 0x000000ff); float hsl[3]; - SPColor::rgb_to_hsl_floatv (hsl, SP_RGBA32_R_F(rgba), SP_RGBA32_G_F(rgba), SP_RGBA32_B_F(rgba)); + SPColor::rgb_to_hsl_floatv(hsl, SP_RGBA32_R_F(rgba), SP_RGBA32_G_F(rgba), SP_RGBA32_B_F(rgba)); - double eff_i = (color_alternatei? (i%2) : (i)); - double eff_j = (color_alternatej? (j%2) : (j)); + double eff_i = (color_alternatei ? (i % 2) : (i)); + double eff_j = (color_alternatej ? (j % 2) : (j)); - hsl[0] += hue_per_i * eff_i + hue_per_j * eff_j + hue_rand * g_random_double_range (-1, 1); + hsl[0] += hue_per_i * eff_i + hue_per_j * eff_j + hue_rand * g_random_double_range(-1, 1); double notused; - hsl[0] = modf( hsl[0], ¬used ); // Restrict to 0-1 - hsl[1] += saturation_per_i * eff_i + saturation_per_j * eff_j + saturation_rand * g_random_double_range (-1, 1); - hsl[1] = CLAMP (hsl[1], 0, 1); - hsl[2] += lightness_per_i * eff_i + lightness_per_j * eff_j + lightness_rand * g_random_double_range (-1, 1); - hsl[2] = CLAMP (hsl[2], 0, 1); + hsl[0] = modf(hsl[0], ¬used); // Restrict to 0-1 + hsl[1] += saturation_per_i * eff_i + saturation_per_j * eff_j + + saturation_rand * g_random_double_range(-1, 1); + hsl[1] = CLAMP(hsl[1], 0, 1); + hsl[2] += + lightness_per_i * eff_i + lightness_per_j * eff_j + lightness_rand * g_random_double_range(-1, 1); + hsl[2] = CLAMP(hsl[2], 0, 1); float rgb[3]; - SPColor::hsl_to_rgb_floatv (rgb, hsl[0], hsl[1], hsl[2]); - sp_svg_write_color(color_string, sizeof(color_string), SP_RGBA32_F_COMPOSE(rgb[0], rgb[1], rgb[2], 1.0)); + SPColor::hsl_to_rgb_floatv(rgb, hsl[0], hsl[1], hsl[2]); + sp_svg_write_color(color_string, sizeof(color_string), + SP_RGBA32_F_COMPOSE(rgb[0], rgb[1], rgb[2], 1.0)); } // Blur double blur = 0.0; { - int eff_i = (blur_alternatei? (i%2) : (i)); - int eff_j = (blur_alternatej? (j%2) : (j)); - blur = (blur_per_i * eff_i + blur_per_j * eff_j + blur_rand * g_random_double_range (-1, 1)); - blur = CLAMP (blur, 0, 1); + int eff_i = (blur_alternatei ? (i % 2) : (i)); + int eff_j = (blur_alternatej ? (j % 2) : (j)); + blur = (blur_per_i * eff_i + blur_per_j * eff_j + blur_rand * g_random_double_range(-1, 1)); + blur = CLAMP(blur, 0, 1); } // Opacity double opacity = 1.0; { - int eff_i = (opacity_alternatei? (i%2) : (i)); - int eff_j = (opacity_alternatej? (j%2) : (j)); - opacity = 1 - (opacity_per_i * eff_i + opacity_per_j * eff_j + opacity_rand * g_random_double_range (-1, 1)); - opacity = CLAMP (opacity, 0, 1); + int eff_i = (opacity_alternatei ? (i % 2) : (i)); + int eff_j = (opacity_alternatej ? (j % 2) : (j)); + opacity = + 1 - (opacity_per_i * eff_i + opacity_per_j * eff_j + opacity_rand * g_random_double_range(-1, 1)); + opacity = CLAMP(opacity, 0, 1); } // Trace tab if (dotrace) { - Geom::Rect bbox_t = transform_rect (bbox_original, t*Geom::Scale(1.0/scale_units)); + Geom::Rect bbox_t = transform_rect(bbox_original, t * Geom::Scale(1.0 / scale_units)); - guint32 rgba = trace_pick (bbox_t); + guint32 rgba = trace_pick(bbox_t); float r = SP_RGBA32_R_F(rgba); float g = SP_RGBA32_G_F(rgba); float b = SP_RGBA32_B_F(rgba); float a = SP_RGBA32_A_F(rgba); float hsl[3]; - SPColor::rgb_to_hsl_floatv (hsl, r, g, b); + SPColor::rgb_to_hsl_floatv(hsl, r, g, b); gdouble val = 0; switch (pick) { - case PICK_COLOR: - val = 1 - hsl[2]; // inverse lightness; to match other picks where black = max - break; - case PICK_OPACITY: - val = a; - break; - case PICK_R: - val = r; - break; - case PICK_G: - val = g; - break; - case PICK_B: - val = b; - break; - case PICK_H: - val = hsl[0]; - break; - case PICK_S: - val = hsl[1]; - break; - case PICK_L: - val = 1 - hsl[2]; - break; - default: - break; + case PICK_COLOR: + val = 1 - hsl[2]; // inverse lightness; to match other picks where black = max + break; + case PICK_OPACITY: + val = a; + break; + case PICK_R: + val = r; + break; + case PICK_G: + val = g; + break; + case PICK_B: + val = b; + break; + case PICK_H: + val = hsl[0]; + break; + case PICK_S: + val = hsl[1]; + break; + case PICK_L: + val = 1 - hsl[2]; + break; + default: + break; } if (rand_picked > 0) { - val = randomize01 (val, rand_picked); - r = randomize01 (r, rand_picked); - g = randomize01 (g, rand_picked); - b = randomize01 (b, rand_picked); + val = randomize01(val, rand_picked); + r = randomize01(r, rand_picked); + g = randomize01(g, rand_picked); + b = randomize01(b, rand_picked); } if (gamma_picked != 0) { double power; if (gamma_picked > 0) - power = 1/(1 + fabs(gamma_picked)); + power = 1 / (1 + fabs(gamma_picked)); else power = 1 + fabs(gamma_picked); - val = pow (val, power); - r = pow (r, power); - g = pow (g, power); - b = pow (b, power); + val = pow(val, power); + r = pow(r, power); + g = pow(g, power); + b = pow(b, power); } if (invert_picked) { @@ -2419,23 +2392,22 @@ void CloneTiler::apply() b = 1 - b; } - val = CLAMP (val, 0, 1); - r = CLAMP (r, 0, 1); - g = CLAMP (g, 0, 1); - b = CLAMP (b, 0, 1); + val = CLAMP(val, 0, 1); + r = CLAMP(r, 0, 1); + g = CLAMP(g, 0, 1); + b = CLAMP(b, 0, 1); // recompose tweaked color rgba = SP_RGBA32_F_COMPOSE(r, g, b, a); if (pick_to_presence) { - if (g_random_double_range (0, 1) > val) { + if (g_random_double_range(0, 1) > val) { continue; // skip! } } if (pick_to_size) { - t = parent_transform * Geom::Translate(-center[Geom::X], -center[Geom::Y]) - * Geom::Scale (val, val) * Geom::Translate(center[Geom::X], center[Geom::Y]) - * parent_transform.inverse() * t; + t = parent_transform * Geom::Translate(-center[Geom::X], -center[Geom::Y]) * Geom::Scale(val, val) * + Geom::Translate(center[Geom::X], center[Geom::Y]) * parent_transform.inverse() * t; } if (pick_to_opacity) { opacity *= val; @@ -2449,7 +2421,7 @@ void CloneTiler::apply() continue; } - if (fabs(t[0]) + fabs (t[1]) + fabs(t[2]) + fabs(t[3]) < 1e-6) { // too small, skip + if (fabs(t[0]) + fabs(t[1]) + fabs(t[2]) + fabs(t[3]) < 1e-6) { // too small, skip continue; } @@ -2462,12 +2434,13 @@ void CloneTiler::apply() Geom::Point new_center; bool center_set = false; - if (obj_repr->attribute("inkscape:transform-center-x") || obj_repr->attribute("inkscape:transform-center-y")) { - new_center = scale_units*desktop->dt2doc(item->getCenter()) * orig_t; + if (obj_repr->attribute("inkscape:transform-center-x") || + obj_repr->attribute("inkscape:transform-center-y")) { + new_center = scale_units * desktop->dt2doc(item->getCenter()) * orig_t; center_set = true; } - gchar *affinestr=sp_svg_transform_write(t); + gchar *affinestr = sp_svg_transform_write(t); clone->setAttribute("transform", affinestr); g_free(affinestr); @@ -2493,8 +2466,9 @@ void CloneTiler::apply() // it's hard to figure out exact width/height of the tile without having an object // that we can take bbox of; however here we only need a lower bound so that blur // margins are not too small, and the perimeter should work - SPFilter *constructed = new_filter_gaussian_blur(desktop->getDocument(), radius, t.descrim(), t.expansionX(), t.expansionY(), perimeter, perimeter); - sp_style_set_property_url (clone_object, "filter", constructed, false); + SPFilter *constructed = new_filter_gaussian_blur(desktop->getDocument(), radius, t.descrim(), + t.expansionX(), t.expansionY(), perimeter, perimeter); + sp_style_set_property_url(clone_object, "filter", constructed, false); } if (center_set) { @@ -2513,18 +2487,17 @@ void CloneTiler::apply() } if (dotrace) { - trace_finish (); + trace_finish(); } change_selection(selection); desktop->clearWaitingCursor(); - DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_CLONETILER, - _("Create tiled clones")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_CLONETILER, _("Create tiled clones")); } -Gtk::Box * CloneTiler::new_tab(Gtk::Notebook *nb, const gchar *label) +Gtk::Box *CloneTiler::new_tab(Gtk::Notebook *nb, const gchar *label) { auto l = Gtk::manage(new Gtk::Label(label, true)); auto vb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL, VB_MARGIN)); @@ -2534,18 +2507,16 @@ Gtk::Box * CloneTiler::new_tab(Gtk::Notebook *nb, const gchar *label) return vb; } -void CloneTiler::checkbox_toggled(Gtk::ToggleButton *tb, - const Glib::ustring &attr) +void CloneTiler::checkbox_toggled(Gtk::ToggleButton *tb, const Glib::ustring &attr) { auto prefs = Inkscape::Preferences::get(); prefs->setBool(prefs_path + attr, tb->get_active()); } -Gtk::Widget * CloneTiler::checkbox(const char *tip, - const Glib::ustring &attr) +Gtk::Widget *CloneTiler::checkbox(const char *tip, const Glib::ustring &attr) { auto hb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, VB_MARGIN)); - auto b = Gtk::manage(new UI::Widget::CheckButtonInternal()); + auto b = Gtk::manage(new UI::Widget::CheckButtonInternal()); b->set_tooltip_text(tip); auto const prefs = Inkscape::Preferences::get(); @@ -2560,47 +2531,38 @@ Gtk::Widget * CloneTiler::checkbox(const char *tip, return hb; } -void CloneTiler::value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, - Glib::ustring const &pref) +void CloneTiler::value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, Glib::ustring const &pref) { auto prefs = Inkscape::Preferences::get(); prefs->setDouble(prefs_path + pref, adj->get_value()); } -Gtk::Widget * CloneTiler::spinbox(const char *tip, - const Glib::ustring &attr, - double lower, - double upper, - const gchar *suffix, - bool exponent/* = false*/) +Gtk::Widget *CloneTiler::spinbox(const char *tip, const Glib::ustring &attr, double lower, double upper, + const gchar *suffix, bool exponent /* = false*/) { auto hb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0)); { // Parameters for adjustment - auto const initial_value = (exponent ? 1.0 : 0.0); + auto const initial_value = (exponent ? 1.0 : 0.0); auto const step_increment = (exponent ? 0.01 : 0.1); auto const page_increment = (exponent ? 0.05 : 0.4); - auto a = Gtk::Adjustment::create(initial_value, - lower, - upper, - step_increment, - page_increment); + auto a = Gtk::Adjustment::create(initial_value, lower, upper, step_increment, page_increment); auto const climb_rate = (exponent ? 0.01 : 0.1); auto const digits = (exponent ? 2 : 1); auto sb = new Inkscape::UI::Widget::SpinButton(a, climb_rate, digits); - sb->set_tooltip_text (tip); - sb->set_width_chars (5); + sb->set_tooltip_text(tip); + sb->set_width_chars(5); sb->set_digits(3); hb->pack_start(*sb, false, false, SB_MARGIN); auto prefs = Inkscape::Preferences::get(); - auto value = prefs->getDoubleLimited(prefs_path + attr, exponent? 1.0 : 0.0, lower, upper); - a->set_value (value); + auto value = prefs->getDoubleLimited(prefs_path + attr, exponent ? 1.0 : 0.0, lower, upper); + a->set_value(value); a->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &CloneTiler::value_changed), a, attr)); if (exponent) { @@ -2629,7 +2591,7 @@ void CloneTiler::symgroup_changed(Gtk::ComboBox *cb) void CloneTiler::xy_changed(Glib::RefPtr<Gtk::Adjustment> &adj, Glib::ustring const &pref) { auto prefs = Inkscape::Preferences::get(); - prefs->setInt(prefs_path + pref, (int) floor(adj->get_value() + 0.5)); + prefs->setInt(prefs_path + pref, (int)floor(adj->get_value() + 0.5)); } void CloneTiler::keep_bbox_toggled() @@ -2644,7 +2606,6 @@ void CloneTiler::pick_to(Gtk::ToggleButton *tb, Glib::ustring const &pref) prefs->setBool(prefs_path + pref, tb->get_active()); } - void CloneTiler::reset_recursive(Gtk::Widget *w) { if (w) { @@ -2692,7 +2653,7 @@ void CloneTiler::table_attach(Gtk::Grid *table, Gtk::Widget *widget, float align table->attach(*widget, col, row, 1, 1); } -Gtk::Grid * CloneTiler::table_x_y_rand(int values) +Gtk::Grid *CloneTiler::table_x_y_rand(int values) { auto table = Gtk::manage(new Gtk::Grid()); table->set_row_spacing(6); @@ -2701,8 +2662,8 @@ Gtk::Grid * CloneTiler::table_x_y_rand(int values) table->set_border_width(VB_MARGIN); { - auto hb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0)); - hb->set_homogeneous(false); + auto hb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0)); + hb->set_homogeneous(false); auto i = Glib::wrap(sp_get_icon_image("object-rows", GTK_ICON_SIZE_MENU)); hb->pack_start(*i, false, false, 2); @@ -2715,8 +2676,8 @@ Gtk::Grid * CloneTiler::table_x_y_rand(int values) } { - auto hb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0)); - hb->set_homogeneous(false); + auto hb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0)); + hb->set_homogeneous(false); auto i = Glib::wrap(sp_get_icon_image("object-columns", GTK_ICON_SIZE_MENU)); hb->pack_start(*i, false, false, 2); @@ -2756,7 +2717,6 @@ void CloneTiler::switch_to_create() prefs->setBool(prefs_path + "fillrect", false); } - void CloneTiler::switch_to_fill() { if (_rowscols) { @@ -2773,8 +2733,8 @@ void CloneTiler::switch_to_fill() void CloneTiler::fill_width_changed() { auto const raw_dist = fill_width->get_value(); - auto const unit = unit_menu->getUnit(); - auto const pixels = Inkscape::Util::Quantity::convert(raw_dist, unit, "px"); + auto const unit = unit_menu->getUnit(); + auto const pixels = Inkscape::Util::Quantity::convert(raw_dist, unit, "px"); auto prefs = Inkscape::Preferences::get(); prefs->setDouble(prefs_path + "fillwidth", pixels); @@ -2783,8 +2743,8 @@ void CloneTiler::fill_width_changed() void CloneTiler::fill_height_changed() { auto const raw_dist = fill_height->get_value(); - auto const unit = unit_menu->getUnit(); - auto const pixels = Inkscape::Util::Quantity::convert(raw_dist, unit, "px"); + auto const unit = unit_menu->getUnit(); + auto const pixels = Inkscape::Util::Quantity::convert(raw_dist, unit, "px"); auto prefs = Inkscape::Preferences::get(); prefs->setDouble(prefs_path + "fillheight", pixels); @@ -2795,9 +2755,9 @@ void 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); fill_width->set_value(width_value); @@ -2806,7 +2766,7 @@ void CloneTiler::unit_changed() void CloneTiler::do_pick_toggled() { - auto prefs = Inkscape::Preferences::get(); + auto prefs = Inkscape::Preferences::get(); auto active = _b->get_active(); prefs->setBool(prefs_path + "dotrace", active); @@ -2821,11 +2781,9 @@ void CloneTiler::show_page_trace() _b->set_active(false); } - -} -} -} - +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/clonetiler.h b/src/ui/dialog/clonetiler.h index 434dee3471362b693a95b95b7a150dc1ad9a85c4..a695190b97728e2f91832d3c3923e40cd29427a1 100644 --- a/src/ui/dialog/clonetiler.h +++ b/src/ui/dialog/clonetiler.h @@ -11,46 +11,48 @@ #ifndef __SP_CLONE_TILER_H__ #define __SP_CLONE_TILER_H__ -#include "ui/widget/panel.h" - #include "ui/widget/color-picker.h" +#include "ui/widget/panel.h" namespace Gtk { - class Box; - class ComboBox; - class Grid; - class Notebook; - class SizeGroup; - class ToggleButton; -} +class Box; +class ComboBox; +class Grid; +class Notebook; +class SizeGroup; +class ToggleButton; +} // namespace Gtk class SPItem; class SPObject; namespace Geom { - class Rect; - class Affine; -} +class Rect; +class Affine; +} // namespace Geom namespace Inkscape { namespace UI { namespace Widget { - class CheckButtonInternal; - class UnitMenu; -} +class CheckButtonInternal; +class UnitMenu; +} // namespace Widget namespace Dialog { -class CloneTiler : public Widget::Panel { +class CloneTiler : public Widget::Panel +{ public: CloneTiler(); ~CloneTiler() override; static CloneTiler &getInstance() { return *new CloneTiler(); } void show_page_trace(); + protected: - enum PickType { + enum PickType + { PICK_COLOR, PICK_OPACITY, PICK_R, @@ -61,42 +63,35 @@ protected: PICK_L }; - Gtk::Box * new_tab(Gtk::Notebook *nb, const gchar *label); - Gtk::Grid * table_x_y_rand(int values); - Gtk::Widget * spinbox(const char *tip, - const Glib::ustring &attr, - double lower, - double upper, - const gchar *suffix, - bool exponent = false); - Gtk::Widget * checkbox(const char *tip, - const Glib::ustring &attr); + Gtk::Box *new_tab(Gtk::Notebook *nb, const gchar *label); + Gtk::Grid *table_x_y_rand(int values); + Gtk::Widget *spinbox(const char *tip, const Glib::ustring &attr, double lower, double upper, const gchar *suffix, + bool exponent = false); + Gtk::Widget *checkbox(const char *tip, const Glib::ustring &attr); void table_attach(Gtk::Grid *table, Gtk::Widget *widget, float align, int row, int col); - void symgroup_changed(Gtk::ComboBox *cb); - void on_picker_color_changed(guint rgba); - void trace_hide_tiled_clones_recursively(SPObject *from); - guint number_of_clones(SPObject *obj); - void trace_setup(SPDocument *doc, gdouble zoom, SPItem *original); - guint32 trace_pick(Geom::Rect box); - void trace_finish(); - bool is_a_clone_of(SPObject *tile, SPObject *obj); + void symgroup_changed(Gtk::ComboBox *cb); + void on_picker_color_changed(guint rgba); + void trace_hide_tiled_clones_recursively(SPObject *from); + guint number_of_clones(SPObject *obj); + void trace_setup(SPDocument *doc, gdouble zoom, SPItem *original); + guint32 trace_pick(Geom::Rect box); + void trace_finish(); + bool is_a_clone_of(SPObject *tile, SPObject *obj); Geom::Rect transform_rect(Geom::Rect const &r, Geom::Affine const &m); - double randomize01(double val, double rand); + double randomize01(double val, double rand); void apply(); void change_selection(Inkscape::Selection *selection); - void checkbox_toggled(Gtk::ToggleButton *tb, - Glib::ustring const &attr); + void checkbox_toggled(Gtk::ToggleButton *tb, Glib::ustring const &attr); void do_pick_toggled(); void external_change(); void fill_width_changed(); void fill_height_changed(); void keep_bbox_toggled(); - void on_remove_button_clicked() {remove();} + void on_remove_button_clicked() { remove(); } void pick_switched(PickType); - void pick_to(Gtk::ToggleButton *tb, - Glib::ustring const &pref); + void pick_to(Gtk::ToggleButton *tb, Glib::ustring const &pref); void remove(bool do_undo = true); void reset(); void reset_recursive(Gtk::Widget *w); @@ -108,46 +103,33 @@ protected: void xy_changed(Glib::RefPtr<Gtk::Adjustment> &adj, Glib::ustring const &pref); Geom::Affine get_transform( - // symmetry group - int type, - - // row, column - int i, int j, - - // center, width, height of the tile - double cx, double cy, - double w, double h, - - // values from the dialog: - // Shift - double shiftx_per_i, double shifty_per_i, - double shiftx_per_j, double shifty_per_j, - double shiftx_rand, double shifty_rand, - double shiftx_exp, double shifty_exp, - int shiftx_alternate, int shifty_alternate, - int shiftx_cumulate, int shifty_cumulate, - int shiftx_excludew, int shifty_excludeh, - - // Scale - double scalex_per_i, double scaley_per_i, - double scalex_per_j, double scaley_per_j, - double scalex_rand, double scaley_rand, - double scalex_exp, double scaley_exp, - double scalex_log, double scaley_log, - int scalex_alternate, int scaley_alternate, - int scalex_cumulate, int scaley_cumulate, - - // Rotation - double rotate_per_i, double rotate_per_j, - double rotate_rand, - int rotate_alternatei, int rotate_alternatej, - int rotate_cumulatei, int rotate_cumulatej - ); + // symmetry group + int type, + + // row, column + int i, int j, + // center, width, height of the tile + double cx, double cy, double w, double h, + + // values from the dialog: + // Shift + double shiftx_per_i, double shifty_per_i, double shiftx_per_j, double shifty_per_j, double shiftx_rand, + double shifty_rand, double shiftx_exp, double shifty_exp, int shiftx_alternate, int shifty_alternate, + int shiftx_cumulate, int shifty_cumulate, int shiftx_excludew, int shifty_excludeh, + + // Scale + double scalex_per_i, double scaley_per_i, double scalex_per_j, double scaley_per_j, double scalex_rand, + double scaley_rand, double scalex_exp, double scaley_exp, double scalex_log, double scaley_log, + int scalex_alternate, int scaley_alternate, int scalex_cumulate, int scaley_cumulate, + + // Rotation + double rotate_per_i, double rotate_per_j, double rotate_rand, int rotate_alternatei, int rotate_alternatej, + int rotate_cumulatei, int rotate_cumulatej); private: CloneTiler(CloneTiler const &d) = delete; - CloneTiler& operator=(CloneTiler const &d) = delete; + CloneTiler &operator=(CloneTiler const &d) = delete; UI::Widget::CheckButtonInternal *_b; UI::Widget::CheckButtonInternal *_cb_keep_bbox; @@ -177,11 +159,10 @@ private: Gtk::Label *_status; Gtk::Box *_rowscols; Gtk::Box *_widthheight; - }; - -enum { +enum +{ TILE_P1, TILE_P2, TILE_PM, @@ -205,7 +186,6 @@ enum { } // namespace UI } // namespace Inkscape - #endif /* diff --git a/src/ui/dialog/color-item.cpp b/src/ui/dialog/color-item.cpp index 170ba0418f0ad536ce25ffbf87ed020c769c047b..7a244751960553c79d4846f301285ffa93b4c2a8 100644 --- a/src/ui/dialog/color-item.cpp +++ b/src/ui/dialog/color-item.cpp @@ -12,27 +12,24 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cerrno> - -#include <gtkmm/label.h> -#include <glibmm/i18n.h> - #include "color-item.h" -#include "desktop.h" +#include <cerrno> +#include <glibmm/i18n.h> +#include <gtkmm/label.h> #include "desktop-style.h" +#include "desktop.h" #include "display/cairo-utils.h" -#include "document.h" #include "document-undo.h" +#include "document.h" #include "inkscape.h" // for SP_ACTIVE_DESKTOP #include "io/resource.h" #include "io/sys.h" #include "message-context.h" #include "svg/svg-color.h" -#include "verbs.h" #include "ui/widget/gradient-vector-selector.h" - +#include "verbs.h" namespace Inkscape { namespace UI { @@ -41,23 +38,22 @@ namespace Dialog { static std::vector<std::string> mimeStrings; static std::map<std::string, guint> mimeToInt; - -void -ColorItem::handleClick() { +void ColorItem::handleClick() +{ buttonClicked(false); } -void -ColorItem::handleSecondaryClick(gint /*arg1*/) { +void ColorItem::handleSecondaryClick(gint /*arg1*/) +{ buttonClicked(true); } -bool -ColorItem::handleEnterNotify(GdkEventCrossing* /*event*/) { +bool ColorItem::handleEnterNotify(GdkEventCrossing * /*event*/) +{ SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if ( desktop ) { - gchar* msg = g_strdup_printf(_("Color: <b>%s</b>; <b>Click</b> to set fill, <b>Shift+click</b> to set stroke"), - def.descr.c_str()); + if (desktop) { + gchar *msg = g_strdup_printf(_("Color: <b>%s</b>; <b>Click</b> to set fill, <b>Shift+click</b> to set stroke"), + def.descr.c_str()); desktop->tipsMessageContext()->set(Inkscape::INFORMATION_MESSAGE, msg); g_free(msg); } @@ -65,28 +61,27 @@ ColorItem::handleEnterNotify(GdkEventCrossing* /*event*/) { return false; } -bool -ColorItem::handleLeaveNotify(GdkEventCrossing* /*event*/) { +bool ColorItem::handleLeaveNotify(GdkEventCrossing * /*event*/) +{ SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if ( desktop ) { + if (desktop) { desktop->tipsMessageContext()->clear(); } return false; } -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); - if ( pos != std::string::npos ) - { - std::string::size_type pos2 = str.find( '(', pos ); - if ( pos2 != std::string::npos ) { - std::string::size_type endPos = str.find( ')', pos2 ); - if ( endPos != std::string::npos ) { - dst = str.substr( pos2 + 1, (endPos - pos2 - 1) ); + if (pos != std::string::npos) { + std::string::size_type pos2 = str.find('(', pos); + if (pos2 != std::string::npos) { + std::string::size_type endPos = str.find(')', pos2); + if (endPos != std::string::npos) { + dst = str.substr(pos2 + 1, (endPos - pos2 - 1)); good = true; } } @@ -94,26 +89,26 @@ static bool getBlock( std::string& dst, guchar ch, std::string const & str ) return good; } -static bool popVal( guint64& numVal, std::string& str ) +static bool popVal(guint64 &numVal, std::string &str) { bool good = false; std::string::size_type endPos = str.find(','); - if ( endPos == std::string::npos ) { + if (endPos == std::string::npos) { endPos = str.length(); } - if ( endPos != std::string::npos && endPos > 0 ) { - std::string xxx = str.substr( 0, endPos ); - const gchar* ptr = xxx.c_str(); - gchar* endPtr = nullptr; - numVal = g_ascii_strtoull( ptr, &endPtr, 10 ); - if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) { + if (endPos != std::string::npos && endPos > 0) { + std::string xxx = str.substr(0, endPos); + const gchar *ptr = xxx.c_str(); + gchar *endPtr = nullptr; + numVal = g_ascii_strtoull(ptr, &endPtr, 10); + if ((numVal == G_MAXUINT64) && (ERANGE == errno)) { // overflow - } else if ( (numVal == 0) && (endPtr == ptr) ) { + } else if ((numVal == 0) && (endPtr == ptr)) { // failed conversion } else { good = true; - str.erase( 0, endPos + 1 ); + str.erase(0, endPos + 1); } } @@ -121,10 +116,9 @@ static bool popVal( guint64& numVal, std::string& str ) } // TODO resolve this more cleanly: -extern bool colorItemHandleButtonPress(GdkEventButton* event, UI::Widget::Preview *preview, gpointer user_data); +extern bool colorItemHandleButtonPress(GdkEventButton *event, UI::Widget::Preview *preview, gpointer user_data); -void -ColorItem::drag_begin(const Glib::RefPtr<Gdk::DragContext> &dc) +void ColorItem::drag_begin(const Glib::RefPtr<Gdk::DragContext> &dc) { using Inkscape::IO::Resource::get_path; using Inkscape::IO::Resource::PIXMAPS; @@ -132,18 +126,18 @@ ColorItem::drag_begin(const Glib::RefPtr<Gdk::DragContext> &dc) int width = 32; int height = 24; - if (def.getType() != ege::PaintDef::RGB){ + if (def.getType() != ege::PaintDef::RGB) { GError *error; gsize bytesRead = 0; gsize bytesWritten = 0; - gchar *localFilename = g_filename_from_utf8(get_path(SYSTEM, PIXMAPS, "remove-color.png"), -1, &bytesRead, - &bytesWritten, &error); + gchar *localFilename = + g_filename_from_utf8(get_path(SYSTEM, PIXMAPS, "remove-color.png"), -1, &bytesRead, &bytesWritten, &error); auto pixbuf = Gdk::Pixbuf::create_from_file(localFilename, width, height, false); g_free(localFilename); dc->set_icon(pixbuf, 0, 0); } else { Glib::RefPtr<Gdk::Pixbuf> pixbuf; - if (getGradient() ){ + if (getGradient()) { cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); cairo_pattern_t *gradient = getGradient()->create_preview_pattern(width); cairo_t *ct = cairo_create(s); @@ -155,11 +149,10 @@ ColorItem::drag_begin(const Glib::RefPtr<Gdk::DragContext> &dc) pixbuf = Glib::wrap(ink_pixbuf_create_from_cairo_surface(s)); } else { - pixbuf = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, width, height ); - guint32 fillWith = (0xff000000 & (def.getR() << 24)) - | (0x00ff0000 & (def.getG() << 16)) - | (0x0000ff00 & (def.getB() << 8)); - pixbuf->fill( fillWith ); + pixbuf = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, false, 8, width, height); + guint32 fillWith = (0xff000000 & (def.getR() << 24)) | (0x00ff0000 & (def.getG() << 16)) | + (0x0000ff00 & (def.getB() << 8)); + pixbuf->fill(fillWith); } dc->set_icon(pixbuf, 0, 0); } @@ -178,43 +171,37 @@ ColorItem::drag_begin(const Glib::RefPtr<Gdk::DragContext> &dc) // return TRUE; // } - SwatchPage::SwatchPage() : _prefWidth(0) -{ -} - -SwatchPage::~SwatchPage() -= default; - - -ColorItem::ColorItem(ege::PaintDef::ColorType type) : - def(type), - _isFill(false), - _isStroke(false), - _isLive(false), - _linkIsTone(false), - _linkPercent(0), - _linkGray(0), - _linkSrc(nullptr), - _grad(nullptr), - _pattern(nullptr) -{ -} - -ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) : - def( r, g, b, name.raw() ), - _isFill(false), - _isStroke(false), - _isLive(false), - _linkIsTone(false), - _linkPercent(0), - _linkGray(0), - _linkSrc(nullptr), - _grad(nullptr), - _pattern(nullptr) -{ -} +{} + +SwatchPage::~SwatchPage() = default; + +ColorItem::ColorItem(ege::PaintDef::ColorType type) + : def(type) + , _isFill(false) + , _isStroke(false) + , _isLive(false) + , _linkIsTone(false) + , _linkPercent(0) + , _linkGray(0) + , _linkSrc(nullptr) + , _grad(nullptr) + , _pattern(nullptr) +{} + +ColorItem::ColorItem(unsigned int r, unsigned int g, unsigned int b, Glib::ustring &name) + : def(r, g, b, name.raw()) + , _isFill(false) + , _isStroke(false) + , _isLive(false) + , _linkIsTone(false) + , _linkPercent(0) + , _linkGray(0) + , _linkSrc(nullptr) + , _grad(nullptr) + , _pattern(nullptr) +{} ColorItem::~ColorItem() { @@ -223,17 +210,17 @@ ColorItem::~ColorItem() } } -ColorItem::ColorItem(ColorItem const &other) : - Inkscape::UI::Previewable() +ColorItem::ColorItem(ColorItem const &other) + : Inkscape::UI::Previewable() { - if ( this != &other ) { + if (this != &other) { *this = other; } } ColorItem &ColorItem::operator=(ColorItem const &other) { - if ( this != &other ) { + if (this != &other) { def = other.def; // TODO - correct linkage @@ -243,22 +230,22 @@ ColorItem &ColorItem::operator=(ColorItem const &other) return *this; } -void ColorItem::setState( bool fill, bool stroke ) +void ColorItem::setState(bool fill, bool stroke) { - if ( (_isFill != fill) || (_isStroke != stroke) ) { + if ((_isFill != fill) || (_isStroke != stroke)) { _isFill = fill; _isStroke = stroke; - for ( auto widget : _previews ) { + for (auto widget : _previews) { auto preview = dynamic_cast<UI::Widget::Preview *>(widget); if (preview) { int val = preview->get_linked(); val &= ~(UI::Widget::PREVIEW_FILL | UI::Widget::PREVIEW_STROKE); - if ( _isFill ) { + if (_isFill) { val |= UI::Widget::PREVIEW_FILL; } - if ( _isStroke ) { + if (_isStroke) { val |= UI::Widget::PREVIEW_STROKE; } preview->set_linked(static_cast<UI::Widget::LinkType>(val)); @@ -274,20 +261,19 @@ void ColorItem::setGradient(SPGradient *grad) // TODO regen and push to listeners } - setName( gr_prepare_label(_grad) ); + setName(gr_prepare_label(_grad)); } void ColorItem::setName(const Glib::ustring name) { - //def.descr = name; + // def.descr = name; for (auto widget : _previews) { auto preview = dynamic_cast<UI::Widget::Preview *>(widget); auto label = dynamic_cast<Gtk::Label *>(widget); if (preview) { preview->set_tooltip_text(name); - } - else if (label) { + } else if (label) { label->set_text(name); } } @@ -306,45 +292,36 @@ void ColorItem::setPattern(cairo_pattern_t *pattern) _updatePreviews(); } -void -ColorItem::_dragGetColorData(const Glib::RefPtr<Gdk::DragContext>& /*drag_context*/, - Gtk::SelectionData &data, - guint info, - guint /*time*/) +void ColorItem::_dragGetColorData(const Glib::RefPtr<Gdk::DragContext> & /*drag_context*/, Gtk::SelectionData &data, + guint info, guint /*time*/) { std::string key; - if ( info < mimeStrings.size() ) { + if (info < mimeStrings.size()) { key = mimeStrings[info]; } else { g_warning("ERROR: unknown value (%d)", info); } - if ( !key.empty() ) { - char* tmp = nullptr; + if (!key.empty()) { + char *tmp = nullptr; int len = 0; int format = 0; def.getMIMEData(key, tmp, len, format); - if ( tmp ) { - data.set(key, format, (guchar*)tmp, len ); + if (tmp) { + data.set(key, format, (guchar *)tmp, len); delete[] tmp; } } } -void ColorItem::_dropDataIn( GtkWidget */*widget*/, - GdkDragContext */*drag_context*/, - gint /*x*/, gint /*y*/, - GtkSelectionData */*data*/, - guint /*info*/, - guint /*event_time*/, - gpointer /*user_data*/) -{ -} +void ColorItem::_dropDataIn(GtkWidget * /*widget*/, GdkDragContext * /*drag_context*/, gint /*x*/, gint /*y*/, + GtkSelectionData * /*data*/, guint /*info*/, guint /*event_time*/, gpointer /*user_data*/) +{} -void ColorItem::_colorDefChanged(void* data) +void ColorItem::_colorDefChanged(void *data) { - ColorItem* item = reinterpret_cast<ColorItem*>(data); - if ( item ) { + ColorItem *item = reinterpret_cast<ColorItem *>(data); + if (item) { item->_updatePreviews(); } } @@ -359,28 +336,28 @@ void ColorItem::_updatePreviews() } } - for (auto & _listener : _listeners) { + for (auto &_listener : _listeners) { guint r = def.getR(); guint g = def.getG(); guint b = def.getB(); - if ( _listener->_linkIsTone ) { - r = ( (_listener->_linkPercent * _listener->_linkGray) + ((100 - _listener->_linkPercent) * r) ) / 100; - g = ( (_listener->_linkPercent * _listener->_linkGray) + ((100 - _listener->_linkPercent) * g) ) / 100; - b = ( (_listener->_linkPercent * _listener->_linkGray) + ((100 - _listener->_linkPercent) * b) ) / 100; + if (_listener->_linkIsTone) { + r = ((_listener->_linkPercent * _listener->_linkGray) + ((100 - _listener->_linkPercent) * r)) / 100; + g = ((_listener->_linkPercent * _listener->_linkGray) + ((100 - _listener->_linkPercent) * g)) / 100; + b = ((_listener->_linkPercent * _listener->_linkGray) + ((100 - _listener->_linkPercent) * b)) / 100; } else { - r = ( (_listener->_linkPercent * 255) + ((100 - _listener->_linkPercent) * r) ) / 100; - g = ( (_listener->_linkPercent * 255) + ((100 - _listener->_linkPercent) * g) ) / 100; - b = ( (_listener->_linkPercent * 255) + ((100 - _listener->_linkPercent) * b) ) / 100; + r = ((_listener->_linkPercent * 255) + ((100 - _listener->_linkPercent) * r)) / 100; + g = ((_listener->_linkPercent * 255) + ((100 - _listener->_linkPercent) * g)) / 100; + b = ((_listener->_linkPercent * 255) + ((100 - _listener->_linkPercent) * b)) / 100; } - _listener->def.setRGB( r, g, b ); + _listener->def.setRGB(r, g, b); } } -void ColorItem::_regenPreview(UI::Widget::Preview * preview) +void ColorItem::_regenPreview(UI::Widget::Preview *preview) { - if ( def.getType() != ege::PaintDef::RGB ) { + if (def.getType() != ege::PaintDef::RGB) { using Inkscape::IO::Resource::get_path; using Inkscape::IO::Resource::PIXMAPS; using Inkscape::IO::Resource::SYSTEM; @@ -391,16 +368,14 @@ void ColorItem::_regenPreview(UI::Widget::Preview * preview) g_filename_from_utf8(get_path(SYSTEM, PIXMAPS, "remove-color.png"), -1, &bytesRead, &bytesWritten, &error); auto pixbuf = Gdk::Pixbuf::create_from_file(localFilename); if (!pixbuf) { - g_warning("Null pixbuf for %p [%s]", localFilename, localFilename ); + g_warning("Null pixbuf for %p [%s]", localFilename, localFilename); } g_free(localFilename); preview->set_pixbuf(pixbuf); - } - else if ( !_pattern ){ - preview->set_color((def.getR() << 8) | def.getR(), - (def.getG() << 8) | def.getG(), - (def.getB() << 8) | def.getB() ); + } else if (!_pattern) { + preview->set_color((def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), + (def.getB() << 8) | def.getB()); } else { // These correspond to PREVIEW_PIXBUF_WIDTH and VBLOCK from swatches.cpp // TODO: the pattern to draw should be in the widget that draws the preview, @@ -419,20 +394,16 @@ void ColorItem::_regenPreview(UI::Widget::Preview * preview) preview->set_pixbuf(pixbuf); } - preview->set_linked(static_cast<UI::Widget::LinkType>( (_linkSrc ? UI::Widget::PREVIEW_LINK_IN : 0) - | (_listeners.empty() ? 0 : UI::Widget::PREVIEW_LINK_OUT) - | (_isLive ? UI::Widget::PREVIEW_LINK_OTHER:0)) ); + preview->set_linked(static_cast<UI::Widget::LinkType>((_linkSrc ? UI::Widget::PREVIEW_LINK_IN : 0) | + (_listeners.empty() ? 0 : UI::Widget::PREVIEW_LINK_OUT) | + (_isLive ? UI::Widget::PREVIEW_LINK_OTHER : 0))); } -Gtk::Widget* -ColorItem::getPreview(UI::Widget::PreviewStyle style, - UI::Widget::ViewType view, - UI::Widget::PreviewSize size, - guint ratio, - guint border) +Gtk::Widget *ColorItem::getPreview(UI::Widget::PreviewStyle style, UI::Widget::ViewType view, + UI::Widget::PreviewSize size, guint ratio, guint border) { - Gtk::Widget* widget = nullptr; - if ( style == UI::Widget::PREVIEW_STYLE_BLURB) { + Gtk::Widget *widget = nullptr; + if (style == UI::Widget::PREVIEW_STYLE_BLURB) { Gtk::Label *lbl = new Gtk::Label(def.descr); lbl->set_halign(Gtk::ALIGN_START); lbl->set_valign(Gtk::ALIGN_CENTER); @@ -443,27 +414,25 @@ ColorItem::getPreview(UI::Widget::PreviewStyle style, _regenPreview(preview); - preview->set_details((UI::Widget::ViewType)view, - (UI::Widget::PreviewSize)size, - ratio, - border ); + preview->set_details((UI::Widget::ViewType)view, (UI::Widget::PreviewSize)size, ratio, border); - def.addCallback( _colorDefChanged, this ); + def.addCallback(_colorDefChanged, this); preview->set_focus_on_click(false); preview->set_tooltip_text(def.descr); preview->signal_clicked().connect(sigc::mem_fun(*this, &ColorItem::handleClick)); preview->signal_alt_clicked().connect(sigc::mem_fun(*this, &ColorItem::handleSecondaryClick)); - preview->signal_button_press_event().connect(sigc::bind(sigc::ptr_fun(&colorItemHandleButtonPress), preview, this)); + preview->signal_button_press_event().connect( + sigc::bind(sigc::ptr_fun(&colorItemHandleButtonPress), preview, this)); { auto listing = def.getMIMETypes(); std::vector<Gtk::TargetEntry> entries; - for ( auto str : listing ) { + for (auto str : listing) { auto target = str.c_str(); guint flags = 0; - if ( mimeToInt.find(str) == mimeToInt.end() ){ + if (mimeToInt.find(str) == mimeToInt.end()) { // these next lines are order-dependent: mimeToInt[str] = mimeStrings.size(); mimeStrings.push_back(str); @@ -473,8 +442,7 @@ ColorItem::getPreview(UI::Widget::PreviewStyle style, entries.push_back(entry); } - preview->drag_source_set(entries, Gdk::BUTTON1_MASK, - Gdk::DragAction(Gdk::ACTION_MOVE | Gdk::ACTION_COPY) ); + preview->drag_source_set(entries, Gdk::BUTTON1_MASK, Gdk::DragAction(Gdk::ACTION_MOVE | Gdk::ACTION_COPY)); } preview->signal_drag_data_get().connect(sigc::mem_fun(*this, &ColorItem::_dragGetColorData)); @@ -485,7 +453,7 @@ ColorItem::getPreview(UI::Widget::PreviewStyle style, widget = preview; } - _previews.push_back( widget ); + _previews.push_back(widget); return widget; } @@ -494,26 +462,26 @@ void ColorItem::buttonClicked(bool secondary) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; if (desktop) { - char const * attrName = secondary ? "stroke" : "fill"; + char const *attrName = secondary ? "stroke" : "fill"; SPCSSAttr *css = sp_repr_css_attr_new(); Glib::ustring descr; switch (def.getType()) { case ege::PaintDef::CLEAR: { // TODO actually make this clear - sp_repr_css_set_property( css, attrName, "none" ); - descr = secondary? _("Remove stroke color") : _("Remove fill color"); + sp_repr_css_set_property(css, attrName, "none"); + descr = secondary ? _("Remove stroke color") : _("Remove fill color"); break; } case ege::PaintDef::NONE: { - sp_repr_css_set_property( css, attrName, "none" ); - descr = secondary? _("Set stroke color to none") : _("Set fill color to none"); + sp_repr_css_set_property(css, attrName, "none"); + descr = secondary ? _("Set stroke color to none") : _("Set fill color to none"); break; } -//mark + // mark case ege::PaintDef::RGB: { Glib::ustring colorspec; - if ( _grad ){ + if (_grad) { colorspec = "url(#"; colorspec += _grad->getId(); colorspec += ")"; @@ -523,90 +491,82 @@ void ColorItem::buttonClicked(bool secondary) sp_svg_write_color(c, sizeof(c), rgba); colorspec = c; } -//end mark - sp_repr_css_set_property( css, attrName, colorspec.c_str() ); - descr = secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"); + // end mark + sp_repr_css_set_property(css, attrName, colorspec.c_str()); + descr = secondary ? _("Set stroke color from swatch") : _("Set fill color from swatch"); break; } } sp_desktop_set_style(desktop, css); sp_repr_css_attr_unref(css); - DocumentUndo::done( desktop->getDocument(), SP_VERB_DIALOG_SWATCHES, descr.c_str() ); + DocumentUndo::done(desktop->getDocument(), SP_VERB_DIALOG_SWATCHES, descr.c_str()); } } -void ColorItem::_wireMagicColors( SwatchPage *colorSet ) +void ColorItem::_wireMagicColors(SwatchPage *colorSet) { - if ( colorSet ) - { - for ( boost::ptr_vector<ColorItem>::iterator it = colorSet->_colors.begin(); it != colorSet->_colors.end(); ++it ) - { + if (colorSet) { + for (boost::ptr_vector<ColorItem>::iterator it = colorSet->_colors.begin(); it != colorSet->_colors.end(); + ++it) { std::string::size_type pos = it->def.descr.find("*{"); - if ( pos != std::string::npos ) - { - std::string subby = it->def.descr.substr( pos + 2 ); + if (pos != std::string::npos) { + std::string subby = it->def.descr.substr(pos + 2); std::string::size_type endPos = subby.find("}*"); - if ( endPos != std::string::npos ) - { - subby.erase( endPos ); - //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str()); - //g_message(" '%s'", subby.c_str()); - - if ( subby.find('E') != std::string::npos ) - { - it->def.setEditable( true ); + if (endPos != std::string::npos) { + subby.erase(endPos); + // g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str()); + // g_message(" '%s'", subby.c_str()); + + if (subby.find('E') != std::string::npos) { + it->def.setEditable(true); } - if ( subby.find('L') != std::string::npos ) - { + if (subby.find('L') != std::string::npos) { it->_isLive = true; } std::string part; // Tint. index + 1 more val. - if ( getBlock( part, 'T', subby ) ) { + if (getBlock(part, 'T', subby)) { guint64 colorIndex = 0; - if ( popVal( colorIndex, part ) ) { + if (popVal(colorIndex, part)) { guint64 percent = 0; - if ( popVal( percent, part ) ) { - it->_linkTint( colorSet->_colors[colorIndex], percent ); + if (popVal(percent, part)) { + it->_linkTint(colorSet->_colors[colorIndex], percent); } } } // Shade/tone. index + 1 or 2 more val. - if ( getBlock( part, 'S', subby ) ) { + if (getBlock(part, 'S', subby)) { guint64 colorIndex = 0; - if ( popVal( colorIndex, part ) ) { + if (popVal(colorIndex, part)) { guint64 percent = 0; - if ( popVal( percent, part ) ) { + if (popVal(percent, part)) { guint64 grayLevel = 0; - if ( !popVal( grayLevel, part ) ) { + if (!popVal(grayLevel, part)) { grayLevel = 0; } - it->_linkTone( colorSet->_colors[colorIndex], percent, grayLevel ); + it->_linkTone(colorSet->_colors[colorIndex], percent, grayLevel); } } } - } } } } } - -void ColorItem::_linkTint( ColorItem& other, int percent ) +void ColorItem::_linkTint(ColorItem &other, int percent) { - if ( !_linkSrc ) - { + if (!_linkSrc) { other._listeners.push_back(this); _linkIsTone = false; _linkPercent = percent; - if ( _linkPercent > 100 ) + if (_linkPercent > 100) _linkPercent = 100; - if ( _linkPercent < 0 ) + if (_linkPercent < 0) _linkPercent = 0; _linkGray = 0; _linkSrc = &other; @@ -615,16 +575,15 @@ void ColorItem::_linkTint( ColorItem& other, int percent ) } } -void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel ) +void ColorItem::_linkTone(ColorItem &other, int percent, int grayLevel) { - if ( !_linkSrc ) - { + if (!_linkSrc) { other._listeners.push_back(this); _linkIsTone = true; _linkPercent = percent; - if ( _linkPercent > 100 ) + if (_linkPercent > 100) _linkPercent = 100; - if ( _linkPercent < 0 ) + if (_linkPercent < 0) _linkPercent = 0; _linkGray = grayLevel; _linkSrc = &other; diff --git a/src/ui/dialog/color-item.h b/src/ui/dialog/color-item.h index 7210ed2929185a4ec9cbe8e5b1fa0c9c78737a17..d4b3c4c967b78a303d1e48b25e7981484c2438c7 100644 --- a/src/ui/dialog/color-item.h +++ b/src/ui/dialog/color-item.h @@ -15,8 +15,8 @@ #include <boost/ptr_container/ptr_vector.hpp> -#include "widgets/ege-paint-def.h" #include "ui/previewable.h" +#include "widgets/ege-paint-def.h" class SPGradient; @@ -37,68 +37,56 @@ public: boost::ptr_vector<ColorItem> _colors; }; - /** * The color swatch you see on screen as a clickable box. */ class ColorItem : public Inkscape::UI::Previewable { - friend void _loadPaletteFile( gchar const *filename ); + friend void _loadPaletteFile(gchar const *filename); + public: - ColorItem( ege::PaintDef::ColorType type ); - ColorItem( unsigned int r, unsigned int g, unsigned int b, - Glib::ustring& name ); + ColorItem(ege::PaintDef::ColorType type); + ColorItem(unsigned int r, unsigned int g, unsigned int b, Glib::ustring &name); ~ColorItem() override; ColorItem(ColorItem const &other); virtual ColorItem &operator=(ColorItem const &other); - Gtk::Widget* getPreview(UI::Widget::PreviewStyle style, - UI::Widget::ViewType view, - UI::Widget::PreviewSize size, - guint ratio, - guint border) override; + Gtk::Widget *getPreview(UI::Widget::PreviewStyle style, UI::Widget::ViewType view, UI::Widget::PreviewSize size, + guint ratio, guint border) override; void buttonClicked(bool secondary = false); void setGradient(SPGradient *grad); - SPGradient * getGradient() const { return _grad; } + SPGradient *getGradient() const { return _grad; } void setPattern(cairo_pattern_t *pattern); void setName(const Glib::ustring name); - void setState( bool fill, bool stroke ); + void setState(bool fill, bool stroke); bool isFill() { return _isFill; } bool isStroke() { return _isStroke; } ege::PaintDef def; private: + static void _dropDataIn(GtkWidget *widget, GdkDragContext *drag_context, gint x, gint y, GtkSelectionData *data, + guint info, guint event_time, gpointer user_data); - static void _dropDataIn( GtkWidget *widget, - GdkDragContext *drag_context, - gint x, gint y, - GtkSelectionData *data, - guint info, - guint event_time, - gpointer user_data); - - void _dragGetColorData(const Glib::RefPtr<Gdk::DragContext> &drag_context, - Gtk::SelectionData &data, - guint info, - guint time); + void _dragGetColorData(const Glib::RefPtr<Gdk::DragContext> &drag_context, Gtk::SelectionData &data, guint info, + guint time); - static void _wireMagicColors( SwatchPage *colorSet ); - static void _colorDefChanged(void* data); + static void _wireMagicColors(SwatchPage *colorSet); + static void _colorDefChanged(void *data); void _updatePreviews(); - void _regenPreview(UI::Widget::Preview * preview); + void _regenPreview(UI::Widget::Preview *preview); - void _linkTint( ColorItem& other, int percent ); - void _linkTone( ColorItem& other, int percent, int grayLevel ); + void _linkTint(ColorItem &other, int percent); + void _linkTone(ColorItem &other, int percent, int grayLevel); void drag_begin(const Glib::RefPtr<Gdk::DragContext> &dc); void handleClick(); void handleSecondaryClick(gint arg1); - bool handleEnterNotify(GdkEventCrossing* event); - bool handleLeaveNotify(GdkEventCrossing* event); + bool handleEnterNotify(GdkEventCrossing *event); + bool handleLeaveNotify(GdkEventCrossing *event); - std::vector<Gtk::Widget*> _previews; + std::vector<Gtk::Widget *> _previews; bool _isFill; bool _isStroke; @@ -106,10 +94,10 @@ private: bool _linkIsTone; int _linkPercent; int _linkGray; - ColorItem* _linkSrc; - SPGradient* _grad; + ColorItem *_linkSrc; + SPGradient *_grad; cairo_pattern_t *_pattern; - std::vector<ColorItem*> _listeners; + std::vector<ColorItem *> _listeners; }; } // namespace Dialog diff --git a/src/ui/dialog/debug.cpp b/src/ui/dialog/debug.cpp index af2f08bdee56b2052485862a52b7531a0800d476..8c827e9a09426050d87cca92ab703801d9ba6607 100644 --- a/src/ui/dialog/debug.cpp +++ b/src/ui/dialog/debug.cpp @@ -11,14 +11,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "debug.h" + +#include <glibmm/i18n.h> #include <gtkmm/box.h> #include <gtkmm/dialog.h> -#include <gtkmm/textview.h> #include <gtkmm/menubar.h> #include <gtkmm/scrolledwindow.h> -#include <glibmm/i18n.h> - -#include "debug.h" +#include <gtkmm/textview.h> namespace Inkscape { namespace UI { @@ -27,7 +27,9 @@ namespace Dialog { /** * A very simple dialog for displaying Inkscape messages - implementation. */ -class DebugDialogImpl : public DebugDialog, public Gtk::Dialog +class DebugDialogImpl + : public DebugDialog + , public Gtk::Dialog { public: DebugDialogImpl(); @@ -42,11 +44,11 @@ public: private: Gtk::MenuBar menuBar; - Gtk::Menu fileMenu; + Gtk::Menu fileMenu; Gtk::ScrolledWindow textScroll; Gtk::TextView messageText; - //Handler ID's + // Handler ID's guint handlerDefault; guint handlerGlibmm; guint handlerAtkmm; @@ -68,7 +70,7 @@ DebugDialogImpl::DebugDialogImpl() auto mainVBox = get_content_area(); //## Add a menu for clear() - Gtk::MenuItem* item = Gtk::manage(new Gtk::MenuItem(_("_File"), true)); + Gtk::MenuItem *item = Gtk::manage(new Gtk::MenuItem(_("_File"), true)); item->set_submenu(fileMenu); menuBar.append(*item); @@ -79,13 +81,12 @@ DebugDialogImpl::DebugDialogImpl() 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); - //### Set up the text widget messageText.set_editable(false); @@ -100,28 +101,26 @@ DebugDialogImpl::DebugDialogImpl() message("dialogs.debug 'redirect' attribute to 1 in preferences.xml"); handlerDefault = 0; - handlerGlibmm = 0; - handlerAtkmm = 0; + handlerGlibmm = 0; + handlerAtkmm = 0; handlerPangomm = 0; - handlerGdkmm = 0; - handlerGtkmm = 0; + handlerGdkmm = 0; + handlerGtkmm = 0; } - DebugDialog *DebugDialog::create() { DebugDialog *dialog = new DebugDialogImpl(); return dialog; } -DebugDialogImpl::~DebugDialogImpl() -= default; +DebugDialogImpl::~DebugDialogImpl() = default; void DebugDialogImpl::show() { - //call super() + // call super() Gtk::Dialog::show(); - //sp_transientize(GTK_WIDGET(gobj())); //Make transient + // sp_transientize(GTK_WIDGET(gobj())); //Make transient raise(); Gtk::Dialog::present(); } @@ -136,9 +135,9 @@ void DebugDialogImpl::message(char const *msg) { Glib::RefPtr<Gtk::TextBuffer> buffer = messageText.get_buffer(); Glib::ustring uMsg = msg; - if (uMsg[uMsg.length()-1] != '\n') + if (uMsg[uMsg.length() - 1] != '\n') uMsg += '\n'; - buffer->insert (buffer->end(), uMsg); + buffer->insert(buffer->end(), uMsg); } /* static instance, to reduce dependencies */ @@ -152,100 +151,83 @@ DebugDialog *DebugDialog::getInstance() return debugDialogInstance; } - - void DebugDialog::showInstance() { DebugDialog *debugDialog = getInstance(); debugDialog->show(); - // this is not a real memleak because getInstance() only creates a debug dialog once, and returns that instance for all subsequent calls - // cppcheck-suppress memleak + // this is not a real memleak because getInstance() only creates a debug dialog once, and returns that instance for + // all subsequent calls cppcheck-suppress memleak } - - - /*##### THIS IS THE IMPORTANT PART ##### */ -static void dialogLoggingFunction(const gchar */*log_domain*/, - GLogLevelFlags /*log_level*/, - const gchar *messageText, +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); } - void DebugDialogImpl::captureLogMessages() { /* This might likely need more code, to capture Gtkmm and Glibmm warnings, or maybe just simply grab stdout/stderr */ - GLogLevelFlags flags = (GLogLevelFlags) (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | - G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE | - G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG); - if ( !handlerDefault ) { - handlerDefault = g_log_set_handler(nullptr, flags, - dialogLoggingFunction, (gpointer)this); + GLogLevelFlags flags = (GLogLevelFlags)(G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | + G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG); + if (!handlerDefault) { + handlerDefault = g_log_set_handler(nullptr, flags, dialogLoggingFunction, (gpointer)this); } - if ( !handlerGlibmm ) { - handlerGlibmm = g_log_set_handler("glibmm", flags, - dialogLoggingFunction, (gpointer)this); + if (!handlerGlibmm) { + handlerGlibmm = g_log_set_handler("glibmm", flags, dialogLoggingFunction, (gpointer)this); } - if ( !handlerAtkmm ) { - handlerAtkmm = g_log_set_handler("atkmm", flags, - dialogLoggingFunction, (gpointer)this); + if (!handlerAtkmm) { + handlerAtkmm = g_log_set_handler("atkmm", flags, dialogLoggingFunction, (gpointer)this); } - if ( !handlerPangomm ) { - handlerPangomm = g_log_set_handler("pangomm", flags, - dialogLoggingFunction, (gpointer)this); + if (!handlerPangomm) { + handlerPangomm = g_log_set_handler("pangomm", flags, dialogLoggingFunction, (gpointer)this); } - if ( !handlerGdkmm ) { - handlerGdkmm = g_log_set_handler("gdkmm", flags, - dialogLoggingFunction, (gpointer)this); + if (!handlerGdkmm) { + handlerGdkmm = g_log_set_handler("gdkmm", flags, dialogLoggingFunction, (gpointer)this); } - if ( !handlerGtkmm ) { - handlerGtkmm = g_log_set_handler("gtkmm", flags, - dialogLoggingFunction, (gpointer)this); + if (!handlerGtkmm) { + handlerGtkmm = g_log_set_handler("gtkmm", flags, dialogLoggingFunction, (gpointer)this); } message("log capture started"); } void DebugDialogImpl::releaseLogMessages() { - if ( handlerDefault ) { + if (handlerDefault) { g_log_remove_handler(nullptr, handlerDefault); handlerDefault = 0; } - if ( handlerGlibmm ) { + if (handlerGlibmm) { g_log_remove_handler("glibmm", handlerGlibmm); handlerGlibmm = 0; } - if ( handlerAtkmm ) { + if (handlerAtkmm) { g_log_remove_handler("atkmm", handlerAtkmm); handlerAtkmm = 0; } - if ( handlerPangomm ) { + if (handlerPangomm) { g_log_remove_handler("pangomm", handlerPangomm); handlerPangomm = 0; } - if ( handlerGdkmm ) { + if (handlerGdkmm) { g_log_remove_handler("gdkmm", handlerGdkmm); handlerGdkmm = 0; } - if ( handlerGtkmm ) { + if (handlerGtkmm) { g_log_remove_handler("gtkmm", handlerGtkmm); handlerGtkmm = 0; } message("log capture discontinued"); } - - -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/debug.h b/src/ui/dialog/debug.h index 4520c739fe1765f5e4355dc80e21d4e8878fd3a6..cb19ef0d78756f9a363df860a43eb94b9c84acd8 100644 --- a/src/ui/dialog/debug.h +++ b/src/ui/dialog/debug.h @@ -18,7 +18,6 @@ namespace Inkscape { namespace UI { namespace Dialog { - /** * @brief A very simple dialog for displaying Inkscape messages. * @@ -28,7 +27,8 @@ namespace Dialog { class DebugDialog { public: - DebugDialog() = default;; + DebugDialog() = default; + ; /** * Factory method */ @@ -37,8 +37,8 @@ public: /** * Destructor */ - virtual ~DebugDialog() = default;; - + virtual ~DebugDialog() = default; + ; /** * Show the dialog @@ -52,8 +52,8 @@ public: /** * @brief Clear all information from the dialog - * - * Also a public method. Remove all text from the dialog + * + * Also a public method. Remove all text from the dialog */ virtual void clear() = 0; @@ -73,8 +73,8 @@ public: virtual void releaseLogMessages() = 0; /** - * Factory method. Use this to create a new DebugDialog - */ + * Factory method. Use this to create a new DebugDialog + */ static DebugDialog *getInstance(); /** @@ -83,9 +83,9 @@ public: static void showInstance(); }; -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif /* __DEBUGDIALOG_H__ */ diff --git a/src/ui/dialog/dialog-manager.cpp b/src/ui/dialog/dialog-manager.cpp index bc66a316d4a00af27332146ad4b97cc047d47c8e..a392d8b37b357025da4452e12e20a50e3004a4da 100644 --- a/src/ui/dialog/dialog-manager.cpp +++ b/src/ui/dialog/dialog-manager.cpp @@ -25,22 +25,21 @@ #include "ui/dialog/filter-effects-dialog.h" #include "ui/dialog/find.h" #include "ui/dialog/glyphs.h" +#include "ui/dialog/icon-preview.h" #include "ui/dialog/inkscape-preferences.h" #include "ui/dialog/input.h" +#include "ui/dialog/layers.h" #include "ui/dialog/livepatheffect-editor.h" #include "ui/dialog/memory.h" #include "ui/dialog/messages.h" #include "ui/dialog/paint-servers.h" +#include "ui/dialog/panel-dialog.h" #include "ui/dialog/prototype.h" #include "ui/dialog/symbols.h" #include "ui/dialog/tile.h" -# include "ui/dialog/tracedialog.h" - +#include "ui/dialog/tracedialog.h" #include "ui/dialog/transformation.h" #include "ui/dialog/undo-history.h" -#include "ui/dialog/panel-dialog.h" -#include "ui/dialog/layers.h" -#include "ui/dialog/icon-preview.h" //#include "ui/dialog/print-colors-preview-dialog.h" #include "ui/dialog/clonetiler.h" #include "ui/dialog/export.h" @@ -50,7 +49,7 @@ #include "ui/dialog/selectorsdialog.h" #if WITH_GSPELL -# include "ui/dialog/spellcheck.h" +#include "ui/dialog/spellcheck.h" #endif #include "ui/dialog/styledialog.h" @@ -67,10 +66,13 @@ namespace { using namespace Behavior; template <typename T, typename B> -inline Dialog *create() { return PanelDialog<B>::template create<T>(); } - +inline Dialog *create() +{ + return PanelDialog<B>::template create<T>(); } +} // namespace + // static member variables DialogManager::DialogMap DialogManager::_app_dialog_map; unsigned DialogManager::_app_dialog_map_refcount = 0; @@ -95,8 +97,8 @@ unsigned DialogManager::_app_dialog_map_refcount = 0; * to these signals. * */ -DialogManager::DialogManager() { - +DialogManager::DialogManager() +{ using namespace Behavior; // increment reference count @@ -106,7 +108,7 @@ DialogManager::DialogManager() { int dialogs_type = prefs->getIntLimited("/options/dialogtype/value", DOCK, 0, 1); // The preferences dialog is broken, the DockBehavior code resizes it's floating window to the smallest size - registerFactory("InkscapePreferences", &create<InkscapePreferences, FloatingBehavior>); + registerFactory("InkscapePreferences", &create<InkscapePreferences, FloatingBehavior>); if (dialogs_type == FLOATING) { // clang-format off @@ -152,7 +154,6 @@ DialogManager::DialogManager() { // clang-format on } else { - // clang-format off registerFactory("Prototype", &create<Prototype, DockBehavior>); registerFactory("AlignAndDistribute", &create<AlignAndDistribute, DockBehavior>); @@ -196,14 +197,14 @@ DialogManager::DialogManager() { } } -DialogManager::~DialogManager() { +DialogManager::~DialogManager() +{ // destroy application level dialogs when the last dialog manager goes out of scope if (!--_app_dialog_map_refcount) { _app_dialog_map.clear(); } } - /** * Get a static singleton if we use floating dialogs, or NULL if we use dockable dialogs. */ @@ -227,8 +228,7 @@ DialogManager *DialogManager::getInstance() /** * Registers a dialog factory function used to create the named dialog. */ -void DialogManager::registerFactory(gchar const *name, - DialogManager::DialogFactory factory) +void DialogManager::registerFactory(gchar const *name, DialogManager::DialogFactory factory) { registerFactory(g_quark_from_string(name), factory); } @@ -236,8 +236,7 @@ void DialogManager::registerFactory(gchar const *name, /** * Registers a dialog factory function used to create the named dialog. */ -void DialogManager::registerFactory(GQuark name, - DialogManager::DialogFactory factory) +void DialogManager::registerFactory(GQuark name, DialogManager::DialogFactory factory) { _factory_map[name] = factory; } @@ -246,7 +245,8 @@ void DialogManager::registerFactory(GQuark name, * Fetches the named dialog, creating it if it has not already been * created (assuming a factory has been registered for it). */ -Dialog *DialogManager::getDialog(gchar const *name) { +Dialog *DialogManager::getDialog(gchar const *name) +{ return getDialog(g_quark_from_string(name)); } @@ -254,12 +254,13 @@ Dialog *DialogManager::getDialog(gchar const *name) { * Fetches the named dialog, creating it if it has not already been * created (assuming a factory has been registered for it). */ -Dialog *DialogManager::getDialog(GQuark name) { +Dialog *DialogManager::getDialog(GQuark name) +{ DialogMap::iterator dialog_found; dialog_found = _dialog_map.find(name); - Dialog *dialog=nullptr; - if ( dialog_found != _dialog_map.end() ) { + Dialog *dialog = nullptr; + if (dialog_found != _dialog_map.end()) { return dialog_found->second.get(); } else if ((dialog_found = _app_dialog_map.find(name)) != _app_dialog_map.end()) { return dialog_found->second.get(); @@ -267,7 +268,7 @@ Dialog *DialogManager::getDialog(GQuark name) { FactoryMap::iterator factory_found; factory_found = _factory_map.find(name); - if ( factory_found != _factory_map.end() ) { + if (factory_found != _factory_map.end()) { dialog = factory_found->second(); static GQuark InkscapePreferences_quark = g_quark_from_static_string("InkscapePreferences"); if (name == InkscapePreferences_quark) { @@ -284,16 +285,18 @@ Dialog *DialogManager::getDialog(GQuark name) { /** * Shows the named dialog, creating it if necessary. */ -void DialogManager::showDialog(gchar const *name, bool grabfocus) { +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, bool grabfocus) { +void DialogManager::showDialog(GQuark name, bool grabfocus) +{ Dialog *dialog = getDialog(name); - if ( dialog ) { + if (dialog) { if (grabfocus) { dialogs_unhide(); dialog->present(); @@ -303,38 +306,35 @@ void DialogManager::showDialog(GQuark name, bool grabfocus) { } } -void -DialogManager::dialogs_hide() +void DialogManager::dialogs_hide() { _dialogs_toggle = false; - for(auto &item : _dialog_map) { + for (auto &item : _dialog_map) { item.second->onHideF12(); } - for(auto &item : _app_dialog_map) { + for (auto &item : _app_dialog_map) { item.second->onHideF12(); } } -void -DialogManager::dialogs_unhide() +void DialogManager::dialogs_unhide() { _dialogs_toggle = true; - - for(auto &item : _dialog_map) { + + for (auto &item : _dialog_map) { item.second->onShowF12(); } - for(auto &item : _app_dialog_map) { + for (auto &item : _app_dialog_map) { item.second->onShowF12(); } } -void -DialogManager::dialogs_toggle() +void DialogManager::dialogs_toggle() { - if(_dialogs_toggle) { + if (_dialogs_toggle) { dialogs_hide(); } else { dialogs_unhide(); diff --git a/src/ui/dialog/dialog-manager.h b/src/ui/dialog/dialog-manager.h index e4a0c278175e64742e3404576a320f556ae594c1..09dc7738e8dbf56c28cfa79df8ac077b55fcb83b 100644 --- a/src/ui/dialog/dialog-manager.h +++ b/src/ui/dialog/dialog-manager.h @@ -15,14 +15,16 @@ #ifndef INKSCAPE_UI_DIALOG_MANAGER_H #define INKSCAPE_UI_DIALOG_MANAGER_H -#include "dialog.h" #include <map> +#include "dialog.h" + namespace Inkscape { namespace UI { namespace Dialog { -class DialogManager { +class DialogManager +{ public: typedef Dialog *(*DialogFactory)(); @@ -43,22 +45,22 @@ public: void registerFactory(gchar const *name, DialogFactory factory); void registerFactory(GQuark name, DialogFactory factory); - Dialog *getDialog(gchar const* dlgName); - Dialog *getDialog(GQuark dlgName); - void showDialog(gchar const *name, bool grabfocus=true); - void showDialog(GQuark name, bool grabfocus=true); + Dialog *getDialog(gchar const *dlgName); + Dialog *getDialog(GQuark dlgName); + void showDialog(gchar const *name, bool grabfocus = true); + void showDialog(GQuark name, bool grabfocus = true); - //functions for hiding and showing dialogs + // functions for hiding and showing dialogs void dialogs_hide(); void dialogs_unhide(); void dialogs_toggle(); protected: - DialogManager(DialogManager const &d); // no copy - DialogManager& operator=(DialogManager const &d); // no assign + DialogManager(DialogManager const &d); // no copy + DialogManager &operator=(DialogManager const &d); // no assign - FactoryMap _factory_map; //< factories to create dialogs - DialogMap _dialog_map; //< map of already created dialogs + FactoryMap _factory_map; //< factories to create dialogs + DialogMap _dialog_map; //< map of already created dialogs static DialogMap _app_dialog_map; //< map of application-level dialogs static unsigned _app_dialog_map_refcount; @@ -70,7 +72,7 @@ private: } // namespace UI } // namespace Inkscape -#endif //INKSCAPE_UI_DIALOG_MANAGER_H +#endif // INKSCAPE_UI_DIALOG_MANAGER_H /* Local Variables: diff --git a/src/ui/dialog/dialog.cpp b/src/ui/dialog/dialog.cpp index 2ca898ee2acbbcd2ea8d0a7925ff3a221f1bb101..7f8e1b7499dad8a4e26288326c826c24a59fb482 100644 --- a/src/ui/dialog/dialog.cpp +++ b/src/ui/dialog/dialog.cpp @@ -14,28 +14,23 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm/dialog.h> - #include <gdk/gdkkeysyms.h> - -#include "dialog-manager.h" - +#include <gtkmm/dialog.h> #include <utility> #include "desktop.h" +#include "dialog-manager.h" #include "inkscape.h" #include "shortcuts.h" -#include "verbs.h" - #include "ui/interface.h" #include "ui/monitor.h" #include "ui/tool/event-utils.h" #include "ui/tools/tool-base.h" #include "ui/widget/canvas.h" +#include "verbs.h" #define MIN_ONSCREEN_DISTANCE 50 - namespace Inkscape { namespace UI { namespace Dialog { @@ -70,20 +65,20 @@ bool Dialog::retransientize_suppress() Dialog::Dialog(Behavior::BehaviorFactory behavior_factory, const char *prefs_path, int verb_num, Glib::ustring apply_label) - : _user_hidden(false), - _hiddenF12(false), - _prefs_path(prefs_path), - _verb_num(verb_num), - _title(), - _apply_label(std::move(apply_label)), - _desktop(nullptr), - _is_active_desktop(true), - _behavior(nullptr) + : _user_hidden(false) + , _hiddenF12(false) + , _prefs_path(prefs_path) + , _verb_num(verb_num) + , _title() + , _apply_label(std::move(apply_label)) + , _desktop(nullptr) + , _is_active_desktop(true) + , _behavior(nullptr) { gchar title[500]; if (verb_num) { - sp_ui_dialog_title_string (Inkscape::Verb::get(verb_num), title); + sp_ui_dialog_title_string(Inkscape::Verb::get(verb_num), title); } _title = title; @@ -119,10 +114,8 @@ Dialog::~Dialog() _behavior = nullptr; } - //--------------------------------------------------------------------- - void Dialog::onDesktopActivated(SPDesktop *desktop) { _is_active_desktop = (desktop == _desktop); @@ -154,26 +147,79 @@ void Dialog::onShowF12() _hiddenF12 = false; } +inline Dialog::operator Gtk::Widget &() +{ + return *_behavior; +} +inline GtkWidget *Dialog::gobj() +{ + return _behavior->gobj(); +} +inline void Dialog::present() +{ + _behavior->present(); +} +inline Gtk::Box *Dialog::get_vbox() +{ + return _behavior->get_vbox(); +} +inline void Dialog::hide() +{ + _behavior->hide(); +} +inline void Dialog::show() +{ + _behavior->show(); +} +inline void Dialog::show_all_children() +{ + _behavior->show_all_children(); +} +inline void Dialog::set_size_request(int width, int height) +{ + _behavior->set_size_request(width, height); +} +inline void Dialog::size_request(Gtk::Requisition &requisition) +{ + _behavior->size_request(requisition); +} +inline void Dialog::get_position(int &x, int &y) +{ + _behavior->get_position(x, y); +} +inline void Dialog::get_size(int &width, int &height) +{ + _behavior->get_size(width, height); +} +inline void Dialog::resize(int width, int height) +{ + _behavior->resize(width, height); +} +inline void Dialog::move(int x, int y) +{ + _behavior->move(x, y); +} +inline void Dialog::set_position(Gtk::WindowPosition position) +{ + _behavior->set_position(position); +} +inline void Dialog::set_title(Glib::ustring title) +{ + _behavior->set_title(title); +} +inline void Dialog::set_sensitive(bool sensitive) +{ + _behavior->set_sensitive(sensitive); +} -inline Dialog::operator Gtk::Widget &() { return *_behavior; } -inline GtkWidget *Dialog::gobj() { return _behavior->gobj(); } -inline void Dialog::present() { _behavior->present(); } -inline Gtk::Box *Dialog::get_vbox() { return _behavior->get_vbox(); } -inline void Dialog::hide() { _behavior->hide(); } -inline void Dialog::show() { _behavior->show(); } -inline void Dialog::show_all_children() { _behavior->show_all_children(); } -inline void Dialog::set_size_request(int width, int height) { _behavior->set_size_request(width, height); } -inline void Dialog::size_request(Gtk::Requisition &requisition) { _behavior->size_request(requisition); } -inline void Dialog::get_position(int &x, int &y) { _behavior->get_position(x, y); } -inline void Dialog::get_size(int &width, int &height) { _behavior->get_size(width, height); } -inline void Dialog::resize(int width, int height) { _behavior->resize(width, height); } -inline void Dialog::move(int x, int y) { _behavior->move(x, y); } -inline void Dialog::set_position(Gtk::WindowPosition position) { _behavior->set_position(position); } -inline void Dialog::set_title(Glib::ustring title) { _behavior->set_title(title); } -inline void Dialog::set_sensitive(bool sensitive) { _behavior->set_sensitive(sensitive); } - -Glib::SignalProxy0<void> Dialog::signal_show() { return _behavior->signal_show(); } -Glib::SignalProxy0<void> Dialog::signal_hide() { return _behavior->signal_hide(); } +Glib::SignalProxy0<void> Dialog::signal_show() +{ + return _behavior->signal_show(); +} +Glib::SignalProxy0<void> Dialog::signal_hide() +{ + return _behavior->signal_hide(); +} void Dialog::read_geometry() { @@ -194,22 +240,21 @@ void Dialog::read_geometry() } Gdk::Rectangle monitor_geometry = Inkscape::UI::get_monitor_geometry_primary(); - auto const screen_width = monitor_geometry.get_width(); + auto const screen_width = monitor_geometry.get_width(); auto const screen_height = monitor_geometry.get_height(); // If there are stored values for where the dialog should be // located, then restore the dialog to that position. // also check if (x,y) is actually onscreen with the current screen dimensions - if ( (x >= 0) && (y >= 0) && (x < (screen_width-MIN_ONSCREEN_DISTANCE)) && (y < (screen_height-MIN_ONSCREEN_DISTANCE)) ) { + if ((x >= 0) && (y >= 0) && (x < (screen_width - MIN_ONSCREEN_DISTANCE)) && + (y < (screen_height - MIN_ONSCREEN_DISTANCE))) { move(x, y); } else { // ...otherwise just put it in the middle of the screen set_position(Gtk::WIN_POS_CENTER); } - } - void Dialog::save_geometry() { int y, x, w, h; @@ -219,23 +264,23 @@ void Dialog::save_geometry() // g_print ("write %d %d %d %d\n", x, y, w, h); - if (x<0) x=0; - if (y<0) y=0; + if (x < 0) + x = 0; + if (y < 0) + y = 0; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setInt(_prefs_path + "/x", x); prefs->setInt(_prefs_path + "/y", y); prefs->setInt(_prefs_path + "/w", w); prefs->setInt(_prefs_path + "/h", h); - } -void -Dialog::save_status(int visible, int state, int placement) +void Dialog::save_status(int visible, int state, int placement) { - // Only save dialog status for dialogs on the "last document" + // Only save dialog status for dialogs on the "last document" SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if (desktop != nullptr || !_is_active_desktop ) { + if (desktop != nullptr || !_is_active_desktop) { return; } @@ -247,7 +292,6 @@ Dialog::save_status(int visible, int state, int placement) } } - void Dialog::_handleResponse(int response_id) { switch (response_id) { @@ -258,7 +302,7 @@ void Dialog::_handleResponse(int response_id) } } -bool Dialog::_onDeleteEvent(GdkEventAny */*event*/) +bool Dialog::_onDeleteEvent(GdkEventAny * /*event*/) { save_geometry(); _user_hidden = true; @@ -272,7 +316,7 @@ bool Dialog::_onEvent(GdkEvent *event) switch (event->type) { case GDK_KEY_PRESS: { - switch (Inkscape::UI::Tools::get_latin_keyval (&event->key)) { + switch (Inkscape::UI::Tools::get_latin_keyval(&event->key)) { case GDK_KEY_Escape: { _defocus(); ret = true; @@ -292,8 +336,7 @@ bool Dialog::_onEvent(GdkEvent *event) } } } - default: - ; + default:; } return ret; @@ -302,7 +345,7 @@ bool Dialog::_onEvent(GdkEvent *event) bool Dialog::_onKeyPress(GdkEventKey *event) { unsigned int shortcut; - shortcut = sp_shortcut_get_for_event((GdkEventKey*)event); + shortcut = sp_shortcut_get_for_event((GdkEventKey *)event); return sp_shortcut_invoke(shortcut, SP_ACTIVE_DESKTOP); } @@ -333,8 +376,7 @@ void Dialog::_defocus() } } -Inkscape::Selection* -Dialog::_getSelection() +Inkscape::Selection *Dialog::_getSelection() { return SP_ACTIVE_DESKTOP->getSelection(); } diff --git a/src/ui/dialog/dialog.h b/src/ui/dialog/dialog.h index 7c0409e39c75149ebc42cd3b78ba6102fe0c1930..67af2ffa75b34da2b8e4fca1a5d07f46c3b200bd 100644 --- a/src/ui/dialog/dialog.h +++ b/src/ui/dialog/dialog.h @@ -29,13 +29,17 @@ namespace Inkscape { namespace UI { namespace Dialog { -enum BehaviorType { FLOATING, DOCK }; +enum BehaviorType +{ + FLOATING, + DOCK +}; void sp_dialog_shutdown(GObject *object, gpointer dlgPtr); /** * Base class for Inkscape dialogs. - * + * * UI::Dialog::Dialog is a base class for all dialogs in Inkscape. The * purpose of this class is to provide a unified place for ensuring * style and behavior. Specifically, this class provides functionality @@ -52,23 +56,22 @@ void sp_dialog_shutdown(GObject *object, gpointer dlgPtr); * @see UI::Dialog::DialogManager manages the dialogs within inkscape. * @see UI::Dialog::PanelDialog which links Panel and Dialog together in a dockable and floatable dialog. */ -class Dialog { - +class Dialog +{ public: - /** * Constructor. - * + * * @param behavior_factory floating or docked. * @param prefs_path characteristic path for loading/saving dialog position. * @param verb_num the dialog verb. */ - Dialog(Behavior::BehaviorFactory behavior_factory, const char *prefs_path = nullptr, - int verb_num = 0, Glib::ustring apply_label = ""); + Dialog(Behavior::BehaviorFactory behavior_factory, const char *prefs_path = nullptr, int verb_num = 0, + Glib::ustring apply_label = ""); virtual ~Dialog(); - virtual void onDesktopActivated(SPDesktop*); + virtual void onDesktopActivated(SPDesktop *); virtual void onShutdown(); /* Hide and show dialogs */ @@ -90,51 +93,51 @@ public: virtual void move(int x, int y); virtual void set_position(Gtk::WindowPosition position); virtual void set_title(Glib::ustring title); - virtual void set_sensitive(bool sensitive=true); + virtual void set_sensitive(bool sensitive = true); virtual Glib::SignalProxy0<void> signal_show(); virtual Glib::SignalProxy0<void> signal_hide(); - bool _user_hidden; // when it is closed by the user, to prevent repopping on f12 - bool _hiddenF12; + bool _user_hidden; // when it is closed by the user, to prevent repopping on f12 + bool _hiddenF12; /** * Read window position from preferences. */ - void read_geometry(); - + void read_geometry(); + /** * Save window position to preferences. */ - void save_geometry(); - void save_status(int visible, int state, int placement); + void save_geometry(); + void save_status(int visible, int state, int placement); - private: +private: // when true, do not retransientize (prevents races when switching new windows too fast) bool _retransientize_suppress = false; guint _retransientize_again_timeout = 0; static gboolean retransientize_again(gpointer); - public: +public: bool retransientize_suppress(); void retransientize_again_timeout_add(); protected: Glib::ustring const _prefs_path; - int _verb_num; - Glib::ustring _title; - Glib::ustring _apply_label; - SPDesktop * _desktop; - bool _is_active_desktop; + int _verb_num; + Glib::ustring _title; + Glib::ustring _apply_label; + SPDesktop *_desktop; + bool _is_active_desktop; + + virtual void _handleResponse(int response_id); - virtual void _handleResponse(int response_id); + virtual bool _onDeleteEvent(GdkEventAny *); + virtual bool _onEvent(GdkEvent *event); + virtual bool _onKeyPress(GdkEventKey *event); - virtual bool _onDeleteEvent (GdkEventAny*); - virtual bool _onEvent(GdkEvent *event); - virtual bool _onKeyPress(GdkEventKey *event); + virtual void _apply(); - virtual void _apply(); - /* Closes the dialog window. * * This code sends a delete_event to the dialog, @@ -142,10 +145,10 @@ protected: * dialog can do some housekeeping, such as remember * its position. */ - virtual void _close(); - virtual void _defocus(); + virtual void _close(); + virtual void _defocus(); - Inkscape::Selection* _getSelection(); + Inkscape::Selection *_getSelection(); #if 0 sigc::connection _desktop_activated_connection; @@ -155,16 +158,16 @@ protected: sigc::connection _change_theme_connection; #endif - protected: +protected: std::vector<sigc::connection> _connections; - private: - Behavior::Behavior* _behavior; +private: + Behavior::Behavior *_behavior; Dialog() = delete; // no constructor without params Dialog(Dialog const &d) = delete; // no copy - Dialog& operator=(Dialog const &d) = delete; // no assign + Dialog &operator=(Dialog const &d) = delete; // no assign friend class Behavior::FloatingBehavior; friend class Behavior::DockBehavior; @@ -175,9 +178,7 @@ void sp_add_top_window_classes(Gtk::Widget *widg); } // namespace UI } // namespace Inkscape - - -#endif //INKSCAPE_DIALOG_H +#endif // INKSCAPE_DIALOG_H /* Local Variables: diff --git a/src/ui/dialog/dock-behavior.cpp b/src/ui/dialog/dock-behavior.cpp index f3c5c8f81b3c1849d0202f510d79af70aedcc3ec..6a933089e7feaafac01f0b2ed46cb7e6e10f6732 100644 --- a/src/ui/dialog/dock-behavior.cpp +++ b/src/ui/dialog/dock-behavior.cpp @@ -12,74 +12,68 @@ */ #include "dock-behavior.h" -#include "inkscape.h" + #include "desktop.h" -#include "ui/widget/dock.h" -#include "verbs.h" #include "dialog.h" +#include "inkscape.h" #include "ui/dialog-events.h" +#include "ui/widget/dock.h" +#include "verbs.h" namespace Inkscape { namespace UI { namespace Dialog { namespace Behavior { - -DockBehavior::DockBehavior(Dialog &dialog) : - Behavior(dialog), - _dock_item(*SP_ACTIVE_DESKTOP->getDock(), - Inkscape::Verb::get(dialog._verb_num)->get_id(), dialog._title.c_str(), - (Inkscape::Verb::get(dialog._verb_num)->get_image() ? - Inkscape::Verb::get(dialog._verb_num)->get_image() : ""), - static_cast<Widget::DockItem::State>( - Inkscape::Preferences::get()->getInt(_dialog._prefs_path + "/state", - UI::Widget::DockItem::DOCKED_STATE)), - static_cast<GdlDockPlacement>( - Inkscape::Preferences::get()->getInt(_dialog._prefs_path + "/placement", - GDL_DOCK_TOP))) +DockBehavior::DockBehavior(Dialog &dialog) + : Behavior(dialog) + , _dock_item( + *SP_ACTIVE_DESKTOP->getDock(), Inkscape::Verb::get(dialog._verb_num)->get_id(), dialog._title.c_str(), + (Inkscape::Verb::get(dialog._verb_num)->get_image() ? Inkscape::Verb::get(dialog._verb_num)->get_image() + : ""), + static_cast<Widget::DockItem::State>( + Inkscape::Preferences::get()->getInt(_dialog._prefs_path + "/state", UI::Widget::DockItem::DOCKED_STATE)), + static_cast<GdlDockPlacement>( + Inkscape::Preferences::get()->getInt(_dialog._prefs_path + "/placement", GDL_DOCK_TOP))) { // Connect signals - _signal_hide_connection = signal_hide().connect(sigc::mem_fun(*this, &Inkscape::UI::Dialog::Behavior::DockBehavior::_onHide)); + _signal_hide_connection = + signal_hide().connect(sigc::mem_fun(*this, &Inkscape::UI::Dialog::Behavior::DockBehavior::_onHide)); _connections.emplace_back(_signal_hide_connection); _connections.emplace_back( signal_show().connect(sigc::mem_fun(*this, &Inkscape::UI::Dialog::Behavior::DockBehavior::_onShow))); } -DockBehavior::~DockBehavior() { +DockBehavior::~DockBehavior() +{ for (auto &conn : _connections) { conn.disconnect(); } } - -Behavior * -DockBehavior::create(Dialog &dialog) +Behavior *DockBehavior::create(Dialog &dialog) { return new DockBehavior(dialog); } - DockBehavior::operator Gtk::Widget &() { return _dock_item.getWidget(); } -GtkWidget * -DockBehavior::gobj() +GtkWidget *DockBehavior::gobj() { return _dock_item.gobj(); } -Gtk::VBox * -DockBehavior::get_vbox() +Gtk::VBox *DockBehavior::get_vbox() { return _dock_item.get_vbox(); } -void -DockBehavior::present() +void DockBehavior::present() { bool was_attached = _dock_item.isAttached(); @@ -89,70 +83,59 @@ DockBehavior::present() _dialog.read_geometry(); } -void -DockBehavior::hide() +void DockBehavior::hide() { _signal_hide_connection.block(); _dock_item.hide(); _signal_hide_connection.unblock(); } -void -DockBehavior::show() +void DockBehavior::show() { _dock_item.show(); } -void -DockBehavior::show_all_children() +void DockBehavior::show_all_children() { get_vbox()->show_all_children(); } -void -DockBehavior::get_position(int &x, int &y) +void DockBehavior::get_position(int &x, int &y) { _dock_item.get_position(x, y); } -void -DockBehavior::get_size(int &width, int &height) +void DockBehavior::get_size(int &width, int &height) { _dock_item.get_size(width, height); } -void -DockBehavior::resize(int width, int height) +void DockBehavior::resize(int width, int height) { _dock_item.resize(width, height); } -void -DockBehavior::move(int x, int y) +void DockBehavior::move(int x, int y) { _dock_item.move(x, y); } -void -DockBehavior::set_position(Gtk::WindowPosition position) +void DockBehavior::set_position(Gtk::WindowPosition position) { _dock_item.set_position(position); } -void -DockBehavior::set_size_request(int width, int height) +void DockBehavior::set_size_request(int width, int height) { _dock_item.set_size_request(width, height); } -void -DockBehavior::size_request(Gtk::Requisition &requisition) +void DockBehavior::size_request(Gtk::Requisition &requisition) { _dock_item.size_request(requisition); } -void -DockBehavior::set_title(Glib::ustring title) +void DockBehavior::set_title(Glib::ustring title) { _dock_item.set_title(title); } @@ -163,72 +146,70 @@ void DockBehavior::set_sensitive(bool sensitive) get_vbox()->set_sensitive(); } - -void -DockBehavior::_onHide() +void DockBehavior::_onHide() { _dialog.save_geometry(); _dialog._user_hidden = true; } -void -DockBehavior::_onShow() +void DockBehavior::_onShow() { _dialog._user_hidden = false; } -void -DockBehavior::_onStateChanged(Widget::DockItem::State /*prev_state*/, - Widget::DockItem::State new_state) +void DockBehavior::_onStateChanged(Widget::DockItem::State /*prev_state*/, Widget::DockItem::State new_state) { // TODO remove method g_assert_not_reached(); } -void -DockBehavior::onHideF12() +void DockBehavior::onHideF12() { _dialog.save_geometry(); hide(); } -void -DockBehavior::onShowF12() +void DockBehavior::onShowF12() { present(); } -void -DockBehavior::onShutdown() +void DockBehavior::onShutdown() { int visible = _dock_item.isIconified() || !_dialog._user_hidden; - int status = (_dock_item.getState() == Inkscape::UI::Widget::DockItem::UNATTACHED) ? _dock_item.getPrevState() : _dock_item.getState(); - _dialog.save_status( visible, status, _dock_item.getPlacement() ); -} - -void -DockBehavior::onDesktopActivated(SPDesktop *desktop) -{ + int status = (_dock_item.getState() == Inkscape::UI::Widget::DockItem::UNATTACHED) ? _dock_item.getPrevState() + : _dock_item.getState(); + _dialog.save_status(visible, status, _dock_item.getPlacement()); } +void DockBehavior::onDesktopActivated(SPDesktop *desktop) {} /* Signal wrappers */ -Glib::SignalProxy0<void> -DockBehavior::signal_show() { return _dock_item.signal_show(); } - -Glib::SignalProxy0<void> -DockBehavior::signal_hide() { return _dock_item.signal_hide(); } +Glib::SignalProxy0<void> DockBehavior::signal_show() +{ + return _dock_item.signal_show(); +} -Glib::SignalProxy1<bool, GdkEventAny *> -DockBehavior::signal_delete_event() { return _dock_item.signal_delete_event(); } +Glib::SignalProxy0<void> DockBehavior::signal_hide() +{ + return _dock_item.signal_hide(); +} -Glib::SignalProxy0<void> -DockBehavior::signal_drag_begin() { return _dock_item.signal_drag_begin(); } +Glib::SignalProxy1<bool, GdkEventAny *> DockBehavior::signal_delete_event() +{ + return _dock_item.signal_delete_event(); +} -Glib::SignalProxy1<void, bool> -DockBehavior::signal_drag_end() { return _dock_item.signal_drag_end(); } +Glib::SignalProxy0<void> DockBehavior::signal_drag_begin() +{ + return _dock_item.signal_drag_begin(); +} +Glib::SignalProxy1<void, bool> DockBehavior::signal_drag_end() +{ + return _dock_item.signal_drag_end(); +} } // namespace Behavior } // namespace Dialog diff --git a/src/ui/dialog/dock-behavior.h b/src/ui/dialog/dock-behavior.h index 1cabc21d5d9f4d0cec7d2ba63fdf0f59a710c64f..9ed54b48a9a209bee6bac0f38816c5bdb4260d9a 100644 --- a/src/ui/dialog/dock-behavior.h +++ b/src/ui/dialog/dock-behavior.h @@ -10,15 +10,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #ifndef INKSCAPE_UI_DIALOG_DOCK_BEHAVIOR_H #define INKSCAPE_UI_DIALOG_DOCK_BEHAVIOR_H -#include "ui/widget/dock-item.h" #include "behavior.h" +#include "ui/widget/dock-item.h" namespace Gtk { - class Paned; +class Paned; } namespace Inkscape { @@ -26,15 +25,15 @@ namespace UI { namespace Dialog { namespace Behavior { -class DockBehavior : public Behavior { - +class DockBehavior : public Behavior +{ public: - static Behavior *create(Dialog& dialog); + static Behavior *create(Dialog &dialog); ~DockBehavior() override; /** Gtk::Dialog methods */ - operator Gtk::Widget&() override; + operator Gtk::Widget &() override; GtkWidget *gobj() override; void present() override; Gtk::VBox *get_vbox() override; @@ -45,9 +44,9 @@ public: void move(int x, int y) override; void set_position(Gtk::WindowPosition) override; void set_size_request(int width, int height) override; - void size_request(Gtk::Requisition& requisition) override; - void get_position(int& x, int& y) override; - void get_size(int& width, int& height) override; + void size_request(Gtk::Requisition &requisition) override; + void get_position(int &x, int &y) override; + void get_size(int &width, int &height) override; void set_title(Glib::ustring title) override; void set_sensitive(bool sensitive) override; @@ -69,11 +68,11 @@ private: Widget::DockItem _dock_item; - DockBehavior(Dialog& dialog); + DockBehavior(Dialog &dialog); /** Internal helpers */ - Gtk::Paned *_getPaned(); //< gives the parent pane, if the dock item has one - void _requestHeight(int height); //< tries to resize the dock item to the requested height + Gtk::Paned *_getPaned(); //< gives the parent pane, if the dock item has one + void _requestHeight(int height); //< tries to resize the dock item to the requested height /** Internal signal handlers */ void _onHide(); @@ -84,7 +83,6 @@ private: sigc::connection _signal_hide_connection; sigc::connection _signal_key_press_event_connection; - }; } // namespace Behavior diff --git a/src/ui/dialog/document-properties.cpp b/src/ui/dialog/document-properties.cpp index 47af1e06ed6cd6ad4f6359b33b8e288bc49ec653..99be6c11726d57f142936c1cc48130f9a7c01f8c 100644 --- a/src/ui/dialog/document-properties.cpp +++ b/src/ui/dialog/document-properties.cpp @@ -20,13 +20,10 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include <vector> -#include "style.h" -#include "rdf.h" -#include "verbs.h" #include "display/canvas-grid.h" #include "document-properties.h" @@ -35,6 +32,8 @@ #include "io/sys.h" #include "object/sp-root.h" #include "object/sp-script.h" +#include "rdf.h" +#include "style.h" #include "ui/dialog/filedialog.h" #include "ui/icon-loader.h" #include "ui/icon-names.h" @@ -42,6 +41,7 @@ #include "ui/tools-switch.h" #include "ui/widget/entity-entry.h" #include "ui/widget/notebook-page.h" +#include "verbs.h" #include "xml/node-event-vector.h" #if defined(HAVE_LIBLCMS2) @@ -55,32 +55,32 @@ namespace Dialog { #define SPACE_SIZE_X 15 #define SPACE_SIZE_Y 10 - //=================================================== //--------------------------------------------------- -static void on_child_added(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, void * data); -static void on_child_removed(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, void * data); -static void on_repr_attr_changed (Inkscape::XML::Node *, gchar const *, gchar const *, gchar const *, bool, gpointer); +static void on_child_added(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, void *data); +static void on_child_removed(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, + void *data); +static void on_repr_attr_changed(Inkscape::XML::Node *, gchar const *, gchar const *, gchar const *, bool, gpointer); static Inkscape::XML::NodeEventVector const _repr_events = { - on_child_added, // child_added + on_child_added, // child_added on_child_removed, // child_removed on_repr_attr_changed, nullptr, // content_changed nullptr // order_changed }; -static void docprops_style_button(Gtk::Button& btn, char const* iconName) +static void docprops_style_button(Gtk::Button &btn, char const *iconName) { GtkWidget *child = sp_get_icon_image(iconName, GTK_ICON_SIZE_SMALL_TOOLBAR); - gtk_widget_show( child ); + gtk_widget_show(child); btn.add(*Gtk::manage(Glib::wrap(child))); btn.set_relief(Gtk::RELIEF_NONE); } -DocumentProperties& DocumentProperties::getInstance() +DocumentProperties &DocumentProperties::getInstance() { DocumentProperties &instance = *new DocumentProperties(); instance.init(); @@ -100,62 +100,78 @@ DocumentProperties::DocumentProperties() , _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, nullptr, nullptr, nullptr, "crispEdges") - , _rcb_checkerboard(_("Checkerboard background"), _("If set, use a colored checkerboard for the canvas background"), "inkscape:pagecheckerboard", _wr, false) + , _rcb_antialias(_("Use antialiasing"), _("If unset, no antialiasing will be done on the drawing"), + "shape-rendering", _wr, false, nullptr, nullptr, nullptr, "crispEdges") + , _rcb_checkerboard(_("Checkerboard background"), _("If set, use a colored checkerboard for the canvas background"), + "inkscape:pagecheckerboard", _wr, false) , _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 color:"), _("Background color"), _("Color of the canvas background. Note: opacity is ignored except when exporting to bitmap."), "pagecolor", "inkscape:pageopacity", _wr) - , _rcp_bord(_("Border _color:"), _("Page border color"), _("Color of the page border"), "bordercolor", "borderopacity", _wr) + , _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 color:"), _("Background color"), + _("Color of the canvas background. Note: opacity is ignored except 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(_("Display _units:"), "inkscape:document-units", _wr) , _page_sizer(_wr) //--------------------------------------------------------------- - //General snap options + // General snap options , _rcb_sgui(_("Show _guides"), _("Show or hide guides"), "showguides", _wr) , _rcb_lgui(_("Lock all guides"), _("Toggle lock of all guides in the document"), "inkscape:lockguides", _wr) , _rcp_gui(_("Guide co_lor:"), _("Guideline color"), _("Color of guidelines"), "guidecolor", "guideopacity", _wr) - , _rcp_hgui(_("_Highlight color:"), _("Highlighted guideline color"), _("Color of a guideline when it is under mouse"), "guidehicolor", "guidehiopacity", _wr) + , _rcp_hgui(_("_Highlight color:"), _("Highlighted guideline color"), + _("Color of a guideline when it is under mouse"), "guidehicolor", "guidehiopacity", _wr) , _create_guides_btn(_("Create guides around the page")) , _delete_guides_btn(_("Delete all guides")) //--------------------------------------------------------------- , _rsu_sno(_("Snap _distance"), _("Snap only when _closer than:"), _("Always snap"), - _("Snapping distance, in screen pixels, for snapping to objects"), _("Always snap to objects, regardless of their distance"), + _("Snapping distance, in screen pixels, for snapping to objects"), + _("Always snap to objects, regardless of their distance"), _("If set, objects only snap to another object when it's within the range specified below"), "objecttolerance", _wr) - //Options for snapping to grids + // Options for snapping to grids , _rsu_sn(_("Snap d_istance"), _("Snap only when c_loser than:"), _("Always snap"), - _("Snapping distance, in screen pixels, for snapping to grid"), _("Always snap to grids, regardless of the distance"), - _("If set, objects only snap to a grid line when it's within the range specified below"), - "gridtolerance", _wr) - //Options for snapping to guides + _("Snapping distance, in screen pixels, for snapping to grid"), + _("Always snap to grids, regardless of the distance"), + _("If set, objects only snap to a grid line when it's within the range specified below"), "gridtolerance", + _wr) + // Options for snapping to guides , _rsu_gusn(_("Snap dist_ance"), _("Snap only when close_r than:"), _("Always snap"), - _("Snapping distance, in screen pixels, for snapping to guides"), _("Always snap to guides, regardless of the distance"), - _("If set, objects only snap to a guide when it's within the range specified below"), - "guidetolerance", _wr) + _("Snapping distance, in screen pixels, for snapping to guides"), + _("Always snap to guides, regardless of the distance"), + _("If set, objects only snap to a guide when it's within the range specified below"), "guidetolerance", + _wr) //--------------------------------------------------------------- - , _rcb_snclp(_("Snap to clip paths"), _("When snapping to paths, then also try snapping to clip paths"), "inkscape:snap-path-clip", _wr) - , _rcb_snmsk(_("Snap to mask paths"), _("When snapping to paths, then also try snapping to mask paths"), "inkscape:snap-path-mask", _wr) - , _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) + , _rcb_snclp(_("Snap to clip paths"), _("When snapping to paths, then also try snapping to clip paths"), + "inkscape:snap-path-clip", _wr) + , _rcb_snmsk(_("Snap to mask paths"), _("When snapping to paths, then also try snapping to mask paths"), + "inkscape:snap-path-mask", _wr) + , _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) //--------------------------------------------------------------- , _grids_label_crea("", Gtk::ALIGN_START) , _grids_button_new(C_("Grid", "_New"), _("Create new grid.")) , _grids_button_remove(C_("Grid", "_Remove"), _("Remove selected grid.")) , _grids_label_def("", Gtk::ALIGN_START) { - _getContents()->set_spacing (4); + _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(_grids_vbox, _("Grids")); - _notebook.append_page(*_page_snap, _("Snap")); - _notebook.append_page(*_page_cms, _("Color")); + _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")); _notebook.append_page(*_page_scripting, _("Scripting")); _notebook.append_page(*_page_metadata1, _("Metadata")); _notebook.append_page(*_page_metadata2, _("License")); - _wr.setUpdating (true); + _wr.setUpdating(true); build_page(); build_guides(); build_gridspage(); @@ -165,7 +181,7 @@ DocumentProperties::DocumentProperties() #endif // defined(HAVE_LIBLCMS2) build_scripting(); build_metadata(); - _wr.setUpdating (false); + _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)); @@ -182,7 +198,7 @@ void DocumentProperties::init() DocumentProperties::~DocumentProperties() { - for (auto & it : _rdflist) + for (auto &it : _rdflist) delete it; } @@ -200,38 +216,38 @@ DocumentProperties::~DocumentProperties() void attach_all(Gtk::Grid &table, Gtk::Widget *const arr[], unsigned const n) { for (unsigned i = 0, r = 0; i < n; i += 2) { - if (arr[i] && arr[i+1]) { + if (arr[i] && arr[i + 1]) { arr[i]->set_hexpand(); - arr[i+1]->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], 0, r, 1, 1); - table.attach(*arr[i+1], 1, r, 1, 1); + arr[i + 1]->set_valign(Gtk::ALIGN_CENTER); + table.attach(*arr[i], 0, r, 1, 1); + table.attach(*arr[i + 1], 1, r, 1, 1); } else { - if (arr[i+1]) { + if (arr[i + 1]) { Gtk::AttachOptions yoptions = (Gtk::AttachOptions)0; - if (dynamic_cast<Inkscape::UI::Widget::PageSizer*>(arr[i+1])) { + 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; + yoptions = Gtk::FILL | Gtk::EXPAND; } - arr[i+1]->set_hexpand(); + arr[i + 1]->set_hexpand(); if (yoptions & Gtk::EXPAND) - arr[i+1]->set_vexpand(); + arr[i + 1]->set_vexpand(); else - arr[i+1]->set_valign(Gtk::ALIGN_CENTER); + arr[i + 1]->set_valign(Gtk::ALIGN_CENTER); - table.attach(*arr[i+1], 0, r, 2, 1); + table.attach(*arr[i + 1], 0, r, 2, 1); } else if (arr[i]) { - Gtk::Label& label = reinterpret_cast<Gtk::Label&>(*arr[i]); + Gtk::Label &label = reinterpret_cast<Gtk::Label &>(*arr[i]); label.set_hexpand(); label.set_halign(Gtk::ALIGN_START); label.set_valign(Gtk::ALIGN_CENTER); table.attach(label, 0, r, 2, 1); } else { - auto space = Gtk::manage (new Gtk::Box); - space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y); + auto space = Gtk::manage(new Gtk::Box); + space->set_size_request(SPACE_SIZE_X, SPACE_SIZE_Y); space->set_halign(Gtk::ALIGN_CENTER); space->set_valign(Gtk::ALIGN_CENTER); @@ -246,20 +262,20 @@ void DocumentProperties::build_page() { _page_page->show(); - Gtk::Label* label_gen = Gtk::manage (new Gtk::Label); - label_gen->set_markup (_("<b>General</b>")); + Gtk::Label *label_gen = Gtk::manage(new Gtk::Label); + label_gen->set_markup(_("<b>General</b>")); - Gtk::Label *label_for = Gtk::manage (new Gtk::Label); - label_for->set_markup (_("<b>Page Size</b>")); + Gtk::Label *label_for = Gtk::manage(new Gtk::Label); + label_for->set_markup(_("<b>Page Size</b>")); - Gtk::Label* label_bkg = Gtk::manage (new Gtk::Label); - label_bkg->set_markup (_("<b>Background</b>")); + Gtk::Label *label_bkg = Gtk::manage(new Gtk::Label); + label_bkg->set_markup(_("<b>Background</b>")); - Gtk::Label* label_bdr = Gtk::manage (new Gtk::Label); - label_bdr->set_markup (_("<b>Border</b>")); + Gtk::Label *label_bdr = Gtk::manage(new Gtk::Label); + label_bdr->set_markup(_("<b>Border</b>")); - Gtk::Label* label_dsp = Gtk::manage (new Gtk::Label); - label_dsp->set_markup (_("<b>Display</b>")); + Gtk::Label *label_dsp = Gtk::manage(new Gtk::Label); + label_dsp->set_markup(_("<b>Display</b>")); _page_sizer.init(); @@ -270,39 +286,36 @@ void DocumentProperties::build_page() _rcb_doc_props_right.set_row_spacing(4); _rcb_doc_props_right.set_column_spacing(4); - Gtk::Widget *const widget_array[] = - { - label_gen, nullptr, - nullptr, &_rum_deflt, - nullptr, nullptr, - label_for, nullptr, - nullptr, &_page_sizer, - nullptr, nullptr, - &_rcb_doc_props_left, &_rcb_doc_props_right, + Gtk::Widget *const widget_array[] = { + label_gen, + nullptr, + nullptr, + &_rum_deflt, + nullptr, + nullptr, + label_for, + nullptr, + nullptr, + &_page_sizer, + nullptr, + nullptr, + &_rcb_doc_props_left, + &_rcb_doc_props_right, }; attach_all(_page_page->table(), widget_array, G_N_ELEMENTS(widget_array)); - Gtk::Widget *const widget_array_left[] = - { - label_bkg, nullptr, - nullptr, &_rcb_checkerboard, - nullptr, &_rcp_bg, - label_dsp, nullptr, - nullptr, &_rcb_antialias, + Gtk::Widget *const widget_array_left[] = { + label_bkg, nullptr, nullptr, &_rcb_checkerboard, nullptr, &_rcp_bg, + label_dsp, nullptr, nullptr, &_rcb_antialias, }; attach_all(_rcb_doc_props_left, widget_array_left, G_N_ELEMENTS(widget_array_left)); - Gtk::Widget *const widget_array_right[] = - { - label_bdr, nullptr, - nullptr, &_rcb_canb, - nullptr, &_rcb_bord, - nullptr, &_rcb_shad, - nullptr, &_rcp_bord, + Gtk::Widget *const widget_array_right[] = { + label_bdr, nullptr, nullptr, &_rcb_canb, nullptr, &_rcb_bord, nullptr, &_rcb_shad, nullptr, &_rcp_bord, }; attach_all(_rcb_doc_props_right, widget_array_right, G_N_ELEMENTS(widget_array_right)); - std::list<Gtk::Widget*> _slaveList; + std::list<Gtk::Widget *> _slaveList; _slaveList.push_back(&_rcb_bord); _slaveList.push_back(&_rcb_shad); _slaveList.push_back(&_rcp_bord); @@ -313,8 +326,8 @@ void DocumentProperties::build_guides() { _page_guides->show(); - Gtk::Label *label_gui = Gtk::manage (new Gtk::Label); - label_gui->set_markup (_("<b>Guides</b>")); + Gtk::Label *label_gui = Gtk::manage(new Gtk::Label); + label_gui->set_markup(_("<b>Guides</b>")); _rum_deflt.set_margin_start(0); _rcp_bg.set_margin_start(0); @@ -330,14 +343,9 @@ void DocumentProperties::build_guides() inner->add(_rcp_gui); inner->add(_rcp_hgui); auto spacer = Gtk::manage(new Gtk::Label()); - Gtk::Widget *const widget_array[] = - { - label_gui, nullptr, - inner, spacer, - nullptr, nullptr, - nullptr, &_create_guides_btn, - nullptr, &_delete_guides_btn - }; + Gtk::Widget *const widget_array[] = { + label_gui, nullptr, inner, spacer, nullptr, nullptr, nullptr, &_create_guides_btn, nullptr, + &_delete_guides_btn}; attach_all(_page_guides->table(), widget_array, G_N_ELEMENTS(widget_array)); inner->set_hexpand(false); @@ -349,41 +357,29 @@ void DocumentProperties::build_snap() { _page_snap->show(); - Gtk::Label *label_o = Gtk::manage (new Gtk::Label); - label_o->set_markup (_("<b>Snap to objects</b>")); - Gtk::Label *label_gr = Gtk::manage (new Gtk::Label); - label_gr->set_markup (_("<b>Snap to grids</b>")); - Gtk::Label *label_gu = Gtk::manage (new Gtk::Label); - label_gu->set_markup (_("<b>Snap to guides</b>")); - Gtk::Label *label_m = Gtk::manage (new Gtk::Label); - label_m->set_markup (_("<b>Miscellaneous</b>")); + Gtk::Label *label_o = Gtk::manage(new Gtk::Label); + label_o->set_markup(_("<b>Snap to objects</b>")); + Gtk::Label *label_gr = Gtk::manage(new Gtk::Label); + label_gr->set_markup(_("<b>Snap to grids</b>")); + Gtk::Label *label_gu = Gtk::manage(new Gtk::Label); + label_gu->set_markup(_("<b>Snap to guides</b>")); + Gtk::Label *label_m = Gtk::manage(new Gtk::Label); + label_m->set_markup(_("<b>Miscellaneous</b>")); auto spacer = Gtk::manage(new Gtk::Label()); - Gtk::Widget *const array[] = - { - label_o, nullptr, - nullptr, _rsu_sno._vbox, - &_rcb_snclp, spacer, - nullptr, &_rcb_snmsk, - nullptr, nullptr, - label_gr, nullptr, - nullptr, _rsu_sn._vbox, - nullptr, nullptr, - label_gu, nullptr, - nullptr, _rsu_gusn._vbox, - nullptr, nullptr, - label_m, nullptr, - nullptr, &_rcb_perp, - nullptr, &_rcb_tang - }; + Gtk::Widget *const array[] = {label_o, nullptr, nullptr, _rsu_sno._vbox, &_rcb_snclp, spacer, + nullptr, &_rcb_snmsk, nullptr, nullptr, label_gr, nullptr, + nullptr, _rsu_sn._vbox, nullptr, nullptr, label_gu, nullptr, + nullptr, _rsu_gusn._vbox, nullptr, nullptr, label_m, nullptr, + nullptr, &_rcb_perp, nullptr, &_rcb_tang}; attach_all(_page_snap->table(), array, G_N_ELEMENTS(array)); - } +} void DocumentProperties::create_guides_around_page() { SPDesktop *dt = getDesktop(); - Verb *verb = Verb::get( SP_VERB_EDIT_GUIDES_AROUND_PAGE ); + Verb *verb = Verb::get(SP_VERB_EDIT_GUIDES_AROUND_PAGE); if (verb) { SPAction *action = verb->get_action(Inkscape::ActionContext(dt)); if (action) { @@ -395,7 +391,7 @@ void DocumentProperties::create_guides_around_page() void DocumentProperties::delete_all_guides() { SPDesktop *dt = getDesktop(); - Verb *verb = Verb::get( SP_VERB_EDIT_DELETE_ALL_GUIDES ); + Verb *verb = Verb::get(SP_VERB_EDIT_DELETE_ALL_GUIDES); if (verb) { SPAction *action = verb->get_action(Inkscape::ActionContext(dt)); if (action) { @@ -406,22 +402,22 @@ void DocumentProperties::delete_all_guides() #if defined(HAVE_LIBLCMS2) /// Populates the available color profiles combo box -void DocumentProperties::populate_available_profiles(){ +void DocumentProperties::populate_available_profiles() +{ _AvailableProfilesListStore->clear(); // Clear any existing items in the combo box // Iterate through the list of profiles and add the name to the combo box. bool home = true; // initial value doesn't matter, it's just to avoid a compiler warning bool first = true; - for (auto &profile: ColorProfile::getProfileFilesWithNames()) { + for (auto &profile : ColorProfile::getProfileFilesWithNames()) { Gtk::TreeModel::Row row; // add a separator between profiles from the user's home directory and system profiles - if (!first && profile.isInHome != home) - { - row = *(_AvailableProfilesListStore->append()); - row[_AvailableProfilesListColumns.fileColumn] = "<separator>"; - row[_AvailableProfilesListColumns.nameColumn] = "<separator>"; - row[_AvailableProfilesListColumns.separatorColumn] = true; + if (!first && profile.isInHome != home) { + row = *(_AvailableProfilesListStore->append()); + row[_AvailableProfilesListColumns.fileColumn] = "<separator>"; + row[_AvailableProfilesListColumns.nameColumn] = "<separator>"; + row[_AvailableProfilesListColumns.separatorColumn] = true; } home = profile.isInHome; first = false; @@ -441,25 +437,17 @@ void DocumentProperties::populate_available_profiles(){ * * @param str the string to clean up. */ -static void sanitizeName( Glib::ustring& str ) +static void sanitizeName(Glib::ustring &str) { if (str.size() > 0) { char val = str.at(0); - if (((val < 'A') || (val > 'Z')) - && ((val < 'a') || (val > 'z')) - && (val != '_') - && (val != ':')) { - str.insert(0, "_"); + if (((val < 'A') || (val > 'Z')) && ((val < 'a') || (val > 'z')) && (val != '_') && (val != ':')) { + str.insert(0, "_"); } for (Glib::ustring::size_type i = 1; i < str.size(); i++) { char val = str.at(i); - if (((val < 'A') || (val > 'Z')) - && ((val < 'a') || (val > 'z')) - && ((val < '0') || (val > '9')) - && (val != '_') - && (val != ':') - && (val != '-') - && (val != '.')) { + if (((val < 'A') || (val > 'Z')) && ((val < 'a') || (val > 'z')) && ((val < '0') || (val > '9')) && + (val != '_') && (val != ':') && (val != '-') && (val != '.')) { str.replace(i, 1, "-"); } } @@ -469,10 +457,10 @@ static void sanitizeName( Glib::ustring& str ) /// Links the selected color profile in the combo box to the document void DocumentProperties::linkSelectedProfile() { - //store this profile in the SVG document (create <color-profile> element in the XML) + // store this profile in the SVG document (create <color-profile> element in the XML) // TODO remove use of 'active' desktop SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if (!desktop){ + if (!desktop) { g_warning("No active desktop"); } else { // Find the index of the currently-selected row in the color profiles combobox @@ -487,22 +475,21 @@ void DocumentProperties::linkSelectedProfile() Glib::ustring file = (*iter)[_AvailableProfilesListColumns.fileColumn]; Glib::ustring name = (*iter)[_AvailableProfilesListColumns.nameColumn]; - std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList( "iccprofile" ); + std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList("iccprofile"); for (auto obj : current) { - Inkscape::ColorProfile* prof = reinterpret_cast<Inkscape::ColorProfile*>(obj); + Inkscape::ColorProfile *prof = reinterpret_cast<Inkscape::ColorProfile *>(obj); if (!strcmp(prof->href, file.c_str())) return; } Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); Inkscape::XML::Node *cprofRepr = xml_doc->createElement("svg:color-profile"); - gchar* tmp = g_strdup(name.c_str()); + gchar *tmp = g_strdup(name.c_str()); Glib::ustring nameStr = tmp ? tmp : "profile"; // TODO add some auto-numbering to avoid collisions sanitizeName(nameStr); cprofRepr->setAttribute("name", nameStr); cprofRepr->setAttribute("xlink:href", Glib::filename_to_uri(Glib::filename_from_utf8(file))); cprofRepr->setAttribute("id", file); - // Checks whether there is a defs element. Creates it when needed Inkscape::XML::Node *defsRepr = sp_repr_lookup_name(xml_doc, "svg:defs"); if (!defsRepr) { @@ -514,7 +501,7 @@ void DocumentProperties::linkSelectedProfile() defsRepr->addChild(cprofRepr, nullptr); // TODO check if this next line was sometimes needed. It being there caused an assertion. - //Inkscape::GC::release(defsRepr); + // Inkscape::GC::release(defsRepr); // inform the document, so we can undo DocumentUndo::done(desktop->doc(), SP_VERB_EDIT_LINK_COLOR_PROFILE, _("Link Color Profile")); @@ -523,87 +510,88 @@ void DocumentProperties::linkSelectedProfile() } } -struct _cmp { - bool operator()(const SPObject * const & a, const SPObject * const & b) - { - const Inkscape::ColorProfile &a_prof = reinterpret_cast<const Inkscape::ColorProfile &>(*a); - const Inkscape::ColorProfile &b_prof = reinterpret_cast<const Inkscape::ColorProfile &>(*b); - gchar *a_name_casefold = g_utf8_casefold(a_prof.name, -1 ); - gchar *b_name_casefold = g_utf8_casefold(b_prof.name, -1 ); - int result = g_strcmp0(a_name_casefold, b_name_casefold); - g_free(a_name_casefold); - g_free(b_name_casefold); - return result < 0; - } +struct _cmp +{ + bool operator()(const SPObject *const &a, const SPObject *const &b) + { + const Inkscape::ColorProfile &a_prof = reinterpret_cast<const Inkscape::ColorProfile &>(*a); + const Inkscape::ColorProfile &b_prof = reinterpret_cast<const Inkscape::ColorProfile &>(*b); + gchar *a_name_casefold = g_utf8_casefold(a_prof.name, -1); + gchar *b_name_casefold = g_utf8_casefold(b_prof.name, -1); + int result = g_strcmp0(a_name_casefold, b_name_casefold); + g_free(a_name_casefold); + g_free(b_name_casefold); + return result < 0; + } }; template <typename From, typename To> -struct static_caster { To * operator () (From * value) const { return static_cast<To *>(value); } }; +struct static_caster +{ + To *operator()(From *value) const { return static_cast<To *>(value); } +}; void DocumentProperties::populate_linked_profiles_box() { _LinkedProfilesListStore->clear(); - std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList( "iccprofile" ); - if (! current.empty()) { + std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList("iccprofile"); + if (!current.empty()) { _emb_profiles_observer.set((*(current.begin()))->parent); } std::set<Inkscape::ColorProfile *> _current; - std::transform(current.begin(), - current.end(), - std::inserter(_current, _current.begin()), + std::transform(current.begin(), current.end(), std::inserter(_current, _current.begin()), static_caster<SPObject, Inkscape::ColorProfile>()); - for (auto &profile: _current) { + for (auto &profile : _current) { Gtk::TreeModel::Row row = *(_LinkedProfilesListStore->append()); row[_LinkedProfilesListColumns.nameColumn] = profile->name; -// row[_LinkedProfilesListColumns.previewColumn] = "Color Preview"; + // row[_LinkedProfilesListColumns.previewColumn] = "Color Preview"; } } -void DocumentProperties::external_scripts_list_button_release(GdkEventButton* event) +void DocumentProperties::external_scripts_list_button_release(GdkEventButton *event) { - if((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { + if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { _ExternalScriptsContextMenu.popup_at_pointer(reinterpret_cast<GdkEvent *>(event)); } } -void DocumentProperties::embedded_scripts_list_button_release(GdkEventButton* event) +void DocumentProperties::embedded_scripts_list_button_release(GdkEventButton *event) { - if((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { + if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { _EmbeddedScriptsContextMenu.popup_at_pointer(reinterpret_cast<GdkEvent *>(event)); } } -void DocumentProperties::linked_profiles_list_button_release(GdkEventButton* event) +void DocumentProperties::linked_profiles_list_button_release(GdkEventButton *event) { - if((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { + if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { _EmbProfContextMenu.popup_at_pointer(reinterpret_cast<GdkEvent *>(event)); } } -void DocumentProperties::cms_create_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem) +void DocumentProperties::cms_create_popup_menu(Gtk::Widget &parent, sigc::slot<void> rem) { - Gtk::MenuItem* mi = Gtk::manage(new Gtk::MenuItem(_("_Remove"), true)); + Gtk::MenuItem *mi = Gtk::manage(new Gtk::MenuItem(_("_Remove"), true)); _EmbProfContextMenu.append(*mi); mi->signal_activate().connect(rem); mi->show(); _EmbProfContextMenu.accelerate(parent); } - -void DocumentProperties::external_create_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem) +void DocumentProperties::external_create_popup_menu(Gtk::Widget &parent, sigc::slot<void> rem) { - Gtk::MenuItem* mi = Gtk::manage(new Gtk::MenuItem(_("_Remove"), true)); + Gtk::MenuItem *mi = Gtk::manage(new Gtk::MenuItem(_("_Remove"), true)); _ExternalScriptsContextMenu.append(*mi); mi->signal_activate().connect(rem); mi->show(); _ExternalScriptsContextMenu.accelerate(parent); } -void DocumentProperties::embedded_create_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem) +void DocumentProperties::embedded_create_popup_menu(Gtk::Widget &parent, sigc::slot<void> rem) { - Gtk::MenuItem* mi = Gtk::manage(new Gtk::MenuItem(_("_Remove"), true)); + Gtk::MenuItem *mi = Gtk::manage(new Gtk::MenuItem(_("_Remove"), true)); _EmbeddedScriptsContextMenu.append(*mi); mi->signal_activate().connect(rem); mi->show(); @@ -614,26 +602,26 @@ void DocumentProperties::onColorProfileSelectRow() { Glib::RefPtr<Gtk::TreeSelection> sel = _LinkedProfilesList.get_selection(); if (sel) { - _unlink_btn.set_sensitive(sel->count_selected_rows () > 0); + _unlink_btn.set_sensitive(sel->count_selected_rows() > 0); } } - -void DocumentProperties::removeSelectedProfile(){ +void DocumentProperties::removeSelectedProfile() +{ Glib::ustring name; - if(_LinkedProfilesList.get_selection()) { + if (_LinkedProfilesList.get_selection()) { Gtk::TreeModel::iterator i = _LinkedProfilesList.get_selection()->get_selected(); - if(i){ + if (i) { name = (*i)[_LinkedProfilesListColumns.nameColumn]; } else { return; } } - std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList( "iccprofile" ); + std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList("iccprofile"); for (auto obj : current) { - Inkscape::ColorProfile* prof = reinterpret_cast<Inkscape::ColorProfile*>(obj); - if (!name.compare(prof->name)){ + Inkscape::ColorProfile *prof = reinterpret_cast<Inkscape::ColorProfile *>(obj); + if (!name.compare(prof->name)) { prof->deleteObject(true, false); DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_REMOVE_COLOR_PROFILE, _("Remove linked color profile")); break; // removing the color profile likely invalidates part of the traversed list, stop traversing here. @@ -644,7 +632,8 @@ void DocumentProperties::removeSelectedProfile(){ onColorProfileSelectRow(); } -bool DocumentProperties::_AvailableProfilesList_separator(const Glib::RefPtr<Gtk::TreeModel>& model, const Gtk::TreeModel::iterator& iter) +bool DocumentProperties::_AvailableProfilesList_separator(const Glib::RefPtr<Gtk::TreeModel> &model, + const Gtk::TreeModel::iterator &iter) { bool separator = (*iter)[_AvailableProfilesListColumns.separatorColumn]; return separator; @@ -653,10 +642,10 @@ bool DocumentProperties::_AvailableProfilesList_separator(const Glib::RefPtr<Gtk void DocumentProperties::build_cms() { _page_cms->show(); - Gtk::Label *label_link= Gtk::manage (new Gtk::Label("", Gtk::ALIGN_START)); - label_link->set_markup (_("<b>Linked Color Profiles:</b>")); - Gtk::Label *label_avail = Gtk::manage (new Gtk::Label("", Gtk::ALIGN_START)); - label_avail->set_markup (_("<b>Available Color Profiles:</b>")); + Gtk::Label *label_link = Gtk::manage(new Gtk::Label("", Gtk::ALIGN_START)); + label_link->set_markup(_("<b>Linked Color Profiles:</b>")); + Gtk::Label *label_avail = Gtk::manage(new Gtk::Label("", Gtk::ALIGN_START)); + label_avail->set_markup(_("<b>Available Color Profiles:</b>")); _link_btn.set_tooltip_text(_("Link Profile")); docprops_style_button(_link_btn, INKSCAPE_ICON("list-add")); @@ -679,7 +668,7 @@ void DocumentProperties::build_cms() row++; - Gtk::HBox* spacer = Gtk::manage(new Gtk::HBox()); + Gtk::HBox *spacer = Gtk::manage(new Gtk::HBox()); spacer->set_size_request(SPACE_SIZE_X, SPACE_SIZE_Y); spacer->set_hexpand(); @@ -713,7 +702,8 @@ void DocumentProperties::build_cms() _AvailableProfilesListStore = Gtk::ListStore::create(_AvailableProfilesListColumns); _AvailableProfilesList.set_model(_AvailableProfilesListStore); _AvailableProfilesList.pack_start(_AvailableProfilesListColumns.nameColumn); - _AvailableProfilesList.set_row_separator_func(sigc::mem_fun(*this, &DocumentProperties::_AvailableProfilesList_separator)); + _AvailableProfilesList.set_row_separator_func( + sigc::mem_fun(*this, &DocumentProperties::_AvailableProfilesList_separator)); populate_available_profiles(); @@ -721,9 +711,9 @@ void DocumentProperties::build_cms() _LinkedProfilesListStore = Gtk::ListStore::create(_LinkedProfilesListColumns); _LinkedProfilesList.set_model(_LinkedProfilesListStore); _LinkedProfilesList.append_column(_("Profile Name"), _LinkedProfilesListColumns.nameColumn); -// _LinkedProfilesList.append_column(_("Color Preview"), _LinkedProfilesListColumns.previewColumn); + // _LinkedProfilesList.append_column(_("Color Preview"), _LinkedProfilesListColumns.previewColumn); _LinkedProfilesList.set_headers_visible(false); -// TODO restore? _LinkedProfilesList.set_fixed_height_mode(true); + // TODO restore? _LinkedProfilesList.set_fixed_height_mode(true); populate_linked_profiles_box(); @@ -735,16 +725,19 @@ void DocumentProperties::build_cms() _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.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)); + _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)); - std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList( "defs" ); + std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList("defs"); if (!current.empty()) { _emb_profiles_observer.set((*(current.begin()))->parent); } - _emb_profiles_observer.signal_changed().connect(sigc::mem_fun(*this, &DocumentProperties::populate_linked_profiles_box)); + _emb_profiles_observer.signal_changed().connect( + sigc::mem_fun(*this, &DocumentProperties::populate_linked_profiles_box)); onColorProfileSelectRow(); } #endif // defined(HAVE_LIBLCMS2) @@ -752,7 +745,7 @@ void DocumentProperties::build_cms() void DocumentProperties::build_scripting() { _page_scripting->show(); - + _page_scripting->table().attach(_scripting_notebook, 0, 0, 1, 1); _scripting_notebook.append_page(*_page_external_scripts, _("External scripts")); @@ -760,8 +753,8 @@ void DocumentProperties::build_scripting() //# External scripts tab _page_external_scripts->show(); - Gtk::Label *label_external= Gtk::manage (new Gtk::Label("", Gtk::ALIGN_START)); - label_external->set_markup (_("<b>External script files:</b>")); + Gtk::Label *label_external = Gtk::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")); docprops_style_button(_external_add_btn, INKSCAPE_ICON("list-add")); @@ -784,7 +777,7 @@ void DocumentProperties::build_scripting() row++; - Gtk::HBox* spacer_external = Gtk::manage(new Gtk::HBox()); + Gtk::HBox *spacer_external = Gtk::manage(new Gtk::HBox()); spacer_external->set_size_request(SPACE_SIZE_X, SPACE_SIZE_Y); spacer_external->set_hexpand(); @@ -813,13 +806,12 @@ void DocumentProperties::build_scripting() _ExternalScriptsList.set_model(_ExternalScriptsListStore); _ExternalScriptsList.append_column(_("Filename"), _ExternalScriptsListColumns.filenameColumn); _ExternalScriptsList.set_headers_visible(true); -// TODO restore? _ExternalScriptsList.set_fixed_height_mode(true); - + // TODO restore? _ExternalScriptsList.set_fixed_height_mode(true); //# Embedded scripts tab _page_embedded_scripts->show(); - Gtk::Label *label_embedded= Gtk::manage (new Gtk::Label("", Gtk::ALIGN_START)); - label_embedded->set_markup (_("<b>Embedded script files:</b>")); + Gtk::Label *label_embedded = Gtk::manage(new Gtk::Label("", Gtk::ALIGN_START)); + label_embedded->set_markup(_("<b>Embedded script files:</b>")); _embed_new_btn.set_tooltip_text(_("New")); docprops_style_button(_embed_new_btn, INKSCAPE_ICON("list-add")); @@ -827,7 +819,7 @@ void DocumentProperties::build_scripting() _embed_remove_btn.set_tooltip_text(_("Remove")); docprops_style_button(_embed_remove_btn, INKSCAPE_ICON("list-remove")); - _embed_button_box.set_layout (Gtk::BUTTONBOX_START); + _embed_button_box.set_layout(Gtk::BUTTONBOX_START); _embed_button_box.add(_embed_new_btn); _embed_button_box.add(_embed_remove_btn); @@ -852,7 +844,7 @@ void DocumentProperties::build_scripting() row++; - Gtk::HBox* spacer_embedded = Gtk::manage(new Gtk::HBox()); + Gtk::HBox *spacer_embedded = Gtk::manage(new Gtk::HBox()); spacer_embedded->set_size_request(SPACE_SIZE_X, SPACE_SIZE_Y); spacer_embedded->set_hexpand(); spacer_embedded->set_valign(Gtk::ALIGN_CENTER); @@ -865,11 +857,11 @@ void DocumentProperties::build_scripting() _EmbeddedScriptsList.set_model(_EmbeddedScriptsListStore); _EmbeddedScriptsList.append_column(_("Script id"), _EmbeddedScriptsListColumns.idColumn); _EmbeddedScriptsList.set_headers_visible(true); -// TODO restore? _EmbeddedScriptsList.set_fixed_height_mode(true); + // TODO restore? _EmbeddedScriptsList.set_fixed_height_mode(true); //# Set up the Embedded Scripts content box - Gtk::Label *label_embedded_content= Gtk::manage (new Gtk::Label("", Gtk::ALIGN_START)); - label_embedded_content->set_markup (_("<b>Content:</b>")); + Gtk::Label *label_embedded_content = Gtk::manage(new Gtk::Label("", Gtk::ALIGN_START)); + label_embedded_content->set_markup(_("<b>Content:</b>")); label_embedded_content->set_hexpand(); label_embedded_content->set_halign(Gtk::ALIGN_START); @@ -887,12 +879,16 @@ void DocumentProperties::build_scripting() _EmbeddedContentScroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); _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) ); + _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) ); + _ExternalScriptsList.get_selection()->signal_changed().connect( + sigc::mem_fun(*this, &DocumentProperties::onExternalScriptSelectRow)); - _EmbeddedContent.get_buffer()->signal_changed().connect(sigc::mem_fun(*this, &DocumentProperties::editEmbeddedScript)); + _EmbeddedContent.get_buffer()->signal_changed().connect( + sigc::mem_fun(*this, &DocumentProperties::editEmbeddedScript)); populate_script_lists(); @@ -915,16 +911,18 @@ void DocumentProperties::build_scripting() _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)); + _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)); - _EmbeddedScriptsList.signal_button_release_event().connect_notify(sigc::mem_fun(*this, &DocumentProperties::embedded_scripts_list_button_release)); + _EmbeddedScriptsList.signal_button_release_event().connect_notify( + sigc::mem_fun(*this, &DocumentProperties::embedded_scripts_list_button_release)); embedded_create_popup_menu(_EmbeddedScriptsList, sigc::mem_fun(*this, &DocumentProperties::removeEmbeddedScript)); #endif // defined(HAVE_LIBLCMS2) -//TODO: review this observers code: - std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList( "script" ); - if (! current.empty()) { + // TODO: review this observers code: + std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList("script"); + if (!current.empty()) { _scripts_observer.set((*(current.begin()))->parent); } _scripts_observer.signal_changed().connect(sigc::mem_fun(*this, &DocumentProperties::populate_script_lists)); @@ -938,19 +936,19 @@ void DocumentProperties::build_metadata() _page_metadata1->show(); - Gtk::Label *label = Gtk::manage (new Gtk::Label); - label->set_markup (_("<b>Dublin Core Entities</b>")); + Gtk::Label *label = Gtk::manage(new Gtk::Label); + label->set_markup(_("<b>Dublin Core Entities</b>")); label->set_halign(Gtk::ALIGN_START); label->set_valign(Gtk::ALIGN_CENTER); - _page_metadata1->table().attach (*label, 0,0,2,1); + _page_metadata1->table().attach(*label, 0, 0, 2, 1); - /* add generic metadata entry areas */ - struct rdf_work_entity_t * entity; + /* 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); + if (entity->editable == RDF_EDIT_GENERIC) { + EntityEntry *w = EntityEntry::create(entity, _wr); + _rdflist.push_back(w); w->_label.set_halign(Gtk::ALIGN_START); w->_label.set_valign(Gtk::ALIGN_CENTER); @@ -962,12 +960,12 @@ void DocumentProperties::build_metadata() } } - Gtk::Button *button_save = Gtk::manage (new Gtk::Button(_("_Save as default"),true)); + Gtk::Button *button_save = Gtk::manage(new Gtk::Button(_("_Save as default"), true)); button_save->set_tooltip_text(_("Save this metadata as the default metadata")); - Gtk::Button *button_load = Gtk::manage (new Gtk::Button(_("Use _default"),true)); + Gtk::Button *button_load = Gtk::manage(new Gtk::Button(_("Use _default"), true)); button_load->set_tooltip_text(_("Use the previously saved default metadata here")); - auto box_buttons = Gtk::manage (new Gtk::ButtonBox); + auto box_buttons = Gtk::manage(new Gtk::ButtonBox); box_buttons->set_layout(Gtk::BUTTONBOX_END); box_buttons->set_spacing(4); @@ -981,36 +979,35 @@ void DocumentProperties::build_metadata() _page_metadata2->show(); row = 0; - Gtk::Label *llabel = Gtk::manage (new Gtk::Label); - llabel->set_markup (_("<b>License</b>")); + Gtk::Label *llabel = Gtk::manage(new Gtk::Label); + llabel->set_markup(_("<b>License</b>")); llabel->set_halign(Gtk::ALIGN_START); llabel->set_valign(Gtk::ALIGN_CENTER); _page_metadata2->table().attach(*llabel, 0, row, 2, 1); /* add license selector pull-down and URI */ ++row; - _licensor.init (_wr); + _licensor.init(_wr); _licensor.set_hexpand(); _licensor.set_valign(Gtk::ALIGN_CENTER); _page_metadata2->table().attach(_licensor, 0, row, 2, 1); } -void DocumentProperties::addExternalScript(){ - +void DocumentProperties::addExternalScript() +{ SPDesktop *desktop = SP_ACTIVE_DESKTOP; if (!desktop) { g_warning("No active desktop"); return; } - if (_script_entry.get_text().empty() ) { + 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->setAttributeOrRemoveIfEmpty("xlink:href", _script_entry.get_text()); @@ -1023,29 +1020,26 @@ void DocumentProperties::addExternalScript(){ populate_script_lists(); } - } -static Inkscape::UI::Dialog::FileOpenDialog * selectPrefsFileInstance = nullptr; - -void DocumentProperties::browseExternalScript() { +static Inkscape::UI::Dialog::FileOpenDialog *selectPrefsFileInstance = nullptr; +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; + 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))) + 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()) - { + if (open_path.empty()) { open_path = g_get_home_dir(); open_path.append(G_DIR_SEPARATOR_S); } @@ -1053,12 +1047,8 @@ void DocumentProperties::browseExternalScript() { //# 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 = Inkscape::UI::Dialog::FileOpenDialog::create( + *desktop->getToplevel(), open_path, Inkscape::UI::Dialog::CUSTOM_TYPE, _("Select a script to load")); selectPrefsFileInstance->addFilterMenu("Javascript Files", "*.js"); } @@ -1075,9 +1065,10 @@ void DocumentProperties::browseExternalScript() { _script_entry.set_text(fileName); } -void DocumentProperties::addEmbeddedScript(){ +void DocumentProperties::addEmbeddedScript() +{ SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if (!desktop){ + if (!desktop) { g_warning("No active desktop"); } else { Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); @@ -1092,31 +1083,32 @@ void DocumentProperties::addEmbeddedScript(){ } } -void DocumentProperties::removeExternalScript(){ +void DocumentProperties::removeExternalScript() +{ Glib::ustring name; - if(_ExternalScriptsList.get_selection()) { + if (_ExternalScriptsList.get_selection()) { Gtk::TreeModel::iterator i = _ExternalScriptsList.get_selection()->get_selected(); - if(i){ + if (i) { name = (*i)[_ExternalScriptsListColumns.filenameColumn]; } else { return; } } - std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList( "script" ); + std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList("script"); for (auto obj : current) { if (obj) { - SPScript* script = dynamic_cast<SPScript *>(obj); + SPScript *script = dynamic_cast<SPScript *>(obj); if (script && (name == script->xlinkhref)) { - - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. Inkscape::XML::Node *repr = obj->getRepr(); - if (repr){ + 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")); + DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_REMOVE_EXTERNAL_SCRIPT, + _("Remove external script")); } } } @@ -1125,23 +1117,24 @@ void DocumentProperties::removeExternalScript(){ populate_script_lists(); } -void DocumentProperties::removeEmbeddedScript(){ +void DocumentProperties::removeEmbeddedScript() +{ Glib::ustring id; - if(_EmbeddedScriptsList.get_selection()) { + if (_EmbeddedScriptsList.get_selection()) { Gtk::TreeModel::iterator i = _EmbeddedScriptsList.get_selection()->get_selected(); - if(i){ + if (i) { id = (*i)[_EmbeddedScriptsListColumns.idColumn]; } else { return; } } - SPObject* obj = SP_ACTIVE_DOCUMENT->getObjectById(id); + SPObject *obj = SP_ACTIVE_DOCUMENT->getObjectById(id); if (obj) { - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. Inkscape::XML::Node *repr = obj->getRepr(); - if (repr){ + if (repr) { sp_repr_unparent(repr); // inform the document, so we can undo @@ -1156,7 +1149,7 @@ void DocumentProperties::onExternalScriptSelectRow() { Glib::RefPtr<Gtk::TreeSelection> sel = _ExternalScriptsList.get_selection(); if (sel) { - _external_remove_btn.set_sensitive(sel->count_selected_rows () > 0); + _external_remove_btn.set_sensitive(sel->count_selected_rows() > 0); } } @@ -1164,39 +1157,42 @@ void DocumentProperties::onEmbeddedScriptSelectRow() { Glib::RefPtr<Gtk::TreeSelection> sel = _EmbeddedScriptsList.get_selection(); if (sel) { - _embed_remove_btn.set_sensitive(sel->count_selected_rows () > 0); + _embed_remove_btn.set_sensitive(sel->count_selected_rows() > 0); } } -void DocumentProperties::changeEmbeddedScript(){ +void DocumentProperties::changeEmbeddedScript() +{ Glib::ustring id; - if(_EmbeddedScriptsList.get_selection()) { + if (_EmbeddedScriptsList.get_selection()) { Gtk::TreeModel::iterator i = _EmbeddedScriptsList.get_selection()->get_selected(); - if(i){ + if (i) { id = (*i)[_EmbeddedScriptsListColumns.idColumn]; } else { return; } } - bool voidscript=true; - std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList( "script" ); + bool voidscript = true; + std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList("script"); for (auto obj : current) { - if (id == obj->getId()){ - int count = (int) obj->children.size(); - - if (count>1) - g_warning("TODO: Found a script element with multiple (%d) child nodes! We must implement support for that!", count); - - //XML Tree being used directly here while it shouldn't be. - SPObject* child = obj->firstChild(); - //TODO: shouldn't we get all children instead of simply the first child? - - if (child && child->getRepr()){ - const gchar* content = child->getRepr()->content(); - if (content){ - voidscript=false; + if (id == obj->getId()) { + int count = (int)obj->children.size(); + + if (count > 1) + g_warning( + "TODO: Found a script element with multiple (%d) child nodes! We must implement support for that!", + count); + + // XML Tree being used directly here while it shouldn't be. + SPObject *child = obj->firstChild(); + // TODO: shouldn't we get all children instead of simply the first child? + + if (child && child->getRepr()) { + const gchar *content = child->getRepr()->content(); + if (content) { + voidscript = false; _EmbeddedContent.get_buffer()->set_text(content); } } @@ -1207,12 +1203,13 @@ void DocumentProperties::changeEmbeddedScript(){ _EmbeddedContent.get_buffer()->set_text(""); } -void DocumentProperties::editEmbeddedScript(){ +void DocumentProperties::editEmbeddedScript() +{ Glib::ustring id; - if(_EmbeddedScriptsList.get_selection()) { + if (_EmbeddedScriptsList.get_selection()) { Gtk::TreeModel::iterator i = _EmbeddedScriptsList.get_selection()->get_selected(); - if(i){ + if (i) { id = (*i)[_EmbeddedScriptsListColumns.idColumn]; } else { return; @@ -1220,21 +1217,20 @@ void DocumentProperties::editEmbeddedScript(){ } Inkscape::XML::Document *xml_doc = SP_ACTIVE_DOCUMENT->getReprDoc(); - std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList( "script" ); + std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList("script"); for (auto obj : current) { - if (id == obj->getId()){ - - //XML Tree being used directly here while it shouldn't be. + if (id == obj->getId()) { + // XML Tree being used directly here while it shouldn't be. Inkscape::XML::Node *repr = obj->getRepr(); - if (repr){ - auto tmp = obj->children | boost::adaptors::transformed([](SPObject& o) { return &o; }); - std::vector<SPObject*> vec(tmp.begin(), tmp.end()); - for (auto &child: vec) { + if (repr) { + auto tmp = obj->children | boost::adaptors::transformed([](SPObject &o) { return &o; }); + std::vector<SPObject *> vec(tmp.begin(), tmp.end()); + for (auto &child : vec) { child->deleteObject(); } obj->appendChildRepr(xml_doc->createTextNode(_EmbeddedContent.get_buffer()->get_text().c_str())); - //TODO repr->set_content(_EmbeddedContent.get_buffer()->get_text()); + // TODO repr->set_content(_EmbeddedContent.get_buffer()->get_text()); // inform the document, so we can undo DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_EMBEDDED_SCRIPT, _("Edit embedded script")); @@ -1243,24 +1239,23 @@ void DocumentProperties::editEmbeddedScript(){ } } -void DocumentProperties::populate_script_lists(){ +void DocumentProperties::populate_script_lists() +{ _ExternalScriptsListStore->clear(); _EmbeddedScriptsListStore->clear(); - std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList( "script" ); + std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList("script"); if (!current.empty()) { SPObject *obj = *(current.begin()); g_assert(obj != nullptr); _scripts_observer.set(obj->parent); } for (auto obj : current) { - SPScript* script = dynamic_cast<SPScript *>(obj); + SPScript *script = dynamic_cast<SPScript *>(obj); g_assert(script != nullptr); - if (script->xlinkhref) - { + if (script->xlinkhref) { Gtk::TreeModel::Row row = *(_ExternalScriptsListStore->append()); row[_ExternalScriptsListColumns.filenameColumn] = script->xlinkhref; - } - else // Embedded scripts + } else // Embedded scripts { Gtk::TreeModel::Row row = *(_EmbeddedScriptsListStore->append()); row[_EmbeddedScriptsListColumns.idColumn] = obj->getId(); @@ -1269,8 +1264,8 @@ void DocumentProperties::populate_script_lists(){ } /** -* Called for _updating_ the dialog (e.g. when a new grid was manually added in XML) -*/ + * Called for _updating_ the dialog (e.g. when a new grid was manually added in XML) + */ void DocumentProperties::update_gridspage() { SPDesktop *dt = getDesktop(); @@ -1279,14 +1274,15 @@ void DocumentProperties::update_gridspage() int prev_page_count = _grids_notebook.get_n_pages(); int prev_page_pos = _grids_notebook.get_current_page(); - //remove all tabs + // remove all tabs while (_grids_notebook.get_n_pages() != 0) { _grids_notebook.remove_page(-1); // this also deletes the page. } - //add tabs - for(auto grid : nv->grids) { - if (!grid->repr->attribute("id")) continue; // update_gridspage is called again when "id" is added + // add tabs + for (auto grid : nv->grids) { + if (!grid->repr->attribute("id")) + continue; // update_gridspage is called again when "id" is added Glib::ustring name(grid->repr->attribute("id")); const char *icon = nullptr; switch (grid->getGridType()) { @@ -1334,11 +1330,11 @@ void DocumentProperties::build_gridspage() _grids_hbox_crea.pack_start(_grids_button_new, true, true); for (gint t = 0; t <= GRID_MAXTYPENR; t++) { - _grids_combo_gridtype.append( CanvasGrid::getName( (GridType) t ) ); + _grids_combo_gridtype.append(CanvasGrid::getName((GridType)t)); } - _grids_combo_gridtype.set_active_text( CanvasGrid::getName(GRID_RECTANGULAR) ); + _grids_combo_gridtype.set_active_text(CanvasGrid::getName(GRID_RECTANGULAR)); - _grids_space.set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y); + _grids_space.set_size_request(SPACE_SIZE_X, SPACE_SIZE_Y); _grids_vbox.set_border_width(4); _grids_vbox.set_spacing(4); @@ -1350,35 +1346,34 @@ void DocumentProperties::build_gridspage() _grids_vbox.pack_start(_grids_button_remove, false, false); } - - /** * Update dialog widgets from desktop. Also call updateWidget routines of the grids. */ void DocumentProperties::update() { - if (_wr.isUpdating()) return; + if (_wr.isUpdating()) + return; SPDesktop *dt = getDesktop(); SPNamedView *nv = dt->getNamedView(); - _wr.setUpdating (true); - set_sensitive (true); + _wr.setUpdating(true); + set_sensitive(true); //-----------------------------------------------------------page page - _rcb_checkerboard.setActive (nv->pagecheckerboard); - _rcp_bg.setRgba32 (nv->pagecolor); - _rcb_canb.setActive (nv->showborder); - _rcb_bord.setActive (nv->borderlayer == SP_BORDER_LAYER_TOP); - _rcp_bord.setRgba32 (nv->bordercolor); - _rcb_shad.setActive (nv->showpageshadow); + _rcb_checkerboard.setActive(nv->pagecheckerboard); + _rcp_bg.setRgba32(nv->pagecolor); + _rcb_canb.setActive(nv->showborder); + _rcb_bord.setActive(nv->borderlayer == SP_BORDER_LAYER_TOP); + _rcp_bord.setRgba32(nv->bordercolor); + _rcb_shad.setActive(nv->showpageshadow); 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->display_units) { - _rum_deflt.setUnit (nv->display_units->abbr); + _rum_deflt.setUnit(nv->display_units->abbr); } double doc_w = dt->getDocument()->getRoot()->width.value; @@ -1403,20 +1398,20 @@ void DocumentProperties::update() //-----------------------------------------------------------guide page - _rcb_sgui.setActive (nv->showguides); - _rcb_lgui.setActive (nv->lockguides); - _rcp_gui.setRgba32 (nv->guidecolor); - _rcp_hgui.setRgba32 (nv->guidehicolor); + _rcb_sgui.setActive(nv->showguides); + _rcb_lgui.setActive(nv->lockguides); + _rcp_gui.setRgba32(nv->guidecolor); + _rcp_hgui.setRgba32(nv->guidehicolor); //-----------------------------------------------------------snap page - _rsu_sno.setValue (nv->snap_manager.snapprefs.getObjectTolerance()); - _rsu_sn.setValue (nv->snap_manager.snapprefs.getGridTolerance()); - _rsu_gusn.setValue (nv->snap_manager.snapprefs.getGuideTolerance()); - _rcb_snclp.setActive (nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_CLIP)); - _rcb_snmsk.setActive (nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_MASK)); - _rcb_perp.setActive (nv->snap_manager.snapprefs.getSnapPerp()); - _rcb_tang.setActive (nv->snap_manager.snapprefs.getSnapTang()); + _rsu_sno.setValue(nv->snap_manager.snapprefs.getObjectTolerance()); + _rsu_sn.setValue(nv->snap_manager.snapprefs.getGridTolerance()); + _rsu_gusn.setValue(nv->snap_manager.snapprefs.getGuideTolerance()); + _rcb_snclp.setActive(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_CLIP)); + _rcb_snmsk.setActive(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_MASK)); + _rcb_perp.setActive(nv->snap_manager.snapprefs.getSnapPerp()); + _rcb_tang.setActive(nv->snap_manager.snapprefs.getSnapTang()); //-----------------------------------------------------------grids page @@ -1431,18 +1426,16 @@ void DocumentProperties::update() //-----------------------------------------------------------meta pages /* update the RDF entities */ - for (auto & it : _rdflist) - it->update (SP_ACTIVE_DOCUMENT); + for (auto &it : _rdflist) + it->update(SP_ACTIVE_DOCUMENT); - _licensor.update (SP_ACTIVE_DOCUMENT); + _licensor.update(SP_ACTIVE_DOCUMENT); - - _wr.setUpdating (false); + _wr.setUpdating(false); } // TODO: copied from fill-and-stroke.cpp factor out into new ui/widget file? -Gtk::HBox& -DocumentProperties::_createPageTabLabel(const Glib::ustring& label, const char *label_image) +Gtk::HBox &DocumentProperties::_createPageTabLabel(const Glib::ustring &label, const char *label_image) { Gtk::HBox *_tab_label_box = Gtk::manage(new Gtk::HBox(false, 0)); _tab_label_box->set_spacing(4); @@ -1459,10 +1452,9 @@ DocumentProperties::_createPageTabLabel(const Glib::ustring& label, const char * //-------------------------------------------------------------------- -void DocumentProperties::on_response (int id) +void DocumentProperties::on_response(int id) { - if (id == Gtk::RESPONSE_DELETE_EVENT || id == Gtk::RESPONSE_CLOSE) - { + if (id == Gtk::RESPONSE_DELETE_EVENT || id == Gtk::RESPONSE_CLOSE) { _rcp_bg.closeWindow(); _rcp_bord.closeWindow(); _rcp_gui.closeWindow(); @@ -1476,21 +1468,20 @@ void DocumentProperties::on_response (int id) void DocumentProperties::load_default_metadata() { /* Get the data RDF entities data from preferences*/ - for (auto & it : _rdflist) { - it->load_from_preferences (); + for (auto &it : _rdflist) { + it->load_from_preferences(); } } void DocumentProperties::save_default_metadata() { /* Save these RDF entities to preferences*/ - for (auto & it : _rdflist) { - it->save_to_preferences (SP_ACTIVE_DOCUMENT); - } + for (auto &it : _rdflist) { + it->save_to_preferences(SP_ACTIVE_DOCUMENT); + } } - -void DocumentProperties::_handleDocumentReplaced(SPDesktop* desktop, SPDocument *document) +void DocumentProperties::_handleDocumentReplaced(SPDesktop *desktop, SPDocument *document) { _repr_root = desktop->getNamedView()->getRepr(); _repr_root->addListener(&_repr_events, this); @@ -1522,30 +1513,30 @@ void DocumentProperties::setDesktop(SPDesktop *desktop) } } -static void on_child_added(Inkscape::XML::Node */*repr*/, Inkscape::XML::Node */*child*/, Inkscape::XML::Node */*ref*/, void *data) +static void on_child_added(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node * /*child*/, + Inkscape::XML::Node * /*ref*/, void *data) { if (DocumentProperties *dialog = static_cast<DocumentProperties *>(data)) dialog->update_gridspage(); } -static void on_child_removed(Inkscape::XML::Node */*repr*/, Inkscape::XML::Node */*child*/, Inkscape::XML::Node */*ref*/, void *data) +static void on_child_removed(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node * /*child*/, + Inkscape::XML::Node * /*ref*/, void *data) { if (DocumentProperties *dialog = static_cast<DocumentProperties *>(data)) dialog->update_gridspage(); } - - /** * Called when XML node attribute changed; updates dialog widgets. */ -static void on_repr_attr_changed(Inkscape::XML::Node *, gchar const *, gchar const *, gchar const *, bool, gpointer data) +static void on_repr_attr_changed(Inkscape::XML::Node *, gchar const *, gchar const *, gchar const *, bool, + gpointer data) { if (DocumentProperties *dialog = static_cast<DocumentProperties *>(data)) dialog->update(); } - /*######################################################################## # BUTTON CLICK HANDLERS (callbacks) ########################################################################*/ @@ -1563,22 +1554,22 @@ void DocumentProperties::onNewGrid() dt->showGrids(true); } - void DocumentProperties::onRemoveGrid() { gint pagenum = _grids_notebook.get_current_page(); if (pagenum == -1) // no pages - return; + return; SPDesktop *dt = getDesktop(); SPNamedView *nv = dt->getNamedView(); - Inkscape::CanvasGrid * found_grid = nullptr; - if( pagenum < (gint)nv->grids.size()) + Inkscape::CanvasGrid *found_grid = nullptr; + if (pagenum < (gint)nv->grids.size()) found_grid = nv->grids[pagenum]; if (found_grid) { // delete the grid that corresponds with the selected tab - // when the grid is deleted from SVG, the SPNamedview handler automatically deletes the object, so found_grid becomes an invalid pointer! + // when the grid is deleted from SVG, the SPNamedview handler automatically deletes the object, so found_grid + // becomes an invalid pointer! found_grid->repr->parent()->removeChild(found_grid->repr); DocumentUndo::done(dt->getDocument(), SP_VERB_DIALOG_NAMEDVIEW, _("Remove grid")); } @@ -1599,7 +1590,6 @@ void DocumentProperties::onDocUnitChange() return; } - Inkscape::XML::Node *repr = getDesktop()->getNamedView()->getRepr(); /*Inkscape::Util::Unit const *old_doc_unit = unit_table.getUnit("px"); if(repr->attribute("inkscape:document-units")) { @@ -1615,7 +1605,8 @@ void DocumentProperties::onDocUnitChange() _page_sizer.updateScaleUI(); // Disable changing of SVG Units. The intent here is to change the units in the UI, not the units in SVG. - // This code should be moved (and fixed) once we have an "SVG Units" setting that sets what units are used in SVG data. + // This code should be moved (and fixed) once we have an "SVG Units" setting that sets what units are used in SVG + // data. #if 0 // Set viewBox if (doc->getRoot()->viewBox_set) { diff --git a/src/ui/dialog/document-properties.h b/src/ui/dialog/document-properties.h index 99243af9ab778c5de7fc4c7311a6044afa38ab56..7d52c954314a533d884a26f445a7a51204effa03 100644 --- a/src/ui/dialog/document-properties.h +++ b/src/ui/dialog/document-properties.h @@ -16,117 +16,117 @@ #define INKSCAPE_UI_DIALOG_DOCUMENT_PREFERENCES_H #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include <cstddef> -#include <sigc++/sigc++.h> +#include <gtkmm/buttonbox.h> #include <gtkmm/comboboxtext.h> #include <gtkmm/liststore.h> #include <gtkmm/notebook.h> -#include <gtkmm/buttonbox.h> #include <gtkmm/textview.h> +#include <sigc++/sigc++.h> +#include "ui/widget/licensor.h" #include "ui/widget/page-sizer.h" +#include "ui/widget/panel.h" #include "ui/widget/registered-widget.h" #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 { +namespace XML { +class Node; +} +namespace UI { +namespace Widget { +class EntityEntry; +class NotebookPage; +} // namespace Widget +namespace Dialog { + +typedef std::list<UI::Widget::EntityEntry *> RDElist; + +class DocumentProperties : public UI::Widget::Panel +{ public: - void update(); + void update(); static DocumentProperties &getInstance(); static void destroy(); void setDesktop(SPDesktop *desktop) override; - void update_gridspage(); + void update_gridspage(); protected: - void build_page(); - void build_grid(); - void build_guides(); - void build_snap(); - void build_gridspage(); - - void create_guides_around_page(); - void delete_all_guides(); + void build_page(); + void build_grid(); + void build_guides(); + void build_snap(); + void build_gridspage(); + + void create_guides_around_page(); + void delete_all_guides(); #if defined(HAVE_LIBLCMS2) - void build_cms(); + void build_cms(); #endif // defined(HAVE_LIBLCMS2) - void build_scripting(); - void build_metadata(); - void init(); + void build_scripting(); + void build_metadata(); + void init(); - virtual void on_response (int); + virtual void on_response(int); #if defined(HAVE_LIBLCMS2) - void populate_available_profiles(); - 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); + void populate_available_profiles(); + 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_LIBLCMS2) - void external_scripts_list_button_release(GdkEventButton* event); - 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 external_scripts_list_button_release(GdkEventButton *event); + 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); Inkscape::XML::SignalObserver _emb_profiles_observer, _scripts_observer; - Gtk::Notebook _notebook; + 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_metadata1; - UI::Widget::NotebookPage *_page_metadata2; + UI::Widget::NotebookPage *_page_metadata1; + UI::Widget::NotebookPage *_page_metadata2; - Gtk::VBox _grids_vbox; + Gtk::VBox _grids_vbox; UI::Widget::Registry _wr; //--------------------------------------------------------------- - Gtk::Grid _rcb_doc_props_left; - Gtk::Grid _rcb_doc_props_right; + Gtk::Grid _rcb_doc_props_left; + Gtk::Grid _rcb_doc_props_right; UI::Widget::RegisteredCheckButton _rcb_antialias; UI::Widget::RegisteredCheckButton _rcb_checkerboard; UI::Widget::RegisteredCheckButton _rcb_canb; @@ -134,47 +134,55 @@ protected: UI::Widget::RegisteredCheckButton _rcb_shad; UI::Widget::RegisteredColorPicker _rcp_bg; UI::Widget::RegisteredColorPicker _rcp_bord; - UI::Widget::RegisteredUnitMenu _rum_deflt; - UI::Widget::PageSizer _page_sizer; + UI::Widget::RegisteredUnitMenu _rum_deflt; + UI::Widget::PageSizer _page_sizer; //--------------------------------------------------------------- UI::Widget::RegisteredCheckButton _rcb_sgui; UI::Widget::RegisteredCheckButton _rcb_lgui; UI::Widget::RegisteredColorPicker _rcp_gui; UI::Widget::RegisteredColorPicker _rcp_hgui; - Gtk::Button _create_guides_btn; - Gtk::Button _delete_guides_btn; + Gtk::Button _create_guides_btn; + Gtk::Button _delete_guides_btn; //--------------------------------------------------------------- - UI::Widget::ToleranceSlider _rsu_sno; - UI::Widget::ToleranceSlider _rsu_sn; - UI::Widget::ToleranceSlider _rsu_gusn; + UI::Widget::ToleranceSlider _rsu_sno; + UI::Widget::ToleranceSlider _rsu_sn; + UI::Widget::ToleranceSlider _rsu_gusn; UI::Widget::RegisteredCheckButton _rcb_snclp; UI::Widget::RegisteredCheckButton _rcb_snmsk; UI::Widget::RegisteredCheckButton _rcb_perp; UI::Widget::RegisteredCheckButton _rcb_tang; //--------------------------------------------------------------- - Gtk::Button _link_btn; - Gtk::Button _unlink_btn; + Gtk::Button _link_btn; + Gtk::Button _unlink_btn; class AvailableProfilesColumns : public Gtk::TreeModel::ColumnRecord + { + public: + AvailableProfilesColumns() { - public: - AvailableProfilesColumns() - { add(fileColumn); add(nameColumn); add(separatorColumn); } - Gtk::TreeModelColumn<Glib::ustring> fileColumn; - Gtk::TreeModelColumn<Glib::ustring> nameColumn; - Gtk::TreeModelColumn<bool> separatorColumn; - }; + add(fileColumn); + add(nameColumn); + add(separatorColumn); + } + Gtk::TreeModelColumn<Glib::ustring> fileColumn; + Gtk::TreeModelColumn<Glib::ustring> nameColumn; + Gtk::TreeModelColumn<bool> separatorColumn; + }; AvailableProfilesColumns _AvailableProfilesListColumns; Glib::RefPtr<Gtk::ListStore> _AvailableProfilesListStore; Gtk::ComboBox _AvailableProfilesList; - bool _AvailableProfilesList_separator(const Glib::RefPtr<Gtk::TreeModel>& model, const Gtk::TreeModel::iterator& iter); + bool _AvailableProfilesList_separator(const Glib::RefPtr<Gtk::TreeModel> &model, + const Gtk::TreeModel::iterator &iter); class LinkedProfilesColumns : public Gtk::TreeModel::ColumnRecord + { + public: + LinkedProfilesColumns() { - public: - LinkedProfilesColumns() - { add(nameColumn); add(previewColumn); } - Gtk::TreeModelColumn<Glib::ustring> nameColumn; - Gtk::TreeModelColumn<Glib::ustring> previewColumn; - }; + add(nameColumn); + add(previewColumn); + } + Gtk::TreeModelColumn<Glib::ustring> nameColumn; + Gtk::TreeModelColumn<Glib::ustring> previewColumn; + }; LinkedProfilesColumns _LinkedProfilesListColumns; Glib::RefPtr<Gtk::ListStore> _LinkedProfilesListStore; Gtk::TreeView _LinkedProfilesList; @@ -182,27 +190,25 @@ protected: Gtk::Menu _EmbProfContextMenu; //--------------------------------------------------------------- - Gtk::Button _external_add_btn; - Gtk::Button _external_remove_btn; - Gtk::Button _embed_new_btn; - Gtk::Button _embed_remove_btn; - Gtk::ButtonBox _embed_button_box; + Gtk::Button _external_add_btn; + Gtk::Button _external_remove_btn; + Gtk::Button _embed_new_btn; + Gtk::Button _embed_remove_btn; + Gtk::ButtonBox _embed_button_box; class ExternalScriptsColumns : public Gtk::TreeModel::ColumnRecord - { - public: - ExternalScriptsColumns() - { add(filenameColumn); } - Gtk::TreeModelColumn<Glib::ustring> filenameColumn; - }; + { + public: + ExternalScriptsColumns() { add(filenameColumn); } + Gtk::TreeModelColumn<Glib::ustring> filenameColumn; + }; ExternalScriptsColumns _ExternalScriptsListColumns; class EmbeddedScriptsColumns : public Gtk::TreeModel::ColumnRecord - { - public: - EmbeddedScriptsColumns() - { add(idColumn); } - Gtk::TreeModelColumn<Glib::ustring> idColumn; - }; + { + public: + EmbeddedScriptsColumns() { add(idColumn); } + Gtk::TreeModelColumn<Glib::ustring> idColumn; + }; EmbeddedScriptsColumns _EmbeddedScriptsListColumns; Glib::RefPtr<Gtk::ListStore> _ExternalScriptsListStore; Glib::RefPtr<Gtk::ListStore> _EmbeddedScriptsListStore; @@ -217,20 +223,20 @@ protected: Gtk::ScrolledWindow _EmbeddedContentScroller; //--------------------------------------------------------------- - Gtk::Notebook _grids_notebook; - Gtk::HBox _grids_hbox_crea; - Gtk::Label _grids_label_crea; - Gtk::Button _grids_button_new; - Gtk::Button _grids_button_remove; + Gtk::Notebook _grids_notebook; + Gtk::HBox _grids_hbox_crea; + Gtk::Label _grids_label_crea; + Gtk::Button _grids_button_new; + Gtk::Button _grids_button_remove; Gtk::ComboBoxText _grids_combo_gridtype; - Gtk::Label _grids_label_def; - Gtk::HBox _grids_space; + Gtk::Label _grids_label_def; + Gtk::HBox _grids_space; //--------------------------------------------------------------- RDElist _rdflist; UI::Widget::Licensor _licensor; - Gtk::HBox& _createPageTabLabel(const Glib::ustring& label, const char *label_image); + Gtk::HBox &_createPageTabLabel(const Glib::ustring &label, const char *label_image); private: DocumentProperties(); diff --git a/src/ui/dialog/export.cpp b/src/ui/dialog/export.cpp index f1ad19455ddc5e3c6e68435a50116c94ff7673ec..b3a20f635d5d75e9bfa42255641dc78c41343491 100644 --- a/src/ui/dialog/export.cpp +++ b/src/ui/dialog/export.cpp @@ -15,8 +15,10 @@ */ // This has to be included prior to anything that includes setjmp.h, it croaks otherwise -#include <png.h> - +#include <gdl/gdl-dock-item.h> +#include <glibmm/convert.h> +#include <glibmm/i18n.h> +#include <glibmm/miscutils.h> #include <gtkmm/box.h> #include <gtkmm/buttonbox.h> #include <gtkmm/dialog.h> @@ -25,47 +27,36 @@ #include <gtkmm/grid.h> #include <gtkmm/main.h> #include <gtkmm/spinbutton.h> - -#include <glibmm/convert.h> -#include <glibmm/miscutils.h> -#include <glibmm/i18n.h> - -#include <gdl/gdl-dock-item.h> +#include <png.h> #include "document-undo.h" #include "document.h" #include "file.h" -#include "inkscape.h" #include "inkscape-window.h" +#include "inkscape.h" #include "preferences.h" #include "selection-chemistry.h" #include "verbs.h" // required to set status message after export #include "desktop.h" -#include "message-stack.h" - +#include "extension/db.h" +#include "extension/output.h" #include "helper/png-write.h" - #include "io/resource.h" #include "io/sys.h" - +#include "message-stack.h" #include "object/sp-namedview.h" #include "object/sp-root.h" - #include "ui/dialog-events.h" #include "ui/interface.h" #include "ui/widget/unit-menu.h" -#include "extension/db.h" -#include "extension/output.h" - - #ifdef _WIN32 -#include <windows.h> #include <commdlg.h> #include <gdk/gdkwin32.h> #include <glibmm/fileutils.h> +#include <windows.h> #endif #define SP_EXPORT_MIN_SIZE 1.0 @@ -83,11 +74,10 @@ namespace { class MessageCleaner { public: - MessageCleaner(Inkscape::MessageId messageId, SPDesktop *desktop) : - _desktop(desktop), - _messageId(messageId) - { - } + MessageCleaner(Inkscape::MessageId messageId, SPDesktop *desktop) + : _desktop(desktop) + , _messageId(messageId) + {} ~MessageCleaner() { @@ -110,92 +100,93 @@ namespace Inkscape { namespace UI { namespace Dialog { -class ExportProgressDialog : public Gtk::Dialog { - private: - Gtk::ProgressBar *_progress = nullptr; - Export *_export_panel = nullptr; - int _current = 0; - int _total = 0; +class ExportProgressDialog : public Gtk::Dialog +{ +private: + Gtk::ProgressBar *_progress = nullptr; + Export *_export_panel = nullptr; + int _current = 0; + int _total = 0; - public: - ExportProgressDialog(const Glib::ustring &title, bool modal = false) - : Gtk::Dialog(title, modal) - {} +public: + ExportProgressDialog(const Glib::ustring &title, bool modal = false) + : Gtk::Dialog(title, modal) + {} - inline void set_export_panel(const decltype(_export_panel) export_panel) { _export_panel = export_panel; } - inline decltype(_export_panel) get_export_panel() const { return _export_panel; } + inline void set_export_panel(const decltype(_export_panel) export_panel) { _export_panel = export_panel; } + inline decltype(_export_panel) get_export_panel() const { return _export_panel; } - inline void set_progress(const decltype(_progress) progress) { _progress = progress; } - inline decltype(_progress) get_progress() const { return _progress; } + inline void set_progress(const decltype(_progress) progress) { _progress = progress; } + inline decltype(_progress) get_progress() const { return _progress; } - inline void set_current(const int current) { _current = current; } - inline int get_current() const { return _current; } + inline void set_current(const int current) { _current = current; } + inline int get_current() const { return _current; } - inline void set_total(const int total) { _total = total; } - inline int get_total() const { return _total; } + inline void set_total(const int total) { _total = total; } + inline int get_total() const { return _total; } }; static std::string create_filepath_from_id(Glib::ustring, const Glib::ustring &); /** 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" -}; +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 () : - UI::Widget::Panel("/dialogs/export/", SP_VERB_DIALOG_EXPORT), - current_key(SELECTION_PAGE), - manual_key(SELECTION_PAGE), - original_name(), - doc_export_name(), - filename_modified(false), - update(false), - togglebox(true, 0), - area_box(false, 3), - singleexport_box(false, 0), - size_box(false, 3), - file_box(false, 3), - unitbox(false, 0), - unit_selector(), - units_label(_("Units:")), - filename_box(false, 5), - browse_label(_("_Export As..."), true), - browse_image(), - batch_box(false, 5), - batch_export(_("B_atch export all selected objects")), - interlacing(_("Use interlacing")), - bitdepth_label(_("Bit depth")), - bitdepth_cb(), - zlib_label(_("Compression")), - zlib_compression(), - pHYs_label(_("pHYs dpi")), - pHYs_sb(pHYs_adj, 1.0, 2), - antialiasing_label(_("Antialiasing")), - antialiasing_cb(), - hide_box(false, 3), - hide_export(_("Hide all except selected")), - closeWhenDone(_("Close when complete")), - button_box(false, 3), - _prog(), - prog_dlg(nullptr), - interrupted(false), - prefs(nullptr), - selectChangedConn(), - subselChangedConn(), - selectModifiedConn() +static const char *selection_labels[SELECTION_NUMBER_OF] = {N_("_Page"), N_("_Drawing"), N_("_Selection"), + N_("_Custom")}; + +Export::Export() + : UI::Widget::Panel("/dialogs/export/", SP_VERB_DIALOG_EXPORT) + , current_key(SELECTION_PAGE) + , manual_key(SELECTION_PAGE) + , original_name() + , doc_export_name() + , filename_modified(false) + , update(false) + , togglebox(true, 0) + , area_box(false, 3) + , singleexport_box(false, 0) + , size_box(false, 3) + , file_box(false, 3) + , unitbox(false, 0) + , unit_selector() + , units_label(_("Units:")) + , filename_box(false, 5) + , browse_label(_("_Export As..."), true) + , browse_image() + , batch_box(false, 5) + , batch_export(_("B_atch export all selected objects")) + , interlacing(_("Use interlacing")) + , bitdepth_label(_("Bit depth")) + , bitdepth_cb() + , zlib_label(_("Compression")) + , zlib_compression() + , pHYs_label(_("pHYs dpi")) + , pHYs_sb(pHYs_adj, 1.0, 2) + , antialiasing_label(_("Antialiasing")) + , antialiasing_cb() + , hide_box(false, 3) + , hide_export(_("Hide all except selected")) + , closeWhenDone(_("Close when complete")) + , button_box(false, 3) + , _prog() + , prog_dlg(nullptr) + , interrupted(false) + , prefs(nullptr) + , selectChangedConn() + , subselChangedConn() + , selectModifiedConn() { batch_export.set_use_underline(); - batch_export.set_tooltip_text(_("Export each selected object into its own PNG file, using export hints if any (caution, overwrites without asking!)")); + batch_export.set_tooltip_text(_("Export each selected object into its own PNG file, using export hints if any " + "(caution, overwrites without asking!)")); hide_export.set_use_underline(); hide_export.set_tooltip_text(_("In the exported image, hide all objects except those that are selected")); interlacing.set_use_underline(); - interlacing.set_tooltip_text(_("Enables ADAM7 interlacing for PNG output. This results in slightly larger image files, but big images can already be displayed (slightly blurry) while still loading.")); + interlacing.set_tooltip_text( + _("Enables ADAM7 interlacing for PNG output. This results in slightly larger image files, but big images can " + "already be displayed (slightly blurry) while still loading.")); closeWhenDone.set_use_underline(); closeWhenDone.set_tooltip_text(_("Once the export completes, close this dialog")); prefs = Inkscape::Preferences::get(); @@ -204,7 +195,7 @@ Export::Export () : /* Export area frame */ { - Gtk::Label* lbl = new Gtk::Label(_("<b>Export area</b>"), Gtk::ALIGN_START); + Gtk::Label *lbl = new Gtk::Label(_("<b>Export area</b>"), Gtk::ALIGN_START); lbl->set_use_markup(true); area_box.pack_start(*lbl); @@ -236,29 +227,23 @@ Export::Export () : t->set_row_spacing(4); t->set_column_spacing(4); - x0_adj = createSpinbutton ( "x0", 0.0, -1000000.0, 1000000.0, 0.1, 1.0, - 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, - t, 0, 1, _("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, - t, 0, 2, _("Wid_th:"), "", EXPORT_COORD_PRECISION, 1, - &Export::onAreaWidthChange); + width_adj = createSpinbutton("width", 0.0, 0.0, PNG_UINT_31_MAX, 0.1, 1.0, 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, - t, 2, 0, _("_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, - 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, - t, 2, 2, _("Hei_ght:"), "", EXPORT_COORD_PRECISION, 1, - &Export::onAreaHeightChange); + height_adj = createSpinbutton("height", 0.0, 0.0, PNG_UINT_31_MAX, 0.1, 1.0, 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); @@ -282,28 +267,20 @@ Export::Export () : size_box.pack_start(*t); - bmwidth_adj = createSpinbutton ( "bmwidth", 16.0, 1.0, 1000000.0, 1.0, 10.0, - t, 0, 0, - _("_Width:"), _("pixels at"), 0, 1, - &Export::onBitmapWidthChange); + bmwidth_adj = createSpinbutton("bmwidth", 16.0, 1.0, 1000000.0, 1.0, 10.0, 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, t, 3, 0, - "", _("dp_i"), 2, 1, - &Export::onExportXdpiChange); + xdpi_adj = createSpinbutton("xdpi", 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, - t, 0, 1, - _("_Height:"), _("pixels at"), 0, 1, - &Export::onBitmapHeightChange); + bmheight_adj = createSpinbutton("bmheight", 16.0, 1.0, 1000000.0, 1.0, 10.0, 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, t, 3, 1, - "", _("dpi"), 2, 0, nullptr ); + ydpi_adj = createSpinbutton("ydpi", prefs->getDouble("/dialogs/export/defaultxdpi/value", DPI_BASE), 0.01, + 100000.0, 0.1, 1.0, t, 3, 1, "", _("dpi"), 2, 0, nullptr); singleexport_box.pack_start(size_box, Gtk::PACK_SHRINK); } @@ -317,14 +294,14 @@ Export::Export () : set_default_filename(); - filename_box.pack_start (filename_entry, true, true, 0); + filename_box.pack_start(filename_entry, true, true, 0); - Gtk::HBox* browser_im_label = new Gtk::HBox(false, 3); + Gtk::HBox *browser_im_label = new Gtk::HBox(false, 3); browse_image.set_from_icon_name("folder", Gtk::ICON_SIZE_BUTTON); browser_im_label->pack_start(browse_image); browser_im_label->pack_start(browse_label); browse_button.add(*browser_im_label); - filename_box.pack_end (browse_button, false, false); + filename_box.pack_end(browse_button, false, false); filename_box.pack_end(export_button, false, false); file_box.add(filename_box); @@ -344,38 +321,42 @@ Export::Export () : batch_box.pack_start(batch_export, false, false, 3); hide_export.set_sensitive(true); - hide_export.set_active (prefs->getBool("/dialogs/export/hideexceptselected/value", false)); + hide_export.set_active(prefs->getBool("/dialogs/export/hideexceptselected/value", false)); hide_box.pack_start(hide_export, false, false, 3); - /* Export Button row */ export_button.set_label(_("_Export")); export_button.set_use_underline(); - export_button.set_tooltip_text (_("Export the bitmap file with these settings")); + export_button.set_tooltip_text(_("Export the bitmap file with these settings")); button_box.set_border_width(3); button_box.pack_start(closeWhenDone, true, true, 0); /*Advanced*/ - Gtk::Label *label_advanced = Gtk::manage(new Gtk::Label(_("Advanced"),true)); + Gtk::Label *label_advanced = Gtk::manage(new Gtk::Label(_("Advanced"), true)); expander.set_label_widget(*label_advanced); expander.set_vexpand(false); - const char* const modes_list[]={"Gray_1", "Gray_2","Gray_4","Gray_8","Gray_16","RGB_8","RGB_16","GrayAlpha_8","GrayAlpha_16","RGBA_8","RGBA_16"}; - for(auto i : modes_list) + const char *const modes_list[] = {"Gray_1", "Gray_2", "Gray_4", "Gray_8", "Gray_16", "RGB_8", + "RGB_16", "GrayAlpha_8", "GrayAlpha_16", "RGBA_8", "RGBA_16"}; + for (auto i : modes_list) bitdepth_cb.append(i); bitdepth_cb.set_active_text("RGBA_8"); bitdepth_cb.set_hexpand(); - const char* const zlist[]={"Z_NO_COMPRESSION","Z_BEST_SPEED","2","3","4","5","Z_DEFAULT_COMPRESSION","7","8","Z_BEST_COMPRESSION"}; - for(auto i : zlist) + const char *const zlist[] = { + "Z_NO_COMPRESSION", "Z_BEST_SPEED", "2", "3", "4", "5", "Z_DEFAULT_COMPRESSION", "7", "8", + "Z_BEST_COMPRESSION"}; + for (auto i : zlist) zlib_compression.append(i); zlib_compression.set_active_text("Z_DEFAULT_COMPRESSION"); pHYs_adj = Gtk::Adjustment::create(0, 0, 100000, 0.1, 1.0, 0); pHYs_sb.set_adjustment(pHYs_adj); pHYs_sb.set_width_chars(7); - pHYs_sb.set_tooltip_text( _("Will force-set the physical dpi for the png file. Set this to 72 if you're planning to work on your png with Photoshop") ); + pHYs_sb.set_tooltip_text(_("Will force-set the physical dpi for the png file. Set this to 72 if you're planning to " + "work on your png with Photoshop")); zlib_compression.set_hexpand(); - const char* const antialising_list[] = {"CAIRO_ANTIALIAS_NONE","CAIRO_ANTIALIAS_FAST","CAIRO_ANTIALIAS_GOOD (default)","CAIRO_ANTIALIAS_BEST"}; - for(auto i : antialising_list) + const char *const antialising_list[] = {"CAIRO_ANTIALIAS_NONE", "CAIRO_ANTIALIAS_FAST", + "CAIRO_ANTIALIAS_GOOD (default)", "CAIRO_ANTIALIAS_BEST"}; + for (auto i : antialising_list) antialiasing_cb.append(i); antialiasing_cb.set_active_text(antialising_list[2]); bitdepth_label.set_halign(Gtk::ALIGN_START); @@ -385,15 +366,15 @@ Export::Export () : auto table = new Gtk::Grid(); expander.add(*table); table->set_border_width(4); - table->attach(interlacing,0,0,1,1); - table->attach(bitdepth_label,0,1,1,1); - table->attach(bitdepth_cb,1,1,1,1); - table->attach(zlib_label,0,2,1,1); - table->attach(zlib_compression,1,2,1,1); - table->attach(pHYs_label,0,3,1,1); - table->attach(pHYs_sb,1,3,1,1); - table->attach(antialiasing_label,0,4,1,1); - table->attach(antialiasing_cb,1,4,1,1); + table->attach(interlacing, 0, 0, 1, 1); + table->attach(bitdepth_label, 0, 1, 1, 1); + table->attach(bitdepth_cb, 1, 1, 1, 1); + table->attach(zlib_label, 0, 2, 1, 1); + table->attach(zlib_compression, 1, 2, 1, 1); + table->attach(pHYs_label, 0, 3, 1, 1); + table->attach(pHYs_sb, 1, 3, 1, 1); + table->attach(antialiasing_label, 0, 4, 1, 1); + table->attach(antialiasing_cb, 1, 4, 1, 1); table->show(); /* Main dialog */ @@ -407,9 +388,9 @@ Export::Export () : contents->pack_end(_prog, Gtk::PACK_SHRINK); /* Signal handlers */ - filename_entry.signal_changed().connect( sigc::mem_fun(*this, &Export::onFilenameModified) ); + filename_entry.signal_changed().connect(sigc::mem_fun(*this, &Export::onFilenameModified)); // pressing enter in the filename field is the same as clicking export: - filename_entry.signal_activate().connect(sigc::mem_fun(*this, &Export::onExport) ); + filename_entry.signal_activate().connect(sigc::mem_fun(*this, &Export::onExport)); 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)); @@ -422,7 +403,7 @@ Export::Export () : refreshArea(); } -Export::~Export () +Export::~Export() { selectModifiedConn.disconnect(); subselChangedConn.disconnect(); @@ -440,12 +421,14 @@ void Export::setDesktop(SPDesktop *desktop) selectChangedConn.disconnect(); } if (desktop && desktop->selection) { - - selectChangedConn = desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &Export::onSelectionChanged))); - subselChangedConn = desktop->connectToolSubselectionChanged(sigc::hide(sigc::mem_fun(*this, &Export::onSelectionChanged))); + selectChangedConn = + desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &Export::onSelectionChanged))); + subselChangedConn = + desktop->connectToolSubselectionChanged(sigc::hide(sigc::mem_fun(*this, &Export::onSelectionChanged))); //// Must check flags, so can't call widget_setup() directly. - selectModifiedConn = desktop->selection->connectModified(sigc::hide<0>(sigc::mem_fun(*this, &Export::onSelectionModified))); + selectModifiedConn = + desktop->selection->connectModified(sigc::hide<0>(sigc::mem_fun(*this, &Export::onSelectionModified))); } } } @@ -462,25 +445,25 @@ void Export::setDesktop(SPDesktop *desktop) * this code sets the name first, it may not be the one users * really see. */ -void Export::set_default_filename () { - - if ( SP_ACTIVE_DOCUMENT && SP_ACTIVE_DOCUMENT->getDocumentURI() ) - { - SPDocument * doc = SP_ACTIVE_DOCUMENT; +void Export::set_default_filename() +{ + if (SP_ACTIVE_DOCUMENT && SP_ACTIVE_DOCUMENT->getDocumentURI()) { + SPDocument *doc = SP_ACTIVE_DOCUMENT; const gchar *uri = doc->getDocumentURI(); auto &&text_extension = get_file_save_extension(Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS); - Inkscape::Extension::Output * oextension = nullptr; + Inkscape::Extension::Output *oextension = nullptr; if (!text_extension.empty()) { - oextension = dynamic_cast<Inkscape::Extension::Output *>(Inkscape::Extension::db.get(text_extension.c_str())); + oextension = + dynamic_cast<Inkscape::Extension::Output *>(Inkscape::Extension::db.get(text_extension.c_str())); } if (oextension != nullptr) { - gchar * old_extension = oextension->get_extension(); + gchar *old_extension = oextension->get_extension(); if (g_str_has_suffix(uri, old_extension)) { - gchar * uri_copy; - gchar * extension_point; - gchar * final_name; + gchar *uri_copy; + gchar *extension_point; + gchar *final_name; uri_copy = g_strdup(uri); extension_point = g_strrstr(uri_copy, old_extension); @@ -502,10 +485,8 @@ void Export::set_default_filename () { } doc_export_name = filename_entry.get_text(); - } - else if ( SP_ACTIVE_DOCUMENT ) - { - Glib::ustring filename = create_filepath_from_id (_("bitmap"), filename_entry.get_text()); + } else if (SP_ACTIVE_DOCUMENT) { + Glib::ustring filename = create_filepath_from_id(_("bitmap"), filename_entry.get_text()); filename_entry.set_text(filename); filename_entry.set_position(filename.length()); @@ -513,12 +494,10 @@ void Export::set_default_filename () { } } -Glib::RefPtr<Gtk::Adjustment> Export::createSpinbutton( gchar const * /*key*/, float val, float min, float max, - 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)() ) +Glib::RefPtr<Gtk::Adjustment> Export::createSpinbutton(gchar const * /*key*/, float val, float min, float max, + 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)()) { auto adj = Gtk::Adjustment::create(val, min, max, step, page, 0); @@ -526,7 +505,7 @@ Glib::RefPtr<Gtk::Adjustment> Export::createSpinbutton( gchar const * /*key*/, f Gtk::Label *l = nullptr; if (!ll.empty()) { - l = new Gtk::Label(ll,true); + l = new Gtk::Label(ll, true); l->set_halign(Gtk::ALIGN_END); l->set_valign(Gtk::ALIGN_CENTER); l->set_hexpand(); @@ -540,7 +519,7 @@ Glib::RefPtr<Gtk::Adjustment> Export::createSpinbutton( gchar const * /*key*/, f t->attach(*sb, x + pos, y, 1, 1); sb->set_width_chars(7); - sb->set_sensitive (sensitive); + sb->set_sensitive(sensitive); pos++; if (l) { @@ -548,28 +527,26 @@ Glib::RefPtr<Gtk::Adjustment> Export::createSpinbutton( gchar const * /*key*/, f } if (!lr.empty()) { - l = new Gtk::Label(lr,true); + l = new Gtk::Label(lr, true); l->set_halign(Gtk::ALIGN_START); l->set_valign(Gtk::ALIGN_CENTER); l->set_hexpand(); t->attach(*l, x + pos, y, 1, 1); - l->set_sensitive (sensitive); + l->set_sensitive(sensitive); pos++; - l->set_mnemonic_widget (*sb); + l->set_mnemonic_widget(*sb); } if (cb) { - adj->signal_value_changed().connect( sigc::mem_fun(*this, cb) ); + adj->signal_value_changed().connect(sigc::mem_fun(*this, cb)); } return adj; } // end of createSpinbutton() - std::string create_filepath_from_id(Glib::ustring id, const Glib::ustring &file_entry_text) { - if (id.empty()) - { /* This should never happen */ + if (id.empty()) { /* This should never happen */ id = "bitmap"; } @@ -581,7 +558,7 @@ std::string create_filepath_from_id(Glib::ustring id, const Glib::ustring &file_ if (directory.empty()) { /* Grab document directory */ - const gchar* docURI = SP_ACTIVE_DOCUMENT->getDocumentURI(); + const gchar *docURI = SP_ACTIVE_DOCUMENT->getDocumentURI(); if (docURI) { directory = Glib::path_get_dirname(docURI); } @@ -594,7 +571,7 @@ std::string create_filepath_from_id(Glib::ustring id, const Glib::ustring &file_ return Glib::build_filename(directory, Glib::filename_from_utf8(id) + ".png"); } -void Export::onBatchClicked () +void Export::onBatchClicked() { if (batch_export.get_active()) { singleexport_box.set_sensitive(false); @@ -603,18 +580,19 @@ void Export::onBatchClicked () } } -void Export::updateCheckbuttons () +void Export::updateCheckbuttons() { - gint num = (gint) boost::distance(SP_ACTIVE_DESKTOP->getSelection()->items()); + gint num = (gint)boost::distance(SP_ACTIVE_DESKTOP->getSelection()->items()); if (num >= 2) { batch_export.set_sensitive(true); - batch_export.set_label(g_strdup_printf (ngettext("B_atch export %d selected object","B_atch export %d selected objects",num), num)); + batch_export.set_label(g_strdup_printf( + ngettext("B_atch export %d selected object", "B_atch export %d selected objects", num), num)); } else { - batch_export.set_active (false); + batch_export.set_active(false); batch_export.set_sensitive(false); } - //hide_export.set_sensitive (num > 0); + // hide_export.set_sensitive (num > 0); } inline void Export::findDefaultSelection() @@ -627,7 +605,6 @@ inline void Export::findDefaultSelection() /* Try using the preferences */ if (key == SELECTION_NUMBER_OF) { - int i = SELECTION_NUMBER_OF; Glib::ustring what = prefs->getString("/dialogs/export/exportarea/value"); @@ -649,10 +626,9 @@ inline void Export::findDefaultSelection() current_key = key; selectiontype_buttons[current_key]->set_active(true); - updateCheckbuttons (); + updateCheckbuttons(); } - /** * If selection changed and "Export area" is set to "Selection" * recalculate bounds when the selection changes @@ -666,50 +642,44 @@ void Export::onSelectionChanged() } } -void Export::onSelectionModified ( guint /*flags*/ ) +void Export::onSelectionModified(guint /*flags*/) { - Inkscape::Selection * Sel; + Inkscape::Selection *Sel; switch (current_key) { - case SELECTION_DRAWING: - if ( SP_ACTIVE_DESKTOP ) { - SPDocument *doc; - doc = SP_ACTIVE_DESKTOP->getDocument(); - 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_ACTIVE_DESKTOP->getDocument(); + Geom::OptRect bbox = doc->getRoot()->desktopVisualBounds(); + if (bbox) { + setArea(bbox->left(), bbox->top(), bbox->right(), bbox->bottom()); + } } - } - break; - case SELECTION_SELECTION: - Sel = SP_ACTIVE_DESKTOP->getSelection(); - 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_ACTIVE_DESKTOP->getSelection(); + 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; } /// Called when one of the selection buttons was toggled. -void Export::onAreaTypeToggled() { +void Export::onAreaTypeToggled() +{ if (update) { return; } - + /* Find which button is active */ selection_type key = current_key; for (int i = 0; i < SELECTION_NUMBER_OF; i++) { @@ -724,114 +694,107 @@ void Export::onAreaTypeToggled() { /// Called when area needs to be refreshed /// Area type changed, unit changed, initialization -void Export::refreshArea () +void Export::refreshArea() { - if ( SP_ACTIVE_DESKTOP ) - { + if (SP_ACTIVE_DESKTOP) { SPDocument *doc; Geom::OptRect bbox; - bbox = Geom::Rect(Geom::Point(0.0, 0.0),Geom::Point(0.0, 0.0)); + bbox = Geom::Rect(Geom::Point(0.0, 0.0), Geom::Point(0.0, 0.0)); doc = SP_ACTIVE_DESKTOP->getDocument(); /* Notice how the switch is used to 'fall through' here to get various backups. If you modify this without noticing you'll probably screw something up. */ switch (current_key) { - case SELECTION_SELECTION: - if ((SP_ACTIVE_DESKTOP->getSelection())->isEmpty() == false) - { - bbox = SP_ACTIVE_DESKTOP->getSelection()->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; - current_key = SELECTION_SELECTION; - break; - } - case SELECTION_DRAWING: - if (manual_key == SELECTION_DRAWING || manual_key == SELECTION_SELECTION) { - /** \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; - current_key= SELECTION_DRAWING; + case SELECTION_SELECTION: + if ((SP_ACTIVE_DESKTOP->getSelection())->isEmpty() == false) { + bbox = SP_ACTIVE_DESKTOP->getSelection()->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; + current_key = SELECTION_SELECTION; break; } - } - case SELECTION_PAGE: - if (manual_key == SELECTION_PAGE){ - bbox = Geom::Rect(Geom::Point(0.0, 0.0), - Geom::Point(doc->getWidth().value("px"), doc->getHeight().value("px"))); + case SELECTION_DRAWING: + if (manual_key == SELECTION_DRAWING || manual_key == SELECTION_SELECTION) { + /** \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; + current_key = SELECTION_DRAWING; + break; + } + } + case SELECTION_PAGE: + if (manual_key == 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; - current_key= SELECTION_PAGE; + // std::cout << "Using selection: PAGE" << std::endl; + current_key = SELECTION_PAGE; + break; + } + case SELECTION_CUSTOM: + current_key = SELECTION_CUSTOM; + default: break; - } - case SELECTION_CUSTOM: - current_key = SELECTION_CUSTOM; - default: - break; } // switch // remember area setting prefs->setString("/dialogs/export/exportarea/value", selection_names[current_key]); - if ( current_key != SELECTION_CUSTOM && bbox ) { - setArea ( bbox->min()[Geom::X], - bbox->min()[Geom::Y], - bbox->max()[Geom::X], - bbox->max()[Geom::Y]); + if (current_key != SELECTION_CUSTOM && bbox) { + setArea(bbox->min()[Geom::X], bbox->min()[Geom::Y], bbox->max()[Geom::X], bbox->max()[Geom::Y]); } } // end of if ( SP_ACTIVE_DESKTOP ) if (SP_ACTIVE_DESKTOP && !filename_modified) { - Glib::ustring filename; float xdpi = 0.0, ydpi = 0.0; switch (current_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; - } - } - break; - } - case SELECTION_SELECTION: - if ((SP_ACTIVE_DESKTOP->getSelection())->isEmpty() == false) { + case SELECTION_PAGE: + case SELECTION_DRAWING: { + SPDocument *doc = SP_ACTIVE_DOCUMENT; + sp_document_get_export_hints(doc, filename, &xdpi, &ydpi); - SP_ACTIVE_DESKTOP->getSelection()->getExportHints(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"; - auto reprlst = SP_ACTIVE_DESKTOP->getSelection()->xmlNodes(); - for(auto i=reprlst.begin(); reprlst.end() != i; ++i) { - Inkscape::XML::Node * repr = *i; - if (repr->attribute("id")) { - id = repr->attribute("id"); - break; - } + if (!doc_export_name.empty()) { + filename = doc_export_name; } - - filename = create_filepath_from_id (id, filename_entry.get_text()); } + break; } - break; - case SELECTION_CUSTOM: - default: - break; + case SELECTION_SELECTION: + if ((SP_ACTIVE_DESKTOP->getSelection())->isEmpty() == false) { + SP_ACTIVE_DESKTOP->getSelection()->getExportHints(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"; + auto reprlst = SP_ACTIVE_DESKTOP->getSelection()->xmlNodes(); + for (auto i = reprlst.begin(); reprlst.end() != i; ++i) { + Inkscape::XML::Node *repr = *i; + 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; } if (!filename.empty()) { @@ -856,29 +819,27 @@ void Export::refreshArea () } // end of sp_export_area_toggled() /// Called when dialog is deleted -bool Export::onProgressDelete (GdkEventAny * /*event*/) +bool Export::onProgressDelete(GdkEventAny * /*event*/) { interrupted = true; return TRUE; } // end of sp_export_progress_delete() - /// Called when progress is cancelled -void Export::onProgressCancel () +void Export::onProgressCancel() { interrupted = true; } // end of sp_export_progress_cancel() - /// Called for every progress iteration unsigned int Export::onProgressCallback(float value, void *dlg) { - auto dlg2 = reinterpret_cast<ExportProgressDialog*>(dlg); + auto dlg2 = reinterpret_cast<ExportProgressDialog *>(dlg); auto self = dlg2->get_export_panel(); if (self->interrupted) return FALSE; - + auto current = dlg2->get_current(); auto total = dlg2->get_total(); if (total > 0) { @@ -922,24 +883,23 @@ void Export::setExporting(bool exporting, Glib::ustring const &text) } } -ExportProgressDialog * -Export::create_progress_dialog(Glib::ustring progress_text) +ExportProgressDialog *Export::create_progress_dialog(Glib::ustring progress_text) { auto dlg = new ExportProgressDialog(_("Export in progress"), true); - dlg->set_transient_for( *(INKSCAPE.active_desktop()->getToplevel()) ); + dlg->set_transient_for(*(INKSCAPE.active_desktop()->getToplevel())); - Gtk::ProgressBar *prg = new Gtk::ProgressBar (); + Gtk::ProgressBar *prg = new Gtk::ProgressBar(); prg->set_text(progress_text); dlg->set_progress(prg); auto CA = dlg->get_content_area(); CA->pack_start(*prg, FALSE, FALSE, 4); - Gtk::Button* btn = dlg->add_button (_("_Cancel"),Gtk::RESPONSE_CANCEL ); + Gtk::Button *btn = dlg->add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL); - btn->signal_clicked().connect( sigc::mem_fun(*this, &Export::onProgressCancel) ); - dlg->signal_delete_event().connect( sigc::mem_fun(*this, &Export::onProgressDelete) ); + btn->signal_clicked().connect(sigc::mem_fun(*this, &Export::onProgressCancel)); + dlg->signal_delete_event().connect(sigc::mem_fun(*this, &Export::onProgressDelete)); - dlg->show_all (); + dlg->show_all(); return dlg; } @@ -957,7 +917,7 @@ static Glib::ustring filename_add_extension(Glib::ustring filename, Glib::ustrin static std::string absolutize_path_from_document_location(SPDocument *doc, const std::string &filename) { std::string path; - //Make relative paths go from the document location, if possible: + // Make relative paths go from the document location, if possible: if (!Glib::path_is_absolute(filename) && doc->getDocumentURI()) { auto dirname = Glib::path_get_dirname(doc->getDocumentURI()); if (!dirname.empty()) { @@ -976,39 +936,41 @@ void Export::onUnitChanged() refreshArea(); } -void Export::onHideExceptSelected () +void Export::onHideExceptSelected() { prefs->setBool("/dialogs/export/hideexceptselected/value", hide_export.get_active()); } /// Called when export button is clicked -void Export::onExport () +void Export::onExport() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if (!desktop) return; + if (!desktop) + return; SPNamedView *nv = desktop->getNamedView(); SPDocument *doc = desktop->getDocument(); bool exportSuccessful = false; - bool hide = hide_export.get_active (); + bool hide = hide_export.get_active(); // Advanced parameters bool do_interlace = (interlacing.get_active()); float pHYs = 0; - int zlib = zlib_compression.get_active_row_number() ; - int colortypes[] = {0,0,0,0,0,2,2,4,4,6,6}; //keep in sync with modes_list in Export constructor. values are from libpng doc. - int bitdepths[] = {1,2,4,8,16,8,16,8,16,8,16}; - int color_type = colortypes[bitdepth_cb.get_active_row_number()] ; - int bit_depth = bitdepths[bitdepth_cb.get_active_row_number()] ; + int zlib = zlib_compression.get_active_row_number(); + int colortypes[] = {0, 0, 0, 0, 0, 2, + 2, 4, 4, 6, 6}; // keep in sync with modes_list in Export constructor. values are from libpng + // doc. + int bitdepths[] = {1, 2, 4, 8, 16, 8, 16, 8, 16, 8, 16}; + int color_type = colortypes[bitdepth_cb.get_active_row_number()]; + int bit_depth = bitdepths[bitdepth_cb.get_active_row_number()]; int antialiasing = antialiasing_cb.get_active_row_number(); - - if (batch_export.get_active ()) { + if (batch_export.get_active()) { // Batch export of selected objects - gint num = (gint) boost::distance(desktop->getSelection()->items()); + gint num = (gint)boost::distance(desktop->getSelection()->items()); gint n = 0; if (num < 1) { @@ -1022,8 +984,8 @@ void Export::onExport () gint export_count = 0; - auto itemlist= desktop->getSelection()->items(); - for(auto i = itemlist.begin();i!=itemlist.end() && !interrupted ;++i){ + auto itemlist = desktop->getSelection()->items(); + for (auto i = itemlist.begin(); i != itemlist.end() && !interrupted; ++i) { SPItem *item = *i; prog_dlg->set_current(n); @@ -1041,7 +1003,8 @@ void Export::onExport () } // retrieve export dpi hints - const gchar *dpi_hint = item->getRepr()->attribute("inkscape:export-xdpi"); // only xdpi, ydpi is always the same now + const gchar *dpi_hint = + item->getRepr()->attribute("inkscape:export-xdpi"); // only xdpi, ydpi is always the same now gdouble dpi = 0.0; if (dpi_hint) { dpi = atof(dpi_hint); @@ -1053,27 +1016,29 @@ void Export::onExport () Geom::OptRect area = item->documentVisualBounds(); if (area) { - gint width = (gint) (area->width() * dpi / DPI_BASE + 0.5); - gint height = (gint) (area->height() * dpi / DPI_BASE + 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 - gchar * safeFile = Inkscape::IO::sanitizeString(path.c_str()); + gchar *safeFile = Inkscape::IO::sanitizeString(path.c_str()); MessageCleaner msgCleanup(desktop->messageStack()->pushF(Inkscape::IMMEDIATE_MESSAGE, - _("Exporting file <b>%s</b>..."), safeFile), desktop); + _("Exporting file <b>%s</b>..."), + safeFile), + desktop); MessageCleaner msgFlashCleanup(desktop->messageStack()->flashF(Inkscape::IMMEDIATE_MESSAGE, - _("Exporting file <b>%s</b>..."), safeFile), desktop); - std::vector<SPItem*> x; - std::vector<SPItem*> selected(desktop->getSelection()->items().begin(), desktop->getSelection()->items().end()); - if (!sp_export_png_file (doc, path.c_str(), - *area, width, height, pHYs, pHYs, - nv->pagecolor, - onProgressCallback, (void*)prog_dlg, - TRUE, // overwrite without asking - hide ? selected : x, - do_interlace, color_type, bit_depth, zlib, antialiasing - )) { - gchar * error = g_strdup_printf(_("Could not export to filename %s.\n"), safeFile); + _("Exporting file <b>%s</b>..."), + safeFile), + desktop); + std::vector<SPItem *> x; + std::vector<SPItem *> selected(desktop->getSelection()->items().begin(), + desktop->getSelection()->items().end()); + if (!sp_export_png_file(doc, path.c_str(), *area, width, height, pHYs, pHYs, nv->pagecolor, + onProgressCallback, (void *)prog_dlg, + TRUE, // overwrite without asking + hide ? selected : x, do_interlace, color_type, bit_depth, zlib, + antialiasing)) { + 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); @@ -1091,7 +1056,8 @@ void Export::onExport () } desktop->messageStack()->flashF(Inkscape::INFORMATION_MESSAGE, - _("Successfully exported <b>%d</b> files from <b>%d</b> selected items."), export_count, num); + _("Successfully exported <b>%d</b> files from <b>%d</b> selected items."), + export_count, num); setExporting(false); delete prog_dlg; @@ -1130,12 +1096,10 @@ void Export::onExport () std::string path = absolutize_path_from_document_location(doc, Glib::filename_from_utf8(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)) ) - { + if (dirname.empty() || + !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); + 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); @@ -1148,7 +1112,7 @@ void Export::onExport () auto fn = Glib::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 = create_progress_dialog(Glib::ustring::compose(_("Exporting %1 (%2 x %3)"), fn, width, height)); prog_dlg->set_export_panel(this); setExporting(true, Glib::ustring::compose(_("Exporting %1 (%2 x %3)"), fn, width, height)); @@ -1158,19 +1122,16 @@ void Export::onExport () auto area = Geom::Rect(Geom::Point(x0, y0), Geom::Point(x1, y1)) * desktop->dt2doc(); /* Do export */ - std::vector<SPItem*> x; - std::vector<SPItem*> selected(desktop->getSelection()->items().begin(), desktop->getSelection()->items().end()); - ExportResult status = sp_export_png_file(desktop->getDocument(), path.c_str(), - area, width, height, pHYs, pHYs, //previously xdpi, ydpi. - nv->pagecolor, - onProgressCallback, (void*)prog_dlg, - FALSE, - hide ? selected : x, - do_interlace, color_type, bit_depth, zlib, antialiasing - ); + std::vector<SPItem *> x; + std::vector<SPItem *> selected(desktop->getSelection()->items().begin(), + desktop->getSelection()->items().end()); + ExportResult status = sp_export_png_file( + desktop->getDocument(), path.c_str(), area, width, height, pHYs, pHYs, // previously xdpi, ydpi. + nv->pagecolor, onProgressCallback, (void *)prog_dlg, FALSE, hide ? selected : x, do_interlace, color_type, + bit_depth, zlib, antialiasing); if (status == EXPORT_ERROR) { - gchar * safeFile = Inkscape::IO::sanitizeString(path.c_str()); - gchar * error = g_strdup_printf(_("Could not export to filename %s.\n"), safeFile); + gchar *safeFile = Inkscape::IO::sanitizeString(path.c_str()); + 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); @@ -1181,7 +1142,8 @@ void Export::onExport () exportSuccessful = true; gchar *safeFile = Inkscape::IO::sanitizeString(path.c_str()); - desktop->messageStack()->flashF(Inkscape::INFORMATION_MESSAGE, _("Drawing exported to <b>%s</b>."), safeFile); + desktop->messageStack()->flashF(Inkscape::INFORMATION_MESSAGE, _("Drawing exported to <b>%s</b>."), + safeFile); g_free(safeFile); } else { @@ -1200,64 +1162,19 @@ void Export::onExport () /* 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 == nullptr || (filename_ext != temp_string)) { - repr->setAttribute("inkscape:export-filename", filename_ext); - modified = true; - } - temp_string = repr->attribute("inkscape:export-xdpi"); - if (temp_string == nullptr || 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 == nullptr || 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: { - SPDocument * doc = SP_ACTIVE_DOCUMENT; - bool modified = false; - - bool saved = DocumentUndo::getUndoSensitive(doc); - DocumentUndo::setUndoSensitive(doc, false); - auto reprlst = desktop->getSelection()->xmlNodes(); - - for(auto i=reprlst.begin(); reprlst.end() != i; ++i) { - Inkscape::XML::Node * repr = *i; - const gchar * temp_string; - Glib::ustring dir = Glib::path_get_dirname(filename.c_str()); - const gchar* docURI=SP_ACTIVE_DOCUMENT->getDocumentURI(); - Glib::ustring docdir; - if (docURI) - { - docdir = Glib::path_get_dirname(docURI); - } - if (repr->attribute("id") == nullptr || - !(filename_ext.find_last_of(repr->attribute("id")) && - ( !docURI || - (dir == docdir)))) { - temp_string = repr->attribute("inkscape:export-filename"); - if (temp_string == nullptr || (filename_ext != temp_string)) { - repr->setAttribute("inkscape:export-filename", filename_ext); - 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 == nullptr || (filename_ext != temp_string)) { + repr->setAttribute("inkscape:export-filename", filename_ext); + modified = true; } temp_string = repr->attribute("inkscape:export-xdpi"); if (temp_string == nullptr || xdpi != atof(temp_string)) { @@ -1269,22 +1186,64 @@ void Export::onExport () sp_repr_set_svg_double(repr, "inkscape:export-ydpi", ydpi); modified = true; } + DocumentUndo::setUndoSensitive(doc, saved); + + if (modified) { + doc->setModifiedSinceSave(); + } + break; } - DocumentUndo::setUndoSensitive(doc, saved); + case SELECTION_SELECTION: { + SPDocument *doc = SP_ACTIVE_DOCUMENT; + bool modified = false; + + bool saved = DocumentUndo::getUndoSensitive(doc); + DocumentUndo::setUndoSensitive(doc, false); + auto reprlst = desktop->getSelection()->xmlNodes(); + + for (auto i = reprlst.begin(); reprlst.end() != i; ++i) { + Inkscape::XML::Node *repr = *i; + const gchar *temp_string; + Glib::ustring dir = Glib::path_get_dirname(filename.c_str()); + const gchar *docURI = SP_ACTIVE_DOCUMENT->getDocumentURI(); + Glib::ustring docdir; + if (docURI) { + docdir = Glib::path_get_dirname(docURI); + } + if (repr->attribute("id") == nullptr || + !(filename_ext.find_last_of(repr->attribute("id")) && (!docURI || (dir == docdir)))) { + temp_string = repr->attribute("inkscape:export-filename"); + if (temp_string == nullptr || (filename_ext != temp_string)) { + repr->setAttribute("inkscape:export-filename", filename_ext); + modified = true; + } + } + temp_string = repr->attribute("inkscape:export-xdpi"); + if (temp_string == nullptr || 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 == nullptr || ydpi != atof(temp_string)) { + sp_repr_set_svg_double(repr, "inkscape:export-ydpi", ydpi); + modified = true; + } + } + DocumentUndo::setUndoSensitive(doc, saved); - if (modified) { - doc->setModifiedSinceSave(); + if (modified) { + doc->setModifiedSinceSave(); + } + break; } - break; - } - default: - break; + default: + break; } } if (exportSuccessful && closeWhenDone.get_active()) { - for ( Gtk::Container *parent = get_parent(); parent; parent = parent->get_parent()) { - if ( GDL_IS_DOCK_ITEM(parent->gobj()) ) { + 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); @@ -1297,13 +1256,12 @@ void Export::onExport () /// Called when Browse button is clicked /// @todo refactor this code to use ui/dialog/filedialog.cpp -void Export::onBrowse () +void Export::onBrowse() { bool accept = false; - Gtk::FileChooserDialog fs(_("Select a filename for exporting"), - Gtk::FILE_CHOOSER_ACTION_SAVE); + Gtk::FileChooserDialog fs(_("Select a filename for exporting"), Gtk::FILE_CHOOSER_ACTION_SAVE); fs.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL); - fs.add_button(_("_Save"), Gtk::RESPONSE_ACCEPT); + fs.add_button(_("_Save"), Gtk::RESPONSE_ACCEPT); fs.set_local_only(false); sp_transientize(GTK_WIDGET(fs.gobj())); @@ -1327,28 +1285,26 @@ void Export::onBrowse () filter_string[3] = L'\0'; filter_string[9] = L'\0'; filter_string[10] = L'\0'; - 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); + 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); - if ( !Glib::file_test(dirname, Glib::FILE_TEST_EXISTS) || - Glib::file_test(filename, Glib::FILE_TEST_IS_DIR) || - dirname.empty() ) - { + 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, reinterpret_cast<wchar_t*>(utf16_path_string), _MAX_PATH); + gunichar2 *utf16_path_string = g_utf8_to_utf16(filename.c_str(), -1, NULL, NULL, NULL); + wcsncpy(_filename, reinterpret_cast<wchar_t *>(utf16_path_string), _MAX_PATH); g_free(utf16_path_string); auto desktop = getDesktop(); Glib::RefPtr<const Gdk::Window> parentWindow = desktop->getToplevel()->get_window(); g_assert(parentWindow->gobj() != NULL); - opf.hwndOwner = (HWND)gdk_win32_window_get_handle((GdkWindow*)parentWindow->gobj()); + opf.hwndOwner = (HWND)gdk_win32_window_get_handle((GdkWindow *)parentWindow->gobj()); opf.lpstrFilter = filter_string; opf.lpstrCustomFilter = 0; opf.nMaxCustFilter = 0L; @@ -1356,7 +1312,7 @@ void Export::onBrowse () opf.lpstrFile = _filename; opf.nMaxFile = _MAX_PATH; opf.lpstrFileTitle = NULL; - opf.nMaxFileTitle=0; + opf.nMaxFileTitle = 0; opf.lpstrInitialDir = 0; opf.lpstrTitle = title_string; opf.nFileOffset = 0; @@ -1366,10 +1322,9 @@ void Export::onBrowse () opf.lCustData = 0; opf.Flags = OFN_PATHMUSTEXIST; opf.lStructSize = sizeof(OPENFILENAMEW); - if (GetSaveFileNameW(&opf) != 0) - { + if (GetSaveFileNameW(&opf) != 0) { // 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); + gchar *utf8string = g_utf16_to_utf8((const gunichar2 *)opf.lpstrFile, _MAX_PATH, NULL, NULL, NULL); filename_entry.set_text(utf8string); filename_entry.set_position(-1); accept = true; @@ -1379,8 +1334,7 @@ void Export::onBrowse () g_free(title_string); #else - if (fs.run() == Gtk::RESPONSE_ACCEPT) - { + if (fs.run() == Gtk::RESPONSE_ACCEPT) { auto file = fs.get_filename(); auto utf8file = Glib::filename_to_utf8(file); @@ -1399,12 +1353,10 @@ void Export::onBrowse () 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) - ); + 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)); } /** @@ -1429,15 +1381,15 @@ bool Export::bbox_equal(Geom::Rect const &one, Geom::Rect const &two) * * @todo finish writing this up. */ -void Export::detectSize() { - static const selection_type test_order[SELECTION_NUMBER_OF] = {SELECTION_SELECTION, SELECTION_DRAWING, SELECTION_PAGE, SELECTION_CUSTOM}; +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), - getValuePx(y1_adj)); + Geom::Point x(getValuePx(x0_adj), getValuePx(y0_adj)); + Geom::Point y(getValuePx(x1_adj), getValuePx(y1_adj)); Geom::Rect current_bbox(x, y); this_test[0] = current_key; @@ -1445,50 +1397,45 @@ void Export::detectSize() { this_test[i + 1] = test_order[i]; } - for (int i = 0; - i < SELECTION_NUMBER_OF + 1 && - key == SELECTION_NUMBER_OF && - SP_ACTIVE_DESKTOP != nullptr; - i++) { + for (int i = 0; i < SELECTION_NUMBER_OF + 1 && key == SELECTION_NUMBER_OF && SP_ACTIVE_DESKTOP != nullptr; i++) { switch (this_test[i]) { - case SELECTION_SELECTION: - if ((SP_ACTIVE_DESKTOP->getSelection())->isEmpty() == false) { - Geom::OptRect bbox = (SP_ACTIVE_DESKTOP->getSelection())->bounds(SPItem::VISUAL_BBOX); + case SELECTION_SELECTION: + if ((SP_ACTIVE_DESKTOP->getSelection())->isEmpty() == false) { + Geom::OptRect bbox = (SP_ACTIVE_DESKTOP->getSelection())->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_ACTIVE_DESKTOP->getDocument(); + break; + case SELECTION_DRAWING: { + SPDocument *doc = SP_ACTIVE_DESKTOP->getDocument(); - Geom::OptRect bbox = doc->getRoot()->desktopVisualBounds(); + Geom::OptRect bbox = doc->getRoot()->desktopVisualBounds(); - if ( bbox && bbox_equal(*bbox,current_bbox) ) { - key = SELECTION_DRAWING; + if (bbox && bbox_equal(*bbox, current_bbox)) { + key = SELECTION_DRAWING; + } + break; } - break; - } - case SELECTION_PAGE: { - SPDocument *doc; + case SELECTION_PAGE: { + SPDocument *doc; - doc = SP_ACTIVE_DESKTOP->getDocument(); + doc = SP_ACTIVE_DESKTOP->getDocument(); - Geom::Point x(0.0, 0.0); - Geom::Point y(doc->getWidth().value("px"), - doc->getHeight().value("px")); - 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; - } - default: - break; + break; + } + default: + break; } } // std::cout << std::endl; @@ -1504,7 +1451,7 @@ void Export::detectSize() { } /* sp_export_detect_size */ /// Called when area x0 value is changed -void Export::areaXChange(Glib::RefPtr<Gtk::Adjustment>& adj) +void Export::areaXChange(Glib::RefPtr<Gtk::Adjustment> &adj) { float x0, x1, xdpi, width; @@ -1518,7 +1465,7 @@ void Export::areaXChange(Glib::RefPtr<Gtk::Adjustment>& adj) x1 = getValuePx(x1_adj); xdpi = getValue(xdpi_adj); - width = floor ((x1 - x0) * xdpi / DPI_BASE + 0.5); + width = floor((x1 - x0) * xdpi / DPI_BASE + 0.5); if (width < SP_EXPORT_MIN_SIZE) { width = SP_EXPORT_MIN_SIZE; @@ -1543,7 +1490,7 @@ void Export::areaXChange(Glib::RefPtr<Gtk::Adjustment>& adj) } // end of sp_export_area_x_value_changed() /// Called when area y0 value is changed. -void Export::areaYChange(Glib::RefPtr<Gtk::Adjustment>& adj) +void Export::areaYChange(Glib::RefPtr<Gtk::Adjustment> &adj) { float y0, y1, ydpi, height; @@ -1557,12 +1504,12 @@ void Export::areaYChange(Glib::RefPtr<Gtk::Adjustment>& adj) y1 = getValuePx(y1_adj); ydpi = getValue(ydpi_adj); - height = floor ((y1 - y0) * ydpi / DPI_BASE + 0.5); + height = floor((y1 - y0) * ydpi / DPI_BASE + 0.5); if (height < SP_EXPORT_MIN_SIZE) { height = SP_EXPORT_MIN_SIZE; if (adj == y1_adj) { - //if (!strcmp (key, "y0")) { + // if (!strcmp (key, "y0")) { y1 = y0 + height * DPI_BASE / ydpi; setValuePx(y1_adj, y1); } else { @@ -1596,7 +1543,6 @@ void Export::onAreaWidthChange() float bmwidth = floor(width * xdpi / DPI_BASE + 0.5); if (bmwidth < SP_EXPORT_MIN_SIZE) { - bmwidth = SP_EXPORT_MIN_SIZE; width = bmwidth * DPI_BASE / xdpi; setValuePx(width_adj, width); @@ -1620,10 +1566,10 @@ void Export::onAreaHeightChange() update = true; float y0 = getValuePx(y0_adj); - //float y1 = sp_export_value_get_px(y1_adj); + // float y1 = sp_export_value_get_px(y1_adj); float ydpi = getValue(ydpi_adj); float height = getValuePx(height_adj); - float bmheight = floor (height * ydpi / DPI_BASE + 0.5); + float bmheight = floor(height * ydpi / DPI_BASE + 0.5); if (bmheight < SP_EXPORT_MIN_SIZE) { bmheight = SP_EXPORT_MIN_SIZE; @@ -1684,7 +1630,7 @@ void Export::setImageX() } // end of setImageX() /// Called when pixel width is changed -void Export::onBitmapWidthChange () +void Export::onBitmapWidthChange() { float x0, x1, bmwidth, xdpi; @@ -1706,7 +1652,7 @@ void Export::onBitmapWidthChange () xdpi = bmwidth * DPI_BASE / (x1 - x0); setValue(xdpi_adj, xdpi); - setImageY (); + setImageY(); update = false; @@ -1714,7 +1660,7 @@ void Export::onBitmapWidthChange () } // end of sp_export_bitmap_width_value_changed() /// Called when pixel height is changed -void Export::onBitmapHeightChange () +void Export::onBitmapHeightChange() { float y0, y1, bmheight, xdpi; @@ -1736,7 +1682,7 @@ void Export::onBitmapHeightChange () xdpi = bmheight * DPI_BASE / (y1 - y0); setValue(xdpi_adj, xdpi); - setImageX (); + setImageX(); update = false; @@ -1800,14 +1746,13 @@ void Export::onExportXdpiChange() setValue(bmwidth_adj, bmwidth); - setImageY (); + setImageY(); update = false; return; } // end of sp_export_xdpi_value_changed() - /** * A function to change the area that is used for the exported. * bitmap. @@ -1827,7 +1772,7 @@ void Export::onExportXdpiChange() * @param x1 Horizontal lower right hand corner of the picture in points. * @param y1 Vertical lower right hand corner of the picture in points. */ -void Export::setArea( double x0, double y0, double x1, double y1 ) +void Export::setArea(double x0, double y0, double x1, double y1) { update = true; setValuePx(x1_adj, x1); @@ -1836,8 +1781,8 @@ void Export::setArea( double x0, double y0, double x1, double y1 ) setValuePx(y0_adj, y0); update = false; - areaXChange (x1_adj); - areaYChange (y1_adj); + areaXChange(x1_adj); + areaYChange(y1_adj); return; } @@ -1848,7 +1793,7 @@ void Export::setArea( double x0, double y0, double x1, double y1 ) * @param adj The adjustment widget * @param val What value to set it to. */ -void Export::setValue(Glib::RefPtr<Gtk::Adjustment>& adj, double val ) +void Export::setValue(Glib::RefPtr<Gtk::Adjustment> &adj, double val) { if (adj) { adj->set_value(val); @@ -1866,7 +1811,7 @@ void Export::setValue(Glib::RefPtr<Gtk::Adjustment>& adj, double val ) * @param adj The adjustment widget * @param val What the value should be in points. */ -void Export::setValuePx(Glib::RefPtr<Gtk::Adjustment>& adj, double val) +void Export::setValuePx(Glib::RefPtr<Gtk::Adjustment> &adj, double val) { Unit const *unit = unit_selector.getUnit(); @@ -1885,7 +1830,7 @@ void Export::setValuePx(Glib::RefPtr<Gtk::Adjustment>& adj, double val) * * @return The value in the specified adjustment. */ -float Export::getValue(Glib::RefPtr<Gtk::Adjustment>& adj) +float Export::getValue(Glib::RefPtr<Gtk::Adjustment> &adj) { if (!adj) { g_message("sp_export_value_get : adj is NULL"); @@ -1907,9 +1852,9 @@ float Export::getValue(Glib::RefPtr<Gtk::Adjustment>& adj) * * @return The value in the adjustment in points. */ -float Export::getValuePx(Glib::RefPtr<Gtk::Adjustment>& adj) +float Export::getValuePx(Glib::RefPtr<Gtk::Adjustment> &adj) { - float value = getValue( adj); + float value = getValue(adj); Unit const *unit = unit_selector.getUnit(); return Inkscape::Util::Quantity::convert(value, unit, "px"); @@ -1936,9 +1881,9 @@ void Export::onFilenameModified() return; } // end sp_export_filename_modified -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/export.h b/src/ui/dialog/export.h index e90fec9534b857e171aaa8c289386187d3f51e9d..dbac95d547de3b9b2a4b93076cbaf4d162f6ab26 100644 --- a/src/ui/dialog/export.h +++ b/src/ui/dialog/export.h @@ -13,11 +13,11 @@ #ifndef SP_EXPORT_H #define SP_EXPORT_H -#include <gtkmm/progressbar.h> +#include <gtkmm/checkbutton.h> +#include <gtkmm/comboboxtext.h> #include <gtkmm/expander.h> #include <gtkmm/grid.h> -#include <gtkmm/comboboxtext.h> -#include <gtkmm/checkbutton.h> +#include <gtkmm/progressbar.h> #include <gtkmm/radiobutton.h> #include <gtkmm/spinbutton.h> @@ -30,7 +30,8 @@ namespace Dialog { class ExportProgressDialog; /** What type of button is being pressed */ -enum selection_type { +enum selection_type +{ SELECTION_PAGE = 0, /**< Export the whole page */ SELECTION_DRAWING, /**< Export everything drawn on the page */ SELECTION_SELECTION, /**< Export everything that is selected */ @@ -45,17 +46,15 @@ enum selection_type { * shows it to the user. If the dialog has already been created, it simply shows the window. * */ -class Export : public Widget::Panel { +class Export : public Widget::Panel +{ public: - Export (); - ~Export () override; + Export(); + ~Export() override; - static Export &getInstance() { - return *new Export(); - } + static Export &getInstance() { return *new Export(); } private: - /** * A function to set the xdpi. * @@ -75,17 +74,17 @@ private: */ void setImageY(); bool bbox_equal(Geom::Rect const &one, Geom::Rect const &two); - void updateCheckbuttons (); + void updateCheckbuttons(); inline void findDefaultSelection(); void detectSize(); - void setArea ( double x0, double y0, double x1, double y1); + void setArea(double x0, double y0, double x1, double y1); /* * Getter/setter style functions for the spinbuttons */ - void setValue(Glib::RefPtr<Gtk::Adjustment>& adj, double val); - void setValuePx(Glib::RefPtr<Gtk::Adjustment>& adj, double val); - float getValue(Glib::RefPtr<Gtk::Adjustment>& adj); - float getValuePx(Glib::RefPtr<Gtk::Adjustment>& adj); + void setValue(Glib::RefPtr<Gtk::Adjustment> &adj, double val); + void setValuePx(Glib::RefPtr<Gtk::Adjustment> &adj, double val); + float getValue(Glib::RefPtr<Gtk::Adjustment> &adj); + float getValuePx(Glib::RefPtr<Gtk::Adjustment> &adj); /** * Helper function to create, style and pack spinbuttons for the export dialog. @@ -108,12 +107,10 @@ private: * * No unit_selector is stored in the created spinbutton, relies on external unit management */ - Glib::RefPtr<Gtk::Adjustment> createSpinbutton( gchar const *key, float val, float min, float max, - 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)() ); + Glib::RefPtr<Gtk::Adjustment> createSpinbutton(gchar const *key, float val, float min, float max, 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)()); /** * One of the area select radio buttons was pressed @@ -124,34 +121,26 @@ private: /** * Export button callback */ - void onExport (); + void onExport(); /** * File Browse button callback */ - void onBrowse (); + void onBrowse(); /** * Area X value changed callback */ - void onAreaX0Change() { - areaXChange(x0_adj); - } ; - void onAreaX1Change() { - areaXChange(x1_adj); - } ; - void areaXChange(Glib::RefPtr<Gtk::Adjustment>& adj); + void onAreaX0Change() { areaXChange(x0_adj); }; + void onAreaX1Change() { areaXChange(x1_adj); }; + void areaXChange(Glib::RefPtr<Gtk::Adjustment> &adj); /** * Area Y value changed callback */ - void onAreaY0Change() { - areaYChange(y0_adj); - } ; - void onAreaY1Change() { - areaYChange(y1_adj); - } ; - void areaYChange(Glib::RefPtr<Gtk::Adjustment>& adj); + void onAreaY0Change() { areaYChange(y0_adj); }; + void onAreaY1Change() { areaYChange(y1_adj); }; + void areaYChange(Glib::RefPtr<Gtk::Adjustment> &adj); /** * Unit changed callback @@ -161,48 +150,48 @@ private: /** * Hide except selected callback */ - void onHideExceptSelected (); + void onHideExceptSelected(); /** * Area width value changed callback */ - void onAreaWidthChange (); + void onAreaWidthChange(); /** * Area height value changed callback */ - void onAreaHeightChange (); + void onAreaHeightChange(); /** * Bitmap width value changed callback */ - void onBitmapWidthChange (); + void onBitmapWidthChange(); /** * Bitmap height value changed callback */ - void onBitmapHeightChange (); + void onBitmapHeightChange(); /** * Export xdpi value changed callback */ - void onExportXdpiChange (); + void onExportXdpiChange(); /** * Batch export callback */ - void onBatchClicked (); + void onBatchClicked(); /** * Inkscape selection change callback */ - void onSelectionChanged (); - void onSelectionModified (guint flags); + void onSelectionChanged(); + void onSelectionModified(guint flags); /** * Filename modified callback */ - void onFilenameModified (); + void onFilenameModified(); /** * Can be invoked for setting the desktop. Currently not used. @@ -214,7 +203,7 @@ private: * * @param progress_text Text to be shown in the progress bar */ - ExportProgressDialog * create_progress_dialog(Glib::ustring progress_text); + ExportProgressDialog *create_progress_dialog(Glib::ustring progress_text); /** * Callback to be used in for loop to update the progress bar. @@ -227,12 +216,12 @@ private: /** * Callback for pressing the cancel button. */ - void onProgressCancel (); + void onProgressCancel(); /** * Callback invoked on closing the progress dialog. */ - bool onProgressDelete (GdkEventAny *event); + bool onProgressDelete(GdkEventAny *event); /** * Handles state changes as exporting starts or stops. @@ -242,7 +231,7 @@ private: /* * Utility filename and path functions */ - void set_default_filename (); + void set_default_filename(); /* * Currently selected export area type @@ -290,7 +279,7 @@ private: Glib::RefPtr<Gtk::Adjustment> ydpi_adj; Gtk::VBox size_box; - Gtk::Label* bm_label; + Gtk::Label *bm_label; Gtk::VBox file_box; Gtk::Label *flabel; @@ -308,25 +297,25 @@ private: Gtk::Image browse_image; Gtk::HBox batch_box; - Gtk::CheckButton batch_export; + Gtk::CheckButton batch_export; Gtk::HBox hide_box; - Gtk::CheckButton hide_export; + Gtk::CheckButton hide_export; Gtk::CheckButton closeWhenDone; /* Advanced */ Gtk::Expander expander; Gtk::CheckButton interlacing; - Gtk::Label bitdepth_label; - Gtk::ComboBoxText bitdepth_cb; - Gtk::Label zlib_label; - Gtk::ComboBoxText zlib_compression; - Gtk::Label pHYs_label; - Glib::RefPtr<Gtk::Adjustment> pHYs_adj; - Gtk::SpinButton pHYs_sb; - Gtk::Label antialiasing_label; - Gtk::ComboBoxText antialiasing_cb; + Gtk::Label bitdepth_label; + Gtk::ComboBoxText bitdepth_cb; + Gtk::Label zlib_label; + Gtk::ComboBoxText zlib_compression; + Gtk::Label pHYs_label; + Glib::RefPtr<Gtk::Adjustment> pHYs_adj; + Gtk::SpinButton pHYs_sb; + Gtk::Label antialiasing_label; + Gtk::ComboBoxText antialiasing_cb; /* Export Button widgets */ Gtk::HBox button_box; @@ -335,19 +324,19 @@ private: Gtk::ProgressBar _prog; ExportProgressDialog *prog_dlg; - bool interrupted; // indicates whether export needs to be interrupted (read: user pressed cancel in the progress dialog) + bool interrupted; // indicates whether export needs to be interrupted (read: user pressed cancel in the progress + // dialog) Inkscape::Preferences *prefs; sigc::connection selectChangedConn; sigc::connection subselChangedConn; sigc::connection selectModifiedConn; sigc::connection unitChangedConn; - }; -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif /* diff --git a/src/ui/dialog/extension-editor.cpp b/src/ui/dialog/extension-editor.cpp index f399a9e49de32c728f43c91bfd817215b3e89383..0163b4b5eaab73a3f24d6ea74c24d28721f6992c 100644 --- a/src/ui/dialog/extension-editor.cpp +++ b/src/ui/dialog/extension-editor.cpp @@ -13,16 +13,15 @@ */ #include "extension-editor.h" -#include <glibmm/i18n.h> +#include <glibmm/i18n.h> #include <gtkmm/frame.h> #include <gtkmm/notebook.h> -#include "verbs.h" +#include "extension/db.h" #include "preferences.h" #include "ui/interface.h" - -#include "extension/db.h" +#include "verbs.h" namespace Inkscape { namespace UI { @@ -42,18 +41,17 @@ ExtensionEditor::ExtensionEditor() { _notebook_info.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); _notebook_params.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); - - //Main HBox - Gtk::HBox* hbox_list_page = Gtk::manage(new Gtk::HBox()); + + // Main HBox + Gtk::HBox *hbox_list_page = Gtk::manage(new Gtk::HBox()); hbox_list_page->set_border_width(12); hbox_list_page->set_spacing(12); hbox_list_page->set_vexpand(); _getContents()->add(*hbox_list_page); - - //Pagelist - Gtk::Frame* list_frame = Gtk::manage(new Gtk::Frame()); - Gtk::ScrolledWindow* scrolled_window = Gtk::manage(new Gtk::ScrolledWindow()); + // Pagelist + Gtk::Frame *list_frame = Gtk::manage(new Gtk::Frame()); + Gtk::ScrolledWindow *scrolled_window = Gtk::manage(new Gtk::ScrolledWindow()); hbox_list_page->pack_start(*list_frame, false, true, 0); _page_list.set_headers_visible(false); scrolled_window->set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); @@ -62,25 +60,26 @@ ExtensionEditor::ExtensionEditor() list_frame->add(*scrolled_window); _page_list_model = Gtk::TreeStore::create(_page_list_columns); _page_list.set_model(_page_list_model); - _page_list.append_column("name",_page_list_columns._col_name); + _page_list.append_column("name", _page_list_columns._col_name); Glib::RefPtr<Gtk::TreeSelection> page_list_selection = _page_list.get_selection(); - page_list_selection->signal_changed().connect(sigc::mem_fun(*this, &ExtensionEditor::on_pagelist_selection_changed)); + page_list_selection->signal_changed().connect( + sigc::mem_fun(*this, &ExtensionEditor::on_pagelist_selection_changed)); page_list_selection->set_mode(Gtk::SELECTION_BROWSE); - - //Pages - Gtk::VBox* vbox_page = Gtk::manage(new Gtk::VBox()); + // Pages + Gtk::VBox *vbox_page = Gtk::manage(new Gtk::VBox()); hbox_list_page->pack_start(*vbox_page, true, true, 0); - Gtk::Notebook * notebook = Gtk::manage(new Gtk::Notebook()); + Gtk::Notebook *notebook = Gtk::manage(new Gtk::Notebook()); notebook->append_page(_notebook_info, *Gtk::manage(new Gtk::Label(_("Information")))); notebook->append_page(_notebook_params, *Gtk::manage(new Gtk::Label(_("Parameters")))); vbox_page->pack_start(*notebook, true, true, 0); - Inkscape::Extension::db.foreach(dbfunc, this); - + Inkscape::Extension::db.foreach (dbfunc, this); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring defaultext = prefs->getString("/dialogs/extensioneditor/selected-extension"); - if (defaultext.empty()) defaultext = "org.inkscape.input.svg"; + if (defaultext.empty()) + defaultext = "org.inkscape.input.svg"; this->setExtension(defaultext); show_all_children(); @@ -89,18 +88,16 @@ ExtensionEditor::ExtensionEditor() /** * Destroys the extension editor dialog. */ -ExtensionEditor::~ExtensionEditor() -= default; +ExtensionEditor::~ExtensionEditor() = default; -void -ExtensionEditor::setExtension(Glib::ustring extension_id) { +void ExtensionEditor::setExtension(Glib::ustring extension_id) +{ _selection_search = extension_id; _page_list_model->foreach_iter(sigc::mem_fun(*this, &ExtensionEditor::setExtensionIter)); return; } -bool -ExtensionEditor::setExtensionIter(const Gtk::TreeModel::iterator &iter) +bool ExtensionEditor::setExtensionIter(const Gtk::TreeModel::iterator &iter) { Gtk::TreeModel::Row row = *iter; if (row[_page_list_columns._col_id] == _selection_search) { @@ -133,7 +130,7 @@ void ExtensionEditor::on_pagelist_selection_changed() /* Adjust the dialog's title */ gchar title[500]; - sp_ui_dialog_title_string (Inkscape::Verb::get(SP_VERB_DIALOG_EXTENSIONEDITOR), title); + sp_ui_dialog_title_string(Inkscape::Verb::get(SP_VERB_DIALOG_EXTENSIONEDITOR), title); Glib::ustring utitle(title); // set_title(utitle + ": " + name); @@ -141,11 +138,11 @@ void ExtensionEditor::on_pagelist_selection_changed() _notebook_info.remove(); _notebook_params.remove(); - Inkscape::Extension::Extension * ext = Inkscape::Extension::db.get(id.c_str()); + Inkscape::Extension::Extension *ext = Inkscape::Extension::db.get(id.c_str()); /* Make sure we have all the widgets */ - Gtk::Widget * info = nullptr; - Gtk::Widget * params = nullptr; + Gtk::Widget *info = nullptr; + Gtk::Widget *params = nullptr; if (ext != nullptr) { info = ext->get_info_widget(); @@ -159,7 +156,6 @@ void ExtensionEditor::on_pagelist_selection_changed() if (params != nullptr) { _notebook_params.add(*params); } - } return; @@ -177,9 +173,9 @@ void ExtensionEditor::on_pagelist_selection_changed() * @param in_plug The extension to evaluate. * @param in_data A pointer to the Extension Editor class. */ -void ExtensionEditor::dbfunc(Inkscape::Extension::Extension * in_plug, gpointer in_data) +void ExtensionEditor::dbfunc(Inkscape::Extension::Extension *in_plug, gpointer in_data) { - ExtensionEditor * ee = static_cast<ExtensionEditor *>(in_data); + ExtensionEditor *ee = static_cast<ExtensionEditor *>(in_data); ee->add_extension(in_plug); return; } @@ -193,7 +189,7 @@ void ExtensionEditor::dbfunc(Inkscape::Extension::Extension * in_plug, gpointer * @param ext The extension to add. * @return The iterator representing the location in the tree model. */ -Gtk::TreeModel::iterator ExtensionEditor::add_extension(Inkscape::Extension::Extension * ext) +Gtk::TreeModel::iterator ExtensionEditor::add_extension(Inkscape::Extension::Extension *ext) { Gtk::TreeModel::iterator iter; @@ -201,7 +197,7 @@ Gtk::TreeModel::iterator ExtensionEditor::add_extension(Inkscape::Extension::Ext Gtk::TreeModel::Row row = *iter; row[_page_list_columns._col_name] = ext->get_name(); - row[_page_list_columns._col_id] = ext->get_id(); + row[_page_list_columns._col_id] = ext->get_id(); return iter; } diff --git a/src/ui/dialog/extension-editor.h b/src/ui/dialog/extension-editor.h index 403ee1fb56769c3f3fd4bf9e402b239f62f2b258..eb082c9f8b081c4e03c90963d159bef1d4e5c500 100644 --- a/src/ui/dialog/extension-editor.h +++ b/src/ui/dialog/extension-editor.h @@ -14,19 +14,19 @@ #ifndef INKSCAPE_UI_DIALOG_EXTENSION_EDITOR_H #define INKSCAPE_UI_DIALOG_EXTENSION_EDITOR_H -#include "ui/widget/panel.h" - +#include <gtkmm/scrolledwindow.h> #include <gtkmm/treestore.h> #include <gtkmm/treeview.h> -#include <gtkmm/scrolledwindow.h> #include "extension/extension.h" +#include "ui/widget/panel.h" namespace Inkscape { namespace UI { namespace Dialog { -class ExtensionEditor : public UI::Widget::Panel { +class ExtensionEditor : public UI::Widget::Panel +{ public: ExtensionEditor(); ~ExtensionEditor() override; @@ -43,12 +43,14 @@ protected: /** \brief The notebook page that holds all the parameters */ Gtk::ScrolledWindow _notebook_params; - //Pagelist model columns: - class PageListModelColumns : public Gtk::TreeModel::ColumnRecord { + // Pagelist model columns: + class PageListModelColumns : public Gtk::TreeModel::ColumnRecord + { public: /** \brief Creates the Page List model by adding all of the members of the class as column records. */ - PageListModelColumns() { + PageListModelColumns() + { Gtk::TreeModelColumnRecord::add(_col_name); Gtk::TreeModelColumnRecord::add(_col_id); } @@ -65,12 +67,13 @@ private: Glib::ustring _selection_search; ExtensionEditor(ExtensionEditor const &d) = delete; - ExtensionEditor& operator=(ExtensionEditor const &d) = delete; + ExtensionEditor &operator=(ExtensionEditor const &d) = delete; void on_pagelist_selection_changed(); - static void dbfunc (Inkscape::Extension::Extension * in_plug, gpointer in_data); - Gtk::TreeModel::iterator add_extension (Inkscape::Extension::Extension * ext); + static void dbfunc(Inkscape::Extension::Extension *in_plug, gpointer in_data); + Gtk::TreeModel::iterator add_extension(Inkscape::Extension::Extension *ext); bool setExtensionIter(const Gtk::TreeModel::iterator &iter); + public: void setExtension(Glib::ustring extension_id); }; diff --git a/src/ui/dialog/extensions.cpp b/src/ui/dialog/extensions.cpp index f39c7d54983ec8fcc0ad9cda82c25cd0f981698e..dc2d33d99302ec4607cd75a42d9def3fca4f558a 100644 --- a/src/ui/dialog/extensions.cpp +++ b/src/ui/dialog/extensions.cpp @@ -12,11 +12,11 @@ */ #include "extensions.h" -#include "extension/extension.h" + #include <gtkmm/scrolledwindow.h> #include "extension/db.h" - +#include "extension/extension.h" namespace Inkscape { namespace UI { @@ -33,11 +33,10 @@ ExtensionsPanel &ExtensionsPanel::getInstance() return instance; } - -ExtensionsPanel::ExtensionsPanel() : - _showAll(false) +ExtensionsPanel::ExtensionsPanel() + : _showAll(false) { - Gtk::ScrolledWindow* scroller = new Gtk::ScrolledWindow(); + Gtk::ScrolledWindow *scroller = new Gtk::ScrolledWindow(); _view.set_editable(false); @@ -51,43 +50,37 @@ ExtensionsPanel::ExtensionsPanel() : void ExtensionsPanel::set_full(bool full) { - if ( full != _showAll ) { + if (full != _showAll) { _showAll = full; rescan(); } } -void ExtensionsPanel::listCB( Inkscape::Extension::Extension * in_plug, gpointer in_data ) +void ExtensionsPanel::listCB(Inkscape::Extension::Extension *in_plug, gpointer in_data) { - ExtensionsPanel * self = static_cast<ExtensionsPanel*>(in_data); + ExtensionsPanel *self = static_cast<ExtensionsPanel *>(in_data); - const char* stateStr; + const char *stateStr; Extension::state_t state = in_plug->get_state(); - switch ( state ) { - case Extension::STATE_LOADED: - { + switch (state) { + case Extension::STATE_LOADED: { stateStr = "loaded"; - } - break; - case Extension::STATE_UNLOADED: - { + } break; + case Extension::STATE_UNLOADED: { stateStr = "unloaded"; - } - break; - case Extension::STATE_DEACTIVATED: - { + } break; + case Extension::STATE_DEACTIVATED: { stateStr = "deactivated"; - } - break; + } break; default: stateStr = "unknown"; } - if ( self->_showAll || in_plug->deactivated() ) { - gchar* line = g_strdup_printf( "%s %s\n \"%s\"", stateStr, in_plug->get_name(), in_plug->get_id() ); + if (self->_showAll || in_plug->deactivated()) { + gchar *line = g_strdup_printf("%s %s\n \"%s\"", stateStr, in_plug->get_name(), in_plug->get_id()); - self->_view.get_buffer()->insert( self->_view.get_buffer()->end(), line ); - self->_view.get_buffer()->insert( self->_view.get_buffer()->end(), "\n" ); + self->_view.get_buffer()->insert(self->_view.get_buffer()->end(), line); + self->_view.get_buffer()->insert(self->_view.get_buffer()->end(), "\n"); g_free(line); } @@ -97,16 +90,16 @@ void ExtensionsPanel::listCB( Inkscape::Extension::Extension * in_plug, gpointer void ExtensionsPanel::rescan() { _view.get_buffer()->set_text("Extensions:\n"); -// g_message("/------------------"); + // g_message("/------------------"); - Inkscape::Extension::db.foreach(listCB, (gpointer)this); + Inkscape::Extension::db.foreach (listCB, (gpointer)this); -// g_message("\\------------------"); + // g_message("\\------------------"); } -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/extensions.h b/src/ui/dialog/extensions.h index 16d2e919a4ca5f5b7ce8c335dedce92cf0358861..18a02c5de5d6785bd8d8ad71839b1fc4b3f763bd 100644 --- a/src/ui/dialog/extensions.h +++ b/src/ui/dialog/extensions.h @@ -12,20 +12,20 @@ #ifndef SEEN_EXTENSIONS_H #define SEEN_EXTENSIONS_H -#include "ui/widget/panel.h" #include <gtkmm/textview.h> +#include "ui/widget/panel.h" + namespace Inkscape { namespace Extension { class Extension; } -} +} // namespace Inkscape namespace Inkscape { namespace UI { namespace Dialogs { - /** * A panel that displays information about extensions. */ @@ -39,7 +39,7 @@ public: void set_full(bool full); private: - ExtensionsPanel(ExtensionsPanel const &) = delete; // no copy + ExtensionsPanel(ExtensionsPanel const &) = delete; // no copy ExtensionsPanel &operator=(ExtensionsPanel const &) = delete; // no assign static void listCB(Inkscape::Extension::Extension *in_plug, gpointer in_data); @@ -50,8 +50,8 @@ private: Gtk::TextView _view; }; -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape #endif // SEEN_EXTENSIONS_H diff --git a/src/ui/dialog/filedialog.cpp b/src/ui/dialog/filedialog.cpp index fdce498d9d9762f432ce2cbc26f271f9614fb233..7373e7a7213663ea35d09b489289af3aca097b0a 100644 --- a/src/ui/dialog/filedialog.cpp +++ b/src/ui/dialog/filedialog.cpp @@ -17,23 +17,19 @@ */ #ifdef _WIN32 -# include "filedialogimpl-win32.h" -# include "preferences.h" +#include "filedialogimpl-win32.h" +#include "preferences.h" #endif -#include "filedialogimpl-gtkmm.h" +#include <glibmm/convert.h> -#include "ui/dialog-events.h" #include "extension/output.h" +#include "filedialogimpl-gtkmm.h" +#include "ui/dialog-events.h" -#include <glibmm/convert.h> - -namespace Inkscape -{ -namespace UI -{ -namespace Dialog -{ +namespace Inkscape { +namespace UI { +namespace Dialog { /*######################################################################### ### U T I L I T Y @@ -45,34 +41,29 @@ bool hasSuffix(const Glib::ustring &str, const Glib::ustring &ext) int extLen = ext.length(); if (extLen > strLen) return false; - int strpos = strLen-1; - for (int extpos = extLen-1 ; extpos>=0 ; extpos--, strpos--) - { + int strpos = strLen - 1; + for (int extpos = extLen - 1; extpos >= 0; extpos--, strpos--) { Glib::ustring::value_type ch = str[strpos]; - if (ch != ext[extpos]) - { - if ( ((ch & 0xff80) != 0) || - static_cast<Glib::ustring::value_type>( g_ascii_tolower( static_cast<gchar>(0x07f & ch) ) ) != ext[extpos] ) - { + if (ch != ext[extpos]) { + if (((ch & 0xff80) != 0) || static_cast<Glib::ustring::value_type>( + g_ascii_tolower(static_cast<gchar>(0x07f & ch))) != ext[extpos]) { return false; - } } } + } return true; } bool isValidImageFile(const Glib::ustring &fileName) { - std::vector<Gdk::PixbufFormat>formats = Gdk::Pixbuf::get_formats(); - for (auto format : formats) - { - std::vector<Glib::ustring>extensions = format.get_extensions(); - for (auto ext : extensions) - { + std::vector<Gdk::PixbufFormat> formats = Gdk::Pixbuf::get_formats(); + for (auto format : formats) { + std::vector<Glib::ustring> extensions = format.get_extensions(); + for (auto ext : extensions) { if (hasSuffix(fileName, ext)) return true; - } } + } return false; } @@ -83,15 +74,13 @@ bool isValidImageFile(const Glib::ustring &fileName) /** * Public factory. Called by file.cpp, among others. */ -FileOpenDialog *FileOpenDialog::create(Gtk::Window &parentWindow, - const Glib::ustring &path, - FileDialogType fileTypes, +FileOpenDialog *FileOpenDialog::create(Gtk::Window &parentWindow, const Glib::ustring &path, FileDialogType fileTypes, const char *title) { #ifdef _WIN32 FileOpenDialog *dialog = NULL; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (prefs->getBool( "/options/desktopintegration/value")) { + if (prefs->getBool("/options/desktopintegration/value")) { dialog = new FileOpenDialogImplWin32(parentWindow, path, fileTypes, title); } else { dialog = new FileOpenDialogImplGtk(parentWindow, path, fileTypes, title); @@ -100,7 +89,7 @@ FileOpenDialog *FileOpenDialog::create(Gtk::Window &parentWindow, FileOpenDialog *dialog = new FileOpenDialogImplGtk(parentWindow, path, fileTypes, title); #endif - return dialog; + return dialog; } Glib::ustring FileOpenDialog::getFilename() @@ -115,24 +104,21 @@ Glib::ustring FileOpenDialog::getFilename() /** * Public factory method. Used in file.cpp */ -FileSaveDialog *FileSaveDialog::create(Gtk::Window& parentWindow, - const Glib::ustring &path, - FileDialogType fileTypes, - const char *title, - const Glib::ustring &default_key, - const gchar *docTitle, +FileSaveDialog *FileSaveDialog::create(Gtk::Window &parentWindow, const Glib::ustring &path, FileDialogType fileTypes, + const char *title, const Glib::ustring &default_key, const gchar *docTitle, const Inkscape::Extension::FileSaveMethod save_method) { #ifdef _WIN32 FileSaveDialog *dialog = NULL; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (prefs->getBool( "/options/desktopintegration/value")) { + if (prefs->getBool("/options/desktopintegration/value")) { dialog = new FileSaveDialogImplWin32(parentWindow, path, fileTypes, title, default_key, docTitle, save_method); } else { dialog = new FileSaveDialogImplGtk(parentWindow, path, fileTypes, title, default_key, docTitle, save_method); } #else - FileSaveDialog *dialog = new FileSaveDialogImplGtk(parentWindow, path, fileTypes, title, default_key, docTitle, save_method); + FileSaveDialog *dialog = + new FileSaveDialogImplGtk(parentWindow, path, fileTypes, title, default_key, docTitle, save_method); #endif return dialog; } @@ -144,50 +130,46 @@ Glib::ustring FileSaveDialog::getFilename() Glib::ustring FileSaveDialog::getDocTitle() { - return myDocTitle; + return myDocTitle; } -//void FileSaveDialog::change_path(const Glib::ustring& path) +// void FileSaveDialog::change_path(const Glib::ustring& path) //{ // myFilename = path; //} -void FileSaveDialog::appendExtension(Glib::ustring& path, Inkscape::Extension::Output* outputExtension) +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 ); - Glib::ustring::size_type pos = utf8Name.rfind('.'); - if ( pos != Glib::ustring::npos ) { - Glib::ustring trail = utf8Name.substr( pos ); - Glib::ustring foldedTrail = trail.casefold(); - if ( (trail == ".") - | (foldedTrail != Glib::ustring( outputExtension->get_extension() ).casefold() - && ( knownExtensions.find(foldedTrail) != knownExtensions.end() ) ) ) { - utf8Name = utf8Name.erase( pos ); - } else { - appendExtension = false; - } - } - - if (appendExtension) { - utf8Name = utf8Name + outputExtension->get_extension(); - myFilename = Glib::filename_from_utf8( utf8Name ); - } - } catch ( Glib::ConvertError& e ) { - // ignore - } -} - - -} //namespace Dialog -} //namespace UI -} //namespace Inkscape + if (!outputExtension) + return; + + try { + bool appendExtension = true; + Glib::ustring utf8Name = Glib::filename_to_utf8(path); + Glib::ustring::size_type pos = utf8Name.rfind('.'); + if (pos != Glib::ustring::npos) { + Glib::ustring trail = utf8Name.substr(pos); + Glib::ustring foldedTrail = trail.casefold(); + if ((trail == ".") | (foldedTrail != Glib::ustring(outputExtension->get_extension()).casefold() && + (knownExtensions.find(foldedTrail) != knownExtensions.end()))) { + utf8Name = utf8Name.erase(pos); + } else { + appendExtension = false; + } + } + if (appendExtension) { + utf8Name = utf8Name + outputExtension->get_extension(); + myFilename = Glib::filename_from_utf8(utf8Name); + } + } catch (Glib::ConvertError &e) { + // ignore + } +} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/filedialog.h b/src/ui/dialog/filedialog.h index 898917147a25a228316ad64a45d15519cbaa70f8..51215ea002990c6587adb2bebca70b5431974157 100644 --- a/src/ui/dialog/filedialog.h +++ b/src/ui/dialog/filedialog.h @@ -17,50 +17,47 @@ #ifndef __FILE_DIALOG_H__ #define __FILE_DIALOG_H__ -#include <vector> +#include <glibmm/ustring.h> #include <set> +#include <vector> #include "extension/system.h" -#include <glibmm/ustring.h> - class SPDocument; namespace Inkscape { namespace Extension { class Extension; class Output; -} -} +} // namespace Extension +} // namespace Inkscape -namespace Inkscape -{ -namespace UI -{ -namespace Dialog -{ +namespace Inkscape { +namespace UI { +namespace Dialog { /** * Used for setting filters and options, and * reading them back from user selections. */ -enum FileDialogType { +enum FileDialogType +{ SVG_TYPES, IMPORT_TYPES, EXPORT_TYPES, EXE_TYPES, SWATCH_TYPES, CUSTOM_TYPE - }; +}; /** * Used for returning the type selected in a SaveAs */ -enum FileDialogSelectionType { +enum FileDialogSelectionType +{ SVG_NAMESPACE, SVG_NAMESPACE_WITH_EXTENSIONS - }; - +}; /** * Return true if the string ends with the given suffix @@ -80,16 +77,14 @@ bool isValidImageFile(const Glib::ustring &fileName); class FileOpenDialog { public: - - /** * Constructor .. do not call directly * @param path the directory where to start searching * @param fileTypes one of FileDialogTypes * @param title the title of the dialog */ - FileOpenDialog() - = default;; + FileOpenDialog() = default; + ; /** * Factory. @@ -97,17 +92,15 @@ public: * @param fileTypes one of FileDialogTypes * @param title the title of the dialog */ - static FileOpenDialog *create(Gtk::Window& parentWindow, - const Glib::ustring &path, - FileDialogType fileTypes, + static FileOpenDialog *create(Gtk::Window &parentWindow, const Glib::ustring &path, FileDialogType fileTypes, const char *title); - /** * Destructor. * Perform any necessary cleanups. */ - virtual ~FileOpenDialog() = default;; + virtual ~FileOpenDialog() = default; + ; /** * Show an OpenFile file selector. @@ -120,7 +113,7 @@ public: * @return a pointer to a string if successful (which must * be later freed with g_free(), else NULL. */ - virtual Inkscape::Extension::Extension * getSelectionType() = 0; + virtual Inkscape::Extension::Extension *getSelectionType() = 0; Glib::ustring getFilename(); @@ -136,12 +129,7 @@ protected: */ Glib::ustring myFilename; -}; //FileOpenDialog - - - - - +}; // FileOpenDialog /** * This class provides an implementation-independent API for @@ -150,7 +138,6 @@ protected: class FileSaveDialog { public: - /** * Constructor. Do not call directly . Use the factory. * @param path the directory where to start searching @@ -158,8 +145,8 @@ public: * @param title the title of the dialog * @param key a list of file types from which the user can select */ - FileSaveDialog () - = default;; + FileSaveDialog() = default; + ; /** * Factory. @@ -168,53 +155,47 @@ public: * @param title the title of the dialog * @param key a list of file types from which the user can select */ - static FileSaveDialog *create(Gtk::Window& parentWindow, - const Glib::ustring &path, - FileDialogType fileTypes, - const char *title, - const Glib::ustring &default_key, - const gchar *docTitle, + static FileSaveDialog *create(Gtk::Window &parentWindow, const Glib::ustring &path, FileDialogType fileTypes, + const char *title, const Glib::ustring &default_key, const gchar *docTitle, const Inkscape::Extension::FileSaveMethod save_method); - /** * Destructor. * Perform any necessary cleanups. */ - virtual ~FileSaveDialog() = default;; - + virtual ~FileSaveDialog() = default; + ; /** * Show an SaveAs file selector. * @return the selected path if user selected one, else NULL */ - virtual bool show() =0; + virtual bool show() = 0; /** * Return the 'key' (filetype) of the selection, if any * @return a pointer to a string if successful (which must * be later freed with g_free(), else NULL. */ - virtual Inkscape::Extension::Extension * getSelectionType() = 0; + virtual Inkscape::Extension::Extension *getSelectionType() = 0; - virtual void setSelectionType( Inkscape::Extension::Extension * key ) = 0; + virtual void setSelectionType(Inkscape::Extension::Extension *key) = 0; /** * Get the file name chosen by the user. Valid after an [OK] */ - Glib::ustring getFilename (); + Glib::ustring getFilename(); /** * Get the document title chosen by the user. Valid after an [OK] */ - Glib::ustring getDocTitle (); + Glib::ustring getDocTitle(); virtual Glib::ustring getCurrentDirectory() = 0; virtual void addFileType(Glib::ustring name, Glib::ustring pattern) = 0; protected: - /** * Filename that was given */ @@ -228,17 +209,15 @@ protected: /** * List of known file extensions. */ - std::map<Glib::ustring, Inkscape::Extension::Output*> knownExtensions; - - - void appendExtension(Glib::ustring& path, Inkscape::Extension::Output* outputExtension); + std::map<Glib::ustring, Inkscape::Extension::Output *> knownExtensions; -}; //FileSaveDialog + void appendExtension(Glib::ustring &path, Inkscape::Extension::Output *outputExtension); +}; // FileSaveDialog -} //namespace Dialog -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif /* __FILE_DIALOG_H__ */ diff --git a/src/ui/dialog/filedialogimpl-gtkmm.cpp b/src/ui/dialog/filedialogimpl-gtkmm.cpp index 5d205c94d82ca2065151166f7fbb97afff629440..3ee3878cfee61dc53318601eed4660114e8bd2c8 100644 --- a/src/ui/dialog/filedialogimpl-gtkmm.cpp +++ b/src/ui/dialog/filedialogimpl-gtkmm.cpp @@ -18,7 +18,7 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <iostream> +#include "filedialogimpl-gtkmm.h" #include <glibmm/convert.h> #include <glibmm/fileutils.h> @@ -26,21 +26,17 @@ #include <glibmm/miscutils.h> #include <glibmm/regex.h> #include <gtkmm/expander.h> - -#include "filedialogimpl-gtkmm.h" +#include <iostream> #include "document.h" -#include "inkscape.h" -#include "path-prefix.h" -#include "preferences.h" - #include "extension/db.h" #include "extension/input.h" #include "extension/output.h" - +#include "inkscape.h" #include "io/resource.h" #include "io/sys.h" - +#include "path-prefix.h" +#include "preferences.h" #include "ui/dialog-events.h" #include "ui/view/svg-view-widget.h" @@ -52,14 +48,10 @@ void dump_str(const gchar *str, const gchar *prefix); void dump_ustr(const Glib::ustring &ustr); #endif - - namespace Inkscape { namespace UI { namespace Dialog { - - //######################################################################## //### U T I L I T Y //######################################################################## @@ -78,7 +70,6 @@ void fileDialogExtensionToPattern(Glib::ustring &pattern, Glib::ustring &extensi } } - void findEntryWidgets(Gtk::Container *parent, std::vector<Gtk::Entry *> &result) { if (!parent) { @@ -108,7 +99,6 @@ void findExpanderWidgets(Gtk::Container *parent, std::vector<Gtk::Expander *> &r } } - /*######################################################################### ### F I L E D I A L O G B A S E C L A S S #########################################################################*/ @@ -118,7 +108,7 @@ void FileDialogBaseGtk::internalSetup() // Open executable file dialogs don't need the preview panel if (_dialogType != EXE_TYPES) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool enablePreview = prefs->getBool(preferenceBase + "/enable_preview", true); + bool enablePreview = prefs->getBool(preferenceBase + "/enable_preview", true); bool enableSVGExport = prefs->getBool(preferenceBase + "/enable_svgexport", false); previewCheckbox.set_label(Glib::ustring(_("Enable preview"))); @@ -141,7 +131,6 @@ void FileDialogBaseGtk::internalSetup() } } - void FileDialogBaseGtk::cleanup(bool showConfirmed) { if (_dialogType != EXE_TYPES) { @@ -152,7 +141,6 @@ void FileDialogBaseGtk::cleanup(bool showConfirmed) } } - void FileDialogBaseGtk::_previewEnabledCB() { bool enabled = previewCheckbox.get_active(); @@ -172,8 +160,6 @@ void FileDialogBaseGtk::_svgexportEnabledCB() prefs->setBool(preferenceBase + "/enable_svgexport", enabled); } - - /** * Callback for checking if the preview needs to be redrawn */ @@ -193,7 +179,6 @@ void FileDialogBaseGtk::_updatePreviewCallback() } } - /*######################################################################### ### F I L E O P E N #########################################################################*/ @@ -205,8 +190,6 @@ FileOpenDialogImplGtk::FileOpenDialogImplGtk(Gtk::Window &parentWindow, const Gl FileDialogType fileTypes, const Glib::ustring &title) : FileDialogBaseGtk(parentWindow, title, Gtk::FILE_CHOOSER_ACTION_OPEN, fileTypes, "/dialogs/open") { - - if (_dialogType == EXE_TYPES) { /* One file at a time */ set_select_multiple(false); @@ -225,7 +208,6 @@ FileOpenDialogImplGtk::FileOpenDialogImplGtk(Gtk::Window &parentWindow, const Gl /* Set our dialog type (open, import, etc...)*/ _dialogType = fileTypes; - /* Set the pwd and/or the filename */ if (dir.size() > 0) { Glib::ustring udir(dir); @@ -264,8 +246,7 @@ FileOpenDialogImplGtk::FileOpenDialogImplGtk(Gtk::Window &parentWindow, const Gl /** * Destructor */ -FileOpenDialogImplGtk::~FileOpenDialogImplGtk() -= default; +FileOpenDialogImplGtk::~FileOpenDialogImplGtk() = default; void FileOpenDialogImplGtk::addFilterMenu(Glib::ustring name, Glib::ustring pattern) { @@ -323,8 +304,7 @@ void FileOpenDialogImplGtk::createFilterMenu() Inkscape::Extension::DB::InputList extension_list; Inkscape::Extension::db.get_input_list(extension_list); - for (auto imod : extension_list) - { + for (auto imod : extension_list) { // FIXME: would be nice to grey them out instead of not listing them if (imod->deactivated()) continue; @@ -341,7 +321,7 @@ void FileOpenDialogImplGtk::createFilterMenu() add_filter(filter); extensionMap[uname] = imod; -// g_message("ext %s:%s '%s'\n", ioext->name, ioext->mimetype, upattern.c_str()); + // g_message("ext %s:%s '%s'\n", ioext->name, ioext->mimetype, upattern.c_str()); allInkscapeFilter->add_pattern(upattern); if (strncmp("image", imod->get_mimetype(), 5) == 0) allImageFilter->add_pattern(upattern); @@ -362,10 +342,9 @@ void FileOpenDialogImplGtk::createFilterMenu() strncmp("image/tiff", imod->get_mimetype(), 10) == 0 || strncmp("image/x-xbitmap", imod->get_mimetype(), 15) == 0 || strncmp("image/x-tga", imod->get_mimetype(), 11) == 0 || - strncmp("image/x-pcx", imod->get_mimetype(), 11) == 0) - { + strncmp("image/x-pcx", imod->get_mimetype(), 11) == 0) { allBitmapFilter->add_pattern(upattern); - } else { + } else { allVectorFilter->add_pattern(upattern); } } @@ -378,9 +357,9 @@ void FileOpenDialogImplGtk::createFilterMenu() */ bool FileOpenDialogImplGtk::show() { - set_modal(TRUE); // Window + set_modal(TRUE); // Window sp_transientize(GTK_WIDGET(gobj())); // Make transient - gint b = run(); // Dialog + gint b = run(); // Dialog svgPreview.showNoPreview(); hide(); @@ -408,8 +387,6 @@ bool FileOpenDialogImplGtk::show() } } - - /** * Get the file extension type that was selected by the user. Valid after an [OK] */ @@ -418,7 +395,6 @@ Inkscape::Extension::Extension *FileOpenDialogImplGtk::getSelectionType() return extension; } - /** * Get the file name chosen by the user. Valid after an [OK] */ @@ -427,7 +403,6 @@ Glib::ustring FileOpenDialogImplGtk::getFilename() return myFilename; } - /** * To Get Multiple filenames selected at-once. */ @@ -453,8 +428,6 @@ Glib::ustring FileOpenDialogImplGtk::getCurrentDirectory() return get_current_folder(); } - - //######################################################################## //# F I L E S A V E //######################################################################## @@ -517,7 +490,6 @@ FileSaveDialogImplGtk::FileSaveDialogImplGtk(Gtk::Window &parentWindow, const Gl fileTypeComboBox.set_size_request(200, 40); fileTypeComboBox.signal_changed().connect(sigc::mem_fun(*this, &FileSaveDialogImplGtk::fileTypeChangedCallback)); - childBox.pack_start(checksBox); childBox.pack_end(fileTypeComboBox); checksBox.pack_start(fileTypeCheckbox); @@ -538,8 +510,7 @@ FileSaveDialogImplGtk::FileSaveDialogImplGtk(Gtk::Window &parentWindow, const Gl fileNameEntry->signal_activate().connect( sigc::mem_fun(*this, &FileSaveDialogImplGtk::fileNameEntryChangedCallback)); } - signal_selection_changed().connect( - sigc::mem_fun(*this, &FileSaveDialogImplGtk::fileNameChanged)); + signal_selection_changed().connect(sigc::mem_fun(*this, &FileSaveDialogImplGtk::fileNameChanged)); // Let's do more customization std::vector<Gtk::Expander *> expanders; @@ -571,8 +542,7 @@ FileSaveDialogImplGtk::FileSaveDialogImplGtk(Gtk::Window &parentWindow, const Gl /** * Destructor */ -FileSaveDialogImplGtk::~FileSaveDialogImplGtk() -= default; +FileSaveDialogImplGtk::~FileSaveDialogImplGtk() = default; /** * Callback for fileNameEntry widget @@ -609,8 +579,6 @@ void FileSaveDialogImplGtk::fileNameEntryChangedCallback() } } - - /** * Callback for fileNameEntry widget */ @@ -629,7 +597,7 @@ void FileSaveDialogImplGtk::fileTypeChangedCallback() set_filter(filter); if (fromCB) { - //do not update if called from a name change + // do not update if called from a name change fromCB = false; return; } @@ -637,13 +605,18 @@ void FileSaveDialogImplGtk::fileTypeChangedCallback() updateNameAndExtension(); } -void FileSaveDialogImplGtk::fileNameChanged() { +void FileSaveDialogImplGtk::fileNameChanged() +{ Glib::ustring name = get_filename(); Glib::ustring::size_type pos = name.rfind('.'); - if ( pos == Glib::ustring::npos ) return; - Glib::ustring ext = name.substr( pos ).casefold(); - if (extension && Glib::ustring(dynamic_cast<Inkscape::Extension::Output *>(extension)->get_extension()).casefold() == ext ) return; - if (knownExtensions.find(ext) == knownExtensions.end()) return; + if (pos == Glib::ustring::npos) + return; + Glib::ustring ext = name.substr(pos).casefold(); + if (extension && + Glib::ustring(dynamic_cast<Inkscape::Extension::Output *>(extension)->get_extension()).casefold() == ext) + return; + if (knownExtensions.find(ext) == knownExtensions.end()) + return; fromCB = true; fileTypeComboBox.set_active_text(knownExtensions[ext]->get_filetypename(true)); } @@ -658,7 +631,6 @@ void FileSaveDialogImplGtk::addFileType(Glib::ustring name, Glib::ustring patter fileTypeComboBox.append(guessType.name); fileTypes.push_back(guessType); - fileTypeComboBox.set_active(0); fileTypeChangedCallback(); // call at least once to set the filter } @@ -678,7 +650,7 @@ void FileSaveDialogImplGtk::createFileTypeMenu() type.name = omod->get_filetypename(true); type.pattern = "*"; Glib::ustring extension = omod->get_extension(); - knownExtensions.insert(std::pair<Glib::ustring, Inkscape::Extension::Output*>(extension.casefold(), omod)); + knownExtensions.insert(std::pair<Glib::ustring, Inkscape::Extension::Output *>(extension.casefold(), omod)); fileDialogExtensionToPattern(type.pattern, extension); type.extension = omod; fileTypeComboBox.append(type.name); @@ -693,22 +665,19 @@ void FileSaveDialogImplGtk::createFileTypeMenu() fileTypeComboBox.append(guessType.name); fileTypes.push_back(guessType); - fileTypeComboBox.set_active(0); fileTypeChangedCallback(); // call at least once to set the filter } - - /** * Show this dialog modally. Return true if user hits [OK] */ bool FileSaveDialogImplGtk::show() { change_path(myFilename); - set_modal(TRUE); // Window + set_modal(TRUE); // Window sp_transientize(GTK_WIDGET(gobj())); // Make transient - gint b = run(); // Dialog + gint b = run(); // Dialog svgPreview.showNoPreview(); set_preview_widget_active(false); hide(); @@ -724,7 +693,8 @@ bool FileSaveDialogImplGtk::show() prefs->setBool("/dialogs/save_as/append_extension", fileTypeCheckbox.get_active()); } - Inkscape::Extension::store_file_extension_in_prefs((extension != nullptr ? extension->get_id() : ""), save_method); + Inkscape::Extension::store_file_extension_in_prefs((extension != nullptr ? extension->get_id() : ""), + save_method); cleanup(true); @@ -735,7 +705,6 @@ bool FileSaveDialogImplGtk::show() } } - /** * Get the file extension type that was selected by the user. Valid after an [OK] */ @@ -790,7 +759,6 @@ Glib::ustring FileSaveDialogImplGtk::getCurrentDirectory() return get_current_folder(); } - /*void FileSaveDialogImplGtk::change_title(const Glib::ustring& title) { @@ -798,8 +766,8 @@ FileSaveDialogImplGtk::change_title(const Glib::ustring& title) }*/ /** - * Change the default save path location. - */ + * Change the default save path location. + */ void FileSaveDialogImplGtk::change_path(const Glib::ustring &path) { myFilename = path; @@ -819,12 +787,9 @@ void FileSaveDialogImplGtk::change_path(const Glib::ustring &path) } Glib::ustring basename = Glib::path_get_basename(myFilename); // fprintf(stderr,"set_current_name(%s)\n",basename.c_str()); - try - { + try { set_current_name(Glib::filename_to_utf8(basename)); - } - catch (Glib::ConvertError &e) - { + } catch (Glib::ConvertError &e) { g_warning("Error converting save filename to UTF-8."); // try a fallback. set_current_name(basename); @@ -853,7 +818,6 @@ void FileSaveDialogImplGtk::updateNameAndExtension() } } - } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/filedialogimpl-gtkmm.h b/src/ui/dialog/filedialogimpl-gtkmm.h index 430f6b6eb8265fc5c6b5b4a3cbb9ffd4cf4ff76b..07d412067c0c985844f6e141b0240d6c555ed76a 100644 --- a/src/ui/dialog/filedialogimpl-gtkmm.h +++ b/src/ui/dialog/filedialogimpl-gtkmm.h @@ -18,9 +18,9 @@ #ifndef __FILE_DIALOGIMPL_H__ #define __FILE_DIALOGIMPL_H__ -//Gtk includes -#include <gtkmm/filechooserdialog.h> +// Gtk includes #include <glib/gstdio.h> +#include <gtkmm/filechooserdialog.h> #include "filedialog.h" #include "svg-preview.h" @@ -29,15 +29,15 @@ namespace Gtk { class CheckButton; class ComboBoxText; class Expander; -} +} // namespace Gtk namespace Inkscape { - class URI; +class URI; namespace UI { namespace View { - class SVGViewWidget; +class SVGViewWidget; } namespace Dialog { @@ -45,22 +45,20 @@ namespace Dialog { /*######################################################################### ### Utility #########################################################################*/ -void -fileDialogExtensionToPattern(Glib::ustring &pattern, - Glib::ustring &extension); +void fileDialogExtensionToPattern(Glib::ustring &pattern, Glib::ustring &extension); -void -findEntryWidgets(Gtk::Container *parent, - std::vector<Gtk::Entry *> &result); +void findEntryWidgets(Gtk::Container *parent, std::vector<Gtk::Entry *> &result); -void -findExpanderWidgets(Gtk::Container *parent, - std::vector<Gtk::Expander *> &result); +void findExpanderWidgets(Gtk::Container *parent, std::vector<Gtk::Expander *> &result); class FileType { - public: - FileType(): name(), pattern(),extension(nullptr) {} +public: + FileType() + : name() + , pattern() + , extension(nullptr) + {} ~FileType() = default; Glib::ustring name; Glib::ustring pattern; @@ -78,15 +76,14 @@ class FileType class FileDialogBaseGtk : public Gtk::FileChooserDialog { public: - /** * */ - FileDialogBaseGtk(Gtk::Window& parentWindow, const Glib::ustring &title, - Gtk::FileChooserAction dialogType, FileDialogType type, gchar const* preferenceBase) : - Gtk::FileChooserDialog(parentWindow, title, dialogType), - preferenceBase(preferenceBase ? preferenceBase : "unknown"), - _dialogType(type) + FileDialogBaseGtk(Gtk::Window &parentWindow, const Glib::ustring &title, Gtk::FileChooserAction dialogType, + FileDialogType type, gchar const *preferenceBase) + : Gtk::FileChooserDialog(parentWindow, title, dialogType) + , preferenceBase(preferenceBase ? preferenceBase : "unknown") + , _dialogType(type) { internalSetup(); } @@ -94,11 +91,11 @@ public: /** * */ - FileDialogBaseGtk(Gtk::Window& parentWindow, const char *title, - Gtk::FileChooserAction dialogType, FileDialogType type, gchar const* preferenceBase) : - Gtk::FileChooserDialog(parentWindow, title, dialogType), - preferenceBase(preferenceBase ? preferenceBase : "unknown"), - _dialogType(type) + FileDialogBaseGtk(Gtk::Window &parentWindow, const char *title, Gtk::FileChooserAction dialogType, + FileDialogType type, gchar const *preferenceBase) + : Gtk::FileChooserDialog(parentWindow, title, dialogType) + , preferenceBase(preferenceBase ? preferenceBase : "unknown") + , _dialogType(type) { internalSetup(); } @@ -106,11 +103,10 @@ public: /** * */ - ~FileDialogBaseGtk() override - = default; + ~FileDialogBaseGtk() override = default; protected: - void cleanup( bool showConfirmed ); + void cleanup(bool showConfirmed); Glib::ustring const preferenceBase; /** @@ -148,9 +144,6 @@ private: void _svgexportEnabledCB(); }; - - - /*######################################################################### ### F I L E O P E N #########################################################################*/ @@ -158,14 +151,13 @@ private: /** * Our implementation class for the FileOpenDialog interface.. */ -class FileOpenDialogImplGtk : public FileOpenDialog, public FileDialogBaseGtk +class FileOpenDialogImplGtk + : public FileOpenDialog + , public FileDialogBaseGtk { public: - - FileOpenDialogImplGtk(Gtk::Window& parentWindow, - const Glib::ustring &dir, - FileDialogType fileTypes, - const Glib::ustring &title); + FileOpenDialogImplGtk(Gtk::Window &parentWindow, const Glib::ustring &dir, FileDialogType fileTypes, + const Glib::ustring &title); ~FileOpenDialogImplGtk() override; @@ -177,7 +169,7 @@ public: std::vector<Glib::ustring> getFilenames() override; - Glib::ustring getCurrentDirectory() override; + Glib::ustring getCurrentDirectory() override; /// Add a custom file filter menu item /// @param name - Name of the filter (such as "Javscript") @@ -186,13 +178,11 @@ public: void addFilterMenu(Glib::ustring name, Glib::ustring pattern) override; private: - /** * Create a filter menu for this type of dialog */ void createFilterMenu(); - /** * Filter name->extension lookup */ @@ -202,11 +192,8 @@ private: * The extension to use to write this file */ Inkscape::Extension::Extension *extension; - }; - - //######################################################################## //# F I L E S A V E //######################################################################## @@ -214,16 +201,13 @@ private: /** * Our implementation of the FileSaveDialog interface. */ -class FileSaveDialogImplGtk : public FileSaveDialog, public FileDialogBaseGtk +class FileSaveDialogImplGtk + : public FileSaveDialog + , public FileDialogBaseGtk { - public: - FileSaveDialogImplGtk(Gtk::Window &parentWindow, - const Glib::ustring &dir, - FileDialogType fileTypes, - const Glib::ustring &title, - const Glib::ustring &default_key, - const gchar* docTitle, + FileSaveDialogImplGtk(Gtk::Window &parentWindow, const Glib::ustring &dir, FileDialogType fileTypes, + const Glib::ustring &title, const Glib::ustring &default_key, const gchar *docTitle, const Inkscape::Extension::FileSaveMethod save_method); ~FileSaveDialogImplGtk() override; @@ -231,14 +215,14 @@ public: bool show() override; Inkscape::Extension::Extension *getSelectionType() override; - void setSelectionType( Inkscape::Extension::Extension * key ) override; + void setSelectionType(Inkscape::Extension::Extension *key) override; - Glib::ustring getCurrentDirectory() override; - void addFileType(Glib::ustring name, Glib::ustring pattern) override; + Glib::ustring getCurrentDirectory() override; + void addFileType(Glib::ustring name, Glib::ustring pattern) override; private: - //void change_title(const Glib::ustring& title); - void change_path(const Glib::ustring& path); + // void change_title(const Glib::ustring& title); + void change_path(const Glib::ustring &path); void updateNameAndExtension(); /** @@ -252,13 +236,11 @@ private: */ Gtk::Entry *fileNameEntry; - /** * Allow the specification of the output file type */ Gtk::ComboBoxText fileTypeComboBox; - /** * Data mirror of the combo box */ @@ -280,7 +262,6 @@ private: */ void createFileTypeMenu(); - /** * The extension to use to write this file */ @@ -294,7 +275,6 @@ private: bool fromCB; }; - } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/filedialogimpl-win32.cpp b/src/ui/dialog/filedialogimpl-win32.cpp index 6d4f00b60bf8a1b20b0472a714cf4f6710322f0a..808e3ab5859991cd3d676de7d29b56ff24495411 100644 --- a/src/ui/dialog/filedialogimpl-win32.cpp +++ b/src/ui/dialog/filedialogimpl-win32.cpp @@ -24,7 +24,7 @@ #include <list> #include <vector> -//Inkscape includes +// Inkscape includes #include "display/cairo-utils.h" #include "document.h" #include "extension/db.h" @@ -35,17 +35,13 @@ #include "preferences.h" #include "util/units.h" - using namespace Glib; using namespace Cairo; using namespace Gdk::Cairo; -namespace Inkscape -{ -namespace UI -{ -namespace Dialog -{ +namespace Inkscape { +namespace UI { +namespace Dialog { const int PREVIEW_WIDENING = 150; const int WINDOW_WIDTH_MINIMUM = 32; @@ -55,21 +51,20 @@ const int WINDOW_HEIGHT_FALLBACK = 360; const char PreviewWindowClassName[] = "PreviewWnd"; const unsigned long MaxPreviewFileSize = 10240; // kB -#define IDC_SHOW_PREVIEW 1000 +#define IDC_SHOW_PREVIEW 1000 struct Filter { - gunichar2* name; + gunichar2 *name; glong name_length; - gunichar2* filter; + gunichar2 *filter; glong filter_length; - Inkscape::Extension::Extension* mod; + Inkscape::Extension::Extension *mod; }; ustring utf16_to_ustring(const wchar_t *utf16string, int utf16length = -1) { - gchar *utf8string = g_utf16_to_utf8((const gunichar2*)utf16string, - utf16length, NULL, NULL, NULL); + gchar *utf8string = g_utf16_to_utf8((const gunichar2 *)utf16string, utf16length, NULL, NULL, NULL); ustring result(utf8string); g_free(utf8string); @@ -78,11 +73,11 @@ ustring utf16_to_ustring(const wchar_t *utf16string, int utf16length = -1) namespace { -int sanitizeWindowSizeParam( int size, int delta, int minimum, int fallback ) +int sanitizeWindowSizeParam(int size, int delta, int minimum, int fallback) { int result = size; - if ( size < minimum ) { - g_warning( "Window size %d is less than cutoff.", size ); + if (size < minimum) { + g_warning("Window size %d is less than cutoff.", size); result = fallback - delta; } result += delta; @@ -95,24 +90,23 @@ int sanitizeWindowSizeParam( int size, int delta, int minimum, int fallback ) ### F I L E D I A L O G B A S E C L A S S #########################################################################*/ -FileDialogBaseWin32::FileDialogBaseWin32(Gtk::Window &parent, - const Glib::ustring &dir, const gchar *title, - FileDialogType type, gchar const* /*preferenceBase*/) : - dialogType(type), - parent(parent), - _current_directory(dir) +FileDialogBaseWin32::FileDialogBaseWin32(Gtk::Window &parent, const Glib::ustring &dir, const gchar *title, + FileDialogType type, gchar const * /*preferenceBase*/) + : dialogType(type) + , parent(parent) + , _current_directory(dir) { _main_loop = NULL; _filter_index = 1; _filter_count = 0; - _title = (wchar_t*)g_utf8_to_utf16(title, -1, NULL, NULL, NULL); + _title = (wchar_t *)g_utf8_to_utf16(title, -1, NULL, NULL, NULL); g_assert(_title != NULL); Glib::RefPtr<const Gdk::Window> parentWindow = parent.get_window(); g_assert(parentWindow->gobj() != NULL); - _ownerHwnd = (HWND)gdk_win32_window_get_handle((GdkWindow*)parentWindow->gobj()); + _ownerHwnd = (HWND)gdk_win32_window_get_handle((GdkWindow *)parentWindow->gobj()); } FileDialogBaseWin32::~FileDialogBaseWin32() @@ -139,11 +133,9 @@ bool FileOpenDialogImplWin32::_show_preview = true; /** * Constructor. Not called directly. Use the factory. */ -FileOpenDialogImplWin32::FileOpenDialogImplWin32(Gtk::Window &parent, - const Glib::ustring &dir, - FileDialogType fileTypes, - const gchar *title) : - FileDialogBaseWin32(parent, dir, title, fileTypes, "dialogs.open") +FileOpenDialogImplWin32::FileOpenDialogImplWin32(Gtk::Window &parent, const Glib::ustring &dir, + FileDialogType fileTypes, const gchar *title) + : FileDialogBaseWin32(parent, dir, title, fileTypes, "dialogs.open") { // Initialize to Autodetect _extension = NULL; @@ -168,18 +160,17 @@ FileOpenDialogImplWin32::FileOpenDialogImplWin32(Gtk::Window &parent, _mutex = NULL; if (dialogType != CUSTOM_TYPE) - createFilterMenu(); + createFilterMenu(); } - /** * Destructor */ FileOpenDialogImplWin32::~FileOpenDialogImplWin32() { - if(_filter != NULL) + if (_filter != NULL) delete[] _filter; - if(_extension_map != NULL) + if (_extension_map != NULL) delete[] _extension_map; } @@ -197,13 +188,11 @@ void FileOpenDialogImplWin32::addFilterMenu(Glib::ustring name, Glib::ustring pa int filter_length = 1; int extension_index = 0; - _extension_map = new Inkscape::Extension::Extension*[filter_count]; + _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, - -1, NULL, &all_exe_files.filter_length, NULL); + 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, -1, NULL, &all_exe_files.filter_length, NULL); all_exe_files.mod = NULL; filter_list.push_front(all_exe_files); @@ -212,21 +201,19 @@ void FileOpenDialogImplWin32::addFilterMenu(Glib::ustring name, Glib::ustring pa _filter = new wchar_t[filter_length]; wchar_t *filterptr = _filter; - for(std::list<Filter>::iterator filter_iterator = filter_list.begin(); - filter_iterator != filter_list.end(); ++filter_iterator) - { + for (std::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); + 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); + if (filter.filter != NULL) { + wcsncpy(filterptr, (wchar_t *)filter.filter, filter.filter_length); filterptr += filter.filter_length; g_free(filter.filter); } @@ -239,7 +226,7 @@ void FileOpenDialogImplWin32::addFilterMenu(Glib::ustring name, Glib::ustring pa *(filterptr++) = L'\0'; _filter_count = extension_index; - _filter_index = 1; // Select the 1st filter in the list + _filter_index = 1; // Select the 1st filter in the list } void FileOpenDialogImplWin32::createFilterMenu() @@ -271,15 +258,15 @@ void FileOpenDialogImplWin32::createFilterMenu() const gchar *all_bitmaps_filter_name = _("All Bitmaps"); // Calculate the amount of memory required - int filter_count = 5; // 5 - one for each filter type + int filter_count = 5; // 5 - one for each filter type for (Inkscape::Extension::DB::InputList::iterator current_item = extension_list.begin(); - current_item != extension_list.end(); ++current_item) - { + current_item != extension_list.end(); ++current_item) { Filter filter; Inkscape::Extension::Input *imod = *current_item; - if (imod->deactivated()) continue; + if (imod->deactivated()) + continue; // Type filter.name = g_utf8_to_utf16(imod->get_filetypename(true), -1, NULL, &filter.name_length, NULL); @@ -291,42 +278,39 @@ void FileOpenDialogImplWin32::createFilterMenu() filter.mod = imod; filter_list.push_back(filter); - filter_length += filter.name_length + filter.filter_length + 3; // Add 3 for two \0s and a * + filter_length += filter.name_length + filter.filter_length + 3; // Add 3 for two \0s and a * // Add to the "All Inkscape Files" Entry - if(all_inkscape_files_filter.length() > 0) + if (all_inkscape_files_filter.length() > 0) all_inkscape_files_filter += ";*"; all_inkscape_files_filter += file_extension_name; - if( strncmp("image", imod->get_mimetype(), 5) == 0) - { + if (strncmp("image", imod->get_mimetype(), 5) == 0) { // Add to the "All Image Files" Entry - if(all_image_files_filter.length() > 0) + if (all_image_files_filter.length() > 0) all_image_files_filter += ";*"; all_image_files_filter += file_extension_name; } // I don't know of any other way to define "bitmap" formats other than by listing them // if you change it here, do the same change in filedialogimpl-gtkmm - if ( - strncmp("image/png", imod->get_mimetype(), 9)==0 || - strncmp("image/jpeg", imod->get_mimetype(), 10)==0 || - strncmp("image/gif", imod->get_mimetype(), 9)==0 || - strncmp("image/x-icon", imod->get_mimetype(), 12)==0 || - strncmp("image/x-navi-animation", imod->get_mimetype(), 22)==0 || - strncmp("image/x-cmu-raster", imod->get_mimetype(), 18)==0 || - strncmp("image/x-xpixmap", imod->get_mimetype(), 15)==0 || - strncmp("image/bmp", imod->get_mimetype(), 9)==0 || - strncmp("image/vnd.wap.wbmp", imod->get_mimetype(), 18)==0 || - strncmp("image/tiff", imod->get_mimetype(), 10)==0 || - strncmp("image/x-xbitmap", imod->get_mimetype(), 15)==0 || - strncmp("image/x-tga", imod->get_mimetype(), 11)==0 || - strncmp("image/x-pcx", imod->get_mimetype(), 11)==0 - ) { - if(all_bitmaps_filter.length() > 0) + if (strncmp("image/png", imod->get_mimetype(), 9) == 0 || + strncmp("image/jpeg", imod->get_mimetype(), 10) == 0 || + strncmp("image/gif", imod->get_mimetype(), 9) == 0 || + strncmp("image/x-icon", imod->get_mimetype(), 12) == 0 || + strncmp("image/x-navi-animation", imod->get_mimetype(), 22) == 0 || + strncmp("image/x-cmu-raster", imod->get_mimetype(), 18) == 0 || + strncmp("image/x-xpixmap", imod->get_mimetype(), 15) == 0 || + strncmp("image/bmp", imod->get_mimetype(), 9) == 0 || + strncmp("image/vnd.wap.wbmp", imod->get_mimetype(), 18) == 0 || + strncmp("image/tiff", imod->get_mimetype(), 10) == 0 || + strncmp("image/x-xbitmap", imod->get_mimetype(), 15) == 0 || + strncmp("image/x-tga", imod->get_mimetype(), 11) == 0 || + strncmp("image/x-pcx", imod->get_mimetype(), 11) == 0) { + if (all_bitmaps_filter.length() > 0) all_bitmaps_filter += ";*"; all_bitmaps_filter += file_extension_name; } else { - if(all_vectors_filter.length() > 0) + if (all_vectors_filter.length() > 0) all_vectors_filter += ";*"; all_vectors_filter += file_extension_name; } @@ -334,59 +318,48 @@ void FileOpenDialogImplWin32::createFilterMenu() filter_count++; } - _extension_map = new Inkscape::Extension::Extension*[filter_count]; + _extension_map = new Inkscape::Extension::Extension *[filter_count]; // Filter bitmap files - all_bitmaps.name = g_utf8_to_utf16(all_bitmaps_filter_name, - -1, NULL, &all_bitmaps.name_length, NULL); - all_bitmaps.filter = g_utf8_to_utf16(all_bitmaps_filter.data(), - -1, NULL, &all_bitmaps.filter_length, NULL); + all_bitmaps.name = g_utf8_to_utf16(all_bitmaps_filter_name, -1, NULL, &all_bitmaps.name_length, NULL); + all_bitmaps.filter = g_utf8_to_utf16(all_bitmaps_filter.data(), -1, NULL, &all_bitmaps.filter_length, NULL); all_bitmaps.mod = NULL; filter_list.push_front(all_bitmaps); // Filter vector files - all_vectors.name = g_utf8_to_utf16(all_vectors_filter_name, - -1, NULL, &all_vectors.name_length, NULL); - all_vectors.filter = g_utf8_to_utf16(all_vectors_filter.data(), - -1, NULL, &all_vectors.filter_length, NULL); + all_vectors.name = g_utf8_to_utf16(all_vectors_filter_name, -1, NULL, &all_vectors.name_length, NULL); + all_vectors.filter = g_utf8_to_utf16(all_vectors_filter.data(), -1, NULL, &all_vectors.filter_length, NULL); all_vectors.mod = NULL; filter_list.push_front(all_vectors); // Filter Image Files - all_image_files.name = g_utf8_to_utf16(all_image_files_filter_name, - -1, NULL, &all_image_files.name_length, NULL); - all_image_files.filter = g_utf8_to_utf16(all_image_files_filter.data(), - -1, NULL, &all_image_files.filter_length, NULL); + all_image_files.name = + g_utf8_to_utf16(all_image_files_filter_name, -1, NULL, &all_image_files.name_length, NULL); + all_image_files.filter = + g_utf8_to_utf16(all_image_files_filter.data(), -1, NULL, &all_image_files.filter_length, NULL); all_image_files.mod = NULL; filter_list.push_front(all_image_files); // Filter Inkscape Files - all_inkscape_files.name = g_utf8_to_utf16(all_inkscape_files_filter_name, - -1, NULL, &all_inkscape_files.name_length, NULL); - all_inkscape_files.filter = g_utf8_to_utf16(all_inkscape_files_filter.data(), - -1, NULL, &all_inkscape_files.filter_length, NULL); + all_inkscape_files.name = + g_utf8_to_utf16(all_inkscape_files_filter_name, -1, NULL, &all_inkscape_files.name_length, NULL); + all_inkscape_files.filter = + g_utf8_to_utf16(all_inkscape_files_filter.data(), -1, NULL, &all_inkscape_files.filter_length, NULL); all_inkscape_files.mod = NULL; filter_list.push_front(all_inkscape_files); // Filter All Files - all_files.name = g_utf8_to_utf16(all_files_filter_name, - -1, NULL, &all_files.name_length, NULL); + all_files.name = g_utf8_to_utf16(all_files_filter_name, -1, NULL, &all_files.name_length, NULL); all_files.filter = NULL; all_files.filter_length = 0; all_files.mod = NULL; filter_list.push_front(all_files); - filter_length += all_files.name_length + 3 + - all_inkscape_files.filter_length + - all_inkscape_files.name_length + 3 + - all_image_files.filter_length + - all_image_files.name_length + 3 + - all_vectors.filter_length + - all_vectors.name_length + 3 + - all_bitmaps.filter_length + - all_bitmaps.name_length + 3 + - 1; - // Add 3 for 2*2 \0s and a *, and 1 for a trailing \0 + filter_length += all_files.name_length + 3 + all_inkscape_files.filter_length + all_inkscape_files.name_length + + 3 + all_image_files.filter_length + all_image_files.name_length + 3 + + all_vectors.filter_length + all_vectors.name_length + 3 + all_bitmaps.filter_length + + all_bitmaps.name_length + 3 + 1; + // Add 3 for 2*2 \0s and a *, and 1 for a trailing \0 } else { // Executables only ustring all_exe_files_filter = "*.exe;*.bat;*.com"; @@ -396,51 +369,44 @@ void FileOpenDialogImplWin32::createFilterMenu() const gchar *all_exe_files_filter_name = _("All Executable Files"); // Calculate the amount of memory required - int filter_count = 2; // 2 - All Files and All Executable Files + int filter_count = 2; // 2 - All Files and All Executable Files - _extension_map = new Inkscape::Extension::Extension*[filter_count]; + _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.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 All Files - all_files.name = g_utf8_to_utf16(all_files_filter_name, - -1, NULL, &all_files.name_length, NULL); + all_files.name = g_utf8_to_utf16(all_files_filter_name, -1, NULL, &all_files.name_length, NULL); all_files.filter = NULL; all_files.filter_length = 0; all_files.mod = NULL; filter_list.push_front(all_files); - filter_length += all_files.name_length + 3 + - all_exe_files.filter_length + - all_exe_files.name_length + 3 + - 1; - // Add 3 for 2*2 \0s and a *, and 1 for a trailing \0 + filter_length += all_files.name_length + 3 + all_exe_files.filter_length + all_exe_files.name_length + 3 + 1; + // Add 3 for 2*2 \0s and a *, and 1 for a trailing \0 } _filter = new wchar_t[filter_length]; wchar_t *filterptr = _filter; - for(std::list<Filter>::iterator filter_iterator = filter_list.begin(); - filter_iterator != filter_list.end(); ++filter_iterator) - { + for (std::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); + 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); + if (filter.filter != NULL) { + wcsncpy(filterptr, (wchar_t *)filter.filter, filter.filter_length); filterptr += filter.filter_length; g_free(filter.filter); } @@ -453,7 +419,7 @@ void FileOpenDialogImplWin32::createFilterMenu() *(filterptr++) = L'\0'; _filter_count = extension_index; - _filter_index = 2; // Select the 2nd filter in the list - 2 is NOT the 3rd + _filter_index = 2; // Select the 2nd filter in the list - 2 is NOT the 3rd } void FileOpenDialogImplWin32::GetOpenFileName_thread() @@ -462,17 +428,15 @@ void FileOpenDialogImplWin32::GetOpenFileName_thread() g_assert(_mutex != NULL); - WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16( - _current_directory.data(), _current_directory.length(), - NULL, NULL, NULL); + WCHAR *current_directory_string = + (WCHAR *)g_utf8_to_utf16(_current_directory.data(), _current_directory.length(), NULL, NULL, NULL); memset(&ofn, 0, sizeof(ofn)); // Copy the selected file name, converting from UTF-8 to UTF-16 memset(_path_string, 0, sizeof(_path_string)); - gunichar2* utf16_path_string = g_utf8_to_utf16( - myFilename.data(), -1, NULL, NULL, NULL); - wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH); + gunichar2 *utf16_path_string = g_utf8_to_utf16(myFilename.data(), -1, NULL, NULL, NULL); + wcsncpy(_path_string, (wchar_t *)utf16_path_string, _MAX_PATH); g_free(utf16_path_string); ofn.lStructSize = sizeof(ofn); @@ -483,7 +447,8 @@ void FileOpenDialogImplWin32::GetOpenFileName_thread() ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = current_directory_string; ofn.lpstrTitle = _title; - ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK | OFN_HIDEREADONLY | OFN_ENABLESIZING; + ofn.Flags = + OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK | OFN_HIDEREADONLY | OFN_ENABLESIZING; ofn.lpstrFilter = _filter; ofn.nFilterIndex = _filter_index; ofn.lpfnHook = GetOpenFileName_hookproc; @@ -509,80 +474,65 @@ void FileOpenDialogImplWin32::GetOpenFileName_thread() void FileOpenDialogImplWin32::register_preview_wnd_class() { HINSTANCE hInstance = GetModuleHandle(NULL); - const WNDCLASSA PreviewWndClass = - { - CS_HREDRAW | CS_VREDRAW, - preview_wnd_proc, - 0, - 0, - hInstance, - NULL, - LoadCursor(hInstance, IDC_ARROW), - (HBRUSH)(COLOR_BTNFACE + 1), - NULL, - PreviewWindowClassName - }; + const WNDCLASSA PreviewWndClass = {CS_HREDRAW | CS_VREDRAW, + preview_wnd_proc, + 0, + 0, + hInstance, + NULL, + LoadCursor(hInstance, IDC_ARROW), + (HBRUSH)(COLOR_BTNFACE + 1), + NULL, + PreviewWindowClassName}; RegisterClassA(&PreviewWndClass); } -UINT_PTR CALLBACK FileOpenDialogImplWin32::GetOpenFileName_hookproc( - HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam) +UINT_PTR CALLBACK FileOpenDialogImplWin32::GetOpenFileName_hookproc(HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam) { - FileOpenDialogImplWin32 *pImpl = reinterpret_cast<FileOpenDialogImplWin32*> - (GetWindowLongPtr(hdlg, GWLP_USERDATA)); + FileOpenDialogImplWin32 *pImpl = reinterpret_cast<FileOpenDialogImplWin32 *>(GetWindowLongPtr(hdlg, GWLP_USERDATA)); - switch(uiMsg) - { - case WM_INITDIALOG: - { + switch (uiMsg) { + case WM_INITDIALOG: { HWND hParentWnd = GetParent(hdlg); HINSTANCE hInstance = GetModuleHandle(NULL); // Set the pointer to the object - OPENFILENAMEW *ofn = reinterpret_cast<OPENFILENAMEW*>(lParam); + OPENFILENAMEW *ofn = reinterpret_cast<OPENFILENAMEW *>(lParam); SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData); SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData); - pImpl = reinterpret_cast<FileOpenDialogImplWin32*>(ofn->lCustData); + pImpl = reinterpret_cast<FileOpenDialogImplWin32 *>(ofn->lCustData); // Make the window a bit wider RECT rcRect; GetWindowRect(hParentWnd, &rcRect); // Don't show the preview when opening executable files - if ( pImpl->dialogType == EXE_TYPES) { - MoveWindow(hParentWnd, rcRect.left, rcRect.top, - rcRect.right - rcRect.left, - rcRect.bottom - rcRect.top, + if (pImpl->dialogType == EXE_TYPES) { + MoveWindow(hParentWnd, rcRect.left, rcRect.top, rcRect.right - rcRect.left, rcRect.bottom - rcRect.top, FALSE); } else { - MoveWindow(hParentWnd, rcRect.left, rcRect.top, - rcRect.right - rcRect.left + PREVIEW_WIDENING, - rcRect.bottom - rcRect.top, - FALSE); + MoveWindow(hParentWnd, rcRect.left, rcRect.top, rcRect.right - rcRect.left + PREVIEW_WIDENING, + rcRect.bottom - rcRect.top, FALSE); } // Subclass the parent pImpl->_base_window_proc = (WNDPROC)GetWindowLongPtr(hParentWnd, GWLP_WNDPROC); SetWindowLongPtr(hParentWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(file_dialog_subclass_proc)); - if ( pImpl->dialogType != EXE_TYPES) { + if (pImpl->dialogType != EXE_TYPES) { // Add a button to the toolbar pImpl->_toolbar_wnd = FindWindowEx(hParentWnd, NULL, "ToolbarWindow32", NULL); - pImpl->_show_preview_button_bitmap = LoadBitmap( - hInstance, MAKEINTRESOURCE(IDC_SHOW_PREVIEW)); + pImpl->_show_preview_button_bitmap = LoadBitmap(hInstance, MAKEINTRESOURCE(IDC_SHOW_PREVIEW)); TBADDBITMAP tbAddBitmap = {NULL, reinterpret_cast<UINT_PTR>(pImpl->_show_preview_button_bitmap)}; - const int iBitmapIndex = SendMessage(pImpl->_toolbar_wnd, - TB_ADDBITMAP, 1, (LPARAM)&tbAddBitmap); - + const int iBitmapIndex = SendMessage(pImpl->_toolbar_wnd, TB_ADDBITMAP, 1, (LPARAM)&tbAddBitmap); TBBUTTON tbButton; memset(&tbButton, 0, sizeof(TBBUTTON)); tbButton.iBitmap = iBitmapIndex; tbButton.idCommand = IDC_SHOW_PREVIEW; - tbButton.fsState = (pImpl->_show_preview ? TBSTATE_CHECKED : 0) - | TBSTATE_ENABLED; + tbButton.fsState = (pImpl->_show_preview ? TBSTATE_CHECKED : 0) | TBSTATE_ENABLED; tbButton.fsStyle = TBSTYLE_CHECK; tbButton.iString = (INT_PTR)_("Show Preview"); SendMessage(pImpl->_toolbar_wnd, TB_ADDBUTTONS, 1, (LPARAM)&tbButton); @@ -595,59 +545,48 @@ UINT_PTR CALLBACK FileOpenDialogImplWin32::GetOpenFileName_hookproc( pImpl->_file_dialog_wnd = hParentWnd; - if ( pImpl->dialogType != EXE_TYPES) { - pImpl->_preview_wnd = - CreateWindowA(PreviewWindowClassName, "", - WS_CHILD | WS_VISIBLE, - 0, 0, 100, 100, hParentWnd, NULL, hInstance, NULL); + if (pImpl->dialogType != EXE_TYPES) { + pImpl->_preview_wnd = CreateWindowA(PreviewWindowClassName, "", WS_CHILD | WS_VISIBLE, 0, 0, 100, 100, + hParentWnd, NULL, hInstance, NULL); SetWindowLongPtr(pImpl->_preview_wnd, GWLP_USERDATA, ofn->lCustData); } pImpl->_mutex->unlock(); pImpl->layout_dialog(); - } - break; - - case WM_NOTIFY: - { + } break; - OFNOTIFY *pOFNotify = reinterpret_cast<OFNOTIFY*>(lParam); - switch(pOFNotify->hdr.code) - { - case CDN_SELCHANGE: - { - if(pImpl != NULL) - { - // Get the file name - pImpl->_mutex->lock(); + case WM_NOTIFY: { + OFNOTIFY *pOFNotify = reinterpret_cast<OFNOTIFY *>(lParam); + switch (pOFNotify->hdr.code) { + case CDN_SELCHANGE: { + if (pImpl != NULL) { + // Get the file name + pImpl->_mutex->lock(); - SendMessage(pOFNotify->hdr.hwndFrom, CDM_GETFILEPATH, - sizeof(pImpl->_path_string) / sizeof(wchar_t), - (LPARAM)pImpl->_path_string); + SendMessage(pOFNotify->hdr.hwndFrom, CDM_GETFILEPATH, + sizeof(pImpl->_path_string) / sizeof(wchar_t), (LPARAM)pImpl->_path_string); - pImpl->_file_selected = true; + pImpl->_file_selected = true; - pImpl->_mutex->unlock(); - } + pImpl->_mutex->unlock(); + } + } break; } - break; - } - } - break; + } break; - case WM_CLOSE: - pImpl->_mutex->lock(); - pImpl->_preview_file_size = 0; + case WM_CLOSE: + pImpl->_mutex->lock(); + pImpl->_preview_file_size = 0; - pImpl->_file_dialog_wnd = NULL; - DestroyWindow(pImpl->_preview_wnd); - pImpl->_preview_wnd = NULL; - DeleteObject(pImpl->_show_preview_button_bitmap); - pImpl->_show_preview_button_bitmap = NULL; - pImpl->_mutex->unlock(); + pImpl->_file_dialog_wnd = NULL; + DestroyWindow(pImpl->_preview_wnd); + pImpl->_preview_wnd = NULL; + DeleteObject(pImpl->_show_preview_button_bitmap); + pImpl->_show_preview_button_bitmap = NULL; + pImpl->_mutex->unlock(); - break; + break; } // Use default dialog behaviour @@ -656,30 +595,26 @@ UINT_PTR CALLBACK FileOpenDialogImplWin32::GetOpenFileName_hookproc( LRESULT CALLBACK FileOpenDialogImplWin32::file_dialog_subclass_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - FileOpenDialogImplWin32 *pImpl = reinterpret_cast<FileOpenDialogImplWin32*> - (GetWindowLongPtr(hwnd, GWLP_USERDATA)); + FileOpenDialogImplWin32 *pImpl = reinterpret_cast<FileOpenDialogImplWin32 *>(GetWindowLongPtr(hwnd, GWLP_USERDATA)); LRESULT lResult = CallWindowProc(pImpl->_base_window_proc, hwnd, uMsg, wParam, lParam); - switch(uMsg) - { - case WM_SHOWWINDOW: - if(wParam != 0) - pImpl->layout_dialog(); - break; + switch (uMsg) { + case WM_SHOWWINDOW: + if (wParam != 0) + pImpl->layout_dialog(); + break; - case WM_SIZE: - pImpl->layout_dialog(); - break; + case WM_SIZE: + pImpl->layout_dialog(); + break; - case WM_COMMAND: - if(wParam == IDC_SHOW_PREVIEW) - { - const bool enable = SendMessage(pImpl->_toolbar_wnd, - TB_ISBUTTONCHECKED, IDC_SHOW_PREVIEW, 0) != 0; - pImpl->enable_preview(enable); - } - break; + case WM_COMMAND: + if (wParam == IDC_SHOW_PREVIEW) { + const bool enable = SendMessage(pImpl->_toolbar_wnd, TB_ISBUTTONCHECKED, IDC_SHOW_PREVIEW, 0) != 0; + pImpl->enable_preview(enable); + } + break; } return lResult; @@ -690,21 +625,18 @@ LRESULT CALLBACK FileOpenDialogImplWin32::preview_wnd_proc(HWND hwnd, UINT uMsg, const int CaptionPadding = 4; const int IconSize = 32; - FileOpenDialogImplWin32 *pImpl = reinterpret_cast<FileOpenDialogImplWin32*> - (GetWindowLongPtr(hwnd, GWLP_USERDATA)); + FileOpenDialogImplWin32 *pImpl = reinterpret_cast<FileOpenDialogImplWin32 *>(GetWindowLongPtr(hwnd, GWLP_USERDATA)); LRESULT lResult = 0; - switch(uMsg) - { - case WM_ERASEBKGND: - // Do nothing to erase the background - // - otherwise there'll be flicker - lResult = 1; - break; + switch (uMsg) { + case WM_ERASEBKGND: + // Do nothing to erase the background + // - otherwise there'll be flicker + lResult = 1; + break; - case WM_PAINT: - { + case WM_PAINT: { // Get the client rect RECT rcClient; GetClientRect(hwnd, &rcClient); @@ -713,24 +645,18 @@ LRESULT CALLBACK FileOpenDialogImplWin32::preview_wnd_proc(HWND hwnd, UINT uMsg, PAINTSTRUCT paint_struct; HDC dc = BeginPaint(hwnd, &paint_struct); - HFONT hCaptionFont = reinterpret_cast<HFONT>(SendMessage(GetParent(hwnd), - WM_GETFONT, 0, 0)); + HFONT hCaptionFont = reinterpret_cast<HFONT>(SendMessage(GetParent(hwnd), WM_GETFONT, 0, 0)); HFONT hOldFont = static_cast<HFONT>(SelectObject(dc, hCaptionFont)); SetBkMode(dc, TRANSPARENT); pImpl->_mutex->lock(); - if(pImpl->_path_string[0] == 0) - { - WCHAR* noFileText=(WCHAR*)g_utf8_to_utf16(_("No file selected"), - -1, NULL, NULL, NULL); + if (pImpl->_path_string[0] == 0) { + WCHAR *noFileText = (WCHAR *)g_utf8_to_utf16(_("No file selected"), -1, NULL, NULL, NULL); FillRect(dc, &rcClient, reinterpret_cast<HBRUSH>(COLOR_3DFACE + 1)); - DrawTextW(dc, noFileText, -1, &rcClient, - DT_CENTER | DT_VCENTER | DT_NOPREFIX); + DrawTextW(dc, noFileText, -1, &rcClient, DT_CENTER | DT_VCENTER | DT_NOPREFIX); g_free(noFileText); - } - else if(pImpl->_preview_bitmap != NULL) - { + } else if (pImpl->_preview_bitmap != NULL) { BITMAP bitmap; GetObject(pImpl->_preview_bitmap, sizeof(bitmap), &bitmap); const int destX = (rcClient.right - bitmap.bmWidth) / 2; @@ -739,17 +665,14 @@ LRESULT CALLBACK FileOpenDialogImplWin32::preview_wnd_proc(HWND hwnd, UINT uMsg, HDC hSrcDC = CreateCompatibleDC(dc); HBITMAP hOldBitmap = (HBITMAP)SelectObject(hSrcDC, pImpl->_preview_bitmap); - BitBlt(dc, destX, 0, bitmap.bmWidth, bitmap.bmHeight, - hSrcDC, 0, 0, SRCCOPY); + BitBlt(dc, destX, 0, bitmap.bmWidth, bitmap.bmHeight, hSrcDC, 0, 0, SRCCOPY); SelectObject(hSrcDC, hOldBitmap); DeleteDC(hSrcDC); // Fill in the background area - HRGN hEraseRgn = CreateRectRgn(rcClient.left, rcClient.top, - rcClient.right, rcClient.bottom); - HRGN hImageRgn = CreateRectRgn(destX, 0, - destX + bitmap.bmWidth, bitmap.bmHeight); + HRGN hEraseRgn = CreateRectRgn(rcClient.left, rcClient.top, rcClient.right, rcClient.bottom); + HRGN hImageRgn = CreateRectRgn(destX, 0, destX + bitmap.bmWidth, bitmap.bmHeight); CombineRgn(hEraseRgn, hEraseRgn, hImageRgn, RGN_DIFF); FillRgn(dc, hEraseRgn, GetSysColorBrush(COLOR_3DFACE)); @@ -758,44 +681,32 @@ LRESULT CALLBACK FileOpenDialogImplWin32::preview_wnd_proc(HWND hwnd, UINT uMsg, DeleteObject(hEraseRgn); // Draw the caption on - RECT rcCaptionRect = {rcClient.left, - rcClient.top + bitmap.bmHeight + CaptionPadding, - rcClient.right, rcClient.bottom}; + RECT rcCaptionRect = {rcClient.left, rcClient.top + bitmap.bmHeight + CaptionPadding, rcClient.right, + rcClient.bottom}; WCHAR szCaption[_MAX_FNAME + 32]; - const int iLength = pImpl->format_caption( - szCaption, sizeof(szCaption) / sizeof(WCHAR)); + const int iLength = pImpl->format_caption(szCaption, sizeof(szCaption) / sizeof(WCHAR)); - DrawTextW(dc, szCaption, iLength, &rcCaptionRect, - DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS); - } - else if(pImpl->_preview_file_icon != NULL) - { + DrawTextW(dc, szCaption, iLength, &rcCaptionRect, DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS); + } else if (pImpl->_preview_file_icon != NULL) { FillRect(dc, &rcClient, reinterpret_cast<HBRUSH>(COLOR_3DFACE + 1)); // Draw the files icon const int destX = (rcClient.right - IconSize) / 2; - DrawIconEx(dc, destX, 0, pImpl->_preview_file_icon, - IconSize, IconSize, 0, NULL, - DI_NORMAL | DI_COMPAT); + DrawIconEx(dc, destX, 0, pImpl->_preview_file_icon, IconSize, IconSize, 0, NULL, DI_NORMAL | DI_COMPAT); // Draw the caption on - RECT rcCaptionRect = {rcClient.left, - rcClient.top + IconSize + CaptionPadding, - rcClient.right, rcClient.bottom}; + RECT rcCaptionRect = {rcClient.left, rcClient.top + IconSize + CaptionPadding, rcClient.right, + rcClient.bottom}; WCHAR szFileName[_MAX_FNAME], szCaption[_MAX_FNAME + 32]; _wsplitpath(pImpl->_path_string, NULL, NULL, szFileName, NULL); - const int iLength = snwprintf(szCaption, - sizeof(szCaption), L"%ls\n%d kB", - szFileName, pImpl->_preview_file_size); + const int iLength = + snwprintf(szCaption, sizeof(szCaption), L"%ls\n%d kB", szFileName, pImpl->_preview_file_size); - DrawTextW(dc, szCaption, iLength, &rcCaptionRect, - DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS); - } - else - { + DrawTextW(dc, szCaption, iLength, &rcCaptionRect, DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS); + } else { // Can't show anything! FillRect(dc, &rcClient, reinterpret_cast<HBRUSH>(COLOR_3DFACE + 1)); } @@ -809,13 +720,13 @@ LRESULT CALLBACK FileOpenDialogImplWin32::preview_wnd_proc(HWND hwnd, UINT uMsg, break; - case WM_DESTROY: - pImpl->free_preview(); - break; + case WM_DESTROY: + pImpl->free_preview(); + break; - default: - lResult = DefWindowProc(hwnd, uMsg, wParam, lParam); - break; + default: + lResult = DefWindowProc(hwnd, uMsg, wParam, lParam); + break; } return lResult; @@ -834,13 +745,12 @@ void FileOpenDialogImplWin32::enable_preview(bool enable) layout_dialog(); // Load or unload the preview - if(enable) - { + if (enable) { _mutex->lock(); _file_selected = true; _mutex->unlock(); - } - else free_preview(); + } else + free_preview(); } void FileOpenDialogImplWin32::layout_dialog() @@ -860,7 +770,6 @@ void FileOpenDialogImplWin32::layout_dialog() HWND hFileListWnd = GetDlgItem(_file_dialog_wnd, lst2); HWND hFolderComboWnd = GetDlgItem(_file_dialog_wnd, cmb2); - RECT rcFolderComboRect; RECTPOINTS rcFileList; GetWindowRect(hFileListWnd, &rcFileList.r); @@ -869,46 +778,43 @@ void FileOpenDialogImplWin32::layout_dialog() MapWindowPoints(NULL, _file_dialog_wnd, rcFileList.p, 2); RECT rcPreview; - RECT rcBody = {rcFileList.r.left, rcFileList.r.top, - rcClient.right - iPadding, rcFileList.r.bottom}; + RECT rcBody = {rcFileList.r.left, rcFileList.r.top, rcClient.right - iPadding, rcFileList.r.bottom}; rcFileList.r.right = rcBody.right; - if(_show_preview && dialogType != EXE_TYPES) - { + if (_show_preview && dialogType != EXE_TYPES) { rcPreview.top = rcBody.top; rcPreview.left = rcClient.right - (rcBody.bottom - rcBody.top); const int iMaxExtent = (int)(MaxExtentScale * (float)(rcBody.left + rcBody.right)) + iPadding / 2; - if(rcPreview.left < iMaxExtent) rcPreview.left = iMaxExtent; + if (rcPreview.left < iMaxExtent) + rcPreview.left = iMaxExtent; rcPreview.bottom = rcBody.bottom; rcPreview.right = rcBody.right; // Re-layout the preview box _mutex->lock(); - _preview_width = rcPreview.right - rcPreview.left; - _preview_height = rcPreview.bottom - rcPreview.top; + _preview_width = rcPreview.right - rcPreview.left; + _preview_height = rcPreview.bottom - rcPreview.top; _mutex->unlock(); render_preview(); - MoveWindow(_preview_wnd, rcPreview.left, rcPreview.top, - _preview_width, _preview_height, TRUE); + MoveWindow(_preview_wnd, rcPreview.left, rcPreview.top, _preview_width, _preview_height, TRUE); rcFileList.r.right = rcPreview.left - iPadding; } // Re-layout the file list box - MoveWindow(hFileListWnd, rcFileList.r.left, rcFileList.r.top, - rcFileList.r.right - rcFileList.r.left, - rcFileList.r.bottom - rcFileList.r.top, TRUE); + MoveWindow(hFileListWnd, rcFileList.r.left, rcFileList.r.top, rcFileList.r.right - rcFileList.r.left, + rcFileList.r.bottom - rcFileList.r.top, TRUE); // Re-layout the toolbar RECTPOINTS rcToolBar; GetWindowRect(_toolbar_wnd, &rcToolBar.r); MapWindowPoints(NULL, _file_dialog_wnd, rcToolBar.p, 2); - MoveWindow(_toolbar_wnd, rcToolBar.r.left, rcToolBar.r.top, - rcToolBar.r.right - rcToolBar.r.left, rcToolBar.r.bottom - rcToolBar.r.top, TRUE); + MoveWindow(_toolbar_wnd, rcToolBar.r.left, rcToolBar.r.top, rcToolBar.r.right - rcToolBar.r.left, + rcToolBar.r.bottom - rcToolBar.r.top, TRUE); } void FileOpenDialogImplWin32::file_selected() @@ -916,26 +822,26 @@ void FileOpenDialogImplWin32::file_selected() // Destroy any previous previews free_preview(); - // Determine if the file exists DWORD attributes = GetFileAttributesW(_path_string); - if(attributes == 0xFFFFFFFF || - attributes == FILE_ATTRIBUTE_DIRECTORY) - { + if (attributes == 0xFFFFFFFF || attributes == FILE_ATTRIBUTE_DIRECTORY) { InvalidateRect(_preview_wnd, NULL, FALSE); return; } // Check the file exists and get the file size - HANDLE file_handle = CreateFileW(_path_string, GENERIC_READ, - FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if(file_handle == INVALID_HANDLE_VALUE) return; + HANDLE file_handle = + CreateFileW(_path_string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (file_handle == INVALID_HANDLE_VALUE) + return; const DWORD file_size = GetFileSize(file_handle, NULL); - if (file_size == INVALID_FILE_SIZE) return; + if (file_size == INVALID_FILE_SIZE) + return; _preview_file_size = file_size / 1024; CloseHandle(file_handle); - if(_show_preview) load_preview(); + if (_show_preview) + load_preview(); } void FileOpenDialogImplWin32::load_preview() @@ -945,13 +851,11 @@ void FileOpenDialogImplWin32::load_preview() // Try to get the file icon SHFILEINFOW fileInfo; - if(SUCCEEDED(SHGetFileInfoW(_path_string, 0, &fileInfo, - sizeof(fileInfo), SHGFI_ICON | SHGFI_LARGEICON))) + if (SUCCEEDED(SHGetFileInfoW(_path_string, 0, &fileInfo, sizeof(fileInfo), SHGFI_ICON | SHGFI_LARGEICON))) _preview_file_icon = fileInfo.hIcon; // Will this file be too big? - if(_preview_file_size > MaxPreviewFileSize) - { + if (_preview_file_size > MaxPreviewFileSize) { InvalidateRect(_preview_wnd, NULL, FALSE); return; } @@ -967,8 +871,7 @@ void FileOpenDialogImplWin32::load_preview() _preview_document_width = _preview_document_height = 0; - if ((dialogType == SVG_TYPES || dialogType == IMPORT_TYPES) && - (hasSuffix(path, svg) || hasSuffix(path, svgz))) + if ((dialogType == SVG_TYPES || dialogType == IMPORT_TYPES) && (hasSuffix(path, svg) || hasSuffix(path, svgz))) success = set_svg_preview(); else if (hasSuffix(path, emf) || hasSuffix(path, wmf)) success = set_emf_preview(); @@ -978,7 +881,8 @@ void FileOpenDialogImplWin32::load_preview() // Show no preview } - if(success) render_preview(); + if (success) + render_preview(); InvalidateRect(_preview_wnd, NULL, FALSE); } @@ -986,11 +890,11 @@ void FileOpenDialogImplWin32::load_preview() void FileOpenDialogImplWin32::free_preview() { _mutex->lock(); - if(_preview_bitmap != NULL) + if (_preview_bitmap != NULL) DeleteObject(_preview_bitmap); _preview_bitmap = NULL; - if(_preview_file_icon != NULL) + if (_preview_file_icon != NULL) DestroyIcon(_preview_file_icon); _preview_file_icon = NULL; @@ -1003,8 +907,7 @@ bool FileOpenDialogImplWin32::set_svg_preview() { const int PreviewSize = 512; - gchar *utf8string = g_utf16_to_utf8((const gunichar2*)_path_string, - _MAX_PATH, NULL, NULL, NULL); + gchar *utf8string = g_utf16_to_utf8((const gunichar2 *)_path_string, _MAX_PATH, NULL, NULL, NULL); std::unique_ptr<SPDocument> svgDoc(SPDocument::createNewDoc(utf8string, 0)); g_free(utf8string); @@ -1012,8 +915,7 @@ bool FileOpenDialogImplWin32::set_svg_preview() if (svgDoc == NULL) { return false; } - if (svgDoc->getRoot() == NULL) - { + if (svgDoc->getRoot() == NULL) { return false; } @@ -1029,10 +931,10 @@ bool FileOpenDialogImplWin32::set_svg_preview() const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX; // Now get the resized values - const int scaledSvgWidth = round(scaleFactor * svgWidth_px); + const int scaledSvgWidth = round(scaleFactor * svgWidth_px); const int scaledSvgHeight = round(scaleFactor * svgHeight_px); - const double dpi = 96*scaleFactor; + const double dpi = 96 * scaleFactor; Inkscape::Pixbuf *pixbuf = sp_generate_internal_bitmap(svgDoc.get(), NULL, 0, 0, svgWidth_px, svgHeight_px, scaledSvgWidth, scaledSvgHeight, dpi, dpi, (guint32)0xffffff00, NULL); @@ -1058,7 +960,7 @@ bool FileOpenDialogImplWin32::set_svg_preview() void FileOpenDialogImplWin32::destroy_svg_rendering(const guint8 *buffer) { g_assert(buffer != NULL); - g_free((void*)buffer); + g_free((void *)buffer); } bool FileOpenDialogImplWin32::set_image_preview() @@ -1078,9 +980,9 @@ bool FileOpenDialogImplWin32::set_image_preview() _preview_document_height = _preview_image_height; successful = true; } + } catch (const Gdk::PixbufError &) { + } catch (const Glib::FileError &) { } - catch (const Gdk::PixbufError&) {} - catch (const Glib::FileError&) {} _mutex->unlock(); @@ -1092,23 +994,21 @@ bool FileOpenDialogImplWin32::set_image_preview() // be identical to a 16 bit app's version. To do this, we use the #pragma // to adjust packing, we use a WORD for the hmf handle, and a SMALL_RECT // for the bbox rectangle. -#pragma pack( push ) -#pragma pack( 2 ) +#pragma pack(push) +#pragma pack(2) struct APMHEADER { - DWORD dwKey; - WORD hmf; - SMALL_RECT bbox; - WORD wInch; - DWORD dwReserved; - WORD wCheckSum; + DWORD dwKey; + WORD hmf; + SMALL_RECT bbox; + WORD wInch; + DWORD dwReserved; + WORD wCheckSum; }; using PAPMHEADER = APMHEADER *; -#pragma pack( pop ) +#pragma pack(pop) - -static HENHMETAFILE -MyGetEnhMetaFileW( const WCHAR *filename ) +static HENHMETAFILE MyGetEnhMetaFileW(const WCHAR *filename) { // Try open as Enhanced Metafile HENHMETAFILE hemf = GetEnhMetaFileW(filename); @@ -1123,20 +1023,20 @@ MyGetEnhMetaFileW( const WCHAR *filename ) if (!hmf) { WCHAR szTemp[MAX_PATH]; - DWORD dw = GetShortPathNameW( filename, szTemp, MAX_PATH ); + DWORD dw = GetShortPathNameW(filename, szTemp, MAX_PATH); if (dw) { - hmf = GetMetaFileW( szTemp ); + hmf = GetMetaFileW(szTemp); } } if (hmf) { // Convert Windows Metafile to Enhanced Metafile - DWORD nSize = GetMetaFileBitsEx( hmf, 0, NULL ); + DWORD nSize = GetMetaFileBitsEx(hmf, 0, NULL); if (nSize) { BYTE *lpvData = new BYTE[nSize]; if (lpvData) { - DWORD dw = GetMetaFileBitsEx( hmf, nSize, lpvData ); + DWORD dw = GetMetaFileBitsEx(hmf, nSize, lpvData); if (dw) { // Fill out a METAFILEPICT structure mp.mm = MM_ANISOTROPIC; @@ -1144,55 +1044,52 @@ MyGetEnhMetaFileW( const WCHAR *filename ) mp.yExt = 1000; mp.hMF = NULL; // Get a reference DC - hDC = GetDC( NULL ); + hDC = GetDC(NULL); // Make an enhanced metafile from the windows metafile - hemf = SetWinMetaFileBits( nSize, lpvData, hDC, &mp ); + hemf = SetWinMetaFileBits(nSize, lpvData, hDC, &mp); // Clean up - ReleaseDC( NULL, hDC ); - DeleteMetaFile( hmf ); + ReleaseDC(NULL, hDC); + DeleteMetaFile(hmf); } delete[] lpvData; + } else { + DeleteMetaFile(hmf); } - else { - DeleteMetaFile( hmf ); - } - } - else { - DeleteMetaFile( hmf ); + } else { + DeleteMetaFile(hmf); } - } - else { + } else { // Try open as Aldus Placeable Metafile HANDLE hFile; - hFile = CreateFileW( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); + hFile = CreateFileW(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { - DWORD nSize = GetFileSize( hFile, NULL ); + DWORD nSize = GetFileSize(hFile, NULL); if (nSize) { BYTE *lpvData = new BYTE[nSize]; if (lpvData) { - DWORD dw = ReadFile( hFile, lpvData, nSize, &nSize, NULL ); + DWORD dw = ReadFile(hFile, lpvData, nSize, &nSize, NULL); if (dw) { - if ( ((PAPMHEADER)lpvData)->dwKey == 0x9ac6cdd7l ) { + if (((PAPMHEADER)lpvData)->dwKey == 0x9ac6cdd7l) { // Fill out a METAFILEPICT structure mp.mm = MM_ANISOTROPIC; mp.xExt = ((PAPMHEADER)lpvData)->bbox.Right - ((PAPMHEADER)lpvData)->bbox.Left; - mp.xExt = ( mp.xExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch); + mp.xExt = (mp.xExt * 2540l) / (DWORD)(((PAPMHEADER)lpvData)->wInch); mp.yExt = ((PAPMHEADER)lpvData)->bbox.Bottom - ((PAPMHEADER)lpvData)->bbox.Top; - mp.yExt = ( mp.yExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch); + mp.yExt = (mp.yExt * 2540l) / (DWORD)(((PAPMHEADER)lpvData)->wInch); mp.hMF = NULL; // Get a reference DC - hDC = GetDC( NULL ); + hDC = GetDC(NULL); // Create an enhanced metafile from the bits - hemf = SetWinMetaFileBits( nSize, lpvData+sizeof(APMHEADER), hDC, &mp ); + hemf = SetWinMetaFileBits(nSize, lpvData + sizeof(APMHEADER), hDC, &mp); // Clean up - ReleaseDC( NULL, hDC ); + ReleaseDC(NULL, hDC); } } delete[] lpvData; } } - CloseHandle( hFile ); + CloseHandle(hFile); } } } @@ -1200,7 +1097,6 @@ MyGetEnhMetaFileW( const WCHAR *filename ) return hemf; } - bool FileOpenDialogImplWin32::set_emf_preview() { _mutex->lock(); @@ -1210,10 +1106,9 @@ bool FileOpenDialogImplWin32::set_emf_preview() DWORD w = 0; DWORD h = 0; - HENHMETAFILE hemf = MyGetEnhMetaFileW( _path_string ); + HENHMETAFILE hemf = MyGetEnhMetaFileW(_path_string); - if (hemf) - { + if (hemf) { ENHMETAHEADER emh; ZeroMemory(&emh, sizeof(emh)); ok = GetEnhMetaFileHeader(hemf, sizeof(emh), &emh) != 0; @@ -1224,15 +1119,14 @@ bool FileOpenDialogImplWin32::set_emf_preview() DeleteEnhMetaFile(hemf); } - if (ok) - { + if (ok) { const int PreviewSize = 512; // Get the size of the document const double emfWidth = w; const double emfHeight = h; - _preview_document_width = emfWidth / 2540 * 96; // width is in units of 0.01 mm + _preview_document_width = emfWidth / 2540 * 96; // width is in units of 0.01 mm _preview_document_height = emfHeight / 2540 * 96; // height is in units of 0.01 mm _preview_image_width = emfWidth; _preview_image_height = emfHeight; @@ -1256,48 +1150,47 @@ void FileOpenDialogImplWin32::render_preview() const double shaddowAlpha = 0.75; // Is the preview showing? - if(!_show_preview) + if (!_show_preview) return; // Do we have anything to render? _mutex->lock(); - if(!_preview_bitmap_image && !_preview_emf_image) - { + if (!_preview_bitmap_image && !_preview_emf_image) { _mutex->unlock(); return; } // Tidy up any previous bitmap renderings - if(_preview_bitmap != NULL) + if (_preview_bitmap != NULL) DeleteObject(_preview_bitmap); _preview_bitmap = NULL; // Calculate the size of the caption int captionHeight = 0; - if(_preview_wnd != NULL) - { + if (_preview_wnd != NULL) { RECT rcCaptionRect; WCHAR szCaption[_MAX_FNAME + 32]; - const int iLength = format_caption(szCaption, - sizeof(szCaption) / sizeof(WCHAR)); + const int iLength = format_caption(szCaption, sizeof(szCaption) / sizeof(WCHAR)); HDC dc = GetDC(_preview_wnd); DrawTextW(dc, szCaption, iLength, &rcCaptionRect, - DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_CALCRECT); + DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_CALCRECT); ReleaseDC(_preview_wnd, dc); captionHeight = rcCaptionRect.bottom - rcCaptionRect.top; } // Find the minimum scale to fit the image inside the preview area - const double scaleFactorX = ((double)_preview_width - pagePadding * 2 - blurRadius) / _preview_image_width; - const double scaleFactorY = ((double)_preview_height - pagePadding * 2 - shaddowOffsetY - halfBlurRadius - captionHeight) / _preview_image_height; + const double scaleFactorX = ((double)_preview_width - pagePadding * 2 - blurRadius) / _preview_image_width; + const double scaleFactorY = + ((double)_preview_height - pagePadding * 2 - shaddowOffsetY - halfBlurRadius - captionHeight) / + _preview_image_height; const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX; // Now get the resized values - const double scaledSvgWidth = scaleFactor * _preview_image_width; + const double scaledSvgWidth = scaleFactor * _preview_image_width; const double scaledSvgHeight = scaleFactor * _preview_image_height; const int svgX = pagePadding + halfBlurRadius; @@ -1321,108 +1214,96 @@ void FileOpenDialogImplWin32::render_preview() // Paint the background to match the dialog colour const COLORREF background = GetSysColor(COLOR_3DFACE); - context->set_source_rgb( - GetRValue(background) / 255.0, - GetGValue(background) / 255.0, - GetBValue(background) / 255.0); + context->set_source_rgb(GetRValue(background) / 255.0, GetGValue(background) / 255.0, + GetBValue(background) / 255.0); context->paint(); //----- Draw the drop shadow -----// // Left Edge x = frameX + shaddowOffsetX - halfBlurRadius; - Cairo::RefPtr<LinearGradient> leftEdgeFade = LinearGradient::create( - x, 0.0, x + blurRadius, 0.0); - leftEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0); - leftEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha); + Cairo::RefPtr<LinearGradient> leftEdgeFade = LinearGradient::create(x, 0.0, x + blurRadius, 0.0); + leftEdgeFade->add_color_stop_rgba(0, 0, 0, 0, 0); + leftEdgeFade->add_color_stop_rgba(1, 0, 0, 0, shaddowAlpha); context->set_source(leftEdgeFade); - context->rectangle (x, frameY + shaddowOffsetY + halfBlurRadius, - blurRadius, frameHeight - blurRadius); + context->rectangle(x, frameY + shaddowOffsetY + halfBlurRadius, blurRadius, frameHeight - blurRadius); context->fill(); // Right Edge x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius; - Cairo::RefPtr<LinearGradient> rightEdgeFade = LinearGradient::create( - x, 0.0, x + blurRadius, 0.0); - rightEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha); - rightEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0); + Cairo::RefPtr<LinearGradient> rightEdgeFade = LinearGradient::create(x, 0.0, x + blurRadius, 0.0); + rightEdgeFade->add_color_stop_rgba(0, 0, 0, 0, shaddowAlpha); + rightEdgeFade->add_color_stop_rgba(1, 0, 0, 0, 0); context->set_source(rightEdgeFade); - context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius, - frameY + shaddowOffsetY + halfBlurRadius, - blurRadius, frameHeight - blurRadius); + context->rectangle(frameX + frameWidth + shaddowOffsetX - halfBlurRadius, frameY + shaddowOffsetY + halfBlurRadius, + blurRadius, frameHeight - blurRadius); context->fill(); // Top Edge y = frameY + shaddowOffsetY - halfBlurRadius; - Cairo::RefPtr<LinearGradient> topEdgeFade = LinearGradient::create( - 0.0, y, 0.0, y + blurRadius); - topEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0); - topEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha); + Cairo::RefPtr<LinearGradient> topEdgeFade = LinearGradient::create(0.0, y, 0.0, y + blurRadius); + topEdgeFade->add_color_stop_rgba(0, 0, 0, 0, 0); + topEdgeFade->add_color_stop_rgba(1, 0, 0, 0, shaddowAlpha); context->set_source(topEdgeFade); - context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y, - frameWidth - blurRadius, blurRadius); + context->rectangle(frameX + shaddowOffsetX + halfBlurRadius, y, frameWidth - blurRadius, blurRadius); context->fill(); // Bottom Edge y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius; - Cairo::RefPtr<LinearGradient> bottomEdgeFade = LinearGradient::create( - 0.0, y, 0.0, y + blurRadius); - bottomEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha); - bottomEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0); + Cairo::RefPtr<LinearGradient> bottomEdgeFade = LinearGradient::create(0.0, y, 0.0, y + blurRadius); + bottomEdgeFade->add_color_stop_rgba(0, 0, 0, 0, shaddowAlpha); + bottomEdgeFade->add_color_stop_rgba(1, 0, 0, 0, 0); context->set_source(bottomEdgeFade); - context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y, - frameWidth - blurRadius, blurRadius); + context->rectangle(frameX + shaddowOffsetX + halfBlurRadius, y, frameWidth - blurRadius, blurRadius); context->fill(); // Top Left Corner x = frameX + shaddowOffsetX - halfBlurRadius; y = frameY + shaddowOffsetY - halfBlurRadius; - Cairo::RefPtr<RadialGradient> topLeftCornerFade = RadialGradient::create( - x + blurRadius, y + blurRadius, 0, x + blurRadius, y + blurRadius, blurRadius); - topLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha); - topLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0); + Cairo::RefPtr<RadialGradient> topLeftCornerFade = + RadialGradient::create(x + blurRadius, y + blurRadius, 0, x + blurRadius, y + blurRadius, blurRadius); + topLeftCornerFade->add_color_stop_rgba(0, 0, 0, 0, shaddowAlpha); + topLeftCornerFade->add_color_stop_rgba(1, 0, 0, 0, 0); context->set_source(topLeftCornerFade); - context->rectangle (x, y, blurRadius, blurRadius); + context->rectangle(x, y, blurRadius, blurRadius); context->fill(); // Top Right Corner x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius; y = frameY + shaddowOffsetY - halfBlurRadius; - Cairo::RefPtr<RadialGradient> topRightCornerFade = RadialGradient::create( - x, y + blurRadius, 0, x, y + blurRadius, blurRadius); - topRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha); - topRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0); + Cairo::RefPtr<RadialGradient> topRightCornerFade = + RadialGradient::create(x, y + blurRadius, 0, x, y + blurRadius, blurRadius); + topRightCornerFade->add_color_stop_rgba(0, 0, 0, 0, shaddowAlpha); + topRightCornerFade->add_color_stop_rgba(1, 0, 0, 0, 0); context->set_source(topRightCornerFade); - context->rectangle (x, y, blurRadius, blurRadius); + context->rectangle(x, y, blurRadius, blurRadius); context->fill(); // Bottom Left Corner x = frameX + shaddowOffsetX - halfBlurRadius; y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius; - Cairo::RefPtr<RadialGradient> bottomLeftCornerFade = RadialGradient::create( - x + blurRadius, y, 0, x + blurRadius, y, blurRadius); - bottomLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha); - bottomLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0); + Cairo::RefPtr<RadialGradient> bottomLeftCornerFade = + RadialGradient::create(x + blurRadius, y, 0, x + blurRadius, y, blurRadius); + bottomLeftCornerFade->add_color_stop_rgba(0, 0, 0, 0, shaddowAlpha); + bottomLeftCornerFade->add_color_stop_rgba(1, 0, 0, 0, 0); context->set_source(bottomLeftCornerFade); - context->rectangle (x, y, blurRadius, blurRadius); + context->rectangle(x, y, blurRadius, blurRadius); context->fill(); // Bottom Right Corner x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius; y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius; - Cairo::RefPtr<RadialGradient> bottomRightCornerFade = RadialGradient::create( - x, y, 0, x, y, blurRadius); - bottomRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha); - bottomRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0); + Cairo::RefPtr<RadialGradient> bottomRightCornerFade = RadialGradient::create(x, y, 0, x, y, blurRadius); + bottomRightCornerFade->add_color_stop_rgba(0, 0, 0, 0, shaddowAlpha); + bottomRightCornerFade->add_color_stop_rgba(1, 0, 0, 0, 0); context->set_source(bottomRightCornerFade); - context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius, - frameY + frameHeight + shaddowOffsetY - halfBlurRadius, - blurRadius, blurRadius); + context->rectangle(frameX + frameWidth + shaddowOffsetX - halfBlurRadius, + frameY + frameHeight + shaddowOffsetY - halfBlurRadius, blurRadius, blurRadius); context->fill(); // Draw the frame context->set_line_width(1); - context->rectangle (frameX, frameY, frameWidth, frameHeight); + context->rectangle(frameX, frameY, frameWidth, frameHeight); context->set_source_rgb(1.0, 1.0, 1.0); context->fill_preserve(); @@ -1430,17 +1311,14 @@ void FileOpenDialogImplWin32::render_preview() context->stroke_preserve(); // Draw the image - if(_preview_bitmap_image) // Is the image a pixbuf? + if (_preview_bitmap_image) // Is the image a pixbuf? { // Set the transformation - const Cairo::Matrix matrix( - scaleFactor, 0, - 0, scaleFactor, - svgX, svgY); - context->set_matrix (matrix); + const Cairo::Matrix matrix(scaleFactor, 0, 0, scaleFactor, svgX, svgY); + context->set_matrix(matrix); // Render the image - set_source_pixbuf (context, _preview_bitmap_image, 0, 0); + set_source_pixbuf(context, _preview_bitmap_image, 0, 0); context->paint(); // Reset the transformation @@ -1449,7 +1327,7 @@ void FileOpenDialogImplWin32::render_preview() // Draw the inner frame context->set_source_rgb(0.75, 0.75, 0.75); - context->rectangle (svgX, svgY, scaledSvgWidth, scaledSvgHeight); + context->rectangle(svgX, svgY, scaledSvgWidth, scaledSvgHeight); context->stroke(); _mutex->unlock(); @@ -1461,16 +1339,16 @@ void FileOpenDialogImplWin32::render_preview() HENHMETAFILE hemf = MyGetEnhMetaFileW(_path_string); if (hemf) { RECT rc; - rc.top = svgY+2; - rc.left = svgX+2; - rc.bottom = scaledSvgHeight-2; - rc.right = scaledSvgWidth-2; + rc.top = svgY + 2; + rc.left = svgX + 2; + rc.bottom = scaledSvgHeight - 2; + rc.right = scaledSvgWidth - 2; PlayEnhMetaFile(hMemDC, hemf, &rc); DeleteEnhMetaFile(hemf); } } - SelectObject(hMemDC, hOldBitmap) ; + SelectObject(hMemDC, hOldBitmap); DeleteDC(hMemDC); // Refresh the preview pane @@ -1482,22 +1360,21 @@ int FileOpenDialogImplWin32::format_caption(wchar_t *caption, int caption_size) wchar_t szFileName[_MAX_FNAME]; _wsplitpath(_path_string, NULL, NULL, szFileName, NULL); - return snwprintf(caption, caption_size, - L"%ls\n%d\u2009kB\n%d\u2009px \xD7 %d\u2009px", szFileName, _preview_file_size, - (int)_preview_document_width, (int)_preview_document_height); + return snwprintf(caption, caption_size, L"%ls\n%d\u2009kB\n%d\u2009px \xD7 %d\u2009px", szFileName, + _preview_file_size, (int)_preview_document_width, (int)_preview_document_height); } /** * Show this dialog modally. Return true if user hits [OK] */ -bool -FileOpenDialogImplWin32::show() +bool FileOpenDialogImplWin32::show() { // We can only run one worker thread at a time - if(_mutex != NULL) return false; + if (_mutex != NULL) + return false; -#if !GLIB_CHECK_VERSION(2,32,0) - if(!Glib::thread_supported()) +#if !GLIB_CHECK_VERSION(2, 32, 0) + if (!Glib::thread_supported()) Glib::thread_init(); #endif @@ -1506,28 +1383,28 @@ FileOpenDialogImplWin32::show() _file_selected = false; _main_loop = g_main_loop_new(g_main_context_default(), FALSE); -#if GLIB_CHECK_VERSION(2,32,0) +#if GLIB_CHECK_VERSION(2, 32, 0) _mutex = new Glib::Threads::Mutex(); - if(Glib::Threads::Thread::create(sigc::mem_fun(*this, &FileOpenDialogImplWin32::GetOpenFileName_thread))) + 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)) + if (Glib::Thread::create(sigc::mem_fun(*this, &FileOpenDialogImplWin32::GetOpenFileName_thread), true)) #endif { - while(1) - { + while (1) { g_main_context_iteration(g_main_context_default(), FALSE); - if(_mutex->trylock()) - { + if (_mutex->trylock()) { // Read mutexed data const bool finished = _finished; const bool is_file_selected = _file_selected; _file_selected = false; _mutex->unlock(); - if(finished) break; - if(is_file_selected) file_selected(); + if (finished) + break; + if (is_file_selected) + file_selected(); } Sleep(10); @@ -1544,14 +1421,13 @@ FileOpenDialogImplWin32::show() /** * To Get Multiple filenames selected at-once. */ -std::vector<Glib::ustring>FileOpenDialogImplWin32::getFilenames() +std::vector<Glib::ustring> FileOpenDialogImplWin32::getFilenames() { std::vector<Glib::ustring> result; result.push_back(getFilename()); return result; } - /*######################################################################### ### F I L E S A V E #########################################################################*/ @@ -1559,52 +1435,49 @@ std::vector<Glib::ustring>FileOpenDialogImplWin32::getFilenames() /** * Constructor */ -FileSaveDialogImplWin32::FileSaveDialogImplWin32(Gtk::Window &parent, - const Glib::ustring &dir, - FileDialogType fileTypes, - const char *title, - const Glib::ustring &/*default_key*/, - const char *docTitle, - const Inkscape::Extension::FileSaveMethod save_method) : - FileDialogBaseWin32(parent, dir, title, fileTypes, - (save_method == Inkscape::Extension::FILE_SAVE_METHOD_SAVE_COPY) ? "dialogs.save_copy" : "dialogs.save_as"), - _title_label(NULL), - _title_edit(NULL) +FileSaveDialogImplWin32::FileSaveDialogImplWin32(Gtk::Window &parent, const Glib::ustring &dir, + FileDialogType fileTypes, const char *title, + const Glib::ustring & /*default_key*/, const char *docTitle, + const Inkscape::Extension::FileSaveMethod save_method) + : FileDialogBaseWin32(parent, dir, title, fileTypes, + (save_method == Inkscape::Extension::FILE_SAVE_METHOD_SAVE_COPY) ? "dialogs.save_copy" + : "dialogs.save_as") + , _title_label(NULL) + , _title_edit(NULL) { FileSaveDialog::myDocTitle = docTitle; createFilterMenu(); /* The code below sets the default file name */ - myFilename = ""; - if (dir.size() > 0) { - Glib::ustring udir(dir); - Glib::ustring::size_type len = udir.length(); - // leaving a trailing backslash on the directory name leads to the infamous - // double-directory bug on win32 - if (len != 0 && udir[len - 1] == '\\') udir.erase(len - 1); - - // Remove the extension: remove everything past the last period found past the last slash - // (not for CUSTOM_TYPE as we can not automatically add a file extension in that case yet) - if (dialogType == CUSTOM_TYPE) { - myFilename = udir; - } else { - size_t last_slash_index = udir.find_last_of( '\\' ); - size_t last_period_index = udir.find_last_of( '.' ); - if (last_period_index > last_slash_index) { - myFilename = udir.substr(0, last_period_index ); - } + myFilename = ""; + if (dir.size() > 0) { + Glib::ustring udir(dir); + Glib::ustring::size_type len = udir.length(); + // leaving a trailing backslash on the directory name leads to the infamous + // double-directory bug on win32 + if (len != 0 && udir[len - 1] == '\\') + udir.erase(len - 1); + + // Remove the extension: remove everything past the last period found past the last slash + // (not for CUSTOM_TYPE as we can not automatically add a file extension in that case yet) + if (dialogType == CUSTOM_TYPE) { + myFilename = udir; + } else { + size_t last_slash_index = udir.find_last_of('\\'); + size_t last_period_index = udir.find_last_of('.'); + if (last_period_index > last_slash_index) { + myFilename = udir.substr(0, last_period_index); } + } - // remove one slash if double - if (1 + myFilename.find("\\\\",2)) { - myFilename.replace(myFilename.find("\\\\",2), 1, ""); - } + // remove one slash if double + if (1 + myFilename.find("\\\\", 2)) { + myFilename.replace(myFilename.find("\\\\", 2), 1, ""); } + } } -FileSaveDialogImplWin32::~FileSaveDialogImplWin32() -{ -} +FileSaveDialogImplWin32::~FileSaveDialogImplWin32() {} void FileSaveDialogImplWin32::createFilterMenu() { @@ -1621,10 +1494,10 @@ void FileSaveDialogImplWin32::createFilterMenu() int filter_length = 1; for (Inkscape::Extension::DB::OutputList::iterator current_item = extension_list.begin(); - current_item != extension_list.end(); ++current_item) - { + current_item != extension_list.end(); ++current_item) { Inkscape::Extension::Output *omod = *current_item; - if (omod->deactivated()) continue; + if (omod->deactivated()) + continue; filter_count++; @@ -1632,40 +1505,38 @@ void FileSaveDialogImplWin32::createFilterMenu() // Extension const gchar *filter_extension = omod->get_extension(); - filter.filter = g_utf8_to_utf16( - filter_extension, -1, NULL, &filter.filter_length, NULL); - knownExtensions.insert(std::pair<Glib::ustring, Inkscape::Extension::Output*>(Glib::ustring(filter_extension).casefold(), omod)); + filter.filter = g_utf8_to_utf16(filter_extension, -1, NULL, &filter.filter_length, NULL); + knownExtensions.insert( + std::pair<Glib::ustring, Inkscape::Extension::Output *>(Glib::ustring(filter_extension).casefold(), omod)); // Type filter.name = g_utf8_to_utf16(omod->get_filetypename(true), -1, NULL, &filter.name_length, NULL); filter.mod = omod; - filter_length += filter.name_length + - filter.filter_length + 3; // Add 3 for two \0s and a * + filter_length += filter.name_length + filter.filter_length + 3; // Add 3 for two \0s and a * filter_list.push_back(filter); } int extension_index = 0; - _extension_map = new Inkscape::Extension::Extension*[filter_count]; + _extension_map = new Inkscape::Extension::Extension *[filter_count]; _filter = new wchar_t[filter_length]; wchar_t *filterptr = _filter; - for(std::list<Filter>::iterator filter_iterator = filter_list.begin(); - filter_iterator != filter_list.end(); ++filter_iterator) - { + for (std::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); + wcsncpy(filterptr, (wchar_t *)filter.name, filter.name_length); filterptr += filter.name_length; g_free(filter.name); *(filterptr++) = L'\0'; *(filterptr++) = L'*'; - wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length); + wcsncpy(filterptr, (wchar_t *)filter.filter, filter.filter_length); filterptr += filter.filter_length; g_free(filter.filter); @@ -1677,10 +1548,9 @@ void FileSaveDialogImplWin32::createFilterMenu() *(filterptr++) = 0; _filter_count = extension_index; - _filter_index = 1; // A value of 1 selects the 1st filter - NOT the 2nd + _filter_index = 1; // A value of 1 selects the 1st filter - NOT the 2nd } - void FileSaveDialogImplWin32::addFileType(Glib::ustring name, Glib::ustring pattern) { std::list<Filter> filter_list; @@ -1697,38 +1567,35 @@ void FileSaveDialogImplWin32::addFileType(Glib::ustring name, Glib::ustring patt int filter_length = 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, - -1, NULL, &all_exe_files.filter_length, NULL); + 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, -1, NULL, &all_exe_files.filter_length, NULL); all_exe_files.mod = NULL; filter_list.push_front(all_exe_files); filter_length = all_exe_files.name_length + all_exe_files.filter_length + 3; // Add 3 for two \0s and a * - knownExtensions.insert(std::pair<Glib::ustring, Inkscape::Extension::Output*>(Glib::ustring(all_exe_files_filter).casefold(), NULL)); + knownExtensions.insert( + std::pair<Glib::ustring, Inkscape::Extension::Output *>(Glib::ustring(all_exe_files_filter).casefold(), NULL)); int extension_index = 0; - _extension_map = new Inkscape::Extension::Extension*[filter_count]; + _extension_map = new Inkscape::Extension::Extension *[filter_count]; _filter = new wchar_t[filter_length]; wchar_t *filterptr = _filter; - for(std::list<Filter>::iterator filter_iterator = filter_list.begin(); - filter_iterator != filter_list.end(); ++filter_iterator) - { + for (std::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); + 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); + if (filter.filter != NULL) { + wcsncpy(filterptr, (wchar_t *)filter.filter, filter.filter_length); filterptr += filter.filter_length; g_free(filter.filter); } @@ -1741,9 +1608,7 @@ void FileSaveDialogImplWin32::addFileType(Glib::ustring name, Glib::ustring patt *(filterptr++) = L'\0'; _filter_count = extension_index; - _filter_index = 1; // Select the 1st filter in the list - - + _filter_index = 1; // Select the 1st filter in the list } void FileSaveDialogImplWin32::GetSaveFileName_thread() @@ -1752,15 +1617,13 @@ void FileSaveDialogImplWin32::GetSaveFileName_thread() g_assert(_main_loop != NULL); - WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16( - _current_directory.data(), _current_directory.length(), - NULL, NULL, NULL); + WCHAR *current_directory_string = + (WCHAR *)g_utf8_to_utf16(_current_directory.data(), _current_directory.length(), NULL, NULL, NULL); // Copy the selected file name, converting from UTF-8 to UTF-16 memset(_path_string, 0, sizeof(_path_string)); - gunichar2* utf16_path_string = g_utf8_to_utf16( - myFilename.data(), -1, NULL, NULL, NULL); - wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH); + gunichar2 *utf16_path_string = g_utf8_to_utf16(myFilename.data(), -1, NULL, NULL, NULL); + wcsncpy(_path_string, (wchar_t *)utf16_path_string, _MAX_PATH); g_free(utf16_path_string); ZeroMemory(&ofn, sizeof(ofn)); @@ -1797,50 +1660,42 @@ void FileSaveDialogImplWin32::GetSaveFileName_thread() /** * Show this dialog modally. Return true if user hits [OK] */ -bool -FileSaveDialogImplWin32::show() +bool FileSaveDialogImplWin32::show() { -#if !GLIB_CHECK_VERSION(2,32,0) - if(!Glib::thread_supported()) +#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))) + 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)) + if (Glib::Thread::create(sigc::mem_fun(*this, &FileSaveDialogImplWin32::GetSaveFileName_thread), true)) #endif g_main_loop_run(_main_loop); - if(_result && _extension) - appendExtension(myFilename, (Inkscape::Extension::Output*)_extension); + if (_result && _extension) + appendExtension(myFilename, (Inkscape::Extension::Output *)_extension); } return _result; } -void FileSaveDialogImplWin32::setSelectionType( Inkscape::Extension::Extension * /*key*/ ) +void FileSaveDialogImplWin32::setSelectionType(Inkscape::Extension::Extension * /*key*/) { // If no pointer to extension is passed in, look up based on filename extension. - } - -UINT_PTR CALLBACK FileSaveDialogImplWin32::GetSaveFileName_hookproc( - HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam) +UINT_PTR CALLBACK FileSaveDialogImplWin32::GetSaveFileName_hookproc(HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam) { - FileSaveDialogImplWin32 *pImpl = reinterpret_cast<FileSaveDialogImplWin32*> - (GetWindowLongPtr(hdlg, GWLP_USERDATA)); + FileSaveDialogImplWin32 *pImpl = reinterpret_cast<FileSaveDialogImplWin32 *>(GetWindowLongPtr(hdlg, GWLP_USERDATA)); - switch(uiMsg) - { - case WM_INITDIALOG: - { + switch (uiMsg) { + case WM_INITDIALOG: { HWND hParentWnd = GetParent(hdlg); HINSTANCE hInstance = GetModuleHandle(NULL); @@ -1851,78 +1706,80 @@ UINT_PTR CALLBACK FileSaveDialogImplWin32::GetSaveFileName_hookproc( GetWindowRect(GetDlgItem(hParentWnd, stc2), &rST); GetWindowRect(hdlg, &rROOT); int ydelta = rCB1.top - rEDT1.top; - if ( ydelta < 0 ) { + if (ydelta < 0) { g_warning("Negative dialog ydelta"); ydelta = 0; } // Make the window a bit longer - // Note: we have a width delta of 1 because there is a suspicion that MoveWindow() to the same size causes zero-width results. + // Note: we have a width delta of 1 because there is a suspicion that MoveWindow() to the same size causes + // zero-width results. RECT rcRect; GetWindowRect(hParentWnd, &rcRect); - MoveWindow(hParentWnd, rcRect.left, rcRect.top, - sanitizeWindowSizeParam( rcRect.right - rcRect.left, 1, WINDOW_WIDTH_MINIMUM, WINDOW_WIDTH_FALLBACK ), - sanitizeWindowSizeParam( rcRect.bottom - rcRect.top, ydelta, WINDOW_HEIGHT_MINIMUM, WINDOW_HEIGHT_FALLBACK ), - FALSE); + MoveWindow( + hParentWnd, rcRect.left, rcRect.top, + sanitizeWindowSizeParam(rcRect.right - rcRect.left, 1, WINDOW_WIDTH_MINIMUM, WINDOW_WIDTH_FALLBACK), + sanitizeWindowSizeParam(rcRect.bottom - rcRect.top, ydelta, WINDOW_HEIGHT_MINIMUM, + WINDOW_HEIGHT_FALLBACK), + FALSE); // It is not necessary to delete stock objects by calling DeleteObject HGDIOBJ dlgFont = GetStockObject(DEFAULT_GUI_FONT); // Set the pointer to the object - OPENFILENAMEW *ofn = reinterpret_cast<OPENFILENAMEW*>(lParam); + OPENFILENAMEW *ofn = reinterpret_cast<OPENFILENAMEW *>(lParam); SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData); SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData); - pImpl = reinterpret_cast<FileSaveDialogImplWin32*>(ofn->lCustData); + pImpl = reinterpret_cast<FileSaveDialogImplWin32 *>(ofn->lCustData); // Create the Title label and edit control wchar_t *title_label_str = (wchar_t *)g_utf8_to_utf16(_("Title:"), -1, NULL, NULL, NULL); - pImpl->_title_label = CreateWindowExW(0, L"STATIC", title_label_str, - WS_VISIBLE|WS_CHILD, - CW_USEDEFAULT, CW_USEDEFAULT, rCB1.left-rST.left, rST.bottom-rST.top, - hParentWnd, NULL, hInstance, NULL); + pImpl->_title_label = + CreateWindowExW(0, L"STATIC", title_label_str, WS_VISIBLE | WS_CHILD, CW_USEDEFAULT, CW_USEDEFAULT, + rCB1.left - rST.left, rST.bottom - rST.top, hParentWnd, NULL, hInstance, NULL); g_free(title_label_str); - if(pImpl->_title_label) { - if(dlgFont) SendMessage(pImpl->_title_label, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0)); - SetWindowPos(pImpl->_title_label, NULL, rST.left-rROOT.left, rST.top+ydelta-rROOT.top, - rCB1.left-rST.left, rST.bottom-rST.top, SWP_SHOWWINDOW|SWP_NOZORDER); + if (pImpl->_title_label) { + if (dlgFont) + SendMessage(pImpl->_title_label, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0)); + SetWindowPos(pImpl->_title_label, NULL, rST.left - rROOT.left, rST.top + ydelta - rROOT.top, + rCB1.left - rST.left, rST.bottom - rST.top, SWP_SHOWWINDOW | SWP_NOZORDER); } - pImpl->_title_edit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", - WS_VISIBLE|WS_CHILD|WS_TABSTOP|ES_AUTOHSCROLL, - CW_USEDEFAULT, CW_USEDEFAULT, rCB1.right-rCB1.left, rCB1.bottom-rCB1.top, - hParentWnd, NULL, hInstance, NULL); - if(pImpl->_title_edit) { - if(dlgFont) SendMessage(pImpl->_title_edit, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0)); - SetWindowPos(pImpl->_title_edit, NULL, rCB1.left-rROOT.left, rCB1.top+ydelta-rROOT.top, - rCB1.right-rCB1.left, rCB1.bottom-rCB1.top, SWP_SHOWWINDOW|SWP_NOZORDER); - SetWindowTextW(pImpl->_title_edit, - (const wchar_t*)g_utf8_to_utf16(pImpl->myDocTitle.c_str(), -1, NULL, NULL, NULL)); + pImpl->_title_edit = CreateWindowEx( + WS_EX_CLIENTEDGE, "EDIT", "", WS_VISIBLE | WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL, CW_USEDEFAULT, + CW_USEDEFAULT, rCB1.right - rCB1.left, rCB1.bottom - rCB1.top, hParentWnd, NULL, hInstance, NULL); + if (pImpl->_title_edit) { + if (dlgFont) + SendMessage(pImpl->_title_edit, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0)); + SetWindowPos(pImpl->_title_edit, NULL, rCB1.left - rROOT.left, rCB1.top + ydelta - rROOT.top, + rCB1.right - rCB1.left, rCB1.bottom - rCB1.top, SWP_SHOWWINDOW | SWP_NOZORDER); + SetWindowTextW(pImpl->_title_edit, + (const wchar_t *)g_utf8_to_utf16(pImpl->myDocTitle.c_str(), -1, NULL, NULL, NULL)); } - } - break; - case WM_DESTROY: - { - if(pImpl->_title_edit) { - int length = GetWindowTextLengthW(pImpl->_title_edit)+1; - wchar_t* temp_title = new wchar_t[length]; - GetWindowTextW(pImpl->_title_edit, temp_title, length); - pImpl->myDocTitle = g_utf16_to_utf8((gunichar2*)temp_title, -1, NULL, NULL, NULL); - delete[] temp_title; - DestroyWindow(pImpl->_title_label); - pImpl->_title_label = NULL; - DestroyWindow(pImpl->_title_edit); - pImpl->_title_edit = NULL; - } - } - break; + } break; + case WM_DESTROY: { + if (pImpl->_title_edit) { + int length = GetWindowTextLengthW(pImpl->_title_edit) + 1; + wchar_t *temp_title = new wchar_t[length]; + GetWindowTextW(pImpl->_title_edit, temp_title, length); + pImpl->myDocTitle = g_utf16_to_utf8((gunichar2 *)temp_title, -1, NULL, NULL, NULL); + delete[] temp_title; + DestroyWindow(pImpl->_title_label); + pImpl->_title_label = NULL; + DestroyWindow(pImpl->_title_edit); + pImpl->_title_edit = NULL; + } + } break; } // Use default dialog behaviour return 0; } -} } } // namespace Dialog, UI, Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif // ifdef _WIN32 diff --git a/src/ui/dialog/filedialogimpl-win32.h b/src/ui/dialog/filedialogimpl-win32.h index 9dedaa30c4d723dca54487ce6db0850eba4e0feb..be26f88b4badf6248ee116e2031f57cebe0d2e76 100644 --- a/src/ui/dialog/filedialogimpl-win32.h +++ b/src/ui/dialog/filedialogimpl-win32.h @@ -15,19 +15,14 @@ #ifdef _WIN32 +#include <windows.h> + #include "filedialogimpl-gtkmm.h" - #include "inkgc/gc-core.h" -#include <windows.h> - - -namespace Inkscape -{ -namespace UI -{ -namespace Dialog -{ +namespace Inkscape { +namespace UI { +namespace Dialog { /*######################################################################### ### F I L E D I A L O G B A S E C L A S S @@ -44,29 +39,26 @@ protected: /// @param title The title caption for the dialog in UTF-8 /// @param type The dialog type /// @param preferenceBase The preferences key - FileDialogBaseWin32(Gtk::Window &parent, const Glib::ustring &dir, - const char *title, FileDialogType type, - gchar const *preferenceBase); + FileDialogBaseWin32(Gtk::Window &parent, const Glib::ustring &dir, const char *title, FileDialogType type, + gchar const *preferenceBase); /// Destructor ~FileDialogBaseWin32(); public: - /// Gets the currently selected extension. Valid after an [OK] /// @return Returns a pointer to the selected extension, or NULL /// if the selected filter requires an automatic type detection - Inkscape::Extension::Extension* getSelectionType(); + Inkscape::Extension::Extension *getSelectionType(); /// Get the path of the current directory Glib::ustring getCurrentDirectory(); - protected: /// The dialog type FileDialogType dialogType; - /// A pointer to the GTK main-loop context object. This + /// A pointer to the GTK main-loop context object. This /// is used to keep the rest of the inkscape UI running /// while the file dialog is displayed GMainLoop *_main_loop; @@ -95,12 +87,12 @@ protected: wchar_t *_filter; /// The index of the currently selected filter. - /// This value must be greater than or equal to 1, - /// and less than or equal to _filter_count. + /// This value must be greater than or equal to 1, + /// and less than or equal to _filter_count. unsigned int _filter_index; - /// The number of filters registered - unsigned int _filter_count; + /// The number of filters registered + unsigned int _filter_count; /// An array of the extensions associated with the /// file types of each filter. So the Nth entry of @@ -109,17 +101,18 @@ protected: /// specified/ Inkscape::Extension::Extension **_extension_map; - /// The currently selected extension. Valid after an [OK] + /// The currently selected extension. Valid after an [OK] Inkscape::Extension::Extension *_extension; }; - /*######################################################################### ### F I L E O P E N #########################################################################*/ /// An Inkscape compatible wrapper around MS Windows GetOpenFileName API -class FileOpenDialogImplWin32 : public FileOpenDialog, public FileDialogBaseWin32 +class FileOpenDialogImplWin32 + : public FileOpenDialog + , public FileDialogBaseWin32 { public: /// Constructor @@ -127,10 +120,7 @@ public: /// @param dir The directory to begin browing from /// @param title The title caption for the dialog in UTF-8 /// @param type The dialog type - FileOpenDialogImplWin32(Gtk::Window &parent, - const Glib::ustring &dir, - FileDialogType fileTypes, - const char *title); + FileOpenDialogImplWin32(Gtk::Window &parent, const Glib::ustring &dir, FileDialogType fileTypes, const char *title); /// Destructor virtual ~FileOpenDialogImplWin32(); @@ -147,15 +137,12 @@ public: std::vector<Glib::ustring> getFilenames(); /// Get the path of the current directory - virtual Glib::ustring getCurrentDirectory() - { return FileDialogBaseWin32::getCurrentDirectory(); } + virtual Glib::ustring getCurrentDirectory() { return FileDialogBaseWin32::getCurrentDirectory(); } /// Gets the currently selected extension. Valid after an [OK] /// @return Returns a pointer to the selected extension, or NULL /// if the selected filter requires an automatic type detection - virtual Inkscape::Extension::Extension* getSelectionType() - { return FileDialogBaseWin32::getSelectionType(); } - + virtual Inkscape::Extension::Extension *getSelectionType() { return FileDialogBaseWin32::getSelectionType(); } /// Add a custom file filter menu item /// @param name - Name of the filter (such as "Javscript") @@ -164,11 +151,9 @@ public: virtual void addFilterMenu(Glib::ustring name, Glib::ustring pattern); private: - /// Create filter menu for this type of dialog void createFilterMenu(); - /// The handle of the preview pane window HWND _preview_wnd; @@ -190,7 +175,6 @@ private: /// shown, or false when it should be hidden static bool _show_preview; - /// The current width of the preview pane in pixels int _preview_width; @@ -207,7 +191,6 @@ private: /// The size of the preview file in kilobytes unsigned long _preview_file_size; - /// The width of the document to be shown in the preview panel double _preview_document_width; @@ -226,20 +209,19 @@ private: /// This flag is set true if a file has been selected bool _file_selected; - /// This flag is set true when the GetOpenFileName call + /// This flag is set true when the GetOpenFileName call /// has returned bool _finished; /// 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) +#if GLIB_CHECK_VERSION(2, 32, 0) Glib::Threads::Mutex *_mutex; #else Glib::Mutex *_mutex; #endif - /// The controller function for the thread which calls /// GetOpenFileName void GetOpenFileName_thread(); @@ -315,22 +297,18 @@ private: int format_caption(wchar_t *caption, int caption_size); }; - /*######################################################################### ### F I L E S A V E #########################################################################*/ /// An Inkscape compatible wrapper around MS Windows GetSaveFileName API -class FileSaveDialogImplWin32 : public FileSaveDialog, public FileDialogBaseWin32 +class FileSaveDialogImplWin32 + : public FileSaveDialog + , public FileDialogBaseWin32 { - public: - FileSaveDialogImplWin32(Gtk::Window &parent, - const Glib::ustring &dir, - FileDialogType fileTypes, - const char *title, - const Glib::ustring &default_key, - const char *docTitle, + FileSaveDialogImplWin32(Gtk::Window &parent, const Glib::ustring &dir, FileDialogType fileTypes, const char *title, + const Glib::ustring &default_key, const char *docTitle, const Inkscape::Extension::FileSaveMethod save_method); /// Destructor @@ -343,21 +321,19 @@ public: bool show(); /// Get the path of the current directory - virtual Glib::ustring getCurrentDirectory() - { return FileDialogBaseWin32::getCurrentDirectory(); } + virtual Glib::ustring getCurrentDirectory() { return FileDialogBaseWin32::getCurrentDirectory(); } /// Gets the currently selected extension. Valid after an [OK] /// @return Returns a pointer to the selected extension, or NULL /// if the selected filter requires an automatic type detection - virtual Inkscape::Extension::Extension* getSelectionType() - { return FileDialogBaseWin32::getSelectionType(); } + virtual Inkscape::Extension::Extension *getSelectionType() { return FileDialogBaseWin32::getSelectionType(); } - virtual void setSelectionType( Inkscape::Extension::Extension *key ); + 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 + /// A handle to the title label and edit box HWND _title_label; HWND _title_edit; @@ -371,13 +347,11 @@ private: /// A message proc which is called by the standard dialog /// proc static UINT_PTR CALLBACK GetSaveFileName_hookproc(HWND hdlg, UINT uiMsg, WPARAM wParam, LPARAM lParam); - }; - -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/dialog/fill-and-stroke.cpp b/src/ui/dialog/fill-and-stroke.cpp index ad90f9eeed817e924c32b1090e32525a87ad6ed4..51060323bc0d81f6fe82f426ab5454fc0dec5e88 100644 --- a/src/ui/dialog/fill-and-stroke.cpp +++ b/src/ui/dialog/fill-and-stroke.cpp @@ -16,24 +16,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "fill-and-stroke.h" #include "desktop-style.h" #include "document.h" -#include "fill-and-stroke.h" #include "filter-chemistry.h" #include "inkscape.h" #include "preferences.h" -#include "verbs.h" - #include "svg/css-ostringstream.h" - #include "ui/icon-loader.h" #include "ui/icon-names.h" - #include "ui/widget/fill-style.h" -#include "ui/widget/stroke-style.h" #include "ui/widget/notebook-page.h" - +#include "ui/widget/stroke-style.h" +#include "verbs.h" namespace Inkscape { namespace UI { @@ -45,10 +41,8 @@ FillAndStroke::FillAndStroke() , _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::ISOLATION | - UI::Widget::SimpleFilterModifier::BLEND | - UI::Widget::SimpleFilterModifier::BLUR | - UI::Widget::SimpleFilterModifier::OPACITY) + UI::Widget::SimpleFilterModifier::ISOLATION | UI::Widget::SimpleFilterModifier::BLEND | + UI::Widget::SimpleFilterModifier::BLUR | UI::Widget::SimpleFilterModifier::OPACITY) , targetDesktop(nullptr) , fillWdgt(nullptr) , strokeWdgt(nullptr) @@ -59,7 +53,8 @@ FillAndStroke::FillAndStroke() _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_stroke_style, + _createPageTabLabel(_("Stroke st_yle"), INKSCAPE_ICON("object-stroke-style"))); _notebook.set_vexpand(true); _notebook.signal_switch_page().connect(sigc::mem_fun(this, &FillAndStroke::_onSwitchPage)); @@ -75,9 +70,7 @@ FillAndStroke::FillAndStroke() _composite_settings.setSubject(&_subject); } -FillAndStroke::~FillAndStroke() -{ -} +FillAndStroke::~FillAndStroke() {} void FillAndStroke::setDesktop(SPDesktop *desktop) { @@ -103,30 +96,26 @@ void FillAndStroke::_onSwitchPage(Gtk::Widget * /*page*/, guint pagenum) _savePagePref(pagenum); } -void -FillAndStroke::_savePagePref(guint page_num) +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() +void FillAndStroke::_layoutPageFill() { fillWdgt = Gtk::manage(new UI::Widget::FillNStroke(FILL)); _page_fill->table().attach(*fillWdgt, 0, 0, 1, 1); } -void -FillAndStroke::_layoutPageStrokePaint() +void FillAndStroke::_layoutPageStrokePaint() { strokeWdgt = Gtk::manage(new UI::Widget::FillNStroke(STROKE)); _page_stroke_paint->table().attach(*strokeWdgt, 0, 0, 1, 1); } -void -FillAndStroke::_layoutPageStrokeStyle() +void FillAndStroke::_layoutPageStrokeStyle() { strokeStyleWdgt = Gtk::manage(new UI::Widget::StrokeStyle()); strokeStyleWdgt->set_hexpand(); @@ -135,34 +124,28 @@ FillAndStroke::_layoutPageStrokeStyle() _page_stroke_style->table().attach(*strokeStyleWdgt, 0, 0, 1, 1); } -void -FillAndStroke::showPageFill() +void FillAndStroke::showPageFill() { present(); _notebook.set_current_page(0); _savePagePref(0); - } -void -FillAndStroke::showPageStrokePaint() +void FillAndStroke::showPageStrokePaint() { present(); _notebook.set_current_page(1); _savePagePref(1); } -void -FillAndStroke::showPageStrokeStyle() +void FillAndStroke::showPageStrokeStyle() { present(); _notebook.set_current_page(2); _savePagePref(2); - } -Gtk::HBox& -FillAndStroke::_createPageTabLabel(const Glib::ustring& label, const char *label_image) +Gtk::HBox &FillAndStroke::_createPageTabLabel(const Glib::ustring &label, const char *label_image) { Gtk::HBox *_tab_label_box = Gtk::manage(new Gtk::HBox(false, 4)); diff --git a/src/ui/dialog/fill-and-stroke.h b/src/ui/dialog/fill-and-stroke.h index a82c5bec123e34fbdfd1769ffa6e2d269979473f..fa9ac2bb4ed5f2af393b22f8b0f97cbe11ce34e1 100644 --- a/src/ui/dialog/fill-and-stroke.h +++ b/src/ui/dialog/fill-and-stroke.h @@ -16,10 +16,10 @@ #ifndef INKSCAPE_UI_DIALOG_FILL_AND_STROKE_H #define INKSCAPE_UI_DIALOG_FILL_AND_STROKE_H -#include "ui/widget/panel.h" -#include "ui/widget/object-composite-settings.h" - #include <gtkmm/notebook.h> + +#include "ui/widget/object-composite-settings.h" +#include "ui/widget/panel.h" #include "ui/widget/style-subject.h" namespace Inkscape { @@ -29,38 +29,37 @@ namespace Widget { class FillNStroke; class NotebookPage; class StrokeStyle; -} +} // namespace Widget namespace Dialog { -class FillAndStroke : public UI::Widget::Panel { +class FillAndStroke : public UI::Widget::Panel +{ public: FillAndStroke(); ~FillAndStroke() override; static FillAndStroke &getInstance() { return *new FillAndStroke(); } - void setDesktop(SPDesktop *desktop) override; - //void selectionChanged(Inkscape::Selection *selection); + // void selectionChanged(Inkscape::Selection *selection); void showPageFill(); void showPageStrokePaint(); void showPageStrokeStyle(); protected: - Gtk::Notebook _notebook; + 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; - Gtk::HBox &_createPageTabLabel(const Glib::ustring &label, - const char *label_image); + Gtk::HBox &_createPageTabLabel(const Glib::ustring &label, const char *label_image); void _layoutPageFill(); void _layoutPageStrokePaint(); @@ -70,7 +69,7 @@ protected: private: FillAndStroke(FillAndStroke const &d) = delete; - FillAndStroke& operator=(FillAndStroke const &d) = delete; + FillAndStroke &operator=(FillAndStroke const &d) = delete; SPDesktop *targetDesktop; UI::Widget::FillNStroke *fillWdgt; @@ -82,7 +81,6 @@ private: } // namespace UI } // namespace Inkscape - #endif // INKSCAPE_UI_DIALOG_FILL_AND_STROKE_H /* diff --git a/src/ui/dialog/filter-editor.cpp b/src/ui/dialog/filter-editor.cpp index 7293bf7cb0c17de125b2c646bffb94b66faf5c98..b22aea82166c7d3cbb44fcc5711998e60c5484f2 100644 --- a/src/ui/dialog/filter-editor.cpp +++ b/src/ui/dialog/filter-editor.cpp @@ -11,49 +11,43 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <string> - -#include <gtkmm.h> +#include "filter-editor.h" #include <gdkmm/display.h> #include <gdkmm/seat.h> - #include <glibmm/convert.h> #include <glibmm/error.h> #include <glibmm/i18n.h> #include <glibmm/main.h> #include <glibmm/stringutils.h> +#include <gtkmm.h> +#include <string> #include "desktop.h" #include "dialog-manager.h" #include "document-undo.h" #include "document.h" #include "filter-chemistry.h" -#include "filter-editor.h" #include "filter-enums.h" #include "inkscape.h" -#include "selection-chemistry.h" -#include "verbs.h" - -#include "io/sys.h" #include "io/resource.h" - +#include "io/sys.h" #include "object/filters/blend.h" #include "object/filters/colormatrix.h" -#include "object/filters/componenttransfer.h" #include "object/filters/componenttransfer-funcnode.h" +#include "object/filters/componenttransfer.h" #include "object/filters/convolvematrix.h" #include "object/filters/distantlight.h" #include "object/filters/merge.h" #include "object/filters/mergenode.h" #include "object/filters/pointlight.h" #include "object/filters/spotlight.h" +#include "selection-chemistry.h" #include "style.h" - #include "svg/svg-color.h" - #include "ui/dialog/filedialog.h" #include "ui/widget/spinbutton.h" +#include "verbs.h" using namespace Inkscape::Filters; using namespace Inkscape::IO::Resource; @@ -61,52 +55,47 @@ namespace Inkscape { namespace UI { namespace Dialog { -FilterEditorDialog::FilterEditorDialog() : UI::Widget::Panel("/dialogs/filtereffects", SP_VERB_DIALOG_FILTER_EFFECTS) +FilterEditorDialog::FilterEditorDialog() + : UI::Widget::Panel("/dialogs/filtereffects", SP_VERB_DIALOG_FILTER_EFFECTS) { - - const std::string req_widgets[] = {"FilterEditor", "FilterList", "FilterFERX", "FilterFERY", "FilterFERH", "FilterFERW", "FilterPreview", "FilterPrimitiveDescImage", "FilterPrimitiveList", "FilterPrimitiveDescText", "FilterPrimitiveAdd"}; + const std::string req_widgets[] = {"FilterEditor", "FilterList", + "FilterFERX", "FilterFERY", + "FilterFERH", "FilterFERW", + "FilterPreview", "FilterPrimitiveDescImage", + "FilterPrimitiveList", "FilterPrimitiveDescText", + "FilterPrimitiveAdd"}; auto gladefile = get_filename_string(UIS, "dialog-filter-editor.glade"); try { builder = Gtk::Builder::create_from_file(gladefile); - } catch(const Glib::Error& ex) { + } catch (const Glib::Error &ex) { g_warning("Glade file loading failed for filter effect dialog"); return; } - Gtk::Object* test; - for(std::string w:req_widgets) { - builder->get_widget(w,test); - if(!test){ + Gtk::Object *test; + for (std::string w : req_widgets) { + builder->get_widget(w, test); + if (!test) { g_warning("Required widget %s does not exist", w.c_str()); return; - } + } } builder->get_widget("FilterEditor", FilterEditor); _getContents()->add(*FilterEditor); -//test + // test Gtk::ComboBox *OptionList; - builder->get_widget("OptionList",OptionList); + builder->get_widget("OptionList", OptionList); FilterStore = builder->get_object("FilterStore"); - Glib::RefPtr<Gtk::ListStore> fs = Glib::RefPtr<Gtk::ListStore>::cast_static(FilterStore); + Glib::RefPtr<Gtk::ListStore> fs = Glib::RefPtr<Gtk::ListStore>::cast_static(FilterStore); Gtk::TreeModel::Row row = *(fs->append()); - - - - - } -FilterEditorDialog::~FilterEditorDialog()= default; - - - +FilterEditorDialog::~FilterEditorDialog() = default; - - -} // Never put these namespaces together unless you are using gcc 6+ -} -} // P.S. This is for Inkscape::UI::Dialog +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/filter-editor.h b/src/ui/dialog/filter-editor.h index e20ecbf73835180af48cce8b54a910ba5dd3880d..6636325a1fc377d9898e99e958b8b6903bdf8acd 100644 --- a/src/ui/dialog/filter-editor.h +++ b/src/ui/dialog/filter-editor.h @@ -13,41 +13,38 @@ #ifndef INKSCAPE_UI_DIALOG_FILTER_EDITOR_H #define INKSCAPE_UI_DIALOG_FILTER_EDITOR_H -#include <gtkmm/notebook.h> -#include <gtkmm/sizegroup.h> #include <gtkmm/builder.h> -#include <gtkmm/comboboxtext.h> #include <gtkmm/combobox.h> +#include <gtkmm/comboboxtext.h> #include <gtkmm/drawingarea.h> #include <gtkmm/liststore.h> - +#include <gtkmm/notebook.h> #include <gtkmm/paned.h> #include <gtkmm/scrolledwindow.h> +#include <gtkmm/sizegroup.h> #include <gtkmm/treeview.h> #include "ui/widget/panel.h" - namespace Inkscape { namespace UI { namespace Dialog { -class FilterEditorDialog : public UI::Widget::Panel { +class FilterEditorDialog : public UI::Widget::Panel +{ public: - FilterEditorDialog(); ~FilterEditorDialog() override; - static FilterEditorDialog &getInstance() - { return *new FilterEditorDialog(); } + static FilterEditorDialog &getInstance() { return *new FilterEditorDialog(); } -// void set_attrs_locked(const bool); + // void set_attrs_locked(const bool); private: Glib::RefPtr<Gtk::Builder> builder; Glib::RefPtr<Glib::Object> FilterStore; Gtk::Box *FilterEditor; }; -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/dialog/filter-effects-dialog.cpp b/src/ui/dialog/filter-effects-dialog.cpp index ce28aaa6e03db138e5f988ac1509395f5ec097f7..a8da976474817616ea08727626e79a34f969437b 100644 --- a/src/ui/dialog/filter-effects-dialog.cpp +++ b/src/ui/dialog/filter-effects-dialog.cpp @@ -16,22 +16,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm/imagemenuitem.h> +#include "filter-effects-dialog.h" #include <gdkmm/display.h> #include <gdkmm/general.h> #include <gdkmm/seat.h> - +#include <glibmm/convert.h> +#include <glibmm/i18n.h> +#include <glibmm/main.h> +#include <glibmm/stringutils.h> #include <gtkmm/checkbutton.h> #include <gtkmm/colorbutton.h> #include <gtkmm/eventbox.h> +#include <gtkmm/imagemenuitem.h> #include <gtkmm/sizegroup.h> - -#include <glibmm/i18n.h> -#include <glibmm/stringutils.h> -#include <glibmm/main.h> -#include <glibmm/convert.h> - #include <utility> #include "desktop.h" @@ -39,34 +37,27 @@ #include "document-undo.h" #include "document.h" #include "filter-chemistry.h" -#include "filter-effects-dialog.h" #include "filter-enums.h" -#include "inkscape.h" -#include "selection-chemistry.h" -#include "verbs.h" - #include "include/gtkmm_version.h" - +#include "inkscape.h" +#include "io/sys.h" #include "object/filters/blend.h" #include "object/filters/colormatrix.h" -#include "object/filters/componenttransfer.h" #include "object/filters/componenttransfer-funcnode.h" +#include "object/filters/componenttransfer.h" #include "object/filters/convolvematrix.h" #include "object/filters/distantlight.h" #include "object/filters/merge.h" #include "object/filters/mergenode.h" #include "object/filters/pointlight.h" #include "object/filters/spotlight.h" +#include "selection-chemistry.h" #include "style.h" - #include "svg/svg-color.h" - #include "ui/dialog/filedialog.h" #include "ui/widget/filter-effect-chooser.h" #include "ui/widget/spinbutton.h" - -#include "io/sys.h" - +#include "verbs.h" using namespace Inkscape::Filters; @@ -79,31 +70,31 @@ using Inkscape::UI::Widget::ComboBoxEnum; using Inkscape::UI::Widget::DualSpinScale; using Inkscape::UI::Widget::SpinScale; - // Returns the number of inputs available for the filter primitive type -static int input_count(const SPFilterPrimitive* prim) +static int input_count(const SPFilterPrimitive *prim) { - if(!prim) + if (!prim) return 0; - else if(SP_IS_FEBLEND(prim) || SP_IS_FECOMPOSITE(prim) || SP_IS_FEDISPLACEMENTMAP(prim)) + else if (SP_IS_FEBLEND(prim) || SP_IS_FECOMPOSITE(prim) || SP_IS_FEDISPLACEMENTMAP(prim)) return 2; - else if(SP_IS_FEMERGE(prim)) { + else if (SP_IS_FEMERGE(prim)) { // Return the number of feMergeNode connections plus an extra - return (int) (prim->children.size() + 1); - } - else + return (int)(prim->children.size() + 1); + } else return 1; } -class CheckButtonAttr : public Gtk::CheckButton, public AttrWidget +class CheckButtonAttr + : public Gtk::CheckButton + , public AttrWidget { public: - CheckButtonAttr(bool def, const Glib::ustring& label, - Glib::ustring tv, Glib::ustring fv, - const SPAttr a, char* tip_text) - : Gtk::CheckButton(label), - AttrWidget(a, def), - _true_val(std::move(tv)), _false_val(std::move(fv)) + CheckButtonAttr(bool def, const Glib::ustring &label, Glib::ustring tv, Glib::ustring fv, const SPAttr a, + char *tip_text) + : Gtk::CheckButton(label) + , AttrWidget(a, def) + , _true_val(std::move(tv)) + , _false_val(std::move(fv)) { signal_toggled().connect(signal_attr_changed().make_slot()); if (tip_text) { @@ -111,34 +102,34 @@ public: } } - Glib::ustring get_as_attribute() const override - { - return get_active() ? _true_val : _false_val; - } + Glib::ustring get_as_attribute() const override { return get_active() ? _true_val : _false_val; } - void set_from_attribute(SPObject* o) override + void set_from_attribute(SPObject *o) override { - const gchar* val = attribute_value(o); - if(val) { - if(_true_val == val) + const gchar *val = attribute_value(o); + if (val) { + if (_true_val == val) set_active(true); - else if(_false_val == val) + else if (_false_val == val) set_active(false); } else { set_active(get_default()->as_bool()); } } + private: const Glib::ustring _true_val, _false_val; }; -class SpinButtonAttr : public Inkscape::UI::Widget::SpinButton, public AttrWidget +class SpinButtonAttr + : public Inkscape::UI::Widget::SpinButton + , public AttrWidget { public: - SpinButtonAttr(double lower, double upper, double step_inc, - double climb_rate, int digits, const SPAttr a, double def, char* tip_text) - : Inkscape::UI::Widget::SpinButton(climb_rate, digits), - AttrWidget(a, def) + SpinButtonAttr(double lower, double upper, double step_inc, double climb_rate, int digits, const SPAttr a, + double def, char *tip_text) + : Inkscape::UI::Widget::SpinButton(climb_rate, digits) + , AttrWidget(a, def) { if (tip_text) { set_tooltip_text(tip_text); @@ -153,16 +144,16 @@ public: { const double val = get_value(); - if(get_digits() == 0) + if (get_digits() == 0) return Glib::Ascii::dtostr((int)val); else return Glib::Ascii::dtostr(val); } - void set_from_attribute(SPObject* o) override + void set_from_attribute(SPObject *o) override { - const gchar* val = attribute_value(o); - if(val){ + const gchar *val = attribute_value(o); + if (val) { set_value(Glib::Ascii::strtod(val)); } else { set_value(get_default()->as_double()); @@ -170,10 +161,12 @@ public: } }; -template< typename T> class ComboWithTooltip : public Gtk::EventBox +template <typename T> +class ComboWithTooltip : public Gtk::EventBox { public: - ComboWithTooltip<T>(T default_value, const Util::EnumDataConverter<T>& c, const SPAttr a = SPAttr::INVALID, char* tip_text = nullptr) + ComboWithTooltip<T>(T default_value, const Util::EnumDataConverter<T> &c, const SPAttr a = SPAttr::INVALID, + char *tip_text = nullptr) { if (tip_text) { set_tooltip_text(tip_text); @@ -183,58 +176,56 @@ public: show_all(); } - ~ComboWithTooltip() override - { - delete combo; - } + ~ComboWithTooltip() override { delete combo; } + + ComboBoxEnum<T> *get_attrwidget() { return combo; } - ComboBoxEnum<T>* get_attrwidget() - { - return combo; - } private: - ComboBoxEnum<T>* combo; + ComboBoxEnum<T> *combo; }; // Contains an arbitrary number of spin buttons that use separate attributes class MultiSpinButton : public Gtk::HBox { public: - MultiSpinButton(double lower, double upper, double step_inc, - double climb_rate, int digits, std::vector<SPAttr> attrs, std::vector<double> default_values, std::vector<char*> tip_text) + MultiSpinButton(double lower, double upper, double step_inc, double climb_rate, int digits, + std::vector<SPAttr> attrs, std::vector<double> default_values, std::vector<char *> tip_text) { - g_assert(attrs.size()==default_values.size()); - g_assert(attrs.size()==tip_text.size()); + g_assert(attrs.size() == default_values.size()); + g_assert(attrs.size() == tip_text.size()); set_spacing(4); - for(unsigned i = 0; i < attrs.size(); ++i) { + for (unsigned i = 0; i < attrs.size(); ++i) { unsigned index = attrs.size() - 1 - i; - _spins.push_back(new SpinButtonAttr(lower, upper, step_inc, climb_rate, digits, attrs[index], default_values[index], tip_text[index])); + _spins.push_back(new SpinButtonAttr(lower, upper, step_inc, climb_rate, digits, attrs[index], + default_values[index], tip_text[index])); pack_end(*_spins.back(), false, false); } } ~MultiSpinButton() override { - for(auto & _spin : _spins) + for (auto &_spin : _spins) delete _spin; } - std::vector<SpinButtonAttr*>& get_spinbuttons() - { - return _spins; - } + std::vector<SpinButtonAttr *> &get_spinbuttons() { return _spins; } + private: - std::vector<SpinButtonAttr*> _spins; + std::vector<SpinButtonAttr *> _spins; }; // Contains two spinbuttons that describe a NumberOptNumber -class DualSpinButton : public Gtk::HBox, public AttrWidget +class DualSpinButton + : public Gtk::HBox + , public AttrWidget { public: - DualSpinButton(char* def, double lower, double upper, double step_inc, - double climb_rate, int digits, const SPAttr a, char* tt1, char* tt2) - : AttrWidget(a, def), //TO-DO: receive default num-opt-num as parameter in the constructor - _s1(climb_rate, digits), _s2(climb_rate, digits) + DualSpinButton(char *def, double lower, double upper, double step_inc, double climb_rate, int digits, + const SPAttr a, char *tt1, char *tt2) + : AttrWidget(a, def) + , // TO-DO: receive default num-opt-num as parameter in the constructor + _s1(climb_rate, digits) + , _s2(climb_rate, digits) { if (tt1) { _s1.set_tooltip_text(tt1); @@ -255,22 +246,16 @@ public: pack_end(_s1, false, false); } - Inkscape::UI::Widget::SpinButton& get_spinbutton1() - { - return _s1; - } + Inkscape::UI::Widget::SpinButton &get_spinbutton1() { return _s1; } - Inkscape::UI::Widget::SpinButton& get_spinbutton2() - { - return _s2; - } + Inkscape::UI::Widget::SpinButton &get_spinbutton2() { return _s2; } Glib::ustring get_as_attribute() const override { double v1 = _s1.get_value(); double v2 = _s2.get_value(); - if(_s1.get_digits() == 0) { + if (_s1.get_digits() == 0) { v1 = (int)v1; v2 = (int)v2; } @@ -278,27 +263,29 @@ public: return Glib::Ascii::dtostr(v1) + " " + Glib::Ascii::dtostr(v2); } - void set_from_attribute(SPObject* o) override + void set_from_attribute(SPObject *o) override { - const gchar* val = attribute_value(o); + const gchar *val = attribute_value(o); NumberOptNumber n; - if(val) { + if (val) { n.set(val); } else { n.set(get_default()->as_charptr()); } _s1.set_value(n.getNumber()); _s2.set_value(n.getOptNumber()); - } + private: Inkscape::UI::Widget::SpinButton _s1, _s2; }; -class ColorButton : public Gtk::ColorButton, public AttrWidget +class ColorButton + : public Gtk::ColorButton + , public AttrWidget { public: - ColorButton(unsigned int def, const SPAttr a, char* tip_text) + ColorButton(unsigned int def, const SPAttr a, char *tip_text) : AttrWidget(a, def) { signal_color_set().connect(signal_attr_changed().make_slot()); @@ -318,20 +305,20 @@ public: std::ostringstream os; const auto 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? + 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? os << "rgb(" << r << "," << g << "," << b << ")"; return os.str(); } - - void set_from_attribute(SPObject* o) override + void set_from_attribute(SPObject *o) override { - const gchar* val = attribute_value(o); + const gchar *val = attribute_value(o); guint32 i = 0; - if(val) { + if (val) { i = sp_svg_read_color(val, 0xFFFFFFFF); } else { - i = (guint32) get_default()->as_uint(); + 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); @@ -342,10 +329,12 @@ public: }; // Used for tableValue in feComponentTransfer -class EntryAttr : public Gtk::Entry, public AttrWidget +class EntryAttr + : public Gtk::Entry + , public AttrWidget { public: - EntryAttr(const SPAttr a, char* tip_text) + EntryAttr(const SPAttr a, char *tip_text) : AttrWidget(a) { signal_changed().connect(signal_attr_changed().make_slot()); @@ -355,28 +344,28 @@ public: } // No validity checking is done - Glib::ustring get_as_attribute() const override - { - return get_text(); - } + Glib::ustring get_as_attribute() const override { return get_text(); } - void set_from_attribute(SPObject* o) override + void set_from_attribute(SPObject *o) override { - const gchar* val = attribute_value(o); - if(val) { - set_text( val ); + const gchar *val = attribute_value(o); + if (val) { + set_text(val); } else { - set_text( "" ); + set_text(""); } } }; /* Displays/Edits the matrix for feConvolveMatrix or feColorMatrix */ -class FilterEffectsDialog::MatrixAttr : public Gtk::Frame, public AttrWidget +class FilterEffectsDialog::MatrixAttr + : public Gtk::Frame + , public AttrWidget { public: - MatrixAttr(const SPAttr a, char* tip_text = nullptr) - : AttrWidget(a), _locked(false) + MatrixAttr(const SPAttr a, char *tip_text = nullptr) + : AttrWidget(a) + , _locked(false) { _model = Gtk::ListStore::create(_columns); _tree.set_model(_model); @@ -392,19 +381,19 @@ public: std::vector<double> get_values() const { std::vector<double> vec; - for(const auto & iter : _model->children()) { - for(unsigned c = 0; c < _tree.get_columns().size(); ++c) + for (const auto &iter : _model->children()) { + for (unsigned c = 0; c < _tree.get_columns().size(); ++c) vec.push_back(iter[_columns.cols[c]]); } return vec; } - void set_values(const std::vector<double>& v) + void set_values(const std::vector<double> &v) { unsigned i = 0; - for(const auto & iter : _model->children()) { - for(unsigned c = 0; c < _tree.get_columns().size(); ++c) { - if(i >= v.size()) + for (const auto &iter : _model->children()) { + for (unsigned c = 0; c < _tree.get_columns().size(); ++c) { + if (i >= v.size()) return; iter[_columns.cols[c]] = v[i]; ++i; @@ -417,8 +406,8 @@ public: // use SVGOStringStream to output SVG-compatible doubles Inkscape::SVGOStringStream os; - for(const auto & iter : _model->children()) { - for(unsigned c = 0; c < _tree.get_columns().size(); ++c) { + for (const auto &iter : _model->children()) { + for (unsigned c = 0; c < _tree.get_columns().size(); ++c) { os << iter[_columns.cols[c]] << " "; } } @@ -426,22 +415,22 @@ public: return os.str(); } - void set_from_attribute(SPObject* o) override + void set_from_attribute(SPObject *o) override { - if(o) { - if(SP_IS_FECONVOLVEMATRIX(o)) { - SPFeConvolveMatrix* conv = SP_FECONVOLVEMATRIX(o); + if (o) { + if (SP_IS_FECONVOLVEMATRIX(o)) { + SPFeConvolveMatrix *conv = SP_FECONVOLVEMATRIX(o); int cols, rows; cols = (int)conv->order.getNumber(); - if(cols > 5) + if (cols > 5) cols = 5; rows = conv->order.optNumber_set ? (int)conv->order.getOptNumber() : cols; update(o, rows, cols); - } - else if(SP_IS_FECOLORMATRIX(o)) + } else if (SP_IS_FECOLORMATRIX(o)) update(o, 4, 5); } } + private: class MatrixColumns : public Gtk::TreeModel::ColumnRecord { @@ -449,49 +438,49 @@ private: MatrixColumns() { cols.resize(5); - for(auto & col : cols) + for (auto &col : cols) add(col); } - std::vector<Gtk::TreeModelColumn<double> > cols; + std::vector<Gtk::TreeModelColumn<double>> cols; }; - void update(SPObject* o, const int rows, const int cols) + void update(SPObject *o, const int rows, const int cols) { - if(_locked) + if (_locked) return; _model->clear(); _tree.remove_all_columns(); - std::vector<gdouble>* values = nullptr; - if(SP_IS_FECOLORMATRIX(o)) + std::vector<gdouble> *values = nullptr; + if (SP_IS_FECOLORMATRIX(o)) values = &SP_FECOLORMATRIX(o)->values; - else if(SP_IS_FECONVOLVEMATRIX(o)) + else if (SP_IS_FECONVOLVEMATRIX(o)) values = &SP_FECONVOLVEMATRIX(o)->kernelMatrix; else return; - if(o) { + if (o) { int ndx = 0; - for(int i = 0; i < cols; ++i) { + for (int i = 0; i < cols; ++i) { _tree.append_column_numeric_editable("", _columns.cols[i], "%.2f"); - dynamic_cast<Gtk::CellRendererText*>( - _tree.get_column_cell_renderer(i))->signal_edited().connect( - sigc::mem_fun(*this, &MatrixAttr::rebind)); + dynamic_cast<Gtk::CellRendererText *>(_tree.get_column_cell_renderer(i)) + ->signal_edited() + .connect(sigc::mem_fun(*this, &MatrixAttr::rebind)); } - for(int r = 0; r < rows; ++r) { + for (int r = 0; r < rows; ++r) { Gtk::TreeRow row = *(_model->append()); // Default to identity matrix - for(int c = 0; c < cols; ++c, ++ndx) + for (int c = 0; c < cols; ++c, ++ndx) row[_columns.cols[c]] = ndx < (int)values->size() ? (*values)[ndx] : (r == c ? 1 : 0); } } } - void rebind(const Glib::ustring&, const Glib::ustring&) + void rebind(const Glib::ustring &, const Glib::ustring &) { _locked = true; signal_attr_changed()(); @@ -505,19 +494,25 @@ private: }; // Displays a matrix or a slider for feColorMatrix -class FilterEffectsDialog::ColorMatrixValues : public Gtk::Frame, public AttrWidget +class FilterEffectsDialog::ColorMatrixValues + : public Gtk::Frame + , public AttrWidget { public: ColorMatrixValues() - : AttrWidget(SPAttr::VALUES), - // TRANSLATORS: this dialog is accessible via menu Filters - Filter editor - _matrix(SPAttr::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, SPAttr::VALUES), - _angle("", 0, 0, 360, 0.1, 0.01, 1, SPAttr::VALUES), - _label(C_("Label", "None"), Gtk::ALIGN_START), - _use_stored(false), - _saturation_store(0), - _angle_store(0) + : AttrWidget(SPAttr::VALUES) + , + // TRANSLATORS: this dialog is accessible via menu Filters - Filter editor + _matrix(SPAttr::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, SPAttr::VALUES) + , _angle("", 0, 0, 360, 0.1, 0.01, 1, SPAttr::VALUES) + , _label(C_("Label", "None"), Gtk::ALIGN_START) + , _use_stored(false) + , _saturation_store(0) + , _angle_store(0) { _matrix.signal_attr_changed().connect(signal_attr_changed().make_slot()); _saturation.signal_attr_changed().connect(signal_attr_changed().make_slot()); @@ -533,22 +528,22 @@ public: set_shadow_type(Gtk::SHADOW_NONE); } - void set_from_attribute(SPObject* o) override + void set_from_attribute(SPObject *o) override { - if(SP_IS_FECOLORMATRIX(o)) { - SPFeColorMatrix* col = SP_FECOLORMATRIX(o); + if (SP_IS_FECOLORMATRIX(o)) { + SPFeColorMatrix *col = SP_FECOLORMATRIX(o); remove(); - switch(col->type) { + switch (col->type) { case COLORMATRIX_SATURATE: add(_saturation); - if(_use_stored) + if (_use_stored) _saturation.set_value(_saturation_store); else _saturation.set_from_attribute(o); break; case COLORMATRIX_HUEROTATE: add(_angle); - if(_use_stored) + if (_use_stored) _angle.set_value(_angle_store); else _angle.set_from_attribute(o); @@ -559,7 +554,7 @@ public: case COLORMATRIX_MATRIX: default: add(_matrix); - if(_use_stored) + if (_use_stored) _matrix.set_values(_matrix_store); else _matrix.set_from_attribute(o); @@ -571,26 +566,24 @@ public: Glib::ustring get_as_attribute() const override { - const Widget* w = get_child(); - if(w == &_label) + const Widget *w = get_child(); + if (w == &_label) return ""; else - return dynamic_cast<const AttrWidget*>(w)->get_as_attribute(); + return dynamic_cast<const AttrWidget *>(w)->get_as_attribute(); } - void clear_store() - { - _use_stored = false; - } + void clear_store() { _use_stored = false; } + private: void update_store() { - const Widget* w = get_child(); - if(w == &_matrix) + const Widget *w = get_child(); + if (w == &_matrix) _matrix_store = _matrix.get_values(); - else if(w == &_saturation) + else if (w == &_saturation) _saturation_store = _saturation.get_value(); - else if(w == &_angle) + else if (w == &_angle) _angle_store = _angle.get_value(); } @@ -606,12 +599,14 @@ private: double _angle_store; }; -static Inkscape::UI::Dialog::FileOpenDialog * selectFeImageFileInstance = nullptr; +static Inkscape::UI::Dialog::FileOpenDialog *selectFeImageFileInstance = nullptr; -//Displays a chooser for feImage input -//It may be a filename or the id for an SVG Element -//described in xlink:href syntax -class FileOrElementChooser : public Gtk::HBox, public AttrWidget +// Displays a chooser for feImage input +// It may be a filename or the id for an SVG Element +// described in xlink:href syntax +class FileOrElementChooser + : public Gtk::HBox + , public AttrWidget { public: FileOrElementChooser(const SPAttr a) @@ -630,44 +625,40 @@ public: _entry.signal_changed().connect(signal_attr_changed().make_slot()); show_all(); - } // Returns the element in xlink:href form. - Glib::ustring get_as_attribute() const override - { - return _entry.get_text(); - } - + Glib::ustring get_as_attribute() const override { return _entry.get_text(); } - void set_from_attribute(SPObject* o) override + void set_from_attribute(SPObject *o) override { - const gchar* val = attribute_value(o); - if(val) { + const gchar *val = attribute_value(o); + if (val) { _entry.set_text(val); } else { _entry.set_text(""); } } - void set_desktop(SPDesktop* d){ - _desktop = d; - } + void set_desktop(SPDesktop *d) { _desktop = d; } private: - void select_svg_element(){ - Inkscape::Selection* sel = _desktop->getSelection(); - if (sel->isEmpty()) return; - Inkscape::XML::Node* node = sel->xmlNodes().front(); - if (!node || !node->matchAttributeName("id")) return; + void select_svg_element() + { + Inkscape::Selection *sel = _desktop->getSelection(); + if (sel->isEmpty()) + return; + Inkscape::XML::Node *node = sel->xmlNodes().front(); + if (!node || !node->matchAttributeName("id")) + return; std::ostringstream xlikhref; xlikhref << "#" << node->attribute("id"); _entry.set_text(xlikhref.str()); } - void select_file(){ - + void select_file() + { //# Get the current directory for finding files Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring open_path; @@ -676,25 +667,20 @@ private: 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))) + 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.size() < 1) - { + if (open_path.size() < 1) { open_path = g_get_home_dir(); open_path.append(G_DIR_SEPARATOR_S); - } + } //# Create a dialog if we don't already have one if (!selectFeImageFileInstance) { - selectFeImageFileInstance = - Inkscape::UI::Dialog::FileOpenDialog::create( - *_desktop->getToplevel(), - open_path, - Inkscape::UI::Dialog::SVG_TYPES,/*TODO: any image, not just svg*/ - (char const *)_("Select an image to be used as feImage input")); + selectFeImageFileInstance = Inkscape::UI::Dialog::FileOpenDialog::create( + *_desktop->getToplevel(), open_path, Inkscape::UI::Dialog::SVG_TYPES, /*TODO: any image, not just svg*/ + (char const *)_("Select an image to be used as feImage input")); } //# Show the dialog @@ -706,13 +692,12 @@ private: Glib::ustring fileName = selectFeImageFileInstance->getFilename(); if (fileName.size() > 0) { - Glib::ustring newFileName = Glib::filename_to_utf8(fileName); - if ( newFileName.size() > 0) + if (newFileName.size() > 0) fileName = newFileName; else - g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" ); + g_warning("ERROR CONVERTING OPEN FILENAME TO UTF-8"); open_path = fileName; open_path.append(G_DIR_SEPARATOR_S); @@ -726,22 +711,25 @@ private: Gtk::Entry _entry; Gtk::Button _fromFile; Gtk::Button _fromSVGElement; - SPDesktop* _desktop; + SPDesktop *_desktop; }; class FilterEffectsDialog::Settings { public: - typedef sigc::slot<void, const AttrWidget*> SetAttrSlot; + typedef sigc::slot<void, const AttrWidget *> SetAttrSlot; - Settings(FilterEffectsDialog& d, Gtk::Box& b, SetAttrSlot slot, const int maxtypes) - : _dialog(d), _set_attr_slot(std::move(slot)), _current_type(-1), _max_types(maxtypes) + Settings(FilterEffectsDialog &d, Gtk::Box &b, SetAttrSlot slot, const int maxtypes) + : _dialog(d) + , _set_attr_slot(std::move(slot)) + , _current_type(-1) + , _max_types(maxtypes) { _groups.resize(_max_types); _attrwidgets.resize(_max_types); _size_group = Gtk::SizeGroup::create(Gtk::SIZE_GROUP_HORIZONTAL); - for(int i = 0; i < _max_types; ++i) { + for (int i = 0; i < _max_types; ++i) { _groups[i] = new Gtk::VBox(false, 3); b.set_spacing(4); b.pack_start(*_groups[i], Gtk::PACK_SHRINK); @@ -751,147 +739,141 @@ public: ~Settings() { - for(int i = 0; i < _max_types; ++i) { + for (int i = 0; i < _max_types; ++i) { delete _groups[i]; - for(auto & j : _attrwidgets[i]) + for (auto &j : _attrwidgets[i]) delete j; } } // Show the active settings group and update all the AttrWidgets with new values - void show_and_update(const int t, SPObject* ob) + void show_and_update(const int t, SPObject *ob) { - if(t != _current_type) { + if (t != _current_type) { type(t); - for(auto & _group : _groups) + for (auto &_group : _groups) _group->hide(); } - if(t >= 0) { + if (t >= 0) { _groups[t]->show(); // Do not use show_all(), it shows children than should be hidden } _dialog.set_attrs_locked(true); - for(auto & i : _attrwidgets[_current_type]) + for (auto &i : _attrwidgets[_current_type]) i->set_from_attribute(ob); _dialog.set_attrs_locked(false); } - int get_current_type() const - { - return _current_type; - } + int get_current_type() const { return _current_type; } - void type(const int t) - { - _current_type = t; - } + void type(const int t) { _current_type = t; } void add_no_params() { - Gtk::Label* lbl = Gtk::manage(new Gtk::Label(_("This SVG filter effect does not require any parameters."))); + Gtk::Label *lbl = Gtk::manage(new Gtk::Label(_("This SVG filter effect does not require any parameters."))); add_widget(lbl, ""); } void add_notimplemented() { - Gtk::Label* lbl = Gtk::manage(new Gtk::Label(_("This SVG filter effect is not yet implemented in Inkscape."))); + Gtk::Label *lbl = Gtk::manage(new Gtk::Label(_("This SVG filter effect is not yet implemented in Inkscape."))); add_widget(lbl, ""); } // LightSource - LightSourceControl* add_lightsource(); + LightSourceControl *add_lightsource(); // Component Transfer Values - ComponentTransferValues* add_componenttransfervalues(const Glib::ustring& label, SPFeFuncNode::Channel channel); + ComponentTransferValues *add_componenttransfervalues(const Glib::ustring &label, SPFeFuncNode::Channel channel); // CheckButton - CheckButtonAttr* add_checkbutton(bool def, const SPAttr attr, const Glib::ustring& label, - const Glib::ustring& tv, const Glib::ustring& fv, char* tip_text = nullptr) + CheckButtonAttr *add_checkbutton(bool def, const SPAttr attr, const Glib::ustring &label, const Glib::ustring &tv, + const Glib::ustring &fv, char *tip_text = nullptr) { - CheckButtonAttr* cb = new CheckButtonAttr(def, label, tv, fv, attr, tip_text); + CheckButtonAttr *cb = new CheckButtonAttr(def, label, tv, fv, attr, tip_text); add_widget(cb, ""); add_attr_widget(cb); return cb; } // ColorButton - ColorButton* add_color(unsigned int def, const SPAttr attr, const Glib::ustring& label, char* tip_text = nullptr) + ColorButton *add_color(unsigned int def, const SPAttr attr, const Glib::ustring &label, char *tip_text = nullptr) { - ColorButton* col = new ColorButton(def, attr, tip_text); + ColorButton *col = new ColorButton(def, attr, tip_text); add_widget(col, label); add_attr_widget(col); return col; } // Matrix - MatrixAttr* add_matrix(const SPAttr attr, const Glib::ustring& label, char* tip_text) + MatrixAttr *add_matrix(const SPAttr attr, const Glib::ustring &label, char *tip_text) { - MatrixAttr* conv = new MatrixAttr(attr, tip_text); + MatrixAttr *conv = new MatrixAttr(attr, tip_text); add_widget(conv, label); add_attr_widget(conv); return conv; } // ColorMatrixValues - ColorMatrixValues* add_colormatrixvalues(const Glib::ustring& label) + ColorMatrixValues *add_colormatrixvalues(const Glib::ustring &label) { - ColorMatrixValues* cmv = new ColorMatrixValues(); + ColorMatrixValues *cmv = new ColorMatrixValues(); add_widget(cmv, label); add_attr_widget(cmv); return cmv; } // SpinScale - SpinScale* add_spinscale(double def, const SPAttr attr, const Glib::ustring& label, - const double lo, const double hi, const double step_inc, const double climb, const int digits, char* tip_text = nullptr) + SpinScale *add_spinscale(double def, const SPAttr attr, const Glib::ustring &label, const double lo, + const double hi, const double step_inc, const double climb, const int digits, + char *tip_text = nullptr) { Glib::ustring tip_text2; if (tip_text) tip_text2 = tip_text; - SpinScale* spinslider = new SpinScale("", def, lo, hi, step_inc, climb, digits, attr, tip_text2); + SpinScale *spinslider = new SpinScale("", def, lo, hi, step_inc, climb, digits, attr, tip_text2); add_widget(spinslider, label); add_attr_widget(spinslider); return spinslider; } // DualSpinScale - DualSpinScale* add_dualspinscale(const SPAttr attr, const Glib::ustring& label, - const double lo, const double hi, const double step_inc, - const double climb, const int digits, - const Glib::ustring tip_text1 = "", - const Glib::ustring tip_text2 = "") + DualSpinScale *add_dualspinscale(const SPAttr attr, const Glib::ustring &label, const double lo, const double hi, + const double step_inc, const double climb, const int digits, + const Glib::ustring tip_text1 = "", const Glib::ustring tip_text2 = "") { - DualSpinScale* dss = new DualSpinScale("", "", 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; } // SpinButton - SpinButtonAttr* add_spinbutton(double defalt_value, const SPAttr attr, const Glib::ustring& label, - const double lo, const double hi, const double step_inc, - const double climb, const int digits, char* tip = nullptr) + SpinButtonAttr *add_spinbutton(double defalt_value, const SPAttr attr, const Glib::ustring &label, const double lo, + const double hi, const double step_inc, const double climb, const int digits, + char *tip = nullptr) { - SpinButtonAttr* sb = new SpinButtonAttr(lo, hi, step_inc, climb, digits, attr, defalt_value, tip); + SpinButtonAttr *sb = new SpinButtonAttr(lo, hi, step_inc, climb, digits, attr, defalt_value, tip); add_widget(sb, label); add_attr_widget(sb); return sb; } // DualSpinButton - DualSpinButton* add_dualspinbutton(char* defalt_value, const SPAttr attr, const Glib::ustring& label, - const double lo, const double hi, const double step_inc, - const double climb, const int digits, char* tip1 = nullptr, char* tip2 = nullptr) + DualSpinButton *add_dualspinbutton(char *defalt_value, const SPAttr attr, const Glib::ustring &label, + const double lo, const double hi, const double step_inc, const double climb, + const int digits, char *tip1 = nullptr, char *tip2 = nullptr) { - DualSpinButton* dsb = new DualSpinButton(defalt_value, lo, hi, step_inc, climb, digits, attr, tip1, tip2); + DualSpinButton *dsb = new DualSpinButton(defalt_value, lo, hi, step_inc, climb, digits, attr, tip1, tip2); add_widget(dsb, label); add_attr_widget(dsb); return dsb; } // MultiSpinButton - MultiSpinButton* add_multispinbutton(double def1, double def2, const SPAttr attr1, const SPAttr attr2, - const Glib::ustring& label, const double lo, const double hi, - const double step_inc, const double climb, const int digits, char* tip1 = nullptr, char* tip2 = nullptr) + MultiSpinButton *add_multispinbutton(double def1, double def2, const SPAttr attr1, const SPAttr attr2, + const Glib::ustring &label, const double lo, const double hi, + const double step_inc, const double climb, const int digits, + char *tip1 = nullptr, char *tip2 = nullptr) { std::vector<SPAttr> attrs; attrs.push_back(attr1); @@ -901,19 +883,20 @@ public: default_values.push_back(def1); default_values.push_back(def2); - std::vector<char*> tips; + std::vector<char *> tips; tips.push_back(tip1); tips.push_back(tip2); - MultiSpinButton* msb = new MultiSpinButton(lo, hi, step_inc, climb, digits, attrs, default_values, tips); + MultiSpinButton *msb = new MultiSpinButton(lo, hi, step_inc, climb, digits, attrs, default_values, tips); add_widget(msb, label); - for(auto & i : msb->get_spinbuttons()) + for (auto &i : msb->get_spinbuttons()) add_attr_widget(i); return msb; } - MultiSpinButton* add_multispinbutton(double def1, double def2, double def3, const SPAttr attr1, const SPAttr attr2, - const SPAttr attr3, const Glib::ustring& label, const double lo, - const double hi, const double step_inc, const double climb, const int digits, char* tip1 = nullptr, char* tip2 = nullptr, char* tip3 = nullptr) + MultiSpinButton *add_multispinbutton(double def1, double def2, double def3, const SPAttr attr1, const SPAttr attr2, + const SPAttr attr3, const Glib::ustring &label, const double lo, + const double hi, const double step_inc, const double climb, const int digits, + char *tip1 = nullptr, char *tip2 = nullptr, char *tip3 = nullptr) { std::vector<SPAttr> attrs; attrs.push_back(attr1); @@ -925,22 +908,22 @@ public: default_values.push_back(def2); default_values.push_back(def3); - std::vector<char*> tips; + std::vector<char *> tips; tips.push_back(tip1); tips.push_back(tip2); tips.push_back(tip3); - MultiSpinButton* msb = new MultiSpinButton(lo, hi, step_inc, climb, digits, attrs, default_values, tips); + MultiSpinButton *msb = new MultiSpinButton(lo, hi, step_inc, climb, digits, attrs, default_values, tips); add_widget(msb, label); - for(auto & i : msb->get_spinbuttons()) + for (auto &i : msb->get_spinbuttons()) add_attr_widget(i); return msb; } // FileOrElementChooser - FileOrElementChooser* add_fileorelement(const SPAttr attr, const Glib::ustring& label) + FileOrElementChooser *add_fileorelement(const SPAttr attr, const Glib::ustring &label) { - FileOrElementChooser* foech = new FileOrElementChooser(attr); + FileOrElementChooser *foech = new FileOrElementChooser(attr); foech->set_desktop(_dialog.getDesktop()); add_widget(foech, label); add_attr_widget(foech); @@ -948,30 +931,29 @@ public: } // ComboBoxEnum - template<typename T> ComboBoxEnum<T>* add_combo(T default_value, const SPAttr attr, - const Glib::ustring& label, - const Util::EnumDataConverter<T>& conv, char* tip_text = nullptr) + template <typename T> + ComboBoxEnum<T> *add_combo(T default_value, const SPAttr attr, const Glib::ustring &label, + const Util::EnumDataConverter<T> &conv, char *tip_text = nullptr) { - ComboWithTooltip<T>* combo = new ComboWithTooltip<T>(default_value, conv, attr, tip_text); + ComboWithTooltip<T> *combo = new ComboWithTooltip<T>(default_value, conv, attr, tip_text); add_widget(combo, label); add_attr_widget(combo->get_attrwidget()); return combo->get_attrwidget(); } // Entry - EntryAttr* add_entry(const SPAttr attr, - const Glib::ustring& label, - char* tip_text = nullptr) + EntryAttr *add_entry(const SPAttr attr, const Glib::ustring &label, char *tip_text = nullptr) { - EntryAttr* entry = new EntryAttr(attr, tip_text); + EntryAttr *entry = new EntryAttr(attr, tip_text); add_widget(entry, label); add_attr_widget(entry); return entry; } Glib::RefPtr<Gtk::SizeGroup> _size_group; + private: - void add_attr_widget(AttrWidget* a) + void add_attr_widget(AttrWidget *a) { _attrwidgets[_current_type].push_back(a); a->signal_attr_changed().connect(sigc::bind(_set_attr_slot, a)); @@ -979,7 +961,7 @@ private: /* Adds a new settings widget using the specified label. The label will be formatted with a colon and all widgets within the setting group are aligned automatically. */ - void add_widget(Gtk::Widget* w, const Glib::ustring& label) + void add_widget(Gtk::Widget *w, const Glib::ustring &label) { Gtk::HBox *hb = Gtk::manage(new Gtk::HBox); hb->set_spacing(12); @@ -996,24 +978,27 @@ private: hb->show_all(); } - std::vector<Gtk::VBox*> _groups; - FilterEffectsDialog& _dialog; + std::vector<Gtk::VBox *> _groups; + FilterEffectsDialog &_dialog; SetAttrSlot _set_attr_slot; - std::vector<std::vector< AttrWidget*> > _attrwidgets; + std::vector<std::vector<AttrWidget *>> _attrwidgets; int _current_type, _max_types; }; // Displays sliders and/or tables for feComponentTransfer -class FilterEffectsDialog::ComponentTransferValues : public Gtk::Frame, public AttrWidget +class FilterEffectsDialog::ComponentTransferValues + : public Gtk::Frame + , public AttrWidget { public: - ComponentTransferValues(FilterEffectsDialog& d, SPFeFuncNode::Channel channel) - : AttrWidget(SPAttr::INVALID), - _dialog(d), - _settings(d, _box, sigc::mem_fun(*this, &ComponentTransferValues::set_func_attr), COMPONENTTRANSFER_TYPE_ERROR), - _type(ComponentTransferTypeConverter, SPAttr::TYPE, false), - _channel(channel), - _funcNode(nullptr) + ComponentTransferValues(FilterEffectsDialog &d, SPFeFuncNode::Channel channel) + : AttrWidget(SPAttr::INVALID) + , _dialog(d) + , _settings(d, _box, sigc::mem_fun(*this, &ComponentTransferValues::set_func_attr), + COMPONENTTRANSFER_TYPE_ERROR) + , _type(ComponentTransferTypeConverter, SPAttr::TYPE, false) + , _channel(channel) + , _funcNode(nullptr) { set_shadow_type(Gtk::SHADOW_IN); add(_box); @@ -1022,64 +1007,64 @@ public: _type.signal_changed().connect(sigc::mem_fun(*this, &ComponentTransferValues::on_type_changed)); _settings.type(COMPONENTTRANSFER_TYPE_LINEAR); - _settings.add_spinscale(1, SPAttr::SLOPE, _("Slope"), -10, 10, 0.1, 0.01, 2); + _settings.add_spinscale(1, SPAttr::SLOPE, _("Slope"), -10, 10, 0.1, 0.01, 2); _settings.add_spinscale(0, SPAttr::INTERCEPT, _("Intercept"), -10, 10, 0.1, 0.01, 2); _settings.type(COMPONENTTRANSFER_TYPE_GAMMA); - _settings.add_spinscale(1, SPAttr::AMPLITUDE, _("Amplitude"), 0, 10, 0.1, 0.01, 2); - _settings.add_spinscale(1, SPAttr::EXPONENT, _("Exponent"), 0, 10, 0.1, 0.01, 2); - _settings.add_spinscale(0, SPAttr::OFFSET, _("Offset"), -10, 10, 0.1, 0.01, 2); + _settings.add_spinscale(1, SPAttr::AMPLITUDE, _("Amplitude"), 0, 10, 0.1, 0.01, 2); + _settings.add_spinscale(1, SPAttr::EXPONENT, _("Exponent"), 0, 10, 0.1, 0.01, 2); + _settings.add_spinscale(0, SPAttr::OFFSET, _("Offset"), -10, 10, 0.1, 0.01, 2); _settings.type(COMPONENTTRANSFER_TYPE_TABLE); - _settings.add_entry(SPAttr::TABLEVALUES, _("Table")); + _settings.add_entry(SPAttr::TABLEVALUES, _("Table")); _settings.type(COMPONENTTRANSFER_TYPE_DISCRETE); - _settings.add_entry(SPAttr::TABLEVALUES, _("Discrete")); + _settings.add_entry(SPAttr::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) + SPFeFuncNode *find_node(SPFeComponentTransfer *ct) { - SPFeFuncNode* funcNode = nullptr; + SPFeFuncNode *funcNode = nullptr; bool found = false; - for(auto& node: ct->children) { + for (auto &node : ct->children) { funcNode = SP_FEFUNCNODE(&node); - if( funcNode->channel == _channel ) { + if (funcNode->channel == _channel) { found = true; break; } } - if( !found ) + if (!found) funcNode = nullptr; return funcNode; } - void set_func_attr(const AttrWidget* input) + void set_func_attr(const AttrWidget *input) { - _dialog.set_attr( _funcNode, input->get_attribute(), input->get_as_attribute().c_str()); + _dialog.set_attr(_funcNode, input->get_attribute(), input->get_as_attribute().c_str()); } // Set new type and update widget visibility - void set_from_attribute(SPObject* o) override + void set_from_attribute(SPObject *o) override { // See componenttransfer.cpp - if(SP_IS_FECOMPONENTTRANSFER(o)) { - SPFeComponentTransfer* ct = SP_FECOMPONENTTRANSFER(o); + if (SP_IS_FECOMPONENTTRANSFER(o)) { + SPFeComponentTransfer *ct = SP_FECOMPONENTTRANSFER(o); _funcNode = find_node(ct); - if( _funcNode ) { - _type.set_from_attribute( _funcNode ); + if (_funcNode) { + _type.set_from_attribute(_funcNode); } else { // Create <funcNode> - SPFilterPrimitive* prim = _dialog._primitive_list.get_selected(); - if(prim) { + SPFilterPrimitive *prim = _dialog._primitive_list.get_selected(); + if (prim) { Inkscape::XML::Document *xml_doc = prim->document->getReprDoc(); Inkscape::XML::Node *repr = nullptr; - switch(_channel) { + switch (_channel) { case SPFeFuncNode::R: repr = xml_doc->createElement("svg:feFuncR"); break; @@ -1094,20 +1079,20 @@ public: break; } - //XML Tree being used directly here while it shouldn't be. + // 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" ); + if (_funcNode) { + _funcNode->setAttribute("type", "identity"); } else { - //std::cout << "ERROR ERROR: feFuncX not found!" << std::endl; + // std::cout << "ERROR ERROR: feFuncX not found!" << std::endl; } } } - + update(); } } @@ -1115,12 +1100,11 @@ public: private: void on_type_changed() { - SPFilterPrimitive* prim = _dialog._primitive_list.get_selected(); - if(prim) { - + SPFilterPrimitive *prim = _dialog._primitive_list.get_selected(); + if (prim) { _funcNode->setAttributeOrRemoveIfEmpty("type", _type.get_as_attribute()); - SPFilter* filter = _dialog._filter_modifier.get_selected_filter(); + 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")); @@ -1130,37 +1114,34 @@ private: void update() { - SPFilterPrimitive* prim = _dialog._primitive_list.get_selected(); - if(prim && _funcNode) { + SPFilterPrimitive *prim = _dialog._primitive_list.get_selected(); + if (prim && _funcNode) { _settings.show_and_update(_type.get_active_data()->id, _funcNode); } } public: - Glib::ustring get_as_attribute() const override - { - return ""; - } + Glib::ustring get_as_attribute() const override { return ""; } - FilterEffectsDialog& _dialog; + FilterEffectsDialog &_dialog; Gtk::VBox _box; Settings _settings; ComboBoxEnum<FilterComponentTransferType> _type; SPFeFuncNode::Channel _channel; // RGBA - SPFeFuncNode* _funcNode; + SPFeFuncNode *_funcNode; }; // Settings for the three light source objects class FilterEffectsDialog::LightSourceControl : public AttrWidget { public: - LightSourceControl(FilterEffectsDialog& d) - : AttrWidget(SPAttr::INVALID), - _dialog(d), - _settings(d, _box, sigc::mem_fun(_dialog, &FilterEffectsDialog::set_child_attr_direct), LIGHT_ENDSOURCE), - _light_label(_("Light Source:")), - _light_source(LightSourceConverter), - _locked(false) + LightSourceControl(FilterEffectsDialog &d) + : AttrWidget(SPAttr::INVALID) + , _dialog(d) + , _settings(d, _box, sigc::mem_fun(_dialog, &FilterEffectsDialog::set_child_attr_direct), LIGHT_ENDSOURCE) + , _light_label(_("Light Source:")) + , _light_source(LightSourceConverter) + , _locked(false) { _light_label.set_xalign(0.0); _settings._size_group->add_widget(_light_label); @@ -1176,48 +1157,53 @@ public: // FIXME: these range values are complete crap _settings.type(LIGHT_DISTANT); - _settings.add_spinscale(0, SPAttr::AZIMUTH, _("Azimuth:"), 0, 360, 1, 1, 0, _("Direction angle for the light source on the XY plane, in degrees")); - _settings.add_spinscale(0, SPAttr::ELEVATION, _("Elevation:"), 0, 360, 1, 1, 0, _("Direction angle for the light source on the YZ plane, in degrees")); + _settings.add_spinscale(0, SPAttr::AZIMUTH, _("Azimuth:"), 0, 360, 1, 1, 0, + _("Direction angle for the light source on the XY plane, in degrees")); + _settings.add_spinscale(0, SPAttr::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, SPAttr::X, SPAttr::Y, SPAttr::Z, _("Location:"), -99999, 99999, 1, 100, 0, _("X coordinate"), _("Y coordinate"), _("Z coordinate")); + _settings.add_multispinbutton(/*default x:*/ (double)0, /*default y:*/ (double)0, /*default z:*/ (double)0, + SPAttr::X, SPAttr::Y, SPAttr::Z, _("Location:"), -99999, 99999, 1, 100, 0, + _("X coordinate"), _("Y coordinate"), _("Z coordinate")); _settings.type(LIGHT_SPOT); - _settings.add_multispinbutton(/*default x:*/ (double) 0, /*default y:*/ (double) 0, /*default z:*/ (double) 0, SPAttr::X, SPAttr::Y, SPAttr::Z, _("Location:"), -99999, 99999, 1, 100, 0, _("X coordinate"), _("Y coordinate"), _("Z coordinate")); - _settings.add_multispinbutton(/*default x:*/ (double) 0, /*default y:*/ (double) 0, /*default z:*/ (double) 0, - SPAttr::POINTSATX, SPAttr::POINTSATY, SPAttr::POINTSATZ, - _("Points at:"), -99999, 99999, 1, 100, 0, _("X coordinate"), _("Y coordinate"), _("Z coordinate")); - _settings.add_spinscale(1, SPAttr::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_spinscale(100, SPAttr::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_multispinbutton(/*default x:*/ (double)0, /*default y:*/ (double)0, /*default z:*/ (double)0, + SPAttr::X, SPAttr::Y, SPAttr::Z, _("Location:"), -99999, 99999, 1, 100, 0, + _("X coordinate"), _("Y coordinate"), _("Z coordinate")); + _settings.add_multispinbutton(/*default x:*/ (double)0, /*default y:*/ (double)0, /*default z:*/ (double)0, + SPAttr::POINTSATX, SPAttr::POINTSATY, SPAttr::POINTSATZ, _("Points at:"), -99999, + 99999, 1, 100, 0, _("X coordinate"), _("Y coordinate"), _("Z coordinate")); + _settings.add_spinscale(1, SPAttr::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_spinscale( + 100, SPAttr::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() - { - return _box; - } + Gtk::VBox &get_box() { return _box; } + protected: - Glib::ustring get_as_attribute() const override + Glib::ustring get_as_attribute() const override { return ""; } + void set_from_attribute(SPObject *o) override { - return ""; - } - void set_from_attribute(SPObject* o) override - { - if(_locked) + if (_locked) return; _locked = true; - SPObject* child = o->firstChild(); + SPObject *child = o->firstChild(); - if(SP_IS_FEDISTANTLIGHT(child)) + if (SP_IS_FEDISTANTLIGHT(child)) _light_source.set_active(0); - else if(SP_IS_FEPOINTLIGHT(child)) + else if (SP_IS_FEPOINTLIGHT(child)) _light_source.set_active(1); - else if(SP_IS_FESPOTLIGHT(child)) + else if (SP_IS_FESPOTLIGHT(child)) _light_source.set_active(2); else _light_source.set_active(-1); @@ -1226,31 +1212,30 @@ protected: _locked = false; } + private: void on_source_changed() { - if(_locked) + if (_locked) return; - SPFilterPrimitive* prim = _dialog._primitive_list.get_selected(); - if(prim) { + SPFilterPrimitive *prim = _dialog._primitive_list.get_selected(); + if (prim) { _locked = true; - SPObject* child = prim->firstChild(); + SPObject *child = prim->firstChild(); const int ls = _light_source.get_active_row_number(); // Check if the light source type has changed - if(!(ls == -1 && !child) && - !(ls == 0 && SP_IS_FEDISTANTLIGHT(child)) && - !(ls == 1 && SP_IS_FEPOINTLIGHT(child)) && - !(ls == 2 && SP_IS_FESPOTLIGHT(child))) { - if(child) - //XML Tree being used directly here while it shouldn't be. + if (!(ls == -1 && !child) && !(ls == 0 && SP_IS_FEDISTANTLIGHT(child)) && + !(ls == 1 && SP_IS_FEPOINTLIGHT(child)) && !(ls == 2 && SP_IS_FESPOTLIGHT(child))) { + if (child) + // XML Tree being used directly here while it shouldn't be. sp_repr_unparent(child->getRepr()); - if(ls != -1) { + if (ls != -1) { Inkscape::XML::Document *xml_doc = prim->document->getReprDoc(); Inkscape::XML::Node *repr = xml_doc->createElement(_light_source.get_active_data()->key.c_str()); - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. prim->getRepr()->appendChild(repr); Inkscape::GC::release(repr); } @@ -1269,12 +1254,12 @@ private: _box.show(); _light_box.show_all(); - SPFilterPrimitive* prim = _dialog._primitive_list.get_selected(); - if(prim && prim->firstChild()) + SPFilterPrimitive *prim = _dialog._primitive_list.get_selected(); + if (prim && prim->firstChild()) _settings.show_and_update(_light_source.get_active_data()->id, prim->firstChild()); } - FilterEffectsDialog& _dialog; + FilterEffectsDialog &_dialog; Gtk::VBox _box; Settings _settings; Gtk::HBox _light_box; @@ -1283,35 +1268,33 @@ 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; - } - +// 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() +FilterEffectsDialog::LightSourceControl *FilterEffectsDialog::Settings::add_lightsource() { - LightSourceControl* ls = new LightSourceControl(_dialog); + LightSourceControl *ls = new LightSourceControl(_dialog); add_attr_widget(ls); add_widget(&ls->get_box(), ""); return ls; } -static Gtk::Menu * create_popup_menu(Gtk::Widget& parent, - sigc::slot<void> dup, - sigc::slot<void> rem) +static Gtk::Menu *create_popup_menu(Gtk::Widget &parent, sigc::slot<void> dup, sigc::slot<void> rem) { auto menu = Gtk::manage(new Gtk::Menu); - Gtk::MenuItem* mi = Gtk::manage(new Gtk::MenuItem(_("_Duplicate"),true)); + 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::MenuItem(_("_Remove"), true)); menu->append(*mi); mi->signal_activate().connect(rem); @@ -1322,13 +1305,13 @@ static Gtk::Menu * create_popup_menu(Gtk::Widget& parent, } /*** FilterModifier ***/ -FilterEffectsDialog::FilterModifier::FilterModifier(FilterEffectsDialog& d) - : _desktop(nullptr), - _dialog(d), - _add(_("_New"), true), - _observer(new Inkscape::XML::SignalObserver) +FilterEffectsDialog::FilterModifier::FilterModifier(FilterEffectsDialog &d) + : _desktop(nullptr) + , _dialog(d) + , _add(_("_New"), true) + , _observer(new Inkscape::XML::SignalObserver) { - Gtk::ScrolledWindow* sw = Gtk::manage(new Gtk::ScrolledWindow); + Gtk::ScrolledWindow *sw = Gtk::manage(new Gtk::ScrolledWindow); pack_start(*sw); pack_start(_add, false, false); sw->add(_list); @@ -1337,12 +1320,13 @@ FilterEffectsDialog::FilterModifier::FilterModifier(FilterEffectsDialog& d) _list.set_model(_model); _cell_toggle.set_active(true); const int selcol = _list.append_column("", _cell_toggle); - Gtk::TreeViewColumn* col = _list.get_column(selcol - 1); - if(col) - col->add_attribute(_cell_toggle.property_active(), _columns.sel); + Gtk::TreeViewColumn *col = _list.get_column(selcol - 1); + if (col) + col->add_attribute(_cell_toggle.property_active(), _columns.sel); _list.append_column_editable(_("_Filter"), _columns.label); - ((Gtk::CellRendererText*)_list.get_column(1)->get_first_cell())-> - signal_edited().connect(sigc::mem_fun(*this, &FilterEffectsDialog::FilterModifier::on_name_edited)); + ((Gtk::CellRendererText *)_list.get_column(1)->get_first_cell()) + ->signal_edited() + .connect(sigc::mem_fun(*this, &FilterEffectsDialog::FilterModifier::on_name_edited)); _list.append_column("#", _columns.count); _list.get_column(2)->set_sizing(Gtk::TREE_VIEW_COLUMN_AUTOSIZE); @@ -1353,11 +1337,11 @@ FilterEffectsDialog::FilterModifier::FilterModifier(FilterEffectsDialog& d) _list.get_column(1)->set_resizable(true); _list.get_column(1)->set_sizing(Gtk::TREE_VIEW_COLUMN_AUTOSIZE); _list.get_column(1)->set_expand(true); - + _list.set_reorderable(true); - _list.enable_model_drag_dest (Gdk::ACTION_MOVE); + _list.enable_model_drag_dest(Gdk::ACTION_MOVE); - _list.signal_drag_drop().connect( sigc::mem_fun(*this, &FilterModifier::on_filter_move), false ); + _list.signal_drag_drop().connect(sigc::mem_fun(*this, &FilterModifier::on_filter_move), false); sw->set_shadow_type(Gtk::SHADOW_IN); show_all_children(); @@ -1366,8 +1350,7 @@ FilterEffectsDialog::FilterModifier::FilterModifier(FilterEffectsDialog& d) _list.signal_button_release_event().connect_notify( sigc::mem_fun(*this, &FilterModifier::filter_list_button_release)); - _menu = create_popup_menu(*this, - sigc::mem_fun(*this, &FilterModifier::duplicate_filter), + _menu = create_popup_menu(*this, sigc::mem_fun(*this, &FilterModifier::duplicate_filter), sigc::mem_fun(*this, &FilterModifier::remove_filter)); Gtk::MenuItem *rename_item = Gtk::manage(new Gtk::MenuItem(_("R_ename"), true)); @@ -1388,10 +1371,10 @@ FilterEffectsDialog::FilterModifier::FilterModifier(FilterEffectsDialog& d) FilterEffectsDialog::FilterModifier::~FilterModifier() { - _selectChangedConn.disconnect(); - _selectModifiedConn.disconnect(); - _resource_changed.disconnect(); - _doc_replaced.disconnect(); + _selectChangedConn.disconnect(); + _selectModifiedConn.disconnect(); + _resource_changed.disconnect(); + _doc_replaced.disconnect(); } void FilterEffectsDialog::FilterModifier::setTargetDesktop(SPDesktop *desktop) @@ -1406,11 +1389,15 @@ void FilterEffectsDialog::FilterModifier::setTargetDesktop(SPDesktop *desktop) _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))); + _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 = desktop->getDocument()->connectResourcesChanged("filter",sigc::mem_fun(*this, &FilterModifier::update_filters)); + _doc_replaced = + desktop->connectDocumentReplaced(sigc::mem_fun(*this, &FilterModifier::on_document_replaced)); + _resource_changed = desktop->getDocument()->connectResourcesChanged( + "filter", sigc::mem_fun(*this, &FilterModifier::update_filters)); update_filters(); } @@ -1423,9 +1410,9 @@ void FilterEffectsDialog::FilterModifier::on_document_replaced(SPDesktop * /*des if (_resource_changed) { _resource_changed.disconnect(); } - if (document) - { - _resource_changed = document->connectResourcesChanged("filter",sigc::mem_fun(*this, &FilterModifier::update_filters)); + if (document) { + _resource_changed = + document->connectResourcesChanged("filter", sigc::mem_fun(*this, &FilterModifier::update_filters)); } update_filters(); @@ -1441,11 +1428,9 @@ void FilterEffectsDialog::FilterModifier::on_change_selection() update_selection(selection); } -void FilterEffectsDialog::FilterModifier::on_modified_selection( guint flags ) +void FilterEffectsDialog::FilterModifier::on_modified_selection(guint flags) { - if (flags & ( SP_OBJECT_MODIFIED_FLAG | - SP_OBJECT_PARENT_MODIFIED_FLAG | - SP_OBJECT_STYLE_MODIFIED_FLAG) ) { + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG)) { on_change_selection(); } } @@ -1460,9 +1445,9 @@ void FilterEffectsDialog::FilterModifier::update_selection(Selection *sel) return; } - std::set<SPFilter*> used; - auto itemlist= sel->items(); - for(auto i=itemlist.begin(); itemlist.end() != i; ++i) { + std::set<SPFilter *> used; + auto itemlist = sel->items(); + for (auto i = itemlist.begin(); itemlist.end() != i; ++i) { SPObject *obj = *i; SPStyle *style = obj->style; if (!style || !SP_IS_ITEM(obj)) { @@ -1499,52 +1484,53 @@ void FilterEffectsDialog::FilterModifier::on_filter_selection_changed() signal_filter_changed()(); } -void FilterEffectsDialog::FilterModifier::on_name_edited(const Glib::ustring& path, const Glib::ustring& text) +void FilterEffectsDialog::FilterModifier::on_name_edited(const Glib::ustring &path, const Glib::ustring &text) { Gtk::TreeModel::iterator iter = _model->get_iter(path); - if(iter) { - SPFilter* filter = (*iter)[_columns.filter]; + if (iter) { + SPFilter *filter = (*iter)[_columns.filter]; filter->setLabel(text.c_str()); DocumentUndo::done(filter->document, SP_VERB_DIALOG_FILTER_EFFECTS, _("Rename filter")); - if(iter) + if (iter) (*iter)[_columns.label] = text; } } -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; +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) +void FilterEffectsDialog::FilterModifier::on_selection_toggled(const Glib::ustring &path) { Gtk::TreeIter iter = _model->get_iter(path); - if(iter) { + if (iter) { SPDesktop *desktop = _dialog.getDesktop(); SPDocument *doc = desktop->getDocument(); - SPFilter* filter = (*iter)[_columns.filter]; + SPFilter *filter = (*iter)[_columns.filter]; Inkscape::Selection *sel = desktop->getSelection(); /* If this filter is the only one used in the selection, unset it */ - if((*iter)[_columns.sel] == 1) + if ((*iter)[_columns.sel] == 1) filter = nullptr; - auto itemlist= sel->items(); - for(auto i=itemlist.begin(); itemlist.end() != i; ++i) { - SPItem * item = *i; + auto itemlist = sel->items(); + for (auto i = itemlist.begin(); itemlist.end() != i; ++i) { + SPItem *item = *i; SPStyle *style = item->style; g_assert(style != nullptr); @@ -1554,40 +1540,39 @@ void FilterEffectsDialog::FilterModifier::on_selection_toggled(const Glib::ustri ::remove_filter(item, false); } - item->requestDisplayUpdate((SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG )); + item->requestDisplayUpdate((SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG)); } update_selection(sel); - DocumentUndo::done(doc, SP_VERB_DIALOG_FILTER_EFFECTS, _("Apply filter")); + DocumentUndo::done(doc, SP_VERB_DIALOG_FILTER_EFFECTS, _("Apply filter")); } } - void FilterEffectsDialog::FilterModifier::update_counts() -{ - for(const auto & i : _model->children()) { - SPFilter* f = SP_FILTER(i[_columns.filter]); +{ + for (const auto &i : _model->children()) { + SPFilter *f = SP_FILTER(i[_columns.filter]); i[_columns.count] = f->getRefCount(); - } + } } /* Add all filters in the document to the combobox. Keeps the same selection if possible, otherwise selects the first element */ void FilterEffectsDialog::FilterModifier::update_filters() { - SPDesktop* desktop = _dialog.getDesktop(); - SPDocument* document = desktop->getDocument(); + SPDesktop *desktop = _dialog.getDesktop(); + SPDocument *document = desktop->getDocument(); - std::vector<SPObject *> filters = document->getResourceList( "filter" ); + std::vector<SPObject *> filters = document->getResourceList("filter"); _model->clear(); for (auto filter : filters) { Gtk::TreeModel::Row row = *_model->append(); - SPFilter* f = SP_FILTER(filter); + SPFilter *f = SP_FILTER(filter); row[_columns.filter] = f; - const gchar* lbl = f->label(); - const gchar* id = f->getId(); + const gchar *lbl = f->label(); + const gchar *id = f->getId(); row[_columns.label] = lbl ? lbl : (id ? id : "filter"); } @@ -1595,24 +1580,23 @@ void FilterEffectsDialog::FilterModifier::update_filters() _dialog.update_filter_general_settings_view(); } -SPFilter* FilterEffectsDialog::FilterModifier::get_selected_filter() +SPFilter *FilterEffectsDialog::FilterModifier::get_selected_filter() { - if(_list.get_selection()) { + if (_list.get_selection()) { Gtk::TreeModel::iterator i = _list.get_selection()->get_selected(); - if(i) + if (i) return (*i)[_columns.filter]; } return nullptr; } -void FilterEffectsDialog::FilterModifier::select_filter(const SPFilter* filter) +void FilterEffectsDialog::FilterModifier::select_filter(const SPFilter *filter) { - if(filter) { - for(Gtk::TreeModel::iterator i = _model->children().begin(); - i != _model->children().end(); ++i) { - if((*i)[_columns.filter] == filter) { + if (filter) { + for (Gtk::TreeModel::iterator i = _model->children().begin(); i != _model->children().end(); ++i) { + if ((*i)[_columns.filter] == filter) { _list.get_selection()->select(i); break; } @@ -1620,12 +1604,12 @@ void FilterEffectsDialog::FilterModifier::select_filter(const SPFilter* filter) } } -void FilterEffectsDialog::FilterModifier::filter_list_button_release(GdkEventButton* event) +void FilterEffectsDialog::FilterModifier::filter_list_button_release(GdkEventButton *event) { - if((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { + if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { const bool sensitive = get_selected_filter() != nullptr; - auto items = _menu->get_children(); - items[0]->set_sensitive(sensitive); + auto items = _menu->get_children(); + items[0]->set_sensitive(sensitive); items[1]->set_sensitive(sensitive); items[3]->set_sensitive(sensitive); @@ -1635,8 +1619,8 @@ void FilterEffectsDialog::FilterModifier::filter_list_button_release(GdkEventBut void FilterEffectsDialog::FilterModifier::add_filter() { - SPDocument* doc = _dialog.getDesktop()->getDocument(); - SPFilter* filter = new_filter(doc); + SPDocument *doc = _dialog.getDesktop()->getDocument(); + SPFilter *filter = new_filter(doc); const int count = _model->children().size(); std::ostringstream os; @@ -1654,13 +1638,13 @@ void FilterEffectsDialog::FilterModifier::remove_filter() { SPFilter *filter = get_selected_filter(); - if(filter) { - SPDocument* doc = filter->document; + if (filter) { + SPDocument *doc = filter->document; // Delete all references to this filter - std::vector<SPItem*> x,y; - std::vector<SPItem*> all = get_all_items(x, _desktop->currentRoot(), _desktop, false, false, true, y); - for(std::vector<SPItem*>::const_iterator i=all.begin(); all.end() != i; ++i) { + std::vector<SPItem *> x, y; + std::vector<SPItem *> all = get_all_items(x, _desktop->currentRoot(), _desktop, false, false, true, y); + for (std::vector<SPItem *>::const_iterator i = all.begin(); all.end() != i; ++i) { if (!SP_IS_ITEM(*i)) { continue; } @@ -1678,7 +1662,7 @@ void FilterEffectsDialog::FilterModifier::remove_filter() } } - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. sp_repr_unparent(filter->getRepr()); DocumentUndo::done(doc, SP_VERB_DIALOG_FILTER_EFFECTS, _("Remove filter")); @@ -1689,7 +1673,7 @@ void FilterEffectsDialog::FilterModifier::remove_filter() void FilterEffectsDialog::FilterModifier::duplicate_filter() { - SPFilter* filter = get_selected_filter(); + SPFilter *filter = get_selected_filter(); if (filter) { Inkscape::XML::Node *repr = filter->getRepr(); @@ -1712,13 +1696,13 @@ void FilterEffectsDialog::FilterModifier::select_filter_elements() { SPFilter *filter = get_selected_filter(); - if(!filter) + if (!filter) return; - std::vector<SPItem*> x,y; - std::vector<SPItem*> items; - std::vector<SPItem*> all = get_all_items(x, _desktop->currentRoot(), _desktop, false, false, true, y); - for(SPItem *item: all) { + std::vector<SPItem *> x, y; + std::vector<SPItem *> items; + std::vector<SPItem *> all = get_all_items(x, _desktop->currentRoot(), _desktop, false, false, true, y); + for (SPItem *item : all) { if (!item->style) { continue; } @@ -1736,55 +1720,53 @@ void FilterEffectsDialog::FilterModifier::select_filter_elements() } FilterEffectsDialog::CellRendererConnection::CellRendererConnection() - : Glib::ObjectBase(typeid(CellRendererConnection)), - _primitive(*this, "primitive", nullptr), - _text_width(0) + : Glib::ObjectBase(typeid(CellRendererConnection)) + , _primitive(*this, "primitive", nullptr) + , _text_width(0) {} -Glib::PropertyProxy<void*> FilterEffectsDialog::CellRendererConnection::property_primitive() +Glib::PropertyProxy<void *> FilterEffectsDialog::CellRendererConnection::property_primitive() { return _primitive.get_proxy(); } -void FilterEffectsDialog::CellRendererConnection::get_preferred_width_vfunc(Gtk::Widget& widget, - int& minimum_width, - int& natural_width) const +void FilterEffectsDialog::CellRendererConnection::get_preferred_width_vfunc(Gtk::Widget &widget, int &minimum_width, + int &natural_width) const { - PrimitiveList& primlist = dynamic_cast<PrimitiveList&>(widget); + 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, +void FilterEffectsDialog::CellRendererConnection::get_preferred_width_for_height_vfunc(Gtk::Widget &widget, int /* height */, - int& minimum_width, - int& natural_width) const + 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 +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()); + 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, +void FilterEffectsDialog::CellRendererConnection::get_preferred_height_for_width_vfunc(Gtk::Widget &widget, int /* width */, - int& minimum_height, - int& natural_height) const + int &minimum_height, + int &natural_height) const { get_preferred_height(widget, minimum_height, natural_height); } /*** PrimitiveList ***/ -FilterEffectsDialog::PrimitiveList::PrimitiveList(FilterEffectsDialog& d) - : _dialog(d), - _in_drag(0), - _observer(new Inkscape::XML::SignalObserver) +FilterEffectsDialog::PrimitiveList::PrimitiveList(FilterEffectsDialog &d) + : _dialog(d) + , _in_drag(0) + , _observer(new Inkscape::XML::SignalObserver) { signal_draw().connect(sigc::mem_fun(*this, &PrimitiveList::on_draw_signal)); @@ -1806,9 +1788,9 @@ FilterEffectsDialog::PrimitiveList::PrimitiveList(FilterEffectsDialog& d) init_text(); int cols_count = append_column(_("Connections"), _connection_cell); - Gtk::TreeViewColumn* col = get_column(cols_count - 1); - if(col) - col->add_attribute(_connection_cell.property_primitive(), _columns.primitive); + Gtk::TreeViewColumn *col = get_column(cols_count - 1); + if (col) + col->add_attribute(_connection_cell.property_primitive(), _columns.primitive); } // Sets up a vertical Pango context/layout, and returns the largest @@ -1824,18 +1806,18 @@ void FilterEffectsDialog::PrimitiveList::init_text() // Store the maximum height and width of the an input type label // for later use in drawing and measuring. _input_type_height = _input_type_width = 0; - for(unsigned int i = 0; i < FPInputConverter._length; ++i) { + for (unsigned int i = 0; i < FPInputConverter._length; ++i) { _vertical_layout->set_text(_(FPInputConverter.get_label((FilterPrimitiveInput)i).c_str())); int fontw, fonth; _vertical_layout->get_pixel_size(fontw, fonth); - if(fonth > _input_type_width) + if (fonth > _input_type_width) _input_type_width = fonth; if (fontw > _input_type_height) _input_type_height = fontw; } } -sigc::signal<void>& FilterEffectsDialog::PrimitiveList::signal_primitive_changed() +sigc::signal<void> &FilterEffectsDialog::PrimitiveList::signal_primitive_changed() { return _signal_primitive_changed; } @@ -1851,37 +1833,37 @@ void FilterEffectsDialog::PrimitiveList::on_primitive_selection_changed() Keeps the same selection if possible, otherwise selects the first element */ void FilterEffectsDialog::PrimitiveList::update() { - SPFilter* f = _dialog._filter_modifier.get_selected_filter(); - const SPFilterPrimitive* active_prim = get_selected(); + SPFilter *f = _dialog._filter_modifier.get_selected_filter(); + const SPFilterPrimitive *active_prim = get_selected(); _model->clear(); - if(f) { + if (f) { bool active_found = false; _dialog._primitive_box->set_sensitive(true); _dialog.update_filter_general_settings_view(); - for(auto& prim_obj: f->children) { + for (auto &prim_obj : f->children) { SPFilterPrimitive *prim = SP_FILTER_PRIMITIVE(&prim_obj); - if(!prim) { + if (!prim) { break; } Gtk::TreeModel::Row row = *_model->append(); row[_columns.primitive] = prim; - //XML Tree being used directly here while it shouldn't be. + // 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()); if (prim->getId()) { - row[_columns.id] = Glib::ustring(prim->getId()); + row[_columns.id] = Glib::ustring(prim->getId()); } - if(prim == active_prim) { + if (prim == active_prim) { get_selection()->select(row); active_found = true; } } - if(!active_found && _model->children().begin()) + if (!active_found && _model->children().begin()) get_selection()->select(_model->children().begin()); columns_autosize(); @@ -1889,59 +1871,55 @@ void FilterEffectsDialog::PrimitiveList::update() int width, height; get_size_request(width, height); if (height == -1) { - // Need to account for the height of the input type text (rotated text) as well as the - // column headers. Input type text height determined in init_text() by measuring longest - // string. Column header height determined by mapping y coordinate of visible - // rectangle to widget coordinates. - Gdk::Rectangle vis; - int vis_x, vis_y; - get_visible_rect(vis); - convert_tree_to_widget_coords(vis.get_x(), vis.get_y(), vis_x, vis_y); - set_size_request(width, _input_type_height + 2 + vis_y); - } - } - else { + // Need to account for the height of the input type text (rotated text) as well as the + // column headers. Input type text height determined in init_text() by measuring longest + // string. Column header height determined by mapping y coordinate of visible + // rectangle to widget coordinates. + Gdk::Rectangle vis; + int vis_x, vis_y; + get_visible_rect(vis); + convert_tree_to_widget_coords(vis.get_x(), vis.get_y(), vis_x, vis_y); + set_size_request(width, _input_type_height + 2 + vis_y); + } + } else { _dialog._primitive_box->set_sensitive(false); set_size_request(-1, -1); } } -void FilterEffectsDialog::PrimitiveList::set_menu(Gtk::Widget& parent, - sigc::slot<void> dup, - sigc::slot<void> rem) +void FilterEffectsDialog::PrimitiveList::set_menu(Gtk::Widget &parent, sigc::slot<void> dup, sigc::slot<void> rem) { _primitive_menu = create_popup_menu(parent, dup, rem); } -SPFilterPrimitive* FilterEffectsDialog::PrimitiveList::get_selected() +SPFilterPrimitive *FilterEffectsDialog::PrimitiveList::get_selected() { - if(_dialog._filter_modifier.get_selected_filter()) { + if (_dialog._filter_modifier.get_selected_filter()) { Gtk::TreeModel::iterator i = get_selection()->get_selected(); - if(i) + if (i) return (*i)[_columns.primitive]; } return nullptr; } -void FilterEffectsDialog::PrimitiveList::select(SPFilterPrimitive* prim) +void FilterEffectsDialog::PrimitiveList::select(SPFilterPrimitive *prim) { - for(Gtk::TreeIter i = _model->children().begin(); - i != _model->children().end(); ++i) { - if((*i)[_columns.primitive] == prim) + for (Gtk::TreeIter i = _model->children().begin(); i != _model->children().end(); ++i) { + if ((*i)[_columns.primitive] == prim) get_selection()->select(i); } } void FilterEffectsDialog::PrimitiveList::remove_selected() { - SPFilterPrimitive* prim = get_selected(); + SPFilterPrimitive *prim = get_selected(); - if(prim) { + if (prim) { _observer->set(nullptr); _model->erase(get_selection()->get_selected()); - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. sp_repr_unparent(prim->getRepr()); DocumentUndo::done(_dialog.getDesktop()->getDocument(), SP_VERB_DIALOG_FILTER_EFFECTS, @@ -1951,16 +1929,16 @@ void FilterEffectsDialog::PrimitiveList::remove_selected() } } -bool FilterEffectsDialog::PrimitiveList::on_draw_signal(const Cairo::RefPtr<Cairo::Context> & cr) +bool FilterEffectsDialog::PrimitiveList::on_draw_signal(const Cairo::RefPtr<Cairo::Context> &cr) { cr->set_line_width(1.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 + // 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); + convert_bin_window_to_widget_coords(0, 0, x_origin, y_origin); cr->translate(x_origin, y_origin); - + auto sc = get_style_context(); Gdk::RGBA bg_color("#f0f0f0"); // Fix bg as a light gray @@ -1969,48 +1947,47 @@ bool FilterEffectsDialog::PrimitiveList::on_draw_signal(const Cairo::RefPtr<Cair auto fg_color = sc->get_color(state); Gdk::RGBA mid_color; - mid_color.set_rgba((bg_color.get_red() + fg_color.get_red() )/2.0, - (bg_color.get_green() + fg_color.get_green())/2.0, - (bg_color.get_blue() + fg_color.get_blue()) /2.0, - (bg_color.get_alpha() + fg_color.get_alpha())/2.0); - - SPFilterPrimitive* prim = get_selected(); + mid_color.set_rgba( + (bg_color.get_red() + fg_color.get_red()) / 2.0, (bg_color.get_green() + fg_color.get_green()) / 2.0, + (bg_color.get_blue() + fg_color.get_blue()) / 2.0, (bg_color.get_alpha() + fg_color.get_alpha()) / 2.0); + + SPFilterPrimitive *prim = get_selected(); int row_count = get_model()->children().size(); int fheight = CellRendererConnection::size; Gdk::Rectangle rct, vis; Gtk::TreeIter row = get_model()->children().begin(); int text_start_x = 0; - if(row) { + if (row) { get_cell_area(get_model()->get_path(row), *get_column(1), rct); get_visible_rect(vis); text_start_x = rct.get_x() + rct.get_width() - get_input_type_width() * FPInputConverter._length + 1; - - for(unsigned int i = 0; i < FPInputConverter._length; ++i) { + + for (unsigned int i = 0; i < FPInputConverter._length; ++i) { _vertical_layout->set_text(_(FPInputConverter.get_label((FilterPrimitiveInput)i).c_str())); const int x = text_start_x + get_input_type_width() * i; - cr->save(); + cr->save(); Gdk::Cairo::set_source_rgba(cr, bg_color); - cr->rectangle(x, 0, get_input_type_width(), vis.get_height()); - cr->fill_preserve(); + cr->rectangle(x, 0, get_input_type_width(), vis.get_height()); + cr->fill_preserve(); Gdk::Cairo::set_source_rgba(cr, fg_color); - cr->move_to(x + get_input_type_width(), 5); - cr->rotate_degrees(90); - _vertical_layout->show_in_cairo_context(cr); - + cr->move_to(x + get_input_type_width(), 5); + cr->rotate_degrees(90); + _vertical_layout->show_in_cairo_context(cr); + Gdk::Cairo::set_source_rgba(cr, mid_color); - cr->move_to(x, 0); - cr->line_to(x, vis.get_height()); - cr->stroke(); - cr->restore(); + cr->move_to(x, 0); + cr->line_to(x, vis.get_height()); + cr->stroke(); + cr->restore(); } cr->rectangle(vis.get_x(), 0, vis.get_width(), vis.get_height()); cr->clip(); } int row_index = 0; - for(; row != get_model()->children().end(); ++row, ++row_index) { + for (; row != get_model()->children().end(); ++row, ++row_index) { get_cell_area(get_model()->get_path(row), *get_column(1), rct); const int x = rct.get_x(), y = rct.get_y(), h = rct.get_height(); @@ -2026,110 +2003,110 @@ bool FilterEffectsDialog::PrimitiveList::on_draw_signal(const Cairo::RefPtr<Cair // Outline the bottom of the connection area const int outline_x = x + fheight * (row_count - row_index); - cr->save(); + cr->save(); Gdk::Cairo::set_source_rgba(cr, mid_color); - cr->move_to(vis.get_x(), y + h); - cr->line_to(outline_x, y + h); + cr->move_to(vis.get_x(), y + h); + cr->line_to(outline_x, y + h); // Side outline - cr->line_to(outline_x, y - 1); + cr->line_to(outline_x, y - 1); - cr->stroke(); - cr->restore(); + cr->stroke(); + cr->restore(); 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 SPFilterPrimitive *row_prim = (*row)[_columns.primitive]; const int inputs = input_count(row_prim); - if(SP_IS_FEMERGE(row_prim)) { - for(int i = 0; i < inputs; ++i) { + if (SP_IS_FEMERGE(row_prim)) { + for (int i = 0; i < inputs; ++i) { inside = do_connection_node(row, i, con_poly, mx, my); - cr->save(); + cr->save(); Gdk::Cairo::set_source_rgba(cr, mid_color); - draw_connection_node(cr, con_poly, inside); + draw_connection_node(cr, con_poly, inside); - cr->restore(); + cr->restore(); - if(_in_drag == (i + 1)) { + if (_in_drag == (i + 1)) { con_drag_y = con_poly[2].get_y(); - con_drag_x = con_poly[2].get_x(); + con_drag_x = con_poly[2].get_x(); } - if(_in_drag != (i + 1) || row_prim != prim) { - draw_connection(cr, row, SPAttr::INVALID, text_start_x, outline_x, con_poly[2].get_y(), row_count, i); + if (_in_drag != (i + 1) || row_prim != prim) { + draw_connection(cr, row, SPAttr::INVALID, text_start_x, outline_x, con_poly[2].get_y(), row_count, + i); } } - } - else { + } else { // Draw "in" shape inside = do_connection_node(row, 0, con_poly, mx, my); con_drag_y = con_poly[2].get_y(); - con_drag_x = con_poly[2].get_x(); - - cr->save(); - + con_drag_x = con_poly[2].get_x(); + + cr->save(); + Gdk::Cairo::set_source_rgba(cr, mid_color); draw_connection_node(cr, con_poly, inside); - cr->restore(); + cr->restore(); // Draw "in" connection - if(_in_drag != 1 || row_prim != prim) { + if (_in_drag != 1 || row_prim != prim) { draw_connection(cr, row, SPAttr::IN_, text_start_x, outline_x, con_poly[2].get_y(), row_count, -1); } - if(inputs == 2) { + if (inputs == 2) { // Draw "in2" shape inside = do_connection_node(row, 1, con_poly, mx, my); - if(_in_drag == 2) { + if (_in_drag == 2) { con_drag_y = con_poly[2].get_y(); - con_drag_x = con_poly[2].get_x(); + con_drag_x = con_poly[2].get_x(); } - - cr->save(); + + cr->save(); Gdk::Cairo::set_source_rgba(cr, mid_color); draw_connection_node(cr, con_poly, inside); - + cr->restore(); // Draw "in2" connection - if(_in_drag != 2 || row_prim != prim) { + if (_in_drag != 2 || row_prim != prim) { draw_connection(cr, row, SPAttr::IN2, text_start_x, outline_x, con_poly[2].get_y(), row_count, -1); } } } // Draw drag connection - if(row_prim == prim && _in_drag) { - cr->save(); - 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(); - } + if (row_prim == prim && _in_drag) { + cr->save(); + 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(); + } } return true; } -void FilterEffectsDialog::PrimitiveList::draw_connection(const Cairo::RefPtr<Cairo::Context>& cr, - const Gtk::TreeIter& input, const SPAttr attr, +void FilterEffectsDialog::PrimitiveList::draw_connection(const Cairo::RefPtr<Cairo::Context> &cr, + const Gtk::TreeIter &input, const SPAttr attr, const int text_start_x, const int x1, const int y1, const int row_count, const int pos) { cr->save(); auto sc = get_style_context(); - + Gdk::RGBA bg_color("f0f0f0"); // Fix bg as a light gray // TODO: In Gtk+ 4, the state is not used in get_color @@ -2137,45 +2114,43 @@ void FilterEffectsDialog::PrimitiveList::draw_connection(const Cairo::RefPtr<Cai auto fg_color = sc->get_color(state); Gdk::RGBA mid_color; - mid_color.set_rgba((bg_color.get_red() + fg_color.get_red() )/2.0, - (bg_color.get_green() + fg_color.get_green())/2.0, - (bg_color.get_blue() + fg_color.get_blue() )/2.0, - (bg_color.get_alpha() + fg_color.get_alpha())/2.0); + mid_color.set_rgba( + (bg_color.get_red() + fg_color.get_red()) / 2.0, (bg_color.get_green() + fg_color.get_green()) / 2.0, + (bg_color.get_blue() + fg_color.get_blue()) / 2.0, (bg_color.get_alpha() + fg_color.get_alpha()) / 2.0); int src_id = 0; Gtk::TreeIter res = find_result(input, attr, src_id, pos); const bool is_first = input == get_model()->children().begin(); - const bool is_merge = SP_IS_FEMERGE((SPFilterPrimitive*)(*input)[_columns.primitive]); + const bool is_merge = SP_IS_FEMERGE((SPFilterPrimitive *)(*input)[_columns.primitive]); const bool use_default = !res && !is_merge; - if(res == input || (use_default && is_first)) { + 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 const int tw = get_input_type_width(); gint end_x = text_start_x + tw * src_id + (int)(tw * 0.5f) + 1; - if(use_default && is_first) { + if (use_default && is_first) { Gdk::Cairo::set_source_rgba(cr, mid_color); } else { cr->set_source_rgb(0.0, 0.0, 0.0); } - - cr->rectangle(end_x-2, y1-2, 5, 5); - cr->fill_preserve(); - cr->move_to(x1, y1); - cr->line_to(end_x, y1); - cr->stroke(); - } - else { + + cr->rectangle(end_x - 2, y1 - 2, 5, 5); + cr->fill_preserve(); + cr->move_to(x1, y1); + cr->line_to(end_x, y1); + cr->stroke(); + } else { // Draw an 'L'-shaped connection to another filter primitive // If no connection is specified, draw a light connection to the previous primitive - if(use_default) { - res = input; - --res; - } + if (use_default) { + res = input; + --res; + } - if(res) { + if (res) { Gdk::Rectangle rct; get_cell_area(get_model()->get_path(_model->children().begin()), *get_column(1), rct); @@ -2187,12 +2162,12 @@ void FilterEffectsDialog::PrimitiveList::draw_connection(const Cairo::RefPtr<Cai const int y2 = rct.get_y() + rct.get_height(); // Draw a bevelled 'L'-shaped connection - 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); - cr->line_to(x2, y2); - cr->stroke(); + 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); + cr->line_to(x2, y2); + cr->stroke(); } } cr->restore(); @@ -2200,26 +2175,26 @@ void FilterEffectsDialog::PrimitiveList::draw_connection(const Cairo::RefPtr<Cai // 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) +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); + 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(); + 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 -bool FilterEffectsDialog::PrimitiveList::do_connection_node(const Gtk::TreeIter& row, const int input, - std::vector<Gdk::Point>& points, - const int ix, const int iy) +bool FilterEffectsDialog::PrimitiveList::do_connection_node(const Gtk::TreeIter &row, const int input, + std::vector<Gdk::Point> &points, const int ix, const int iy) { Gdk::Rectangle rct; const int icnt = input_count((*row)[_columns.primitive]); @@ -2241,53 +2216,48 @@ bool FilterEffectsDialog::PrimitiveList::do_connection_node(const Gtk::TreeIter& return ix >= x - h && iy >= con_y && ix <= x && iy <= points[1].get_y(); } -const Gtk::TreeIter FilterEffectsDialog::PrimitiveList::find_result(const Gtk::TreeIter& start, - const SPAttr attr, int& src_id, - const int pos) +const Gtk::TreeIter FilterEffectsDialog::PrimitiveList::find_result(const Gtk::TreeIter &start, const SPAttr attr, + int &src_id, const int pos) { - SPFilterPrimitive* prim = (*start)[_columns.primitive]; + SPFilterPrimitive *prim = (*start)[_columns.primitive]; Gtk::TreeIter target = _model->children().end(); int image = 0; - if(SP_IS_FEMERGE(prim)) { + if (SP_IS_FEMERGE(prim)) { int c = 0; bool found = false; - for (auto& o: prim->children) { - if(c == pos && SP_IS_FEMERGENODE(&o)) { + for (auto &o : prim->children) { + if (c == pos && SP_IS_FEMERGENODE(&o)) { image = SP_FEMERGENODE(&o)->input; found = true; } ++c; } - if(!found) + if (!found) return target; - } - else { - if(attr == SPAttr::IN_) + } else { + if (attr == SPAttr::IN_) image = prim->image_in; - else if(attr == SPAttr::IN2) { - if(SP_IS_FEBLEND(prim)) + else if (attr == SPAttr::IN2) { + if (SP_IS_FEBLEND(prim)) image = SP_FEBLEND(prim)->in2; - else if(SP_IS_FECOMPOSITE(prim)) + else if (SP_IS_FECOMPOSITE(prim)) image = SP_FECOMPOSITE(prim)->in2; - else if(SP_IS_FEDISPLACEMENTMAP(prim)) + else if (SP_IS_FEDISPLACEMENTMAP(prim)) image = SP_FEDISPLACEMENTMAP(prim)->in2; else return target; - } - else + } else return target; } - if(image >= 0) { - for(Gtk::TreeIter i = _model->children().begin(); - i != start; ++i) { - if(((SPFilterPrimitive*)(*i)[_columns.primitive])->image_out == image) + if (image >= 0) { + for (Gtk::TreeIter i = _model->children().begin(); i != start; ++i) { + if (((SPFilterPrimitive *)(*i)[_columns.primitive])->image_out == image) target = i; } return target; - } - else if(image < -1) { + } else if (image < -1) { src_id = -(image + 2); return start; } @@ -2295,32 +2265,32 @@ const Gtk::TreeIter FilterEffectsDialog::PrimitiveList::find_result(const Gtk::T return target; } -int FilterEffectsDialog::PrimitiveList::find_index(const Gtk::TreeIter& target) +int FilterEffectsDialog::PrimitiveList::find_index(const Gtk::TreeIter &target) { int i = 0; - for(Gtk::TreeIter iter = _model->children().begin(); - iter != target; ++iter, ++i){}; + for (Gtk::TreeIter iter = _model->children().begin(); iter != target; ++iter, ++i) { + }; return i; } -bool FilterEffectsDialog::PrimitiveList::on_button_press_event(GdkEventButton* e) +bool FilterEffectsDialog::PrimitiveList::on_button_press_event(GdkEventButton *e) { Gtk::TreePath path; - Gtk::TreeViewColumn* col; + Gtk::TreeViewColumn *col; const int x = (int)e->x, y = (int)e->y; int cx, cy; _drag_prim = nullptr; - if(get_path_at_pos(x, y, path, col, cx, cy)) { + if (get_path_at_pos(x, y, path, col, cx, cy)) { Gtk::TreeIter iter = _model->get_iter(path); std::vector<Gdk::Point> points; _drag_prim = (*iter)[_columns.primitive]; const int icnt = input_count(_drag_prim); - for(int i = 0; i < icnt; ++i) { - if(do_connection_node(_model->get_iter(path), i, points, x, y)) { + for (int i = 0; i < icnt; ++i) { + if (do_connection_node(_model->get_iter(path), i, points, x, y)) { _in_drag = i + 1; break; } @@ -2329,18 +2299,18 @@ bool FilterEffectsDialog::PrimitiveList::on_button_press_event(GdkEventButton* e queue_draw(); } - if(_in_drag) { - _scroll_connection = Glib::signal_timeout().connect(sigc::mem_fun(*this, &PrimitiveList::on_scroll_timeout), 150); - _autoscroll_x = 0; - _autoscroll_y = 0; + if (_in_drag) { + _scroll_connection = + Glib::signal_timeout().connect(sigc::mem_fun(*this, &PrimitiveList::on_scroll_timeout), 150); + _autoscroll_x = 0; + _autoscroll_y = 0; get_selection()->select(path); return true; - } - else + } else return Gtk::TreeView::on_button_press_event(e); } -bool FilterEffectsDialog::PrimitiveList::on_motion_notify_event(GdkEventMotion* e) +bool FilterEffectsDialog::PrimitiveList::on_motion_notify_event(GdkEventMotion *e) { const int speed = 10; const int limit = 15; @@ -2348,59 +2318,57 @@ 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; 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) + if (e->y < vis_y) _autoscroll_y = -(int)(speed + (vis_y - e->y) / 5); - else if(e->y < vis_y + limit) + else if (e->y < vis_y + limit) _autoscroll_y = -speed; - else if(e->y > top) + else if (e->y > top) _autoscroll_y = (int)(speed + (e->y - top) / 5); - else if(e->y > top - limit) + else if (e->y > top - limit) _autoscroll_y = speed; else _autoscroll_y = 0; - double e2 = ( e->x - vis_x2/2); - // horizontal scrolling - if(e2 < vis_x) + 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) + else if (e2 < vis_x + limit) _autoscroll_x = -speed; - else if(e2 > right_edge) + else if (e2 > right_edge) _autoscroll_x = (int)(speed + (e2 - right_edge) / 5); - else if(e2 > right_edge - limit) + else if (e2 > right_edge - limit) _autoscroll_x = speed; else _autoscroll_x = 0; - - - + queue_draw(); return Gtk::TreeView::on_motion_notify_event(e); } -bool FilterEffectsDialog::PrimitiveList::on_button_release_event(GdkEventButton* e) +bool FilterEffectsDialog::PrimitiveList::on_button_release_event(GdkEventButton *e) { SPFilterPrimitive *prim = get_selected(), *target; _scroll_connection.disconnect(); - if(_in_drag && prim) { + if (_in_drag && prim) { Gtk::TreePath path; - Gtk::TreeViewColumn* col; + Gtk::TreeViewColumn *col; int cx, cy; - if(get_path_at_pos((int)e->x, (int)e->y, path, col, cx, cy)) { + if (get_path_at_pos((int)e->x, (int)e->y, path, col, cx, cy)) { const gchar *in_val = nullptr; Glib::ustring result; Gtk::TreeIter target_iter = _model->get_iter(path); @@ -2411,48 +2379,43 @@ bool FilterEffectsDialog::PrimitiveList::on_button_release_event(GdkEventButton* get_cell_area(path, *col, rct); const int twidth = get_input_type_width(); const int sources_x = rct.get_width() - twidth * FPInputConverter._length; - if(cx > sources_x) { + if (cx > sources_x) { int src = (cx - sources_x) / twidth; if (src < 0) { src = 0; - } else if(src >= static_cast<int>(FPInputConverter._length)) { + } else if (src >= static_cast<int>(FPInputConverter._length)) { src = FPInputConverter._length - 1; } result = FPInputConverter.get_key((FilterPrimitiveInput)src); in_val = result.c_str(); - } - else { + } else { // Ensure that the target comes before the selected primitive - for(Gtk::TreeIter iter = _model->children().begin(); - iter != get_selection()->get_selected(); ++iter) { - if(iter == target_iter) { + for (Gtk::TreeIter iter = _model->children().begin(); iter != get_selection()->get_selected(); ++iter) { + if (iter == target_iter) { Inkscape::XML::Node *repr = target->getRepr(); // Make sure the target has a result const gchar *gres = repr->attribute("result"); - if(!gres) { + if (!gres) { result = SP_FILTER(prim->parent)->get_new_result_name(); repr->setAttributeOrRemoveIfEmpty("result", result); in_val = result.c_str(); - } - else + } else in_val = gres; break; } } } - if(SP_IS_FEMERGE(prim)) { + if (SP_IS_FEMERGE(prim)) { int c = 1; bool handled = false; - for (auto& o: prim->children) { - if(c == _in_drag && SP_IS_FEMERGENODE(&o)) { + for (auto &o : prim->children) { + if (c == _in_drag && SP_IS_FEMERGENODE(&o)) { // If input is null, delete it - if(!in_val) { - - //XML Tree being used directly here while it shouldn't be. + if (!in_val) { + // XML Tree being used directly here while it shouldn't be. sp_repr_unparent(o.getRepr()); - DocumentUndo::done(prim->document, SP_VERB_DIALOG_FILTER_EFFECTS, - _("Remove merge node")); + DocumentUndo::done(prim->document, SP_VERB_DIALOG_FILTER_EFFECTS, _("Remove merge node")); (*get_selection()->get_selected())[_columns.primitive] = prim; } else { _dialog.set_attr(&o, SPAttr::IN_, in_val); @@ -2463,23 +2426,22 @@ bool FilterEffectsDialog::PrimitiveList::on_button_release_event(GdkEventButton* ++c; } // Add new input? - if(!handled && c == _in_drag && in_val) { + if (!handled && c == _in_drag && in_val) { Inkscape::XML::Document *xml_doc = prim->document->getReprDoc(); Inkscape::XML::Node *repr = xml_doc->createElement("svg:feMergeNode"); repr->setAttribute("inkscape:collect", "always"); - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. prim->getRepr()->appendChild(repr); SPFeMergeNode *node = SP_FEMERGENODE(prim->document->getObjectByRepr(repr)); Inkscape::GC::release(repr); _dialog.set_attr(node, SPAttr::IN_, in_val); (*get_selection()->get_selected())[_columns.primitive] = prim; } - } - else { - if(_in_drag == 1) + } else { + if (_in_drag == 1) _dialog.set_attr(prim, SPAttr::IN_, in_val); - else if(_in_drag == 2) + else if (_in_drag == 2) _dialog.set_attr(prim, SPAttr::IN2, in_val); } } @@ -2490,22 +2452,21 @@ bool FilterEffectsDialog::PrimitiveList::on_button_release_event(GdkEventButton* _dialog.update_settings_view(); } - if((e->type == GDK_BUTTON_RELEASE) && (e->button == 3)) { + if ((e->type == GDK_BUTTON_RELEASE) && (e->button == 3)) { const bool sensitive = get_selected() != nullptr; - auto items = _primitive_menu->get_children(); + auto items = _primitive_menu->get_children(); items[0]->set_sensitive(sensitive); items[1]->set_sensitive(sensitive); _primitive_menu->popup_at_pointer(reinterpret_cast<GdkEvent *>(e)); return true; - } - else + } else return Gtk::TreeView::on_button_release_event(e); } // Checks all of prim's inputs, removes any that use result -static 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) { @@ -2529,18 +2490,17 @@ static void check_single_connection(SPFilterPrimitive* prim, const int result) } // Remove any connections going to/from prim_iter that forward-reference other primitives -void FilterEffectsDialog::PrimitiveList::sanitize_connections(const Gtk::TreeIter& prim_iter) +void FilterEffectsDialog::PrimitiveList::sanitize_connections(const Gtk::TreeIter &prim_iter) { SPFilterPrimitive *prim = (*prim_iter)[_columns.primitive]; bool before = true; - for(Gtk::TreeIter iter = _model->children().begin(); - iter != _model->children().end(); ++iter) { - if(iter == prim_iter) + for (Gtk::TreeIter iter = _model->children().begin(); iter != _model->children().end(); ++iter) { + if (iter == prim_iter) before = false; else { - SPFilterPrimitive* cur_prim = (*iter)[_columns.primitive]; - if(before) + SPFilterPrimitive *cur_prim = (*iter)[_columns.primitive]; + if (before) check_single_connection(cur_prim, prim->image_out); else check_single_connection(prim, cur_prim->image_out); @@ -2549,23 +2509,21 @@ void FilterEffectsDialog::PrimitiveList::sanitize_connections(const Gtk::TreeIte } // Reorder the filter primitives to match the list order -void FilterEffectsDialog::PrimitiveList::on_drag_end(const Glib::RefPtr<Gdk::DragContext>& /*dc*/) +void FilterEffectsDialog::PrimitiveList::on_drag_end(const Glib::RefPtr<Gdk::DragContext> & /*dc*/) { - SPFilter* filter = _dialog._filter_modifier.get_selected_filter(); + SPFilter *filter = _dialog._filter_modifier.get_selected_filter(); int ndx = 0; - for (Gtk::TreeModel::iterator iter = _model->children().begin(); - iter != _model->children().end(); ++iter, ++ndx) { - SPFilterPrimitive* prim = (*iter)[_columns.primitive]; + for (Gtk::TreeModel::iterator iter = _model->children().begin(); iter != _model->children().end(); ++iter, ++ndx) { + SPFilterPrimitive *prim = (*iter)[_columns.primitive]; if (prim && prim == _drag_prim) { prim->getRepr()->setPosition(ndx); break; } } - for (Gtk::TreeModel::iterator iter = _model->children().begin(); - iter != _model->children().end(); ++iter, ++ndx) { - SPFilterPrimitive* prim = (*iter)[_columns.primitive]; + for (Gtk::TreeModel::iterator iter = _model->children().begin(); iter != _model->children().end(); ++iter, ++ndx) { + SPFilterPrimitive *prim = (*iter)[_columns.primitive]; if (prim && prim == _drag_prim) { sanitize_connections(iter); get_selection()->select(iter); @@ -2581,13 +2539,13 @@ 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_y) { - auto a = dynamic_cast<Gtk::ScrolledWindow*>(get_parent())->get_vadjustment(); + if (_autoscroll_y) { + auto a = dynamic_cast<Gtk::ScrolledWindow *>(get_parent())->get_vadjustment(); double v = a->get_value() + _autoscroll_y; - - if(v < 0) + + if (v < 0) v = 0; - if(v > a->get_upper() - a->get_page_size()) + if (v > a->get_upper() - a->get_page_size()) v = a->get_upper() - a->get_page_size(); a->set_value(v); @@ -2595,21 +2553,20 @@ bool FilterEffectsDialog::PrimitiveList::on_scroll_timeout() queue_draw(); } - - if(_autoscroll_x) { - auto a_h = dynamic_cast<Gtk::ScrolledWindow*>(get_parent())->get_hadjustment(); + if (_autoscroll_x) { + auto a_h = dynamic_cast<Gtk::ScrolledWindow *>(get_parent())->get_hadjustment(); double h = a_h->get_value() + _autoscroll_x; - - if(h < 0) + + if (h < 0) h = 0; - if(h > a_h->get_upper() - a_h->get_page_size()) + 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); queue_draw(); } - + return true; } @@ -2620,56 +2577,56 @@ int FilterEffectsDialog::PrimitiveList::primitive_count() const int FilterEffectsDialog::PrimitiveList::get_input_type_width() const { - // Maximum font height calculated in initText() and stored in _input_type_width. - // Add 2 to font height to account for rectangle around text. + // Maximum font height calculated in initText() and stored in _input_type_width. + // Add 2 to font height to account for rectangle around text. return _input_type_width + 2; } /*** FilterEffectsDialog ***/ FilterEffectsDialog::FilterEffectsDialog() - : UI::Widget::Panel("/dialogs/filtereffects", SP_VERB_DIALOG_FILTER_EFFECTS), - _add_primitive_type(FPConverter), - _add_primitive(_("Add Effect:")), - _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), - _filter_modifier(*this), - _primitive_list(*this) + : UI::Widget::Panel("/dialogs/filtereffects", SP_VERB_DIALOG_FILTER_EFFECTS) + , _add_primitive_type(FPConverter) + , _add_primitive(_("Add Effect:")) + , _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) + , _filter_modifier(*this) + , _primitive_list(*this) { _settings = new Settings(*this, _settings_tab1, sigc::mem_fun(*this, &FilterEffectsDialog::set_attr_direct), NR_FILTER_ENDPRIMITIVETYPE); - _filter_general_settings = new Settings(*this, _settings_tab2, sigc::mem_fun(*this, &FilterEffectsDialog::set_filternode_attr), - 1); + _filter_general_settings = + new Settings(*this, _settings_tab2, sigc::mem_fun(*this, &FilterEffectsDialog::set_filternode_attr), 1); // Initialize widget hierarchy auto hpaned = Gtk::manage(new Gtk::Paned()); _primitive_box = Gtk::manage(new Gtk::Paned(Gtk::ORIENTATION_VERTICAL)); _sw_infobox = Gtk::manage(new Gtk::ScrolledWindow); - Gtk::ScrolledWindow* sw_prims = 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); - Gtk::VBox* vb_prims = Gtk::manage(new Gtk::VBox); - Gtk::VBox* vb_desc = Gtk::manage(new Gtk::VBox); - - Gtk::VBox* prim_vbox_p = Gtk::manage(new Gtk::VBox); - Gtk::VBox* prim_vbox_i = Gtk::manage(new Gtk::VBox); + Gtk::ScrolledWindow *sw_prims = 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); + Gtk::VBox *vb_prims = Gtk::manage(new Gtk::VBox); + Gtk::VBox *vb_desc = Gtk::manage(new Gtk::VBox); + + Gtk::VBox *prim_vbox_p = Gtk::manage(new Gtk::VBox); + Gtk::VBox *prim_vbox_i = Gtk::manage(new Gtk::VBox); sw_prims->add(_primitive_list); - + prim_vbox_p->pack_start(*sw_prims, true, true); prim_vbox_i->pack_start(*vb_prims, true, true); - + _primitive_box->pack1(*prim_vbox_p); _primitive_box->pack2(*prim_vbox_i, false, false); - + hpaned->pack1(_filter_modifier); hpaned->pack2(*_primitive_box); _getContents()->pack_start(*hpaned, true, true); - + _infobox_icon.set_halign(Gtk::ALIGN_START); _infobox_icon.set_valign(Gtk::ALIGN_START); _infobox_desc.set_halign(Gtk::ALIGN_START); @@ -2677,44 +2634,42 @@ FilterEffectsDialog::FilterEffectsDialog() _infobox_desc.set_justify(Gtk::JUSTIFY_LEFT); _infobox_desc.set_line_wrap(true); _infobox_desc.set_size_request(300, -1); - + vb_desc->pack_start(_infobox_desc, true, true); - + infobox->pack_start(_infobox_icon, false, false); infobox->pack_start(*vb_desc, true, true); - + //_sw_infobox->set_size_request(-1, -1); _sw_infobox->set_size_request(300, -1); _sw_infobox->add(*infobox); - - //vb_prims->set_size_request(-1, 50); + + // vb_prims->set_size_request(-1, 50); vb_prims->pack_start(*hb_prims, false, false); vb_prims->pack_start(*_sw_infobox, true, true); - - hb_prims->pack_start(_add_primitive, false, false); + + hb_prims->pack_start(_add_primitive, false, false); hb_prims->pack_start(_add_primitive_type, true, true); _getContents()->pack_start(_settings_tabs, false, false); _settings_tabs.append_page(_settings_tab1, _("Effect parameters")); _settings_tabs.append_page(_settings_tab2, _("Filter General Settings")); - + _primitive_list.signal_primitive_changed().connect( sigc::mem_fun(*this, &FilterEffectsDialog::update_settings_view)); - _filter_modifier.signal_filter_changed().connect( - sigc::mem_fun(_primitive_list, &PrimitiveList::update)); + _filter_modifier.signal_filter_changed().connect(sigc::mem_fun(_primitive_list, &PrimitiveList::update)); - _add_primitive_type.signal_changed().connect( - sigc::mem_fun(*this, &FilterEffectsDialog::update_primitive_infobox)); + _add_primitive_type.signal_changed().connect(sigc::mem_fun(*this, &FilterEffectsDialog::update_primitive_infobox)); sw_prims->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); sw_prims->set_shadow_type(Gtk::SHADOW_IN); _sw_infobox->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); - -// 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(); + + // 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(); _add_primitive.signal_clicked().connect(sigc::mem_fun(*this, &FilterEffectsDialog::add_primitive)); _primitive_list.set_menu(*this, sigc::mem_fun(*this, &FilterEffectsDialog::duplicate_primitive), - sigc::mem_fun(_primitive_list, &PrimitiveList::remove_selected)); + sigc::mem_fun(_primitive_list, &PrimitiveList::remove_selected)); show_all_children(); init_settings_widgets(); @@ -2762,14 +2717,24 @@ void FilterEffectsDialog::init_settings_widgets() _settings_initialized = true; _filter_general_settings->type(0); - _filter_general_settings->add_multispinbutton(/*default x:*/ (double) -0.1, /*default y:*/ (double) -0.1, SPAttr::X, SPAttr::Y, _("Coordinates:"), -100, 100, 0.01, 0.1, 2, _("X coordinate of the left corners of filter effects region"), _("Y coordinate of the upper corners of filter effects region")); - _filter_general_settings->add_multispinbutton(/*default width:*/ (double) 1.2, /*default height:*/ (double) 1.2, SPAttr::WIDTH, SPAttr::HEIGHT, _("Dimensions:"), 0, 1000, 0.01, 0.1, 2, _("Width of filter effects region"), _("Height of filter effects region")); + _filter_general_settings->add_multispinbutton(/*default x:*/ (double)-0.1, /*default y:*/ (double)-0.1, SPAttr::X, + SPAttr::Y, _("Coordinates:"), -100, 100, 0.01, 0.1, 2, + _("X coordinate of the left corners of filter effects region"), + _("Y coordinate of the upper corners of filter effects region")); + _filter_general_settings->add_multispinbutton(/*default width:*/ (double)1.2, /*default height:*/ (double)1.2, + SPAttr::WIDTH, SPAttr::HEIGHT, _("Dimensions:"), 0, 1000, 0.01, 0.1, + 2, _("Width of filter effects region"), + _("Height of filter effects region")); _settings->type(NR_FILTER_BLEND); _settings->add_combo(SP_CSS_BLEND_NORMAL, SPAttr::MODE, _("Mode:"), SPBlendModeConverter); _settings->type(NR_FILTER_COLORMATRIX); - ComboBoxEnum<FilterColorMatrixType>* colmat = _settings->add_combo(COLORMATRIX_MATRIX, SPAttr::TYPE, _("Type:"), ColorMatrixTypeConverter, _("Indicates the type of matrix operation. The keyword 'matrix' indicates that a full 5x4 matrix of values will be provided. The other keywords represent convenience shortcuts to allow commonly used color operations to be performed without specifying a complete matrix.")); + ComboBoxEnum<FilterColorMatrixType> *colmat = _settings->add_combo( + COLORMATRIX_MATRIX, SPAttr::TYPE, _("Type:"), ColorMatrixTypeConverter, + _("Indicates the type of matrix operation. The keyword 'matrix' indicates that a full 5x4 matrix of values " + "will be provided. The other keywords represent convenience shortcuts to allow commonly used color " + "operations to be performed without specifying a complete matrix.")); _color_matrix_values = _settings->add_colormatrixvalues(_("Value(s):")); colmat->signal_attr_changed().connect(sigc::mem_fun(*this, &FilterEffectsDialog::update_color_matrix)); @@ -2781,66 +2746,119 @@ void FilterEffectsDialog::init_settings_widgets() _settings->type(NR_FILTER_COMPOSITE); _settings->add_combo(COMPOSITE_OVER, SPAttr::OPERATOR, _("Operator:"), CompositeOperatorConverter); - _k1 = _settings->add_spinscale(0, SPAttr::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, SPAttr::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, SPAttr::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, SPAttr::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, SPAttr::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, SPAttr::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, SPAttr::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, SPAttr::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", SPAttr::ORDER, _("Size:"), 1, 5, 1, 1, 0, _("width of the convolve matrix"), _("height of the convolve matrix")); - _convolve_target = _settings->add_multispinbutton(/*default x:*/ (double) 0, /*default y:*/ (double) 0, SPAttr::TARGETX, SPAttr::TARGETY, _("Target:"), 0, 4, 1, 1, 0, _("X coordinate of the target point in the convolve matrix. The convolution is applied to pixels around this point."), _("Y coordinate of the target point in the convolve matrix. The convolution is applied to pixels around this point.")); - //TRANSLATORS: for info on "Kernel", see http://en.wikipedia.org/wiki/Kernel_(matrix) - _convolve_matrix = _settings->add_matrix(SPAttr::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 = + _settings->add_dualspinbutton((char *)"3", SPAttr::ORDER, _("Size:"), 1, 5, 1, 1, 0, + _("width of the convolve matrix"), _("height of the convolve matrix")); + _convolve_target = _settings->add_multispinbutton(/*default x:*/ (double)0, /*default y:*/ (double)0, + SPAttr::TARGETX, SPAttr::TARGETY, _("Target:"), 0, 4, 1, 1, 0, + _("X coordinate of the target point in the convolve matrix. The " + "convolution is applied to pixels around this point."), + _("Y coordinate of the target point in the convolve matrix. The " + "convolution is applied to pixels around this point.")); + // TRANSLATORS: for info on "Kernel", see http://en.wikipedia.org/wiki/Kernel_(matrix) + _convolve_matrix = _settings->add_matrix( + SPAttr::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_spinscale(0, SPAttr::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, SPAttr::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, SPAttr::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, SPAttr::PRESERVEALPHA, _("Preserve Alpha"), "true", "false", _("If set, the alpha channel won't be altered by this filter primitive.")); + _settings->add_spinscale( + 0, SPAttr::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, SPAttr::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, SPAttr::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, SPAttr::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, SPAttr::LIGHTING_COLOR, _("Diffuse Color:"), _("Defines the color of the light source")); - _settings->add_spinscale(1, SPAttr::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, SPAttr::DIFFUSECONSTANT, _("Constant:"), 0, 5, 0.1, 0.01, 2, _("This constant affects the Phong lighting model.")); + _settings->add_color(/*default: white*/ 0xffffffff, SPAttr::LIGHTING_COLOR, _("Diffuse Color:"), + _("Defines the color of the light source")); + _settings->add_spinscale(1, SPAttr::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, SPAttr::DIFFUSECONSTANT, _("Constant:"), 0, 5, 0.1, 0.01, 2, + _("This constant affects the Phong lighting model.")); _settings->add_dualspinscale(SPAttr::KERNELUNITLENGTH, _("Kernel Unit Length:"), 0.01, 10, 1, 0.01, 1); _settings->add_lightsource(); _settings->type(NR_FILTER_DISPLACEMENTMAP); - _settings->add_spinscale(0, SPAttr::SCALE, _("Scale:"), 0, 100, 1, 0.01, 1, _("This defines the intensity of the displacement effect.")); - _settings->add_combo(DISPLACEMENTMAP_CHANNEL_ALPHA, SPAttr::XCHANNELSELECTOR, _("X displacement:"), DisplacementMapChannelConverter, _("Color component that controls the displacement in the X direction")); - _settings->add_combo(DISPLACEMENTMAP_CHANNEL_ALPHA, SPAttr::YCHANNELSELECTOR, _("Y displacement:"), DisplacementMapChannelConverter, _("Color component that controls the displacement in the Y direction")); + _settings->add_spinscale(0, SPAttr::SCALE, _("Scale:"), 0, 100, 1, 0.01, 1, + _("This defines the intensity of the displacement effect.")); + _settings->add_combo(DISPLACEMENTMAP_CHANNEL_ALPHA, SPAttr::XCHANNELSELECTOR, _("X displacement:"), + DisplacementMapChannelConverter, + _("Color component that controls the displacement in the X direction")); + _settings->add_combo(DISPLACEMENTMAP_CHANNEL_ALPHA, SPAttr::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, SPAttr::FLOOD_COLOR, _("Flood Color:"), _("The whole filter region will be filled with this color.")); + _settings->add_color(/*default: black*/ 0, SPAttr::FLOOD_COLOR, _("Flood Color:"), + _("The whole filter region will be filled with this color.")); _settings->add_spinscale(1, SPAttr::FLOOD_OPACITY, _("Opacity:"), 0, 1, 0.1, 0.01, 2); _settings->type(NR_FILTER_GAUSSIANBLUR); - _settings->add_dualspinscale(SPAttr::STDDEVIATION, _("Standard Deviation:"), 0.01, 100, 1, 0.01, 2, _("The standard deviation for the blur operation.")); + _settings->add_dualspinscale(SPAttr::STDDEVIATION, _("Standard Deviation:"), 0.01, 100, 1, 0.01, 2, + _("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, SPAttr::OPERATOR, _("Operator:"), MorphologyOperatorConverter, _("Erode: performs \"thinning\" of input image.\nDilate: performs \"fattening\" of input image.")); + _settings->add_combo( + MORPHOLOGY_OPERATOR_ERODE, SPAttr::OPERATOR, _("Operator:"), MorphologyOperatorConverter, + _("Erode: performs \"thinning\" of input image.\nDilate: performs \"fattening\" of input image.")); _settings->add_dualspinscale(SPAttr::RADIUS, _("Radius:"), 0, 100, 1, 0.01, 1); _settings->type(NR_FILTER_IMAGE); _settings->add_fileorelement(SPAttr::XLINK_HREF, _("Source of Image:")); - _image_x = _settings->add_entry(SPAttr::X,_("X"),_("X")); + _image_x = _settings->add_entry(SPAttr::X, _("X"), _("X")); _image_x->signal_attr_changed().connect(sigc::mem_fun(*this, &FilterEffectsDialog::image_x_changed)); - //This commented because we want the default empty value of X or Y and couldent get it from SpinButton + // This commented because we want the default empty value of X or Y and couldent get it from SpinButton //_image_y = _settings->add_spinbutton(0, SPAttr::Y, _("Y:"), -DBL_MAX, DBL_MAX, 1, 1, 5, _("Y")); - _image_y = _settings->add_entry(SPAttr::Y,_("Y"),_("Y")); + _image_y = _settings->add_entry(SPAttr::Y, _("Y"), _("Y")); _image_y->signal_attr_changed().connect(sigc::mem_fun(*this, &FilterEffectsDialog::image_y_changed)); _settings->type(NR_FILTER_OFFSET); - _settings->add_checkbutton(false, SPAttr::PRESERVEALPHA, _("Preserve Alpha"), "true", "false", _("If set, the alpha channel won't be altered by this filter primitive.")); - _settings->add_spinscale(0, SPAttr::DX, _("Delta X:"), -100, 100, 1, 0.01, 2, _("This is how far the input image gets shifted to the right")); - _settings->add_spinscale(0, SPAttr::DY, _("Delta Y:"), -100, 100, 1, 0.01, 2, _("This is how far the input image gets shifted downwards")); + _settings->add_checkbutton(false, SPAttr::PRESERVEALPHA, _("Preserve Alpha"), "true", "false", + _("If set, the alpha channel won't be altered by this filter primitive.")); + _settings->add_spinscale(0, SPAttr::DX, _("Delta X:"), -100, 100, 1, 0.01, 2, + _("This is how far the input image gets shifted to the right")); + _settings->add_spinscale(0, SPAttr::DY, _("Delta Y:"), -100, 100, 1, 0.01, 2, + _("This is how far the input image gets shifted downwards")); _settings->type(NR_FILTER_SPECULARLIGHTING); - _settings->add_color(/*default: white*/ 0xffffffff, SPAttr::LIGHTING_COLOR, _("Specular Color:"), _("Defines the color of the light source")); - _settings->add_spinscale(1, SPAttr::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, SPAttr::SPECULARCONSTANT, _("Constant:"), 0, 5, 0.1, 0.01, 2, _("This constant affects the Phong lighting model.")); - _settings->add_spinscale(1, SPAttr::SPECULAREXPONENT, _("Exponent:"), 1, 50, 1, 0.01, 1, _("Exponent for specular term, larger is more \"shiny\".")); + _settings->add_color(/*default: white*/ 0xffffffff, SPAttr::LIGHTING_COLOR, _("Specular Color:"), + _("Defines the color of the light source")); + _settings->add_spinscale(1, SPAttr::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, SPAttr::SPECULARCONSTANT, _("Constant:"), 0, 5, 0.1, 0.01, 2, + _("This constant affects the Phong lighting model.")); + _settings->add_spinscale(1, SPAttr::SPECULAREXPONENT, _("Exponent:"), 1, 50, 1, 0.01, 1, + _("Exponent for specular term, larger is more \"shiny\".")); _settings->add_dualspinscale(SPAttr::KERNELUNITLENGTH, _("Kernel Unit Length:"), 0.01, 10, 1, 0.01, 1); _settings->add_lightsource(); @@ -2848,19 +2866,21 @@ void FilterEffectsDialog::init_settings_widgets() _settings->add_no_params(); _settings->type(NR_FILTER_TURBULENCE); -// _settings->add_checkbutton(false, SPAttr::STITCHTILES, _("Stitch Tiles"), "stitch", "noStitch"); - _settings->add_combo(TURBULENCE_TURBULENCE, SPAttr::TYPE, _("Type:"), TurbulenceTypeConverter, _("Indicates whether the filter primitive should perform a noise or turbulence function.")); + // _settings->add_checkbutton(false, SPAttr::STITCHTILES, _("Stitch Tiles"), "stitch", "noStitch"); + _settings->add_combo(TURBULENCE_TURBULENCE, SPAttr::TYPE, _("Type:"), TurbulenceTypeConverter, + _("Indicates whether the filter primitive should perform a noise or turbulence function.")); _settings->add_dualspinscale(SPAttr::BASEFREQUENCY, _("Base Frequency:"), 0, 1, 0.001, 0.01, 3); _settings->add_spinscale(1, SPAttr::NUMOCTAVES, _("Octaves:"), 1, 10, 1, 1, 0); - _settings->add_spinscale(0, SPAttr::SEED, _("Seed:"), 0, 1000, 1, 1, 0, _("The starting number for the pseudo random number generator.")); + _settings->add_spinscale(0, SPAttr::SEED, _("Seed:"), 0, 1000, 1, 1, 0, + _("The starting number for the pseudo random number generator.")); } void FilterEffectsDialog::add_primitive() { - SPFilter* filter = _filter_modifier.get_selected_filter(); + SPFilter *filter = _filter_modifier.get_selected_filter(); - if(filter) { - SPFilterPrimitive* prim = filter_add_primitive(filter, _add_primitive_type.get_active_data()->id); + if (filter) { + SPFilterPrimitive *prim = filter_add_primitive(filter, _add_primitive_type.get_active_data()->id); _primitive_list.select(prim); @@ -2871,75 +2891,119 @@ void FilterEffectsDialog::add_primitive() void FilterEffectsDialog::update_primitive_infobox() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (prefs->getBool("/options/showfiltersinfobox/value", true)){ + if (prefs->getBool("/options/showfiltersinfobox/value", true)) { _sw_infobox->show(); } else { _sw_infobox->hide(); } - switch(_add_primitive_type.get_active_data()->id){ - case(NR_FILTER_BLEND): + switch (_add_primitive_type.get_active_data()->id) { + case (NR_FILTER_BLEND): _infobox_icon.set_from_icon_name("feBlend-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feBlend</b> filter primitive provides 4 image blending modes: screen, multiply, darken and lighten.")); + _infobox_desc.set_markup(_("The <b>feBlend</b> filter primitive provides 4 image blending modes: screen, " + "multiply, darken and lighten.")); break; - case(NR_FILTER_COLORMATRIX): + case (NR_FILTER_COLORMATRIX): _infobox_icon.set_from_icon_name("feColorMatrix-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feColorMatrix</b> filter primitive applies a matrix transformation to color of each rendered pixel. This allows for effects like turning object to grayscale, modifying color saturation and changing color hue.")); + _infobox_desc.set_markup( + _("The <b>feColorMatrix</b> filter primitive applies a matrix transformation to color " + "of each rendered pixel. This allows for effects like turning object to grayscale, " + "modifying color saturation and changing color hue.")); break; - case(NR_FILTER_COMPONENTTRANSFER): + case (NR_FILTER_COMPONENTTRANSFER): _infobox_icon.set_from_icon_name("feComponentTransfer-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feComponentTransfer</b> filter primitive manipulates the input's color components (red, green, blue, and alpha) according to particular transfer functions, allowing operations like brightness and contrast adjustment, color balance, and thresholding.")); + _infobox_desc.set_markup(_( + "The <b>feComponentTransfer</b> filter primitive manipulates the input's color components (red, green, " + "blue, and alpha) according to particular transfer functions, allowing operations like brightness and " + "contrast adjustment, color balance, and thresholding.")); break; - case(NR_FILTER_COMPOSITE): + case (NR_FILTER_COMPOSITE): _infobox_icon.set_from_icon_name("feComposite-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feComposite</b> filter primitive composites two images using one of the Porter-Duff blending modes or the arithmetic mode described in SVG standard. Porter-Duff blending modes are essentially logical operations between the corresponding pixel values of the images.")); + _infobox_desc.set_markup( + _("The <b>feComposite</b> filter primitive composites two images using one of the Porter-Duff blending " + "modes or the arithmetic mode described in SVG standard. Porter-Duff blending modes are essentially " + "logical operations between the corresponding pixel values of the images.")); break; - case(NR_FILTER_CONVOLVEMATRIX): + case (NR_FILTER_CONVOLVEMATRIX): _infobox_icon.set_from_icon_name("feConvolveMatrix-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feConvolveMatrix</b> lets you specify a Convolution to be applied on the image. Common effects created using convolution matrices are blur, sharpening, embossing and edge detection. Note that while gaussian blur can be created using this filter primitive, the special gaussian blur primitive is faster and resolution-independent.")); + _infobox_desc.set_markup(_( + "The <b>feConvolveMatrix</b> lets you specify a Convolution to be applied on the image. Common effects " + "created using convolution matrices are blur, sharpening, embossing and edge detection. Note that " + "while " + "gaussian blur can be created using this filter primitive, the special gaussian blur primitive is " + "faster " + "and resolution-independent.")); break; - case(NR_FILTER_DIFFUSELIGHTING): + case (NR_FILTER_DIFFUSELIGHTING): _infobox_icon.set_from_icon_name("feDiffuseLighting-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feDiffuseLighting</b> and feSpecularLighting 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 feSpecularLighting 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_DISPLACEMENTMAP): + case (NR_FILTER_DISPLACEMENTMAP): _infobox_icon.set_from_icon_name("feDisplacementMap-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feDisplacementMap</b> filter primitive displaces the pixels in the first input using the second input as a displacement map, that shows from how far the pixel should come from. Classical examples are whirl and pinch effects.")); + _infobox_desc.set_markup( + _("The <b>feDisplacementMap</b> filter primitive displaces the pixels in the first " + "input using the second input as a displacement map, that shows from how far the " + "pixel should come from. Classical examples are whirl and pinch effects.")); break; - case(NR_FILTER_FLOOD): + case (NR_FILTER_FLOOD): _infobox_icon.set_from_icon_name("feFlood-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feFlood</b> filter primitive fills the region with a given color and opacity. It is usually used as an input to other filters to apply color to a graphic.")); + _infobox_desc.set_markup( + _("The <b>feFlood</b> filter primitive fills the region with a given color and opacity. It is usually " + "used as an input to other filters to apply color to a graphic.")); break; - case(NR_FILTER_GAUSSIANBLUR): + case (NR_FILTER_GAUSSIANBLUR): _infobox_icon.set_from_icon_name("feGaussianBlur-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feGaussianBlur</b> filter primitive uniformly blurs its input. It is commonly used together with feOffset to create a drop shadow effect.")); + _infobox_desc.set_markup(_("The <b>feGaussianBlur</b> filter primitive uniformly blurs its input. It is " + "commonly used together with feOffset to create a drop shadow effect.")); break; - case(NR_FILTER_IMAGE): + case (NR_FILTER_IMAGE): _infobox_icon.set_from_icon_name("feImage-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feImage</b> filter primitive fills the region with an external image or another part of the document.")); + _infobox_desc.set_markup(_("The <b>feImage</b> filter primitive fills the region with an external image or " + "another part of the document.")); break; - case(NR_FILTER_MERGE): + case (NR_FILTER_MERGE): _infobox_icon.set_from_icon_name("feMerge-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feMerge</b> filter primitive composites several temporary images inside the filter primitive to a single image. It uses normal alpha compositing for this. This is equivalent to using several feBlend primitives in 'normal' mode or several feComposite primitives in 'over' mode.")); + _infobox_desc.set_markup( + _("The <b>feMerge</b> filter primitive composites several temporary images inside the filter primitive " + "to " + "a single image. It uses normal alpha compositing for this. This is equivalent to using several " + "feBlend " + "primitives in 'normal' mode or several feComposite primitives in 'over' mode.")); break; - case(NR_FILTER_MORPHOLOGY): + case (NR_FILTER_MORPHOLOGY): _infobox_icon.set_from_icon_name("feMorphology-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feMorphology</b> filter primitive provides erode and dilate effects. For single-color objects erode makes the object thinner and dilate makes it thicker.")); + _infobox_desc.set_markup( + _("The <b>feMorphology</b> filter primitive provides erode and dilate effects. For " + "single-color objects erode makes the object thinner and dilate makes it thicker.")); break; - case(NR_FILTER_OFFSET): + case (NR_FILTER_OFFSET): _infobox_icon.set_from_icon_name("feOffset-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feOffset</b> filter primitive offsets the image by an user-defined amount. For example, this is useful for drop shadows, where the shadow is in a slightly different position than the actual object.")); + _infobox_desc.set_markup(_("The <b>feOffset</b> filter primitive offsets the image by an user-defined " + "amount. For example, this is " + "useful for drop shadows, where the shadow is in a slightly different position " + "than the actual object.")); break; - case(NR_FILTER_SPECULARLIGHTING): + case (NR_FILTER_SPECULARLIGHTING): _infobox_icon.set_from_icon_name("feSpecularLighting-icon", Gtk::ICON_SIZE_DIALOG); - _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.")); + _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): + case (NR_FILTER_TILE): _infobox_icon.set_from_icon_name("feTile-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feTile</b> filter primitive tiles a region with an input graphic. The source tile is defined by the filter primitive subregion of the input.")); + _infobox_desc.set_markup(_("The <b>feTile</b> filter primitive tiles a region with an input graphic. The " + "source tile is defined by the filter primitive subregion of the input.")); break; - case(NR_FILTER_TURBULENCE): + case (NR_FILTER_TURBULENCE): _infobox_icon.set_from_icon_name("feTurbulence-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The <b>feTurbulence</b> filter primitive renders Perlin noise. This kind of noise is useful in simulating several nature phenomena like clouds, fire and smoke and in generating complex textures like marble or granite.")); + _infobox_desc.set_markup( + _("The <b>feTurbulence</b> filter primitive renders Perlin noise. This kind of noise " + "is useful in simulating several nature phenomena like clouds, fire and smoke and " + "in generating complex textures like marble or granite.")); break; default: g_assert(false); @@ -2951,8 +3015,8 @@ void FilterEffectsDialog::update_primitive_infobox() void FilterEffectsDialog::duplicate_primitive() { - SPFilter* filter = _filter_modifier.get_selected_filter(); - SPFilterPrimitive* origprim = _primitive_list.get_selected(); + SPFilter *filter = _filter_modifier.get_selected_filter(); + SPFilterPrimitive *origprim = _primitive_list.get_selected(); if (filter && origprim) { Inkscape::XML::Node *repr; @@ -2968,20 +3032,22 @@ void FilterEffectsDialog::duplicate_primitive() void FilterEffectsDialog::convolve_order_changed() { _convolve_matrix->set_from_attribute(_primitive_list.get_selected()); - _convolve_target->get_spinbuttons()[0]->get_adjustment()->set_upper(_convolve_order->get_spinbutton1().get_value() - 1); - _convolve_target->get_spinbuttons()[1]->get_adjustment()->set_upper(_convolve_order->get_spinbutton2().get_value() - 1); + _convolve_target->get_spinbuttons()[0]->get_adjustment()->set_upper(_convolve_order->get_spinbutton1().get_value() - + 1); + _convolve_target->get_spinbuttons()[1]->get_adjustment()->set_upper(_convolve_order->get_spinbutton2().get_value() - + 1); } -bool number_or_empy(const Glib::ustring& text) { +bool number_or_empy(const Glib::ustring &text) +{ if (text.empty()) { return true; } - double n = atof( text.c_str() ); + double n = atof(text.c_str()); if (n == 0.0 && strcmp(text.c_str(), "0") != 0 && strcmp(text.c_str(), "0.0") != 0) { - return false; - } - else { - return true; + return false; + } else { + return true; } } @@ -2999,18 +3065,18 @@ void FilterEffectsDialog::image_y_changed() } } -void FilterEffectsDialog::set_attr_direct(const AttrWidget* input) +void FilterEffectsDialog::set_attr_direct(const AttrWidget *input) { set_attr(_primitive_list.get_selected(), input->get_attribute(), input->get_as_attribute().c_str()); } -void FilterEffectsDialog::set_filternode_attr(const AttrWidget* input) +void FilterEffectsDialog::set_filternode_attr(const AttrWidget *input) { - if(!_locked) { + if (!_locked) { _attr_lock = true; SPFilter *filter = _filter_modifier.get_selected_filter(); - const gchar* name = (const gchar*)sp_attribute_name(input->get_attribute()); - if (filter && name && filter->getRepr()){ + const gchar *name = (const gchar *)sp_attribute_name(input->get_attribute()); + if (filter && name && filter->getRepr()) { filter->setAttributeOrRemoveIfEmpty(name, input->get_as_attribute()); filter->requestModified(SP_OBJECT_MODIFIED_FLAG); } @@ -3018,19 +3084,19 @@ void FilterEffectsDialog::set_filternode_attr(const AttrWidget* input) } } -void FilterEffectsDialog::set_child_attr_direct(const AttrWidget* input) +void FilterEffectsDialog::set_child_attr_direct(const AttrWidget *input) { set_attr(_primitive_list.get_selected()->firstChild(), input->get_attribute(), input->get_as_attribute().c_str()); } -void FilterEffectsDialog::set_attr(SPObject* o, const SPAttr attr, const gchar* val) +void FilterEffectsDialog::set_attr(SPObject *o, const SPAttr attr, const gchar *val) { - if(!_locked) { + if (!_locked) { _attr_lock = true; SPFilter *filter = _filter_modifier.get_selected_filter(); - const gchar* name = (const gchar*)sp_attribute_name(attr); - if(filter && name && o) { + const gchar *name = (const gchar *)sp_attribute_name(attr); + if (filter && name && o) { update_settings_sensitivity(); o->setAttribute(name, val); @@ -3048,19 +3114,19 @@ void FilterEffectsDialog::set_attr(SPObject* o, const SPAttr attr, const gchar* void FilterEffectsDialog::update_filter_general_settings_view() { - if(_settings_initialized != true) return; + if (_settings_initialized != true) + return; - if(!_locked) { + if (!_locked) { _attr_lock = true; - SPFilter* filter = _filter_modifier.get_selected_filter(); + SPFilter *filter = _filter_modifier.get_selected_filter(); - if(filter) { + if (filter) { _filter_general_settings->show_and_update(0, filter); _no_filter_selected.hide(); - } - else { - std::vector<Gtk::Widget*> vect = _settings_tab2.get_children(); + } else { + std::vector<Gtk::Widget *> vect = _settings_tab2.get_children(); vect[0]->hide(); _no_filter_selected.show(); } @@ -3073,56 +3139,53 @@ void FilterEffectsDialog::update_settings_view() { update_settings_sensitivity(); - if(_attr_lock) + if (_attr_lock) return; -//First Tab + // First Tab - std::vector<Gtk::Widget*> vect1 = _settings_tab1.get_children(); - for(auto & i : vect1) - i->hide(); + std::vector<Gtk::Widget *> vect1 = _settings_tab1.get_children(); + for (auto &i : vect1) + i->hide(); _empty_settings.show(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (prefs->getBool("/options/showfiltersinfobox/value", true)){ + if (prefs->getBool("/options/showfiltersinfobox/value", true)) { _sw_infobox->show(); } else { _sw_infobox->hide(); } - SPFilterPrimitive* prim = _primitive_list.get_selected(); - - if(prim && prim->getRepr()) { + SPFilterPrimitive *prim = _primitive_list.get_selected(); - //XML Tree being used directly here while it shouldn't be. + if (prim && prim->getRepr()) { + // XML Tree being used directly here while it shouldn't be. _settings->show_and_update(FPConverter.get_id_from_key(prim->getRepr()->name()), prim); _empty_settings.hide(); } -//Second Tab + // Second Tab - std::vector<Gtk::Widget*> vect2 = _settings_tab2.get_children(); + std::vector<Gtk::Widget *> vect2 = _settings_tab2.get_children(); vect2[0]->hide(); _no_filter_selected.show(); - SPFilter* filter = _filter_modifier.get_selected_filter(); + SPFilter *filter = _filter_modifier.get_selected_filter(); - if(filter) { + if (filter) { _filter_general_settings->show_and_update(0, filter); _no_filter_selected.hide(); } - } void FilterEffectsDialog::update_settings_sensitivity() { - SPFilterPrimitive* prim = _primitive_list.get_selected(); + SPFilterPrimitive *prim = _primitive_list.get_selected(); const bool use_k = SP_IS_FECOMPOSITE(prim) && SP_FECOMPOSITE(prim)->composite_operator == COMPOSITE_ARITHMETIC; _k1->set_sensitive(use_k); _k2->set_sensitive(use_k); _k3->set_sensitive(use_k); _k4->set_sensitive(use_k); - } void FilterEffectsDialog::update_color_matrix() diff --git a/src/ui/dialog/filter-effects-dialog.h b/src/ui/dialog/filter-effects-dialog.h index 0b2e091cd283b941c722ce1c7b823691b4a083b2..db68f5c16c8e9566b7426a166b75d69f84535ce2 100644 --- a/src/ui/dialog/filter-effects-dialog.h +++ b/src/ui/dialog/filter-effects-dialog.h @@ -15,21 +15,18 @@ #ifndef INKSCAPE_UI_DIALOG_FILTER_EFFECTS_H #define INKSCAPE_UI_DIALOG_FILTER_EFFECTS_H -#include <memory> - #include <glibmm/property.h> #include <glibmm/propertyproxy.h> #include <gtkmm/notebook.h> - #include <gtkmm/paned.h> #include <gtkmm/scrolledwindow.h> +#include <memory> #include "attributes.h" #include "display/nr-filter-types.h" #include "ui/widget/combo-enums.h" #include "ui/widget/panel.h" #include "ui/widget/spin-scale.h" - #include "xml/helper-observer.h" class SPFilter; @@ -40,38 +37,36 @@ namespace UI { namespace Dialog { class EntryAttr; -//class SpinButtonAttr; +// class SpinButtonAttr; class DualSpinButton; class MultiSpinButton; -class FilterEffectsDialog : public UI::Widget::Panel { +class FilterEffectsDialog : public UI::Widget::Panel +{ public: - FilterEffectsDialog(); ~FilterEffectsDialog() override; void setDesktop(SPDesktop *) override; - static FilterEffectsDialog &getInstance() - { return *new FilterEffectsDialog(); } + static FilterEffectsDialog &getInstance() { return *new FilterEffectsDialog(); } void set_attrs_locked(const bool); + protected: void show_all_vfunc() override; -private: +private: class FilterModifier : public Gtk::VBox { public: - FilterModifier(FilterEffectsDialog&); + FilterModifier(FilterEffectsDialog &); ~FilterModifier() override; - SPFilter* get_selected_filter(); - void select_filter(const SPFilter*); + SPFilter *get_selected_filter(); + void select_filter(const SPFilter *); + + sigc::signal<void> &signal_filter_changed() { return _signal_filter_changed; } - sigc::signal<void>& signal_filter_changed() - { - return _signal_filter_changed; - } private: class Columns : public Gtk::TreeModel::ColumnRecord { @@ -84,30 +79,30 @@ private: add(count); } - Gtk::TreeModelColumn<SPFilter*> filter; + Gtk::TreeModelColumn<SPFilter *> filter; Gtk::TreeModelColumn<Glib::ustring> label; Gtk::TreeModelColumn<int> sel; Gtk::TreeModelColumn<int> count; }; - public: + public: void setTargetDesktop(SPDesktop *desktop); - - private: + + private: void on_document_replaced(SPDesktop *desktop, SPDocument *document); void on_change_selection(); - void on_modified_selection( guint flags ); - + 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 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_counts(); void update_filters(); - void filter_list_button_release(GdkEventButton*); + void filter_list_button_release(GdkEventButton *); void add_filter(); void remove_filter(); void duplicate_filter(); @@ -127,13 +122,13 @@ private: sigc::connection _doc_replaced; sigc::connection _resource_changed; - FilterEffectsDialog& _dialog; + FilterEffectsDialog &_dialog; Gtk::TreeView _list; Glib::RefPtr<Gtk::ListStore> _model; Columns _columns; Gtk::CellRendererToggle _cell_toggle; Gtk::Button _add; - Gtk::Menu *_menu; + Gtk::Menu *_menu; sigc::signal<void> _signal_filter_changed; std::unique_ptr<Inkscape::XML::SignalObserver> _observer; }; @@ -149,7 +144,7 @@ private: add(id); } - Gtk::TreeModelColumn<SPFilterPrimitive*> primitive; + Gtk::TreeModelColumn<SPFilterPrimitive *> primitive; Gtk::TreeModelColumn<Inkscape::Filters::FilterPrimitiveType> type_id; Gtk::TreeModelColumn<Glib::ustring> type; Gtk::TreeModelColumn<Glib::ustring> id; @@ -159,47 +154,38 @@ private: { public: CellRendererConnection(); - Glib::PropertyProxy<void*> property_primitive(); + Glib::PropertyProxy<void *> property_primitive(); static const int size = 24; - + protected: - void get_preferred_width_vfunc(Gtk::Widget& widget, - int& minimum_width, - int& natural_width) const override; - - void get_preferred_width_for_height_vfunc(Gtk::Widget& widget, - int height, - int& minimum_width, - int& natural_width) const override; - - void get_preferred_height_vfunc(Gtk::Widget& widget, - int& minimum_height, - int& natural_height) const override; - - void get_preferred_height_for_width_vfunc(Gtk::Widget& widget, - int width, - int& minimum_height, - int& natural_height) const override; + void get_preferred_width_vfunc(Gtk::Widget &widget, int &minimum_width, int &natural_width) const override; + + void get_preferred_width_for_height_vfunc(Gtk::Widget &widget, int height, int &minimum_width, + int &natural_width) const override; + + void get_preferred_height_vfunc(Gtk::Widget &widget, int &minimum_height, int &natural_height) const override; + + void get_preferred_height_for_width_vfunc(Gtk::Widget &widget, int width, int &minimum_height, + int &natural_height) const override; + private: // void* should be SPFilterPrimitive*, some weirdness with properties prevents this - Glib::Property<void*> _primitive; + Glib::Property<void *> _primitive; int _text_width; }; class PrimitiveList : public Gtk::TreeView { public: - PrimitiveList(FilterEffectsDialog&); + PrimitiveList(FilterEffectsDialog &); - sigc::signal<void>& signal_primitive_changed(); + sigc::signal<void> &signal_primitive_changed(); void update(); - void set_menu(Gtk::Widget &parent, - sigc::slot<void> dup, - sigc::slot<void> rem); + void set_menu(Gtk::Widget &parent, sigc::slot<void> dup, sigc::slot<void> rem); - SPFilterPrimitive* get_selected(); + SPFilterPrimitive *get_selected(); void select(SPFilterPrimitive *prim); void remove_selected(); @@ -209,38 +195,36 @@ private: protected: bool on_draw_signal(const Cairo::RefPtr<Cairo::Context> &cr); + bool on_button_press_event(GdkEventButton *) override; + bool on_motion_notify_event(GdkEventMotion *) override; + bool on_button_release_event(GdkEventButton *) override; + void on_drag_end(const Glib::RefPtr<Gdk::DragContext> &) override; - bool on_button_press_event(GdkEventButton*) override; - bool on_motion_notify_event(GdkEventMotion*) override; - bool on_button_release_event(GdkEventButton*) override; - void on_drag_end(const Glib::RefPtr<Gdk::DragContext>&) override; private: void init_text(); - void draw_connection_node(const Cairo::RefPtr<Cairo::Context>& cr, - const std::vector<Gdk::Point>& points, - const bool fill); + 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, + 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 SPAttr attr, int& src_id, const int pos); - int find_index(const Gtk::TreeIter& target); - void draw_connection(const Cairo::RefPtr<Cairo::Context>& cr, - const Gtk::TreeIter&, const SPAttr attr, const int text_start_x, - const int x1, const int y1, const int row_count, const int pos); - void sanitize_connections(const Gtk::TreeIter& prim_iter); + const Gtk::TreeIter find_result(const Gtk::TreeIter &start, const SPAttr attr, int &src_id, const int pos); + int find_index(const Gtk::TreeIter &target); + void draw_connection(const Cairo::RefPtr<Cairo::Context> &cr, const Gtk::TreeIter &, const SPAttr attr, + const int text_start_x, const int x1, const int y1, const int row_count, const int pos); + void sanitize_connections(const Gtk::TreeIter &prim_iter); void on_primitive_selection_changed(); bool on_scroll_timeout(); - FilterEffectsDialog& _dialog; + FilterEffectsDialog &_dialog; Glib::RefPtr<Gtk::ListStore> _model; PrimitiveColumns _columns; CellRendererConnection _connection_cell; Gtk::Menu *_primitive_menu; Glib::RefPtr<Pango::Layout> _vertical_layout; int _in_drag; - SPFilterPrimitive* _drag_prim; + SPFilterPrimitive *_drag_prim; sigc::signal<void> _signal_primitive_changed; sigc::connection _scroll_connection; int _autoscroll_y; @@ -260,24 +244,24 @@ private: void image_x_changed(); void image_y_changed(); - void set_attr_direct(const UI::Widget::AttrWidget*); - void set_child_attr_direct(const UI::Widget::AttrWidget*); - void set_filternode_attr(const UI::Widget::AttrWidget*); - void set_attr(SPObject*, const SPAttr, const gchar* val); + void set_attr_direct(const UI::Widget::AttrWidget *); + void set_child_attr_direct(const UI::Widget::AttrWidget *); + void set_filternode_attr(const UI::Widget::AttrWidget *); + void set_attr(SPObject *, const SPAttr, const gchar *val); void update_settings_view(); void update_filter_general_settings_view(); void update_settings_sensitivity(); void update_color_matrix(); void update_primitive_infobox(); - // Primitives Info Box + // Primitives Info Box Gtk::Label _infobox_desc; Gtk::Image _infobox_icon; - Gtk::ScrolledWindow* _sw_infobox; + Gtk::ScrolledWindow *_sw_infobox; // View/add primitives - Gtk::Paned* _primitive_box; - + Gtk::Paned *_primitive_box; + UI::Widget::ComboBoxEnum<Inkscape::Filters::FilterPrimitiveType> _add_primitive_type; Gtk::Button _add_primitive; @@ -294,26 +278,26 @@ private: class ColorMatrixValues; class ComponentTransferValues; class LightSourceControl; - Settings* _settings; - Settings* _filter_general_settings; + Settings *_settings; + Settings *_filter_general_settings; // Color Matrix - ColorMatrixValues* _color_matrix_values; + ColorMatrixValues *_color_matrix_values; // Component Transfer - ComponentTransferValues* _component_transfer_values; + ComponentTransferValues *_component_transfer_values; // Convolve Matrix - MatrixAttr* _convolve_matrix; - DualSpinButton* _convolve_order; - MultiSpinButton* _convolve_target; + MatrixAttr *_convolve_matrix; + DualSpinButton *_convolve_order; + MultiSpinButton *_convolve_target; // Image - EntryAttr* _image_x; - EntryAttr* _image_y; - + EntryAttr *_image_x; + EntryAttr *_image_y; + // For controlling setting sensitivity - Gtk::Widget* _k1, *_k2, *_k3, *_k4; + Gtk::Widget *_k1, *_k2, *_k3, *_k4; // To prevent unwanted signals bool _locked; @@ -325,7 +309,7 @@ private: PrimitiveList _primitive_list; FilterEffectsDialog(FilterEffectsDialog const &d); - FilterEffectsDialog& operator=(FilterEffectsDialog const &d); + FilterEffectsDialog &operator=(FilterEffectsDialog const &d); }; } // namespace Dialog diff --git a/src/ui/dialog/find.cpp b/src/ui/dialog/find.cpp index c84fcdef45990e81a49604b1df1831092940dc31..26370b2b933ccbcb420e13093753593c791a0ea1 100644 --- a/src/ui/dialog/find.cpp +++ b/src/ui/dialog/find.cpp @@ -13,19 +13,15 @@ #include "find.h" -#include <gtkmm/entry.h> #include <glibmm/i18n.h> #include <glibmm/regex.h> +#include <gtkmm/entry.h> #include "desktop.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" #include "message-stack.h" -#include "selection-chemistry.h" -#include "text-editing.h" -#include "verbs.h" - #include "object/sp-defs.h" #include "object/sp-ellipse.h" #include "object/sp-flowdiv.h" @@ -43,69 +39,76 @@ #include "object/sp-tref.h" #include "object/sp-tspan.h" #include "object/sp-use.h" - +#include "selection-chemistry.h" +#include "text-editing.h" #include "ui/dialog-events.h" - +#include "verbs.h" #include "xml/attribute-record.h" #include "xml/node-iterators.h" - namespace Inkscape { namespace UI { namespace Dialog { 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(_("R_eplace:"), _("Replace match with this value")), - - check_scope_all(_("_All")), - check_scope_layer(_("Current _layer")), - check_scope_selection(_("Sele_ction")), - check_searchin_text(_("_Text")), - check_searchin_property(_("_Properties")), - vbox_searchin(false, false), - frame_searchin(_("Search in")), - frame_scope(_("Scope")), - - check_case_sensitive(_("Case sensiti_ve")), - check_exact_match(_("E_xact match")), - check_include_hidden(_("Include _hidden")), - check_include_locked(_("Include loc_ked")), - expander_options(_("Options")), - frame_options(_("General")), - - check_ids(_("_ID")), - check_attributename(_("Attribute _name")), - check_attributevalue(_("Attri_bute value")), - check_style(_("_Style")), - check_font(_("F_ont")), - check_desc(_("_Desc")), - check_title(_("Title")), - frame_properties(_("Properties")), - - check_alltypes(_("All types")), - check_rects(_("Rectangles")), - check_ellipses(_("Ellipses")), - check_stars(_("Stars")), - check_spirals(_("Spirals")), - check_paths(_("Paths")), - check_texts(_("Texts")), - check_groups(_("Groups")), - check_clones( - //TRANSLATORS: "Clones" is a noun indicating type of object to find - C_("Find dialog", "Clones")), - - check_images(_("Images")), - check_offsets(_("Offsets")), - frame_types(_("Object types")), - - status(""), - button_find(_("_Find")), - button_replace(_("_Replace All")), - _action_replace(false), - blocked(false) + : 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(_("R_eplace:"), _("Replace match with this value")) + , + + check_scope_all(_("_All")) + , check_scope_layer(_("Current _layer")) + , check_scope_selection(_("Sele_ction")) + , check_searchin_text(_("_Text")) + , check_searchin_property(_("_Properties")) + , vbox_searchin(false, false) + , frame_searchin(_("Search in")) + , frame_scope(_("Scope")) + , + + check_case_sensitive(_("Case sensiti_ve")) + , check_exact_match(_("E_xact match")) + , check_include_hidden(_("Include _hidden")) + , check_include_locked(_("Include loc_ked")) + , expander_options(_("Options")) + , frame_options(_("General")) + , + + check_ids(_("_ID")) + , check_attributename(_("Attribute _name")) + , check_attributevalue(_("Attri_bute value")) + , check_style(_("_Style")) + , check_font(_("F_ont")) + , check_desc(_("_Desc")) + , check_title(_("Title")) + , frame_properties(_("Properties")) + , + + check_alltypes(_("All types")) + , check_rects(_("Rectangles")) + , check_ellipses(_("Ellipses")) + , check_stars(_("Stars")) + , check_spirals(_("Spirals")) + , check_paths(_("Paths")) + , check_texts(_("Texts")) + , check_groups(_("Groups")) + , check_clones( + // TRANSLATORS: "Clones" is a noun indicating type of object to find + C_("Find dialog", "Clones")) + , + + check_images(_("Images")) + , check_offsets(_("Offsets")) + , frame_types(_("Object types")) + , + + status("") + , button_find(_("_Find")) + , button_replace(_("_Replace All")) + , _action_replace(false) + , blocked(false) { _left_size_group = Gtk::SizeGroup::create(Gtk::SIZE_GROUP_HORIZONTAL); @@ -180,8 +183,7 @@ Find::Find() check_texts.set_active(false); check_groups.set_use_underline(); check_groups.set_tooltip_text(_("Search groups")); - check_groups.set_active(false), - check_clones.set_use_underline(); + check_groups.set_active(false), check_clones.set_use_underline(); check_clones.set_tooltip_text(_("Search clones")); check_clones.set_active(false); check_images.set_use_underline(); @@ -327,11 +329,11 @@ Find::Find() check_searchin_property.signal_clicked().connect(sigc::mem_fun(*this, &Find::onSearchinProperty)); check_alltypes.signal_clicked().connect(sigc::mem_fun(*this, &Find::onToggleAlltypes)); - for (auto & checkProperty : checkProperties) { + for (auto &checkProperty : checkProperties) { checkProperty->signal_clicked().connect(sigc::mem_fun(*this, &Find::onToggleCheck)); } - for (auto & checkType : checkTypes) { + for (auto &checkType : checkTypes) { checkType->signal_clicked().connect(sigc::mem_fun(*this, &Find::onToggleCheck)); } @@ -341,7 +343,7 @@ Find::Find() show_all_children(); button_find.set_can_default(); - //button_find.grab_default(); // activatable by Enter + // button_find.grab_default(); // activatable by Enter entry_find.getEntry()->grab_focus(); } @@ -385,7 +387,8 @@ void Find::onSelectionChange() # FIND helper functions ########################################################################*/ -Glib::ustring Find::find_replace(const gchar *str, const gchar *find, const gchar *replace, bool exact, bool casematch, bool replaceall) +Glib::ustring Find::find_replace(const gchar *str, const gchar *find, const gchar *replace, bool exact, bool casematch, + bool replaceall) { Glib::ustring ustr = str; Glib::ustring ufind = find; @@ -404,7 +407,7 @@ Glib::ustring Find::find_replace(const gchar *str, const gchar *find, const gcha return ustr; } -gsize Find::find_strcmp_pos(const gchar *str, const gchar *find, bool exact, bool casematch, gsize start/*=0*/) +gsize Find::find_strcmp_pos(const gchar *str, const gchar *find, bool exact, bool casematch, gsize start /*=0*/) { Glib::ustring ustr = str ? str : ""; Glib::ustring ufind = find; @@ -426,37 +429,38 @@ gsize Find::find_strcmp_pos(const gchar *str, const gchar *find, bool exact, boo return pos; } - bool Find::find_strcmp(const gchar *str, const gchar *find, bool exact, bool casematch) { return (std::string::npos != find_strcmp_pos(str, find, exact, casematch)); } -bool Find::item_desc_match (SPItem *item, const gchar *text, bool exact, bool casematch, bool replace) +bool Find::item_desc_match(SPItem *item, const gchar *text, bool exact, bool casematch, bool replace) { - gchar* desc = item->desc(); + gchar *desc = item->desc(); bool found = find_strcmp(desc, text, exact, casematch); if (found && replace) { - Glib::ustring r = find_replace(desc, text, entry_replace.getEntry()->get_text().c_str(), exact, casematch, replace); + Glib::ustring r = + find_replace(desc, text, entry_replace.getEntry()->get_text().c_str(), exact, casematch, replace); item->setDesc(r.c_str()); } g_free(desc); return found; } -bool Find::item_title_match (SPItem *item, const gchar *text, bool exact, bool casematch, bool replace) +bool Find::item_title_match(SPItem *item, const gchar *text, bool exact, bool casematch, bool replace) { - gchar* title = item->title(); + gchar *title = item->title(); bool found = find_strcmp(title, text, exact, casematch); if (found && replace) { - Glib::ustring r = find_replace(title, text, entry_replace.getEntry()->get_text().c_str(), exact, casematch, replace); + Glib::ustring r = + find_replace(title, text, entry_replace.getEntry()->get_text().c_str(), exact, casematch, replace); item->setTitle(r.c_str()); } g_free(title); return found; } -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() == nullptr) { return false; @@ -473,12 +477,12 @@ bool Find::item_text_match (SPItem *item, const gchar *find, bool exact, bool ca ufind = ufind.lowercase(); } - Inkscape::Text::Layout const *layout = te_get_layout (item); + Inkscape::Text::Layout const *layout = te_get_layout(item); if (!layout) { return found; } - gchar* replace_text = g_strdup(entry_replace.getEntry()->get_text().c_str()); + gchar *replace_text = g_strdup(entry_replace.getEntry()->get_text().c_str()); gsize n = find_strcmp_pos(item_text.c_str(), ufind.c_str(), exact, casematch); static Inkscape::Text::Layout::iterator _begin_w; static Inkscape::Text::Layout::iterator _end_w; @@ -486,7 +490,7 @@ bool Find::item_text_match (SPItem *item, const gchar *find, bool exact, bool ca _begin_w = layout->charIndexToIterator(n); _end_w = layout->charIndexToIterator(n + strlen(find)); sp_te_replace(item, _begin_w, _end_w, replace_text); - item_text = sp_te_get_string_multiline (item); + item_text = sp_te_get_string_multiline(item); n = find_strcmp_pos(item_text.c_str(), ufind.c_str(), exact, casematch, n + strlen(replace_text) + 1); } @@ -498,8 +502,7 @@ bool Find::item_text_match (SPItem *item, const gchar *find, bool exact, bool ca return false; } - -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() == nullptr) { return false; @@ -517,8 +520,8 @@ bool Find::item_id_match (SPItem *item, const gchar *id, bool exact, bool casema bool found = find_strcmp(item_id, id, exact, casematch); if (found && replace) { - gchar * replace_text = g_strdup(entry_replace.getEntry()->get_text().c_str()); - Glib::ustring new_item_style = find_replace(item_id, id, replace_text , exact, casematch, true); + gchar *replace_text = g_strdup(entry_replace.getEntry()->get_text().c_str()); + Glib::ustring new_item_style = find_replace(item_id, id, replace_text, exact, casematch, true); if (new_item_style != item_id) { item->setAttribute("id", new_item_style); } @@ -528,7 +531,7 @@ bool Find::item_id_match (SPItem *item, const gchar *id, bool exact, bool casema 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() == nullptr) { return false; @@ -542,8 +545,8 @@ bool Find::item_style_match (SPItem *item, const gchar *text, bool exact, bool c bool found = find_strcmp(item_style, text, exact, casematch); if (found && replace) { - gchar * replace_text = g_strdup(entry_replace.getEntry()->get_text().c_str()); - Glib::ustring new_item_style = find_replace(item_style, text, replace_text , exact, casematch, true); + gchar *replace_text = g_strdup(entry_replace.getEntry()->get_text().c_str()); + Glib::ustring new_item_style = find_replace(item_style, text, replace_text, exact, casematch, true); if (new_item_style != item_style) { item->setAttribute("style", new_item_style); } @@ -554,7 +557,7 @@ bool Find::item_style_match (SPItem *item, const gchar *text, bool exact, bool c return found; } -bool Find::item_attr_match(SPItem *item, const gchar *text, bool exact, bool /*casematch*/, bool replace/*=false*/) +bool Find::item_attr_match(SPItem *item, const gchar *text, bool exact, bool /*casematch*/, bool replace /*=false*/) { bool found = false; @@ -564,7 +567,7 @@ bool Find::item_attr_match(SPItem *item, const gchar *text, bool exact, bool /*c gchar *attr_value = g_strdup(item->getRepr()->attribute(text)); if (exact) { - found = (attr_value != nullptr); + found = (attr_value != nullptr); } else { found = item->getRepr()->matchAttributeName(text); } @@ -578,7 +581,7 @@ bool Find::item_attr_match(SPItem *item, const gchar *text, bool exact, bool /*c return found; } -bool Find::item_attrvalue_match(SPItem *item, const gchar *text, bool exact, bool casematch, bool replace/*=false*/) +bool Find::item_attrvalue_match(SPItem *item, const gchar *text, bool exact, bool casematch, bool replace /*=false*/) { bool ret = false; @@ -588,7 +591,7 @@ bool Find::item_attrvalue_match(SPItem *item, const gchar *text, bool exact, boo Inkscape::Util::List<Inkscape::XML::AttributeRecord const> iter = item->getRepr()->attributeList(); for (; iter; ++iter) { - const gchar* key = g_quark_to_string(iter->key); + const gchar *key = g_quark_to_string(iter->key); gchar *attr_value = g_strdup(item->getRepr()->attribute(key)); bool found = find_strcmp(attr_value, text, exact, casematch); if (found) { @@ -596,8 +599,8 @@ bool Find::item_attrvalue_match(SPItem *item, const gchar *text, bool exact, boo } if (found && replace) { - gchar * replace_text = g_strdup(entry_replace.getEntry()->get_text().c_str()); - Glib::ustring new_item_style = find_replace(attr_value, text, replace_text , exact, casematch, true); + gchar *replace_text = g_strdup(entry_replace.getEntry()->get_text().c_str()); + Glib::ustring new_item_style = find_replace(attr_value, text, replace_text, exact, casematch, true); if (new_item_style != attr_value) { item->setAttribute(key, new_item_style); } @@ -609,7 +612,6 @@ bool Find::item_attrvalue_match(SPItem *item, const gchar *text, bool exact, boo return ret; } - bool Find::item_font_match(SPItem *item, const gchar *text, bool exact, bool casematch, bool /*replace*/ /*=false*/) { bool ret = false; @@ -628,19 +630,21 @@ bool Find::item_font_match(SPItem *item, const gchar *text, bool exact, bool cas vFontTokenNames.emplace_back("-inkscape-font-specification:"); std::vector<Glib::ustring> vStyleTokens = Glib::Regex::split_simple(";", item_style); - for (auto & vStyleToken : vStyleTokens) { + for (auto &vStyleToken : vStyleTokens) { Glib::ustring token = vStyleToken; - for (const auto & vFontTokenName : vFontTokenNames) { - if ( token.find(vFontTokenName) != std::string::npos) { + for (const auto &vFontTokenName : vFontTokenNames) { + if (token.find(vFontTokenName) != std::string::npos) { Glib::ustring font1 = Glib::ustring(vFontTokenName).append(text); bool found = find_strcmp(token.c_str(), font1.c_str(), exact, casematch); if (found) { ret = true; if (_action_replace) { - gchar *replace_text = g_strdup(entry_replace.getEntry()->get_text().c_str()); + gchar *replace_text = g_strdup(entry_replace.getEntry()->get_text().c_str()); gchar *orig_str = g_strdup(token.c_str()); - // Exact match fails since the "font-family:" is in the token, since the find was exact it still works with false below - Glib::ustring new_item_style = find_replace(orig_str, text, replace_text , false /*exact*/, casematch, true); + // Exact match fails since the "font-family:" is in the token, since the find was exact it still + // works with false below + Glib::ustring new_item_style = + find_replace(orig_str, text, replace_text, false /*exact*/, casematch, true); if (new_item_style != orig_str) { vStyleToken = new_item_style; } @@ -654,35 +658,34 @@ bool Find::item_font_match(SPItem *item, const gchar *text, bool exact, bool cas if (ret && _action_replace) { Glib::ustring new_item_style; - for (const auto & vStyleToken : vStyleTokens) { + for (const auto &vStyleToken : vStyleTokens) { new_item_style.append(vStyleToken).append(";"); } - new_item_style.erase(new_item_style.size()-1); + new_item_style.erase(new_item_style.size() - 1); item->setAttribute("style", new_item_style); } return ret; } - -std::vector<SPItem*> Find::filter_fields (std::vector<SPItem*> &l, bool exact, bool casematch) +std::vector<SPItem *> Find::filter_fields(std::vector<SPItem *> &l, bool exact, bool casematch) { Glib::ustring tmp = entry_find.getEntry()->get_text(); if (tmp.empty()) { return l; } - gchar* text = g_strdup(tmp.c_str()); + gchar *text = g_strdup(tmp.c_str()); - std::vector<SPItem*> in = l; - std::vector<SPItem*> out; + std::vector<SPItem *> in = l; + std::vector<SPItem *> out; if (check_searchin_text.get_active()) { - for (std::vector<SPItem*>::const_reverse_iterator i=in.rbegin(); in.rend() != i; ++i) { + for (std::vector<SPItem *>::const_reverse_iterator i = in.rbegin(); in.rend() != i; ++i) { SPObject *obj = *i; SPItem *item = dynamic_cast<SPItem *>(obj); g_assert(item != nullptr); if (item_text_match(item, text, exact, casematch)) { - if (out.end()==find(out.begin(),out.end(), *i)) { + if (out.end() == find(out.begin(), out.end(), *i)) { out.push_back(*i); if (_action_replace) { item_text_match(item, text, exact, casematch, _action_replace); @@ -690,23 +693,21 @@ std::vector<SPItem*> Find::filter_fields (std::vector<SPItem*> &l, bool exact, b } } } - } - else if (check_searchin_property.get_active()) { - + } else if (check_searchin_property.get_active()) { bool ids = check_ids.get_active(); bool style = check_style.get_active(); bool font = check_font.get_active(); bool desc = check_desc.get_active(); bool title = check_title.get_active(); - bool attrname = check_attributename.get_active(); + bool attrname = check_attributename.get_active(); bool attrvalue = check_attributevalue.get_active(); if (ids) { - for (std::vector<SPItem*>::const_reverse_iterator i=in.rbegin(); in.rend() != i; ++i) { + for (std::vector<SPItem *>::const_reverse_iterator i = in.rbegin(); in.rend() != i; ++i) { SPObject *obj = *i; SPItem *item = dynamic_cast<SPItem *>(obj); if (item_id_match(item, text, exact, casematch)) { - if (out.end()==find(out.begin(),out.end(), *i)) { + if (out.end() == find(out.begin(), out.end(), *i)) { out.push_back(*i); if (_action_replace) { item_id_match(item, text, exact, casematch, _action_replace); @@ -716,31 +717,29 @@ std::vector<SPItem*> Find::filter_fields (std::vector<SPItem*> &l, bool exact, b } } - if (style) { - for (std::vector<SPItem*>::const_reverse_iterator i=in.rbegin(); in.rend() != i; ++i) { + for (std::vector<SPItem *>::const_reverse_iterator i = in.rbegin(); in.rend() != i; ++i) { SPObject *obj = *i; SPItem *item = dynamic_cast<SPItem *>(obj); g_assert(item != nullptr); if (item_style_match(item, text, exact, casematch)) { - if (out.end()==find(out.begin(),out.end(), *i)){ - out.push_back(*i); - if (_action_replace) { - item_style_match(item, text, exact, casematch, _action_replace); - } + if (out.end() == find(out.begin(), out.end(), *i)) { + out.push_back(*i); + if (_action_replace) { + item_style_match(item, text, exact, casematch, _action_replace); } + } } } } - if (attrname) { - for (std::vector<SPItem*>::const_reverse_iterator i=in.rbegin(); in.rend() != i; ++i) { + for (std::vector<SPItem *>::const_reverse_iterator i = in.rbegin(); in.rend() != i; ++i) { SPObject *obj = *i; SPItem *item = dynamic_cast<SPItem *>(obj); g_assert(item != nullptr); if (item_attr_match(item, text, exact, casematch)) { - if (out.end()==find(out.begin(),out.end(), *i)) { + if (out.end() == find(out.begin(), out.end(), *i)) { out.push_back(*i); if (_action_replace) { item_attr_match(item, text, exact, casematch, _action_replace); @@ -750,14 +749,13 @@ std::vector<SPItem*> Find::filter_fields (std::vector<SPItem*> &l, bool exact, b } } - if (attrvalue) { - for (std::vector<SPItem*>::const_reverse_iterator i=in.rbegin(); in.rend() != i; ++i) { + for (std::vector<SPItem *>::const_reverse_iterator i = in.rbegin(); in.rend() != i; ++i) { SPObject *obj = *i; SPItem *item = dynamic_cast<SPItem *>(obj); g_assert(item != nullptr); if (item_attrvalue_match(item, text, exact, casematch)) { - if (out.end()==find(out.begin(),out.end(), *i)) { + if (out.end() == find(out.begin(), out.end(), *i)) { out.push_back(*i); if (_action_replace) { item_attrvalue_match(item, text, exact, casematch, _action_replace); @@ -767,14 +765,13 @@ std::vector<SPItem*> Find::filter_fields (std::vector<SPItem*> &l, bool exact, b } } - if (font) { - for (std::vector<SPItem*>::const_reverse_iterator i=in.rbegin(); in.rend() != i; ++i) { + for (std::vector<SPItem *>::const_reverse_iterator i = in.rbegin(); in.rend() != i; ++i) { SPObject *obj = *i; SPItem *item = dynamic_cast<SPItem *>(obj); g_assert(item != nullptr); if (item_font_match(item, text, exact, casematch)) { - if (out.end()==find(out.begin(),out.end(),*i)) { + if (out.end() == find(out.begin(), out.end(), *i)) { out.push_back(*i); if (_action_replace) { item_font_match(item, text, exact, casematch, _action_replace); @@ -784,12 +781,12 @@ std::vector<SPItem*> Find::filter_fields (std::vector<SPItem*> &l, bool exact, b } } if (desc) { - for (std::vector<SPItem*>::const_reverse_iterator i=in.rbegin(); in.rend() != i; ++i) { + for (std::vector<SPItem *>::const_reverse_iterator i = in.rbegin(); in.rend() != i; ++i) { SPObject *obj = *i; SPItem *item = dynamic_cast<SPItem *>(obj); g_assert(item != nullptr); if (item_desc_match(item, text, exact, casematch)) { - if (out.end()==find(out.begin(),out.end(),*i)) { + if (out.end() == find(out.begin(), out.end(), *i)) { out.push_back(*i); if (_action_replace) { item_desc_match(item, text, exact, casematch, _action_replace); @@ -799,12 +796,12 @@ std::vector<SPItem*> Find::filter_fields (std::vector<SPItem*> &l, bool exact, b } } if (title) { - for (std::vector<SPItem*>::const_reverse_iterator i=in.rbegin(); in.rend() != i; ++i) { + for (std::vector<SPItem *>::const_reverse_iterator i = in.rbegin(); in.rend() != i; ++i) { SPObject *obj = *i; SPItem *item = dynamic_cast<SPItem *>(obj); g_assert(item != nullptr); if (item_title_match(item, text, exact, casematch)) { - if (out.end()==find(out.begin(),out.end(),*i)) { + if (out.end() == find(out.begin(), out.end(), *i)) { out.push_back(*i); if (_action_replace) { item_title_match(item, text, exact, casematch, _action_replace); @@ -813,7 +810,6 @@ std::vector<SPItem*> Find::filter_fields (std::vector<SPItem*> &l, bool exact, b } } } - } g_free(text); @@ -821,33 +817,31 @@ std::vector<SPItem*> Find::filter_fields (std::vector<SPItem*> &l, bool exact, b return out; } - -bool Find::item_type_match (SPItem *item) +bool Find::item_type_match(SPItem *item) { - bool all =check_alltypes.get_active(); + bool all = check_alltypes.get_active(); - if ( dynamic_cast<SPRect *>(item)) { - return ( all ||check_rects.get_active()); + if (dynamic_cast<SPRect *>(item)) { + return (all || check_rects.get_active()); } else if (dynamic_cast<SPGenericEllipse *>(item)) { - return ( all || check_ellipses.get_active()); + return (all || check_ellipses.get_active()); } else if (dynamic_cast<SPStar *>(item) || dynamic_cast<SPPolygon *>(item)) { - return ( all || check_stars.get_active()); + return (all || check_stars.get_active()); } else if (dynamic_cast<SPSpiral *>(item)) { - return ( all || check_spirals.get_active()); + return (all || check_spirals.get_active()); } else if (dynamic_cast<SPPath *>(item) || dynamic_cast<SPLine *>(item) || dynamic_cast<SPPolyLine *>(item)) { return (all || check_paths.get_active()); - } else if (dynamic_cast<SPText *>(item) || dynamic_cast<SPTSpan *>(item) || - dynamic_cast<SPTRef *>(item) || dynamic_cast<SPString *>(item) || - dynamic_cast<SPFlowtext *>(item) || dynamic_cast<SPFlowdiv *>(item) || - dynamic_cast<SPFlowtspan *>(item) || dynamic_cast<SPFlowpara *>(item)) { + } else if (dynamic_cast<SPText *>(item) || dynamic_cast<SPTSpan *>(item) || dynamic_cast<SPTRef *>(item) || + dynamic_cast<SPString *>(item) || dynamic_cast<SPFlowtext *>(item) || dynamic_cast<SPFlowdiv *>(item) || + dynamic_cast<SPFlowtspan *>(item) || dynamic_cast<SPFlowpara *>(item)) { return (all || check_texts.get_active()); - } else if (dynamic_cast<SPGroup *>(item) && !getDesktop()->isLayer(item) ) { // never select layers! + } else if (dynamic_cast<SPGroup *>(item) && !getDesktop()->isLayer(item)) { // never select layers! return (all || check_groups.get_active()); } else if (dynamic_cast<SPUse *>(item)) { @@ -863,29 +857,28 @@ bool Find::item_type_match (SPItem *item) return false; } -std::vector<SPItem*> Find::filter_types (std::vector<SPItem*> &l) +std::vector<SPItem *> Find::filter_types(std::vector<SPItem *> &l) { - std::vector<SPItem*> n; - for (std::vector<SPItem*>::const_reverse_iterator i=l.rbegin(); l.rend() != i; ++i) { + std::vector<SPItem *> n; + for (std::vector<SPItem *>::const_reverse_iterator i = l.rbegin(); l.rend() != i; ++i) { SPObject *obj = *i; SPItem *item = dynamic_cast<SPItem *>(obj); g_assert(item != nullptr); if (item_type_match(item)) { - n.push_back(*i); + n.push_back(*i); } } return n; } - -std::vector<SPItem*> &Find::filter_list (std::vector<SPItem*> &l, bool exact, bool casematch) +std::vector<SPItem *> &Find::filter_list(std::vector<SPItem *> &l, bool exact, bool casematch) { - l = filter_types (l); - l = filter_fields (l, exact, casematch); + l = filter_types(l); + l = filter_fields(l, exact, casematch); return l; } -std::vector<SPItem*> &Find::all_items (SPObject *r, std::vector<SPItem*> &l, bool hidden, bool locked) +std::vector<SPItem *> &Find::all_items(SPObject *r, std::vector<SPItem *> &l, bool hidden, bool locked) { if (dynamic_cast<SPDefs *>(r)) { return l; // we're not interested in items in defs @@ -897,24 +890,25 @@ std::vector<SPItem*> &Find::all_items (SPObject *r, std::vector<SPItem*> &l, boo auto desktop = getDesktop(); - for (auto& child: r->children) { + for (auto &child : r->children) { SPItem *item = dynamic_cast<SPItem *>(&child); if (item && !child.cloned && !desktop->isLayer(item)) { if ((hidden || !desktop->itemIsHidden(item)) && (locked || !item->isLocked())) { - l.insert(l.begin(),(SPItem*)&child); + l.insert(l.begin(), (SPItem *)&child); } } - l = all_items (&child, l, hidden, locked); + l = all_items(&child, l, hidden, locked); } return l; } -std::vector<SPItem*> &Find::all_selection_items (Inkscape::Selection *s, std::vector<SPItem*> &l, SPObject *ancestor, bool hidden, bool locked) +std::vector<SPItem *> &Find::all_selection_items(Inkscape::Selection *s, std::vector<SPItem *> &l, SPObject *ancestor, + bool hidden, bool locked) { auto desktop = getDesktop(); - auto itemlist= s->items(); - for (auto i=boost::rbegin(itemlist); boost::rend(itemlist) != i; ++i) { + auto itemlist = s->items(); + for (auto i = boost::rbegin(itemlist); boost::rend(itemlist) != i; ++i) { SPObject *obj = *i; SPItem *item = dynamic_cast<SPItem *>(obj); g_assert(item != nullptr); @@ -932,8 +926,6 @@ std::vector<SPItem*> &Find::all_selection_items (Inkscape::Selection *s, std::ve return l; } - - /*######################################################################## # BUTTON CLICK HANDLERS (callbacks) ########################################################################*/ @@ -970,39 +962,38 @@ void Find::onAction() bool casematch = check_case_sensitive.get_active(); blocked = true; - std::vector<SPItem*> l; + std::vector<SPItem *> l; if (check_scope_selection.get_active()) { if (check_scope_layer.get_active()) { - l = all_selection_items (desktop->selection, l, desktop->currentLayer(), hidden, locked); + l = all_selection_items(desktop->selection, l, desktop->currentLayer(), hidden, locked); } else { - l = all_selection_items (desktop->selection, l, nullptr, hidden, locked); + l = all_selection_items(desktop->selection, l, nullptr, hidden, locked); } } else { if (check_scope_layer.get_active()) { - l = all_items (desktop->currentLayer(), l, hidden, locked); + l = all_items(desktop->currentLayer(), l, hidden, locked); } else { l = all_items(desktop->getDocument()->getRoot(), l, hidden, locked); } } guint all = l.size(); - std::vector<SPItem*> n = filter_list (l, exact, casematch); + std::vector<SPItem *> n = filter_list(l, exact, casematch); if (!n.empty()) { int count = n.size(); desktop->messageStack()->flashF(Inkscape::NORMAL_MESSAGE, - // TRANSLATORS: "%s" is replaced with "exact" or "partial" when this string is displayed + // TRANSLATORS: "%s" is replaced with "exact" or "partial" when this string is + // displayed ngettext("<b>%d</b> object found (out of <b>%d</b>), %s match.", - "<b>%d</b> objects found (out of <b>%d</b>), %s match.", - count), - count, all, exact? _("exact") : _("partial")); - if (_action_replace){ + "<b>%d</b> objects found (out of <b>%d</b>), %s match.", count), + count, all, exact ? _("exact") : _("partial")); + if (_action_replace) { // TRANSLATORS: "%1" is replaced with the number of matches - status.set_text(Glib::ustring::compose(ngettext("%1 match replaced","%1 matches replaced",count), count)); - } - else { + 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(ngettext("%1 object found","%1 objects found",count), 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); } @@ -1028,10 +1019,9 @@ void Find::onAction() desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No objects found")); } blocked = false; - } -void Find::onToggleCheck () +void Find::onToggleCheck() { bool objectok = false; status.set_text(""); @@ -1039,7 +1029,7 @@ void Find::onToggleCheck () if (check_alltypes.get_active()) { objectok = true; } - for (auto & checkType : checkTypes) { + for (auto &checkType : checkTypes) { if (checkType->get_active()) { objectok = true; } @@ -1049,14 +1039,12 @@ void Find::onToggleCheck () status.set_text(_("Select an object type")); } - bool propertyok = false; if (!check_searchin_property.get_active()) { propertyok = true; } else { - - for (auto & checkProperty : checkProperties) { + for (auto &checkProperty : checkProperties) { if (checkProperty->get_active()) { propertyok = true; } @@ -1075,23 +1063,23 @@ void Find::onToggleCheck () button_replace.set_sensitive(false); } -void Find::onToggleAlltypes () +void Find::onToggleAlltypes() { - bool all =check_alltypes.get_active(); - for (auto & checkType : checkTypes) { - checkType->set_sensitive(!all); - } + bool all = check_alltypes.get_active(); + for (auto &checkType : checkTypes) { + checkType->set_sensitive(!all); + } - onToggleCheck(); + onToggleCheck(); } -void Find::onSearchinText () +void Find::onSearchinText() { searchinToggle(false); onToggleCheck(); } -void Find::onSearchinProperty () +void Find::onSearchinProperty() { searchinToggle(true); onToggleCheck(); @@ -1099,12 +1087,12 @@ void Find::onSearchinProperty () void Find::searchinToggle(bool on) { - for (auto & checkProperty : checkProperties) { + for (auto &checkProperty : checkProperties) { checkProperty->set_sensitive(on); } } -void Find::onExpander () +void Find::onExpander() { if (!expander_options.get_expanded()) squeeze_window(); @@ -1124,7 +1112,6 @@ void Find::squeeze_window() } // namespace UI } // namespace Inkscape - /* Local Variables: mode:c++ diff --git a/src/ui/dialog/find.h b/src/ui/dialog/find.h index ea6e18e1b9dd95395a86b9a0fb580cc7c4ae2851..33ef3cb9f26c75ec46f7ae76ada2f35d567835d6 100644 --- a/src/ui/dialog/find.h +++ b/src/ui/dialog/find.h @@ -13,10 +13,6 @@ #ifndef INKSCAPE_UI_DIALOG_FIND_H #define INKSCAPE_UI_DIALOG_FIND_H -#include "ui/widget/panel.h" -#include "ui/widget/entry.h" -#include "ui/widget/frame.h" - #include <gtkmm/box.h> #include <gtkmm/buttonbox.h> #include <gtkmm/expander.h> @@ -24,6 +20,9 @@ #include <gtkmm/radiobutton.h> #include <gtkmm/sizegroup.h> +#include "ui/widget/entry.h" +#include "ui/widget/frame.h" +#include "ui/widget/panel.h" class SPItem; class SPObject; @@ -44,7 +43,8 @@ namespace Dialog { * Other options allow searching on specific object types and properties. */ -class Find : public UI::Widget::Panel { +class Find : public UI::Widget::Panel +{ public: Find(); ~Find() override; @@ -56,24 +56,22 @@ public: static Find &getInstance() { return *new Find(); } protected: - - /** * Callbacks for pressing the dialog buttons. */ - void onFind(); - void onReplace(); - void onExpander(); - void onAction(); - void onToggleAlltypes(); - void onToggleCheck(); - void onSearchinText(); - void onSearchinProperty(); + void onFind(); + void onReplace(); + void onExpander(); + void onAction(); + void onToggleAlltypes(); + void onToggleCheck(); + void onSearchinText(); + void onSearchinProperty(); /** * Toggle all the properties checkboxes */ - void searchinToggle(bool on); + void searchinToggle(bool on); /** * Returns true if the SPItem 'item' has the same id @@ -85,7 +83,7 @@ protected: * @param replace replace the value if found * */ - bool item_id_match (SPItem *item, const gchar *id, bool exact, bool casematch, bool replace=false); + bool item_id_match(SPItem *item, const gchar *id, bool exact, bool casematch, bool replace = false); /** * Returns true if the SPItem 'item' has the same text content * @@ -97,7 +95,7 @@ protected: * * */ - bool item_text_match (SPItem *item, const gchar *text, bool exact, bool casematch, bool replace=false); + bool item_text_match(SPItem *item, const gchar *text, bool exact, bool casematch, bool replace = false); /** * Returns true if the SPItem 'item' has the same text in the style attribute * @@ -108,7 +106,7 @@ protected: * @param replace replace the value if found * */ - bool item_style_match (SPItem *item, const gchar *text, bool exact, bool casematch, bool replace=false); + bool item_style_match(SPItem *item, const gchar *text, bool exact, bool casematch, bool replace = false); /** * Returns true if the SPItem 'item' has a <title> or <desc> child that * matches @@ -120,8 +118,8 @@ protected: * @param replace replace the value if found * */ - bool item_desc_match (SPItem *item, const gchar *text, bool exact, bool casematch, bool replace=false); - bool item_title_match (SPItem *item, const gchar *text, bool exact, bool casematch, bool replace=false); + bool item_desc_match(SPItem *item, const gchar *text, bool exact, bool casematch, bool replace = false); + bool item_title_match(SPItem *item, const gchar *text, bool exact, bool casematch, bool replace = false); /** * Returns true if found the SPItem 'item' has the same attribute name * @@ -132,7 +130,7 @@ protected: * @param replace replace the value if found * */ - bool item_attr_match (SPItem *item, const gchar *name, bool exact, bool casematch, bool replace=false); + bool item_attr_match(SPItem *item, const gchar *name, bool exact, bool casematch, bool replace = false); /** * Returns true if the SPItem 'item' has the same attribute value * @@ -143,7 +141,7 @@ protected: * @param replace replace the value if found * */ - bool item_attrvalue_match (SPItem *item, const gchar *name, bool exact, bool casematch, bool replace=false); + bool item_attrvalue_match(SPItem *item, const gchar *name, bool exact, bool casematch, bool replace = false); /** * Returns true if the SPItem 'item' has the same font values * @@ -154,50 +152,53 @@ protected: * @param replace replace the value if found * */ - bool item_font_match (SPItem *item, const gchar *name, bool exact, bool casematch, bool replace=false); + bool item_font_match(SPItem *item, const gchar *name, bool exact, bool casematch, bool replace = false); /** * Function to filter a list of items based on the item type by calling each item_XXX_match function */ - std::vector<SPItem*> filter_fields (std::vector<SPItem*> &l, bool exact, bool casematch); - bool item_type_match (SPItem *item); - std::vector<SPItem*> filter_types (std::vector<SPItem*> &l); - std::vector<SPItem*> & filter_list (std::vector<SPItem*> &l, bool exact, bool casematch); + std::vector<SPItem *> filter_fields(std::vector<SPItem *> &l, bool exact, bool casematch); + bool item_type_match(SPItem *item); + std::vector<SPItem *> filter_types(std::vector<SPItem *> &l); + std::vector<SPItem *> &filter_list(std::vector<SPItem *> &l, bool exact, bool casematch); /** * Find a string within a string and returns true if found with options for exact and casematching */ - bool find_strcmp(const gchar *str, const gchar *find, bool exact, bool casematch); + bool find_strcmp(const gchar *str, const gchar *find, bool exact, bool casematch); /** - * Find a string within a string and return the position with options for exact, casematching and search start location + * Find a string within a string and return the position with options for exact, casematching and search start + * location */ - gsize find_strcmp_pos(const gchar *str, const gchar *find, bool exact, bool casematch, gsize start=0); + gsize find_strcmp_pos(const gchar *str, const gchar *find, bool exact, bool casematch, gsize start = 0); /** * Replace a string with another string with options for exact and casematching and replace once/all */ - Glib::ustring find_replace(const gchar *str, const gchar *find, const gchar *replace, bool exact, bool casematch, bool replaceall); + Glib::ustring find_replace(const gchar *str, const gchar *find, const gchar *replace, bool exact, bool casematch, + bool replaceall); /** * recursive function to return a list of all the items in the SPObject tree * */ - std::vector<SPItem*> & all_items (SPObject *r, std::vector<SPItem*> &l, bool hidden, bool locked); + std::vector<SPItem *> &all_items(SPObject *r, std::vector<SPItem *> &l, bool hidden, bool locked); /** * to return a list of all the selected items * */ - std::vector<SPItem*> & all_selection_items (Inkscape::Selection *s, std::vector<SPItem*> &l, SPObject *ancestor, bool hidden, bool locked); + std::vector<SPItem *> &all_selection_items(Inkscape::Selection *s, std::vector<SPItem *> &l, SPObject *ancestor, + bool hidden, bool locked); /** * Shrink the dialog size when the expander widget is closed * Currently not working, no known way to do this */ - void squeeze_window(); + void squeeze_window(); /** * Can be invoked for setting the desktop. Currently not used. */ - void setDesktop(SPDesktop *desktop) override; + void setDesktop(SPDesktop *desktop) override; /** * Called when desktop selection changes @@ -206,22 +207,22 @@ protected: private: Find(Find const &d) = delete; - Find& operator=(Find const &d) = delete; + Find &operator=(Find const &d) = delete; /* * Find and replace combo box widgets */ - UI::Widget::Entry entry_find; - UI::Widget::Entry entry_replace; + UI::Widget::Entry entry_find; + UI::Widget::Entry entry_replace; /** * Scope and search in widgets */ - Gtk::RadioButton check_scope_all; - Gtk::RadioButton check_scope_layer; - Gtk::RadioButton check_scope_selection; - Gtk::RadioButton check_searchin_text; - Gtk::RadioButton check_searchin_property; + Gtk::RadioButton check_scope_all; + Gtk::RadioButton check_scope_layer; + Gtk::RadioButton check_scope_selection; + Gtk::RadioButton check_searchin_text; + Gtk::RadioButton check_searchin_property; Gtk::HBox hbox_searchin; Gtk::VBox vbox_scope; Gtk::VBox vbox_searchin; @@ -231,27 +232,27 @@ private: /** * General option widgets */ - Gtk::CheckButton check_case_sensitive; - Gtk::CheckButton check_exact_match; - Gtk::CheckButton check_include_hidden; - Gtk::CheckButton check_include_locked; + Gtk::CheckButton check_case_sensitive; + Gtk::CheckButton check_exact_match; + Gtk::CheckButton check_include_hidden; + Gtk::CheckButton check_include_locked; Gtk::VBox vbox_options1; Gtk::VBox vbox_options2; Gtk::HBox hbox_options; Gtk::VBox vbox_expander; - Gtk::Expander expander_options; + Gtk::Expander expander_options; UI::Widget::Frame frame_options; /** * Property type widgets */ - Gtk::CheckButton check_ids; - Gtk::CheckButton check_attributename; - Gtk::CheckButton check_attributevalue; - Gtk::CheckButton check_style; - Gtk::CheckButton check_font; - Gtk::CheckButton check_desc; - Gtk::CheckButton check_title; + Gtk::CheckButton check_ids; + Gtk::CheckButton check_attributename; + Gtk::CheckButton check_attributevalue; + Gtk::CheckButton check_style; + Gtk::CheckButton check_font; + Gtk::CheckButton check_desc; + Gtk::CheckButton check_title; Gtk::HBox hbox_properties; Gtk::VBox vbox_properties1; Gtk::VBox vbox_properties2; @@ -265,17 +266,17 @@ private: /** * Object type widgets */ - Gtk::CheckButton check_alltypes; - Gtk::CheckButton check_rects; - Gtk::CheckButton check_ellipses; - Gtk::CheckButton check_stars; - Gtk::CheckButton check_spirals; - Gtk::CheckButton check_paths; - Gtk::CheckButton check_texts; - Gtk::CheckButton check_groups; - Gtk::CheckButton check_clones; - Gtk::CheckButton check_images; - Gtk::CheckButton check_offsets; + Gtk::CheckButton check_alltypes; + Gtk::CheckButton check_rects; + Gtk::CheckButton check_ellipses; + Gtk::CheckButton check_stars; + Gtk::CheckButton check_spirals; + Gtk::CheckButton check_paths; + Gtk::CheckButton check_texts; + Gtk::CheckButton check_groups; + Gtk::CheckButton check_clones; + Gtk::CheckButton check_images; + Gtk::CheckButton check_offsets; Gtk::VBox vbox_types1; Gtk::VBox vbox_types2; Gtk::HBox hbox_types; @@ -289,7 +290,7 @@ private: */ std::vector<Gtk::CheckButton *> checkTypes; - //Gtk::HBox hbox_text; + // Gtk::HBox hbox_text; /** * Action Buttons and status diff --git a/src/ui/dialog/floating-behavior.cpp b/src/ui/dialog/floating-behavior.cpp index f9c0e56529f4c0d907fe68555c68298b1bbc627f..6c73fd0164980f7d8b83ecc43c09e6263208d003 100644 --- a/src/ui/dialog/floating-behavior.cpp +++ b/src/ui/dialog/floating-behavior.cpp @@ -11,14 +11,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm/dialog.h> +#include "floating-behavior.h" + #include <glibmm/main.h> +#include <gtkmm/dialog.h> -#include "floating-behavior.h" +#include "desktop.h" #include "dialog.h" - #include "inkscape.h" -#include "desktop.h" #include "ui/dialog-events.h" #include "verbs.h" @@ -27,13 +27,13 @@ namespace UI { namespace Dialog { namespace Behavior { -FloatingBehavior::FloatingBehavior(Dialog &dialog) : - Behavior(dialog), - _d (new Gtk::Dialog(_dialog._title)) - ,_dialog_active(_d->property_is_active()) - ,_trans_focus(Inkscape::Preferences::get()->getDoubleLimited("/dialogs/transparency/on-focus", 0.95, 0.0, 1.0)) - ,_trans_blur(Inkscape::Preferences::get()->getDoubleLimited("/dialogs/transparency/on-blur", 0.50, 0.0, 1.0)) - ,_trans_time(Inkscape::Preferences::get()->getIntLimited("/dialogs/transparency/animate-time", 100, 0, 5000)) +FloatingBehavior::FloatingBehavior(Dialog &dialog) + : Behavior(dialog) + , _d(new Gtk::Dialog(_dialog._title)) + , _dialog_active(_d->property_is_active()) + , _trans_focus(Inkscape::Preferences::get()->getDoubleLimited("/dialogs/transparency/on-focus", 0.95, 0.0, 1.0)) + , _trans_blur(Inkscape::Preferences::get()->getDoubleLimited("/dialogs/transparency/on-blur", 0.50, 0.0, 1.0)) + , _trans_time(Inkscape::Preferences::get()->getIntLimited("/dialogs/transparency/animate-time", 100, 0, 5000)) { hide(); @@ -48,61 +48,108 @@ FloatingBehavior::~FloatingBehavior() _d = nullptr; } -Behavior * -FloatingBehavior::create(Dialog &dialog) +Behavior *FloatingBehavior::create(Dialog &dialog) { return new FloatingBehavior(dialog); } -inline FloatingBehavior::operator Gtk::Widget &() { return *_d; } -inline GtkWidget *FloatingBehavior::gobj() { return GTK_WIDGET(_d->gobj()); } -inline Gtk::Box* FloatingBehavior::get_vbox() { +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_content_area(); } -inline void FloatingBehavior::present() { _d->present(); } -inline void FloatingBehavior::hide() { _d->hide(); } -inline void FloatingBehavior::show() { _d->show(); } -inline void FloatingBehavior::show_all_children() { _d->show_all_children(); } -inline void FloatingBehavior::resize(int width, int height) { _d->resize(width, height); } -inline void FloatingBehavior::move(int x, int y) { _d->move(x, y); } -inline void FloatingBehavior::set_position(Gtk::WindowPosition position) { _d->set_position(position); } -inline void FloatingBehavior::set_size_request(int width, int height) { _d->set_size_request(width, height); } -inline void FloatingBehavior::size_request(Gtk::Requisition &requisition) { - Gtk::Requisition requisition_natural; - _d->get_preferred_size(requisition, requisition_natural); +inline void FloatingBehavior::present() +{ + _d->present(); +} +inline void FloatingBehavior::hide() +{ + _d->hide(); +} +inline void FloatingBehavior::show() +{ + _d->show(); +} +inline void FloatingBehavior::show_all_children() +{ + _d->show_all_children(); +} +inline void FloatingBehavior::resize(int width, int height) +{ + _d->resize(width, height); +} +inline void FloatingBehavior::move(int x, int y) +{ + _d->move(x, y); +} +inline void FloatingBehavior::set_position(Gtk::WindowPosition position) +{ + _d->set_position(position); +} +inline void FloatingBehavior::set_size_request(int width, int height) +{ + _d->set_size_request(width, height); +} +inline void FloatingBehavior::size_request(Gtk::Requisition &requisition) +{ + Gtk::Requisition requisition_natural; + _d->get_preferred_size(requisition, requisition_natural); +} +inline void FloatingBehavior::get_position(int &x, int &y) +{ + _d->get_position(x, y); +} +inline void FloatingBehavior::get_size(int &width, int &height) +{ + _d->get_size(width, height); +} +inline void FloatingBehavior::set_title(Glib::ustring title) +{ + _d->set_title(title); +} +inline void FloatingBehavior::set_sensitive(bool sensitive) +{ + _d->set_sensitive(sensitive); } -inline void FloatingBehavior::get_position(int &x, int &y) { _d->get_position(x, y); } -inline void FloatingBehavior::get_size(int &width, int &height) { _d->get_size(width, height); } -inline void FloatingBehavior::set_title(Glib::ustring title) { _d->set_title(title); } -inline void FloatingBehavior::set_sensitive(bool sensitive) { _d->set_sensitive(sensitive); } - -Glib::SignalProxy0<void> FloatingBehavior::signal_show() { return _d->signal_show(); } -Glib::SignalProxy0<void> FloatingBehavior::signal_hide() { return _d->signal_hide(); } -Glib::SignalProxy1<bool, GdkEventAny *> FloatingBehavior::signal_delete_event () { return _d->signal_delete_event(); } +Glib::SignalProxy0<void> FloatingBehavior::signal_show() +{ + return _d->signal_show(); +} +Glib::SignalProxy0<void> FloatingBehavior::signal_hide() +{ + return _d->signal_hide(); +} +Glib::SignalProxy1<bool, GdkEventAny *> FloatingBehavior::signal_delete_event() +{ + return _d->signal_delete_event(); +} -void -FloatingBehavior::onHideF12() +void FloatingBehavior::onHideF12() { _dialog.save_geometry(); hide(); } -void -FloatingBehavior::onShowF12() +void FloatingBehavior::onShowF12() { show(); _dialog.read_geometry(); } -void -FloatingBehavior::onShutdown() +void FloatingBehavior::onShutdown() { _dialog.save_status(!_dialog._user_hidden, 1, GDL_DOCK_TOP); // Make sure 1 == DockItem::FLOATING_STATE } -void -FloatingBehavior::onDesktopActivated (SPDesktop *desktop) +void FloatingBehavior::onDesktopActivated(SPDesktop *desktop) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gint transient_policy = prefs->getIntLimited("/options/transientpolicy/value", 1, 0, 2); @@ -116,9 +163,8 @@ FloatingBehavior::onDesktopActivated (SPDesktop *desktop) GtkWindow *dialog_win = GTK_WINDOW(_d->gobj()); - if (dialog_win && _dialog.retransientize_suppress()) - { - desktop->setWindowTransient (dialog_win); + if (dialog_win && _dialog.retransientize_suppress()) { + desktop->setWindowTransient(dialog_win); /* * This enables "aggressive" transientization, @@ -127,18 +173,16 @@ FloatingBehavior::onDesktopActivated (SPDesktop *desktop) * manager because the switched-to document will be raised at once * (so that its transients also could raise) */ - if (transient_policy == 2 && ! _dialog._hiddenF12 && !_dialog._user_hidden) { + if (transient_policy == 2 && !_dialog._hiddenF12 && !_dialog._user_hidden) { // without this, a transient window not always emerges on top - gtk_window_present (dialog_win); + gtk_window_present(dialog_win); } // we're done, allow next retransientizing not sooner than after 120 msec _dialog.retransientize_again_timeout_add(); } - } - } // namespace Behavior } // namespace Dialog } // namespace UI diff --git a/src/ui/dialog/floating-behavior.h b/src/ui/dialog/floating-behavior.h index d4e9ebecb08e03e287fff91fdf3f91a17f675241..0f833e4e8b81915feae92558c3319efc85276162 100644 --- a/src/ui/dialog/floating-behavior.h +++ b/src/ui/dialog/floating-behavior.h @@ -10,11 +10,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #ifndef INKSCAPE_UI_DIALOG_FLOATING_BEHAVIOR_H #define INKSCAPE_UI_DIALOG_FLOATING_BEHAVIOR_H #include <glibmm/property.h> + #include "behavior.h" namespace Gtk { @@ -26,8 +26,8 @@ namespace UI { namespace Dialog { namespace Behavior { -class FloatingBehavior : public Behavior { - +class FloatingBehavior : public Behavior +{ public: static Behavior *create(Dialog &dialog); @@ -47,7 +47,7 @@ public: void set_size_request(int width, int height) override; void size_request(Gtk::Requisition &requisition) override; void get_position(int &x, int &y) override; - void get_size(int& width, int &height) override; + void get_size(int &width, int &height) override; void set_title(Glib::ustring title) override; void set_sensitive(bool sensitive) override; @@ -63,14 +63,15 @@ public: void onShutdown() override; private: - FloatingBehavior(Dialog& dialog); + FloatingBehavior(Dialog &dialog); - Gtk::Dialog *_d; //< the actual dialog + Gtk::Dialog *_d; //< the actual dialog - Glib::PropertyProxy_ReadOnly<bool> _dialog_active; //< Variable proxy to track whether the dialog is the active window - float _trans_focus; //< The percentage opacity when the dialog is focused - float _trans_blur; //< The percentage opactiy when the dialog is not focused - int _trans_time; //< The amount of time (in ms) for the dialog to change it's transparency + Glib::PropertyProxy_ReadOnly<bool> _dialog_active; //< Variable proxy to track whether the dialog is the active + // window + float _trans_focus; //< The percentage opacity when the dialog is focused + float _trans_blur; //< The percentage opactiy when the dialog is not focused + int _trans_time; //< The amount of time (in ms) for the dialog to change it's transparency }; } // namespace Behavior diff --git a/src/ui/dialog/font-substitution.cpp b/src/ui/dialog/font-substitution.cpp index bf912595ea05412f505297c9d7e961bb2e401b35..925e695df827f76b155985e43675905b55ddff7f 100644 --- a/src/ui/dialog/font-substitution.cpp +++ b/src/ui/dialog/font-substitution.cpp @@ -7,114 +7,103 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <set> +#include "font-substitution.h" #include <glibmm/i18n.h> #include <glibmm/regex.h> - -#include <gtkmm/messagedialog.h> #include <gtkmm/checkbutton.h> +#include <gtkmm/messagedialog.h> #include <gtkmm/scrolledwindow.h> #include <gtkmm/textview.h> - -#include "font-substitution.h" +#include <set> #include "desktop.h" #include "document.h" #include "inkscape.h" -#include "selection-chemistry.h" -#include "text-editing.h" - +#include "libnrtype/FontFactory.h" +#include "libnrtype/font-instance.h" +#include "object/sp-flowdiv.h" +#include "object/sp-flowtext.h" #include "object/sp-root.h" #include "object/sp-text.h" #include "object/sp-textpath.h" -#include "object/sp-flowtext.h" -#include "object/sp-flowdiv.h" #include "object/sp-tspan.h" - -#include "libnrtype/FontFactory.h" -#include "libnrtype/font-instance.h" - +#include "selection-chemistry.h" +#include "text-editing.h" #include "ui/dialog-events.h" namespace Inkscape { namespace UI { namespace Dialog { -FontSubstitution::FontSubstitution() -= default; +FontSubstitution::FontSubstitution() = default; -FontSubstitution::~FontSubstitution() -= default; +FontSubstitution::~FontSubstitution() = default; -void -FontSubstitution::checkFontSubstitutions(SPDocument* doc) +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; - std::vector<SPItem*> l = getFontReplacedItems(doc, &out); + std::vector<SPItem *> l = getFontReplacedItems(doc, &out); if (out.length() > 0) { show(out, l); } } } -void -FontSubstitution::show(Glib::ustring out, std::vector<SPItem*> &l) +void FontSubstitution::show(Glib::ustring out, std::vector<SPItem *> &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(); - - auto box = warning.get_content_area(); - 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 = desktop->getSelection(); - selection->clear(); - selection->setList(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(); + + auto box = warning.get_content_area(); + 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 = desktop->getSelection(); + selection->clear(); + selection->setList(l); + } } /* @@ -128,47 +117,45 @@ FontSubstitution::show(Glib::ustring out, std::vector<SPItem*> &l) * 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. */ -std::vector<SPItem*> FontSubstitution::getFontReplacedItems(SPDocument* doc, Glib::ustring *out) +std::vector<SPItem *> FontSubstitution::getFontReplacedItems(SPDocument *doc, Glib::ustring *out) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - std::vector<SPItem*> allList; - std::vector<SPItem*> outList,x,y; + std::vector<SPItem *> allList; + std::vector<SPItem *> outList, x, y; std::set<Glib::ustring> setErrors; std::set<Glib::ustring> setFontSpans; std::map<SPItem *, Glib::ustring> mapFontStyles; allList = get_all_items(x, doc->getRoot(), desktop, false, false, true, y); - for(auto item : allList){ + for (auto item : allList) { SPStyle *style = item->style; Glib::ustring family = ""; - if (is_top_level_text_object (item)) { + 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)) { + } else if (SP_IS_TEXTPATH(item)) { SPTextPath const *textpath = SP_TEXTPATH(item); if (textpath->originalPath != nullptr) { family = SP_TEXT(item->parent)->layout.getFontFamily(0); setFontSpans.insert(family); } - } - else if (SP_IS_TSPAN(item) || SP_IS_FLOWTSPAN(item)) { + } 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 != nullptr) { - family = SP_TEXT(parent_text)->layout.getFontFamily(0); - // Add all the spans fonts to the set - for (unsigned int f=0; f < parent_text->children.size(); f++) { - family = SP_TEXT(parent_text)->layout.getFontFamily(f); - setFontSpans.insert(family); - } - } + // 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 != nullptr) { + family = SP_TEXT(parent_text)->layout.getFontFamily(0); + // Add all the spans fonts to the set + for (unsigned int f = 0; f < parent_text->children.size(); f++) { + family = SP_TEXT(parent_text)->layout.getFontFamily(f); + setFontSpans.insert(family); + } + } } if (style) { @@ -182,7 +169,7 @@ std::vector<SPItem*> FontSubstitution::getFontReplacedItems(SPDocument* doc, Gli if (style_font) { if (has_visible_text(item)) { - mapFontStyles.insert(std::make_pair (item, style_font)); + mapFontStyles.insert(std::make_pair(item, style_font)); } } } @@ -195,32 +182,28 @@ std::vector<SPItem*> FontSubstitution::getFontReplacedItems(SPDocument* doc, Gli 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); + std::vector<Glib::ustring> vFonts = Glib::Regex::split_simple(",", fonts); bool fontFound = false; - for(auto font : vFonts) { + for (auto font : vFonts) { // 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)) { + if ((std::string::npos == startpos) || (std::string::npos == endpos)) { continue; // empty font name } - font = font.substr( startpos, endpos-startpos+1 ); + 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")) { + 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()); + Glib::ustring err = + Glib::ustring::compose(_("Font '%1' substituted with '%2'"), fonts.c_str(), subName.c_str()); setErrors.insert(err); outList.push_back(item); } @@ -236,13 +219,12 @@ std::vector<SPItem*> FontSubstitution::getFontReplacedItems(SPDocument* doc, Gli return outList; } - -Glib::ustring FontSubstitution::getSubstituteFontName (Glib::ustring font) +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()); + 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); @@ -253,12 +235,10 @@ Glib::ustring FontSubstitution::getSubstituteFontName (Glib::ustring font) return out; } - } // namespace Dialog } // namespace UI } // namespace Inkscape - /* Local Variables: mode:c++ diff --git a/src/ui/dialog/font-substitution.h b/src/ui/dialog/font-substitution.h index 6ab01d3a34c5fde710677f1bdb7c75a600490231..b0227865dd6f0c65e6166c77890447be85d9b5fd 100644 --- a/src/ui/dialog/font-substitution.h +++ b/src/ui/dialog/font-substitution.h @@ -23,22 +23,23 @@ namespace Inkscape { namespace UI { namespace Dialog { -class FontSubstitution { +class FontSubstitution +{ public: FontSubstitution(); virtual ~FontSubstitution(); - void checkFontSubstitutions(SPDocument* doc); - void show(Glib::ustring out, std::vector<SPItem*> &l); + void checkFontSubstitutions(SPDocument *doc); + void show(Glib::ustring out, std::vector<SPItem *> &l); static FontSubstitution &getInstance() { return *new FontSubstitution(); } - Glib::ustring getSubstituteFontName (Glib::ustring font); + Glib::ustring getSubstituteFontName(Glib::ustring font); protected: - std::vector<SPItem*> getFontReplacedItems(SPDocument* doc, Glib::ustring *out); + std::vector<SPItem *> getFontReplacedItems(SPDocument *doc, Glib::ustring *out); private: FontSubstitution(FontSubstitution const &d) = delete; - FontSubstitution& operator=(FontSubstitution const &d) = delete; + FontSubstitution &operator=(FontSubstitution const &d) = delete; }; } // namespace Dialog diff --git a/src/ui/dialog/glyphs.cpp b/src/ui/dialog/glyphs.cpp index 29e5088e94a54441910543b8654348e1ddce672e..bb0c39a3d3d9bb8b71dda31b8db6fc0725b6ac27 100644 --- a/src/ui/dialog/glyphs.cpp +++ b/src/ui/dialog/glyphs.cpp @@ -8,8 +8,6 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <vector> - #include "glyphs.h" #include <glibmm/i18n.h> @@ -19,195 +17,191 @@ #include <gtkmm/iconview.h> #include <gtkmm/liststore.h> #include <gtkmm/scrolledwindow.h> +#include <vector> #include "desktop.h" #include "document-undo.h" #include "document.h" // for SPDocumentUndo::done() -#include "selection.h" -#include "text-editing.h" -#include "verbs.h" - #include "libnrtype/font-instance.h" #include "libnrtype/font-lister.h" - #include "object/sp-flowtext.h" #include "object/sp-text.h" - +#include "selection.h" +#include "text-editing.h" #include "ui/widget/font-selector.h" +#include "verbs.h" namespace Inkscape { namespace UI { namespace Dialog { - GlyphsPanel &GlyphsPanel::getInstance() { return *new GlyphsPanel(); } - -static std::map<GUnicodeScript, Glib::ustring> & getScriptToName() +static std::map<GUnicodeScript, Glib::ustring> &getScriptToName() { static bool init = false; static std::map<GUnicodeScript, Glib::ustring> mappings; if (!init) { init = true; - mappings[G_UNICODE_SCRIPT_INVALID_CODE] = _("all"); - mappings[G_UNICODE_SCRIPT_COMMON] = _("common"); - mappings[G_UNICODE_SCRIPT_INHERITED] = _("inherited"); - mappings[G_UNICODE_SCRIPT_ARABIC] = _("Arabic"); - mappings[G_UNICODE_SCRIPT_ARMENIAN] = _("Armenian"); - mappings[G_UNICODE_SCRIPT_BENGALI] = _("Bengali"); - mappings[G_UNICODE_SCRIPT_BOPOMOFO] = _("Bopomofo"); - mappings[G_UNICODE_SCRIPT_CHEROKEE] = _("Cherokee"); - mappings[G_UNICODE_SCRIPT_COPTIC] = _("Coptic"); - mappings[G_UNICODE_SCRIPT_CYRILLIC] = _("Cyrillic"); - mappings[G_UNICODE_SCRIPT_DESERET] = _("Deseret"); - mappings[G_UNICODE_SCRIPT_DEVANAGARI] = _("Devanagari"); - mappings[G_UNICODE_SCRIPT_ETHIOPIC] = _("Ethiopic"); - mappings[G_UNICODE_SCRIPT_GEORGIAN] = _("Georgian"); - mappings[G_UNICODE_SCRIPT_GOTHIC] = _("Gothic"); - mappings[G_UNICODE_SCRIPT_GREEK] = _("Greek"); - mappings[G_UNICODE_SCRIPT_GUJARATI] = _("Gujarati"); - mappings[G_UNICODE_SCRIPT_GURMUKHI] = _("Gurmukhi"); - mappings[G_UNICODE_SCRIPT_HAN] = _("Han"); - mappings[G_UNICODE_SCRIPT_HANGUL] = _("Hangul"); - mappings[G_UNICODE_SCRIPT_HEBREW] = _("Hebrew"); - mappings[G_UNICODE_SCRIPT_HIRAGANA] = _("Hiragana"); - mappings[G_UNICODE_SCRIPT_KANNADA] = _("Kannada"); - mappings[G_UNICODE_SCRIPT_KATAKANA] = _("Katakana"); - mappings[G_UNICODE_SCRIPT_KHMER] = _("Khmer"); - mappings[G_UNICODE_SCRIPT_LAO] = _("Lao"); - mappings[G_UNICODE_SCRIPT_LATIN] = _("Latin"); - mappings[G_UNICODE_SCRIPT_MALAYALAM] = _("Malayalam"); - mappings[G_UNICODE_SCRIPT_MONGOLIAN] = _("Mongolian"); - mappings[G_UNICODE_SCRIPT_MYANMAR] = _("Myanmar"); - mappings[G_UNICODE_SCRIPT_OGHAM] = _("Ogham"); - mappings[G_UNICODE_SCRIPT_OLD_ITALIC] = _("Old Italic"); - mappings[G_UNICODE_SCRIPT_ORIYA] = _("Oriya"); - mappings[G_UNICODE_SCRIPT_RUNIC] = _("Runic"); - mappings[G_UNICODE_SCRIPT_SINHALA] = _("Sinhala"); - mappings[G_UNICODE_SCRIPT_SYRIAC] = _("Syriac"); - mappings[G_UNICODE_SCRIPT_TAMIL] = _("Tamil"); - mappings[G_UNICODE_SCRIPT_TELUGU] = _("Telugu"); - mappings[G_UNICODE_SCRIPT_THAANA] = _("Thaana"); - mappings[G_UNICODE_SCRIPT_THAI] = _("Thai"); - mappings[G_UNICODE_SCRIPT_TIBETAN] = _("Tibetan"); - mappings[G_UNICODE_SCRIPT_CANADIAN_ABORIGINAL] = _("Canadian Aboriginal"); - mappings[G_UNICODE_SCRIPT_YI] = _("Yi"); - mappings[G_UNICODE_SCRIPT_TAGALOG] = _("Tagalog"); - mappings[G_UNICODE_SCRIPT_HANUNOO] = _("Hanunoo"); - mappings[G_UNICODE_SCRIPT_BUHID] = _("Buhid"); - mappings[G_UNICODE_SCRIPT_TAGBANWA] = _("Tagbanwa"); - mappings[G_UNICODE_SCRIPT_BRAILLE] = _("Braille"); - mappings[G_UNICODE_SCRIPT_CYPRIOT] = _("Cypriot"); - mappings[G_UNICODE_SCRIPT_LIMBU] = _("Limbu"); - mappings[G_UNICODE_SCRIPT_OSMANYA] = _("Osmanya"); - mappings[G_UNICODE_SCRIPT_SHAVIAN] = _("Shavian"); - mappings[G_UNICODE_SCRIPT_LINEAR_B] = _("Linear B"); - mappings[G_UNICODE_SCRIPT_TAI_LE] = _("Tai Le"); - mappings[G_UNICODE_SCRIPT_UGARITIC] = _("Ugaritic"); - mappings[G_UNICODE_SCRIPT_NEW_TAI_LUE] = _("New Tai Lue"); - mappings[G_UNICODE_SCRIPT_BUGINESE] = _("Buginese"); - mappings[G_UNICODE_SCRIPT_GLAGOLITIC] = _("Glagolitic"); - mappings[G_UNICODE_SCRIPT_TIFINAGH] = _("Tifinagh"); - mappings[G_UNICODE_SCRIPT_SYLOTI_NAGRI] = _("Syloti Nagri"); - mappings[G_UNICODE_SCRIPT_OLD_PERSIAN] = _("Old Persian"); - mappings[G_UNICODE_SCRIPT_KHAROSHTHI] = _("Kharoshthi"); - mappings[G_UNICODE_SCRIPT_UNKNOWN] = _("unassigned"); - mappings[G_UNICODE_SCRIPT_BALINESE] = _("Balinese"); - mappings[G_UNICODE_SCRIPT_CUNEIFORM] = _("Cuneiform"); - mappings[G_UNICODE_SCRIPT_PHOENICIAN] = _("Phoenician"); - mappings[G_UNICODE_SCRIPT_PHAGS_PA] = _("Phags-pa"); - mappings[G_UNICODE_SCRIPT_NKO] = _("N'Ko"); - mappings[G_UNICODE_SCRIPT_KAYAH_LI] = _("Kayah Li"); - mappings[G_UNICODE_SCRIPT_LEPCHA] = _("Lepcha"); - mappings[G_UNICODE_SCRIPT_REJANG] = _("Rejang"); - mappings[G_UNICODE_SCRIPT_SUNDANESE] = _("Sundanese"); - mappings[G_UNICODE_SCRIPT_SAURASHTRA] = _("Saurashtra"); - mappings[G_UNICODE_SCRIPT_CHAM] = _("Cham"); - mappings[G_UNICODE_SCRIPT_OL_CHIKI] = _("Ol Chiki"); - mappings[G_UNICODE_SCRIPT_VAI] = _("Vai"); - mappings[G_UNICODE_SCRIPT_CARIAN] = _("Carian"); - mappings[G_UNICODE_SCRIPT_LYCIAN] = _("Lycian"); - mappings[G_UNICODE_SCRIPT_LYDIAN] = _("Lydian"); - mappings[G_UNICODE_SCRIPT_AVESTAN] = _("Avestan"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_BAMUM] = _("Bamum"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_EGYPTIAN_HIEROGLYPHS] = _("Egyptian Hieroglpyhs"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_IMPERIAL_ARAMAIC] = _("Imperial Aramaic"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_INSCRIPTIONAL_PAHLAVI]= _("Inscriptional Pahlavi"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_INSCRIPTIONAL_PARTHIAN]= _("Inscriptional Parthian"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_JAVANESE] = _("Javanese"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_KAITHI] = _("Kaithi"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_LISU] = _("Lisu"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_MEETEI_MAYEK] = _("Meetei Mayek"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_OLD_SOUTH_ARABIAN] = _("Old South Arabian"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_OLD_TURKIC] = _("Old Turkic"); // Since: 2.28 - mappings[G_UNICODE_SCRIPT_SAMARITAN] = _("Samaritan"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_TAI_THAM] = _("Tai Tham"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_TAI_VIET] = _("Tai Viet"); // Since: 2.26 - mappings[G_UNICODE_SCRIPT_BATAK] = _("Batak"); // Since: 2.28 - mappings[G_UNICODE_SCRIPT_BRAHMI] = _("Brahmi"); // Since: 2.28 - mappings[G_UNICODE_SCRIPT_MANDAIC] = _("Mandaic"); // Since: 2.28 - mappings[G_UNICODE_SCRIPT_CHAKMA] = _("Chakma"); // Since: 2.32 - mappings[G_UNICODE_SCRIPT_MEROITIC_CURSIVE] = _("Meroitic Cursive"); // Since: 2.32 - mappings[G_UNICODE_SCRIPT_MEROITIC_HIEROGLYPHS] = _("Meroitic Hieroglyphs"); // Since: 2.32 - mappings[G_UNICODE_SCRIPT_MIAO] = _("Miao"); // Since: 2.32 - mappings[G_UNICODE_SCRIPT_SHARADA] = _("Sharada"); // Since: 2.32 - mappings[G_UNICODE_SCRIPT_SORA_SOMPENG] = _("Sora Sompeng"); // Since: 2.32 - mappings[G_UNICODE_SCRIPT_TAKRI] = _("Takri"); // Since: 2.32 - mappings[G_UNICODE_SCRIPT_BASSA_VAH] = _("Bassa"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_CAUCASIAN_ALBANIAN] = _("Caucasian Albanian"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_DUPLOYAN] = _("Duployan"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_ELBASAN] = _("Elbasan"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_GRANTHA] = _("Grantha"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_KHOJKI] = _("Khojki"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_KHUDAWADI] = _("Khudawadi, Sindhi"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_LINEAR_A] = _("Linear A"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_MAHAJANI] = _("Mahajani"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_MANICHAEAN] = _("Manichaean"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_MENDE_KIKAKUI] = _("Mende Kikakui"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_MODI] = _("Modi"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_MRO] = _("Mro"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_NABATAEAN] = _("Nabataean"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_OLD_NORTH_ARABIAN] = _("Old North Arabian"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_OLD_PERMIC] = _("Old Permic"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_PAHAWH_HMONG] = _("Pahawh Hmong"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_PALMYRENE] = _("Palmyrene"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_PAU_CIN_HAU] = _("Pau Cin Hau"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_PSALTER_PAHLAVI] = _("Psalter Pahlavi"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_SIDDHAM] = _("Siddham"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_TIRHUTA] = _("Tirhuta"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_WARANG_CITI] = _("Warang Citi"); // Since: 2.42 - mappings[G_UNICODE_SCRIPT_AHOM] = _("Ahom"); // Since: 2.48 - mappings[G_UNICODE_SCRIPT_ANATOLIAN_HIEROGLYPHS]= _("Anatolian Hieroglyphs"); // Since: 2.48 - mappings[G_UNICODE_SCRIPT_HATRAN] = _("Hatran"); // Since: 2.48 - mappings[G_UNICODE_SCRIPT_MULTANI] = _("Multani"); // Since: 2.48 - mappings[G_UNICODE_SCRIPT_OLD_HUNGARIAN] = _("Old Hungarian"); // Since: 2.48 - mappings[G_UNICODE_SCRIPT_SIGNWRITING] = _("Signwriting"); // Since: 2.48 -/* - mappings[G_UNICODE_SCRIPT_ADLAM] = _("Adlam"); // Since: 2.50 - mappings[G_UNICODE_SCRIPT_BHAIKSUKI] = _("Bhaiksuki"); // Since: 2.50 - mappings[G_UNICODE_SCRIPT_MARCHEN] = _("Marchen"); // Since: 2.50 - mappings[G_UNICODE_SCRIPT_NEWA] = _("Newa"); // Since: 2.50 - mappings[G_UNICODE_SCRIPT_OSAGE] = _("Osage"); // Since: 2.50 - mappings[G_UNICODE_SCRIPT_TANGUT] = _("Tangut"); // Since: 2.50 - mappings[G_UNICODE_SCRIPT_MASARAM_GONDI] = _("Masaram Gondi"); // Since: 2.54 - mappings[G_UNICODE_SCRIPT_NUSHU] = _("Nushu"); // Since: 2.54 - mappings[G_UNICODE_SCRIPT_SOYOMBO] = _("Soyombo"); // Since: 2.54 - mappings[G_UNICODE_SCRIPT_ZANABAZAR_SQUARE] = _("Zanabazar Square"); // Since: 2.54 - mappings[G_UNICODE_SCRIPT_DOGRA] = _("Dogra"); // Since: 2.58 - mappings[G_UNICODE_SCRIPT_GUNJALA_GONDI] = _("Gunjala Gondi"); // Since: 2.58 - mappings[G_UNICODE_SCRIPT_HANIFI_ROHINGYA] = _("Hanifi Rohingya"); // Since: 2.58 - mappings[G_UNICODE_SCRIPT_MAKASAR] = _("Makasar"); // Since: 2.58 - mappings[G_UNICODE_SCRIPT_MEDEFAIDRIN] = _("Medefaidrin"); // Since: 2.58 - mappings[G_UNICODE_SCRIPT_OLD_SOGDIAN] = _("Old Sogdian"); // Since: 2.58 - mappings[G_UNICODE_SCRIPT_SOGDIAN] = _("Sogdian"); // Since: 2.58 - mappings[G_UNICODE_SCRIPT_ELYMAIC] = _("Elym"); // Since: 2.62 - mappings[G_UNICODE_SCRIPT_NANDINAGARI] = _("Nand"); // Since: 2.62 - mappings[G_UNICODE_SCRIPT_NYIAKENG_PUACHUE_HMONG]= _("Rohg"); // Since: 2.62 - mappings[G_UNICODE_SCRIPT_WANCHO] = _("Wcho"); // Since: 2.62 -*/ + mappings[G_UNICODE_SCRIPT_INVALID_CODE] = _("all"); + mappings[G_UNICODE_SCRIPT_COMMON] = _("common"); + mappings[G_UNICODE_SCRIPT_INHERITED] = _("inherited"); + mappings[G_UNICODE_SCRIPT_ARABIC] = _("Arabic"); + mappings[G_UNICODE_SCRIPT_ARMENIAN] = _("Armenian"); + mappings[G_UNICODE_SCRIPT_BENGALI] = _("Bengali"); + mappings[G_UNICODE_SCRIPT_BOPOMOFO] = _("Bopomofo"); + mappings[G_UNICODE_SCRIPT_CHEROKEE] = _("Cherokee"); + mappings[G_UNICODE_SCRIPT_COPTIC] = _("Coptic"); + mappings[G_UNICODE_SCRIPT_CYRILLIC] = _("Cyrillic"); + mappings[G_UNICODE_SCRIPT_DESERET] = _("Deseret"); + mappings[G_UNICODE_SCRIPT_DEVANAGARI] = _("Devanagari"); + mappings[G_UNICODE_SCRIPT_ETHIOPIC] = _("Ethiopic"); + mappings[G_UNICODE_SCRIPT_GEORGIAN] = _("Georgian"); + mappings[G_UNICODE_SCRIPT_GOTHIC] = _("Gothic"); + mappings[G_UNICODE_SCRIPT_GREEK] = _("Greek"); + mappings[G_UNICODE_SCRIPT_GUJARATI] = _("Gujarati"); + mappings[G_UNICODE_SCRIPT_GURMUKHI] = _("Gurmukhi"); + mappings[G_UNICODE_SCRIPT_HAN] = _("Han"); + mappings[G_UNICODE_SCRIPT_HANGUL] = _("Hangul"); + mappings[G_UNICODE_SCRIPT_HEBREW] = _("Hebrew"); + mappings[G_UNICODE_SCRIPT_HIRAGANA] = _("Hiragana"); + mappings[G_UNICODE_SCRIPT_KANNADA] = _("Kannada"); + mappings[G_UNICODE_SCRIPT_KATAKANA] = _("Katakana"); + mappings[G_UNICODE_SCRIPT_KHMER] = _("Khmer"); + mappings[G_UNICODE_SCRIPT_LAO] = _("Lao"); + mappings[G_UNICODE_SCRIPT_LATIN] = _("Latin"); + mappings[G_UNICODE_SCRIPT_MALAYALAM] = _("Malayalam"); + mappings[G_UNICODE_SCRIPT_MONGOLIAN] = _("Mongolian"); + mappings[G_UNICODE_SCRIPT_MYANMAR] = _("Myanmar"); + mappings[G_UNICODE_SCRIPT_OGHAM] = _("Ogham"); + mappings[G_UNICODE_SCRIPT_OLD_ITALIC] = _("Old Italic"); + mappings[G_UNICODE_SCRIPT_ORIYA] = _("Oriya"); + mappings[G_UNICODE_SCRIPT_RUNIC] = _("Runic"); + mappings[G_UNICODE_SCRIPT_SINHALA] = _("Sinhala"); + mappings[G_UNICODE_SCRIPT_SYRIAC] = _("Syriac"); + mappings[G_UNICODE_SCRIPT_TAMIL] = _("Tamil"); + mappings[G_UNICODE_SCRIPT_TELUGU] = _("Telugu"); + mappings[G_UNICODE_SCRIPT_THAANA] = _("Thaana"); + mappings[G_UNICODE_SCRIPT_THAI] = _("Thai"); + mappings[G_UNICODE_SCRIPT_TIBETAN] = _("Tibetan"); + mappings[G_UNICODE_SCRIPT_CANADIAN_ABORIGINAL] = _("Canadian Aboriginal"); + mappings[G_UNICODE_SCRIPT_YI] = _("Yi"); + mappings[G_UNICODE_SCRIPT_TAGALOG] = _("Tagalog"); + mappings[G_UNICODE_SCRIPT_HANUNOO] = _("Hanunoo"); + mappings[G_UNICODE_SCRIPT_BUHID] = _("Buhid"); + mappings[G_UNICODE_SCRIPT_TAGBANWA] = _("Tagbanwa"); + mappings[G_UNICODE_SCRIPT_BRAILLE] = _("Braille"); + mappings[G_UNICODE_SCRIPT_CYPRIOT] = _("Cypriot"); + mappings[G_UNICODE_SCRIPT_LIMBU] = _("Limbu"); + mappings[G_UNICODE_SCRIPT_OSMANYA] = _("Osmanya"); + mappings[G_UNICODE_SCRIPT_SHAVIAN] = _("Shavian"); + mappings[G_UNICODE_SCRIPT_LINEAR_B] = _("Linear B"); + mappings[G_UNICODE_SCRIPT_TAI_LE] = _("Tai Le"); + mappings[G_UNICODE_SCRIPT_UGARITIC] = _("Ugaritic"); + mappings[G_UNICODE_SCRIPT_NEW_TAI_LUE] = _("New Tai Lue"); + mappings[G_UNICODE_SCRIPT_BUGINESE] = _("Buginese"); + mappings[G_UNICODE_SCRIPT_GLAGOLITIC] = _("Glagolitic"); + mappings[G_UNICODE_SCRIPT_TIFINAGH] = _("Tifinagh"); + mappings[G_UNICODE_SCRIPT_SYLOTI_NAGRI] = _("Syloti Nagri"); + mappings[G_UNICODE_SCRIPT_OLD_PERSIAN] = _("Old Persian"); + mappings[G_UNICODE_SCRIPT_KHAROSHTHI] = _("Kharoshthi"); + mappings[G_UNICODE_SCRIPT_UNKNOWN] = _("unassigned"); + mappings[G_UNICODE_SCRIPT_BALINESE] = _("Balinese"); + mappings[G_UNICODE_SCRIPT_CUNEIFORM] = _("Cuneiform"); + mappings[G_UNICODE_SCRIPT_PHOENICIAN] = _("Phoenician"); + mappings[G_UNICODE_SCRIPT_PHAGS_PA] = _("Phags-pa"); + mappings[G_UNICODE_SCRIPT_NKO] = _("N'Ko"); + mappings[G_UNICODE_SCRIPT_KAYAH_LI] = _("Kayah Li"); + mappings[G_UNICODE_SCRIPT_LEPCHA] = _("Lepcha"); + mappings[G_UNICODE_SCRIPT_REJANG] = _("Rejang"); + mappings[G_UNICODE_SCRIPT_SUNDANESE] = _("Sundanese"); + mappings[G_UNICODE_SCRIPT_SAURASHTRA] = _("Saurashtra"); + mappings[G_UNICODE_SCRIPT_CHAM] = _("Cham"); + mappings[G_UNICODE_SCRIPT_OL_CHIKI] = _("Ol Chiki"); + mappings[G_UNICODE_SCRIPT_VAI] = _("Vai"); + mappings[G_UNICODE_SCRIPT_CARIAN] = _("Carian"); + mappings[G_UNICODE_SCRIPT_LYCIAN] = _("Lycian"); + mappings[G_UNICODE_SCRIPT_LYDIAN] = _("Lydian"); + mappings[G_UNICODE_SCRIPT_AVESTAN] = _("Avestan"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_BAMUM] = _("Bamum"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_EGYPTIAN_HIEROGLYPHS] = _("Egyptian Hieroglpyhs"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_IMPERIAL_ARAMAIC] = _("Imperial Aramaic"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_INSCRIPTIONAL_PAHLAVI] = _("Inscriptional Pahlavi"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_INSCRIPTIONAL_PARTHIAN] = _("Inscriptional Parthian"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_JAVANESE] = _("Javanese"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_KAITHI] = _("Kaithi"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_LISU] = _("Lisu"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_MEETEI_MAYEK] = _("Meetei Mayek"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_OLD_SOUTH_ARABIAN] = _("Old South Arabian"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_OLD_TURKIC] = _("Old Turkic"); // Since: 2.28 + mappings[G_UNICODE_SCRIPT_SAMARITAN] = _("Samaritan"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_TAI_THAM] = _("Tai Tham"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_TAI_VIET] = _("Tai Viet"); // Since: 2.26 + mappings[G_UNICODE_SCRIPT_BATAK] = _("Batak"); // Since: 2.28 + mappings[G_UNICODE_SCRIPT_BRAHMI] = _("Brahmi"); // Since: 2.28 + mappings[G_UNICODE_SCRIPT_MANDAIC] = _("Mandaic"); // Since: 2.28 + mappings[G_UNICODE_SCRIPT_CHAKMA] = _("Chakma"); // Since: 2.32 + mappings[G_UNICODE_SCRIPT_MEROITIC_CURSIVE] = _("Meroitic Cursive"); // Since: 2.32 + mappings[G_UNICODE_SCRIPT_MEROITIC_HIEROGLYPHS] = _("Meroitic Hieroglyphs"); // Since: 2.32 + mappings[G_UNICODE_SCRIPT_MIAO] = _("Miao"); // Since: 2.32 + mappings[G_UNICODE_SCRIPT_SHARADA] = _("Sharada"); // Since: 2.32 + mappings[G_UNICODE_SCRIPT_SORA_SOMPENG] = _("Sora Sompeng"); // Since: 2.32 + mappings[G_UNICODE_SCRIPT_TAKRI] = _("Takri"); // Since: 2.32 + mappings[G_UNICODE_SCRIPT_BASSA_VAH] = _("Bassa"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_CAUCASIAN_ALBANIAN] = _("Caucasian Albanian"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_DUPLOYAN] = _("Duployan"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_ELBASAN] = _("Elbasan"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_GRANTHA] = _("Grantha"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_KHOJKI] = _("Khojki"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_KHUDAWADI] = _("Khudawadi, Sindhi"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_LINEAR_A] = _("Linear A"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_MAHAJANI] = _("Mahajani"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_MANICHAEAN] = _("Manichaean"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_MENDE_KIKAKUI] = _("Mende Kikakui"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_MODI] = _("Modi"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_MRO] = _("Mro"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_NABATAEAN] = _("Nabataean"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_OLD_NORTH_ARABIAN] = _("Old North Arabian"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_OLD_PERMIC] = _("Old Permic"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_PAHAWH_HMONG] = _("Pahawh Hmong"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_PALMYRENE] = _("Palmyrene"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_PAU_CIN_HAU] = _("Pau Cin Hau"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_PSALTER_PAHLAVI] = _("Psalter Pahlavi"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_SIDDHAM] = _("Siddham"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_TIRHUTA] = _("Tirhuta"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_WARANG_CITI] = _("Warang Citi"); // Since: 2.42 + mappings[G_UNICODE_SCRIPT_AHOM] = _("Ahom"); // Since: 2.48 + mappings[G_UNICODE_SCRIPT_ANATOLIAN_HIEROGLYPHS] = _("Anatolian Hieroglyphs"); // Since: 2.48 + mappings[G_UNICODE_SCRIPT_HATRAN] = _("Hatran"); // Since: 2.48 + mappings[G_UNICODE_SCRIPT_MULTANI] = _("Multani"); // Since: 2.48 + mappings[G_UNICODE_SCRIPT_OLD_HUNGARIAN] = _("Old Hungarian"); // Since: 2.48 + mappings[G_UNICODE_SCRIPT_SIGNWRITING] = _("Signwriting"); // Since: 2.48 + /* + mappings[G_UNICODE_SCRIPT_ADLAM] = _("Adlam"); // Since: 2.50 + mappings[G_UNICODE_SCRIPT_BHAIKSUKI] = _("Bhaiksuki"); // Since: 2.50 + mappings[G_UNICODE_SCRIPT_MARCHEN] = _("Marchen"); // Since: 2.50 + mappings[G_UNICODE_SCRIPT_NEWA] = _("Newa"); // Since: 2.50 + mappings[G_UNICODE_SCRIPT_OSAGE] = _("Osage"); // Since: 2.50 + mappings[G_UNICODE_SCRIPT_TANGUT] = _("Tangut"); // Since: 2.50 + mappings[G_UNICODE_SCRIPT_MASARAM_GONDI] = _("Masaram Gondi"); // Since: 2.54 + mappings[G_UNICODE_SCRIPT_NUSHU] = _("Nushu"); // Since: 2.54 + mappings[G_UNICODE_SCRIPT_SOYOMBO] = _("Soyombo"); // Since: 2.54 + mappings[G_UNICODE_SCRIPT_ZANABAZAR_SQUARE] = _("Zanabazar Square"); // Since: 2.54 + mappings[G_UNICODE_SCRIPT_DOGRA] = _("Dogra"); // Since: 2.58 + mappings[G_UNICODE_SCRIPT_GUNJALA_GONDI] = _("Gunjala Gondi"); // Since: 2.58 + mappings[G_UNICODE_SCRIPT_HANIFI_ROHINGYA] = _("Hanifi Rohingya"); // Since: 2.58 + mappings[G_UNICODE_SCRIPT_MAKASAR] = _("Makasar"); // Since: 2.58 + mappings[G_UNICODE_SCRIPT_MEDEFAIDRIN] = _("Medefaidrin"); // Since: 2.58 + mappings[G_UNICODE_SCRIPT_OLD_SOGDIAN] = _("Old Sogdian"); // Since: 2.58 + mappings[G_UNICODE_SCRIPT_SOGDIAN] = _("Sogdian"); // Since: 2.58 + mappings[G_UNICODE_SCRIPT_ELYMAIC] = _("Elym"); // Since: 2.62 + mappings[G_UNICODE_SCRIPT_NANDINAGARI] = _("Nand"); // Since: 2.62 + mappings[G_UNICODE_SCRIPT_NYIAKENG_PUACHUE_HMONG]= _("Rohg"); // Since: 2.62 + mappings[G_UNICODE_SCRIPT_WANCHO] = _("Wcho"); // Since: 2.62 + */ } return mappings; } @@ -215,7 +209,7 @@ static std::map<GUnicodeScript, Glib::ustring> & getScriptToName() typedef std::pair<gunichar, gunichar> Range; typedef std::pair<Range, Glib::ustring> NamedRange; -static std::vector<NamedRange> & getRanges() +static std::vector<NamedRange> &getRanges() { static bool init = false; static std::vector<NamedRange> ranges; @@ -388,7 +382,6 @@ static std::vector<NamedRange> & getRanges() ranges.emplace_back(std::make_pair(0x1F900, 0x1F9FF), _("Supplemental Symbols and Pictographs")); ranges.emplace_back(std::make_pair(0x1FA00, 0x1FA7F), _("Chess Symbols")); ranges.emplace_back(std::make_pair(0x1FA80, 0x1FAFF), _("Symbols and Pictographs Extended-A")); - } return ranges; @@ -419,11 +412,11 @@ GlyphColumns *GlyphsPanel::getColumns() /** * Constructor */ -GlyphsPanel::GlyphsPanel() : - Inkscape::UI::Widget::Panel("/dialogs/glyphs", SP_VERB_DIALOG_GLYPHS), - store(Gtk::ListStore::create(*getColumns())), - instanceConns(), - desktopConns() +GlyphsPanel::GlyphsPanel() + : Inkscape::UI::Widget::Panel("/dialogs/glyphs", SP_VERB_DIALOG_GLYPHS) + , store(Gtk::ListStore::create(*getColumns())) + , instanceConns() + , desktopConns() { auto table = new Gtk::Grid(); table->set_row_spacing(4); @@ -431,30 +424,28 @@ GlyphsPanel::GlyphsPanel() : _getContents()->pack_start(*Gtk::manage(table), Gtk::PACK_EXPAND_WIDGET); guint row = 0; -// ------------------------------- + // ------------------------------- { - fontSelector = new Inkscape::UI::Widget::FontSelector (false, false); - fontSelector->set_name ("UnicodeCharacters"); + fontSelector = new Inkscape::UI::Widget::FontSelector(false, false); + fontSelector->set_name("UnicodeCharacters"); - sigc::connection conn = - fontSelector->connectChanged(sigc::hide(sigc::mem_fun(*this, &GlyphsPanel::rebuild))); + sigc::connection conn = fontSelector->connectChanged(sigc::hide(sigc::mem_fun(*this, &GlyphsPanel::rebuild))); instanceConns.push_back(conn); table->attach(*Gtk::manage(fontSelector), 0, row, 3, 1); row++; } -// ------------------------------- + // ------------------------------- { auto label = new Gtk::Label(_("Script: ")); - table->attach( *Gtk::manage(label), 0, row, 1, 1); + table->attach(*Gtk::manage(label), 0, row, 1, 1); scriptCombo = Gtk::manage(new Gtk::ComboBoxText()); - for (auto & it : getScriptToName()) - { + for (auto &it : getScriptToName()) { scriptCombo->append(it.second); } @@ -470,14 +461,14 @@ GlyphsPanel::GlyphsPanel() : row++; -// ------------------------------- + // ------------------------------- { auto label = new Gtk::Label(_("Range: ")); - table->attach( *Gtk::manage(label), 0, row, 1, 1); + table->attach(*Gtk::manage(label), 0, row, 1, 1); rangeCombo = Gtk::manage(new Gtk::ComboBoxText()); - for (auto & it : getRanges()) { + for (auto &it : getRanges()) { rangeCombo->append(it.second); } @@ -493,11 +484,11 @@ GlyphsPanel::GlyphsPanel() : row++; -// ------------------------------- + // ------------------------------- GlyphColumns *columns = getColumns(); - iconView = new Gtk::IconView(static_cast<Glib::RefPtr<Gtk::TreeModel> >(store)); + iconView = new Gtk::IconView(static_cast<Glib::RefPtr<Gtk::TreeModel>>(store)); iconView->set_name("UnicodeIconView"); iconView->set_markup_column(columns->name); iconView->set_tooltip_column(2); // Uses Pango markup, must use column number. @@ -512,7 +503,6 @@ GlyphsPanel::GlyphsPanel() : conn = iconView->signal_selection_changed().connect(sigc::mem_fun(*this, &GlyphsPanel::glyphSelectionChanged)); instanceConns.push_back(conn); - Gtk::ScrolledWindow *scroller = new Gtk::ScrolledWindow(); scroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS); scroller->add(*Gtk::manage(iconView)); @@ -522,7 +512,7 @@ GlyphsPanel::GlyphsPanel() : row++; -// ------------------------------- + // ------------------------------- Gtk::HBox *box = new Gtk::HBox(); @@ -549,51 +539,52 @@ GlyphsPanel::GlyphsPanel() : box->pack_end(*Gtk::manage(insertBtn), Gtk::PACK_SHRINK); box->set_hexpand(); - table->attach( *Gtk::manage(box), 0, row, 3, 1); + table->attach(*Gtk::manage(box), 0, row, 3, 1); row++; -// ------------------------------- - + // ------------------------------- show_all_children(); } GlyphsPanel::~GlyphsPanel() { - for (auto & instanceConn : instanceConns) { + for (auto &instanceConn : instanceConns) { instanceConn.disconnect(); } instanceConns.clear(); - for (auto & desktopConn : desktopConns) { + for (auto &desktopConn : desktopConns) { desktopConn.disconnect(); } desktopConns.clear(); } - void GlyphsPanel::setDesktop(SPDesktop *desktop) { Panel::setDesktop(desktop); { { - for (auto & desktopConn : desktopConns) { + for (auto &desktopConn : desktopConns) { desktopConn.disconnect(); } desktopConns.clear(); } if (desktop && desktop->selection) { - sigc::connection conn = desktop->selection->connectChanged(sigc::hide(sigc::bind(sigc::mem_fun(*this, &GlyphsPanel::readSelection), true, true))); + sigc::connection conn = desktop->selection->connectChanged( + sigc::hide(sigc::bind(sigc::mem_fun(*this, &GlyphsPanel::readSelection), true, true))); desktopConns.push_back(conn); // Text selection within selected items has changed: - conn = desktop->connectToolSubselectionChanged(sigc::hide(sigc::bind(sigc::mem_fun(*this, &GlyphsPanel::readSelection), true, false))); + conn = desktop->connectToolSubselectionChanged( + sigc::hide(sigc::bind(sigc::mem_fun(*this, &GlyphsPanel::readSelection), true, false))); desktopConns.push_back(conn); // Must check flags, so can't call performUpdate() directly. - conn = desktop->selection->connectModified(sigc::hide<0>(sigc::mem_fun(*this, &GlyphsPanel::selectionModifiedCB))); + conn = desktop->selection->connectModified( + sigc::hide<0>(sigc::mem_fun(*this, &GlyphsPanel::selectionModifiedCB))); desktopConns.push_back(conn); readSelection(true, true); @@ -606,9 +597,9 @@ void GlyphsPanel::insertText() { auto targetDesktop = getDesktop(); SPItem *textItem = nullptr; - auto itemlist= targetDesktop->selection->items(); - for(auto i=itemlist.begin(); itemlist.end() != i; ++i) { - if (SP_IS_TEXT(*i) || SP_IS_FLOWTEXT(*i)) { + auto itemlist = targetDesktop->selection->items(); + for (auto i = itemlist.begin(); itemlist.end() != i; ++i) { + if (SP_IS_TEXT(*i) || SP_IS_FLOWTEXT(*i)) { textItem = *i; break; } @@ -622,7 +613,7 @@ void GlyphsPanel::insertText() auto itemArray = iconView->get_selected_items(); if (!itemArray.empty()) { - Gtk::TreeModel::Path const & path = *itemArray.begin(); + Gtk::TreeModel::Path const &path = *itemArray.begin(); Gtk::ListStore::iterator row = store->get_iter(path); gunichar ch = (*row)[getColumns()->code]; glyphs = ch; @@ -638,7 +629,7 @@ void GlyphsPanel::insertText() } } -void GlyphsPanel::glyphActivated(Gtk::TreeModel::Path const & path) +void GlyphsPanel::glyphActivated(Gtk::TreeModel::Path const &path) { Gtk::ListStore::iterator row = store->get_iter(path); gunichar ch = (*row)[getColumns()->code]; @@ -663,18 +654,17 @@ void GlyphsPanel::glyphSelectionChanged() if (itemArray.empty()) { label->set_text(" "); } else { - Gtk::TreeModel::Path const & path = *itemArray.begin(); + Gtk::TreeModel::Path const &path = *itemArray.begin(); Gtk::ListStore::iterator row = store->get_iter(path); gunichar ch = (*row)[getColumns()->code]; - Glib::ustring scriptName; GUnicodeScript script = g_unichar_get_script(ch); std::map<GUnicodeScript, Glib::ustring> mappings = getScriptToName(); if (mappings.find(script) != mappings.end()) { scriptName = mappings[script]; } - gchar * tmp = g_strdup_printf("U+%04X %s", ch, scriptName.c_str()); + gchar *tmp = g_strdup_printf("U+%04X %s", ch, scriptName.c_str()); label->set_text(tmp); } calcCanInsert(); @@ -682,11 +672,9 @@ void GlyphsPanel::glyphSelectionChanged() void GlyphsPanel::selectionModifiedCB(guint flags) { - bool style = ((flags & ( SP_OBJECT_CHILD_MODIFIED_FLAG | - SP_OBJECT_STYLE_MODIFIED_FLAG )) != 0 ); + bool style = ((flags & (SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG)) != 0); - bool content = ((flags & ( SP_OBJECT_CHILD_MODIFIED_FLAG | - SP_TEXT_CONTENT_MODIFIED_FLAG )) != 0 ); + bool content = ((flags & (SP_OBJECT_CHILD_MODIFIED_FLAG | SP_TEXT_CONTENT_MODIFIED_FLAG)) != 0); readSelection(style, content); } @@ -695,7 +683,7 @@ void GlyphsPanel::calcCanInsert() { int items = 0; auto itemlist = getDesktop()->selection->items(); - for(auto i=itemlist.begin(); itemlist.end() != i; ++i) { + for (auto i = itemlist.begin(); itemlist.end() != i; ++i) { if (SP_IS_TEXT(*i) || SP_IS_FLOWTEXT(*i)) { ++items; } @@ -703,8 +691,7 @@ void GlyphsPanel::calcCanInsert() bool enable = (items == 1); if (enable) { - enable &= (!iconView->get_selected_items().empty() - || (entry->get_text_length() > 0)); + enable &= (!iconView->get_selected_items().empty() || (entry->get_text_length() > 0)); } if (enable != insertBtn->is_sensitive()) { @@ -712,37 +699,35 @@ void GlyphsPanel::calcCanInsert() } } -void GlyphsPanel::readSelection( bool updateStyle, bool updateContent ) +void GlyphsPanel::readSelection(bool updateStyle, bool updateContent) { calcCanInsert(); if (updateStyle) { - Inkscape::FontLister* fontlister = Inkscape::FontLister::get_instance(); + Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); // Update family/style based on selection. fontlister->selection_update(); // Update GUI (based on fontlister values). - fontSelector->update_font (); + fontSelector->update_font(); } } - void GlyphsPanel::rebuild() { Glib::ustring fontspec = fontSelector->get_fontspec(); - font_instance* font = nullptr; - if( !fontspec.empty() ) { - font = font_factory::Default()->FaceFromFontSpecification( fontspec.c_str() ); + font_instance *font = nullptr; + if (!fontspec.empty()) { + font = font_factory::Default()->FaceFromFontSpecification(fontspec.c_str()); } if (font) { - GUnicodeScript script = G_UNICODE_SCRIPT_INVALID_CODE; Glib::ustring scriptName = scriptCombo->get_active_text(); std::map<GUnicodeScript, Glib::ustring> items = getScriptToName(); - for (auto & item : items) { + for (auto &item : items) { if (scriptName == item.second) { script = item.first; break; @@ -772,14 +757,13 @@ void GlyphsPanel::rebuild() GlyphColumns *columns = getColumns(); store->clear(); - for (unsigned int & it : present) - { + for (unsigned int &it : present) { Gtk::ListStore::iterator row = store->append(); Glib::ustring tmp; tmp += it; - tmp = Glib::Markup::escape_text(tmp); // Escape '&', '<', etc. + tmp = Glib::Markup::escape_text(tmp); // Escape '&', '<', etc. (*row)[columns->code] = it; - (*row)[columns->name] = "<span font_desc=\"" + fontspec + "\">" + tmp + "</span>"; + (*row)[columns->name] = "<span font_desc=\"" + fontspec + "\">" + tmp + "</span>"; (*row)[columns->tooltip] = "<span font_desc=\"" + fontspec + "\" size=\"42000\">" + tmp + "</span>"; } @@ -788,8 +772,7 @@ void GlyphsPanel::rebuild() } } - -} // namespace Dialogs +} // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/glyphs.h b/src/ui/dialog/glyphs.h index 3beafb1e88d74041a9c19774d202b50494bfb634..414533438aad24b388c586e044108dc08d0dbf17 100644 --- a/src/ui/dialog/glyphs.h +++ b/src/ui/dialog/glyphs.h @@ -8,9 +8,9 @@ #ifndef SEEN_DIALOGS_GLYPHS_H #define SEEN_DIALOGS_GLYPHS_H -#include "ui/widget/panel.h" #include <gtkmm/treemodel.h> +#include "ui/widget/panel.h" namespace Gtk { class ComboBoxText; @@ -18,7 +18,7 @@ class Entry; class IconView; class Label; class ListStore; -} +} // namespace Gtk namespace Inkscape { namespace UI { @@ -40,28 +40,26 @@ public: GlyphsPanel(); ~GlyphsPanel() override; - static GlyphsPanel& getInstance(); + static GlyphsPanel &getInstance(); void setDesktop(SPDesktop *desktop) override; protected: - private: - GlyphsPanel(GlyphsPanel const &) = delete; // no copy + GlyphsPanel(GlyphsPanel const &) = delete; // no copy GlyphsPanel &operator=(GlyphsPanel const &) = delete; // no assign static GlyphColumns *getColumns(); void rebuild(); - void glyphActivated(Gtk::TreeModel::Path const & path); + void glyphActivated(Gtk::TreeModel::Path const &path); void glyphSelectionChanged(); void selectionModifiedCB(guint flags); - void readSelection( bool updateStyle, bool updateContent ); + void readSelection(bool updateStyle, bool updateContent); void calcCanInsert(); void insertText(); - Glib::RefPtr<Gtk::ListStore> store; Gtk::IconView *iconView; Gtk::Entry *entry; @@ -75,8 +73,7 @@ private: std::vector<sigc::connection> desktopConns; }; - -} // namespace Dialogs +} // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/grid-arrange-tab.cpp b/src/ui/dialog/grid-arrange-tab.cpp index 262039056f04debcc439421dd186d7ccf99a85da..92fee26bced77eed308a586816ab9f8ada37a52a 100644 --- a/src/ui/dialog/grid-arrange-tab.cpp +++ b/src/ui/dialog/grid-arrange-tab.cpp @@ -17,327 +17,316 @@ //#define DEBUG_GRID_ARRANGE 1 #include "ui/dialog/grid-arrange-tab.h" -#include <glibmm/i18n.h> +#include <2geom/transforms.h> +#include <glibmm/i18n.h> #include <gtkmm/grid.h> #include <gtkmm/sizegroup.h> -#include <2geom/transforms.h> - -#include "verbs.h" -#include "preferences.h" -#include "inkscape.h" - -#include "document.h" -#include "document-undo.h" #include "desktop.h" +#include "document-undo.h" +#include "document.h" +#include "inkscape.h" +#include "preferences.h" +#include "verbs.h" //#include "sp-item-transform.h" FIXME #include "ui/dialog/tile.h" // for Inkscape::UI::Dialog::ArrangeDialog - /* - * Sort items by their x co-ordinates, taking account of y (keeps rows intact) - * - * <0 *elem1 goes before *elem2 - * 0 *elem1 == *elem2 - * >0 *elem1 goes after *elem2 - */ - static bool sp_compare_x_position(SPItem *first, SPItem *second) - { - using Geom::X; - using Geom::Y; - - Geom::OptRect a = first->documentVisualBounds(); - Geom::OptRect b = second->documentVisualBounds(); +/* + * Sort items by their x co-ordinates, taking account of y (keeps rows intact) + * + * <0 *elem1 goes before *elem2 + * 0 *elem1 == *elem2 + * >0 *elem1 goes after *elem2 + */ +static bool sp_compare_x_position(SPItem *first, SPItem *second) +{ + using Geom::X; + using Geom::Y; - if ( !a || !b ) { - // FIXME? - return false; - } + Geom::OptRect a = first->documentVisualBounds(); + Geom::OptRect b = second->documentVisualBounds(); - double const a_height = a->dimensions()[Y]; - double const b_height = b->dimensions()[Y]; + if (!a || !b) { + // FIXME? + return false; + } - bool a_in_b_vert = false; - if ((a->min()[Y] < b->min()[Y] + 0.1) && (a->min()[Y] > b->min()[Y] - b_height)) { - a_in_b_vert = true; - } else if ((b->min()[Y] < a->min()[Y] + 0.1) && (b->min()[Y] > a->min()[Y] - a_height)) { - a_in_b_vert = true; - } else if (b->min()[Y] == a->min()[Y]) { - a_in_b_vert = true; - } else { - a_in_b_vert = false; - } + double const a_height = a->dimensions()[Y]; + double const b_height = b->dimensions()[Y]; - if (!a_in_b_vert) { // a and b are not in the same row - return (a->min()[Y] < b->min()[Y]); - } - return (a->min()[X] < b->min()[X]); + bool a_in_b_vert = false; + if ((a->min()[Y] < b->min()[Y] + 0.1) && (a->min()[Y] > b->min()[Y] - b_height)) { + a_in_b_vert = true; + } else if ((b->min()[Y] < a->min()[Y] + 0.1) && (b->min()[Y] > a->min()[Y] - a_height)) { + a_in_b_vert = true; + } else if (b->min()[Y] == a->min()[Y]) { + a_in_b_vert = true; + } else { + a_in_b_vert = false; } - /* - * Sort items by their y co-ordinates. - */ - static bool sp_compare_y_position(SPItem *first, SPItem *second) - { - Geom::OptRect a = first->documentVisualBounds(); - Geom::OptRect b = second->documentVisualBounds(); + if (!a_in_b_vert) { // a and b are not in the same row + return (a->min()[Y] < b->min()[Y]); + } + return (a->min()[X] < b->min()[X]); +} - if ( !a || !b ) { - // FIXME? - return false; - } +/* + * Sort items by their y co-ordinates. + */ +static bool sp_compare_y_position(SPItem *first, SPItem *second) +{ + Geom::OptRect a = first->documentVisualBounds(); + Geom::OptRect b = second->documentVisualBounds(); - if (a->min()[Geom::Y] > b->min()[Geom::Y]) { - return false; - } - if (a->min()[Geom::Y] < b->min()[Geom::Y]) { - return true; - } + if (!a || !b) { + // FIXME? + return false; + } + if (a->min()[Geom::Y] > b->min()[Geom::Y]) { return false; } + if (a->min()[Geom::Y] < b->min()[Geom::Y]) { + return true; + } + return false; +} - namespace Inkscape { - namespace UI { - namespace Dialog { +namespace Inkscape { +namespace UI { +namespace Dialog { +//######################################################################### +//## E V E N T S +//######################################################################### - //######################################################################### - //## E V E N T S - //######################################################################### +/* + * + * This arranges the selection in a grid pattern. + * + */ - /* - * - * This arranges the selection in a grid pattern. - * - */ +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; + double total_col_width, total_row_height; + col_width = 0; + row_height = 0; + total_col_width = 0; + total_row_height = 0; + + // check for correct numbers in the row- and col-spinners + on_col_spinbutton_changed(); + on_row_spinbutton_changed(); + + // set padding to manual values + paddingx = XPadding.getValue("px"); + paddingy = YPadding.getValue("px"); + + std::vector<double> row_heights; + std::vector<double> col_widths; + std::vector<double> row_ys; + std::vector<double> col_xs; + + int NoOfCols = NoOfColsSpinner.get_value_as_int(); + int NoOfRows = NoOfRowsSpinner.get_value_as_int(); + + width = 0; + for (a = 0; a < NoOfCols; a++) { + col_widths.push_back(width); + } - void GridArrangeTab::arrange() - { + height = 0; + for (a = 0; a < NoOfRows; a++) { + row_heights.push_back(height); + } + grid_left = 99999; + grid_top = 99999; - 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; - double total_col_width,total_row_height; - col_width = 0; - row_height = 0; - total_col_width=0; - total_row_height=0; - - // check for correct numbers in the row- and col-spinners - on_col_spinbutton_changed(); - on_row_spinbutton_changed(); - - // set padding to manual values - paddingx = XPadding.getValue("px"); - paddingy = YPadding.getValue("px"); - - std::vector<double> row_heights; - std::vector<double> col_widths; - std::vector<double> row_ys; - std::vector<double> col_xs; - - int NoOfCols = NoOfColsSpinner.get_value_as_int(); - int NoOfRows = NoOfRowsSpinner.get_value_as_int(); - - width = 0; - for (a=0;a<NoOfCols; a++){ - col_widths.push_back(width); - } + SPDesktop *desktop = Parent->getDesktop(); + desktop->getDocument()->ensureUpToDate(); - height = 0; - for (a=0;a<NoOfRows; a++){ - row_heights.push_back(height); + Inkscape::Selection *selection = desktop->getSelection(); + std::vector<SPItem *> items; + if (selection) { + items.insert(items.end(), selection->items().begin(), selection->items().end()); + } + + for (auto item : items) { + Geom::OptRect b = item->documentVisualBounds(); + if (!b) { + continue; } - grid_left = 99999; - grid_top = 99999; - SPDesktop *desktop = Parent->getDesktop(); - desktop->getDocument()->ensureUpToDate(); + width = b->dimensions()[Geom::X]; + height = b->dimensions()[Geom::Y]; - Inkscape::Selection *selection = desktop->getSelection(); - std::vector<SPItem*> items; - if (selection) { - items.insert(items.end(), selection->items().begin(), selection->items().end()); + if (b->min()[Geom::X] < grid_left) { + grid_left = b->min()[Geom::X]; + } + if (b->min()[Geom::Y] < grid_top) { + grid_top = b->min()[Geom::Y]; } + if (width > col_width) { + col_width = width; + } + if (height > row_height) { + row_height = height; + } + } - for(auto item : items){ - Geom::OptRect b = item->documentVisualBounds(); - if (!b) { - continue; - } + // require the sorting done before we can calculate row heights etc. + + g_return_if_fail(selection); + std::vector<SPItem *> sorted(selection->items().begin(), selection->items().end()); + sort(sorted.begin(), sorted.end(), sp_compare_y_position); + sort(sorted.begin(), sorted.end(), sp_compare_x_position); + + // Calculate individual Row and Column sizes if necessary + cnt = 0; + const std::vector<SPItem *> sizes(sorted); + for (auto item : sizes) { + Geom::OptRect b = item->documentVisualBounds(); + if (b) { width = b->dimensions()[Geom::X]; height = b->dimensions()[Geom::Y]; - - if (b->min()[Geom::X] < grid_left) { - grid_left = b->min()[Geom::X]; - } - if (b->min()[Geom::Y] < grid_top) { - grid_top = b->min()[Geom::Y]; + if (width > col_widths[(cnt % NoOfCols)]) { + col_widths[(cnt % NoOfCols)] = width; } - if (width > col_width) { - col_width = width; - } - if (height > row_height) { - row_height = height; + if (height > row_heights[(cnt / NoOfCols)]) { + row_heights[(cnt / NoOfCols)] = height; } } + cnt++; + } - // require the sorting done before we can calculate row heights etc. - - g_return_if_fail(selection); - std::vector<SPItem*> sorted(selection->items().begin(), selection->items().end()); - sort(sorted.begin(),sorted.end(),sp_compare_y_position); - sort(sorted.begin(),sorted.end(),sp_compare_x_position); - - - // Calculate individual Row and Column sizes if necessary - - - cnt=0; - const std::vector<SPItem*> sizes(sorted); - for (auto item : sizes) { - Geom::OptRect b = item->documentVisualBounds(); - if (b) { - width = b->dimensions()[Geom::X]; - height = b->dimensions()[Geom::Y]; - if (width > col_widths[(cnt % NoOfCols)]) { - col_widths[(cnt % NoOfCols)] = width; - } - if (height > row_heights[(cnt / NoOfCols)]) { - row_heights[(cnt / NoOfCols)] = height; - } - } - - cnt++; - } - - - /// Make sure the top and left of the grid don't move by compensating for align values. - if (RowHeightButton.get_active()){ - grid_top = grid_top - (((row_height - row_heights[0]) / 2)*(VertAlign)); + /// Make sure the top and left of the grid don't move by compensating for align values. + if (RowHeightButton.get_active()) { + grid_top = grid_top - (((row_height - row_heights[0]) / 2) * (VertAlign)); } - if (ColumnWidthButton.get_active()){ - grid_left = grid_left - (((col_width - col_widths[0]) /2)*(HorizAlign)); + if (ColumnWidthButton.get_active()) { + grid_left = grid_left - (((col_width - col_widths[0]) / 2) * (HorizAlign)); } - #ifdef DEBUG_GRID_ARRANGE - g_print("\n cx = %f cy= %f gridleft=%f",cx,cy,grid_left); - #endif +#ifdef DEBUG_GRID_ARRANGE + g_print("\n cx = %f cy= %f gridleft=%f", cx, cy, grid_left); +#endif // Calculate total widths and heights, allowing for columns and rows non uniformly sized. - if (ColumnWidthButton.get_active()){ + if (ColumnWidthButton.get_active()) { total_col_width = col_width * NoOfCols; col_widths.clear(); - for (a=0;a<NoOfCols; a++){ + for (a = 0; a < NoOfCols; a++) { col_widths.push_back(col_width); } } else { - for (a = 0; a < (int)col_widths.size(); a++) - { - total_col_width += col_widths[a] ; + for (a = 0; a < (int)col_widths.size(); a++) { + total_col_width += col_widths[a]; } } - if (RowHeightButton.get_active()){ + if (RowHeightButton.get_active()) { total_row_height = row_height * NoOfRows; row_heights.clear(); - for (a=0;a<NoOfRows; a++){ + for (a = 0; a < NoOfRows; a++) { row_heights.push_back(row_height); } } else { - for (a = 0; a < (int)row_heights.size(); a++) - { - total_row_height += row_heights[a] ; + for (a = 0; a < (int)row_heights.size(); a++) { + total_row_height += row_heights[a]; } } - Geom::OptRect sel_bbox = selection->visualBounds(); // Fit to bbox, calculate padding between rows accordingly. - if ( sel_bbox && !SpaceManualRadioButton.get_active() ){ + if (sel_bbox && !SpaceManualRadioButton.get_active()) { #ifdef DEBUG_GRID_ARRANGE -g_print("\n row = %f col = %f selection x= %f selection y = %f", total_row_height,total_col_width, b.extent(Geom::X), b.extent(Geom::Y)); + g_print("\n row = %f col = %f selection x= %f selection y = %f", total_row_height, total_col_width, + b.extent(Geom::X), b.extent(Geom::Y)); #endif - paddingx = (sel_bbox->width() - total_col_width) / (NoOfCols -1); - paddingy = (sel_bbox->height() - total_row_height) / (NoOfRows -1); + paddingx = (sel_bbox->width() - total_col_width) / (NoOfCols - 1); + paddingy = (sel_bbox->height() - total_row_height) / (NoOfRows - 1); } -/* - Horizontal align - Left = 0 - Centre = 1 - Right = 2 + /* + Horizontal align - Left = 0 + Centre = 1 + Right = 2 - Vertical align - Top = 0 - Middle = 1 - Bottom = 2 + Vertical align - Top = 0 + Middle = 1 + Bottom = 2 - X position is calculated by taking the grids left co-ord, adding the distance to the column, - then adding 1/2 the spacing multiplied by the align variable above, - Y position likewise, takes the top of the grid, adds the y to the current row then adds the padding in to align it. + X position is calculated by taking the grids left co-ord, adding the distance to the column, + then adding 1/2 the spacing multiplied by the align variable above, + Y position likewise, takes the top of the grid, adds the y to the current row then adds the padding in to align + it. -*/ + */ // Calculate row and column x and y coords required to allow for columns and rows which are non uniformly sized. - for (a=0;a<NoOfCols; a++){ - if (a<1) col_xs.push_back(0); - else col_xs.push_back(col_widths[a-1]+paddingx+col_xs[a-1]); + for (a = 0; a < NoOfCols; a++) { + if (a < 1) + col_xs.push_back(0); + else + col_xs.push_back(col_widths[a - 1] + paddingx + col_xs[a - 1]); } - - for (a=0;a<NoOfRows; a++){ - if (a<1) row_ys.push_back(0); - else row_ys.push_back(row_heights[a-1]+paddingy+row_ys[a-1]); + for (a = 0; a < NoOfRows; a++) { + if (a < 1) + row_ys.push_back(0); + else + row_ys.push_back(row_heights[a - 1] + paddingy + row_ys[a - 1]); } - cnt=0; - std::vector<SPItem*>::iterator it = sorted.begin(); - for (row_cnt=0; ((it != sorted.end()) && (row_cnt<NoOfRows)); ++row_cnt) { - - std::vector<SPItem *> current_row; - col_cnt = 0; - for(;it!=sorted.end()&&col_cnt<NoOfCols;++it) { - current_row.push_back(*it); - col_cnt++; - } + cnt = 0; + std::vector<SPItem *>::iterator it = sorted.begin(); + for (row_cnt = 0; ((it != sorted.end()) && (row_cnt < NoOfRows)); ++row_cnt) { + std::vector<SPItem *> current_row; + col_cnt = 0; + for (; it != sorted.end() && col_cnt < NoOfCols; ++it) { + current_row.push_back(*it); + col_cnt++; + } - for (auto item:current_row) { - Geom::OptRect b = item->documentVisualBounds(); - Geom::Point min; - if (b) { - width = b->dimensions()[Geom::X]; - height = b->dimensions()[Geom::Y]; - min = b->min(); - } else { - width = height = 0; - min = Geom::Point(0, 0); - } + for (auto item : current_row) { + Geom::OptRect b = item->documentVisualBounds(); + Geom::Point min; + if (b) { + width = b->dimensions()[Geom::X]; + height = b->dimensions()[Geom::Y]; + min = b->min(); + } else { + width = height = 0; + min = Geom::Point(0, 0); + } - row = cnt / NoOfCols; - col = cnt % NoOfCols; + row = cnt / NoOfCols; + col = cnt % NoOfCols; - new_x = grid_left + (((col_widths[col] - width)/2)*HorizAlign) + col_xs[col]; - new_y = grid_top + (((row_heights[row] - height)/2)*VertAlign) + row_ys[row]; + new_x = grid_left + (((col_widths[col] - width) / 2) * HorizAlign) + col_xs[col]; + new_y = grid_top + (((row_heights[row] - height) / 2) * VertAlign) + row_ys[row]; - Geom::Point move = Geom::Point(new_x, new_y) - min; - Geom::Affine const affine = Geom::Affine(Geom::Translate(move)); - item->set_i2d_affine(item->i2doc_affine() * affine * item->document->doc2dt()); - item->doWriteTransform(item->transform); - item->updateRepr(); - cnt +=1; - } + Geom::Point move = Geom::Point(new_x, new_y) - min; + Geom::Affine const affine = Geom::Affine(Geom::Translate(move)); + item->set_i2d_affine(item->i2doc_affine() * affine * item->document->doc2dt()); + item->doWriteTransform(item->transform); + item->updateRepr(); + cnt += 1; + } } - DocumentUndo::done(desktop->getDocument(), SP_VERB_SELECTION_ARRANGE, - _("Arrange in a grid")); - + DocumentUndo::done(desktop->getDocument(), SP_VERB_SELECTION_ARRANGE, _("Arrange in a grid")); } - //######################################################################### //## E V E N T S //######################################################################### @@ -349,23 +338,23 @@ void GridArrangeTab::on_row_spinbutton_changed() { // quit if run by the attr_changed listener if (updating) { - return; - } + return; + } // in turn, prevent listener from responding updating = true; SPDesktop *desktop = Parent->getDesktop(); Inkscape::Selection *selection = desktop ? desktop->selection : nullptr; - g_return_if_fail( selection ); + g_return_if_fail(selection); - int selcount = (int) boost::distance(selection->items()); + int selcount = (int)boost::distance(selection->items()); double PerCol = ceil(selcount / NoOfColsSpinner.get_value()); NoOfRowsSpinner.set_value(PerCol); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble("/dialogs/gridtiler/NoOfCols", NoOfColsSpinner.get_value()); - updating=false; + updating = false; } /** @@ -375,8 +364,8 @@ void GridArrangeTab::on_col_spinbutton_changed() { // quit if run by the attr_changed listener if (updating) { - return; - } + return; + } // in turn, prevent listener from responding updating = true; @@ -384,14 +373,14 @@ void GridArrangeTab::on_col_spinbutton_changed() Inkscape::Selection *selection = desktop ? desktop->selection : nullptr; g_return_if_fail(selection); - int selcount = (int) boost::distance(selection->items()); + int selcount = (int)boost::distance(selection->items()); double PerRow = ceil(selcount / NoOfRowsSpinner.get_value()); NoOfColsSpinner.set_value(PerRow); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble("/dialogs/gridtiler/NoOfCols", PerRow); - updating=false; + updating = false; } /** @@ -401,7 +390,6 @@ void GridArrangeTab::on_xpad_spinbutton_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble("/dialogs/gridtiler/XPad", XPadding.getValue("px")); - } /** @@ -413,7 +401,6 @@ void GridArrangeTab::on_ypad_spinbutton_changed() prefs->setDouble("/dialogs/gridtiler/YPad", YPadding.getValue("px")); } - /** * checked/unchecked autosize Rows button. */ @@ -425,7 +412,7 @@ void GridArrangeTab::on_RowSize_checkbutton_changed() } else { prefs->setDouble("/dialogs/gridtiler/AutoRowSize", -20); } - RowHeightBox.set_sensitive ( !RowHeightButton.get_active()); + RowHeightBox.set_sensitive(!RowHeightButton.get_active()); } /** @@ -439,7 +426,7 @@ void GridArrangeTab::on_ColSize_checkbutton_changed() } else { prefs->setDouble("/dialogs/gridtiler/AutoColSize", -20); } - ColumnWidthBox.set_sensitive ( !ColumnWidthButton.get_active()); + ColumnWidthBox.set_sensitive(!ColumnWidthButton.get_active()); } /** @@ -449,15 +436,14 @@ void GridArrangeTab::on_rowSize_spinbutton_changed() { // quit if run by the attr_changed listener if (updating) { - return; - } + return; + } // in turn, prevent listener from responding updating = true; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble("/dialogs/gridtiler/RowHeight", RowHeightSpinner.get_value()); - updating=false; - + updating = false; } /** @@ -467,15 +453,14 @@ void GridArrangeTab::on_colSize_spinbutton_changed() { // quit if run by the attr_changed listener if (updating) { - return; - } + return; + } // in turn, prevent listener from responding updating = true; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble("/dialogs/gridtiler/ColWidth", ColumnWidthSpinner.get_value()); - updating=false; - + updating = false; } /** @@ -490,8 +475,8 @@ void GridArrangeTab::Spacing_button_changed() prefs->setDouble("/dialogs/gridtiler/SpacingType", -20); } - XPadding.set_sensitive ( SpaceManualRadioButton.get_active()); - YPadding.set_sensitive ( SpaceManualRadioButton.get_active()); + XPadding.set_sensitive(SpaceManualRadioButton.get_active()); + YPadding.set_sensitive(SpaceManualRadioButton.get_active()); } /** @@ -521,7 +506,7 @@ void GridArrangeTab::updateSelection() updating = true; SPDesktop *desktop = Parent->getDesktop(); Inkscape::Selection *selection = desktop ? desktop->selection : nullptr; - std::vector<SPItem*> items; + std::vector<SPItem *> items; if (selection) { items.insert(items.end(), selection->items().begin(), selection->items().end()); } @@ -529,7 +514,7 @@ void GridArrangeTab::updateSelection() if (!items.empty()) { int selcount = items.size(); - if (NoOfColsSpinner.get_value() > 1 && NoOfRowsSpinner.get_value() > 1){ + if (NoOfColsSpinner.get_value() > 1 && NoOfRowsSpinner.get_value() > 1) { // Update the number of rows assuming number of columns wanted remains same. double NoOfRows = ceil(selcount / NoOfColsSpinner.get_value()); NoOfRowsSpinner.set_value(NoOfRows); @@ -564,7 +549,6 @@ void GridArrangeTab::setDesktop(SPDesktop *desktop) } } - //######################################################################### //## C O N S T R U C T O R / D E S T R U C T O R //######################################################################### @@ -572,12 +556,13 @@ void GridArrangeTab::setDesktop(SPDesktop *desktop) * Constructor */ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) - : Parent(parent), - XPadding(_("X:"), _("Horizontal spacing between columns."), UNIT_TYPE_LINEAR, "", "object-columns", &PaddingUnitMenu), - YPadding(_("Y:"), _("Vertical spacing between rows."), XPadding, "", "object-rows"), - PaddingTable(Gtk::manage(new Gtk::Grid())) + : Parent(parent) + , XPadding(_("X:"), _("Horizontal spacing between columns."), UNIT_TYPE_LINEAR, "", "object-columns", + &PaddingUnitMenu) + , YPadding(_("Y:"), _("Vertical spacing between rows."), XPadding, "", "object-rows") + , PaddingTable(Gtk::manage(new Gtk::Grid())) { - // bool used by spin button callbacks to stop loops where they change each other. + // bool used by spin button callbacks to stop loops where they change each other. updating = false; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -607,10 +592,10 @@ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) RowHeightButton.set_label(_("Equal _height")); RowHeightButton.set_use_underline(true); double AutoRow = prefs->getDouble("/dialogs/gridtiler/AutoRowSize", 15); - if (AutoRow>0) - AutoRowSize=true; + if (AutoRow > 0) + AutoRowSize = true; else - AutoRowSize=false; + AutoRowSize = false; RowHeightButton.set_active(AutoRowSize); NoOfRowsBox.pack_start(RowHeightButton, false, false, MARGIN); @@ -620,7 +605,6 @@ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) SpinsHBox.pack_start(NoOfRowsBox, false, false, MARGIN); - /*#### Label for X ####*/ padXByYLabel.set_label(" "); XByYLabelVBox.set_orientation(Gtk::ORIENTATION_VERTICAL); @@ -648,10 +632,10 @@ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) ColumnWidthButton.set_label(_("Equal _width")); ColumnWidthButton.set_use_underline(true); double AutoCol = prefs->getDouble("/dialogs/gridtiler/AutoColSize", 15); - if (AutoCol>0) - AutoColSize=true; + if (AutoCol > 0) + AutoColSize = true; else - AutoColSize=false; + AutoColSize = false; ColumnWidthButton.set_active(AutoColSize); NoOfColsBox.pack_start(ColumnWidthButton, false, false, MARGIN); @@ -678,14 +662,14 @@ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) { /*#### Radio buttons to control spacing manually or to fit selection bbox ####*/ SpaceByBBoxRadioButton.set_label(_("_Fit into selection box")); - SpaceByBBoxRadioButton.set_use_underline (true); + SpaceByBBoxRadioButton.set_use_underline(true); SpaceByBBoxRadioButton.signal_toggled().connect(sigc::mem_fun(*this, &GridArrangeTab::Spacing_button_changed)); SpacingGroup = SpaceByBBoxRadioButton.get_group(); SpacingVBox.pack_start(SpaceByBBoxRadioButton, false, false, MARGIN); SpaceManualRadioButton.set_label(_("_Set spacing:")); - SpaceManualRadioButton.set_use_underline (true); + SpaceManualRadioButton.set_use_underline(true); SpaceManualRadioButton.set_group(SpacingGroup); SpaceManualRadioButton.signal_toggled().connect(sigc::mem_fun(*this, &GridArrangeTab::Spacing_button_changed)); SpacingVBox.pack_start(SpaceManualRadioButton, false, false, MARGIN); @@ -717,9 +701,9 @@ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) PaddingTable->set_border_width(MARGIN); PaddingTable->set_row_spacing(MARGIN); PaddingTable->set_column_spacing(MARGIN); - PaddingTable->attach(XPadding, 0, 0, 1, 1); + PaddingTable->attach(XPadding, 0, 0, 1, 1); PaddingTable->attach(PaddingUnitMenu, 1, 0, 1, 1); - PaddingTable->attach(YPadding, 0, 1, 1, 1); + PaddingTable->attach(YPadding, 0, 1, 1, 1); TileBox.pack_start(*PaddingTable, false, false, MARGIN); @@ -727,22 +711,22 @@ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) contents->pack_start(TileBox); double SpacingType = prefs->getDouble("/dialogs/gridtiler/SpacingType", 15); - if (SpacingType>0) { - ManualSpacing=true; + if (SpacingType > 0) { + ManualSpacing = true; } else { - ManualSpacing=false; + ManualSpacing = false; } SpaceManualRadioButton.set_active(ManualSpacing); SpaceByBBoxRadioButton.set_active(!ManualSpacing); - XPadding.set_sensitive (ManualSpacing); - YPadding.set_sensitive (ManualSpacing); + XPadding.set_sensitive(ManualSpacing); + YPadding.set_sensitive(ManualSpacing); show_all_children(); } -} //namespace Dialog -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/grid-arrange-tab.h b/src/ui/dialog/grid-arrange-tab.h index bb7719e0920d8efbd99c1dd2fb04d5d19d40d0c3..edda32fed3d170250ffc285a8d0d624222bb769b 100644 --- a/src/ui/dialog/grid-arrange-tab.h +++ b/src/ui/dialog/grid-arrange-tab.h @@ -18,16 +18,15 @@ #ifndef INKSCAPE_UI_DIALOG_GRID_ARRANGE_TAB_H #define INKSCAPE_UI_DIALOG_GRID_ARRANGE_TAB_H -#include "ui/widget/scalar-unit.h" -#include "ui/dialog/arrange-tab.h" - -#include "ui/widget/anchor-selector.h" -#include "ui/widget/spinbutton.h" - #include <gtkmm/checkbutton.h> #include <gtkmm/radiobutton.h> #include <gtkmm/radiobuttongroup.h> +#include "ui/dialog/arrange-tab.h" +#include "ui/widget/anchor-selector.h" +#include "ui/widget/scalar-unit.h" +#include "ui/widget/spinbutton.h" + class SPDesktop; namespace Inkscape { @@ -39,10 +38,12 @@ class ArrangeDialog; /** * Dialog for tiling an object */ -class GridArrangeTab : public ArrangeTab { +class GridArrangeTab : public ArrangeTab +{ public: GridArrangeTab(ArrangeDialog *parent); - ~GridArrangeTab() override = default;; + ~GridArrangeTab() override = default; + ; /** * Do the actual work @@ -66,77 +67,75 @@ public: void Spacing_button_changed(); void Align_changed(); - private: GridArrangeTab(GridArrangeTab const &d) = delete; // no copy void operator=(GridArrangeTab const &d) = delete; // no assign - ArrangeDialog *Parent; + ArrangeDialog *Parent; bool updating; - Gtk::Box TileBox; + Gtk::Box TileBox; // Number selected label - Gtk::Label SelectionContentsLabel; - + Gtk::Label SelectionContentsLabel; - Gtk::Box AlignHBox; - Gtk::Box SpinsHBox; + Gtk::Box AlignHBox; + Gtk::Box SpinsHBox; // Number per Row - Gtk::Box NoOfColsBox; - Gtk::Label NoOfColsLabel; + Gtk::Box NoOfColsBox; + Gtk::Label NoOfColsLabel; Inkscape::UI::Widget::SpinButton NoOfColsSpinner; bool AutoRowSize; - Gtk::CheckButton RowHeightButton; + Gtk::CheckButton RowHeightButton; - Gtk::Box XByYLabelVBox; - Gtk::Label padXByYLabel; - Gtk::Label XByYLabel; + Gtk::Box XByYLabelVBox; + Gtk::Label padXByYLabel; + Gtk::Label XByYLabel; // Number per Column - Gtk::Box NoOfRowsBox; - Gtk::Label NoOfRowsLabel; + Gtk::Box NoOfRowsBox; + Gtk::Label NoOfRowsLabel; Inkscape::UI::Widget::SpinButton NoOfRowsSpinner; bool AutoColSize; - Gtk::CheckButton ColumnWidthButton; + Gtk::CheckButton ColumnWidthButton; // Alignment - Gtk::Label AlignLabel; - Inkscape::UI::Widget::AnchorSelector AlignmentSelector; + Gtk::Label AlignLabel; + Inkscape::UI::Widget::AnchorSelector AlignmentSelector; double VertAlign; double HorizAlign; - Inkscape::UI::Widget::UnitMenu PaddingUnitMenu; - Inkscape::UI::Widget::ScalarUnit XPadding; - Inkscape::UI::Widget::ScalarUnit YPadding; - Gtk::Grid *PaddingTable; + Inkscape::UI::Widget::UnitMenu PaddingUnitMenu; + Inkscape::UI::Widget::ScalarUnit XPadding; + Inkscape::UI::Widget::ScalarUnit YPadding; + Gtk::Grid *PaddingTable; // BBox or manual spacing - Gtk::VBox SpacingVBox; + Gtk::VBox SpacingVBox; Gtk::RadioButtonGroup SpacingGroup; - Gtk::RadioButton SpaceByBBoxRadioButton; - Gtk::RadioButton SpaceManualRadioButton; + Gtk::RadioButton SpaceByBBoxRadioButton; + Gtk::RadioButton SpaceManualRadioButton; bool ManualSpacing; // Row height - Gtk::Box RowHeightBox; + Gtk::Box RowHeightBox; Inkscape::UI::Widget::SpinButton RowHeightSpinner; // Column width - Gtk::Box ColumnWidthBox; + Gtk::Box ColumnWidthBox; Inkscape::UI::Widget::SpinButton ColumnWidthSpinner; sigc::connection _selection_changed_connection; - public: +public: void setDesktop(SPDesktop *); }; -} //namespace Dialog -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif /* INKSCAPE_UI_DIALOG_GRID_ARRANGE_TAB_H */ diff --git a/src/ui/dialog/guides.cpp b/src/ui/dialog/guides.cpp index 0f065d566e867a8b217c00c1a11477187e2d5ab3..f6c9cc5812a8c7ac30e334e37728e4fd4973ccbb 100644 --- a/src/ui/dialog/guides.cpp +++ b/src/ui/dialog/guides.cpp @@ -19,22 +19,17 @@ #include <glibmm/i18n.h> #include "desktop.h" +#include "display/guideline.h" #include "document-undo.h" #include "document.h" -#include "message-context.h" -#include "verbs.h" - #include "include/gtkmm_version.h" - +#include "message-context.h" #include "object/sp-guide.h" #include "object/sp-namedview.h" - -#include "display/guideline.h" - #include "ui/dialog-events.h" #include "ui/tools/tool-base.h" #include "ui/widget/spinbutton.h" - +#include "verbs.h" #include "widgets/desktop-widget.h" namespace Inkscape { @@ -42,14 +37,17 @@ namespace UI { namespace Dialogs { GuidelinePropertiesDialog::GuidelinePropertiesDialog(SPGuide *guide, SPDesktop *desktop) -: _desktop(desktop), _guide(guide), - _locked_toggle(_("Lo_cked")), - _relative_toggle(_("Rela_tive change")), - _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) + : _desktop(desktop) + , _guide(guide) + , _locked_toggle(_("Lo_cked")) + , _relative_toggle(_("Rela_tive change")) + , _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) { _locked_toggle.set_use_underline(); _locked_toggle.set_tooltip_text(_("Lock the movement of guides")); @@ -57,16 +55,19 @@ GuidelinePropertiesDialog::GuidelinePropertiesDialog(SPGuide *guide, SPDesktop * _relative_toggle.set_tooltip_text(_("Move and/or rotate the guide relative to current settings")); } -bool GuidelinePropertiesDialog::_relative_toggle_status = false; // initialize relative checkbox status for when this dialog is opened for first time +bool GuidelinePropertiesDialog::_relative_toggle_status = + false; // initialize relative checkbox status for when this dialog is opened for first time Glib::ustring GuidelinePropertiesDialog::_angle_unit_status = DEG; // initialize angle unit status -GuidelinePropertiesDialog::~GuidelinePropertiesDialog() { +GuidelinePropertiesDialog::~GuidelinePropertiesDialog() +{ // save current status _relative_toggle_status = _relative_toggle.get_active(); _angle_unit_status = _spin_angle.getUnit()->abbr; } -void GuidelinePropertiesDialog::showDialog(SPGuide *guide, SPDesktop *desktop) { +void GuidelinePropertiesDialog::showDialog(SPGuide *guide, SPDesktop *desktop) +{ GuidelinePropertiesDialog dialog(guide, desktop); dialog._setup(); dialog.run(); @@ -93,9 +94,7 @@ void GuidelinePropertiesDialog::_modeChanged() void GuidelinePropertiesDialog::_onOK() { this->_onOKimpl(); - DocumentUndo::done(_guide->document, SP_VERB_NONE, - _("Set guide properties")); - + DocumentUndo::done(_guide->document, SP_VERB_NONE, _("Set guide properties")); } void GuidelinePropertiesDialog::_onOKimpl() @@ -104,15 +103,15 @@ void GuidelinePropertiesDialog::_onOKimpl() if (!_mode) deg_angle += _oldangle; Geom::Point normal; - if ( deg_angle == 90. || deg_angle == 270. || deg_angle == -90. || deg_angle == -270.) { - normal = Geom::Point(1.,0.); - } else if ( deg_angle == 0. || deg_angle == 180. || deg_angle == -180.) { - normal = Geom::Point(0.,1.); + if (deg_angle == 90. || deg_angle == 270. || deg_angle == -90. || deg_angle == -270.) { + normal = Geom::Point(1., 0.); + } else if (deg_angle == 0. || deg_angle == 180. || deg_angle == -180.) { + normal = Geom::Point(0., 1.); } else { - double rad_angle = Geom::rad_from_deg( deg_angle ); + double rad_angle = Geom::rad_from_deg(deg_angle); normal = Geom::rot90(Geom::Point::polar(rad_angle, 1.0)); } - //To allow reposition from dialog + // To allow reposition from dialog _guide->set_locked(false, false); _guide->set_normal(normal, true); @@ -125,19 +124,19 @@ void GuidelinePropertiesDialog::_onOKimpl() _guide->moveto(newpos, true); - const gchar* name = g_strdup( _label_entry.getEntry()->get_text().c_str() ); + const gchar *name = g_strdup(_label_entry.getEntry()->get_text().c_str()); _guide->set_label(name, true); - + const bool locked = _locked_toggle.get_active(); _guide->set_locked(locked, true); - - g_free((gpointer) name); + + g_free((gpointer)name); const auto c = _color.get_rgba(); - unsigned r = c.get_red_u()/257, g = c.get_green_u()/257, b = c.get_blue_u()/257; - //TODO: why 257? verify this! + unsigned r = c.get_red_u() / 257, g = c.get_green_u() / 257, b = c.get_blue_u() / 257; + // TODO: why 257? verify this! // don't know why, but introduced: 761f7da58cd6d625b88c24eee6fae1b7fa3bfcdd _guide->set_color(r, g, b, true); @@ -147,8 +146,7 @@ void GuidelinePropertiesDialog::_onDelete() { SPDocument *doc = _guide->document; sp_guide_remove(_guide); - DocumentUndo::done(doc, SP_VERB_NONE, - _("Delete guide")); + DocumentUndo::done(doc, SP_VERB_NONE, _("Delete guide")); } void GuidelinePropertiesDialog::_onDuplicate() @@ -161,25 +159,26 @@ void GuidelinePropertiesDialog::_onDuplicate() void GuidelinePropertiesDialog::_response(gint response) { switch (response) { - case Gtk::RESPONSE_OK: + case Gtk::RESPONSE_OK: _onOK(); break; - case -12: + case -12: _onDelete(); break; - case -13: + case -13: _onDuplicate(); break; - case Gtk::RESPONSE_CANCEL: + case Gtk::RESPONSE_CANCEL: break; - case Gtk::RESPONSE_DELETE_EVENT: + case Gtk::RESPONSE_DELETE_EVENT: break; - default: + default: g_assert_not_reached(); } } -void GuidelinePropertiesDialog::_setup() { +void GuidelinePropertiesDialog::_setup() +{ set_title(_("Guideline")); add_button(_("_OK"), Gtk::RESPONSE_OK); add_button(_("_Duplicate"), -13); @@ -200,7 +199,7 @@ void GuidelinePropertiesDialog::_setup() { _label_descr.set_label("foo1"); _label_descr.set_halign(Gtk::ALIGN_START); _label_descr.set_valign(Gtk::ALIGN_CENTER); - + _label_name.set_halign(Gtk::ALIGN_FILL); _label_name.set_valign(Gtk::ALIGN_FILL); _layout_table.attach(_label_name, 0, 0, 3, 1); @@ -225,7 +224,7 @@ void GuidelinePropertiesDialog::_setup() { _unit_menu.setUnitType(UNIT_TYPE_LINEAR); _unit_menu.setUnit("px"); if (_desktop->namedview->display_units) { - _unit_menu.setUnit( _desktop->namedview->display_units->abbr ); + _unit_menu.setUnit(_desktop->namedview->display_units->abbr); } _spin_angle.setUnit(_angle_unit_status); @@ -241,7 +240,7 @@ void GuidelinePropertiesDialog::_setup() { _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(); @@ -280,19 +279,23 @@ void GuidelinePropertiesDialog::_setup() { _relative_toggle.set_active(_relative_toggle_status); bool global_guides_lock = _desktop->namedview->lockguides; - if(global_guides_lock){ + if (global_guides_lock) { _locked_toggle.set_sensitive(false); } _locked_toggle.set_active(_guide->getLocked()); - // This results in the dialog closing when entering a value in one of the spinbuttons and pressing enter (see LP bug 484187) + // This results in the dialog closing when entering a value in one of the spinbuttons and pressing enter (see LP bug + // 484187) auto sbx = dynamic_cast<UI::Widget::SpinButton *>(_spin_button_x.getWidget()); auto sby = dynamic_cast<UI::Widget::SpinButton *>(_spin_button_y.getWidget()); auto sba = dynamic_cast<UI::Widget::SpinButton *>(_spin_button_y.getWidget()); - if(sbx) sbx->signal_activate().connect(sigc::mem_fun(this, &GuidelinePropertiesDialog::on_sb_activate)); - if(sby) sby->signal_activate().connect(sigc::mem_fun(this, &GuidelinePropertiesDialog::on_sb_activate)); - if(sba) sba->signal_activate().connect(sigc::mem_fun(this, &GuidelinePropertiesDialog::on_sb_activate)); + if (sbx) + sbx->signal_activate().connect(sigc::mem_fun(this, &GuidelinePropertiesDialog::on_sb_activate)); + if (sby) + sby->signal_activate().connect(sigc::mem_fun(this, &GuidelinePropertiesDialog::on_sb_activate)); + if (sba) + sba->signal_activate().connect(sigc::mem_fun(this, &GuidelinePropertiesDialog::on_sb_activate)); // dialog set_default_response(Gtk::RESPONSE_OK); @@ -305,7 +308,7 @@ void GuidelinePropertiesDialog::_setup() { } else if (_guide->isHorizontal()) { _oldangle = 0; } else { - _oldangle = Geom::deg_from_rad( std::atan2( - _guide->getNormal()[Geom::X], _guide->getNormal()[Geom::Y] ) ); + _oldangle = Geom::deg_from_rad(std::atan2(-_guide->getNormal()[Geom::X], _guide->getNormal()[Geom::Y])); } { @@ -328,14 +331,15 @@ void GuidelinePropertiesDialog::_setup() { _label_entry.getEntry()->set_text(_guide->getLabel() ? _guide->getLabel() : ""); Gdk::RGBA c; - c.set_rgba(((_guide->getColor()>>24)&0xff) / 255.0, ((_guide->getColor()>>16)&0xff) / 255.0, ((_guide->getColor()>>8)&0xff) / 255.0); + c.set_rgba(((_guide->getColor() >> 24) & 0xff) / 255.0, ((_guide->getColor() >> 16) & 0xff) / 255.0, + ((_guide->getColor() >> 8) & 0xff) / 255.0); _color.set_rgba(c); _modeChanged(); // sets values of spinboxes. - if ( _oldangle == 90. || _oldangle == 270. || _oldangle == -90. || _oldangle == -270.) { + if (_oldangle == 90. || _oldangle == 270. || _oldangle == -90. || _oldangle == -270.) { _spin_button_x.grabFocusAndSelectEntry(); - } else if ( _oldangle == 0. || _oldangle == 180. || _oldangle == -180.) { + } else if (_oldangle == 0. || _oldangle == 180. || _oldangle == -180.) { _spin_button_y.grabFocusAndSelectEntry(); } else { _spin_angle.grabFocusAndSelectEntry(); @@ -345,18 +349,17 @@ void GuidelinePropertiesDialog::_setup() { show_all_children(); set_modal(true); - _desktop->setWindowTransient (gobj()); + _desktop->setWindowTransient(gobj()); property_destroy_with_parent() = true; } -void -GuidelinePropertiesDialog::on_sb_activate() +void GuidelinePropertiesDialog::on_sb_activate() { activate_default(); } -} -} -} +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/guides.h b/src/ui/dialog/guides.h index 9c449ce57c2509a39bfed4b26afa8ba7933d1604..f3fc15de2c3f65c2e78ef936a2919983aa0da36f 100644 --- a/src/ui/dialog/guides.h +++ b/src/ui/dialog/guides.h @@ -12,16 +12,16 @@ #ifndef INKSCAPE_DIALOG_GUIDELINE_H #define INKSCAPE_DIALOG_GUIDELINE_H +#include <2geom/point.h> #include <gtkmm/checkbutton.h> #include <gtkmm/colorbutton.h> #include <gtkmm/dialog.h> #include <gtkmm/grid.h> #include <gtkmm/label.h> -#include "ui/widget/unit-menu.h" -#include "ui/widget/scalar-unit.h" #include "ui/widget/entry.h" -#include <2geom/point.h> +#include "ui/widget/scalar-unit.h" +#include "ui/widget/unit-menu.h" class SPGuide; class SPDesktop; @@ -30,7 +30,7 @@ namespace Inkscape { namespace UI { namespace Widget { - class UnitMenu; +class UnitMenu; }; namespace Dialogs { @@ -38,12 +38,13 @@ namespace Dialogs { /** * Dialog for modifying guidelines. */ -class GuidelinePropertiesDialog : public Gtk::Dialog { +class GuidelinePropertiesDialog : public Gtk::Dialog +{ public: GuidelinePropertiesDialog(SPGuide *guide, SPDesktop *desktop); ~GuidelinePropertiesDialog() override; - Glib::ustring getName() const { return "GuidelinePropertiesDialog"; } + Glib::ustring getName() const { return "GuidelinePropertiesDialog"; } static void showDialog(SPGuide *guide, SPDesktop *desktop); @@ -59,15 +60,15 @@ protected: void _modeChanged(); private: - GuidelinePropertiesDialog(GuidelinePropertiesDialog const &) = delete; // no copy + GuidelinePropertiesDialog(GuidelinePropertiesDialog const &) = delete; // no copy GuidelinePropertiesDialog &operator=(GuidelinePropertiesDialog const &) = delete; // no assign SPDesktop *_desktop; SPGuide *_guide; - Gtk::Grid _layout_table; - Gtk::Label _label_name; - Gtk::Label _label_descr; + Gtk::Grid _layout_table; + Gtk::Label _label_name; + Gtk::Label _label_descr; Gtk::CheckButton _locked_toggle; Gtk::CheckButton _relative_toggle; static bool _relative_toggle_status; // remember the status of the _relative_toggle_status button across instances @@ -78,7 +79,8 @@ private: Gtk::ColorButton _color; Inkscape::UI::Widget::ScalarUnit _spin_angle; - static Glib::ustring _angle_unit_status; // remember the status of the _relative_toggle_status button across instances + static Glib::ustring _angle_unit_status; // remember the status of the _relative_toggle_status button across + // instances bool _mode; Geom::Point _oldpos; @@ -87,10 +89,9 @@ private: void on_sb_activate(); }; -} // namespace -} // namespace -} // namespace - +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape #endif // INKSCAPE_DIALOG_GUIDELINE_H diff --git a/src/ui/dialog/icon-preview.cpp b/src/ui/dialog/icon-preview.cpp index 4d81796cc83d70edfb390b2787d5a65b22eeb822..6347ea678da5f1322ecf9e30720f83a0b6cee040 100644 --- a/src/ui/dialog/icon-preview.cpp +++ b/src/ui/dialog/icon-preview.cpp @@ -15,35 +15,30 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "icon-preview.h" + #include <glibmm/i18n.h> -#include <glibmm/timer.h> #include <glibmm/main.h> - +#include <glibmm/timer.h> #include <gtkmm/buttonbox.h> #include <gtkmm/checkbutton.h> #include <gtkmm/frame.h> #include "desktop.h" -#include "document.h" -#include "inkscape.h" -#include "verbs.h" - #include "display/cairo-utils.h" -#include "display/drawing.h" #include "display/drawing-context.h" - +#include "display/drawing.h" +#include "document.h" +#include "inkscape.h" #include "object/sp-namedview.h" #include "object/sp-root.h" - -#include "icon-preview.h" - #include "ui/widget/frame.h" +#include "verbs.h" extern "C" { // takes doc, drawing, icon, and icon name to produce pixels -guchar * -sp_icon_doc_icon( SPDocument *doc, Inkscape::Drawing &drawing, - const gchar *name, unsigned int psize, unsigned &stride); +guchar *sp_icon_doc_icon(SPDocument *doc, Inkscape::Drawing &drawing, const gchar *name, unsigned int psize, + unsigned &stride); } #define noICON_VERBOSE 1 @@ -52,7 +47,6 @@ namespace Inkscape { namespace UI { namespace Dialog { - IconPreviewPanel &IconPreviewPanel::getInstance() { IconPreviewPanel *instance = new IconPreviewPanel(); @@ -68,8 +62,8 @@ IconPreviewPanel &IconPreviewPanel::getInstance() void IconPreviewPanel::on_button_clicked(int which) { - if ( hot != which ) { - buttons[hot]->set_active( false ); + if (hot != which) { + buttons[hot]->set_active(false); hot = which; updateMagnify(); @@ -77,31 +71,28 @@ void IconPreviewPanel::on_button_clicked(int which) } } - - - //######################################################################### //## C O N S T R U C T O R / D E S T R U C T O R //######################################################################### /** * Constructor */ -IconPreviewPanel::IconPreviewPanel() : - UI::Widget::Panel("/dialogs/iconpreview", SP_VERB_VIEW_ICON_PREVIEW), - desktop(nullptr), - document(nullptr), - drawing(nullptr), - visionkey(0), - timer(nullptr), - renderTimer(nullptr), - pending(false), - minDelay(0.1), - targetId(), - hot(1), - selectionButton(nullptr), - docReplacedConn(), - docModConn(), - selChangedConn() +IconPreviewPanel::IconPreviewPanel() + : UI::Widget::Panel("/dialogs/iconpreview", SP_VERB_VIEW_ICON_PREVIEW) + , desktop(nullptr) + , document(nullptr) + , drawing(nullptr) + , visionkey(0) + , timer(nullptr) + , renderTimer(nullptr) + , pending(false) + , minDelay(0.1) + , targetId() + , hot(1) + , selectionButton(nullptr) + , docReplacedConn() + , docModConn() + , selChangedConn() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); numEntries = 0; @@ -111,7 +102,7 @@ IconPreviewPanel::IconPreviewPanel() : std::vector<Glib::ustring> pref_sizes = prefs->getAllDirs("/iconpreview/sizes/default"); std::vector<int> rawSizes; - for (auto & pref_size : pref_sizes) { + for (auto &pref_size : pref_sizes) { if (prefs->getBool(pref_size + "/show", true)) { int sizeVal = prefs->getInt(pref_size + "/value", -1); if (sizeVal > 0) { @@ -120,17 +111,16 @@ IconPreviewPanel::IconPreviewPanel() : } } - if ( !rawSizes.empty() ) { + if (!rawSizes.empty()) { numEntries = rawSizes.size(); sizes = new int[numEntries]; int i = 0; - for ( std::vector<int>::iterator it = rawSizes.begin(); it != rawSizes.end(); ++it, ++i ) { + for (std::vector<int>::iterator it = rawSizes.begin(); it != rawSizes.end(); ++it, ++i) { sizes[i] = *it; } } - if ( numEntries < 1 ) - { + if (numEntries < 1) { numEntries = 5; sizes = new int[numEntries]; sizes[0] = 16; @@ -140,13 +130,12 @@ IconPreviewPanel::IconPreviewPanel() : sizes[4] = 128; } - pixMem = new guchar*[numEntries]; - images = new Gtk::Image*[numEntries]; - labels = new Glib::ustring*[numEntries]; - buttons = new Gtk::ToggleToolButton*[numEntries]; + pixMem = new guchar *[numEntries]; + images = new Gtk::Image *[numEntries]; + labels = new Glib::ustring *[numEntries]; + buttons = new Gtk::ToggleToolButton *[numEntries]; - - for ( int i = 0; i < numEntries; i++ ) { + for (int i = 0; i < numEntries; i++) { char *label = g_strdup_printf(_("%d x %d"), sizes[i], sizes[i]); labels[i] = new Glib::ustring(label); g_free(label); @@ -154,33 +143,31 @@ IconPreviewPanel::IconPreviewPanel() : images[i] = nullptr; } + magLabel.set_label(*labels[hot]); - magLabel.set_label( *labels[hot] ); - - Gtk::VBox* magBox = new Gtk::VBox(); + Gtk::VBox *magBox = new Gtk::VBox(); UI::Widget::Frame *magFrame = Gtk::manage(new UI::Widget::Frame(_("Magnified:"))); - magFrame->add( magnified ); - - magBox->pack_start( *magFrame, Gtk::PACK_EXPAND_WIDGET ); - magBox->pack_start( magLabel, Gtk::PACK_SHRINK ); + magFrame->add(magnified); + magBox->pack_start(*magFrame, Gtk::PACK_EXPAND_WIDGET); + magBox->pack_start(magLabel, Gtk::PACK_SHRINK); Gtk::VBox *verts = new Gtk::VBox(); Gtk::HBox *horiz = nullptr; int previous = 0; int avail = 0; - for ( int i = numEntries - 1; i >= 0; --i ) { + for (int i = numEntries - 1; i >= 0; --i) { int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, sizes[i]); pixMem[i] = new guchar[sizes[i] * stride]; - memset( pixMem[i], 0x00, sizes[i] * stride ); + memset(pixMem[i], 0x00, sizes[i] * stride); auto pb = Gdk::Pixbuf::create_from_data(pixMem[i], Gdk::COLORSPACE_RGB, true, 8, sizes[i], sizes[i], stride); images[i] = Gtk::make_managed<Gtk::Image>(pb); Glib::ustring label(*labels[i]); buttons[i] = new Gtk::ToggleToolButton(label); - buttons[i]->set_active( i == hot ); - if ( prefs->getBool("/iconpreview/showFrames", true) ) { + buttons[i]->set_active(i == hot); + if (prefs->getBool("/iconpreview/showFrames", true)) { Gtk::Frame *frame = new Gtk::Frame(); frame->set_shadow_type(Gtk::SHADOW_ETCHED_IN); frame->add(*images[i]); @@ -191,12 +178,13 @@ IconPreviewPanel::IconPreviewPanel() : buttons[i]->set_tooltip_text(label); - buttons[i]->signal_clicked().connect( sigc::bind<int>( sigc::mem_fun(*this, &IconPreviewPanel::on_button_clicked), i) ); + buttons[i]->signal_clicked().connect( + sigc::bind<int>(sigc::mem_fun(*this, &IconPreviewPanel::on_button_clicked), i)); buttons[i]->set_halign(Gtk::ALIGN_CENTER); buttons[i]->set_valign(Gtk::ALIGN_CENTER); - if ( !pack || ( (avail == 0) && (previous == 0) ) ) { + if (!pack || ((avail == 0) && (previous == 0))) { verts->pack_end(*(buttons[i]), Gtk::PACK_SHRINK); previous = sizes[i]; avail = sizes[i]; @@ -225,26 +213,26 @@ IconPreviewPanel::IconPreviewPanel() : } iconBox.pack_start(splitter); - splitter.pack1( *magBox, true, false ); - UI::Widget::Frame *actuals = Gtk::manage(new UI::Widget::Frame (_("Actual Size:"))); + splitter.pack1(*magBox, true, false); + UI::Widget::Frame *actuals = Gtk::manage(new UI::Widget::Frame(_("Actual Size:"))); actuals->set_border_width(4); actuals->add(*verts); - splitter.pack2( *actuals, false, false ); - + splitter.pack2(*actuals, false, false); - selectionButton = new Gtk::CheckButton(C_("Icon preview window", "Sele_ction"), true);//selectionButton = (Gtk::ToggleButton*) gtk_check_button_new_with_mnemonic(_("_Selection")); // , GTK_RESPONSE_APPLY - magBox->pack_start( *selectionButton, Gtk::PACK_SHRINK ); + selectionButton = + new Gtk::CheckButton(C_("Icon preview window", "Sele_ction"), + true); // selectionButton = (Gtk::ToggleButton*) + // gtk_check_button_new_with_mnemonic(_("_Selection")); // , GTK_RESPONSE_APPLY + magBox->pack_start(*selectionButton, Gtk::PACK_SHRINK); selectionButton->set_tooltip_text(_("Selection only or whole document")); - selectionButton->signal_clicked().connect( sigc::mem_fun(*this, &IconPreviewPanel::modeToggled) ); + selectionButton->signal_clicked().connect(sigc::mem_fun(*this, &IconPreviewPanel::modeToggled)); gint val = prefs->getBool("/iconpreview/selectionOnly"); - selectionButton->set_active( val != 0 ); - + selectionButton->set_active(val != 0); _getContents()->pack_start(iconBox, Gtk::PACK_SHRINK); show_all_children(); - } IconPreviewPanel::~IconPreviewPanel() @@ -255,7 +243,7 @@ IconPreviewPanel::~IconPreviewPanel() delete timer; timer = nullptr; } - if ( renderTimer ) { + if (renderTimer) { renderTimer->stop(); delete renderTimer; renderTimer = nullptr; @@ -270,7 +258,6 @@ IconPreviewPanel::~IconPreviewPanel() //## M E T H O D S //######################################################################### - #if ICON_VERBOSE static Glib::ustring getTimestr() { @@ -286,28 +273,30 @@ static Glib::ustring getTimestr() } #endif // ICON_VERBOSE -void IconPreviewPanel::setDesktop( SPDesktop* desktop ) +void IconPreviewPanel::setDesktop(SPDesktop *desktop) { Panel::setDesktop(desktop); SPDocument *newDoc = (desktop) ? desktop->doc() : nullptr; - if ( desktop != this->desktop ) { + if (desktop != this->desktop) { docReplacedConn.disconnect(); selChangedConn.disconnect(); this->desktop = Panel::getDesktop(); - if ( this->desktop ) { - docReplacedConn = this->desktop->connectDocumentReplaced(sigc::hide<0>(sigc::mem_fun(this, &IconPreviewPanel::setDocument))); - if ( this->desktop->selection && Inkscape::Preferences::get()->getBool("/iconpreview/autoRefresh", true) ) { - selChangedConn = this->desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(this, &IconPreviewPanel::queueRefresh))); + if (this->desktop) { + docReplacedConn = this->desktop->connectDocumentReplaced( + sigc::hide<0>(sigc::mem_fun(this, &IconPreviewPanel::setDocument))); + if (this->desktop->selection && Inkscape::Preferences::get()->getBool("/iconpreview/autoRefresh", true)) { + selChangedConn = this->desktop->selection->connectChanged( + sigc::hide(sigc::mem_fun(this, &IconPreviewPanel::queueRefresh))); } } } setDocument(newDoc); } -void IconPreviewPanel::setDocument( SPDocument *document ) +void IconPreviewPanel::setDocument(SPDocument *document) { if (this->document != document) { docModConn.disconnect(); @@ -322,8 +311,9 @@ void IconPreviewPanel::setDocument( SPDocument *document ) visionkey = SPItem::display_key_new(1); drawing->setRoot(this->document->getRoot()->invoke_show(*drawing, visionkey, SP_ITEM_SHOW_DISPLAY)); - if ( Inkscape::Preferences::get()->getBool("/iconpreview/autoRefresh", true) ) { - docModConn = this->document->connectModified(sigc::hide(sigc::mem_fun(this, &IconPreviewPanel::queueRefresh))); + if (Inkscape::Preferences::get()->getBool("/iconpreview/autoRefresh", true)) { + docModConn = + this->document->connectModified(sigc::hide(sigc::mem_fun(this, &IconPreviewPanel::queueRefresh))); } queueRefresh(); } @@ -338,30 +328,29 @@ void IconPreviewPanel::refreshPreview() } if (timer->elapsed() < minDelay) { #if ICON_VERBOSE - g_message( "%s Deferring refresh as too soon. calling queueRefresh()", getTimestr().c_str() ); -#endif //ICON_VERBOSE - // Do not refresh too quickly + g_message("%s Deferring refresh as too soon. calling queueRefresh()", getTimestr().c_str()); +#endif // ICON_VERBOSE + // Do not refresh too quickly queueRefresh(); - } else if ( desktop && desktop->doc() ) { + } else if (desktop && desktop->doc()) { #if ICON_VERBOSE - g_message( "%s Refreshing preview.", getTimestr().c_str() ); + g_message("%s Refreshing preview.", getTimestr().c_str()); #endif // ICON_VERBOSE bool hold = Inkscape::Preferences::get()->getBool("/iconpreview/selectionHold", true); SPObject *target = nullptr; - if ( selectionButton && selectionButton->get_active() ) - { - target = (hold && !targetId.empty()) ? desktop->doc()->getObjectById( targetId.c_str() ) : nullptr; - if ( !target ) { + if (selectionButton && selectionButton->get_active()) { + target = (hold && !targetId.empty()) ? desktop->doc()->getObjectById(targetId.c_str()) : nullptr; + if (!target) { targetId.clear(); - Inkscape::Selection * sel = desktop->getSelection(); - if ( sel ) { - //g_message("found a selection to play with"); + Inkscape::Selection *sel = desktop->getSelection(); + if (sel) { + // g_message("found a selection to play with"); - auto items = sel->items(); - for(auto i=items.begin();!target && i!=items.end();++i){ - SPItem* item = *i; + auto items = sel->items(); + for (auto i = items.begin(); !target && i != items.end(); ++i) { + SPItem *item = *i; gchar const *id = item->getId(); - if ( id ) { + if (id) { targetId = id; target = item; } @@ -371,11 +360,11 @@ void IconPreviewPanel::refreshPreview() } else { target = desktop->currentRoot(); } - if ( target ) { + if (target) { renderPreview(target); } #if ICON_VERBOSE - g_message( "%s resetting timer", getTimestr().c_str() ); + g_message("%s resetting timer", getTimestr().c_str()); #endif // ICON_VERBOSE timer->reset(); } @@ -387,14 +376,14 @@ bool IconPreviewPanel::refreshCB() if (!timer) { timer = new Glib::Timer(); } - if ( timer->elapsed() > minDelay ) { + if (timer->elapsed() > minDelay) { #if ICON_VERBOSE - g_message( "%s refreshCB() timer has progressed", getTimestr().c_str() ); + g_message("%s refreshCB() timer has progressed", getTimestr().c_str()); #endif // ICON_VERBOSE callAgain = false; refreshPreview(); #if ICON_VERBOSE - g_message( "%s refreshCB() setting pending false", getTimestr().c_str() ); + g_message("%s refreshCB() setting pending false", getTimestr().c_str()); #endif // ICON_VERBOSE pending = false; } @@ -406,12 +395,12 @@ void IconPreviewPanel::queueRefresh() if (!pending) { pending = true; #if ICON_VERBOSE - g_message( "%s queueRefresh() Setting pending true", getTimestr().c_str() ); + g_message("%s queueRefresh() Setting pending true", getTimestr().c_str()); #endif // ICON_VERBOSE if (!timer) { timer = new Glib::Timer(); } - Glib::signal_idle().connect( sigc::mem_fun(this, &IconPreviewPanel::refreshCB), Glib::PRIORITY_DEFAULT_IDLE ); + Glib::signal_idle().connect(sigc::mem_fun(this, &IconPreviewPanel::refreshCB), Glib::PRIORITY_DEFAULT_IDLE); } } @@ -420,21 +409,20 @@ void IconPreviewPanel::modeToggled() Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool selectionOnly = (selectionButton && selectionButton->get_active()); prefs->setBool("/iconpreview/selectionOnly", selectionOnly); - if ( !selectionOnly ) { + if (!selectionOnly) { targetId.clear(); } refreshPreview(); } -void overlayPixels(guchar *px, int width, int height, int stride, - unsigned r, unsigned g, unsigned b) +void overlayPixels(guchar *px, int width, int height, int stride, unsigned r, unsigned g, unsigned b) { int bytesPerPixel = 4; int spacing = 4; - for ( int y = 0; y < height; y += spacing ) { + for (int y = 0; y < height; y += spacing) { guchar *ptr = px + y * stride; - for ( int x = 0; x < width; x += spacing ) { + for (int x = 0; x < width; x += spacing) { *(ptr++) = r; *(ptr++) = g; *(ptr++) = b; @@ -444,11 +432,11 @@ void overlayPixels(guchar *px, int width, int height, int stride, } } - if ( width > 1 && height > 1 ) { + if (width > 1 && height > 1) { // point at the last pixel - guchar *ptr = px + ((height-1) * stride) + ((width - 1) * bytesPerPixel); + guchar *ptr = px + ((height - 1) * stride) + ((width - 1) * bytesPerPixel); - if ( width > 2 ) { + if (width > 2) { px[4] = r; px[5] = g; px[6] = b; @@ -475,7 +463,7 @@ void overlayPixels(guchar *px, int width, int height, int stride, ptr[2 - stride] = b; ptr[3 - stride] = 0xff; - if ( height > 2 ) { + if (height > 2) { ptr[0 - stride * 3] = r; ptr[1 - stride * 3] = g; ptr[2 - stride * 3] = b; @@ -485,10 +473,8 @@ void overlayPixels(guchar *px, int width, int height, int stride, } // takes doc, drawing, icon, and icon name to produce pixels -extern "C" guchar * -sp_icon_doc_icon( SPDocument *doc, Inkscape::Drawing &drawing, - gchar const *name, unsigned psize, - unsigned &stride) +extern "C" guchar *sp_icon_doc_icon(SPDocument *doc, Inkscape::Drawing &drawing, gchar const *name, unsigned psize, + unsigned &stride) { bool const dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg"); guchar *px = nullptr; @@ -500,14 +486,13 @@ sp_icon_doc_icon( SPDocument *doc, Inkscape::Drawing &drawing, // Find bbox in document Geom::OptRect dbox = item->documentVisualBounds(); - if ( object->parent == nullptr ) - { + if (object->parent == nullptr) { dbox = Geom::Rect(Geom::Point(0, 0), - Geom::Point(doc->getWidth().value("px"), doc->getHeight().value("px"))); + Geom::Point(doc->getWidth().value("px"), doc->getHeight().value("px"))); } /* This is in document coordinates, i.e. pixels */ - if ( dbox ) { + if (dbox) { /* Update to renderable state */ double sf = 1.0; drawing.root()->setTransform(Geom::Scale(sf)); @@ -516,23 +501,24 @@ sp_icon_doc_icon( SPDocument *doc, Inkscape::Drawing &drawing, // NOTE: previously, each rect coordinate was rounded using floor(c + 0.5) Geom::IntRect ibox = dbox->roundOutwards(); - if ( dump ) { - g_message( " box --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.left(), (double)ibox.top(), (double)ibox.right(), (double)ibox.bottom() ); + if (dump) { + g_message(" box --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.left(), (double)ibox.top(), + (double)ibox.right(), (double)ibox.bottom()); } /* Find button visible area */ int width = ibox.width(); int height = ibox.height(); - if ( dump ) { - g_message( " vis --'%s' (%d,%d)", name, width, height ); + if (dump) { + g_message(" vis --'%s' (%d,%d)", name, width, height); } { int block = std::max(width, height); - if (block != static_cast<int>(psize) ) { - if ( dump ) { - g_message(" resizing" ); + if (block != static_cast<int>(psize)) { + if (dump) { + g_message(" resizing"); } sf = (double)psize / (double)block; @@ -541,33 +527,37 @@ sp_icon_doc_icon( SPDocument *doc, Inkscape::Drawing &drawing, auto scaled_box = *dbox * Geom::Scale(sf); ibox = scaled_box.roundOutwards(); - if ( dump ) { - g_message( " box2 --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.left(), (double)ibox.top(), (double)ibox.right(), (double)ibox.bottom() ); + if (dump) { + g_message(" box2 --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.left(), + (double)ibox.top(), (double)ibox.right(), (double)ibox.bottom()); } /* Find button visible area */ width = ibox.width(); height = ibox.height(); - if ( dump ) { - g_message( " vis2 --'%s' (%d,%d)", name, width, height ); + if (dump) { + g_message(" vis2 --'%s' (%d,%d)", name, width, height); } } } Geom::IntPoint pdim(psize, psize); int dx, dy; - //dx = (psize - width) / 2; - //dy = (psize - height) / 2; - dx=dy=psize; - dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative - dy=(dy-height)/2; - Geom::IntRect area = Geom::IntRect::from_xywh(ibox.min() - Geom::IntPoint(dx,dy), pdim); + // dx = (psize - width) / 2; + // dy = (psize - height) / 2; + dx = dy = psize; + dx = (dx - width) / + 2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative + dy = (dy - height) / 2; + Geom::IntRect area = Geom::IntRect::from_xywh(ibox.min() - Geom::IntPoint(dx, dy), pdim); /* Actual renderable area */ Geom::IntRect ua = *Geom::intersect(ibox, area); - if ( dump ) { - g_message( " area --'%s' (%f,%f)-(%f,%f)", name, (double)area.left(), (double)area.top(), (double)area.right(), (double)area.bottom() ); - g_message( " ua --'%s' (%f,%f)-(%f,%f)", name, (double)ua.left(), (double)ua.top(), (double)ua.right(), (double)ua.bottom() ); + if (dump) { + g_message(" area --'%s' (%f,%f)-(%f,%f)", name, (double)area.left(), (double)area.top(), + (double)area.right(), (double)area.bottom()); + g_message(" ua --'%s' (%f,%f)-(%f,%f)", name, (double)ua.left(), (double)ua.top(), + (double)ua.right(), (double)ua.bottom()); } stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, psize); @@ -577,8 +567,7 @@ sp_icon_doc_icon( SPDocument *doc, Inkscape::Drawing &drawing, memset(px, 0x00, stride * psize); /* Render */ - cairo_surface_t *s = cairo_image_surface_create_for_data(px, - CAIRO_FORMAT_ARGB32, psize, psize, stride); + cairo_surface_t *s = cairo_image_surface_create_for_data(px, CAIRO_FORMAT_ARGB32, psize, psize, stride); Inkscape::DrawingContext dc(s, ua.min()); SPNamedView *nv = sp_document_namedview(doc, nullptr); @@ -600,8 +589,8 @@ sp_icon_doc_icon( SPDocument *doc, Inkscape::Drawing &drawing, // convert to GdkPixbuf format convert_pixels_argb32_to_pixbuf(px, psize, psize, stride); - if ( Inkscape::Preferences::get()->getBool("/debug/icons/overlaySvg") ) { - overlayPixels( px, psize, psize, stride, 0x00, 0x00, 0xff ); + if (Inkscape::Preferences::get()->getBool("/debug/icons/overlaySvg")) { + overlayPixels(px, psize, psize, stride, 0x00, 0x00, 0xff); } } } @@ -610,31 +599,30 @@ sp_icon_doc_icon( SPDocument *doc, Inkscape::Drawing &drawing, return px; } // end of sp_icon_doc_icon() - -void IconPreviewPanel::renderPreview( SPObject* obj ) +void IconPreviewPanel::renderPreview(SPObject *obj) { - SPDocument * doc = obj->document; - gchar const * id = obj->getId(); - if ( !renderTimer ) { + SPDocument *doc = obj->document; + gchar const *id = obj->getId(); + if (!renderTimer) { renderTimer = new Glib::Timer(); } renderTimer->reset(); #if ICON_VERBOSE - g_message("%s setting up to render '%s' as the icon", getTimestr().c_str(), id ); + g_message("%s setting up to render '%s' as the icon", getTimestr().c_str(), id); #endif // ICON_VERBOSE - for ( int i = 0; i < numEntries; i++ ) { + for (int i = 0; i < numEntries; i++) { unsigned unused; int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, sizes[i]); guchar *px = sp_icon_doc_icon(doc, *drawing, id, sizes[i], unused); -// g_message( " size %d %s", sizes[i], (px ? "worked" : "failed") ); - if ( px ) { - memcpy( pixMem[i], px, sizes[i] * stride ); - g_free( px ); + // g_message( " size %d %s", sizes[i], (px ? "worked" : "failed") ); + if (px) { + memcpy(pixMem[i], px, sizes[i] * stride); + g_free(px); px = nullptr; } else { - memset( pixMem[i], 0, sizes[i] * stride ); + memset(pixMem[i], 0, sizes[i] * stride); } images[i]->set(images[i]->get_pixbuf()); // images[i]->queue_draw(); @@ -642,7 +630,7 @@ void IconPreviewPanel::renderPreview( SPObject* obj ) updateMagnify(); renderTimer->stop(); - minDelay = std::max( 0.1, renderTimer->elapsed() * 3.0 ); + minDelay = std::max(0.1, renderTimer->elapsed() * 3.0); #if ICON_VERBOSE g_message(" render took %f seconds.", renderTimer->elapsed()); #endif // ICON_VERBOSE @@ -650,16 +638,16 @@ void IconPreviewPanel::renderPreview( SPObject* obj ) void IconPreviewPanel::updateMagnify() { - Glib::RefPtr<Gdk::Pixbuf> buf = images[hot]->get_pixbuf()->scale_simple( 128, 128, Gdk::INTERP_NEAREST ); - magLabel.set_label( *labels[hot] ); - magnified.set( buf ); + Glib::RefPtr<Gdk::Pixbuf> buf = images[hot]->get_pixbuf()->scale_simple(128, 128, Gdk::INTERP_NEAREST); + magLabel.set_label(*labels[hot]); + magnified.set(buf); // magnified.queue_draw(); // magnified.get_parent()->queue_draw(); } -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/icon-preview.h b/src/ui/dialog/icon-preview.h index 2ebb4a78811a3d7f96326ec8fe6bd0f78f334e09..4f157a5959bdc96f2109b96c8fa691d0a4ce800e 100644 --- a/src/ui/dialog/icon-preview.h +++ b/src/ui/dialog/icon-preview.h @@ -18,9 +18,9 @@ #include <gtkmm/box.h> #include <gtkmm/button.h> +#include <gtkmm/image.h> #include <gtkmm/label.h> #include <gtkmm/paned.h> -#include <gtkmm/image.h> #include <gtkmm/togglebutton.h> #include <gtkmm/toggletoolbutton.h> @@ -36,7 +36,6 @@ class Drawing; namespace UI { namespace Dialog { - /** * A panel that displays an icon preview */ @@ -44,20 +43,19 @@ class IconPreviewPanel : public UI::Widget::Panel { public: IconPreviewPanel(); - //IconPreviewPanel(Glib::ustring const &label); + // IconPreviewPanel(Glib::ustring const &label); ~IconPreviewPanel() override; - static IconPreviewPanel& getInstance(); + static IconPreviewPanel &getInstance(); - void setDesktop( SPDesktop* desktop ) override; + void setDesktop(SPDesktop *desktop) override; void refreshPreview(); void modeToggled(); private: - IconPreviewPanel(IconPreviewPanel const &) = delete; // no copy + IconPreviewPanel(IconPreviewPanel const &) = delete; // no copy IconPreviewPanel &operator=(IconPreviewPanel const &) = delete; // no assign - SPDesktop *desktop; SPDocument *document; Drawing *drawing; @@ -67,40 +65,37 @@ private: bool pending; gdouble minDelay; - Gtk::VBox iconBox; - Gtk::Paned splitter; + Gtk::VBox iconBox; + Gtk::Paned splitter; Glib::ustring targetId; int hot; int numEntries; - int* sizes; + int *sizes; - Gtk::Image magnified; - Gtk::Label magLabel; + Gtk::Image magnified; + Gtk::Label magLabel; - Gtk::ToggleButton *selectionButton; + Gtk::ToggleButton *selectionButton; - guchar** pixMem; - Gtk::Image** images; - Glib::ustring** labels; - Gtk::ToggleToolButton** buttons; + guchar **pixMem; + Gtk::Image **images; + Glib::ustring **labels; + Gtk::ToggleToolButton **buttons; sigc::connection docReplacedConn; sigc::connection docModConn; sigc::connection selChangedConn; - - void setDocument( SPDocument *document ); + void setDocument(SPDocument *document); void on_button_clicked(int which); - void renderPreview( SPObject* obj ); + void renderPreview(SPObject *obj); void updateMagnify(); void queueRefresh(); bool refreshCB(); }; -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape - - +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif // SEEN_ICON_PREVIEW_H diff --git a/src/ui/dialog/inkscape-preferences.cpp b/src/ui/dialog/inkscape-preferences.cpp index 44c59d85ab201fe6a54295072878c27729ef4db8..4d689e051aa49944207bd54762595ccc9a7948d6 100644 --- a/src/ui/dialog/inkscape-preferences.cpp +++ b/src/ui/dialog/inkscape-preferences.cpp @@ -15,25 +15,28 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include "inkscape-preferences.h" - #include <fstream> - #include <gio/gio.h> -#include <gtk/gtk.h> #include <glibmm/i18n.h> +#include <gtk/gtk.h> #include <gtkmm.h> #include "auto-save.h" #include "cms-system.h" +#include "display/canvas-grid.h" +#include "display/nr-filter-gaussian.h" #include "document.h" #include "enums.h" +#include "extension/internal/gdkpixbuf-input.h" +#include "inkscape-preferences.h" #include "inkscape-window.h" #include "inkscape.h" +#include "io/resource.h" #include "message-stack.h" +#include "object/color-profile.h" #include "path-prefix.h" #include "preferences.h" #include "selcue.h" @@ -41,57 +44,45 @@ #include "selection.h" #include "shortcuts.h" #include "style.h" -#include "verbs.h" - -#include "display/canvas-grid.h" -#include "display/nr-filter-gaussian.h" - -#include "extension/internal/gdkpixbuf-input.h" - -#include "io/resource.h" - -#include "object/color-profile.h" - #include "svg/svg-color.h" - #include "ui/interface.h" #include "ui/widget/style-swatch.h" - +#include "verbs.h" #include "widgets/desktop-widget.h" #if WITH_GSPELL -# include "ui/dialog/spellcheck.h" // for get_available_langs -# ifdef _WIN32 -# include <windows.h> -# endif +#include "ui/dialog/spellcheck.h" // for get_available_langs +#ifdef _WIN32 +#include <windows.h> +#endif #endif namespace Inkscape { namespace UI { namespace Dialog { +using Inkscape::CMSSystem; using Inkscape::UI::Widget::DialogPage; using Inkscape::UI::Widget::PrefCheckButton; using Inkscape::UI::Widget::PrefRadioButton; using Inkscape::UI::Widget::PrefSpinButton; using Inkscape::UI::Widget::StyleSwatch; -using Inkscape::CMSSystem; -#define REMOVE_SPACES(x) \ - x.erase(0, x.find_first_not_of(' ')); \ +#define REMOVE_SPACES(x) \ + x.erase(0, x.find_first_not_of(' ')); \ x.erase(x.find_last_not_of(' ') + 1); InkscapePreferences::InkscapePreferences() - : UI::Widget::Panel ("/dialogs/preferences", SP_VERB_DIALOG_DISPLAY), - _minimum_width(0), - _minimum_height(0), - _natural_width(0), - _natural_height(0), - _current_page(nullptr), - _init(true) + : UI::Widget::Panel("/dialogs/preferences", SP_VERB_DIALOG_DISPLAY) + , _minimum_width(0) + , _minimum_height(0) + , _natural_width(0) + , _natural_height(0) + , _current_page(nullptr) + , _init(true) { - //get the width of a spinbutton - Inkscape::UI::Widget::SpinButton* sb = new Inkscape::UI::Widget::SpinButton; + // get the width of a spinbutton + Inkscape::UI::Widget::SpinButton *sb = new Inkscape::UI::Widget::SpinButton; sb->set_width_chars(6); _getContents()->add(*sb); show_all_children(); @@ -102,15 +93,15 @@ InkscapePreferences::InkscapePreferences() _getContents()->remove(*sb); delete sb; - //Main HBox + // Main HBox auto hbox_list_page = Gtk::manage(new Gtk::Box()); hbox_list_page->set_border_width(12); hbox_list_page->set_spacing(12); _setContents(hbox_list_page); - //Pagelist - Gtk::Frame* list_frame = Gtk::manage(new Gtk::Frame()); - Gtk::ScrolledWindow* scrolled_window = Gtk::manage(new Gtk::ScrolledWindow()); + // Pagelist + Gtk::Frame *list_frame = Gtk::manage(new Gtk::Frame()); + Gtk::ScrolledWindow *scrolled_window = Gtk::manage(new Gtk::ScrolledWindow()); hbox_list_page->pack_start(*list_frame, false, true, 0); _page_list.set_headers_visible(false); scrolled_window->set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); @@ -121,16 +112,17 @@ InkscapePreferences::InkscapePreferences() list_frame->add(*scrolled_window); _page_list_model = Gtk::TreeStore::create(_page_list_columns); _page_list.set_model(_page_list_model); - _page_list.append_column("name",_page_list_columns._col_name); + _page_list.append_column("name", _page_list_columns._col_name); Glib::RefPtr<Gtk::TreeSelection> page_list_selection = _page_list.get_selection(); - page_list_selection->signal_changed().connect(sigc::mem_fun(*this, &InkscapePreferences::on_pagelist_selection_changed)); + page_list_selection->signal_changed().connect( + sigc::mem_fun(*this, &InkscapePreferences::on_pagelist_selection_changed)); page_list_selection->set_mode(Gtk::SELECTION_BROWSE); - //Pages + // Pages auto vbox_page = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL)); - Gtk::Frame* title_frame = Gtk::manage(new Gtk::Frame()); + Gtk::Frame *title_frame = Gtk::manage(new Gtk::Frame()); - Gtk::ScrolledWindow* pageScroller = Gtk::manage(new Gtk::ScrolledWindow()); + Gtk::ScrolledWindow *pageScroller = Gtk::manage(new Gtk::ScrolledWindow()); pageScroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); pageScroller->set_propagate_natural_width(); pageScroller->set_propagate_natural_height(); @@ -155,27 +147,27 @@ InkscapePreferences::InkscapePreferences() signal_map().connect(sigc::mem_fun(*this, &InkscapePreferences::_presentPages)); - //calculate the size request for this dialog + // calculate the size request for this dialog _page_list.expand_all(); _page_list_model->foreach_iter(sigc::mem_fun(*this, &InkscapePreferences::GetSizeRequest)); _page_list.collapse_all(); } -InkscapePreferences::~InkscapePreferences() -= default; +InkscapePreferences::~InkscapePreferences() = default; -Gtk::TreeModel::iterator InkscapePreferences::AddPage(DialogPage& p, Glib::ustring title, int id) +Gtk::TreeModel::iterator InkscapePreferences::AddPage(DialogPage &p, Glib::ustring title, int id) { - return AddPage(p, title, Gtk::TreeModel::iterator() , id); + return AddPage(p, title, Gtk::TreeModel::iterator(), id); } -Gtk::TreeModel::iterator InkscapePreferences::AddPage(DialogPage& p, Glib::ustring title, Gtk::TreeModel::iterator parent, int id) +Gtk::TreeModel::iterator InkscapePreferences::AddPage(DialogPage &p, Glib::ustring title, + Gtk::TreeModel::iterator parent, int id) { Gtk::TreeModel::iterator iter; if (parent) - iter = _page_list_model->append((*parent).children()); + iter = _page_list_model->append((*parent).children()); else - iter = _page_list_model->append(); + iter = _page_list_model->append(); Gtk::TreeModel::Row row = *iter; row[_page_list_columns._col_name] = title; row[_page_list_columns._col_id] = id; @@ -185,43 +177,43 @@ Gtk::TreeModel::iterator InkscapePreferences::AddPage(DialogPage& p, Glib::ustri void InkscapePreferences::AddSelcueCheckbox(DialogPage &p, Glib::ustring const &prefs_path, bool def_value) { - PrefCheckButton* cb = Gtk::manage( new PrefCheckButton); - cb->init ( _("Show selection cue"), prefs_path + "/selcue", def_value); - p.add_line( false, "", *cb, "", _("Whether selected objects display a selection cue (the same as in selector)")); + PrefCheckButton *cb = Gtk::manage(new PrefCheckButton); + cb->init(_("Show selection cue"), prefs_path + "/selcue", def_value); + p.add_line(false, "", *cb, "", _("Whether selected objects display a selection cue (the same as in selector)")); } void InkscapePreferences::AddGradientCheckbox(DialogPage &p, Glib::ustring const &prefs_path, bool def_value) { - PrefCheckButton* cb = Gtk::manage( new PrefCheckButton); - cb->init ( _("Enable gradient editing"), prefs_path + "/gradientdrag", def_value); - p.add_line( false, "", *cb, "", _("Whether selected objects display gradient editing controls")); + PrefCheckButton *cb = Gtk::manage(new PrefCheckButton); + cb->init(_("Enable gradient editing"), prefs_path + "/gradientdrag", def_value); + p.add_line(false, "", *cb, "", _("Whether selected objects display gradient editing controls")); } -void InkscapePreferences::AddConvertGuidesCheckbox(DialogPage &p, Glib::ustring const &prefs_path, bool def_value) { - PrefCheckButton* cb = Gtk::manage( new PrefCheckButton); - cb->init ( _("Conversion to guides uses edges instead of bounding box"), prefs_path + "/convertguides", def_value); - p.add_line( false, "", *cb, "", _("Converting an object to guides places these along the object's true edges (imitating the object's shape), not along the bounding box")); +void InkscapePreferences::AddConvertGuidesCheckbox(DialogPage &p, Glib::ustring const &prefs_path, bool def_value) +{ + PrefCheckButton *cb = Gtk::manage(new PrefCheckButton); + cb->init(_("Conversion to guides uses edges instead of bounding box"), prefs_path + "/convertguides", def_value); + p.add_line(false, "", *cb, "", + _("Converting an object to guides places these along the object's true edges (imitating the object's " + "shape), not along the bounding box")); } void InkscapePreferences::AddDotSizeSpinbutton(DialogPage &p, Glib::ustring const &prefs_path, double def_value) { - 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"), - _("Size of dots created with Ctrl+click (relative to current stroke width)"), - false ); + 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"), + _("Size of dots created with Ctrl+click (relative to current stroke width)"), false); } void InkscapePreferences::AddBaseSimplifySpinbutton(DialogPage &p, Glib::ustring const &prefs_path, double def_value) { - PrefSpinButton* sb = Gtk::manage( new PrefSpinButton); - sb->init ( prefs_path + "/base-simplify", 0.0, 100.0, 1.0, 10.0, def_value, false, false); - p.add_line( false, _("Base simplify:"), *sb, _("on dynamic LPE simplify"), - _("Base simplify of dynamic LPE based simplify"), - false ); + PrefSpinButton *sb = Gtk::manage(new PrefSpinButton); + sb->init(prefs_path + "/base-simplify", 0.0, 100.0, 1.0, 10.0, def_value, false, false); + p.add_line(false, _("Base simplify:"), *sb, _("on dynamic LPE simplify"), + _("Base simplify of dynamic LPE based simplify"), false); } - static void StyleFromSelectionToTool(Glib::ustring const &prefs_path, StyleSwatch *swatch) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; @@ -232,7 +224,7 @@ static void StyleFromSelectionToTool(Glib::ustring const &prefs_path, StyleSwatc if (selection->isEmpty()) { desktop->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, - _("<b>No objects selected</b> to take the style from.")); + _("<b>No objects selected</b> to take the style from.")); return; } SPItem *item = selection->singleItem(); @@ -240,34 +232,36 @@ static void StyleFromSelectionToTool(Glib::ustring const &prefs_path, StyleSwatc /* TODO: If each item in the selection has the same style then don't consider it an error. * Maybe we should try to handle multiple selections anyway, e.g. the intersection of the * style attributes for the selected items. */ - desktop->getMessageStack()->flash(Inkscape::ERROR_MESSAGE, - _("<b>More than one object selected.</b> Cannot take style from multiple objects.")); + desktop->getMessageStack()->flash( + Inkscape::ERROR_MESSAGE, + _("<b>More than one object selected.</b> Cannot take style from multiple objects.")); return; } - SPCSSAttr *css = take_style_from_item (item); + SPCSSAttr *css = take_style_from_item(item); - if (!css) return; + if (!css) + return; // remove black-listed properties - css = sp_css_attr_unset_blacklist (css); + css = sp_css_attr_unset_blacklist(css); // only store text style for the text tool if (prefs_path != "/tools/text") { - css = sp_css_attr_unset_text (css); + css = sp_css_attr_unset_text(css); } // we cannot store properties with uris - they will be invalid in other documents - css = sp_css_attr_unset_uris (css); + css = sp_css_attr_unset_uris(css); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setStyle(prefs_path + "/style", css); - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); // update the swatch if (swatch) { SPCSSAttr *css = prefs->getInheritedStyle(prefs_path + "/style"); - swatch->setStyle (css); + swatch->setStyle(css); sp_repr_css_attr_unref(css); } } @@ -277,23 +271,24 @@ void InkscapePreferences::AddNewObjectsStyle(DialogPage &p, Glib::ustring const if (banner) p.add_group_header(banner); else - p.add_group_header( _("Style of new objects")); - PrefRadioButton* current = Gtk::manage( new PrefRadioButton); - current->init ( _("Last used style"), prefs_path + "/usecurrent", 1, true, nullptr); - p.add_line( true, "", *current, "", - _("Apply the style you last set on an object")); - - PrefRadioButton* own = Gtk::manage( new PrefRadioButton); - auto hb = Gtk::manage( new Gtk::Box); - own->init ( _("This tool's own style:"), prefs_path + "/usecurrent", 0, false, current); + p.add_group_header(_("Style of new objects")); + PrefRadioButton *current = Gtk::manage(new PrefRadioButton); + current->init(_("Last used style"), prefs_path + "/usecurrent", 1, true, nullptr); + p.add_line(true, "", *current, "", _("Apply the style you last set on an object")); + + PrefRadioButton *own = Gtk::manage(new PrefRadioButton); + auto hb = Gtk::manage(new Gtk::Box); + own->init(_("This tool's own style:"), prefs_path + "/usecurrent", 0, false, current); own->set_halign(Gtk::ALIGN_START); own->set_valign(Gtk::ALIGN_START); hb->add(*own); - p.set_tip( *own, _("Each tool may store its own style to apply to the newly created objects. Use the button below to set it.")); - p.add_line( true, "", *hb, "", ""); + p.set_tip( + *own, + _("Each tool may store its own style to apply to the newly created objects. Use the button below to set it.")); + p.add_line(true, "", *hb, "", ""); // style swatch - Gtk::Button* button = Gtk::manage( new Gtk::Button(_("Take from selection"), true)); + Gtk::Button *button = Gtk::manage(new Gtk::Button(_("Take from selection"), true)); StyleSwatch *swatch = nullptr; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -306,10 +301,9 @@ void InkscapePreferences::AddNewObjectsStyle(DialogPage &p, Glib::ustring const hb->add(*swatch); sp_repr_css_attr_unref(css); - button->signal_clicked().connect( sigc::bind( sigc::ptr_fun(StyleFromSelectionToTool), prefs_path, swatch) ); - own->changed_signal.connect( sigc::mem_fun(*button, &Gtk::Button::set_sensitive) ); - p.add_line( true, "", *button, "", - _("Remember the style of the (first) selected object as this tool's style")); + button->signal_clicked().connect(sigc::bind(sigc::ptr_fun(StyleFromSelectionToTool), prefs_path, swatch)); + own->changed_signal.connect(sigc::mem_fun(*button, &Gtk::Button::set_sensitive)); + p.add_line(true, "", *button, "", _("Remember the style of the (first) selected object as this tool's style")); } void InkscapePreferences::initPageTools() @@ -317,15 +311,16 @@ void InkscapePreferences::initPageTools() Gtk::TreeModel::iterator iter_tools = this->AddPage(_page_tools, _("Tools"), PREFS_PAGE_TOOLS); this->AddPage(_page_selector, _("Selector"), iter_tools, PREFS_PAGE_TOOLS_SELECTOR); this->AddPage(_page_node, _("Node"), iter_tools, PREFS_PAGE_TOOLS_NODE); - + // shapes - Gtk::TreeModel::iterator iter_shapes = this->AddPage(_page_shapes, _("Shapes"), iter_tools, PREFS_PAGE_TOOLS_SHAPES); + Gtk::TreeModel::iterator iter_shapes = + this->AddPage(_page_shapes, _("Shapes"), iter_tools, PREFS_PAGE_TOOLS_SHAPES); this->AddPage(_page_rectangle, _("Rectangle"), iter_shapes, PREFS_PAGE_TOOLS_SHAPES_RECT); this->AddPage(_page_ellipse, _("Ellipse"), iter_shapes, PREFS_PAGE_TOOLS_SHAPES_ELLIPSE); this->AddPage(_page_star, _("Star"), iter_shapes, PREFS_PAGE_TOOLS_SHAPES_STAR); this->AddPage(_page_3dbox, _("3D Box"), iter_shapes, PREFS_PAGE_TOOLS_SHAPES_3DBOX); this->AddPage(_page_spiral, _("Spiral"), iter_shapes, PREFS_PAGE_TOOLS_SHAPES_SPIRAL); - + this->AddPage(_page_pen, _("Pen"), iter_tools, PREFS_PAGE_TOOLS_PEN); this->AddPage(_page_pencil, _("Pencil"), iter_tools, PREFS_PAGE_TOOLS_PENCIL); this->AddPage(_page_calligraphy, _("Calligraphy"), iter_tools, PREFS_PAGE_TOOLS_CALLIGRAPHY); @@ -334,7 +329,7 @@ void InkscapePreferences::initPageTools() this->AddPage(_page_gradient, _("Gradient"), iter_tools, PREFS_PAGE_TOOLS_GRADIENT); this->AddPage(_page_dropper, _("Dropper"), iter_tools, PREFS_PAGE_TOOLS_DROPPER); this->AddPage(_page_paintbucket, _("Paint Bucket"), iter_tools, PREFS_PAGE_TOOLS_PAINTBUCKET); - + this->AddPage(_page_tweak, _("Tweak"), iter_tools, PREFS_PAGE_TOOLS_TWEAK); this->AddPage(_page_spray, _("Spray"), iter_tools, PREFS_PAGE_TOOLS_SPRAY); this->AddPage(_page_eraser, _("Eraser"), iter_tools, PREFS_PAGE_TOOLS_ERASER); @@ -344,199 +339,230 @@ void InkscapePreferences::initPageTools() #endif // WITH_LPETOOL this->AddPage(_page_zoom, _("Zoom"), iter_tools, PREFS_PAGE_TOOLS_ZOOM); this->AddPage(_page_measure, C_("ContextVerb", "Measure"), iter_tools, PREFS_PAGE_TOOLS_MEASURE); - - _page_tools.add_group_header( _("Bounding box to use")); - _t_bbox_visual.init ( _("Visual bounding box"), "/tools/bounding_box", 0, false, nullptr); // 0 means visual - _page_tools.add_line( true, "", _t_bbox_visual, "", - _("This bounding box includes stroke width, markers, filter margins, etc.")); - _t_bbox_geometric.init ( _("Geometric bounding box"), "/tools/bounding_box", 1, true, &_t_bbox_visual); // 1 means geometric - _page_tools.add_line( true, "", _t_bbox_geometric, "", - _("This bounding box includes only the bare path")); - - _page_tools.add_group_header( _("Conversion to guides")); - _t_cvg_keep_objects.init ( _("Keep objects after conversion to guides"), "/tools/cvg_keep_objects", false); - _page_tools.add_line( true, "", _t_cvg_keep_objects, "", - _("When converting an object to guides, don't delete the object after the conversion")); - _t_cvg_convert_whole_groups.init ( _("Treat groups as a single object"), "/tools/cvg_convert_whole_groups", false); - _page_tools.add_line( true, "", _t_cvg_convert_whole_groups, "", - _("Treat groups as a single object during conversion to guides rather than converting each child separately")); - - _pencil_average_all_sketches.init ( _("Average all sketches"), "/tools/freehand/pencil/average_all_sketches", false); - _calligrapy_use_abs_size.init ( _("Width is in absolute units"), "/tools/calligraphic/abs_width", false); - _calligrapy_keep_selected.init ( _("Select new path"), "/tools/calligraphic/keep_selected", true); - _connector_ignore_text.init( _("Don't attach connectors to text objects"), "/tools/connector/ignoretext", true); - - //Selector + _page_tools.add_group_header(_("Bounding box to use")); + _t_bbox_visual.init(_("Visual bounding box"), "/tools/bounding_box", 0, false, nullptr); // 0 means visual + _page_tools.add_line(true, "", _t_bbox_visual, "", + _("This bounding box includes stroke width, markers, filter margins, etc.")); + _t_bbox_geometric.init(_("Geometric bounding box"), "/tools/bounding_box", 1, true, + &_t_bbox_visual); // 1 means geometric + _page_tools.add_line(true, "", _t_bbox_geometric, "", _("This bounding box includes only the bare path")); + + _page_tools.add_group_header(_("Conversion to guides")); + _t_cvg_keep_objects.init(_("Keep objects after conversion to guides"), "/tools/cvg_keep_objects", false); + _page_tools.add_line(true, "", _t_cvg_keep_objects, "", + _("When converting an object to guides, don't delete the object after the conversion")); + _t_cvg_convert_whole_groups.init(_("Treat groups as a single object"), "/tools/cvg_convert_whole_groups", false); + _page_tools.add_line( + true, "", _t_cvg_convert_whole_groups, "", + _("Treat groups as a single object during conversion to guides rather than converting each child separately")); + + _pencil_average_all_sketches.init(_("Average all sketches"), "/tools/freehand/pencil/average_all_sketches", false); + _calligrapy_use_abs_size.init(_("Width is in absolute units"), "/tools/calligraphic/abs_width", false); + _calligrapy_keep_selected.init(_("Select new path"), "/tools/calligraphic/keep_selected", true); + _connector_ignore_text.init(_("Don't attach connectors to text objects"), "/tools/connector/ignoretext", true); + + // 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, nullptr); - _page_selector.add_line( true, "", _t_sel_trans_obj, "", - _("Show the actual objects when moving or transforming")); - _t_sel_trans_outl.init ( _("Box outline"), "/tools/select/show", "outline", false, &_t_sel_trans_obj); - _page_selector.add_line( true, "", _t_sel_trans_outl, "", + _page_selector.add_group_header(_("When transforming, show")); + _t_sel_trans_obj.init(_("Objects"), "/tools/select/show", "content", true, nullptr); + _page_selector.add_line(true, "", _t_sel_trans_obj, "", _("Show the actual objects when moving or transforming")); + _t_sel_trans_outl.init(_("Box outline"), "/tools/select/show", "outline", false, &_t_sel_trans_obj); + _page_selector.add_line(true, "", _t_sel_trans_outl, "", _("Show only a box outline of the objects when moving or transforming")); - _page_selector.add_group_header( _("Per-object selection cue")); - _t_sel_cue_none.init ( C_("Selection cue", "None"), "/options/selcue/value", Inkscape::SelCue::NONE, false, nullptr); - _page_selector.add_line( true, "", _t_sel_cue_none, "", - _("No per-object selection indication")); - _t_sel_cue_mark.init ( _("Mark"), "/options/selcue/value", Inkscape::SelCue::MARK, true, &_t_sel_cue_none); - _page_selector.add_line( true, "", _t_sel_cue_mark, "", + _page_selector.add_group_header(_("Per-object selection cue")); + _t_sel_cue_none.init(C_("Selection cue", "None"), "/options/selcue/value", Inkscape::SelCue::NONE, false, nullptr); + _page_selector.add_line(true, "", _t_sel_cue_none, "", _("No per-object selection indication")); + _t_sel_cue_mark.init(_("Mark"), "/options/selcue/value", Inkscape::SelCue::MARK, true, &_t_sel_cue_none); + _page_selector.add_line(true, "", _t_sel_cue_mark, "", _("Each selected object has a diamond mark in the top left corner")); - _t_sel_cue_box.init ( _("Box"), "/options/selcue/value", Inkscape::SelCue::BBOX, false, &_t_sel_cue_none); - _page_selector.add_line( true, "", _t_sel_cue_box, "", - _("Each selected object displays its bounding box")); + _t_sel_cue_box.init(_("Box"), "/options/selcue/value", Inkscape::SelCue::BBOX, false, &_t_sel_cue_none); + _page_selector.add_line(true, "", _t_sel_cue_box, "", _("Each selected object displays its bounding box")); - //Node + // Node AddSelcueCheckbox(_page_node, "/tools/nodes", true); AddGradientCheckbox(_page_node, "/tools/nodes", true); - _page_node.add_group_header( _("Path outline")); + _page_node.add_group_header(_("Path outline")); _t_node_pathoutline_color.init(_("Path outline color"), "/tools/nodes/highlight_color", 0xff0000ff); - _page_node.add_line( false, "", _t_node_pathoutline_color, "", _("Selects the color used for showing the path outline"), false); + _page_node.add_line(false, "", _t_node_pathoutline_color, "", + _("Selects the color used for showing the path outline"), false); _t_node_show_outline.init(_("Always show outline"), "/tools/nodes/show_outline", false); - _page_node.add_line( true, "", _t_node_show_outline, "", _("Show outlines for all paths, not only invisible paths")); + _page_node.add_line(true, "", _t_node_show_outline, "", _("Show outlines for all paths, not only invisible paths")); _t_node_live_outline.init(_("Update outline when dragging nodes"), "/tools/nodes/live_outline", false); - _page_node.add_line( true, "", _t_node_live_outline, "", _("Update the outline when dragging or transforming nodes; if this is off, the outline will only update when completing a drag")); + _page_node.add_line(true, "", _t_node_live_outline, "", + _("Update the outline when dragging or transforming nodes; if this is off, the outline will " + "only update when completing a drag")); _t_node_live_objects.init(_("Update paths when dragging nodes"), "/tools/nodes/live_objects", false); - _page_node.add_line( true, "", _t_node_live_objects, "", _("Update paths when dragging or transforming nodes; if this is off, paths will only be updated when completing a drag")); + _page_node.add_line(true, "", _t_node_live_objects, "", + _("Update paths when dragging or transforming nodes; if this is off, paths will only be " + "updated when completing a drag")); _t_node_show_path_direction.init(_("Show path direction on outlines"), "/tools/nodes/show_path_direction", false); - _page_node.add_line( true, "", _t_node_show_path_direction, "", _("Visualize the direction of selected paths by drawing small arrows in the middle of each outline segment")); - _t_node_pathflash_enabled.init ( _("Show temporary path outline"), "/tools/nodes/pathflash_enabled", false); - _page_node.add_line( true, "", _t_node_pathflash_enabled, "", _("When hovering over a path, briefly flash its outline")); - _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")); + _page_node.add_line( + true, "", _t_node_show_path_direction, "", + _("Visualize the direction of selected paths by drawing small arrows in the middle of each outline segment")); + _t_node_pathflash_enabled.init(_("Show temporary path outline"), "/tools/nodes/pathflash_enabled", false); + _page_node.add_line(true, "", _t_node_pathflash_enabled, "", + _("When hovering over a path, briefly flash its outline")); + _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")); - _t_node_delete_preserves_shape.init(_("Deleting nodes preserves shape"), "/tools/nodes/delete_preserves_shape", true); - _page_node.add_line( true, "", _t_node_delete_preserves_shape, "", _("Move handles next to deleted nodes to resemble original shape; hold Ctrl to get the other behavior")); - - //Tweak + _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")); + _t_node_delete_preserves_shape.init(_("Deleting nodes preserves shape"), "/tools/nodes/delete_preserves_shape", + true); + _page_node.add_line( + true, "", _t_node_delete_preserves_shape, "", + _("Move handles next to deleted nodes to resemble original shape; hold Ctrl to get the other behavior")); + + // Tweak this->AddNewObjectsStyle(_page_tweak, "/tools/tweak", _("Object paint style")); AddSelcueCheckbox(_page_tweak, "/tools/tweak", true); AddGradientCheckbox(_page_tweak, "/tools/tweak", false); - //Zoom + // Zoom AddSelcueCheckbox(_page_zoom, "/tools/zoom", true); AddGradientCheckbox(_page_zoom, "/tools/zoom", false); - //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.")); + // 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.")); - //Shapes + // Shapes this->AddSelcueCheckbox(_page_shapes, "/tools/shapes", true); this->AddGradientCheckbox(_page_shapes, "/tools/shapes", true); - //Rectangle + // Rectangle this->AddNewObjectsStyle(_page_rectangle, "/tools/shapes/rect"); this->AddConvertGuidesCheckbox(_page_rectangle, "/tools/shapes/rect", true); - //3D box + // 3D box this->AddNewObjectsStyle(_page_3dbox, "/tools/shapes/3dbox"); this->AddConvertGuidesCheckbox(_page_3dbox, "/tools/shapes/3dbox", true); - //Ellipse + // Ellipse this->AddNewObjectsStyle(_page_ellipse, "/tools/shapes/arc"); - //Star + // Star this->AddNewObjectsStyle(_page_star, "/tools/shapes/star"); - //Spiral + // Spiral this->AddNewObjectsStyle(_page_spiral, "/tools/shapes/spiral"); - //Pencil + // Pencil this->AddSelcueCheckbox(_page_pencil, "/tools/freehand/pencil", true); this->AddNewObjectsStyle(_page_pencil, "/tools/freehand/pencil"); this->AddDotSizeSpinbutton(_page_pencil, "/tools/freehand/pencil", 3.0); this->AddBaseSimplifySpinbutton(_page_pencil, "/tools/freehand/pencil", 25.0); - _page_pencil.add_group_header( _("Sketch mode")); - _page_pencil.add_line( true, "", _pencil_average_all_sketches, "", - _("If on, the sketch result will be the normal average of all sketches made, instead of averaging the old result with the new sketch")); + _page_pencil.add_group_header(_("Sketch mode")); + _page_pencil.add_line(true, "", _pencil_average_all_sketches, "", + _("If on, the sketch result will be the normal average of all sketches made, instead of " + "averaging the old result with the new sketch")); - //Pen + // Pen this->AddSelcueCheckbox(_page_pen, "/tools/freehand/pen", true); this->AddNewObjectsStyle(_page_pen, "/tools/freehand/pen"); this->AddDotSizeSpinbutton(_page_pen, "/tools/freehand/pen", 3.0); - //Calligraphy + // Calligraphy this->AddSelcueCheckbox(_page_calligraphy, "/tools/calligraphic", false); this->AddNewObjectsStyle(_page_calligraphy, "/tools/calligraphic"); - _page_calligraphy.add_line( false, "", _calligrapy_use_abs_size, "", - _("If on, pen width is in absolute units (px) independent of zoom; otherwise pen width depends on zoom so that it looks the same at any zoom")); - _page_calligraphy.add_line( false, "", _calligrapy_keep_selected, "", - _("If on, each newly created object will be selected (deselecting previous selection)")); + _page_calligraphy.add_line(false, "", _calligrapy_use_abs_size, "", + _("If on, pen width is in absolute units (px) independent of zoom; otherwise pen width " + "depends on zoom so that it looks the same at any zoom")); + _page_calligraphy.add_line(false, "", _calligrapy_keep_selected, "", + _("If on, each newly created object will be selected (deselecting previous selection)")); - //Text + // 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", true); - _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", true); + _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")); + _page_text.add_line( + false, "", _font_dialog, "", + _("Show font substitution warning dialog when requested fonts are not available on the system")); cb = Gtk::manage(new PrefCheckButton); - cb->init ( _("Use SVG2 auto-flowed text"), "/tools/text/use_svg2", true); - _page_text.add_line( false, "", *cb, "", _("Use SVG2 auto-flowed text instead of SVG1.2 auto-flowed text. (Recommended)")); + cb->init(_("Use SVG2 auto-flowed text"), "/tools/text/use_svg2", true); + _page_text.add_line(false, "", *cb, "", + _("Use SVG2 auto-flowed text instead of SVG1.2 auto-flowed text. (Recommended)")); } //_page_text.add_group_header( _("Text units")); //_font_output_px.init ( _("Always output text size in pixels (px)"), "/options/font/textOutputPx", true); - //_page_text.add_line( true, "", _font_output_px, "", _("Always convert the text size units above into pixels (px) before saving to file")); - - _page_text.add_group_header( _("Font directories")); - _font_fontsdir_system.init( _("Use Inkscape's fonts directory"), "/options/font/use_fontsdir_system", true); - _page_text.add_line( true, "", _font_fontsdir_system, "", _("Load additional fonts from \"fonts\" directory located in Inkscape's global \"share\" directory")); - _font_fontsdir_user.init( _("Use user's fonts directory"), "/options/font/use_fontsdir_user", true); - _page_text.add_line( true, "", _font_fontsdir_user, "", _("Load additional fonts from \"fonts\" directory located in Inkscape's user configuration directory")); + //_page_text.add_line( true, "", _font_output_px, "", _("Always convert the text size units above into pixels (px) + // before saving to file")); + + _page_text.add_group_header(_("Font directories")); + _font_fontsdir_system.init(_("Use Inkscape's fonts directory"), "/options/font/use_fontsdir_system", true); + _page_text.add_line( + true, "", _font_fontsdir_system, "", + _("Load additional fonts from \"fonts\" directory located in Inkscape's global \"share\" directory")); + _font_fontsdir_user.init(_("Use user's fonts directory"), "/options/font/use_fontsdir_user", true); + _page_text.add_line( + true, "", _font_fontsdir_user, "", + _("Load additional fonts from \"fonts\" directory located in Inkscape's user configuration directory")); _font_fontdirs_custom.init("/options/font/custom_fontdirs", 50); - _page_text.add_line(true, _("Additional font directories"), _font_fontdirs_custom, "", _("Load additional fonts from custom locations (one path per line)"), true); - + _page_text.add_line(true, _("Additional font directories"), _font_fontdirs_custom, "", + _("Load additional fonts from custom locations (one path per line)"), true); this->AddNewObjectsStyle(_page_text, "/tools/text"); - //Spray + // Spray AddSelcueCheckbox(_page_spray, "/tools/spray", true); AddGradientCheckbox(_page_spray, "/tools/spray", false); - //Eraser + // Eraser this->AddNewObjectsStyle(_page_eraser, "/tools/eraser"); - //Paint Bucket + // Paint Bucket this->AddSelcueCheckbox(_page_paintbucket, "/tools/paintbucket", false); this->AddNewObjectsStyle(_page_paintbucket, "/tools/paintbucket"); - //Gradient + // Gradient this->AddSelcueCheckbox(_page_gradient, "/tools/gradient", true); - _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_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_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); - + _page_gradient.add_line(false, _("Linear gradient _angle:"), _misc_gradientangle, "", + _("Default angle of new linear gradients in degrees (clockwise from horizontal)"), false); - //Dropper + // Dropper this->AddSelcueCheckbox(_page_dropper, "/tools/dropper", true); this->AddGradientCheckbox(_page_dropper, "/tools/dropper", true); - //Connector + // Connector this->AddSelcueCheckbox(_page_connector, "/tools/connector", true); _page_connector.add_line(false, "", _connector_ignore_text, "", - _("If on, connector attachment points will not be shown for text objects")); + _("If on, connector attachment points will not be shown for text objects")); #ifdef WITH_LPETOOL - //LPETool - //disabled, because the LPETool is not finished yet. + // LPETool + // disabled, because the LPETool is not finished yet. this->AddNewObjectsStyle(_page_lpetool, "/tools/lpetool"); #endif // WITH_LPETOOL } @@ -704,7 +730,10 @@ void InkscapePreferences::resetIconsColors(bool themechange) } } -void InkscapePreferences::resetIconsColorsWrapper() { resetIconsColors(false); } +void InkscapePreferences::resetIconsColorsWrapper() +{ + resetIconsColors(false); +} void InkscapePreferences::changeIconsColors() { @@ -741,7 +770,7 @@ void InkscapePreferences::toggleSymbolic() Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Gtk::Window *window = SP_ACTIVE_DESKTOP->getToplevel(); if (prefs->getBool("/theme/symbolicIcons", false)) { - if (window ) { + if (window) { window->get_style_context()->add_class("symbolic"); window->get_style_context()->remove_class("regular"); } @@ -771,7 +800,6 @@ void InkscapePreferences::themeChange() { Gtk::Window *window = SP_ACTIVE_DESKTOP->getToplevel(); if (window) { - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring current_theme = prefs->getString("/theme/gtkTheme"); auto settings = Gtk::Settings::get_default(); @@ -854,7 +882,7 @@ void InkscapePreferences::symbolicThemeCheck() } } if (prefs->getString("/theme/defaultIconTheme") != prefs->getString("/theme/iconTheme")) { - auto folders = get_foldernames(ICONS, { "application" }); + auto folders = get_foldernames(ICONS, {"application"}); for (auto &folder : folders) { auto path = folder; const size_t last_slash_idx = folder.find_last_of("\\/"); @@ -867,7 +895,7 @@ void InkscapePreferences::symbolicThemeCheck() #else path += "/symbolic/actions"; #endif - std::vector<Glib::ustring> symbolic_icons = get_filenames(path, { ".svg" }, {}); + std::vector<Glib::ustring> symbolic_icons = get_filenames(path, {".svg"}, {}); if (symbolic_icons.size() > 0) { symbolic = true; symbolic_icons.clear(); @@ -963,142 +991,200 @@ void InkscapePreferences::initPageUI() Gtk::TreeModel::iterator iter_ui = this->AddPage(_page_ui, _("Interface"), PREFS_PAGE_UI); Glib::ustring languages[] = {_("System default"), - _("Albanian (sq)"), _("Arabic (ar)"), _("Armenian (hy)"), _("Assamese (as)"), _("Azerbaijani (az)"), - _("Basque (eu)"), _("Belarusian (be)"), _("Bulgarian (bg)"), _("Bengali (bn)"), _("Bengali/Bangladesh (bn_BD)"), _("Bodo (brx)"), _("Breton (br)"), - _("Catalan (ca)"), _("Valencian Catalan (ca@valencia)"), _("Chinese/China (zh_CN)"), _("Chinese/Taiwan (zh_TW)"), _("Croatian (hr)"), _("Czech (cs)"), - _("Danish (da)"), _("Dogri (doi)"), _("Dutch (nl)"), _("Dzongkha (dz)"), - _("German (de)"), _("Greek (el)"), - _("English (en)"), _("English/Australia (en_AU)"), _("English/Canada (en_CA)"), _("English/Great Britain (en_GB)"), _("Esperanto (eo)"), _("Estonian (et)"), - _("Farsi (fa)"), _("Finnish (fi)"), _("French (fr)"), - _("Galician (gl)"), _("Gujarati (gu)"), - _("Hebrew (he)"), _("Hindi (hi)"), _("Hungarian (hu)"), - _("Icelandic (is)"), _("Indonesian (id)"), _("Irish (ga)"), _("Italian (it)"), - _("Japanese (ja)"), - _("Kannada (kn)"), _("Kashmiri in Perso-Arabic script (ks@aran)"), _("Kashmiri in Devanagari script (ks@deva)"), _("Khmer (km)"), _("Kinyarwanda (rw)"), _("Konkani (kok)"), _("Konkani in Latin script (kok@latin)"), _("Korean (ko)"), - _("Latvian (lv)"), _("Lithuanian (lt)"), - _("Macedonian (mk)"), _("Maithili (mai)"), _("Malayalam (ml)"), _("Manipuri (mni)"), _("Manipuri in Bengali script (mni@beng)"), _("Marathi (mr)"), _("Mongolian (mn)"), - _("Nepali (ne)"), _("Norwegian Bokmål (nb)"), _("Norwegian Nynorsk (nn)"), - _("Odia (or)"), - _("Panjabi (pa)"), _("Polish (pl)"), _("Portuguese (pt)"), _("Portuguese/Brazil (pt_BR)"), - _("Romanian (ro)"), _("Russian (ru)"), - _("Sanskrit (sa)"), _("Santali (sat)"), _("Santali in Devanagari script (sat@deva)"), _("Serbian (sr)"), _("Serbian in Latin script (sr@latin)"), - _("Sindhi (sd)"), _("Sindhi in Devanagari script (sd@deva)"), _("Slovak (sk)"), _("Slovenian (sl)"), _("Spanish (es)"), _("Spanish/Mexico (es_MX)"), _("Swedish (sv)"), - _("Tamil (ta)"), _("Telugu (te)"), _("Thai (th)"), _("Turkish (tr)"), - _("Ukrainian (uk)"), _("Urdu (ur)"), - _("Vietnamese (vi)")}; - Glib::ustring langValues[] = {"", - "sq", "ar", "hy", "as", "az", - "eu", "be", "bg", "bn", "bn_BD", "brx", "br", - "ca", "ca@valencia", "zh_CN", "zh_TW", "hr", "cs", - "da", "doi", "nl", "dz", - "de", "el", - "en", "en_AU", "en_CA", "en_GB", "eo", "et", - "fa", "fi", "fr", - "gl", "gu", - "he", "hi", "hu", - "is", "id", "ga", "it", - "ja", - "kn", "ks@aran", "ks@deva", "km", "rw", "kok", "kok@latin", "ko", - "lv", "lt", - "mk", "mai", "ml", "mni", "mni@beng", "mr", "mn", - "ne", "nb", "nn", - "or", - "pa", "pl", "pt", "pt_BR", - "ro", "ru", - "sa", "sat", "sat@deva", "sr", "sr@latin", - "sd", "sd@deva", "sk", "sl", "es", "es_MX", "sv", - "ta", "te", "th", "tr", - "uk", "ur", - "vi" }; + _("Albanian (sq)"), + _("Arabic (ar)"), + _("Armenian (hy)"), + _("Assamese (as)"), + _("Azerbaijani (az)"), + _("Basque (eu)"), + _("Belarusian (be)"), + _("Bulgarian (bg)"), + _("Bengali (bn)"), + _("Bengali/Bangladesh (bn_BD)"), + _("Bodo (brx)"), + _("Breton (br)"), + _("Catalan (ca)"), + _("Valencian Catalan (ca@valencia)"), + _("Chinese/China (zh_CN)"), + _("Chinese/Taiwan (zh_TW)"), + _("Croatian (hr)"), + _("Czech (cs)"), + _("Danish (da)"), + _("Dogri (doi)"), + _("Dutch (nl)"), + _("Dzongkha (dz)"), + _("German (de)"), + _("Greek (el)"), + _("English (en)"), + _("English/Australia (en_AU)"), + _("English/Canada (en_CA)"), + _("English/Great Britain (en_GB)"), + _("Esperanto (eo)"), + _("Estonian (et)"), + _("Farsi (fa)"), + _("Finnish (fi)"), + _("French (fr)"), + _("Galician (gl)"), + _("Gujarati (gu)"), + _("Hebrew (he)"), + _("Hindi (hi)"), + _("Hungarian (hu)"), + _("Icelandic (is)"), + _("Indonesian (id)"), + _("Irish (ga)"), + _("Italian (it)"), + _("Japanese (ja)"), + _("Kannada (kn)"), + _("Kashmiri in Perso-Arabic script (ks@aran)"), + _("Kashmiri in Devanagari script (ks@deva)"), + _("Khmer (km)"), + _("Kinyarwanda (rw)"), + _("Konkani (kok)"), + _("Konkani in Latin script (kok@latin)"), + _("Korean (ko)"), + _("Latvian (lv)"), + _("Lithuanian (lt)"), + _("Macedonian (mk)"), + _("Maithili (mai)"), + _("Malayalam (ml)"), + _("Manipuri (mni)"), + _("Manipuri in Bengali script (mni@beng)"), + _("Marathi (mr)"), + _("Mongolian (mn)"), + _("Nepali (ne)"), + _("Norwegian Bokmål (nb)"), + _("Norwegian Nynorsk (nn)"), + _("Odia (or)"), + _("Panjabi (pa)"), + _("Polish (pl)"), + _("Portuguese (pt)"), + _("Portuguese/Brazil (pt_BR)"), + _("Romanian (ro)"), + _("Russian (ru)"), + _("Sanskrit (sa)"), + _("Santali (sat)"), + _("Santali in Devanagari script (sat@deva)"), + _("Serbian (sr)"), + _("Serbian in Latin script (sr@latin)"), + _("Sindhi (sd)"), + _("Sindhi in Devanagari script (sd@deva)"), + _("Slovak (sk)"), + _("Slovenian (sl)"), + _("Spanish (es)"), + _("Spanish/Mexico (es_MX)"), + _("Swedish (sv)"), + _("Tamil (ta)"), + _("Telugu (te)"), + _("Thai (th)"), + _("Turkish (tr)"), + _("Ukrainian (uk)"), + _("Urdu (ur)"), + _("Vietnamese (vi)")}; + Glib::ustring langValues[] = { + "", "sq", "ar", "hy", "as", "az", "eu", "be", "bg", "bn", + "bn_BD", "brx", "br", "ca", "ca@valencia", "zh_CN", "zh_TW", "hr", "cs", "da", + "doi", "nl", "dz", "de", "el", "en", "en_AU", "en_CA", "en_GB", "eo", + "et", "fa", "fi", "fr", "gl", "gu", "he", "hi", "hu", "is", + "id", "ga", "it", "ja", "kn", "ks@aran", "ks@deva", "km", "rw", "kok", + "kok@latin", "ko", "lv", "lt", "mk", "mai", "ml", "mni", "mni@beng", "mr", + "mn", "ne", "nb", "nn", "or", "pa", "pl", "pt", "pt_BR", "ro", + "ru", "sa", "sat", "sat@deva", "sr", "sr@latin", "sd", "sd@deva", "sk", "sl", + "es", "es_MX", "sv", "ta", "te", "th", "tr", "uk", "ur", "vi"}; { // sorting languages according to translated name int i = 0; int j = 0; - int n = sizeof( languages ) / sizeof( Glib::ustring ); + int n = sizeof(languages) / sizeof(Glib::ustring); Glib::ustring key_language; Glib::ustring key_langValue; - for ( j = 1 ; j < n ; j++ ) { + for (j = 1; j < n; j++) { key_language = languages[j]; key_langValue = langValues[j]; - i = j-1; - while ( i >= 0 - && ( ( languages[i] > key_language - && langValues[i] != "" ) - || key_langValue == "" ) ) - { - languages[i+1] = languages[i]; - langValues[i+1] = langValues[i]; + i = j - 1; + while (i >= 0 && ((languages[i] > key_language && langValues[i] != "") || key_langValue == "")) { + languages[i + 1] = languages[i]; + langValues[i + 1] = langValues[i]; i--; } - languages[i+1] = key_language; - langValues[i+1] = key_langValue; + languages[i + 1] = key_language; + langValues[i + 1] = key_langValue; } } - _ui_languages.init( "/ui/language", languages, langValues, G_N_ELEMENTS(languages), languages[0]); - _page_ui.add_line( false, _("Language (requires restart):"), _ui_languages, "", - _("Set the language for menus and number formats"), false); + _ui_languages.init("/ui/language", languages, langValues, G_N_ELEMENTS(languages), languages[0]); + _page_ui.add_line(false, _("Language (requires restart):"), _ui_languages, "", + _("Set the language for menus and number formats"), false); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - _ui_colorsliders_top.init( _("Work-around color sliders not drawing"), "/options/workarounds/colorsontop", false); - _page_ui.add_line( false, "", _ui_colorsliders_top, "", - _("When on, will attempt to work around bugs in certain GTK themes drawing color sliders"), true); - + _ui_colorsliders_top.init(_("Work-around color sliders not drawing"), "/options/workarounds/colorsontop", false); + _page_ui.add_line(false, "", _ui_colorsliders_top, "", + _("When on, will attempt to work around bugs in certain GTK themes drawing color sliders"), true); _misc_recent.init("/options/maxrecentdocuments/value", 0.0, 1000.0, 1.0, 1.0, 1.0, true, false); - Gtk::Button* reset_recent = Gtk::manage(new Gtk::Button(_("Clear list"))); + 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)); - _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); + _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, 0.01, 500.0, 1.0, 10.0, 1.0); - _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); + _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); - _ui_partialdynamic.init( _("Enable dynamic relayout for incomplete sections"), "/options/workarounds/dynamicnotdone", false); - _page_ui.add_line( false, "", _ui_partialdynamic, "", - _("When on, will allow dynamic layout of components that are not completely finished being refactored"), true); + _ui_partialdynamic.init(_("Enable dynamic relayout for incomplete sections"), "/options/workarounds/dynamicnotdone", + false); + _page_ui.add_line( + false, "", _ui_partialdynamic, "", + _("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 (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")); + _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 */ + _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); + _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); } - _ui_yaxisdown.init( _("Origin at upper left with y-axis pointing down (requires restart)"), "/options/yaxisdown", true); - _page_ui.add_line( false, "", _ui_yaxisdown, "", - _("When off, origin is at lower left corner and y-axis points up"), true); + _ui_yaxisdown.init(_("Origin at upper left with y-axis pointing down (requires restart)"), "/options/yaxisdown", + true); + _page_ui.add_line(false, "", _ui_yaxisdown, "", _("When off, origin is at lower left corner and y-axis points up"), + true); _ui_rotationlock.init(_("Lock canvas rotation by default"), "/options/rotationlock", false); _page_ui.add_line(false, "", _ui_rotationlock, "", - _("When enabled, common actions which normally rotate the canvas no longer do so by default"), true); + _("When enabled, common actions which normally rotate the canvas no longer do so by default"), + true); - _mouse_grabsize.init("/options/grabsize/value", 1, 7, 1, 2, 3, 0); - _page_ui.add_line(false, _("_Handle size:"), _mouse_grabsize, "", - _("Set the relative size of node handles"), true); - + _page_ui.add_line(false, _("_Handle size:"), _mouse_grabsize, "", _("Set the relative size of node handles"), true); + // Theme _page_theme.add_group_header(_("Theme")); _dark_theme.init(_("Use dark theme"), "/theme/preferDarkTheme", false); @@ -1174,7 +1260,8 @@ void InkscapePreferences::initPageUI() _gtk_theme.signal_changed().connect(sigc::mem_fun(*this, &InkscapePreferences::themeChange)); } _sys_user_themes_dir_copy.init(g_build_filename(g_get_user_data_dir(), "themes", NULL), _("Open themes folder")); - _page_theme.add_line(true, _("User themes:"), _sys_user_themes_dir_copy, "", _("Location of the user’s themes"), true, Gtk::manage(new Gtk::Box())); + _page_theme.add_line(true, _("User themes:"), _sys_user_themes_dir_copy, "", _("Location of the user’s themes"), + true, Gtk::manage(new Gtk::Box())); _page_theme.add_line(true, "", _dark_theme, "", _("Use dark theme"), true); if (dark_themes[current_theme]) { @@ -1189,7 +1276,7 @@ void InkscapePreferences::initPageUI() _page_theme.add_group_header(_("Icons")); { using namespace Inkscape::IO::Resource; - auto folders = get_foldernames(ICONS, { "application" }); + auto folders = get_foldernames(ICONS, {"application"}); std::vector<Glib::ustring> labels; std::vector<Glib::ustring> values; Glib::ustring default_icon_theme = prefs->getString("/theme/defaultIconTheme"); @@ -1224,8 +1311,9 @@ void InkscapePreferences::initPageUI() _page_theme.add_line(false, _("Change icon theme:"), _icon_theme, "", "", false); _icon_theme.signal_changed().connect(sigc::mem_fun(*this, &InkscapePreferences::symbolicThemeCheck)); _sys_user_icons_dir_copy.init((char const *)IO::Resource::get_path(IO::Resource::USER, IO::Resource::ICONS, ""), - _("Open icons folder")); - _page_theme.add_line(true, _("User icons: "), _sys_user_icons_dir_copy, "", _("Location of the user’s icons"), true, Gtk::manage(new Gtk::Box())); + _("Open icons folder")); + _page_theme.add_line(true, _("User icons: "), _sys_user_icons_dir_copy, "", _("Location of the user’s icons"), + true, Gtk::manage(new Gtk::Box())); } Glib::ustring themeiconname = prefs->getString("/theme/iconTheme"); _symbolic_icons.init(_("Use symbolic icons"), "/theme/symbolicIcons", false); @@ -1257,26 +1345,23 @@ void InkscapePreferences::initPageUI() /* _complementary_colors = Gtk::manage(new Gtk::Image()); */ Gtk::Box *icon_buttons = Gtk::manage(new Gtk::Box()); icon_buttons->pack_start(_symbolic_base_color, true, true, 4); - _page_theme.add_line(false, "", *icon_buttons, _("Icon color"), - _("Base color for icons"), false); + _page_theme.add_line(false, "", *icon_buttons, _("Icon color"), _("Base color for icons"), false); Gtk::Box *icon_buttons_hight = Gtk::manage(new Gtk::Box()); icon_buttons_hight->pack_start(_symbolic_success_color, true, true, 4); icon_buttons_hight->pack_start(_symbolic_warning_color, true, true, 4); icon_buttons_hight->pack_start(_symbolic_error_color, true, true, 4); /* icon_buttons_hight->pack_start(*_complementary_colors, true, true, 4); */ _page_theme.add_line(false, "", *icon_buttons_hight, _("Highlights"), - _("Highlight colors supported by some symbolic icon themes"), - false); + _("Highlight colors supported by some symbolic icon themes"), false); Gtk::Box *icon_buttons_def = Gtk::manage(new Gtk::Box()); resetIconsColors(); changeIconsColor(0xffffffff); - _page_theme.add_line(false, "", *icon_buttons_def, "", - _("Reset theme colors for some symbolic icon themes"), + _page_theme.add_line(false, "", *icon_buttons_def, "", _("Reset theme colors for some symbolic icon themes"), false); { - Glib::ustring sizeLabels[] = { C_("Icon size", "Larger"), C_("Icon size", "Large"), C_("Icon size", "Small"), - C_("Icon size", "Smaller") }; - int sizeValues[] = { 3, 2, 0, 1 }; + Glib::ustring sizeLabels[] = {C_("Icon size", "Larger"), C_("Icon size", "Large"), C_("Icon size", "Small"), + C_("Icon size", "Smaller")}; + int sizeValues[] = {3, 2, 0, 1}; // "Larger" is 3 to not break existing preference files. Should fix in GTK3 _misc_small_tools.init("/toolbox/tools/small", sizeLabels, sizeValues, G_N_ELEMENTS(sizeLabels), 0); @@ -1295,159 +1380,168 @@ void InkscapePreferences::initPageUI() Glib::ustring menu_icons_labels[] = {_("Yes"), _("No"), _("Theme decides")}; int menu_icons_values[] = {1, -1, 0}; _menu_icons.init("/theme/menuIcons", menu_icons_labels, menu_icons_values, G_N_ELEMENTS(menu_icons_labels), 0); - _page_theme.add_line(false, _("Show icons in menus:"), _menu_icons, "", - _("You can either enable or disable all icons in menus. By default, the setting for the 'show-icons' attribute in the 'menus.xml' file determines whether to display icons in menus. (requires restart)"), false); + _page_theme.add_line( + false, _("Show icons in menus:"), _menu_icons, "", + _("You can either enable or disable all icons in menus. By default, the setting for the 'show-icons' " + "attribute in the 'menus.xml' file determines whether to display icons in menus. (requires restart)"), + false); } this->AddPage(_page_theme, _("Themeing"), iter_ui, PREFS_PAGE_UI_THEME); symbolicThemeCheck(); // Windows - _win_save_geom.init ( _("Save and restore window geometry for each document"), "/options/savewindowgeometry/value", PREFS_WINDOW_GEOMETRY_FILE, true, nullptr); - _win_save_geom_prefs.init ( _("Remember and use last window's geometry"), "/options/savewindowgeometry/value", PREFS_WINDOW_GEOMETRY_LAST, false, &_win_save_geom); - _win_save_geom_off.init ( _("Don't save window geometry"), "/options/savewindowgeometry/value", PREFS_WINDOW_GEOMETRY_NONE, false, &_win_save_geom); - - _win_save_dialog_pos_on.init ( _("Save and restore dialogs status"), "/options/savedialogposition/value", 1, true, nullptr); - _win_save_dialog_pos_off.init ( _("Don't save dialogs status"), "/options/savedialogposition/value", 0, false, &_win_save_dialog_pos_on); - - _win_dockable.init ( _("Dockable"), "/options/dialogtype/value", 1, true, nullptr); - _win_floating.init ( _("Floating"), "/options/dialogtype/value", 0, false, &_win_dockable); - - - _win_native.init ( _("Native open/save dialogs"), "/options/desktopintegration/value", 1, true, nullptr); - _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_ontop_none.init ( C_("Dialog on top", "None"), "/options/transientpolicy/value", 0, false, nullptr); - _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); + _win_save_geom.init(_("Save and restore window geometry for each document"), "/options/savewindowgeometry/value", + PREFS_WINDOW_GEOMETRY_FILE, true, nullptr); + _win_save_geom_prefs.init(_("Remember and use last window's geometry"), "/options/savewindowgeometry/value", + PREFS_WINDOW_GEOMETRY_LAST, false, &_win_save_geom); + _win_save_geom_off.init(_("Don't save window geometry"), "/options/savewindowgeometry/value", + PREFS_WINDOW_GEOMETRY_NONE, false, &_win_save_geom); + + _win_save_dialog_pos_on.init(_("Save and restore dialogs status"), "/options/savedialogposition/value", 1, true, + nullptr); + _win_save_dialog_pos_off.init(_("Don't save dialogs status"), "/options/savedialogposition/value", 0, false, + &_win_save_dialog_pos_on); + + _win_dockable.init(_("Dockable"), "/options/dialogtype/value", 1, true, nullptr); + _win_floating.init(_("Floating"), "/options/dialogtype/value", 0, false, &_win_dockable); + + _win_native.init(_("Native open/save dialogs"), "/options/desktopintegration/value", 1, true, nullptr); + _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_ontop_none.init(C_("Dialog on top", "None"), "/options/transientpolicy/value", 0, false, nullptr); + _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[] = {C_("Window size", "Default"), - C_("Window size", "Small"), - C_("Window size", "Large"), - C_("Window size", "Maximized")}; - int defaultSizeValues[] = {PREFS_WINDOW_SIZE_NATURAL, - PREFS_WINDOW_SIZE_SMALL, - PREFS_WINDOW_SIZE_LARGE, + Glib::ustring defaultSizeLabels[] = {C_("Window size", "Default"), C_("Window size", "Small"), + C_("Window size", "Large"), C_("Window size", "Maximized")}; + int defaultSizeValues[] = {PREFS_WINDOW_SIZE_NATURAL, PREFS_WINDOW_SIZE_SMALL, PREFS_WINDOW_SIZE_LARGE, PREFS_WINDOW_SIZE_MAXIMIZED}; - _win_default_size.init( "/options/defaultwindowsize/value", defaultSizeLabels, defaultSizeValues, G_N_ELEMENTS(defaultSizeLabels), PREFS_WINDOW_SIZE_NATURAL); - _page_windows.add_line( false, _("Default window size:"), _win_default_size, "", - _("Set the default window size"), false); + _win_default_size.init("/options/defaultwindowsize/value", defaultSizeLabels, defaultSizeValues, + G_N_ELEMENTS(defaultSizeLabels), PREFS_WINDOW_SIZE_NATURAL); + _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")); - _page_windows.add_line( true, "", _win_save_geom_prefs, "", - _("Remember and use the last window's geometry (saves geometry to user preferences)")); - _page_windows.add_line( true, "", _win_save_geom, "", - _("Save and restore window geometry for each document (saves geometry in the document)")); - - _page_windows.add_group_header( _("Saving dialogs' status")); - _page_windows.add_line( true, "", _win_save_dialog_pos_off, "", - _("Don't save dialogs' status")); - _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")); - _page_windows.add_line( true, "", _win_floating, "", - _("Floating")); + _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")); + _page_windows.add_line(true, "", _win_save_geom_prefs, "", + _("Remember and use the last window's geometry (saves geometry to user preferences)")); + _page_windows.add_line(true, "", _win_save_geom, "", + _("Save and restore window geometry for each document (saves geometry in the document)")); + + _page_windows.add_group_header(_("Saving dialogs' status")); + _page_windows.add_line(true, "", _win_save_dialog_pos_off, "", _("Don't save dialogs' status")); + _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")); + _page_windows.add_line(true, "", _win_floating, "", _("Floating")); #ifdef _WIN32 - _page_windows.add_group_header( _("Desktop integration")); - _page_windows.add_line( true, "", _win_native, "", - _("Use Windows like open and save dialogs")); - _page_windows.add_line( true, "", _win_gtk, "", - _("Use GTK open and save dialogs ")); + _page_windows.add_group_header(_("Desktop integration")); + _page_windows.add_line(true, "", _win_native, "", _("Use Windows like open and save dialogs")); + _page_windows.add_line(true, "", _win_gtk, "", _("Use GTK open and save dialogs ")); #endif #ifndef _WIN32 // non-Win32 special code to enable transient dialogs - _page_windows.add_group_header( _("Dialogs on top:")); - - _page_windows.add_line( true, "", _win_ontop_none, "", - _("Dialogs are treated as regular windows")); - _page_windows.add_line( true, "", _win_ontop_normal, "", - _("Dialogs stay on top of document windows")); - _page_windows.add_line( true, "", _win_ontop_agressive, "", - _("Same as Normal but may work better with some window managers")); + _page_windows.add_group_header(_("Dialogs on top:")); + + _page_windows.add_line(true, "", _win_ontop_none, "", _("Dialogs are treated as regular windows")); + _page_windows.add_line(true, "", _win_ontop_normal, "", _("Dialogs stay on top of document windows")); + _page_windows.add_line(true, "", _win_ontop_agressive, "", + _("Same as Normal but may work better with some window managers")); #endif - _page_windows.add_group_header( _("Miscellaneous")); + _page_windows.add_group_header(_("Miscellaneous")); #ifndef _WIN32 // FIXME: Temporary Win32 special code to enable transient dialogs - _page_windows.add_line( true, "", _win_hide_task, "", - _("Whether dialog windows are to be hidden in the window manager taskbar")); + _page_windows.add_line(true, "", _win_hide_task, "", + _("Whether dialog windows are to be hidden in the window manager taskbar")); #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_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.")); this->AddPage(_page_windows, _("Windows"), iter_ui, PREFS_PAGE_UI_WINDOWS); // Grids - _page_grids.add_group_header( _("Line color when zooming out")); - - _grids_no_emphasize_on_zoom.init( _("Minor grid line color"), "/options/grids/no_emphasize_when_zoomedout", 1, true, nullptr); - _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")); - - _page_grids.add_line( true, "", _grids_notebook, "", "", false); - _grids_notebook.append_page(_grids_xy, CanvasGrid::getName( GRID_RECTANGULAR )); - _grids_notebook.append_page(_grids_axonom, CanvasGrid::getName( GRID_AXONOMETRIC )); - _grids_xy_units.init("/options/grids/xy/units"); - _grids_xy.add_line( false, _("Grid units:"), _grids_xy_units, "", "", false); - _grids_xy_origin_x.init("/options/grids/xy/origin_x", -10000.0, 10000.0, 0.1, 1.0, 0.0, false, false); - _grids_xy_origin_y.init("/options/grids/xy/origin_y", -10000.0, 10000.0, 0.1, 1.0, 0.0, false, false); - _grids_xy_origin_x.set_digits(5); - _grids_xy_origin_y.set_digits(5); - _grids_xy.add_line( false, _("Origin X:"), _grids_xy_origin_x, "", _("X coordinate of grid origin"), false); - _grids_xy.add_line( false, _("Origin Y:"), _grids_xy_origin_y, "", _("Y coordinate of grid origin"), false); - _grids_xy_spacing_x.init("/options/grids/xy/spacing_x", -10000.0, 10000.0, 0.1, 1.0, 1.0, false, false); - _grids_xy_spacing_y.init("/options/grids/xy/spacing_y", -10000.0, 10000.0, 0.1, 1.0, 1.0, false, false); - _grids_xy_spacing_x.set_digits(5); - _grids_xy_spacing_y.set_digits(5); - _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(_("Minor grid line color:"), "/options/grids/xy/color", GRID_DEFAULT_COLOR); - _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", GRID_DEFAULT_EMPCOLOR); - _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); - _grids_xy.add_line( false, _("Major grid line every:"), _grids_xy_empspacing, "", "", false); - _grids_xy_dotted.init( _("Show dots instead of lines"), "/options/grids/xy/dotted", false); - _grids_xy.add_line( false, "", _grids_xy_dotted, "", _("If set, display dots at gridpoints instead of gridlines"), false); + _page_grids.add_group_header(_("Line color when zooming out")); + + _grids_no_emphasize_on_zoom.init(_("Minor grid line color"), "/options/grids/no_emphasize_when_zoomedout", 1, true, + nullptr); + _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")); + + _page_grids.add_line(true, "", _grids_notebook, "", "", false); + _grids_notebook.append_page(_grids_xy, CanvasGrid::getName(GRID_RECTANGULAR)); + _grids_notebook.append_page(_grids_axonom, CanvasGrid::getName(GRID_AXONOMETRIC)); + _grids_xy_units.init("/options/grids/xy/units"); + _grids_xy.add_line(false, _("Grid units:"), _grids_xy_units, "", "", false); + _grids_xy_origin_x.init("/options/grids/xy/origin_x", -10000.0, 10000.0, 0.1, 1.0, 0.0, false, false); + _grids_xy_origin_y.init("/options/grids/xy/origin_y", -10000.0, 10000.0, 0.1, 1.0, 0.0, false, false); + _grids_xy_origin_x.set_digits(5); + _grids_xy_origin_y.set_digits(5); + _grids_xy.add_line(false, _("Origin X:"), _grids_xy_origin_x, "", _("X coordinate of grid origin"), false); + _grids_xy.add_line(false, _("Origin Y:"), _grids_xy_origin_y, "", _("Y coordinate of grid origin"), false); + _grids_xy_spacing_x.init("/options/grids/xy/spacing_x", -10000.0, 10000.0, 0.1, 1.0, 1.0, false, false); + _grids_xy_spacing_y.init("/options/grids/xy/spacing_y", -10000.0, 10000.0, 0.1, 1.0, 1.0, false, false); + _grids_xy_spacing_x.set_digits(5); + _grids_xy_spacing_y.set_digits(5); + _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(_("Minor grid line color:"), "/options/grids/xy/color", GRID_DEFAULT_COLOR); + _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", GRID_DEFAULT_EMPCOLOR); + _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); + _grids_xy.add_line(false, _("Major grid line every:"), _grids_xy_empspacing, "", "", false); + _grids_xy_dotted.init(_("Show dots instead of lines"), "/options/grids/xy/dotted", false); + _grids_xy.add_line(false, "", _grids_xy_dotted, "", _("If set, display dots at gridpoints instead of gridlines"), + false); // CanvasAxonomGrid properties: - _grids_axonom_units.init("/options/grids/axonom/units"); - _grids_axonom.add_line( false, _("Grid units:"), _grids_axonom_units, "", "", false); - _grids_axonom_origin_x.init("/options/grids/axonom/origin_x", -10000.0, 10000.0, 0.1, 1.0, 0.0, false, false); - _grids_axonom_origin_y.init("/options/grids/axonom/origin_y", -10000.0, 10000.0, 0.1, 1.0, 0.0, false, false); - _grids_axonom_origin_x.set_digits(5); - _grids_axonom_origin_y.set_digits(5); - _grids_axonom.add_line( false, _("Origin X:"), _grids_axonom_origin_x, "", _("X coordinate of grid origin"), false); - _grids_axonom.add_line( false, _("Origin Y:"), _grids_axonom_origin_y, "", _("Y coordinate of grid origin"), false); - _grids_axonom_spacing_y.init("/options/grids/axonom/spacing_y", -10000.0, 10000.0, 0.1, 1.0, 1.0, false, false); - _grids_axonom_spacing_y.set_digits(5); - _grids_axonom.add_line( false, _("Spacing Y:"), _grids_axonom_spacing_y, "", _("Base length of z-axis"), false); - _grids_axonom_angle_x.init("/options/grids/axonom/angle_x", -360.0, 360.0, 1.0, 10.0, 30.0, false, false); - _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(_("Minor grid line color:"), "/options/grids/axonom/color", GRID_DEFAULT_COLOR); - _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", GRID_DEFAULT_EMPCOLOR); - _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); + _grids_axonom_units.init("/options/grids/axonom/units"); + _grids_axonom.add_line(false, _("Grid units:"), _grids_axonom_units, "", "", false); + _grids_axonom_origin_x.init("/options/grids/axonom/origin_x", -10000.0, 10000.0, 0.1, 1.0, 0.0, false, false); + _grids_axonom_origin_y.init("/options/grids/axonom/origin_y", -10000.0, 10000.0, 0.1, 1.0, 0.0, false, false); + _grids_axonom_origin_x.set_digits(5); + _grids_axonom_origin_y.set_digits(5); + _grids_axonom.add_line(false, _("Origin X:"), _grids_axonom_origin_x, "", _("X coordinate of grid origin"), false); + _grids_axonom.add_line(false, _("Origin Y:"), _grids_axonom_origin_y, "", _("Y coordinate of grid origin"), false); + _grids_axonom_spacing_y.init("/options/grids/axonom/spacing_y", -10000.0, 10000.0, 0.1, 1.0, 1.0, false, false); + _grids_axonom_spacing_y.set_digits(5); + _grids_axonom.add_line(false, _("Spacing Y:"), _grids_axonom_spacing_y, "", _("Base length of z-axis"), false); + _grids_axonom_angle_x.init("/options/grids/axonom/angle_x", -360.0, 360.0, 1.0, 10.0, 30.0, false, false); + _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(_("Minor grid line color:"), "/options/grids/axonom/color", GRID_DEFAULT_COLOR); + _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", GRID_DEFAULT_EMPCOLOR); + _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); @@ -1455,40 +1549,41 @@ void InkscapePreferences::initPageUI() } #if defined(HAVE_LIBLCMS2) -static void profileComboChanged( Gtk::ComboBoxText* combo ) +static void profileComboChanged(Gtk::ComboBoxText *combo) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int rowNum = combo->get_active_row_number(); - if ( rowNum < 1 ) { + if (rowNum < 1) { prefs->setString("/options/displayprofile/uri", ""); } else { Glib::ustring active = combo->get_active_text(); Glib::ustring path = CMSSystem::getPathForProfile(active); - if ( !path.empty() ) { + if (!path.empty()) { prefs->setString("/options/displayprofile/uri", path); } } } -static void proofComboChanged( Gtk::ComboBoxText* combo ) +static void proofComboChanged(Gtk::ComboBoxText *combo) { Glib::ustring active = combo->get_active_text(); Glib::ustring path = CMSSystem::getPathForProfile(active); - if ( !path.empty() ) { + if (!path.empty()) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setString("/options/softproof/uri", path); } } -static void gamutColorChanged( Gtk::ColorButton* btn ) { +static void gamutColorChanged(Gtk::ColorButton *btn) +{ auto rgba = btn->get_rgba(); auto r = rgba.get_red_u(); auto g = rgba.get_green_u(); auto b = rgba.get_blue_u(); - gchar* tmp = g_strdup_printf("#%02x%02x%02x", (r >> 8), (g >> 8), (b >> 8) ); + gchar *tmp = g_strdup_printf("#%02x%02x%02x", (r >> 8), (g >> 8), (b >> 8)); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setString("/options/softproof/gamutcolor", tmp); @@ -1500,280 +1595,350 @@ void InkscapePreferences::initPageIO() { Gtk::TreeModel::iterator iter_io = this->AddPage(_page_io, _("Input/Output"), PREFS_PAGE_IO); - _save_use_current_dir.init( _("Use current directory for \"Save As ...\""), "/dialogs/save_as/use_current_dir", true); - _page_io.add_line( false, "", _save_use_current_dir, "", - _("When this option is on, the \"Save as...\" and \"Save a Copy...\" dialogs will always open in the directory where the currently open document is; when it's off, each will open in the directory where you last saved a file using it"), true); - - _misc_comment.init( _("Add label comments to printing output"), "/printing/debug/show-label-comments", false); - _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); + _save_use_current_dir.init(_("Use current directory for \"Save As ...\""), "/dialogs/save_as/use_current_dir", + true); + _page_io.add_line(false, "", _save_use_current_dir, "", + _("When this option is on, the \"Save as...\" and \"Save a Copy...\" dialogs will always open in " + "the directory where the currently open document is; when it's off, each will open in the " + "directory where you last saved a file using it"), + true); + + _misc_comment.init(_("Add label comments to printing output"), "/printing/debug/show-label-comments", false); + _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 (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"), - _("Maximum mouse drag (in screen pixels) which is considered a click, not a drag"), false); - - _mouse_use_ext_input.init( _("Use pressure-sensitive tablet (requires restart)"), "/options/useextinput/value", true); - _page_mouse.add_line(false, "",_mouse_use_ext_input, "", - _("Use the capabilities of a tablet or other pressure-sensitive device. Disable this only if you have problems with the tablet (you can still use it as a mouse)")); - - _mouse_switch_on_ext_input.init( _("Switch tool based on tablet device (requires restart)"), "/options/switchonextinput/value", false); - _page_mouse.add_line(false, "",_mouse_switch_on_ext_input, "", - _("Change tool as different devices are used on the tablet (pen, eraser, mouse)")); + _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 (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"), + _("Maximum mouse drag (in screen pixels) which is considered a click, not a drag"), false); + + _mouse_use_ext_input.init(_("Use pressure-sensitive tablet (requires restart)"), "/options/useextinput/value", + true); + _page_mouse.add_line(false, "", _mouse_use_ext_input, "", + _("Use the capabilities of a tablet or other pressure-sensitive device. Disable this only if " + "you have problems with the tablet (you can still use it as a mouse)")); + + _mouse_switch_on_ext_input.init(_("Switch tool based on tablet device (requires restart)"), + "/options/switchonextinput/value", false); + _page_mouse.add_line(false, "", _mouse_switch_on_ext_input, "", + _("Change tool as different devices are used on the tablet (pen, eraser, mouse)")); this->AddPage(_page_mouse, _("Input devices"), iter_io, PREFS_PAGE_IO_MOUSE); // SVG output options - _svgoutput_usenamedcolors.init( _("Use named colors"), "/options/svgoutput/usenamedcolors", false); - _page_svgoutput.add_line( false, "", _svgoutput_usenamedcolors, "", _("If set, write the CSS name of the color when available (e.g. 'red' or 'magenta') instead of the numeric value"), false); + _svgoutput_usenamedcolors.init(_("Use named colors"), "/options/svgoutput/usenamedcolors", false); + _page_svgoutput.add_line(false, "", _svgoutput_usenamedcolors, "", + _("If set, write the CSS name of the color when available (e.g. 'red' or 'magenta') " + "instead of the numeric value"), + false); - _page_svgoutput.add_group_header( _("XML formatting")); + _page_svgoutput.add_group_header(_("XML formatting")); - _svgoutput_inlineattrs.init( _("Inline attributes"), "/options/svgoutput/inlineattrs", false); - _page_svgoutput.add_line( true, "", _svgoutput_inlineattrs, "", _("Put attributes on the same line as the element tag"), false); + _svgoutput_inlineattrs.init(_("Inline attributes"), "/options/svgoutput/inlineattrs", false); + _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")); + _page_svgoutput.add_group_header(_("Path data")); 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_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); + _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); - _page_svgoutput.add_group_header( _("Numbers")); + _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 */ /* Add incorrect style properties options */ - _page_svgoutput.add_group_header( _("Improper Attributes Actions")); + _page_svgoutput.add_group_header(_("Improper Attributes Actions")); - _svgoutput_attrwarn.init( _("Print warnings"), "/options/svgoutput/incorrect_attributes_warn", true); - _page_svgoutput.add_line( true, "", _svgoutput_attrwarn, "", _("Print warning if invalid or non-useful attributes found. Database files located in inkscape_data_dir/attributes."), false); - _svgoutput_attrremove.init( _("Remove attributes"), "/options/svgoutput/incorrect_attributes_remove", false); - _page_svgoutput.add_line( true, "", _svgoutput_attrremove, "", _("Delete invalid or non-useful attributes from element tag"), false); + _svgoutput_attrwarn.init(_("Print warnings"), "/options/svgoutput/incorrect_attributes_warn", true); + _page_svgoutput.add_line(true, "", _svgoutput_attrwarn, "", + _("Print warning if invalid or non-useful attributes found. Database files located in " + "inkscape_data_dir/attributes."), + false); + _svgoutput_attrremove.init(_("Remove attributes"), "/options/svgoutput/incorrect_attributes_remove", false); + _page_svgoutput.add_line(true, "", _svgoutput_attrremove, "", + _("Delete invalid or non-useful attributes from element tag"), false); /* Add incorrect style properties options */ - _page_svgoutput.add_group_header( _("Inappropriate Style Properties Actions")); - - _svgoutput_stylepropwarn.init( _("Print warnings"), "/options/svgoutput/incorrect_style_properties_warn", true); - _page_svgoutput.add_line( true, "", _svgoutput_stylepropwarn, "", _("Print warning if inappropriate style properties found (i.e. 'font-family' set on a <rect>). Database files located in inkscape_data_dir/attributes."), false); - _svgoutput_stylepropremove.init( _("Remove style properties"), "/options/svgoutput/incorrect_style_properties_remove", false); - _page_svgoutput.add_line( true, "", _svgoutput_stylepropremove, "", _("Delete inappropriate style properties"), false); + _page_svgoutput.add_group_header(_("Inappropriate Style Properties Actions")); + + _svgoutput_stylepropwarn.init(_("Print warnings"), "/options/svgoutput/incorrect_style_properties_warn", true); + _page_svgoutput.add_line(true, "", _svgoutput_stylepropwarn, "", + _("Print warning if inappropriate style properties found (i.e. 'font-family' set on a " + "<rect>). Database files located in inkscape_data_dir/attributes."), + false); + _svgoutput_stylepropremove.init(_("Remove style properties"), + "/options/svgoutput/incorrect_style_properties_remove", false); + _page_svgoutput.add_line(true, "", _svgoutput_stylepropremove, "", _("Delete inappropriate style properties"), + false); /* Add default or inherited style properties options */ - _page_svgoutput.add_group_header( _("Non-useful Style Properties Actions")); - - _svgoutput_styledefaultswarn.init( _("Print warnings"), "/options/svgoutput/style_defaults_warn", true); - _page_svgoutput.add_line( true, "", _svgoutput_styledefaultswarn, "", _("Print warning if redundant style properties found (i.e. if a property has the default value and a different value is not inherited or if value is the same as would be inherited). Database files located in inkscape_data_dir/attributes."), false); - _svgoutput_styledefaultsremove.init( _("Remove style properties"), "/options/svgoutput/style_defaults_remove", false); - _page_svgoutput.add_line( true, "", _svgoutput_styledefaultsremove, "", _("Delete redundant style properties"), false); - - _page_svgoutput.add_group_header( _("Check Attributes and Style Properties on")); - - _svgoutput_check_reading.init( _("Reading"), "/options/svgoutput/check_on_reading", false); - _page_svgoutput.add_line( true, "", _svgoutput_check_reading, "", _("Check attributes and style properties on reading in SVG files (including those internal to Inkscape which will slow down startup)"), false); - _svgoutput_check_editing.init( _("Editing"), "/options/svgoutput/check_on_editing", false); - _page_svgoutput.add_line( true, "", _svgoutput_check_editing, "", _("Check attributes and style properties while editing SVG files (may slow down Inkscape, mostly useful for debugging)"), false); - _svgoutput_check_writing.init( _("Writing"), "/options/svgoutput/check_on_writing", true); - _page_svgoutput.add_line( true, "", _svgoutput_check_writing, "", _("Check attributes and style properties on writing out SVG files"), false); + _page_svgoutput.add_group_header(_("Non-useful Style Properties Actions")); + + _svgoutput_styledefaultswarn.init(_("Print warnings"), "/options/svgoutput/style_defaults_warn", true); + _page_svgoutput.add_line(true, "", _svgoutput_styledefaultswarn, "", + _("Print warning if redundant style properties found (i.e. if a property has the default " + "value and a different value is not inherited or if value is the same as would be " + "inherited). Database files located in inkscape_data_dir/attributes."), + false); + _svgoutput_styledefaultsremove.init(_("Remove style properties"), "/options/svgoutput/style_defaults_remove", + false); + _page_svgoutput.add_line(true, "", _svgoutput_styledefaultsremove, "", _("Delete redundant style properties"), + false); + + _page_svgoutput.add_group_header(_("Check Attributes and Style Properties on")); + + _svgoutput_check_reading.init(_("Reading"), "/options/svgoutput/check_on_reading", false); + _page_svgoutput.add_line(true, "", _svgoutput_check_reading, "", + _("Check attributes and style properties on reading in SVG files (including those " + "internal to Inkscape which will slow down startup)"), + false); + _svgoutput_check_editing.init(_("Editing"), "/options/svgoutput/check_on_editing", false); + _page_svgoutput.add_line(true, "", _svgoutput_check_editing, "", + _("Check attributes and style properties while editing SVG files (may slow down Inkscape, " + "mostly useful for debugging)"), + false); + _svgoutput_check_writing.init(_("Writing"), "/options/svgoutput/check_on_writing", true); + _page_svgoutput.add_line(true, "", _svgoutput_check_writing, "", + _("Check attributes and style properties on writing out SVG files"), false); this->AddPage(_page_svgoutput, _("SVG output"), iter_io, PREFS_PAGE_IO_SVGOUTPUT); // SVG Export Options ========================================== // SVG 2 Fallbacks - _page_svgexport.add_group_header( _("SVG 2")); - _svgexport_insert_text_fallback.init( _("Insert SVG 1.1 fallback in text."), "/options/svgexport/text_insertfallback", true ); - _svgexport_insert_mesh_polyfill.init( _("Insert JavaScript code for mesh gradients."), "/options/svgexport/mesh_insertpolyfill", true ); - _svgexport_insert_hatch_polyfill.init( _("Insert JavaScript code for SVG2 hatches."), "/options/svgexport/hatch_insertpolyfill", true ); - - _page_svgexport.add_line( false, "", _svgexport_insert_text_fallback, "", _("Adds fallback options for non-SVG 2 renderers."), false); - _page_svgexport.add_line( false, "", _svgexport_insert_mesh_polyfill, "", _("Adds a JavaScript polyfill for rendering meshes in web browsers."), false); - _page_svgexport.add_line( false, "", _svgexport_insert_hatch_polyfill, "", _("Adds a JavaScript polyfill for rendering hatches in web browsers."), false); + _page_svgexport.add_group_header(_("SVG 2")); + _svgexport_insert_text_fallback.init(_("Insert SVG 1.1 fallback in text."), + "/options/svgexport/text_insertfallback", true); + _svgexport_insert_mesh_polyfill.init(_("Insert JavaScript code for mesh gradients."), + "/options/svgexport/mesh_insertpolyfill", true); + _svgexport_insert_hatch_polyfill.init(_("Insert JavaScript code for SVG2 hatches."), + "/options/svgexport/hatch_insertpolyfill", true); + + _page_svgexport.add_line(false, "", _svgexport_insert_text_fallback, "", + _("Adds fallback options for non-SVG 2 renderers."), false); + _page_svgexport.add_line(false, "", _svgexport_insert_mesh_polyfill, "", + _("Adds a JavaScript polyfill for rendering meshes in web browsers."), false); + _page_svgexport.add_line(false, "", _svgexport_insert_hatch_polyfill, "", + _("Adds a JavaScript polyfill for rendering hatches in web browsers."), false); // SVG Export Options (SVG 2 -> SVG 1) - _page_svgexport.add_group_header( _("SVG 2 to SVG 1.1")); - - _svgexport_remove_marker_auto_start_reverse.init( _("Use correct marker direction in SVG 1.1 renderers."), "/options/svgexport/marker_autostartreverse", false); - _svgexport_remove_marker_context_paint.init( _("Use correct marker colors in SVG 1.1 renderers."), "/options/svgexport/marker_contextpaint", false); - - _page_svgexport.add_line( false, "", _svgexport_remove_marker_auto_start_reverse, "", _("SVG 2 allows markers to automatically be reversed at the start of a path with 'auto_start_reverse'. This adds a rotated duplicate of the marker's definition."), false); - _page_svgexport.add_line( false, "", _svgexport_remove_marker_context_paint, "", _("SVG 2 allows markers to automatically match the stroke color by using 'context_paint' or 'context_fill'. This adjusts the markers own colors."), false); + _page_svgexport.add_group_header(_("SVG 2 to SVG 1.1")); + + _svgexport_remove_marker_auto_start_reverse.init(_("Use correct marker direction in SVG 1.1 renderers."), + "/options/svgexport/marker_autostartreverse", false); + _svgexport_remove_marker_context_paint.init(_("Use correct marker colors in SVG 1.1 renderers."), + "/options/svgexport/marker_contextpaint", false); + + _page_svgexport.add_line(false, "", _svgexport_remove_marker_auto_start_reverse, "", + _("SVG 2 allows markers to automatically be reversed at the start of a path with " + "'auto_start_reverse'. This adds a rotated duplicate of the marker's definition."), + false); + _page_svgexport.add_line(false, "", _svgexport_remove_marker_context_paint, "", + _("SVG 2 allows markers to automatically match the stroke color by using 'context_paint' " + "or 'context_fill'. This adjusts the markers own colors."), + false); this->AddPage(_page_svgexport, _("SVG export"), iter_io, PREFS_PAGE_IO_SVGEXPORT); - // CMS options Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int const numIntents = 4; /* TRANSLATORS: see http://www.newsandtech.com/issues/2004/03-04/pt/03-04_rendering.htm */ - Glib::ustring intentLabels[numIntents] = {_("Perceptual"), _("Relative Colorimetric"), _("Saturation"), _("Absolute Colorimetric")}; + Glib::ustring intentLabels[numIntents] = {_("Perceptual"), _("Relative Colorimetric"), _("Saturation"), + _("Absolute Colorimetric")}; int intentValues[numIntents] = {0, 1, 2, 3}; #if !defined(HAVE_LIBLCMS2) - Gtk::Label* lbl = new Gtk::Label(_("(Note: Color management has been disabled in this build)")); - _page_cms.add_line( false, "", *lbl, "", "", true); + Gtk::Label *lbl = new Gtk::Label(_("(Note: Color management has been disabled in this build)")); + _page_cms.add_line(false, "", *lbl, "", "", true); #endif // !defined(HAVE_LIBLCMS2) - _page_cms.add_group_header( _("Display adjustment")); + _page_cms.add_group_header(_("Display adjustment")); Glib::ustring tmpStr; - for (auto &profile: ColorProfile::getBaseProfileDirs()) { - gchar* part = g_strdup_printf( "\n%s", profile.filename.c_str() ); + for (auto &profile : ColorProfile::getBaseProfileDirs()) { + gchar *part = g_strdup_printf("\n%s", profile.filename.c_str()); tmpStr += part; g_free(part); } - gchar* profileTip = g_strdup_printf(_("The ICC profile to use to calibrate display output.\nSearched directories:%s"), tmpStr.c_str()); - _page_cms.add_line( true, _("Display profile:"), _cms_display_profile, "", - profileTip, false); + gchar *profileTip = g_strdup_printf( + _("The ICC profile to use to calibrate display output.\nSearched directories:%s"), tmpStr.c_str()); + _page_cms.add_line(true, _("Display profile:"), _cms_display_profile, "", profileTip, false); g_free(profileTip); profileTip = nullptr; - _cms_from_display.init( _("Retrieve profile from display"), "/options/displayprofile/from_display", false); - _page_cms.add_line( true, "", _cms_from_display, "", + _cms_from_display.init(_("Retrieve profile from display"), "/options/displayprofile/from_display", false); + _page_cms.add_line(true, "", _cms_from_display, "", #ifdef GDK_WINDOWING_X11 - _("Retrieve profiles from those attached to displays via XICC"), false); + _("Retrieve profiles from those attached to displays via XICC"), false); #else - _("Retrieve profiles from those attached to displays"), false); + _("Retrieve profiles from those attached to displays"), false); #endif // GDK_WINDOWING_X11 - _cms_intent.init("/options/displayprofile/intent", intentLabels, intentValues, numIntents, 0); - _page_cms.add_line( true, _("Display rendering intent:"), _cms_intent, "", - _("The rendering intent to use to calibrate display output"), false); + _page_cms.add_line(true, _("Display rendering intent:"), _cms_intent, "", + _("The rendering intent to use to calibrate display output"), false); - _page_cms.add_group_header( _("Proofing")); + _page_cms.add_group_header(_("Proofing")); - _cms_softproof.init( _("Simulate output on screen"), "/options/softproof/enable", false); - _page_cms.add_line( true, "", _cms_softproof, "", - _("Simulates output of target device"), false); + _cms_softproof.init(_("Simulate output on screen"), "/options/softproof/enable", false); + _page_cms.add_line(true, "", _cms_softproof, "", _("Simulates output of target device"), false); - _cms_gamutwarn.init( _("Mark out of gamut colors"), "/options/softproof/gamutwarn", false); - _page_cms.add_line( true, "", _cms_gamutwarn, "", - _("Highlights colors that are out of gamut for the target device"), false); + _cms_gamutwarn.init(_("Mark out of gamut colors"), "/options/softproof/gamutwarn", false); + _page_cms.add_line(true, "", _cms_gamutwarn, "", _("Highlights colors that are out of gamut for the target device"), + false); Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor"); - Gdk::RGBA tmpColor( colorStr.empty() ? "#00ff00" : colorStr); - _cms_gamutcolor.set_rgba( tmpColor ); + Gdk::RGBA tmpColor(colorStr.empty() ? "#00ff00" : colorStr); + _cms_gamutcolor.set_rgba(tmpColor); - _page_cms.add_line( true, _("Out of gamut warning color:"), _cms_gamutcolor, "", - _("Selects the color used for out of gamut warning"), false); + _page_cms.add_line(true, _("Out of gamut warning color:"), _cms_gamutcolor, "", + _("Selects the color used for out of gamut warning"), false); - _page_cms.add_line( true, _("Device profile:"), _cms_proof_profile, "", - _("The ICC profile to use to simulate device output"), false); + _page_cms.add_line(true, _("Device profile:"), _cms_proof_profile, "", + _("The ICC profile to use to simulate device output"), false); _cms_proof_intent.init("/options/softproof/intent", intentLabels, intentValues, numIntents, 0); - _page_cms.add_line( true, _("Device rendering intent:"), _cms_proof_intent, "", - _("The rendering intent to use to calibrate device output"), false); + _page_cms.add_line(true, _("Device rendering intent:"), _cms_proof_intent, "", + _("The rendering intent to use to calibrate device output"), false); - _cms_proof_blackpoint.init( _("Black point compensation"), "/options/softproof/bpc", false); - _page_cms.add_line( true, "", _cms_proof_blackpoint, "", - _("Enables black point compensation"), false); + _cms_proof_blackpoint.init(_("Black point compensation"), "/options/softproof/bpc", false); + _page_cms.add_line(true, "", _cms_proof_blackpoint, "", _("Enables black point compensation"), false); - _cms_proof_preserveblack.init( _("Preserve black"), "/options/softproof/preserveblack", false); + _cms_proof_preserveblack.init(_("Preserve black"), "/options/softproof/preserveblack", false); #if !defined(HAVE_LIBLCMS2) - _page_cms.add_line( true, "", _cms_proof_preserveblack, + _page_cms.add_line(true, "", _cms_proof_preserveblack, #if defined(cmsFLAGS_PRESERVEBLACK) - "", + "", #else - _("(LittleCMS 1.15 or later required)"), + _("(LittleCMS 1.15 or later required)"), #endif // defined(cmsFLAGS_PRESERVEBLACK) - _("Preserve K channel in CMYK -> CMYK transforms"), false); + _("Preserve K channel in CMYK -> CMYK transforms"), false); #endif // !defined(HAVE_LIBLCMS2) #if !defined(cmsFLAGS_PRESERVEBLACK) - _cms_proof_preserveblack.set_sensitive( false ); + _cms_proof_preserveblack.set_sensitive(false); #endif // !defined(cmsFLAGS_PRESERVEBLACK) - #if defined(HAVE_LIBLCMS2) { std::vector<Glib::ustring> names = ::Inkscape::CMSSystem::getDisplayNames(); - Glib::ustring current = prefs->getString( "/options/displayprofile/uri" ); + Glib::ustring current = prefs->getString("/options/displayprofile/uri"); gint index = 0; _cms_display_profile.append(_("<none>")); index++; - for (auto & name : names) { - _cms_display_profile.append( name ); + for (auto &name : names) { + _cms_display_profile.append(name); Glib::ustring path = CMSSystem::getPathForProfile(name); - if ( !path.empty() && path == current ) { + if (!path.empty() && path == current) { _cms_display_profile.set_active(index); } index++; } - if ( current.empty() ) { + if (current.empty()) { _cms_display_profile.set_active(0); } names = ::Inkscape::CMSSystem::getSoftproofNames(); current = prefs->getString("/options/softproof/uri"); index = 0; - for (auto & name : names) { - _cms_proof_profile.append( name ); + for (auto &name : names) { + _cms_proof_profile.append(name); Glib::ustring path = CMSSystem::getPathForProfile(name); - if ( !path.empty() && path == current ) { + if (!path.empty() && path == current) { _cms_proof_profile.set_active(index); } index++; } } - _cms_gamutcolor.signal_color_set().connect( sigc::bind( sigc::ptr_fun(gamutColorChanged), &_cms_gamutcolor) ); + _cms_gamutcolor.signal_color_set().connect(sigc::bind(sigc::ptr_fun(gamutColorChanged), &_cms_gamutcolor)); - _cms_display_profile.signal_changed().connect( sigc::bind( sigc::ptr_fun(profileComboChanged), &_cms_display_profile) ); - _cms_proof_profile.signal_changed().connect( sigc::bind( sigc::ptr_fun(proofComboChanged), &_cms_proof_profile) ); + _cms_display_profile.signal_changed().connect( + sigc::bind(sigc::ptr_fun(profileComboChanged), &_cms_display_profile)); + _cms_proof_profile.signal_changed().connect(sigc::bind(sigc::ptr_fun(proofComboChanged), &_cms_proof_profile)); #else // disable it, but leave it visible - _cms_intent.set_sensitive( false ); - _cms_display_profile.set_sensitive( false ); - _cms_from_display.set_sensitive( false ); - _cms_softproof.set_sensitive( false ); - _cms_gamutwarn.set_sensitive( false ); - _cms_gamutcolor.set_sensitive( false ); - _cms_proof_intent.set_sensitive( false ); - _cms_proof_profile.set_sensitive( false ); - _cms_proof_blackpoint.set_sensitive( false ); - _cms_proof_preserveblack.set_sensitive( false ); + _cms_intent.set_sensitive(false); + _cms_display_profile.set_sensitive(false); + _cms_from_display.set_sensitive(false); + _cms_softproof.set_sensitive(false); + _cms_gamutwarn.set_sensitive(false); + _cms_gamutcolor.set_sensitive(false); + _cms_proof_intent.set_sensitive(false); + _cms_proof_profile.set_sensitive(false); + _cms_proof_blackpoint.set_sensitive(false); + _cms_proof_preserveblack.set_sensitive(false); #endif // defined(HAVE_LIBLCMS2) this->AddPage(_page_cms, _("Color management"), iter_io, PREFS_PAGE_IO_CMS); // Autosave options - _save_autosave_enable.init( _("Enable autosave (requires restart)"), "/options/autosave/enable", true); - _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_enable.init(_("Enable autosave (requires restart)"), "/options/autosave/enable", true); + _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_path.init("/options/autosave/path", true); 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::build_filename(Glib::get_user_cache_dir(), "inkscape")); } - _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); + _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); + _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 @@ -1782,8 +1947,8 @@ void InkscapePreferences::initPageIO() * AutoSave::restart() should be called AFTER the values have been changed * (which cannot be guaranteed from here) - use a PrefObserver somewhere. */ - _save_autosave_enable.signal_toggled( ).connect( sigc::ptr_fun(Inkscape::AutoSave::restart), true); - _save_autosave_interval.signal_changed().connect( sigc::ptr_fun(Inkscape::AutoSave::restart), true); + _save_autosave_enable.signal_toggled().connect(sigc::ptr_fun(Inkscape::AutoSave::restart), true); + _save_autosave_interval.signal_changed().connect(sigc::ptr_fun(Inkscape::AutoSave::restart), true); this->AddPage(_page_autosave, _("Autosave"), iter_io, PREFS_PAGE_IO_AUTOSAVE); } @@ -1793,65 +1958,74 @@ void InkscapePreferences::initPageBehavior() Gtk::TreeModel::iterator iter_behavior = this->AddPage(_page_behavior, _("Behavior"), PREFS_PAGE_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, "", - _("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); + _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, nullptr); - _sel_current.init ( _("Select only within current layer"), "/options/kbselection/inlayer", PREFS_SELECTION_LAYER, true, &_sel_all); - _sel_recursive.init ( _("Select in current layer and sublayers"), "/options/kbselection/inlayer", PREFS_SELECTION_LAYER_RECURSIVE, false, &_sel_all); - _sel_hidden.init ( _("Ignore hidden objects and layers"), "/options/kbselection/onlyvisible", true); - _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")); - _page_select.add_line( true, "", _sel_current, "", - _("Make keyboard selection commands work on objects in current layer only")); - _page_select.add_line( true, "", _sel_recursive, "", - _("Make keyboard selection commands work on objects in current layer and all its sublayers")); - _page_select.add_line( true, "", _sel_hidden, "", - _("Uncheck this to be able to select objects that are hidden (either by themselves or by being in a hidden layer)")); - _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)")); - - _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")); + _sel_all.init(_("Select in all layers"), "/options/kbselection/inlayer", PREFS_SELECTION_ALL, false, nullptr); + _sel_current.init(_("Select only within current layer"), "/options/kbselection/inlayer", PREFS_SELECTION_LAYER, + true, &_sel_all); + _sel_recursive.init(_("Select in current layer and sublayers"), "/options/kbselection/inlayer", + PREFS_SELECTION_LAYER_RECURSIVE, false, &_sel_all); + _sel_hidden.init(_("Ignore hidden objects and layers"), "/options/kbselection/onlyvisible", true); + _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")); + _page_select.add_line(true, "", _sel_current, "", + _("Make keyboard selection commands work on objects in current layer only")); + _page_select.add_line(true, "", _sel_recursive, "", + _("Make keyboard selection commands work on objects in current layer and all its sublayers")); + _page_select.add_line(true, "", _sel_hidden, "", + _("Uncheck this to be able to select objects that are hidden (either by themselves or by " + "being in a hidden layer)")); + _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)")); + + _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); // Transforms options - _trans_scale_stroke.init ( _("Scale stroke width"), "/options/transform/stroke", true); - _trans_scale_corner.init ( _("Scale rounded corners in rectangles"), "/options/transform/rectcorners", false); - _trans_gradient.init ( _("Transform gradients"), "/options/transform/gradient", true); - _trans_pattern.init ( _("Transform patterns"), "/options/transform/pattern", false); - _trans_optimized.init ( _("Optimized"), "/options/preservetransform/value", 0, true, nullptr); - _trans_preserved.init ( _("Preserved"), "/options/preservetransform/value", 1, false, &_trans_optimized); - - _page_transforms.add_line( false, "", _trans_scale_stroke, "", - _("When scaling objects, scale the stroke width by the same proportion")); - _page_transforms.add_line( false, "", _trans_scale_corner, "", - _("When scaling rectangles, scale the radii of rounded corners")); - _page_transforms.add_line( false, "", _trans_gradient, "", - _("Move gradients (in fill or stroke) along with the objects")); - _page_transforms.add_line( false, "", _trans_pattern, "", - _("Move patterns (in fill or stroke) along with the objects")); - _page_transforms.add_group_header( _("Store transformation")); - _page_transforms.add_line( true, "", _trans_optimized, "", - _("If possible, apply transformation to objects without adding a transform= attribute")); - _page_transforms.add_line( true, "", _trans_preserved, "", - _("Always store transformation as a transform= attribute on objects")); + _trans_scale_stroke.init(_("Scale stroke width"), "/options/transform/stroke", true); + _trans_scale_corner.init(_("Scale rounded corners in rectangles"), "/options/transform/rectcorners", false); + _trans_gradient.init(_("Transform gradients"), "/options/transform/gradient", true); + _trans_pattern.init(_("Transform patterns"), "/options/transform/pattern", false); + _trans_optimized.init(_("Optimized"), "/options/preservetransform/value", 0, true, nullptr); + _trans_preserved.init(_("Preserved"), "/options/preservetransform/value", 1, false, &_trans_optimized); + + _page_transforms.add_line(false, "", _trans_scale_stroke, "", + _("When scaling objects, scale the stroke width by the same proportion")); + _page_transforms.add_line(false, "", _trans_scale_corner, "", + _("When scaling rectangles, scale the radii of rounded corners")); + _page_transforms.add_line(false, "", _trans_gradient, "", + _("Move gradients (in fill or stroke) along with the objects")); + _page_transforms.add_line(false, "", _trans_pattern, "", + _("Move patterns (in fill or stroke) along with the objects")); + _page_transforms.add_group_header(_("Store transformation")); + _page_transforms.add_line(true, "", _trans_optimized, "", + _("If possible, apply transformation to objects without adding a transform= attribute")); + _page_transforms.add_line(true, "", _trans_preserved, "", + _("Always store transformation as a transform= attribute on objects")); this->AddPage(_page_transforms, _("Transforms"), iter_behavior, PREFS_PAGE_BEHAVIOR_TRANSFORMS); @@ -1861,210 +2035,242 @@ void InkscapePreferences::initPageBehavior() this->AddPage(_page_dashes, _("Dashes"), iter_behavior, PREFS_PAGE_BEHAVIOR_DASHES); // 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"), - _("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, _("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, "", - _("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, "", - _("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"), - _("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 ( _("Mouse move pans when Space is pressed"), "/options/spacebarpans/value", true); - _page_scrolling.add_line( true, "", _scroll_space, "", - _("When on, pressing and holding Space and dragging pans canvas")); - _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")); + _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"), + _("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, _("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, "", + _("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, "", + _("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"), + _("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(_("Mouse move pans when Space is pressed"), "/options/spacebarpans/value", true); + _page_scrolling.add_line(true, "", _scroll_space, "", + _("When on, pressing and holding Space and dragging pans canvas")); + _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")); this->AddPage(_page_scrolling, _("Scrolling"), iter_behavior, PREFS_PAGE_BEHAVIOR_SCROLLING); // Snapping options - _page_snapping.add_group_header( _("Snap defaults")); + _page_snapping.add_group_header(_("Snap defaults")); - _snap_default.init( _("Enable snapping in new documents"), "/options/snapdefault/value", true); - _page_snapping.add_line( true, "", _snap_default, "", - _("Initial state of snapping in new documents and SVG files that are opened with Inkscape for the first time. Snap status is subsequently saved per-document.")); + _snap_default.init(_("Enable snapping in new documents"), "/options/snapdefault/value", true); + _page_snapping.add_line(true, "", _snap_default, "", + _("Initial state of snapping in new documents and SVG files that are opened with Inkscape " + "for the first time. Snap status is subsequently saved per-document.")); - _page_snapping.add_group_header( _("Snap indicator")); + _page_snapping.add_group_header(_("Snap indicator")); - _snap_indicator.init( _("Enable snap indicator"), "/options/snapindicator/value", true); - _page_snapping.add_line( true, "", _snap_indicator, "", - _("After snapping, a symbol is drawn at the point that has snapped")); + _snap_indicator.init(_("Enable snap indicator"), "/options/snapindicator/value", true); + _page_snapping.add_line(true, "", _snap_indicator, "", + _("After snapping, a symbol is drawn at the point that has snapped")); - _snap_indicator.changed_signal.connect( sigc::mem_fun(_snap_persistence, &Gtk::Widget::set_sensitive) ); + _snap_indicator.changed_signal.connect(sigc::mem_fun(_snap_persistence, &Gtk::Widget::set_sensitive)); _snap_persistence.init("/options/snapindicatorpersistence/value", 0.1, 10, 0.1, 1, 2, 1); - _page_snapping.add_line( true, _("Snap indicator persistence (in seconds):"), _snap_persistence, "", - _("Controls how long the snap indicator message will be shown, before it disappears"), true); + _page_snapping.add_line(true, _("Snap indicator persistence (in seconds):"), _snap_persistence, "", + _("Controls how long the snap indicator message will be shown, before it disappears"), + true); - _page_snapping.add_group_header( _("What should snap")); + _page_snapping.add_group_header(_("What should snap")); - _snap_closest_only.init( _("Only snap the node closest to the pointer"), "/options/snapclosestonly/value", false); - _page_snapping.add_line( true, "", _snap_closest_only, "", - _("Only try to snap the node that is initially closest to the mouse pointer")); + _snap_closest_only.init(_("Only snap the node closest to the pointer"), "/options/snapclosestonly/value", false); + _page_snapping.add_line(true, "", _snap_closest_only, "", + _("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( true, _("_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); + _page_snapping.add_line( + true, _("_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); - _page_snapping.add_line( true, "", _snap_mouse_pointer, "", - _("When dragging a knot along a constraint line, then snap the position of the mouse pointer instead of snapping the projection of the knot onto the constraint line")); + _snap_mouse_pointer.init(_("Snap the mouse pointer when dragging a constrained knot"), + "/options/snapmousepointer/value", false); + _page_snapping.add_line(true, "", _snap_mouse_pointer, "", + _("When dragging a knot along a constraint line, then snap the position of the mouse " + "pointer instead of snapping the projection of the knot onto the constraint line")); - _page_snapping.add_group_header( _("Delayed snap")); + _page_snapping.add_group_header(_("Delayed snap")); _snap_delay.init("/options/snapdelay/value", 0, 1, 0.1, 0.2, 0, 1); - _page_snapping.add_line( true, _("Delay (in seconds):"), _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); + _page_snapping.add_line(true, _("Delay (in seconds):"), _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); this->AddPage(_page_snapping, _("Snapping"), iter_behavior, PREFS_PAGE_BEHAVIOR_SNAPPING); // 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, "", - _("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, "", - _("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, "", - _("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, "", - _("When on, angles are displayed with 0 at north, 0 to 360 range, positive clockwise; otherwise with 0 at east, -180 to 180 range, positive counterclockwise")); + _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, "", + _("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, "", + _("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, "", + _("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, "", + _("When on, angles are displayed with 0 at north, 0 to 360 range, positive clockwise; " + "otherwise with 0 at east, -180 to 180 range, positive counterclockwise")); int const num_items = 18; - Glib::ustring labels[num_items] = {"90", "60", "45", "36", "30", "22.5", "18", "15", "12", "10", "7.5", "6", "5", "3", "2", "1", "0.5", C_("Rotation angle", "None")}; + Glib::ustring labels[num_items] = {"90", "60", "45", "36", "30", "22.5", + "18", "15", "12", "10", "7.5", "6", + "5", "3", "2", "1", "0.5", C_("Rotation angle", "None")}; int values[num_items] = {2, 3, 4, 5, 6, 8, 10, 12, 15, 18, 24, 30, 36, 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"), - _("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, M_SQRT2, true, true); - _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); - _steps_rotate.init ( "/options/rotateincrement/value", 1, 90, 1.0, 5.0, 15, false, false); - _page_steps.add_line( false, _("_Rotate canvas by:"), _steps_rotate, _("degrees"), - _("Rotate canvas clockwise and counter-clockwise by this amount."), false); + _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, M_SQRT2, true, true); + _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); + _steps_rotate.init("/options/rotateincrement/value", 1, 90, 1.0, 5.0, 15, false, false); + _page_steps.add_line(false, _("_Rotate canvas by:"), _steps_rotate, _("degrees"), + _("Rotate canvas clockwise and counter-clockwise by this amount."), false); this->AddPage(_page_steps, _("Steps"), iter_behavior, PREFS_PAGE_BEHAVIOR_STEPS); // Clones options - _clone_option_parallel.init ( _("Move in parallel"), "/options/clonecompensation/value", - SP_CLONE_COMPENSATION_PARALLEL, true, nullptr); - _clone_option_stay.init ( _("Stay unmoved"), "/options/clonecompensation/value", - SP_CLONE_COMPENSATION_UNMOVED, false, &_clone_option_parallel); - _clone_option_transform.init ( _("Move according to transform"), "/options/clonecompensation/value", - SP_CLONE_COMPENSATION_NONE, false, &_clone_option_parallel); - _clone_option_unlink.init ( _("Are unlinked"), "/options/cloneorphans/value", - SP_CLONE_ORPHANS_UNLINK, true, nullptr); - _clone_option_delete.init ( _("Are deleted"), "/options/cloneorphans/value", - SP_CLONE_ORPHANS_DELETE, false, &_clone_option_unlink); - - _page_clones.add_group_header( _("Moving original: clones and linked offsets")); + _clone_option_parallel.init(_("Move in parallel"), "/options/clonecompensation/value", + SP_CLONE_COMPENSATION_PARALLEL, true, nullptr); + _clone_option_stay.init(_("Stay unmoved"), "/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED, false, + &_clone_option_parallel); + _clone_option_transform.init(_("Move according to transform"), "/options/clonecompensation/value", + SP_CLONE_COMPENSATION_NONE, false, &_clone_option_parallel); + _clone_option_unlink.init(_("Are unlinked"), "/options/cloneorphans/value", SP_CLONE_ORPHANS_UNLINK, true, nullptr); + _clone_option_delete.init(_("Are deleted"), "/options/cloneorphans/value", SP_CLONE_ORPHANS_DELETE, false, + &_clone_option_unlink); + + _page_clones.add_group_header(_("Moving original: clones and linked offsets")); _page_clones.add_line(true, "", _clone_option_parallel, "", - _("Clones are translated by the same vector as their original")); + _("Clones are translated by the same vector as their original")); _page_clones.add_line(true, "", _clone_option_stay, "", - _("Clones preserve their positions when their original is moved")); + _("Clones preserve their positions when their original is moved")); _page_clones.add_line(true, "", _clone_option_transform, "", - _("Each clone moves according to the value of its transform= attribute; for example, a rotated clone will move in a different direction than its original")); - _page_clones.add_group_header( _("Deleting original: clones")); - _page_clones.add_line(true, "", _clone_option_unlink, "", - _("Orphaned clones are converted to regular objects")); + _("Each clone moves according to the value of its transform= attribute; for example, a " + "rotated clone will move in a different direction than its original")); + _page_clones.add_group_header(_("Deleting original: clones")); + _page_clones.add_line(true, "", _clone_option_unlink, "", _("Orphaned clones are converted to regular objects")); _page_clones.add_line(true, "", _clone_option_delete, "", - _("Orphaned clones are deleted along with their original")); + _("Orphaned clones are deleted along with their original")); - _page_clones.add_group_header( _("Duplicating original+clones/linked offset")); + _page_clones.add_group_header(_("Duplicating original+clones/linked offset")); - _clone_relink_on_duplicate.init ( _("Relink duplicated clones"), "/options/relinkclonesonduplicate/value", false); - _page_clones.add_line(true, "", _clone_relink_on_duplicate, "", - _("When duplicating a selection containing both a clone and its original (possibly in groups), relink the duplicated clone to the duplicated original instead of the old original")); + _clone_relink_on_duplicate.init(_("Relink duplicated clones"), "/options/relinkclonesonduplicate/value", false); + _page_clones.add_line( + true, "", _clone_relink_on_duplicate, "", + _("When duplicating a selection containing both a clone and its original (possibly in groups), relink the " + "duplicated clone to the duplicated original instead of the old original")); - _page_clones.add_group_header( _("Unlinking clones")); - _clone_to_curves.init ( _("Path operations unlink clones"), "/options/pathoperationsunlink/value", true); + _page_clones.add_group_header(_("Unlinking clones")); + _clone_to_curves.init(_("Path operations unlink clones"), "/options/pathoperationsunlink/value", true); _page_clones.add_line(true, "", _clone_to_curves, "", - _("The following path operations will unlink clones: Stroke to path, Object to path, Boolean operations, Combine, Break apart")); + _("The following path operations will unlink clones: Stroke to path, Object to path, Boolean " + "operations, Combine, Break apart")); - //TRANSLATORS: Heading for the Inkscape Preferences "Clones" Page + // TRANSLATORS: Heading for the Inkscape Preferences "Clones" Page this->AddPage(_page_clones, _("Clones"), iter_behavior, PREFS_PAGE_BEHAVIOR_CLONES); // Clip paths and masks options - _mask_mask_on_top.init ( _("When applying, use the topmost selected object as clippath/mask"), "/options/maskobject/topmost", true); + _mask_mask_on_top.init(_("When applying, use the topmost selected object as clippath/mask"), + "/options/maskobject/topmost", true); _page_mask.add_line(false, "", _mask_mask_on_top, "", _("Uncheck this to use the bottom selected object as the clipping path or mask")); - _mask_mask_remove.init ( _("Remove clippath/mask object after applying"), "/options/maskobject/remove", true); + _mask_mask_remove.init(_("Remove clippath/mask object after applying"), "/options/maskobject/remove", true); _page_mask.add_line(false, "", _mask_mask_remove, "", _("After applying, remove the object used as the clipping path or mask from the drawing")); - _page_mask.add_group_header( _("Before applying")); + _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, nullptr); - _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); + _mask_grouping_none.init(_("Do not group clipped/masked objects"), "/options/maskobject/grouping", + PREFS_MASKOBJECT_GROUPING_NONE, true, nullptr); + _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, "", - _("Apply clippath/mask to every object")); + _page_mask.add_line(true, "", _mask_grouping_none, "", _("Apply clippath/mask to every object")); _page_mask.add_line(true, "", _mask_grouping_separate, "", _("Apply clippath/mask to groups containing single object")); - _page_mask.add_line(true, "", _mask_grouping_all, "", - _("Apply clippath/mask to group containing all objects")); + _page_mask.add_line(true, "", _mask_grouping_all, "", _("Apply clippath/mask to group containing all objects")); - _page_mask.add_group_header( _("After releasing")); + _page_mask.add_group_header(_("After releasing")); - _mask_ungrouping.init ( _("Ungroup automatically created groups"), "/options/maskobject/ungrouping", true); - _page_mask.add_line(true, "", _mask_ungrouping, "", - _("Ungroup groups created when setting clip/mask")); + _mask_ungrouping.init(_("Ungroup automatically created groups"), "/options/maskobject/ungrouping", true); + _page_mask.add_line(true, "", _mask_ungrouping, "", _("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, "", + _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, "", + _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")); + _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, "", + _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() { - - /* threaded blur */ //related comments/widgets/functions should be renamed and option should be moved elsewhere when inkscape is fully multi-threaded + /* 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)"), - _("Configure number of processors/threads to use when rendering filters"), false); + _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); // rendering tile multiplier _rendering_tile_multiplier.init("/options/rendering/tile-multiplier", 1.0, 512.0, 1.0, 16.0, 16.0, true, false); - _page_rendering.add_line( false, _("Rendering tile multiplier:"), _rendering_tile_multiplier, "", - _("On modern hardware, increasing this value (default is 16) can help to get a better performance when there are large areas with filtered objects (this includes blur and blend modes) in your drawing. Decrease the value to make zooming and panning in relevant areas faster on low-end hardware in drawings with few or no filters."), false); + _page_rendering.add_line(false, _("Rendering tile multiplier:"), _rendering_tile_multiplier, "", + _("On modern hardware, increasing this value (default is 16) can help to get a better " + "performance when there are large areas with filtered objects (this includes blur and " + "blend modes) in your drawing. Decrease the value to make zooming and panning in " + "relevant areas faster on low-end hardware in drawings with few or no filters."), + false); // rendering xray radius _rendering_xray_radius.init("/options/rendering/xray-radius", 1.0, 1500.0, 1.0, 100.0, 100.0, true, false); @@ -2073,65 +2279,64 @@ void InkscapePreferences::initPageRendering() { // if these GTK constants ever change, consider adding a compatibility shim to SPCanvas::addIdle() - static_assert(G_PRIORITY_HIGH_IDLE == 100, "G_PRIORITY_HIGH_IDLE must be 100 to match preferences.xml"); + static_assert(G_PRIORITY_HIGH_IDLE == 100, "G_PRIORITY_HIGH_IDLE must be 100 to match preferences.xml"); static_assert(G_PRIORITY_DEFAULT_IDLE == 200, "G_PRIORITY_DEFAULT_IDLE must be 200 to match preferences.xml"); Glib::ustring redrawPriorityLabels[] = {_("Responsive"), _("Conservative")}; int redrawPriorityValues[] = {G_PRIORITY_HIGH_IDLE, G_PRIORITY_DEFAULT_IDLE}; // redraw priority - _rendering_redraw_priority.init("/options/redrawpriority/value", redrawPriorityLabels, redrawPriorityValues, G_N_ELEMENTS(redrawPriorityLabels), 0); + _rendering_redraw_priority.init("/options/redrawpriority/value", redrawPriorityLabels, redrawPriorityValues, + G_N_ELEMENTS(redrawPriorityLabels), 0); _page_rendering.add_line(false, _("Redraw while editing:"), _rendering_redraw_priority, "", - _("Set how quickly the canvas display is updated while editing objects"), false); + _("Set how quickly the canvas display is updated while editing objects"), false); } /* blur quality */ - _blur_quality_best.init ( _("Best quality (slowest)"), "/options/blurquality/value", - BLUR_QUALITY_BEST, false, nullptr); - _blur_quality_better.init ( _("Better quality (slower)"), "/options/blurquality/value", - BLUR_QUALITY_BETTER, false, &_blur_quality_best); - _blur_quality_normal.init ( _("Average quality"), "/options/blurquality/value", - BLUR_QUALITY_NORMAL, true, &_blur_quality_best); - _blur_quality_worse.init ( _("Lower quality (faster)"), "/options/blurquality/value", - BLUR_QUALITY_WORSE, false, &_blur_quality_best); - _blur_quality_worst.init ( _("Lowest quality (fastest)"), "/options/blurquality/value", - BLUR_QUALITY_WORST, false, &_blur_quality_best); - - _page_rendering.add_group_header( _("Gaussian blur quality for display")); - _page_rendering.add_line( true, "", _blur_quality_best, "", - _("Best quality, but display may be very slow at high zooms (bitmap export always uses best quality)")); - _page_rendering.add_line( true, "", _blur_quality_better, "", - _("Better quality, but slower display")); - _page_rendering.add_line( true, "", _blur_quality_normal, "", - _("Average quality, acceptable display speed")); - _page_rendering.add_line( true, "", _blur_quality_worse, "", - _("Lower quality (some artifacts), but display is faster")); - _page_rendering.add_line( true, "", _blur_quality_worst, "", - _("Lowest quality (considerable artifacts), but display is fastest")); + _blur_quality_best.init(_("Best quality (slowest)"), "/options/blurquality/value", BLUR_QUALITY_BEST, false, + nullptr); + _blur_quality_better.init(_("Better quality (slower)"), "/options/blurquality/value", BLUR_QUALITY_BETTER, false, + &_blur_quality_best); + _blur_quality_normal.init(_("Average quality"), "/options/blurquality/value", BLUR_QUALITY_NORMAL, true, + &_blur_quality_best); + _blur_quality_worse.init(_("Lower quality (faster)"), "/options/blurquality/value", BLUR_QUALITY_WORSE, false, + &_blur_quality_best); + _blur_quality_worst.init(_("Lowest quality (fastest)"), "/options/blurquality/value", BLUR_QUALITY_WORST, false, + &_blur_quality_best); + + _page_rendering.add_group_header(_("Gaussian blur quality for display")); + _page_rendering.add_line( + true, "", _blur_quality_best, "", + _("Best quality, but display may be very slow at high zooms (bitmap export always uses best quality)")); + _page_rendering.add_line(true, "", _blur_quality_better, "", _("Better quality, but slower display")); + _page_rendering.add_line(true, "", _blur_quality_normal, "", _("Average quality, acceptable display speed")); + _page_rendering.add_line(true, "", _blur_quality_worse, "", + _("Lower quality (some artifacts), but display is faster")); + _page_rendering.add_line(true, "", _blur_quality_worst, "", + _("Lowest quality (considerable artifacts), but display is fastest")); /* filter quality */ - _filter_quality_best.init ( _("Best quality (slowest)"), "/options/filterquality/value", - Inkscape::Filters::FILTER_QUALITY_BEST, false, nullptr); - _filter_quality_better.init ( _("Better quality (slower)"), "/options/filterquality/value", - Inkscape::Filters::FILTER_QUALITY_BETTER, false, &_filter_quality_best); - _filter_quality_normal.init ( _("Average quality"), "/options/filterquality/value", - Inkscape::Filters::FILTER_QUALITY_NORMAL, true, &_filter_quality_best); - _filter_quality_worse.init ( _("Lower quality (faster)"), "/options/filterquality/value", - Inkscape::Filters::FILTER_QUALITY_WORSE, false, &_filter_quality_best); - _filter_quality_worst.init ( _("Lowest quality (fastest)"), "/options/filterquality/value", - Inkscape::Filters::FILTER_QUALITY_WORST, false, &_filter_quality_best); - - _page_rendering.add_group_header( _("Filter effects quality for display")); - _page_rendering.add_line( true, "", _filter_quality_best, "", - _("Best quality, but display may be very slow at high zooms (bitmap export always uses best quality)")); - _page_rendering.add_line( true, "", _filter_quality_better, "", - _("Better quality, but slower display")); - _page_rendering.add_line( true, "", _filter_quality_normal, "", - _("Average quality, acceptable display speed")); - _page_rendering.add_line( true, "", _filter_quality_worse, "", - _("Lower quality (some artifacts), but display is faster")); - _page_rendering.add_line( true, "", _filter_quality_worst, "", - _("Lowest quality (considerable artifacts), but display is fastest")); + _filter_quality_best.init(_("Best quality (slowest)"), "/options/filterquality/value", + Inkscape::Filters::FILTER_QUALITY_BEST, false, nullptr); + _filter_quality_better.init(_("Better quality (slower)"), "/options/filterquality/value", + Inkscape::Filters::FILTER_QUALITY_BETTER, false, &_filter_quality_best); + _filter_quality_normal.init(_("Average quality"), "/options/filterquality/value", + Inkscape::Filters::FILTER_QUALITY_NORMAL, true, &_filter_quality_best); + _filter_quality_worse.init(_("Lower quality (faster)"), "/options/filterquality/value", + Inkscape::Filters::FILTER_QUALITY_WORSE, false, &_filter_quality_best); + _filter_quality_worst.init(_("Lowest quality (fastest)"), "/options/filterquality/value", + Inkscape::Filters::FILTER_QUALITY_WORST, false, &_filter_quality_best); + + _page_rendering.add_group_header(_("Filter effects quality for display")); + _page_rendering.add_line( + true, "", _filter_quality_best, "", + _("Best quality, but display may be very slow at high zooms (bitmap export always uses best quality)")); + _page_rendering.add_line(true, "", _filter_quality_better, "", _("Better quality, but slower display")); + _page_rendering.add_line(true, "", _filter_quality_normal, "", _("Average quality, acceptable display speed")); + _page_rendering.add_line(true, "", _filter_quality_worse, "", + _("Lower quality (some artifacts), but display is faster")); + _page_rendering.add_line(true, "", _filter_quality_worst, "", + _("Lowest quality (considerable artifacts), but display is fastest")); this->AddPage(_page_rendering, _("Rendering"), PREFS_PAGE_RENDERING); } @@ -2139,31 +2344,32 @@ void InkscapePreferences::initPageRendering() void InkscapePreferences::initPageBitmaps() { /* Note: /options/bitmapoversample removed with Cairo renderer */ - _page_bitmaps.add_group_header( _("Edit")); + _page_bitmaps.add_group_header(_("Edit")); _misc_bitmap_autoreload.init(_("Automatically reload images"), "/options/bitmapautoreload/value", true); - _page_bitmaps.add_line( false, "", _misc_bitmap_autoreload, "", + _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); + _page_bitmaps.add_line(false, _("_Bitmap editor:"), _misc_bitmap_editor, "", "", true); _misc_svg_editor.init("/options/svgeditor/value", true); - _page_bitmaps.add_line( false, _("_SVG editor:"), _misc_svg_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 image resolution (in dots per inch) in the Export dialog"), false); - _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")); + _page_bitmaps.add_line(false, _("_SVG editor:"), _misc_svg_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 image resolution (in dots per inch) in the Export dialog"), false); + _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 bitmap images"), "/dialogs/import/ask", true); - _page_bitmaps.add_line( true, "", _bitmap_ask, "", + _page_bitmaps.add_line(true, "", _bitmap_ask, "", _("Pop-up linking and scaling dialog when importing bitmap image.")); _svg_ask.init(_("Ask about linking and scaling when importing SVG images"), "/dialogs/import/ask_svg", true); - _page_bitmaps.add_line( true, "", _svg_ask, "", - _("Pop-up linking and scaling dialog when importing SVG image.")); + _page_bitmaps.add_line(true, "", _svg_ask, "", _("Pop-up linking and scaling dialog when importing SVG image.")); _svgoutput_usesodipodiabsref.init(_("Store absolute file path for linked images"), "/options/svgoutput/usesodipodiabsref", false); @@ -2179,35 +2385,38 @@ void InkscapePreferences::initPageBitmaps() 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 import/open mode:"), _bitmap_link, "", "", false); + _page_bitmaps.add_line(false, _("Bitmap import/open mode:"), _bitmap_link, "", "", false); } { Glib::ustring labels[] = {_("Include"), _("Embed"), _("Link")}; Glib::ustring values[] = {"include", "embed", "link"}; _svg_link.init("/dialogs/import/import_mode_svg", labels, values, G_N_ELEMENTS(values), "include"); - _page_bitmaps.add_line( false, _("SVG import mode:"), _svg_link, "", "", false); + _page_bitmaps.add_line(false, _("SVG import mode:"), _svg_link, "", "", false); } { - Glib::ustring labels[] = {_("None (auto)"), _("Smooth (optimizeQuality)"), _("Blocky (optimizeSpeed)") }; + 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, _("Image scale (image-rendering):"), _bitmap_scale, "", "", false); + _page_bitmaps.add_line(false, _("Image 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 import resolution (in dots per inch) for bitmap and SVG import"), false); + _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 import resolution (in dots per inch) for bitmap and SVG 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")); + _page_bitmaps.add_line(false, "", _importexport_import_res_override, "", + _("Use default bitmap resolution in favor of information from file")); - _page_bitmaps.add_group_header( _("Render")); + _page_bitmaps.add_group_header(_("Render")); // rendering outlines for pixmap image tags - _rendering_image_outline.init( _("Images in Outline Mode"), "/options/rendering/imageinoutlinemode", false); - _page_bitmaps.add_line(false, "", _rendering_image_outline, "", _("When active will render images while in outline mode instead of a red box with an x. This is useful for manual tracing.")); + _rendering_image_outline.init(_("Images in Outline Mode"), "/options/rendering/imageinoutlinemode", false); + _page_bitmaps.add_line(false, "", _rendering_image_outline, "", + _("When active will render images while in outline mode instead of a red box with an x. " + "This is useful for manual tracing.")); this->AddPage(_page_bitmaps, _("Imported Images"), PREFS_PAGE_BITMAPS); } @@ -2219,21 +2428,24 @@ void InkscapePreferences::initKeyboardShortcuts(Gtk::TreeModel::iterator iter_ui sp_shortcut_get_file_names(&fileLabels, &fileNames); - _kb_filelist.init( "/options/kbshortcuts/shortcutfile", &fileLabels[0], &fileNames[0], fileLabels.size(), fileNames[0]); + _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 separately to ")); + Glib::ustring tooltip(_("Select a file of predefined shortcuts to use. Any customized shortcuts you create will be " + "added separately 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); + _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); + _page_keyshortcuts.add_line(false, _("Search:"), _kb_search, "", "", true); - _kb_store = Gtk::TreeStore::create( _kb_columns ); - _kb_store->set_sort_column ( GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID, Gtk::SORT_ASCENDING ); // only sort in onKBListKeyboardShortcuts() + _kb_store = Gtk::TreeStore::create(_kb_columns); + _kb_store->set_sort_column(GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID, + Gtk::SORT_ASCENDING); // only sort in onKBListKeyboardShortcuts() _kb_filter = Gtk::TreeModelFilter::create(_kb_store); - _kb_filter->set_visible_func (sigc::mem_fun(*this, &InkscapePreferences::onKBSearchFilter)); + _kb_filter->set_visible_func(sigc::mem_fun(*this, &InkscapePreferences::onKBSearchFilter)); _kb_shortcut_renderer.property_editable() = true; @@ -2247,13 +2459,14 @@ void InkscapePreferences::initKeyboardShortcuts(Gtk::TreeModel::iterator iter_ui _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(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)->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(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); @@ -2261,10 +2474,10 @@ void InkscapePreferences::initKeyboardShortcuts(Gtk::TreeModel::iterator iter_ui _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) ); + _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(); + Gtk::ScrolledWindow *scroller = new Gtk::ScrolledWindow(); scroller->add(_kb_tree); int row = 3; @@ -2285,7 +2498,8 @@ void InkscapePreferences::initKeyboardShortcuts(Gtk::TreeModel::iterator iter_ui auto kb_reset = Gtk::manage(new Gtk::Button(_("Reset"))); kb_reset->set_use_underline(); - kb_reset->set_tooltip_text(_("Remove all your customized keyboard shortcuts, and revert to the shortcuts in the shortcut file listed above")); + kb_reset->set_tooltip_text(_("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); @@ -2299,12 +2513,12 @@ void InkscapePreferences::initKeyboardShortcuts(Gtk::TreeModel::iterator iter_ui kb_export->set_tooltip_text(_("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) ); + 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); @@ -2316,7 +2530,6 @@ void InkscapePreferences::initKeyboardShortcuts(Gtk::TreeModel::iterator iter_ui (*iter_group)[_kb_columns.description] = ""; (*iter_group)[_kb_columns.shortcutid] = 0; (*iter_group)[_kb_columns.user_set] = 0; - } void InkscapePreferences::onKBList() @@ -2350,7 +2563,7 @@ bool InkscapePreferences::onKBSearchKeyEvent(GdkEventKey * /*event*/) return FALSE; } -void InkscapePreferences::onKBTreeCleared(const Glib::ustring& path) +void InkscapePreferences::onKBTreeCleared(const Glib::ustring &path) { Gtk::TreeModel::iterator iter = _kb_filter->get_iter(path); Glib::ustring id = (*iter)[_kb_columns.id]; @@ -2361,10 +2574,10 @@ void InkscapePreferences::onKBTreeCleared(const Glib::ustring& path) sp_shortcut_init(); onKBListKeyboardShortcuts(); - } -void InkscapePreferences::onKBTreeEdited (const Glib::ustring& path, guint accel_key, Gdk::ModifierType accel_mods, guint hardware_keycode) +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); @@ -2377,7 +2590,7 @@ void InkscapePreferences::onKBTreeEdited (const Glib::ustring& path, guint accel return; } - unsigned int const new_shortcut_id = sp_shortcut_get_from_gdk_event(accel_key, accel_mods, hardware_keycode); + unsigned int const new_shortcut_id = sp_shortcut_get_from_gdk_event(accel_key, accel_mods, hardware_keycode); if (new_shortcut_id && (new_shortcut_id != current_shortcut_id)) { // check if there is currently a verb assigned to this shortcut; if yes ask if the shortcut should be reassigned Inkscape::Verb *current_verb = sp_shortcut_get_verb(new_shortcut_id); @@ -2411,7 +2624,7 @@ void InkscapePreferences::onKBTreeEdited (const Glib::ustring& path, guint accel } } -bool InkscapePreferences::onKBSearchFilter(const Gtk::TreeModel::const_iterator& iter) +bool InkscapePreferences::onKBSearchFilter(const Gtk::TreeModel::const_iterator &iter) { Glib::ustring search = _kb_search.get_text().lowercase(); if (search.empty()) { @@ -2424,13 +2637,11 @@ bool InkscapePreferences::onKBSearchFilter(const Gtk::TreeModel::const_iterator& Glib::ustring id = (*iter)[_kb_columns.id]; if (id.empty()) { - return TRUE; // Keep all group nodes visible + 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); + 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() @@ -2447,8 +2658,8 @@ InkscapePreferences::ModelColumns &InkscapePreferences::onKBGetCols() return cols; } -void InkscapePreferences::onKBShortcutRenderer(Gtk::CellRenderer *renderer, Gtk::TreeIter const &iter) { - +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); @@ -2470,14 +2681,13 @@ void InkscapePreferences::onKBListKeyboardShortcuts() _kb_store->clear(); - std::vector<Verb *>verbs = Inkscape::Verb::getList(); + std::vector<Verb *> verbs = Inkscape::Verb::getList(); for (auto verb : verbs) { - if (!verb) { continue; } - if (!verb->get_name()){ + if (!verb->get_name()) { continue; } @@ -2489,7 +2699,7 @@ void InkscapePreferences::onKBListKeyboardShortcuts() // Find this group in the tree Glib::ustring group = verb->get_group() ? _(verb->get_group()) : _("Misc"); Glib::ustring verb_id = verb->get_id(); - if (verb_id .compare(0,26,"org.inkscape.effect.filter") == 0) { + if (verb_id.compare(0, 26, "org.inkscape.effect.filter") == 0) { group = _("Filters"); } Gtk::TreeStore::iterator iter_group; @@ -2521,7 +2731,7 @@ void InkscapePreferences::onKBListKeyboardShortcuts() // 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) { + while ((k = name.find('_', k)) != name.npos) { name.erase(k, 1); } @@ -2529,7 +2739,7 @@ void InkscapePreferences::onKBListKeyboardShortcuts() 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); + gchar *str = sp_shortcut_get_label(shortcut_id); if (str) { shortcut_label = Glib::Markup::escape_text(str); g_free(str); @@ -2538,7 +2748,7 @@ void InkscapePreferences::onKBListKeyboardShortcuts() } // Add the verb to the group Gtk::TreeStore::iterator row = _kb_store->append(iter_group->children()); - (*row)[_kb_columns.name] = name; + (*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; @@ -2553,13 +2763,12 @@ void InkscapePreferences::onKBListKeyboardShortcuts() } // re-order once after updating (then disable ordering again to increase performance) - _kb_store->set_sort_column (_kb_columns.id, Gtk::SORT_ASCENDING ); - _kb_store->set_sort_column ( GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID, Gtk::SORT_ASCENDING ); + _kb_store->set_sort_column(_kb_columns.id, Gtk::SORT_ASCENDING); + _kb_store->set_sort_column(GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID, Gtk::SORT_ASCENDING); if (selected_id.empty()) { _kb_tree.expand_to_path(_kb_store->get_path(_kb_store->get_iter("0:1"))); } - } void InkscapePreferences::initPageSpellcheck() @@ -2578,55 +2787,61 @@ void InkscapePreferences::initPageSpellcheck() langValues.emplace_back(pair.second); } - _spell_language.init( "/dialogs/spellcheck/lang", &languages[0], &langValues[0], languages.size(), languages[0]); - _page_spellcheck.add_line( false, _("Language:"), _spell_language, "", - _("Set the main spell check language"), false); + _spell_language.init("/dialogs/spellcheck/lang", &languages[0], &langValues[0], languages.size(), languages[0]); + _page_spellcheck.add_line(false, _("Language:"), _spell_language, "", _("Set the main spell check language"), + false); - _spell_language2.init( "/dialogs/spellcheck/lang2", &languages[0], &langValues[0], languages.size(), languages[0]); - _page_spellcheck.add_line( false, _("Second language:"), _spell_language2, "", - _("Set the second spell check language; checking will only stop on words unknown in ALL chosen languages"), false); + _spell_language2.init("/dialogs/spellcheck/lang2", &languages[0], &langValues[0], languages.size(), languages[0]); + _page_spellcheck.add_line( + false, _("Second language:"), _spell_language2, "", + _("Set the second spell check language; checking will only stop on words unknown in ALL chosen languages"), + false); - _spell_language3.init( "/dialogs/spellcheck/lang3", &languages[0], &langValues[0], languages.size(), languages[0]); - _page_spellcheck.add_line( false, _("Third language:"), _spell_language3, "", - _("Set the third spell check language; checking will only stop on words unknown in ALL chosen languages"), false); + _spell_language3.init("/dialogs/spellcheck/lang3", &languages[0], &langValues[0], languages.size(), languages[0]); + _page_spellcheck.add_line( + false, _("Third language:"), _spell_language3, "", + _("Set the third spell check language; checking will only stop on words unknown in ALL chosen languages"), + false); - _spell_ignorenumbers.init( _("Ignore words with digits"), "/dialogs/spellcheck/ignorenumbers", true); - _page_spellcheck.add_line( false, "", _spell_ignorenumbers, "", - _("Ignore words containing digits, such as \"R2D2\""), true); + _spell_ignorenumbers.init(_("Ignore words with digits"), "/dialogs/spellcheck/ignorenumbers", true); + _page_spellcheck.add_line(false, "", _spell_ignorenumbers, "", + _("Ignore words containing digits, such as \"R2D2\""), true); - _spell_ignoreallcaps.init( _("Ignore words in ALL CAPITALS"), "/dialogs/spellcheck/ignoreallcaps", false); - _page_spellcheck.add_line( false, "", _spell_ignoreallcaps, "", - _("Ignore words in all capitals, such as \"IUPAC\""), true); + _spell_ignoreallcaps.init(_("Ignore words in ALL CAPITALS"), "/dialogs/spellcheck/ignoreallcaps", false); + _page_spellcheck.add_line(false, "", _spell_ignoreallcaps, "", _("Ignore words in all capitals, such as \"IUPAC\""), + true); this->AddPage(_page_spellcheck, _("Spellcheck"), PREFS_PAGE_SPELLCHECK); #endif } template <typename string_type> -static void appendList(Glib::ustring& tmp, const std::vector<string_type> &listing) +static void appendList(Glib::ustring &tmp, const std::vector<string_type> &listing) { - for (auto const & str : listing) { + for (auto const &str : listing) { tmp += str; tmp += "\n"; } } - 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)"), - _("Factor by which the event clock is skewed from the actual time (0.9766 on some systems)"), false); + _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); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - _misc_namedicon_delay.init( _("Pre-render named icons"), "/options/iconrender/named_nodelay", false); - _page_system.add_line( false, "", _misc_namedicon_delay, "", - _("When on, named icons will be rendered before displaying the ui. This is for working around bugs in GTK+ named icon notification"), true); + _misc_namedicon_delay.init(_("Pre-render named icons"), "/options/iconrender/named_nodelay", false); + _page_system.add_line(false, "", _misc_namedicon_delay, "", + _("When on, named icons will be rendered before displaying the ui. This is for working " + "around bugs in GTK+ named icon notification"), + true); - _page_system.add_group_header( _("System info")); + _page_system.add_group_header(_("System info")); _sys_user_prefs.set_text(prefs->getPrefsFilename()); _sys_user_prefs.set_editable(false); - Gtk::Button* reset_prefs = Gtk::manage(new Gtk::Button(_("Reset Preferences"))); + Gtk::Button *reset_prefs = Gtk::manage(new Gtk::Button(_("Reset Preferences"))); reset_prefs->signal_clicked().connect(sigc::mem_fun(*this, &InkscapePreferences::on_reset_prefs_clicked)); _page_system.add_line(true, _("User preferences: "), _sys_user_prefs, "", @@ -2636,8 +2851,7 @@ void InkscapePreferences::initPageSystem() _page_system.add_line(true, _("User config: "), _sys_user_config, "", _("Location of users configuration"), true); auto extensions_folder = IO::Resource::get_path_string(IO::Resource::USER, IO::Resource::EXTENSIONS); - _sys_user_extension_dir.init(extensions_folder, - _("Open extensions folder")); + _sys_user_extension_dir.init(extensions_folder, _("Open extensions folder")); _page_system.add_line(true, _("User extensions: "), _sys_user_extension_dir, "", _("Location of the user’s extensions"), true); @@ -2664,10 +2878,10 @@ void InkscapePreferences::initPageSystem() true); _sys_user_paint_servers_dir.init((char const *)IO::Resource::get_path(IO::Resource::USER, IO::Resource::PAINT, ""), - _("Open paint servers folder")); + _("Open paint servers folder")); _page_system.add_line(true, _("User paint servers: "), _sys_user_paint_servers_dir, "", - _("Location of the user’s paint servers"), true); + _("Location of the user’s paint servers"), true); _sys_user_palettes_dir.init((char const *)IO::Resource::get_path(IO::Resource::USER, IO::Resource::PALETTES, ""), _("Open palettes folder")); @@ -2694,7 +2908,8 @@ void InkscapePreferences::initPageSystem() } _sys_tmp_files.set_text(tmp_dir); _sys_tmp_files.set_editable(false); - _page_system.add_line(true, _("Temporary files: "), _sys_tmp_files, "", _("Location of the temporary files used for autosave"), true); + _page_system.add_line(true, _("Temporary files: "), _sys_tmp_files, "", + _("Location of the temporary files used for autosave"), true); _sys_data.set_text(get_inkscape_datadir()); _sys_data.set_editable(false); @@ -2703,7 +2918,8 @@ void InkscapePreferences::initPageSystem() extensions_folder = IO::Resource::get_path_string(IO::Resource::SYSTEM, IO::Resource::EXTENSIONS); _sys_extension_dir.set_text(extensions_folder); _sys_extension_dir.set_editable(false); - _page_system.add_line(true, _("Inkscape extensions: "), _sys_extension_dir, "", _("Location of the Inkscape extensions"), true); + _page_system.add_line(true, _("Inkscape extensions: "), _sys_extension_dir, "", + _("Location of the Inkscape extensions"), true); Glib::ustring tmp; auto system_data_dirs = Glib::get_system_data_dirs(); @@ -2714,51 +2930,51 @@ void InkscapePreferences::initPageSystem() _sys_systemdata_scroll.set_size_request(100, 80); _sys_systemdata_scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); _sys_systemdata_scroll.set_shadow_type(Gtk::SHADOW_IN); - _page_system.add_line(true, _("System data: "), _sys_systemdata_scroll, "", _("Locations of system data"), true); + _page_system.add_line(true, _("System data: "), _sys_systemdata_scroll, "", _("Locations of system data"), true); _sys_fontdirs_custom.init("/options/font/custom_fontdirs", 50); - _page_system.add_line(true, _("Custom Font directories"), _sys_fontdirs_custom, "", _("Load additional fonts from custom locations (one path per line)"), true); + _page_system.add_line(true, _("Custom Font directories"), _sys_fontdirs_custom, "", + _("Load additional fonts from custom locations (one path per line)"), true); tmp = ""; auto icon_theme = Gtk::IconTheme::get_default(); auto paths = icon_theme->get_search_path(); - appendList( tmp, paths ); + appendList(tmp, paths); _sys_icon.get_buffer()->insert(_sys_icon.get_buffer()->end(), tmp); _sys_icon.set_editable(false); _sys_icon_scroll.add(_sys_icon); _sys_icon_scroll.set_size_request(100, 80); _sys_icon_scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); _sys_icon_scroll.set_shadow_type(Gtk::SHADOW_IN); - _page_system.add_line(true, _("Icon theme: "), _sys_icon_scroll, "", _("Locations of icon themes"), true); + _page_system.add_line(true, _("Icon theme: "), _sys_icon_scroll, "", _("Locations of icon themes"), true); this->AddPage(_page_system, _("System"), PREFS_PAGE_SYSTEM); } -bool InkscapePreferences::GetSizeRequest(const Gtk::TreeModel::iterator& iter) +bool InkscapePreferences::GetSizeRequest(const Gtk::TreeModel::iterator &iter) { Gtk::TreeModel::Row row = *iter; - DialogPage* page = row[_page_list_columns._col_page]; + DialogPage *page = row[_page_list_columns._col_page]; _page_frame.add(*page); this->show_all_children(); Gtk::Requisition sreq_minimum; Gtk::Requisition sreq_natural; _getContents()->get_preferred_size(sreq_minimum, sreq_natural); - _minimum_width = std::max(_minimum_width, sreq_minimum.width); + _minimum_width = std::max(_minimum_width, sreq_minimum.width); _minimum_height = std::max(_minimum_height, sreq_minimum.height); - _natural_width = std::max(_natural_width, sreq_natural.width); + _natural_width = std::max(_natural_width, sreq_natural.width); _natural_height = std::max(_natural_height, sreq_natural.height); _page_frame.remove(); return false; } -bool InkscapePreferences::PresentPage(const Gtk::TreeModel::iterator& iter) +bool InkscapePreferences::PresentPage(const Gtk::TreeModel::iterator &iter) { Gtk::TreeModel::Row row = *iter; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int desired_page = prefs->getInt("/dialogs/preferences/page", 0); _init = false; - if (desired_page == row[_page_list_columns._col_id]) - { + if (desired_page == row[_page_list_columns._col_id]) { auto const path = _page_list.get_model()->get_path(*iter); _page_list.expand_to_path(path); _page_list.get_selection()->select(iter); @@ -2772,19 +2988,18 @@ bool InkscapePreferences::PresentPage(const Gtk::TreeModel::iterator& iter) void InkscapePreferences::on_reset_open_recent_clicked() { Glib::RefPtr<Gtk::RecentManager> manager = Gtk::RecentManager::get_default(); - std::vector< Glib::RefPtr< Gtk::RecentInfo > > recent_list = manager->get_items(); + std::vector<Glib::RefPtr<Gtk::RecentInfo>> recent_list = manager->get_items(); // Remove only elements that were added by Inkscape // TODO: This should likely preserve items that were also accessed by other apps. // However there does not seem to be straightforward way to delete only an application from an item. for (auto e : recent_list) { - if (e->has_application(g_get_prgname()) - || e->has_application("org.inkscape.Inkscape") - || e->has_application("inkscape") + if (e->has_application(g_get_prgname()) || e->has_application("org.inkscape.Inkscape") || + e->has_application("inkscape") #ifdef _WIN32 || e->has_application("inkscape.exe") #endif - ) { + ) { manager->remove_item(e->get_uri()); } } @@ -2800,8 +3015,7 @@ void InkscapePreferences::on_pagelist_selection_changed() // show new selection Glib::RefPtr<Gtk::TreeSelection> selection = _page_list.get_selection(); Gtk::TreeModel::iterator iter = selection->get_selected(); - if(iter) - { + if (iter) { if (_current_page) _page_frame.remove(); Gtk::TreeModel::Row row = *iter; @@ -2810,7 +3024,7 @@ void InkscapePreferences::on_pagelist_selection_changed() if (!_init) { prefs->setInt("/dialogs/preferences/page", row[_page_list_columns._col_id]); } - Glib::ustring col_name_escaped = Glib::Markup::escape_text( row[_page_list_columns._col_name] ); + Glib::ustring col_name_escaped = Glib::Markup::escape_text(row[_page_list_columns._col_name]); _page_title.set_markup("<span size='large'><b>" + col_name_escaped + "</b></span>"); _page_frame.add(*_current_page); _current_page->show(); diff --git a/src/ui/dialog/inkscape-preferences.h b/src/ui/dialog/inkscape-preferences.h index 7e785e2658d1853410fce048c829f594b0479b1d..c44fb9f6e6189106b168c722523a8bbbdfca9b75 100644 --- a/src/ui/dialog/inkscape-preferences.h +++ b/src/ui/dialog/inkscape-preferences.h @@ -16,28 +16,29 @@ #ifndef INKSCAPE_UI_DIALOG_INKSCAPE_PREFERENCES_H #define INKSCAPE_UI_DIALOG_INKSCAPE_PREFERENCES_H -#include <iostream> -#include <vector> -#include "ui/widget/preferences-widget.h" #include <cstddef> #include <gtkmm/colorbutton.h> #include <gtkmm/comboboxtext.h> -#include <gtkmm/treestore.h> -#include <gtkmm/treeview.h> #include <gtkmm/frame.h> +#include <gtkmm/liststore.h> #include <gtkmm/notebook.h> -#include <gtkmm/textview.h> #include <gtkmm/scrolledwindow.h> -#include <gtkmm/liststore.h> +#include <gtkmm/textview.h> #include <gtkmm/treemodel.h> #include <gtkmm/treemodelfilter.h> +#include <gtkmm/treestore.h> +#include <gtkmm/treeview.h> +#include <iostream> +#include <vector> #include "ui/widget/panel.h" +#include "ui/widget/preferences-widget.h" // UPDATE THIS IF YOU'RE ADDING PREFS PAGES. // Otherwise the commands that open the dialog with the new page will fail. -enum { +enum +{ PREFS_PAGE_TOOLS, PREFS_PAGE_TOOLS_SELECTOR, PREFS_PAGE_TOOLS_NODE, @@ -98,7 +99,8 @@ namespace Inkscape { namespace UI { namespace Dialog { -class InkscapePreferences : public UI::Widget::Panel { +class InkscapePreferences : public UI::Widget::Panel +{ public: ~InkscapePreferences() override; @@ -110,15 +112,19 @@ protected: Gtk::TreeView _page_list; Glib::RefPtr<Gtk::TreeStore> _page_list_model; - //Pagelist model columns: + // Pagelist model columns: class PageListModelColumns : public Gtk::TreeModel::ColumnRecord { public: PageListModelColumns() - { Gtk::TreeModelColumnRecord::add(_col_name); Gtk::TreeModelColumnRecord::add(_col_page); Gtk::TreeModelColumnRecord::add(_col_id); } + { + Gtk::TreeModelColumnRecord::add(_col_name); + Gtk::TreeModelColumnRecord::add(_col_page); + Gtk::TreeModelColumnRecord::add(_col_id); + } Gtk::TreeModelColumn<Glib::ustring> _col_name; Gtk::TreeModelColumn<int> _col_id; - Gtk::TreeModelColumn<UI::Widget::DialogPage*> _col_page; + Gtk::TreeModelColumn<UI::Widget::DialogPage *> _col_page; }; PageListModelColumns _page_list_columns; @@ -180,7 +186,7 @@ protected: UI::Widget::PrefSpinButton _mouse_sens; UI::Widget::PrefSpinButton _mouse_thres; - UI::Widget::PrefSlider _mouse_grabsize; + UI::Widget::PrefSlider _mouse_grabsize; UI::Widget::PrefCheckButton _mouse_use_ext_input; UI::Widget::PrefCheckButton _mouse_switch_on_ext_input; @@ -192,21 +198,21 @@ protected: UI::Widget::PrefCheckButton _scroll_space; UI::Widget::PrefCheckButton _wheel_zoom; - Gtk::Scale *_slider_snapping_delay; + Gtk::Scale *_slider_snapping_delay; UI::Widget::PrefCheckButton _snap_default; UI::Widget::PrefCheckButton _snap_indicator; UI::Widget::PrefCheckButton _snap_closest_only; UI::Widget::PrefCheckButton _snap_mouse_pointer; - UI::Widget::PrefCombo _steps_rot_snap; + UI::Widget::PrefCombo _steps_rot_snap; UI::Widget::PrefCheckButton _steps_rot_relative; UI::Widget::PrefCheckButton _steps_compass; - UI::Widget::PrefSpinUnit _steps_arrow; - UI::Widget::PrefSpinUnit _steps_scale; - UI::Widget::PrefSpinUnit _steps_inset; - UI::Widget::PrefSpinButton _steps_zoom; - UI::Widget::PrefSpinButton _steps_rotate; + UI::Widget::PrefSpinUnit _steps_arrow; + UI::Widget::PrefSpinUnit _steps_scale; + UI::Widget::PrefSpinUnit _steps_inset; + UI::Widget::PrefSpinButton _steps_zoom; + UI::Widget::PrefSpinButton _steps_rotate; UI::Widget::PrefRadioButton _t_sel_trans_obj; UI::Widget::PrefRadioButton _t_sel_trans_outl; @@ -223,7 +229,7 @@ protected: UI::Widget::PrefCheckButton _t_node_live_objects; UI::Widget::PrefCheckButton _t_node_pathflash_enabled; UI::Widget::PrefCheckButton _t_node_pathflash_selected; - UI::Widget::PrefSpinButton _t_node_pathflash_timeout; + UI::Widget::PrefSpinButton _t_node_pathflash_timeout; UI::Widget::PrefCheckButton _t_node_show_path_direction; UI::Widget::PrefCheckButton _t_node_single_node_transform_handles; UI::Widget::PrefCheckButton _t_node_delete_preserves_shape; @@ -254,7 +260,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::PrefCombo _win_default_size; UI::Widget::PrefRadioButton _win_ontop_none; UI::Widget::PrefRadioButton _win_ontop_normal; UI::Widget::PrefRadioButton _win_ontop_agressive; @@ -298,14 +304,14 @@ 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::PrefCombo _dockbar_style; + UI::Widget::PrefCombo _switcher_style; UI::Widget::PrefCheckButton _rendering_image_outline; - UI::Widget::PrefSpinButton _rendering_cache_size; - UI::Widget::PrefSpinButton _rendering_tile_multiplier; - UI::Widget::PrefSpinButton _rendering_xray_radius; - UI::Widget::PrefCombo _rendering_redraw_priority; - UI::Widget::PrefSpinButton _filter_multi_threaded; + UI::Widget::PrefSpinButton _rendering_cache_size; + UI::Widget::PrefSpinButton _rendering_tile_multiplier; + UI::Widget::PrefSpinButton _rendering_xray_radius; + UI::Widget::PrefCombo _rendering_redraw_priority; + UI::Widget::PrefSpinButton _filter_multi_threaded; UI::Widget::PrefCheckButton _trans_scale_stroke; UI::Widget::PrefCheckButton _trans_scale_corner; @@ -330,33 +336,33 @@ protected: UI::Widget::PrefCheckButton _cleanup_swatches; - UI::Widget::PrefSpinButton _importexport_export_res; - UI::Widget::PrefSpinButton _importexport_import_res; + 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::PrefSlider _snap_persistence; + UI::Widget::PrefSlider _snap_delay; + UI::Widget::PrefSlider _snap_weight; + UI::Widget::PrefSlider _snap_persistence; UI::Widget::PrefCheckButton _font_dialog; - UI::Widget::PrefCombo _font_unit_type; + UI::Widget::PrefCombo _font_unit_type; UI::Widget::PrefCheckButton _font_output_px; UI::Widget::PrefCheckButton _font_fontsdir_system; UI::Widget::PrefCheckButton _font_fontsdir_user; - UI::Widget::PrefMultiEntry _font_fontdirs_custom; + UI::Widget::PrefMultiEntry _font_fontdirs_custom; UI::Widget::PrefCheckButton _misc_comment; UI::Widget::PrefCheckButton _misc_default_metadata; UI::Widget::PrefCheckButton _misc_forkvectors; - UI::Widget::PrefSpinButton _misc_gradientangle; + UI::Widget::PrefSpinButton _misc_gradientangle; UI::Widget::PrefCheckButton _misc_scripts; UI::Widget::PrefCheckButton _misc_namedicon_delay; // System page // Gtk::Button *_apply_theme; - UI::Widget::PrefSpinButton _misc_latency_skew; - UI::Widget::PrefSpinButton _misc_simpl; - Gtk::Entry _sys_user_prefs; - Gtk::Entry _sys_tmp_files; - Gtk::Entry _sys_extension_dir; + UI::Widget::PrefSpinButton _misc_latency_skew; + UI::Widget::PrefSpinButton _misc_simpl; + Gtk::Entry _sys_user_prefs; + Gtk::Entry _sys_tmp_files; + Gtk::Entry _sys_extension_dir; UI::Widget::PrefOpenFolder _sys_user_config; UI::Widget::PrefOpenFolder _sys_user_extension_dir; UI::Widget::PrefOpenFolder _sys_user_themes_dir; @@ -369,124 +375,125 @@ protected: UI::Widget::PrefOpenFolder _sys_user_symbols_dir; UI::Widget::PrefOpenFolder _sys_user_paint_servers_dir; UI::Widget::PrefMultiEntry _sys_fontdirs_custom; - Gtk::Entry _sys_user_cache; - Gtk::Entry _sys_data; - Gtk::TextView _sys_icon; - Gtk::ScrolledWindow _sys_icon_scroll; - Gtk::TextView _sys_systemdata; - Gtk::ScrolledWindow _sys_systemdata_scroll; + Gtk::Entry _sys_user_cache; + Gtk::Entry _sys_data; + Gtk::TextView _sys_icon; + Gtk::ScrolledWindow _sys_icon_scroll; + Gtk::TextView _sys_systemdata; + Gtk::ScrolledWindow _sys_systemdata_scroll; // UI page - UI::Widget::PrefCombo _ui_languages; + UI::Widget::PrefCombo _ui_languages; UI::Widget::PrefCheckButton _ui_colorsliders_top; - UI::Widget::PrefSpinButton _misc_recent; + UI::Widget::PrefSpinButton _misc_recent; UI::Widget::PrefCheckButton _ui_partialdynamic; UI::Widget::ZoomCorrRulerSlider _ui_zoom_correction; UI::Widget::PrefCheckButton _ui_yaxisdown; UI::Widget::PrefCheckButton _ui_rotationlock; - //Spellcheck - UI::Widget::PrefCombo _spell_language; - UI::Widget::PrefCombo _spell_language2; - UI::Widget::PrefCombo _spell_language3; + // Spellcheck + UI::Widget::PrefCombo _spell_language; + UI::Widget::PrefCombo _spell_language2; + UI::Widget::PrefCombo _spell_language3; 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::PrefEntryFileButtonHBox _misc_svg_editor; + UI::Widget::PrefCombo _misc_overs_bitmap; + UI::Widget::PrefEntryFileButtonHBox _misc_bitmap_editor; + UI::Widget::PrefEntryFileButtonHBox _misc_svg_editor; UI::Widget::PrefCheckButton _misc_bitmap_autoreload; - UI::Widget::PrefSpinButton _bitmap_copy_res; + UI::Widget::PrefSpinButton _bitmap_copy_res; UI::Widget::PrefCheckButton _bitmap_ask; UI::Widget::PrefCheckButton _svg_ask; - UI::Widget::PrefCombo _bitmap_link; - UI::Widget::PrefCombo _svg_link; - UI::Widget::PrefCombo _bitmap_scale; - UI::Widget::PrefSpinButton _bitmap_import_quality; + UI::Widget::PrefCombo _bitmap_link; + UI::Widget::PrefCombo _svg_link; + UI::Widget::PrefCombo _bitmap_scale; + UI::Widget::PrefSpinButton _bitmap_import_quality; - UI::Widget::PrefEntry _kb_search; - UI::Widget::PrefCombo _kb_filelist; + UI::Widget::PrefEntry _kb_search; + UI::Widget::PrefCombo _kb_filelist; UI::Widget::PrefCheckButton _save_use_current_dir; UI::Widget::PrefCheckButton _save_autosave_enable; - UI::Widget::PrefSpinButton _save_autosave_interval; - UI::Widget::PrefEntry _save_autosave_path; - UI::Widget::PrefSpinButton _save_autosave_max; - - Gtk::ComboBoxText _cms_display_profile; - UI::Widget::PrefCheckButton _cms_from_display; - UI::Widget::PrefCombo _cms_intent; - - UI::Widget::PrefCheckButton _cms_softproof; - UI::Widget::PrefCheckButton _cms_gamutwarn; - Gtk::ColorButton _cms_gamutcolor; - Gtk::ComboBoxText _cms_proof_profile; - UI::Widget::PrefCombo _cms_proof_intent; - UI::Widget::PrefCheckButton _cms_proof_blackpoint; - UI::Widget::PrefCheckButton _cms_proof_preserveblack; - - Gtk::Notebook _grids_notebook; - 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; + UI::Widget::PrefSpinButton _save_autosave_interval; + UI::Widget::PrefEntry _save_autosave_path; + UI::Widget::PrefSpinButton _save_autosave_max; + + Gtk::ComboBoxText _cms_display_profile; + UI::Widget::PrefCheckButton _cms_from_display; + UI::Widget::PrefCombo _cms_intent; + + UI::Widget::PrefCheckButton _cms_softproof; + UI::Widget::PrefCheckButton _cms_gamutwarn; + Gtk::ColorButton _cms_gamutcolor; + Gtk::ComboBoxText _cms_proof_profile; + UI::Widget::PrefCombo _cms_proof_intent; + UI::Widget::PrefCheckButton _cms_proof_blackpoint; + UI::Widget::PrefCheckButton _cms_proof_preserveblack; + + Gtk::Notebook _grids_notebook; + 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: - UI::Widget::PrefUnit _grids_xy_units; - UI::Widget::PrefSpinButton _grids_xy_origin_x; - UI::Widget::PrefSpinButton _grids_xy_origin_y; - UI::Widget::PrefSpinButton _grids_xy_spacing_x; - UI::Widget::PrefSpinButton _grids_xy_spacing_y; - UI::Widget::PrefColorPicker _grids_xy_color; - UI::Widget::PrefColorPicker _grids_xy_empcolor; - UI::Widget::PrefSpinButton _grids_xy_empspacing; - UI::Widget::PrefCheckButton _grids_xy_dotted; + UI::Widget::PrefUnit _grids_xy_units; + UI::Widget::PrefSpinButton _grids_xy_origin_x; + UI::Widget::PrefSpinButton _grids_xy_origin_y; + UI::Widget::PrefSpinButton _grids_xy_spacing_x; + UI::Widget::PrefSpinButton _grids_xy_spacing_y; + UI::Widget::PrefColorPicker _grids_xy_color; + UI::Widget::PrefColorPicker _grids_xy_empcolor; + UI::Widget::PrefSpinButton _grids_xy_empspacing; + UI::Widget::PrefCheckButton _grids_xy_dotted; // CanvasAxonomGrid properties: - UI::Widget::PrefUnit _grids_axonom_units; - UI::Widget::PrefSpinButton _grids_axonom_origin_x; - UI::Widget::PrefSpinButton _grids_axonom_origin_y; - UI::Widget::PrefSpinButton _grids_axonom_spacing_y; - UI::Widget::PrefSpinButton _grids_axonom_angle_x; - UI::Widget::PrefSpinButton _grids_axonom_angle_z; - UI::Widget::PrefColorPicker _grids_axonom_color; - UI::Widget::PrefColorPicker _grids_axonom_empcolor; - UI::Widget::PrefSpinButton _grids_axonom_empspacing; + UI::Widget::PrefUnit _grids_axonom_units; + UI::Widget::PrefSpinButton _grids_axonom_origin_x; + UI::Widget::PrefSpinButton _grids_axonom_origin_y; + UI::Widget::PrefSpinButton _grids_axonom_spacing_y; + UI::Widget::PrefSpinButton _grids_axonom_angle_x; + UI::Widget::PrefSpinButton _grids_axonom_angle_z; + UI::Widget::PrefColorPicker _grids_axonom_color; + UI::Widget::PrefColorPicker _grids_axonom_empcolor; + UI::Widget::PrefSpinButton _grids_axonom_empspacing; // SVG Output page: - UI::Widget::PrefCheckButton _svgoutput_usenamedcolors; - UI::Widget::PrefCheckButton _svgoutput_usesodipodiabsref; - UI::Widget::PrefSpinButton _svgoutput_numericprecision; - UI::Widget::PrefSpinButton _svgoutput_minimumexponent; - UI::Widget::PrefCheckButton _svgoutput_inlineattrs; - UI::Widget::PrefSpinButton _svgoutput_indent; - UI::Widget::PrefCombo _svgoutput_pathformat; - UI::Widget::PrefCheckButton _svgoutput_forcerepeatcommands; + UI::Widget::PrefCheckButton _svgoutput_usenamedcolors; + UI::Widget::PrefCheckButton _svgoutput_usesodipodiabsref; + UI::Widget::PrefSpinButton _svgoutput_numericprecision; + UI::Widget::PrefSpinButton _svgoutput_minimumexponent; + UI::Widget::PrefCheckButton _svgoutput_inlineattrs; + UI::Widget::PrefSpinButton _svgoutput_indent; + UI::Widget::PrefCombo _svgoutput_pathformat; + UI::Widget::PrefCheckButton _svgoutput_forcerepeatcommands; // Attribute Checking controls for SVG Output page: - UI::Widget::PrefCheckButton _svgoutput_attrwarn; - UI::Widget::PrefCheckButton _svgoutput_attrremove; - UI::Widget::PrefCheckButton _svgoutput_stylepropwarn; - UI::Widget::PrefCheckButton _svgoutput_stylepropremove; - UI::Widget::PrefCheckButton _svgoutput_styledefaultswarn; - UI::Widget::PrefCheckButton _svgoutput_styledefaultsremove; - UI::Widget::PrefCheckButton _svgoutput_check_reading; - UI::Widget::PrefCheckButton _svgoutput_check_editing; - UI::Widget::PrefCheckButton _svgoutput_check_writing; + UI::Widget::PrefCheckButton _svgoutput_attrwarn; + UI::Widget::PrefCheckButton _svgoutput_attrremove; + UI::Widget::PrefCheckButton _svgoutput_stylepropwarn; + UI::Widget::PrefCheckButton _svgoutput_stylepropremove; + UI::Widget::PrefCheckButton _svgoutput_styledefaultswarn; + UI::Widget::PrefCheckButton _svgoutput_styledefaultsremove; + UI::Widget::PrefCheckButton _svgoutput_check_reading; + UI::Widget::PrefCheckButton _svgoutput_check_editing; + UI::Widget::PrefCheckButton _svgoutput_check_writing; // SVG Output export: - UI::Widget::PrefCheckButton _svgexport_insert_text_fallback; - UI::Widget::PrefCheckButton _svgexport_insert_mesh_polyfill; - UI::Widget::PrefCheckButton _svgexport_insert_hatch_polyfill; - UI::Widget::PrefCheckButton _svgexport_remove_marker_auto_start_reverse; - UI::Widget::PrefCheckButton _svgexport_remove_marker_context_paint; - + UI::Widget::PrefCheckButton _svgexport_insert_text_fallback; + UI::Widget::PrefCheckButton _svgexport_insert_mesh_polyfill; + UI::Widget::PrefCheckButton _svgexport_insert_hatch_polyfill; + UI::Widget::PrefCheckButton _svgexport_remove_marker_auto_start_reverse; + UI::Widget::PrefCheckButton _svgexport_remove_marker_context_paint; /* * Keyboard shortcut members */ - class ModelColumns: public Gtk::TreeModel::ColumnRecord { + class ModelColumns : public Gtk::TreeModel::ColumnRecord + { public: - ModelColumns() { + ModelColumns() + { add(name); add(id); add(shortcut); @@ -515,37 +522,43 @@ protected: int _minimum_height; int _natural_width; int _natural_height; - bool GetSizeRequest(const Gtk::TreeModel::iterator& iter); - void get_preferred_width_vfunc (int& minimum_width, int& natural_width) const override { + bool GetSizeRequest(const Gtk::TreeModel::iterator &iter); + void get_preferred_width_vfunc(int &minimum_width, int &natural_width) const override + { minimum_width = _minimum_width; natural_width = _natural_width; } - void get_preferred_width_for_height_vfunc (int height, int& minimum_width, int& natural_width) const override { + void get_preferred_width_for_height_vfunc(int height, int &minimum_width, int &natural_width) const override + { minimum_width = _minimum_width; natural_width = _natural_width; } - void get_preferred_height_vfunc (int& minimum_height, int& natural_height) const override { + void get_preferred_height_vfunc(int &minimum_height, int &natural_height) const override + { minimum_height = _minimum_height; natural_height = _natural_height; } - void get_preferred_height_for_width_vfunc (int width, int& minimum_height, int& natural_height) const override { + void get_preferred_height_for_width_vfunc(int width, int &minimum_height, int &natural_height) const override + { minimum_height = _minimum_height; natural_height = _natural_height; } int _sb_width; - UI::Widget::DialogPage* _current_page; - - Gtk::TreeModel::iterator AddPage(UI::Widget::DialogPage& p, Glib::ustring title, int id); - Gtk::TreeModel::iterator AddPage(UI::Widget::DialogPage& p, Glib::ustring title, Gtk::TreeModel::iterator parent, int id); - bool PresentPage(const Gtk::TreeModel::iterator& iter); - - static void AddSelcueCheckbox(UI::Widget::DialogPage& p, Glib::ustring const &prefs_path, bool def_value); - static void AddGradientCheckbox(UI::Widget::DialogPage& p, Glib::ustring const &prefs_path, bool def_value); - static void AddConvertGuidesCheckbox(UI::Widget::DialogPage& p, Glib::ustring const &prefs_path, bool def_value); - static void AddFirstAndLastCheckbox(UI::Widget::DialogPage& p, Glib::ustring const &prefs_path, bool def_value); - static void AddDotSizeSpinbutton(UI::Widget::DialogPage& p, Glib::ustring const &prefs_path, double def_value); - static void AddBaseSimplifySpinbutton(UI::Widget::DialogPage& p, Glib::ustring const &prefs_path, double def_value); - static void AddNewObjectsStyle(UI::Widget::DialogPage& p, Glib::ustring const &prefs_path, const gchar* banner = nullptr); + UI::Widget::DialogPage *_current_page; + + Gtk::TreeModel::iterator AddPage(UI::Widget::DialogPage &p, Glib::ustring title, int id); + Gtk::TreeModel::iterator AddPage(UI::Widget::DialogPage &p, Glib::ustring title, Gtk::TreeModel::iterator parent, + int id); + bool PresentPage(const Gtk::TreeModel::iterator &iter); + + static void AddSelcueCheckbox(UI::Widget::DialogPage &p, Glib::ustring const &prefs_path, bool def_value); + static void AddGradientCheckbox(UI::Widget::DialogPage &p, Glib::ustring const &prefs_path, bool def_value); + static void AddConvertGuidesCheckbox(UI::Widget::DialogPage &p, Glib::ustring const &prefs_path, bool def_value); + static void AddFirstAndLastCheckbox(UI::Widget::DialogPage &p, Glib::ustring const &prefs_path, bool def_value); + static void AddDotSizeSpinbutton(UI::Widget::DialogPage &p, Glib::ustring const &prefs_path, double def_value); + static void AddBaseSimplifySpinbutton(UI::Widget::DialogPage &p, Glib::ustring const &prefs_path, double def_value); + static void AddNewObjectsStyle(UI::Widget::DialogPage &p, Glib::ustring const &prefs_path, + const gchar *banner = nullptr); void on_pagelist_selection_changed(); void on_reset_open_recent_clicked(); @@ -574,36 +587,37 @@ protected: 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); + 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); + bool onKBSearchFilter(const Gtk::TreeModel::const_iterator &iter); static void onKBShortcutRenderer(Gtk::CellRenderer *rndr, Gtk::TreeIter const &iter); private: - void themeChange(); - void preferDarkThemeChange(); - void symbolicThemeCheck(); - void toggleSymbolic(); - void changeIconsColors(); - void resetIconsColors(bool themechange = false); - void resetIconsColorsWrapper(); - void changeIconsColor(guint32 /*color*/); - void get_highlight_colors(guint32 &colorsetbase, guint32 &colorsetsuccess, guint32 &colorsetwarning, - guint32 &colorseterror); - - std::map<Glib::ustring, bool> dark_themes; - InkscapePreferences(); - InkscapePreferences(InkscapePreferences const &d); - InkscapePreferences operator=(InkscapePreferences const &d); - bool _init; + void themeChange(); + void preferDarkThemeChange(); + void symbolicThemeCheck(); + void toggleSymbolic(); + void changeIconsColors(); + void resetIconsColors(bool themechange = false); + void resetIconsColorsWrapper(); + void changeIconsColor(guint32 /*color*/); + void get_highlight_colors(guint32 &colorsetbase, guint32 &colorsetsuccess, guint32 &colorsetwarning, + guint32 &colorseterror); + + std::map<Glib::ustring, bool> dark_themes; + InkscapePreferences(); + InkscapePreferences(InkscapePreferences const &d); + InkscapePreferences operator=(InkscapePreferences const &d); + bool _init; }; } // namespace Dialog } // namespace UI } // namespace Inkscape -#endif //INKSCAPE_UI_DIALOG_INKSCAPE_PREFERENCES_H +#endif // INKSCAPE_UI_DIALOG_INKSCAPE_PREFERENCES_H /* Local Variables: diff --git a/src/ui/dialog/input.cpp b/src/ui/dialog/input.cpp index 0f33cbba845379dcc42773ea43b25afa8cb0af44..f222c57246b80ed05565a5d550b85874d0d33696 100644 --- a/src/ui/dialog/input.cpp +++ b/src/ui/dialog/input.cpp @@ -10,18 +10,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <map> -#include <set> -#include <list> -#include "ui/widget/panel.h" -#include "ui/widget/frame.h" +#include "input.h" #include <glibmm/i18n.h> - #include <gtkmm/buttonbox.h> #include <gtkmm/cellrenderercombo.h> #include <gtkmm/checkbutton.h> #include <gtkmm/comboboxtext.h> +#include <gtkmm/eventbox.h> #include <gtkmm/grid.h> #include <gtkmm/liststore.h> #include <gtkmm/menubar.h> @@ -30,12 +26,14 @@ #include <gtkmm/progressbar.h> #include <gtkmm/scrolledwindow.h> #include <gtkmm/treestore.h> -#include <gtkmm/eventbox.h> +#include <list> +#include <map> +#include <set> #include "device-manager.h" #include "preferences.h" - -#include "input.h" +#include "ui/widget/frame.h" +#include "ui/widget/panel.h" // clang-format off /* XPM */ @@ -327,19 +325,23 @@ namespace Inkscape { namespace UI { namespace Dialog { - - class DeviceModelColumns : public Gtk::TreeModel::ColumnRecord { public: - Gtk::TreeModelColumn<bool> toggler; - Gtk::TreeModelColumn<Glib::ustring> expander; - Gtk::TreeModelColumn<Glib::ustring> description; - Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf> > thumbnail; - Gtk::TreeModelColumn<Glib::RefPtr<InputDevice const> > device; - Gtk::TreeModelColumn<Gdk::InputMode> mode; - - DeviceModelColumns() { add(toggler), add(expander), add(description); add(thumbnail); add(device); add(mode); } + Gtk::TreeModelColumn<bool> toggler; + Gtk::TreeModelColumn<Glib::ustring> expander; + Gtk::TreeModelColumn<Glib::ustring> description; + Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf>> thumbnail; + Gtk::TreeModelColumn<Glib::RefPtr<InputDevice const>> device; + Gtk::TreeModelColumn<Gdk::InputMode> mode; + + DeviceModelColumns() + { + add(toggler), add(expander), add(description); + add(thumbnail); + add(device); + add(mode); + } }; static std::map<Gdk::InputMode, Glib::ustring> &getModeToString() @@ -347,8 +349,8 @@ static std::map<Gdk::InputMode, Glib::ustring> &getModeToString() static std::map<Gdk::InputMode, Glib::ustring> mapping; if (mapping.empty()) { mapping[Gdk::MODE_DISABLED] = _("Disabled"); - mapping[Gdk::MODE_SCREEN] = C_("Input device", "Screen"); - mapping[Gdk::MODE_WINDOW] = _("Window"); + mapping[Gdk::MODE_SCREEN] = C_("Input device", "Screen"); + mapping[Gdk::MODE_WINDOW] = _("Window"); } return mapping; @@ -356,9 +358,12 @@ static std::map<Gdk::InputMode, Glib::ustring> &getModeToString() 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; + if (im == Gdk::MODE_DISABLED) + return 0; + if (im == Gdk::MODE_SCREEN) + return 1; + if (im == Gdk::MODE_WINDOW) + return 2; return 0; } @@ -368,16 +373,15 @@ static std::map<Glib::ustring, Gdk::InputMode> &getStringToMode() static std::map<Glib::ustring, Gdk::InputMode> mapping; if (mapping.empty()) { mapping[_("Disabled")] = Gdk::MODE_DISABLED; - mapping[_("Screen")] = Gdk::MODE_SCREEN; - mapping[_("Window")] = Gdk::MODE_WINDOW; + mapping[_("Screen")] = Gdk::MODE_SCREEN; + mapping[_("Window")] = Gdk::MODE_WINDOW; } return mapping; } - - -class InputDialogImpl : public InputDialog { +class InputDialogImpl : public InputDialog +{ public: InputDialogImpl(); ~InputDialogImpl() override = default; @@ -399,7 +403,8 @@ private: ConfPanel &parent; }; - static void commitCellModeChange(Glib::ustring const &path, Glib::ustring const &newText, Glib::RefPtr<Gtk::TreeStore> store); + static void commitCellModeChange(Glib::ustring const &path, Glib::ustring const &newText, + Glib::RefPtr<Gtk::TreeStore> store); static void setModeCellString(Gtk::CellRenderer *rndr, Gtk::TreeIter const &iter); static void commitCellStateChange(Glib::ustring const &path, Glib::RefPtr<Gtk::TreeStore> store); @@ -433,7 +438,7 @@ private: class KeysColumns : public Gtk::TreeModel::ColumnRecord { - public: + public: KeysColumns() { add(name); @@ -449,27 +454,38 @@ private: KeysColumns axisColumns; Glib::RefPtr<Gtk::ListStore> axisStore; - Gtk::TreeView axisTree; + Gtk::TreeView axisTree; Gtk::ScrolledWindow axisScroll; Glib::RefPtr<Gtk::ListStore> keysStore; - Gtk::TreeView keysTree; + Gtk::TreeView keysTree; Gtk::ScrolledWindow keysScroll; Gtk::CellRendererAccel _kb_shortcut_renderer; - - }; static DeviceModelColumns &getCols(); - enum PixId {PIX_CORE, PIX_PEN, PIX_MOUSE, PIX_TIP, PIX_TABLET, PIX_ERASER, PIX_SIDEBUTTONS, - PIX_BUTTONS_NONE, PIX_BUTTONS_ON, PIX_BUTTONS_OFF, - PIX_AXIS_NONE, PIX_AXIS_ON, PIX_AXIS_OFF}; + enum PixId + { + PIX_CORE, + PIX_PEN, + PIX_MOUSE, + PIX_TIP, + PIX_TABLET, + PIX_ERASER, + PIX_SIDEBUTTONS, + PIX_BUTTONS_NONE, + PIX_BUTTONS_ON, + PIX_BUTTONS_OFF, + PIX_AXIS_NONE, + PIX_AXIS_ON, + PIX_AXIS_OFF + }; static Glib::RefPtr<Gdk::Pixbuf> getPix(PixId id); - std::map<Glib::ustring, std::set<guint> > buttonMap; - std::map<Glib::ustring, std::map<guint, std::pair<guint, gdouble> > > axesMap; + std::map<Glib::ustring, std::set<guint>> buttonMap; + std::map<Glib::ustring, std::map<guint, std::pair<guint, gdouble>>> axesMap; Gdk::InputSource lastSourceSeen; Glib::ustring lastDevnameSeen; @@ -503,31 +519,27 @@ private: 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, gdouble const * axes, GdkDevice* dev); - Glib::ustring getKeyFor( GdkDevice* device ); - bool eventSnoop(GdkEvent* event); + 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, gdouble const *axes, GdkDevice *dev); + Glib::ustring getKeyFor(GdkDevice *device); + bool eventSnoop(GdkEvent *event); void linkComboChanged(); void resyncToSelection(); void handleDeviceChange(Glib::RefPtr<InputDevice const> device); void updateDeviceAxes(Glib::RefPtr<InputDevice const> device); void updateDeviceButtons(Glib::RefPtr<InputDevice const> device); - static void updateDeviceLinks(Glib::RefPtr<InputDevice const> device, Gtk::TreeIter tabletIter, Gtk::TreeView *tree); + static void updateDeviceLinks(Glib::RefPtr<InputDevice const> device, Gtk::TreeIter tabletIter, + Gtk::TreeView *tree); - static bool findDevice(const Gtk::TreeModel::iterator& iter, - Glib::ustring id, - Gtk::TreeModel::iterator* result); - static bool findDeviceByLink(const Gtk::TreeModel::iterator& iter, - Glib::ustring link, - Gtk::TreeModel::iterator* result); + static bool findDevice(const Gtk::TreeModel::iterator &iter, Glib::ustring id, Gtk::TreeModel::iterator *result); + static bool findDeviceByLink(const Gtk::TreeModel::iterator &iter, Glib::ustring link, + Gtk::TreeModel::iterator *result); }; // class InputDialogImpl - DeviceModelColumns &InputDialogImpl::getCols() { static DeviceModelColumns cols; @@ -536,23 +548,23 @@ DeviceModelColumns &InputDialogImpl::getCols() Glib::RefPtr<Gdk::Pixbuf> InputDialogImpl::getPix(PixId id) { - static std::map<PixId, Glib::RefPtr<Gdk::Pixbuf> > mappings; + static std::map<PixId, Glib::RefPtr<Gdk::Pixbuf>> mappings; - mappings[PIX_CORE] = Gdk::Pixbuf::create_from_xpm_data(core_xpm); - mappings[PIX_PEN] = Gdk::Pixbuf::create_from_xpm_data(pen); - mappings[PIX_MOUSE] = Gdk::Pixbuf::create_from_xpm_data(mouse); - mappings[PIX_TIP] = Gdk::Pixbuf::create_from_xpm_data(tip); - mappings[PIX_TABLET] = Gdk::Pixbuf::create_from_xpm_data(tablet); - mappings[PIX_ERASER] = Gdk::Pixbuf::create_from_xpm_data(eraser); - mappings[PIX_SIDEBUTTONS] = Gdk::Pixbuf::create_from_xpm_data(sidebuttons); + mappings[PIX_CORE] = Gdk::Pixbuf::create_from_xpm_data(core_xpm); + mappings[PIX_PEN] = Gdk::Pixbuf::create_from_xpm_data(pen); + mappings[PIX_MOUSE] = Gdk::Pixbuf::create_from_xpm_data(mouse); + mappings[PIX_TIP] = Gdk::Pixbuf::create_from_xpm_data(tip); + mappings[PIX_TABLET] = Gdk::Pixbuf::create_from_xpm_data(tablet); + mappings[PIX_ERASER] = Gdk::Pixbuf::create_from_xpm_data(eraser); + mappings[PIX_SIDEBUTTONS] = Gdk::Pixbuf::create_from_xpm_data(sidebuttons); - mappings[PIX_BUTTONS_NONE] = Gdk::Pixbuf::create_from_xpm_data(button_none); - mappings[PIX_BUTTONS_ON] = Gdk::Pixbuf::create_from_xpm_data(button_on); - mappings[PIX_BUTTONS_OFF] = Gdk::Pixbuf::create_from_xpm_data(button_off); + mappings[PIX_BUTTONS_NONE] = Gdk::Pixbuf::create_from_xpm_data(button_none); + mappings[PIX_BUTTONS_ON] = Gdk::Pixbuf::create_from_xpm_data(button_on); + mappings[PIX_BUTTONS_OFF] = Gdk::Pixbuf::create_from_xpm_data(button_off); - mappings[PIX_AXIS_NONE] = Gdk::Pixbuf::create_from_xpm_data(axis_none_xpm); - mappings[PIX_AXIS_ON] = Gdk::Pixbuf::create_from_xpm_data(axis_on_xpm); - mappings[PIX_AXIS_OFF] = Gdk::Pixbuf::create_from_xpm_data(axis_off_xpm); + mappings[PIX_AXIS_NONE] = Gdk::Pixbuf::create_from_xpm_data(axis_none_xpm); + mappings[PIX_AXIS_ON] = Gdk::Pixbuf::create_from_xpm_data(axis_on_xpm); + mappings[PIX_AXIS_OFF] = Gdk::Pixbuf::create_from_xpm_data(axis_off_xpm); Glib::RefPtr<Gdk::Pixbuf> pix; if (mappings.find(id) != mappings.end()) { @@ -562,7 +574,6 @@ Glib::RefPtr<Gdk::Pixbuf> InputDialogImpl::getPix(PixId id) return pix; } - // Now that we've defined the *Impl class, we can do the method to acquire one. InputDialog &InputDialog::getInstance() { @@ -570,26 +581,25 @@ InputDialog &InputDialog::getInstance() return *dialog; } - -InputDialogImpl::InputDialogImpl() : - InputDialog(), - lastSourceSeen(static_cast<Gdk::InputSource>(-1)), - lastDevnameSeen(""), - deviceStore(Gtk::TreeStore::create(getCols())), - deviceIter(), - deviceTree(deviceStore), - testFrame(_("Test Area")), - axisFrame(_("Axis")), - treeScroller(), - detailScroller(), - splitter(), - split2(Gtk::ORIENTATION_VERTICAL), - axisTable(), - linkCombo(), - topHolder(), - imageTable(), - testDetector(), - cfgPanel() +InputDialogImpl::InputDialogImpl() + : InputDialog() + , lastSourceSeen(static_cast<Gdk::InputSource>(-1)) + , lastDevnameSeen("") + , deviceStore(Gtk::TreeStore::create(getCols())) + , deviceIter() + , deviceTree(deviceStore) + , testFrame(_("Test Area")) + , axisFrame(_("Axis")) + , treeScroller() + , detailScroller() + , splitter() + , split2(Gtk::ORIENTATION_VERTICAL) + , axisTable() + , linkCombo() + , topHolder() + , imageTable() + , testDetector() + , cfgPanel() { Gtk::Box *contents = _getContents(); @@ -618,7 +628,7 @@ InputDialogImpl::InputDialogImpl() : { guint col = 0; guint row = 1; - for (auto & testButton : testButtons) { + for (auto &testButton : testButtons) { testButton.set(getPix(PIX_BUTTONS_NONE)); imageTable.attach(testButton, col, row, 1, 1); col++; @@ -629,7 +639,7 @@ InputDialogImpl::InputDialogImpl() : } col = 0; - for (auto & testAxe : testAxes) { + for (auto &testAxe : testAxes) { testAxe.set(getPix(PIX_AXIS_NONE)); imageTable.attach(testAxe, col * 2, row, 2, 1); col++; @@ -640,7 +650,6 @@ InputDialogImpl::InputDialogImpl() : } } - // 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")) { @@ -653,7 +662,6 @@ InputDialogImpl::InputDialogImpl() : contents->pack_start(cfgPanel); } - int rowNum = 0; axisFrame.add(axisTable); @@ -672,18 +680,16 @@ InputDialogImpl::InputDialogImpl() : axisTable.attach(devAxesCount, 1, rowNum, 1, 1); rowNum++; - for (auto & axesValue : axesValues) { + for (auto &axesValue : axesValues) { lbl = Gtk::manage(new Gtk::Label(_("axis:"))); lbl->set_hexpand(); axisTable.attach(*lbl, 0, rowNum, 1, 1); - + axesValue.set_hexpand(); axisTable.attach(axesValue, 1, rowNum, 1, 1); axesValue.set_sensitive(false); rowNum++; - - } lbl = Gtk::manage(new Gtk::Label(_("Button count:"))); @@ -701,22 +707,22 @@ InputDialogImpl::InputDialogImpl() : // TODO: Extension event stuff has been removed from public API in GTK+ 3 // Need to check that this hasn't broken anything - 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); + 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); axisTable.attach(keyEntry, 0, rowNum, 2, 1); rowNum++; - axisTable.set_sensitive(false); -//- 16x16/devices -// gnome-dev-mouse-optical -// input-mouse -// input-tablet -// mouse + //- 16x16/devices + // gnome-dev-mouse-optical + // input-mouse + // input-tablet + // mouse - //Add the TreeView's view columns: + // Add the TreeView's view columns: deviceTree.append_column("I", getCols().thumbnail); deviceTree.append_column("Bar", getCols().description); @@ -724,39 +730,42 @@ InputDialogImpl::InputDialogImpl() : deviceTree.set_headers_visible(false); deviceTree.get_selection()->signal_changed().connect(sigc::mem_fun(*this, &InputDialogImpl::resyncToSelection)); + setupTree(deviceStore, deviceIter); - 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)); - Inkscape::DeviceManager::getManager().signalLinkChanged().connect(sigc::bind(sigc::ptr_fun(&InputDialogImpl::updateDeviceLinks), deviceIter, &deviceTree)); + 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)); + Inkscape::DeviceManager::getManager().signalLinkChanged().connect( + sigc::bind(sigc::ptr_fun(&InputDialogImpl::updateDeviceLinks), deviceIter, &deviceTree)); deviceTree.expand_all(); show_all_children(); } -class TabletTmp { +class TabletTmp +{ public: TabletTmp() = default; Glib::ustring name; - std::list<Glib::RefPtr<InputDevice const> > devices; + std::list<Glib::RefPtr<InputDevice const>> devices; }; -static Glib::ustring getCommon( std::list<Glib::ustring> const &names ) +static Glib::ustring getCommon(std::list<Glib::ustring> const &names) { Glib::ustring result; - if ( !names.empty() ) { + if (!names.empty()) { size_t pos = 0; bool match = true; - while ( match ) { - if ( names.begin()->length() > pos ) { + while (match) { + if (names.begin()->length() > pos) { gunichar ch = (*names.begin())[pos]; - for (const auto & name : names) { - if ( (pos >= name.length()) - || (name[pos] != ch) ) { + for (const auto &name : names) { + if ((pos >= name.length()) || (name[pos] != ch)) { match = false; break; } @@ -774,7 +783,6 @@ static Glib::ustring getCommon( std::list<Glib::ustring> const &names ) return result; } - void InputDialogImpl::ConfPanel::onModeChange() { Glib::ustring newText = modeCombo.get_active_text(); @@ -785,19 +793,17 @@ void InputDialogImpl::ConfPanel::onModeChange() 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 ); + Inkscape::DeviceManager::getManager().setMode(dev->getId(), mode); } } - } - -void InputDialogImpl::setupTree( Glib::RefPtr<Gtk::TreeStore> store, Gtk::TreeIter &tablet ) +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"); + std::list<Glib::RefPtr<InputDevice const>> devList = Inkscape::DeviceManager::getManager().getDevices(); + if (!devList.empty()) { + // Gtk::TreeModel::Row row = *(store->append()); + // row[getCols().description] = _("Hardware"); // Let's make some tablets!!! std::list<TabletTmp> tablets; @@ -805,10 +811,10 @@ void InputDialogImpl::setupTree( Glib::RefPtr<Gtk::TreeStore> store, Gtk::TreeIt // Phase 1 - figure out which tablets are present for (auto dev : devList) { - if ( dev ) { - if ( dev->getSource() != Gdk::SOURCE_MOUSE ) { - consumed.insert( dev->getId() ); - if ( tablets.empty() ) { + if (dev) { + if (dev->getSource() != Gdk::SOURCE_MOUSE) { + consumed.insert(dev->getId()); + if (tablets.empty()) { TabletTmp tmp; tablets.push_back(tmp); } @@ -820,30 +826,31 @@ void InputDialogImpl::setupTree( Glib::RefPtr<Gtk::TreeStore> store, Gtk::TreeIt } // Phase 2 - build a UI for the present devices - for (auto & it : tablets) { + for (auto &it : tablets) { tablet = store->prepend(/*row.children()*/); Gtk::TreeModel::Row childrow = *tablet; - if ( it.name.empty() ) { + if (it.name.empty()) { // Check to see if we can derive one std::list<Glib::ustring> names; - for (auto & device : it.devices) { - names.push_back( device->getName() ); + for (auto &device : it.devices) { + names.push_back(device->getName()); } Glib::ustring common = getCommon(names); - if ( !common.empty() ) { + if (!common.empty()) { it.name = common; } } - childrow[getCols().description] = it.name.empty() ? _("Tablet") : it.name ; + childrow[getCols().description] = it.name.empty() ? _("Tablet") : it.name; childrow[getCols().thumbnail] = getPix(PIX_TABLET); // Check if there is an eraser we can link to a pen - for ( std::list<Glib::RefPtr<InputDevice const> >::iterator it2 = it.devices.begin(); it2 != it.devices.end(); ++it2 ) { + for (std::list<Glib::RefPtr<InputDevice const>>::iterator it2 = it.devices.begin(); it2 != it.devices.end(); + ++it2) { Glib::RefPtr<InputDevice const> dev = *it2; - if ( dev->getSource() == Gdk::SOURCE_PEN ) { + if (dev->getSource() == Gdk::SOURCE_PEN) { for (auto dev2 : it.devices) { - if ( dev2->getSource() == Gdk::SOURCE_ERASER ) { - DeviceManager::getManager().setLinkedTo(dev->getId(), dev2->getId()); + if (dev2->getSource() == Gdk::SOURCE_ERASER) { + DeviceManager::getManager().setLinkedTo(dev->getId(), dev2->getId()); break; // only check the first eraser... for now } break; // only check the first pen... for now @@ -856,7 +863,7 @@ void InputDialogImpl::setupTree( Glib::RefPtr<Gtk::TreeStore> store, Gtk::TreeIt deviceRow[getCols().description] = dev->getName(); deviceRow[getCols().device] = dev; deviceRow[getCols().mode] = dev->getMode(); - switch ( dev->getSource() ) { + switch (dev->getSource()) { case Gdk::SOURCE_MOUSE: deviceRow[getCols().thumbnail] = getPix(PIX_CORE); break; @@ -873,14 +880,13 @@ void InputDialogImpl::setupTree( Glib::RefPtr<Gtk::TreeStore> store, Gtk::TreeIt case Gdk::SOURCE_ERASER: deviceRow[getCols().thumbnail] = getPix(PIX_ERASER); break; - default: - ; // nothing + default:; // nothing } } } for (auto dev : devList) { - if ( dev && (consumed.find( dev->getId() ) == consumed.end()) ) { + if (dev && (consumed.find(dev->getId()) == consumed.end())) { Gtk::TreeModel::Row deviceRow = *(store->prepend(/*row.children()*/)); deviceRow[getCols().description] = dev->getName(); deviceRow[getCols().device] = dev; @@ -894,27 +900,24 @@ void InputDialogImpl::setupTree( Glib::RefPtr<Gtk::TreeStore> store, Gtk::TreeIt } } - -InputDialogImpl::ConfPanel::ConfPanel() : - Gtk::VBox(), - confDeviceStore(Gtk::TreeStore::create(getCols())), - confDeviceIter(), - confDeviceTree(confDeviceStore), - confDeviceScroller(), - watcher(*this), - useExt(_("_Use pressure-sensitive tablet (requires restart)"), true), - save(_("_Save"), true), - detailsBox(false, 4), - titleFrame(false, 4), - titleLabel(""), - axisFrame(_("Axes")), - keysFrame(_("Keys")), - modeLabel(_("Mode:")), - modeBox(false, 4) +InputDialogImpl::ConfPanel::ConfPanel() + : Gtk::VBox() + , confDeviceStore(Gtk::TreeStore::create(getCols())) + , confDeviceIter() + , confDeviceTree(confDeviceStore) + , confDeviceScroller() + , watcher(*this) + , useExt(_("_Use pressure-sensitive tablet (requires restart)"), true) + , save(_("_Save"), true) + , detailsBox(false, 4) + , titleFrame(false, 4) + , titleLabel("") + , axisFrame(_("Axes")) + , keysFrame(_("Keys")) + , modeLabel(_("Mode:")) + , modeBox(false, 4) { - - confDeviceScroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); confDeviceScroller.set_shadow_type(Gtk::SHADOW_IN); confDeviceScroller.add(confDeviceTree); @@ -938,35 +941,37 @@ InputDialogImpl::ConfPanel::ConfPanel() : } }*/ - //int expPos = confDeviceTree.append_column("", getCols().expander); + // int expPos = confDeviceTree.append_column("", getCols().expander); confDeviceTree.append_column("I", getCols().thumbnail); confDeviceTree.append_column("Bar", getCols().description); - //confDeviceTree.get_column(0)->set_fixed_width(100); - //confDeviceTree.get_column(1)->set_expand(); + // confDeviceTree.get_column(0)->set_fixed_width(100); + // confDeviceTree.get_column(1)->set_expand(); -/* { - Gtk::TreeViewColumn *col = new Gtk::TreeViewColumn("X", *rendr); - if (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), confDeviceStore)); - rendr->property_editable() = true; - } - }*/ + /* { + Gtk::TreeViewColumn *col = new Gtk::TreeViewColumn("X", *rendr); + if (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), confDeviceStore)); + rendr->property_editable() = true; + } + }*/ - //confDeviceTree.set_enable_tree_lines(); + // 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) ); + // confDeviceTree.set_expander_column( *confDeviceTree.get_column(expPos - 1) ); - confDeviceTree.get_selection()->signal_changed().connect(sigc::mem_fun(*this, &InputDialogImpl::ConfPanel::onTreeSelect)); + confDeviceTree.get_selection()->signal_changed().connect( + sigc::mem_fun(*this, &InputDialogImpl::ConfPanel::onTreeSelect)); - setupTree( confDeviceStore, confDeviceIter ); + setupTree(confDeviceStore, confDeviceIter); - Inkscape::DeviceManager::getManager().signalLinkChanged().connect(sigc::bind(sigc::ptr_fun(&InputDialogImpl::updateDeviceLinks), confDeviceIter, &confDeviceTree)); + Inkscape::DeviceManager::getManager().signalLinkChanged().connect( + sigc::bind(sigc::ptr_fun(&InputDialogImpl::updateDeviceLinks), confDeviceIter, &confDeviceTree)); confDeviceTree.expand_all(); @@ -974,18 +979,19 @@ InputDialogImpl::ConfPanel::ConfPanel() : useExt.signal_toggled().connect(sigc::mem_fun(*this, &InputDialogImpl::ConfPanel::useExtToggled)); auto buttonBox = Gtk::manage(new Gtk::ButtonBox); - buttonBox->set_layout (Gtk::BUTTONBOX_END); - //Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_END, Gtk::ALIGN_START, 0, 0); + 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); + // 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.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); @@ -1013,8 +1019,8 @@ InputDialogImpl::ConfPanel::ConfPanel() : 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); + // 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) ); @@ -1048,11 +1054,9 @@ InputDialogImpl::ConfPanel::ConfPanel() : // Select the first device confDeviceTree.get_selection()->select(confDeviceStore->get_iter("0")); - } -InputDialogImpl::ConfPanel::~ConfPanel() -= default; +InputDialogImpl::ConfPanel::~ConfPanel() = default; void InputDialogImpl::ConfPanel::setModeCellString(Gtk::CellRenderer *rndr, Gtk::TreeIter const &iter) { @@ -1070,18 +1074,17 @@ void InputDialogImpl::ConfPanel::setModeCellString(Gtk::CellRenderer *rndr, Gtk: } } -void InputDialogImpl::ConfPanel::commitCellModeChange(Glib::ustring const &path, Glib::ustring const &newText, Glib::RefPtr<Gtk::TreeStore> store) +void InputDialogImpl::ConfPanel::commitCellModeChange(Glib::ustring const &path, Glib::ustring const &newText, + Glib::RefPtr<Gtk::TreeStore> store) { Gtk::TreeIter iter = store->get_iter(path); 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 ); + Inkscape::DeviceManager::getManager().setMode(dev->getId(), mode); } } - - } void InputDialogImpl::ConfPanel::setCellStateToggle(Gtk::CellRenderer *rndr, Gtk::TreeIter const &iter) @@ -1108,9 +1111,9 @@ void InputDialogImpl::ConfPanel::commitCellStateChange(Glib::ustring const &path if (dev) { Gdk::InputMode mode = (*iter)[getCols().mode]; if (mode == Gdk::MODE_DISABLED) { - Inkscape::DeviceManager::getManager().setMode( dev->getId(), Gdk::MODE_SCREEN ); + Inkscape::DeviceManager::getManager().setMode(dev->getId(), Gdk::MODE_SCREEN); } else { - Inkscape::DeviceManager::getManager().setMode( dev->getId(), Gdk::MODE_DISABLED ); + Inkscape::DeviceManager::getManager().setMode(dev->getId(), Gdk::MODE_DISABLED); } } } @@ -1155,9 +1158,9 @@ void InputDialogImpl::ConfPanel::useExtToggled() } } -InputDialogImpl::ConfPanel::Blink::Blink(ConfPanel &parent) : - Preferences::Observer("/options/useextinput/value"), - parent(parent) +InputDialogImpl::ConfPanel::Blink::Blink(ConfPanel &parent) + : Preferences::Observer("/options/useextinput/value") + , parent(parent) { Preferences::get()->addObserver(*this); } @@ -1174,18 +1177,16 @@ void InputDialogImpl::ConfPanel::Blink::notify(Preferences::Entry const &new_val 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; + // g_message("OUCH!!!! for %p hits %s", &device, device->getId().c_str()); + std::vector<Glib::RefPtr<Gtk::TreeStore>> stores; stores.push_back(deviceStore); stores.push_back(cfgPanel.confDeviceStore); - for (auto & store : stores) { + for (auto &store : stores) { Gtk::TreeModel::iterator deviceIter; - store->foreach_iter( sigc::bind<Glib::ustring, Gtk::TreeModel::iterator*>( - sigc::ptr_fun(&InputDialogImpl::findDevice), - device->getId(), - &deviceIter) ); - if ( deviceIter ) { + store->foreach_iter(sigc::bind<Glib::ustring, Gtk::TreeModel::iterator *>( + sigc::ptr_fun(&InputDialogImpl::findDevice), device->getId(), &deviceIter)); + if (deviceIter) { Gdk::InputMode mode = device->getMode(); Gtk::TreeModel::Row row = *deviceIter; if (row[getCols().mode] != mode) { @@ -1199,17 +1200,17 @@ void InputDialogImpl::updateDeviceAxes(Glib::RefPtr<InputDevice const> device) { gint live = device->getLiveAxes(); - std::map<guint, std::pair<guint, gdouble> > existing = axesMap[device->getId()]; + std::map<guint, std::pair<guint, gdouble>> existing = axesMap[device->getId()]; gint mask = 0x1; - for ( gint num = 0; num < 32; num++, mask <<= 1) { - if ( (mask & live) != 0 ) { - if ( (existing.find(num) == existing.end()) || (existing[num].first < 2) ) { + for (gint num = 0; num < 32; num++, mask <<= 1) { + if ((mask & live) != 0) { + if ((existing.find(num) == existing.end()) || (existing[num].first < 2)) { axesMap[device->getId()][num].first = 2; axesMap[device->getId()][num].second = 0.0; } } } - updateTestAxes( device->getId(), nullptr ); + updateTestAxes(device->getId(), nullptr); } void InputDialogImpl::updateDeviceButtons(Glib::RefPtr<InputDevice const> device) @@ -1217,9 +1218,9 @@ void InputDialogImpl::updateDeviceButtons(Glib::RefPtr<InputDevice const> device gint live = device->getLiveButtons(); std::set<guint> existing = buttonMap[device->getId()]; gint mask = 0x1; - for ( gint num = 0; num < 32; num++, mask <<= 1) { - if ( (mask & live) != 0 ) { - if ( existing.find(num) == existing.end() ) { + for (gint num = 0; num < 32; num++, mask <<= 1) { + if ((mask & live) != 0) { + if (existing.find(num) == existing.end()) { buttonMap[device->getId()].insert(num); } } @@ -1227,15 +1228,13 @@ void InputDialogImpl::updateDeviceButtons(Glib::RefPtr<InputDevice const> device updateTestButtons(device->getId(), -1); } - -bool InputDialogImpl::findDevice(const Gtk::TreeModel::iterator& iter, - Glib::ustring id, - Gtk::TreeModel::iterator* result) +bool InputDialogImpl::findDevice(const Gtk::TreeModel::iterator &iter, Glib::ustring id, + Gtk::TreeModel::iterator *result) { bool stop = false; Glib::RefPtr<InputDevice const> dev = (*iter)[getCols().device]; - if ( dev && (dev->getId() == id) ) { - if ( result ) { + if (dev && (dev->getId() == id)) { + if (result) { *result = iter; } stop = true; @@ -1243,14 +1242,13 @@ bool InputDialogImpl::findDevice(const Gtk::TreeModel::iterator& iter, return stop; } -bool InputDialogImpl::findDeviceByLink(const Gtk::TreeModel::iterator& iter, - Glib::ustring link, - Gtk::TreeModel::iterator* result) +bool InputDialogImpl::findDeviceByLink(const Gtk::TreeModel::iterator &iter, Glib::ustring link, + Gtk::TreeModel::iterator *result) { bool stop = false; Glib::RefPtr<InputDevice const> dev = (*iter)[getCols().device]; - if ( dev && (dev->getLink() == link) ) { - if ( result ) { + if (dev && (dev->getLink() == link)) { + if (result) { *result = iter; } stop = true; @@ -1258,24 +1256,24 @@ bool InputDialogImpl::findDeviceByLink(const Gtk::TreeModel::iterator& iter, return stop; } -void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, Gtk::TreeIter tabletIter, Gtk::TreeView *tree) +void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, Gtk::TreeIter tabletIter, + Gtk::TreeView *tree) { 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()); + // g_message("Links!!!! for %p hits [%s] with link of [%s]", &device, device->getId().c_str(), + // device->getLink().c_str()); Gtk::TreeModel::iterator deviceIter; - deviceStore->foreach_iter( sigc::bind<Glib::ustring, Gtk::TreeModel::iterator*>( - sigc::ptr_fun(&InputDialogImpl::findDevice), - device->getId(), - &deviceIter) ); + deviceStore->foreach_iter(sigc::bind<Glib::ustring, Gtk::TreeModel::iterator *>( + sigc::ptr_fun(&InputDialogImpl::findDevice), device->getId(), &deviceIter)); - if ( deviceIter ) { + if (deviceIter) { // Found the device concerned. Can proceed. - if ( device->getLink().empty() ) { + if (device->getLink().empty()) { // is now unlinked -// g_message("Item %s is unlinked", device->getId().c_str()); - if ( deviceIter->parent() != tabletIter ) { + // g_message("Item %s is unlinked", device->getId().c_str()); + if (deviceIter->parent() != tabletIter) { // Not the child of the tablet. move on up Glib::RefPtr<InputDevice const> dev = (*deviceIter)[getCols().device]; @@ -1290,13 +1288,13 @@ void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, Gtk::TreeModel::iterator oldParent = deviceIter->parent(); deviceStore->erase(deviceIter); - if ( oldParent->children().empty() ) { + if (oldParent->children().empty()) { deviceStore->erase(oldParent); } } } else { // is linking - if ( deviceIter->parent() == tabletIter ) { + if (deviceIter->parent() == tabletIter) { // Simple case. Not already linked Gtk::TreeIter newGroup = deviceStore->append(tabletIter->children()); @@ -1313,13 +1311,10 @@ void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, deviceRow[getCols().device] = dev; deviceRow[getCols().mode] = dev->getMode(); - Gtk::TreeModel::iterator linkIter; - deviceStore->foreach_iter( sigc::bind<Glib::ustring, Gtk::TreeModel::iterator*>( - sigc::ptr_fun(&InputDialogImpl::findDeviceByLink), - device->getId(), - &linkIter) ); - if ( linkIter ) { + deviceStore->foreach_iter(sigc::bind<Glib::ustring, Gtk::TreeModel::iterator *>( + sigc::ptr_fun(&InputDialogImpl::findDeviceByLink), device->getId(), &linkIter)); + if (linkIter) { dev = (*linkIter)[getCols().device]; descr = (*linkIter)[getCols().description]; thumb = (*linkIter)[getCols().thumbnail]; @@ -1331,14 +1326,14 @@ void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, deviceRow[getCols().mode] = dev->getMode(); Gtk::TreeModel::iterator oldParent = linkIter->parent(); deviceStore->erase(linkIter); - if ( oldParent->children().empty() ) { + if (oldParent->children().empty()) { deviceStore->erase(oldParent); } } Gtk::TreeModel::iterator oldParent = deviceIter->parent(); deviceStore->erase(deviceIter); - if ( oldParent->children().empty() ) { + if (oldParent->children().empty()) { deviceStore->erase(oldParent); } tree->expand_row(Gtk::TreePath(newGroup), true); @@ -1347,22 +1342,24 @@ void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, } } -void InputDialogImpl::linkComboChanged() { +void InputDialogImpl::linkComboChanged() +{ 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 ) { - if ( linkCombo.get_active_row_number() == 0 ) { + if (dev) { + if (linkCombo.get_active_row_number() == 0) { // It is the "None" entry DeviceManager::getManager().setLinkedTo(dev->getId(), ""); } else { Glib::ustring linkName = linkCombo.get_active_text(); - 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 ( linkName == (*it)->getName() ) { + 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 (linkName == (*it)->getName()) { DeviceManager::getManager().setLinkedTo(dev->getId(), (*it)->getId()); break; } @@ -1372,7 +1369,8 @@ void InputDialogImpl::linkComboChanged() { } } -void InputDialogImpl::resyncToSelection() { +void InputDialogImpl::resyncToSelection() +{ bool clear = true; Glib::RefPtr<Gtk::TreeSelection> treeSel = deviceTree.get_selection(); Gtk::TreeModel::iterator iter = treeSel->get_selected(); @@ -1381,20 +1379,21 @@ void InputDialogImpl::resyncToSelection() { Glib::ustring val = row[getCols().description]; Glib::RefPtr<InputDevice const> dev = row[getCols().device]; - if ( dev ) { + if (dev) { axisTable.set_sensitive(true); linkConnection.block(); linkCombo.remove_all(); linkCombo.append(_("None")); linkCombo.set_active(0); - if ( dev->getSource() != Gdk::SOURCE_MOUSE ) { + 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) ) { + 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)) { linkCombo.append((*it)->getName().c_str()); - if ( (linked.length() > 0) && (linked == (*it)->getId()) ) { + if ((linked.length() > 0) && (linked == (*it)->getId())) { linkCombo.set_active_text((*it)->getName().c_str()); } } @@ -1408,10 +1407,8 @@ void InputDialogImpl::resyncToSelection() { clear = false; devName.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); - - + setupValueAndCombo(dev->getNumAxes(), dev->getNumAxes(), devAxesCount, axesCombo); + setupValueAndCombo(dev->getNumKeys(), dev->getNumKeys(), devKeyCount, buttonCombo); } } @@ -1433,17 +1430,15 @@ void InputDialogImpl::ConfPanel::setAxis(gint count) 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] = C_("Input device axe", "None"); - } + 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] = C_("Input device axe", "None"); + } } - } void InputDialogImpl::ConfPanel::setKeys(gint count) { @@ -1455,35 +1450,33 @@ void InputDialogImpl::ConfPanel::setKeys(gint count) for (gint i = 0; i < count; i++) { Gtk::TreeModel::Row row = *(keysStore->append()); - row[keysColumns.name] = Glib::ustring::format(i+1); + 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 ) +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); combo.remove_all(); - for ( gint i = 1; i <= reported; ++i ) { + for (gint i = 1; i <= reported; ++i) { tmp = g_strdup_printf("%d", i); combo.append(tmp); g_free(tmp); } - if ( (1 <= actual) && (actual <= reported) ) { + if ((1 <= actual) && (actual <= reported)) { combo.set_active(actual - 1); } } -void InputDialogImpl::updateTestButtons( Glib::ustring const& key, gint hotButton ) +void InputDialogImpl::updateTestButtons(Glib::ustring const &key, gint hotButton) { - for ( gint i = 0; i < static_cast<gint>(G_N_ELEMENTS(testButtons)); i++ ) { - if ( buttonMap[key].find(i) != buttonMap[key].end() ) { - if ( i == hotButton ) { + for (gint i = 0; i < static_cast<gint>(G_N_ELEMENTS(testButtons)); i++) { + if (buttonMap[key].find(i) != buttonMap[key].end()) { + if (i == hotButton) { testButtons[i].set(getPix(PIX_BUTTONS_ON)); } else { testButtons[i].set(getPix(PIX_BUTTONS_OFF)); @@ -1494,9 +1487,9 @@ void InputDialogImpl::updateTestButtons( Glib::ustring const& key, gint hotButto } } -void InputDialogImpl::updateTestAxes( Glib::ustring const& key, GdkDevice* dev ) +void InputDialogImpl::updateTestAxes(Glib::ustring const &key, GdkDevice *dev) { - //static gdouble epsilon = 0.0001; + // static gdouble epsilon = 0.0001; { Glib::RefPtr<Gtk::TreeSelection> treeSel = deviceTree.get_selection(); Gtk::TreeModel::iterator iter = treeSel->get_selected(); @@ -1504,36 +1497,38 @@ void InputDialogImpl::updateTestAxes( Glib::ustring const& key, GdkDevice* dev ) Gtk::TreeModel::Row row = *iter; Glib::ustring val = row[getCols().description]; Glib::RefPtr<InputDevice const> idev = row[getCols().device]; - if ( !idev || (idev->getId() != key) ) { + if (!idev || (idev->getId() != key)) { dev = nullptr; } } } - 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 ) { + 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) { case 0: case 1: testAxes[i].set(getPix(PIX_AXIS_NONE)); - if ( dev && (i < static_cast<gint>(G_N_ELEMENTS(axesValues)) ) ) { + if (dev && (i < static_cast<gint>(G_N_ELEMENTS(axesValues)))) { axesValues[i].set_sensitive(false); } break; case 2: testAxes[i].set(getPix(PIX_AXIS_OFF)); axesValues[i].set_sensitive(true); - if ( dev && (i < static_cast<gint>(G_N_ELEMENTS(axesValues)) ) ) { - // 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) ); - // } - - gchar* str = g_strdup_printf("%f", axesMap[key][i].second); + if (dev && (i < static_cast<gint>(G_N_ELEMENTS(axesValues)))) { + // 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) ); + // } + + gchar *str = g_strdup_printf("%f", axesMap[key][i].second); axesValues[i].set_text(str); g_free(str); } @@ -1541,18 +1536,18 @@ void InputDialogImpl::updateTestAxes( Glib::ustring const& key, GdkDevice* dev ) case 3: testAxes[i].set(getPix(PIX_AXIS_ON)); axesValues[i].set_sensitive(true); - if ( dev && (i < static_cast<gint>(G_N_ELEMENTS(axesValues)) ) ) { - - // 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) ); - // } - - gchar* str = g_strdup_printf("%f", axesMap[key][i].second); + if (dev && (i < static_cast<gint>(G_N_ELEMENTS(axesValues)))) { + // 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) ); + // } + + gchar *str = g_strdup_printf("%f", axesMap[key][i].second); axesValues[i].set_text(str); g_free(str); } @@ -1562,8 +1557,8 @@ void InputDialogImpl::updateTestAxes( Glib::ustring const& key, GdkDevice* dev ) testAxes[i].set(getPix(PIX_AXIS_NONE)); } } - if ( !dev ) { - for (auto & axesValue : axesValues) { + if (!dev) { + for (auto &axesValue : axesValues) { axesValue.set_fraction(0.0); axesValue.set_text(""); axesValue.set_sensitive(false); @@ -1571,46 +1566,39 @@ void InputDialogImpl::updateTestAxes( Glib::ustring const& key, GdkDevice* dev ) } } -void InputDialogImpl::mapAxesValues( Glib::ustring const& key, gdouble const * axes, GdkDevice* dev ) +void InputDialogImpl::mapAxesValues(Glib::ustring const &key, gdouble const *axes, GdkDevice *dev) { auto device = Glib::wrap(dev); auto numAxes = device->get_n_axes(); static gdouble epsilon = 0.0001; - if ( (numAxes > 0) && axes) { - for ( guint axisNum = 0; axisNum < numAxes; axisNum++ ) { + if ((numAxes > 0) && axes) { + for (guint axisNum = 0; axisNum < numAxes; axisNum++) { // 0 == new, 1 == set value, 2 == changed value, 3 == active gdouble diff = axesMap[key][axisNum].second - axes[axisNum]; - switch(axesMap[key][axisNum].first) { - case 0: - { + switch (axesMap[key][axisNum].first) { + case 0: { axesMap[key][axisNum].first = 1; axesMap[key][axisNum].second = axes[axisNum]; - } - break; - case 1: - { - if ( (diff > epsilon) || (diff < -epsilon) ) { -// g_message("Axis %d changed on %s]", axisNum, key.c_str()); + } break; + case 1: { + if ((diff > epsilon) || (diff < -epsilon)) { + // g_message("Axis %d changed on %s]", axisNum, key.c_str()); axesMap[key][axisNum].first = 3; axesMap[key][axisNum].second = axes[axisNum]; updateTestAxes(key, dev); DeviceManager::getManager().addAxis(key, axisNum); } - } - break; - case 2: - { - if ( (diff > epsilon) || (diff < -epsilon) ) { + } break; + case 2: { + if ((diff > epsilon) || (diff < -epsilon)) { axesMap[key][axisNum].first = 3; axesMap[key][axisNum].second = axes[axisNum]; updateTestAxes(key, dev); } - } - break; - case 3: - { - if ( (diff > epsilon) || (diff < -epsilon) ) { + } break; + case 3: { + if ((diff > epsilon) || (diff < -epsilon)) { axesMap[key][axisNum].second = axes[axisNum]; } else { axesMap[key][axisNum].first = 2; @@ -1623,7 +1611,7 @@ void InputDialogImpl::mapAxesValues( Glib::ustring const& key, gdouble const * a // std::map<Glib::ustring, std::map<guint, std::pair<guint, gdouble> > > axesMap; } -Glib::ustring InputDialogImpl::getKeyFor( GdkDevice* device ) +Glib::ustring InputDialogImpl::getKeyFor(GdkDevice *device) { Glib::ustring key; auto devicemm = Glib::wrap(device); @@ -1631,7 +1619,7 @@ Glib::ustring InputDialogImpl::getKeyFor( GdkDevice* device ) auto source = devicemm->get_source(); const auto name = devicemm->get_name(); - switch ( source ) { + switch (source) { case Gdk::SOURCE_MOUSE: key = "M:"; break; @@ -1652,7 +1640,7 @@ Glib::ustring InputDialogImpl::getKeyFor( GdkDevice* device ) return key; } -bool InputDialogImpl::eventSnoop(GdkEvent* event) +bool InputDialogImpl::eventSnoop(GdkEvent *event) { int modmod = 0; @@ -1661,22 +1649,20 @@ bool InputDialogImpl::eventSnoop(GdkEvent* event) Glib::ustring key; gint hotButton = -1; - switch ( event->type ) { + switch (event->type) { case GDK_KEY_PRESS: - case GDK_KEY_RELEASE: - { - auto keyEvt = reinterpret_cast<GdkEventKey*>(event); + case GDK_KEY_RELEASE: { + auto keyEvt = reinterpret_cast<GdkEventKey *>(event); auto name = Gtk::AccelGroup::name(keyEvt->keyval, static_cast<Gdk::ModifierType>(keyEvt->state)); keyVal.set_label(name); -// g_message("%d KEY state:0x%08x 0x%04x [%s]", keyEvt->type, keyEvt->state, keyEvt->keyval, name); - } - break; + // g_message("%d KEY state:0x%08x 0x%04x [%s]", keyEvt->type, keyEvt->state, keyEvt->keyval, + // name); + } break; case GDK_BUTTON_PRESS: modmod = 1; // fallthrough - case GDK_BUTTON_RELEASE: - { - auto btnEvt = reinterpret_cast<GdkEventButton*>(event); + case GDK_BUTTON_RELEASE: { + auto btnEvt = reinterpret_cast<GdkEventButton *>(event); auto device = Glib::wrap(btnEvt->device); if (device) { key = getKeyFor(btnEvt->device); @@ -1684,8 +1670,8 @@ bool InputDialogImpl::eventSnoop(GdkEvent* event) devName = device->get_name(); mapAxesValues(key, 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); + 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); DeviceManager::getManager().addButton(key, btnEvt->button); } @@ -1694,18 +1680,16 @@ bool InputDialogImpl::eventSnoop(GdkEvent* event) } auto name = Gtk::AccelGroup::name(0, static_cast<Gdk::ModifierType>(btnEvt->state)); keyVal.set_label(name); -// g_message("%d BTN state:0x%08x %c %4d [%s] dev:%p [%s] ", -// btnEvt->type, btnEvt->state, -// (modmod ? '+':'-'), -// btnEvt->button, name, btnEvt->device, -// (btnEvt->device ? btnEvt->device->name : "null") - -// ); - } - break; - case GDK_MOTION_NOTIFY: - { - GdkEventMotion* btnMtn = reinterpret_cast<GdkEventMotion*>(event); + // g_message("%d BTN state:0x%08x %c %4d [%s] dev:%p [%s] ", + // btnEvt->type, btnEvt->state, + // (modmod ? '+':'-'), + // btnEvt->button, name, btnEvt->device, + // (btnEvt->device ? btnEvt->device->name : "null") + + // ); + } break; + case GDK_MOTION_NOTIFY: { + GdkEventMotion *btnMtn = reinterpret_cast<GdkEventMotion *>(event); auto device = Glib::wrap(btnMtn->device); if (device) { key = getKeyFor(btnMtn->device); @@ -1715,46 +1699,50 @@ bool InputDialogImpl::eventSnoop(GdkEvent* event) } auto name = Gtk::AccelGroup::name(0, static_cast<Gdk::ModifierType>(btnMtn->state)); keyVal.set_label(name); -// g_message("%d MOV state:0x%08x [%s] dev:%p [%s] %3.2f %3.2f %3.2f %3.2f %3.2f %3.2f", btnMtn->type, btnMtn->state, -// name, btnMtn->device, -// (btnMtn->device ? btnMtn->device->name : "null"), -// ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 0)) ? btnMtn->axes[0]:0), -// ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 1)) ? btnMtn->axes[1]:0), -// ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 2)) ? btnMtn->axes[2]:0), -// ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 3)) ? btnMtn->axes[3]:0), -// ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 4)) ? btnMtn->axes[4]:0), -// ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 5)) ? btnMtn->axes[5]:0) -// ); - } - break; - default: - ;// nothing + // g_message("%d MOV state:0x%08x [%s] dev:%p [%s] %3.2f %3.2f %3.2f %3.2f %3.2f + // %3.2f", btnMtn->type, btnMtn->state, + // name, btnMtn->device, + // (btnMtn->device ? btnMtn->device->name : "null"), + // ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 0)) ? + // btnMtn->axes[0]:0), + // ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 1)) ? + // btnMtn->axes[1]:0), + // ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 2)) ? + // btnMtn->axes[2]:0), + // ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 3)) ? + // btnMtn->axes[3]:0), + // ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 4)) ? + // btnMtn->axes[4]:0), + // ((btnMtn->device && btnMtn->axes && (btnMtn->device->num_axes > 5)) ? + // btnMtn->axes[5]:0) + // ); + } break; + default:; // nothing } - - if ( (lastSourceSeen != source) || (lastDevnameSeen != devName) ) { + if ((lastSourceSeen != source) || (lastDevnameSeen != devName)) { switch (source) { case Gdk::SOURCE_MOUSE: { testThumb.set(getPix(PIX_CORE)); break; } case Gdk::SOURCE_CURSOR: { -// g_message("flip to cursor"); + // g_message("flip to cursor"); testThumb.set(getPix(PIX_MOUSE)); break; } case Gdk::SOURCE_PEN: { if (devName == _("pad")) { -// g_message("flip to pad"); + // g_message("flip to pad"); testThumb.set(getPix(PIX_SIDEBUTTONS)); } else { -// g_message("flip to pen"); + // g_message("flip to pen"); testThumb.set(getPix(PIX_TIP)); } break; } case Gdk::SOURCE_ERASER: { -// g_message("flip to eraser"); + // g_message("flip to eraser"); testThumb.set(getPix(PIX_ERASER)); break; } @@ -1764,8 +1752,8 @@ bool InputDialogImpl::eventSnoop(GdkEvent* event) case Gdk::SOURCE_TOUCHPAD: case Gdk::SOURCE_TRACKPOINT: case Gdk::SOURCE_TABLET_PAD: - g_warning("InputDialogImpl::eventSnoop : unhandled GDK_SOURCE type!"); - break; + g_warning("InputDialogImpl::eventSnoop : unhandled GDK_SOURCE type!"); + break; } updateTestButtons(key, hotButton); @@ -1776,11 +1764,9 @@ bool InputDialogImpl::eventSnoop(GdkEvent* event) return false; } - -} // end namespace Inkscape +} // namespace Dialog } // end namespace UI -} // end namespace Dialog - +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/input.h b/src/ui/dialog/input.h index a756cc56091ff5c93d51799327912ff2bc779e0d..335b31ac4cf69e458fa1d2db2c4a2e1b04fd07f7 100644 --- a/src/ui/dialog/input.h +++ b/src/ui/dialog/input.h @@ -12,9 +12,8 @@ #ifndef INKSCAPE_UI_DIALOG_INPUT_H #define INKSCAPE_UI_DIALOG_INPUT_H - -#include "verbs.h" #include "ui/widget/panel.h" +#include "verbs.h" namespace Inkscape { namespace UI { @@ -25,12 +24,14 @@ class InputDialog : public UI::Widget::Panel public: static InputDialog &getInstance(); - InputDialog() : UI::Widget::Panel("/dialogs/inputdevices", SP_VERB_DIALOG_INPUT) {} + InputDialog() + : UI::Widget::Panel("/dialogs/inputdevices", SP_VERB_DIALOG_INPUT) + {} ~InputDialog() override = default; }; } // namespace Dialog -} // namesapce UI +} // namespace UI } // namespace Inkscape #endif // INKSCAPE_UI_DIALOG_INPUT_H diff --git a/src/ui/dialog/knot-properties.cpp b/src/ui/dialog/knot-properties.cpp index 708c90ea769d066b3f049746953f1b087ab061a2..bed1344fdc9d357a50ff07c1452de45e762f2d54 100644 --- a/src/ui/dialog/knot-properties.cpp +++ b/src/ui/dialog/knot-properties.cpp @@ -19,14 +19,14 @@ #include <boost/lexical_cast.hpp> #include <glibmm/i18n.h> #include <glibmm/main.h> -#include "inkscape.h" -#include "util/units.h" + #include "desktop.h" -#include "document.h" #include "document-undo.h" +#include "document.h" +#include "inkscape.h" #include "layer-manager.h" - #include "selection-chemistry.h" +#include "util/units.h" //#include "event-context.h" @@ -35,10 +35,10 @@ namespace UI { namespace Dialogs { KnotPropertiesDialog::KnotPropertiesDialog() - : _desktop(nullptr), - _knotpoint(nullptr), - _position_visible(false), - _close_button(_("_Close"), true) + : _desktop(nullptr) + , _knotpoint(nullptr) + , _position_visible(false) + , _close_button(_("_Close"), true) { Gtk::Box *mainVBox = get_content_area(); @@ -48,7 +48,7 @@ KnotPropertiesDialog::KnotPropertiesDialog() // Layer name widgets _knot_x_entry.set_activates_default(true); _knot_x_entry.set_digits(4); - _knot_x_entry.set_increments(1,1); + _knot_x_entry.set_increments(1, 1); _knot_x_entry.set_range(-G_MAXDOUBLE, G_MAXDOUBLE); _knot_x_entry.set_hexpand(); _knot_x_label.set_label(_("Position X:")); @@ -57,7 +57,7 @@ KnotPropertiesDialog::KnotPropertiesDialog() _knot_y_entry.set_activates_default(true); _knot_y_entry.set_digits(4); - _knot_y_entry.set_increments(1,1); + _knot_y_entry.set_increments(1, 1); _knot_y_entry.set_range(-G_MAXDOUBLE, G_MAXDOUBLE); _knot_y_entry.set_hexpand(); _knot_y_label.set_label(_("Position Y:")); @@ -78,17 +78,11 @@ KnotPropertiesDialog::KnotPropertiesDialog() _apply_button.set_use_underline(true); _apply_button.set_can_default(); - _close_button.signal_clicked() - .connect(sigc::mem_fun(*this, &KnotPropertiesDialog::_close)); - _apply_button.signal_clicked() - .connect(sigc::mem_fun(*this, &KnotPropertiesDialog::_apply)); + _close_button.signal_clicked().connect(sigc::mem_fun(*this, &KnotPropertiesDialog::_close)); + _apply_button.signal_clicked().connect(sigc::mem_fun(*this, &KnotPropertiesDialog::_apply)); signal_delete_event().connect( - sigc::bind_return( - sigc::hide(sigc::mem_fun(*this, &KnotPropertiesDialog::_close)), - true - ) - ); + sigc::bind_return(sigc::hide(sigc::mem_fun(*this, &KnotPropertiesDialog::_close)), true)); add_action_widget(_close_button, Gtk::RESPONSE_CLOSE); add_action_widget(_apply_button, Gtk::RESPONSE_APPLY); @@ -99,8 +93,8 @@ KnotPropertiesDialog::KnotPropertiesDialog() set_focus(_knot_y_entry); } -KnotPropertiesDialog::~KnotPropertiesDialog() { - +KnotPropertiesDialog::~KnotPropertiesDialog() +{ _setDesktop(nullptr); } @@ -115,39 +109,32 @@ void KnotPropertiesDialog::showDialog(SPDesktop *desktop, const SPKnot *pt, Glib dialog->_apply_button.set_label(_("_Move")); dialog->set_modal(true); - desktop->setWindowTransient (dialog->gobj()); + desktop->setWindowTransient(dialog->gobj()); dialog->property_destroy_with_parent() = true; dialog->show(); dialog->present(); } -void -KnotPropertiesDialog::_apply() +void KnotPropertiesDialog::_apply() { - double d_x = Inkscape::Util::Quantity::convert(_knot_x_entry.get_value(), _unit_name, "px"); - double d_y = Inkscape::Util::Quantity::convert(_knot_y_entry.get_value(), _unit_name, "px"); + double d_x = Inkscape::Util::Quantity::convert(_knot_x_entry.get_value(), _unit_name, "px"); + double d_y = Inkscape::Util::Quantity::convert(_knot_y_entry.get_value(), _unit_name, "px"); _knotpoint->moveto(Geom::Point(d_x, d_y)); _knotpoint->moved_signal.emit(_knotpoint, _knotpoint->position(), 0); _close(); } -void -KnotPropertiesDialog::_close() +void KnotPropertiesDialog::_close() { _setDesktop(nullptr); destroy_(); Glib::signal_idle().connect( - sigc::bind_return( - sigc::bind(sigc::ptr_fun<void*, void>(&::operator delete), this), - false - ) - ); + sigc::bind_return(sigc::bind(sigc::ptr_fun<void *, void>(&::operator delete), this), false)); } bool KnotPropertiesDialog::_handleKeyEvent(GdkEventKey * /*event*/) { - /*switch (get_latin_keyval(event)) { case GDK_KEY_Return: case GDK_KEY_KP_Enter: { @@ -159,9 +146,9 @@ bool KnotPropertiesDialog::_handleKeyEvent(GdkEventKey * /*event*/) return false; } -void KnotPropertiesDialog::_handleButtonEvent(GdkEventButton* event) +void KnotPropertiesDialog::_handleButtonEvent(GdkEventButton *event) { - if ( (event->type == GDK_2BUTTON_PRESS) && (event->button == 1) ) { + if ((event->type == GDK_2BUTTON_PRESS) && (event->button == 1)) { _apply(); } } @@ -169,31 +156,31 @@ void KnotPropertiesDialog::_handleButtonEvent(GdkEventButton* event) void KnotPropertiesDialog::_setKnotPoint(Geom::Point knotpoint, Glib::ustring const unit_name) { _unit_name = unit_name; - _knot_x_entry.set_value( Inkscape::Util::Quantity::convert(knotpoint.x(), "px", _unit_name)); - _knot_y_entry.set_value( Inkscape::Util::Quantity::convert(knotpoint.y(), "px", _unit_name)); + _knot_x_entry.set_value(Inkscape::Util::Quantity::convert(knotpoint.x(), "px", _unit_name)); + _knot_y_entry.set_value(Inkscape::Util::Quantity::convert(knotpoint.y(), "px", _unit_name)); _knot_x_label.set_label(g_strdup_printf(_("Position X (%s):"), _unit_name.c_str())); _knot_y_label.set_label(g_strdup_printf(_("Position Y (%s):"), _unit_name.c_str())); } void KnotPropertiesDialog::_setPt(const SPKnot *pt) { - _knotpoint = const_cast<SPKnot *>(pt); + _knotpoint = const_cast<SPKnot *>(pt); } -void KnotPropertiesDialog::_setDesktop(SPDesktop *desktop) { +void KnotPropertiesDialog::_setDesktop(SPDesktop *desktop) +{ if (desktop) { - Inkscape::GC::anchor (desktop); + Inkscape::GC::anchor(desktop); } if (_desktop) { - Inkscape::GC::release (_desktop); + Inkscape::GC::release(_desktop); } _desktop = desktop; } -} // namespace -} // namespace -} // namespace - +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/knot-properties.h b/src/ui/dialog/knot-properties.h index fb88fade52a02d73edb4e52f84dd148adeed07e4..6aead6a1abca8e8e3c8eac959b42e1ad18faab1c 100644 --- a/src/ui/dialog/knot-properties.h +++ b/src/ui/dialog/knot-properties.h @@ -13,11 +13,12 @@ #ifndef INKSCAPE_DIALOG_KNOT_PROPERTIES_H #define INKSCAPE_DIALOG_KNOT_PROPERTIES_H +#include <2geom/point.h> #include <gtkmm/dialog.h> #include <gtkmm/grid.h> #include <gtkmm/label.h> #include <gtkmm/spinbutton.h> -#include <2geom/point.h> + #include "knot.h" #include "ui/tools/measure-tool.h" @@ -27,35 +28,35 @@ namespace Inkscape { namespace UI { namespace Dialogs { - -class KnotPropertiesDialog : public Gtk::Dialog { - public: - KnotPropertiesDialog(); +class KnotPropertiesDialog : public Gtk::Dialog +{ +public: + KnotPropertiesDialog(); ~KnotPropertiesDialog() override; - Glib::ustring getName() const { return "LayerPropertiesDialog"; } + Glib::ustring getName() const { return "LayerPropertiesDialog"; } static void showDialog(SPDesktop *desktop, const SPKnot *pt, Glib::ustring const unit_name); protected: - SPDesktop *_desktop; - SPKnot *_knotpoint; + SPKnot *_knotpoint; - Gtk::Label _knot_x_label; - Gtk::SpinButton _knot_x_entry; - Gtk::Label _knot_y_label; - Gtk::SpinButton _knot_y_entry; - Gtk::Grid _layout_table; - bool _position_visible; + Gtk::Label _knot_x_label; + Gtk::SpinButton _knot_x_entry; + Gtk::Label _knot_y_label; + Gtk::SpinButton _knot_y_entry; + Gtk::Grid _layout_table; + bool _position_visible; - Gtk::Button _close_button; - Gtk::Button _apply_button; + Gtk::Button _close_button; + Gtk::Button _apply_button; Glib::ustring _unit_name; - sigc::connection _destroy_connection; + sigc::connection _destroy_connection; - static KnotPropertiesDialog &_instance() { + static KnotPropertiesDialog &_instance() + { static KnotPropertiesDialog instance; return instance; } @@ -70,20 +71,19 @@ protected: void _prepareLabelRenderer(Gtk::TreeModel::const_iterator const &row); bool _handleKeyEvent(GdkEventKey *event); - void _handleButtonEvent(GdkEventButton* event); + void _handleButtonEvent(GdkEventButton *event); friend class Inkscape::UI::Tools::MeasureTool; - + private: - KnotPropertiesDialog(KnotPropertiesDialog const &); // no copy + KnotPropertiesDialog(KnotPropertiesDialog const &); // no copy KnotPropertiesDialog &operator=(KnotPropertiesDialog const &); // no assign }; -} // namespace -} // namespace -} // namespace - +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape -#endif //INKSCAPE_DIALOG_LAYER_PROPERTIES_H +#endif // INKSCAPE_DIALOG_LAYER_PROPERTIES_H /* Local Variables: diff --git a/src/ui/dialog/layer-properties.cpp b/src/ui/dialog/layer-properties.cpp index 3a077d3891062081c1a83c52b58e06e0f166bff6..b337ff24e29e97927a4b196f1eadc8fff11e1092 100644 --- a/src/ui/dialog/layer-properties.cpp +++ b/src/ui/dialog/layer-properties.cpp @@ -15,32 +15,32 @@ */ #include "layer-properties.h" + #include <glibmm/i18n.h> #include <glibmm/main.h> -#include "inkscape.h" #include "desktop.h" -#include "document.h" #include "document-undo.h" +#include "document.h" +#include "inkscape.h" #include "layer-manager.h" #include "message-stack.h" - -#include "verbs.h" #include "selection-chemistry.h" #include "ui/icon-names.h" -#include "ui/widget/imagetoggler.h" #include "ui/tools/tool-base.h" +#include "ui/widget/imagetoggler.h" +#include "verbs.h" namespace Inkscape { namespace UI { namespace Dialogs { LayerPropertiesDialog::LayerPropertiesDialog() - : _strategy(nullptr), - _desktop(nullptr), - _layer(nullptr), - _position_visible(false), - _close_button(_("_Cancel"), true) + : _strategy(nullptr) + , _desktop(nullptr) + , _layer(nullptr) + , _position_visible(false) + , _close_button(_("_Cancel"), true) { auto mainVBox = get_content_area(); _layout_table.set_row_spacing(4); @@ -53,7 +53,7 @@ LayerPropertiesDialog::LayerPropertiesDialog() _layer_name_label.set_valign(Gtk::ALIGN_CENTER); _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(); @@ -67,17 +67,11 @@ LayerPropertiesDialog::LayerPropertiesDialog() _apply_button.set_use_underline(true); _apply_button.set_can_default(); - _close_button.signal_clicked() - .connect(sigc::mem_fun(*this, &LayerPropertiesDialog::_close)); - _apply_button.signal_clicked() - .connect(sigc::mem_fun(*this, &LayerPropertiesDialog::_apply)); + _close_button.signal_clicked().connect(sigc::mem_fun(*this, &LayerPropertiesDialog::_close)); + _apply_button.signal_clicked().connect(sigc::mem_fun(*this, &LayerPropertiesDialog::_apply)); signal_delete_event().connect( - sigc::bind_return( - sigc::hide(sigc::mem_fun(*this, &LayerPropertiesDialog::_close)), - true - ) - ); + sigc::bind_return(sigc::hide(sigc::mem_fun(*this, &LayerPropertiesDialog::_close)), true)); add_action_widget(_close_button, Gtk::RESPONSE_CLOSE); add_action_widget(_apply_button, Gtk::RESPONSE_APPLY); @@ -87,14 +81,13 @@ LayerPropertiesDialog::LayerPropertiesDialog() show_all_children(); } -LayerPropertiesDialog::~LayerPropertiesDialog() { - +LayerPropertiesDialog::~LayerPropertiesDialog() +{ _setDesktop(nullptr); _setLayer(nullptr); } -void LayerPropertiesDialog::_showDialog(LayerPropertiesDialog::Strategy &strategy, - SPDesktop *desktop, SPObject *layer) +void LayerPropertiesDialog::_showDialog(LayerPropertiesDialog::Strategy &strategy, SPDesktop *desktop, SPObject *layer) { LayerPropertiesDialog *dialog = new LayerPropertiesDialog(); @@ -105,15 +98,14 @@ void LayerPropertiesDialog::_showDialog(LayerPropertiesDialog::Strategy &strateg dialog->_strategy->setup(*dialog); dialog->set_modal(true); - desktop->setWindowTransient (dialog->gobj()); + desktop->setWindowTransient(dialog->gobj()); dialog->property_destroy_with_parent() = true; dialog->show(); dialog->present(); } -void -LayerPropertiesDialog::_apply() +void LayerPropertiesDialog::_apply() { g_assert(_strategy != nullptr); @@ -121,23 +113,18 @@ LayerPropertiesDialog::_apply() _close(); } -void -LayerPropertiesDialog::_close() +void LayerPropertiesDialog::_close() { _setLayer(nullptr); _setDesktop(nullptr); destroy_(); Glib::signal_idle().connect( - sigc::bind_return( - sigc::bind(sigc::ptr_fun<void*, void>(&::operator delete), this), - false - ) - ); + sigc::bind_return(sigc::bind(sigc::ptr_fun<void *, void>(&::operator delete), this), false)); } -void -LayerPropertiesDialog::_setup_position_controls() { - if ( nullptr == _layer || _desktop->currentRoot() == _layer ) { +void LayerPropertiesDialog::_setup_position_controls() +{ + if (nullptr == _layer || _desktop->currentRoot() == _layer) { // no layers yet, so option above/below/sublayer is useless return; } @@ -164,7 +151,7 @@ LayerPropertiesDialog::_setup_position_controls() { _layer_position_label.set_label(_("Position:")); _layer_position_label.set_halign(Gtk::ALIGN_START); _layer_position_label.set_valign(Gtk::ALIGN_CENTER); - + _layer_position_combo.set_halign(Gtk::ALIGN_FILL); _layer_position_combo.set_valign(Gtk::ALIGN_FILL); _layer_position_combo.set_hexpand(); @@ -175,29 +162,28 @@ LayerPropertiesDialog::_setup_position_controls() { show_all_children(); } -void -LayerPropertiesDialog::_setup_layers_controls() { - +void LayerPropertiesDialog::_setup_layers_controls() +{ ModelColumns *zoop = new ModelColumns(); _model = zoop; - _store = Gtk::TreeStore::create( *zoop ); - _tree.set_model( _store ); + _store = Gtk::TreeStore::create(*zoop); + _tree.set_model(_store); _tree.set_headers_visible(false); - Inkscape::UI::Widget::ImageToggler *eyeRenderer = Gtk::manage( new Inkscape::UI::Widget::ImageToggler( - INKSCAPE_ICON("object-visible"), INKSCAPE_ICON("object-hidden")) ); + Inkscape::UI::Widget::ImageToggler *eyeRenderer = Gtk::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 ); + Gtk::TreeViewColumn *col = _tree.get_column(visibleColNum); + if (col) { + col->add_attribute(eyeRenderer->property_active(), _model->_colVisible); } - Inkscape::UI::Widget::ImageToggler * renderer = Gtk::manage( new Inkscape::UI::Widget::ImageToggler( - INKSCAPE_ICON("object-locked"), INKSCAPE_ICON("object-unlocked")) ); + Inkscape::UI::Widget::ImageToggler *renderer = Gtk::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 ); + if (col) { + col->add_attribute(renderer->property_active(), _model->_colLocked); } Gtk::CellRendererText *_text_renderer = Gtk::manage(new Gtk::CellRendererText()); @@ -205,21 +191,21 @@ LayerPropertiesDialog::_setup_layers_controls() { 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) ); + _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.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(); + SPDocument *document = _desktop->doc(); + SPRoot *root = document->getRoot(); + if (root) { + SPObject *target = _desktop->currentLayer(); _store->clear(); - _addLayer( document, SP_OBJECT(root), nullptr, target, 0 ); + _addLayer(document, SP_OBJECT(root), nullptr, target, 0); } _layout_table.remove(_layer_name_entry); @@ -234,16 +220,17 @@ LayerPropertiesDialog::_setup_layers_controls() { show_all_children(); } -void LayerPropertiesDialog::_addLayer( SPDocument* doc, SPObject* layer, Gtk::TreeModel::Row* parentRow, SPObject* target, int level ) +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) ) { + if (_desktop && _desktop->layer_manager && layer && (level < _maxNestDepth)) { unsigned int counter = _desktop->layer_manager->childCount(layer); - for ( unsigned int i = 0; i < counter; i++ ) { + for (unsigned int i = 0; i < counter; i++) { SPObject *child = _desktop->layer_manager->nthChildOf(layer, i); - if ( child ) { + 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->id, child->label()); #endif // DUMP_LAYERS Gtk::TreeModel::iterator iter = parentRow ? _store->prepend(parentRow->children()) : _store->prepend(); @@ -253,8 +240,8 @@ void LayerPropertiesDialog::_addLayer( SPDocument* doc, SPObject* layer, Gtk::Tr 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) ); + if (target && child == target) { + _tree.expand_to_path(_store->get_path(iter)); Glib::RefPtr<Gtk::TreeSelection> select = _tree.get_selection(); select->select(iter); @@ -262,18 +249,18 @@ void LayerPropertiesDialog::_addLayer( SPDocument* doc, SPObject* layer, Gtk::Tr //_checkTreeSelection(); } - _addLayer( doc, child, &row, target, level + 1 ); + _addLayer(doc, child, &row, target, level + 1); } } } } -SPObject* LayerPropertiesDialog::_selectedLayer() +SPObject *LayerPropertiesDialog::_selectedLayer() { - SPObject* obj = nullptr; + SPObject *obj = nullptr; Gtk::TreeModel::iterator iter = _tree.get_selection()->get_selected(); - if ( iter ) { + if (iter) { Gtk::TreeModel::Row row = *iter; obj = row[_model->_colObject]; } @@ -283,59 +270,56 @@ SPObject* LayerPropertiesDialog::_selectedLayer() bool LayerPropertiesDialog::_handleKeyEvent(GdkEventKey *event) { - switch (Inkscape::UI::Tools::get_latin_keyval(event)) { case GDK_KEY_Return: case GDK_KEY_KP_Enter: { _strategy->perform(*this); _close(); return true; - } - break; + } break; } return false; } -void LayerPropertiesDialog::_handleButtonEvent(GdkEventButton* event) +void LayerPropertiesDialog::_handleButtonEvent(GdkEventButton *event) { - if ( (event->type == GDK_2BUTTON_PRESS) && (event->button == 1) ) { + if ((event->type == GDK_2BUTTON_PRESS) && (event->button == 1)) { _strategy->perform(*this); _close(); } } -/** Formats the label for a given layer row +/** Formats the label for a given layer row */ -void LayerPropertiesDialog::_prepareLabelRenderer( - Gtk::TreeModel::const_iterator const &row -) { - Glib::ustring name=(*row)[_dropdown_columns.name]; +void LayerPropertiesDialog::_prepareLabelRenderer(Gtk::TreeModel::const_iterator const &row) +{ + Glib::ustring name = (*row)[_dropdown_columns.name]; _label_renderer.property_markup() = name.c_str(); } -void LayerPropertiesDialog::Rename::setup(LayerPropertiesDialog &dialog) { - SPDesktop *desktop=dialog._desktop; +void LayerPropertiesDialog::Rename::setup(LayerPropertiesDialog &dialog) +{ + SPDesktop *desktop = dialog._desktop; dialog.set_title(_("Rename Layer")); gchar const *name = desktop->currentLayer()->label(); - dialog._layer_name_entry.set_text(( name ? name : _("Layer") )); + dialog._layer_name_entry.set_text((name ? name : _("Layer"))); dialog._apply_button.set_label(_("_Rename")); } -void LayerPropertiesDialog::Rename::perform(LayerPropertiesDialog &dialog) { - SPDesktop *desktop=dialog._desktop; +void LayerPropertiesDialog::Rename::perform(LayerPropertiesDialog &dialog) +{ + SPDesktop *desktop = dialog._desktop; Glib::ustring name(dialog._layer_name_entry.get_text()); if (name.empty()) return; - desktop->layer_manager->renameLayer( desktop->currentLayer(), - (gchar *)name.c_str(), - FALSE - ); + desktop->layer_manager->renameLayer(desktop->currentLayer(), (gchar *)name.c_str(), FALSE); DocumentUndo::done(desktop->getDocument(), SP_VERB_LAYER_RENAME, _("Rename layer")); // TRANSLATORS: This means "The layer has been renamed" desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Renamed layer")); } -void LayerPropertiesDialog::Create::setup(LayerPropertiesDialog &dialog) { +void LayerPropertiesDialog::Create::setup(LayerPropertiesDialog &dialog) +{ dialog.set_title(_("Add Layer")); // Set the initial name to the "next available" layer name @@ -346,11 +330,12 @@ void LayerPropertiesDialog::Create::setup(LayerPropertiesDialog &dialog) { dialog._setup_position_controls(); } -void LayerPropertiesDialog::Create::perform(LayerPropertiesDialog &dialog) { - SPDesktop *desktop=dialog._desktop; +void LayerPropertiesDialog::Create::perform(LayerPropertiesDialog &dialog) +{ + SPDesktop *desktop = dialog._desktop; LayerRelativePosition position = LPOS_ABOVE; - + if (dialog._position_visible) { Gtk::ListStore::iterator activeRow(dialog._layer_position_combo.get_active()); position = activeRow->get_value(dialog._dropdown_columns.position); @@ -359,10 +344,10 @@ void LayerPropertiesDialog::Create::perform(LayerPropertiesDialog &dialog) { if (name.empty()) return; - SPObject *new_layer=Inkscape::create_layer(desktop->currentRoot(), dialog._layer, position); - + SPObject *new_layer = Inkscape::create_layer(desktop->currentRoot(), dialog._layer, position); + if (!name.empty()) { - desktop->layer_manager->renameLayer( new_layer, (gchar *)name.c_str(), TRUE ); + desktop->layer_manager->renameLayer(new_layer, (gchar *)name.c_str(), TRUE); } desktop->getSelection()->clear(); desktop->setCurrentLayer(new_layer); @@ -370,31 +355,34 @@ void LayerPropertiesDialog::Create::perform(LayerPropertiesDialog &dialog) { desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("New layer created.")); } -void LayerPropertiesDialog::Move::setup(LayerPropertiesDialog &dialog) { +void LayerPropertiesDialog::Move::setup(LayerPropertiesDialog &dialog) +{ dialog.set_title(_("Move to Layer")); - //TODO: find an unused layer number, forming name from _("Layer ") + "%d" + // 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) { - +void LayerPropertiesDialog::Move::perform(LayerPropertiesDialog &dialog) +{ SPObject *moveto = dialog._selectedLayer(); dialog._desktop->selection->toLayer(moveto); } -void LayerPropertiesDialog::_setDesktop(SPDesktop *desktop) { +void LayerPropertiesDialog::_setDesktop(SPDesktop *desktop) +{ if (desktop) { - Inkscape::GC::anchor (desktop); + Inkscape::GC::anchor(desktop); } if (_desktop) { - Inkscape::GC::release (_desktop); + Inkscape::GC::release(_desktop); } _desktop = desktop; } -void LayerPropertiesDialog::_setLayer(SPObject *layer) { +void LayerPropertiesDialog::_setLayer(SPObject *layer) +{ if (layer) { sp_object_ref(layer, nullptr); } @@ -404,10 +392,9 @@ void LayerPropertiesDialog::_setLayer(SPObject *layer) { _layer = layer; } -} // namespace -} // namespace -} // namespace - +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/layer-properties.h b/src/ui/dialog/layer-properties.h index 7cdd130bcee87466b365a7006540b88be357a95c..27027706649c942cb8919dfede18b69d87f8be56 100644 --- a/src/ui/dialog/layer-properties.h +++ b/src/ui/dialog/layer-properties.h @@ -13,16 +13,15 @@ #ifndef INKSCAPE_DIALOG_LAYER_PROPERTIES_H #define INKSCAPE_DIALOG_LAYER_PROPERTIES_H +#include <gtkmm/combobox.h> #include <gtkmm/dialog.h> #include <gtkmm/entry.h> -#include <gtkmm/label.h> #include <gtkmm/grid.h> - -#include <gtkmm/combobox.h> +#include <gtkmm/label.h> #include <gtkmm/liststore.h> -#include <gtkmm/treeview.h> -#include <gtkmm/treestore.h> #include <gtkmm/scrolledwindow.h> +#include <gtkmm/treestore.h> +#include <gtkmm/treeview.h> #include "layer-fns.h" #include "ui/widget/layer-selector.h" @@ -33,41 +32,52 @@ namespace Inkscape { namespace UI { namespace Dialogs { -class LayerPropertiesDialog : public Gtk::Dialog { - public: +class LayerPropertiesDialog : public Gtk::Dialog +{ +public: LayerPropertiesDialog(); ~LayerPropertiesDialog() override; - Glib::ustring getName() const { return "LayerPropertiesDialog"; } + Glib::ustring getName() const { return "LayerPropertiesDialog"; } - static void showRename(SPDesktop *desktop, SPObject *layer) { - _showDialog(Rename::instance(), desktop, layer); - } - static void showCreate(SPDesktop *desktop, SPObject *layer) { - _showDialog(Create::instance(), desktop, layer); - } - static void showMove(SPDesktop *desktop, SPObject *layer) { - _showDialog(Move::instance(), desktop, layer); - } + static void showRename(SPDesktop *desktop, SPObject *layer) { _showDialog(Rename::instance(), desktop, layer); } + 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 { + struct Strategy + { virtual ~Strategy() = default; - virtual void setup(LayerPropertiesDialog &)=0; - virtual void perform(LayerPropertiesDialog &)=0; + virtual void setup(LayerPropertiesDialog &) = 0; + virtual void perform(LayerPropertiesDialog &) = 0; }; - struct Rename : public Strategy { - static Rename &instance() { static Rename instance; return instance; } + struct Rename : public Strategy + { + static Rename &instance() + { + static Rename instance; + return instance; + } void setup(LayerPropertiesDialog &dialog) override; void perform(LayerPropertiesDialog &dialog) override; }; - struct Create : public Strategy { - static Create &instance() { static Create instance; return instance; } + struct Create : public Strategy + { + static Create &instance() + { + static Create instance; + return instance; + } void setup(LayerPropertiesDialog &dialog) override; void perform(LayerPropertiesDialog &dialog) override; }; - struct Move : public Strategy { - static Move &instance() { static Move instance; return instance; } + struct Move : public Strategy + { + static Move &instance() + { + static Move instance; + return instance; + } void setup(LayerPropertiesDialog &dialog) override; void perform(LayerPropertiesDialog &dialog) override; }; @@ -80,28 +90,30 @@ protected: SPDesktop *_desktop; SPObject *_layer; - class PositionDropdownColumns : public Gtk::TreeModel::ColumnRecord { + class PositionDropdownColumns : public Gtk::TreeModel::ColumnRecord + { public: Gtk::TreeModelColumn<LayerRelativePosition> position; Gtk::TreeModelColumn<Glib::ustring> name; - PositionDropdownColumns() { - add(position); add(name); + PositionDropdownColumns() + { + add(position); + add(name); } }; - Gtk::Label _layer_name_label; - Gtk::Entry _layer_name_entry; - Gtk::Label _layer_position_label; - Gtk::ComboBox _layer_position_combo; - Gtk::Grid _layout_table; + Gtk::Label _layer_name_label; + Gtk::Entry _layer_name_entry; + Gtk::Label _layer_position_label; + Gtk::ComboBox _layer_position_combo; + Gtk::Grid _layout_table; - bool _position_visible; + bool _position_visible; class ModelColumns : public Gtk::TreeModel::ColumnRecord { public: - ModelColumns() { add(_colObject); @@ -111,28 +123,28 @@ protected: } ~ModelColumns() override = default; - Gtk::TreeModelColumn<SPObject*> _colObject; + Gtk::TreeModelColumn<SPObject *> _colObject; Gtk::TreeModelColumn<Glib::ustring> _colLabel; Gtk::TreeModelColumn<bool> _colVisible; Gtk::TreeModelColumn<bool> _colLocked; }; Gtk::TreeView _tree; - ModelColumns* _model; + ModelColumns *_model; Glib::RefPtr<Gtk::TreeStore> _store; Gtk::ScrolledWindow _scroller; - PositionDropdownColumns _dropdown_columns; Gtk::CellRendererText _label_renderer; Glib::RefPtr<Gtk::ListStore> _dropdown_list; - Gtk::Button _close_button; - Gtk::Button _apply_button; + Gtk::Button _close_button; + Gtk::Button _apply_button; - sigc::connection _destroy_connection; + sigc::connection _destroy_connection; - static LayerPropertiesDialog &_instance() { + static LayerPropertiesDialog &_instance() + { static LayerPropertiesDialog instance; return instance; } @@ -148,22 +160,21 @@ protected: 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(); + void _addLayer(SPDocument *doc, SPObject *layer, Gtk::TreeModel::Row *parentRow, SPObject *target, int level); + SPObject *_selectedLayer(); bool _handleKeyEvent(GdkEventKey *event); - void _handleButtonEvent(GdkEventButton* event); + void _handleButtonEvent(GdkEventButton *event); private: - LayerPropertiesDialog(LayerPropertiesDialog const &) = delete; // no copy + LayerPropertiesDialog(LayerPropertiesDialog const &) = delete; // no copy LayerPropertiesDialog &operator=(LayerPropertiesDialog const &) = delete; // no assign }; -} // namespace -} // namespace -} // namespace - +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape -#endif //INKSCAPE_DIALOG_LAYER_PROPERTIES_H +#endif // INKSCAPE_DIALOG_LAYER_PROPERTIES_H /* Local Variables: diff --git a/src/ui/dialog/layers.cpp b/src/ui/dialog/layers.cpp index ac44762274656dfa673b313bcb6363e07e0225e2..8cb7c040d258517306a1b53d48e8ee5dc48fab95 100644 --- a/src/ui/dialog/layers.cpp +++ b/src/ui/dialog/layers.cpp @@ -13,34 +13,28 @@ #include "layers.h" +#include <glibmm/main.h> #include <gtkmm/icontheme.h> #include <gtkmm/separatormenuitem.h> -#include <glibmm/main.h> #include "desktop-style.h" #include "desktop.h" #include "document-undo.h" #include "document.h" +#include "helper/action.h" +#include "include/gtkmm_version.h" #include "inkscape.h" #include "layer-fns.h" #include "layer-manager.h" -#include "selection-chemistry.h" -#include "verbs.h" - -#include "helper/action.h" -#include "ui/icon-loader.h" - -#include "include/gtkmm_version.h" - #include "object/sp-root.h" - +#include "selection-chemistry.h" #include "svg/css-ostringstream.h" - #include "ui/contextmenu.h" #include "ui/icon-loader.h" #include "ui/icon-names.h" #include "ui/tools/tool-base.h" #include "ui/widget/imagetoggler.h" +#include "verbs.h" //#define DUMP_LAYERS 1 @@ -48,17 +42,19 @@ namespace Inkscape { namespace UI { namespace Dialog { -LayersPanel& LayersPanel::getInstance() +LayersPanel &LayersPanel::getInstance() { return *new LayersPanel(); } -enum { +enum +{ COL_VISIBLE = 1, COL_LOCKED }; -enum { +enum +{ BUTTON_NEW = 0, BUTTON_RENAME, BUTTON_TOP, @@ -80,14 +76,15 @@ class LayersPanel::InternalUIBounce { public: int _actionCode; - SPObject* _target; + SPObject *_target; }; -void LayersPanel::_styleButton( Gtk::Button& btn, SPDesktop *desktop, unsigned int code, char const* iconName, char const* fallback ) +void LayersPanel::_styleButton(Gtk::Button &btn, SPDesktop *desktop, unsigned int code, char const *iconName, + char const *fallback) { bool set = false; - if ( iconName ) { + if (iconName) { auto child = Glib::wrap(sp_get_icon_image(iconName, GTK_ICON_SIZE_SMALL_TOOLBAR)); child->show(); btn.add(*child); @@ -95,48 +92,47 @@ void LayersPanel::_styleButton( Gtk::Button& btn, SPDesktop *desktop, unsigned i set = true; } - if ( desktop ) { - Verb *verb = Verb::get( code ); - if ( verb ) { + if (desktop) { + Verb *verb = Verb::get(code); + if (verb) { SPAction *action = verb->get_action(Inkscape::ActionContext(desktop)); - if ( !set && action && action->image ) { + if (!set && action && action->image) { auto child = Glib::wrap(sp_get_icon_image(action->image, GTK_ICON_SIZE_SMALL_TOOLBAR)); child->show(); btn.add(*child); set = true; } - if ( action && action->tip ) { - btn.set_tooltip_text (action->tip); + if (action && action->tip) { + btn.set_tooltip_text(action->tip); } } } - if ( !set && fallback ) { - btn.set_label( fallback ); + if (!set && fallback) { + btn.set_label(fallback); } } - -Gtk::MenuItem& LayersPanel::_addPopupItem( SPDesktop *desktop, unsigned int code, int id ) +Gtk::MenuItem &LayersPanel::_addPopupItem(SPDesktop *desktop, unsigned int code, int id) { - Verb *verb = Verb::get( code ); + Verb *verb = Verb::get(code); g_assert(verb); SPAction *action = verb->get_action(Inkscape::ActionContext(desktop)); - Gtk::MenuItem* item = Gtk::manage(new Gtk::MenuItem()); + Gtk::MenuItem *item = Gtk::manage(new Gtk::MenuItem()); Gtk::Label *label = Gtk::manage(new Gtk::Label(action->name, true)); label->set_xalign(0.0); if (_show_contextmenu_icons && action->image) { - item->set_name("ImageMenuItem"); // custom name to identify our "ImageMenuItems" + item->set_name("ImageMenuItem"); // custom name to identify our "ImageMenuItems" Gtk::Image *icon = Gtk::manage(sp_get_icon_image(action->image, Gtk::ICON_SIZE_MENU)); // Create a box to hold icon and label as Gtk::MenuItem derives from GtkBin and can only hold one child Gtk::Box *box = Gtk::manage(new Gtk::Box()); box->pack_start(*icon, false, false, 0); - box->pack_start(*label, true, true, 0); + box->pack_start(*label, true, true, 0); item->add(*box); } else { item->add(*label); @@ -148,127 +144,91 @@ Gtk::MenuItem& LayersPanel::_addPopupItem( SPDesktop *desktop, unsigned int code return *item; } -void LayersPanel::_fireAction( unsigned int code ) +void LayersPanel::_fireAction(unsigned int code) { - if ( _desktop ) { - Verb *verb = Verb::get( code ); - if ( verb ) { + if (_desktop) { + Verb *verb = Verb::get(code); + if (verb) { SPAction *action = verb->get_action(Inkscape::ActionContext(_desktop)); - if ( action ) { - sp_action_perform( action, nullptr ); -// } else { -// g_message("no action"); + if (action) { + sp_action_perform(action, nullptr); + // } else { + // g_message("no action"); } -// } else { -// g_message("no verb for %u", code); + // } else { + // g_message("no verb for %u", code); } -// } else { -// g_message("no active desktop"); + // } else { + // g_message("no active desktop"); } } // SP_VERB_LAYER_NEXT, // SP_VERB_LAYER_PREV, -void LayersPanel::_takeAction( int val ) +void LayersPanel::_takeAction(int val) { - if ( !_pending ) { + if (!_pending) { _pending = new InternalUIBounce(); _pending->_actionCode = val; _pending->_target = _selectedLayer(); - Glib::signal_timeout().connect( sigc::mem_fun(*this, &LayersPanel::_executeAction), 0 ); + Glib::signal_timeout().connect(sigc::mem_fun(*this, &LayersPanel::_executeAction), 0); } } bool LayersPanel::_executeAction() { // Make sure selected layer hasn't changed since the action was triggered - if ( _pending - && ( - (_pending->_actionCode == BUTTON_NEW || _pending->_actionCode == DRAGNDROP) - || !( (_desktop && _desktop->currentLayer()) - && (_desktop->currentLayer() != _pending->_target) - ) - ) - ) { + if (_pending && ((_pending->_actionCode == BUTTON_NEW || _pending->_actionCode == DRAGNDROP) || + !((_desktop && _desktop->currentLayer()) && (_desktop->currentLayer() != _pending->_target)))) { int val = _pending->_actionCode; -// SPObject* target = _pending->_target; - - switch ( val ) { - case BUTTON_NEW: - { - _fireAction( SP_VERB_LAYER_NEW ); - } - break; - case BUTTON_RENAME: - { - _fireAction( SP_VERB_LAYER_RENAME ); - } - break; - case BUTTON_TOP: - { - _fireAction( SP_VERB_LAYER_TO_TOP ); - } - break; - case BUTTON_BOTTOM: - { - _fireAction( SP_VERB_LAYER_TO_BOTTOM ); - } - break; - case BUTTON_UP: - { - _fireAction( SP_VERB_LAYER_RAISE ); - } - break; - case BUTTON_DOWN: - { - _fireAction( SP_VERB_LAYER_LOWER ); - } - break; - case BUTTON_DUPLICATE: - { - _fireAction( SP_VERB_LAYER_DUPLICATE ); - } - break; - case BUTTON_DELETE: - { - _fireAction( SP_VERB_LAYER_DELETE ); - } - break; - case BUTTON_SOLO: - { - _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; + // SPObject* target = _pending->_target; + + switch (val) { + case BUTTON_NEW: { + _fireAction(SP_VERB_LAYER_NEW); + } break; + case BUTTON_RENAME: { + _fireAction(SP_VERB_LAYER_RENAME); + } break; + case BUTTON_TOP: { + _fireAction(SP_VERB_LAYER_TO_TOP); + } break; + case BUTTON_BOTTOM: { + _fireAction(SP_VERB_LAYER_TO_BOTTOM); + } break; + case BUTTON_UP: { + _fireAction(SP_VERB_LAYER_RAISE); + } break; + case BUTTON_DOWN: { + _fireAction(SP_VERB_LAYER_LOWER); + } break; + case BUTTON_DUPLICATE: { + _fireAction(SP_VERB_LAYER_DUPLICATE); + } break; + case BUTTON_DELETE: { + _fireAction(SP_VERB_LAYER_DELETE); + } break; + case BUTTON_SOLO: { + _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; @@ -281,7 +241,6 @@ bool LayersPanel::_executeAction() class LayersPanel::ModelColumns : public Gtk::TreeModel::ColumnRecord { public: - ModelColumns() { add(_colObject); @@ -291,28 +250,28 @@ public: } ~ModelColumns() override = default; - Gtk::TreeModelColumn<SPObject*> _colObject; + Gtk::TreeModelColumn<SPObject *> _colObject; Gtk::TreeModelColumn<Glib::ustring> _colLabel; Gtk::TreeModelColumn<bool> _colVisible; Gtk::TreeModelColumn<bool> _colLocked; }; -void LayersPanel::_updateLayer( SPObject *layer ) { - _store->foreach( sigc::bind<SPObject*>(sigc::mem_fun(*this, &LayersPanel::_checkForUpdated), layer) ); +void LayersPanel::_updateLayer(SPObject *layer) +{ + _store->foreach (sigc::bind<SPObject *>(sigc::mem_fun(*this, &LayersPanel::_checkForUpdated), layer)); } -bool LayersPanel::_checkForUpdated(const Gtk::TreePath &/*path*/, const Gtk::TreeIter& iter, SPObject* layer) +bool LayersPanel::_checkForUpdated(const Gtk::TreePath & /*path*/, const Gtk::TreeIter &iter, SPObject *layer) { bool stopGoing = false; Gtk::TreeModel::Row row = *iter; - if ( layer == row[_model->_colObject] ) - { + if (layer == row[_model->_colObject]) { /* * We get notified of layer update here (from layer->setLabel()) before layer->label() is set * with the correct value (sp-object bug?). So use the inkscape:label attribute instead which * has the correct value (bug #168351) */ - //row[_model->_colLabel] = layer->label() ? layer->label() : layer->defaultLabel(); + // row[_model->_colLabel] = layer->label() ? layer->label() : layer->defaultLabel(); gchar const *label = layer->getAttribute("inkscape:label"); row[_model->_colLabel] = label ? label : layer->defaultLabel(); row[_model->_colVisible] = SP_IS_ITEM(layer) ? !SP_ITEM(layer)->isHidden() : false; @@ -324,26 +283,26 @@ bool LayersPanel::_checkForUpdated(const Gtk::TreePath &/*path*/, const Gtk::Tre return stopGoing; } -void LayersPanel::_selectLayer( SPObject *layer ) { - if ( !layer || (_desktop && _desktop->doc() && (layer == _desktop->doc()->getRoot())) ) { - if ( _tree.get_selection()->count_selected_rows() != 0 ) { +void LayersPanel::_selectLayer(SPObject *layer) +{ + if (!layer || (_desktop && _desktop->doc() && (layer == _desktop->doc()->getRoot()))) { + if (_tree.get_selection()->count_selected_rows() != 0) { _tree.get_selection()->unselect_all(); } } else { - _store->foreach( sigc::bind<SPObject*>(sigc::mem_fun(*this, &LayersPanel::_checkForSelected), layer) ); + _store->foreach (sigc::bind<SPObject *>(sigc::mem_fun(*this, &LayersPanel::_checkForSelected), layer)); } _checkTreeSelection(); } -bool LayersPanel::_checkForSelected(const Gtk::TreePath &path, const Gtk::TreeIter& iter, SPObject* layer) +bool LayersPanel::_checkForSelected(const Gtk::TreePath &path, const Gtk::TreeIter &iter, SPObject *layer) { bool stopGoing = false; Gtk::TreeModel::Row row = *iter; - if ( layer == row[_model->_colObject] ) - { - _tree.expand_to_path( path ); + if (layer == row[_model->_colObject]) { + _tree.expand_to_path(path); Glib::RefPtr<Gtk::TreeSelection> select = _tree.get_selection(); @@ -358,35 +317,36 @@ bool LayersPanel::_checkForSelected(const Gtk::TreePath &path, const Gtk::TreeIt void LayersPanel::_layersChanged() { assert(_desktop); - SPDocument* document = _desktop->doc(); + SPDocument *document = _desktop->doc(); if (document) { - SPRoot* root = document->getRoot(); - if ( root ) { + SPRoot *root = document->getRoot(); + if (root) { _selectedConnection.block(); - if ( _desktop->layer_manager && _desktop->layer_manager->includes( root ) ) { - SPObject* target = _desktop->currentLayer(); + if (_desktop->layer_manager && _desktop->layer_manager->includes(root)) { + SPObject *target = _desktop->currentLayer(); _store->clear(); - #if DUMP_LAYERS - g_message("root:%p {%s} [%s]", root, root->id, root->label() ); - #endif // DUMP_LAYERS - _addLayer( document, root, nullptr, target, 0 ); +#if DUMP_LAYERS + g_message("root:%p {%s} [%s]", root, root->id, root->label()); +#endif // DUMP_LAYERS + _addLayer(document, root, nullptr, target, 0); } _selectedConnection.unblock(); } } } -void LayersPanel::_addLayer( SPDocument* doc, SPObject* layer, Gtk::TreeModel::Row* parentRow, SPObject* target, int level ) +void LayersPanel::_addLayer(SPDocument *doc, SPObject *layer, Gtk::TreeModel::Row *parentRow, SPObject *target, + int level) { - if ( _desktop && _desktop->layer_manager && layer && (level < _maxNestDepth) ) { + if (_desktop && _desktop->layer_manager && layer && (level < _maxNestDepth)) { unsigned int counter = _desktop->layer_manager->childCount(layer); - for ( unsigned int i = 0; i < counter; i++ ) { + for (unsigned int i = 0; i < counter; i++) { SPObject *child = _desktop->layer_manager->nthChildOf(layer, i); - if ( child ) { + if (child) { #if DUMP_LAYERS - g_message(" %3d layer:%p {%s} [%s]", level, child, child->getId(), 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(); @@ -396,8 +356,8 @@ void LayersPanel::_addLayer( SPDocument* doc, SPObject* layer, Gtk::TreeModel::R 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) ); + if (target && child == target) { + _tree.expand_to_path(_store->get_path(iter)); Glib::RefPtr<Gtk::TreeSelection> select = _tree.get_selection(); select->select(iter); @@ -405,18 +365,18 @@ void LayersPanel::_addLayer( SPDocument* doc, SPObject* layer, Gtk::TreeModel::R _checkTreeSelection(); } - _addLayer( doc, child, &row, target, level + 1 ); + _addLayer(doc, child, &row, target, level + 1); } } } } -SPObject* LayersPanel::_selectedLayer() +SPObject *LayersPanel::_selectedLayer() { - SPObject* obj = nullptr; + SPObject *obj = nullptr; Gtk::TreeModel::iterator iter = _tree.get_selection()->get_selected(); - if ( iter ) { + if (iter) { Gtk::TreeModel::Row row = *iter; obj = row[_model->_colObject]; } @@ -427,15 +387,15 @@ SPObject* LayersPanel::_selectedLayer() void LayersPanel::_pushTreeSelectionToCurrent() { // TODO hunt down the possible API abuse in getting NULL - if ( _desktop && _desktop->layer_manager && _desktop->currentRoot() ) { - SPObject* inTree = _selectedLayer(); - if ( inTree ) { - SPObject* curr = _desktop->currentLayer(); - if ( curr != inTree ) { - _desktop->layer_manager->setCurrentLayer( inTree ); + if (_desktop && _desktop->layer_manager && _desktop->currentRoot()) { + SPObject *inTree = _selectedLayer(); + if (inTree) { + SPObject *curr = _desktop->currentLayer(); + if (curr != inTree) { + _desktop->layer_manager->setCurrentLayer(inTree); } } else { - _desktop->layer_manager->setCurrentLayer( _desktop->doc()->getRoot() ); + _desktop->layer_manager->setCurrentLayer(_desktop->doc()->getRoot()); } } } @@ -445,45 +405,41 @@ void LayersPanel::_checkTreeSelection() bool sensitive = false; bool sensitiveNonTop = false; bool sensitiveNonBottom = false; - if ( _tree.get_selection()->count_selected_rows() > 0 ) { + if (_tree.get_selection()->count_selected_rows() > 0) { sensitive = true; - SPObject* inTree = _selectedLayer(); - if ( inTree ) { - + SPObject *inTree = _selectedLayer(); + if (inTree) { sensitiveNonTop = (Inkscape::next_layer(inTree->parent, inTree) != nullptr); sensitiveNonBottom = (Inkscape::previous_layer(inTree->parent, inTree) != nullptr); - } } - - for (auto & it : _watching) { - it->set_sensitive( sensitive ); + for (auto &it : _watching) { + it->set_sensitive(sensitive); } - for (auto & it : _watchingNonTop) { - it->set_sensitive( sensitiveNonTop ); + for (auto &it : _watchingNonTop) { + it->set_sensitive(sensitiveNonTop); } - for (auto & it : _watchingNonBottom) { - it->set_sensitive( sensitiveNonBottom ); + for (auto &it : _watchingNonBottom) { + it->set_sensitive(sensitiveNonBottom); } } -void LayersPanel::_preToggle( GdkEvent const *event ) +void LayersPanel::_preToggle(GdkEvent const *event) { - - if ( _toggleEvent ) { + if (_toggleEvent) { gdk_event_free(_toggleEvent); _toggleEvent = nullptr; } - if ( event && (event->type == GDK_BUTTON_PRESS) ) { + if (event && (event->type == GDK_BUTTON_PRESS)) { // Make a copy so we can keep it around. - _toggleEvent = gdk_event_copy(const_cast<GdkEvent*>(event)); + _toggleEvent = gdk_event_copy(const_cast<GdkEvent *>(event)); } } -void LayersPanel::_toggled( Glib::ustring const& str, int targetCol ) +void LayersPanel::_toggled(Glib::ustring const &str, int targetCol) { g_return_if_fail(_desktop != nullptr); @@ -492,80 +448,73 @@ void LayersPanel::_toggled( Glib::ustring const& str, int targetCol ) Glib::ustring tmp = row[_model->_colLabel]; - SPObject* obj = row[_model->_colObject]; - SPItem* item = ( obj && SP_IS_ITEM(obj) ) ? SP_ITEM(obj) : nullptr; - if ( item ) { - switch ( targetCol ) { - case COL_VISIBLE: - { + SPObject *obj = row[_model->_colObject]; + SPItem *item = (obj && SP_IS_ITEM(obj)) ? SP_ITEM(obj) : nullptr; + if (item) { + switch (targetCol) { + case COL_VISIBLE: { bool newValue = !row[_model->_colVisible]; row[_model->_colVisible] = newValue; - item->setHidden( !newValue ); + item->setHidden(!newValue); item->updateRepr(); - DocumentUndo::done( _desktop->doc() , SP_VERB_DIALOG_LAYERS, - newValue? _("Unhide layer") : _("Hide layer")); - } - break; + DocumentUndo::done(_desktop->doc(), SP_VERB_DIALOG_LAYERS, + newValue ? _("Unhide layer") : _("Hide layer")); + } break; - case COL_LOCKED: - { + case COL_LOCKED: { bool newValue = !row[_model->_colLocked]; row[_model->_colLocked] = newValue; - item->setLocked( newValue ); + item->setLocked(newValue); item->updateRepr(); - DocumentUndo::done( _desktop->doc() , SP_VERB_DIALOG_LAYERS, - newValue? _("Lock layer") : _("Unlock layer")); - } - break; + DocumentUndo::done(_desktop->doc(), SP_VERB_DIALOG_LAYERS, + newValue ? _("Lock layer") : _("Unlock layer")); + } break; } } Inkscape::SelectionHelper::fixSelection(_desktop); } -bool LayersPanel::_handleButtonEvent(GdkEventButton* event) +bool LayersPanel::_handleButtonEvent(GdkEventButton *event) { static unsigned doubleclick = 0; - if ( (event->type == GDK_BUTTON_PRESS) && (event->button == 3) ) { + 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 ) ) { + if (_tree.get_path_at_pos(x, y, path)) { _checkTreeSelection(); _popupMenu.popup_at_pointer(reinterpret_cast<GdkEvent *>(event)); } } - if ( (event->type == GDK_BUTTON_PRESS) && (event->button == 1) - && (event->state & GDK_MOD1_MASK)) { + 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 = nullptr; + Gtk::TreeViewColumn *col = nullptr; 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)) { + 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))) { - + if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 1) && + (event->state & (GDK_SHIFT_MASK | GDK_MOD1_MASK))) { Gtk::TreeModel::Path path; - Gtk::TreeViewColumn* col = nullptr; + Gtk::TreeViewColumn *col = nullptr; 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 (_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)) { @@ -580,19 +529,20 @@ bool LayersPanel::_handleButtonEvent(GdkEventButton* event) 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")); + _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")); + _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) ) { + if ((event->type == GDK_2BUTTON_PRESS) && (event->button == 1)) { doubleclick = 1; } @@ -603,7 +553,7 @@ bool LayersPanel::_handleButtonEvent(GdkEventButton* event) * 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*/) +bool LayersPanel::_handleDragDrop(const Glib::RefPtr<Gdk::DragContext> & /*context*/, int x, int y, guint /*time*/) { int cell_x = 0, cell_y = 0; Gtk::TreeModel::Path target_path; @@ -612,15 +562,15 @@ bool LayersPanel::_handleDragDrop(const Glib::RefPtr<Gdk::DragContext>& /*contex _dnd_into = false; _dnd_target = nullptr; - _dnd_source = ( selected && SP_IS_ITEM(selected) ) ? SP_ITEM(selected) : nullptr; + _dnd_source = (selected && SP_IS_ITEM(selected)) ? SP_ITEM(selected) : nullptr; - if (_tree.get_path_at_pos (x, y, target_path, target_column, cell_x, cell_y)) { + 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); + _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)) { + _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))) { @@ -643,7 +593,7 @@ bool LayersPanel::_handleDragDrop(const Glib::RefPtr<Gdk::DragContext>& /*contex 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) : nullptr; + _dnd_target = (obj && SP_IS_ITEM(obj)) ? SP_ITEM(obj) : nullptr; } } @@ -655,14 +605,15 @@ bool LayersPanel::_handleDragDrop(const Glib::RefPtr<Gdk::DragContext>& /*contex /* * Move a layer in response to a drag & drop action */ -void LayersPanel::_doTreeMove( ) +void LayersPanel::_doTreeMove() { - if (_dnd_source && _dnd_source->getRepr() ) { - if(!_dnd_target){ - _dnd_source->doWriteTransform(_dnd_source->i2doc_affine() * _dnd_source->document->getRoot()->i2doc_affine().inverse()); - }else{ - SPItem* parent = _dnd_into ? _dnd_target : dynamic_cast<SPItem*>(_dnd_target->parent); - if(parent){ + if (_dnd_source && _dnd_source->getRepr()) { + if (!_dnd_target) { + _dnd_source->doWriteTransform(_dnd_source->i2doc_affine() * + _dnd_source->document->getRoot()->i2doc_affine().inverse()); + } else { + SPItem *parent = _dnd_into ? _dnd_target : dynamic_cast<SPItem *>(_dnd_target->parent); + if (parent) { Geom::Affine move = _dnd_source->i2doc_affine() * parent->i2doc_affine().inverse(); _dnd_source->doWriteTransform(move); } @@ -670,13 +621,11 @@ void LayersPanel::_doTreeMove( ) _dnd_source->moveTo(_dnd_target, _dnd_into); _selectLayer(_dnd_source); _dnd_source = nullptr; - DocumentUndo::done( _desktop->doc() , SP_VERB_NONE, - _("Move layer")); + DocumentUndo::done(_desktop->doc(), SP_VERB_NONE, _("Move layer")); } } - -void LayersPanel::_handleEdited(const Glib::ustring& path, const Glib::ustring& new_text) +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; @@ -684,40 +633,34 @@ void LayersPanel::_handleEdited(const Glib::ustring& path, const Glib::ustring& _renameLayer(row, new_text); } -void LayersPanel::_renameLayer(Gtk::TreeModel::Row row, const Glib::ustring& name) +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(); - if ( !name.empty() && (!oldLabel || name != oldLabel) ) { - _desktop->layer_manager->renameLayer( obj, name.c_str(), FALSE ); - DocumentUndo::done( _desktop->doc() , SP_VERB_NONE, - _("Rename layer")); + if (row && _desktop && _desktop->layer_manager) { + SPObject *obj = row[_model->_colObject]; + if (obj) { + gchar const *oldLabel = obj->label(); + if (!name.empty() && (!oldLabel || name != oldLabel)) { + _desktop->layer_manager->renameLayer(obj, name.c_str(), FALSE); + DocumentUndo::done(_desktop->doc(), SP_VERB_NONE, _("Rename layer")); } - } } } -bool LayersPanel::_rowSelectFunction( Glib::RefPtr<Gtk::TreeModel> const & /*model*/, Gtk::TreeModel::Path const & /*path*/, bool currentlySelected ) +bool LayersPanel::_rowSelectFunction(Glib::RefPtr<Gtk::TreeModel> const & /*model*/, + Gtk::TreeModel::Path const & /*path*/, bool currentlySelected) { bool val = true; - if ( !currentlySelected && _toggleEvent ) - { - GdkEvent* event = gtk_get_current_event(); - if ( event ) { + if (!currentlySelected && _toggleEvent) { + GdkEvent *event = gtk_get_current_event(); + if (event) { // (keep these checks separate, so we know when to call gdk_event_free() - if ( event->type == GDK_BUTTON_PRESS ) { - GdkEventButton const* target = reinterpret_cast<GdkEventButton const*>(_toggleEvent); - GdkEventButton const* evtb = reinterpret_cast<GdkEventButton const*>(event); - - if ( (evtb->window == target->window) - && (evtb->send_event == target->send_event) - && (evtb->time == target->time) - && (evtb->state == target->state) - ) - { + if (event->type == GDK_BUTTON_PRESS) { + GdkEventButton const *target = reinterpret_cast<GdkEventButton const *>(_toggleEvent); + GdkEventButton const *evtb = reinterpret_cast<GdkEventButton const *>(event); + + if ((evtb->window == target->window) && (evtb->send_event == target->send_event) && + (evtb->time == target->time) && (evtb->state == target->state)) { // Ooooh! It's a magic one val = false; } @@ -731,18 +674,16 @@ bool LayersPanel::_rowSelectFunction( Glib::RefPtr<Gtk::TreeModel> const & /*mod /** * Constructor */ -LayersPanel::LayersPanel() : - UI::Widget::Panel("/dialogs/layers", SP_VERB_DIALOG_LAYERS), - _maxNestDepth(20), - _desktop(nullptr), - _model(nullptr), - _pending(nullptr), - _toggleEvent(nullptr), - _compositeSettings(SP_VERB_DIALOG_LAYERS, "layers", - UI::Widget::SimpleFilterModifier::ISOLATION | - UI::Widget::SimpleFilterModifier::BLEND | - UI::Widget::SimpleFilterModifier::OPACITY | - UI::Widget::SimpleFilterModifier::BLUR) +LayersPanel::LayersPanel() + : UI::Widget::Panel("/dialogs/layers", SP_VERB_DIALOG_LAYERS) + , _maxNestDepth(20) + , _desktop(nullptr) + , _model(nullptr) + , _pending(nullptr) + , _toggleEvent(nullptr) + , _compositeSettings(SP_VERB_DIALOG_LAYERS, "layers", + UI::Widget::SimpleFilterModifier::ISOLATION | UI::Widget::SimpleFilterModifier::BLEND | + UI::Widget::SimpleFilterModifier::OPACITY | UI::Widget::SimpleFilterModifier::BLUR) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); _maxNestDepth = prefs->getIntLimited("/dialogs/layers/maxDepth", 20, 1, 1000); @@ -750,34 +691,33 @@ LayersPanel::LayersPanel() : ModelColumns *zoop = new ModelColumns(); _model = zoop; - _store = Gtk::TreeStore::create( *zoop ); + _store = Gtk::TreeStore::create(*zoop); - _tree.set_model( _store ); + _tree.set_model(_store); _tree.set_headers_visible(false); _tree.set_reorderable(true); - _tree.enable_model_drag_dest (Gdk::ACTION_MOVE); + _tree.enable_model_drag_dest(Gdk::ACTION_MOVE); - Inkscape::UI::Widget::ImageToggler *eyeRenderer = Gtk::manage( new Inkscape::UI::Widget::ImageToggler( - INKSCAPE_ICON("object-visible"), INKSCAPE_ICON("object-hidden")) ); + Inkscape::UI::Widget::ImageToggler *eyeRenderer = Gtk::manage( + new Inkscape::UI::Widget::ImageToggler(INKSCAPE_ICON("object-visible"), INKSCAPE_ICON("object-hidden"))); int visibleColNum = _tree.append_column("vis", *eyeRenderer) - 1; - eyeRenderer->signal_pre_toggle().connect( sigc::mem_fun(*this, &LayersPanel::_preToggle) ); - eyeRenderer->signal_toggled().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_toggled), (int)COL_VISIBLE) ); + eyeRenderer->signal_pre_toggle().connect(sigc::mem_fun(*this, &LayersPanel::_preToggle)); + eyeRenderer->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &LayersPanel::_toggled), (int)COL_VISIBLE)); eyeRenderer->property_activatable() = true; - Gtk::TreeViewColumn* col = _tree.get_column(visibleColNum); - if ( col ) { - col->add_attribute( eyeRenderer->property_active(), _model->_colVisible ); + Gtk::TreeViewColumn *col = _tree.get_column(visibleColNum); + if (col) { + col->add_attribute(eyeRenderer->property_active(), _model->_colVisible); } - - Inkscape::UI::Widget::ImageToggler * renderer = Gtk::manage( new Inkscape::UI::Widget::ImageToggler( - INKSCAPE_ICON("object-locked"), INKSCAPE_ICON("object-unlocked")) ); + Inkscape::UI::Widget::ImageToggler *renderer = Gtk::manage( + new Inkscape::UI::Widget::ImageToggler(INKSCAPE_ICON("object-locked"), INKSCAPE_ICON("object-unlocked"))); int lockedColNum = _tree.append_column("lock", *renderer) - 1; - renderer->signal_pre_toggle().connect( sigc::mem_fun(*this, &LayersPanel::_preToggle) ); - renderer->signal_toggled().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_toggled), (int)COL_LOCKED) ); + renderer->signal_pre_toggle().connect(sigc::mem_fun(*this, &LayersPanel::_preToggle)); + renderer->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &LayersPanel::_toggled), (int)COL_LOCKED)); renderer->property_activatable() = true; col = _tree.get_column(lockedColNum); - if ( col ) { - col->add_attribute( renderer->property_active(), _model->_colLocked ); + if (col) { + col->add_attribute(renderer->property_active(), _model->_colLocked); } _text_renderer = Gtk::manage(new Gtk::CellRendererText()); @@ -785,24 +725,25 @@ LayersPanel::LayersPanel() : _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_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) ); + _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.signal_drag_drop().connect( sigc::mem_fun(*this, &LayersPanel::_handleDragDrop), false); + _tree.signal_drag_drop().connect(sigc::mem_fun(*this, &LayersPanel::_handleDragDrop), false); _text_renderer->property_editable() = true; - _text_renderer->signal_edited().connect( sigc::mem_fun(*this, &LayersPanel::_handleEdited) ); + _text_renderer->signal_edited().connect(sigc::mem_fun(*this, &LayersPanel::_handleEdited)); - _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_button_press_event().connect(sigc::mem_fun(*this, &LayersPanel::_handleButtonEvent), false); + _tree.signal_button_release_event().connect(sigc::mem_fun(*this, &LayersPanel::_handleButtonEvent), false); - _scroller.add( _tree ); - _scroller.set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC ); + _scroller.add(_tree); + _scroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); _scroller.set_shadow_type(Gtk::SHADOW_IN); Gtk::Requisition sreq; Gtk::Requisition sreq_natural; @@ -813,109 +754,106 @@ LayersPanel::LayersPanel() : _scroller.set_size_request(sreq.width, minHeight); } - _watching.push_back( &_compositeSettings ); + _watching.push_back(&_compositeSettings); - _layersPage.pack_start( _scroller, Gtk::PACK_EXPAND_WIDGET ); + _layersPage.pack_start(_scroller, Gtk::PACK_EXPAND_WIDGET); _layersPage.pack_end(_compositeSettings, Gtk::PACK_SHRINK); _layersPage.pack_end(_buttonsRow, Gtk::PACK_SHRINK); _getContents()->pack_start(_layersPage, Gtk::PACK_EXPAND_WIDGET); - SPDesktop* targetDesktop = getDesktop(); + SPDesktop *targetDesktop = getDesktop(); - Gtk::Button* btn = Gtk::manage( new Gtk::Button() ); - _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) ); + Gtk::Button *btn = Gtk::manage(new Gtk::Button()); + _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)); _buttonsSecondary.pack_start(*btn, Gtk::PACK_SHRINK); - btn = Gtk::manage( new Gtk::Button() ); - _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 ); + btn = Gtk::manage(new Gtk::Button()); + _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 = Gtk::manage( new Gtk::Button() ); - _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 ); + + btn = Gtk::manage(new Gtk::Button()); + _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); _buttonsPrimary.pack_end(*btn, Gtk::PACK_SHRINK); - - btn = Gtk::manage( new Gtk::Button() ); - _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 ); + + btn = Gtk::manage(new Gtk::Button()); + _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 = Gtk::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 ); + + btn = Gtk::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 = Gtk::manage( new Gtk::Button("Dup") ); -// btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), (int)BUTTON_DUPLICATE) ); -// _buttonsRow.add( *btn ); + // btn = Gtk::manage( new Gtk::Button("Dup") ); + // btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), + // (int)BUTTON_DUPLICATE) ); _buttonsRow.add( *btn ); - btn = Gtk::manage( new Gtk::Button() ); - _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 ); + btn = Gtk::manage(new Gtk::Button()); + _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); _buttonsSecondary.pack_start(*btn, Gtk::PACK_SHRINK); - + _buttonsRow.pack_start(_buttonsSecondary, Gtk::PACK_EXPAND_WIDGET); _buttonsRow.pack_end(_buttonsPrimary, Gtk::PACK_EXPAND_WIDGET); - - // ------------------------------------------------------- { _show_contextmenu_icons = prefs->getBool("/theme/menuIcons_layers", true); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_NEW, (int)BUTTON_NEW ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_RENAME, (int)BUTTON_RENAME ) ); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_NEW, (int)BUTTON_NEW)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_RENAME, (int)BUTTON_RENAME)); _popupMenu.append(*Gtk::manage(new Gtk::SeparatorMenuItem())); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_SOLO, (int)BUTTON_SOLO ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_SHOW_ALL, (int)BUTTON_SHOW_ALL ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_HIDE_ALL, (int)BUTTON_HIDE_ALL ) ); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_SOLO, (int)BUTTON_SOLO)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_SHOW_ALL, (int)BUTTON_SHOW_ALL)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_HIDE_ALL, (int)BUTTON_HIDE_ALL)); _popupMenu.append(*Gtk::manage(new Gtk::SeparatorMenuItem())); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_LOCK_OTHERS, (int)BUTTON_LOCK_OTHERS ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_LOCK_ALL, (int)BUTTON_LOCK_ALL ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_UNLOCK_ALL, (int)BUTTON_UNLOCK_ALL ) ); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_LOCK_OTHERS, (int)BUTTON_LOCK_OTHERS)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_LOCK_ALL, (int)BUTTON_LOCK_ALL)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_UNLOCK_ALL, (int)BUTTON_UNLOCK_ALL)); _popupMenu.append(*Gtk::manage(new Gtk::SeparatorMenuItem())); - _watchingNonTop.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_RAISE, (int)BUTTON_UP ) ); - _watchingNonBottom.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_LOWER, (int)BUTTON_DOWN ) ); + _watchingNonTop.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_RAISE, (int)BUTTON_UP)); + _watchingNonBottom.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_LOWER, (int)BUTTON_DOWN)); _popupMenu.append(*Gtk::manage(new Gtk::SeparatorMenuItem())); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_DUPLICATE, (int)BUTTON_DUPLICATE ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_DELETE, (int)BUTTON_DELETE ) ); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_DUPLICATE, (int)BUTTON_DUPLICATE)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_DELETE, (int)BUTTON_DELETE)); _popupMenu.show_all_children(); // Install CSS to shift icons into the space reserved for toggles (i.e. check and radio items). - _popupMenu.signal_map().connect(sigc::mem_fun(static_cast<ContextMenu*>(&_popupMenu), &ContextMenu::ShiftIcons)); + _popupMenu.signal_map().connect( + sigc::mem_fun(static_cast<ContextMenu *>(&_popupMenu), &ContextMenu::ShiftIcons)); } // ------------------------------------------------------- - - - for (auto & it : _watching) { - it->set_sensitive( false ); + for (auto &it : _watching) { + it->set_sensitive(false); } - for (auto & it : _watchingNonTop) { - it->set_sensitive( false ); + for (auto &it : _watchingNonTop) { + it->set_sensitive(false); } - for (auto & it : _watchingNonBottom) { - it->set_sensitive( false ); + for (auto &it : _watchingNonBottom) { + it->set_sensitive(false); } - setDesktop( targetDesktop ); + setDesktop(targetDesktop); show_all_children(); @@ -928,8 +866,7 @@ LayersPanel::~LayersPanel() _compositeSettings.setSubject(nullptr); - if ( _model ) - { + if (_model) { delete _model; _model = nullptr; } @@ -939,19 +876,17 @@ LayersPanel::~LayersPanel() _pending = nullptr; } - if ( _toggleEvent ) - { - gdk_event_free( _toggleEvent ); + if (_toggleEvent) { + gdk_event_free(_toggleEvent); _toggleEvent = nullptr; } } - -void LayersPanel::setDesktop( SPDesktop* desktop ) +void LayersPanel::setDesktop(SPDesktop *desktop) { Panel::setDesktop(desktop); - if ( desktop != _desktop ) { + if (desktop != _desktop) { _layerChangedConnection.disconnect(); _layerUpdatedConnection.disconnect(); _changedConnection.disconnect(); @@ -959,14 +894,16 @@ void LayersPanel::setDesktop( SPDesktop* desktop ) _desktop = desktop; _subject.setDesktop(desktop); - if ( _desktop ) { - //setLabel( _desktop->doc()->name ); + if (_desktop) { + // setLabel( _desktop->doc()->name ); LayerManager *mgr = _desktop->layer_manager; - if ( mgr ) { - _layerChangedConnection = mgr->connectCurrentLayerChanged( sigc::mem_fun(*this, &LayersPanel::_selectLayer) ); - _layerUpdatedConnection = mgr->connectLayerDetailsChanged( sigc::mem_fun(*this, &LayersPanel::_updateLayer) ); - _changedConnection = mgr->connectChanged( sigc::mem_fun(*this, &LayersPanel::_layersChanged) ); + if (mgr) { + _layerChangedConnection = + mgr->connectCurrentLayerChanged(sigc::mem_fun(*this, &LayersPanel::_selectLayer)); + _layerUpdatedConnection = + mgr->connectLayerDetailsChanged(sigc::mem_fun(*this, &LayersPanel::_updateLayer)); + _changedConnection = mgr->connectChanged(sigc::mem_fun(*this, &LayersPanel::_layersChanged)); } _layersChanged(); @@ -974,12 +911,9 @@ void LayersPanel::setDesktop( SPDesktop* desktop ) } } - - -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape - +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/layers.h b/src/ui/dialog/layers.h index 9c4c8c99102c9586b40108999b6e9964328d4e01..5e1d3ba4ec27dfe2921ae73f076a6ce392fcbfaa 100644 --- a/src/ui/dialog/layers.h +++ b/src/ui/dialog/layers.h @@ -14,12 +14,13 @@ #define SEEN_LAYERS_PANEL_H #include <gtkmm/box.h> -#include <gtkmm/treeview.h> -#include <gtkmm/treestore.h> #include <gtkmm/scrolledwindow.h> -#include "ui/widget/spinbutton.h" -#include "ui/widget/panel.h" +#include <gtkmm/treestore.h> +#include <gtkmm/treeview.h> + #include "ui/widget/object-composite-settings.h" +#include "ui/widget/panel.h" +#include "ui/widget/spinbutton.h" #include "ui/widget/style-subject.h" class SPObject; @@ -31,7 +32,6 @@ class LayerManager; namespace UI { namespace Dialog { - /** * A panel that displays layers. */ @@ -41,51 +41,52 @@ public: LayersPanel(); ~LayersPanel() override; - static LayersPanel& getInstance(); + static LayersPanel &getInstance(); - void setDesktop( SPDesktop* desktop ) override; + void setDesktop(SPDesktop *desktop) override; private: class ModelColumns; class InternalUIBounce; - LayersPanel(LayersPanel const &) = delete; // no copy + LayersPanel(LayersPanel const &) = delete; // no copy LayersPanel &operator=(LayersPanel const &) = delete; // no assign - void _styleButton( Gtk::Button& btn, SPDesktop *desktop, unsigned int code, char const* iconName, char const* fallback ); - void _fireAction( unsigned int code ); - Gtk::MenuItem& _addPopupItem( SPDesktop *desktop, unsigned int code, int id ); + void _styleButton(Gtk::Button &btn, SPDesktop *desktop, unsigned int code, char const *iconName, + char const *fallback); + void _fireAction(unsigned int code); + Gtk::MenuItem &_addPopupItem(SPDesktop *desktop, unsigned int code, int id); - void _preToggle( GdkEvent const *event ); - void _toggled( Glib::ustring const& str, int targetCol ); + void _preToggle(GdkEvent const *event); + void _toggled(Glib::ustring const &str, int targetCol); 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); + 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 _renameLayer(Gtk::TreeModel::Row row, const Glib::ustring &name); void _pushTreeSelectionToCurrent(); void _checkTreeSelection(); - void _takeAction( int val ); + void _takeAction(int val); bool _executeAction(); - bool _rowSelectFunction( Glib::RefPtr<Gtk::TreeModel> const & model, Gtk::TreeModel::Path const & path, bool b ); + bool _rowSelectFunction(Glib::RefPtr<Gtk::TreeModel> const &model, Gtk::TreeModel::Path const &path, bool b); void _updateLayer(SPObject *layer); - bool _checkForUpdated(const Gtk::TreePath &path, const Gtk::TreeIter& iter, SPObject* layer); + bool _checkForUpdated(const Gtk::TreePath &path, const Gtk::TreeIter &iter, SPObject *layer); void _selectLayer(SPObject *layer); - bool _checkForSelected(const Gtk::TreePath& path, const Gtk::TreeIter& iter, SPObject* layer); + bool _checkForSelected(const Gtk::TreePath &path, const Gtk::TreeIter &iter, SPObject *layer); void _layersChanged(); - void _addLayer( SPDocument* doc, SPObject* layer, Gtk::TreeModel::Row* parentRow, SPObject* target, int level ); + void _addLayer(SPDocument *doc, SPObject *layer, Gtk::TreeModel::Row *parentRow, SPObject *target, int level); - SPObject* _selectedLayer(); + SPObject *_selectedLayer(); // Hooked to the layer manager: sigc::connection _layerChangedConnection; @@ -98,19 +99,19 @@ private: sigc::connection _selectedConnection; int _maxNestDepth; - SPDesktop* _desktop; - ModelColumns* _model; - InternalUIBounce* _pending; + SPDesktop *_desktop; + ModelColumns *_model; + InternalUIBounce *_pending; gboolean _dnd_into; - SPItem* _dnd_source; - SPItem* _dnd_target; - GdkEvent* _toggleEvent; + SPItem *_dnd_source; + SPItem *_dnd_target; + GdkEvent *_toggleEvent; bool _show_contextmenu_icons; Glib::RefPtr<Gtk::TreeStore> _store; - std::vector<Gtk::Widget*> _watching; - std::vector<Gtk::Widget*> _watchingNonTop; - std::vector<Gtk::Widget*> _watchingNonBottom; + std::vector<Gtk::Widget *> _watching; + std::vector<Gtk::Widget *> _watchingNonTop; + std::vector<Gtk::Widget *> _watchingNonBottom; Gtk::TreeView _tree; Gtk::CellRendererText *_text_renderer; @@ -127,13 +128,9 @@ private: UI::Widget::ObjectCompositeSettings _compositeSettings; }; - - -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape - - +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif // SEEN_LAYERS_PANEL_H diff --git a/src/ui/dialog/livepatheffect-add.cpp b/src/ui/dialog/livepatheffect-add.cpp index f6abff5e679ac2846a51fc234596645c94d2884b..c896d5121261f6862e827ebec98833c0fc635abc 100644 --- a/src/ui/dialog/livepatheffect-add.cpp +++ b/src/ui/dialog/livepatheffect-add.cpp @@ -10,6 +10,10 @@ */ #include "livepatheffect-add.h" + +#include <cmath> +#include <glibmm/i18n.h> + #include "desktop.h" #include "dialog.h" #include "io/resource.h" @@ -20,8 +24,6 @@ #include "object/sp-path.h" #include "object/sp-shape.h" #include "preferences.h" -#include <cmath> -#include <glibmm/i18n.h> namespace Inkscape { namespace UI { @@ -108,7 +110,7 @@ LivePathEffectAdd::LivePathEffectAdd() _LPEDialogSelector->add_events(Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK | Gdk::ENTER_NOTIFY_MASK | Gdk::LEAVE_NOTIFY_MASK | Gdk::KEY_PRESS_MASK); _LPESelectorFlowBox->signal_set_focus_child().connect(sigc::mem_fun(*this, &LivePathEffectAdd::on_focus)); - + gladefile = get_filename_string(Inkscape::IO::Resource::UIS, "dialog-livepatheffect-effect.glade"); for (int i = 0; i < static_cast<int>(converter._length); ++i) { Glib::RefPtr<Gtk::Builder> builder_effect; @@ -328,8 +330,8 @@ void LivePathEffectAdd::on_focus(Gtk::Widget *widget) } } - child->show_all_children(); - _LPESelectorFlowBox->select_child(*child); + child->show_all_children(); + _LPESelectorFlowBox->select_child(*child); } } @@ -437,7 +439,7 @@ bool LivePathEffectAdd::apply(GdkEventButton *evt, Glib::RefPtr<Gtk::Builder> bu _to_add = to_add; Gtk::EventBox *LPESelectorEffect; builder_effect->get_widget("LPESelectorEffect", LPESelectorEffect); - Gtk::FlowBoxChild *flowboxchild = dynamic_cast<Gtk::FlowBoxChild *>(LPESelectorEffect->get_parent()); + Gtk::FlowBoxChild *flowboxchild = dynamic_cast<Gtk::FlowBoxChild *>(LPESelectorEffect->get_parent()); _LPESelectorFlowBox->select_child(*flowboxchild); if (flowboxchild && flowboxchild->get_style_context()->has_class("lpedisabled")) { return true; @@ -456,7 +458,7 @@ bool LivePathEffectAdd::on_press_enter(GdkEventKey *key, Glib::RefPtr<Gtk::Build _to_add = to_add; Gtk::EventBox *LPESelectorEffect; builder_effect->get_widget("LPESelectorEffect", LPESelectorEffect); - Gtk::FlowBoxChild *flowboxchild = dynamic_cast<Gtk::FlowBoxChild *>(LPESelectorEffect->get_parent()); + Gtk::FlowBoxChild *flowboxchild = dynamic_cast<Gtk::FlowBoxChild *>(LPESelectorEffect->get_parent()); if (flowboxchild && flowboxchild->get_style_context()->has_class("lpedisabled")) { return true; } @@ -480,8 +482,6 @@ bool LivePathEffectAdd::expand(GdkEventButton *evt, Glib::RefPtr<Gtk::Builder> b return true; } - - bool LivePathEffectAdd::on_filter(Gtk::FlowBoxChild *child) { std::vector<Glib::ustring> classes = child->get_style_context()->list_classes(); @@ -502,7 +502,7 @@ bool LivePathEffectAdd::on_filter(Gtk::FlowBoxChild *child) } else if (_item_type == "path" && !converter.get_on_path(data->id)) { disable = true; } - + if (!_has_clip && data->id == Inkscape::LivePathEffect::POWERCLIP) { disable = true; } @@ -569,7 +569,8 @@ void LivePathEffectAdd::reload_effect_list() _LPESelectorFlowBox->invalidate_filter(); if (_showfavs) { if (_visiblelpe == 0) { - _LPEInfo->set_text(_("You don't have any favorites yet. Click on the favorites star again to see all LPEs.")); + _LPEInfo->set_text( + _("You don't have any favorites yet. Click on the favorites star again to see all LPEs.")); _LPEInfo->set_visible(true); _LPEInfo->get_style_context()->add_class("lpeinfowarn"); } else { @@ -863,8 +864,10 @@ int LivePathEffectAdd::on_sort(Gtk::FlowBoxChild *child1, Gtk::FlowBoxChild *chi return 1; } - -void LivePathEffectAdd::onClose() { _LPEDialogSelector->hide(); } +void LivePathEffectAdd::onClose() +{ + _LPEDialogSelector->hide(); +} void LivePathEffectAdd::onKeyEvent(GdkEventKey *evt) { @@ -908,7 +911,7 @@ void LivePathEffectAdd::show(SPDesktop *desktop) dial._LPEDialogSelector->show(); int searchlen = dial._LPEFilter->get_text().length(); if (searchlen > 0) { - dial._LPEFilter->select_region (0, searchlen); + dial._LPEFilter->select_region(0, searchlen); dial._LPESelectorFlowBox->unselect_all(); } else if (dial._lasteffect) { dial._lasteffect->grab_focus(); diff --git a/src/ui/dialog/livepatheffect-add.h b/src/ui/dialog/livepatheffect-add.h index bd8dca4c066a543df9ba9cbc673482da37ee57bd..0ed3506e9686cc496f3bc41fe82858aa483dee92 100644 --- a/src/ui/dialog/livepatheffect-add.h +++ b/src/ui/dialog/livepatheffect-add.h @@ -12,7 +12,6 @@ #ifndef INKSCAPE_DIALOG_LIVEPATHEFFECT_ADD_H #define INKSCAPE_DIALOG_LIVEPATHEFFECT_ADD_H -#include "live_effects/effect-enum.h" #include <gtkmm/adjustment.h> #include <gtkmm/box.h> #include <gtkmm/builder.h> @@ -31,18 +30,21 @@ #include <gtkmm/switch.h> #include <gtkmm/viewport.h> +#include "live_effects/effect-enum.h" + class SPDesktop; namespace Inkscape { namespace UI { namespace Dialog { - + /** * A dialog widget to list the live path effects that can be added * */ -class LivePathEffectAdd { - public: +class LivePathEffectAdd +{ +public: LivePathEffectAdd(); ~LivePathEffectAdd() = default; ; @@ -58,7 +60,7 @@ class LivePathEffectAdd { static const LivePathEffect::EnumEffectData<LivePathEffect::EffectType> *getActiveData(); - protected: +protected: /** * Close button was clicked */ @@ -87,48 +89,49 @@ class LivePathEffectAdd { /** * Tree was clicked */ - void onButtonEvent(GdkEventButton* evt); + void onButtonEvent(GdkEventButton *evt); /** * Key event */ - void onKeyEvent(GdkEventKey* evt); + void onKeyEvent(GdkEventKey *evt); + private: - Gtk::Button _add_button; - Gtk::Button _close_button; - Gtk::Dialog *_LPEDialogSelector; - Glib::RefPtr<Gtk::Builder> _builder; - Gtk::FlowBox *_LPESelectorFlowBox; - Gtk::Popover *_LPESelectorEffectInfoPop; - Gtk::EventBox *_LPESelectorEffectEventFavShow; - Gtk::EventBox *_LPESelectorEffectInfoEventBox; - Gtk::RadioButton *_LPESelectorEffectRadioList; - Gtk::RadioButton *_LPESelectorEffectRadioPackLess; - Gtk::RadioButton *_LPESelectorEffectRadioPackMore; - Gtk::Switch *_LPEExperimental; - Gtk::SearchEntry *_LPEFilter; - Gtk::ScrolledWindow *_LPEScrolled; - Gtk::Label *_LPEInfo; - Gtk::Box *_LPESelector; - guint _visiblelpe; - Glib::ustring _item_type; - bool _has_clip; - bool _has_mask; - Gtk::FlowBoxChild *_lasteffect; - const LivePathEffect::EnumEffectData<LivePathEffect::EffectType> *_to_add; - bool _showfavs; - bool _applied; - class Effect; - const LivePathEffect::EnumEffectDataConverter<LivePathEffect::EffectType> &converter; - static LivePathEffectAdd &instance() - { - static LivePathEffectAdd instance_; - return instance_; - } - LivePathEffectAdd(LivePathEffectAdd const &) = delete; // no copy - LivePathEffectAdd &operator=(LivePathEffectAdd const &) = delete; // no assign + Gtk::Button _add_button; + Gtk::Button _close_button; + Gtk::Dialog *_LPEDialogSelector; + Glib::RefPtr<Gtk::Builder> _builder; + Gtk::FlowBox *_LPESelectorFlowBox; + Gtk::Popover *_LPESelectorEffectInfoPop; + Gtk::EventBox *_LPESelectorEffectEventFavShow; + Gtk::EventBox *_LPESelectorEffectInfoEventBox; + Gtk::RadioButton *_LPESelectorEffectRadioList; + Gtk::RadioButton *_LPESelectorEffectRadioPackLess; + Gtk::RadioButton *_LPESelectorEffectRadioPackMore; + Gtk::Switch *_LPEExperimental; + Gtk::SearchEntry *_LPEFilter; + Gtk::ScrolledWindow *_LPEScrolled; + Gtk::Label *_LPEInfo; + Gtk::Box *_LPESelector; + guint _visiblelpe; + Glib::ustring _item_type; + bool _has_clip; + bool _has_mask; + Gtk::FlowBoxChild *_lasteffect; + const LivePathEffect::EnumEffectData<LivePathEffect::EffectType> *_to_add; + bool _showfavs; + bool _applied; + class Effect; + const LivePathEffect::EnumEffectDataConverter<LivePathEffect::EffectType> &converter; + static LivePathEffectAdd &instance() + { + static LivePathEffectAdd instance_; + return instance_; + } + LivePathEffectAdd(LivePathEffectAdd const &) = delete; // no copy + LivePathEffectAdd &operator=(LivePathEffectAdd const &) = delete; // no assign }; - + } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/livepatheffect-editor.cpp b/src/ui/dialog/livepatheffect-editor.cpp index 19598db054468d863756fb28c08622bc87d99079..88958a330dfbf1a690ede04dfa68745e1588530f 100644 --- a/src/ui/dialog/livepatheffect-editor.cpp +++ b/src/ui/dialog/livepatheffect-editor.cpp @@ -20,63 +20,55 @@ #include "desktop.h" #include "document-undo.h" #include "document.h" -#include "inkscape.h" -#include "livepatheffect-add.h" -#include "path-chemistry.h" -#include "selection-chemistry.h" -#include "verbs.h" - #include "helper/action.h" -#include "ui/icon-loader.h" - +#include "inkscape.h" #include "live_effects/effect.h" #include "live_effects/lpeobject-reference.h" #include "live_effects/lpeobject.h" - +#include "livepatheffect-add.h" #include "object/sp-item-group.h" #include "object/sp-path.h" -#include "object/sp-use.h" #include "object/sp-text.h" - +#include "object/sp-use.h" +#include "path-chemistry.h" +#include "selection-chemistry.h" +#include "ui/icon-loader.h" #include "ui/icon-names.h" #include "ui/tools/node-tool.h" #include "ui/widget/imagetoggler.h" +#include "verbs.h" namespace Inkscape { namespace UI { namespace Dialog { - /*#################### * Callback functions */ - -void lpeeditor_selection_changed (Inkscape::Selection * selection, gpointer data) +void lpeeditor_selection_changed(Inkscape::Selection *selection, gpointer data) { LivePathEffectEditor *lpeeditor = static_cast<LivePathEffectEditor *>(data); lpeeditor->lpe_list_locked = false; lpeeditor->onSelectionChanged(selection); - lpeeditor->_on_button_release(nullptr); //to force update widgets + lpeeditor->_on_button_release(nullptr); // to force update widgets } -void lpeeditor_selection_modified (Inkscape::Selection * selection, guint /*flags*/, gpointer data) +void lpeeditor_selection_modified(Inkscape::Selection *selection, guint /*flags*/, gpointer data) { - LivePathEffectEditor *lpeeditor = static_cast<LivePathEffectEditor *>(data); lpeeditor->lpe_list_locked = false; lpeeditor->onSelectionChanged(selection); } -static void lpe_style_button(Gtk::Button& btn, char const* iconName) +static void lpe_style_button(Gtk::Button &btn, char const *iconName) { GtkWidget *child = sp_get_icon_image(iconName, GTK_ICON_SIZE_SMALL_TOOLBAR); - gtk_widget_show( child ); + gtk_widget_show(child); btn.add(*Gtk::manage(Glib::wrap(child))); btn.set_relief(Gtk::RELIEF_NONE); } - /* * LivePathEffectEditor * @@ -85,23 +77,23 @@ static void lpe_style_button(Gtk::Button& btn, char const* iconName) */ LivePathEffectEditor::LivePathEffectEditor() - : UI::Widget::Panel("/dialogs/livepatheffect", SP_VERB_DIALOG_LIVE_PATH_EFFECT), - lpe_list_locked(false), - effectwidget(nullptr), - status_label("", Gtk::ALIGN_CENTER), - effectcontrol_frame(""), - button_add(), - button_remove(), - button_up(), - button_down(), - current_desktop(nullptr), - current_lpeitem(nullptr), - current_lperef(nullptr) + : UI::Widget::Panel("/dialogs/livepatheffect", SP_VERB_DIALOG_LIVE_PATH_EFFECT) + , lpe_list_locked(false) + , effectwidget(nullptr) + , status_label("", Gtk::ALIGN_CENTER) + , effectcontrol_frame("") + , button_add() + , button_remove() + , button_up() + , button_down() + , current_desktop(nullptr) + , current_lpeitem(nullptr) + , current_lperef(nullptr) { Gtk::Box *contents = _getContents(); contents->set_spacing(4); - //Add the TreeView, inside a ScrolledWindow, with the button underneath: + // Add the TreeView, inside a ScrolledWindow, with the button underneath: scrolled_window.add(effectlist_view); scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); scrolled_window.set_shadow_type(Gtk::SHADOW_IN); @@ -113,7 +105,8 @@ LivePathEffectEditor::LivePathEffectEditor() effectlist_vbox.pack_start(scrolled_window, Gtk::PACK_EXPAND_WIDGET); effectlist_vbox.pack_end(toolbar_hbox, Gtk::PACK_SHRINK); effectcontrol_eventbox.add_events(Gdk::BUTTON_RELEASE_MASK); - effectcontrol_eventbox.signal_button_release_event().connect(sigc::mem_fun(*this, &LivePathEffectEditor::_on_button_release) ); + effectcontrol_eventbox.signal_button_release_event().connect( + sigc::mem_fun(*this, &LivePathEffectEditor::_on_button_release)); effectcontrol_eventbox.add(effectcontrol_vbox); effectcontrol_frame.add(effectcontrol_eventbox); @@ -134,35 +127,36 @@ LivePathEffectEditor::LivePathEffectEditor() button_down.set_relief(Gtk::RELIEF_NONE); // Add toolbar items to toolbar - toolbar_hbox.set_layout (Gtk::BUTTONBOX_END); - toolbar_hbox.add( button_add ); - toolbar_hbox.set_child_secondary( button_add , true); - toolbar_hbox.add( button_remove ); - toolbar_hbox.set_child_secondary( button_remove , true); - toolbar_hbox.add( button_up ); - toolbar_hbox.add( button_down ); - - //Create the Tree model: + toolbar_hbox.set_layout(Gtk::BUTTONBOX_END); + toolbar_hbox.add(button_add); + toolbar_hbox.set_child_secondary(button_add, true); + toolbar_hbox.add(button_remove); + toolbar_hbox.set_child_secondary(button_remove, true); + toolbar_hbox.add(button_up); + toolbar_hbox.add(button_down); + + // Create the Tree model: effectlist_store = Gtk::ListStore::create(columns); effectlist_view.set_model(effectlist_store); effectlist_view.set_headers_visible(false); // Handle tree selections effectlist_selection = effectlist_view.get_selection(); - effectlist_selection->signal_changed().connect( sigc::mem_fun(*this, &LivePathEffectEditor::on_effect_selection_changed) ); + effectlist_selection->signal_changed().connect( + sigc::mem_fun(*this, &LivePathEffectEditor::on_effect_selection_changed)); - //Add the visibility icon column: - Inkscape::UI::Widget::ImageToggler *eyeRenderer = Gtk::manage( new Inkscape::UI::Widget::ImageToggler( - INKSCAPE_ICON("object-visible"), INKSCAPE_ICON("object-hidden")) ); + // Add the visibility icon column: + Inkscape::UI::Widget::ImageToggler *eyeRenderer = Gtk::manage( + new Inkscape::UI::Widget::ImageToggler(INKSCAPE_ICON("object-visible"), INKSCAPE_ICON("object-hidden"))); int visibleColNum = effectlist_view.append_column("is_visible", *eyeRenderer) - 1; - eyeRenderer->signal_toggled().connect( sigc::mem_fun(*this, &LivePathEffectEditor::on_visibility_toggled) ); + eyeRenderer->signal_toggled().connect(sigc::mem_fun(*this, &LivePathEffectEditor::on_visibility_toggled)); eyeRenderer->property_activatable() = true; - Gtk::TreeViewColumn* col = effectlist_view.get_column(visibleColNum); - if ( col ) { - col->add_attribute( eyeRenderer->property_active(), columns.col_visible ); + Gtk::TreeViewColumn *col = effectlist_view.get_column(visibleColNum); + if (col) { + col->add_attribute(eyeRenderer->property_active(), columns.col_visible); } - //Add the effect name column: + // Add the effect name column: effectlist_view.append_column("Effect", columns.col_name); contents->pack_start(effectlist_vbox, true, true); @@ -194,16 +188,17 @@ LivePathEffectEditor::~LivePathEffectEditor() } } -bool LivePathEffectEditor::_on_button_release(GdkEventButton* button_event) { +bool LivePathEffectEditor::_on_button_release(GdkEventButton *button_event) +{ Glib::RefPtr<Gtk::TreeSelection> sel = effectlist_view.get_selection(); - if (sel->count_selected_rows () == 0) { + if (sel->count_selected_rows() == 0) { return true; } Gtk::TreeModel::iterator it = sel->get_selected(); - LivePathEffect::LPEObjectReference * lperef = (*it)[columns.lperef]; + LivePathEffect::LPEObjectReference *lperef = (*it)[columns.lperef]; if (lperef && current_lpeitem && current_lperef != lperef) { if (lperef->getObject()) { - LivePathEffect::Effect * effect = lperef->lpeobject->get_lpe(); + LivePathEffect::Effect *effect = lperef->lpeobject->get_lpe(); if (effect) { effect->refresh_widgets = true; showParams(*effect); @@ -213,8 +208,7 @@ bool LivePathEffectEditor::_on_button_release(GdkEventButton* button_event) { return true; } -void -LivePathEffectEditor::showParams(LivePathEffect::Effect& effect) +void LivePathEffectEditor::showParams(LivePathEffect::Effect &effect) { if (effectwidget && !effect.refresh_widgets) { return; @@ -227,7 +221,7 @@ LivePathEffectEditor::showParams(LivePathEffect::Effect& effect) effectwidget = effect.newWidget(); effectcontrol_frame.set_label(effect.getName()); effectcontrol_vbox.pack_start(*effectwidget, true, true); - + button_remove.show(); status_label.hide(); effectcontrol_frame.show(); @@ -236,19 +230,16 @@ LivePathEffectEditor::showParams(LivePathEffect::Effect& effect) effect.refresh_widgets = false; } -void -LivePathEffectEditor::selectInList(LivePathEffect::Effect* effect) +void LivePathEffectEditor::selectInList(LivePathEffect::Effect *effect) { Gtk::TreeNodeChildren chi = effectlist_view.get_model()->children(); - for (Gtk::TreeIter ci = chi.begin() ; ci != chi.end(); ci++) { + for (Gtk::TreeIter ci = chi.begin(); ci != chi.end(); ci++) { if (ci->get_value(columns.lperef)->lpeobject->get_lpe() == effect && effectlist_view.get_selection()) effectlist_view.get_selection()->select(ci); } } - -void -LivePathEffectEditor::showText(Glib::ustring const &str) +void LivePathEffectEditor::showText(Glib::ustring const &str) { if (effectwidget) { effectcontrol_vbox.remove(*effectwidget); @@ -264,10 +255,9 @@ LivePathEffectEditor::showText(Glib::ustring const &str) // fixme: do resizing of dialog ? } -void -LivePathEffectEditor::set_sensitize_all(bool sensitive) +void LivePathEffectEditor::set_sensitize_all(bool sensitive) { - //combo_effecttype.set_sensitive(sensitive); + // combo_effecttype.set_sensitive(sensitive); button_add.set_sensitive(sensitive); button_remove.set_sensitive(sensitive); effectlist_view.set_sensitive(sensitive); @@ -275,8 +265,7 @@ LivePathEffectEditor::set_sensitize_all(bool sensitive) button_down.set_sensitive(sensitive); } -void -LivePathEffectEditor::onSelectionChanged(Inkscape::Selection *sel) +void LivePathEffectEditor::onSelectionChanged(Inkscape::Selection *sel) { if (lpe_list_locked) { // this was triggered by selecting a row in the list, so skip reloading @@ -286,15 +275,15 @@ LivePathEffectEditor::onSelectionChanged(Inkscape::Selection *sel) current_lpeitem = nullptr; effectlist_store->clear(); - if ( sel && !sel->isEmpty() ) { + if (sel && !sel->isEmpty()) { SPItem *item = sel->singleItem(); - if ( item ) { + if (item) { SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(item); - if ( lpeitem ) { + if (lpeitem) { effect_list_reload(lpeitem); current_lpeitem = lpeitem; set_sensitize_all(true); - if ( lpeitem->hasPathEffect() ) { + if (lpeitem->hasPathEffect()) { Inkscape::LivePathEffect::Effect *lpe = lpeitem->getCurrentLPE(); if (lpe) { showParams(*lpe); @@ -311,13 +300,12 @@ LivePathEffectEditor::onSelectionChanged(Inkscape::Selection *sel) } } else { SPUse *use = dynamic_cast<SPUse *>(item); - if ( use ) { + if (use) { // test whether linked object is supported by the CLONE_ORIGINAL LPE SPItem *orig = use->get_original(); - if ( dynamic_cast<SPShape *>(orig) || - dynamic_cast<SPText *>(orig) ) - { - // Note that an SP_USE cannot have an LPE applied, so we only need to worry about the "add effect" case. + if (dynamic_cast<SPShape *>(orig) || dynamic_cast<SPText *>(orig)) { + // Note that an SP_USE cannot have an LPE applied, so we only need to worry about the "add + // effect" case. set_sensitize_all(true); showText(_("Click add button to convert clone")); button_remove.set_sensitive(false); @@ -345,16 +333,14 @@ LivePathEffectEditor::onSelectionChanged(Inkscape::Selection *sel) /* * First clears the effectlist_store, then appends all effects from the effectlist. */ -void -LivePathEffectEditor::effect_list_reload(SPLPEItem *lpeitem) +void LivePathEffectEditor::effect_list_reload(SPLPEItem *lpeitem) { effectlist_store->clear(); PathEffectList effectlist = lpeitem->getEffectList(); PathEffectList::iterator it; - for( it = effectlist.begin() ; it!=effectlist.end(); ++it) - { - if ( !(*it)->lpeobject ) { + for (it = effectlist.begin(); it != effectlist.end(); ++it) { + if (!(*it)->lpeobject) { continue; } @@ -372,13 +358,11 @@ LivePathEffectEditor::effect_list_reload(SPLPEItem *lpeitem) } } - -void -LivePathEffectEditor::setDesktop(SPDesktop *desktop) +void LivePathEffectEditor::setDesktop(SPDesktop *desktop) { Panel::setDesktop(desktop); - if ( desktop == current_desktop ) { + if (desktop == current_desktop) { return; } @@ -391,10 +375,10 @@ LivePathEffectEditor::setDesktop(SPDesktop *desktop) current_desktop = desktop; if (desktop) { Inkscape::Selection *selection = desktop->getSelection(); - selection_changed_connection = selection->connectChanged( - sigc::bind (sigc::ptr_fun(&lpeeditor_selection_changed), this ) ); - selection_modified_connection = selection->connectModified( - sigc::bind (sigc::ptr_fun(&lpeeditor_selection_modified), this ) ); + selection_changed_connection = + selection->connectChanged(sigc::bind(sigc::ptr_fun(&lpeeditor_selection_changed), this)); + selection_modified_connection = + selection->connectModified(sigc::bind(sigc::ptr_fun(&lpeeditor_selection_modified), this)); onSelectionChanged(selection); } else { @@ -407,18 +391,17 @@ LivePathEffectEditor::setDesktop(SPDesktop *desktop) ########################################################################*/ // TODO: factor out the effect applying code which can be called from anywhere. (selection-chemistry.cpp also needs it) -void -LivePathEffectEditor::onAdd() +void LivePathEffectEditor::onAdd() { Inkscape::Selection *sel = _getSelection(); - if ( sel && !sel->isEmpty() ) { + if (sel && !sel->isEmpty()) { SPItem *item = sel->singleItem(); if (item) { - if ( dynamic_cast<SPLPEItem *>(item) ) { + if (dynamic_cast<SPLPEItem *>(item)) { // show effectlist dialog using Inkscape::UI::Dialog::LivePathEffectAdd; LivePathEffectAdd::show(current_desktop); - if ( !LivePathEffectAdd::isApplied()) { + if (!LivePathEffectAdd::isApplied()) { return; } @@ -433,22 +416,19 @@ LivePathEffectEditor::onAdd() LivePathEffect::Effect::createAndApply(data->key.c_str(), doc, item); - DocumentUndo::done(doc, SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Create and apply path effect")); + DocumentUndo::done(doc, SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Create and apply path effect")); lpe_list_locked = false; onSelectionChanged(sel); } else { SPUse *use = dynamic_cast<SPUse *>(item); - if ( use ) { + if (use) { // item is a clone. do not show effectlist dialog. // 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 = use->get_original(); - if ( dynamic_cast<SPShape *>(orig) || - dynamic_cast<SPText *>(orig) ) - { + if (dynamic_cast<SPShape *>(orig) || dynamic_cast<SPText *>(orig)) { // select original sel->set(orig); @@ -458,11 +438,12 @@ LivePathEffectEditor::onAdd() item->deleteObject(false); item = nullptr; - // run sp_selection_clone_original_path_lpe + // run sp_selection_clone_original_path_lpe sel->cloneOriginalPathLPE(true); SPItem *new_item = sel->singleItem(); - // Check that the cloning was successful. We don't want to change the ID of the original referenced path! + // Check that the cloning was successful. We don't want to change the ID of the original + // referenced path! if (new_item && (new_item != orig)) { new_item->setAttribute("id", id); new_item->setAttribute("transform", transform); @@ -485,38 +466,36 @@ LivePathEffectEditor::onAdd() } } -void -LivePathEffectEditor::onRemove() +void LivePathEffectEditor::onRemove() { Inkscape::Selection *sel = _getSelection(); - if ( sel && !sel->isEmpty() ) { + if (sel && !sel->isEmpty()) { SPItem *item = sel->singleItem(); - SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(item); - if ( lpeitem ) { + SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(item); + if (lpeitem) { sp_lpe_item_update_patheffect(lpeitem, false, false); lpeitem->removeCurrentPathEffect(false); current_lperef = nullptr; - DocumentUndo::done( current_desktop->getDocument(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Remove path effect") ); + DocumentUndo::done(current_desktop->getDocument(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, + _("Remove path effect")); lpe_list_locked = false; onSelectionChanged(sel); } } - } void LivePathEffectEditor::onUp() { Inkscape::Selection *sel = _getSelection(); - if ( sel && !sel->isEmpty() ) { + if (sel && !sel->isEmpty()) { SPItem *item = sel->singleItem(); SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(item); - if ( lpeitem ) { + if (lpeitem) { Inkscape::LivePathEffect::Effect *lpe = lpeitem->getCurrentLPE(); lpeitem->upCurrentPathEffect(); - DocumentUndo::done( current_desktop->getDocument(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Move path effect up") ); - + DocumentUndo::done(current_desktop->getDocument(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, + _("Move path effect up")); + effect_list_reload(lpeitem); if (lpe) { showParams(*lpe); @@ -530,15 +509,15 @@ void LivePathEffectEditor::onUp() void LivePathEffectEditor::onDown() { Inkscape::Selection *sel = _getSelection(); - if ( sel && !sel->isEmpty() ) { + if (sel && !sel->isEmpty()) { SPItem *item = sel->singleItem(); SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(item); - if ( lpeitem ) { + if (lpeitem) { Inkscape::LivePathEffect::Effect *lpe = lpeitem->getCurrentLPE(); lpeitem->downCurrentPathEffect(); - DocumentUndo::done( current_desktop->getDocument(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - _("Move path effect down") ); + DocumentUndo::done(current_desktop->getDocument(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, + _("Move path effect down")); effect_list_reload(lpeitem); if (lpe) { showParams(*lpe); @@ -552,32 +531,32 @@ void LivePathEffectEditor::onDown() void LivePathEffectEditor::on_effect_selection_changed() { Glib::RefPtr<Gtk::TreeSelection> sel = effectlist_view.get_selection(); - if (sel->count_selected_rows () == 0) { + if (sel->count_selected_rows() == 0) { button_remove.set_sensitive(false); return; } button_remove.set_sensitive(true); Gtk::TreeModel::iterator it = sel->get_selected(); - LivePathEffect::LPEObjectReference * lperef = (*it)[columns.lperef]; + LivePathEffect::LPEObjectReference *lperef = (*it)[columns.lperef]; if (lperef && current_lpeitem && current_lperef != lperef) { - //The last condition ignore Gtk::TreeModel may occasionally be changed emitted when nothing has happened + // The last condition ignore Gtk::TreeModel may occasionally be changed emitted when nothing has happened if (lperef->getObject()) { lpe_list_locked = true; // prevent reload of the list which would lose selection current_lpeitem->setCurrentPathEffect(lperef); current_lperef = lperef; - LivePathEffect::Effect * effect = lperef->lpeobject->get_lpe(); + LivePathEffect::Effect *effect = lperef->lpeobject->get_lpe(); if (effect) { effect->refresh_widgets = true; showParams(*effect); - //To reload knots and helper paths + // To reload knots and helper paths Inkscape::Selection *sel = _getSelection(); - if ( sel && !sel->isEmpty() ) { + if (sel && !sel->isEmpty()) { SPItem *item = sel->singleItem(); if (item) { sel->clear(); sel->add(item); - Inkscape::UI::Tools::sp_update_helperpath(current_desktop); + Inkscape::UI::Tools::sp_update_helperpath(current_desktop); } } } @@ -585,30 +564,29 @@ void LivePathEffectEditor::on_effect_selection_changed() } } -void LivePathEffectEditor::on_visibility_toggled( Glib::ustring const& str ) +void LivePathEffectEditor::on_visibility_toggled(Glib::ustring const &str) { - Gtk::TreeModel::Children::iterator iter = effectlist_view.get_model()->get_iter(str); Gtk::TreeModel::Row row = *iter; - LivePathEffect::LPEObjectReference * lpeobjref = row[columns.lperef]; + LivePathEffect::LPEObjectReference *lpeobjref = row[columns.lperef]; - if ( lpeobjref && lpeobjref->lpeobject->get_lpe() ) { + if (lpeobjref && lpeobjref->lpeobject->get_lpe()) { bool newValue = !row[columns.col_visible]; row[columns.col_visible] = newValue; - /* FIXME: this explicit writing to SVG is wrong. The lpe_item should have a method to disable/enable an effect within its stack. - * So one can call: lpe_item->setActive(lpeobjref->lpeobject); */ + /* FIXME: this explicit writing to SVG is wrong. The lpe_item should have a method to disable/enable an effect + * within its stack. So one can call: lpe_item->setActive(lpeobjref->lpeobject); */ lpeobjref->lpeobject->get_lpe()->getRepr()->setAttribute("is_visible", newValue ? "true" : "false"); Inkscape::Selection *sel = _getSelection(); - if ( sel && !sel->isEmpty() ) { + if (sel && !sel->isEmpty()) { SPItem *item = sel->singleItem(); - SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(item); - if ( lpeitem ) { + SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(item); + if (lpeitem) { lpeobjref->lpeobject->get_lpe()->doOnVisibilityToggled(lpeitem); } } - DocumentUndo::done( current_desktop->getDocument(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, - newValue ? _("Activate path effect") : _("Deactivate path effect")); + DocumentUndo::done(current_desktop->getDocument(), SP_VERB_DIALOG_LIVE_PATH_EFFECT, + newValue ? _("Activate path effect") : _("Deactivate path effect")); } } diff --git a/src/ui/dialog/livepatheffect-editor.h b/src/ui/dialog/livepatheffect-editor.h index 6af7aed72adf572f9dd71bd122e0134dc674d66c..b5ef11dd00f5abaee10f8cce6a49dc4442bd934b 100644 --- a/src/ui/dialog/livepatheffect-editor.h +++ b/src/ui/dialog/livepatheffect-editor.h @@ -12,20 +12,20 @@ #ifndef INKSCAPE_UI_DIALOG_LIVE_PATH_EFFECT_H #define INKSCAPE_UI_DIALOG_LIVE_PATH_EFFECT_H -#include "ui/widget/panel.h" - -#include <gtkmm/label.h> +#include <gtkmm/buttonbox.h> +#include <gtkmm/eventbox.h> #include <gtkmm/frame.h> -#include "ui/widget/combo-enums.h" -#include "ui/widget/frame.h" -#include "object/sp-item.h" -#include "live_effects/effect-enum.h" +#include <gtkmm/label.h> #include <gtkmm/liststore.h> -#include <gtkmm/eventbox.h> -#include <gtkmm/treeview.h> #include <gtkmm/scrolledwindow.h> #include <gtkmm/toolbar.h> -#include <gtkmm/buttonbox.h> +#include <gtkmm/treeview.h> + +#include "live_effects/effect-enum.h" +#include "object/sp-item.h" +#include "ui/widget/combo-enums.h" +#include "ui/widget/frame.h" +#include "ui/widget/panel.h" class SPDesktop; class SPLPEItem; @@ -33,14 +33,15 @@ class SPLPEItem; namespace Inkscape { namespace LivePathEffect { - class Effect; - class LPEObjectReference; -} +class Effect; +class LPEObjectReference; +} // namespace LivePathEffect namespace UI { namespace Dialog { -class LivePathEffectEditor : public UI::Widget::Panel { +class LivePathEffectEditor : public UI::Widget::Panel +{ public: LivePathEffectEditor(); ~LivePathEffectEditor() override; @@ -53,7 +54,6 @@ public: void setDesktop(SPDesktop *desktop) override; private: - sigc::connection selection_changed_connection; sigc::connection selection_modified_connection; @@ -61,9 +61,9 @@ private: void effect_list_reload(SPLPEItem *lpeitem); void set_sensitize_all(bool sensitive); - void showParams(LivePathEffect::Effect& effect); + void showParams(LivePathEffect::Effect &effect); void showText(Glib::ustring const &str); - void selectInList(LivePathEffect::Effect* effect); + void selectInList(LivePathEffect::Effect *effect); // callback methods for buttons on grids page. void onAdd(); @@ -73,7 +73,7 @@ private: class ModelColumns : public Gtk::TreeModel::ColumnRecord { - public: + public: ModelColumns() { add(col_name); @@ -88,9 +88,9 @@ private: }; bool lpe_list_locked; - //Inkscape::UI::Widget::ComboBoxEnum<LivePathEffect::EffectType> combo_effecttype; - - Gtk::Widget * effectwidget; + // Inkscape::UI::Widget::ComboBoxEnum<LivePathEffect::EffectType> combo_effecttype; + + Gtk::Widget *effectwidget; Gtk::Label status_label; UI::Widget::Frame effectcontrol_frame; Gtk::HBox effectapplication_hbox; @@ -103,25 +103,25 @@ private: Glib::RefPtr<Gtk::ListStore> effectlist_store; Glib::RefPtr<Gtk::TreeSelection> effectlist_selection; - void on_visibility_toggled( Glib::ustring const& str); - bool _on_button_release(GdkEventButton* button_event); + void on_visibility_toggled(Glib::ustring const &str); + bool _on_button_release(GdkEventButton *button_event); Gtk::ButtonBox toolbar_hbox; Gtk::Button button_add; Gtk::Button button_remove; Gtk::Button button_up; Gtk::Button button_down; - SPDesktop * current_desktop; - - SPLPEItem * current_lpeitem; + SPDesktop *current_desktop; + + SPLPEItem *current_lpeitem; - LivePathEffect::LPEObjectReference * current_lperef; + LivePathEffect::LPEObjectReference *current_lperef; - friend void lpeeditor_selection_changed (Inkscape::Selection * selection, gpointer data); - friend void lpeeditor_selection_modified (Inkscape::Selection * selection, guint /*flags*/, gpointer data); + friend void lpeeditor_selection_changed(Inkscape::Selection *selection, gpointer data); + friend void lpeeditor_selection_modified(Inkscape::Selection *selection, guint /*flags*/, gpointer data); LivePathEffectEditor(LivePathEffectEditor const &d); - LivePathEffectEditor& operator=(LivePathEffectEditor const &d); + LivePathEffectEditor &operator=(LivePathEffectEditor const &d); }; } // namespace Dialog diff --git a/src/ui/dialog/lpe-fillet-chamfer-properties.cpp b/src/ui/dialog/lpe-fillet-chamfer-properties.cpp index 42c6efc8d4f7266531390198ac8f70696a6bd05d..26dc27bed7878690844de3e912f2109266f10687 100644 --- a/src/ui/dialog/lpe-fillet-chamfer-properties.cpp +++ b/src/ui/dialog/lpe-fillet-chamfer-properties.cpp @@ -5,16 +5,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm.h> #include "lpe-fillet-chamfer-properties.h" + #include <boost/lexical_cast.hpp> #include <glibmm/i18n.h> -#include "inkscape.h" +#include <gtkmm.h> + #include "desktop.h" #include "document-undo.h" +#include "inkscape.h" #include "layer-manager.h" #include "message-stack.h" - #include "selection-chemistry.h" //#include "event-context.h" @@ -24,10 +25,10 @@ namespace UI { namespace Dialogs { FilletChamferPropertiesDialog::FilletChamferPropertiesDialog() - : _desktop(nullptr), - _knotpoint(nullptr), - _position_visible(false), - _close_button(_("_Cancel"), true) + : _desktop(nullptr) + , _knotpoint(nullptr) + , _position_visible(false) + , _close_button(_("_Cancel"), true) { Gtk::Box *mainVBox = get_content_area(); mainVBox->set_homogeneous(false); @@ -36,8 +37,8 @@ FilletChamferPropertiesDialog::FilletChamferPropertiesDialog() // Layer name widgets _fillet_chamfer_position_numeric.set_digits(4); - _fillet_chamfer_position_numeric.set_increments(1,1); - //todo: get tha max aloable infinity freeze the widget + _fillet_chamfer_position_numeric.set_increments(1, 1); + // todo: get tha max aloable infinity freeze the widget _fillet_chamfer_position_numeric.set_range(0., SCALARPARAM_G_MAXDOUBLE); _fillet_chamfer_position_numeric.set_hexpand(); _fillet_chamfer_position_label.set_label(_("Radius (pixels):")); @@ -47,8 +48,8 @@ FilletChamferPropertiesDialog::FilletChamferPropertiesDialog() _layout_table.attach(_fillet_chamfer_position_label, 0, 0, 1, 1); _layout_table.attach(_fillet_chamfer_position_numeric, 1, 0, 1, 1); _fillet_chamfer_chamfer_subdivisions.set_digits(0); - _fillet_chamfer_chamfer_subdivisions.set_increments(1,1); - //todo: get tha max aloable infinity freeze the widget + _fillet_chamfer_chamfer_subdivisions.set_increments(1, 1); + // todo: get tha max aloable infinity freeze the widget _fillet_chamfer_chamfer_subdivisions.set_range(0, SCALARPARAM_G_MAXDOUBLE); _fillet_chamfer_chamfer_subdivisions.set_hexpand(); _fillet_chamfer_chamfer_subdivisions_label.set_label(_("Chamfer subdivisions:")); @@ -66,7 +67,6 @@ FilletChamferPropertiesDialog::FilletChamferPropertiesDialog() _fillet_chamfer_type_inverse_chamfer.set_label(_("Inverse chamfer")); _fillet_chamfer_type_inverse_chamfer.set_group(_fillet_chamfer_type_group); - mainVBox->pack_start(_layout_table, true, true, 4); mainVBox->pack_start(_fillet_chamfer_type_fillet, true, true, 4); mainVBox->pack_start(_fillet_chamfer_type_inverse_fillet, true, true, 4); @@ -79,14 +79,11 @@ FilletChamferPropertiesDialog::FilletChamferPropertiesDialog() _apply_button.set_use_underline(true); _apply_button.set_can_default(); - _close_button.signal_clicked() - .connect(sigc::mem_fun(*this, &FilletChamferPropertiesDialog::_close)); - _apply_button.signal_clicked() - .connect(sigc::mem_fun(*this, &FilletChamferPropertiesDialog::_apply)); + _close_button.signal_clicked().connect(sigc::mem_fun(*this, &FilletChamferPropertiesDialog::_close)); + _apply_button.signal_clicked().connect(sigc::mem_fun(*this, &FilletChamferPropertiesDialog::_apply)); - signal_delete_event().connect(sigc::bind_return( - sigc::hide(sigc::mem_fun(*this, &FilletChamferPropertiesDialog::_close)), - true)); + signal_delete_event().connect( + sigc::bind_return(sigc::hide(sigc::mem_fun(*this, &FilletChamferPropertiesDialog::_close)), true)); add_action_widget(_close_button, Gtk::RESPONSE_CLOSE); add_action_widget(_apply_button, Gtk::RESPONSE_APPLY); @@ -100,18 +97,12 @@ FilletChamferPropertiesDialog::FilletChamferPropertiesDialog() FilletChamferPropertiesDialog::~FilletChamferPropertiesDialog() { - _setDesktop(nullptr); } -void FilletChamferPropertiesDialog::showDialog( - SPDesktop *desktop, - double _amount, - const Inkscape::LivePathEffect:: - FilletChamferKnotHolderEntity *pt, - bool _use_distance, - bool _aprox_radius, - Satellite _satellite) +void FilletChamferPropertiesDialog::showDialog(SPDesktop *desktop, double _amount, + const Inkscape::LivePathEffect::FilletChamferKnotHolderEntity *pt, + bool _use_distance, bool _aprox_radius, Satellite _satellite) { FilletChamferPropertiesDialog *dialog = new FilletChamferPropertiesDialog(); @@ -135,8 +126,7 @@ void FilletChamferPropertiesDialog::showDialog( void FilletChamferPropertiesDialog::_apply() { - - double d_pos = _fillet_chamfer_position_numeric.get_value(); + double d_pos = _fillet_chamfer_position_numeric.get_value(); if (d_pos >= 0) { if (_fillet_chamfer_type_fillet.get_active() == true) { _satellite.satellite_type = FILLET; @@ -169,11 +159,7 @@ void FilletChamferPropertiesDialog::_close() _setDesktop(nullptr); destroy_(); Glib::signal_idle().connect( - sigc::bind_return( - sigc::bind(sigc::ptr_fun<void*, void>(&::operator delete), this), - false - ) - ); + sigc::bind_return(sigc::bind(sigc::ptr_fun<void *, void>(&::operator delete), this), false)); } bool FilletChamferPropertiesDialog::_handleKeyEvent(GdkEventKey * /*event*/) @@ -204,7 +190,7 @@ void FilletChamferPropertiesDialog::_setSatellite(Satellite satellite) _fillet_chamfer_position_label.set_label(_("Position (%):")); } else { _flexible = false; - auto posConcat = Glib::ustring::compose (_("%1:"), distance_or_radius); + auto posConcat = Glib::ustring::compose(_("%1:"), distance_or_radius); _fillet_chamfer_position_label.set_label(_(posConcat.c_str())); position = _amount; } @@ -222,23 +208,16 @@ void FilletChamferPropertiesDialog::_setSatellite(Satellite satellite) _satellite = satellite; } -void FilletChamferPropertiesDialog::_setPt( - const Inkscape::LivePathEffect:: - FilletChamferKnotHolderEntity *pt) +void FilletChamferPropertiesDialog::_setPt(const Inkscape::LivePathEffect::FilletChamferKnotHolderEntity *pt) { - _knotpoint = const_cast< - Inkscape::LivePathEffect::FilletChamferKnotHolderEntity *>( - pt); + _knotpoint = const_cast<Inkscape::LivePathEffect::FilletChamferKnotHolderEntity *>(pt); } - void FilletChamferPropertiesDialog::_setAmount(double amount) { _amount = amount; } - - void FilletChamferPropertiesDialog::_setUseDistance(bool use_knot_distance) { _use_distance = use_knot_distance; @@ -260,9 +239,9 @@ void FilletChamferPropertiesDialog::_setDesktop(SPDesktop *desktop) _desktop = desktop; } -} // namespace -} // namespace -} // namespace +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/lpe-fillet-chamfer-properties.h b/src/ui/dialog/lpe-fillet-chamfer-properties.h index 26a0569ab2a9b68ef48120f156ab8eef50e9aa05..1d236a2b37f7a108bdc33838945e5dee0e28ef57 100644 --- a/src/ui/dialog/lpe-fillet-chamfer-properties.h +++ b/src/ui/dialog/lpe-fillet-chamfer-properties.h @@ -11,6 +11,7 @@ #include <2geom/point.h> #include <gtkmm.h> + #include "live_effects/parameter/satellitesarray.h" class SPDesktop; @@ -19,28 +20,21 @@ namespace Inkscape { namespace UI { namespace Dialogs { -class FilletChamferPropertiesDialog : public Gtk::Dialog { +class FilletChamferPropertiesDialog : public Gtk::Dialog +{ public: FilletChamferPropertiesDialog(); ~FilletChamferPropertiesDialog() override; - Glib::ustring getName() const - { - return "LayerPropertiesDialog"; - } + Glib::ustring getName() const { return "LayerPropertiesDialog"; } static void showDialog(SPDesktop *desktop, double _amount, - const Inkscape::LivePathEffect:: - FilletChamferKnotHolderEntity *pt, - bool _use_distance, - bool _aprox_radius, - Satellite _satellite); + const Inkscape::LivePathEffect::FilletChamferKnotHolderEntity *pt, bool _use_distance, + bool _aprox_radius, Satellite _satellite); protected: - SPDesktop *_desktop; - Inkscape::LivePathEffect::FilletChamferKnotHolderEntity * - _knotpoint; + Inkscape::LivePathEffect::FilletChamferKnotHolderEntity *_knotpoint; Gtk::Label _fillet_chamfer_position_label; Gtk::SpinButton _fillet_chamfer_position_numeric; @@ -67,8 +61,7 @@ protected: } void _setDesktop(SPDesktop *desktop); - void _setPt(const Inkscape::LivePathEffect:: - FilletChamferKnotHolderEntity *pt); + void _setPt(const Inkscape::LivePathEffect::FilletChamferKnotHolderEntity *pt); void _setUseDistance(bool use_knot_distance); void _setAprox(bool aprox_radius); void _setAmount(double amount); @@ -86,21 +79,18 @@ protected: double _amount; bool _aprox; - friend class Inkscape::LivePathEffect:: - FilletChamferKnotHolderEntity; + friend class Inkscape::LivePathEffect::FilletChamferKnotHolderEntity; private: - FilletChamferPropertiesDialog( - FilletChamferPropertiesDialog const &); // no copy - FilletChamferPropertiesDialog &operator=( - FilletChamferPropertiesDialog const &); // no assign + FilletChamferPropertiesDialog(FilletChamferPropertiesDialog const &); // no copy + FilletChamferPropertiesDialog &operator=(FilletChamferPropertiesDialog const &); // no assign }; -} // namespace -} // namespace -} // namespace +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape -#endif //INKSCAPE_DIALOG_LAYER_PROPERTIES_H +#endif // INKSCAPE_DIALOG_LAYER_PROPERTIES_H /* Local Variables: diff --git a/src/ui/dialog/lpe-powerstroke-properties.cpp b/src/ui/dialog/lpe-powerstroke-properties.cpp index 1e5d1b12560fdc718f5e14e19c40f1272a5f8671..a6eac1a101b267a3ed90205ec47e311a219876e3 100644 --- a/src/ui/dialog/lpe-powerstroke-properties.cpp +++ b/src/ui/dialog/lpe-powerstroke-properties.cpp @@ -15,13 +15,14 @@ */ #include "lpe-powerstroke-properties.h" + #include <boost/lexical_cast.hpp> #include <glibmm/i18n.h> -#include "inkscape.h" + #include "desktop.h" #include "document-undo.h" +#include "inkscape.h" #include "layer-manager.h" - #include "selection-chemistry.h" //#include "event-context.h" @@ -30,10 +31,10 @@ namespace UI { namespace Dialogs { PowerstrokePropertiesDialog::PowerstrokePropertiesDialog() - : _desktop(nullptr), - _knotpoint(nullptr), - _position_visible(false), - _close_button(_("_Cancel"), true) + : _desktop(nullptr) + , _knotpoint(nullptr) + , _position_visible(false) + , _close_button(_("_Cancel"), true) { Gtk::Box *mainVBox = get_content_area(); @@ -43,7 +44,7 @@ PowerstrokePropertiesDialog::PowerstrokePropertiesDialog() // Layer name widgets _powerstroke_position_entry.set_activates_default(true); _powerstroke_position_entry.set_digits(4); - _powerstroke_position_entry.set_increments(1,1); + _powerstroke_position_entry.set_increments(1, 1); _powerstroke_position_entry.set_range(-SCALARPARAM_G_MAXDOUBLE, SCALARPARAM_G_MAXDOUBLE); _powerstroke_position_entry.set_hexpand(); _powerstroke_position_label.set_label(_("Position:")); @@ -52,17 +53,17 @@ PowerstrokePropertiesDialog::PowerstrokePropertiesDialog() _powerstroke_width_entry.set_activates_default(true); _powerstroke_width_entry.set_digits(4); - _powerstroke_width_entry.set_increments(1,1); + _powerstroke_width_entry.set_increments(1, 1); _powerstroke_width_entry.set_range(-SCALARPARAM_G_MAXDOUBLE, SCALARPARAM_G_MAXDOUBLE); _powerstroke_width_entry.set_hexpand(); _powerstroke_width_label.set_label(_("Width:")); _powerstroke_width_label.set_halign(Gtk::ALIGN_END); _powerstroke_width_label.set_valign(Gtk::ALIGN_CENTER); - _layout_table.attach(_powerstroke_position_label,0,0,1,1); - _layout_table.attach(_powerstroke_position_entry,1,0,1,1); - _layout_table.attach(_powerstroke_width_label, 0,1,1,1); - _layout_table.attach(_powerstroke_width_entry, 1,1,1,1); + _layout_table.attach(_powerstroke_position_label, 0, 0, 1, 1); + _layout_table.attach(_powerstroke_position_entry, 1, 0, 1, 1); + _layout_table.attach(_powerstroke_width_label, 0, 1, 1, 1); + _layout_table.attach(_powerstroke_width_entry, 1, 1, 1, 1); mainVBox->pack_start(_layout_table, true, true, 4); @@ -72,17 +73,11 @@ PowerstrokePropertiesDialog::PowerstrokePropertiesDialog() _apply_button.set_use_underline(true); _apply_button.set_can_default(); - _close_button.signal_clicked() - .connect(sigc::mem_fun(*this, &PowerstrokePropertiesDialog::_close)); - _apply_button.signal_clicked() - .connect(sigc::mem_fun(*this, &PowerstrokePropertiesDialog::_apply)); + _close_button.signal_clicked().connect(sigc::mem_fun(*this, &PowerstrokePropertiesDialog::_close)); + _apply_button.signal_clicked().connect(sigc::mem_fun(*this, &PowerstrokePropertiesDialog::_apply)); signal_delete_event().connect( - sigc::bind_return( - sigc::hide(sigc::mem_fun(*this, &PowerstrokePropertiesDialog::_close)), - true - ) - ); + sigc::bind_return(sigc::hide(sigc::mem_fun(*this, &PowerstrokePropertiesDialog::_close)), true)); add_action_widget(_close_button, Gtk::RESPONSE_CLOSE); add_action_widget(_apply_button, Gtk::RESPONSE_APPLY); @@ -94,14 +89,16 @@ PowerstrokePropertiesDialog::PowerstrokePropertiesDialog() set_focus(_powerstroke_width_entry); } -PowerstrokePropertiesDialog::~PowerstrokePropertiesDialog() { - +PowerstrokePropertiesDialog::~PowerstrokePropertiesDialog() +{ _setDesktop(nullptr); } -void PowerstrokePropertiesDialog::showDialog(SPDesktop *desktop, Geom::Point knotpoint, const Inkscape::LivePathEffect::PowerStrokePointArrayParamKnotHolderEntity *pt) +void PowerstrokePropertiesDialog::showDialog( + SPDesktop *desktop, Geom::Point knotpoint, + const Inkscape::LivePathEffect::PowerStrokePointArrayParamKnotHolderEntity *pt) { - PowerstrokePropertiesDialog *dialog = new PowerstrokePropertiesDialog(); + PowerstrokePropertiesDialog *dialog = new PowerstrokePropertiesDialog(); dialog->_setDesktop(desktop); dialog->_setKnotPoint(knotpoint); @@ -111,38 +108,31 @@ void PowerstrokePropertiesDialog::showDialog(SPDesktop *desktop, Geom::Point kno dialog->_apply_button.set_label(_("_Move")); dialog->set_modal(true); - desktop->setWindowTransient (dialog->gobj()); + desktop->setWindowTransient(dialog->gobj()); dialog->property_destroy_with_parent() = true; dialog->show(); dialog->present(); } -void -PowerstrokePropertiesDialog::_apply() +void PowerstrokePropertiesDialog::_apply() { - double d_pos = _powerstroke_position_entry.get_value(); + double d_pos = _powerstroke_position_entry.get_value(); double d_width = _powerstroke_width_entry.get_value(); _knotpoint->knot_set_offset(Geom::Point(d_pos, d_width)); _close(); } -void -PowerstrokePropertiesDialog::_close() +void PowerstrokePropertiesDialog::_close() { _setDesktop(nullptr); destroy_(); Glib::signal_idle().connect( - sigc::bind_return( - sigc::bind(sigc::ptr_fun<void*, void>(&::operator delete), this), - false - ) - ); + sigc::bind_return(sigc::bind(sigc::ptr_fun<void *, void>(&::operator delete), this), false)); } bool PowerstrokePropertiesDialog::_handleKeyEvent(GdkEventKey * /*event*/) { - /*switch (get_latin_keyval(event)) { case GDK_KEY_Return: case GDK_KEY_KP_Enter: { @@ -154,38 +144,38 @@ bool PowerstrokePropertiesDialog::_handleKeyEvent(GdkEventKey * /*event*/) return false; } -void PowerstrokePropertiesDialog::_handleButtonEvent(GdkEventButton* event) +void PowerstrokePropertiesDialog::_handleButtonEvent(GdkEventButton *event) { - if ( (event->type == GDK_2BUTTON_PRESS) && (event->button == 1) ) { + if ((event->type == GDK_2BUTTON_PRESS) && (event->button == 1)) { _apply(); } } void PowerstrokePropertiesDialog::_setKnotPoint(Geom::Point knotpoint) { - _powerstroke_position_entry.set_value(knotpoint.x()); - _powerstroke_width_entry.set_value(knotpoint.y()); + _powerstroke_position_entry.set_value(knotpoint.x()); + _powerstroke_width_entry.set_value(knotpoint.y()); } void PowerstrokePropertiesDialog::_setPt(const Inkscape::LivePathEffect::PowerStrokePointArrayParamKnotHolderEntity *pt) { - _knotpoint = const_cast<Inkscape::LivePathEffect::PowerStrokePointArrayParamKnotHolderEntity *>(pt); + _knotpoint = const_cast<Inkscape::LivePathEffect::PowerStrokePointArrayParamKnotHolderEntity *>(pt); } -void PowerstrokePropertiesDialog::_setDesktop(SPDesktop *desktop) { +void PowerstrokePropertiesDialog::_setDesktop(SPDesktop *desktop) +{ if (desktop) { - Inkscape::GC::anchor (desktop); + Inkscape::GC::anchor(desktop); } if (_desktop) { - Inkscape::GC::release (_desktop); + Inkscape::GC::release(_desktop); } _desktop = desktop; } -} // namespace -} // namespace -} // namespace - +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/lpe-powerstroke-properties.h b/src/ui/dialog/lpe-powerstroke-properties.h index 0bf6539af803300d40a980c32439aeb2c80e0572..015199b2f6fef01feb9f005227ada4ea02496c54 100644 --- a/src/ui/dialog/lpe-powerstroke-properties.h +++ b/src/ui/dialog/lpe-powerstroke-properties.h @@ -15,6 +15,7 @@ #include <2geom/point.h> #include <gtkmm.h> + #include "live_effects/parameter/powerstrokepointarray.h" class SPDesktop; @@ -23,33 +24,35 @@ namespace Inkscape { namespace UI { namespace Dialogs { -class PowerstrokePropertiesDialog : public Gtk::Dialog { - public: - PowerstrokePropertiesDialog(); +class PowerstrokePropertiesDialog : public Gtk::Dialog +{ +public: + PowerstrokePropertiesDialog(); ~PowerstrokePropertiesDialog() override; - Glib::ustring getName() const { return "LayerPropertiesDialog"; } + Glib::ustring getName() const { return "LayerPropertiesDialog"; } - static void showDialog(SPDesktop *desktop, Geom::Point knotpoint, const Inkscape::LivePathEffect::PowerStrokePointArrayParamKnotHolderEntity *pt); + static void showDialog(SPDesktop *desktop, Geom::Point knotpoint, + const Inkscape::LivePathEffect::PowerStrokePointArrayParamKnotHolderEntity *pt); protected: - SPDesktop *_desktop; Inkscape::LivePathEffect::PowerStrokePointArrayParamKnotHolderEntity *_knotpoint; - Gtk::Label _powerstroke_position_label; - Gtk::SpinButton _powerstroke_position_entry; - Gtk::Label _powerstroke_width_label; - Gtk::SpinButton _powerstroke_width_entry; - Gtk::Grid _layout_table; - bool _position_visible; + Gtk::Label _powerstroke_position_label; + Gtk::SpinButton _powerstroke_position_entry; + Gtk::Label _powerstroke_width_label; + Gtk::SpinButton _powerstroke_width_entry; + Gtk::Grid _layout_table; + bool _position_visible; - Gtk::Button _close_button; - Gtk::Button _apply_button; + Gtk::Button _close_button; + Gtk::Button _apply_button; - sigc::connection _destroy_connection; + sigc::connection _destroy_connection; - static PowerstrokePropertiesDialog &_instance() { + static PowerstrokePropertiesDialog &_instance() + { static PowerstrokePropertiesDialog instance; return instance; } @@ -64,21 +67,20 @@ protected: void _prepareLabelRenderer(Gtk::TreeModel::const_iterator const &row); bool _handleKeyEvent(GdkEventKey *event); - void _handleButtonEvent(GdkEventButton* event); + void _handleButtonEvent(GdkEventButton *event); friend class Inkscape::LivePathEffect::PowerStrokePointArrayParamKnotHolderEntity; private: - PowerstrokePropertiesDialog(PowerstrokePropertiesDialog const &); // no copy + PowerstrokePropertiesDialog(PowerstrokePropertiesDialog const &); // no copy PowerstrokePropertiesDialog &operator=(PowerstrokePropertiesDialog const &); // no assign }; -} // namespace -} // namespace -} // namespace - +} // namespace Dialogs +} // namespace UI +} // namespace Inkscape -#endif //INKSCAPE_DIALOG_LAYER_PROPERTIES_H +#endif // INKSCAPE_DIALOG_LAYER_PROPERTIES_H /* Local Variables: diff --git a/src/ui/dialog/memory.cpp b/src/ui/dialog/memory.cpp index a4210ca0cf4a21ebaddf7805f8a747f0fb621af7..0f68cf7530d5616ec01abff38c323ec02567746a 100644 --- a/src/ui/dialog/memory.cpp +++ b/src/ui/dialog/memory.cpp @@ -12,15 +12,15 @@ */ #include "ui/dialog/memory.h" + #include <glibmm/i18n.h> #include <glibmm/main.h> - +#include <gtkmm/dialog.h> #include <gtkmm/liststore.h> #include <gtkmm/treeview.h> -#include <gtkmm/dialog.h> -#include "inkgc/gc-core.h" #include "debug/heap.h" +#include "inkgc/gc-core.h" #include "verbs.h" namespace Inkscape { @@ -29,7 +29,8 @@ namespace Dialog { namespace { -Glib::ustring format_size(std::size_t value) { +Glib::ustring format_size(std::size_t value) +{ if (!value) { return Glib::ustring("0"); } @@ -42,12 +43,12 @@ Glib::ustring format_size(std::size_t value) { Digits *digits; while (value) { - unsigned places=3; + unsigned places = 3; digits = new Digits(); digits->reserve(places); - while ( value && places ) { - digits->push_back('0' + (char)( value % 10 )); + while (value && places) { + digits->push_back('0' + (char)(value % 10)); value /= 10; --places; } @@ -76,20 +77,29 @@ Glib::ustring format_size(std::size_t value) { return temp; } -} +} // namespace -struct Memory::Private { - class ModelColumns : public Gtk::TreeModel::ColumnRecord { +struct Memory::Private +{ + class ModelColumns : public Gtk::TreeModel::ColumnRecord + { public: Gtk::TreeModelColumn<Glib::ustring> name; Gtk::TreeModelColumn<Glib::ustring> used; Gtk::TreeModelColumn<Glib::ustring> slack; Gtk::TreeModelColumn<Glib::ustring> total; - ModelColumns() { add(name); add(used); add(slack); add(total); } + ModelColumns() + { + add(name); + add(used); + add(slack); + add(total); + } }; - Private() { + Private() + { model = Gtk::ListStore::create(columns); view.set_model(model); view.append_column(_("Heap"), columns.name); @@ -112,42 +122,41 @@ struct Memory::Private { sigc::connection update_task; }; -void Memory::Private::update() { - Debug::Heap::Stats total = { 0, 0 }; +void Memory::Private::update() +{ + Debug::Heap::Stats total = {0, 0}; int aggregate_features = Debug::Heap::SIZE_AVAILABLE | Debug::Heap::USED_AVAILABLE; Gtk::ListStore::iterator row; row = model->children().begin(); - for ( unsigned i = 0 ; i < Debug::heap_count() ; i++ ) { - Debug::Heap *heap=Debug::get_heap(i); + for (unsigned i = 0; i < Debug::heap_count(); i++) { + Debug::Heap *heap = Debug::get_heap(i); if (heap) { - Debug::Heap::Stats stats=heap->stats(); - int features=heap->features(); + Debug::Heap::Stats stats = heap->stats(); + int features = heap->features(); aggregate_features &= features; - if ( row == model->children().end() ) { + if (row == model->children().end()) { row = model->append(); } row->set_value(columns.name, Glib::ustring(heap->name())); - if ( features & Debug::Heap::SIZE_AVAILABLE ) { + if (features & Debug::Heap::SIZE_AVAILABLE) { row->set_value(columns.total, format_size(stats.size)); total.size += stats.size; } else { row->set_value(columns.total, Glib::ustring(_("Unknown"))); } - if ( features & Debug::Heap::USED_AVAILABLE ) { + if (features & Debug::Heap::USED_AVAILABLE) { row->set_value(columns.used, format_size(stats.bytes_used)); total.bytes_used += stats.bytes_used; } else { row->set_value(columns.used, Glib::ustring(_("Unknown"))); } - if ( features & Debug::Heap::SIZE_AVAILABLE && - features & Debug::Heap::USED_AVAILABLE ) - { + if (features & Debug::Heap::SIZE_AVAILABLE && features & Debug::Heap::USED_AVAILABLE) { row->set_value(columns.slack, format_size(stats.size - stats.bytes_used)); } else { row->set_value(columns.slack, Glib::ustring(_("Unknown"))); @@ -157,7 +166,7 @@ void Memory::Private::update() { } } - if ( row == model->children().end() ) { + if (row == model->children().end()) { row = model->append(); } @@ -165,21 +174,19 @@ void Memory::Private::update() { row->set_value(columns.name, Glib::ustring(_("Combined"))); - if ( aggregate_features & Debug::Heap::SIZE_AVAILABLE ) { + if (aggregate_features & Debug::Heap::SIZE_AVAILABLE) { row->set_value(columns.total, format_size(total.size)); } else { row->set_value(columns.total, Glib::ustring("> ") + format_size(total.size)); } - if ( aggregate_features & Debug::Heap::USED_AVAILABLE ) { + if (aggregate_features & Debug::Heap::USED_AVAILABLE) { row->set_value(columns.used, format_size(total.bytes_used)); } else { row->set_value(columns.used, Glib::ustring("> ") + format_size(total.bytes_used)); } - if ( aggregate_features & Debug::Heap::SIZE_AVAILABLE && - aggregate_features & Debug::Heap::USED_AVAILABLE ) - { + if (aggregate_features & Debug::Heap::SIZE_AVAILABLE && aggregate_features & Debug::Heap::USED_AVAILABLE) { row->set_value(columns.slack, format_size(total.size - total.bytes_used)); } else { row->set_value(columns.slack, Glib::ustring(_("Unknown"))); @@ -187,26 +194,25 @@ void Memory::Private::update() { ++row; - while ( row != model->children().end() ) { + while (row != model->children().end()) { row = model->erase(row); } } -void Memory::Private::start_update_task() { +void Memory::Private::start_update_task() +{ update_task.disconnect(); - update_task = Glib::signal_timeout().connect( - sigc::bind_return(sigc::mem_fun(*this, &Private::update), true), - 500 - ); + update_task = Glib::signal_timeout().connect(sigc::bind_return(sigc::mem_fun(*this, &Private::update), true), 500); } -void Memory::Private::stop_update_task() { +void Memory::Private::stop_update_task() +{ update_task.disconnect(); } -Memory::Memory() - : UI::Widget::Panel("/dialogs/memory", SP_VERB_HELP_MEMORY), - _private(*(new Memory::Private())) +Memory::Memory() + : UI::Widget::Panel("/dialogs/memory", SP_VERB_HELP_MEMORY) + , _private(*(new Memory::Private())) { _getContents()->pack_start(_private.view); @@ -222,11 +228,13 @@ Memory::Memory() _private.start_update_task(); } -Memory::~Memory() { +Memory::~Memory() +{ delete &_private; } -void Memory::_apply() { +void Memory::_apply() +{ GC::Core::gcollect(); _private.update(); } diff --git a/src/ui/dialog/memory.h b/src/ui/dialog/memory.h index 5e6a917653101c9c5aab6f17fc4709172ae65759..78617af8cbcd4a965ce1d5a71cc2ebd0712f6054 100644 --- a/src/ui/dialog/memory.h +++ b/src/ui/dialog/memory.h @@ -18,7 +18,8 @@ namespace Inkscape { namespace UI { namespace Dialog { -class Memory : public UI::Widget::Panel { +class Memory : public UI::Widget::Panel +{ public: Memory(); ~Memory() override; @@ -29,7 +30,7 @@ protected: void _apply() override; private: - Memory(Memory const &d) = delete; // no copy + Memory(Memory const &d) = delete; // no copy void operator=(Memory const &d) = delete; // no assign struct Private; diff --git a/src/ui/dialog/messages.cpp b/src/ui/dialog/messages.cpp index 85ba840f5ecd0344c997288ed03eebb38857023e..a57277df1d65291da2948940e31dc11039411b4d 100644 --- a/src/ui/dialog/messages.cpp +++ b/src/ui/dialog/messages.cpp @@ -13,13 +13,13 @@ */ #include "messages.h" + #include "verbs.h" namespace Inkscape { namespace UI { namespace Dialog { - //######################################################################### //## E V E N T S //######################################################################### @@ -33,7 +33,6 @@ void Messages::clear() buffer->erase(buffer->begin(), buffer->end()); } - //######################################################################### //## C O N S T R U C T O R / D E S T R U C T O R //######################################################################### @@ -41,9 +40,9 @@ void Messages::clear() * Constructor */ Messages::Messages() - : UI::Widget::Panel("/dialogs/messages", SP_VERB_DIALOG_DEBUG), - buttonClear(_("_Clear"), _("Clear log messages")), - checkCapture(_("Capture log messages"), _("Capture log messages")) + : UI::Widget::Panel("/dialogs/messages", SP_VERB_DIALOG_DEBUG) + , buttonClear(_("_Clear"), _("Clear log messages")) + , checkCapture(_("Capture log messages"), _("Capture log messages")) { Gtk::Box *contents = _getContents(); @@ -73,7 +72,7 @@ Messages::Messages() // sick of this thing shrinking too much set_size_request(400, 300); - + show_all_children(); message(_("Ready.")); @@ -84,23 +83,21 @@ Messages::Messages() /* * TODO - Setting this preference doesn't capture messages that the user can see. * Inkscape creates an instance of a dialog on startup and sends messages there, but when the user - * opens the dialog View > Messages the DialogManager creates a new instance of this class that is not capturing messages. + * opens the dialog View > Messages the DialogManager creates a new instance of this class that is not capturing + * messages. * * message(_("Enable log display by setting dialogs.debug 'redirect' attribute to 1 in preferences.xml")); - */ + */ handlerDefault = 0; - handlerGlibmm = 0; - handlerAtkmm = 0; + handlerGlibmm = 0; + handlerAtkmm = 0; handlerPangomm = 0; - handlerGdkmm = 0; - handlerGtkmm = 0; - + handlerGdkmm = 0; + handlerGtkmm = 0; } -Messages::~Messages() -= default; - +Messages::~Messages() = default; //######################################################################### //## M E T H O D S @@ -110,20 +107,17 @@ void Messages::message(char *msg) { Glib::RefPtr<Gtk::TextBuffer> buffer = messageText.get_buffer(); Glib::ustring uMsg = msg; - if (uMsg[uMsg.length()-1] != '\n') + if (uMsg[uMsg.length() - 1] != '\n') uMsg += '\n'; - buffer->insert (buffer->end(), uMsg); + buffer->insert(buffer->end(), uMsg); } // dialogLoggingCallback is already used in debug.cpp -static void dialogLoggingCallback(const gchar */*log_domain*/, - GLogLevelFlags /*log_level*/, - const gchar *messageText, - gpointer user_data) +static void dialogLoggingCallback(const gchar * /*log_domain*/, GLogLevelFlags /*log_level*/, const gchar *messageText, + gpointer user_data) { Messages *dlg = static_cast<Messages *>(user_data); - dlg->message(const_cast<char*>(messageText)); - + dlg->message(const_cast<char *>(messageText)); } void Messages::toggleCapture() @@ -141,68 +135,61 @@ void Messages::captureLogMessages() This might likely need more code, to capture Gtkmm and Glibmm warnings, or maybe just simply grab stdout/stderr */ - GLogLevelFlags flags = (GLogLevelFlags) (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | - G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE | - G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG); - if ( !handlerDefault ) { - handlerDefault = g_log_set_handler(nullptr, flags, - dialogLoggingCallback, (gpointer)this); + GLogLevelFlags flags = (GLogLevelFlags)(G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | + G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG); + if (!handlerDefault) { + handlerDefault = g_log_set_handler(nullptr, flags, dialogLoggingCallback, (gpointer)this); } - if ( !handlerGlibmm ) { - handlerGlibmm = g_log_set_handler("glibmm", flags, - dialogLoggingCallback, (gpointer)this); + if (!handlerGlibmm) { + handlerGlibmm = g_log_set_handler("glibmm", flags, dialogLoggingCallback, (gpointer)this); } - if ( !handlerAtkmm ) { - handlerAtkmm = g_log_set_handler("atkmm", flags, - dialogLoggingCallback, (gpointer)this); + if (!handlerAtkmm) { + handlerAtkmm = g_log_set_handler("atkmm", flags, dialogLoggingCallback, (gpointer)this); } - if ( !handlerPangomm ) { - handlerPangomm = g_log_set_handler("pangomm", flags, - dialogLoggingCallback, (gpointer)this); + if (!handlerPangomm) { + handlerPangomm = g_log_set_handler("pangomm", flags, dialogLoggingCallback, (gpointer)this); } - if ( !handlerGdkmm ) { - handlerGdkmm = g_log_set_handler("gdkmm", flags, - dialogLoggingCallback, (gpointer)this); + if (!handlerGdkmm) { + handlerGdkmm = g_log_set_handler("gdkmm", flags, dialogLoggingCallback, (gpointer)this); } - if ( !handlerGtkmm ) { - handlerGtkmm = g_log_set_handler("gtkmm", flags, - dialogLoggingCallback, (gpointer)this); + if (!handlerGtkmm) { + handlerGtkmm = g_log_set_handler("gtkmm", flags, dialogLoggingCallback, (gpointer)this); } message(_("Log capture started.")); } void Messages::releaseLogMessages() { - if ( handlerDefault ) { + if (handlerDefault) { g_log_remove_handler(nullptr, handlerDefault); handlerDefault = 0; } - if ( handlerGlibmm ) { + if (handlerGlibmm) { g_log_remove_handler("glibmm", handlerGlibmm); handlerGlibmm = 0; } - if ( handlerAtkmm ) { + if (handlerAtkmm) { g_log_remove_handler("atkmm", handlerAtkmm); handlerAtkmm = 0; } - if ( handlerPangomm ) { + if (handlerPangomm) { g_log_remove_handler("pangomm", handlerPangomm); handlerPangomm = 0; } - if ( handlerGdkmm ) { + if (handlerGdkmm) { g_log_remove_handler("gdkmm", handlerGdkmm); handlerGdkmm = 0; } - if ( handlerGtkmm ) { + if (handlerGtkmm) { g_log_remove_handler("gtkmm", handlerGtkmm); handlerGtkmm = 0; } message(_("Log capture stopped.")); } -} //namespace Dialog -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/messages.h b/src/ui/dialog/messages.h index b3ad39320a21c3407ddca05062ff4b2f13cd81d3..be142d6b7cd25a5dad9ee3ff0f01c17aeaed7348 100644 --- a/src/ui/dialog/messages.h +++ b/src/ui/dialog/messages.h @@ -17,15 +17,14 @@ #ifndef INKSCAPE_UI_DIALOG_MESSAGES_H #define INKSCAPE_UI_DIALOG_MESSAGES_H +#include <glibmm/i18n.h> #include <gtkmm/box.h> -#include <gtkmm/textview.h> #include <gtkmm/button.h> #include <gtkmm/checkbutton.h> -#include <gtkmm/menubar.h> #include <gtkmm/menu.h> +#include <gtkmm/menubar.h> #include <gtkmm/scrolledwindow.h> - -#include <glibmm/i18n.h> +#include <gtkmm/textview.h> #include "ui/widget/panel.h" @@ -33,7 +32,8 @@ namespace Inkscape { namespace UI { namespace Dialog { -class Messages : public UI::Widget::Panel { +class Messages : public UI::Widget::Panel +{ public: Messages(); ~Messages() override; @@ -63,15 +63,15 @@ public: void toggleCapture(); protected: - //Gtk::MenuBar menuBar; - //Gtk::Menu fileMenu; + // Gtk::MenuBar menuBar; + // Gtk::Menu fileMenu; Gtk::ScrolledWindow textScroll; - Gtk::TextView messageText; - Gtk::HBox buttonBox; - Gtk::Button buttonClear; - Gtk::CheckButton checkCapture; + Gtk::TextView messageText; + Gtk::HBox buttonBox; + Gtk::Button buttonClear; + Gtk::CheckButton checkCapture; - //Handler ID's + // Handler ID's guint handlerDefault; guint handlerGlibmm; guint handlerAtkmm; @@ -84,10 +84,9 @@ private: Messages operator=(Messages const &d) = delete; }; - -} //namespace Dialog -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif // INKSCAPE_UI_DIALOG_MESSAGES_H diff --git a/src/ui/dialog/new-from-template.cpp b/src/ui/dialog/new-from-template.cpp index bfccdb627ed5f7fecd2e3b9c4b1a98ae468a1e8f..98889ee04d6b75dfe4e9d2d3de8a683916ee0776 100644 --- a/src/ui/dialog/new-from-template.cpp +++ b/src/ui/dialog/new-from-template.cpp @@ -10,14 +10,13 @@ */ #include "new-from-template.h" -#include "file.h" +#include "file.h" #include "include/gtkmm_version.h" namespace Inkscape { namespace UI { - NewFromTemplate::NewFromTemplate() : _create_template_button(_("Create from template")) { @@ -27,17 +26,16 @@ NewFromTemplate::NewFromTemplate() _main_widget = new TemplateLoadTab(this); get_content_area()->pack_start(*_main_widget); - + _create_template_button.set_halign(Gtk::ALIGN_END); _create_template_button.set_valign(Gtk::ALIGN_END); _create_template_button.set_margin_end(15); get_content_area()->pack_end(_create_template_button, Gtk::PACK_SHRINK); - - _create_template_button.signal_clicked().connect( - sigc::mem_fun(*this, &NewFromTemplate::_createFromTemplate)); + + _create_template_button.signal_clicked().connect(sigc::mem_fun(*this, &NewFromTemplate::_createFromTemplate)); _create_template_button.set_sensitive(false); - + show_all(); } @@ -68,5 +66,5 @@ void NewFromTemplate::load_new_from_template() dl.run(); } -} -} +} // namespace UI +} // namespace Inkscape diff --git a/src/ui/dialog/new-from-template.h b/src/ui/dialog/new-from-template.h index a308fe4f76f9da896fdb8cf1ed4374853652a2f5..cc1a948449fbad0d18cb15ed7d643ad54aa8ef54 100644 --- a/src/ui/dialog/new-from-template.h +++ b/src/ui/dialog/new-from-template.h @@ -12,20 +12,18 @@ #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 <gtkmm/dialog.h> #include "template-load-tab.h" - namespace Inkscape { namespace UI { - class NewFromTemplate : public Gtk::Dialog { + friend class TemplateLoadTab; -friend class TemplateLoadTab; public: static void load_new_from_template(); void setCreateButtonSensitive(bool value); @@ -34,12 +32,12 @@ public: private: NewFromTemplate(); Gtk::Button _create_template_button; - TemplateLoadTab* _main_widget; - + TemplateLoadTab *_main_widget; + void _createFromTemplate(); void _onClose(); }; -} -} +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/dialog/object-attributes.cpp b/src/ui/dialog/object-attributes.cpp index 44bcf7f138527b667ca14d120d3a8f0bf894f7f4..b9ac7094a048bda07ed5191bdcb2643a3405dfa0 100644 --- a/src/ui/dialog/object-attributes.cpp +++ b/src/ui/dialog/object-attributes.cpp @@ -10,155 +10,133 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/dialog/object-attributes.h" #include <glibmm/i18n.h> #include "desktop.h" #include "inkscape.h" -#include "verbs.h" - #include "object/sp-anchor.h" #include "object/sp-image.h" - -#include "ui/dialog/object-attributes.h" #include "ui/dialog/dialog-manager.h" - +#include "verbs.h" #include "widgets/sp-attribute-widget.h" namespace Inkscape { namespace UI { namespace Dialog { -struct SPAttrDesc { +struct SPAttrDesc +{ gchar const *label; gchar const *attribute; }; static const SPAttrDesc anchor_desc[] = { - { N_("Href:"), "xlink:href"}, - { N_("Target:"), "target"}, - { N_("Type:"), "xlink:type"}, + {N_("Href:"), "xlink:href"}, + {N_("Target:"), "target"}, + {N_("Type:"), "xlink:type"}, // TRANSLATORS: for info, see http://www.w3.org/TR/2000/CR-SVG-20000802/linking.html#AElementXLinkRoleAttribute // Identifies the type of the related resource with an absolute URI - { N_("Role:"), "xlink:role"}, + {N_("Role:"), "xlink:role"}, // TRANSLATORS: for info, see http://www.w3.org/TR/2000/CR-SVG-20000802/linking.html#AElementXLinkArcRoleAttribute - // For situations where the nature/role alone isn't enough, this offers an additional URI defining the purpose of the link. - { N_("Arcrole:"), "xlink:arcrole"}, + // For situations where the nature/role alone isn't enough, this offers an additional URI defining the purpose of + // the link. + {N_("Arcrole:"), "xlink:arcrole"}, // TRANSLATORS: for info, see http://www.w3.org/TR/2000/CR-SVG-20000802/linking.html#AElementXLinkTitleAttribute - { N_("Title:"), "xlink:title"}, - { N_("Show:"), "xlink:show"}, + {N_("Title:"), "xlink:title"}, + {N_("Show:"), "xlink:show"}, // TRANSLATORS: for info, see http://www.w3.org/TR/2000/CR-SVG-20000802/linking.html#AElementXLinkActuateAttribute - { N_("Actuate:"), "xlink:actuate"}, - { nullptr, nullptr} -}; - -static const SPAttrDesc image_desc[] = { - { N_("URL:"), "xlink:href"}, - { N_("X:"), "x"}, - { N_("Y:"), "y"}, - { N_("Width:"), "width"}, - { N_("Height:"), "height"}, - { nullptr, nullptr} -}; - -static const SPAttrDesc image_nohref_desc[] = { - { N_("X:"), "x"}, - { N_("Y:"), "y"}, - { N_("Width:"), "width"}, - { N_("Height:"), "height"}, - { nullptr, nullptr} -}; - -ObjectAttributes::ObjectAttributes () : - UI::Widget::Panel("/dialogs/objectattr/", SP_VERB_DIALOG_ATTR), - blocked (false), - CurrentItem(nullptr), - attrTable(Gtk::manage(new SPAttributeTable())), - selectChangedConn(), - subselChangedConn(), - selectModifiedConn() + {N_("Actuate:"), "xlink:actuate"}, + {nullptr, nullptr}}; + +static const SPAttrDesc image_desc[] = {{N_("URL:"), "xlink:href"}, {N_("X:"), "x"}, {N_("Y:"), "y"}, + {N_("Width:"), "width"}, {N_("Height:"), "height"}, {nullptr, nullptr}}; + +static const SPAttrDesc image_nohref_desc[] = {{N_("X:"), "x"}, + {N_("Y:"), "y"}, + {N_("Width:"), "width"}, + {N_("Height:"), "height"}, + {nullptr, nullptr}}; + +ObjectAttributes::ObjectAttributes() + : UI::Widget::Panel("/dialogs/objectattr/", SP_VERB_DIALOG_ATTR) + , blocked(false) + , CurrentItem(nullptr) + , attrTable(Gtk::manage(new SPAttributeTable())) + , selectChangedConn() + , subselChangedConn() + , selectModifiedConn() { attrTable->show(); } -ObjectAttributes::~ObjectAttributes () +ObjectAttributes::~ObjectAttributes() { selectModifiedConn.disconnect(); subselChangedConn.disconnect(); selectChangedConn.disconnect(); } -void ObjectAttributes::widget_setup () +void ObjectAttributes::widget_setup() { if (blocked || !getDesktop()) { return; } - + Inkscape::Selection *selection = getDesktop()->getSelection(); SPItem *item = selection->singleItem(); - if (!item) - { - set_sensitive (false); + if (!item) { + set_sensitive(false); CurrentItem = nullptr; - //no selection anymore or multiple objects selected, means that we need - //to close the connections to the previously selected object + // no selection anymore or multiple objects selected, means that we need + // to close the connections to the previously selected object return; } - + blocked = true; // CPPIFY - SPObject *obj = 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); + SPObject *obj = 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 (SP_IS_ANCHOR(item)) - { + + // if (type == SP_TYPE_ANCHOR) + if (SP_IS_ANCHOR(item)) { desc = anchor_desc; } -// else if (type == SP_TYPE_IMAGE) - else if (SP_IS_IMAGE(item)) - { + // 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"); - if ( (!href) || ((strncmp(href, "data:", 5) == 0)) ) - { + if ((!href) || ((strncmp(href, "data:", 5) == 0))) { desc = image_nohref_desc; - } - else - { + } else { desc = image_desc; } - } - else - { + } else { blocked = false; - set_sensitive (false); + set_sensitive(false); return; } - + std::vector<Glib::ustring> labels; std::vector<Glib::ustring> attrs; - if (CurrentItem != item) - { + if (CurrentItem != item) { int len = 0; - while (desc[len].label) - { + while (desc[len].label) { labels.emplace_back(desc[len].label); attrs.emplace_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 - { + } else { attrTable->change_object(obj); } - - set_sensitive (true); + + set_sensitive(true); show_all(); blocked = false; } @@ -175,29 +153,29 @@ void ObjectAttributes::setDesktop(SPDesktop *desktop) Panel::setDesktop(desktop); if (desktop && desktop->selection) { - selectChangedConn = desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &ObjectAttributes::widget_setup))); - subselChangedConn = desktop->connectToolSubselectionChanged(sigc::hide(sigc::mem_fun(*this, &ObjectAttributes::widget_setup))); + selectChangedConn = + desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &ObjectAttributes::widget_setup))); + subselChangedConn = desktop->connectToolSubselectionChanged( + sigc::hide(sigc::mem_fun(*this, &ObjectAttributes::widget_setup))); // Must check flags, so can't call widget_setup() directly. - selectModifiedConn = desktop->selection->connectModified(sigc::hide<0>(sigc::mem_fun(*this, &ObjectAttributes::selectionModifiedCB))); + selectModifiedConn = desktop->selection->connectModified( + sigc::hide<0>(sigc::mem_fun(*this, &ObjectAttributes::selectionModifiedCB))); } widget_setup(); } } -void ObjectAttributes::selectionModifiedCB( guint flags ) +void ObjectAttributes::selectionModifiedCB(guint flags) { - if (flags & ( SP_OBJECT_MODIFIED_FLAG | - SP_OBJECT_PARENT_MODIFIED_FLAG | - SP_OBJECT_STYLE_MODIFIED_FLAG) ) { + if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG)) { attrTable->reread_properties(); } } - -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/object-attributes.h b/src/ui/dialog/object-attributes.h index 6c7d30ca437d825a561825c2ad29c47c6349fb2b..0267e5fcc8985b837bf6118dde1a28446220d2b6 100644 --- a/src/ui/dialog/object-attributes.h +++ b/src/ui/dialog/object-attributes.h @@ -25,18 +25,19 @@ namespace Dialog { /** * A dialog widget to show object attributes (currently for images and links). */ -class ObjectAttributes : public Widget::Panel { +class ObjectAttributes : public Widget::Panel +{ public: - ObjectAttributes (); - ~ObjectAttributes () override; - + ObjectAttributes(); + ~ObjectAttributes() override; + /** * Returns a new instance of the object attributes dialog. - * - * Auxiliary function needed by the DialogManager. + * + * Auxiliary function needed by the DialogManager. */ static ObjectAttributes &getInstance() { return *new ObjectAttributes(); } - + /** * Updates entries and other child widgets on selection change, object modification, etc. */ @@ -47,44 +48,44 @@ private: * Is UI update bloched? */ bool blocked; - + /** * Contains a pointer to the currently selected item (NULL in case nothing is or multiple objects are selected). */ SPItem *CurrentItem; - + /** * Child widget to show the object attributes. - * + * * attrTable makes the labels and edit boxes for the attributes defined * 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; - + /** * Link to callback function for a selection change. */ sigc::connection selectChangedConn; sigc::connection subselChangedConn; - + /** * Link to callback function for a modification of the selected object. */ sigc::connection selectModifiedConn; - + /** * Callback function invoked by the desktop tracker in case of a modification of the selected object. */ - void selectionModifiedCB( guint flags ); - - public: + void selectionModifiedCB(guint flags); + +public: void setDesktop(SPDesktop *desktop) override; }; -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/dialog/object-properties.cpp b/src/ui/dialog/object-properties.cpp index caf05f3710352a6144f75b8dabb1e0c4e5d29609..442956406063cd2691ede3a2339a902337bb78ec 100644 --- a/src/ui/dialog/object-properties.cpp +++ b/src/ui/dialog/object-properties.cpp @@ -30,19 +30,16 @@ #include "object-properties.h" #include <glibmm/i18n.h> - #include <gtkmm/grid.h> #include "desktop.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" -#include "verbs.h" -#include "style.h" -#include "style-enums.h" - #include "object/sp-image.h" - +#include "style-enums.h" +#include "style.h" +#include "verbs.h" #include "widgets/sp-attribute-widget.h" namespace Inkscape { @@ -65,7 +62,7 @@ ObjectProperties::ObjectProperties() , _attr_table(Gtk::manage(new SPAttributeTable())) , _desktop(nullptr) { - //initialize labels for the table at the bottom of the dialog + // initialize labels for the table at the bottom of the dialog _int_attrs.emplace_back("onclick"); _int_attrs.emplace_back("onmouseover"); _int_attrs.emplace_back("onmouseout"); @@ -107,7 +104,6 @@ void ObjectProperties::_init() contents->pack_start(*grid_top, false, false, 0); - /* Create the label for the object id */ _label_id.set_label(_label_id.get_label() + " "); _label_id.set_halign(Gtk::ALIGN_START); @@ -128,7 +124,6 @@ void ObjectProperties::_init() // focus is in the id field initially: _entry_id.grab_focus(); - /* Create the label for the object label */ _label_label.set_label(_label_label.get_label() + " "); _label_label.set_halign(Gtk::ALIGN_START); @@ -148,7 +143,6 @@ void ObjectProperties::_init() // pressing enter in the label field is the same as clicking Set: _entry_label.signal_activate().connect(sigc::mem_fun(this, &ObjectProperties::_labelChanged)); - /* Create the label for the object title */ _label_title.set_label(_label_title.get_label() + " "); _label_title.set_halign(Gtk::ALIGN_START); @@ -156,8 +150,8 @@ void ObjectProperties::_init() grid_top->attach(_label_title, 0, 2, 1, 1); /* Create the entry box for the object title */ - _entry_title.set_sensitive (FALSE); - _entry_title.set_max_length (256); + _entry_title.set_sensitive(FALSE); + _entry_title.set_max_length(256); _entry_title.set_hexpand(); _entry_title.set_valign(Gtk::ALIGN_CENTER); @@ -171,7 +165,7 @@ void ObjectProperties::_init() Gtk::Label *label_desc = Gtk::manage(new Gtk::Label(_("_Description:"), true)); 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); + 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 */ @@ -211,25 +205,22 @@ void ObjectProperties::_init() for (unsigned i = 0; enum_image_rendering[i].key; ++i) { _combo_image_rendering.append(enum_image_rendering[i].key); } - _combo_image_rendering.set_tooltip_text(_("The 'image-rendering' property can influence how a bitmap is re-scaled:\n" - "\t• 'auto': no preference (scaled image is usually smooth but blurred)\n" - "\t• 'optimizeQuality': prefer rendering quality (usually smooth but blurred)\n" - "\t• 'optimizeSpeed': prefer rendering speed (usually blocky)\n" - "\t• 'crisp-edges': rescale without blurring edges (often blocky)\n" - "\t• 'pixelated': render blocky\n" - "Note that the specification of this property is not finalized. " - "Support and interpretation of these values varies between renderers.")); + _combo_image_rendering.set_tooltip_text( + _("The 'image-rendering' property can influence how a bitmap is re-scaled:\n" + "\t• 'auto': no preference (scaled image is usually smooth but blurred)\n" + "\t• 'optimizeQuality': prefer rendering quality (usually smooth but blurred)\n" + "\t• 'optimizeSpeed': prefer rendering speed (usually blocky)\n" + "\t• 'crisp-edges': rescale without blurring edges (often blocky)\n" + "\t• 'pixelated': render blocky\n" + "Note that the specification of this property is not finalized. " + "Support and interpretation of these values varies between renderers.")); _combo_image_rendering.set_valign(Gtk::ALIGN_CENTER); grid_top->attach(_combo_image_rendering, 1, 4, 1, 1); _label_image_rendering.set_mnemonic_widget(_combo_image_rendering); - _combo_image_rendering.signal_changed().connect( - sigc::mem_fun(this, &ObjectProperties::_imageRenderingChanged) - ); - - + _combo_image_rendering.signal_changed().connect(sigc::mem_fun(this, &ObjectProperties::_imageRenderingChanged)); /* Check boxes */ Gtk::HBox *hb_checkboxes = Gtk::manage(new Gtk::HBox()); @@ -243,7 +234,7 @@ void ObjectProperties::_init() hb_checkboxes->pack_start(*grid_cb, true, true, 0); /* Hide */ - _cb_hide.set_tooltip_text (_("Check to make the object invisible")); + _cb_hide.set_tooltip_text(_("Check to make the object invisible")); _cb_hide.set_hexpand(); _cb_hide.set_valign(Gtk::ALIGN_CENTER); grid_cb->attach(_cb_hide, 0, 0, 1, 1); @@ -267,7 +258,6 @@ void ObjectProperties::_init() _cb_aspect_ratio.signal_toggled().connect(sigc::mem_fun(this, &ObjectProperties::_aspectRatioToggled)); - /* Button for setting the object's id, label, title and description. */ Gtk::Button *btn_set = Gtk::manage(new Gtk::Button(_("_Set"), true)); btn_set->set_hexpand(); @@ -297,28 +287,27 @@ void ObjectProperties::update() Gtk::Box *contents = _getContents(); if (!selection->singleItem()) { - contents->set_sensitive (false); + contents->set_sensitive(false); _current_item = nullptr; - //no selection anymore or multiple objects selected, means that we need - //to close the connections to the previously selected object + // no selection anymore or multiple objects selected, means that we need + // to close the connections to the previously selected object _attr_table->clear(); return; } else { - contents->set_sensitive (true); + contents->set_sensitive(true); } - + SPItem *item = selection->singleItem(); - 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 _attr_table) + 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 _attr_table) return; } _blocked = true; _cb_aspect_ratio.set_active(g_strcmp0(item->getAttribute("preserveAspectRatio"), "none") != 0); _cb_lock.set_active(item->isLocked()); /* Sensitive */ _cb_hide.set_active(item->isExplicitlyHidden()); /* Hidden */ - + if (item->cloned) { /* ID */ _entry_id.set_text(""); @@ -331,7 +320,7 @@ void ObjectProperties::update() _label_label.set_text(_("Ref")); } else { - SPObject *obj = static_cast<SPObject*>(item); + SPObject *obj = static_cast<SPObject *>(item); /* ID */ _entry_id.set_text(obj->getId() ? obj->getId() : ""); @@ -354,8 +343,7 @@ void ObjectProperties::update() if (title) { _entry_title.set_text(title); g_free(title); - } - else { + } else { _entry_title.set_text(""); } _entry_title.set_sensitive(TRUE); @@ -390,9 +378,9 @@ void ObjectProperties::update() _tv_description.get_buffer()->set_text(""); } _ft_description.set_sensitive(TRUE); - + if (_current_item == nullptr) { - _attr_table->set_object(obj, _int_labels, _int_attrs, (GtkWidget*) _exp_interactivity.gobj()); + _attr_table->set_object(obj, _int_labels, _int_attrs, (GtkWidget *)_exp_interactivity.gobj()); } else { _attr_table->change_object(obj); } @@ -407,9 +395,9 @@ void ObjectProperties::_labelChanged() if (_blocked) { return; } - + SPItem *item = SP_ACTIVE_DESKTOP->getSelection()->singleItem(); - g_return_if_fail (item != nullptr); + g_return_if_fail(item != nullptr); _blocked = true; @@ -418,7 +406,7 @@ void ObjectProperties::_labelChanged() g_strcanon(id, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.:", '_'); if (g_strcmp0(id, item->getId()) == 0) { _label_id.set_markup_with_mnemonic(_("_ID:") + Glib::ustring(" ")); - } else if (!*id || !isalnum (*id)) { + } else if (!*id || !isalnum(*id)) { _label_id.set_text(_("Id invalid! ")); } else if (SP_ACTIVE_DOCUMENT->getObjectById(id) != nullptr) { _label_id.set_text(_("Id exists! ")); @@ -437,18 +425,16 @@ void ObjectProperties::_labelChanged() /* Give feedback on success of setting the drawing object's label * using the widget's label text */ - SPObject *obj = static_cast<SPObject*>(item); + SPObject *obj = static_cast<SPObject *>(item); char const *currentlabel = obj->label(); if (label.compare(currentlabel ? currentlabel : "")) { obj->setLabel(label.c_str()); - DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, - _("Set object label")); + DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, _("Set object label")); } /* Retrieve the title */ if (obj->setTitle(_entry_title.get_text().c_str())) { - DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, - _("Set object title")); + DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, _("Set object title")); } /* Retrieve the DPI */ @@ -463,10 +449,9 @@ void ObjectProperties::_labelChanged() _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")); + DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, _("Set object description")); } - + _blocked = false; } @@ -475,9 +460,9 @@ void ObjectProperties::_imageRenderingChanged() if (_blocked) { return; } - + SPItem *item = SP_ACTIVE_DESKTOP->getSelection()->singleItem(); - g_return_if_fail (item != nullptr); + g_return_if_fail(item != nullptr); _blocked = true; @@ -489,11 +474,10 @@ void ObjectProperties::_imageRenderingChanged() Inkscape::XML::Node *image_node = item->getRepr(); if (image_node) { sp_repr_css_change(image_node, css, "style"); - DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, - _("Set image rendering option")); + DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, _("Set image rendering option")); } sp_repr_css_attr_unref(css); - + _blocked = false; } @@ -527,8 +511,7 @@ void ObjectProperties::_aspectRatioToggled() const char *active; if (_cb_aspect_ratio.get_active()) { active = "xMidYMid"; - } - else { + } else { active = "none"; } /* Retrieve the DPI */ @@ -552,7 +535,7 @@ void ObjectProperties::_hiddenToggled() _blocked = true; item->setExplicitlyHidden(_cb_hide.get_active()); DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, - _cb_hide.get_active() ? _("Hide object") : _("Unhide object")); + _cb_hide.get_active() ? _("Hide object") : _("Unhide object")); _blocked = false; } @@ -567,20 +550,18 @@ void ObjectProperties::setDesktop(SPDesktop *desktop) } this->_desktop = desktop; if (desktop && desktop->selection) { - _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)) - ); + _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))); } update(); } } -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/object-properties.h b/src/ui/dialog/object-properties.h index 6e6b9ef121657a93786eadae171436d53c3660f1..e14da3b1495e807542a3176655f5429b2eb20423 100644 --- a/src/ui/dialog/object-properties.h +++ b/src/ui/dialog/object-properties.h @@ -30,17 +30,16 @@ #ifndef SEEN_DIALOGS_ITEM_PROPERTIES_H #define SEEN_DIALOGS_ITEM_PROPERTIES_H -#include "ui/widget/panel.h" -#include "ui/widget/frame.h" - #include <gtkmm/checkbutton.h> +#include <gtkmm/comboboxtext.h> #include <gtkmm/entry.h> #include <gtkmm/expander.h> #include <gtkmm/frame.h> #include <gtkmm/spinbutton.h> #include <gtkmm/textview.h> -#include <gtkmm/comboboxtext.h> +#include "ui/widget/frame.h" +#include "ui/widget/panel.h" class SPAttributeTable; class SPDesktop; @@ -60,48 +59,49 @@ namespace Dialog { * A widget to enter an ID, label, title and description for an object. * In addition it allows to edit the properties of an object. */ -class ObjectProperties : public Widget::Panel { +class ObjectProperties : public Widget::Panel +{ public: ObjectProperties(); ~ObjectProperties() override; - + static ObjectProperties &getInstance() { return *new ObjectProperties(); } - + /// Updates entries and other child widgets on selection change, object modification, etc. void update(); private: bool _blocked; - SPItem *_current_item; //to store the current item, for not wasting resources + 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_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::Label _label_image_rendering; // the label for 'image-rendering' Gtk::ComboBoxText _combo_image_rendering; // the combo box text for 'image-rendering' - - 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::CheckButton _cb_aspect_ratio; //the preserve aspect ratio of images - - Gtk::Label _label_dpi; //the entry for the dpi value - Gtk::SpinButton _spin_dpi; //the expander for interactivity - Gtk::Expander _exp_interactivity; //the expander for interactivity - SPAttributeTable *_attr_table; //the widget for showing the on... names at the bottom - + + 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::CheckButton _cb_aspect_ratio; // the preserve aspect ratio of images + + Gtk::Label _label_dpi; // the entry for the dpi value + Gtk::SpinButton _spin_dpi; // the expander for interactivity + Gtk::Expander _exp_interactivity; // the expander for interactivity + SPAttributeTable *_attr_table; // the widget for showing the on... names at the bottom + SPDesktop *_desktop; sigc::connection _selection_changed_connection; sigc::connection _subselection_changed_connection; - + /// Constructor auxiliary function creating the child widgets. void _init(); @@ -120,13 +120,13 @@ private: /// Callback for checkbox Preserve Aspect Ratio. void _aspectRatioToggled(); - public: +public: void setDesktop(SPDesktop *desktop) override; }; -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/dialog/objects.cpp b/src/ui/dialog/objects.cpp index e42d714f146f81b262f7e40f27ffd50605354237..5daced4bc645457796a1e14f87f6384f5a2d162c 100644 --- a/src/ui/dialog/objects.cpp +++ b/src/ui/dialog/objects.cpp @@ -15,41 +15,35 @@ #include "objects.h" +#include <glibmm/main.h> #include <gtkmm/icontheme.h> #include <gtkmm/imagemenuitem.h> #include <gtkmm/separatormenuitem.h> -#include <glibmm/main.h> #include "desktop-style.h" #include "desktop.h" #include "document-undo.h" #include "document.h" #include "filter-chemistry.h" -#include "inkscape.h" -#include "layer-manager.h" -#include "shortcuts.h" -#include "verbs.h" - #include "helper/action.h" -#include "ui/icon-loader.h" - #include "include/gtkmm_version.h" - +#include "inkscape.h" +#include "layer-manager.h" #include "object/filters/blend.h" #include "object/filters/gaussian-blur.h" #include "object/sp-clippath.h" #include "object/sp-mask.h" #include "object/sp-root.h" #include "object/sp-shape.h" +#include "shortcuts.h" #include "style.h" - #include "ui/contextmenu.h" #include "ui/dialog-events.h" +#include "ui/icon-loader.h" #include "ui/icon-names.h" #include "ui/selected-color.h" #include "ui/tools-switch.h" #include "ui/tools/node-tool.h" - #include "ui/widget/canvas.h" #include "ui/widget/clipmaskicon.h" #include "ui/widget/color-notebook.h" @@ -57,7 +51,7 @@ #include "ui/widget/imagetoggler.h" #include "ui/widget/insertordericon.h" #include "ui/widget/layertypeicon.h" - +#include "verbs.h" #include "xml/node-observer.h" //#define DUMP_LAYERS 1 @@ -71,7 +65,7 @@ using Inkscape::XML::Node; /** * Gets an instance of the Objects panel */ -ObjectsPanel& ObjectsPanel::getInstance() +ObjectsPanel &ObjectsPanel::getInstance() { return *new ObjectsPanel(); } @@ -79,11 +73,12 @@ ObjectsPanel& ObjectsPanel::getInstance() /** * Column enumeration */ -enum { +enum +{ COL_VISIBLE = 1, COL_LOCKED, COL_TYPE, -// COL_INSERTORDER, + // COL_INSERTORDER, COL_CLIPMASK, COL_HIGHLIGHT }; @@ -91,7 +86,8 @@ enum { /** * Button enumeration */ -enum { +enum +{ BUTTON_NEW = 0, BUTTON_RENAME, BUTTON_TOP, @@ -108,7 +104,7 @@ enum { BUTTON_UNLOCK_ALL, BUTTON_SETCLIP, BUTTON_CLIPGROUP, -// BUTTON_SETINVCLIP, + // BUTTON_SETINVCLIP, BUTTON_UNSETCLIP, BUTTON_SETMASK, BUTTON_UNSETMASK, @@ -122,52 +118,55 @@ enum { /** * Xml node observer for observing objects in the document */ -class ObjectsPanel::ObjectWatcher : public Inkscape::XML::NodeObserver { +class ObjectsPanel::ObjectWatcher : public Inkscape::XML::NodeObserver +{ public: /** * Creates a new object watcher * @param pnl The panel to which the object watcher belongs * @param obj The object to watch */ - ObjectWatcher(ObjectsPanel* pnl, SPObject* obj) : - _pnl(pnl), - _obj(obj), - _repr(obj->getRepr()), - _highlightAttr(g_quark_from_string("inkscape:highlight-color")), - _lockedAttr(g_quark_from_string("sodipodi:insensitive")), - _labelAttr(g_quark_from_string("inkscape:label")), - _groupAttr(g_quark_from_string("inkscape:groupmode")), - _styleAttr(g_quark_from_string("style")), - _clipAttr(g_quark_from_string("clip-path")), - _maskAttr(g_quark_from_string("mask")) + ObjectWatcher(ObjectsPanel *pnl, SPObject *obj) + : _pnl(pnl) + , _obj(obj) + , _repr(obj->getRepr()) + , _highlightAttr(g_quark_from_string("inkscape:highlight-color")) + , _lockedAttr(g_quark_from_string("sodipodi:insensitive")) + , _labelAttr(g_quark_from_string("inkscape:label")) + , _groupAttr(g_quark_from_string("inkscape:groupmode")) + , _styleAttr(g_quark_from_string("style")) + , _clipAttr(g_quark_from_string("clip-path")) + , _maskAttr(g_quark_from_string("mask")) { _repr->addObserver(*this); } - ~ObjectWatcher() override { - _repr->removeObserver(*this); - } + ~ObjectWatcher() override { _repr->removeObserver(*this); } - void notifyChildAdded( Node &/*node*/, Node &/*child*/, Node */*prev*/ ) override + void notifyChildAdded(Node & /*node*/, Node & /*child*/, Node * /*prev*/) override { - if ( _pnl && _obj ) { - _pnl->_objectsChangedWrapper( _obj ); + if (_pnl && _obj) { + _pnl->_objectsChangedWrapper(_obj); } } - void notifyChildRemoved( Node &/*node*/, Node &/*child*/, Node */*prev*/ ) override + void notifyChildRemoved(Node & /*node*/, Node & /*child*/, Node * /*prev*/) override { - if ( _pnl && _obj ) { - _pnl->_objectsChangedWrapper( _obj ); + if (_pnl && _obj) { + _pnl->_objectsChangedWrapper(_obj); } } - void notifyChildOrderChanged( Node &/*node*/, Node &/*child*/, Node */*old_prev*/, Node */*new_prev*/ ) override + void notifyChildOrderChanged(Node & /*node*/, Node & /*child*/, Node * /*old_prev*/, Node * /*new_prev*/) override { - if ( _pnl && _obj ) { - _pnl->_objectsChangedWrapper( _obj ); + if (_pnl && _obj) { + _pnl->_objectsChangedWrapper(_obj); } } - void notifyContentChanged( Node &/*node*/, Util::ptr_shared /*old_content*/, Util::ptr_shared /*new_content*/ ) override {} - void notifyAttributeChanged( Node &node, GQuark name, Util::ptr_shared /*old_value*/, Util::ptr_shared /*new_value*/ ) override { + void notifyContentChanged(Node & /*node*/, Util::ptr_shared /*old_content*/, + Util::ptr_shared /*new_content*/) override + {} + void notifyAttributeChanged(Node &node, GQuark name, Util::ptr_shared /*old_value*/, + Util::ptr_shared /*new_value*/) override + { /* Weird things happen on undo! we get notified about the child being removed, but after that we still get * notified for attributes being changed on this XML node! In that case the corresponding SPObject might already * have been deleted and the pointer to might be invalid, leading to a segfault if we're not carefull. @@ -175,10 +174,11 @@ public: * _pending_update flag is set, and we will no longer process any notifyAttributeChanged() * Reproducing the crash: new document -> open objects panel -> draw freehand line -> undo -> segfault (but only * if we don't check for _pending_update) */ - if ( _pnl && (!_pnl->_pending_update) && _obj ) { - if ( name == _lockedAttr || name == _labelAttr || name == _highlightAttr || name == _groupAttr || name == _styleAttr || name == _clipAttr || name == _maskAttr ) { + if (_pnl && (!_pnl->_pending_update) && _obj) { + if (name == _lockedAttr || name == _labelAttr || name == _highlightAttr || name == _groupAttr || + name == _styleAttr || name == _clipAttr || name == _maskAttr) { _pnl->_updateObject(_obj, name == _highlightAttr); - if ( name == _styleAttr ) { + if (name == _styleAttr) { _pnl->_updateComposite(); } } @@ -188,18 +188,18 @@ public: /** * Objects panel to which this watcher belongs */ - ObjectsPanel* _pnl; - + ObjectsPanel *_pnl; + /** * The object that is being observed */ - SPObject* _obj; - + SPObject *_obj; + /** * The xml representation of the object that is being observed */ - Inkscape::XML::Node* _repr; - + Inkscape::XML::Node *_repr; + /* These are quarks which define the attributes that we are observing */ GQuark _highlightAttr; GQuark _lockedAttr; @@ -220,7 +220,6 @@ public: class ObjectsPanel::ModelColumns : public Gtk::TreeModel::ColumnRecord { public: - ModelColumns() { add(_colObject); @@ -231,11 +230,11 @@ public: add(_colHighlight); add(_colClipMask); add(_colPrevSelectionState); - //add(_colInsertOrder); + // add(_colInsertOrder); } ~ModelColumns() override = default; - Gtk::TreeModelColumn<SPItem*> _colObject; + Gtk::TreeModelColumn<SPItem *> _colObject; Gtk::TreeModelColumn<Glib::ustring> _colLabel; Gtk::TreeModelColumn<bool> _colVisible; Gtk::TreeModelColumn<bool> _colLocked; @@ -243,13 +242,13 @@ public: Gtk::TreeModelColumn<guint32> _colHighlight; Gtk::TreeModelColumn<int> _colClipMask; Gtk::TreeModelColumn<bool> _colPrevSelectionState; - //Gtk::TreeModelColumn<int> _colInsertOrder; + // Gtk::TreeModelColumn<int> _colInsertOrder; }; /** * Stylizes a button using the given icon name and tooltip */ -void ObjectsPanel::_styleButton(Gtk::Button& btn, char const* iconName, char const* tooltip) +void ObjectsPanel::_styleButton(Gtk::Button &btn, char const *iconName, char const *tooltip) { auto child = Glib::wrap(sp_get_icon_image(iconName, GTK_ICON_SIZE_SMALL_TOOLBAR)); child->show(); @@ -265,25 +264,25 @@ void ObjectsPanel::_styleButton(Gtk::Button& btn, char const* iconName, char con * @param id Button id for callback function * @return The generated menu item */ -Gtk::MenuItem& ObjectsPanel::_addPopupItem( SPDesktop *desktop, unsigned int code, int id ) +Gtk::MenuItem &ObjectsPanel::_addPopupItem(SPDesktop *desktop, unsigned int code, int id) { - Verb *verb = Verb::get( code ); + Verb *verb = Verb::get(code); g_assert(verb); SPAction *action = verb->get_action(Inkscape::ActionContext(desktop)); - Gtk::MenuItem* item = Gtk::manage(new Gtk::MenuItem()); + Gtk::MenuItem *item = Gtk::manage(new Gtk::MenuItem()); Gtk::Label *label = Gtk::manage(new Gtk::Label(action->name, true)); label->set_xalign(0.0); if (_show_contextmenu_icons && action->image) { - item->set_name("ImageMenuItem"); // custom name to identify our "ImageMenuItems" + item->set_name("ImageMenuItem"); // custom name to identify our "ImageMenuItems" Gtk::Image *icon = Gtk::manage(sp_get_icon_image(action->image, Gtk::ICON_SIZE_MENU)); // Create a box to hold icon and label as Gtk::MenuItem derives from GtkBin and can only hold one child Gtk::Box *box = Gtk::manage(new Gtk::Box()); box->pack_start(*icon, false, false, 0); - box->pack_start(*label, true, true, 0); + box->pack_start(*label, true, true, 0); item->add(*box); } else { item->add(*label); @@ -299,7 +298,8 @@ Gtk::MenuItem& ObjectsPanel::_addPopupItem( SPDesktop *desktop, unsigned int cod * Attach a watcher to the XML node of an item, which will signal us in case of changes to that item or node * @param item The item of which the XML node is to be watched */ -void ObjectsPanel::_addWatcher(SPItem *item) { +void ObjectsPanel::_addWatcher(SPItem *item) +{ bool used = true; // Any newly created watcher is obviously being used auto iter = _objectWatchers.find(item); if (iter == _objectWatchers.end()) { // If not found then watcher doesn't exist yet @@ -314,13 +314,14 @@ void ObjectsPanel::_addWatcher(SPItem *item) { * Delete the watchers, which signal us in case of changes to the item being watched * @param only_unused Only delete those watchers that are no longer in use */ -void ObjectsPanel::_removeWatchers(bool only_unused = false) { +void ObjectsPanel::_removeWatchers(bool only_unused = false) +{ // Delete all watchers (optionally only those which are not in use) auto iter = _objectWatchers.begin(); while (iter != _objectWatchers.end()) { bool used = (*iter).second.second; bool delete_watcher = (!only_unused) || (only_unused && !used); - if ( delete_watcher ) { + if (delete_watcher) { ObjectsPanel::ObjectWatcher *w = (*iter).second.first; delete w; iter = _objectWatchers.erase(iter); @@ -337,7 +338,8 @@ void ObjectsPanel::_removeWatchers(bool only_unused = false) { /** * Call function for asynchronous invocation of _objectsChanged */ -void ObjectsPanel::_objectsChangedWrapper(SPObject */*obj*/) { +void ObjectsPanel::_objectsChangedWrapper(SPObject * /*obj*/) +{ // We used to call _objectsChanged with a reference to _obj, // but since _obj wasn't used, I'm dropping that for now _takeAction(UPDATE_TREE); @@ -347,19 +349,19 @@ void ObjectsPanel::_objectsChangedWrapper(SPObject */*obj*/) { * Callback function for when an object changes. Essentially refreshes the entire tree * @param obj Object which was changed (currently not used as the entire tree is recreated) */ -void ObjectsPanel::_objectsChanged(SPObject */*obj*/) +void ObjectsPanel::_objectsChanged(SPObject * /*obj*/) { if (_desktop) { - //Get the current document's root and use that to enumerate the tree - SPDocument* document = _desktop->doc(); - SPRoot* root = document->getRoot(); - if ( root ) { + // Get the current document's root and use that to enumerate the tree + SPDocument *document = _desktop->doc(); + SPRoot *root = document->getRoot(); + if (root) { _selectedConnection.block(); // Will be unblocked after the queue has been processed fully _documentChangedCurrentLayer.block(); - //Clear the tree store - _store->clear(); // This will increment it's stamp, making all old iterators - _tree_cache.clear(); // invalid. So we will also clear our own cache, as well + // Clear the tree store + _store->clear(); // This will increment it's stamp, making all old iterators + _tree_cache.clear(); // invalid. So we will also clear our own cache, as well _tree_update_queue.clear(); // as any remaining update queue // Temporarily detach the TreeStore from the TreeView to slightly reduce flickering, and to speed up @@ -367,16 +369,18 @@ void ObjectsPanel::_objectsChanged(SPObject */*obj*/) // but maybe this is a bit too much effort/bloat for too little gain? _tree.unset_model(); - //Add all items recursively; we will do this asynchronously, by first filling a queue, which is rather fast - _queueObject( root, nullptr ); - //However, the processing of this queue is slow, so this is done at a low priority and in small chunks. Using - //only small chunks keeps Inkscape responsive, for example while using the spray tool. After processing each - //of the chunks, Inkscape will check if there are other tasks with a high priority, for example when user is - //spraying. If so, the sprayed objects will be added first, and the whole updating will be restarted before - //it even finished. + // Add all items recursively; we will do this asynchronously, by first filling a queue, which is rather fast + _queueObject(root, nullptr); + // However, the processing of this queue is slow, so this is done at a low priority and in small chunks. + // Using only small chunks keeps Inkscape responsive, for example while using the spray tool. After + // processing each of the chunks, Inkscape will check if there are other tasks with a high priority, for + // example when user is spraying. If so, the sprayed objects will be added first, and the whole updating + // will be restarted before it even finished. _paths_to_be_expanded.clear(); - _processQueue_sig.disconnect(); // Might be needed in case objectsChanged is called directly, and not through objectsChangedWrapper() - _processQueue_sig = Glib::signal_timeout().connect( sigc::mem_fun(*this, &ObjectsPanel::_processQueue), 0, Glib::PRIORITY_DEFAULT_IDLE+100); + _processQueue_sig.disconnect(); // Might be needed in case objectsChanged is called directly, and not + // through objectsChangedWrapper() + _processQueue_sig = Glib::signal_timeout().connect(sigc::mem_fun(*this, &ObjectsPanel::_processQueue), 0, + Glib::PRIORITY_DEFAULT_IDLE + 100); } } } @@ -386,23 +390,23 @@ void ObjectsPanel::_objectsChanged(SPObject */*obj*/) * @param obj Root object to add to the tree * @param parentRow Parent tree row (or NULL if adding to tree root) */ -void ObjectsPanel::_queueObject(SPObject* obj, Gtk::TreeModel::Row* parentRow) +void ObjectsPanel::_queueObject(SPObject *obj, Gtk::TreeModel::Row *parentRow) { bool already_expanded = false; - for(auto& child: obj->children) { + for (auto &child : obj->children) { if (SP_IS_ITEM(&child)) { - //Add the item to the tree, basically only creating an empty row in the tree view + // Add the item to the tree, basically only creating an empty row in the tree view Gtk::TreeModel::iterator iter = parentRow ? _store->prepend(parentRow->children()) : _store->prepend(); - //Add the item to a queue, so we can fill in the data in each row asynchronously - //at a later stage. See the comments in _objectsChanged() for more details + // Add the item to a queue, so we can fill in the data in each row asynchronously + // at a later stage. See the comments in _objectsChanged() for more details bool expand = SP_IS_GROUP(obj) && SP_GROUP(obj)->expanded() && (not already_expanded); _tree_update_queue.emplace_back(SP_ITEM(&child), iter, expand); already_expanded = expand || already_expanded; // We need to expand only a single child in each group - //If the item is a group, recursively add its children + // If the item is a group, recursively add its children if (SP_IS_GROUP(&child)) { Gtk::TreeModel::Row row = *iter; _queueObject(&child, &row); @@ -415,22 +419,23 @@ void ObjectsPanel::_queueObject(SPObject* obj, Gtk::TreeModel::Row* parentRow) * Walks through the queue in small chunks, and fills in the rows in the tree view accordingly * @return False if the queue has been fully emptied */ -bool ObjectsPanel::_processQueue() { +bool ObjectsPanel::_processQueue() +{ auto *desktop = getDesktop(); if (!desktop) { return false; } auto queue_iter = _tree_update_queue.begin(); - auto queue_end = _tree_update_queue.end(); + auto queue_end = _tree_update_queue.end(); int count = 0; while (queue_iter != queue_end) { - //The queue is a list of tuples; expand the tuples - SPItem *item = std::get<0>(*queue_iter); - Gtk::TreeModel::iterator iter = std::get<1>(*queue_iter); - bool expanded = std::get<2>(*queue_iter); - //Add the object to the tree view and tree cache + // The queue is a list of tuples; expand the tuples + SPItem *item = std::get<0>(*queue_iter); + Gtk::TreeModel::iterator iter = std::get<1>(*queue_iter); + bool expanded = std::get<2>(*queue_iter); + // Add the object to the tree view and tree cache _addObjectToTree(item, *iter, expanded); _tree_cache.emplace(item, *iter); @@ -444,24 +449,25 @@ bool ObjectsPanel::_processQueue() { queue_iter = _tree_update_queue.erase(queue_iter); count++; if (count == 100 && (!_tree_update_queue.empty())) { - return true; // we have not yet reached the end of the queue, so return true to keep the timeout signal alive + return true; // we have not yet reached the end of the queue, so return true to keep the timeout signal + // alive } } - //We have reached the end of the queue, and it is safe to remove any watchers + // We have reached the end of the queue, and it is safe to remove any watchers _removeWatchers(true); // ... but only remove those that are no longer in use // Now we can bring the tree view back to life safely _tree.set_model(_store); // Attach the store again to the tree view // Expand the tree; this is kept outside of _addObjectToTree() and _processQueue() to allow // temporarily detaching the store from the tree, which slightly reduces flickering - for (auto path: _paths_to_be_expanded) { + for (auto path : _paths_to_be_expanded) { _tree.expand_to_path(path); _tree.collapse_row(path); } _blockAllSignals(false); - _objectsSelected(desktop->selection); //Set the tree selection; will also invoke _checkTreeSelection() + _objectsSelected(desktop->selection); // Set the tree selection; will also invoke _checkTreeSelection() _pending_update = false; return false; // Return false to kill the timeout signal that kept calling _processQueue } @@ -472,25 +478,23 @@ bool ObjectsPanel::_processQueue() { * @param row Row where the item is residing * @param expanded True if the item is part of a group that is shown as expanded in the tree view */ -void ObjectsPanel::_addObjectToTree(SPItem* item, const Gtk::TreeModel::Row &row, bool expanded) +void ObjectsPanel::_addObjectToTree(SPItem *item, const Gtk::TreeModel::Row &row, bool expanded) { - SPGroup * group = SP_IS_GROUP(item) ? SP_GROUP(item) : nullptr; + SPGroup *group = SP_IS_GROUP(item) ? SP_GROUP(item) : nullptr; row[_model->_colObject] = item; - gchar const * label = item->label() ? item->label() : item->getId(); + gchar const *label = item->label() ? item->label() : item->getId(); row[_model->_colLabel] = label ? label : item->defaultLabel(); row[_model->_colVisible] = !item->isHidden(); row[_model->_colLocked] = !item->isSensitive(); row[_model->_colType] = group ? (group->layerMode() == SPGroup::LAYER ? 2 : 1) : 0; - row[_model->_colHighlight] = item->isHighlightSet() ? item->highlight_color() : item->highlight_color() & 0xffffff00; - row[_model->_colClipMask] = item ? ( - (item->getClipObject() ? 1 : 0) | - (item->getMaskObject() ? 2 : 0) - ) : 0; + row[_model->_colHighlight] = + item->isHighlightSet() ? item->highlight_color() : item->highlight_color() & 0xffffff00; + row[_model->_colClipMask] = item ? ((item->getClipObject() ? 1 : 0) | (item->getMaskObject() ? 2 : 0)) : 0; row[_model->_colPrevSelectionState] = false; - //row[_model->_colInsertOrder] = group ? (group->insertBottom() ? 2 : 1) : 0; + // row[_model->_colInsertOrder] = group ? (group->insertBottom() ? 2 : 1) : 0; - //If our parent object is a group and it's expanded, expand the tree + // If our parent object is a group and it's expanded, expand the tree if (expanded) { _paths_to_be_expanded.emplace_back(_store->get_path(row)); } @@ -501,29 +505,28 @@ void ObjectsPanel::_addObjectToTree(SPItem* item, const Gtk::TreeModel::Row &row * @param obj The item to update in the tree * @param recurse Whether to recurse through the item's children */ -void ObjectsPanel::_updateObject( SPObject *obj, bool recurse ) { +void ObjectsPanel::_updateObject(SPObject *obj, bool recurse) +{ Gtk::TreeModel::iterator tree_iter; if (_findInTreeCache(SP_ITEM(obj), tree_iter)) { Gtk::TreeModel::Row row = *tree_iter; - //We found our item in the tree; now update it! - SPItem * item = SP_IS_ITEM(obj) ? SP_ITEM(obj) : nullptr; - SPGroup * group = SP_IS_GROUP(obj) ? SP_GROUP(obj) : nullptr; + // We found our item in the tree; now update it! + SPItem *item = SP_IS_ITEM(obj) ? SP_ITEM(obj) : nullptr; + SPGroup *group = SP_IS_GROUP(obj) ? SP_GROUP(obj) : nullptr; - gchar const * label = obj->label() ? obj->label() : obj->getId(); + gchar const *label = obj->label() ? obj->label() : obj->getId(); row[_model->_colLabel] = label ? label : obj->defaultLabel(); row[_model->_colVisible] = item ? !item->isHidden() : false; row[_model->_colLocked] = item ? !item->isSensitive() : false; row[_model->_colType] = group ? (group->layerMode() == SPGroup::LAYER ? 2 : 1) : 0; - row[_model->_colHighlight] = item ? (item->isHighlightSet() ? item->highlight_color() : item->highlight_color() & 0xffffff00) : 0; - row[_model->_colClipMask] = item ? ( - (item->getClipObject() ? 1 : 0) | - (item->getMaskObject() ? 2 : 0) - ) : 0; - //row[_model->_colInsertOrder] = group ? (group->insertBottom() ? 2 : 1) : 0; - - if (recurse){ - for (auto& iter: obj->children) { + row[_model->_colHighlight] = + item ? (item->isHighlightSet() ? item->highlight_color() : item->highlight_color() & 0xffffff00) : 0; + row[_model->_colClipMask] = item ? ((item->getClipObject() ? 1 : 0) | (item->getMaskObject() ? 2 : 0)) : 0; + // row[_model->_colInsertOrder] = group ? (group->insertBottom() ? 2 : 1) : 0; + + if (recurse) { + for (auto &iter : obj->children) { _updateObject(&iter, recurse); } } @@ -533,15 +536,15 @@ void ObjectsPanel::_updateObject( SPObject *obj, bool recurse ) { /** * Updates the composite controls for the selected item */ -void ObjectsPanel::_updateComposite() { - if (!_blockCompositeUpdate) - { - //Set the default values +void ObjectsPanel::_updateComposite() +{ + if (!_blockCompositeUpdate) { + // Set the default values bool setValues = true; - //Get/set the values - _tree.get_selection()->selected_foreach_iter(sigc::bind<bool *>(sigc::mem_fun(*this, &ObjectsPanel::_compositingChanged), &setValues)); - + // Get/set the values + _tree.get_selection()->selected_foreach_iter( + sigc::bind<bool *>(sigc::mem_fun(*this, &ObjectsPanel::_compositingChanged), &setValues)); } } @@ -550,13 +553,12 @@ void ObjectsPanel::_updateComposite() { * @param iter Current tree item * @param setValues Whether to set the compositing values */ -void ObjectsPanel::_compositingChanged( const Gtk::TreeModel::iterator& iter, bool *setValues ) +void ObjectsPanel::_compositingChanged(const Gtk::TreeModel::iterator &iter, bool *setValues) { if (iter) { Gtk::TreeModel::Row row = *iter; SPItem *item = row[_model->_colObject]; - if (*setValues) - { + if (*setValues) { _setCompositingValues(item); *setValues = false; } @@ -567,8 +569,8 @@ void ObjectsPanel::_compositingChanged( const Gtk::TreeModel::iterator& iter, bo * Occurs when the current desktop selection changes * @param sel The current selection */ -void ObjectsPanel::_objectsSelected( Selection *sel ) { - +void ObjectsPanel::_objectsSelected(Selection *sel) +{ bool setOpacity = true; _selectedConnection.block(); @@ -577,14 +579,13 @@ void ObjectsPanel::_objectsSelected( Selection *sel ) { SPItem *item = nullptr; auto items = sel->items(); - for(auto i=items.begin(); i!=items.end(); ++i){ + for (auto i = items.begin(); i != items.end(); ++i) { item = *i; - if (setOpacity) - { + if (setOpacity) { _setCompositingValues(item); setOpacity = false; } - _updateObjectSelected(item, (*i)==items.back(), false); + _updateObjectSelected(item, (*i) == items.back(), false); } if (!item) { if (_desktop->currentLayer() && SP_IS_ITEM(_desktop->currentLayer())) { @@ -630,29 +631,31 @@ void ObjectsPanel::_setCompositingValues(SPItem *item) } SPGaussianBlur *spblur = nullptr; if (item->style->getFilter()) { - for (auto& primitive_obj: item->style->getFilter()->children) { + for (auto &primitive_obj : item->style->getFilter()->children) { if (!SP_IS_FILTER_PRIMITIVE(&primitive_obj)) { break; } if (SP_IS_GAUSSIANBLUR(&primitive_obj) && !spblur) { - //Get the blur value + // Get the blur value spblur = SP_GAUSSIANBLUR(&primitive_obj); } } } - //Set the blur value + // Set the blur value double blur_value = 0; if (spblur) { - Geom::OptRect bbox = item->bounds(SPItem::GEOMETRIC_BBOX); // calculating the bbox is expensive; only do this if we have an spblur in the first place + Geom::OptRect bbox = item->bounds(SPItem::GEOMETRIC_BBOX); // calculating the bbox is expensive; only do this if + // we have an spblur in the first place if (bbox) { - double perimeter = bbox->dimensions()[Geom::X] + bbox->dimensions()[Geom::Y]; // fixme: this is only half the perimeter, is that correct? + double perimeter = bbox->dimensions()[Geom::X] + + bbox->dimensions()[Geom::Y]; // fixme: this is only half the perimeter, is that correct? blur_value = spblur->stdDeviation.getNumber() * 400 / perimeter; } } _filter_modifier.set_blur_value(blur_value); - //Unblock connections + // Unblock connections _isolationConnection.unblock(); _blurConnection.unblock(); _blendConnection.unblock(); @@ -666,15 +669,15 @@ void ObjectsPanel::_setCompositingValues(SPItem *item) * @param tree_iter Tree_iter will point to the row in which the tree item was found * @return True if found */ -bool ObjectsPanel::_findInTreeCache(SPItem* item, Gtk::TreeModel::iterator &tree_iter) { +bool ObjectsPanel::_findInTreeCache(SPItem *item, Gtk::TreeModel::iterator &tree_iter) +{ if (not item) { return false; } try { tree_iter = _tree_cache.at(item); - } - catch (std::out_of_range) { + } catch (std::out_of_range) { // Apparently, item cannot be found in the tree_cache, which could mean that // - the tree and/or tree_cache are out-dated or in the process of being updated. // - a layer is selected, which is not visible in the objects panel (see _objectsSelected()) @@ -695,22 +698,21 @@ bool ObjectsPanel::_findInTreeCache(SPItem* item, Gtk::TreeModel::iterator &tree return true; } - /** * Find the specified item in the tree store and (de)select it, optionally scrolling to the item * @param item Item to select in the tree * @param scrollto Whether to scroll to the item * @param expand If true, the path in the tree towards item will be expanded */ -void ObjectsPanel::_updateObjectSelected(SPItem* item, bool scrollto, bool expand) +void ObjectsPanel::_updateObjectSelected(SPItem *item, bool scrollto, bool expand) { Gtk::TreeModel::iterator tree_iter; if (_findInTreeCache(item, tree_iter)) { Gtk::TreeModel::Row row = *tree_iter; - //We found the item! Expand to the path and select it in the tree. + // We found the item! Expand to the path and select it in the tree. Gtk::TreePath path = _store->get_path(tree_iter); - _tree.expand_to_path( path ); + _tree.expand_to_path(path); if (!expand) // but don't expand itself, just the path _tree.collapse_row(path); @@ -720,7 +722,7 @@ void ObjectsPanel::_updateObjectSelected(SPItem* item, bool scrollto, bool expan select->select(tree_iter); row[_model->_colPrevSelectionState] = true; if (scrollto) { - //Scroll to the item in the tree + // Scroll to the item in the tree _tree.scroll_to_row(path, 0.5); } } @@ -731,22 +733,24 @@ void ObjectsPanel::_updateObjectSelected(SPItem* item, bool scrollto, bool expan */ void ObjectsPanel::_pushTreeSelectionToCurrent() { - if ( _desktop && _desktop->currentRoot() ) { - //block connections for selection and compositing values to prevent interference + if (_desktop && _desktop->currentRoot()) { + // block connections for selection and compositing values to prevent interference _selectionChangedConnection.block(); _documentChangedCurrentLayer.block(); - //Clear the selection and then iterate over the tree selection, pushing each item to the desktop + // Clear the selection and then iterate over the tree selection, pushing each item to the desktop _desktop->selection->clear(); if (_tree.get_selection()->count_selected_rows() == 0) { _store->foreach_iter(sigc::mem_fun(*this, &ObjectsPanel::_clearPrevSelectionState)); } bool setOpacity = true; bool first_pass = true; - _store->foreach_iter(sigc::bind<bool *>(sigc::mem_fun(*this, &ObjectsPanel::_selectItemCallback), &setOpacity, &first_pass)); + _store->foreach_iter( + sigc::bind<bool *>(sigc::mem_fun(*this, &ObjectsPanel::_selectItemCallback), &setOpacity, &first_pass)); first_pass = false; - _store->foreach_iter(sigc::bind<bool *>(sigc::mem_fun(*this, &ObjectsPanel::_selectItemCallback), &setOpacity, &first_pass)); + _store->foreach_iter( + sigc::bind<bool *>(sigc::mem_fun(*this, &ObjectsPanel::_selectItemCallback), &setOpacity, &first_pass)); - //unblock connections, unless we were already blocking them beforehand + // unblock connections, unless we were already blocking them beforehand _selectionChangedConnection.unblock(); _documentChangedCurrentLayer.unblock(); @@ -759,38 +763,41 @@ void ObjectsPanel::_pushTreeSelectionToCurrent() * @param iter Current tree item * @param setCompositingValues Whether to set the compositing values */ -bool ObjectsPanel::_selectItemCallback(const Gtk::TreeModel::iterator& iter, bool *setCompositingValues, bool *first_pass) +bool ObjectsPanel::_selectItemCallback(const Gtk::TreeModel::iterator &iter, bool *setCompositingValues, + bool *first_pass) { Gtk::TreeModel::Row row = *iter; bool selected = _tree.get_selection()->is_selected(iter); if (selected) { // All items selected in the treeview will be added to the current selection - /* Adding/removing only the items that were selected or deselected since the previous call to _pushTreeSelectionToCurrent() - * is very slow on large documents, because _desktop->selection->remove(item) needs to traverse the whole ObjectSet to find - * the item to be removed. When all N objects are selected in a document, clearing the whole selection would require O(N^2) - * That's why we simply clear the complete selection using _desktop->selection->clear(), and re-add all items one by one. - * This is much faster. + /* Adding/removing only the items that were selected or deselected since the previous call to + * _pushTreeSelectionToCurrent() is very slow on large documents, because _desktop->selection->remove(item) + * needs to traverse the whole ObjectSet to find the item to be removed. When all N objects are selected in a + * document, clearing the whole selection would require O(N^2) That's why we simply clear the complete selection + * using _desktop->selection->clear(), and re-add all items one by one. This is much faster. */ - /* On the first pass, we will add only the items that were selected before too. Then, on the second pass, we will add the - * newly selected items such that the last selected items will be actually last. This is needed for example when the user - * wants to align relative to the last selected item. + /* On the first pass, we will add only the items that were selected before too. Then, on the second pass, we + * will add the newly selected items such that the last selected items will be actually last. This is needed for + * example when the user wants to align relative to the last selected item. */ if (*first_pass == row[_model->_colPrevSelectionState]) { SPItem *item = row[_model->_colObject]; if (!SP_IS_GROUP(item) || SP_GROUP(item)->layerMode() != SPGroup::LAYER) { - //If the item is not a layer, then select it and set the current layer to its parent (if it's the first item) + // If the item is not a layer, then select it and set the current layer to its parent (if it's the first + // item) if (_desktop->selection->isEmpty()) { _desktop->setCurrentLayer(item->parent); } _desktop->selection->add(item); } else { - //If the item is a layer, set the current layer + // If the item is a layer, set the current layer if (_desktop->selection->isEmpty()) { _desktop->setCurrentLayer(item); } } if (*setCompositingValues) { - //Only set the compositing values for the first item <-- TODO: We have this comment here, but this has not actually been implemented? + // Only set the compositing values for the first item <-- TODO: We have this comment here, but this has + // not actually been implemented? _setCompositingValues(item); *setCompositingValues = false; } @@ -804,7 +811,8 @@ bool ObjectsPanel::_selectItemCallback(const Gtk::TreeModel::iterator& iter, boo return false; } -bool ObjectsPanel::_clearPrevSelectionState( const Gtk::TreeModel::iterator& iter) { +bool ObjectsPanel::_clearPrevSelectionState(const Gtk::TreeModel::iterator &iter) +{ Gtk::TreeModel::Row row = *iter; row[_model->_colPrevSelectionState] = false; return false; @@ -816,21 +824,22 @@ bool ObjectsPanel::_clearPrevSelectionState( const Gtk::TreeModel::iterator& ite void ObjectsPanel::_checkTreeSelection() { bool sensitive = _tree.get_selection()->count_selected_rows() > 0; - //TODO: top/bottom sensitivity + // TODO: top/bottom sensitivity bool sensitiveNonTop = true; bool sensitiveNonBottom = true; - for (auto & it : _watching) { - it->set_sensitive( sensitive ); + for (auto &it : _watching) { + it->set_sensitive(sensitive); } - for (auto & it : _watchingNonTop) { - it->set_sensitive( sensitiveNonTop ); + for (auto &it : _watchingNonTop) { + it->set_sensitive(sensitiveNonTop); } - for (auto & it : _watchingNonBottom) { - it->set_sensitive( sensitiveNonBottom ); + for (auto &it : _watchingNonBottom) { + it->set_sensitive(sensitiveNonBottom); } - _tree.set_reorderable(sensitive); // Reorderable means that we allow drag-and-drop, but we only allow that when at least one row is selected + _tree.set_reorderable(sensitive); // Reorderable means that we allow drag-and-drop, but we only allow that when at + // least one row is selected } /** @@ -838,13 +847,12 @@ void ObjectsPanel::_checkTreeSelection() * @param iter Current item in the tree * @param visible Whether the item should be visible or not */ -void ObjectsPanel::_setVisibleIter( const Gtk::TreeModel::iterator& iter, const bool visible ) +void ObjectsPanel::_setVisibleIter(const Gtk::TreeModel::iterator &iter, const bool visible) { Gtk::TreeModel::Row row = *iter; - SPItem* item = row[_model->_colObject]; - if (item) - { - item->setHidden( !visible ); + SPItem *item = row[_model->_colObject]; + if (item) { + item->setHidden(!visible); row[_model->_colVisible] = visible; item->updateRepr(SP_OBJECT_WRITE_NO_CHILDREN | SP_OBJECT_WRITE_EXT); } @@ -855,13 +863,12 @@ void ObjectsPanel::_setVisibleIter( const Gtk::TreeModel::iterator& iter, const * @param iter Current item in the tree * @param locked Whether the item should be locked */ -void ObjectsPanel::_setLockedIter( const Gtk::TreeModel::iterator& iter, const bool locked ) +void ObjectsPanel::_setLockedIter(const Gtk::TreeModel::iterator &iter, const bool locked) { Gtk::TreeModel::Row row = *iter; - SPItem* item = row[_model->_colObject]; - if (item) - { - item->setLocked( locked ); + SPItem *item = row[_model->_colObject]; + if (item) { + item->setLocked(locked); row[_model->_colLocked] = locked; item->updateRepr(SP_OBJECT_WRITE_NO_CHILDREN | SP_OBJECT_WRITE_EXT); } @@ -907,14 +914,13 @@ bool ObjectsPanel::_handleKeyEvent(GdkEventKey *event) switch (Inkscape::UI::Tools::get_latin_keyval(event)) { case GDK_KEY_Return: - case GDK_KEY_KP_Enter: - { + case GDK_KEY_KP_Enter: { Gtk::TreeModel::Path path; Gtk::TreeViewColumn *focus_column = nullptr; _tree.get_cursor(path, focus_column); if (focus_column == _name_column && !_text_renderer->property_editable()) { - //Rename item + // Rename item _text_renderer->property_editable() = true; _tree.set_cursor(path, *_name_column, true); grab_focus(); @@ -932,17 +938,17 @@ bool ObjectsPanel::_handleKeyEvent(GdkEventKey *event) * @param event Mouse event from GDK * @return whether to eat the event (om nom nom) */ -bool ObjectsPanel::_handleButtonEvent(GdkEventButton* event) +bool ObjectsPanel::_handleButtonEvent(GdkEventButton *event) { static unsigned doubleclick = 0; static bool overVisible = false; - //Right mouse button was clicked, launch the pop-up menu - if ( (event->type == GDK_BUTTON_PRESS) && (event->button == 3) ) { + // Right mouse button was clicked, launch the pop-up menu + if ((event->type == GDK_BUTTON_PRESS) && (event->button == 3)) { 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 ) ) { + if (_tree.get_path_at_pos(x, y, path)) { _checkTreeSelection(); _popupMenu.popup_at_pointer(reinterpret_cast<GdkEvent *>(event)); @@ -952,63 +958,60 @@ bool ObjectsPanel::_handleButtonEvent(GdkEventButton* event) } } - //Left mouse button was pressed! In order to handle multiple item drag & drop, - //we need to defer selection by setting the select function so that the tree doesn't - //automatically select anything. In order to handle multiple item icon clicking, - //we need to eat the event. There might be a better way to do both of these... - if ( (event->type == GDK_BUTTON_PRESS) && (event->button == 1)) { + // Left mouse button was pressed! In order to handle multiple item drag & drop, + // we need to defer selection by setting the select function so that the tree doesn't + // automatically select anything. In order to handle multiple item icon clicking, + // we need to eat the event. There might be a better way to do both of these... + if ((event->type == GDK_BUTTON_PRESS) && (event->button == 1)) { overVisible = false; Gtk::TreeModel::Path path; - Gtk::TreeViewColumn* col = nullptr; + Gtk::TreeViewColumn *col = nullptr; 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)) { - //Click on visible column, eat this event to keep row selection + if (_tree.get_path_at_pos(x, y, path, col, x2, y2)) { + if (col == _tree.get_column(COL_VISIBLE - 1)) { + // Click on visible column, eat this event to keep row selection overVisible = true; return true; - } else if (col == _tree.get_column(COL_LOCKED-1) || - col == _tree.get_column(COL_TYPE-1) || - //col == _tree.get_column(COL_INSERTORDER - 1) || - col == _tree.get_column(COL_HIGHLIGHT-1)) { - //Click on an icon column, eat this event to keep row selection + } else if (col == _tree.get_column(COL_LOCKED - 1) || col == _tree.get_column(COL_TYPE - 1) || + // col == _tree.get_column(COL_INSERTORDER - 1) || + col == _tree.get_column(COL_HIGHLIGHT - 1)) { + // Click on an icon column, eat this event to keep row selection return true; - } else if ( !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) & _tree.get_selection()->is_selected(path) ) { - //Click on a selected item with no modifiers, defer selection to the mouse-up by - //setting the select function to _noSelection + } else if (!(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) & + _tree.get_selection()->is_selected(path)) { + // Click on a selected item with no modifiers, defer selection to the mouse-up by + // setting the select function to _noSelection _tree.get_selection()->set_select_function(sigc::mem_fun(*this, &ObjectsPanel::_noSelection)); _defer_target = path; } } } - //Restore the selection function to allow tree selection on mouse button release - if ( event->type == GDK_BUTTON_RELEASE) { + // Restore the selection function to allow tree selection on mouse button release + if (event->type == GDK_BUTTON_RELEASE) { _tree.get_selection()->set_select_function(sigc::mem_fun(*this, &ObjectsPanel::_rowSelectFunction)); } - - //CellRenderers do not have good support for dealing with multiple items, so - //we handle all events on them here - if ( (event->type == GDK_BUTTON_RELEASE) && (event->button == 1)) { + // CellRenderers do not have good support for dealing with multiple items, so + // we handle all events on them here + if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 1)) { Gtk::TreeModel::Path path; - Gtk::TreeViewColumn* col = nullptr; + Gtk::TreeViewColumn *col = nullptr; 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 (_tree.get_path_at_pos(x, y, path, col, x2, y2)) { if (_defer_target) { - //We had deferred a selection target, select it here (assuming no drag & drop) - if (_defer_target == path && !(event->x == 0 && event->y == 0)) - { + // We had deferred a selection target, select it here (assuming no drag & drop) + if (_defer_target == path && !(event->x == 0 && event->y == 0)) { _tree.set_cursor(path, *col, false); } _defer_target = Gtk::TreeModel::Path(); - } - else { + } else { 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)) { @@ -1023,70 +1026,67 @@ bool ObjectsPanel::_handleButtonEvent(GdkEventButton* event) Gtk::TreeModel::Row row = *iter; SPItem *item = row[_model->_colObject]; if (col == _tree.get_column(COL_VISIBLE - 1)) { - _desktop->toggleLayerSolo( item ); - DocumentUndo::maybeDone(_desktop->doc(), "layer:solo", SP_VERB_LAYER_SOLO, _("Toggle layer solo")); + _desktop->toggleLayerSolo(item); + DocumentUndo::maybeDone(_desktop->doc(), "layer:solo", SP_VERB_LAYER_SOLO, + _("Toggle layer solo")); } else if (col == _tree.get_column(COL_LOCKED - 1)) { - _desktop->toggleLockOtherLayers( item ); - DocumentUndo::maybeDone(_desktop->doc(), "layer:lockothers", SP_VERB_LAYER_LOCK_OTHERS, _("Lock other layers")); + _desktop->toggleLockOtherLayers(item); + DocumentUndo::maybeDone(_desktop->doc(), "layer:lockothers", SP_VERB_LAYER_LOCK_OTHERS, + _("Lock other layers")); } } } else { Gtk::TreeModel::Children::iterator iter = _tree.get_model()->get_iter(path); Gtk::TreeModel::Row row = *iter; - SPItem* item = row[_model->_colObject]; + SPItem *item = row[_model->_colObject]; if (col == _tree.get_column(COL_VISIBLE - 1)) { if (overVisible) { - //Toggle visibility + // Toggle visibility bool newValue = !row[_model->_colVisible]; - if (_tree.get_selection()->is_selected(path)) - { - //If the current row is selected, toggle the visibility - //for all selected items - _tree.get_selection()->selected_foreach_iter(sigc::bind<bool>(sigc::mem_fun(*this, &ObjectsPanel::_setVisibleIter), newValue)); - } - else - { - //If the current row is not selected, toggle just its visibility + if (_tree.get_selection()->is_selected(path)) { + // If the current row is selected, toggle the visibility + // for all selected items + _tree.get_selection()->selected_foreach_iter( + sigc::bind<bool>(sigc::mem_fun(*this, &ObjectsPanel::_setVisibleIter), newValue)); + } else { + // If the current row is not selected, toggle just its visibility row[_model->_colVisible] = newValue; item->setHidden(!newValue); item->updateRepr(SP_OBJECT_WRITE_NO_CHILDREN | SP_OBJECT_WRITE_EXT); } - DocumentUndo::done( _desktop->doc() , SP_VERB_DIALOG_OBJECTS, - newValue? _("Unhide objects") : _("Hide objects")); + DocumentUndo::done(_desktop->doc(), SP_VERB_DIALOG_OBJECTS, + newValue ? _("Unhide objects") : _("Hide objects")); overVisible = false; } } else if (col == _tree.get_column(COL_LOCKED - 1)) { - //Toggle locking + // Toggle locking bool newValue = !row[_model->_colLocked]; - if (_tree.get_selection()->is_selected(path)) - { - //If the current row is selected, toggle the sensitivity for - //all selected items - _tree.get_selection()->selected_foreach_iter(sigc::bind<bool>(sigc::mem_fun(*this, &ObjectsPanel::_setLockedIter), newValue)); - } - else - { - //If the current row is not selected, toggle just its sensitivity + if (_tree.get_selection()->is_selected(path)) { + // If the current row is selected, toggle the sensitivity for + // all selected items + _tree.get_selection()->selected_foreach_iter( + sigc::bind<bool>(sigc::mem_fun(*this, &ObjectsPanel::_setLockedIter), newValue)); + } else { + // If the current row is not selected, toggle just its sensitivity row[_model->_colLocked] = newValue; - item->setLocked( newValue ); + item->setLocked(newValue); item->updateRepr(SP_OBJECT_WRITE_NO_CHILDREN | SP_OBJECT_WRITE_EXT); } - DocumentUndo::done( _desktop->doc() , SP_VERB_DIALOG_OBJECTS, - newValue? _("Lock objects") : _("Unlock objects")); + DocumentUndo::done(_desktop->doc(), SP_VERB_DIALOG_OBJECTS, + newValue ? _("Lock objects") : _("Unlock objects")); } else if (col == _tree.get_column(COL_TYPE - 1)) { - if (SP_IS_GROUP(item)) - { - //Toggle the current item between a group and a layer - SPGroup * g = SP_GROUP(item); + if (SP_IS_GROUP(item)) { + // Toggle the current item between a group and a layer + SPGroup *g = SP_GROUP(item); bool newValue = g->layerMode() == SPGroup::LAYER; - row[_model->_colType] = newValue ? 1: 2; + row[_model->_colType] = newValue ? 1 : 2; g->setLayerMode(newValue ? SPGroup::GROUP : SPGroup::LAYER); g->updateRepr(SP_OBJECT_WRITE_NO_CHILDREN | SP_OBJECT_WRITE_EXT); - DocumentUndo::done( _desktop->doc() , SP_VERB_DIALOG_OBJECTS, - newValue? _("Layer to group") : _("Group to layer")); + DocumentUndo::done(_desktop->doc(), SP_VERB_DIALOG_OBJECTS, + newValue ? _("Layer to group") : _("Group to layer")); _pushTreeSelectionToCurrent(); } } /*else if (col == _tree.get_column(COL_INSERTORDER - 1)) { @@ -1101,26 +1101,26 @@ bool ObjectsPanel::_handleButtonEvent(GdkEventButton* event) DocumentUndo::done( _desktop->doc() , SP_VERB_DIALOG_OBJECTS, newValue? _("Set insert mode bottom") : _("Set insert mode top")); } - }*/ else if (col == _tree.get_column(COL_HIGHLIGHT - 1)) { - //Clear the highlight targets + }*/ + else if (col == _tree.get_column(COL_HIGHLIGHT - 1)) { + // Clear the highlight targets _highlight_target.clear(); - if (_tree.get_selection()->is_selected(path)) - { - //If the current item is selected, store all selected items - //in the highlight source - _tree.get_selection()->selected_foreach_iter(sigc::mem_fun(*this, &ObjectsPanel::_storeHighlightTarget)); + if (_tree.get_selection()->is_selected(path)) { + // If the current item is selected, store all selected items + // in the highlight source + _tree.get_selection()->selected_foreach_iter( + sigc::mem_fun(*this, &ObjectsPanel::_storeHighlightTarget)); } else { - //If the current item is not selected, store only it in the highlight source + // If the current item is not selected, store only it in the highlight source _storeHighlightTarget(iter); } - if (_selectedColor) - { - //Set up the color selector + if (_selectedColor) { + // Set up the color selector SPColor color; - color.set( row[_model->_colHighlight] ); + color.set(row[_model->_colHighlight]); _selectedColor->setColorAlpha(color, SP_RGBA32_A_F(row[_model->_colHighlight])); } - //Show the color selector dialog + // Show the color selector dialog _colorSelectorDialog.show(); } } @@ -1128,29 +1128,29 @@ bool ObjectsPanel::_handleButtonEvent(GdkEventButton* event) } } - //Second mouse button press, set double click status for when the mouse is released - if ( (event->type == GDK_2BUTTON_PRESS) && (event->button == 1) ) { + // Second mouse button press, set double click status for when the mouse is released + if ((event->type == GDK_2BUTTON_PRESS) && (event->button == 1)) { doubleclick = 1; } - //Double click on mouse button release, if we're over the label column, edit - //the item name - if ( event->type == GDK_BUTTON_RELEASE && doubleclick) { + // Double click on mouse button release, if we're over the label column, edit + // the item name + if (event->type == GDK_BUTTON_RELEASE && doubleclick) { doubleclick = 0; Gtk::TreeModel::Path path; - Gtk::TreeViewColumn* col = nullptr; + Gtk::TreeViewColumn *col = nullptr; 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) { + 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); + _tree.set_cursor(path, *_name_column, true); grab_focus(); } } - + return false; } @@ -1158,12 +1158,11 @@ bool ObjectsPanel::_handleButtonEvent(GdkEventButton* event) * Stores items in the highlight target vector to manipulate with the color selector * @param iter Current tree item to store */ -void ObjectsPanel::_storeHighlightTarget(const Gtk::TreeModel::iterator& iter) +void ObjectsPanel::_storeHighlightTarget(const Gtk::TreeModel::iterator &iter) { Gtk::TreeModel::Row row = *iter; - SPItem* item = row[_model->_colObject]; - if (item) - { + SPItem *item = row[_model->_colObject]; + if (item) { _highlight_target.push_back(item); } } @@ -1171,15 +1170,15 @@ void ObjectsPanel::_storeHighlightTarget(const Gtk::TreeModel::iterator& iter) /* * Drag and drop within the tree */ -bool ObjectsPanel::_handleDragDrop(const Glib::RefPtr<Gdk::DragContext>& /*context*/, int x, int y, guint /*time*/) +bool ObjectsPanel::_handleDragDrop(const Glib::RefPtr<Gdk::DragContext> & /*context*/, int x, int y, guint /*time*/) { - //Set up our defaults and clear the source vector + // Set up our defaults and clear the source vector _dnd_into = false; _dnd_target = nullptr; _dnd_source.clear(); _dnd_source_includes_layer = false; - //Add all selected items to the source vector + // Add all selected items to the source vector _tree.get_selection()->selected_foreach_iter(sigc::mem_fun(*this, &ObjectsPanel::_storeDragSource)); bool cancel_dnd = false; @@ -1224,7 +1223,7 @@ bool ObjectsPanel::_handleDragDrop(const Glib::RefPtr<Gdk::DragContext>& /*conte Gtk::TreeModel::iterator iter = _store->get_iter(target_path); if (_store->iter_is_valid(iter)) { Gtk::TreeModel::Row row = *iter; - _dnd_target = row[_model->_colObject]; //Set the drop target + _dnd_target = row[_model->_colObject]; // Set the drop target if ((pos == Gtk::TREE_VIEW_DROP_INTO_OR_BEFORE) or (pos == Gtk::TREE_VIEW_DROP_INTO_OR_AFTER)) { // Trying to drop into a layer or group if (SP_IS_GROUP(_dnd_target)) { @@ -1236,8 +1235,8 @@ bool ObjectsPanel::_handleDragDrop(const Glib::RefPtr<Gdk::DragContext>& /*conte } } // If the source selection contains a layer however, then it can not be dropped ... - bool c1 = target_path.size() > 1; // .. below the top-level - bool c2 = SP_IS_GROUP(_dnd_target) and _dnd_into; // .. or in any group (at the top level) + bool c1 = target_path.size() > 1; // .. below the top-level + bool c2 = SP_IS_GROUP(_dnd_target) and _dnd_into; // .. or in any group (at the top level) if (_dnd_source_includes_layer and (c1 or c2)) { cancel_dnd = true; } @@ -1251,17 +1250,18 @@ bool ObjectsPanel::_handleDragDrop(const Glib::RefPtr<Gdk::DragContext>& /*conte _takeAction(DRAGNDROP); } - return true; // If True: then we're signaling here that nothing needs to be done by the TreeView; we're updating ourselves.. + return true; // If True: then we're signaling here that nothing needs to be done by the TreeView; we're updating + // ourselves.. } /** * Stores all selected items as the drag source * @param iter Current tree item */ -void ObjectsPanel::_storeDragSource(const Gtk::TreeModel::iterator& iter) +void ObjectsPanel::_storeDragSource(const Gtk::TreeModel::iterator &iter) { Gtk::TreeModel::Row row = *iter; - SPItem* item = row[_model->_colObject]; + SPItem *item = row[_model->_colObject]; if (item) { _dnd_source.push_back(item); if (SP_IS_GROUP(item) && (SP_GROUP(item)->layerMode() == SPGroup::LAYER)) { @@ -1273,56 +1273,53 @@ void ObjectsPanel::_storeDragSource(const Gtk::TreeModel::iterator& iter) /* * Move a selection of items in response to a drag & drop action */ -void ObjectsPanel::_doTreeMove( ) +void ObjectsPanel::_doTreeMove() { g_assert(_desktop != nullptr); g_assert(_document != nullptr); std::vector<gchar *> idvector; - //Clear the desktop selection + // Clear the desktop selection _desktop->selection->clear(); - while (!_dnd_source.empty()) - { + while (!_dnd_source.empty()) { SPItem *obj = _dnd_source.back(); _dnd_source.pop_back(); if (obj != _dnd_target) { - //Store the object id (for selection later) and move the object + // Store the object id (for selection later) and move the object idvector.push_back(g_strdup(obj->getId())); obj->moveTo(_dnd_target, _dnd_into); } } - //Select items + // Select items while (!idvector.empty()) { - //Grab the id from the vector, get the item in the document and select it - gchar * id = idvector.back(); + // Grab the id from the vector, get the item in the document and select it + gchar *id = idvector.back(); idvector.pop_back(); SPObject *obj = _document->getObjectById(id); g_free(id); if (obj && SP_IS_ITEM(obj)) { SPItem *item = SP_ITEM(obj); - if (!SP_IS_GROUP(item) || SP_GROUP(item)->layerMode() != SPGroup::LAYER) - { - if (_desktop->selection->isEmpty()) _desktop->setCurrentLayer(item->parent); + if (!SP_IS_GROUP(item) || SP_GROUP(item)->layerMode() != SPGroup::LAYER) { + if (_desktop->selection->isEmpty()) + _desktop->setCurrentLayer(item->parent); _desktop->selection->add(item); - } - else - { - if (_desktop->selection->isEmpty()) _desktop->setCurrentLayer(item); + } else { + if (_desktop->selection->isEmpty()) + _desktop->setCurrentLayer(item); } } } - DocumentUndo::done( _desktop->doc() , SP_VERB_NONE, - _("Moved objects")); + DocumentUndo::done(_desktop->doc(), SP_VERB_NONE, _("Moved objects")); } /** * Prevents the treeview from emiting and responding to most signals; needed when it's not up to date */ -void ObjectsPanel::_blockAllSignals(bool should_block = true) { - +void ObjectsPanel::_blockAllSignals(bool should_block = true) +{ // incoming signals _documentChangedCurrentLayer.block(should_block); _isolationConnection.block(should_block); @@ -1345,20 +1342,21 @@ void ObjectsPanel::_blockAllSignals(bool should_block = true) { /** * Fires the action verb */ -void ObjectsPanel::_fireAction( unsigned int code ) +void ObjectsPanel::_fireAction(unsigned int code) { - if ( _desktop ) { - Verb *verb = Verb::get( code ); - if ( verb ) { + if (_desktop) { + Verb *verb = Verb::get(code); + if (verb) { SPAction *action = verb->get_action(_desktop); - if ( action ) { - sp_action_perform( action, nullptr ); + if (action) { + sp_action_perform(action, nullptr); } } } } -bool ObjectsPanel::_executeUpdate() { +bool ObjectsPanel::_executeUpdate() +{ _objectsChanged(nullptr); return false; } @@ -1366,7 +1364,7 @@ bool ObjectsPanel::_executeUpdate() { /** * Executes the given button action during the idle time */ -void ObjectsPanel::_takeAction( int val ) +void ObjectsPanel::_takeAction(int val) { if (val == UPDATE_TREE) { _pending_update = true; @@ -1377,16 +1375,17 @@ void ObjectsPanel::_takeAction( int val ) _blockAllSignals(true); //_store->clear(); _tree_cache.clear(); - _executeUpdate_sig = Glib::signal_timeout().connect( sigc::mem_fun(*this, &ObjectsPanel::_executeUpdate), 500, Glib::PRIORITY_DEFAULT_IDLE+50); + _executeUpdate_sig = Glib::signal_timeout().connect(sigc::mem_fun(*this, &ObjectsPanel::_executeUpdate), 500, + Glib::PRIORITY_DEFAULT_IDLE + 50); // In the spray tool, updating the tree competes in priority with the redrawing of the canvas, // see SPCanvas::addIdle(), which is set to UPDATE_PRIORITY (=G_PRIORITY_DEFAULT_IDLE). We // should take a lower priority (= higher value) to keep the spray tool updating longer, and to prevent // the objects-panel from clogging the processor; however, once the spraying slows down, the tree might // get updated anyway. - } else if ( !_pending ) { + } else if (!_pending) { _pending = new InternalUIBounce(); _pending->_actionCode = val; - _pending->_signal = Glib::signal_timeout().connect( sigc::mem_fun(*this, &ObjectsPanel::_executeAction), 0 ); + _pending->_signal = Glib::signal_timeout().connect(sigc::mem_fun(*this, &ObjectsPanel::_executeAction), 0); } } @@ -1396,174 +1395,110 @@ void ObjectsPanel::_takeAction( int val ) bool ObjectsPanel::_executeAction() { // Make sure selected layer hasn't changed since the action was triggered - if ( _document && _pending) - { + if (_document && _pending) { int val = _pending->_actionCode; -// SPObject* target = _pending->_target; - - switch ( val ) { - case BUTTON_NEW: - { - _fireAction( SP_VERB_LAYER_NEW ); - } - break; - case BUTTON_RENAME: - { - _fireAction( SP_VERB_LAYER_RENAME ); - } - break; - case BUTTON_TOP: - { - if (_desktop->selection->isEmpty()) - { - _fireAction( SP_VERB_LAYER_TO_TOP ); - } - else - { - _fireAction( SP_VERB_SELECTION_TO_FRONT); - } - } - break; - case BUTTON_BOTTOM: - { - if (_desktop->selection->isEmpty()) - { - _fireAction( SP_VERB_LAYER_TO_BOTTOM ); - } - else - { - _fireAction( SP_VERB_SELECTION_TO_BACK); - } - } - break; - case BUTTON_UP: - { - if (_desktop->selection->isEmpty()) - { - _fireAction( SP_VERB_LAYER_RAISE ); - } - else - { - _fireAction( SP_VERB_SELECTION_STACK_UP ); - } - } - break; - case BUTTON_DOWN: - { - if (_desktop->selection->isEmpty()) - { - _fireAction( SP_VERB_LAYER_LOWER ); + // SPObject* target = _pending->_target; + + switch (val) { + case BUTTON_NEW: { + _fireAction(SP_VERB_LAYER_NEW); + } break; + case BUTTON_RENAME: { + _fireAction(SP_VERB_LAYER_RENAME); + } break; + case BUTTON_TOP: { + if (_desktop->selection->isEmpty()) { + _fireAction(SP_VERB_LAYER_TO_TOP); + } else { + _fireAction(SP_VERB_SELECTION_TO_FRONT); } - else - { - _fireAction( SP_VERB_SELECTION_STACK_DOWN ); + } break; + case BUTTON_BOTTOM: { + if (_desktop->selection->isEmpty()) { + _fireAction(SP_VERB_LAYER_TO_BOTTOM); + } else { + _fireAction(SP_VERB_SELECTION_TO_BACK); } - } - break; - case BUTTON_DUPLICATE: - { - if (_desktop->selection->isEmpty()) - { - _fireAction( SP_VERB_LAYER_DUPLICATE ); + } break; + case BUTTON_UP: { + if (_desktop->selection->isEmpty()) { + _fireAction(SP_VERB_LAYER_RAISE); + } else { + _fireAction(SP_VERB_SELECTION_STACK_UP); } - else - { - _fireAction( SP_VERB_EDIT_DUPLICATE ); + } break; + case BUTTON_DOWN: { + if (_desktop->selection->isEmpty()) { + _fireAction(SP_VERB_LAYER_LOWER); + } else { + _fireAction(SP_VERB_SELECTION_STACK_DOWN); } - } - break; - case BUTTON_DELETE: - { - if (_desktop->selection->isEmpty()) - { - _fireAction( SP_VERB_LAYER_DELETE ); + } break; + case BUTTON_DUPLICATE: { + if (_desktop->selection->isEmpty()) { + _fireAction(SP_VERB_LAYER_DUPLICATE); + } else { + _fireAction(SP_VERB_EDIT_DUPLICATE); } - else - { - _fireAction( SP_VERB_EDIT_DELETE ); + } break; + case BUTTON_DELETE: { + if (_desktop->selection->isEmpty()) { + _fireAction(SP_VERB_LAYER_DELETE); + } else { + _fireAction(SP_VERB_EDIT_DELETE); } + } break; + case BUTTON_SOLO: { + _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 BUTTON_CLIPGROUP: { + _fireAction(SP_VERB_OBJECT_CREATE_CLIP_GROUP); } - break; - case BUTTON_SOLO: - { - _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 BUTTON_CLIPGROUP: - { - _fireAction ( SP_VERB_OBJECT_CREATE_CLIP_GROUP ); - } - case BUTTON_SETCLIP: - { - _fireAction( SP_VERB_OBJECT_SET_CLIPPATH ); - } - break; - case BUTTON_UNSETCLIP: - { - _fireAction( SP_VERB_OBJECT_UNSET_CLIPPATH ); - } - break; - case BUTTON_SETMASK: - { - _fireAction( SP_VERB_OBJECT_SET_MASK ); - } - break; - case BUTTON_UNSETMASK: - { - _fireAction( SP_VERB_OBJECT_UNSET_MASK ); - } - break; - case BUTTON_GROUP: - { - _fireAction( SP_VERB_SELECTION_GROUP ); - } - break; - case BUTTON_UNGROUP: - { - _fireAction( SP_VERB_SELECTION_UNGROUP ); - } - break; - case BUTTON_COLLAPSE_ALL: - { - for (auto& obj: _document->getRoot()->children) { + case BUTTON_SETCLIP: { + _fireAction(SP_VERB_OBJECT_SET_CLIPPATH); + } break; + case BUTTON_UNSETCLIP: { + _fireAction(SP_VERB_OBJECT_UNSET_CLIPPATH); + } break; + case BUTTON_SETMASK: { + _fireAction(SP_VERB_OBJECT_SET_MASK); + } break; + case BUTTON_UNSETMASK: { + _fireAction(SP_VERB_OBJECT_UNSET_MASK); + } break; + case BUTTON_GROUP: { + _fireAction(SP_VERB_SELECTION_GROUP); + } break; + case BUTTON_UNGROUP: { + _fireAction(SP_VERB_SELECTION_UNGROUP); + } break; + case BUTTON_COLLAPSE_ALL: { + for (auto &obj : _document->getRoot()->children) { if (SP_IS_GROUP(&obj)) { _setCollapsed(SP_GROUP(&obj)); } } _objectsChanged(_document->getRoot()); - } - break; - case DRAGNDROP: - { - _doTreeMove( ); + } break; + case DRAGNDROP: { + _doTreeMove(); // The notifyChildOrderChanged signal will ensure that the TreeView gets updated - } - break; + } break; } delete _pending; @@ -1586,7 +1521,7 @@ void ObjectsPanel::_handleEditingCancelled() * @param path Tree path of the item currently being edited * @param new_text New label text */ -void ObjectsPanel::_handleEdited(const Glib::ustring& path, const Glib::ustring& new_text) +void ObjectsPanel::_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; @@ -1600,16 +1535,15 @@ void ObjectsPanel::_handleEdited(const Glib::ustring& path, const Glib::ustring& * @param row Tree row * @param name New label to give to the item */ -void ObjectsPanel::_renameObject(Gtk::TreeModel::Row row, const Glib::ustring& name) +void ObjectsPanel::_renameObject(Gtk::TreeModel::Row row, const Glib::ustring &name) { - if ( row && _desktop) { - SPItem* item = row[_model->_colObject]; - if ( item ) { - gchar const* oldLabel = item->label(); - if ( !name.empty() && (!oldLabel || name != oldLabel) ) { + if (row && _desktop) { + SPItem *item = row[_model->_colObject]; + if (item) { + gchar const *oldLabel = item->label(); + if (!name.empty() && (!oldLabel || name != oldLabel)) { item->setLabel(name.c_str()); - DocumentUndo::done( _desktop->doc() , SP_VERB_NONE, - _("Rename object")); + DocumentUndo::done(_desktop->doc(), SP_VERB_NONE, _("Rename object")); } } } @@ -1619,7 +1553,8 @@ void ObjectsPanel::_renameObject(Gtk::TreeModel::Row row, const Glib::ustring& n * A row selection function used by the tree that doesn't allow any new items to be selected. * Currently, this is used to allow multi-item drag & drop. */ -bool ObjectsPanel::_noSelection( Glib::RefPtr<Gtk::TreeModel> const & /*model*/, Gtk::TreeModel::Path const & /*path*/, bool /*currentlySelected*/ ) +bool ObjectsPanel::_noSelection(Glib::RefPtr<Gtk::TreeModel> const & /*model*/, Gtk::TreeModel::Path const & /*path*/, + bool /*currentlySelected*/) { return false; } @@ -1627,24 +1562,20 @@ bool ObjectsPanel::_noSelection( Glib::RefPtr<Gtk::TreeModel> const & /*model*/, /** * Default row selection function taken from the layers dialog */ -bool ObjectsPanel::_rowSelectFunction( Glib::RefPtr<Gtk::TreeModel> const & /*model*/, Gtk::TreeModel::Path const & /*path*/, bool currentlySelected ) +bool ObjectsPanel::_rowSelectFunction(Glib::RefPtr<Gtk::TreeModel> const & /*model*/, + Gtk::TreeModel::Path const & /*path*/, bool currentlySelected) { bool val = true; - if ( !currentlySelected && _toggleEvent ) - { - GdkEvent* event = gtk_get_current_event(); - if ( event ) { + if (!currentlySelected && _toggleEvent) { + GdkEvent *event = gtk_get_current_event(); + if (event) { // (keep these checks separate, so we know when to call gdk_event_free() - if ( event->type == GDK_BUTTON_PRESS ) { - GdkEventButton const* target = reinterpret_cast<GdkEventButton const*>(_toggleEvent); - GdkEventButton const* evtb = reinterpret_cast<GdkEventButton const*>(event); - - if ( (evtb->window == target->window) - && (evtb->send_event == target->send_event) - && (evtb->time == target->time) - && (evtb->state == target->state) - ) - { + if (event->type == GDK_BUTTON_PRESS) { + GdkEventButton const *target = reinterpret_cast<GdkEventButton const *>(_toggleEvent); + GdkEventButton const *evtb = reinterpret_cast<GdkEventButton const *>(event); + + if ((evtb->window == target->window) && (evtb->send_event == target->send_event) && + (evtb->time == target->time) && (evtb->state == target->state)) { // Ooooh! It's a magic one val = false; } @@ -1659,11 +1590,11 @@ bool ObjectsPanel::_rowSelectFunction( Glib::RefPtr<Gtk::TreeModel> const & /*mo * Sets a group to be collapsed and recursively collapses its children * @param group The group to collapse */ -void ObjectsPanel::_setCollapsed(SPGroup * group) +void ObjectsPanel::_setCollapsed(SPGroup *group) { group->setExpanded(false); group->updateRepr(SP_OBJECT_WRITE_NO_CHILDREN | SP_OBJECT_WRITE_EXT); - for (auto& iter: group->children) { + for (auto &iter : group->children) { if (SP_IS_GROUP(&iter)) { _setCollapsed(SP_GROUP(&iter)); } @@ -1675,22 +1606,19 @@ void ObjectsPanel::_setCollapsed(SPGroup * group) * @param iter Current tree item * @param isexpanded Whether to expand or collapse */ -void ObjectsPanel::_setExpanded(const Gtk::TreeModel::iterator& iter, const Gtk::TreeModel::Path& /*path*/, bool isexpanded) +void ObjectsPanel::_setExpanded(const Gtk::TreeModel::iterator &iter, const Gtk::TreeModel::Path & /*path*/, + bool isexpanded) { Gtk::TreeModel::Row row = *iter; - SPItem* item = row[_model->_colObject]; - if (item && SP_IS_GROUP(item)) - { - if (isexpanded) - { - //If we're expanding, simply perform the expansion + SPItem *item = row[_model->_colObject]; + if (item && SP_IS_GROUP(item)) { + if (isexpanded) { + // If we're expanding, simply perform the expansion SP_GROUP(item)->setExpanded(isexpanded); item->updateRepr(SP_OBJECT_WRITE_NO_CHILDREN | SP_OBJECT_WRITE_EXT); - } - else - { - //If we're collapsing, we need to recursively collapse, so call our helper function + } else { + // If we're collapsing, we need to recursively collapse, so call our helper function _setCollapsed(SP_GROUP(item)); } } @@ -1707,11 +1635,10 @@ void ObjectsPanel::_highlightPickerColorMod() float alpha = 0; _selectedColor->colorAlpha(color, alpha); - guint32 rgba = color.toRGBA32( alpha ); + guint32 rgba = color.toRGBA32(alpha); - //Set the highlight color for all items in the _highlight_target (all selected items) - for (auto target : _highlight_target) - { + // Set the highlight color for all items in the _highlight_target (all selected items) + for (auto target : _highlight_target) { target->setHighlightColor(rgba); target->updateRepr(SP_OBJECT_WRITE_NO_CHILDREN | SP_OBJECT_WRITE_EXT); } @@ -1733,12 +1660,11 @@ void ObjectsPanel::_opacityValueChanged() * Change the opacity of the selected items in the tree * @param iter Current tree item */ -void ObjectsPanel::_opacityChangedIter(const Gtk::TreeIter& iter) +void ObjectsPanel::_opacityChangedIter(const Gtk::TreeIter &iter) { Gtk::TreeModel::Row row = *iter; - SPItem* item = row[_model->_colObject]; - if (item) - { + SPItem *item = row[_model->_colObject]; + if (item) { item->style->opacity.set = TRUE; item->style->opacity.value = SP_SCALE24_FROM_FLOAT(_filter_modifier.get_opacity_value() / 100); item->updateRepr(SP_OBJECT_WRITE_NO_CHILDREN | SP_OBJECT_WRITE_EXT); @@ -1795,20 +1721,17 @@ void ObjectsPanel::_blendValueChanged() void ObjectsPanel::_blendChangedIter(const Gtk::TreeIter &iter) { Gtk::TreeModel::Row row = *iter; - SPItem* item = row[_model->_colObject]; - if (item) - { + SPItem *item = row[_model->_colObject]; + if (item) { // < 1.0 filter based blend removal if (!item->style->mix_blend_mode.set && item->style->filter.set && item->style->getFilter()) { remove_filter_legacy_blend(item); } item->style->mix_blend_mode.set = TRUE; - if (_filter_modifier.get_blend_mode() && - item->style->isolation.value == SP_CSS_ISOLATION_ISOLATE) - { + if (_filter_modifier.get_blend_mode() && item->style->isolation.value == SP_CSS_ISOLATION_ISOLATE) { item->style->mix_blend_mode.value = SP_CSS_BLEND_NORMAL; _filter_modifier.set_blend_mode(SP_CSS_BLEND_NORMAL, false); - } else { + } else { item->style->mix_blend_mode.value = _filter_modifier.get_blend_mode(); } item->updateRepr(SP_OBJECT_WRITE_NO_CHILDREN | SP_OBJECT_WRITE_EXT); @@ -1821,8 +1744,9 @@ void ObjectsPanel::_blendChangedIter(const Gtk::TreeIter &iter) void ObjectsPanel::_blurValueChanged() { _blockCompositeUpdate = true; - _tree.get_selection()->selected_foreach_iter(sigc::bind<double>(sigc::mem_fun(*this, &ObjectsPanel::_blurChangedIter), _filter_modifier.get_blur_value())); - DocumentUndo::maybeDone(_document, "blur", SP_VERB_DIALOG_OBJECTS, _("Set object blur")); + _tree.get_selection()->selected_foreach_iter( + sigc::bind<double>(sigc::mem_fun(*this, &ObjectsPanel::_blurChangedIter), _filter_modifier.get_blur_value())); + DocumentUndo::maybeDone(_document, "blur", SP_VERB_DIALOG_OBJECTS, _("Set object blur")); _blockCompositeUpdate = false; } @@ -1831,19 +1755,20 @@ void ObjectsPanel::_blurValueChanged() * @param iter Current tree item * @param blur Blur value to set */ -void ObjectsPanel::_blurChangedIter(const Gtk::TreeIter& iter, double blur) +void ObjectsPanel::_blurChangedIter(const Gtk::TreeIter &iter, double blur) { Gtk::TreeModel::Row row = *iter; - SPItem* item = row[_model->_colObject]; - if (item) - { - //Since blur and blend are both filters, we need to set both at the same time + SPItem *item = row[_model->_colObject]; + if (item) { + // Since blur and blend are both filters, we need to set both at the same time SPStyle *style = item->style; if (style) { Geom::OptRect bbox = item->bounds(SPItem::GEOMETRIC_BBOX); double radius; if (bbox) { - double perimeter = bbox->dimensions()[Geom::X] + bbox->dimensions()[Geom::Y]; // fixme: this is only half the perimeter, is that correct? + double perimeter = + bbox->dimensions()[Geom::X] + + bbox->dimensions()[Geom::Y]; // fixme: this is only half the perimeter, is that correct? radius = blur * perimeter / 400; } else { radius = 0; @@ -1851,13 +1776,13 @@ void ObjectsPanel::_blurChangedIter(const Gtk::TreeIter& iter, double blur) if (radius != 0) { // The modify function expects radius to be in display pixels. - Geom::Affine i2d (item->i2dt_affine()); + Geom::Affine i2d(item->i2dt_affine()); double expansion = i2d.descrim(); radius *= expansion; SPFilter *filter = modify_filter_gaussian_blur_from_item(_document, item, radius); sp_style_set_property_url(item, "filter", filter, false); } else if (item->style->filter.set && item->style->getFilter()) { - for (auto& primitive: item->style->getFilter()->children) { + for (auto &primitive : item->style->getFilter()->children) { if (!SP_IS_FILTER_PRIMITIVE(&primitive)) { break; } @@ -1878,147 +1803,149 @@ void ObjectsPanel::_blurChangedIter(const Gtk::TreeIter& iter, double blur) /** * Constructor */ -ObjectsPanel::ObjectsPanel() : - UI::Widget::Panel("/dialogs/objects", SP_VERB_DIALOG_OBJECTS), - _rootWatcher(nullptr), - _desktop(nullptr), - _document(nullptr), - _model(nullptr), - _pending(nullptr), - _pending_update(false), - _toggleEvent(nullptr), - _defer_target(), - _visibleHeader(C_("Visibility", "V")), - _lockHeader(C_("Lock", "L")), - _typeHeader(C_("Type", "T")), - _clipmaskHeader(C_("Clip and mask", "CM")), - _highlightHeader(C_("Highlight", "HL")), - _nameHeader(_("Label")), - _filter_modifier( UI::Widget::SimpleFilterModifier::ISOLATION | - UI::Widget::SimpleFilterModifier::BLEND | - UI::Widget::SimpleFilterModifier::BLUR | - UI::Widget::SimpleFilterModifier::OPACITY ), - _colorSelectorDialog("dialogs.colorpickerwindow") +ObjectsPanel::ObjectsPanel() + : UI::Widget::Panel("/dialogs/objects", SP_VERB_DIALOG_OBJECTS) + , _rootWatcher(nullptr) + , _desktop(nullptr) + , _document(nullptr) + , _model(nullptr) + , _pending(nullptr) + , _pending_update(false) + , _toggleEvent(nullptr) + , _defer_target() + , _visibleHeader(C_("Visibility", "V")) + , _lockHeader(C_("Lock", "L")) + , _typeHeader(C_("Type", "T")) + , _clipmaskHeader(C_("Clip and mask", "CM")) + , _highlightHeader(C_("Highlight", "HL")) + , _nameHeader(_("Label")) + , _filter_modifier(UI::Widget::SimpleFilterModifier::ISOLATION | UI::Widget::SimpleFilterModifier::BLEND | + UI::Widget::SimpleFilterModifier::BLUR | UI::Widget::SimpleFilterModifier::OPACITY) + , _colorSelectorDialog("dialogs.colorpickerwindow") { - //Create the tree model and store + // Create the tree model and store ModelColumns *zoop = new ModelColumns(); _model = zoop; - _store = Gtk::TreeStore::create( *zoop ); + _store = Gtk::TreeStore::create(*zoop); - //Set up the tree - _tree.set_model( _store ); + // Set up the tree + _tree.set_model(_store); _tree.set_headers_visible(true); - _tree.set_reorderable(false); // Reorderable means that we allow drag-and-drop, but we only allow that when at least one row is selected - _tree.enable_model_drag_dest (Gdk::ACTION_MOVE); - - //Create the column CellRenderers - //Visible - Inkscape::UI::Widget::ImageToggler *eyeRenderer = Gtk::manage( new Inkscape::UI::Widget::ImageToggler( - INKSCAPE_ICON("object-visible"), INKSCAPE_ICON("object-hidden")) ); + _tree.set_reorderable(false); // Reorderable means that we allow drag-and-drop, but we only allow that when at least + // one row is selected + _tree.enable_model_drag_dest(Gdk::ACTION_MOVE); + + // Create the column CellRenderers + // Visible + Inkscape::UI::Widget::ImageToggler *eyeRenderer = Gtk::manage( + new Inkscape::UI::Widget::ImageToggler(INKSCAPE_ICON("object-visible"), INKSCAPE_ICON("object-hidden"))); int visibleColNum = _tree.append_column("vis", *eyeRenderer) - 1; eyeRenderer->property_activatable() = true; - Gtk::TreeViewColumn* col = _tree.get_column(visibleColNum); - if ( col ) { - col->add_attribute( eyeRenderer->property_active(), _model->_colVisible ); + Gtk::TreeViewColumn *col = _tree.get_column(visibleColNum); + if (col) { + col->add_attribute(eyeRenderer->property_active(), _model->_colVisible); // In order to get tooltips on header, we must create our own label. _visibleHeader.set_tooltip_text(_("Toggle visibility of Layer, Group, or Object.")); _visibleHeader.show(); - col->set_widget( _visibleHeader ); + col->set_widget(_visibleHeader); } - //Locked - Inkscape::UI::Widget::ImageToggler * renderer = Gtk::manage( new Inkscape::UI::Widget::ImageToggler( - INKSCAPE_ICON("object-locked"), INKSCAPE_ICON("object-unlocked")) ); + // Locked + Inkscape::UI::Widget::ImageToggler *renderer = Gtk::manage( + new Inkscape::UI::Widget::ImageToggler(INKSCAPE_ICON("object-locked"), INKSCAPE_ICON("object-unlocked"))); int lockedColNum = _tree.append_column("lock", *renderer) - 1; renderer->property_activatable() = true; col = _tree.get_column(lockedColNum); - if ( col ) { - col->add_attribute( renderer->property_active(), _model->_colLocked ); + if (col) { + col->add_attribute(renderer->property_active(), _model->_colLocked); _lockHeader.set_tooltip_text(_("Toggle lock of Layer, Group, or Object.")); _lockHeader.show(); - col->set_widget( _lockHeader ); + col->set_widget(_lockHeader); } - - //Type - Inkscape::UI::Widget::LayerTypeIcon * typeRenderer = Gtk::manage( new Inkscape::UI::Widget::LayerTypeIcon()); + + // Type + Inkscape::UI::Widget::LayerTypeIcon *typeRenderer = Gtk::manage(new Inkscape::UI::Widget::LayerTypeIcon()); int typeColNum = _tree.append_column("type", *typeRenderer) - 1; typeRenderer->property_activatable() = true; col = _tree.get_column(typeColNum); - if ( col ) { - col->add_attribute( typeRenderer->property_active(), _model->_colType ); - _typeHeader.set_tooltip_text(_("Type: Layer, Group, or Object. Clicking on Layer or Group icon, toggles between the two types.")); + if (col) { + col->add_attribute(typeRenderer->property_active(), _model->_colType); + _typeHeader.set_tooltip_text( + _("Type: Layer, Group, or Object. Clicking on Layer or Group icon, toggles between the two types.")); _typeHeader.show(); - col->set_widget( _typeHeader ); + col->set_widget(_typeHeader); } - //Insert order (LiamW: unused) - /*Inkscape::UI::Widget::InsertOrderIcon * insertRenderer = Gtk::manage( new Inkscape::UI::Widget::InsertOrderIcon()); - int insertColNum = _tree.append_column("type", *insertRenderer) - 1; - col = _tree.get_column(insertColNum); - if ( col ) { - col->add_attribute( insertRenderer->property_active(), _model->_colInsertOrder ); + // Insert order (LiamW: unused) + /*Inkscape::UI::Widget::InsertOrderIcon * insertRenderer = Gtk::manage( new + Inkscape::UI::Widget::InsertOrderIcon()); int insertColNum = _tree.append_column("type", *insertRenderer) - 1; col = + _tree.get_column(insertColNum); if ( col ) { col->add_attribute( insertRenderer->property_active(), + _model->_colInsertOrder ); }*/ - - //Clip/mask - Inkscape::UI::Widget::ClipMaskIcon * clipRenderer = Gtk::manage( new Inkscape::UI::Widget::ClipMaskIcon()); + + // Clip/mask + Inkscape::UI::Widget::ClipMaskIcon *clipRenderer = Gtk::manage(new Inkscape::UI::Widget::ClipMaskIcon()); int clipColNum = _tree.append_column("clipmask", *clipRenderer) - 1; col = _tree.get_column(clipColNum); - if ( col ) { - col->add_attribute( clipRenderer->property_active(), _model->_colClipMask ); + if (col) { + col->add_attribute(clipRenderer->property_active(), _model->_colClipMask); _clipmaskHeader.set_tooltip_text(_("Is object clipped and/or masked?")); _clipmaskHeader.show(); - col->set_widget( _clipmaskHeader ); + col->set_widget(_clipmaskHeader); } - - //Highlight - Inkscape::UI::Widget::HighlightPicker * highlightRenderer = Gtk::manage( new Inkscape::UI::Widget::HighlightPicker()); + + // Highlight + Inkscape::UI::Widget::HighlightPicker *highlightRenderer = Gtk::manage(new Inkscape::UI::Widget::HighlightPicker()); int highlightColNum = _tree.append_column("highlight", *highlightRenderer) - 1; col = _tree.get_column(highlightColNum); - if ( col ) { - col->add_attribute( highlightRenderer->property_active(), _model->_colHighlight ); - _highlightHeader.set_tooltip_text(_("Highlight color of outline in Node tool. Click to set. If alpha is zero, use inherited color.")); + if (col) { + col->add_attribute(highlightRenderer->property_active(), _model->_colHighlight); + _highlightHeader.set_tooltip_text( + _("Highlight color of outline in Node tool. Click to set. If alpha is zero, use inherited color.")); _highlightHeader.show(); - col->set_widget( _highlightHeader ); + col->set_widget(_highlightHeader); } - //Label + // Label _text_renderer = Gtk::manage(new Gtk::CellRendererText()); int nameColNum = _tree.append_column("Name", *_text_renderer) - 1; _name_column = _tree.get_column(nameColNum); - if( _name_column ) { + if (_name_column) { _name_column->add_attribute(_text_renderer->property_text(), _model->_colLabel); - _nameHeader.set_tooltip_text(_("Layer/Group/Object label (inkscape:label). Double-click to set. Default value is object 'id'.")); + _nameHeader.set_tooltip_text( + _("Layer/Group/Object label (inkscape:label). Double-click to set. Default value is object 'id'.")); _nameHeader.show(); - _name_column->set_widget( _nameHeader ); + _name_column->set_widget(_nameHeader); } - //Set the expander and search columns - _tree.set_expander_column( *_tree.get_column(nameColNum) ); + // Set the expander and search columns + _tree.set_expander_column(*_tree.get_column(nameColNum)); _tree.set_search_column(_model->_colLabel); // use ctrl+f to start search _tree.set_enable_search(false); - //Set up the tree selection + // Set up the tree selection _tree.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE); - _selectedConnection = _tree.get_selection()->signal_changed().connect( sigc::mem_fun(*this, &ObjectsPanel::_pushTreeSelectionToCurrent) ); - _tree.get_selection()->set_select_function( sigc::mem_fun(*this, &ObjectsPanel::_rowSelectFunction) ); - - //Set up tree signals - _tree.signal_button_press_event().connect( sigc::mem_fun(*this, &ObjectsPanel::_handleButtonEvent), false ); - _tree.signal_button_release_event().connect( sigc::mem_fun(*this, &ObjectsPanel::_handleButtonEvent), false ); - _tree.signal_key_press_event().connect( sigc::mem_fun(*this, &ObjectsPanel::_handleKeyEvent), false ); - _tree.signal_drag_drop().connect( sigc::mem_fun(*this, &ObjectsPanel::_handleDragDrop), false); - _tree.signal_row_collapsed().connect( sigc::bind<bool>(sigc::mem_fun(*this, &ObjectsPanel::_setExpanded), false)); - _tree.signal_row_expanded().connect( sigc::bind<bool>(sigc::mem_fun(*this, &ObjectsPanel::_setExpanded), true)); - - //Set up the label editing signals - _text_renderer->signal_edited().connect( sigc::mem_fun(*this, &ObjectsPanel::_handleEdited) ); - _text_renderer->signal_editing_canceled().connect( sigc::mem_fun(*this, &ObjectsPanel::_handleEditingCancelled) ); - - //Set up the scroller window and pack the page - _scroller.add( _tree ); - _scroller.set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC ); + _selectedConnection = _tree.get_selection()->signal_changed().connect( + sigc::mem_fun(*this, &ObjectsPanel::_pushTreeSelectionToCurrent)); + _tree.get_selection()->set_select_function(sigc::mem_fun(*this, &ObjectsPanel::_rowSelectFunction)); + + // Set up tree signals + _tree.signal_button_press_event().connect(sigc::mem_fun(*this, &ObjectsPanel::_handleButtonEvent), false); + _tree.signal_button_release_event().connect(sigc::mem_fun(*this, &ObjectsPanel::_handleButtonEvent), false); + _tree.signal_key_press_event().connect(sigc::mem_fun(*this, &ObjectsPanel::_handleKeyEvent), false); + _tree.signal_drag_drop().connect(sigc::mem_fun(*this, &ObjectsPanel::_handleDragDrop), false); + _tree.signal_row_collapsed().connect(sigc::bind<bool>(sigc::mem_fun(*this, &ObjectsPanel::_setExpanded), false)); + _tree.signal_row_expanded().connect(sigc::bind<bool>(sigc::mem_fun(*this, &ObjectsPanel::_setExpanded), true)); + + // Set up the label editing signals + _text_renderer->signal_edited().connect(sigc::mem_fun(*this, &ObjectsPanel::_handleEdited)); + _text_renderer->signal_editing_canceled().connect(sigc::mem_fun(*this, &ObjectsPanel::_handleEditingCancelled)); + + // Set up the scroller window and pack the page + _scroller.add(_tree); + _scroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); _scroller.set_shadow_type(Gtk::SHADOW_IN); Gtk::Requisition sreq; Gtk::Requisition sreq_natural; @@ -2029,170 +1956,174 @@ ObjectsPanel::ObjectsPanel() : _scroller.set_size_request(sreq.width, minHeight); } - _page.pack_start( _scroller, Gtk::PACK_EXPAND_WIDGET ); + _page.pack_start(_scroller, Gtk::PACK_EXPAND_WIDGET); - //Set up the compositing items - _blendConnection = _filter_modifier.signal_blend_changed().connect(sigc::mem_fun(*this, &ObjectsPanel::_blendValueChanged)); - _blurConnection = _filter_modifier.signal_blur_changed().connect(sigc::mem_fun(*this, &ObjectsPanel::_blurValueChanged)); - _opacityConnection = _filter_modifier.signal_opacity_changed().connect( sigc::mem_fun(*this, &ObjectsPanel::_opacityValueChanged)); + // Set up the compositing items + _blendConnection = + _filter_modifier.signal_blend_changed().connect(sigc::mem_fun(*this, &ObjectsPanel::_blendValueChanged)); + _blurConnection = + _filter_modifier.signal_blur_changed().connect(sigc::mem_fun(*this, &ObjectsPanel::_blurValueChanged)); + _opacityConnection = + _filter_modifier.signal_opacity_changed().connect(sigc::mem_fun(*this, &ObjectsPanel::_opacityValueChanged)); _isolationConnection = _filter_modifier.signal_isolation_changed().connect( sigc::mem_fun(*this, &ObjectsPanel::_isolationValueChanged)); - //Pack the compositing functions and the button row + // Pack the compositing functions and the button row _page.pack_end(_filter_modifier, Gtk::PACK_SHRINK); _page.pack_end(_buttonsRow, Gtk::PACK_SHRINK); - //Pack into the panel contents + // Pack into the panel contents _getContents()->pack_start(_page, Gtk::PACK_EXPAND_WIDGET); - SPDesktop* targetDesktop = getDesktop(); - - //Set up the button row + SPDesktop *targetDesktop = getDesktop(); + // Set up the button row - //Add object/layer - Gtk::Button* btn = Gtk::manage( new Gtk::Button() ); + // Add object/layer + Gtk::Button *btn = Gtk::manage(new Gtk::Button()); _styleButton(*btn, INKSCAPE_ICON("list-add"), _("Add layer...")); btn->set_relief(Gtk::RELIEF_NONE); - btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_NEW) ); + btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_NEW)); _buttonsSecondary.pack_start(*btn, Gtk::PACK_SHRINK); - //Remove object - btn = Gtk::manage( new Gtk::Button() ); + // Remove object + btn = Gtk::manage(new Gtk::Button()); _styleButton(*btn, INKSCAPE_ICON("list-remove"), _("Remove object")); btn->set_relief(Gtk::RELIEF_NONE); - btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_DELETE) ); - _watching.push_back( btn ); + btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_DELETE)); + _watching.push_back(btn); _buttonsSecondary.pack_start(*btn, Gtk::PACK_SHRINK); - //Move to bottom - btn = Gtk::manage( new Gtk::Button() ); + // Move to bottom + btn = Gtk::manage(new Gtk::Button()); _styleButton(*btn, INKSCAPE_ICON("go-bottom"), _("Move To Bottom")); btn->set_relief(Gtk::RELIEF_NONE); - btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_BOTTOM) ); - _watchingNonBottom.push_back( btn ); + btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_BOTTOM)); + _watchingNonBottom.push_back(btn); _buttonsPrimary.pack_end(*btn, Gtk::PACK_SHRINK); - - //Move down - btn = Gtk::manage( new Gtk::Button() ); + + // Move down + btn = Gtk::manage(new Gtk::Button()); _styleButton(*btn, INKSCAPE_ICON("go-down"), _("Move Down")); btn->set_relief(Gtk::RELIEF_NONE); - btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_DOWN) ); - _watchingNonBottom.push_back( btn ); + btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_DOWN)); + _watchingNonBottom.push_back(btn); _buttonsPrimary.pack_end(*btn, Gtk::PACK_SHRINK); - - //Move up - btn = Gtk::manage( new Gtk::Button() ); + + // Move up + btn = Gtk::manage(new Gtk::Button()); _styleButton(*btn, INKSCAPE_ICON("go-up"), _("Move Up")); btn->set_relief(Gtk::RELIEF_NONE); - btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_UP) ); - _watchingNonTop.push_back( btn ); + btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_UP)); + _watchingNonTop.push_back(btn); _buttonsPrimary.pack_end(*btn, Gtk::PACK_SHRINK); - - //Move to top - btn = Gtk::manage( new Gtk::Button() ); + + // Move to top + btn = Gtk::manage(new Gtk::Button()); _styleButton(*btn, INKSCAPE_ICON("go-top"), _("Move To Top")); btn->set_relief(Gtk::RELIEF_NONE); - btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_TOP) ); - _watchingNonTop.push_back( btn ); + btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_TOP)); + _watchingNonTop.push_back(btn); _buttonsPrimary.pack_end(*btn, Gtk::PACK_SHRINK); - - //Collapse all - btn = Gtk::manage( new Gtk::Button() ); + + // Collapse all + btn = Gtk::manage(new Gtk::Button()); _styleButton(*btn, INKSCAPE_ICON("format-indent-less"), _("Collapse All")); btn->set_relief(Gtk::RELIEF_NONE); - btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_COLLAPSE_ALL) ); - _watchingNonBottom.push_back( btn ); + btn->signal_clicked().connect( + sigc::bind(sigc::mem_fun(*this, &ObjectsPanel::_takeAction), (int)BUTTON_COLLAPSE_ALL)); + _watchingNonBottom.push_back(btn); _buttonsPrimary.pack_end(*btn, Gtk::PACK_SHRINK); - + _buttonsRow.pack_start(_buttonsSecondary, Gtk::PACK_EXPAND_WIDGET); _buttonsRow.pack_end(_buttonsPrimary, Gtk::PACK_EXPAND_WIDGET); _watching.push_back(&_filter_modifier); - - //Set up the pop-up menu + + // Set up the pop-up menu // ------------------------------------------------------- { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); _show_contextmenu_icons = prefs->getBool("/theme/menuIcons_objects", true); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_RENAME, (int)BUTTON_RENAME ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_NEW, (int)BUTTON_NEW ) ); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_RENAME, (int)BUTTON_RENAME)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_NEW, (int)BUTTON_NEW)); _popupMenu.append(*Gtk::manage(new Gtk::SeparatorMenuItem())); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_SOLO, (int)BUTTON_SOLO ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_SHOW_ALL, (int)BUTTON_SHOW_ALL ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_HIDE_ALL, (int)BUTTON_HIDE_ALL ) ); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_SOLO, (int)BUTTON_SOLO)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_SHOW_ALL, (int)BUTTON_SHOW_ALL)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_HIDE_ALL, (int)BUTTON_HIDE_ALL)); _popupMenu.append(*Gtk::manage(new Gtk::SeparatorMenuItem())); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_LOCK_OTHERS, (int)BUTTON_LOCK_OTHERS ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_LOCK_ALL, (int)BUTTON_LOCK_ALL ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_UNLOCK_ALL, (int)BUTTON_UNLOCK_ALL ) ); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_LOCK_OTHERS, (int)BUTTON_LOCK_OTHERS)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_LOCK_ALL, (int)BUTTON_LOCK_ALL)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_LAYER_UNLOCK_ALL, (int)BUTTON_UNLOCK_ALL)); _popupMenu.append(*Gtk::manage(new Gtk::SeparatorMenuItem())); - _watchingNonTop.push_back( &_addPopupItem(targetDesktop, SP_VERB_SELECTION_STACK_UP, (int)BUTTON_UP) ); - _watchingNonBottom.push_back( &_addPopupItem(targetDesktop, SP_VERB_SELECTION_STACK_DOWN, (int)BUTTON_DOWN) ); + _watchingNonTop.push_back(&_addPopupItem(targetDesktop, SP_VERB_SELECTION_STACK_UP, (int)BUTTON_UP)); + _watchingNonBottom.push_back(&_addPopupItem(targetDesktop, SP_VERB_SELECTION_STACK_DOWN, (int)BUTTON_DOWN)); _popupMenu.append(*Gtk::manage(new Gtk::SeparatorMenuItem())); - - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_SELECTION_GROUP, (int)BUTTON_GROUP ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_SELECTION_UNGROUP, (int)BUTTON_UNGROUP ) ); - + + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_SELECTION_GROUP, (int)BUTTON_GROUP)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_SELECTION_UNGROUP, (int)BUTTON_UNGROUP)); + _popupMenu.append(*Gtk::manage(new Gtk::SeparatorMenuItem())); - - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_OBJECT_SET_CLIPPATH, (int)BUTTON_SETCLIP ) ); - - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_OBJECT_CREATE_CLIP_GROUP, (int)BUTTON_CLIPGROUP ) ); - //will never be implemented - //_watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_OBJECT_SET_INVERSE_CLIPPATH, (int)BUTTON_SETINVCLIP ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_OBJECT_UNSET_CLIPPATH, (int)BUTTON_UNSETCLIP ) ); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_OBJECT_SET_CLIPPATH, (int)BUTTON_SETCLIP)); + + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_OBJECT_CREATE_CLIP_GROUP, (int)BUTTON_CLIPGROUP)); + + // will never be implemented + //_watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_OBJECT_SET_INVERSE_CLIPPATH, + //(int)BUTTON_SETINVCLIP ) ); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_OBJECT_UNSET_CLIPPATH, (int)BUTTON_UNSETCLIP)); _popupMenu.append(*Gtk::manage(new Gtk::SeparatorMenuItem())); - - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_OBJECT_SET_MASK, (int)BUTTON_SETMASK ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_OBJECT_UNSET_MASK, (int)BUTTON_UNSETMASK ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_EDIT_DUPLICATE, (int)BUTTON_DUPLICATE ) ); - _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_EDIT_DELETE, (int)BUTTON_DELETE ) ); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_OBJECT_SET_MASK, (int)BUTTON_SETMASK)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_OBJECT_UNSET_MASK, (int)BUTTON_UNSETMASK)); + + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_EDIT_DUPLICATE, (int)BUTTON_DUPLICATE)); + _watching.push_back(&_addPopupItem(targetDesktop, SP_VERB_EDIT_DELETE, (int)BUTTON_DELETE)); _popupMenu.show_all_children(); // Install CSS to shift icons into the space reserved for toggles (i.e. check and radio items). - _popupMenu.signal_map().connect(sigc::mem_fun(static_cast<ContextMenu*>(&_popupMenu), &ContextMenu::ShiftIcons)); + _popupMenu.signal_map().connect( + sigc::mem_fun(static_cast<ContextMenu *>(&_popupMenu), &ContextMenu::ShiftIcons)); } // ------------------------------------------------------- - //Set initial sensitivity of buttons - for (auto & it : _watching) { - it->set_sensitive( false ); + // Set initial sensitivity of buttons + for (auto &it : _watching) { + it->set_sensitive(false); } - for (auto & it : _watchingNonTop) { - it->set_sensitive( false ); + for (auto &it : _watchingNonTop) { + it->set_sensitive(false); } - for (auto & it : _watchingNonBottom) { - it->set_sensitive( false ); + for (auto &it : _watchingNonBottom) { + it->set_sensitive(false); } - //Set up the color selection dialog + // Set up the color selection dialog _colorSelectorDialog.hide(); - _colorSelectorDialog.set_title (_("Select Highlight Color")); - _colorSelectorDialog.set_border_width (4); + _colorSelectorDialog.set_title(_("Select Highlight Color")); + _colorSelectorDialog.set_border_width(4); _colorSelectorDialog.property_modal() = true; _selectedColor.reset(new Inkscape::UI::SelectedColor); Gtk::Widget *color_selector = Gtk::manage(new Inkscape::UI::Widget::ColorNotebook(*_selectedColor)); - _colorSelectorDialog.get_content_area()->pack_start ( - *color_selector, true, true, 0); + _colorSelectorDialog.get_content_area()->pack_start(*color_selector, true, true, 0); _selectedColor->signal_dragged.connect(sigc::mem_fun(*this, &ObjectsPanel::_highlightPickerColorMod)); _selectedColor->signal_released.connect(sigc::mem_fun(*this, &ObjectsPanel::_highlightPickerColorMod)); _selectedColor->signal_changed.connect(sigc::mem_fun(*this, &ObjectsPanel::_highlightPickerColorMod)); color_selector->show(); - - setDesktop( targetDesktop ); + + setDesktop(targetDesktop); show_all_children(); } @@ -2200,7 +2131,8 @@ ObjectsPanel::ObjectsPanel() : /** * Callback method that will be called when the desktop is destroyed */ -void ObjectsPanel::_desktopDestroyed(SPDesktop* /*desktop*/) { +void ObjectsPanel::_desktopDestroyed(SPDesktop * /*desktop*/) +{ // We need to make sure that we're not trying to update the tree after the desktop has vanished, e.g. // when closing Inkscape. Preferably, we would have done so in the destructor of the ObjectsPanel. But // as this destructor is never ever called, we will do this by attaching to the desktop_destroyed signal @@ -2217,14 +2149,13 @@ ObjectsPanel::~ObjectsPanel() { // Never being called, not even when closing Inkscape? - //Close the highlight selection dialog + // Close the highlight selection dialog _colorSelectorDialog.hide(); - //Set the desktop to null, which will disconnect all object watchers + // Set the desktop to null, which will disconnect all object watchers setDesktop(nullptr); - if ( _model ) - { + if (_model) { delete _model; _model = nullptr; } @@ -2234,9 +2165,8 @@ ObjectsPanel::~ObjectsPanel() _pending = nullptr; } - if ( _toggleEvent ) - { - gdk_event_free( _toggleEvent ); + if (_toggleEvent) { + gdk_event_free(_toggleEvent); _toggleEvent = nullptr; } } @@ -2244,14 +2174,13 @@ ObjectsPanel::~ObjectsPanel() /** * Sets the current document */ -void ObjectsPanel::setDocument(SPDesktop* /*desktop*/, SPDocument* document) +void ObjectsPanel::setDocument(SPDesktop * /*desktop*/, SPDocument *document) { - //Clear all object watchers + // Clear all object watchers _removeWatchers(); - //Delete the root watcher - if (_rootWatcher) - { + // Delete the root watcher + if (_rootWatcher) { _rootWatcher->_repr->removeObserver(*_rootWatcher); delete _rootWatcher; _rootWatcher = nullptr; @@ -2259,9 +2188,8 @@ void ObjectsPanel::setDocument(SPDesktop* /*desktop*/, SPDocument* document) _document = document; - if (document && document->getRoot() && document->getRoot()->getRepr()) - { - //Create a new root watcher for the document and then call _objectsChanged to fill the tree + if (document && document->getRoot() && document->getRoot()->getRepr()) { + // Create a new root watcher for the document and then call _objectsChanged to fill the tree _rootWatcher = new ObjectsPanel::ObjectWatcher(this, document->getRoot()); document->getRoot()->getRepr()->addObserver(*_rootWatcher); _objectsChanged(document->getRoot()); @@ -2271,28 +2199,32 @@ void ObjectsPanel::setDocument(SPDesktop* /*desktop*/, SPDocument* document) /** * Set the current panel desktop */ -void ObjectsPanel::setDesktop( SPDesktop* desktop ) +void ObjectsPanel::setDesktop(SPDesktop *desktop) { Panel::setDesktop(desktop); - if ( desktop != _desktop ) { + if (desktop != _desktop) { _documentChangedConnection.disconnect(); _documentChangedCurrentLayer.disconnect(); _selectionChangedConnection.disconnect(); - if ( _desktop ) { + if (_desktop) { _desktop = nullptr; } _desktop = Panel::getDesktop(); - if ( _desktop ) { - //Connect desktop signals - _documentChangedConnection = _desktop->connectDocumentReplaced( sigc::mem_fun(*this, &ObjectsPanel::setDocument)); + if (_desktop) { + // Connect desktop signals + _documentChangedConnection = + _desktop->connectDocumentReplaced(sigc::mem_fun(*this, &ObjectsPanel::setDocument)); - _documentChangedCurrentLayer = _desktop->connectCurrentLayerChanged( sigc::mem_fun(*this, &ObjectsPanel::_objectsChangedWrapper)); + _documentChangedCurrentLayer = + _desktop->connectCurrentLayerChanged(sigc::mem_fun(*this, &ObjectsPanel::_objectsChangedWrapper)); - _selectionChangedConnection = _desktop->selection->connectChanged( sigc::mem_fun(*this, &ObjectsPanel::_objectsSelected)); + _selectionChangedConnection = + _desktop->selection->connectChanged(sigc::mem_fun(*this, &ObjectsPanel::_objectsSelected)); - _desktopDestroyedConnection = _desktop->connectDestroy( sigc::mem_fun(*this, &ObjectsPanel::_desktopDestroyed)); + _desktopDestroyedConnection = + _desktop->connectDestroy(sigc::mem_fun(*this, &ObjectsPanel::_desktopDestroyed)); setDocument(_desktop, _desktop->doc()); } else { @@ -2300,30 +2232,27 @@ void ObjectsPanel::setDesktop( SPDesktop* desktop ) } } } -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape -//should be okay to put these here because they are never referenced anywhere else +// should be okay to put these here because they are never referenced anywhere else using namespace Inkscape::UI::Tools; void SPItem::setHighlightColor(guint32 const color) { g_free(_highlightColor); - if (color & 0x000000ff) - { + if (color & 0x000000ff) { _highlightColor = g_strdup_printf("%u", color); - } - else - { + } else { _highlightColor = nullptr; } - + NodeTool *tool = nullptr; - if (SP_ACTIVE_DESKTOP ) { + if (SP_ACTIVE_DESKTOP) { Inkscape::UI::Tools::ToolBase *ec = SP_ACTIVE_DESKTOP->event_context; if (INK_IS_NODE_TOOL(ec)) { - tool = static_cast<NodeTool*>(ec); + tool = static_cast<NodeTool *>(ec); tools_switch(tool->getDesktop(), TOOLS_NODES); } } @@ -2334,10 +2263,10 @@ void SPItem::unsetHighlightColor() g_free(_highlightColor); _highlightColor = nullptr; NodeTool *tool = nullptr; - if (SP_ACTIVE_DESKTOP ) { + if (SP_ACTIVE_DESKTOP) { Inkscape::UI::Tools::ToolBase *ec = SP_ACTIVE_DESKTOP->event_context; if (INK_IS_NODE_TOOL(ec)) { - tool = static_cast<NodeTool*>(ec); + tool = static_cast<NodeTool *>(ec); tools_switch(tool->getDesktop(), TOOLS_NODES); } } diff --git a/src/ui/dialog/objects.h b/src/ui/dialog/objects.h index c192d5e41a8994806217d66011ae3dd3372ea938..382e5f483e048bda5c4a24584439e399322f6188 100644 --- a/src/ui/dialog/objects.h +++ b/src/ui/dialog/objects.h @@ -16,16 +16,17 @@ #define SEEN_OBJECTS_PANEL_H #include <gtkmm/box.h> -#include <gtkmm/treeview.h> -#include <gtkmm/treestore.h> -#include <gtkmm/scrolledwindow.h> -#include <gtkmm/scale.h> #include <gtkmm/dialog.h> -#include "ui/widget/spinbutton.h" -#include "ui/widget/panel.h" -#include "ui/widget/style-subject.h" +#include <gtkmm/scale.h> +#include <gtkmm/scrolledwindow.h> +#include <gtkmm/treestore.h> +#include <gtkmm/treeview.h> + #include "selection.h" #include "ui/widget/filter-effect-chooser.h" +#include "ui/widget/panel.h" +#include "ui/widget/spinbutton.h" +#include "ui/widget/style-subject.h" class SPObject; class SPGroup; @@ -39,7 +40,6 @@ class SelectedColor; namespace Dialog { - /** * A panel that displays objects. */ @@ -49,106 +49,106 @@ public: ObjectsPanel(); ~ObjectsPanel() override; - static ObjectsPanel& getInstance(); + static ObjectsPanel &getInstance(); - void setDesktop( SPDesktop* desktop ) override; - void setDocument( SPDesktop* desktop, SPDocument* document); + void setDesktop(SPDesktop *desktop) override; + void setDocument(SPDesktop *desktop, SPDocument *document); private: - //Internal Classes: + // Internal Classes: class ModelColumns; class InternalUIBounce; class ObjectWatcher; - //Connections, Watchers, Trackers: - - //Document root watcher - ObjectsPanel::ObjectWatcher* _rootWatcher; - - //All object watchers - std::map<SPItem*, std::pair<ObjectsPanel::ObjectWatcher*, bool> > _objectWatchers; - - //Connection for when the desktop is destroyed (I.e. its deconstructor is called) + // Connections, Watchers, Trackers: + + // Document root watcher + ObjectsPanel::ObjectWatcher *_rootWatcher; + + // All object watchers + std::map<SPItem *, std::pair<ObjectsPanel::ObjectWatcher *, bool>> _objectWatchers; + + // Connection for when the desktop is destroyed (I.e. its deconstructor is called) sigc::connection _desktopDestroyedConnection; - //Connection for when the document changes + // Connection for when the document changes sigc::connection _documentChangedConnection; - - //Connection for when the active layer changes + + // Connection for when the active layer changes sigc::connection _documentChangedCurrentLayer; - //Connection for when the active selection in the document changes + // Connection for when the active selection in the document changes sigc::connection _selectionChangedConnection; - //Connection for when the selection in the dialog changes + // Connection for when the selection in the dialog changes sigc::connection _selectedConnection; - - //Connections for when the opacity/blend/blur of the active selection in the document changes + + // Connections for when the opacity/blend/blur of the active selection in the document changes sigc::connection _isolationConnection; sigc::connection _opacityConnection; sigc::connection _blendConnection; sigc::connection _blurConnection; - + sigc::connection _processQueue_sig; sigc::connection _executeUpdate_sig; - //Members: - - //The current desktop - SPDesktop* _desktop; - - //The current document - SPDocument* _document; - - //Tree data model - ModelColumns* _model; - - //Prevents the composite controls from updating + // Members: + + // The current desktop + SPDesktop *_desktop; + + // The current document + SPDocument *_document; + + // Tree data model + ModelColumns *_model; + + // Prevents the composite controls from updating bool _blockCompositeUpdate; - + // - InternalUIBounce* _pending; + InternalUIBounce *_pending; bool _pending_update; - - //Whether the drag & drop was dragged into an item + + // Whether the drag & drop was dragged into an item gboolean _dnd_into; - - //List of drag & drop source items - std::vector<SPItem*> _dnd_source; - - //Drag & drop target item - SPItem* _dnd_target; - + + // List of drag & drop source items + std::vector<SPItem *> _dnd_source; + + // Drag & drop target item + SPItem *_dnd_target; + // Whether the drag sources include a layer bool _dnd_source_includes_layer; - //List of items to change the highlight on - std::vector<SPItem*> _highlight_target; + // List of items to change the highlight on + std::vector<SPItem *> _highlight_target; - //Show icons in the context menu + // Show icons in the context menu bool _show_contextmenu_icons; - //GUI Members: - - GdkEvent* _toggleEvent; - + // GUI Members: + + GdkEvent *_toggleEvent; + Gtk::TreeModel::Path _defer_target; Glib::RefPtr<Gtk::TreeStore> _store; - std::list<std::tuple<SPItem*, Gtk::TreeModel::iterator, bool> > _tree_update_queue; - //When the user selects an item in the document, we need to find that item in the tree view - //and highlight it. When looking up a specific item in the tree though, we don't want to have - //to iterate through the whole list, as this would take too long if the list is very long. So - //we will use a std::map for this instead, which is much faster (and call it _tree_cache). It - //would have been cleaner to create our own custom tree model, as described here - //https://en.wikibooks.org/wiki/GTK%2B_By_Example/Tree_View/Tree_Models - std::map<SPItem*, Gtk::TreeModel::iterator> _tree_cache; + std::list<std::tuple<SPItem *, Gtk::TreeModel::iterator, bool>> _tree_update_queue; + // When the user selects an item in the document, we need to find that item in the tree view + // and highlight it. When looking up a specific item in the tree though, we don't want to have + // to iterate through the whole list, as this would take too long if the list is very long. So + // we will use a std::map for this instead, which is much faster (and call it _tree_cache). It + // would have been cleaner to create our own custom tree model, as described here + // https://en.wikibooks.org/wiki/GTK%2B_By_Example/Tree_View/Tree_Models + std::map<SPItem *, Gtk::TreeModel::iterator> _tree_cache; std::list<SPItem *> _selected_objects_order; // ordered by time of selection std::list<Gtk::TreePath> _paths_to_be_expanded; - std::vector<Gtk::Widget*> _watching; - std::vector<Gtk::Widget*> _watchingNonTop; - std::vector<Gtk::Widget*> _watchingNonBottom; + std::vector<Gtk::Widget *> _watching; + std::vector<Gtk::Widget *> _watchingNonTop; + std::vector<Gtk::Widget *> _watchingNonBottom; Gtk::TreeView _tree; Gtk::CellRendererText *_text_renderer; @@ -173,90 +173,86 @@ private: Gtk::Dialog _colorSelectorDialog; std::unique_ptr<Inkscape::UI::SelectedColor> _selectedColor; - - //Methods: - - ObjectsPanel(ObjectsPanel const &) = delete; // no copy + + // Methods: + + ObjectsPanel(ObjectsPanel const &) = delete; // no copy ObjectsPanel &operator=(ObjectsPanel const &) = delete; // no assign - void _styleButton( Gtk::Button& btn, char const* iconName, char const* tooltip ); - void _fireAction( unsigned int code ); - - Gtk::MenuItem& _addPopupItem( SPDesktop *desktop, unsigned int code, int id ); - - void _setVisibleIter( const Gtk::TreeModel::iterator& iter, const bool visible ); - void _setLockedIter( const Gtk::TreeModel::iterator& iter, const bool locked ); - + void _styleButton(Gtk::Button &btn, char const *iconName, char const *tooltip); + void _fireAction(unsigned int code); + + Gtk::MenuItem &_addPopupItem(SPDesktop *desktop, unsigned int code, int id); + + void _setVisibleIter(const Gtk::TreeModel::iterator &iter, const bool visible); + void _setLockedIter(const Gtk::TreeModel::iterator &iter, const bool locked); + bool _handleButtonEvent(GdkEventButton *event); bool _handleKeyEvent(GdkEventKey *event); - - void _storeHighlightTarget(const Gtk::TreeModel::iterator& iter); - void _storeDragSource(const Gtk::TreeModel::iterator& iter); - 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 _storeHighlightTarget(const Gtk::TreeModel::iterator &iter); + void _storeDragSource(const Gtk::TreeModel::iterator &iter); + 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 _renameObject(Gtk::TreeModel::Row row, const Glib::ustring& name); + void _renameObject(Gtk::TreeModel::Row row, const Glib::ustring &name); void _pushTreeSelectionToCurrent(); - bool _selectItemCallback(const Gtk::TreeModel::iterator& iter, bool *setOpacity, bool *first_pass); - bool _clearPrevSelectionState(const Gtk::TreeModel::iterator& iter); - void _desktopDestroyed(SPDesktop* desktop); - + bool _selectItemCallback(const Gtk::TreeModel::iterator &iter, bool *setOpacity, bool *first_pass); + bool _clearPrevSelectionState(const Gtk::TreeModel::iterator &iter); + void _desktopDestroyed(SPDesktop *desktop); + void _checkTreeSelection(); void _blockAllSignals(bool should_block); - void _takeAction( int val ); + void _takeAction(int val); bool _executeAction(); bool _executeUpdate(); - void _setExpanded( const Gtk::TreeModel::iterator& iter, const Gtk::TreeModel::Path& path, bool isexpanded ); - void _setCollapsed(SPGroup * group); - - bool _noSelection( Glib::RefPtr<Gtk::TreeModel> const & model, Gtk::TreeModel::Path const & path, bool b ); - bool _rowSelectFunction( Glib::RefPtr<Gtk::TreeModel> const & model, Gtk::TreeModel::Path const & path, bool b ); + void _setExpanded(const Gtk::TreeModel::iterator &iter, const Gtk::TreeModel::Path &path, bool isexpanded); + void _setCollapsed(SPGroup *group); + + bool _noSelection(Glib::RefPtr<Gtk::TreeModel> const &model, Gtk::TreeModel::Path const &path, bool b); + bool _rowSelectFunction(Glib::RefPtr<Gtk::TreeModel> const &model, Gtk::TreeModel::Path const &path, bool b); - void _compositingChanged( const Gtk::TreeModel::iterator& iter, bool *setValues ); + void _compositingChanged(const Gtk::TreeModel::iterator &iter, bool *setValues); void _updateComposite(); void _setCompositingValues(SPItem *item); - - bool _findInTreeCache(SPItem* item, Gtk::TreeModel::iterator &tree_iter); + + bool _findInTreeCache(SPItem *item, Gtk::TreeModel::iterator &tree_iter); void _updateObject(SPObject *obj, bool recurse); void _objectsSelected(Selection *sel); - void _updateObjectSelected(SPItem* item, bool scrollto, bool expand); + void _updateObjectSelected(SPItem *item, bool scrollto, bool expand); void _removeWatchers(bool only_unused); - void _addWatcher(SPItem* item); + void _addWatcher(SPItem *item); void _objectsChangedWrapper(SPObject *obj); void _objectsChanged(SPObject *obj); bool _processQueue(); - void _queueObject(SPObject* obj, Gtk::TreeModel::Row* parentRow); - void _addObjectToTree(SPItem* item, const Gtk::TreeModel::Row &parentRow, bool expanded); + void _queueObject(SPObject *obj, Gtk::TreeModel::Row *parentRow); + void _addObjectToTree(SPItem *item, const Gtk::TreeModel::Row &parentRow, bool expanded); void _isolationChangedIter(const Gtk::TreeIter &iter); void _isolationValueChanged(); - void _opacityChangedIter(const Gtk::TreeIter& iter); + void _opacityChangedIter(const Gtk::TreeIter &iter); void _opacityValueChanged(); void _blendChangedIter(const Gtk::TreeIter &iter); void _blendValueChanged(); - void _blurChangedIter(const Gtk::TreeIter& iter, double blur); + void _blurChangedIter(const Gtk::TreeIter &iter, double blur); void _blurValueChanged(); void _highlightPickerColorMod(); }; - - -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape - - +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif // SEEN_OBJECTS_PANEL_H diff --git a/src/ui/dialog/paint-servers.cpp b/src/ui/dialog/paint-servers.cpp index ec49312da5f1a5c977e1833efc60f0752622cc35..cb788975b2c7ee6a7b2ab4b2b001d8dcb228b3bd 100644 --- a/src/ui/dialog/paint-servers.cpp +++ b/src/ui/dialog/paint-servers.cpp @@ -10,11 +10,9 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <algorithm> -#include <iostream> -#include <map> -#include <utility> +#include "paint-servers.h" +#include <algorithm> #include <giomm/listmodel.h> #include <glibmm/regex.h> #include <gtkmm/drawingarea.h> @@ -22,21 +20,22 @@ #include <gtkmm/liststore.h> #include <gtkmm/stockid.h> #include <gtkmm/switch.h> +#include <iostream> +#include <map> +#include <utility> #include "document.h" #include "inkscape.h" -#include "paint-servers.h" -#include "path-prefix.h" -#include "style.h" -#include "verbs.h" - #include "io/resource.h" #include "object/sp-defs.h" #include "object/sp-hatch.h" #include "object/sp-pattern.h" #include "object/sp-root.h" #include "object/sp-shape.h" +#include "path-prefix.h" +#include "style.h" #include "ui/cache/svg_preview_cache.h" +#include "verbs.h" namespace Inkscape { namespace UI { @@ -50,22 +49,27 @@ static Glib::ustring const wrapper = R"=====( </svg> )====="; -class PaintServersColumns : public Gtk::TreeModel::ColumnRecord { - public: +class PaintServersColumns : public Gtk::TreeModel::ColumnRecord +{ +public: Gtk::TreeModelColumn<Glib::ustring> id; Gtk::TreeModelColumn<Glib::ustring> paint; Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf>> pixbuf; Gtk::TreeModelColumn<Glib::ustring> document; - PaintServersColumns() { - add(id); - add(paint); - add(pixbuf); - add(document); + PaintServersColumns() + { + add(id); + add(paint); + add(pixbuf); + add(document); } }; -PaintServersColumns *PaintServersDialog::getColumns() { return new PaintServersColumns(); } +PaintServersColumns *PaintServersDialog::getColumns() +{ + return new PaintServersColumns(); +} // Constructor PaintServersDialog::PaintServersDialog(gchar const *prefsPath) @@ -112,9 +116,7 @@ PaintServersDialog::PaintServersDialog(gchar const *prefsPath) grid->attach(*target_dropdown, 1, 1, 1, 1); // Grid row 2 - icon_view = Gtk::manage(new Gtk::IconView( - static_cast<Glib::RefPtr<Gtk::TreeModel>>(store[current_store]) - )); + icon_view = Gtk::manage(new Gtk::IconView(static_cast<Glib::RefPtr<Gtk::TreeModel>>(store[current_store]))); icon_view->set_tooltip_column(0); icon_view->set_pixbuf_column(2); icon_view->set_size_request(200, 300); @@ -130,21 +132,14 @@ PaintServersDialog::PaintServersDialog(gchar const *prefsPath) grid->attach(*scroller, 0, 2, 2, 1); // Events - target_dropdown->signal_changed().connect( - sigc::mem_fun(*this, &PaintServersDialog::on_target_changed) - ); + target_dropdown->signal_changed().connect(sigc::mem_fun(*this, &PaintServersDialog::on_target_changed)); - dropdown->signal_changed().connect( - sigc::mem_fun(*this, &PaintServersDialog::on_document_changed) - ); + dropdown->signal_changed().connect(sigc::mem_fun(*this, &PaintServersDialog::on_document_changed)); - icon_view->signal_item_activated().connect( - sigc::mem_fun(*this, &PaintServersDialog::on_item_activated) - ); + icon_view->signal_item_activated().connect(sigc::mem_fun(*this, &PaintServersDialog::on_item_activated)); desktop->getDocument()->getDefs()->connectModified( - sigc::mem_fun(*this, &PaintServersDialog::load_current_document) - ); + sigc::mem_fun(*this, &PaintServersDialog::load_current_document)); // Get wrapper document (rectangle to fill with paint server). preview_document = SPDocument::createNewDocFromMem(wrapper.c_str(), wrapper.length(), true); @@ -170,7 +165,6 @@ PaintServersDialog::~PaintServersDialog() = default; // Get url or color value. Glib::ustring get_url(Glib::ustring paint) { - Glib::MatchInfo matchInfo; // Paint server @@ -193,16 +187,15 @@ Glib::ustring get_url(Glib::ustring paint) } // This is too complicated to use selectors! -void recurse_find_paint(SPObject* in, std::vector<Glib::ustring>& list) +void recurse_find_paint(SPObject *in, std::vector<Glib::ustring> &list) { - g_return_if_fail(in != nullptr); // Add paint servers in <defs> section. if (dynamic_cast<SPPaintServer *>(in)) { if (in->getId()) { // Need to check as one can't construct Glib::ustring with nullptr. - list.push_back (Glib::ustring("url(#") + in->getId() + ")"); + list.push_back(Glib::ustring("url(#") + in->getId() + ")"); } // Don't recurse into paint servers. return; @@ -210,11 +203,11 @@ void recurse_find_paint(SPObject* in, std::vector<Glib::ustring>& list) // Add paint servers referenced by shapes. if (dynamic_cast<SPShape *>(in)) { - list.push_back (get_url(in->style->fill.write())); - list.push_back (get_url(in->style->stroke.write())); + list.push_back(get_url(in->style->fill.write())); + list.push_back(get_url(in->style->stroke.write())); } - for (auto child: in->childList(false)) { + for (auto child : in->childList(false)) { recurse_find_paint(child, list); } } @@ -222,12 +215,11 @@ void recurse_find_paint(SPObject* in, std::vector<Glib::ustring>& list) // Load paint servers from all the files associated void PaintServersDialog::load_sources() { - // Extract paints from the current file load_document(desktop->getDocument()); // Extract out paints from files in share/paint. - for (auto &path : get_filenames(Inkscape::IO::Resource::PAINT, { ".svg" })) { + for (auto &path : get_filenames(Inkscape::IO::Resource::PAINT, {".svg"})) { SPDocument *document = SPDocument::createNewDoc(path.c_str(), FALSE); load_document(document); @@ -236,7 +228,6 @@ void PaintServersDialog::load_sources() Glib::RefPtr<Gdk::Pixbuf> PaintServersDialog::get_pixbuf(SPDocument *document, Glib::ustring paint, Glib::ustring *id) { - SPObject *rect = preview_document->getObjectById("Rect"); SPObject *defs = preview_document->getObjectById("Defs"); @@ -414,11 +405,11 @@ void PaintServersDialog::on_document_changed() icon_view->set_model(store[current_store]); } -void PaintServersDialog::on_item_activated(const Gtk::TreeModel::Path& path) +void PaintServersDialog::on_item_activated(const Gtk::TreeModel::Path &path) { // Get the current selected elements Selection *selection = desktop->getSelection(); - std::vector<SPObject*> const selected_items(selection->items().begin(), selection->items().end()); + std::vector<SPObject *> const selected_items(selection->items().begin(), selection->items().end()); if (!selected_items.size()) { return; @@ -458,9 +449,9 @@ void PaintServersDialog::on_item_activated(const Gtk::TreeModel::Path& path) } // Recursively find elements in groups, if any - std::vector<SPObject*> items; + std::vector<SPObject *> items; for (auto item : selected_items) { - std::vector<SPObject*> current_items = extract_elements(item); + std::vector<SPObject *> current_items = extract_elements(item); items.insert(std::end(items), std::begin(current_items), std::end(current_items)); } @@ -472,15 +463,15 @@ void PaintServersDialog::on_item_activated(const Gtk::TreeModel::Path& path) document_target->collectOrphans(); } -std::vector<SPObject*> PaintServersDialog::extract_elements(SPObject* item) +std::vector<SPObject *> PaintServersDialog::extract_elements(SPObject *item) { - std::vector<SPObject*> elements; - std::vector<SPObject*> children = item->childList(false); + std::vector<SPObject *> elements; + std::vector<SPObject *> children = item->childList(false); if (!children.size()) { elements.push_back(item); } else { for (auto e : children) { - std::vector<SPObject*> current_items = extract_elements(e); + std::vector<SPObject *> current_items = extract_elements(e); elements.insert(std::end(elements), std::begin(current_items), std::end(current_items)); } } diff --git a/src/ui/dialog/paint-servers.h b/src/ui/dialog/paint-servers.h index 3eeef0513ec4758d133abe254e1f3bb686f490e8..422c36d2d531fee4fceefc9f6ca7ccd3a6afd47f 100644 --- a/src/ui/dialog/paint-servers.h +++ b/src/ui/dialog/paint-servers.h @@ -36,8 +36,8 @@ class PaintServersColumns; // For Gtk::ListStore * for each document, for all documents and for the current document. */ -class PaintServersDialog : public Inkscape::UI::Widget::Panel { - +class PaintServersDialog : public Inkscape::UI::Widget::Panel +{ public: PaintServersDialog(gchar const *prefsPath = "/dialogs/paint"); ~PaintServersDialog() override; @@ -46,7 +46,7 @@ public: PaintServersDialog(PaintServersDialog const &) = delete; PaintServersDialog &operator=(PaintServersDialog const &) = delete; - private: +private: static PaintServersColumns *getColumns(); void load_sources(); void load_document(SPDocument *document); diff --git a/src/ui/dialog/panel-dialog.h b/src/ui/dialog/panel-dialog.h index 098f9c6ea0e88a12b238a67d09e5311ce43e20c0..5e6726b160e1e8a3f2ffe365f26bfb43d639a4d4 100644 --- a/src/ui/dialog/panel-dialog.h +++ b/src/ui/dialog/panel-dialog.h @@ -15,13 +15,13 @@ #include <glibmm/i18n.h> #include <gtkmm/dialog.h> -#include "verbs.h" +#include "desktop.h" #include "dialog.h" -#include "ui/dialog/swatches.h" -#include "ui/dialog/floating-behavior.h" -#include "ui/dialog/dock-behavior.h" #include "inkscape.h" -#include "desktop.h" +#include "ui/dialog/dock-behavior.h" +#include "ui/dialog/floating-behavior.h" +#include "ui/dialog/swatches.h" +#include "verbs.h" namespace Inkscape { namespace UI { @@ -33,10 +33,12 @@ namespace Dialog { * PanelDialog handles signals emitted when a desktop changes, either changing to a * different desktop or a new document. */ -class PanelDialogBase { +class PanelDialogBase +{ public: - PanelDialogBase(UI::Widget::Panel &panel, char const */*prefs_path*/, int const /*verb_num*/) : - _panel (panel) { } + PanelDialogBase(UI::Widget::Panel &panel, char const * /*prefs_path*/, int const /*verb_num*/) + : _panel(panel) + {} virtual void present() = 0; virtual ~PanelDialogBase() @@ -47,8 +49,7 @@ public: virtual UI::Widget::Panel &getPanel() { return _panel; } protected: - - inline virtual void _propagateDocumentReplaced(SPDesktop* desktop, SPDocument *document); + inline virtual void _propagateDocumentReplaced(SPDesktop *desktop, SPDocument *document); inline virtual void _propagateDesktopActivated(SPDesktop *); inline virtual void _propagateDesktopDeactivated(SPDesktop *); @@ -65,12 +66,14 @@ protected: * dockable and floatable dialog. The link with Dialog is made via PanelDialogBase. */ template <typename Behavior> -class PanelDialog : public PanelDialogBase, public Inkscape::UI::Dialog::Dialog { - +class PanelDialog + : public PanelDialogBase + , public Inkscape::UI::Dialog::Dialog +{ public: /** * Constructor. - * + * * @param contents panel with the actual dialog content. * @param prefs_path characteristic path for loading/saving dialog position. * @param verb_num the dialog verb. @@ -92,10 +95,9 @@ private: PanelDialog() = delete; PanelDialog(PanelDialog<Behavior> const &d) = delete; // no copy - PanelDialog<Behavior>& operator=(PanelDialog<Behavior> const &d) = delete; // no assign + PanelDialog<Behavior> &operator=(PanelDialog<Behavior> const &d) = delete; // no assign }; - void PanelDialogBase::_propagateDocumentReplaced(SPDesktop *desktop, SPDocument *document) { _panel.signalDocumentReplaced().emit(desktop, document); @@ -115,11 +117,10 @@ void PanelDialogBase::_propagateDesktopDeactivated(SPDesktop *desktop) _panel.signalDeactiveDesktop().emit(desktop); } - template <typename B> -PanelDialog<B>::PanelDialog(Widget::Panel &panel, char const *prefs_path, int const verb_num) : - PanelDialogBase(panel, prefs_path, verb_num), - Dialog(&B::create, prefs_path, verb_num) +PanelDialog<B>::PanelDialog(Widget::Panel &panel, char const *prefs_path, int const verb_num) + : PanelDialogBase(panel, prefs_path, verb_num) + , Dialog(&B::create, prefs_path, verb_num) { Gtk::Box *vbox = get_vbox(); _connections.emplace_back(_panel.signalResponse().connect(sigc::mem_fun(*this, &PanelDialog::_handleResponse))); @@ -134,13 +135,15 @@ PanelDialog<B>::PanelDialog(Widget::Panel &panel, char const *prefs_path, int co show_all_children(); } -template <typename B> template <typename P> +template <typename B> +template <typename P> PanelDialog<B> *PanelDialog<B>::create() { return _create<P>(); } -template <typename B> template <typename P> +template <typename B> +template <typename P> PanelDialog<B> *PanelDialog<B>::_create() { UI::Widget::Panel &panel = *Gtk::manage(&P::getInstance()); @@ -159,17 +162,16 @@ void PanelDialog<B>::_presentDialog() Dialog::present(); } -template <> inline -void PanelDialog<Behavior::FloatingBehavior>::present() +template <> +inline void PanelDialog<Behavior::FloatingBehavior>::present() { Dialog::present(); _panel.present(); } -template <> inline -void PanelDialog<Behavior::FloatingBehavior>::_presentDialog() -{ -} +template <> +inline void PanelDialog<Behavior::FloatingBehavior>::_presentDialog() +{} /** * Specialized factory method for panel dialogs with floating behavior in order to make them work as @@ -192,7 +194,7 @@ PanelDialog<Behavior::FloatingBehavior> *PanelDialog<Behavior::FloatingBehavior> } // namespace UI } // namespace Inkscape -#endif //INKSCAPE_PANEL_DIALOG_H +#endif // INKSCAPE_PANEL_DIALOG_H /* Local Variables: diff --git a/src/ui/dialog/polar-arrange-tab.cpp b/src/ui/dialog/polar-arrange-tab.cpp index 67f14429f7fce8713755c10fc3302b4bbfdd5bdb..a2562d788db32b9bf1361a68f59bcffd94da539c 100644 --- a/src/ui/dialog/polar-arrange-tab.cpp +++ b/src/ui/dialog/polar-arrange-tab.cpp @@ -8,128 +8,126 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/i18n.h> -#include <gtkmm/messagedialog.h> +#include "ui/dialog/polar-arrange-tab.h" #include <2geom/transforms.h> +#include <glibmm/i18n.h> +#include <gtkmm/messagedialog.h> #include "desktop.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" -#include "preferences.h" -#include "verbs.h" - #include "object/sp-ellipse.h" #include "object/sp-item-transform.h" - -#include "ui/dialog/polar-arrange-tab.h" +#include "preferences.h" #include "ui/dialog/tile.h" - +#include "verbs.h" namespace Inkscape { namespace UI { namespace Dialog { PolarArrangeTab::PolarArrangeTab(ArrangeDialog *parent_) - : parent(parent_), - parametersTable(), - centerY("", C_("Polar arrange tab", "Y coordinate of the center"), UNIT_TYPE_LINEAR), - centerX("", C_("Polar arrange tab", "X coordinate of the center"), centerY), - radiusY("", C_("Polar arrange tab", "Y coordinate of the radius"), UNIT_TYPE_LINEAR), - radiusX("", C_("Polar arrange tab", "X coordinate of the radius"), radiusY), - angleY("", C_("Polar arrange tab", "Ending angle"), UNIT_TYPE_RADIAL), - angleX("", C_("Polar arrange tab", "Starting angle"), angleY) + : parent(parent_) + , parametersTable() + , centerY("", C_("Polar arrange tab", "Y coordinate of the center"), UNIT_TYPE_LINEAR) + , centerX("", C_("Polar arrange tab", "X coordinate of the center"), centerY) + , radiusY("", C_("Polar arrange tab", "Y coordinate of the radius"), UNIT_TYPE_LINEAR) + , radiusX("", C_("Polar arrange tab", "X coordinate of the radius"), radiusY) + , angleY("", C_("Polar arrange tab", "Ending angle"), UNIT_TYPE_RADIAL) + , angleX("", C_("Polar arrange tab", "Starting angle"), angleY) { - anchorPointLabel.set_text(C_("Polar arrange tab", "Anchor point:")); - anchorPointLabel.set_halign(Gtk::ALIGN_START); - pack_start(anchorPointLabel, false, false); - - anchorBoundingBoxRadio.set_label(C_("Polar arrange tab", "Objects' bounding boxes:")); - anchorRadioGroup = anchorBoundingBoxRadio.get_group(); - anchorBoundingBoxRadio.signal_toggled().connect(sigc::mem_fun(*this, &PolarArrangeTab::on_anchor_radio_changed)); - pack_start(anchorBoundingBoxRadio, false, false); - - pack_start(anchorSelector, false, false); - - anchorObjectPivotRadio.set_label(C_("Polar arrange tab", "Objects' rotational centers")); - anchorObjectPivotRadio.set_group(anchorRadioGroup); - anchorObjectPivotRadio.signal_toggled().connect(sigc::mem_fun(*this, &PolarArrangeTab::on_anchor_radio_changed)); - pack_start(anchorObjectPivotRadio, false, false); - - arrangeOnLabel.set_text(C_("Polar arrange tab", "Arrange on:")); - arrangeOnLabel.set_halign(Gtk::ALIGN_START); - pack_start(arrangeOnLabel, false, false); - - arrangeOnFirstCircleRadio.set_label(C_("Polar arrange tab", "First selected circle/ellipse/arc")); - arrangeRadioGroup = arrangeOnFirstCircleRadio.get_group(); - arrangeOnFirstCircleRadio.signal_toggled().connect(sigc::mem_fun(*this, &PolarArrangeTab::on_arrange_radio_changed)); - pack_start(arrangeOnFirstCircleRadio, false, false); - - arrangeOnLastCircleRadio.set_label(C_("Polar arrange tab", "Last selected circle/ellipse/arc")); - arrangeOnLastCircleRadio.set_group(arrangeRadioGroup); - arrangeOnLastCircleRadio.signal_toggled().connect(sigc::mem_fun(*this, &PolarArrangeTab::on_arrange_radio_changed)); - pack_start(arrangeOnLastCircleRadio, false, false); - - arrangeOnParametersRadio.set_label(C_("Polar arrange tab", "Parameterized:")); - arrangeOnParametersRadio.set_group(arrangeRadioGroup); - arrangeOnParametersRadio.signal_toggled().connect(sigc::mem_fun(*this, &PolarArrangeTab::on_arrange_radio_changed)); - pack_start(arrangeOnParametersRadio, false, false); - - centerLabel.set_text(C_("Polar arrange tab", "Center X/Y:")); - parametersTable.attach(centerLabel, 0, 0, 1, 1); - centerX.setDigits(2); - centerX.setIncrements(0.2, 0); - centerX.setRange(-10000, 10000); - centerX.setValue(0, "px"); - centerY.setDigits(2); - centerY.setIncrements(0.2, 0); - centerY.setRange(-10000, 10000); - centerY.setValue(0, "px"); - parametersTable.attach(centerX, 1, 0, 1, 1); - parametersTable.attach(centerY, 2, 0, 1, 1); - - radiusLabel.set_text(C_("Polar arrange tab", "Radius X/Y:")); - parametersTable.attach(radiusLabel, 0, 1, 1, 1); - radiusX.setDigits(2); - radiusX.setIncrements(0.2, 0); - radiusX.setRange(0.001, 10000); - radiusX.setValue(100, "px"); - radiusY.setDigits(2); - radiusY.setIncrements(0.2, 0); - radiusY.setRange(0.001, 10000); - radiusY.setValue(100, "px"); - parametersTable.attach(radiusX, 1, 1, 1, 1); - parametersTable.attach(radiusY, 2, 1, 1, 1); - - angleLabel.set_text(_("Angle X/Y:")); - parametersTable.attach(angleLabel, 0, 2, 1, 1); - angleX.setDigits(2); - angleX.setIncrements(0.2, 0); - angleX.setRange(-10000, 10000); - angleX.setValue(0, "°"); - angleY.setDigits(2); - angleY.setIncrements(0.2, 0); - angleY.setRange(-10000, 10000); - angleY.setValue(180, "°"); - parametersTable.attach(angleX, 1, 2, 1, 1); - parametersTable.attach(angleY, 2, 2, 1, 1); - parametersTable.set_row_spacing(4); - parametersTable.set_column_spacing(4); - pack_start(parametersTable, false, false); - - rotateObjectsCheckBox.set_label(_("Rotate objects")); - rotateObjectsCheckBox.set_active(true); - pack_start(rotateObjectsCheckBox, false, false); - - centerX.set_sensitive(false); - centerY.set_sensitive(false); - angleX.set_sensitive(false); - angleY.set_sensitive(false); - radiusX.set_sensitive(false); - radiusY.set_sensitive(false); - - set_border_width(4); + anchorPointLabel.set_text(C_("Polar arrange tab", "Anchor point:")); + anchorPointLabel.set_halign(Gtk::ALIGN_START); + pack_start(anchorPointLabel, false, false); + + anchorBoundingBoxRadio.set_label(C_("Polar arrange tab", "Objects' bounding boxes:")); + anchorRadioGroup = anchorBoundingBoxRadio.get_group(); + anchorBoundingBoxRadio.signal_toggled().connect(sigc::mem_fun(*this, &PolarArrangeTab::on_anchor_radio_changed)); + pack_start(anchorBoundingBoxRadio, false, false); + + pack_start(anchorSelector, false, false); + + anchorObjectPivotRadio.set_label(C_("Polar arrange tab", "Objects' rotational centers")); + anchorObjectPivotRadio.set_group(anchorRadioGroup); + anchorObjectPivotRadio.signal_toggled().connect(sigc::mem_fun(*this, &PolarArrangeTab::on_anchor_radio_changed)); + pack_start(anchorObjectPivotRadio, false, false); + + arrangeOnLabel.set_text(C_("Polar arrange tab", "Arrange on:")); + arrangeOnLabel.set_halign(Gtk::ALIGN_START); + pack_start(arrangeOnLabel, false, false); + + arrangeOnFirstCircleRadio.set_label(C_("Polar arrange tab", "First selected circle/ellipse/arc")); + arrangeRadioGroup = arrangeOnFirstCircleRadio.get_group(); + arrangeOnFirstCircleRadio.signal_toggled().connect( + sigc::mem_fun(*this, &PolarArrangeTab::on_arrange_radio_changed)); + pack_start(arrangeOnFirstCircleRadio, false, false); + + arrangeOnLastCircleRadio.set_label(C_("Polar arrange tab", "Last selected circle/ellipse/arc")); + arrangeOnLastCircleRadio.set_group(arrangeRadioGroup); + arrangeOnLastCircleRadio.signal_toggled().connect(sigc::mem_fun(*this, &PolarArrangeTab::on_arrange_radio_changed)); + pack_start(arrangeOnLastCircleRadio, false, false); + + arrangeOnParametersRadio.set_label(C_("Polar arrange tab", "Parameterized:")); + arrangeOnParametersRadio.set_group(arrangeRadioGroup); + arrangeOnParametersRadio.signal_toggled().connect(sigc::mem_fun(*this, &PolarArrangeTab::on_arrange_radio_changed)); + pack_start(arrangeOnParametersRadio, false, false); + + centerLabel.set_text(C_("Polar arrange tab", "Center X/Y:")); + parametersTable.attach(centerLabel, 0, 0, 1, 1); + centerX.setDigits(2); + centerX.setIncrements(0.2, 0); + centerX.setRange(-10000, 10000); + centerX.setValue(0, "px"); + centerY.setDigits(2); + centerY.setIncrements(0.2, 0); + centerY.setRange(-10000, 10000); + centerY.setValue(0, "px"); + parametersTable.attach(centerX, 1, 0, 1, 1); + parametersTable.attach(centerY, 2, 0, 1, 1); + + radiusLabel.set_text(C_("Polar arrange tab", "Radius X/Y:")); + parametersTable.attach(radiusLabel, 0, 1, 1, 1); + radiusX.setDigits(2); + radiusX.setIncrements(0.2, 0); + radiusX.setRange(0.001, 10000); + radiusX.setValue(100, "px"); + radiusY.setDigits(2); + radiusY.setIncrements(0.2, 0); + radiusY.setRange(0.001, 10000); + radiusY.setValue(100, "px"); + parametersTable.attach(radiusX, 1, 1, 1, 1); + parametersTable.attach(radiusY, 2, 1, 1, 1); + + angleLabel.set_text(_("Angle X/Y:")); + parametersTable.attach(angleLabel, 0, 2, 1, 1); + angleX.setDigits(2); + angleX.setIncrements(0.2, 0); + angleX.setRange(-10000, 10000); + angleX.setValue(0, "°"); + angleY.setDigits(2); + angleY.setIncrements(0.2, 0); + angleY.setRange(-10000, 10000); + angleY.setValue(180, "°"); + parametersTable.attach(angleX, 1, 2, 1, 1); + parametersTable.attach(angleY, 2, 2, 1, 1); + parametersTable.set_row_spacing(4); + parametersTable.set_column_spacing(4); + pack_start(parametersTable, false, false); + + rotateObjectsCheckBox.set_label(_("Rotate objects")); + rotateObjectsCheckBox.set_active(true); + pack_start(rotateObjectsCheckBox, false, false); + + centerX.set_sensitive(false); + centerY.set_sensitive(false); + angleX.set_sensitive(false); + angleY.set_sensitive(false); + radiusX.set_sensitive(false); + radiusY.set_sensitive(false); + + set_border_width(4); } /** @@ -140,20 +138,19 @@ PolarArrangeTab::PolarArrangeTab(ArrangeDialog *parent_) */ static void rotateAround(SPItem *item, Geom::Point center, Geom::Rotate const &rotation) { - Geom::Translate const s(center); - Geom::Affine affine = Geom::Affine(s).inverse() * Geom::Affine(rotation) * Geom::Affine(s); + Geom::Translate const s(center); + Geom::Affine affine = Geom::Affine(s).inverse() * Geom::Affine(rotation) * Geom::Affine(s); - // Save old center + // Save old center center = item->getCenter(); - item->set_i2d_affine(item->i2dt_affine() * affine); - item->doWriteTransform(item->transform); + item->set_i2d_affine(item->i2dt_affine() * affine); + item->doWriteTransform(item->transform); - if(item->isCenterSet()) - { - item->setCenter(center * affine); - item->updateRepr(); - } + if (item->isCenterSet()) { + item->setCenter(center * affine); + item->updateRepr(); + } } /** @@ -167,16 +164,17 @@ static void rotateAround(SPItem *item, Geom::Point center, Geom::Rotate const &r */ static float calcAngle(float arcBegin, float arcEnd, int count, int n) { - float arcLength = arcEnd - arcBegin; - float delta = std::abs(std::abs(arcLength) - 2*M_PI); - if(delta > 0.01) count--; // If not a complete circle, put an object also at the extremes of the arc; + float arcLength = arcEnd - arcBegin; + float delta = std::abs(std::abs(arcLength) - 2 * M_PI); + if (delta > 0.01) + count--; // If not a complete circle, put an object also at the extremes of the arc; - float angle = n / (float)count; - // Normalize for arcLength: - angle = angle * arcLength; - angle += arcBegin; + float angle = n / (float)count; + // Normalize for arcLength: + angle = angle * arcLength; + angle += arcBegin; - return angle; + return angle; } /** @@ -185,7 +183,7 @@ static float calcAngle(float arcBegin, float arcEnd, int count, int n) */ static Geom::Point calcPoint(float cx, float cy, float rx, float ry, float angle) { - return Geom::Point(cx + cos(angle) * rx, cy + sin(angle) * ry); + return Geom::Point(cx + cos(angle) * rx, cy + sin(angle) * ry); } /** @@ -195,57 +193,54 @@ static Geom::Point calcPoint(float cx, float cy, float rx, float ry, float angle */ static Geom::Point getAnchorPoint(int anchor, SPItem *item) { - Geom::Point source; - - Geom::OptRect bbox = item->documentVisualBounds(); - - switch(anchor) - { - case 0: // Top - Left - case 3: // Middle - Left - case 6: // Bottom - Left - source[0] = bbox->min()[Geom::X]; - break; - case 1: // Top - Middle - case 4: // Middle - Middle - case 7: // Bottom - Middle - source[0] = (bbox->min()[Geom::X] + bbox->max()[Geom::X]) / 2.0f; - break; - case 2: // Top - Right - case 5: // Middle - Right - case 8: // Bottom - Right - source[0] = bbox->max()[Geom::X]; - break; - }; - - switch(anchor) - { - case 0: // Top - Left - case 1: // Top - Middle - case 2: // Top - Right - source[1] = bbox->min()[Geom::Y]; - break; - case 3: // Middle - Left - case 4: // Middle - Middle - case 5: // Middle - Right - source[1] = (bbox->min()[Geom::Y] + bbox->max()[Geom::Y]) / 2.0f; - break; - case 6: // Bottom - Left - case 7: // Bottom - Middle - case 8: // Bottom - Right - source[1] = bbox->max()[Geom::Y]; - break; - }; - - // If using center - if(anchor == 9) - source = item->getCenter(); - else - { - source *= item->document->doc2dt(); - } - - return source; + Geom::Point source; + + Geom::OptRect bbox = item->documentVisualBounds(); + + switch (anchor) { + case 0: // Top - Left + case 3: // Middle - Left + case 6: // Bottom - Left + source[0] = bbox->min()[Geom::X]; + break; + case 1: // Top - Middle + case 4: // Middle - Middle + case 7: // Bottom - Middle + source[0] = (bbox->min()[Geom::X] + bbox->max()[Geom::X]) / 2.0f; + break; + case 2: // Top - Right + case 5: // Middle - Right + case 8: // Bottom - Right + source[0] = bbox->max()[Geom::X]; + break; + }; + + switch (anchor) { + case 0: // Top - Left + case 1: // Top - Middle + case 2: // Top - Right + source[1] = bbox->min()[Geom::Y]; + break; + case 3: // Middle - Left + case 4: // Middle - Middle + case 5: // Middle - Right + source[1] = (bbox->min()[Geom::Y] + bbox->max()[Geom::Y]) / 2.0f; + break; + case 6: // Bottom - Left + case 7: // Bottom - Middle + case 8: // Bottom - Right + source[1] = bbox->max()[Geom::Y]; + break; + }; + + // If using center + if (anchor == 9) + source = item->getCenter(); + else { + source *= item->document->doc2dt(); + } + + return source; } /** @@ -260,141 +255,131 @@ static Geom::Point getAnchorPoint(int anchor, SPItem *item) */ static void moveToPoint(int anchor, SPItem *item, Geom::Point p) { - item->move_rel(Geom::Translate(p - getAnchorPoint(anchor, item))); + item->move_rel(Geom::Translate(p - getAnchorPoint(anchor, item))); } void PolarArrangeTab::arrange() { - Inkscape::Selection *selection = parent->getDesktop()->getSelection(); - const std::vector<SPItem*> tmp(selection->items().begin(), selection->items().end()); - SPGenericEllipse *referenceEllipse = nullptr; // Last ellipse in selection - - bool arrangeOnEllipse = !arrangeOnParametersRadio.get_active(); - bool arrangeOnFirstEllipse = arrangeOnEllipse && arrangeOnFirstCircleRadio.get_active(); - float yaxisdir = parent->getDesktop()->yaxisdir(); - - int count = 0; - for(auto item : tmp) - { - if(arrangeOnEllipse) - { - if(arrangeOnFirstEllipse) - { - // The first selected ellipse is actually the last one in the list - if(SP_IS_GENERICELLIPSE(item)) - referenceEllipse = SP_GENERICELLIPSE(item); - } else { - // The last selected ellipse is actually the first in list - if(SP_IS_GENERICELLIPSE(item) && referenceEllipse == nullptr) - referenceEllipse = SP_GENERICELLIPSE(item); - } - } - ++count; - } - - float cx, cy; // Center of the ellipse - float rx, ry; // Radiuses of the ellipse in x and y direction - float arcBeg, arcEnd; // begin and end angles for arcs - Geom::Affine transformation; // Any additional transformation to apply to the objects - - if(arrangeOnEllipse) - { - if(referenceEllipse == nullptr) - { - Gtk::MessageDialog dialog(_("Couldn't find an ellipse in selection"), false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE, true); - dialog.run(); - return; - } else { - cx = referenceEllipse->cx.value; - cy = referenceEllipse->cy.value; - rx = referenceEllipse->rx.value; - ry = referenceEllipse->ry.value; - arcBeg = referenceEllipse->start; - arcEnd = referenceEllipse->end; - - transformation = referenceEllipse->i2dt_affine(); - - // We decrement the count by 1 as we are not going to lay - // out the reference ellipse - --count; - } - - } else { - // Read options from UI - cx = centerX.getValue("px"); - cy = centerY.getValue("px"); - rx = radiusX.getValue("px"); - ry = radiusY.getValue("px"); - arcBeg = angleX.getValue("rad"); - arcEnd = angleY.getValue("rad") * yaxisdir; - transformation.setIdentity(); - referenceEllipse = nullptr; - } - - int anchor = 9; - if(anchorBoundingBoxRadio.get_active()) - { - anchor = anchorSelector.getHorizontalAlignment() + - anchorSelector.getVerticalAlignment() * 3; - } - - Geom::Point realCenter = Geom::Point(cx, cy) * transformation; - - int i = 0; - for(auto item : tmp) - { - // Ignore the reference ellipse if any - if(item != referenceEllipse) - { - float angle = calcAngle(arcBeg, arcEnd, count, i); - Geom::Point newLocation = calcPoint(cx, cy, rx, ry, angle) * transformation; - - moveToPoint(anchor, item, newLocation); - - if(rotateObjectsCheckBox.get_active()) { - // Calculate the angle by which to rotate each object - angle = -atan2f(-yaxisdir * (newLocation.x() - realCenter.x()), -yaxisdir * (newLocation.y() - realCenter.y())); - rotateAround(item, newLocation, Geom::Rotate(angle)); - } - - ++i; - } - } - - DocumentUndo::done(parent->getDesktop()->getDocument(), SP_VERB_SELECTION_ARRANGE, - _("Arrange on ellipse")); + Inkscape::Selection *selection = parent->getDesktop()->getSelection(); + const std::vector<SPItem *> tmp(selection->items().begin(), selection->items().end()); + SPGenericEllipse *referenceEllipse = nullptr; // Last ellipse in selection + + bool arrangeOnEllipse = !arrangeOnParametersRadio.get_active(); + bool arrangeOnFirstEllipse = arrangeOnEllipse && arrangeOnFirstCircleRadio.get_active(); + float yaxisdir = parent->getDesktop()->yaxisdir(); + + int count = 0; + for (auto item : tmp) { + if (arrangeOnEllipse) { + if (arrangeOnFirstEllipse) { + // The first selected ellipse is actually the last one in the list + if (SP_IS_GENERICELLIPSE(item)) + referenceEllipse = SP_GENERICELLIPSE(item); + } else { + // The last selected ellipse is actually the first in list + if (SP_IS_GENERICELLIPSE(item) && referenceEllipse == nullptr) + referenceEllipse = SP_GENERICELLIPSE(item); + } + } + ++count; + } + + float cx, cy; // Center of the ellipse + float rx, ry; // Radiuses of the ellipse in x and y direction + float arcBeg, arcEnd; // begin and end angles for arcs + Geom::Affine transformation; // Any additional transformation to apply to the objects + + if (arrangeOnEllipse) { + if (referenceEllipse == nullptr) { + Gtk::MessageDialog dialog(_("Couldn't find an ellipse in selection"), false, Gtk::MESSAGE_ERROR, + Gtk::BUTTONS_CLOSE, true); + dialog.run(); + return; + } else { + cx = referenceEllipse->cx.value; + cy = referenceEllipse->cy.value; + rx = referenceEllipse->rx.value; + ry = referenceEllipse->ry.value; + arcBeg = referenceEllipse->start; + arcEnd = referenceEllipse->end; + + transformation = referenceEllipse->i2dt_affine(); + + // We decrement the count by 1 as we are not going to lay + // out the reference ellipse + --count; + } + + } else { + // Read options from UI + cx = centerX.getValue("px"); + cy = centerY.getValue("px"); + rx = radiusX.getValue("px"); + ry = radiusY.getValue("px"); + arcBeg = angleX.getValue("rad"); + arcEnd = angleY.getValue("rad") * yaxisdir; + transformation.setIdentity(); + referenceEllipse = nullptr; + } + + int anchor = 9; + if (anchorBoundingBoxRadio.get_active()) { + anchor = anchorSelector.getHorizontalAlignment() + anchorSelector.getVerticalAlignment() * 3; + } + + Geom::Point realCenter = Geom::Point(cx, cy) * transformation; + + int i = 0; + for (auto item : tmp) { + // Ignore the reference ellipse if any + if (item != referenceEllipse) { + float angle = calcAngle(arcBeg, arcEnd, count, i); + Geom::Point newLocation = calcPoint(cx, cy, rx, ry, angle) * transformation; + + moveToPoint(anchor, item, newLocation); + + if (rotateObjectsCheckBox.get_active()) { + // Calculate the angle by which to rotate each object + angle = -atan2f(-yaxisdir * (newLocation.x() - realCenter.x()), + -yaxisdir * (newLocation.y() - realCenter.y())); + rotateAround(item, newLocation, Geom::Rotate(angle)); + } + + ++i; + } + } + + DocumentUndo::done(parent->getDesktop()->getDocument(), SP_VERB_SELECTION_ARRANGE, _("Arrange on ellipse")); } -void PolarArrangeTab::updateSelection() -{ -} +void PolarArrangeTab::updateSelection() {} void PolarArrangeTab::on_arrange_radio_changed() { - bool arrangeParametric = arrangeOnParametersRadio.get_active(); + bool arrangeParametric = arrangeOnParametersRadio.get_active(); - centerX.set_sensitive(arrangeParametric); - centerY.set_sensitive(arrangeParametric); + centerX.set_sensitive(arrangeParametric); + centerY.set_sensitive(arrangeParametric); - angleX.set_sensitive(arrangeParametric); - angleY.set_sensitive(arrangeParametric); + angleX.set_sensitive(arrangeParametric); + angleY.set_sensitive(arrangeParametric); - radiusX.set_sensitive(arrangeParametric); - radiusY.set_sensitive(arrangeParametric); + radiusX.set_sensitive(arrangeParametric); + radiusY.set_sensitive(arrangeParametric); - parametersTable.set_visible(arrangeParametric); + parametersTable.set_visible(arrangeParametric); } void PolarArrangeTab::on_anchor_radio_changed() { - bool anchorBoundingBox = anchorBoundingBoxRadio.get_active(); + bool anchorBoundingBox = anchorBoundingBoxRadio.get_active(); - anchorSelector.set_sensitive(anchorBoundingBox); + anchorSelector.set_sensitive(anchorBoundingBox); } -} //namespace Dialog -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/polar-arrange-tab.h b/src/ui/dialog/polar-arrange-tab.h index 0c5acdee99ced0a7f8b1474160dbed6efe8970f2..a4ebc367f7e92250f417f639fd2cc5959623c580 100644 --- a/src/ui/dialog/polar-arrange-tab.h +++ b/src/ui/dialog/polar-arrange-tab.h @@ -11,13 +11,13 @@ #ifndef INKSCAPE_UI_DIALOG_POLAR_ARRANGE_TAB_H #define INKSCAPE_UI_DIALOG_POLAR_ARRANGE_TAB_H -#include "ui/widget/scalar-unit.h" -#include "ui/widget/anchor-selector.h" -#include "ui/dialog/arrange-tab.h" - +#include <gtkmm/grid.h> #include <gtkmm/radiobutton.h> #include <gtkmm/radiobuttongroup.h> -#include <gtkmm/grid.h> + +#include "ui/dialog/arrange-tab.h" +#include "ui/widget/anchor-selector.h" +#include "ui/widget/scalar-unit.h" namespace Inkscape { namespace UI { @@ -29,10 +29,12 @@ class ArrangeDialog; * PolarArrangeTab is a Tab displayed in the Arrange dialog and contains * enables the user to arrange objects on a circular or elliptical shape */ -class PolarArrangeTab : public ArrangeTab { +class PolarArrangeTab : public ArrangeTab +{ public: - PolarArrangeTab(ArrangeDialog *parent_); - ~PolarArrangeTab() override = default;; + PolarArrangeTab(ArrangeDialog *parent_); + ~PolarArrangeTab() override = default; + ; /** * Do the actual arrangement @@ -49,46 +51,44 @@ public: private: PolarArrangeTab(PolarArrangeTab const &d) = delete; // no copy - void operator=(PolarArrangeTab const &d) = delete; // no assign + void operator=(PolarArrangeTab const &d) = delete; // no assign - ArrangeDialog *parent; + ArrangeDialog *parent; - Gtk::Label anchorPointLabel; + Gtk::Label anchorPointLabel; - Gtk::RadioButtonGroup anchorRadioGroup; - Gtk::RadioButton anchorBoundingBoxRadio; - Gtk::RadioButton anchorObjectPivotRadio; + Gtk::RadioButtonGroup anchorRadioGroup; + Gtk::RadioButton anchorBoundingBoxRadio; + Gtk::RadioButton anchorObjectPivotRadio; Inkscape::UI::Widget::AnchorSelector anchorSelector; - Gtk::Label arrangeOnLabel; + Gtk::Label arrangeOnLabel; - Gtk::RadioButtonGroup arrangeRadioGroup; - Gtk::RadioButton arrangeOnFirstCircleRadio; - Gtk::RadioButton arrangeOnLastCircleRadio; - Gtk::RadioButton arrangeOnParametersRadio; + Gtk::RadioButtonGroup arrangeRadioGroup; + Gtk::RadioButton arrangeOnFirstCircleRadio; + Gtk::RadioButton arrangeOnLastCircleRadio; + Gtk::RadioButton arrangeOnParametersRadio; - Gtk::Grid parametersTable; + Gtk::Grid parametersTable; - Gtk::Label centerLabel; + Gtk::Label centerLabel; Inkscape::UI::Widget::ScalarUnit centerY; Inkscape::UI::Widget::ScalarUnit centerX; - Gtk::Label radiusLabel; + Gtk::Label radiusLabel; Inkscape::UI::Widget::ScalarUnit radiusY; Inkscape::UI::Widget::ScalarUnit radiusX; - Gtk::Label angleLabel; + Gtk::Label angleLabel; Inkscape::UI::Widget::ScalarUnit angleY; Inkscape::UI::Widget::ScalarUnit angleX; - Gtk::CheckButton rotateObjectsCheckBox; - - + Gtk::CheckButton rotateObjectsCheckBox; }; -} //namespace Dialog -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif /* INKSCAPE_UI_DIALOG_POLAR_ARRANGE_TAB_H */ diff --git a/src/ui/dialog/print-colors-preview-dialog.cpp b/src/ui/dialog/print-colors-preview-dialog.cpp index 6371af9d482b19313d4ffb940a737c84e5cc1981..9cbf05d6a135967aec00c9b75dbb146f02ad10e5 100644 --- a/src/ui/dialog/print-colors-preview-dialog.cpp +++ b/src/ui/dialog/print-colors-preview-dialog.cpp @@ -10,11 +10,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ /* -#include "desktop.h" #include "print-colors-preview-dialog.h" -#include "preferences.h" + #include <glibmm/i18n.h> +#include "desktop.h" +#include "preferences.h" + namespace Inkscape { namespace UI { namespace Dialog { diff --git a/src/ui/dialog/print-colors-preview-dialog.h b/src/ui/dialog/print-colors-preview-dialog.h index e40f987fa70bccfaea922a529c0c18be1e43345c..908aba2cd0b857368a1687ed0b108d5cb0c30446 100644 --- a/src/ui/dialog/print-colors-preview-dialog.h +++ b/src/ui/dialog/print-colors-preview-dialog.h @@ -12,22 +12,22 @@ #ifndef INKSCAPE_UI_DIALOG_PRINT_COLORS_PREVIEW_H #define INKSCAPE_UI_DIALOG_PRINT_COLORS_PREVIEW_H +#include <gtkmm/box.h> + #include "ui/widget/panel.h" #include "verbs.h" -#include <gtkmm/box.h> - namespace Inkscape { namespace UI { namespace Dialog { -class PrintColorsPreviewDialog : public UI::Widget::Panel { +class PrintColorsPreviewDialog : public UI::Widget::Panel +{ public: PrintColorsPreviewDialog(); ~PrintColorsPreviewDialog(); - static PrintColorsPreviewDialog &getInstance() - { return *new PrintColorsPreviewDialog(); } + static PrintColorsPreviewDialog &getInstance() { return *new PrintColorsPreviewDialog(); } private: void toggle_cyan(); @@ -35,10 +35,10 @@ private: void toggle_yellow(); void toggle_black(); - Gtk::ToggleButton* cyan; - Gtk::ToggleButton* magenta; - Gtk::ToggleButton* yellow; - Gtk::ToggleButton* black; + Gtk::ToggleButton *cyan; + Gtk::ToggleButton *magenta; + Gtk::ToggleButton *yellow; + Gtk::ToggleButton *black; }; } // namespace Dialog diff --git a/src/ui/dialog/print.cpp b/src/ui/dialog/print.cpp index 3baa2c75427815674a93ce6d24ce6c369580d0f7..405226b420e22429dddb7ea875a5d58b528b4011 100644 --- a/src/ui/dialog/print.cpp +++ b/src/ui/dialog/print.cpp @@ -13,35 +13,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cmath> +#include "print.h" +#include <cmath> +#include <glibmm/i18n.h> #include <gtkmm.h> -#include "inkscape.h" -#include "preferences.h" -#include "print.h" - +#include "document.h" #include "extension/internal/cairo-render-context.h" #include "extension/internal/cairo-renderer.h" -#include "document.h" - -#include "util/units.h" #include "helper/png-write.h" +#include "inkscape.h" +#include "preferences.h" #include "svg/svg-color.h" - -#include <glibmm/i18n.h> - +#include "util/units.h" namespace Inkscape { namespace UI { namespace Dialog { -Print::Print(SPDocument *doc, SPItem *base) : - _doc (doc), - _base (base) +Print::Print(SPDocument *doc, SPItem *base) + : _doc(doc) + , _base(base) { - g_assert (_doc); - g_assert (_base); + g_assert(_doc); + g_assert(_base); _printop = Gtk::PrintOperation::create(); @@ -58,8 +54,7 @@ Print::Print(SPDocument *doc, SPItem *base) : // Default to a custom paper size, in case we can't find a more specific size gdouble doc_width = _doc->getWidth().value("pt"); gdouble doc_height = _doc->getHeight().value("pt"); - page_setup->set_paper_size( - Gtk::PaperSize("custom", "custom", doc_width, doc_height, Gtk::UNIT_POINTS)); + page_setup->set_paper_size(Gtk::PaperSize("custom", "custom", doc_width, doc_height, Gtk::UNIT_POINTS)); // Some print drivers, like the EPSON's ESC/P-R CUPS driver, don't accept custom // page sizes, so we'll try to find a known page size. @@ -77,7 +72,7 @@ Print::Print(SPDocument *doc, SPItem *base) : // attempt to match document size against known paper sizes std::vector<Gtk::PaperSize> known_sizes = Gtk::PaperSize::get_paper_sizes(false); - for (auto& size : known_sizes) { + for (auto &size : known_sizes) { if (fabs(size.get_width(Gtk::UNIT_POINTS) - doc_width) >= 1.0) { // width (short edge) doesn't match continue; @@ -107,14 +102,14 @@ Print::Print(SPDocument *doc, SPItem *base) : _printop->set_custom_tab_label(_("Rendering")); } -void Print::draw_page(const Glib::RefPtr<Gtk::PrintContext>& context, int /*page_nr*/) +void Print::draw_page(const Glib::RefPtr<Gtk::PrintContext> &context, int /*page_nr*/) { // TODO: If the user prints multiple copies we render the whole page for each copy // It would be more efficient to render the page once (e.g. in "begin_print") // and simply print this result as often as necessary Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - //printf("%s %d\n",__FUNCTION__, page_nr); + // printf("%s %d\n",__FUNCTION__, page_nr); if (_workaround._tab->as_bitmap()) { // Render as exported PNG @@ -123,38 +118,38 @@ void Print::draw_page(const Glib::RefPtr<Gtk::PrintContext>& context, int /*page gdouble height = (_workaround._doc)->getHeight().value("px"); gdouble dpi = _workaround._tab->bitmap_dpi(); prefs->setDouble("/dialogs/printing/dpi", dpi); - + std::string tmp_png; std::string tmp_base = "inkscape-print-png-XXXXXX"; int tmp_fd; - if ( (tmp_fd = Glib::file_open_tmp(tmp_png, tmp_base)) >= 0) { + if ((tmp_fd = Glib::file_open_tmp(tmp_png, tmp_base)) >= 0) { close(tmp_fd); guint32 bgcolor = 0x00000000; Inkscape::XML::Node *nv = _workaround._doc->getReprNamedView(); - if (nv && nv->attribute("pagecolor")){ + if (nv && nv->attribute("pagecolor")) { bgcolor = sp_svg_read_color(nv->attribute("pagecolor"), 0xffffff00); } - if (nv && nv->attribute("inkscape:pageopacity")){ + if (nv && nv->attribute("inkscape:pageopacity")) { double opacity = 1.0; - sp_repr_get_double (nv, "inkscape:pageopacity", &opacity); + sp_repr_get_double(nv, "inkscape:pageopacity", &opacity); bgcolor |= SP_COLOR_F_TO_U(opacity); } - sp_export_png_file(_workaround._doc, tmp_png.c_str(), 0.0, 0.0, - width, height, - (unsigned long)(Inkscape::Util::Quantity::convert(width, "px", "in") * dpi), - (unsigned long)(Inkscape::Util::Quantity::convert(height, "px", "in") * dpi), - dpi, dpi, bgcolor, nullptr, nullptr, true, std::vector<SPItem*>()); + sp_export_png_file(_workaround._doc, tmp_png.c_str(), 0.0, 0.0, width, height, + (unsigned long)(Inkscape::Util::Quantity::convert(width, "px", "in") * dpi), + (unsigned long)(Inkscape::Util::Quantity::convert(height, "px", "in") * dpi), dpi, dpi, + bgcolor, nullptr, nullptr, true, std::vector<SPItem *>()); // This doesn't seem to work: - //context->set_cairo_context ( Cairo::Context::create (Cairo::ImageSurface::create_from_png (tmp_png) ), dpi, dpi ); + // context->set_cairo_context ( Cairo::Context::create (Cairo::ImageSurface::create_from_png (tmp_png) ), + // dpi, dpi ); // // so we'll use a surface pattern blat instead... // // but the C++ interface isn't implemented in cairomm: - //context->get_cairo_context ()->set_source_surface(Cairo::ImageSurface::create_from_png (tmp_png) ); + // context->get_cairo_context ()->set_source_surface(Cairo::ImageSurface::create_from_png (tmp_png) ); // // so do it in C: { @@ -171,13 +166,11 @@ void Print::draw_page(const Glib::RefPtr<Gtk::PrintContext>& context, int /*page } // Clean up - unlink (tmp_png.c_str()); - } - else { + unlink(tmp_png.c_str()); + } else { g_warning("%s", _("Could not open temporary PNG for bitmap printing")); } - } - else { + } else { // Render as vectors prefs->setBool("/dialogs/printing/asbitmap", false); Inkscape::Extension::Internal::CairoRenderer renderer; @@ -194,34 +187,31 @@ void Print::draw_page(const Glib::RefPtr<Gtk::PrintContext>& context, int /*page bool ret = ctx->setSurfaceTarget(surface->cobj(), true, &ctm); if (ret) { - ret = renderer.setupDocument (ctx, _workaround._doc, TRUE, 0., nullptr); + ret = renderer.setupDocument(ctx, _workaround._doc, TRUE, 0., nullptr); if (ret) { renderer.renderItem(ctx, _workaround._base); - ctx->finish(false); // do not finish the cairo_surface_t - it's owned by our GtkPrintContext! - } - else { + ctx->finish(false); // do not finish the cairo_surface_t - it's owned by our GtkPrintContext! + } else { g_warning("%s", _("Could not set up Document")); } - } - else { + } else { g_warning("%s", _("Failed to set CairoRenderContext")); } // Clean up renderer.destroyContext(ctx); } - } Gtk::Widget *Print::create_custom_widget() { - //printf("%s\n",__FUNCTION__); + // printf("%s\n",__FUNCTION__); return &_tab; } -void Print::begin_print(const Glib::RefPtr<Gtk::PrintContext>&) +void Print::begin_print(const Glib::RefPtr<Gtk::PrintContext> &) { - //printf("%s\n",__FUNCTION__); + // printf("%s\n",__FUNCTION__); _printop->set_n_pages(1); } @@ -246,7 +236,6 @@ Gtk::PrintOperationResult Print::run(Gtk::PrintOperationAction, Gtk::Window &par return Gtk::PRINT_OPERATION_RESULT_ERROR; } - } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/print.h b/src/ui/dialog/print.h index d0152100afcdcffe7c55d6caf79ec53944e49678..330e27526f58a9a52844cbb2cf8462b2b2776b77 100644 --- a/src/ui/dialog/print.h +++ b/src/ui/dialog/print.h @@ -12,13 +12,13 @@ #ifndef INKSCAPE_UI_DIALOG_PRINT_H #define INKSCAPE_UI_DIALOG_PRINT_H -#include "ui/widget/rendering-options.h" #include <gtkmm/printoperation.h> // GtkMM +#include "ui/widget/rendering-options.h" + class SPItem; class SPDocument; - /* * gtk 2.12.0 has a bug (http://bugzilla.gnome.org/show_bug.cgi?id=482089) * where it fails to correctly deal with gtkmm signal management. As a result @@ -30,7 +30,7 @@ class SPDocument; struct workaround_gtkmm { SPDocument *_doc; - SPItem *_base; + SPItem *_base; Inkscape::UI::Widget::RenderingOptions *_tab; }; @@ -38,28 +38,29 @@ namespace Inkscape { namespace UI { namespace Dialog { -struct PrinterSettings { +struct PrinterSettings +{ Glib::RefPtr<Gtk::PrintSettings> _gtk_print_settings; }; -class Print { +class Print +{ public: Print(SPDocument *doc, SPItem *base); Gtk::PrintOperationResult run(Gtk::PrintOperationAction, Gtk::Window &parent_window); protected: - private: Glib::RefPtr<Gtk::PrintOperation> _printop; SPDocument *_doc; - SPItem *_base; + SPItem *_base; Inkscape::UI::Widget::RenderingOptions _tab; struct workaround_gtkmm _workaround; - void draw_page(const Glib::RefPtr<Gtk::PrintContext>& context, int /*page_nr*/); + void draw_page(const Glib::RefPtr<Gtk::PrintContext> &context, int /*page_nr*/); Gtk::Widget *create_custom_widget(); - void begin_print(const Glib::RefPtr<Gtk::PrintContext>&); + void begin_print(const Glib::RefPtr<Gtk::PrintContext> &); }; } // namespace Dialog diff --git a/src/ui/dialog/prototype.cpp b/src/ui/dialog/prototype.cpp index 90ab6e53fbeaf5a9206fc4556970b0da29efe1c1..d3d82c4a0b67451aad5afe40d5ad06e38bb9459b 100644 --- a/src/ui/dialog/prototype.cpp +++ b/src/ui/dialog/prototype.cpp @@ -33,7 +33,7 @@ Prototype::Prototype() std::cout << "Prototype::Prototype()" << std::endl; // A widget for demonstration that displays the current SVG's id. - _getContents()->pack_start(label); // Panel::_getContents() + _getContents()->pack_start(label); // Panel::_getContents() } Prototype::~Prototype() @@ -52,8 +52,7 @@ Prototype::~Prototype() * (When a dialog is closed, it is not destroyed so the constructor is not called. * This function can handle any reinitialization needed.) */ -void -Prototype::present() +void Prototype::present() { std::cout << "Prototype::present()" << std::endl; UI::Widget::Panel::present(); @@ -64,12 +63,12 @@ Prototype::present() * opened, it will replace the default document in the same desktop. This function handles the * change. Bug: This is called twice for some reason. */ -void -Prototype::handleDocumentReplaced(SPDesktop *desktop, SPDocument * /* document */) +void Prototype::handleDocumentReplaced(SPDesktop *desktop, SPDocument * /* document */) { std::cout << "Prototype::handleDocumentReplaced()" << std::endl; if (getDesktop() != desktop) { - std::cerr << "Prototype::handleDocumentReplaced(): Error: panel desktop not equal to existing desktop!" << std::endl; + std::cerr << "Prototype::handleDocumentReplaced(): Error: panel desktop not equal to existing desktop!" + << std::endl; } connectionSelectionChanged.disconnect(); @@ -77,8 +76,8 @@ Prototype::handleDocumentReplaced(SPDesktop *desktop, SPDocument * /* document * if (!desktop) return; - connectionSelectionChanged = desktop->getSelection()->connectChanged( - sigc::hide(sigc::mem_fun(this, &Prototype::handleSelectionChanged))); + connectionSelectionChanged = + desktop->getSelection()->connectChanged(sigc::hide(sigc::mem_fun(this, &Prototype::handleSelectionChanged))); // Update demonstration widget. updateLabel(); @@ -87,8 +86,8 @@ Prototype::handleDocumentReplaced(SPDesktop *desktop, SPDocument * /* document * /* * When a dialog is floating, it is connected to the active desktop. */ -void -Prototype::setDesktop(SPDesktop* desktop) { +void Prototype::setDesktop(SPDesktop *desktop) +{ std::cout << "Prototype::handleDesktopChanged(): " << desktop << std::endl; // Connections are disconnect safe. @@ -97,8 +96,8 @@ Prototype::setDesktop(SPDesktop* desktop) { Panel::setDesktop(desktop); if (desktop) { - connectionDocumentReplaced = desktop->connectDocumentReplaced( - sigc::mem_fun(this, &Prototype::handleDocumentReplaced)); + connectionDocumentReplaced = + desktop->connectDocumentReplaced(sigc::mem_fun(this, &Prototype::handleDocumentReplaced)); } handleDocumentReplaced(desktop, nullptr); @@ -107,8 +106,8 @@ Prototype::setDesktop(SPDesktop* desktop) { /* * Handle a change in which objects are selected in a document. */ -void -Prototype::handleSelectionChanged() { +void Prototype::handleSelectionChanged() +{ std::cout << "Prototype::handleSelectionChanged()" << std::endl; // Update demonstration widget. @@ -118,12 +117,11 @@ Prototype::handleSelectionChanged() { /* * Update label... just a utility function for this example. */ -void -Prototype::updateLabel() { - - const gchar* root_id = getDesktop()->getDocument()->getRoot()->getId(); +void Prototype::updateLabel() +{ + const gchar *root_id = getDesktop()->getDocument()->getRoot()->getId(); Glib::ustring label_string("Document's SVG id: "); - label_string += (root_id?root_id:"null"); + label_string += (root_id ? root_id : "null"); label.set_label(label_string); } diff --git a/src/ui/dialog/prototype.h b/src/ui/dialog/prototype.h index dd4796c0bc3b6e407521ea3ce065cc608fbe5160..2dbb37ccf04d05fda6cf8523dfa6e46db13f9b8b 100644 --- a/src/ui/dialog/prototype.h +++ b/src/ui/dialog/prototype.h @@ -14,6 +14,7 @@ #define SEEN_PROTOTYPE_PANEL_H #include <iostream> + #include "ui/widget/panel.h" // Only to display status. @@ -31,12 +32,11 @@ class Prototype : public UI::Widget::Panel public: ~Prototype() override; - static Prototype& getInstance() { return *new Prototype(); }; + static Prototype &getInstance() { return *new Prototype(); }; void present() override; private: - // No default constructor, noncopyable, nonassignable Prototype(); Prototype(Prototype const &d) = delete; @@ -46,7 +46,7 @@ private: sigc::connection connectionDocumentReplaced; sigc::connection connectionSelectionChanged; - void handleDocumentReplaced(SPDesktop* desktop, SPDocument *document); + void handleDocumentReplaced(SPDesktop *desktop, SPDocument *document); void setDesktop(SPDesktop *) override; void handleSelectionChanged(); @@ -55,9 +55,9 @@ private: void updateLabel(); }; -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif // SEEN_PROTOTYPE_PANEL_H diff --git a/src/ui/dialog/save-template-dialog.cpp b/src/ui/dialog/save-template-dialog.cpp index a240f619d8c062409963f0901b3d9189168bb135..e54ec92b24806201cef0546190f6c756f1381f50 100644 --- a/src/ui/dialog/save-template-dialog.cpp +++ b/src/ui/dialog/save-template-dialog.cpp @@ -9,8 +9,6 @@ */ #include "save-template-dialog.h" -#include "file.h" -#include "io/resource.h" #include <glibmm/i18n.h> #include <gtkmm/builder.h> @@ -19,12 +17,15 @@ #include <gtkmm/entry.h> #include <gtkmm/window.h> +#include "file.h" +#include "io/resource.h" + namespace Inkscape { namespace UI { namespace Dialog { -SaveTemplate::SaveTemplate(Gtk::Window &parent) { - +SaveTemplate::SaveTemplate(Gtk::Window &parent) +{ std::string gladefile = get_filename_string(Inkscape::IO::Resource::UIS, "dialog-save-template.glade"); Glib::RefPtr<Gtk::Builder> builder; try { @@ -53,34 +54,34 @@ SaveTemplate::SaveTemplate(Gtk::Window &parent) { dialog->show_all(); } -void SaveTemplate::on_name_changed() { - +void SaveTemplate::on_name_changed() +{ bool has_text = name->get_text_length() != 0; dialog->set_response_sensitive(Gtk::RESPONSE_OK, has_text); } -void SaveTemplate::save_template(Gtk::Window &parent) { - - sp_file_save_template(parent, name->get_text(), author->get_text(), description->get_text(), - keywords->get_text(), set_default_template->get_active()); +void SaveTemplate::save_template(Gtk::Window &parent) +{ + sp_file_save_template(parent, name->get_text(), author->get_text(), description->get_text(), keywords->get_text(), + set_default_template->get_active()); } -void SaveTemplate::save_document_as_template(Gtk::Window &parent) { - +void SaveTemplate::save_document_as_template(Gtk::Window &parent) +{ SaveTemplate dialog(parent); int response = dialog.dialog->run(); switch (response) { - case Gtk::RESPONSE_OK: - dialog.save_template(parent); - break; - default: - break; + case Gtk::RESPONSE_OK: + dialog.save_template(parent); + break; + default: + break; } dialog.dialog->close(); } -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape diff --git a/src/ui/dialog/save-template-dialog.h b/src/ui/dialog/save-template-dialog.h index eb702ca656a2a333a485d674292cdc296d142869..ca976c1766b6b55d41fa321a529b47649561084d 100644 --- a/src/ui/dialog/save-template-dialog.h +++ b/src/ui/dialog/save-template-dialog.h @@ -18,7 +18,7 @@ class CheckButton; class Dialog; class Entry; class Window; -} +} // namespace Gtk namespace Inkscape { namespace UI { @@ -26,17 +26,13 @@ namespace Dialog { class SaveTemplate { - public: - static void save_document_as_template(Gtk::Window &parentWindow); protected: - void on_name_changed(); private: - Gtk::Dialog *dialog; Gtk::Entry *name; @@ -48,9 +44,8 @@ private: SaveTemplate(Gtk::Window &parent); void save_template(Gtk::Window &parent); - }; -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/dialog/selectorsdialog.cpp b/src/ui/dialog/selectorsdialog.cpp index abff84dd62afa12b8c473010ef236308ac77d29e..6781637bf7a85fb21b8f501e77de285e4d3280a7 100644 --- a/src/ui/dialog/selectorsdialog.cpp +++ b/src/ui/dialog/selectorsdialog.cpp @@ -14,6 +14,13 @@ */ #include "selectorsdialog.h" + +#include <glibmm/i18n.h> +#include <glibmm/regex.h> +#include <map> +#include <regex> +#include <utility> + #include "attribute-rel-svg.h" #include "document-undo.h" #include "inkscape.h" @@ -23,18 +30,10 @@ #include "ui/icon-names.h" #include "ui/widget/iconrenderer.h" #include "verbs.h" - #include "xml/attribute-record.h" #include "xml/node-observer.h" #include "xml/sp-css-attr.h" -#include <glibmm/i18n.h> -#include <glibmm/regex.h> - -#include <map> -#include <regex> -#include <utility> - // G_MESSAGES_DEBUG=DEBUG_SELECTORSDIALOG gdb ./inkscape // #define DEBUG_SELECTORSDIALOG // #define G_LOG_DOMAIN "SELECTORSDIALOG" @@ -47,12 +46,12 @@ using Inkscape::XML::AttributeRecord; * This macro is used to remove spaces around selectors or any strings when * parsing is done to update XML style element or row labels in this dialog. */ -#define REMOVE_SPACES(x) \ - x.erase(0, x.find_first_not_of(' ')); \ - if (x.size() && x[0] == ',') \ - x.erase(0, 1); \ - if (x.size() && x[x.size() - 1] == ',') \ - x.erase(x.size() - 1, 1); \ +#define REMOVE_SPACES(x) \ + x.erase(0, x.find_first_not_of(' ')); \ + if (x.size() && x[0] == ',') \ + x.erase(0, 1); \ + if (x.size() && x[x.size() - 1] == ',') \ + x.erase(x.size() - 1, 1); \ x.erase(x.find_last_not_of(' ') + 1); namespace Inkscape { @@ -60,27 +59,25 @@ namespace UI { namespace Dialog { // Keeps a watch on style element -class SelectorsDialog::NodeObserver : public Inkscape::XML::NodeObserver { - public: +class SelectorsDialog::NodeObserver : public Inkscape::XML::NodeObserver +{ +public: NodeObserver(SelectorsDialog *selectorsdialog) : _selectorsdialog(selectorsdialog) { g_debug("SelectorsDialog::NodeObserver: Constructor"); }; - void notifyContentChanged(Inkscape::XML::Node &node, - Inkscape::Util::ptr_shared old_content, - Inkscape::Util::ptr_shared new_content) override; + void notifyContentChanged(Inkscape::XML::Node &node, Inkscape::Util::ptr_shared old_content, + Inkscape::Util::ptr_shared new_content) override; SelectorsDialog *_selectorsdialog; }; - void SelectorsDialog::NodeObserver::notifyContentChanged(Inkscape::XML::Node & /*node*/, Inkscape::Util::ptr_shared /*old_content*/, Inkscape::Util::ptr_shared /*new_content*/) { - g_debug("SelectorsDialog::NodeObserver::notifyContentChanged"); _selectorsdialog->_scroollock = true; _selectorsdialog->_updating = false; @@ -88,36 +85,32 @@ void SelectorsDialog::NodeObserver::notifyContentChanged(Inkscape::XML::Node & / _selectorsdialog->_selectRow(); } - // Keeps a watch for new/removed/changed nodes // (Must update objects that selectors match.) -class SelectorsDialog::NodeWatcher : public Inkscape::XML::NodeObserver { - public: +class SelectorsDialog::NodeWatcher : public Inkscape::XML::NodeObserver +{ +public: NodeWatcher(SelectorsDialog *selectorsdialog) : _selectorsdialog(selectorsdialog) { g_debug("SelectorsDialog::NodeWatcher: Constructor"); }; - void notifyChildAdded( Inkscape::XML::Node &/*node*/, - Inkscape::XML::Node &child, - Inkscape::XML::Node */*prev*/ ) override + void notifyChildAdded(Inkscape::XML::Node & /*node*/, Inkscape::XML::Node &child, + Inkscape::XML::Node * /*prev*/) override { - _selectorsdialog->_nodeAdded(child); + _selectorsdialog->_nodeAdded(child); } - void notifyChildRemoved( Inkscape::XML::Node &/*node*/, - Inkscape::XML::Node &child, - Inkscape::XML::Node */*prev*/ ) override + void notifyChildRemoved(Inkscape::XML::Node & /*node*/, Inkscape::XML::Node &child, + Inkscape::XML::Node * /*prev*/) override { - _selectorsdialog->_nodeRemoved(child); + _selectorsdialog->_nodeRemoved(child); } - void notifyAttributeChanged( Inkscape::XML::Node &node, - GQuark qname, - Util::ptr_shared /*old_value*/, - Util::ptr_shared /*new_value*/ ) override { - + void notifyAttributeChanged(Inkscape::XML::Node &node, GQuark qname, Util::ptr_shared /*old_value*/, + Util::ptr_shared /*new_value*/) override + { static GQuark const CODE_id = g_quark_from_static_string("id"); static GQuark const CODE_class = g_quark_from_static_string("class"); @@ -147,7 +140,6 @@ void SelectorsDialog::_nodeRemoved(Inkscape::XML::Node &repr) void SelectorsDialog::_nodeChanged(Inkscape::XML::Node &object) { - g_debug("SelectorsDialog::NodeChanged"); _scroollock = true; @@ -158,7 +150,6 @@ void SelectorsDialog::_nodeChanged(Inkscape::XML::Node &object) SelectorsDialog::TreeStore::TreeStore() = default; - /** * Allow dragging only selectors. */ @@ -189,7 +180,6 @@ bool SelectorsDialog::TreeStore::row_drop_possible_vfunc(const Gtk::TreeModel::P return dest_parent.empty(); } - // This is only here to handle updating style element after a drag and drop. void SelectorsDialog::TreeStore::on_row_deleted(const TreeModel::Path &path) { @@ -201,7 +191,6 @@ void SelectorsDialog::TreeStore::on_row_deleted(const TreeModel::Path &path) _selectorsdialog->_readStyleElement(); } - Glib::RefPtr<SelectorsDialog::TreeStore> SelectorsDialog::TreeStore::create(SelectorsDialog *selectorsdialog) { g_debug("SelectorsDialog::TreeStore::create"); @@ -231,8 +220,7 @@ SelectorsDialog::SelectorsDialog() m_styletextwatcher.reset(new SelectorsDialog::NodeObserver(this)); // Tree - Inkscape::UI::Widget::IconRenderer * addRenderer = manage( - new Inkscape::UI::Widget::IconRenderer() ); + Inkscape::UI::Widget::IconRenderer *addRenderer = manage(new Inkscape::UI::Widget::IconRenderer()); addRenderer->add_icon("edit-delete"); addRenderer->add_icon("list-add"); addRenderer->add_icon("empty-icon"); @@ -241,10 +229,10 @@ SelectorsDialog::SelectorsDialog() _treeView.set_headers_visible(false); _treeView.enable_model_drag_source(); - _treeView.enable_model_drag_dest( Gdk::ACTION_MOVE ); + _treeView.enable_model_drag_dest(Gdk::ACTION_MOVE); int addCol = _treeView.append_column("", *addRenderer) - 1; Gtk::TreeViewColumn *col = _treeView.get_column(addCol); - if ( col ) { + if (col) { col->add_attribute(addRenderer->property_icon(), _mColumns._colType); } @@ -257,7 +245,6 @@ SelectorsDialog::SelectorsDialog() } _treeView.set_expander_column(*(_treeView.get_column(1))); - // Signal handlers _treeView.signal_button_release_event().connect( // Needs to be release, not press. sigc::mem_fun(*this, &SelectorsDialog::_handleButtonEvent), false); @@ -274,7 +261,6 @@ SelectorsDialog::SelectorsDialog() show_all(); } - void SelectorsDialog::_vscrool() { if (!_scroollock) { @@ -410,7 +396,6 @@ SelectorsDialog::~SelectorsDialog() _selection_changed_connection.disconnect(); } - /** * @return Inkscape::XML::Node* pointing to a style element's text node. * Returns the style element's text node. If there is no style element, one is created. @@ -444,10 +429,11 @@ void SelectorsDialog::_readStyleElement() { g_debug("SelectorsDialog::_readStyleElement(): updating %s", (_updating ? "true" : "false")); - if (_updating) return; // Don't read if we wrote style element. + if (_updating) + return; // Don't read if we wrote style element. _updating = true; _scroollock = true; - Inkscape::XML::Node * textNode = _getStyleTextNode(); + Inkscape::XML::Node *textNode = _getStyleTextNode(); // Get content from style text node. std::string content = (textNode && textNode->content()) ? textNode->content() : ""; @@ -503,9 +489,8 @@ void SelectorsDialog::_readStyleElement() _store->clear(); bool rewrite = false; - std::vector<SPObject *> objVec; - for (unsigned i = 0; i < tokens.size()-1; i += 2) { + for (unsigned i = 0; i < tokens.size() - 1; i += 2) { Glib::ustring selector = tokens[i]; REMOVE_SPACES(selector); // Remove leading/trailing spaces std::vector<Glib::ustring> selectordata = Glib::Regex::split_simple(";", selector); @@ -539,8 +524,8 @@ void SelectorsDialog::_readStyleElement() Glib::ustring properties; // Check to make sure we do have a value to match selector. - if ((i+1) < tokens.size()) { - properties = tokens[i+1]; + if ((i + 1) < tokens.size()) { + properties = tokens[i + 1]; } else { std::cerr << "SelectorsDialog::_readStyleElement(): Missing values " "for last selector!" @@ -555,10 +540,10 @@ void SelectorsDialog::_readStyleElement() } std::vector<Glib::ustring> properties_data = Glib::Regex::split_simple(";", properties); Gtk::TreeModel::Row row = *(_store->append()); - row[_mColumns._colSelector] = selector; + row[_mColumns._colSelector] = selector; row[_mColumns._colExpand] = colExpand; row[_mColumns._colType] = colType; - row[_mColumns._colObj] = objVec; + row[_mColumns._colObj] = objVec; row[_mColumns._colProperties] = properties; row[_mColumns._colVisible] = true; row[_mColumns._colSelected] = 400; @@ -578,7 +563,6 @@ void SelectorsDialog::_readStyleElement() } } - _updating = false; if (rewrite) { _writeStyleElement(); @@ -605,7 +589,6 @@ void SelectorsDialog::_rowCollapse(const Gtk::TreeModel::iterator &iter, const G */ void SelectorsDialog::_writeStyleElement() { - if (_updating) { return; } @@ -615,7 +598,7 @@ void SelectorsDialog::_writeStyleElement() _scroollock = true; _updating = true; Glib::ustring styleContent = ""; - for (auto& row: _store->children()) { + for (auto &row : _store->children()) { Glib::ustring selector = row[_mColumns._colSelector]; #if 0 REMOVE_SPACES(selector); @@ -893,7 +876,6 @@ void SelectorsDialog::_removeFromSelector(Gtk::TreeModel::Row row) } } - /** * @param sel * @return This function returns a comma separated list of ids for objects in input vector. @@ -904,7 +886,7 @@ Glib::ustring SelectorsDialog::_getIdList(std::vector<SPObject *> sel) g_debug("SelectorsDialog::_getIdList"); Glib::ustring str; - for (auto& obj: sel) { + for (auto &obj : sel) { char const *id = obj->getId(); if (id) { if (!str.empty()) { @@ -923,7 +905,6 @@ Glib::ustring SelectorsDialog::_getIdList(std::vector<SPObject *> sel) */ std::vector<SPObject *> SelectorsDialog::_getObjVec(Glib::ustring selector) { - g_debug("SelectorsDialog::_getObjVec: | %s |", selector.c_str()); g_assert(selector.find(";") == Glib::ustring::npos); @@ -931,7 +912,6 @@ std::vector<SPObject *> SelectorsDialog::_getObjVec(Glib::ustring selector) return getDesktop()->getDocument()->getObjectsBySelector(selector); } - /** * @param objs: list of objects to insert class * @param class: class to insert @@ -941,7 +921,7 @@ void SelectorsDialog::_insertClass(const std::vector<SPObject *> &objVec, const { g_debug("SelectorsDialog::_insertClass"); - for (auto& obj: objVec) { + for (auto &obj : objVec) { _insertClass(obj, className); } } @@ -1025,7 +1005,6 @@ void SelectorsDialog::_removeClass(SPObject *obj, const Glib::ustring &className } } - /** * @param eventX * @param eventY @@ -1074,19 +1053,18 @@ void SelectorsDialog::_addSelector() g_debug("SelectorsDialog::_addSelector: Entrance"); _scroollock = true; // Store list of selected elements on desktop (not to be confused with selector). - Inkscape::Selection* selection = getDesktop()->getSelection(); - std::vector<SPObject *> objVec( selection->objects().begin(), - selection->objects().end() ); + Inkscape::Selection *selection = getDesktop()->getSelection(); + std::vector<SPObject *> objVec(selection->objects().begin(), selection->objects().end()); // ==== Create popup dialog ==== - Gtk::Dialog *textDialogPtr = new Gtk::Dialog(); + Gtk::Dialog *textDialogPtr = new Gtk::Dialog(); textDialogPtr->property_modal() = true; textDialogPtr->property_title() = _("CSS selector"); textDialogPtr->property_window_position() = Gtk::WIN_POS_CENTER_ON_PARENT; textDialogPtr->add_button(_("Cancel"), Gtk::RESPONSE_CANCEL); - textDialogPtr->add_button(_("Add"), Gtk::RESPONSE_OK); + textDialogPtr->add_button(_("Add"), Gtk::RESPONSE_OK); - Gtk::Entry *textEditPtr = manage ( new Gtk::Entry() ); + Gtk::Entry *textEditPtr = manage(new Gtk::Entry()); textEditPtr->signal_activate().connect( sigc::bind<Gtk::Dialog *>(sigc::mem_fun(*this, &SelectorsDialog::_closeDialog), textDialogPtr)); textDialogPtr->get_content_area()->pack_start(*textEditPtr, Gtk::PACK_SHRINK); @@ -1109,14 +1087,13 @@ void SelectorsDialog::_addSelector() textDialogPtr->get_preferred_size(sreq1, sreq2); int minWidth = 200; int minHeight = 100; - minWidth = (sreq2.width > minWidth ? sreq2.width : minWidth ); + minWidth = (sreq2.width > minWidth ? sreq2.width : minWidth); minHeight = (sreq2.height > minHeight ? sreq2.height : minHeight); textDialogPtr->set_size_request(minWidth, minHeight); textEditPtr->show(); textLabelPtr->hide(); textDialogPtr->show(); - // ==== Get response ==== int result = -1; bool invalid = true; @@ -1208,7 +1185,10 @@ void SelectorsDialog::_addSelector() _vadj->set_value(std::min(_scroolpos, _vadj->get_upper())); } -void SelectorsDialog::_closeDialog(Gtk::Dialog *textDialogPtr) { textDialogPtr->response(Gtk::RESPONSE_OK); } +void SelectorsDialog::_closeDialog(Gtk::Dialog *textDialogPtr) +{ + textDialogPtr->response(Gtk::RESPONSE_OK); +} /** * This function deletes selector when '-' at the bottom is clicked. @@ -1280,14 +1260,16 @@ bool SelectorsDialog::_handleButtonEvent(GdkEventButton *event) class PropertyData { public: - PropertyData() = default;; - PropertyData(Glib::ustring name) : _name(std::move(name)) {}; + PropertyData() = default; + ; + PropertyData(Glib::ustring name) + : _name(std::move(name)){}; void _setSheetValue(Glib::ustring value) { _sheetValue = value; }; - void _setAttrValue(Glib::ustring value) { _attrValue = value; }; - Glib::ustring _getName() { return _name; }; + void _setAttrValue(Glib::ustring value) { _attrValue = value; }; + Glib::ustring _getName() { return _name; }; Glib::ustring _getSheetValue() { return _sheetValue; }; - Glib::ustring _getAttrValue() { return _attrValue; }; + Glib::ustring _getAttrValue() { return _attrValue; }; private: Glib::ustring _name; @@ -1297,7 +1279,6 @@ private: // ------------------------------------------------------------------- - /** * Handle document replaced. (Happens when a default document is immediately replaced by another * document in a new window.) @@ -1320,7 +1301,6 @@ void SelectorsDialog::_handleDocumentReplaced(SPDesktop *desktop, SPDocument * / _selectRow(); } - /* * When a dialog is floating, it is connected to the active desktop. */ @@ -1330,7 +1310,7 @@ void SelectorsDialog::setDesktop(SPDesktop *desktop) _document_replaced_connection.disconnect(); - Panel::setDesktop( desktop ); + Panel::setDesktop(desktop); _handleDocumentReplaced(desktop, nullptr); @@ -1343,7 +1323,6 @@ void SelectorsDialog::setDesktop(SPDesktop *desktop) desktop->connectDocumentReplaced(sigc::mem_fun(this, &SelectorsDialog::_handleDocumentReplaced)); } - /* * Handle a change in which objects are selected in a document. */ @@ -1356,7 +1335,6 @@ void SelectorsDialog::_handleSelectionChanged() _selectRow(); } - /** * @param event * This function detects single or double click on a selector in any row. Clicking @@ -1377,7 +1355,6 @@ void SelectorsDialog::_buttonEventsSelectObjs(GdkEventButton *event) _updating = false; } - /** * This function selects the row in treeview corresponding to an object selected * in the drawing. If more than one row matches, the first is chosen. @@ -1399,11 +1376,12 @@ void SelectorsDialog::_selectRow() } else if (selectedrows.size() == 0) { _del.show(); } - if (_updating || !getDesktop()) return; // Avoid updating if we have set row via dialog. + if (_updating || !getDesktop()) + return; // Avoid updating if we have set row via dialog. _treeView.get_selection()->unselect_all(); Gtk::TreeModel::Children children = _store->children(); - Inkscape::Selection* selection = getDesktop()->getSelection(); + Inkscape::Selection *selection = getDesktop()->getSelection(); SPObject *obj = nullptr; if (!selection->isEmpty()) { obj = selection->objects().back(); @@ -1454,10 +1432,9 @@ void SelectorsDialog::_styleButton(Gtk::Button &btn, char const *iconName, char gtk_widget_show(child); btn.add(*manage(Glib::wrap(child))); btn.set_relief(Gtk::RELIEF_NONE); - btn.set_tooltip_text (tooltip); + btn.set_tooltip_text(tooltip); } - } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/selectorsdialog.h b/src/ui/dialog/selectorsdialog.h index f1579524ab5ae1bf2f7fe4e64483b0f74298a969..d9f58907f0aeca91dc4efb2efcfe03b4fc5eab20 100644 --- a/src/ui/dialog/selectorsdialog.h +++ b/src/ui/dialog/selectorsdialog.h @@ -15,9 +15,6 @@ #ifndef SELECTORSDIALOG_H #define SELECTORSDIALOG_H -#include "ui/dialog/dialog-manager.h" -#include "ui/dialog/styledialog.h" -#include "ui/widget/panel.h" #include <gtkmm/dialog.h> #include <gtkmm/paned.h> #include <gtkmm/radiobutton.h> @@ -27,13 +24,15 @@ #include <gtkmm/treeselection.h> #include <gtkmm/treestore.h> #include <gtkmm/treeview.h> +#include <memory> #include <ui/widget/panel.h> +#include <vector> +#include "ui/dialog/dialog-manager.h" +#include "ui/dialog/styledialog.h" +#include "ui/widget/panel.h" #include "xml/helper-observer.h" -#include <memory> -#include <vector> - namespace Inkscape { namespace UI { namespace Dialog { @@ -49,9 +48,9 @@ namespace Dialog { * 1. The text node of the style element. * 2. The Gtk::TreeModel. */ -class SelectorsDialog : public Widget::Panel { - - public: +class SelectorsDialog : public Widget::Panel +{ +public: ~SelectorsDialog() override; // No default constructor, noncopyable, nonassignable SelectorsDialog(); @@ -59,21 +58,33 @@ class SelectorsDialog : public Widget::Panel { SelectorsDialog operator=(SelectorsDialog const &d) = delete; static SelectorsDialog &getInstance() { return *new SelectorsDialog(); } - private: +private: // Monitor <style> element for changes. class NodeObserver; // Monitor all objects for addition/removal/attribute change class NodeWatcher; - enum SelectorType { CLASS, ID, TAG }; - void _nodeAdded( Inkscape::XML::Node &repr ); - void _nodeRemoved( Inkscape::XML::Node &repr ); - void _nodeChanged( Inkscape::XML::Node &repr ); + enum SelectorType + { + CLASS, + ID, + TAG + }; + void _nodeAdded(Inkscape::XML::Node &repr); + void _nodeRemoved(Inkscape::XML::Node &repr); + void _nodeChanged(Inkscape::XML::Node &repr); // Data structure - enum coltype { OBJECT, SELECTOR, OTHER }; - class ModelColumns : public Gtk::TreeModel::ColumnRecord { + enum coltype + { + OBJECT, + SELECTOR, + OTHER + }; + class ModelColumns : public Gtk::TreeModel::ColumnRecord + { public: - ModelColumns() { + ModelColumns() + { add(_colSelector); add(_colExpand); add(_colType); @@ -82,13 +93,13 @@ class SelectorsDialog : public Widget::Panel { add(_colVisible); add(_colSelected); } - Gtk::TreeModelColumn<Glib::ustring> _colSelector; // Selector or matching object id. - Gtk::TreeModelColumn<bool> _colExpand; // Open/Close store row. - Gtk::TreeModelColumn<gint> _colType; // Selector row or child object row. - Gtk::TreeModelColumn<std::vector<SPObject *> > _colObj; // List of matching objects. - Gtk::TreeModelColumn<Glib::ustring> _colProperties; // List of properties. - Gtk::TreeModelColumn<bool> _colVisible; // Make visible or not. - Gtk::TreeModelColumn<gint> _colSelected; // Make selected. + Gtk::TreeModelColumn<Glib::ustring> _colSelector; // Selector or matching object id. + Gtk::TreeModelColumn<bool> _colExpand; // Open/Close store row. + Gtk::TreeModelColumn<gint> _colType; // Selector row or child object row. + Gtk::TreeModelColumn<std::vector<SPObject *>> _colObj; // List of matching objects. + Gtk::TreeModelColumn<Glib::ustring> _colProperties; // List of properties. + Gtk::TreeModelColumn<bool> _colVisible; // Make visible or not. + Gtk::TreeModelColumn<gint> _colSelected; // Make selected. }; ModelColumns _mColumns; @@ -98,19 +109,20 @@ class SelectorsDialog : public Widget::Panel { // TreeStore implements simple drag and drop (DND) but there appears no way to know when a DND // has been completed (other than doing the whole DND ourselves). As a hack, we use // on_row_deleted to trigger write of style element. - class TreeStore : public Gtk::TreeStore { + class TreeStore : public Gtk::TreeStore + { protected: TreeStore(); - bool row_draggable_vfunc(const Gtk::TreeModel::Path& path) const override; - bool row_drop_possible_vfunc(const Gtk::TreeModel::Path& path, - const Gtk::SelectionData& selection_data) const override; - void on_row_deleted(const TreeModel::Path& path) override; + bool row_draggable_vfunc(const Gtk::TreeModel::Path &path) const override; + bool row_drop_possible_vfunc(const Gtk::TreeModel::Path &path, + const Gtk::SelectionData &selection_data) const override; + void on_row_deleted(const TreeModel::Path &path) override; public: - static Glib::RefPtr<SelectorsDialog::TreeStore> create(SelectorsDialog *styledialog); + static Glib::RefPtr<SelectorsDialog::TreeStore> create(SelectorsDialog *styledialog); private: - SelectorsDialog *_selectorsdialog; + SelectorsDialog *_selectorsdialog; }; // TreeView @@ -137,13 +149,13 @@ class SelectorsDialog : public Widget::Panel { std::unique_ptr<Inkscape::XML::NodeObserver> m_nodewatcher; std::unique_ptr<Inkscape::XML::NodeObserver> m_styletextwatcher; void _updateWatchers(SPDesktop *); - + // Manipulate Tree void _addToSelector(Gtk::TreeModel::Row row); void _removeFromSelector(Gtk::TreeModel::Row row); Glib::ustring _getIdList(std::vector<SPObject *>); std::vector<SPObject *> _getObjVec(Glib::ustring selector); - void _insertClass(const std::vector<SPObject *>& objVec, const Glib::ustring& className); + void _insertClass(const std::vector<SPObject *> &objVec, const Glib::ustring &className); void _insertClass(SPObject *obj, const Glib::ustring &className); void _removeClass(const std::vector<SPObject *> &objVec, const Glib::ustring &className, bool all = false); void _removeClass(SPObject *obj, const Glib::ustring &className, bool all = false); @@ -157,7 +169,7 @@ class SelectorsDialog : public Widget::Panel { // Variables double _scroolpos; bool _scroollock; - bool _updating; // Prevent cyclic actions: read <-> write, select via dialog <-> via desktop + bool _updating; // Prevent cyclic actions: read <-> write, select via dialog <-> via desktop Inkscape::XML::Node *m_root = nullptr; Inkscape::XML::Node *_textNode; // Track so we know when to add a NodeObserver. @@ -165,7 +177,7 @@ class SelectorsDialog : public Widget::Panel { sigc::connection _document_replaced_connection; sigc::connection _selection_changed_connection; - void _handleDocumentReplaced(SPDesktop* desktop, SPDocument *document); + void _handleDocumentReplaced(SPDesktop *desktop, SPDocument *document); void setDesktop(SPDesktop *desktop) override; void _handleSelectionChanged(); void _rowExpand(const Gtk::TreeModel::iterator &iter, const Gtk::TreeModel::Path &path); @@ -183,10 +195,10 @@ class SelectorsDialog : public Widget::Panel { void _vscrool(); // GUI - void _styleButton(Gtk::Button& btn, char const* iconName, char const* tooltip); + void _styleButton(Gtk::Button &btn, char const *iconName, char const *tooltip); }; -} // namespace Dialogc +} // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/spellcheck.cpp b/src/ui/dialog/spellcheck.cpp index 93b33382708a7ff629ff108c6306679566ae60f0..1d3b8364329fa9bcd88adc0f373a8832b9c88ee3 100644 --- a/src/ui/dialog/spellcheck.cpp +++ b/src/ui/dialog/spellcheck.cpp @@ -14,23 +14,18 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include "spellcheck.h" +#include <glibmm/i18n.h> #include "desktop.h" +#include "display/canvas-bpath.h" +#include "display/curve.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" #include "message-stack.h" -#include "selection-chemistry.h" -#include "text-editing.h" -#include "verbs.h" - -#include "display/curve.h" -#include "display/canvas-bpath.h" - #include "object/sp-defs.h" #include "object/sp-flowtext.h" #include "object/sp-object.h" @@ -38,13 +33,14 @@ #include "object/sp-string.h" #include "object/sp-text.h" #include "object/sp-tref.h" - +#include "selection-chemistry.h" +#include "spellcheck.h" +#include "text-editing.h" #include "ui/dialog/dialog-manager.h" #include "ui/dialog/inkscape-preferences.h" // for PREFS_PAGE_SPELLCHECK #include "ui/tools-switch.h" #include "ui/tools/text-tool.h" - -#include <glibmm/i18n.h> +#include "verbs.h" #ifdef _WIN32 #include <windows.h> @@ -65,13 +61,16 @@ std::vector<LanguagePair> SpellCheck::get_available_langs() // TODO: write a gspellmm library. // TODO: why is this not const? GList *list = const_cast<GList *>(gspell_language_get_available()); - g_list_foreach(list, [](gpointer data, gpointer user_data) { - GspellLanguage *language = reinterpret_cast<GspellLanguage*>(data); - std::vector<LanguagePair> *langs = reinterpret_cast<std::vector<LanguagePair>*>(user_data); - const gchar *name = gspell_language_get_name(language); - const gchar *code = gspell_language_get_code(language); - langs->emplace_back(name, code); - }, &langs); + g_list_foreach( + list, + [](gpointer data, gpointer user_data) { + GspellLanguage *language = reinterpret_cast<GspellLanguage *>(data); + std::vector<LanguagePair> *langs = reinterpret_cast<std::vector<LanguagePair> *>(user_data); + const gchar *name = gspell_language_get_name(language); + const gchar *code = gspell_language_get_code(language); + langs->emplace_back(name, code); + }, + &langs); #endif return langs; @@ -83,29 +82,29 @@ static void show_spellcheck_preferences_dialog() SP_ACTIVE_DESKTOP->_dlg_mgr->showDialog("InkscapePreferences"); } -SpellCheck::SpellCheck () : - UI::Widget::Panel("/dialogs/spellcheck/", SP_VERB_DIALOG_SPELLCHECK), - _text(nullptr), - _layout(nullptr), - _stops(0), - _adds(0), - _working(false), - _local_change(false), - _prefs(nullptr), - accept_button(_("_Accept"), true), - ignoreonce_button(_("_Ignore once"), true), - ignore_button(_("_Ignore"), true), - add_button(_("A_dd"), true), - dictionary_label(_("Language")), - dictionary_hbox(false, 0), - stop_button(_("_Stop"), true), - start_button(_("_Start"), true), - desktop(nullptr) +SpellCheck::SpellCheck() + : UI::Widget::Panel("/dialogs/spellcheck/", SP_VERB_DIALOG_SPELLCHECK) + , _text(nullptr) + , _layout(nullptr) + , _stops(0) + , _adds(0) + , _working(false) + , _local_change(false) + , _prefs(nullptr) + , accept_button(_("_Accept"), true) + , ignoreonce_button(_("_Ignore once"), true) + , ignore_button(_("_Ignore"), true) + , add_button(_("A_dd"), true) + , dictionary_label(_("Language")) + , dictionary_hbox(false, 0) + , stop_button(_("_Stop"), true) + , start_button(_("_Start"), true) + , desktop(nullptr) { _prefs = Inkscape::Preferences::get(); // take languages from prefs - for (const char *langkey : { "lang", "lang2", "lang3" }) { + for (const char *langkey : {"lang", "lang2", "lang3"}) { auto lang = _prefs->getString(_prefs_path + langkey); if (!lang.empty()) { #if WITH_GSPELL @@ -162,8 +161,8 @@ SpellCheck::SpellCheck () : changebutton_vbox.pack_start(ignore_button, false, false, 0); changebutton_vbox.pack_start(add_button, false, false, 0); - suggestion_hbox.pack_start (scrolled_window, true, true, 4); - suggestion_hbox.pack_end (changebutton_vbox, false, false, 0); + suggestion_hbox.pack_start(scrolled_window, true, true, 4); + suggestion_hbox.pack_end(changebutton_vbox, false, false, 0); stop_button.set_tooltip_text(_("Stop the check")); start_button.set_tooltip_text(_("Start the check")); @@ -178,11 +177,11 @@ SpellCheck::SpellCheck () : */ Gtk::Box *contents = _getContents(); contents->set_spacing(6); - contents->pack_start (banner_hbox, false, false, 0); - contents->pack_start (suggestion_hbox, true, true, 0); - contents->pack_start (dictionary_hbox, false, false, 0); - contents->pack_start (action_sep, false, false, 6); - contents->pack_start (actionbutton_hbox, false, false, 0); + contents->pack_start(banner_hbox, false, false, 0); + contents->pack_start(suggestion_hbox, true, true, 0); + contents->pack_start(dictionary_hbox, false, false, 0); + contents->pack_start(action_sep, false, false, 6); + contents->pack_start(actionbutton_hbox, false, false, 0); /* * Signal handlers @@ -197,7 +196,7 @@ SpellCheck::SpellCheck () : dictionary_combo.signal_changed().connect(sigc::mem_fun(*this, &SpellCheck::onLanguageChanged)); pref_button.signal_clicked().connect(sigc::ptr_fun(show_spellcheck_preferences_dialog)); - show_all_children (); + show_all_children(); tree_view.set_sensitive(false); accept_button.set_sensitive(false); @@ -230,7 +229,7 @@ void SpellCheck::setDesktop(SPDesktop *desktop) void SpellCheck::clearRects() { - for(auto t : _rects) { + for (auto t : _rects) { sp_canvas_item_hide(t); sp_canvas_item_destroy(t); } @@ -247,7 +246,7 @@ void SpellCheck::disconnect() } } -void SpellCheck::allTextItems (SPObject *r, std::vector<SPItem *> &l, bool hidden, bool locked) +void SpellCheck::allTextItems(SPObject *r, std::vector<SPItem *> &l, bool hidden, bool locked) { if (!desktop) return; // no desktop to check @@ -259,27 +258,26 @@ void SpellCheck::allTextItems (SPObject *r, std::vector<SPItem *> &l, bool hidde return; // we're not interested in metadata } - for (auto& child: r->children) { - if (SP_IS_ITEM (&child) && !child.cloned && !desktop->isLayer(SP_ITEM(&child))) { - if ((hidden || !desktop->itemIsHidden(SP_ITEM(&child))) && (locked || !SP_ITEM(&child)->isLocked())) { - if (SP_IS_TEXT(&child) || SP_IS_FLOWTEXT(&child)) - l.push_back(static_cast<SPItem*>(&child)); - } + for (auto &child : r->children) { + if (SP_IS_ITEM(&child) && !child.cloned && !desktop->isLayer(SP_ITEM(&child))) { + if ((hidden || !desktop->itemIsHidden(SP_ITEM(&child))) && (locked || !SP_ITEM(&child)->isLocked())) { + if (SP_IS_TEXT(&child) || SP_IS_FLOWTEXT(&child)) + l.push_back(static_cast<SPItem *>(&child)); + } } - allTextItems (&child, l, hidden, locked); + allTextItems(&child, l, hidden, locked); } return; } -bool -SpellCheck::textIsValid (SPObject *root, SPItem *text) +bool SpellCheck::textIsValid(SPObject *root, SPItem *text) { - std::vector<SPItem*> l; - allTextItems (root, l, false, true); + std::vector<SPItem *> l; + allTextItems(root, l, false, true); return (std::find(l.begin(), l.end(), text) != l.end()); } -bool SpellCheck::compareTextBboxes (gconstpointer a, gconstpointer b)//returns a<b +bool SpellCheck::compareTextBboxes(gconstpointer a, gconstpointer b) // returns a<b { SPItem *i1 = SP_ITEM(a); SPItem *i2 = SP_ITEM(b); @@ -298,41 +296,39 @@ bool SpellCheck::compareTextBboxes (gconstpointer a, gconstpointer b)//returns a // We regenerate and resort the list every time, because user could have changed it while the // dialog was waiting -SPItem *SpellCheck::getText (SPObject *root) +SPItem *SpellCheck::getText(SPObject *root) { - std::vector<SPItem*> l; - allTextItems (root, l, false, true); - std::sort(l.begin(),l.end(),SpellCheck::compareTextBboxes); + std::vector<SPItem *> l; + allTextItems(root, l, false, true); + std::sort(l.begin(), l.end(), SpellCheck::compareTextBboxes); - for (auto item:l) { - if(_seen_objects.insert(item).second) + for (auto item : l) { + if (_seen_objects.insert(item).second) return item; } return nullptr; } -void -SpellCheck::nextText() +void SpellCheck::nextText() { disconnect(); _text = getText(_root); if (_text) { - _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); + _layout = te_get_layout(_text); _begin_w = _layout->begin(); } _end_w = _begin_w; _word.clear(); } -void SpellCheck::deleteSpeller() { -} +void SpellCheck::deleteSpeller() {} -bool SpellCheck::updateSpeller() { +bool SpellCheck::updateSpeller() +{ #if WITH_GSPELL auto lang = dictionary_combo.get_active_id(); if (!lang.empty()) { @@ -373,8 +369,7 @@ void SpellCheck::onStart() doSpellcheck(); } -void -SpellCheck::finished () +void SpellCheck::finished() { deleteSpeller(); @@ -407,8 +402,7 @@ SpellCheck::finished () _working = false; } -bool -SpellCheck::nextWord() +bool SpellCheck::nextWord() { if (!_working) return false; @@ -433,7 +427,7 @@ SpellCheck::nextWord() _end_w = _begin_w; _end_w.nextEndOfWord(); - _word = sp_te_get_string_multiline (_text, _begin_w, _end_w); + _word = sp_te_get_string_multiline(_text, _begin_w, _end_w); } // try to link this word with the next if separated by ' @@ -450,7 +444,7 @@ SpellCheck::nextWord() int this_char = *text_iter; if (g_ascii_isalpha(this_char)) { // 's _end_w.nextEndOfWord(); - _word = sp_te_get_string_multiline (_text, _begin_w, _end_w); + _word = sp_te_get_string_multiline(_text, _begin_w, _end_w); } } } @@ -461,8 +455,8 @@ SpellCheck::nextWord() bool digits = false; for (unsigned int i : _word) { if (g_unichar_isdigit(i)) { - digits = true; - break; + digits = true; + break; } } if (digits) { @@ -470,13 +464,13 @@ SpellCheck::nextWord() } } - // skip ALL-CAPS words + // skip ALL-CAPS words if (_prefs->getInt(_prefs_path + "ignoreallcaps") != 0) { bool allcaps = true; for (unsigned int i : _word) { if (!g_unichar_isupper(i)) { - allcaps = false; - break; + allcaps = false; + break; } } if (allcaps) { @@ -491,10 +485,10 @@ SpellCheck::nextWord() GError *error = nullptr; have += gspell_checker_check_word(_checker, _word.c_str(), -1, &error); } -#endif /* WITH_GSPELL */ +#endif /* WITH_GSPELL */ if (have == 0) { // not found in any! - _stops ++; + _stops++; // display it in window { @@ -510,12 +504,12 @@ SpellCheck::nextWord() stop_button.set_sensitive(true); // draw rect - std::vector<Geom::Point> points = - _layout->createSelectionShape(_begin_w, _end_w, _text->i2dt_affine()); - 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 + std::vector<Geom::Point> points = _layout->createSelectionShape(_begin_w, _end_w, _text->i2dt_affine()); + 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 (auto & point : points) { + for (auto &point : points) { if (point[Geom::X] < tl[Geom::X]) tl[Geom::X] = point[Geom::X]; if (point[Geom::Y] < tl[Geom::Y]) @@ -535,7 +529,8 @@ SpellCheck::nextWord() // create canvas path rectangle, red stroke SPCanvasItem *rect = sp_canvas_bpath_new(desktop->getSketch(), nullptr); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(rect), 0xff0000ff, 3.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + 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)); @@ -552,27 +547,27 @@ SpellCheck::nextWord() area.expandBy(0.5 * mindim); Geom::Point scrollto; double dist = 0; - for (unsigned corner = 0; corner < 4; corner ++) { + 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 if (desktop->selection->singleItem() != _text) - desktop->selection->set (_text); + desktop->selection->set(_text); if (tools_isactive(desktop, TOOLS_TEXT)) { Inkscape::Text::Layout::iterator *cursor = sp_text_context_get_cursor_position(SP_TEXT_CONTEXT(desktop->event_context), _text); if (!cursor) // some other text is selected there - desktop->selection->set (_text); + desktop->selection->set(_text); else if (*cursor <= _begin_w || *cursor >= _end_w) - sp_text_context_place_cursor (SP_TEXT_CONTEXT(desktop->event_context), _text, _begin_w); - } + sp_text_context_place_cursor(SP_TEXT_CONTEXT(desktop->event_context), _text, _begin_w); + } #if WITH_GSPELL @@ -586,11 +581,14 @@ SpellCheck::nextWord() std::vector<std::string> suggs; // TODO: use a better API for that, or figure out how to make gspellmm. - g_slist_foreach(list, [](gpointer data, gpointer user_data) { - const gchar *suggestion = reinterpret_cast<const gchar*>(data); - std::vector<std::string> *suggs = reinterpret_cast<std::vector<std::string>*>(user_data); - suggs->push_back(suggestion); - }, &suggs); + g_slist_foreach( + list, + [](gpointer data, gpointer user_data) { + const gchar *suggestion = reinterpret_cast<const gchar *>(data); + std::vector<std::string> *suggs = reinterpret_cast<std::vector<std::string> *>(user_data); + suggs->push_back(suggestion); + }, + &suggs); g_slist_free_full(list, g_free); Gtk::TreeModel::iterator iter; @@ -608,18 +606,14 @@ SpellCheck::nextWord() accept_button.set_sensitive(n_sugg > 0); -#endif /* WITH_GSPELL */ +#endif /* WITH_GSPELL */ return true; - } return false; } - - -void -SpellCheck::deleteLastRect () +void SpellCheck::deleteLastRect() { if (!_rects.empty()) { sp_canvas_item_hide(_rects.back()); @@ -628,7 +622,7 @@ SpellCheck::deleteLastRect () } } -void SpellCheck::doSpellcheck () +void SpellCheck::doSpellcheck() { if (_langs.empty()) { return; @@ -646,7 +640,7 @@ void SpellCheck::onTreeSelectionChange() accept_button.set_sensitive(true); } -void SpellCheck::onObjModified (SPObject* /* blah */, unsigned int /* bleh */) +void SpellCheck::onObjModified(SPObject * /* blah */, unsigned int /* bleh */) { if (_local_change) { // this was a change by this dialog, i.e. an Accept, skip it _local_change = false; @@ -658,32 +652,32 @@ void SpellCheck::onObjModified (SPObject* /* blah */, unsigned int /* bleh */) // situation // just in case, re-get text's layout - _layout = te_get_layout (_text); + _layout = te_get_layout(_text); // re-get the word _layout->validateIterator(&_begin_w); _end_w = _begin_w; _end_w.nextEndOfWord(); - Glib::ustring word_new = sp_te_get_string_multiline (_text, _begin_w, _end_w); + Glib::ustring word_new = sp_te_get_string_multiline(_text, _begin_w, _end_w); if (word_new != _word) { _end_w = _begin_w; - deleteLastRect (); - doSpellcheck (); // recheck this word and go ahead if it's ok + deleteLastRect(); + doSpellcheck(); // recheck this word and go ahead if it's ok } } } -void SpellCheck::onObjReleased (SPObject* /* blah */) +void SpellCheck::onObjReleased(SPObject * /* blah */) { if (_working && _root) { // the text object was deleted - deleteLastRect (); + deleteLastRect(); nextText(); - doSpellcheck (); // get next text and continue + doSpellcheck(); // get next text and continue } } -void SpellCheck::onAccept () +void SpellCheck::onAccept() { // insert chosen suggestion @@ -694,14 +688,13 @@ void SpellCheck::onAccept () Glib::ustring sugg = row[tree_columns.suggestions]; if (sugg.length() > 0) { - //g_print("chosen: %s\n", sugg); + // g_print("chosen: %s\n", sugg); _local_change = true; sp_te_replace(_text, _begin_w, _end_w, sugg.c_str()); // find the end of the word anew _end_w = _begin_w; _end_w.nextEndOfWord(); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Fix spelling")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Fix spelling")); } } @@ -709,28 +702,25 @@ void SpellCheck::onAccept () doSpellcheck(); } -void -SpellCheck::onIgnore () +void SpellCheck::onIgnore() { #if WITH_GSPELL if (_checker) { gspell_checker_add_word_to_session(_checker, _word.c_str(), -1); } -#endif /* WITH_GSPELL */ +#endif /* WITH_GSPELL */ deleteLastRect(); doSpellcheck(); } -void -SpellCheck::onIgnoreOnce () +void SpellCheck::onIgnoreOnce() { deleteLastRect(); doSpellcheck(); } -void -SpellCheck::onAdd () +void SpellCheck::onAdd() { _adds++; @@ -738,14 +728,13 @@ SpellCheck::onAdd () if (_checker) { gspell_checker_add_word_to_personal(_checker, _word.c_str(), -1); } -#endif /* WITH_GSPELL */ +#endif /* WITH_GSPELL */ deleteLastRect(); doSpellcheck(); } -void -SpellCheck::onStop () +void SpellCheck::onStop() { finished(); } @@ -766,9 +755,9 @@ void SpellCheck::onLanguageChanged() deleteLastRect(); doSpellcheck(); } -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/spellcheck.h b/src/ui/dialog/spellcheck.h index 9608d330d7b5a1a513e3b3e466097da90da33d20..ac8630d3b7859aca07d0b9ed9c474f215d449a3b 100644 --- a/src/ui/dialog/spellcheck.h +++ b/src/ui/dialog/spellcheck.h @@ -14,28 +14,26 @@ #define SEEN_SPELLCHECK_H #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include <vector> -#include <set> - #include <gtkmm/box.h> #include <gtkmm/button.h> #include <gtkmm/buttonbox.h> #include <gtkmm/comboboxtext.h> +#include <gtkmm/liststore.h> #include <gtkmm/scrolledwindow.h> #include <gtkmm/separator.h> -#include <gtkmm/liststore.h> #include <gtkmm/treeview.h> - -#include "ui/widget/panel.h" +#include <set> +#include <vector> #include "text-editing.h" +#include "ui/widget/panel.h" #if WITH_GSPELL #include <gspell/gspell.h> -#endif /* WITH_GSPELL */ +#endif /* WITH_GSPELL */ class SPDesktop; class SPObject; @@ -56,17 +54,17 @@ using LanguagePair = std::pair<std::string, std::string>; * Uses gspell and one of the languages set in the users preference file * */ -class SpellCheck : public Widget::Panel { +class SpellCheck : public Widget::Panel +{ public: - SpellCheck (); - ~SpellCheck () override; + SpellCheck(); + ~SpellCheck() override; static SpellCheck &getInstance() { return *new SpellCheck(); } static std::vector<LanguagePair> get_available_langs(); private: - /** * Remove the highlight rectangle form the canvas */ @@ -80,31 +78,31 @@ private: /** * Returns a list of all the text items in the SPObject */ - void allTextItems (SPObject *r, std::vector<SPItem *> &l, bool hidden, bool locked); + void allTextItems(SPObject *r, std::vector<SPItem *> &l, bool hidden, bool locked); /** * Is text inside the SPOject's tree */ - bool textIsValid (SPObject *root, SPItem *text); + bool textIsValid(SPObject *root, SPItem *text); /** * Compare the visual bounds of 2 SPItems referred to by a and b */ - static bool compareTextBboxes (gconstpointer a, gconstpointer b); - SPItem *getText (SPObject *root); - void nextText (); + static bool compareTextBboxes(gconstpointer a, gconstpointer b); + SPItem *getText(SPObject *root); + void nextText(); /** * Cleanup after spellcheck is finished */ - void finished (); + void finished(); /** * Find the next word to spell check */ - bool nextWord(); - void deleteLastRect (); - void doSpellcheck (); + bool nextWord(); + void deleteLastRect(); + void doSpellcheck(); /** * Update speller from language combobox @@ -116,47 +114,47 @@ private: /** * Accept button clicked */ - void onAccept (); + void onAccept(); /** * Ignore button clicked */ - void onIgnore (); + void onIgnore(); /** * Ignore once button clicked */ - void onIgnoreOnce (); + void onIgnoreOnce(); /** * Add button clicked */ - void onAdd (); + void onAdd(); /** * Stop button clicked */ - void onStop (); + void onStop(); /** * Start button clicked */ - void onStart (); + void onStart(); /** * Language selection changed */ - void onLanguageChanged(); + void onLanguageChanged(); /** * Selected object modified on canvas */ - void onObjModified (SPObject* /* blah */, unsigned int /* bleh */); + void onObjModified(SPObject * /* blah */, unsigned int /* bleh */); /** * Selected object removed from canvas */ - void onObjReleased (SPObject* /* blah */); + void onObjReleased(SPObject * /* blah */); /** * Selection in suggestions text view changed @@ -172,7 +170,7 @@ private: #if WITH_GSPELL GspellChecker *_checker = nullptr; -#endif /* WITH_GSPELL */ +#endif /* WITH_GSPELL */ /** * list of canvasitems (currently just rects) that mark misspelled things on canvas @@ -234,47 +232,43 @@ private: /* * Dialogs widgets */ - Gtk::Label banner_label; - Gtk::ButtonBox banner_hbox; + Gtk::Label banner_label; + Gtk::ButtonBox banner_hbox; Gtk::ScrolledWindow scrolled_window; - Gtk::TreeView tree_view; + Gtk::TreeView tree_view; Glib::RefPtr<Gtk::ListStore> model; - Gtk::HBox suggestion_hbox; - Gtk::VBox changebutton_vbox; - Gtk::Button accept_button; - Gtk::Button ignoreonce_button; - Gtk::Button ignore_button; + Gtk::HBox suggestion_hbox; + Gtk::VBox changebutton_vbox; + Gtk::Button accept_button; + Gtk::Button ignoreonce_button; + Gtk::Button ignore_button; - Gtk::Button add_button; - Gtk::Button pref_button; - Gtk::Label dictionary_label; + Gtk::Button add_button; + Gtk::Button pref_button; + Gtk::Label dictionary_label; Gtk::ComboBoxText dictionary_combo; - Gtk::HBox dictionary_hbox; - Gtk::Separator action_sep; - Gtk::Button stop_button; - Gtk::Button start_button; - Gtk::ButtonBox actionbutton_hbox; + Gtk::HBox dictionary_hbox; + Gtk::Separator action_sep; + Gtk::Button stop_button; + Gtk::Button start_button; + Gtk::ButtonBox actionbutton_hbox; - SPDesktop * desktop; + SPDesktop *desktop; class TreeColumns : public Gtk::TreeModel::ColumnRecord { - public: - TreeColumns() - { - add(suggestions); - } + public: + TreeColumns() { add(suggestions); } ~TreeColumns() override = default; Gtk::TreeModelColumn<Glib::ustring> suggestions; }; TreeColumns tree_columns; - }; -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_SPELLCHECK_H */ diff --git a/src/ui/dialog/styledialog.cpp b/src/ui/dialog/styledialog.cpp index bfb27d15ab756c0ec25daf097df99d73dec7b419..ed5b00e7efffd7d96c46b6d2290951be06172c40 100644 --- a/src/ui/dialog/styledialog.cpp +++ b/src/ui/dialog/styledialog.cpp @@ -14,6 +14,13 @@ */ #include "styledialog.h" + +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> +#include <map> +#include <regex> +#include <utility> + #include "attribute-rel-svg.h" #include "attributes.h" #include "document-undo.h" @@ -30,13 +37,6 @@ #include "xml/node-observer.h" #include "xml/sp-css-attr.h" -#include <map> -#include <regex> -#include <utility> - -#include <gdk/gdkkeysyms.h> -#include <glibmm/i18n.h> - // G_MESSAGES_DEBUG=DEBUG_STYLEDIALOG gdb ./inkscape // #define DEBUG_STYLEDIALOG // #define G_LOG_DOMAIN "STYLEDIALOG" @@ -49,8 +49,8 @@ using Inkscape::XML::AttributeRecord; * This macro is used to remove spaces around selectors or any strings when * parsing is done to update XML style element or row labels in this dialog. */ -#define REMOVE_SPACES(x) \ - x.erase(0, x.find_first_not_of(' ')); \ +#define REMOVE_SPACES(x) \ + x.erase(0, x.find_first_not_of(' ')); \ x.erase(x.find_last_not_of(' ') + 1); namespace Inkscape { @@ -115,8 +115,9 @@ namespace UI { namespace Dialog { // Keeps a watch on style element -class StyleDialog::NodeObserver : public Inkscape::XML::NodeObserver { - public: +class StyleDialog::NodeObserver : public Inkscape::XML::NodeObserver +{ +public: NodeObserver(StyleDialog *styledialog) : _styledialog(styledialog) { @@ -129,22 +130,20 @@ class StyleDialog::NodeObserver : public Inkscape::XML::NodeObserver { StyleDialog *_styledialog; }; - void StyleDialog::NodeObserver::notifyContentChanged(Inkscape::XML::Node & /*node*/, Inkscape::Util::ptr_shared /*old_content*/, Inkscape::Util::ptr_shared /*new_content*/) { - g_debug("StyleDialog::NodeObserver::notifyContentChanged"); _styledialog->_updating = false; _styledialog->readStyleElement(); } - // Keeps a watch for new/removed/changed nodes // (Must update objects that selectors match.) -class StyleDialog::NodeWatcher : public Inkscape::XML::NodeObserver { - public: +class StyleDialog::NodeWatcher : public Inkscape::XML::NodeObserver +{ +public: NodeWatcher(StyleDialog *styledialog) : _styledialog(styledialog) { @@ -154,13 +153,13 @@ class StyleDialog::NodeWatcher : public Inkscape::XML::NodeObserver { void notifyChildAdded(Inkscape::XML::Node & /*node*/, Inkscape::XML::Node &child, Inkscape::XML::Node * /*prev*/) override { - _styledialog->_nodeAdded(child); + _styledialog->_nodeAdded(child); } void notifyChildRemoved(Inkscape::XML::Node & /*node*/, Inkscape::XML::Node &child, Inkscape::XML::Node * /*prev*/) override { - _styledialog->_nodeRemoved(child); + _styledialog->_nodeRemoved(child); } /* void notifyContentChanged(Inkscape::XML::Node &node, Inkscape::Util::ptr_shared old_content, @@ -201,7 +200,7 @@ void StyleDialog::_nodeRemoved(Inkscape::XML::Node &repr) void StyleDialog::_nodeChanged(Inkscape::XML::Node &object) { - g_debug("StyleDialog::_nodeChanged"); + g_debug("StyleDialog::_nodeChanged"); readStyleElement(); } @@ -305,7 +304,10 @@ StyleDialog::~StyleDialog() _selection_changed_connection.disconnect(); } -void StyleDialog::_reload() { readStyleElement(); } +void StyleDialog::_reload() +{ + readStyleElement(); +} /** * @return Inkscape::XML::Node* pointing to a style element's text node. @@ -333,7 +335,6 @@ Inkscape::XML::Node *StyleDialog::_getStyleTextNode(bool create_if_missing) return textNode; } - Glib::RefPtr<Gtk::TreeModel> StyleDialog::_selectTree(Glib::ustring selector) { g_debug("StyleDialog::_selectTree"); @@ -1018,7 +1019,6 @@ void StyleDialog::_addOwnerStyle(Glib::ustring name, Glib::ustring selector) } } - /** * @brief StyleDialog::parseStyle * @@ -1048,7 +1048,6 @@ std::map<Glib::ustring, Glib::ustring> StyleDialog::parseStyle(Glib::ustring sty return ret; } - /** * Update the content of the style element as selectors (or objects) are added/removed. */ @@ -1205,11 +1204,11 @@ void StyleDialog::_setAutocompletion(Gtk::Entry *entry, SPStyleEnum const cssenu Glib::RefPtr<Gtk::ListStore> completionModel = Gtk::ListStore::create(_mCSSData); Glib::RefPtr<Gtk::EntryCompletion> entry_completion = Gtk::EntryCompletion::create(); entry_completion->set_model(completionModel); - entry_completion->set_text_column (_mCSSData._colCSSData); + entry_completion->set_text_column(_mCSSData._colCSSData); entry_completion->set_minimum_key_length(0); entry_completion->set_popup_completion(true); gint counter = 0; - const char * key = cssenum[counter].key; + const char *key = cssenum[counter].key; while (key) { Gtk::TreeModel::Row row = *(completionModel->prepend()); row[_mCSSData._colCSSData] = Glib::ustring(key); @@ -1246,8 +1245,8 @@ void StyleDialog::_setAutocompletion(Gtk::Entry *entry, Glib::ustring name) entry->set_completion(entry_completion); } -void -StyleDialog::_startValueEdit(Gtk::CellEditable* cell, const Glib::ustring& path, Glib::RefPtr<Gtk::TreeStore> store) +void StyleDialog::_startValueEdit(Gtk::CellEditable *cell, const Glib::ustring &path, + Glib::RefPtr<Gtk::TreeStore> store) { g_debug("StyleDialog::_startValueEdit"); _deletion = false; @@ -1332,7 +1331,6 @@ void StyleDialog::_startNameEdit(Gtk::CellEditable *cell, const Glib::ustring &p entry->signal_key_press_event().connect(sigc::bind(sigc::mem_fun(*this, &StyleDialog::_onNameKeyPressed), entry)); } - gboolean sp_styledialog_store_move_to_next(gpointer data) { StyleDialog *styledialog = reinterpret_cast<StyleDialog *>(data); @@ -1575,7 +1573,6 @@ void StyleDialog::_updateWatchers(SPDesktop *desktop) } } - /** * @param selector: a valid CSS selector string. * @return objVec: a vector of pointers to SPObject's the selector matches. @@ -1590,8 +1587,10 @@ std::vector<SPObject *> StyleDialog::_getObjVec(Glib::ustring selector) return getDesktop()->getDocument()->getObjectsBySelector(selector); } -void StyleDialog::_closeDialog(Gtk::Dialog *textDialogPtr) { textDialogPtr->response(Gtk::RESPONSE_OK); } - +void StyleDialog::_closeDialog(Gtk::Dialog *textDialogPtr) +{ + textDialogPtr->response(Gtk::RESPONSE_OK); +} /** * Handle document replaced. (Happens when a default document is immediately replaced by another @@ -1614,7 +1613,6 @@ void StyleDialog::_handleDocumentReplaced(SPDesktop *desktop, SPDocument * /* do readStyleElement(); } - /* * When a dialog is floating, it is connected to the active desktop. */ @@ -1634,13 +1632,12 @@ void StyleDialog::setDesktop(SPDesktop *desktop) if (desktop) { _document_replaced_connection = - desktop->connectDocumentReplaced(sigc::mem_fun(this, &StyleDialog::_handleDocumentReplaced)); + desktop->connectDocumentReplaced(sigc::mem_fun(this, &StyleDialog::_handleDocumentReplaced)); } _handleDocumentReplaced(desktop, nullptr); } - /* * Handle a change in which objects are selected in a document. */ diff --git a/src/ui/dialog/styledialog.h b/src/ui/dialog/styledialog.h index 46708603dc2226f6cde2a396ec700cce54ecd38e..ed2b297a58545580d2a9b0de3bee10c20e51d3c0 100644 --- a/src/ui/dialog/styledialog.h +++ b/src/ui/dialog/styledialog.h @@ -15,7 +15,6 @@ #ifndef STYLEDIALOG_H #define STYLEDIALOG_H -#include "style-enums.h" #include <glibmm/regex.h> #include <gtkmm/adjustment.h> #include <gtkmm/builder.h> @@ -35,14 +34,13 @@ #include <gtkmm/treestore.h> #include <gtkmm/treeview.h> #include <gtkmm/viewport.h> +#include <memory> #include <ui/widget/panel.h> +#include <vector> - +#include "style-enums.h" #include "xml/helper-observer.h" -#include <memory> -#include <vector> - namespace Inkscape { XML::Node *get_first_style_text_node(XML::Node *root, bool create_if_missing); @@ -61,9 +59,9 @@ namespace Dialog { * 1. The text node of the style element. * 2. The Gtk::TreeModel. */ -class StyleDialog : public Widget::Panel { - - public: +class StyleDialog : public Widget::Panel +{ +public: ~StyleDialog() override; // No default constructor, noncopyable, nonassignable StyleDialog(); @@ -81,7 +79,7 @@ class StyleDialog : public Widget::Panel { Glib::ustring fixCSSSelectors(Glib::ustring selector); void readStyleElement(); - private: +private: // Monitor <style> element for changes. class NodeObserver; // Monitor all objects for addition/removal/attribute change @@ -93,8 +91,9 @@ class StyleDialog : public Widget::Panel { void _nodeChanged(Inkscape::XML::Node &repr); /* void _stylesheetChanged( Inkscape::XML::Node &repr ); */ // Data structure - class ModelColumns : public Gtk::TreeModel::ColumnRecord { - public: + class ModelColumns : public Gtk::TreeModel::ColumnRecord + { + public: ModelColumns() { add(_colActive); @@ -119,8 +118,9 @@ class StyleDialog : public Widget::Panel { }; ModelColumns _mColumns; - class CSSData : public Gtk::TreeModel::ColumnRecord { - public: + class CSSData : public Gtk::TreeModel::ColumnRecord + { + public: CSSData() { add(_colCSSData); } Gtk::TreeModelColumn<Glib::ustring> _colCSSData; // Name of the property. }; diff --git a/src/ui/dialog/svg-fonts-dialog.cpp b/src/ui/dialog/svg-fonts-dialog.cpp index f6b48538836484bc117ff2fcc1270a2457516133..1f744e865654d2142c214099e50cc72a0076f91b 100644 --- a/src/ui/dialog/svg-fonts-dialog.cpp +++ b/src/ui/dialog/svg-fonts-dialog.cpp @@ -12,22 +12,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <message-stack.h> -#include <sstream> +#include "svg-fonts-dialog.h" -#include <gtkmm/scale.h> -#include <gtkmm/notebook.h> -#include <gtkmm/imagemenuitem.h> -#include <glibmm/stringutils.h> #include <glibmm/i18n.h> +#include <glibmm/stringutils.h> +#include <gtkmm/imagemenuitem.h> +#include <gtkmm/notebook.h> +#include <gtkmm/scale.h> +#include <message-stack.h> +#include <sstream> #include "desktop.h" -#include "document-undo.h" -#include "selection.h" -#include "svg-fonts-dialog.h" -#include "verbs.h" - #include "display/nr-svgfonts.h" +#include "document-undo.h" #include "include/gtkmm_version.h" #include "object/sp-defs.h" #include "object/sp-font-face.h" @@ -35,53 +32,60 @@ #include "object/sp-glyph-kerning.h" #include "object/sp-glyph.h" #include "object/sp-missing-glyph.h" +#include "selection.h" #include "svg/svg.h" +#include "verbs.h" #include "xml/repr.h" -SvgFontDrawingArea::SvgFontDrawingArea(): - _x(0), - _y(0), - _svgfont(nullptr), - _text() -{ -} +SvgFontDrawingArea::SvgFontDrawingArea() + : _x(0) + , _y(0) + , _svgfont(nullptr) + , _text() +{} -void SvgFontDrawingArea::set_svgfont(SvgFont* svgfont){ +void SvgFontDrawingArea::set_svgfont(SvgFont *svgfont) +{ _svgfont = svgfont; } -void SvgFontDrawingArea::set_text(Glib::ustring text){ +void SvgFontDrawingArea::set_text(Glib::ustring text) +{ _text = text; redraw(); } -void SvgFontDrawingArea::set_size(int x, int y){ +void SvgFontDrawingArea::set_size(int x, int y) +{ _x = x; _y = y; - ((Gtk::Widget*) this)->set_size_request(_x, _y); + ((Gtk::Widget *)this)->set_size_request(_x, _y); } -void SvgFontDrawingArea::redraw(){ - ((Gtk::Widget*) this)->queue_draw(); +void SvgFontDrawingArea::redraw() +{ + ((Gtk::Widget *)this)->queue_draw(); } -bool SvgFontDrawingArea::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) { - if (_svgfont){ - cr->set_font_face( Cairo::RefPtr<Cairo::FontFace>(new Cairo::FontFace(_svgfont->get_font_face(), false /* does not have reference */)) ); - cr->set_font_size (_y-20); - cr->move_to (10, 10); - cr->show_text (_text.c_str()); - - // Draw some lines to show line area. - cr->set_source_rgb( 0.5, 0.5, 0.5 ); - cr->move_to ( 0, 10); - cr->line_to (_x, 10); - cr->stroke(); - cr->move_to ( 0, _y-10); - cr->line_to (_x, _y-10); - cr->stroke(); - } - return true; +bool SvgFontDrawingArea::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) +{ + if (_svgfont) { + cr->set_font_face(Cairo::RefPtr<Cairo::FontFace>( + new Cairo::FontFace(_svgfont->get_font_face(), false /* does not have reference */))); + cr->set_font_size(_y - 20); + cr->move_to(10, 10); + cr->show_text(_text.c_str()); + + // Draw some lines to show line area. + cr->set_source_rgb(0.5, 0.5, 0.5); + cr->move_to(0, 10); + cr->line_to(_x, 10); + cr->stroke(); + cr->move_to(0, _y - 10); + cr->line_to(_x, _y - 10); + cr->stroke(); + } + return true; } namespace Inkscape { @@ -101,7 +105,8 @@ Gtk::HBox* SvgFontsDialog::AttrEntry(gchar* lbl, const SPAttr attr){ } */ -SvgFontsDialog::AttrEntry::AttrEntry(SvgFontsDialog* d, gchar* lbl, Glib::ustring tooltip, const SPAttr attr){ +SvgFontsDialog::AttrEntry::AttrEntry(SvgFontsDialog *d, gchar *lbl, Glib::ustring tooltip, const SPAttr attr) +{ this->dialog = d; this->attr = attr; entry.set_tooltip_text(tooltip); @@ -113,19 +118,21 @@ SvgFontsDialog::AttrEntry::AttrEntry(SvgFontsDialog* d, gchar* lbl, Glib::ustrin entry.signal_changed().connect(sigc::mem_fun(*this, &SvgFontsDialog::AttrEntry::on_attr_changed)); } -void SvgFontsDialog::AttrEntry::set_text(char* t){ - if (!t) return; +void SvgFontsDialog::AttrEntry::set_text(char *t) +{ + if (!t) + return; entry.set_text(t); } // 'font-family' has a problem as it is also a presentation attribute for <text> -void SvgFontsDialog::AttrEntry::on_attr_changed(){ - - SPObject* o = nullptr; - for (auto& node: dialog->get_selected_spfont()->children) { - switch(this->attr){ +void SvgFontsDialog::AttrEntry::on_attr_changed() +{ + SPObject *o = nullptr; + for (auto &node : dialog->get_selected_spfont()->children) { + switch (this->attr) { case SPAttr::FONT_FAMILY: - if (SP_IS_FONTFACE(&node)){ + if (SP_IS_FONTFACE(&node)) { o = &node; continue; } @@ -135,21 +142,19 @@ void SvgFontsDialog::AttrEntry::on_attr_changed(){ } } - const gchar* name = (const gchar*)sp_attribute_name(this->attr); - if(name && o) { - o->setAttribute((const gchar*) name, this->entry.get_text()); + const gchar *name = (const gchar *)sp_attribute_name(this->attr); + if (name && o) { + o->setAttribute((const gchar *)name, this->entry.get_text()); o->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); Glib::ustring undokey = "svgfonts:"; undokey += name; - DocumentUndo::maybeDone(o->document, undokey.c_str(), SP_VERB_DIALOG_SVG_FONTS, - _("Set SVG Font attribute")); + DocumentUndo::maybeDone(o->document, undokey.c_str(), SP_VERB_DIALOG_SVG_FONTS, _("Set SVG Font attribute")); } - } -SvgFontsDialog::AttrSpin::AttrSpin(SvgFontsDialog* d, gchar* lbl, Glib::ustring tooltip, const SPAttr attr) { - +SvgFontsDialog::AttrSpin::AttrSpin(SvgFontsDialog *d, gchar *lbl, Glib::ustring tooltip, const SPAttr attr) +{ this->dialog = d; this->attr = attr; spin.set_tooltip_text(tooltip); @@ -164,19 +169,20 @@ SvgFontsDialog::AttrSpin::AttrSpin(SvgFontsDialog* d, gchar* lbl, Glib::ustring spin.signal_value_changed().connect(sigc::mem_fun(*this, &SvgFontsDialog::AttrSpin::on_attr_changed)); } -void SvgFontsDialog::AttrSpin::set_range(double low, double high){ +void SvgFontsDialog::AttrSpin::set_range(double low, double high) +{ spin.set_range(low, high); } -void SvgFontsDialog::AttrSpin::set_value(double v){ +void SvgFontsDialog::AttrSpin::set_value(double v) +{ spin.set_value(v); } -void SvgFontsDialog::AttrSpin::on_attr_changed(){ - - SPObject* o = nullptr; +void SvgFontsDialog::AttrSpin::on_attr_changed() +{ + SPObject *o = nullptr; switch (this->attr) { - // <font> attributes case SPAttr::HORIZ_ORIGIN_X: case SPAttr::HORIZ_ORIGIN_Y: @@ -193,8 +199,8 @@ void SvgFontsDialog::AttrSpin::on_attr_changed(){ case SPAttr::DESCENT: case SPAttr::CAP_HEIGHT: case SPAttr::X_HEIGHT: - for (auto& node: dialog->get_selected_spfont()->children){ - if (SP_IS_FONTFACE(&node)){ + for (auto &node : dialog->get_selected_spfont()->children) { + if (SP_IS_FONTFACE(&node)) { o = &node; continue; } @@ -205,8 +211,8 @@ void SvgFontsDialog::AttrSpin::on_attr_changed(){ o = nullptr; } - const gchar* name = (const gchar*)sp_attribute_name(this->attr); - if(name && o) { + const gchar *name = (const gchar *)sp_attribute_name(this->attr); + if (name && o) { std::ostringstream temp; temp << this->spin.get_value(); o->setAttribute(name, temp.str()); @@ -214,16 +220,15 @@ void SvgFontsDialog::AttrSpin::on_attr_changed(){ Glib::ustring undokey = "svgfonts:"; undokey += name; - DocumentUndo::maybeDone(o->document, undokey.c_str(), SP_VERB_DIALOG_SVG_FONTS, - _("Set SVG Font attribute")); + DocumentUndo::maybeDone(o->document, undokey.c_str(), SP_VERB_DIALOG_SVG_FONTS, _("Set SVG Font attribute")); } - } -Gtk::HBox* SvgFontsDialog::AttrCombo(gchar* lbl, const SPAttr /*attr*/){ - Gtk::HBox* hbox = Gtk::manage(new Gtk::HBox()); - hbox->add(* Gtk::manage(new Gtk::Label(lbl)) ); - hbox->add(* Gtk::manage(new Gtk::ComboBox()) ); +Gtk::HBox *SvgFontsDialog::AttrCombo(gchar *lbl, const SPAttr /*attr*/) +{ + Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox()); + hbox->add(*Gtk::manage(new Gtk::Label(lbl))); + hbox->add(*Gtk::manage(new Gtk::ComboBox())); hbox->show_all(); return hbox; } @@ -239,66 +244,70 @@ Gtk::HBox* SvgFontsDialog::AttrSpin(gchar* lbl){ /*** SvgFontsDialog ***/ -GlyphComboBox::GlyphComboBox()= default; +GlyphComboBox::GlyphComboBox() = default; -void GlyphComboBox::update(SPFont* spfont){ - if (!spfont) return; +void GlyphComboBox::update(SPFont *spfont) +{ + if (!spfont) + return; this->remove_all(); - for (auto& node: spfont->children) { - if (SP_IS_GLYPH(&node)){ - this->append((static_cast<SPGlyph*>(&node))->unicode); + for (auto &node : spfont->children) { + if (SP_IS_GLYPH(&node)) { + this->append((static_cast<SPGlyph *>(&node))->unicode); } } } -void SvgFontsDialog::on_kerning_value_changed(){ +void SvgFontsDialog::on_kerning_value_changed() +{ if (!get_selected_kerning_pair()) { return; } - SPDocument* document = this->getDesktop()->getDocument(); + SPDocument *document = this->getDesktop()->getDocument(); - //TODO: I am unsure whether this is the correct way of calling SPDocumentUndo::maybe_done + // TODO: I am unsure whether this is the correct way of calling SPDocumentUndo::maybe_done Glib::ustring undokey = "svgfonts:hkern:k:"; undokey += this->kerning_pair->u1->attribute_string(); undokey += ":"; undokey += this->kerning_pair->u2->attribute_string(); - //slider values increase from right to left so that they match the kerning pair preview + // 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->setAttribute("k", Glib::Ascii::dtostr(get_selected_spfont()->horiz_adv_x - kerning_slider->get_value())); + // XML Tree being directly used here while it shouldn't be. + this->kerning_pair->setAttribute( + "k", Glib::Ascii::dtostr(get_selected_spfont()->horiz_adv_x - kerning_slider->get_value())); DocumentUndo::maybeDone(document, undokey.c_str(), SP_VERB_DIALOG_SVG_FONTS, _("Adjust kerning value")); - //populate_kerning_pairs_box(); + // populate_kerning_pairs_box(); kerning_preview.redraw(); _font_da.redraw(); } -void SvgFontsDialog::glyphs_list_button_release(GdkEventButton* event) +void SvgFontsDialog::glyphs_list_button_release(GdkEventButton *event) { - if((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { + if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { _GlyphsContextMenu.popup_at_pointer(reinterpret_cast<GdkEvent *>(event)); } } -void SvgFontsDialog::kerning_pairs_list_button_release(GdkEventButton* event) +void SvgFontsDialog::kerning_pairs_list_button_release(GdkEventButton *event) { - if((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { + if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { _KerningPairsContextMenu.popup_at_pointer(reinterpret_cast<GdkEvent *>(event)); } } -void SvgFontsDialog::fonts_list_button_release(GdkEventButton* event) +void SvgFontsDialog::fonts_list_button_release(GdkEventButton *event) { - if((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { + if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { _FontsContextMenu.popup_at_pointer(reinterpret_cast<GdkEvent *>(event)); } } -void SvgFontsDialog::create_glyphs_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem) +void SvgFontsDialog::create_glyphs_popup_menu(Gtk::Widget &parent, sigc::slot<void> rem) { auto mi = Gtk::manage(new Gtk::MenuItem(_("_Remove"), true)); _GlyphsContextMenu.append(*mi); @@ -307,7 +316,7 @@ void SvgFontsDialog::create_glyphs_popup_menu(Gtk::Widget& parent, sigc::slot<vo _GlyphsContextMenu.accelerate(parent); } -void SvgFontsDialog::create_kerning_pairs_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem) +void SvgFontsDialog::create_kerning_pairs_popup_menu(Gtk::Widget &parent, sigc::slot<void> rem) { auto mi = Gtk::manage(new Gtk::MenuItem(_("_Remove"), true)); _KerningPairsContextMenu.append(*mi); @@ -316,7 +325,7 @@ void SvgFontsDialog::create_kerning_pairs_popup_menu(Gtk::Widget& parent, sigc:: _KerningPairsContextMenu.accelerate(parent); } -void SvgFontsDialog::create_fonts_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem) +void SvgFontsDialog::create_fonts_popup_menu(Gtk::Widget &parent, sigc::slot<void> rem) { auto mi = Gtk::manage(new Gtk::MenuItem(_("_Remove"), true)); _FontsContextMenu.append(*mi); @@ -325,8 +334,9 @@ void SvgFontsDialog::create_fonts_popup_menu(Gtk::Widget& parent, sigc::slot<voi _FontsContextMenu.accelerate(parent); } -void SvgFontsDialog::update_sensitiveness(){ - if (get_selected_spfont()){ +void SvgFontsDialog::update_sensitiveness() +{ + if (get_selected_spfont()) { global_vbox.set_sensitive(true); glyphs_vbox.set_sensitive(true); kerning_vbox.set_sensitive(true); @@ -340,30 +350,32 @@ void SvgFontsDialog::update_sensitiveness(){ /* Add all fonts in the document to the combobox. */ void SvgFontsDialog::update_fonts() { - SPDesktop* desktop = this->getDesktop(); - SPDocument* document = desktop->getDocument(); - std::vector<SPObject *> fonts = document->getResourceList( "font" ); + SPDesktop *desktop = this->getDesktop(); + SPDocument *document = desktop->getDocument(); + std::vector<SPObject *> fonts = document->getResourceList("font"); _model->clear(); for (auto font : fonts) { Gtk::TreeModel::Row row = *_model->append(); - SPFont* f = SP_FONT(font); + SPFont *f = SP_FONT(font); row[_columns.spfont] = f; row[_columns.svgfont] = new SvgFont(f); - const gchar* lbl = f->label(); - const gchar* id = f->getId(); + const gchar *lbl = f->label(); + const gchar *id = f->getId(); row[_columns.label] = lbl ? lbl : (id ? id : "font"); } update_sensitiveness(); } -void SvgFontsDialog::on_preview_text_changed(){ +void SvgFontsDialog::on_preview_text_changed() +{ _font_da.set_text(_preview_entry.get_text()); } -void SvgFontsDialog::on_kerning_pair_selection_changed(){ - SPGlyphKerning* kern = get_selected_kerning_pair(); +void SvgFontsDialog::on_kerning_pair_selection_changed() +{ + SPGlyphKerning *kern = get_selected_kerning_pair(); if (!kern) { kerning_preview.set_text(""); return; @@ -375,20 +387,22 @@ void SvgFontsDialog::on_kerning_pair_selection_changed(){ kerning_preview.set_text(str); this->kerning_pair = kern; - //slider values increase from right to left so that they match the kerning pair preview + // 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); } -void SvgFontsDialog::update_global_settings_tab(){ - SPFont* font = get_selected_spfont(); - if (!font) return; +void SvgFontsDialog::update_global_settings_tab() +{ + SPFont *font = get_selected_spfont(); + if (!font) + return; _horiz_adv_x_spin->set_value(font->horiz_adv_x); _horiz_origin_x_spin->set_value(font->horiz_origin_x); _horiz_origin_y_spin->set_value(font->horiz_origin_y); - for (auto& obj: font->children) { - if (SP_IS_FONTFACE(&obj)){ + for (auto &obj : font->children) { + if (SP_IS_FONTFACE(&obj)) { _familyname_entry->set_text((SP_FONTFACE(&obj))->font_family); _units_per_em_spin->set_value((SP_FONTFACE(&obj))->units_per_em); _ascent_spin->set_value((SP_FONTFACE(&obj))->ascent); @@ -399,17 +413,19 @@ void SvgFontsDialog::update_global_settings_tab(){ } } -void SvgFontsDialog::on_font_selection_changed(){ - SPFont* spfont = this->get_selected_spfont(); - if (!spfont) return; +void SvgFontsDialog::on_font_selection_changed() +{ + SPFont *spfont = this->get_selected_spfont(); + if (!spfont) + return; - SvgFont* svgfont = this->get_selected_svgfont(); + SvgFont *svgfont = this->get_selected_svgfont(); first_glyph.update(spfont); second_glyph.update(spfont); kerning_preview.set_svgfont(svgfont); _font_da.set_svgfont(svgfont); _font_da.redraw(); - + kerning_slider->set_range(0, spfont->horiz_adv_x); kerning_slider->set_draw_value(false); kerning_slider->set_value(0); @@ -420,50 +436,70 @@ void SvgFontsDialog::on_font_selection_changed(){ update_sensitiveness(); } -SPGlyphKerning* SvgFontsDialog::get_selected_kerning_pair() +SPGlyphKerning *SvgFontsDialog::get_selected_kerning_pair() { Gtk::TreeModel::iterator i = _KerningPairsList.get_selection()->get_selected(); - if(i) + if (i) return (*i)[_KerningPairsListColumns.spnode]; return nullptr; } -SvgFont* SvgFontsDialog::get_selected_svgfont() +SvgFont *SvgFontsDialog::get_selected_svgfont() { Gtk::TreeModel::iterator i = _FontsList.get_selection()->get_selected(); - if(i) + if (i) return (*i)[_columns.svgfont]; return nullptr; } -SPFont* SvgFontsDialog::get_selected_spfont() +SPFont *SvgFontsDialog::get_selected_spfont() { Gtk::TreeModel::iterator i = _FontsList.get_selection()->get_selected(); - if(i) + if (i) return (*i)[_columns.spfont]; return nullptr; } -SPGlyph* SvgFontsDialog::get_selected_glyph() +SPGlyph *SvgFontsDialog::get_selected_glyph() { Gtk::TreeModel::iterator i = _GlyphsList.get_selection()->get_selected(); - if(i) + if (i) return (*i)[_GlyphsListColumns.glyph_node]; return nullptr; } -Gtk::VBox* SvgFontsDialog::global_settings_tab(){ - _font_label = new Gtk::Label(Glib::ustring("<b>") + _("Font Attributes") + "</b>", Gtk::ALIGN_START, Gtk::ALIGN_CENTER); - _horiz_adv_x_spin = new AttrSpin( this, (gchar*) _("Horiz. Advance X:"), _("Default glyph width for horizontal text"), SPAttr::HORIZ_ADV_X); - _horiz_origin_x_spin = new AttrSpin( this, (gchar*) _("Horiz. Origin X:"), _("Default X-coordinate of the origin of a glyph (for horizontal text)"), SPAttr::HORIZ_ORIGIN_X); - _horiz_origin_y_spin = new AttrSpin( this, (gchar*) _("Horiz. Origin Y:"), _("Default Y-coordinate of the origin of a glyph (for horizontal text)"), SPAttr::HORIZ_ORIGIN_Y); - _font_face_label = new Gtk::Label(Glib::ustring("<b>") + _("Font Face Attributes") + "</b>", Gtk::ALIGN_START, Gtk::ALIGN_CENTER); - _familyname_entry = new AttrEntry(this, (gchar*) _("Family Name:"), _("Name of the font as it appears in font selectors and css font-family properties"), SPAttr::FONT_FAMILY); - _units_per_em_spin = new AttrSpin( this, (gchar*) _("Units per em:"), _("Display units per <italic>em</italic> (nominally width of 'M' character)"), SPAttr::UNITS_PER_EM); - _ascent_spin = new AttrSpin( this, (gchar*) _("Ascent:"), _("Amount of space taken up by ascenders like the tall line on the letter 'h'"), SPAttr::ASCENT); - _descent_spin = new AttrSpin( this, (gchar*) _("Descent:"), _("Amount of space taken up by descenders like the tail on the letter 'g'"), SPAttr::DESCENT); - _cap_height_spin = new AttrSpin( this, (gchar*) _("Cap Height:"), _("The height of a capital letter above the baseline like the letter 'H' or 'I'"), SPAttr::CAP_HEIGHT); - _x_height_spin = new AttrSpin( this, (gchar*) _("x Height:"), _("The height of a lower-case letter above the baseline like the letter 'x'"), SPAttr::X_HEIGHT); +Gtk::VBox *SvgFontsDialog::global_settings_tab() +{ + _font_label = + new Gtk::Label(Glib::ustring("<b>") + _("Font Attributes") + "</b>", Gtk::ALIGN_START, Gtk::ALIGN_CENTER); + _horiz_adv_x_spin = new AttrSpin(this, (gchar *)_("Horiz. Advance X:"), + _("Default glyph width for horizontal text"), SPAttr::HORIZ_ADV_X); + _horiz_origin_x_spin = + new AttrSpin(this, (gchar *)_("Horiz. Origin X:"), + _("Default X-coordinate of the origin of a glyph (for horizontal text)"), SPAttr::HORIZ_ORIGIN_X); + _horiz_origin_y_spin = + new AttrSpin(this, (gchar *)_("Horiz. Origin Y:"), + _("Default Y-coordinate of the origin of a glyph (for horizontal text)"), SPAttr::HORIZ_ORIGIN_Y); + _font_face_label = + new Gtk::Label(Glib::ustring("<b>") + _("Font Face Attributes") + "</b>", Gtk::ALIGN_START, Gtk::ALIGN_CENTER); + _familyname_entry = new AttrEntry( + this, (gchar *)_("Family Name:"), + _("Name of the font as it appears in font selectors and css font-family properties"), SPAttr::FONT_FAMILY); + _units_per_em_spin = new AttrSpin(this, (gchar *)_("Units per em:"), + _("Display units per <italic>em</italic> (nominally width of 'M' character)"), + SPAttr::UNITS_PER_EM); + _ascent_spin = + new AttrSpin(this, (gchar *)_("Ascent:"), + _("Amount of space taken up by ascenders like the tall line on the letter 'h'"), SPAttr::ASCENT); + _descent_spin = + new AttrSpin(this, (gchar *)_("Descent:"), + _("Amount of space taken up by descenders like the tail on the letter 'g'"), SPAttr::DESCENT); + _cap_height_spin = new AttrSpin(this, (gchar *)_("Cap Height:"), + _("The height of a capital letter above the baseline like the letter 'H' or 'I'"), + SPAttr::CAP_HEIGHT); + _x_height_spin = + new AttrSpin(this, (gchar *)_("x Height:"), + _("The height of a lower-case letter above the baseline like the letter 'x'"), SPAttr::X_HEIGHT); //_descent_spin->set_range(-4096,0); _font_label->set_use_markup(); @@ -482,54 +518,56 @@ Gtk::VBox* SvgFontsDialog::global_settings_tab(){ global_vbox.pack_start(*_cap_height_spin); global_vbox.pack_start(*_x_height_spin); -/* global_vbox->add(*AttrCombo((gchar*) _("Style:"), SPAttr::FONT_STYLE)); - global_vbox->add(*AttrCombo((gchar*) _("Variant:"), SPAttr::FONT_VARIANT)); - global_vbox->add(*AttrCombo((gchar*) _("Weight:"), SPAttr::FONT_WEIGHT)); -*/ + /* global_vbox->add(*AttrCombo((gchar*) _("Style:"), SPAttr::FONT_STYLE)); + global_vbox->add(*AttrCombo((gchar*) _("Variant:"), SPAttr::FONT_VARIANT)); + global_vbox->add(*AttrCombo((gchar*) _("Weight:"), SPAttr::FONT_WEIGHT)); + */ return &global_vbox; } -void -SvgFontsDialog::populate_glyphs_box() +void SvgFontsDialog::populate_glyphs_box() { - if (!_GlyphsListStore) return; + if (!_GlyphsListStore) + return; _GlyphsListStore->clear(); - SPFont* spfont = this->get_selected_spfont(); + SPFont *spfont = this->get_selected_spfont(); _glyphs_observer.set(spfont); - for (auto& node: spfont->children) { - if (SP_IS_GLYPH(&node)){ + for (auto &node : spfont->children) { + if (SP_IS_GLYPH(&node)) { Gtk::TreeModel::Row row = *(_GlyphsListStore->append()); - row[_GlyphsListColumns.glyph_node] = static_cast<SPGlyph*>(&node); - row[_GlyphsListColumns.glyph_name] = (static_cast<SPGlyph*>(&node))->glyph_name; - row[_GlyphsListColumns.unicode] = (static_cast<SPGlyph*>(&node))->unicode; - row[_GlyphsListColumns.advance] = (static_cast<SPGlyph*>(&node))->horiz_adv_x; + row[_GlyphsListColumns.glyph_node] = static_cast<SPGlyph *>(&node); + row[_GlyphsListColumns.glyph_name] = (static_cast<SPGlyph *>(&node))->glyph_name; + row[_GlyphsListColumns.unicode] = (static_cast<SPGlyph *>(&node))->unicode; + row[_GlyphsListColumns.advance] = (static_cast<SPGlyph *>(&node))->horiz_adv_x; } } } -void -SvgFontsDialog::populate_kerning_pairs_box() +void SvgFontsDialog::populate_kerning_pairs_box() { - if (!_KerningPairsListStore) return; + if (!_KerningPairsListStore) + return; _KerningPairsListStore->clear(); - SPFont* spfont = this->get_selected_spfont(); + SPFont *spfont = this->get_selected_spfont(); - for (auto& node: spfont->children) { - if (SP_IS_HKERN(&node)){ + for (auto &node : spfont->children) { + if (SP_IS_HKERN(&node)) { Gtk::TreeModel::Row row = *(_KerningPairsListStore->append()); - row[_KerningPairsListColumns.first_glyph] = (static_cast<SPGlyphKerning*>(&node))->u1->attribute_string().c_str(); - row[_KerningPairsListColumns.second_glyph] = (static_cast<SPGlyphKerning*>(&node))->u2->attribute_string().c_str(); - row[_KerningPairsListColumns.kerning_value] = (static_cast<SPGlyphKerning*>(&node))->k; - row[_KerningPairsListColumns.spnode] = static_cast<SPGlyphKerning*>(&node); + row[_KerningPairsListColumns.first_glyph] = + (static_cast<SPGlyphKerning *>(&node))->u1->attribute_string().c_str(); + row[_KerningPairsListColumns.second_glyph] = + (static_cast<SPGlyphKerning *>(&node))->u2->attribute_string().c_str(); + row[_KerningPairsListColumns.kerning_value] = (static_cast<SPGlyphKerning *>(&node))->k; + row[_KerningPairsListColumns.spnode] = static_cast<SPGlyphKerning *>(&node); } } } -SPGlyph *new_glyph(SPDocument* document, SPFont *font, const int count) +SPGlyph *new_glyph(SPDocument *document, SPFont *font, const int count) { g_return_val_if_fail(font != nullptr, NULL); Inkscape::XML::Document *xml_doc = document->getReprDoc(); @@ -547,7 +585,7 @@ SPGlyph *new_glyph(SPDocument* document, SPFont *font, const int count) Inkscape::GC::release(repr); // get corresponding object - SPGlyph *g = SP_GLYPH( document->getObjectByRepr(repr) ); + SPGlyph *g = SP_GLYPH(document->getObjectByRepr(repr)); g_assert(g != nullptr); g_assert(SP_IS_GLYPH(g)); @@ -555,9 +593,11 @@ SPGlyph *new_glyph(SPDocument* document, SPFont *font, const int count) return g; } -void SvgFontsDialog::update_glyphs(){ - SPFont* font = get_selected_spfont(); - if (!font) return; +void SvgFontsDialog::update_glyphs() +{ + SPFont *font = get_selected_spfont(); + if (!font) + return; populate_glyphs_box(); populate_kerning_pairs_box(); first_glyph.update(font); @@ -566,57 +606,61 @@ void SvgFontsDialog::update_glyphs(){ _font_da.redraw(); } -void SvgFontsDialog::add_glyph(){ +void SvgFontsDialog::add_glyph() +{ const int count = _GlyphsListStore->children().size(); - SPDocument* doc = this->getDesktop()->getDocument(); - /* SPGlyph* glyph =*/ new_glyph(doc, get_selected_spfont(), count+1); + SPDocument *doc = this->getDesktop()->getDocument(); + /* SPGlyph* glyph =*/new_glyph(doc, get_selected_spfont(), count + 1); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Add glyph")); update_glyphs(); } -Geom::PathVector -SvgFontsDialog::flip_coordinate_system(Geom::PathVector pathv){ +Geom::PathVector SvgFontsDialog::flip_coordinate_system(Geom::PathVector pathv) +{ double units_per_em = 1024; - for (auto& obj: get_selected_spfont()->children) { - if (SP_IS_FONTFACE(&obj)){ - //XML Tree being directly used here while it shouldn't be. + for (auto &obj : get_selected_spfont()->children) { + if (SP_IS_FONTFACE(&obj)) { + // XML Tree being directly used here while it shouldn't be. sp_repr_get_double(obj.getRepr(), "units-per-em", &units_per_em); } } double baseline_offset = units_per_em - get_selected_spfont()->horiz_origin_y; - //This matrix flips y-axis and places the origin at baseline - Geom::Affine m(Geom::Coord(1),Geom::Coord(0),Geom::Coord(0),Geom::Coord(-1),Geom::Coord(0),Geom::Coord(baseline_offset)); - return pathv*m; + // This matrix flips y-axis and places the origin at baseline + Geom::Affine m(Geom::Coord(1), Geom::Coord(0), Geom::Coord(0), Geom::Coord(-1), Geom::Coord(0), + Geom::Coord(baseline_offset)); + return pathv * m; } -void SvgFontsDialog::set_glyph_description_from_selected_path(){ - SPDesktop* desktop = this->getDesktop(); +void SvgFontsDialog::set_glyph_description_from_selected_path() +{ + SPDesktop *desktop = this->getDesktop(); if (!desktop) { g_warning("SvgFontsDialog: No active desktop"); return; } Inkscape::MessageStack *msgStack = desktop->getMessageStack(); - SPDocument* doc = desktop->getDocument(); - Inkscape::Selection* sel = desktop->getSelection(); - if (sel->isEmpty()){ + SPDocument *doc = desktop->getDocument(); + Inkscape::Selection *sel = desktop->getSelection(); + if (sel->isEmpty()) { char *msg = _("Select a <b>path</b> to define the curves of a glyph"); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); return; } - Inkscape::XML::Node* node = sel->xmlNodes().front(); - if (!node) return;//TODO: should this be an assert? - if (!node->matchAttributeName("d") || !node->attribute("d")){ + Inkscape::XML::Node *node = sel->xmlNodes().front(); + if (!node) + return; // TODO: should this be an assert? + if (!node->matchAttributeName("d") || !node->attribute("d")) { char *msg = _("The selected object does not have a <b>path</b> description."); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); return; - } //TODO: //Is there a better way to tell it to to the user? + } // TODO: //Is there a better way to tell it to to the user? - SPGlyph* glyph = get_selected_glyph(); - if (!glyph){ + SPGlyph *glyph = get_selected_glyph(); + if (!glyph) { char *msg = _("No glyph selected in the SVGFonts dialog."); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); return; @@ -624,8 +668,8 @@ 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. - gchar *str = sp_svg_write_path (flip_coordinate_system(pathv)); + // XML Tree being directly used here while it shouldn't be. + gchar *str = sp_svg_write_path(flip_coordinate_system(pathv)); glyph->setAttribute("d", str); g_free(str); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Set glyph curves")); @@ -633,37 +677,38 @@ void SvgFontsDialog::set_glyph_description_from_selected_path(){ update_glyphs(); } -void SvgFontsDialog::missing_glyph_description_from_selected_path(){ - SPDesktop* desktop = this->getDesktop(); +void SvgFontsDialog::missing_glyph_description_from_selected_path() +{ + SPDesktop *desktop = this->getDesktop(); if (!desktop) { g_warning("SvgFontsDialog: No active desktop"); return; } Inkscape::MessageStack *msgStack = desktop->getMessageStack(); - SPDocument* doc = desktop->getDocument(); - Inkscape::Selection* sel = desktop->getSelection(); - if (sel->isEmpty()){ + SPDocument *doc = desktop->getDocument(); + Inkscape::Selection *sel = desktop->getSelection(); + if (sel->isEmpty()) { char *msg = _("Select a <b>path</b> to define the curves of a glyph"); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); return; } - Inkscape::XML::Node* node = sel->xmlNodes().front(); - if (!node) return;//TODO: should this be an assert? - if (!node->matchAttributeName("d") || !node->attribute("d")){ + Inkscape::XML::Node *node = sel->xmlNodes().front(); + if (!node) + return; // TODO: should this be an assert? + if (!node->matchAttributeName("d") || !node->attribute("d")) { char *msg = _("The selected object does not have a <b>path</b> description."); msgStack->flash(Inkscape::ERROR_MESSAGE, msg); return; - } //TODO: //Is there a better way to tell it to to the user? + } // TODO: //Is there a better way to tell it to to the user? Geom::PathVector pathv = sp_svg_read_pathv(node->attribute("d")); - for (auto& obj: get_selected_spfont()->children) { - if (SP_IS_MISSING_GLYPH(&obj)){ - - //XML Tree being directly used here while it shouldn't be. - gchar *str = sp_svg_write_path (flip_coordinate_system(pathv)); + for (auto &obj : get_selected_spfont()->children) { + if (SP_IS_MISSING_GLYPH(&obj)) { + // XML Tree being directly used here while it shouldn't be. + gchar *str = sp_svg_write_path(flip_coordinate_system(pathv)); obj.setAttribute("d", str); g_free(str); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Set glyph curves")); @@ -673,17 +718,18 @@ void SvgFontsDialog::missing_glyph_description_from_selected_path(){ update_glyphs(); } -void SvgFontsDialog::reset_missing_glyph_description(){ - SPDesktop* desktop = this->getDesktop(); +void SvgFontsDialog::reset_missing_glyph_description() +{ + SPDesktop *desktop = this->getDesktop(); if (!desktop) { g_warning("SvgFontsDialog: No active desktop"); return; } - SPDocument* doc = desktop->getDocument(); - for (auto& obj: get_selected_spfont()->children) { - if (SP_IS_MISSING_GLYPH(&obj)){ - //XML Tree being directly used here while it shouldn't be. + SPDocument *doc = desktop->getDocument(); + for (auto &obj : get_selected_spfont()->children) { + if (SP_IS_MISSING_GLYPH(&obj)) { + // XML Tree being directly used here while it shouldn't be. obj.setAttribute("d", "M0,0h1000v1024h-1000z"); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Reset missing-glyph")); } @@ -692,46 +738,52 @@ void SvgFontsDialog::reset_missing_glyph_description(){ update_glyphs(); } -void SvgFontsDialog::glyph_name_edit(const Glib::ustring&, const Glib::ustring& str){ +void SvgFontsDialog::glyph_name_edit(const Glib::ustring &, const Glib::ustring &str) +{ Gtk::TreeModel::iterator i = _GlyphsList.get_selection()->get_selected(); - if (!i) return; + if (!i) + return; - SPGlyph* glyph = (*i)[_GlyphsListColumns.glyph_node]; - //XML Tree being directly used here while it shouldn't be. + SPGlyph *glyph = (*i)[_GlyphsListColumns.glyph_node]; + // XML Tree being directly used here while it shouldn't be. glyph->setAttribute("glyph-name", str); - SPDocument* doc = this->getDesktop()->getDocument(); + SPDocument *doc = this->getDesktop()->getDocument(); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Edit glyph name")); update_glyphs(); } -void SvgFontsDialog::glyph_unicode_edit(const Glib::ustring&, const Glib::ustring& str){ +void SvgFontsDialog::glyph_unicode_edit(const Glib::ustring &, const Glib::ustring &str) +{ Gtk::TreeModel::iterator i = _GlyphsList.get_selection()->get_selected(); - if (!i) return; + if (!i) + return; - SPGlyph* glyph = (*i)[_GlyphsListColumns.glyph_node]; - //XML Tree being directly used here while it shouldn't be. + SPGlyph *glyph = (*i)[_GlyphsListColumns.glyph_node]; + // XML Tree being directly used here while it shouldn't be. glyph->setAttribute("unicode", str); - SPDocument* doc = this->getDesktop()->getDocument(); + SPDocument *doc = this->getDesktop()->getDocument(); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Set glyph unicode")); update_glyphs(); } -void SvgFontsDialog::glyph_advance_edit(const Glib::ustring&, const Glib::ustring& str){ +void SvgFontsDialog::glyph_advance_edit(const Glib::ustring &, const Glib::ustring &str) +{ Gtk::TreeModel::iterator i = _GlyphsList.get_selection()->get_selected(); - if (!i) return; + if (!i) + return; - SPGlyph* glyph = (*i)[_GlyphsListColumns.glyph_node]; - //XML Tree being directly used here while it shouldn't be. + SPGlyph *glyph = (*i)[_GlyphsListColumns.glyph_node]; + // XML Tree being directly used here while it shouldn't be. std::istringstream is(str.raw()); double value; // Check if input valid if ((is >> value)) { glyph->setAttribute("horiz-adv-x", str); - SPDocument* doc = this->getDesktop()->getDocument(); + SPDocument *doc = this->getDesktop()->getDocument(); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Set glyph advance")); update_glyphs(); @@ -740,71 +792,83 @@ void SvgFontsDialog::glyph_advance_edit(const Glib::ustring&, const Glib::ustrin } } -void SvgFontsDialog::remove_selected_font(){ - SPFont* font = get_selected_spfont(); - if (!font) return; +void SvgFontsDialog::remove_selected_font() +{ + SPFont *font = get_selected_spfont(); + if (!font) + return; - //XML Tree being directly used here while it shouldn't be. + // XML Tree being directly used here while it shouldn't be. sp_repr_unparent(font->getRepr()); - SPDocument* doc = this->getDesktop()->getDocument(); + SPDocument *doc = this->getDesktop()->getDocument(); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Remove font")); update_fonts(); } -void SvgFontsDialog::remove_selected_glyph(){ - if(!_GlyphsList.get_selection()) return; +void SvgFontsDialog::remove_selected_glyph() +{ + if (!_GlyphsList.get_selection()) + return; Gtk::TreeModel::iterator i = _GlyphsList.get_selection()->get_selected(); - if(!i) return; + if (!i) + return; - SPGlyph* glyph = (*i)[_GlyphsListColumns.glyph_node]; + SPGlyph *glyph = (*i)[_GlyphsListColumns.glyph_node]; - //XML Tree being directly used here while it shouldn't be. + // XML Tree being directly used here while it shouldn't be. sp_repr_unparent(glyph->getRepr()); - SPDocument* doc = this->getDesktop()->getDocument(); + SPDocument *doc = this->getDesktop()->getDocument(); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Remove glyph")); update_glyphs(); } -void SvgFontsDialog::remove_selected_kerning_pair(){ - if(!_KerningPairsList.get_selection()) return; +void SvgFontsDialog::remove_selected_kerning_pair() +{ + if (!_KerningPairsList.get_selection()) + return; Gtk::TreeModel::iterator i = _KerningPairsList.get_selection()->get_selected(); - if(!i) return; + if (!i) + return; - SPGlyphKerning* pair = (*i)[_KerningPairsListColumns.spnode]; + SPGlyphKerning *pair = (*i)[_KerningPairsListColumns.spnode]; - //XML Tree being directly used here while it shouldn't be. + // XML Tree being directly used here while it shouldn't be. sp_repr_unparent(pair->getRepr()); - SPDocument* doc = this->getDesktop()->getDocument(); + SPDocument *doc = this->getDesktop()->getDocument(); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Remove kerning pair")); update_glyphs(); } -Gtk::VBox* SvgFontsDialog::glyphs_tab(){ - _GlyphsList.signal_button_release_event().connect_notify(sigc::mem_fun(*this, &SvgFontsDialog::glyphs_list_button_release)); +Gtk::VBox *SvgFontsDialog::glyphs_tab() +{ + _GlyphsList.signal_button_release_event().connect_notify( + sigc::mem_fun(*this, &SvgFontsDialog::glyphs_list_button_release)); create_glyphs_popup_menu(_GlyphsList, sigc::mem_fun(*this, &SvgFontsDialog::remove_selected_glyph)); - Gtk::HBox* missing_glyph_hbox = Gtk::manage(new Gtk::HBox(false, 4)); - Gtk::Label* missing_glyph_label = Gtk::manage(new Gtk::Label(_("Missing Glyph:"))); + Gtk::HBox *missing_glyph_hbox = Gtk::manage(new Gtk::HBox(false, 4)); + Gtk::Label *missing_glyph_label = Gtk::manage(new Gtk::Label(_("Missing Glyph:"))); missing_glyph_hbox->set_hexpand(false); - missing_glyph_hbox->pack_start(*missing_glyph_label, false,false); - missing_glyph_hbox->pack_start(missing_glyph_button, false,false); - missing_glyph_hbox->pack_start(missing_glyph_reset_button, false,false); + missing_glyph_hbox->pack_start(*missing_glyph_label, false, false); + missing_glyph_hbox->pack_start(missing_glyph_button, false, false); + missing_glyph_hbox->pack_start(missing_glyph_reset_button, false, false); missing_glyph_button.set_label(_("From selection...")); - missing_glyph_button.signal_clicked().connect(sigc::mem_fun(*this, &SvgFontsDialog::missing_glyph_description_from_selected_path)); + missing_glyph_button.signal_clicked().connect( + sigc::mem_fun(*this, &SvgFontsDialog::missing_glyph_description_from_selected_path)); missing_glyph_reset_button.set_label(_("Reset")); - missing_glyph_reset_button.signal_clicked().connect(sigc::mem_fun(*this, &SvgFontsDialog::reset_missing_glyph_description)); + missing_glyph_reset_button.signal_clicked().connect( + sigc::mem_fun(*this, &SvgFontsDialog::reset_missing_glyph_description)); glyphs_vbox.set_border_width(4); glyphs_vbox.set_spacing(4); - glyphs_vbox.pack_start(*missing_glyph_hbox, false,false); + glyphs_vbox.pack_start(*missing_glyph_hbox, false, false); glyphs_vbox.add(_GlyphsListScroller); _GlyphsListScroller.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS); @@ -812,53 +876,60 @@ Gtk::VBox* SvgFontsDialog::glyphs_tab(){ _GlyphsListScroller.add(_GlyphsList); _GlyphsListStore = Gtk::ListStore::create(_GlyphsListColumns); _GlyphsList.set_model(_GlyphsListStore); - _GlyphsList.append_column_editable(_("Glyph name"), _GlyphsListColumns.glyph_name); + _GlyphsList.append_column_editable(_("Glyph name"), _GlyphsListColumns.glyph_name); _GlyphsList.append_column_editable(_("Matching string"), _GlyphsListColumns.unicode); _GlyphsList.append_column_numeric_editable(_("Advance"), _GlyphsListColumns.advance, "%.2f"); - Gtk::HBox* hb = Gtk::manage(new Gtk::HBox(false, 4)); + Gtk::HBox *hb = Gtk::manage(new Gtk::HBox(false, 4)); add_glyph_button.set_label(_("Add Glyph")); add_glyph_button.signal_clicked().connect(sigc::mem_fun(*this, &SvgFontsDialog::add_glyph)); - hb->pack_start(add_glyph_button, false,false); - hb->pack_start(glyph_from_path_button, false,false); + hb->pack_start(add_glyph_button, false, false); + hb->pack_start(glyph_from_path_button, false, false); glyphs_vbox.pack_start(*hb, false, false); glyph_from_path_button.set_label(_("Get curves from selection...")); - glyph_from_path_button.signal_clicked().connect(sigc::mem_fun(*this, &SvgFontsDialog::set_glyph_description_from_selected_path)); + glyph_from_path_button.signal_clicked().connect( + sigc::mem_fun(*this, &SvgFontsDialog::set_glyph_description_from_selected_path)); - dynamic_cast<Gtk::CellRendererText*>( _GlyphsList.get_column_cell_renderer(0))->signal_edited().connect( - sigc::mem_fun(*this, &SvgFontsDialog::glyph_name_edit)); + dynamic_cast<Gtk::CellRendererText *>(_GlyphsList.get_column_cell_renderer(0)) + ->signal_edited() + .connect(sigc::mem_fun(*this, &SvgFontsDialog::glyph_name_edit)); - dynamic_cast<Gtk::CellRendererText*>( _GlyphsList.get_column_cell_renderer(1))->signal_edited().connect( - sigc::mem_fun(*this, &SvgFontsDialog::glyph_unicode_edit)); + dynamic_cast<Gtk::CellRendererText *>(_GlyphsList.get_column_cell_renderer(1)) + ->signal_edited() + .connect(sigc::mem_fun(*this, &SvgFontsDialog::glyph_unicode_edit)); - dynamic_cast<Gtk::CellRendererText*>( _GlyphsList.get_column_cell_renderer(2))->signal_edited().connect( - sigc::mem_fun(*this, &SvgFontsDialog::glyph_advance_edit)); + dynamic_cast<Gtk::CellRendererText *>(_GlyphsList.get_column_cell_renderer(2)) + ->signal_edited() + .connect(sigc::mem_fun(*this, &SvgFontsDialog::glyph_advance_edit)); _glyphs_observer.signal_changed().connect(sigc::mem_fun(*this, &SvgFontsDialog::update_glyphs)); return &glyphs_vbox; } -void SvgFontsDialog::add_kerning_pair(){ - if (first_glyph.get_active_text() == "" || - second_glyph.get_active_text() == "") return; +void SvgFontsDialog::add_kerning_pair() +{ + if (first_glyph.get_active_text() == "" || second_glyph.get_active_text() == "") + return; - //look for this kerning pair on the currently selected font + // look for this kerning pair on the currently selected font this->kerning_pair = nullptr; - for (auto& node: get_selected_spfont()->children) { - //TODO: It is not really correct to get only the first byte of each string. - //TODO: We should also support vertical kerning - if (SP_IS_HKERN(&node) && (static_cast<SPGlyphKerning*>(&node))->u1->contains((gchar) first_glyph.get_active_text().c_str()[0]) - && (static_cast<SPGlyphKerning*>(&node))->u2->contains((gchar) second_glyph.get_active_text().c_str()[0]) ){ - this->kerning_pair = static_cast<SPGlyphKerning*>(&node); + for (auto &node : get_selected_spfont()->children) { + // TODO: It is not really correct to get only the first byte of each string. + // TODO: We should also support vertical kerning + if (SP_IS_HKERN(&node) && + (static_cast<SPGlyphKerning *>(&node))->u1->contains((gchar)first_glyph.get_active_text().c_str()[0]) && + (static_cast<SPGlyphKerning *>(&node))->u2->contains((gchar)second_glyph.get_active_text().c_str()[0])) { + this->kerning_pair = static_cast<SPGlyphKerning *>(&node); continue; } } - if (this->kerning_pair) return; //We already have this kerning pair + if (this->kerning_pair) + return; // We already have this kerning pair - SPDocument* document = this->getDesktop()->getDocument(); + SPDocument *document = this->getDesktop()->getDocument(); Inkscape::XML::Document *xml_doc = document->getReprDoc(); // create a new hkern node @@ -873,20 +944,23 @@ void SvgFontsDialog::add_kerning_pair(){ Inkscape::GC::release(repr); // get corresponding object - this->kerning_pair = SP_HKERN( document->getObjectByRepr(repr) ); + this->kerning_pair = SP_HKERN(document->getObjectByRepr(repr)); DocumentUndo::done(document, SP_VERB_DIALOG_SVG_FONTS, _("Add kerning pair")); } -Gtk::VBox* SvgFontsDialog::kerning_tab(){ - _KerningPairsList.signal_button_release_event().connect_notify(sigc::mem_fun(*this, &SvgFontsDialog::kerning_pairs_list_button_release)); - create_kerning_pairs_popup_menu(_KerningPairsList, sigc::mem_fun(*this, &SvgFontsDialog::remove_selected_kerning_pair)); +Gtk::VBox *SvgFontsDialog::kerning_tab() +{ + _KerningPairsList.signal_button_release_event().connect_notify( + sigc::mem_fun(*this, &SvgFontsDialog::kerning_pairs_list_button_release)); + create_kerning_pairs_popup_menu(_KerningPairsList, + sigc::mem_fun(*this, &SvgFontsDialog::remove_selected_kerning_pair)); -//Kerning Setup: + // Kerning Setup: kerning_vbox.set_border_width(4); kerning_vbox.set_spacing(4); // kerning_vbox.add(*Gtk::manage(new Gtk::Label(_("Kerning Setup")))); - Gtk::HBox* kerning_selector = Gtk::manage(new Gtk::HBox()); + Gtk::HBox *kerning_selector = Gtk::manage(new Gtk::HBox()); kerning_selector->pack_start(*Gtk::manage(new Gtk::Label(_("1st Glyph:"))), false, false); kerning_selector->pack_start(first_glyph, true, true, 4); kerning_selector->pack_start(*Gtk::manage(new Gtk::Label(_("2nd Glyph:"))), false, false); @@ -894,27 +968,29 @@ Gtk::VBox* SvgFontsDialog::kerning_tab(){ kerning_selector->pack_start(add_kernpair_button, true, true); 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)); + _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_vbox.pack_start(*kerning_selector, false,false); + kerning_vbox.pack_start(*kerning_selector, false, false); - kerning_vbox.pack_start(_KerningPairsListScroller, true,true); + kerning_vbox.pack_start(_KerningPairsListScroller, true, true); _KerningPairsListScroller.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS); _KerningPairsListScroller.add(_KerningPairsList); _KerningPairsListStore = Gtk::ListStore::create(_KerningPairsListColumns); _KerningPairsList.set_model(_KerningPairsListStore); _KerningPairsList.append_column(_("First Unicode range"), _KerningPairsListColumns.first_glyph); _KerningPairsList.append_column(_("Second Unicode range"), _KerningPairsListColumns.second_glyph); -// _KerningPairsList.append_column_numeric_editable(_("Kerning Value"), _KerningPairsListColumns.kerning_value, "%f"); + // _KerningPairsList.append_column_numeric_editable(_("Kerning Value"), _KerningPairsListColumns.kerning_value, + // "%f"); - kerning_vbox.pack_start((Gtk::Widget&) kerning_preview, false,false); + kerning_vbox.pack_start((Gtk::Widget &)kerning_preview, false, false); // kerning_slider has a big handle. Extra padding added - Gtk::HBox* kerning_amount_hbox = Gtk::manage(new Gtk::HBox(false, 8)); - kerning_vbox.pack_start(*kerning_amount_hbox, false,false); - kerning_amount_hbox->pack_start(*Gtk::manage(new Gtk::Label(_("Kerning Value:"))), false,false); - kerning_amount_hbox->pack_start(*kerning_slider, true,true); + Gtk::HBox *kerning_amount_hbox = Gtk::manage(new Gtk::HBox(false, 8)); + kerning_vbox.pack_start(*kerning_amount_hbox, false, false); + kerning_amount_hbox->pack_start(*Gtk::manage(new Gtk::Label(_("Kerning Value:"))), false, false); + kerning_amount_hbox->pack_start(*kerning_slider, true, true); kerning_preview.set_size(300 + 20, 150 + 20); _font_da.set_size(300 + 50 + 20, 60 + 20); @@ -933,26 +1009,26 @@ SPFont *new_font(SPDocument *document) // create a new font Inkscape::XML::Node *repr = xml_doc->createElement("svg:font"); - //By default, set the horizontal advance to 1024 units + // By default, set the horizontal advance to 1024 units repr->setAttribute("horiz-adv-x", "1024"); // Append the new font node to defs defs->getRepr()->appendChild(repr); - //create a missing glyph + // create a missing glyph Inkscape::XML::Node *fontface; fontface = xml_doc->createElement("svg:font-face"); fontface->setAttribute("units-per-em", "1024"); repr->appendChild(fontface); - //create a missing glyph + // create a missing glyph Inkscape::XML::Node *mg; mg = xml_doc->createElement("svg:missing-glyph"); mg->setAttribute("d", "M0,0h1000v1024h-1000z"); repr->appendChild(mg); // get corresponding object - SPFont *f = SP_FONT( document->getObjectByRepr(repr) ); + SPFont *f = SP_FONT(document->getObjectByRepr(repr)); g_assert(f != nullptr); g_assert(SP_IS_FONT(f)); @@ -961,11 +1037,13 @@ SPFont *new_font(SPDocument *document) return f; } -void set_font_family(SPFont* font, char* str){ - if (!font) return; - for (auto& obj: font->children) { - if (SP_IS_FONTFACE(&obj)){ - //XML Tree being directly used here while it shouldn't be. +void set_font_family(SPFont *font, char *str) +{ + if (!font) + return; + for (auto &obj : font->children) { + if (SP_IS_FONTFACE(&obj)) { + // XML Tree being directly used here while it shouldn't be. obj.setAttribute("font-family", str); } } @@ -973,9 +1051,10 @@ void set_font_family(SPFont* font, char* str){ DocumentUndo::done(font->document, SP_VERB_DIALOG_SVG_FONTS, _("Set font family")); } -void SvgFontsDialog::add_font(){ - SPDocument* doc = this->getDesktop()->getDocument(); - SPFont* font = new_font(doc); +void SvgFontsDialog::add_font() +{ + SPDocument *doc = this->getDesktop()->getDocument(); + SPFont *font = new_font(doc); const int count = _model->children().size(); std::ostringstream os, os2; @@ -983,28 +1062,28 @@ void SvgFontsDialog::add_font(){ font->setLabel(os.str().c_str()); os2 << "SVGFont " << count; - for (auto& obj: font->children) { - if (SP_IS_FONTFACE(&obj)){ - //XML Tree being directly used here while it shouldn't be. + for (auto &obj : font->children) { + if (SP_IS_FONTFACE(&obj)) { + // XML Tree being directly used here while it shouldn't be. obj.setAttribute("font-family", os2.str()); } } update_fonts(); -// select_font(font); + // select_font(font); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Add font")); } SvgFontsDialog::SvgFontsDialog() - : UI::Widget::Panel("/dialogs/svgfonts", SP_VERB_DIALOG_SVG_FONTS), - _add(_("_New"), true) + : UI::Widget::Panel("/dialogs/svgfonts", SP_VERB_DIALOG_SVG_FONTS) + , _add(_("_New"), true) { kerning_slider = Gtk::manage(new Gtk::Scale(Gtk::ORIENTATION_HORIZONTAL)); _add.signal_clicked().connect(sigc::mem_fun(*this, &SvgFontsDialog::add_font)); - Gtk::HBox* hbox = Gtk::manage(new Gtk::HBox()); - Gtk::VBox* vbox = Gtk::manage(new Gtk::VBox()); + Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox()); + Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox()); vbox->pack_start(_FontsList); vbox->pack_start(_add, false, false); @@ -1012,11 +1091,12 @@ SvgFontsDialog::SvgFontsDialog() hbox->add(_font_settings); _getContents()->add(*hbox); -//List of SVGFonts declared in a document: + // List of SVGFonts declared in a document: _model = Gtk::ListStore::create(_columns); _FontsList.set_model(_model); _FontsList.append_column_editable(_("_Fonts"), _columns.label); - _FontsList.get_selection()->signal_changed().connect(sigc::mem_fun(*this, &SvgFontsDialog::on_font_selection_changed)); + _FontsList.get_selection()->signal_changed().connect( + sigc::mem_fun(*this, &SvgFontsDialog::on_font_selection_changed)); Gtk::Notebook *tabs = Gtk::manage(new Gtk::Notebook()); tabs->set_scrollable(); @@ -1027,24 +1107,25 @@ SvgFontsDialog::SvgFontsDialog() _font_settings.add(*tabs); -//Text Preview: + // Text Preview: _preview_entry.signal_changed().connect(sigc::mem_fun(*this, &SvgFontsDialog::on_preview_text_changed)); - _getContents()->pack_start((Gtk::Widget&) _font_da, false, false); + _getContents()->pack_start((Gtk::Widget &)_font_da, false, false); _preview_entry.set_text(_("Sample Text")); _font_da.set_text(_("Sample Text")); - Gtk::HBox* preview_entry_hbox = Gtk::manage(new Gtk::HBox(false, 4)); + Gtk::HBox *preview_entry_hbox = Gtk::manage(new Gtk::HBox(false, 4)); _getContents()->pack_start(*preview_entry_hbox, false, false); // Non-latin characters may need more height. preview_entry_hbox->pack_start(*Gtk::manage(new Gtk::Label(_("Preview Text:"))), false, false); preview_entry_hbox->pack_start(_preview_entry, true, true); - _FontsList.signal_button_release_event().connect_notify(sigc::mem_fun(*this, &SvgFontsDialog::fonts_list_button_release)); + _FontsList.signal_button_release_event().connect_notify( + sigc::mem_fun(*this, &SvgFontsDialog::fonts_list_button_release)); create_fonts_popup_menu(_FontsList, sigc::mem_fun(*this, &SvgFontsDialog::remove_selected_font)); _getContents()->show_all(); } -SvgFontsDialog::~SvgFontsDialog()= default; +SvgFontsDialog::~SvgFontsDialog() = default; void SvgFontsDialog::setDesktop(SPDesktop *desktop) { diff --git a/src/ui/dialog/svg-fonts-dialog.h b/src/ui/dialog/svg-fonts-dialog.h index ffd0e7deb43d4cffcac2e4ddf04a411fd93b95ca..b87efbf1f552128c2a025a2b1aaf2c50e5cc02e5 100644 --- a/src/ui/dialog/svg-fonts-dialog.h +++ b/src/ui/dialog/svg-fonts-dialog.h @@ -12,10 +12,7 @@ #ifndef INKSCAPE_UI_DIALOG_SVG_FONTS_H #define INKSCAPE_UI_DIALOG_SVG_FONTS_H -#include "ui/widget/panel.h" #include <2geom/pathvector.h> -#include "ui/widget/spinbutton.h" - #include <gtkmm/box.h> #include <gtkmm/comboboxtext.h> #include <gtkmm/drawingarea.h> @@ -25,6 +22,8 @@ #include <gtkmm/treeview.h> #include "attributes.h" +#include "ui/widget/panel.h" +#include "ui/widget/spinbutton.h" #include "xml/helper-observer.h" namespace Gtk { @@ -35,16 +34,18 @@ class SPGlyph; class SPGlyphKerning; class SvgFont; -class SvgFontDrawingArea : Gtk::DrawingArea{ +class SvgFontDrawingArea : Gtk::DrawingArea +{ public: SvgFontDrawingArea(); void set_text(Glib::ustring); - void set_svgfont(SvgFont*); + void set_svgfont(SvgFont *); void set_size(int x, int y); void redraw(); + private: - int _x,_y; - SvgFont* _svgfont; + int _x, _y; + SvgFont *_svgfont; Glib::ustring _text; bool on_draw(const Cairo::RefPtr<Cairo::Context> &cr) override; }; @@ -55,13 +56,15 @@ namespace Inkscape { namespace UI { namespace Dialog { -class GlyphComboBox : public Gtk::ComboBoxText { +class GlyphComboBox : public Gtk::ComboBoxText +{ public: GlyphComboBox(); - void update(SPFont*); + void update(SPFont *); }; -class SvgFontsDialog : public UI::Widget::Panel { +class SvgFontsDialog : public UI::Widget::Panel +{ public: SvgFontsDialog(); ~SvgFontsDialog() override; @@ -71,12 +74,12 @@ public: void setDesktop(SPDesktop *) override; void update_fonts(); - SvgFont* get_selected_svgfont(); - SPFont* get_selected_spfont(); - SPGlyph* get_selected_glyph(); - SPGlyphKerning* get_selected_kerning_pair(); + SvgFont *get_selected_svgfont(); + SPFont *get_selected_spfont(); + SPGlyph *get_selected_glyph(); + SPGlyphKerning *get_selected_kerning_pair(); - //TODO: these methods should be private, right?! + // TODO: these methods should be private, right?! void on_font_selection_changed(); void on_kerning_pair_selection_changed(); void on_preview_text_changed(); @@ -91,10 +94,11 @@ public: class AttrEntry : public Gtk::HBox { public: - AttrEntry(SvgFontsDialog* d, gchar* lbl, Glib::ustring tooltip, const SPAttr attr); - void set_text(char*); + AttrEntry(SvgFontsDialog *d, gchar *lbl, Glib::ustring tooltip, const SPAttr attr); + void set_text(char *); + private: - SvgFontsDialog* dialog; + SvgFontsDialog *dialog; void on_attr_changed(); Gtk::Entry entry; SPAttr attr; @@ -103,12 +107,13 @@ public: class AttrSpin : public Gtk::HBox { public: - AttrSpin(SvgFontsDialog* d, gchar* lbl, Glib::ustring tooltip, const SPAttr attr); + AttrSpin(SvgFontsDialog *d, gchar *lbl, Glib::ustring tooltip, const SPAttr attr); void set_value(double v); void set_range(double low, double high); - Inkscape::UI::Widget::SpinButton* getSpin() { return &spin; } + Inkscape::UI::Widget::SpinButton *getSpin() { return &spin; } + private: - SvgFontsDialog* dialog; + SvgFontsDialog *dialog; void on_attr_changed(); Inkscape::UI::Widget::SpinButton spin; SPAttr attr; @@ -124,50 +129,50 @@ private: void missing_glyph_description_from_selected_path(); void reset_missing_glyph_description(); void add_glyph(); - void glyph_unicode_edit(const Glib::ustring&, const Glib::ustring&); - void glyph_name_edit( const Glib::ustring&, const Glib::ustring&); - void glyph_advance_edit(const Glib::ustring&, const Glib::ustring&); + void glyph_unicode_edit(const Glib::ustring &, const Glib::ustring &); + void glyph_name_edit(const Glib::ustring &, const Glib::ustring &); + void glyph_advance_edit(const Glib::ustring &, const Glib::ustring &); void remove_selected_glyph(); void remove_selected_font(); void remove_selected_kerning_pair(); void add_kerning_pair(); - void create_glyphs_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem); - void glyphs_list_button_release(GdkEventButton* event); + void create_glyphs_popup_menu(Gtk::Widget &parent, sigc::slot<void> rem); + void glyphs_list_button_release(GdkEventButton *event); - void create_fonts_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem); - void fonts_list_button_release(GdkEventButton* event); + void create_fonts_popup_menu(Gtk::Widget &parent, sigc::slot<void> rem); + void fonts_list_button_release(GdkEventButton *event); - void create_kerning_pairs_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem); - void kerning_pairs_list_button_release(GdkEventButton* event); + void create_kerning_pairs_popup_menu(Gtk::Widget &parent, sigc::slot<void> rem); + void kerning_pairs_list_button_release(GdkEventButton *event); - Inkscape::XML::SignalObserver _defs_observer; //in order to update fonts + Inkscape::XML::SignalObserver _defs_observer; // in order to update fonts Inkscape::XML::SignalObserver _glyphs_observer; sigc::connection _defs_observer_connection; - Gtk::HBox* AttrCombo(gchar* lbl, const SPAttr attr); -// Gtk::HBox* AttrSpin(gchar* lbl, const SPAttr attr); - Gtk::VBox* global_settings_tab(); + Gtk::HBox *AttrCombo(gchar *lbl, const SPAttr attr); + // Gtk::HBox* AttrSpin(gchar* lbl, const SPAttr attr); + Gtk::VBox *global_settings_tab(); // <font> - Gtk::Label* _font_label; - AttrSpin* _horiz_adv_x_spin; - AttrSpin* _horiz_origin_x_spin; - AttrSpin* _horiz_origin_y_spin; + Gtk::Label *_font_label; + AttrSpin *_horiz_adv_x_spin; + AttrSpin *_horiz_origin_x_spin; + AttrSpin *_horiz_origin_y_spin; // <font-face> - Gtk::Label* _font_face_label; - AttrEntry* _familyname_entry; - AttrSpin* _units_per_em_spin; - AttrSpin* _ascent_spin; - AttrSpin* _descent_spin; - AttrSpin* _cap_height_spin; - AttrSpin* _x_height_spin; - - Gtk::VBox* kerning_tab(); - Gtk::VBox* glyphs_tab(); + Gtk::Label *_font_face_label; + AttrEntry *_familyname_entry; + AttrSpin *_units_per_em_spin; + AttrSpin *_ascent_spin; + AttrSpin *_descent_spin; + AttrSpin *_cap_height_spin; + AttrSpin *_x_height_spin; + + Gtk::VBox *kerning_tab(); + Gtk::VBox *glyphs_tab(); Gtk::Button _add; Gtk::Button add_glyph_button; Gtk::Button glyph_from_path_button; @@ -178,14 +183,14 @@ private: { public: Columns() - { + { add(spfont); add(svgfont); add(label); - } + } - Gtk::TreeModelColumn<SPFont*> spfont; - Gtk::TreeModelColumn<SvgFont*> svgfont; + Gtk::TreeModelColumn<SPFont *> spfont; + Gtk::TreeModelColumn<SvgFont *> svgfont; Gtk::TreeModelColumn<Glib::ustring> label; }; Glib::RefPtr<Gtk::ListStore> _model; @@ -196,14 +201,14 @@ private: { public: GlyphsColumns() - { + { add(glyph_node); add(glyph_name); add(unicode); add(advance); - } + } - Gtk::TreeModelColumn<SPGlyph*> glyph_node; + Gtk::TreeModelColumn<SPGlyph *> glyph_node; Gtk::TreeModelColumn<Glib::ustring> glyph_name; Gtk::TreeModelColumn<Glib::ustring> unicode; Gtk::TreeModelColumn<double> advance; @@ -216,18 +221,18 @@ private: class KerningPairColumns : public Gtk::TreeModel::ColumnRecord { public: - KerningPairColumns() - { - add(first_glyph); - add(second_glyph); - add(kerning_value); - add(spnode); - } - - Gtk::TreeModelColumn<Glib::ustring> first_glyph; - Gtk::TreeModelColumn<Glib::ustring> second_glyph; - Gtk::TreeModelColumn<double> kerning_value; - Gtk::TreeModelColumn<SPGlyphKerning*> spnode; + KerningPairColumns() + { + add(first_glyph); + add(second_glyph); + add(kerning_value); + add(spnode); + } + + Gtk::TreeModelColumn<Glib::ustring> first_glyph; + Gtk::TreeModelColumn<Glib::ustring> second_glyph; + Gtk::TreeModelColumn<double> kerning_value; + Gtk::TreeModelColumn<SPGlyphKerning *> spnode; }; KerningPairColumns _KerningPairsListColumns; Glib::RefPtr<Gtk::ListStore> _KerningPairsListStore; @@ -247,21 +252,20 @@ private: SvgFontDrawingArea _font_da, kerning_preview; GlyphComboBox first_glyph, second_glyph; - SPGlyphKerning* kerning_pair; + SPGlyphKerning *kerning_pair; Inkscape::UI::Widget::SpinButton setwidth_spin; - Gtk::Scale* kerning_slider; + Gtk::Scale *kerning_slider; class EntryWidget : public Gtk::HBox { public: EntryWidget() - { + { this->add(this->_label); this->add(this->_entry); - } - void set_label(const gchar* l){ - this->_label.set_text(l); } + void set_label(const gchar *l) { this->_label.set_text(l); } + private: Gtk::Label _label; Gtk::Entry _entry; diff --git a/src/ui/dialog/svg-preview.cpp b/src/ui/dialog/svg-preview.cpp index 0269933c1db7dcf00e33a44f99d282d01801659b..5eb9759d8f0ee6189c5c5b4a7486418b917378ba 100644 --- a/src/ui/dialog/svg-preview.cpp +++ b/src/ui/dialog/svg-preview.cpp @@ -18,13 +18,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <iostream> -#include <fstream> +#include "svg-preview.h" +#include <fstream> +#include <glib/gstdio.h> // GStatBuf #include <glibmm/i18n.h> -#include <glib/gstdio.h> // GStatBuf - -#include "svg-preview.h" +#include <iostream> #include "document.h" #include "ui/view/svg-view-widget.h" @@ -56,7 +55,6 @@ bool SVGPreview::setDocument(SPDocument *doc) return true; } - bool SVGPreview::setFileName(Glib::ustring &theFileName) { Glib::ustring fileName = theFileName; @@ -78,8 +76,6 @@ bool SVGPreview::setFileName(Glib::ustring &theFileName) return true; } - - bool SVGPreview::setFromMem(char const *xmlBuffer) { if (!xmlBuffer) @@ -97,8 +93,6 @@ bool SVGPreview::setFromMem(char const *xmlBuffer) return true; } - - void SVGPreview::showImage(Glib::ustring &theFileName) { Glib::ustring fileName = theFileName; @@ -123,44 +117,35 @@ void SVGPreview::showImage(Glib::ustring &theFileName) // Get some image info. Smart pointer does not need to be deleted Glib::RefPtr<Gdk::Pixbuf> img(nullptr); - try - { + try { img = Gdk::Pixbuf::create_from_file(fileName); - } - catch (const Glib::FileError &e) - { + } catch (const Glib::FileError &e) { g_message("caught Glib::FileError in SVGPreview::showImage"); return; - } - catch (const Gdk::PixbufError &e) - { + } catch (const Gdk::PixbufError &e) { g_message("Gdk::PixbufError in SVGPreview::showImage"); return; - } - catch (...) - { + } catch (...) { g_message("Caught ... in SVGPreview::showImage"); return; } gint imgWidth = img->get_width(); gint imgHeight = img->get_height(); - + Glib::ustring svg = ".svg"; if (hasSuffix(fileName, svg)) { std::ifstream input(theFileName.c_str()); - if( !input ) { + if (!input) { std::cerr << "SVGPreview::showImage: Failed to open file: " << theFileName << std::endl; } else { - Glib::ustring token; Glib::MatchInfo match_info; Glib::RefPtr<Glib::Regex> regex1 = Glib::Regex::create("width=\"(.*)\""); Glib::RefPtr<Glib::Regex> regex2 = Glib::Regex::create("height=\"(.*)\""); - - while( !input.eof() && (height.empty() || width.empty()) ) { + while (!input.eof() && (height.empty() || width.empty())) { input >> token; // std::cout << "|" << token << "|" << std::endl; @@ -171,11 +156,10 @@ void SVGPreview::showImage(Glib::ustring &theFileName) if (regex2->match(token, match_info)) { height = match_info.fetch(1).raw(); } - } } } - + // TODO: replace int to string conversion with std::to_string when fully C++11 compliant if (height.empty() || width.empty()) { std::ostringstream s_width; @@ -228,7 +212,7 @@ void SVGPreview::showImage(Glib::ustring &theFileName) /* FIXME: Do proper XML quoting for fileName. */ gchar *xmlBuffer = g_strdup_printf(xformat, previewWidth, previewHeight, imgX, imgY, scaledImgWidth, scaledImgHeight, - encodedName.c_str(), rectX, rectY, rectWidth, rectHeight, width.c_str(), height.c_str() ); + encodedName.c_str(), rectX, rectY, rectWidth, rectHeight, width.c_str(), height.c_str()); // g_message("%s\n", xmlBuffer); @@ -237,8 +221,6 @@ void SVGPreview::showImage(Glib::ustring &theFileName) g_free(xmlBuffer); } - - void SVGPreview::showNoPreview() { // Are we already showing it? @@ -313,7 +295,6 @@ void SVGPreview::showNoPreview() showingNoPreview = true; } - /** * Inform the user that the svg file is too large to be displayed. * This does not check for sizes of embedded images (yet) @@ -379,13 +360,11 @@ void SVGPreview::showTooLarge(long fileLength) </svg> )C"; - // Fill in the template double floatFileLength = ((double)fileLength) / 1048576.0; // printf("%ld %f\n", fileLength, floatFileLength); - gchar *xmlBuffer = - g_strdup_printf(xformat, floatFileLength, _("Too large for preview")); + gchar *xmlBuffer = g_strdup_printf(xformat, floatFileLength, _("Too large for preview")); // g_message("%s\n", xmlBuffer); @@ -396,7 +375,6 @@ void SVGPreview::showTooLarge(long fileLength) bool SVGPreview::set(Glib::ustring &fileName, int dialogType) { - if (!Glib::file_test(fileName, Glib::FILE_TEST_EXISTS)) { showNoPreview(); return false; @@ -409,8 +387,8 @@ 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 = const_cast<gchar *>( - fileNameUtf8.c_str()); // const-cast probably not necessary? (not necessary on Windows version of stat()) + gchar *fName = const_cast<gchar *>(fileNameUtf8.c_str()); // const-cast probably not necessary? (not necessary + // on Windows version of stat()) GStatBuf info; if (g_stat(fName, &info)) // stat returns 0 upon success { @@ -442,7 +420,6 @@ bool SVGPreview::set(Glib::ustring &fileName, int dialogType) } } - SVGPreview::SVGPreview() : document(nullptr) , viewer(nullptr) @@ -455,8 +432,8 @@ SVGPreview::~SVGPreview() { if (viewer) { viewer->setDocument(nullptr); - } - delete document; + } + delete document; } } // namespace Dialog @@ -473,4 +450,3 @@ SVGPreview::~SVGPreview() End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - diff --git a/src/ui/dialog/svg-preview.h b/src/ui/dialog/svg-preview.h index 8263e152941305b28c305f37f1f7afa3dc7473ea..e7af46c86f51be4b2744ddef47f84661660dbdc7 100644 --- a/src/ui/dialog/svg-preview.h +++ b/src/ui/dialog/svg-preview.h @@ -18,28 +18,27 @@ #ifndef __SVG_PREVIEW_H__ #define __SVG_PREVIEW_H__ -//Gtk includes +// Gtk includes #include <gtkmm.h> -//General includes -#include <unistd.h> -#include <sys/stat.h> +// General includes #include <cerrno> +#include <sys/stat.h> +#include <unistd.h> #include "filedialog.h" - namespace Gtk { class Expander; } namespace Inkscape { - class URI; +class URI; namespace UI { namespace View { - class SVGViewWidget; +class SVGViewWidget; } namespace Dialog { @@ -56,7 +55,6 @@ namespace Dialog { class SVGPreview : public Gtk::VBox { public: - SVGPreview(); ~SVGPreview() override; @@ -101,10 +99,8 @@ private: * are we currently showing the "no preview" image? */ bool showingNoPreview; - }; - } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/swatches.cpp b/src/ui/dialog/swatches.cpp index e5a97c5d91709ce465dc8e19b96b99c91b814cad..c8377984c11e538cf1c728e74ba10c8843dd8fd7 100644 --- a/src/ui/dialog/swatches.cpp +++ b/src/ui/dialog/swatches.cpp @@ -10,58 +10,51 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <map> -#include <algorithm> -#include <iomanip> -#include <set> - #include "swatches.h" -#include <gtkmm/radiomenuitem.h> - -#include <gtkmm/menu.h> -#include <gtkmm/checkmenuitem.h> -#include <gtkmm/radiomenuitem.h> -#include <gtkmm/separatormenuitem.h> -#include <gtkmm/menubutton.h> +#include <algorithm> +#include <glibmm/fileutils.h> #include <glibmm/i18n.h> #include <glibmm/main.h> -#include <glibmm/timer.h> -#include <glibmm/fileutils.h> #include <glibmm/miscutils.h> +#include <glibmm/timer.h> +#include <gtkmm/checkmenuitem.h> +#include <gtkmm/menu.h> +#include <gtkmm/menubutton.h> +#include <gtkmm/radiomenuitem.h> +#include <gtkmm/separatormenuitem.h> +#include <iomanip> +#include <map> +#include <set> #include "color-item.h" -#include "desktop.h" - #include "desktop-style.h" -#include "document.h" +#include "desktop.h" +#include "dialog-manager.h" +#include "display/cairo-utils.h" #include "document-undo.h" +#include "document.h" #include "extension/db.h" +#include "gradient-chemistry.h" +#include "helper/action.h" #include "inkscape.h" -#include "io/sys.h" #include "io/resource.h" +#include "io/sys.h" #include "message-context.h" +#include "object/sp-defs.h" +#include "object/sp-gradient-reference.h" #include "path-prefix.h" - #include "ui/previewholder.h" -#include "widgets/desktop-widget.h" #include "ui/widget/gradient-vector-selector.h" -#include "display/cairo-utils.h" - -#include "object/sp-defs.h" -#include "object/sp-gradient-reference.h" - -#include "dialog-manager.h" #include "verbs.h" -#include "gradient-chemistry.h" -#include "helper/action.h" +#include "widgets/desktop-widget.h" namespace Inkscape { namespace UI { namespace Dialog { - -enum { +enum +{ SWATCHES_SETTINGS_SIZE = 0, SWATCHES_SETTINGS_MODE = 1, SWATCHES_SETTINGS_SHAPE = 2, @@ -73,76 +66,77 @@ enum { #define VBLOCK 16 #define PREVIEW_PIXBUF_WIDTH 128 -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; - +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; class SwatchesPanelHook : public SwatchesPanel { public: - static void convertGradient( GtkMenuItem *menuitem, gpointer userData ); - static void deleteGradient( GtkMenuItem *menuitem, gpointer userData ); + static void convertGradient(GtkMenuItem *menuitem, gpointer userData); + static void deleteGradient(GtkMenuItem *menuitem, gpointer userData); }; -static void handleClick( GtkWidget* /*widget*/, gpointer callback_data ) { - ColorItem* item = reinterpret_cast<ColorItem*>(callback_data); - if ( item ) { +static void handleClick(GtkWidget * /*widget*/, gpointer callback_data) +{ + ColorItem *item = reinterpret_cast<ColorItem *>(callback_data); + if (item) { item->buttonClicked(false); } } -static void handleSecondaryClick( GtkWidget* /*widget*/, gint /*arg1*/, gpointer callback_data ) { - ColorItem* item = reinterpret_cast<ColorItem*>(callback_data); - if ( item ) { +static void handleSecondaryClick(GtkWidget * /*widget*/, gint /*arg1*/, gpointer callback_data) +{ + ColorItem *item = reinterpret_cast<ColorItem *>(callback_data); + if (item) { item->buttonClicked(true); } } -static GtkWidget* popupMenu = nullptr; +static GtkWidget *popupMenu = nullptr; static GtkWidget *popupSubHolder = nullptr; static GtkWidget *popupSub = nullptr; static std::vector<Glib::ustring> popupItems; -static std::vector<GtkWidget*> popupExtras; -static ColorItem* bounceTarget = nullptr; -static SwatchesPanel* bouncePanel = nullptr; +static std::vector<GtkWidget *> popupExtras; +static ColorItem *bounceTarget = nullptr; +static SwatchesPanel *bouncePanel = nullptr; -static void redirClick( GtkMenuItem *menuitem, gpointer /*user_data*/ ) +static void redirClick(GtkMenuItem *menuitem, gpointer /*user_data*/) { - if ( bounceTarget ) { - handleClick( GTK_WIDGET(menuitem), bounceTarget ); + if (bounceTarget) { + handleClick(GTK_WIDGET(menuitem), bounceTarget); } } -static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer /*user_data*/ ) +static void redirSecondaryClick(GtkMenuItem *menuitem, gpointer /*user_data*/) { - if ( bounceTarget ) { - handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget ); + if (bounceTarget) { + handleSecondaryClick(GTK_WIDGET(menuitem), 0, bounceTarget); } } -static void editGradientImpl( SPDesktop* desktop, SPGradient* gr ) +static void editGradientImpl(SPDesktop *desktop, SPGradient *gr) { g_assert(desktop != nullptr); g_assert(desktop->doc() != nullptr); - if ( gr ) { + if (gr) { bool shown = false; { Inkscape::Selection *selection = desktop->getSelection(); - std::vector<SPItem*> const items(selection->items().begin(), selection->items().end()); + std::vector<SPItem *> const items(selection->items().begin(), selection->items().end()); if (!items.empty()) { - SPStyle query( desktop->doc() ); + SPStyle query(desktop->doc()); int result = objects_query_fillstroke((items), &query, true); - if ( (result == QUERY_STYLE_MULTIPLE_SAME) || (result == QUERY_STYLE_SINGLE) ) { + if ((result == QUERY_STYLE_MULTIPLE_SAME) || (result == QUERY_STYLE_SINGLE)) { // could be pertinent if (query.fill.isPaintserver()) { - SPPaintServer* server = query.getFillPaintServer(); - if ( SP_IS_GRADIENT(server) ) { - SPGradient* grad = SP_GRADIENT(server); - if ( grad->isSwatch() && grad->getId() == gr->getId()) { + SPPaintServer *server = query.getFillPaintServer(); + if (SP_IS_GRADIENT(server)) { + SPGradient *grad = SP_GRADIENT(server); + if (grad->isSwatch() && grad->getId() == gr->getId()) { desktop->_dlg_mgr->showDialog("FillAndStroke"); shown = true; } @@ -165,19 +159,19 @@ static void editGradientImpl( SPDesktop* desktop, SPGradient* gr ) } } -static void editGradient( GtkMenuItem */*menuitem*/, gpointer /*user_data*/ ) +static void editGradient(GtkMenuItem * /*menuitem*/, gpointer /*user_data*/) { - if ( bounceTarget ) { - SwatchesPanel* swp = bouncePanel; - SPDesktop* desktop = swp ? swp->getDesktop() : nullptr; + if (bounceTarget) { + SwatchesPanel *swp = bouncePanel; + SPDesktop *desktop = swp ? swp->getDesktop() : nullptr; SPDocument *doc = desktop ? desktop->doc() : nullptr; if (doc) { std::string targetName(bounceTarget->def.descr); std::vector<SPObject *> gradients = doc->getResourceList("gradient"); for (auto gradient : gradients) { - SPGradient* grad = SP_GRADIENT(gradient); - if ( targetName == grad->getId() ) { - editGradientImpl( desktop, grad ); + SPGradient *grad = SP_GRADIENT(gradient); + if (targetName == grad->getId()) { + editGradientImpl(desktop, grad); break; } } @@ -185,23 +179,22 @@ static void editGradient( GtkMenuItem */*menuitem*/, gpointer /*user_data*/ ) } } -void SwatchesPanelHook::convertGradient( GtkMenuItem * /*menuitem*/, gpointer userData ) +void SwatchesPanelHook::convertGradient(GtkMenuItem * /*menuitem*/, gpointer userData) { - if ( bounceTarget ) { - SwatchesPanel* swp = bouncePanel; - SPDesktop* desktop = swp ? swp->getDesktop() : nullptr; + if (bounceTarget) { + SwatchesPanel *swp = bouncePanel; + SPDesktop *desktop = swp ? swp->getDesktop() : nullptr; SPDocument *doc = desktop ? desktop->doc() : nullptr; gint index = GPOINTER_TO_INT(userData); - if ( doc && (index >= 0) && (static_cast<guint>(index) < popupItems.size()) ) { + if (doc && (index >= 0) && (static_cast<guint>(index) < popupItems.size())) { Glib::ustring targetName = popupItems[index]; std::vector<SPObject *> gradients = doc->getResourceList("gradient"); for (auto gradient : gradients) { - SPGradient* grad = SP_GRADIENT(gradient); + SPGradient *grad = SP_GRADIENT(gradient); - if ( targetName == grad->getId() ) { + if (targetName == grad->getId()) { grad->setSwatch(); - DocumentUndo::done(doc, SP_VERB_CONTEXT_GRADIENT, - _("Add gradient stop")); + DocumentUndo::done(doc, SP_VERB_CONTEXT_GRADIENT, _("Add gradient stop")); break; } } @@ -209,25 +202,25 @@ void SwatchesPanelHook::convertGradient( GtkMenuItem * /*menuitem*/, gpointer us } } -void SwatchesPanelHook::deleteGradient( GtkMenuItem */*menuitem*/, gpointer /*userData*/ ) +void SwatchesPanelHook::deleteGradient(GtkMenuItem * /*menuitem*/, gpointer /*userData*/) { - if ( bounceTarget ) { - SwatchesPanel* swp = bouncePanel; - SPDesktop* desktop = swp ? swp->getDesktop() : nullptr; + if (bounceTarget) { + SwatchesPanel *swp = bouncePanel; + SPDesktop *desktop = swp ? swp->getDesktop() : nullptr; sp_gradient_unset_swatch(desktop, bounceTarget->def.descr); } } -static SwatchesPanel* findContainingPanel( GtkWidget *widget ) +static SwatchesPanel *findContainingPanel(GtkWidget *widget) { SwatchesPanel *swp = nullptr; - std::map<GtkWidget*, SwatchesPanel*> rawObjects; - for (std::map<SwatchesPanel*, SPDocument*>::iterator it = docPerPanel.begin(); it != docPerPanel.end(); ++it) { + std::map<GtkWidget *, SwatchesPanel *> rawObjects; + for (std::map<SwatchesPanel *, SPDocument *>::iterator it = docPerPanel.begin(); it != docPerPanel.end(); ++it) { rawObjects[GTK_WIDGET(it->first->gobj())] = it->first; } - for (GtkWidget* curr = widget; curr && !swp; curr = gtk_widget_get_parent(curr)) { + for (GtkWidget *curr = widget; curr && !swp; curr = gtk_widget_get_parent(curr)) { if (rawObjects.find(curr) != rawObjects.end()) { swp = rawObjects[curr]; } @@ -236,38 +229,32 @@ static SwatchesPanel* findContainingPanel( GtkWidget *widget ) return swp; } -static void removeit( GtkWidget *widget, gpointer data ) +static void removeit(GtkWidget *widget, gpointer data) { - gtk_container_remove( GTK_CONTAINER(data), widget ); + gtk_container_remove(GTK_CONTAINER(data), widget); } /* extern'ed from color-item.cpp */ -bool colorItemHandleButtonPress(GdkEventButton* event, UI::Widget::Preview *preview, gpointer user_data) +bool colorItemHandleButtonPress(GdkEventButton *event, UI::Widget::Preview *preview, gpointer user_data) { gboolean handled = FALSE; - if ( event && (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) { - SwatchesPanel* swp = findContainingPanel( GTK_WIDGET(preview->gobj()) ); + if (event && (event->button == 3) && (event->type == GDK_BUTTON_PRESS)) { + SwatchesPanel *swp = findContainingPanel(GTK_WIDGET(preview->gobj())); - if ( !popupMenu ) { + if (!popupMenu) { popupMenu = gtk_menu_new(); - GtkWidget* child = nullptr; + GtkWidget *child = nullptr; - //TRANSLATORS: An item in context menu on a colour in the swatches + // TRANSLATORS: An item in context menu on a colour in the swatches child = gtk_menu_item_new_with_label(_("Set fill")); - g_signal_connect( G_OBJECT(child), - "activate", - G_CALLBACK(redirClick), - user_data); + g_signal_connect(G_OBJECT(child), "activate", G_CALLBACK(redirClick), user_data); gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child); - //TRANSLATORS: An item in context menu on a colour in the swatches + // TRANSLATORS: An item in context menu on a colour in the swatches child = gtk_menu_item_new_with_label(_("Set stroke")); - g_signal_connect( G_OBJECT(child), - "activate", - G_CALLBACK(redirSecondaryClick), - user_data); + g_signal_connect(G_OBJECT(child), "activate", G_CALLBACK(redirSecondaryClick), user_data); gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child); child = gtk_separator_menu_item_new(); @@ -275,19 +262,13 @@ bool colorItemHandleButtonPress(GdkEventButton* event, UI::Widget::Preview *prev popupExtras.push_back(child); child = gtk_menu_item_new_with_label(_("Delete")); - g_signal_connect( G_OBJECT(child), - "activate", - G_CALLBACK(SwatchesPanelHook::deleteGradient), - user_data ); + g_signal_connect(G_OBJECT(child), "activate", G_CALLBACK(SwatchesPanelHook::deleteGradient), user_data); gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child); popupExtras.push_back(child); - gtk_widget_set_sensitive( child, FALSE ); + gtk_widget_set_sensitive(child, FALSE); child = gtk_menu_item_new_with_label(_("Edit...")); - g_signal_connect( G_OBJECT(child), - "activate", - G_CALLBACK(editGradient), - user_data ); + g_signal_connect(G_OBJECT(child), "activate", G_CALLBACK(editGradient), user_data); gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child); popupExtras.push_back(child); @@ -297,50 +278,49 @@ bool colorItemHandleButtonPress(GdkEventButton* event, UI::Widget::Preview *prev child = gtk_menu_item_new_with_label(_("Convert")); gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child); - //popupExtras.push_back(child); - //gtk_widget_set_sensitive( child, FALSE ); + // popupExtras.push_back(child); + // gtk_widget_set_sensitive( child, FALSE ); { popupSubHolder = child; popupSub = gtk_menu_new(); - gtk_menu_item_set_submenu( GTK_MENU_ITEM(child), popupSub ); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(child), popupSub); } gtk_widget_show_all(popupMenu); } - if ( user_data ) { - ColorItem* item = reinterpret_cast<ColorItem*>(user_data); + if (user_data) { + ColorItem *item = reinterpret_cast<ColorItem *>(user_data); bool show = swp && (swp->getSelectedIndex() == 0); - for (auto & popupExtra : popupExtras) { + for (auto &popupExtra : popupExtras) { gtk_widget_set_sensitive(popupExtra, show); } bounceTarget = item; bouncePanel = swp; popupItems.clear(); - if ( popupMenu ) { + if (popupMenu) { gtk_container_foreach(GTK_CONTAINER(popupSub), removeit, popupSub); bool processed = false; auto *wdgt = preview->get_ancestor(SPDesktopWidget::get_type()); - if ( wdgt ) { + if (wdgt) { SPDesktopWidget *dtw = SP_DESKTOP_WIDGET(wdgt); - if ( dtw && dtw->desktop ) { + if (dtw && dtw->desktop) { // Pick up all gradients with vectors std::vector<SPObject *> gradients = (dtw->desktop->doc())->getResourceList("gradient"); gint index = 0; for (auto gradient : gradients) { - SPGradient* grad = SP_GRADIENT(gradient); - if ( grad->hasStops() && !grad->isSwatch() ) { - //gl = g_slist_prepend(gl, curr->data); + SPGradient *grad = SP_GRADIENT(gradient); + if (grad->hasStops() && !grad->isSwatch()) { + // gl = g_slist_prepend(gl, curr->data); processed = true; GtkWidget *child = gtk_menu_item_new_with_label(grad->getId()); gtk_menu_shell_append(GTK_MENU_SHELL(popupSub), child); popupItems.emplace_back(grad->getId()); - g_signal_connect( G_OBJECT(child), - "activate", - G_CALLBACK(SwatchesPanelHook::convertGradient), - GINT_TO_POINTER(index) ); + g_signal_connect(G_OBJECT(child), "activate", + G_CALLBACK(SwatchesPanelHook::convertGradient), + GINT_TO_POINTER(index)); index++; } } @@ -348,7 +328,7 @@ bool colorItemHandleButtonPress(GdkEventButton* event, UI::Widget::Preview *prev gtk_widget_show_all(popupSub); } } - gtk_widget_set_sensitive( popupSubHolder, processed ); + gtk_widget_set_sensitive(popupSubHolder, processed); gtk_menu_popup_at_pointer(GTK_MENU(popupMenu), reinterpret_cast<GdkEvent *>(event)); handled = TRUE; } @@ -358,32 +338,34 @@ bool colorItemHandleButtonPress(GdkEventButton* event, UI::Widget::Preview *prev return handled; } - -static char* trim( char* str ) { - char* ret = str; - while ( *str && (*str == ' ' || *str == '\t') ) { +static char *trim(char *str) +{ + char *ret = str; + while (*str && (*str == ' ' || *str == '\t')) { str++; } ret = str; - while ( *str ) { + while (*str) { str++; } str--; - while ( str >= ret && (( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n') ) { + while (str >= ret && ((*str == ' ' || *str == '\t') || *str == '\r' || *str == '\n')) { *str-- = 0; } return ret; } -static void skipWhitespace( char*& str ) { - while ( *str == ' ' || *str == '\t' ) { +static void skipWhitespace(char *&str) +{ + while (*str == ' ' || *str == '\t') { str++; } } -static bool parseNum( char*& str, int& val ) { +static bool parseNum(char *&str, int &val) +{ val = 0; - while ( '0' <= *str && *str <= '9' ) { + while ('0' <= *str && *str <= '9') { val = val * 10 + (*str - '0'); str++; } @@ -391,17 +373,15 @@ static bool parseNum( char*& str, int& val ) { return retval; } - -static -void _loadPaletteFile(Glib::ustring path, gboolean user/*=FALSE*/) +static void _loadPaletteFile(Glib::ustring path, gboolean user /*=FALSE*/) { auto filename = Glib::path_get_basename(path.raw()); char block[1024]; FILE *f = Inkscape::IO::fopen_utf8name(path.c_str(), "r"); - if ( f ) { - char* result = fgets( block, sizeof(block), f ); - if ( result ) { - if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) { + if (f) { + char *result = fgets(block, sizeof(block), f); + if (result) { + if (strncmp("GIMP Palette", block, 12) == 0) { bool inHeader = true; bool hasErr = false; @@ -409,82 +389,82 @@ void _loadPaletteFile(Glib::ustring path, gboolean user/*=FALSE*/) onceMore->_name = filename.c_str(); do { - result = fgets( block, sizeof(block), f ); + result = fgets(block, sizeof(block), f); block[sizeof(block) - 1] = 0; - if ( result ) { - if ( block[0] == '#' ) { + if (result) { + if (block[0] == '#') { // ignore comment } else { char *ptr = block; // very simple check for header versus entry - while ( *ptr == ' ' || *ptr == '\t' ) { + while (*ptr == ' ' || *ptr == '\t') { ptr++; } - if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) { + if ((*ptr == 0) || (*ptr == '\r') || (*ptr == '\n')) { // blank line. skip it. - } else if ( '0' <= *ptr && *ptr <= '9' ) { + } else if ('0' <= *ptr && *ptr <= '9') { // should be an entry link inHeader = false; ptr = block; Glib::ustring name(""); skipWhitespace(ptr); - if ( *ptr ) { + if (*ptr) { int r = 0; int g = 0; int b = 0; hasErr = parseNum(ptr, r); - if ( !hasErr ) { + if (!hasErr) { skipWhitespace(ptr); hasErr = parseNum(ptr, g); } - if ( !hasErr ) { + if (!hasErr) { skipWhitespace(ptr); hasErr = parseNum(ptr, b); } - if ( !hasErr && *ptr ) { - char* n = trim(ptr); + if (!hasErr && *ptr) { + char *n = trim(ptr); if (n != nullptr && *n) { name = g_dpgettext2(nullptr, "Palette", n); } if (name == "") { name = Glib::ustring::compose("#%1%2%3", - Glib::ustring::format(std::hex, std::setw(2), std::setfill(L'0'), r), - Glib::ustring::format(std::hex, std::setw(2), std::setfill(L'0'), g), - Glib::ustring::format(std::hex, std::setw(2), std::setfill(L'0'), b) - ).uppercase(); - } + Glib::ustring::format(std::hex, std::setw(2), + std::setfill(L'0'), r), + Glib::ustring::format(std::hex, std::setw(2), + std::setfill(L'0'), g), + Glib::ustring::format(std::hex, std::setw(2), + std::setfill(L'0'), b)) + .uppercase(); + } } - if ( !hasErr ) { + if (!hasErr) { // Add the entry now Glib::ustring nameStr(name); - ColorItem* item = new ColorItem( r, g, b, nameStr ); + ColorItem *item = new ColorItem(r, g, b, nameStr); onceMore->_colors.push_back(item); } } else { hasErr = true; } } else { - if ( !inHeader ) { + if (!inHeader) { // Hmmm... probably bad. Not quite the format we want? hasErr = true; } else { - char* sep = strchr(result, ':'); - if ( sep ) { + char *sep = strchr(result, ':'); + if (sep) { *sep = 0; - char* val = trim(sep + 1); - char* name = trim(result); - if ( *name ) { - if ( strcmp( "Name", name ) == 0 ) - { + char *val = trim(sep + 1); + char *name = trim(result); + if (*name) { + if (strcmp("Name", name) == 0) { onceMore->_name = val; - } - else if ( strcmp( "Columns", name ) == 0 ) - { - gchar* endPtr = nullptr; - guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 ); - if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) { + } else if (strcmp("Columns", name) == 0) { + gchar *endPtr = nullptr; + guint64 numVal = g_ascii_strtoull(val, &endPtr, 10); + if ((numVal == G_MAXUINT64) && (ERANGE == errno)) { // overflow - } else if ( (numVal == 0) && (endPtr == val) ) { + } else if ((numVal == 0) && (endPtr == val)) { // failed conversion } else { onceMore->_prefWidth = numVal; @@ -502,8 +482,8 @@ void _loadPaletteFile(Glib::ustring path, gboolean user/*=FALSE*/) } } } - } while ( result && !hasErr ); - if ( !hasErr ) { + } while (result && !hasErr); + if (!hasErr) { if (user) userSwatchPages.push_back(onceMore); else @@ -518,9 +498,8 @@ void _loadPaletteFile(Glib::ustring path, gboolean user/*=FALSE*/) } } -static bool -compare_swatch_names(SwatchPage const *a, SwatchPage const *b) { - +static bool compare_swatch_names(SwatchPage const *a, SwatchPage const *b) +{ return g_utf8_collate(a->_name.c_str(), b->_name.c_str()) < 0; } @@ -533,7 +512,7 @@ static void load_palettes() } init_done = true; - for (auto &filename: Inkscape::IO::Resource::get_filenames(Inkscape::IO::Resource::PALETTES, {".gpl"})) { + for (auto &filename : Inkscape::IO::Resource::get_filenames(Inkscape::IO::Resource::PALETTES, {".gpl"})) { bool userPalette = Inkscape::IO::file_is_writable(filename.c_str()); _loadPaletteFile(filename, userPalette); } @@ -543,24 +522,23 @@ static void load_palettes() systemSwatchPages.sort(compare_swatch_names); } -SwatchesPanel& SwatchesPanel::getInstance() +SwatchesPanel &SwatchesPanel::getInstance() { return *new SwatchesPanel(); } - /** * Constructor */ -SwatchesPanel::SwatchesPanel(gchar const* prefsPath) : - Inkscape::UI::Widget::Panel(prefsPath, SP_VERB_DIALOG_SWATCHES), - _menu(nullptr), - _holder(nullptr), - _clear(nullptr), - _remove(nullptr), - _currentIndex(0), - _currentDesktop(nullptr), - _currentDocument(nullptr) +SwatchesPanel::SwatchesPanel(gchar const *prefsPath) + : Inkscape::UI::Widget::Panel(prefsPath, SP_VERB_DIALOG_SWATCHES) + , _menu(nullptr) + , _holder(nullptr) + , _clear(nullptr) + , _remove(nullptr) + , _currentIndex(0) + , _currentDesktop(nullptr) + , _currentDocument(nullptr) { _holder = new PreviewHolder(); @@ -589,9 +567,9 @@ SwatchesPanel::SwatchesPanel(gchar const* prefsPath) : load_palettes(); - Gtk::RadioMenuItem* hotItem = nullptr; - _clear = new ColorItem( ege::PaintDef::CLEAR ); - _remove = new ColorItem( ege::PaintDef::NONE ); + Gtk::RadioMenuItem *hotItem = nullptr; + _clear = new ColorItem(ege::PaintDef::CLEAR); + _remove = new ColorItem(ege::PaintDef::NONE); if (docPalettes.empty()) { SwatchPage *docPalette = new SwatchPage(); @@ -600,20 +578,20 @@ SwatchesPanel::SwatchesPanel(gchar const* prefsPath) : docPalettes[nullptr] = docPalette; } - if ( !systemSwatchPages.empty() || !userSwatchPages.empty()) { - SwatchPage* first = nullptr; + if (!systemSwatchPages.empty() || !userSwatchPages.empty()) { + SwatchPage *first = nullptr; int index = 0; Glib::ustring targetName; - if ( !_prefs_path.empty() ) { + if (!_prefs_path.empty()) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); targetName = prefs->getString(_prefs_path + "/palette"); if (!targetName.empty()) { if (targetName == "Auto") { first = docPalettes[nullptr]; } else { - std::vector<SwatchPage*> pages = _getSwatchSets(); - for (auto & page : pages) { - if ( page->_name == targetName ) { + std::vector<SwatchPage *> pages = _getSwatchSets(); + for (auto &page : pages) { + if (page->_name == targetName) { first = page; break; } @@ -623,7 +601,7 @@ SwatchesPanel::SwatchesPanel(gchar const* prefsPath) : } } - if ( !first ) { + if (!first) { first = docPalettes[nullptr]; _currentIndex = 0; } else { @@ -635,10 +613,10 @@ SwatchesPanel::SwatchesPanel(gchar const* prefsPath) : Gtk::RadioMenuItem::Group groupOne; int i = 0; - std::vector<SwatchPage*> swatchSets = _getSwatchSets(); + std::vector<SwatchPage *> swatchSets = _getSwatchSets(); for (auto curr : swatchSets) { - Gtk::RadioMenuItem* single = Gtk::manage(new Gtk::RadioMenuItem(groupOne, curr->_name)); - if ( curr == first ) { + Gtk::RadioMenuItem *single = Gtk::manage(new Gtk::RadioMenuItem(groupOne, curr->_name)); + if (curr == first) { hotItem = single; } _regItem(single, i); @@ -647,7 +625,7 @@ SwatchesPanel::SwatchesPanel(gchar const* prefsPath) : } } - if ( hotItem ) { + if (hotItem) { hotItem->set_active(); } @@ -656,15 +634,15 @@ SwatchesPanel::SwatchesPanel(gchar const* prefsPath) : SwatchesPanel::~SwatchesPanel() { - _trackDocument( this, nullptr ); + _trackDocument(this, nullptr); - if ( _clear ) { + if (_clear) { delete _clear; } - if ( _remove ) { + if (_remove) { delete _remove; } - if ( _holder ) { + if (_holder) { delete _holder; } @@ -680,8 +658,8 @@ void SwatchesPanel::_build_menu() panel_wrap = prefs->getBool(_prefs_path + "/panel_wrap"); panel_size = prefs->getIntLimited(_prefs_path + "/panel_size", 1, 0, UI::Widget::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", UI::Widget::BORDER_NONE, 0, 2 ); + panel_ratio = prefs->getIntLimited(_prefs_path + "/panel_ratio", 100, 0, 500); + panel_border = prefs->getIntLimited(_prefs_path + "/panel_border", UI::Widget::BORDER_NONE, 0, 2); } _menu = new Gtk::Menu(); @@ -703,21 +681,19 @@ void SwatchesPanel::_build_menu() _menu->append(*grid_item); _menu->append(*Gtk::manage(new Gtk::SeparatorMenuItem())); - list_item->signal_activate().connect(sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), SWATCHES_SETTINGS_MODE, 0)); - grid_item->signal_activate().connect(sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), SWATCHES_SETTINGS_MODE, 1)); + list_item->signal_activate().connect( + sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), SWATCHES_SETTINGS_MODE, 0)); + grid_item->signal_activate().connect( + sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), SWATCHES_SETTINGS_MODE, 1)); } { Glib::ustring heightItemLabel(C_("Swatches", "Size")); - //TRANSLATORS: Indicates size of colour swatches - const gchar *heightLabels[] = { - NC_("Swatches height", "Tiny"), - NC_("Swatches height", "Small"), - NC_("Swatches height", "Medium"), - NC_("Swatches height", "Large"), - NC_("Swatches height", "Huge") - }; + // TRANSLATORS: Indicates size of colour swatches + const gchar *heightLabels[] = {NC_("Swatches height", "Tiny"), NC_("Swatches height", "Small"), + NC_("Swatches height", "Medium"), NC_("Swatches height", "Large"), + NC_("Swatches height", "Huge")}; Gtk::MenuItem *sizeItem = Gtk::manage(new Gtk::MenuItem(heightItemLabel)); Gtk::Menu *sizeMenu = Gtk::manage(new Gtk::Menu()); @@ -726,30 +702,27 @@ void SwatchesPanel::_build_menu() Gtk::RadioMenuItem::Group heightGroup; for (unsigned int i = 0; i < G_N_ELEMENTS(heightLabels); i++) { Glib::ustring _label(g_dpgettext2(nullptr, "Swatches height", heightLabels[i])); - Gtk::RadioMenuItem* _item = Gtk::manage(new Gtk::RadioMenuItem(heightGroup, _label)); + Gtk::RadioMenuItem *_item = Gtk::manage(new Gtk::RadioMenuItem(heightGroup, _label)); sizeMenu->append(*_item); if (i == panel_size) { _item->set_active(true); } - _item->signal_activate().connect(sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), SWATCHES_SETTINGS_SIZE, i)); - } + _item->signal_activate().connect( + sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), SWATCHES_SETTINGS_SIZE, i)); + } - _menu->append(*sizeItem); + _menu->append(*sizeItem); } { Glib::ustring widthItemLabel(C_("Swatches", "Width")); - //TRANSLATORS: Indicates width of colour swatches - const gchar *widthLabels[] = { - NC_("Swatches width", "Narrower"), - NC_("Swatches width", "Narrow"), - NC_("Swatches width", "Medium"), - NC_("Swatches width", "Wide"), - NC_("Swatches width", "Wider") - }; + // TRANSLATORS: Indicates width of colour swatches + const gchar *widthLabels[] = {NC_("Swatches width", "Narrower"), NC_("Swatches width", "Narrow"), + NC_("Swatches width", "Medium"), NC_("Swatches width", "Wide"), + NC_("Swatches width", "Wider")}; - Gtk::MenuItem *item = Gtk::manage( new Gtk::MenuItem(widthItemLabel)); + Gtk::MenuItem *item = Gtk::manage(new Gtk::MenuItem(widthItemLabel)); Gtk::Menu *type_menu = Gtk::manage(new Gtk::Menu()); item->set_submenu(*type_menu); _menu->append(*item); @@ -758,34 +731,35 @@ void SwatchesPanel::_build_menu() guint values[] = {0, 25, 50, 100, 200, 400}; guint hot_index = 3; - for ( guint i = 0; i < G_N_ELEMENTS(widthLabels); ++i ) { + for (guint i = 0; i < G_N_ELEMENTS(widthLabels); ++i) { // Assume all values are in increasing order - if ( values[i] <= panel_ratio ) { + if (values[i] <= panel_ratio) { hot_index = i; } } - for ( guint i = 0; i < G_N_ELEMENTS(widthLabels); ++i ) { + for (guint i = 0; i < G_N_ELEMENTS(widthLabels); ++i) { Glib::ustring _label(g_dpgettext2(nullptr, "Swatches width", widthLabels[i])); Gtk::RadioMenuItem *_item = Gtk::manage(new Gtk::RadioMenuItem(widthGroup, _label)); type_menu->append(*_item); - if ( i <= hot_index ) { + if (i <= hot_index) { _item->set_active(true); } - _item->signal_activate().connect(sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), SWATCHES_SETTINGS_SHAPE, values[i])); + _item->signal_activate().connect(sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), + SWATCHES_SETTINGS_SHAPE, values[i])); } } { Glib::ustring widthItemLabel(C_("Swatches", "Border")); - //TRANSLATORS: Indicates border of colour swatches + // TRANSLATORS: Indicates border of colour swatches const gchar *widthLabels[] = { NC_("Swatches border", "None"), NC_("Swatches border", "Solid"), NC_("Swatches border", "Wide"), }; - Gtk::MenuItem *item = Gtk::manage( new Gtk::MenuItem(widthItemLabel)); + Gtk::MenuItem *item = Gtk::manage(new Gtk::MenuItem(widthItemLabel)); Gtk::Menu *type_menu = Gtk::manage(new Gtk::Menu()); item->set_submenu(*type_menu); _menu->append(*item); @@ -794,31 +768,33 @@ void SwatchesPanel::_build_menu() guint values[] = {0, 1, 2}; guint hot_index = 0; - for ( guint i = 0; i < G_N_ELEMENTS(widthLabels); ++i ) { + for (guint i = 0; i < G_N_ELEMENTS(widthLabels); ++i) { // Assume all values are in increasing order - if ( values[i] <= panel_border ) { + if (values[i] <= panel_border) { hot_index = i; } } - for ( guint i = 0; i < G_N_ELEMENTS(widthLabels); ++i ) { + for (guint i = 0; i < G_N_ELEMENTS(widthLabels); ++i) { Glib::ustring _label(g_dpgettext2(nullptr, "Swatches border", widthLabels[i])); Gtk::RadioMenuItem *_item = Gtk::manage(new Gtk::RadioMenuItem(widthGroup, _label)); type_menu->append(*_item); - if ( i <= hot_index ) { + if (i <= hot_index) { _item->set_active(true); } - _item->signal_activate().connect(sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), SWATCHES_SETTINGS_BORDER, values[i])); + _item->signal_activate().connect(sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), + SWATCHES_SETTINGS_BORDER, values[i])); } } if (_prefs_path == "/embedded/swatches") { - //TRANSLATORS: "Wrap" indicates how colour swatches are displayed - Glib::ustring wrap_label(C_("Swatches","Wrap")); + // TRANSLATORS: "Wrap" indicates how colour swatches are displayed + Glib::ustring wrap_label(C_("Swatches", "Wrap")); Gtk::CheckMenuItem *check = Gtk::manage(new Gtk::CheckMenuItem(wrap_label)); check->set_active(panel_wrap); _menu->append(*check); - check->signal_toggled().connect(sigc::bind<Gtk::CheckMenuItem*>(sigc::mem_fun(*this, &SwatchesPanel::_wrapToggled), check)); + check->signal_toggled().connect( + sigc::bind<Gtk::CheckMenuItem *>(sigc::mem_fun(*this, &SwatchesPanel::_wrapToggled), check)); } _menu->append(*Gtk::manage(new Gtk::SeparatorMenuItem())); @@ -832,10 +808,10 @@ void SwatchesPanel::_build_menu() _updateSettings(SWATCHES_SETTINGS_BORDER, panel_border); } -void SwatchesPanel::setDesktop( SPDesktop* desktop ) +void SwatchesPanel::setDesktop(SPDesktop *desktop) { - if ( desktop != _currentDesktop ) { - if ( _currentDesktop ) { + if (desktop != _currentDesktop) { + if (_currentDesktop) { for (auto &conn : _desktopConnections) { conn.disconnect(); } @@ -843,7 +819,7 @@ void SwatchesPanel::setDesktop( SPDesktop* desktop ) _currentDesktop = desktop; - if ( desktop ) { + if (desktop) { _desktopConnections.emplace_back(desktop->selection->connectChanged( // [this](Inkscape::Selection *) { this->_updateFromSelection(); })); @@ -863,140 +839,140 @@ void SwatchesPanel::setDesktop( SPDesktop* desktop ) } } - void SwatchesPanel::_updateSettings(int settings, int value) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); switch (settings) { - case SWATCHES_SETTINGS_SIZE: { - prefs->setInt(_prefs_path + "/panel_size", value); + case SWATCHES_SETTINGS_SIZE: { + prefs->setInt(_prefs_path + "/panel_size", value); - auto curr_type = _holder->getPreviewType(); - guint curr_ratio = _holder->getPreviewRatio(); - auto curr_border = _holder->getPreviewBorder(); + auto curr_type = _holder->getPreviewType(); + guint curr_ratio = _holder->getPreviewRatio(); + auto curr_border = _holder->getPreviewBorder(); - switch (value) { - case 0: - _holder->setStyle(UI::Widget::PREVIEW_SIZE_TINY, curr_type, curr_ratio, curr_border); - break; - case 1: - _holder->setStyle(UI::Widget::PREVIEW_SIZE_SMALL, curr_type, curr_ratio, curr_border); - break; - case 2: - _holder->setStyle(UI::Widget::PREVIEW_SIZE_MEDIUM, curr_type, curr_ratio, curr_border); - break; - case 3: - _holder->setStyle(UI::Widget::PREVIEW_SIZE_BIG, curr_type, curr_ratio, curr_border); - break; - case 4: - _holder->setStyle(UI::Widget::PREVIEW_SIZE_HUGE, curr_type, curr_ratio, curr_border); - break; - default: - break; - } + switch (value) { + case 0: + _holder->setStyle(UI::Widget::PREVIEW_SIZE_TINY, curr_type, curr_ratio, curr_border); + break; + case 1: + _holder->setStyle(UI::Widget::PREVIEW_SIZE_SMALL, curr_type, curr_ratio, curr_border); + break; + case 2: + _holder->setStyle(UI::Widget::PREVIEW_SIZE_MEDIUM, curr_type, curr_ratio, curr_border); + break; + case 3: + _holder->setStyle(UI::Widget::PREVIEW_SIZE_BIG, curr_type, curr_ratio, curr_border); + break; + case 4: + _holder->setStyle(UI::Widget::PREVIEW_SIZE_HUGE, curr_type, curr_ratio, curr_border); + break; + default: + break; + } - break; - } - case SWATCHES_SETTINGS_MODE: { - prefs->setInt(_prefs_path + "/panel_mode", value); - - auto curr_size = _holder->getPreviewSize(); - guint curr_ratio = _holder->getPreviewRatio(); - auto curr_border = _holder->getPreviewBorder(); - switch (value) { - case 0: - _holder->setStyle(curr_size, UI::Widget::VIEW_TYPE_LIST, curr_ratio, curr_border); - break; - case 1: - _holder->setStyle(curr_size, UI::Widget::VIEW_TYPE_GRID, curr_ratio, curr_border); break; - default: + } + case SWATCHES_SETTINGS_MODE: { + prefs->setInt(_prefs_path + "/panel_mode", value); + + auto curr_size = _holder->getPreviewSize(); + guint curr_ratio = _holder->getPreviewRatio(); + auto curr_border = _holder->getPreviewBorder(); + switch (value) { + case 0: + _holder->setStyle(curr_size, UI::Widget::VIEW_TYPE_LIST, curr_ratio, curr_border); + break; + case 1: + _holder->setStyle(curr_size, UI::Widget::VIEW_TYPE_GRID, curr_ratio, curr_border); + break; + default: + break; + } break; } - break; - } - case SWATCHES_SETTINGS_SHAPE: { - prefs->setInt(_prefs_path + "/panel_ratio", value); + case SWATCHES_SETTINGS_SHAPE: { + prefs->setInt(_prefs_path + "/panel_ratio", value); - auto curr_type = _holder->getPreviewType(); - auto curr_size = _holder->getPreviewSize(); - auto curr_border = _holder->getPreviewBorder(); + auto curr_type = _holder->getPreviewType(); + auto curr_size = _holder->getPreviewSize(); + auto curr_border = _holder->getPreviewBorder(); - _holder->setStyle(curr_size, curr_type, value, curr_border); - break; - } - case SWATCHES_SETTINGS_BORDER: { - prefs->setInt(_prefs_path + "/panel_border", value); + _holder->setStyle(curr_size, curr_type, value, curr_border); + break; + } + case SWATCHES_SETTINGS_BORDER: { + prefs->setInt(_prefs_path + "/panel_border", value); - auto curr_size = _holder->getPreviewSize(); - auto curr_type = _holder->getPreviewType(); - guint curr_ratio = _holder->getPreviewRatio(); + auto curr_size = _holder->getPreviewSize(); + auto curr_type = _holder->getPreviewType(); + guint curr_ratio = _holder->getPreviewRatio(); - switch (value) { - case 0: - _holder->setStyle(curr_size, curr_type, curr_ratio, UI::Widget::BORDER_NONE); - break; - case 1: - _holder->setStyle(curr_size, curr_type, curr_ratio, UI::Widget::BORDER_SOLID); - break; - case 2: - _holder->setStyle(curr_size, curr_type, curr_ratio, UI::Widget::BORDER_WIDE); + switch (value) { + case 0: + _holder->setStyle(curr_size, curr_type, curr_ratio, UI::Widget::BORDER_NONE); + break; + case 1: + _holder->setStyle(curr_size, curr_type, curr_ratio, UI::Widget::BORDER_SOLID); + break; + case 2: + _holder->setStyle(curr_size, curr_type, curr_ratio, UI::Widget::BORDER_WIDE); + break; + default: + break; + } break; - default: + } + case SWATCHES_SETTINGS_WRAP: { + prefs->setBool(_prefs_path + "/panel_wrap", value); + _holder->setWrap(value); break; } - break; - } - case SWATCHES_SETTINGS_WRAP: { - prefs->setBool(_prefs_path + "/panel_wrap", value); - _holder->setWrap(value); - break; - } - case SWATCHES_SETTINGS_PALETTE: { - std::vector<SwatchPage*> pages = _getSwatchSets(); - if (value >= 0 && value < static_cast<int>(pages.size()) ) { - _currentIndex = value; + case SWATCHES_SETTINGS_PALETTE: { + std::vector<SwatchPage *> pages = _getSwatchSets(); + if (value >= 0 && value < static_cast<int>(pages.size())) { + _currentIndex = value; - prefs->setString(_prefs_path + "/palette", pages[_currentIndex]->_name); + prefs->setString(_prefs_path + "/palette", pages[_currentIndex]->_name); - _rebuild(); + _rebuild(); + } } - } - default: - break; + default: + break; } } -void SwatchesPanel::_wrapToggled(Gtk::CheckMenuItem* toggler) +void SwatchesPanel::_wrapToggled(Gtk::CheckMenuItem *toggler) { if (toggler) { _updateSettings(SWATCHES_SETTINGS_WRAP, toggler->get_active() ? 1 : 0); } } -void SwatchesPanel::_regItem(Gtk::MenuItem* item, int id) +void SwatchesPanel::_regItem(Gtk::MenuItem *item, int id) { _menu->append(*item); - item->signal_activate().connect(sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), SWATCHES_SETTINGS_PALETTE, id)); + item->signal_activate().connect( + sigc::bind<int, int>(sigc::mem_fun(*this, &SwatchesPanel::_updateSettings), SWATCHES_SETTINGS_PALETTE, id)); item->show(); } - class DocTrack { public: - DocTrack(SPDocument *doc, sigc::connection &gradientRsrcChanged, sigc::connection &defsChanged, sigc::connection &defsModified) : - doc(doc->doRef()), - updatePending(false), - lastGradientUpdate(0.0), - gradientRsrcChanged(gradientRsrcChanged), - defsChanged(defsChanged), - defsModified(defsModified) + DocTrack(SPDocument *doc, sigc::connection &gradientRsrcChanged, sigc::connection &defsChanged, + sigc::connection &defsModified) + : doc(doc->doRef()) + , updatePending(false) + , lastGradientUpdate(0.0) + , gradientRsrcChanged(gradientRsrcChanged) + , defsChanged(defsChanged) + , defsModified(defsModified) { - if ( !timer ) { + if (!timer) { timer = new Glib::Timer(); - refreshTimer = Glib::signal_timeout().connect( sigc::ptr_fun(handleTimerCB), 33 ); + refreshTimer = Glib::signal_timeout().connect(sigc::ptr_fun(handleTimerCB), 33); } timerRefCount++; } @@ -1004,10 +980,10 @@ public: ~DocTrack() { timerRefCount--; - if ( timerRefCount <= 0 ) { + if (timerRefCount <= 0) { refreshTimer.disconnect(); timerRefCount = 0; - if ( timer ) { + if (timer) { timer->stop(); delete timer; timer = nullptr; @@ -1041,7 +1017,7 @@ public: sigc::connection defsModified; private: - DocTrack(DocTrack const &) = delete; // no copy + DocTrack(DocTrack const &) = delete; // no copy DocTrack &operator=(DocTrack const &) = delete; // no assign }; @@ -1049,7 +1025,7 @@ Glib::Timer *DocTrack::timer = nullptr; int DocTrack::timerRefCount = 0; sigc::connection DocTrack::refreshTimer; -static const double DOC_UPDATE_THREASHOLD = 0.090; +static const double DOC_UPDATE_THREASHOLD = 0.090; bool DocTrack::handleTimerCB() { @@ -1057,13 +1033,14 @@ bool DocTrack::handleTimerCB() std::vector<DocTrack *> needCallback; for (auto track : docTrackings) { - if ( track->updatePending && ( (now - track->lastGradientUpdate) >= DOC_UPDATE_THREASHOLD) ) { + if (track->updatePending && ((now - track->lastGradientUpdate) >= DOC_UPDATE_THREASHOLD)) { needCallback.push_back(track); } } for (auto track : needCallback) { - if ( std::find(docTrackings.begin(), docTrackings.end(), track) != docTrackings.end() ) { // Just in case one gets deleted while we are looping + if (std::find(docTrackings.begin(), docTrackings.end(), track) != + docTrackings.end()) { // Just in case one gets deleted while we are looping // Note: calling handleDefsModified will call queueUpdateIfNeeded and thus update the time and flag. SwatchesPanel::handleDefsModified(track->doc.get()); } @@ -1072,15 +1049,15 @@ bool DocTrack::handleTimerCB() return true; } -bool DocTrack::queueUpdateIfNeeded( SPDocument *doc ) +bool DocTrack::queueUpdateIfNeeded(SPDocument *doc) { bool deferProcessing = false; for (auto track : docTrackings) { - if ( track->doc.get() == doc ) { + if (track->doc.get() == doc) { double now = timer->elapsed(); double elapsed = now - track->lastGradientUpdate; - if ( elapsed < DOC_UPDATE_THREASHOLD ) { + if (elapsed < DOC_UPDATE_THREASHOLD) { deferProcessing = true; track->updatePending = true; } else { @@ -1094,7 +1071,7 @@ bool DocTrack::queueUpdateIfNeeded( SPDocument *doc ) return deferProcessing; } -void SwatchesPanel::_trackDocument( SwatchesPanel *panel, SPDocument *document ) +void SwatchesPanel::_trackDocument(SwatchesPanel *panel, SPDocument *document) { SPDocument *oldDoc = nullptr; if (docPerPanel.find(panel) != docPerPanel.end()) { @@ -1107,11 +1084,12 @@ void SwatchesPanel::_trackDocument( SwatchesPanel *panel, SPDocument *document ) if (oldDoc) { docPerPanel[panel] = nullptr; bool found = false; - for (std::map<SwatchesPanel*, SPDocument*>::iterator it = docPerPanel.begin(); (it != docPerPanel.end()) && !found; ++it) { + for (std::map<SwatchesPanel *, SPDocument *>::iterator it = docPerPanel.begin(); + (it != docPerPanel.end()) && !found; ++it) { found = (it->second == document); } if (!found) { - for (std::vector<DocTrack*>::iterator it = docTrackings.begin(); it != docTrackings.end(); ++it){ + for (std::vector<DocTrack *>::iterator it = docTrackings.begin(); it != docTrackings.end(); ++it) { if ((*it)->doc.get() == oldDoc) { delete *it; docTrackings.erase(it); @@ -1123,14 +1101,18 @@ void SwatchesPanel::_trackDocument( SwatchesPanel *panel, SPDocument *document ) if (document) { bool found = false; - for (std::map<SwatchesPanel*, SPDocument*>::iterator it = docPerPanel.begin(); (it != docPerPanel.end()) && !found; ++it) { + for (std::map<SwatchesPanel *, SPDocument *>::iterator it = docPerPanel.begin(); + (it != docPerPanel.end()) && !found; ++it) { found = (it->second == document); } docPerPanel[panel] = document; if (!found) { - 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))) ); + 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); docTrackings.push_back(dt); @@ -1145,9 +1127,9 @@ void SwatchesPanel::_trackDocument( SwatchesPanel *panel, SPDocument *document ) } } -void SwatchesPanel::_setDocument( SPDocument *document ) +void SwatchesPanel::_setDocument(SPDocument *document) { - if ( document != _currentDocument ) { + if (document != _currentDocument) { _trackDocument(this, document); _currentDocument = document; @@ -1157,30 +1139,27 @@ void SwatchesPanel::_setDocument( SPDocument *document ) } } -static void recalcSwatchContents(SPDocument* doc, - boost::ptr_vector<ColorItem> &tmpColors, - std::map<ColorItem*, cairo_pattern_t*> &previewMappings, - std::map<ColorItem*, SPGradient*> &gradMappings) +static void recalcSwatchContents(SPDocument *doc, boost::ptr_vector<ColorItem> &tmpColors, + std::map<ColorItem *, cairo_pattern_t *> &previewMappings, + std::map<ColorItem *, SPGradient *> &gradMappings) { - std::vector<SPGradient*> newList; + std::vector<SPGradient *> newList; std::vector<SPObject *> gradients = doc->getResourceList("gradient"); for (auto gradient : gradients) { - SPGradient* grad = SP_GRADIENT(gradient); - if ( grad->isSwatch() ) { + SPGradient *grad = SP_GRADIENT(gradient); + if (grad->isSwatch()) { newList.push_back(SP_GRADIENT(gradient)); } } - if ( !newList.empty() ) { + if (!newList.empty()) { std::reverse(newList.begin(), newList.end()); - for (auto grad : newList) - { - cairo_surface_t *preview = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, - PREVIEW_PIXBUF_WIDTH, VBLOCK); + for (auto grad : newList) { + cairo_surface_t *preview = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, PREVIEW_PIXBUF_WIDTH, VBLOCK); cairo_t *ct = cairo_create(preview); - Glib::ustring name( grad->getId() ); - ColorItem* item = new ColorItem( 0, 0, 0, name ); + Glib::ustring name(grad->getId()); + ColorItem *item = new ColorItem(0, 0, 0, name); cairo_pattern_t *check = ink_cairo_pattern_create_checkerboard(); cairo_pattern_t *gradient = grad->create_preview_pattern(PREVIEW_PIXBUF_WIDTH); @@ -1209,16 +1188,16 @@ void SwatchesPanel::handleGradientsChange(SPDocument *document) SwatchPage *docPalette = (docPalettes.find(document) != docPalettes.end()) ? docPalettes[document] : nullptr; if (docPalette) { boost::ptr_vector<ColorItem> tmpColors; - std::map<ColorItem*, cairo_pattern_t*> tmpPrevs; - std::map<ColorItem*, SPGradient*> tmpGrads; + std::map<ColorItem *, cairo_pattern_t *> tmpPrevs; + std::map<ColorItem *, SPGradient *> tmpGrads; recalcSwatchContents(document, tmpColors, tmpPrevs, tmpGrads); - for (auto & tmpPrev : tmpPrevs) { + for (auto &tmpPrev : tmpPrevs) { tmpPrev.first->setPattern(tmpPrev.second); cairo_pattern_destroy(tmpPrev.second); } - for (auto & tmpGrad : tmpGrads) { + for (auto &tmpGrad : tmpGrads) { tmpGrad.first->setGradient(tmpGrad.second); } @@ -1226,11 +1205,11 @@ void SwatchesPanel::handleGradientsChange(SPDocument *document) // Figure out which SwatchesPanel instances are affected and update them. - for (auto & it : docPerPanel) { + for (auto &it : docPerPanel) { if (it.second == document) { - SwatchesPanel* swp = it.first; - std::vector<SwatchPage*> pages = swp->_getSwatchSets(); - SwatchPage* curr = pages[swp->_currentIndex]; + SwatchesPanel *swp = it.first; + std::vector<SwatchPage *> pages = swp->_getSwatchSets(); + SwatchPage *curr = pages[swp->_currentIndex]; if (curr == docPalette) { swp->_rebuild(); } @@ -1242,44 +1221,42 @@ void SwatchesPanel::handleGradientsChange(SPDocument *document) void SwatchesPanel::handleDefsModified(SPDocument *document) { SwatchPage *docPalette = (docPalettes.find(document) != docPalettes.end()) ? docPalettes[document] : nullptr; - if (docPalette && !DocTrack::queueUpdateIfNeeded(document) ) { + if (docPalette && !DocTrack::queueUpdateIfNeeded(document)) { boost::ptr_vector<ColorItem> tmpColors; - std::map<ColorItem*, cairo_pattern_t*> tmpPrevs; - std::map<ColorItem*, SPGradient*> tmpGrads; + std::map<ColorItem *, cairo_pattern_t *> tmpPrevs; + std::map<ColorItem *, SPGradient *> tmpGrads; recalcSwatchContents(document, tmpColors, tmpPrevs, tmpGrads); - if ( tmpColors.size() != docPalette->_colors.size() ) { + if (tmpColors.size() != docPalette->_colors.size()) { handleGradientsChange(document); } else { int cap = std::min(docPalette->_colors.size(), tmpColors.size()); for (int i = 0; i < cap; i++) { ColorItem *newColor = &tmpColors[i]; ColorItem *oldColor = &docPalette->_colors[i]; - if ( (newColor->def.getType() != oldColor->def.getType()) || - (newColor->def.getR() != oldColor->def.getR()) || - (newColor->def.getG() != oldColor->def.getG()) || - (newColor->def.getB() != oldColor->def.getB()) ) { + if ((newColor->def.getType() != oldColor->def.getType()) || + (newColor->def.getR() != oldColor->def.getR()) || (newColor->def.getG() != oldColor->def.getG()) || + (newColor->def.getB() != oldColor->def.getB())) { oldColor->def.setRGB(newColor->def.getR(), newColor->def.getG(), newColor->def.getB()); } if (tmpGrads.find(newColor) != tmpGrads.end()) { oldColor->setGradient(tmpGrads[newColor]); } - if ( tmpPrevs.find(newColor) != tmpPrevs.end() ) { + if (tmpPrevs.find(newColor) != tmpPrevs.end()) { oldColor->setPattern(tmpPrevs[newColor]); } } } - for (auto & tmpPrev : tmpPrevs) { + for (auto &tmpPrev : tmpPrevs) { cairo_pattern_destroy(tmpPrev.second); } } } - -std::vector<SwatchPage*> SwatchesPanel::_getSwatchSets() const +std::vector<SwatchPage *> SwatchesPanel::_getSwatchSets() const { - std::vector<SwatchPage*> tmp; + std::vector<SwatchPage *> tmp; if (docPalettes.find(_currentDocument) != docPalettes.end()) { tmp.push_back(docPalettes[_currentDocument]); } @@ -1292,36 +1269,36 @@ std::vector<SwatchPage*> SwatchesPanel::_getSwatchSets() const void SwatchesPanel::_updateFromSelection() { - SwatchPage *docPalette = (docPalettes.find(_currentDocument) != docPalettes.end()) ? docPalettes[_currentDocument] : nullptr; - if ( docPalette ) { + SwatchPage *docPalette = + (docPalettes.find(_currentDocument) != docPalettes.end()) ? docPalettes[_currentDocument] : nullptr; + if (docPalette) { std::string fillId; std::string strokeId; SPStyle tmpStyle(_currentDesktop->getDocument()); - int result = sp_desktop_query_style( _currentDesktop, &tmpStyle, QUERY_STYLE_PROPERTY_FILL ); + int result = sp_desktop_query_style(_currentDesktop, &tmpStyle, QUERY_STYLE_PROPERTY_FILL); switch (result) { case QUERY_STYLE_SINGLE: case QUERY_STYLE_MULTIPLE_AVERAGED: - case QUERY_STYLE_MULTIPLE_SAME: - { + case QUERY_STYLE_MULTIPLE_SAME: { if (tmpStyle.fill.set && tmpStyle.fill.isPaintserver()) { - SPPaintServer* server = tmpStyle.getFillPaintServer(); - if ( SP_IS_GRADIENT(server) ) { - SPGradient* target = nullptr; - SPGradient* grad = SP_GRADIENT(server); + SPPaintServer *server = tmpStyle.getFillPaintServer(); + if (SP_IS_GRADIENT(server)) { + SPGradient *target = nullptr; + SPGradient *grad = SP_GRADIENT(server); - if ( grad->isSwatch() ) { + if (grad->isSwatch()) { target = grad; - } else if ( grad->ref ) { + } else if (grad->ref) { SPGradient *tmp = grad->ref->getObject(); - if ( tmp && tmp->isSwatch() ) { + if (tmp && tmp->isSwatch()) { target = tmp; } } - if ( target ) { - //XML Tree being used directly here while it shouldn't be - gchar const* id = target->getRepr()->attribute("id"); - if ( id ) { + if (target) { + // XML Tree being used directly here while it shouldn't be + gchar const *id = target->getRepr()->attribute("id"); + if (id) { fillId = id; } } @@ -1331,29 +1308,28 @@ void SwatchesPanel::_updateFromSelection() } } - result = sp_desktop_query_style( _currentDesktop, &tmpStyle, QUERY_STYLE_PROPERTY_STROKE ); + result = sp_desktop_query_style(_currentDesktop, &tmpStyle, QUERY_STYLE_PROPERTY_STROKE); switch (result) { case QUERY_STYLE_SINGLE: case QUERY_STYLE_MULTIPLE_AVERAGED: - case QUERY_STYLE_MULTIPLE_SAME: - { + case QUERY_STYLE_MULTIPLE_SAME: { if (tmpStyle.stroke.set && tmpStyle.stroke.isPaintserver()) { - SPPaintServer* server = tmpStyle.getStrokePaintServer(); - if ( SP_IS_GRADIENT(server) ) { - SPGradient* target = nullptr; - SPGradient* grad = SP_GRADIENT(server); - if ( grad->isSwatch() ) { + SPPaintServer *server = tmpStyle.getStrokePaintServer(); + if (SP_IS_GRADIENT(server)) { + SPGradient *target = nullptr; + SPGradient *grad = SP_GRADIENT(server); + if (grad->isSwatch()) { target = grad; - } else if ( grad->ref ) { + } else if (grad->ref) { SPGradient *tmp = grad->ref->getObject(); - if ( tmp && tmp->isSwatch() ) { + if (tmp && tmp->isSwatch()) { target = tmp; } } - if ( target ) { - //XML Tree being used directly here while it shouldn't be - gchar const* id = target->getRepr()->attribute("id"); - if ( id ) { + if (target) { + // XML Tree being used directly here while it shouldn't be + gchar const *id = target->getRepr()->attribute("id"); + if (id) { strokeId = id; } } @@ -1363,37 +1339,36 @@ void SwatchesPanel::_updateFromSelection() } } - for (auto & _color : docPalette->_colors) { - ColorItem* item = &_color; + for (auto &_color : docPalette->_colors) { + ColorItem *item = &_color; bool isFill = (fillId == item->def.descr); bool isStroke = (strokeId == item->def.descr); - item->setState( isFill, isStroke ); + item->setState(isFill, isStroke); } } } void SwatchesPanel::_rebuild() { - std::vector<SwatchPage*> pages = _getSwatchSets(); - SwatchPage* curr = pages[_currentIndex]; + std::vector<SwatchPage *> pages = _getSwatchSets(); + SwatchPage *curr = pages[_currentIndex]; _holder->clear(); - if ( curr->_prefWidth > 0 ) { - _holder->setColumnPref( curr->_prefWidth ); + if (curr->_prefWidth > 0) { + _holder->setColumnPref(curr->_prefWidth); } _holder->freezeUpdates(); // TODO restore once 'clear' works _holder->addPreview(_clear); _holder->addPreview(_remove); - for (auto & _color : curr->_colors) { + for (auto &_color : curr->_colors) { _holder->addPreview(&_color); } _holder->thawUpdates(); } -} //namespace Dialog -} //namespace UI -} //namespace Inkscape - +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/swatches.h b/src/ui/dialog/swatches.h index 52eb6e847f4ee341d01dbd9793e30f67405e6ec3..d389dd97f9a40541fb61aab94e1650a89d9d7d19 100644 --- a/src/ui/dialog/swatches.h +++ b/src/ui/dialog/swatches.h @@ -14,10 +14,10 @@ #include "ui/widget/panel.h" namespace Gtk { - class Menu; - class MenuItem; - class CheckMenuItem; -} +class Menu; +class MenuItem; +class CheckMenuItem; +} // namespace Gtk namespace Inkscape { namespace UI { @@ -41,59 +41,57 @@ class DocTrack; class SwatchesPanel : public Inkscape::UI::Widget::Panel { public: - SwatchesPanel(gchar const* prefsPath = "/dialogs/swatches"); + SwatchesPanel(gchar const *prefsPath = "/dialogs/swatches"); ~SwatchesPanel() override; - static SwatchesPanel& getInstance(); + static SwatchesPanel &getInstance(); - void setDesktop( SPDesktop* desktop ) override; - virtual SPDesktop* getDesktop() {return _currentDesktop;} + void setDesktop(SPDesktop *desktop) override; + virtual SPDesktop *getDesktop() { return _currentDesktop; } - virtual int getSelectedIndex() {return _currentIndex;} // temporary + virtual int getSelectedIndex() { return _currentIndex; } // temporary protected: static void handleGradientsChange(SPDocument *document); virtual void _updateFromSelection(); - virtual void _setDocument( SPDocument *document ); + virtual void _setDocument(SPDocument *document); virtual void _rebuild(); - virtual std::vector<SwatchPage*> _getSwatchSets() const; + virtual std::vector<SwatchPage *> _getSwatchSets() const; private: - SwatchesPanel(SwatchesPanel const &) = delete; // no copy + SwatchesPanel(SwatchesPanel const &) = delete; // no copy SwatchesPanel &operator=(SwatchesPanel const &) = delete; // no assign void _build_menu(); - static void _trackDocument( SwatchesPanel *panel, SPDocument *document ); + static void _trackDocument(SwatchesPanel *panel, SPDocument *document); static void handleDefsModified(SPDocument *document); - PreviewHolder* _holder; - ColorItem* _clear; - ColorItem* _remove; + PreviewHolder *_holder; + ColorItem *_clear; + ColorItem *_remove; int _currentIndex; - SPDesktop* _currentDesktop; - SPDocument* _currentDocument; + SPDesktop *_currentDesktop; + SPDocument *_currentDocument; - void _regItem(Gtk::MenuItem* item, int id); + void _regItem(Gtk::MenuItem *item, int id); void _updateSettings(int settings, int value); void _wrapToggled(Gtk::CheckMenuItem *toggler); - Gtk::Menu *_menu; + Gtk::Menu *_menu; std::vector<sigc::connection> _desktopConnections; friend class DocTrack; }; -} //namespace Dialog -} //namespace UI -} //namespace Inkscape - - +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif // SEEN_SWATCHES_H diff --git a/src/ui/dialog/symbols.cpp b/src/ui/dialog/symbols.cpp index 9dc867bb4cd3219e19ab84e82187a08ac6ff4798..b5a3f90bfdb428c04de4aea025711f31b377780c 100644 --- a/src/ui/dialog/symbols.cpp +++ b/src/ui/dialog/symbols.cpp @@ -10,63 +10,60 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include <iostream> #include <algorithm> -#include <locale> -#include <sstream> #include <fstream> -#include <regex> - #include <glibmm/i18n.h> #include <glibmm/markup.h> #include <glibmm/regex.h> #include <glibmm/stringutils.h> +#include <iostream> +#include <locale> +#include <regex> +#include <sstream> #include "desktop.h" -#include "document.h" -#include "inkscape.h" -#include "path-prefix.h" -#include "selection.h" -#include "symbols.h" -#include "verbs.h" - #include "display/cairo-utils.h" +#include "document.h" #include "helper/action.h" #include "include/gtkmm_version.h" +#include "inkscape.h" #include "io/resource.h" #include "io/sys.h" #include "object/sp-defs.h" #include "object/sp-root.h" #include "object/sp-symbol.h" #include "object/sp-use.h" +#include "path-prefix.h" +#include "selection.h" +#include "symbols.h" #include "ui/cache/svg_preview_cache.h" #include "ui/clipboard.h" #include "ui/icon-loader.h" #include "ui/icon-names.h" +#include "verbs.h" #ifdef WITH_LIBVISIO - #include <libvisio/libvisio.h> - - // TODO: Drop this check when librevenge is widespread. - #if WITH_LIBVISIO01 - #include <librevenge-stream/librevenge-stream.h> - - using librevenge::RVNGFileStream; - using librevenge::RVNGString; - using librevenge::RVNGStringVector; - using librevenge::RVNGPropertyList; - using librevenge::RVNGSVGDrawingGenerator; - #else - #include <libwpd-stream/libwpd-stream.h> - - typedef WPXFileStream RVNGFileStream; - typedef libvisio::VSDStringVector RVNGStringVector; - #endif -#endif +#include <libvisio/libvisio.h> + +// TODO: Drop this check when librevenge is widespread. +#if WITH_LIBVISIO01 +#include <librevenge-stream/librevenge-stream.h> +using librevenge::RVNGFileStream; +using librevenge::RVNGPropertyList; +using librevenge::RVNGString; +using librevenge::RVNGStringVector; +using librevenge::RVNGSVGDrawingGenerator; +#else +#include <libwpd-stream/libwpd-stream.h> + +typedef WPXFileStream RVNGFileStream; +typedef libvisio::VSDStringVector RVNGStringVector; +#endif +#endif namespace Inkscape { namespace UI { @@ -77,833 +74,841 @@ namespace Dialog { class SymbolColumns : public Gtk::TreeModel::ColumnRecord { public: + Gtk::TreeModelColumn<Glib::ustring> symbol_id; + Gtk::TreeModelColumn<Glib::ustring> symbol_title; + Gtk::TreeModelColumn<Glib::ustring> symbol_doc_title; + Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf>> symbol_image; - Gtk::TreeModelColumn<Glib::ustring> symbol_id; - Gtk::TreeModelColumn<Glib::ustring> symbol_title; - Gtk::TreeModelColumn<Glib::ustring> symbol_doc_title; - Gtk::TreeModelColumn< Glib::RefPtr<Gdk::Pixbuf> > symbol_image; - - - SymbolColumns() { - add(symbol_id); - add(symbol_title); - add(symbol_doc_title); - add(symbol_image); - } + SymbolColumns() + { + add(symbol_id); + add(symbol_title); + add(symbol_doc_title); + add(symbol_image); + } }; -SymbolColumns* SymbolsDialog::getColumns() +SymbolColumns *SymbolsDialog::getColumns() { - SymbolColumns* columns = new SymbolColumns(); - return columns; + 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())), - all_docs_processed(false), - icon_view(nullptr), - current_desktop(nullptr), - current_document(nullptr), - preview_document(nullptr), - instanceConns(), - CURRENTDOC(_("Current document")), - ALLDOCS(_("All symbol sets")) +SymbolsDialog::SymbolsDialog(gchar const *prefsPath) + : UI::Widget::Panel(prefsPath, SP_VERB_DIALOG_SYMBOLS) + , store(Gtk::ListStore::create(*getColumns())) + , all_docs_processed(false) + , icon_view(nullptr) + , current_desktop(nullptr) + , current_document(nullptr) + , preview_document(nullptr) + , instanceConns() + , CURRENTDOC(_("Current document")) + , ALLDOCS(_("All symbol sets")) { - /******************** Table *************************/ - auto table = new Gtk::Grid(); - - table->set_margin_start(3); - table->set_margin_end(3); - table->set_margin_top(4); - // panel is a locked Gtk::VBox - _getContents()->pack_start(*Gtk::manage(table), Gtk::PACK_EXPAND_WIDGET); - guint row = 0; - - /******************** Symbol Sets *************************/ - Gtk::Label* label_set = new Gtk::Label(Glib::ustring(_("Symbol set")) + ": "); - table->attach(*Gtk::manage(label_set),0,row,1,1); - symbol_set = new Gtk::ComboBoxText(); // Fill in later - symbol_set->append(CURRENTDOC); - symbol_set->append(ALLDOCS); - symbol_set->set_active_text(CURRENTDOC); - symbol_set->set_hexpand(); - - table->attach(*Gtk::manage(symbol_set),1,row,1,1); - - ++row; - - /******************** Separator *************************/ - - - Gtk::Separator* separator = Gtk::manage(new Gtk::Separator()); // Search - separator->set_margin_top(10); - separator->set_margin_bottom(10); - table->attach(*Gtk::manage(separator),0,row,2,1); - - ++row; - - /******************** Search *************************/ - - - search = Gtk::manage(new Gtk::SearchEntry()); // Search - search->set_tooltip_text(_("Press 'Return' to start search.")); - search->signal_key_press_event().connect_notify( sigc::mem_fun(*this, &SymbolsDialog::beforeSearch)); - search->signal_key_release_event().connect_notify(sigc::mem_fun(*this, &SymbolsDialog::unsensitive)); - - search->set_margin_bottom(6); - search->signal_search_changed().connect(sigc::mem_fun(*this, &SymbolsDialog::clearSearch)); - table->attach(*Gtk::manage(search),0,row,2,1); - search_str = ""; - - ++row; - - - /********************* Icon View **************************/ - SymbolColumns* columns = getColumns(); - - icon_view = new Gtk::IconView(static_cast<Glib::RefPtr<Gtk::TreeModel> >(store)); - //icon_view->set_text_column( columns->symbol_id ); - icon_view->set_tooltip_column( 1 ); - icon_view->set_pixbuf_column( columns->symbol_image ); - // Giving the iconview a small minimum size will help users understand - // What the dialog does. - icon_view->set_size_request( 100, 250 ); - - std::vector< Gtk::TargetEntry > targets; - targets.emplace_back( "application/x-inkscape-paste"); - - icon_view->enable_model_drag_source (targets, Gdk::BUTTON1_MASK, Gdk::ACTION_COPY); - icon_view->signal_drag_data_get().connect( - sigc::mem_fun(*this, &SymbolsDialog::iconDragDataGet)); - - scroller = new Gtk::ScrolledWindow(); - scroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS); - scroller->add(*Gtk::manage(icon_view)); - scroller->set_hexpand(); - scroller->set_vexpand(); - - overlay = new Gtk::Overlay(); - overlay->set_hexpand(); - overlay->set_vexpand(); - overlay->add(* scroller); - overlay->get_style_context()->add_class("forcebright"); - scroller->set_size_request(100, 250); - table->attach(*Gtk::manage(overlay), 0, row, 2, 1); - - /*************************Overlays******************************/ - overlay_opacity = new Gtk::Image(); - overlay_opacity->set_halign(Gtk::ALIGN_START); - overlay_opacity->set_valign(Gtk::ALIGN_START); - overlay_opacity->get_style_context()->add_class("rawstyle"); - - // No results - overlay_icon = sp_get_icon_image("searching", Gtk::ICON_SIZE_DIALOG); - overlay_icon->set_pixel_size(110); - overlay_icon->set_halign(Gtk::ALIGN_CENTER); - overlay_icon->set_valign(Gtk::ALIGN_START); - - overlay_icon->set_margin_top(45); - - overlay_title = new Gtk::Label(); - overlay_title->set_halign(Gtk::ALIGN_CENTER ); - overlay_title->set_valign(Gtk::ALIGN_START ); - overlay_title->set_justify(Gtk::JUSTIFY_CENTER); - overlay_title->set_margin_top(155); - - overlay_desc = new Gtk::Label(); - overlay_desc->set_halign(Gtk::ALIGN_CENTER); - overlay_desc->set_valign(Gtk::ALIGN_START); - overlay_desc->set_margin_top(180); - overlay_desc->set_justify(Gtk::JUSTIFY_CENTER); - - overlay->add_overlay(*overlay_opacity); - overlay->add_overlay(*overlay_icon); - overlay->add_overlay(*overlay_title); - overlay->add_overlay(*overlay_desc); - - previous_height = 0; - previous_width = 0; - ++row; - - /******************** Progress *******************************/ - progress = new Gtk::HBox(); - progress_bar = Gtk::manage(new Gtk::ProgressBar()); - table->attach(*Gtk::manage(progress),0,row, 2, 1); - progress->pack_start(* progress_bar, Gtk::PACK_EXPAND_WIDGET); - progress->set_margin_top(15); - progress->set_margin_bottom(15); - progress->set_margin_start(20); - progress->set_margin_end(20); - - ++row; - - /******************** Tools *******************************/ - tools = new Gtk::HBox(); - - //tools->set_layout( Gtk::BUTTONBOX_END ); - scroller->set_hexpand(); - table->attach(*Gtk::manage(tools),0,row,2,1); - - auto add_symbol_image = Gtk::manage(sp_get_icon_image("symbol-add", Gtk::ICON_SIZE_SMALL_TOOLBAR)); - - add_symbol = Gtk::manage(new Gtk::Button()); - add_symbol->add(*add_symbol_image); - add_symbol->set_tooltip_text(_("Add Symbol from the current document.")); - add_symbol->set_relief( Gtk::RELIEF_NONE ); - add_symbol->set_focus_on_click( false ); - add_symbol->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::insertSymbol)); - tools->pack_start(* add_symbol, Gtk::PACK_SHRINK); - - auto remove_symbolImage = Gtk::manage(sp_get_icon_image("symbol-remove", Gtk::ICON_SIZE_SMALL_TOOLBAR)); - - remove_symbol = Gtk::manage(new Gtk::Button()); - remove_symbol->add(*remove_symbolImage); - remove_symbol->set_tooltip_text(_("Remove Symbol from the current document.")); - remove_symbol->set_relief( Gtk::RELIEF_NONE ); - remove_symbol->set_focus_on_click( false ); - remove_symbol->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::revertSymbol)); - tools->pack_start(* remove_symbol, Gtk::PACK_SHRINK); - - Gtk::Label* spacer = Gtk::manage(new Gtk::Label("")); - tools->pack_start(* Gtk::manage(spacer)); - - // Pack size (controls display area) - pack_size = 2; // Default 32px - - auto packMoreImage = Gtk::manage(sp_get_icon_image("pack-more", Gtk::ICON_SIZE_SMALL_TOOLBAR)); - - more = Gtk::manage(new Gtk::Button()); - more->add(*packMoreImage); - more->set_tooltip_text(_("Display more icons in row.")); - more->set_relief( Gtk::RELIEF_NONE ); - more->set_focus_on_click( false ); - more->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::packmore)); - tools->pack_start(* more, Gtk::PACK_SHRINK); - - auto packLessImage = Gtk::manage(sp_get_icon_image("pack-less", Gtk::ICON_SIZE_SMALL_TOOLBAR)); - - fewer = Gtk::manage(new Gtk::Button()); - fewer->add(*packLessImage); - fewer->set_tooltip_text(_("Display fewer icons in row.")); - fewer->set_relief( Gtk::RELIEF_NONE ); - fewer->set_focus_on_click( false ); - fewer->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::packless)); - tools->pack_start(* fewer, Gtk::PACK_SHRINK); - - // Toggle scale to fit on/off - auto fit_symbolImage = Gtk::manage(sp_get_icon_image("symbol-fit", Gtk::ICON_SIZE_SMALL_TOOLBAR)); - - fit_symbol = Gtk::manage(new Gtk::ToggleButton()); - fit_symbol->add(*fit_symbolImage); - fit_symbol->set_tooltip_text(_("Toggle 'fit' symbols in icon space.")); - fit_symbol->set_relief( Gtk::RELIEF_NONE ); - fit_symbol->set_focus_on_click( false ); - fit_symbol->set_active( true ); - fit_symbol->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::rebuild)); - tools->pack_start(* fit_symbol, Gtk::PACK_SHRINK); - - // Render size (scales symbols within display area) - scale_factor = 0; // Default 1:1 * pack_size/pack_size default - auto zoom_outImage = Gtk::manage(sp_get_icon_image("symbol-smaller", Gtk::ICON_SIZE_SMALL_TOOLBAR)); - - zoom_out = Gtk::manage(new Gtk::Button()); - zoom_out->add(*zoom_outImage); - zoom_out->set_tooltip_text(_("Make symbols smaller by zooming out.")); - zoom_out->set_relief( Gtk::RELIEF_NONE ); - zoom_out->set_focus_on_click( false ); - zoom_out->set_sensitive( false ); - zoom_out->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::zoomout)); - tools->pack_start(* zoom_out, Gtk::PACK_SHRINK); - - auto zoom_inImage = Gtk::manage(sp_get_icon_image("symbol-bigger", Gtk::ICON_SIZE_SMALL_TOOLBAR)); - - zoom_in = Gtk::manage(new Gtk::Button()); - zoom_in->add(*zoom_inImage); - zoom_in->set_tooltip_text(_("Make symbols bigger by zooming in.")); - zoom_in->set_relief( Gtk::RELIEF_NONE ); - zoom_in->set_focus_on_click( false ); - zoom_in->set_sensitive( false ); - zoom_in->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::zoomin)); - tools->pack_start(* zoom_in, Gtk::PACK_SHRINK); - - ++row; - - sensitive = true; - - preview_document = symbolsPreviewDoc(); /* Template to render symbols in */ - preview_document->ensureUpToDate(); /* Necessary? */ - key = SPItem::display_key_new(1); - renderDrawing.setRoot(preview_document->getRoot()->invoke_show(renderDrawing, key, SP_ITEM_SHOW_DISPLAY )); - - getSymbolsTitle(); - icons_found = false; + auto table = new Gtk::Grid(); + + table->set_margin_start(3); + table->set_margin_end(3); + table->set_margin_top(4); + // panel is a locked Gtk::VBox + _getContents()->pack_start(*Gtk::manage(table), Gtk::PACK_EXPAND_WIDGET); + guint row = 0; + + /******************** Symbol Sets *************************/ + Gtk::Label *label_set = new Gtk::Label(Glib::ustring(_("Symbol set")) + ": "); + table->attach(*Gtk::manage(label_set), 0, row, 1, 1); + symbol_set = new Gtk::ComboBoxText(); // Fill in later + symbol_set->append(CURRENTDOC); + symbol_set->append(ALLDOCS); + symbol_set->set_active_text(CURRENTDOC); + symbol_set->set_hexpand(); + + table->attach(*Gtk::manage(symbol_set), 1, row, 1, 1); + + ++row; + + /******************** Separator *************************/ + + Gtk::Separator *separator = Gtk::manage(new Gtk::Separator()); // Search + separator->set_margin_top(10); + separator->set_margin_bottom(10); + table->attach(*Gtk::manage(separator), 0, row, 2, 1); + + ++row; + + /******************** Search *************************/ + + search = Gtk::manage(new Gtk::SearchEntry()); // Search + search->set_tooltip_text(_("Press 'Return' to start search.")); + search->signal_key_press_event().connect_notify(sigc::mem_fun(*this, &SymbolsDialog::beforeSearch)); + search->signal_key_release_event().connect_notify(sigc::mem_fun(*this, &SymbolsDialog::unsensitive)); + + search->set_margin_bottom(6); + search->signal_search_changed().connect(sigc::mem_fun(*this, &SymbolsDialog::clearSearch)); + table->attach(*Gtk::manage(search), 0, row, 2, 1); + search_str = ""; + + ++row; + + /********************* Icon View **************************/ + SymbolColumns *columns = getColumns(); + + icon_view = new Gtk::IconView(static_cast<Glib::RefPtr<Gtk::TreeModel>>(store)); + // icon_view->set_text_column( columns->symbol_id ); + icon_view->set_tooltip_column(1); + icon_view->set_pixbuf_column(columns->symbol_image); + // Giving the iconview a small minimum size will help users understand + // What the dialog does. + icon_view->set_size_request(100, 250); + + std::vector<Gtk::TargetEntry> targets; + targets.emplace_back("application/x-inkscape-paste"); + + icon_view->enable_model_drag_source(targets, Gdk::BUTTON1_MASK, Gdk::ACTION_COPY); + icon_view->signal_drag_data_get().connect(sigc::mem_fun(*this, &SymbolsDialog::iconDragDataGet)); + + scroller = new Gtk::ScrolledWindow(); + scroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS); + scroller->add(*Gtk::manage(icon_view)); + scroller->set_hexpand(); + scroller->set_vexpand(); + + overlay = new Gtk::Overlay(); + overlay->set_hexpand(); + overlay->set_vexpand(); + overlay->add(*scroller); + overlay->get_style_context()->add_class("forcebright"); + scroller->set_size_request(100, 250); + table->attach(*Gtk::manage(overlay), 0, row, 2, 1); + + /*************************Overlays******************************/ + overlay_opacity = new Gtk::Image(); + overlay_opacity->set_halign(Gtk::ALIGN_START); + overlay_opacity->set_valign(Gtk::ALIGN_START); + overlay_opacity->get_style_context()->add_class("rawstyle"); + + // No results + overlay_icon = sp_get_icon_image("searching", Gtk::ICON_SIZE_DIALOG); + overlay_icon->set_pixel_size(110); + overlay_icon->set_halign(Gtk::ALIGN_CENTER); + overlay_icon->set_valign(Gtk::ALIGN_START); + + overlay_icon->set_margin_top(45); + + overlay_title = new Gtk::Label(); + overlay_title->set_halign(Gtk::ALIGN_CENTER); + overlay_title->set_valign(Gtk::ALIGN_START); + overlay_title->set_justify(Gtk::JUSTIFY_CENTER); + overlay_title->set_margin_top(155); + + overlay_desc = new Gtk::Label(); + overlay_desc->set_halign(Gtk::ALIGN_CENTER); + overlay_desc->set_valign(Gtk::ALIGN_START); + overlay_desc->set_margin_top(180); + overlay_desc->set_justify(Gtk::JUSTIFY_CENTER); + + overlay->add_overlay(*overlay_opacity); + overlay->add_overlay(*overlay_icon); + overlay->add_overlay(*overlay_title); + overlay->add_overlay(*overlay_desc); + + previous_height = 0; + previous_width = 0; + ++row; + + /******************** Progress *******************************/ + progress = new Gtk::HBox(); + progress_bar = Gtk::manage(new Gtk::ProgressBar()); + table->attach(*Gtk::manage(progress), 0, row, 2, 1); + progress->pack_start(*progress_bar, Gtk::PACK_EXPAND_WIDGET); + progress->set_margin_top(15); + progress->set_margin_bottom(15); + progress->set_margin_start(20); + progress->set_margin_end(20); + + ++row; + + /******************** Tools *******************************/ + tools = new Gtk::HBox(); + + // tools->set_layout( Gtk::BUTTONBOX_END ); + scroller->set_hexpand(); + table->attach(*Gtk::manage(tools), 0, row, 2, 1); + + auto add_symbol_image = Gtk::manage(sp_get_icon_image("symbol-add", Gtk::ICON_SIZE_SMALL_TOOLBAR)); + + add_symbol = Gtk::manage(new Gtk::Button()); + add_symbol->add(*add_symbol_image); + add_symbol->set_tooltip_text(_("Add Symbol from the current document.")); + add_symbol->set_relief(Gtk::RELIEF_NONE); + add_symbol->set_focus_on_click(false); + add_symbol->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::insertSymbol)); + tools->pack_start(*add_symbol, Gtk::PACK_SHRINK); + + auto remove_symbolImage = Gtk::manage(sp_get_icon_image("symbol-remove", Gtk::ICON_SIZE_SMALL_TOOLBAR)); + + remove_symbol = Gtk::manage(new Gtk::Button()); + remove_symbol->add(*remove_symbolImage); + remove_symbol->set_tooltip_text(_("Remove Symbol from the current document.")); + remove_symbol->set_relief(Gtk::RELIEF_NONE); + remove_symbol->set_focus_on_click(false); + remove_symbol->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::revertSymbol)); + tools->pack_start(*remove_symbol, Gtk::PACK_SHRINK); + + Gtk::Label *spacer = Gtk::manage(new Gtk::Label("")); + tools->pack_start(*Gtk::manage(spacer)); + + // Pack size (controls display area) + pack_size = 2; // Default 32px + + auto packMoreImage = Gtk::manage(sp_get_icon_image("pack-more", Gtk::ICON_SIZE_SMALL_TOOLBAR)); + + more = Gtk::manage(new Gtk::Button()); + more->add(*packMoreImage); + more->set_tooltip_text(_("Display more icons in row.")); + more->set_relief(Gtk::RELIEF_NONE); + more->set_focus_on_click(false); + more->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::packmore)); + tools->pack_start(*more, Gtk::PACK_SHRINK); + + auto packLessImage = Gtk::manage(sp_get_icon_image("pack-less", Gtk::ICON_SIZE_SMALL_TOOLBAR)); + + fewer = Gtk::manage(new Gtk::Button()); + fewer->add(*packLessImage); + fewer->set_tooltip_text(_("Display fewer icons in row.")); + fewer->set_relief(Gtk::RELIEF_NONE); + fewer->set_focus_on_click(false); + fewer->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::packless)); + tools->pack_start(*fewer, Gtk::PACK_SHRINK); + + // Toggle scale to fit on/off + auto fit_symbolImage = Gtk::manage(sp_get_icon_image("symbol-fit", Gtk::ICON_SIZE_SMALL_TOOLBAR)); + + fit_symbol = Gtk::manage(new Gtk::ToggleButton()); + fit_symbol->add(*fit_symbolImage); + fit_symbol->set_tooltip_text(_("Toggle 'fit' symbols in icon space.")); + fit_symbol->set_relief(Gtk::RELIEF_NONE); + fit_symbol->set_focus_on_click(false); + fit_symbol->set_active(true); + fit_symbol->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::rebuild)); + tools->pack_start(*fit_symbol, Gtk::PACK_SHRINK); + + // Render size (scales symbols within display area) + scale_factor = 0; // Default 1:1 * pack_size/pack_size default + auto zoom_outImage = Gtk::manage(sp_get_icon_image("symbol-smaller", Gtk::ICON_SIZE_SMALL_TOOLBAR)); + + zoom_out = Gtk::manage(new Gtk::Button()); + zoom_out->add(*zoom_outImage); + zoom_out->set_tooltip_text(_("Make symbols smaller by zooming out.")); + zoom_out->set_relief(Gtk::RELIEF_NONE); + zoom_out->set_focus_on_click(false); + zoom_out->set_sensitive(false); + zoom_out->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::zoomout)); + tools->pack_start(*zoom_out, Gtk::PACK_SHRINK); + + auto zoom_inImage = Gtk::manage(sp_get_icon_image("symbol-bigger", Gtk::ICON_SIZE_SMALL_TOOLBAR)); + + zoom_in = Gtk::manage(new Gtk::Button()); + zoom_in->add(*zoom_inImage); + zoom_in->set_tooltip_text(_("Make symbols bigger by zooming in.")); + zoom_in->set_relief(Gtk::RELIEF_NONE); + zoom_in->set_focus_on_click(false); + zoom_in->set_sensitive(false); + zoom_in->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::zoomin)); + tools->pack_start(*zoom_in, Gtk::PACK_SHRINK); + + ++row; + + sensitive = true; + + preview_document = symbolsPreviewDoc(); /* Template to render symbols in */ + preview_document->ensureUpToDate(); /* Necessary? */ + key = SPItem::display_key_new(1); + renderDrawing.setRoot(preview_document->getRoot()->invoke_show(renderDrawing, key, SP_ITEM_SHOW_DISPLAY)); + + getSymbolsTitle(); + icons_found = false; } SymbolsDialog::~SymbolsDialog() { - for (auto & instanceConn : instanceConns) { - instanceConn.disconnect(); - } - idleconn.disconnect(); - instanceConns.clear(); + for (auto &instanceConn : instanceConns) { + instanceConn.disconnect(); + } + idleconn.disconnect(); + instanceConns.clear(); } -SymbolsDialog& SymbolsDialog::getInstance() +SymbolsDialog &SymbolsDialog::getInstance() { - return *new SymbolsDialog(); + return *new SymbolsDialog(); } -void SymbolsDialog::packless() { - if(pack_size < 4) { - pack_size++; - rebuild(); - } +void SymbolsDialog::packless() +{ + if (pack_size < 4) { + pack_size++; + rebuild(); + } } -void SymbolsDialog::packmore() { - if(pack_size > 0) { - pack_size--; - rebuild(); - } +void SymbolsDialog::packmore() +{ + if (pack_size > 0) { + pack_size--; + rebuild(); + } } -void SymbolsDialog::zoomin() { - if(scale_factor < 4) { - scale_factor++; - rebuild(); - } +void SymbolsDialog::zoomin() +{ + if (scale_factor < 4) { + scale_factor++; + rebuild(); + } } -void SymbolsDialog::zoomout() { - if(scale_factor > -8) { - scale_factor--; - rebuild(); - } +void SymbolsDialog::zoomout() +{ + if (scale_factor > -8) { + scale_factor--; + rebuild(); + } } -void SymbolsDialog::rebuild() { - - if (!sensitive) { - return; - } - - if( fit_symbol->get_active() ) { - zoom_in->set_sensitive( false ); - zoom_out->set_sensitive( false ); - } else { - zoom_in->set_sensitive( true); - zoom_out->set_sensitive( true ); - } - store->clear(); - SPDocument* symbol_document = selectedSymbols(); - icons_found = false; - //We are not in search all docs - if (search->get_text() != _("Searching...") && search->get_text() != _("Loading all symbols...")) { - Glib::ustring current = Glib::Markup::escape_text(symbol_set->get_active_text()); - if (current == ALLDOCS && search->get_text() != "") { - searchsymbols(); - return; - } - } - if (symbol_document) { - addSymbolsInDoc(symbol_document); - } else { - showOverlay(); - } +void SymbolsDialog::rebuild() +{ + if (!sensitive) { + return; + } + + if (fit_symbol->get_active()) { + zoom_in->set_sensitive(false); + zoom_out->set_sensitive(false); + } else { + zoom_in->set_sensitive(true); + zoom_out->set_sensitive(true); + } + store->clear(); + SPDocument *symbol_document = selectedSymbols(); + icons_found = false; + // We are not in search all docs + if (search->get_text() != _("Searching...") && search->get_text() != _("Loading all symbols...")) { + Glib::ustring current = Glib::Markup::escape_text(symbol_set->get_active_text()); + if (current == ALLDOCS && search->get_text() != "") { + searchsymbols(); + return; + } + } + if (symbol_document) { + addSymbolsInDoc(symbol_document); + } else { + showOverlay(); + } } -void SymbolsDialog::showOverlay() { - Glib::ustring current = Glib::Markup::escape_text(symbol_set->get_active_text()); - if (current == ALLDOCS && !l.size()) - { - overlay_icon->hide(); - if (!all_docs_processed ) { - overlay_icon->show(); - overlay_title->set_markup(Glib::ustring("<span size=\"large\">") + - Glib::ustring(_("Search in all symbol sets...")) + Glib::ustring("</span>")); - overlay_desc->set_markup(Glib::ustring("<span size=\"small\">") + - Glib::ustring(_("The first search can be slow.")) + Glib::ustring("</span>")); +void SymbolsDialog::showOverlay() +{ + Glib::ustring current = Glib::Markup::escape_text(symbol_set->get_active_text()); + if (current == ALLDOCS && !l.size()) { + overlay_icon->hide(); + if (!all_docs_processed) { + overlay_icon->show(); + overlay_title->set_markup(Glib::ustring("<span size=\"large\">") + + Glib::ustring(_("Search in all symbol sets...")) + Glib::ustring("</span>")); + overlay_desc->set_markup(Glib::ustring("<span size=\"small\">") + + Glib::ustring(_("The first search can be slow.")) + Glib::ustring("</span>")); + } else if (!icons_found && !search_str.empty()) { + overlay_title->set_markup(Glib::ustring("<span size=\"large\">") + Glib::ustring(_("No symbols found.")) + + Glib::ustring("</span>")); + overlay_desc->set_markup(Glib::ustring("<span size=\"small\">") + + Glib::ustring(_("Try a different search term.")) + Glib::ustring("</span>")); + } else { + overlay_icon->show(); + overlay_title->set_markup(Glib::ustring("<spansize=\"large\">") + + Glib::ustring(_("Search in all symbol sets...")) + Glib::ustring("</span>")); + overlay_desc->set_markup(Glib::ustring("<span size=\"small\">") + Glib::ustring("</span>")); + } + } else if (!number_symbols && (current != CURRENTDOC || !search_str.empty())) { + overlay_title->set_markup(Glib::ustring("<span size=\"large\">") + Glib::ustring(_("No symbols found.")) + + Glib::ustring("</span>")); + overlay_desc->set_markup( + Glib::ustring("<span size=\"small\">") + + Glib::ustring(_("Try a different search term,\nor switch to a different symbol set.")) + + Glib::ustring("</span>")); + } else if (!number_symbols && current == CURRENTDOC) { + overlay_title->set_markup(Glib::ustring("<span size=\"large\">") + Glib::ustring(_("No symbols found.")) + + Glib::ustring("</span>")); + overlay_desc->set_markup( + Glib::ustring("<span size=\"small\">") + + Glib::ustring(_("No symbols in current document.\nChoose a different symbol set\nor add a new symbol.")) + + Glib::ustring("</span>")); } else if (!icons_found && !search_str.empty()) { overlay_title->set_markup(Glib::ustring("<span size=\"large\">") + Glib::ustring(_("No symbols found.")) + Glib::ustring("</span>")); - overlay_desc->set_markup(Glib::ustring("<span size=\"small\">") + - Glib::ustring(_("Try a different search term.")) + Glib::ustring("</span>")); - } else { - overlay_icon->show(); - overlay_title->set_markup(Glib::ustring("<spansize=\"large\">") + - Glib::ustring(_("Search in all symbol sets...")) + Glib::ustring("</span>")); - overlay_desc->set_markup(Glib::ustring("<span size=\"small\">") + Glib::ustring("</span>")); + overlay_desc->set_markup( + Glib::ustring("<span size=\"small\">") + + Glib::ustring(_("Try a different search term,\nor switch to a different symbol set.")) + + Glib::ustring("</span>")); + } + gint width = scroller->get_allocated_width(); + gint height = scroller->get_allocated_height(); + if (previous_height != height || previous_width != width) { + previous_height = height; + previous_width = width; + overlay_opacity->set_size_request(width, height); + overlay_opacity->set(getOverlay(width, height)); + } + overlay_opacity->hide(); + overlay_icon->show(); + overlay_title->show(); + overlay_desc->show(); + if (l.size()) { + overlay_opacity->show(); + overlay_icon->hide(); + overlay_title->hide(); + overlay_desc->hide(); } - } else if (!number_symbols && (current != CURRENTDOC || !search_str.empty())) { - overlay_title->set_markup(Glib::ustring("<span size=\"large\">") + Glib::ustring(_("No symbols found.")) + - Glib::ustring("</span>")); - overlay_desc->set_markup(Glib::ustring("<span size=\"small\">") + - Glib::ustring(_("Try a different search term,\nor switch to a different symbol set.")) + - Glib::ustring("</span>")); - } else if (!number_symbols && current == CURRENTDOC) { - overlay_title->set_markup(Glib::ustring("<span size=\"large\">") + Glib::ustring(_("No symbols found.")) + - Glib::ustring("</span>")); - overlay_desc->set_markup( - Glib::ustring("<span size=\"small\">") + - Glib::ustring(_("No symbols in current document.\nChoose a different symbol set\nor add a new symbol.")) + - Glib::ustring("</span>")); - } else if (!icons_found && !search_str.empty()) { - overlay_title->set_markup(Glib::ustring("<span size=\"large\">") + Glib::ustring(_("No symbols found.")) + - Glib::ustring("</span>")); - overlay_desc->set_markup(Glib::ustring("<span size=\"small\">") + - Glib::ustring(_("Try a different search term,\nor switch to a different symbol set.")) + - Glib::ustring("</span>")); - } - gint width = scroller->get_allocated_width(); - gint height = scroller->get_allocated_height(); - if (previous_height != height || previous_width != width) { - previous_height = height; - previous_width = width; - overlay_opacity->set_size_request(width, height); - overlay_opacity->set(getOverlay(width, height)); - } - overlay_opacity->hide(); - overlay_icon->show(); - overlay_title->show(); - overlay_desc->show(); - if (l.size()) { - overlay_opacity->show(); - overlay_icon->hide(); - overlay_title->hide(); - overlay_desc->hide(); - } } -void SymbolsDialog::hideOverlay() { +void SymbolsDialog::hideOverlay() +{ overlay_opacity->hide(); overlay_icon->hide(); overlay_title->hide(); overlay_desc->hide(); } -void SymbolsDialog::insertSymbol() { - Inkscape::Verb *verb = Inkscape::Verb::get( SP_VERB_EDIT_SYMBOL ); - SPAction *action = verb->get_action(Inkscape::ActionContext( (Inkscape::UI::View::View *) current_desktop) ); - sp_action_perform (action, nullptr); +void SymbolsDialog::insertSymbol() +{ + Inkscape::Verb *verb = Inkscape::Verb::get(SP_VERB_EDIT_SYMBOL); + SPAction *action = verb->get_action(Inkscape::ActionContext((Inkscape::UI::View::View *)current_desktop)); + sp_action_perform(action, nullptr); } -void SymbolsDialog::revertSymbol() { - Inkscape::Verb *verb = Inkscape::Verb::get( SP_VERB_EDIT_UNSYMBOL ); - SPAction *action = verb->get_action(Inkscape::ActionContext( (Inkscape::UI::View::View *) current_desktop ) ); - sp_action_perform (action, nullptr); +void SymbolsDialog::revertSymbol() +{ + Inkscape::Verb *verb = Inkscape::Verb::get(SP_VERB_EDIT_UNSYMBOL); + SPAction *action = verb->get_action(Inkscape::ActionContext((Inkscape::UI::View::View *)current_desktop)); + sp_action_perform(action, nullptr); } -void SymbolsDialog::iconDragDataGet(const Glib::RefPtr<Gdk::DragContext>& /*context*/, Gtk::SelectionData& data, guint /*info*/, guint /*time*/) +void SymbolsDialog::iconDragDataGet(const Glib::RefPtr<Gdk::DragContext> & /*context*/, Gtk::SelectionData &data, + guint /*info*/, guint /*time*/) { - auto iconArray = icon_view->get_selected_items(); - - 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() ); - } + auto iconArray = icon_view->get_selected_items(); + 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*/) { - Glib::ustring doc_title = symbol_set->get_active_text(); - if (doc_title != ALLDOCS && !symbol_sets[doc_title] ) { - rebuild(); - } + Glib::ustring doc_title = symbol_set->get_active_text(); + if (doc_title != ALLDOCS && !symbol_sets[doc_title]) { + rebuild(); + } } -void SymbolsDialog::selectionChanged(Inkscape::Selection *selection) { - Glib::ustring symbol_id = selectedSymbolId(); - Glib::ustring doc_title = selectedSymbolDocTitle(); - if (!doc_title.empty()) { - SPDocument* symbol_document = symbol_sets[doc_title]; - if (!symbol_document) { - //we are in global search so get the original symbol document by title - symbol_document = selectedSymbols(); - } - if (symbol_document) { - SPObject* symbol = symbol_document->getObjectById(symbol_id); - if(symbol && !selection->includes(symbol)) { - icon_view->unselect_all(); - } +void SymbolsDialog::selectionChanged(Inkscape::Selection *selection) +{ + Glib::ustring symbol_id = selectedSymbolId(); + Glib::ustring doc_title = selectedSymbolDocTitle(); + if (!doc_title.empty()) { + SPDocument *symbol_document = symbol_sets[doc_title]; + if (!symbol_document) { + // we are in global search so get the original symbol document by title + symbol_document = selectedSymbols(); + } + if (symbol_document) { + SPObject *symbol = symbol_document->getObjectById(symbol_id); + if (symbol && !selection->includes(symbol)) { + icon_view->unselect_all(); + } + } } - } } void SymbolsDialog::documentReplaced(SPDesktop *desktop, SPDocument *document) { - if (current_desktop) { - for (auto &conn : instanceConns) { - conn.disconnect(); - } - } + if (current_desktop) { + for (auto &conn : instanceConns) { + conn.disconnect(); + } + } - current_desktop = desktop; - current_document = document; + current_desktop = desktop; + current_document = document; - if (!current_desktop) { - return; - } + if (!current_desktop) { + return; + } - instanceConns.emplace_back(symbol_set->signal_changed().connect(sigc::mem_fun(*this, &SymbolsDialog::rebuild))); + instanceConns.emplace_back(symbol_set->signal_changed().connect(sigc::mem_fun(*this, &SymbolsDialog::rebuild))); - instanceConns.emplace_back( - icon_view->signal_selection_changed().connect(sigc::mem_fun(*this, &SymbolsDialog::iconChanged))); + instanceConns.emplace_back( + icon_view->signal_selection_changed().connect(sigc::mem_fun(*this, &SymbolsDialog::iconChanged))); - SPDefs *defs = current_document->getDefs(); - instanceConns.emplace_back(defs->connectModified(sigc::mem_fun(*this, &SymbolsDialog::defsModified))); + SPDefs *defs = current_document->getDefs(); + instanceConns.emplace_back(defs->connectModified(sigc::mem_fun(*this, &SymbolsDialog::defsModified))); - instanceConns.emplace_back( - current_desktop->selection->connectChanged(sigc::mem_fun(*this, &SymbolsDialog::selectionChanged))); + instanceConns.emplace_back( + current_desktop->selection->connectChanged(sigc::mem_fun(*this, &SymbolsDialog::selectionChanged))); - instanceConns.emplace_back( - current_desktop->connectDocumentReplaced(sigc::mem_fun(*this, &SymbolsDialog::documentReplaced))); + instanceConns.emplace_back( + current_desktop->connectDocumentReplaced(sigc::mem_fun(*this, &SymbolsDialog::documentReplaced))); - if (symbol_sets[symbol_set->get_active_text()]) { - // Symbol set is not from Current document, no need to rebuild - return; - } + if (symbol_sets[symbol_set->get_active_text()]) { + // Symbol set is not from Current document, no need to rebuild + return; + } - rebuild(); + rebuild(); } -SPDocument* SymbolsDialog::selectedSymbols() { - /* OK, we know symbol name... now we need to copy it to clipboard, bon chance! */ - Glib::ustring doc_title = symbol_set->get_active_text(); - if (doc_title == ALLDOCS) { - return nullptr; - } - SPDocument* symbol_document = symbol_sets[doc_title]; - if( !symbol_document ) { - symbol_document = getSymbolsSet(doc_title).second; - // Symbol must be from Current Document (this method of checking should be language independent). - if( !symbol_document ) { - // Symbol must be from Current Document (this method of - // checking should be language independent). - symbol_document = current_document; - add_symbol->set_sensitive( true ); - remove_symbol->set_sensitive( true ); - } else { - add_symbol->set_sensitive( false ); - remove_symbol->set_sensitive( false ); +SPDocument *SymbolsDialog::selectedSymbols() +{ + /* OK, we know symbol name... now we need to copy it to clipboard, bon chance! */ + Glib::ustring doc_title = symbol_set->get_active_text(); + if (doc_title == ALLDOCS) { + return nullptr; + } + SPDocument *symbol_document = symbol_sets[doc_title]; + if (!symbol_document) { + symbol_document = getSymbolsSet(doc_title).second; + // Symbol must be from Current Document (this method of checking should be language independent). + if (!symbol_document) { + // Symbol must be from Current Document (this method of + // checking should be language independent). + symbol_document = current_document; + add_symbol->set_sensitive(true); + remove_symbol->set_sensitive(true); + } else { + add_symbol->set_sensitive(false); + remove_symbol->set_sensitive(false); + } } - } - return symbol_document; + return symbol_document; } -Glib::ustring SymbolsDialog::selectedSymbolId() { - - auto iconArray = icon_view->get_selected_items(); +Glib::ustring SymbolsDialog::selectedSymbolId() +{ + auto iconArray = icon_view->get_selected_items(); - 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(""); + 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(""); } -Glib::ustring SymbolsDialog::selectedSymbolDocTitle() { - - auto iconArray = icon_view->get_selected_items(); +Glib::ustring SymbolsDialog::selectedSymbolDocTitle() +{ + auto iconArray = icon_view->get_selected_items(); - if( !iconArray.empty() ) { - Gtk::TreeModel::Path const & path = *iconArray.begin(); - Gtk::ListStore::iterator row = store->get_iter(path); - return (*row)[getColumns()->symbol_doc_title]; - } - return Glib::ustring(""); + if (!iconArray.empty()) { + Gtk::TreeModel::Path const &path = *iconArray.begin(); + Gtk::ListStore::iterator row = store->get_iter(path); + return (*row)[getColumns()->symbol_doc_title]; + } + return Glib::ustring(""); } -Glib::ustring SymbolsDialog::documentTitle(SPDocument* symbol_doc) { - if (symbol_doc) { - SPRoot * root = symbol_doc->getRoot(); - gchar * title = root->title(); - if (title) { - return ellipsize(Glib::ustring(title), 33); +Glib::ustring SymbolsDialog::documentTitle(SPDocument *symbol_doc) +{ + if (symbol_doc) { + SPRoot *root = symbol_doc->getRoot(); + gchar *title = root->title(); + if (title) { + return ellipsize(Glib::ustring(title), 33); + } + g_free(title); } - g_free(title); - } - Glib::ustring current = symbol_set->get_active_text(); - if (current == CURRENTDOC) { - return current; - } - return _("Untitled document"); + Glib::ustring current = symbol_set->get_active_text(); + if (current == CURRENTDOC) { + return current; + } + return _("Untitled document"); } -void SymbolsDialog::iconChanged() { - - Glib::ustring symbol_id = selectedSymbolId(); - SPDocument* symbol_document = selectedSymbols(); - if (!symbol_document) { - //we are in global search so get the original symbol document by title - Glib::ustring doc_title = selectedSymbolDocTitle(); - if (!doc_title.empty()) { - symbol_document = symbol_sets[doc_title]; - } - } - if (symbol_document) { - SPObject* symbol = symbol_document->getObjectById(symbol_id); - - if( symbol ) { - if( symbol_document == current_document ) { - // Select the symbol on the canvas so it can be manipulated - current_desktop->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( symbol_document == current_document ) { - style = styleFromUse( symbol_id.c_str(), current_document ); - } else { - style = symbol_document->getReprRoot()->attribute("style"); +void SymbolsDialog::iconChanged() +{ + Glib::ustring symbol_id = selectedSymbolId(); + SPDocument *symbol_document = selectedSymbols(); + if (!symbol_document) { + // we are in global search so get the original symbol document by title + Glib::ustring doc_title = selectedSymbolDocTitle(); + if (!doc_title.empty()) { + symbol_document = symbol_sets[doc_title]; } - } + } + if (symbol_document) { + SPObject *symbol = symbol_document->getObjectById(symbol_id); + + if (symbol) { + if (symbol_document == current_document) { + // Select the symbol on the canvas so it can be manipulated + current_desktop->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 (symbol_document == current_document) { + style = styleFromUse(symbol_id.c_str(), current_document); + } else { + style = symbol_document->getReprRoot()->attribute("style"); + } + } - ClipboardManager *cm = ClipboardManager::get(); - cm->copySymbol(symbol->getRepr(), style, symbol_document == current_document); + ClipboardManager *cm = ClipboardManager::get(); + cm->copySymbol(symbol->getRepr(), style, symbol_document == current_document); + } } - } } #ifdef WITH_LIBVISIO #if WITH_LIBVISIO01 // Extend libvisio's native RVNGSVGDrawingGenerator with support for extracting stencil names (to be used as ID/title) -class REVENGE_API RVNGSVGDrawingGenerator_WithTitle : public RVNGSVGDrawingGenerator { - public: +class REVENGE_API RVNGSVGDrawingGenerator_WithTitle : public RVNGSVGDrawingGenerator +{ +public: RVNGSVGDrawingGenerator_WithTitle(RVNGStringVector &output, RVNGStringVector &titles, const RVNGString &nmSpace) - : RVNGSVGDrawingGenerator(output, nmSpace) - , _titles(titles) + : RVNGSVGDrawingGenerator(output, nmSpace) + , _titles(titles) {} void startPage(const RVNGPropertyList &propList) override { - RVNGSVGDrawingGenerator::startPage(propList); - if (propList["draw:name"]) { - _titles.append(propList["draw:name"]->getStr()); - } else { - _titles.append(""); - } + RVNGSVGDrawingGenerator::startPage(propList); + if (propList["draw:name"]) { + _titles.append(propList["draw:name"]->getStr()); + } else { + _titles.append(""); + } } - private: +private: RVNGStringVector &_titles; }; #endif // Read Visio stencil files -SPDocument* read_vss(Glib::ustring filename, Glib::ustring name ) { - gchar *fullname; - #ifdef _WIN32 +SPDocument *read_vss(Glib::ustring filename, Glib::ustring name) +{ + gchar *fullname; +#ifdef _WIN32 // RVNGFileStream uses fopen() internally which unfortunately only uses ANSI encoding on Windows // therefore attempt to convert uri to the system codepage // even if this is not possible the alternate short (8.3) file name will be used if available fullname = g_win32_locale_filename_from_utf8(filename.c_str()); - #else +#else fullname = strdup(filename.c_str()); - #endif +#endif - RVNGFileStream input(fullname); - g_free(fullname); + RVNGFileStream input(fullname); + g_free(fullname); - if (!libvisio::VisioDocument::isSupported(&input)) { - return nullptr; - } - RVNGStringVector output; - RVNGStringVector titles; + if (!libvisio::VisioDocument::isSupported(&input)) { + return nullptr; + } + RVNGStringVector output; + RVNGStringVector titles; #if WITH_LIBVISIO01 - RVNGSVGDrawingGenerator_WithTitle generator(output, titles, "svg"); + RVNGSVGDrawingGenerator_WithTitle generator(output, titles, "svg"); - if (!libvisio::VisioDocument::parseStencils(&input, &generator)) { + if (!libvisio::VisioDocument::parseStencils(&input, &generator)) { #else - if (!libvisio::VisioDocument::generateSVGStencils(&input, output)) { + if (!libvisio::VisioDocument::generateSVGStencils(&input, output)) { #endif - return nullptr; - } - if (output.empty()) { - return nullptr; - } - - // prepare a valid title for the symbol file - Glib::ustring title = Glib::Markup::escape_text(name); - // prepare a valid id prefix for symbols libvisio doesn't give us a name for - Glib::RefPtr<Glib::Regex> regex1 = Glib::Regex::create("[^a-zA-Z0-9_-]"); - Glib::ustring id = regex1->replace(name, 0, "_", Glib::REGEX_MATCH_PARTIAL); - - 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 += title; - tmpSVGOutput += "\n"; - tmpSVGOutput += " \n"; - - // Each "symbol" is in its own SVG file, we wrap with and merge into one file. - for (unsigned i=0; ireplace(titles[i].cstr(), 0, "_", Glib::REGEX_MATCH_PARTIAL); - } else { - ss << id << "_" << i; + return nullptr; + } + if (output.empty()) { + return nullptr; } - tmpSVGOutput += " \n"; + // prepare a valid title for the symbol file + Glib::ustring title = Glib::Markup::escape_text(name); + // prepare a valid id prefix for symbols libvisio doesn't give us a name for + Glib::RefPtr regex1 = Glib::Regex::create("[^a-zA-Z0-9_-]"); + Glib::ustring id = regex1->replace(name, 0, "_", Glib::REGEX_MATCH_PARTIAL); + + Glib::ustring tmpSVGOutput; + tmpSVGOutput += "\n"; + tmpSVGOutput += "\n"; + tmpSVGOutput += " "; + tmpSVGOutput += title; + tmpSVGOutput += "\n"; + tmpSVGOutput += " \n"; + + // Each "symbol" is in its own SVG file, we wrap with and merge into one file. + for (unsigned i = 0; i < output.size(); ++i) { + std::stringstream ss; + if (titles.size() == output.size() && titles[i] != "") { + // TODO: Do we need to check for duplicated titles? + ss << regex1->replace(titles[i].cstr(), 0, "_", Glib::REGEX_MATCH_PARTIAL); + } else { + ss << id << "_" << i; + } + + tmpSVGOutput += " \n"; #if WITH_LIBVISIO01 - if (titles.size() == output.size() && titles[i] != "") { - tmpSVGOutput += " " + Glib::ustring(RVNGString::escapeXML(titles[i].cstr()).cstr()) + "\n"; - } + if (titles.size() == output.size() && titles[i] != "") { + tmpSVGOutput += + " " + Glib::ustring(RVNGString::escapeXML(titles[i].cstr()).cstr()) + "\n"; + } #endif - std::istringstream iss( output[i].cstr() ); - std::string line; - while( std::getline( iss, line ) ) { - if( line.find( "svg:svg" ) == std::string::npos ) { - tmpSVGOutput += " " + line + "\n"; - } - } - - tmpSVGOutput += " \n"; - } + std::istringstream iss(output[i].cstr()); + std::string line; + while (std::getline(iss, line)) { + if (line.find("svg:svg") == std::string::npos) { + tmpSVGOutput += " " + line + "\n"; + } + } - tmpSVGOutput += " \n"; - tmpSVGOutput += "\n"; - return SPDocument::createNewDocFromMem( tmpSVGOutput.c_str(), strlen( tmpSVGOutput.c_str()), false ); + tmpSVGOutput += " \n"; + } + tmpSVGOutput += " \n"; + tmpSVGOutput += "\n"; + return SPDocument::createNewDocFromMem(tmpSVGOutput.c_str(), strlen(tmpSVGOutput.c_str()), false); } #endif /* Hunts preference directories for symbol files */ -void SymbolsDialog::getSymbolsTitle() { - +void SymbolsDialog::getSymbolsTitle() +{ using namespace Inkscape::IO::Resource; Glib::ustring title; number_docs = 0; - std::regex matchtitle (".*?(.*?)<(/| /)"); - for(auto &filename: get_filenames(SYMBOLS, {".svg", ".vss"})) { - if(Glib::str_has_suffix(filename, ".vss")) { - std::size_t found = filename.find_last_of("/\\"); - filename = filename.substr(found+1); - title = filename.erase(filename.rfind('.')); - if(title.empty()) { - title = _("Unnamed Symbols"); - } - symbol_sets[title]= nullptr; - ++number_docs; + std::regex matchtitle(".*?(.*?)<(/| /)"); + for (auto &filename : get_filenames(SYMBOLS, {".svg", ".vss"})) { + if (Glib::str_has_suffix(filename, ".vss")) { + std::size_t found = filename.find_last_of("/\\"); + filename = filename.substr(found + 1); + title = filename.erase(filename.rfind('.')); + if (title.empty()) { + title = _("Unnamed Symbols"); + } + symbol_sets[title] = nullptr; + ++number_docs; } else { - std::ifstream infile(filename); - std::string line; - while (std::getline(infile, line)) { - std::string title_res = std::regex_replace (line, matchtitle,"$1",std::regex_constants::format_no_copy); - if (!title_res.empty()) { - title_res = g_dpgettext2(nullptr, "Symbol", title_res.c_str()); - symbol_sets[ellipsize(Glib::ustring(title_res), 33)]= nullptr; - ++number_docs; - break; - } - std::string::size_type position_exit = line.find ("append(symbol_document_map.first); + for (auto const &symbol_document_map : symbol_sets) { + symbol_set->append(symbol_document_map.first); } } /* Hunts preference directories for symbol files */ -std::pair -SymbolsDialog::getSymbolsSet(Glib::ustring title) +std::pair SymbolsDialog::getSymbolsSet(Glib::ustring title) { - SPDocument* symbol_doc = nullptr; + SPDocument *symbol_doc = nullptr; Glib::ustring current = symbol_set->get_active_text(); if (current == CURRENTDOC) { - return std::make_pair(CURRENTDOC, symbol_doc); + return std::make_pair(CURRENTDOC, symbol_doc); } if (symbol_sets[title]) { - sensitive = false; - symbol_set->remove_all(); - symbol_set->append(CURRENTDOC); - symbol_set->append(ALLDOCS); - for(auto const &symbol_document_map : symbol_sets) { - if (CURRENTDOC != symbol_document_map.first) { - symbol_set->append(symbol_document_map.first); + sensitive = false; + symbol_set->remove_all(); + symbol_set->append(CURRENTDOC); + symbol_set->append(ALLDOCS); + for (auto const &symbol_document_map : symbol_sets) { + if (CURRENTDOC != symbol_document_map.first) { + symbol_set->append(symbol_document_map.first); + } } - } - symbol_set->set_active_text(title); - sensitive = true; - return std::make_pair(title, symbol_sets[title]); + symbol_set->set_active_text(title); + sensitive = true; + return std::make_pair(title, symbol_sets[title]); } using namespace Inkscape::IO::Resource; Glib::ustring new_title; - std::regex matchtitle (".*?(.*?)<(/| /)"); - for(auto &filename: get_filenames(SYMBOLS, {".svg", ".vss"})) { - if(Glib::str_has_suffix(filename, ".vss")) { + std::regex matchtitle(".*?(.*?)<(/| /)"); + for (auto &filename : get_filenames(SYMBOLS, {".svg", ".vss"})) { + if (Glib::str_has_suffix(filename, ".vss")) { #ifdef WITH_LIBVISIO - std::size_t pos = filename.find_last_of("/\\"); - Glib::ustring filename_short = ""; - if (pos != std::string::npos) { - filename_short = filename.substr(pos+1); - } - if (filename_short == title + ".vss") { - new_title = title; - symbol_doc = read_vss(Glib::ustring(filename), title); - } + std::size_t pos = filename.find_last_of("/\\"); + Glib::ustring filename_short = ""; + if (pos != std::string::npos) { + filename_short = filename.substr(pos + 1); + } + if (filename_short == title + ".vss") { + new_title = title; + symbol_doc = read_vss(Glib::ustring(filename), title); + } #endif } else { std::ifstream infile(filename); std::string line; while (std::getline(infile, line)) { - std::string title_res = std::regex_replace (line, matchtitle,"$1",std::regex_constants::format_no_copy); + std::string title_res = + std::regex_replace(line, matchtitle, "$1", std::regex_constants::format_no_copy); if (!title_res.empty()) { - title_res = g_dpgettext2(nullptr, "Symbol", title_res.c_str()); - new_title = ellipsize(Glib::ustring(title_res), 33); + title_res = g_dpgettext2(nullptr, "Symbol", title_res.c_str()); + new_title = ellipsize(Glib::ustring(title_res), 33); } std::size_t pos = filename.find_last_of("/\\"); Glib::ustring filename_short = ""; if (pos != std::string::npos) { - filename_short = filename.substr(pos+1); + filename_short = filename.substr(pos + 1); } if (title == new_title || filename_short == title + ".svg") { new_title = title; - if(Glib::str_has_suffix(filename, ".svg")) { + if (Glib::str_has_suffix(filename, ".svg")) { symbol_doc = SPDocument::createNewDoc(filename.c_str(), FALSE); } } if (symbol_doc) { break; } - std::string::size_type position_exit = line.find ("remove_all(); - symbol_set->append(CURRENTDOC); - symbol_set->append(ALLDOCS); - for(auto const &symbol_document_map : symbol_sets) { - if (CURRENTDOC != symbol_document_map.first) { - symbol_set->append(symbol_document_map.first); + if (symbol_doc) { + symbol_sets.erase(title); + symbol_sets[new_title] = symbol_doc; + sensitive = false; + symbol_set->remove_all(); + symbol_set->append(CURRENTDOC); + symbol_set->append(ALLDOCS); + for (auto const &symbol_document_map : symbol_sets) { + if (CURRENTDOC != symbol_document_map.first) { + symbol_set->append(symbol_document_map.first); + } } - } - symbol_set->set_active_text(new_title); - sensitive = true; + symbol_set->set_active_text(new_title); + sensitive = true; } return std::make_pair(new_title, symbol_doc); } -void SymbolsDialog::symbolsInDocRecursive (SPObject *r, std::map > &l, Glib::ustring doc_title) +void SymbolsDialog::symbolsInDocRecursive(SPObject *r, std::map> &l, + Glib::ustring doc_title) { - if(!r) return; - - // Stop multiple counting of same symbol - if ( dynamic_cast(r) ) { - return; - } - - if ( dynamic_cast(r)) { - Glib::ustring id = r->getAttribute("id"); - gchar * title = r->title(); - if(title) { - l[doc_title + title + id] = std::make_pair(doc_title,dynamic_cast(r)); - } else { - l[Glib::ustring(_("notitle_")) + id] = std::make_pair(doc_title,dynamic_cast(r)); + if (!r) + return; + + // Stop multiple counting of same symbol + if (dynamic_cast(r)) { + return; + } + + if (dynamic_cast(r)) { + Glib::ustring id = r->getAttribute("id"); + gchar *title = r->title(); + if (title) { + l[doc_title + title + id] = std::make_pair(doc_title, dynamic_cast(r)); + } else { + l[Glib::ustring(_("notitle_")) + id] = std::make_pair(doc_title, dynamic_cast(r)); + } + g_free(title); + } + for (auto &child : r->children) { + symbolsInDocRecursive(&child, l, doc_title); } - g_free(title); - } - for (auto& child: r->children) { - symbolsInDocRecursive(&child, l, doc_title); - } } -std::map > -SymbolsDialog::symbolsInDoc( SPDocument* symbol_document, Glib::ustring doc_title) +std::map> SymbolsDialog::symbolsInDoc(SPDocument *symbol_document, + Glib::ustring doc_title) { - - std::map > l; - if (symbol_document) { - symbolsInDocRecursive (symbol_document->getRoot(), l , doc_title); - } - return l; + std::map> l; + if (symbol_document) { + symbolsInDocRecursive(symbol_document->getRoot(), l, doc_title); + } + return l; } -void SymbolsDialog::useInDoc (SPObject *r, std::vector &l) +void SymbolsDialog::useInDoc(SPObject *r, std::vector &l) { + if (dynamic_cast(r)) { + l.push_back(dynamic_cast(r)); + } - if ( dynamic_cast(r) ) { - l.push_back(dynamic_cast(r)); - } - - for (auto& child: r->children) { - useInDoc( &child, l ); - } + for (auto &child : r->children) { + useInDoc(&child, l); + } } -std::vector SymbolsDialog::useInDoc( SPDocument* useDocument) { - std::vector l; - useInDoc (useDocument->getRoot(), l); - return l; +std::vector SymbolsDialog::useInDoc(SPDocument *useDocument) +{ + std::vector l; + useInDoc(useDocument->getRoot(), l); + return l; } // Returns style from first element found that references id. // This is a last ditch effort to find a style. -gchar const* SymbolsDialog::styleFromUse( gchar const* id, SPDocument* document) { - - gchar const* style = nullptr; - std::vector l = useInDoc( document ); - for( auto use:l ) { - if ( 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; +gchar const *SymbolsDialog::styleFromUse(gchar const *id, SPDocument *document) +{ + gchar const *style = nullptr; + std::vector l = useInDoc(document); + for (auto use : l) { + if (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; + return style; } -void SymbolsDialog::clearSearch() +void SymbolsDialog::clearSearch() { - if(search->get_text().empty() && sensitive) { - enableWidgets(false); - search_str = ""; - store->clear(); - SPDocument* symbol_document = selectedSymbols(); - if (symbol_document) { - //We are not in search all docs - icons_found = false; - addSymbolsInDoc(symbol_document); - } else { - showOverlay(); - enableWidgets(true); + if (search->get_text().empty() && sensitive) { + enableWidgets(false); + search_str = ""; + store->clear(); + SPDocument *symbol_document = selectedSymbols(); + if (symbol_document) { + // We are not in search all docs + icons_found = false; + addSymbolsInDoc(symbol_document); + } else { + showOverlay(); + enableWidgets(true); + } } - } } -void SymbolsDialog::enableWidgets(bool enable) +void SymbolsDialog::enableWidgets(bool enable) { - symbol_set->set_sensitive(enable); - search->set_sensitive(enable); - tools ->set_sensitive(enable); + symbol_set->set_sensitive(enable); + search->set_sensitive(enable); + tools->set_sensitive(enable); } -void SymbolsDialog::beforeSearch(GdkEventKey* evt) +void SymbolsDialog::beforeSearch(GdkEventKey *evt) { - sensitive = false; - search_str = search->get_text().lowercase(); - if (evt->keyval != GDK_KEY_Return) { - return; - } - searchsymbols(); + sensitive = false; + search_str = search->get_text().lowercase(); + if (evt->keyval != GDK_KEY_Return) { + return; + } + searchsymbols(); } void SymbolsDialog::searchsymbols() @@ -1060,186 +1066,190 @@ void SymbolsDialog::searchsymbols() } } -void SymbolsDialog::unsensitive(GdkEventKey* evt) +void SymbolsDialog::unsensitive(GdkEventKey *evt) { - sensitive = true; + sensitive = true; } -bool SymbolsDialog::callbackSymbols(){ - if (l.size()) { - showOverlay(); - for (auto symbol_data = l.begin(); symbol_data != l.end();) { - Glib::ustring doc_title = symbol_data->second.first; - SPSymbol * symbol = symbol_data->second.second; - counter_symbols ++; - gchar *symbol_title_char = symbol->title(); - gchar *symbol_desc_char = symbol->description(); - bool found = false; - if (symbol_title_char) { - Glib::ustring symbol_title = Glib::ustring(symbol_title_char).lowercase(); - auto pos = symbol_title.rfind(search_str); - if (pos != std::string::npos) { - found = true; +bool SymbolsDialog::callbackSymbols() +{ + if (l.size()) { + showOverlay(); + for (auto symbol_data = l.begin(); symbol_data != l.end();) { + Glib::ustring doc_title = symbol_data->second.first; + SPSymbol *symbol = symbol_data->second.second; + counter_symbols++; + gchar *symbol_title_char = symbol->title(); + gchar *symbol_desc_char = symbol->description(); + bool found = false; + if (symbol_title_char) { + Glib::ustring symbol_title = Glib::ustring(symbol_title_char).lowercase(); + auto pos = symbol_title.rfind(search_str); + if (pos != std::string::npos) { + found = true; + } + if (!found && symbol_desc_char) { + Glib::ustring symbol_desc = Glib::ustring(symbol_desc_char).lowercase(); + auto pos = symbol_desc.rfind(search_str); + if (pos != std::string::npos) { + found = true; + } + } + } + if (symbol && (search_str.empty() || found)) { + addSymbol(symbol, doc_title); + icons_found = true; + } + + progress_bar->set_fraction(((100.0 / number_symbols) * counter_symbols) / 100.0); + symbol_data = l.erase(l.begin()); + // to get more items and best performance + int modulus = number_symbols > 200 ? 50 : (number_symbols / 4); + g_free(symbol_title_char); + g_free(symbol_desc_char); + if (modulus && counter_symbols % modulus == 0 && !l.empty()) { + return true; + } } - if (!found && symbol_desc_char) { - Glib::ustring symbol_desc = Glib::ustring(symbol_desc_char).lowercase(); - auto pos = symbol_desc.rfind(search_str); - if (pos != std::string::npos) { - found = true; - } + if (!icons_found && !search_str.empty()) { + showOverlay(); + } else { + hideOverlay(); } - } - if (symbol && (search_str.empty() || found)) { - addSymbol( symbol, doc_title); - icons_found = true; - } - - progress_bar->set_fraction(((100.0/number_symbols) * counter_symbols)/100.0); - symbol_data = l.erase(l.begin()); - //to get more items and best performance - int modulus = number_symbols > 200 ? 50 : (number_symbols/4); - g_free(symbol_title_char); - g_free(symbol_desc_char); - if (modulus && counter_symbols % modulus == 0 && !l.empty()) { - return true; - } - } - if (!icons_found && !search_str.empty()) { - showOverlay(); - } else { - hideOverlay(); + progress_bar->set_fraction(0); + sensitive = false; + search->set_text(search_str); + sensitive = true; + enableWidgets(true); + return false; } - progress_bar->set_fraction(0); - sensitive = false; - search->set_text(search_str); - sensitive = true; - enableWidgets(true); - return false; - } - return true; + return true; } -bool SymbolsDialog::callbackAllSymbols(){ - Glib::ustring current = symbol_set->get_active_text(); - if (current == ALLDOCS && search->get_text() == _("Loading all symbols...")) { - size_t counter = 0; - std::map symbol_sets_tmp = symbol_sets; - for(auto const &symbol_document_map : symbol_sets_tmp) { - ++counter; - SPDocument* symbol_document = symbol_document_map.second; - if (symbol_document) { - continue; - } - symbol_document = getSymbolsSet(symbol_document_map.first).second; - symbol_set->set_active_text(ALLDOCS); - if (!symbol_document) { - continue; - } - progress_bar->set_fraction(((100.0/number_docs) * counter)/100.0); - return true; +bool SymbolsDialog::callbackAllSymbols() +{ + Glib::ustring current = symbol_set->get_active_text(); + if (current == ALLDOCS && search->get_text() == _("Loading all symbols...")) { + size_t counter = 0; + std::map symbol_sets_tmp = symbol_sets; + for (auto const &symbol_document_map : symbol_sets_tmp) { + ++counter; + SPDocument *symbol_document = symbol_document_map.second; + if (symbol_document) { + continue; + } + symbol_document = getSymbolsSet(symbol_document_map.first).second; + symbol_set->set_active_text(ALLDOCS); + if (!symbol_document) { + continue; + } + progress_bar->set_fraction(((100.0 / number_docs) * counter) / 100.0); + return true; + } + symbol_sets_tmp.clear(); + hideOverlay(); + all_docs_processed = true; + addSymbols(); + progress_bar->set_fraction(0); + search->set_text("Searching..."); + return false; } - symbol_sets_tmp.clear(); - hideOverlay(); - all_docs_processed = true; - addSymbols(); - progress_bar->set_fraction(0); - search->set_text("Searching..."); - return false; - } - return true; + return true; } -Glib::ustring SymbolsDialog::ellipsize(Glib::ustring data, size_t limit) { +Glib::ustring SymbolsDialog::ellipsize(Glib::ustring data, size_t limit) +{ if (data.length() > limit) { - data = data.substr(0, limit-3); - return data + "..."; + data = data.substr(0, limit - 3); + return data + "..."; } return data; } -void SymbolsDialog::addSymbolsInDoc(SPDocument* symbol_document) { - - if (!symbol_document) { - return; //Search all - } - Glib::ustring doc_title = documentTitle(symbol_document); - progress_bar->set_fraction(0.0); - counter_symbols = 0; - l = symbolsInDoc(symbol_document, doc_title); - number_symbols = l.size(); - if (!number_symbols) { - sensitive = false; - search->set_text(search_str); - sensitive = true; - enableWidgets(true); - idleconn.disconnect(); - showOverlay(); - } else { - idleconn.disconnect(); - idleconn = Glib::signal_idle().connect( sigc::mem_fun(*this, &SymbolsDialog::callbackSymbols)); - } -} - -void SymbolsDialog::addSymbols() { - store->clear(); - icons_found = false; - for(auto const &symbol_document_map : symbol_sets) { - SPDocument* symbol_document = symbol_document_map.second; +void SymbolsDialog::addSymbolsInDoc(SPDocument *symbol_document) +{ if (!symbol_document) { - continue; + return; // Search all } Glib::ustring doc_title = documentTitle(symbol_document); - std::map > l_tmp = symbolsInDoc(symbol_document, doc_title); - for(auto &p : l_tmp ) { - l[p.first] = p.second; + progress_bar->set_fraction(0.0); + counter_symbols = 0; + l = symbolsInDoc(symbol_document, doc_title); + number_symbols = l.size(); + if (!number_symbols) { + sensitive = false; + search->set_text(search_str); + sensitive = true; + enableWidgets(true); + idleconn.disconnect(); + showOverlay(); + } else { + idleconn.disconnect(); + idleconn = Glib::signal_idle().connect(sigc::mem_fun(*this, &SymbolsDialog::callbackSymbols)); } - l_tmp.clear(); - } - counter_symbols = 0; - progress_bar->set_fraction(0.0); - number_symbols = l.size(); - if (!number_symbols) { - showOverlay(); - idleconn.disconnect(); - sensitive = false; - search->set_text(search_str); - sensitive = true; - enableWidgets(true); - } else { - idleconn.disconnect(); - idleconn = Glib::signal_idle().connect( sigc::mem_fun(*this, &SymbolsDialog::callbackSymbols)); - } } -void SymbolsDialog::addSymbol( SPObject* symbol, Glib::ustring doc_title) +void SymbolsDialog::addSymbols() { - gchar const *id = symbol->getRepr()->attribute("id"); - - if (doc_title.empty()) { - doc_title = CURRENTDOC; - } else { - doc_title = g_dpgettext2(nullptr, "Symbol", doc_title.c_str()); - } - - Glib::ustring symbol_title; - gchar *title = symbol->title(); // From title element - if (title) { - symbol_title = Glib::ustring::compose("%1 (%2)", g_dpgettext2(nullptr, "Symbol", title), doc_title.c_str()); - } else { - symbol_title = Glib::ustring::compose("%1 %2 (%3)", _("Symbol without title"), Glib::ustring(id), doc_title); - } - g_free(title); - - Glib::RefPtr pixbuf = drawSymbol( symbol ); - if( pixbuf ) { - Gtk::ListStore::iterator row = store->append(); - SymbolColumns* columns = getColumns(); - (*row)[columns->symbol_id] = Glib::ustring( id ); - (*row)[columns->symbol_title] = Glib::Markup::escape_text(symbol_title); - (*row)[columns->symbol_doc_title] = Glib::Markup::escape_text(doc_title); - (*row)[columns->symbol_image] = pixbuf; - delete columns; - } + store->clear(); + icons_found = false; + for (auto const &symbol_document_map : symbol_sets) { + SPDocument *symbol_document = symbol_document_map.second; + if (!symbol_document) { + continue; + } + Glib::ustring doc_title = documentTitle(symbol_document); + std::map> l_tmp = symbolsInDoc(symbol_document, doc_title); + for (auto &p : l_tmp) { + l[p.first] = p.second; + } + l_tmp.clear(); + } + counter_symbols = 0; + progress_bar->set_fraction(0.0); + number_symbols = l.size(); + if (!number_symbols) { + showOverlay(); + idleconn.disconnect(); + sensitive = false; + search->set_text(search_str); + sensitive = true; + enableWidgets(true); + } else { + idleconn.disconnect(); + idleconn = Glib::signal_idle().connect(sigc::mem_fun(*this, &SymbolsDialog::callbackSymbols)); + } +} + +void SymbolsDialog::addSymbol(SPObject *symbol, Glib::ustring doc_title) +{ + gchar const *id = symbol->getRepr()->attribute("id"); + + if (doc_title.empty()) { + doc_title = CURRENTDOC; + } else { + doc_title = g_dpgettext2(nullptr, "Symbol", doc_title.c_str()); + } + + Glib::ustring symbol_title; + gchar *title = symbol->title(); // From title element + if (title) { + symbol_title = Glib::ustring::compose("%1 (%2)", g_dpgettext2(nullptr, "Symbol", title), doc_title.c_str()); + } else { + symbol_title = Glib::ustring::compose("%1 %2 (%3)", _("Symbol without title"), Glib::ustring(id), doc_title); + } + g_free(title); + + Glib::RefPtr pixbuf = drawSymbol(symbol); + if (pixbuf) { + Gtk::ListStore::iterator row = store->append(); + SymbolColumns *columns = getColumns(); + (*row)[columns->symbol_id] = Glib::ustring(id); + (*row)[columns->symbol_title] = Glib::Markup::escape_text(symbol_title); + (*row)[columns->symbol_doc_title] = Glib::Markup::escape_text(doc_title); + (*row)[columns->symbol_image] = pixbuf; + delete columns; + } } /* @@ -1251,89 +1261,92 @@ void SymbolsDialog::addSymbol( SPObject* symbol, Glib::ustring doc_title) * element. Each real symbol is swapped in for the dummy symbol and * the temporary document is rendered. */ -Glib::RefPtr -SymbolsDialog::drawSymbol(SPObject *symbol) +Glib::RefPtr SymbolsDialog::drawSymbol(SPObject *symbol) { - // Create a copy repr of the symbol with id="the_symbol" - Inkscape::XML::Document *xml_doc = preview_document->getReprDoc(); - Inkscape::XML::Node *repr = symbol->getRepr()->duplicate(xml_doc); - repr->setAttribute("id", "the_symbol"); - - // Replace old "the_symbol" in preview_document by new. - Inkscape::XML::Node *root = preview_document->getReprRoot(); - SPObject *symbol_old = preview_document->getObjectById("the_symbol"); - if (symbol_old) { - symbol_old->deleteObject(false); - } - - // First look for default style stored in - gchar const* style = repr->attribute("inkscape:symbol-style"); - if( !style ) { - // If no default style in , look in documents. - if( symbol->document == current_document ) { - gchar const *id = symbol->getRepr()->attribute("id"); - style = styleFromUse( id, symbol->document ); - } else { - style = symbol->document->getReprRoot()->attribute("style"); + // Create a copy repr of the symbol with id="the_symbol" + Inkscape::XML::Document *xml_doc = preview_document->getReprDoc(); + Inkscape::XML::Node *repr = symbol->getRepr()->duplicate(xml_doc); + repr->setAttribute("id", "the_symbol"); + + // Replace old "the_symbol" in preview_document by new. + Inkscape::XML::Node *root = preview_document->getReprRoot(); + SPObject *symbol_old = preview_document->getObjectById("the_symbol"); + if (symbol_old) { + symbol_old->deleteObject(false); + } + + // First look for default style stored in + gchar const *style = repr->attribute("inkscape:symbol-style"); + if (!style) { + // If no default style in , look in documents. + if (symbol->document == current_document) { + gchar const *id = symbol->getRepr()->attribute("id"); + style = styleFromUse(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 . 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 preview_document documents saved (useful for debugging) - // FILE *fp = fopen (g_strconcat(id, ".svg", NULL), "w"); - // sp_repr_save_stream(preview_document->getReprDoc(), fp); - // fclose (fp); - - // Make sure preview_document is up-to-date. - preview_document->getRoot()->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - preview_document->ensureUpToDate(); - - // Make sure we have symbol in preview_document - SPObject *object_temp = preview_document->getObjectById( "the_use" ); - preview_document->getRoot()->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); - preview_document->ensureUpToDate(); - - SPItem *item = dynamic_cast(object_temp); - g_assert(item != nullptr); - unsigned psize = SYMBOL_ICON_SIZES[pack_size]; - - Glib::RefPtr pixbuf(nullptr); - // 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( fit_symbol->get_active() ) - scale = psize / ceil(std::max(width, height)); - else - scale = pow( 2.0, scale_factor/2.0 ) * psize / 32.0; - - pixbuf = Glib::wrap(render_pixbuf(renderDrawing, scale, *dbox, psize)); - } - - return pixbuf; + // 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 . 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 preview_document documents saved (useful for debugging) + // FILE *fp = fopen (g_strconcat(id, ".svg", NULL), "w"); + // sp_repr_save_stream(preview_document->getReprDoc(), fp); + // fclose (fp); + + // Make sure preview_document is up-to-date. + preview_document->getRoot()->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + preview_document->ensureUpToDate(); + + // Make sure we have symbol in preview_document + SPObject *object_temp = preview_document->getObjectById("the_use"); + preview_document->getRoot()->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + preview_document->ensureUpToDate(); + + SPItem *item = dynamic_cast(object_temp); + g_assert(item != nullptr); + unsigned psize = SYMBOL_ICON_SIZES[pack_size]; + + Glib::RefPtr pixbuf(nullptr); + // 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 (fit_symbol->get_active()) + scale = psize / ceil(std::max(width, height)); + else + scale = pow(2.0, scale_factor / 2.0) * psize / 32.0; + + pixbuf = Glib::wrap(render_pixbuf(renderDrawing, scale, *dbox, psize)); + } + + return pixbuf; } /* @@ -1341,38 +1354,36 @@ SymbolsDialog::drawSymbol(SPObject *symbol) * Symbols are by default not rendered so a element is * provided. */ -SPDocument* SymbolsDialog::symbolsPreviewDoc() +SPDocument *SymbolsDialog::symbolsPreviewDoc() { - // BUG: must be inside - gchar const *buffer = -"" -" " -" " -" " -" " -""; - return SPDocument::createNewDocFromMem( buffer, strlen(buffer), FALSE ); + // BUG: must be inside + gchar const *buffer = "" + " " + " " + " " + " " + ""; + return SPDocument::createNewDocFromMem(buffer, strlen(buffer), FALSE); } /* * Update image widgets */ -Glib::RefPtr -SymbolsDialog::getOverlay(gint width, gint height) +Glib::RefPtr SymbolsDialog::getOverlay(gint width, gint height) { - cairo_surface_t *surface; - cairo_t *cr; - surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); - cr = cairo_create (surface); - cairo_set_source_rgba(cr, 1, 1, 1, 0.75); - cairo_rectangle (cr, 0, 0, width, height); - cairo_fill (cr); - GdkPixbuf* pixbuf = ink_pixbuf_create_from_cairo_surface(surface); - cairo_destroy (cr); - return Glib::wrap(pixbuf); + cairo_surface_t *surface; + cairo_t *cr; + surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); + cr = cairo_create(surface); + cairo_set_source_rgba(cr, 1, 1, 1, 0.75); + cairo_rectangle(cr, 0, 0, width, height); + cairo_fill(cr); + GdkPixbuf *pixbuf = ink_pixbuf_create_from_cairo_surface(surface); + cairo_destroy(cr); + return Glib::wrap(pixbuf); } void SymbolsDialog::setDesktop(SPDesktop *desktop) @@ -1382,9 +1393,9 @@ void SymbolsDialog::setDesktop(SPDesktop *desktop) documentReplaced(desktop, desktop ? desktop->getDocument() : nullptr); } -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/symbols.h b/src/ui/dialog/symbols.h index 1b4df5ae8f60942e9ee92ef32ee92b51bec1f91f..c6bf2454f1ac16a19c74309697dc9dd4eaa7aef2 100644 --- a/src/ui/dialog/symbols.h +++ b/src/ui/dialog/symbols.h @@ -15,9 +15,8 @@ #ifndef INKSCAPE_UI_DIALOG_SYMBOLS_H #define INKSCAPE_UI_DIALOG_SYMBOLS_H -#include - #include +#include #include "display/drawing.h" #include "include/gtkmm_version.h" @@ -55,18 +54,18 @@ class SymbolColumns; // For Gtk::ListStore const int SYMBOL_ICON_SIZES[] = {16, 24, 32, 48, 64}; -class SymbolsDialog : public UI::Widget::Panel { - +class SymbolsDialog : public UI::Widget::Panel +{ public: - SymbolsDialog( gchar const* prefsPath = "/dialogs/symbols" ); + SymbolsDialog(gchar const *prefsPath = "/dialogs/symbols"); ~SymbolsDialog() override; void setDesktop(SPDesktop *) override; - static SymbolsDialog& getInstance(); + static SymbolsDialog &getInstance(); private: - SymbolsDialog(SymbolsDialog const &) = delete; // no copy + SymbolsDialog(SymbolsDialog const &) = delete; // no copy SymbolsDialog &operator=(SymbolsDialog const &) = delete; // no assign static SymbolColumns *getColumns(); @@ -84,25 +83,28 @@ private: void defsModified(SPObject *object, guint flags); void selectionChanged(Inkscape::Selection *selection); void documentReplaced(SPDesktop *desktop, SPDocument *document); - SPDocument* selectedSymbols(); + SPDocument *selectedSymbols(); Glib::ustring selectedSymbolId(); Glib::ustring selectedSymbolDocTitle(); void iconChanged(); - void iconDragDataGet(const Glib::RefPtr& context, Gtk::SelectionData& selection_data, guint info, guint time); + void iconDragDataGet(const Glib::RefPtr &context, Gtk::SelectionData &selection_data, guint info, + guint time); void getSymbolsTitle(); - Glib::ustring documentTitle(SPDocument* doc); - std::pair getSymbolsSet(Glib::ustring title); - void addSymbol( SPObject* symbol, Glib::ustring doc_title); - SPDocument* symbolsPreviewDoc(); - void symbolsInDocRecursive (SPObject *r, std::map > &l, Glib::ustring doc_title); - std::map > symbolsInDoc( SPDocument* document, Glib::ustring doc_title); - void useInDoc(SPObject *r, std::vector &l); - std::vector useInDoc( SPDocument* document); - void beforeSearch(GdkEventKey* evt); - void unsensitive(GdkEventKey* evt); + Glib::ustring documentTitle(SPDocument *doc); + std::pair getSymbolsSet(Glib::ustring title); + void addSymbol(SPObject *symbol, Glib::ustring doc_title); + SPDocument *symbolsPreviewDoc(); + void symbolsInDocRecursive(SPObject *r, std::map> &l, + Glib::ustring doc_title); + std::map> symbolsInDoc(SPDocument *document, + Glib::ustring doc_title); + void useInDoc(SPObject *r, std::vector &l); + std::vector useInDoc(SPDocument *document); + void beforeSearch(GdkEventKey *evt); + void unsensitive(GdkEventKey *evt); void searchsymbols(); void addSymbols(); - void addSymbolsInDoc(SPDocument* document); + void addSymbolsInDoc(SPDocument *document); void showOverlay(); void hideOverlay(); void clearSearch(); @@ -110,12 +112,12 @@ private: bool callbackAllSymbols(); void enableWidgets(bool enable); Glib::ustring ellipsize(Glib::ustring data, size_t limit); - gchar const* styleFromUse( gchar const* id, SPDocument* document); + gchar const *styleFromUse(gchar const *id, SPDocument *document); Glib::RefPtr drawSymbol(SPObject *symbol); Glib::RefPtr getOverlay(gint width, gint height); /* Keep track of all symbol template documents */ - std::map symbol_sets; - std::map > l; + std::map symbol_sets; + std::map> l; // Index into sizes which is selected int pack_size; // Scale factor @@ -130,32 +132,32 @@ private: bool icons_found; Glib::RefPtr store; Glib::ustring search_str; - Gtk::ComboBoxText* symbol_set; - Gtk::ProgressBar* progress_bar; - Gtk::HBox* progress; - Gtk::SearchEntry* search; - Gtk::IconView* icon_view; - Gtk::Button* add_symbol; - Gtk::Button* remove_symbol; - Gtk::Button* zoom_in; - Gtk::Button* zoom_out; - Gtk::Button* more; - Gtk::Button* fewer; - Gtk::HBox* tools; - Gtk::Overlay* overlay; - Gtk::Image* overlay_icon; - Gtk::Image* overlay_opacity; - Gtk::Label* overlay_title; - Gtk::Label* overlay_desc; + Gtk::ComboBoxText *symbol_set; + Gtk::ProgressBar *progress_bar; + Gtk::HBox *progress; + Gtk::SearchEntry *search; + Gtk::IconView *icon_view; + Gtk::Button *add_symbol; + Gtk::Button *remove_symbol; + Gtk::Button *zoom_in; + Gtk::Button *zoom_out; + Gtk::Button *more; + Gtk::Button *fewer; + Gtk::HBox *tools; + Gtk::Overlay *overlay; + Gtk::Image *overlay_icon; + Gtk::Image *overlay_opacity; + Gtk::Label *overlay_title; + Gtk::Label *overlay_desc; Gtk::ScrolledWindow *scroller; - Gtk::ToggleButton* fit_symbol; + Gtk::ToggleButton *fit_symbol; Gtk::IconSize iconsize; - SPDesktop* current_desktop; - SPDocument* current_document; - SPDocument* preview_document; /* Document to render single symbol */ - + SPDesktop *current_desktop; + SPDocument *current_document; + SPDocument *preview_document; /* Document to render single symbol */ + sigc::connection idleconn; - + /* For rendering the template drawing */ unsigned key; Inkscape::Drawing renderDrawing; @@ -163,10 +165,9 @@ private: std::vector instanceConns; }; -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape - +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif // INKSCAPE_UI_DIALOG_SYMBOLS_H diff --git a/src/ui/dialog/template-load-tab.cpp b/src/ui/dialog/template-load-tab.cpp index 12085a588673e4974d8467827ff4b9464da38ea9..246149abd49d827284a7618b98cd460ddcb726c2 100644 --- a/src/ui/dialog/template-load-tab.cpp +++ b/src/ui/dialog/template-load-tab.cpp @@ -9,28 +9,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "template-widget.h" -#include "new-from-template.h" - +#include #include #include -#include #include #include #include -#include "extension/extension.h" #include "extension/db.h" -#include "inkscape.h" +#include "extension/extension.h" #include "file.h" +#include "inkscape.h" +#include "new-from-template.h" #include "path-prefix.h" +#include "template-widget.h" using namespace Inkscape::IO::Resource; namespace Inkscape { namespace UI { -TemplateLoadTab::TemplateLoadTab(NewFromTemplate* parent) +TemplateLoadTab::TemplateLoadTab(NewFromTemplate *parent) : _current_keyword("") , _keywords_combo(true) , _current_search_type(ALL) @@ -56,29 +55,24 @@ TemplateLoadTab::TemplateLoadTab(NewFromTemplate* parent) 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)); + _keywords_combo.signal_changed().connect(sigc::mem_fun(*this, &TemplateLoadTab::_keywordSelected)); this->show_all(); _loadTemplates(); _initLists(); } - -TemplateLoadTab::~TemplateLoadTab() -= default; - +TemplateLoadTab::~TemplateLoadTab() = default; void TemplateLoadTab::createTemplate() { _info_widget->create(); } - -void TemplateLoadTab::_onRowActivated(const Gtk::TreeModel::Path &, Gtk::TreeViewColumn*) +void TemplateLoadTab::_onRowActivated(const Gtk::TreeModel::Path &, Gtk::TreeViewColumn *) { createTemplate(); - NewFromTemplate* parent = static_cast (this->get_toplevel()); + NewFromTemplate *parent = static_cast(this->get_toplevel()); parent->_onClose(); } @@ -91,20 +85,17 @@ void TemplateLoadTab::_displayTemplateInfo() _info_widget->display(_tdata[_current_template]); _parent_widget->setCreateButtonSensitive(true); } - } - void TemplateLoadTab::_initKeywordsList() { _keywords_combo.append(_("All")); - for (const auto & _keyword : _keywords){ + for (const auto &_keyword : _keywords) { _keywords_combo.append(_keyword); } } - void TemplateLoadTab::_initLists() { _tlist_store = Gtk::ListStore::create(_columns); @@ -115,23 +106,19 @@ void TemplateLoadTab::_initLists() _initKeywordsList(); _refreshTemplatesList(); - Glib::RefPtr templateSelectionRef = - _tlist_view.get_selection(); - templateSelectionRef->signal_changed().connect( - sigc::mem_fun(*this, &TemplateLoadTab::_displayTemplateInfo)); + Glib::RefPtr 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)); + _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 == ""){ + if (_current_keyword == "") { _current_keyword = _keywords_combo.get_entry_text(); _current_search_type = USER_SPECIFIED; - } - else + } else _current_search_type = LIST_KEYWORD; if (_current_keyword == "" || _current_keyword == _("All")) @@ -140,51 +127,50 @@ void TemplateLoadTab::_keywordSelected() _refreshTemplatesList(); } - void TemplateLoadTab::_refreshTemplatesList() { _tlist_store->clear(); - switch (_current_search_type){ - case ALL :{ - for (auto & it : _tdata) { - Gtk::TreeModel::iterator iter = _tlist_store->append(); - Gtk::TreeModel::Row row = *iter; - row[_columns.textValue] = it.first; - } - break; - } - - case LIST_KEYWORD: { - for (auto & it : _tdata) { - if (it.second.keywords.count(_current_keyword.lowercase()) != 0){ + switch (_current_search_type) { + case ALL: { + for (auto &it : _tdata) { Gtk::TreeModel::iterator iter = _tlist_store->append(); Gtk::TreeModel::Row row = *iter; - row[_columns.textValue] = it.first; + row[_columns.textValue] = it.first; } + break; } - break; - } - case USER_SPECIFIED : { - for (auto & it : _tdata) { - 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) - { - Gtk::TreeModel::iterator iter = _tlist_store->append(); - Gtk::TreeModel::Row row = *iter; - row[_columns.textValue] = it.first; + case LIST_KEYWORD: { + for (auto &it : _tdata) { + 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 (auto &it : _tdata) { + 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) { + Gtk::TreeModel::iterator iter = _tlist_store->append(); + Gtk::TreeModel::Row row = *iter; + row[_columns.textValue] = it.first; + } + } + break; } - break; - } } // reselect item - Gtk::TreeIter* item_to_select = nullptr; - for (Gtk::TreeModel::Children::iterator it = _tlist_store->children().begin(); it != _tlist_store->children().end(); ++it) { + Gtk::TreeIter *item_to_select = nullptr; + for (Gtk::TreeModel::Children::iterator it = _tlist_store->children().begin(); it != _tlist_store->children().end(); + ++it) { Gtk::TreeModel::Row row = *it; if (_current_template == row[_columns.textValue]) { item_to_select = new Gtk::TreeIter(it); @@ -205,20 +191,17 @@ void TemplateLoadTab::_refreshTemplatesList() } } - void TemplateLoadTab::_loadTemplates() { - for(auto &filename: get_filenames(TEMPLATES, {".svg"}, {"default."})) { + for (auto &filename : get_filenames(TEMPLATES, {".svg"}, {"default."})) { TemplateData tmp = _processTemplateFile(filename.raw()); if (tmp.display_name != "") _tdata[tmp.display_name] = tmp; - } // procedural templates _getProceduralTemplates(); } - TemplateLoadTab::TemplateData TemplateLoadTab::_processTemplateFile(const std::string &path) { TemplateData result; @@ -229,16 +212,16 @@ TemplateLoadTab::TemplateData TemplateLoadTab::_processTemplateFile(const std::s // 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){ + 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"); + 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){ + if (rdoc) { Inkscape::XML::Node *root = rdoc->root(); - if (strcmp(root->name(), "svg:svg") != 0){ // Wrong file format + if (strcmp(root->name(), "svg:svg") != 0) { // Wrong file format return result; } @@ -247,7 +230,7 @@ TemplateLoadTab::TemplateData TemplateLoadTab::_processTemplateFile(const std::s templateinfo = sp_repr_lookup_name(root, "inkscape:_templateinfo"); // backwards-compatibility } - if (templateinfo == nullptr) // No template info + if (templateinfo == nullptr) // No template info return result; _getDataFromNode(templateinfo, result); } @@ -261,14 +244,14 @@ void TemplateLoadTab::_getProceduralTemplates() Inkscape::Extension::db.get_effect_list(effects); std::list::iterator it = effects.begin(); - while (it != effects.end()){ + while (it != effects.end()) { Inkscape::XML::Node *repr = (*it)->get_repr(); Inkscape::XML::Node *templateinfo = sp_repr_lookup_name(repr, "inkscape:templateinfo"); if (!templateinfo) { templateinfo = sp_repr_lookup_name(repr, "inkscape:_templateinfo"); // backwards-compatibility } - if (templateinfo){ + if (templateinfo) { TemplateData result; result.display_name = (*it)->get_name(); result.is_procedural = true; @@ -284,7 +267,7 @@ void TemplateLoadTab::_getProceduralTemplates() // if the template data comes from a procedural template (aka Effect extension), // attempt to translate within the extension's context (which might use a different gettext textdomain) -const char *_translate(const char* msgid, Extension::Extension *extension) +const char *_translate(const char *msgid, Extension::Extension *extension) { if (extension) { return extension->get_translation(msgid); @@ -293,7 +276,8 @@ const char *_translate(const char* msgid, Extension::Extension *extension) } } -void TemplateLoadTab::_getDataFromNode(Inkscape::XML::Node *dataNode, TemplateData &data, Extension::Extension *extension) +void TemplateLoadTab::_getDataFromNode(Inkscape::XML::Node *dataNode, TemplateData &data, + Extension::Extension *extension) { Inkscape::XML::Node *currentData; if ((currentData = sp_repr_lookup_name(dataNode, "inkscape:name")) != nullptr) @@ -315,9 +299,9 @@ void TemplateLoadTab::_getDataFromNode(Inkscape::XML::Node *dataNode, TemplateDa if ((currentData = sp_repr_lookup_name(dataNode, "inkscape:date")) != nullptr) data.creation_date = currentData->firstChild()->content(); - if ((currentData = sp_repr_lookup_name(dataNode, "inkscape:_keywords")) != nullptr){ + if ((currentData = sp_repr_lookup_name(dataNode, "inkscape:_keywords")) != nullptr) { Glib::ustring tplKeywords = _translate(currentData->firstChild()->content(), extension); - while (!tplKeywords.empty()){ + while (!tplKeywords.empty()) { std::size_t pos = tplKeywords.find_first_of(" "); if (pos == Glib::ustring::npos) pos = tplKeywords.size(); @@ -328,10 +312,10 @@ void TemplateLoadTab::_getDataFromNode(Inkscape::XML::Node *dataNode, TemplateDa if (pos == tplKeywords.size()) break; - tplKeywords.erase(0, pos+1); + tplKeywords.erase(0, pos + 1); } } } -} -} +} // namespace UI +} // namespace Inkscape diff --git a/src/ui/dialog/template-load-tab.h b/src/ui/dialog/template-load-tab.h index 2b8f98f12426fb5ff522933d84b84f30969aeea4..f70aeb79031e391219bf93a17817e27294807505 100644 --- a/src/ui/dialog/template-load-tab.h +++ b/src/ui/dialog/template-load-tab.h @@ -21,10 +21,9 @@ #include #include -#include "xml/node.h" -#include "io/resource.h" #include "extension/effect.h" - +#include "io/resource.h" +#include "xml/node.h" namespace Inkscape { @@ -39,7 +38,6 @@ class NewFromTemplate; class TemplateLoadTab : public Gtk::HBox { - public: struct TemplateData { @@ -55,18 +53,15 @@ public: Inkscape::Extension::Effect *tpl_effect; }; - TemplateLoadTab(NewFromTemplate* parent); + TemplateLoadTab(NewFromTemplate *parent); ~TemplateLoadTab() override; virtual void createTemplate(); protected: class StringModelColumns : public Gtk::TreeModelColumnRecord { - public: - StringModelColumns() - { - add(textValue); - } + public: + StringModelColumns() { add(textValue); } Gtk::TreeModelColumn textValue; }; @@ -76,7 +71,6 @@ protected: std::map _tdata; std::set _keywords; - virtual void _displayTemplateInfo(); virtual void _initKeywordsList(); virtual void _refreshTemplatesList(); @@ -102,18 +96,18 @@ private: }; SearchType _current_search_type; - NewFromTemplate* _parent_widget; + NewFromTemplate *_parent_widget; - void _getDataFromNode(Inkscape::XML::Node *, TemplateData &, Extension::Extension *extension=nullptr); + void _getDataFromNode(Inkscape::XML::Node *, TemplateData &, Extension::Extension *extension = nullptr); void _getProceduralTemplates(); void _getTemplatesFromDomain(Inkscape::IO::Resource::Domain domain); void _keywordSelected(); TemplateData _processTemplateFile(const std::string &); - void _onRowActivated(const Gtk::TreeModel::Path &, Gtk::TreeViewColumn*); + void _onRowActivated(const Gtk::TreeModel::Path &, Gtk::TreeViewColumn *); }; -} -} +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/dialog/template-widget.cpp b/src/ui/dialog/template-widget.cpp index e0716eb1eb266fe30dfd388ce05ef7beb74c2f34..a1d2106adc731f9a8a6d6b80143fcf4cd6230f73 100644 --- a/src/ui/dialog/template-widget.cpp +++ b/src/ui/dialog/template-widget.cpp @@ -15,19 +15,16 @@ #include #include "desktop.h" -#include "document.h" #include "document-undo.h" +#include "document.h" +#include "extension/implementation/implementation.h" #include "file.h" #include "inkscape.h" - -#include "extension/implementation/implementation.h" - #include "object/sp-namedview.h" namespace Inkscape { namespace UI { - TemplateWidget::TemplateWidget() : _more_info_button(_("More info")) , _short_description_label(" ") @@ -48,36 +45,32 @@ TemplateWidget::TemplateWidget() pack_end(_short_description_label, Gtk::PACK_SHRINK, 5); - _more_info_button.signal_clicked().connect( - sigc::mem_fun(*this, &TemplateWidget::_displayTemplateDetails)); + _more_info_button.signal_clicked().connect(sigc::mem_fun(*this, &TemplateWidget::_displayTemplateDetails)); _more_info_button.set_sensitive(false); } - void TemplateWidget::create() { if (_current_template.display_name == "") return; - if (_current_template.is_procedural){ + if (_current_template.is_procedural) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; SPDesktop *desc = sp_file_new_default(); _current_template.tpl_effect->effect(desc); DocumentUndo::clearUndo(desc->getDocument()); desc->getDocument()->setModifiedSinceSave(false); - // Apply cx,cy etc. from document - sp_namedview_window_from_document( desc ); + // Apply cx,cy etc. from document + sp_namedview_window_from_document(desc); if (desktop) desktop->clearWaitingCursor(); - } - else { + } else { sp_file_new(_current_template.path); } } - void TemplateWidget::display(TemplateLoadTab::TemplateData data) { clear(); @@ -86,19 +79,18 @@ void TemplateWidget::display(TemplateLoadTab::TemplateData data) _template_name_label.set_text(_current_template.display_name); _short_description_label.set_text(_current_template.short_description); - if (data.preview_name != ""){ + if (data.preview_name != "") { std::string imagePath = Glib::build_filename(Glib::path_get_dirname(_current_template.path), Glib::filename_from_utf8(_current_template.preview_name)); _preview_image.set(imagePath); _preview_image.show(); - } - else if (!data.is_procedural){ + } else if (!data.is_procedural) { Glib::ustring gPath = data.path.c_str(); _preview_render.showImage(gPath); _preview_render.show(); } - if (data.is_procedural){ + if (data.is_procedural) { _effect_prefs = data.tpl_effect->get_imp()->prefs_effect(data.tpl_effect, SP_ACTIVE_DESKTOP, nullptr, nullptr); pack_start(*_effect_prefs); } @@ -111,8 +103,8 @@ void TemplateWidget::clear() _short_description_label.set_text(""); _preview_render.hide(); _preview_image.hide(); - if (_effect_prefs != nullptr){ - remove (*_effect_prefs); + if (_effect_prefs != nullptr) { + remove(*_effect_prefs); _effect_prefs = nullptr; } _more_info_button.set_sensitive(false); @@ -128,10 +120,10 @@ void TemplateWidget::_displayTemplateDetails() message += _current_template.author + " " + _current_template.creation_date + "\n\n"; } - if (!_current_template.keywords.empty()){ + if (!_current_template.keywords.empty()) { message += _("Keywords"); message += ":"; - for (const auto & keyword : _current_template.keywords) { + for (const auto &keyword : _current_template.keywords) { message += " "; message += keyword; } @@ -149,5 +141,5 @@ void TemplateWidget::_displayTemplateDetails() dl.run(); } -} -} +} // namespace UI +} // namespace Inkscape diff --git a/src/ui/dialog/template-widget.h b/src/ui/dialog/template-widget.h index 5d7023bfd90f69b18218bd7a4a720b7d64fa0113..c342006407df6a5eb96cf5c6ef9d734658023ace 100644 --- a/src/ui/dialog/template-widget.h +++ b/src/ui/dialog/template-widget.h @@ -12,28 +12,25 @@ #ifndef INKSCAPE_SEEN_UI_DIALOG_TEMPLATE_WIDGET_H #define INKSCAPE_SEEN_UI_DIALOG_TEMPLATE_WIDGET_H -#include "svg-preview.h" - #include +#include "svg-preview.h" #include "template-load-tab.h" - namespace Inkscape { namespace UI { - - + class TemplateWidget : public Gtk::VBox { public: - TemplateWidget (); + TemplateWidget(); void create(); void display(TemplateLoadTab::TemplateData); void clear(); - + private: TemplateLoadTab::TemplateData _current_template; - + Gtk::Button _more_info_button; Gtk::HBox _preview_box; Gtk::Image _preview_image; @@ -41,11 +38,11 @@ private: Gtk::Label _short_description_label; Gtk::Label _template_name_label; Gtk::Widget *_effect_prefs; - + void _displayTemplateDetails(); }; -} -} +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/dialog/text-edit.cpp b/src/ui/dialog/text-edit.cpp index 12bd62d60af67e9947b86b80a40c44fe784cefdb..ddce7509438b38c224be03449d4dc5ab40c24d3d 100644 --- a/src/ui/dialog/text-edit.cpp +++ b/src/ui/dialog/text-edit.cpp @@ -18,14 +18,11 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include "text-edit.h" - #include #include - #include #include #include @@ -35,54 +32,52 @@ #include #include +#include "text-edit.h" + #ifdef WITH_GSPELL -# include +#include #endif +#include +#include +#include + #include "desktop-style.h" #include "desktop.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" -#include "style.h" -#include "text-editing.h" -#include "verbs.h" - -#include -#include -#include - +#include "io/resource.h" #include "object/sp-flowtext.h" #include "object/sp-text.h" #include "object/sp-textpath.h" - -#include "io/resource.h" +#include "style.h" #include "svg/css-ostringstream.h" +#include "text-editing.h" #include "ui/icon-names.h" #include "ui/toolbar/text-toolbar.h" #include "ui/widget/font-selector.h" - #include "util/units.h" - +#include "verbs.h" namespace Inkscape { namespace UI { namespace Dialog { TextEdit::TextEdit() - : UI::Widget::Panel("/dialogs/textandfont", SP_VERB_DIALOG_TEXT), - selectChangedConn(), - subselChangedConn(), - selectModifiedConn(), - blocked(false), - /* - TRANSLATORS: Test string used in text and font dialog (when no - * text has been entered) to get a preview of the font. Choose - * some representative characters that users of your locale will be - * interested in.*/ - samplephrase(_("AaBbCcIiPpQq12369$\342\202\254\302\242?.;/()")) + : UI::Widget::Panel("/dialogs/textandfont", SP_VERB_DIALOG_TEXT) + , selectChangedConn() + , subselChangedConn() + , selectModifiedConn() + , blocked(false) + , + /* + TRANSLATORS: Test string used in text and font dialog (when no + * text has been entered) to get a preview of the font. Choose + * some representative characters that users of your locale will be + * interested in.*/ + samplephrase(_("AaBbCcIiPpQq12369$\342\202\254\302\242?.;/()")) { - std::string gladefile = get_filename_string(Inkscape::IO::Resource::UIS, "dialog-text-edit.glade"); Glib::RefPtr builder; try { @@ -151,33 +146,30 @@ TextEdit::~TextEdit() fontFeaturesChangedConn.disconnect(); } -void TextEdit::onSelectionModified(guint flags ) +void TextEdit::onSelectionModified(guint flags) { gboolean style, content; - style = ((flags & ( SP_OBJECT_CHILD_MODIFIED_FLAG | - SP_OBJECT_STYLE_MODIFIED_FLAG )) != 0 ); + style = ((flags & (SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG)) != 0); - content = ((flags & ( SP_OBJECT_CHILD_MODIFIED_FLAG | - SP_TEXT_CONTENT_MODIFIED_FLAG )) != 0 ); + content = ((flags & (SP_OBJECT_CHILD_MODIFIED_FLAG | SP_TEXT_CONTENT_MODIFIED_FLAG)) != 0); - onReadSelection (style, content); + onReadSelection(style, content); } -void TextEdit::onReadSelection ( gboolean dostyle, gboolean /*docontent*/ ) +void TextEdit::onReadSelection(gboolean dostyle, gboolean /*docontent*/) { if (blocked) return; blocked = true; - SPItem *text = getSelectedTextItem (); + SPItem *text = getSelectedTextItem(); Glib::ustring phrase = samplephrase; - if (text) - { - guint items = getSelectedTextCount (); + if (text) { + guint items = getSelectedTextCount(); bool has_one_item = items == 1; text_view->set_sensitive(has_one_item); apply_button->set_sensitive(false); @@ -211,45 +203,43 @@ void TextEdit::onReadSelection ( gboolean dostyle, gboolean /*docontent*/ ) // Query style from desktop into it. This returns a result flag and fills query with the // style of subselection, if any, or selection - int result_numbers = sp_desktop_query_style (desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); + int result_numbers = sp_desktop_query_style(desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); // If querying returned nothing, read the style from the text tool prefs (default style for new texts). if (result_numbers == QUERY_STYLE_NOTHING) { query.readFromPrefs("/tools/text"); } - Inkscape::FontLister* font_lister = Inkscape::FontLister::get_instance(); + Inkscape::FontLister *font_lister = Inkscape::FontLister::get_instance(); // Update family/style based on selection. font_lister->selection_update(); Glib::ustring fontspec = font_lister->get_fontspec(); // Update Font Face. - font_selector.update_font (); + font_selector.update_font(); // Update Size. 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); - font_selector.update_size (size); + double size = sp_style_css_size_px_to_units(query.font_size.computed, unit); + font_selector.update_size(size); selected_fontsize = size; // Update font features (variant) widget - //int result_features = - sp_desktop_query_style (desktop, &query, QUERY_STYLE_PROPERTY_FONTVARIANTS); - int result_features = - sp_desktop_query_style (desktop, &query, QUERY_STYLE_PROPERTY_FONTFEATURESETTINGS); - font_features.update( &query, result_features == QUERY_STYLE_MULTIPLE_DIFFERENT, fontspec ); + // int result_features = + sp_desktop_query_style(desktop, &query, QUERY_STYLE_PROPERTY_FONTVARIANTS); + int result_features = sp_desktop_query_style(desktop, &query, QUERY_STYLE_PROPERTY_FONTFEATURESETTINGS); + font_features.update(&query, result_features == QUERY_STYLE_MULTIPLE_DIFFERENT, fontspec); Glib::ustring features = font_features.get_markup(); // Update Preview - setPreviewText (fontspec, features, phrase); + setPreviewText(fontspec, features, phrase); } blocked = false; } - -void TextEdit::setPreviewText (Glib::ustring font_spec, Glib::ustring font_features, Glib::ustring phrase) +void TextEdit::setPreviewText(Glib::ustring font_spec, Glib::ustring font_features, Glib::ustring phrase) { if (font_spec.empty()) { preview_label->set_markup(""); @@ -270,43 +260,42 @@ void TextEdit::setPreviewText (Glib::ustring font_spec, Glib::ustring font_featu auto from = start_pos; for (int i = 0; i < max_lines; ++i) { end_pos = phrase.find("\n", from); - if (end_pos == Glib::ustring::npos) { break; } + if (end_pos == Glib::ustring::npos) { + break; + } from = end_pos + 1; } - Glib::ustring phrase_trimmed = phrase.substr(start_pos, end_pos != Glib::ustring::npos ? end_pos - start_pos : end_pos); + Glib::ustring phrase_trimmed = + phrase.substr(start_pos, end_pos != Glib::ustring::npos ? end_pos - start_pos : end_pos); - Glib::ustring font_spec_escaped = Glib::Markup::escape_text( font_spec ); + Glib::ustring font_spec_escaped = Glib::Markup::escape_text(font_spec); Glib::ustring phrase_escaped = Glib::Markup::escape_text(phrase_trimmed); 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(font_selector.get_fontsize(), unit), "px", "pt"); + double pt_size = Inkscape::Util::Quantity::convert( + sp_style_css_size_units_to_px(font_selector.get_fontsize(), unit), "px", "pt"); pt_size = std::min(pt_size, 100.0); // Pango font size is in 1024ths of a point - Glib::ustring size = std::to_string( int(pt_size * PANGO_SCALE) ); - Glib::ustring markup = ""; - preview_label->set_markup (markup); - preview_label2->set_markup (markup); + preview_label->set_markup(markup); + preview_label2->set_markup(markup); } - -SPItem *TextEdit::getSelectedTextItem () +SPItem *TextEdit::getSelectedTextItem() { if (!getDesktop()) return nullptr; - auto tmp= getDesktop()->getSelection()->items(); - for(auto i=tmp.begin();i!=tmp.end();++i) - { + auto tmp = getDesktop()->getSelection()->items(); + for (auto i = tmp.begin(); i != tmp.end(); ++i) { if (SP_IS_TEXT(*i) || SP_IS_FLOWTEXT(*i)) return *i; } @@ -314,17 +303,15 @@ SPItem *TextEdit::getSelectedTextItem () return nullptr; } - -unsigned TextEdit::getSelectedTextCount () +unsigned TextEdit::getSelectedTextCount() { if (!getDesktop()) return 0; unsigned int items = 0; - auto tmp= getDesktop()->getSelection()->items(); - for(auto i=tmp.begin();i!=tmp.end();++i) - { + auto tmp = getDesktop()->getSelection()->items(); + for (auto i = tmp.begin(); i != tmp.end(); ++i) { if (SP_IS_TEXT(*i) || SP_IS_FLOWTEXT(*i)) ++items; } @@ -334,10 +321,10 @@ unsigned TextEdit::getSelectedTextCount () void TextEdit::onSelectionChange() { - onReadSelection (TRUE, TRUE); + onReadSelection(TRUE, TRUE); } -void TextEdit::updateObjectText ( SPItem *text ) +void TextEdit::updateObjectText(SPItem *text) { Gtk::TextIter start, end; @@ -345,53 +332,52 @@ void TextEdit::updateObjectText ( SPItem *text ) if (text_buffer->get_modified()) { text_buffer->get_bounds(start, end); Glib::ustring str = text_buffer->get_text(start, end); - sp_te_set_repr_text_multiline (text, str.c_str()); + sp_te_set_repr_text_multiline(text, str.c_str()); text_buffer->set_modified(false); } } -SPCSSAttr *TextEdit::fillTextStyle () +SPCSSAttr *TextEdit::fillTextStyle() { - SPCSSAttr *css = sp_repr_css_attr_new (); - - Glib::ustring fontspec = font_selector.get_fontspec(); + SPCSSAttr *css = sp_repr_css_attr_new(); - if( !fontspec.empty() ) { + Glib::ustring fontspec = font_selector.get_fontspec(); - Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); - fontlister->fill_css( css, fontspec ); + if (!fontspec.empty()) { + 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; - 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(font_selector.get_fontsize(), unit) - << sp_style_get_css_unit_string(SP_CSS_UNIT_PX); - } else { - os << font_selector.get_fontsize() << sp_style_get_css_unit_string(unit); - } - sp_repr_css_set_property (css, "font-size", os.str().c_str()); + // TODO, possibly move this to FontLister::set_css to be shared. + Inkscape::CSSOStringStream os; + 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(font_selector.get_fontsize(), unit) + << sp_style_get_css_unit_string(SP_CSS_UNIT_PX); + } else { + os << font_selector.get_fontsize() << sp_style_get_css_unit_string(unit); } + sp_repr_css_set_property(css, "font-size", os.str().c_str()); + } - // Font features - font_features.fill_css( css ); + // Font features + font_features.fill_css(css); - return css; + return css; } void TextEdit::onSetDefault() { - SPCSSAttr *css = fillTextStyle (); + SPCSSAttr *css = fillTextStyle(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); blocked = true; prefs->mergeStyle("/tools/text/style", css); blocked = false; - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); - setasdefault_button->set_sensitive ( false ); + setasdefault_button->set_sensitive(false); } void TextEdit::onApply() @@ -402,11 +388,11 @@ void TextEdit::onApply() unsigned items = 0; auto item_list = desktop->getSelection()->items(); - SPCSSAttr *css = fillTextStyle (); + SPCSSAttr *css = fillTextStyle(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - for(auto i=item_list.begin();i!=item_list.end();++i){ + for (auto i = item_list.begin(); i != item_list.end(); ++i) { // apply style to the reprs of all text objects in the selection - if (SP_IS_TEXT (*i) || (SP_IS_FLOWTEXT (*i)) ) { + if (SP_IS_TEXT(*i) || (SP_IS_FLOWTEXT(*i))) { ++items; } } @@ -419,13 +405,13 @@ void TextEdit::onApply() if (items == 0) { // no text objects; apply style to prefs for new objects prefs->mergeStyle("/tools/text/style", css); - setasdefault_button->set_sensitive ( false ); + setasdefault_button->set_sensitive(false); } else if (items == 1) { // exactly one text object; now set its text, too SPItem *item = desktop->getSelection()->singleItem(); - if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) { - updateObjectText (item); + if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item)) { + updateObjectText(item); SPStyle *item_style = item->style; if (SP_IS_TEXT(item) && item_style->inline_size.value == 0) { css = sp_css_attr_from_style(item_style, SP_STYLE_FLAG_IFSET); @@ -437,25 +423,24 @@ void TextEdit::onApply() // Update FontLister Glib::ustring fontspec = font_selector.get_fontspec(); - if( !fontspec.empty() ) { + if (!fontspec.empty()) { Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); - fontlister->set_fontspec( fontspec, false ); + fontlister->set_fontspec(fontspec, false); } // complete the transaction - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Set text style")); - apply_button->set_sensitive ( false ); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Set text style")); + apply_button->set_sensitive(false); - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); - Inkscape::FontLister* font_lister = Inkscape::FontLister::get_instance(); + Inkscape::FontLister *font_lister = Inkscape::FontLister::get_instance(); font_lister->update_font_list(desktop->getDocument()); blocked = false; } -void TextEdit::onFontFeatures(Gtk::Widget * widgt, int pos) +void TextEdit::onFontFeatures(Gtk::Widget *widgt, int pos) { if (pos == 1) { Glib::ustring fontspec = font_selector.get_fontspec(); @@ -481,15 +466,15 @@ void TextEdit::onChange() Glib::ustring fontspec = font_selector.get_fontspec(); Glib::ustring features = font_features.get_markup(); - const Glib::ustring& phrase = str.empty() ? samplephrase : str; + const Glib::ustring &phrase = str.empty() ? samplephrase : str; setPreviewText(fontspec, features, phrase); SPItem *text = getSelectedTextItem(); if (text) { - apply_button->set_sensitive ( true ); + apply_button->set_sensitive(true); } - setasdefault_button->set_sensitive ( true); + setasdefault_button->set_sensitive(true); } void TextEdit::onFontChange(Glib::ustring fontspec) @@ -508,17 +493,20 @@ void TextEdit::setDesktop(SPDesktop *desktop) { if (desktop && desktop->selection) { - selectChangedConn = desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &TextEdit::onSelectionChange))); - subselChangedConn = desktop->connectToolSubselectionChanged(sigc::hide(sigc::mem_fun(*this, &TextEdit::onSelectionChange))); - selectModifiedConn = desktop->selection->connectModified(sigc::hide<0>(sigc::mem_fun(*this, &TextEdit::onSelectionModified))); + selectChangedConn = + desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &TextEdit::onSelectionChange))); + subselChangedConn = + desktop->connectToolSubselectionChanged(sigc::hide(sigc::mem_fun(*this, &TextEdit::onSelectionChange))); + selectModifiedConn = desktop->selection->connectModified( + sigc::hide<0>(sigc::mem_fun(*this, &TextEdit::onSelectionModified))); onReadSelection(TRUE, TRUE); } } } -} //namespace Dialog -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/text-edit.h b/src/ui/dialog/text-edit.h index 597ed041201f1688914cd25af726619aa2907a51..2d5d666e87ad913255de7fb1155aa88011ecf198 100644 --- a/src/ui/dialog/text-edit.h +++ b/src/ui/dialog/text-edit.h @@ -21,11 +21,10 @@ #include -#include "ui/widget/panel.h" -#include "ui/widget/frame.h" - #include "ui/widget/font-selector.h" #include "ui/widget/font-variants.h" +#include "ui/widget/frame.h" +#include "ui/widget/panel.h" namespace Gtk { class Box; @@ -35,7 +34,7 @@ class Label; class Notebook; class TextBuffer; class TextView; -} +} // namespace Gtk class SPItem; class font_instance; @@ -48,12 +47,13 @@ namespace Dialog { #define VB_MARGIN 4 /** * The TextEdit class defines the Text and font dialog. - * + * * The Text and font dialog allows you to set the font family, style and size * and shows a preview of the result. The dialogs layout settings include * horizontal and vertical alignment and inter line distance. */ -class TextEdit : public UI::Widget::Panel { +class TextEdit : public UI::Widget::Panel +{ public: TextEdit(); ~TextEdit() override; @@ -65,29 +65,30 @@ public: static TextEdit &getInstance() { return *new TextEdit(); } protected: - /** * Callback for pressing the default button. */ - void onSetDefault (); + void onSetDefault(); /** * Callback for pressing the apply button. */ - void onApply (); - void onSelectionChange (); - void onSelectionModified (guint flags); - + void onApply(); + void onSelectionChange(); + void onSelectionModified(guint flags); + /** * Called whenever something 'changes' on canvas. - * - * onReadSelection gets the currently selected item from the canvas and sets all the controls in this dialog to the correct state. - * + * + * onReadSelection gets the currently selected item from the canvas and sets all the controls in this dialog to the + * correct state. + * * @param dostyle Indicates whether the modification of the user includes a style change. - * @param content Indicates whether the modification of the user includes a style change. Actually refers to the question if we do want to show the content? (Parameter currently not used) + * @param content Indicates whether the modification of the user includes a style change. Actually refers to the + * question if we do want to show the content? (Parameter currently not used) */ - void onReadSelection (gboolean style, gboolean content); - + void onReadSelection(gboolean style, gboolean content); + /** * Callback invoked when the user modifies the text of the selected text object. * @@ -97,9 +98,9 @@ protected: * * @param self pointer to the current instance of the dialog. */ - void onChange (); - void onFontFeatures (Gtk::Widget * widgt, int pos); - + void onChange(); + void onFontFeatures(Gtk::Widget *widgt, int pos); + /** * Callback invoked when the user modifies the font through the dialog or the tools control bar. * @@ -107,31 +108,31 @@ protected: * * @param fontspec for the text to be previewed. */ - void onFontChange (Glib::ustring fontspec); + void onFontChange(Glib::ustring fontspec); /** * Get the selected text off the main canvas. * * @return SPItem pointer to the selected text object */ - SPItem *getSelectedTextItem (); + SPItem *getSelectedTextItem(); /** * Count the number of text objects in the selection on the canvas. */ - unsigned getSelectedTextCount (); + unsigned getSelectedTextCount(); /** * Helper function to create markup from a fontspec and display in the preview label. - * + * * @param fontspec for the text to be previewed. * @param font_features for text to be previewed (in CSS format). * @param phrase text to be shown. */ - void setPreviewText (Glib::ustring font_spec, Glib::ustring font_features, Glib::ustring phrase); + void setPreviewText(Glib::ustring font_spec, Glib::ustring font_features, Glib::ustring phrase); - void updateObjectText ( SPItem *text ); - SPCSSAttr *fillTextStyle (); + void updateObjectText(SPItem *text); + SPCSSAttr *fillTextStyle(); /** * Can be invoked for setting the desktop. Currently not used. @@ -139,7 +140,6 @@ protected: void setDesktop(SPDesktop *desktop) override; private: - /* * All the dialogs widgets */ @@ -147,7 +147,7 @@ private: // Tab 1: Font ---------------------- // Inkscape::UI::Widget::FontSelector font_selector; Inkscape::UI::Widget::FontVariations font_variations; - Gtk::Label *preview_label; // Share with variants tab? + Gtk::Label *preview_label; // Share with variants tab? // Tab 2: Text ---------------------- // Gtk::TextView *text_view; @@ -174,15 +174,13 @@ private: bool blocked; const Glib::ustring samplephrase; - TextEdit(TextEdit const &d) = delete; TextEdit operator=(TextEdit const &d) = delete; }; - -} //namespace Dialog -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif // INKSCAPE_UI_DIALOG_TEXT_EDIT_H diff --git a/src/ui/dialog/tile.cpp b/src/ui/dialog/tile.cpp index e46f0d79dc72a0af67b8c477d0efd8389245b439..8f4ad8288d54e07950a36d9585367d3799dd1341 100644 --- a/src/ui/dialog/tile.cpp +++ b/src/ui/dialog/tile.cpp @@ -15,12 +15,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/dialog/grid-arrange-tab.h" -#include "ui/dialog/polar-arrange-tab.h" +#include "tile.h" #include -#include "tile.h" +#include "ui/dialog/grid-arrange-tab.h" +#include "ui/dialog/polar-arrange-tab.h" #include "verbs.h" namespace Inkscape { @@ -28,9 +28,9 @@ namespace UI { namespace Dialog { ArrangeDialog::ArrangeDialog() - : UI::Widget::Panel("/dialogs/gridtiler", SP_VERB_SELECTION_ARRANGE), - _gridArrangeTab(new GridArrangeTab(this)), - _polarArrangeTab(new PolarArrangeTab(this)) + : UI::Widget::Panel("/dialogs/gridtiler", SP_VERB_SELECTION_ARRANGE) + , _gridArrangeTab(new GridArrangeTab(this)) + , _polarArrangeTab(new PolarArrangeTab(this)) { Gtk::Box *contents = this->_getContents(); @@ -41,31 +41,29 @@ ArrangeDialog::ArrangeDialog() _notebook.append_page(*_polarArrangeTab, C_("Arrange dialog", "Polar Coordinates")); _arrangeBox.pack_start(_notebook); - _arrangeButton = this->addResponseButton(C_("Arrange dialog","_Arrange"), GTK_RESPONSE_APPLY); + _arrangeButton = this->addResponseButton(C_("Arrange dialog", "_Arrange"), GTK_RESPONSE_APPLY); _arrangeButton->set_use_underline(true); _arrangeButton->set_tooltip_text(_("Arrange selected objects")); contents->pack_start(_arrangeBox); - //show_all_children(); + // show_all_children(); } - void ArrangeDialog::on_show() { - UI::Widget::Panel::on_show(); - _polarArrangeTab->on_arrange_radio_changed(); + UI::Widget::Panel::on_show(); + _polarArrangeTab->on_arrange_radio_changed(); } void ArrangeDialog::_apply() { - switch(_notebook.get_current_page()) - { - case 0: - _gridArrangeTab->arrange(); - break; - case 1: - _polarArrangeTab->arrange(); - break; - } + switch (_notebook.get_current_page()) { + case 0: + _gridArrangeTab->arrange(); + break; + case 1: + _polarArrangeTab->arrange(); + break; + } } void ArrangeDialog::setDesktop(SPDesktop *desktop) @@ -74,9 +72,9 @@ void ArrangeDialog::setDesktop(SPDesktop *desktop) _gridArrangeTab->setDesktop(desktop); } -} //namespace Dialog -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/tile.h b/src/ui/dialog/tile.h index 0d31ff8700f2e6c821f9fe4ae64639dc771a5d28..542baa806762336050ef0b68d00f85cf83faa996 100644 --- a/src/ui/dialog/tile.h +++ b/src/ui/dialog/tile.h @@ -18,8 +18,8 @@ #define SEEN_UI_DIALOG_TILE_H #include -#include #include +#include #include #include "ui/widget/panel.h" @@ -27,7 +27,7 @@ namespace Gtk { class Button; class Grid; -} +} // namespace Gtk namespace Inkscape { namespace UI { @@ -37,19 +37,21 @@ class ArrangeTab; class GridArrangeTab; class PolarArrangeTab; -class ArrangeDialog : public UI::Widget::Panel { +class ArrangeDialog : public UI::Widget::Panel +{ private: - Gtk::VBox _arrangeBox; - Gtk::Notebook _notebook; + Gtk::VBox _arrangeBox; + Gtk::Notebook _notebook; - GridArrangeTab *_gridArrangeTab; - PolarArrangeTab *_polarArrangeTab; + GridArrangeTab *_gridArrangeTab; + PolarArrangeTab *_polarArrangeTab; - Gtk::Button *_arrangeButton; + Gtk::Button *_arrangeButton; public: - ArrangeDialog(); - ~ArrangeDialog() override = default;; + ArrangeDialog(); + ~ArrangeDialog() override = default; + ; void setDesktop(SPDesktop *) override; @@ -60,13 +62,12 @@ public: void on_show() override; - static ArrangeDialog& getInstance() { return *new ArrangeDialog(); } + static ArrangeDialog &getInstance() { return *new ArrangeDialog(); } }; -} //namespace Dialog -} //namespace UI -} //namespace Inkscape - +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif /* __TILEDIALOG_H__ */ diff --git a/src/ui/dialog/tracedialog.cpp b/src/ui/dialog/tracedialog.cpp index 3f730e0bcfc41bedb3c96b432ecbb546fbfa0eb5..8e21191ad6982c386b13a6cb080c743fc7d8c5a9 100644 --- a/src/ui/dialog/tracedialog.cpp +++ b/src/ui/dialog/tracedialog.cpp @@ -13,6 +13,7 @@ #include "tracedialog.h" +#include #include #include #include @@ -20,37 +21,32 @@ #include #include - -#include - #include "desktop.h" -#include "selection.h" - #include "inkscape.h" #include "io/resource.h" #include "io/sys.h" +#include "selection.h" #include "trace/autotrace/inkscape-autotrace.h" -#include "trace/potrace/inkscape-potrace.h" #include "trace/depixelize/inkscape-depixelize.h" - - +#include "trace/potrace/inkscape-potrace.h" namespace Inkscape { namespace UI { namespace Dialog { -class TraceDialogImpl2 : public TraceDialog { - public: +class TraceDialogImpl2 : public TraceDialog +{ +public: TraceDialogImpl2(); ~TraceDialogImpl2() override; - private: +private: Inkscape::Trace::Tracer tracer; void traceProcess(bool do_i_trace); void abort(); void previewCallback(); - bool previewResize(const Cairo::RefPtr&); + bool previewResize(const Cairo::RefPtr &); void traceCallback(); void onSelectionModified(guint flags); void onSetDefaults(); @@ -62,8 +58,8 @@ class TraceDialogImpl2 : public TraceDialog { Glib::RefPtr builder; - Glib::RefPtr MS_scans, PA_curves, PA_islands, PA_sparse1, PA_sparse2, SS_AT_ET_T, SS_AT_FI_T, SS_BC_T, SS_CQ_T, - SS_ED_T, optimize, smooth, speckles; + Glib::RefPtr MS_scans, PA_curves, PA_islands, PA_sparse1, PA_sparse2, SS_AT_ET_T, SS_AT_FI_T, + SS_BC_T, SS_CQ_T, SS_ED_T, optimize, smooth, speckles; Gtk::ComboBoxText *CBT_SS, *CBT_MS; Gtk::CheckButton *CB_invert, *CB_MS_smooth, *CB_MS_stack, *CB_MS_rb, *CB_speckles, *CB_smooth, *CB_optimize, /* *CB_live,*/ *CB_SIOX; @@ -113,42 +109,35 @@ void TraceDialogImpl2::traceProcess(bool do_i_trace) Inkscape::Trace::Autotrace::AutotraceTracingEngine ate; // TODO if (type == _("Brightness cutoff")) - potraceType = Inkscape::Trace::Potrace::TRACE_BRIGHTNESS; + potraceType = Inkscape::Trace::Potrace::TRACE_BRIGHTNESS; else if (type == _("Edge detection")) - potraceType = Inkscape::Trace::Potrace::TRACE_CANNY; + potraceType = Inkscape::Trace::Potrace::TRACE_CANNY; else if (type == _("Color quantization")) - potraceType = Inkscape::Trace::Potrace::TRACE_QUANT; - else if (type == _("Autotrace")) - { - // autotraceType = Inkscape::Trace::Autotrace::TRACE_CENTERLINE - use_autotrace = true; - ate.opts->color_count = 2; - } - else if (type == _("Centerline tracing (autotrace)")) - { - // autotraceType = Inkscape::Trace::Autotrace::TRACE_CENTERLINE - use_autotrace = true; - ate.opts->color_count = 2; - ate.opts->centerline = true; - ate.opts->preserve_width = true; - } - else if (type == _("Brightness steps")) - potraceType = Inkscape::Trace::Potrace::TRACE_BRIGHTNESS_MULTI; + potraceType = Inkscape::Trace::Potrace::TRACE_QUANT; + else if (type == _("Autotrace")) { + // autotraceType = Inkscape::Trace::Autotrace::TRACE_CENTERLINE + use_autotrace = true; + ate.opts->color_count = 2; + } else if (type == _("Centerline tracing (autotrace)")) { + // autotraceType = Inkscape::Trace::Autotrace::TRACE_CENTERLINE + use_autotrace = true; + ate.opts->color_count = 2; + ate.opts->centerline = true; + ate.opts->preserve_width = true; + } else if (type == _("Brightness steps")) + potraceType = Inkscape::Trace::Potrace::TRACE_BRIGHTNESS_MULTI; else if (type == _("Colors")) - potraceType = Inkscape::Trace::Potrace::TRACE_QUANT_COLOR; + potraceType = Inkscape::Trace::Potrace::TRACE_QUANT_COLOR; else if (type == _("Grays")) - potraceType = Inkscape::Trace::Potrace::TRACE_QUANT_MONO; - else if (type == _("Autotrace (slower)")) - { - // autotraceType = Inkscape::Trace::Autotrace::TRACE_CENTERLINE - use_autotrace = true; - ate.opts->color_count = (int)MS_scans->get_value() + 1; - } - else - { - g_warning("Should not happen!"); + potraceType = Inkscape::Trace::Potrace::TRACE_QUANT_MONO; + else if (type == _("Autotrace (slower)")) { + // autotraceType = Inkscape::Trace::Autotrace::TRACE_CENTERLINE + use_autotrace = true; + ate.opts->color_count = (int)MS_scans->get_value() + 1; + } else { + g_warning("Should not happen!"); } - ate.opts->filter_iterations = (int) SS_AT_FI_T->get_value(); + ate.opts->filter_iterations = (int)SS_AT_FI_T->get_value(); ate.opts->error_threshold = SS_AT_ET_T->get_value(); Inkscape::Trace::Potrace::PotraceTracingEngine pte( @@ -161,11 +150,11 @@ void TraceDialogImpl2::traceProcess(bool do_i_trace) pte.potraceParams->alphamax = CB_smooth->get_active() ? smooth->get_value() : 0; pte.potraceParams->turdsize = CB_speckles->get_active() ? (int)speckles->get_value() : 0; - - - //Inkscape::Trace::Autotrace::AutotraceTracingEngine ate; // TODO - Inkscape::Trace::Depixelize::DepixelizeTracingEngine dte(RB_PA_voronoi->get_active() ? Inkscape::Trace::Depixelize::TraceType::TRACE_VORONOI : Inkscape::Trace::Depixelize::TraceType::TRACE_BSPLINES, PA_curves->get_value(), (int) PA_islands->get_value(), (int) PA_sparse1->get_value(), PA_sparse2->get_value() ); - + // Inkscape::Trace::Autotrace::AutotraceTracingEngine ate; // TODO + Inkscape::Trace::Depixelize::DepixelizeTracingEngine dte( + RB_PA_voronoi->get_active() ? Inkscape::Trace::Depixelize::TraceType::TRACE_VORONOI + : Inkscape::Trace::Depixelize::TraceType::TRACE_BSPLINES, + PA_curves->get_value(), (int)PA_islands->get_value(), (int)PA_sparse1->get_value(), PA_sparse2->get_value()); Glib::RefPtr pixbuf = tracer.getSelectedImage(); if (pixbuf) { @@ -183,12 +172,12 @@ void TraceDialogImpl2::traceProcess(bool do_i_trace) previewArea->queue_draw(); } } - if (do_i_trace){ - if (choice_tab->get_current_page() == 1){ + if (do_i_trace) { + if (choice_tab->get_current_page() == 1) { tracer.trace(&dte); printf("dt\n"); } else if (use_autotrace) { - tracer.trace(&ate); + tracer.trace(&ate); printf("at\n"); } else if (choice_tab->get_current_page() == 0) { tracer.trace(&pte); @@ -200,9 +189,10 @@ void TraceDialogImpl2::traceProcess(bool do_i_trace) desktop->clearWaitingCursor(); } -bool TraceDialogImpl2::previewResize(const Cairo::RefPtr& cr) +bool TraceDialogImpl2::previewResize(const Cairo::RefPtr &cr) { - if (!scaledPreview) return false; // return early + if (!scaledPreview) + return false; // return early int width = scaledPreview->get_width(); int height = scaledPreview->get_height(); const Gtk::Allocation &vboxAlloc = previewArea->get_allocation(); @@ -211,8 +201,8 @@ bool TraceDialogImpl2::previewResize(const Cairo::RefPtr& cr) double scaleFactor = scaleFX > scaleFY ? scaleFY : scaleFX; int newWidth = (int)(((double)width) * scaleFactor); int newHeight = (int)(((double)height) * scaleFactor); - int offsetX = (vboxAlloc.get_width() - newWidth)/2; - int offsetY = (vboxAlloc.get_height() - newHeight)/2; + int offsetX = (vboxAlloc.get_width() - newWidth) / 2; + int offsetY = (vboxAlloc.get_height() - newHeight) / 2; Glib::RefPtr temp = scaledPreview->scale_simple(newWidth, newHeight, Gdk::INTERP_NEAREST); Gdk::Cairo::set_source_pixbuf(cr, temp, offsetX, offsetY); @@ -221,11 +211,11 @@ bool TraceDialogImpl2::previewResize(const Cairo::RefPtr& cr) } void TraceDialogImpl2::abort() -{ - SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if (desktop) - desktop->clearWaitingCursor(); - tracer.abort(); +{ + SPDesktop *desktop = SP_ACTIVE_DESKTOP; + if (desktop) + desktop->clearWaitingCursor(); + tracer.abort(); } void TraceDialogImpl2::onSelectionModified(guint flags) @@ -257,24 +247,52 @@ void TraceDialogImpl2::onSetDefaults() CB_speckles->set_active(true); CB_smooth->set_active(true); CB_optimize->set_active(true); - //CB_live->set_active(false); + // CB_live->set_active(false); CB_SIOX->set_active(false); } -void TraceDialogImpl2::previewCallback() { traceProcess(false); } -void TraceDialogImpl2::traceCallback() { traceProcess(true); } - +void TraceDialogImpl2::previewCallback() +{ + traceProcess(false); +} +void TraceDialogImpl2::traceCallback() +{ + traceProcess(true); +} TraceDialogImpl2::TraceDialogImpl2() : TraceDialog() { - const std::string req_widgets[] = { "MS_scans", "PA_curves", "PA_islands", "PA_sparse1", "PA_sparse2", - "SS_AT_FI_T", "SS_AT_ET_T", "SS_BC_T", "SS_CQ_T", "SS_ED_T", - "optimize", "smooth", "speckles", "CB_invert", "CB_MS_smooth", - "CB_MS_stack", "CB_MS_rb", "CB_speckles", "CB_smooth", "CB_optimize", - /*"CB_live",*/ "CB_SIOX", "CBT_SS", "CBT_MS", "B_RESET", - "B_STOP", "B_OK", "mainBox", "choice_tab", "choice_scan", - "previewArea" }; + const std::string req_widgets[] = {"MS_scans", + "PA_curves", + "PA_islands", + "PA_sparse1", + "PA_sparse2", + "SS_AT_FI_T", + "SS_AT_ET_T", + "SS_BC_T", + "SS_CQ_T", + "SS_ED_T", + "optimize", + "smooth", + "speckles", + "CB_invert", + "CB_MS_smooth", + "CB_MS_stack", + "CB_MS_rb", + "CB_speckles", + "CB_smooth", + "CB_optimize", + /*"CB_live",*/ "CB_SIOX", + "CBT_SS", + "CBT_MS", + "B_RESET", + "B_STOP", + "B_OK", + "mainBox", + "choice_tab", + "choice_scan", + "previewArea"}; auto gladefile = get_filename_string(Inkscape::IO::Resource::UIS, "dialog-trace.glade"); try { builder = Gtk::Builder::create_from_file(gladefile); @@ -292,8 +310,8 @@ TraceDialogImpl2::TraceDialogImpl2() } } -#define GET_O(name) \ - tmp = builder->get_object(#name); \ +#define GET_O(name) \ + tmp = builder->get_object(#name); \ name = Glib::RefPtr::cast_dynamic(tmp); Glib::RefPtr tmp; @@ -320,7 +338,7 @@ TraceDialogImpl2::TraceDialogImpl2() GET_W(CB_speckles) GET_W(CB_smooth) GET_W(CB_optimize) - //GET_W(CB_live) + // GET_W(CB_live) GET_W(CB_SIOX) GET_W(RB_PA_voronoi) GET_W(CBT_SS) @@ -345,23 +363,18 @@ TraceDialogImpl2::TraceDialogImpl2() previewArea->signal_draw().connect(sigc::mem_fun(*this, &TraceDialogImpl2::previewResize)); } - TraceDialogImpl2::~TraceDialogImpl2() { selectChangedConn.disconnect(); selectModifiedConn.disconnect(); } - - TraceDialog &TraceDialog::getInstance() { TraceDialog *dialog = new TraceDialogImpl2(); return *dialog; } - - } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/tracedialog.h b/src/ui/dialog/tracedialog.h index d02e705d52ae567c63b5f26197f7fc7bd8a6871a..032e03a8eff4d7943cdd35969b60d28995ab9d3a 100644 --- a/src/ui/dialog/tracedialog.h +++ b/src/ui/dialog/tracedialog.h @@ -20,22 +20,18 @@ namespace Inkscape { namespace UI { namespace Dialog { - /** * A dialog that displays log messages */ class TraceDialog : public UI::Widget::Panel { - public: - /** * Constructor */ - TraceDialog() : - UI::Widget::Panel("/dialogs/trace", SP_VERB_SELECTION_TRACE) - {} - + TraceDialog() + : UI::Widget::Panel("/dialogs/trace", SP_VERB_SELECTION_TRACE) + {} /** * Factory method @@ -45,15 +41,13 @@ public: /** * Destructor */ - ~TraceDialog() override = default;; - - + ~TraceDialog() override = default; + ; }; - -} //namespace Dialog -} //namespace UI -} //namespace Inkscape +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif /* __TRACEDIALOG_H__ */ diff --git a/src/ui/dialog/transformation.cpp b/src/ui/dialog/transformation.cpp index c275d508befee2f52a3a67d762d546c23a84dd03..95ca603503beb350b6280d5d8a0b1874adb68121 100644 --- a/src/ui/dialog/transformation.cpp +++ b/src/ui/dialog/transformation.cpp @@ -12,9 +12,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "transformation.h" #include <2geom/transforms.h> +#include #include "align-and-distribute.h" #include "desktop.h" @@ -22,17 +23,12 @@ #include "document.h" #include "inkscape.h" #include "message-stack.h" -#include "selection-chemistry.h" -#include "transformation.h" -#include "verbs.h" - #include "object/sp-item-transform.h" #include "object/sp-namedview.h" +#include "selection-chemistry.h" #include "ui/icon-loader.h" - #include "ui/icon-names.h" - - +#include "verbs.h" namespace Inkscape { namespace UI { @@ -55,51 +51,61 @@ static void on_selection_modified(Inkscape::Selection *selection, Transformation ########################################################################*/ Transformation::Transformation() - : UI::Widget::Panel("/dialogs/transformation", SP_VERB_DIALOG_TRANSFORM), - _page_move (4, 2), - _page_scale (4, 2), - _page_rotate (4, 2), - _page_skew (4, 2), - _page_transform (3, 3), - _scalar_move_horizontal (_("_Horizontal:"), _("Horizontal displacement (relative) or position (absolute)"), UNIT_TYPE_LINEAR, - "", "transform-move-horizontal", &_units_move), - _scalar_move_vertical (_("_Vertical:"), _("Vertical displacement (relative) or position (absolute)"), UNIT_TYPE_LINEAR, - "", "transform-move-vertical", &_units_move), - _scalar_scale_horizontal(_("_Width:"), _("Horizontal size (absolute or percentage of current)"), UNIT_TYPE_DIMENSIONLESS, - "", "transform-scale-horizontal", &_units_scale), - _scalar_scale_vertical (_("_Height:"), _("Vertical size (absolute or percentage of current)"), UNIT_TYPE_DIMENSIONLESS, - "", "transform-scale-vertical", &_units_scale), - _scalar_rotate (_("A_ngle:"), _("Rotation angle (positive = counterclockwise)"), UNIT_TYPE_RADIAL, - "", "transform-rotate", &_units_rotate), - _scalar_skew_horizontal (_("_Horizontal:"), _("Horizontal skew angle (positive = counterclockwise), or absolute displacement, or percentage displacement"), UNIT_TYPE_LINEAR, - "", "transform-skew-horizontal", &_units_skew), - _scalar_skew_vertical (_("_Vertical:"), _("Vertical skew angle (positive = clockwise), or absolute displacement, or percentage displacement"), UNIT_TYPE_LINEAR, - "", "transform-skew-vertical", &_units_skew), - - _scalar_transform_a ("_A:", _("Transformation matrix element A")), - _scalar_transform_b ("_B:", _("Transformation matrix element B")), - _scalar_transform_c ("_C:", _("Transformation matrix element C")), - _scalar_transform_d ("_D:", _("Transformation matrix element D")), - _scalar_transform_e ("_E:", _("Transformation matrix element E"), UNIT_TYPE_LINEAR, "", "", &_units_transform), - _scalar_transform_f ("_F:", _("Transformation matrix element F"), UNIT_TYPE_LINEAR, "", "", &_units_transform), - - _counterclockwise_rotate (), - _clockwise_rotate (), - - _check_move_relative (_("Rela_tive move")), - _check_scale_proportional (_("_Scale proportionally")), - _check_apply_separately (_("Apply to each _object separately")), - _check_replace_matrix (_("Edit c_urrent matrix")) + : UI::Widget::Panel("/dialogs/transformation", SP_VERB_DIALOG_TRANSFORM) + , _page_move(4, 2) + , _page_scale(4, 2) + , _page_rotate(4, 2) + , _page_skew(4, 2) + , _page_transform(3, 3) + , _scalar_move_horizontal(_("_Horizontal:"), _("Horizontal displacement (relative) or position (absolute)"), + UNIT_TYPE_LINEAR, "", "transform-move-horizontal", &_units_move) + , _scalar_move_vertical(_("_Vertical:"), _("Vertical displacement (relative) or position (absolute)"), + UNIT_TYPE_LINEAR, "", "transform-move-vertical", &_units_move) + , _scalar_scale_horizontal(_("_Width:"), _("Horizontal size (absolute or percentage of current)"), + UNIT_TYPE_DIMENSIONLESS, "", "transform-scale-horizontal", &_units_scale) + , _scalar_scale_vertical(_("_Height:"), _("Vertical size (absolute or percentage of current)"), + UNIT_TYPE_DIMENSIONLESS, "", "transform-scale-vertical", &_units_scale) + , _scalar_rotate(_("A_ngle:"), _("Rotation angle (positive = counterclockwise)"), UNIT_TYPE_RADIAL, "", + "transform-rotate", &_units_rotate) + , _scalar_skew_horizontal(_("_Horizontal:"), + _("Horizontal skew angle (positive = counterclockwise), or absolute displacement, or " + "percentage displacement"), + UNIT_TYPE_LINEAR, "", "transform-skew-horizontal", &_units_skew) + , _scalar_skew_vertical( + _("_Vertical:"), + _("Vertical skew angle (positive = clockwise), or absolute displacement, or percentage displacement"), + UNIT_TYPE_LINEAR, "", "transform-skew-vertical", &_units_skew) + , + + _scalar_transform_a("_A:", _("Transformation matrix element A")) + , _scalar_transform_b("_B:", _("Transformation matrix element B")) + , _scalar_transform_c("_C:", _("Transformation matrix element C")) + , _scalar_transform_d("_D:", _("Transformation matrix element D")) + , _scalar_transform_e("_E:", _("Transformation matrix element E"), UNIT_TYPE_LINEAR, "", "", &_units_transform) + , _scalar_transform_f("_F:", _("Transformation matrix element F"), UNIT_TYPE_LINEAR, "", "", &_units_transform) + , + + _counterclockwise_rotate() + , _clockwise_rotate() + , + + _check_move_relative(_("Rela_tive move")) + , _check_scale_proportional(_("_Scale proportionally")) + , _check_apply_separately(_("Apply to each _object separately")) + , _check_replace_matrix(_("Edit c_urrent matrix")) { _check_move_relative.set_use_underline(); - _check_move_relative.set_tooltip_text(_("Add the specified relative displacement to the current position; otherwise, edit the current absolute position directly")); + _check_move_relative.set_tooltip_text(_("Add the specified relative displacement to the current position; " + "otherwise, edit the current absolute position directly")); _check_scale_proportional.set_use_underline(); _check_scale_proportional.set_tooltip_text(_("Preserve the width/height ratio of the scaled objects")); _check_apply_separately.set_use_underline(); - _check_apply_separately.set_tooltip_text(_("Apply the scale/rotate/skew to each selected object separately; otherwise, transform the selection as a whole")); + _check_apply_separately.set_tooltip_text(_("Apply the scale/rotate/skew to each selected object separately; " + "otherwise, transform the selection as a whole")); _check_replace_matrix.set_use_underline(); - _check_replace_matrix.set_tooltip_text(_("Edit the current transform= matrix; otherwise, post-multiply transform= by this matrix")); + _check_replace_matrix.set_tooltip_text( + _("Edit the current transform= matrix; otherwise, post-multiply transform= by this matrix")); Gtk::Box *contents = _getContents(); contents->set_spacing(0); @@ -136,13 +142,13 @@ Transformation::Transformation() _check_apply_separately.signal_toggled().connect(sigc::mem_fun(*this, &Transformation::onApplySeparatelyToggled)); // make sure all spinbuttons activate Apply on pressing Enter - ((Gtk::Entry *) (_scalar_move_horizontal.getWidget()))->set_activates_default(true); - ((Gtk::Entry *) (_scalar_move_vertical.getWidget()))->set_activates_default(true); - ((Gtk::Entry *) (_scalar_scale_horizontal.getWidget()))->set_activates_default(true); - ((Gtk::Entry *) (_scalar_scale_vertical.getWidget()))->set_activates_default(true); - ((Gtk::Entry *) (_scalar_rotate.getWidget()))->set_activates_default(true); - ((Gtk::Entry *) (_scalar_skew_horizontal.getWidget()))->set_activates_default(true); - ((Gtk::Entry *) (_scalar_skew_vertical.getWidget()))->set_activates_default(true); + ((Gtk::Entry *)(_scalar_move_horizontal.getWidget()))->set_activates_default(true); + ((Gtk::Entry *)(_scalar_move_vertical.getWidget()))->set_activates_default(true); + ((Gtk::Entry *)(_scalar_scale_horizontal.getWidget()))->set_activates_default(true); + ((Gtk::Entry *)(_scalar_scale_vertical.getWidget()))->set_activates_default(true); + ((Gtk::Entry *)(_scalar_rotate.getWidget()))->set_activates_default(true); + ((Gtk::Entry *)(_scalar_skew_horizontal.getWidget()))->set_activates_default(true); + ((Gtk::Entry *)(_scalar_skew_vertical.getWidget()))->set_activates_default(true); resetButton = addResponseButton(_("_Clear"), 0); if (resetButton) { @@ -159,7 +165,8 @@ Transformation::Transformation() // Connect to the global selection changed & modified signals _selChangeConn = INKSCAPE.signal_selection_changed.connect(sigc::bind(sigc::ptr_fun(&on_selection_changed), this)); - _selModifyConn = INKSCAPE.signal_selection_modified.connect(sigc::hide<1>(sigc::bind(sigc::ptr_fun(&on_selection_modified), this))); + _selModifyConn = INKSCAPE.signal_selection_modified.connect( + sigc::hide<1>(sigc::bind(sigc::ptr_fun(&on_selection_modified), this))); show_all_children(); } @@ -167,7 +174,7 @@ Transformation::Transformation() Transformation::~Transformation() { _selModifyConn.disconnect(); - _selChangeConn.disconnect(); + _selChangeConn.disconnect(); } /*######################################################################## @@ -181,18 +188,14 @@ void Transformation::presentPage(Transformation::PageType page) present(); } - - - /*######################################################################## # S E T U P L A Y O U T ########################################################################*/ - void Transformation::layoutPageMove() { _units_move.setUnitType(UNIT_TYPE_LINEAR); - + _scalar_move_horizontal.initScalar(-1e6, 1e6); _scalar_move_horizontal.setDigits(3); _scalar_move_horizontal.setIncrements(0.1, 1.0); @@ -204,25 +207,22 @@ void Transformation::layoutPageMove() _scalar_move_vertical.set_hexpand(); //_scalar_move_vertical.set_label_image( INKSCAPE_STOCK_ARROWS_HOR ); - + _page_move.table().attach(_scalar_move_horizontal, 0, 0, 2, 1); - _page_move.table().attach(_units_move, 2, 0, 1, 1); + _page_move.table().attach(_units_move, 2, 0, 1, 1); - _scalar_move_horizontal.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onMoveValueChanged)); + _scalar_move_horizontal.signal_value_changed().connect(sigc::mem_fun(*this, &Transformation::onMoveValueChanged)); //_scalar_move_vertical.set_label_image( INKSCAPE_STOCK_ARROWS_VER ); _page_move.table().attach(_scalar_move_vertical, 0, 1, 2, 1); - _scalar_move_vertical.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onMoveValueChanged)); + _scalar_move_vertical.signal_value_changed().connect(sigc::mem_fun(*this, &Transformation::onMoveValueChanged)); // Relative moves _page_move.table().attach(_check_move_relative, 0, 2, 2, 1); _check_move_relative.set_active(true); - _check_move_relative.signal_toggled() - .connect(sigc::mem_fun(*this, &Transformation::onMoveRelativeToggled)); + _check_move_relative.signal_toggled().connect(sigc::mem_fun(*this, &Transformation::onMoveRelativeToggled)); } void Transformation::layoutPageScale() @@ -248,22 +248,21 @@ void Transformation::layoutPageScale() _page_scale.table().attach(_scalar_scale_horizontal, 0, 0, 2, 1); - _scalar_scale_horizontal.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onScaleXValueChanged)); + _scalar_scale_horizontal.signal_value_changed().connect( + sigc::mem_fun(*this, &Transformation::onScaleXValueChanged)); - _page_scale.table().attach(_units_scale, 2, 0, 1, 1); + _page_scale.table().attach(_units_scale, 2, 0, 1, 1); _page_scale.table().attach(_scalar_scale_vertical, 0, 1, 2, 1); - _scalar_scale_vertical.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onScaleYValueChanged)); + _scalar_scale_vertical.signal_value_changed().connect(sigc::mem_fun(*this, &Transformation::onScaleYValueChanged)); _page_scale.table().attach(_check_scale_proportional, 0, 2, 2, 1); _check_scale_proportional.set_active(false); - _check_scale_proportional.signal_toggled() - .connect(sigc::mem_fun(*this, &Transformation::onScaleProportionalToggled)); + _check_scale_proportional.signal_toggled().connect( + sigc::mem_fun(*this, &Transformation::onScaleProportionalToggled)); - //TODO: add a widget for selecting the fixed point in scaling, or honour rotation center? + // TODO: add a widget for selecting the fixed point in scaling, or honour rotation center? } void Transformation::layoutPageRotate() @@ -292,18 +291,18 @@ void Transformation::layoutPageRotate() Gtk::RadioButton::Group group = _counterclockwise_rotate.get_group(); _clockwise_rotate.set_group(group); - _page_rotate.table().attach(_scalar_rotate, 0, 0, 2, 1); - _page_rotate.table().attach(_units_rotate, 2, 0, 1, 1); + _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); + _page_rotate.table().attach(_clockwise_rotate, 4, 0, 1, 1); - _scalar_rotate.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onRotateValueChanged)); + _scalar_rotate.signal_value_changed().connect(sigc::mem_fun(*this, &Transformation::onRotateValueChanged)); - _counterclockwise_rotate.signal_clicked().connect(sigc::mem_fun(*this, &Transformation::onRotateCounterclockwiseClicked)); + _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? + // TODO: honour rotation center? } void Transformation::layoutPageSkew() @@ -323,19 +322,15 @@ void Transformation::layoutPageSkew() _scalar_skew_vertical.set_hexpand(); _page_skew.table().attach(_scalar_skew_horizontal, 0, 0, 2, 1); - _page_skew.table().attach(_units_skew, 2, 0, 1, 1); - _page_skew.table().attach(_scalar_skew_vertical, 0, 1, 2, 1); + _page_skew.table().attach(_units_skew, 2, 0, 1, 1); + _page_skew.table().attach(_scalar_skew_vertical, 0, 1, 2, 1); - _scalar_skew_horizontal.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onSkewValueChanged)); - _scalar_skew_vertical.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onSkewValueChanged)); + _scalar_skew_horizontal.signal_value_changed().connect(sigc::mem_fun(*this, &Transformation::onSkewValueChanged)); + _scalar_skew_vertical.signal_value_changed().connect(sigc::mem_fun(*this, &Transformation::onSkewValueChanged)); - //TODO: honour rotation center? + // TODO: honour rotation center? } - - void Transformation::layoutPageTransform() { _units_transform.setUnitType(UNIT_TYPE_LINEAR); @@ -351,8 +346,7 @@ void Transformation::layoutPageTransform() _page_transform.table().attach(_scalar_transform_a, 0, 0, 1, 1); - _scalar_transform_a.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); + _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); @@ -364,8 +358,7 @@ void Transformation::layoutPageTransform() _page_transform.table().attach(_scalar_transform_b, 0, 1, 1, 1); - _scalar_transform_b.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); + _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); @@ -377,9 +370,7 @@ void Transformation::layoutPageTransform() _page_transform.table().attach(_scalar_transform_c, 1, 0, 1, 1); - _scalar_transform_c.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); - + _scalar_transform_c.signal_value_changed().connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); _scalar_transform_d.setWidgetSizeRequest(65, -1); _scalar_transform_d.setRange(-1e10, 1e10); @@ -391,9 +382,7 @@ void Transformation::layoutPageTransform() _page_transform.table().attach(_scalar_transform_d, 1, 1, 1, 1); - _scalar_transform_d.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); - + _scalar_transform_d.signal_value_changed().connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); _scalar_transform_e.setWidgetSizeRequest(65, -1); _scalar_transform_e.setRange(-1e10, 1e10); @@ -405,9 +394,7 @@ void Transformation::layoutPageTransform() _page_transform.table().attach(_scalar_transform_e, 2, 0, 1, 1); - _scalar_transform_e.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); - + _scalar_transform_e.signal_value_changed().connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); _scalar_transform_f.setWidgetSizeRequest(65, -1); _scalar_transform_f.setRange(-1e10, 1e10); @@ -420,18 +407,15 @@ void Transformation::layoutPageTransform() _page_transform.table().attach(_scalar_transform_f, 2, 1, 1, 1); _page_transform.table().attach(_units_transform, 2, 2, 1, 1); - _scalar_transform_f.signal_value_changed() - .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); + _scalar_transform_f.signal_value_changed().connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); // Edit existing matrix _page_transform.table().attach(_check_replace_matrix, 0, 3, 2, 1); _check_replace_matrix.set_active(false); - _check_replace_matrix.signal_toggled() - .connect(sigc::mem_fun(*this, &Transformation::onReplaceMatrixToggled)); + _check_replace_matrix.signal_toggled().connect(sigc::mem_fun(*this, &Transformation::onReplaceMatrixToggled)); } - /*######################################################################## # U P D A T E ########################################################################*/ @@ -467,8 +451,7 @@ void Transformation::updateSelection(PageType page, Inkscape::Selection *selecti } } - setResponseSensitive(Gtk::RESPONSE_APPLY, - selection && !selection->isEmpty()); + setResponseSensitive(Gtk::RESPONSE_APPLY, selection && !selection->isEmpty()); } void Transformation::onSwitchPage(Gtk::Widget * /*page*/, guint pagenum) @@ -480,7 +463,6 @@ void Transformation::onSwitchPage(Gtk::Widget * /*page*/, guint pagenum) updateSelection((PageType)pagenum, getDesktop()->getSelection()); } - void Transformation::updatePageMove(Inkscape::Selection *selection) { if (selection && !selection->isEmpty()) { @@ -553,7 +535,7 @@ void Transformation::updatePageTransform(Inkscape::Selection *selection) { if (selection && !selection->isEmpty()) { if (_check_replace_matrix.get_active()) { - Geom::Affine current (selection->items().front()->transform); // take from the first item in selection + Geom::Affine current(selection->items().front()->transform); // take from the first item in selection Geom::Affine new_displayed = current; @@ -572,19 +554,13 @@ void Transformation::updatePageTransform(Inkscape::Selection *selection) } } - - - - /*######################################################################## # A P P L Y ########################################################################*/ - - void Transformation::_apply() { - Inkscape::Selection * const selection = _getSelection(); + Inkscape::Selection *const selection = _getSelection(); if (!selection || selection->isEmpty()) return; @@ -613,8 +589,8 @@ void Transformation::_apply() } } - //Let's play with never turning this off - //setResponseSensitive(Gtk::RESPONSE_APPLY, false); + // Let's play with never turning this off + // setResponseSensitive(Gtk::RESPONSE_APPLY, false); } void Transformation::applyPageMove(Inkscape::Selection *selection) @@ -637,51 +613,43 @@ void Transformation::applyPageMove(Inkscape::Selection *selection) } } } else { - if (_check_move_relative.get_active()) { // shift each object relatively to the previous one - std::vector selected(selection->items().begin(), selection->items().end()); - if (selected.empty()) return; + std::vector selected(selection->items().begin(), selection->items().end()); + if (selected.empty()) + return; if (fabs(x) > 1e-6) { - std::vector< BBoxSort > sorted; - for (auto item : selected) - { - Geom::OptRect bbox = item->desktopPreferredBounds(); + std::vector sorted; + for (auto item : selected) { + Geom::OptRect bbox = item->desktopPreferredBounds(); if (bbox) { - sorted.emplace_back(item, *bbox, Geom::X, x > 0? 1. : 0., x > 0? 0. : 1.); + sorted.emplace_back(item, *bbox, Geom::X, x > 0 ? 1. : 0., x > 0 ? 0. : 1.); } } - //sort bbox by anchors + // sort bbox by anchors std::stable_sort(sorted.begin(), sorted.end()); double move = x; - for ( std::vector ::iterator it (sorted.begin()); - it < sorted.end(); - ++it ) - { + for (std::vector::iterator it(sorted.begin()); it < sorted.end(); ++it) { it->item->move_rel(Geom::Translate(move, 0)); // move each next object by x relative to previous move += x; } } if (fabs(y) > 1e-6) { - std::vector< BBoxSort > sorted; - for (auto item : selected) - { - Geom::OptRect bbox = item->desktopPreferredBounds(); + std::vector sorted; + for (auto item : selected) { + Geom::OptRect bbox = item->desktopPreferredBounds(); if (bbox) { - sorted.emplace_back(item, *bbox, Geom::Y, y > 0? 1. : 0., y > 0? 0. : 1.); + sorted.emplace_back(item, *bbox, Geom::Y, y > 0 ? 1. : 0., y > 0 ? 0. : 1.); } } - //sort bbox by anchors + // sort bbox by anchors std::stable_sort(sorted.begin(), sorted.end()); double move = y; - for ( std::vector ::iterator it (sorted.begin()); - it < sorted.end(); - ++it ) - { + for (std::vector::iterator it(sorted.begin()); it < sorted.end(); ++it) { it->item->move_rel(Geom::Translate(0, move)); // move each next object by x relative to previous move += y; @@ -695,8 +663,7 @@ void Transformation::applyPageMove(Inkscape::Selection *selection) } } - DocumentUndo::done( selection->desktop()->getDocument() , SP_VERB_DIALOG_TRANSFORM, - _("Move")); + DocumentUndo::done(selection->desktop()->getDocument(), SP_VERB_DIALOG_TRANSFORM, _("Move")); } void Transformation::applyPageScale(Inkscape::Selection *selection) @@ -708,8 +675,8 @@ void Transformation::applyPageScale(Inkscape::Selection *selection) bool transform_stroke = prefs->getBool("/options/transform/stroke", true); bool preserve = prefs->getBool("/options/preservetransform/value", false); if (prefs->getBool("/dialogs/transformation/applyseparately")) { - auto tmp= selection->items(); - for(auto i=tmp.begin();i!=tmp.end();++i){ + auto tmp = selection->items(); + for (auto i = tmp.begin(); i != tmp.end(); ++i) { SPItem *item = *i; Geom::OptRect bbox_pref = item->desktopPreferredBounds(); Geom::OptRect bbox_geom = item->desktopGeometricBounds(); @@ -718,18 +685,21 @@ void Transformation::applyPageScale(Inkscape::Selection *selection) double new_height = scaleY; // the values are increments! if (!_units_scale.isAbsolute()) { // Relative scaling, i.e in percent - new_width = scaleX/100 * bbox_pref->width(); - new_height = scaleY/100 * bbox_pref->height(); + new_width = scaleX / 100 * bbox_pref->width(); + new_height = scaleY / 100 * bbox_pref->height(); } - if (fabs(new_width) < 1e-6) new_width = 1e-6; // not 0, as this would result in a nasty no-bbox object - if (fabs(new_height) < 1e-6) new_height = 1e-6; - - double x0 = bbox_pref->midpoint()[Geom::X] - new_width/2; - 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, preserve, x0, y0, x1, y1); + if (fabs(new_width) < 1e-6) + new_width = 1e-6; // not 0, as this would result in a nasty no-bbox object + if (fabs(new_height) < 1e-6) + new_height = 1e-6; + + double x0 = bbox_pref->midpoint()[Geom::X] - new_width / 2; + 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, + preserve, x0, y0, x1, y1); item->set_i2d_affine(item->i2dt_affine() * scaler); item->doWriteTransform(item->transform); } @@ -742,24 +712,26 @@ void Transformation::applyPageScale(Inkscape::Selection *selection) double new_width = scaleX; double new_height = scaleY; if (!_units_scale.isAbsolute()) { // Relative scaling, i.e in percent - new_width = scaleX/100 * bbox_pref->width(); - new_height = scaleY/100 * bbox_pref->height(); + new_width = scaleX / 100 * bbox_pref->width(); + new_height = scaleY / 100 * bbox_pref->height(); } - if (fabs(new_width) < 1e-6) new_width = 1e-6; - if (fabs(new_height) < 1e-6) new_height = 1e-6; - - double x0 = bbox_pref->midpoint()[Geom::X] - new_width/2; - 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, preserve, x0, y0, x1, y1); + if (fabs(new_width) < 1e-6) + new_width = 1e-6; + if (fabs(new_height) < 1e-6) + new_height = 1e-6; + + double x0 = bbox_pref->midpoint()[Geom::X] - new_width / 2; + 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, + preserve, x0, y0, x1, y1); selection->applyAffine(scaler); } } - DocumentUndo::done(selection->desktop()->getDocument(), SP_VERB_DIALOG_TRANSFORM, - _("Scale")); + DocumentUndo::done(selection->desktop()->getDocument(), SP_VERB_DIALOG_TRANSFORM, _("Scale")); } void Transformation::applyPageRotate(Inkscape::Selection *selection) @@ -772,10 +744,10 @@ void Transformation::applyPageRotate(Inkscape::Selection *selection) } if (prefs->getBool("/dialogs/transformation/applyseparately")) { - auto tmp= selection->items(); - for(auto i=tmp.begin();i!=tmp.end();++i){ + auto tmp = selection->items(); + for (auto i = tmp.begin(); i != tmp.end(); ++i) { SPItem *item = *i; - item->rotate_rel(Geom::Rotate (angle*M_PI/180.0)); + item->rotate_rel(Geom::Rotate(angle * M_PI / 180.0)); } } else { boost::optional center = selection->center(); @@ -784,35 +756,36 @@ void Transformation::applyPageRotate(Inkscape::Selection *selection) } } - DocumentUndo::done(selection->desktop()->getDocument(), SP_VERB_DIALOG_TRANSFORM, - _("Rotate")); + DocumentUndo::done(selection->desktop()->getDocument(), SP_VERB_DIALOG_TRANSFORM, _("Rotate")); } void Transformation::applyPageSkew(Inkscape::Selection *selection) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs->getBool("/dialogs/transformation/applyseparately")) { - auto items = selection->items(); - for(auto i = items.begin();i!=items.end();++i){ + auto items = selection->items(); + for (auto i = items.begin(); i != items.end(); ++i) { SPItem *item = *i; if (!_units_skew.isAbsolute()) { // percentage double skewX = _scalar_skew_horizontal.getValue("%"); double skewY = _scalar_skew_vertical.getValue("%"); skewY *= getDesktop()->yaxisdir(); - if (fabs(0.01*skewX*0.01*skewY - 1.0) < Geom::EPSILON) { - getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, not used.")); + if (fabs(0.01 * skewX * 0.01 * skewY - 1.0) < Geom::EPSILON) { + getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Transform matrix is singular, not used.")); return; } - item->skew_rel(0.01*skewX, 0.01*skewY); - } else if (_units_skew.isRadial()) { //deg or rad + item->skew_rel(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)) { - getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, not used.")); + 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)) { + getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Transform matrix is singular, not used.")); return; } double skewX = tan(angleX); @@ -828,11 +801,12 @@ 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) { - getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, not used.")); + if (fabs(skewX * skewY - width * height) < Geom::EPSILON) { + getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Transform matrix is singular, not used.")); return; } - item->skew_rel(skewX/height, skewY/width); + item->skew_rel(skewX / height, skewY / width); } } } @@ -840,27 +814,29 @@ void Transformation::applyPageSkew(Inkscape::Selection *selection) Geom::OptRect bbox = selection->preferredBounds(); boost::optional center = selection->center(); - if ( bbox && center ) { - double width = bbox->dimensions()[Geom::X]; + if (bbox && center) { + double width = bbox->dimensions()[Geom::X]; double height = bbox->dimensions()[Geom::Y]; if (!_units_skew.isAbsolute()) { // percentage double skewX = _scalar_skew_horizontal.getValue("%"); double skewY = _scalar_skew_vertical.getValue("%"); skewY *= getDesktop()->yaxisdir(); - if (fabs(0.01*skewX*0.01*skewY - 1.0) < Geom::EPSILON) { - getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, not used.")); + if (fabs(0.01 * skewX * 0.01 * skewY - 1.0) < Geom::EPSILON) { + getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Transform matrix is singular, not used.")); return; } selection->skewRelative(*center, 0.01 * skewX, 0.01 * skewY); - } else if (_units_skew.isRadial()) { //deg or rad + } 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)) { - getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, not used.")); + 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)) { + getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Transform matrix is singular, not used.")); return; } double skewX = tan(angleX); @@ -872,8 +848,9 @@ void Transformation::applyPageSkew(Inkscape::Selection *selection) double skewX = _scalar_skew_horizontal.getValue("px"); double skewY = _scalar_skew_vertical.getValue("px"); skewY *= getDesktop()->yaxisdir(); - if (fabs(skewX*skewY - width*height) < Geom::EPSILON) { - getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, not used.")); + if (fabs(skewX * skewY - width * height) < Geom::EPSILON) { + getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Transform matrix is singular, not used.")); return; } selection->skewRelative(*center, skewX / height, skewY / width); @@ -881,11 +858,9 @@ void Transformation::applyPageSkew(Inkscape::Selection *selection) } } - DocumentUndo::done(selection->desktop()->getDocument(), SP_VERB_DIALOG_TRANSFORM, - _("Skew")); + DocumentUndo::done(selection->desktop()->getDocument(), SP_VERB_DIALOG_TRANSFORM, _("Skew")); } - void Transformation::applyPageTransform(Inkscape::Selection *selection) { double a = _scalar_transform_a.getValue(); @@ -897,13 +872,14 @@ void Transformation::applyPageTransform(Inkscape::Selection *selection) Geom::Affine displayed(a, b, c, d, e, f); if (displayed.isSingular()) { - getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, not used.")); + getDesktop()->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Transform matrix is singular, not used.")); return; } if (_check_replace_matrix.get_active()) { - auto tmp = selection->items(); - for(auto i=tmp.begin();i!=tmp.end();++i){ + auto tmp = selection->items(); + for (auto i = tmp.begin(); i != tmp.end(); ++i) { SPItem *item = *i; item->set_item_transform(displayed); item->updateRepr(); @@ -912,14 +888,9 @@ void Transformation::applyPageTransform(Inkscape::Selection *selection) selection->applyAffine(displayed); // post-multiply each object's transform } - DocumentUndo::done(selection->desktop()->getDocument(), SP_VERB_DIALOG_TRANSFORM, - _("Edit transformation matrix")); + DocumentUndo::done(selection->desktop()->getDocument(), SP_VERB_DIALOG_TRANSFORM, _("Edit transformation matrix")); } - - - - /*######################################################################## # V A L U E - C H A N G E D C A L L B A C K S ########################################################################*/ @@ -941,7 +912,7 @@ void Transformation::onMoveRelativeToggled() double conversion = _units_move.getConversion("px"); - //g_message("onMoveRelativeToggled: %f, %f px\n", x, y); + // g_message("onMoveRelativeToggled: %f, %f px\n", x, y); Geom::OptRect bbox = selection->preferredBounds(); @@ -949,11 +920,11 @@ void Transformation::onMoveRelativeToggled() if (_check_move_relative.get_active()) { // From absolute to relative _scalar_move_horizontal.setValue((x - bbox->min()[Geom::X]) / conversion); - _scalar_move_vertical.setValue(( y - bbox->min()[Geom::Y]) / conversion); + _scalar_move_vertical.setValue((y - bbox->min()[Geom::Y]) / conversion); } else { // From relative to absolute _scalar_move_horizontal.setValue((bbox->min()[Geom::X] + x) / conversion); - _scalar_move_vertical.setValue(( bbox->min()[Geom::Y] + y) / conversion); + _scalar_move_vertical.setValue((bbox->min()[Geom::Y] + y) / conversion); } } @@ -974,7 +945,7 @@ void Transformation::onScaleXValueChanged() _scalar_scale_vertical.setValue(_scalar_scale_horizontal.getValue("%")); } else { double scaleXPercentage = _scalar_scale_horizontal.getAsPercentage(); - _scalar_scale_vertical.setFromPercentage (scaleXPercentage); + _scalar_scale_vertical.setFromPercentage(scaleXPercentage); } } } @@ -993,7 +964,7 @@ void Transformation::onScaleYValueChanged() _scalar_scale_horizontal.setValue(_scalar_scale_vertical.getValue("%")); } else { double scaleYPercentage = _scalar_scale_vertical.getAsPercentage(); - _scalar_scale_horizontal.setFromPercentage (scaleYPercentage); + _scalar_scale_horizontal.setFromPercentage(scaleYPercentage); } } } @@ -1024,7 +995,6 @@ void Transformation::onSkewValueChanged() void Transformation::onTransformValueChanged() { - /* double a = _scalar_transform_a.getValue(); double b = _scalar_transform_b.getValue(); @@ -1054,7 +1024,7 @@ void Transformation::onReplaceMatrixToggled() double e = _scalar_transform_e.getValue("px"); double f = _scalar_transform_f.getValue("px"); - Geom::Affine displayed (a, b, c, d, e, f); + Geom::Affine displayed(a, b, c, d, e, f); Geom::Affine current = selection->items().front()->transform; // take from the first item in selection Geom::Affine new_displayed; @@ -1080,49 +1050,48 @@ void Transformation::onScaleProportionalToggled() } } - void Transformation::onClear() { int const page = _notebook.get_current_page(); switch (page) { - case PAGE_MOVE: { - Inkscape::Selection *selection = _getSelection(); - if (!selection || selection->isEmpty() || _check_move_relative.get_active()) { - _scalar_move_horizontal.setValue(0); - _scalar_move_vertical.setValue(0); - } else { - Geom::OptRect bbox = selection->preferredBounds(); - if (bbox) { - _scalar_move_horizontal.setValue(bbox->min()[Geom::X], "px"); - _scalar_move_vertical.setValue(bbox->min()[Geom::Y], "px"); + case PAGE_MOVE: { + Inkscape::Selection *selection = _getSelection(); + if (!selection || selection->isEmpty() || _check_move_relative.get_active()) { + _scalar_move_horizontal.setValue(0); + _scalar_move_vertical.setValue(0); + } else { + Geom::OptRect bbox = selection->preferredBounds(); + if (bbox) { + _scalar_move_horizontal.setValue(bbox->min()[Geom::X], "px"); + _scalar_move_vertical.setValue(bbox->min()[Geom::Y], "px"); + } } + break; + } + case PAGE_ROTATE: { + _scalar_rotate.setValue(0); + break; + } + case PAGE_SCALE: { + _scalar_scale_horizontal.setValue(100, "%"); + _scalar_scale_vertical.setValue(100, "%"); + break; + } + case PAGE_SKEW: { + _scalar_skew_horizontal.setValue(0); + _scalar_skew_vertical.setValue(0); + break; + } + case PAGE_TRANSFORM: { + _scalar_transform_a.setValue(1); + _scalar_transform_b.setValue(0); + _scalar_transform_c.setValue(0); + _scalar_transform_d.setValue(1); + _scalar_transform_e.setValue(0, "px"); + _scalar_transform_f.setValue(0, "px"); + break; } - break; - } - case PAGE_ROTATE: { - _scalar_rotate.setValue(0); - break; - } - case PAGE_SCALE: { - _scalar_scale_horizontal.setValue(100, "%"); - _scalar_scale_vertical.setValue(100, "%"); - break; - } - case PAGE_SKEW: { - _scalar_skew_horizontal.setValue(0); - _scalar_skew_vertical.setValue(0); - break; - } - case PAGE_TRANSFORM: { - _scalar_transform_a.setValue(1); - _scalar_transform_b.setValue(0); - _scalar_transform_c.setValue(0); - _scalar_transform_d.setValue(1); - _scalar_transform_e.setValue(0, "px"); - _scalar_transform_f.setValue(0, "px"); - break; - } } } @@ -1132,7 +1101,7 @@ void Transformation::onApplySeparatelyToggled() prefs->setBool("/dialogs/transformation/applyseparately", _check_apply_separately.get_active()); } -void Transformation::setDesktop(SPDesktop*desktop) +void Transformation::setDesktop(SPDesktop *desktop) { Panel::setDesktop(desktop); @@ -1159,7 +1128,6 @@ void Transformation::setDesktop(SPDesktop*desktop) updateSelection(PAGE_MOVE, _getSelection()); } - } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/transformation.h b/src/ui/dialog/transformation.h index a84db07f226db012ca5b6c110b753685e30f3a82..f6696718f91a19bd5d27d08afe66ba59c3126f20 100644 --- a/src/ui/dialog/transformation.h +++ b/src/ui/dialog/transformation.h @@ -12,14 +12,13 @@ #ifndef INKSCAPE_UI_DIALOG_TRANSFORMATION_H #define INKSCAPE_UI_DIALOG_TRANSFORMATION_H - +#include +#include #include #include -#include -#include -#include "ui/widget/panel.h" #include "ui/widget/notebook-page.h" +#include "ui/widget/panel.h" #include "ui/widget/scalar-unit.h" namespace Gtk { @@ -30,22 +29,19 @@ namespace Inkscape { namespace UI { namespace Dialog { - /** * Transformation dialog. - * + * * The transformation dialog allows to modify Inkscape objects. * 5 transformation operations are currently possible: move, scale, - * rotate, skew and matrix. + * rotate, skew and matrix. */ class Transformation : public UI::Widget::Panel { - public: - /** * Constructor for Transformation. - * + * * This does the initialization * and layout of the dialog used for transforming SVG objects. It * consists of 5 pages for the 5 operations it handles: @@ -72,48 +68,43 @@ public: /** * Factory method. Create an instance of this class/interface */ - static Transformation &getInstance() - { return *new Transformation(); } - + static Transformation &getInstance() { return *new Transformation(); } /** * Show the Move panel */ - void setPageMove() - { presentPage(PAGE_MOVE); } - + void setPageMove() { presentPage(PAGE_MOVE); } /** * Show the Scale panel */ - void setPageScale() - { presentPage(PAGE_SCALE); } - + void setPageScale() { presentPage(PAGE_SCALE); } /** * Show the Rotate panel */ - void setPageRotate() - { presentPage(PAGE_ROTATE); } + void setPageRotate() { presentPage(PAGE_ROTATE); } /** * Show the Skew panel */ - void setPageSkew() - { presentPage(PAGE_SKEW); } + void setPageSkew() { presentPage(PAGE_SKEW); } /** * Show the Transform panel */ - void setPageTransform() - { presentPage(PAGE_TRANSFORM); } - - - int getCurrentPage() - { return _notebook.get_current_page(); } - - enum PageType { - PAGE_MOVE, PAGE_SCALE, PAGE_ROTATE, PAGE_SKEW, PAGE_TRANSFORM, PAGE_QTY + void setPageTransform() { presentPage(PAGE_TRANSFORM); } + + int getCurrentPage() { return _notebook.get_current_page(); } + + enum PageType + { + PAGE_MOVE, + PAGE_SCALE, + PAGE_ROTATE, + PAGE_SKEW, + PAGE_TRANSFORM, + PAGE_QTY }; void updateSelection(PageType page, Inkscape::Selection *selection); @@ -121,43 +112,42 @@ public: void setDesktop(SPDesktop *) override; protected: - - Gtk::Notebook _notebook; - - UI::Widget::NotebookPage _page_move; - UI::Widget::NotebookPage _page_scale; - UI::Widget::NotebookPage _page_rotate; - UI::Widget::NotebookPage _page_skew; - UI::Widget::NotebookPage _page_transform; - - UI::Widget::UnitMenu _units_move; - UI::Widget::UnitMenu _units_scale; - UI::Widget::UnitMenu _units_rotate; - UI::Widget::UnitMenu _units_skew; - UI::Widget::UnitMenu _units_transform; - - UI::Widget::ScalarUnit _scalar_move_horizontal; - UI::Widget::ScalarUnit _scalar_move_vertical; - UI::Widget::ScalarUnit _scalar_scale_horizontal; - UI::Widget::ScalarUnit _scalar_scale_vertical; - UI::Widget::ScalarUnit _scalar_rotate; - UI::Widget::ScalarUnit _scalar_skew_horizontal; - UI::Widget::ScalarUnit _scalar_skew_vertical; - - UI::Widget::Scalar _scalar_transform_a; - UI::Widget::Scalar _scalar_transform_b; - UI::Widget::Scalar _scalar_transform_c; - UI::Widget::Scalar _scalar_transform_d; - UI::Widget::ScalarUnit _scalar_transform_e; - UI::Widget::ScalarUnit _scalar_transform_f; - - Gtk::RadioButton _counterclockwise_rotate; - Gtk::RadioButton _clockwise_rotate; - - Gtk::CheckButton _check_move_relative; - Gtk::CheckButton _check_scale_proportional; - Gtk::CheckButton _check_apply_separately; - Gtk::CheckButton _check_replace_matrix; + Gtk::Notebook _notebook; + + UI::Widget::NotebookPage _page_move; + UI::Widget::NotebookPage _page_scale; + UI::Widget::NotebookPage _page_rotate; + UI::Widget::NotebookPage _page_skew; + UI::Widget::NotebookPage _page_transform; + + UI::Widget::UnitMenu _units_move; + UI::Widget::UnitMenu _units_scale; + UI::Widget::UnitMenu _units_rotate; + UI::Widget::UnitMenu _units_skew; + UI::Widget::UnitMenu _units_transform; + + UI::Widget::ScalarUnit _scalar_move_horizontal; + UI::Widget::ScalarUnit _scalar_move_vertical; + UI::Widget::ScalarUnit _scalar_scale_horizontal; + UI::Widget::ScalarUnit _scalar_scale_vertical; + UI::Widget::ScalarUnit _scalar_rotate; + UI::Widget::ScalarUnit _scalar_skew_horizontal; + UI::Widget::ScalarUnit _scalar_skew_vertical; + + UI::Widget::Scalar _scalar_transform_a; + UI::Widget::Scalar _scalar_transform_b; + UI::Widget::Scalar _scalar_transform_c; + UI::Widget::Scalar _scalar_transform_d; + UI::Widget::ScalarUnit _scalar_transform_e; + UI::Widget::ScalarUnit _scalar_transform_f; + + Gtk::RadioButton _counterclockwise_rotate; + Gtk::RadioButton _clockwise_rotate; + + Gtk::CheckButton _check_move_relative; + Gtk::CheckButton _check_scale_proportional; + Gtk::CheckButton _check_apply_separately; + Gtk::CheckButton _check_replace_matrix; /** * Layout the GUI components, and prepare for use @@ -214,7 +204,6 @@ protected: void applyPageTransform(Inkscape::Selection *); private: - /** * Copy constructor */ @@ -233,19 +222,11 @@ private: sigc::connection _selModifyConn; }; - - - } // namespace Dialog } // namespace UI } // namespace Inkscape - - -#endif //INKSCAPE_UI_DIALOG_TRANSFORMATION_H - - - +#endif // INKSCAPE_UI_DIALOG_TRANSFORMATION_H /* Local Variables: diff --git a/src/ui/dialog/undo-history.cpp b/src/ui/dialog/undo-history.cpp index 77c48313f36c8a6850d2dd8f7ee4764e6098e878..4a8f570709d636fe7918a0e32f3ddd0a455b4fec 100644 --- a/src/ui/dialog/undo-history.cpp +++ b/src/ui/dialog/undo-history.cpp @@ -14,40 +14,35 @@ #include "undo-history.h" +#include "desktop.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" #include "ui/icon-loader.h" #include "util/signal-blocker.h" -#include "desktop.h" - - namespace Inkscape { namespace UI { namespace Dialog { /* Rendering functions for custom cell renderers */ -void CellRendererSPIcon::render_vfunc(const Cairo::RefPtr& cr, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, +void CellRendererSPIcon::render_vfunc(const Cairo::RefPtr &cr, Gtk::Widget &widget, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, Gtk::CellRendererState flags) { // if this event type doesn't have an icon... - if ( !Inkscape::Verb::get(_property_event_type)->get_image() ) return; + if (!Inkscape::Verb::get(_property_event_type)->get_image()) + return; // if the icon isn't cached, render it to a pixbuf - if ( !_icon_cache[_property_event_type] ) { - + if (!_icon_cache[_property_event_type]) { Glib::ustring image_name = Inkscape::Verb::get(_property_event_type)->get_image(); - Gtk::Image* icon = Gtk::manage(new Gtk::Image()); + Gtk::Image *icon = Gtk::manage(new Gtk::Image()); icon = sp_get_icon_image(image_name, Gtk::ICON_SIZE_MENU); if (icon) { - // check icon type (inkscape, gtk, none) - if ( GTK_IS_IMAGE(icon->gobj()) ) { + if (GTK_IS_IMAGE(icon->gobj())) { _property_icon = sp_get_icon_pixbuf(image_name, 16); } else { delete icon; @@ -62,43 +57,38 @@ void CellRendererSPIcon::render_vfunc(const Cairo::RefPtr& cr, property_pixbuf() = _icon_cache[_property_event_type]; } - Gtk::CellRendererPixbuf::render_vfunc(cr, widget, background_area, - cell_area, flags); + Gtk::CellRendererPixbuf::render_vfunc(cr, widget, background_area, cell_area, flags); } - -void CellRendererInt::render_vfunc(const Cairo::RefPtr& cr, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, +void CellRendererInt::render_vfunc(const Cairo::RefPtr &cr, Gtk::Widget &widget, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, Gtk::CellRendererState flags) { - if( _filter(_property_number) ) { + if (_filter(_property_number)) { std::ostringstream s; s << _property_number << std::flush; property_text() = s.str(); - Gtk::CellRendererText::render_vfunc(cr, widget, background_area, - cell_area, flags); + Gtk::CellRendererText::render_vfunc(cr, widget, background_area, cell_area, flags); } } -const CellRendererInt::Filter& CellRendererInt::no_filter = CellRendererInt::NoFilter(); +const CellRendererInt::Filter &CellRendererInt::no_filter = CellRendererInt::NoFilter(); -UndoHistory& UndoHistory::getInstance() +UndoHistory &UndoHistory::getInstance() { return *new UndoHistory(); } UndoHistory::UndoHistory() - : UI::Widget::Panel("/dialogs/undo-history", SP_VERB_DIALOG_UNDO_HISTORY), - _document_replaced_connection(), - _desktop(nullptr), - _document(nullptr), - _event_log(nullptr), - _scrolled_window(), - _event_list_store(), - _event_list_selection(_event_list_view.get_selection()), - _callback_connections() + : UI::Widget::Panel("/dialogs/undo-history", SP_VERB_DIALOG_UNDO_HISTORY) + , _document_replaced_connection() + , _desktop(nullptr) + , _document(nullptr) + , _event_log(nullptr) + , _scrolled_window() + , _event_list_store() + , _event_list_selection(_event_list_view.get_selection()) + , _callback_connections() { auto *_columns = &EventLog::getColumns(); @@ -110,47 +100,47 @@ UndoHistory::UndoHistory() _event_list_view.set_enable_search(false); _event_list_view.set_headers_visible(false); - CellRendererSPIcon* icon_renderer = Gtk::manage(new CellRendererSPIcon()); + CellRendererSPIcon *icon_renderer = Gtk::manage(new CellRendererSPIcon()); 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); + 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)); + 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); + 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()); + 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); + 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); + description_column->set_min_width(150); - _event_list_view.set_expander_column( *_event_list_view.get_column(cols_count-1) ); + _event_list_view.set_expander_column(*_event_list_view.get_column(cols_count - 1)); _scrolled_window.add(_event_list_view); // connect EventLog callbacks - _callback_connections[EventLog::CALLB_SELECTION_CHANGE] = - _event_list_selection->signal_changed().connect(sigc::mem_fun(*this, &Inkscape::UI::Dialog::UndoHistory::_onListSelectionChange)); + _callback_connections[EventLog::CALLB_SELECTION_CHANGE] = _event_list_selection->signal_changed().connect( + sigc::mem_fun(*this, &Inkscape::UI::Dialog::UndoHistory::_onListSelectionChange)); - _callback_connections[EventLog::CALLB_EXPAND] = - _event_list_view.signal_row_expanded().connect(sigc::mem_fun(*this, &Inkscape::UI::Dialog::UndoHistory::_onExpandEvent)); + _callback_connections[EventLog::CALLB_EXPAND] = _event_list_view.signal_row_expanded().connect( + sigc::mem_fun(*this, &Inkscape::UI::Dialog::UndoHistory::_onExpandEvent)); - _callback_connections[EventLog::CALLB_COLLAPSE] = - _event_list_view.signal_row_collapsed().connect(sigc::mem_fun(*this, &Inkscape::UI::Dialog::UndoHistory::_onCollapseEvent)); + _callback_connections[EventLog::CALLB_COLLAPSE] = _event_list_view.signal_row_collapsed().connect( + sigc::mem_fun(*this, &Inkscape::UI::Dialog::UndoHistory::_onCollapseEvent)); // connect to be informed of document changes signalDocumentReplaced().connect(sigc::mem_fun(*this, &UndoHistory::_handleDocumentReplaced)); @@ -158,26 +148,21 @@ UndoHistory::UndoHistory() show_all_children(); } -UndoHistory::~UndoHistory() -{ -} - +UndoHistory::~UndoHistory() {} -void UndoHistory::setDesktop(SPDesktop* desktop) +void UndoHistory::setDesktop(SPDesktop *desktop) { Panel::setDesktop(desktop); EventLog *newEventLog = desktop ? desktop->event_log : nullptr; if ((_desktop == desktop) && (_event_log == newEventLog)) { // same desktop set - } - else - { + } else { _connectDocument(desktop, desktop ? desktop->doc() : nullptr); } } -void UndoHistory::_connectDocument(SPDesktop* desktop, SPDocument * /*document*/) +void UndoHistory::_connectDocument(SPDesktop *desktop, SPDocument * /*document*/) { // disconnect from prior if (_event_log) { @@ -204,11 +189,11 @@ void UndoHistory::_connectEventLog() _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())); + _event_list_view.scroll_to_row(_event_list_store->get_path(_event_list_selection->get_selected())); } } -void UndoHistory::_handleDocumentReplaced(SPDesktop* desktop, SPDocument *document) +void UndoHistory::_handleDocumentReplaced(SPDesktop *desktop, SPDocument *document) { if ((desktop != _desktop) || (document != _document)) { _connectDocument(desktop, document); @@ -219,7 +204,7 @@ void *UndoHistory::_handleEventLogDestroyCB(void *data) { void *result = nullptr; if (data) { - UndoHistory *self = reinterpret_cast(data); + UndoHistory *self = reinterpret_cast(data); result = self->_handleEventLogDestroy(); } return result; @@ -239,26 +224,22 @@ void *UndoHistory::_handleEventLogDestroy() return nullptr; } -void -UndoHistory::_onListSelectionChange() +void UndoHistory::_onListSelectionChange() { - EventLog::const_iterator selected = _event_list_selection->get_selected(); /* If no event is selected in the view, find the right one and select it. This happens whenever * a branch we're currently in is collapsed. */ if (!selected) { - EventLog::iterator curr_event = _event_log->getCurrEvent(); if (curr_event->parent()) { - EventLog::iterator curr_event_parent = curr_event->parent(); EventLog::iterator last = curr_event_parent->children().end(); _event_log->blockNotifications(); - for ( --last ; curr_event != last ; ++curr_event ) { + for (--last; curr_event != last; ++curr_event) { DocumentUndo::redo(_document); } _event_log->blockNotifications(false); @@ -266,43 +247,35 @@ UndoHistory::_onListSelectionChange() _event_log->setCurrEvent(curr_event); _event_list_selection->select(curr_event_parent); - } else { // this should not happen + } else { // this should not happen _event_list_selection->select(curr_event); } } else { - EventLog::const_iterator last_selected = _event_log->getCurrEvent(); /* Selecting a collapsed parent event is equal to selecting the last child * of that parent's branch. */ - if ( !selected->children().empty() && - !_event_list_view.row_expanded(_event_list_store->get_path(selected)) ) - { + if (!selected->children().empty() && !_event_list_view.row_expanded(_event_list_store->get_path(selected))) { selected = selected->children().end(); --selected; } // An event before the current one has been selected. Undo to the selected event. - if ( _event_list_store->get_path(selected) < - _event_list_store->get_path(last_selected) ) - { + if (_event_list_store->get_path(selected) < _event_list_store->get_path(last_selected)) { _event_log->blockNotifications(); - while ( selected != last_selected ) { - + while (selected != last_selected) { DocumentUndo::undo(_document); - if ( last_selected->parent() && - last_selected == last_selected->parent()->children().begin() ) - { + if (last_selected->parent() && last_selected == last_selected->parent()->children().begin()) { last_selected = last_selected->parent(); - _event_log->setCurrEventParent((EventLog::iterator)nullptr); + _event_log->setCurrEventParent((EventLog::iterator) nullptr); } else { --last_selected; - if ( !last_selected->children().empty() ) { + if (!last_selected->children().empty()) { _event_log->setCurrEventParent(last_selected); last_selected = last_selected->children().end(); --last_selected; @@ -316,47 +289,40 @@ UndoHistory::_onListSelectionChange() _event_log->blockNotifications(); - while ( selected != last_selected ) { - + while (selected != last_selected) { DocumentUndo::redo(_document); - if ( !last_selected->children().empty() ) { + if (!last_selected->children().empty()) { _event_log->setCurrEventParent(last_selected); last_selected = last_selected->children().begin(); } else { ++last_selected; - if ( last_selected->parent() && - last_selected == last_selected->parent()->children().end() ) - { + if (last_selected->parent() && last_selected == last_selected->parent()->children().end()) { last_selected = last_selected->parent(); ++last_selected; - _event_log->setCurrEventParent((EventLog::iterator)nullptr); + _event_log->setCurrEventParent((EventLog::iterator) nullptr); } } } _event_log->blockNotifications(false); - } _event_log->setCurrEvent(selected); _event_log->updateUndoVerbs(); } - } -void -UndoHistory::_onExpandEvent(const Gtk::TreeModel::iterator &iter, const Gtk::TreeModel::Path &/*path*/) +void UndoHistory::_onExpandEvent(const Gtk::TreeModel::iterator &iter, const Gtk::TreeModel::Path & /*path*/) { - if ( iter == _event_list_selection->get_selected() ) { + if (iter == _event_list_selection->get_selected()) { _event_list_selection->select(_event_log->getCurrEvent()); } } -void -UndoHistory::_onCollapseEvent(const Gtk::TreeModel::iterator &iter, const Gtk::TreeModel::Path &/*path*/) +void UndoHistory::_onCollapseEvent(const Gtk::TreeModel::iterator &iter, const Gtk::TreeModel::Path & /*path*/) { // Collapsing a branch we're currently in is equal to stepping to the last event in that branch - if ( iter == _event_log->getCurrEvent() ) { + if (iter == _event_log->getCurrEvent()) { EventLog::const_iterator curr_event_parent = _event_log->getCurrEvent(); EventLog::const_iterator curr_event = curr_event_parent->children().begin(); EventLog::const_iterator last = curr_event_parent->children().end(); @@ -364,7 +330,7 @@ UndoHistory::_onCollapseEvent(const Gtk::TreeModel::iterator &iter, const Gtk::T _event_log->blockNotifications(); DocumentUndo::redo(_document); - for ( --last ; curr_event != last ; ++curr_event ) { + for (--last; curr_event != last; ++curr_event) { DocumentUndo::redo(_document); } _event_log->blockNotifications(false); @@ -375,7 +341,7 @@ UndoHistory::_onCollapseEvent(const Gtk::TreeModel::iterator &iter, const Gtk::T } } -const CellRendererInt::Filter& UndoHistory::greater_than_1 = UndoHistory::GreaterThan(1); +const CellRendererInt::Filter &UndoHistory::greater_than_1 = UndoHistory::GreaterThan(1); } // namespace Dialog } // namespace UI diff --git a/src/ui/dialog/undo-history.h b/src/ui/dialog/undo-history.h index b988b1bf69d70099c64757fc37aeb99d82e41d13..46907ffde895bbc9fdde2d17399417372fcc7a8e 100644 --- a/src/ui/dialog/undo-history.h +++ b/src/ui/dialog/undo-history.h @@ -13,18 +13,16 @@ #ifndef INKSCAPE_UI_DIALOG_UNDO_HISTORY_H #define INKSCAPE_UI_DIALOG_UNDO_HISTORY_H -#include "ui/widget/panel.h" +#include +#include #include #include #include #include -#include - -#include #include #include "event-log.h" - +#include "ui/widget/panel.h" class SPDesktop; @@ -32,71 +30,64 @@ namespace Inkscape { namespace UI { namespace Dialog { - /* Custom cell renderers */ -class CellRendererSPIcon : public Gtk::CellRendererPixbuf { +class CellRendererSPIcon : public Gtk::CellRendererPixbuf +{ public: + CellRendererSPIcon() + : Glib::ObjectBase(typeid(CellRendererPixbuf)) + , Gtk::CellRendererPixbuf() + , _property_icon(*this, "icon", Glib::RefPtr(nullptr)) + , _property_event_type(*this, "event_type", 0) + {} - CellRendererSPIcon() : - Glib::ObjectBase(typeid(CellRendererPixbuf)), - Gtk::CellRendererPixbuf(), - _property_icon(*this, "icon", Glib::RefPtr(nullptr)), - _property_event_type(*this, "event_type", 0) - { } - - Glib::PropertyProxy - property_event_type() { return _property_event_type.get_proxy(); } + Glib::PropertyProxy property_event_type() { return _property_event_type.get_proxy(); } protected: - void render_vfunc(const Cairo::RefPtr& cr, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - Gtk::CellRendererState flags) override; -private: + void render_vfunc(const Cairo::RefPtr &cr, Gtk::Widget &widget, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) override; - Glib::Property > _property_icon; +private: + Glib::Property> _property_icon; Glib::Property _property_event_type; - std::map > _icon_cache; - + std::map> _icon_cache; }; - -class CellRendererInt : public Gtk::CellRendererText { +class CellRendererInt : public Gtk::CellRendererText +{ public: - - struct Filter : std::unary_function { + struct Filter : std::unary_function + { virtual ~Filter() = default; - virtual bool operator() (const int&) const =0; + virtual bool operator()(const int &) const = 0; }; - CellRendererInt(const Filter& filter=no_filter) : - Glib::ObjectBase(typeid(CellRendererText)), - Gtk::CellRendererText(), - _property_number(*this, "number", 0), - _filter (filter) - { } - + CellRendererInt(const Filter &filter = no_filter) + : Glib::ObjectBase(typeid(CellRendererText)) + , Gtk::CellRendererText() + , _property_number(*this, "number", 0) + , _filter(filter) + {} - Glib::PropertyProxy - property_number() { return _property_number.get_proxy(); } + Glib::PropertyProxy property_number() { return _property_number.get_proxy(); } - static const Filter& no_filter; + static const Filter &no_filter; protected: - void render_vfunc(const Cairo::RefPtr& cr, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - Gtk::CellRendererState flags) override; + void render_vfunc(const Cairo::RefPtr &cr, Gtk::Widget &widget, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) override; private: - Glib::Property _property_number; - const Filter& _filter; + const Filter &_filter; - struct NoFilter : Filter { bool operator() (const int& /*x*/) const override { return true; } }; + struct NoFilter : Filter + { + bool operator()(const int & /*x*/) const override { return true; } + }; }; /** @@ -105,22 +96,22 @@ private: * This dialog allows the user to undo and redo multiple events in a more convenient way * than repateaded ctrl-z, ctrl-shift-z. */ -class UndoHistory : public Widget::Panel { +class UndoHistory : public Widget::Panel +{ public: ~UndoHistory() override; static UndoHistory &getInstance(); - void setDesktop(SPDesktop* desktop) override; + void setDesktop(SPDesktop *desktop) override; sigc::connection _document_replaced_connection; protected: - SPDesktop *_desktop; SPDocument *_document; EventLog *_event_log; - Gtk::ScrolledWindow _scrolled_window; + Gtk::ScrolledWindow _scrolled_window; Glib::RefPtr _event_list_store; Gtk::TreeView _event_list_view; @@ -130,9 +121,9 @@ protected: static void *_handleEventLogDestroyCB(void *data); - void _connectDocument(SPDesktop* desktop, SPDocument *document); + void _connectDocument(SPDesktop *desktop, SPDocument *document); void _connectEventLog(); - void _handleDocumentReplaced(SPDesktop* desktop, SPDocument *document); + void _handleDocumentReplaced(SPDesktop *desktop, SPDocument *document); void *_handleEventLogDestroy(); void _onListSelectionChange(); void _onExpandEvent(const Gtk::TreeModel::iterator &iter, const Gtk::TreeModel::Path &path); @@ -140,25 +131,28 @@ protected: private: UndoHistory(); - + // no default constructor, noncopyable, nonassignable UndoHistory(UndoHistory const &d) = delete; UndoHistory operator=(UndoHistory const &d) = delete; - struct GreaterThan : CellRendererInt::Filter { - GreaterThan(int _i) : i (_i) {} - bool operator() (const int& x) const override { return x > i; } + struct GreaterThan : CellRendererInt::Filter + { + GreaterThan(int _i) + : i(_i) + {} + bool operator()(const int &x) const override { return x > i; } int i; }; - static const CellRendererInt::Filter& greater_than_1; + static const CellRendererInt::Filter &greater_than_1; }; } // namespace Dialog } // namespace UI } // namespace Inkscape -#endif //INKSCAPE_UI_DIALOG_UNDO_HISTORY_H +#endif // INKSCAPE_UI_DIALOG_UNDO_HISTORY_H /* Local Variables: diff --git a/src/ui/dialog/xml-tree.cpp b/src/ui/dialog/xml-tree.cpp index cd8c5461de139a43e66376aa03a9ac1146403f93..939c6f11e421c37bc4a9ccf863def9be43d68cea 100644 --- a/src/ui/dialog/xml-tree.cpp +++ b/src/ui/dialog/xml-tree.cpp @@ -22,24 +22,20 @@ #include #include - #include "desktop.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" #include "message-context.h" #include "message-stack.h" -#include "shortcuts.h" -#include "verbs.h" - #include "object/sp-root.h" #include "object/sp-string.h" - +#include "shortcuts.h" #include "ui/dialog-events.h" #include "ui/icon-loader.h" #include "ui/icon-names.h" #include "ui/tools/tool-base.h" - +#include "verbs.h" #include "widgets/sp-xmlview-tree.h" namespace { @@ -82,7 +78,7 @@ XmlTree::XmlTree() status.set_markup(""); status.set_line_wrap(true); status.get_style_context()->add_class("inksmall"); - status_box.pack_start( status, TRUE, TRUE, 0); + status_box.pack_start(status, TRUE, TRUE, 0); contents->pack_start(_paned, true, true, 0); contents->set_valign(Gtk::ALIGN_FILL); contents->child_property_fill(_paned); @@ -90,12 +86,12 @@ XmlTree::XmlTree() _paned.set_vexpand(true); _message_stack = std::make_shared(); _message_context = std::unique_ptr(new Inkscape::MessageContext(_message_stack)); - _message_changed_connection = _message_stack->connectChanged( - sigc::bind(sigc::ptr_fun(_set_status_message), GTK_WIDGET(status.gobj()))); + _message_changed_connection = + _message_stack->connectChanged(sigc::bind(sigc::ptr_fun(_set_status_message), GTK_WIDGET(status.gobj()))); /* tree view */ tree = SP_XMLVIEW_TREE(sp_xmlview_tree_new(nullptr, nullptr, nullptr)); - gtk_widget_set_tooltip_text( GTK_WIDGET(tree), _("Drag to reorder nodes") ); + gtk_widget_set_tooltip_text(GTK_WIDGET(tree), _("Drag to reorder nodes")); tree_toolbar.set_toolbar_style(Gtk::TOOLBAR_ICONS); @@ -171,7 +167,7 @@ XmlTree::XmlTree() Gtk::ScrolledWindow *tree_scroller = new Gtk::ScrolledWindow(); tree_scroller->set_overlay_scrolling(false); - tree_scroller->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC ); + tree_scroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); tree_scroller->set_shadow_type(Gtk::SHADOW_IN); tree_scroller->add(*Gtk::manage(Glib::wrap(GTK_WIDGET(tree)))); @@ -213,9 +209,9 @@ XmlTree::XmlTree() paned_set_vertical(_paned, dir); contents->pack_start(*actionsbox, false, false, 0); /* Signal handlers */ - GtkTreeSelection *selection = gtk_tree_view_get_selection (GTK_TREE_VIEW(tree)); - g_signal_connect (G_OBJECT(selection), "changed", G_CALLBACK (on_tree_select_row), this); - g_signal_connect_after( G_OBJECT(tree), "tree_move", G_CALLBACK(after_tree_move), this); + GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree)); + g_signal_connect(G_OBJECT(selection), "changed", G_CALLBACK(on_tree_select_row), this); + g_signal_connect_after(G_OBJECT(tree), "tree_move", G_CALLBACK(after_tree_move), this); xml_element_new_button.signal_clicked().connect(sigc::mem_fun(*this, &XmlTree::cmd_new_element_node)); xml_text_new_button.signal_clicked().connect(sigc::mem_fun(*this, &XmlTree::cmd_new_text_node)); @@ -237,7 +233,6 @@ XmlTree::XmlTree() tree_reset_context(); root->pack_start(*Gtk::manage(contents), true, true); - } void XmlTree::_resized() @@ -279,7 +274,7 @@ void XmlTree::present() } } -XmlTree::~XmlTree () +XmlTree::~XmlTree() { assert(!current_desktop); _message_changed_connection.disconnect(); @@ -297,14 +292,12 @@ void XmlTree::setDesktop(SPDesktop *desktop) */ void XmlTree::tree_reset_context() { - _message_context->set(Inkscape::NORMAL_MESSAGE, - _("Click to select nodes, drag to rearrange.")); + _message_context->set(Inkscape::NORMAL_MESSAGE, _("Click to select nodes, drag to rearrange.")); } - void XmlTree::set_tree_desktop(SPDesktop *desktop) { - if ( desktop == current_desktop ) { + if (desktop == current_desktop) { return; } @@ -322,8 +315,10 @@ void XmlTree::set_tree_desktop(SPDesktop *desktop) } current_desktop = desktop; if (desktop) { - sel_changed_connection = desktop->getSelection()->connectChanged(sigc::hide(sigc::mem_fun(this, &XmlTree::on_desktop_selection_changed))); - document_replaced_connection = desktop->connectDocumentReplaced(sigc::mem_fun(this, &XmlTree::on_document_replaced)); + sel_changed_connection = desktop->getSelection()->connectChanged( + sigc::hide(sigc::mem_fun(this, &XmlTree::on_desktop_selection_changed))); + document_replaced_connection = + desktop->connectDocumentReplaced(sigc::mem_fun(this, &XmlTree::on_document_replaced)); set_tree_document(desktop->getDocument()); } else { @@ -332,7 +327,6 @@ void XmlTree::set_tree_desktop(SPDesktop *desktop) } // end of set_tree_desktop() - void XmlTree::set_tree_document(SPDocument *document) { if (document == current_document) { @@ -344,17 +338,15 @@ void XmlTree::set_tree_document(SPDocument *document) } current_document = document; if (current_document) { - - document_uri_set_connection = current_document->connectURISet(sigc::bind(sigc::ptr_fun(&on_document_uri_set), current_document)); - on_document_uri_set( current_document->getDocumentURI(), current_document ); + document_uri_set_connection = + current_document->connectURISet(sigc::bind(sigc::ptr_fun(&on_document_uri_set), current_document)); + on_document_uri_set(current_document->getDocumentURI(), current_document); set_tree_repr(current_document->getReprRoot()); } else { set_tree_repr(nullptr); } } - - void XmlTree::set_tree_repr(Inkscape::XML::Node *repr) { if (repr == selected_repr) { @@ -369,7 +361,6 @@ void XmlTree::set_tree_repr(Inkscape::XML::Node *repr) } propagate_tree_select(selected_repr); - } /** @@ -411,11 +402,10 @@ void XmlTree::set_tree_select(Inkscape::XML::Node *repr) expand_parents(tree, repr); if (sp_xmlview_tree_get_repr_node(SP_XMLVIEW_TREE(tree), repr, &node)) { - GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree)); - gtk_tree_selection_unselect_all (selection); + gtk_tree_selection_unselect_all(selection); - GtkTreePath* path = gtk_tree_model_get_path(GTK_TREE_MODEL(tree->store), &node); + GtkTreePath *path = gtk_tree_model_get_path(GTK_TREE_MODEL(tree->store), &node); gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(tree), path, nullptr, TRUE, 0.66, 0.0); gtk_tree_selection_select_iter(selection, &node); gtk_tree_view_set_cursor(GTK_TREE_VIEW(tree), path, NULL, false); @@ -426,29 +416,23 @@ void XmlTree::set_tree_select(Inkscape::XML::Node *repr) } } else { GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree)); - gtk_tree_selection_unselect_all (selection); + gtk_tree_selection_unselect_all(selection); on_tree_unselect_row_disable(); } propagate_tree_select(repr); } - - void XmlTree::propagate_tree_select(Inkscape::XML::Node *repr) { - if (repr && - (repr->type() == Inkscape::XML::ELEMENT_NODE || - repr->type() == Inkscape::XML::TEXT_NODE || - repr->type() == Inkscape::XML::COMMENT_NODE)) - { + if (repr && (repr->type() == Inkscape::XML::ELEMENT_NODE || repr->type() == Inkscape::XML::TEXT_NODE || + repr->type() == Inkscape::XML::COMMENT_NODE)) { attributes->setRepr(repr); } else { attributes->setRepr(nullptr); } } - Inkscape::XML::Node *XmlTree::get_dt_select() { if (!current_desktop) { @@ -457,7 +441,6 @@ Inkscape::XML::Node *XmlTree::get_dt_select() return current_desktop->getSelection()->singleRepr(); } - /** * Like SPDesktop::isLayer(), but ignores SPGroup::effectiveLayerMode(). */ @@ -477,9 +460,7 @@ void XmlTree::set_dt_select(Inkscape::XML::Node *repr) SPObject *object; if (repr) { - while ( ( repr->type() != Inkscape::XML::ELEMENT_NODE ) - && repr->parent() ) - { + while ((repr->type() != Inkscape::XML::ELEMENT_NODE) && repr->parent()) { repr = repr->parent(); } // end of while loop @@ -508,7 +489,6 @@ void XmlTree::set_dt_select(Inkscape::XML::Node *repr) } // end of set_dt_select() - void XmlTree::on_tree_select_row(GtkTreeSelection *selection, gpointer data) { XmlTree *self = static_cast(data); @@ -532,7 +512,7 @@ gboolean XmlTree::deferred_on_tree_select_row(gpointer data) self->deferred_on_tree_select_row_id = 0; - GtkTreeIter iter; + GtkTreeIter iter; GtkTreeModel *model; if (self->selected_repr) { @@ -542,7 +522,7 @@ gboolean XmlTree::deferred_on_tree_select_row(gpointer data) GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(self->tree)); - if (!gtk_tree_selection_get_selected (selection, &model, &iter)) { + if (!gtk_tree_selection_get_selected(selection, &model, &iter)) { // Nothing selected, update widgets self->propagate_tree_select(nullptr); self->set_dt_select(nullptr); @@ -553,7 +533,6 @@ gboolean XmlTree::deferred_on_tree_select_row(gpointer data) Inkscape::XML::Node *repr = sp_xmlview_tree_node_get_repr(model, &iter); g_assert(repr != nullptr); - self->selected_repr = repr; Inkscape::GC::anchor(self->selected_repr); @@ -568,7 +547,6 @@ gboolean XmlTree::deferred_on_tree_select_row(gpointer data) return FALSE; } - void XmlTree::after_tree_move(SPXMLViewTree * /*tree*/, gpointer value, gpointer data) { XmlTree *self = static_cast(data); @@ -578,7 +556,7 @@ void XmlTree::after_tree_move(SPXMLViewTree * /*tree*/, gpointer value, gpointer DocumentUndo::done(self->current_document, SP_VERB_DIALOG_XML_EDITOR, Q_("Undo History / XML dialog|Drag XML subtree")); } else { - //DocumentUndo::cancel(self->current_document); + // DocumentUndo::cancel(self->current_document); /* * There was a problem with drag & drop, * data is probably not synchronized, so reload the tree @@ -603,13 +581,13 @@ void XmlTree::on_tree_select_row_enable(GtkTreeIter *node) } Inkscape::XML::Node *repr = sp_xmlview_tree_node_get_repr(GTK_TREE_MODEL(tree->store), node); - Inkscape::XML::Node *parent=repr->parent(); + Inkscape::XML::Node *parent = repr->parent(); - //on_tree_select_row_enable_if_mutable + // on_tree_select_row_enable_if_mutable xml_node_duplicate_button.set_sensitive(xml_tree_node_mutable(node)); xml_node_delete_button.set_sensitive(xml_tree_node_mutable(node)); - //on_tree_select_row_enable_if_element + // on_tree_select_row_enable_if_element if (repr->type() == Inkscape::XML::ELEMENT_NODE) { xml_element_new_button.set_sensitive(true); xml_text_new_button.set_sensitive(true); @@ -619,7 +597,7 @@ void XmlTree::on_tree_select_row_enable(GtkTreeIter *node) xml_text_new_button.set_sensitive(false); } - //on_tree_select_row_enable_if_has_grandparent + // on_tree_select_row_enable_if_has_grandparent { GtkTreeIter parent; if (gtk_tree_model_iter_parent(GTK_TREE_MODEL(tree->store), &parent, node)) { @@ -639,13 +617,12 @@ void XmlTree::on_tree_select_row_enable(GtkTreeIter *node) if (xml_tree_node_mutable(node)) { Inkscape::XML::Node *prev; - if ( parent && repr != parent->firstChild() ) { + if (parent && repr != parent->firstChild()) { g_assert(parent->firstChild()); // skip to the child just before the current repr - for ( prev = parent->firstChild() ; - prev && prev->next() != repr ; - prev = prev->next() ){}; + for (prev = parent->firstChild(); prev && prev->next() != repr; prev = prev->next()) { + }; if (prev && (prev->type() == Inkscape::XML::ELEMENT_NODE)) { indentable = TRUE; @@ -655,18 +632,18 @@ void XmlTree::on_tree_select_row_enable(GtkTreeIter *node) indent_node_button.set_sensitive(indentable); - //on_tree_select_row_enable_if_not_first_child + // on_tree_select_row_enable_if_not_first_child { - if ( parent && repr != parent->firstChild() ) { + if (parent && repr != parent->firstChild()) { raise_node_button.set_sensitive(true); } else { raise_node_button.set_sensitive(false); } } - //on_tree_select_row_enable_if_not_last_child + // 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); @@ -674,7 +651,6 @@ void XmlTree::on_tree_select_row_enable(GtkTreeIter *node) } } - gboolean XmlTree::xml_tree_node_mutable(GtkTreeIter *node) { // top-level is immutable, obviously @@ -683,7 +659,6 @@ gboolean XmlTree::xml_tree_node_mutable(GtkTreeIter *node) return false; } - // if not in base level (where namedview, defs, etc go), we're mutable GtkTreeIter child; if (gtk_tree_model_iter_parent(GTK_TREE_MODEL(tree->store), &child, &parent)) { @@ -695,8 +670,7 @@ gboolean XmlTree::xml_tree_node_mutable(GtkTreeIter *node) g_assert(repr); // don't let "defs" or "namedview" disappear - if ( !strcmp(repr->name(),"svg:defs") || - !strcmp(repr->name(),"sodipodi:namedview") ) { + if (!strcmp(repr->name(), "svg:defs") || !strcmp(repr->name(), "sodipodi:namedview")) { return false; } @@ -704,8 +678,6 @@ gboolean XmlTree::xml_tree_node_mutable(GtkTreeIter *node) return true; } - - void XmlTree::on_tree_unselect_row_disable() { xml_text_new_button.set_sensitive(false); @@ -739,25 +711,26 @@ void XmlTree::on_document_replaced(SPDesktop *dt, SPDocument *doc) if (current_desktop) sel_changed_connection.disconnect(); - sel_changed_connection = dt->getSelection()->connectChanged(sigc::hide(sigc::mem_fun(this, &XmlTree::on_desktop_selection_changed))); + sel_changed_connection = + dt->getSelection()->connectChanged(sigc::hide(sigc::mem_fun(this, &XmlTree::on_desktop_selection_changed))); set_tree_document(doc); } void XmlTree::on_document_uri_set(gchar const * /*uri*/, SPDocument * /*document*/) { -/* - * Seems to be no way to set the title on a docked dialog - gchar title[500]; - sp_ui_dialog_title_string(Inkscape::Verb::get(SP_VERB_DIALOG_XML_EDITOR), title); - gchar *t = g_strdup_printf("%s: %s", document->getName(), title); - //gtk_window_set_title(GTK_WINDOW(dlg), t); - g_free(t); -*/ + /* + * Seems to be no way to set the title on a docked dialog + gchar title[500]; + sp_ui_dialog_title_string(Inkscape::Verb::get(SP_VERB_DIALOG_XML_EDITOR), title); + gchar *t = g_strdup_printf("%s: %s", document->getName(), title); + //gtk_window_set_title(GTK_WINDOW(dlg), t); + g_free(t); + */ } -gboolean XmlTree::quit_on_esc (GtkWidget *w, GdkEventKey *event, GObject */*tbl*/) +gboolean XmlTree::quit_on_esc(GtkWidget *w, GdkEventKey *event, GObject * /*tbl*/) { - switch (Inkscape::UI::Tools::get_latin_keyval (event)) { + switch (Inkscape::UI::Tools::get_latin_keyval(event)) { case GDK_KEY_Escape: // defocus gtk_widget_destroy(w); return TRUE; @@ -797,7 +770,6 @@ void XmlTree::cmd_new_element_node() } } // end of cmd_new_element_node() - void XmlTree::cmd_new_text_node() { g_assert(selected_repr != nullptr); @@ -855,7 +827,6 @@ void XmlTree::cmd_raise_node() { g_assert(selected_repr != nullptr); - Inkscape::XML::Node *parent = selected_repr->parent(); g_return_if_fail(parent != nullptr); g_return_if_fail(parent->firstChild() != selected_repr); @@ -875,8 +846,6 @@ void XmlTree::cmd_raise_node() set_dt_select(selected_repr); } - - void XmlTree::cmd_lower_node() { g_assert(selected_repr != nullptr); @@ -901,16 +870,17 @@ void XmlTree::cmd_indent_node() g_return_if_fail(parent != nullptr); g_return_if_fail(parent->firstChild() != repr); - Inkscape::XML::Node* prev = parent->firstChild(); + Inkscape::XML::Node *prev = parent->firstChild(); while (prev && (prev->next() != repr)) { prev = prev->next(); } g_return_if_fail(prev != nullptr); g_return_if_fail(prev->type() == Inkscape::XML::ELEMENT_NODE); - Inkscape::XML::Node* ref = nullptr; + Inkscape::XML::Node *ref = nullptr; if (prev->firstChild()) { - for( ref = prev->firstChild() ; ref->next() ; ref = ref->next() ){}; + for (ref = prev->firstChild(); ref->next(); ref = ref->next()) { + }; } parent->removeChild(repr); @@ -922,8 +892,6 @@ void XmlTree::cmd_indent_node() } // end of cmd_indent_node() - - void XmlTree::cmd_unindent_node() { Inkscape::XML::Node *repr = selected_repr; @@ -954,7 +922,7 @@ bool XmlTree::in_dt_coordsys(SPObject const &item) /* Definition based on sp_item_i2doc_affine. */ SPObject const *child = &item; while (SP_IS_ITEM(child)) { - SPObject const * const parent = child->parent; + SPObject const *const parent = child->parent; if (parent == nullptr) { g_assert(SP_IS_ROOT(child)); if (child == &item) { @@ -969,9 +937,9 @@ bool XmlTree::in_dt_coordsys(SPObject const &item) return false; } -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/dialog/xml-tree.h b/src/ui/dialog/xml-tree.h index 0823c0929fd4430ce72038042f12a2de56641b65..552190c4233131e44e5405576f757585760c9216 100644 --- a/src/ui/dialog/xml-tree.h +++ b/src/ui/dialog/xml-tree.h @@ -13,9 +13,6 @@ #ifndef SEEN_UI_DIALOGS_XML_TREE_H #define SEEN_UI_DIALOGS_XML_TREE_H -#include - -#include "ui/widget/panel.h" #include #include #include @@ -25,11 +22,11 @@ #include #include #include +#include #include "message.h" - #include "ui/dialog/attrdialog.h" - +#include "ui/widget/panel.h" class SPDesktop; class SPObject; @@ -53,15 +50,15 @@ namespace Dialog { * */ -class XmlTree : public Widget::Panel { +class XmlTree : public Widget::Panel +{ public: - XmlTree (); - ~XmlTree () override; + XmlTree(); + ~XmlTree() override; static XmlTree &getInstance() { return *new XmlTree(); } private: - /** * Is invoked by the desktop tracker when the desktop changes. */ @@ -90,7 +87,7 @@ private: /** * Callback to close the add dialog on Escape key */ - static gboolean quit_on_esc (GtkWidget *w, GdkEventKey *event, GObject */*tbl*/); + static gboolean quit_on_esc(GtkWidget *w, GdkEventKey *event, GObject * /*tbl*/); /** * Select a node in the xml tree @@ -103,18 +100,18 @@ private: void propagate_tree_select(Inkscape::XML::Node *repr); /** - * Find the current desktop selection - */ + * Find the current desktop selection + */ Inkscape::XML::Node *get_dt_select(); /** - * Select the current desktop selection - */ + * Select the current desktop selection + */ void set_dt_select(Inkscape::XML::Node *repr); /** - * Callback for a node in the tree being selected - */ + * Callback for a node in the tree being selected + */ static void on_tree_select_row(GtkTreeSelection *selection, gpointer data); /** * Callback for deferring the `on_tree_select_row` response in order to @@ -127,23 +124,24 @@ private: guint deferred_on_tree_select_row_id = 0; /** - * Callback when a node is moved in the tree - */ + * Callback when a node is moved in the tree + */ static void after_tree_move(SPXMLViewTree *tree, gpointer value, gpointer data); /** - * Callback for when an attribute is edited. - */ - //static void on_attr_edited(SPXMLViewAttrList *attributes, const gchar * name, const gchar * value, gpointer /*data*/); + * Callback for when an attribute is edited. + */ + // static void on_attr_edited(SPXMLViewAttrList *attributes, const gchar * name, const gchar * value, gpointer + // /*data*/); /** - * Callback for when attribute list values change - */ - //static void on_attr_row_changed(SPXMLViewAttrList *attributes, const gchar * name, gpointer data); + * Callback for when attribute list values change + */ + // static void on_attr_row_changed(SPXMLViewAttrList *attributes, const gchar * name, gpointer data); /** - * Enable widgets based on current selections - */ + * Enable widgets based on current selections + */ void on_tree_select_row_enable(GtkTreeIter *node); void on_tree_unselect_row_disable(); void on_tree_unselect_row_hide(); @@ -153,8 +151,8 @@ private: void onCreateNameChanged(); /** - * Callbacks for changes in desktop selection and current document - */ + * Callbacks for changes in desktop selection and current document + */ void on_desktop_selection_changed(); void on_document_replaced(SPDesktop *dt, SPDocument *document); static void on_document_uri_set(gchar const *uri, SPDocument *document); @@ -162,8 +160,8 @@ private: static void _set_status_message(Inkscape::MessageType type, const gchar *message, GtkWidget *dialog); /** - * Callbacks for toolbar buttons being pressed - */ + * Callbacks for toolbar buttons being pressed + */ void cmd_new_element_node(); void cmd_new_text_node(); void cmd_duplicate_node(); @@ -215,7 +213,7 @@ private: /* XmlTree Widgets */ SPXMLViewTree *tree; - //SPXMLViewAttrList *attributes; + // SPXMLViewAttrList *attributes; AttrDialog *attributes; Gtk::Box *_attrbox; @@ -243,9 +241,9 @@ private: GtkWidget *new_window; }; -} -} -} +} // namespace Dialog +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/drag-and-drop.cpp b/src/ui/drag-and-drop.cpp index cc81c2660b051d3988eaac86ff54fa4a61c07815..34afdeb267b191015a570a0e4e5d616eb7013453 100644 --- a/src/ui/drag-and-drop.cpp +++ b/src/ui/drag-and-drop.cpp @@ -14,40 +14,35 @@ #include "drag-and-drop.h" -#include // Internationalization +#include // Internationalization #include "desktop-style.h" -#include "document.h" #include "document-undo.h" -#include "gradient-drag.h" -#include "file.h" -#include "selection.h" -#include "style.h" -#include "verbs.h" - +#include "document.h" #include "extension/db.h" #include "extension/find_extension_by_mime.h" - +#include "file.h" +#include "gradient-drag.h" +#include "object/sp-flowtext.h" #include "object/sp-shape.h" #include "object/sp-text.h" -#include "object/sp-flowtext.h" - #include "path/path-util.h" - +#include "selection.h" +#include "style.h" #include "svg/svg-color.h" // write color - #include "ui/clipboard.h" #include "ui/interface.h" #include "ui/tools/tool-base.h" -#include "ui/widget/canvas.h" // Target, canvas to world transform. - +#include "ui/widget/canvas.h" // Target, canvas to world transform. +#include "verbs.h" #include "widgets/desktop-widget.h" #include "widgets/ege-paint-def.h" using Inkscape::DocumentUndo; /* Drag and Drop */ -enum ui_drop_target_info { +enum ui_drop_target_info +{ URI_LIST, SVG_XML_DATA, SVG_DATA, @@ -60,7 +55,7 @@ enum ui_drop_target_info { APP_X_INK_PASTE }; -static GtkTargetEntry ui_drop_target_entries [] = { +static GtkTargetEntry ui_drop_target_entries[] = { // clang-format off {(gchar *)"text/uri-list", 0, URI_LIST }, {(gchar *)"image/svg+xml", 0, SVG_XML_DATA }, @@ -79,56 +74,46 @@ static int completeDropTargetsCount = 0; static guint nui_drop_target_entries = G_N_ELEMENTS(ui_drop_target_entries); /* Drag and Drop */ -static -void -ink_drag_data_received(GtkWidget *widget, - GdkDragContext *drag_context, - gint x, gint y, - GtkSelectionData *data, - guint info, - guint /*event_time*/, - gpointer user_data) +static void ink_drag_data_received(GtkWidget *widget, GdkDragContext *drag_context, gint x, gint y, + GtkSelectionData *data, guint info, guint /*event_time*/, gpointer user_data) { auto dtw = static_cast(user_data); SPDesktop *desktop = dtw->desktop; SPDocument *doc = desktop->doc(); switch (info) { - case APP_X_COLOR: - { + case APP_X_COLOR: { int destX = 0; int destY = 0; auto canvas = dtw->get_canvas(); - gtk_widget_translate_coordinates( widget, GTK_WIDGET(canvas->gobj()), x, y, &destX, &destY ); - Geom::Point where( canvas->canvas_to_world(Geom::Point(destX, destY))); + gtk_widget_translate_coordinates(widget, GTK_WIDGET(canvas->gobj()), x, y, &destX, &destY); + Geom::Point where(canvas->canvas_to_world(Geom::Point(destX, destY))); Geom::Point const button_dt(desktop->w2d(where)); Geom::Point const button_doc(desktop->dt2doc(button_dt)); - if ( gtk_selection_data_get_length (data) == 8 ) { + if (gtk_selection_data_get_length(data) == 8) { gchar colorspec[64] = {0}; // Careful about endian issues. - guint16* dataVals = (guint16*)gtk_selection_data_get_data (data); - sp_svg_write_color( colorspec, sizeof(colorspec), - SP_RGBA32_U_COMPOSE( - 0x0ff & (dataVals[0] >> 8), - 0x0ff & (dataVals[1] >> 8), - 0x0ff & (dataVals[2] >> 8), - 0xff // can't have transparency in the color itself - //0x0ff & (data->data[3] >> 8), - )); - - SPItem *item = desktop->getItemAtPoint( where, true ); + guint16 *dataVals = (guint16 *)gtk_selection_data_get_data(data); + sp_svg_write_color(colorspec, sizeof(colorspec), + SP_RGBA32_U_COMPOSE(0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), + 0x0ff & (dataVals[2] >> 8), + 0xff // can't have transparency in the color itself + // 0x0ff & (data->data[3] >> 8), + )); + + SPItem *item = desktop->getItemAtPoint(where, true); bool consumed = false; if (desktop->event_context && desktop->event_context->get_drag()) { consumed = desktop->event_context->get_drag()->dropColor(item, colorspec, button_dt); if (consumed) { - DocumentUndo::done( doc , SP_VERB_NONE, _("Drop color on gradient") ); + DocumentUndo::done(doc, SP_VERB_NONE, _("Drop color on gradient")); desktop->event_context->get_drag()->updateDraggers(); } } - //if (!consumed && tools_active(desktop, TOOLS_TEXT)) { + // if (!consumed && tools_active(desktop, TOOLS_TEXT)) { // consumed = sp_text_context_drop_color(c, button_doc); // if (consumed) { // SPDocumentUndo::done( doc , SP_VERB_NONE, _("Drop color on gradient stop")); @@ -136,27 +121,26 @@ ink_drag_data_received(GtkWidget *widget, //} if (!consumed && item) { - bool fillnotstroke = (gdk_drag_context_get_actions (drag_context) != GDK_ACTION_MOVE); - if (fillnotstroke && - (SP_IS_SHAPE(item) || SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))) { + bool fillnotstroke = (gdk_drag_context_get_actions(drag_context) != GDK_ACTION_MOVE); + if (fillnotstroke && (SP_IS_SHAPE(item) || SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))) { Path *livarot_path = Path_for_item(item, true, true); livarot_path->ConvertWithBackData(0.04); - boost::optional position = get_nearest_position_on_Path(livarot_path, button_doc); + boost::optional position = + get_nearest_position_on_Path(livarot_path, button_doc); if (position) { Geom::Point nearest = get_point_on_Path(livarot_path, position->piece, position->t); Geom::Point delta = nearest - button_doc; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); delta = desktop->d2w(delta); double stroke_tolerance = - ( !item->style->stroke.isNone() ? - desktop->current_zoom() * - item->style->stroke_width.computed * - item->i2dt_affine().descrim() * 0.5 - : 0.0) - + prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); - - if (Geom::L2 (delta) < stroke_tolerance) { + (!item->style->stroke.isNone() + ? desktop->current_zoom() * item->style->stroke_width.computed * + item->i2dt_affine().descrim() * 0.5 + : 0.0) + + prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + if (Geom::L2(delta) < stroke_tolerance) { fillnotstroke = false; } } @@ -164,44 +148,40 @@ ink_drag_data_received(GtkWidget *widget, } SPCSSAttr *css = sp_repr_css_attr_new(); - sp_repr_css_set_property( css, fillnotstroke ? "fill":"stroke", colorspec ); + sp_repr_css_set_property(css, fillnotstroke ? "fill" : "stroke", colorspec); - sp_desktop_apply_css_recursive( item, css, true ); + sp_desktop_apply_css_recursive(item, css, true); item->updateRepr(); - DocumentUndo::done( doc , SP_VERB_NONE, - _("Drop color") ); + DocumentUndo::done(doc, SP_VERB_NONE, _("Drop color")); } } - } - break; + } break; - case APP_OSWB_COLOR: - { + case APP_OSWB_COLOR: { bool worked = false; Glib::ustring colorspec; - if ( gtk_selection_data_get_format (data) == 8 ) { + if (gtk_selection_data_get_format(data) == 8) { ege::PaintDef color; worked = color.fromMIMEData("application/x-oswb-color", - reinterpret_cast(gtk_selection_data_get_data (data)), - gtk_selection_data_get_length (data), - gtk_selection_data_get_format (data)); - if ( worked ) { - if ( color.getType() == ege::PaintDef::CLEAR ) { + reinterpret_cast(gtk_selection_data_get_data(data)), + gtk_selection_data_get_length(data), gtk_selection_data_get_format(data)); + if (worked) { + if (color.getType() == ege::PaintDef::CLEAR) { colorspec = ""; // TODO check if this is sufficient - } else if ( color.getType() == ege::PaintDef::NONE ) { + } else if (color.getType() == ege::PaintDef::NONE) { colorspec = "none"; } else { unsigned int r = color.getR(); unsigned int g = color.getG(); unsigned int b = color.getB(); - SPGradient* matches = nullptr; + SPGradient *matches = nullptr; std::vector gradients = doc->getResourceList("gradient"); for (auto gradient : gradients) { - SPGradient* grad = SP_GRADIENT(gradient); - if ( color.descr == grad->getId() ) { - if ( grad->hasStops() ) { + SPGradient *grad = SP_GRADIENT(gradient); + if (color.descr == grad->getId()) { + if (grad->hasStops()) { matches = grad; break; } @@ -212,55 +192,54 @@ ink_drag_data_received(GtkWidget *widget, colorspec += matches->getId(); colorspec += ")"; } else { - gchar* tmp = g_strdup_printf("#%02x%02x%02x", r, g, b); + gchar *tmp = g_strdup_printf("#%02x%02x%02x", r, g, b); colorspec = tmp; g_free(tmp); } } } } - if ( worked ) { + if (worked) { int destX = 0; int destY = 0; auto canvas = dtw->get_canvas(); - gtk_widget_translate_coordinates( widget, GTK_WIDGET(canvas->gobj()), x, y, &destX, &destY ); - Geom::Point where( canvas->canvas_to_world(Geom::Point(destX, destY))); + gtk_widget_translate_coordinates(widget, GTK_WIDGET(canvas->gobj()), x, y, &destX, &destY); + Geom::Point where(canvas->canvas_to_world(Geom::Point(destX, destY))); Geom::Point const button_dt(desktop->w2d(where)); Geom::Point const button_doc(desktop->dt2doc(button_dt)); - SPItem *item = desktop->getItemAtPoint( where, true ); + SPItem *item = desktop->getItemAtPoint(where, true); bool consumed = false; if (desktop->event_context && desktop->event_context->get_drag()) { consumed = desktop->event_context->get_drag()->dropColor(item, colorspec.c_str(), button_dt); if (consumed) { - DocumentUndo::done( doc , SP_VERB_NONE, _("Drop color on gradient") ); + DocumentUndo::done(doc, SP_VERB_NONE, _("Drop color on gradient")); desktop->event_context->get_drag()->updateDraggers(); } } if (!consumed && item) { - bool fillnotstroke = (gdk_drag_context_get_actions (drag_context) != GDK_ACTION_MOVE); - if (fillnotstroke && - (SP_IS_SHAPE(item) || SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))) { + bool fillnotstroke = (gdk_drag_context_get_actions(drag_context) != GDK_ACTION_MOVE); + if (fillnotstroke && (SP_IS_SHAPE(item) || SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))) { Path *livarot_path = Path_for_item(item, true, true); livarot_path->ConvertWithBackData(0.04); - boost::optional position = get_nearest_position_on_Path(livarot_path, button_doc); + boost::optional position = + get_nearest_position_on_Path(livarot_path, button_doc); if (position) { Geom::Point nearest = get_point_on_Path(livarot_path, position->piece, position->t); Geom::Point delta = nearest - button_doc; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); delta = desktop->d2w(delta); double stroke_tolerance = - ( !item->style->stroke.isNone() ? - desktop->current_zoom() * - item->style->stroke_width.computed * - item->i2dt_affine().descrim() * 0.5 - : 0.0) - + prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); - - if (Geom::L2 (delta) < stroke_tolerance) { + (!item->style->stroke.isNone() + ? desktop->current_zoom() * item->style->stroke_width.computed * + item->i2dt_affine().descrim() * 0.5 + : 0.0) + + prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + if (Geom::L2(delta) < stroke_tolerance) { fillnotstroke = false; } } @@ -268,25 +247,24 @@ ink_drag_data_received(GtkWidget *widget, } SPCSSAttr *css = sp_repr_css_attr_new(); - sp_repr_css_set_property( css, fillnotstroke ? "fill":"stroke", colorspec.c_str() ); + sp_repr_css_set_property(css, fillnotstroke ? "fill" : "stroke", colorspec.c_str()); - sp_desktop_apply_css_recursive( item, css, true ); + sp_desktop_apply_css_recursive(item, css, true); item->updateRepr(); - DocumentUndo::done( doc , SP_VERB_NONE, - _("Drop color") ); + DocumentUndo::done(doc, SP_VERB_NONE, _("Drop color")); } } - } - break; + } break; case SVG_DATA: case SVG_XML_DATA: { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setBool("/options/onimport", true); - gchar *svgdata = (gchar *)gtk_selection_data_get_data (data); + gchar *svgdata = (gchar *)gtk_selection_data_get_data(data); - Inkscape::XML::Document *rnewdoc = sp_repr_read_mem(svgdata, gtk_selection_data_get_length (data), SP_SVG_NS_URI); + Inkscape::XML::Document *rnewdoc = + sp_repr_read_mem(svgdata, gtk_selection_data_get_length(data), SP_SVG_NS_URI); if (rnewdoc == nullptr) { sp_ui_error_dialog(_("Could not parse SVG data")); @@ -299,7 +277,7 @@ ink_drag_data_received(GtkWidget *widget, Inkscape::XML::Node *newgroup = rnewdoc->createElement("svg:g"); newgroup->setAttribute("style", style); - Inkscape::XML::Document * xml_doc = doc->getReprDoc(); + Inkscape::XML::Document *xml_doc = doc->getReprDoc(); for (Inkscape::XML::Node *child = repr->firstChild(); child != nullptr; child = child->next()) { Inkscape::XML::Node *newchild = child->duplicate(xml_doc); newgroup->appendChild(newchild); @@ -321,14 +299,13 @@ ink_drag_data_received(GtkWidget *widget, desktop->getDocument()->ensureUpToDate(); Geom::OptRect sel_bbox = selection->visualBounds(); if (sel_bbox) { - Geom::Point m( desktop->point() - sel_bbox->midpoint() ); + Geom::Point m(desktop->point() - sel_bbox->midpoint()); selection->moveRelative(m, false); } } Inkscape::GC::release(newgroup); - DocumentUndo::done( doc, SP_VERB_NONE, - _("Drop SVG") ); + DocumentUndo::done(doc, SP_VERB_NONE, _("Drop SVG")); prefs->setBool("/options/onimport", false); break; } @@ -336,7 +313,7 @@ ink_drag_data_received(GtkWidget *widget, case URI_LIST: { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setBool("/options/onimport", true); - gchar *uri = (gchar *)gtk_selection_data_get_data (data); + gchar *uri = (gchar *)gtk_selection_data_get_data(data); sp_ui_import_files(uri); prefs->setBool("/options/onimport", false); break; @@ -345,30 +322,28 @@ ink_drag_data_received(GtkWidget *widget, case APP_X_INK_PASTE: { Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); cm->paste(desktop); - DocumentUndo::done( doc, SP_VERB_NONE, _("Drop Symbol") ); + DocumentUndo::done(doc, SP_VERB_NONE, _("Drop Symbol")); break; } case PNG_DATA: case JPEG_DATA: case IMAGE_DATA: { - Inkscape::Extension::Extension *ext = Inkscape::Extension::find_by_mime((info == JPEG_DATA ? "image/jpeg" : "image/png")); + Inkscape::Extension::Extension *ext = + Inkscape::Extension::find_by_mime((info == JPEG_DATA ? "image/jpeg" : "image/png")); bool save = (strcmp(ext->get_param_optiongroup("link"), "embed") == 0); ext->set_param_optiongroup("link", "embed"); ext->set_gui(false); - gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-dnd-import", NULL ); - g_file_set_contents(filename, - reinterpret_cast(gtk_selection_data_get_data (data)), - gtk_selection_data_get_length (data), - nullptr); + gchar *filename = g_build_filename(g_get_tmp_dir(), "inkscape-dnd-import", NULL); + g_file_set_contents(filename, reinterpret_cast(gtk_selection_data_get_data(data)), + gtk_selection_data_get_length(data), nullptr); file_import(doc, filename, ext); g_free(filename); ext->set_param_optiongroup("link", save ? "embed" : "link"); ext->set_gui(true); - DocumentUndo::done( doc , SP_VERB_NONE, - _("Drop bitmap image") ); + DocumentUndo::done(doc, SP_VERB_NONE, _("Drop bitmap image")); break; } } @@ -400,28 +375,26 @@ static void ink_drag_leave( GtkWidget */*widget*/, } #endif -void -ink_drag_setup(SPDesktopWidget* dtw) +void ink_drag_setup(SPDesktopWidget *dtw) { - if ( completeDropTargets == nullptr || completeDropTargetsCount == 0 ) - { + if (completeDropTargets == nullptr || completeDropTargetsCount == 0) { std::vector types; std::vector list = Gdk::Pixbuf::get_formats(); - for (auto one:list) { + for (auto one : list) { std::vector typesXX = one.get_mime_types(); - for (auto i:typesXX) { + for (auto i : typesXX) { types.push_back(i); } } completeDropTargetsCount = nui_drop_target_entries + types.size(); completeDropTargets = new GtkTargetEntry[completeDropTargetsCount]; - for ( int i = 0; i < (int)nui_drop_target_entries; i++ ) { + for (int i = 0; i < (int)nui_drop_target_entries; i++) { completeDropTargets[i] = ui_drop_target_entries[i]; } int pos = nui_drop_target_entries; - for (auto & type : types) { + for (auto &type : types) { completeDropTargets[pos].target = g_strdup(type.c_str()); completeDropTargets[pos].flags = 0; completeDropTargets[pos].info = IMAGE_DATA; @@ -431,16 +404,10 @@ ink_drag_setup(SPDesktopWidget* dtw) auto canvas = dtw->get_canvas(); - gtk_drag_dest_set(GTK_WIDGET(canvas->gobj()), - GTK_DEST_DEFAULT_ALL, - completeDropTargets, - completeDropTargetsCount, + gtk_drag_dest_set(GTK_WIDGET(canvas->gobj()), GTK_DEST_DEFAULT_ALL, completeDropTargets, completeDropTargetsCount, GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE)); - g_signal_connect(G_OBJECT(canvas->gobj()), - "drag_data_received", - G_CALLBACK(ink_drag_data_received), - dtw); + g_signal_connect(G_OBJECT(canvas->gobj()), "drag_data_received", G_CALLBACK(ink_drag_data_received), dtw); #if 0 g_signal_connect(G_OBJECT(win->gobj()), @@ -455,7 +422,6 @@ ink_drag_setup(SPDesktopWidget* dtw) #endif } - /* Local Variables: mode:c++ diff --git a/src/ui/draw-anchor.cpp b/src/ui/draw-anchor.cpp index 8f62f7a2c006388e0d3032dc75fe09d409db9e83..594996b1dc04ad36f0ce2c8bb9f02d7ecd21a3df 100644 --- a/src/ui/draw-anchor.cpp +++ b/src/ui/draw-anchor.cpp @@ -13,14 +13,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "ui/draw-anchor.h" + #include "desktop.h" -#include "ui/tools/tool-base.h" -#include "ui/tools/lpe-tool.h" -#include "display/sodipodi-ctrl.h" #include "display/curve.h" +#include "display/sodipodi-ctrl.h" #include "ui/control-manager.h" +#include "ui/tools/lpe-tool.h" +#include "ui/tools/tool-base.h" using Inkscape::ControlManager; @@ -77,7 +77,7 @@ SPDrawAnchor *sp_draw_anchor_test(SPDrawAnchor *anchor, Geom::Point w, bool acti { SPCtrl *ctrl = SP_CTRL(anchor->ctrl); - if ( activate && ( Geom::LInfty( w - anchor->dc->getDesktop()->d2w(anchor->dp) ) <= (ctrl->box.width() / 2.0) ) ) { + if (activate && (Geom::LInfty(w - anchor->dc->getDesktop()->d2w(anchor->dp)) <= (ctrl->box.width() / 2.0))) { if (!anchor->active) { ControlManager::getManager().setControlResize(anchor->ctrl, 4); g_object_set(anchor->ctrl, "fill_color", FILL_COLOR_MOUSEOVER, NULL); @@ -95,7 +95,6 @@ SPDrawAnchor *sp_draw_anchor_test(SPDrawAnchor *anchor, Geom::Point w, bool acti return nullptr; } - /* Local Variables: mode:c++ diff --git a/src/ui/draw-anchor.h b/src/ui/draw-anchor.h index 616e79aba5a10d3cdc789458f2df7e07bdea7632..bb0942b7d46a7556998f4326b481422a7ffd73c9 100644 --- a/src/ui/draw-anchor.h +++ b/src/ui/draw-anchor.h @@ -10,12 +10,11 @@ #ifndef SEEN_DRAW_ANCHOR_H #define SEEN_DRAW_ANCHOR_H -/** \file - * Drawing anchors. +/** \file + * Drawing anchors. */ #include <2geom/point.h> - #include namespace Inkscape { @@ -25,15 +24,16 @@ namespace Tools { class FreehandBase; } -} -} +} // namespace UI +} // namespace Inkscape class SPCurve; struct SPCanvasItem; /// The drawing anchor. /// \todo Make this a regular knot, this will allow setting statusbar tips. -struct SPDrawAnchor { +struct SPDrawAnchor +{ ~SPDrawAnchor(); Inkscape::UI::Tools::FreehandBase *dc; @@ -44,13 +44,10 @@ struct SPDrawAnchor { SPCanvasItem *ctrl = nullptr; }; - -SPDrawAnchor *sp_draw_anchor_new(Inkscape::UI::Tools::FreehandBase *dc, SPCurve *curve, bool start, - Geom::Point delta); +SPDrawAnchor *sp_draw_anchor_new(Inkscape::UI::Tools::FreehandBase *dc, SPCurve *curve, bool start, Geom::Point delta); SPDrawAnchor *sp_draw_anchor_destroy(SPDrawAnchor *anchor); SPDrawAnchor *sp_draw_anchor_test(SPDrawAnchor *anchor, Geom::Point w, bool activate); - #endif /* !SEEN_DRAW_ANCHOR_H */ /* diff --git a/src/ui/event-debug.h b/src/ui/event-debug.h index 150b84746d6b257c3deca5012042c3fb22da0035..916fa221fe8ea2f42ba744b2fd27c62e94ebc315 100644 --- a/src/ui/event-debug.h +++ b/src/ui/event-debug.h @@ -10,20 +10,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include #include +#include // See: https://developer.gnome.org/gdk3/stable/gdk3-Events.html -inline void ui_dump_event (GdkEvent *event, Glib::ustring const &prefix, bool merge = true) { - +inline void ui_dump_event(GdkEvent *event, Glib::ustring const &prefix, bool merge = true) +{ static GdkEventType old_type = GDK_NOTHING; static unsigned count = 0; // Doesn't usually help to dump a zillion events of the same type (e.g. GDK_MOTION_NOTIFY). ++count; if (merge && event->type == old_type) { - if ( count == 1 ) { + if (count == 1) { std::cout << prefix << " ... ditto" << std::endl; } return; @@ -34,9 +34,8 @@ inline void ui_dump_event (GdkEvent *event, Glib::ustring const &prefix, bool me std::cout << prefix << ": "; switch (event->type) { - case GDK_KEY_PRESS: - std::cout << "GDK_KEY_PRESS: " << event->key.hardware_keycode << std::endl; + std::cout << "GDK_KEY_PRESS: " << event->key.hardware_keycode << std::endl; break; case GDK_KEY_RELEASE: std::cout << "GDK_KEY_RELEASE: " << event->key.hardware_keycode << std::endl; @@ -79,7 +78,7 @@ inline void ui_dump_event (GdkEvent *event, Glib::ustring const &prefix, bool me std::cout << "GDK_TOUCH_END" << std::endl; break; case GDK_TOUCH_CANCEL: - std::cout << "GDK_TOUCH_CANCEL" << std::endl; + std::cout << "GDK_TOUCH_CANCEL" << std::endl; break; case GDK_TOUCHPAD_SWIPE: std::cout << "GDK_TOUCHPAD_SWIPE" << std::endl; diff --git a/src/ui/icon-loader.cpp b/src/ui/icon-loader.cpp index 626e3c97bac2c9a363a8068676cca7b41778c710..1c573239db492c3e3db31212709d8cfef688c140 100644 --- a/src/ui/icon-loader.cpp +++ b/src/ui/icon-loader.cpp @@ -10,18 +10,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "icon-loader.h" -#include "inkscape.h" -#include "io/resource.h" -#include "svg/svg-color.h" -#include "widgets/toolbox.h" + #include #include #include #include #include +#include "inkscape.h" +#include "io/resource.h" +#include "svg/svg-color.h" +#include "widgets/toolbox.h" + Gtk::Image *sp_get_icon_image(Glib::ustring icon_name, gint size) { Gtk::Image *icon = new Gtk::Image(); @@ -58,12 +59,13 @@ GtkWidget *sp_get_icon_image(Glib::ustring icon_name, GtkIconSize icon_size) Glib::RefPtr sp_get_icon_pixbuf(Glib::ustring icon_name, gint size) { Glib::RefPtr display = Gdk::Display::get_default(); - Glib::RefPtr screen = display->get_default_screen(); + Glib::RefPtr screen = display->get_default_screen(); Glib::RefPtr icon_theme = Gtk::IconTheme::get_for_screen(screen); Glib::RefPtr _icon_pixbuf; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs->getBool("/theme/symbolicIcons", false)) { - Gtk::IconInfo iconinfo = icon_theme->lookup_icon(icon_name + Glib::ustring("-symbolic"), size, Gtk::ICON_LOOKUP_FORCE_SIZE); + Gtk::IconInfo iconinfo = + icon_theme->lookup_icon(icon_name + Glib::ustring("-symbolic"), size, Gtk::ICON_LOOKUP_FORCE_SIZE); if (iconinfo) { bool was_symbolic = false; Glib::ustring css_str = ""; diff --git a/src/ui/icon-loader.h b/src/ui/icon-loader.h index 78975e210c0915a2eb8ee21793113d74c133cb93..16b5f85c2f1356c70fae9d8985c58c7159f2aee2 100644 --- a/src/ui/icon-loader.h +++ b/src/ui/icon-loader.h @@ -19,7 +19,7 @@ Gtk::Image *sp_get_icon_image(Glib::ustring icon_name, gint size); Gtk::Image *sp_get_icon_image(Glib::ustring icon_name, Gtk::BuiltinIconSize icon_size); Gtk::Image *sp_get_icon_image(Glib::ustring icon_name, Gtk::IconSize icon_size); Gtk::Image *sp_get_icon_image(Glib::ustring icon_name, gchar const *prefs_sice); -GtkWidget *sp_get_icon_image(Glib::ustring icon_name, GtkIconSize icon_size); +GtkWidget *sp_get_icon_image(Glib::ustring icon_name, GtkIconSize icon_size); Glib::RefPtr sp_get_icon_pixbuf(Glib::ustring icon_name, gint size); Glib::RefPtr sp_get_icon_pixbuf(Glib::ustring icon_name, Gtk::IconSize icon_size); Glib::RefPtr sp_get_icon_pixbuf(Glib::ustring icon_name, Gtk::BuiltinIconSize icon_size); diff --git a/src/ui/interface.cpp b/src/ui/interface.cpp index e1bf1f8676cb98be6fda9cf233456b8f1c4ba135..2296580b99c1ba82c00ddb1f98d92d2c206a843d 100644 --- a/src/ui/interface.cpp +++ b/src/ui/interface.cpp @@ -20,55 +20,49 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/interface.h" + #include "desktop.h" #include "document.h" #include "enums.h" -#include "file.h" -#include "inkscape.h" -#include "inkscape-window.h" -#include "preferences.h" -#include "shortcuts.h" - #include "extension/db.h" #include "extension/effect.h" #include "extension/find_extension_by_mime.h" #include "extension/input.h" - +#include "file.h" #include "helper/action.h" - +#include "inkscape-window.h" +#include "inkscape.h" #include "io/sys.h" - #include "object/sp-namedview.h" #include "object/sp-root.h" - +#include "preferences.h" +#include "shortcuts.h" #include "ui/dialog-events.h" #include "ui/dialog/dialog-manager.h" #include "ui/dialog/inkscape-preferences.h" #include "ui/dialog/layer-properties.h" -#include "ui/interface.h" - #include "ui/view/svg-view-widget.h" - #include "widgets/desktop-widget.h" static void sp_ui_import_one_file(char const *filename); static void sp_ui_import_one_file_with_check(gpointer filename, gpointer unused); -void -sp_ui_new_view() +void sp_ui_new_view() { SPDocument *document; document = SP_ACTIVE_DOCUMENT; - if (!document) return; + if (!document) + return; - ConcreteInkscapeApplication* app = &(ConcreteInkscapeApplication::get_instance()); + ConcreteInkscapeApplication *app = + &(ConcreteInkscapeApplication::get_instance()); app->window_open(document); } -void -sp_ui_close_view(GtkWidget */*widget*/) +void sp_ui_close_view(GtkWidget * /*widget*/) { SPDesktop *dt = SP_ACTIVE_DESKTOP; @@ -80,21 +74,21 @@ sp_ui_close_view(GtkWidget */*widget*/) return; // Shutdown operation has been canceled, so do nothing } - ConcreteInkscapeApplication* app = &(ConcreteInkscapeApplication::get_instance()); + ConcreteInkscapeApplication *app = + &(ConcreteInkscapeApplication::get_instance()); - InkscapeWindow* window = SP_ACTIVE_DESKTOP->getInkscapeWindow(); + InkscapeWindow *window = SP_ACTIVE_DESKTOP->getInkscapeWindow(); // If closing the last document, open a new document so Inkscape doesn't quit. std::list desktops; INKSCAPE.get_all_desktops(desktops); if (desktops.size() == 1) { - - SPDocument* old_document = window->get_document(); + SPDocument *old_document = window->get_document(); auto template_path = sp_file_default_template_uri(); - SPDocument *doc = app->document_new (template_path); + SPDocument *doc = app->document_new(template_path); - app->document_swap (window, doc); + app->document_swap(window, doc); if (app->document_window_count(old_document) == 0) { app->document_close(old_document); @@ -105,31 +99,26 @@ sp_ui_close_view(GtkWidget */*widget*/) sp_namedview_update_layers_from_document(dt); } else { - - app->destroy_window (window); + app->destroy_window(window); } } - -unsigned int -sp_ui_close_all() +unsigned int sp_ui_close_all() { - - ConcreteInkscapeApplication* app = &(ConcreteInkscapeApplication::get_instance()); + ConcreteInkscapeApplication *app = + &(ConcreteInkscapeApplication::get_instance()); app->destroy_all(); return true; } - -void -sp_ui_dialog_title_string(Inkscape::Verb *verb, gchar *c) +void sp_ui_dialog_title_string(Inkscape::Verb *verb, gchar *c) { - SPAction *action; + SPAction *action; unsigned int shortcut; - gchar *s; - gchar *atitle; + gchar *s; + gchar *atitle; action = verb->get_action(Inkscape::ActionContext()); if (!action) @@ -142,8 +131,8 @@ sp_ui_dialog_title_string(Inkscape::Verb *verb, gchar *c) g_free(atitle); shortcut = sp_shortcut_get_primary(verb); - if (shortcut!=GDK_KEY_VoidSymbol) { - gchar* key = sp_shortcut_get_label(shortcut); + if (shortcut != GDK_KEY_VoidSymbol) { + gchar *key = sp_shortcut_get_label(shortcut); s = g_stpcpy(s, " ("); s = g_stpcpy(s, key); g_stpcpy(s, ")"); @@ -151,14 +140,13 @@ sp_ui_dialog_title_string(Inkscape::Verb *verb, gchar *c) } } - -Glib::ustring getLayoutPrefPath( Inkscape::UI::View::View *view ) +Glib::ustring getLayoutPrefPath(Inkscape::UI::View::View *view) { Glib::ustring prefPath; - if (reinterpret_cast(view)->is_focusMode()) { + if (reinterpret_cast(view)->is_focusMode()) { prefPath = "/focus/"; - } else if (reinterpret_cast(view)->is_fullscreen()) { + } else if (reinterpret_cast(view)->is_fullscreen()) { prefPath = "/fullscreen/"; } else { prefPath = "/window/"; @@ -167,21 +155,18 @@ Glib::ustring getLayoutPrefPath( Inkscape::UI::View::View *view ) return prefPath; } - -void -sp_ui_import_files(gchar *buffer) +void sp_ui_import_files(gchar *buffer) { - gchar** l = g_uri_list_extract_uris(buffer); - for (unsigned int i=0; i < g_strv_length(l); i++) { - gchar *f = g_filename_from_uri (l[i], nullptr, nullptr); + gchar **l = g_uri_list_extract_uris(buffer); + for (unsigned int i = 0; i < g_strv_length(l); i++) { + gchar *f = g_filename_from_uri(l[i], nullptr, nullptr); sp_ui_import_one_file_with_check(f, nullptr); g_free(f); } g_strfreev(l); } -static void -sp_ui_import_one_file_with_check(gpointer filename, gpointer /*unused*/) +static void sp_ui_import_one_file_with_check(gpointer filename, gpointer /*unused*/) { if (filename) { if (strlen((char const *)filename) > 2) @@ -189,27 +174,27 @@ sp_ui_import_one_file_with_check(gpointer filename, gpointer /*unused*/) } } -static void -sp_ui_import_one_file(char const *filename) +static void sp_ui_import_one_file(char const *filename) { SPDocument *doc = SP_ACTIVE_DOCUMENT; - if (!doc) return; + if (!doc) + return; - if (filename == nullptr) return; + if (filename == nullptr) + return; // Pass off to common implementation // TODO might need to get the proper type of Inkscape::Extension::Extension - file_import( doc, filename, nullptr ); + file_import(doc, filename, nullptr); } -void -sp_ui_error_dialog(gchar const *message) +void sp_ui_error_dialog(gchar const *message) { GtkWidget *dlg; gchar *safeMsg = Inkscape::IO::sanitizeString(message); - dlg = gtk_message_dialog_new(nullptr, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, - GTK_BUTTONS_CLOSE, "%s", safeMsg); + dlg = gtk_message_dialog_new(nullptr, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", + safeMsg); sp_transientize(dlg); gtk_window_set_resizable(GTK_WINDOW(dlg), FALSE); gtk_dialog_run(GTK_DIALOG(dlg)); @@ -217,38 +202,32 @@ sp_ui_error_dialog(gchar const *message) g_free(safeMsg); } -bool -sp_ui_overwrite_file(gchar const *filename) +bool sp_ui_overwrite_file(gchar const *filename) { bool return_value = FALSE; if (Inkscape::IO::file_test(filename, G_FILE_TEST_EXISTS)) { Gtk::Window *window = SP_ACTIVE_DESKTOP->getToplevel(); - gchar* baseName = g_path_get_basename( filename ); - gchar* dirName = g_path_get_dirname( filename ); - GtkWidget* dialog = gtk_message_dialog_new_with_markup( window->gobj(), - (GtkDialogFlags)(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), - GTK_MESSAGE_QUESTION, - GTK_BUTTONS_NONE, - _( "A file named \"%s\" already exists. Do you want to replace it?\n\n" - "The file already exists in \"%s\". Replacing it will overwrite its contents." ), - baseName, - dirName - ); - gtk_dialog_add_buttons( GTK_DIALOG(dialog), - _("_Cancel"), GTK_RESPONSE_NO, - _("Replace"), GTK_RESPONSE_YES, - NULL ); - gtk_dialog_set_default_response( GTK_DIALOG(dialog), GTK_RESPONSE_YES ); - - if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_YES ) { + gchar *baseName = g_path_get_basename(filename); + gchar *dirName = g_path_get_dirname(filename); + GtkWidget *dialog = gtk_message_dialog_new_with_markup( + window->gobj(), (GtkDialogFlags)(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_MESSAGE_QUESTION, + GTK_BUTTONS_NONE, + _("A file named \"%s\" already exists. Do you want to replace " + "it?\n\n" + "The file already exists in \"%s\". Replacing it will overwrite its contents."), + baseName, dirName); + gtk_dialog_add_buttons(GTK_DIALOG(dialog), _("_Cancel"), GTK_RESPONSE_NO, _("Replace"), GTK_RESPONSE_YES, NULL); + gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_YES); + + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_YES) { return_value = TRUE; } else { return_value = FALSE; } gtk_widget_destroy(dialog); - g_free( baseName ); - g_free( dirName ); + g_free(baseName); + g_free(dirName); } else { return_value = TRUE; } diff --git a/src/ui/interface.h b/src/ui/interface.h index e7e191a64cc6c034865661892fd99039ff9f8c10..9a6ca86deb7ba164baad21bbb2faf841e6c224a0 100644 --- a/src/ui/interface.h +++ b/src/ui/interface.h @@ -35,9 +35,9 @@ class View; /** * \param widget unused */ -void sp_ui_close_view (GtkWidget *widget); +void sp_ui_close_view(GtkWidget *widget); -void sp_ui_new_view (); +void sp_ui_new_view(); void sp_ui_import_files(gchar *buffer); @@ -50,17 +50,17 @@ void sp_ui_import_files(gchar *buffer); * Returns FALSE if the user cancels the close_all operation, TRUE * otherwise. */ -unsigned int sp_ui_close_all (); +unsigned int sp_ui_close_all(); -void sp_ui_dialog_title_string (Inkscape::Verb * verb, char* c); +void sp_ui_dialog_title_string(Inkscape::Verb *verb, char *c); -Glib::ustring getLayoutPrefPath( Inkscape::UI::View::View *view ); +Glib::ustring getLayoutPrefPath(Inkscape::UI::View::View *view); /** * */ -void sp_ui_error_dialog (char const* message); -bool sp_ui_overwrite_file (char const* filename); +void sp_ui_error_dialog(char const *message); +bool sp_ui_overwrite_file(char const *filename); #endif // SEEN_SP_INTERFACE_H diff --git a/src/ui/monitor.cpp b/src/ui/monitor.cpp index a9a3f83985cdac72fe812ca09285d067375c7a17..95110e3833e3b466f9a7284f048af4e95f8f2e6d 100644 --- a/src/ui/monitor.cpp +++ b/src/ui/monitor.cpp @@ -20,7 +20,8 @@ namespace Inkscape { namespace UI { /** get monitor geometry of primary monitor */ -Gdk::Rectangle get_monitor_geometry_primary() { +Gdk::Rectangle get_monitor_geometry_primary() +{ Gdk::Rectangle monitor_geometry; auto const display = Gdk::Display::get_default(); auto monitor = display->get_primary_monitor(); @@ -35,7 +36,8 @@ Gdk::Rectangle get_monitor_geometry_primary() { } /** get monitor geometry of monitor containing largest part of window */ -Gdk::Rectangle get_monitor_geometry_at_window(const Glib::RefPtr& window) { +Gdk::Rectangle get_monitor_geometry_at_window(const Glib::RefPtr &window) +{ Gdk::Rectangle monitor_geometry; auto const display = Gdk::Display::get_default(); auto const monitor = display->get_monitor_at_window(window); @@ -44,17 +46,17 @@ Gdk::Rectangle get_monitor_geometry_at_window(const Glib::RefPtr& w } /** get monitor geometry of monitor at (or closest to) point on combined screen area */ -Gdk::Rectangle get_monitor_geometry_at_point(int x, int y) { +Gdk::Rectangle get_monitor_geometry_at_point(int x, int y) +{ Gdk::Rectangle monitor_geometry; auto const display = Gdk::Display::get_default(); - auto const monitor = display->get_monitor_at_point(x ,y); + auto const monitor = display->get_monitor_at_point(x, y); monitor->get_geometry(monitor_geometry); return monitor_geometry; } -} -} - +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/monitor.h b/src/ui/monitor.h index 78c105a904407100a6be276e04d64da0212cb471..f35e1a4d8c8f8e1c2fa0e3a9786cf784de199b91 100644 --- a/src/ui/monitor.h +++ b/src/ui/monitor.h @@ -18,11 +18,11 @@ namespace Inkscape { namespace UI { - Gdk::Rectangle get_monitor_geometry_primary(); - Gdk::Rectangle get_monitor_geometry_at_window(const Glib::RefPtr& window); - Gdk::Rectangle get_monitor_geometry_at_point(int x, int y); -} -} +Gdk::Rectangle get_monitor_geometry_primary(); +Gdk::Rectangle get_monitor_geometry_at_window(const Glib::RefPtr &window); +Gdk::Rectangle get_monitor_geometry_at_point(int x, int y); +} // namespace UI +} // namespace Inkscape #endif // SEEN_MONITOR_H diff --git a/src/ui/pref-pusher.cpp b/src/ui/pref-pusher.cpp index 3b84ba65a210632ffd7f2b731f0f9ca9061298df..fe66b77f0e03289a2f376c0717af8dbf4914d610 100644 --- a/src/ui/pref-pusher.cpp +++ b/src/ui/pref-pusher.cpp @@ -6,16 +6,16 @@ namespace Inkscape { namespace UI { -PrefPusher::PrefPusher( GtkToggleAction *act, Glib::ustring const &path, void (*callback)(gpointer), gpointer cbData ) : - Observer(path), - act(act), - callback(callback), - cbData(cbData), - freeze(false) +PrefPusher::PrefPusher(GtkToggleAction *act, Glib::ustring const &path, void (*callback)(gpointer), gpointer cbData) + : Observer(path) + , act(act) + , callback(callback) + , cbData(cbData) + , freeze(false) { - g_signal_connect_after( G_OBJECT(act), "toggled", G_CALLBACK(toggleCB), this); + g_signal_connect_after(G_OBJECT(act), "toggled", G_CALLBACK(toggleCB), this); freeze = true; - gtk_toggle_action_set_active( act, Inkscape::Preferences::get()->getBool(observed_path) ); + gtk_toggle_action_set_active(act, Inkscape::Preferences::get()->getBool(observed_path)); freeze = false; Inkscape::Preferences::get()->addObserver(*this); @@ -26,7 +26,7 @@ PrefPusher::~PrefPusher() Inkscape::Preferences::get()->removeObserver(*this); } -void PrefPusher::toggleCB( GtkToggleAction * /*act*/, PrefPusher *self ) +void PrefPusher::toggleCB(GtkToggleAction * /*act*/, PrefPusher *self) { if (self) { self->handleToggled(); @@ -37,7 +37,7 @@ void PrefPusher::handleToggled() { if (!freeze) { freeze = true; - Inkscape::Preferences::get()->setBool(observed_path, gtk_toggle_action_get_active( act )); + Inkscape::Preferences::get()->setBool(observed_path, gtk_toggle_action_get_active(act)); if (callback) { (*callback)(cbData); } @@ -51,12 +51,12 @@ void PrefPusher::notify(Inkscape::Preferences::Entry const &newVal) bool oldBool = gtk_toggle_action_get_active(act); if (!freeze && (newBool != oldBool)) { - gtk_toggle_action_set_active( act, newBool ); + gtk_toggle_action_set_active(act, newBool); } } -} -} +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/pref-pusher.h b/src/ui/pref-pusher.h index 0d62266c478572fd507cc43312db0a4ca555c751..c03d51fca1e6b14a638315c0497fad56ddb3bbb8 100644 --- a/src/ui/pref-pusher.h +++ b/src/ui/pref-pusher.h @@ -25,10 +25,8 @@ public: * @param callback function to invoke when changes are pushed. * @param cbData data to be passed on to the callback function. */ - PrefPusher( GtkToggleAction *act, - Glib::ustring const & path, - void (*callback)(gpointer) = nullptr, - gpointer cbData = nullptr ); + PrefPusher(GtkToggleAction *act, Glib::ustring const &path, void (*callback)(gpointer) = nullptr, + gpointer cbData = nullptr); /** * Destructor that unregisters the preference callback. @@ -40,7 +38,6 @@ public: */ void notify(Inkscape::Preferences::Entry const &new_val) override; - private: /** * Callback hook invoked when the widget changes. @@ -48,7 +45,7 @@ private: * @param act the toggle action widget that was changed. * @param self the PrefPusher instance the callback was registered to. */ - static void toggleCB( GtkToggleAction *act, PrefPusher *self ); + static void toggleCB(GtkToggleAction *act, PrefPusher *self); /** * Method to handle the widget change. @@ -64,8 +61,8 @@ private: bool freeze; }; -} -} +} // namespace UI +} // namespace Inkscape #endif /* diff --git a/src/ui/previewable.h b/src/ui/previewable.h index c25f2dbb63782424196cd0ce8d38207f9a253e75..82fff5dfa2693deab1ed577971a9967d5262167a 100644 --- a/src/ui/previewable.h +++ b/src/ui/previewable.h @@ -13,7 +13,6 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include #include "widget/preview.h" @@ -21,7 +20,8 @@ namespace Inkscape { namespace UI { -enum PreviewStyle { +enum PreviewStyle +{ PREVIEW_STYLE_ICON = 0, PREVIEW_STYLE_PREVIEW, PREVIEW_STYLE_NAME, @@ -32,23 +32,17 @@ enum PreviewStyle { PREVIEW_STYLE_PREVIEW_BLURB }; - class Previewable { public: -// TODO need to add some nice parameters + // TODO need to add some nice parameters virtual ~Previewable() = default; - virtual Gtk::Widget* getPreview(UI::Widget::PreviewStyle style, - UI::Widget::ViewType view, - UI::Widget::PreviewSize size, - guint ratio, - guint border) = 0; + virtual Gtk::Widget *getPreview(UI::Widget::PreviewStyle style, UI::Widget::ViewType view, + UI::Widget::PreviewSize size, guint ratio, guint border) = 0; }; - -} //namespace UI -} //namespace Inkscape - +} // namespace UI +} // namespace Inkscape #endif // SEEN_PREVIEWABLE_H diff --git a/src/ui/previewholder.cpp b/src/ui/previewholder.cpp index 12a71c8e89c0919595d648493b917f198355a559..b7751011e003a96df161e6e3f52df2ae6395558a 100644 --- a/src/ui/previewholder.cpp +++ b/src/ui/previewholder.cpp @@ -10,51 +10,49 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - -#include "previewable.h" #include "previewholder.h" -#include -#include -#include #include #include +#include +#include +#include + +#include "previewable.h" #define COLUMNS_FOR_SMALL 16 #define COLUMNS_FOR_LARGE 8 //#define COLUMNS_FOR_SMALL 48 //#define COLUMNS_FOR_LARGE 32 - namespace Inkscape { namespace UI { - -PreviewHolder::PreviewHolder() : - Bin(), - _scroller(nullptr), - _insides(nullptr), - _prefCols(0), - _updatesFrozen(false), - _anchor(SP_ANCHOR_CENTER), - _baseSize(UI::Widget::PREVIEW_SIZE_SMALL), - _ratio(100), - _view(UI::Widget::VIEW_TYPE_LIST), - _wrap(false), - _border(UI::Widget::BORDER_NONE) +PreviewHolder::PreviewHolder() + : Bin() + , _scroller(nullptr) + , _insides(nullptr) + , _prefCols(0) + , _updatesFrozen(false) + , _anchor(SP_ANCHOR_CENTER) + , _baseSize(UI::Widget::PREVIEW_SIZE_SMALL) + , _ratio(100) + , _view(UI::Widget::VIEW_TYPE_LIST) + , _wrap(false) + , _border(UI::Widget::BORDER_NONE) { - set_name( "PreviewHolder" ); + set_name("PreviewHolder"); _scroller = Gtk::manage(new Gtk::ScrolledWindow()); - _scroller->set_name( "PreviewHolderScroller" ); + _scroller->set_name("PreviewHolderScroller"); _scroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); _insides = Gtk::manage(new Gtk::Grid()); - _insides->set_name( "PreviewHolderGrid" ); + _insides->set_name("PreviewHolderGrid"); _insides->set_column_spacing(8); _scroller->set_hexpand(); _scroller->set_vexpand(); - _scroller->add( *_insides ); + _scroller->add(*_insides); // Disable overlay scrolling as the scrollbar covers up swatches. // For some reason this also makes the height 55px. @@ -63,8 +61,7 @@ PreviewHolder::PreviewHolder() : add(*_scroller); } -PreviewHolder::~PreviewHolder() -= default; +PreviewHolder::~PreviewHolder() = default; /** * Translates vertical scrolling into horizontal @@ -90,7 +87,7 @@ bool PreviewHolder::on_scroll_event(GdkEventScroll *event) break; case GDK_SCROLL_DOWN: case GDK_SCROLL_RIGHT: - move = adj->get_page_size(); + move = adj->get_page_size(); break; case GDK_SCROLL_SMOOTH: if (fabs(event->delta_y) <= fabs(event->delta_x)) { @@ -118,8 +115,8 @@ void PreviewHolder::clear() items.clear(); _prefCols = 0; // Kludge to restore scrollbars - if ( !_wrap && (_view != UI::Widget::VIEW_TYPE_LIST) && (_anchor == SP_ANCHOR_NORTH || _anchor == SP_ANCHOR_SOUTH) ) { - _scroller->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_NEVER ); + if (!_wrap && (_view != UI::Widget::VIEW_TYPE_LIST) && (_anchor == SP_ANCHOR_NORTH || _anchor == SP_ANCHOR_SOUTH)) { + _scroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_NEVER); } rebuildUI(); } @@ -129,73 +126,65 @@ void PreviewHolder::clear() * * \param[in] preview The Previewable item to add */ -void PreviewHolder::addPreview( Previewable* preview ) +void PreviewHolder::addPreview(Previewable *preview) { items.push_back(preview); - if ( !_updatesFrozen ) - { + if (!_updatesFrozen) { int i = items.size() - 1; - switch(_view) { - case UI::Widget::VIEW_TYPE_LIST: - { - Gtk::Widget* label = Gtk::manage(preview->getPreview(UI::Widget::PREVIEW_STYLE_BLURB, - UI::Widget::VIEW_TYPE_LIST, - _baseSize, _ratio, _border)); - Gtk::Widget* item = Gtk::manage(preview->getPreview(UI::Widget::PREVIEW_STYLE_PREVIEW, - UI::Widget::VIEW_TYPE_LIST, - _baseSize, _ratio, _border)); - - item->set_hexpand(); - item->set_vexpand(); - _insides->attach(*item, 0, i, 1, 1); - - label->set_hexpand(); - label->set_valign(Gtk::ALIGN_CENTER); - _insides->attach(*label, 1, i, 1, 1); + switch (_view) { + case UI::Widget::VIEW_TYPE_LIST: { + Gtk::Widget *label = Gtk::manage(preview->getPreview( + UI::Widget::PREVIEW_STYLE_BLURB, UI::Widget::VIEW_TYPE_LIST, _baseSize, _ratio, _border)); + Gtk::Widget *item = Gtk::manage(preview->getPreview( + UI::Widget::PREVIEW_STYLE_PREVIEW, UI::Widget::VIEW_TYPE_LIST, _baseSize, _ratio, _border)); + + item->set_hexpand(); + item->set_vexpand(); + _insides->attach(*item, 0, i, 1, 1); + + label->set_hexpand(); + label->set_valign(Gtk::ALIGN_CENTER); + _insides->attach(*label, 1, i, 1, 1); + } + + break; + case UI::Widget::VIEW_TYPE_GRID: { + Gtk::Widget *item = Gtk::manage(items[i]->getPreview( + UI::Widget::PREVIEW_STYLE_PREVIEW, UI::Widget::VIEW_TYPE_GRID, _baseSize, _ratio, _border)); + + int ncols = 1; + int nrows = 1; + int col = 0; + int row = 0; + + // To get size + auto kids = _insides->get_children(); + int childCount = (int)kids.size(); + if (childCount > 0) { + // Need already shown widget + calcGridSize(kids[0], items.size() + 1, ncols, nrows); + + // Column and row for the new widget + col = i % ncols; + row = i / ncols; } - break; - case UI::Widget::VIEW_TYPE_GRID: - { - Gtk::Widget* item = Gtk::manage(items[i]->getPreview(UI::Widget::PREVIEW_STYLE_PREVIEW, - UI::Widget::VIEW_TYPE_GRID, - _baseSize, _ratio, _border)); - - int ncols = 1; - int nrows = 1; - int col = 0; - int row = 0; - - // To get size - auto kids = _insides->get_children(); - int childCount = (int)kids.size(); - if (childCount > 0 ) { - - // Need already shown widget - calcGridSize( kids[0], items.size()+1, ncols, nrows ); - - // Column and row for the new widget - col = i % ncols; - row = i / ncols; - - } - - // Loop through the existing widgets and move them to new location - for ( int j = 1; j < childCount; j++ ) { - auto target = kids[childCount - (j + 1)]; - int col2 = j % ncols; - int row2 = j / ncols; - _insides->remove( *target ); - - target->set_hexpand(); - target->set_vexpand(); - _insides->attach( *target, col2, row2, 1, 1); - } - item->set_hexpand(); - item->set_vexpand(); - _insides->attach(*item, col, row, 1, 1); + // Loop through the existing widgets and move them to new location + for (int j = 1; j < childCount; j++) { + auto target = kids[childCount - (j + 1)]; + int col2 = j % ncols; + int row2 = j / ncols; + _insides->remove(*target); + + target->set_hexpand(); + target->set_vexpand(); + _insides->attach(*target, col2, row2, 1, 1); } + item->set_hexpand(); + item->set_vexpand(); + _insides->attach(*item, col, row, 1, 1); + } } _scroller->show_all_children(); @@ -213,20 +202,18 @@ void PreviewHolder::thawUpdates() rebuildUI(); } -void -PreviewHolder::setStyle(UI::Widget::PreviewSize size, - UI::Widget::ViewType view, - guint ratio, - UI::Widget::BorderStyle border ) +void PreviewHolder::setStyle(UI::Widget::PreviewSize size, UI::Widget::ViewType view, guint ratio, + UI::Widget::BorderStyle border) { - if ( size != _baseSize || view != _view || ratio != _ratio || border != _border ) { + if (size != _baseSize || view != _view || ratio != _ratio || border != _border) { _baseSize = size; _view = view; _ratio = ratio; _border = border; // Kludge to restore scrollbars - if ( !_wrap && (_view != UI::Widget::VIEW_TYPE_LIST) && (_anchor == SP_ANCHOR_NORTH || _anchor == SP_ANCHOR_SOUTH) ) { - _scroller->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_NEVER ); + if (!_wrap && (_view != UI::Widget::VIEW_TYPE_LIST) && + (_anchor == SP_ANCHOR_NORTH || _anchor == SP_ANCHOR_SOUTH)) { + _scroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_NEVER); } rebuildUI(); } @@ -234,48 +221,37 @@ PreviewHolder::setStyle(UI::Widget::PreviewSize size, void PreviewHolder::setOrientation(SPAnchorType anchor) { - if ( _anchor != anchor ) - { + if (_anchor != anchor) { _anchor = anchor; - switch ( _anchor ) - { + switch (_anchor) { case SP_ANCHOR_NORTH: - case SP_ANCHOR_SOUTH: - { - _scroller->set_policy( Gtk::POLICY_AUTOMATIC, _wrap ? Gtk::POLICY_AUTOMATIC : Gtk::POLICY_NEVER ); - } - break; + case SP_ANCHOR_SOUTH: { + _scroller->set_policy(Gtk::POLICY_AUTOMATIC, _wrap ? Gtk::POLICY_AUTOMATIC : Gtk::POLICY_NEVER); + } break; case SP_ANCHOR_EAST: - case SP_ANCHOR_WEST: - { - _scroller->set_policy( Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC ); - } - break; + case SP_ANCHOR_WEST: { + _scroller->set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); + } break; - default: - { - _scroller->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC ); + default: { + _scroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); } } rebuildUI(); } } -void PreviewHolder::setWrap( bool wrap ) +void PreviewHolder::setWrap(bool wrap) { if (_wrap != wrap) { _wrap = wrap; - switch ( _anchor ) - { + switch (_anchor) { case SP_ANCHOR_NORTH: - case SP_ANCHOR_SOUTH: - { - _scroller->set_policy( Gtk::POLICY_AUTOMATIC, _wrap ? Gtk::POLICY_AUTOMATIC : Gtk::POLICY_NEVER ); - } - break; - default: - { + case SP_ANCHOR_SOUTH: { + _scroller->set_policy(Gtk::POLICY_AUTOMATIC, _wrap ? Gtk::POLICY_AUTOMATIC : Gtk::POLICY_NEVER); + } break; + default: { (void)0; // do nothing; } @@ -284,12 +260,11 @@ void PreviewHolder::setWrap( bool wrap ) } } -void PreviewHolder::setColumnPref( int cols ) +void PreviewHolder::setColumnPref(int cols) { _prefCols = cols; } - /** * Calculate the grid side of a preview holder * @@ -298,23 +273,22 @@ void PreviewHolder::setColumnPref( int cols ) * \param[out] ncols The number of columns in grid. * \param[out] nrows The number of rows in grid. */ -void PreviewHolder::calcGridSize( const Gtk::Widget* item, int itemCount, int& ncols, int& nrows ) +void PreviewHolder::calcGridSize(const Gtk::Widget *item, int itemCount, int &ncols, int &nrows) { // Initially set all items in a horizontal row ncols = itemCount; nrows = 1; - if ( _anchor == SP_ANCHOR_SOUTH || _anchor == SP_ANCHOR_NORTH ) { + if (_anchor == SP_ANCHOR_SOUTH || _anchor == SP_ANCHOR_NORTH) { Gtk::Requisition req; Gtk::Requisition req_natural; _scroller->get_preferred_size(req, req_natural); int currW = _scroller->get_width(); - if ( currW > req.width ) { + if (currW > req.width) { req.width = currW; } if (_wrap && item != nullptr) { - // Get width of bar. int width_scroller = _scroller->get_width(); @@ -331,20 +305,21 @@ void PreviewHolder::calcGridSize( const Gtk::Widget* item, int itemCount, int& n // On first run, scroller width is not set correct... so we need to fudge it: if (ncols < 2) { - ncols = itemCount/2; + ncols = itemCount / 2; nrows = 2; } else { nrows = itemCount / ncols; } } } else { - ncols = (_baseSize == UI::Widget::PREVIEW_SIZE_SMALL || _baseSize == UI::Widget::PREVIEW_SIZE_TINY) ? - COLUMNS_FOR_SMALL : COLUMNS_FOR_LARGE; - if ( _prefCols > 0 ) { + ncols = (_baseSize == UI::Widget::PREVIEW_SIZE_SMALL || _baseSize == UI::Widget::PREVIEW_SIZE_TINY) + ? COLUMNS_FOR_SMALL + : COLUMNS_FOR_LARGE; + if (_prefCols > 0) { ncols = _prefCols; } nrows = (itemCount + (ncols - 1)) / ncols; - if ( nrows < 1 ) { + if (nrows < 1) { nrows = 1; } } @@ -366,15 +341,16 @@ void PreviewHolder::rebuildUI() } switch (_view) { - case UI::Widget::VIEW_TYPE_LIST: - { + case UI::Widget::VIEW_TYPE_LIST: { _insides->set_column_spacing(8); - for ( unsigned int i = 0; i < items.size(); i++ ) { - Gtk::Widget* label = Gtk::manage(items[i]->getPreview(UI::Widget::PREVIEW_STYLE_BLURB, _view, _baseSize, _ratio, _border)); - //label->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER); + for (unsigned int i = 0; i < items.size(); i++) { + Gtk::Widget *label = Gtk::manage( + items[i]->getPreview(UI::Widget::PREVIEW_STYLE_BLURB, _view, _baseSize, _ratio, _border)); + // label->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER); - Gtk::Widget* item = Gtk::manage(items[i]->getPreview(UI::Widget::PREVIEW_STYLE_PREVIEW, _view, _baseSize, _ratio, _border)); + Gtk::Widget *item = Gtk::manage( + items[i]->getPreview(UI::Widget::PREVIEW_STYLE_PREVIEW, _view, _baseSize, _ratio, _border)); item->set_hexpand(); item->set_vexpand(); @@ -384,37 +360,36 @@ void PreviewHolder::rebuildUI() label->set_valign(Gtk::ALIGN_CENTER); _insides->attach(*label, 1, i, 1, 1); } - } - break; + } break; - case UI::Widget::VIEW_TYPE_GRID: - { + case UI::Widget::VIEW_TYPE_GRID: { int col = 0; int row = 0; int ncols = 2; int nrows = 1; - for ( unsigned int i = 0; i < items.size(); i++ ) { - + for (unsigned int i = 0; i < items.size(); i++) { // If this is the last row, flag so the previews can draw a bottom - UI::Widget::BorderStyle border = ((row == nrows -1) && (_border == UI::Widget::BORDER_SOLID)) ? - UI::Widget::BORDER_SOLID_LAST_ROW : _border; + UI::Widget::BorderStyle border = ((row == nrows - 1) && (_border == UI::Widget::BORDER_SOLID)) + ? UI::Widget::BORDER_SOLID_LAST_ROW + : _border; - Gtk::Widget* item = Gtk::manage(items[i]->getPreview(UI::Widget::PREVIEW_STYLE_PREVIEW, _view, _baseSize, _ratio, border)); + Gtk::Widget *item = Gtk::manage( + items[i]->getPreview(UI::Widget::PREVIEW_STYLE_PREVIEW, _view, _baseSize, _ratio, border)); item->set_hexpand(); item->set_vexpand(); if (i == 0) { // We need one item shown before we can call calcGridSize()... - _insides->attach( *item, 0, 0, 1, 1); + _insides->attach(*item, 0, 0, 1, 1); _scroller->show_all_children(); - calcGridSize( item, items.size(), ncols, nrows ); + calcGridSize(item, items.size(), ncols, nrows); } else { // We've already calculated grid size. - _insides->attach( *item, col, row, 1, 1); + _insides->attach(*item, col, row, 1, 1); } - if ( ++col >= ncols ) { + if (++col >= ncols) { col = 0; row++; } @@ -425,13 +400,8 @@ void PreviewHolder::rebuildUI() _scroller->show_all_children(); } - - - - -} //namespace UI -} //namespace Inkscape - +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/previewholder.h b/src/ui/previewholder.h index 1dd35bfb58d9212a825b0fc935eb0fdaa5f3e547..ec0e96b221a2f20ecc888a0daf60e52fb0f6f7e0 100644 --- a/src/ui/previewholder.h +++ b/src/ui/previewholder.h @@ -20,7 +20,7 @@ namespace Gtk { class Grid; class ScrolledWindow; -} +} // namespace Gtk #include "enums.h" @@ -36,31 +36,29 @@ public: ~PreviewHolder() override; virtual void clear(); - virtual void addPreview( Previewable* preview ); + virtual void addPreview(Previewable *preview); virtual void freezeUpdates(); virtual void thawUpdates(); - virtual void setStyle(UI::Widget::PreviewSize size, - UI::Widget::ViewType view, - guint ratio, + virtual void setStyle(UI::Widget::PreviewSize size, UI::Widget::ViewType view, guint ratio, UI::Widget::BorderStyle border); virtual void setOrientation(SPAnchorType how); virtual int getColumnPref() const { return _prefCols; } - virtual void setColumnPref( int cols ); + virtual void setColumnPref(int cols); virtual UI::Widget::PreviewSize getPreviewSize() const { return _baseSize; } virtual UI::Widget::ViewType getPreviewType() const { return _view; } virtual guint getPreviewRatio() const { return _ratio; } virtual UI::Widget::BorderStyle getPreviewBorder() const { return _border; } - virtual void setWrap( bool wrap ); + virtual void setWrap(bool wrap); virtual bool getWrap() const { return _wrap; } protected: - bool on_scroll_event(GdkEventScroll*) override; + bool on_scroll_event(GdkEventScroll *) override; private: void rebuildUI(); - void calcGridSize( const Gtk::Widget* item, int itemCount, int& ncols, int& nrows ); + void calcGridSize(const Gtk::Widget *item, int itemCount, int &ncols, int &nrows); - std::vector items; + std::vector items; Gtk::ScrolledWindow *_scroller; Gtk::Grid *_insides; @@ -74,8 +72,8 @@ private: UI::Widget::BorderStyle _border; }; -} //namespace UI -} //namespace Inkscape +} // namespace UI +} // namespace Inkscape #endif // SEEN_PREVIEW_HOLDER_H diff --git a/src/ui/selected-color.cpp b/src/ui/selected-color.cpp index d8bbab1bcd8d238459fb110a00b34b44c5494673..51275a3dd5b596c8c8fb718109dba638187ff258 100644 --- a/src/ui/selected-color.cpp +++ b/src/ui/selected-color.cpp @@ -12,11 +12,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include +#include "ui/selected-color.h" + #include +#include #include "svg/svg-icc-color.h" -#include "ui/selected-color.h" namespace Inkscape { namespace UI { @@ -24,20 +25,18 @@ namespace UI { double const SelectedColor::_EPSILON = 1e-4; SelectedColor::SelectedColor() - : _color(0) + : _color(0) , _alpha(1.0) , _held(false) , _virgin(true) , _updating(false) -{ - -} +{} SelectedColor::~SelectedColor() = default; void SelectedColor::setColor(SPColor const &color) { - setColorAlpha( color, _alpha); + setColorAlpha(color, _alpha); } SPColor SelectedColor::color() const @@ -47,8 +46,8 @@ SPColor SelectedColor::color() const void SelectedColor::setAlpha(gfloat alpha) { - g_return_if_fail( ( 0.0 <= alpha ) && ( alpha <= 1.0 ) ); - setColorAlpha( _color, alpha); + g_return_if_fail((0.0 <= alpha) && (alpha <= 1.0)); + setColorAlpha(_color, alpha); } gfloat SelectedColor::alpha() const @@ -71,32 +70,29 @@ guint32 SelectedColor::value() const void SelectedColor::setColorAlpha(SPColor const &color, gfloat alpha, bool emit_signal) { #ifdef DUMP_CHANGE_INFO - g_message("SelectedColor::setColorAlpha( this=%p, %f, %f, %f, %s, %f, %s)", this, color.v.c[0], color.v.c[1], color.v.c[2], (color.icc?color.icc->colorProfile.c_str():""), alpha, (emit_signal?"YES":"no")); + g_message("SelectedColor::setColorAlpha( this=%p, %f, %f, %f, %s, %f, %s)", this, color.v.c[0], color.v.c[1], + color.v.c[2], (color.icc ? color.icc->colorProfile.c_str() : ""), alpha, + (emit_signal ? "YES" : "no")); #endif - g_return_if_fail( ( 0.0 <= alpha ) && ( alpha <= 1.0 ) ); + g_return_if_fail((0.0 <= alpha) && (alpha <= 1.0)); if (_updating) { return; } #ifdef DUMP_CHANGE_INFO - g_message("---- SelectedColor::setColorAlpha virgin:%s !close:%s alpha is:%s", - (_virgin?"YES":"no"), - (!color.isClose( _color, _EPSILON )?"YES":"no"), - ((fabs((_alpha) - (alpha)) >= _EPSILON )?"YES":"no") - ); + g_message("---- SelectedColor::setColorAlpha virgin:%s !close:%s alpha is:%s", (_virgin ? "YES" : "no"), + (!color.isClose(_color, _EPSILON) ? "YES" : "no"), + ((fabs((_alpha) - (alpha)) >= _EPSILON) ? "YES" : "no")); #endif - if ( _virgin || !color.isClose( _color, _EPSILON ) || - (fabs((_alpha) - (alpha)) >= _EPSILON )) { - + if (_virgin || !color.isClose(_color, _EPSILON) || (fabs((_alpha) - (alpha)) >= _EPSILON)) { _virgin = false; _color = color; _alpha = alpha; - if (emit_signal) - { + if (emit_signal) { _updating = true; if (_held) { signal_dragged.emit(); @@ -108,18 +104,20 @@ void SelectedColor::setColorAlpha(SPColor const &color, gfloat alpha, bool emit_ #ifdef DUMP_CHANGE_INFO } else { - g_message("++++ SelectedColor::setColorAlpha color:%08x ==> _color:%08X isClose:%s", color.toRGBA32(alpha), _color.toRGBA32(_alpha), - (color.isClose( _color, _EPSILON )?"YES":"no")); + g_message("++++ SelectedColor::setColorAlpha color:%08x ==> _color:%08X isClose:%s", + color.toRGBA32(alpha), _color.toRGBA32(_alpha), (color.isClose(_color, _EPSILON) ? "YES" : "no")); #endif } } -void SelectedColor::colorAlpha(SPColor &color, gfloat &alpha) const { - color = _color; - alpha = _alpha; +void SelectedColor::colorAlpha(SPColor &color, gfloat &alpha) const +{ + color = _color; + alpha = _alpha; } -void SelectedColor::setHeld(bool held) { +void SelectedColor::setHeld(bool held) +{ if (_updating) { return; } @@ -140,12 +138,13 @@ void SelectedColor::setHeld(bool held) { _updating = false; } -void SelectedColor::preserveICC() { +void SelectedColor::preserveICC() +{ _color.icc = _color.icc ? new SVGICCColor(*_color.icc) : nullptr; } -} -} +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/selected-color.h b/src/ui/selected-color.h index 9543111d9a6567eb74a7ae9030376bba30417d33..80a2feacd0008b80ba5cf0936765b3c251a377fe 100644 --- a/src/ui/selected-color.h +++ b/src/ui/selected-color.h @@ -15,27 +15,27 @@ #define SEEN_SELECTED_COLOR #include -#include #include +#include #include "color.h" -namespace Gtk -{ - class Widget; +namespace Gtk { +class Widget; } namespace Inkscape { namespace UI { -class SelectedColor { +class SelectedColor +{ public: SelectedColor(); virtual ~SelectedColor(); // By default, disallow copy constructor and assignment operator SelectedColor(SelectedColor const &obj) = delete; - SelectedColor& operator=(SelectedColor const &obj) = delete; + SelectedColor &operator=(SelectedColor const &obj) = delete; void setColor(SPColor const &color); SPColor color() const; @@ -76,16 +76,17 @@ private: static double const _EPSILON; }; -class ColorSelectorFactory { +class ColorSelectorFactory +{ public: virtual ~ColorSelectorFactory() = default; - virtual Gtk::Widget* createWidget(SelectedColor &color) const = 0; + virtual Gtk::Widget *createWidget(SelectedColor &color) const = 0; virtual Glib::ustring modeName() const = 0; }; -} -} +} // namespace UI +} // namespace Inkscape #endif /* diff --git a/src/ui/shape-editor-knotholders.cpp b/src/ui/shape-editor-knotholders.cpp index a9fb25c0c9110d291c63d18512c3b01af90f7756..10312fc7552b63f26b63c2b933c1f6fd55962516 100644 --- a/src/ui/shape-editor-knotholders.cpp +++ b/src/ui/shape-editor-knotholders.cpp @@ -14,14 +14,10 @@ #include -#include "preferences.h" #include "desktop.h" -#include "knotholder.h" #include "knot-holder-entity.h" -#include "style.h" - +#include "knotholder.h" #include "live_effects/effect.h" - #include "object/box3d.h" #include "object/sp-ellipse.h" #include "object/sp-flowtext.h" @@ -35,59 +31,79 @@ #include "object/sp-text.h" #include "object/sp-textpath.h" #include "object/sp-tspan.h" +#include "preferences.h" +#include "style.h" -class RectKnotHolder : public KnotHolder { +class RectKnotHolder : public KnotHolder +{ public: RectKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler); - ~RectKnotHolder() override = default;; + ~RectKnotHolder() override = default; + ; }; -class Box3DKnotHolder : public KnotHolder { +class Box3DKnotHolder : public KnotHolder +{ public: Box3DKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler); - ~Box3DKnotHolder() override = default;; + ~Box3DKnotHolder() override = default; + ; }; -class ArcKnotHolder : public KnotHolder { +class ArcKnotHolder : public KnotHolder +{ public: ArcKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler); - ~ArcKnotHolder() override = default;; + ~ArcKnotHolder() override = default; + ; }; -class StarKnotHolder : public KnotHolder { +class StarKnotHolder : public KnotHolder +{ public: StarKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler); - ~StarKnotHolder() override = default;; + ~StarKnotHolder() override = default; + ; }; -class SpiralKnotHolder : public KnotHolder { +class SpiralKnotHolder : public KnotHolder +{ public: SpiralKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler); - ~SpiralKnotHolder() override = default;; + ~SpiralKnotHolder() override = default; + ; }; -class OffsetKnotHolder : public KnotHolder { +class OffsetKnotHolder : public KnotHolder +{ public: OffsetKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler); - ~OffsetKnotHolder() override = default;; + ~OffsetKnotHolder() override = default; + ; }; -class TextKnotHolder : public KnotHolder { +class TextKnotHolder : public KnotHolder +{ public: TextKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler); - ~TextKnotHolder() override = default;; + ~TextKnotHolder() override = default; + ; }; -class FlowtextKnotHolder : public KnotHolder { +class FlowtextKnotHolder : public KnotHolder +{ public: FlowtextKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler); - ~FlowtextKnotHolder() override = default;; + ~FlowtextKnotHolder() override = default; + ; }; -class MiscKnotHolder : public KnotHolder { +class MiscKnotHolder : public KnotHolder +{ public: MiscKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler); - ~MiscKnotHolder() override = default;; + ~MiscKnotHolder() override = default; + ; }; namespace { @@ -130,7 +146,8 @@ KnotHolder *createKnotHolder(SPItem *item, SPDesktop *desktop) // might not be first child if or <desc> is present. bool is_on_path = false; for (auto child : text->childList(false)) { - if (dynamic_cast<SPTextPath *>(child)) is_on_path = true; + if (dynamic_cast<SPTextPath *>(child)) + is_on_path = true; } if (!is_on_path) { knotholder = new TextKnotHolder(desktop, item, nullptr); @@ -139,13 +156,16 @@ KnotHolder *createKnotHolder(SPItem *item, SPDesktop *desktop) SPFlowtext *flowtext = dynamic_cast<SPFlowtext *>(item); if (flowtext && flowtext->has_internal_frame()) { knotholder = new FlowtextKnotHolder(desktop, flowtext->get_frame(nullptr), nullptr); - } else if ((item->style->fill.isPaintserver() && dynamic_cast<SPPattern *>(item->style->getFillPaintServer())) || - (item->style->stroke.isPaintserver() && dynamic_cast<SPPattern *>(item->style->getStrokePaintServer()))) { + } else if ((item->style->fill.isPaintserver() && + dynamic_cast<SPPattern *>(item->style->getFillPaintServer())) || + (item->style->stroke.isPaintserver() && + dynamic_cast<SPPattern *>(item->style->getStrokePaintServer()))) { knotholder = new KnotHolder(desktop, item, nullptr); knotholder->add_pattern_knotholder(); } } - if (!knotholder) knotholder = new KnotHolder(desktop, item, nullptr); + if (!knotholder) + knotholder = new KnotHolder(desktop, item, nullptr); knotholder->add_filter_knotholder(); return knotholder; @@ -156,43 +176,44 @@ KnotHolder *createLPEKnotHolder(SPItem *item, SPDesktop *desktop) KnotHolder *knotholder = nullptr; SPLPEItem *lpe = dynamic_cast<SPLPEItem *>(item); - if (lpe && - lpe->getCurrentLPE() && - lpe->getCurrentLPE()->isVisible() && + if (lpe && lpe->getCurrentLPE() && lpe->getCurrentLPE()->isVisible() && lpe->getCurrentLPE()->providesKnotholder()) { knotholder = sp_lpe_knot_holder(lpe, desktop); } return knotholder; } -} +} // namespace UI } // namespace Inkscape /* SPRect */ /* handle for horizontal rounding radius */ -class RectKnotHolderEntityRX : public KnotHolderEntity { +class RectKnotHolderEntityRX : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_click(unsigned int state) override; }; /* handle for vertical rounding radius */ -class RectKnotHolderEntityRY : public KnotHolderEntity { +class RectKnotHolderEntityRY : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_click(unsigned int state) override; }; /* handle for width/height adjustment */ -class RectKnotHolderEntityWH : public KnotHolderEntity { +class RectKnotHolderEntityWH : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; protected: @@ -200,23 +221,24 @@ protected: }; /* handle for x/y adjustment */ -class RectKnotHolderEntityXY : public KnotHolderEntity { +class RectKnotHolderEntityXY : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; /* handle for position */ -class RectKnotHolderEntityCenter : public KnotHolderEntity { +class RectKnotHolderEntityCenter : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -Geom::Point -RectKnotHolderEntityRX::knot_get() const +Geom::Point RectKnotHolderEntityRX::knot_get() const { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); @@ -224,16 +246,19 @@ RectKnotHolderEntityRX::knot_get() const return Geom::Point(rect->x.computed + rect->width.computed - rect->rx.computed, rect->y.computed); } -void -RectKnotHolderEntityRX::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void RectKnotHolderEntityRX::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); - //In general we cannot just snap this radius to an arbitrary point, as we have only a single - //degree of freedom. For snapping to an arbitrary point we need two DOF. If we're going to snap - //the radius then we should have a constrained snap. snap_knot_position() is unconstrained - Geom::Point const s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(Geom::Point(rect->x.computed + rect->width.computed, rect->y.computed), Geom::Point(-1, 0)), state); + // In general we cannot just snap this radius to an arbitrary point, as we have only a single + // degree of freedom. For snapping to an arbitrary point we need two DOF. If we're going to snap + // the radius then we should have a constrained snap. snap_knot_position() is unconstrained + Geom::Point const s = snap_knot_position_constrained( + p, + Inkscape::Snapper::SnapConstraint(Geom::Point(rect->x.computed + rect->width.computed, rect->y.computed), + Geom::Point(-1, 0)), + state); if (state & GDK_CONTROL_MASK) { gdouble temp = MIN(rect->height.computed, rect->width.computed) / 2.0; @@ -247,8 +272,7 @@ RectKnotHolderEntityRX::knot_set(Geom::Point const &p, Geom::Point const &/*orig rect->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void -RectKnotHolderEntityRX::knot_click(unsigned int state) +void RectKnotHolderEntityRX::knot_click(unsigned int state) { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); @@ -261,11 +285,9 @@ RectKnotHolderEntityRX::knot_click(unsigned int state) /* Ctrl-click sets the vertical rounding to be the same as the horizontal */ rect->getRepr()->setAttribute("ry", rect->getRepr()->attribute("rx")); } - } -Geom::Point -RectKnotHolderEntityRY::knot_get() const +Geom::Point RectKnotHolderEntityRY::knot_get() const { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); @@ -273,16 +295,19 @@ RectKnotHolderEntityRY::knot_get() const return Geom::Point(rect->x.computed + rect->width.computed, rect->y.computed + rect->ry.computed); } -void -RectKnotHolderEntityRY::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void RectKnotHolderEntityRY::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); - //In general we cannot just snap this radius to an arbitrary point, as we have only a single - //degree of freedom. For snapping to an arbitrary point we need two DOF. If we're going to snap - //the radius then we should have a constrained snap. snap_knot_position() is unconstrained - Geom::Point const s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(Geom::Point(rect->x.computed + rect->width.computed, rect->y.computed), Geom::Point(0, 1)), state); + // In general we cannot just snap this radius to an arbitrary point, as we have only a single + // degree of freedom. For snapping to an arbitrary point we need two DOF. If we're going to snap + // the radius then we should have a constrained snap. snap_knot_position() is unconstrained + Geom::Point const s = snap_knot_position_constrained( + p, + Inkscape::Snapper::SnapConstraint(Geom::Point(rect->x.computed + rect->width.computed, rect->y.computed), + Geom::Point(0, 1)), + state); if (state & GDK_CONTROL_MASK) { // When holding control then rx will be kept equal to ry, // resulting in a perfect circle (and not an ellipse) @@ -290,13 +315,10 @@ RectKnotHolderEntityRY::knot_set(Geom::Point const &p, Geom::Point const &/*orig rect->rx = rect->ry = CLAMP(s[Geom::Y] - rect->y.computed, 0.0, temp); } else { if (!rect->rx._set || rect->rx.computed == 0) { - rect->ry = CLAMP(s[Geom::Y] - rect->y.computed, - 0.0, - MIN(rect->height.computed / 2.0, rect->width.computed / 2.0)); + rect->ry = + CLAMP(s[Geom::Y] - rect->y.computed, 0.0, MIN(rect->height.computed / 2.0, rect->width.computed / 2.0)); } else { - rect->ry = CLAMP(s[Geom::Y] - rect->y.computed, - 0.0, - rect->height.computed / 2.0); + rect->ry = CLAMP(s[Geom::Y] - rect->y.computed, 0.0, rect->height.computed / 2.0); } } @@ -305,8 +327,7 @@ RectKnotHolderEntityRY::knot_set(Geom::Point const &p, Geom::Point const &/*orig rect->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void -RectKnotHolderEntityRY::knot_click(unsigned int state) +void RectKnotHolderEntityRY::knot_click(unsigned int state) { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); @@ -321,7 +342,7 @@ RectKnotHolderEntityRY::knot_click(unsigned int state) } } -#define SGN(x) ((x)>0?1:((x)<0?-1:0)) +#define SGN(x) ((x) > 0 ? 1 : ((x) < 0 ? -1 : 0)) static void sp_rect_clamp_radii(SPRect *rect) { @@ -334,8 +355,7 @@ static void sp_rect_clamp_radii(SPRect *rect) } } -Geom::Point -RectKnotHolderEntityWH::knot_get() const +Geom::Point RectKnotHolderEntityWH::knot_get() const { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); @@ -343,8 +363,7 @@ RectKnotHolderEntityWH::knot_get() const return Geom::Point(rect->x.computed + rect->width.computed, rect->y.computed + rect->height.computed); } -void -RectKnotHolderEntityWH::set_internal(Geom::Point const &p, Geom::Point const &origin, unsigned int state) +void RectKnotHolderEntityWH::set_internal(Geom::Point const &p, Geom::Point const &origin, unsigned int state) { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); @@ -356,7 +375,7 @@ RectKnotHolderEntityWH::set_internal(Geom::Point const &p, Geom::Point const &or gdouble const w_orig = (origin[Geom::X] - rect->x.computed); gdouble const h_orig = (origin[Geom::Y] - rect->y.computed); - //original ratio + // original ratio gdouble ratio = (w_orig / h_orig); // mouse displacement since drag started @@ -367,42 +386,45 @@ RectKnotHolderEntityWH::set_internal(Geom::Point const &p, Geom::Point const &or if (fabs(minx) > fabs(miny)) { // snap to horizontal or diagonal - if (minx != 0 && fabs(miny/minx) > 0.5 * 1/ratio && (SGN(minx) == SGN(miny))) { + if (minx != 0 && fabs(miny / minx) > 0.5 * 1 / ratio && (SGN(minx) == SGN(miny))) { // closer to the diagonal and in same-sign quarters, change both using ratio - s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-ratio, -1)), state); + s = snap_knot_position_constrained( + p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-ratio, -1)), state); minx = s[Geom::X] - origin[Geom::X]; // Dead assignment: Value stored to 'miny' is never read - //miny = s[Geom::Y] - origin[Geom::Y]; + // miny = s[Geom::Y] - origin[Geom::Y]; rect->height = MAX(h_orig + minx / ratio, 0); } else { // closer to the horizontal, change only width, height is h_orig - s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-1, 0)), state); + s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-1, 0)), + state); minx = s[Geom::X] - origin[Geom::X]; // Dead assignment: Value stored to 'miny' is never read - //miny = s[Geom::Y] - origin[Geom::Y]; + // miny = s[Geom::Y] - origin[Geom::Y]; rect->height = MAX(h_orig, 0); } rect->width = MAX(w_orig + minx, 0); } else { // snap to vertical or diagonal - if (miny != 0 && fabs(minx/miny) > 0.5 * ratio && (SGN(minx) == SGN(miny))) { + if (miny != 0 && fabs(minx / miny) > 0.5 * ratio && (SGN(minx) == SGN(miny))) { // closer to the diagonal and in same-sign quarters, change both using ratio - s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-ratio, -1)), state); + s = snap_knot_position_constrained( + p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-ratio, -1)), state); // Dead assignment: Value stored to 'minx' is never read - //minx = s[Geom::X] - origin[Geom::X]; + // minx = s[Geom::X] - origin[Geom::X]; miny = s[Geom::Y] - origin[Geom::Y]; rect->width = MAX(w_orig + miny * ratio, 0); } else { // closer to the vertical, change only height, width is w_orig - s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(0, -1)), state); + s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(0, -1)), + state); // Dead assignment: Value stored to 'minx' is never read - //minx = s[Geom::X] - origin[Geom::X]; + // minx = s[Geom::X] - origin[Geom::X]; miny = s[Geom::Y] - origin[Geom::Y]; rect->width = MAX(w_orig, 0); } rect->height = MAX(h_orig + miny, 0); - } } else { @@ -417,15 +439,13 @@ RectKnotHolderEntityWH::set_internal(Geom::Point const &p, Geom::Point const &or rect->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void -RectKnotHolderEntityWH::knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) +void RectKnotHolderEntityWH::knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) { set_internal(p, origin, state); update_knot(); } -Geom::Point -RectKnotHolderEntityXY::knot_get() const +Geom::Point RectKnotHolderEntityXY::knot_get() const { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); @@ -433,8 +453,7 @@ RectKnotHolderEntityXY::knot_get() const return Geom::Point(rect->x.computed, rect->y.computed); } -void -RectKnotHolderEntityXY::knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) +void RectKnotHolderEntityXY::knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); @@ -455,25 +474,27 @@ RectKnotHolderEntityXY::knot_set(Geom::Point const &p, Geom::Point const &origin gdouble miny = p[Geom::Y] - origin[Geom::Y]; if (state & GDK_CONTROL_MASK) { - //original ratio + // original ratio gdouble ratio = (w_orig / h_orig); if (fabs(minx) > fabs(miny)) { // snap to horizontal or diagonal - if (minx != 0 && fabs(miny/minx) > 0.5 * 1/ratio && (SGN(minx) == SGN(miny))) { + if (minx != 0 && fabs(miny / minx) > 0.5 * 1 / ratio && (SGN(minx) == SGN(miny))) { // closer to the diagonal and in same-sign quarters, change both using ratio - s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-ratio, -1)), state); + s = snap_knot_position_constrained( + p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-ratio, -1)), state); minx = s[Geom::X] - origin[Geom::X]; // Dead assignment: Value stored to 'miny' is never read - //miny = s[Geom::Y] - origin[Geom::Y]; + // miny = s[Geom::Y] - origin[Geom::Y]; rect->y = MIN(origin[Geom::Y] + minx / ratio, opposite_y); rect->height = MAX(h_orig - minx / ratio, 0); } else { // closer to the horizontal, change only width, height is h_orig - s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-1, 0)), state); + s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-1, 0)), + state); minx = s[Geom::X] - origin[Geom::X]; // Dead assignment: Value stored to 'miny' is never read - //miny = s[Geom::Y] - origin[Geom::Y]; + // miny = s[Geom::Y] - origin[Geom::Y]; rect->y = MIN(origin[Geom::Y], opposite_y); rect->height = MAX(h_orig, 0); } @@ -481,19 +502,21 @@ RectKnotHolderEntityXY::knot_set(Geom::Point const &p, Geom::Point const &origin rect->width = MAX(w_orig - minx, 0); } else { // snap to vertical or diagonal - if (miny != 0 && fabs(minx/miny) > 0.5 *ratio && (SGN(minx) == SGN(miny))) { + if (miny != 0 && fabs(minx / miny) > 0.5 * ratio && (SGN(minx) == SGN(miny))) { // closer to the diagonal and in same-sign quarters, change both using ratio - s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-ratio, -1)), state); + s = snap_knot_position_constrained( + p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(-ratio, -1)), state); // Dead assignment: Value stored to 'minx' is never read - //minx = s[Geom::X] - origin[Geom::X]; + // minx = s[Geom::X] - origin[Geom::X]; miny = s[Geom::Y] - origin[Geom::Y]; rect->x = MIN(origin[Geom::X] + miny * ratio, opposite_x); rect->width = MAX(w_orig - miny * ratio, 0); } else { // closer to the vertical, change only height, width is w_orig - s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(0, -1)), state); + s = snap_knot_position_constrained(p, Inkscape::Snapper::SnapConstraint(p_handle, Geom::Point(0, -1)), + state); // Dead assignment: Value stored to 'minx' is never read - //minx = s[Geom::X] - origin[Geom::X]; + // minx = s[Geom::X] - origin[Geom::X]; miny = s[Geom::Y] - origin[Geom::Y]; rect->x = MIN(origin[Geom::X], opposite_x); rect->width = MAX(w_orig, 0); @@ -521,8 +544,7 @@ RectKnotHolderEntityXY::knot_set(Geom::Point const &p, Geom::Point const &origin rect->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -Geom::Point -RectKnotHolderEntityCenter::knot_get() const +Geom::Point RectKnotHolderEntityCenter::knot_get() const { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); @@ -530,8 +552,7 @@ RectKnotHolderEntityCenter::knot_get() const return Geom::Point(rect->x.computed + (rect->width.computed / 2.), rect->y.computed + (rect->height.computed / 2.)); } -void -RectKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void RectKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPRect *rect = dynamic_cast<SPRect *>(item); g_assert(rect != nullptr); @@ -547,8 +568,8 @@ RectKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const &/* rect->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -RectKnotHolder::RectKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) : - KnotHolder(desktop, item, relhandler) +RectKnotHolder::RectKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) + : KnotHolder(desktop, item, relhandler) { RectKnotHolderEntityRX *entity_rx = new RectKnotHolderEntityRX(); RectKnotHolderEntityRY *entity_ry = new RectKnotHolderEntityRY(); @@ -576,8 +597,7 @@ RectKnotHolder::RectKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderRel "to lock ratio or stretch in one dimension only"), SP_KNOT_SHAPE_SQUARE, SP_KNOT_MODE_XOR); - entity_center->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, - _("Drag to move the rectangle"), + entity_center->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, _("Drag to move the rectangle"), SP_KNOT_SHAPE_CROSS); entity.push_back(entity_rx); @@ -592,7 +612,8 @@ RectKnotHolder::RectKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderRel /* Box3D (= the new 3D box structure) */ -class Box3DKnotHolderEntity : public KnotHolderEntity { +class Box3DKnotHolderEntity : public KnotHolderEntity +{ public: Geom::Point knot_get() const override = 0; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override = 0; @@ -601,8 +622,7 @@ public: void knot_set_generic(SPItem *item, unsigned int knot_id, Geom::Point const &p, unsigned int state); }; -Geom::Point -Box3DKnotHolderEntity::knot_get_generic(SPItem *item, unsigned int knot_id) const +Geom::Point Box3DKnotHolderEntity::knot_get_generic(SPItem *item, unsigned int knot_id) const { SPBox3D *box = dynamic_cast<SPBox3D *>(item); if (box) { @@ -612,15 +632,15 @@ Box3DKnotHolderEntity::knot_get_generic(SPItem *item, unsigned int knot_id) cons } } -void -Box3DKnotHolderEntity::knot_set_generic(SPItem *item, unsigned int knot_id, Geom::Point const &new_pos, unsigned int state) +void Box3DKnotHolderEntity::knot_set_generic(SPItem *item, unsigned int knot_id, Geom::Point const &new_pos, + unsigned int state) { Geom::Point const s = snap_knot_position(new_pos, state); g_assert(item != nullptr); SPBox3D *box = dynamic_cast<SPBox3D *>(item); g_assert(box != nullptr); - Geom::Affine const i2dt (item->i2dt_affine ()); + Geom::Affine const i2dt(item->i2dt_affine()); Box3D::Axis movement; if ((knot_id < 4) != (state & GDK_SHIFT_MASK)) { @@ -629,124 +649,124 @@ Box3DKnotHolderEntity::knot_set_generic(SPItem *item, unsigned int knot_id, Geom movement = Box3D::Z; } - box->set_corner (knot_id, s * i2dt, movement, (state & GDK_CONTROL_MASK)); + box->set_corner(knot_id, s * i2dt, movement, (state & GDK_CONTROL_MASK)); box->set_z_orders(); box->position_set(); } -class Box3DKnotHolderEntity0 : public Box3DKnotHolderEntity { +class Box3DKnotHolderEntity0 : public Box3DKnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class Box3DKnotHolderEntity1 : public Box3DKnotHolderEntity { +class Box3DKnotHolderEntity1 : public Box3DKnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class Box3DKnotHolderEntity2 : public Box3DKnotHolderEntity { +class Box3DKnotHolderEntity2 : public Box3DKnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class Box3DKnotHolderEntity3 : public Box3DKnotHolderEntity { +class Box3DKnotHolderEntity3 : public Box3DKnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class Box3DKnotHolderEntity4 : public Box3DKnotHolderEntity { +class Box3DKnotHolderEntity4 : public Box3DKnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class Box3DKnotHolderEntity5 : public Box3DKnotHolderEntity { +class Box3DKnotHolderEntity5 : public Box3DKnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class Box3DKnotHolderEntity6 : public Box3DKnotHolderEntity { +class Box3DKnotHolderEntity6 : public Box3DKnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class Box3DKnotHolderEntity7 : public Box3DKnotHolderEntity { +class Box3DKnotHolderEntity7 : public Box3DKnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class Box3DKnotHolderEntityCenter : public KnotHolderEntity { +class Box3DKnotHolderEntityCenter : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -Geom::Point -Box3DKnotHolderEntity0::knot_get() const +Geom::Point Box3DKnotHolderEntity0::knot_get() const { return knot_get_generic(item, 0); } -Geom::Point -Box3DKnotHolderEntity1::knot_get() const +Geom::Point Box3DKnotHolderEntity1::knot_get() const { return knot_get_generic(item, 1); } -Geom::Point -Box3DKnotHolderEntity2::knot_get() const +Geom::Point Box3DKnotHolderEntity2::knot_get() const { return knot_get_generic(item, 2); } -Geom::Point -Box3DKnotHolderEntity3::knot_get() const +Geom::Point Box3DKnotHolderEntity3::knot_get() const { return knot_get_generic(item, 3); } -Geom::Point -Box3DKnotHolderEntity4::knot_get() const +Geom::Point Box3DKnotHolderEntity4::knot_get() const { return knot_get_generic(item, 4); } -Geom::Point -Box3DKnotHolderEntity5::knot_get() const +Geom::Point Box3DKnotHolderEntity5::knot_get() const { return knot_get_generic(item, 5); } -Geom::Point -Box3DKnotHolderEntity6::knot_get() const +Geom::Point Box3DKnotHolderEntity6::knot_get() const { return knot_get_generic(item, 6); } -Geom::Point -Box3DKnotHolderEntity7::knot_get() const +Geom::Point Box3DKnotHolderEntity7::knot_get() const { return knot_get_generic(item, 7); } -Geom::Point -Box3DKnotHolderEntityCenter::knot_get() const +Geom::Point Box3DKnotHolderEntityCenter::knot_get() const { SPBox3D *box = dynamic_cast<SPBox3D *>(item); if (box) { @@ -756,62 +776,53 @@ Box3DKnotHolderEntityCenter::knot_get() const } } -void -Box3DKnotHolderEntity0::knot_set(Geom::Point const &new_pos, Geom::Point const &/*origin*/, unsigned int state) +void Box3DKnotHolderEntity0::knot_set(Geom::Point const &new_pos, Geom::Point const & /*origin*/, unsigned int state) { knot_set_generic(item, 0, new_pos, state); } -void -Box3DKnotHolderEntity1::knot_set(Geom::Point const &new_pos, Geom::Point const &/*origin*/, unsigned int state) +void Box3DKnotHolderEntity1::knot_set(Geom::Point const &new_pos, Geom::Point const & /*origin*/, unsigned int state) { knot_set_generic(item, 1, new_pos, state); } -void -Box3DKnotHolderEntity2::knot_set(Geom::Point const &new_pos, Geom::Point const &/*origin*/, unsigned int state) +void Box3DKnotHolderEntity2::knot_set(Geom::Point const &new_pos, Geom::Point const & /*origin*/, unsigned int state) { knot_set_generic(item, 2, new_pos, state); } -void -Box3DKnotHolderEntity3::knot_set(Geom::Point const &new_pos, Geom::Point const &/*origin*/, unsigned int state) +void Box3DKnotHolderEntity3::knot_set(Geom::Point const &new_pos, Geom::Point const & /*origin*/, unsigned int state) { knot_set_generic(item, 3, new_pos, state); } -void -Box3DKnotHolderEntity4::knot_set(Geom::Point const &new_pos, Geom::Point const &/*origin*/, unsigned int state) +void Box3DKnotHolderEntity4::knot_set(Geom::Point const &new_pos, Geom::Point const & /*origin*/, unsigned int state) { knot_set_generic(item, 4, new_pos, state); } -void -Box3DKnotHolderEntity5::knot_set(Geom::Point const &new_pos, Geom::Point const &/*origin*/, unsigned int state) +void Box3DKnotHolderEntity5::knot_set(Geom::Point const &new_pos, Geom::Point const & /*origin*/, unsigned int state) { knot_set_generic(item, 5, new_pos, state); } -void -Box3DKnotHolderEntity6::knot_set(Geom::Point const &new_pos, Geom::Point const &/*origin*/, unsigned int state) +void Box3DKnotHolderEntity6::knot_set(Geom::Point const &new_pos, Geom::Point const & /*origin*/, unsigned int state) { knot_set_generic(item, 6, new_pos, state); } -void -Box3DKnotHolderEntity7::knot_set(Geom::Point const &new_pos, Geom::Point const &/*origin*/, unsigned int state) +void Box3DKnotHolderEntity7::knot_set(Geom::Point const &new_pos, Geom::Point const & /*origin*/, unsigned int state) { knot_set_generic(item, 7, new_pos, state); } -void -Box3DKnotHolderEntityCenter::knot_set(Geom::Point const &new_pos, Geom::Point const &origin, unsigned int state) +void Box3DKnotHolderEntityCenter::knot_set(Geom::Point const &new_pos, Geom::Point const &origin, unsigned int state) { Geom::Point const s = snap_knot_position(new_pos, state); SPBox3D *box = dynamic_cast<SPBox3D *>(item); g_assert(box != nullptr); - Geom::Affine const i2dt (item->i2dt_affine ()); + Geom::Affine const i2dt(item->i2dt_affine()); box->set_center(s * i2dt, origin * i2dt, !(state & GDK_SHIFT_MASK) ? Box3D::XY : Box3D::Z, state & GDK_CONTROL_MASK); @@ -820,8 +831,8 @@ Box3DKnotHolderEntityCenter::knot_set(Geom::Point const &new_pos, Geom::Point co box->position_set(); } -Box3DKnotHolder::Box3DKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) : - KnotHolder(desktop, item, relhandler) +Box3DKnotHolder::Box3DKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) + : KnotHolder(desktop, item, relhandler) { Box3DKnotHolderEntity0 *entity_corner0 = new Box3DKnotHolderEntity0(); Box3DKnotHolderEntity1 *entity_corner1 = new Box3DKnotHolderEntity1(); @@ -850,23 +861,22 @@ Box3DKnotHolder::Box3DKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderR "with <b>Ctrl</b> to constrain to the directions of edges or diagonals")); entity_corner4->create(desktop, item, this, Inkscape::CTRL_TYPE_SHAPER, - _("Resize box along the Z axis; with <b>Shift</b> in X/Y direction; " - "with <b>Ctrl</b> to constrain to the directions of edges or diagonals")); + _("Resize box along the Z axis; with <b>Shift</b> in X/Y direction; " + "with <b>Ctrl</b> to constrain to the directions of edges or diagonals")); entity_corner5->create(desktop, item, this, Inkscape::CTRL_TYPE_SHAPER, - _("Resize box along the Z axis; with <b>Shift</b> in X/Y direction; " - "with <b>Ctrl</b> to constrain to the directions of edges or diagonals")); + _("Resize box along the Z axis; with <b>Shift</b> in X/Y direction; " + "with <b>Ctrl</b> to constrain to the directions of edges or diagonals")); entity_corner6->create(desktop, item, this, Inkscape::CTRL_TYPE_SHAPER, - _("Resize box along the Z axis; with <b>Shift</b> in X/Y direction; " - "with <b>Ctrl</b> to constrain to the directions of edges or diagonals")); + _("Resize box along the Z axis; with <b>Shift</b> in X/Y direction; " + "with <b>Ctrl</b> to constrain to the directions of edges or diagonals")); entity_corner7->create(desktop, item, this, Inkscape::CTRL_TYPE_SHAPER, - _("Resize box along the Z axis; with <b>Shift</b> in X/Y direction; " - "with <b>Ctrl</b> to constrain to the directions of edges or diagonals")); + _("Resize box along the Z axis; with <b>Shift</b> in X/Y direction; " + "with <b>Ctrl</b> to constrain to the directions of edges or diagonals")); - entity_center->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, - _("Move the box in perspective"), + entity_center->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, _("Move the box in perspective"), SP_KNOT_SHAPE_CROSS); entity.push_back(entity_corner0); @@ -885,42 +895,47 @@ Box3DKnotHolder::Box3DKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderR /* SPArc */ -class ArcKnotHolderEntityStart : public KnotHolderEntity { +class ArcKnotHolderEntityStart : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_click(unsigned int state) override; }; -class ArcKnotHolderEntityEnd : public KnotHolderEntity { +class ArcKnotHolderEntityEnd : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_click(unsigned int state) override; }; -class ArcKnotHolderEntityRX : public KnotHolderEntity { +class ArcKnotHolderEntityRX : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_click(unsigned int state) override; }; -class ArcKnotHolderEntityRY : public KnotHolderEntity { +class ArcKnotHolderEntityRY : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_click(unsigned int state) override; }; -class ArcKnotHolderEntityCenter : public KnotHolderEntity { +class ArcKnotHolderEntityCenter : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; @@ -930,8 +945,7 @@ public: * 0 : on the curves * -1 : outside */ -static gint -sp_genericellipse_side(SPGenericEllipse *ellipse, Geom::Point const &p) +static gint sp_genericellipse_side(SPGenericEllipse *ellipse, Geom::Point const &p) { gdouble dx = (p[Geom::X] - ellipse->cx.computed) / ellipse->rx.computed; gdouble dy = (p[Geom::Y] - ellipse->cy.computed) / ellipse->ry.computed; @@ -940,13 +954,14 @@ sp_genericellipse_side(SPGenericEllipse *ellipse, Geom::Point const &p) // We add a bit of a buffer, so there's a decent chance the user will // be able to adjust the arc without the closed status flipping between // open and closed during micro mouse movements. - if (s < 0.75) return 1; - if (s > 1.25) return -1; + if (s < 0.75) + return 1; + if (s > 1.25) + return -1; return 0; } -void -ArcKnotHolderEntityStart::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void ArcKnotHolderEntityStart::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { int snaps = Inkscape::Preferences::get()->getInt("/options/rotationsnapsperpi/value", 12); @@ -954,9 +969,9 @@ ArcKnotHolderEntityStart::knot_set(Geom::Point const &p, Geom::Point const &/*or g_assert(arc != nullptr); gint side = sp_genericellipse_side(arc, p); - if(side != 0) { arc->setArcType( (side == -1) ? - SP_GENERIC_ELLIPSE_ARC_TYPE_SLICE : - SP_GENERIC_ELLIPSE_ARC_TYPE_ARC); } + if (side != 0) { + arc->setArcType((side == -1) ? SP_GENERIC_ELLIPSE_ARC_TYPE_SLICE : SP_GENERIC_ELLIPSE_ARC_TYPE_ARC); + } Geom::Point delta = p - Geom::Point(arc->cx.computed, arc->cy.computed); Geom::Scale sc(arc->rx.computed, arc->ry.computed); @@ -965,8 +980,8 @@ ArcKnotHolderEntityStart::knot_set(Geom::Point const &p, Geom::Point const &/*or arc->start -= offset; if ((state & GDK_CONTROL_MASK) && snaps) { - double snaps_radian = M_PI/snaps; - arc->start = std::round(arc->start/snaps_radian) * snaps_radian; + double snaps_radian = M_PI / snaps; + arc->start = std::round(arc->start / snaps_radian) * snaps_radian; } if (state & GDK_SHIFT_MASK) { arc->end -= offset; @@ -976,8 +991,7 @@ ArcKnotHolderEntityStart::knot_set(Geom::Point const &p, Geom::Point const &/*or arc->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -Geom::Point -ArcKnotHolderEntityStart::knot_get() const +Geom::Point ArcKnotHolderEntityStart::knot_get() const { SPGenericEllipse const *ge = dynamic_cast<SPGenericEllipse const *>(item); g_assert(ge != nullptr); @@ -985,8 +999,7 @@ ArcKnotHolderEntityStart::knot_get() const return ge->getPointAtAngle(ge->start); } -void -ArcKnotHolderEntityStart::knot_click(unsigned int state) +void ArcKnotHolderEntityStart::knot_click(unsigned int state) { SPGenericEllipse *ge = dynamic_cast<SPGenericEllipse *>(item); g_assert(ge != nullptr); @@ -997,8 +1010,7 @@ ArcKnotHolderEntityStart::knot_click(unsigned int state) } } -void -ArcKnotHolderEntityEnd::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void ArcKnotHolderEntityEnd::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { int snaps = Inkscape::Preferences::get()->getInt("/options/rotationsnapsperpi/value", 12); @@ -1006,9 +1018,9 @@ ArcKnotHolderEntityEnd::knot_set(Geom::Point const &p, Geom::Point const &/*orig g_assert(arc != nullptr); gint side = sp_genericellipse_side(arc, p); - if(side != 0) { arc->setArcType( (side == -1) ? - SP_GENERIC_ELLIPSE_ARC_TYPE_SLICE : - SP_GENERIC_ELLIPSE_ARC_TYPE_ARC); } + if (side != 0) { + arc->setArcType((side == -1) ? SP_GENERIC_ELLIPSE_ARC_TYPE_SLICE : SP_GENERIC_ELLIPSE_ARC_TYPE_ARC); + } Geom::Point delta = p - Geom::Point(arc->cx.computed, arc->cy.computed); Geom::Scale sc(arc->rx.computed, arc->ry.computed); @@ -1017,8 +1029,8 @@ ArcKnotHolderEntityEnd::knot_set(Geom::Point const &p, Geom::Point const &/*orig arc->end -= offset; if ((state & GDK_CONTROL_MASK) && snaps) { - double snaps_radian = M_PI/snaps; - arc->end = std::round(arc->end/snaps_radian) * snaps_radian; + double snaps_radian = M_PI / snaps; + arc->end = std::round(arc->end / snaps_radian) * snaps_radian; } if (state & GDK_SHIFT_MASK) { arc->start -= offset; @@ -1028,8 +1040,7 @@ ArcKnotHolderEntityEnd::knot_set(Geom::Point const &p, Geom::Point const &/*orig arc->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -Geom::Point -ArcKnotHolderEntityEnd::knot_get() const +Geom::Point ArcKnotHolderEntityEnd::knot_get() const { SPGenericEllipse const *ge = dynamic_cast<SPGenericEllipse const *>(item); g_assert(ge != nullptr); @@ -1037,9 +1048,7 @@ ArcKnotHolderEntityEnd::knot_get() const return ge->getPointAtAngle(ge->end); } - -void -ArcKnotHolderEntityEnd::knot_click(unsigned int state) +void ArcKnotHolderEntityEnd::knot_click(unsigned int state) { SPGenericEllipse *ge = dynamic_cast<SPGenericEllipse *>(item); g_assert(ge != nullptr); @@ -1050,35 +1059,31 @@ ArcKnotHolderEntityEnd::knot_click(unsigned int state) } } - -void -ArcKnotHolderEntityRX::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void ArcKnotHolderEntityRX::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPGenericEllipse *ge = dynamic_cast<SPGenericEllipse *>(item); g_assert(ge != nullptr); Geom::Point const s = snap_knot_position(p, state); - ge->rx = fabs( ge->cx.computed - s[Geom::X] ); + ge->rx = fabs(ge->cx.computed - s[Geom::X]); - if ( state & GDK_CONTROL_MASK ) { + if (state & GDK_CONTROL_MASK) { ge->ry = ge->rx.computed; } item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -Geom::Point -ArcKnotHolderEntityRX::knot_get() const +Geom::Point ArcKnotHolderEntityRX::knot_get() const { SPGenericEllipse const *ge = dynamic_cast<SPGenericEllipse const *>(item); g_assert(ge != nullptr); - return (Geom::Point(ge->cx.computed, ge->cy.computed) - Geom::Point(ge->rx.computed, 0)); + return (Geom::Point(ge->cx.computed, ge->cy.computed) - Geom::Point(ge->rx.computed, 0)); } -void -ArcKnotHolderEntityRX::knot_click(unsigned int state) +void ArcKnotHolderEntityRX::knot_click(unsigned int state) { SPGenericEllipse *ge = dynamic_cast<SPGenericEllipse *>(item); g_assert(ge != nullptr); @@ -1089,34 +1094,31 @@ ArcKnotHolderEntityRX::knot_click(unsigned int state) } } -void -ArcKnotHolderEntityRY::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void ArcKnotHolderEntityRY::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPGenericEllipse *ge = dynamic_cast<SPGenericEllipse *>(item); g_assert(ge != nullptr); Geom::Point const s = snap_knot_position(p, state); - ge->ry = fabs( ge->cy.computed - s[Geom::Y] ); + ge->ry = fabs(ge->cy.computed - s[Geom::Y]); - if ( state & GDK_CONTROL_MASK ) { + if (state & GDK_CONTROL_MASK) { ge->rx = ge->ry.computed; } item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -Geom::Point -ArcKnotHolderEntityRY::knot_get() const +Geom::Point ArcKnotHolderEntityRY::knot_get() const { SPGenericEllipse const *ge = dynamic_cast<SPGenericEllipse *>(item); g_assert(ge != nullptr); - return (Geom::Point(ge->cx.computed, ge->cy.computed) - Geom::Point(0, ge->ry.computed)); + return (Geom::Point(ge->cx.computed, ge->cy.computed) - Geom::Point(0, ge->ry.computed)); } -void -ArcKnotHolderEntityRY::knot_click(unsigned int state) +void ArcKnotHolderEntityRY::knot_click(unsigned int state) { SPGenericEllipse *ge = dynamic_cast<SPGenericEllipse *>(item); g_assert(ge != nullptr); @@ -1127,8 +1129,7 @@ ArcKnotHolderEntityRY::knot_click(unsigned int state) } } -void -ArcKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void ArcKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPGenericEllipse *ge = dynamic_cast<SPGenericEllipse *>(item); g_assert(ge != nullptr); @@ -1141,8 +1142,7 @@ ArcKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const &/*o item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -Geom::Point -ArcKnotHolderEntityCenter::knot_get() const +Geom::Point ArcKnotHolderEntityCenter::knot_get() const { SPGenericEllipse const *ge = dynamic_cast<SPGenericEllipse *>(item); g_assert(ge != nullptr); @@ -1150,9 +1150,8 @@ ArcKnotHolderEntityCenter::knot_get() const return Geom::Point(ge->cx.computed, ge->cy.computed); } - -ArcKnotHolder::ArcKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) : - KnotHolder(desktop, item, relhandler) +ArcKnotHolder::ArcKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) + : KnotHolder(desktop, item, relhandler) { ArcKnotHolderEntityRX *entity_rx = new ArcKnotHolderEntityRX(); ArcKnotHolderEntityRY *entity_ry = new ArcKnotHolderEntityRY(); @@ -1161,12 +1160,12 @@ ArcKnotHolder::ArcKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderRelea ArcKnotHolderEntityCenter *entity_center = new ArcKnotHolderEntityCenter(); entity_rx->create(desktop, item, this, Inkscape::CTRL_TYPE_SIZER, - _("Adjust ellipse <b>width</b>, with <b>Ctrl</b> to make circle"), - SP_KNOT_SHAPE_SQUARE, SP_KNOT_MODE_XOR); + _("Adjust ellipse <b>width</b>, with <b>Ctrl</b> to make circle"), SP_KNOT_SHAPE_SQUARE, + SP_KNOT_MODE_XOR); entity_ry->create(desktop, item, this, Inkscape::CTRL_TYPE_SIZER, - _("Adjust ellipse <b>height</b>, with <b>Ctrl</b> to make circle"), - SP_KNOT_SHAPE_SQUARE, SP_KNOT_MODE_XOR); + _("Adjust ellipse <b>height</b>, with <b>Ctrl</b> to make circle"), SP_KNOT_SHAPE_SQUARE, + SP_KNOT_MODE_XOR); entity_start->create(desktop, item, this, Inkscape::CTRL_TYPE_ROTATE, _("Position the <b>start point</b> of the arc or segment; with <b>Shift</b> to move " @@ -1180,8 +1179,7 @@ ArcKnotHolder::ArcKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderRelea "ellipse for arc, <b>outside</b> for segment"), SP_KNOT_SHAPE_CIRCLE, SP_KNOT_MODE_XOR); - entity_center->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, - _("Drag to move the ellipse"), + entity_center->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, _("Drag to move the ellipse"), SP_KNOT_SHAPE_CROSS); entity.push_back(entity_rx); @@ -1196,31 +1194,33 @@ ArcKnotHolder::ArcKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderRelea /* SPStar */ -class StarKnotHolderEntity1 : public KnotHolderEntity { +class StarKnotHolderEntity1 : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_click(unsigned int state) override; }; -class StarKnotHolderEntity2 : public KnotHolderEntity { +class StarKnotHolderEntity2 : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_click(unsigned int state) override; }; -class StarKnotHolderEntityCenter : public KnotHolderEntity { +class StarKnotHolderEntityCenter : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -void -StarKnotHolderEntity1::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void StarKnotHolderEntity1::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPStar *star = dynamic_cast<SPStar *>(item); g_assert(star != nullptr); @@ -1233,21 +1233,20 @@ StarKnotHolderEntity1::knot_set(Geom::Point const &p, Geom::Point const &/*origi double darg1 = arg1 - star->arg[0]; if (state & GDK_MOD1_MASK) { - star->randomized = darg1/(star->arg[0] - star->arg[1]); + star->randomized = darg1 / (star->arg[0] - star->arg[1]); } else if (state & GDK_SHIFT_MASK) { - star->rounded = darg1/(star->arg[0] - star->arg[1]); + star->rounded = darg1 / (star->arg[0] - star->arg[1]); } else if (state & GDK_CONTROL_MASK) { - star->r[0] = L2(d); + star->r[0] = L2(d); } else { - star->r[0] = L2(d); - star->arg[0] = arg1; + star->r[0] = L2(d); + star->arg[0] = arg1; star->arg[1] += darg1; } star->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void -StarKnotHolderEntity2::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void StarKnotHolderEntity2::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPStar *star = dynamic_cast<SPStar *>(item); g_assert(star != nullptr); @@ -1261,23 +1260,21 @@ StarKnotHolderEntity2::knot_set(Geom::Point const &p, Geom::Point const &/*origi double darg1 = arg1 - star->arg[1]; if (state & GDK_MOD1_MASK) { - star->randomized = darg1/(star->arg[0] - star->arg[1]); + star->randomized = darg1 / (star->arg[0] - star->arg[1]); } else if (state & GDK_SHIFT_MASK) { - star->rounded = fabs(darg1/(star->arg[0] - star->arg[1])); + star->rounded = fabs(darg1 / (star->arg[0] - star->arg[1])); } else if (state & GDK_CONTROL_MASK) { - star->r[1] = L2(d); + star->r[1] = L2(d); star->arg[1] = star->arg[0] + M_PI / star->sides; - } - else { - star->r[1] = L2(d); + } else { + star->r[1] = L2(d); star->arg[1] = atan2(d); } star->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } -void -StarKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void StarKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPStar *star = dynamic_cast<SPStar *>(item); g_assert(star != nullptr); @@ -1287,8 +1284,7 @@ StarKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const &/* item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -Geom::Point -StarKnotHolderEntity1::knot_get() const +Geom::Point StarKnotHolderEntity1::knot_get() const { g_assert(item != nullptr); @@ -1296,11 +1292,9 @@ StarKnotHolderEntity1::knot_get() const g_assert(star != nullptr); return sp_star_get_xy(star, SP_STAR_POINT_KNOT1, 0); - } -Geom::Point -StarKnotHolderEntity2::knot_get() const +Geom::Point StarKnotHolderEntity2::knot_get() const { g_assert(item != nullptr); @@ -1310,8 +1304,7 @@ StarKnotHolderEntity2::knot_get() const return sp_star_get_xy(star, SP_STAR_POINT_KNOT2, 0); } -Geom::Point -StarKnotHolderEntityCenter::knot_get() const +Geom::Point StarKnotHolderEntityCenter::knot_get() const { g_assert(item != nullptr); @@ -1321,8 +1314,7 @@ StarKnotHolderEntityCenter::knot_get() const return star->center; } -static void -sp_star_knot_click(SPItem *item, unsigned int state) +static void sp_star_knot_click(SPItem *item, unsigned int state) { SPStar *star = dynamic_cast<SPStar *>(item); g_assert(star != nullptr); @@ -1339,20 +1331,18 @@ sp_star_knot_click(SPItem *item, unsigned int state) } } -void -StarKnotHolderEntity1::knot_click(unsigned int state) +void StarKnotHolderEntity1::knot_click(unsigned int state) { sp_star_knot_click(item, state); } -void -StarKnotHolderEntity2::knot_click(unsigned int state) +void StarKnotHolderEntity2::knot_click(unsigned int state) { sp_star_knot_click(item, state); } -StarKnotHolder::StarKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) : - KnotHolder(desktop, item, relhandler) +StarKnotHolder::StarKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) + : KnotHolder(desktop, item, relhandler) { SPStar *star = dynamic_cast<SPStar *>(item); g_assert(item != nullptr); @@ -1373,8 +1363,7 @@ StarKnotHolder::StarKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderRel } StarKnotHolderEntityCenter *entity_center = new StarKnotHolderEntityCenter(); - entity_center->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, - _("Drag to move the star"), + entity_center->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, _("Drag to move the star"), SP_KNOT_SHAPE_CROSS); entity.push_back(entity_center); @@ -1384,37 +1373,38 @@ StarKnotHolder::StarKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderRel /* SPSpiral */ -class SpiralKnotHolderEntityInner : public KnotHolderEntity { +class SpiralKnotHolderEntityInner : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_click(unsigned int state) override; }; -class SpiralKnotHolderEntityOuter : public KnotHolderEntity { +class SpiralKnotHolderEntityOuter : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -class SpiralKnotHolderEntityCenter : public KnotHolderEntity { +class SpiralKnotHolderEntityCenter : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; - /* * set attributes via inner (t=t0) knot point: * [default] increase/decrease inner point * [shift] increase/decrease inner and outer arg synchronizely * [control] constrain inner arg to round per PI/4 */ -void -SpiralKnotHolderEntityInner::knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) +void SpiralKnotHolderEntityInner::knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12); @@ -1422,35 +1412,33 @@ SpiralKnotHolderEntityInner::knot_set(Geom::Point const &p, Geom::Point const &o SPSpiral *spiral = dynamic_cast<SPSpiral *>(item); g_assert(spiral != nullptr); - gdouble dx = p[Geom::X] - spiral->cx; - gdouble dy = p[Geom::Y] - spiral->cy; + gdouble dx = p[Geom::X] - spiral->cx; + gdouble dy = p[Geom::Y] - spiral->cy; - gdouble moved_y = p[Geom::Y] - origin[Geom::Y]; + gdouble moved_y = p[Geom::Y] - origin[Geom::Y]; if (state & GDK_MOD1_MASK) { // adjust divergence by vertical drag, relative to rad if (spiral->rad > 0) { - double exp_delta = 0.1*moved_y/(spiral->rad); // arbitrary multiplier to slow it down + double exp_delta = 0.1 * moved_y / (spiral->rad); // arbitrary multiplier to slow it down spiral->exp += exp_delta; if (spiral->exp < 1e-3) spiral->exp = 1e-3; } } else { // roll/unroll from inside - gdouble arg_t0; + gdouble arg_t0; spiral->getPolar(spiral->t0, nullptr, &arg_t0); - gdouble arg_tmp = atan2(dy, dx) - arg_t0; - gdouble arg_t0_new = arg_tmp - floor((arg_tmp+M_PI)/(2.0*M_PI))*2.0*M_PI + arg_t0; - spiral->t0 = (arg_t0_new - spiral->arg) / (2.0*M_PI*spiral->revo); + gdouble arg_tmp = atan2(dy, dx) - arg_t0; + gdouble arg_t0_new = arg_tmp - floor((arg_tmp + M_PI) / (2.0 * M_PI)) * 2.0 * M_PI + arg_t0; + spiral->t0 = (arg_t0_new - spiral->arg) / (2.0 * M_PI * spiral->revo); /* round inner arg per PI/snaps, if CTRL is pressed */ - if ( ( state & GDK_CONTROL_MASK ) - && ( fabs(spiral->revo) > SP_EPSILON_2 ) - && ( snaps != 0 ) ) { - gdouble arg = 2.0*M_PI*spiral->revo*spiral->t0 + spiral->arg; - double snaps_radian = M_PI/snaps; - spiral->t0 = (std::round(arg/snaps_radian)*snaps_radian - spiral->arg)/(2.0*M_PI*spiral->revo); + if ((state & GDK_CONTROL_MASK) && (fabs(spiral->revo) > SP_EPSILON_2) && (snaps != 0)) { + gdouble arg = 2.0 * M_PI * spiral->revo * spiral->t0 + spiral->arg; + double snaps_radian = M_PI / snaps; + spiral->t0 = (std::round(arg / snaps_radian) * snaps_radian - spiral->arg) / (2.0 * M_PI * spiral->revo); } spiral->t0 = CLAMP(spiral->t0, 0.0, 0.999); @@ -1464,8 +1452,7 @@ SpiralKnotHolderEntityInner::knot_set(Geom::Point const &p, Geom::Point const &o * [default] increase/decrease revolution factor * [control] constrain inner arg to round per PI/4 */ -void -SpiralKnotHolderEntityOuter::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void SpiralKnotHolderEntityOuter::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12); @@ -1473,18 +1460,18 @@ SpiralKnotHolderEntityOuter::knot_set(Geom::Point const &p, Geom::Point const &/ SPSpiral *spiral = dynamic_cast<SPSpiral *>(item); g_assert(spiral != nullptr); - gdouble dx = p[Geom::X] - spiral->cx; - gdouble dy = p[Geom::Y] - spiral->cy; + gdouble dx = p[Geom::X] - spiral->cx; + gdouble dy = p[Geom::Y] - spiral->cy; if (state & GDK_SHIFT_MASK) { // rotate without roll/unroll - spiral->arg = atan2(dy, dx) - 2.0*M_PI*spiral->revo; + spiral->arg = atan2(dy, dx) - 2.0 * M_PI * spiral->revo; if (!(state & GDK_MOD1_MASK)) { // if alt not pressed, change also rad; otherwise it is locked spiral->rad = MAX(hypot(dx, dy), 0.001); } - if ( ( state & GDK_CONTROL_MASK ) && snaps ) { - double snaps_radian = M_PI/snaps; - spiral->arg = std::round(spiral->arg/snaps_radian) * snaps_radian; + if ((state & GDK_CONTROL_MASK) && snaps) { + double snaps_radian = M_PI / snaps; + spiral->arg = std::round(spiral->arg / snaps_radian) * snaps_radian; } } else { // roll/unroll // arg of the spiral outer end @@ -1493,7 +1480,7 @@ SpiralKnotHolderEntityOuter::knot_set(Geom::Point const &p, Geom::Point const &/ // its fractional part after the whole turns are subtracted static double _2PI = 2.0 * M_PI; - double arg_r = arg_1 - std::round(arg_1/_2PI) * _2PI; + double arg_r = arg_1 - std::round(arg_1 / _2PI) * _2PI; // arg of the mouse point relative to spiral center double mouse_angle = atan2(dy, dx); @@ -1501,9 +1488,9 @@ SpiralKnotHolderEntityOuter::knot_set(Geom::Point const &p, Geom::Point const &/ mouse_angle += _2PI; // snap if ctrl - if ( ( state & GDK_CONTROL_MASK ) && snaps ) { - double snaps_radian = M_PI/snaps; - mouse_angle = std::round(mouse_angle/snaps_radian) * snaps_radian; + if ((state & GDK_CONTROL_MASK) && snaps) { + double snaps_radian = M_PI / snaps; + mouse_angle = std::round(mouse_angle / snaps_radian) * snaps_radian; } // by how much we want to rotate the outer point @@ -1515,34 +1502,34 @@ SpiralKnotHolderEntityOuter::knot_set(Geom::Point const &p, Geom::Point const &/ // calculate the new rad; // the value of t corresponding to the angle arg_1 + diff: - double t_temp = ((arg_1 + diff) - spiral->arg)/(_2PI*spiral->revo); + double t_temp = ((arg_1 + diff) - spiral->arg) / (_2PI * spiral->revo); // the rad at that t: double rad_new = 0; if (t_temp > spiral->t0) spiral->getPolar(t_temp, &rad_new, nullptr); // change the revo (converting diff from radians to the number of turns) - spiral->revo += diff/(2*M_PI); + spiral->revo += diff / (2 * M_PI); if (spiral->revo < 1e-3) spiral->revo = 1e-3; // if alt not pressed and the values are sane, change the rad - if (!(state & GDK_MOD1_MASK) && rad_new > 1e-3 && rad_new/spiral->rad < 2) { + if (!(state & GDK_MOD1_MASK) && rad_new > 1e-3 && rad_new / spiral->rad < 2) { // adjust t0 too so that the inner point stays unmoved double r0; spiral->getPolar(spiral->t0, &r0, nullptr); spiral->rad = rad_new; - spiral->t0 = pow(r0 / spiral->rad, 1.0/spiral->exp); + spiral->t0 = pow(r0 / spiral->rad, 1.0 / spiral->exp); } - if (!std::isfinite(spiral->t0)) spiral->t0 = 0.0; + if (!std::isfinite(spiral->t0)) + spiral->t0 = 0.0; spiral->t0 = CLAMP(spiral->t0, 0.0, 0.999); } spiral->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -void -SpiralKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void SpiralKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPSpiral *spiral = dynamic_cast<SPSpiral *>(item); g_assert(spiral != nullptr); @@ -1555,8 +1542,7 @@ SpiralKnotHolderEntityCenter::knot_set(Geom::Point const &p, Geom::Point const & spiral->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } -Geom::Point -SpiralKnotHolderEntityInner::knot_get() const +Geom::Point SpiralKnotHolderEntityInner::knot_get() const { SPSpiral const *spiral = dynamic_cast<SPSpiral const *>(item); g_assert(spiral != nullptr); @@ -1564,8 +1550,7 @@ SpiralKnotHolderEntityInner::knot_get() const return spiral->getXY(spiral->t0); } -Geom::Point -SpiralKnotHolderEntityOuter::knot_get() const +Geom::Point SpiralKnotHolderEntityOuter::knot_get() const { SPSpiral const *spiral = dynamic_cast<SPSpiral const *>(item); g_assert(spiral != nullptr); @@ -1573,8 +1558,7 @@ SpiralKnotHolderEntityOuter::knot_get() const return spiral->getXY(1.0); } -Geom::Point -SpiralKnotHolderEntityCenter::knot_get() const +Geom::Point SpiralKnotHolderEntityCenter::knot_get() const { SPSpiral const *spiral = dynamic_cast<SPSpiral const *>(item); g_assert(spiral != nullptr); @@ -1582,8 +1566,7 @@ SpiralKnotHolderEntityCenter::knot_get() const return Geom::Point(spiral->cx, spiral->cy); } -void -SpiralKnotHolderEntityInner::knot_click(unsigned int state) +void SpiralKnotHolderEntityInner::knot_click(unsigned int state) { SPSpiral *spiral = dynamic_cast<SPSpiral *>(item); g_assert(spiral != nullptr); @@ -1597,8 +1580,8 @@ SpiralKnotHolderEntityInner::knot_click(unsigned int state) } } -SpiralKnotHolder::SpiralKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) : - KnotHolder(desktop, item, relhandler) +SpiralKnotHolder::SpiralKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) + : KnotHolder(desktop, item, relhandler) { SpiralKnotHolderEntityCenter *entity_center = new SpiralKnotHolderEntityCenter(); SpiralKnotHolderEntityInner *entity_inner = new SpiralKnotHolderEntityInner(); @@ -1616,8 +1599,7 @@ SpiralKnotHolder::SpiralKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolde // // So, create entity_inner AFTER entity_center; this ensures that // entity_inner gets rendered ON TOP. - entity_center->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, - _("Drag to move the spiral"), + entity_center->create(desktop, item, this, Inkscape::CTRL_TYPE_POINT, _("Drag to move the spiral"), SP_KNOT_SHAPE_CROSS); entity_inner->create(desktop, item, this, Inkscape::CTRL_TYPE_SHAPER, @@ -1638,15 +1620,15 @@ SpiralKnotHolder::SpiralKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolde /* SPOffset */ -class OffsetKnotHolderEntity : public KnotHolderEntity { +class OffsetKnotHolderEntity : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -void -OffsetKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void OffsetKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPOffset *offset = dynamic_cast<SPOffset *>(item); g_assert(offset != nullptr); @@ -1660,50 +1642,46 @@ OffsetKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const &/*orig offset->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } - -Geom::Point -OffsetKnotHolderEntity::knot_get() const +Geom::Point OffsetKnotHolderEntity::knot_get() const { SPOffset const *offset = dynamic_cast<SPOffset const *>(item); g_assert(offset != nullptr); Geom::Point np; - sp_offset_top_point(offset,&np); + sp_offset_top_point(offset, &np); return np; } -OffsetKnotHolder::OffsetKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) : - KnotHolder(desktop, item, relhandler) +OffsetKnotHolder::OffsetKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) + : KnotHolder(desktop, item, relhandler) { OffsetKnotHolderEntity *entity_offset = new OffsetKnotHolderEntity(); - entity_offset->create(desktop, item, this, Inkscape::CTRL_TYPE_SHAPER, - _("Adjust the <b>offset distance</b>")); + entity_offset->create(desktop, item, this, Inkscape::CTRL_TYPE_SHAPER, _("Adjust the <b>offset distance</b>")); entity.push_back(entity_offset); add_pattern_knotholder(); add_hatch_knotholder(); } - /* SPText */ -class TextKnotHolderEntityInlineSize : public KnotHolderEntity { +class TextKnotHolderEntityInlineSize : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_click(unsigned int state) override; }; -Geom::Point -TextKnotHolderEntityInlineSize::knot_get() const +Geom::Point TextKnotHolderEntityInlineSize::knot_get() const { SPText *text = dynamic_cast<SPText *>(item); g_assert(text != nullptr); - SPStyle* style = text->style; + SPStyle *style = text->style; double inline_size = style->inline_size.computed; - unsigned mode = style->writing_mode.computed; - unsigned anchor = style->text_anchor.computed; + unsigned mode = style->writing_mode.computed; + unsigned anchor = style->text_anchor.computed; unsigned direction = style->direction.computed; Geom::Point p(text->attributes.firstXY()); @@ -1712,56 +1690,54 @@ TextKnotHolderEntityInlineSize::knot_get() const // SVG 2 'inline-size' // Keep handle at end of text line. - if (mode == SP_CSS_WRITING_MODE_LR_TB || - mode == SP_CSS_WRITING_MODE_RL_TB) { + if (mode == SP_CSS_WRITING_MODE_LR_TB || mode == SP_CSS_WRITING_MODE_RL_TB) { // horizontal - if ( (direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_START ) || - (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_END) ) { - p *= Geom::Translate (inline_size, 0); - } else if ( direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { - p *= Geom::Translate (inline_size/2.0, 0 ); - } else if ( direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { - p *= Geom::Translate (-inline_size/2.0, 0 ); - } else if ( (direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_END ) || - (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_START) ) { - p *= Geom::Translate (-inline_size, 0); + if ((direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_START) || + (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_END)) { + p *= Geom::Translate(inline_size, 0); + } else if (direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { + p *= Geom::Translate(inline_size / 2.0, 0); + } else if (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { + p *= Geom::Translate(-inline_size / 2.0, 0); + } else if ((direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_END) || + (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_START)) { + p *= Geom::Translate(-inline_size, 0); } } else { // vertical if (anchor == SP_CSS_TEXT_ANCHOR_START) { - p *= Geom::Translate (0, inline_size); + p *= Geom::Translate(0, inline_size); } else if (anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { - p *= Geom::Translate (0, inline_size/2.0); + p *= Geom::Translate(0, inline_size / 2.0); } else if (anchor == SP_CSS_TEXT_ANCHOR_END) { - p *= Geom::Translate (0, -inline_size); + p *= Geom::Translate(0, -inline_size); } } } else { // Normal single line text. Geom::OptRect bbox = text->geometricBounds(); // Check if this is best. if (bbox) { - if (mode == SP_CSS_WRITING_MODE_LR_TB || - mode == SP_CSS_WRITING_MODE_RL_TB) { + if (mode == SP_CSS_WRITING_MODE_LR_TB || mode == SP_CSS_WRITING_MODE_RL_TB) { // horizontal - if ( (direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_START ) || - (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_END) ) { - p *= Geom::Translate ((*bbox).width(), 0); - } else if ( direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { - p *= Geom::Translate ((*bbox).width()/2, 0); - } else if ( direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { - p *= Geom::Translate (-(*bbox).width()/2, 0); - } else if ( (direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_END ) || - (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_START) ) { - p *= Geom::Translate (-(*bbox).width(), 0); + if ((direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_START) || + (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_END)) { + p *= Geom::Translate((*bbox).width(), 0); + } else if (direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { + p *= Geom::Translate((*bbox).width() / 2, 0); + } else if (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { + p *= Geom::Translate(-(*bbox).width() / 2, 0); + } else if ((direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_END) || + (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_START)) { + p *= Geom::Translate(-(*bbox).width(), 0); } } else { // vertical if (anchor == SP_CSS_TEXT_ANCHOR_START) { - p *= Geom::Translate (0, (*bbox).height()); + p *= Geom::Translate(0, (*bbox).height()); } else if (anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { - p *= Geom::Translate (0, (*bbox).height()/2); + p *= Geom::Translate(0, (*bbox).height() / 2); } else if (anchor == SP_CSS_TEXT_ANCHOR_END) { - p *= Geom::Translate (0, -(*bbox).height()); + p *= Geom::Translate(0, -(*bbox).height()); } p += Geom::Point((*bbox).width(), 0); // Keep on right side } @@ -1772,32 +1748,30 @@ TextKnotHolderEntityInlineSize::knot_get() const } // Conversion from Inkscape SVG 1.1 to SVG 2 'inline-size'. -void -TextKnotHolderEntityInlineSize::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void TextKnotHolderEntityInlineSize::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { SPText *text = dynamic_cast<SPText *>(item); g_assert(text != nullptr); - SPStyle* style = text->style; - unsigned mode = style->writing_mode.computed; - unsigned anchor = style->text_anchor.computed; + SPStyle *style = text->style; + unsigned mode = style->writing_mode.computed; + unsigned anchor = style->text_anchor.computed; unsigned direction = style->direction.computed; Geom::Point const s = snap_knot_position(p, state); Geom::Point delta = s - text->attributes.firstXY(); double size = 0.0; - if (mode == SP_CSS_WRITING_MODE_LR_TB || - mode == SP_CSS_WRITING_MODE_RL_TB) { + if (mode == SP_CSS_WRITING_MODE_LR_TB || mode == SP_CSS_WRITING_MODE_RL_TB) { // horizontal size = delta[Geom::X]; - if ( (direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_START ) || - (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_END) ) { + if ((direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_START) || + (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_END)) { // Do nothing - } else if ( (direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_END ) || - (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_START) ) { + } else if ((direction == SP_CSS_DIRECTION_LTR && anchor == SP_CSS_TEXT_ANCHOR_END) || + (direction == SP_CSS_DIRECTION_RTL && anchor == SP_CSS_TEXT_ANCHOR_START)) { size = -size; - } else if ( anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { + } else if (anchor == SP_CSS_TEXT_ANCHOR_MIDDLE) { size = 2.0 * abs(size); } else { std::cerr << "TextKnotHolderEntityInlinSize: Should not be reached!" << std::endl; @@ -1837,32 +1811,30 @@ TextKnotHolderEntityInlineSize::knot_set(Geom::Point const &p, Geom::Point const } // Conversion from SVG 2 'inline-size' to Inkscape's SVG 1.1. -void -TextKnotHolderEntityInlineSize::knot_click(unsigned int state) +void TextKnotHolderEntityInlineSize::knot_click(unsigned int state) { SPText *text = dynamic_cast<SPText *>(item); g_assert(text != nullptr); if (state & GDK_CONTROL_MASK) { - text->style->inline_size.clear(); - text->remove_svg11_fallback(); // Else 'x' and 'y' will be interpreted as absolute positions. - text->newline_to_sodipodi(); // Convert '\n' to tspans with sodipodi:role="line". + text->remove_svg11_fallback(); // Else 'x' and 'y' will be interpreted as absolute positions. + text->newline_to_sodipodi(); // Convert '\n' to tspans with sodipodi:role="line". text->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); text->updateRepr(); } } -class TextKnotHolderEntityShapeInside : public KnotHolderEntity { +class TextKnotHolderEntityShapeInside : public KnotHolderEntity +{ public: Geom::Point knot_get() const override; - void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override {}; + void knot_ungrabbed(Geom::Point const &p, Geom::Point const &origin, guint state) override{}; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -Geom::Point -TextKnotHolderEntityShapeInside::knot_get() const +Geom::Point TextKnotHolderEntityShapeInside::knot_get() const { // SVG 2 'shape-inside'. We only get here if there is a rectangle shape. SPText *text = dynamic_cast<SPText *>(item); @@ -1881,8 +1853,7 @@ TextKnotHolderEntityShapeInside::knot_get() const return p; } -void -TextKnotHolderEntityShapeInside::knot_set(Geom::Point const &p, Geom::Point const &/*origin*/, unsigned int state) +void TextKnotHolderEntityShapeInside::knot_set(Geom::Point const &p, Geom::Point const & /*origin*/, unsigned int state) { // Text in a shape: rectangle SPText *text = dynamic_cast<SPText *>(item); @@ -1891,21 +1862,21 @@ TextKnotHolderEntityShapeInside::knot_set(Geom::Point const &p, Geom::Point cons Geom::Point const s = snap_knot_position(p, state); - Inkscape::XML::Node* rectangle = text->get_first_rectangle(); + Inkscape::XML::Node *rectangle = text->get_first_rectangle(); double x = 0.0; double y = 0.0; - sp_repr_get_double (rectangle, "x", &x); - sp_repr_get_double (rectangle, "y", &y); - double width = s[Geom::X] - x; + sp_repr_get_double(rectangle, "x", &x); + sp_repr_get_double(rectangle, "y", &y); + double width = s[Geom::X] - x; double height = s[Geom::Y] - y; - sp_repr_set_svg_double (rectangle, "width", width); - sp_repr_set_svg_double (rectangle, "height", height); + sp_repr_set_svg_double(rectangle, "width", width); + sp_repr_set_svg_double(rectangle, "height", height); text->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); text->updateRepr(); } -TextKnotHolder::TextKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) : - KnotHolder(desktop, item, relhandler) +TextKnotHolder::TextKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) + : KnotHolder(desktop, item, relhandler) { SPText *text = dynamic_cast<SPText *>(item); g_assert(text != nullptr); @@ -1915,8 +1886,8 @@ TextKnotHolder::TextKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderRel TextKnotHolderEntityShapeInside *entity_shapeinside = new TextKnotHolderEntityShapeInside(); entity_shapeinside->create(desktop, item, this, Inkscape::CTRL_TYPE_SHAPER, - _("Adjust the <b>rectangular</b> region of the text."), - SP_KNOT_SHAPE_DIAMOND, SP_KNOT_MODE_XOR); + _("Adjust the <b>rectangular</b> region of the text."), SP_KNOT_SHAPE_DIAMOND, + SP_KNOT_MODE_XOR); entity.push_back(entity_shapeinside); @@ -1925,25 +1896,24 @@ TextKnotHolder::TextKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderRel TextKnotHolderEntityInlineSize *entity_inlinesize = new TextKnotHolderEntityInlineSize(); entity_inlinesize->create(desktop, item, this, Inkscape::CTRL_TYPE_SHAPER, - _("Adjust the <b>inline size</b> (line length) of the text."), - SP_KNOT_SHAPE_DIAMOND, SP_KNOT_MODE_XOR); + _("Adjust the <b>inline size</b> (line length) of the text."), SP_KNOT_SHAPE_DIAMOND, + SP_KNOT_MODE_XOR); entity.push_back(entity_inlinesize); } } - // TODO: this is derived from RectKnotHolderEntityWH because it used the same static function // set_internal as the latter before KnotHolderEntity was C++ified. Check whether this also makes // sense logically. -class FlowtextKnotHolderEntity : public RectKnotHolderEntityWH { +class FlowtextKnotHolderEntity : public RectKnotHolderEntityWH +{ public: Geom::Point knot_get() const override; void knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) override; }; -Geom::Point -FlowtextKnotHolderEntity::knot_get() const +Geom::Point FlowtextKnotHolderEntity::knot_get() const { SPRect const *rect = dynamic_cast<SPRect const *>(item); g_assert(rect != nullptr); @@ -1951,14 +1921,13 @@ FlowtextKnotHolderEntity::knot_get() const return Geom::Point(rect->x.computed + rect->width.computed, rect->y.computed + rect->height.computed); } -void -FlowtextKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) +void FlowtextKnotHolderEntity::knot_set(Geom::Point const &p, Geom::Point const &origin, unsigned int state) { set_internal(p, origin, state); } -FlowtextKnotHolder::FlowtextKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) : - KnotHolder(desktop, item, relhandler) +FlowtextKnotHolder::FlowtextKnotHolder(SPDesktop *desktop, SPItem *item, SPKnotHolderReleasedFunc relhandler) + : KnotHolder(desktop, item, relhandler) { g_assert(item != nullptr); diff --git a/src/ui/shape-editor.cpp b/src/ui/shape-editor.cpp index 9125bbc78f7a2c9ab28a0c1e40b4027865355e53..1b0dce31bf9139cec9c3e62d9a7c3c83fc6fcc9f 100644 --- a/src/ui/shape-editor.cpp +++ b/src/ui/shape-editor.cpp @@ -12,16 +12,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/shape-editor.h" + #include "desktop.h" #include "document.h" #include "knotholder.h" #include "live_effects/effect.h" #include "object/sp-lpe-item.h" - -#include "ui/shape-editor.h" #include "xml/node-event-vector.h" - namespace Inkscape { namespace UI { @@ -30,21 +29,22 @@ KnotHolder *createLPEKnotHolder(SPItem *item, SPDesktop *desktop); bool ShapeEditor::_blockSetItem = false; -ShapeEditor::ShapeEditor(SPDesktop *dt, Geom::Affine edit_transform) : - desktop(dt), - knotholder(nullptr), - lpeknotholder(nullptr), - knotholder_listener_attached_for(nullptr), - lpeknotholder_listener_attached_for(nullptr), - _edit_transform(edit_transform) -{ -} +ShapeEditor::ShapeEditor(SPDesktop *dt, Geom::Affine edit_transform) + : desktop(dt) + , knotholder(nullptr) + , lpeknotholder(nullptr) + , knotholder_listener_attached_for(nullptr) + , lpeknotholder_listener_attached_for(nullptr) + , _edit_transform(edit_transform) +{} -ShapeEditor::~ShapeEditor() { +ShapeEditor::~ShapeEditor() +{ unset_item(); } -void ShapeEditor::unset_item(bool keep_knotholder) { +void ShapeEditor::unset_item(bool keep_knotholder) +{ if (this->knotholder) { Inkscape::XML::Node *old_repr = this->knotholder->repr; if (old_repr && old_repr == knotholder_listener_attached_for) { @@ -73,22 +73,27 @@ void ShapeEditor::unset_item(bool keep_knotholder) { } } -bool ShapeEditor::has_knotholder() { +bool ShapeEditor::has_knotholder() +{ return this->knotholder != nullptr || this->lpeknotholder != nullptr; } -void ShapeEditor::update_knotholder() { +void ShapeEditor::update_knotholder() +{ if (this->knotholder) this->knotholder->update_knots(); if (this->lpeknotholder) this->lpeknotholder->update_knots(); } -bool ShapeEditor::has_local_change() { - return (this->knotholder && this->knotholder->local_change != 0) || (this->lpeknotholder && this->lpeknotholder->local_change != 0); +bool ShapeEditor::has_local_change() +{ + return (this->knotholder && this->knotholder->local_change != 0) || + (this->lpeknotholder && this->lpeknotholder->local_change != 0); } -void ShapeEditor::decrement_local_change() { +void ShapeEditor::decrement_local_change() +{ if (this->knotholder) { this->knotholder->local_change = FALSE; } @@ -97,14 +102,14 @@ void ShapeEditor::decrement_local_change() { } } -void ShapeEditor::event_attr_changed(Inkscape::XML::Node * node, gchar const *name, gchar const *, gchar const *, bool, void *data) +void ShapeEditor::event_attr_changed(Inkscape::XML::Node *node, gchar const *name, gchar const *, gchar const *, bool, + void *data) { g_assert(data); ShapeEditor *sh = static_cast<ShapeEditor *>(data); bool changed_kh = false; - if (sh->has_knotholder()) - { + if (sh->has_knotholder()) { changed_kh = !sh->has_local_change(); sh->decrement_local_change(); if (changed_kh) { @@ -114,15 +119,14 @@ void ShapeEditor::event_attr_changed(Inkscape::XML::Node * node, gchar const *na } static Inkscape::XML::NodeEventVector shapeeditor_repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - ShapeEditor::event_attr_changed, - nullptr, /* content_changed */ - nullptr /* order_changed */ + nullptr, /* child_added */ + nullptr, /* child_removed */ + ShapeEditor::event_attr_changed, nullptr, /* content_changed */ + nullptr /* order_changed */ }; - -void ShapeEditor::set_item(SPItem *item) { +void ShapeEditor::set_item(SPItem *item) +{ if (_blockSetItem) { return; } @@ -138,11 +142,8 @@ void ShapeEditor::set_item(SPItem *item) { this->knotholder = createKnotHolder(item, desktop); } SPLPEItem *lpe = dynamic_cast<SPLPEItem *>(item); - if (!(lpe && - lpe->getCurrentLPE() && - lpe->getCurrentLPE()->isVisible() && - lpe->getCurrentLPE()->providesKnotholder())) - { + if (!(lpe && lpe->getCurrentLPE() && lpe->getCurrentLPE()->isVisible() && + lpe->getCurrentLPE()->providesKnotholder())) { delete this->lpeknotholder; this->lpeknotholder = nullptr; } @@ -175,16 +176,19 @@ void ShapeEditor::set_item(SPItem *item) { } } - /** FIXME: This thing is only called when the item needs to be updated in response to repr change. Why not make a reload function in KnotHolder? */ void ShapeEditor::reset_item() { if (knotholder) { - SPObject *obj = desktop->getDocument()->getObjectByRepr(knotholder_listener_attached_for); /// note that it is not certain that this is an SPItem; it could be a LivePathEffectObject. + SPObject *obj = desktop->getDocument()->getObjectByRepr( + knotholder_listener_attached_for); /// note that it is not certain that this is an SPItem; it could be a + /// LivePathEffectObject. set_item(SP_ITEM(obj)); } else if (lpeknotholder) { - SPObject *obj = desktop->getDocument()->getObjectByRepr(lpeknotholder_listener_attached_for); /// note that it is not certain that this is an SPItem; it could be a LivePathEffectObject. + SPObject *obj = desktop->getDocument()->getObjectByRepr( + lpeknotholder_listener_attached_for); /// note that it is not certain that this is an SPItem; it could be a + /// LivePathEffectObject. set_item(SP_ITEM(obj)); } } @@ -192,7 +196,8 @@ void ShapeEditor::reset_item() /** * Returns true if this ShapeEditor has a knot above which the mouse currently hovers. */ -bool ShapeEditor::knot_mouseover() const { +bool ShapeEditor::knot_mouseover() const +{ if (this->knotholder) { return knotholder->knot_mouseover(); } diff --git a/src/ui/shape-editor.h b/src/ui/shape-editor.h index 05b972eae19b6fc59f1de3a40738c65160537088..3875f15216fb4fb6d57922e28a06fbee309aa879 100644 --- a/src/ui/shape-editor.h +++ b/src/ui/shape-editor.h @@ -20,12 +20,15 @@ class LivePathEffectObject; class SPDesktop; class SPItem; -namespace Inkscape { namespace XML { class Node; } +namespace Inkscape { +namespace XML { +class Node; +} namespace UI { -class ShapeEditor { +class ShapeEditor +{ public: - ShapeEditor(SPDesktop *desktop, Geom::Affine edit_transform = Geom::identity()); ~ShapeEditor(); @@ -44,6 +47,7 @@ public: static void blockSetItem(bool b) { _blockSetItem = b; } // kludge static void event_attr_changed(Inkscape::XML::Node * /*repr*/, char const *name, char const * /*old_value*/, char const * /*new_value*/, bool /*is_interactive*/, void *data); + private: void reset_item(); static bool _blockSetItem; @@ -59,7 +63,6 @@ private: #endif // SEEN_SHAPE_EDITOR_H - /* Local Variables: mode:c++ @@ -70,4 +73,3 @@ private: End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : - diff --git a/src/ui/simple-pref-pusher.cpp b/src/ui/simple-pref-pusher.cpp index bc71f27506d6639c4005e356ccda2a592956f0db..76c4a192402ac009f1c08b32348b00a06194d1aa 100644 --- a/src/ui/simple-pref-pusher.cpp +++ b/src/ui/simple-pref-pusher.cpp @@ -6,13 +6,13 @@ namespace Inkscape { namespace UI { -SimplePrefPusher::SimplePrefPusher( Gtk::ToggleToolButton *btn, Glib::ustring const &path ) : - Observer(path), - _btn(btn), - freeze(false) +SimplePrefPusher::SimplePrefPusher(Gtk::ToggleToolButton *btn, Glib::ustring const &path) + : Observer(path) + , _btn(btn) + , freeze(false) { freeze = true; - _btn->set_active( Inkscape::Preferences::get()->getBool(observed_path) ); + _btn->set_active(Inkscape::Preferences::get()->getBool(observed_path)); freeze = false; Inkscape::Preferences::get()->addObserver(*this); @@ -23,8 +23,7 @@ SimplePrefPusher::~SimplePrefPusher() Inkscape::Preferences::get()->removeObserver(*this); } -void -SimplePrefPusher::notify(Inkscape::Preferences::Entry const &newVal) +void SimplePrefPusher::notify(Inkscape::Preferences::Entry const &newVal) { bool newBool = newVal.getBool(); bool oldBool = _btn->get_active(); @@ -34,8 +33,8 @@ SimplePrefPusher::notify(Inkscape::Preferences::Entry const &newVal) } } -} -} +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/simple-pref-pusher.h b/src/ui/simple-pref-pusher.h index c17c625fa1251450ec70b733dce43e0d0fe27094..fe90b0ea3a93ece6afd18e973004acbd5275d5cd 100644 --- a/src/ui/simple-pref-pusher.h +++ b/src/ui/simple-pref-pusher.h @@ -30,8 +30,7 @@ public: * @param callback function to invoke when changes are pushed. * @param cbData data to be passed on to the callback function. */ - SimplePrefPusher(Gtk::ToggleToolButton *btn, - Glib::ustring const & path); + SimplePrefPusher(Gtk::ToggleToolButton *btn, Glib::ustring const &path); /** * Destructor that unregisters the preference callback. @@ -43,14 +42,13 @@ public: */ void notify(Inkscape::Preferences::Entry const &new_val) override; - private: Gtk::ToggleToolButton *_btn; bool freeze; }; -} -} +} // namespace UI +} // namespace Inkscape #endif /* diff --git a/src/ui/tool-factory.cpp b/src/ui/tool-factory.cpp index 8c80c392142f4ee7741b3f766ab6cef093995db2..38fa2f5265e9cfb6379d702a4e503657cb992e07 100644 --- a/src/ui/tool-factory.cpp +++ b/src/ui/tool-factory.cpp @@ -35,7 +35,7 @@ using namespace Inkscape::UI::Tools; -ToolBase *ToolFactory::createObject(std::string const& id) +ToolBase *ToolFactory::createObject(std::string const &id) { ToolBase *tool = nullptr; diff --git a/src/ui/tool-factory.h b/src/ui/tool-factory.h index e6dcbd29d74f33543bfbfec43f7472a79ae477b2..57ccdada27699bb2ed93da53c8841a2207351f69 100644 --- a/src/ui/tool-factory.h +++ b/src/ui/tool-factory.h @@ -21,14 +21,14 @@ namespace Tools { class ToolBase; } -} -} +} // namespace UI +} // namespace Inkscape -struct ToolFactory { - static Inkscape::UI::Tools::ToolBase *createObject(std::string const& id); +struct ToolFactory +{ + static Inkscape::UI::Tools::ToolBase *createObject(std::string const &id); }; - #endif /* diff --git a/src/ui/tool/commit-events.h b/src/ui/tool/commit-events.h index 37fb86164066346b977d2e5e3a8459c47c9fb26e..602a2e4c4138a40cce4c3b476cc8aa4e22e58eb0 100644 --- a/src/ui/tool/commit-events.h +++ b/src/ui/tool/commit-events.h @@ -16,7 +16,8 @@ namespace Inkscape { namespace UI { /// This is used to provide sensible messages on the undo stack. -enum CommitEvent { +enum CommitEvent +{ COMMIT_MOUSE_MOVE, COMMIT_KEYBOARD_MOVE_X, COMMIT_KEYBOARD_MOVE_Y, diff --git a/src/ui/tool/control-point-selection.cpp b/src/ui/tool/control-point-selection.cpp index 186d782d1e0fb48cf0bb9f2d539307e5c4c4b83d..8b1067ebff1cb8452acd6a30ab1ce0b3a889f48e 100644 --- a/src/ui/tool/control-point-selection.cpp +++ b/src/ui/tool/control-point-selection.cpp @@ -10,18 +10,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <boost/none.hpp> -#include "ui/tool/selectable-control-point.h" +#include "ui/tool/control-point-selection.h" + #include <2geom/transforms.h> +#include <boost/none.hpp> +#include <gdk/gdkkeysyms.h> + #include "desktop.h" -#include "ui/tool/control-point-selection.h" #include "ui/tool/event-utils.h" -#include "ui/tool/transform-handle-set.h" #include "ui/tool/node.h" - - - -#include <gdk/gdkkeysyms.h> +#include "ui/tool/selectable-control-point.h" +#include "ui/tool/transform-handle-set.h" namespace Inkscape { namespace UI { @@ -43,7 +42,7 @@ namespace UI { */ /** @var ControlPointSelection::signal_point_changed * Fires when a control point is added to or removed from the selection. - * The first param contains a pointer to the control point that changed sel. state. + * The first param contains a pointer to the control point that changed sel. state. * The second says whether the point is currently selected. */ /** @var ControlPointSelection::signal_commit @@ -57,16 +56,11 @@ ControlPointSelection::ControlPointSelection(SPDesktop *d, SPCanvasGroup *th_gro , _handles_visible(true) , _one_node_handles(false) { - signal_update.connect( sigc::bind( - sigc::mem_fun(*this, &ControlPointSelection::_updateTransformHandles), - true)); + signal_update.connect(sigc::bind(sigc::mem_fun(*this, &ControlPointSelection::_updateTransformHandles), true)); ControlPoint::signal_mouseover_change.connect( - sigc::hide( - sigc::mem_fun(*this, &ControlPointSelection::_mouseoverChanged))); - _handles->signal_transform.connect( - sigc::mem_fun(*this, &ControlPointSelection::transform)); - _handles->signal_commit.connect( - sigc::mem_fun(*this, &ControlPointSelection::_commitHandlesTransform)); + sigc::hide(sigc::mem_fun(*this, &ControlPointSelection::_mouseoverChanged))); + _handles->signal_transform.connect(sigc::mem_fun(*this, &ControlPointSelection::transform)); + _handles->signal_commit.connect(sigc::mem_fun(*this, &ControlPointSelection::_commitHandlesTransform)); } ControlPointSelection::~ControlPointSelection() @@ -76,7 +70,8 @@ ControlPointSelection::~ControlPointSelection() } /** Add a control point to the selection. */ -std::pair<ControlPointSelection::iterator, bool> ControlPointSelection::insert(const value_type &x, bool notify, bool to_update) +std::pair<ControlPointSelection::iterator, bool> ControlPointSelection::insert(const value_type &x, bool notify, + bool to_update) { iterator found = _points.find(x); if (found != _points.end()) { @@ -112,7 +107,8 @@ void ControlPointSelection::erase(iterator pos, bool to_update) ControlPointSelection::size_type ControlPointSelection::erase(const key_type &k, bool notify) { iterator pos = _points.find(k); - if (pos == _points.end()) return 0; + if (pos == _points.end()) + return 0; erase(pos); if (notify) { @@ -182,11 +178,10 @@ void ControlPointSelection::invertSelection() for (auto _all_point : _all_points) { if (_all_point->selected()) { in.push_back(_all_point); - erase(_all_point); - } - else { + erase(_all_point); + } else { out.push_back(_all_point); - insert(_all_point, false, false); + insert(_all_point, false, false); } } _update(); @@ -220,8 +215,10 @@ void ControlPointSelection::spatialGrow(SelectableControlPoint *origin, int dir) } } if (match) { - if (grow) insert(match); - else erase(match); + if (grow) + insert(match); + else + erase(match); signal_selection_changed.emit(std::vector<value_type>(1, match), grow); } } @@ -234,43 +231,54 @@ void ControlPointSelection::transform(Geom::Affine const &m) } _updateBounds(); // TODO preserving the rotation radius needs some rethinking... - if (_rot_radius) (*_rot_radius) *= m.descrim(); - if (_mouseover_rot_radius) (*_mouseover_rot_radius) *= m.descrim(); + if (_rot_radius) + (*_rot_radius) *= m.descrim(); + if (_mouseover_rot_radius) + (*_mouseover_rot_radius) *= m.descrim(); signal_update.emit(); } /** Align control points on the specified axis. */ void ControlPointSelection::align(Geom::Dim2 axis) { - enum AlignTargetNode { LAST_NODE=0, FIRST_NODE, MID_NODE, MIN_NODE, MAX_NODE }; - if (empty()) return; + enum AlignTargetNode + { + LAST_NODE = 0, + FIRST_NODE, + MID_NODE, + MIN_NODE, + MAX_NODE + }; + if (empty()) + return; Geom::Dim2 d = static_cast<Geom::Dim2>((axis + 1) % 2); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - Geom::OptInterval bound; for (auto _point : _points) { bound.unionWith(Geom::OptInterval(_point->position()[d])); } - if (!bound) { return; } + if (!bound) { + return; + } double new_coord; - switch (AlignTargetNode(prefs->getInt("/dialogs/align/align-nodes-to", 2))){ + switch (AlignTargetNode(prefs->getInt("/dialogs/align/align-nodes-to", 2))) { case FIRST_NODE: - new_coord=(_points_list.front())->position()[d]; + new_coord = (_points_list.front())->position()[d]; break; case LAST_NODE: - new_coord=(_points_list.back())->position()[d]; + new_coord = (_points_list.back())->position()[d]; break; case MID_NODE: - new_coord=bound->middle(); + new_coord = bound->middle(); break; case MIN_NODE: - new_coord=bound->min(); + new_coord = bound->min(); break; case MAX_NODE: - new_coord=bound->max(); + new_coord = bound->max(); break; default: return; @@ -286,10 +294,11 @@ void ControlPointSelection::align(Geom::Dim2 axis) /** Equdistantly distribute control points by moving them in the specified dimension. */ void ControlPointSelection::distribute(Geom::Dim2 d) { - if (empty()) return; + if (empty()) + return; // this needs to be a multimap, otherwise it will fail when some points have the same coord - typedef std::multimap<double, SelectableControlPoint*> SortMap; + typedef std::multimap<double, SelectableControlPoint *> SortMap; SortMap sm; Geom::OptInterval bound; @@ -301,7 +310,9 @@ void ControlPointSelection::distribute(Geom::Dim2 d) bound.unionWith(Geom::OptInterval(pos[d])); } - if (!bound) { return; } + if (!bound) { + return; + } // now we iterate over the multimap and set aligned positions. double step = size() == 1 ? 0 : bound->extent() / (size() - 1); @@ -385,7 +396,7 @@ void ControlPointSelection::_pointDragged(Geom::Point &new_pos, GdkEventMotion * Geom::Affine trans; trans.setIdentity(); double dist = Geom::distance(_original_positions[cur], _original_positions[_grabbed_point]); - double deltafrac = 0.5 + 0.5 * cos(M_PI * dist/fdist); + double deltafrac = 0.5 + 0.5 * cos(M_PI * dist / fdist); if (dist != 0.0) { // The sculpting transformation is not affine, but it can be // locally approximated by one. Here we compute the local @@ -403,8 +414,8 @@ void ControlPointSelection::_pointDragged(Geom::Point &new_pos, GdkEventMotion * Geom::Point origpy = _original_positions[cur] + origdy; double distdx = Geom::distance(origpx, _original_positions[_grabbed_point]); double distdy = Geom::distance(origpy, _original_positions[_grabbed_point]); - double deltafracdx = 0.5 + 0.5 * cos(M_PI * distdx/fdist); - double deltafracdy = 0.5 + 0.5 * cos(M_PI * distdy/fdist); + double deltafracdx = 0.5 + 0.5 * cos(M_PI * distdx / fdist); + double deltafracdy = 0.5 + 0.5 * cos(M_PI * distdy / fdist); Geom::Point newp = origp + abs_delta * deltafrac; Geom::Point newpx = origpx + abs_delta * deltafracdx; Geom::Point newpy = origpy + abs_delta * deltafracdy; @@ -424,7 +435,7 @@ void ControlPointSelection::_pointDragged(Geom::Point &new_pos, GdkEventMotion * trans *= Geom::Translate(-cur->position() + _original_positions[cur] + abs_delta * deltafrac); } cur->transform(trans); - //cur->move(_original_positions[cur] + abs_delta * deltafrac); + // cur->move(_original_positions[cur] + abs_delta * deltafrac); } } else { Geom::Point delta = new_pos - _grabbed_point->position(); @@ -488,7 +499,8 @@ void ControlPointSelection::_updateBounds() void ControlPointSelection::_updateTransformHandles(bool preserve_center) { - if (_dragging) return; + if (_dragging) + return; if (_handles_visible && size() > 1) { _handles->setBounds(*bounds(), preserve_center); @@ -508,11 +520,13 @@ void ControlPointSelection::_updateTransformHandles(bool preserve_center) * the modifier state of the supplied event. */ bool ControlPointSelection::_keyboardMove(GdkEventKey const &event, Geom::Point const &dir) { - if (held_control(event)) return false; + if (held_control(event)) + return false; unsigned num = 1 + combine_key_events(shortcut_key(event), 0); - Geom::Point delta = dir * num; - if (held_shift(event)) delta *= 10; + Geom::Point delta = dir * num; + if (held_shift(event)) + delta *= 10; if (held_alt(event)) { delta /= _desktop->current_zoom(); } else { @@ -536,12 +550,14 @@ bool ControlPointSelection::_keyboardMove(GdkEventKey const &event, Geom::Point */ double ControlPointSelection::_rotationRadius(Geom::Point const &rc) { - if (empty()) return 1.0; // some safe value + if (empty()) + return 1.0; // some safe value Geom::Rect b = *bounds(); double maxlen = 0; for (unsigned i = 0; i < 4; ++i) { double len = Geom::distance(b.corner(i), rc); - if (len > maxlen) maxlen = len; + if (len > maxlen) + maxlen = len; } return maxlen; } @@ -554,15 +570,15 @@ double ControlPointSelection::_rotationRadius(Geom::Point const &rc) */ bool ControlPointSelection::_keyboardRotate(GdkEventKey const &event, int dir) { - if (empty()) return false; + if (empty()) + return false; Geom::Point rc; // rotate around the mouseovered point, or the selection's rotation center // if nothing is mouseovered double radius; - SelectableControlPoint *scp = - dynamic_cast<SelectableControlPoint*>(ControlPoint::mouseovered_point); + SelectableControlPoint *scp = dynamic_cast<SelectableControlPoint *>(ControlPoint::mouseovered_point); if (scp) { rc = scp->position(); if (!_mouseover_rot_radius) { @@ -590,24 +606,23 @@ bool ControlPointSelection::_keyboardRotate(GdkEventKey const &event, int dir) } // translate to origin, rotate, translate back to original position - Geom::Affine m = Geom::Translate(-rc) - * Geom::Rotate(angle) * Geom::Translate(rc); + Geom::Affine m = Geom::Translate(-rc) * Geom::Rotate(angle) * Geom::Translate(rc); transform(m); signal_commit.emit(COMMIT_KEYBOARD_ROTATE); return true; } - bool ControlPointSelection::_keyboardScale(GdkEventKey const &event, int dir) { - if (empty()) return false; + if (empty()) + return false; double maxext = bounds()->maxExtent(); - if (Geom::are_near(maxext, 0)) return false; + if (Geom::are_near(maxext, 0)) + return false; Geom::Point center; - SelectableControlPoint *scp = - dynamic_cast<SelectableControlPoint*>(ControlPoint::mouseovered_point); + SelectableControlPoint *scp = dynamic_cast<SelectableControlPoint *>(ControlPoint::mouseovered_point); if (scp) { center = scp->position(); } else { @@ -625,7 +640,7 @@ bool ControlPointSelection::_keyboardScale(GdkEventKey const &event, int dir) length_change *= dir; } double scale = (maxext + length_change) / maxext; - + Geom::Affine m = Geom::Translate(-center) * Geom::Scale(scale) * Geom::Translate(center); transform(m); signal_commit.emit(COMMIT_KEYBOARD_SCALE_UNIFORM); @@ -634,7 +649,8 @@ bool ControlPointSelection::_keyboardScale(GdkEventKey const &event, int dir) bool ControlPointSelection::_keyboardFlip(Geom::Dim2 d) { - if (empty()) return false; + if (empty()) + return false; Geom::Scale scale_transform(1, 1); if (d == Geom::X) { @@ -643,8 +659,7 @@ bool ControlPointSelection::_keyboardFlip(Geom::Dim2 d) scale_transform = Geom::Scale(1, -1); } - SelectableControlPoint *scp = - dynamic_cast<SelectableControlPoint*>(ControlPoint::mouseovered_point); + SelectableControlPoint *scp = dynamic_cast<SelectableControlPoint *>(ControlPoint::mouseovered_point); Geom::Point center = scp ? scp->position() : _handles->rotationCenter().position(); Geom::Affine m = Geom::Translate(-center) * scale_transform * Geom::Translate(center); @@ -668,64 +683,69 @@ bool ControlPointSelection::event(Inkscape::UI::Tools::ToolBase * /*event_contex // Later split out so that it can be reused in object selection switch (event->type) { - case GDK_KEY_PRESS: - // do not handle key events if the selection is empty - if (empty()) break; - - switch(shortcut_key(event->key)) { - // moves - case GDK_KEY_Up: - case GDK_KEY_KP_Up: - case GDK_KEY_KP_8: - return _keyboardMove(event->key, Geom::Point(0, -_desktop->yaxisdir())); - case GDK_KEY_Down: - case GDK_KEY_KP_Down: - case GDK_KEY_KP_2: - return _keyboardMove(event->key, Geom::Point(0, _desktop->yaxisdir())); - case GDK_KEY_Right: - case GDK_KEY_KP_Right: - case GDK_KEY_KP_6: - return _keyboardMove(event->key, Geom::Point(1, 0)); - case GDK_KEY_Left: - case GDK_KEY_KP_Left: - case GDK_KEY_KP_4: - return _keyboardMove(event->key, Geom::Point(-1, 0)); - - // rotates - case GDK_KEY_bracketleft: - return _keyboardRotate(event->key, -_desktop->yaxisdir()); - case GDK_KEY_bracketright: - return _keyboardRotate(event->key, _desktop->yaxisdir()); - - // scaling - case GDK_KEY_less: - case GDK_KEY_comma: - return _keyboardScale(event->key, -1); - case GDK_KEY_greater: - case GDK_KEY_period: - return _keyboardScale(event->key, 1); - - // TODO: skewing - - // flipping - // NOTE: H is horizontal flip, while Shift+H switches transform handle mode! - case GDK_KEY_h: - case GDK_KEY_H: - if (held_shift(event->key)) { - toggleTransformHandlesMode(); - return true; + case GDK_KEY_PRESS: + // do not handle key events if the selection is empty + if (empty()) + break; + + switch (shortcut_key(event->key)) { + // moves + case GDK_KEY_Up: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_8: + return _keyboardMove(event->key, Geom::Point(0, -_desktop->yaxisdir())); + case GDK_KEY_Down: + case GDK_KEY_KP_Down: + case GDK_KEY_KP_2: + return _keyboardMove(event->key, Geom::Point(0, _desktop->yaxisdir())); + case GDK_KEY_Right: + case GDK_KEY_KP_Right: + case GDK_KEY_KP_6: + return _keyboardMove(event->key, Geom::Point(1, 0)); + case GDK_KEY_Left: + case GDK_KEY_KP_Left: + case GDK_KEY_KP_4: + return _keyboardMove(event->key, Geom::Point(-1, 0)); + + // rotates + case GDK_KEY_bracketleft: + return _keyboardRotate(event->key, -_desktop->yaxisdir()); + case GDK_KEY_bracketright: + return _keyboardRotate(event->key, _desktop->yaxisdir()); + + // scaling + case GDK_KEY_less: + case GDK_KEY_comma: + return _keyboardScale(event->key, -1); + case GDK_KEY_greater: + case GDK_KEY_period: + return _keyboardScale(event->key, 1); + + // TODO: skewing + + // flipping + // NOTE: H is horizontal flip, while Shift+H switches transform handle mode! + case GDK_KEY_h: + case GDK_KEY_H: + if (held_shift(event->key)) { + toggleTransformHandlesMode(); + return true; + } + // any modifiers except shift should cause no action + if (held_any_modifiers(event->key)) + break; + return _keyboardFlip(Geom::X); + case GDK_KEY_v: + case GDK_KEY_V: + if (held_any_modifiers(event->key)) + break; + return _keyboardFlip(Geom::Y); + default: + break; } - // any modifiers except shift should cause no action - if (held_any_modifiers(event->key)) break; - return _keyboardFlip(Geom::X); - case GDK_KEY_v: - case GDK_KEY_V: - if (held_any_modifiers(event->key)) break; - return _keyboardFlip(Geom::Y); - default: break; - } - break; - default: break; + break; + default: + break; } return false; } @@ -744,7 +764,7 @@ void ControlPointSelection::getUnselectedPoints(std::vector<Inkscape::SnapCandid ControlPointSelection::Set &nodes = this->allPoints(); for (auto node : nodes) { if (!node->selected()) { - Node *n = static_cast<Node*>(node); + Node *n = static_cast<Node *>(node); pts.push_back(n->snapCandidatePoint()); } } diff --git a/src/ui/tool/control-point-selection.h b/src/ui/tool/control-point-selection.h index b50f1f2479d7873a3676b90cb972873b7cfc75d9..41b5032814dc8bf9a1d6f87664be2f1844495ced 100644 --- a/src/ui/tool/control-point-selection.h +++ b/src/ui/tool/control-point-selection.h @@ -13,19 +13,20 @@ #ifndef SEEN_UI_TOOL_CONTROL_POINT_SELECTION_H #define SEEN_UI_TOOL_CONTROL_POINT_SELECTION_H +#include <2geom/forward.h> +#include <2geom/point.h> +#include <2geom/rect.h> +#include <boost/optional.hpp> +#include <cstddef> #include <list> #include <memory> +#include <sigc++/sigc++.h> #include <unordered_map> #include <unordered_set> -#include <boost/optional.hpp> -#include <cstddef> -#include <sigc++/sigc++.h> -#include <2geom/forward.h> -#include <2geom/point.h> -#include <2geom/rect.h> + +#include "snap-candidate.h" #include "ui/tool/commit-events.h" #include "ui/tool/manipulator.h" -#include "snap-candidate.h" class SPDesktop; struct SPCanvasGroup; @@ -34,13 +35,16 @@ namespace Inkscape { namespace UI { class TransformHandleSet; class SelectableControlPoint; -} -} +} // namespace UI +} // namespace Inkscape namespace Inkscape { namespace UI { -class ControlPointSelection : public Manipulator, public sigc::trackable { +class ControlPointSelection + : public Manipulator + , public sigc::trackable +{ public: ControlPointSelection(SPDesktop *d, SPCanvasGroup *th_group); ~ControlPointSelection() override; @@ -64,9 +68,10 @@ public: const_iterator end() const { return _points.end(); } // insert - std::pair<iterator, bool> insert(const value_type& x, bool notify = true, bool to_update = true); + std::pair<iterator, bool> insert(const value_type &x, bool notify = true, bool to_update = true); template <class InputIterator> - void insert(InputIterator first, InputIterator last) { + void insert(InputIterator first, InputIterator last) + { for (; first != last; ++first) { insert(*first, false, false); } @@ -77,13 +82,11 @@ public: // erase void clear(); void erase(iterator pos, bool to_update = true); - size_type erase(const key_type& k, bool notify = true); + size_type erase(const key_type &k, bool notify = true); void erase(iterator first, iterator last); // find - iterator find(const key_type &k) { - return _points.find(k); - } + iterator find(const key_type &k) { return _points.find(k); } // Sometimes it is very useful to keep a list of all selectable points. set_type const &allPoints() const { return _all_points; } @@ -120,7 +123,7 @@ public: void getOriginalPoints(std::vector<Inkscape::SnapCandidatePoint> &pts); void getUnselectedPoints(std::vector<Inkscape::SnapCandidatePoint> &pts); void setOriginalPoints(); - //the purpose of this list is to keep track of first and last selected + // the purpose of this list is to keep track of first and last selected std::list<SelectableControlPoint *> _points_list; private: @@ -154,8 +157,8 @@ private: Geom::OptRect _bounds; TransformHandleSet *_handles; SelectableControlPoint *_grabbed_point, *_farthest_point; - unsigned _dragging : 1; - unsigned _handles_visible : 1; + unsigned _dragging : 1; + unsigned _handles_visible : 1; unsigned _one_node_handles : 1; friend class SelectableControlPoint; diff --git a/src/ui/tool/control-point.cpp b/src/ui/tool/control-point.cpp index 0153ed4f27d6de8d358b81466bd77b06e44c39ac..13f9e5f4778349303f5a5a2bb0b0e419939545f5 100644 --- a/src/ui/tool/control-point.cpp +++ b/src/ui/tool/control-point.cpp @@ -7,32 +7,26 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <iostream> +#include "ui/tool/control-point.h" +#include <2geom/point.h> #include <gdk/gdkkeysyms.h> #include <gdkmm.h> - -#include <2geom/point.h> +#include <iostream> #include "desktop.h" -#include "message-context.h" - #include "display/snap-indicator.h" - +#include "message-context.h" #include "object/sp-namedview.h" - -#include "ui/tools/tool-base.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" - +#include "ui/tools/tool-base.h" #include "ui/widget/canvas.h" // Forced redraws namespace Inkscape { namespace UI { - // Default colors for control points ControlPoint::ColorSet ControlPoint::_default_color_set = { {0xffffff00, 0x01000000}, // normal fill, stroke @@ -46,67 +40,55 @@ ControlPoint::ColorSet ControlPoint::_default_color_set = { ControlPoint *ControlPoint::mouseovered_point = nullptr; -sigc::signal<void, ControlPoint*> ControlPoint::signal_mouseover_change; +sigc::signal<void, ControlPoint *> ControlPoint::signal_mouseover_change; Geom::Point ControlPoint::_drag_event_origin(Geom::infinity(), Geom::infinity()); Geom::Point ControlPoint::_drag_origin(Geom::infinity(), Geom::infinity()); -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 | GDK_SCROLL_MASK | GDK_SMOOTH_SCROLL_MASK); +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 | GDK_SCROLL_MASK | GDK_SMOOTH_SCROLL_MASK); bool ControlPoint::_drag_initiated = false; bool ControlPoint::_event_grab = false; -ControlPoint::ColorSet ControlPoint::invisible_cset = { - {0x00000000, 0x00000000}, - {0x00000000, 0x00000000}, - {0x00000000, 0x00000000}, - {0x00000000, 0x00000000}, - {0x00000000, 0x00000000}, - {0x00000000, 0x00000000} -}; +ControlPoint::ColorSet ControlPoint::invisible_cset = {{0x00000000, 0x00000000}, {0x00000000, 0x00000000}, + {0x00000000, 0x00000000}, {0x00000000, 0x00000000}, + {0x00000000, 0x00000000}, {0x00000000, 0x00000000}}; 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(nullptr), - _cset(cset), - _state(STATE_NORMAL), - _position(initial_pos), - _lurking(false), - _double_clicked(false) -{ - _canvas_item = sp_canvas_item_new( - group ? group : _desktop->getControls(), SP_TYPE_CTRL, - "anchor", (SPAnchorType) anchor, "size", (unsigned int) 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); + Glib::RefPtr<Gdk::Pixbuf> pixbuf, ColorSet const &cset, SPCanvasGroup *group) + : _desktop(d) + , _canvas_item(nullptr) + , _cset(cset) + , _state(STATE_NORMAL) + , _position(initial_pos) + , _lurking(false) + , _double_clicked(false) +{ + _canvas_item = + sp_canvas_item_new(group ? group : _desktop->getControls(), SP_TYPE_CTRL, "anchor", (SPAnchorType)anchor, + "size", (unsigned int)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(); } -ControlPoint::ControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, - ControlType type, - ColorSet const &cset, SPCanvasGroup *group) : - _desktop(d), - _canvas_item(nullptr), - _cset(cset), - _state(STATE_NORMAL), - _position(initial_pos), - _lurking(false), - _double_clicked(false) +ControlPoint::ControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, ControlType type, + ColorSet const &cset, SPCanvasGroup *group) + : _desktop(d) + , _canvas_item(nullptr) + , _cset(cset) + , _state(STATE_NORMAL) + , _position(initial_pos) + , _lurking(false) + , _double_clicked(false) { _canvas_item = ControlManager::getManager().createControl(group ? group : _desktop->getControls(), 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); + 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(); } @@ -118,15 +100,14 @@ ControlPoint::~ControlPoint() } g_signal_handler_disconnect(G_OBJECT(_canvas_item), _event_handler_connection); - //sp_canvas_item_hide(_canvas_item); + // sp_canvas_item_hide(_canvas_item); sp_canvas_item_destroy(_canvas_item); } void ControlPoint::_commonInit() { SP_CTRL(_canvas_item)->moveto(_position); - _event_handler_connection = g_signal_connect(G_OBJECT(_canvas_item), "event", - G_CALLBACK(_event_handler), this); + _event_handler_connection = g_signal_connect(G_OBJECT(_canvas_item), "event", G_CALLBACK(_event_handler), this); } void ControlPoint::setPosition(Geom::Point const &pos) @@ -140,7 +121,8 @@ void ControlPoint::move(Geom::Point const &pos) setPosition(pos); } -void ControlPoint::transform(Geom::Affine const &m) { +void ControlPoint::transform(Geom::Affine const &m) +{ move(position() * m); } @@ -151,8 +133,10 @@ bool ControlPoint::visible() const void ControlPoint::setVisible(bool v) { - if (v) sp_canvas_item_show(_canvas_item); - else sp_canvas_item_hide(_canvas_item); + if (v) + sp_canvas_item_show(_canvas_item); + else + sp_canvas_item_hide(_canvas_item); } Glib::ustring ControlPoint::format_tip(char const *format, ...) @@ -217,7 +201,7 @@ 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) +int ControlPoint::_event_handler(SPCanvasItem * /*item*/, GdkEvent *event, ControlPoint *point) { if ((point == nullptr) || (point->_desktop == nullptr)) { return FALSE; @@ -231,23 +215,19 @@ bool ControlPoint::_eventHandler(Inkscape::UI::Tools::ToolBase *event_context, G // NOTE the static variables below are shared for all points! // TODO handle clicks and drags from other buttons too - if (event == nullptr) - { + if (event == nullptr) { return false; } - - if (event_context == nullptr) - { + + if (event_context == nullptr) { return false; } - if (_desktop == nullptr) - { + if (_desktop == nullptr) { return false; } - if(event_context->getDesktop() !=_desktop) - { - g_warning ("ControlPoint: desktop pointers not equal!"); - //return false; + if (event_context->getDesktop() != _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; @@ -258,215 +238,214 @@ bool ControlPoint::_eventHandler(Inkscape::UI::Tools::ToolBase *event_context, G Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int drag_tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); - switch(event->type) - { - case GDK_BUTTON_PRESS: - next_release_doubleclick = 0; - if (event->button.button == 1 && !event_context->space_panning) { - // 1st mouse button click. internally, start dragging, but do not emit signals - // or change position until drag tolerance is exceeded. - _drag_event_origin[Geom::X] = event->button.x; - _drag_event_origin[Geom::Y] = event->button.y; - pointer_offset = _position - _desktop->w2d(_drag_event_origin); - _drag_initiated = false; - // route all events to this handler - sp_canvas_item_grab(_canvas_item, _grab_event_mask, nullptr, event->button.time); - _event_grab = true; - _setState(STATE_CLICKED); - return true; - } - return _event_grab; + switch (event->type) { + case GDK_BUTTON_PRESS: + next_release_doubleclick = 0; + if (event->button.button == 1 && !event_context->space_panning) { + // 1st mouse button click. internally, start dragging, but do not emit signals + // or change position until drag tolerance is exceeded. + _drag_event_origin[Geom::X] = event->button.x; + _drag_event_origin[Geom::Y] = event->button.y; + pointer_offset = _position - _desktop->w2d(_drag_event_origin); + _drag_initiated = false; + // route all events to this handler + sp_canvas_item_grab(_canvas_item, _grab_event_mask, nullptr, event->button.time); + _event_grab = true; + _setState(STATE_CLICKED); + return true; + } + return _event_grab; - case GDK_2BUTTON_PRESS: - // store the button number for next release - next_release_doubleclick = event->button.button; - return true; - - case GDK_MOTION_NOTIFY: - 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; - } + case GDK_2BUTTON_PRESS: + // store the button number for next release + next_release_doubleclick = event->button.button; + return true; - // if we are here, it means the tolerance was just exceeded. - _drag_origin = _position; - transferred = grabbed(&event->motion); - // _drag_initiated might change during the above virtual call + case GDK_MOTION_NOTIFY: + if (_event_grab && !event_context->space_panning) { + _desktop->snapindicator->remove_snaptarget(); + bool transferred = false; if (!_drag_initiated) { - // this guarantees smooth redraws while dragging - _desktop->getCanvas()->forced_redraws_start(5); - _drag_initiated = true; + 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; + } + + // if we are here, it means the tolerance was just exceeded. + _drag_origin = _position; + transferred = grabbed(&event->motion); + // _drag_initiated might change during the above virtual call + if (!_drag_initiated) { + // this guarantees smooth redraws while dragging + _desktop->getCanvas()->forced_redraws_start(5); + _drag_initiated = true; + } } - } - 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); - move(new_pos); - _updateDragTip(&event->motion); // 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(event_context, nullptr, - (gpointer) this, &event->motion, - Inkscape::UI::Tools::DelayedSnapEvent::CONTROL_POINT_HANDLER); - } - return true; - } - break; - - case GDK_BUTTON_RELEASE: - if (_event_grab && event->button.button == 1) { - // If we have any pending snap event, then invoke it now! - // (This is needed because we might not have snapped on the latest GDK_MOTION_NOTIFY event - // if the mouse speed was too high. This is inherent to the snap-delay mechanism. - // 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 && _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); + 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); + move(new_pos); + _updateDragTip(&event->motion); // 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(event_context, nullptr, (gpointer)this, &event->motion, + Inkscape::UI::Tools::DelayedSnapEvent::CONTROL_POINT_HANDLER); + } + return true; } + break; - sp_canvas_item_ungrab(_canvas_item); - _setMouseover(this, event->button.state); - _event_grab = false; - - if (_drag_initiated) { - // it is the end of a drag - _desktop->getCanvas()->forced_redraws_stop(); - _drag_initiated = false; - ungrabbed(&event->button); - return true; - } else { - // it is the end of a click - if (next_release_doubleclick) { - _double_clicked = true; - return doubleclicked(&event->button); - } else { - return clicked(&event->button); + case GDK_BUTTON_RELEASE: + if (_event_grab && event->button.button == 1) { + // If we have any pending snap event, then invoke it now! + // (This is needed because we might not have snapped on the latest GDK_MOTION_NOTIFY event + // if the mouse speed was too high. This is inherent to the snap-delay mechanism. + // 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 && _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); } - } - } - break; - case GDK_ENTER_NOTIFY: - _setMouseover(this, event->crossing.state); - return true; - case GDK_LEAVE_NOTIFY: - _clearMouseover(); - return true; + sp_canvas_item_ungrab(_canvas_item); + _setMouseover(this, event->button.state); + _event_grab = false; - case GDK_GRAB_BROKEN: - if (_event_grab && !event->grab_broken.keyboard) { - { - ungrabbed(nullptr); if (_drag_initiated) { + // it is the end of a drag _desktop->getCanvas()->forced_redraws_stop(); + _drag_initiated = false; + ungrabbed(&event->button); + return true; + } else { + // it is the end of a click + if (next_release_doubleclick) { + _double_clicked = true; + return doubleclicked(&event->button); + } else { + return clicked(&event->button); + } } } - _setState(STATE_NORMAL); - _event_grab = false; - _drag_initiated = false; + break; + + case GDK_ENTER_NOTIFY: + _setMouseover(this, event->crossing.state); return true; - } - break; - - // update tips on modifier state change - // TODO add ESC keybinding as drag cancel - case GDK_KEY_PRESS: - switch (Inkscape::UI::Tools::get_latin_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(event_context); - SnapPreferences &snapprefs = _desktop->namedview->snap_manager.snapprefs; - bool snap_save = snapprefs.getSnapEnabledGlobally(); - snapprefs.setSnapEnabledGlobally(false); - - Geom::Point new_pos = _drag_origin; - - // make a fake event for dragging - // ASSUMPTION: dragging a point without modifiers will never prevent us from moving it - // to its original position - GdkEventMotion fake; - fake.type = GDK_MOTION_NOTIFY; - fake.window = event->key.window; - fake.send_event = event->key.send_event; - fake.time = event->key.time; - fake.x = _drag_event_origin[Geom::X]; // these two are normally not used in handlers - fake.y = _drag_event_origin[Geom::Y]; // (and shouldn't be) - fake.axes = nullptr; - fake.state = 0; // unconstrained drag - fake.is_hint = FALSE; - fake.device = nullptr; - fake.x_root = -1; // not used in handlers (and shouldn't be) - fake.y_root = -1; // can be used as a flag to check for cancelled drag - - dragged(new_pos, &fake); - - sp_canvas_item_ungrab(_canvas_item); - _clearMouseover(); // this will also reset state to normal - _desktop->getCanvas()->forced_redraws_stop(); - _event_grab = false; - _drag_initiated = false; - - ungrabbed(nullptr); // ungrabbed handlers can handle a NULL event - snapprefs.setSnapEnabledGlobally(snap_save); - } + case GDK_LEAVE_NOTIFY: + _clearMouseover(); 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 - TransformHandle *th = dynamic_cast<TransformHandle*>(this); - if (th) { - th->getNextClosestPoint(false); + + case GDK_GRAB_BROKEN: + if (_event_grab && !event->grab_broken.keyboard) { + { + ungrabbed(nullptr); + if (_drag_initiated) { + _desktop->getCanvas()->forced_redraws_stop(); + } + } + _setState(STATE_NORMAL); + _event_grab = false; + _drag_initiated = false; return true; } break; + + // update tips on modifier state change + // TODO add ESC keybinding as drag cancel + case GDK_KEY_PRESS: + switch (Inkscape::UI::Tools::get_latin_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(event_context); + SnapPreferences &snapprefs = _desktop->namedview->snap_manager.snapprefs; + bool snap_save = snapprefs.getSnapEnabledGlobally(); + snapprefs.setSnapEnabledGlobally(false); + + Geom::Point new_pos = _drag_origin; + + // make a fake event for dragging + // ASSUMPTION: dragging a point without modifiers will never prevent us from moving it + // to its original position + GdkEventMotion fake; + fake.type = GDK_MOTION_NOTIFY; + fake.window = event->key.window; + fake.send_event = event->key.send_event; + fake.time = event->key.time; + fake.x = _drag_event_origin[Geom::X]; // these two are normally not used in handlers + fake.y = _drag_event_origin[Geom::Y]; // (and shouldn't be) + fake.axes = nullptr; + fake.state = 0; // unconstrained drag + fake.is_hint = FALSE; + fake.device = nullptr; + fake.x_root = -1; // not used in handlers (and shouldn't be) + fake.y_root = -1; // can be used as a flag to check for cancelled drag + + dragged(new_pos, &fake); + + sp_canvas_item_ungrab(_canvas_item); + _clearMouseover(); // this will also reset state to normal + _desktop->getCanvas()->forced_redraws_stop(); + _event_grab = false; + _drag_initiated = false; + + ungrabbed(nullptr); // ungrabbed handlers can handle a NULL event + snapprefs.setSnapEnabledGlobally(snap_save); + } + 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 + TransformHandle *th = dynamic_cast<TransformHandle *>(this); + if (th) { + th->getNextClosestPoint(false); + return true; + } + break; + } + case GDK_KEY_ISO_Left_Tab: { // Downcast from ControlPoint to TransformHandle, if possible + // This is an ugly hack; we should have the transform handle intercept the + // keystrokes itself + TransformHandle *th = dynamic_cast<TransformHandle *>(this); + if (th) { + th->getNextClosestPoint(true); + return true; + } + break; + } + default: + break; } - case GDK_KEY_ISO_Left_Tab: - {// Downcast from ControlPoint to TransformHandle, if possible - // This is an ugly hack; we should have the transform handle intercept the keystrokes itself - TransformHandle *th = dynamic_cast<TransformHandle*>(this); - if (th) { - th->getNextClosestPoint(true); - return true; + // Do not break here, to allow for updating tooltips and such + case GDK_KEY_RELEASE: + if (mouseovered_point != this) { + return false; } - break; + if (_drag_initiated) { + return true; // this prevents the tool from overwriting the drag tip + } else { + unsigned state = state_after_event(event); + if (state != event->key.state) { + // we need to return true if there was a tip available, otherwise the tool's + // handler will process this event and set the tool's message, overwriting + // the point's message + return _updateTip(state); + } } - default: break; - } - // Do not break here, to allow for updating tooltips and such - case GDK_KEY_RELEASE: - if (mouseovered_point != this){ - return false; - } - if (_drag_initiated) { - return true; // this prevents the tool from overwriting the drag tip - } else { - unsigned state = state_after_event(event); - if (state != event->key.state) { - // we need to return true if there was a tip available, otherwise the tool's - // handler will process this event and set the tool's message, overwriting - // the point's message - return _updateTip(state); - } - } - break; - default: break; + default: + break; } // do not propagate events during grab - it might cause problems @@ -491,8 +470,7 @@ bool ControlPoint::_updateTip(unsigned state) { Glib::ustring tip = _getTip(state); if (!tip.empty()) { - _desktop->event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, - tip.data()); + _desktop->event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, tip.data()); return true; } else { _desktop->event_context->defaultMessageContext()->clear(); @@ -507,8 +485,7 @@ bool ControlPoint::_updateDragTip(GdkEventMotion *event) } Glib::ustring tip = _getDragTip(event); if (!tip.empty()) { - _desktop->event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, - tip.data()); + _desktop->event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, tip.data()); return true; } else { _desktop->event_context->defaultMessageContext()->clear(); @@ -528,7 +505,8 @@ void ControlPoint::_clearMouseover() void ControlPoint::transferGrab(ControlPoint *prev_point, GdkEventMotion *event) { - if (!_event_grab) return; + if (!_event_grab) + return; grabbed(event); sp_canvas_item_ungrab(prev_point->_canvas_item); @@ -547,7 +525,7 @@ void ControlPoint::_setState(State state) { ColorEntry current = {0, 0}; ColorSet const &activeCset = (_isLurking()) ? invisible_cset : _cset; - switch(state) { + switch (state) { case STATE_NORMAL: current = activeCset.normal; break; @@ -587,7 +565,6 @@ void ControlPoint::_setLurking(bool lurking) } } - bool ControlPoint::_is_drag_cancelled(GdkEventMotion *event) { return !event || event->x_root == -1; @@ -600,13 +577,9 @@ bool ControlPoint::grabbed(GdkEventMotion * /*event*/) return false; } -void ControlPoint::dragged(Geom::Point &/*new_pos*/, GdkEventMotion * /*event*/) -{ -} +void ControlPoint::dragged(Geom::Point & /*new_pos*/, GdkEventMotion * /*event*/) {} -void ControlPoint::ungrabbed(GdkEventButton * /*event*/) -{ -} +void ControlPoint::ungrabbed(GdkEventButton * /*event*/) {} bool ControlPoint::clicked(GdkEventButton * /*event*/) { diff --git a/src/ui/tool/control-point.h b/src/ui/tool/control-point.h index b97f3cbcbff8961bc11205c3a6cacf1b77af649b..f0ee49041d53855b1d241b3dcb0f87e1ca72701b 100644 --- a/src/ui/tool/control-point.h +++ b/src/ui/tool/control-point.h @@ -11,16 +11,16 @@ #ifndef SEEN_UI_TOOL_CONTROL_POINT_H #define SEEN_UI_TOOL_CONTROL_POINT_H -#include <gdkmm/pixbuf.h> +#include <2geom/point.h> #include <boost/utility.hpp> #include <cstddef> +#include <gdkmm/pixbuf.h> #include <sigc++/signal.h> #include <sigc++/trackable.h> -#include <2geom/point.h> -#include "ui/control-types.h" #include "display/sodipodi-ctrl.h" #include "enums.h" +#include "ui/control-types.h" class SPDesktop; @@ -31,8 +31,8 @@ namespace Tools { class ToolBase; } -} -} +} // namespace UI +} // namespace Inkscape namespace Inkscape { namespace UI { @@ -74,16 +74,19 @@ namespace UI { * - If the point has additional canvas items tied to it (like handle lines), override * the setPosition() method. */ -class ControlPoint : boost::noncopyable, public sigc::trackable { +class ControlPoint + : boost::noncopyable + , public sigc::trackable +{ public: - /** * 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 { + enum State + { /** Normal state. */ STATE_NORMAL, @@ -98,7 +101,7 @@ public: * Destructor */ virtual ~ControlPoint(); - + /// @name Adjust the position of the control point /// @{ /** Current position of the control point. */ @@ -130,7 +133,7 @@ public: */ virtual void transform(Geom::Affine const &m); /// @} - + /// @name Toggle the point's visibility /// @{ bool visible() const; @@ -142,7 +145,7 @@ public: */ virtual void setVisible(bool v); /// @} - + /// @name Transfer grab from another event handler /// @{ /** @@ -174,19 +177,19 @@ public: * 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 sigc::signal<void, ControlPoint *> signal_mouseover_change; - static Glib::ustring format_tip(char const *format, ...) G_GNUC_PRINTF(1,2); + 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(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event); SPDesktop *const _desktop; ///< The desktop this control point resides on. - bool doubleClicked() {return _double_clicked;} + bool doubleClicked() { return _double_clicked; } protected: - - struct ColorEntry { + struct ColorEntry + { guint32 fill; guint32 stroke; }; @@ -195,7 +198,8 @@ protected: * Color entries for each possible state. * @todo resolve this to be in sync with the five standard GTK states. */ - struct ColorSet { + struct ColorSet + { ColorEntry normal; ColorEntry mouseover; ColorEntry clicked; @@ -220,8 +224,7 @@ protected: * @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, - ControlType type, + ControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, ControlType type, ColorSet const &cset = _default_color_set, SPCanvasGroup *group = nullptr); /** @@ -234,8 +237,7 @@ protected: * @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, + ControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, Glib::RefPtr<Gdk::Pixbuf> pixbuf, ColorSet const &cset = _default_color_set, SPCanvasGroup *group = nullptr); /// @name Handle control point events in subclasses @@ -332,12 +334,11 @@ protected: virtual Glib::ustring _getTip(unsigned /*state*/) const { return ""; } - virtual Glib::ustring _getDragTip(GdkEventMotion */*event*/) const { return ""; } + virtual Glib::ustring _getDragTip(GdkEventMotion * /*event*/) const { return ""; } virtual bool _hasDragTips() const { return false; } - - SPCanvasItem * _canvas_item; ///< Visual representation of the control point. + SPCanvasItem *_canvas_item; ///< Visual representation of the control point. ColorSet const &_cset; ///< Colors used to represent the point @@ -355,7 +356,6 @@ protected: static bool _drag_initiated; private: - ControlPoint(ControlPoint const &other); void operator=(ControlPoint const &other); @@ -393,7 +393,6 @@ private: bool _double_clicked; }; - } // namespace UI } // namespace Inkscape diff --git a/src/ui/tool/curve-drag-point.cpp b/src/ui/tool/curve-drag-point.cpp index 4e878d07e49b625499f7d072eb006e02e49d6003..c81938a19a7fb2868e8b0c74654d3c51cc2367ea 100644 --- a/src/ui/tool/curve-drag-point.cpp +++ b/src/ui/tool/curve-drag-point.cpp @@ -8,28 +8,27 @@ */ #include "ui/tool/curve-drag-point.h" + #include <glib/gi18n.h> + #include "desktop.h" +#include "object/sp-namedview.h" +#include "object/sp-path.h" #include "ui/tool/control-point-selection.h" #include "ui/tool/event-utils.h" #include "ui/tool/multi-path-manipulator.h" #include "ui/tool/path-manipulator.h" -#include "object/sp-namedview.h" -#include "object/sp-path.h" - namespace Inkscape { namespace UI { - 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, - CTRL_TYPE_INVISIPOINT, - 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); } @@ -44,7 +43,7 @@ bool CurveDragPoint::_eventHandler(Inkscape::UI::Tools::ToolBase *event_context, return ControlPoint::_eventHandler(event_context, event); } -bool CurveDragPoint::grabbed(GdkEventMotion */*event*/) +bool CurveDragPoint::grabbed(GdkEventMotion * /*event*/) { _pm._selection.hideTransformHandles(); NodeList::iterator second = first.next(); @@ -56,7 +55,7 @@ bool CurveDragPoint::grabbed(GdkEventMotion */*event*/) // delta is a vector equal 1/3 of distance from first to second Geom::Point delta = (second->position() - first->position()) / 3.0; // only update the nodes if the mode is bspline - if(!_pm._isBSpline()){ + if (!_pm._isBSpline()) { first->front()->move(first->front()->position() + delta); second->back()->move(second->back()->position() - delta); } @@ -69,7 +68,8 @@ bool CurveDragPoint::grabbed(GdkEventMotion */*event*/) void CurveDragPoint::dragged(Geom::Point &new_pos, GdkEventMotion *event) { - if (!first || !first.next()) return; + if (!first || !first.next()) + return; NodeList::iterator second = first.next(); // special cancel handling - retract handles when if the segment was degenerate @@ -94,32 +94,36 @@ void CurveDragPoint::dragged(Geom::Point &new_pos, GdkEventMotion *event) // "weight" describes how the influence of the drag should be distributed // among the handles; 0 = front handle only, 1 = back handle only. double weight, t = _t; - if (t <= 1.0 / 6.0) weight = 0; - else if (t <= 0.5) weight = (pow((6 * t - 1) / 2.0, 3)) / 2; - else if (t <= 5.0 / 6.0) weight = (1 - pow((6 * (1-t) - 1) / 2.0, 3)) / 2 + 0.5; - else weight = 1; + if (t <= 1.0 / 6.0) + weight = 0; + else if (t <= 0.5) + weight = (pow((6 * t - 1) / 2.0, 3)) / 2; + else if (t <= 5.0 / 6.0) + weight = (1 - pow((6 * (1 - t) - 1) / 2.0, 3)) / 2 + 0.5; + else + weight = 1; Geom::Point delta = new_pos - position(); - Geom::Point offset0 = ((1-weight)/(3*t*(1-t)*(1-t))) * delta; - Geom::Point offset1 = (weight/(3*t*t*(1-t))) * delta; + Geom::Point offset0 = ((1 - weight) / (3 * t * (1 - t) * (1 - t))) * delta; + Geom::Point offset1 = (weight / (3 * t * t * (1 - t))) * delta; - //modified so that, if the trace is bspline, it only acts if the SHIFT key is pressed - if(!_pm._isBSpline()){ + // modified so that, if the trace is bspline, it only acts if the SHIFT key is pressed + if (!_pm._isBSpline()) { first->front()->move(first->front()->position() + offset0); second->back()->move(second->back()->position() + offset1); - }else if(weight>=0.8){ - if(held_shift(*event)){ + } else if (weight >= 0.8) { + if (held_shift(*event)) { second->back()->move(new_pos); } else { second->move(second->position() + delta); } - }else if(weight<=0.2){ - if(held_shift(*event)){ + } else if (weight <= 0.2) { + if (held_shift(*event)) { first->back()->move(new_pos); } else { first->move(first->position() + delta); } - }else{ + } else { first->move(first->position() + delta); second->move(second->position() + delta); } @@ -136,10 +140,12 @@ void CurveDragPoint::ungrabbed(GdkEventButton *) bool CurveDragPoint::clicked(GdkEventButton *event) { // This check is probably redundant - if (!first || event->button != 1) return false; + if (!first || event->button != 1) + return false; // the next iterator can be invalid if we click very near the end of path NodeList::iterator second = first.next(); - if (!second) return false; + if (!second) + return false; // insert nodes on Ctrl+Alt+click if (held_control(*event) && held_alt(*event)) { @@ -150,7 +156,7 @@ bool CurveDragPoint::clicked(GdkEventButton *event) if (held_shift(*event)) { // if both nodes of the segment are selected, deselect; // otherwise add to selection - if (first->selected() && second->selected()) { + if (first->selected() && second->selected()) { _pm._selection.erase(first.ptr()); _pm._selection.erase(second.ptr()); } else { @@ -168,7 +174,8 @@ bool CurveDragPoint::clicked(GdkEventButton *event) bool CurveDragPoint::doubleclicked(GdkEventButton *event) { - if (event->button != 1 || !first || !first.next()) return false; + if (event->button != 1 || !first || !first.next()) + return false; _insertNode(true); return true; } @@ -185,34 +192,30 @@ void CurveDragPoint::_insertNode(bool take_selection) Glib::ustring CurveDragPoint::_getTip(unsigned state) const { - if (_pm.empty()) return ""; - if (!first || !first.next()) return ""; + if (_pm.empty()) + return ""; + if (!first || !first.next()) + return ""; bool linear = first->front()->isDegenerate() && first.next()->back()->isDegenerate(); - if(state_held_shift(state) && _pm._isBSpline()){ - return C_("Path segment tip", - "<b>Shift</b>: drag to open or move BSpline handles"); + if (state_held_shift(state) && _pm._isBSpline()) { + return C_("Path segment tip", "<b>Shift</b>: drag to open or move BSpline handles"); } if (state_held_shift(state)) { - return C_("Path segment tip", - "<b>Shift</b>: click to toggle segment selection"); + return C_("Path segment tip", "<b>Shift</b>: click to toggle segment selection"); } if (state_held_control(state) && state_held_alt(state)) { - return C_("Path segment tip", - "<b>Ctrl+Alt</b>: click to insert a node"); + return C_("Path segment tip", "<b>Ctrl+Alt</b>: click to insert a node"); } - if(_pm._isBSpline()){ - return C_("Path segment tip", - "<b>BSpline segment</b>: drag to shape the segment, doubleclick to insert node, " - "click to select (more: Shift, Ctrl+Alt)"); + if (_pm._isBSpline()) { + return C_("Path segment tip", "<b>BSpline segment</b>: drag to shape the segment, doubleclick to insert node, " + "click to select (more: Shift, Ctrl+Alt)"); } if (linear) { - return C_("Path segment tip", - "<b>Linear segment</b>: drag to convert to a Bezier segment, " - "doubleclick to insert node, click to select (more: Shift, Ctrl+Alt)"); + return C_("Path segment tip", "<b>Linear segment</b>: drag to convert to a Bezier segment, " + "doubleclick to insert node, click to select (more: Shift, Ctrl+Alt)"); } else { - return C_("Path segment tip", - "<b>Bezier segment</b>: drag to shape the segment, doubleclick to insert node, " - "click to select (more: Shift, Ctrl+Alt)"); + return C_("Path segment tip", "<b>Bezier segment</b>: drag to shape the segment, doubleclick to insert node, " + "click to select (more: Shift, Ctrl+Alt)"); } } diff --git a/src/ui/tool/curve-drag-point.h b/src/ui/tool/curve-drag-point.h index bfe0ad74cb1810384b15ef4d78483c7ff5daeb87..071cc130325a3030beee38be534819c8ac6d2736 100644 --- a/src/ui/tool/curve-drag-point.h +++ b/src/ui/tool/curve-drag-point.h @@ -29,9 +29,9 @@ struct PathSharedData; * 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 { +class CurveDragPoint : public ControlPoint +{ public: - CurveDragPoint(PathManipulator &pm); void setSize(double sz) { _setSize(sz); } void setTimeValue(double t) { _t = t; } @@ -41,7 +41,6 @@ public: bool _eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) override; protected: - Glib::ustring _getTip(unsigned state) const override; void dragged(Geom::Point &, GdkEventMotion *) override; bool grabbed(GdkEventMotion *) override; diff --git a/src/ui/tool/event-utils.cpp b/src/ui/tool/event-utils.cpp index 5008c127f148f53b2e694f418901addbf10cd5b6..b368ffa3a4c8f1390ce32b1c1e213f37d8eb3cc1 100644 --- a/src/ui/tool/event-utils.cpp +++ b/src/ui/tool/event-utils.cpp @@ -9,25 +9,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/tool/event-utils.h" + #include <cstring> #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> #include <gdkmm/display.h> -#include "ui/tool/event-utils.h" namespace Inkscape { namespace UI { - guint shortcut_key(GdkEventKey const &event) { guint shortcut_key = 0; - gdk_keymap_translate_keyboard_state( - Gdk::Display::get_default()->get_keymap(), - event.hardware_keycode, - (GdkModifierType) event.state, - 0 /*event->key.group*/, - &shortcut_key, nullptr, nullptr, nullptr); + gdk_keymap_translate_keyboard_state(Gdk::Display::get_default()->get_keymap(), event.hardware_keycode, + (GdkModifierType)event.state, 0 /*event->key.group*/, &shortcut_key, nullptr, + nullptr, nullptr); return shortcut_key; } @@ -38,18 +35,18 @@ unsigned combine_key_events(guint keyval, gint mask) 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)) { + 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 ++; + 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); + if (event_next) + gdk_event_put(event_next); return i; } @@ -60,43 +57,46 @@ unsigned state_after_event(GdkEvent *event) { unsigned state = 0; switch (event->type) { - case GDK_KEY_PRESS: - state = event->key.state; - switch(shortcut_key(event->key)) { - case GDK_KEY_Shift_L: - case GDK_KEY_Shift_R: - state |= GDK_SHIFT_MASK; - break; - case GDK_KEY_Control_L: - case GDK_KEY_Control_R: - state |= GDK_CONTROL_MASK; - break; - case GDK_KEY_Alt_L: - case GDK_KEY_Alt_R: - state |= GDK_MOD1_MASK; - break; - default: break; - } - break; - case GDK_KEY_RELEASE: - state = event->key.state; - switch(shortcut_key(event->key)) { - case GDK_KEY_Shift_L: - case GDK_KEY_Shift_R: - state &= ~GDK_SHIFT_MASK; + case GDK_KEY_PRESS: + state = event->key.state; + switch (shortcut_key(event->key)) { + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + state |= GDK_SHIFT_MASK; + break; + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + state |= GDK_CONTROL_MASK; + break; + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + state |= GDK_MOD1_MASK; + break; + default: + break; + } break; - case GDK_KEY_Control_L: - case GDK_KEY_Control_R: - state &= ~GDK_CONTROL_MASK; + case GDK_KEY_RELEASE: + state = event->key.state; + switch (shortcut_key(event->key)) { + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + state &= ~GDK_SHIFT_MASK; + break; + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + state &= ~GDK_CONTROL_MASK; + break; + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + state &= ~GDK_MOD1_MASK; + break; + default: + break; + } break; - case GDK_KEY_Alt_L: - case GDK_KEY_Alt_R: - state &= ~GDK_MOD1_MASK; + default: break; - default: break; - } - break; - default: break; } return state; } diff --git a/src/ui/tool/event-utils.h b/src/ui/tool/event-utils.h index 6b303c95595bcbec1be651f9f24f8ea682c2b139..238e66e445051ea751bc21eb388b566ad65b1e0c 100644 --- a/src/ui/tool/event-utils.h +++ b/src/ui/tool/event-utils.h @@ -12,100 +12,118 @@ #ifndef SEEN_UI_TOOL_EVENT_UTILS_H #define SEEN_UI_TOOL_EVENT_UTILS_H -#include <gdk/gdk.h> #include <2geom/point.h> +#include <gdk/gdk.h> namespace Inkscape { namespace UI { -inline bool state_held_shift(unsigned state) { +inline bool state_held_shift(unsigned state) +{ return state & GDK_SHIFT_MASK; } -inline bool state_held_control(unsigned state) { +inline bool state_held_control(unsigned state) +{ return state & GDK_CONTROL_MASK; } -inline bool state_held_alt(unsigned state) { +inline bool state_held_alt(unsigned state) +{ return state & GDK_MOD1_MASK; } -inline bool state_held_only_shift(unsigned state) { +inline bool state_held_only_shift(unsigned state) +{ return (state & GDK_SHIFT_MASK) && !(state & (GDK_CONTROL_MASK | GDK_MOD1_MASK)); } -inline bool state_held_only_control(unsigned state) { +inline bool state_held_only_control(unsigned state) +{ return (state & GDK_CONTROL_MASK) && !(state & (GDK_SHIFT_MASK | GDK_MOD1_MASK)); } -inline bool state_held_only_alt(unsigned state) { +inline bool state_held_only_alt(unsigned state) +{ return (state & GDK_MOD1_MASK) && !(state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)); } -inline bool state_held_any_modifiers(unsigned state) { +inline bool state_held_any_modifiers(unsigned state) +{ return state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK); } -inline bool state_held_no_modifiers(unsigned state) { +inline bool state_held_no_modifiers(unsigned state) +{ return !state_held_any_modifiers(state); } template <unsigned button> -inline bool state_held_button(unsigned state) { - return (button == 0 || button > 5) ? false : state & (GDK_BUTTON1_MASK << (button-1)); +inline bool state_held_button(unsigned state) +{ + return (button == 0 || button > 5) ? false : state & (GDK_BUTTON1_MASK << (button - 1)); } - /** Checks whether Shift was held when the event was generated. */ template <typename E> -inline bool held_shift(E const &event) { +inline bool held_shift(E const &event) +{ return state_held_shift(event.state); } /** Checks whether Control was held when the event was generated. */ template <typename E> -inline bool held_control(E const &event) { +inline bool held_control(E const &event) +{ return state_held_control(event.state); } /** Checks whether Alt was held when the event was generated. */ template <typename E> -inline bool held_alt(E const &event) { +inline bool held_alt(E const &event) +{ return state_held_alt(event.state); } /** True if from the set of Ctrl, Shift and Alt only Ctrl was held when the event * was generated. */ template <typename E> -inline bool held_only_control(E const &event) { +inline bool held_only_control(E const &event) +{ return state_held_only_control(event.state); } /** True if from the set of Ctrl, Shift and Alt only Shift was held when the event * was generated. */ template <typename E> -inline bool held_only_shift(E const &event) { +inline bool held_only_shift(E const &event) +{ return state_held_only_shift(event.state); } /** True if from the set of Ctrl, Shift and Alt only Alt was held when the event * was generated. */ template <typename E> -inline bool held_only_alt(E const &event) { +inline bool held_only_alt(E const &event) +{ return state_held_only_alt(event.state); } template <typename E> -inline bool held_no_modifiers(E const &event) { +inline bool held_no_modifiers(E const &event) +{ return state_held_no_modifiers(event.state); } template <typename E> -inline bool held_any_modifiers(E const &event) { +inline bool held_any_modifiers(E const &event) +{ return state_held_any_modifiers(event.state); } template <typename E> -inline Geom::Point event_point(E const &event) { +inline Geom::Point event_point(E const &event) +{ return Geom::Point(event.x, event.y); } /** Use like this: * @code if (held_button<2>(event->motion)) { ... @endcode */ template <unsigned button, typename E> -inline bool held_button(E const &event) { +inline bool held_button(E const &event) +{ return state_held_button<button>(event.state); } diff --git a/src/ui/tool/manipulator.cpp b/src/ui/tool/manipulator.cpp index a68de5e98ee2c2bfef748c5bc6167b352ede4efd..0336fed87aec750ac14b0669f34540af8dbe84f0 100644 --- a/src/ui/tool/manipulator.cpp +++ b/src/ui/tool/manipulator.cpp @@ -68,7 +68,7 @@ bool ManipulatorGroup::event(GdkEvent *event) if (_grab) { return _grab->event(event); } - + for (std::list<boost::shared_ptr<Manipulator> >::iterator i = begin(); i != end(); ++i) { if ((*i)->event(event) || _grab) return true; } diff --git a/src/ui/tool/manipulator.h b/src/ui/tool/manipulator.h index 308ad1c9d4fac8129b5b5c85bf1f432caf81791a..bf2a67cb074871808a2ec425205f241f5ddb3c6e 100644 --- a/src/ui/tool/manipulator.h +++ b/src/ui/tool/manipulator.h @@ -12,12 +12,13 @@ #ifndef SEEN_UI_TOOL_MANIPULATOR_H #define SEEN_UI_TOOL_MANIPULATOR_H -#include <set> -#include <map> #include <cstddef> -#include <sigc++/sigc++.h> -#include <glib.h> #include <gdk/gdk.h> +#include <glib.h> +#include <map> +#include <set> +#include <sigc++/sigc++.h> + #include "ui/tools/tool-base.h" class SPDesktop; @@ -31,16 +32,18 @@ class ControlPointSelection; * @brief Tool component that processes events and does something in response to them. * Note: this class is probably redundant. */ -class Manipulator { -friend class ManipulatorGroup; +class Manipulator +{ + friend class ManipulatorGroup; + public: Manipulator(SPDesktop *d) : _desktop(d) {} virtual ~Manipulator() = default; - + /// Handle input event. Returns true if handled. - virtual bool event(Inkscape::UI::Tools::ToolBase *, GdkEvent *)=0; + virtual bool event(Inkscape::UI::Tools::ToolBase *, GdkEvent *) = 0; SPDesktop *const _desktop; }; @@ -48,7 +51,10 @@ public: * @brief Tool component that edits something on the canvas using selectable control points. * Note: this class is probably redundant. */ -class PointManipulator : public Manipulator, public sigc::trackable { +class PointManipulator + : public Manipulator + , public sigc::trackable +{ public: PointManipulator(SPDesktop *d, ControlPointSelection &sel) : Manipulator(d) @@ -56,12 +62,14 @@ public: {} /// Type of extremum points to add in PathManipulator::insertNodeAtExtremum - enum ExtremumType { + enum ExtremumType + { EXTR_MIN_X = 0, EXTR_MAX_X, EXTR_MIN_Y, EXTR_MAX_Y }; + protected: ControlPointSelection &_selection; }; @@ -73,42 +81,38 @@ protected: * * This is not used at the moment and is probably useless. */ template <typename T> -class MultiManipulator : public PointManipulator { +class MultiManipulator : public PointManipulator +{ public: - //typedef typename T::ItemType ItemType; - typedef typename std::pair<void*, std::shared_ptr<T> > MapPair; - typedef typename std::map<void*, std::shared_ptr<T> > MapType; + // typedef typename T::ItemType ItemType; + typedef typename std::pair<void *, std::shared_ptr<T>> MapPair; + typedef typename std::map<void *, std::shared_ptr<T>> MapType; MultiManipulator(SPDesktop *d, ControlPointSelection &sel) : PointManipulator(d, sel) {} - void addItem(void *item) { + void addItem(void *item) + { std::shared_ptr<T> m(_createManipulator(item)); _mmap.insert(MapPair(item, m)); } - void removeItem(void *item) { - _mmap.erase(item); - } - void clear() { - _mmap.clear(); - } - bool contains(void *item) { - return _mmap.find(item) != _mmap.end(); - } - bool empty() { - return _mmap.empty(); - } - - void setItems(std::vector<gpointer> list) { // this function is not called anywhere ... delete ? - std::set<void*> to_remove; + void removeItem(void *item) { _mmap.erase(item); } + void clear() { _mmap.clear(); } + bool contains(void *item) { return _mmap.find(item) != _mmap.end(); } + bool empty() { return _mmap.empty(); } + + void setItems(std::vector<gpointer> list) + { // this function is not called anywhere ... delete ? + std::set<void *> to_remove; for (typename MapType::iterator mi = _mmap.begin(); mi != _mmap.end(); ++mi) { to_remove.insert(mi->first); } - for (auto i:list) { + for (auto i : list) { if (_isItemType(i)) { // erase returns the number of items removed // if nothing was removed, it means this item did not have a manipulator - add it - if (!to_remove.erase(i)) addItem(i); + if (!to_remove.erase(i)) + addItem(i); } } for (auto ri : to_remove) { @@ -121,36 +125,43 @@ public: * @code m.invokeForAll(&SomeManipulator::someMethod); @endcode */ template <typename R> - void invokeForAll(R (T::*method)()) { + void invokeForAll(R (T::*method)()) + { for (typename MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) { ((i->second.get())->*method)(); } } template <typename R, typename A> - void invokeForAll(R (T::*method)(A), A a) { + void invokeForAll(R (T::*method)(A), A a) + { for (typename MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) { ((i->second.get())->*method)(a); } } template <typename R, typename A> - void invokeForAll(R (T::*method)(A const &), A const &a) { + void invokeForAll(R (T::*method)(A const &), A const &a) + { for (typename MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) { ((i->second.get())->*method)(a); } } template <typename R, typename A, typename B> - void invokeForAll(R (T::*method)(A,B), A a, B b) { + void invokeForAll(R (T::*method)(A, B), A a, B b) + { for (typename MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) { ((i->second.get())->*method)(a, b); } } - - bool event(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) override { + + bool event(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) override + { for (typename MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) { - if ((*i).second->event(event_context, event)) return true; + if ((*i).second->event(event_context, event)) + return true; } return false; } + protected: virtual T *_createManipulator(void *item) = 0; virtual bool _isItemType(void *item) = 0; diff --git a/src/ui/tool/modifier-tracker.cpp b/src/ui/tool/modifier-tracker.cpp index 70c85a6a5130965f4d2486b66b0b9acb67e14b78..fe8b3235fcc4fa1c5b0b1507fea5fdb12f9b095a 100644 --- a/src/ui/tool/modifier-tracker.cpp +++ b/src/ui/tool/modifier-tracker.cpp @@ -9,10 +9,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/tool/modifier-tracker.h" + #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> + #include "ui/tool/event-utils.h" -#include "ui/tool/modifier-tracker.h" namespace Inkscape { namespace UI { @@ -29,51 +31,52 @@ ModifierTracker::ModifierTracker() bool ModifierTracker::event(GdkEvent *event) { switch (event->type) { - case GDK_KEY_PRESS: - switch (shortcut_key(event->key)) { - case GDK_KEY_Shift_L: - _left_shift = true; - break; - case GDK_KEY_Shift_R: - _right_shift = true; - break; - case GDK_KEY_Control_L: - _left_ctrl = true; - break; - case GDK_KEY_Control_R: - _right_ctrl = true; - break; - case GDK_KEY_Alt_L: - _left_alt = true; - break; - case GDK_KEY_Alt_R: - _right_alt = true; - break; - } - break; - case GDK_KEY_RELEASE: - switch (shortcut_key(event->key)) { - case GDK_KEY_Shift_L: - _left_shift = false; - break; - case GDK_KEY_Shift_R: - _right_shift = false; - break; - case GDK_KEY_Control_L: - _left_ctrl = false; - break; - case GDK_KEY_Control_R: - _right_ctrl = false; + case GDK_KEY_PRESS: + switch (shortcut_key(event->key)) { + case GDK_KEY_Shift_L: + _left_shift = true; + break; + case GDK_KEY_Shift_R: + _right_shift = true; + break; + case GDK_KEY_Control_L: + _left_ctrl = true; + break; + case GDK_KEY_Control_R: + _right_ctrl = true; + break; + case GDK_KEY_Alt_L: + _left_alt = true; + break; + case GDK_KEY_Alt_R: + _right_alt = true; + break; + } break; - case GDK_KEY_Alt_L: - _left_alt = false; + case GDK_KEY_RELEASE: + switch (shortcut_key(event->key)) { + case GDK_KEY_Shift_L: + _left_shift = false; + break; + case GDK_KEY_Shift_R: + _right_shift = false; + break; + case GDK_KEY_Control_L: + _left_ctrl = false; + break; + case GDK_KEY_Control_R: + _right_ctrl = false; + break; + case GDK_KEY_Alt_L: + _left_alt = false; + break; + case GDK_KEY_Alt_R: + _right_alt = false; + break; + } break; - case GDK_KEY_Alt_R: - _right_alt = false; + default: break; - } - break; - default: break; } return false; diff --git a/src/ui/tool/modifier-tracker.h b/src/ui/tool/modifier-tracker.h index c5762e589f75be1bab2551ecd9286199dfecf49f..1700c2fb9a98038325a04a5ecad75632bfe28700 100644 --- a/src/ui/tool/modifier-tracker.h +++ b/src/ui/tool/modifier-tracker.h @@ -17,7 +17,8 @@ namespace Inkscape { namespace UI { -class ModifierTracker { +class ModifierTracker +{ public: ModifierTracker(); bool event(GdkEvent *); diff --git a/src/ui/tool/multi-path-manipulator.cpp b/src/ui/tool/multi-path-manipulator.cpp index 42599a39235193a4560a2e92cebb63d585047466..a0904a53aaa71d43e521eb9303fe9cb90de879a2 100644 --- a/src/ui/tool/multi-path-manipulator.cpp +++ b/src/ui/tool/multi-path-manipulator.cpp @@ -11,38 +11,32 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <unordered_set> +#include "ui/tool/multi-path-manipulator.h" #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> +#include <unordered_set> #include "desktop.h" -#include "document.h" #include "document-undo.h" +#include "document.h" +#include "live_effects/lpeobject.h" #include "message-stack.h" #include "node.h" -#include "verbs.h" - -#include "live_effects/lpeobject.h" - #include "object/sp-path.h" - #include "ui/tool/control-point-selection.h" #include "ui/tool/event-utils.h" -#include "ui/tool/multi-path-manipulator.h" #include "ui/tool/path-manipulator.h" +#include "verbs.h" namespace Inkscape { namespace UI { namespace { -struct hash_nodelist_iterator - : public std::unary_function<NodeList::iterator, std::size_t> +struct hash_nodelist_iterator : public std::unary_function<NodeList::iterator, std::size_t> { - std::size_t operator()(NodeList::iterator i) const { - return std::hash<NodeList::iterator::pointer>()(&*i); - } + std::size_t operator()(NodeList::iterator i) const { return std::hash<NodeList::iterator::pointer>()(&*i); } }; typedef std::pair<NodeList::iterator, NodeList::iterator> IterPair; @@ -58,13 +52,16 @@ void find_join_iterators(ControlPointSelection &sel, IterPairList &pairs) // find all endnodes in selection for (auto i : sel) { - Node *node = dynamic_cast<Node*>(i); - if (!node) continue; + Node *node = dynamic_cast<Node *>(i); + if (!node) + continue; NodeList::iterator iter = NodeList::get_iterator(node); - if (!iter.next() || !iter.prev()) join_iters.insert(iter); + if (!iter.next() || !iter.prev()) + join_iters.insert(iter); } - if (join_iters.size() < 2) return; + if (join_iters.size() < 2) + return; // Below we find the closest pairs. The algorithm is O(N^3). // We can go down to O(N^2 log N) by using O(N^2) memory, by putting all pairs @@ -99,13 +96,13 @@ bool prepare_join(IterPair &join_iters) NodeList &sp_first = NodeList::get(join_iters.first); NodeList &sp_second = NodeList::get(join_iters.second); - if (join_iters.first.next()) { // first is begin + if (join_iters.first.next()) { // first is begin if (join_iters.second.next()) { // second is begin sp_first.reverse(); } else { // second is end std::swap(join_iters.first, join_iters.second); } - } else { // first is end + } else { // first is end if (join_iters.second.next()) { // second is begin // do nothing } else { // second is end @@ -116,17 +113,13 @@ bool prepare_join(IterPair &join_iters) } } // anonymous namespace - MultiPathManipulator::MultiPathManipulator(PathSharedData &data, sigc::connection &chg) : PointManipulator(data.node_data.desktop, *data.node_data.selection) , _path_data(data) , _changed(chg) { - _selection.signal_commit.connect( - sigc::mem_fun(*this, &MultiPathManipulator::_commit)); - _selection.signal_selection_changed.connect( - sigc::hide( sigc::hide( - signal_coords_changed.make_slot()))); + _selection.signal_commit.connect(sigc::mem_fun(*this, &MultiPathManipulator::_commit)); + _selection.signal_selection_changed.connect(sigc::hide(sigc::hide(signal_coords_changed.make_slot()))); } MultiPathManipulator::~MultiPathManipulator() @@ -137,9 +130,11 @@ MultiPathManipulator::~MultiPathManipulator() /** Remove empty manipulators. */ void MultiPathManipulator::cleanup() { - for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ) { - if (i->second->empty()) _mmap.erase(i++); - else ++i; + for (MapType::iterator i = _mmap.begin(); i != _mmap.end();) { + if (i->second->empty()) + _mmap.erase(i++); + else + ++i; } } @@ -162,14 +157,12 @@ void MultiPathManipulator::setItems(std::set<ShapeRecord> const &s) ShapeRecord const &sr = i->first; ShapeRecord const &sr_new = *si; // if the shape record differs, replace the key only and modify other values - if (sr.edit_transform != sr_new.edit_transform || - sr.role != sr_new.role) - { + if (sr.edit_transform != sr_new.edit_transform || sr.role != sr_new.role) { std::shared_ptr<PathManipulator> hold(i->second); if (sr.edit_transform != sr_new.edit_transform) hold->setControlsTransform(sr_new.edit_transform); if (sr.role != sr_new.role) { - //hold->setOutlineColor(_getOutlineColor(sr_new.role)); + // hold->setOutlineColor(_getOutlineColor(sr_new.role)); } _mmap.erase(sr); _mmap.insert(std::make_pair(sr_new, hold)); @@ -180,11 +173,12 @@ void MultiPathManipulator::setItems(std::set<ShapeRecord> const &s) } // add newly selected items - for (const auto & r : shapes) { + for (const auto &r : shapes) { LivePathEffectObject *lpobj = dynamic_cast<LivePathEffectObject *>(r.object); - if (!SP_IS_PATH(r.object) && !lpobj) continue; - std::shared_ptr<PathManipulator> newpm(new PathManipulator(*this, (SPPath*) r.object, - r.edit_transform, _getOutlineColor(r.role, r.object), r.lpe_key)); + if (!SP_IS_PATH(r.object) && !lpobj) + continue; + std::shared_ptr<PathManipulator> newpm(new PathManipulator(*this, (SPPath *)r.object, r.edit_transform, + _getOutlineColor(r.role, r.object), r.lpe_key)); newpm->showHandles(_show_handles); // always show outlines for clips and masks newpm->showOutline(_show_outline || r.role != SHAPE_ROLE_NORMAL); @@ -206,7 +200,8 @@ void MultiPathManipulator::selectSubpaths() void MultiPathManipulator::shiftSelection(int dir) { - if (empty()) return; + if (empty()) + return; // 1. find last selected node // 2. select the next node; if the last node or nothing is selected, @@ -228,12 +223,13 @@ void MultiPathManipulator::shiftSelection(int dir) last_k = k; anything_found = true; // when tabbing backwards, we want the first node - if (dir == -1) goto exit_loop; + if (dir == -1) + goto exit_loop; } } } } - exit_loop: +exit_loop: // NOTE: we should not assume the _selection contains only nodes // in future it might also contain handles and other types of control points @@ -243,11 +239,11 @@ void MultiPathManipulator::shiftSelection(int dir) // select first / last node // this should never fail because there must be at least 1 non-empty manipulator if (anynode_found) { - if (dir == 1) { - _selection.insert((*_mmap.begin()->second->subpathList().begin())->begin().ptr()); - } else { - _selection.insert((--(*--(--_mmap.end())->second->subpathList().end())->end()).ptr()); - } + if (dir == 1) { + _selection.insert((*_mmap.begin()->second->subpathList().begin())->begin().ptr()); + } else { + _selection.insert((--(*--(--_mmap.end())->second->subpathList().end())->end()).ptr()); + } } return; } @@ -291,13 +287,14 @@ void MultiPathManipulator::invertSelectionInSubpaths() void MultiPathManipulator::setNodeType(NodeType type) { - if (_selection.empty()) return; + if (_selection.empty()) + return; // When all selected nodes are already cusp, retract their handles bool retract_handles = (type == NODE_CUSP); for (auto i : _selection) { - Node *node = dynamic_cast<Node*>(i); + Node *node = dynamic_cast<Node *>(i); if (node) { retract_handles &= (node->type() == NODE_CUSP); node->setType(type); @@ -306,7 +303,7 @@ void MultiPathManipulator::setNodeType(NodeType type) if (retract_handles) { for (auto i : _selection) { - Node *node = dynamic_cast<Node*>(i); + Node *node = dynamic_cast<Node *>(i); if (node) { node->front()->retract(); node->back()->retract(); @@ -319,7 +316,8 @@ void MultiPathManipulator::setNodeType(NodeType type) void MultiPathManipulator::setSegmentType(SegmentType type) { - if (_selection.empty()) return; + if (_selection.empty()) + return; invokeForAll(&PathManipulator::setSegmentType, type); if (type == SEGMENT_STRAIGHT) { _done(_("Straighten segments")); @@ -330,13 +328,15 @@ void MultiPathManipulator::setSegmentType(SegmentType type) void MultiPathManipulator::insertNodes() { - if (_selection.empty()) return; + if (_selection.empty()) + return; invokeForAll(&PathManipulator::insertNodes); _done(_("Add nodes")); } void MultiPathManipulator::insertNodesAtExtrema(ExtremumType extremum) { - if (_selection.empty()) return; + if (_selection.empty()) + return; invokeForAll(&PathManipulator::insertNodeAtExtremum, extremum); _done(_("Add extremum nodes")); } @@ -351,26 +351,28 @@ void MultiPathManipulator::insertNode(Geom::Point pt) void MultiPathManipulator::duplicateNodes() { - if (_selection.empty()) return; + if (_selection.empty()) + return; invokeForAll(&PathManipulator::duplicateNodes); _done(_("Duplicate nodes")); } void MultiPathManipulator::joinNodes() { - if (_selection.empty()) return; + 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. IterPairList joins; NodeList::iterator preserve_pos; - Node *mouseover_node = dynamic_cast<Node*>(ControlPoint::mouseovered_point); + Node *mouseover_node = dynamic_cast<Node *>(ControlPoint::mouseovered_point); if (mouseover_node) { preserve_pos = NodeList::get_iterator(mouseover_node); } find_join_iterators(_selection, joins); - for (auto & join : joins) { + for (auto &join : joins) { bool same_path = prepare_join(join); NodeList &sp_first = NodeList::get(join.first); NodeList &sp_second = NodeList::get(join.second); @@ -421,14 +423,16 @@ void MultiPathManipulator::joinNodes() void MultiPathManipulator::breakNodes() { - if (_selection.empty()) return; + if (_selection.empty()) + return; invokeForAll(&PathManipulator::breakNodes); _done(_("Break nodes"), true); } void MultiPathManipulator::deleteNodes(bool keep_shape) { - if (_selection.empty()) return; + if (_selection.empty()) + return; invokeForAll(&PathManipulator::deleteNodes, keep_shape); _doneWithCleanup(_("Delete nodes"), true); } @@ -436,11 +440,12 @@ void MultiPathManipulator::deleteNodes(bool keep_shape) /** Join selected endpoints to create segments. */ void MultiPathManipulator::joinSegments() { - if (_selection.empty()) return; + if (_selection.empty()) + return; IterPairList joins; find_join_iterators(_selection, joins); - for (auto & join : joins) { + for (auto &join : joins) { bool same_path = prepare_join(join); NodeList &sp_first = NodeList::get(join.first); NodeList &sp_second = NodeList::get(join.second); @@ -462,14 +467,16 @@ void MultiPathManipulator::joinSegments() void MultiPathManipulator::deleteSegments() { - if (_selection.empty()) return; + if (_selection.empty()) + return; invokeForAll(&PathManipulator::deleteSegments); _doneWithCleanup("Delete segments", true); } void MultiPathManipulator::alignNodes(Geom::Dim2 d) { - if (_selection.empty()) return; + if (_selection.empty()) + return; _selection.align(d); if (d == Geom::X) { _done("Align nodes to a horizontal line"); @@ -480,7 +487,8 @@ void MultiPathManipulator::alignNodes(Geom::Dim2 d) void MultiPathManipulator::distributeNodes(Geom::Dim2 d) { - if (_selection.empty()) return; + if (_selection.empty()) + return; _selection.distribute(d); if (d == Geom::X) { _done("Distribute nodes horizontally"); @@ -502,14 +510,15 @@ void MultiPathManipulator::reverseSubpaths() void MultiPathManipulator::move(Geom::Point const &delta) { - if (_selection.empty()) return; + if (_selection.empty()) + return; _selection.transform(Geom::Translate(delta)); _done("Move nodes"); } void MultiPathManipulator::showOutline(bool show) { - for (auto & i : _mmap) { + for (auto &i : _mmap) { // always show outlines for clipping paths and masks i.second->showOutline(show || i.first.role != SHAPE_ROLE_NORMAL); } @@ -554,7 +563,7 @@ void MultiPathManipulator::setLiveObjects(bool set) void MultiPathManipulator::updateOutlineColors() { - //for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) { + // for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) { // i->second->setOutlineColor(_getOutlineColor(i->first.role)); //} } @@ -576,7 +585,8 @@ bool MultiPathManipulator::event(Inkscape::UI::Tools::ToolBase *event_context, G if (_selection.size() == 1 && event->type == GDK_KEY_PRESS) { do { Node *n = dynamic_cast<Node *>(*_selection.begin()); - if (!n) break; + if (!n) + break; PathManipulator &pm = n->nodeList().subpathList().pm(); @@ -585,183 +595,188 @@ bool MultiPathManipulator::event(Inkscape::UI::Tools::ToolBase *event_context, G which = 1; } if (_tracker.leftAlt() || _tracker.leftControl()) { - if (which != 0) break; // ambiguous + if (which != 0) + break; // ambiguous which = -1; } - if (which == 0) break; // no handle chosen + if (which == 0) + break; // no handle chosen bool one_pixel = _tracker.leftAlt() || _tracker.rightAlt(); bool handled = true; switch (key) { - // single handle functions - // rotation - case GDK_KEY_bracketleft: - case GDK_KEY_braceleft: - pm.rotateHandle(n, which, -_desktop->yaxisdir(), one_pixel); - break; - case GDK_KEY_bracketright: - case GDK_KEY_braceright: - pm.rotateHandle(n, which, _desktop->yaxisdir(), one_pixel); - break; - // adjust length - case GDK_KEY_period: - case GDK_KEY_greater: - pm.scaleHandle(n, which, 1, one_pixel); - break; - case GDK_KEY_comma: - case GDK_KEY_less: - pm.scaleHandle(n, which, -1, one_pixel); - break; - default: - handled = false; - break; + // single handle functions + // rotation + case GDK_KEY_bracketleft: + case GDK_KEY_braceleft: + pm.rotateHandle(n, which, -_desktop->yaxisdir(), one_pixel); + break; + case GDK_KEY_bracketright: + case GDK_KEY_braceright: + pm.rotateHandle(n, which, _desktop->yaxisdir(), one_pixel); + break; + // adjust length + case GDK_KEY_period: + case GDK_KEY_greater: + pm.scaleHandle(n, which, 1, one_pixel); + break; + case GDK_KEY_comma: + case GDK_KEY_less: + pm.scaleHandle(n, which, -1, one_pixel); + break; + default: + handled = false; + break; } - if (handled) return true; - } while(false); + if (handled) + return true; + } while (false); } - switch (event->type) { - case GDK_KEY_PRESS: - switch (key) { - case GDK_KEY_Insert: - case GDK_KEY_KP_Insert: - // Insert - insert nodes in the middle of selected segments - insertNodes(); - return true; - case GDK_KEY_i: - case GDK_KEY_I: - if (held_only_shift(event->key)) { - // Shift+I - insert nodes (alternate keybinding for Mac keyboards - // that don't have the Insert key) - insertNodes(); - return true; - } - break; - case GDK_KEY_d: - case GDK_KEY_D: - if (held_only_shift(event->key)) { - duplicateNodes(); - return true; - } - case GDK_KEY_j: - case GDK_KEY_J: - if (held_only_shift(event->key)) { - // Shift+J - join nodes - joinNodes(); - return true; - } - if (held_only_alt(event->key)) { - // Alt+J - join segments - joinSegments(); - return true; - } - break; - case GDK_KEY_b: - case GDK_KEY_B: - if (held_only_shift(event->key)) { - // Shift+B - break nodes - breakNodes(); - return true; - } - break; - case GDK_KEY_Delete: - case GDK_KEY_KP_Delete: - case GDK_KEY_BackSpace: - if (held_shift(event->key)) break; - if (held_alt(event->key)) { - // Alt+Delete - delete segments - deleteSegments(); - } else { - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool del_preserves_shape = prefs->getBool("/tools/nodes/delete_preserves_shape", true); - // pass keep_shape = true when: - // a) del preserves shape, and control is not pressed - // b) ctrl+del preserves shape (del_preserves_shape is false), and control is pressed - // Hence xor - guint mode = prefs->getInt("/tools/freehand/pen/freehand-mode", 0); - - //if the trace is bspline ( mode 2) - if(mode==2){ - // is this correct ? - if(del_preserves_shape ^ held_control(event->key)){ - deleteNodes(false); + case GDK_KEY_PRESS: + switch (key) { + case GDK_KEY_Insert: + case GDK_KEY_KP_Insert: + // Insert - insert nodes in the middle of selected segments + insertNodes(); + return true; + case GDK_KEY_i: + case GDK_KEY_I: + if (held_only_shift(event->key)) { + // Shift+I - insert nodes (alternate keybinding for Mac keyboards + // that don't have the Insert key) + insertNodes(); + return true; + } + break; + case GDK_KEY_d: + case GDK_KEY_D: + if (held_only_shift(event->key)) { + duplicateNodes(); + return true; + } + case GDK_KEY_j: + case GDK_KEY_J: + if (held_only_shift(event->key)) { + // Shift+J - join nodes + joinNodes(); + return true; + } + if (held_only_alt(event->key)) { + // Alt+J - join segments + joinSegments(); + return true; + } + break; + case GDK_KEY_b: + case GDK_KEY_B: + if (held_only_shift(event->key)) { + // Shift+B - break nodes + breakNodes(); + return true; + } + break; + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + if (held_shift(event->key)) + break; + if (held_alt(event->key)) { + // Alt+Delete - delete segments + deleteSegments(); } else { - deleteNodes(true); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + bool del_preserves_shape = prefs->getBool("/tools/nodes/delete_preserves_shape", true); + // pass keep_shape = true when: + // a) del preserves shape, and control is not pressed + // b) ctrl+del preserves shape (del_preserves_shape is false), and control is pressed + // Hence xor + guint mode = prefs->getInt("/tools/freehand/pen/freehand-mode", 0); + + // if the trace is bspline ( mode 2) + if (mode == 2) { + // is this correct ? + if (del_preserves_shape ^ held_control(event->key)) { + deleteNodes(false); + } else { + deleteNodes(true); + } + } else { + deleteNodes(del_preserves_shape ^ held_control(event->key)); + } + + // Delete any selected gradient nodes as well + event_context->deleteSelectedDrag(held_control(event->key)); } - } else { - 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: - case GDK_KEY_C: - if (held_only_shift(event->key)) { - // Shift+C - make nodes cusp - setNodeType(NODE_CUSP); - return true; - } - break; - case GDK_KEY_s: - case GDK_KEY_S: - if (held_only_shift(event->key)) { - // Shift+S - make nodes smooth - setNodeType(NODE_SMOOTH); - return true; - } - break; - case GDK_KEY_a: - case GDK_KEY_A: - if (held_only_shift(event->key)) { - // Shift+A - make nodes auto-smooth - setNodeType(NODE_AUTO); - return true; - } - break; - case GDK_KEY_y: - case GDK_KEY_Y: - if (held_only_shift(event->key)) { - // Shift+Y - make nodes symmetric - setNodeType(NODE_SYMMETRIC); - return true; + return true; + case GDK_KEY_c: + case GDK_KEY_C: + if (held_only_shift(event->key)) { + // Shift+C - make nodes cusp + setNodeType(NODE_CUSP); + return true; + } + break; + case GDK_KEY_s: + case GDK_KEY_S: + if (held_only_shift(event->key)) { + // Shift+S - make nodes smooth + setNodeType(NODE_SMOOTH); + return true; + } + break; + case GDK_KEY_a: + case GDK_KEY_A: + if (held_only_shift(event->key)) { + // Shift+A - make nodes auto-smooth + setNodeType(NODE_AUTO); + return true; + } + break; + case GDK_KEY_y: + case GDK_KEY_Y: + if (held_only_shift(event->key)) { + // Shift+Y - make nodes symmetric + setNodeType(NODE_SYMMETRIC); + return true; + } + break; + case GDK_KEY_r: + case GDK_KEY_R: + if (held_only_shift(event->key)) { + // Shift+R - reverse subpaths + reverseSubpaths(); + return true; + } + break; + case GDK_KEY_l: + case GDK_KEY_L: + if (held_only_shift(event->key)) { + // Shift+L - make segments linear + setSegmentType(SEGMENT_STRAIGHT); + return true; + } + case GDK_KEY_u: + case GDK_KEY_U: + if (held_only_shift(event->key)) { + // Shift+U - make segments curves + setSegmentType(SEGMENT_CUBIC_BEZIER); + return true; + } + default: + break; } break; - case GDK_KEY_r: - case GDK_KEY_R: - if (held_only_shift(event->key)) { - // Shift+R - reverse subpaths - reverseSubpaths(); - return true; + case GDK_MOTION_NOTIFY: + for (auto &i : _mmap) { + if (i.second->event(event_context, event)) + return true; } break; - case GDK_KEY_l: - case GDK_KEY_L: - if (held_only_shift(event->key)) { - // Shift+L - make segments linear - setSegmentType(SEGMENT_STRAIGHT); - return true; - } - case GDK_KEY_u: - case GDK_KEY_U: - if (held_only_shift(event->key)) { - // Shift+U - make segments curves - setSegmentType(SEGMENT_CUBIC_BEZIER); - return true; - } default: break; - } - break; - case GDK_MOTION_NOTIFY: - for (auto & i : _mmap) { - if (i.second->event(event_context, event)) return true; - } - break; - default: break; } return false; @@ -773,58 +788,59 @@ void MultiPathManipulator::_commit(CommitEvent cps) { gchar const *reason = nullptr; gchar const *key = nullptr; - switch(cps) { - case COMMIT_MOUSE_MOVE: - reason = _("Move nodes"); - break; - case COMMIT_KEYBOARD_MOVE_X: - reason = _("Move nodes horizontally"); - key = "node:move:x"; - break; - case COMMIT_KEYBOARD_MOVE_Y: - reason = _("Move nodes vertically"); - key = "node:move:y"; - break; - case COMMIT_MOUSE_ROTATE: - reason = _("Rotate nodes"); - break; - case COMMIT_KEYBOARD_ROTATE: - reason = _("Rotate nodes"); - key = "node:rotate"; - break; - case COMMIT_MOUSE_SCALE_UNIFORM: - reason = _("Scale nodes uniformly"); - break; - case COMMIT_MOUSE_SCALE: - reason = _("Scale nodes"); - break; - case COMMIT_KEYBOARD_SCALE_UNIFORM: - reason = _("Scale nodes uniformly"); - key = "node:scale:uniform"; - break; - case COMMIT_KEYBOARD_SCALE_X: - reason = _("Scale nodes horizontally"); - key = "node:scale:x"; - break; - case COMMIT_KEYBOARD_SCALE_Y: - reason = _("Scale nodes vertically"); - key = "node:scale:y"; - break; - case COMMIT_MOUSE_SKEW_X: - reason = _("Skew nodes horizontally"); - key = "node:skew:x"; - break; - case COMMIT_MOUSE_SKEW_Y: - reason = _("Skew nodes vertically"); - key = "node:skew:y"; - break; - case COMMIT_FLIP_X: - reason = _("Flip nodes horizontally"); - break; - case COMMIT_FLIP_Y: - reason = _("Flip nodes vertically"); - break; - default: return; + switch (cps) { + case COMMIT_MOUSE_MOVE: + reason = _("Move nodes"); + break; + case COMMIT_KEYBOARD_MOVE_X: + reason = _("Move nodes horizontally"); + key = "node:move:x"; + break; + case COMMIT_KEYBOARD_MOVE_Y: + reason = _("Move nodes vertically"); + key = "node:move:y"; + break; + case COMMIT_MOUSE_ROTATE: + reason = _("Rotate nodes"); + break; + case COMMIT_KEYBOARD_ROTATE: + reason = _("Rotate nodes"); + key = "node:rotate"; + break; + case COMMIT_MOUSE_SCALE_UNIFORM: + reason = _("Scale nodes uniformly"); + break; + case COMMIT_MOUSE_SCALE: + reason = _("Scale nodes"); + break; + case COMMIT_KEYBOARD_SCALE_UNIFORM: + reason = _("Scale nodes uniformly"); + key = "node:scale:uniform"; + break; + case COMMIT_KEYBOARD_SCALE_X: + reason = _("Scale nodes horizontally"); + key = "node:scale:x"; + break; + case COMMIT_KEYBOARD_SCALE_Y: + reason = _("Scale nodes vertically"); + key = "node:scale:y"; + break; + case COMMIT_MOUSE_SKEW_X: + reason = _("Skew nodes horizontally"); + key = "node:skew:x"; + break; + case COMMIT_MOUSE_SKEW_Y: + reason = _("Skew nodes vertically"); + key = "node:skew:y"; + break; + case COMMIT_FLIP_X: + reason = _("Flip nodes horizontally"); + break; + case COMMIT_FLIP_Y: + reason = _("Flip nodes vertically"); + break; + default: + return; } _selection.signal_update.emit(); @@ -838,7 +854,8 @@ void MultiPathManipulator::_commit(CommitEvent cps) } /** Commits changes to XML and adds undo stack entry. */ -void MultiPathManipulator::_done(gchar const *reason, bool alert_LPE) { +void MultiPathManipulator::_done(gchar const *reason, bool alert_LPE) +{ invokeForAll(&PathManipulator::update, alert_LPE); invokeForAll(&PathManipulator::writeXML); DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_NODE, reason); @@ -846,7 +863,8 @@ void MultiPathManipulator::_done(gchar const *reason, bool alert_LPE) { } /** Commits changes to XML, adds undo stack entry and removes empty manipulators. */ -void MultiPathManipulator::_doneWithCleanup(gchar const *reason, bool alert_LPE) { +void MultiPathManipulator::_doneWithCleanup(gchar const *reason, bool alert_LPE) +{ _changed.block(); _done(reason, alert_LPE); cleanup(); @@ -857,16 +875,16 @@ void MultiPathManipulator::_doneWithCleanup(gchar const *reason, bool alert_LPE) guint32 MultiPathManipulator::_getOutlineColor(ShapeRole role, SPObject *object) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - switch(role) { - case SHAPE_ROLE_CLIPPING_PATH: - return prefs->getColor("/tools/nodes/clipping_path_color", 0x00ff00ff); - case SHAPE_ROLE_MASK: - return prefs->getColor("/tools/nodes/mask_color", 0x0000ffff); - case SHAPE_ROLE_LPE_PARAM: - return prefs->getColor("/tools/nodes/lpe_param_color", 0x009000ff); - case SHAPE_ROLE_NORMAL: - default: - return SP_ITEM(object)->highlight_color(); + switch (role) { + case SHAPE_ROLE_CLIPPING_PATH: + return prefs->getColor("/tools/nodes/clipping_path_color", 0x00ff00ff); + case SHAPE_ROLE_MASK: + return prefs->getColor("/tools/nodes/mask_color", 0x0000ffff); + case SHAPE_ROLE_LPE_PARAM: + return prefs->getColor("/tools/nodes/lpe_param_color", 0x009000ff); + case SHAPE_ROLE_NORMAL: + default: + return SP_ITEM(object)->highlight_color(); } } diff --git a/src/ui/tool/multi-path-manipulator.h b/src/ui/tool/multi-path-manipulator.h index 7fbb9591f76af38308fb48fb9dfce964b7278e0c..b0d4104f6b26a5b754dd7d3796f6e7cae19890d7 100644 --- a/src/ui/tool/multi-path-manipulator.h +++ b/src/ui/tool/multi-path-manipulator.h @@ -14,11 +14,12 @@ #include <cstddef> #include <sigc++/connection.h> -#include "node.h" + #include "commit-events.h" #include "manipulator.h" #include "modifier-tracker.h" #include "node-types.h" +#include "node.h" #include "shape-record.h" struct SPCanvasGroup; @@ -33,7 +34,8 @@ struct PathSharedData; /** * Manipulator that manages multiple path manipulators active at the same time. */ -class MultiPathManipulator : public PointManipulator { +class MultiPathManipulator : public PointManipulator +{ public: MultiPathManipulator(PathSharedData &data, sigc::connection &chg); ~MultiPathManipulator() override; @@ -74,16 +76,17 @@ public: 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 + /// shown in the status bar need updating private: - typedef std::pair<ShapeRecord, std::shared_ptr<PathManipulator> > MapPair; - typedef std::map<ShapeRecord, std::shared_ptr<PathManipulator> > MapType; + typedef std::pair<ShapeRecord, std::shared_ptr<PathManipulator>> MapPair; + typedef std::map<ShapeRecord, std::shared_ptr<PathManipulator>> MapType; template <typename R> - void invokeForAll(R (PathManipulator::*method)()) { - for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ) { + void invokeForAll(R (PathManipulator::*method)()) + { + for (MapType::iterator i = _mmap.begin(); i != _mmap.end();) { // Sometimes the PathManipulator got freed at loop end, thus // invalidating the iterator so make sure that next_i will // be a valid iterator and then assign i to it. @@ -99,20 +102,23 @@ private: } } template <typename R, typename A> - void invokeForAll(R (PathManipulator::*method)(A), A a) { - for (auto & i : _mmap) { + void invokeForAll(R (PathManipulator::*method)(A), A a) + { + for (auto &i : _mmap) { ((i.second.get())->*method)(a); } } template <typename R, typename A> - void invokeForAll(R (PathManipulator::*method)(A const &), A const &a) { - for (auto & i : _mmap) { + void invokeForAll(R (PathManipulator::*method)(A const &), A const &a) + { + for (auto &i : _mmap) { ((i.second.get())->*method)(a); } } template <typename R, typename A, typename B> - void invokeForAll(R (PathManipulator::*method)(A,B), A a, B b) { - for (auto & i : _mmap) { + void invokeForAll(R (PathManipulator::*method)(A, B), A a, B b) + { + for (auto &i : _mmap) { ((i.second.get())->*method)(a, b); } } @@ -123,8 +129,10 @@ private: guint32 _getOutlineColor(ShapeRole role, SPObject *object); MapType _mmap; + public: PathSharedData const &_path_data; + private: sigc::connection &_changed; ModifierTracker _tracker; diff --git a/src/ui/tool/node-types.h b/src/ui/tool/node-types.h index ee2d27fc964acb8c65f7cf41f97142aa8adb1d31..823a2584f1827d92935cd794cc30ffe59370bf0a 100644 --- a/src/ui/tool/node-types.h +++ b/src/ui/tool/node-types.h @@ -17,18 +17,20 @@ namespace Inkscape { namespace UI { /** Types of nodes supported in the node tool. */ -enum NodeType { - NODE_CUSP, ///< Cusp node - no handle constraints - NODE_SMOOTH, ///< Smooth node - handles must be colinear - NODE_AUTO, ///< Auto node - handles adjusted automatically based on neighboring nodes - NODE_SYMMETRIC, ///< Symmetric node - handles must be colinear and of equal length +enum NodeType +{ + NODE_CUSP, ///< Cusp node - no handle constraints + NODE_SMOOTH, ///< Smooth node - handles must be colinear + NODE_AUTO, ///< Auto node - handles adjusted automatically based on neighboring nodes + NODE_SYMMETRIC, ///< Symmetric node - handles must be colinear and of equal length NODE_LAST_REAL_TYPE, ///< Last real type of node - used for ctrl+click on a node NODE_PICK_BEST = 100 ///< Select type based on handle positions }; /** Types of segments supported in the node tool. */ -enum SegmentType { - SEGMENT_STRAIGHT, ///< Straight linear segment +enum SegmentType +{ + SEGMENT_STRAIGHT, ///< Straight linear segment SEGMENT_CUBIC_BEZIER ///< Bezier curve with two control points }; diff --git a/src/ui/tool/node.cpp b/src/ui/tool/node.cpp index 49149aac7dc6b97dddc73d78196352d10d0a64e8..73ada8c7ffc04a69c1208d28fd8f3211c0bfa30c 100644 --- a/src/ui/tool/node.cpp +++ b/src/ui/tool/node.cpp @@ -7,28 +7,24 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <iostream> -#include <stdexcept> +#include <2geom/bezier-utils.h> #include <boost/utility.hpp> - -#include <glib/gi18n.h> #include <gdk/gdkkeysyms.h> - -#include <2geom/bezier-utils.h> +#include <glib/gi18n.h> +#include <iostream> +#include <stdexcept> #include "desktop.h" +#include "display/sp-canvas-util.h" +#include "display/sp-ctrlline.h" #include "multi-path-manipulator.h" #include "snap.h" - -#include "display/sp-ctrlline.h" -#include "display/sp-canvas-util.h" - #include "ui/control-manager.h" #include "ui/tool/control-point-selection.h" #include "ui/tool/event-utils.h" #include "ui/tool/path-manipulator.h" -#include "ui/tools/node-tool.h" #include "ui/tools-switch.h" +#include "ui/tools/node-tool.h" #include "ui/widget/canvas.h" namespace { @@ -36,7 +32,7 @@ namespace { Inkscape::ControlType nodeTypeToCtrlType(Inkscape::UI::NodeType type) { Inkscape::ControlType result = Inkscape::CTRL_TYPE_NODE_CUSP; - switch(type) { + switch (type) { case Inkscape::UI::NODE_SMOOTH: result = Inkscape::CTRL_TYPE_NODE_SMOOTH; break; @@ -60,30 +56,32 @@ Inkscape::ControlType nodeTypeToCtrlType(Inkscape::UI::NodeType type) * Keeps cached value up to date with preferences option `/options/svgoutput/numericprecision` * to avoid costly direct reads * */ -class SvgOutputPrecisionWatcher : public Inkscape::Preferences::Observer { +class SvgOutputPrecisionWatcher : public Inkscape::Preferences::Observer +{ public: /// Returns absolute \a value`s rounding serialization error based on current preferences settings - static double error_of(double value) { - return value * instance().rel_error; - } + static double error_of(double value) { return value * instance().rel_error; } - void notify(const Inkscape::Preferences::Entry &new_val) override { + void notify(const Inkscape::Preferences::Entry &new_val) override + { int digits = new_val.getIntLimited(6, 1, 16); set_numeric_precision(digits); } private: - SvgOutputPrecisionWatcher() : Observer("/options/svgoutput/numericprecision"), rel_error(1) { + SvgOutputPrecisionWatcher() + : Observer("/options/svgoutput/numericprecision") + , rel_error(1) + { Inkscape::Preferences::get()->addObserver(*this); int digits = Inkscape::Preferences::get()->getIntLimited("/options/svgoutput/numericprecision", 6, 1, 16); set_numeric_precision(digits); } - ~SvgOutputPrecisionWatcher() override { - Inkscape::Preferences::get()->removeObserver(*this); - } + ~SvgOutputPrecisionWatcher() override { Inkscape::Preferences::get()->removeObserver(*this); } /// Update cached value of relative error with number of significant digits - void set_numeric_precision(int digits) { + void set_numeric_precision(int digits) + { double relative_error = 0.5; // the error is half of last digit while (digits > 0) { relative_error /= 10; @@ -92,7 +90,8 @@ private: rel_error = relative_error; } - static SvgOutputPrecisionWatcher &instance() { + static SvgOutputPrecisionWatcher &instance() + { static SvgOutputPrecisionWatcher _instance; return _instance; } @@ -101,7 +100,8 @@ private: }; /// Returns absolute error of \a point as if serialized to svg with current preferences -double serializing_error_of(const Geom::Point &point) { +double serializing_error_of(const Geom::Point &point) +{ return SvgOutputPrecisionWatcher::error_of(point.length()); } @@ -114,7 +114,8 @@ double serializing_error_of(const Geom::Point &point) { * would declare it's check algorithm as part of the public API. * * */ -bool are_collinear_within_serializing_error(const Geom::Point &A, const Geom::Point &B, const Geom::Point &C) { +bool are_collinear_within_serializing_error(const Geom::Point &A, const Geom::Point &B, const Geom::Point &C) +{ const double tolerance_factor = 10; // to account other factors which increase uncertainty const double tolerance_A = serializing_error_of(A) * tolerance_factor; const double tolerance_B = serializing_error_of(B) * tolerance_factor; @@ -122,10 +123,9 @@ bool are_collinear_within_serializing_error(const Geom::Point &A, const Geom::Po const double CB_length = (B - C).length(); const double AB_length = (B - A).length(); Geom::Point C_reflect_scaled = B + (B - C) / CB_length * AB_length; - double tolerance_C_reflect_scaled = tolerance_B - + (tolerance_B + tolerance_C) - * (1 + (tolerance_A + tolerance_B) / AB_length) - * (1 + (tolerance_C + tolerance_B) / CB_length); + double tolerance_C_reflect_scaled = tolerance_B + (tolerance_B + tolerance_C) * + (1 + (tolerance_A + tolerance_B) / AB_length) * + (1 + (tolerance_C + tolerance_B) / CB_length); return Geom::are_near(C_reflect_scaled, A, tolerance_C_reflect_scaled + tolerance_A); } @@ -135,7 +135,7 @@ namespace Inkscape { namespace UI { const double NO_POWER = 0.0; -const double DEFAULT_START_POWER = 1.0/3.0; +const double DEFAULT_START_POWER = 1.0 / 3.0; ControlPoint::ColorSet Node::node_colors = { {0xbfbfbf00, 0x000000ff}, // normal fill, stroke @@ -159,18 +159,29 @@ ControlPoint::ColorSet Handle::_handle_colors = { std::ostream &operator<<(std::ostream &out, NodeType type) { - switch(type) { - case NODE_CUSP: out << 'c'; break; - case NODE_SMOOTH: out << 's'; break; - case NODE_AUTO: out << 'a'; break; - case NODE_SYMMETRIC: out << 'z'; break; - default: out << 'b'; break; + switch (type) { + case NODE_CUSP: + out << 'c'; + break; + case NODE_SMOOTH: + out << 's'; + break; + case NODE_AUTO: + out << 'a'; + break; + case NODE_SYMMETRIC: + out << 'z'; + break; + default: + out << 'b'; + break; } return out; } /** Computes an unit vector of the direction from first to second control point */ -static Geom::Point direction(Geom::Point const &first, Geom::Point const &second) { +static Geom::Point direction(Geom::Point const &first, Geom::Point const &second) +{ return Geom::unit_vector(second - first); } @@ -180,20 +191,18 @@ 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, - CTRL_TYPE_ADJ_HANDLE, - _handle_colors, data.handle_group), - _parent(parent), - _handle_line(ControlManager::getManager().createControlLine(data.handle_line_group)), - _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) { setVisible(false); } Handle::~Handle() { - //sp_canvas_item_hide(_handle_line); + // sp_canvas_item_hide(_handle_line); sp_canvas_item_destroy(_handle_line); } @@ -211,7 +220,7 @@ void Handle::move(Geom::Point const &new_pos) { Handle *other = this->other(); Node *node_towards = _parent->nodeToward(this); // node in direction of this handle - Node *node_away = _parent->nodeAwayFrom(this); // node in the opposite direction + Node *node_away = _parent->nodeAwayFrom(this); // node in the opposite direction Handle *towards = node_towards ? node_towards->handleAwayFrom(_parent) : nullptr; Handle *towards_second = node_towards ? node_towards->handleToward(_parent) : nullptr; double bspline_weight = 0.0; @@ -225,13 +234,13 @@ void Handle::move(Geom::Point const &new_pos) } else { // Only 1 handle becomes degenerate switch (_parent->type()) { - case NODE_AUTO: - case NODE_SYMMETRIC: - _parent->setType(NODE_SMOOTH, false); - break; - default: - // do nothing for other node types - break; + case NODE_AUTO: + case NODE_SYMMETRIC: + _parent->setType(NODE_SMOOTH, false); + break; + default: + // do nothing for other node types + break; } } // If the segment between the handle and the node in its direction becomes linear, @@ -247,7 +256,7 @@ void Handle::move(Geom::Point const &new_pos) setPosition(new_pos); // move the handle and its opposite the same proportion - if(_pm()._isBSpline()){ + if (_pm()._isBSpline()) { setPosition(_pm()._bsplineHandleReposition(this, false)); bspline_weight = _pm()._bsplineHandlePosition(this, false); this->other()->setPosition(_pm()._bsplineHandleReposition(this->other(), bspline_weight)); @@ -271,34 +280,35 @@ void Handle::move(Geom::Point const &new_pos) setRelativePos(new_delta); // move the handle and its opposite the same proportion - if(_pm()._isBSpline()){ + if (_pm()._isBSpline()) { setPosition(_pm()._bsplineHandleReposition(this, false)); bspline_weight = _pm()._bsplineHandlePosition(this, false); this->other()->setPosition(_pm()._bsplineHandleReposition(this->other(), bspline_weight)); } - + return; } switch (_parent->type()) { - case NODE_AUTO: - _parent->setType(NODE_SMOOTH, false); - // fall through - auto nodes degrade into smooth nodes - case NODE_SMOOTH: { - // for smooth nodes, we need to rotate the opposite handle - // so that it's collinear with the dragged one, while conserving length. - other->setDirection(new_pos, *_parent); + case NODE_AUTO: + _parent->setType(NODE_SMOOTH, false); + // fall through - auto nodes degrade into smooth nodes + case NODE_SMOOTH: { + // for smooth nodes, we need to rotate the opposite handle + // so that it's collinear with the dragged one, while conserving length. + other->setDirection(new_pos, *_parent); } break; - case NODE_SYMMETRIC: - // for symmetric nodes, place the other handle on the opposite side - other->setRelativePos(-(new_pos - _parent->position())); - break; - default: break; + case NODE_SYMMETRIC: + // for symmetric nodes, place the other handle on the opposite side + other->setRelativePos(-(new_pos - _parent->position())); + break; + default: + break; } setPosition(new_pos); // move the handle and its opposite the same proportion - if(_pm()._isBSpline()){ + if (_pm()._isBSpline()) { setPosition(_pm()._bsplineHandleReposition(this, false)); bspline_weight = _pm()._bsplineHandlePosition(this, false); this->other()->setPosition(_pm()._bsplineHandleReposition(this->other(), bspline_weight)); @@ -314,7 +324,8 @@ void Handle::setPosition(Geom::Point const &p) // update degeneration info and visibility if (Geom::are_near(position(), _parent->position())) _degenerate = true; - else _degenerate = false; + else + _degenerate = false; if (_parent->_handles_shown && _parent->visible() && !_degenerate) { setVisible(true); @@ -325,7 +336,8 @@ void Handle::setPosition(Geom::Point const &p) void Handle::setLength(double len) { - if (isDegenerate()) return; + if (isDegenerate()) + return; Geom::Point dir = Geom::unit_vector(relativePos()); setRelativePos(dir * len); } @@ -351,96 +363,92 @@ void Handle::setDirection(Geom::Point const &dir) */ char const *Handle::handle_type_to_localized_string(NodeType type) { - switch(type) { - case NODE_CUSP: - return _("Corner node handle"); - case NODE_SMOOTH: - return _("Smooth node handle"); - case NODE_SYMMETRIC: - return _("Symmetric node handle"); - case NODE_AUTO: - return _("Auto-smooth node handle"); - default: - return ""; + switch (type) { + case NODE_CUSP: + return _("Corner node handle"); + case NODE_SMOOTH: + return _("Smooth node handle"); + case NODE_SYMMETRIC: + return _("Symmetric node handle"); + case NODE_AUTO: + return _("Auto-smooth node handle"); + default: + return ""; } } bool Handle::_eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) { - switch (event->type) - { - case GDK_KEY_PRESS: + switch (event->type) { + case GDK_KEY_PRESS: - switch (shortcut_key(event->key)) - { - case GDK_KEY_s: - case GDK_KEY_S: + switch (shortcut_key(event->key)) { + case GDK_KEY_s: + case GDK_KEY_S: - /* if Shift+S is pressed while hovering over a cusp node handle, - hold the handle in place; otherwise, process normally. - this handle is guaranteed not to be degenerate. */ + /* if Shift+S is pressed while hovering over a cusp node handle, + hold the handle in place; otherwise, process normally. + this handle is guaranteed not to be degenerate. */ - if (held_only_shift(event->key) && _parent->_type == NODE_CUSP) { + if (held_only_shift(event->key) && _parent->_type == NODE_CUSP) { + // make opposite handle collinear, + // but preserve length, unless degenerate + if (other()->isDegenerate()) + other()->setRelativePos(-relativePos()); + else + other()->setDirection(-relativePos()); + _parent->setType(NODE_SMOOTH, false); - // make opposite handle collinear, - // but preserve length, unless degenerate - if (other()->isDegenerate()) - other()->setRelativePos(-relativePos()); - else - other()->setDirection(-relativePos()); - _parent->setType(NODE_SMOOTH, false); + // update display + _parent->_pm().update(); - // update display - _parent->_pm().update(); + // update undo history + _parent->_pm()._commit(_("Change node type")); - // update undo history - _parent->_pm()._commit(_("Change node type")); - - return true; - } - break; + return true; + } + break; - case GDK_KEY_y: - case GDK_KEY_Y: + case GDK_KEY_y: + case GDK_KEY_Y: - /* if Shift+Y is pressed while hovering over a cusp, smooth, or auto node handle, - hold the handle in place; otherwise, process normally. - this handle is guaranteed not to be degenerate. */ + /* if Shift+Y is pressed while hovering over a cusp, smooth, or auto node handle, + hold the handle in place; otherwise, process normally. + this handle is guaranteed not to be degenerate. */ - if (held_only_shift(event->key) && (_parent->_type == NODE_CUSP || - _parent->_type == NODE_SMOOTH || - _parent->_type == NODE_AUTO)) { + if (held_only_shift(event->key) && + (_parent->_type == NODE_CUSP || _parent->_type == NODE_SMOOTH || _parent->_type == NODE_AUTO)) { + // make opposite handle collinear, and of equal length + other()->setRelativePos(-relativePos()); + _parent->setType(NODE_SYMMETRIC, false); - // make opposite handle collinear, and of equal length - other()->setRelativePos(-relativePos()); - _parent->setType(NODE_SYMMETRIC, false); + // update display + _parent->_pm().update(); - // update display - _parent->_pm().update(); + // update undo history + _parent->_pm()._commit(_("Change node type")); - // update undo history - _parent->_pm()._commit(_("Change node type")); - - return true; + return true; + } + break; } break; - } - break; - case GDK_2BUTTON_PRESS: + case GDK_2BUTTON_PRESS: - // double-click event to set the handles of a node - // to the position specified by DEFAULT_START_POWER - handle_2button_press(); - break; + // double-click event to set the handles of a node + // to the position specified by DEFAULT_START_POWER + handle_2button_press(); + break; } return ControlPoint::_eventHandler(event_context, event); } // this function moves the handle and its opposite to the position specified by DEFAULT_START_POWER -void Handle::handle_2button_press(){ - if(_pm()._isBSpline()){ +void Handle::handle_2button_press() +{ + if (_pm()._isBSpline()) { setPosition(_pm()._bsplineHandleReposition(this, DEFAULT_START_POWER)); this->other()->setPosition(_pm()._bsplineHandleReposition(this->other(), DEFAULT_START_POWER)); _pm().update(); @@ -478,8 +486,8 @@ void Handle::dragged(Geom::Point &new_pos, GdkEventMotion *event) // direction of the handle, change to Ray instead of Line Geom::Line original_line(parent_pos, origin); Geom::Line perp_line(parent_pos, parent_pos + Geom::rot90(origin - parent_pos)); - Geom::Point snap_pos = parent_pos + Geom::constrain_angle( - Geom::Point(0,0), new_pos - parent_pos, snaps, Geom::Point(1,0)); + Geom::Point snap_pos = + parent_pos + Geom::constrain_angle(Geom::Point(0, 0), new_pos - parent_pos, snaps, Geom::Point(1, 0)); Geom::Point orig_pos = original_line.pointAt(original_line.nearestTime(new_pos)); Geom::Point perp_pos = perp_line.pointAt(perp_line.nearestTime(new_pos)); @@ -494,12 +502,13 @@ void Handle::dragged(Geom::Point &new_pos, GdkEventMotion *event) ctrl_constraint = Inkscape::Snapper::SnapConstraint(parent_pos, parent_pos - perp_pos); } new_pos = result; - // move the handle and its opposite in X fixed positions depending on parameter "steps with control" + // move the handle and its opposite in X fixed positions depending on parameter "steps with control" // by default in live BSpline - if(_pm()._isBSpline()){ + if (_pm()._isBSpline()) { setPosition(new_pos); int steps = _pm()._bsplineGetSteps(); - new_pos=_pm()._bsplineHandleReposition(this,ceilf(_pm()._bsplineHandlePosition(this, false)*steps)/steps); + new_pos = + _pm()._bsplineHandleReposition(this, ceilf(_pm()._bsplineHandlePosition(this, false) * steps) / steps); } } @@ -508,15 +517,14 @@ void Handle::dragged(Geom::Point &new_pos, GdkEventMotion *event) if (snap && !_pm()._isBSpline()) { ControlPointSelection::Set &nodes = _parent->_selection.allPoints(); for (auto node : nodes) { - Node *n = static_cast<Node*>(node); + Node *n = static_cast<Node *>(node); unselected.push_back(n->snapCandidatePoint()); } sm.setupIgnoreSelection(_desktop, true, &unselected); Node *node_away = _parent->nodeAwayFrom(this); if (_parent->type() == NODE_SMOOTH && Node::_is_line_segment(_parent, node_away)) { - Inkscape::Snapper::SnapConstraint cl(_parent->position(), - _parent->position() - node_away->position()); + Inkscape::Snapper::SnapConstraint cl(_parent->position(), _parent->position() - node_away->position()); Inkscape::SnappedPoint p; p = sm.constrainedSnap(Inkscape::SnapCandidatePoint(new_pos, SNAPSOURCE_NODE_HANDLE), cl); new_pos = p.getPoint(); @@ -533,7 +541,6 @@ void Handle::dragged(Geom::Point &new_pos, GdkEventMotion *event) sm.unSetup(); } - // with Shift, if the node is cusp, rotate the other handle as well if (_parent->type() == NODE_CUSP && !_drag_out) { if (held_shift(*event)) { @@ -546,8 +553,8 @@ void Handle::dragged(Geom::Point &new_pos, GdkEventMotion *event) } } // if it is BSpline, but SHIFT or CONTROL are not pressed, fix it in the original position - if(_pm()._isBSpline() && !held_shift(*event) && !held_control(*event)){ - new_pos=_last_drag_origin(); + if (_pm()._isBSpline() && !held_shift(*event) && !held_control(*event)) { + new_pos = _last_drag_origin(); } move(new_pos); // needed for correct update, even though it's redundant _pm().update(); @@ -598,7 +605,8 @@ Handle *Handle::other() } } -static double snap_increment_degrees() { +static double snap_increment_degrees() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000); return 180.0 / snaps; @@ -613,127 +621,104 @@ Glib::ustring Handle::_getTip(unsigned state) const bool isBSpline = _pm()._isBSpline(); bool can_shift_rotate = _parent->type() == NODE_CUSP && !other()->isDegenerate(); Glib::ustring s = C_("Path handle tip", - "node control handle"); // not expected + "node control handle"); // not expected if (state_held_alt(state) && !isBSpline) { if (state_held_control(state)) { if (state_held_shift(state) && can_shift_rotate) { - s = format_tip(C_("Path handle tip", - "<b>Shift+Ctrl+Alt</b>: " - "preserve length and snap rotation angle to %g° increments, " - "and rotate both handles"), - snap_increment_degrees()); - } - else { - s = format_tip(C_("Path handle tip", - "<b>Ctrl+Alt</b>: " - "preserve length and snap rotation angle to %g° increments"), - snap_increment_degrees()); + s = format_tip(C_("Path handle tip", "<b>Shift+Ctrl+Alt</b>: " + "preserve length and snap rotation angle to %g° increments, " + "and rotate both handles"), + snap_increment_degrees()); + } else { + s = format_tip(C_("Path handle tip", "<b>Ctrl+Alt</b>: " + "preserve length and snap rotation angle to %g° increments"), + snap_increment_degrees()); } - } - else { + } else { if (state_held_shift(state) && can_shift_rotate) { - s = C_("Path handle tip", - "<b>Shift+Alt</b>: preserve handle length and rotate both handles"); - } - else { - s = C_("Path handle tip", - "<b>Alt</b>: preserve handle length while dragging"); + s = C_("Path handle tip", "<b>Shift+Alt</b>: preserve handle length and rotate both handles"); + } else { + s = C_("Path handle tip", "<b>Alt</b>: preserve handle length while dragging"); } } - } - else { + } else { if (state_held_control(state)) { if (state_held_shift(state) && can_shift_rotate && !isBSpline) { - s = format_tip(C_("Path handle tip", - "<b>Shift+Ctrl</b>: " - "snap rotation angle to %g° increments, and rotate both handles"), - snap_increment_degrees()); - } - else if (isBSpline) { - s = C_("Path handle tip", - "<b>Ctrl</b>: " - "Snap handle to steps defined in BSpline Live Path Effect"); - } - else { - s = format_tip(C_("Path handle tip", - "<b>Ctrl</b>: " - "snap rotation angle to %g° increments, click to retract"), - snap_increment_degrees()); + s = format_tip(C_("Path handle tip", "<b>Shift+Ctrl</b>: " + "snap rotation angle to %g° increments, and rotate both handles"), + snap_increment_degrees()); + } else if (isBSpline) { + s = C_("Path handle tip", "<b>Ctrl</b>: " + "Snap handle to steps defined in BSpline Live Path Effect"); + } else { + s = format_tip(C_("Path handle tip", "<b>Ctrl</b>: " + "snap rotation angle to %g° increments, click to retract"), + snap_increment_degrees()); } - } - else if (state_held_shift(state) && can_shift_rotate && !isBSpline) { - s = C_("Path handle tip", - "<b>Shift</b>: rotate both handles by the same angle"); - } - else if (state_held_shift(state) && isBSpline) { - s = C_("Path handle tip", - "<b>Shift</b>: move handle"); - } - else { + } else if (state_held_shift(state) && can_shift_rotate && !isBSpline) { + s = C_("Path handle tip", "<b>Shift</b>: rotate both handles by the same angle"); + } else if (state_held_shift(state) && isBSpline) { + s = C_("Path handle tip", "<b>Shift</b>: move handle"); + } else { char const *handletype = handle_type_to_localized_string(_parent->_type); char const *more; if (can_shift_rotate && !isBSpline) { - more = C_("Path handle tip", - "Shift, Ctrl, Alt"); - } - else if (isBSpline) { - more = C_("Path handle tip", - "Ctrl"); - } - else { - more = C_("Path handle tip", - "Ctrl, Alt"); + more = C_("Path handle tip", "Shift, Ctrl, Alt"); + } else if (isBSpline) { + more = C_("Path handle tip", "Ctrl"); + } else { + more = C_("Path handle tip", "Ctrl, Alt"); } if (_parent->type() == NODE_CUSP) { - s = format_tip(C_("Path handle tip", - "<b>%s</b>: " - "drag to shape the path" ", " - "hover to lock" ", " - "Shift+S to make smooth" ", " - "Shift+Y to make symmetric" ". " - "(more: %s)"), + s = format_tip(C_("Path handle tip", "<b>%s</b>: " + "drag to shape the path" + ", " + "hover to lock" + ", " + "Shift+S to make smooth" + ", " + "Shift+Y to make symmetric" + ". " + "(more: %s)"), handletype, more); - } - else if (_parent->type() == NODE_SMOOTH) { - s = format_tip(C_("Path handle tip", - "<b>%s</b>: " - "drag to shape the path" ", " - "hover to lock" ", " - "Shift+Y to make symmetric" ". " - "(more: %s)"), + } else if (_parent->type() == NODE_SMOOTH) { + s = format_tip(C_("Path handle tip", "<b>%s</b>: " + "drag to shape the path" + ", " + "hover to lock" + ", " + "Shift+Y to make symmetric" + ". " + "(more: %s)"), handletype, more); - } - else if (_parent->type() == NODE_AUTO) { - s = format_tip(C_("Path handle tip", - "<b>%s</b>: " - "drag to make smooth, " - "hover to lock" ", " - "Shift+Y to make symmetric" ". " - "(more: %s)"), + } else if (_parent->type() == NODE_AUTO) { + s = format_tip(C_("Path handle tip", "<b>%s</b>: " + "drag to make smooth, " + "hover to lock" + ", " + "Shift+Y to make symmetric" + ". " + "(more: %s)"), handletype, more); - } - else if (_parent->type() == NODE_SYMMETRIC) { - s = format_tip(C_("Path handle tip", - "<b>%s</b>: " - "drag to shape the path" ". " - "(more: %s)"), + } else if (_parent->type() == NODE_SYMMETRIC) { + s = format_tip(C_("Path handle tip", "<b>%s</b>: " + "drag to shape the path" + ". " + "(more: %s)"), handletype, more); - } - else if (isBSpline) { + } else if (isBSpline) { double power = _pm()._bsplineHandlePosition(h); - s = format_tip(C_("Path handle tip", - "<b>BSpline node handle</b> (%.3g power): " - "Shift-drag to move, " - "double-click to reset. " - "(more: %s)"), + s = format_tip(C_("Path handle tip", "<b>BSpline node handle</b> (%.3g power): " + "Shift-drag to move, " + "double-click to reset. " + "(more: %s)"), power, more); - } - else { + } else { s = C_("Path handle tip", - "<b>unknown node handle</b>"); // not expected + "<b>unknown node handle</b>"); // not expected } } } @@ -741,41 +726,39 @@ Glib::ustring Handle::_getTip(unsigned state) const return (s); } -Glib::ustring Handle::_getDragTip(GdkEventMotion */*event*/) const +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()); + 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); - + 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"); Glib::ustring x = x_q.string(_desktop->namedview->display_units); Glib::ustring y = y_q.string(_desktop->namedview->display_units); Glib::ustring len = len_q.string(_desktop->namedview->display_units); - Glib::ustring ret = format_tip(C_("Path handle tip", - "Move handle by %s, %s; angle %.2f°, length %s"), x.c_str(), y.c_str(), angle, len.c_str()); + Glib::ustring ret = format_tip(C_("Path handle tip", "Move handle by %s, %s; angle %.2f°, length %s"), x.c_str(), + y.c_str(), angle, len.c_str()); return ret; } -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) +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(); + return const_cast<Node *>(this)->_next(); } // NOTE: not using iterators won't make this much quicker because iterators can be 100% inlined. @@ -810,18 +793,18 @@ void Node::move(Geom::Point const &new_pos) Geom::Point old_pos = position(); Geom::Point delta = new_pos - position(); - // save the previous nodes strength to apply it again once the node is moved + // save the previous nodes strength to apply it again once the node is moved double nodeWeight = NO_POWER; double nextNodeWeight = NO_POWER; double prevNodeWeight = NO_POWER; Node *n = this; - Node * nextNode = n->nodeToward(n->front()); - Node * prevNode = n->nodeToward(n->back()); - nodeWeight = fmax(_pm()._bsplineHandlePosition(n->front(), false),_pm()._bsplineHandlePosition(n->back(), false)); - if(prevNode){ + Node *nextNode = n->nodeToward(n->front()); + Node *prevNode = n->nodeToward(n->back()); + nodeWeight = fmax(_pm()._bsplineHandlePosition(n->front(), false), _pm()._bsplineHandlePosition(n->back(), false)); + if (prevNode) { prevNodeWeight = _pm()._bsplineHandlePosition(prevNode->front()); } - if(nextNode){ + if (nextNode) { nextNodeWeight = _pm()._bsplineHandlePosition(nextNode->back()); } @@ -835,13 +818,13 @@ void Node::move(Geom::Point const &new_pos) _fixNeighbors(old_pos, new_pos); // move the affected handles. First the node ones, later the adjoining ones. - if(_pm()._isBSpline()){ - _front.setPosition(_pm()._bsplineHandleReposition(this->front(),nodeWeight)); - _back.setPosition(_pm()._bsplineHandleReposition(this->back(),nodeWeight)); - if(prevNode){ + if (_pm()._isBSpline()) { + _front.setPosition(_pm()._bsplineHandleReposition(this->front(), nodeWeight)); + _back.setPosition(_pm()._bsplineHandleReposition(this->back(), nodeWeight)); + if (prevNode) { prevNode->front()->setPosition(_pm()._bsplineHandleReposition(prevNode->front(), prevNodeWeight)); } - if(nextNode){ + if (nextNode) { nextNode->back()->setPosition(_pm()._bsplineHandleReposition(nextNode->back(), nextNodeWeight)); } } @@ -850,21 +833,20 @@ void Node::move(Geom::Point const &new_pos) void Node::transform(Geom::Affine const &m) { - Geom::Point old_pos = position(); - // save the previous nodes strength to apply it again once the node is moved + // save the previous nodes strength to apply it again once the node is moved double nodeWeight = NO_POWER; double nextNodeWeight = NO_POWER; double prevNodeWeight = NO_POWER; Node *n = this; - Node * nextNode = n->nodeToward(n->front()); - Node * prevNode = n->nodeToward(n->back()); + Node *nextNode = n->nodeToward(n->front()); + Node *prevNode = n->nodeToward(n->back()); nodeWeight = _pm()._bsplineHandlePosition(n->front()); - if(prevNode){ + if (prevNode) { prevNodeWeight = _pm()._bsplineHandlePosition(prevNode->front()); } - if(nextNode){ + if (nextNode) { nextNodeWeight = _pm()._bsplineHandlePosition(nextNode->back()); } @@ -877,13 +859,13 @@ void Node::transform(Geom::Affine const &m) _fixNeighbors(old_pos, position()); // move the involved handles. First the node ones, later the adjoining ones. - if(_pm()._isBSpline()){ + if (_pm()._isBSpline()) { _front.setPosition(_pm()._bsplineHandleReposition(this->front(), nodeWeight)); _back.setPosition(_pm()._bsplineHandleReposition(this->back(), nodeWeight)); - if(prevNode){ + if (prevNode) { prevNode->front()->setPosition(_pm()._bsplineHandleReposition(prevNode->front(), prevNodeWeight)); } - if(nextNode){ + if (nextNode) { nextNode->back()->setPosition(_pm()._bsplineHandleReposition(nextNode->back(), nextNodeWeight)); } } @@ -903,10 +885,13 @@ void Node::_fixNeighbors(Geom::Point const &old_pos, Geom::Point const &new_pos) // and invariants that are based on positions of those nodes for this one. // Fix auto handles - if (_type == NODE_AUTO) _updateAutoHandles(); + if (_type == NODE_AUTO) + _updateAutoHandles(); if (old_pos != new_pos) { - if (_next() && _next()->_type == NODE_AUTO) _next()->_updateAutoHandles(); - if (_prev() && _prev()->_type == NODE_AUTO) _prev()->_updateAutoHandles(); + if (_next() && _next()->_type == NODE_AUTO) + _next()->_updateAutoHandles(); + if (_prev() && _prev()->_type == NODE_AUTO) + _prev()->_updateAutoHandles(); } /* Fix smooth handles at the ends of linear segments. @@ -922,7 +907,8 @@ void Node::_fixNeighbors(Geom::Point const &old_pos, Geom::Point const &new_pos) handle = &_front; other = _prev(); other_handle = &_prev()->_back; - } else return; + } else + return; if (_type == NODE_SMOOTH && !handle->isDegenerate()) { handle->setDirection(other->position(), new_pos); @@ -971,7 +957,6 @@ void Node::showHandles(bool v) if (!_back.isDegenerate()) { _back.setVisible(v); } - } void Node::updateHandles() @@ -982,7 +967,6 @@ void Node::updateHandles() _back._handleControlStyling(); } - void Node::setType(NodeType type, bool update_handles) { if (type == NODE_PICK_BEST) { @@ -995,88 +979,93 @@ void Node::setType(NodeType type, bool update_handles) // handle degenerate handles appropriately if (update_handles) { switch (type) { - case NODE_CUSP: - // nothing to do - break; - case NODE_AUTO: - // auto handles make no sense for endnodes - if (isEndNode()) return; - _updateAutoHandles(); - break; - case NODE_SMOOTH: { - // ignore attempts to make smooth endnodes. - if (isEndNode()) return; - // rotate handles to be collinear - // for degenerate nodes set positions like auto handles - bool prev_line = _is_line_segment(_prev(), this); - bool next_line = _is_line_segment(this, _next()); - if (_type == NODE_SMOOTH) { - // For a node that is already smooth and has a degenerate handle, - // drag out the second handle without changing the direction of the first one. - if (_front.isDegenerate()) { - double dist = Geom::distance(_next()->position(), position()); - _front.setRelativePos(Geom::unit_vector(-_back.relativePos()) * dist / 3); - } - if (_back.isDegenerate()) { - double dist = Geom::distance(_prev()->position(), position()); - _back.setRelativePos(Geom::unit_vector(-_front.relativePos()) * dist / 3); - } - } else if (isDegenerate()) { + case NODE_CUSP: + // nothing to do + break; + case NODE_AUTO: + // auto handles make no sense for endnodes + if (isEndNode()) + return; _updateAutoHandles(); - } else if (_front.isDegenerate()) { - // if the front handle is degenerate and next path segment is a line, make back collinear; - // otherwise, pull out the other handle to 1/3 of distance to prev. - if (next_line) { - _back.setDirection(*_next(), *this); - } else if (_prev()) { - Geom::Point dir = direction(_back, *this); - _front.setRelativePos(Geom::distance(_prev()->position(), position()) / 3 * dir); - } - } else if (_back.isDegenerate()) { - if (prev_line) { - _front.setDirection(*_prev(), *this); - } else if (_next()) { - Geom::Point dir = direction(_front, *this); - _back.setRelativePos(Geom::distance(_next()->position(), position()) / 3 * dir); + break; + case NODE_SMOOTH: { + // ignore attempts to make smooth endnodes. + if (isEndNode()) + return; + // rotate handles to be collinear + // for degenerate nodes set positions like auto handles + bool prev_line = _is_line_segment(_prev(), this); + bool next_line = _is_line_segment(this, _next()); + if (_type == NODE_SMOOTH) { + // For a node that is already smooth and has a degenerate handle, + // drag out the second handle without changing the direction of the first one. + if (_front.isDegenerate()) { + double dist = Geom::distance(_next()->position(), position()); + _front.setRelativePos(Geom::unit_vector(-_back.relativePos()) * dist / 3); + } + if (_back.isDegenerate()) { + double dist = Geom::distance(_prev()->position(), position()); + _back.setRelativePos(Geom::unit_vector(-_front.relativePos()) * dist / 3); + } + } else if (isDegenerate()) { + _updateAutoHandles(); + } else if (_front.isDegenerate()) { + // if the front handle is degenerate and next path segment is a line, make back collinear; + // otherwise, pull out the other handle to 1/3 of distance to prev. + if (next_line) { + _back.setDirection(*_next(), *this); + } else if (_prev()) { + Geom::Point dir = direction(_back, *this); + _front.setRelativePos(Geom::distance(_prev()->position(), position()) / 3 * dir); + } + } else if (_back.isDegenerate()) { + if (prev_line) { + _front.setDirection(*_prev(), *this); + } else if (_next()) { + Geom::Point dir = direction(_front, *this); + _back.setRelativePos(Geom::distance(_next()->position(), position()) / 3 * dir); + } + } else { + /* both handles are extended. make collinear while keeping length. + first make back collinear with the vector front ---> back, + then make front collinear with back ---> node. + (not back ---> front, because back's position was changed in the first call) */ + _back.setDirection(_front, _back); + _front.setDirection(_back, *this); } - } else { - /* both handles are extended. make collinear while keeping length. - first make back collinear with the vector front ---> back, - then make front collinear with back ---> node. - (not back ---> front, because back's position was changed in the first call) */ - _back.setDirection(_front, _back); - _front.setDirection(_back, *this); - } } break; - case NODE_SYMMETRIC: - if (isEndNode()) return; // symmetric handles make no sense for endnodes - if (isDegenerate()) { - // similar to auto handles but set the same length for both - Geom::Point vec_next = _next()->position() - position(); - Geom::Point vec_prev = _prev()->position() - position(); - double len_next = vec_next.length(), len_prev = vec_prev.length(); - double len = (len_next + len_prev) / 6; // take 1/3 of average - if (len == 0) return; - - Geom::Point dir = Geom::unit_vector((len_prev / len_next) * vec_next - vec_prev); - _back.setRelativePos(-dir * len); - _front.setRelativePos(dir * len); - } else { - // Both handles are extended. Compute average length, use direction from - // back handle to front handle. This also works correctly for degenerates - double len = (_front.length() + _back.length()) / 2; - Geom::Point dir = direction(_back, _front); - _front.setRelativePos(dir * len); - _back.setRelativePos(-dir * len); - } - break; - default: break; + case NODE_SYMMETRIC: + if (isEndNode()) + return; // symmetric handles make no sense for endnodes + if (isDegenerate()) { + // similar to auto handles but set the same length for both + Geom::Point vec_next = _next()->position() - position(); + Geom::Point vec_prev = _prev()->position() - position(); + double len_next = vec_next.length(), len_prev = vec_prev.length(); + double len = (len_next + len_prev) / 6; // take 1/3 of average + if (len == 0) + return; + + Geom::Point dir = Geom::unit_vector((len_prev / len_next) * vec_next - vec_prev); + _back.setRelativePos(-dir * len); + _front.setRelativePos(dir * len); + } else { + // Both handles are extended. Compute average length, use direction from + // back handle to front handle. This also works correctly for degenerates + double len = (_front.length() + _back.length()) / 2; + Geom::Point dir = direction(_back, _front); + _front.setRelativePos(dir * len); + _back.setRelativePos(-dir * len); + } + break; + default: + break; } // in node type changes, for BSpline traces, we can either maintain them // with NO_POWER power in border mode, or give them the default power in curve mode. - if(_pm()._isBSpline()){ + if (_pm()._isBSpline()) { double weight = NO_POWER; - if(_pm()._bsplineHandlePosition(this->front()) != NO_POWER ){ + if (_pm()._bsplineHandlePosition(this->front()) != NO_POWER) { weight = DEFAULT_START_POWER; } _front.setPosition(_pm()._bsplineHandleReposition(this->front(), weight)); @@ -1097,7 +1086,8 @@ void Node::pickBestType() bool neither_degen = !front_degen && !back_degen; do { // if both handles are degenerate, do nothing - if (both_degen) break; + if (both_degen) + break; // if neither are degenerate, check their respective positions if (neither_degen) { // for now do not automatically make nodes symmetric, it can be annoying @@ -1142,11 +1132,16 @@ void Node::sink() NodeType Node::parse_nodetype(char x) { switch (x) { - case 'a': return NODE_AUTO; - case 'c': return NODE_CUSP; - case 's': return NODE_SMOOTH; - case 'z': return NODE_SYMMETRIC; - default: return NODE_PICK_BEST; + case 'a': + return NODE_AUTO; + case 'c': + return NODE_CUSP; + case 's': + return NODE_SMOOTH; + case 'z': + return NODE_SYMMETRIC; + default: + return NODE_PICK_BEST; } } @@ -1154,48 +1149,47 @@ bool Node::_eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent { int dir = 0; - switch (event->type) - { - case GDK_SCROLL: - if (event->scroll.direction == GDK_SCROLL_UP) { - dir = 1; - } else if (event->scroll.direction == GDK_SCROLL_DOWN) { - dir = -1; - } else if (event->scroll.direction == GDK_SCROLL_SMOOTH) { - dir = event->scroll.delta_y > 0 ? -1 : 1; - } else { - break; - } - if (held_control(event->scroll)) { - _linearGrow(dir); - } else { - _selection.spatialGrow(this, dir); - } - return true; - case GDK_KEY_PRESS: - switch (shortcut_key(event->key)) - { - case GDK_KEY_Page_Up: - dir = 1; - break; - case GDK_KEY_Page_Down: - dir = -1; - break; - default: goto bail_out; - } + switch (event->type) { + case GDK_SCROLL: + if (event->scroll.direction == GDK_SCROLL_UP) { + dir = 1; + } else if (event->scroll.direction == GDK_SCROLL_DOWN) { + dir = -1; + } else if (event->scroll.direction == GDK_SCROLL_SMOOTH) { + dir = event->scroll.delta_y > 0 ? -1 : 1; + } else { + break; + } + if (held_control(event->scroll)) { + _linearGrow(dir); + } else { + _selection.spatialGrow(this, dir); + } + return true; + case GDK_KEY_PRESS: + switch (shortcut_key(event->key)) { + case GDK_KEY_Page_Up: + dir = 1; + break; + case GDK_KEY_Page_Down: + dir = -1; + break; + default: + goto bail_out; + } - if (held_control(event->key)) { - _linearGrow(dir); - } else { - _selection.spatialGrow(this, dir); - } - return true; + if (held_control(event->key)) { + _linearGrow(dir); + } else { + _selection.spatialGrow(this, dir); + } + return true; - default: - break; + default: + break; } - - bail_out: + +bail_out: return ControlPoint::_eventHandler(event_context, event); } @@ -1240,19 +1234,24 @@ void Node::_linearGrow(int dir) NodeList::iterator t; // node to select if (fwd && rev) { - if (distance_front <= distance_back) t = fwd; - else t = rev; + if (distance_front <= distance_back) + t = fwd; + else + t = rev; } else { - if (fwd) t = fwd; - if (rev) t = rev; + if (fwd) + t = fwd; + if (rev) + t = rev; } - if (t) _selection.insert(t.ptr()); - - // Linear shrink is more complicated. We need to find the farthest selected node. - // This means we have to check the entire subpath. We go in the direction in which - // the distance we traveled is lower. We do this until we run out of nodes (ends of path) - // or the two iterators meet. On the way, we store the last selected node and its distance - // in each direction (if any). At the end, we choose the one that is farther and deselect it. + if (t) + _selection.insert(t.ptr()); + + // Linear shrink is more complicated. We need to find the farthest selected node. + // This means we have to check the entire subpath. We go in the direction in which + // the distance we traveled is lower. We do this until we run out of nodes (ends of path) + // or the two iterators meet. On the way, we store the last selected node and its distance + // in each direction (if any). At the end, we choose the one that is farther and deselect it. } else { // both iterators that store last selected nodes are initially empty NodeList::iterator last_fwd, last_rev; @@ -1265,7 +1264,8 @@ void Node::_linearGrow(int dir) last_distance_front = distance_front; } NodeList::iterator n = fwd.next(); - if (n) distance_front += Geom::bezier_length(*fwd, fwd->_front, n->_back, *n); + if (n) + distance_front += Geom::bezier_length(*fwd, fwd->_front, n->_back, *n); fwd = n; } else if (rev && (!fwd || distance_front > distance_back)) { if (rev->selected()) { @@ -1273,7 +1273,8 @@ void Node::_linearGrow(int dir) last_distance_back = distance_back; } NodeList::iterator p = rev.prev(); - if (p) distance_back += Geom::bezier_length(*rev, rev->_back, p->_front, *p); + if (p) + distance_back += Geom::bezier_length(*rev, rev->_back, p->_front, *p); rev = p; } // Check whether we walked the entire cyclic subpath. @@ -1281,7 +1282,8 @@ void Node::_linearGrow(int dir) // so this check cannot go in the while condition. // When this happens, we need to check the last node, pointed to by the iterators. if (fwd && fwd == rev) { - if (!fwd->selected()) break; + if (!fwd->selected()) + break; NodeList::iterator fwdp = fwd.prev(), revn = rev.next(); double df = distance_front + Geom::bezier_length(*fwdp, fwdp->_front, fwd->_back, *fwd); double db = distance_back + Geom::bezier_length(*revn, revn->_back, rev->_front, *rev); @@ -1298,13 +1300,18 @@ void Node::_linearGrow(int dir) NodeList::iterator t; if (last_fwd && last_rev) { - if (last_distance_front >= last_distance_back) t = last_fwd; - else t = last_rev; + if (last_distance_front >= last_distance_back) + t = last_fwd; + else + t = last_rev; } else { - if (last_fwd) t = last_fwd; - if (last_rev) t = last_rev; + if (last_fwd) + t = last_fwd; + if (last_rev) + t = last_rev; } - if (t) _selection.erase(t.ptr()); + if (t) + _selection.erase(t.ptr()); } } @@ -1326,7 +1333,7 @@ void Node::_setState(State state) mgr.setActive(_canvas_item, true); mgr.setPrelight(_canvas_item, false); // show the handles when selecting the nodes - if(_pm()._isBSpline()){ + if (_pm()._isBSpline()) { this->front()->setPosition(_pm()._bsplineHandleReposition(this->front())); this->back()->setPosition(_pm()._bsplineHandleReposition(this->back())); } @@ -1355,14 +1362,12 @@ bool Node::grabbed(GdkEventMotion *event) bool has_degenerate = false; // determine which handle to drag out based on degeneration and the direction of drag if (_front.isDegenerate() && _next()) { - Geom::Point next_relpos = _desktop->d2w(_next()->position()) - - _desktop->d2w(position()); + Geom::Point next_relpos = _desktop->d2w(_next()->position()) - _desktop->d2w(position()); angle_next = fabs(Geom::angle_between(rel_evp, next_relpos)); has_degenerate = true; } if (_back.isDegenerate() && _prev()) { - Geom::Point prev_relpos = _desktop->d2w(_prev()->position()) - - _desktop->d2w(position()); + Geom::Point prev_relpos = _desktop->d2w(_prev()->position()) - _desktop->d2w(position()); angle_prev = fabs(Geom::angle_between(rel_evp, prev_relpos)); has_degenerate = true; } @@ -1406,7 +1411,7 @@ void Node::dragged(Geom::Point &new_pos, GdkEventMotion *event) Set &nodes = _selection.allPoints(); for (auto node : nodes) { if (!node->selected()) { - Node *n = static_cast<Node*>(node); + Node *n = static_cast<Node *>(node); Inkscape::SnapCandidatePoint p(n->position(), n->_snapSourceType(), n->_snapTargetType()); unselected.push_back(p); } @@ -1478,25 +1483,25 @@ void Node::dragged(Geom::Point &new_pos, GdkEventMotion *event) } // perpendiculars only snap when they are further than snap increment away // from the second handle constraint - if (fperp_point && (!back_point || - (fabs(Geom::angle_between(*fperp_point, *back_point)) > min_angle && - fabs(Geom::angle_between(*fperp_point, *back_point)) < M_PI - min_angle))) - { + if (fperp_point && + (!back_point || (fabs(Geom::angle_between(*fperp_point, *back_point)) > min_angle && + fabs(Geom::angle_between(*fperp_point, *back_point)) < M_PI - min_angle))) { constraints.emplace_back(origin, *fperp_point); } - if (bperp_point && (!front_point || - (fabs(Geom::angle_between(*bperp_point, *front_point)) > min_angle && - fabs(Geom::angle_between(*bperp_point, *front_point)) < M_PI - min_angle))) - { + if (bperp_point && + (!front_point || (fabs(Geom::angle_between(*bperp_point, *front_point)) > min_angle && + fabs(Geom::angle_between(*bperp_point, *front_point)) < M_PI - min_angle))) { constraints.emplace_back(origin, *bperp_point); } - sp = sm.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(new_pos, _snapSourceType()), constraints, held_shift(*event)); + sp = sm.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(new_pos, _snapSourceType()), constraints, + held_shift(*event)); } else { // with Ctrl, constrain to axes constraints.emplace_back(origin, Geom::Point(1, 0)); constraints.emplace_back(origin, Geom::Point(0, 1)); - sp = sm.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(new_pos, _snapSourceType()), constraints, held_shift(*event)); + sp = sm.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(new_pos, _snapSourceType()), constraints, + held_shift(*event)); } new_pos = sp.getPoint(); } else if (snap) { @@ -1511,7 +1516,7 @@ void Node::dragged(Geom::Point &new_pos, GdkEventMotion *event) bool Node::clicked(GdkEventButton *event) { - if(_pm()._nodeClicked(this, event)) + if (_pm()._nodeClicked(this, event)) return true; return SelectableControlPoint::clicked(event); } @@ -1587,11 +1592,10 @@ Glib::ustring Node::_getTip(unsigned state) const bool isBSpline = _pm()._isBSpline(); Handle *h = const_cast<Handle *>(&_front); Glib::ustring s = C_("Path node tip", - "node handle"); // not expected + "node handle"); // not expected if (state_held_shift(state)) { - bool can_drag_out = (_next() && _front.isDegenerate()) || - (_prev() && _back.isDegenerate()); + bool can_drag_out = (_next() && _front.isDegenerate()) || (_prev() && _back.isDegenerate()); if (can_drag_out) { /*if (state_held_control(state)) { @@ -1599,75 +1603,67 @@ Glib::ustring Node::_getTip(unsigned state) const "<b>Shift+Ctrl:</b> drag out a handle and snap its angle " "to %f° increments"), snap_increment_degrees()); }*/ - s = C_("Path node tip", - "<b>Shift</b>: drag out a handle, click to toggle selection"); - } - else { - s = C_("Path node tip", - "<b>Shift</b>: click to toggle selection"); + s = C_("Path node tip", "<b>Shift</b>: drag out a handle, click to toggle selection"); + } else { + s = C_("Path node tip", "<b>Shift</b>: click to toggle selection"); } } else if (state_held_control(state)) { if (state_held_alt(state)) { - s = C_("Path node tip", - "<b>Ctrl+Alt</b>: move along handle lines, click to delete node"); - } - else { - s = C_("Path node tip", - "<b>Ctrl</b>: move along axes, click to change node type"); + s = C_("Path node tip", "<b>Ctrl+Alt</b>: move along handle lines, click to delete node"); + } else { + s = C_("Path node tip", "<b>Ctrl</b>: move along axes, click to change node type"); } } else if (state_held_alt(state)) { - s = C_("Path node tip", - "<b>Alt</b>: sculpt nodes"); + s = C_("Path node tip", "<b>Alt</b>: sculpt nodes"); } - else { // No modifiers: assemble tip from node type + else { // No modifiers: assemble tip from node type char const *nodetype = node_type_to_localized_string(_type); double power = _pm()._bsplineHandlePosition(h); if (_selection.transformHandlesEnabled() && selected()) { if (_selection.size() == 1) { if (!isBSpline) { - s = format_tip(C_("Path node tip", - "<b>%s</b>: " - "drag to shape the path" ". " - "(more: Shift, Ctrl, Alt)"), + s = format_tip(C_("Path node tip", "<b>%s</b>: " + "drag to shape the path" + ". " + "(more: Shift, Ctrl, Alt)"), nodetype); - } - else { - s = format_tip(C_("Path node tip", - "<b>BSpline node</b> (%.3g power): " - "drag to shape the path" ". " - "(more: Shift, Ctrl, Alt)"), + } else { + s = format_tip(C_("Path node tip", "<b>BSpline node</b> (%.3g power): " + "drag to shape the path" + ". " + "(more: Shift, Ctrl, Alt)"), power); } - } - else { - s = format_tip(C_("Path node tip", - "<b>%s</b>: " - "drag to shape the path" ", " - "click to toggle scale/rotation handles" ". " - "(more: Shift, Ctrl, Alt)"), + } else { + s = format_tip(C_("Path node tip", "<b>%s</b>: " + "drag to shape the path" + ", " + "click to toggle scale/rotation handles" + ". " + "(more: Shift, Ctrl, Alt)"), nodetype); } - } - else if (!isBSpline) { - s = format_tip(C_("Path node tip", - "<b>%s</b>: " - "drag to shape the path" ", " - "click to select only this node" ". " - "(more: Shift, Ctrl, Alt)"), + } else if (!isBSpline) { + s = format_tip(C_("Path node tip", "<b>%s</b>: " + "drag to shape the path" + ", " + "click to select only this node" + ". " + "(more: Shift, Ctrl, Alt)"), nodetype); - } - else { - s = format_tip(C_("Path node tip", - "<b>BSpline node</b> (%.3g power): " - "drag to shape the path" ", " - "click to select only this node" ". " - "(more: Shift, Ctrl, Alt)"), + } else { + s = format_tip(C_("Path node tip", "<b>BSpline node</b> (%.3g power): " + "drag to shape the path" + ", " + "click to select only this node" + ". " + "(more: Shift, Ctrl, Alt)"), power); } } @@ -1675,10 +1671,10 @@ Glib::ustring Node::_getTip(unsigned state) const return (s); } -Glib::ustring Node::_getDragTip(GdkEventMotion */*event*/) const +Glib::ustring Node::_getDragTip(GdkEventMotion * /*event*/) const { Geom::Point dist = position() - _last_drag_origin(); - + Inkscape::Util::Quantity x_q = Inkscape::Util::Quantity(dist[Geom::X], "px"); Inkscape::Util::Quantity y_q = Inkscape::Util::Quantity(dist[Geom::Y], "px"); Glib::ustring x = x_q.string(_desktop->namedview->display_units); @@ -1693,22 +1689,23 @@ Glib::ustring Node::_getDragTip(GdkEventMotion */*event*/) const char const *Node::node_type_to_localized_string(NodeType type) { switch (type) { - case NODE_CUSP: - return _("Corner node"); - case NODE_SMOOTH: - return _("Smooth node"); - case NODE_SYMMETRIC: - return _("Symmetric node"); - case NODE_AUTO: - return _("Auto-smooth node"); - default: - return ""; + case NODE_CUSP: + return _("Corner node"); + case NODE_SMOOTH: + return _("Smooth node"); + case NODE_SYMMETRIC: + return _("Symmetric node"); + case NODE_AUTO: + return _("Auto-smooth node"); + default: + return ""; } } bool Node::_is_line_segment(Node *first, Node *second) { - if (!first || !second) return false; + if (!first || !second) + return false; if (first->_next() == second) return first->_front.isDegenerate() && second->_back.isDegenerate(); if (second->_next() == first) @@ -1738,7 +1735,8 @@ bool NodeList::empty() NodeList::size_type NodeList::size() { size_type sz = 0; - for (ListNode *ln = ln_next; ln != this; ln = ln->ln_next) ++sz; + for (ListNode *ln = ln_next; ln != this; ln = ln->ln_next) + ++sz; return sz; } @@ -1793,7 +1791,7 @@ void NodeList::splice(iterator pos, NodeList &list, iterator i) splice(pos, list, i, j); } -void NodeList::splice(iterator pos, NodeList &/*list*/, iterator first, iterator last) +void NodeList::splice(iterator pos, NodeList & /*list*/, iterator first, iterator last) { ListNode *ins_beg = first._node, *ins_end = last._node, *at = pos._node; for (ListNode *ln = ins_beg; ln != ins_end; ln = ln->ln_next) { @@ -1817,9 +1815,11 @@ void NodeList::shift(int n) // 2. find new begin ListNode *new_begin = ln_next; if (n > 0) { - for (; n > 0; --n) new_begin = new_begin->ln_next; + for (; n > 0; --n) + new_begin = new_begin->ln_next; } else { - for (; n < 0; ++n) new_begin = new_begin->ln_prev; + for (; n < 0; ++n) + new_begin = new_begin->ln_prev; } // 3. relink begin to list ln_next = new_begin; @@ -1832,7 +1832,7 @@ void NodeList::reverse() { for (ListNode *ln = ln_next; ln != this; ln = ln->ln_prev) { std::swap(ln->ln_next, ln->ln_prev); - Node *node = static_cast<Node*>(ln); + Node *node = static_cast<Node *>(ln); Geom::Point save_pos = node->front()->position(); node->front()->setPosition(node->back()->position()); node->back()->setPosition(save_pos); @@ -1844,10 +1844,10 @@ void NodeList::clear() { // ugly but more efficient clearing mechanism std::vector<ControlPointSelection *> to_clear; - std::vector<std::pair<SelectableControlPoint *, long> > nodes; + std::vector<std::pair<SelectableControlPoint *, long>> nodes; long in = -1; for (iterator i = begin(); i != end(); ++i) { - SelectableControlPoint *rm = static_cast<Node*>(i._node); + SelectableControlPoint *rm = static_cast<Node *>(i._node); if (std::find(to_clear.begin(), to_clear.end(), &rm->_selection) == to_clear.end()) { to_clear.push_back(&rm->_selection); ++in; @@ -1857,7 +1857,7 @@ void NodeList::clear() for (size_t i = 0, e = nodes.size(); i != e; ++i) { to_clear[nodes[i].second]->erase(nodes[i].first, false); } - std::vector<std::vector<SelectableControlPoint *> > emission; + std::vector<std::vector<SelectableControlPoint *>> emission; for (long i = 0, e = to_clear.size(); i != e; ++i) { emission.emplace_back(); for (size_t j = 0, f = nodes.size(); j != f; ++j) { @@ -1872,14 +1872,14 @@ void NodeList::clear() } for (iterator i = begin(); i != end();) - erase (i++); + erase(i++); } NodeList::iterator NodeList::erase(iterator i) { // some gymnastics are required to ensure that the node is valid when deleted; // otherwise the code that updates handle visibility will break - Node *rm = static_cast<Node*>(i._node); + Node *rm = static_cast<Node *>(i._node); ListNode *rmnext = rm->ln_next, *rmprev = rm->ln_prev; ++i; delete rm; @@ -1900,14 +1900,15 @@ void NodeList::kill() } } -NodeList &NodeList::get(Node *n) { +NodeList &NodeList::get(Node *n) +{ return n->nodeList(); } -NodeList &NodeList::get(iterator const &i) { +NodeList &NodeList::get(iterator const &i) +{ return *(i._node->ln_list); } - } // namespace UI } // namespace Inkscape diff --git a/src/ui/tool/node.h b/src/ui/tool/node.h index d4e09caa0bc4f0f5b05eaa0136b932ed3878097c..e76dad7ddf77b2fd39fed46bd7aca6125d0a0b45 100644 --- a/src/ui/tool/node.h +++ b/src/ui/tool/node.h @@ -13,23 +13,24 @@ #ifndef SEEN_UI_TOOL_NODE_H #define SEEN_UI_TOOL_NODE_H -#include <iterator> -#include <iosfwd> -#include <stdexcept> #include <cstddef> #include <functional> +#include <iosfwd> +#include <iterator> +#include <stdexcept> -#include "ui/tool/selectable-control-point.h" #include "snapped-point.h" #include "ui/tool/node-types.h" +#include "ui/tool/selectable-control-point.h" struct SPCtrlLine; namespace Inkscape { namespace UI { -template <typename> class NodeIterator; -} +template <typename> +class NodeIterator; } +} // namespace Inkscape namespace Inkscape { namespace UI { @@ -41,7 +42,8 @@ class Node; class Handle; class NodeList; class SubpathList; -template <typename> class NodeIterator; +template <typename> +class NodeIterator; std::ostream &operator<<(std::ostream &, NodeType); @@ -59,13 +61,15 @@ struct SubpathListMember : public ListMember<SubpathListMember> { }; */ -struct ListNode { +struct ListNode +{ ListNode *ln_next; ListNode *ln_prev; NodeList *ln_list; }; -struct NodeSharedData { +struct NodeSharedData +{ SPDesktop *desktop; ControlPointSelection *selection; SPCanvasGroup *node_group; @@ -73,9 +77,9 @@ struct NodeSharedData { SPCanvasGroup *handle_line_group; }; -class Handle : public ControlPoint { +class Handle : public ControlPoint +{ public: - ~Handle() override; inline Geom::Point relativePos() const; inline double length() const; @@ -97,7 +101,6 @@ public: static char const *handle_type_to_localized_string(NodeType type); protected: - Handle(NodeSharedData const &data, Geom::Point const &initial_pos, Node *parent); virtual void handle_2button_press(); bool _eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) override; @@ -111,13 +114,13 @@ protected: bool _hasDragTips() const override { return true; } private: - inline PathManipulator &_pm(); inline PathManipulator &_pm() const; 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 + 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. @@ -133,9 +136,11 @@ private: friend class Node; }; -class Node : ListNode, public SelectableControlPoint { +class Node + : ListNode + , public SelectableControlPoint +{ public: - /** * Curve endpoint in an editable path. * @@ -165,7 +170,6 @@ public: 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. @@ -175,7 +179,7 @@ public: bool isDegenerate() const { return _front.isDegenerate() && _back.isDegenerate(); } bool isEndNode() const; Handle *front() { return &_front; } - Handle *back() { return &_back; } + Handle *back() { return &_back; } /** * Gets the handle that faces the given adjacent node. @@ -201,8 +205,8 @@ public: */ Node *nodeAwayFrom(Handle *h); - NodeList &nodeList() { return *(static_cast<ListNode*>(this)->ln_list); } - NodeList &nodeList() const { return *(static_cast<ListNode const*>(this)->ln_list); } + NodeList &nodeList() { return *(static_cast<ListNode *>(this)->ln_list); } + NodeList &nodeList() const { return *(static_cast<ListNode const *>(this)->ln_list); } /** * Move the node to the bottom of its canvas group. @@ -220,7 +224,6 @@ public: Inkscape::SnapCandidatePoint snapCandidatePoint(); protected: - void dragged(Geom::Point &new_pos, GdkEventMotion *event) override; bool grabbed(GdkEventMotion *event) override; bool clicked(GdkEventButton *event) override; @@ -231,7 +234,6 @@ protected: bool _hasDragTips() const override { return true; } private: - void _fixNeighbors(Geom::Point const &old_pos, Geom::Point const &new_pos); void _updateAutoHandles(); @@ -256,8 +258,8 @@ private: // Handles are always present, but are not visible if they coincide with the node // (are degenerate). A segment that has both handles degenerate is always treated // as a line segment - Handle _front; ///< Node handle in the backward direction of the path - Handle _back; ///< Node handle in the forward direction of the path + Handle _front; ///< Node handle in the backward direction of the path + 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; @@ -295,9 +297,7 @@ private: * Simply use <code>if (i) { ...</code> * */ template <typename N> -class NodeIterator - : public boost::bidirectional_iterator_helper<NodeIterator<N>, N, std::ptrdiff_t, - N *, N &> +class NodeIterator : public boost::bidirectional_iterator_helper<NodeIterator<N>, N, std::ptrdiff_t, N *, N &> { public: typedef NodeIterator self; @@ -306,43 +306,51 @@ public: {} // default copy, default assign - self &operator++() { - _node = (_node?_node->ln_next:nullptr); + self &operator++() + { + _node = (_node ? _node->ln_next : nullptr); return *this; } - self &operator--() { - _node = (_node?_node->ln_prev:nullptr); + self &operator--() + { + _node = (_node ? _node->ln_prev : nullptr); return *this; } bool operator==(self const &other) const { return _node == other._node; } - N &operator*() const { return *static_cast<N*>(_node); } + 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>. - N *get_pointer() const { return static_cast<N*>(_node); } + N *get_pointer() const { return static_cast<N *>(_node); } /// @see get_pointer() - N *ptr() const { return static_cast<N*>(_node); } + N *ptr() const { return static_cast<N *>(_node); } - self next() const { + self next() const + { self r(*this); r.advance(); return r; } - self prev() const { + self prev() const + { self r(*this); r.retreat(); return r; } self &advance(); self &retreat(); + private: NodeIterator(ListNode const *n) - : _node(const_cast<ListNode*>(n)) + : _node(const_cast<ListNode *>(n)) {} ListNode *_node; friend class NodeList; }; -class NodeList : ListNode, boost::noncopyable { +class NodeList + : ListNode + , boost::noncopyable +{ public: typedef std::size_t size_type; typedef Node &reference; @@ -391,12 +399,11 @@ public: void setClosed(bool c) { _closed = c; } iterator before(double t, double *fracpart = nullptr); iterator before(Geom::PathTime const &pvp); - const_iterator before(double t, double *fracpart = nullptr) const { + const_iterator before(double t, double *fracpart = nullptr) const + { return const_cast<NodeList *>(this)->before(t, fracpart)._node; } - const_iterator before(Geom::PathTime const &pvp) const { - return const_cast<NodeList *>(this)->before(pvp)._node; - } + const_iterator before(Geom::PathTime const &pvp) const { return const_cast<NodeList *>(this)->before(pvp)._node; } // list operations @@ -404,8 +411,10 @@ public: iterator insert(iterator pos, Node *x); template <class InputIterator> - void insert(iterator pos, InputIterator first, InputIterator last) { - for (; first != last; ++first) insert(pos, *first); + void insert(iterator pos, InputIterator first, InputIterator last) + { + for (; first != last; ++first) + insert(pos, *first); } void splice(iterator pos, NodeList &list); void splice(iterator pos, NodeList &list, iterator i); @@ -418,15 +427,17 @@ public: void pop_back() { erase(--end()); } void clear(); iterator erase(iterator pos); - iterator erase(iterator first, iterator last) { + iterator erase(iterator first, iterator last) + { NodeList::iterator ret = first; - while (first != last) ret = erase(first++); + while (first != last) + ret = erase(first++); return ret; } // member access - undefined results when the list is empty - Node &front() { return *static_cast<Node*>(ln_next); } - Node &back() { return *static_cast<Node*>(ln_prev); } + Node &front() { return *static_cast<Node *>(ln_next); } + Node &back() { return *static_cast<Node *>(ln_prev); } // HACK remove this subpath from its path. This will be removed later. void kill(); @@ -436,8 +447,8 @@ public: static const_iterator get_iterator(Node const *n) { return const_iterator(n); } static NodeList &get(Node *n); static NodeList &get(iterator const &i); -private: +private: SubpathList &_list; bool _closed; @@ -451,11 +462,14 @@ private: * List of node lists. Represents an editable path. * Editable path composed of one or more subpaths. */ -class SubpathList : public std::list< std::shared_ptr<NodeList> > { +class SubpathList : public std::list<std::shared_ptr<NodeList>> +{ public: - typedef std::list< std::shared_ptr<NodeList> > list_type; + typedef std::list<std::shared_ptr<NodeList>> list_type; - SubpathList(PathManipulator &pm) : _path_manipulator(pm) {} + SubpathList(PathManipulator &pm) + : _path_manipulator(pm) + {} PathManipulator &pm() { return _path_manipulator; } private: @@ -466,47 +480,57 @@ private: friend class Handle; }; - - // define inline Handle funcs after definition of Node -inline Geom::Point Handle::relativePos() const { +inline Geom::Point Handle::relativePos() const +{ return position() - _parent->position(); } -inline void Handle::setRelativePos(Geom::Point const &p) { +inline void Handle::setRelativePos(Geom::Point const &p) +{ setPosition(_parent->position() + p); } -inline double Handle::length() const { +inline double Handle::length() const +{ return relativePos().length(); } -inline PathManipulator &Handle::_pm() { +inline PathManipulator &Handle::_pm() +{ return _parent->_pm(); } -inline PathManipulator &Handle::_pm() const { +inline PathManipulator &Handle::_pm() const +{ return _parent->_pm(); } -inline PathManipulator &Node::_pm() { +inline PathManipulator &Node::_pm() +{ return nodeList().subpathList().pm(); } -inline PathManipulator &Node::_pm() const { +inline PathManipulator &Node::_pm() const +{ return nodeList().subpathList().pm(); } // definitions for node iterator template <typename N> -NodeIterator<N>::operator bool() const { - return _node && static_cast<ListNode*>(_node->ln_list) != _node; +NodeIterator<N>::operator bool() const +{ + return _node && static_cast<ListNode *>(_node->ln_list) != _node; } template <typename N> -NodeIterator<N> &NodeIterator<N>::advance() { +NodeIterator<N> &NodeIterator<N>::advance() +{ ++(*this); - if (G_UNLIKELY(!*this) && _node->ln_list->closed()) ++(*this); + if (G_UNLIKELY(!*this) && _node->ln_list->closed()) + ++(*this); return *this; } template <typename N> -NodeIterator<N> &NodeIterator<N>::retreat() { +NodeIterator<N> &NodeIterator<N>::retreat() +{ --(*this); - if (G_UNLIKELY(!*this) && _node->ln_list->closed()) --(*this); + if (G_UNLIKELY(!*this) && _node->ln_list->closed()) + --(*this); return *this; } diff --git a/src/ui/tool/path-manipulator.cpp b/src/ui/tool/path-manipulator.cpp index 5f464ae8f630ae558b612772c29341f4f17831d6..f3c50b1acba51ad20e8cecfb6b42db3c3f7f0309 100644 --- a/src/ui/tool/path-manipulator.cpp +++ b/src/ui/tool/path-manipulator.cpp @@ -11,32 +11,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/tool/path-manipulator.h" + #include <2geom/bezier-utils.h> #include <2geom/path-sink.h> - #include <utility> -#include "display/curve.h" #include "display/canvas-bpath.h" - +#include "display/curve.h" #include "helper/geom.h" - -#include "live_effects/lpeobject.h" -#include "live_effects/lpeobject-reference.h" -#include "live_effects/lpe-powerstroke.h" #include "live_effects/lpe-bspline.h" +#include "live_effects/lpe-powerstroke.h" +#include "live_effects/lpeobject-reference.h" +#include "live_effects/lpeobject.h" #include "live_effects/parameter/path.h" - #include "object/sp-path.h" #include "style.h" - #include "ui/tool/control-point-selection.h" #include "ui/tool/curve-drag-point.h" #include "ui/tool/event-utils.h" #include "ui/tool/multi-path-manipulator.h" -#include "ui/tool/path-manipulator.h" #include "ui/tools/node-tool.h" - #include "xml/node-observer.h" namespace Inkscape { @@ -44,7 +39,8 @@ namespace UI { namespace { /// Types of path changes that we must react to. -enum PathChange { +enum PathChange +{ PATH_CHANGE_D, PATH_CHANGE_TRANSFORM }; @@ -52,14 +48,14 @@ enum PathChange { } // anonymous namespace const double HANDLE_CUBIC_GAP = 0.001; const double NO_POWER = 0.0; -const double DEFAULT_START_POWER = 1.0/3.0; - +const double DEFAULT_START_POWER = 1.0 / 3.0; /** * Notifies the path manipulator when something changes the path being edited * (e.g. undo / redo) */ -class PathManipulatorObserver : public Inkscape::XML::NodeObserver { +class PathManipulatorObserver : public Inkscape::XML::NodeObserver +{ public: PathManipulatorObserver(PathManipulator *p, Inkscape::XML::Node *node) : _pm(p) @@ -70,16 +66,18 @@ public: _node->addObserver(*this); } - ~PathManipulatorObserver() override { + ~PathManipulatorObserver() override + { _node->removeObserver(*this); Inkscape::GC::release(_node); } - void notifyAttributeChanged(Inkscape::XML::Node &/*node*/, GQuark attr, - Util::ptr_shared, Util::ptr_shared) override + void notifyAttributeChanged(Inkscape::XML::Node & /*node*/, GQuark attr, Util::ptr_shared, + Util::ptr_shared) override { // do nothing if blocked - if (_blocked) return; + if (_blocked) + return; GQuark path_d = g_quark_from_static_string("d"); GQuark path_transform = g_quark_from_static_string("transform"); @@ -95,6 +93,7 @@ public: void block() { _blocked = true; } void unblock() { _blocked = false; } + private: PathManipulator *_pm; Inkscape::XML::Node *_node; @@ -102,15 +101,16 @@ private: }; void build_segment(Geom::PathBuilder &, Node *, Node *); -PathManipulator::PathManipulator(MultiPathManipulator &mpm, SPObject *path, - Geom::Affine const &et, guint32 outline_color, Glib::ustring lpe_key) +PathManipulator::PathManipulator(MultiPathManipulator &mpm, SPObject *path, Geom::Affine const &et, + guint32 outline_color, Glib::ustring lpe_key) : PointManipulator(mpm._path_data.node_data.desktop, *mpm._path_data.node_data.selection) , _subpaths(*this) , _multi_path_manipulator(mpm) , _path(path) , _spcurve(new SPCurve()) , _dragpoint(new CurveDragPoint(*this)) - , /* XML Tree being used here directly while it shouldn't be*/_observer(new PathManipulatorObserver(this, path->getRepr())) + , /* XML Tree being used here directly while it shouldn't be*/ _observer( + new PathManipulatorObserver(this, path->getRepr())) , _edit_transform(et) , _show_handles(true) , _show_outline(false) @@ -134,19 +134,17 @@ PathManipulator::PathManipulator(MultiPathManipulator &mpm, SPObject *path, _outline = sp_canvas_bpath_new(_multi_path_manipulator._path_data.outline_group, nullptr); sp_canvas_item_hide(_outline); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(_outline), outline_color, 1.0, - SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(_outline), outline_color, 1.0, SP_STROKE_LINEJOIN_MITER, + SP_STROKE_LINECAP_BUTT); sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(_outline), 0, SP_WIND_RULE_NONZERO); - _selection.signal_update.connect( - sigc::bind(sigc::mem_fun(*this, &PathManipulator::update), false)); - _selection.signal_selection_changed.connect( - sigc::mem_fun(*this, &PathManipulator::_selectionChangedM)); + _selection.signal_update.connect(sigc::bind(sigc::mem_fun(*this, &PathManipulator::update), false)); + _selection.signal_selection_changed.connect(sigc::mem_fun(*this, &PathManipulator::_selectionChangedM)); _desktop->signal_zoom_changed.connect( - sigc::hide( sigc::mem_fun(*this, &PathManipulator::_updateOutlineOnZoomChange))); + sigc::hide(sigc::mem_fun(*this, &PathManipulator::_updateOutlineOnZoomChange))); _createControlPointsFromGeometry(); - //Define if the path is BSpline on construction + // Define if the path is BSpline on construction _recalculateIsBSpline(); } @@ -161,26 +159,28 @@ PathManipulator::~PathManipulator() /** Handle motion events to update the position of the curve drag point. */ bool PathManipulator::event(Inkscape::UI::Tools::ToolBase * /*event_context*/, GdkEvent *event) { - if (empty()) return false; + if (empty()) + return false; - switch (event->type) - { - case GDK_MOTION_NOTIFY: - _updateDragPoint(event_point(event->motion)); - break; - default: - break; + switch (event->type) { + case GDK_MOTION_NOTIFY: + _updateDragPoint(event_point(event->motion)); + break; + default: + break; } return false; } /** Check whether the manipulator has any nodes. */ -bool PathManipulator::empty() { +bool PathManipulator::empty() +{ return !_path || _subpaths.empty(); } /** Update the display and the outline of the path. - * \param alert_LPE if true, alerts an applied LPE to what the path is going to be changed to, so it can adjust its parameters for nicer user interfacing + * \param alert_LPE if true, alerts an applied LPE to what the path is going to be changed to, so it can adjust its + * parameters for nicer user interfacing */ void PathManipulator::update(bool alert_LPE) { @@ -200,8 +200,7 @@ void PathManipulator::writeXML() if (!empty()) { _path->updateRepr(); _getXMLNode()->setAttribute(_nodetypesKey(), _createTypeString()); - } - else { + } else { // this manipulator will have to be destroyed right after this call _getXMLNode()->removeObserver(*_observer); _path->deleteObject(true, true); @@ -222,7 +221,7 @@ void PathManipulator::clear() /** Select all nodes in subpaths that have something selected. */ void PathManipulator::selectSubpaths() { - for (auto & _subpath : _subpaths) { + for (auto &_subpath : _subpaths) { NodeList::iterator sp_start = _subpath->begin(), sp_end = _subpath->end(); for (NodeList::iterator j = sp_start; j != sp_end; ++j) { if (j->selected()) { @@ -239,13 +238,15 @@ void PathManipulator::selectSubpaths() /** Invert selection in the selected subpaths. */ void PathManipulator::invertSelectionInSubpaths() { - for (auto & _subpath : _subpaths) { + for (auto &_subpath : _subpaths) { for (NodeList::iterator j = _subpath->begin(); j != _subpath->end(); ++j) { if (j->selected()) { // found selected node - invert selection in this subpath for (NodeList::iterator k = _subpath->begin(); k != _subpath->end(); ++k) { - if (k->selected()) _selection.erase(k.ptr()); - else _selection.insert(k.ptr()); + if (k->selected()) + _selection.erase(k.ptr()); + else + _selection.insert(k.ptr()); } // next subpath break; @@ -257,9 +258,10 @@ void PathManipulator::invertSelectionInSubpaths() /** Insert a new node in the middle of each selected segment. */ void PathManipulator::insertNodes() { - if (_selection.size() < 2) return; + if (_selection.size() < 2) + return; - for (auto & _subpath : _subpaths) { + for (auto &_subpath : _subpaths) { for (NodeList::iterator j = _subpath->begin(); j != _subpath->end(); ++j) { NodeList::iterator k = j.next(); if (k && j->selected() && k->selected()) { @@ -273,7 +275,8 @@ void PathManipulator::insertNodes() void PathManipulator::insertNode(Geom::Point pt) { Geom::Coord dist = _updateDragPoint(pt); - if (dist < 1e-5) { // 1e-6 is too small, as observed occasionally when inserting a node at a snapped intersection of paths + if (dist < 1e-5) { // 1e-6 is too small, as observed occasionally when inserting a node at a snapped intersection of + // paths insertNode(_dragpoint->getIterator(), _dragpoint->getTimeValue(), true); } } @@ -290,33 +293,32 @@ void PathManipulator::insertNode(NodeList::iterator first, double t, bool take_s _commit(_("Add node")); } - -static void -add_or_replace_if_extremum(std::vector< std::pair<NodeList::iterator, double> > &vec, - double & extrvalue, double testvalue, NodeList::iterator const& node, double t) +static void add_or_replace_if_extremum(std::vector<std::pair<NodeList::iterator, double>> &vec, double &extrvalue, + double testvalue, NodeList::iterator const &node, double t) { if (testvalue > extrvalue) { // replace all extreme nodes with the new one vec.clear(); - vec.emplace_back( node, t ); + vec.emplace_back(node, t); extrvalue = testvalue; - } else if ( Geom::are_near(testvalue, extrvalue) ) { + } else if (Geom::are_near(testvalue, extrvalue)) { // very rare but: extremum node at the same extreme value!!! so add it to the list - vec.emplace_back( node, t ); + vec.emplace_back(node, t); } } /** Insert a new node at the extremum of the selected segments. */ void PathManipulator::insertNodeAtExtremum(ExtremumType extremum) { - if (_selection.size() < 2) return; + if (_selection.size() < 2) + return; - double sign = (extremum == EXTR_MIN_X || extremum == EXTR_MIN_Y) ? -1. : 1.; + double sign = (extremum == EXTR_MIN_X || extremum == EXTR_MIN_Y) ? -1. : 1.; Geom::Dim2 dim = (extremum == EXTR_MIN_X || extremum == EXTR_MAX_X) ? Geom::X : Geom::Y; - for (auto & _subpath : _subpaths) { - Geom::Coord extrvalue = - Geom::infinity(); - std::vector< std::pair<NodeList::iterator, double> > extremum_vector; + for (auto &_subpath : _subpaths) { + Geom::Coord extrvalue = -Geom::infinity(); + std::vector<std::pair<NodeList::iterator, double>> extremum_vector; for (NodeList::iterator first = _subpath->begin(); first != _subpath->end(); ++first) { NodeList::iterator second = first.next(); @@ -333,32 +335,32 @@ void PathManipulator::insertNodeAtExtremum(ExtremumType extremum) // and determine extremum Geom::Bezier deriv1d = derivative(temp1d); std::vector<double> rs = deriv1d.roots(); - for (double & r : rs) { + for (double &r : rs) { add_or_replace_if_extremum(extremum_vector, extrvalue, sign * temp1d.valueAt(r), first, r); } } } } - for (auto & i : extremum_vector) { + for (auto &i : extremum_vector) { // don't insert node at the start or end of a segment, i.e. round values for extr_t double t = i.second; - if ( !Geom::are_near(t - std::floor(t+0.5),0.) ) // std::floor(t+0.5) is another way of writing round(t) + if (!Geom::are_near(t - std::floor(t + 0.5), 0.)) // std::floor(t+0.5) is another way of writing round(t) { - _selection.insert( subdivideSegment(i.first, t).ptr() ); + _selection.insert(subdivideSegment(i.first, t).ptr()); } } } } - /** Insert new nodes exactly at the positions of selected nodes while preserving shape. * This is equivalent to breaking, except that it doesn't split into subpaths. */ void PathManipulator::duplicateNodes() { - if (_selection.empty()) return; + if (_selection.empty()) + return; - for (auto & _subpath : _subpaths) { + for (auto &_subpath : _subpaths) { for (NodeList::iterator j = _subpath->begin(); j != _subpath->end(); ++j) { if (j->selected()) { NodeList::iterator k = j.next(); @@ -397,17 +399,21 @@ void PathManipulator::duplicateNodes() /** Replace contiguous selections of nodes in each subpath with one node. */ void PathManipulator::weldNodes(NodeList::iterator preserve_pos) { - if (_selection.size() < 2) return; + if (_selection.size() < 2) + return; hideDragPoint(); bool pos_valid = preserve_pos; for (auto sp : _subpaths) { unsigned num_selected = 0, num_unselected = 0; - for (auto & j : *sp) { - if (j.selected()) ++num_selected; - else ++num_unselected; + for (auto &j : *sp) { + if (j.selected()) + ++num_selected; + else + ++num_unselected; } - if (num_selected < 2) continue; + if (num_selected < 2) + continue; if (num_unselected == 0) { // if all nodes in a subpath are selected, the operation doesn't make much sense continue; @@ -417,15 +423,18 @@ void PathManipulator::weldNodes(NodeList::iterator preserve_pos) // of a selection NodeList::iterator sel_beg = sp->begin(), sel_end; if (sp->closed()) { - while (sel_beg->selected()) ++sel_beg; + while (sel_beg->selected()) + ++sel_beg; } // Work loop while (num_selected > 0) { // Find selected node - while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next(); - if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, " - "but there are still nodes to process!"); + while (sel_beg && !sel_beg->selected()) + sel_beg = sel_beg.next(); + if (!sel_beg) + throw std::logic_error("Join nodes: end of open path reached, " + "but there are still nodes to process!"); // note: this is initialized to zero, because the loop below counts sel_beg as well // the loop conditions are simpler that way @@ -437,7 +446,8 @@ void PathManipulator::weldNodes(NodeList::iterator preserve_pos) for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) { ++num_points; front_pos = *sel_end->front(); - if (pos_valid && sel_end == preserve_pos) use_pos = true; + if (pos_valid && sel_end == preserve_pos) + use_pos = true; } if (num_points > 1) { Geom::Point joined_pos; @@ -472,18 +482,22 @@ void PathManipulator::weldNodes(NodeList::iterator preserve_pos) /** Remove nodes in the middle of selected segments. */ void PathManipulator::weldSegments() { - if (_selection.size() < 2) return; + if (_selection.size() < 2) + return; hideDragPoint(); for (auto sp : _subpaths) { unsigned num_selected = 0, num_unselected = 0; - for (auto & j : *sp) { - if (j.selected()) ++num_selected; - else ++num_unselected; + for (auto &j : *sp) { + if (j.selected()) + ++num_selected; + else + ++num_unselected; } // if 2 or fewer nodes are selected, there can't be any middle points to remove. - if (num_selected <= 2) continue; + 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 @@ -494,15 +508,18 @@ void PathManipulator::weldSegments() // of a selection NodeList::iterator sel_beg = sp->begin(), sel_end; if (sp->closed()) { - while (sel_beg->selected()) ++sel_beg; + while (sel_beg->selected()) + ++sel_beg; } // Work loop while (num_selected > 0) { // Find selected node - while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next(); - if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, " - "but there are still nodes to process!"); + while (sel_beg && !sel_beg->selected()) + sel_beg = sel_beg.next(); + if (!sel_beg) + throw std::logic_error("Join nodes: end of open path reached, " + "but there are still nodes to process!"); // note: this is initialized to zero, because the loop below counts sel_beg as well // the loop conditions are simpler that way @@ -542,7 +559,8 @@ void PathManipulator::breakNodes() --end; } for (; cur != end; ++cur) { - if (!cur->selected()) continue; + if (!cur->selected()) + continue; SubpathPtr ins; bool becomes_open = false; @@ -579,7 +597,8 @@ void PathManipulator::breakNodes() * in a way that attempts to preserve the original shape of the curve. */ void PathManipulator::deleteNodes(bool keep_shape) { - if (_selection.empty()) return; + if (_selection.empty()) + return; hideDragPoint(); for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) { @@ -588,9 +607,11 @@ void PathManipulator::deleteNodes(bool keep_shape) // If there are less than 2 unselected nodes in an open subpath or no unselected nodes // in a closed one, delete entire subpath. unsigned num_unselected = 0, num_selected = 0; - for (auto & j : *sp) { - if (j.selected()) ++num_selected; - else ++num_unselected; + for (auto &j : *sp) { + if (j.selected()) + ++num_selected; + else + ++num_unselected; } if (num_selected == 0) { ++i; @@ -605,10 +626,11 @@ void PathManipulator::deleteNodes(bool keep_shape) // of a selected stretch and the resulting bezier fit would be suboptimal NodeList::iterator sel_beg = sp->begin(), sel_end; if (sp->closed()) { - while (sel_beg->selected()) ++sel_beg; + while (sel_beg->selected()) + ++sel_beg; } sel_end = sel_beg; - + while (num_selected > 0) { while (sel_beg && !sel_beg->selected()) { sel_beg = sel_beg.next(); @@ -618,7 +640,7 @@ void PathManipulator::deleteNodes(bool keep_shape) while (sel_end && sel_end->selected()) { sel_end = sel_end.next(); } - + num_selected -= _deleteStretch(sel_beg, sel_end, keep_shape); sel_beg = sel_end; } @@ -644,13 +666,16 @@ unsigned PathManipulator::_deleteStretch(NodeList::iterator start, NodeList::ite for (NodeList::iterator i = start; i != end; i = i.next()) { ++del_len; } - if (del_len == 0) return 0; + if (del_len == 0) + return 0; // set surrounding node types to cusp if: // 1. keep_shape is on, or // 2. we are deleting at the end or beginning of an open path - if ((keep_shape || !end) && start.prev()) start.prev()->setType(NODE_CUSP, false); - if ((keep_shape || !start.prev()) && end) end->setType(NODE_CUSP, false); + if ((keep_shape || !end) && start.prev()) + start.prev()->setType(NODE_CUSP, false); + if ((keep_shape || !start.prev()) && end) + end->setType(NODE_CUSP, false); if (keep_shape && start.prev() && end) { unsigned num_samples = (del_len + 1) * samples_per_segment + 1; @@ -685,14 +710,14 @@ unsigned PathManipulator::_deleteStretch(NodeList::iterator start, NodeList::ite start = next; } // if we are removing, we readjust the handlers - if(_isBSpline()){ - if(start.prev()){ + if (_isBSpline()) { + if (start.prev()) { double bspline_weight = _bsplineHandlePosition(start.prev()->back(), false); start.prev()->front()->setPosition(_bsplineHandleReposition(start.prev()->front(), bspline_weight)); } - if(end){ + if (end) { double bspline_weight = _bsplineHandlePosition(end->front(), false); - end->back()->setPosition(_bsplineHandleReposition(end->back(),bspline_weight)); + end->back()->setPosition(_bsplineHandleReposition(end->back(), bspline_weight)); } } @@ -702,14 +727,15 @@ unsigned PathManipulator::_deleteStretch(NodeList::iterator start, NodeList::ite /** Removes selected segments */ void PathManipulator::deleteSegments() { - if (_selection.empty()) return; + if (_selection.empty()) + return; hideDragPoint(); for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) { SubpathPtr sp = *i; bool has_unselected = false; unsigned num_selected = 0; - for (auto & j : *sp) { + for (auto &j : *sp) { if (j.selected()) { ++num_selected; } else { @@ -723,7 +749,8 @@ void PathManipulator::deleteSegments() NodeList::iterator sel_beg = sp->begin(); if (sp->closed()) { - while (sel_beg && sel_beg->selected()) ++sel_beg; + while (sel_beg && sel_beg->selected()) + ++sel_beg; } while (num_selected > 0) { if (!sel_beg->selected()) { @@ -779,7 +806,7 @@ void PathManipulator::deleteSegments() * will be reversed. Otherwise all subpaths will be reversed. */ void PathManipulator::reverseSubpaths(bool selected_only) { - for (auto & _subpath : _subpaths) { + for (auto &_subpath : _subpaths) { if (selected_only) { for (NodeList::iterator j = _subpath->begin(); j != _subpath->end(); ++j) { if (j->selected()) { @@ -796,25 +823,27 @@ void PathManipulator::reverseSubpaths(bool selected_only) /** Make selected segments curves / lines. */ void PathManipulator::setSegmentType(SegmentType type) { - if (_selection.empty()) return; - for (auto & _subpath : _subpaths) { + if (_selection.empty()) + return; + for (auto &_subpath : _subpaths) { for (NodeList::iterator j = _subpath->begin(); j != _subpath->end(); ++j) { NodeList::iterator k = j.next(); - if (!(k && j->selected() && k->selected())) continue; + if (!(k && j->selected() && k->selected())) + continue; switch (type) { - case SEGMENT_STRAIGHT: - if (j->front()->isDegenerate() && k->back()->isDegenerate()) + case SEGMENT_STRAIGHT: + if (j->front()->isDegenerate() && k->back()->isDegenerate()) + break; + j->front()->move(*j); + k->back()->move(*k); break; - j->front()->move(*j); - k->back()->move(*k); - break; - case SEGMENT_CUBIC_BEZIER: - if (!j->front()->isDegenerate() || !k->back()->isDegenerate()) + case SEGMENT_CUBIC_BEZIER: + if (!j->front()->isDegenerate() || !k->back()->isDegenerate()) + break; + // move both handles to 1/3 of the line + j->front()->move(j->position() + (k->position() - j->position()) / 3); + k->back()->move(k->position() + (j->position() - k->position()) / 3); break; - // move both handles to 1/3 of the line - j->front()->move(j->position() + (k->position() - j->position()) / 3); - k->back()->move(k->position() + (j->position() - k->position()) / 3); - break; } } } @@ -838,9 +867,11 @@ void PathManipulator::scaleHandle(Node *n, int which, int dir, bool pixel) Geom::Point relpos; if (h->isDegenerate()) { - if (dir < 0) return; + if (dir < 0) + return; Node *nh = n->nodeToward(h); - if (!nh) return; + if (!nh) + return; relpos = Geom::unit_vector(nh->position() - n->position()) * length_change; } else { relpos = h->relativePos(); @@ -859,7 +890,8 @@ void PathManipulator::rotateHandle(Node *n, int which, int dir, bool pixel) n->setType(NODE_CUSP); } Handle *h = _chooseHandle(n, which); - if (h->isDegenerate()) return; + if (h->isDegenerate()) + return; double angle; if (pixel) { @@ -884,8 +916,10 @@ Handle *PathManipulator::_chooseHandle(Node *n, int which) Node *next = i.next().ptr(); // on an endnode, the remaining handle automatically wins - if (!next) return n->back(); - if (!prev) return n->front(); + if (!next) + return n->back(); + if (!prev) + return n->front(); // compare X coord offline segments Geom::Point npos = next->position(); @@ -906,19 +940,23 @@ Handle *PathManipulator::_chooseHandle(Node *n, int which) /** Set the visibility of handles. */ void PathManipulator::showHandles(bool show) { - if (show == _show_handles) return; + if (show == _show_handles) + return; if (show) { - for (auto & _subpath : _subpaths) { + for (auto &_subpath : _subpaths) { for (NodeList::iterator j = _subpath->begin(); j != _subpath->end(); ++j) { - if (!j->selected()) continue; + if (!j->selected()) + continue; j->showHandles(true); - if (j.prev()) j.prev()->showHandles(true); - if (j.next()) j.next()->showHandles(true); + if (j.prev()) + j.prev()->showHandles(true); + if (j.next()) + j.next()->showHandles(true); } } } else { - for (auto & _subpath : _subpaths) { - for (auto & j : *_subpath) { + for (auto &_subpath : _subpaths) { + for (auto &j : *_subpath) { j.showHandles(false); } } @@ -929,14 +967,16 @@ void PathManipulator::showHandles(bool show) /** Set the visibility of outline. */ void PathManipulator::showOutline(bool show) { - if (show == _show_outline) return; + if (show == _show_outline) + return; _show_outline = show; _updateOutline(); } void PathManipulator::showPathDirection(bool show) { - if (show == _show_path_direction) return; + if (show == _show_path_direction) + return; _show_path_direction = show; _updateOutline(); } @@ -953,8 +993,8 @@ void PathManipulator::setLiveObjects(bool set) void PathManipulator::updateHandles() { - for (auto & _subpath : _subpaths) { - for (auto & j : *_subpath) { + for (auto &_subpath : _subpaths) { + for (auto &j : *_subpath) { j.updateHandles(); } } @@ -964,8 +1004,8 @@ void PathManipulator::setControlsTransform(Geom::Affine const &tnew) { Geom::Affine delta = _i2d_transform.inverse() * _edit_transform.inverse() * tnew * _i2d_transform; _edit_transform = tnew; - for (auto & _subpath : _subpaths) { - for (auto & j : *_subpath) { + for (auto &_subpath : _subpaths) { + for (auto &j : *_subpath) { j.transform(delta); } } @@ -985,10 +1025,12 @@ void PathManipulator::hideDragPoint() * at the given time value */ NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, double t) { - if (!first) throw std::invalid_argument("Subdivide after invalid iterator"); + if (!first) + throw std::invalid_argument("Subdivide after invalid iterator"); NodeList &list = NodeList::get(first); NodeList::iterator second = first.next(); - if (!second) throw std::invalid_argument("Subdivide after last node in open path"); + if (!second) + throw std::invalid_argument("Subdivide after last node in open path"); if (first->type() == NODE_SYMMETRIC) first->setType(NODE_SMOOTH, false); if (second->type() == NODE_SYMMETRIC) @@ -1004,44 +1046,44 @@ NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, d if (first->front()->isDegenerate() && second->back()->isDegenerate()) { // for a line segment, insert a cusp node Node *n = new Node(_multi_path_manipulator._path_data.node_data, - Geom::lerp(t, first->position(), second->position())); + Geom::lerp(t, first->position(), second->position())); n->setType(NODE_CUSP, false); inserted = list.insert(insert_at, n); } else { // build bezier curve and subdivide - Geom::CubicBezier temp(first->position(), first->front()->position(), - second->back()->position(), second->position()); + Geom::CubicBezier temp(first->position(), first->front()->position(), second->back()->position(), + second->position()); std::pair<Geom::CubicBezier, Geom::CubicBezier> div = temp.subdivide(t); std::vector<Geom::Point> seg1 = div.first.controlPoints(), seg2 = div.second.controlPoints(); // set new handle positions Node *n = new Node(_multi_path_manipulator._path_data.node_data, seg2[0]); - if(!_isBSpline()){ + if (!_isBSpline()) { n->back()->setPosition(seg1[2]); n->front()->setPosition(seg2[1]); n->setType(NODE_SMOOTH, false); } else { - Geom::D2< Geom::SBasis > sbasis_inside_nodes; + Geom::D2<Geom::SBasis> sbasis_inside_nodes; std::unique_ptr<SPCurve> line_inside_nodes(new SPCurve()); - if(second->back()->isDegenerate()){ + if (second->back()->isDegenerate()) { line_inside_nodes->moveto(n->position()); line_inside_nodes->lineto(second->position()); sbasis_inside_nodes = line_inside_nodes->first_segment()->toSBasis(); Geom::Point next = sbasis_inside_nodes.valueAt(DEFAULT_START_POWER); - next = Geom::Point(next[Geom::X] + HANDLE_CUBIC_GAP,next[Geom::Y] + HANDLE_CUBIC_GAP); + next = Geom::Point(next[Geom::X] + HANDLE_CUBIC_GAP, next[Geom::Y] + HANDLE_CUBIC_GAP); line_inside_nodes->reset(); n->front()->setPosition(next); - }else{ + } else { n->front()->setPosition(seg2[1]); } - if(first->front()->isDegenerate()){ + if (first->front()->isDegenerate()) { line_inside_nodes->moveto(n->position()); line_inside_nodes->lineto(first->position()); sbasis_inside_nodes = line_inside_nodes->first_segment()->toSBasis(); Geom::Point previous = sbasis_inside_nodes.valueAt(DEFAULT_START_POWER); - previous = Geom::Point(previous[Geom::X] + HANDLE_CUBIC_GAP,previous[Geom::Y] + HANDLE_CUBIC_GAP); + previous = Geom::Point(previous[Geom::X] + HANDLE_CUBIC_GAP, previous[Geom::Y] + HANDLE_CUBIC_GAP); n->back()->setPosition(previous); - }else{ + } else { n->back()->setPosition(seg1[2]); } n->setType(NODE_CUSP, false); @@ -1061,19 +1103,22 @@ NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, d * @param closest If true, return closest node, if false, return farthest * @return The matching node, or an empty iterator if none found */ -NodeList::iterator PathManipulator::extremeNode(NodeList::iterator origin, bool search_selected, - bool search_unselected, bool closest) +NodeList::iterator PathManipulator::extremeNode(NodeList::iterator origin, bool search_selected, bool search_unselected, + bool closest) { NodeList::iterator match; double extr_dist = closest ? HUGE_VAL : -HUGE_VAL; - if (_selection.empty() && !search_unselected) return match; + if (_selection.empty() && !search_unselected) + return match; - for (auto & _subpath : _subpaths) { + for (auto &_subpath : _subpaths) { for (NodeList::iterator j = _subpath->begin(); j != _subpath->end(); ++j) { - if(j->selected()) { - if (!search_selected) continue; + if (j->selected()) { + if (!search_selected) + continue; } else { - if (!search_unselected) continue; + if (!search_unselected) + continue; } double dist = Geom::distance(*j, *origin); bool cond = closest ? (dist < extr_dist) : (dist > extr_dist); @@ -1092,48 +1137,51 @@ void PathManipulator::_externalChange(unsigned type) hideDragPoint(); switch (type) { - case PATH_CHANGE_D: { - _getGeometry(); - - // ugly: stored offsets of selected nodes in a vector - // vector<bool> should be specialized so that it takes only 1 bit per value - std::vector<bool> selpos; - for (auto & _subpath : _subpaths) { - for (auto & j : *_subpath) { - selpos.push_back(j.selected()); + case PATH_CHANGE_D: { + _getGeometry(); + + // ugly: stored offsets of selected nodes in a vector + // vector<bool> should be specialized so that it takes only 1 bit per value + std::vector<bool> selpos; + for (auto &_subpath : _subpaths) { + for (auto &j : *_subpath) { + selpos.push_back(j.selected()); + } } - } - unsigned size = selpos.size(), curpos = 0; + unsigned size = selpos.size(), curpos = 0; - _createControlPointsFromGeometry(); + _createControlPointsFromGeometry(); - for (auto & _subpath : _subpaths) { - for (NodeList::iterator j = _subpath->begin(); j != _subpath->end(); ++j) { - if (curpos >= size) goto end_restore; - if (selpos[curpos]) _selection.insert(j.ptr()); - ++curpos; + for (auto &_subpath : _subpaths) { + for (NodeList::iterator j = _subpath->begin(); j != _subpath->end(); ++j) { + if (curpos >= size) + goto end_restore; + if (selpos[curpos]) + _selection.insert(j.ptr()); + ++curpos; + } } - } end_restore: - _updateOutline(); + _updateOutline(); } break; - case PATH_CHANGE_TRANSFORM: { - SPPath *path = dynamic_cast<SPPath *>(_path); - if (path) { - Geom::Affine i2d_change = _d2i_transform; - _i2d_transform = path->i2dt_affine(); - _d2i_transform = _i2d_transform.inverse(); - i2d_change *= _i2d_transform; - for (auto & _subpath : _subpaths) { - for (auto & j : *_subpath) { - j.transform(i2d_change); + case PATH_CHANGE_TRANSFORM: { + SPPath *path = dynamic_cast<SPPath *>(_path); + if (path) { + Geom::Affine i2d_change = _d2i_transform; + _i2d_transform = path->i2dt_affine(); + _d2i_transform = _i2d_transform.inverse(); + i2d_change *= _i2d_transform; + for (auto &_subpath : _subpaths) { + for (auto &j : *_subpath) { + j.transform(i2d_change); + } } + _updateOutline(); } - _updateOutline(); - } } break; - default: break; + default: + break; } } @@ -1145,7 +1193,7 @@ void PathManipulator::_createControlPointsFromGeometry() // sanitize pathvector and store it in SPCurve, // so that _updateDragPoint doesn't crash on paths with naked movetos Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector()); - for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) { + for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end();) { // NOTE: this utilizes the fact that Geom::PathVector is an std::vector. // When we erase an element, the next one slides into position, // so we do not increment the iterator even though it is theoretically invalidated. @@ -1163,7 +1211,7 @@ void PathManipulator::_createControlPointsFromGeometry() pathv *= (_edit_transform * _i2d_transform); // in this loop, we know that there are no zero-segment subpaths - for (auto & pit : pathv) { + for (auto &pit : pathv) { // prepare new subpath SubpathPtr subpath(new NodeList(_subpaths)); _subpaths.push_back(subpath); @@ -1191,16 +1239,16 @@ void PathManipulator::_createControlPointsFromGeometry() // TODO: I don't know why the dynamic cast below doesn't want to work // when I replace BezierCurve with CubicBezier. Might be a bug // somewhere in pathv_to_linear_and_cubic_beziers - Geom::BezierCurve const *bezier = dynamic_cast<Geom::BezierCurve const*>(&*cit); - if (bezier && bezier->order() == 3) - { + Geom::BezierCurve const *bezier = dynamic_cast<Geom::BezierCurve const *>(&*cit); + if (bezier && bezier->order() == 3) { previous_node->front()->setPosition((*bezier)[1]); - current_node ->back() ->setPosition((*bezier)[2]); + current_node->back()->setPosition((*bezier)[2]); } previous_node = current_node; } // If the path is closed, make the list cyclic - if (pit.closed()) subpath->setClosed(true); + if (pit.closed()) + subpath->setClosed(true); } // we need to set the nodetypes after all the handles are in place, @@ -1208,7 +1256,7 @@ void PathManipulator::_createControlPointsFromGeometry() // TODO maybe migrate to inkscape:node-types? // TODO move this into SPPath - do not manipulate directly - //XML Tree being used here directly while it shouldn't be. + // XML Tree being used here directly while it shouldn't be. gchar const *nts_raw = _path ? _path->getRepr()->attribute(_nodetypesKey().data()) : nullptr; /* Calculate the needed length of the nodetype string. * For closed paths, the entry is duplicated for the starting node, @@ -1218,8 +1266,8 @@ void PathManipulator::_createControlPointsFromGeometry() * 'b' and any other letter not recognized by the parser causes the best fit to be set * as the node type */ auto const *tsi = nts_raw ? nts_raw : ""; - for (auto & _subpath : _subpaths) { - for (auto & j : *_subpath) { + for (auto &_subpath : _subpaths) { + for (auto &j : *_subpath) { char nodetype = (*tsi) ? (*tsi++) : 'b'; j.setType(Node::parse_nodetype(nodetype), false); } @@ -1231,33 +1279,36 @@ void PathManipulator::_createControlPointsFromGeometry() } } -//determines if the trace has a bspline effect and the number of steps that it takes -int PathManipulator::_bsplineGetSteps() const { - +// determines if the trace has a bspline effect and the number of steps that it takes +int PathManipulator::_bsplineGetSteps() const +{ LivePathEffect::LPEBSpline const *lpe_bsp = nullptr; - SPLPEItem * path = dynamic_cast<SPLPEItem *>(_path); - if (path){ - if(path->hasPathEffect()){ - Inkscape::LivePathEffect::Effect const *this_effect = path->getPathEffectOfType(Inkscape::LivePathEffect::BSPLINE); - if(this_effect){ - lpe_bsp = dynamic_cast<LivePathEffect::LPEBSpline const*>(this_effect->getLPEObj()->get_lpe()); + SPLPEItem *path = dynamic_cast<SPLPEItem *>(_path); + if (path) { + if (path->hasPathEffect()) { + Inkscape::LivePathEffect::Effect const *this_effect = + path->getPathEffectOfType(Inkscape::LivePathEffect::BSPLINE); + if (this_effect) { + lpe_bsp = dynamic_cast<LivePathEffect::LPEBSpline const *>(this_effect->getLPEObj()->get_lpe()); } } } int steps = 0; - if(lpe_bsp){ - steps = lpe_bsp->steps+1; + if (lpe_bsp) { + steps = lpe_bsp->steps + 1; } return steps; } // determines if the trace has bspline effect -void PathManipulator::_recalculateIsBSpline(){ +void PathManipulator::_recalculateIsBSpline() +{ SPPath *path = dynamic_cast<SPPath *>(_path); if (path && path->hasPathEffect()) { - Inkscape::LivePathEffect::Effect const *this_effect = path->getPathEffectOfType(Inkscape::LivePathEffect::BSPLINE); - if(this_effect){ + Inkscape::LivePathEffect::Effect const *this_effect = + path->getPathEffectOfType(Inkscape::LivePathEffect::BSPLINE); + if (this_effect) { _is_bspline = true; return; } @@ -1265,8 +1316,9 @@ void PathManipulator::_recalculateIsBSpline(){ _is_bspline = false; } -bool PathManipulator::_isBSpline() const { - return _is_bspline; +bool PathManipulator::_isBSpline() const +{ + return _is_bspline; } // returns the corresponding strength to the position of the handlers @@ -1276,17 +1328,19 @@ double PathManipulator::_bsplineHandlePosition(Handle *h, bool check_other) using Geom::Y; double pos = NO_POWER; Node *n = h->parent(); - Node * next_node = nullptr; + Node *next_node = nullptr; next_node = n->nodeToward(h); - if(next_node){ + if (next_node) { std::unique_ptr<SPCurve> line_inside_nodes(new SPCurve()); line_inside_nodes->moveto(n->position()); line_inside_nodes->lineto(next_node->position()); - if(!are_near(h->position(), n->position())){ - pos = Geom::nearest_time(Geom::Point(h->position()[X] - HANDLE_CUBIC_GAP, h->position()[Y] - HANDLE_CUBIC_GAP), *line_inside_nodes->first_segment()); + if (!are_near(h->position(), n->position())) { + pos = Geom::nearest_time( + Geom::Point(h->position()[X] - HANDLE_CUBIC_GAP, h->position()[Y] - HANDLE_CUBIC_GAP), + *line_inside_nodes->first_segment()); } } - if (pos == NO_POWER && check_other){ + if (pos == NO_POWER && check_other) { return _bsplineHandlePosition(h->other(), false); } return pos; @@ -1296,27 +1350,28 @@ double PathManipulator::_bsplineHandlePosition(Handle *h, bool check_other) Geom::Point PathManipulator::_bsplineHandleReposition(Handle *h, bool check_other) { double pos = this->_bsplineHandlePosition(h, check_other); - return _bsplineHandleReposition(h,pos); + return _bsplineHandleReposition(h, pos); } // give the location for the handler to the specified position -Geom::Point PathManipulator::_bsplineHandleReposition(Handle *h,double pos){ +Geom::Point PathManipulator::_bsplineHandleReposition(Handle *h, double pos) +{ using Geom::X; using Geom::Y; Geom::Point ret = h->position(); Node *n = h->parent(); - Geom::D2< Geom::SBasis > sbasis_inside_nodes; + Geom::D2<Geom::SBasis> sbasis_inside_nodes; std::unique_ptr<SPCurve> line_inside_nodes(new SPCurve()); - Node * next_node = nullptr; + Node *next_node = nullptr; next_node = n->nodeToward(h); - if(next_node && pos != NO_POWER){ + if (next_node && pos != NO_POWER) { line_inside_nodes->moveto(n->position()); line_inside_nodes->lineto(next_node->position()); sbasis_inside_nodes = line_inside_nodes->first_segment()->toSBasis(); ret = sbasis_inside_nodes.valueAt(pos); ret = Geom::Point(ret[X] + HANDLE_CUBIC_GAP, ret[Y] + HANDLE_CUBIC_GAP); - }else{ - if(pos == NO_POWER){ + } else { + if (pos == NO_POWER) { ret = n->position(); } } @@ -1330,9 +1385,9 @@ Geom::Point PathManipulator::_bsplineHandleReposition(Handle *h,double pos){ void PathManipulator::_createGeometryFromControlPoints(bool alert_LPE) { Geom::PathBuilder builder; - //Refresh if is bspline some times -think on path change selection, this value get lost + // Refresh if is bspline some times -think on path change selection, this value get lost _recalculateIsBSpline(); - for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end(); ) { + for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end();) { SubpathPtr subpath = *spi; if (subpath->empty()) { _subpaths.erase(spi++); @@ -1357,7 +1412,7 @@ void PathManipulator::_createGeometryFromControlPoints(bool alert_LPE) } builder.flush(); Geom::PathVector pathv = builder.peek() * (_edit_transform * _i2d_transform).inverse(); - for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) { + for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end();) { // NOTE: this utilizes the fact that Geom::PathVector is an std::vector. // When we erase an element, the next one slides into position, // so we do not increment the iterator even though it is theoretically invalidated. @@ -1376,12 +1431,15 @@ void PathManipulator::_createGeometryFromControlPoints(bool alert_LPE) } _spcurve->set_pathvector(pathv); if (alert_LPE) { - /// \todo note that _path can be an Inkscape::LivePathEffect::Effect* too, kind of confusing, rework member naming? + /// \todo note that _path can be an Inkscape::LivePathEffect::Effect* too, kind of confusing, rework member + /// naming? SPPath *path = dynamic_cast<SPPath *>(_path); if (path && path->hasPathEffect()) { - Inkscape::LivePathEffect::Effect* this_effect = path->getPathEffectOfType(Inkscape::LivePathEffect::POWERSTROKE); - if(this_effect){ - LivePathEffect::LPEPowerStroke *lpe_pwr = dynamic_cast<LivePathEffect::LPEPowerStroke*>(this_effect->getLPEObj()->get_lpe()); + Inkscape::LivePathEffect::Effect *this_effect = + path->getPathEffectOfType(Inkscape::LivePathEffect::POWERSTROKE); + if (this_effect) { + LivePathEffect::LPEPowerStroke *lpe_pwr = + dynamic_cast<LivePathEffect::LPEPowerStroke *>(this_effect->getLPEObj()->get_lpe()); if (lpe_pwr) { lpe_pwr->adjustForNewPath(pathv); } @@ -1400,17 +1458,13 @@ void PathManipulator::_createGeometryFromControlPoints(bool alert_LPE) * @relates PathManipulator */ void build_segment(Geom::PathBuilder &builder, Node *prev_node, Node *cur_node) { - if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate()) - { + if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate()) { // NOTE: It seems like the renderer cannot correctly handle vline / hline segments, // and trying to display a path using them results in funny artifacts. builder.lineTo(cur_node->position()); } else { // this is a bezier segment - builder.curveTo( - prev_node->front()->position(), - cur_node->back()->position(), - cur_node->position()); + builder.curveTo(prev_node->front()->position(), cur_node->back()->position(), cur_node->position()); } } @@ -1419,12 +1473,13 @@ std::string PathManipulator::_createTypeString() { // precondition: no single-node subpaths std::stringstream tstr; - for (auto & _subpath : _subpaths) { - for (auto & j : *_subpath) { + for (auto &_subpath : _subpaths) { + for (auto &j : *_subpath) { tstr << j.type(); } // nodestring format peculiarity: first node is counted twice for closed paths - if (_subpath->closed()) tstr << _subpath->begin()->type(); + if (_subpath->closed()) + tstr << _subpath->begin()->type(); } return tstr.str(); } @@ -1448,7 +1503,7 @@ void PathManipulator::_updateOutline() // of little 'harpoons' that show the direction of the subpaths. auto rot_scale_w2d = Geom::Rotate(210.0 / 180.0 * M_PI) * Geom::Scale(10.0) * _desktop->w2d(); Geom::PathVector arrows; - for (auto & path : pv) { + for (auto &path : pv) { for (Geom::Path::iterator j = path.begin(); j != path.end_default(); ++j) { Geom::Point at = j->pointAt(0.5); Geom::Point ut = j->unitTangentAt(0.5); @@ -1501,7 +1556,7 @@ void PathManipulator::_setGeometry() if (lpe) { PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data())); if (pathparam->get_pathvector() == _spcurve->get_pathvector()) { - return; //False we dont update LPE + return; // False we dont update LPE } pathparam->set_new_value(_spcurve->get_pathvector(), false); lpeobj->requestModified(SP_OBJECT_MODIFIED_FLAG); @@ -1509,7 +1564,8 @@ void PathManipulator::_setGeometry() } else if (path) { // return true to leave the decision on empty to the caller. // Maybe the path become empty and we want to update to empty - if (empty()) return; + if (empty()) + return; if (path->curveBeforeLPE()) { if (!_spcurve->is_equal(path->curveBeforeLPE())) { path->setCurveBeforeLPE(_spcurve.get()); @@ -1536,17 +1592,18 @@ Glib::ustring PathManipulator::_nodetypesKey() * This method is wrong but necessary at the moment. */ Inkscape::XML::Node *PathManipulator::_getXMLNode() { - //XML Tree being used here directly while it shouldn't be. + // XML Tree being used here directly while it shouldn't be. LivePathEffectObject *lpeobj = dynamic_cast<LivePathEffectObject *>(_path); if (!lpeobj) return _path->getRepr(); - //XML Tree being used here directly while it shouldn't be. + // XML Tree being used here directly while it shouldn't be. return lpeobj->getRepr(); } bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event) { - if (event->button != 1) return false; + if (event->button != 1) + return false; if (held_alt(*event) && held_control(*event)) { // Ctrl+Alt+click: delete nodes hideDragPoint(); @@ -1561,7 +1618,7 @@ bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event) _deleteStretch(iter, iter.next(), true); } - if (!empty()) { + if (!empty()) { update(true); } @@ -1604,8 +1661,9 @@ bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event) return false; } -void PathManipulator::_selectionChangedM(std::vector<SelectableControlPoint *> pvec, bool selected) { - for (auto & n : pvec) { +void PathManipulator::_selectionChangedM(std::vector<SelectableControlPoint *> pvec, bool selected) +{ + for (auto &n : pvec) { _selectionChanged(n, selected); } } @@ -1613,11 +1671,13 @@ void PathManipulator::_selectionChangedM(std::vector<SelectableControlPoint *> p void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected) { // don't do anything if we do not show handles - if (!_show_handles) return; + if (!_show_handles) + return; // only do something if a node changed selection state - Node *node = dynamic_cast<Node*>(p); - if (!node) return; + Node *node = dynamic_cast<Node *>(p); + if (!node) + return; // update handle display NodeList::iterator iters[5]; @@ -1627,21 +1687,25 @@ void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected if (selected) { // selection - show handles on this node and adjacent ones node->showHandles(true); - if (iters[1]) iters[1]->showHandles(true); - if (iters[3]) iters[3]->showHandles(true); + if (iters[1]) + iters[1]->showHandles(true); + if (iters[3]) + iters[3]->showHandles(true); } else { /* Deselection is more complex. * The change might affect 3 nodes - this one and two adjacent. * If the node and both its neighbors are deselected, hide handles. * Otherwise, leave as is. */ - if (iters[1]) iters[0] = iters[1].prev(); - if (iters[3]) iters[4] = iters[3].next(); + if (iters[1]) + iters[0] = iters[1].prev(); + if (iters[3]) + iters[4] = iters[3].next(); bool nodesel[5]; for (int i = 0; i < 5; ++i) { nodesel[i] = iters[i] && iters[i]->selected(); } for (int i = 1; i < 4; ++i) { - if (iters[i] && !nodesel[i-1] && !nodesel[i] && !nodesel[i+1]) { + if (iters[i] && !nodesel[i - 1] && !nodesel[i] && !nodesel[i + 1]) { iters[i]->showHandles(false); } } @@ -1652,7 +1716,7 @@ void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected void PathManipulator::_removeNodesFromSelection() { // remove this manipulator's nodes from selection - for (auto & _subpath : _subpaths) { + for (auto &_subpath : _subpaths) { for (NodeList::iterator j = _subpath->begin(); j != _subpath->end(); ++j) { _selection.erase(j.get_pointer()); } @@ -1671,8 +1735,7 @@ void PathManipulator::_commit(Glib::ustring const &annotation) void PathManipulator::_commit(Glib::ustring const &annotation, gchar const *key) { writeXML(); - DocumentUndo::maybeDone(_desktop->getDocument(), key, SP_VERB_CONTEXT_NODE, - annotation.data()); + DocumentUndo::maybeDone(_desktop->getDocument(), key, SP_VERB_CONTEXT_NODE, annotation.data()); } /** Update the position of the curve drag point such that it is over the nearest @@ -1683,24 +1746,21 @@ Geom::Coord PathManipulator::_updateDragPoint(Geom::Point const &evp) Geom::Affine to_desktop = _edit_transform * _i2d_transform; Geom::PathVector pv = _spcurve->get_pathvector(); - boost::optional<Geom::PathVectorTime> pvp = - pv.nearestTime(_desktop->w2d(evp) * to_desktop.inverse()); - if (!pvp) return dist; + boost::optional<Geom::PathVectorTime> pvp = pv.nearestTime(_desktop->w2d(evp) * to_desktop.inverse()); + if (!pvp) + return dist; Geom::Point nearest_pt = _desktop->d2w(pv.pointAt(*pvp) * to_desktop); double fracpart = pvp->t; std::list<SubpathPtr>::iterator spi = _subpaths.begin(); - for (unsigned i = 0; i < pvp->path_index; ++i, ++spi) {} + for (unsigned i = 0; i < pvp->path_index; ++i, ++spi) { + } NodeList::iterator first = (*spi)->before(pvp->asPathTime()); - + dist = Geom::distance(evp, nearest_pt); double stroke_tolerance = _getStrokeTolerance(); - if (first && first.next() && - fracpart != 0.0 && - fracpart != 1.0 && - dist < stroke_tolerance) - { + if (first && first.next() && fracpart != 0.0 && fracpart != 1.0 && dist < stroke_tolerance) { _dragpoint->setVisible(true); _dragpoint->setPosition(_desktop->w2d(nearest_pt)); _dragpoint->setSize(2 * stroke_tolerance); @@ -1716,7 +1776,8 @@ Geom::Coord PathManipulator::_updateDragPoint(Geom::Point const &evp) /// This is called on zoom change to update the direction arrows void PathManipulator::_updateOutlineOnZoomChange() { - if (_show_path_direction) _updateOutline(); + if (_show_path_direction) + _updateOutline(); } /** Compute the radius from the edge of the path where clicks should initiate a curve drag @@ -1728,9 +1789,9 @@ double PathManipulator::_getStrokeTolerance() Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100); if (_path && _path->style && !_path->style->stroke.isNone()) { - ret += _path->style->stroke_width.computed * 0.5 - * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords - * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords + ret += _path->style->stroke_width.computed * 0.5 * + (_edit_transform * _i2d_transform).descrim() // scale to desktop coords + * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords } return ret; } diff --git a/src/ui/tool/path-manipulator.h b/src/ui/tool/path-manipulator.h index c7934063291016c336318fc63b45dd9ddac37f57..9ec376f15e5c0810bed1a20f135b1733e45c28bc 100644 --- a/src/ui/tool/path-manipulator.h +++ b/src/ui/tool/path-manipulator.h @@ -12,20 +12,23 @@ #ifndef SEEN_UI_TOOL_PATH_MANIPULATOR_H #define SEEN_UI_TOOL_PATH_MANIPULATOR_H -#include <string> -#include <memory> -#include <2geom/pathvector.h> #include <2geom/affine.h> -#include "ui/tool/node.h" -#include "ui/tool/manipulator.h" +#include <2geom/pathvector.h> +#include <memory> +#include <string> + #include "live_effects/lpe-bspline.h" +#include "ui/tool/manipulator.h" +#include "ui/tool/node.h" struct SPCanvasItem; class SPCurve; class SPPath; namespace Inkscape { -namespace XML { class Node; } +namespace XML { +class Node; +} namespace UI { @@ -38,7 +41,8 @@ class MultiPathManipulator; class Node; class Handle; -struct PathSharedData { +struct PathSharedData +{ NodeSharedData node_data; SPCanvasGroup *outline_group; SPCanvasGroup *dragpoint_group; @@ -49,19 +53,20 @@ struct PathSharedData { * Currently only cubic bezier and linear segments are supported, but this might change * some time in the future. */ -class PathManipulator : public PointManipulator { +class PathManipulator : public PointManipulator +{ public: typedef SPPath *ItemType; - PathManipulator(MultiPathManipulator &mpm, SPObject *path, Geom::Affine const &edit_trans, - guint32 outline_color, Glib::ustring lpe_key); + PathManipulator(MultiPathManipulator &mpm, SPObject *path, Geom::Affine const &edit_trans, guint32 outline_color, + Glib::ustring lpe_key); ~PathManipulator() override; bool event(Inkscape::UI::Tools::ToolBase *, GdkEvent *) override; bool empty(); void writeXML(); void update(bool alert_LPE = false); // update display, but don't commit - void clear(); // remove all nodes from manipulator + void clear(); // remove all nodes from manipulator SPObject *item() { return _path; } void selectSubpaths(); @@ -94,14 +99,15 @@ public: MultiPathManipulator &mpm() { return _multi_path_manipulator; } NodeList::iterator subdivideSegment(NodeList::iterator after, double t); - NodeList::iterator extremeNode(NodeList::iterator origin, bool search_selected, - bool search_unselected, bool closest); + NodeList::iterator extremeNode(NodeList::iterator origin, bool search_selected, bool search_unselected, + bool closest); int _bsplineGetSteps() const; // this is necessary for Tab-selection in MultiPathManipulator SubpathList &subpathList() { return _subpaths; } static bool is_item_type(void *item); + private: typedef NodeList Subpath; typedef std::shared_ptr<NodeList> SubpathPtr; @@ -117,14 +123,14 @@ private: unsigned _deleteStretch(NodeList::iterator first, NodeList::iterator last, bool keep_shape); std::string _createTypeString(); void _updateOutline(); - //void _setOutline(Geom::PathVector const &); + // void _setOutline(Geom::PathVector const &); void _getGeometry(); void _setGeometry(); Glib::ustring _nodetypesKey(); Inkscape::XML::Node *_getXMLNode(); void _selectionChangedM(std::vector<SelectableControlPoint *> pvec, bool selected); - void _selectionChanged(SelectableControlPoint * p, bool selected); + void _selectionChanged(SelectableControlPoint *p, bool selected); bool _nodeClicked(Node *, GdkEventButton *); void _handleGrabbed(); bool _handleClicked(Handle *, GdkEventButton *); @@ -141,13 +147,13 @@ private: SubpathList _subpaths; MultiPathManipulator &_multi_path_manipulator; - SPObject *_path; ///< can be an SPPath or an Inkscape::LivePathEffect::Effect !!! + SPObject *_path; ///< can be an SPPath or an Inkscape::LivePathEffect::Effect !!! std::unique_ptr<SPCurve> _spcurve; // in item coordinates SPCanvasItem *_outline; CurveDragPoint *_dragpoint; // an invisible control point hovering over curve PathManipulatorObserver *_observer; - Geom::Affine _d2i_transform; ///< desktop-to-item transform - Geom::Affine _i2d_transform; ///< item-to-desktop transform, inverse of _d2i_transform + Geom::Affine _d2i_transform; ///< desktop-to-item transform + Geom::Affine _i2d_transform; ///< item-to-desktop transform, inverse of _d2i_transform Geom::Affine _edit_transform; ///< additional transform to apply to editing controls bool _show_handles; bool _show_outline; diff --git a/src/ui/tool/selectable-control-point.cpp b/src/ui/tool/selectable-control-point.cpp index 02480ec10444cd848a456a59c356b7961f45906d..79e9bfe5d0b051acb33ed3e7d9fab6e241b474b9 100644 --- a/src/ui/tool/selectable-control-point.cpp +++ b/src/ui/tool/selectable-control-point.cpp @@ -8,6 +8,7 @@ */ #include "ui/tool/selectable-control-point.h" + #include "ui/tool/control-point-selection.h" #include "ui/tool/event-utils.h" @@ -25,21 +26,19 @@ ControlPoint::ColorSet SelectableControlPoint::_default_scp_color_set = { }; 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) + 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 const &cset, SPCanvasGroup *group) : - ControlPoint(d, initial_pos, anchor, pixbuf, cset, group), - _selection (sel) + 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); } @@ -75,7 +74,8 @@ bool SelectableControlPoint::clicked(GdkEventButton *event) if (_selection._pointClicked(this, event)) return true; - if (event->button != 1) return false; + if (event->button != 1) + return false; if (held_shift(*event)) { if (selected()) { _selection.erase(this); @@ -105,7 +105,7 @@ void SelectableControlPoint::_takeSelection() bool SelectableControlPoint::selected() const { - SelectableControlPoint *p = const_cast<SelectableControlPoint*>(this); + SelectableControlPoint *p = const_cast<SelectableControlPoint *>(this); return _selection.find(p) != _selection.end(); } diff --git a/src/ui/tool/selectable-control-point.h b/src/ui/tool/selectable-control-point.h index 919988a754f5ad4f7d9df1eb493c9787c23761fb..958f9a3cece2b4933ddb92fe17b72998899e31df 100644 --- a/src/ui/tool/selectable-control-point.h +++ b/src/ui/tool/selectable-control-point.h @@ -20,29 +20,23 @@ class ControlPointSelection; /** * Desktop-bound selectable control object. */ -class SelectableControlPoint : public ControlPoint { +class SelectableControlPoint : public ControlPoint +{ public: - ~SelectableControlPoint() override; bool selected() const; void updateState() { _setState(_state); } - virtual Geom::Rect bounds() const { - return Geom::Rect(position(), position()); - } + virtual Geom::Rect bounds() const { return Geom::Rect(position(), position()); } virtual void select(bool toselect); friend class NodeList; - protected: - SelectableControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, - Inkscape::ControlType type, - ControlPointSelection &sel, + Inkscape::ControlType type, ControlPointSelection &sel, ColorSet const &cset = _default_scp_color_set, SPCanvasGroup *group = nullptr); SelectableControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, - Glib::RefPtr<Gdk::Pixbuf> pixbuf, - ControlPointSelection &sel, + Glib::RefPtr<Gdk::Pixbuf> pixbuf, ControlPointSelection &sel, ColorSet const &cset = _default_scp_color_set, SPCanvasGroup *group = nullptr); void _setState(State state) override; @@ -55,7 +49,6 @@ protected: ControlPointSelection &_selection; private: - void _takeSelection(); static ColorSet _default_scp_color_set; diff --git a/src/ui/tool/selector.cpp b/src/ui/tool/selector.cpp index 934d62382bef9a4e6f7991c5e23dc77ea6b735eb..96fc4708d73a2d67aa7e8778b9065674335edd68 100644 --- a/src/ui/tool/selector.cpp +++ b/src/ui/tool/selector.cpp @@ -10,15 +10,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/tool/selector.h" + +#include <gdk/gdkkeysyms.h> + #include "control-point.h" #include "desktop.h" - #include "display/sodipodi-ctrlrect.h" -#include "ui/tools/tool-base.h" #include "ui/tool/event-utils.h" -#include "ui/tool/selector.h" - -#include <gdk/gdkkeysyms.h> +#include "ui/tools/tool-base.h" namespace Inkscape { namespace UI { @@ -27,38 +27,32 @@ namespace UI { * It uses a clever hack: the canvas item is hidden and only receives events when they * are passed to it using Selector's event() function. When left mouse button * is pressed, it grabs events and handles drags and clicks in the usual way. */ -class SelectorPoint : public ControlPoint { +class SelectorPoint : public ControlPoint +{ public: - 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) + 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(_desktop->getControls(), - SP_TYPE_CTRLRECT, nullptr)); + _rubber = static_cast<CtrlRect *>(sp_canvas_item_new(_desktop->getControls(), SP_TYPE_CTRLRECT, nullptr)); _rubber->setColor(0x8080ffff, false, 0x0); _rubber->setInvert(true); sp_canvas_item_hide(_rubber); } - ~SelectorPoint() override { - sp_canvas_item_destroy(_rubber); - } + ~SelectorPoint() override { sp_canvas_item_destroy(_rubber); } SPDesktop *desktop() { return _desktop; } - bool event(Inkscape::UI::Tools::ToolBase *ec, GdkEvent *e) { - return _eventHandler(ec, e); - } + bool event(Inkscape::UI::Tools::ToolBase *ec, GdkEvent *e) { return _eventHandler(ec, e); } protected: - bool _eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) override { + bool _eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) override + { if (event->type == GDK_KEY_PRESS && shortcut_key(event->key) == GDK_KEY_Escape && - sp_canvas_item_is_visible(_rubber)) - { + sp_canvas_item_is_visible(_rubber)) { _cancel = true; sp_canvas_item_hide(_rubber); return true; @@ -67,28 +61,35 @@ protected: } private: - bool grabbed(GdkEventMotion *) override { + bool grabbed(GdkEventMotion *) override + { _cancel = false; _start = position(); sp_canvas_item_show(_rubber); return false; } - void dragged(Geom::Point &new_pos, GdkEventMotion *) override { - if (_cancel) return; + void dragged(Geom::Point &new_pos, GdkEventMotion *) override + { + if (_cancel) + return; Geom::Rect sel(_start, new_pos); _rubber->setRectangle(sel); } - void ungrabbed(GdkEventButton *event) override { - if (_cancel) return; + void ungrabbed(GdkEventButton *event) override + { + if (_cancel) + return; sp_canvas_item_hide(_rubber); Geom::Rect sel(_start, position()); _selector->signal_area.emit(sel, event); } - bool clicked(GdkEventButton *event) override { - if (event->button != 1) return false; + bool clicked(GdkEventButton *event) override + { + if (event->button != 1) + return false; _selector->signal_point.emit(position(), event); return true; } @@ -99,7 +100,6 @@ private: bool _cancel; }; - Selector::Selector(SPDesktop *d) : Manipulator(d) , _dragger(new SelectorPoint(d, d->getControls(), this)) @@ -118,20 +118,22 @@ bool Selector::event(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *eve // but it relies on this function to initiate it. If we pass only first button // press events here, it won't interfere with any other event handling. 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 ToolBase. - if (event->button.button == 1 && !event_context->space_panning) { - _dragger->setPosition(_desktop->w2d(event_point(event->motion))); - return _dragger->event(event_context, event); - } - break; - default: break; + 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 ToolBase. + if (event->button.button == 1 && !event_context->space_panning) { + _dragger->setPosition(_desktop->w2d(event_point(event->motion))); + return _dragger->event(event_context, event); + } + break; + default: + break; } return false; } -bool Selector::doubleClicked() { +bool Selector::doubleClicked() +{ return _dragger->doubleClicked(); } diff --git a/src/ui/tool/selector.h b/src/ui/tool/selector.h index 6881a63fd6a6fb7e5744c43977aa2f4081b82f8b..d45adc0cbae7ecf94a4ad9ff13ffce5fc3fdc4e6 100644 --- a/src/ui/tool/selector.h +++ b/src/ui/tool/selector.h @@ -12,9 +12,10 @@ #ifndef SEEN_UI_TOOL_SELECTOR_H #define SEEN_UI_TOOL_SELECTOR_H -#include <memory> -#include <gdk/gdk.h> #include <2geom/rect.h> +#include <gdk/gdk.h> +#include <memory> + #include "ui/tool/manipulator.h" class SPDesktop; @@ -25,15 +26,17 @@ namespace UI { class SelectorPoint; -class Selector : public Manipulator { +class Selector : public Manipulator +{ public: Selector(SPDesktop *d); ~Selector() override; bool event(Inkscape::UI::Tools::ToolBase *, GdkEvent *) override; virtual bool doubleClicked(); - - sigc::signal<void, Geom::Rect const &, GdkEventButton*> signal_area; - sigc::signal<void, Geom::Point const &, GdkEventButton*> signal_point; + + sigc::signal<void, Geom::Rect const &, GdkEventButton *> signal_area; + sigc::signal<void, Geom::Point const &, GdkEventButton *> signal_point; + private: SelectorPoint *_dragger; Geom::Point _start; diff --git a/src/ui/tool/shape-record.h b/src/ui/tool/shape-record.h index a994e3d46f6bb36bdc9a460256eceaa7cd824a3b..a05a534d41818281d66c8c444fd52075fa45e21f 100644 --- a/src/ui/tool/shape-record.h +++ b/src/ui/tool/shape-record.h @@ -13,9 +13,9 @@ #ifndef SEEN_UI_TOOL_SHAPE_RECORD_H #define SEEN_UI_TOOL_SHAPE_RECORD_H -#include <glibmm/ustring.h> -#include <boost/operators.hpp> #include <2geom/affine.h> +#include <boost/operators.hpp> +#include <glibmm/ustring.h> class SPItem; class SPObject; @@ -23,25 +23,24 @@ namespace Inkscape { namespace UI { /** Role of the shape in the drawing - affects outline display and color */ -enum ShapeRole { +enum ShapeRole +{ SHAPE_ROLE_NORMAL, SHAPE_ROLE_CLIPPING_PATH, SHAPE_ROLE_MASK, SHAPE_ROLE_LPE_PARAM // implies edit_original set to true in ShapeRecord }; -struct ShapeRecord : - public boost::totally_ordered<ShapeRecord> +struct ShapeRecord : public boost::totally_ordered<ShapeRecord> { - SPObject *object; // SP node for the edited shape could be a lpeoject invisible so we use a spobject + SPObject *object; // SP node for the edited shape could be a lpeoject invisible so we use a spobject Geom::Affine edit_transform; // how to transform controls - used for clipping paths and masks ShapeRole role; Glib::ustring lpe_key; // name of LPE shape param being edited - inline bool operator==(ShapeRecord const &o) const { - return object == o.object && lpe_key == o.lpe_key; - } - inline bool operator<(ShapeRecord const &o) const { + inline bool operator==(ShapeRecord const &o) const { return object == o.object && lpe_key == o.lpe_key; } + inline bool operator<(ShapeRecord const &o) const + { return object == o.object ? (lpe_key < o.lpe_key) : (object < o.object); } }; diff --git a/src/ui/tool/transform-handle-set.cpp b/src/ui/tool/transform-handle-set.cpp index c1d6692bc5ce3e804f8f87eed1ee594b7c841c52..e31af2ec3b2327162b603e3cbe6c23e9c24e4a13 100644 --- a/src/ui/tool/transform-handle-set.cpp +++ b/src/ui/tool/transform-handle-set.cpp @@ -10,32 +10,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cmath> -#include <algorithm> - -#include <glib/gi18n.h> +#include "ui/tool/transform-handle-set.h" #include <2geom/transforms.h> +#include <algorithm> +#include <cmath> +#include <glib/gi18n.h> #include "control-point.h" #include "desktop.h" +#include "display/sodipodi-ctrlrect.h" +#include "object/sp-namedview.h" #include "pure-transform.h" #include "seltrans.h" #include "snap.h" - -#include "display/sodipodi-ctrlrect.h" - -#include "object/sp-namedview.h" - #include "ui/tool/commit-events.h" #include "ui/tool/control-point-selection.h" #include "ui/tool/event-utils.h" #include "ui/tool/node.h" #include "ui/tool/selectable-control-point.h" -#include "ui/tool/transform-handle-set.h" #include "ui/tools/node-tool.h" - // FIXME BRAIN DAMAGE WARNING: this is a global variable in select-context.cpp // It should be moved to a header extern GdkPixbuf *handles[]; @@ -46,33 +41,45 @@ namespace UI { namespace { -SPAnchorType corner_to_anchor(unsigned c) { +SPAnchorType corner_to_anchor(unsigned c) +{ switch (c % 4) { - case 0: return SP_ANCHOR_NE; - case 1: return SP_ANCHOR_NW; - case 2: return SP_ANCHOR_SW; - default: return SP_ANCHOR_SE; + case 0: + return SP_ANCHOR_NE; + case 1: + return SP_ANCHOR_NW; + case 2: + return SP_ANCHOR_SW; + default: + return SP_ANCHOR_SE; } } -SPAnchorType side_to_anchor(unsigned s) { +SPAnchorType side_to_anchor(unsigned s) +{ switch (s % 4) { - case 0: return SP_ANCHOR_N; - case 1: return SP_ANCHOR_W; - case 2: return SP_ANCHOR_S; - default: return SP_ANCHOR_E; + case 0: + return SP_ANCHOR_N; + case 1: + return SP_ANCHOR_W; + case 2: + return SP_ANCHOR_S; + default: + return SP_ANCHOR_E; } } // TODO move those two functions into a common place -double snap_angle(double a) { +double snap_angle(double a) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000); double unit_angle = M_PI / snaps; return CLAMP(unit_angle * round(a / unit_angle), -M_PI, M_PI); } -double snap_increment_degrees() { +double snap_increment_degrees() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000); return 180.0 / snaps; @@ -80,21 +87,17 @@ double snap_increment_degrees() { } // anonymous namespace -ControlPoint::ColorSet TransformHandle::thandle_cset = { - {0x000000ff, 0x000000ff}, - {0x00ff6600, 0x000000ff}, - {0x00ff6600, 0x000000ff}, - // - {0x000000ff, 0x000000ff}, - {0x00ff6600, 0x000000ff}, - {0x00ff6600, 0x000000ff} -}; - -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) +ControlPoint::ColorSet TransformHandle::thandle_cset = {{0x000000ff, 0x000000ff}, + {0x00ff6600, 0x000000ff}, + {0x00ff6600, 0x000000ff}, + // + {0x000000ff, 0x000000ff}, + {0x00ff6600, 0x000000ff}, + {0x00ff6600, 0x000000ff}}; + +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); } @@ -141,8 +144,8 @@ bool TransformHandle::grabbed(GdkEventMotion *) // Collect the snap-candidates, one for each selected node. These will be stored in the _snap_points vector. Inkscape::UI::Tools::NodeTool *nt = INK_NODE_TOOL(_th._desktop->event_context); - //ControlPointSelection *selection = nt->_selected_nodes.get(); - ControlPointSelection* selection = nt->_selected_nodes; + // ControlPointSelection *selection = nt->_selected_nodes.get(); + ControlPointSelection *selection = nt->_selected_nodes; selection->setOriginalPoints(); selection->getOriginalPoints(_snap_points); @@ -154,7 +157,7 @@ bool TransformHandle::grabbed(GdkEventMotion *) _all_snap_sources_sorted = _snap_points; // Calculate and store the distance to the reference point for each snap candidate point - for(auto & i : _all_snap_sources_sorted) { + for (auto &i : _all_snap_sources_sorted) { i.setDistance(Geom::L2(i.getPoint() - _origin)); } @@ -176,9 +179,11 @@ void TransformHandle::dragged(Geom::Point &new_pos, GdkEventMotion *event) { Geom::Affine t = computeTransform(new_pos, event); // protect against degeneracies - if (t.isSingular()) return; + if (t.isSingular()) + return; Geom::Affine incr = _last_transform.inverse() * t; - if (incr.isSingular()) return; + if (incr.isSingular()) + return; _th.signal_transform.emit(incr); _last_transform = t; } @@ -192,31 +197,32 @@ void TransformHandle::ungrabbed(GdkEventButton *) endTransform(); _th.signal_commit.emit(getCommitEvent()); - //updates the positions of the nodes + // updates the positions of the nodes Inkscape::UI::Tools::NodeTool *nt = INK_NODE_TOOL(_th._desktop->event_context); - ControlPointSelection* selection = nt->_selected_nodes; + ControlPointSelection *selection = nt->_selected_nodes; selection->setOriginalPoints(); } - -class ScaleHandle : public TransformHandle { +class ScaleHandle : public TransformHandle +{ public: ScaleHandle(TransformHandleSet &th, SPAnchorType anchor, Glib::RefPtr<Gdk::Pixbuf> pb) : TransformHandle(th, anchor, pb) {} + protected: - Glib::ustring _getTip(unsigned state) const override { + Glib::ustring _getTip(unsigned state) const override + { if (state_held_control(state)) { if (state_held_shift(state)) { - return C_("Transform handle tip", - "<b>Shift+Ctrl</b>: scale uniformly about the rotation center"); + return C_("Transform handle tip", "<b>Shift+Ctrl</b>: scale uniformly about the rotation center"); } return C_("Transform handle tip", "<b>Ctrl:</b> scale uniformly"); } if (state_held_shift(state)) { if (state_held_alt(state)) { return C_("Transform handle tip", - "<b>Shift+Alt</b>: scale using an integer ratio about the rotation center"); + "<b>Shift+Alt</b>: scale using an integer ratio about the rotation center"); } return C_("Transform handle tip", "<b>Shift</b>: scale from the rotation center"); } @@ -226,9 +232,10 @@ protected: return C_("Transform handle tip", "<b>Scale handle</b>: drag to scale the selection"); } - Glib::ustring _getDragTip(GdkEventMotion */*event*/) const override { - return format_tip(C_("Transform handle tip", - "Scale by %.2f%% x %.2f%%"), _last_scale_x * 100, _last_scale_y * 100); + Glib::ustring _getDragTip(GdkEventMotion * /*event*/) const override + { + return format_tip(C_("Transform handle tip", "Scale by %.2f%% x %.2f%%"), _last_scale_x * 100, + _last_scale_y * 100); } bool _hasDragTips() const override { return true; } @@ -241,22 +248,24 @@ double ScaleHandle::_last_scale_y = 1.0; /** * Corner scaling handle for node transforms. */ -class ScaleCornerHandle : public ScaleHandle { +class ScaleCornerHandle : public ScaleHandle +{ public: - - ScaleCornerHandle(TransformHandleSet &th, unsigned corner, unsigned d_corner) : - ScaleHandle(th, corner_to_anchor(d_corner), _corner_to_pixbuf(d_corner)), - _corner(corner) + ScaleCornerHandle(TransformHandleSet &th, unsigned corner, unsigned d_corner) + : ScaleHandle(th, corner_to_anchor(d_corner), _corner_to_pixbuf(d_corner)) + , _corner(corner) {} protected: - void startTransform() override { + void startTransform() override + { _sc_center = _th.rotationCenter(); _sc_opposite = _th.bounds().corner(_corner + 2); _last_scale_x = _last_scale_y = 1.0; } - Geom::Affine computeTransform(Geom::Point const &new_pos, GdkEventMotion *event) override { + Geom::Affine computeTransform(Geom::Point const &new_pos, GdkEventMotion *event) override + { Geom::Point scc = held_shift(*event) ? _sc_center : _sc_opposite; Geom::Point vold = _origin - scc, vnew = new_pos - scc; // avoid exploding the selection @@ -270,7 +279,7 @@ protected: if (fabs(scale[i]) >= 1.0) { scale[i] = round(scale[i]); } else { - scale[i] = 1.0 / round(1.0 / MIN(scale[i],10)); + scale[i] = 1.0 / round(1.0 / MIN(scale[i], 10)); } } } else { @@ -295,22 +304,19 @@ protected: _last_scale_x = scale[0]; _last_scale_y = scale[1]; - Geom::Affine t = Geom::Translate(-scc) - * Geom::Scale(scale[0], scale[1]) - * Geom::Translate(scc); + Geom::Affine t = Geom::Translate(-scc) * Geom::Scale(scale[0], scale[1]) * Geom::Translate(scc); return t; } - CommitEvent getCommitEvent() override { - return _last_transform.isUniformScale() - ? COMMIT_MOUSE_SCALE_UNIFORM - : COMMIT_MOUSE_SCALE; + CommitEvent getCommitEvent() override + { + 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(); + static Glib::RefPtr<Gdk::Pixbuf> _corner_to_pixbuf(unsigned c) + { + // sp_select_context_get_type(); switch (c % 2) { case 0: return Glib::wrap(handles[1], true); @@ -329,20 +335,24 @@ private: /** * Side scaling handle for node transforms. */ -class ScaleSideHandle : public ScaleHandle { +class ScaleSideHandle : public ScaleHandle +{ public: ScaleSideHandle(TransformHandleSet &th, unsigned side, unsigned d_side) : ScaleHandle(th, side_to_anchor(d_side), _side_to_pixbuf(side)) , _side(side) {} + protected: - void startTransform() override { + void startTransform() override + { _sc_center = _th.rotationCenter(); Geom::Rect b = _th.bounds(); _sc_opposite = Geom::middle_point(b.corner(_side + 2), b.corner(_side + 3)); _last_scale_x = _last_scale_y = 1.0; } - Geom::Affine computeTransform(Geom::Point const &new_pos, GdkEventMotion *event) override { + Geom::Affine computeTransform(Geom::Point const &new_pos, GdkEventMotion *event) override + { Geom::Point scc = held_shift(*event) ? _sc_center : _sc_opposite; Geom::Point vs; Geom::Dim2 d1 = static_cast<Geom::Dim2>((_side + 1) % 2); @@ -357,7 +367,7 @@ protected: if (fabs(vs[d1]) >= 1.0) { vs[d1] = round(vs[d1]); } else { - vs[d1] = 1.0 / round(1.0 / MIN(vs[d1],10)); + vs[d1] = 1.0 / round(1.0 / MIN(vs[d1], 10)); } vs[d2] = 1.0; } else { @@ -370,7 +380,7 @@ protected: m.unSetup(); if (psc.best_snapped_point.getSnapped()) { - Geom::Point result = psc.getStretchSnapped().vector(); //best_snapped_point.getTransformation(); + Geom::Point result = psc.getStretchSnapped().vector(); // best_snapped_point.getTransformation(); vs[d1] = result[d1]; vs[d2] = result[d2]; } else { @@ -382,22 +392,23 @@ protected: _last_scale_x = vs[Geom::X]; _last_scale_y = vs[Geom::Y]; - Geom::Affine t = Geom::Translate(-scc) - * Geom::Scale(vs) - * Geom::Translate(scc); + Geom::Affine t = Geom::Translate(-scc) * Geom::Scale(vs) * Geom::Translate(scc); return t; } - CommitEvent getCommitEvent() override { - return _last_transform.isUniformScale() - ? COMMIT_MOUSE_SCALE_UNIFORM - : COMMIT_MOUSE_SCALE; + CommitEvent getCommitEvent() override + { + return _last_transform.isUniformScale() ? COMMIT_MOUSE_SCALE_UNIFORM : COMMIT_MOUSE_SCALE; } + private: - static Glib::RefPtr<Gdk::Pixbuf> _side_to_pixbuf(unsigned c) { - //sp_select_context_get_type(); + static Glib::RefPtr<Gdk::Pixbuf> _side_to_pixbuf(unsigned c) + { + // sp_select_context_get_type(); switch (c % 2) { - case 0: return Glib::wrap(handles[3], true); - default: return Glib::wrap(handles[2], true); + case 0: + return Glib::wrap(handles[3], true); + default: + return Glib::wrap(handles[2], true); } } Geom::Point _sc_center; @@ -408,15 +419,17 @@ private: /** * Rotation handle for node transforms. */ -class RotateHandle : public TransformHandle { +class RotateHandle : public TransformHandle +{ public: RotateHandle(TransformHandleSet &th, unsigned corner, unsigned d_corner) : TransformHandle(th, corner_to_anchor(d_corner), _corner_to_pixbuf(d_corner)) , _corner(corner) {} -protected: - void startTransform() override { +protected: + void startTransform() override + { _rot_center = _th.rotationCenter(); _rot_opposite = _th.bounds().corner(_corner + 2); _last_angle = 0; @@ -436,51 +449,56 @@ protected: m.unSetup(); if (prc.best_snapped_point.getSnapped()) { - angle = prc.getAngleSnapped(); //best_snapped_point.getTransformation()[0]; + angle = prc.getAngleSnapped(); // best_snapped_point.getTransformation()[0]; } } _last_angle = angle; - Geom::Affine t = Geom::Translate(-rotc) - * Geom::Rotate(angle) - * Geom::Translate(rotc); + Geom::Affine t = Geom::Translate(-rotc) * Geom::Rotate(angle) * Geom::Translate(rotc); return t; } CommitEvent getCommitEvent() override { return COMMIT_MOUSE_ROTATE; } - Glib::ustring _getTip(unsigned state) const override { + Glib::ustring _getTip(unsigned state) const override + { if (state_held_shift(state)) { if (state_held_control(state)) { return format_tip(C_("Transform handle tip", - "<b>Shift+Ctrl</b>: rotate around the opposite corner and snap " - "angle to %f° increments"), snap_increment_degrees()); + "<b>Shift+Ctrl</b>: rotate around the opposite corner and snap " + "angle to %f° increments"), + snap_increment_degrees()); } return C_("Transform handle tip", "<b>Shift</b>: rotate around the opposite corner"); } if (state_held_control(state)) { - return format_tip(C_("Transform handle tip", - "<b>Ctrl</b>: snap angle to %f° increments"), snap_increment_degrees()); + return format_tip(C_("Transform handle tip", "<b>Ctrl</b>: snap angle to %f° increments"), + snap_increment_degrees()); } return C_("Transform handle tip", "<b>Rotation handle</b>: drag to rotate " - "the selection around the rotation center"); + "the selection around the rotation center"); } - Glib::ustring _getDragTip(GdkEventMotion */*event*/) const override { - return format_tip(C_("Transform handle tip", "Rotate by %.2f°"), - _last_angle * 180.0 / M_PI); + Glib::ustring _getDragTip(GdkEventMotion * /*event*/) const override + { + return format_tip(C_("Transform handle tip", "Rotate by %.2f°"), _last_angle * 180.0 / M_PI); } bool _hasDragTips() const override { return true; } private: - static Glib::RefPtr<Gdk::Pixbuf> _corner_to_pixbuf(unsigned c) { - //sp_select_context_get_type(); + static Glib::RefPtr<Gdk::Pixbuf> _corner_to_pixbuf(unsigned c) + { + // sp_select_context_get_type(); switch (c % 4) { - 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); + 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); } } Geom::Point _rot_center; @@ -490,7 +508,8 @@ private: }; double RotateHandle::_last_angle = 0; -class SkewHandle : public TransformHandle { +class SkewHandle : public TransformHandle +{ public: SkewHandle(TransformHandleSet &th, unsigned side, unsigned d_side) : TransformHandle(th, side_to_anchor(d_side), _side_to_pixbuf(side)) @@ -498,8 +517,8 @@ public: {} protected: - - void startTransform() override { + void startTransform() override + { _skew_center = _th.rotationCenter(); Geom::Rect b = _th.bounds(); _skew_opposite = Geom::middle_point(b.corner(_side + 2), b.corner(_side + 3)); @@ -551,7 +570,7 @@ protected: m.unSetup(); if (psc.best_snapped_point.getSnapped()) { - skew[d1] = psc.getSkewSnapped(); //best_snapped_point.getTransformation()[0]; + skew[d1] = psc.getSkewSnapped(); // best_snapped_point.getTransformation()[0]; } } @@ -564,69 +583,67 @@ protected: // Calculate the relative affine Geom::Affine relative_affine = Geom::identity(); - relative_affine[2*d1 + d1] = (new_new_pos[d1] - scc[d1]) / initial_delta[d1]; - relative_affine[2*d1 + (d2)] = (new_new_pos[d2] - _origin[d2]) / initial_delta[d1]; - relative_affine[2*(d2) + (d1)] = 0; - relative_affine[2*(d2) + (d2)] = 1; + relative_affine[2 * d1 + d1] = (new_new_pos[d1] - scc[d1]) / initial_delta[d1]; + relative_affine[2 * d1 + (d2)] = (new_new_pos[d2] - _origin[d2]) / initial_delta[d1]; + relative_affine[2 * (d2) + (d1)] = 0; + relative_affine[2 * (d2) + (d2)] = 1; for (int i = 0; i < 2; i++) { - if (fabs(relative_affine[3*i]) < 1e-15) { - relative_affine[3*i] = 1e-15; + if (fabs(relative_affine[3 * i]) < 1e-15) { + relative_affine[3 * i] = 1e-15; } } - Geom::Affine t = Geom::Translate(-scc) - * relative_affine - * Geom::Translate(scc); + Geom::Affine t = Geom::Translate(-scc) * relative_affine * Geom::Translate(scc); return t; } - CommitEvent getCommitEvent() override { - return (_side % 2) - ? COMMIT_MOUSE_SKEW_Y - : COMMIT_MOUSE_SKEW_X; - } + CommitEvent getCommitEvent() override { return (_side % 2) ? COMMIT_MOUSE_SKEW_Y : COMMIT_MOUSE_SKEW_X; } - Glib::ustring _getTip(unsigned state) const override { + Glib::ustring _getTip(unsigned state) const override + { if (state_held_shift(state)) { if (state_held_control(state)) { return format_tip(C_("Transform handle tip", - "<b>Shift+Ctrl</b>: skew about the rotation center with snapping " - "to %f° increments"), snap_increment_degrees()); + "<b>Shift+Ctrl</b>: skew about the rotation center with snapping " + "to %f° increments"), + snap_increment_degrees()); } return C_("Transform handle tip", "<b>Shift</b>: skew about the rotation center"); } if (state_held_control(state)) { - return format_tip(C_("Transform handle tip", - "<b>Ctrl</b>: snap skew angle to %f° increments"), snap_increment_degrees()); + return format_tip(C_("Transform handle tip", "<b>Ctrl</b>: snap skew angle to %f° increments"), + snap_increment_degrees()); } - return C_("Transform handle tip", - "<b>Skew handle</b>: drag to skew (shear) selection about " - "the opposite handle"); + return C_("Transform handle tip", "<b>Skew handle</b>: drag to skew (shear) selection about " + "the opposite handle"); } - Glib::ustring _getDragTip(GdkEventMotion */*event*/) const override { + Glib::ustring _getDragTip(GdkEventMotion * /*event*/) const override + { if (_last_horizontal) { - return format_tip(C_("Transform handle tip", "Skew horizontally by %.2f°"), - _last_angle * 360.0); + return format_tip(C_("Transform handle tip", "Skew horizontally by %.2f°"), _last_angle * 360.0); } else { - return format_tip(C_("Transform handle tip", "Skew vertically by %.2f°"), - _last_angle * 360.0); + return format_tip(C_("Transform handle tip", "Skew vertically by %.2f°"), _last_angle * 360.0); } } bool _hasDragTips() const override { return true; } private: - - static Glib::RefPtr<Gdk::Pixbuf> _side_to_pixbuf(unsigned s) { - //sp_select_context_get_type(); + static Glib::RefPtr<Gdk::Pixbuf> _side_to_pixbuf(unsigned s) + { + // sp_select_context_get_type(); switch (s % 4) { - 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); + 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); } } Geom::Point _skew_center; @@ -638,20 +655,20 @@ private: bool SkewHandle::_last_horizontal = false; double SkewHandle::_last_angle = 0; -class RotationCenter : public ControlPoint { - +class RotationCenter : public ControlPoint +{ public: - RotationCenter(TransformHandleSet &th) : - ControlPoint(th._desktop, Geom::Point(), SP_ANCHOR_CENTER, - _get_pixbuf(), - _center_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); } protected: - void dragged(Geom::Point &new_pos, GdkEventMotion *event) override { + void dragged(Geom::Point &new_pos, GdkEventMotion *event) override + { SnapManager &sm = _th._desktop->namedview->snap_manager; sm.setup(_th._desktop); bool snap = !held_shift(*event) && sm.someSnapperMightSnap(); @@ -661,22 +678,23 @@ protected: std::vector<Inkscape::Snapper::SnapConstraint> constraints; constraints.emplace_back(origin, Geom::Point(1, 0)); constraints.emplace_back(origin, Geom::Point(0, 1)); - new_pos = sm.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(new_pos, - SNAPSOURCE_ROTATION_CENTER), constraints, held_shift(*event)).getPoint(); + new_pos = sm.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(new_pos, SNAPSOURCE_ROTATION_CENTER), + constraints, held_shift(*event)) + .getPoint(); } else if (snap) { sm.freeSnapReturnByRef(new_pos, SNAPSOURCE_ROTATION_CENTER); } sm.unSetup(); } - Glib::ustring _getTip(unsigned /*state*/) const override { - return C_("Transform handle tip", - "<b>Rotation center</b>: drag to change the origin of transforms"); + Glib::ustring _getTip(unsigned /*state*/) const override + { + return C_("Transform handle tip", "<b>Rotation center</b>: drag to change the origin of transforms"); } private: - - static Glib::RefPtr<Gdk::Pixbuf> _get_pixbuf() { - //sp_select_context_get_type(); + static Glib::RefPtr<Gdk::Pixbuf> _get_pixbuf() + { + // sp_select_context_get_type(); return Glib::wrap(handles[12], true); } @@ -684,16 +702,13 @@ private: TransformHandleSet &_th; }; -ControlPoint::ColorSet RotationCenter::_center_cset = { - {0x00000000, 0x000000ff}, - {0x00000000, 0xff0000b0}, - {0x00000000, 0xff0000b0}, - // - {0x00000000, 0x000000ff}, - {0x00000000, 0xff0000b0}, - {0x00000000, 0xff0000b0} -}; - +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) @@ -703,8 +718,7 @@ TransformHandleSet::TransformHandleSet(SPDesktop *d, SPCanvasGroup *th_group) , _in_transform(false) , _visible(true) { - _trans_outline = static_cast<CtrlRect*>(sp_canvas_item_new(_desktop->getControls(), - SP_TYPE_CTRLRECT, nullptr)); + _trans_outline = static_cast<CtrlRect *>(sp_canvas_item_new(_desktop->getControls(), SP_TYPE_CTRLRECT, nullptr)); sp_canvas_item_hide(_trans_outline); _trans_outline->setDashed(true); @@ -724,7 +738,7 @@ TransformHandleSet::TransformHandleSet(SPDesktop *d, SPCanvasGroup *th_group) TransformHandleSet::~TransformHandleSet() { - for (auto & _handle : _handles) { + for (auto &_handle : _handles) { delete _handle; } } @@ -765,16 +779,18 @@ void TransformHandleSet::setBounds(Geom::Rect const &r, bool preserve_center) } else { for (unsigned i = 0; i < 4; ++i) { _scale_corners[i]->move(r.corner(i)); - _scale_sides[i]->move(Geom::middle_point(r.corner(i), r.corner(i+1))); + _scale_sides[i]->move(Geom::middle_point(r.corner(i), r.corner(i + 1))); _rot_corners[i]->move(r.corner(i)); - _skew_sides[i]->move(Geom::middle_point(r.corner(i), r.corner(i+1))); + _skew_sides[i]->move(Geom::middle_point(r.corner(i), r.corner(i + 1))); } - if (!preserve_center) _center->move(r.midpoint()); - if (_visible) _updateVisibility(true); + if (!preserve_center) + _center->move(r.midpoint()); + if (_visible) + _updateVisibility(true); } } -bool TransformHandleSet::event(Inkscape::UI::Tools::ToolBase *, GdkEvent*) +bool TransformHandleSet::event(Inkscape::UI::Tools::ToolBase *, GdkEvent *) { return false; } @@ -809,9 +825,8 @@ void TransformHandleSet::_updateVisibility(bool v) { if (v) { Geom::Rect b = bounds(); - Geom::Point handle_size( - gdk_pixbuf_get_width(handles[0]) / _desktop->current_zoom(), - gdk_pixbuf_get_height(handles[0]) / _desktop->current_zoom()); + Geom::Point handle_size(gdk_pixbuf_get_width(handles[0]) / _desktop->current_zoom(), + gdk_pixbuf_get_height(handles[0]) / _desktop->current_zoom()); Geom::Point bp = b.dimensions(); // do not scale when the bounding rectangle has zero width or height @@ -827,29 +842,26 @@ void TransformHandleSet::_updateVisibility(bool v) // make sense if rotate handles are not shown for (unsigned i = 0; i < 2; ++i) { Geom::Dim2 d = static_cast<Geom::Dim2>(i); - Geom::Dim2 otherd = static_cast<Geom::Dim2>((i+1)%2); + Geom::Dim2 otherd = static_cast<Geom::Dim2>((i + 1) % 2); show_scale_side[i] = (_mode == MODE_SCALE); - show_scale_side[i] &= (show_scale ? bp[d] >= handle_size[d] - : !Geom::are_near(bp[otherd], 0)); - show_skew[i] = (show_rotate && bp[d] >= handle_size[d] - && !Geom::are_near(bp[otherd], 0)); + show_scale_side[i] &= (show_scale ? bp[d] >= handle_size[d] : !Geom::are_near(bp[otherd], 0)); + show_skew[i] = (show_rotate && bp[d] >= handle_size[d] && !Geom::are_near(bp[otherd], 0)); } for (unsigned i = 0; i < 4; ++i) { _scale_corners[i]->setVisible(show_scale); _rot_corners[i]->setVisible(show_rotate); - _scale_sides[i]->setVisible(show_scale_side[i%2]); - _skew_sides[i]->setVisible(show_skew[i%2]); + _scale_sides[i]->setVisible(show_scale_side[i % 2]); + _skew_sides[i]->setVisible(show_skew[i % 2]); } // show rotation center if there is enough space (?) _center->setVisible(show_rotate /*&& bp[Geom::X] > handle_size[Geom::X] && bp[Geom::Y] > handle_size[Geom::Y]*/); } else { - for (auto & _handle : _handles) { + for (auto &_handle : _handles) { if (_handle != _active) _handle->setVisible(false); } } - } } // namespace UI diff --git a/src/ui/tool/transform-handle-set.h b/src/ui/tool/transform-handle-set.h index 1511e85f17d7362856dbbecac4e60cbf44dec12a..70407f84464663e54f31c8d5995f73c3c5fc7441 100644 --- a/src/ui/tool/transform-handle-set.h +++ b/src/ui/tool/transform-handle-set.h @@ -13,14 +13,15 @@ #ifndef SEEN_UI_TOOL_TRANSFORM_HANDLE_SET_H #define SEEN_UI_TOOL_TRANSFORM_HANDLE_SET_H -#include <memory> -#include <gdk/gdk.h> #include <2geom/forward.h> -#include "ui/tool/commit-events.h" -#include "ui/tool/manipulator.h" -#include "ui/tool/control-point.h" +#include <gdk/gdk.h> +#include <memory> + #include "enums.h" #include "snap-candidate.h" +#include "ui/tool/commit-events.h" +#include "ui/tool/control-point.h" +#include "ui/tool/manipulator.h" class SPDesktop; class SPCanvasGroup; @@ -34,10 +35,11 @@ class ScaleCornerHandle; class ScaleSideHandle; class RotationCenter; -class TransformHandleSet : public Manipulator { +class TransformHandleSet : public Manipulator +{ public: - - enum Mode { + enum Mode + { MODE_SCALE, MODE_ROTATE_SKEW }; @@ -65,7 +67,6 @@ public: sigc::signal<void, CommitEvent> signal_commit; private: - void _emitTransform(Geom::Affine const &); void _setActiveHandle(ControlPoint *h); void _clearActiveHandle(); @@ -77,9 +78,11 @@ private: void _updateVisibility(bool v); // TODO unions must GO AWAY: - union { + union + { ControlPoint *_handles[17]; - struct { + struct + { ScaleCornerHandle *_scale_corners[4]; ScaleSideHandle *_scale_sides[4]; RotateHandle *_rot_corners[4]; diff --git a/src/ui/toolbar/arc-toolbar.cpp b/src/ui/toolbar/arc-toolbar.cpp index fc5d48ec82f822d5a02ba8d1b44dd0b37cb624f9..0104f79688a1b3b1384a7ce44b874e5927332a35 100644 --- a/src/ui/toolbar/arc-toolbar.cpp +++ b/src/ui/toolbar/arc-toolbar.cpp @@ -28,19 +28,15 @@ #include "arc-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/radiotoolbutton.h> #include <gtkmm/separatortoolitem.h> #include "desktop.h" #include "document-undo.h" #include "mod360.h" -#include "selection.h" -#include "verbs.h" - #include "object/sp-ellipse.h" #include "object/sp-namedview.h" - +#include "selection.h" #include "ui/icon-names.h" #include "ui/pref-pusher.h" #include "ui/tools/arc-tool.h" @@ -50,34 +46,31 @@ #include "ui/widget/label-tool-item.h" #include "ui/widget/spin-button-tool-item.h" #include "ui/widget/unit-tracker.h" - +#include "verbs.h" #include "widgets/widget-sizes.h" - #include "xml/node-event-vector.h" -using Inkscape::UI::Widget::UnitTracker; -using Inkscape::UI::UXManager; using Inkscape::DocumentUndo; +using Inkscape::UI::UXManager; +using Inkscape::UI::Widget::UnitTracker; using Inkscape::Util::Quantity; using Inkscape::Util::unit_table; - static Inkscape::XML::NodeEventVector arc_tb_repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - Inkscape::UI::Toolbar::ArcToolbar::event_attr_changed, - nullptr, /* content_changed */ - nullptr /* order_changed */ + nullptr, /* child_added */ + nullptr, /* child_removed */ + Inkscape::UI::Toolbar::ArcToolbar::event_attr_changed, nullptr, /* content_changed */ + nullptr /* order_changed */ }; namespace Inkscape { namespace UI { namespace Toolbar { -ArcToolbar::ArcToolbar(SPDesktop *desktop) : - Toolbar(desktop), - _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)), - _freeze(false), - _repr(nullptr) +ArcToolbar::ArcToolbar(SPDesktop *desktop) + : Toolbar(desktop) + , _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)) + , _freeze(false) + , _repr(nullptr) { _tracker->setActiveUnit(desktop->getNamedView()->display_units); auto prefs = Inkscape::Preferences::get(); @@ -98,8 +91,8 @@ ArcToolbar::ArcToolbar(SPDesktop *desktop) : _rx_item->set_custom_numeric_menu_data(values); _tracker->addAdjustment(_rx_adj->gobj()); _rx_item->set_focus_widget(desktop->canvas); - _rx_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &ArcToolbar::value_changed), - _rx_adj, "rx")); + _rx_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &ArcToolbar::value_changed), _rx_adj, "rx")); _rx_item->set_sensitive(false); add(*_rx_item); } @@ -114,19 +107,19 @@ ArcToolbar::ArcToolbar(SPDesktop *desktop) : _ry_item->set_custom_numeric_menu_data(values); _tracker->addAdjustment(_ry_adj->gobj()); _ry_item->set_focus_widget(desktop->canvas); - _ry_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &ArcToolbar::value_changed), - _ry_adj, "ry")); + _ry_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &ArcToolbar::value_changed), _ry_adj, "ry")); _ry_item->set_sensitive(false); add(*_ry_item); } // add the units menu { - auto unit_menu = _tracker->create_tool_item(_("Units"), ("") ); + auto unit_menu = _tracker->create_tool_item(_("Units"), ("")); add(*unit_menu); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Start */ { @@ -147,12 +140,12 @@ ArcToolbar::ArcToolbar(SPDesktop *desktop) : eact->set_focus_widget(desktop->canvas); add(*eact); } - _start_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &ArcToolbar::startend_value_changed), - _start_adj, "start", _end_adj)); - _end_adj->signal_value_changed().connect( sigc::bind(sigc::mem_fun(*this, &ArcToolbar::startend_value_changed), - _end_adj, "end", _start_adj)); + _start_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &ArcToolbar::startend_value_changed), _start_adj, "start", _end_adj)); + _end_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &ArcToolbar::startend_value_changed), _end_adj, "end", _start_adj)); - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Arc: Slice, Arc, Chord */ { @@ -181,15 +174,14 @@ ArcToolbar::ArcToolbar(SPDesktop *desktop) : _type_buttons[type]->set_active(); int btn_index = 0; - for (auto btn : _type_buttons) - { + for (auto btn : _type_buttons) { btn->set_sensitive(); btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &ArcToolbar::type_changed), btn_index++)); add(*btn); } } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Make Whole */ { @@ -204,7 +196,7 @@ ArcToolbar::ArcToolbar(SPDesktop *desktop) : _single = true; // sensitivize make whole and open checkbox { - sensitivize( _start_adj->get_value(), _end_adj->get_value() ); + sensitivize(_start_adj->get_value(), _end_adj->get_value()); } desktop->connectEventContextChanged(sigc::mem_fun(*this, &ArcToolbar::check_ec)); @@ -214,23 +206,20 @@ ArcToolbar::ArcToolbar(SPDesktop *desktop) : ArcToolbar::~ArcToolbar() { - if(_repr) { + if (_repr) { _repr->removeListenerByData(this); GC::release(_repr); _repr = nullptr; } } -GtkWidget * -ArcToolbar::create(SPDesktop *desktop) +GtkWidget *ArcToolbar::create(SPDesktop *desktop) { auto toolbar = new ArcToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -ArcToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, - gchar const *value_name) +void ArcToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, gchar const *value_name) { // Per SVG spec "a [radius] value of zero disables rendering of the element". // However our implementation does not allow a setting of zero in the UI (not even in the XML editor) @@ -242,13 +231,13 @@ ArcToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, Unit const *unit = _tracker->getActiveUnit(); g_return_if_fail(unit != nullptr); - SPDocument* document = _desktop->getDocument(); + SPDocument *document = _desktop->getDocument(); Geom::Scale scale = document->getDocumentScale(); if (DocumentUndo::getUndoSensitive(document)) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble(Glib::ustring("/tools/shapes/arc/") + value_name, - Quantity::convert(adj->get_value(), unit, "px")); + Quantity::convert(adj->get_value(), unit, "px")); } // quit if run by the attr_changed listener @@ -261,11 +250,10 @@ ArcToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, bool modmade = false; Inkscape::Selection *selection = _desktop->getSelection(); - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (SP_IS_GENERICELLIPSE(item)) { - SPGenericEllipse *ge = SP_GENERICELLIPSE(item); if (!strcmp(value_name, "rx")) { @@ -283,17 +271,14 @@ ArcToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, } if (modmade) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_ARC, - _("Ellipse: Change radius")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_ARC, _("Ellipse: Change radius")); } _freeze = false; } -void -ArcToolbar::startend_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, - gchar const *value_name, - Glib::RefPtr<Gtk::Adjustment>& other_adj) +void ArcToolbar::startend_value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, gchar const *value_name, + Glib::RefPtr<Gtk::Adjustment> &other_adj) { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -308,20 +293,19 @@ ArcToolbar::startend_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, // in turn, prevent listener from responding _freeze = true; - gchar* namespaced_name = g_strconcat("sodipodi:", value_name, NULL); + gchar *namespaced_name = g_strconcat("sodipodi:", value_name, NULL); bool modmade = false; - auto itemlist= _desktop->getSelection()->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = _desktop->getSelection()->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (SP_IS_GENERICELLIPSE(item)) { - SPGenericEllipse *ge = SP_GENERICELLIPSE(item); if (!strcmp(value_name, "start")) { - ge->start = (adj->get_value() * M_PI)/ 180; + ge->start = (adj->get_value() * M_PI) / 180; } else { - ge->end = (adj->get_value() * M_PI)/ 180; + ge->end = (adj->get_value() * M_PI) / 180; } ge->normalize(); @@ -334,18 +318,16 @@ ArcToolbar::startend_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, g_free(namespaced_name); - sensitivize( adj->get_value(), other_adj->get_value() ); + sensitivize(adj->get_value(), other_adj->get_value()); if (modmade) { - DocumentUndo::maybeDone(_desktop->getDocument(), value_name, SP_VERB_CONTEXT_ARC, - _("Arc: Change start/end")); + DocumentUndo::maybeDone(_desktop->getDocument(), value_name, SP_VERB_CONTEXT_ARC, _("Arc: Change start/end")); } _freeze = false; } -void -ArcToolbar::type_changed( int type ) +void ArcToolbar::type_changed(int type) { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -378,14 +360,14 @@ ArcToolbar::type_changed( int type ) default: std::cerr << "sp_arctb_type_changed: bad arc type: " << type << std::endl; } - + bool modmade = false; - auto itemlist= _desktop->getSelection()->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = _desktop->getSelection()->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (SP_IS_GENERICELLIPSE(item)) { Inkscape::XML::Node *repr = item->getRepr(); - repr->setAttribute("sodipodi:open", (open?"true":nullptr) ); + repr->setAttribute("sodipodi:open", (open ? "true" : nullptr)); repr->setAttribute("sodipodi:arc-type", arc_type); item->updateRepr(); modmade = true; @@ -393,38 +375,37 @@ ArcToolbar::type_changed( int type ) } if (modmade) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_ARC, - _("Arc: Changed arc type")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_ARC, _("Arc: Changed arc type")); } _freeze = false; } -void -ArcToolbar::defaults() +void ArcToolbar::defaults() { _start_adj->set_value(0.0); _end_adj->set_value(0.0); - if(_desktop->canvas) _desktop->canvas->grab_focus(); + if (_desktop->canvas) + _desktop->canvas->grab_focus(); } -void -ArcToolbar::sensitivize( double v1, double v2 ) +void ArcToolbar::sensitivize(double v1, double v2) { if (v1 == 0 && v2 == 0) { if (_single) { // only for a single selected ellipse (for now) - for (auto btn : _type_buttons) btn->set_sensitive(false); + for (auto btn : _type_buttons) + btn->set_sensitive(false); _make_whole->set_sensitive(false); } } else { - for (auto btn : _type_buttons) btn->set_sensitive(true); + for (auto btn : _type_buttons) + btn->set_sensitive(true); _make_whole->set_sensitive(true); } } -void -ArcToolbar::check_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) +void ArcToolbar::check_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec) { if (SP_IS_ARC_CONTEXT(ec)) { _changed = _desktop->getSelection()->connectChanged(sigc::mem_fun(*this, &ArcToolbar::selection_changed)); @@ -432,7 +413,7 @@ ArcToolbar::check_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) } else { if (_changed) { _changed.disconnect(); - if(_repr) { + if (_repr) { _repr->removeListenerByData(this); Inkscape::GC::release(_repr); _repr = nullptr; @@ -441,13 +422,12 @@ ArcToolbar::check_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) } } -void -ArcToolbar::selection_changed(Inkscape::Selection *selection) +void ArcToolbar::selection_changed(Inkscape::Selection *selection) { int n_selected = 0; Inkscape::XML::Node *repr = nullptr; - if ( _repr ) { + if (_repr) { _item = nullptr; _repr->removeListenerByData(this); GC::release(_repr); @@ -456,7 +436,7 @@ ArcToolbar::selection_changed(Inkscape::Selection *selection) SPItem *item = nullptr; - for(auto i : selection->items()){ + for (auto i : selection->items()) { if (SP_IS_GENERICELLIPSE(i)) { n_selected++; item = i; @@ -482,16 +462,14 @@ ArcToolbar::selection_changed(Inkscape::Selection *selection) } } else { // FIXME: implement averaging of all parameters for multiple selected - //gtk_label_set_markup(GTK_LABEL(l), _("<b>Average:</b>")); + // gtk_label_set_markup(GTK_LABEL(l), _("<b>Average:</b>")); _mode_item->set_markup(_("<b>Change:</b>")); - sensitivize( 1, 0 ); + sensitivize(1, 0); } } -void -ArcToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const * /*name*/, - gchar const * /*old_value*/, gchar const * /*new_value*/, - bool /*is_interactive*/, gpointer data) +void ArcToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const * /*name*/, gchar const * /*old_value*/, + gchar const * /*new_value*/, bool /*is_interactive*/, gpointer data) { auto toolbar = reinterpret_cast<ArcToolbar *>(data); @@ -520,8 +498,8 @@ ArcToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const * /*name*/ sp_repr_get_double(repr, "sodipodi:start", &start); sp_repr_get_double(repr, "sodipodi:end", &end); - toolbar->_start_adj->set_value(mod360((start * 180)/M_PI)); - toolbar->_end_adj->set_value(mod360((end * 180)/M_PI)); + toolbar->_start_adj->set_value(mod360((start * 180) / M_PI)); + toolbar->_end_adj->set_value(mod360((end * 180) / M_PI)); toolbar->sensitivize(toolbar->_start_adj->get_value(), toolbar->_end_adj->get_value()); @@ -533,9 +511,9 @@ ArcToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const * /*name*/ arctypestr = (openstr ? "arc" : "slice"); } - if (!strcmp(arctypestr,"slice")) { + if (!strcmp(arctypestr, "slice")) { toolbar->_type_buttons[0]->set_active(); - } else if (!strcmp(arctypestr,"arc")) { + } else if (!strcmp(arctypestr, "arc")) { toolbar->_type_buttons[1]->set_active(); } else { toolbar->_type_buttons[2]->set_active(); @@ -544,10 +522,9 @@ ArcToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const * /*name*/ toolbar->_freeze = false; } -} -} -} - +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/arc-toolbar.h b/src/ui/toolbar/arc-toolbar.h index b0b04500b99a4c5651c3da1f8a9427f66415a820..71a5a507d1c3c578ab3c45c5d3e7f13fbe20dad0 100644 --- a/src/ui/toolbar/arc-toolbar.h +++ b/src/ui/toolbar/arc-toolbar.h @@ -28,17 +28,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; class SPItem; namespace Gtk { class RadioToolButton; class ToolButton; -} +} // namespace Gtk namespace Inkscape { class Selection; @@ -56,10 +56,11 @@ namespace Widget { class LabelToolItem; class SpinButtonToolItem; class UnitTracker; -} +} // namespace Widget namespace Toolbar { -class ArcToolbar : public Toolbar { +class ArcToolbar : public Toolbar +{ private: UI::Widget::UnitTracker *_tracker; @@ -82,15 +83,13 @@ private: XML::Node *_repr; SPItem *_item; - void value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, - gchar const *value_name); - void startend_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, - gchar const *value_name, - Glib::RefPtr<Gtk::Adjustment>& other_adj); - void type_changed( int type ); + void value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, gchar const *value_name); + void startend_value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, gchar const *value_name, + Glib::RefPtr<Gtk::Adjustment> &other_adj); + void type_changed(int type); void defaults(); - void sensitivize( double v1, double v2 ); - void check_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec); + void sensitivize(double v1, double v2); + void check_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec); void selection_changed(Inkscape::Selection *selection); sigc::connection _changed; @@ -100,17 +99,13 @@ protected: ~ArcToolbar() override; public: - static GtkWidget * create(SPDesktop *desktop); - static void event_attr_changed(Inkscape::XML::Node *repr, - gchar const *name, - gchar const *old_value, - gchar const *new_value, - bool is_interactive, - gpointer data); + static GtkWidget *create(SPDesktop *desktop); + static void event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, gchar const *old_value, + gchar const *new_value, bool is_interactive, gpointer data); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_ARC_TOOLBAR_H */ diff --git a/src/ui/toolbar/box3d-toolbar.cpp b/src/ui/toolbar/box3d-toolbar.cpp index fe6201748a37b4d4359eaa4076c735a73e77b02e..0e2465bfa6d056c1929bcab343c5337b293a5353 100644 --- a/src/ui/toolbar/box3d-toolbar.cpp +++ b/src/ui/toolbar/box3d-toolbar.cpp @@ -33,43 +33,38 @@ #include "desktop.h" #include "document-undo.h" #include "document.h" -#include "selection.h" -#include "verbs.h" - #include "object/box3d.h" #include "object/persp3d.h" - +#include "selection.h" #include "ui/icon-names.h" #include "ui/pref-pusher.h" #include "ui/tools/box3d-tool.h" #include "ui/uxmanager.h" #include "ui/widget/canvas.h" #include "ui/widget/spin-button-tool-item.h" - +#include "verbs.h" #include "xml/node-event-vector.h" -using Inkscape::UI::UXManager; using Inkscape::DocumentUndo; +using Inkscape::UI::UXManager; -static Inkscape::XML::NodeEventVector box3d_persp_tb_repr_events = -{ - nullptr, /* child_added */ - nullptr, /* child_removed */ - Inkscape::UI::Toolbar::Box3DToolbar::event_attr_changed, - nullptr, /* content_changed */ - nullptr /* order_changed */ +static Inkscape::XML::NodeEventVector box3d_persp_tb_repr_events = { + nullptr, /* child_added */ + nullptr, /* child_removed */ + Inkscape::UI::Toolbar::Box3DToolbar::event_attr_changed, nullptr, /* content_changed */ + nullptr /* order_changed */ }; namespace Inkscape { namespace UI { namespace Toolbar { Box3DToolbar::Box3DToolbar(SPDesktop *desktop) - : Toolbar(desktop), - _repr(nullptr), - _freeze(false) + : Toolbar(desktop) + , _repr(nullptr) + , _freeze(false) { - auto prefs = Inkscape::Preferences::get(); - auto document = desktop->getDocument(); + auto prefs = Inkscape::Preferences::get(); + auto document = desktop->getDocument(); auto persp_impl = document->getCurrentPersp3DImpl(); /* Angle X */ @@ -82,8 +77,8 @@ Box3DToolbar::Box3DToolbar(SPDesktop *desktop) _angle_x_item->set_tooltip_text(_("Angle of PLs in X direction")); _angle_x_item->set_custom_numeric_menu_data(values); _angle_x_item->set_focus_widget(desktop->canvas); - _angle_x_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::angle_value_changed), - _angle_x_adj, Proj::X)); + _angle_x_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::angle_value_changed), _angle_x_adj, Proj::X)); add(*_angle_x_item); } @@ -99,9 +94,10 @@ Box3DToolbar::Box3DToolbar(SPDesktop *desktop) _vp_x_state_item = add_toggle_button(_("State of VP in X direction"), _("Toggle VP in X direction between 'finite' and 'infinite' (=parallel)")); _vp_x_state_item->set_icon_name(INKSCAPE_ICON("perspective-parallel")); - _vp_x_state_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::vp_state_changed), Proj::X)); - _angle_x_item->set_sensitive( !prefs->getBool("/tools/shapes/3dbox/vp_x_state", true) ); - _vp_x_state_item->set_active( prefs->getBool("/tools/shapes/3dbox/vp_x_state", true) ); + _vp_x_state_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::vp_state_changed), Proj::X)); + _angle_x_item->set_sensitive(!prefs->getBool("/tools/shapes/3dbox/vp_x_state", true)); + _vp_x_state_item->set_active(prefs->getBool("/tools/shapes/3dbox/vp_x_state", true)); } /* Angle Y */ @@ -114,8 +110,8 @@ Box3DToolbar::Box3DToolbar(SPDesktop *desktop) std::vector<double> values = {-90, -60, -30, 0, 30, 60, 90}; _angle_y_item->set_custom_numeric_menu_data(values); _angle_y_item->set_focus_widget(desktop->canvas); - _angle_y_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::angle_value_changed), - _angle_y_adj, Proj::Y)); + _angle_y_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::angle_value_changed), _angle_y_adj, Proj::Y)); add(*_angle_y_item); } @@ -131,9 +127,10 @@ Box3DToolbar::Box3DToolbar(SPDesktop *desktop) _vp_y_state_item = add_toggle_button(_("State of VP in Y direction"), _("Toggle VP in Y direction between 'finite' and 'infinite' (=parallel)")); _vp_y_state_item->set_icon_name(INKSCAPE_ICON("perspective-parallel")); - _vp_y_state_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::vp_state_changed), Proj::Y)); - _angle_y_item->set_sensitive( !prefs->getBool("/tools/shapes/3dbox/vp_y_state", true) ); - _vp_y_state_item->set_active( prefs->getBool("/tools/shapes/3dbox/vp_y_state", true) ); + _vp_y_state_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::vp_state_changed), Proj::Y)); + _angle_y_item->set_sensitive(!prefs->getBool("/tools/shapes/3dbox/vp_y_state", true)); + _vp_y_state_item->set_active(prefs->getBool("/tools/shapes/3dbox/vp_y_state", true)); } /* Angle Z */ @@ -146,8 +143,8 @@ Box3DToolbar::Box3DToolbar(SPDesktop *desktop) std::vector<double> values = {-90, -60, -30, 0, 30, 60, 90}; _angle_z_item->set_custom_numeric_menu_data(values); _angle_z_item->set_focus_widget(desktop->canvas); - _angle_z_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::angle_value_changed), - _angle_z_adj, Proj::Z)); + _angle_z_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::angle_value_changed), _angle_z_adj, Proj::Z)); add(*_angle_z_item); } @@ -163,9 +160,10 @@ Box3DToolbar::Box3DToolbar(SPDesktop *desktop) _vp_z_state_item = add_toggle_button(_("State of VP in Z direction"), _("Toggle VP in Z direction between 'finite' and 'infinite' (=parallel)")); _vp_z_state_item->set_icon_name(INKSCAPE_ICON("perspective-parallel")); - _vp_z_state_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::vp_state_changed), Proj::Z)); + _vp_z_state_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &Box3DToolbar::vp_state_changed), Proj::Z)); _angle_z_item->set_sensitive(!prefs->getBool("/tools/shapes/3dbox/vp_z_state", true)); - _vp_z_state_item->set_active( prefs->getBool("/tools/shapes/3dbox/vp_z_state", true) ); + _vp_z_state_item->set_active(prefs->getBool("/tools/shapes/3dbox/vp_z_state", true)); } desktop->connectEventContextChanged(sigc::mem_fun(*this, &Box3DToolbar::check_ec)); @@ -173,16 +171,13 @@ Box3DToolbar::Box3DToolbar(SPDesktop *desktop) show_all(); } -GtkWidget * -Box3DToolbar::create(SPDesktop *desktop) +GtkWidget *Box3DToolbar::create(SPDesktop *desktop) { auto toolbar = new Box3DToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -Box3DToolbar::angle_value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, - Proj::Axis axis) +void Box3DToolbar::angle_value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, Proj::Axis axis) { SPDocument *document = _desktop->getDocument(); @@ -201,18 +196,17 @@ Box3DToolbar::angle_value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, } Persp3D *persp = sel_persps.front(); - persp->perspective_impl->tmat.set_infinite_direction (axis, - adj->get_value()); + persp->perspective_impl->tmat.set_infinite_direction(axis, adj->get_value()); persp->updateRepr(); // TODO: use the correct axis here, too - DocumentUndo::maybeDone(document, "perspangle", SP_VERB_CONTEXT_3DBOX, _("3D Box: Change perspective (angle of infinite axis)")); + DocumentUndo::maybeDone(document, "perspangle", SP_VERB_CONTEXT_3DBOX, + _("3D Box: Change perspective (angle of infinite axis)")); _freeze = false; } -void -Box3DToolbar::vp_state_changed(Proj::Axis axis) +void Box3DToolbar::vp_state_changed(Proj::Axis axis) { // TODO: Take all selected perspectives into account auto sel_persps = _desktop->getSelection()->perspList(); @@ -224,7 +218,7 @@ Box3DToolbar::vp_state_changed(Proj::Axis axis) Gtk::ToggleToolButton *btn = nullptr; - switch(axis) { + switch (axis) { case Proj::X: btn = _vp_x_state_item; break; @@ -239,11 +233,10 @@ Box3DToolbar::vp_state_changed(Proj::Axis axis) } bool set_infinite = btn->get_active(); - persp->set_VP_state (axis, set_infinite ? Proj::VP_INFINITE : Proj::VP_FINITE); + persp->set_VP_state(axis, set_infinite ? Proj::VP_INFINITE : Proj::VP_FINITE); } -void -Box3DToolbar::check_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) +void Box3DToolbar::check_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec) { if (SP_IS_BOX3D_CONTEXT(ec)) { _changed = desktop->getSelection()->connectChanged(sigc::mem_fun(*this, &Box3DToolbar::selection_changed)); @@ -268,8 +261,7 @@ Box3DToolbar::~Box3DToolbar() */ // FIXME: This should rather be put into persp3d-reference.cpp or something similar so that it reacts upon each // Change of the perspective, and not of the current selection (but how to refer to the toolbar then?) -void -Box3DToolbar::selection_changed(Inkscape::Selection *selection) +void Box3DToolbar::selection_changed(Inkscape::Selection *selection) { // Here the following should be done: If all selected boxes have finite VPs in a certain direction, // disable the angle entry fields for this direction (otherwise entering a value in them should only @@ -306,11 +298,10 @@ Box3DToolbar::selection_changed(Inkscape::Selection *selection) } } -void -Box3DToolbar::resync_toolbar(Inkscape::XML::Node *persp_repr) +void Box3DToolbar::resync_toolbar(Inkscape::XML::Node *persp_repr) { if (!persp_repr) { - g_print ("No perspective given to box3d_resync_toolbar().\n"); + g_print("No perspective given to box3d_resync_toolbar().\n"); return; } @@ -319,26 +310,14 @@ Box3DToolbar::resync_toolbar(Inkscape::XML::Node *persp_repr) // Hmm, is it an error if this happens? return; } - set_button_and_adjustment(persp, Proj::X, - _angle_x_adj, - _angle_x_item, - _vp_x_state_item); - set_button_and_adjustment(persp, Proj::Y, - _angle_y_adj, - _angle_y_item, - _vp_y_state_item); - set_button_and_adjustment(persp, Proj::Z, - _angle_z_adj, - _angle_z_item, - _vp_z_state_item); + set_button_and_adjustment(persp, Proj::X, _angle_x_adj, _angle_x_item, _vp_x_state_item); + set_button_and_adjustment(persp, Proj::Y, _angle_y_adj, _angle_y_item, _vp_y_state_item); + set_button_and_adjustment(persp, Proj::Z, _angle_z_adj, _angle_z_item, _vp_z_state_item); } -void -Box3DToolbar::set_button_and_adjustment(Persp3D *persp, - Proj::Axis axis, - Glib::RefPtr<Gtk::Adjustment>& adj, - UI::Widget::SpinButtonToolItem *spin_btn, - Gtk::ToggleToolButton *toggle_btn) +void Box3DToolbar::set_button_and_adjustment(Persp3D *persp, Proj::Axis axis, Glib::RefPtr<Gtk::Adjustment> &adj, + UI::Widget::SpinButtonToolItem *spin_btn, + Gtk::ToggleToolButton *toggle_btn) { // TODO: Take all selected perspectives into account but don't touch the state button if not all of them // have the same state (otherwise a call to box3d_vp_z_state_changed() is triggered and the states @@ -359,15 +338,10 @@ Box3DToolbar::set_button_and_adjustment(Persp3D *persp, } } -void -Box3DToolbar::event_attr_changed(Inkscape::XML::Node *repr, - gchar const * /*name*/, - gchar const * /*old_value*/, - gchar const * /*new_value*/, - bool /*is_interactive*/, - gpointer data) +void Box3DToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const * /*name*/, gchar const * /*old_value*/, + gchar const * /*new_value*/, bool /*is_interactive*/, gpointer data) { - auto toolbar = reinterpret_cast<Box3DToolbar*>(data); + auto toolbar = reinterpret_cast<Box3DToolbar *>(data); // quit if run by the attr_changed or selection changed listener if (toolbar->_freeze) { @@ -379,9 +353,9 @@ Box3DToolbar::event_attr_changed(Inkscape::XML::Node *repr, toolbar->_freeze = true; // TODO: Only update the appropriate part of the toolbar -// if (!strcmp(name, "inkscape:vp_z")) { - toolbar->resync_toolbar(repr); -// } + // if (!strcmp(name, "inkscape:vp_z")) { + toolbar->resync_toolbar(repr); + // } Persp3D *persp = Persp3D::get_from_repr(repr); persp->update_box_reprs(); @@ -394,19 +368,18 @@ Box3DToolbar::event_attr_changed(Inkscape::XML::Node *repr, * * TODO: Isn't there something in 2Geom or cmath that does this? */ -double -Box3DToolbar::normalize_angle(double a) { - double angle = a + ((int) (a/360.0))*360; +double Box3DToolbar::normalize_angle(double a) +{ + double angle = a + ((int)(a / 360.0)) * 360; if (angle < 0) { angle += 360.0; } return angle; } -} -} -} - +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/box3d-toolbar.h b/src/ui/toolbar/box3d-toolbar.h index 8ba7872d9188f98e99350154b628ae2a3c2f788a..12214633106ac0290c43839b21ad5ff22986897d 100644 --- a/src/ui/toolbar/box3d-toolbar.h +++ b/src/ui/toolbar/box3d-toolbar.h @@ -28,9 +28,8 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include "axis-manip.h" +#include "toolbar.h" namespace Gtk { class Adjustment; @@ -56,7 +55,8 @@ class ToolBase; } namespace Toolbar { -class Box3DToolbar : public Toolbar { +class Box3DToolbar : public Toolbar +{ private: UI::Widget::SpinButtonToolItem *_angle_x_item; UI::Widget::SpinButtonToolItem *_angle_y_item; @@ -73,17 +73,13 @@ private: XML::Node *_repr; bool _freeze; - void angle_value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, - Proj::Axis axis); + void angle_value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, Proj::Axis axis); void vp_state_changed(Proj::Axis axis); - void check_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec); + void check_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec); void selection_changed(Inkscape::Selection *selection); void resync_toolbar(Inkscape::XML::Node *persp_repr); - void set_button_and_adjustment(Persp3D *persp, - Proj::Axis axis, - Glib::RefPtr<Gtk::Adjustment>& adj, - UI::Widget::SpinButtonToolItem *spin_btn, - Gtk::ToggleToolButton *toggle_btn); + void set_button_and_adjustment(Persp3D *persp, Proj::Axis axis, Glib::RefPtr<Gtk::Adjustment> &adj, + UI::Widget::SpinButtonToolItem *spin_btn, Gtk::ToggleToolButton *toggle_btn); double normalize_angle(double a); sigc::connection _changed; @@ -93,16 +89,11 @@ protected: ~Box3DToolbar() override; public: - static GtkWidget * create(SPDesktop *desktop); - static void event_attr_changed(Inkscape::XML::Node *repr, - gchar const *name, - gchar const *old_value, - gchar const *new_value, - bool is_interactive, - gpointer data); - + static GtkWidget *create(SPDesktop *desktop); + static void event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, gchar const *old_value, + gchar const *new_value, bool is_interactive, gpointer data); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_BOX3D_TOOLBAR_H */ diff --git a/src/ui/toolbar/calligraphy-toolbar.cpp b/src/ui/toolbar/calligraphy-toolbar.cpp index 5f0ecfcb22bf86c5de0ffde0c13a48ad92cdbea9..3b9ab6e47f2f779885fe9aeb4ce88784ffda8bf0 100644 --- a/src/ui/toolbar/calligraphy-toolbar.cpp +++ b/src/ui/toolbar/calligraphy-toolbar.cpp @@ -28,24 +28,22 @@ #include "calligraphy-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/comboboxtext.h> #include <gtkmm/separatortoolitem.h> #include "desktop.h" #include "document-undo.h" - +#include "ui/dialog/calligraphic-profile-rename.h" #include "ui/icon-names.h" #include "ui/simple-pref-pusher.h" #include "ui/uxmanager.h" -#include "ui/dialog/calligraphic-profile-rename.h" #include "ui/widget/canvas.h" #include "ui/widget/spin-button-tool-item.h" using Inkscape::DocumentUndo; -std::vector<Glib::ustring> get_presets_list() { - +std::vector<Glib::ustring> get_presets_list() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); std::vector<Glib::ustring> presets = prefs->getAllDirs("/tools/calligraphic/preset"); @@ -58,8 +56,8 @@ namespace UI { namespace Toolbar { CalligraphyToolbar::CalligraphyToolbar(SPDesktop *desktop) - : Toolbar(desktop), - _presets_blocked(false) + : Toolbar(desktop) + , _presets_blocked(false) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -86,15 +84,17 @@ CalligraphyToolbar::CalligraphyToolbar(SPDesktop *desktop) add(*profile_edit_item); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { /* Width */ - std::vector<Glib::ustring> labels = {_("(hairline)"), "", "", "", _("(default)"), "", "", "", "", _("(broad stroke)")}; - std::vector<double> values = { 1, 3, 5, 10, 15, 20, 30, 50, 75, 100}; + std::vector<Glib::ustring> labels = {_("(hairline)"), "", "", "", _("(default)"), "", "", "", "", + _("(broad stroke)")}; + std::vector<double> values = {1, 3, 5, 10, 15, 20, 30, 50, 75, 100}; auto width_val = prefs->getDouble("/tools/calligraphic/width", 15); _width_adj = Gtk::Adjustment::create(width_val, 1, 100, 1.0, 10.0); - auto width_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-width", _("Width:"), _width_adj, 1, 0)); + auto width_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-width", _("Width:"), _width_adj, 1, 0)); width_item->set_tooltip_text(_("The width of the calligraphic pen (relative to the visible canvas area)")); width_item->set_custom_numeric_menu_data(values, labels); width_item->set_focus_widget(desktop->canvas); @@ -107,36 +107,40 @@ CalligraphyToolbar::CalligraphyToolbar(SPDesktop *desktop) /* Use Pressure button */ { - _usepressure = add_toggle_button(_("Pressure"), - _("Use the pressure of the input device to alter the width of the pen")); + _usepressure = + add_toggle_button(_("Pressure"), _("Use the pressure of the input device to alter the width of the pen")); _usepressure->set_icon_name(INKSCAPE_ICON("draw-use-pressure")); _widget_map["usepressure"] = G_OBJECT(_usepressure->gobj()); _usepressure_pusher.reset(new SimplePrefPusher(_usepressure, "/tools/calligraphic/usepressure")); _usepressure->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CalligraphyToolbar::on_pref_toggled), - _usepressure, - "/tools/calligraphic/usepressure")); + _usepressure, "/tools/calligraphic/usepressure")); } /* Trace Background button */ { - _tracebackground = add_toggle_button(_("Trace Background"), - _("Trace the lightness of the background by the width of the pen (white - minimum width, black - maximum width)")); + _tracebackground = + add_toggle_button(_("Trace Background"), _("Trace the lightness of the background by the width of the pen " + "(white - minimum width, black - maximum width)")); _tracebackground->set_icon_name(INKSCAPE_ICON("draw-trace-background")); _widget_map["tracebackground"] = G_OBJECT(_tracebackground->gobj()); _tracebackground_pusher.reset(new SimplePrefPusher(_tracebackground, "/tools/calligraphic/tracebackground")); - _tracebackground->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &CalligraphyToolbar::on_pref_toggled), - _tracebackground, - "/tools/calligraphic/tracebackground")); + _tracebackground->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &CalligraphyToolbar::on_pref_toggled), _tracebackground, + "/tools/calligraphic/tracebackground")); } { /* Thinning */ - std::vector<Glib::ustring> labels = {_("(speed blows up stroke)"), "", "", _("(slight widening)"), _("(constant width)"), _("(slight thinning, default)"), "", "", _("(speed deflates stroke)")}; - std::vector<double> values = { -100, -40, -20, -10, 0, 10, 20, 40, 100}; + std::vector<Glib::ustring> labels = { + _("(speed blows up stroke)"), "", "", _("(slight widening)"), _("(constant width)"), + _("(slight thinning, default)"), "", "", _("(speed deflates stroke)")}; + std::vector<double> values = {-100, -40, -20, -10, 0, 10, 20, 40, 100}; auto thinning_val = prefs->getDouble("/tools/calligraphic/thinning", 10); _thinning_adj = Gtk::Adjustment::create(thinning_val, -100, 100, 1, 10.0); - auto thinning_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-thinning", _("Thinning:"), _thinning_adj, 1, 0)); - thinning_item->set_tooltip_text(("How much velocity thins the stroke (> 0 makes fast strokes thinner, < 0 makes them broader, 0 makes width independent of velocity)")); + auto thinning_item = Gtk::manage( + new UI::Widget::SpinButtonToolItem("calligraphy-thinning", _("Thinning:"), _thinning_adj, 1, 0)); + thinning_item->set_tooltip_text(("How much velocity thins the stroke (> 0 makes fast strokes thinner, < 0 " + "makes them broader, 0 makes width independent of velocity)")); thinning_item->set_custom_numeric_menu_data(values, labels); thinning_item->set_focus_widget(desktop->canvas); _thinning_adj->signal_value_changed().connect(sigc::mem_fun(*this, &CalligraphyToolbar::velthin_value_changed)); @@ -145,16 +149,19 @@ CalligraphyToolbar::CalligraphyToolbar(SPDesktop *desktop) thinning_item->set_sensitive(true); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { /* Angle */ - std::vector<Glib::ustring> labels = {_("(left edge up)"), "", "", _("(horizontal)"), _("(default)"), "", _("(right edge up)")}; - std::vector<double> values = { -90, -60, -30, 0, 30, 60, 90}; + std::vector<Glib::ustring> labels = {_("(left edge up)"), "", "", _("(horizontal)"), _("(default)"), "", + _("(right edge up)")}; + std::vector<double> values = {-90, -60, -30, 0, 30, 60, 90}; auto angle_val = prefs->getDouble("/tools/calligraphic/angle", 30); _angle_adj = Gtk::Adjustment::create(angle_val, -90.0, 90.0, 1.0, 10.0); - _angle_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-angle", _("Angle:"), _angle_adj, 1, 0)); - _angle_item->set_tooltip_text(_("The angle of the pen's nib (in degrees; 0 = horizontal; has no effect if fixation = 0)")); + _angle_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-angle", _("Angle:"), _angle_adj, 1, 0)); + _angle_item->set_tooltip_text( + _("The angle of the pen's nib (in degrees; 0 = horizontal; has no effect if fixation = 0)")); _angle_item->set_custom_numeric_menu_data(values, labels); _angle_item->set_focus_widget(desktop->canvas); _angle_adj->signal_value_changed().connect(sigc::mem_fun(*this, &CalligraphyToolbar::angle_value_changed)); @@ -165,8 +172,8 @@ CalligraphyToolbar::CalligraphyToolbar(SPDesktop *desktop) /* Use Tilt button */ { - _usetilt = add_toggle_button(_("Tilt"), - _("Use the tilt of the input device to alter the angle of the pen's nib")); + _usetilt = + add_toggle_button(_("Tilt"), _("Use the tilt of the input device to alter the angle of the pen's nib")); _usetilt->set_icon_name(INKSCAPE_ICON("draw-use-tilt")); _widget_map["usetilt"] = G_OBJECT(_usetilt->gobj()); _usetilt_pusher.reset(new SimplePrefPusher(_usetilt, "/tools/calligraphic/usetilt")); @@ -177,49 +184,63 @@ CalligraphyToolbar::CalligraphyToolbar(SPDesktop *desktop) { /* Fixation */ - std::vector<Glib::ustring> labels = {_("(perpendicular to stroke, \"brush\")"), "", "", "", _("(almost fixed, default)"), _("(fixed by Angle, \"pen\")")}; - std::vector<double> values = { 0, 20, 40, 60, 90, 100}; + std::vector<Glib::ustring> labels = {_("(perpendicular to stroke, \"brush\")"), + "", + "", + "", + _("(almost fixed, default)"), + _("(fixed by Angle, \"pen\")")}; + std::vector<double> values = {0, 20, 40, 60, 90, 100}; auto flatness_val = prefs->getDouble("/tools/calligraphic/flatness", 90); _fixation_adj = Gtk::Adjustment::create(flatness_val, 0.0, 100, 1.0, 10.0); - auto flatness_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-fixation", _("Fixation:"), _fixation_adj, 1, 0)); - flatness_item->set_tooltip_text(_("Angle behavior (0 = nib always perpendicular to stroke direction, 100 = fixed angle)")); + auto flatness_item = Gtk::manage( + new UI::Widget::SpinButtonToolItem("calligraphy-fixation", _("Fixation:"), _fixation_adj, 1, 0)); + flatness_item->set_tooltip_text( + _("Angle behavior (0 = nib always perpendicular to stroke direction, 100 = fixed angle)")); flatness_item->set_custom_numeric_menu_data(values, labels); flatness_item->set_focus_widget(desktop->canvas); - _fixation_adj->signal_value_changed().connect(sigc::mem_fun(*this, &CalligraphyToolbar::flatness_value_changed)); + _fixation_adj->signal_value_changed().connect( + sigc::mem_fun(*this, &CalligraphyToolbar::flatness_value_changed)); _widget_map["flatness"] = G_OBJECT(_fixation_adj->gobj()); add(*flatness_item); flatness_item->set_sensitive(true); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { /* Cap Rounding */ - std::vector<Glib::ustring> labels = {_("(blunt caps, default)"), _("(slightly bulging)"), "", "", _("(approximately round)"), _("(long protruding caps)")}; - std::vector<double> values = { 0, 0.3, 0.5, 1.0, 1.4, 5.0}; + std::vector<Glib::ustring> labels = {_("(blunt caps, default)"), _("(slightly bulging)"), "", "", + _("(approximately round)"), _("(long protruding caps)")}; + std::vector<double> values = {0, 0.3, 0.5, 1.0, 1.4, 5.0}; auto cap_rounding_val = prefs->getDouble("/tools/calligraphic/cap_rounding", 0.0); _cap_rounding_adj = Gtk::Adjustment::create(cap_rounding_val, 0.0, 5.0, 0.01, 0.1); - auto cap_rounding_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-cap-rounding", _("Caps:"), _cap_rounding_adj, 0.01, 2)); + auto cap_rounding_item = Gtk::manage( + new UI::Widget::SpinButtonToolItem("calligraphy-cap-rounding", _("Caps:"), _cap_rounding_adj, 0.01, 2)); // TRANSLATORS: "cap" means "end" (both start and finish) here - cap_rounding_item->set_tooltip_text(_("Increase to make caps at the ends of strokes protrude more (0 = no caps, 1 = round caps)")); + cap_rounding_item->set_tooltip_text( + _("Increase to make caps at the ends of strokes protrude more (0 = no caps, 1 = round caps)")); cap_rounding_item->set_custom_numeric_menu_data(values, labels); cap_rounding_item->set_focus_widget(desktop->canvas); - _cap_rounding_adj->signal_value_changed().connect(sigc::mem_fun(*this, &CalligraphyToolbar::cap_rounding_value_changed)); + _cap_rounding_adj->signal_value_changed().connect( + sigc::mem_fun(*this, &CalligraphyToolbar::cap_rounding_value_changed)); _widget_map["cap_rounding"] = G_OBJECT(_cap_rounding_adj->gobj()); add(*cap_rounding_item); cap_rounding_item->set_sensitive(true); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { /* Tremor */ - std::vector<Glib::ustring> labels = {_("(smooth line)"), _("(slight tremor)"), _("(noticeable tremor)"), "", "", _("(maximum tremor)")}; - std::vector<double> values = { 0, 10, 20, 40, 60, 100}; + std::vector<Glib::ustring> labels = { + _("(smooth line)"), _("(slight tremor)"), _("(noticeable tremor)"), "", "", _("(maximum tremor)")}; + std::vector<double> values = {0, 10, 20, 40, 60, 100}; auto tremor_val = prefs->getDouble("/tools/calligraphic/tremor", 0.0); _tremor_adj = Gtk::Adjustment::create(tremor_val, 0.0, 100, 1, 10.0); - auto tremor_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-tremor", _("Tremor:"), _tremor_adj, 1, 0)); + auto tremor_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-tremor", _("Tremor:"), _tremor_adj, 1, 0)); tremor_item->set_tooltip_text(_("Increase to make strokes rugged and trembling")); tremor_item->set_custom_numeric_menu_data(values, labels); tremor_item->set_focus_widget(desktop->canvas); @@ -232,11 +253,13 @@ CalligraphyToolbar::CalligraphyToolbar(SPDesktop *desktop) { /* Wiggle */ - std::vector<Glib::ustring> labels = {_("(no wiggle)"), _("(slight deviation)"), "", "", _("(wild waves and curls)")}; - std::vector<double> values = { 0, 20, 40, 60, 100}; + std::vector<Glib::ustring> labels = {_("(no wiggle)"), _("(slight deviation)"), "", "", + _("(wild waves and curls)")}; + std::vector<double> values = {0, 20, 40, 60, 100}; auto wiggle_val = prefs->getDouble("/tools/calligraphic/wiggle", 0.0); _wiggle_adj = Gtk::Adjustment::create(wiggle_val, 0.0, 100, 1, 10.0); - auto wiggle_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-wiggle", _("Wiggle:"), _wiggle_adj, 1, 0)); + auto wiggle_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-wiggle", _("Wiggle:"), _wiggle_adj, 1, 0)); wiggle_item->set_tooltip_text(_("Increase to make the pen waver and wiggle")); wiggle_item->set_custom_numeric_menu_data(values, labels); wiggle_item->set_focus_widget(desktop->canvas); @@ -249,11 +272,14 @@ CalligraphyToolbar::CalligraphyToolbar(SPDesktop *desktop) { /* Mass */ - std::vector<Glib::ustring> labels = {_("(no inertia)"), _("(slight smoothing, default)"), _("(noticeable lagging)"), "", "", _("(maximum inertia)")}; - std::vector<double> values = { 0.0, 2, 10, 20, 50, 100}; + std::vector<Glib::ustring> labels = { + _("(no inertia)"), _("(slight smoothing, default)"), _("(noticeable lagging)"), "", "", + _("(maximum inertia)")}; + std::vector<double> values = {0.0, 2, 10, 20, 50, 100}; auto mass_val = prefs->getDouble("/tools/calligraphic/mass", 2.0); _mass_adj = Gtk::Adjustment::create(mass_val, 0.0, 100, 1, 10.0); - auto mass_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-mass", _("Mass:"), _mass_adj, 1, 0)); + auto mass_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("calligraphy-mass", _("Mass:"), _mass_adj, 1, 0)); mass_item->set_tooltip_text(_("Increase to make the pen drag behind, as if slowed by inertia")); mass_item->set_custom_numeric_menu_data(values, labels); mass_item->set_focus_widget(desktop->canvas); @@ -267,88 +293,76 @@ CalligraphyToolbar::CalligraphyToolbar(SPDesktop *desktop) show_all(); } -GtkWidget * -CalligraphyToolbar::create(SPDesktop *desktop) +GtkWidget *CalligraphyToolbar::create(SPDesktop *desktop) { auto toolbar = new CalligraphyToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -CalligraphyToolbar::width_value_changed() +void CalligraphyToolbar::width_value_changed() { auto prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/calligraphic/width", _width_adj->get_value() ); + prefs->setDouble("/tools/calligraphic/width", _width_adj->get_value()); update_presets_list(); } -void -CalligraphyToolbar::velthin_value_changed() +void CalligraphyToolbar::velthin_value_changed() { auto prefs = Inkscape::Preferences::get(); - prefs->setDouble("/tools/calligraphic/thinning", _thinning_adj->get_value() ); + prefs->setDouble("/tools/calligraphic/thinning", _thinning_adj->get_value()); update_presets_list(); } -void -CalligraphyToolbar::angle_value_changed() +void CalligraphyToolbar::angle_value_changed() { auto prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/calligraphic/angle", _angle_adj->get_value() ); + prefs->setDouble("/tools/calligraphic/angle", _angle_adj->get_value()); update_presets_list(); } -void -CalligraphyToolbar::flatness_value_changed() +void CalligraphyToolbar::flatness_value_changed() { auto prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/calligraphic/flatness", _fixation_adj->get_value() ); + prefs->setDouble("/tools/calligraphic/flatness", _fixation_adj->get_value()); update_presets_list(); } -void -CalligraphyToolbar::cap_rounding_value_changed() +void CalligraphyToolbar::cap_rounding_value_changed() { auto prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/calligraphic/cap_rounding", _cap_rounding_adj->get_value() ); + prefs->setDouble("/tools/calligraphic/cap_rounding", _cap_rounding_adj->get_value()); update_presets_list(); } -void -CalligraphyToolbar::tremor_value_changed() +void CalligraphyToolbar::tremor_value_changed() { auto prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/calligraphic/tremor", _tremor_adj->get_value() ); + prefs->setDouble("/tools/calligraphic/tremor", _tremor_adj->get_value()); update_presets_list(); } -void -CalligraphyToolbar::wiggle_value_changed() +void CalligraphyToolbar::wiggle_value_changed() { auto prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/calligraphic/wiggle", _wiggle_adj->get_value() ); + prefs->setDouble("/tools/calligraphic/wiggle", _wiggle_adj->get_value()); update_presets_list(); } -void -CalligraphyToolbar::mass_value_changed() +void CalligraphyToolbar::mass_value_changed() { auto prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/calligraphic/mass", _mass_adj->get_value() ); + prefs->setDouble("/tools/calligraphic/mass", _mass_adj->get_value()); update_presets_list(); } -void -CalligraphyToolbar::on_pref_toggled(Gtk::ToggleToolButton *item, - const Glib::ustring& path) +void CalligraphyToolbar::on_pref_toggled(Gtk::ToggleToolButton *item, const Glib::ustring &path) { auto prefs = Inkscape::Preferences::get(); prefs->setBool(path, item->get_active()); update_presets_list(); } -void -CalligraphyToolbar::update_presets_list() +void CalligraphyToolbar::update_presets_list() { if (_presets_blocked) { return; @@ -357,12 +371,12 @@ CalligraphyToolbar::update_presets_list() auto prefs = Inkscape::Preferences::get(); auto presets = get_presets_list(); - int index = 1; // 0 is for no preset. + int index = 1; // 0 is for no preset. for (auto i = presets.begin(); i != presets.end(); ++i, ++index) { bool match = true; auto preset = prefs->getAllEntries(*i); - for (auto & j : preset) { + for (auto &j : preset) { Glib::ustring entry_name = j.getEntryName(); if (entry_name == "id" || entry_name == "name") { continue; @@ -372,8 +386,9 @@ CalligraphyToolbar::update_presets_list() if (widget) { if (GTK_IS_ADJUSTMENT(widget)) { double v = j.getDouble(); - GtkAdjustment* adj = static_cast<GtkAdjustment *>(widget); - //std::cout << "compared adj " << attr_name << gtk_adjustment_get_value(adj) << " to " << v << "\n"; + GtkAdjustment *adj = static_cast<GtkAdjustment *>(widget); + // std::cout << "compared adj " << attr_name << gtk_adjustment_get_value(adj) << " to " << v << + // "\n"; if (fabs(gtk_adjustment_get_value(adj) - v) > 1e-6) { match = false; break; @@ -381,8 +396,9 @@ CalligraphyToolbar::update_presets_list() } else if (GTK_IS_TOGGLE_TOOL_BUTTON(widget)) { bool v = j.getBool(); auto toggle = GTK_TOGGLE_TOOL_BUTTON(widget); - //std::cout << "compared toggle " << attr_name << gtk_toggle_action_get_active(toggle) << " to " << v << "\n"; - if ( static_cast<bool>(gtk_toggle_tool_button_get_active(toggle)) != v ) { + // std::cout << "compared toggle " << attr_name << gtk_toggle_action_get_active(toggle) << " to " << + // v << "\n"; + if (static_cast<bool>(gtk_toggle_tool_button_get_active(toggle)) != v) { match = false; break; } @@ -403,15 +419,13 @@ CalligraphyToolbar::update_presets_list() _profile_selector_combo->set_active(0); } -void -CalligraphyToolbar::tilt_state_changed() +void CalligraphyToolbar::tilt_state_changed() { _angle_item->set_sensitive(!_usetilt->get_active()); on_pref_toggled(_usetilt, "/tools/calligraphic/usetilt"); } -void -CalligraphyToolbar::build_presets_list() +void CalligraphyToolbar::build_presets_list() { _presets_blocked = true; @@ -422,7 +436,7 @@ CalligraphyToolbar::build_presets_list() auto prefs = Inkscape::Preferences::get(); auto presets = get_presets_list(); - for (auto & preset : presets) { + for (auto &preset : presets) { Glib::ustring preset_name = prefs->getString(preset + "/name"); if (!preset_name.empty()) { @@ -435,8 +449,7 @@ CalligraphyToolbar::build_presets_list() update_presets_list(); } -void -CalligraphyToolbar::change_profile() +void CalligraphyToolbar::change_profile() { auto mode = _profile_selector_combo->get_active_row_number(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -454,12 +467,12 @@ CalligraphyToolbar::change_profile() } if (!preset_path.empty()) { - _presets_blocked = true; //temporarily block the selector so no one will updadte it while we're reading it + _presets_blocked = true; // temporarily block the selector so no one will updadte it while we're reading it std::vector<Inkscape::Preferences::Entry> preset = prefs->getAllEntries(preset_path); // Shouldn't this be std::map? - for (auto & i : preset) { + for (auto &i : preset) { Glib::ustring entry_name = i.getEntryName(); if (entry_name == "id" || entry_name == "name") { continue; @@ -467,13 +480,13 @@ CalligraphyToolbar::change_profile() void *widget = _widget_map[entry_name.data()]; if (widget) { if (GTK_IS_ADJUSTMENT(widget)) { - GtkAdjustment* adj = static_cast<GtkAdjustment *>(widget); + GtkAdjustment *adj = static_cast<GtkAdjustment *>(widget); gtk_adjustment_set_value(adj, i.getDouble()); - //std::cout << "set adj " << attr_name << " to " << v << "\n"; + // std::cout << "set adj " << attr_name << " to " << v << "\n"; } else if (GTK_IS_TOGGLE_TOOL_BUTTON(widget)) { auto toggle = GTK_TOGGLE_TOOL_BUTTON(widget); gtk_toggle_tool_button_set_active(toggle, i.getBool()); - //std::cout << "set toggle " << attr_name << " to " << v << "\n"; + // std::cout << "set toggle " << attr_name << " to " << v << "\n"; } else { g_warning("Unknown widget type for preset: %s\n", entry_name.data()); } @@ -485,18 +498,16 @@ CalligraphyToolbar::change_profile() } } -void -CalligraphyToolbar::edit_profile() +void CalligraphyToolbar::edit_profile() { save_profile(nullptr); } -void -CalligraphyToolbar::save_profile(GtkWidget * /*widget*/) +void CalligraphyToolbar::save_profile(GtkWidget * /*widget*/) { using Inkscape::UI::Dialog::CalligraphicProfileRename; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (! _desktop) { + if (!_desktop) { return; } @@ -511,7 +522,7 @@ CalligraphyToolbar::save_profile(GtkWidget * /*widget*/) } CalligraphicProfileRename::show(_desktop, current_profile_name); - if ( !CalligraphicProfileRename::applied()) { + if (!CalligraphicProfileRename::applied()) { // dialog cancelled update_presets_list(); return; @@ -520,7 +531,7 @@ CalligraphyToolbar::save_profile(GtkWidget * /*widget*/) if (new_profile_name.empty()) { // empty name entered - update_presets_list (); + update_presets_list(); return; } @@ -542,7 +553,7 @@ CalligraphyToolbar::save_profile(GtkWidget * /*widget*/) } } - if ( CalligraphicProfileRename::deleted() && new_index != -1) { + if (CalligraphicProfileRename::deleted() && new_index != -1) { prefs->remove(save_path); _presets_blocked = false; build_presets_list(); @@ -559,17 +570,17 @@ CalligraphyToolbar::save_profile(GtkWidget * /*widget*/) for (auto map_item : _widget_map) { auto widget_name = map_item.first; - auto widget = map_item.second; + auto widget = map_item.second; if (widget) { if (GTK_IS_ADJUSTMENT(widget)) { - GtkAdjustment* adj = GTK_ADJUSTMENT(widget); + GtkAdjustment *adj = GTK_ADJUSTMENT(widget); prefs->setDouble(save_path + "/" + widget_name, gtk_adjustment_get_value(adj)); - //std::cout << "wrote adj " << widget_name << ": " << v << "\n"; + // std::cout << "wrote adj " << widget_name << ": " << v << "\n"; } else if (GTK_IS_TOGGLE_TOOL_BUTTON(widget)) { auto toggle = GTK_TOGGLE_TOOL_BUTTON(widget); prefs->setBool(save_path + "/" + widget_name, gtk_toggle_tool_button_get_active(toggle)); - //std::cout << "wrote tog " << widget_name << ": " << v << "\n"; + // std::cout << "wrote tog " << widget_name << ": " << v << "\n"; } else { g_warning("Unknown widget type for preset: %s\n", widget_name.c_str()); } @@ -583,10 +594,9 @@ CalligraphyToolbar::save_profile(GtkWidget * /*widget*/) build_presets_list(); } -} -} -} - +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/calligraphy-toolbar.h b/src/ui/toolbar/calligraphy-toolbar.h index d2168888c3201fe4ba073713094f8bdd7490fed5..2c7906af6ab6e1fdc75b6fae7268389554918102 100644 --- a/src/ui/toolbar/calligraphy-toolbar.h +++ b/src/ui/toolbar/calligraphy-toolbar.h @@ -28,9 +28,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; namespace Gtk { @@ -47,7 +48,8 @@ class SpinButtonToolItem; namespace Toolbar { -class CalligraphyToolbar : public Toolbar { +class CalligraphyToolbar : public Toolbar +{ private: bool _presets_blocked; @@ -86,18 +88,17 @@ private: void edit_profile(); void update_presets_list(); void tilt_state_changed(); - void on_pref_toggled(Gtk::ToggleToolButton *item, - const Glib::ustring& path); - + void on_pref_toggled(Gtk::ToggleToolButton *item, const Glib::ustring &path); + protected: CalligraphyToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_CALLIGRAPHY_TOOLBAR_H */ diff --git a/src/ui/toolbar/connector-toolbar.cpp b/src/ui/toolbar/connector-toolbar.cpp index 5a964f2867c5a79a70c0164ee7e8de061a36536c..bb59982a06d9c7ce4a53bc187ea672b0bd35fd7e 100644 --- a/src/ui/toolbar/connector-toolbar.cpp +++ b/src/ui/toolbar/connector-toolbar.cpp @@ -28,47 +28,41 @@ #include "connector-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/separatortoolitem.h> #include "conn-avoid-ref.h" - #include "desktop.h" #include "document-undo.h" #include "enums.h" #include "graphlayout.h" -#include "selection.h" -#include "verbs.h" - #include "object/sp-namedview.h" #include "object/sp-path.h" - +#include "selection.h" #include "ui/icon-names.h" #include "ui/tools/connector-tool.h" #include "ui/uxmanager.h" #include "ui/widget/canvas.h" #include "ui/widget/spin-button-tool-item.h" - +#include "verbs.h" #include "xml/node-event-vector.h" -using Inkscape::UI::UXManager; using Inkscape::DocumentUndo; +using Inkscape::UI::UXManager; static Inkscape::XML::NodeEventVector connector_tb_repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - Inkscape::UI::Toolbar::ConnectorToolbar::event_attr_changed, - nullptr, /* content_changed */ - nullptr /* order_changed */ + nullptr, /* child_added */ + nullptr, /* child_removed */ + Inkscape::UI::Toolbar::ConnectorToolbar::event_attr_changed, nullptr, /* content_changed */ + nullptr /* order_changed */ }; namespace Inkscape { namespace UI { namespace Toolbar { ConnectorToolbar::ConnectorToolbar(SPDesktop *desktop) - : Toolbar(desktop), - _freeze(false), - _repr(nullptr) + : Toolbar(desktop) + , _freeze(false) + , _repr(nullptr) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -90,21 +84,21 @@ ConnectorToolbar::ConnectorToolbar(SPDesktop *desktop) // Orthogonal connectors toggle button { - _orthogonal = add_toggle_button(_("Orthogonal"), - _("Make connector orthogonal or polyline")); + _orthogonal = add_toggle_button(_("Orthogonal"), _("Make connector orthogonal or polyline")); _orthogonal->set_icon_name(INKSCAPE_ICON("connector-orthogonal")); bool tbuttonstate = prefs->getBool("/tools/connector/orthogonal"); - _orthogonal->set_active(( tbuttonstate ? TRUE : FALSE )); + _orthogonal->set_active((tbuttonstate ? TRUE : FALSE)); _orthogonal->signal_toggled().connect(sigc::mem_fun(*this, &ConnectorToolbar::orthogonal_toggled)); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); // Curvature spinbox auto curvature_val = prefs->getDouble("/tools/connector/curvature", defaultConnCurvature); _curvature_adj = Gtk::Adjustment::create(curvature_val, 0, 100, 1.0, 10.0); - auto curvature_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("inkscape:connector-curvature", _("Curvature:"), _curvature_adj, 1, 0)); + auto curvature_item = Gtk::manage( + new UI::Widget::SpinButtonToolItem("inkscape:connector-curvature", _("Curvature:"), _curvature_adj, 1, 0)); curvature_item->set_tooltip_text(_("The amount of connectors curvature")); curvature_item->set_focus_widget(desktop->canvas); _curvature_adj->signal_value_changed().connect(sigc::mem_fun(*this, &ConnectorToolbar::curvature_changed)); @@ -113,7 +107,8 @@ ConnectorToolbar::ConnectorToolbar(SPDesktop *desktop) // Spacing spinbox auto spacing_val = prefs->getDouble("/tools/connector/spacing", defaultConnSpacing); _spacing_adj = Gtk::Adjustment::create(spacing_val, 0, 100, 1.0, 10.0); - auto spacing_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("inkscape:connector-spacing", _("Spacing:"), _spacing_adj, 1, 0)); + auto spacing_item = Gtk::manage( + new UI::Widget::SpinButtonToolItem("inkscape:connector-spacing", _("Spacing:"), _spacing_adj, 1, 0)); spacing_item->set_tooltip_text(_("The amount of space left around objects by auto-routing connectors")); spacing_item->set_focus_widget(desktop->canvas); _spacing_adj->signal_value_changed().connect(sigc::mem_fun(*this, &ConnectorToolbar::spacing_changed)); @@ -131,7 +126,8 @@ ConnectorToolbar::ConnectorToolbar(SPDesktop *desktop) // Default connector length spinbox auto length_val = prefs->getDouble("/tools/connector/length", 100); _length_adj = Gtk::Adjustment::create(length_val, 10, 1000, 10.0, 100.0); - auto length_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("inkscape:connector-length", _("Length:"), _length_adj, 1, 0)); + auto length_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("inkscape:connector-length", _("Length:"), _length_adj, 1, 0)); length_item->set_tooltip_text(_("Ideal length for connectors when layout is applied")); length_item->set_focus_widget(desktop->canvas); _length_adj->signal_value_changed().connect(sigc::mem_fun(*this, &ConnectorToolbar::length_changed)); @@ -139,27 +135,28 @@ ConnectorToolbar::ConnectorToolbar(SPDesktop *desktop) // Directed edges toggle button { - _directed_item = add_toggle_button(_("Downwards"), - _("Make connectors with end-markers (arrows) point downwards")); + _directed_item = + add_toggle_button(_("Downwards"), _("Make connectors with end-markers (arrows) point downwards")); _directed_item->set_icon_name(INKSCAPE_ICON("distribute-graph-directed")); bool tbuttonstate = prefs->getBool("/tools/connector/directedlayout"); _directed_item->set_active(tbuttonstate ? TRUE : FALSE); - _directed_item->signal_toggled().connect(sigc::mem_fun(*this, &ConnectorToolbar::directed_graph_layout_toggled)); + _directed_item->signal_toggled().connect( + sigc::mem_fun(*this, &ConnectorToolbar::directed_graph_layout_toggled)); desktop->getSelection()->connectChanged(sigc::mem_fun(*this, &ConnectorToolbar::selection_changed)); } // Avoid overlaps toggle button { - _overlap_item = add_toggle_button(_("Remove overlaps"), - _("Do not allow overlapping shapes")); + _overlap_item = add_toggle_button(_("Remove overlaps"), _("Do not allow overlapping shapes")); _overlap_item->set_icon_name(INKSCAPE_ICON("distribute-remove-overlaps")); bool tbuttonstate = prefs->getBool("/tools/connector/avoidoverlaplayout"); _overlap_item->set_active(tbuttonstate ? TRUE : FALSE); - _overlap_item->signal_toggled().connect(sigc::mem_fun(*this, &ConnectorToolbar::nooverlaps_graph_layout_toggled)); + _overlap_item->signal_toggled().connect( + sigc::mem_fun(*this, &ConnectorToolbar::nooverlaps_graph_layout_toggled)); } // Code to watch for changes to the connector-spacing attribute in @@ -167,7 +164,7 @@ ConnectorToolbar::ConnectorToolbar(SPDesktop *desktop) Inkscape::XML::Node *repr = desktop->namedview->getRepr(); g_assert(repr != nullptr); - if(_repr) { + if (_repr) { _repr->removeListenerByData(this); Inkscape::GC::release(_repr); _repr = nullptr; @@ -183,27 +180,23 @@ ConnectorToolbar::ConnectorToolbar(SPDesktop *desktop) show_all(); } -GtkWidget * -ConnectorToolbar::create( SPDesktop *desktop) +GtkWidget *ConnectorToolbar::create(SPDesktop *desktop) { auto toolbar = new ConnectorToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } // end of ConnectorToolbar::prep() -void -ConnectorToolbar::path_set_avoid() +void ConnectorToolbar::path_set_avoid() { Inkscape::UI::Tools::cc_selection_set_avoid(_desktop, true); } -void -ConnectorToolbar::path_set_ignore() +void ConnectorToolbar::path_set_ignore() { Inkscape::UI::Tools::cc_selection_set_avoid(_desktop, false); } -void -ConnectorToolbar::orthogonal_toggled() +void ConnectorToolbar::orthogonal_toggled() { auto doc = _desktop->getDocument(); @@ -222,16 +215,15 @@ ConnectorToolbar::orthogonal_toggled() bool is_orthog = _orthogonal->get_active(); gchar orthog_str[] = "orthogonal"; gchar polyline_str[] = "polyline"; - gchar *value = is_orthog ? orthog_str : polyline_str ; + gchar *value = is_orthog ? orthog_str : polyline_str; bool modmade = false; - auto itemlist= _desktop->getSelection()->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = _desktop->getSelection()->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (Inkscape::UI::Tools::cc_item_is_connector(item)) { - item->setAttribute( "inkscape:connector-type", - value, nullptr); + item->setAttribute("inkscape:connector-type", value, nullptr); item->getAvoidRef().handleSettingChange(); modmade = true; } @@ -241,16 +233,14 @@ ConnectorToolbar::orthogonal_toggled() Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setBool("/tools/connector/orthogonal", is_orthog); } else { - DocumentUndo::done(doc, SP_VERB_CONTEXT_CONNECTOR, - is_orthog ? _("Set connector type: orthogonal"): _("Set connector type: polyline")); + is_orthog ? _("Set connector type: orthogonal") : _("Set connector type: polyline")); } _freeze = false; } -void -ConnectorToolbar::curvature_changed() +void ConnectorToolbar::curvature_changed() { SPDocument *doc = _desktop->getDocument(); @@ -258,7 +248,6 @@ ConnectorToolbar::curvature_changed() return; } - // quit if run by the _changed callbacks if (_freeze) { return; @@ -272,13 +261,12 @@ ConnectorToolbar::curvature_changed() g_ascii_dtostr(value, G_ASCII_DTOSTR_BUF_SIZE, newValue); bool modmade = false; - auto itemlist= _desktop->getSelection()->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = _desktop->getSelection()->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (Inkscape::UI::Tools::cc_item_is_connector(item)) { - item->setAttribute( "inkscape:connector-curvature", - value, nullptr); + item->setAttribute("inkscape:connector-curvature", value, nullptr); item->getAvoidRef().handleSettingChange(); modmade = true; } @@ -287,17 +275,14 @@ ConnectorToolbar::curvature_changed() if (!modmade) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble(Glib::ustring("/tools/connector/curvature"), newValue); - } - else { - DocumentUndo::done(doc, SP_VERB_CONTEXT_CONNECTOR, - _("Change connector curvature")); + } else { + DocumentUndo::done(doc, SP_VERB_CONTEXT_CONNECTOR, _("Change connector curvature")); } _freeze = false; } -void -ConnectorToolbar::spacing_changed() +void ConnectorToolbar::spacing_changed() { SPDocument *doc = _desktop->getDocument(); @@ -307,8 +292,7 @@ ConnectorToolbar::spacing_changed() Inkscape::XML::Node *repr = _desktop->namedview->getRepr(); - if ( !repr->attribute("inkscape:connector-spacing") && - ( _spacing_adj->get_value() == defaultConnSpacing )) { + if (!repr->attribute("inkscape:connector-spacing") && (_spacing_adj->get_value() == defaultConnSpacing)) { // Don't need to update the repr if the attribute doesn't // exist and it is being set to the default value -- as will // happen at startup. @@ -335,15 +319,13 @@ ConnectorToolbar::spacing_changed() modmade = true; } - if(modmade) { - DocumentUndo::done(doc, SP_VERB_CONTEXT_CONNECTOR, - _("Change connector spacing")); + if (modmade) { + DocumentUndo::done(doc, SP_VERB_CONTEXT_CONNECTOR, _("Change connector spacing")); } _freeze = false; } -void -ConnectorToolbar::graph_layout() +void ConnectorToolbar::graph_layout() { assert(_desktop); if (!_desktop) { @@ -364,54 +346,41 @@ ConnectorToolbar::graph_layout() DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_ALIGN_DISTRIBUTE, _("Arrange connector network")); } -void -ConnectorToolbar::length_changed() +void ConnectorToolbar::length_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble("/tools/connector/length", _length_adj->get_value()); } -void -ConnectorToolbar::directed_graph_layout_toggled() +void ConnectorToolbar::directed_graph_layout_toggled() { auto prefs = Inkscape::Preferences::get(); prefs->setBool("/tools/connector/directedlayout", _directed_item->get_active()); } -void -ConnectorToolbar::selection_changed(Inkscape::Selection *selection) +void ConnectorToolbar::selection_changed(Inkscape::Selection *selection) { SPItem *item = selection->singleItem(); - if (SP_IS_PATH(item)) - { + if (SP_IS_PATH(item)) { gdouble curvature = SP_PATH(item)->connEndPair.getCurvature(); bool is_orthog = SP_PATH(item)->connEndPair.isOrthogonal(); _orthogonal->set_active(is_orthog); _curvature_adj->set_value(curvature); } - } -void -ConnectorToolbar::nooverlaps_graph_layout_toggled() +void ConnectorToolbar::nooverlaps_graph_layout_toggled() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setBool("/tools/connector/avoidoverlaplayout", - _overlap_item->get_active()); + prefs->setBool("/tools/connector/avoidoverlaplayout", _overlap_item->get_active()); } -void -ConnectorToolbar::event_attr_changed(Inkscape::XML::Node *repr, - gchar const *name, - gchar const * /*old_value*/, - gchar const * /*new_value*/, - bool /*is_interactive*/, - gpointer data) +void ConnectorToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, gchar const * /*old_value*/, + gchar const * /*new_value*/, bool /*is_interactive*/, gpointer data) { auto toolbar = reinterpret_cast<ConnectorToolbar *>(data); - if ( !toolbar->_freeze - && (strcmp(name, "inkscape:connector-spacing") == 0) ) { + if (!toolbar->_freeze && (strcmp(name, "inkscape:connector-spacing") == 0)) { gdouble spacing = defaultConnSpacing; sp_repr_get_double(repr, "inkscape:connector-spacing", &spacing); @@ -423,9 +392,9 @@ ConnectorToolbar::event_attr_changed(Inkscape::XML::Node *repr, } } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/connector-toolbar.h b/src/ui/toolbar/connector-toolbar.h index 66df79ee93222c45836f3e7a8a15dee7d5495cf5..82da270ad000de99165d2a2dad58c3bd5b192cb3 100644 --- a/src/ui/toolbar/connector-toolbar.h +++ b/src/ui/toolbar/connector-toolbar.h @@ -28,10 +28,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; namespace Gtk { @@ -47,7 +47,8 @@ class Node; namespace UI { namespace Toolbar { -class ConnectorToolbar : public Toolbar { +class ConnectorToolbar : public Toolbar +{ private: Gtk::ToggleToolButton *_orthogonal; Gtk::ToggleToolButton *_directed_item; @@ -76,18 +77,14 @@ protected: ConnectorToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); - - static void event_attr_changed(Inkscape::XML::Node *repr, - gchar const *name, - gchar const * /*old_value*/, - gchar const * /*new_value*/, - bool /*is_interactive*/, - gpointer data); + static GtkWidget *create(SPDesktop *desktop); + + static void event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, gchar const * /*old_value*/, + gchar const * /*new_value*/, bool /*is_interactive*/, gpointer data); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_CONNECTOR_TOOLBAR_H */ diff --git a/src/ui/toolbar/dropper-toolbar.cpp b/src/ui/toolbar/dropper-toolbar.cpp index 83a18c37a28e3ce8e62b541b9bb361e9d9d11266..d53237dceae3a63d2a11d94f59ef47872671560b 100644 --- a/src/ui/toolbar/dropper-toolbar.cpp +++ b/src/ui/toolbar/dropper-toolbar.cpp @@ -25,13 +25,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "dropper-toolbar.h" + #include <glibmm/i18n.h> -#include "dropper-toolbar.h" +#include "desktop.h" #include "document-undo.h" #include "preferences.h" -#include "desktop.h" - #include "ui/widget/canvas.h" // Grab focus namespace Inkscape { @@ -43,7 +43,7 @@ void DropperToolbar::on_pick_alpha_button_toggled() auto active = _pick_alpha_button->get_active(); auto prefs = Inkscape::Preferences::get(); - prefs->setInt( "/tools/dropper/pick", active ); + prefs->setInt("/tools/dropper/pick", active); _set_alpha_button->set_sensitive(active); _desktop->canvas->grab_focus(); @@ -52,7 +52,7 @@ void DropperToolbar::on_pick_alpha_button_toggled() void DropperToolbar::on_set_alpha_button_toggled() { auto prefs = Inkscape::Preferences::get(); - prefs->setBool( "/tools/dropper/setalpha", _set_alpha_button->get_active( ) ); + prefs->setBool("/tools/dropper/setalpha", _set_alpha_button->get_active()); _desktop->canvas->grab_focus(); } @@ -66,18 +66,17 @@ DropperToolbar::DropperToolbar(SPDesktop *desktop) { // Add widgets to toolbar add_label(_("Opacity:")); - _pick_alpha_button = add_toggle_button(_("Pick"), - _("Pick both the color and the alpha (transparency) under cursor; " - "otherwise, pick only the visible color premultiplied by alpha")); - _set_alpha_button = add_toggle_button(_("Assign"), - _("If alpha was picked, assign it to selection " - "as fill or stroke transparency")); + _pick_alpha_button = + add_toggle_button(_("Pick"), _("Pick both the color and the alpha (transparency) under cursor; " + "otherwise, pick only the visible color premultiplied by alpha")); + _set_alpha_button = add_toggle_button(_("Assign"), _("If alpha was picked, assign it to selection " + "as fill or stroke transparency")); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); // Set initial state of widgets - auto pickAlpha = prefs->getInt( "/tools/dropper/pick", 1 ); - auto setAlpha = prefs->getBool( "/tools/dropper/setalpha", true); + auto pickAlpha = prefs->getInt("/tools/dropper/pick", 1); + auto setAlpha = prefs->getBool("/tools/dropper/setalpha", true); _pick_alpha_button->set_active(pickAlpha); _set_alpha_button->set_active(setAlpha); @@ -87,7 +86,7 @@ DropperToolbar::DropperToolbar(SPDesktop *desktop) // Connect signal handlers auto pick_alpha_button_toggled_cb = sigc::mem_fun(*this, &DropperToolbar::on_pick_alpha_button_toggled); - auto set_alpha_button_toggled_cb = sigc::mem_fun(*this, &DropperToolbar::on_set_alpha_button_toggled); + auto set_alpha_button_toggled_cb = sigc::mem_fun(*this, &DropperToolbar::on_set_alpha_button_toggled); _pick_alpha_button->signal_toggled().connect(pick_alpha_button_toggled_cb); _set_alpha_button->signal_toggled().connect(set_alpha_button_toggled_cb); @@ -95,15 +94,14 @@ DropperToolbar::DropperToolbar(SPDesktop *desktop) show_all(); } -GtkWidget * -DropperToolbar::create(SPDesktop *desktop) +GtkWidget *DropperToolbar::create(SPDesktop *desktop) { auto toolbar = Gtk::manage(new DropperToolbar(desktop)); return GTK_WIDGET(toolbar->gobj()); } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/dropper-toolbar.h b/src/ui/toolbar/dropper-toolbar.h index c8aa42f309847a6c68a0631574d9134681dc7f0c..20572017c2a24d426832858207b63c1aa6d3ca8f 100644 --- a/src/ui/toolbar/dropper-toolbar.h +++ b/src/ui/toolbar/dropper-toolbar.h @@ -37,7 +37,8 @@ namespace Toolbar { /** * \brief A toolbar for controlling the dropper tool */ -class DropperToolbar : public Toolbar { +class DropperToolbar : public Toolbar +{ private: // Tool widgets Gtk::ToggleToolButton *_pick_alpha_button; ///< Control whether to pick opacity @@ -51,11 +52,11 @@ protected: DropperToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_DROPPER_TOOLBAR_H */ /* diff --git a/src/ui/toolbar/eraser-toolbar.cpp b/src/ui/toolbar/eraser-toolbar.cpp index 270256e60c28e1015b7e083b496e41fa31c1943b..8a376837729a1ae62099f4c23dd419134f06b2b3 100644 --- a/src/ui/toolbar/eraser-toolbar.cpp +++ b/src/ui/toolbar/eraser-toolbar.cpp @@ -28,9 +28,7 @@ #include "eraser-toolbar.h" #include <array> - #include <glibmm/i18n.h> - #include <gtkmm/radiotoolbutton.h> #include <gtkmm/separatortoolitem.h> @@ -39,8 +37,7 @@ #include "ui/icon-names.h" #include "ui/simple-pref-pusher.h" #include "ui/tools/eraser-tool.h" - -#include "ui/widget/canvas.h" // Focus widget +#include "ui/widget/canvas.h" // Focus widget #include "ui/widget/spin-button-tool-item.h" using Inkscape::DocumentUndo; @@ -49,8 +46,8 @@ namespace Inkscape { namespace UI { namespace Toolbar { EraserToolbar::EraserToolbar(SPDesktop *desktop) - : Toolbar(desktop), - _freeze(false) + : Toolbar(desktop) + , _freeze(false) { gint eraser_mode = ERASER_MODE_DELETE; auto prefs = Inkscape::Preferences::get(); @@ -84,8 +81,7 @@ EraserToolbar::EraserToolbar(SPDesktop *desktop) int btn_index = 0; - for (auto btn : mode_buttons) - { + for (auto btn : mode_buttons) { add(*btn); btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &EraserToolbar::mode_changed), btn_index++)); } @@ -96,8 +92,9 @@ EraserToolbar::EraserToolbar(SPDesktop *desktop) /* Width */ { - std::vector<Glib::ustring> labels = {_("(no width)"), _("(hairline)"), "", "", "", _("(default)"), "", "", "", "", _("(broad stroke)")}; - std::vector<double> values = { 0, 1, 3, 5, 10, 15, 20, 30, 50, 75, 100}; + std::vector<Glib::ustring> labels = { + _("(no width)"), _("(hairline)"), "", "", "", _("(default)"), "", "", "", "", _("(broad stroke)")}; + std::vector<double> values = {0, 1, 3, 5, 10, 15, 20, 30, 50, 75, 100}; auto width_val = prefs->getDouble("/tools/eraser/width", 15); _width_adj = Gtk::Adjustment::create(width_val, 0, 100, 1.0, 10.0); _width = Gtk::manage(new UI::Widget::SpinButtonToolItem("eraser-width", _("Width:"), _width_adj, 1, 0)); @@ -125,12 +122,16 @@ EraserToolbar::EraserToolbar(SPDesktop *desktop) /* Thinning */ { - std::vector<Glib::ustring> labels = {_("(speed blows up stroke)"), "", "", _("(slight widening)"), _("(constant width)"), _("(slight thinning, default)"), "", "", _("(speed deflates stroke)")}; - std::vector<double> values = { -100, -40, -20, -10, 0, 10, 20, 40, 100}; + std::vector<Glib::ustring> labels = { + _("(speed blows up stroke)"), "", "", _("(slight widening)"), _("(constant width)"), + _("(slight thinning, default)"), "", "", _("(speed deflates stroke)")}; + std::vector<double> values = {-100, -40, -20, -10, 0, 10, 20, 40, 100}; auto thinning_val = prefs->getDouble("/tools/eraser/thinning", 10); _thinning_adj = Gtk::Adjustment::create(thinning_val, -100, 100, 1, 10.0); - _thinning = Gtk::manage(new UI::Widget::SpinButtonToolItem("eraser-thinning", _("Thinning:"), _thinning_adj, 1, 0)); - _thinning->set_tooltip_text(_("How much velocity thins the stroke (> 0 makes fast strokes thinner, < 0 makes them broader, 0 makes width independent of velocity)")); + _thinning = + Gtk::manage(new UI::Widget::SpinButtonToolItem("eraser-thinning", _("Thinning:"), _thinning_adj, 1, 0)); + _thinning->set_tooltip_text(_("How much velocity thins the stroke (> 0 makes fast strokes thinner, < 0 makes " + "them broader, 0 makes width independent of velocity)")); _thinning->set_custom_numeric_menu_data(values, labels); _thinning->set_focus_widget(desktop->canvas); _thinning_adj->signal_value_changed().connect(sigc::mem_fun(*this, &EraserToolbar::velthin_value_changed)); @@ -143,16 +144,20 @@ EraserToolbar::EraserToolbar(SPDesktop *desktop) /* Cap Rounding */ { - std::vector<Glib::ustring> labels = {_("(blunt caps, default)"), _("(slightly bulging)"), "", "", _("(approximately round)"), _("(long protruding caps)")}; - std::vector<double> values = { 0, 0.3, 0.5, 1.0, 1.4, 5.0}; + std::vector<Glib::ustring> labels = {_("(blunt caps, default)"), _("(slightly bulging)"), "", "", + _("(approximately round)"), _("(long protruding caps)")}; + std::vector<double> values = {0, 0.3, 0.5, 1.0, 1.4, 5.0}; auto cap_rounding_val = prefs->getDouble("/tools/eraser/cap_rounding", 0.0); _cap_rounding_adj = Gtk::Adjustment::create(cap_rounding_val, 0.0, 5.0, 0.01, 0.1); // TRANSLATORS: "cap" means "end" (both start and finish) here - _cap_rounding = Gtk::manage(new UI::Widget::SpinButtonToolItem("eraser-cap-rounding", _("Caps:"), _cap_rounding_adj, 0.01, 2)); - _cap_rounding->set_tooltip_text(_("Increase to make caps at the ends of strokes protrude more (0 = no caps, 1 = round caps)")); + _cap_rounding = Gtk::manage( + new UI::Widget::SpinButtonToolItem("eraser-cap-rounding", _("Caps:"), _cap_rounding_adj, 0.01, 2)); + _cap_rounding->set_tooltip_text( + _("Increase to make caps at the ends of strokes protrude more (0 = no caps, 1 = round caps)")); _cap_rounding->set_custom_numeric_menu_data(values, labels); _cap_rounding->set_focus_widget(desktop->canvas); - _cap_rounding_adj->signal_value_changed().connect(sigc::mem_fun(*this, &EraserToolbar::cap_rounding_value_changed)); + _cap_rounding_adj->signal_value_changed().connect( + sigc::mem_fun(*this, &EraserToolbar::cap_rounding_value_changed)); add(*_cap_rounding); _cap_rounding->set_sensitive(true); } @@ -162,8 +167,9 @@ EraserToolbar::EraserToolbar(SPDesktop *desktop) /* Tremor */ { - std::vector<Glib::ustring> labels = {_("(smooth line)"), _("(slight tremor)"), _("(noticeable tremor)"), "", "", _("(maximum tremor)")}; - std::vector<double> values = { 0, 10, 20, 40, 60, 100}; + std::vector<Glib::ustring> labels = { + _("(smooth line)"), _("(slight tremor)"), _("(noticeable tremor)"), "", "", _("(maximum tremor)")}; + std::vector<double> values = {0, 10, 20, 40, 60, 100}; auto tremor_val = prefs->getDouble("/tools/eraser/tremor", 0.0); _tremor_adj = Gtk::Adjustment::create(tremor_val, 0.0, 100, 1, 10.0); _tremor = Gtk::manage(new UI::Widget::SpinButtonToolItem("eraser-tremor", _("Tremor:"), _tremor_adj, 1, 0)); @@ -173,7 +179,7 @@ EraserToolbar::EraserToolbar(SPDesktop *desktop) _tremor_adj->signal_value_changed().connect(sigc::mem_fun(*this, &EraserToolbar::tremor_value_changed)); // TODO: Allow slider appearance - //ege_adjustment_action_set_appearance( toolbar->_tremor, TOOLBAR_SLIDER_HINT ); + // ege_adjustment_action_set_appearance( toolbar->_tremor, TOOLBAR_SLIDER_HINT ); add(*_tremor); _tremor->set_sensitive(true); } @@ -183,8 +189,10 @@ EraserToolbar::EraserToolbar(SPDesktop *desktop) /* Mass */ { - std::vector<Glib::ustring> labels = {_("(no inertia)"), _("(slight smoothing, default)"), _("(noticeable lagging)"), "", "", _("(maximum inertia)")}; - std::vector<double> values = { 0.0, 2, 10, 20, 50, 100}; + std::vector<Glib::ustring> labels = { + _("(no inertia)"), _("(slight smoothing, default)"), _("(noticeable lagging)"), "", "", + _("(maximum inertia)")}; + std::vector<double> values = {0.0, 2, 10, 20, 50, 100}; auto mass_val = prefs->getDouble("/tools/eraser/mass", 10.0); _mass_adj = Gtk::Adjustment::create(mass_val, 0.0, 100, 1, 10.0); _mass = Gtk::manage(new UI::Widget::SpinButtonToolItem("eraser-mass", _("Mass:"), _mass_adj, 1, 0)); @@ -193,7 +201,7 @@ EraserToolbar::EraserToolbar(SPDesktop *desktop) _mass->set_focus_widget(desktop->canvas); _mass_adj->signal_value_changed().connect(sigc::mem_fun(*this, &EraserToolbar::mass_value_changed)); // TODO: Allow slider appearance - //ege_adjustment_action_set_appearance( toolbar->_mass, TOOLBAR_SLIDER_HINT ); + // ege_adjustment_action_set_appearance( toolbar->_mass, TOOLBAR_SLIDER_HINT ); add(*_mass); _mass->set_sensitive(true); } @@ -203,10 +211,9 @@ EraserToolbar::EraserToolbar(SPDesktop *desktop) /* Overlap */ { - _split = add_toggle_button(_("Break apart cut items"), - _("Break apart cut items")); + _split = add_toggle_button(_("Break apart cut items"), _("Break apart cut items")); _split->set_icon_name(INKSCAPE_ICON("distribute-randomize")); - _split->set_active( prefs->getBool("/tools/eraser/break_apart", false) ); + _split->set_active(prefs->getBool("/tools/eraser/break_apart", false)); _split->signal_toggled().connect(sigc::mem_fun(*this, &EraserToolbar::toggle_break_apart)); } @@ -215,19 +222,17 @@ EraserToolbar::EraserToolbar(SPDesktop *desktop) set_eraser_mode_visibility(eraser_mode); } -GtkWidget * -EraserToolbar::create(SPDesktop *desktop) +GtkWidget *EraserToolbar::create(SPDesktop *desktop) { auto toolbar = new EraserToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -EraserToolbar::mode_changed(int mode) +void EraserToolbar::mode_changed(int mode) { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setInt( "/tools/eraser/mode", mode ); + prefs->setInt("/tools/eraser/mode", mode); } set_eraser_mode_visibility(mode); @@ -244,23 +249,17 @@ EraserToolbar::mode_changed(int mode) */ // TODO finish implementation - _freeze = false; + _freeze = false; } } -void -EraserToolbar::set_eraser_mode_visibility(const guint eraser_mode) +void EraserToolbar::set_eraser_mode_visibility(const guint eraser_mode) { _split->set_visible((eraser_mode == ERASER_MODE_CUT)); const gboolean visibility = (eraser_mode != ERASER_MODE_DELETE); - const std::array<Gtk::Widget *, 6> arr = {_cap_rounding, - _mass, - _thinning, - _tremor, - _usepressure, - _width}; + const std::array<Gtk::Widget *, 6> arr = {_cap_rounding, _mass, _thinning, _tremor, _usepressure, _width}; for (auto widget : arr) { widget->set_visible(visibility); } @@ -270,59 +269,52 @@ EraserToolbar::set_eraser_mode_visibility(const guint eraser_mode) } } -void -EraserToolbar::width_value_changed() +void EraserToolbar::width_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/eraser/width", _width_adj->get_value() ); + prefs->setDouble("/tools/eraser/width", _width_adj->get_value()); } -void -EraserToolbar::mass_value_changed() +void EraserToolbar::mass_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/eraser/mass", _mass_adj->get_value() ); + prefs->setDouble("/tools/eraser/mass", _mass_adj->get_value()); } -void -EraserToolbar::velthin_value_changed() +void EraserToolbar::velthin_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble("/tools/eraser/thinning", _thinning_adj->get_value() ); + prefs->setDouble("/tools/eraser/thinning", _thinning_adj->get_value()); } -void -EraserToolbar::cap_rounding_value_changed() +void EraserToolbar::cap_rounding_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/eraser/cap_rounding", _cap_rounding_adj->get_value() ); + prefs->setDouble("/tools/eraser/cap_rounding", _cap_rounding_adj->get_value()); } -void -EraserToolbar::tremor_value_changed() +void EraserToolbar::tremor_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/eraser/tremor", _tremor_adj->get_value() ); + prefs->setDouble("/tools/eraser/tremor", _tremor_adj->get_value()); } -void -EraserToolbar::toggle_break_apart() +void EraserToolbar::toggle_break_apart() { auto prefs = Inkscape::Preferences::get(); bool active = _split->get_active(); prefs->setBool("/tools/eraser/break_apart", active); } -void -EraserToolbar::usepressure_toggled() +void EraserToolbar::usepressure_toggled() { auto prefs = Inkscape::Preferences::get(); prefs->setBool("/tools/eraser/usepressure", _usepressure->get_active()); } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/eraser-toolbar.h b/src/ui/toolbar/eraser-toolbar.h index 4ab94b77304a77fcb028f86ac6d301aa95e83ee8..ee58c89fcbcbd4cb65894ba868998f963a6fbbe3 100644 --- a/src/ui/toolbar/eraser-toolbar.h +++ b/src/ui/toolbar/eraser-toolbar.h @@ -28,10 +28,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; namespace Gtk { @@ -47,7 +47,8 @@ class SpinButtonToolItem; } namespace Toolbar { -class EraserToolbar : public Toolbar { +class EraserToolbar : public Toolbar +{ private: UI::Widget::SpinButtonToolItem *_width; UI::Widget::SpinButtonToolItem *_mass; @@ -85,11 +86,11 @@ protected: EraserToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_ERASOR_TOOLBAR_H */ diff --git a/src/ui/toolbar/gradient-toolbar.cpp b/src/ui/toolbar/gradient-toolbar.cpp index 677ae06876090601b4185a8efc479b601adaea45..d7c85d2d77c54ad0064cb295d2770c3382affef0 100644 --- a/src/ui/toolbar/gradient-toolbar.cpp +++ b/src/ui/toolbar/gradient-toolbar.cpp @@ -13,8 +13,9 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/i18n.h> +#include "gradient-toolbar.h" +#include <glibmm/i18n.h> #include <gtkmm/comboboxtext.h> #include <gtkmm/radiotoolbutton.h> #include <gtkmm/separatortoolitem.h> @@ -24,16 +25,12 @@ #include "document.h" #include "gradient-chemistry.h" #include "gradient-drag.h" -#include "gradient-toolbar.h" -#include "selection.h" -#include "verbs.h" - #include "object/sp-defs.h" #include "object/sp-linear-gradient.h" #include "object/sp-radial-gradient.h" #include "object/sp-stop.h" +#include "selection.h" #include "style.h" - #include "ui/icon-names.h" #include "ui/tools/gradient-tool.h" #include "ui/util.h" @@ -41,31 +38,31 @@ #include "ui/widget/color-preview.h" #include "ui/widget/combo-tool-item.h" #include "ui/widget/gradient-image.h" -#include "ui/widget/spin-button-tool-item.h" #include "ui/widget/gradient-vector-selector.h" +#include "ui/widget/spin-button-tool-item.h" +#include "verbs.h" using Inkscape::DocumentUndo; using Inkscape::UI::Tools::ToolBase; static bool blocked = false; -void gr_apply_gradient_to_item( SPItem *item, SPGradient *gr, SPGradientType initialType, Inkscape::PaintTarget initialMode, Inkscape::PaintTarget mode ) +void gr_apply_gradient_to_item(SPItem *item, SPGradient *gr, SPGradientType initialType, + Inkscape::PaintTarget initialMode, Inkscape::PaintTarget mode) { SPStyle *style = item->style; bool isFill = (mode == Inkscape::FOR_FILL); - if (style - && (isFill ? style->fill.isPaintserver() : style->stroke.isPaintserver()) + if (style && + (isFill ? style->fill.isPaintserver() : style->stroke.isPaintserver()) //&& SP_IS_GRADIENT(isFill ? style->getFillPaintServer() : style->getStrokePaintServer()) ) { - && (isFill ? SP_IS_GRADIENT(style->getFillPaintServer()) : SP_IS_GRADIENT(style->getStrokePaintServer())) ) { + && (isFill ? SP_IS_GRADIENT(style->getFillPaintServer()) : SP_IS_GRADIENT(style->getStrokePaintServer()))) { SPPaintServer *server = isFill ? style->getFillPaintServer() : style->getStrokePaintServer(); - if ( SP_IS_LINEARGRADIENT(server) ) { + if (SP_IS_LINEARGRADIENT(server)) { sp_item_set_gradient(item, gr, SP_GRADIENT_TYPE_LINEAR, mode); - } else if ( SP_IS_RADIALGRADIENT(server) ) { + } else if (SP_IS_RADIALGRADIENT(server)) { sp_item_set_gradient(item, gr, SP_GRADIENT_TYPE_RADIAL, mode); } - } - else if (initialMode == mode) - { + } else if (initialMode == mode) { sp_item_set_gradient(item, gr, initialType, mode); } } @@ -79,29 +76,31 @@ gradient. void gr_apply_gradient(Inkscape::Selection *selection, GrDrag *drag, SPGradient *gr) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - SPGradientType initialType = static_cast<SPGradientType>(prefs->getInt("/tools/gradient/newgradient", SP_GRADIENT_TYPE_LINEAR)); - Inkscape::PaintTarget initialMode = (prefs->getInt("/tools/gradient/newfillorstroke", 1) != 0) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; + SPGradientType initialType = + static_cast<SPGradientType>(prefs->getInt("/tools/gradient/newgradient", SP_GRADIENT_TYPE_LINEAR)); + Inkscape::PaintTarget initialMode = + (prefs->getInt("/tools/gradient/newfillorstroke", 1) != 0) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; // GRADIENTFIXME: make this work for multiple selected draggers. // First try selected dragger if (drag && !drag->selected.empty()) { GrDragger *dragger = *(drag->selected.begin()); - for(auto draggable : dragger->draggables) { //for all draggables of dragger + for (auto draggable : dragger->draggables) { // for all draggables of dragger gr_apply_gradient_to_item(draggable->item, gr, initialType, initialMode, draggable->fill_or_stroke); } return; } - // If no drag or no dragger selected, act on selection - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ - gr_apply_gradient_to_item(*i, gr, initialType, initialMode, initialMode); - } + // If no drag or no dragger selected, act on selection + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { + gr_apply_gradient_to_item(*i, gr, initialType, initialMode, initialMode); + } } -int gr_vector_list(Glib::RefPtr<Gtk::ListStore> store, SPDesktop *desktop, - bool selection_empty, SPGradient *gr_selected, bool gr_multi) +int gr_vector_list(Glib::RefPtr<Gtk::ListStore> store, SPDesktop *desktop, bool selection_empty, + SPGradient *gr_selected, bool gr_multi) { int selected = -1; @@ -112,10 +111,10 @@ int gr_vector_list(Glib::RefPtr<Gtk::ListStore> store, SPDesktop *desktop, // Get list of gradients in document. SPDocument *document = desktop->getDocument(); std::vector<SPObject *> gl; - std::vector<SPObject *> gradients = document->getResourceList( "gradient" ); + std::vector<SPObject *> gradients = document->getResourceList("gradient"); for (auto gradient : gradients) { SPGradient *grad = SP_GRADIENT(gradient); - if ( grad->hasStops() && !grad->isSolid() ) { + if (grad->hasStops() && !grad->isSolid()) { gl.push_back(gradient); } } @@ -129,39 +128,38 @@ int gr_vector_list(Glib::RefPtr<Gtk::ListStore> store, SPDesktop *desktop, // The document has no gradients row = *(store->append()); - row[columns.col_label ] = _("No gradient"); - row[columns.col_tooltip ] = ""; - row[columns.col_icon ] = "NotUsed"; - row[columns.col_data ] = nullptr; + row[columns.col_label] = _("No gradient"); + row[columns.col_tooltip] = ""; + row[columns.col_icon] = "NotUsed"; + row[columns.col_data] = nullptr; row[columns.col_sensitive] = true; } else if (selection_empty) { // Document has gradients, but nothing is currently selected. row = *(store->append()); - row[columns.col_label ] = _("Nothing Selected"); - row[columns.col_tooltip ] = ""; - row[columns.col_icon ] = "NotUsed"; - row[columns.col_data ] = nullptr; + row[columns.col_label] = _("Nothing Selected"); + row[columns.col_tooltip] = ""; + row[columns.col_icon] = "NotUsed"; + row[columns.col_data] = nullptr; row[columns.col_sensitive] = true; } else { - if (gr_selected == nullptr) { row = *(store->append()); - row[columns.col_label ] = _("No gradient"); - row[columns.col_tooltip ] = ""; - row[columns.col_icon ] = "NotUsed"; - row[columns.col_data ] = nullptr; + row[columns.col_label] = _("No gradient"); + row[columns.col_tooltip] = ""; + row[columns.col_icon] = "NotUsed"; + row[columns.col_data] = nullptr; row[columns.col_sensitive] = true; } if (gr_multi) { row = *(store->append()); - row[columns.col_label ] = _("Multiple gradients"); - row[columns.col_tooltip ] = ""; - row[columns.col_icon ] = "NotUsed"; - row[columns.col_data ] = nullptr; + row[columns.col_label] = _("Multiple gradients"); + row[columns.col_tooltip] = ""; + row[columns.col_icon] = "NotUsed"; + row[columns.col_data] = nullptr; row[columns.col_sensitive] = true; } @@ -173,17 +171,17 @@ int gr_vector_list(Glib::RefPtr<Gtk::ListStore> store, SPDesktop *desktop, Glib::RefPtr<Gdk::Pixbuf> pixbuf = sp_gradient_to_pixbuf_ref(gradient, 64, 16); row = *(store->append()); - row[columns.col_label ] = label; - row[columns.col_tooltip ] = ""; - row[columns.col_icon ] = "NotUsed"; - row[columns.col_pixbuf ] = pixbuf; - row[columns.col_data ] = gradient; + row[columns.col_label] = label; + row[columns.col_tooltip] = ""; + row[columns.col_icon] = "NotUsed"; + row[columns.col_pixbuf] = pixbuf; + row[columns.col_data] = gradient; row[columns.col_sensitive] = true; if (gradient == gr_selected) { selected = idx; } - idx ++; + idx++; } if (gr_multi) { @@ -202,22 +200,22 @@ void gr_get_dt_selected_gradient(Inkscape::Selection *selection, SPGradient *&gr { SPGradient *gradient = nullptr; - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ - SPItem *item = *i;// get the items gradient, not the getVector() version - SPStyle *style = item->style; - SPPaintServer *server = nullptr; - - if (style && (style->fill.isPaintserver())) { - server = item->style->getFillPaintServer(); - } - if (style && (style->stroke.isPaintserver())) { - server = item->style->getStrokePaintServer(); - } - - if ( SP_IS_GRADIENT(server) ) { - gradient = SP_GRADIENT(server); - } + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { + SPItem *item = *i; // get the items gradient, not the getVector() version + SPStyle *style = item->style; + SPPaintServer *server = nullptr; + + if (style && (style->fill.isPaintserver())) { + server = item->style->getFillPaintServer(); + } + if (style && (style->stroke.isPaintserver())) { + server = item->style->getStrokePaintServer(); + } + + if (SP_IS_GRADIENT(server)) { + gradient = SP_GRADIENT(server); + } } if (gradient && gradient->isSolid()) { @@ -232,17 +230,13 @@ void gr_get_dt_selected_gradient(Inkscape::Selection *selection, SPGradient *&gr /* * Get the current selection and dragger status from the desktop */ -void gr_read_selection( Inkscape::Selection *selection, - GrDrag *drag, - SPGradient *&gr_selected, - bool &gr_multi, - SPGradientSpread &spr_selected, - bool &spr_multi ) +void gr_read_selection(Inkscape::Selection *selection, GrDrag *drag, SPGradient *&gr_selected, bool &gr_multi, + SPGradientSpread &spr_selected, bool &spr_multi) { if (drag && !drag->selected.empty()) { // GRADIENTFIXME: make this work for more than one selected dragger? GrDragger *dragger = *(drag->selected.begin()); - for(auto draggable : dragger->draggables) { //for all draggables of dragger + for (auto draggable : dragger->draggables) { // for all draggables of dragger SPGradient *gradient = sp_item_gradient_get_vector(draggable->item, draggable->fill_or_stroke); SPGradientSpread spread = sp_item_gradient_get_spread(draggable->item, draggable->fill_or_stroke); @@ -264,19 +258,19 @@ void gr_read_selection( Inkscape::Selection *selection, spr_selected = spread; } } - } + } return; } - // If no selected dragger, read desktop selection - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + // If no selected dragger, read desktop selection + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; SPStyle *style = item->style; if (style && (style->fill.isPaintserver())) { SPPaintServer *server = item->style->getFillPaintServer(); - if ( SP_IS_GRADIENT(server) ) { + if (SP_IS_GRADIENT(server)) { SPGradient *gradient = SP_GRADIENT(server)->getVector(); SPGradientSpread spread = SP_GRADIENT(server)->fetchSpread(); @@ -302,7 +296,7 @@ void gr_read_selection( Inkscape::Selection *selection, } if (style && (style->stroke.isPaintserver())) { SPPaintServer *server = item->style->getStrokePaintServer(); - if ( SP_IS_GRADIENT(server) ) { + if (SP_IS_GRADIENT(server)) { SPGradient *gradient = SP_GRADIENT(server)->getVector(); SPGradientSpread spread = SP_GRADIENT(server)->fetchSpread(); @@ -327,13 +321,13 @@ void gr_read_selection( Inkscape::Selection *selection, } } } - } +} namespace Inkscape { namespace UI { namespace Toolbar { GradientToolbar::GradientToolbar(SPDesktop *desktop) - : Toolbar(desktop) + : Toolbar(desktop) { auto prefs = Inkscape::Preferences::get(); @@ -354,13 +348,13 @@ GradientToolbar::GradientToolbar(SPDesktop *desktop) _new_type_buttons.push_back(radial_button); gint mode = prefs->getInt("/tools/gradient/newgradient", SP_GRADIENT_TYPE_LINEAR); - _new_type_buttons[ mode == SP_GRADIENT_TYPE_LINEAR ? 0 : 1 ]->set_active(); // linear == 1, radial == 2 + _new_type_buttons[mode == SP_GRADIENT_TYPE_LINEAR ? 0 : 1]->set_active(); // linear == 1, radial == 2 int btn_index = 0; - for (auto btn : _new_type_buttons) - { + for (auto btn : _new_type_buttons) { btn->set_sensitive(true); - btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &GradientToolbar::new_type_changed), btn_index++)); + btn->signal_clicked().connect( + sigc::bind(sigc::mem_fun(*this, &GradientToolbar::new_type_changed), btn_index++)); add(*btn); } } @@ -379,19 +373,20 @@ GradientToolbar::GradientToolbar(SPDesktop *desktop) stroke_btn->set_icon_name(INKSCAPE_ICON("object-stroke")); _new_fillstroke_buttons.push_back(stroke_btn); - auto fsmode = (prefs->getInt("/tools/gradient/newfillorstroke", 1) != 0) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; - _new_fillstroke_buttons[ fsmode == Inkscape::FOR_FILL ? 0 : 1 ]->set_active(); + auto fsmode = + (prefs->getInt("/tools/gradient/newfillorstroke", 1) != 0) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; + _new_fillstroke_buttons[fsmode == Inkscape::FOR_FILL ? 0 : 1]->set_active(); auto btn_index = 0; - for (auto btn : _new_fillstroke_buttons) - { - btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &GradientToolbar::new_fillstroke_changed), btn_index++)); + for (auto btn : _new_fillstroke_buttons) { + btn->signal_clicked().connect( + sigc::bind(sigc::mem_fun(*this, &GradientToolbar::new_fillstroke_changed), btn_index++)); btn->set_sensitive(); add(*btn); } } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Gradient Select list*/ { @@ -402,21 +397,21 @@ GradientToolbar::GradientToolbar(SPDesktop *desktop) Gtk::TreeModel::Row row; row = *(store->append()); - row[columns.col_label ] = _("No gradient"); - row[columns.col_tooltip ] = ""; - row[columns.col_icon ] = "NotUsed"; + row[columns.col_label] = _("No gradient"); + row[columns.col_tooltip] = ""; + row[columns.col_icon] = "NotUsed"; row[columns.col_sensitive] = true; - _select_cb = UI::Widget::ComboToolItem::create(_("Select"), // Label - "", // Tooltip - "Not Used", // Icon - store ); // Tree store + _select_cb = UI::Widget::ComboToolItem::create(_("Select"), // Label + "", // Tooltip + "Not Used", // Icon + store); // Tree store - _select_cb->use_icon( false ); - _select_cb->use_pixbuf( true ); - _select_cb->use_group_label( true ); - _select_cb->set_active( 0 ); - _select_cb->set_sensitive( false ); + _select_cb->use_icon(false); + _select_cb->use_pixbuf(true); + _select_cb->use_group_label(true); + _select_cb->set_active(0); + _select_cb->set_sensitive(false); add(*_select_cb); _select_cb->signal_changed().connect(sigc::mem_fun(*this, &GradientToolbar::gradient_changed)); @@ -424,8 +419,7 @@ GradientToolbar::GradientToolbar(SPDesktop *desktop) // Gradients Linked toggle { - _linked_item = add_toggle_button(_("Link gradients"), - _("Link gradients to change all related gradients")); + _linked_item = add_toggle_button(_("Link gradients"), _("Link gradients to change all related gradients")); _linked_item->set_icon_name(INKSCAPE_ICON("object-unlocked")); _linked_item->signal_toggled().connect(sigc::mem_fun(*this, &GradientToolbar::linked_changed)); @@ -448,25 +442,24 @@ GradientToolbar::GradientToolbar(SPDesktop *desktop) UI::Widget::ComboToolItemColumns columns; Glib::RefPtr<Gtk::ListStore> store = Gtk::ListStore::create(columns); - std::vector<gchar*> spread_dropdown_items_list = { - const_cast<gchar *>(C_("Gradient repeat type", "None")), - _("Reflected"), - _("Direct") - }; + std::vector<gchar *> spread_dropdown_items_list = {const_cast<gchar *>(C_("Gradient repeat type", "None")), + _("Reflected"), _("Direct")}; - for (auto item: spread_dropdown_items_list) { + for (auto item : spread_dropdown_items_list) { Gtk::TreeModel::Row row = *(store->append()); - row[columns.col_label ] = item; + row[columns.col_label] = item; row[columns.col_sensitive] = true; } - _spread_cb = Gtk::manage(UI::Widget::ComboToolItem::create(_("Repeat"), - // TRANSLATORS: for info, see http://www.w3.org/TR/2000/CR-SVG-20000802/pservers.html#LinearGradientSpreadMethodAttribute - _("Whether to fill with flat color beyond the ends of the gradient vector " - "(spreadMethod=\"pad\"), or repeat the gradient in the same direction " - "(spreadMethod=\"repeat\"), or repeat the gradient in alternating opposite " - "directions (spreadMethod=\"reflect\")"), - "Not Used", store)); + _spread_cb = Gtk::manage(UI::Widget::ComboToolItem::create( + _("Repeat"), + // TRANSLATORS: for info, see + // http://www.w3.org/TR/2000/CR-SVG-20000802/pservers.html#LinearGradientSpreadMethodAttribute + _("Whether to fill with flat color beyond the ends of the gradient vector " + "(spreadMethod=\"pad\"), or repeat the gradient in the same direction " + "(spreadMethod=\"repeat\"), or repeat the gradient in alternating opposite " + "directions (spreadMethod=\"reflect\")"), + "Not Used", store)); _spread_cb->use_group_label(true); _spread_cb->set_active(0); @@ -476,7 +469,7 @@ GradientToolbar::GradientToolbar(SPDesktop *desktop) add(*_spread_cb); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Gradient Stop list */ { @@ -487,22 +480,21 @@ GradientToolbar::GradientToolbar(SPDesktop *desktop) Gtk::TreeModel::Row row; row = *(store->append()); - row[columns.col_label ] = _("No stops"); - row[columns.col_tooltip ] = ""; - row[columns.col_icon ] = "NotUsed"; + row[columns.col_label] = _("No stops"); + row[columns.col_tooltip] = ""; + row[columns.col_icon] = "NotUsed"; row[columns.col_sensitive] = true; - _stop_cb = - UI::Widget::ComboToolItem::create(_("Stops" ), // Label - "", // Tooltip - "Not Used", // Icon - store ); // Tree store + _stop_cb = UI::Widget::ComboToolItem::create(_("Stops"), // Label + "", // Tooltip + "Not Used", // Icon + store); // Tree store - _stop_cb->use_icon( false ); - _stop_cb->use_pixbuf( true ); - _stop_cb->use_group_label( true ); - _stop_cb->set_active( 0 ); - _stop_cb->set_sensitive( false ); + _stop_cb->use_icon(false); + _stop_cb->use_pixbuf(true); + _stop_cb->use_group_label(true); + _stop_cb->set_active(0); + _stop_cb->set_sensitive(false); add(*_stop_cb); _stop_cb->signal_changed().connect(sigc::mem_fun(*this, &GradientToolbar::stop_changed)); @@ -512,10 +504,12 @@ GradientToolbar::GradientToolbar(SPDesktop *desktop) { auto offset_val = prefs->getDouble("/tools/gradient/stopoffset", 0); _offset_adj = Gtk::Adjustment::create(offset_val, 0.0, 1.0, 0.01, 0.1); - _offset_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("gradient-stopoffset", C_("Gradient", "Offset:"), _offset_adj, 0.01, 2)); + _offset_item = Gtk::manage( + new UI::Widget::SpinButtonToolItem("gradient-stopoffset", C_("Gradient", "Offset:"), _offset_adj, 0.01, 2)); _offset_item->set_tooltip_text(_("Offset of selected stop")); _offset_item->set_focus_widget(desktop->canvas); - _offset_adj->signal_value_changed().connect(sigc::mem_fun(*this, &GradientToolbar::stop_offset_adjustment_changed)); + _offset_adj->signal_value_changed().connect( + sigc::mem_fun(*this, &GradientToolbar::stop_offset_adjustment_changed)); add(*_offset_item); _offset_item->set_sensitive(false); } @@ -549,23 +543,19 @@ GradientToolbar::GradientToolbar(SPDesktop *desktop) * Gradient auxiliary toolbar construction and setup. * */ -GtkWidget * -GradientToolbar::create(SPDesktop * desktop) +GtkWidget *GradientToolbar::create(SPDesktop *desktop) { auto toolbar = new GradientToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -GradientToolbar::new_type_changed(int mode) +void GradientToolbar::new_type_changed(int mode) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setInt("/tools/gradient/newgradient", - mode == 0 ? SP_GRADIENT_TYPE_LINEAR : SP_GRADIENT_TYPE_RADIAL); + prefs->setInt("/tools/gradient/newgradient", mode == 0 ? SP_GRADIENT_TYPE_LINEAR : SP_GRADIENT_TYPE_RADIAL); } -void -GradientToolbar::new_fillstroke_changed(int mode) +void GradientToolbar::new_fillstroke_changed(int mode) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Inkscape::PaintTarget fsmode = (mode == 0) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; @@ -575,8 +565,7 @@ GradientToolbar::new_fillstroke_changed(int mode) /* * User selected a gradient from the combobox */ -void -GradientToolbar::gradient_changed(int active) +void GradientToolbar::gradient_changed(int active) { if (blocked) { return; @@ -598,8 +587,7 @@ GradientToolbar::gradient_changed(int active) gr_apply_gradient(selection, ev ? ev->get_drag() : nullptr, gr); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, - _("Assign gradient to object")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, _("Assign gradient to object")); } blocked = false; @@ -608,16 +596,15 @@ GradientToolbar::gradient_changed(int active) /** * \brief Return gradient selected in menu */ -SPGradient * -GradientToolbar::get_selected_gradient() +SPGradient *GradientToolbar::get_selected_gradient() { int active = _select_cb->get_active(); auto store = _select_cb->get_store(); - auto row = store->children()[active]; + auto row = store->children()[active]; UI::Widget::ComboToolItemColumns columns; - void* pointer = row[columns.col_data]; + void *pointer = row[columns.col_data]; SPGradient *gr = static_cast<SPGradient *>(pointer); return gr; @@ -626,8 +613,7 @@ GradientToolbar::get_selected_gradient() /** * \brief User selected a spread method from the combobox */ -void -GradientToolbar::spread_changed(int active) +void GradientToolbar::spread_changed(int active) { if (blocked) { return; @@ -640,12 +626,11 @@ GradientToolbar::spread_changed(int active) gr_get_dt_selected_gradient(selection, gradient); if (gradient) { - SPGradientSpread spread = (SPGradientSpread) active; + SPGradientSpread spread = (SPGradientSpread)active; gradient->setSpread(spread); gradient->updateRepr(); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, - _("Set gradient repeat")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, _("Set gradient repeat")); } blocked = false; @@ -654,8 +639,7 @@ GradientToolbar::spread_changed(int active) /** * \brief User selected a stop from the combobox */ -void -GradientToolbar::stop_changed(int active) +void GradientToolbar::stop_changed(int active) { if (blocked) { return; @@ -671,9 +655,7 @@ GradientToolbar::stop_changed(int active) blocked = false; } -void -GradientToolbar::select_dragger_by_stop(SPGradient *gradient, - ToolBase *ev) +void GradientToolbar::select_dragger_by_stop(SPGradient *gradient, ToolBase *ev) { if (!blocked) { std::cerr << "select_dragger_by_stop: should be blocked!" << std::endl; @@ -698,15 +680,14 @@ GradientToolbar::select_dragger_by_stop(SPGradient *gradient, /** * \brief Get stop selected by menu */ -SPStop * -GradientToolbar::get_selected_stop() +SPStop *GradientToolbar::get_selected_stop() { int active = _stop_cb->get_active(); auto store = _stop_cb->get_store(); - auto row = store->children()[active]; + auto row = store->children()[active]; UI::Widget::ComboToolItemColumns columns; - void* pointer = row[columns.col_data]; + void *pointer = row[columns.col_data]; SPStop *stop = static_cast<SPStop *>(pointer); return stop; @@ -717,8 +698,7 @@ GradientToolbar::get_selected_stop() * * Set the offset widget value (based on which stop is selected) */ -void -GradientToolbar::stop_set_offset() +void GradientToolbar::stop_set_offset() { if (!blocked) { std::cerr << "gr_stop_set_offset: should be blocked!" << std::endl; @@ -737,7 +717,7 @@ GradientToolbar::stop_set_offset() SPStop *prev = nullptr; prev = stop->getPrevStop(); - if (prev != nullptr ) { + if (prev != nullptr) { _offset_adj->set_lower(prev->offset); } else { isEndStop = true; @@ -746,7 +726,7 @@ GradientToolbar::stop_set_offset() SPStop *next = nullptr; next = stop->getNextStop(); - if (next != nullptr ) { + if (next != nullptr) { _offset_adj->set_upper(next->offset); } else { isEndStop = true; @@ -754,14 +734,13 @@ GradientToolbar::stop_set_offset() } _offset_adj->set_value(stop->offset); - _offset_item->set_sensitive( !isEndStop ); + _offset_item->set_sensitive(!isEndStop); } /** * \brief User changed the offset */ -void -GradientToolbar::stop_offset_adjustment_changed() +void GradientToolbar::stop_offset_adjustment_changed() { if (blocked) { return; @@ -776,7 +755,6 @@ GradientToolbar::stop_offset_adjustment_changed() DocumentUndo::maybeDone(stop->document, "gradient:stop:offset", SP_VERB_CONTEXT_GRADIENT, _("Change gradient stop offset")); - } blocked = false; @@ -785,8 +763,7 @@ GradientToolbar::stop_offset_adjustment_changed() /** * \brief Add stop to gradient */ -void -GradientToolbar::add_stop() +void GradientToolbar::add_stop() { if (!_desktop) { return; @@ -808,8 +785,7 @@ GradientToolbar::add_stop() /** * \brief Remove stop from vector */ -void -GradientToolbar::remove_stop() +void GradientToolbar::remove_stop() { if (!_desktop) { return; @@ -834,8 +810,7 @@ GradientToolbar::remove_stop() /** * \brief Reverse vector */ -void -GradientToolbar::reverse() +void GradientToolbar::reverse() { sp_gradient_reverse_selected_gradients(_desktop); } @@ -843,11 +818,10 @@ GradientToolbar::reverse() /** * \brief Lock or unlock links */ -void -GradientToolbar::linked_changed() +void GradientToolbar::linked_changed() { bool active = _linked_item->get_active(); - if ( active ) { + if (active) { _linked_item->set_icon_name(INKSCAPE_ICON("object-locked")); } else { _linked_item->set_icon_name(INKSCAPE_ICON("object-unlocked")); @@ -862,24 +836,26 @@ GradientToolbar::linked_changed() * Checks the current tool and connects gradient aux toolbox signals if it happens to be the gradient tool. * Called every time the current tool changes by signal emission. */ -void -GradientToolbar::check_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) +void GradientToolbar::check_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec) { if (SP_IS_GRADIENT_CONTEXT(ec)) { Inkscape::Selection *selection = desktop->getSelection(); SPDocument *document = desktop->getDocument(); // connect to selection modified and changed signals - _connection_changed = selection->connectChanged(sigc::mem_fun(*this, &GradientToolbar::selection_changed)); + _connection_changed = selection->connectChanged(sigc::mem_fun(*this, &GradientToolbar::selection_changed)); _connection_modified = selection->connectModified(sigc::mem_fun(*this, &GradientToolbar::selection_modified)); - _connection_subselection_changed = desktop->connectToolSubselectionChanged(sigc::mem_fun(*this, &GradientToolbar::drag_selection_changed)); + _connection_subselection_changed = + desktop->connectToolSubselectionChanged(sigc::mem_fun(*this, &GradientToolbar::drag_selection_changed)); // Is this necessary? Couldn't hurt. selection_changed(selection); // connect to release and modified signals of the defs (i.e. when someone changes gradient) - _connection_defs_release = document->getDefs()->connectRelease(sigc::mem_fun(*this, &GradientToolbar::defs_release)); - _connection_defs_modified = document->getDefs()->connectModified(sigc::mem_fun(*this, &GradientToolbar::defs_modified)); + _connection_defs_release = + document->getDefs()->connectRelease(sigc::mem_fun(*this, &GradientToolbar::defs_release)); + _connection_defs_modified = + document->getDefs()->connectModified(sigc::mem_fun(*this, &GradientToolbar::defs_modified)); } else { if (_connection_changed) _connection_changed.disconnect(); @@ -897,8 +873,7 @@ GradientToolbar::check_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) /** * Core function, setup all the widgets whenever something changes on the desktop */ -void -GradientToolbar::selection_changed(Inkscape::Selection * /*selection*/) +void GradientToolbar::selection_changed(Inkscape::Selection * /*selection*/) { if (blocked) return; @@ -911,7 +886,6 @@ GradientToolbar::selection_changed(Inkscape::Selection * /*selection*/) Inkscape::Selection *selection = _desktop->getSelection(); // take from desktop, not from args if (selection) { - ToolBase *ev = _desktop->getEventContext(); GrDrag *drag = nullptr; if (ev) { @@ -927,29 +901,29 @@ GradientToolbar::selection_changed(Inkscape::Selection * /*selection*/) // Gradient selection menu auto store = _select_cb->get_store(); - int gradient = gr_vector_list (store, _desktop, selection->isEmpty(), gr_selected, gr_multi); + int gradient = gr_vector_list(store, _desktop, selection->isEmpty(), gr_selected, gr_multi); if (gradient < 0) { // No selection or no gradients - _select_cb->set_active( 0 ); - _select_cb->set_sensitive (false); + _select_cb->set_active(0); + _select_cb->set_sensitive(false); } else { // Single gradient or multiple gradients - _select_cb->set_active( gradient ); - _select_cb->set_sensitive (true); + _select_cb->set_active(gradient); + _select_cb->set_sensitive(true); } // Spread menu - _spread_cb->set_sensitive( gr_selected && !gr_multi ); - _spread_cb->set_active( gr_selected ? (int)spr_selected : 0 ); + _spread_cb->set_sensitive(gr_selected && !gr_multi); + _spread_cb->set_active(gr_selected ? (int)spr_selected : 0); _stops_add_item->set_sensitive((gr_selected && !gr_multi && drag && !drag->selected.empty())); _stops_delete_item->set_sensitive((gr_selected && !gr_multi && drag && !drag->selected.empty())); - _stops_reverse_item->set_sensitive((gr_selected!= nullptr)); + _stops_reverse_item->set_sensitive((gr_selected != nullptr)); - _stop_cb->set_sensitive( gr_selected && !gr_multi); + _stop_cb->set_sensitive(gr_selected && !gr_multi); - update_stop_list (gr_selected, nullptr, gr_multi); + update_stop_list(gr_selected, nullptr, gr_multi); select_stop_by_draggers(gr_selected, ev); } @@ -959,8 +933,7 @@ GradientToolbar::selection_changed(Inkscape::Selection * /*selection*/) /** * \brief Construct stop list */ -int -GradientToolbar::update_stop_list( SPGradient *gradient, SPStop *new_stop, bool gr_multi) +int GradientToolbar::update_stop_list(SPGradient *gradient, SPStop *new_stop, bool gr_multi) { if (!blocked) { std::cerr << "update_stop_list should be blocked!" << std::endl; @@ -983,48 +956,47 @@ GradientToolbar::update_stop_list( SPGradient *gradient, SPStop *new_stop, bool // No valid gradient row = *(store->append()); - row[columns.col_label ] = _("No gradient"); - row[columns.col_tooltip ] = ""; - row[columns.col_icon ] = "NotUsed"; - row[columns.col_data ] = nullptr; + row[columns.col_label] = _("No gradient"); + row[columns.col_tooltip] = ""; + row[columns.col_icon] = "NotUsed"; + row[columns.col_data] = nullptr; row[columns.col_sensitive] = true; } else if (!gradient->hasStops()) { // Has gradient but it has no stops row = *(store->append()); - row[columns.col_label ] = _("No stops in gradient"); - row[columns.col_tooltip ] = ""; - row[columns.col_icon ] = "NotUsed"; - row[columns.col_data ] = nullptr; + row[columns.col_label] = _("No stops in gradient"); + row[columns.col_tooltip] = ""; + row[columns.col_icon] = "NotUsed"; + row[columns.col_data] = nullptr; row[columns.col_sensitive] = true; } else { // Gradient has stops // Get list of stops - for (auto& ochild: gradient->children) { + for (auto &ochild : gradient->children) { if (SP_IS_STOP(&ochild)) { - SPStop *stop = SP_STOP(&ochild); - Glib::RefPtr<Gdk::Pixbuf> pixbuf = sp_gradstop_to_pixbuf_ref (stop, 32, 16); + Glib::RefPtr<Gdk::Pixbuf> pixbuf = sp_gradstop_to_pixbuf_ref(stop, 32, 16); Inkscape::XML::Node *repr = reinterpret_cast<SPItem *>(&ochild)->getRepr(); Glib::ustring label = gr_ellipsize_text(repr->attribute("id"), 25); row = *(store->append()); - row[columns.col_label ] = label; - row[columns.col_tooltip ] = ""; - row[columns.col_icon ] = "NotUsed"; - row[columns.col_pixbuf ] = pixbuf; - row[columns.col_data ] = stop; + row[columns.col_label] = label; + row[columns.col_tooltip] = ""; + row[columns.col_icon] = "NotUsed"; + row[columns.col_pixbuf] = pixbuf; + row[columns.col_data] = stop; row[columns.col_sensitive] = true; } } } if (new_stop != nullptr) { - selected = select_stop_in_list (gradient, new_stop); + selected = select_stop_in_list(gradient, new_stop); } return selected; @@ -1033,11 +1005,10 @@ GradientToolbar::update_stop_list( SPGradient *gradient, SPStop *new_stop, bool /** * \brief Find position of new_stop in menu. */ -int -GradientToolbar::select_stop_in_list(SPGradient *gradient, SPStop *new_stop) +int GradientToolbar::select_stop_in_list(SPGradient *gradient, SPStop *new_stop) { int i = 0; - for (auto& ochild: gradient->children) { + for (auto &ochild : gradient->children) { if (SP_IS_STOP(&ochild)) { if (&ochild == new_stop) { return i; @@ -1051,8 +1022,7 @@ GradientToolbar::select_stop_in_list(SPGradient *gradient, SPStop *new_stop) /** * \brief Set stop in menu to match stops selected by draggers */ -void -GradientToolbar::select_stop_by_draggers(SPGradient *gradient, ToolBase *ev) +void GradientToolbar::select_stop_by_draggers(SPGradient *gradient, ToolBase *ev) { if (!blocked) { std::cerr << "select_stop_by_draggers should be blocked!" << std::endl; @@ -1078,14 +1048,13 @@ GradientToolbar::select_stop_by_draggers(SPGradient *gradient, ToolBase *ev) int selected = -1; // For all selected draggers - for(auto dragger : drag->selected) { - + for (auto dragger : drag->selected) { // For all draggables of dragger - for(auto draggable : dragger->draggables) { - + for (auto draggable : dragger->draggables) { if (draggable->point_type != POINT_RG_FOCUS) { n++; - if (n > 1) break; + if (n > 1) + break; } stop = vector->getFirstStop(); @@ -1105,7 +1074,8 @@ GradientToolbar::select_stop_by_draggers(SPGradient *gradient, ToolBase *ev) break; } } - if (n > 1) break; + if (n > 1) + break; } if (n > 1) { @@ -1119,9 +1089,9 @@ GradientToolbar::select_stop_by_draggers(SPGradient *gradient, ToolBase *ev) auto store = _stop_cb->get_store(); auto row = *(store->prepend()); - row[columns.col_label ] = _("Multiple stops"); - row[columns.col_tooltip ] = ""; - row[columns.col_icon ] = "NotUsed"; + row[columns.col_label] = _("Multiple stops"); + row[columns.col_tooltip] = ""; + row[columns.col_icon] = "NotUsed"; row[columns.col_sensitive] = true; selected = 0; @@ -1130,42 +1100,38 @@ GradientToolbar::select_stop_by_draggers(SPGradient *gradient, ToolBase *ev) } if (selected < 0) { - _stop_cb->set_active (0); - _stop_cb->set_sensitive (false); + _stop_cb->set_active(0); + _stop_cb->set_sensitive(false); } else { - _stop_cb->set_active (selected); - _stop_cb->set_sensitive (true); + _stop_cb->set_active(selected); + _stop_cb->set_sensitive(true); stop_set_offset(); } } -void -GradientToolbar::selection_modified(Inkscape::Selection *selection, guint /*flags*/) +void GradientToolbar::selection_modified(Inkscape::Selection *selection, guint /*flags*/) { selection_changed(selection); } -void -GradientToolbar::drag_selection_changed(gpointer /*dragger*/) +void GradientToolbar::drag_selection_changed(gpointer /*dragger*/) { - selection_changed(nullptr); + selection_changed(nullptr); } -void -GradientToolbar::defs_release(SPObject * /*defs*/) +void GradientToolbar::defs_release(SPObject * /*defs*/) { selection_changed(nullptr); } -void -GradientToolbar::defs_modified(SPObject * /*defs*/, guint /*flags*/) +void GradientToolbar::defs_modified(SPObject * /*defs*/, guint /*flags*/) { selection_changed(nullptr); } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: mode:c++ diff --git a/src/ui/toolbar/gradient-toolbar.h b/src/ui/toolbar/gradient-toolbar.h index 96beb0f08b8a8d2fbcfc872336478cb714f88c2b..c622c1c22d38b0e80b0839a81d22670dba12ace6 100644 --- a/src/ui/toolbar/gradient-toolbar.h +++ b/src/ui/toolbar/gradient-toolbar.h @@ -13,10 +13,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; class SPGradient; class SPStop; @@ -27,7 +27,7 @@ class ComboBoxText; class RadioToolButton; class ToolButton; class ToolItem; -} +} // namespace Gtk namespace Inkscape { class Selection; @@ -40,10 +40,11 @@ class ToolBase; namespace Widget { class ComboToolItem; class SpinButtonToolItem; -} +} // namespace Widget namespace Toolbar { -class GradientToolbar : public Toolbar { +class GradientToolbar : public Toolbar +{ private: std::vector<Gtk::RadioToolButton *> _new_type_buttons; std::vector<Gtk::RadioToolButton *> _new_fillstroke_buttons; @@ -63,26 +64,25 @@ private: void new_type_changed(int mode); void new_fillstroke_changed(int mode); void gradient_changed(int active); - SPGradient * get_selected_gradient(); + SPGradient *get_selected_gradient(); void spread_changed(int active); void stop_changed(int active); - void select_dragger_by_stop(SPGradient *gradient, - UI::Tools::ToolBase *ev); - SPStop * get_selected_stop(); + void select_dragger_by_stop(SPGradient *gradient, UI::Tools::ToolBase *ev); + SPStop *get_selected_stop(); void stop_set_offset(); void stop_offset_adjustment_changed(); void add_stop(); void remove_stop(); void reverse(); void linked_changed(); - void check_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec); + void check_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec); void selection_changed(Inkscape::Selection *selection); - int update_stop_list( SPGradient *gradient, SPStop *new_stop, bool gr_multi); + int update_stop_list(SPGradient *gradient, SPStop *new_stop, bool gr_multi); int select_stop_in_list(SPGradient *gradient, SPStop *new_stop); void select_stop_by_draggers(SPGradient *gradient, UI::Tools::ToolBase *ev); void selection_modified(Inkscape::Selection *selection, guint flags); void drag_selection_changed(gpointer dragger); - void defs_release(SPObject * defs); + void defs_release(SPObject *defs); void defs_modified(SPObject *defs, guint flags); sigc::connection _connection_changed; @@ -95,11 +95,11 @@ protected: GradientToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_GRADIENT_TOOLBAR_H */ diff --git a/src/ui/toolbar/lpe-toolbar.cpp b/src/ui/toolbar/lpe-toolbar.cpp index ad08f6a15b2cf073a0f32e4b04e25bd9754351d5..00df87764a55490b19f56012414a945ca93e8ace 100644 --- a/src/ui/toolbar/lpe-toolbar.cpp +++ b/src/ui/toolbar/lpe-toolbar.cpp @@ -30,33 +30,31 @@ #include <gtkmm/radiotoolbutton.h> #include <gtkmm/separatortoolitem.h> -#include "live_effects/lpe-line_segment.h" - #include "helper/action-context.h" #include "helper/action.h" - +#include "live_effects/lpe-line_segment.h" #include "ui/icon-names.h" #include "ui/tools-switch.h" #include "ui/tools/lpe-tool.h" #include "ui/widget/combo-tool-item.h" #include "ui/widget/unit-tracker.h" -using Inkscape::UI::Widget::UnitTracker; -using Inkscape::Util::Unit; -using Inkscape::Util::Quantity; using Inkscape::DocumentUndo; -using Inkscape::UI::Tools::ToolBase; using Inkscape::UI::Tools::LpeTool; +using Inkscape::UI::Tools::ToolBase; +using Inkscape::UI::Widget::UnitTracker; +using Inkscape::Util::Quantity; +using Inkscape::Util::Unit; namespace Inkscape { namespace UI { namespace Toolbar { LPEToolbar::LPEToolbar(SPDesktop *desktop) - : Toolbar(desktop), - _tracker(new UnitTracker(Util::UNIT_TYPE_LINEAR)), - _freeze(false), - _currentlpe(nullptr), - _currentlpeitem(nullptr) + : Toolbar(desktop) + , _tracker(new UnitTracker(Util::UNIT_TYPE_LINEAR)) + , _freeze(false) + , _currentlpe(nullptr) + , _currentlpeitem(nullptr) { _tracker->setActiveUnit(_desktop->getNamedView()->display_units); @@ -79,9 +77,10 @@ LPEToolbar::LPEToolbar(SPDesktop *desktop) Inkscape::LivePathEffect::EffectType type; for (int i = 1; i < num_subtools; ++i) { // i == 0 ia INVALIDE_LPE. - type = lpesubtools[i].type; + type = lpesubtools[i].type; - auto btn = Gtk::manage(new Gtk::RadioToolButton(mode_group, Inkscape::LivePathEffect::LPETypeConverter.get_label(type))); + auto btn = Gtk::manage( + new Gtk::RadioToolButton(mode_group, Inkscape::LivePathEffect::LPETypeConverter.get_label(type))); btn->set_tooltip_text(_(Inkscape::LivePathEffect::LPETypeConverter.get_label(type).c_str())); btn->set_icon_name(lpesubtools[i].icon_name); _mode_buttons.push_back(btn); @@ -98,48 +97,46 @@ LPEToolbar::LPEToolbar(SPDesktop *desktop) _mode_buttons[mode]->set_active(); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Show limiting bounding box */ { - _show_bbox_item = add_toggle_button(_("Show limiting bounding box"), - _("Show bounding box (used to cut infinite lines)")); + _show_bbox_item = + add_toggle_button(_("Show limiting bounding box"), _("Show bounding box (used to cut infinite lines)")); _show_bbox_item->set_icon_name(INKSCAPE_ICON("show-bounding-box")); _show_bbox_item->signal_toggled().connect(sigc::mem_fun(*this, &LPEToolbar::toggle_show_bbox)); - _show_bbox_item->set_active(prefs->getBool( "/tools/lpetool/show_bbox", true )); + _show_bbox_item->set_active(prefs->getBool("/tools/lpetool/show_bbox", true)); } /* Set limiting bounding box to bbox of current selection */ { // TODO: Shouldn't this just be a button (not toggle button)? - _bbox_from_selection_item = add_toggle_button(_("Get limiting bounding box from selection"), - _("Set limiting bounding box (used to cut infinite lines) to the bounding box of current selection")); + _bbox_from_selection_item = add_toggle_button( + _("Get limiting bounding box from selection"), + _("Set limiting bounding box (used to cut infinite lines) to the bounding box of current selection")); _bbox_from_selection_item->set_icon_name(INKSCAPE_ICON("draw-geometry-set-bounding-box")); _bbox_from_selection_item->signal_toggled().connect(sigc::mem_fun(*this, &LPEToolbar::toggle_set_bbox)); _bbox_from_selection_item->set_active(false); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Combo box to choose line segment type */ { UI::Widget::ComboToolItemColumns columns; Glib::RefPtr<Gtk::ListStore> store = Gtk::ListStore::create(columns); - std::vector<gchar*> line_segment_dropdown_items_list = { - _("Closed"), - _("Open start"), - _("Open end"), - _("Open both") - }; + std::vector<gchar *> line_segment_dropdown_items_list = {_("Closed"), _("Open start"), _("Open end"), + _("Open both")}; - for (auto item: line_segment_dropdown_items_list) { + for (auto item : line_segment_dropdown_items_list) { Gtk::TreeModel::Row row = *(store->append()); - row[columns.col_label ] = item; + row[columns.col_label] = item; row[columns.col_sensitive] = true; } - _line_segment_combo = Gtk::manage(UI::Widget::ComboToolItem::create(_("Line Type"), _("Choose a line segment type"), "Not Used", store)); + _line_segment_combo = Gtk::manage( + UI::Widget::ComboToolItem::create(_("Line Type"), _("Choose a line segment type"), "Not Used", store)); _line_segment_combo->use_group_label(false); _line_segment_combo->set_active(0); @@ -148,32 +145,32 @@ LPEToolbar::LPEToolbar(SPDesktop *desktop) add(*_line_segment_combo); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Display measuring info for selected items */ { - _measuring_item = add_toggle_button(_("Display measuring info"), - _("Display measuring info for selected items")); + _measuring_item = + add_toggle_button(_("Display measuring info"), _("Display measuring info for selected items")); _measuring_item->set_icon_name(INKSCAPE_ICON("draw-geometry-show-measuring-info")); _measuring_item->signal_toggled().connect(sigc::mem_fun(*this, &LPEToolbar::toggle_show_measuring_info)); - _measuring_item->set_active( prefs->getBool( "/tools/lpetool/show_measuring_info", true ) ); + _measuring_item->set_active(prefs->getBool("/tools/lpetool/show_measuring_info", true)); } // Add the units menu { - _units_item = _tracker->create_tool_item(_("Units"), ("") ); + _units_item = _tracker->create_tool_item(_("Units"), ("")); add(*_units_item); _units_item->signal_changed_after().connect(sigc::mem_fun(*this, &LPEToolbar::unit_changed)); - _units_item->set_sensitive( prefs->getBool("/tools/lpetool/show_measuring_info", true)); + _units_item->set_sensitive(prefs->getBool("/tools/lpetool/show_measuring_info", true)); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Open LPE dialog (to adapt parameters numerically) */ { // TODO: Shouldn't this be a regular Gtk::ToolButton (not toggle)? - _open_lpe_dialog_item = add_toggle_button(_("Open LPE dialog"), - _("Open LPE dialog (to adapt parameters numerically)")); + _open_lpe_dialog_item = + add_toggle_button(_("Open LPE dialog"), _("Open LPE dialog (to adapt parameters numerically)")); _open_lpe_dialog_item->set_icon_name(INKSCAPE_ICON("dialog-geometry")); _open_lpe_dialog_item->signal_toggled().connect(sigc::mem_fun(*this, &LPEToolbar::open_lpe_dialog)); _open_lpe_dialog_item->set_active(false); @@ -184,22 +181,19 @@ LPEToolbar::LPEToolbar(SPDesktop *desktop) show_all(); } -void -LPEToolbar::set_mode(int mode) +void LPEToolbar::set_mode(int mode) { _mode_buttons[mode]->set_active(); } -GtkWidget * -LPEToolbar::create(SPDesktop *desktop) +GtkWidget *LPEToolbar::create(SPDesktop *desktop) { auto toolbar = new LPEToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } // this is called when the mode is changed via the toolbar (i.e., one of the subtool buttons is pressed) -void -LPEToolbar::mode_changed(int mode) +void LPEToolbar::mode_changed(int mode) { using namespace Inkscape::LivePathEffect; @@ -228,19 +222,19 @@ LPEToolbar::mode_changed(int mode) if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setInt( "/tools/lpetool/mode", mode ); + prefs->setInt("/tools/lpetool/mode", mode); } _freeze = false; } } -void -LPEToolbar::toggle_show_bbox() { +void LPEToolbar::toggle_show_bbox() +{ auto prefs = Inkscape::Preferences::get(); bool show = _show_bbox_item->get_active(); - prefs->setBool("/tools/lpetool/show_bbox", show); + prefs->setBool("/tools/lpetool/show_bbox", show); if (tools_isactive(_desktop, TOOLS_LPETOOL)) { LpeTool *lc = SP_LPETOOL_CONTEXT(_desktop->event_context); @@ -248,8 +242,7 @@ LPEToolbar::toggle_show_bbox() { } } -void -LPEToolbar::toggle_set_bbox() +void LPEToolbar::toggle_set_bbox() { auto selection = _desktop->selection; @@ -275,8 +268,7 @@ LPEToolbar::toggle_set_bbox() _bbox_from_selection_item->set_active(false); } -void -LPEToolbar::change_line_segment_type(int mode) +void LPEToolbar::change_line_segment_type(int mode) { using namespace Inkscape::LivePathEffect; @@ -297,8 +289,7 @@ LPEToolbar::change_line_segment_type(int mode) _freeze = false; } -void -LPEToolbar::toggle_show_measuring_info() +void LPEToolbar::toggle_show_measuring_info() { if (!tools_isactive(_desktop, TOOLS_LPETOOL)) { return; @@ -307,16 +298,15 @@ LPEToolbar::toggle_show_measuring_info() bool show = _measuring_item->get_active(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setBool("/tools/lpetool/show_measuring_info", show); + prefs->setBool("/tools/lpetool/show_measuring_info", show); LpeTool *lc = SP_LPETOOL_CONTEXT(_desktop->event_context); lpetool_show_measuring_info(lc, show); - _units_item->set_sensitive( show ); + _units_item->set_sensitive(show); } -void -LPEToolbar::unit_changed(int /* NotUsed */) +void LPEToolbar::unit_changed(int /* NotUsed */) { Unit const *unit = _tracker->getActiveUnit(); g_return_if_fail(unit != nullptr); @@ -330,21 +320,22 @@ LPEToolbar::unit_changed(int /* NotUsed */) } } -void -LPEToolbar::open_lpe_dialog() +void LPEToolbar::open_lpe_dialog() { if (tools_isactive(_desktop, TOOLS_LPETOOL)) { - sp_action_perform(Inkscape::Verb::get(SP_VERB_DIALOG_LIVE_PATH_EFFECT)->get_action(Inkscape::ActionContext(_desktop)), nullptr); + sp_action_perform( + Inkscape::Verb::get(SP_VERB_DIALOG_LIVE_PATH_EFFECT)->get_action(Inkscape::ActionContext(_desktop)), + nullptr); } _open_lpe_dialog_item->set_active(false); } -void -LPEToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) +void LPEToolbar::watch_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec) { if (SP_IS_LPETOOL_CONTEXT(ec)) { // Watch selection - c_selection_modified = desktop->getSelection()->connectModified(sigc::mem_fun(*this, &LPEToolbar::sel_modified)); + c_selection_modified = + desktop->getSelection()->connectModified(sigc::mem_fun(*this, &LPEToolbar::sel_modified)); c_selection_changed = desktop->getSelection()->connectChanged(sigc::mem_fun(*this, &LPEToolbar::sel_changed)); sel_changed(desktop->getSelection()); } else { @@ -355,8 +346,7 @@ LPEToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) } } -void -LPEToolbar::sel_modified(Inkscape::Selection *selection, guint /*flags*/) +void LPEToolbar::sel_modified(Inkscape::Selection *selection, guint /*flags*/) { ToolBase *ec = selection->desktop()->event_context; if (SP_IS_LPETOOL_CONTEXT(ec)) { @@ -364,8 +354,7 @@ LPEToolbar::sel_modified(Inkscape::Selection *selection, guint /*flags*/) } } -void -LPEToolbar::sel_changed(Inkscape::Selection *selection) +void LPEToolbar::sel_changed(Inkscape::Selection *selection) { using namespace Inkscape::LivePathEffect; ToolBase *ec = selection->desktop()->event_context; @@ -380,15 +369,14 @@ LPEToolbar::sel_changed(Inkscape::Selection *selection) // activate line segment combo box if a single item with LPELineSegment is selected SPItem *item = selection->singleItem(); if (item && SP_IS_LPE_ITEM(item) && lpetool_item_has_construction(lc, item)) { - SPLPEItem *lpeitem = SP_LPE_ITEM(item); - Effect* lpe = lpeitem->getCurrentLPE(); + Effect *lpe = lpeitem->getCurrentLPE(); if (lpe && lpe->effectType() == LINE_SEGMENT) { - LPELineSegment *lpels = static_cast<LPELineSegment*>(lpe); + LPELineSegment *lpels = static_cast<LPELineSegment *>(lpe); _currentlpe = lpe; _currentlpeitem = lpeitem; _line_segment_combo->set_sensitive(true); - _line_segment_combo->set_active( lpels->end_type.get_value() ); + _line_segment_combo->set_active(lpels->end_type.get_value()); } else { _currentlpe = nullptr; _currentlpeitem = nullptr; @@ -402,9 +390,9 @@ LPEToolbar::sel_changed(Inkscape::Selection *selection) } } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/lpe-toolbar.h b/src/ui/toolbar/lpe-toolbar.h index 903d9daf92d6d1b9e586c4d6aed5e28e525f5bd2..cf698b90373c586df22536a6eda894f111074f14 100644 --- a/src/ui/toolbar/lpe-toolbar.h +++ b/src/ui/toolbar/lpe-toolbar.h @@ -52,10 +52,11 @@ class ToolBase; namespace Widget { class ComboToolItem; class UnitTracker; -} +} // namespace Widget namespace Toolbar { -class LPEToolbar : public Toolbar { +class LPEToolbar : public Toolbar +{ private: std::unique_ptr<UI::Widget::UnitTracker> _tracker; std::vector<Gtk::RadioToolButton *> _mode_buttons; @@ -79,7 +80,7 @@ private: void sel_modified(Inkscape::Selection *selection, guint flags); void sel_changed(Inkscape::Selection *selection); void change_line_segment_type(int mode); - void watch_ec(SPDesktop* desktop, UI::Tools::ToolBase* ec); + void watch_ec(SPDesktop *desktop, UI::Tools::ToolBase *ec); void toggle_show_bbox(); void toggle_set_bbox(); @@ -90,12 +91,12 @@ protected: LPEToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); void set_mode(int mode); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_LPE_TOOLBAR_H */ diff --git a/src/ui/toolbar/measure-toolbar.cpp b/src/ui/toolbar/measure-toolbar.cpp index 4418025a7aa2c3c1314a1e48fca4e0521fe4a435..04928e8797c75978268d1d3ac4c446ac4dba7fe5 100644 --- a/src/ui/toolbar/measure-toolbar.cpp +++ b/src/ui/toolbar/measure-toolbar.cpp @@ -28,13 +28,11 @@ #include "measure-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/separatortoolitem.h> #include "desktop.h" #include "document-undo.h" #include "message-stack.h" - #include "ui/icon-names.h" #include "ui/tools/measure-tool.h" #include "ui/widget/canvas.h" @@ -43,10 +41,10 @@ #include "ui/widget/spin-button-tool-item.h" #include "ui/widget/unit-tracker.h" -using Inkscape::UI::Widget::UnitTracker; -using Inkscape::Util::Unit; using Inkscape::DocumentUndo; using Inkscape::UI::Tools::MeasureTool; +using Inkscape::UI::Widget::UnitTracker; +using Inkscape::Util::Unit; static MeasureTool *get_measure_tool(SPDesktop *desktop) { @@ -56,14 +54,12 @@ static MeasureTool *get_measure_tool(SPDesktop *desktop) return nullptr; } - - namespace Inkscape { namespace UI { namespace Toolbar { MeasureToolbar::MeasureToolbar(SPDesktop *desktop) - : Toolbar(desktop), - _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)) + : Toolbar(desktop) + , _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)) { auto prefs = Inkscape::Preferences::get(); _tracker->setActiveUnitByAbbr(prefs->getString("/tools/measure/unit").c_str()); @@ -72,7 +68,8 @@ MeasureToolbar::MeasureToolbar(SPDesktop *desktop) { auto font_size_val = prefs->getDouble("/tools/measure/fontsize", 10.0); _font_size_adj = Gtk::Adjustment::create(font_size_val, 1.0, 36.0, 1.0, 4.0); - auto font_size_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("measure-fontsize", _("Font Size:"), _font_size_adj, 0, 2)); + auto font_size_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("measure-fontsize", _("Font Size:"), _font_size_adj, 0, 2)); font_size_item->set_tooltip_text(_("The font size to be used in the measurement labels")); font_size_item->set_focus_widget(desktop->canvas); _font_size_adj->signal_value_changed().connect(sigc::mem_fun(*this, &MeasureToolbar::fontsize_value_changed)); @@ -83,7 +80,8 @@ MeasureToolbar::MeasureToolbar(SPDesktop *desktop) { auto precision_val = prefs->getDouble("/tools/measure/precision", 2); _precision_adj = Gtk::Adjustment::create(precision_val, 0, 10, 1, 0); - auto precision_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("measure-precision", _("Precision:"), _precision_adj, 0, 0)); + auto precision_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("measure-precision", _("Precision:"), _precision_adj, 0, 0)); precision_item->set_tooltip_text(_("Decimal precision of measure")); precision_item->set_focus_widget(desktop->canvas); _precision_adj->signal_value_changed().connect(sigc::mem_fun(*this, &MeasureToolbar::precision_value_changed)); @@ -94,7 +92,8 @@ MeasureToolbar::MeasureToolbar(SPDesktop *desktop) { auto scale_val = prefs->getDouble("/tools/measure/scale", 100.0); _scale_adj = Gtk::Adjustment::create(scale_val, 0.0, 90000.0, 1.0, 4.0); - auto scale_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("measure-scale", _("Scale %:"), _scale_adj, 0, 3)); + auto scale_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("measure-scale", _("Scale %:"), _scale_adj, 0, 3)); scale_item->set_tooltip_text(_("Scale the results")); scale_item->set_focus_widget(desktop->canvas); _scale_adj->signal_value_changed().connect(sigc::mem_fun(*this, &MeasureToolbar::scale_value_changed)); @@ -111,7 +110,7 @@ MeasureToolbar::MeasureToolbar(SPDesktop *desktop) /* units menu */ { - auto ti = _tracker->create_tool_item(_("Units"), _("The units to be used for the measurements") ); + auto ti = _tracker->create_tool_item(_("Units"), _("The units to be used for the measurements")); ti->signal_changed().connect(sigc::mem_fun(*this, &MeasureToolbar::unit_changed)); add(*ti); } @@ -120,8 +119,7 @@ MeasureToolbar::MeasureToolbar(SPDesktop *desktop) /* measure only selected */ { - _only_selected_item = add_toggle_button(_("Measure only selected"), - _("Measure only selected")); + _only_selected_item = add_toggle_button(_("Measure only selected"), _("Measure only selected")); _only_selected_item->set_icon_name(INKSCAPE_ICON("snap-bounding-box-center")); _only_selected_item->set_active(prefs->getBool("/tools/measure/only_selected", false)); _only_selected_item->signal_toggled().connect(sigc::mem_fun(*this, &MeasureToolbar::toggle_only_selected)); @@ -129,17 +127,16 @@ MeasureToolbar::MeasureToolbar(SPDesktop *desktop) /* ignore_1st_and_last */ { - _ignore_1st_and_last_item = add_toggle_button(_("Ignore first and last"), - _("Ignore first and last")); + _ignore_1st_and_last_item = add_toggle_button(_("Ignore first and last"), _("Ignore first and last")); _ignore_1st_and_last_item->set_icon_name(INKSCAPE_ICON("draw-geometry-line-segment")); _ignore_1st_and_last_item->set_active(prefs->getBool("/tools/measure/ignore_1st_and_last", true)); - _ignore_1st_and_last_item->signal_toggled().connect(sigc::mem_fun(*this, &MeasureToolbar::toggle_ignore_1st_and_last)); + _ignore_1st_and_last_item->signal_toggled().connect( + sigc::mem_fun(*this, &MeasureToolbar::toggle_ignore_1st_and_last)); } /* measure in betweens */ { - _inbetween_item = add_toggle_button(_("Show measures between items"), - _("Show measures between items")); + _inbetween_item = add_toggle_button(_("Show measures between items"), _("Show measures between items")); _inbetween_item->set_icon_name(INKSCAPE_ICON("distribute-randomize")); _inbetween_item->set_active(prefs->getBool("/tools/measure/show_in_between", true)); _inbetween_item->signal_toggled().connect(sigc::mem_fun(*this, &MeasureToolbar::toggle_show_in_between)); @@ -147,23 +144,21 @@ MeasureToolbar::MeasureToolbar(SPDesktop *desktop) /* only visible */ { - _show_hidden_item = add_toggle_button(_("Show hidden intersections"), - _("Show hidden intersections")); + _show_hidden_item = add_toggle_button(_("Show hidden intersections"), _("Show hidden intersections")); _show_hidden_item->set_icon_name(INKSCAPE_ICON("object-hidden")); _show_hidden_item->set_active(prefs->getBool("/tools/measure/show_hidden", true)); - _show_hidden_item->signal_toggled().connect(sigc::mem_fun(*this, &MeasureToolbar::toggle_show_hidden)) ; + _show_hidden_item->signal_toggled().connect(sigc::mem_fun(*this, &MeasureToolbar::toggle_show_hidden)); } /* measure only current layer */ { - _all_layers_item = add_toggle_button(_("Measure all layers"), - _("Measure all layers")); + _all_layers_item = add_toggle_button(_("Measure all layers"), _("Measure all layers")); _all_layers_item->set_icon_name(INKSCAPE_ICON("dialog-layers")); _all_layers_item->set_active(prefs->getBool("/tools/measure/all_layers", true)); _all_layers_item->signal_toggled().connect(sigc::mem_fun(*this, &MeasureToolbar::toggle_all_layers)); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* toggle start end */ { @@ -214,7 +209,8 @@ MeasureToolbar::MeasureToolbar(SPDesktop *desktop) { auto offset_val = prefs->getDouble("/tools/measure/offset", 5.0); _offset_adj = Gtk::Adjustment::create(offset_val, 0.0, 90000.0, 1.0, 4.0); - auto offset_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("measure-offset", _("Offset:"), _offset_adj, 0, 2)); + auto offset_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("measure-offset", _("Offset:"), _offset_adj, 0, 2)); offset_item->set_tooltip_text(_("Mark dimension offset")); offset_item->set_focus_widget(desktop->canvas); _offset_adj->signal_value_changed().connect(sigc::mem_fun(*this, &MeasureToolbar::offset_value_changed)); @@ -224,20 +220,17 @@ MeasureToolbar::MeasureToolbar(SPDesktop *desktop) show_all(); } -GtkWidget * -MeasureToolbar::create(SPDesktop * desktop) +GtkWidget *MeasureToolbar::create(SPDesktop *desktop) { auto toolbar = new MeasureToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } // MeasureToolbar::prep() -void -MeasureToolbar::fontsize_value_changed() +void MeasureToolbar::fontsize_value_changed() { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble(Glib::ustring("/tools/measure/fontsize"), - _font_size_adj->get_value()); + prefs->setDouble(Glib::ustring("/tools/measure/fontsize"), _font_size_adj->get_value()); MeasureTool *mt = get_measure_tool(_desktop); if (mt) { mt->showCanvasItems(); @@ -245,8 +238,7 @@ MeasureToolbar::fontsize_value_changed() } } -void -MeasureToolbar::unit_changed(int /* notUsed */) +void MeasureToolbar::unit_changed(int /* notUsed */) { Glib::ustring const unit = _tracker->getActiveUnit()->abbr; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -257,13 +249,11 @@ MeasureToolbar::unit_changed(int /* notUsed */) } } -void -MeasureToolbar::precision_value_changed() +void MeasureToolbar::precision_value_changed() { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setInt(Glib::ustring("/tools/measure/precision"), - _precision_adj->get_value()); + prefs->setInt(Glib::ustring("/tools/measure/precision"), _precision_adj->get_value()); MeasureTool *mt = get_measure_tool(_desktop); if (mt) { mt->showCanvasItems(); @@ -271,13 +261,11 @@ MeasureToolbar::precision_value_changed() } } -void -MeasureToolbar::scale_value_changed() +void MeasureToolbar::scale_value_changed() { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble(Glib::ustring("/tools/measure/scale"), - _scale_adj->get_value()); + prefs->setDouble(Glib::ustring("/tools/measure/scale"), _scale_adj->get_value()); MeasureTool *mt = get_measure_tool(_desktop); if (mt) { mt->showCanvasItems(); @@ -285,13 +273,11 @@ MeasureToolbar::scale_value_changed() } } -void -MeasureToolbar::offset_value_changed() +void MeasureToolbar::offset_value_changed() { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble(Glib::ustring("/tools/measure/offset"), - _offset_adj->get_value()); + prefs->setDouble(Glib::ustring("/tools/measure/offset"), _offset_adj->get_value()); MeasureTool *mt = get_measure_tool(_desktop); if (mt) { mt->showCanvasItems(); @@ -299,13 +285,12 @@ MeasureToolbar::offset_value_changed() } } -void -MeasureToolbar::toggle_only_selected() +void MeasureToolbar::toggle_only_selected() { auto prefs = Inkscape::Preferences::get(); bool active = _only_selected_item->get_active(); prefs->setBool("/tools/measure/only_selected", active); - if ( active ) { + if (active) { _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Measures only selected.")); } else { _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Measure all.")); @@ -316,13 +301,12 @@ MeasureToolbar::toggle_only_selected() } } -void -MeasureToolbar::toggle_ignore_1st_and_last() +void MeasureToolbar::toggle_ignore_1st_and_last() { auto prefs = Inkscape::Preferences::get(); bool active = _ignore_1st_and_last_item->get_active(); prefs->setBool("/tools/measure/ignore_1st_and_last", active); - if ( active ) { + if (active) { _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Start and end measures inactive.")); } else { _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Start and end measures active.")); @@ -333,13 +317,12 @@ MeasureToolbar::toggle_ignore_1st_and_last() } } -void -MeasureToolbar::toggle_show_in_between() +void MeasureToolbar::toggle_show_in_between() { auto prefs = Inkscape::Preferences::get(); bool active = _inbetween_item->get_active(); prefs->setBool("/tools/measure/show_in_between", active); - if ( active ) { + if (active) { _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Compute all elements.")); } else { _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Compute max length.")); @@ -350,13 +333,12 @@ MeasureToolbar::toggle_show_in_between() } } -void -MeasureToolbar::toggle_show_hidden() +void MeasureToolbar::toggle_show_hidden() { auto prefs = Inkscape::Preferences::get(); bool active = _show_hidden_item->get_active(); prefs->setBool("/tools/measure/show_hidden", active); - if ( active ) { + if (active) { _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Show all crossings.")); } else { _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Show visible crossings.")); @@ -367,13 +349,12 @@ MeasureToolbar::toggle_show_hidden() } } -void -MeasureToolbar::toggle_all_layers() +void MeasureToolbar::toggle_all_layers() { auto prefs = Inkscape::Preferences::get(); bool active = _all_layers_item->get_active(); prefs->setBool("/tools/measure/all_layers", active); - if ( active ) { + if (active) { _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Use all layers in the measure.")); } else { _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Use current layer in the measure.")); @@ -384,8 +365,7 @@ MeasureToolbar::toggle_all_layers() } } -void -MeasureToolbar::reverse_knots() +void MeasureToolbar::reverse_knots() { MeasureTool *mt = get_measure_tool(_desktop); if (mt) { @@ -393,8 +373,7 @@ MeasureToolbar::reverse_knots() } } -void -MeasureToolbar::to_phantom() +void MeasureToolbar::to_phantom() { MeasureTool *mt = get_measure_tool(_desktop); if (mt) { @@ -402,8 +381,7 @@ MeasureToolbar::to_phantom() } } -void -MeasureToolbar::to_guides() +void MeasureToolbar::to_guides() { MeasureTool *mt = get_measure_tool(_desktop); if (mt) { @@ -411,8 +389,7 @@ MeasureToolbar::to_guides() } } -void -MeasureToolbar::to_item() +void MeasureToolbar::to_item() { MeasureTool *mt = get_measure_tool(_desktop); if (mt) { @@ -420,8 +397,7 @@ MeasureToolbar::to_item() } } -void -MeasureToolbar::to_mark_dimension() +void MeasureToolbar::to_mark_dimension() { MeasureTool *mt = get_measure_tool(_desktop); if (mt) { @@ -429,10 +405,9 @@ MeasureToolbar::to_mark_dimension() } } -} -} -} - +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/measure-toolbar.h b/src/ui/toolbar/measure-toolbar.h index a922fa15e04e7f777e22d075563530e34bffad44..9c1a87183df25b48b80925d91fee2fa2358ec925 100644 --- a/src/ui/toolbar/measure-toolbar.h +++ b/src/ui/toolbar/measure-toolbar.h @@ -28,10 +28,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; namespace Inkscape { @@ -41,7 +41,8 @@ class UnitTracker; } namespace Toolbar { -class MeasureToolbar : public Toolbar { +class MeasureToolbar : public Toolbar +{ private: UI::Widget::UnitTracker *_tracker; Glib::RefPtr<Gtk::Adjustment> _font_size_adj; @@ -81,11 +82,11 @@ protected: MeasureToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_MEASURE_TOOLBAR_H */ diff --git a/src/ui/toolbar/mesh-toolbar.cpp b/src/ui/toolbar/mesh-toolbar.cpp index d5915215d07227dd7208dd467f2f58d5fe2eb20f..6fb4a73700b8cdd9b1fdee93ddc479bb4fbe4ade 100644 --- a/src/ui/toolbar/mesh-toolbar.cpp +++ b/src/ui/toolbar/mesh-toolbar.cpp @@ -18,7 +18,6 @@ #include "mesh-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/comboboxtext.h> #include <gtkmm/messagedialog.h> #include <gtkmm/radiotoolbutton.h> @@ -30,15 +29,11 @@ #include "gradient-chemistry.h" #include "gradient-drag.h" #include "inkscape.h" -#include "verbs.h" - #include "object/sp-defs.h" #include "object/sp-mesh-gradient.h" #include "object/sp-stop.h" #include "style.h" - #include "svg/css-ostringstream.h" - #include "ui/icon-names.h" #include "ui/simple-pref-pusher.h" #include "ui/tools/gradient-tool.h" @@ -48,6 +43,7 @@ #include "ui/widget/combo-tool-item.h" #include "ui/widget/gradient-image.h" #include "ui/widget/spin-button-tool-item.h" +#include "verbs.h" using Inkscape::DocumentUndo; using Inkscape::UI::Tools::MeshTool; @@ -55,23 +51,21 @@ using Inkscape::UI::Tools::MeshTool; static bool blocked = false; // Get a list of selected meshes taking into account fill/stroke toggles -std::vector<SPMeshGradient *> ms_get_dt_selected_gradients(Inkscape::Selection *selection) +std::vector<SPMeshGradient *> ms_get_dt_selected_gradients(Inkscape::Selection *selection) { std::vector<SPMeshGradient *> ms_selected; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool edit_fill = prefs->getBool("/tools/mesh/edit_fill", true); + bool edit_fill = prefs->getBool("/tools/mesh/edit_fill", true); bool edit_stroke = prefs->getBool("/tools/mesh/edit_stroke", true); - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ - SPItem *item = *i;// get the items gradient, not the getVector() version + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { + SPItem *item = *i; // get the items gradient, not the getVector() version SPStyle *style = item->style; if (style) { - - - if (edit_fill && style->fill.isPaintserver()) { + if (edit_fill && style->fill.isPaintserver()) { SPPaintServer *server = item->style->getFillPaintServer(); SPMeshGradient *mesh = dynamic_cast<SPMeshGradient *>(server); if (mesh) { @@ -87,20 +81,15 @@ std::vector<SPMeshGradient *> ms_get_dt_selected_gradients(Inkscape::Selection } } } - } return ms_selected; } - /* * Get the current selection status from the desktop */ -void ms_read_selection( Inkscape::Selection *selection, - SPMeshGradient *&ms_selected, - bool &ms_selected_multi, - SPMeshType &ms_type, - bool &ms_type_multi ) +void ms_read_selection(Inkscape::Selection *selection, SPMeshGradient *&ms_selected, bool &ms_selected_multi, + SPMeshType &ms_type, bool &ms_type_multi) { ms_selected = nullptr; ms_selected_multi = false; @@ -110,8 +99,8 @@ void ms_read_selection( Inkscape::Selection *selection, bool first = true; // Read desktop selection, taking into account fill/stroke toggles - std::vector<SPMeshGradient *> meshes = ms_get_dt_selected_gradients( selection ); - for (auto & meshe : meshes) { + std::vector<SPMeshGradient *> meshes = ms_get_dt_selected_gradients(selection); + for (auto &meshe : meshes) { if (first) { ms_selected = meshe; ms_type = meshe->type; @@ -127,33 +116,30 @@ void ms_read_selection( Inkscape::Selection *selection, } } - /* * Callback functions for user actions */ - /** Temporary hack: Returns the mesh tool in the active desktop. * Will go away during tool refactoring. */ static MeshTool *get_mesh_tool() { MeshTool *tool = nullptr; - if (SP_ACTIVE_DESKTOP ) { + if (SP_ACTIVE_DESKTOP) { Inkscape::UI::Tools::ToolBase *ec = SP_ACTIVE_DESKTOP->event_context; if (SP_IS_MESH_CONTEXT(ec)) { - tool = static_cast<MeshTool*>(ec); + tool = static_cast<MeshTool *>(ec); } } return tool; } - namespace Inkscape { namespace UI { namespace Toolbar { MeshToolbar::MeshToolbar(SPDesktop *desktop) - : Toolbar(desktop), - _edit_fill_pusher(nullptr) + : Toolbar(desktop) + , _edit_fill_pusher(nullptr) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -177,7 +163,8 @@ MeshToolbar::MeshToolbar(SPDesktop *desktop) for (auto btn : _new_type_buttons) { add(*btn); btn->set_sensitive(); - btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &MeshToolbar::new_geometry_changed), btn_idx++)); + btn->signal_clicked().connect( + sigc::bind(sigc::mem_fun(*this, &MeshToolbar::new_geometry_changed), btn_idx++)); } gint mode = prefs->getInt("/tools/mesh/mesh_geometry", SP_MESH_GEOMETRY_NORMAL); @@ -199,10 +186,11 @@ MeshToolbar::MeshToolbar(SPDesktop *desktop) _new_fillstroke_buttons.push_back(stroke_btn); int btn_idx = 0; - for(auto btn : _new_fillstroke_buttons) { + for (auto btn : _new_fillstroke_buttons) { add(*btn); btn->set_sensitive(true); - btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &MeshToolbar::new_fillstroke_changed), btn_idx++)); + btn->signal_clicked().connect( + sigc::bind(sigc::mem_fun(*this, &MeshToolbar::new_fillstroke_changed), btn_idx++)); } gint mode = prefs->getInt("/tools/mesh/newfillorstroke"); @@ -237,7 +225,7 @@ MeshToolbar::MeshToolbar(SPDesktop *desktop) col_item->set_sensitive(true); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); // TODO: These were disabled in the UI file. Either activate or delete #if 0 @@ -281,7 +269,8 @@ MeshToolbar::MeshToolbar(SPDesktop *desktop) { auto btn = Gtk::manage(new Gtk::ToolButton(_("Make elliptical"))); - btn->set_tooltip_text(_("Make selected sides elliptical by changing length of handles. Works best if handles already approximate ellipse.")); + btn->set_tooltip_text(_("Make selected sides elliptical by changing length of handles. Works best if handles " + "already approximate ellipse.")); btn->set_icon_name(INKSCAPE_ICON("node-segment-curve")); btn->signal_clicked().connect(sigc::mem_fun(*this, &MeshToolbar::make_elliptical)); add(*btn); @@ -295,7 +284,6 @@ MeshToolbar::MeshToolbar(SPDesktop *desktop) add(*btn); } - { auto btn = Gtk::manage(new Gtk::ToolButton(_("Scale mesh to bounding box:"))); btn->set_tooltip_text(_("Scale mesh to fit inside bounding box.")); @@ -304,7 +292,7 @@ MeshToolbar::MeshToolbar(SPDesktop *desktop) add(*btn); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Warning */ { @@ -323,17 +311,17 @@ MeshToolbar::MeshToolbar(SPDesktop *desktop) Gtk::TreeModel::Row row; row = *(store->append()); - row[columns.col_label ] = C_("Type", "Coons"); + row[columns.col_label] = C_("Type", "Coons"); row[columns.col_sensitive] = true; row = *(store->append()); - row[columns.col_label ] = _("Bicubic"); + row[columns.col_label] = _("Bicubic"); row[columns.col_sensitive] = true; - _select_type_item = Gtk::manage(UI::Widget::ComboToolItem::create(_("Smoothing"), + _select_type_item = Gtk::manage(UI::Widget::ComboToolItem::create( + _("Smoothing"), // TRANSLATORS: Type of Smoothing. See https://en.wikipedia.org/wiki/Coons_patch - _("Coons: no smoothing. Bicubic: smoothing across patch boundaries."), - "Not Used", store)); + _("Coons: no smoothing. Bicubic: smoothing across patch boundaries."), "Not Used", store)); _select_type_item->use_group_label(true); _select_type_item->set_active(0); @@ -350,29 +338,25 @@ MeshToolbar::MeshToolbar(SPDesktop *desktop) * Don't forget to add to XML in widgets/toolbox.cpp! * */ -GtkWidget * -MeshToolbar::create(SPDesktop * desktop) +GtkWidget *MeshToolbar::create(SPDesktop *desktop) { auto toolbar = new MeshToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -MeshToolbar::new_geometry_changed(int mode) +void MeshToolbar::new_geometry_changed(int mode) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setInt("/tools/mesh/mesh_geometry", mode); } -void -MeshToolbar::new_fillstroke_changed(int mode) +void MeshToolbar::new_fillstroke_changed(int mode) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setInt("/tools/mesh/newfillorstroke", mode); } -void -MeshToolbar::row_changed() +void MeshToolbar::row_changed() { if (blocked) { return; @@ -389,8 +373,7 @@ MeshToolbar::row_changed() blocked = FALSE; } -void -MeshToolbar::col_changed() +void MeshToolbar::col_changed() { if (blocked) { return; @@ -407,8 +390,7 @@ MeshToolbar::col_changed() blocked = FALSE; } -void -MeshToolbar::toggle_fill_stroke() +void MeshToolbar::toggle_fill_stroke() { auto prefs = Inkscape::Preferences::get(); prefs->setBool("tools/mesh/edit_fill", _edit_fill_item->get_active()); @@ -424,8 +406,7 @@ MeshToolbar::toggle_fill_stroke() } } -void -MeshToolbar::toggle_handles() +void MeshToolbar::toggle_handles() { MeshTool *mt = get_mesh_tool(); if (mt) { @@ -434,8 +415,7 @@ MeshToolbar::toggle_handles() } } -void -MeshToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) +void MeshToolbar::watch_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec) { if (SP_IS_MESH_CONTEXT(ec)) { // connect to selection modified and changed signals @@ -444,7 +424,8 @@ MeshToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) c_selection_changed = selection->connectChanged(sigc::mem_fun(*this, &MeshToolbar::selection_changed)); c_selection_modified = selection->connectModified(sigc::mem_fun(*this, &MeshToolbar::selection_modified)); - c_subselection_changed = desktop->connectToolSubselectionChanged(sigc::mem_fun(*this, &MeshToolbar::drag_selection_changed)); + c_subselection_changed = + desktop->connectToolSubselectionChanged(sigc::mem_fun(*this, &MeshToolbar::drag_selection_changed)); c_defs_release = document->getDefs()->connectRelease(sigc::mem_fun(*this, &MeshToolbar::defs_release)); c_defs_modified = document->getDefs()->connectModified(sigc::mem_fun(*this, &MeshToolbar::defs_modified)); @@ -463,26 +444,22 @@ MeshToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) } } -void -MeshToolbar::selection_modified(Inkscape::Selection *selection, guint /*flags*/) +void MeshToolbar::selection_modified(Inkscape::Selection *selection, guint /*flags*/) { selection_changed(selection); } -void -MeshToolbar::drag_selection_changed(gpointer /*dragger*/) +void MeshToolbar::drag_selection_changed(gpointer /*dragger*/) { selection_changed(nullptr); } -void -MeshToolbar::defs_release(SPObject * /*defs*/) +void MeshToolbar::defs_release(SPObject * /*defs*/) { selection_changed(nullptr); } -void -MeshToolbar::defs_modified(SPObject * /*defs*/, guint /*flags*/) +void MeshToolbar::defs_modified(SPObject * /*defs*/, guint /*flags*/) { selection_changed(nullptr); } @@ -490,8 +467,7 @@ MeshToolbar::defs_modified(SPObject * /*defs*/, guint /*flags*/) /* * Core function, setup all the widgets whenever something changes on the desktop */ -void -MeshToolbar::selection_changed(Inkscape::Selection * /* selection */) +void MeshToolbar::selection_changed(Inkscape::Selection * /* selection */) { // std::cout << "ms_tb_selection_changed" << std::endl; @@ -514,10 +490,10 @@ MeshToolbar::selection_changed(Inkscape::Selection * /* selection */) SPMeshGradient *ms_selected = nullptr; SPMeshType ms_type = SP_MESH_TYPE_COONS; bool ms_selected_multi = false; - bool ms_type_multi = false; - ms_read_selection( selection, ms_selected, ms_selected_multi, ms_type, ms_type_multi ); + bool ms_type_multi = false; + ms_read_selection(selection, ms_selected, ms_selected_multi, ms_type, ms_type_multi); // std::cout << " type: " << ms_type << std::endl; - + if (_select_type_item) { _select_type_item->set_sensitive(!ms_type_multi); blocked = TRUE; @@ -527,8 +503,7 @@ MeshToolbar::selection_changed(Inkscape::Selection * /* selection */) } } -void -MeshToolbar::warning_popup() +void MeshToolbar::warning_popup() { char *msg = _("Mesh gradients are part of SVG 2:\n" "* Syntax may change.\n" @@ -536,16 +511,14 @@ MeshToolbar::warning_popup() "\n" "For web: convert to bitmap (Edit->Make bitmap copy).\n" "For print: export to PDF."); - Gtk::MessageDialog dialog(msg, false, Gtk::MESSAGE_WARNING, - Gtk::BUTTONS_OK, true); + Gtk::MessageDialog dialog(msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK, true); dialog.run(); } /** * Sets mesh type: Coons, Bicubic */ -void -MeshToolbar::type_changed(int mode) +void MeshToolbar::type_changed(int mode) { if (blocked) { return; @@ -554,57 +527,52 @@ MeshToolbar::type_changed(int mode) Inkscape::Selection *selection = _desktop->getSelection(); std::vector<SPMeshGradient *> meshes = ms_get_dt_selected_gradients(selection); - SPMeshType type = (SPMeshType) mode; - for (auto & meshe : meshes) { + SPMeshType type = (SPMeshType)mode; + for (auto &meshe : meshes) { meshe->type = type; meshe->type_set = true; meshe->updateRepr(); } - if (!meshes.empty() ) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_MESH,_("Set mesh type")); + if (!meshes.empty()) { + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_MESH, _("Set mesh type")); } } -void -MeshToolbar::toggle_sides() +void MeshToolbar::toggle_sides() { MeshTool *mt = get_mesh_tool(); if (mt) { - sp_mesh_context_corner_operation( mt, MG_CORNER_SIDE_TOGGLE ); + sp_mesh_context_corner_operation(mt, MG_CORNER_SIDE_TOGGLE); } } -void -MeshToolbar::make_elliptical() +void MeshToolbar::make_elliptical() { MeshTool *mt = get_mesh_tool(); if (mt) { - sp_mesh_context_corner_operation( mt, MG_CORNER_SIDE_ARC ); + sp_mesh_context_corner_operation(mt, MG_CORNER_SIDE_ARC); } } -void -MeshToolbar::pick_colors() +void MeshToolbar::pick_colors() { MeshTool *mt = get_mesh_tool(); if (mt) { - sp_mesh_context_corner_operation( mt, MG_CORNER_COLOR_PICK ); + sp_mesh_context_corner_operation(mt, MG_CORNER_COLOR_PICK); } } -void -MeshToolbar::fit_mesh() +void MeshToolbar::fit_mesh() { MeshTool *mt = get_mesh_tool(); if (mt) { - sp_mesh_context_fit_mesh_in_bbox( mt ); + sp_mesh_context_fit_mesh_in_bbox(mt); } } - -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/mesh-toolbar.h b/src/ui/toolbar/mesh-toolbar.h index 2df441135dfb2aa9c8eaf6cc2f49704eb738fe0c..5be84ba7599a2538616ea3b7a7cc00e00ecd9897 100644 --- a/src/ui/toolbar/mesh-toolbar.h +++ b/src/ui/toolbar/mesh-toolbar.h @@ -15,10 +15,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; class SPObject; @@ -39,10 +39,11 @@ class ToolBase; namespace Widget { class ComboToolItem; class SpinButtonToolItem; -} +} // namespace Widget namespace Toolbar { -class MeshToolbar : public Toolbar { +class MeshToolbar : public Toolbar +{ private: std::vector<Gtk::RadioToolButton *> _new_type_buttons; std::vector<Gtk::RadioToolButton *> _new_fillstroke_buttons; @@ -71,7 +72,7 @@ private: void toggle_fill_stroke(); void selection_changed(Inkscape::Selection *selection); void toggle_handles(); - void watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec); + void watch_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec); void selection_modified(Inkscape::Selection *selection, guint flags); void drag_selection_changed(gpointer dragger); void defs_release(SPObject *defs); @@ -87,11 +88,11 @@ protected: MeshToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_MESH_TOOLBAR_H */ diff --git a/src/ui/toolbar/node-toolbar.cpp b/src/ui/toolbar/node-toolbar.cpp index a9b193dea4d61c5d9770cbd0051fad3d53abd754..4221773342074716098672abe25730f63344d55a 100644 --- a/src/ui/toolbar/node-toolbar.cpp +++ b/src/ui/toolbar/node-toolbar.cpp @@ -28,7 +28,6 @@ #include "node-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/adjustment.h> #include <gtkmm/image.h> #include <gtkmm/menutoolbutton.h> @@ -36,14 +35,10 @@ #include "desktop.h" #include "document-undo.h" -#include "inkscape.h" -#include "selection-chemistry.h" -#include "verbs.h" - #include "helper/action.h" - +#include "inkscape.h" #include "object/sp-namedview.h" - +#include "selection-chemistry.h" #include "ui/icon-names.h" #include "ui/simple-pref-pusher.h" #include "ui/tool/control-point-selection.h" @@ -53,25 +48,25 @@ #include "ui/widget/combo-tool-item.h" #include "ui/widget/spin-button-tool-item.h" #include "ui/widget/unit-tracker.h" - +#include "verbs.h" #include "widgets/widget-sizes.h" +using Inkscape::DocumentUndo; +using Inkscape::UI::Tools::NodeTool; using Inkscape::UI::Widget::UnitTracker; -using Inkscape::Util::Unit; using Inkscape::Util::Quantity; -using Inkscape::DocumentUndo; +using Inkscape::Util::Unit; using Inkscape::Util::unit_table; -using Inkscape::UI::Tools::NodeTool; /** Temporary hack: Returns the node tool in the active desktop. * Will go away during tool refactoring. */ static NodeTool *get_node_tool() { NodeTool *tool = nullptr; - if (SP_ACTIVE_DESKTOP ) { + if (SP_ACTIVE_DESKTOP) { Inkscape::UI::Tools::ToolBase *ec = SP_ACTIVE_DESKTOP->event_context; if (INK_IS_NODE_TOOL(ec)) { - tool = static_cast<NodeTool*>(ec); + tool = static_cast<NodeTool *>(ec); } } return tool; @@ -82,9 +77,9 @@ namespace UI { namespace Toolbar { NodeToolbar::NodeToolbar(SPDesktop *desktop) - : Toolbar(desktop), - _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)), - _freeze(false) + : Toolbar(desktop) + , _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)) + , _freeze(false) { auto prefs = Inkscape::Preferences::get(); @@ -102,36 +97,36 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) { // TODO: Consider moving back to icons in menu? - //auto insert_min_x_icon = Gtk::manage(new Gtk::Image()); - //insert_min_x_icon->set_from_icon_name(INKSCAPE_ICON("node_insert_min_x"), Gtk::ICON_SIZE_MENU); - //auto insert_min_x_item = Gtk::manage(new Gtk::MenuItem(*insert_min_x_icon)); + // auto insert_min_x_icon = Gtk::manage(new Gtk::Image()); + // insert_min_x_icon->set_from_icon_name(INKSCAPE_ICON("node_insert_min_x"), Gtk::ICON_SIZE_MENU); + // auto insert_min_x_item = Gtk::manage(new Gtk::MenuItem(*insert_min_x_icon)); auto insert_min_x_item = Gtk::manage(new Gtk::MenuItem(_("Insert node at min X"))); insert_min_x_item->set_tooltip_text(_("Insert new nodes at min X into selected segments")); insert_min_x_item->signal_activate().connect(sigc::mem_fun(*this, &NodeToolbar::edit_add_min_x)); insert_node_menu->append(*insert_min_x_item); } { - //auto insert_max_x_icon = Gtk::manage(new Gtk::Image()); - //insert_max_x_icon->set_from_icon_name(INKSCAPE_ICON("node_insert_max_x"), Gtk::ICON_SIZE_MENU); - //auto insert_max_x_item = Gtk::manage(new Gtk::MenuItem(*insert_max_x_icon)); + // auto insert_max_x_icon = Gtk::manage(new Gtk::Image()); + // insert_max_x_icon->set_from_icon_name(INKSCAPE_ICON("node_insert_max_x"), Gtk::ICON_SIZE_MENU); + // auto insert_max_x_item = Gtk::manage(new Gtk::MenuItem(*insert_max_x_icon)); auto insert_max_x_item = Gtk::manage(new Gtk::MenuItem(_("Insert node at max X"))); insert_max_x_item->set_tooltip_text(_("Insert new nodes at max X into selected segments")); insert_max_x_item->signal_activate().connect(sigc::mem_fun(*this, &NodeToolbar::edit_add_max_x)); insert_node_menu->append(*insert_max_x_item); } { - //auto insert_min_y_icon = Gtk::manage(new Gtk::Image()); - //insert_min_y_icon->set_from_icon_name(INKSCAPE_ICON("node_insert_min_y"), Gtk::ICON_SIZE_MENU); - //auto insert_min_y_item = Gtk::manage(new Gtk::MenuItem(*insert_min_y_icon)); + // auto insert_min_y_icon = Gtk::manage(new Gtk::Image()); + // insert_min_y_icon->set_from_icon_name(INKSCAPE_ICON("node_insert_min_y"), Gtk::ICON_SIZE_MENU); + // auto insert_min_y_item = Gtk::manage(new Gtk::MenuItem(*insert_min_y_icon)); auto insert_min_y_item = Gtk::manage(new Gtk::MenuItem(_("Insert node at min Y"))); insert_min_y_item->set_tooltip_text(_("Insert new nodes at min Y into selected segments")); insert_min_y_item->signal_activate().connect(sigc::mem_fun(*this, &NodeToolbar::edit_add_min_y)); insert_node_menu->append(*insert_min_y_item); } { - //auto insert_max_y_icon = Gtk::manage(new Gtk::Image()); - //insert_max_y_icon->set_from_icon_name(INKSCAPE_ICON("node_insert_max_y"), Gtk::ICON_SIZE_MENU); - //auto insert_max_y_item = Gtk::manage(new Gtk::MenuItem(*insert_max_y_icon)); + // auto insert_max_y_icon = Gtk::manage(new Gtk::Image()); + // insert_max_y_icon->set_from_icon_name(INKSCAPE_ICON("node_insert_max_y"), Gtk::ICON_SIZE_MENU); + // auto insert_max_y_item = Gtk::manage(new Gtk::MenuItem(*insert_max_y_icon)); auto insert_max_y_item = Gtk::manage(new Gtk::MenuItem(_("Insert node at max Y"))); insert_max_y_item->set_tooltip_text(_("Insert new nodes at max Y into selected segments")); insert_max_y_item->signal_activate().connect(sigc::mem_fun(*this, &NodeToolbar::edit_add_max_y)); @@ -151,7 +146,7 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) add(*delete_item); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { auto join_item = Gtk::manage(new Gtk::ToolButton(_("Join nodes"))); @@ -169,7 +164,7 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) add(*break_item); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { auto join_segment_item = Gtk::manage(new Gtk::ToolButton(_("Join with segment"))); @@ -187,7 +182,7 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) add(*delete_segment_item); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { auto cusp_item = Gtk::manage(new Gtk::ToolButton(_("Node Cusp"))); @@ -221,7 +216,7 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) add(*auto_item); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { auto line_item = Gtk::manage(new Gtk::ToolButton(_("Node Line"))); @@ -239,7 +234,7 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) add(*curve_item); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); auto context = Inkscape::ActionContext(_desktop); @@ -253,7 +248,7 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) add(*stroke_to_path_item); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* X coord of selected node(s) */ { @@ -265,7 +260,8 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) _nodes_x_item->set_custom_numeric_menu_data(values); _tracker->addAdjustment(_nodes_x_adj->gobj()); _nodes_x_item->set_focus_widget(desktop->canvas); - _nodes_x_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &NodeToolbar::value_changed), Geom::X)); + _nodes_x_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &NodeToolbar::value_changed), Geom::X)); _nodes_x_item->set_sensitive(false); add(*_nodes_x_item); } @@ -280,7 +276,8 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) _nodes_y_item->set_custom_numeric_menu_data(values); _tracker->addAdjustment(_nodes_y_adj->gobj()); _nodes_y_item->set_focus_widget(desktop->canvas); - _nodes_y_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &NodeToolbar::value_changed), Geom::Y)); + _nodes_y_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &NodeToolbar::value_changed), Geom::Y)); _nodes_y_item->set_sensitive(false); add(*_nodes_y_item); } @@ -291,26 +288,26 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) add(*unit_menu); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { - _object_edit_clip_path_item = add_toggle_button(_("Edit clipping paths"), - _("Show clipping path(s) of selected object(s)")); + _object_edit_clip_path_item = + add_toggle_button(_("Edit clipping paths"), _("Show clipping path(s) of selected object(s)")); _object_edit_clip_path_item->set_icon_name(INKSCAPE_ICON("path-clip-edit")); - _pusher_edit_clipping_paths.reset(new SimplePrefPusher(_object_edit_clip_path_item, "/tools/nodes/edit_clipping_paths")); - _object_edit_clip_path_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &NodeToolbar::on_pref_toggled), - _object_edit_clip_path_item, - "/tools/nodes/edit_clipping_paths")); + _pusher_edit_clipping_paths.reset( + new SimplePrefPusher(_object_edit_clip_path_item, "/tools/nodes/edit_clipping_paths")); + _object_edit_clip_path_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &NodeToolbar::on_pref_toggled), _object_edit_clip_path_item, + "/tools/nodes/edit_clipping_paths")); } { - _object_edit_mask_path_item = add_toggle_button(_("Edit masks"), - _("Show mask(s) of selected object(s)")); + _object_edit_mask_path_item = add_toggle_button(_("Edit masks"), _("Show mask(s) of selected object(s)")); _object_edit_mask_path_item->set_icon_name(INKSCAPE_ICON("path-mask-edit")); _pusher_edit_masks.reset(new SimplePrefPusher(_object_edit_mask_path_item, "/tools/nodes/edit_masks")); - _object_edit_mask_path_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &NodeToolbar::on_pref_toggled), - _object_edit_mask_path_item, - "/tools/nodes/edit_masks")); + _object_edit_mask_path_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &NodeToolbar::on_pref_toggled), _object_edit_mask_path_item, + "/tools/nodes/edit_masks")); } { @@ -318,36 +315,33 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) add(*_nodes_lpeedit_item); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { - _show_transform_handles_item = add_toggle_button(_("Show Transform Handles"), - _("Show transformation handles for selected nodes")); + _show_transform_handles_item = + add_toggle_button(_("Show Transform Handles"), _("Show transformation handles for selected nodes")); _show_transform_handles_item->set_icon_name(INKSCAPE_ICON("node-transform")); - _pusher_show_transform_handles.reset(new UI::SimplePrefPusher(_show_transform_handles_item, "/tools/nodes/show_transform_handles")); - _show_transform_handles_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &NodeToolbar::on_pref_toggled), - _show_transform_handles_item, - "/tools/nodes/show_transform_handles")); + _pusher_show_transform_handles.reset( + new UI::SimplePrefPusher(_show_transform_handles_item, "/tools/nodes/show_transform_handles")); + _show_transform_handles_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &NodeToolbar::on_pref_toggled), _show_transform_handles_item, + "/tools/nodes/show_transform_handles")); } { - _show_handles_item = add_toggle_button(_("Show Handles"), - _("Show Bezier handles of selected nodes")); + _show_handles_item = add_toggle_button(_("Show Handles"), _("Show Bezier handles of selected nodes")); _show_handles_item->set_icon_name(INKSCAPE_ICON("show-node-handles")); _pusher_show_handles.reset(new UI::SimplePrefPusher(_show_handles_item, "/tools/nodes/show_handles")); _show_handles_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &NodeToolbar::on_pref_toggled), - _show_handles_item, - "/tools/nodes/show_handles")); + _show_handles_item, "/tools/nodes/show_handles")); } { - _show_helper_path_item = add_toggle_button(_("Show Outline"), - _("Show path outline (without path effects)")); + _show_helper_path_item = add_toggle_button(_("Show Outline"), _("Show path outline (without path effects)")); _show_helper_path_item->set_icon_name(INKSCAPE_ICON("show-path-outline")); _pusher_show_outline.reset(new UI::SimplePrefPusher(_show_helper_path_item, "/tools/nodes/show_outline")); - _show_helper_path_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &NodeToolbar::on_pref_toggled), - _show_helper_path_item, - "/tools/nodes/show_outline")); + _show_helper_path_item->signal_toggled().connect(sigc::bind( + sigc::mem_fun(*this, &NodeToolbar::on_pref_toggled), _show_helper_path_item, "/tools/nodes/show_outline")); } sel_changed(desktop->getSelection()); @@ -356,15 +350,13 @@ NodeToolbar::NodeToolbar(SPDesktop *desktop) show_all(); } -GtkWidget * -NodeToolbar::create(SPDesktop *desktop) +GtkWidget *NodeToolbar::create(SPDesktop *desktop) { auto holder = new NodeToolbar(desktop); return GTK_WIDGET(holder->gobj()); } // NodeToolbar::prep() -void -NodeToolbar::value_changed(Geom::Dim2 d) +void NodeToolbar::value_changed(Geom::Dim2 d) { auto adj = (d == Geom::X) ? _nodes_x_adj : _nodes_y_adj; @@ -378,7 +370,7 @@ NodeToolbar::value_changed(Geom::Dim2 d) if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { prefs->setDouble(Glib::ustring("/tools/nodes/") + (d == Geom::X ? "x" : "y"), - Quantity::convert(adj->get_value(), unit, "px")); + Quantity::convert(adj->get_value(), unit, "px")); } // quit if run by the attr_changed listener @@ -393,7 +385,7 @@ NodeToolbar::value_changed(Geom::Dim2 d) if (nt && !nt->_selected_nodes->empty()) { double val = Quantity::convert(adj->get_value(), unit, "px"); double oldval = nt->_selected_nodes->pointwiseBounds()->midpoint()[d]; - Geom::Point delta(0,0); + Geom::Point delta(0, 0); delta[d] = val - oldval; nt->_multipath->move(delta); } @@ -401,29 +393,29 @@ NodeToolbar::value_changed(Geom::Dim2 d) _freeze = false; } -void -NodeToolbar::sel_changed(Inkscape::Selection *selection) +void NodeToolbar::sel_changed(Inkscape::Selection *selection) { SPItem *item = selection->singleItem(); if (item && SP_IS_LPE_ITEM(item)) { - if (SP_LPE_ITEM(item)->hasPathEffect()) { - _nodes_lpeedit_item->set_sensitive(true); - } else { - _nodes_lpeedit_item->set_sensitive(false); - } + if (SP_LPE_ITEM(item)->hasPathEffect()) { + _nodes_lpeedit_item->set_sensitive(true); + } else { + _nodes_lpeedit_item->set_sensitive(false); + } } else { - _nodes_lpeedit_item->set_sensitive(false); + _nodes_lpeedit_item->set_sensitive(false); } } -void -NodeToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) +void NodeToolbar::watch_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec) { if (INK_IS_NODE_TOOL(ec)) { // watch selection c_selection_changed = desktop->getSelection()->connectChanged(sigc::mem_fun(*this, &NodeToolbar::sel_changed)); - c_selection_modified = desktop->getSelection()->connectModified(sigc::mem_fun(*this, &NodeToolbar::sel_modified)); - c_subselection_changed = desktop->connectToolSubselectionChanged(sigc::mem_fun(*this, &NodeToolbar::coord_changed)); + c_selection_modified = + desktop->getSelection()->connectModified(sigc::mem_fun(*this, &NodeToolbar::sel_modified)); + c_subselection_changed = + desktop->connectToolSubselectionChanged(sigc::mem_fun(*this, &NodeToolbar::coord_changed)); sel_changed(desktop->getSelection()); } else { @@ -436,15 +428,13 @@ NodeToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) } } -void -NodeToolbar::sel_modified(Inkscape::Selection *selection, guint /*flags*/) +void NodeToolbar::sel_modified(Inkscape::Selection *selection, guint /*flags*/) { sel_changed(selection); } /* is called when the node selection is modified */ -void -NodeToolbar::coord_changed(gpointer /*shape_editor*/) +void NodeToolbar::coord_changed(gpointer /*shape_editor*/) { // quit if run by the attr_changed listener if (_freeze) { @@ -461,7 +451,7 @@ NodeToolbar::coord_changed(gpointer /*shape_editor*/) g_return_if_fail(unit != nullptr); NodeTool *nt = get_node_tool(); - if (!nt || !(nt->_selected_nodes) ||nt->_selected_nodes->empty()) { + if (!nt || !(nt->_selected_nodes) || nt->_selected_nodes->empty()) { // no path selected _nodes_x_item->set_sensitive(false); _nodes_y_item->set_sensitive(false); @@ -483,8 +473,7 @@ NodeToolbar::coord_changed(gpointer /*shape_editor*/) _freeze = false; } -void -NodeToolbar::edit_add() +void NodeToolbar::edit_add() { NodeTool *nt = get_node_tool(); if (nt) { @@ -492,8 +481,7 @@ NodeToolbar::edit_add() } } -void -NodeToolbar::edit_add_min_x() +void NodeToolbar::edit_add_min_x() { NodeTool *nt = get_node_tool(); if (nt) { @@ -501,8 +489,7 @@ NodeToolbar::edit_add_min_x() } } -void -NodeToolbar::edit_add_max_x() +void NodeToolbar::edit_add_max_x() { NodeTool *nt = get_node_tool(); if (nt) { @@ -510,8 +497,7 @@ NodeToolbar::edit_add_max_x() } } -void -NodeToolbar::edit_add_min_y() +void NodeToolbar::edit_add_min_y() { NodeTool *nt = get_node_tool(); if (nt) { @@ -519,8 +505,7 @@ NodeToolbar::edit_add_min_y() } } -void -NodeToolbar::edit_add_max_y() +void NodeToolbar::edit_add_max_y() { NodeTool *nt = get_node_tool(); if (nt) { @@ -528,8 +513,7 @@ NodeToolbar::edit_add_max_y() } } -void -NodeToolbar::edit_delete() +void NodeToolbar::edit_delete() { NodeTool *nt = get_node_tool(); if (nt) { @@ -538,8 +522,7 @@ NodeToolbar::edit_delete() } } -void -NodeToolbar::edit_join() +void NodeToolbar::edit_join() { NodeTool *nt = get_node_tool(); if (nt) { @@ -547,8 +530,7 @@ NodeToolbar::edit_join() } } -void -NodeToolbar::edit_break() +void NodeToolbar::edit_break() { NodeTool *nt = get_node_tool(); if (nt) { @@ -556,8 +538,7 @@ NodeToolbar::edit_break() } } -void -NodeToolbar::edit_delete_segment() +void NodeToolbar::edit_delete_segment() { NodeTool *nt = get_node_tool(); if (nt) { @@ -565,8 +546,7 @@ NodeToolbar::edit_delete_segment() } } -void -NodeToolbar::edit_join_segment() +void NodeToolbar::edit_join_segment() { NodeTool *nt = get_node_tool(); if (nt) { @@ -574,8 +554,7 @@ NodeToolbar::edit_join_segment() } } -void -NodeToolbar::edit_cusp() +void NodeToolbar::edit_cusp() { NodeTool *nt = get_node_tool(); if (nt) { @@ -583,8 +562,7 @@ NodeToolbar::edit_cusp() } } -void -NodeToolbar::edit_smooth() +void NodeToolbar::edit_smooth() { NodeTool *nt = get_node_tool(); if (nt) { @@ -592,8 +570,7 @@ NodeToolbar::edit_smooth() } } -void -NodeToolbar::edit_symmetrical() +void NodeToolbar::edit_symmetrical() { NodeTool *nt = get_node_tool(); if (nt) { @@ -601,8 +578,7 @@ NodeToolbar::edit_symmetrical() } } -void -NodeToolbar::edit_auto() +void NodeToolbar::edit_auto() { NodeTool *nt = get_node_tool(); if (nt) { @@ -610,8 +586,7 @@ NodeToolbar::edit_auto() } } -void -NodeToolbar::edit_toline() +void NodeToolbar::edit_toline() { NodeTool *nt = get_node_tool(); if (nt) { @@ -619,8 +594,7 @@ NodeToolbar::edit_toline() } } -void -NodeToolbar::edit_tocurve() +void NodeToolbar::edit_tocurve() { NodeTool *nt = get_node_tool(); if (nt) { @@ -628,17 +602,15 @@ NodeToolbar::edit_tocurve() } } -void -NodeToolbar::on_pref_toggled(Gtk::ToggleToolButton *item, - const Glib::ustring& path) +void NodeToolbar::on_pref_toggled(Gtk::ToggleToolButton *item, const Glib::ustring &path) { auto prefs = Inkscape::Preferences::get(); prefs->setBool(path, item->get_active()); } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/node-toolbar.h b/src/ui/toolbar/node-toolbar.h index fc603cbf50f21eef1a253c0d2e4102863955c71c..b34a3d70d2af71e88b849a193d6128746aede743 100644 --- a/src/ui/toolbar/node-toolbar.h +++ b/src/ui/toolbar/node-toolbar.h @@ -28,8 +28,8 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" #include "2geom/coord.h" +#include "toolbar.h" class SPDesktop; @@ -46,10 +46,11 @@ class ToolBase; namespace Widget { class SpinButtonToolItem; class UnitTracker; -} +} // namespace Widget namespace Toolbar { -class NodeToolbar : public Toolbar { +class NodeToolbar : public Toolbar +{ private: std::unique_ptr<UI::Widget::UnitTracker> _tracker; @@ -83,7 +84,7 @@ private: void sel_changed(Inkscape::Selection *selection); void sel_modified(Inkscape::Selection *selection, guint /*flags*/); void coord_changed(gpointer shape_editor); - void watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec); + void watch_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec); void edit_add(); void edit_add_min_x(); void edit_add_max_x(); @@ -100,16 +101,15 @@ private: void edit_auto(); void edit_toline(); void edit_tocurve(); - void on_pref_toggled(Gtk::ToggleToolButton *item, - const Glib::ustring& path); + void on_pref_toggled(Gtk::ToggleToolButton *item, const Glib::ustring &path); protected: NodeToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_SELECT_TOOLBAR_H */ diff --git a/src/ui/toolbar/paintbucket-toolbar.cpp b/src/ui/toolbar/paintbucket-toolbar.cpp index ad0f9fbde4324cd271406cccf47ea4b2e73da653..4cc153eced3fa1c20d7a3adfc55cf7750d5c3f22 100644 --- a/src/ui/toolbar/paintbucket-toolbar.cpp +++ b/src/ui/toolbar/paintbucket-toolbar.cpp @@ -28,12 +28,10 @@ #include "paintbucket-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/separatortoolitem.h> #include "desktop.h" #include "document-undo.h" - #include "ui/icon-names.h" #include "ui/tools/flood-tool.h" #include "ui/uxmanager.h" @@ -42,16 +40,16 @@ #include "ui/widget/spin-button-tool-item.h" #include "ui/widget/unit-tracker.h" -using Inkscape::UI::Widget::UnitTracker; using Inkscape::DocumentUndo; +using Inkscape::UI::Widget::UnitTracker; using Inkscape::Util::unit_table; namespace Inkscape { namespace UI { namespace Toolbar { PaintbucketToolbar::PaintbucketToolbar(SPDesktop *desktop) - : Toolbar(desktop), - _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)) + : Toolbar(desktop) + , _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)) { auto prefs = Inkscape::Preferences::get(); @@ -61,13 +59,14 @@ PaintbucketToolbar::PaintbucketToolbar(SPDesktop *desktop) Glib::RefPtr<Gtk::ListStore> store = Gtk::ListStore::create(columns); - for (auto item: Inkscape::UI::Tools::FloodTool::channel_list) { + for (auto item : Inkscape::UI::Tools::FloodTool::channel_list) { Gtk::TreeModel::Row row = *(store->append()); - row[columns.col_label ] = item; + row[columns.col_label] = item; row[columns.col_sensitive] = true; } - _channels_item = Gtk::manage(UI::Widget::ComboToolItem::create(_("Fill by"), Glib::ustring(), "Not Used", store)); + _channels_item = + Gtk::manage(UI::Widget::ComboToolItem::create(_("Fill by"), Glib::ustring(), "Not Used", store)); _channels_item->use_group_label(true); int channels = prefs->getInt("/tools/paintbucket/channels", 0); @@ -81,15 +80,17 @@ PaintbucketToolbar::PaintbucketToolbar(SPDesktop *desktop) { auto threshold_val = prefs->getDouble("/tools/paintbucket/threshold", 5); _threshold_adj = Gtk::Adjustment::create(threshold_val, 0, 100.0, 1.0, 10.0); - auto threshold_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("inkscape:paintbucket-threshold", _("Threshold:"), _threshold_adj, 1, 0)); - threshold_item->set_tooltip_text(_("The maximum allowed difference between the clicked pixel and the neighboring pixels to be counted in the fill")); + auto threshold_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("inkscape:paintbucket-threshold", + _("Threshold:"), _threshold_adj, 1, 0)); + threshold_item->set_tooltip_text(_("The maximum allowed difference between the clicked pixel and the " + "neighboring pixels to be counted in the fill")); threshold_item->set_focus_widget(desktop->canvas); _threshold_adj->signal_value_changed().connect(sigc::mem_fun(*this, &PaintbucketToolbar::threshold_changed)); // ege_adjustment_action_set_appearance( eact, TOOLBAR_SLIDER_HINT ); add(*threshold_item); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); // Create the units menu. Glib::ustring stored_unit = prefs->getString("/tools/paintbucket/offsetunits"); @@ -102,7 +103,8 @@ PaintbucketToolbar::PaintbucketToolbar(SPDesktop *desktop) { auto offset_val = prefs->getDouble("/tools/paintbucket/offset", 0); _offset_adj = Gtk::Adjustment::create(offset_val, -1e4, 1e4, 0.1, 0.5); - auto offset_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("inkscape:paintbucket-offset", _("Grow/shrink by:"), _offset_adj, 1, 2)); + auto offset_item = Gtk::manage( + new UI::Widget::SpinButtonToolItem("inkscape:paintbucket-offset", _("Grow/shrink by:"), _offset_adj, 1, 2)); offset_item->set_tooltip_text(_("The amount to grow (positive) or shrink (negative) the created fill path")); _tracker->addAdjustment(_offset_adj->gobj()); offset_item->set_focus_widget(desktop->canvas); @@ -115,7 +117,7 @@ PaintbucketToolbar::PaintbucketToolbar(SPDesktop *desktop) add(*unit_menu); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Auto Gap */ { @@ -123,13 +125,14 @@ PaintbucketToolbar::PaintbucketToolbar(SPDesktop *desktop) Glib::RefPtr<Gtk::ListStore> store = Gtk::ListStore::create(columns); - for (auto item: Inkscape::UI::Tools::FloodTool::gap_list) { + for (auto item : Inkscape::UI::Tools::FloodTool::gap_list) { Gtk::TreeModel::Row row = *(store->append()); - row[columns.col_label ] = item; + row[columns.col_label] = item; row[columns.col_sensitive] = true; } - _autogap_item = Gtk::manage(UI::Widget::ComboToolItem::create(_("Close gaps"), Glib::ustring(), "Not Used", store)); + _autogap_item = + Gtk::manage(UI::Widget::ComboToolItem::create(_("Close gaps"), Glib::ustring(), "Not Used", store)); _autogap_item->use_group_label(true); int autogap = prefs->getInt("/tools/paintbucket/autogap", 0); @@ -139,12 +142,13 @@ PaintbucketToolbar::PaintbucketToolbar(SPDesktop *desktop) add(*_autogap_item); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Reset */ { auto reset_button = Gtk::manage(new Gtk::ToolButton(_("Defaults"))); - reset_button->set_tooltip_text(_("Reset paint bucket parameters to defaults (use Inkscape Preferences > Tools to change defaults)")); + reset_button->set_tooltip_text( + _("Reset paint bucket parameters to defaults (use Inkscape Preferences > Tools to change defaults)")); reset_button->set_icon_name(INKSCAPE_ICON("edit-clear")); reset_button->signal_clicked().connect(sigc::mem_fun(*this, &PaintbucketToolbar::defaults)); add(*reset_button); @@ -154,28 +158,24 @@ PaintbucketToolbar::PaintbucketToolbar(SPDesktop *desktop) show_all(); } -GtkWidget * -PaintbucketToolbar::create(SPDesktop *desktop) +GtkWidget *PaintbucketToolbar::create(SPDesktop *desktop) { auto toolbar = new PaintbucketToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -PaintbucketToolbar::channels_changed(int channels) +void PaintbucketToolbar::channels_changed(int channels) { Inkscape::UI::Tools::FloodTool::set_channels(channels); } -void -PaintbucketToolbar::threshold_changed() +void PaintbucketToolbar::threshold_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setInt("/tools/paintbucket/threshold", (gint)_threshold_adj->get_value()); } -void -PaintbucketToolbar::offset_changed() +void PaintbucketToolbar::offset_changed() { Unit const *unit = _tracker->getActiveUnit(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -188,15 +188,13 @@ PaintbucketToolbar::offset_changed() prefs->setString("/tools/paintbucket/offsetunits", unit->abbr); } -void -PaintbucketToolbar::autogap_changed(int autogap) +void PaintbucketToolbar::autogap_changed(int autogap) { auto prefs = Inkscape::Preferences::get(); prefs->setInt("/tools/paintbucket/autogap", autogap); } -void -PaintbucketToolbar::defaults() +void PaintbucketToolbar::defaults() { // FIXME: make defaults settable via Inkscape Options _threshold_adj->set_value(15); @@ -206,9 +204,9 @@ PaintbucketToolbar::defaults() _autogap_item->set_active(0); } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/paintbucket-toolbar.h b/src/ui/toolbar/paintbucket-toolbar.h index d1b1a775e835f747b24e18b7a8afad7d0412602e..e49855ae0a99f8cea838792796b697e4d0b490b0 100644 --- a/src/ui/toolbar/paintbucket-toolbar.h +++ b/src/ui/toolbar/paintbucket-toolbar.h @@ -28,10 +28,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; namespace Inkscape { @@ -39,10 +39,11 @@ namespace UI { namespace Widget { class UnitTracker; class ComboToolItem; -} +} // namespace Widget namespace Toolbar { -class PaintbucketToolbar : public Toolbar { +class PaintbucketToolbar : public Toolbar +{ private: UI::Widget::ComboToolItem *_channels_item; UI::Widget::ComboToolItem *_autogap_item; @@ -62,11 +63,11 @@ protected: PaintbucketToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_PAINTBUCKET_TOOLBAR_H */ diff --git a/src/ui/toolbar/pencil-toolbar.cpp b/src/ui/toolbar/pencil-toolbar.cpp index 88410bc663cbae804f47e28ad07fe24266bf4f53..946c32695dcb4b05a7b47752f0bb37c7f3d00611 100644 --- a/src/ui/toolbar/pencil-toolbar.cpp +++ b/src/ui/toolbar/pencil-toolbar.cpp @@ -25,54 +25,47 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm.h> -#include <glibmm/i18n.h> - #include "pencil-toolbar.h" -#include "desktop.h" -#include "selection.h" +#include <glibmm/i18n.h> +#include <gtkmm.h> +#include "desktop.h" +#include "display/curve.h" #include "live_effects/lpe-bspline.h" #include "live_effects/lpe-powerstroke.h" #include "live_effects/lpe-simplify.h" #include "live_effects/lpe-spiro.h" #include "live_effects/lpeobject-reference.h" #include "live_effects/lpeobject.h" - -#include "display/curve.h" - #include "object/sp-shape.h" - +#include "selection.h" #include "ui/icon-names.h" #include "ui/tools-switch.h" #include "ui/tools/pen-tool.h" - +#include "ui/uxmanager.h" #include "ui/widget/canvas.h" -#include "ui/widget/label-tool-item.h" #include "ui/widget/combo-tool-item.h" +#include "ui/widget/label-tool-item.h" #include "ui/widget/spin-button-tool-item.h" -#include "ui/uxmanager.h" - using Inkscape::UI::UXManager; namespace Inkscape { namespace UI { namespace Toolbar { -PencilToolbar::PencilToolbar(SPDesktop *desktop, - bool pencil_mode) - : Toolbar(desktop), - _repr(nullptr), - _freeze(false), - _flatten_simplify(nullptr), - _simplify(nullptr) +PencilToolbar::PencilToolbar(SPDesktop *desktop, bool pencil_mode) + : Toolbar(desktop) + , _repr(nullptr) + , _freeze(false) + , _flatten_simplify(nullptr) + , _simplify(nullptr) { auto prefs = Inkscape::Preferences::get(); add_freehand_mode_toggle(pencil_mode); - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); if (pencil_mode) { /* Use pressure */ @@ -87,8 +80,8 @@ PencilToolbar::PencilToolbar(SPDesktop *desktop, { auto minpressure_val = prefs->getDouble("/tools/freehand/pencil/minpressure", 0); _minpressure_adj = Gtk::Adjustment::create(minpressure_val, 0, 100, 1, 0); - _minpressure = - Gtk::manage(new UI::Widget::SpinButtonToolItem("pencil-minpressure", _("Min:"), _minpressure_adj, 0, 0)); + _minpressure = Gtk::manage( + new UI::Widget::SpinButtonToolItem("pencil-minpressure", _("Min:"), _minpressure_adj, 0, 0)); _minpressure->set_tooltip_text(_("Min percent of pressure")); _minpressure->set_focus_widget(desktop->canvas); _minpressure_adj->signal_value_changed().connect( @@ -99,8 +92,8 @@ PencilToolbar::PencilToolbar(SPDesktop *desktop, { auto maxpressure_val = prefs->getDouble("/tools/freehand/pencil/maxpressure", 30); _maxpressure_adj = Gtk::Adjustment::create(maxpressure_val, 0, 100, 1, 0); - _maxpressure = - Gtk::manage(new UI::Widget::SpinButtonToolItem("pencil-maxpressure", _("Max:"), _maxpressure_adj, 0, 0)); + _maxpressure = Gtk::manage( + new UI::Widget::SpinButtonToolItem("pencil-maxpressure", _("Max:"), _maxpressure_adj, 0, 0)); _maxpressure->set_tooltip_text(_("Max percent of pressure")); _maxpressure->set_focus_widget(desktop->canvas); _maxpressure_adj->signal_value_changed().connect( @@ -115,17 +108,18 @@ PencilToolbar::PencilToolbar(SPDesktop *desktop, /* Tolerance */ { - std::vector<Glib::ustring> labels = { _("(many nodes, rough)"), _("(default)"), "", "", "", "", - _("(few nodes, smooth)") }; - std::vector<double> values = { 1, 10, 20, 30, 50, 75, 100 }; + std::vector<Glib::ustring> labels = {_("(many nodes, rough)"), _("(default)"), "", "", "", "", + _("(few nodes, smooth)")}; + std::vector<double> values = {1, 10, 20, 30, 50, 75, 100}; auto tolerance_val = prefs->getDouble("/tools/freehand/pencil/tolerance", 3.0); _tolerance_adj = Gtk::Adjustment::create(tolerance_val, 0, 100.0, 0.5, 1.0); - auto tolerance_item = - Gtk::manage(new UI::Widget::SpinButtonToolItem("pencil-tolerance", _("Smoothing:"), _tolerance_adj, 1, 2)); + auto tolerance_item = Gtk::manage( + new UI::Widget::SpinButtonToolItem("pencil-tolerance", _("Smoothing:"), _tolerance_adj, 1, 2)); tolerance_item->set_tooltip_text(_("How much smoothing (simplifying) is applied to the line")); tolerance_item->set_custom_numeric_menu_data(values, labels); tolerance_item->set_focus_widget(desktop->canvas); - _tolerance_adj->signal_value_changed().connect(sigc::mem_fun(*this, &PencilToolbar::tolerance_value_changed)); + _tolerance_adj->signal_value_changed().connect( + sigc::mem_fun(*this, &PencilToolbar::tolerance_value_changed)); // ege_adjustment_action_set_appearance( eact, TOOLBAR_SLIDER_HINT ); add(*tolerance_item); } @@ -156,9 +150,8 @@ PencilToolbar::PencilToolbar(SPDesktop *desktop, show_all(); // Elements must be hidden after show_all() is called - guint freehandMode = prefs->getInt(( pencil_mode ? - "/tools/freehand/pencil/freehand-mode" : - "/tools/freehand/pen/freehand-mode" ), 0); + guint freehandMode = + prefs->getInt((pencil_mode ? "/tools/freehand/pencil/freehand-mode" : "/tools/freehand/pen/freehand-mode"), 0); if (freehandMode != 1 && freehandMode != 2) { _flatten_spiro_bspline->set_visible(false); } @@ -167,8 +160,7 @@ PencilToolbar::PencilToolbar(SPDesktop *desktop, } } -GtkWidget * -PencilToolbar::create_pencil(SPDesktop *desktop) +GtkWidget *PencilToolbar::create_pencil(SPDesktop *desktop) { auto toolbar = new PencilToolbar(desktop, true); return GTK_WIDGET(toolbar->gobj()); @@ -176,15 +168,14 @@ PencilToolbar::create_pencil(SPDesktop *desktop) PencilToolbar::~PencilToolbar() { - if(_repr) { + if (_repr) { _repr->removeListenerByData(this); GC::release(_repr); _repr = nullptr; } } -void -PencilToolbar::mode_changed(int mode) +void PencilToolbar::mode_changed(int mode) { auto prefs = Inkscape::Preferences::get(); prefs->setInt(freehand_tool_name() + "/freehand-mode", mode); @@ -209,16 +200,12 @@ PencilToolbar::mode_changed(int mode) } /* This is used in generic functions below to share large portions of code between pen and pencil tool */ -Glib::ustring const -PencilToolbar::freehand_tool_name() +Glib::ustring const PencilToolbar::freehand_tool_name() { - return ( tools_isactive(_desktop, TOOLS_FREEHAND_PEN) - ? "/tools/freehand/pen" - : "/tools/freehand/pencil" ); + return (tools_isactive(_desktop, TOOLS_FREEHAND_PEN) ? "/tools/freehand/pen" : "/tools/freehand/pencil"); } -void -PencilToolbar::add_freehand_mode_toggle(bool tool_is_pencil) +void PencilToolbar::add_freehand_mode_toggle(bool tool_is_pencil) { auto label = Gtk::manage(new UI::Widget::LabelToolItem(_("Mode:"))); label->set_tooltip_text(_("Mode of new lines drawn by this tool")); @@ -261,7 +248,7 @@ PencilToolbar::add_freehand_mode_toggle(bool tool_is_pencil) auto prefs = Inkscape::Preferences::get(); - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* LPE bspline spiro flatten */ _flatten_spiro_bspline = Gtk::manage(new Gtk::ToolButton(_("Flatten Spiro or BSpline LPE"))); @@ -270,16 +257,14 @@ PencilToolbar::add_freehand_mode_toggle(bool tool_is_pencil) _flatten_spiro_bspline->signal_clicked().connect(sigc::mem_fun(*this, &PencilToolbar::flatten_spiro_bspline)); add(*_flatten_spiro_bspline); - guint freehandMode = prefs->getInt(( tool_is_pencil ? - "/tools/freehand/pencil/freehand-mode" : - "/tools/freehand/pen/freehand-mode" ), 0); + guint freehandMode = prefs->getInt( + (tool_is_pencil ? "/tools/freehand/pencil/freehand-mode" : "/tools/freehand/pen/freehand-mode"), 0); // freehandMode range is (0,5] for the pen tool, (0,3] for the pencil tool // freehandMode = 3 is an old way of signifying pressure, set it to 0. _mode_buttons[(freehandMode < _mode_buttons.size()) ? freehandMode : 0]->set_active(); } -void -PencilToolbar::minpressure_value_changed() +void PencilToolbar::minpressure_value_changed() { // quit if run by the attr_changed listener if (_freeze) { @@ -287,11 +272,10 @@ PencilToolbar::minpressure_value_changed() } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/freehand/pencil/minpressure", _minpressure_adj->get_value()); + prefs->setDouble("/tools/freehand/pencil/minpressure", _minpressure_adj->get_value()); } -void -PencilToolbar::maxpressure_value_changed() +void PencilToolbar::maxpressure_value_changed() { // quit if run by the attr_changed listener if (_freeze) { @@ -299,11 +283,11 @@ PencilToolbar::maxpressure_value_changed() } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/freehand/pencil/maxpressure", _maxpressure_adj->get_value()); + prefs->setDouble("/tools/freehand/pencil/maxpressure", _maxpressure_adj->get_value()); } -void -PencilToolbar::use_pencil_pressure() { +void PencilToolbar::use_pencil_pressure() +{ // assumes called by pencil toolbar (and all these widgets exist) bool pressure = _pressure_item->get_active(); auto prefs = Inkscape::Preferences::get(); @@ -338,45 +322,41 @@ PencilToolbar::use_pencil_pressure() { } } -void -PencilToolbar::add_advanced_shape_options(bool tool_is_pencil) +void PencilToolbar::add_advanced_shape_options(bool tool_is_pencil) { /*advanced shape options */ UI::Widget::ComboToolItemColumns columns; Glib::RefPtr<Gtk::ListStore> store = Gtk::ListStore::create(columns); - std::vector<gchar*> freehand_shape_dropdown_items_list = { - const_cast<gchar *>(C_("Freehand shape", "None")), - _("Triangle in"), - _("Triangle out"), - _("Ellipse"), - _("From clipboard"), - _("Bend from clipboard"), - _("Last applied") - }; - - for (auto item:freehand_shape_dropdown_items_list) { + std::vector<gchar *> freehand_shape_dropdown_items_list = {const_cast<gchar *>(C_("Freehand shape", "None")), + _("Triangle in"), + _("Triangle out"), + _("Ellipse"), + _("From clipboard"), + _("Bend from clipboard"), + _("Last applied")}; + + for (auto item : freehand_shape_dropdown_items_list) { Gtk::TreeModel::Row row = *(store->append()); - row[columns.col_label ] = item; + row[columns.col_label] = item; row[columns.col_sensitive] = true; } - _shape_item = Gtk::manage(UI::Widget::ComboToolItem::create(_("Shape"), _("Shape of new paths drawn by this tool"), "Not Used", store)); + _shape_item = Gtk::manage( + UI::Widget::ComboToolItem::create(_("Shape"), _("Shape of new paths drawn by this tool"), "Not Used", store)); _shape_item->use_group_label(true); auto prefs = Inkscape::Preferences::get(); - int shape = prefs->getInt((tool_is_pencil ? - "/tools/freehand/pencil/shape" : - "/tools/freehand/pen/shape" ), 0); + int shape = prefs->getInt((tool_is_pencil ? "/tools/freehand/pencil/shape" : "/tools/freehand/pen/shape"), 0); _shape_item->set_active(shape); _shape_item->signal_changed().connect(sigc::mem_fun(*this, &PencilToolbar::change_shape)); add(*_shape_item); } -void -PencilToolbar::change_shape(int shape) { +void PencilToolbar::change_shape(int shape) +{ auto prefs = Inkscape::Preferences::get(); prefs->setInt(freehand_tool_name() + "/shape", shape); } @@ -388,15 +368,16 @@ void PencilToolbar::add_powerstroke_cap(bool tool_is_pencil) Glib::RefPtr<Gtk::ListStore> store = Gtk::ListStore::create(columns); - std::vector<gchar *> powerstroke_cap_items_list = { const_cast<gchar *>(C_("Cap", "Butt")), _("Square"), _("Round"), - _("Peak"), _("Zero width") }; + std::vector<gchar *> powerstroke_cap_items_list = {const_cast<gchar *>(C_("Cap", "Butt")), _("Square"), _("Round"), + _("Peak"), _("Zero width")}; for (auto item : powerstroke_cap_items_list) { Gtk::TreeModel::Row row = *(store->append()); row[columns.col_label] = item; row[columns.col_sensitive] = true; } - _cap_item = Gtk::manage(UI::Widget::ComboToolItem::create(_("Caps"), _("Line endings when drawing with pressure-sensitive PowerPencil"), "Not Used", store)); + _cap_item = Gtk::manage(UI::Widget::ComboToolItem::create( + _("Caps"), _("Line endings when drawing with pressure-sensitive PowerPencil"), "Not Used", store)); auto prefs = Inkscape::Preferences::get(); @@ -415,8 +396,7 @@ void PencilToolbar::change_cap(int cap) prefs->setInt("/live_effects/powerstroke/powerpencilcap", cap); } -void -PencilToolbar::simplify_lpe() +void PencilToolbar::simplify_lpe() { bool simplify = _simplify->get_active(); auto prefs = Inkscape::Preferences::get(); @@ -424,14 +404,13 @@ PencilToolbar::simplify_lpe() _flatten_simplify->set_visible(simplify); } -void -PencilToolbar::simplify_flatten() +void PencilToolbar::simplify_flatten() { auto selected = _desktop->getSelection()->items(); - SPLPEItem* lpeitem = nullptr; - for (auto it(selected.begin()); it != selected.end(); ++it){ - lpeitem = dynamic_cast<SPLPEItem*>(*it); - if (lpeitem && lpeitem->hasPathEffect()){ + SPLPEItem *lpeitem = nullptr; + for (auto it(selected.begin()); it != selected.end(); ++it) { + lpeitem = dynamic_cast<SPLPEItem *>(*it); + if (lpeitem && lpeitem->hasPathEffect()) { PathEffectList lpelist = lpeitem->getEffectList(); PathEffectList::iterator i; for (i = lpelist.begin(); i != lpelist.end(); ++i) { @@ -439,12 +418,12 @@ PencilToolbar::simplify_flatten() if (lpeobj) { Inkscape::LivePathEffect::Effect *lpe = lpeobj->get_lpe(); if (dynamic_cast<Inkscape::LivePathEffect::LPESimplify *>(lpe)) { - SPShape * shape = dynamic_cast<SPShape *>(lpeitem); - if(shape){ + SPShape *shape = dynamic_cast<SPShape *>(lpeitem); + if (shape) { auto c = SPCurve::copy(shape->curveForEdit()); lpe->doEffect(c.get()); lpeitem->setCurrentPathEffect(*i); - if (lpelist.size() > 1){ + if (lpelist.size() > 1) { lpeitem->removeCurrentPathEffect(true); shape->setCurveBeforeLPE(std::move(c)); } else { @@ -465,30 +444,28 @@ PencilToolbar::simplify_flatten() } } -void -PencilToolbar::flatten_spiro_bspline() +void PencilToolbar::flatten_spiro_bspline() { auto selected = _desktop->getSelection()->items(); - SPLPEItem* lpeitem = nullptr; + SPLPEItem *lpeitem = nullptr; - for (auto it(selected.begin()); it != selected.end(); ++it){ - lpeitem = dynamic_cast<SPLPEItem*>(*it); - if (lpeitem && lpeitem->hasPathEffect()){ + for (auto it(selected.begin()); it != selected.end(); ++it) { + lpeitem = dynamic_cast<SPLPEItem *>(*it); + if (lpeitem && lpeitem->hasPathEffect()) { PathEffectList lpelist = lpeitem->getEffectList(); PathEffectList::iterator i; for (i = lpelist.begin(); i != lpelist.end(); ++i) { LivePathEffectObject *lpeobj = (*i)->lpeobject; if (lpeobj) { Inkscape::LivePathEffect::Effect *lpe = lpeobj->get_lpe(); - if (dynamic_cast<Inkscape::LivePathEffect::LPEBSpline *>(lpe) || - dynamic_cast<Inkscape::LivePathEffect::LPESpiro *>(lpe)) - { - SPShape * shape = dynamic_cast<SPShape *>(lpeitem); - if(shape){ + if (dynamic_cast<Inkscape::LivePathEffect::LPEBSpline *>(lpe) || + dynamic_cast<Inkscape::LivePathEffect::LPESpiro *>(lpe)) { + SPShape *shape = dynamic_cast<SPShape *>(lpeitem); + if (shape) { auto c = SPCurve::copy(shape->curveForEdit()); lpe->doEffect(c.get()); lpeitem->setCurrentPathEffect(*i); - if (lpelist.size() > 1){ + if (lpelist.size() > 1) { lpeitem->removeCurrentPathEffect(true); shape->setCurveBeforeLPE(std::move(c)); } else { @@ -509,15 +486,13 @@ PencilToolbar::flatten_spiro_bspline() } } -GtkWidget * -PencilToolbar::create_pen(SPDesktop *desktop) +GtkWidget *PencilToolbar::create_pen(SPDesktop *desktop) { auto toolbar = new PencilToolbar(desktop, false); return GTK_WIDGET(toolbar->gobj()); } -void -PencilToolbar::tolerance_value_changed() +void PencilToolbar::tolerance_value_changed() { // quit if run by the attr_changed listener if (_freeze) { @@ -527,26 +502,30 @@ PencilToolbar::tolerance_value_changed() // in turn, prevent listener from responding Inkscape::Preferences *prefs = Inkscape::Preferences::get(); _freeze = true; - prefs->setDouble("/tools/freehand/pencil/tolerance", - _tolerance_adj->get_value()); + prefs->setDouble("/tools/freehand/pencil/tolerance", _tolerance_adj->get_value()); _freeze = false; auto selected = _desktop->getSelection()->items(); - for (auto it(selected.begin()); it != selected.end(); ++it){ - SPLPEItem* lpeitem = dynamic_cast<SPLPEItem*>(*it); - if (lpeitem && lpeitem->hasPathEffect()){ - Inkscape::LivePathEffect::Effect* simplify = lpeitem->getPathEffectOfType(Inkscape::LivePathEffect::SIMPLIFY); - if(simplify){ - Inkscape::LivePathEffect::LPESimplify *lpe_simplify = dynamic_cast<Inkscape::LivePathEffect::LPESimplify*>(simplify->getLPEObj()->get_lpe()); + for (auto it(selected.begin()); it != selected.end(); ++it) { + SPLPEItem *lpeitem = dynamic_cast<SPLPEItem *>(*it); + if (lpeitem && lpeitem->hasPathEffect()) { + Inkscape::LivePathEffect::Effect *simplify = + lpeitem->getPathEffectOfType(Inkscape::LivePathEffect::SIMPLIFY); + if (simplify) { + Inkscape::LivePathEffect::LPESimplify *lpe_simplify = + dynamic_cast<Inkscape::LivePathEffect::LPESimplify *>(simplify->getLPEObj()->get_lpe()); if (lpe_simplify) { double tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0); - tol = tol/(100.0*(102.0-tol)); + tol = tol / (100.0 * (102.0 - tol)); std::ostringstream ss; ss << tol; - Inkscape::LivePathEffect::Effect* powerstroke = lpeitem->getPathEffectOfType(Inkscape::LivePathEffect::POWERSTROKE); + Inkscape::LivePathEffect::Effect *powerstroke = + lpeitem->getPathEffectOfType(Inkscape::LivePathEffect::POWERSTROKE); bool simplified = false; - if(powerstroke){ - Inkscape::LivePathEffect::LPEPowerStroke *lpe_powerstroke = dynamic_cast<Inkscape::LivePathEffect::LPEPowerStroke*>(powerstroke->getLPEObj()->get_lpe()); - if(lpe_powerstroke){ + if (powerstroke) { + Inkscape::LivePathEffect::LPEPowerStroke *lpe_powerstroke = + dynamic_cast<Inkscape::LivePathEffect::LPEPowerStroke *>( + powerstroke->getLPEObj()->get_lpe()); + if (lpe_powerstroke) { lpe_powerstroke->getRepr()->setAttribute("is_visible", "false"); sp_lpe_item_update_patheffect(lpeitem, false, false); SPShape *sp_shape = dynamic_cast<SPShape *>(lpeitem); @@ -557,8 +536,8 @@ PencilToolbar::tolerance_value_changed() simplified = true; guint curve_length = sp_shape->curve()->get_segment_count(); std::vector<Geom::Point> ts = lpe_powerstroke->offset_points.data(); - double factor = (double)curve_length/ (double)previous_curve_length; - for (auto & t : ts) { + double factor = (double)curve_length / (double)previous_curve_length; + for (auto &t : ts) { t[Geom::X] = t[Geom::X] * factor; } lpe_powerstroke->offset_points.param_setValue(ts); @@ -567,7 +546,7 @@ PencilToolbar::tolerance_value_changed() sp_lpe_item_update_patheffect(lpeitem, false, false); } } - if(!simplified){ + if (!simplified) { lpe_simplify->getRepr()->setAttribute("threshold", ss.str()); } } @@ -576,9 +555,9 @@ PencilToolbar::tolerance_value_changed() } } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: mode:c++ diff --git a/src/ui/toolbar/pencil-toolbar.h b/src/ui/toolbar/pencil-toolbar.h index 631b3dfc98adc74684438074629571a7c444bba7..1986731d1f6ac2188c58845d71f1b003b4413e7f 100644 --- a/src/ui/toolbar/pencil-toolbar.h +++ b/src/ui/toolbar/pencil-toolbar.h @@ -28,18 +28,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> #include <vector> +#include "toolbar.h" + class SPDesktop; namespace Gtk { class RadioToolButton; class ToggleToolButton; class ToolButton; -} +} // namespace Gtk namespace Inkscape { namespace XML { @@ -50,10 +50,11 @@ namespace UI { namespace Widget { class SpinButtonToolItem; class ComboToolItem; -} +} // namespace Widget namespace Toolbar { -class PencilToolbar : public Toolbar { +class PencilToolbar : public Toolbar +{ private: std::vector<Gtk::RadioToolButton *> _mode_buttons; @@ -92,15 +93,15 @@ private: void flatten_spiro_bspline(); protected: - PencilToolbar(SPDesktop *desktop, bool pencil_mode); - ~PencilToolbar() override; + PencilToolbar(SPDesktop *desktop, bool pencil_mode); + ~PencilToolbar() override; public: - static GtkWidget * create_pencil(SPDesktop *desktop); - static GtkWidget * create_pen(SPDesktop *desktop); + static GtkWidget *create_pencil(SPDesktop *desktop); + static GtkWidget *create_pen(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_PENCIL_TOOLBAR_H */ diff --git a/src/ui/toolbar/rect-toolbar.cpp b/src/ui/toolbar/rect-toolbar.cpp index 461935a7f7ea400d84f0558b30348119b19db324..90d4ea701092b869c7332b87db4b9892b56343e2 100644 --- a/src/ui/toolbar/rect-toolbar.cpp +++ b/src/ui/toolbar/rect-toolbar.cpp @@ -28,18 +28,14 @@ #include "rect-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/separatortoolitem.h> #include <gtkmm/toolbutton.h> #include "desktop.h" #include "document-undo.h" -#include "selection.h" -#include "verbs.h" - #include "object/sp-namedview.h" #include "object/sp-rect.h" - +#include "selection.h" #include "ui/icon-names.h" #include "ui/tools/rect-tool.h" #include "ui/uxmanager.h" @@ -48,24 +44,22 @@ #include "ui/widget/label-tool-item.h" #include "ui/widget/spin-button-tool-item.h" #include "ui/widget/unit-tracker.h" - +#include "verbs.h" #include "widgets/widget-sizes.h" - #include "xml/node-event-vector.h" -using Inkscape::UI::Widget::UnitTracker; -using Inkscape::UI::UXManager; using Inkscape::DocumentUndo; -using Inkscape::Util::Unit; +using Inkscape::UI::UXManager; +using Inkscape::UI::Widget::UnitTracker; using Inkscape::Util::Quantity; +using Inkscape::Util::Unit; using Inkscape::Util::unit_table; static Inkscape::XML::NodeEventVector rect_tb_repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - Inkscape::UI::Toolbar::RectToolbar::event_attr_changed, - nullptr, /* content_changed */ - nullptr /* order_changed */ + nullptr, /* child_added */ + nullptr, /* child_removed */ + Inkscape::UI::Toolbar::RectToolbar::event_attr_changed, nullptr, /* content_changed */ + nullptr /* order_changed */ }; namespace Inkscape { @@ -73,17 +67,17 @@ namespace UI { namespace Toolbar { RectToolbar::RectToolbar(SPDesktop *desktop) - : Toolbar(desktop), - _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)), - _freeze(false), - _single(true), - _repr(nullptr), - _mode_item(Gtk::manage(new UI::Widget::LabelToolItem(_("<b>New:</b>")))) + : Toolbar(desktop) + , _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)) + , _freeze(false) + , _single(true) + , _repr(nullptr) + , _mode_item(Gtk::manage(new UI::Widget::LabelToolItem(_("<b>New:</b>")))) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); // rx/ry units menu: create - //tracker->addUnit( SP_UNIT_PERCENT, 0 ); + // tracker->addUnit( SP_UNIT_PERCENT, 0 ); // fixme: add % meaning per cent of the width/height _tracker->setActiveUnit(desktop->getNamedView()->display_units); _mode_item->set_use_markup(true); @@ -95,11 +89,9 @@ RectToolbar::RectToolbar(SPDesktop *desktop) _width_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("rect-width", _("W:"), _width_adj)); _width_item->set_focus_widget(_desktop->canvas); _width_item->set_all_tooltip_text(_("Width of rectangle")); - + _width_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &RectToolbar::value_changed), - _width_adj, - "width", - &SPRect::setVisibleWidth)); + _width_adj, "width", &SPRect::setVisibleWidth)); _tracker->addAdjustment(_width_adj->gobj()); _width_item->set_sensitive(false); @@ -113,12 +105,10 @@ RectToolbar::RectToolbar(SPDesktop *desktop) _height_adj = Gtk::Adjustment::create(height_val, 0, 1e6, SPIN_STEP, SPIN_PAGE_STEP); _height_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &RectToolbar::value_changed), - _height_adj, - "height", - &SPRect::setVisibleHeight)); + _height_adj, "height", &SPRect::setVisibleHeight)); _tracker->addAdjustment(_height_adj->gobj()); - std::vector<double> values = { 1, 2, 3, 5, 10, 20, 50, 100, 200, 500}; + std::vector<double> values = {1, 2, 3, 5, 10, 20, 50, 100, 200, 500}; _height_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("rect-height", _("H:"), _height_adj)); _height_item->set_custom_numeric_menu_data(values); _height_item->set_all_tooltip_text(_("Height of rectangle")); @@ -128,14 +118,12 @@ RectToolbar::RectToolbar(SPDesktop *desktop) /* rx */ { - std::vector<Glib::ustring> labels = {_("not rounded"), "", "", "", "", "", "", "", ""}; - std::vector<double> values = { 0.5, 1, 2, 3, 5, 10, 20, 50, 100}; + std::vector<Glib::ustring> labels = {_("not rounded"), "", "", "", "", "", "", "", ""}; + std::vector<double> values = {0.5, 1, 2, 3, 5, 10, 20, 50, 100}; auto rx_val = prefs->getDouble("/tools/shapes/rect/rx", 0); _rx_adj = Gtk::Adjustment::create(rx_val, 0, 1e6, SPIN_STEP, SPIN_PAGE_STEP); - _rx_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &RectToolbar::value_changed), - _rx_adj, - "rx", - &SPRect::setVisibleRx)); + _rx_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &RectToolbar::value_changed), _rx_adj, "rx", &SPRect::setVisibleRx)); _tracker->addAdjustment(_rx_adj->gobj()); _rx_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("rect-rx", _("Rx:"), _rx_adj)); _rx_item->set_all_tooltip_text(_("Horizontal radius of rounded corners")); @@ -145,14 +133,12 @@ RectToolbar::RectToolbar(SPDesktop *desktop) /* ry */ { - std::vector<Glib::ustring> labels = {_("not rounded"), "", "", "", "", "", "", "", ""}; - std::vector<double> values = { 0.5, 1, 2, 3, 5, 10, 20, 50, 100}; + std::vector<Glib::ustring> labels = {_("not rounded"), "", "", "", "", "", "", "", ""}; + std::vector<double> values = {0.5, 1, 2, 3, 5, 10, 20, 50, 100}; auto ry_val = prefs->getDouble("/tools/shapes/rect/ry", 0); _ry_adj = Gtk::Adjustment::create(ry_val, 0, 1e6, SPIN_STEP, SPIN_PAGE_STEP); - _ry_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &RectToolbar::value_changed), - _ry_adj, - "ry", - &SPRect::setVisibleRy)); + _ry_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &RectToolbar::value_changed), _ry_adj, "ry", &SPRect::setVisibleRy)); _tracker->addAdjustment(_ry_adj->gobj()); _ry_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("rect-ry", _("Ry:"), _ry_adj)); _ry_item->set_all_tooltip_text(_("Vertical radius of rounded corners")); @@ -178,10 +164,10 @@ RectToolbar::RectToolbar(SPDesktop *desktop) add(*_rx_item); add(*_ry_item); add(*unit_menu_ti); - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); add(*_not_rounded); show_all(); - + sensitivize(); _desktop->connectEventContextChanged(sigc::mem_fun(*this, &RectToolbar::watch_ec)); @@ -196,17 +182,14 @@ RectToolbar::~RectToolbar() } } -GtkWidget * -RectToolbar::create(SPDesktop *desktop) +GtkWidget *RectToolbar::create(SPDesktop *desktop) { auto toolbar = new RectToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -RectToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, - gchar const *value_name, - void (SPRect::*setter)(gdouble)) +void RectToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, gchar const *value_name, + void (SPRect::*setter)(gdouble)) { Unit const *unit = _tracker->getActiveUnit(); g_return_if_fail(unit != nullptr); @@ -214,7 +197,7 @@ RectToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble(Glib::ustring("/tools/shapes/rect/") + value_name, - Quantity::convert(adj->get_value(), unit, "px")); + Quantity::convert(adj->get_value(), unit, "px")); } // quit if run by the attr_changed listener @@ -227,8 +210,8 @@ RectToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, bool modmade = false; Inkscape::Selection *selection = _desktop->getSelection(); - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { if (SP_IS_RECT(*i)) { if (adj->get_value() != 0) { (SP_RECT(*i)->*setter)(Quantity::convert(adj->get_value(), unit, "px")); @@ -242,25 +225,23 @@ RectToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, sensitivize(); if (modmade) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_RECT, - _("Change rectangle")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_RECT, _("Change rectangle")); } _freeze = false; } -void -RectToolbar::sensitivize() +void RectToolbar::sensitivize() { - if (_rx_adj->get_value() == 0 && _ry_adj->get_value() == 0 && _single) { // only for a single selected rect (for now) + if (_rx_adj->get_value() == 0 && _ry_adj->get_value() == 0 && _single) { // only for a single selected rect (for + // now) _not_rounded->set_sensitive(false); } else { _not_rounded->set_sensitive(true); } } -void -RectToolbar::defaults() +void RectToolbar::defaults() { _rx_adj->set_value(0.0); _ry_adj->set_value(0.0); @@ -268,8 +249,7 @@ RectToolbar::defaults() sensitivize(); } -void -RectToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) +void RectToolbar::watch_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec) { static sigc::connection changed; @@ -285,7 +265,7 @@ RectToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) } else { if (changed) { changed.disconnect(); - + if (_repr) { // remove old listener _repr->removeListenerByData(this); Inkscape::GC::release(_repr); @@ -298,8 +278,7 @@ RectToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) /** * \param selection should not be NULL. */ -void -RectToolbar::selection_changed(Inkscape::Selection *selection) +void RectToolbar::selection_changed(Inkscape::Selection *selection) { int n_selected = 0; Inkscape::XML::Node *repr = nullptr; @@ -312,8 +291,8 @@ RectToolbar::selection_changed(Inkscape::Selection *selection) _repr = nullptr; } - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { if (SP_IS_RECT(*i)) { n_selected++; item = *i; @@ -342,17 +321,17 @@ RectToolbar::selection_changed(Inkscape::Selection *selection) } } else { // FIXME: implement averaging of all parameters for multiple selected - //gtk_label_set_markup(GTK_LABEL(l), _("<b>Average:</b>")); + // gtk_label_set_markup(GTK_LABEL(l), _("<b>Average:</b>")); _mode_item->set_markup(_("<b>Change:</b>")); sensitivize(); } } void RectToolbar::event_attr_changed(Inkscape::XML::Node * /*repr*/, gchar const * /*name*/, - gchar const * /*old_value*/, gchar const * /*new_value*/, - bool /*is_interactive*/, gpointer data) + gchar const * /*old_value*/, gchar const * /*new_value*/, bool /*is_interactive*/, + gpointer data) { - auto toolbar = reinterpret_cast<RectToolbar*>(data); + auto toolbar = reinterpret_cast<RectToolbar *>(data); // quit if run by the _changed callbacks if (toolbar->_freeze) { @@ -391,10 +370,9 @@ void RectToolbar::event_attr_changed(Inkscape::XML::Node * /*repr*/, gchar const toolbar->_freeze = false; } -} -} -} - +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/rect-toolbar.h b/src/ui/toolbar/rect-toolbar.h index 58d4b2c1c6119d57e1935ea2cbf3ab983aedb5f8..1a2a6fad4b8611160ae238314914b8d8916b8faf 100644 --- a/src/ui/toolbar/rect-toolbar.h +++ b/src/ui/toolbar/rect-toolbar.h @@ -28,10 +28,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; class SPItem; class SPRect; @@ -56,17 +56,18 @@ namespace Widget { class LabelToolItem; class SpinButtonToolItem; class UnitTracker; -} +} // namespace Widget namespace Toolbar { -class RectToolbar : public Toolbar { +class RectToolbar : public Toolbar +{ private: UI::Widget::UnitTracker *_tracker; XML::Node *_repr; SPItem *_item; - UI::Widget::LabelToolItem *_mode_item; + UI::Widget::LabelToolItem *_mode_item; UI::Widget::SpinButtonToolItem *_width_item; UI::Widget::SpinButtonToolItem *_height_item; UI::Widget::SpinButtonToolItem *_rx_item; @@ -81,13 +82,11 @@ private: bool _freeze; bool _single; - void value_changed(Glib::RefPtr<Gtk::Adjustment>& adj, - gchar const *value_name, - void (SPRect::*setter)(gdouble)); + void value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, gchar const *value_name, void (SPRect::*setter)(gdouble)); void sensitivize(); void defaults(); - void watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec); + void watch_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec); void selection_changed(Inkscape::Selection *selection); protected: @@ -95,19 +94,14 @@ protected: ~RectToolbar() override; public: - static GtkWidget * create(SPDesktop *desktop); - - static void event_attr_changed(Inkscape::XML::Node *repr, - gchar const *name, - gchar const *old_value, - gchar const *new_value, - bool is_interactive, - gpointer data); + static GtkWidget *create(SPDesktop *desktop); + static void event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, gchar const *old_value, + gchar const *new_value, bool is_interactive, gpointer data); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_RECT_TOOLBAR_H */ diff --git a/src/ui/toolbar/select-toolbar.cpp b/src/ui/toolbar/select-toolbar.cpp index 7330ebf3dba5c659e3e4a6ecf177dbfe5ce9bd42..1f1fc9b847f3f1bd2dd0dc8188b8dec34e83562c 100644 --- a/src/ui/toolbar/select-toolbar.cpp +++ b/src/ui/toolbar/select-toolbar.cpp @@ -15,92 +15,86 @@ #include "select-toolbar.h" +#include <2geom/rect.h> #include <glibmm/i18n.h> - #include <gtkmm/adjustment.h> #include <gtkmm/separatortoolitem.h> -#include <2geom/rect.h> - #include "desktop.h" #include "document-undo.h" #include "document.h" -#include "selection.h" #include "message-stack.h" -#include "selection-chemistry.h" -#include "verbs.h" - - #include "object/sp-item-transform.h" #include "object/sp-namedview.h" - +#include "selection-chemistry.h" +#include "selection.h" #include "ui/icon-names.h" #include "ui/widget/canvas.h" // Focus widget #include "ui/widget/combo-tool-item.h" #include "ui/widget/spin-button-tool-item.h" #include "ui/widget/unit-tracker.h" - +#include "verbs.h" #include "widgets/widget-sizes.h" +using Inkscape::DocumentUndo; using Inkscape::UI::Widget::UnitTracker; -using Inkscape::Util::Unit; using Inkscape::Util::Quantity; -using Inkscape::DocumentUndo; +using Inkscape::Util::Unit; using Inkscape::Util::unit_table; namespace Inkscape { namespace UI { namespace Toolbar { -SelectToolbar::SelectToolbar(SPDesktop *desktop) : - Toolbar(desktop), - _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)), - _update(false), - _lock_btn(Gtk::manage(new Gtk::ToggleToolButton())), - _transform_stroke_btn(Gtk::manage(new Gtk::ToggleToolButton())), - _transform_corners_btn(Gtk::manage(new Gtk::ToggleToolButton())), - _transform_gradient_btn(Gtk::manage(new Gtk::ToggleToolButton())), - _transform_pattern_btn(Gtk::manage(new Gtk::ToggleToolButton())) +SelectToolbar::SelectToolbar(SPDesktop *desktop) + : Toolbar(desktop) + , _tracker(new UnitTracker(Inkscape::Util::UNIT_TYPE_LINEAR)) + , _update(false) + , _lock_btn(Gtk::manage(new Gtk::ToggleToolButton())) + , _transform_stroke_btn(Gtk::manage(new Gtk::ToggleToolButton())) + , _transform_corners_btn(Gtk::manage(new Gtk::ToggleToolButton())) + , _transform_gradient_btn(Gtk::manage(new Gtk::ToggleToolButton())) + , _transform_pattern_btn(Gtk::manage(new Gtk::ToggleToolButton())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); add_toolbutton_for_verb(SP_VERB_EDIT_SELECT_ALL); add_toolbutton_for_verb(SP_VERB_EDIT_SELECT_ALL_IN_ALL_LAYERS); - auto deselect_button = add_toolbutton_for_verb(SP_VERB_EDIT_DESELECT); + auto deselect_button = add_toolbutton_for_verb(SP_VERB_EDIT_DESELECT); _context_items.push_back(deselect_button); - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); - auto object_rotate_90_ccw_button = add_toolbutton_for_verb(SP_VERB_OBJECT_ROTATE_90_CCW); + auto object_rotate_90_ccw_button = add_toolbutton_for_verb(SP_VERB_OBJECT_ROTATE_90_CCW); _context_items.push_back(object_rotate_90_ccw_button); - auto object_rotate_90_cw_button = add_toolbutton_for_verb(SP_VERB_OBJECT_ROTATE_90_CW); + auto object_rotate_90_cw_button = add_toolbutton_for_verb(SP_VERB_OBJECT_ROTATE_90_CW); _context_items.push_back(object_rotate_90_cw_button); - auto object_flip_horizontal_button = add_toolbutton_for_verb(SP_VERB_OBJECT_FLIP_HORIZONTAL); + auto object_flip_horizontal_button = add_toolbutton_for_verb(SP_VERB_OBJECT_FLIP_HORIZONTAL); _context_items.push_back(object_flip_horizontal_button); - auto object_flip_vertical_button = add_toolbutton_for_verb(SP_VERB_OBJECT_FLIP_VERTICAL); + auto object_flip_vertical_button = add_toolbutton_for_verb(SP_VERB_OBJECT_FLIP_VERTICAL); _context_items.push_back(object_flip_vertical_button); - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); - auto selection_to_back_button = add_toolbutton_for_verb(SP_VERB_SELECTION_TO_BACK); + auto selection_to_back_button = add_toolbutton_for_verb(SP_VERB_SELECTION_TO_BACK); _context_items.push_back(selection_to_back_button); - auto selection_lower_button = add_toolbutton_for_verb(SP_VERB_SELECTION_LOWER); + auto selection_lower_button = add_toolbutton_for_verb(SP_VERB_SELECTION_LOWER); _context_items.push_back(selection_lower_button); - auto selection_raise_button = add_toolbutton_for_verb(SP_VERB_SELECTION_RAISE); + auto selection_raise_button = add_toolbutton_for_verb(SP_VERB_SELECTION_RAISE); _context_items.push_back(selection_raise_button); - auto selection_to_front_button = add_toolbutton_for_verb(SP_VERB_SELECTION_TO_FRONT); + auto selection_to_front_button = add_toolbutton_for_verb(SP_VERB_SELECTION_TO_FRONT); _context_items.push_back(selection_to_front_button); - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); _tracker->addUnit(unit_table.getUnit("%")); - _tracker->setActiveUnit( desktop->getNamedView()->display_units ); + _tracker->setActiveUnit(desktop->getNamedView()->display_units); // x-value control auto x_val = prefs->getDouble("/tools/select/X", 0.0); @@ -108,10 +102,8 @@ SelectToolbar::SelectToolbar(SPDesktop *desktop) : _adj_x->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &SelectToolbar::any_value_changed), _adj_x)); _tracker->addAdjustment(_adj_x->gobj()); - auto x_btn = Gtk::manage(new UI::Widget::SpinButtonToolItem("select-x", - C_("Select toolbar", "X:"), - _adj_x, - SPIN_STEP, 3)); + auto x_btn = + Gtk::manage(new UI::Widget::SpinButtonToolItem("select-x", C_("Select toolbar", "X:"), _adj_x, SPIN_STEP, 3)); x_btn->set_focus_widget(_desktop->getCanvas()); x_btn->set_all_tooltip_text(C_("Select toolbar", "Horizontal coordinate of selection")); _context_items.push_back(x_btn); @@ -123,10 +115,8 @@ SelectToolbar::SelectToolbar(SPDesktop *desktop) : _adj_y->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &SelectToolbar::any_value_changed), _adj_y)); _tracker->addAdjustment(_adj_y->gobj()); - auto y_btn = Gtk::manage(new UI::Widget::SpinButtonToolItem("select-y", - C_("Select toolbar", "Y:"), - _adj_y, - SPIN_STEP, 3)); + auto y_btn = + Gtk::manage(new UI::Widget::SpinButtonToolItem("select-y", C_("Select toolbar", "Y:"), _adj_y, SPIN_STEP, 3)); y_btn->set_focus_widget(_desktop->getCanvas()); y_btn->set_all_tooltip_text(C_("Select toolbar", "Vertical coordinate of selection")); _context_items.push_back(y_btn); @@ -138,10 +128,8 @@ SelectToolbar::SelectToolbar(SPDesktop *desktop) : _adj_w->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &SelectToolbar::any_value_changed), _adj_w)); _tracker->addAdjustment(_adj_w->gobj()); - auto w_btn = Gtk::manage(new UI::Widget::SpinButtonToolItem("select-width", - C_("Select toolbar", "W:"), - _adj_w, - SPIN_STEP, 3)); + auto w_btn = Gtk::manage( + new UI::Widget::SpinButtonToolItem("select-width", C_("Select toolbar", "W:"), _adj_w, SPIN_STEP, 3)); w_btn->set_focus_widget(_desktop->getCanvas()); w_btn->set_all_tooltip_text(C_("Select toolbar", "Width of selection")); _context_items.push_back(w_btn); @@ -160,20 +148,18 @@ SelectToolbar::SelectToolbar(SPDesktop *desktop) : _adj_h->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &SelectToolbar::any_value_changed), _adj_h)); _tracker->addAdjustment(_adj_h->gobj()); - auto h_btn = Gtk::manage(new UI::Widget::SpinButtonToolItem("select-height", - C_("Select toolbar", "H:"), - _adj_h, - SPIN_STEP, 3)); + auto h_btn = Gtk::manage( + new UI::Widget::SpinButtonToolItem("select-height", C_("Select toolbar", "H:"), _adj_h, SPIN_STEP, 3)); h_btn->set_focus_widget(_desktop->getCanvas()); h_btn->set_all_tooltip_text(C_("Select toolbar", "Height of selection")); _context_items.push_back(h_btn); add(*h_btn); // units menu - auto unit_menu = _tracker->create_tool_item(_("Units"), ("") ); + auto unit_menu = _tracker->create_tool_item(_("Units"), ("")); add(*unit_menu); - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); _transform_stroke_btn->set_label(_("Scale stroke width")); _transform_stroke_btn->set_tooltip_text(_("When scaling objects, scale the stroke width by the same proportion")); @@ -216,7 +202,7 @@ SelectToolbar::SelectToolbar(SPDesktop *desktop) : layout_widget_update(selection); for (auto item : _context_items) { - if ( item->is_sensitive() ) { + if (item->is_sensitive()) { item->set_sensitive(false); } } @@ -233,21 +219,19 @@ void SelectToolbar::on_unrealize() parent_type::on_unrealize(); } -GtkWidget * -SelectToolbar::create(SPDesktop *desktop) +GtkWidget *SelectToolbar::create(SPDesktop *desktop) { auto toolbar = new SelectToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -SelectToolbar::any_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj) +void SelectToolbar::any_value_changed(Glib::RefPtr<Gtk::Adjustment> &adj) { if (_update) { return; } - if ( !_tracker || _tracker->isUpdating() ) { + if (!_tracker || _tracker->isUpdating()) { /* * When only units are being changed, don't treat changes * to adjuster values as object changes. @@ -260,18 +244,17 @@ SelectToolbar::any_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj) Inkscape::Selection *selection = desktop->getSelection(); SPDocument *document = desktop->getDocument(); - document->ensureUpToDate (); + document->ensureUpToDate(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Geom::OptRect bbox_vis = selection->visualBounds(); Geom::OptRect bbox_geom = selection->geometricBounds(); int prefs_bbox = prefs->getInt("/tools/bounding_box"); - SPItem::BBoxType bbox_type = (prefs_bbox == 0)? - SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; + SPItem::BBoxType bbox_type = (prefs_bbox == 0) ? SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; Geom::OptRect bbox_user = selection->bounds(bbox_type); - if ( !bbox_user ) { + if (!bbox_user) { _update = false; return; } @@ -290,7 +273,8 @@ SelectToolbar::any_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj) y0 = Quantity::convert(_adj_y->get_value(), unit, "px"); x1 = x0 + Quantity::convert(_adj_w->get_value(), unit, "px"); xrel = Quantity::convert(_adj_w->get_value(), unit, "px") / bbox_user->dimensions()[Geom::X]; - y1 = y0 + Quantity::convert(_adj_h->get_value(), unit, "px");; + y1 = y0 + Quantity::convert(_adj_h->get_value(), unit, "px"); + ; yrel = Quantity::convert(_adj_h->get_value(), unit, "px") / bbox_user->dimensions()[Geom::Y]; } else { double const x0_propn = _adj_x->get_value() / 100 / unit->factor; @@ -304,7 +288,7 @@ SelectToolbar::any_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj) } // Keep proportions if lock is on - if ( _lock_btn->get_active() ) { + if (_lock_btn->get_active()) { if (adj == _adj_h) { x1 = x0 + yrel * bbox_user->dimensions()[Geom::X]; } else if (adj == _adj_w) { @@ -331,13 +315,13 @@ SelectToolbar::any_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj) // the value was changed by the user, the difference will be at least that much; otherwise it's // just rounding difference between the spinbox value and actual value, so no action is // performed - char const * const actionkey = ( mh > 5e-4 ? "selector:toolbar:move:horizontal" : - sh > 5e-4 ? "selector:toolbar:scale:horizontal" : - mv > 5e-4 ? "selector:toolbar:move:vertical" : - sv > 5e-4 ? "selector:toolbar:scale:vertical" : nullptr ); + char const *const actionkey = + (mh > 5e-4 ? "selector:toolbar:move:horizontal" + : sh > 5e-4 ? "selector:toolbar:scale:horizontal" + : mv > 5e-4 ? "selector:toolbar:move:vertical" + : sv > 5e-4 ? "selector:toolbar:scale:vertical" : nullptr); if (actionkey != nullptr) { - // FIXME: fix for GTK breakage, see comment in SelectedStyle::on_opacity_changed desktop->getCanvas()->forced_redraws_start(0); @@ -346,18 +330,18 @@ SelectToolbar::any_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj) Geom::Affine scaler; if (bbox_type == SPItem::VISUAL_BBOX) { - scaler = get_scale_transform_for_variable_stroke (*bbox_vis, *bbox_geom, transform_stroke, preserve, x0, y0, x1, y1); + scaler = get_scale_transform_for_variable_stroke(*bbox_vis, *bbox_geom, transform_stroke, preserve, x0, y0, + x1, y1); } else { // 1) We could have use the newer get_scale_transform_for_variable_stroke() here, but to avoid regressions // we'll just use the old get_scale_transform_for_uniform_stroke() for now. // 2) get_scale_transform_for_uniform_stroke() is intended for visual bounding boxes, not geometrical ones! // we'll trick it into using a geometric bounding box though, by setting the stroke width to zero - scaler = get_scale_transform_for_uniform_stroke (*bbox_geom, 0, 0, false, false, x0, y0, x1, y1); + scaler = get_scale_transform_for_uniform_stroke(*bbox_geom, 0, 0, false, false, x0, y0, x1, y1); } selection->applyAffine(scaler); - DocumentUndo::maybeDone(document, actionkey, SP_VERB_CONTEXT_SELECT, - _("Transform by toolbar")); + DocumentUndo::maybeDone(document, actionkey, SP_VERB_CONTEXT_SELECT, _("Transform by toolbar")); // resume interruptibility desktop->getCanvas()->forced_redraws_stop(); @@ -366,8 +350,7 @@ SelectToolbar::any_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj) _update = false; } -void -SelectToolbar::layout_widget_update(Inkscape::Selection *sel) +void SelectToolbar::layout_widget_update(Inkscape::Selection *sel) { if (_update) { return; @@ -378,21 +361,22 @@ SelectToolbar::layout_widget_update(Inkscape::Selection *sel) Inkscape::Preferences *prefs = Inkscape::Preferences::get(); using Geom::X; using Geom::Y; - if ( sel && !sel->isEmpty() ) { + if (sel && !sel->isEmpty()) { int prefs_bbox = prefs->getInt("/tools/bounding_box", 0); - SPItem::BBoxType bbox_type = (prefs_bbox ==0)? - SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; + SPItem::BBoxType bbox_type = (prefs_bbox == 0) ? SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; Geom::OptRect const bbox(sel->bounds(bbox_type)); - if ( bbox ) { + if (bbox) { Unit const *unit = _tracker->getActiveUnit(); g_return_if_fail(unit != nullptr); - struct { char const *key; double val; } const keyval[] = { - { "X", bbox->min()[X] }, - { "Y", bbox->min()[Y] }, - { "width", bbox->dimensions()[X] }, - { "height", bbox->dimensions()[Y] } - }; + struct + { + char const *key; + double val; + } const keyval[] = {{"X", bbox->min()[X]}, + {"Y", bbox->min()[Y]}, + {"width", bbox->dimensions()[X]}, + {"height", bbox->dimensions()[Y]}}; if (unit->type == Inkscape::Util::UNIT_TYPE_DIMENSIONLESS) { double const val = unit->factor * 100; @@ -400,10 +384,10 @@ SelectToolbar::layout_widget_update(Inkscape::Selection *sel) _adj_y->set_value(val); _adj_w->set_value(val); _adj_h->set_value(val); - _tracker->setFullVal( _adj_x->gobj(), keyval[0].val ); - _tracker->setFullVal( _adj_y->gobj(), keyval[1].val ); - _tracker->setFullVal( _adj_w->gobj(), keyval[2].val ); - _tracker->setFullVal( _adj_h->gobj(), keyval[3].val ); + _tracker->setFullVal(_adj_x->gobj(), keyval[0].val); + _tracker->setFullVal(_adj_y->gobj(), keyval[1].val); + _tracker->setFullVal(_adj_w->gobj(), keyval[2].val); + _tracker->setFullVal(_adj_h->gobj(), keyval[3].val); } else { _adj_x->set_value(Quantity::convert(keyval[0].val, "px", unit)); _adj_y->set_value(Quantity::convert(keyval[1].val, "px", unit)); @@ -416,27 +400,22 @@ SelectToolbar::layout_widget_update(Inkscape::Selection *sel) _update = false; } -void -SelectToolbar::on_inkscape_selection_modified(Inkscape::Selection *selection, guint flags) +void SelectToolbar::on_inkscape_selection_modified(Inkscape::Selection *selection, guint flags) { assert(_desktop->getSelection() == selection); - if ((flags & (SP_OBJECT_MODIFIED_FLAG | - SP_OBJECT_PARENT_MODIFIED_FLAG | - SP_OBJECT_CHILD_MODIFIED_FLAG ))) - { + if ((flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) { layout_widget_update(selection); } } -void -SelectToolbar::on_inkscape_selection_changed(Inkscape::Selection *selection) +void SelectToolbar::on_inkscape_selection_changed(Inkscape::Selection *selection) { assert(_desktop->getSelection() == selection); { bool setActive = (selection && !selection->isEmpty()); for (auto item : _context_items) { - if ( setActive != item->get_sensitive() ) { + if (setActive != item->get_sensitive()) { item->set_sensitive(setActive); } } @@ -445,70 +424,80 @@ SelectToolbar::on_inkscape_selection_changed(Inkscape::Selection *selection) } } -void -SelectToolbar::toggle_lock() { - if ( _lock_btn->get_active() ) { +void SelectToolbar::toggle_lock() +{ + if (_lock_btn->get_active()) { _lock_btn->set_icon_name(INKSCAPE_ICON("object-locked")); } else { _lock_btn->set_icon_name(INKSCAPE_ICON("object-unlocked")); } } -void -SelectToolbar::toggle_stroke() +void SelectToolbar::toggle_stroke() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool active = _transform_stroke_btn->get_active(); prefs->setBool("/options/transform/stroke", active); - if ( active ) { - _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Now <b>stroke width</b> is <b>scaled</b> when objects are scaled.")); + if (active) { + _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, + _("Now <b>stroke width</b> is <b>scaled</b> when objects are scaled.")); } else { - _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Now <b>stroke width</b> is <b>not scaled</b> when objects are scaled.")); + _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, + _("Now <b>stroke width</b> is <b>not scaled</b> when objects are scaled.")); } } -void -SelectToolbar::toggle_corners() +void SelectToolbar::toggle_corners() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool active = _transform_corners_btn->get_active(); prefs->setBool("/options/transform/rectcorners", active); - if ( active ) { - _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Now <b>rounded rectangle corners</b> are <b>scaled</b> when rectangles are scaled.")); + if (active) { + _desktop->messageStack()->flash( + Inkscape::INFORMATION_MESSAGE, + _("Now <b>rounded rectangle corners</b> are <b>scaled</b> when rectangles are scaled.")); } else { - _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Now <b>rounded rectangle corners</b> are <b>not scaled</b> when rectangles are scaled.")); + _desktop->messageStack()->flash( + Inkscape::INFORMATION_MESSAGE, + _("Now <b>rounded rectangle corners</b> are <b>not scaled</b> when rectangles are scaled.")); } } -void -SelectToolbar::toggle_gradient() +void SelectToolbar::toggle_gradient() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool active = _transform_gradient_btn->get_active(); prefs->setBool("/options/transform/gradient", active); - if ( active ) { - _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Now <b>gradients</b> are <b>transformed</b> along with their objects when those are transformed (moved, scaled, rotated, or skewed).")); + if (active) { + _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, + _("Now <b>gradients</b> are <b>transformed</b> along with their objects when " + "those are transformed (moved, scaled, rotated, or skewed).")); } else { - _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Now <b>gradients</b> remain <b>fixed</b> when objects are transformed (moved, scaled, rotated, or skewed).")); + _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, + _("Now <b>gradients</b> remain <b>fixed</b> when objects are transformed " + "(moved, scaled, rotated, or skewed).")); } } -void -SelectToolbar::toggle_pattern() +void SelectToolbar::toggle_pattern() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool active = _transform_pattern_btn->get_active(); prefs->setInt("/options/transform/pattern", active); - if ( active ) { - _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Now <b>patterns</b> are <b>transformed</b> along with their objects when those are transformed (moved, scaled, rotated, or skewed).")); + if (active) { + _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, + _("Now <b>patterns</b> are <b>transformed</b> along with their objects when " + "those are transformed (moved, scaled, rotated, or skewed).")); } else { - _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Now <b>patterns</b> remain <b>fixed</b> when objects are transformed (moved, scaled, rotated, or skewed).")); + _desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, + _("Now <b>patterns</b> remain <b>fixed</b> when objects are transformed " + "(moved, scaled, rotated, or skewed).")); } } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/select-toolbar.h b/src/ui/toolbar/select-toolbar.h index b86405f8e28d7db4b01cb0599b0d800355e3f9dd..008d69b23d23b3500e6363aa710c80f407c37f28 100644 --- a/src/ui/toolbar/select-toolbar.h +++ b/src/ui/toolbar/select-toolbar.h @@ -30,21 +30,22 @@ class UnitTracker; namespace Toolbar { -class SelectToolbar : public Toolbar { +class SelectToolbar : public Toolbar +{ using parent_type = Toolbar; private: std::unique_ptr<UI::Widget::UnitTracker> _tracker; - Glib::RefPtr<Gtk::Adjustment> _adj_x; - Glib::RefPtr<Gtk::Adjustment> _adj_y; - Glib::RefPtr<Gtk::Adjustment> _adj_w; - Glib::RefPtr<Gtk::Adjustment> _adj_h; - Gtk::ToggleToolButton *_lock_btn; - Gtk::ToggleToolButton *_transform_stroke_btn; - Gtk::ToggleToolButton *_transform_corners_btn; - Gtk::ToggleToolButton *_transform_gradient_btn; - Gtk::ToggleToolButton *_transform_pattern_btn; + Glib::RefPtr<Gtk::Adjustment> _adj_x; + Glib::RefPtr<Gtk::Adjustment> _adj_y; + Glib::RefPtr<Gtk::Adjustment> _adj_w; + Glib::RefPtr<Gtk::Adjustment> _adj_h; + Gtk::ToggleToolButton *_lock_btn; + Gtk::ToggleToolButton *_transform_stroke_btn; + Gtk::ToggleToolButton *_transform_corners_btn; + Gtk::ToggleToolButton *_transform_gradient_btn; + Gtk::ToggleToolButton *_transform_pattern_btn; std::vector<Gtk::ToolItem *> _context_items; @@ -52,7 +53,7 @@ private: bool _update; - void any_value_changed(Glib::RefPtr<Gtk::Adjustment>& adj); + void any_value_changed(Glib::RefPtr<Gtk::Adjustment> &adj); void layout_widget_update(Inkscape::Selection *sel); void on_inkscape_selection_modified(Inkscape::Selection *selection, guint flags); void on_inkscape_selection_changed(Inkscape::Selection *selection); @@ -68,12 +69,12 @@ protected: void on_unrealize() override; public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_SELECT_TOOLBAR_H */ /* diff --git a/src/ui/toolbar/snap-toolbar.cpp b/src/ui/toolbar/snap-toolbar.cpp index 63347f221907ebd775877f59520351a1b4886bae..fe620b7675fab3c6d4e6064b736f97baaf5c1397 100644 --- a/src/ui/toolbar/snap-toolbar.cpp +++ b/src/ui/toolbar/snap-toolbar.cpp @@ -15,196 +15,179 @@ #include "attributes.h" #include "desktop.h" -#include "verbs.h" - #include "object/sp-namedview.h" - #include "ui/icon-names.h" +#include "verbs.h" namespace Inkscape { namespace UI { namespace Toolbar { SnapToolbar::SnapToolbar(SPDesktop *desktop) - : Toolbar(desktop), - _freeze(false) + : Toolbar(desktop) + , _freeze(false) { // Global snapping control { auto snap_global_verb = Inkscape::Verb::get(SP_VERB_TOGGLE_SNAPPING); - _snap_global_item = add_toggle_button(snap_global_verb->get_name(), - snap_global_verb->get_tip()); + _snap_global_item = add_toggle_button(snap_global_verb->get_name(), snap_global_verb->get_tip()); _snap_global_item->set_icon_name(INKSCAPE_ICON("snap")); - _snap_global_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_GLOBAL)); + _snap_global_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_GLOBAL)); } add_separator(); // Snapping to bounding boxes { - _snap_from_bbox_corner_item = add_toggle_button(_("Bounding box"), - _("Snap bounding boxes")); + _snap_from_bbox_corner_item = add_toggle_button(_("Bounding box"), _("Snap bounding boxes")); _snap_from_bbox_corner_item->set_icon_name(INKSCAPE_ICON("snap")); - _snap_from_bbox_corner_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_BBOX)); + _snap_from_bbox_corner_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_BBOX)); } { - _snap_to_bbox_path_item = add_toggle_button(_("Bounding box edges"), - _("Snap to edges of a bounding box")); + _snap_to_bbox_path_item = add_toggle_button(_("Bounding box edges"), _("Snap to edges of a bounding box")); _snap_to_bbox_path_item->set_icon_name(INKSCAPE_ICON("snap-bounding-box-edges")); - _snap_to_bbox_path_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_BBOX_EDGE)); + _snap_to_bbox_path_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_BBOX_EDGE)); } { - _snap_to_bbox_node_item = add_toggle_button(_("Bounding box corners"), - _("Snap bounding box corners")); + _snap_to_bbox_node_item = add_toggle_button(_("Bounding box corners"), _("Snap bounding box corners")); _snap_to_bbox_node_item->set_icon_name(INKSCAPE_ICON("snap-bounding-box-corners")); - _snap_to_bbox_node_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_BBOX_CORNER)); + _snap_to_bbox_node_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_BBOX_CORNER)); } { - _snap_to_from_bbox_edge_midpoints_item = add_toggle_button(_("BBox Edge Midpoints"), - _("Snap midpoints of bounding box edges")); + _snap_to_from_bbox_edge_midpoints_item = + add_toggle_button(_("BBox Edge Midpoints"), _("Snap midpoints of bounding box edges")); _snap_to_from_bbox_edge_midpoints_item->set_icon_name(INKSCAPE_ICON("snap-bounding-box-midpoints")); - _snap_to_from_bbox_edge_midpoints_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_BBOX_EDGE_MIDPOINT)); + _snap_to_from_bbox_edge_midpoints_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_BBOX_EDGE_MIDPOINT)); } { - _snap_to_from_bbox_edge_centers_item = add_toggle_button(_("BBox Centers"), - _("Snapping centers of bounding boxes")); + _snap_to_from_bbox_edge_centers_item = + add_toggle_button(_("BBox Centers"), _("Snapping centers of bounding boxes")); _snap_to_from_bbox_edge_centers_item->set_icon_name(INKSCAPE_ICON("snap-bounding-box-center")); - _snap_to_from_bbox_edge_centers_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_BBOX_MIDPOINT)); + _snap_to_from_bbox_edge_centers_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_BBOX_MIDPOINT)); } add_separator(); // Snapping to nodes, paths & handles { - _snap_from_node_item = add_toggle_button(_("Nodes"), - _("Snap nodes, paths, and handles")); + _snap_from_node_item = add_toggle_button(_("Nodes"), _("Snap nodes, paths, and handles")); _snap_from_node_item->set_icon_name(INKSCAPE_ICON("snap")); - _snap_from_node_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_NODE)); + _snap_from_node_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_NODE)); } { - _snap_to_item_path_item = add_toggle_button(_("Paths"), - _("Snap to paths")); + _snap_to_item_path_item = add_toggle_button(_("Paths"), _("Snap to paths")); _snap_to_item_path_item->set_icon_name(INKSCAPE_ICON("snap-nodes-path")); - _snap_to_item_path_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_PATH)); + _snap_to_item_path_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_PATH)); } { - _snap_to_path_intersections_item = add_toggle_button(_("Path intersections"), - _("Snap to path intersections")); + _snap_to_path_intersections_item = add_toggle_button(_("Path intersections"), _("Snap to path intersections")); _snap_to_path_intersections_item->set_icon_name(INKSCAPE_ICON("snap-nodes-intersection")); - _snap_to_path_intersections_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_PATH_INTERSECTION)); + _snap_to_path_intersections_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_PATH_INTERSECTION)); } { - _snap_to_item_node_item = add_toggle_button(_("To nodes"), - _("Snap to cusp nodes, incl. rectangle corners")); + _snap_to_item_node_item = add_toggle_button(_("To nodes"), _("Snap to cusp nodes, incl. rectangle corners")); _snap_to_item_node_item->set_icon_name(INKSCAPE_ICON("snap-nodes-cusp")); - _snap_to_item_node_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_NODE_CUSP)); + _snap_to_item_node_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_NODE_CUSP)); } { - _snap_to_smooth_nodes_item = add_toggle_button(_("Smooth nodes"), - _("Snap smooth nodes, incl. quadrant points of ellipses")); + _snap_to_smooth_nodes_item = + add_toggle_button(_("Smooth nodes"), _("Snap smooth nodes, incl. quadrant points of ellipses")); _snap_to_smooth_nodes_item->set_icon_name(INKSCAPE_ICON("snap-nodes-smooth")); - _snap_to_smooth_nodes_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_NODE_SMOOTH)); + _snap_to_smooth_nodes_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_NODE_SMOOTH)); } { - _snap_to_from_line_midpoints_item = add_toggle_button(_("Line Midpoints"), - _("Snap midpoints of line segments")); + _snap_to_from_line_midpoints_item = + add_toggle_button(_("Line Midpoints"), _("Snap midpoints of line segments")); _snap_to_from_line_midpoints_item->set_icon_name(INKSCAPE_ICON("snap-nodes-midpoint")); - _snap_to_from_line_midpoints_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_LINE_MIDPOINT)); + _snap_to_from_line_midpoints_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_LINE_MIDPOINT)); } add_separator(); { - _snap_from_others_item = add_toggle_button(_("Others"), - _("Snap other points (centers, guide origins, gradient handles, etc.)")); + _snap_from_others_item = + add_toggle_button(_("Others"), _("Snap other points (centers, guide origins, gradient handles, etc.)")); _snap_from_others_item->set_icon_name(INKSCAPE_ICON("snap")); - _snap_from_others_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_OTHERS)); + _snap_from_others_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_OTHERS)); } { - _snap_to_from_object_centers_item = add_toggle_button(_("Object Centers"), - _("Snap centers of objects")); + _snap_to_from_object_centers_item = add_toggle_button(_("Object Centers"), _("Snap centers of objects")); _snap_to_from_object_centers_item->set_icon_name(INKSCAPE_ICON("snap-nodes-center")); - _snap_to_from_object_centers_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_OBJECT_MIDPOINT)); + _snap_to_from_object_centers_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_OBJECT_MIDPOINT)); } { - _snap_to_from_rotation_center_item = add_toggle_button(_("Rotation Centers"), - _("Snap an item's rotation center")); + _snap_to_from_rotation_center_item = + add_toggle_button(_("Rotation Centers"), _("Snap an item's rotation center")); _snap_to_from_rotation_center_item->set_icon_name(INKSCAPE_ICON("snap-nodes-rotation-center")); - _snap_to_from_rotation_center_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_ROTATION_CENTER)); + _snap_to_from_rotation_center_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_ROTATION_CENTER)); } { - _snap_to_from_text_baseline_item = add_toggle_button(_("Text baseline"), - _("Snap text anchors and baselines")); + _snap_to_from_text_baseline_item = add_toggle_button(_("Text baseline"), _("Snap text anchors and baselines")); _snap_to_from_text_baseline_item->set_icon_name(INKSCAPE_ICON("snap-text-baseline")); - _snap_to_from_text_baseline_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_TEXT_BASELINE)); + _snap_to_from_text_baseline_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_TEXT_BASELINE)); } add_separator(); { - _snap_to_page_border_item = add_toggle_button(_("Page border"), - _("Snap to the page border")); + _snap_to_page_border_item = add_toggle_button(_("Page border"), _("Snap to the page border")); _snap_to_page_border_item->set_icon_name(INKSCAPE_ICON("snap-page")); - _snap_to_page_border_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_PAGE_BORDER)); + _snap_to_page_border_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_PAGE_BORDER)); } { - _snap_to_grids_item = add_toggle_button(_("Grids"), - _("Snap to grids")); + _snap_to_grids_item = add_toggle_button(_("Grids"), _("Snap to grids")); _snap_to_grids_item->set_icon_name(INKSCAPE_ICON("grid-rectangular")); - _snap_to_grids_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_GRID)); + _snap_to_grids_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_GRID)); } { - _snap_to_guides_item = add_toggle_button(_("Guides"), - _("Snap guides")); + _snap_to_guides_item = add_toggle_button(_("Guides"), _("Snap guides")); _snap_to_guides_item->set_icon_name(INKSCAPE_ICON("guides")); - _snap_to_guides_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), - SPAttr::INKSCAPE_SNAP_GUIDE)); + _snap_to_guides_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SnapToolbar::on_snap_toggled), SPAttr::INKSCAPE_SNAP_GUIDE)); } show_all(); } -GtkWidget * -SnapToolbar::create(SPDesktop *desktop) +GtkWidget *SnapToolbar::create(SPDesktop *desktop) { auto tb = Gtk::manage(new SnapToolbar(desktop)); return GTK_WIDGET(tb->gobj()); } -void -SnapToolbar::update(SnapToolbar *tb) +void SnapToolbar::update(SnapToolbar *tb) { auto nv = tb->_desktop->getNamedView(); @@ -231,9 +214,11 @@ SnapToolbar::update(SnapToolbar *tb) tb->_snap_to_bbox_node_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(SNAPTARGET_BBOX_CORNER)); tb->_snap_to_bbox_node_item->set_sensitive(c1 && c2); - tb->_snap_to_from_bbox_edge_midpoints_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(SNAPTARGET_BBOX_EDGE_MIDPOINT)); + tb->_snap_to_from_bbox_edge_midpoints_item->set_active( + nv->snap_manager.snapprefs.isSnapButtonEnabled(SNAPTARGET_BBOX_EDGE_MIDPOINT)); tb->_snap_to_from_bbox_edge_midpoints_item->set_sensitive(c1 && c2); - tb->_snap_to_from_bbox_edge_centers_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(SNAPTARGET_BBOX_MIDPOINT)); + tb->_snap_to_from_bbox_edge_centers_item->set_active( + nv->snap_manager.snapprefs.isSnapButtonEnabled(SNAPTARGET_BBOX_MIDPOINT)); tb->_snap_to_from_bbox_edge_centers_item->set_sensitive(c1 && c2); bool const c3 = nv->snap_manager.snapprefs.isTargetSnappable(SNAPTARGET_NODE_CATEGORY); @@ -242,25 +227,33 @@ SnapToolbar::update(SnapToolbar *tb) tb->_snap_to_item_path_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH)); tb->_snap_to_item_path_item->set_sensitive(c1 && c3); - tb->_snap_to_path_intersections_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_INTERSECTION)); + tb->_snap_to_path_intersections_item->set_active( + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PATH_INTERSECTION)); tb->_snap_to_path_intersections_item->set_sensitive(c1 && c3); - tb->_snap_to_item_node_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_NODE_CUSP)); + tb->_snap_to_item_node_item->set_active( + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_NODE_CUSP)); tb->_snap_to_item_node_item->set_sensitive(c1 && c3); - tb->_snap_to_smooth_nodes_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_NODE_SMOOTH)); + tb->_snap_to_smooth_nodes_item->set_active( + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_NODE_SMOOTH)); tb->_snap_to_smooth_nodes_item->set_sensitive(c1 && c3); - tb->_snap_to_from_line_midpoints_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_LINE_MIDPOINT)); + tb->_snap_to_from_line_midpoints_item->set_active( + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_LINE_MIDPOINT)); tb->_snap_to_from_line_midpoints_item->set_sensitive(c1 && c3); bool const c5 = nv->snap_manager.snapprefs.isTargetSnappable(SNAPTARGET_OTHERS_CATEGORY); tb->_snap_from_others_item->set_active(c5); tb->_snap_from_others_item->set_sensitive(c1); - tb->_snap_to_from_object_centers_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_OBJECT_MIDPOINT)); + tb->_snap_to_from_object_centers_item->set_active( + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_OBJECT_MIDPOINT)); tb->_snap_to_from_object_centers_item->set_sensitive(c1 && c5); - tb->_snap_to_from_rotation_center_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_ROTATION_CENTER)); + tb->_snap_to_from_rotation_center_item->set_active( + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_ROTATION_CENTER)); tb->_snap_to_from_rotation_center_item->set_sensitive(c1 && c5); - tb->_snap_to_from_text_baseline_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_TEXT_BASELINE)); + tb->_snap_to_from_text_baseline_item->set_active( + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_TEXT_BASELINE)); tb->_snap_to_from_text_baseline_item->set_sensitive(c1 && c5); - tb->_snap_to_page_border_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PAGE_BORDER)); + tb->_snap_to_page_border_item->set_active( + nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_PAGE_BORDER)); tb->_snap_to_page_border_item->set_sensitive(c1); tb->_snap_to_grids_item->set_active(nv->snap_manager.snapprefs.isSnapButtonEnabled(Inkscape::SNAPTARGET_GRID)); tb->_snap_to_grids_item->set_sensitive(c1); @@ -270,15 +263,15 @@ SnapToolbar::update(SnapToolbar *tb) tb->_freeze = false; } -void -SnapToolbar::on_snap_toggled(SPAttr attr) +void SnapToolbar::on_snap_toggled(SPAttr attr) { - if(_freeze) return; + if (_freeze) + return; auto dt = _desktop; auto nv = dt->getNamedView(); - if(!nv) { + if (!nv) { g_warning("No namedview specified in toggle-snap callback"); return; } @@ -286,7 +279,7 @@ SnapToolbar::on_snap_toggled(SPAttr attr) auto doc = nv->document; auto repr = nv->getRepr(); - if(!repr) { + if (!repr) { g_warning("This namedview doesn't have an XML representation attached!"); return; } @@ -387,9 +380,9 @@ SnapToolbar::on_snap_toggled(SPAttr attr) doc->setModifiedSinceSave(); } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: mode:c++ diff --git a/src/ui/toolbar/snap-toolbar.h b/src/ui/toolbar/snap-toolbar.h index 9d948a11b66a3a7108180ee034b7d532db313b3b..2a2f1d75847c7841251fa8e38bd4505293c60cf0 100644 --- a/src/ui/toolbar/snap-toolbar.h +++ b/src/ui/toolbar/snap-toolbar.h @@ -18,7 +18,8 @@ enum class SPAttr; namespace Inkscape { namespace UI { namespace Toolbar { -class SnapToolbar : public Toolbar { +class SnapToolbar : public Toolbar +{ private: bool _freeze; @@ -49,13 +50,13 @@ protected: SnapToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); static void update(SnapToolbar *tb); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_SNAP_TOOLBAR_H */ /* diff --git a/src/ui/toolbar/spiral-toolbar.cpp b/src/ui/toolbar/spiral-toolbar.cpp index 05ce65424227d209b94500197bf2908ab75900ff..5e77ccbd5da2577a1c8cc297baf6d6b449a1a03e 100644 --- a/src/ui/toolbar/spiral-toolbar.cpp +++ b/src/ui/toolbar/spiral-toolbar.cpp @@ -28,43 +28,38 @@ #include "spiral-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/separatortoolitem.h> #include <gtkmm/toolbutton.h> #include "desktop.h" #include "document-undo.h" -#include "selection.h" -#include "verbs.h" - #include "object/sp-spiral.h" - +#include "selection.h" #include "ui/icon-names.h" #include "ui/uxmanager.h" #include "ui/widget/canvas.h" #include "ui/widget/label-tool-item.h" #include "ui/widget/spin-button-tool-item.h" - +#include "verbs.h" #include "xml/node-event-vector.h" -using Inkscape::UI::UXManager; using Inkscape::DocumentUndo; +using Inkscape::UI::UXManager; static Inkscape::XML::NodeEventVector spiral_tb_repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - Inkscape::UI::Toolbar::SpiralToolbar::event_attr_changed, - nullptr, /* content_changed */ - nullptr /* order_changed */ + nullptr, /* child_added */ + nullptr, /* child_removed */ + Inkscape::UI::Toolbar::SpiralToolbar::event_attr_changed, nullptr, /* content_changed */ + nullptr /* order_changed */ }; namespace Inkscape { namespace UI { namespace Toolbar { -SpiralToolbar::SpiralToolbar(SPDesktop *desktop) : - Toolbar(desktop), - _freeze(false), - _repr(nullptr) +SpiralToolbar::SpiralToolbar(SPDesktop *desktop) + : Toolbar(desktop) + , _freeze(false) + , _repr(nullptr) { auto prefs = Inkscape::Preferences::get(); @@ -76,47 +71,52 @@ SpiralToolbar::SpiralToolbar(SPDesktop *desktop) : /* Revolution */ { - std::vector<Glib::ustring> labels = {_("just a curve"), "", _("one full revolution"), "", "", "", "", "", "", ""}; - std::vector<double> values = { 0.01, 0.5, 1, 2, 3, 5, 10, 20, 50, 100}; + std::vector<Glib::ustring> labels = { + _("just a curve"), "", _("one full revolution"), "", "", "", "", "", "", ""}; + std::vector<double> values = {0.01, 0.5, 1, 2, 3, 5, 10, 20, 50, 100}; auto revolution_val = prefs->getDouble("/tools/shapes/spiral/revolution", 3.0); _revolution_adj = Gtk::Adjustment::create(revolution_val, 0.01, 1024.0, 0.1, 1.0); - _revolution_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("spiral-revolutions", _("Turns:"), _revolution_adj, 1, 2)); + _revolution_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("spiral-revolutions", _("Turns:"), _revolution_adj, 1, 2)); _revolution_item->set_tooltip_text(_("Number of revolutions")); _revolution_item->set_custom_numeric_menu_data(values, labels); _revolution_item->set_focus_widget(desktop->getCanvas()); - _revolution_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &SpiralToolbar::value_changed), - _revolution_adj, "revolution")); + _revolution_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &SpiralToolbar::value_changed), _revolution_adj, "revolution")); add(*_revolution_item); } /* Expansion */ { - std::vector<Glib::ustring> labels = {_("circle"), _("edge is much denser"), _("edge is denser"), _("even"), _("center is denser"), _("center is much denser"), ""}; - std::vector<double> values = { 0, 0.1, 0.5, 1, 1.5, 5, 20}; + std::vector<Glib::ustring> labels = {_("circle"), _("edge is much denser"), _("edge is denser"), + _("even"), _("center is denser"), _("center is much denser"), + ""}; + std::vector<double> values = {0, 0.1, 0.5, 1, 1.5, 5, 20}; auto expansion_val = prefs->getDouble("/tools/shapes/spiral/expansion", 1.0); _expansion_adj = Gtk::Adjustment::create(expansion_val, 0.0, 1000.0, 0.01, 1.0); - _expansion_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("spiral-expansion", _("Divergence:"), _expansion_adj)); + _expansion_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("spiral-expansion", _("Divergence:"), _expansion_adj)); _expansion_item->set_tooltip_text(_("How much denser/sparser are outer revolutions; 1 = uniform")); _expansion_item->set_custom_numeric_menu_data(values, labels); _expansion_item->set_focus_widget(desktop->getCanvas()); - _expansion_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &SpiralToolbar::value_changed), - _expansion_adj, "expansion")); + _expansion_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &SpiralToolbar::value_changed), _expansion_adj, "expansion")); add(*_expansion_item); } /* T0 */ { std::vector<Glib::ustring> labels = {_("starts from center"), _("starts mid-way"), _("starts near edge")}; - std::vector<double> values = { 0, 0.5, 0.9}; + std::vector<double> values = {0, 0.5, 0.9}; auto t0_val = prefs->getDouble("/tools/shapes/spiral/t0", 0.0); _t0_adj = Gtk::Adjustment::create(t0_val, 0.0, 0.999, 0.01, 1.0); _t0_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("spiral-t0", _("Inner radius:"), _t0_adj)); _t0_item->set_tooltip_text(_("Radius of the innermost revolution (relative to the spiral size)")); _t0_item->set_custom_numeric_menu_data(values, labels); _t0_item->set_focus_widget(desktop->getCanvas()); - _t0_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(*this, &SpiralToolbar::value_changed), - _t0_adj, "t0")); + _t0_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(*this, &SpiralToolbar::value_changed), _t0_adj, "t0")); add(*_t0_item); } @@ -126,7 +126,8 @@ SpiralToolbar::SpiralToolbar(SPDesktop *desktop) : { _reset_item = Gtk::manage(new Gtk::ToolButton(_("Defaults"))); _reset_item->set_icon_name(INKSCAPE_ICON("edit-clear")); - _reset_item->set_tooltip_text(_("Reset shape parameters to defaults (use Inkscape Preferences > Tools to change defaults)")); + _reset_item->set_tooltip_text( + _("Reset shape parameters to defaults (use Inkscape Preferences > Tools to change defaults)")); _reset_item->signal_clicked().connect(sigc::mem_fun(*this, &SpiralToolbar::defaults)); add(*_reset_item); } @@ -139,32 +140,28 @@ SpiralToolbar::SpiralToolbar(SPDesktop *desktop) : SpiralToolbar::~SpiralToolbar() { - if(_repr) { + if (_repr) { _repr->removeListenerByData(this); GC::release(_repr); _repr = nullptr; } - if(_connection) { + if (_connection) { _connection->disconnect(); } } -GtkWidget * -SpiralToolbar::create(SPDesktop *desktop) +GtkWidget *SpiralToolbar::create(SPDesktop *desktop) { auto toolbar = new SpiralToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -SpiralToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, - Glib::ustring const &value_name) +void SpiralToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, Glib::ustring const &value_name) { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble("/tools/shapes/spiral/" + value_name, - adj->get_value()); + prefs->setDouble("/tools/shapes/spiral/" + value_name, adj->get_value()); } // quit if run by the attr_changed listener @@ -175,16 +172,15 @@ SpiralToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, // in turn, prevent listener from responding _freeze = true; - gchar* namespaced_name = g_strconcat("sodipodi:", value_name.data(), NULL); + gchar *namespaced_name = g_strconcat("sodipodi:", value_name.data(), NULL); bool modmade = false; - auto itemlist= _desktop->getSelection()->items(); - for(auto i=itemlist.begin();i!=itemlist.end(); ++i){ + auto itemlist = _desktop->getSelection()->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (SP_IS_SPIRAL(item)) { Inkscape::XML::Node *repr = item->getRepr(); - sp_repr_set_svg_double( repr, namespaced_name, - adj->get_value() ); + sp_repr_set_svg_double(repr, namespaced_name, adj->get_value()); item->updateRepr(); modmade = true; } @@ -193,15 +189,13 @@ SpiralToolbar::value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, g_free(namespaced_name); if (modmade) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SPIRAL, - _("Change spiral")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_SPIRAL, _("Change spiral")); } _freeze = false; } -void -SpiralToolbar::defaults() +void SpiralToolbar::defaults() { // fixme: make settable gdouble rev = 3; @@ -212,23 +206,23 @@ SpiralToolbar::defaults() _expansion_adj->set_value(exp); _t0_adj->set_value(t0); - if(_desktop->getCanvas()) _desktop->getCanvas()->grab_focus(); + if (_desktop->getCanvas()) + _desktop->getCanvas()->grab_focus(); } -void -SpiralToolbar::selection_changed(Inkscape::Selection *selection) +void SpiralToolbar::selection_changed(Inkscape::Selection *selection) { int n_selected = 0; Inkscape::XML::Node *repr = nullptr; - if ( _repr ) { + if (_repr) { _repr->removeListenerByData(this); GC::release(_repr); _repr = nullptr; } - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end(); ++i){ + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (SP_IS_SPIRAL(item)) { n_selected++; @@ -249,18 +243,13 @@ SpiralToolbar::selection_changed(Inkscape::Selection *selection) } } else { // FIXME: implement averaging of all parameters for multiple selected - //gtk_label_set_markup(GTK_LABEL(l), _("<b>Average:</b>")); + // gtk_label_set_markup(GTK_LABEL(l), _("<b>Average:</b>")); _mode_item->set_markup(_("<b>Change:</b>")); } } -void -SpiralToolbar::event_attr_changed(Inkscape::XML::Node *repr, - gchar const * /*name*/, - gchar const * /*old_value*/, - gchar const * /*new_value*/, - bool /*is_interactive*/, - gpointer data) +void SpiralToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const * /*name*/, gchar const * /*old_value*/, + gchar const * /*new_value*/, bool /*is_interactive*/, gpointer data) { auto toolbar = reinterpret_cast<SpiralToolbar *>(data); @@ -287,9 +276,9 @@ SpiralToolbar::event_attr_changed(Inkscape::XML::Node *repr, toolbar->_freeze = false; } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/spiral-toolbar.h b/src/ui/toolbar/spiral-toolbar.h index 9c27eb560addcd69729a63ad2ca9c797daab9889..18088ea0b01690bfcdb77bb0e60256741ba8e6e3 100644 --- a/src/ui/toolbar/spiral-toolbar.h +++ b/src/ui/toolbar/spiral-toolbar.h @@ -28,10 +28,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; namespace Gtk { @@ -49,10 +49,11 @@ namespace UI { namespace Widget { class LabelToolItem; class SpinButtonToolItem; -} +} // namespace Widget namespace Toolbar { -class SpiralToolbar : public Toolbar { +class SpiralToolbar : public Toolbar +{ private: UI::Widget::LabelToolItem *_mode_item; @@ -70,8 +71,7 @@ private: XML::Node *_repr; - void value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, - Glib::ustring const &value_name); + void value_changed(Glib::RefPtr<Gtk::Adjustment> &adj, Glib::ustring const &value_name); void defaults(); void selection_changed(Inkscape::Selection *selection); @@ -82,17 +82,13 @@ protected: ~SpiralToolbar() override; public: - static GtkWidget * create(SPDesktop *desktop); - - static void event_attr_changed(Inkscape::XML::Node *repr, - gchar const *name, - gchar const *old_value, - gchar const *new_value, - bool is_interactive, - gpointer data); + static GtkWidget *create(SPDesktop *desktop); + + static void event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, gchar const *old_value, + gchar const *new_value, bool is_interactive, gpointer data); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_SPIRAL_TOOLBAR_H */ diff --git a/src/ui/toolbar/spray-toolbar.cpp b/src/ui/toolbar/spray-toolbar.cpp index b55ba875d008bc074ccf910840260fe87e216d1c..0766b18edba35329a3a5714dd7c50ae7ae9a62d4 100644 --- a/src/ui/toolbar/spray-toolbar.cpp +++ b/src/ui/toolbar/spray-toolbar.cpp @@ -29,23 +29,19 @@ #include "spray-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/radiotoolbutton.h> #include <gtkmm/separatortoolitem.h> #include "desktop.h" - -#include "ui/icon-names.h" -#include "ui/simple-pref-pusher.h" - #include "ui/dialog/clonetiler.h" #include "ui/dialog/dialog-manager.h" #include "ui/dialog/panel-dialog.h" - +#include "ui/icon-names.h" +#include "ui/simple-pref-pusher.h" #include "ui/widget/canvas.h" #include "ui/widget/spin-button-tool-item.h" -// Disabled in 0.91 because of Bug #1274831 (crash, spraying an object +// 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 @@ -53,12 +49,13 @@ Inkscape::UI::Dialog::CloneTiler *get_clone_tiler_panel(SPDesktop *desktop) { if (Inkscape::UI::Dialog::PanelDialogBase *panel_dialog = - dynamic_cast<Inkscape::UI::Dialog::PanelDialogBase *>(desktop->_dlg_mgr->getDialog("CloneTiler"))) { + dynamic_cast<Inkscape::UI::Dialog::PanelDialogBase *>(desktop->_dlg_mgr->getDialog("CloneTiler"))) { try { Inkscape::UI::Dialog::CloneTiler &clone_tiler = dynamic_cast<Inkscape::UI::Dialog::CloneTiler &>(panel_dialog->getPanel()); return &clone_tiler; - } catch (std::exception &e) { } + } catch (std::exception &e) { + } } return nullptr; @@ -67,8 +64,8 @@ Inkscape::UI::Dialog::CloneTiler *get_clone_tiler_panel(SPDesktop *desktop) namespace Inkscape { namespace UI { namespace Toolbar { -SprayToolbar::SprayToolbar(SPDesktop *desktop) : - Toolbar(desktop) +SprayToolbar::SprayToolbar(SPDesktop *desktop) + : Toolbar(desktop) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -108,12 +105,13 @@ SprayToolbar::SprayToolbar(SPDesktop *desktop) : } } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { /* Width */ - std::vector<Glib::ustring> labels = {_("(narrow spray)"), "", "", "", _("(default)"), "", "", "", "", _("(broad spray)")}; - std::vector<double> values = { 1, 3, 5, 10, 15, 20, 30, 50, 75, 100}; + std::vector<Glib::ustring> labels = {_("(narrow spray)"), "", "", "", _("(default)"), "", "", "", "", + _("(broad spray)")}; + std::vector<double> values = {1, 3, 5, 10, 15, 20, 30, 50, 75, 100}; auto width_val = prefs->getDouble("/tools/spray/width", 15); _width_adj = Gtk::Adjustment::create(width_val, 1, 100, 1.0, 10.0); auto width_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("spray-width", _("Width:"), _width_adj, 1, 0)); @@ -125,54 +123,58 @@ SprayToolbar::SprayToolbar(SPDesktop *desktop) : add(*width_item); width_item->set_sensitive(true); } - + /* Use Pressure Width button */ { - auto pressure_item = add_toggle_button(_("Pressure"), - _("Use the pressure of the input device to alter the width of spray area")); + auto pressure_item = add_toggle_button( + _("Pressure"), _("Use the pressure of the input device to alter the width of spray area")); pressure_item->set_icon_name(INKSCAPE_ICON("draw-use-pressure")); _usepressurewidth_pusher.reset(new UI::SimplePrefPusher(pressure_item, "/tools/spray/usepressurewidth")); pressure_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), - pressure_item, - "/tools/spray/usepressurewidth")); + pressure_item, "/tools/spray/usepressurewidth")); } - { /* Population */ - std::vector<Glib::ustring> labels = {_("(low population)"), "", "", "", _("(default)"), "", _("(high population)")}; - std::vector<double> values = { 5, 20, 35, 50, 70, 85, 100}; + { /* Population */ + std::vector<Glib::ustring> labels = {_("(low population)"), "", "", "", _("(default)"), "", + _("(high population)")}; + std::vector<double> values = {5, 20, 35, 50, 70, 85, 100}; auto population_val = prefs->getDouble("/tools/spray/population", 70); _population_adj = Gtk::Adjustment::create(population_val, 1, 100, 1.0, 10.0); - _spray_population = Gtk::manage(new UI::Widget::SpinButtonToolItem("spray-population", _("Amount:"), _population_adj, 1, 0)); + _spray_population = + Gtk::manage(new UI::Widget::SpinButtonToolItem("spray-population", _("Amount:"), _population_adj, 1, 0)); _spray_population->set_tooltip_text(_("Adjusts the number of items sprayed per click")); _spray_population->set_custom_numeric_menu_data(values, labels); _spray_population->set_focus_widget(desktop->canvas); _population_adj->signal_value_changed().connect(sigc::mem_fun(*this, &SprayToolbar::population_value_changed)); - //ege_adjustment_action_set_appearance( holder->_spray_population, TOOLBAR_SLIDER_HINT ); + // ege_adjustment_action_set_appearance( holder->_spray_population, TOOLBAR_SLIDER_HINT ); add(*_spray_population); _spray_population->set_sensitive(true); } /* Use Pressure Population button */ { - auto pressure_population_item = add_toggle_button(_("Pressure"), - _("Use the pressure of the input device to alter the amount of sprayed objects")); + auto pressure_population_item = add_toggle_button( + _("Pressure"), _("Use the pressure of the input device to alter the amount of sprayed objects")); pressure_population_item->set_icon_name(INKSCAPE_ICON("draw-use-pressure")); - _usepressurepopulation_pusher.reset(new UI::SimplePrefPusher(pressure_population_item, "/tools/spray/usepressurepopulation")); - pressure_population_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), - pressure_population_item, - "/tools/spray/usepressurepopulation")); + _usepressurepopulation_pusher.reset( + new UI::SimplePrefPusher(pressure_population_item, "/tools/spray/usepressurepopulation")); + pressure_population_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), pressure_population_item, + "/tools/spray/usepressurepopulation")); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); - { /* Rotation */ + { /* Rotation */ std::vector<Glib::ustring> labels = {_("(default)"), "", "", "", "", "", "", _("(high rotation variation)")}; - std::vector<double> values = { 0, 10, 25, 35, 50, 60, 80, 100}; + std::vector<double> values = {0, 10, 25, 35, 50, 60, 80, 100}; auto rotation_val = prefs->getDouble("/tools/spray/rotation_variation", 0); _rotation_adj = Gtk::Adjustment::create(rotation_val, 0, 100, 1.0, 10.0); - _spray_rotation = Gtk::manage(new UI::Widget::SpinButtonToolItem("spray-rotation", _("Rotation:"), _rotation_adj, 1, 0)); + _spray_rotation = + Gtk::manage(new UI::Widget::SpinButtonToolItem("spray-rotation", _("Rotation:"), _rotation_adj, 1, 0)); // xgettext:no-c-format - _spray_rotation->set_tooltip_text(_("Variation of the rotation of the sprayed objects; 0% for the same rotation than the original object")); + _spray_rotation->set_tooltip_text( + _("Variation of the rotation of the sprayed objects; 0% for the same rotation than the original object")); _spray_rotation->set_custom_numeric_menu_data(values, labels); _spray_rotation->set_focus_widget(desktop->canvas); _rotation_adj->signal_value_changed().connect(sigc::mem_fun(*this, &SprayToolbar::rotation_value_changed)); @@ -181,14 +183,16 @@ SprayToolbar::SprayToolbar(SPDesktop *desktop) : _spray_rotation->set_sensitive(); } - { /* Scale */ + { /* Scale */ std::vector<Glib::ustring> labels = {_("(default)"), "", "", "", "", "", "", _("(high scale variation)")}; - std::vector<double> values = { 0, 10, 25, 35, 50, 60, 80, 100}; + std::vector<double> values = {0, 10, 25, 35, 50, 60, 80, 100}; auto scale_val = prefs->getDouble("/tools/spray/scale_variation", 0); _scale_adj = Gtk::Adjustment::create(scale_val, 0, 100, 1.0, 10.0); - _spray_scale = Gtk::manage(new UI::Widget::SpinButtonToolItem("spray-scale", C_("Spray tool", "Scale:"), _scale_adj, 1, 0)); + _spray_scale = Gtk::manage( + new UI::Widget::SpinButtonToolItem("spray-scale", C_("Spray tool", "Scale:"), _scale_adj, 1, 0)); // xgettext:no-c-format - _spray_scale->set_tooltip_text(_("Variation in the scale of the sprayed objects; 0% for the same scale than the original object")); + _spray_scale->set_tooltip_text( + _("Variation in the scale of the sprayed objects; 0% for the same scale than the original object")); _spray_scale->set_custom_numeric_menu_data(values, labels); _spray_scale->set_focus_widget(desktop->canvas); _scale_adj->signal_value_changed().connect(sigc::mem_fun(*this, &SprayToolbar::scale_value_changed)); @@ -199,22 +203,24 @@ SprayToolbar::SprayToolbar(SPDesktop *desktop) : /* Use Pressure Scale button */ { - _usepressurescale = add_toggle_button(_("Pressure"), - _("Use the pressure of the input device to alter the scale of new items")); + _usepressurescale = + add_toggle_button(_("Pressure"), _("Use the pressure of the input device to alter the scale of new items")); _usepressurescale->set_icon_name(INKSCAPE_ICON("draw-use-pressure")); _usepressurescale->set_active(prefs->getBool("/tools/spray/usepressurescale", false)); _usepressurescale->signal_toggled().connect(sigc::mem_fun(*this, &SprayToolbar::toggle_pressure_scale)); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { /* Standard_deviation */ - std::vector<Glib::ustring> labels = {_("(minimum scatter)"), "", "", "", "", "", _("(default)"), _("(maximum scatter)")}; - std::vector<double> values = { 1, 5, 10, 20, 30, 50, 70, 100}; + std::vector<Glib::ustring> labels = {_("(minimum scatter)"), "", "", "", "", "", _("(default)"), + _("(maximum scatter)")}; + std::vector<double> values = {1, 5, 10, 20, 30, 50, 70, 100}; auto sd_val = prefs->getDouble("/tools/spray/standard_deviation", 70); _sd_adj = Gtk::Adjustment::create(sd_val, 1, 100, 1.0, 10.0); - auto sd_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("spray-standard-deviation", C_("Spray tool", "Scatter:"), _sd_adj, 1, 0)); + auto sd_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("spray-standard-deviation", + C_("Spray tool", "Scatter:"), _sd_adj, 1, 0)); sd_item->set_tooltip_text(_("Increase to scatter sprayed objects")); sd_item->set_custom_numeric_menu_data(values, labels); sd_item->set_focus_widget(desktop->canvas); @@ -227,7 +233,7 @@ SprayToolbar::SprayToolbar(SPDesktop *desktop) : { /* Mean */ std::vector<Glib::ustring> labels = {_("(default)"), "", "", "", "", "", "", _("(maximum mean)")}; - std::vector<double> values = { 0, 5, 10, 20, 30, 50, 70, 100}; + std::vector<double> values = {0, 5, 10, 20, 30, 50, 70, 100}; auto mean_val = prefs->getDouble("/tools/spray/mean", 0); _mean_adj = Gtk::Adjustment::create(mean_val, 0, 100, 1.0, 10.0); auto mean_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("spray-mean", _("Focus:"), _mean_adj, 1, 0)); @@ -240,12 +246,12 @@ SprayToolbar::SprayToolbar(SPDesktop *desktop) : mean_item->set_sensitive(true); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Over No Transparent */ { - _over_no_transparent = add_toggle_button(_("Apply over no transparent areas"), - _("Apply over no transparent areas")); + _over_no_transparent = + add_toggle_button(_("Apply over no transparent areas"), _("Apply over no transparent areas")); _over_no_transparent->set_icon_name(INKSCAPE_ICON("object-visible")); _over_no_transparent->set_active(prefs->getBool("/tools/spray/over_no_transparent", true)); _over_no_transparent->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), @@ -255,30 +261,25 @@ SprayToolbar::SprayToolbar(SPDesktop *desktop) : /* Over Transparent */ { - _over_transparent = add_toggle_button(_("Apply over transparent areas"), - _("Apply over transparent areas")); + _over_transparent = add_toggle_button(_("Apply over transparent areas"), _("Apply over transparent areas")); _over_transparent->set_icon_name(INKSCAPE_ICON("object-hidden")); _over_transparent->set_active(prefs->getBool("/tools/spray/over_transparent", true)); _over_transparent->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), - _over_transparent, - "/tools/spray/over_transparent")); + _over_transparent, "/tools/spray/over_transparent")); } /* Pick No Overlap */ { - _pick_no_overlap = add_toggle_button(_("No overlap between colors"), - _("No overlap between colors")); + _pick_no_overlap = add_toggle_button(_("No overlap between colors"), _("No overlap between colors")); _pick_no_overlap->set_icon_name(INKSCAPE_ICON("symbol-bigger")); _pick_no_overlap->set_active(prefs->getBool("/tools/spray/pick_no_overlap", false)); _pick_no_overlap->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), - _pick_no_overlap, - "/tools/spray/pick_no_overlap")); + _pick_no_overlap, "/tools/spray/pick_no_overlap")); } /* Overlap */ { - _no_overlap = add_toggle_button(_("Prevent overlapping objects"), - _("Prevent overlapping objects")); + _no_overlap = add_toggle_button(_("Prevent overlapping objects"), _("Prevent overlapping objects")); _no_overlap->set_icon_name(INKSCAPE_ICON("distribute-randomize")); _no_overlap->set_active(prefs->getBool("/tools/spray/no_overlap", false)); _no_overlap->signal_toggled().connect(sigc::mem_fun(*this, &SprayToolbar::toggle_no_overlap)); @@ -286,8 +287,9 @@ SprayToolbar::SprayToolbar(SPDesktop *desktop) : /* Offset */ { - std::vector<Glib::ustring> labels = {_("(minimum offset)"), "", "", "", _("(default)"), "", "", _("(maximum offset)")}; - std::vector<double> values = { 0, 25, 50, 75, 100, 150, 200, 1000}; + std::vector<Glib::ustring> labels = {_("(minimum offset)"), "", "", "", + _("(default)"), "", "", _("(maximum offset)")}; + std::vector<double> values = {0, 25, 50, 75, 100, 150, 200, 1000}; auto offset_val = prefs->getDouble("/tools/spray/offset", 100); _offset_adj = Gtk::Adjustment::create(offset_val, 0, 1000, 1, 4); _offset = Gtk::manage(new UI::Widget::SpinButtonToolItem("spray-offset", _("Offset %:"), _offset_adj, 0, 0)); @@ -298,37 +300,35 @@ SprayToolbar::SprayToolbar(SPDesktop *desktop) : add(*_offset); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Picker */ { - _picker = add_toggle_button(_("Pick color from the drawing. You can use clonetiler trace dialog for advanced effects. In clone mode original fill or stroke colors must be unset."), - _("Pick color from the drawing. You can use clonetiler trace dialog for advanced effects. In clone mode original fill or stroke colors must be unset.")); + _picker = add_toggle_button(_("Pick color from the drawing. You can use clonetiler trace dialog for advanced " + "effects. In clone mode original fill or stroke colors must be unset."), + _("Pick color from the drawing. You can use clonetiler trace dialog for advanced " + "effects. In clone mode original fill or stroke colors must be unset.")); _picker->set_icon_name(INKSCAPE_ICON("color-picker")); _picker->set_active(prefs->getBool("/tools/spray/picker", false)); _picker->signal_toggled().connect(sigc::mem_fun(*this, &SprayToolbar::toggle_picker)); } - + /* Pick Fill */ { - _pick_fill = add_toggle_button(_("Apply picked color to fill"), - _("Apply picked color to fill")); + _pick_fill = add_toggle_button(_("Apply picked color to fill"), _("Apply picked color to fill")); _pick_fill->set_icon_name(INKSCAPE_ICON("paint-solid")); _pick_fill->set_active(prefs->getBool("/tools/spray/pick_fill", false)); - _pick_fill->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), - _pick_fill, - "/tools/spray/pick_fill")); + _pick_fill->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), _pick_fill, "/tools/spray/pick_fill")); } /* Pick Stroke */ { - _pick_stroke = add_toggle_button(_("Apply picked color to stroke"), - _("Apply picked color to stroke")); + _pick_stroke = add_toggle_button(_("Apply picked color to stroke"), _("Apply picked color to stroke")); _pick_stroke->set_icon_name(INKSCAPE_ICON("no-marker")); _pick_stroke->set_active(prefs->getBool("/tools/spray/pick_stroke", false)); - _pick_stroke->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), - _pick_stroke, - "/tools/spray/pick_stroke")); + _pick_stroke->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), _pick_stroke, "/tools/spray/pick_stroke")); } /* Inverse Value Size */ @@ -348,63 +348,54 @@ SprayToolbar::SprayToolbar(SPDesktop *desktop) : _("Pick from center instead of average area.")); _pick_center->set_icon_name(INKSCAPE_ICON("snap-bounding-box-center")); _pick_center->set_active(prefs->getBool("/tools/spray/pick_center", true)); - _pick_center->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), - _pick_center, - "/tools/spray/pick_center")); + _pick_center->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &SprayToolbar::on_pref_toggled), _pick_center, "/tools/spray/pick_center")); } - + gint mode = prefs->getInt("/tools/spray/mode", 1); _mode_buttons[mode]->set_active(); show_all(); init(); } -GtkWidget * -SprayToolbar::create(SPDesktop *desktop) +GtkWidget *SprayToolbar::create(SPDesktop *desktop) { - auto toolbar = new SprayToolbar(desktop); - return GTK_WIDGET(toolbar->gobj()); + auto toolbar = new SprayToolbar(desktop); + return GTK_WIDGET(toolbar->gobj()); } -void -SprayToolbar::width_value_changed() +void SprayToolbar::width_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/spray/width", - _width_adj->get_value()); + prefs->setDouble("/tools/spray/width", _width_adj->get_value()); } -void -SprayToolbar::mean_value_changed() +void SprayToolbar::mean_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/spray/mean", - _mean_adj->get_value()); + prefs->setDouble("/tools/spray/mean", _mean_adj->get_value()); } -void -SprayToolbar::standard_deviation_value_changed() +void SprayToolbar::standard_deviation_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/spray/standard_deviation", - _sd_adj->get_value()); + prefs->setDouble("/tools/spray/standard_deviation", _sd_adj->get_value()); } -void -SprayToolbar::mode_changed(int mode) +void SprayToolbar::mode_changed(int mode) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setInt("/tools/spray/mode", mode); init(); } -void -SprayToolbar::init(){ +void SprayToolbar::init() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int mode = prefs->getInt("/tools/spray/mode", 0); bool show = true; - if(mode == 3 || mode == 2){ + if (mode == 3 || mode == 2) { show = false; } _no_overlap->set_visible(show); @@ -421,31 +412,26 @@ SprayToolbar::init(){ _pick_stroke->set_visible(show); _pick_inverse_value->set_visible(show); _pick_center->set_visible(show); - if(mode == 2){ + if (mode == 2) { show = true; } _spray_rotation->set_visible(show); update_widgets(); } -void -SprayToolbar::population_value_changed() +void SprayToolbar::population_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/spray/population", - _population_adj->get_value()); + prefs->setDouble("/tools/spray/population", _population_adj->get_value()); } -void -SprayToolbar::rotation_value_changed() +void SprayToolbar::rotation_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/spray/rotation_variation", - _rotation_adj->get_value()); + prefs->setDouble("/tools/spray/rotation_variation", _rotation_adj->get_value()); } -void -SprayToolbar::update_widgets() +void SprayToolbar::update_widgets() { _offset_adj->set_value(100.0); @@ -465,8 +451,7 @@ SprayToolbar::update_widgets() _pick_center->set_visible(picker_is_active); } -void -SprayToolbar::toggle_no_overlap() +void SprayToolbar::toggle_no_overlap() { auto prefs = Inkscape::Preferences::get(); bool active = _no_overlap->get_active(); @@ -474,44 +459,38 @@ SprayToolbar::toggle_no_overlap() update_widgets(); } -void -SprayToolbar::scale_value_changed() +void SprayToolbar::scale_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/spray/scale_variation", - _scale_adj->get_value()); + prefs->setDouble("/tools/spray/scale_variation", _scale_adj->get_value()); } -void -SprayToolbar::offset_value_changed() +void SprayToolbar::offset_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/spray/offset", - _offset_adj->get_value()); + prefs->setDouble("/tools/spray/offset", _offset_adj->get_value()); } -void -SprayToolbar::toggle_pressure_scale() +void SprayToolbar::toggle_pressure_scale() { auto prefs = Inkscape::Preferences::get(); bool active = _usepressurescale->get_active(); prefs->setBool("/tools/spray/usepressurescale", active); - if(active){ + if (active) { prefs->setDouble("/tools/spray/scale_variation", 0); } update_widgets(); } -void -SprayToolbar::toggle_picker() +void SprayToolbar::toggle_picker() { auto prefs = Inkscape::Preferences::get(); bool active = _picker->get_active(); prefs->setBool("/tools/spray/picker", active); - if(active){ + if (active) { prefs->setBool("/dialogs/clonetiler/dotrace", false); SPDesktop *dt = _desktop; - if (Inkscape::UI::Dialog::CloneTiler *ct = get_clone_tiler_panel(dt)){ + if (Inkscape::UI::Dialog::CloneTiler *ct = get_clone_tiler_panel(dt)) { dt->_dlg_mgr->showDialog("CloneTiler"); ct->show_page_trace(); } @@ -519,24 +498,21 @@ SprayToolbar::toggle_picker() update_widgets(); } -void -SprayToolbar::on_pref_toggled(Gtk::ToggleToolButton *btn, - const Glib::ustring& path) +void SprayToolbar::on_pref_toggled(Gtk::ToggleToolButton *btn, const Glib::ustring &path) { auto prefs = Inkscape::Preferences::get(); bool active = btn->get_active(); prefs->setBool(path, active); } -void -SprayToolbar::set_mode(int mode) +void SprayToolbar::set_mode(int mode) { _mode_buttons[mode]->set_active(); } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/spray-toolbar.h b/src/ui/toolbar/spray-toolbar.h index 4587cf03399d5f1395b24815acb13eb082ca36a5..cfe4af91a5d6c9a555870076d97f61cbb4eb8ce3 100644 --- a/src/ui/toolbar/spray-toolbar.h +++ b/src/ui/toolbar/spray-toolbar.h @@ -28,10 +28,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; namespace Gtk { @@ -47,7 +47,8 @@ class SpinButtonToolItem; } namespace Toolbar { -class SprayToolbar : public Toolbar { +class SprayToolbar : public Toolbar +{ private: Glib::RefPtr<Gtk::Adjustment> _width_adj; Glib::RefPtr<Gtk::Adjustment> _mean_adj; @@ -86,8 +87,7 @@ private: void update_widgets(); void scale_value_changed(); void offset_value_changed(); - void on_pref_toggled(Gtk::ToggleToolButton *btn, - const Glib::ustring& path); + void on_pref_toggled(Gtk::ToggleToolButton *btn, const Glib::ustring &path); void toggle_no_overlap(); void toggle_pressure_scale(); void toggle_picker(); @@ -96,12 +96,12 @@ protected: SprayToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); void set_mode(int mode); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_SELECT_TOOLBAR_H */ diff --git a/src/ui/toolbar/star-toolbar.cpp b/src/ui/toolbar/star-toolbar.cpp index d9b09ff5915f3add76a4163371595dc59c44423e..736b8e90bf37d0aadbc7059a4003dd2d81b4ac75 100644 --- a/src/ui/toolbar/star-toolbar.cpp +++ b/src/ui/toolbar/star-toolbar.cpp @@ -28,46 +28,40 @@ #include "star-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/radiotoolbutton.h> #include <gtkmm/separatortoolitem.h> #include "desktop.h" #include "document-undo.h" -#include "selection.h" -#include "verbs.h" - #include "object/sp-star.h" - +#include "selection.h" #include "ui/icon-names.h" #include "ui/tools/star-tool.h" #include "ui/uxmanager.h" #include "ui/widget/canvas.h" #include "ui/widget/label-tool-item.h" #include "ui/widget/spin-button-tool-item.h" - +#include "verbs.h" #include "xml/node-event-vector.h" -using Inkscape::UI::UXManager; using Inkscape::DocumentUndo; +using Inkscape::UI::UXManager; -static Inkscape::XML::NodeEventVector star_tb_repr_events = -{ - nullptr, /* child_added */ - nullptr, /* child_removed */ - Inkscape::UI::Toolbar::StarToolbar::event_attr_changed, - nullptr, /* content_changed */ - nullptr /* order_changed */ +static Inkscape::XML::NodeEventVector star_tb_repr_events = { + nullptr, /* child_added */ + nullptr, /* child_removed */ + Inkscape::UI::Toolbar::StarToolbar::event_attr_changed, nullptr, /* content_changed */ + nullptr /* order_changed */ }; namespace Inkscape { namespace UI { namespace Toolbar { -StarToolbar::StarToolbar(SPDesktop *desktop) : - Toolbar(desktop), - _mode_item(Gtk::manage(new UI::Widget::LabelToolItem(_("<b>New:</b>")))), - _repr(nullptr), - _freeze(false) +StarToolbar::StarToolbar(SPDesktop *desktop) + : Toolbar(desktop) + , _mode_item(Gtk::manage(new UI::Widget::LabelToolItem(_("<b>New:</b>")))) + , _repr(nullptr) + , _freeze(false) { _mode_item->set_use_markup(true); add(*_mode_item); @@ -89,14 +83,14 @@ StarToolbar::StarToolbar(SPDesktop *desktop) : flat_star_button->set_icon_name(INKSCAPE_ICON("draw-star")); _flat_item_buttons.push_back(flat_star_button); - _flat_item_buttons[ isFlatSided ? 0 : 1 ]->set_active(); + _flat_item_buttons[isFlatSided ? 0 : 1]->set_active(); int btn_index = 0; - for (auto btn : _flat_item_buttons) - { + for (auto btn : _flat_item_buttons) { add(*btn); - btn->signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &StarToolbar::side_mode_changed), btn_index++)); + btn->signal_clicked().connect( + sigc::bind(sigc::mem_fun(*this, &StarToolbar::side_mode_changed), btn_index++)); } } @@ -117,7 +111,8 @@ StarToolbar::StarToolbar(SPDesktop *desktop) : std::vector<double> values = {2, 3, 4, 5, 6, 7, 8, 10, 12, 20}; auto magnitude_val = prefs->getDouble("/tools/shapes/star/magnitude", 3); _magnitude_adj = Gtk::Adjustment::create(magnitude_val, isFlatSided ? 3 : 2, 1024, 1, 5); - _magnitude_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("star-magnitude", _("Corners:"), _magnitude_adj, 1.0, 0)); + _magnitude_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("star-magnitude", _("Corners:"), _magnitude_adj, 1.0, 0)); _magnitude_item->set_tooltip_text(_("Number of corners of a polygon or star")); _magnitude_item->set_custom_numeric_menu_data(values, labels); _magnitude_item->set_focus_widget(desktop->canvas); @@ -128,8 +123,9 @@ StarToolbar::StarToolbar(SPDesktop *desktop) : /* Spoke ratio */ { - std::vector<Glib::ustring> labels = {_("thin-ray star"), "", _("pentagram"), _("hexagram"), _("heptagram"), _("octagram"), _("regular polygon")}; - std::vector<double> values = { 0.01, 0.2, 0.382, 0.577, 0.692, 0.765, 1}; + std::vector<Glib::ustring> labels = { + _("thin-ray star"), "", _("pentagram"), _("hexagram"), _("heptagram"), _("octagram"), _("regular polygon")}; + std::vector<double> values = {0.01, 0.2, 0.382, 0.577, 0.692, 0.765, 1}; auto prop_val = prefs->getDouble("/tools/shapes/star/proportion", 0.5); _spoke_adj = Gtk::Adjustment::create(prop_val, 0.01, 1.0, 0.01, 0.1); _spoke_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("star-spoke", _("Spoke ratio:"), _spoke_adj)); @@ -145,12 +141,15 @@ StarToolbar::StarToolbar(SPDesktop *desktop) : /* Roundedness */ { - std::vector<Glib::ustring> labels = {_("stretched"), _("twisted"), _("slightly pinched"), _("NOT rounded"), _("slightly rounded"), - _("visibly rounded"), _("well rounded"), _("amply rounded"), "", _("stretched"), _("blown up")}; + std::vector<Glib::ustring> labels = {_("stretched"), _("twisted"), _("slightly pinched"), + _("NOT rounded"), _("slightly rounded"), _("visibly rounded"), + _("well rounded"), _("amply rounded"), "", + _("stretched"), _("blown up")}; std::vector<double> values = {-1, -0.2, -0.03, 0, 0.05, 0.1, 0.2, 0.3, 0.5, 1, 10}; auto roundedness_val = prefs->getDouble("/tools/shapes/star/rounded", 0.0); _roundedness_adj = Gtk::Adjustment::create(roundedness_val, -10.0, 10.0, 0.01, 0.1); - _roundedness_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("star-roundedness", _("Rounded:"), _roundedness_adj)); + _roundedness_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("star-roundedness", _("Rounded:"), _roundedness_adj)); _roundedness_item->set_tooltip_text(_("How rounded are the corners (0 for sharp)")); _roundedness_item->set_custom_numeric_menu_data(values, labels); _roundedness_item->set_focus_widget(desktop->canvas); @@ -161,15 +160,18 @@ StarToolbar::StarToolbar(SPDesktop *desktop) : /* Randomization */ { - std::vector<Glib::ustring> labels = {_("NOT randomized"), _("slightly irregular"), _("visibly randomized"), _("strongly randomized"), _("blown up")}; - std::vector<double> values = { 0, 0.01, 0.1, 0.5, 10}; + std::vector<Glib::ustring> labels = {_("NOT randomized"), _("slightly irregular"), _("visibly randomized"), + _("strongly randomized"), _("blown up")}; + std::vector<double> values = {0, 0.01, 0.1, 0.5, 10}; auto randomized_val = prefs->getDouble("/tools/shapes/star/randomized", 0.0); _randomization_adj = Gtk::Adjustment::create(randomized_val, -10.0, 10.0, 0.001, 0.01); - _randomization_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("star-randomized", _("Randomized:"), _randomization_adj, 0.1, 3)); + _randomization_item = Gtk::manage( + new UI::Widget::SpinButtonToolItem("star-randomized", _("Randomized:"), _randomization_adj, 0.1, 3)); _randomization_item->set_tooltip_text(_("Scatter randomly the corners and angles")); _randomization_item->set_custom_numeric_menu_data(values, labels); _randomization_item->set_focus_widget(desktop->canvas); - _randomization_adj->signal_value_changed().connect(sigc::mem_fun(*this, &StarToolbar::randomized_value_changed)); + _randomization_adj->signal_value_changed().connect( + sigc::mem_fun(*this, &StarToolbar::randomized_value_changed)); _randomization_item->set_sensitive(true); add(*_randomization_item); } @@ -180,7 +182,8 @@ StarToolbar::StarToolbar(SPDesktop *desktop) : { _reset_item = Gtk::manage(new Gtk::ToolButton(_("Defaults"))); _reset_item->set_icon_name(INKSCAPE_ICON("edit-clear")); - _reset_item->set_tooltip_text(_("Reset shape parameters to defaults (use Inkscape Preferences > Tools to change defaults)")); + _reset_item->set_tooltip_text( + _("Reset shape parameters to defaults (use Inkscape Preferences > Tools to change defaults)")); _reset_item->signal_clicked().connect(sigc::mem_fun(*this, &StarToolbar::defaults)); _reset_item->set_sensitive(true); add(*_reset_item); @@ -201,21 +204,19 @@ StarToolbar::~StarToolbar() } } -GtkWidget * -StarToolbar::create(SPDesktop *desktop) +GtkWidget *StarToolbar::create(SPDesktop *desktop) { auto toolbar = new StarToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -StarToolbar::side_mode_changed(int mode) +void StarToolbar::side_mode_changed(int mode) { bool flat = (mode == 0); if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setBool( "/tools/shapes/star/isflatsided", flat ); + prefs->setBool("/tools/shapes/star/isflatsided", flat); } // quit if run by the attr_changed listener @@ -233,8 +234,8 @@ StarToolbar::side_mode_changed(int mode) _spoke_item->set_visible(!flat); } - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (SP_IS_STAR(item)) { Inkscape::XML::Node *repr = item->getRepr(); @@ -244,7 +245,7 @@ StarToolbar::side_mode_changed(int mode) sp_repr_set_int(repr, "sodipodi:sides", 3); } } - repr->setAttribute("inkscape:flatsided", flat ? "true" : "false" ); + repr->setAttribute("inkscape:flatsided", flat ? "true" : "false"); item->updateRepr(); modmade = true; @@ -257,22 +258,19 @@ StarToolbar::side_mode_changed(int mode) } if (modmade) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_STAR, - flat ? _("Make polygon") : _("Make star")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_STAR, flat ? _("Make polygon") : _("Make star")); } _freeze = false; } -void -StarToolbar::magnitude_value_changed() +void StarToolbar::magnitude_value_changed() { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { // do not remember prefs if this call is initiated by an undo change, because undoing object // creation sets bogus values to its attributes before it is deleted Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setInt("/tools/shapes/star/magnitude", - (gint)_magnitude_adj->get_value()); + prefs->setInt("/tools/shapes/star/magnitude", (gint)_magnitude_adj->get_value()); } // quit if run by the attr_changed listener @@ -286,37 +284,32 @@ StarToolbar::magnitude_value_changed() bool modmade = false; Inkscape::Selection *selection = _desktop->getSelection(); - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (SP_IS_STAR(item)) { Inkscape::XML::Node *repr = item->getRepr(); - sp_repr_set_int(repr,"sodipodi:sides", - (gint)_magnitude_adj->get_value()); + sp_repr_set_int(repr, "sodipodi:sides", (gint)_magnitude_adj->get_value()); double arg1 = 0.5; sp_repr_get_double(repr, "sodipodi:arg1", &arg1); - sp_repr_set_svg_double(repr, "sodipodi:arg2", - (arg1 + M_PI / (gint)_magnitude_adj->get_value())); + sp_repr_set_svg_double(repr, "sodipodi:arg2", (arg1 + M_PI / (gint)_magnitude_adj->get_value())); item->updateRepr(); modmade = true; } } if (modmade) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_STAR, - _("Star: Change number of corners")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_STAR, _("Star: Change number of corners")); } _freeze = false; } -void -StarToolbar::proportion_value_changed() +void StarToolbar::proportion_value_changed() { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { if (!std::isnan(_spoke_adj->get_value())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble("/tools/shapes/star/proportion", - _spoke_adj->get_value()); + prefs->setDouble("/tools/shapes/star/proportion", _spoke_adj->get_value()); } } @@ -330,8 +323,8 @@ StarToolbar::proportion_value_changed() bool modmade = false; Inkscape::Selection *selection = _desktop->getSelection(); - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (SP_IS_STAR(item)) { Inkscape::XML::Node *repr = item->getRepr(); @@ -341,11 +334,9 @@ StarToolbar::proportion_value_changed() sp_repr_get_double(repr, "sodipodi:r1", &r1); sp_repr_get_double(repr, "sodipodi:r2", &r2); if (r2 < r1) { - sp_repr_set_svg_double(repr, "sodipodi:r2", - r1*_spoke_adj->get_value()); + sp_repr_set_svg_double(repr, "sodipodi:r2", r1 * _spoke_adj->get_value()); } else { - sp_repr_set_svg_double(repr, "sodipodi:r1", - r2*_spoke_adj->get_value()); + sp_repr_set_svg_double(repr, "sodipodi:r1", r2 * _spoke_adj->get_value()); } item->updateRepr(); @@ -354,19 +345,17 @@ StarToolbar::proportion_value_changed() } if (modmade) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_STAR, - _("Star: Change spoke ratio")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_STAR, _("Star: Change spoke ratio")); } _freeze = false; } -void -StarToolbar::rounded_value_changed() +void StarToolbar::rounded_value_changed() { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble("/tools/shapes/star/rounded", (gdouble) _roundedness_adj->get_value()); + prefs->setDouble("/tools/shapes/star/rounded", (gdouble)_roundedness_adj->get_value()); } // quit if run by the attr_changed listener @@ -380,32 +369,28 @@ StarToolbar::rounded_value_changed() bool modmade = false; Inkscape::Selection *selection = _desktop->getSelection(); - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (SP_IS_STAR(item)) { Inkscape::XML::Node *repr = item->getRepr(); - sp_repr_set_svg_double(repr, "inkscape:rounded", - (gdouble) _roundedness_adj->get_value()); + sp_repr_set_svg_double(repr, "inkscape:rounded", (gdouble)_roundedness_adj->get_value()); item->updateRepr(); modmade = true; } } if (modmade) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_STAR, - _("Star: Change rounding")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_STAR, _("Star: Change rounding")); } _freeze = false; } -void -StarToolbar::randomized_value_changed() +void StarToolbar::randomized_value_changed() { if (DocumentUndo::getUndoSensitive(_desktop->getDocument())) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble("/tools/shapes/star/randomized", - (gdouble) _randomization_adj->get_value()); + prefs->setDouble("/tools/shapes/star/randomized", (gdouble)_randomization_adj->get_value()); } // quit if run by the attr_changed listener @@ -419,29 +404,25 @@ StarToolbar::randomized_value_changed() bool modmade = false; Inkscape::Selection *selection = _desktop->getSelection(); - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (SP_IS_STAR(item)) { Inkscape::XML::Node *repr = item->getRepr(); - sp_repr_set_svg_double(repr, "inkscape:randomized", - (gdouble) _randomization_adj->get_value()); + sp_repr_set_svg_double(repr, "inkscape:randomized", (gdouble)_randomization_adj->get_value()); item->updateRepr(); modmade = true; } } if (modmade) { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_STAR, - _("Star: Change randomization")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_STAR, _("Star: Change randomization")); } _freeze = false; } -void -StarToolbar::defaults() +void StarToolbar::defaults() { - // FIXME: in this and all other _default functions, set some flag telling the value_changed // callbacks to lump all the changes for all selected objects in one undo step @@ -452,7 +433,7 @@ StarToolbar::defaults() gdouble randomized = 0; gdouble rounded = 0; - _flat_item_buttons[ flat ? 0 : 1 ]->set_active(); + _flat_item_buttons[flat ? 0 : 1]->set_active(); _spoke_item->set_visible(!flat); @@ -462,10 +443,9 @@ StarToolbar::defaults() _randomization_adj->set_value(randomized); } -void -StarToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) +void StarToolbar::watch_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec) { - if (dynamic_cast<Inkscape::UI::Tools::StarTool const*>(ec) != nullptr) { + if (dynamic_cast<Inkscape::UI::Tools::StarTool const *>(ec) != nullptr) { _changed = desktop->getSelection()->connectChanged(sigc::mem_fun(*this, &StarToolbar::selection_changed)); selection_changed(desktop->getSelection()); } else { @@ -477,8 +457,7 @@ StarToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) /** * \param selection Should not be NULL. */ -void -StarToolbar::selection_changed(Inkscape::Selection *selection) +void StarToolbar::selection_changed(Inkscape::Selection *selection) { int n_selected = 0; Inkscape::XML::Node *repr = nullptr; @@ -489,8 +468,8 @@ StarToolbar::selection_changed(Inkscape::Selection *selection) _repr = nullptr; } - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (SP_IS_STAR(item)) { n_selected++; @@ -511,15 +490,13 @@ StarToolbar::selection_changed(Inkscape::Selection *selection) } } else { // FIXME: implement averaging of all parameters for multiple selected stars - //gtk_label_set_markup(GTK_LABEL(l), _("<b>Average:</b>")); - //gtk_label_set_markup(GTK_LABEL(l), _("<b>Change:</b>")); + // gtk_label_set_markup(GTK_LABEL(l), _("<b>Average:</b>")); + // gtk_label_set_markup(GTK_LABEL(l), _("<b>Change:</b>")); } } -void -StarToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, - gchar const * /*old_value*/, gchar const * /*new_value*/, - bool /*is_interactive*/, gpointer dataPointer) +void StarToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, gchar const * /*old_value*/, + gchar const * /*new_value*/, bool /*is_interactive*/, gpointer dataPointer) { auto toolbar = reinterpret_cast<StarToolbar *>(dataPointer); @@ -544,7 +521,7 @@ StarToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, toolbar->_roundedness_adj->set_value(rounded); } else if (!strcmp(name, "inkscape:flatsided")) { char const *flatsides = repr->attribute("inkscape:flatsided"); - if ( flatsides && !strcmp(flatsides,"false") ) { + if (flatsides && !strcmp(flatsides, "false")) { toolbar->_flat_item_buttons[1]->set_active(); toolbar->_spoke_item->set_visible(true); toolbar->_magnitude_adj->set_lower(2); @@ -553,15 +530,15 @@ StarToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, toolbar->_spoke_item->set_visible(false); toolbar->_magnitude_adj->set_lower(3); } - } else if ((!strcmp(name, "sodipodi:r1") || !strcmp(name, "sodipodi:r2")) && (!isFlatSided) ) { + } else if ((!strcmp(name, "sodipodi:r1") || !strcmp(name, "sodipodi:r2")) && (!isFlatSided)) { gdouble r1 = 1.0; gdouble r2 = 1.0; sp_repr_get_double(repr, "sodipodi:r1", &r1); sp_repr_get_double(repr, "sodipodi:r2", &r2); if (r2 < r1) { - toolbar->_spoke_adj->set_value(r2/r1); + toolbar->_spoke_adj->set_value(r2 / r1); } else { - toolbar->_spoke_adj->set_value(r1/r2); + toolbar->_spoke_adj->set_value(r1 / r2); } } else if (!strcmp(name, "sodipodi:sides")) { int sides = 0; @@ -572,9 +549,9 @@ StarToolbar::event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, toolbar->_freeze = false; } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/star-toolbar.h b/src/ui/toolbar/star-toolbar.h index c44caab225264696ee6f1e60b12330305e4ae115..e0cf97f63b8f4ca1121b9c3201871af486fea268 100644 --- a/src/ui/toolbar/star-toolbar.h +++ b/src/ui/toolbar/star-toolbar.h @@ -28,16 +28,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "toolbar.h" - #include <gtkmm/adjustment.h> +#include "toolbar.h" + class SPDesktop; namespace Gtk { class RadioToolButton; class ToolButton; -} +} // namespace Gtk namespace Inkscape { class Selection; @@ -54,10 +54,11 @@ class ToolBase; namespace Widget { class LabelToolItem; class SpinButtonToolItem; -} +} // namespace Widget namespace Toolbar { -class StarToolbar : public Toolbar { +class StarToolbar : public Toolbar +{ private: UI::Widget::LabelToolItem *_mode_item; std::vector<Gtk::RadioToolButton *> _flat_item_buttons; @@ -76,14 +77,14 @@ private: bool _freeze; sigc::connection _changed; - + void side_mode_changed(int mode); void magnitude_value_changed(); void proportion_value_changed(); void rounded_value_changed(); void randomized_value_changed(); void defaults(); - void watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec); + void watch_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec); void selection_changed(Inkscape::Selection *selection); protected: @@ -91,18 +92,14 @@ protected: ~StarToolbar() override; public: - static GtkWidget * create(SPDesktop *desktop); - - static void event_attr_changed(Inkscape::XML::Node *repr, - gchar const *name, - gchar const *old_value, - gchar const *new_value, - bool is_interactive, - gpointer dataPointer); + static GtkWidget *create(SPDesktop *desktop); + + static void event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, gchar const *old_value, + gchar const *new_value, bool is_interactive, gpointer dataPointer); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_SELECT_TOOLBAR_H */ diff --git a/src/ui/toolbar/text-toolbar.cpp b/src/ui/toolbar/text-toolbar.cpp index 3b02a39efbce96cbbd713d88183773ba75d9e5d6..5c1401b037e89d489fe9ffb58ac3279333ba2ab2 100644 --- a/src/ui/toolbar/text-toolbar.cpp +++ b/src/ui/toolbar/text-toolbar.cpp @@ -27,45 +27,41 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/i18n.h> - #include "text-toolbar.h" +#include <glibmm/i18n.h> + #include "desktop-style.h" #include "desktop.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" -#include "selection-chemistry.h" -#include "verbs.h" - #include "libnrtype/font-lister.h" - #include "object/sp-flowdiv.h" #include "object/sp-flowtext.h" #include "object/sp-root.h" +#include "object/sp-string.h" #include "object/sp-text.h" #include "object/sp-tspan.h" -#include "object/sp-string.h" - +#include "selection-chemistry.h" #include "svg/css-ostringstream.h" #include "ui/icon-names.h" #include "ui/tools/select-tool.h" #include "ui/tools/text-tool.h" -#include "ui/widget/canvas.h" // Focus +#include "ui/widget/canvas.h" // Focus #include "ui/widget/combo-box-entry-tool-item.h" #include "ui/widget/combo-tool-item.h" #include "ui/widget/spin-button-tool-item.h" #include "ui/widget/unit-tracker.h" #include "util/units.h" - +#include "verbs.h" #include "widgets/style-utils.h" using Inkscape::DocumentUndo; -using Inkscape::Util::Unit; +using Inkscape::UI::Widget::UnitTracker; using Inkscape::Util::Quantity; +using Inkscape::Util::Unit; using Inkscape::Util::unit_table; -using Inkscape::UI::Widget::UnitTracker; //#define DEBUG_TEXT @@ -77,40 +73,37 @@ using Inkscape::UI::Widget::UnitTracker; #ifdef DEBUG_TEXT static void sp_print_font(SPStyle *query) { - - - bool family_set = query->font_family.set; - bool style_set = query->font_style.set; + bool family_set = query->font_family.set; + bool style_set = query->font_style.set; bool fontspec_set = query->font_specification.set; - std::cout << " Family set? " << family_set - << " Style set? " << style_set - << " FontSpec set? " << fontspec_set - << std::endl; + std::cout << " Family set? " << family_set << " Style set? " << style_set << " FontSpec set? " + << fontspec_set << std::endl; } -static void sp_print_fontweight( SPStyle *query ) { - const gchar* names[] = {"100", "200", "300", "400", "500", "600", "700", "800", "900", - "NORMAL", "BOLD", "LIGHTER", "BOLDER", "Out of range"}; +static void sp_print_fontweight(SPStyle *query) +{ + const gchar *names[] = {"100", "200", "300", "400", "500", "600", "700", + "800", "900", "NORMAL", "BOLD", "LIGHTER", "BOLDER", "Out of range"}; // Missing book = 380 int index = query->font_weight.computed; if (index < 0 || index > 13) index = 13; - std::cout << " Weight: " << names[ index ] - << " (" << query->font_weight.computed << ")" << std::endl; + std::cout << " Weight: " << names[index] << " (" << query->font_weight.computed << ")" << std::endl; } -static void sp_print_fontstyle( SPStyle *query ) { - - const gchar* names[] = {"NORMAL", "ITALIC", "OBLIQUE", "Out of range"}; +static void sp_print_fontstyle(SPStyle *query) +{ + const gchar *names[] = {"NORMAL", "ITALIC", "OBLIQUE", "Out of range"}; int index = query->font_style.computed; - if( index < 0 || index > 3 ) index = 3; - std::cout << " Style: " << names[ index ] << std::endl; - + if (index < 0 || index > 3) + index = 3; + std::cout << " Style: " << names[index] << std::endl; } #endif -static bool is_relative( Unit const *unit ) { +static bool is_relative(Unit const *unit) +{ return (unit->abbr == "" || unit->abbr == "em" || unit->abbr == "ex" || unit->abbr == "%"); } @@ -124,82 +117,77 @@ static bool is_relative(SPCSSUnit const unit) // Should probably be moved to desktop_style.cpp static void recursively_set_properties(SPObject *object, SPCSSAttr *css, bool unset_descendents = true) { - object->changeCSS (css, "style"); + object->changeCSS(css, "style"); - SPCSSAttr *css_unset = sp_repr_css_attr_unset_all( css ); + SPCSSAttr *css_unset = sp_repr_css_attr_unset_all(css); std::vector<SPObject *> children = object->childList(false); - for (auto i: children) { + for (auto i : children) { recursively_set_properties(i, unset_descendents ? css_unset : css); } - sp_repr_css_attr_unref (css_unset); + sp_repr_css_attr_unref(css_unset); } /* * Set the default list of font sizes, scaled to the users preferred unit */ -static void sp_text_set_sizes(GtkListStore* model_size, int unit) +static void sp_text_set_sizes(GtkListStore *model_size, int unit) { gtk_list_store_clear(model_size); // List of font sizes for dropchange-down menu - int sizes[] = { - 4, 6, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 28, - 32, 36, 40, 48, 56, 64, 72, 144 - }; + int sizes[] = {4, 6, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 48, 56, 64, 72, 144}; // Array must be same length as SPCSSUnit in style.h float ratios[] = {1, 1, 1, 10, 4, 40, 100, 16, 8, 0.16}; - for(int i : sizes) { + for (int i : sizes) { GtkTreeIter iter; Glib::ustring size = Glib::ustring::format(i / (float)ratios[unit]); - gtk_list_store_append( model_size, &iter ); - gtk_list_store_set( model_size, &iter, 0, size.c_str(), -1 ); + gtk_list_store_append(model_size, &iter); + gtk_list_store_set(model_size, &iter, 0, size.c_str(), -1); } } - // TODO: possibly share with font-selector by moving most code to font-lister (passing family name) -static void sp_text_toolbox_select_cb( GtkEntry* entry, GtkEntryIconPosition /*position*/, GdkEvent /*event*/, gpointer /*data*/ ) { - - Glib::ustring family = gtk_entry_get_text ( entry ); - //std::cout << "text_toolbox_missing_font_cb: selecting: " << family << std::endl; - - // Get all items with matching font-family set (not inherited!). - std::vector<SPItem*> selectList; - - SPDesktop *desktop = SP_ACTIVE_DESKTOP; - SPDocument *document = desktop->getDocument(); - std::vector<SPItem*> x,y; - std::vector<SPItem*> allList = get_all_items(x, document->getRoot(), desktop, false, false, true, y); - for(std::vector<SPItem*>::const_reverse_iterator i=allList.rbegin();i!=allList.rend(); ++i){ - SPItem *item = *i; - SPStyle *style = item->style; - - if (style) { - - Glib::ustring family_style; - if (style->font_family.set) { - family_style = style->font_family.value(); - //std::cout << " family style from font_family: " << family_style << std::endl; - } - else if (style->font_specification.set) { - family_style = style->font_specification.value(); - //std::cout << " family style from font_spec: " << family_style << std::endl; - } - - if (family_style.compare( family ) == 0 ) { - //std::cout << " found: " << item->getId() << std::endl; - selectList.push_back(item); - } - } - } - - // Update selection - Inkscape::Selection *selection = desktop->getSelection(); - selection->clear(); - //std::cout << " list length: " << g_slist_length ( selectList ) << std::endl; - selection->setList(selectList); +static void sp_text_toolbox_select_cb(GtkEntry *entry, GtkEntryIconPosition /*position*/, GdkEvent /*event*/, + gpointer /*data*/) +{ + Glib::ustring family = gtk_entry_get_text(entry); + // std::cout << "text_toolbox_missing_font_cb: selecting: " << family << std::endl; + + // Get all items with matching font-family set (not inherited!). + std::vector<SPItem *> selectList; + + SPDesktop *desktop = SP_ACTIVE_DESKTOP; + SPDocument *document = desktop->getDocument(); + std::vector<SPItem *> x, y; + std::vector<SPItem *> allList = get_all_items(x, document->getRoot(), desktop, false, false, true, y); + for (std::vector<SPItem *>::const_reverse_iterator i = allList.rbegin(); i != allList.rend(); ++i) { + SPItem *item = *i; + SPStyle *style = item->style; + + if (style) { + Glib::ustring family_style; + if (style->font_family.set) { + family_style = style->font_family.value(); + // std::cout << " family style from font_family: " << family_style << std::endl; + } else if (style->font_specification.set) { + family_style = style->font_specification.value(); + // std::cout << " family style from font_spec: " << family_style << std::endl; + } + + if (family_style.compare(family) == 0) { + // std::cout << " found: " << item->getId() << std::endl; + selectList.push_back(item); + } + } + } + + // Update selection + Inkscape::Selection *selection = desktop->getSelection(); + selection->clear(); + // std::cout << " list length: " << g_slist_length ( selectList ) << std::endl; + selection->setList(selectList); } namespace Inkscape { @@ -231,32 +219,29 @@ TextToolbar::TextToolbar(SPDesktop *desktop) /* Font family */ { // Font list - Inkscape::FontLister* fontlister = Inkscape::FontLister::get_instance(); + Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); fontlister->update_font_list(desktop->getDocument()); Glib::RefPtr<Gtk::ListStore> store = fontlister->get_font_list(); - GtkListStore* model = store->gobj(); - - _font_family_item = - Gtk::manage(new UI::Widget::ComboBoxEntryToolItem( "TextFontFamilyAction", - _("Font Family"), - _("Select Font Family (Alt-X to access)"), - GTK_TREE_MODEL(model), - -1, // Entry width - 50, // Extra list width - (gpointer)font_lister_cell_data_func2, // Cell layout - (gpointer)font_lister_separator_func2, - GTK_WIDGET(desktop->getCanvas()->gobj()))); // Focus widget - _font_family_item->popup_enable(); // Enable entry completion + GtkListStore *model = store->gobj(); + + _font_family_item = Gtk::manage(new UI::Widget::ComboBoxEntryToolItem( + "TextFontFamilyAction", _("Font Family"), _("Select Font Family (Alt-X to access)"), GTK_TREE_MODEL(model), + -1, // Entry width + 50, // Extra list width + (gpointer)font_lister_cell_data_func2, // Cell layout + (gpointer)font_lister_separator_func2, + GTK_WIDGET(desktop->getCanvas()->gobj()))); // Focus widget + _font_family_item->popup_enable(); // Enable entry completion gchar *const info = _("Select all text with this font-family"); - _font_family_item->set_info( info ); // Show selection icon - _font_family_item->set_info_cb( (gpointer)sp_text_toolbox_select_cb ); + _font_family_item->set_info(info); // Show selection icon + _font_family_item->set_info_cb((gpointer)sp_text_toolbox_select_cb); gchar *const warning = _("Font not found on system"); - _font_family_item->set_warning( warning ); // Show icon w/ tooltip if font missing - _font_family_item->set_warning_cb( (gpointer)sp_text_toolbox_select_cb ); + _font_family_item->set_warning(warning); // Show icon w/ tooltip if font missing + _font_family_item->set_warning_cb((gpointer)sp_text_toolbox_select_cb); - //ink_comboboxentry_action_set_warning_callback( act, sp_text_fontfamily_select_all ); - _font_family_item->signal_changed().connect( sigc::mem_fun(*this, &TextToolbar::fontfamily_value_changed) ); + // ink_comboboxentry_action_set_warning_callback( act, sp_text_fontfamily_select_all ); + _font_family_item->signal_changed().connect(sigc::mem_fun(*this, &TextToolbar::fontfamily_value_changed)); add(*_font_family_item); // Change style of drop-down from menu to list @@ -269,27 +254,23 @@ TextToolbar::TextToolbar(SPDesktop *desktop) auto screen = gdk_screen_get_default(); _font_family_item->focus_on_click(false); - gtk_style_context_add_provider_for_screen(screen, - GTK_STYLE_PROVIDER(css_provider), + gtk_style_context_add_provider_for_screen(screen, GTK_STYLE_PROVIDER(css_provider), GTK_STYLE_PROVIDER_PRIORITY_USER); } /* Font styles */ { - Inkscape::FontLister* fontlister = Inkscape::FontLister::get_instance(); + Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); Glib::RefPtr<Gtk::ListStore> store = fontlister->get_style_list(); - GtkListStore* model_style = store->gobj(); - - _font_style_item = - Gtk::manage(new UI::Widget::ComboBoxEntryToolItem( "TextFontStyleAction", - _("Font Style"), - _("Font style"), - GTK_TREE_MODEL(model_style), - 12, // Width in characters - 0, // Extra list width - nullptr, // Cell layout - nullptr, // Separator - GTK_WIDGET(desktop->getCanvas()->gobj()))); // Focus widget + GtkListStore *model_style = store->gobj(); + + _font_style_item = Gtk::manage(new UI::Widget::ComboBoxEntryToolItem( + "TextFontStyleAction", _("Font Style"), _("Font style"), GTK_TREE_MODEL(model_style), + 12, // Width in characters + 0, // Extra list width + nullptr, // Cell layout + nullptr, // Separator + GTK_WIDGET(desktop->getCanvas()->gobj()))); // Focus widget _font_style_item->signal_changed().connect(sigc::mem_fun(*this, &TextToolbar::fontstyle_value_changed)); _font_style_item->focus_on_click(false); @@ -301,7 +282,7 @@ TextToolbar::TextToolbar(SPDesktop *desktop) /* Font size */ { // List of font sizes for drop-down menu - GtkListStore* model_size = gtk_list_store_new( 1, G_TYPE_STRING ); + GtkListStore *model_size = gtk_list_store_new(1, G_TYPE_STRING); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int unit = prefs->getInt("/options/font/unitType", SP_CSS_UNIT_PT); @@ -310,16 +291,13 @@ TextToolbar::TextToolbar(SPDesktop *desktop) auto unit_str = sp_style_get_css_unit_string(unit); Glib::ustring tooltip = Glib::ustring::format(_("Font size"), " (", unit_str, ")"); - _font_size_item = - Gtk::manage(new UI::Widget::ComboBoxEntryToolItem( "TextFontSizeAction", - _("Font Size"), - tooltip, - GTK_TREE_MODEL(model_size), - 8, // Width in characters - 0, // Extra list width - nullptr, // Cell layout - nullptr, // Separator - GTK_WIDGET(desktop->getCanvas()->gobj()))); // Focus widget + _font_size_item = Gtk::manage(new UI::Widget::ComboBoxEntryToolItem( + "TextFontSizeAction", _("Font Size"), tooltip, GTK_TREE_MODEL(model_size), + 8, // Width in characters + 0, // Extra list width + nullptr, // Cell layout + nullptr, // Separator + GTK_WIDGET(desktop->getCanvas()->gobj()))); // Focus widget _font_size_item->signal_changed().connect(sigc::mem_fun(*this, &TextToolbar::fontsize_value_changed)); _font_size_item->focus_on_click(false); @@ -335,8 +313,9 @@ TextToolbar::TextToolbar(SPDesktop *desktop) } { // Drop down menu - std::vector<Glib::ustring> labels = {_("Smaller spacing"), "", "", "", "", C_("Text tool", "Normal"), "", "", "", "", "", _("Larger spacing")}; - std::vector<double> values = { 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 2.0}; + std::vector<Glib::ustring> labels = { + _("Smaller spacing"), "", "", "", "", C_("Text tool", "Normal"), "", "", "", "", "", _("Larger spacing")}; + std::vector<double> values = {0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 2.0}; auto line_height_val = 1.25; _line_height_adj = Gtk::Adjustment::create(line_height_val, 0.0, 1000.0, 0.1, 1.0); @@ -353,8 +332,9 @@ TextToolbar::TextToolbar(SPDesktop *desktop) } /* Line height units */ { - _line_height_units_item = _tracker->create_tool_item( _("Units"), ("")); - _line_height_units_item->signal_changed_after().connect(sigc::mem_fun(*this, &TextToolbar::lineheight_unit_changed)); + _line_height_units_item = _tracker->create_tool_item(_("Units"), ("")); + _line_height_units_item->signal_changed_after().connect( + sigc::mem_fun(*this, &TextToolbar::lineheight_unit_changed)); _line_height_units_item->focus_on_click(false); add(*_line_height_units_item); } @@ -368,38 +348,37 @@ TextToolbar::TextToolbar(SPDesktop *desktop) Gtk::TreeModel::Row row; row = *(store->append()); - row[columns.col_label ] = _("Align left"); - row[columns.col_tooltip ] = _("Align left"); - row[columns.col_icon ] = INKSCAPE_ICON("format-justify-left"); + row[columns.col_label] = _("Align left"); + row[columns.col_tooltip] = _("Align left"); + row[columns.col_icon] = INKSCAPE_ICON("format-justify-left"); row[columns.col_sensitive] = true; row = *(store->append()); - row[columns.col_label ] = _("Align center"); - row[columns.col_tooltip ] = _("Align center"); - row[columns.col_icon ] = INKSCAPE_ICON("format-justify-center"); + row[columns.col_label] = _("Align center"); + row[columns.col_tooltip] = _("Align center"); + row[columns.col_icon] = INKSCAPE_ICON("format-justify-center"); row[columns.col_sensitive] = true; row = *(store->append()); - row[columns.col_label ] = _("Align right"); - row[columns.col_tooltip ] = _("Align right"); - row[columns.col_icon ] = INKSCAPE_ICON("format-justify-right"); + row[columns.col_label] = _("Align right"); + row[columns.col_tooltip] = _("Align right"); + row[columns.col_icon] = INKSCAPE_ICON("format-justify-right"); row[columns.col_sensitive] = true; row = *(store->append()); - row[columns.col_label ] = _("Justify"); - row[columns.col_tooltip ] = _("Justify (only flowed text)"); - row[columns.col_icon ] = INKSCAPE_ICON("format-justify-fill"); + row[columns.col_label] = _("Justify"); + row[columns.col_tooltip] = _("Justify (only flowed text)"); + row[columns.col_icon] = INKSCAPE_ICON("format-justify-fill"); row[columns.col_sensitive] = false; - _align_item = - UI::Widget::ComboToolItem::create(_("Alignment"), // Label - _("Text alignment"), // Tooltip - "Not Used", // Icon - store ); // Tree store - _align_item->use_icon( true ); - _align_item->use_label( false ); + _align_item = UI::Widget::ComboToolItem::create(_("Alignment"), // Label + _("Text alignment"), // Tooltip + "Not Used", // Icon + store); // Tree store + _align_item->use_icon(true); + _align_item->use_label(false); gint mode = prefs->getInt("/tools/text/align_mode", 0); - _align_item->set_active( mode ); + _align_item->set_active(mode); add(*_align_item); _align_item->focus_on_click(false); @@ -414,7 +393,8 @@ TextToolbar::TextToolbar(SPDesktop *desktop) _superscript_item->set_icon_name(INKSCAPE_ICON("text_superscript")); _superscript_item->set_name("text-superscript"); add(*_superscript_item); - _superscript_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &TextToolbar::script_changed), _superscript_item)); + _superscript_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &TextToolbar::script_changed), _superscript_item)); _superscript_item->set_active(prefs->getBool("/tools/text/super", false)); } @@ -426,22 +406,27 @@ TextToolbar::TextToolbar(SPDesktop *desktop) _subscript_item->set_icon_name(INKSCAPE_ICON("text_subscript")); _subscript_item->set_name("text-subscript"); add(*_subscript_item); - _subscript_item->signal_toggled().connect(sigc::bind(sigc::mem_fun(*this, &TextToolbar::script_changed), _subscript_item)); + _subscript_item->signal_toggled().connect( + sigc::bind(sigc::mem_fun(*this, &TextToolbar::script_changed), _subscript_item)); _subscript_item->set_active(prefs->getBool("/tools/text/sub", false)); } /* Letter spacing */ { // Drop down menu - std::vector<Glib::ustring> labels = {_("Negative spacing"), "", "", "", C_("Text tool", "Normal"), "", "", "", "", "", "", "", _("Positive spacing")}; - std::vector<double> values = { -2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0}; + std::vector<Glib::ustring> labels = { + _("Negative spacing"), "", "", "", C_("Text tool", "Normal"), "", "", "", "", "", "", "", + _("Positive spacing")}; + std::vector<double> values = {-2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0}; auto letter_spacing_val = prefs->getDouble("/tools/text/letterspacing", 0.0); _letter_spacing_adj = Gtk::Adjustment::create(letter_spacing_val, -100.0, 100.0, 0.01, 0.10); - _letter_spacing_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("text-letter-spacing", _("Letter:"), _letter_spacing_adj, 0.1, 2)); + _letter_spacing_item = Gtk::manage( + new UI::Widget::SpinButtonToolItem("text-letter-spacing", _("Letter:"), _letter_spacing_adj, 0.1, 2)); _letter_spacing_item->set_tooltip_text(_("Spacing between letters (px)")); _letter_spacing_item->set_custom_numeric_menu_data(values, labels); _letter_spacing_item->set_focus_widget(desktop->getCanvas()); - _letter_spacing_adj->signal_value_changed().connect(sigc::mem_fun(*this, &TextToolbar::letterspacing_value_changed)); + _letter_spacing_adj->signal_value_changed().connect( + sigc::mem_fun(*this, &TextToolbar::letterspacing_value_changed)); add(*_letter_spacing_item); _letter_spacing_item->set_sensitive(true); @@ -451,15 +436,19 @@ TextToolbar::TextToolbar(SPDesktop *desktop) /* Word spacing */ { // Drop down menu - std::vector<Glib::ustring> labels = {_("Negative spacing"), "", "", "", C_("Text tool", "Normal"), "", "", "", "", "", "", "", _("Positive spacing")}; - std::vector<double> values = { -2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0}; + std::vector<Glib::ustring> labels = { + _("Negative spacing"), "", "", "", C_("Text tool", "Normal"), "", "", "", "", "", "", "", + _("Positive spacing")}; + std::vector<double> values = {-2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0}; auto word_spacing_val = prefs->getDouble("/tools/text/wordspacing", 0.0); _word_spacing_adj = Gtk::Adjustment::create(word_spacing_val, -100.0, 100.0, 0.01, 0.10); - _word_spacing_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("text-word-spacing", _("Word:"), _word_spacing_adj, 0.1, 2)); + _word_spacing_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("text-word-spacing", _("Word:"), _word_spacing_adj, 0.1, 2)); _word_spacing_item->set_tooltip_text(_("Spacing between words (px)")); _word_spacing_item->set_custom_numeric_menu_data(values, labels); _word_spacing_item->set_focus_widget(desktop->getCanvas()); - _word_spacing_adj->signal_value_changed().connect(sigc::mem_fun(*this, &TextToolbar::wordspacing_value_changed)); + _word_spacing_adj->signal_value_changed().connect( + sigc::mem_fun(*this, &TextToolbar::wordspacing_value_changed)); add(*_word_spacing_item); _word_spacing_item->set_sensitive(true); @@ -469,7 +458,7 @@ TextToolbar::TextToolbar(SPDesktop *desktop) /* Character kerning (horizontal shift) */ { // Drop down menu - std::vector<double> values = { -2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2.0, 2.5 }; + std::vector<double> values = {-2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2.0, 2.5}; auto dx_val = prefs->getDouble("/tools/text/dx", 0.0); _dx_adj = Gtk::Adjustment::create(dx_val, -100.0, 100.0, 0.01, 0.1); _dx_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("text-dx", _("Kern:"), _dx_adj, 0.1, 2)); @@ -485,7 +474,7 @@ TextToolbar::TextToolbar(SPDesktop *desktop) /* Character vertical shift */ { // Drop down menu - std::vector<double> values = { -2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2.0, 2.5 }; + std::vector<double> values = {-2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2.0, 2.5}; auto dy_val = prefs->getDouble("/tools/text/dy", 0.0); _dy_adj = Gtk::Adjustment::create(dy_val, -100.0, 100.0, 0.01, 0.1); _dy_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("text-dy", _("Vert:"), _dy_adj, 0.1, 2)); @@ -500,10 +489,11 @@ TextToolbar::TextToolbar(SPDesktop *desktop) /* Character rotation */ { - std::vector<double> values = { -90, -45, -30, -15, 0, 15, 30, 45, 90, 180 }; + std::vector<double> values = {-90, -45, -30, -15, 0, 15, 30, 45, 90, 180}; auto rotation_val = prefs->getDouble("/tools/text/rotation", 0.0); _rotation_adj = Gtk::Adjustment::create(rotation_val, -180.0, 180.0, 0.1, 1.0); - _rotation_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("text-rotation", _("Rot:"), _rotation_adj, 0.1, 2)); + _rotation_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("text-rotation", _("Rot:"), _rotation_adj, 0.1, 2)); _rotation_item->set_tooltip_text(_("Character rotation (degrees)")); _rotation_item->set_custom_numeric_menu_data(values); _rotation_item->set_focus_widget(desktop->getCanvas()); @@ -513,7 +503,6 @@ TextToolbar::TextToolbar(SPDesktop *desktop) add(*_rotation_item); } - /* Writing mode (Horizontal, Vertical-LR, Vertical-RL) */ { UI::Widget::ComboToolItemColumns columns; @@ -523,38 +512,36 @@ TextToolbar::TextToolbar(SPDesktop *desktop) Gtk::TreeModel::Row row; row = *(store->append()); - row[columns.col_label ] = _("Horizontal"); - row[columns.col_tooltip ] = _("Horizontal text"); - row[columns.col_icon ] = INKSCAPE_ICON("frmt-text-direction-horizontal"); + row[columns.col_label] = _("Horizontal"); + row[columns.col_tooltip] = _("Horizontal text"); + row[columns.col_icon] = INKSCAPE_ICON("frmt-text-direction-horizontal"); row[columns.col_sensitive] = true; row = *(store->append()); - row[columns.col_label ] = _("Vertical — RL"); - row[columns.col_tooltip ] = _("Vertical text — lines: right to left"); - row[columns.col_icon ] = INKSCAPE_ICON("frmt-text-direction-vertical"); + row[columns.col_label] = _("Vertical — RL"); + row[columns.col_tooltip] = _("Vertical text — lines: right to left"); + row[columns.col_icon] = INKSCAPE_ICON("frmt-text-direction-vertical"); row[columns.col_sensitive] = true; row = *(store->append()); - row[columns.col_label ] = _("Vertical — LR"); - row[columns.col_tooltip ] = _("Vertical text — lines: left to right"); - row[columns.col_icon ] = INKSCAPE_ICON("frmt-text-direction-vertical-lr"); + row[columns.col_label] = _("Vertical — LR"); + row[columns.col_tooltip] = _("Vertical text — lines: left to right"); + row[columns.col_icon] = INKSCAPE_ICON("frmt-text-direction-vertical-lr"); row[columns.col_sensitive] = true; - _writing_mode_item = - UI::Widget::ComboToolItem::create( _("Writing mode"), // Label - _("Block progression"), // Tooltip - "Not Used", // Icon - store ); // Tree store + _writing_mode_item = UI::Widget::ComboToolItem::create(_("Writing mode"), // Label + _("Block progression"), // Tooltip + "Not Used", // Icon + store); // Tree store _writing_mode_item->use_icon(true); - _writing_mode_item->use_label( false ); + _writing_mode_item->use_label(false); gint mode = prefs->getInt("/tools/text/writing_mode", 0); - _writing_mode_item->set_active( mode ); + _writing_mode_item->set_active(mode); add(*_writing_mode_item); _writing_mode_item->focus_on_click(false); _writing_mode_item->signal_changed().connect(sigc::mem_fun(*this, &TextToolbar::writing_mode_changed)); } - /* Text (glyph) orientation (Auto (mixed), Upright, Sideways) */ { UI::Widget::ComboToolItemColumns columns; @@ -564,32 +551,32 @@ TextToolbar::TextToolbar(SPDesktop *desktop) Gtk::TreeModel::Row row; row = *(store->append()); - row[columns.col_label ] = _("Auto"); - row[columns.col_tooltip ] = _("Auto glyph orientation"); - row[columns.col_icon ] = INKSCAPE_ICON("text-orientation-auto"); + row[columns.col_label] = _("Auto"); + row[columns.col_tooltip] = _("Auto glyph orientation"); + row[columns.col_icon] = INKSCAPE_ICON("text-orientation-auto"); row[columns.col_sensitive] = true; row = *(store->append()); - row[columns.col_label ] = _("Upright"); - row[columns.col_tooltip ] = _("Upright glyph orientation"); - row[columns.col_icon ] = INKSCAPE_ICON("text-orientation-upright"); + row[columns.col_label] = _("Upright"); + row[columns.col_tooltip] = _("Upright glyph orientation"); + row[columns.col_icon] = INKSCAPE_ICON("text-orientation-upright"); row[columns.col_sensitive] = true; row = *(store->append()); - row[columns.col_label ] = _("Sideways"); - row[columns.col_tooltip ] = _("Sideways glyph orientation"); - row[columns.col_icon ] = INKSCAPE_ICON("text-orientation-sideways"); + row[columns.col_label] = _("Sideways"); + row[columns.col_tooltip] = _("Sideways glyph orientation"); + row[columns.col_icon] = INKSCAPE_ICON("text-orientation-sideways"); row[columns.col_sensitive] = true; _orientation_item = - UI::Widget::ComboToolItem::create(_("Text orientation"), // Label - _("Text (glyph) orientation in vertical text."), // Tooltip - "Not Used", // Icon - store ); // List store + UI::Widget::ComboToolItem::create(_("Text orientation"), // Label + _("Text (glyph) orientation in vertical text."), // Tooltip + "Not Used", // Icon + store); // List store _orientation_item->use_icon(true); _orientation_item->use_label(false); gint mode = prefs->getInt("/tools/text/text_orientation", 0); - _orientation_item->set_active( mode ); + _orientation_item->set_active(mode); _orientation_item->focus_on_click(false); add(*_orientation_item); @@ -605,26 +592,26 @@ TextToolbar::TextToolbar(SPDesktop *desktop) Gtk::TreeModel::Row row; row = *(store->append()); - row[columns.col_label ] = _("LTR"); - row[columns.col_tooltip ] = _("Left to right text"); - row[columns.col_icon ] = INKSCAPE_ICON("frmt-text-direction-horizontal"); + row[columns.col_label] = _("LTR"); + row[columns.col_tooltip] = _("Left to right text"); + row[columns.col_icon] = INKSCAPE_ICON("frmt-text-direction-horizontal"); row[columns.col_sensitive] = true; row = *(store->append()); - row[columns.col_label ] = _("RTL"); - row[columns.col_tooltip ] = _("Right to left text"); - row[columns.col_icon ] = INKSCAPE_ICON("frmt-text-direction-r2l"); + row[columns.col_label] = _("RTL"); + row[columns.col_tooltip] = _("Right to left text"); + row[columns.col_icon] = INKSCAPE_ICON("frmt-text-direction-r2l"); row[columns.col_sensitive] = true; _direction_item = - UI::Widget::ComboToolItem::create( _("Text direction"), // Label - _("Text direction for normally horizontal text."), // Tooltip - "Not Used", // Icon - store ); // List store + UI::Widget::ComboToolItem::create(_("Text direction"), // Label + _("Text direction for normally horizontal text."), // Tooltip + "Not Used", // Icon + store); // List store _direction_item->use_icon(true); _direction_item->use_label(false); gint mode = prefs->getInt("/tools/text/text_direction", 0); - _direction_item->set_active( mode ); + _direction_item->set_active(mode); _direction_item->focus_on_click(false); add(*_direction_item); @@ -646,7 +633,7 @@ void TextToolbar::text_outer_set_style(SPCSSAttr *css) // will set the style on selected text inside the <text> element. If we want to set // the style on the outer <text> objects we need to bypass this call. SPDesktop *desktop = _desktop; - if(_outer) { + if (_outer) { // Apply css to parent text objects directly. for (auto i : desktop->getSelection()->items()) { SPItem *item = dynamic_cast<SPItem *>(i); @@ -665,12 +652,11 @@ void TextToolbar::text_outer_set_style(SPCSSAttr *css) } } else { // Apply css to selected inner objects. - sp_desktop_set_style (desktop, css, true, false); + sp_desktop_set_style(desktop, css, true, false); } } -void -TextToolbar::fontfamily_value_changed() +void TextToolbar::fontfamily_value_changed() { #ifdef DEBUG_TEXT std::cout << std::endl; @@ -678,7 +664,7 @@ TextToolbar::fontfamily_value_changed() std::cout << "sp_text_fontfamily_value_changed: " << std::endl; #endif - // quit if run by the _changed callbacks + // quit if run by the _changed callbacks if (_freeze) { #ifdef DEBUG_TEXT std::cout << "sp_text_fontfamily_value_changed: frozen... return" << std::endl; @@ -691,69 +677,66 @@ TextToolbar::fontfamily_value_changed() gchar *temp_family = _font_family_item->get_active_text(); Glib::ustring new_family(temp_family); g_free(temp_family); - css_font_family_unquote( new_family ); // Remove quotes around font family names. + css_font_family_unquote(new_family); // Remove quotes around font family names. // TODO: Think about how to handle handle multiple selections. While // the font-family may be the same for all, the styles might be different. // See: TextEdit::onApply() for example of looping over selected items. - Inkscape::FontLister* fontlister = Inkscape::FontLister::get_instance(); + Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); #ifdef DEBUG_TEXT std::cout << " Old family: " << fontlister->get_font_family() << std::endl; std::cout << " New family: " << new_family << std::endl; std::cout << " Old active: " << fontlister->get_font_family_row() << std::endl; // std::cout << " New active: " << act->active << std::endl; #endif - if( new_family.compare( fontlister->get_font_family() ) != 0 ) { + if (new_family.compare(fontlister->get_font_family()) != 0) { // Changed font-family - if( _font_family_item->get_active() == -1 ) { + if (_font_family_item->get_active() == -1) { // New font-family, not in document, not on system (could be fallback list) - fontlister->insert_font_family( new_family ); + fontlister->insert_font_family(new_family); // This just sets a variable in the ComboBoxEntryAction object... // shouldn't we also set the actual active row in the combobox? _font_family_item->set_active(0); // New family is always at top of list. } - fontlister->set_font_family( _font_family_item->get_active() ); + fontlister->set_font_family(_font_family_item->get_active()); // active text set in sp_text_toolbox_selection_changed() - SPCSSAttr *css = sp_repr_css_attr_new (); - fontlister->fill_css( css ); + SPCSSAttr *css = sp_repr_css_attr_new(); + fontlister->fill_css(css); - SPDesktop *desktop = _desktop; - if( desktop->getSelection()->isEmpty() ) { + SPDesktop *desktop = _desktop; + if (desktop->getSelection()->isEmpty()) { // Update default Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->mergeStyle("/tools/text/style", css); } else { // If there is a selection, update - sp_desktop_set_style (desktop, css, true, true); // Results in selection change called twice. - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Text: Change font family")); + sp_desktop_set_style(desktop, css, true, true); // Results in selection change called twice. + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Text: Change font family")); } - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); } // unfreeze _freeze = false; #ifdef DEBUG_TEXT - std::cout << "sp_text_toolbox_fontfamily_changes: exit" << std::endl; + std::cout << "sp_text_toolbox_fontfamily_changes: exit" << std::endl; std::cout << "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" << std::endl; std::cout << std::endl; #endif } -GtkWidget * -TextToolbar::create(SPDesktop *desktop) +GtkWidget *TextToolbar::create(SPDesktop *desktop) { auto tb = Gtk::manage(new TextToolbar(desktop)); return GTK_WIDGET(tb->gobj()); } -void -TextToolbar::fontsize_value_changed() +void TextToolbar::fontsize_value_changed() { // quit if run by the _changed callbacks if (_freeze) { @@ -763,23 +746,24 @@ TextToolbar::fontsize_value_changed() gchar *text = _font_size_item->get_active_text(); gchar *endptr; - gdouble size = g_strtod( text, &endptr ); - if (endptr == text) { // Conversion failed, non-numeric input. - g_warning( "Conversion of size text to double failed, input: %s\n", text ); - g_free( text ); + gdouble size = g_strtod(text, &endptr); + if (endptr == text) { // Conversion failed, non-numeric input. + g_warning("Conversion of size text to double failed, input: %s\n", text); + g_free(text); _freeze = false; return; } - g_free( text ); + g_free(text); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - int max_size = prefs->getInt("/dialogs/textandfont/maxFontSize", 10000); // somewhat arbitrary, but text&font preview freezes with too huge fontsizes + int max_size = prefs->getInt("/dialogs/textandfont/maxFontSize", + 10000); // somewhat arbitrary, but text&font preview freezes with too huge fontsizes if (size > max_size) size = max_size; // Set css font size. - SPCSSAttr *css = sp_repr_css_attr_new (); + SPCSSAttr *css = sp_repr_css_attr_new(); Inkscape::CSSOStringStream osfs; int unit = prefs->getInt("/options/font/unitType", SP_CSS_UNIT_PT); if (prefs->getBool("/options/font/textOutputPx", true)) { @@ -787,7 +771,7 @@ TextToolbar::fontsize_value_changed() } else { osfs << size << sp_style_get_css_unit_string(unit); } - sp_repr_css_set_property (css, "font-size", osfs.str().c_str()); + sp_repr_css_set_property(css, "font-size", osfs.str().c_str()); double factor = size / selection_fontsize; // Apply font size to selected objects. @@ -803,17 +787,14 @@ TextToolbar::fontsize_value_changed() } // If no selected objects, set default. SPStyle query(_desktop->getDocument()); - int result_numbers = - sp_desktop_query_style (_desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); - if (result_numbers == QUERY_STYLE_NOTHING) - { + int result_numbers = sp_desktop_query_style(_desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); + if (result_numbers == QUERY_STYLE_NOTHING) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->mergeStyle("/tools/text/style", css); } else { // Save for undo - sp_desktop_set_style (_desktop, css, true, true); - DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:size", SP_VERB_NONE, - _("Text: Change font size")); + sp_desktop_set_style(_desktop, css, true, true); + DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:size", SP_VERB_NONE, _("Text: Change font size")); } sp_repr_css_attr_unref(css); @@ -821,8 +802,7 @@ TextToolbar::fontsize_value_changed() _freeze = false; } -void -TextToolbar::fontstyle_value_changed() +void TextToolbar::fontstyle_value_changed() { // quit if run by the _changed callbacks if (_freeze) { @@ -832,43 +812,37 @@ TextToolbar::fontstyle_value_changed() Glib::ustring new_style = _font_style_item->get_active_text(); - Inkscape::FontLister* fontlister = Inkscape::FontLister::get_instance(); - - if( new_style.compare( fontlister->get_font_style() ) != 0 ) { + Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); - fontlister->set_font_style( new_style ); + if (new_style.compare(fontlister->get_font_style()) != 0) { + fontlister->set_font_style(new_style); // active text set in sp_text_toolbox_seletion_changed() - SPCSSAttr *css = sp_repr_css_attr_new (); - fontlister->fill_css( css ); - - SPDesktop *desktop = _desktop; - sp_desktop_set_style (desktop, css, true, true); + SPCSSAttr *css = sp_repr_css_attr_new(); + fontlister->fill_css(css); + SPDesktop *desktop = _desktop; + sp_desktop_set_style(desktop, css, true, true); // If no selected objects, set default. SPStyle query(_desktop->getDocument()); - int result_style = - sp_desktop_query_style (desktop, &query, QUERY_STYLE_PROPERTY_FONTSTYLE); + int result_style = sp_desktop_query_style(desktop, &query, QUERY_STYLE_PROPERTY_FONTSTYLE); if (result_style == QUERY_STYLE_NOTHING) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->mergeStyle("/tools/text/style", css); } else { // Save for undo - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Text: Change font style")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Text: Change font style")); } - sp_repr_css_attr_unref (css); - + sp_repr_css_attr_unref(css); } _freeze = false; } // Handles both Superscripts and Subscripts -void -TextToolbar::script_changed(Gtk::ToggleToolButton *btn) +void TextToolbar::script_changed(Gtk::ToggleToolButton *btn) { // quit if run by the _changed callbacks if (_freeze) { @@ -887,66 +861,63 @@ TextToolbar::script_changed(Gtk::ToggleToolButton *btn) // Query baseline SPStyle query(_desktop->getDocument()); - int result_baseline = sp_desktop_query_style (_desktop, &query, QUERY_STYLE_PROPERTY_BASELINES); + int result_baseline = sp_desktop_query_style(_desktop, &query, QUERY_STYLE_PROPERTY_BASELINES); bool setSuper = false; - bool setSub = false; + bool setSub = false; if (Inkscape::is_query_style_updateable(result_baseline)) { // If not set or mixed, turn on superscript or subscript - if( prop == 0 ) { + if (prop == 0) { setSuper = true; } else { setSub = true; } } else { // Superscript - gboolean superscriptSet = (query.baseline_shift.set && - query.baseline_shift.type == SP_BASELINE_SHIFT_LITERAL && - query.baseline_shift.literal == SP_CSS_BASELINE_SHIFT_SUPER ); + gboolean superscriptSet = (query.baseline_shift.set && query.baseline_shift.type == SP_BASELINE_SHIFT_LITERAL && + query.baseline_shift.literal == SP_CSS_BASELINE_SHIFT_SUPER); // Subscript - gboolean subscriptSet = (query.baseline_shift.set && - query.baseline_shift.type == SP_BASELINE_SHIFT_LITERAL && - query.baseline_shift.literal == SP_CSS_BASELINE_SHIFT_SUB ); + gboolean subscriptSet = (query.baseline_shift.set && query.baseline_shift.type == SP_BASELINE_SHIFT_LITERAL && + query.baseline_shift.literal == SP_CSS_BASELINE_SHIFT_SUB); setSuper = !superscriptSet && prop == 0; - setSub = !subscriptSet && prop == 1; + setSub = !subscriptSet && prop == 1; } // Set css properties - SPCSSAttr *css = sp_repr_css_attr_new (); - if( setSuper || setSub ) { + SPCSSAttr *css = sp_repr_css_attr_new(); + if (setSuper || setSub) { // Openoffice 2.3 and Adobe use 58%, Microsoft Word 2002 uses 65%, LaTex about 70%. // 58% looks too small to me, especially if a superscript is placed on a superscript. // If you make a change here, consider making a change to baseline-shift amount // in style.cpp. - sp_repr_css_set_property (css, "font-size", "65%"); + sp_repr_css_set_property(css, "font-size", "65%"); } else { - sp_repr_css_set_property (css, "font-size", ""); + sp_repr_css_set_property(css, "font-size", ""); } - if( setSuper ) { - sp_repr_css_set_property (css, "baseline-shift", "super"); - } else if( setSub ) { - sp_repr_css_set_property (css, "baseline-shift", "sub"); + if (setSuper) { + sp_repr_css_set_property(css, "baseline-shift", "super"); + } else if (setSub) { + sp_repr_css_set_property(css, "baseline-shift", "sub"); } else { - sp_repr_css_set_property (css, "baseline-shift", "baseline"); + sp_repr_css_set_property(css, "baseline-shift", "baseline"); } // Apply css to selected objects. SPDesktop *desktop = _desktop; - sp_desktop_set_style (desktop, css, true, false); + sp_desktop_set_style(desktop, css, true, false); // Save for undo - if(result_baseline != QUERY_STYLE_NOTHING) { + if (result_baseline != QUERY_STYLE_NOTHING) { DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:script", SP_VERB_NONE, - _("Text: Change superscript or subscript")); + _("Text: Change superscript or subscript")); } _freeze = false; } -void -TextToolbar::align_mode_changed(int mode) +void TextToolbar::align_mode_changed(int mode) { // quit if run by the _changed callbacks if (_freeze) { @@ -961,7 +932,7 @@ TextToolbar::align_mode_changed(int mode) // move the x of all texts to preserve the same bbox Inkscape::Selection *selection = desktop->getSelection(); - auto itemlist= selection->items(); + auto itemlist = selection->items(); for (auto i : itemlist) { SPText *text = dynamic_cast<SPText *>(i); // SPFlowtext *flowtext = dynamic_cast<SPFlowtext *>(i); @@ -995,7 +966,7 @@ TextToolbar::align_mode_changed(int mode) move = -left_slack; break; case 1: - move = width/2 + (right_slack - left_slack)/2; + move = width / 2 + (right_slack - left_slack) / 2; break; case 2: move = width + right_slack; @@ -1004,13 +975,13 @@ TextToolbar::align_mode_changed(int mode) } else if (old_align == SP_CSS_TEXT_ALIGN_CENTER) { switch (mode) { case 0: - move = -width/2 - left_slack; + move = -width / 2 - left_slack; break; case 1: - move = (right_slack - left_slack)/2; + move = (right_slack - left_slack) / 2; break; case 2: - move = width/2 + right_slack; + move = width / 2 + right_slack; break; } } else if (old_align == SP_CSS_TEXT_ALIGN_END || old_align == SP_CSS_TEXT_ALIGN_RIGHT) { @@ -1019,7 +990,7 @@ TextToolbar::align_mode_changed(int mode) move = -width - left_slack; break; case 1: - move = -width/2 + (right_slack - left_slack)/2; + move = -width / 2 + (right_slack - left_slack) / 2; break; case 2: move = right_slack; @@ -1028,9 +999,9 @@ TextToolbar::align_mode_changed(int mode) } Geom::Point XY = SP_TEXT(item)->attributes.firstXY(); if (axis == Geom::X) { - XY = XY + Geom::Point (move, 0); + XY = XY + Geom::Point(move, 0); } else { - XY = XY + Geom::Point (0, move); + XY = XY + Geom::Point(0, move); } SP_TEXT(item)->attributes.setFirstXY(XY); item->updateRepr(); @@ -1038,63 +1009,53 @@ TextToolbar::align_mode_changed(int mode) } } - SPCSSAttr *css = sp_repr_css_attr_new (); - switch (mode) - { - case 0: - { - sp_repr_css_set_property (css, "text-anchor", "start"); - sp_repr_css_set_property (css, "text-align", "start"); + SPCSSAttr *css = sp_repr_css_attr_new(); + switch (mode) { + case 0: { + sp_repr_css_set_property(css, "text-anchor", "start"); + sp_repr_css_set_property(css, "text-align", "start"); break; } - case 1: - { - sp_repr_css_set_property (css, "text-anchor", "middle"); - sp_repr_css_set_property (css, "text-align", "center"); + case 1: { + sp_repr_css_set_property(css, "text-anchor", "middle"); + sp_repr_css_set_property(css, "text-align", "center"); break; } - case 2: - { - sp_repr_css_set_property (css, "text-anchor", "end"); - sp_repr_css_set_property (css, "text-align", "end"); + case 2: { + sp_repr_css_set_property(css, "text-anchor", "end"); + sp_repr_css_set_property(css, "text-align", "end"); break; } - case 3: - { - sp_repr_css_set_property (css, "text-anchor", "start"); - sp_repr_css_set_property (css, "text-align", "justify"); + case 3: { + sp_repr_css_set_property(css, "text-anchor", "start"); + sp_repr_css_set_property(css, "text-align", "justify"); break; } } SPStyle query(_desktop->getDocument()); - int result_numbers = - sp_desktop_query_style (_desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); + int result_numbers = sp_desktop_query_style(_desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); // If querying returned nothing, update default style. - if (result_numbers == QUERY_STYLE_NOTHING) - { + if (result_numbers == QUERY_STYLE_NOTHING) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->mergeStyle("/tools/text/style", css); } - sp_desktop_set_style (desktop, css, true, true); - if (result_numbers != QUERY_STYLE_NOTHING) - { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Text: Change alignment")); + sp_desktop_set_style(desktop, css, true, true); + if (result_numbers != QUERY_STYLE_NOTHING) { + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Text: Change alignment")); } - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); desktop->getCanvas()->grab_focus(); _freeze = false; } -void -TextToolbar::writing_mode_changed(int mode) +void TextToolbar::writing_mode_changed(int mode) { // quit if run by the _changed callbacks if (_freeze) { @@ -1102,54 +1063,45 @@ TextToolbar::writing_mode_changed(int mode) } _freeze = true; - SPCSSAttr *css = sp_repr_css_attr_new (); - switch (mode) - { - case 0: - { - sp_repr_css_set_property (css, "writing-mode", "lr-tb"); - break; - } + SPCSSAttr *css = sp_repr_css_attr_new(); + switch (mode) { + case 0: { + sp_repr_css_set_property(css, "writing-mode", "lr-tb"); + break; + } - case 1: - { - sp_repr_css_set_property (css, "writing-mode", "tb-rl"); - break; - } + case 1: { + sp_repr_css_set_property(css, "writing-mode", "tb-rl"); + break; + } - case 2: - { - sp_repr_css_set_property (css, "writing-mode", "vertical-lr"); - break; - } + case 2: { + sp_repr_css_set_property(css, "writing-mode", "vertical-lr"); + break; + } } SPStyle query(_desktop->getDocument()); - int result_numbers = - sp_desktop_query_style (_desktop, &query, QUERY_STYLE_PROPERTY_WRITINGMODES); + int result_numbers = sp_desktop_query_style(_desktop, &query, QUERY_STYLE_PROPERTY_WRITINGMODES); // If querying returned nothing, update default style. - if (result_numbers == QUERY_STYLE_NOTHING) - { + if (result_numbers == QUERY_STYLE_NOTHING) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->mergeStyle("/tools/text/style", css); } - sp_desktop_set_style (_desktop, css, true, true); - if(result_numbers != QUERY_STYLE_NOTHING) - { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Text: Change writing mode")); + sp_desktop_set_style(_desktop, css, true, true); + if (result_numbers != QUERY_STYLE_NOTHING) { + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Text: Change writing mode")); } - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); _desktop->getCanvas()->grab_focus(); _freeze = false; } -void -TextToolbar::orientation_changed(int mode) +void TextToolbar::orientation_changed(int mode) { // quit if run by the _changed callbacks if (_freeze) { @@ -1157,53 +1109,44 @@ TextToolbar::orientation_changed(int mode) } _freeze = true; - SPCSSAttr *css = sp_repr_css_attr_new (); - switch (mode) - { - case 0: - { - sp_repr_css_set_property (css, "text-orientation", "auto"); + SPCSSAttr *css = sp_repr_css_attr_new(); + switch (mode) { + case 0: { + sp_repr_css_set_property(css, "text-orientation", "auto"); break; } - case 1: - { - sp_repr_css_set_property (css, "text-orientation", "upright"); + case 1: { + sp_repr_css_set_property(css, "text-orientation", "upright"); break; } - case 2: - { - sp_repr_css_set_property (css, "text-orientation", "sideways"); + case 2: { + sp_repr_css_set_property(css, "text-orientation", "sideways"); break; } } SPStyle query(_desktop->getDocument()); - int result_numbers = - sp_desktop_query_style (_desktop, &query, QUERY_STYLE_PROPERTY_WRITINGMODES); + int result_numbers = sp_desktop_query_style(_desktop, &query, QUERY_STYLE_PROPERTY_WRITINGMODES); // If querying returned nothing, update default style. - if (result_numbers == QUERY_STYLE_NOTHING) - { + if (result_numbers == QUERY_STYLE_NOTHING) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->mergeStyle("/tools/text/style", css); } - sp_desktop_set_style (_desktop, css, true, true); - if(result_numbers != QUERY_STYLE_NOTHING) - { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Text: Change orientation")); + sp_desktop_set_style(_desktop, css, true, true); + if (result_numbers != QUERY_STYLE_NOTHING) { + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Text: Change orientation")); } - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); _desktop->canvas->grab_focus(); _freeze = false; } -void -TextToolbar::direction_changed(int mode) +void TextToolbar::direction_changed(int mode) { // quit if run by the _changed callbacks if (_freeze) { @@ -1211,54 +1154,46 @@ TextToolbar::direction_changed(int mode) } _freeze = true; - SPCSSAttr *css = sp_repr_css_attr_new (); - switch (mode) - { - case 0: - { - sp_repr_css_set_property (css, "direction", "ltr"); + SPCSSAttr *css = sp_repr_css_attr_new(); + switch (mode) { + case 0: { + sp_repr_css_set_property(css, "direction", "ltr"); break; } - case 1: - { - sp_repr_css_set_property (css, "direction", "rtl"); + case 1: { + sp_repr_css_set_property(css, "direction", "rtl"); break; } } SPStyle query(_desktop->getDocument()); - int result_numbers = - sp_desktop_query_style (_desktop, &query, QUERY_STYLE_PROPERTY_WRITINGMODES); + int result_numbers = sp_desktop_query_style(_desktop, &query, QUERY_STYLE_PROPERTY_WRITINGMODES); // If querying returned nothing, update default style. - if (result_numbers == QUERY_STYLE_NOTHING) - { + if (result_numbers == QUERY_STYLE_NOTHING) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->mergeStyle("/tools/text/style", css); } - sp_desktop_set_style (_desktop, css, true, true); - if(result_numbers != QUERY_STYLE_NOTHING) - { - DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Text: Change direction")); + sp_desktop_set_style(_desktop, css, true, true); + if (result_numbers != QUERY_STYLE_NOTHING) { + DocumentUndo::done(_desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Text: Change direction")); } - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); _desktop->getCanvas()->grab_focus(); _freeze = false; } -void -TextToolbar::lineheight_value_changed() +void TextToolbar::lineheight_value_changed() { // quit if run by the _changed callbacks or is not text tool if (_freeze || !SP_IS_TEXT_CONTEXT(_desktop->event_context)) { return; } - + _freeze = true; SPDesktop *desktop = _desktop; // Get user selected unit and save as preference @@ -1270,16 +1205,16 @@ TextToolbar::lineheight_value_changed() // we can save it (allows us to adjust line height value when unit changes). // Set css line height. - SPCSSAttr *css = sp_repr_css_attr_new (); + SPCSSAttr *css = sp_repr_css_attr_new(); Inkscape::CSSOStringStream osfs; - if ( is_relative(unit) ) { + if (is_relative(unit)) { osfs << _line_height_adj->get_value() << unit->abbr; } else { // Inside SVG file, always use "px" for absolute units. osfs << Quantity::convert(_line_height_adj->get_value(), unit, "px") << "px"; } - sp_repr_css_set_property (css, "line-height", osfs.str().c_str()); + sp_repr_css_set_property(css, "line-height", osfs.str().c_str()); Inkscape::Selection *selection = desktop->getSelection(); auto itemlist = selection->items(); @@ -1349,19 +1284,17 @@ TextToolbar::lineheight_value_changed() // If no selected objects, set default. SPStyle query(_desktop->getDocument()); int result_numbers = sp_desktop_query_style(desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); - if (result_numbers == QUERY_STYLE_NOTHING) - { + if (result_numbers == QUERY_STYLE_NOTHING) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->mergeStyle("/tools/text/style", css); } - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); _freeze = false; } -void -TextToolbar::lineheight_unit_changed(int /* Not Used */) +void TextToolbar::lineheight_unit_changed(int /* Not Used */) { // quit if run by the _changed callbacks or is not text tool if (_freeze || !SP_IS_TEXT_CONTEXT(_desktop->event_context)) { @@ -1433,7 +1366,8 @@ TextToolbar::lineheight_unit_changed(int /* Not Used */) line_height *= 50; } else if (is_relative(unit)) { // Convert absolute to relative... for the moment use average font-size - if (old_unit == SP_CSS_UNIT_NONE) old_unit = SP_CSS_UNIT_EM; + if (old_unit == SP_CSS_UNIT_NONE) + old_unit = SP_CSS_UNIT_EM; line_height = Quantity::convert(line_height, sp_style_get_css_unit_string(old_unit), "px"); if (font_size > 0) { @@ -1445,7 +1379,7 @@ TextToolbar::lineheight_unit_changed(int /* Not Used */) line_height *= 2; } } else if (old_unit == SP_CSS_UNIT_NONE || old_unit == SP_CSS_UNIT_PERCENT || old_unit == SP_CSS_UNIT_EM || - old_unit == SP_CSS_UNIT_EX) { + old_unit == SP_CSS_UNIT_EX) { // Convert relative to absolute... for the moment use average font-size if (old_unit == SP_CSS_UNIT_PERCENT) { line_height /= 100.0; @@ -1459,15 +1393,15 @@ TextToolbar::lineheight_unit_changed(int /* Not Used */) line_height = Quantity::convert(line_height, sp_style_get_css_unit_string(old_unit), unit); } // Set css line height. - SPCSSAttr *css = sp_repr_css_attr_new (); + SPCSSAttr *css = sp_repr_css_attr_new(); Inkscape::CSSOStringStream osfs; // Set css line height. - if ( is_relative(unit) ) { + if (is_relative(unit)) { osfs << line_height << unit->abbr; } else { osfs << Quantity::convert(line_height, unit, "px") << "px"; } - sp_repr_css_set_property (css, "line-height", osfs.str().c_str()); + sp_repr_css_set_property(css, "line-height", osfs.str().c_str()); // Update GUI with line_height value. _line_height_adj->set_value(line_height); @@ -1532,7 +1466,7 @@ TextToolbar::lineheight_unit_changed(int /* Not Used */) subselection_wrap_toggle(false); sp_repr_css_attr_unref(cssfit); } - itemlist= selection->items(); + itemlist = selection->items(); // Only need to save for undo if a text item has been changed. bool modmade = false; for (auto i : itemlist) { @@ -1544,7 +1478,7 @@ TextToolbar::lineheight_unit_changed(int /* Not Used */) } } // Save for undo - if(modmade) { + if (modmade) { // Call ensureUpToDate() causes rebuild of text layout (with all proper style // cascading, etc.). For multi-line text with sodipodi::role="line", we must explicitly // save new <tspan> 'x' and 'y' attribute values by calling updateRepr(). @@ -1562,20 +1496,18 @@ TextToolbar::lineheight_unit_changed(int /* Not Used */) prepare_inner(); } DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:line-height", SP_VERB_NONE, - _("Text: Change line-height unit")); + _("Text: Change line-height unit")); } // If no selected objects, set default. SPStyle query(_desktop->getDocument()); - int result_numbers = - sp_desktop_query_style (_desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); - if (result_numbers == QUERY_STYLE_NOTHING) - { + int result_numbers = sp_desktop_query_style(_desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); + if (result_numbers == QUERY_STYLE_NOTHING) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->mergeStyle("/tools/text/style", css); } - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); _freeze = false; } @@ -1596,8 +1528,7 @@ void TextToolbar::fontsize_unit_changed(int /* Not Used */) selection_changed(_desktop->selection); } -void -TextToolbar::wordspacing_value_changed() +void TextToolbar::wordspacing_value_changed() { // quit if run by the _changed callbacks if (_freeze) { @@ -1607,33 +1538,30 @@ TextToolbar::wordspacing_value_changed() // At the moment this handles only numerical values (i.e. no em unit). // Set css word-spacing - SPCSSAttr *css = sp_repr_css_attr_new (); + SPCSSAttr *css = sp_repr_css_attr_new(); Inkscape::CSSOStringStream osfs; osfs << _word_spacing_adj->get_value() << "px"; // For now always use px - sp_repr_css_set_property (css, "word-spacing", osfs.str().c_str()); + sp_repr_css_set_property(css, "word-spacing", osfs.str().c_str()); text_outer_set_style(css); // If no selected objects, set default. SPStyle query(_desktop->getDocument()); - int result_numbers = - sp_desktop_query_style (_desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); - if (result_numbers == QUERY_STYLE_NOTHING) - { + int result_numbers = sp_desktop_query_style(_desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); + if (result_numbers == QUERY_STYLE_NOTHING) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->mergeStyle("/tools/text/style", css); } else { // Save for undo DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:word-spacing", SP_VERB_NONE, - _("Text: Change word-spacing")); + _("Text: Change word-spacing")); } - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); _freeze = false; } -void -TextToolbar::letterspacing_value_changed() +void TextToolbar::letterspacing_value_changed() { // quit if run by the _changed callbacks if (_freeze) { @@ -1643,35 +1571,30 @@ TextToolbar::letterspacing_value_changed() // At the moment this handles only numerical values (i.e. no em unit). // Set css letter-spacing - SPCSSAttr *css = sp_repr_css_attr_new (); + SPCSSAttr *css = sp_repr_css_attr_new(); Inkscape::CSSOStringStream osfs; - osfs << _letter_spacing_adj->get_value() << "px"; // For now always use px - sp_repr_css_set_property (css, "letter-spacing", osfs.str().c_str()); + osfs << _letter_spacing_adj->get_value() << "px"; // For now always use px + sp_repr_css_set_property(css, "letter-spacing", osfs.str().c_str()); text_outer_set_style(css); // If no selected objects, set default. SPStyle query(_desktop->getDocument()); - int result_numbers = - sp_desktop_query_style (_desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); - if (result_numbers == QUERY_STYLE_NOTHING) - { + int result_numbers = sp_desktop_query_style(_desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); + if (result_numbers == QUERY_STYLE_NOTHING) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->mergeStyle("/tools/text/style", css); - } - else - { + } else { // Save for undo DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:letter-spacing", SP_VERB_NONE, - _("Text: Change letter-spacing")); + _("Text: Change letter-spacing")); } - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); _freeze = false; } -void -TextToolbar::dx_value_changed() +void TextToolbar::dx_value_changed() { // quit if run by the _changed callbacks if (_freeze) { @@ -1682,31 +1605,29 @@ TextToolbar::dx_value_changed() gdouble new_dx = _dx_adj->get_value(); bool modmade = false; - if( SP_IS_TEXT_CONTEXT(_desktop->event_context) ) { + if (SP_IS_TEXT_CONTEXT(_desktop->event_context)) { Inkscape::UI::Tools::TextTool *const tc = SP_TEXT_CONTEXT(_desktop->event_context); - if( tc ) { + if (tc) { unsigned char_index = -1; TextTagAttributes *attributes = - text_tag_attributes_at_position( tc->text, std::min(tc->text_sel_start, tc->text_sel_end), &char_index ); - if( attributes ) { - double old_dx = attributes->getDx( char_index ); + text_tag_attributes_at_position(tc->text, std::min(tc->text_sel_start, tc->text_sel_end), &char_index); + if (attributes) { + double old_dx = attributes->getDx(char_index); double delta_dx = new_dx - old_dx; - sp_te_adjust_dx( tc->text, tc->text_sel_start, tc->text_sel_end, _desktop, delta_dx ); + sp_te_adjust_dx(tc->text, tc->text_sel_start, tc->text_sel_end, _desktop, delta_dx); modmade = true; } } } - if(modmade) { + if (modmade) { // Save for undo - DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:dx", SP_VERB_NONE, - _("Text: Change dx (kern)")); + DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:dx", SP_VERB_NONE, _("Text: Change dx (kern)")); } _freeze = false; } -void -TextToolbar::dy_value_changed() +void TextToolbar::dy_value_changed() { // quit if run by the _changed callbacks if (_freeze) { @@ -1717,32 +1638,30 @@ TextToolbar::dy_value_changed() gdouble new_dy = _dy_adj->get_value(); bool modmade = false; - if( SP_IS_TEXT_CONTEXT(_desktop->event_context) ) { + if (SP_IS_TEXT_CONTEXT(_desktop->event_context)) { Inkscape::UI::Tools::TextTool *const tc = SP_TEXT_CONTEXT(_desktop->event_context); - if( tc ) { + if (tc) { unsigned char_index = -1; TextTagAttributes *attributes = - text_tag_attributes_at_position( tc->text, std::min(tc->text_sel_start, tc->text_sel_end), &char_index ); - if( attributes ) { - double old_dy = attributes->getDy( char_index ); + text_tag_attributes_at_position(tc->text, std::min(tc->text_sel_start, tc->text_sel_end), &char_index); + if (attributes) { + double old_dy = attributes->getDy(char_index); double delta_dy = new_dy - old_dy; - sp_te_adjust_dy( tc->text, tc->text_sel_start, tc->text_sel_end, _desktop, delta_dy ); + sp_te_adjust_dy(tc->text, tc->text_sel_start, tc->text_sel_end, _desktop, delta_dy); modmade = true; } } } - if(modmade) { + if (modmade) { // Save for undo - DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:dy", SP_VERB_NONE, - _("Text: Change dy")); + DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:dy", SP_VERB_NONE, _("Text: Change dy")); } _freeze = false; } -void -TextToolbar::rotation_value_changed() +void TextToolbar::rotation_value_changed() { // quit if run by the _changed callbacks if (_freeze) { @@ -1753,25 +1672,24 @@ TextToolbar::rotation_value_changed() gdouble new_degrees = _rotation_adj->get_value(); bool modmade = false; - if( SP_IS_TEXT_CONTEXT(_desktop->event_context) ) { + if (SP_IS_TEXT_CONTEXT(_desktop->event_context)) { Inkscape::UI::Tools::TextTool *const tc = SP_TEXT_CONTEXT(_desktop->event_context); - if( tc ) { + if (tc) { unsigned char_index = -1; TextTagAttributes *attributes = - text_tag_attributes_at_position( tc->text, std::min(tc->text_sel_start, tc->text_sel_end), &char_index ); - if( attributes ) { - double old_degrees = attributes->getRotate( char_index ); + text_tag_attributes_at_position(tc->text, std::min(tc->text_sel_start, tc->text_sel_end), &char_index); + if (attributes) { + double old_degrees = attributes->getRotate(char_index); double delta_deg = new_degrees - old_degrees; - sp_te_adjust_rotation( tc->text, tc->text_sel_start, tc->text_sel_end, _desktop, delta_deg ); + sp_te_adjust_rotation(tc->text, tc->text_sel_start, tc->text_sel_end, _desktop, delta_deg); modmade = true; } } } // Save for undo - if(modmade) { - DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:rotate", SP_VERB_NONE, - _("Text: Change rotate")); + if (modmade) { + DocumentUndo::maybeDone(_desktop->getDocument(), "ttb:rotate", SP_VERB_NONE, _("Text: Change rotate")); } _freeze = false; @@ -1796,7 +1714,7 @@ void TextToolbar::selection_modified_select_tool(Inkscape::Selection *selection, } void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bother to update font list if subsel - // changed + // changed { #ifdef DEBUG_TEXT static int count = 0; @@ -1808,7 +1726,6 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot // quit if run by the _changed callbacks if (_freeze) { - #ifdef DEBUG_TEXT std::cout << " Frozen, returning" << std::endl; std::cout << "sp_text_toolbox_selection_changed: exit " << count << std::endl; @@ -1826,8 +1743,8 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot auto itemlist = selection->items(); #ifdef DEBUG_TEXT - for(auto i : itemlist) { - const gchar* id = i->getId(); + for (auto i : itemlist) { + const gchar *id = i->getId(); std::cout << " " << id << std::endl; } Glib::ustring selected_text = sp_text_get_selected_text(_desktop->event_context); @@ -1844,8 +1761,7 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot if (text || flowtext) { to_work.push_back(i); } - if (flowtext || - (text && text->style && text->style->shape_inside.set)) { + if (flowtext || (text && text->style && text->style->shape_inside.set)) { isFlow = true; } } @@ -1885,11 +1801,10 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot int result_numbers_fallback = 0; if (!outside) { if (_outer && this->_sub_active_item) { - std::vector<SPItem *> qactive{ this->_sub_active_item }; + std::vector<SPItem *> qactive{this->_sub_active_item}; SPItem *parent = dynamic_cast<SPItem *>(this->_sub_active_item->parent); - std::vector<SPItem *> qparent{ parent }; - result_numbers = - sp_desktop_query_style_from_list(qactive, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); + std::vector<SPItem *> qparent{parent}; + result_numbers = sp_desktop_query_style_from_list(qactive, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); result_numbers_fallback = sp_desktop_query_style_from_list(qparent, &query_fallback, QUERY_STYLE_PROPERTY_FONTNUMBERS); } else if (_outer) { @@ -1898,30 +1813,27 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot result_numbers = sp_desktop_query_style(desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); } } else { - result_numbers = - sp_desktop_query_style(desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); + result_numbers = sp_desktop_query_style(desktop, &query, QUERY_STYLE_PROPERTY_FONTNUMBERS); } - + /* * If no text in selection (querying returned nothing), read the style from * the /tools/text preferences (default style for new texts). Return if * tool bar already set to these preferences. */ - if (result_family == QUERY_STYLE_NOTHING || - result_style == QUERY_STYLE_NOTHING || - result_numbers == QUERY_STYLE_NOTHING || - result_wmode == QUERY_STYLE_NOTHING ) { + if (result_family == QUERY_STYLE_NOTHING || result_style == QUERY_STYLE_NOTHING || + result_numbers == QUERY_STYLE_NOTHING || result_wmode == QUERY_STYLE_NOTHING) { // There are no texts in selection, read from preferences. query.readFromPrefs("/tools/text"); #ifdef DEBUG_TEXT std::cout << " read style from prefs:" << std::endl; - sp_print_font( &query ); + sp_print_font(&query); #endif if (_text_style_from_prefs) { // Do not reset the toolbar style from prefs if we already did it last time _freeze = false; #ifdef DEBUG_TEXT - std::cout << " text_style_from_prefs: toolbar already set" << std:: endl; + std::cout << " text_style_from_prefs: toolbar already set" << std::endl; std::cout << "sp_text_toolbox_selection_changed: exit " << count << std::endl; std::cout << "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&" << std::endl; std::cout << std::endl; @@ -1931,7 +1843,7 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot // To ensure the value of the combobox is properly set on start-up, only mark // the prefs set if the combobox has already been constructed. - if( _font_family_item->get_combobox() != nullptr ) { + if (_font_family_item->get_combobox() != nullptr) { _text_style_from_prefs = true; } } else { @@ -1954,7 +1866,7 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot if (!size && result_numbers_fallback != QUERY_STYLE_NOTHING) { size = sp_style_css_size_px_to_units(query_fallback.font_size.computed, unit); } - + auto unit_str = sp_style_get_css_unit_string(unit); Glib::ustring tooltip = Glib::ustring::format(_("Font size"), " (", unit_str, ")"); @@ -1965,8 +1877,9 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot _tracker_fs->setActiveUnitByAbbr(sp_style_get_css_unit_string(unit)); int rounded_size = std::round(size); - if (std::abs((size - rounded_size)/size) < 0.0001) { - // We use rounded_size to avoid rounding errors when, say, converting stored 'px' values to displayed 'pt' values. + if (std::abs((size - rounded_size) / size) < 0.0001) { + // We use rounded_size to avoid rounding errors when, say, converting stored 'px' values to displayed 'pt' + // values. os << rounded_size; selection_fontsize = rounded_size; } else { @@ -1975,27 +1888,25 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot } // Freeze to ignore callbacks. - //g_object_freeze_notify( G_OBJECT( fontSizeAction->combobox ) ); + // g_object_freeze_notify( G_OBJECT( fontSizeAction->combobox ) ); sp_text_set_sizes(GTK_LIST_STORE(_font_size_item->get_model()), unit); - //g_object_thaw_notify( G_OBJECT( fontSizeAction->combobox ) ); + // g_object_thaw_notify( G_OBJECT( fontSizeAction->combobox ) ); - _font_size_item->set_active_text( os.str().c_str() ); + _font_size_item->set_active_text(os.str().c_str()); // Superscript gboolean superscriptSet = - ((result_baseline == QUERY_STYLE_SINGLE || result_baseline == QUERY_STYLE_MULTIPLE_SAME ) && - query.baseline_shift.set && - query.baseline_shift.type == SP_BASELINE_SHIFT_LITERAL && - query.baseline_shift.literal == SP_CSS_BASELINE_SHIFT_SUPER ); + ((result_baseline == QUERY_STYLE_SINGLE || result_baseline == QUERY_STYLE_MULTIPLE_SAME) && + query.baseline_shift.set && query.baseline_shift.type == SP_BASELINE_SHIFT_LITERAL && + query.baseline_shift.literal == SP_CSS_BASELINE_SHIFT_SUPER); _superscript_item->set_active(superscriptSet); // Subscript gboolean subscriptSet = - ((result_baseline == QUERY_STYLE_SINGLE || result_baseline == QUERY_STYLE_MULTIPLE_SAME ) && - query.baseline_shift.set && - query.baseline_shift.type == SP_BASELINE_SHIFT_LITERAL && - query.baseline_shift.literal == SP_CSS_BASELINE_SHIFT_SUB ); + ((result_baseline == QUERY_STYLE_SINGLE || result_baseline == QUERY_STYLE_MULTIPLE_SAME) && + query.baseline_shift.set && query.baseline_shift.type == SP_BASELINE_SHIFT_LITERAL && + query.baseline_shift.literal == SP_CSS_BASELINE_SHIFT_SUB); _subscript_item->set_active(subscriptSet); @@ -2007,21 +1918,23 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot // Disable button if we don't have flowed text. Glib::RefPtr<Gtk::ListStore> store = _align_item->get_store(); - Gtk::TreeModel::Row row = *(store->get_iter("3")); // Justify entry + Gtk::TreeModel::Row row = *(store->get_iter("3")); // Justify entry UI::Widget::ComboToolItemColumns columns; row[columns.col_sensitive] = isFlow; int activeButton = 0; - if (query.text_align.computed == SP_CSS_TEXT_ALIGN_JUSTIFY) - { + if (query.text_align.computed == SP_CSS_TEXT_ALIGN_JUSTIFY) { activeButton = 3; } else { // This should take 'direction' into account - if (query.text_anchor.computed == SP_CSS_TEXT_ANCHOR_START) activeButton = 0; - if (query.text_anchor.computed == SP_CSS_TEXT_ANCHOR_MIDDLE) activeButton = 1; - if (query.text_anchor.computed == SP_CSS_TEXT_ANCHOR_END) activeButton = 2; + if (query.text_anchor.computed == SP_CSS_TEXT_ANCHOR_START) + activeButton = 0; + if (query.text_anchor.computed == SP_CSS_TEXT_ANCHOR_MIDDLE) + activeButton = 1; + if (query.text_anchor.computed == SP_CSS_TEXT_ANCHOR_END) + activeButton = 2; } - _align_item->set_active( activeButton ); + _align_item->set_active(activeButton); double height = 0; gint line_height_unit = 0; @@ -2058,7 +1971,6 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot } _line_height_adj->set_value(height); - // Update "climb rate" if (line_height_unit == SP_CSS_UNIT_PERCENT) { _line_height_adj->set_step_increment(1.0); @@ -2068,7 +1980,7 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot _line_height_adj->set_page_increment(1.0); } - if( line_height_unit == SP_CSS_UNIT_NONE ) { + if (line_height_unit == SP_CSS_UNIT_NONE) { // Function 'sp_style_get_css_unit_string' returns 'px' for unit none. // We need to avoid this. _tracker->setActiveUnitByAbbr(""); @@ -2080,84 +1992,96 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot _lineheight_unit = line_height_unit; // Word spacing double wordSpacing; - if (query.word_spacing.normal) wordSpacing = 0.0; - else wordSpacing = query.word_spacing.computed; // Assume no units (change in desktop-style.cpp) + if (query.word_spacing.normal) + wordSpacing = 0.0; + else + wordSpacing = query.word_spacing.computed; // Assume no units (change in desktop-style.cpp) _word_spacing_adj->set_value(wordSpacing); // Letter spacing double letterSpacing; - if (query.letter_spacing.normal) letterSpacing = 0.0; - else letterSpacing = query.letter_spacing.computed; // Assume no units (change in desktop-style.cpp) + if (query.letter_spacing.normal) + letterSpacing = 0.0; + else + letterSpacing = query.letter_spacing.computed; // Assume no units (change in desktop-style.cpp) _letter_spacing_adj->set_value(letterSpacing); // Writing mode int activeButton2 = 0; - if (query.writing_mode.computed == SP_CSS_WRITING_MODE_LR_TB) activeButton2 = 0; - if (query.writing_mode.computed == SP_CSS_WRITING_MODE_TB_RL) activeButton2 = 1; - if (query.writing_mode.computed == SP_CSS_WRITING_MODE_TB_LR) activeButton2 = 2; + if (query.writing_mode.computed == SP_CSS_WRITING_MODE_LR_TB) + activeButton2 = 0; + if (query.writing_mode.computed == SP_CSS_WRITING_MODE_TB_RL) + activeButton2 = 1; + if (query.writing_mode.computed == SP_CSS_WRITING_MODE_TB_LR) + activeButton2 = 2; - _writing_mode_item->set_active( activeButton2 ); + _writing_mode_item->set_active(activeButton2); // Orientation int activeButton3 = 0; - if (query.text_orientation.computed == SP_CSS_TEXT_ORIENTATION_MIXED ) activeButton3 = 0; - if (query.text_orientation.computed == SP_CSS_TEXT_ORIENTATION_UPRIGHT ) activeButton3 = 1; - if (query.text_orientation.computed == SP_CSS_TEXT_ORIENTATION_SIDEWAYS) activeButton3 = 2; + if (query.text_orientation.computed == SP_CSS_TEXT_ORIENTATION_MIXED) + activeButton3 = 0; + if (query.text_orientation.computed == SP_CSS_TEXT_ORIENTATION_UPRIGHT) + activeButton3 = 1; + if (query.text_orientation.computed == SP_CSS_TEXT_ORIENTATION_SIDEWAYS) + activeButton3 = 2; - _orientation_item->set_active( activeButton3 ); + _orientation_item->set_active(activeButton3); // Disable text orientation for horizontal text... - _orientation_item->set_sensitive( activeButton2 != 0 ); + _orientation_item->set_sensitive(activeButton2 != 0); // Direction int activeButton4 = 0; - if (query.direction.computed == SP_CSS_DIRECTION_LTR ) activeButton4 = 0; - if (query.direction.computed == SP_CSS_DIRECTION_RTL ) activeButton4 = 1; - _direction_item->set_active( activeButton4 ); + if (query.direction.computed == SP_CSS_DIRECTION_LTR) + activeButton4 = 0; + if (query.direction.computed == SP_CSS_DIRECTION_RTL) + activeButton4 = 1; + _direction_item->set_active(activeButton4); } #ifdef DEBUG_TEXT - std::cout << " GUI: fontfamily.value: " << query.font_family.value() << std::endl; - std::cout << " GUI: font_size.computed: " << query.font_size.computed << std::endl; + std::cout << " GUI: fontfamily.value: " << query.font_family.value() << std::endl; + std::cout << " GUI: font_size.computed: " << query.font_size.computed << std::endl; std::cout << " GUI: font_weight.computed: " << query.font_weight.computed << std::endl; - std::cout << " GUI: font_style.computed: " << query.font_style.computed << std::endl; + std::cout << " GUI: font_style.computed: " << query.font_style.computed << std::endl; std::cout << " GUI: text_anchor.computed: " << query.text_anchor.computed << std::endl; - std::cout << " GUI: text_align.computed: " << query.text_align.computed << std::endl; + std::cout << " GUI: text_align.computed: " << query.text_align.computed << std::endl; std::cout << " GUI: line_height.computed: " << query.line_height.computed - << " line_height.value: " << query.line_height.value - << " line_height.unit: " << query.line_height.unit << std::endl; + << " line_height.value: " << query.line_height.value << " line_height.unit: " << query.line_height.unit + << std::endl; std::cout << " GUI: word_spacing.computed: " << query.word_spacing.computed - << " word_spacing.value: " << query.word_spacing.value - << " word_spacing.unit: " << query.word_spacing.unit << std::endl; + << " word_spacing.value: " << query.word_spacing.value + << " word_spacing.unit: " << query.word_spacing.unit << std::endl; std::cout << " GUI: letter_spacing.computed: " << query.letter_spacing.computed - << " letter_spacing.value: " << query.letter_spacing.value - << " letter_spacing.unit: " << query.letter_spacing.unit << std::endl; + << " letter_spacing.value: " << query.letter_spacing.value + << " letter_spacing.unit: " << query.letter_spacing.unit << std::endl; std::cout << " GUI: writing_mode.computed: " << query.writing_mode.computed << std::endl; #endif // Kerning (xshift), yshift, rotation. NB: These are not CSS attributes. - if( SP_IS_TEXT_CONTEXT(_desktop->event_context) ) { + if (SP_IS_TEXT_CONTEXT(_desktop->event_context)) { Inkscape::UI::Tools::TextTool *const tc = SP_TEXT_CONTEXT(_desktop->event_context); - if( tc ) { + if (tc) { unsigned char_index = -1; TextTagAttributes *attributes = - text_tag_attributes_at_position( tc->text, std::min(tc->text_sel_start, tc->text_sel_end), &char_index ); - if( attributes ) { - + text_tag_attributes_at_position(tc->text, std::min(tc->text_sel_start, tc->text_sel_end), &char_index); + if (attributes) { // Dx - double dx = attributes->getDx( char_index ); + double dx = attributes->getDx(char_index); _dx_adj->set_value(dx); // Dy - double dy = attributes->getDy( char_index ); + double dy = attributes->getDy(char_index); _dy_adj->set_value(dy); // Rotation - double rotation = attributes->getRotate( char_index ); + double rotation = attributes->getRotate(char_index); /* SVG value is between 0 and 360 but we're using -180 to 180 in widget */ - if( rotation > 180.0 ) rotation -= 360.0; + if (rotation > 180.0) + rotation -= 360.0; _rotation_adj->set_value(rotation); #ifdef DEBUG_TEXT @@ -2185,8 +2109,8 @@ void TextToolbar::selection_changed(Inkscape::Selection *selection) // don't bot _freeze = false; } -void -TextToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) { +void TextToolbar::watch_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec) +{ bool is_text_toolbar = SP_IS_TEXT_CONTEXT(ec); bool is_select_toolbar = !is_text_toolbar && SP_IS_SELECT_CONTEXT(ec); if (is_text_toolbar) { @@ -2194,8 +2118,10 @@ TextToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) { // Ensure FontLister is updated here first.................. c_selection_changed = desktop->getSelection()->connectChangedFirst(sigc::mem_fun(*this, &TextToolbar::selection_changed)); - c_selection_modified = desktop->getSelection()->connectModifiedFirst(sigc::mem_fun(*this, &TextToolbar::selection_modified)); - c_subselection_changed = desktop->connectToolSubselectionChanged(sigc::mem_fun(*this, &TextToolbar::subselection_changed)); + c_selection_modified = + desktop->getSelection()->connectModifiedFirst(sigc::mem_fun(*this, &TextToolbar::selection_modified)); + c_subselection_changed = + desktop->connectToolSubselectionChanged(sigc::mem_fun(*this, &TextToolbar::subselection_changed)); this->_sub_active_item = nullptr; selection_changed(desktop->getSelection()); } else if (is_select_toolbar) { @@ -2203,7 +2129,6 @@ TextToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) { sigc::mem_fun(*this, &TextToolbar::selection_modified_select_tool)); } - if (!is_text_toolbar) { c_selection_changed.disconnect(); c_selection_modified.disconnect(); @@ -2215,12 +2140,10 @@ TextToolbar::watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec) { } } -void -TextToolbar::selection_modified(Inkscape::Selection *selection, guint /*flags*/) +void TextToolbar::selection_modified(Inkscape::Selection *selection, guint /*flags*/) { this->_sub_active_item = nullptr; selection_changed(selection); - } void TextToolbar::subselection_wrap_toggle(bool start) @@ -2244,30 +2167,30 @@ void TextToolbar::subselection_wrap_toggle(bool start) } /* -* This function parse the just created line height in one or more lines of a text subselection -* can recibe 2 kinds of input because when we store a text element we apply a fallback that change -* structure. This visualy is not reflected but user maybe want to change a part of this subselection -* once the falback is created, so we need more complex here to fill the gap. -* Basicaly we have a line height changed in the new wraper element/s between wrap_start and wrap_end -* this variables store starting iterator of first char in line and last char in line in a subselection -* this elements are styled well but we can have orphands text nodes before and after the subselection. -* this normaly 3 elements are inside a container as direct child of a text element, so we need to apply -* the container style to the optional previous and last text nodes warping into a new element that get the -* container style (this are not part to the subsselection). After wrap we unindent all child of the container and -* remove the container -* -*/ + * This function parse the just created line height in one or more lines of a text subselection + * can recibe 2 kinds of input because when we store a text element we apply a fallback that change + * structure. This visualy is not reflected but user maybe want to change a part of this subselection + * once the falback is created, so we need more complex here to fill the gap. + * Basicaly we have a line height changed in the new wraper element/s between wrap_start and wrap_end + * this variables store starting iterator of first char in line and last char in line in a subselection + * this elements are styled well but we can have orphands text nodes before and after the subselection. + * this normaly 3 elements are inside a container as direct child of a text element, so we need to apply + * the container style to the optional previous and last text nodes warping into a new element that get the + * container style (this are not part to the subsselection). After wrap we unindent all child of the container and + * remove the container + * + */ void TextToolbar::prepare_inner() { Inkscape::UI::Tools::TextTool *const tc = SP_TEXT_CONTEXT(_desktop->event_context); if (tc) { Inkscape::Text::Layout *layout = const_cast<Inkscape::Text::Layout *>(te_get_layout(tc->text)); if (layout) { - SPDocument *doc = _desktop->getDocument(); - SPObject *spobject = dynamic_cast<SPObject *>(tc->text); - SPItem *spitem = dynamic_cast<SPItem *>(tc->text); - SPText *text = dynamic_cast<SPText *>(tc->text); - SPFlowtext *flowtext = dynamic_cast<SPFlowtext *>(tc->text); + SPDocument *doc = _desktop->getDocument(); + SPObject *spobject = dynamic_cast<SPObject *>(tc->text); + SPItem *spitem = dynamic_cast<SPItem *>(tc->text); + SPText *text = dynamic_cast<SPText *>(tc->text); + SPFlowtext *flowtext = dynamic_cast<SPFlowtext *>(tc->text); Inkscape::XML::Document *xml_doc = doc->getReprDoc(); if (!spobject) { return; @@ -2283,8 +2206,8 @@ void TextToolbar::prepare_inner() Glib::ustring content = spstring->string; if (content != "\n") { Inkscape::XML::Node *rstring = xml_doc->createTextNode(content.c_str()); - Inkscape::XML::Node *rtspan = xml_doc->createElement("svg:tspan"); - //Inkscape::XML::Node *rnl = xml_doc->createTextNode("\n"); + Inkscape::XML::Node *rtspan = xml_doc->createElement("svg:tspan"); + // Inkscape::XML::Node *rnl = xml_doc->createTextNode("\n"); rtspan->setAttribute("sodipodi:role", "line"); rtspan->addChild(rstring, nullptr); text->getRepr()->addChild(rtspan, child->getRepr()); @@ -2314,7 +2237,7 @@ void TextToolbar::prepare_inner() if (flowtext) { flowtext->fix_overflow_flowregion(true); } - if (!rawptr_start || !rawptr_end || !SP_IS_OBJECT(rawptr_start)|| !SP_IS_OBJECT(rawptr_end)) { + if (!rawptr_start || !rawptr_end || !SP_IS_OBJECT(rawptr_start) || !SP_IS_OBJECT(rawptr_end)) { return; } SPObject *startobj = reinterpret_cast<SPObject *>(rawptr_start); @@ -2323,13 +2246,11 @@ void TextToolbar::prepare_inner() // looping parent while text element in start and end // and geting this and the inbetween elements SPObject *start = startobj; - SPObject *end = endobj; - while (start->parent != spobject) - { + SPObject *end = endobj; + while (start->parent != spobject) { start = start->parent; } - while (end->parent != spobject) - { + while (end->parent != spobject) { end = end->parent; } std::vector<SPObject *> containers; @@ -2341,17 +2262,17 @@ void TextToolbar::prepare_inner() containers.push_back(start); } for (auto container : containers) { - Inkscape::XML::Node *prevchild = container->getRepr(); - std::vector<SPObject*> childs = container->childList(false); + Inkscape::XML::Node *prevchild = container->getRepr(); + std::vector<SPObject *> childs = container->childList(false); for (auto child : childs) { - SPString *spstring = dynamic_cast<SPString *>(child); + SPString *spstring = dynamic_cast<SPString *>(child); SPFlowtspan *flowtspan = dynamic_cast<SPFlowtspan *>(child); - SPTSpan *tspan = dynamic_cast<SPTSpan *>(child); + SPTSpan *tspan = dynamic_cast<SPTSpan *>(child); // we need to upper all flowtspans to container level // to this we need to change the element from flowspan to flowpara if (flowtspan) { Inkscape::XML::Node *flowpara = xml_doc->createElement("svg:flowPara"); - std::vector<SPObject*> fts_childs = flowtspan->childList(false); + std::vector<SPObject *> fts_childs = flowtspan->childList(false); bool hascontent = false; // we need to move the contents to the new created element // mayve we can move directly but the safer for me is duplicate @@ -2377,7 +2298,7 @@ void TextToolbar::prepare_inner() } else if (tspan) { if (child->childList(false).size()) { child->getRepr()->setAttribute("sodipodi:role", "line"); - // maybe we need to move unindent function here + // maybe we need to move unindent function here // to be the same as other here prevchild = unindent_node(child->getRepr(), prevchild); } else { @@ -2385,7 +2306,7 @@ void TextToolbar::prepare_inner() container->getRepr()->removeChild(child->getRepr()); } } else if (spstring) { - // we are on a text node, we act diferent if in a text or flowtext. + // we are on a text node, we act diferent if in a text or flowtext. // wrap a duplicate of the element and unindent after the prevchild // and finaly delete original Inkscape::XML::Node *string_node = xml_doc->createTextNode(spstring->string.c_str()); @@ -2454,10 +2375,10 @@ void TextToolbar::subselection_changed(gpointer texttool) if (tc) { Inkscape::Text::Layout const *layout = te_get_layout(tc->text); if (layout) { - Inkscape::Text::Layout::iterator start = layout->begin(); - Inkscape::Text::Layout::iterator end = layout->end(); + Inkscape::Text::Layout::iterator start = layout->begin(); + Inkscape::Text::Layout::iterator end = layout->end(); Inkscape::Text::Layout::iterator start_selection = tc->text_sel_start; - Inkscape::Text::Layout::iterator end_selection = tc->text_sel_end; + Inkscape::Text::Layout::iterator end_selection = tc->text_sel_end; #ifdef DEBUG_TEXT std::cout << " GUI: Start of text: " << layout->iteratorToCharIndex(start) << std::endl; std::cout << " GUI: End of text: " << layout->iteratorToCharIndex(end) << std::endl; @@ -2477,7 +2398,7 @@ void TextToolbar::subselection_changed(gpointer texttool) int origin_selection = layout->iteratorToCharIndex(start_selection); Inkscape::Text::Layout::iterator next = layout->charIndexToIterator(origin_selection + 1); Inkscape::Text::Layout::iterator prev = layout->charIndexToIterator(origin_selection - 1); - //TODO: find a better way to init + // TODO: find a better way to init _updating = true; SPStyle query(_desktop->getDocument()); _query_cursor = query; @@ -2488,7 +2409,8 @@ void TextToolbar::subselection_changed(gpointer texttool) } else { tc->text_sel_start = prev; } - _cusor_numbers = sp_desktop_query_style(_desktop, &_query_cursor, QUERY_STYLE_PROPERTY_FONTNUMBERS); + _cusor_numbers = + sp_desktop_query_style(_desktop, &_query_cursor, QUERY_STYLE_PROPERTY_FONTNUMBERS); tc->text_sel_start = start_selection; wrap_start = tc->text_sel_start; wrap_end = tc->text_sel_end; @@ -2518,7 +2440,7 @@ void TextToolbar::subselection_changed(gpointer texttool) wrap_end.thisEndOfLine(); } selection_changed(nullptr); - } + } } } #ifdef DEBUG_TEXT @@ -2527,9 +2449,9 @@ void TextToolbar::subselection_changed(gpointer texttool) std::cout << std::endl; #endif } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/text-toolbar.h b/src/ui/toolbar/text-toolbar.h index 6108dd60f245b7cdc53940f2857e918e8e44100f..360eb1cf9dd8271eb8b2db3e62b9b54aa96a5b31 100644 --- a/src/ui/toolbar/text-toolbar.h +++ b/src/ui/toolbar/text-toolbar.h @@ -28,23 +28,24 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "object/sp-item.h" -#include "object/sp-object.h" -#include "toolbar.h" -#include "text-editing.h" -#include "style.h" #include <gtkmm/adjustment.h> #include <gtkmm/box.h> #include <gtkmm/popover.h> #include <gtkmm/separatortoolitem.h> #include <sigc++/connection.h> +#include "object/sp-item.h" +#include "object/sp-object.h" +#include "style.h" +#include "text-editing.h" +#include "toolbar.h" + class SPDesktop; namespace Gtk { class ComboBoxText; class ToggleToolButton; -} +} // namespace Gtk namespace Inkscape { class Selection; @@ -59,10 +60,11 @@ class ComboBoxEntryToolItem; class ComboToolItem; class SpinButtonToolItem; class UnitTracker; -} +} // namespace Widget namespace Toolbar { -class TextToolbar : public Toolbar { +class TextToolbar : public Toolbar +{ private: bool _freeze; bool _text_style_from_prefs; @@ -132,18 +134,18 @@ private: void selection_modified(Inkscape::Selection *selection, guint flags); void selection_modified_select_tool(Inkscape::Selection *selection, guint flags); void subselection_changed(gpointer texttool); - void watch_ec(SPDesktop* desktop, Inkscape::UI::Tools::ToolBase* ec); + void watch_ec(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *ec); void set_sizes(int unit); Inkscape::XML::Node *unindent_node(Inkscape::XML::Node *repr, Inkscape::XML::Node *before); - protected: +protected: TextToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_TEXT_TOOLBAR_H */ diff --git a/src/ui/toolbar/toolbar.cpp b/src/ui/toolbar/toolbar.cpp index 445f5b7e831c3bfaf02fdab345597690ac5d4415..c2666787587aee536555d1ac2e6fa1ec12bfceba 100644 --- a/src/ui/toolbar/toolbar.cpp +++ b/src/ui/toolbar/toolbar.cpp @@ -14,15 +14,13 @@ #include <gtkmm/toggletoolbutton.h> #include "desktop.h" - #include "helper/action.h" namespace Inkscape { namespace UI { namespace Toolbar { -Gtk::ToolItem * -Toolbar::add_label(const Glib::ustring &label_text) +Gtk::ToolItem *Toolbar::add_label(const Glib::ustring &label_text) { auto ti = Gtk::manage(new Gtk::ToolItem()); @@ -43,9 +41,7 @@ Toolbar::add_label(const Glib::ustring &label_text) * * \returns The toggle button */ -Gtk::ToggleToolButton * -Toolbar::add_toggle_button(const Glib::ustring &label_text, - const Glib::ustring &tooltip_text) +Gtk::ToggleToolButton *Toolbar::add_toggle_button(const Glib::ustring &label_text, const Glib::ustring &tooltip_text) { auto btn = Gtk::manage(new Gtk::ToggleToolButton(label_text)); btn->set_tooltip_text(tooltip_text); @@ -60,11 +56,10 @@ Toolbar::add_toggle_button(const Glib::ustring &label_text, * * \returns a pointer to the toolbutton */ -Gtk::ToolButton * -Toolbar::add_toolbutton_for_verb(unsigned int verb_code) +Gtk::ToolButton *Toolbar::add_toolbutton_for_verb(unsigned int verb_code) { auto context = Inkscape::ActionContext(_desktop); - auto button = SPAction::create_toolbutton_for_verb(verb_code, context); + auto button = SPAction::create_toolbutton_for_verb(verb_code, context); add(*button); return button; } @@ -75,21 +70,19 @@ Toolbar::add_toolbutton_for_verb(unsigned int verb_code) * \details This is just a convenience wrapper for the * standard GtkMM functionality */ -void -Toolbar::add_separator() +void Toolbar::add_separator() { - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); } -GtkWidget * -Toolbar::create(SPDesktop *desktop) +GtkWidget *Toolbar::create(SPDesktop *desktop) { auto toolbar = Gtk::manage(new Toolbar(desktop)); return GTK_WIDGET(toolbar->gobj()); } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: mode:c++ diff --git a/src/ui/toolbar/toolbar.h b/src/ui/toolbar/toolbar.h index 18c0510b124b367f1b75d3467916bdfefb62bb1d..368df2d80e8fe135d0cac9b11af254dfd069d7f4 100644 --- a/src/ui/toolbar/toolbar.h +++ b/src/ui/toolbar/toolbar.h @@ -15,9 +15,9 @@ class SPDesktop; namespace Gtk { - class Label; - class ToggleToolButton; -} +class Label; +class ToggleToolButton; +} // namespace Gtk namespace Inkscape { namespace UI { @@ -30,7 +30,8 @@ namespace Toolbar { * function that adds all the required tool-items and returns the * toolbar as a GtkWidget */ -class Toolbar : public Gtk::Toolbar { +class Toolbar : public Gtk::Toolbar +{ protected: SPDesktop *_desktop; @@ -41,18 +42,17 @@ protected: : _desktop(desktop) {} - Gtk::ToolItem * add_label(const Glib::ustring &label_text); - Gtk::ToggleToolButton * add_toggle_button(const Glib::ustring &label_text, - const Glib::ustring &tooltip_text); - Gtk::ToolButton * add_toolbutton_for_verb(unsigned int verb_code); + Gtk::ToolItem *add_label(const Glib::ustring &label_text); + Gtk::ToggleToolButton *add_toggle_button(const Glib::ustring &label_text, const Glib::ustring &tooltip_text); + Gtk::ToolButton *add_toolbutton_for_verb(unsigned int verb_code); void add_separator(); protected: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* diff --git a/src/ui/toolbar/tweak-toolbar.cpp b/src/ui/toolbar/tweak-toolbar.cpp index eefdd7a51d6e8c694533935067eed95d7e98efdd..2d2eb4f4cb6799dd73530ac6ae15710bedba35e7 100644 --- a/src/ui/toolbar/tweak-toolbar.cpp +++ b/src/ui/toolbar/tweak-toolbar.cpp @@ -28,32 +28,31 @@ #include "tweak-toolbar.h" #include <glibmm/i18n.h> - #include <gtkmm/radiotoolbutton.h> #include <gtkmm/separatortoolitem.h> #include "desktop.h" #include "document-undo.h" - #include "ui/icon-names.h" #include "ui/tools/tweak-tool.h" #include "ui/widget/canvas.h" #include "ui/widget/label-tool-item.h" -#include "ui/widget/spinbutton.h" #include "ui/widget/spin-button-tool-item.h" +#include "ui/widget/spinbutton.h" namespace Inkscape { namespace UI { namespace Toolbar { TweakToolbar::TweakToolbar(SPDesktop *desktop) - : Toolbar(desktop) + : Toolbar(desktop) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); /* Width */ { - std::vector<Glib::ustring> labels = {_("(pinch tweak)"), "", "", "", _("(default)"), "", "", "", "", _("(broad tweak)")}; - std::vector<double> values = { 1, 3, 5, 10, 15, 20, 30, 50, 75, 100}; + std::vector<Glib::ustring> labels = {_("(pinch tweak)"), "", "", "", _("(default)"), "", "", "", "", + _("(broad tweak)")}; + std::vector<double> values = {1, 3, 5, 10, 15, 20, 30, 50, 75, 100}; auto width_val = prefs->getDouble("/tools/tweak/width", 15); _width_adj = Gtk::Adjustment::create(width_val * 100, 1, 100, 1.0, 10.0); @@ -69,8 +68,9 @@ TweakToolbar::TweakToolbar(SPDesktop *desktop) // Force { - std::vector<Glib::ustring> labels = {_("(minimum force)"), "", "", _("(default)"), "", "", "", _("(maximum force)")}; - std::vector<double> values = { 1, 5, 10, 20, 30, 50, 70, 100}; + std::vector<Glib::ustring> labels = {_("(minimum force)"), "", "", _("(default)"), "", "", "", + _("(maximum force)")}; + std::vector<double> values = {1, 5, 10, 20, 30, 50, 70, 100}; auto force_val = prefs->getDouble("/tools/tweak/force", 20); _force_adj = Gtk::Adjustment::create(force_val * 100, 1, 100, 1.0, 10.0); _force_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("tweak-force", _("Force:"), _force_adj, 0.01, 0)); @@ -85,14 +85,14 @@ TweakToolbar::TweakToolbar(SPDesktop *desktop) /* Use Pressure button */ { - _pressure_item = add_toggle_button(_("Pressure"), - _("Use the pressure of the input device to alter the force of tweak action")); + _pressure_item = add_toggle_button( + _("Pressure"), _("Use the pressure of the input device to alter the force of tweak action")); _pressure_item->set_icon_name(INKSCAPE_ICON("draw-use-pressure")); _pressure_item->signal_toggled().connect(sigc::mem_fun(*this, &TweakToolbar::pressure_state_changed)); _pressure_item->set_active(prefs->getBool("/tools/tweak/usepressure", true)); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); /* Mode */ { @@ -173,26 +173,29 @@ TweakToolbar::TweakToolbar(SPDesktop *desktop) } } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); guint mode = prefs->getInt("/tools/tweak/mode", 0); /* Fidelity */ { - std::vector<Glib::ustring> labels = {_("(rough, simplified)"), "", "", _("(default)"), "", "", _("(fine, but many nodes)")}; - std::vector<double> values = { 10, 25, 35, 50, 60, 80, 100}; + std::vector<Glib::ustring> labels = {_("(rough, simplified)"), "", "", _("(default)"), "", "", + _("(fine, but many nodes)")}; + std::vector<double> values = {10, 25, 35, 50, 60, 80, 100}; auto fidelity_val = prefs->getDouble("/tools/tweak/fidelity", 50); _fidelity_adj = Gtk::Adjustment::create(fidelity_val * 100, 1, 100, 1.0, 10.0); - _fidelity_item = Gtk::manage(new UI::Widget::SpinButtonToolItem("tweak-fidelity", _("Fidelity:"), _fidelity_adj, 0.01, 0)); - _fidelity_item->set_tooltip_text(_("Low fidelity simplifies paths; high fidelity preserves path features but may generate a lot of new nodes")); + _fidelity_item = + Gtk::manage(new UI::Widget::SpinButtonToolItem("tweak-fidelity", _("Fidelity:"), _fidelity_adj, 0.01, 0)); + _fidelity_item->set_tooltip_text(_("Low fidelity simplifies paths; high fidelity preserves path features but " + "may generate a lot of new nodes")); _fidelity_item->set_custom_numeric_menu_data(values, labels); _fidelity_item->set_focus_widget(desktop->canvas); _fidelity_adj->signal_value_changed().connect(sigc::mem_fun(*this, &TweakToolbar::fidelity_value_changed)); add(*_fidelity_item); } - add(* Gtk::manage(new Gtk::SeparatorToolItem())); + add(*Gtk::manage(new Gtk::SeparatorToolItem())); { _channels_label = Gtk::manage(new UI::Widget::LabelToolItem(_("Channels:"))); @@ -201,30 +204,26 @@ TweakToolbar::TweakToolbar(SPDesktop *desktop) } { - //TRANSLATORS: "H" here stands for hue - _doh_item = add_toggle_button(C_("Hue", "H"), - _("In color mode, act on object's hue")); + // TRANSLATORS: "H" here stands for hue + _doh_item = add_toggle_button(C_("Hue", "H"), _("In color mode, act on object's hue")); _doh_item->signal_toggled().connect(sigc::mem_fun(*this, &TweakToolbar::toggle_doh)); _doh_item->set_active(prefs->getBool("/tools/tweak/doh", true)); } { - //TRANSLATORS: "S" here stands for saturation - _dos_item = add_toggle_button(C_("Saturation", "S"), - _("In color mode, act on object's saturation")); + // TRANSLATORS: "S" here stands for saturation + _dos_item = add_toggle_button(C_("Saturation", "S"), _("In color mode, act on object's saturation")); _dos_item->signal_toggled().connect(sigc::mem_fun(*this, &TweakToolbar::toggle_dos)); _dos_item->set_active(prefs->getBool("/tools/tweak/dos", true)); } { - //TRANSLATORS: "S" here stands for saturation - _dol_item = add_toggle_button(C_("Lightness", "L"), - _("In color mode, act on object's lightness")); + // TRANSLATORS: "S" here stands for saturation + _dol_item = add_toggle_button(C_("Lightness", "L"), _("In color mode, act on object's lightness")); _dol_item->signal_toggled().connect(sigc::mem_fun(*this, &TweakToolbar::toggle_dol)); _dol_item->set_active(prefs->getBool("/tools/tweak/dol", true)); } { - //TRANSLATORS: "O" here stands for opacity - _doo_item = add_toggle_button(C_("Opacity", "O"), - _("In color mode, act on object's opacity")); + // TRANSLATORS: "O" here stands for opacity + _doo_item = add_toggle_button(C_("Opacity", "O"), _("In color mode, act on object's opacity")); _doo_item->signal_toggled().connect(sigc::mem_fun(*this, &TweakToolbar::toggle_doo)); _doo_item->set_active(prefs->getBool("/tools/tweak/doo", true)); } @@ -244,43 +243,36 @@ TweakToolbar::TweakToolbar(SPDesktop *desktop) } } -void -TweakToolbar::set_mode(int mode) +void TweakToolbar::set_mode(int mode) { _mode_buttons[mode]->set_active(); } -GtkWidget * -TweakToolbar::create(SPDesktop *desktop) +GtkWidget *TweakToolbar::create(SPDesktop *desktop) { auto toolbar = new TweakToolbar(desktop); return GTK_WIDGET(toolbar->gobj()); } -void -TweakToolbar::width_value_changed() +void TweakToolbar::width_value_changed() { auto prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/tweak/width", - _width_adj->get_value() * 0.01 ); + prefs->setDouble("/tools/tweak/width", _width_adj->get_value() * 0.01); } -void -TweakToolbar::force_value_changed() +void TweakToolbar::force_value_changed() { auto prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/tweak/force", - _force_adj->get_value() * 0.01 ); + prefs->setDouble("/tools/tweak/force", _force_adj->get_value() * 0.01); } -void -TweakToolbar::mode_changed(int mode) +void TweakToolbar::mode_changed(int mode) { auto prefs = Inkscape::Preferences::get(); prefs->setInt("/tools/tweak/mode", mode); - bool flag = ((mode == Inkscape::UI::Tools::TWEAK_MODE_COLORPAINT) || - (mode == Inkscape::UI::Tools::TWEAK_MODE_COLORJITTER)); + bool flag = + ((mode == Inkscape::UI::Tools::TWEAK_MODE_COLORPAINT) || (mode == Inkscape::UI::Tools::TWEAK_MODE_COLORJITTER)); _doh_item->set_visible(flag); _dos_item->set_visible(flag); @@ -293,48 +285,45 @@ TweakToolbar::mode_changed(int mode) } } -void -TweakToolbar::fidelity_value_changed() +void TweakToolbar::fidelity_value_changed() { auto prefs = Inkscape::Preferences::get(); - prefs->setDouble( "/tools/tweak/fidelity", - _fidelity_adj->get_value() * 0.01 ); + prefs->setDouble("/tools/tweak/fidelity", _fidelity_adj->get_value() * 0.01); } -void -TweakToolbar::pressure_state_changed() +void TweakToolbar::pressure_state_changed() { auto prefs = Inkscape::Preferences::get(); prefs->setBool("/tools/tweak/usepressure", _pressure_item->get_active()); } -void -TweakToolbar::toggle_doh() { +void TweakToolbar::toggle_doh() +{ auto prefs = Inkscape::Preferences::get(); prefs->setBool("/tools/tweak/doh", _doh_item->get_active()); } -void -TweakToolbar::toggle_dos() { +void TweakToolbar::toggle_dos() +{ auto prefs = Inkscape::Preferences::get(); prefs->setBool("/tools/tweak/dos", _dos_item->get_active()); } -void -TweakToolbar::toggle_dol() { +void TweakToolbar::toggle_dol() +{ auto prefs = Inkscape::Preferences::get(); prefs->setBool("/tools/tweak/dol", _dol_item->get_active()); } -void -TweakToolbar::toggle_doo() { +void TweakToolbar::toggle_doo() +{ auto prefs = Inkscape::Preferences::get(); prefs->setBool("/tools/tweak/doo", _doo_item->get_active()); } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/tweak-toolbar.h b/src/ui/toolbar/tweak-toolbar.h index cd1c7d048f6eb7ceaffb6ce91fed674563a01397..6301f3b5b6486a172d0fd190d21fca8665bb3aab 100644 --- a/src/ui/toolbar/tweak-toolbar.h +++ b/src/ui/toolbar/tweak-toolbar.h @@ -41,10 +41,11 @@ namespace UI { namespace Widget { class LabelToolItem; class SpinButtonToolItem; -} +} // namespace Widget namespace Toolbar { -class TweakToolbar : public Toolbar { +class TweakToolbar : public Toolbar +{ private: UI::Widget::SpinButtonToolItem *_width_item; UI::Widget::SpinButtonToolItem *_force_item; @@ -78,12 +79,12 @@ protected: TweakToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); void set_mode(int mode); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_SELECT_TOOLBAR_H */ diff --git a/src/ui/toolbar/zoom-toolbar.cpp b/src/ui/toolbar/zoom-toolbar.cpp index 3b4d3d6bc3b10b1dee592aee9d917a5f5eeb3603..14bdfd4dd2f937171a3b1331020ab38edcda9cf4 100644 --- a/src/ui/toolbar/zoom-toolbar.cpp +++ b/src/ui/toolbar/zoom-toolbar.cpp @@ -28,9 +28,8 @@ #include "zoom-toolbar.h" #include "desktop.h" -#include "verbs.h" - #include "helper/action.h" +#include "verbs.h" namespace Inkscape { namespace UI { @@ -63,15 +62,14 @@ ZoomToolbar::ZoomToolbar(SPDesktop *desktop) show_all(); } -GtkWidget * -ZoomToolbar::create(SPDesktop *desktop) +GtkWidget *ZoomToolbar::create(SPDesktop *desktop) { auto toolbar = Gtk::manage(new ZoomToolbar(desktop)); return GTK_WIDGET(toolbar->gobj()); } -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/toolbar/zoom-toolbar.h b/src/ui/toolbar/zoom-toolbar.h index b5d34de40b0cb504bea6e617f6b0fe4fff7439c4..aa422e40366c533287ba2465527a5ee1638aa603 100644 --- a/src/ui/toolbar/zoom-toolbar.h +++ b/src/ui/toolbar/zoom-toolbar.h @@ -37,16 +37,17 @@ namespace Toolbar { /** * \brief A toolbar for controlling the zoom */ -class ZoomToolbar : public Toolbar { +class ZoomToolbar : public Toolbar +{ protected: ZoomToolbar(SPDesktop *desktop); public: - static GtkWidget * create(SPDesktop *desktop); + static GtkWidget *create(SPDesktop *desktop); }; -} -} -} +} // namespace Toolbar +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_ZOOM_TOOLBAR_H */ diff --git a/src/ui/tools-switch.cpp b/src/ui/tools-switch.cpp index 15bbff4a812b105df42b5009ef6f81772829f788..27c30e3425778c4335f4cd515bcc29c02cdfb92f 100644 --- a/src/ui/tools-switch.cpp +++ b/src/ui/tools-switch.cpp @@ -12,26 +12,25 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm.h> // prevents deprecation warnings - -#include "inkscape.h" -#include "desktop.h" +#include "ui/tools-switch.h" #include <glibmm/i18n.h> +#include <gtkmm.h> // prevents deprecation warnings -#include "ui/tools-switch.h" - -#include "object/sp-rect.h" +#include "desktop.h" +#include "inkscape.h" +#include "object/box3d.h" #include "object/sp-ellipse.h" #include "object/sp-flowtext.h" #include "object/sp-offset.h" #include "object/sp-path.h" -#include "object/sp-star.h" +#include "object/sp-rect.h" #include "object/sp-spiral.h" +#include "object/sp-star.h" #include "object/sp-text.h" -#include "object/box3d.h" // TODO: How many of these are actually needed? +#include "message-context.h" #include "ui/tools/arc-tool.h" #include "ui/tools/box3d-tool.h" #include "ui/tools/calligraphic-tool.h" @@ -53,36 +52,32 @@ #include "ui/tools/tweak-tool.h" #include "ui/tools/zoom-tool.h" -#include "message-context.h" - using Inkscape::UI::Tools::ToolBase; -static char const *const tool_names[] = { - nullptr, - "/tools/select", - "/tools/nodes", - "/tools/tweak", - "/tools/spray", - "/tools/shapes/rect", - "/tools/shapes/3dbox", - "/tools/shapes/arc", - "/tools/shapes/star", - "/tools/shapes/spiral", - "/tools/freehand/pencil", - "/tools/freehand/pen", - "/tools/calligraphic", - "/tools/text", - "/tools/gradient", - "/tools/mesh", - "/tools/zoom", - "/tools/measure", - "/tools/dropper", - "/tools/connector", - "/tools/paintbucket", - "/tools/eraser", - "/tools/lpetool", - nullptr -}; +static char const *const tool_names[] = {nullptr, + "/tools/select", + "/tools/nodes", + "/tools/tweak", + "/tools/spray", + "/tools/shapes/rect", + "/tools/shapes/3dbox", + "/tools/shapes/arc", + "/tools/shapes/star", + "/tools/shapes/spiral", + "/tools/freehand/pencil", + "/tools/freehand/pen", + "/tools/calligraphic", + "/tools/text", + "/tools/gradient", + "/tools/mesh", + "/tools/zoom", + "/tools/measure", + "/tools/dropper", + "/tools/connector", + "/tools/paintbucket", + "/tools/eraser", + "/tools/lpetool", + nullptr}; // TODO: HEY! these belong to the tools themselves! static char const *const tool_msg[] = { @@ -92,42 +87,49 @@ static char const *const tool_msg[] = { N_("To tweak a path by pushing, select it and drag over it."), N_("<b>Drag</b>, <b>click</b> or <b>click and scroll</b> to spray the selected objects."), N_("<b>Drag</b> to create a rectangle. <b>Drag controls</b> to round corners and resize. <b>Click</b> to select."), - N_("<b>Drag</b> to create a 3D box. <b>Drag controls</b> to resize in perspective. <b>Click</b> to select (with <b>Ctrl+Alt</b> for single faces)."), + N_("<b>Drag</b> to create a 3D box. <b>Drag controls</b> to resize in perspective. <b>Click</b> to select (with " + "<b>Ctrl+Alt</b> for single faces)."), N_("<b>Drag</b> to create an ellipse. <b>Drag controls</b> to make an arc or segment. <b>Click</b> to select."), N_("<b>Drag</b> to create a star. <b>Drag controls</b> to edit the star shape. <b>Click</b> to select."), N_("<b>Drag</b> to create a spiral. <b>Drag controls</b> to edit the spiral shape. <b>Click</b> to select."), - N_("<b>Drag</b> to create a freehand line. <b>Shift</b> appends to selected path, <b>Alt</b> activates sketch mode."), - N_("<b>Click</b> or <b>click and drag</b> to start a path; with <b>Shift</b> to append to selected path. <b>Ctrl+click</b> to create single dots (straight line modes only)."), - N_("<b>Drag</b> to draw a calligraphic stroke; with <b>Ctrl</b> to track a guide path. <b>Arrow keys</b> adjust width (left/right) and angle (up/down)."), + N_("<b>Drag</b> to create a freehand line. <b>Shift</b> appends to selected path, <b>Alt</b> activates sketch " + "mode."), + N_("<b>Click</b> or <b>click and drag</b> to start a path; with <b>Shift</b> to append to selected path. " + "<b>Ctrl+click</b> to create single dots (straight line modes only)."), + N_("<b>Drag</b> to draw a calligraphic stroke; with <b>Ctrl</b> to track a guide path. <b>Arrow keys</b> adjust " + "width (left/right) and angle (up/down)."), N_("<b>Click</b> to select or create text, <b>drag</b> to create flowed text; then type."), - N_("<b>Drag</b> or <b>double click</b> to create a gradient on selected objects, <b>drag handles</b> to adjust gradients."), - N_("<b>Drag</b> or <b>double click</b> to create a mesh on selected objects, <b>drag handles</b> to adjust meshes."), + N_("<b>Drag</b> or <b>double click</b> to create a gradient on selected objects, <b>drag handles</b> to adjust " + "gradients."), + N_("<b>Drag</b> or <b>double click</b> to create a mesh on selected objects, <b>drag handles</b> to adjust " + "meshes."), N_("<b>Click</b> or <b>drag around an area</b> to zoom in, <b>Shift+click</b> to zoom out."), N_("<b>Drag</b> to measure the dimensions of objects."), - N_("<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"), + N_("<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"), N_("<b>Click and drag</b> between shapes to create a connector."), - N_("<b>Click</b> to paint a bounded area, <b>Shift+click</b> to union the new fill with the current selection, <b>Ctrl+click</b> to change the clicked object's fill and stroke to the current setting."), + N_("<b>Click</b> to paint a bounded area, <b>Shift+click</b> to union the new fill with the current selection, " + "<b>Ctrl+click</b> to change the clicked object's fill and stroke to the current setting."), N_("<b>Drag</b> to erase."), N_("Choose a subtool from the toolbar"), }; -static int -tools_prefpath2num(char const *id) +static int tools_prefpath2num(char const *id) { int i = 1; while (tool_names[i]) { if (strcmp(tool_names[i], id) == 0) return i; - else i++; + else + i++; } - g_assert( 0 == TOOLS_INVALID ); - return 0; //nothing found + g_assert(0 == TOOLS_INVALID); + return 0; // nothing found } -int -tools_isactive(SPDesktop *dt, unsigned num) +int tools_isactive(SPDesktop *dt, unsigned num) { - g_assert( num < G_N_ELEMENTS(tool_names) ); + g_assert(num < G_N_ELEMENTS(tool_names)); if (dynamic_cast<ToolBase *>(dt->event_context)) { return dt->event_context->pref_observer->observed_path == tool_names[num]; } else { @@ -135,16 +137,14 @@ tools_isactive(SPDesktop *dt, unsigned num) } } -int -tools_active(SPDesktop *dt) +int tools_active(SPDesktop *dt) { return tools_prefpath2num(dt->event_context->pref_observer->observed_path.data()); } -void -tools_switch(SPDesktop *dt, int num) +void tools_switch(SPDesktop *dt, int num) { - dt->tipsMessageContext()->set(Inkscape::NORMAL_MESSAGE, gettext( tool_msg[num] ) ); + dt->tipsMessageContext()->set(Inkscape::NORMAL_MESSAGE, gettext(tool_msg[num])); if (dt) { // This event may change the above message dt->_tool_changed.emit(num); @@ -172,14 +172,13 @@ void tools_switch_by_item(SPDesktop *dt, SPItem *item, Geom::Point const p) } else if (dynamic_cast<SPPath *>(item)) { if (Inkscape::UI::Tools::cc_item_is_connector(item)) { tools_switch(dt, TOOLS_CONNECTOR); - } - else { + } else { tools_switch(dt, TOOLS_NODES); } - } else if (dynamic_cast<SPText *>(item) || dynamic_cast<SPFlowtext *>(item)) { + } else if (dynamic_cast<SPText *>(item) || dynamic_cast<SPFlowtext *>(item)) { tools_switch(dt, TOOLS_TEXT); - sp_text_context_place_cursor_at (SP_TEXT_CONTEXT(dt->event_context), item, p); - } else if (dynamic_cast<SPOffset *>(item)) { + sp_text_context_place_cursor_at(SP_TEXT_CONTEXT(dt->event_context), item, p); + } else if (dynamic_cast<SPOffset *>(item)) { tools_switch(dt, TOOLS_NODES); } } diff --git a/src/ui/tools-switch.h b/src/ui/tools-switch.h index ad2a731184378bd30b18313d613b394aa0473cbc..c579a82856e1889e6908a469e4adde415e96620a 100644 --- a/src/ui/tools-switch.h +++ b/src/ui/tools-switch.h @@ -19,37 +19,37 @@ namespace Geom { class Point; } - -enum { - TOOLS_INVALID, - TOOLS_SELECT, - TOOLS_NODES, - TOOLS_TWEAK, - TOOLS_SPRAY, - TOOLS_SHAPES_RECT, - TOOLS_SHAPES_3DBOX, - TOOLS_SHAPES_ARC, - TOOLS_SHAPES_STAR, - TOOLS_SHAPES_SPIRAL, - TOOLS_FREEHAND_PENCIL, - TOOLS_FREEHAND_PEN, - TOOLS_CALLIGRAPHIC, - TOOLS_TEXT, - TOOLS_GRADIENT, - TOOLS_MESH, - TOOLS_ZOOM, - TOOLS_MEASURE, - TOOLS_DROPPER, - TOOLS_CONNECTOR, - TOOLS_PAINTBUCKET, - TOOLS_ERASER, - TOOLS_LPETOOL +enum +{ + TOOLS_INVALID, + TOOLS_SELECT, + TOOLS_NODES, + TOOLS_TWEAK, + TOOLS_SPRAY, + TOOLS_SHAPES_RECT, + TOOLS_SHAPES_3DBOX, + TOOLS_SHAPES_ARC, + TOOLS_SHAPES_STAR, + TOOLS_SHAPES_SPIRAL, + TOOLS_FREEHAND_PENCIL, + TOOLS_FREEHAND_PEN, + TOOLS_CALLIGRAPHIC, + TOOLS_TEXT, + TOOLS_GRADIENT, + TOOLS_MESH, + TOOLS_ZOOM, + TOOLS_MEASURE, + TOOLS_DROPPER, + TOOLS_CONNECTOR, + TOOLS_PAINTBUCKET, + TOOLS_ERASER, + TOOLS_LPETOOL }; int tools_isactive(SPDesktop *dt, unsigned num); int tools_active(SPDesktop *dt); void tools_switch(SPDesktop *dt, int num); -void tools_switch_by_item (SPDesktop *dt, SPItem *item, Geom::Point const p); +void tools_switch_by_item(SPDesktop *dt, SPItem *item, Geom::Point const p); #endif // !SEEN_TOOLS_SWITCH_H diff --git a/src/ui/tools/arc-tool.cpp b/src/ui/tools/arc-tool.cpp index 3e338a1956ac3ab26639a0d6743fbc211ad89499..fe9f283d13fcdfae71b6f4d032c60cb7d37aadc3 100644 --- a/src/ui/tools/arc-tool.cpp +++ b/src/ui/tools/arc-tool.cpp @@ -16,35 +16,30 @@ * * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/i18n.h> +#include "ui/tools/arc-tool.h" + #include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> #include "context-fns.h" #include "desktop-style.h" #include "desktop.h" +#include "display/sp-canvas-item.h" #include "document-undo.h" #include "document.h" +#include "include/macros.h" #include "message-context.h" +#include "object/sp-ellipse.h" +#include "object/sp-namedview.h" #include "preferences.h" #include "selection.h" #include "snap.h" -#include "verbs.h" - -#include "display/sp-canvas-item.h" - -#include "include/macros.h" - -#include "object/sp-ellipse.h" -#include "object/sp-namedview.h" - #include "ui/pixmaps/cursor-ellipse.xpm" - -#include "ui/tools/arc-tool.h" #include "ui/shape-editor.h" #include "ui/tools/tool-base.h" - -#include "xml/repr.h" +#include "verbs.h" #include "xml/node-event-vector.h" +#include "xml/repr.h" using Inkscape::DocumentUndo; @@ -52,20 +47,20 @@ namespace Inkscape { namespace UI { namespace Tools { -const std::string& ArcTool::getPrefsPath() { - return ArcTool::prefsPath; +const std::string &ArcTool::getPrefsPath() +{ + return ArcTool::prefsPath; } const std::string ArcTool::prefsPath = "/tools/shapes/arc"; - ArcTool::ArcTool() : ToolBase(cursor_ellipse_xpm) , arc(nullptr) -{ -} +{} -void ArcTool::finish() { +void ArcTool::finish() +{ sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); this->finishItem(); this->sel_changed_connection.disconnect(); @@ -73,7 +68,8 @@ void ArcTool::finish() { ToolBase::finish(); } -ArcTool::~ArcTool() { +ArcTool::~ArcTool() +{ this->enableGrDrag(false); this->sel_changed_connection.disconnect(); @@ -91,12 +87,14 @@ ArcTool::~ArcTool() { * Callback that processes the "changed" signal on the selection; * destroys old and creates new knotholder. */ -void ArcTool::selection_changed(Inkscape::Selection* selection) { +void ArcTool::selection_changed(Inkscape::Selection *selection) +{ this->shape_editor->unset_item(); this->shape_editor->set_item(selection->singleItem()); } -void ArcTool::setup() { +void ArcTool::setup() +{ ToolBase::setup(); Inkscape::Selection *selection = this->desktop->getSelection(); @@ -109,9 +107,7 @@ void ArcTool::setup() { } this->sel_changed_connection.disconnect(); - this->sel_changed_connection = selection->connectChanged( - sigc::mem_fun(this, &ArcTool::selection_changed) - ); + 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")) { @@ -123,7 +119,8 @@ void ArcTool::setup() { } } -bool ArcTool::item_handler(SPItem* item, GdkEvent* event) { +bool ArcTool::item_handler(SPItem *item, GdkEvent *event) +{ switch (event->type) { case GDK_BUTTON_PRESS: if (event->button.button == 1 && !this->space_panning) { @@ -138,7 +135,8 @@ bool ArcTool::item_handler(SPItem* item, GdkEvent* event) { return ToolBase::item_handler(item, event); } -bool ArcTool::root_handler(GdkEvent* event) { +bool ArcTool::root_handler(GdkEvent *event) +{ static bool dragging; Inkscape::Selection *selection = desktop->getSelection(); @@ -161,8 +159,8 @@ bool ArcTool::root_handler(GdkEvent* event) { 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, + GDK_KEY_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | + GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK, nullptr, event->button.time); handled = true; m.unSetup(); @@ -170,9 +168,8 @@ bool ArcTool::root_handler(GdkEvent* event) { 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 ) ) { + 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 @@ -188,7 +185,7 @@ bool ArcTool::root_handler(GdkEvent* event) { gobble_motion_events(GDK_BUTTON1_MASK); handled = true; - } else if (!this->sp_event_context_knot_mouseover()){ + } else if (!this->sp_event_context_knot_mouseover()) { SnapManager &m = desktop->namedview->snap_manager; m.setup(desktop); @@ -228,27 +225,27 @@ bool ArcTool::root_handler(GdkEvent* event) { break; case GDK_KEY_PRESS: - switch (get_latin_keyval (&event->key)) { + switch (get_latin_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_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"), - nullptr); + 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"), nullptr); } break; case GDK_KEY_x: case GDK_KEY_X: if (MOD__ALT_ONLY(event)) { - desktop->setToolboxFocusTo ("arc-rx"); + desktop->setToolboxFocusTo("arc-rx"); handled = true; } break; @@ -296,7 +293,7 @@ bool ArcTool::root_handler(GdkEvent* event) { 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_L: // Meta is when you press Shift+Alt case GDK_KEY_Meta_R: this->defaultMessageContext()->clear(); break; @@ -311,13 +308,14 @@ bool ArcTool::root_handler(GdkEvent* event) { } if (!handled) { - handled = ToolBase::root_handler(event); + handled = ToolBase::root_handler(event); } return handled; } -void ArcTool::drag(Geom::Point pt, guint state) { +void ArcTool::drag(Geom::Point pt, guint state) +{ if (!this->arc) { if (Inkscape::have_viable_layer(desktop, defaultMessageContext()) == false) { return; @@ -362,24 +360,23 @@ void ArcTool::drag(Geom::Point pt, guint state) { 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::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); + 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); + 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); + 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]; @@ -393,12 +390,12 @@ void ArcTool::drag(Geom::Point pt, guint state) { int ratio_x, ratio_y; bool is_golden_ratio = false; - if (fabs (rdimx) > fabs (rdimy)) { + if (fabs(rdimx) > fabs(rdimy)) { if (fabs(rdimx / rdimy - goldenratio) < 1e-6) { is_golden_ratio = true; } - ratio_x = (int) rint (rdimx / rdimy); + ratio_x = (int)rint(rdimx / rdimy); ratio_y = 1; } else { if (fabs(rdimy / rdimx - goldenratio) < 1e-6) { @@ -406,35 +403,43 @@ void ArcTool::drag(Geom::Point pt, guint state) { } ratio_x = 1; - ratio_y = (int) rint (rdimy / rdimx); + ratio_y = (int)rint(rdimy / rdimx); } if (!is_golden_ratio) { 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.c_str(), ys.c_str(), ratio_x, ratio_y); + _("<b>Ellipse</b>: %s × %s (constrained to ratio %d:%d); with " + "<b>Shift</b> to draw around the starting point"), + xs.c_str(), ys.c_str(), ratio_x, ratio_y); } else { if (ratio_y == 1) { this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, - _("<b>Ellipse</b>: %s × %s (constrained to golden ratio 1.618 : 1); with <b>Shift</b> to draw around the starting point"), - xs.c_str(), ys.c_str()); + _("<b>Ellipse</b>: %s × %s (constrained to golden ratio 1.618 : 1); " + "with <b>Shift</b> to draw around the starting point"), + xs.c_str(), ys.c_str()); } else { this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, - _("<b>Ellipse</b>: %s × %s (constrained to golden ratio 1 : 1.618); with <b>Shift</b> to draw around the starting point"), - xs.c_str(), ys.c_str()); + _("<b>Ellipse</b>: %s × %s (constrained to golden ratio 1 : 1.618); " + "with <b>Shift</b> to draw around the starting point"), + xs.c_str(), ys.c_str()); } } } else { - this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Ellipse</b>: %s × %s; with <b>Ctrl</b> to make circle, integer-ratio, or golden-ratio ellipse; with <b>Shift</b> to draw around the starting point"), xs.c_str(), ys.c_str()); + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, + _("<b>Ellipse</b>: %s × %s; with <b>Ctrl</b> to make circle, integer-ratio, " + "or golden-ratio ellipse; with <b>Shift</b> to draw around the starting point"), + xs.c_str(), ys.c_str()); } } -void ArcTool::finishItem() { +void ArcTool::finishItem() +{ this->message_context->clear(); if (this->arc != nullptr) { 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 + 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; } @@ -451,7 +456,8 @@ void ArcTool::finishItem() { } } -void ArcTool::cancel() { +void ArcTool::cancel() +{ desktop->getSelection()->clear(); sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); @@ -470,10 +476,9 @@ void ArcTool::cancel() { DocumentUndo::cancel(desktop->getDocument()); } -} -} -} - +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/arc-tool.h b/src/ui/tools/arc-tool.h index 6af99e0f99b1bbe6f4e2f41602b1cff118f815bd..57d5569246bfbff343a4b342c64cb584808a2450 100644 --- a/src/ui/tools/arc-tool.h +++ b/src/ui/tools/arc-tool.h @@ -16,9 +16,8 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstddef> - #include <2geom/point.h> +#include <cstddef> #include <sigc++/connection.h> #include "ui/tools/tool-base.h" @@ -27,47 +26,48 @@ class SPItem; class SPGenericEllipse; namespace Inkscape { - class Selection; +class Selection; } -#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*>(obj) != NULL) +#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 *>(obj) != NULL) namespace Inkscape { namespace UI { namespace Tools { -class ArcTool : public ToolBase { +class ArcTool : public ToolBase +{ public: - ArcTool(); - ~ArcTool() override; + ArcTool(); + ~ArcTool() override; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - void finish() override; - bool root_handler(GdkEvent* event) override; - bool item_handler(SPItem* item, GdkEvent* event) override; + void setup() override; + void finish() override; + bool root_handler(GdkEvent *event) override; + bool item_handler(SPItem *item, GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; private: - SPGenericEllipse *arc; + SPGenericEllipse *arc; Geom::Point center; sigc::connection sel_changed_connection; - void selection_changed(Inkscape::Selection* selection); + void selection_changed(Inkscape::Selection *selection); - void drag(Geom::Point pt, guint state); - void finishItem(); - void cancel(); + void drag(Geom::Point pt, guint state); + void finishItem(); + void cancel(); }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_ARC_CONTEXT_H */ diff --git a/src/ui/tools/box3d-tool.cpp b/src/ui/tools/box3d-tool.cpp index 008e6a1cffb1584e4db3dfbb9d3bdda9a392318a..61c0b671df515f68ca9de95d59d89a1ec5390c26 100644 --- a/src/ui/tools/box3d-tool.cpp +++ b/src/ui/tools/box3d-tool.cpp @@ -16,36 +16,30 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/tools/box3d-tool.h" + #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> - #include "context-fns.h" #include "desktop-style.h" #include "desktop.h" +#include "display/sp-canvas-item.h" #include "document-undo.h" #include "document.h" -#include "message-context.h" -#include "perspective-line.h" -#include "selection-chemistry.h" -#include "selection.h" -#include "verbs.h" - -#include "display/sp-canvas-item.h" - #include "include/macros.h" - +#include "message-context.h" #include "object/box3d-side.h" #include "object/box3d.h" #include "object/sp-defs.h" #include "object/sp-namedview.h" - +#include "perspective-line.h" +#include "selection-chemistry.h" +#include "selection.h" #include "ui/pixmaps/cursor-3dbox.xpm" - #include "ui/shape-editor.h" -#include "ui/tools/box3d-tool.h" -#include "ui/widget/canvas.h" // Forced redraw - +#include "ui/widget/canvas.h" // Forced redraw +#include "verbs.h" #include "xml/node-event-vector.h" using Inkscape::DocumentUndo; @@ -54,8 +48,9 @@ namespace Inkscape { namespace UI { namespace Tools { -const std::string& Box3dTool::getPrefsPath() { - return Box3dTool::prefsPath; +const std::string &Box3dTool::getPrefsPath() +{ + return Box3dTool::prefsPath; } const std::string Box3dTool::prefsPath = "/tools/shapes/3dbox"; @@ -66,10 +61,10 @@ Box3dTool::Box3dTool() , box3d(nullptr) , ctrl_dragged(false) , extruded(false) -{ -} +{} -void Box3dTool::finish() { +void Box3dTool::finish() +{ sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); this->finishItem(); this->sel_changed_connection.disconnect(); @@ -77,8 +72,8 @@ void Box3dTool::finish() { ToolBase::finish(); } - -Box3dTool::~Box3dTool() { +Box3dTool::~Box3dTool() +{ this->enableGrDrag(false); delete (this->_vpdrag); @@ -99,7 +94,8 @@ Box3dTool::~Box3dTool() { * Callback that processes the "changed" signal on the selection; * destroys old and creates new knotholder. */ -void Box3dTool::selection_changed(Inkscape::Selection* selection) { +void Box3dTool::selection_changed(Inkscape::Selection *selection) +{ this->shape_editor->unset_item(); this->shape_editor->set_item(selection->singleItem()); @@ -112,11 +108,12 @@ void Box3dTool::selection_changed(Inkscape::Selection* selection) { /* 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) { +static void sp_box3d_context_ensure_persp_in_defs(SPDocument *document) +{ SPDefs *defs = document->getDefs(); bool has_persp = false; - for (auto& child: defs->children) { + for (auto &child : defs->children) { if (SP_IS_PERSP3D(&child)) { has_persp = true; break; @@ -124,11 +121,12 @@ static void sp_box3d_context_ensure_persp_in_defs(SPDocument *document) { } if (!has_persp) { - document->setCurrentPersp3D(Persp3D::create_xml_element (document)); + document->setCurrentPersp3D(Persp3D::create_xml_element(document)); } } -void Box3dTool::setup() { +void Box3dTool::setup() +{ ToolBase::setup(); this->shape_editor = new ShapeEditor(this->desktop); @@ -139,9 +137,8 @@ void Box3dTool::setup() { } this->sel_changed_connection.disconnect(); - this->sel_changed_connection = this->desktop->getSelection()->connectChanged( - sigc::mem_fun(this, &Box3dTool::selection_changed) - ); + this->sel_changed_connection = + this->desktop->getSelection()->connectChanged(sigc::mem_fun(this, &Box3dTool::selection_changed)); this->_vpdrag = new Box3D::VPDrag(this->desktop->getDocument()); @@ -156,31 +153,33 @@ void Box3dTool::setup() { } } -bool Box3dTool::item_handler(SPItem* item, GdkEvent* event) { +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; + 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); -// } + // 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) { +bool Box3dTool::root_handler(GdkEvent *event) +{ static bool dragging; SPDocument *document = desktop->getDocument(); @@ -195,319 +194,313 @@ bool Box3dTool::root_handler(GdkEvent* event) { 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 ), - nullptr, 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; + 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(); + } - this->drag_ptB_proj = cur_persp->perspective_impl->tmat.preimage (motion_dt, 0, Proj::Z); - this->drag_ptC_proj = this->drag_ptB_proj; + /* 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; - } 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); + 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), + nullptr, event->button.time); + ret = TRUE; } + break; - m.unSetup(); - - this->drag(event->motion.state); + 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; + } - ret = TRUE; - } else if (!this->sp_event_context_knot_mouseover()) { - SnapManager &m = desktop->namedview->snap_manager; - m.setup(desktop); + if (!this->extruded) { + this->drag_ptB = motion_dt; + this->drag_ptC = motion_dt; - 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); + 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 { - selection->set(this->item_to_select); + // 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); } - } else { - // click in an empty space - selection->clear(); - } - - this->item_to_select = nullptr; - ret = TRUE; - sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); - } - break; - - case GDK_KEY_PRESS: - switch (get_latin_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: - document->getCurrentPersp3D()->rotate_VP (Proj::X, 180 / snaps * y_dir, MOD__ALT(event)); - DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, - _("Change perspective (angle of PLs)")); - ret = true; - break; - - case GDK_KEY_bracketleft: - document->getCurrentPersp3D()->rotate_VP (Proj::X, -180 / snaps * y_dir, MOD__ALT(event)); - DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, - _("Change perspective (angle of PLs)")); - ret = true; - break; - - case GDK_KEY_parenright: - document->getCurrentPersp3D()->rotate_VP (Proj::Y, 180 / snaps * y_dir, MOD__ALT(event)); - DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, - _("Change perspective (angle of PLs)")); - ret = true; - break; - case GDK_KEY_parenleft: - document->getCurrentPersp3D()->rotate_VP (Proj::Y, -180 / snaps * y_dir, MOD__ALT(event)); - DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, - _("Change perspective (angle of PLs)")); - ret = true; - break; + m.unSetup(); - case GDK_KEY_braceright: - document->getCurrentPersp3D()->rotate_VP (Proj::Z, 180 / snaps * y_dir, MOD__ALT(event)); - DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, - _("Change perspective (angle of PLs)")); - ret = true; - break; - - case GDK_KEY_braceleft: - document->getCurrentPersp3D()->rotate_VP (Proj::Z, -180 / snaps * y_dir, MOD__ALT(event)); - DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, - _("Change perspective (angle of PLs)")); - ret = true; - break; - - case GDK_KEY_g: - case GDK_KEY_G: - if (MOD__SHIFT_ONLY(event)) { - desktop->selection->toGuides(); - ret = true; - } - break; - - case GDK_KEY_p: - case GDK_KEY_P: - if (MOD__SHIFT_ONLY(event)) { - if (document->getCurrentPersp3D()) { - document->getCurrentPersp3D()->print_debugging_info(); - } - ret = true; - } - break; + this->drag(event->motion.state); - case GDK_KEY_x: - case GDK_KEY_X: - if (MOD__ALT_ONLY(event)) { - desktop->setToolboxFocusTo ("box3d-angle-x"); 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; + } 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_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_BUTTON_RELEASE: + this->xp = this->yp = 0; - case GDK_KEY_Escape: - desktop->getSelection()->clear(); - //TODO: make dragging escapable by Esc - break; - - case GDK_KEY_space: - if (dragging) { - sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); + 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(); } - // do not return true, so that space would work switching to selector + + this->item_to_select = nullptr; + ret = TRUE; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); } break; - case GDK_KEY_Delete: - case GDK_KEY_KP_Delete: - case GDK_KEY_BackSpace: - ret = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); + case GDK_KEY_PRESS: + switch (get_latin_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: + document->getCurrentPersp3D()->rotate_VP(Proj::X, 180 / snaps * y_dir, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, _("Change perspective (angle of PLs)")); + ret = true; + break; + + case GDK_KEY_bracketleft: + document->getCurrentPersp3D()->rotate_VP(Proj::X, -180 / snaps * y_dir, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, _("Change perspective (angle of PLs)")); + ret = true; + break; + + case GDK_KEY_parenright: + document->getCurrentPersp3D()->rotate_VP(Proj::Y, 180 / snaps * y_dir, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, _("Change perspective (angle of PLs)")); + ret = true; + break; + + case GDK_KEY_parenleft: + document->getCurrentPersp3D()->rotate_VP(Proj::Y, -180 / snaps * y_dir, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, _("Change perspective (angle of PLs)")); + ret = true; + break; + + case GDK_KEY_braceright: + document->getCurrentPersp3D()->rotate_VP(Proj::Z, 180 / snaps * y_dir, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, _("Change perspective (angle of PLs)")); + ret = true; + break; + + case GDK_KEY_braceleft: + document->getCurrentPersp3D()->rotate_VP(Proj::Z, -180 / snaps * y_dir, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, _("Change perspective (angle of PLs)")); + ret = true; + break; + + case GDK_KEY_g: + case GDK_KEY_G: + if (MOD__SHIFT_ONLY(event)) { + desktop->selection->toGuides(); + ret = true; + } + break; + + case GDK_KEY_p: + case GDK_KEY_P: + if (MOD__SHIFT_ONLY(event)) { + if (document->getCurrentPersp3D()) { + document->getCurrentPersp3D()->print_debugging_info(); + } + ret = true; + } + break; + + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo("box3d-angle-x"); + 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: + desktop->getSelection()->clear(); + // TODO: make dragging escapable by Esc + break; + + case GDK_KEY_space: + if (dragging) { + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); + 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; - } - break; - - default: - break; } if (!ret) { - ret = ToolBase::root_handler(event); + ret = ToolBase::root_handler(event); } return ret; } -void Box3dTool::drag(guint /*state*/) { +void Box3dTool::drag(guint /*state*/) +{ if (!this->box3d) { if (Inkscape::have_viable_layer(desktop, defaultMessageContext()) == false) { return; } // Create object - SPBox3D *box3d = SPBox3D::createBox3D((SPItem*)desktop->currentLayer()); + 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); + 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); + side->front_or_rear = (Box3D::FrontOrRear)(desc & 0x8); // Set style Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -516,18 +509,17 @@ void Box3dTool::drag(guint /*state*/) { descr += side->axes_string(); descr += "/style"; - Glib::ustring cur_style = prefs->getString(descr); - + 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 + // use last used style side->setAttribute("style", cur_style); } else { - // use default style - Glib::ustring tool_path = Glib::ustring::compose("/tools/shapes/3dbox/%1", - side->axes_string()); - desktop->applyCurrentOrToolStyle (side, tool_path, false); + // use default style + Glib::ustring tool_path = Glib::ustring::compose("/tools/shapes/3dbox/%1", side->axes_string()); + desktop->applyCurrentOrToolStyle(side, tool_path, false); } side->updateRepr(); // calls Box3DSide::write() and updates, e.g., the axes string description @@ -552,15 +544,17 @@ void Box3dTool::drag(guint /*state*/) { /* we need to call this from here (instead of from SPBox3D::position_set(), for example) because z-order setting must not interfere with display updates during undo/redo */ - this->box3d->set_z_orders (); + this->box3d->set_z_orders(); this->box3d->position_set(); // status text - this->message_context->setF(Inkscape::NORMAL_MESSAGE, "%s", _("<b>3D Box</b>; with <b>Shift</b> to extrude along the Z axis")); + 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() { +void Box3dTool::finishItem() +{ this->message_context->clear(); this->ctrl_dragged = false; this->extruded = false; @@ -582,16 +576,15 @@ void Box3dTool::finishItem() { forced_redraws_stop(); desktop->getSelection()->set(this->box3d); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_3DBOX, - _("Create 3D box")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_3DBOX, _("Create 3D box")); this->box3d = nullptr; } } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/box3d-tool.h b/src/ui/tools/box3d-tool.h index 1ae63a0ad66dcab7153aae0b51568c6e2eb88dc8..b3409baba72ebc6d5b79c3f53612b18abc8eeb59 100644 --- a/src/ui/tools/box3d-tool.h +++ b/src/ui/tools/box3d-tool.h @@ -16,52 +16,52 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstddef> - #include <2geom/point.h> +#include <cstddef> #include <sigc++/connection.h> #include "proj_pt.h" -#include "vanishing-point.h" - #include "ui/tools/tool-base.h" +#include "vanishing-point.h" class SPItem; class SPBox3D; namespace Box3D { - struct VPDrag; +struct VPDrag; } namespace Inkscape { - class Selection; +class Selection; } -#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) +#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 { +class Box3dTool : public ToolBase +{ public: - Box3dTool(); - ~Box3dTool() override; + Box3dTool(); + ~Box3dTool() override; - Box3D::VPDrag * _vpdrag; + Box3D::VPDrag *_vpdrag; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - void finish() override; - bool root_handler(GdkEvent* event) override; - bool item_handler(SPItem* item, GdkEvent* event) override; + void setup() override; + void finish() override; + bool root_handler(GdkEvent *event) override; + bool item_handler(SPItem *item, GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; private: - SPBox3D* box3d; + SPBox3D *box3d; Geom::Point center; /** @@ -81,19 +81,19 @@ private: Proj::Pt3 drag_ptC_proj; bool ctrl_dragged; /* whether we are ctrl-dragging */ - bool extruded; /* whether shift-dragging already occurred (i.e. the box is already extruded) */ + bool extruded; /* whether shift-dragging already occurred (i.e. the box is already extruded) */ sigc::connection sel_changed_connection; - void selection_changed(Inkscape::Selection* selection); + void selection_changed(Inkscape::Selection *selection); - void drag(guint state); - void finishItem(); + void drag(guint state); + void finishItem(); }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif /* __SP_BOX3D_CONTEXT_H__ */ diff --git a/src/ui/tools/calligraphic-tool.cpp b/src/ui/tools/calligraphic-tool.cpp index bb17410d612f3d536e6563e2862c045f4b754b9c..810efcdcb50e50c7695b08e0927df250dbd381e2 100644 --- a/src/ui/tools/calligraphic-tool.cpp +++ b/src/ui/tools/calligraphic-tool.cpp @@ -24,50 +24,41 @@ #define noDYNA_DRAW_VERBOSE -#include <gtk/gtk.h> -#include <gdk/gdkkeysyms.h> -#include <glibmm/i18n.h> -#include <string> -#include <cstring> -#include <numeric> +#include "ui/tools/calligraphic-tool.h" -#include <2geom/pathvector.h> #include <2geom/bezier-utils.h> #include <2geom/circle.h> +#include <2geom/pathvector.h> +#include <cstring> +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> +#include <gtk/gtk.h> +#include <numeric> +#include <string> #include "context-fns.h" #include "desktop-events.h" #include "desktop-style.h" #include "desktop.h" -#include "document-undo.h" -#include "document.h" -#include "inkscape.h" -#include "message-context.h" -#include "selection.h" -#include "verbs.h" - #include "display/cairo-utils.h" #include "display/canvas-arena.h" #include "display/canvas-bpath.h" #include "display/curve.h" - +#include "document-undo.h" +#include "document.h" #include "include/macros.h" - +#include "inkscape.h" #include "livarot/Path.h" #include "livarot/Shape.h" - +#include "message-context.h" #include "object/sp-shape.h" #include "object/sp-text.h" - #include "path/path-util.h" - -#include "ui/pixmaps/cursor-calligraphy.xpm" - +#include "selection.h" #include "svg/svg.h" - - -#include "ui/tools/calligraphic-tool.h" +#include "ui/pixmaps/cursor-calligraphy.xpm" #include "ui/tools/freehand-base.h" +#include "verbs.h" using Inkscape::DocumentUndo; @@ -85,11 +76,11 @@ namespace Inkscape { namespace UI { namespace Tools { -const std::string& CalligraphicTool::getPrefsPath() { - return CalligraphicTool::prefsPath; +const std::string &CalligraphicTool::getPrefsPath() +{ + return CalligraphicTool::prefsPath; } - const std::string CalligraphicTool::prefsPath = "/tools/calligraphic"; CalligraphicTool::CalligraphicTool() @@ -99,8 +90,8 @@ CalligraphicTool::CalligraphicTool() , hatch_spacing_step(0) , hatch_item(nullptr) , hatch_livarot_path(nullptr) - , hatch_last_nearest(Geom::Point(0,0)) - , hatch_last_pointer(Geom::Point(0,0)) + , hatch_last_nearest(Geom::Point(0, 0)) + , hatch_last_pointer(Geom::Point(0, 0)) , hatch_escaped(false) , hatch_area(nullptr) , just_started_drawing(false) @@ -112,14 +103,16 @@ CalligraphicTool::CalligraphicTool() this->abs_width = false; } -CalligraphicTool::~CalligraphicTool() { +CalligraphicTool::~CalligraphicTool() +{ if (this->hatch_area) { sp_canvas_item_destroy(this->hatch_area); this->hatch_area = nullptr; } } -void CalligraphicTool::setup() { +void CalligraphicTool::setup() +{ DynamicBase::setup(); this->accumulated.reset(new SPCurve()); @@ -130,21 +123,23 @@ void CalligraphicTool::setup() { this->currentshape = sp_canvas_item_new(desktop->getSketch(), SP_TYPE_CANVAS_BPATH, nullptr); 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); + 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); { /* TODO: have a look at DropperTool::setup where the same is done.. generalize? */ - Geom::PathVector path = Geom::Path(Geom::Circle(0,0,1)); + Geom::PathVector path = Geom::Path(Geom::Circle(0, 0, 1)); auto c = std::make_unique<SPCurve>(path); hatch_area = sp_canvas_bpath_new(desktop->getControls(), c.get(), true); - 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_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); } @@ -170,7 +165,8 @@ void CalligraphicTool::setup() { } } -void CalligraphicTool::set(const Inkscape::Preferences::Entry& val) { +void CalligraphicTool::set(const Inkscape::Preferences::Entry &val) +{ Glib::ustring path = val.getEntryName(); if (path == "tracebackground") { @@ -178,21 +174,20 @@ void CalligraphicTool::set(const Inkscape::Preferences::Entry& val) { } else if (path == "keep_selected") { this->keep_selected = val.getBool(); } else { - //pass on up to parent class to handle common attributes. - DynamicBase::set(val); + // 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); + // 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) +static double flerp(double f0, double f1, double p) { - return f0 + ( f1 - f0 ) * p; + return f0 + (f1 - f0) * p; } ///* Get normalized point */ -//Geom::Point CalligraphicTool::getNormalizedPoint(Geom::Point v) const { +// 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] ); @@ -201,7 +196,7 @@ flerp(double f0, double f1, double p) //} // ///* Get view point */ -//Geom::Point CalligraphicTool::getViewPoint(Geom::Point n) const { +// 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] ); @@ -209,38 +204,40 @@ flerp(double f0, double f1, double p) // 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) { +void CalligraphicTool::reset(Geom::Point p) +{ this->last = this->cur = this->getNormalizedPoint(p); - this->vel = Geom::Point(0,0); + 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); + 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); +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); + 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); + 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) { +bool CalligraphicTool::apply(Geom::Point p) +{ Geom::Point n = this->getNormalizedPoint(p); /* Calculate mass and drag */ @@ -257,7 +254,7 @@ bool CalligraphicTool::apply(Geom::Point p) { // 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)) { + if (Geom::L2(force) < DYNA_EPSILON || (this->vel_max < DYNA_VEL_START && Geom::L2(force) < DYNA_EPSILON_START)) { return FALSE; } @@ -282,22 +279,21 @@ bool CalligraphicTool::apply(Geom::Point p) { Geom::Point dir(-this->xtilt, this->ytilt); a1 = atan2(dir); } - } - else { + } else { // 1b. fixed dc->angle (absolutely flat nib): - a1 = ( this->angle / 180.0 ) * M_PI; + a1 = (this->angle / 180.0) * M_PI; } a1 *= -desktop->yaxisdir(); a1 = fmod(a1, M_PI); - if (a1 > 0.5*M_PI) { + if (a1 > 0.5 * M_PI) { a1 -= M_PI; - } else if (a1 <= -0.5*M_PI) { + } else if (a1 <= -0.5 * M_PI) { a1 += M_PI; } // 2. perpendicular to dc->vel (absolutely non-flat nib): gdouble const mag_vel = Geom::L2(this->vel); - if ( mag_vel < DYNA_EPSILON ) { + if (mag_vel < DYNA_EPSILON) { return FALSE; } Geom::Point ang2 = Geom::rot90(this->vel) / mag_vel; @@ -307,30 +303,31 @@ bool CalligraphicTool::apply(Geom::Point p) { 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) { + if (fabs(a2 - a1) > 0.5 * M_PI) { a2 += M_PI; flipped = true; } // normalize a2 if (a2 > M_PI) - a2 -= 2*M_PI; + a2 -= 2 * M_PI; if (a2 < -M_PI) - a2 += 2*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); + 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 ) { + 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)); + 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); + // 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; @@ -342,11 +339,12 @@ bool CalligraphicTool::apply(Geom::Point p) { return TRUE; } -void CalligraphicTool::brush() { - g_assert( this->npoints >= 0 && this->npoints < SAMPLING_SIZE ); +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); + double vel_thin = flerp(0, 160, this->vel_thin); // Influence of pressure on thickness double pressure_thick = (this->usepressure ? this->pressure : 1.0); @@ -365,11 +363,11 @@ void CalligraphicTool::brush() { sp_canvas_arena_render_surface(SP_CANVAS_ARENA(desktop->getDrawing()), 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 + 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); + // g_print ("L %g thick %g\n", L, trace_thick); } double width = (pressure_thick * trace_thick - vel_thin * Geom::L2(this->vel)) * this->width; @@ -379,11 +377,11 @@ void CalligraphicTool::brush() { // 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; + 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 ); + } while (w >= 1.0); + w = sqrt((-2.0 * log(w)) / w); y1 = x1 * w; y2 = x2 * w; @@ -392,11 +390,11 @@ void CalligraphicTool::brush() { // (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)); + 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 ) { + if (width < 0.02 * this->width) { width = 0.02 * this->width; } @@ -411,38 +409,39 @@ void CalligraphicTool::brush() { this->point1[this->npoints] = brush + del_left; this->point2[this->npoints] = brush - del_right; - this->del = 0.5*(del_left + 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) +static void sp_ddc_update_toolbox(SPDesktop *desktop, const gchar *id, double value) { - desktop->setToolboxAdjustmentValue (id, value); + desktop->setToolboxAdjustmentValue(id, value); } -void CalligraphicTool::cancel() { +void CalligraphicTool::cancel() +{ this->dragging = false; this->is_drawing = false; sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); - /* Remove all temporary line segments */ - for (auto i:this->segments) + /* Remove all temporary line segments */ + for (auto i : this->segments) sp_canvas_item_destroy(SP_CANVAS_ITEM(i)); this->segments.clear(); - /* reset accumulated curve */ - this->accumulated->reset(); - this->clear_current(); + /* reset accumulated curve */ + this->accumulated->reset(); + this->clear_current(); - if (this->repr) { - this->repr = nullptr; - } + if (this->repr) { + this->repr = nullptr; + } } -bool CalligraphicTool::root_handler(GdkEvent* event) { +bool CalligraphicTool::root_handler(GdkEvent *event) +{ gint ret = FALSE; switch (event->type) { @@ -461,13 +460,10 @@ bool CalligraphicTool::root_handler(GdkEvent* event) { /* 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 ), - nullptr, - event->button.time); + 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), + nullptr, event->button.time); ret = TRUE; @@ -477,10 +473,8 @@ bool CalligraphicTool::root_handler(GdkEvent* event) { this->just_started_drawing = true; } break; - case GDK_MOTION_NOTIFY: - { - Geom::Point const motion_w(event->motion.x, - event->motion.y); + 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); @@ -488,9 +482,9 @@ bool CalligraphicTool::root_handler(GdkEvent* event) { // for hatching: double hatch_dist = 0; - Geom::Point hatch_unit_vector(0,0); - Geom::Point nearest(0,0); - Geom::Point pointer(0,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 @@ -504,7 +498,7 @@ bool CalligraphicTool::root_handler(GdkEvent* event) { 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 = Path_for_item(this->hatch_item, true, true); this->hatch_livarot_path->ConvertWithBackData(0.01); } @@ -513,22 +507,25 @@ bool CalligraphicTool::root_handler(GdkEvent* event) { 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); + 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; + 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>")); + 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>")); + 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) { + 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 @@ -569,50 +566,53 @@ bool CalligraphicTool::root_handler(GdkEvent* event) { // 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); + 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); + 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 + 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 - ) { + || (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); + // 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 + 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(); + Geom::Point inertia = this->inertia_vectors.front() - this->inertia_vectors.back(); - double dot = Geom::dot (moved_past_escape, inertia); + 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); + 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); + 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 @@ -623,9 +623,10 @@ bool CalligraphicTool::root_handler(GdkEvent* event) { } 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; + target = + (this->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed)) / SPEED_NORMAL; } - if (!std::isnan(dot) && dot < -0.5) {// flip + if (!std::isnan(dot) && dot < -0.5) { // flip target = -target; } @@ -634,7 +635,7 @@ bool CalligraphicTool::root_handler(GdkEvent* event) { // some limited feedback: allow persistent pulling to slightly change // the spacing - this->hatch_spacing += (hatch_dist - this->hatch_spacing)/3500; + this->hatch_spacing += (hatch_dist - this->hatch_spacing) / 3500; // return it to the desktop coords motion_dt = new_pointer * motion_to_curve.inverse(); @@ -659,7 +660,10 @@ bool CalligraphicTool::root_handler(GdkEvent* event) { 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")); + 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")); @@ -675,9 +679,9 @@ bool CalligraphicTool::root_handler(GdkEvent* event) { break; } - if ( this->cur != this->last ) { + if (this->cur != this->last) { this->brush(); - g_assert( this->npoints > 0 ); + g_assert(this->npoints > 0); this->fit_and_split(false); } ret = TRUE; @@ -688,214 +692,223 @@ bool CalligraphicTool::root_handler(GdkEvent* event) { 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)); + 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_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)); + 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_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)); + 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_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 (!std::isnan(c[Geom::X]) && !std::isnan(c[Geom::Y])) { - Geom::Affine const sm (Geom::Scale(this->hatch_spacing, this->hatch_spacing) * Geom::Translate(c)); + 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_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; + } 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)); - 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)); + forced_redraws_stop(); + set_high_motion_precision(false); + this->is_drawing = false; - sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); - forced_redraws_stop(); - set_high_motion_precision(false); - this->is_drawing = false; + if (this->dragging && event->button.button == 1 && !this->space_panning) { + this->dragging = FALSE; - if (this->dragging && event->button.button == 1 && !this->space_panning) { - this->dragging = FALSE; + this->apply(motion_dt); - this->apply(motion_dt); + /* Remove all temporary line segments */ + for (auto i : this->segments) + sp_canvas_item_destroy(SP_CANVAS_ITEM(i)); + this->segments.clear(); - /* Remove all temporary line segments */ - for (auto i:this->segments) - sp_canvas_item_destroy(SP_CANVAS_ITEM(i)); - this->segments.clear(); + /* 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"); - /* 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 = nullptr; - } + /* reset accumulated curve */ + this->accumulated->reset(); - 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 = nullptr; - this->hatch_livarot_path = nullptr; - 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->clear_current(); + if (this->repr) { + this->repr = nullptr; } - this->hatch_spacing += this->hatch_spacing_step; - } - this->message_context->clear(); - ret = TRUE; - } else if (!this->dragging && event->button.button == 1 && !this->space_panning){ - spdc_create_single_dot(this, desktop->w2d(motion_w), "/tools/calligraphic", event->button.state); - } - break; - } + 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 = nullptr; + this->hatch_livarot_path = nullptr; + 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; + } - case GDK_KEY_PRESS: - switch (get_latin_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, "calligraphy-width", this->width * 100); // the same spinbutton is for alt+x + this->message_context->clear(); ret = TRUE; + } else if (!this->dragging && event->button.button == 1 && !this->space_panning) { + spdc_create_single_dot(this, desktop->w2d(motion_w), "/tools/calligraphic", event->button.state); } break; - case GDK_KEY_Left: - case GDK_KEY_KP_Left: - if (!MOD__CTRL_ONLY(event)) { - this->width -= 0.01; - if (this->width < 0.01) + } + + case GDK_KEY_PRESS: + switch (get_latin_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, "calligraphy-width", + 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, "calligraphy-width", this->width * 100); + ret = TRUE; + } + break; + case GDK_KEY_Home: + case GDK_KEY_KP_Home: this->width = 0.01; - sp_ddc_update_toolbox (desktop, "calligraphy-width", this->width * 100); - ret = TRUE; - } - break; - case GDK_KEY_Home: - case GDK_KEY_KP_Home: - this->width = 0.01; - sp_ddc_update_toolbox (desktop, "calligraphy-width", this->width * 100); - ret = TRUE; - break; - case GDK_KEY_End: - case GDK_KEY_KP_End: - this->width = 1.0; - sp_ddc_update_toolbox (desktop, "calligraphy-width", this->width * 100); - ret = TRUE; - break; - case GDK_KEY_x: - case GDK_KEY_X: - if (MOD__ALT_ONLY(event)) { - desktop->setToolboxFocusTo ("calligraphy-width"); - ret = TRUE; - } - break; - case GDK_KEY_Escape: - if (this->is_drawing) { - // if drawing, cancel, otherwise pass it up for deselecting - this->cancel(); - ret = TRUE; + sp_ddc_update_toolbox(desktop, "calligraphy-width", this->width * 100); + ret = TRUE; + break; + case GDK_KEY_End: + case GDK_KEY_KP_End: + this->width = 1.0; + sp_ddc_update_toolbox(desktop, "calligraphy-width", this->width * 100); + ret = TRUE; + break; + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo("calligraphy-width"); + 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_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; + + case GDK_KEY_RELEASE: + switch (get_latin_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; - } - break; - - case GDK_KEY_RELEASE: - switch (get_latin_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); + // 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() { +void CalligraphicTool::clear_current() +{ /* reset bpath */ sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->currentshape), nullptr); /* reset curve */ @@ -906,7 +919,8 @@ void CalligraphicTool::clear_current() { this->npoints = 0; } -void CalligraphicTool::set_to_accumulated(bool unionize, bool subtract) { +void CalligraphicTool::set_to_accumulated(bool unionize, bool subtract) +{ if (!this->accumulated->is_empty()) { if (!this->repr) { /* Create object */ @@ -914,11 +928,11 @@ void CalligraphicTool::set_to_accumulated(bool unionize, bool subtract) { Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); /* Set style */ - sp_desktop_apply_style_tool (desktop, repr, "/tools/calligraphic", false); + sp_desktop_apply_style_tool(desktop, repr, "/tools/calligraphic", false); this->repr = repr; - SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(this->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(); @@ -926,7 +940,7 @@ void CalligraphicTool::set_to_accumulated(bool unionize, bool subtract) { Geom::PathVector pathv = this->accumulated->get_pathvector() * desktop->dt2doc(); gchar *str = sp_svg_write_path(pathv); - g_assert( str != nullptr ); + g_assert(str != nullptr); this->repr->setAttribute("d", str); g_free(str); @@ -963,69 +977,60 @@ void CalligraphicTool::set_to_accumulated(bool unionize, bool subtract) { this->repr = nullptr; } - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_CALLIGRAPHIC, - _("Draw calligraphic stroke")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_CALLIGRAPHIC, _("Draw calligraphic stroke")); } -static void -add_cap(SPCurve &curve, - Geom::Point const &from, - Geom::Point const &to, - double rounding) +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); + 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 ); + 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(); +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 - } + return false; // failure + } - auto rev_cal2 = this->cal2->create_reverse(); + auto rev_cal2 = this->cal2->create_reverse(); - if ((rev_cal2->get_segment_count() <= 0) || rev_cal2->first_path()->closed()) { - this->cal1->reset(); - this->cal2->reset(); + if ((rev_cal2->get_segment_count() <= 0) || rev_cal2->first_path()->closed()) { + this->cal1->reset(); + this->cal2->reset(); - return false; // failure - } + 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(); + 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->reset(); /* Is this required ?? */ - this->accumulated->append(*cal1); + this->accumulated->append(*cal1); - add_cap(*accumulated, dc_cal1_lastseg->finalPoint(), rev_cal2_firstseg->initialPoint(), cap_rounding); + add_cap(*accumulated, dc_cal1_lastseg->finalPoint(), rev_cal2_firstseg->initialPoint(), cap_rounding); - this->accumulated->append(*rev_cal2, true); + this->accumulated->append(*rev_cal2, true); - add_cap(*accumulated, rev_cal2_lastseg->finalPoint(), dc_cal1_firstseg->initialPoint(), cap_rounding); + add_cap(*accumulated, rev_cal2_lastseg->finalPoint(), dc_cal1_firstseg->initialPoint(), cap_rounding); - this->accumulated->closepath(); + this->accumulated->closepath(); - this->cal1->reset(); - this->cal2->reset(); + this->cal1->reset(); + this->cal2->reset(); - return true; // success + return true; // success } static double square(double const x) @@ -1033,29 +1038,29 @@ 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 ); +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'); + g_print("[F&S:R=%c]", release ? 'T' : 'F'); #endif - if (!( this->npoints > 0 && this->npoints < SAMPLING_SIZE )) { + 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 ) + 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"); + 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() ) { + if (this->cal1->is_empty() || this->cal2->is_empty()) { /* dc->npoints > 0 */ /* g_print("calligraphics(1|2) reset\n"); */ this->cal1->reset(); @@ -1066,29 +1071,27 @@ void CalligraphicTool::fit_and_split(bool release) { } 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)) ); + 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)) ); + 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 ) { + 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) { + 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->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?? @@ -1128,24 +1131,27 @@ void CalligraphicTool::fit_and_split(bool release) { if (!release) { g_assert(!this->currentcurve->is_empty()); - SPCanvasItem *cbp = sp_canvas_item_new(desktop->getSketch(), - SP_TYPE_CANVAS_BPATH, - nullptr); + SPCanvasItem *cbp = sp_canvas_item_new(desktop->getSketch(), SP_TYPE_CANVAS_BPATH, nullptr); auto curve = this->currentcurve->copy(); sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cbp), curve.get(), true); - 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); + 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.push_back(cbp); } @@ -1157,12 +1163,13 @@ void CalligraphicTool::fit_and_split(bool release) { } } -void CalligraphicTool::draw_temporary_box() { +void CalligraphicTool::draw_temporary_box() +{ this->currentcurve->reset(); - this->currentcurve->moveto(this->point2[this->npoints-1]); + this->currentcurve->moveto(this->point2[this->npoints - 1]); - for (gint i = this->npoints-2; i >= 0; i--) { + for (gint i = this->npoints - 2; i >= 0; i--) { this->currentcurve->lineto(this->point2[i]); } @@ -1178,10 +1185,9 @@ void CalligraphicTool::draw_temporary_box() { sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(currentshape), currentcurve.get(), true); } -} -} -} - +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/calligraphic-tool.h b/src/ui/tools/calligraphic-tool.h index 924d018f1d56ca962b9dc76a588e189b6c797e19..d86bccdd0448d88c2327588ac70aa81d2899bdc9 100644 --- a/src/ui/tools/calligraphic-tool.h +++ b/src/ui/tools/calligraphic-tool.h @@ -19,41 +19,41 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <2geom/point.h> #include <list> #include <string> -#include <2geom/point.h> - #include "ui/tools/dynamic-base.h" class SPItem; class Path; struct SPCanvasItem; -#define DDC_MIN_PRESSURE 0.0 -#define DDC_MAX_PRESSURE 1.0 -#define DDC_DEFAULT_PRESSURE 1.0 +#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 +#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 { +class CalligraphicTool : public DynamicBase +{ public: - CalligraphicTool(); - ~CalligraphicTool() override; + CalligraphicTool(); + ~CalligraphicTool() override; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - void set(const Inkscape::Preferences::Entry& val) override; - bool root_handler(GdkEvent* event) override; + void setup() override; + void set(const Inkscape::Preferences::Entry &val) override; + bool root_handler(GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; private: /** newly created object remain selected */ @@ -73,21 +73,21 @@ private: 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); + 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); }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif // SP_DYNA_DRAW_CONTEXT_H_SEEN diff --git a/src/ui/tools/connector-tool.cpp b/src/ui/tools/connector-tool.cpp index 3dea4c6cab66321727d30f694ad3d98a2837c568..bca43813192584dfefa15197e88b1c3c33e3e7f5 100644 --- a/src/ui/tools/connector-tool.cpp +++ b/src/ui/tools/connector-tool.cpp @@ -67,45 +67,38 @@ * */ -#include <string> -#include <cstring> +#include "ui/tools/connector-tool.h" +#include <cstring> +#include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> #include <glibmm/stringutils.h> -#include <gdk/gdkkeysyms.h> +#include <string> +#include "3rdparty/adaptagrams/libavoid/router.h" #include "context-fns.h" #include "desktop-style.h" #include "desktop.h" +#include "display/canvas-bpath.h" +#include "display/curve.h" #include "document-undo.h" #include "document.h" #include "inkscape.h" #include "message-context.h" #include "message-stack.h" -#include "selection.h" -#include "snap.h" -#include "verbs.h" - -#include "display/canvas-bpath.h" -#include "display/curve.h" - -#include "3rdparty/adaptagrams/libavoid/router.h" - #include "object/sp-conn-end.h" #include "object/sp-flowtext.h" #include "object/sp-namedview.h" #include "object/sp-path.h" +#include "object/sp-symbol.h" #include "object/sp-text.h" #include "object/sp-use.h" -#include "object/sp-symbol.h" - -#include "ui/pixmaps/cursor-connector.xpm" -#include "ui/widget/canvas.h" // Enter events - +#include "selection.h" +#include "snap.h" #include "svg/svg.h" - -#include "ui/tools/connector-tool.h" - +#include "ui/pixmaps/cursor-connector.xpm" +#include "ui/widget/canvas.h" // Enter events +#include "verbs.h" #include "xml/node-event-vector.h" using Inkscape::DocumentUndo; @@ -116,37 +109,34 @@ 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_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 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 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 = { - nullptr, /* child_added */ - nullptr, /* child_added */ - shape_event_attr_changed, - nullptr, /* content_changed */ - nullptr /* order_changed */ + nullptr, /* child_added */ + nullptr, /* child_added */ + shape_event_attr_changed, nullptr, /* content_changed */ + nullptr /* order_changed */ }; static Inkscape::XML::NodeEventVector layer_repr_events = { - nullptr, /* child_added */ - shape_event_attr_deleted, - nullptr, /* child_added */ - nullptr, /* content_changed */ - nullptr /* order_changed */ + nullptr, /* child_added */ + shape_event_attr_deleted, nullptr, /* child_added */ + nullptr, /* content_changed */ + nullptr /* order_changed */ }; -std::string const& ConnectorTool::getPrefsPath() +std::string const &ConnectorTool::getPrefsPath() { return ConnectorTool::prefsPath; } @@ -194,9 +184,9 @@ ConnectorTool::~ConnectorTool() { this->sel_changed_connection.disconnect(); - for (auto & i : this->endpt_handle) { + for (auto &i : this->endpt_handle) { if (this->endpt_handle[1]) { - //g_object_unref(this->endpt_handle[i]); + // g_object_unref(this->endpt_handle[i]); knot_unref(i); i = nullptr; } @@ -212,7 +202,7 @@ ConnectorTool::~ConnectorTool() this->shref = nullptr; } - g_assert( this->newConnRef == nullptr ); + g_assert(this->newConnRef == nullptr); } void ConnectorTool::setup() @@ -222,16 +212,14 @@ void ConnectorTool::setup() this->selection = desktop->getSelection(); this->sel_changed_connection.disconnect(); - this->sel_changed_connection = this->selection->connectChanged( - sigc::mem_fun(this, &ConnectorTool::_selectionChanged) - ); + this->sel_changed_connection = + this->selection->connectChanged(sigc::mem_fun(this, &ConnectorTool::_selectionChanged)); /* Create red bpath */ this->red_bpath = sp_canvas_bpath_new(desktop->getSketch(), nullptr); - 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); + 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 = std::make_unique<SPCurve>(); @@ -239,7 +227,7 @@ void ConnectorTool::setup() green_curve = std::make_unique<SPCurve>(); // Notice the initial selection. - //cc_selection_changed(this->selection, (gpointer) this); + // cc_selection_changed(this->selection, (gpointer) this); this->_selectionChanged(this->selection); this->within_tolerance = false; @@ -256,7 +244,7 @@ void ConnectorTool::setup() desktop->getCanvas()->set_all_enter_events(true); } -void ConnectorTool::set(const Inkscape::Preferences::Entry& val) +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). */ @@ -289,14 +277,13 @@ void ConnectorTool::finish() //----------------------------------------------------------------------------- - void ConnectorTool::cc_clear_active_shape() { if (this->active_shape == nullptr) { return; } - g_assert( this->active_shape_repr ); - g_assert( this->active_shape_layer_repr ); + g_assert(this->active_shape_repr); + g_assert(this->active_shape_layer_repr); this->active_shape = nullptr; @@ -317,7 +304,7 @@ static void cc_clear_active_knots(SPKnotList k) { // Hide the connection points if they exist. if (k.size()) { - for (auto & it : k) { + for (auto &it : k) { it.first->hide(); } } @@ -328,7 +315,7 @@ void ConnectorTool::cc_clear_active_conn() if (this->active_conn == nullptr) { return; } - g_assert( this->active_conn_repr ); + g_assert(this->active_conn_repr); this->active_conn = nullptr; @@ -339,22 +326,21 @@ void ConnectorTool::cc_clear_active_conn() } // Hide the endpoint handles. - for (auto & i : this->endpt_handle) { + for (auto &i : this->endpt_handle) { if (i) { i->hide(); } } } - -bool ConnectorTool::_ptHandleTest(Geom::Point& p, gchar **href, gchar **subhref) +bool ConnectorTool::_ptHandleTest(Geom::Point &p, gchar **href, gchar **subhref) { 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()); - if(this->active_handle->sub_owner) { + if (this->active_handle->sub_owner) { auto id = this->active_handle->sub_owner->getAttribute("id"); - if(id) { + if (id) { *subhref = g_strdup_printf("#%s", id); } } else { @@ -367,7 +353,7 @@ bool ConnectorTool::_ptHandleTest(Geom::Point& p, gchar **href, gchar **subhref) return false; } -static void cc_select_handle(SPKnot* knot) +static void cc_select_handle(SPKnot *knot) { knot->setShape(SP_KNOT_SHAPE_SQUARE); knot->setSize(10); @@ -376,7 +362,7 @@ static void cc_select_handle(SPKnot* knot) knot->updateCtrl(); } -static void cc_deselect_handle(SPKnot* knot) +static void cc_deselect_handle(SPKnot *knot) { knot->setShape(SP_KNOT_SHAPE_SQUARE); knot->setSize(8); @@ -385,85 +371,85 @@ static void cc_deselect_handle(SPKnot* knot) knot->updateCtrl(); } -bool ConnectorTool::item_handler(SPItem* item, GdkEvent* event) +bool ConnectorTool::item_handler(SPItem *item, GdkEvent *event) { bool 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; - } + 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; - } + 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); + // 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 (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); + if (item != this->active_shape && !cc_item_is_connector(item)) { + this->_setActiveShape(item); + } } + + ret = true; } + break; - ret = true; - } - break; + case GDK_ENTER_NOTIFY: + if (!this->selected_handle) { + if (cc_item_is_shape(item)) { + this->_setActiveShape(item); + } - case GDK_ENTER_NOTIFY: - if (!this->selected_handle) { - if (cc_item_is_shape(item)) { - this->_setActiveShape(item); + ret = true; } + break; - ret = true; - } - break; - - default: - break; + default: + break; } return ret; } -bool ConnectorTool::root_handler(GdkEvent* event) +bool ConnectorTool::root_handler(GdkEvent *event) { bool ret = false; switch (event->type) { - case GDK_BUTTON_PRESS: - ret = this->_handleButtonPress(event->button); - break; + case GDK_BUTTON_PRESS: + ret = this->_handleButtonPress(event->button); + break; - case GDK_MOTION_NOTIFY: - ret = this->_handleMotionNotify(event->motion); - break; + case GDK_MOTION_NOTIFY: + ret = this->_handleMotionNotify(event->motion); + break; - case GDK_BUTTON_RELEASE: - ret = this->_handleButtonRelease(event->button); - break; + case GDK_BUTTON_RELEASE: + ret = this->_handleButtonRelease(event->button); + break; - case GDK_KEY_PRESS: - ret = this->_handleKeyPress(get_latin_keyval (&event->key)); - break; + case GDK_KEY_PRESS: + ret = this->_handleKeyPress(get_latin_keyval(&event->key)); + break; - default: - break; + default: + break; } if (!ret) { @@ -473,7 +459,6 @@ bool ConnectorTool::root_handler(GdkEvent* event) return ret; } - bool ConnectorTool::_handleButtonPress(GdkEventButton const &bevent) { Geom::Point const event_w(bevent.x, bevent.y); @@ -482,27 +467,26 @@ bool ConnectorTool::_handleButtonPress(GdkEventButton const &bevent) bool ret = false; - if ( bevent.button == 1 && !this->space_panning ) { - if (Inkscape::have_viable_layer(desktop, defaultMessageContext()) == false) { - return true; - } + if (bevent.button == 1 && !this->space_panning) { + if (Inkscape::have_viable_layer(desktop, defaultMessageContext()) == false) { + return true; + } - Geom::Point const event_w(bevent.x, bevent.y); + Geom::Point const event_w(bevent.x, bevent.y); - this->xp = bevent.x; - this->yp = bevent.y; - this->within_tolerance = true; + this->xp = bevent.x; + this->yp = bevent.y; + this->within_tolerance = true; - Geom::Point const event_dt = desktop->w2d(event_w); + Geom::Point const event_dt = desktop->w2d(event_w); - SnapManager &m = desktop->namedview->snap_manager; + SnapManager &m = desktop->namedview->snap_manager; - switch (this->state) { + 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 ) { + case SP_CONNECTOR_CONTEXT_IDLE: { + if (this->npoints == 0) { this->cc_clear_active_conn(); desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new connector")); @@ -522,14 +506,12 @@ bool ConnectorTool::_handleButtonPress(GdkEventButton const &bevent) m.unSetup(); } this->_setInitialPoint(p); - } this->state = SP_CONNECTOR_CONTEXT_DRAGGING; ret = true; break; } - case SP_CONNECTOR_CONTEXT_DRAGGING: - { + case SP_CONNECTOR_CONTEXT_DRAGGING: { // This is the second click of a connector creation. m.setup(desktop); m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_OTHER_HANDLE); @@ -547,30 +529,29 @@ bool ConnectorTool::_handleButtonPress(GdkEventButton const &bevent) ret = true; break; } - case SP_CONNECTOR_CONTEXT_CLOSE: - { + 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); + } + } 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; + 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; - } + // 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; } @@ -588,9 +569,8 @@ bool ConnectorTool::_handleMotionNotify(GdkEventMotion const &mevent) 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. + 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 @@ -604,61 +584,59 @@ bool ConnectorTool::_handleMotionNotify(GdkEventMotion const &mevent) SnapManager &m = desktop->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 ) { + case SP_CONNECTOR_CONTEXT_DRAGGING: { + gobble_motion_events(mevent.state); + // This is movement during a connector creation. + if (this->npoints > 0) { + m.setup(desktop); + 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(desktop); 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(desktop); - 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->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 = SPCurve::copy(path->curveForEdit()); - this->red_curve->transform(i2d); + // 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->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); - sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), this->red_curve.get(), true); - ret = true; - break; - } - case SP_CONNECTOR_CONTEXT_STOP: - /* This is perfectly valid */ - break; - default: - if (!this->sp_event_context_knot_mouseover()) { - m.setup(desktop); - m.preSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_OTHER_HANDLE)); - m.unSetup(); + // Copy this to the temporary visible path + this->red_curve = SPCurve::copy(path->curveForEdit()); + this->red_curve->transform(i2d); + + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), this->red_curve.get(), true); + ret = true; + break; } - break; + case SP_CONNECTOR_CONTEXT_STOP: + /* This is perfectly valid */ + break; + default: + if (!this->sp_event_context_knot_mouseover()) { + m.setup(desktop); + m.preSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_OTHER_HANDLE)); + m.unSetup(); + } + break; } return ret; } @@ -667,7 +645,7 @@ bool ConnectorTool::_handleButtonRelease(GdkEventButton const &revent) { bool ret = false; - if ( revent.button == 1 && !this->space_panning ) { + if (revent.button == 1 && !this->space_panning) { SPDocument *doc = desktop->getDocument(); SnapManager &m = desktop->namedview->snap_manager; @@ -677,46 +655,44 @@ bool ConnectorTool::_handleButtonRelease(GdkEventButton const &revent) Geom::Point p = 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(); + // 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) { + 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); - 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, &this->sub_ehref); - if (this->npoints != 0) { - this->_finish(); + // Test whether we clicked on a connection point + this->_ptHandleTest(p, &this->ehref, &this->sub_ehref); + if (this->npoints != 0) { + this->_finish(); + } + this->cc_set_active_conn(this->newconn); + this->state = SP_CONNECTOR_CONTEXT_IDLE; + break; } - 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); + 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; + 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; } @@ -728,35 +704,34 @@ bool ConnectorTool::_handleKeyPress(guint const keyval) bool 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) { - SPDocument *doc = desktop->getDocument(); + 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) { + SPDocument *doc = desktop->getDocument(); - this->_reroutingFinish(nullptr); + this->_reroutingFinish(nullptr); - DocumentUndo::undo(doc); + 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; + 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; } @@ -784,7 +759,7 @@ void ConnectorTool::_reroutingFinish(Geom::Point *const p) this->clickeditem->setAttribute("inkscape:connection-end-point", sub_label); } g_free(shape_label); - if(sub_label) { + if (sub_label) { g_free(sub_label); } } @@ -796,7 +771,6 @@ void ConnectorTool::_reroutingFinish(Geom::Point *const p) this->cc_set_active_conn(this->clickeditem); } - void ConnectorTool::_resetColors() { /* Red */ @@ -809,7 +783,7 @@ void ConnectorTool::_resetColors() void ConnectorTool::_setInitialPoint(Geom::Point const p) { - g_assert( this->npoints == 0 ); + g_assert(this->npoints == 0); this->p[0] = p; this->p[1] = p; @@ -819,7 +793,7 @@ void ConnectorTool::_setInitialPoint(Geom::Point const p) void ConnectorTool::_setSubsequentPoint(Geom::Point const p) { - g_assert( this->npoints != 0 ); + g_assert(this->npoints != 0); Geom::Point o = desktop->dt2doc(this->p[0]); Geom::Point d = desktop->dt2doc(p); @@ -846,7 +820,6 @@ void ConnectorTool::_setSubsequentPoint(Geom::Point const p) sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), red_curve.get(), true); } - /** * Concats red, blue and green. * If any anchors are defined, process these, optionally removing curves from white list @@ -867,7 +840,6 @@ void ConnectorTool::_concatColorsAndFlush() this->_flushWhite(c.get()); } - /* * Flushes white curve(s) and additional curve into object * @@ -884,15 +856,15 @@ void ConnectorTool::_flushWhite(SPCurve *c) SPDocument *doc = desktop->getDocument(); Inkscape::XML::Document *xml_doc = doc->getReprDoc(); - if ( c && !c->is_empty() ) { + 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 != nullptr ); + gchar *str = sp_svg_write_path(c->get_pathvector()); + g_assert(str != nullptr); repr->setAttribute("d", str); g_free(str); @@ -901,23 +873,22 @@ void ConnectorTool::_flushWhite(SPCurve *c) this->newconn->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); bool connection = false; - this->newconn->setAttribute( "inkscape:connector-type", - this->isOrthogonal ? "orthogonal" : "polyline", nullptr ); - this->newconn->setAttribute( "inkscape:connector-curvature", - Glib::Ascii::dtostr(this->curvature).c_str(), nullptr ); + this->newconn->setAttribute("inkscape:connector-type", this->isOrthogonal ? "orthogonal" : "polyline", nullptr); + this->newconn->setAttribute("inkscape:connector-curvature", Glib::Ascii::dtostr(this->curvature).c_str(), + nullptr); if (this->shref) { connection = true; - this->newconn->setAttribute( "inkscape:connection-start", this->shref); - if(this->sub_shref) { - this->newconn->setAttribute( "inkscape:connection-start-point", this->sub_shref); + this->newconn->setAttribute("inkscape:connection-start", this->shref); + if (this->sub_shref) { + this->newconn->setAttribute("inkscape:connection-start-point", this->sub_shref); } } if (this->ehref) { connection = true; - this->newconn->setAttribute( "inkscape:connection-end", this->ehref); - if(this->sub_ehref) { - this->newconn->setAttribute( "inkscape:connection-end-point", this->sub_ehref); + this->newconn->setAttribute("inkscape:connection-end", this->ehref); + if (this->sub_ehref) { + this->newconn->setAttribute("inkscape:connection-end-point", this->sub_ehref); } } // Process pending updates. @@ -943,7 +914,6 @@ void ConnectorTool::_flushWhite(SPCurve *c) DocumentUndo::done(doc, SP_VERB_CONTEXT_CONNECTOR, _("Create connector")); } - void ConnectorTool::_finishSegment(Geom::Point const /*p*/) { if (!this->red_curve->is_empty()) { @@ -972,113 +942,108 @@ void ConnectorTool::_finish() } } - static gboolean cc_generic_knot_handler(SPCanvasItem *, GdkEvent *event, SPKnot *knot) { - g_assert (knot != nullptr); + g_assert(knot != nullptr); - //g_object_ref(knot); + // g_object_ref(knot); knot_ref(knot); - ConnectorTool *cc = SP_CONNECTOR_CONTEXT( - knot->desktop->event_context); + 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: - knot->setFlag(SP_KNOT_MOUSEOVER, TRUE); + case GDK_ENTER_NOTIFY: + knot->setFlag(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: - knot->setFlag(SP_KNOT_MOUSEOVER, FALSE); + cc->active_handle = knot; + if (knot_tip) { + knot->desktop->event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, knot_tip); + } - /* 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 = nullptr; - } + consumed = TRUE; + break; + case GDK_LEAVE_NOTIFY: + knot->setFlag(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 = nullptr; + } - if (knot_tip) { - knot->desktop->event_context->defaultMessageContext()->clear(); - } + if (knot_tip) { + knot->desktop->event_context->defaultMessageContext()->clear(); + } - consumed = TRUE; - break; - default: - break; + consumed = TRUE; + break; + default: + break; } - //g_object_unref(knot); + // g_object_unref(knot); knot_unref(knot); return consumed; } - -static gboolean endpt_handler(SPKnot */*knot*/, GdkEvent *event, ConnectorTool *cc) +static gboolean endpt_handler(SPKnot * /*knot*/, GdkEvent *event, ConnectorTool *cc) { - //g_assert( SP_IS_CONNECTOR_CONTEXT(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; - } + 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. - auto path = static_cast<SPPath const *>(cc->clickeditem); - cc->red_curve = SPCurve::copy(path->curveForEdit()); - 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.get(), true); + // Show the red path for dragging. + auto path = static_cast<SPPath const *>(cc->clickeditem); + cc->red_curve = SPCurve::copy(path->curveForEdit()); + 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.get(), true); - cc->clickeditem->setHidden(true); + cc->clickeditem->setHidden(true); - // The rest of the interaction rerouting the connector is - // handled by the context root handler. - consumed = TRUE; - } - break; - default: - break; + // 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, SPItem* subitem) +void ConnectorTool::_activeShapeAddKnot(SPItem *item, SPItem *subitem) { SPKnot *knot = new SPKnot(desktop, nullptr); knot->owner = item; - if(subitem) { + if (subitem) { SPUse *use = dynamic_cast<SPUse *>(item); g_assert(use != nullptr); knot->sub_owner = subitem; @@ -1102,13 +1067,11 @@ void ConnectorTool::_activeShapeAddKnot(SPItem* item, SPItem* subitem) knot->updateCtrl(); // We don't want to use the standard knot handler. - g_signal_handler_disconnect(G_OBJECT(knot->item), - knot->_event_handler_id); + 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); + g_signal_connect(G_OBJECT(knot->item), "event", G_CALLBACK(cc_generic_knot_handler), knot); knot->show(); this->knots[knot] = 1; @@ -1116,7 +1079,7 @@ void ConnectorTool::_activeShapeAddKnot(SPItem* item, SPItem* subitem) void ConnectorTool::_setActiveShape(SPItem *item) { - g_assert(item != nullptr ); + g_assert(item != nullptr); if (this->active_shape != item) { // The active shape has changed @@ -1146,19 +1109,19 @@ void ConnectorTool::_setActiveShape(SPItem *item) // 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 (auto& child: item->children) { - if(child.getAttribute("inkscape:connector")) { - this->_activeShapeAddKnot((SPItem *) &child, nullptr); + for (auto &child : item->children) { + if (child.getAttribute("inkscape:connector")) { + this->_activeShapeAddKnot((SPItem *)&child, nullptr); } } // Special connector points in a symbol SPUse *use = dynamic_cast<SPUse *>(item); - if(use) { + if (use) { SPItem *orig = use->root(); - //SPItem *orig = use->get_original(); - for (auto& child: orig->children) { - if(child.getAttribute("inkscape:connector")) { - this->_activeShapeAddKnot(item, (SPItem *) &child); + // SPItem *orig = use->get_original(); + for (auto &child : orig->children) { + if (child.getAttribute("inkscape:connector")) { + this->_activeShapeAddKnot(item, (SPItem *)&child); } } } @@ -1174,7 +1137,7 @@ void ConnectorTool::_setActiveShape(SPItem *item) void ConnectorTool::cc_set_active_conn(SPItem *item) { - g_assert( SP_IS_PATH(item) ); + g_assert(SP_IS_PATH(item)); const SPCurve *curve = SP_PATH(item)->curveForEdit(); Geom::Affine i2dt = item->i2dt_affine(); @@ -1215,9 +1178,9 @@ void ConnectorTool::cc_set_active_conn(SPItem *item) for (int i = 0; i < 2; ++i) { // Create the handle if it doesn't exist - if ( this->endpt_handle[i] == nullptr ) { - SPKnot *knot = new SPKnot(desktop, - _("<b>Connector endpoint</b>: drag to reroute or connect to new shapes")); + if (this->endpt_handle[i] == nullptr) { + SPKnot *knot = + new SPKnot(desktop, _("<b>Connector endpoint</b>: drag to reroute or connect to new shapes")); knot->setShape(SP_KNOT_SHAPE_SQUARE); knot->setSize(7); @@ -1228,22 +1191,19 @@ void ConnectorTool::cc_set_active_conn(SPItem *item) // 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); + 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); + 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 ); + 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; } @@ -1251,9 +1211,8 @@ void ConnectorTool::cc_set_active_conn(SPItem *item) // 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); + 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()) { @@ -1272,22 +1231,21 @@ void ConnectorTool::cc_set_active_conn(SPItem *item) this->endpt_handle[1]->show(); } -void cc_create_connection_point(ConnectorTool* cc) +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 ); + cc_deselect_handle(cc->selected_handle); } SPKnot *knot = new SPKnot(cc->getDesktop(), nullptr); // We do not process events on this knot. - g_signal_handler_disconnect(G_OBJECT(knot->item), - knot->_event_handler_id); + g_signal_handler_disconnect(G_OBJECT(knot->item), knot->_event_handler_id); knot->_event_handler_id = 0; - cc_select_handle( knot ); + cc_select_handle(knot); cc->selected_handle = knot; cc->selected_handle->show(); cc->state = SP_CONNECTOR_CONTEXT_NEWCONNPOINT; @@ -1298,7 +1256,7 @@ static bool cc_item_is_shape(SPItem *item) { if (auto path = dynamic_cast<SPPath const *>(item)) { SPCurve const *curve = path->curve(); - if ( curve && !(curve->is_closed()) ) { + if (curve && !(curve->is_closed())) { // Open paths are connectors. return false; } @@ -1312,7 +1270,6 @@ static bool cc_item_is_shape(SPItem *item) return true; } - bool cc_item_is_connector(SPItem *item) { if (SP_IS_PATH(item)) { @@ -1326,7 +1283,6 @@ bool cc_item_is_connector(SPItem *item) return false; } - void cc_selection_set_avoid(SPDesktop *desktop, bool const set_avoid) { if (desktop == nullptr) { @@ -1337,10 +1293,9 @@ void cc_selection_set_avoid(SPDesktop *desktop, bool const set_avoid) Inkscape::Selection *selection = desktop->getSelection(); - int changes = 0; - for (SPItem *item: selection->items()) { + for (SPItem *item : selection->items()) { char const *value = (set_avoid) ? "true" : nullptr; if (cc_item_is_shape(item)) { @@ -1352,13 +1307,12 @@ void cc_selection_set_avoid(SPDesktop *desktop, bool const set_avoid) if (changes == 0) { desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, - _("Select <b>at least one non-connector object</b>.")); + _("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"); + char *event_desc = + (set_avoid) ? _("Make connectors avoid selected objects") : _("Make connectors ignore selected objects"); DocumentUndo::done(document, SP_VERB_CONTEXT_CONNECTOR, event_desc); } @@ -1381,8 +1335,8 @@ void ConnectorTool::_selectionChanged(Inkscape::Selection *selection) } } -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_deleted(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node *child, + Inkscape::XML::Node * /*ref*/, gpointer data) { g_assert(data); ConnectorTool *cc = SP_CONNECTOR_CONTEXT(data); @@ -1393,17 +1347,15 @@ static void shape_event_attr_deleted(Inkscape::XML::Node */*repr*/, Inkscape::XM } } - -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 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 (!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(); @@ -1415,10 +1367,9 @@ static void shape_event_attr_changed(Inkscape::XML::Node *repr, gchar const *nam } } -} -} -} - +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/connector-tool.h b/src/ui/tools/connector-tool.h index 876a9bbdea4dee6d175a76427eb33a2bbd845756..6d56d16e3248c3e3e151604b1fbc13c170f62895 100644 --- a/src/ui/tools/connector-tool.h +++ b/src/ui/tools/connector-tool.h @@ -13,12 +13,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <2geom/point.h> #include <map> #include <memory> -#include <string> - -#include <2geom/point.h> #include <sigc++/connection.h> +#include <string> #include "ui/tools/tool-base.h" @@ -28,21 +27,23 @@ class SPKnot; struct SPCanvasItem; namespace Avoid { - class ConnRef; +class ConnRef; } namespace Inkscape { - class Selection; +class Selection; - namespace XML { - class Node; - } +namespace XML { +class Node; } +} // namespace Inkscape -#define SP_CONNECTOR_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::ConnectorTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#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) -enum { +enum +{ SP_CONNECTOR_CONTEXT_IDLE, SP_CONNECTOR_CONTEXT_DRAGGING, SP_CONNECTOR_CONTEXT_CLOSE, @@ -51,13 +52,14 @@ enum { SP_CONNECTOR_CONTEXT_NEWCONNPOINT }; -typedef std::map<SPKnot *, int> SPKnotList; +typedef std::map<SPKnot *, int> SPKnotList; namespace Inkscape { namespace UI { namespace Tools { -class ConnectorTool : public ToolBase { +class ConnectorTool : public ToolBase +{ public: ConnectorTool(); ~ConnectorTool() override; @@ -104,7 +106,7 @@ public: SPKnotList knots; SPKnot *endpt_handle[2]; - guint endpt_handler_id[2]; + guint endpt_handler_id[2]; gchar *shref; gchar *sub_shref; gchar *ehref; @@ -115,11 +117,11 @@ public: void setup() override; void finish() override; - void set(const Inkscape::Preferences::Entry& val) override; - bool root_handler(GdkEvent* event) override; - bool item_handler(SPItem* item, GdkEvent* event) override; + void set(const Inkscape::Preferences::Entry &val) override; + bool root_handler(GdkEvent *event) override; + bool item_handler(SPItem *item, GdkEvent *event) override; - std::string const& getPrefsPath() override; + std::string const &getPrefsPath() override; void cc_clear_active_shape(); void cc_set_active_conn(SPItem *item); @@ -141,21 +143,21 @@ private: void _concatColorsAndFlush(); void _flushWhite(SPCurve *gc); - void _activeShapeAddKnot(SPItem* item, SPItem* subitem); + void _activeShapeAddKnot(SPItem *item, SPItem *subitem); void _setActiveShape(SPItem *item); - bool _ptHandleTest(Geom::Point& p, gchar **href, gchar **subhref); + bool _ptHandleTest(Geom::Point &p, gchar **href, gchar **subhref); void _reroutingFinish(Geom::Point *const p); }; void cc_selection_set_avoid(SPDesktop *, bool const set_ignore); -void cc_create_connection_point(ConnectorTool* cc); -void cc_remove_connection_point(ConnectorTool* cc); +void cc_create_connection_point(ConnectorTool *cc); +void cc_remove_connection_point(ConnectorTool *cc); bool cc_item_is_connector(SPItem *item); -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_CONNECTOR_CONTEXT_H */ diff --git a/src/ui/tools/dropper-tool.cpp b/src/ui/tools/dropper-tool.cpp index cc564ab1771029cea7bc9364af48ae3c3b483049..c78b0d392b493b26f67d15861f1ac3faa0c1fba2 100644 --- a/src/ui/tools/dropper-tool.cpp +++ b/src/ui/tools/dropper-tool.cpp @@ -12,41 +12,35 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/i18n.h> -#include <gdk/gdk.h> -#include <gdk/gdkkeysyms.h> +#include "ui/tools/dropper-tool.h" -#include <2geom/transforms.h> #include <2geom/circle.h> +#include <2geom/transforms.h> +#include <gdk/gdk.h> +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> #include "color-rgba.h" #include "desktop-style.h" #include "desktop.h" +#include "display/cairo-utils.h" +#include "display/canvas-arena.h" +#include "display/canvas-bpath.h" +#include "display/curve.h" #include "document-undo.h" +#include "include/macros.h" #include "message-context.h" +#include "object/sp-namedview.h" #include "preferences.h" #include "selection.h" #include "sp-cursor.h" -#include "verbs.h" - -#include "display/canvas-bpath.h" -#include "display/canvas-arena.h" -#include "display/curve.h" -#include "display/cairo-utils.h" - -#include "include/macros.h" - -#include "object/sp-namedview.h" - +#include "svg/svg-color.h" #include "ui/pixmaps/cursor-dropper-f.xpm" #include "ui/pixmaps/cursor-dropper-s.xpm" #include "ui/pixmaps/cursor-dropping-f.xpm" #include "ui/pixmaps/cursor-dropping-s.xpm" - -#include "svg/svg-color.h" - -#include "ui/tools/dropper-tool.h" #include "ui/widget/canvas.h" +#include "verbs.h" using Inkscape::DocumentUndo; @@ -54,47 +48,49 @@ namespace Inkscape { namespace UI { namespace Tools { -const std::string& DropperTool::getPrefsPath() { - return DropperTool::prefsPath; +const std::string &DropperTool::getPrefsPath() +{ + return DropperTool::prefsPath; } const std::string DropperTool::prefsPath = "/tools/dropper"; DropperTool::DropperTool() : ToolBase(cursor_dropper_f_xpm) - , R(0) - , G(0) - , B(0) - , alpha(0) - , radius(0) - , invert(false) - , stroke(false) - , dropping(false) - , dragging(false) - , grabbed(nullptr) - , area(nullptr) - , centre(0, 0) -{ -} + , R(0) + , G(0) + , B(0) + , alpha(0) + , radius(0) + , invert(false) + , stroke(false) + , dropping(false) + , dragging(false) + , grabbed(nullptr) + , area(nullptr) + , centre(0, 0) +{} DropperTool::~DropperTool() = default; -void DropperTool::setup() { +void DropperTool::setup() +{ ToolBase::setup(); /* TODO: have a look at CalligraphicTool::setup where the same is done.. generalize? */ - Geom::PathVector path = Geom::Path(Geom::Circle(0,0,1)); + Geom::PathVector path = Geom::Path(Geom::Circle(0, 0, 1)); auto c = std::make_unique<SPCurve>(path); area = sp_canvas_bpath_new(desktop->getControls(), c.get()); - 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_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(); } @@ -104,9 +100,10 @@ void DropperTool::setup() { } } -void DropperTool::finish() { +void DropperTool::finish() +{ this->enableGrDrag(false); - + if (this->grabbed) { sp_canvas_item_ungrab(this->grabbed); this->grabbed = nullptr; @@ -123,20 +120,19 @@ void DropperTool::finish() { /** * Returns the current dropper context color. */ -guint32 DropperTool::get_color(bool invert) { - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); +guint32 DropperTool::get_color(bool invert) +{ + 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( - fabs(invert - this->R), - fabs(invert - this->G), - fabs(invert - this->B), - (pick == SP_DROPPER_PICK_ACTUAL && setalpha) ? this->alpha : 1.0); + return SP_RGBA32_F_COMPOSE(fabs(invert - this->R), fabs(invert - this->G), fabs(invert - this->B), + (pick == SP_DROPPER_PICK_ACTUAL && setalpha) ? this->alpha : 1.0); } -bool DropperTool::root_handler(GdkEvent* event) { +bool DropperTool::root_handler(GdkEvent *event) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int ret = FALSE; @@ -161,22 +157,22 @@ bool DropperTool::root_handler(GdkEvent* event) { } // Get color from selected object instead. - if(this->dropping) { - Inkscape::Selection *selection = desktop->getSelection(); - g_assert(selection); + if (this->dropping) { + Inkscape::Selection *selection = desktop->getSelection(); + g_assert(selection); guint32 apply_color; bool apply_set = false; - for (auto& obj: selection->objects()) { - if(obj->style) { + for (auto &obj : selection->objects()) { + if (obj->style) { double opacity = 1.0; - if(!this->stroke && obj->style->fill.set) { - if(obj->style->fill_opacity.set) { + if (!this->stroke && obj->style->fill.set) { + if (obj->style->fill_opacity.set) { opacity = obj->style->fill_opacity.value; } apply_color = obj->style->fill.value.color.toRGBA32(opacity); apply_set = true; - } else if(this->stroke && obj->style->stroke.set) { - if(obj->style->stroke_opacity.set) { + } else if (this->stroke && obj->style->stroke.set) { + if (obj->style->stroke_opacity.set) { opacity = obj->style->stroke_opacity.value; } apply_color = obj->style->stroke.value.color.toRGBA32(opacity); @@ -184,7 +180,7 @@ bool DropperTool::root_handler(GdkEvent* event) { } } } - if(apply_set) { + if (apply_set) { this->R = SP_RGBA32_R_F(apply_color); this->G = SP_RGBA32_G_F(apply_color); this->B = SP_RGBA32_B_F(apply_color); @@ -197,7 +193,7 @@ bool DropperTool::root_handler(GdkEvent* event) { } switch (event->type) { - case GDK_BUTTON_PRESS: + 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; @@ -205,13 +201,13 @@ bool DropperTool::root_handler(GdkEvent* event) { } 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, - nullptr, event->button.time); + 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, + nullptr, event->button.time); this->grabbed = SP_CANVAS_ITEM(desktop->acetate); break; - case GDK_MOTION_NOTIFY: + 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; @@ -234,7 +230,7 @@ bool DropperTool::root_handler(GdkEvent* event) { 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) ); + 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); @@ -243,7 +239,8 @@ bool DropperTool::root_handler(GdkEvent* event) { 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()); + cairo_surface_t *s = + cairo_image_surface_create(CAIRO_FORMAT_ARGB32, area.width(), area.height()); sp_canvas_arena_render_surface(SP_CANVAS_ARENA(desktop->getDrawing()), s, area); ink_cairo_surface_average_color_premul(s, R, G, B, A); cairo_surface_destroy(s); @@ -278,7 +275,7 @@ bool DropperTool::root_handler(GdkEvent* event) { } // remember color - if(!this->dropping && (R != this->R || G != this->G || B != this->B || A != this->alpha)) { + if (!this->dropping && (R != this->R || G != this->G || B != this->B || A != this->alpha)) { this->R = R; this->G = G; this->B = B; @@ -288,23 +285,24 @@ bool DropperTool::root_handler(GdkEvent* event) { } break; - case GDK_BUTTON_RELEASE: + case GDK_BUTTON_RELEASE: if (event->button.button == 1 && !this->space_panning) { - sp_canvas_item_hide(this->area); - this->dragging = false; + sp_canvas_item_hide(this->area); + this->dragging = false; - if (this->grabbed) { - sp_canvas_item_ungrab(this->grabbed); - this->grabbed = nullptr; - } + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed); + this->grabbed = nullptr; + } Inkscape::Selection *selection = desktop->getSelection(); g_assert(selection); std::vector<SPItem *> old_selection(selection->items().begin(), selection->items().end()); - if(this->dropping) { - Geom::Point const button_w(event->button.x, event->button.y); - // 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); + if (this->dropping) { + Geom::Point const button_w(event->button.x, event->button.y); + // 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); // Change selected object to object under cursor if (this->item_to_select) { @@ -313,7 +311,8 @@ bool DropperTool::root_handler(GdkEvent* event) { } } else { if (prefs->getBool("/tools/dropper/onetimepick", false)) { - // "One time" pick from Fill/Stroke dialog stroke page, always apply fill or stroke (ignore <Shift> key) + // "One time" pick from Fill/Stroke dialog stroke page, always apply fill or stroke (ignore + // <Shift> key) stroke = (prefs->getInt("/dialogs/fillstroke/page", 0) == 0) ? false : true; } } @@ -323,10 +322,9 @@ bool DropperTool::root_handler(GdkEvent* event) { // REJON: set aux. toolbar input to hex color! if (!(desktop->getSelection()->isEmpty())) { - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_DROPPER, - _("Set picked color")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_DROPPER, _("Set picked color")); } - if(this->dropping) { + if (this->dropping) { selection->setList(old_selection); } @@ -343,22 +341,22 @@ bool DropperTool::root_handler(GdkEvent* event) { } break; - case GDK_KEY_PRESS: - switch (get_latin_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; + case GDK_KEY_PRESS: + switch (get_latin_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: + desktop->getSelection()->clear(); + break; } break; - case GDK_KEY_Escape: - desktop->getSelection()->clear(); - break; - } - break; } // set the status message to the right text. @@ -369,36 +367,38 @@ bool DropperTool::root_handler(GdkEvent* event) { // locale-sensitive printf is OK, since this goes to the UI, not into SVG gchar *alpha = g_strdup_printf(_(" alpha %.3g"), this->alpha); // where the color is picked, to show in the statusbar - gchar *where = this->dragging ? g_strdup_printf(_(", averaged with radius %d"), (int) this->radius) : g_strdup_printf("%s", _(" under cursor")); + gchar *where = this->dragging ? g_strdup_printf(_(", averaged with radius %d"), (int)this->radius) + : 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"); + 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); + 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); // Set the right cursor for the mode and apply the special Fill color - auto xpm = (this->dropping ? (this->stroke ? cursor_dropping_s_xpm : cursor_dropping_f_xpm) : - (this->stroke ? cursor_dropper_s_xpm : cursor_dropper_f_xpm)); + auto xpm = (this->dropping ? (this->stroke ? cursor_dropping_s_xpm : cursor_dropping_f_xpm) + : (this->stroke ? cursor_dropper_s_xpm : cursor_dropper_f_xpm)); GdkCursor *cursor = sp_cursor_from_xpm(xpm, this->get_color(this->invert)); auto window = desktop->getCanvas()->get_window(); gdk_window_set_cursor(window->gobj(), cursor); if (!ret) { - ret = ToolBase::root_handler(event); + ret = ToolBase::root_handler(event); } return ret; } -} -} -} - +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/dropper-tool.h b/src/ui/tools/dropper-tool.h index d52049ca2b1a1f02f0f7b31ab214d233da55d1fa..7d004d7bd6f270f70d4458b53631b6b5a22ac6c4 100644 --- a/src/ui/tools/dropper-tool.h +++ b/src/ui/tools/dropper-tool.h @@ -19,44 +19,48 @@ struct SPCanvasItem; -#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 +#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 }; -enum { - DONT_REDRAW_CURSOR, - DRAW_FILL_CURSOR, - DRAW_STROKE_CURSOR +enum +{ + DONT_REDRAW_CURSOR, + DRAW_FILL_CURSOR, + DRAW_STROKE_CURSOR }; namespace Inkscape { namespace UI { namespace Tools { -class DropperTool : public ToolBase { +class DropperTool : public ToolBase +{ public: - DropperTool(); - ~DropperTool() override; + DropperTool(); + ~DropperTool() override; - static const std::string prefsPath; + static const std::string prefsPath; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; - guint32 get_color(bool invert=false); + guint32 get_color(bool invert = false); protected: - void setup() override; - void finish() override; - bool root_handler(GdkEvent* event) override; + void setup() override; + void finish() override; + bool root_handler(GdkEvent *event) override; private: - double R; - double G; - double B; - double alpha; + double R; + double G; + double B; + double alpha; double radius; bool invert; @@ -64,14 +68,14 @@ private: bool dropping; bool dragging; - SPCanvasItem* grabbed; - SPCanvasItem* area; + SPCanvasItem *grabbed; + SPCanvasItem *area; Geom::Point centre; }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/tools/dynamic-base.cpp b/src/ui/tools/dynamic-base.cpp index 260c480efe84074b251493f94a17500e010eaf57..f3c941fc2a35dcd7d5906e8126485fa55e6829ae 100644 --- a/src/ui/tools/dynamic-base.cpp +++ b/src/ui/tools/dynamic-base.cpp @@ -10,14 +10,14 @@ #include "ui/tools/dynamic-base.h" -#include "message-context.h" -#include "display/sp-canvas-item.h" #include "desktop.h" #include "display/curve.h" +#include "display/sp-canvas-item.h" +#include "message-context.h" -#define MIN_PRESSURE 0.0 -#define MAX_PRESSURE 1.0 -#define DEFAULT_PRESSURE 1.0 +#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 @@ -61,11 +61,11 @@ DynamicBase::DynamicBase(gchar const *const *cursor_shape) , cap_rounding(0) , is_drawing(false) , abs_width(false) -{ -} +{} -DynamicBase::~DynamicBase() { - for (auto i:segments) { +DynamicBase::~DynamicBase() +{ + for (auto i : segments) { sp_canvas_item_destroy(SP_CANVAS_ITEM(i)); } segments.clear(); @@ -76,15 +76,16 @@ DynamicBase::~DynamicBase() { } } -void DynamicBase::set(const Inkscape::Preferences::Entry& value) { +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; + return; } if (path == "mass") { @@ -113,7 +114,8 @@ void DynamicBase::set(const Inkscape::Preferences::Entry& value) { } /* Get normalized point */ -Geom::Point DynamicBase::getNormalizedPoint(Geom::Point v) const { +Geom::Point DynamicBase::getNormalizedPoint(Geom::Point v) const +{ auto drect = this->desktop->get_display_area(); double const max = drect.maxExtent(); @@ -122,7 +124,8 @@ Geom::Point DynamicBase::getNormalizedPoint(Geom::Point v) const { } /* Get view point */ -Geom::Point DynamicBase::getViewPoint(Geom::Point n) const { +Geom::Point DynamicBase::getViewPoint(Geom::Point n) const +{ auto drect = this->desktop->get_display_area(); double const max = drect.maxExtent(); @@ -130,9 +133,9 @@ Geom::Point DynamicBase::getViewPoint(Geom::Point n) const { return n * max + drect.bounds().min(); } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/dynamic-base.h b/src/ui/tools/dynamic-base.h index bff939124c9cdc67093cb840e36d2419b040da38..e9468d446a0340f30bb0744963881e8018c78572 100644 --- a/src/ui/tools/dynamic-base.h +++ b/src/ui/tools/dynamic-base.h @@ -20,39 +20,40 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/tools/tool-base.h" -#include "display/sp-canvas-item.h" - #include <memory> +#include "display/sp-canvas-item.h" +#include "ui/tools/tool-base.h" + struct SPCanvasItem; class SPCurve; namespace Inkscape { - namespace XML { - class Node; - } +namespace XML { +class Node; } +} // namespace Inkscape -#define SAMPLING_SIZE 8 /* fixme: ?? */ +#define SAMPLING_SIZE 8 /* fixme: ?? */ namespace Inkscape { namespace UI { namespace Tools { -class DynamicBase : public ToolBase { +class DynamicBase : public ToolBase +{ public: - DynamicBase(gchar const *const *cursor_shape); - ~DynamicBase() override; + DynamicBase(gchar const *const *cursor_shape); + ~DynamicBase() override; - void set(const Inkscape::Preferences::Entry& val) override; + void set(const Inkscape::Preferences::Entry &val) override; protected: /** accumulated shape which ultimately goes in svg:path */ std::unique_ptr<SPCurve> accumulated; /** canvas items for "committed" segments */ - std::vector<SPCanvasItem*> segments; + std::vector<SPCanvasItem *> segments; /** canvas item for red "leading" segment */ SPCanvasItem *currentshape; @@ -92,7 +93,7 @@ protected: gdouble ytilt; /* attributes */ - bool dragging; /* mouse state: mouse is dragging */ + bool dragging; /* mouse state: mouse is dragging */ bool usepressure; bool usetilt; double mass, drag; @@ -109,13 +110,13 @@ protected: /** uses absolute width independent of zoom */ bool abs_width; - Geom::Point getViewPoint(Geom::Point n) const; - Geom::Point getNormalizedPoint(Geom::Point v) const; + Geom::Point getViewPoint(Geom::Point n) const; + Geom::Point getNormalizedPoint(Geom::Point v) const; }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif // COMMON_CONTEXT_H_SEEN @@ -129,4 +130,3 @@ protected: 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 index 61d7ffe856ed55daaab86ba057932c2180d3cbc9..19930371ce6798e9f409ccce3372e2c0e1eb73d4 100644 --- a/src/ui/tools/eraser-tool.cpp +++ b/src/ui/tools/eraser-tool.cpp @@ -25,38 +25,30 @@ #define noERASER_VERBOSE -#include <string> -#include <cstring> -#include <numeric> - -#include <gtk/gtk.h> -#include <gdk/gdkkeysyms.h> -#include <glibmm/i18n.h> +#include "ui/tools/eraser-tool.h" #include <2geom/bezier-utils.h> #include <2geom/pathvector.h> +#include <cstring> +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> +#include <gtk/gtk.h> +#include <numeric> +#include <string> #include "context-fns.h" #include "desktop-events.h" #include "desktop-style.h" #include "desktop.h" +#include "display/canvas-arena.h" +#include "display/canvas-bpath.h" +#include "display/curve.h" #include "document-undo.h" #include "document.h" +#include "include/macros.h" #include "layer-manager.h" #include "layer-model.h" #include "message-context.h" -#include "path-chemistry.h" -#include "rubberband.h" -#include "selection-chemistry.h" -#include "selection.h" -#include "verbs.h" - -#include "display/canvas-arena.h" -#include "display/canvas-bpath.h" -#include "display/curve.h" - -#include "include/macros.h" - #include "object/sp-clippath.h" #include "object/sp-item-group.h" #include "object/sp-path.h" @@ -65,13 +57,14 @@ #include "object/sp-shape.h" #include "object/sp-text.h" #include "object/sp-use.h" +#include "path-chemistry.h" +#include "rubberband.h" +#include "selection-chemistry.h" +#include "selection.h" #include "style.h" - -#include "ui/pixmaps/cursor-eraser.xpm" - #include "svg/svg.h" - -#include "ui/tools/eraser-tool.h" +#include "ui/pixmaps/cursor-eraser.xpm" +#include "verbs.h" using Inkscape::DocumentUndo; @@ -91,8 +84,9 @@ namespace Inkscape { namespace UI { namespace Tools { -const std::string& EraserTool::getPrefsPath() { - return EraserTool::prefsPath; +const std::string &EraserTool::getPrefsPath() +{ + return EraserTool::prefsPath; } const std::string EraserTool::prefsPath = "/tools/eraser"; @@ -100,12 +94,12 @@ const std::string EraserTool::prefsPath = "/tools/eraser"; EraserTool::EraserTool() : DynamicBase(cursor_eraser_xpm) , nowidth(false) -{ -} +{} EraserTool::~EraserTool() = default; -void EraserTool::setup() { +void EraserTool::setup() +{ DynamicBase::setup(); accumulated.reset(new SPCurve()); @@ -117,22 +111,23 @@ void EraserTool::setup() { this->currentshape = sp_canvas_item_new(desktop->getSketch(), SP_TYPE_CANVAS_BPATH, nullptr); 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); + 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} -}; -*/ + /* + 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"); @@ -148,51 +143,52 @@ static ProfileFloatElement f_profile[PROFILE_FLOAT_SIZE] = { sp_event_context_read(this, "cap_rounding"); this->is_drawing = false; - //TODO not sure why get 0.01 if slider width == 0, maybe a double/int problem + // TODO not sure why get 0.01 if slider width == 0, maybe a double/int problem Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs->getBool("/tools/eraser/selcue", false) != 0) { - this->enableSelectionCue(); + this->enableSelectionCue(); } // TODO temp force: this->enableSelectionCue(); } -static double -flerp(double f0, double f1, double p) +static double flerp(double f0, double f1, double p) { - return f0 + ( f1 - f0 ) * p; + return f0 + (f1 - f0) * p; } -void EraserTool::reset(Geom::Point p) { +void EraserTool::reset(Geom::Point p) +{ this->last = this->cur = getNormalizedPoint(p); - this->vel = Geom::Point(0,0); + 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); + 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); +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); + 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); + 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) { +bool EraserTool::apply(Geom::Point p) +{ Geom::Point n = getNormalizedPoint(p); /* Calculate mass and drag */ @@ -205,11 +201,12 @@ bool EraserTool::apply(Geom::Point p) { // 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. + // 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)) { + if (Geom::L2(force) < ERASER_EPSILON || + (this->vel_max < ERASER_VEL_START && Geom::L2(force) < ERASER_EPSILON_START)) { return FALSE; } @@ -226,25 +223,24 @@ bool EraserTool::apply(Geom::Point p) { 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);; + 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); + Geom::Point ang1 = Geom::Point(this->ytilt / length, this->xtilt / length); a1 = atan2(ang1); - } - else + } else a1 = 0.0; - } - else { + } 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)); + 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 ) { + if (mag_vel < ERASER_EPSILON) { return FALSE; } Geom::Point ang2 = Geom::rot90(this->vel) / mag_vel; @@ -254,30 +250,31 @@ bool EraserTool::apply(Geom::Point p) { 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) { + if (fabs(a2 - a1) > 0.5 * M_PI) { a2 += M_PI; flipped = true; } // normalize a2 if (a2 > M_PI) - a2 -= 2*M_PI; + a2 -= 2 * M_PI; if (a2 < -M_PI) - a2 += 2*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); + 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 ) { + 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)); + 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); + // 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; @@ -289,11 +286,12 @@ bool EraserTool::apply(Geom::Point p) { return TRUE; } -void EraserTool::brush() { - g_assert( this->npoints >= 0 && this->npoints < SAMPLING_SIZE ); +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); + double vel_thin = flerp(0, 160, this->vel_thin); // Influence of pressure on thickness double pressure_thick = (this->usepressure ? this->pressure : 1.0); @@ -301,7 +299,7 @@ void EraserTool::brush() { // 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); + // Geom::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); double trace_thick = 1; @@ -312,11 +310,11 @@ void EraserTool::brush() { // 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; + 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 ); + } while (w >= 1.0); + w = sqrt((-2.0 * log(w)) / w); y1 = x1 * w; y2 = x2 * w; @@ -325,11 +323,11 @@ void EraserTool::brush() { // (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)); + 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 ) { + if (width < 0.02 * this->width) { width = 0.02 * this->width; } @@ -343,39 +341,39 @@ void EraserTool::brush() { this->point1[this->npoints] = brush + del_left; this->point2[this->npoints] = brush - del_right; - + if (this->nowidth) { - this->point1[this->npoints] = Geom::middle_point(this->point1[this->npoints],this->point2[this->npoints]); + this->point1[this->npoints] = Geom::middle_point(this->point1[this->npoints], this->point2[this->npoints]); } - this->del = 0.5*(del_left + 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) +static void sp_erc_update_toolbox(SPDesktop *desktop, const gchar *id, double value) { - desktop->setToolboxAdjustmentValue (id, value); + desktop->setToolboxAdjustmentValue(id, value); } -void EraserTool::cancel() { - +void EraserTool::cancel() +{ this->dragging = FALSE; this->is_drawing = false; sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); - /* Remove all temporary line segments */ + /* Remove all temporary line segments */ for (auto i : this->segments) sp_canvas_item_destroy(SP_CANVAS_ITEM(i)); this->segments.clear(); - /* reset accumulated curve */ - this->accumulated->reset(); - this->clear_current(); - if (this->repr) { - this->repr = nullptr; - } + /* reset accumulated curve */ + this->accumulated->reset(); + this->clear_current(); + if (this->repr) { + this->repr = nullptr; + } } -bool EraserTool::root_handler(GdkEvent* event) { +bool EraserTool::root_handler(GdkEvent *event) +{ gint ret = FALSE; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gint eraser_mode = prefs->getInt("/tools/eraser/mode", 2); @@ -398,20 +396,17 @@ bool EraserTool::root_handler(GdkEvent* event) { if (this->repr) { this->repr = nullptr; } - if ( eraser_mode == ERASER_MODE_DELETE ) { + if (eraser_mode == ERASER_MODE_DELETE) { 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 ), - nullptr, - event->button.time); + 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), + nullptr, event->button.time); ret = TRUE; @@ -422,13 +417,12 @@ bool EraserTool::root_handler(GdkEvent* event) { 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_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) { + 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")); @@ -438,191 +432,192 @@ bool EraserTool::root_handler(GdkEvent* event) { break; } - if ( this->cur != this->last ) { + if (this->cur != this->last) { this->brush(); - g_assert( this->npoints > 0 ); + g_assert(this->npoints > 0); this->fit_and_split(false); } ret = TRUE; } - if ( eraser_mode == ERASER_MODE_DELETE ) { + if (eraser_mode == ERASER_MODE_DELETE) { this->accumulated->reset(); Inkscape::Rubberband::get(desktop)->move(motion_dt); } - } - 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)); + 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)); - forced_redraws_stop(); - this->is_drawing = false; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); + forced_redraws_stop(); + this->is_drawing = false; - if (this->dragging && event->button.button == 1 && !this->space_panning) { - this->dragging = FALSE; + if (this->dragging && event->button.button == 1 && !this->space_panning) { + this->dragging = FALSE; - this->apply(motion_dt); + this->apply(motion_dt); - /* Remove all temporary line segments */ - for (auto i : this->segments) - sp_canvas_item_destroy(SP_CANVAS_ITEM(i)); - this->segments.clear(); + /* Remove all temporary line segments */ + for (auto i : this->segments) + sp_canvas_item_destroy(SP_CANVAS_ITEM(i)); + this->segments.clear(); - /* Create object */ - this->fit_and_split(true); - this->accumulate(); - this->set_to_accumulated(); // performs document_done + /* 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 = nullptr; + } - /* reset accumulated curve */ - this->accumulated->reset(); + this->message_context->clear(); + ret = TRUE; + } - this->clear_current(); - if (this->repr) { - this->repr = nullptr; + if (eraser_mode == ERASER_MODE_DELETE && Inkscape::Rubberband::get(desktop)->is_started()) { + Inkscape::Rubberband::get(desktop)->stop(); } - this->message_context->clear(); - ret = TRUE; + break; } - if (eraser_mode == ERASER_MODE_DELETE && Inkscape::Rubberband::get(desktop)->is_started()) { - Inkscape::Rubberband::get(desktop)->stop(); - } - - break; - } + case GDK_KEY_PRESS: + switch (get_latin_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; + } - case GDK_KEY_PRESS: - switch (get_latin_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, "eraser-width", + this->width * 100); // the same spinbutton is for alt+x + ret = TRUE; + } + break; - sp_erc_update_toolbox (desktop, "eraser-width", 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; - 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; + } - if (this->width < 0.01) { + sp_erc_update_toolbox(desktop, "eraser-width", this->width * 100); + ret = TRUE; + } + break; + + case GDK_KEY_Home: + case GDK_KEY_KP_Home: this->width = 0.01; - } + sp_erc_update_toolbox(desktop, "eraser-width", this->width * 100); + ret = TRUE; + break; - sp_erc_update_toolbox (desktop, "eraser-width", this->width * 100); - ret = TRUE; - } - break; + case GDK_KEY_End: + case GDK_KEY_KP_End: + this->width = 1.0; + sp_erc_update_toolbox(desktop, "eraser-width", this->width * 100); + ret = TRUE; + break; - case GDK_KEY_Home: - case GDK_KEY_KP_Home: - this->width = 0.01; - sp_erc_update_toolbox (desktop, "eraser-width", this->width * 100); - ret = TRUE; - break; + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo("eraser-width"); + ret = TRUE; + } + break; - case GDK_KEY_End: - case GDK_KEY_KP_End: - this->width = 1.0; - sp_erc_update_toolbox (desktop, "eraser-width", this->width * 100); - ret = TRUE; - break; + case GDK_KEY_Escape: + if (eraser_mode == ERASER_MODE_DELETE) { + 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_x: - case GDK_KEY_X: - if (MOD__ALT_ONLY(event)) { - desktop->setToolboxFocusTo ("eraser-width"); - 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; - case GDK_KEY_Escape: - if ( eraser_mode == ERASER_MODE_DELETE ) { - Inkscape::Rubberband::get(desktop)->stop(); - } - if (this->is_drawing) { - // if drawing, cancel, otherwise pass it up for deselecting - this->cancel(); - ret = TRUE; + default: + break; } 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; + case GDK_KEY_RELEASE: + switch (get_latin_keyval(&event->key)) { + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + this->message_context->clear(); + break; + + default: + break; } break; default: break; - } - break; - - case GDK_KEY_RELEASE: - switch (get_latin_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); + ret = DynamicBase::root_handler(event); } return ret; } -void EraserTool::clear_current() { +void EraserTool::clear_current() +{ // reset bpath sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->currentshape), nullptr); @@ -635,7 +630,8 @@ void EraserTool::clear_current() { this->npoints = 0; } -void EraserTool::set_to_accumulated() { +void EraserTool::set_to_accumulated() +{ bool workDone = false; SPDocument *document = this->desktop->doc(); if (!this->accumulated->is_empty()) { @@ -645,35 +641,36 @@ void EraserTool::set_to_accumulated() { Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); /* Set style */ - sp_desktop_apply_style_tool (this->desktop, repr, "/tools/eraser", false); + sp_desktop_apply_style_tool(this->desktop, repr, "/tools/eraser", false); this->repr = repr; } - SPObject * top_layer = desktop->currentRoot(); + SPObject *top_layer = desktop->currentRoot(); SPItem *item_repr = SP_ITEM(top_layer->appendChildRepr(this->repr)); Inkscape::GC::release(this->repr); item_repr->updateRepr(); Geom::PathVector pathv = this->accumulated->get_pathvector() * this->desktop->dt2doc(); pathv *= item_repr->i2doc_affine().inverse(); gchar *str = sp_svg_write_path(pathv); - g_assert( str != nullptr ); + g_assert(str != nullptr); this->repr->setAttribute("d", str); g_free(str); Geom::OptRect eraserBbox; - if ( this->repr ) { + if (this->repr) { bool wasSelection = false; Inkscape::Selection *selection = this->desktop->getSelection(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gint eraser_mode = prefs->getInt("/tools/eraser/mode", ERASER_MODE_CLIP); Inkscape::XML::Document *xml_doc = this->desktop->doc()->getReprDoc(); - SPItem* acid = SP_ITEM(this->desktop->doc()->getObjectByRepr(this->repr)); + SPItem *acid = SP_ITEM(this->desktop->doc()->getObjectByRepr(this->repr)); eraserBbox = acid->documentVisualBounds(); - std::vector<SPItem*> remainingItems; - std::vector<SPItem*> toWorkOn; + std::vector<SPItem *> remainingItems; + std::vector<SPItem *> toWorkOn; if (selection->isEmpty()) { - if (eraser_mode == ERASER_MODE_CUT || eraser_mode == ERASER_MODE_CLIP) { - toWorkOn = document->getItemsPartiallyInBox(this->desktop->dkey, *eraserBbox, false, false, false, true); + if (eraser_mode == ERASER_MODE_CUT || eraser_mode == ERASER_MODE_CLIP) { + toWorkOn = + document->getItemsPartiallyInBox(this->desktop->dkey, *eraserBbox, false, false, false, true); } else { Inkscape::Rubberband *r = Inkscape::Rubberband::get(this->desktop); toWorkOn = document->getItemsAtPoints(this->desktop->dkey, r->getPoints()); @@ -682,10 +679,10 @@ void EraserTool::set_to_accumulated() { } else { if (eraser_mode == ERASER_MODE_DELETE) { Inkscape::Rubberband *r = Inkscape::Rubberband::get(this->desktop); - std::vector<SPItem*> touched; + std::vector<SPItem *> touched; touched = document->getItemsAtPoints(this->desktop->dkey, r->getPoints()); for (auto i : touched) { - if(selection->includes(i)){ + if (selection->includes(i)) { toWorkOn.push_back(i); } } @@ -695,21 +692,21 @@ void EraserTool::set_to_accumulated() { wasSelection = true; } - if ( !toWorkOn.empty() ) { - if (eraser_mode == ERASER_MODE_CUT) { - for (auto i : toWorkOn){ + if (!toWorkOn.empty()) { + if (eraser_mode == ERASER_MODE_CUT) { + for (auto i : toWorkOn) { SPItem *item = i; SPUse *use = dynamic_cast<SPUse *>(item); - if (SP_IS_PATH(item) && SP_PATH(item)->nodesInPath () == 2){ + if (SP_IS_PATH(item) && SP_PATH(item)->nodesInPath() == 2) { SPItem *item = i; item->deleteObject(true); workDone = true; - } else if (SP_IS_GROUP(item) || use ) { + } else if (SP_IS_GROUP(item) || use) { /*Do nothing*/ } else { Geom::OptRect bbox = item->documentVisualBounds(); if (bbox && bbox->intersects(*eraserBbox)) { - Inkscape::XML::Node* dup = this->repr->duplicate(xml_doc); + Inkscape::XML::Node *dup = this->repr->duplicate(xml_doc); this->repr->parent()->appendChild(dup); Inkscape::GC::release(dup); // parent takes over selection->set(dup); @@ -717,7 +714,7 @@ void EraserTool::set_to_accumulated() { selection->pathUnion(true); } selection->add(item); - if(item->style->fill_rule.value == SP_WIND_RULE_EVENODD){ + if (item->style->fill_rule.value == SP_WIND_RULE_EVENODD) { SPCSSAttr *css = sp_repr_css_attr_new(); sp_repr_css_set_property(css, "fill-rule", "evenodd"); sp_desktop_set_style(this->desktop, css); @@ -731,16 +728,16 @@ void EraserTool::set_to_accumulated() { } workDone = true; // TODO set this only if something was cut. bool break_apart = prefs->getBool("/tools/eraser/break_apart", false); - if(!break_apart){ + if (!break_apart) { selection->combine(true); } else { - if(!this->nowidth){ + if (!this->nowidth) { selection->breakApart(true); } } - if ( !selection->isEmpty() ) { + if (!selection->isEmpty()) { // If the item was not completely erased, track the new remainder. - std::vector<SPItem*> nowSel(selection->items().begin(), selection->items().end()); + std::vector<SPItem *> nowSel(selection->items().begin(), selection->items().end()); for (auto i2 : nowSel) { remainingItems.push_back(i2); } @@ -753,11 +750,11 @@ void EraserTool::set_to_accumulated() { } else if (eraser_mode == ERASER_MODE_CLIP) { if (!this->nowidth) { remainingItems.clear(); - for (auto item : toWorkOn){ + for (auto item : toWorkOn) { selection->clear(); Geom::OptRect bbox = item->documentVisualBounds(); Inkscape::XML::Document *xml_doc = this->desktop->doc()->getReprDoc(); - Inkscape::XML::Node* dup = this->repr->duplicate(xml_doc); + Inkscape::XML::Node *dup = this->repr->duplicate(xml_doc); this->repr->parent()->appendChild(dup); Inkscape::GC::release(dup); // parent takes over selection->set(dup); @@ -765,19 +762,20 @@ void EraserTool::set_to_accumulated() { if (bbox && bbox->intersects(*eraserBbox)) { SPClipPath *clip_path = item->getClipObject(); if (clip_path) { - std::vector<SPItem*> selected; + std::vector<SPItem *> selected; selected.push_back(SP_ITEM(clip_path->firstChild())); - std::vector<Inkscape::XML::Node*> to_select; - std::vector<SPItem*> items(selected); + std::vector<Inkscape::XML::Node *> to_select; + std::vector<SPItem *> items(selected); sp_item_list_to_curves(items, selected, to_select); - Inkscape::XML::Node * clip_data = SP_ITEM(clip_path->firstChild())->getRepr(); + Inkscape::XML::Node *clip_data = SP_ITEM(clip_path->firstChild())->getRepr(); if (!clip_data && !to_select.empty()) { clip_data = *(to_select.begin()); } if (clip_data) { Inkscape::XML::Node *dup_clip = clip_data->duplicate(xml_doc); if (dup_clip) { - SPItem * dup_clip_obj = SP_ITEM(item_repr->parent->appendChildRepr(dup_clip)); + SPItem *dup_clip_obj = + SP_ITEM(item_repr->parent->appendChildRepr(dup_clip)); Inkscape::GC::release(dup_clip); if (dup_clip_obj) { dup_clip_obj->transform *= @@ -787,16 +785,16 @@ void EraserTool::set_to_accumulated() { selection->raiseToTop(true); selection->add(dup_clip); selection->pathDiff(true); - //SPItem * clip = SP_ITEM(*(selection->items().begin())); + // SPItem * clip = SP_ITEM(*(selection->items().begin())); } } } } else { Inkscape::XML::Node *rect_repr = xml_doc->createElement("svg:rect"); - sp_desktop_apply_style_tool (this->desktop, rect_repr, "/tools/eraser", false); - SPRect * rect = SP_RECT(item_repr->parent->appendChildRepr(rect_repr)); + sp_desktop_apply_style_tool(this->desktop, rect_repr, "/tools/eraser", false); + SPRect *rect = SP_RECT(item_repr->parent->appendChildRepr(rect_repr)); Inkscape::GC::release(rect_repr); - rect->setPosition (bbox->left(), bbox->top(), bbox->width(), bbox->height()); + rect->setPosition(bbox->left(), bbox->top(), bbox->width(), bbox->height()); rect->transform = SP_ITEM(rect->parent)->i2doc_affine().inverse(); rect->updateRepr(); @@ -835,14 +833,14 @@ void EraserTool::set_to_accumulated() { selection->clear(); - if ( wasSelection ) { - if ( !remainingItems.empty() ) { + if (wasSelection) { + if (!remainingItems.empty()) { selection->add(remainingItems.begin(), remainingItems.end()); } } } // Remove the eraser stroke itself: - sp_repr_unparent( this->repr ); + sp_repr_unparent(this->repr); this->repr = nullptr; } } else { @@ -851,26 +849,23 @@ void EraserTool::set_to_accumulated() { this->repr = nullptr; } } - if ( workDone ) { + if (workDone) { DocumentUndo::done(document, SP_VERB_CONTEXT_ERASER, _("Draw eraser stroke")); } else { DocumentUndo::cancel(document); } } -static void -add_cap(SPCurve &curve, - Geom::Point const &pre, Geom::Point const &from, - Geom::Point const &to, Geom::Point const &post, - double rounding) +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); + 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 ) { + if (mag_in > ERASER_EPSILON) { v_in = mag * v_in / mag_in; } else { v_in = Geom::Point(0, 0); @@ -879,56 +874,52 @@ add_cap(SPCurve &curve, Geom::Point v_out = to - post; double mag_out = Geom::L2(v_out); - if ( mag_out > ERASER_EPSILON ) { + 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 ) { + 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() { +void EraserTool::accumulate() +{ // construct a crude outline of the eraser's path. // this desperately needs to be rewritten to use the path outliner... - if ( !this->cal1->is_empty() && !this->cal2->is_empty() ) { + if (!this->cal1->is_empty() && !this->cal2->is_empty()) { this->accumulated->reset(); /* Is this required ?? */ auto 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() ); + g_assert(!this->cal1->first_path()->closed()); + g_assert(!rev_cal2->first_path()->closed()); - Geom::BezierCurve const * dc_cal1_firstseg = dynamic_cast<Geom::BezierCurve const *>( this->cal1->first_segment() ); - Geom::BezierCurve const * rev_cal2_firstseg = dynamic_cast<Geom::BezierCurve const *>( rev_cal2->first_segment() ); - Geom::BezierCurve const * dc_cal1_lastseg = dynamic_cast<Geom::BezierCurve const *>( this->cal1->last_segment() ); - Geom::BezierCurve const * rev_cal2_lastseg = dynamic_cast<Geom::BezierCurve const *>( rev_cal2->last_segment() ); + Geom::BezierCurve const *dc_cal1_firstseg = + dynamic_cast<Geom::BezierCurve const *>(this->cal1->first_segment()); + Geom::BezierCurve const *rev_cal2_firstseg = dynamic_cast<Geom::BezierCurve const *>(rev_cal2->first_segment()); + Geom::BezierCurve const *dc_cal1_lastseg = dynamic_cast<Geom::BezierCurve const *>(this->cal1->last_segment()); + Geom::BezierCurve const *rev_cal2_lastseg = dynamic_cast<Geom::BezierCurve 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 ); + g_assert(dc_cal1_firstseg); + g_assert(rev_cal2_firstseg); + g_assert(dc_cal1_lastseg); + g_assert(rev_cal2_lastseg); accumulated->append(*cal1); - if(!this->nowidth) { - add_cap(*accumulated, - dc_cal1_lastseg->finalPoint() - dc_cal1_lastseg->unitTangentAt(1), - dc_cal1_lastseg->finalPoint(), - rev_cal2_firstseg->initialPoint(), - rev_cal2_firstseg->initialPoint() + rev_cal2_firstseg->unitTangentAt(0), - this->cap_rounding); + if (!this->nowidth) { + add_cap(*accumulated, dc_cal1_lastseg->finalPoint() - dc_cal1_lastseg->unitTangentAt(1), + dc_cal1_lastseg->finalPoint(), rev_cal2_firstseg->initialPoint(), + rev_cal2_firstseg->initialPoint() + rev_cal2_firstseg->unitTangentAt(0), this->cap_rounding); this->accumulated->append(*rev_cal2, true); - add_cap(*accumulated, - rev_cal2_lastseg->finalPoint() - rev_cal2_lastseg->unitTangentAt(1), - rev_cal2_lastseg->finalPoint(), - dc_cal1_firstseg->initialPoint(), - dc_cal1_firstseg->initialPoint() + dc_cal1_firstseg->unitTangentAt(0), - this->cap_rounding); + add_cap(*accumulated, rev_cal2_lastseg->finalPoint() - rev_cal2_lastseg->unitTangentAt(1), + rev_cal2_lastseg->finalPoint(), dc_cal1_firstseg->initialPoint(), + dc_cal1_firstseg->initialPoint() + dc_cal1_firstseg->unitTangentAt(0), this->cap_rounding); this->accumulated->closepath(); } @@ -943,30 +934,30 @@ 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 ); +void EraserTool::fit_and_split(bool release) +{ + double const tolerance_sq = square(desktop->w2d().descrim() * TOLERANCE_ERASER); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - this->nowidth = prefs->getDouble( "/tools/eraser/width", 1) == 0; + this->nowidth = prefs->getDouble("/tools/eraser/width", 1) == 0; #ifdef ERASER_VERBOSE - g_print("[F&S:R=%c]", release?'T':'F'); + g_print("[F&S:R=%c]", release ? 'T' : 'F'); #endif - if (!( this->npoints > 0 && this->npoints < SAMPLING_SIZE )) + 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 ) + 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"); + 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() ) { + if (this->cal1->is_empty() || this->cal2->is_empty()) { /* dc->npoints > 0 */ /* g_print("erasers(1|2) reset\n"); */ this->cal1->reset(); @@ -978,20 +969,20 @@ void EraserTool::fit_and_split(bool release) { 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)) ); + 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)) ); + g_assert(nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2))); - if ( nb1 != -1 && nb2 != -1 ) { + 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) { + if (!release) { this->currentcurve->reset(); this->currentcurve->moveto(b1[0]); @@ -999,9 +990,9 @@ void EraserTool::fit_and_split(bool release) { this->currentcurve->curveto(bp1[1], bp1[2], bp1[3]); } - this->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]); + this->currentcurve->lineto(b2[BEZIER_SIZE * (nb2 - 1) + 3]); - for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) { + for (Geom::Point *bp2 = b2 + BEZIER_SIZE * (nb2 - 1); bp2 >= b2; bp2 -= BEZIER_SIZE) { this->currentcurve->curveto(bp2[2], bp2[1], bp2[0]); } @@ -1043,22 +1034,27 @@ void EraserTool::fit_and_split(bool release) { g_print("[%d]Yup\n", this->npoints); #endif if (!release) { - gint eraser_mode = prefs->getInt("/tools/eraser/mode",2); + gint eraser_mode = prefs->getInt("/tools/eraser/mode", 2); g_assert(!this->currentcurve->is_empty()); SPCanvasItem *cbp = sp_canvas_item_new(desktop->getSketch(), SP_TYPE_CANVAS_BPATH, nullptr); auto curve = this->currentcurve->copy(); sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cbp), curve.get(), true); - 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); + 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); @@ -1078,12 +1074,13 @@ void EraserTool::fit_and_split(bool release) { } } -void EraserTool::draw_temporary_box() { +void EraserTool::draw_temporary_box() +{ this->currentcurve->reset(); - this->currentcurve->moveto(this->point1[this->npoints-1]); + this->currentcurve->moveto(this->point1[this->npoints - 1]); - for (gint i = this->npoints-2; i >= 0; i--) { + for (gint i = this->npoints - 2; i >= 0; i--) { this->currentcurve->lineto(this->point1[i]); } @@ -1101,9 +1098,9 @@ void EraserTool::draw_temporary_box() { sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(currentshape), currentcurve.get(), true); } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/eraser-tool.h b/src/ui/tools/eraser-tool.h index 6da1fa37007babf3e1e3326e721788e63b5fd5f1..9b705bc6e6ee74aeb9e28b8147aaec228a08a3eb 100644 --- a/src/ui/tools/eraser-tool.h +++ b/src/ui/tools/eraser-tool.h @@ -24,51 +24,52 @@ #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_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 +#define ERC_MIN_TILT -1.0 +#define ERC_MAX_TILT 1.0 +#define ERC_DEFAULT_TILT 0.0 -#define ERASER_MODE_DELETE 0 -#define ERASER_MODE_CUT 1 -#define ERASER_MODE_CLIP 2 +#define ERASER_MODE_DELETE 0 +#define ERASER_MODE_CUT 1 +#define ERASER_MODE_CLIP 2 namespace Inkscape { namespace UI { namespace Tools { -class EraserTool : public DynamicBase { +class EraserTool : public DynamicBase +{ public: - EraserTool(); - ~EraserTool() override; + EraserTool(); + ~EraserTool() override; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - bool root_handler(GdkEvent* event) override; + void setup() override; + bool root_handler(GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; 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(); - bool nowidth; + 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(); + bool nowidth; }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif // SP_ERASER_CONTEXT_H_SEEN diff --git a/src/ui/tools/flood-tool.cpp b/src/ui/tools/flood-tool.cpp index 358e31567b159cf3d1e72eff1366859b04ecd5fe..bc4a0aa0bb2853cb46c2a1ef58f31c8735069f2d 100644 --- a/src/ui/tools/flood-tool.cpp +++ b/src/ui/tools/flood-tool.cpp @@ -20,63 +20,54 @@ #include "flood-tool.h" +#include <2geom/pathvector.h> #include <cmath> -#include <queue> - #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> - -#include <2geom/pathvector.h> +#include <queue> #include "color.h" #include "context-fns.h" #include "desktop-style.h" #include "desktop.h" -#include "document-undo.h" -#include "document.h" -#include "message-context.h" -#include "message-stack.h" -#include "rubberband.h" -#include "selection.h" -#include "verbs.h" - #include "display/cairo-utils.h" #include "display/drawing-context.h" #include "display/drawing-image.h" #include "display/drawing.h" - +#include "document-undo.h" +#include "document.h" #include "include/macros.h" - #include "livarot/Path.h" #include "livarot/Shape.h" - +#include "message-context.h" +#include "message-stack.h" #include "object/sp-namedview.h" #include "object/sp-path.h" #include "object/sp-root.h" - +#include "rubberband.h" +#include "selection.h" #include "svg/svg.h" - #include "trace/imagemap.h" #include "trace/potrace/inkscape-potrace.h" - #include "ui/pixmaps/cursor-paintbucket.xpm" #include "ui/shape-editor.h" -#include "ui/widget/canvas.h" // Canvas area - +#include "ui/widget/canvas.h" // Canvas area +#include "verbs.h" #include "xml/node-event-vector.h" using Inkscape::DocumentUndo; +using Inkscape::Display::AssembleARGB32; using Inkscape::Display::ExtractARGB32; using Inkscape::Display::ExtractRGB32; -using Inkscape::Display::AssembleARGB32; namespace Inkscape { namespace UI { namespace Tools { -const std::string& FloodTool::getPrefsPath() { - return FloodTool::prefsPath; +const std::string &FloodTool::getPrefsPath() +{ + return FloodTool::prefsPath; } const std::string FloodTool::prefsPath = "/tools/paintbucket"; @@ -84,24 +75,13 @@ const std::string FloodTool::prefsPath = "/tools/paintbucket"; // TODO: Replace by C++11 initialization // Must match PaintBucketChannels enum Glib::ustring ch_init[8] = { - _("Visible Colors"), - _("Red"), - _("Green"), - _("Blue"), - _("Hue"), - _("Saturation"), - _("Lightness"), - _("Alpha"), + _("Visible Colors"), _("Red"), _("Green"), _("Blue"), _("Hue"), _("Saturation"), _("Lightness"), _("Alpha"), }; -const std::vector<Glib::ustring> FloodTool::channel_list( ch_init, ch_init+8 ); +const std::vector<Glib::ustring> FloodTool::channel_list(ch_init, ch_init + 8); -Glib::ustring gap_init[4] = { - NC_("Flood autogap", "None"), - NC_("Flood autogap", "Small"), - NC_("Flood autogap", "Medium"), - NC_("Flood autogap", "Large") -}; -const std::vector<Glib::ustring> FloodTool::gap_list( gap_init, gap_init+4 ); +Glib::ustring gap_init[4] = {NC_("Flood autogap", "None"), NC_("Flood autogap", "Small"), + NC_("Flood autogap", "Medium"), NC_("Flood autogap", "Large")}; +const std::vector<Glib::ustring> FloodTool::gap_list(gap_init, gap_init + 4); FloodTool::FloodTool() : ToolBase(cursor_paintbucket_xpm) @@ -111,7 +91,8 @@ FloodTool::FloodTool() this->tolerance = 4; } -FloodTool::~FloodTool() { +FloodTool::~FloodTool() +{ this->sel_changed_connection.disconnect(); delete this->shape_editor; @@ -127,12 +108,14 @@ FloodTool::~FloodTool() { * Callback that processes the "changed" signal on the selection; * destroys old and creates new knotholder. */ -void FloodTool::selection_changed(Inkscape::Selection* selection) { +void FloodTool::selection_changed(Inkscape::Selection *selection) +{ this->shape_editor->unset_item(); this->shape_editor->set_item(selection->singleItem()); } -void FloodTool::setup() { +void FloodTool::setup() +{ ToolBase::setup(); this->shape_editor = new ShapeEditor(this->desktop); @@ -143,9 +126,8 @@ void FloodTool::setup() { } this->sel_changed_connection.disconnect(); - this->sel_changed_connection = this->desktop->getSelection()->connectChanged( - sigc::mem_fun(this, &FloodTool::selection_changed) - ); + this->sel_changed_connection = + this->desktop->getSelection()->connectChanged(sigc::mem_fun(this, &FloodTool::selection_changed)); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -154,7 +136,6 @@ void FloodTool::setup() { } } - // Changes from 0.48 -> 0.49 (Cairo) // 0.49: Ignores alpha in background // 0.48: RGBA, 0.49 ARGB @@ -169,9 +150,12 @@ inline static guint32 compose_onto(guint32 px, guint32 bg) // 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 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; @@ -184,11 +168,13 @@ inline static guint32 compose_onto(guint32 px, guint32 bg) * @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 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) { +inline unsigned char *get_trace_pixel(guchar *trace_px, int x, int y, int width) +{ return trace_px + (x + y * width); } @@ -208,7 +194,8 @@ static bool compare_guint32(guint32 const a, guint32 const b, guint32 const d) } /** - * Compare a pixel in a pixel buffer with another pixel to determine if a point should be included in the fill operation. + * 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. @@ -216,9 +203,10 @@ static bool compare_guint32(guint32 const a, guint32 const b, guint32 const d) * @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) +static bool compare_pixels(guint32 check, guint32 orig, guint32 merged_orig_pixel, guint32 dtc, int threshold, + PaintBucketChannels method) { - float hsl_check[3] = {0,0,0}, hsl_orig[3] = {0,0,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); @@ -232,46 +220,43 @@ static bool compare_pixels(guint32 check, guint32 orig, guint32 merged_orig_pixe 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)) { + if ((method == FLOOD_CHANNELS_H) || (method == FLOOD_CHANNELS_S) || (method == FLOOD_CHANNELS_L)) { double dac = ac; double dao = ao; SPColor::rgb_to_hsl_floatv(hsl_check, rc / dac, gc / dac, bc / dac); SPColor::rgb_to_hsl_floatv(hsl_orig, ro / dao, go / dao, bo / dao); } - + switch (method) { case FLOOD_CHANNELS_ALPHA: return compare_guint32(ac, ao, threshold); case FLOOD_CHANNELS_R: - return compare_guint32(ac ? unpremul_alpha(rc, ac) : 0, - ao ? unpremul_alpha(ro, ao) : 0, - threshold); + return compare_guint32(ac ? unpremul_alpha(rc, ac) : 0, ao ? unpremul_alpha(ro, ao) : 0, threshold); case FLOOD_CHANNELS_G: - return compare_guint32(ac ? unpremul_alpha(gc, ac) : 0, - ao ? unpremul_alpha(go, ao) : 0, - threshold); + return compare_guint32(ac ? unpremul_alpha(gc, ac) : 0, ao ? unpremul_alpha(go, ao) : 0, threshold); case FLOOD_CHANNELS_B: - return compare_guint32(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; - - int diff = 0; // The total difference between each of the 3 color components - diff += std::abs(static_cast<int>(amc ? unpremul_alpha(rmc, amc) : 0) - static_cast<int>(amop ? unpremul_alpha(rmop, amop) : 0)); - diff += std::abs(static_cast<int>(amc ? unpremul_alpha(gmc, amc) : 0) - static_cast<int>(amop ? unpremul_alpha(gmop, amop) : 0)); - diff += std::abs(static_cast<int>(amc ? unpremul_alpha(bmc, amc) : 0) - static_cast<int>(amop ? unpremul_alpha(bmop, amop) : 0)); - return ((diff / 3) <= ((threshold * 3) / 4)); - } + return compare_guint32(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; + + int diff = 0; // The total difference between each of the 3 color components + diff += std::abs(static_cast<int>(amc ? unpremul_alpha(rmc, amc) : 0) - + static_cast<int>(amop ? unpremul_alpha(rmop, amop) : 0)); + diff += std::abs(static_cast<int>(amc ? unpremul_alpha(gmc, amc) : 0) - + static_cast<int>(amop ? unpremul_alpha(gmop, amop) : 0)); + diff += std::abs(static_cast<int>(amc ? unpremul_alpha(bmc, amc) : 0) - + static_cast<int>(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: @@ -279,36 +264,75 @@ static bool compare_pixels(guint32 check, guint32 orig, guint32 merged_orig_pixe 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 +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_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 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 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; } +static inline void clear_pixel_paintability(unsigned char *t) +{ + *t ^= PIXEL_PAINTABLE; + *t ^= PIXEL_NOT_PAINTABLE; +} -struct bitmap_coords_info { +struct bitmap_coords_info +{ bool is_left; unsigned int x; unsigned int y; @@ -336,7 +360,9 @@ struct bitmap_coords_info { * @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) { +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 { @@ -358,7 +384,10 @@ inline static bool check_if_pixel_is_paintable(guchar *px, unsigned char *trace_ * @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) { +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 = desktop->getDocument(); unsigned char *trace_t; @@ -382,7 +411,7 @@ static void do_trace(bitmap_coords_info bci, guchar *trace_px, SPDesktop *deskto 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...." + // XML Tree being used here directly while it shouldn't be...." Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); long totalNodeCount = 0L; @@ -395,42 +424,42 @@ static void do_trace(bitmap_coords_info bci, guchar *trace_px, SPDesktop *deskto Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path"); /* Set style */ - sp_desktop_apply_style_tool (desktop, pathRepr, "/tools/paintbucket", false); + 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.")); + desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("<b>Too much inset</b>, the result is empty.")); Inkscape::GC::release(pathRepr); g_free(str); return; @@ -445,22 +474,22 @@ static void do_trace(bitmap_coords_info bci, guchar *trace_px, SPDesktop *deskto g_free(str); } - desktop->currentLayer()->addChild(pathRepr,nullptr); + desktop->currentLayer()->addChild(pathRepr, nullptr); SPObject *reprobj = document->getObjectByRepr(pathRepr); if (reprobj) { SP_ITEM(reprobj)->doWriteTransform(transform); - + // premultiply the item transform by the accumulated parent transform in the paste layer - Geom::Affine local (SP_GROUP(desktop->currentLayer())->i2doc_affine()); + 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()); + 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); + gchar *affinestr = sp_svg_transform_write(item_t); pathRepr->setAttribute("transform", affinestr); g_free(affinestr); } @@ -470,29 +499,33 @@ static void do_trace(bitmap_coords_info bci, guchar *trace_px, SPDesktop *deskto 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() ); + 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); selection->pathUnion(true); } 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() ); + 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 { +enum ScanlineCheckResult +{ SCANLINE_CHECK_OK, SCANLINE_CHECK_ABORTED, SCANLINE_CHECK_BOUNDARY @@ -504,9 +537,9 @@ enum ScanlineCheckResult { * @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); +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 @@ -523,42 +556,60 @@ inline static bool coords_in_range(unsigned int x, unsigned int y, bitmap_coords * @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) { +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); + 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); + 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; } + 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; } - + 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; } } @@ -571,7 +622,9 @@ inline static unsigned int paint_pixel(guchar *px, guchar *trace_px, guint32 ori * @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) { +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)); @@ -588,7 +641,9 @@ static void push_point_onto_queue(std::deque<Geom::Point> *fill_queue, unsigned * @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) { +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)); @@ -605,7 +660,10 @@ static void shift_point_onto_queue(std::deque<Geom::Point> *fill_queue, unsigned * @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) { +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; @@ -643,8 +701,7 @@ static ScanlineCheckResult perform_bitmap_scanline_check(std::deque<Geom::Point> paint_directions = paint_pixel(px, trace_px, orig_color, bci, current_trace_t); if (bci.radius == 0) { mark_pixel_checked(current_trace_t); - if ((!fill_queue->empty()) && - (front_of_queue[Geom::X] == bci.x) && + if ((!fill_queue->empty()) && (front_of_queue[Geom::X] == bci.x) && (front_of_queue[Geom::Y] == bci.y)) { fill_queue->pop_front(); front_of_queue = fill_queue->empty() ? Geom::Point() : fill_queue->front(); @@ -652,12 +709,14 @@ static ScanlineCheckResult perform_bitmap_scanline_check(std::deque<Geom::Point> } if (can_paint_top) { - if (paint_directions & PAINT_DIRECTION_UP) { + 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 (initial_paint) { + currently_painting_top = !ok_to_paint; + } if (ok_to_paint && (!currently_painting_top)) { currently_painting_top = true; @@ -671,12 +730,15 @@ static ScanlineCheckResult perform_bitmap_scanline_check(std::deque<Geom::Point> } if (can_paint_bottom) { - if (paint_directions & PAINT_DIRECTION_DOWN) { + 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); + 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 (initial_paint) { + currently_painting_bottom = !ok_to_paint; + } if (ok_to_paint && (!currently_painting_bottom)) { currently_painting_bottom = true; @@ -691,12 +753,14 @@ static ScanlineCheckResult perform_bitmap_scanline_check(std::deque<Geom::Point> if (bci.is_left) { if (paint_directions & PAINT_DIRECTION_LEFT) { - bci.x--; current_trace_t--; + bci.x--; + current_trace_t--; ok = true; } } else { if (paint_directions & PAINT_DIRECTION_RIGHT) { - bci.x++; current_trace_t++; + bci.x++; + current_trace_t++; ok = true; } } @@ -705,29 +769,36 @@ static ScanlineCheckResult perform_bitmap_scanline_check(std::deque<Geom::Point> } } else { if (bci.bbox.min()[Geom::X] > bci.screen.min()[Geom::X]) { - aborted = true; break; + aborted = true; + break; } else { reached_screen_boundary = true; } } } while (ok); - if (aborted) { return SCANLINE_CHECK_ABORTED; } - if (reached_screen_boundary) { return SCANLINE_CHECK_BOUNDARY; } + 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) { +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) { +static bool sort_fill_queue_horizontal(Geom::Point a, Geom::Point b) +{ return a[Geom::X] > b[Geom::X]; } @@ -737,21 +808,24 @@ static bool sort_fill_queue_horizontal(Geom::Point a, Geom::Point b) { * @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. + * @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) { +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->getDesktop(); SPDocument *document = desktop->getDocument(); 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; } - + // 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; @@ -775,16 +849,15 @@ static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, boo /* 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); + Inkscape::DrawingItem *root = document->getRoot()->invoke_show(drawing, dkey, SP_ITEM_SHOW_DISPLAY); root->setTransform(doc2img); 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_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 = desktop->getNamedView(); @@ -799,11 +872,11 @@ static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, boo drawing.render(dc, final_bbox); - //cairo_surface_write_to_png( s, "cairo.png" ); + // cairo_surface_write_to_png( s, "cairo.png" ); cairo_surface_flush(s); cairo_surface_destroy(s); - + // Hide items document->getRoot()->invoke_hide(dkey); } @@ -818,20 +891,20 @@ static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, boo 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); + PaintBucketChannels method = (PaintBucketChannels)prefs->getInt("/tools/paintbucket/channels", 0); int threshold = prefs->getIntLimited("/tools/paintbucket/threshold", 1, 0, 100); - switch(method) { + switch (method) { case FLOOD_CHANNELS_ALPHA: case FLOOD_CHANNELS_RGB: case FLOOD_CHANNELS_R: @@ -846,7 +919,7 @@ static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, boo } bitmap_coords_info bci; - + bci.y_limit = y_limit; bci.width = width; bci.height = height; @@ -949,7 +1022,7 @@ static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, boo std::deque<Geom::Point>::iterator end_sort = fill_queue.begin(); unsigned int sort_y = (unsigned int)cp[Geom::Y]; unsigned int current_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]; @@ -965,7 +1038,7 @@ static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, boo if (start_sort != end_sort) { std::sort(start_sort, end_sort, sort_fill_queue_horizontal); } - + cp = fill_queue.front(); } } @@ -987,7 +1060,8 @@ static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, boo if (y == 0) { if (bbox->min()[Geom::Y] > screen.min()[Geom::Y]) { - aborted = true; break; + aborted = true; + break; } else { reached_screen_boundary = true; } @@ -995,7 +1069,8 @@ static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, boo if (y == y_limit) { if (bbox->max()[Geom::Y] < screen.max()[Geom::Y]) { - aborted = true; break; + aborted = true; + break; } else { reached_screen_boundary = true; } @@ -1005,7 +1080,8 @@ static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, boo bci.x = x; bci.y = y; - ScanlineCheckResult result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci, &min_x, &max_x); + ScanlineCheckResult result = + perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci, &min_x, &max_x); switch (result) { case SCANLINE_CHECK_ABORTED: @@ -1025,7 +1101,8 @@ static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, boo 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); + result = + perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci, &min_x, &max_x); switch (result) { case SCANLINE_CHECK_ABORTED: @@ -1048,165 +1125,180 @@ static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, boo } } } - + 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.")); + 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; } + 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::Affine inverted_affine = Geom::Translate(min_x, min_y) * doc2img.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) { +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(desktop->getDocument(), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object")); - // Dead assignment: Value stored to 'ret' is never read - //ret = TRUE; - } - break; + 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); - default: - break; + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object")); + // Dead assignment: Value stored to 'ret' is never read + // 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); -// } + // 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) { +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_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); + 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; + 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 THIS LEADS TO CRASHES. USER CAN CHANGE TOOLS AS IT CALLS GTK MAIN LOOP + desktop->setWaitingCursor(); - case GDK_BUTTON_RELEASE: - if (event->button.button == 1 && !this->space_panning) { - Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop); + dragging = false; - if (r->is_started()) { - // set "busy" cursor THIS LEADS TO CRASHES. USER CAN CHANGE TOOLS AS IT CALLS GTK MAIN LOOP - desktop->setWaitingCursor(); + bool is_point_fill = this->within_tolerance; + bool is_touch_fill = event->button.state & GDK_MOD1_MASK; - dragging = false; + sp_flood_do_flood_fill(this, event, event->button.state & GDK_SHIFT_MASK, is_point_fill, + is_touch_fill); - 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(); + desktop->clearWaitingCursor(); - ret = TRUE; + ret = TRUE; - r->stop(); + r->stop(); - this->defaultMessageContext()->clear(); + this->defaultMessageContext()->clear(); + } } - } - break; - case GDK_KEY_PRESS: - switch (get_latin_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: + case GDK_KEY_PRESS: + switch (get_latin_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; - } - break; - default: - break; + default: + break; } if (!ret) { - ret = ToolBase::root_handler(event); + ret = ToolBase::root_handler(event); } return ret; } -void FloodTool::finishItem() { +void FloodTool::finishItem() +{ this->message_context->clear(); if (this->item != nullptr) { @@ -1220,14 +1312,15 @@ void FloodTool::finishItem() { } } -void FloodTool::set_channels(gint channels) { +void FloodTool::set_channels(gint channels) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setInt("/tools/paintbucket/channels", channels); } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/flood-tool.h b/src/ui/tools/flood-tool.h index 877db980a783ab779f43f4807c97ecfe534dc38e..8dd2eb85af3189235957e4d75661820e9dce2576 100644 --- a/src/ui/tools/flood-tool.h +++ b/src/ui/tools/flood-tool.h @@ -12,14 +12,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <vector> - #include <sigc++/connection.h> +#include <vector> #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) +#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 { @@ -28,33 +28,35 @@ class Selection; namespace UI { namespace Tools { -class FloodTool : public ToolBase { +class FloodTool : public ToolBase +{ public: - FloodTool(); - ~FloodTool() override; + FloodTool(); + ~FloodTool() override; - SPItem *item; + SPItem *item; - sigc::connection sel_changed_connection; + sigc::connection sel_changed_connection; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - bool root_handler(GdkEvent* event) override; - bool item_handler(SPItem* item, GdkEvent* event) override; + void setup() override; + bool root_handler(GdkEvent *event) override; + bool item_handler(SPItem *item, GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; - static void set_channels(gint channels); - static const std::vector<Glib::ustring> channel_list; - static const std::vector<Glib::ustring> gap_list; + static void set_channels(gint channels); + static const std::vector<Glib::ustring> channel_list; + static const std::vector<Glib::ustring> gap_list; private: - void selection_changed(Inkscape::Selection* selection); - void finishItem(); + void selection_changed(Inkscape::Selection *selection); + void finishItem(); }; -enum PaintBucketChannels { +enum PaintBucketChannels +{ FLOOD_CHANNELS_RGB, FLOOD_CHANNELS_R, FLOOD_CHANNELS_G, @@ -65,8 +67,8 @@ enum PaintBucketChannels { FLOOD_CHANNELS_ALPHA }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/tools/freehand-base.cpp b/src/ui/tools/freehand-base.cpp index 5fb9afd6f88f75e0126ed3a7e1d54d94ee81ee15..cb669063b2e42877fd4232d30a8c7b3dec3e28ab 100644 --- a/src/ui/tools/freehand-base.cpp +++ b/src/ui/tools/freehand-base.cpp @@ -18,29 +18,23 @@ #define DRAW_VERBOSE #include "desktop-style.h" -#include "message-stack.h" -#include "selection-chemistry.h" - #include "display/canvas-bpath.h" #include "display/curve.h" - +#include "id-clash.h" #include "include/macros.h" - #include "live_effects/lpe-bendpath.h" #include "live_effects/lpe-patternalongpath.h" -#include "live_effects/lpe-simplify.h" #include "live_effects/lpe-powerstroke.h" - -#include "svg/svg-color.h" -#include "svg/svg.h" - -#include "id-clash.h" +#include "live_effects/lpe-simplify.h" +#include "message-stack.h" #include "object/sp-item-group.h" #include "object/sp-path.h" #include "object/sp-rect.h" #include "object/sp-use.h" +#include "selection-chemistry.h" #include "style.h" - +#include "svg/svg-color.h" +#include "svg/svg.h" #include "ui/clipboard.h" #include "ui/control-manager.h" #include "ui/draw-anchor.h" @@ -48,9 +42,9 @@ #include "ui/tools/pen-tool.h" #include "ui/tools/pencil-tool.h" -#define MIN_PRESSURE 0.0 -#define MAX_PRESSURE 1.0 -#define DEFAULT_PRESSURE 1.0 +#define MIN_PRESSURE 0.0 +#define MAX_PRESSURE 1.0 +#define DEFAULT_PRESSURE 1.0 using Inkscape::DocumentUndo; @@ -100,10 +94,10 @@ FreehandBase::FreehandBase(gchar const *const *cursor_shape) , tablet_enabled(false) , is_tablet(false) , pressure(DEFAULT_PRESSURE) -{ -} +{} -FreehandBase::~FreehandBase() { +FreehandBase::~FreehandBase() +{ if (this->grab) { sp_canvas_item_ungrab(this->grab); this->grab = nullptr; @@ -116,29 +110,30 @@ FreehandBase::~FreehandBase() { spdc_free_colors(this); } -void FreehandBase::setup() { +void FreehandBase::setup() +{ ToolBase::setup(); this->selection = desktop->getSelection(); // 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) - ); + 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(this->desktop->getSketch(), nullptr); - 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_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.reset(new SPCurve()); // Create blue bpath this->blue_bpath = sp_canvas_bpath_new(this->desktop->getSketch(), nullptr); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->blue_bpath), this->blue_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + 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.reset(new SPCurve()); @@ -157,7 +152,8 @@ void FreehandBase::setup() { spdc_attach_selection(this, this->selection); } -void FreehandBase::finish() { +void FreehandBase::finish() +{ this->sel_changed_connection.disconnect(); this->sel_modified_connection.disconnect(); @@ -174,15 +170,15 @@ void FreehandBase::finish() { ToolBase::finish(); } -void FreehandBase::set(const Inkscape::Preferences::Entry& /*value*/) { -} +void FreehandBase::set(const Inkscape::Preferences::Entry & /*value*/) {} -bool FreehandBase::root_handler(GdkEvent* event) { +bool FreehandBase::root_handler(GdkEvent *event) +{ gint ret = FALSE; switch (event->type) { case GDK_KEY_PRESS: - switch (get_latin_keyval (&event->key)) { + switch (get_latin_keyval(&event->key)) { case GDK_KEY_Up: case GDK_KEY_Down: case GDK_KEY_KP_Up: @@ -193,15 +189,15 @@ bool FreehandBase::root_handler(GdkEvent* event) { } break; default: + break; + } + break; + default: break; - } - break; - default: - break; } if (!ret) { - ret = ToolBase::root_handler(event); + ret = ToolBase::root_handler(event); } return ret; @@ -218,9 +214,7 @@ boost::optional<Geom::Point> FreehandBase::red_curve_get_last_point() static Glib::ustring const tool_name(FreehandBase *dc) { - return ( SP_IS_PEN_CONTEXT(dc) - ? "/tools/freehand/pen" - : "/tools/freehand/pencil" ); + return (SP_IS_PEN_CONTEXT(dc) ? "/tools/freehand/pen" : "/tools/freehand/pencil"); } static void spdc_paste_curve_as_freehand_shape(Geom::PathVector const &newpath, FreehandBase *dc, SPItem *item) @@ -232,8 +226,8 @@ static void spdc_paste_curve_as_freehand_shape(Geom::PathVector const &newpath, bool saved = DocumentUndo::getUndoSensitive(document); DocumentUndo::setUndoSensitive(document, false); Effect::createAndApply(PATTERN_ALONG_PATH, document, item); - Effect* lpe = SP_LPE_ITEM(item)->getCurrentLPE(); - static_cast<LPEPatternAlongPath*>(lpe)->pattern.set_new_value(newpath,true); + Effect *lpe = SP_LPE_ITEM(item)->getCurrentLPE(); + static_cast<LPEPatternAlongPath *>(lpe)->pattern.set_new_value(newpath, true); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double scale = prefs->getDouble("/live_effects/pap/width", 1); if (!scale) { @@ -311,9 +305,9 @@ static void spdc_apply_powerstroke_shape(std::vector<Geom::Point> points, Freeha bool saved = DocumentUndo::getUndoSensitive(document); DocumentUndo::setUndoSensitive(document, false); Effect::createAndApply(POWERSTROKE, document, item); - Effect* lpe = SP_LPE_ITEM(item)->getCurrentLPE(); + Effect *lpe = SP_LPE_ITEM(item)->getCurrentLPE(); - static_cast<LPEPowerStroke*>(lpe)->offset_points.param_set_and_write_new_value(points); + static_cast<LPEPowerStroke *>(lpe)->offset_points.param_set_and_write_new_value(points); // write powerstroke parameters: lpe->getRepr()->setAttribute("start_linecap_type", "zerowidth"); @@ -332,7 +326,7 @@ static void spdc_apply_bend_shape(gchar const *svgd, FreehandBase *dc, SPItem *i { using namespace Inkscape::LivePathEffect; SPUse *use = dynamic_cast<SPUse *>(item); - if ( use ) { + if (use) { return; } SPDesktop *desktop = dc->getDesktop(); @@ -342,10 +336,10 @@ static void spdc_apply_bend_shape(gchar const *svgd, FreehandBase *dc, SPItem *i } bool saved = DocumentUndo::getUndoSensitive(document); DocumentUndo::setUndoSensitive(document, false); - if(!SP_IS_LPE_ITEM(item) || !SP_LPE_ITEM(item)->hasPathEffectOfType(BEND_PATH)){ + if (!SP_IS_LPE_ITEM(item) || !SP_LPE_ITEM(item)->hasPathEffectOfType(BEND_PATH)) { Effect::createAndApply(BEND_PATH, document, item); } - Effect* lpe = SP_LPE_ITEM(item)->getCurrentLPE(); + Effect *lpe = SP_LPE_ITEM(item)->getCurrentLPE(); // write bend parameters: Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -358,7 +352,7 @@ static void spdc_apply_bend_shape(gchar const *svgd, FreehandBase *dc, SPItem *i lpe->getRepr()->setAttribute("prop_scale", os.str()); lpe->getRepr()->setAttribute("scale_y_rel", "false"); lpe->getRepr()->setAttribute("vertical", "false"); - static_cast<LPEBendPath*>(lpe)->bend_path.paste_param_path(svgd); + static_cast<LPEBendPath *>(lpe)->bend_path.paste_param_path(svgd); DocumentUndo::setUndoSensitive(document, saved); } @@ -374,7 +368,7 @@ static void spdc_apply_simplify(std::string threshold, FreehandBase *dc, SPItem using namespace Inkscape::LivePathEffect; Effect::createAndApply(SIMPLIFY, document, item); - Effect* lpe = SP_LPE_ITEM(item)->getCurrentLPE(); + Effect *lpe = SP_LPE_ITEM(item)->getCurrentLPE(); // write simplify parameters: lpe->getRepr()->setAttribute("steps", "1"); lpe->getRepr()->setAttributeOrRemoveIfEmpty("threshold", threshold); @@ -385,7 +379,16 @@ static void spdc_apply_simplify(std::string threshold, FreehandBase *dc, SPItem DocumentUndo::setUndoSensitive(document, saved); } -enum shapeType { NONE, TRIANGLE_IN, TRIANGLE_OUT, ELLIPSE, CLIPBOARD, BEND_CLIPBOARD, LAST_APPLIED }; +enum shapeType +{ + NONE, + TRIANGLE_IN, + TRIANGLE_OUT, + ELLIPSE, + CLIPBOARD, + BEND_CLIPBOARD, + LAST_APPLIED +}; static shapeType previous_shape_type = NONE; static void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item, SPCurve *curve, bool is_bend) @@ -396,30 +399,28 @@ static void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item, auto *desktop = dc->getDesktop(); if (item && SP_IS_LPE_ITEM(item)) { - //Store the clipboard path to apply in the future without the use of clipboard + // Store the clipboard path to apply in the future without the use of clipboard static Geom::PathVector previous_shape_pathv; static SPItem *bend_item; shapeType shape = (shapeType)prefs->getInt(tool_name(dc) + "/shape", 0); if (previous_shape_type == NONE) { previous_shape_type = shape; } - if(shape == LAST_APPLIED){ + if (shape == LAST_APPLIED) { shape = previous_shape_type; - if(shape == CLIPBOARD || shape == BEND_CLIPBOARD){ + if (shape == CLIPBOARD || shape == BEND_CLIPBOARD) { shape = LAST_APPLIED; } } Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); - if (is_bend && - (shape == BEND_CLIPBOARD || (shape == LAST_APPLIED && previous_shape_type != CLIPBOARD)) && - cm->paste(desktop, true)) - { + if (is_bend && (shape == BEND_CLIPBOARD || (shape == LAST_APPLIED && previous_shape_type != CLIPBOARD)) && + cm->paste(desktop, true)) { bend_item = dc->selection->singleItem(); - if(!bend_item || (!SP_IS_SHAPE(bend_item) && !SP_IS_GROUP(bend_item))){ + if (!bend_item || (!SP_IS_SHAPE(bend_item) && !SP_IS_GROUP(bend_item))) { previous_shape_type = NONE; return; } - } else if(is_bend) { + } else if (is_bend) { return; } if (!is_bend && previous_shape_type == BEND_CLIPBOARD && shape == BEND_CLIPBOARD) { @@ -429,9 +430,9 @@ static void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item, bool simplify = prefs->getInt(tool_name(dc) + "/simplify", 0); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); guint mode = prefs->getInt("/tools/freehand/pencil/freehand-mode", 0); - if(simplify && mode != 2){ + if (simplify && mode != 2) { double tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0); - tol = tol/(100.0*(102.0-tol)); + tol = tol / (100.0 * (102.0 - tol)); std::ostringstream ss; ss << tol; spdc_apply_simplify(ss.str(), dc, item); @@ -455,9 +456,9 @@ static void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item, const char *stroke_width = sp_repr_css_property(css_item, "stroke-width", "0"); double swidth; sp_svg_number_read_d(stroke_width, &swidth); - swidth = prefs->getDouble("/live_effects/powerstroke/width", swidth/2); + swidth = prefs->getDouble("/live_effects/powerstroke/width", swidth / 2); if (!swidth) { - swidth = swidth/2; + swidth = swidth / 2; } swidth = std::abs(swidth); if (SP_IS_PENCIL_CONTEXT(dc)) { @@ -477,62 +478,62 @@ static void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item, case NONE: // don't apply any shape break; - case TRIANGLE_IN: - { + case TRIANGLE_IN: { // "triangle in" std::vector<Geom::Point> points(1); - + points[0] = Geom::Point(0., swidth); - //points[0] *= i2anc_affine(static_cast<SPItem *>(item->parent), NULL).inverse(); + // points[0] *= i2anc_affine(static_cast<SPItem *>(item->parent), NULL).inverse(); spdc_apply_powerstroke_shape(points, dc, item); shape_applied = true; break; } - case TRIANGLE_OUT: - { + case TRIANGLE_OUT: { // "triangle out" guint curve_length = curveref->get_segment_count(); std::vector<Geom::Point> points(1); points[0] = Geom::Point(0, swidth); - //points[0] *= i2anc_affine(static_cast<SPItem *>(item->parent), NULL).inverse(); + // points[0] *= i2anc_affine(static_cast<SPItem *>(item->parent), NULL).inverse(); points[0][Geom::X] = (double)curve_length; spdc_apply_powerstroke_shape(points, dc, item); shape_applied = true; break; } - case ELLIPSE: - { + case ELLIPSE: { // "ellipse" auto c = std::make_unique<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->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->get_pathvector(), dc, item); shape_applied = true; break; } - case CLIPBOARD: - { + case CLIPBOARD: { // take shape from clipboard; Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get(); - if(cm->paste(desktop,true)){ - SPItem * pasted_clipboard = dc->selection->singleItem(); + if (cm->paste(desktop, true)) { + SPItem *pasted_clipboard = dc->selection->singleItem(); dc->selection->toCurves(); pasted_clipboard = dc->selection->singleItem(); - if(pasted_clipboard){ + if (pasted_clipboard) { Inkscape::XML::Node *pasted_clipboard_root = pasted_clipboard->getRepr(); - Inkscape::XML::Node *path = sp_repr_lookup_name(pasted_clipboard_root, "svg:path", -1); // unlimited search depth - if ( path != nullptr ) { + Inkscape::XML::Node *path = + sp_repr_lookup_name(pasted_clipboard_root, "svg:path", -1); // unlimited search depth + if (path != nullptr) { gchar const *svgd = path->attribute("d"); dc->selection->remove(SP_OBJECT(pasted_clipboard)); - previous_shape_pathv = sp_svg_read_pathv(svgd); + previous_shape_pathv = sp_svg_read_pathv(svgd); previous_shape_pathv *= pasted_clipboard->transform; spdc_paste_curve_as_freehand_shape(previous_shape_pathv, dc, item); @@ -550,15 +551,14 @@ static void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item, } break; } - case BEND_CLIPBOARD: - { + case BEND_CLIPBOARD: { gchar const *svgd = item->getRepr()->attribute("d"); - if(bend_item && (SP_IS_SHAPE(bend_item) || SP_IS_GROUP(bend_item))){ + if (bend_item && (SP_IS_SHAPE(bend_item) || SP_IS_GROUP(bend_item))) { // If item is a SPRect, convert it to path first: - if ( dynamic_cast<SPRect *>(bend_item) ) { + if (dynamic_cast<SPRect *>(bend_item)) { if (desktop) { Inkscape::Selection *sel = desktop->getSelection(); - if ( sel && !sel->isEmpty() ) { + if (sel && !sel->isEmpty()) { sel->clear(); sel->add(bend_item); sel->toCurves(); @@ -566,7 +566,7 @@ static void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item, } } } - bend_item->moveTo(item,false); + bend_item->moveTo(item, false); bend_item->transform.setTranslation(Geom::Point()); spdc_apply_bend_shape(svgd, dc, bend_item); dc->selection->add(SP_OBJECT(bend_item)); @@ -578,28 +578,27 @@ static void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item, } break; } - case LAST_APPLIED: - { - if(previous_shape_type == CLIPBOARD){ - if(previous_shape_pathv.size() != 0){ + case LAST_APPLIED: { + if (previous_shape_type == CLIPBOARD) { + if (previous_shape_pathv.size() != 0) { spdc_paste_curve_as_freehand_shape(previous_shape_pathv, dc, item); shape_applied = true; shape = CLIPBOARD; - } else{ + } else { shape = NONE; } } else { - if(bend_item != nullptr && bend_item->getRepr() != nullptr){ + if (bend_item != nullptr && bend_item->getRepr() != nullptr) { gchar const *svgd = item->getRepr()->attribute("d"); dc->selection->add(SP_OBJECT(bend_item)); dc->selection->duplicate(); dc->selection->remove(SP_OBJECT(bend_item)); bend_item = dc->selection->singleItem(); - if(bend_item){ - bend_item->moveTo(item,false); + if (bend_item) { + bend_item->moveTo(item, false); Geom::Coord expansion_X = bend_item->transform.expansionX(); Geom::Coord expansion_Y = bend_item->transform.expansionY(); - bend_item->transform = Geom::Affine(1,0,0,1,0,0); + bend_item->transform = Geom::Affine(1, 0, 0, 1, 0, 0); bend_item->transform.setExpansionX(expansion_X); bend_item->transform.setExpansionY(expansion_Y); spdc_apply_bend_shape(svgd, dc, bend_item); @@ -624,11 +623,11 @@ static void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item, // apply original stroke color as fill and unset stroke; then return SPCSSAttr *css = sp_repr_css_attr_new(); if (!strcmp(cfill, "none")) { - sp_repr_css_set_property (css, "fill", cstroke); + sp_repr_css_set_property(css, "fill", cstroke); } else { - sp_repr_css_set_property (css, "fill", cfill); + sp_repr_css_set_property(css, "fill", cfill); } - sp_repr_css_set_property (css, "stroke", "none"); + sp_repr_css_set_property(css, "stroke", "none"); sp_desktop_apply_css_recursive(dc->white_item, css, true); sp_repr_css_attr_unref(css); return; @@ -668,7 +667,7 @@ static void spdc_selection_modified(Inkscape::Selection *sel, guint /*flags*/, F } } -static void spdc_attach_selection(FreehandBase *dc, Inkscape::Selection */*sel*/) +static void spdc_attach_selection(FreehandBase *dc, Inkscape::Selection * /*sel*/) { // We reset white and forget white/start/end anchors spdc_reset_white(dc); @@ -677,7 +676,7 @@ static void spdc_attach_selection(FreehandBase *dc, Inkscape::Selection */*sel*/ SPItem *item = dc->selection ? dc->selection->singleItem() : nullptr; - if ( item && SP_IS_PATH(item) ) { + if (item && SP_IS_PATH(item)) { // Create new white data // Item dc->white_item = item; @@ -687,14 +686,14 @@ static void spdc_attach_selection(FreehandBase *dc, Inkscape::Selection */*sel*/ auto path = static_cast<SPPath *>(item); auto norm = SPCurve::copy(path->curveForEdit()); norm->transform((dc->white_item)->i2dt_affine()); - g_return_if_fail( norm != nullptr ); + g_return_if_fail(norm != nullptr); dc->white_curves = norm->split(); // Anchor list for (auto const &c_smart_ptr : dc->white_curves) { auto *c = c_smart_ptr.get(); - g_return_if_fail( c->get_segment_count() > 0 ); - if ( !c->is_closed() ) { + 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) @@ -708,9 +707,7 @@ static void spdc_attach_selection(FreehandBase *dc, Inkscape::Selection */*sel*/ } } - -void spdc_endpoint_snap_rotation(ToolBase* const ec, Geom::Point &p, Geom::Point const &o, - guint state) +void spdc_endpoint_snap_rotation(ToolBase *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)); @@ -727,7 +724,8 @@ void spdc_endpoint_snap_rotation(ToolBase* const ec, Geom::Point &p, Geom::Point m.snapprefs.setSnapEnabledGlobally(false); } - Inkscape::SnappedPoint dummy = m.constrainedAngularSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_NODE_HANDLE), boost::optional<Geom::Point>(), o, snaps); + 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) { @@ -737,14 +735,15 @@ void spdc_endpoint_snap_rotation(ToolBase* const ec, Geom::Point &p, Geom::Point m.unSetup(); } - -void spdc_endpoint_snap_free(ToolBase* const ec, Geom::Point& p, boost::optional<Geom::Point> &start_of_line, guint const /*state*/) +void spdc_endpoint_snap_free(ToolBase *const ec, Geom::Point &p, boost::optional<Geom::Point> &start_of_line, + guint const /*state*/) { const SPDesktop *dt = ec->getDesktop(); SnapManager &m = dt->namedview->snap_manager; Inkscape::Selection *selection = dt->getSelection(); - // selection->singleItem() is the item that is currently being drawn. This item will not be snapped to (to avoid self-snapping) + // 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()); @@ -787,10 +786,8 @@ void spdc_concat_colors_and_flush(FreehandBase *dc, gboolean forceclosed) } // Step A - test, whether we ended on green anchor - if ( (forceclosed && - (!dc->sa || (dc->sa && dc->sa->curve->is_empty()))) || - ( dc->green_anchor && dc->green_anchor->active)) - { + if ((forceclosed && (!dc->sa || (dc->sa && dc->sa->curve->is_empty()))) || + (dc->green_anchor && dc->green_anchor->active)) { // We hit green anchor, closing Green-Blue-Red dc->getDesktop()->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Path is closed.")); c->closepath_current(); @@ -800,17 +797,13 @@ void spdc_concat_colors_and_flush(FreehandBase *dc, gboolean forceclosed) } // 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() ) ) - { + 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->getDesktop()->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Closing path.")); dc->sa_overwrited->append_continuous(*c); dc->sa_overwrited->closepath_current(); if (!dc->white_curves.empty()) { - dc->white_curves.erase(std::find(dc->white_curves.begin(),dc->white_curves.end(), dc->sa->curve)); + dc->white_curves.erase(std::find(dc->white_curves.begin(), dc->white_curves.end(), dc->sa->curve)); } dc->white_curves.push_back(std::move(dc->sa_overwrited)); spdc_flush_white(dc, nullptr); @@ -819,41 +812,40 @@ void spdc_concat_colors_and_flush(FreehandBase *dc, gboolean forceclosed) // Step C - test start if (dc->sa) { if (!dc->white_curves.empty()) { - dc->white_curves.erase(std::find(dc->white_curves.begin(),dc->white_curves.end(), dc->sa->curve)); + dc->white_curves.erase(std::find(dc->white_curves.begin(), dc->white_curves.end(), dc->sa->curve)); } dc->sa_overwrited->append_continuous(*c); c = std::move(dc->sa_overwrited); } else /* Step D - test end */ if (dc->ea) { auto e = std::move(dc->ea->curve); if (!dc->white_curves.empty()) { - dc->white_curves.erase(std::find(dc->white_curves.begin(),dc->white_curves.end(), e)); + dc->white_curves.erase(std::find(dc->white_curves.begin(), dc->white_curves.end(), e)); } if (!dc->ea->start) { e = e->create_reverse(); } - if(prefs->getInt(tool_name(dc) + "/freehand-mode", 0) == 1 || - prefs->getInt(tool_name(dc) + "/freehand-mode", 0) == 2){ - e = e->create_reverse(); - Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const*>(&*e->last_segment()); - if(cubic){ - auto lastSeg = std::make_unique<SPCurve>(); - lastSeg->moveto((*cubic)[0]); - lastSeg->curveto((*cubic)[1],(*cubic)[3],(*cubic)[3]); - if( e->get_segment_count() == 1){ - e = std::move(lastSeg); - }else{ - //we eliminate the last segment - e->backspace(); - //and we add it again with the recreation - e->append_continuous(*lastSeg); - } + if (prefs->getInt(tool_name(dc) + "/freehand-mode", 0) == 1 || + prefs->getInt(tool_name(dc) + "/freehand-mode", 0) == 2) { + e = e->create_reverse(); + Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>(&*e->last_segment()); + if (cubic) { + auto lastSeg = std::make_unique<SPCurve>(); + lastSeg->moveto((*cubic)[0]); + lastSeg->curveto((*cubic)[1], (*cubic)[3], (*cubic)[3]); + if (e->get_segment_count() == 1) { + e = std::move(lastSeg); + } else { + // we eliminate the last segment + e->backspace(); + // and we add it again with the recreation + e->append_continuous(*lastSeg); } - e = e->create_reverse(); + } + e = e->create_reverse(); } c->append_continuous(*e); } - if (forceclosed) - { + if (forceclosed) { dc->getDesktop()->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Path is closed.")); c->closepath_current(); } @@ -864,7 +856,7 @@ static void spdc_flush_white(FreehandBase *dc, SPCurve *gc) { std::unique_ptr<SPCurve> c; - if (! dc->white_curves.empty()) { + if (!dc->white_curves.empty()) { g_assert(dc->white_item); // c = concat(white_curves) @@ -888,11 +880,9 @@ static void spdc_flush_white(FreehandBase *dc, SPCurve *gc) Inkscape::XML::Document *xml_doc = doc->getReprDoc(); // Now we have to go back to item coordinates at last - c->transform( dc->white_item - ? (dc->white_item)->dt2i_affine() - : desktop->dt2doc() ); + c->transform(dc->white_item ? (dc->white_item)->dt2i_affine() : desktop->dt2doc()); - if ( c && !c->is_empty() ) { + if (c && !c->is_empty()) { // We actually have something to write bool has_lpe = false; @@ -907,8 +897,8 @@ static void spdc_flush_white(FreehandBase *dc, SPCurve *gc) sp_desktop_apply_style_tool(desktop, repr, tool_name(dc).data(), false); } - gchar *str = sp_svg_write_path( c->get_pathvector() ); - g_assert( str != nullptr ); + gchar *str = sp_svg_write_path(c->get_pathvector()); + g_assert(str != nullptr); if (has_lpe) repr->setAttribute("inkscape:original-d", str); else @@ -925,7 +915,7 @@ static void spdc_flush_white(FreehandBase *dc, SPCurve *gc) // Attach repr SPItem *item = SP_ITEM(desktop->currentLayer()->appendChildRepr(repr)); dc->white_item = item; - //Bend needs the transforms applied after, Other effects best before + // Bend needs the transforms applied after, Other effects best before spdc_check_for_and_apply_waiting_LPE(dc, item, c.get(), true); Inkscape::GC::release(repr); item->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); @@ -933,12 +923,11 @@ static void spdc_flush_white(FreehandBase *dc, SPCurve *gc) item->doWriteTransform(item->transform, nullptr, true); spdc_check_for_and_apply_waiting_LPE(dc, item, c.get(), false); dc->selection->set(repr); - if(previous_shape_type == BEND_CLIPBOARD){ + if (previous_shape_type == BEND_CLIPBOARD) { repr->parent()->removeChild(repr); } } - DocumentUndo::done(doc, SP_IS_PEN_CONTEXT(dc)? SP_VERB_CONTEXT_PEN : SP_VERB_CONTEXT_PENCIL, - _("Draw path")); + 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 @@ -961,9 +950,9 @@ SPDrawAnchor *spdc_test_inside(FreehandBase *dc, Geom::Point p) active = sp_draw_anchor_test(dc->green_anchor, p, TRUE); } - for (auto i:dc->white_anchors) { + for (auto i : dc->white_anchors) { SPDrawAnchor *na = sp_draw_anchor_test(i, p, !active); - if ( !active && na ) { + if (!active && na) { active = na; } } @@ -977,7 +966,7 @@ static void spdc_reset_white(FreehandBase *dc) dc->white_item = nullptr; } dc->white_curves.clear(); - for (auto i:dc->white_anchors) + for (auto i : dc->white_anchors) sp_draw_anchor_destroy(i); dc->white_anchors.clear(); } @@ -997,7 +986,7 @@ static void spdc_free_colors(FreehandBase *dc) dc->blue_bpath = nullptr; } dc->blue_curve.reset(); - + // Overwrite start anchor curve dc->sa_overwrited.reset(); // Green @@ -1015,14 +1004,15 @@ static void spdc_free_colors(FreehandBase *dc) dc->white_item = nullptr; } dc->white_curves.clear(); - for (auto i:dc->white_anchors) + for (auto i : dc->white_anchors) sp_draw_anchor_destroy(i); dc->white_anchors.clear(); } -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") - || !strcmp(tool, "/tools/calligraphic") ); +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") || + !strcmp(tool, "/tools/calligraphic")); Glib::ustring tool_path = tool; SPDesktop *desktop = ec->getDesktop(); @@ -1046,9 +1036,11 @@ void spdc_create_single_dot(ToolBase *ec, Geom::Point const &pt, char const *too } // unset stroke and set fill color to former stroke color - gchar * str; - str = strcmp(tool, "/tools/calligraphic") ? g_strdup_printf("fill:#%06x;stroke:none;", sp_desktop_get_color_tool(desktop, tool, false) >> 8) - : g_strdup_printf("fill:#%06x;stroke:#%06x;", sp_desktop_get_color_tool(desktop, tool, true) >> 8, sp_desktop_get_color_tool(desktop, tool, false) >> 8); + gchar *str; + str = strcmp(tool, "/tools/calligraphic") + ? g_strdup_printf("fill:#%06x;stroke:none;", sp_desktop_get_color_tool(desktop, tool, false) >> 8) + : g_strdup_printf("fill:#%06x;stroke:#%06x;", sp_desktop_get_color_tool(desktop, tool, true) >> 8, + sp_desktop_get_color_tool(desktop, tool, false) >> 8); repr->setAttribute("style", str); g_free(str); @@ -1056,12 +1048,13 @@ void spdc_create_single_dot(ToolBase *ec, Geom::Point const &pt, char const *too // 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::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 (!strcmp(tool, "/tools/calligraphic")) - rad = 0.0333 * prefs->getDouble(tool_path + "/width", 3.0) / desktop->current_zoom() / desktop->getDocument()->getDocumentScale()[Geom::X]; + rad = 0.0333 * prefs->getDouble(tool_path + "/width", 3.0) / desktop->current_zoom() / + desktop->getDocument()->getDocumentScale()[Geom::X]; 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, @@ -1074,10 +1067,10 @@ void spdc_create_single_dot(ToolBase *ec, Geom::Point const &pt, char const *too 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); + 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(); item->doWriteTransform(item->transform, nullptr, true); @@ -1087,9 +1080,9 @@ void spdc_create_single_dot(ToolBase *ec, Geom::Point const &pt, char const *too DocumentUndo::done(desktop->getDocument(), SP_VERB_NONE, _("Create single dot")); } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/freehand-base.h b/src/ui/tools/freehand-base.h index bb201a1aac61d49a0a0bd20ebe56d71bc7bd100f..8786f758ca0affdd2c5721939a2df1e2cd32804c 100644 --- a/src/ui/tools/freehand-base.h +++ b/src/ui/tools/freehand-base.h @@ -15,37 +15,37 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <memory> #include <sigc++/connection.h> -#include "ui/tools/tool-base.h" #include "live_effects/effect-enum.h" - -#include <memory> +#include "ui/tools/tool-base.h" struct SPCanvasItem; class SPCurve; struct SPDrawAnchor; namespace Inkscape { - class Selection; +class Selection; } namespace boost { - template<class T> - class optional; +template <class T> +class optional; } /* 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) - +#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) namespace Inkscape { namespace UI { namespace Tools { -class FreehandBase : public ToolBase { +class FreehandBase : public ToolBase +{ public: FreehandBase(gchar const *const *cursor_shape); ~FreehandBase() override; @@ -70,7 +70,7 @@ public: std::unique_ptr<SPCurve> blue_curve; // Green - New path as it's drawn. - std::vector<SPCanvasItem*> green_bpaths; + std::vector<SPCanvasItem *> green_bpaths; std::unique_ptr<SPCurve> green_curve; SPDrawAnchor *green_anchor; gboolean green_closed; // a flag meaning we hit the green anchor, so close the path on itself @@ -78,7 +78,7 @@ public: // White SPItem *white_item; std::list<std::unique_ptr<SPCurve>> white_curves; - std::vector<SPDrawAnchor*> white_anchors; + std::vector<SPDrawAnchor *> white_anchors; // Temporary modified curve when start anchor std::unique_ptr<SPCurve> sa_overwrited; @@ -89,7 +89,6 @@ public: // 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; @@ -99,19 +98,18 @@ public: bool red_curve_is_valid; bool anchor_statusbar; - + bool tablet_enabled; bool is_tablet; gdouble pressure; - void set(const Inkscape::Preferences::Entry& val) override; + void set(const Inkscape::Preferences::Entry &val) override; protected: - void setup() override; void finish() override; - bool root_handler(GdkEvent* event) override; + bool root_handler(GdkEvent *event) override; }; /** @@ -134,9 +132,10 @@ void spdc_concat_colors_and_flush(FreehandBase *dc, gboolean forceclosed); * @param o origin point. * @param state keyboard state to check if ctrl or shift was pressed. */ -void spdc_endpoint_snap_rotation(ToolBase* const ec, Geom::Point &p, Geom::Point const &o, guint state); +void spdc_endpoint_snap_rotation(ToolBase *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); +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 @@ -149,9 +148,9 @@ void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item); */ void spdc_create_single_dot(ToolBase *ec, Geom::Point const &pt, char const *tool, guint event_state); -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif // SEEN_SP_DRAW_CONTEXT_H diff --git a/src/ui/tools/gradient-tool.cpp b/src/ui/tools/gradient-tool.cpp index 7cc8d8ef9fcf6a67ab4bda4c72d9969a2ca50d2c..4f4aade7300590fe7da5d1f113f1d085fd7a03eb 100644 --- a/src/ui/tools/gradient-tool.cpp +++ b/src/ui/tools/gradient-tool.cpp @@ -13,10 +13,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/i18n.h> +#include "ui/tools/gradient-tool.h" + #include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> #include "desktop.h" +#include "display/sp-ctrlline.h" #include "document-undo.h" #include "document.h" #include "gradient-chemistry.h" @@ -24,23 +27,16 @@ #include "include/macros.h" #include "message-context.h" #include "message-stack.h" +#include "object/sp-namedview.h" +#include "object/sp-stop.h" #include "rubberband.h" #include "selection-chemistry.h" #include "selection.h" #include "snap.h" -#include "verbs.h" - -#include "object/sp-namedview.h" -#include "object/sp-stop.h" - -#include "display/sp-ctrlline.h" - +#include "svg/css-ostringstream.h" #include "ui/pixmaps/cursor-gradient-add.xpm" #include "ui/pixmaps/cursor-gradient.xpm" - -#include "svg/css-ostringstream.h" - -#include "ui/tools/gradient-tool.h" +#include "verbs.h" using Inkscape::DocumentUndo; @@ -50,26 +46,27 @@ namespace Tools { static void sp_gradient_drag(GradientTool &rc, Geom::Point const pt, guint state, guint32 etime); -const std::string& GradientTool::getPrefsPath() { - return GradientTool::prefsPath; +const std::string &GradientTool::getPrefsPath() +{ + return GradientTool::prefsPath; } const std::string GradientTool::prefsPath = "/tools/gradient"; - GradientTool::GradientTool() : ToolBase(cursor_gradient_xpm) , cursor_addnode(false) , node_added(false) -// TODO: Why are these connections stored as pointers? + // TODO: Why are these connections stored as pointers? , selcon(nullptr) , subselcon(nullptr) { - // TODO: This value is overwritten in the root handler + // TODO: This value is overwritten in the root handler this->tolerance = 6; } -GradientTool::~GradientTool() { +GradientTool::~GradientTool() +{ this->enableGrDrag(false); this->selcon->disconnect(); @@ -82,74 +79,76 @@ GradientTool::~GradientTool() { // This must match GrPointType enum sp-gradient.h // We should move this to a shared header (can't simply move to gradient.h since that would require // including <glibmm/i18n.h> which messes up "N_" in extensions... argh!). -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>"), +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>"), - N_("Mesh gradient <b>corner</b>"), - N_("Mesh gradient <b>handle</b>"), - N_("Mesh gradient <b>tensor</b>") -}; - -void GradientTool::selection_changed(Inkscape::Selection*) { + N_("Radial gradient <b>mid stop</b>"), N_("Radial gradient <b>mid stop</b>"), N_("Mesh gradient <b>corner</b>"), + N_("Mesh gradient <b>handle</b>"), N_("Mesh gradient <b>tensor</b>")}; +void GradientTool::selection_changed(Inkscape::Selection *) +{ GrDrag *drag = _grdrag; Inkscape::Selection *selection = this->desktop->getSelection(); if (selection == nullptr) { return; } - guint n_obj = (guint) boost::distance(selection->items()); + guint n_obj = (guint)boost::distance(selection->items()); 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 + // 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 + 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); - message_context->setF(Inkscape::NORMAL_MESSAGE, - message,_(gr_handle_descr[drag->singleSelectedDraggerSingleDraggableType()]), n_tot, n_obj); + // 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); + 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) + 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); - message_context->setF(Inkscape::NORMAL_MESSAGE,message,drag->singleSelectedDraggerNumDraggables(), n_tot, n_obj); + "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); + 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); - message_context->setF(Inkscape::NORMAL_MESSAGE,message, n_sel, n_tot, n_obj); + // 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); + message_context->setF(Inkscape::NORMAL_MESSAGE, message, n_sel, n_tot, n_obj); } else if (n_sel == 0) { message_context->setF(Inkscape::NORMAL_MESSAGE, - //TRANSLATORS: The plural refers to number of selected objects + // 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); + "<b>No</b> gradient handles selected out of %d on %d selected objects", n_obj), + n_tot, n_obj); } } -void GradientTool::setup() { +void GradientTool::setup() +{ ToolBase::setup(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - + if (prefs->getBool("/tools/gradient/selcue", true)) { this->enableSelectionCue(); } @@ -157,56 +156,48 @@ void GradientTool::setup() { this->enableGrDrag(); Inkscape::Selection *selection = this->desktop->getSelection(); - this->selcon = new sigc::connection(selection->connectChanged( - sigc::mem_fun(this, &GradientTool::selection_changed) - )); + 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*)nullptr - )) - )); + sigc::hide(sigc::bind(sigc::mem_fun(this, &GradientTool::selection_changed), (Inkscape::Selection *)nullptr)))); this->selection_changed(selection); } -void -sp_gradient_context_select_next (ToolBase *event_context) +void sp_gradient_context_select_next(ToolBase *event_context) { GrDrag *drag = event_context->_grdrag; - g_assert (drag); + g_assert(drag); GrDragger *d = drag->select_next(); event_context->getDesktop()->scroll_to_point(d->point, 1.0); } -void -sp_gradient_context_select_prev (ToolBase *event_context) +void sp_gradient_context_select_prev(ToolBase *event_context) { GrDrag *drag = event_context->_grdrag; - g_assert (drag); + g_assert(drag); GrDragger *d = drag->select_prev(); event_context->getDesktop()->scroll_to_point(d->point, 1.0); } -static bool -sp_gradient_context_is_over_line (GradientTool *rc, SPItem *item, Geom::Point event_p) +static bool sp_gradient_context_is_over_line(GradientTool *rc, SPItem *item, Geom::Point event_p) { const SPDesktop *desktop = rc->getDesktop(); - //Translate mouse point into proper coord system + // Translate mouse point into proper coord system rc->mousepoint_doc = desktop->w2d(event_p); if (SP_IS_CTRLLINE(item)) { - SPCtrlLine* line = SP_CTRLLINE(item); + SPCtrlLine *line = SP_CTRLLINE(item); Geom::LineSegment ls(line->s, line->e); Geom::Point nearest = ls.pointAt(ls.nearestTime(rc->mousepoint_doc)); - double dist_screen = Geom::L2 (rc->mousepoint_doc - nearest) * desktop->current_zoom(); + double dist_screen = Geom::L2(rc->mousepoint_doc - nearest) * desktop->current_zoom(); bool close = (dist_screen < rc->tolerance); @@ -215,36 +206,35 @@ sp_gradient_context_is_over_line (GradientTool *rc, SPItem *item, Geom::Point ev return false; } -static std::vector<Geom::Point> -sp_gradient_context_get_stop_intervals (GrDrag *drag, std::vector<SPStop *> &these_stops, std::vector<SPStop *> &next_stops) +static std::vector<Geom::Point> sp_gradient_context_get_stop_intervals(GrDrag *drag, std::vector<SPStop *> &these_stops, + std::vector<SPStop *> &next_stops) { std::vector<Geom::Point> coords; // for all selected draggers - for (std::set<GrDragger *>::const_iterator i = drag->selected.begin(); i != drag->selected.end() ; ++i ) { + for (std::set<GrDragger *>::const_iterator i = drag->selected.begin(); i != drag->selected.end(); ++i) { GrDragger *dragger = *i; // remember the coord of the dragger to reselect it later coords.push_back(dragger->point); // for all draggables of dragger - for (std::vector<GrDraggable *>::const_iterator j = dragger->draggables.begin(); j != dragger->draggables.end(); ++j) { + for (std::vector<GrDraggable *>::const_iterator j = dragger->draggables.begin(); j != dragger->draggables.end(); + ++j) { GrDraggable *d = *j; // find the gradient SPGradient *gradient = getGradient(d->item, d->fill_or_stroke); - SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (gradient, false); + 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 || + 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 *this_stop = sp_get_stop_i(vector, d->point_i); SPStop *next_stop = this_stop->getNextStop(); - SPStop *last_stop = sp_last_stop (vector); + SPStop *last_stop = sp_last_stop(vector); Inkscape::PaintTarget fs = d->fill_or_stroke; SPItem *item = d->item; @@ -259,33 +249,32 @@ sp_gradient_context_get_stop_intervals (GrDrag *drag, std::vector<SPStop *> &the // 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); + dnext = drag->getDraggerFor(item, POINT_LG_END, p_i + 1, fs); } else { - dnext = drag->getDraggerFor(item, POINT_LG_MID, p_i+1, fs); + 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); + dnext = drag->getDraggerFor(item, POINT_RG_R1, p_i + 1, fs); } else { - dnext = drag->getDraggerFor(item, POINT_RG_MID1, p_i+1, fs); + dnext = drag->getDraggerFor(item, POINT_RG_MID1, p_i + 1, fs); } } - if ((type == POINT_RG_MID2) || - (type == POINT_RG_CENTER && dnext && !dnext->isSelected())) { + 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); + dnext = drag->getDraggerFor(item, POINT_RG_R2, p_i + 1, fs); } else { - dnext = drag->getDraggerFor(item, POINT_RG_MID2, p_i+1, fs); + dnext = drag->getDraggerFor(item, POINT_RG_MID2, p_i + 1, fs); } } } // if both adjacent draggers selected, - if ((std::find(these_stops.begin(),these_stops.end(),this_stop)==these_stops.end()) && dnext && dnext->isSelected()) { - + if ((std::find(these_stops.begin(), these_stops.end(), this_stop) == these_stops.end()) && dnext && + dnext->isSelected()) { // remember the coords of the future dragger to select it - coords.push_back(0.5*(dragger->point + dnext->point)); + coords.push_back(0.5 * (dragger->point + dnext->point)); // do not insert a stop now, it will confuse the loop; // just remember the stops @@ -298,8 +287,7 @@ sp_gradient_context_get_stop_intervals (GrDrag *drag, std::vector<SPStop *> &the return coords; } -void -sp_gradient_context_add_stops_between_selected_stops (GradientTool *rc) +void sp_gradient_context_add_stops_between_selected_stops(GradientTool *rc) { SPDocument *doc = nullptr; GrDrag *drag = rc->_grdrag; @@ -307,7 +295,7 @@ sp_gradient_context_add_stops_between_selected_stops (GradientTool *rc) std::vector<SPStop *> these_stops; std::vector<SPStop *> next_stops; - std::vector<Geom::Point> coords = sp_gradient_context_get_stop_intervals (drag, these_stops, next_stops); + std::vector<Geom::Point> coords = sp_gradient_context_get_stop_intervals(drag, these_stops, next_stops); if (these_stops.empty() && drag->numSelected() == 1) { // if a single stop is selected, add between that stop and the next one @@ -321,8 +309,8 @@ sp_gradient_context_add_stops_between_selected_stops (GradientTool *rc) 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); + 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) { @@ -338,14 +326,14 @@ sp_gradient_context_add_stops_between_selected_stops (GradientTool *rc) auto j = next_stops.rbegin(); std::vector<SPStop *> new_stops; - for (;i != these_stops.rend() && j != next_stops.rend(); ++i, ++j ) { + for (; i != these_stops.rend() && j != next_stops.rend(); ++i, ++j) { SPStop *this_stop = *i; SPStop *next_stop = *j; - gfloat offset = 0.5*(this_stop->offset + next_stop->offset); + gfloat offset = 0.5 * (this_stop->offset + next_stop->offset); SPObject *parent = this_stop->parent; - if (SP_IS_GRADIENT (parent)) { + if (SP_IS_GRADIENT(parent)) { doc = parent->document; - SPStop *new_stop = sp_vector_add_stop (SP_GRADIENT (parent), this_stop, next_stop, offset); + SPStop *new_stop = sp_vector_add_stop(SP_GRADIENT(parent), this_stop, next_stop, offset); new_stops.push_back(new_stop); SP_GRADIENT(parent)->ensureVector(); } @@ -358,16 +346,18 @@ sp_gradient_context_add_stops_between_selected_stops (GradientTool *rc) drag->local_change = true; // select the newly created stops - for (auto i:new_stops) { + for (auto i : new_stops) { drag->selectByStop(i); } } } -static double sqr(double x) {return x*x;} +static double sqr(double x) +{ + return x * x; +} -static void -sp_gradient_simplify(GradientTool *rc, double tolerance) +static void sp_gradient_simplify(GradientTool *rc, double tolerance) { SPDocument *doc = nullptr; GrDrag *drag = rc->_grdrag; @@ -375,7 +365,7 @@ sp_gradient_simplify(GradientTool *rc, double tolerance) std::vector<SPStop *> these_stops; std::vector<SPStop *> next_stops; - std::vector<Geom::Point> coords = sp_gradient_context_get_stop_intervals (drag, these_stops, next_stops); + std::vector<Geom::Point> coords = sp_gradient_context_get_stop_intervals(drag, these_stops, next_stops); std::set<SPStop *> todel; @@ -387,23 +377,20 @@ sp_gradient_simplify(GradientTool *rc, double tolerance) auto i1 = std::find(these_stops.begin(), these_stops.end(), stop1); if (i1 != these_stops.end()) { - if (next_stops.size()>(i1-these_stops.begin())) { - SPStop *stop2 = *(next_stops.begin() + (i1-these_stops.begin())); + if (next_stops.size() > (i1 - these_stops.begin())) { + SPStop *stop2 = *(next_stops.begin() + (i1 - these_stops.begin())); - if (todel.find(stop0)!=todel.end() || todel.find(stop2) != todel.end()) + if (todel.find(stop0) != todel.end() || todel.find(stop2) != todel.end()) 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)); + 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)); + 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.insert(stop1); @@ -413,8 +400,8 @@ sp_gradient_simplify(GradientTool *rc, double tolerance) for (auto stop : todel) { doc = stop->document; - Inkscape::XML::Node * parent = stop->getRepr()->parent(); - parent->removeChild( stop->getRepr() ); + Inkscape::XML::Node *parent = stop->getRepr()->parent(); + parent->removeChild(stop->getRepr()); } if (!todel.empty()) { @@ -425,27 +412,26 @@ sp_gradient_simplify(GradientTool *rc, double tolerance) } } - -static void -sp_gradient_context_add_stop_near_point (GradientTool *rc, SPItem *item, Geom::Point mouse_p, guint32 /*etime*/) +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 const SPDesktop *desktop = rc->getDesktop(); - double tolerance = (double) rc->tolerance; + double tolerance = (double)rc->tolerance; - SPStop *newstop = rc->get_drag()->addStopNearPoint (item, mouse_p, tolerance/desktop->current_zoom()); + SPStop *newstop = rc->get_drag()->addStopNearPoint(item, mouse_p, tolerance / desktop->current_zoom()); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, - _("Add gradient stop")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, _("Add gradient stop")); rc->get_drag()->updateDraggers(); rc->get_drag()->local_change = true; rc->get_drag()->selectByStop(newstop); } -bool GradientTool::root_handler(GdkEvent* event) { +bool GradientTool::root_handler(GdkEvent *event) +{ static bool dragging; Inkscape::Selection *selection = desktop->getSelection(); @@ -454,321 +440,330 @@ bool GradientTool::root_handler(GdkEvent* event) { this->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); GrDrag *drag = this->_grdrag; - g_assert (drag); + g_assert(drag); gint ret = FALSE; switch (event->type) { - case GDK_2BUTTON_PRESS: - if ( event->button.button == 1 ) { - bool over_line = false; - SPCtrlLine *line = nullptr; - - if (!drag->lines.empty()) { - for (std::vector<SPCtrlLine *>::const_iterator l = drag->lines.begin(); l != drag->lines.end() && (!over_line); ++l) { - line = *l; - over_line |= sp_gradient_context_is_over_line (this, (SPItem*) line, Geom::Point(event->motion.x, event->motion.y)); + case GDK_2BUTTON_PRESS: + if (event->button.button == 1) { + bool over_line = false; + SPCtrlLine *line = nullptr; + + if (!drag->lines.empty()) { + for (std::vector<SPCtrlLine *>::const_iterator l = drag->lines.begin(); + l != drag->lines.end() && (!over_line); ++l) { + line = *l; + 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->items().front()), this->mousepoint_doc, event->button.time); - } else { - auto items= selection->items(); - for (auto i = items.begin();i!=items.end();++i) { - SPItem *item = *i; - 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(desktop->getDocument(), desktop, item, fsmode); - - SPGradient *priv = sp_item_set_gradient(item, vector, new_type, fsmode); - sp_gradient_reset_to_userspace(priv, item); + 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->items().front()), + this->mousepoint_doc, event->button.time); + } else { + auto items = selection->items(); + for (auto i = items.begin(); i != items.end(); ++i) { + SPItem *item = *i; + 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(desktop->getDocument(), desktop, item, fsmode); + + SPGradient *priv = sp_item_set_gradient(item, vector, new_type, fsmode); + sp_gradient_reset_to_userspace(priv, item); + } + desktop->redrawDesktop(); + ; + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, _("Create default gradient")); } - desktop->redrawDesktop();; - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_GRADIENT, - _("Create default gradient")); + ret = TRUE; } - ret = TRUE; - } - break; + break; - case GDK_BUTTON_PRESS: - if ( event->button.button == 1 && !this->space_panning ) { - Geom::Point button_w(event->button.x, event->button.y); + 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; + // save drag origin + this->xp = (gint)button_w[Geom::X]; + this->yp = (gint)button_w[Geom::Y]; + this->within_tolerance = true; - dragging = 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); - } + 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(); - } + 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; - } + 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); + ret = TRUE; } + break; - gobble_motion_events(GDK_BUTTON1_MASK); - - ret = TRUE; - } else { - if (!drag->mouseOver() && !selection->isEmpty()) { - SnapManager &m = desktop->namedview->snap_manager; - m.setup(desktop); + 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); - m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE)); - m.unSetup(); - } - - bool over_line = false; - - if (!drag->lines.empty()) { - for (auto line : drag->lines) { - over_line |= sp_gradient_context_is_over_line (this, (SPItem*) line, Geom::Point(event->motion.x, event->motion.y)); + 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); } - } - 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; + gobble_motion_events(GDK_BUTTON1_MASK); - case GDK_BUTTON_RELEASE: - this->xp = this->yp = 0; + ret = TRUE; + } else { + if (!drag->mouseOver() && !selection->isEmpty()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); - if ( event->button.button == 1 && !this->space_panning ) { - bool over_line = false; - SPCtrlLine *line = nullptr; + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point const motion_dt = this->desktop->w2d(motion_w); - if (!drag->lines.empty()) { - for (std::vector<SPCtrlLine *>::const_iterator l = drag->lines.begin(); l != drag->lines.end() && (!over_line); ++l) { - line = *l; - over_line = sp_gradient_context_is_over_line (this, (SPItem*) line, Geom::Point(event->motion.x, event->motion.y)); + m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE)); + m.unSetup(); } - } - 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; + bool over_line = false; + + if (!drag->lines.empty()) { + for (auto line : drag->lines) { + over_line |= sp_gradient_context_is_over_line(this, (SPItem *)line, + Geom::Point(event->motion.x, event->motion.y)); + } } - } else { - dragging = false; - // unless clicked with Ctrl (to enable Ctrl+doubleclick). - if (event->button.state & GDK_CONTROL_MASK) { - ret = TRUE; - break; + 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; - 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); + case GDK_BUTTON_RELEASE: + this->xp = this->yp = 0; - 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); - } + if (event->button.button == 1 && !this->space_panning) { + bool over_line = false; + SPCtrlLine *line = nullptr; + + if (!drag->lines.empty()) { + for (std::vector<SPCtrlLine *>::const_iterator l = drag->lines.begin(); + l != drag->lines.end() && (!over_line); ++l) { + line = *l; + over_line = sp_gradient_context_is_over_line(this, (SPItem *)line, + Geom::Point(event->motion.x, event->motion.y)); } - } else if (this->item_to_select) { + } + + if ((event->button.state & GDK_CONTROL_MASK) && (event->button.state & GDK_MOD1_MASK)) { if (over_line && line) { - // Clicked on an existing gradient 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 { - drag->deselectAll(); - selection->set(this->item_to_select); - } + sp_gradient_context_add_stop_near_point(this, line->item, this->mousepoint_doc, 0); + ret = TRUE; } } else { - // click in an empty space; do the same as Esc - if (!drag->selected.empty()) { - drag->deselectAll(); + 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, 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 { + drag->deselectAll(); + selection->set(this->item_to_select); + } + } } else { - selection->clear(); + // click in an empty space; do the same as Esc + if (!drag->selected.empty()) { + drag->deselectAll(); + } else { + selection->clear(); + } } + + this->item_to_select = nullptr; + ret = TRUE; } - this->item_to_select = nullptr; - ret = TRUE; + Inkscape::Rubberband::get(desktop)->stop(); } - - Inkscape::Rubberband::get(desktop)->stop(); - } - break; - - case GDK_KEY_PRESS: - switch (get_latin_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"), - nullptr); break; - case GDK_KEY_x: - case GDK_KEY_X: - if (MOD__ALT_ONLY(event)) { - desktop->setToolboxFocusTo ("altx-grad"); - ret = TRUE; - } - break; + case GDK_KEY_PRESS: + switch (get_latin_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"), nullptr); + break; - case GDK_KEY_A: - case GDK_KEY_a: - if (MOD__CTRL_ONLY(event) && drag->isNonEmpty()) { - drag->selectAll(); - ret = TRUE; - } - break; + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo("altx-grad"); + 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_A: + case GDK_KEY_a: + if (MOD__CTRL_ONLY(event) && drag->isNonEmpty()) { + drag->selectAll(); + ret = TRUE; + } + break; - case GDK_KEY_Escape: - if (!drag->selected.empty()) { - drag->deselectAll(); - } else { - Inkscape::SelectionHelper::selectNone(desktop); - } - ret = TRUE; - //TODO: make dragging escapable by Esc - 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_r: - case GDK_KEY_R: - if (MOD__SHIFT_ONLY(event)) { - sp_gradient_reverse_selected_gradients(desktop); - ret = TRUE; - } - break; + case GDK_KEY_Escape: + if (!drag->selected.empty()) { + drag->deselectAll(); + } else { + Inkscape::SelectionHelper::selectNone(desktop); + } + ret = TRUE; + // TODO: make dragging escapable by Esc + 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_r: + case GDK_KEY_R: + if (MOD__SHIFT_ONLY(event)) { + sp_gradient_reverse_selected_gradients(desktop); + ret = TRUE; + } + break; - case GDK_KEY_i: - case GDK_KEY_I: - if (MOD__SHIFT_ONLY(event)) { - // Shift+I - insert stops (alternate keybinding for keyboards - // that don't have the Insert key) - sp_gradient_context_add_stops_between_selected_stops (this); - ret = TRUE; + 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_i: + case GDK_KEY_I: + if (MOD__SHIFT_ONLY(event)) { + // Shift+I - insert stops (alternate keybinding for keyboards + // that don't have the Insert key) + 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: + ret = drag->key_press_handler(event); + break; } break; - case GDK_KEY_Delete: - case GDK_KEY_KP_Delete: - case GDK_KEY_BackSpace: - ret = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); - break; + case GDK_KEY_RELEASE: + switch (get_latin_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: - ret = drag->key_press_handler(event); - break; - } - break; - - case GDK_KEY_RELEASE: - switch (get_latin_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(); + default: + break; + } break; default: break; - } - break; - - default: - break; } if (!ret) { - ret = ToolBase::root_handler(event); + ret = ToolBase::root_handler(event); } return ret; @@ -784,7 +779,8 @@ static void sp_gradient_drag(GradientTool &rc, Geom::Point const pt, guint /*sta 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; + Inkscape::PaintTarget fill_or_stroke = + (prefs->getInt("/tools/gradient/newfillorstroke", 1) != 0) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; SPGradient *vector; if (rc.item_to_select) { @@ -793,8 +789,8 @@ static void sp_gradient_drag(GradientTool &rc, Geom::Point const pt, guint /*sta } else { // Starting from empty space: // Sort items so that the topmost comes last - std::vector<SPItem*> items(selection->items().begin(), selection->items().end()); - sort(items.begin(),items.end(),sp_item_repr_compare_position_bool); + std::vector<SPItem *> items(selection->items().begin(), selection->items().end()); + sort(items.begin(), items.end(), sp_item_repr_compare_position_bool); // take topmost vector = sp_gradient_vector_for_object(document, desktop, SP_ITEM(items.back()), fill_or_stroke); } @@ -804,19 +800,18 @@ static void sp_gradient_drag(GradientTool &rc, Geom::Point const pt, guint /*sta sp_repr_css_set_property(css, "fill-opacity", "1.0"); auto itemlist = selection->items(); - for (auto i = itemlist.begin();i!=itemlist.end();++i) { - - //FIXME: see above + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { + // FIXME: see above sp_repr_css_change_recursive((*i)->getRepr(), css, "style"); - sp_item_set_gradient(*i, vector, (SPGradientType) type, fill_or_stroke); + sp_item_set_gradient(*i, vector, (SPGradientType)type, fill_or_stroke); if (type == SP_GRADIENT_TYPE_LINEAR) { - sp_item_gradient_set_coords (*i, POINT_LG_BEGIN, 0, rc.origin, fill_or_stroke, true, false); - sp_item_gradient_set_coords (*i, POINT_LG_END, 0, pt, fill_or_stroke, true, false); + sp_item_gradient_set_coords(*i, POINT_LG_BEGIN, 0, rc.origin, fill_or_stroke, true, false); + sp_item_gradient_set_coords(*i, POINT_LG_END, 0, pt, fill_or_stroke, true, false); } else if (type == SP_GRADIENT_TYPE_RADIAL) { - sp_item_gradient_set_coords (*i, POINT_RG_CENTER, 0, rc.origin, fill_or_stroke, true, false); - sp_item_gradient_set_coords (*i, POINT_RG_R1, 0, pt, fill_or_stroke, true, false); + sp_item_gradient_set_coords(*i, POINT_RG_CENTER, 0, rc.origin, fill_or_stroke, true, false); + sp_item_gradient_set_coords(*i, POINT_RG_R1, 0, pt, fill_or_stroke, true, false); } (*i)->requestModified(SP_OBJECT_MODIFIED_FLAG); } @@ -827,29 +822,29 @@ static void sp_gradient_drag(GradientTool &rc, Geom::Point const pt, guint /*sta rc._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 - rc._grdrag->grabKnot (selection->items().front(), - 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); + rc._grdrag->grabKnot(selection->items().front(), + 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 = (int) boost::distance(selection->items()); + int n_objects = (int)boost::distance(selection->items()); 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); + 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 { - desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>objects</b> on which to create gradient.")); + desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>objects</b> on which to create gradient.")); } } -} -} -} - +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/gradient-tool.h b/src/ui/tools/gradient-tool.h index 5c94aeb028ecd578218235dc08837b5610bcfd28..2ca3d521e2d89cb51d8254bec38d1fdf6d4c310c 100644 --- a/src/ui/tools/gradient-tool.h +++ b/src/ui/tools/gradient-tool.h @@ -18,10 +18,13 @@ #include <cstddef> #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) +#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 { @@ -30,10 +33,11 @@ class Selection; namespace UI { namespace Tools { -class GradientTool : public ToolBase { +class GradientTool : public ToolBase +{ public: - GradientTool(); - ~GradientTool() override; + GradientTool(); + ~GradientTool() override; Geom::Point origin; @@ -46,28 +50,27 @@ public: sigc::connection *selcon; sigc::connection *subselcon; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - bool root_handler(GdkEvent* event) override; + void setup() override; + bool root_handler(GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; private: - void selection_changed(Inkscape::Selection*); + 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); +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); -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif - /* Local Variables: mode:c++ diff --git a/src/ui/tools/lpe-tool.cpp b/src/ui/tools/lpe-tool.cpp index e97bf45b6219164cd32c1c48d2fc8b678eb2f2d8..015b82570358261cbd9483454e1047fcd4714857 100644 --- a/src/ui/tools/lpe-tool.cpp +++ b/src/ui/tools/lpe-tool.cpp @@ -15,33 +15,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/i18n.h> -#include <gtk/gtk.h> +#include "ui/tools/lpe-tool.h" #include <2geom/sbasis-geometric.h> +#include <glibmm/i18n.h> +#include <gtk/gtk.h> #include "desktop.h" +#include "display/canvas-bpath.h" +#include "display/canvas-text.h" +#include "display/curve.h" #include "document.h" #include "message-context.h" #include "message-stack.h" -#include "selection.h" - -#include "display/curve.h" -#include "display/canvas-bpath.h" -#include "display/canvas-text.h" - #include "object/sp-path.h" - +#include "selection.h" #include "ui/pixmaps/cursor-crosshairs.xpm" - -#include "util/units.h" - -#include "ui/toolbar/lpe-toolbar.h" -#include "ui/tools/lpe-tool.h" #include "ui/shape-editor.h" +#include "ui/toolbar/lpe-toolbar.h" +#include "util/units.h" -using Inkscape::Util::unit_table; using Inkscape::UI::Tools::PenTool; +using Inkscape::Util::unit_table; const int num_subtools = 8; @@ -54,8 +49,7 @@ SubtoolEntry lpesubtools[] = { {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"} -}; + {Inkscape::LivePathEffect::MIRROR_SYMMETRY, "draw-geometry-mirror"}}; namespace Inkscape { namespace UI { @@ -63,8 +57,9 @@ namespace Tools { void sp_lpetool_context_selection_changed(Inkscape::Selection *selection, gpointer data); -const std::string& LpeTool::getPrefsPath() { - return LpeTool::prefsPath; +const std::string &LpeTool::getPrefsPath() +{ + return LpeTool::prefsPath; } const std::string LpeTool::prefsPath = "/tools/lpetool"; @@ -74,12 +69,12 @@ LpeTool::LpeTool() , shape_editor(nullptr) , canvas_bbox(nullptr) , mode(Inkscape::LivePathEffect::BEND_PATH) -// TODO: pointer? - , measuring_items(new std::map<SPPath *, SPCanvasItem*>) -{ -} + // TODO: pointer? + , measuring_items(new std::map<SPPath *, SPCanvasItem *>) +{} -LpeTool::~LpeTool() { +LpeTool::~LpeTool() +{ delete this->shape_editor; this->shape_editor = nullptr; @@ -95,7 +90,8 @@ LpeTool::~LpeTool() { this->sel_changed_connection.disconnect(); } -void LpeTool::setup() { +void LpeTool::setup() +{ PenTool::setup(); Inkscape::Selection *selection = this->desktop->getSelection(); @@ -111,9 +107,9 @@ void LpeTool::setup() { lpetool_context_reset_limiting_bbox(this); lpetool_create_measuring_items(this); -// TODO temp force: + // TODO temp force: this->enableSelectionCue(); - + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (item) { @@ -138,21 +134,22 @@ void sp_lpetool_context_selection_changed(Inkscape::Selection *selection, gpoint lc->shape_editor->set_item(item); } -void LpeTool::set(const Inkscape::Preferences::Entry& val) { +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) { +bool LpeTool::item_handler(SPItem *item, GdkEvent *event) +{ gint ret = FALSE; switch (event->type) { - case GDK_BUTTON_PRESS: - { + case GDK_BUTTON_PRESS: { // select the clicked item but do nothing else - Inkscape::Selection * const selection = this->desktop->getSelection(); + Inkscape::Selection *const selection = this->desktop->getSelection(); selection->clear(); selection->add(item); ret = TRUE; @@ -167,21 +164,22 @@ bool LpeTool::item_handler(SPItem* item, GdkEvent* event) { } if (!ret) { - ret = PenTool::item_handler(item, event); + ret = PenTool::item_handler(item, event); } return ret; } -bool LpeTool::root_handler(GdkEvent* event) { +bool LpeTool::root_handler(GdkEvent *event) +{ Inkscape::Selection *selection = desktop->getSelection(); 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); + // ret = ((ToolBaseClass *) sp_lpetool_context_parent_class)->root_handler(event_context, event); + return PenTool::root_handler(event); } switch (event->type) { @@ -191,14 +189,15 @@ bool LpeTool::root_handler(GdkEvent* event) { // 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.")); + 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->xp = (gint)event->button.x; + this->yp = (gint)event->button.y; this->within_tolerance = true; using namespace Inkscape::LivePathEffect; @@ -207,49 +206,48 @@ bool LpeTool::root_handler(GdkEvent* event) { 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); + // 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); + // 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_latin_keyval (&event->key)) { - } - break; - **/ - - case GDK_KEY_RELEASE: - /** - switch (get_latin_keyval(&event->key)) { - case GDK_Control_L: - case GDK_Control_R: - dc->_message_context->clear(); - break; - default: - break; + case GDK_BUTTON_RELEASE: { + /** + break; + **/ } - **/ - default: - break; + case GDK_KEY_PRESS: + /** + switch (get_latin_keyval (&event->key)) { + } + break; + **/ + + case GDK_KEY_RELEASE: + /** + switch (get_latin_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); + ret = PenTool::root_handler(event); } return ret; @@ -259,8 +257,8 @@ bool LpeTool::root_handler(GdkEvent* event) { * 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) { +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; @@ -273,13 +271,13 @@ lpetool_mode_to_index(Inkscape::LivePathEffect::EffectType const type) { * 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) +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(); + Inkscape::LivePathEffect::Effect *lpe = SP_LPE_ITEM(item)->getCurrentLPE(); if (!lpe) { return -1; } @@ -290,8 +288,7 @@ int lpetool_item_has_construction(LpeTool */*lc*/, SPItem *item) * 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) +bool lpetool_try_construction(LpeTool *lc, Inkscape::LivePathEffect::EffectType const type) { Inkscape::Selection *selection = lc->getDesktop()->getSelection(); SPItem *item = selection->singleItem(); @@ -304,27 +301,26 @@ lpetool_try_construction(LpeTool *lc, Inkscape::LivePathEffect::EffectType const return false; } -void -lpetool_context_switch_mode(LpeTool *lc, Inkscape::LivePathEffect::EffectType const type) +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; - auto tb = dynamic_cast<UI::Toolbar::LPEToolbar*>(lc->getDesktop()->get_toolbar_by_name("LPEToolToolbar")); + auto tb = dynamic_cast<UI::Toolbar::LPEToolbar *>(lc->getDesktop()->get_toolbar_by_name("LPEToolToolbar")); - if(tb) { + if (tb) { tb->set_mode(index); } else { std::cerr << "Could not access LPE toolbar" << std::endl; } } else { - g_warning ("Invalid mode selected: %d", type); + g_warning("Invalid mode selected: %d", type); return; } } -void -lpetool_get_limiting_bbox_corners(SPDocument *document, Geom::Point &A, Geom::Point &B) { +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(); @@ -342,8 +338,7 @@ lpetool_get_limiting_bbox_corners(SPDocument *document, Geom::Point &A, Geom::Po * 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) +void lpetool_context_reset_limiting_bbox(LpeTool *lc) { if (lc->canvas_bbox) { sp_canvas_item_destroy(lc->canvas_bbox); @@ -366,51 +361,50 @@ lpetool_context_reset_limiting_bbox(LpeTool *lc) auto curve = SPCurve::new_from_rect(rect); lc->canvas_bbox = sp_canvas_bpath_new(lc->getDesktop()->getControls(), curve.get()); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(lc->canvas_bbox), 0x0000ffff, 0.8, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 5); + 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) +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); + 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)); + 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) +void lpetool_create_measuring_items(LpeTool *lc, Inkscape::Selection *selection) { if (!selection) { selection = lc->getDesktop()->getSelection(); } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool show = prefs->getBool("/tools/lpetool/show_measuring_info", true); + bool show = prefs->getBool("/tools/lpetool/show_measuring_info", true); SPPath *path; SPCanvasText *canvas_text; SPCanvasGroup *tmpgrp = lc->getDesktop()->getTempGroup(); gchar *arc_length; double lengthval; - auto items= selection->items(); - for(auto i=items.begin();i!=items.end();++i){ + auto items = selection->items(); + for (auto i = items.begin(); i != items.end(); ++i) { if (SP_IS_PATH(*i)) { path = SP_PATH(*i); SPCurve const *curve = path->curve(); - Geom::Piecewise<Geom::D2<Geom::SBasis> > pwd2 = paths_to_pw(curve->get_pathvector()); - canvas_text = (SPCanvasText *) sp_canvastext_new(tmpgrp, lc->getDesktop(), Geom::Point(0,0), ""); + Geom::Piecewise<Geom::D2<Geom::SBasis>> pwd2 = paths_to_pw(curve->get_pathvector()); + canvas_text = (SPCanvasText *)sp_canvastext_new(tmpgrp, lc->getDesktop(), Geom::Point(0, 0), ""); if (!show) sp_canvas_item_hide(SP_CANVAS_ITEM(canvas_text)); - Inkscape::Util::Unit const * unit = nullptr; + Inkscape::Util::Unit const *unit = nullptr; if (prefs->getString("/tools/lpetool/unit").compare("")) { unit = unit_table.getUnit(prefs->getString("/tools/lpetool/unit")); } else { @@ -420,7 +414,7 @@ lpetool_create_measuring_items(LpeTool *lc, Inkscape::Selection *selection) 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); + 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); @@ -428,28 +422,24 @@ lpetool_create_measuring_items(LpeTool *lc, Inkscape::Selection *selection) } } -void -lpetool_delete_measuring_items(LpeTool *lc) +void lpetool_delete_measuring_items(LpeTool *lc) { - std::map<SPPath *, SPCanvasItem*>::iterator i; + 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) +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 ) - { + for (std::map<SPPath *, SPCanvasItem *>::iterator i = lc->measuring_items->begin(); i != lc->measuring_items->end(); + ++i) { SPPath *path = i->first; SPCurve const *curve = path->curve(); - Geom::Piecewise<Geom::D2<Geom::SBasis> > pwd2 = Geom::paths_to_pw(curve->get_pathvector()); - Inkscape::Util::Unit const * unit = nullptr; + Geom::Piecewise<Geom::D2<Geom::SBasis>> pwd2 = Geom::paths_to_pw(curve->get_pathvector()); + Inkscape::Util::Unit const *unit = nullptr; if (prefs->getString("/tools/lpetool/unit").compare("")) { unit = unit_table.getUnit(prefs->getString("/tools/lpetool/unit")); } else { @@ -458,16 +448,15 @@ lpetool_update_measuring_items(LpeTool *lc) 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); + 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) +void lpetool_show_measuring_info(LpeTool *lc, bool show) { - std::map<SPPath *, SPCanvasItem*>::iterator i; + 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); @@ -477,9 +466,9 @@ lpetool_show_measuring_info(LpeTool *lc, bool show) } } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/lpe-tool.h b/src/ui/tools/lpe-tool.h index 789aaf3cd7b49d5dd11d6d601a9e63a37707d8af..cab6be1ebc5d0b2f5b781bf686c7e8fc29e647ec 100644 --- a/src/ui/tools/lpe-tool.h +++ b/src/ui/tools/lpe-tool.h @@ -18,20 +18,23 @@ #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) +#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 { +struct SubtoolEntry +{ Inkscape::LivePathEffect::EffectType type; gchar const *icon_name; }; extern SubtoolEntry lpesubtools[]; -enum LPEToolState { +enum LPEToolState +{ LPETOOL_STATE_PEN, LPETOOL_STATE_NODE }; @@ -46,29 +49,30 @@ namespace Inkscape { namespace UI { namespace Tools { -class LpeTool : public PenTool { +class LpeTool : public PenTool +{ public: - LpeTool(); - ~LpeTool() override; + LpeTool(); + ~LpeTool() override; - ShapeEditor* shape_editor; + ShapeEditor *shape_editor; SPCanvasItem *canvas_bbox; Inkscape::LivePathEffect::EffectType mode; - std::map<SPPath *, SPCanvasItem*> *measuring_items; + std::map<SPPath *, SPCanvasItem *> *measuring_items; sigc::connection sel_changed_connection; sigc::connection sel_modified_connection; - static const std::string prefsPath; + static const std::string prefsPath; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; protected: - void setup() override; - void set(const Inkscape::Preferences::Entry& val) override; - bool root_handler(GdkEvent* event) override; - bool item_handler(SPItem* item, GdkEvent* event) override; + void setup() override; + void set(const Inkscape::Preferences::Entry &val) override; + bool root_handler(GdkEvent *event) override; + bool item_handler(SPItem *item, GdkEvent *event) override; }; int lpetool_mode_to_index(Inkscape::LivePathEffect::EffectType const type); @@ -82,9 +86,9 @@ void lpetool_delete_measuring_items(LpeTool *lc); void lpetool_update_measuring_items(LpeTool *lc); void lpetool_show_measuring_info(LpeTool *lc, bool show = true); -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif // SP_LPETOOL_CONTEXT_H_SEEN diff --git a/src/ui/tools/measure-tool.cpp b/src/ui/tools/measure-tool.cpp index 6ba928cca1c41fc6253b608d688ee44978f677de..e6bf2041c0167235b7ad7883459f02e6b98ba068 100644 --- a/src/ui/tools/measure-tool.cpp +++ b/src/ui/tools/measure-tool.cpp @@ -12,63 +12,55 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm.h> -#include <glibmm/i18n.h> - -#include <boost/none_t.hpp> +#include "ui/tools/measure-tool.h" #include <2geom/line.h> #include <2geom/path-intersection.h> +#include <boost/none_t.hpp> +#include <glibmm/i18n.h> +#include <gtkmm.h> #include "desktop-style.h" #include "desktop.h" -#include "document-undo.h" -#include "inkscape.h" -#include "path-chemistry.h" -#include "rubberband.h" -#include "text-editing.h" -#include "verbs.h" - #include "display/curve.h" #include "display/sodipodi-ctrl.h" #include "display/sp-canvas-util.h" #include "display/sp-ctrlcurve.h" #include "display/sp-ctrlline.h" - +#include "document-undo.h" +#include "inkscape.h" #include "object/sp-defs.h" #include "object/sp-flowtext.h" #include "object/sp-namedview.h" #include "object/sp-root.h" #include "object/sp-shape.h" #include "object/sp-text.h" - -#include "ui/pixmaps/cursor-measure.xpm" - +#include "path-chemistry.h" +#include "rubberband.h" #include "svg/stringstream.h" #include "svg/svg-color.h" #include "svg/svg.h" - +#include "text-editing.h" #include "ui/dialog/knot-properties.h" +#include "ui/pixmaps/cursor-measure.xpm" #include "ui/tools/freehand-base.h" -#include "ui/tools/measure-tool.h" #include "ui/widget/canvas.h" // Canvas area - #include "util/units.h" +#include "verbs.h" using Inkscape::ControlManager; using Inkscape::CTLINE_SECONDARY; -using Inkscape::Util::unit_table; using Inkscape::DocumentUndo; +using Inkscape::Util::unit_table; #define MT_KNOT_COLOR_NORMAL 0xffffff00 #define MT_KNOT_COLOR_MOUSEOVER 0xff000000 - namespace Inkscape { namespace UI { namespace Tools { -const std::string& MeasureTool::getPrefsPath() +const std::string &MeasureTool::getPrefsPath() { return MeasureTool::prefsPath; } @@ -80,9 +72,9 @@ namespace { /** * Simple class to use for removing label overlap. */ -class LabelPlacement { +class LabelPlacement +{ public: - double lengthVal; double offset; Geom::Point start; @@ -98,9 +90,10 @@ bool SortLabelPlacement(LabelPlacement const &first, LabelPlacement const &secon } } -//precision is for give the number of decimal positions -//of the label to calculate label width -void repositionOverlappingLabels(std::vector<LabelPlacement> &placements, SPDesktop *desktop, Geom::Point const &normal, double fontsize, int precision) +// precision is for give the number of decimal positions +// of the label to calculate label width +void repositionOverlappingLabels(std::vector<LabelPlacement> &placements, SPDesktop *desktop, Geom::Point const &normal, + double fontsize, int precision) { std::sort(placements.begin(), placements.end(), SortLabelPlacement); @@ -151,9 +144,8 @@ void repositionOverlappingLabels(std::vector<LabelPlacement> &placements, SPDesk * @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) +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(); @@ -184,10 +176,11 @@ Geom::Point calcAngleDisplayAnchor(SPDesktop *desktop, double angle, double base * @param color of the stroke. * @param measure_repr container element. */ -void setMeasureItem(Geom::PathVector pathv, bool is_curve, bool markers, guint32 color, Inkscape::XML::Node *measure_repr) +void setMeasureItem(Geom::PathVector pathv, bool is_curve, bool markers, guint32 color, + Inkscape::XML::Node *measure_repr) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if(!desktop) { + if (!desktop) { return; } SPDocument *doc = desktop->getDocument(); @@ -199,42 +192,42 @@ void setMeasureItem(Geom::PathVector pathv, bool is_curve, bool markers, guint32 Geom::Coord strokewidth = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse().expansionX(); std::stringstream stroke_width; stroke_width.imbue(std::locale::classic()); - if(measure_repr) { - stroke_width << strokewidth / desktop->current_zoom(); + if (measure_repr) { + stroke_width << strokewidth / desktop->current_zoom(); } else { - stroke_width << strokewidth; + stroke_width << strokewidth; } - sp_repr_css_set_property (css, "stroke-width", stroke_width.str().c_str()); - sp_repr_css_set_property (css, "fill", "none"); - if(color) { + sp_repr_css_set_property(css, "stroke-width", stroke_width.str().c_str()); + sp_repr_css_set_property(css, "fill", "none"); + if (color) { gchar color_line[64]; - sp_svg_write_color (color_line, sizeof(color_line), color); - sp_repr_css_set_property (css, "stroke", color_line); + sp_svg_write_color(color_line, sizeof(color_line), color); + sp_repr_css_set_property(css, "stroke", color_line); } else { - sp_repr_css_set_property (css, "stroke", "#ff0000"); - } - char const * stroke_linecap = is_curve ? "butt" : "square"; - sp_repr_css_set_property (css, "stroke-linecap", stroke_linecap); - sp_repr_css_set_property (css, "stroke-linejoin", "miter"); - sp_repr_css_set_property (css, "stroke-miterlimit", "4"); - sp_repr_css_set_property (css, "stroke-dasharray", "none"); - if(measure_repr) { - sp_repr_css_set_property (css, "stroke-opacity", "0.5"); + sp_repr_css_set_property(css, "stroke", "#ff0000"); + } + char const *stroke_linecap = is_curve ? "butt" : "square"; + sp_repr_css_set_property(css, "stroke-linecap", stroke_linecap); + sp_repr_css_set_property(css, "stroke-linejoin", "miter"); + sp_repr_css_set_property(css, "stroke-miterlimit", "4"); + sp_repr_css_set_property(css, "stroke-dasharray", "none"); + if (measure_repr) { + sp_repr_css_set_property(css, "stroke-opacity", "0.5"); } else { - sp_repr_css_set_property (css, "stroke-opacity", "1"); + sp_repr_css_set_property(css, "stroke-opacity", "1"); } - if(markers) { - sp_repr_css_set_property (css, "marker-start", "url(#Arrow2Sstart)"); - sp_repr_css_set_property (css, "marker-end", "url(#Arrow2Send)"); + if (markers) { + sp_repr_css_set_property(css, "marker-start", "url(#Arrow2Sstart)"); + sp_repr_css_set_property(css, "marker-end", "url(#Arrow2Send)"); } Glib::ustring css_str; - sp_repr_css_write_string(css,css_str); + sp_repr_css_write_string(css, css_str); repr->setAttribute("style", css_str); - sp_repr_css_attr_unref (css); - g_assert( str != nullptr ); + sp_repr_css_attr_unref(css); + g_assert(str != nullptr); repr->setAttribute("d", str); g_free(str); - if(measure_repr) { + if (measure_repr) { measure_repr->addChild(repr, nullptr); Inkscape::GC::release(repr); } else { @@ -256,7 +249,11 @@ void setMeasureItem(Geom::PathVector pathv, bool is_curve, bool markers, guint32 * @param angle the angle of the arc segment to draw. * @param measure_rpr the container of the curve if converted to items. */ -void createAngleDisplayCurve(SPDesktop *desktop, Geom::Point const ¢er, Geom::Point const &end, Geom::Point const &anchor, double angle, bool to_phantom, std::vector<SPCanvasItem *> &measure_phantom_items , std::vector<SPCanvasItem *> &measure_tmp_items , Inkscape::XML::Node *measure_repr = nullptr) +void createAngleDisplayCurve(SPDesktop *desktop, Geom::Point const ¢er, Geom::Point const &end, + Geom::Point const &anchor, double angle, bool to_phantom, + std::vector<SPCanvasItem *> &measure_phantom_items, + std::vector<SPCanvasItem *> &measure_tmp_items, + Inkscape::XML::Node *measure_repr = nullptr) { // Given that we have a point on the arc's edge and the angle of the arc, we need to get the two endpoints. @@ -266,14 +263,12 @@ void createAngleDisplayCurve(SPDesktop *desktop, Geom::Point const ¢er, Geom 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))); + 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))); + 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]; @@ -287,12 +282,11 @@ void createAngleDisplayCurve(SPDesktop *desktop, Geom::Point const ¢er, Geom 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(desktop->getTempGroup(), p1, p2, p3, p4, CTLINE_SECONDARY); - if(to_phantom){ + 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(desktop->getTempGroup(), p1, p2, p3, p4, CTLINE_SECONDARY); + if (to_phantom) { curve->rgba = 0x8888887f; measure_phantom_items.push_back(SP_CANVAS_ITEM(curve)); } else { @@ -300,21 +294,21 @@ void createAngleDisplayCurve(SPDesktop *desktop, Geom::Point const ¢er, Geom } sp_canvas_item_move_to_z(SP_CANVAS_ITEM(curve), 0); sp_canvas_item_show(SP_CANVAS_ITEM(curve)); - if(measure_repr) { + if (measure_repr) { Geom::PathVector pathv; Geom::Path path; path.start(desktop->doc2dt(p1)); - path.appendNew<Geom::CubicBezier>(desktop->doc2dt(p2),desktop->doc2dt(p3),desktop->doc2dt(p4)); + path.appendNew<Geom::CubicBezier>(desktop->doc2dt(p2), desktop->doc2dt(p3), desktop->doc2dt(p4)); pathv.push_back(path); pathv *= SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); - if(!pathv.empty()) { + if (!pathv.empty()) { setMeasureItem(pathv, true, false, 0xff00007f, measure_repr); } } } } -} // namespace +} // namespace boost::optional<Geom::Point> explicit_base_tmp = boost::none; @@ -326,17 +320,19 @@ MeasureTool::MeasureTool() start_p = readMeasurePoint(true); end_p = readMeasurePoint(false); dimension_offset = 35; - last_pos = Geom::Point(0,0); + last_pos = Geom::Point(0, 0); // create the knots this->knot_start = new SPKnot(desktop, _("Measure start, <b>Shift+Click</b> for position dialog")); this->knot_start->setMode(SP_KNOT_MODE_XOR); - this->knot_start->setFill(MT_KNOT_COLOR_NORMAL, MT_KNOT_COLOR_MOUSEOVER, MT_KNOT_COLOR_MOUSEOVER, MT_KNOT_COLOR_MOUSEOVER); + this->knot_start->setFill(MT_KNOT_COLOR_NORMAL, MT_KNOT_COLOR_MOUSEOVER, MT_KNOT_COLOR_MOUSEOVER, + MT_KNOT_COLOR_MOUSEOVER); this->knot_start->setStroke(0x0000007f, 0x0000007f, 0x0000007f, 0x0000007f); this->knot_start->setShape(SP_KNOT_SHAPE_CIRCLE); this->knot_start->updateCtrl(); this->knot_end = new SPKnot(desktop, _("Measure end, <b>Shift+Click</b> for position dialog")); this->knot_end->setMode(SP_KNOT_MODE_XOR); - this->knot_end->setFill(MT_KNOT_COLOR_NORMAL, MT_KNOT_COLOR_MOUSEOVER, MT_KNOT_COLOR_MOUSEOVER, MT_KNOT_COLOR_MOUSEOVER); + this->knot_end->setFill(MT_KNOT_COLOR_NORMAL, MT_KNOT_COLOR_MOUSEOVER, MT_KNOT_COLOR_MOUSEOVER, + MT_KNOT_COLOR_MOUSEOVER); this->knot_end->setStroke(0x0000007f, 0x0000007f, 0x0000007f, 0x0000007f); this->knot_end->setShape(SP_KNOT_SHAPE_CIRCLE); this->knot_end->updateCtrl(); @@ -349,18 +345,23 @@ MeasureTool::MeasureTool() this->knot_end->show(); showCanvasItems(); } else { - start_p = Geom::Point(0,0); - end_p = Geom::Point(0,0); + start_p = Geom::Point(0, 0); + end_p = Geom::Point(0, 0); writeMeasurePoint(start_p, true); writeMeasurePoint(end_p, false); } - this->_knot_start_moved_connection = this->knot_start->moved_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotStartMovedHandler)); - this->_knot_start_click_connection = this->knot_start->click_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotClickHandler)); - this->_knot_start_ungrabbed_connection = this->knot_start->ungrabbed_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotUngrabbedHandler)); - this->_knot_end_moved_connection = this->knot_end->moved_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotEndMovedHandler)); - this->_knot_end_click_connection = this->knot_end->click_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotClickHandler)); - this->_knot_end_ungrabbed_connection = this->knot_end->ungrabbed_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotUngrabbedHandler)); - + this->_knot_start_moved_connection = + this->knot_start->moved_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotStartMovedHandler)); + this->_knot_start_click_connection = + this->knot_start->click_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotClickHandler)); + this->_knot_start_ungrabbed_connection = + this->knot_start->ungrabbed_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotUngrabbedHandler)); + this->_knot_end_moved_connection = + this->knot_end->moved_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotEndMovedHandler)); + this->_knot_end_click_connection = + this->knot_end->click_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotClickHandler)); + this->_knot_end_ungrabbed_connection = + this->knot_end->ungrabbed_signal.connect(sigc::mem_fun(*this, &MeasureTool::knotUngrabbedHandler)); } MeasureTool::~MeasureTool() @@ -373,34 +374,36 @@ MeasureTool::~MeasureTool() /* unref should call destroy */ knot_unref(this->knot_start); knot_unref(this->knot_end); - for (auto & measure_tmp_item : measure_tmp_items) { + for (auto &measure_tmp_item : measure_tmp_items) { sp_canvas_item_destroy(measure_tmp_item); } measure_tmp_items.clear(); - for (auto & idx : measure_item) { + for (auto &idx : measure_item) { sp_canvas_item_destroy(idx); } measure_item.clear(); - for (auto & measure_phantom_item : measure_phantom_items) { + for (auto &measure_phantom_item : measure_phantom_items) { sp_canvas_item_destroy(measure_phantom_item); } measure_phantom_items.clear(); } -Geom::Point MeasureTool::readMeasurePoint(bool is_start) { +Geom::Point MeasureTool::readMeasurePoint(bool is_start) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring measure_point = is_start ? "/tools/measure/measure-start" : "/tools/measure/measure-end"; - return prefs->getPoint(measure_point, Geom::Point(Geom::infinity(),Geom::infinity())); + return prefs->getPoint(measure_point, Geom::Point(Geom::infinity(), Geom::infinity())); } -void MeasureTool::writeMeasurePoint(Geom::Point point, bool is_start) { +void MeasureTool::writeMeasurePoint(Geom::Point point, bool is_start) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring measure_point = is_start ? "/tools/measure/measure-start" : "/tools/measure/measure-end"; prefs->setPoint(measure_point, point); } -//This function is used to reverse the Measure, I do it in two steps because when -//we move the knot the start_ or the end_p are overwritten so I need the original values. +// This function is used to reverse the Measure, I do it in two steps because when +// we move the knot the start_ or the end_p are overwritten so I need the original values. void MeasureTool::reverseKnots() { Geom::Point start = start_p; @@ -419,13 +422,13 @@ void MeasureTool::knotClickHandler(SPKnot *knot, guint state) if (state & GDK_SHIFT_MASK) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - Glib::ustring const unit_name = prefs->getString("/tools/measure/unit"); + Glib::ustring const unit_name = prefs->getString("/tools/measure/unit"); explicit_base = explicit_base_tmp; Inkscape::UI::Dialogs::KnotPropertiesDialog::showDialog(desktop, knot, unit_name); } } -void MeasureTool::knotStartMovedHandler(SPKnot */*knot*/, Geom::Point const &ppointer, guint state) +void MeasureTool::knotStartMovedHandler(SPKnot * /*knot*/, Geom::Point const &ppointer, guint state) { Geom::Point point = this->knot_start->position(); if (state & GDK_CONTROL_MASK) { @@ -439,14 +442,14 @@ void MeasureTool::knotStartMovedHandler(SPKnot */*knot*/, Geom::Point const &ppo point = sp.getPoint(); snap_manager.unSetup(); } - if(start_p != point) { + if (start_p != point) { start_p = point; this->knot_start->moveto(start_p); } showCanvasItems(); } -void MeasureTool::knotEndMovedHandler(SPKnot */*knot*/, Geom::Point const &ppointer, guint state) +void MeasureTool::knotEndMovedHandler(SPKnot * /*knot*/, Geom::Point const &ppointer, guint state) { Geom::Point point = this->knot_end->position(); if (state & GDK_CONTROL_MASK) { @@ -460,22 +463,21 @@ void MeasureTool::knotEndMovedHandler(SPKnot */*knot*/, Geom::Point const &ppoin point = sp.getPoint(); snap_manager.unSetup(); } - if(end_p != point) { + if (end_p != point) { end_p = point; this->knot_end->moveto(end_p); } showCanvasItems(); } -void MeasureTool::knotUngrabbedHandler(SPKnot */*knot*/, unsigned int state) +void MeasureTool::knotUngrabbedHandler(SPKnot * /*knot*/, unsigned int state) { this->knot_start->moveto(start_p); this->knot_end->moveto(end_p); showCanvasItems(); } - -//todo: we need this function? +// todo: we need this function? void MeasureTool::finish() { this->enableGrDrag(false); @@ -500,13 +502,15 @@ static void calculate_intersections(SPDesktop * /*desktop*/, SPItem *item, Geom: Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool show_hidden = prefs->getBool("/tools/measure/show_hidden", true); SPDesktop *desktop = SP_ACTIVE_DESKTOP; - for (const auto & m : cs[0]) { + for (const auto &m : cs[0]) { if (!show_hidden) { double eps = 0.0001; if ((m.ta > eps && - item == desktop->getItemAtPoint(desktop->d2w(desktop->dt2doc(lineseg[0].pointAt(m.ta - eps))), true, nullptr)) || - (m.ta + eps < 1 && - item == desktop->getItemAtPoint(desktop->d2w(desktop->dt2doc(lineseg[0].pointAt(m.ta + eps))), true, nullptr))) { + item == desktop->getItemAtPoint(desktop->d2w(desktop->dt2doc(lineseg[0].pointAt(m.ta - eps))), true, + nullptr)) || + (m.ta + eps < 1 && + item == desktop->getItemAtPoint(desktop->d2w(desktop->dt2doc(lineseg[0].pointAt(m.ta + eps))), true, + nullptr))) { intersections.push_back(m.ta); } } else { @@ -515,100 +519,124 @@ static void calculate_intersections(SPDesktop * /*desktop*/, SPItem *item, Geom: } } -bool MeasureTool::root_handler(GdkEvent* event) +bool MeasureTool::root_handler(GdkEvent *event) { gint ret = FALSE; switch (event->type) { - case GDK_BUTTON_PRESS: { - this->knot_start->hide(); - this->knot_end->hide(); - Geom::Point const button_w(event->button.x, event->button.y); - explicit_base = boost::none; - explicit_base_tmp = boost::none; - last_end = boost::none; - - if (event->button.button == 1 && !this->space_panning) { - // save drag origin - start_p = desktop->w2d(Geom::Point(event->button.x, event->button.y)); - within_tolerance = true; - - ret = TRUE; - } - - SnapManager &snap_manager = desktop->namedview->snap_manager; - snap_manager.setup(desktop); - snap_manager.freeSnapReturnByRef(start_p, Inkscape::SNAPSOURCE_OTHER_HANDLE); - snap_manager.unSetup(); + case GDK_BUTTON_PRESS: { + this->knot_start->hide(); + this->knot_end->hide(); + Geom::Point const button_w(event->button.x, event->button.y); + explicit_base = boost::none; + explicit_base_tmp = boost::none; + last_end = boost::none; + + if (event->button.button == 1 && !this->space_panning) { + // save drag origin + start_p = desktop->w2d(Geom::Point(event->button.x, event->button.y)); + within_tolerance = 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, - nullptr, event->button.time); - this->grabbed = SP_CANVAS_ITEM(desktop->acetate); - break; - } - case GDK_KEY_PRESS: { - if ((event->key.keyval == GDK_KEY_Control_L) || (event->key.keyval == GDK_KEY_Control_R)) { - explicit_base_tmp = explicit_base; - explicit_base = end_p; - showInfoBox(last_pos, true); + SnapManager &snap_manager = desktop->namedview->snap_manager; + snap_manager.setup(desktop); + snap_manager.freeSnapReturnByRef(start_p, Inkscape::SNAPSOURCE_OTHER_HANDLE); + snap_manager.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, + nullptr, event->button.time); + this->grabbed = SP_CANVAS_ITEM(desktop->acetate); + break; } - break; - } - case GDK_KEY_RELEASE: { - if ((event->key.keyval == GDK_KEY_Control_L) || (event->key.keyval == GDK_KEY_Control_R)) { - showInfoBox(last_pos, false); + case GDK_KEY_PRESS: { + if ((event->key.keyval == GDK_KEY_Control_L) || (event->key.keyval == GDK_KEY_Control_R)) { + explicit_base_tmp = explicit_base; + explicit_base = end_p; + showInfoBox(last_pos, true); + } + break; } - break; - } - case GDK_MOTION_NOTIFY: { - if (!(event->motion.state & GDK_BUTTON1_MASK)) { - 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)); + case GDK_KEY_RELEASE: { + if ((event->key.keyval == GDK_KEY_Control_L) || (event->key.keyval == GDK_KEY_Control_R)) { + showInfoBox(last_pos, false); + } + break; + } + case GDK_MOTION_NOTIFY: { + if (!(event->motion.state & GDK_BUTTON1_MASK)) { + 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 &snap_manager = desktop->namedview->snap_manager; - snap_manager.setup(desktop); + SnapManager &snap_manager = desktop->namedview->snap_manager; + snap_manager.setup(desktop); - Inkscape::SnapCandidatePoint scp(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE); - scp.addOrigin(start_p); + Inkscape::SnapCandidatePoint scp(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE); + scp.addOrigin(start_p); - snap_manager.preSnap(scp); - snap_manager.unSetup(); - } - last_pos = Geom::Point(event->motion.x, event->motion.y); - if (event->motion.state & GDK_CONTROL_MASK) { - showInfoBox(last_pos, true); + snap_manager.preSnap(scp); + snap_manager.unSetup(); + } + last_pos = Geom::Point(event->motion.x, event->motion.y); + if (event->motion.state & GDK_CONTROL_MASK) { + showInfoBox(last_pos, true); + } else { + showInfoBox(last_pos, false); + } } else { - showInfoBox(last_pos, false); - } - } else { - SPDesktop *desktop = SP_ACTIVE_DESKTOP; - //Inkscape::Util::Unit const * unit = desktop->getNamedView()->getDisplayUnit(); - for (auto & idx : measure_item) { - sp_canvas_item_destroy(idx); - } - measure_item.clear(); - ret = TRUE; - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); - Geom::Point const motion_w(event->motion.x, event->motion.y); - if ( within_tolerance) { - if ( Geom::LInfty( motion_w - start_p ) < tolerance) { - return FALSE; // Do not drag if we're within tolerance from origin. + SPDesktop *desktop = SP_ACTIVE_DESKTOP; + // Inkscape::Util::Unit const * unit = desktop->getNamedView()->getDisplayUnit(); + for (auto &idx : measure_item) { + sp_canvas_item_destroy(idx); + } + measure_item.clear(); + ret = TRUE; + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + Geom::Point const motion_w(event->motion.x, event->motion.y); + if (within_tolerance) { + if (Geom::LInfty(motion_w - start_p) < 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) + within_tolerance = false; + if (event->motion.time == 0 || !last_end || Geom::LInfty(motion_w - *last_end) > (tolerance / 4.0)) { + Geom::Point const motion_dt(desktop->w2d(motion_w)); + end_p = motion_dt; + + if (event->motion.state & GDK_CONTROL_MASK) { + spdc_endpoint_snap_rotation(this, end_p, start_p, event->motion.state); + } else if (!(event->motion.state & GDK_SHIFT_MASK)) { + SnapManager &snap_manager = desktop->namedview->snap_manager; + snap_manager.setup(desktop); + Inkscape::SnapCandidatePoint scp(end_p, Inkscape::SNAPSOURCE_OTHER_HANDLE); + scp.addOrigin(start_p); + Inkscape::SnappedPoint sp = snap_manager.freeSnap(scp); + end_p = sp.getPoint(); + snap_manager.unSetup(); + } + showCanvasItems(); + last_end = motion_w; } + gobble_motion_events(GDK_BUTTON1_MASK); } - // 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(event->motion.time == 0 || !last_end || Geom::LInfty( motion_w - *last_end ) > (tolerance/4.0)) { - Geom::Point const motion_dt(desktop->w2d(motion_w)); - end_p = motion_dt; - - if (event->motion.state & GDK_CONTROL_MASK) { + break; + } + case GDK_BUTTON_RELEASE: { + this->knot_start->moveto(start_p); + this->knot_start->show(); + if (last_end) { + end_p = desktop->w2d(*last_end); + if (event->button.state & GDK_CONTROL_MASK) { spdc_endpoint_snap_rotation(this, end_p, start_p, event->motion.state); - } else if (!(event->motion.state & GDK_SHIFT_MASK)) { + } else if (!(event->button.state & GDK_SHIFT_MASK)) { SnapManager &snap_manager = desktop->namedview->snap_manager; snap_manager.setup(desktop); Inkscape::SnapCandidatePoint scp(end_p, Inkscape::SNAPSOURCE_OTHER_HANDLE); @@ -617,42 +645,19 @@ bool MeasureTool::root_handler(GdkEvent* event) end_p = sp.getPoint(); snap_manager.unSetup(); } - showCanvasItems(); - last_end = motion_w ; - } - gobble_motion_events(GDK_BUTTON1_MASK); - } - break; - } - case GDK_BUTTON_RELEASE: { - this->knot_start->moveto(start_p); - this->knot_start->show(); - if(last_end) { - end_p = desktop->w2d(*last_end); - if (event->button.state & GDK_CONTROL_MASK) { - spdc_endpoint_snap_rotation(this, end_p, start_p, event->motion.state); - } else if (!(event->button.state & GDK_SHIFT_MASK)) { - SnapManager &snap_manager = desktop->namedview->snap_manager; - snap_manager.setup(desktop); - Inkscape::SnapCandidatePoint scp(end_p, Inkscape::SNAPSOURCE_OTHER_HANDLE); - scp.addOrigin(start_p); - Inkscape::SnappedPoint sp = snap_manager.freeSnap(scp); - end_p = sp.getPoint(); - snap_manager.unSetup(); } - } - this->knot_end->moveto(end_p); - this->knot_end->show(); - showCanvasItems(); + this->knot_end->moveto(end_p); + this->knot_end->show(); + showCanvasItems(); - if (this->grabbed) { - sp_canvas_item_ungrab(this->grabbed); - this->grabbed = nullptr; + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed); + this->grabbed = nullptr; + } + break; } - break; - } - default: - break; + default: + break; } if (!ret) { ret = ToolBase::root_handler(event); @@ -670,7 +675,7 @@ void MeasureTool::setMarkers() if (!arrowStart) { setMarker(true); } - if(!arrowEnd) { + if (!arrowEnd) { setMarker(false); } } @@ -697,14 +702,15 @@ void MeasureTool::setMarker(bool isStart) rpath->setAttribute("d", "M 8.72,4.03 L -2.21,0.02 L 8.72,-4.00 C 6.97,-1.63 6.98,1.62 8.72,4.03 z"); rpath->setAttribute("id", isStart ? "Arrow2SstartPath" : "Arrow2SendPath"); SPCSSAttr *css = sp_repr_css_attr_new(); - sp_repr_css_set_property (css, "stroke", "none"); - sp_repr_css_set_property (css, "fill", "#000000"); - sp_repr_css_set_property (css, "fill-opacity", "1"); + sp_repr_css_set_property(css, "stroke", "none"); + sp_repr_css_set_property(css, "fill", "#000000"); + sp_repr_css_set_property(css, "fill-opacity", "1"); Glib::ustring css_str; - sp_repr_css_write_string(css,css_str); + sp_repr_css_write_string(css, css_str); rpath->setAttribute("style", css_str); - sp_repr_css_attr_unref (css); - rpath->setAttribute("transform", isStart ? "scale(0.3) translate(-2.3,0)" : "scale(0.3) rotate(180) translate(-2.3,0)"); + sp_repr_css_attr_unref(css); + rpath->setAttribute("transform", + isStart ? "scale(0.3) translate(-2.3,0)" : "scale(0.3) rotate(180) translate(-2.3,0)"); SPItem *path = SP_ITEM(marker->appendChildRepr(rpath)); Inkscape::GC::release(rpath); path->updateRepr(); @@ -713,90 +719,91 @@ void MeasureTool::setMarker(bool isStart) void MeasureTool::toGuides() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if(!desktop || !start_p.isFinite() || !end_p.isFinite() || start_p == end_p) { + if (!desktop || !start_p.isFinite() || !end_p.isFinite() || start_p == end_p) { return; } SPDocument *doc = desktop->getDocument(); Geom::Point start = desktop->doc2dt(start_p) * desktop->doc2dt(); Geom::Point end = desktop->doc2dt(end_p) * desktop->doc2dt(); - Geom::Ray ray(start,end); + Geom::Ray ray(start, end); SPNamedView *namedview = desktop->namedview; - if(!namedview) { + if (!namedview) { return; } - setGuide(start,ray.angle(), _("Measure")); - if(explicit_base) { + setGuide(start, ray.angle(), _("Measure")); + if (explicit_base) { explicit_base = *explicit_base * SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); ray.setPoints(start, *explicit_base); - if(ray.angle() != 0) { - setGuide(start,ray.angle(), _("Base")); + if (ray.angle() != 0) { + setGuide(start, ray.angle(), _("Base")); } } - setGuide(start,0,""); - setGuide(start,Geom::rad_from_deg(90),_("Start")); - setGuide(end,0,_("End")); - setGuide(end,Geom::rad_from_deg(90),""); + setGuide(start, 0, ""); + setGuide(start, Geom::rad_from_deg(90), _("Start")); + setGuide(end, 0, _("End")); + setGuide(end, Geom::rad_from_deg(90), ""); showCanvasItems(true); doc->ensureUpToDate(); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MEASURE,_("Add guides from measure tool")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MEASURE, _("Add guides from measure tool")); } void MeasureTool::toPhantom() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if(!desktop || !start_p.isFinite() || !end_p.isFinite() || start_p == end_p) { + if (!desktop || !start_p.isFinite() || !end_p.isFinite() || start_p == end_p) { return; } SPDocument *doc = desktop->getDocument(); - for (auto & measure_phantom_item : measure_phantom_items) { + for (auto &measure_phantom_item : measure_phantom_items) { sp_canvas_item_destroy(measure_phantom_item); } measure_phantom_items.clear(); - for (auto & measure_tmp_item : measure_tmp_items) { + for (auto &measure_tmp_item : measure_tmp_items) { sp_canvas_item_destroy(measure_tmp_item); } measure_tmp_items.clear(); showCanvasItems(false, false, true); doc->ensureUpToDate(); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MEASURE,_("Keep last measure on the canvas, for reference")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MEASURE, + _("Keep last measure on the canvas, for reference")); } void MeasureTool::toItem() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if(!desktop || !start_p.isFinite() || !end_p.isFinite() || start_p == end_p) { + if (!desktop || !start_p.isFinite() || !end_p.isFinite() || start_p == end_p) { return; } SPDocument *doc = desktop->getDocument(); - Geom::Ray ray(start_p,end_p); + Geom::Ray ray(start_p, end_p); guint32 line_color_primary = 0x0000ff7f; Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); Inkscape::XML::Node *rgroup = xml_doc->createElement("svg:g"); showCanvasItems(false, true, false, rgroup); - setLine(start_p,end_p, false, line_color_primary, rgroup); + setLine(start_p, end_p, false, line_color_primary, rgroup); SPItem *measure_item = SP_ITEM(desktop->currentLayer()->appendChildRepr(rgroup)); Inkscape::GC::release(rgroup); measure_item->updateRepr(); doc->ensureUpToDate(); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MEASURE,_("Convert measure to items")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MEASURE, _("Convert measure to items")); reset(); } void MeasureTool::toMarkDimension() { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if(!desktop || !start_p.isFinite() || !end_p.isFinite() || start_p == end_p) { + if (!desktop || !start_p.isFinite() || !end_p.isFinite() || start_p == end_p) { return; } SPDocument *doc = desktop->getDocument(); setMarkers(); - Geom::Ray ray(start_p,end_p); + Geom::Ray ray(start_p, end_p); Geom::Point start = start_p + Geom::Point::polar(ray.angle(), 5); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); dimension_offset = prefs->getDouble("/tools/measure/offset", 5.0); start = start + Geom::Point::polar(ray.angle() + Geom::rad_from_deg(90), -dimension_offset); Geom::Point end = end_p + Geom::Point::polar(ray.angle(), -5); - end = end+ Geom::Point::polar(ray.angle() + Geom::rad_from_deg(90), -dimension_offset); + end = end + Geom::Point::polar(ray.angle() + Geom::rad_from_deg(90), -dimension_offset); guint32 color = 0x000000ff; setLine(start, end, true, color); Glib::ustring unit_name = prefs->getString("/tools/measure/unit"); @@ -807,7 +814,7 @@ void MeasureTool::toMarkDimension() int precision = prefs->getInt("/tools/measure/precision", 2); std::stringstream precision_str; precision_str.imbue(std::locale::classic()); - precision_str << "%." << precision << "f %s"; + precision_str << "%." << precision << "f %s"; Geom::Point middle = Geom::middle_point(start, end); double totallengthval = (end_p - start_p).length(); totallengthval = Inkscape::Util::Quantity::convert(totallengthval, "px", unit_name); @@ -820,7 +827,7 @@ void MeasureTool::toMarkDimension() setLabelText(totallength_str, middle, fontsize, textangle, color); g_free(totallength_str); doc->ensureUpToDate(); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MEASURE,_("Add global measure line")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MEASURE, _("Add global measure line")); } void MeasureTool::setGuide(Geom::Point origin, double angle, const char *label) @@ -830,11 +837,11 @@ void MeasureTool::setGuide(Geom::Point origin, double angle, const char *label) Inkscape::XML::Document *xml_doc = doc->getReprDoc(); SPRoot const *root = doc->getRoot(); Geom::Affine affine(Geom::identity()); - if(root) { + if (root) { affine *= root->c2p.inverse(); } SPNamedView *namedview = desktop->namedview; - if(!namedview) { + if (!namedview) { return; } @@ -845,13 +852,13 @@ void MeasureTool::setGuide(Geom::Point origin, double angle, const char *label) } origin *= affine; - //measure angle + // measure angle Inkscape::XML::Node *guide; guide = xml_doc->createElement("sodipodi:guide"); std::stringstream position; position.imbue(std::locale::classic()); - position << origin[Geom::X] << "," << origin[Geom::Y]; - guide->setAttribute("position", position.str() ); + position << origin[Geom::X] << "," << origin[Geom::Y]; + guide->setAttribute("position", position.str()); guide->setAttribute("inkscape:color", "rgb(167,0,255)"); guide->setAttribute("inkscape:label", label); Geom::Point unit_vector = Geom::rot90(origin.polar(angle)); @@ -863,10 +870,11 @@ void MeasureTool::setGuide(Geom::Point origin, double angle, const char *label) Inkscape::GC::release(guide); } -void MeasureTool::setLine(Geom::Point start_point,Geom::Point end_point, bool markers, guint32 color, Inkscape::XML::Node *measure_repr) +void MeasureTool::setLine(Geom::Point start_point, Geom::Point end_point, bool markers, guint32 color, + Inkscape::XML::Node *measure_repr) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if(!desktop || !start_p.isFinite() || !end_p.isFinite()) { + if (!desktop || !start_p.isFinite() || !end_p.isFinite()) { return; } Geom::PathVector pathv; @@ -875,7 +883,7 @@ void MeasureTool::setLine(Geom::Point start_point,Geom::Point end_point, bool ma path.appendNew<Geom::LineSegment>(desktop->doc2dt(end_point)); pathv.push_back(path); pathv *= SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); - if(!pathv.empty()) { + if (!pathv.empty()) { setMeasureItem(pathv, false, markers, color, measure_repr); } } @@ -883,14 +891,14 @@ void MeasureTool::setLine(Geom::Point start_point,Geom::Point end_point, bool ma void MeasureTool::setPoint(Geom::Point origin, Inkscape::XML::Node *measure_repr) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if(!desktop || !origin.isFinite()) { + if (!desktop || !origin.isFinite()) { return; } - char const * svgd; + char const *svgd; svgd = "m 0.707,0.707 6.586,6.586 m 0,-6.586 -6.586,6.586"; Geom::PathVector pathv = sp_svg_read_pathv(svgd); Geom::Scale scale = Geom::Scale(desktop->current_zoom()).inverse(); - pathv *= Geom::Translate(Geom::Point(-3.5,-3.5)); + pathv *= Geom::Translate(Geom::Point(-3.5, -3.5)); pathv *= scale; pathv *= Geom::Translate(Geom::Point() - (scale.vector() * 0.5)); pathv *= Geom::Translate(desktop->doc2dt(origin)); @@ -901,7 +909,9 @@ void MeasureTool::setPoint(Geom::Point origin, Inkscape::XML::Node *measure_repr } } -void MeasureTool::setLabelText(const char *value, Geom::Point pos, double fontsize, Geom::Coord angle, guint32 background, Inkscape::XML::Node *measure_repr, CanvasTextAnchorPositionEnum text_anchor) +void MeasureTool::setLabelText(const char *value, Geom::Point pos, double fontsize, Geom::Coord angle, + guint32 background, Inkscape::XML::Node *measure_repr, + CanvasTextAnchorPositionEnum text_anchor) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); @@ -910,10 +920,9 @@ void MeasureTool::setLabelText(const char *value, Geom::Point pos, double fontsi Inkscape::XML::Node *rtext = xml_doc->createElement("svg:text"); rtext->setAttribute("xml:space", "preserve"); - /* Set style */ sp_desktop_apply_style_tool(desktop, rtext, "/tools/text", true); - if(measure_repr) { + if (measure_repr) { sp_repr_set_svg_double(rtext, "x", 2); sp_repr_set_svg_double(rtext, "y", 2); } else { @@ -927,30 +936,30 @@ void MeasureTool::setLabelText(const char *value, Geom::Point pos, double fontsi SPCSSAttr *css = sp_repr_css_attr_new(); std::stringstream font_size; font_size.imbue(std::locale::classic()); - if(measure_repr) { - font_size << fontsize; + if (measure_repr) { + font_size << fontsize; } else { - font_size << fontsize << "pt"; - } - sp_repr_css_set_property (css, "font-size", font_size.str().c_str()); - sp_repr_css_set_property (css, "font-style", "normal"); - sp_repr_css_set_property (css, "font-weight", "normal"); - sp_repr_css_set_property (css, "line-height", "125%"); - sp_repr_css_set_property (css, "letter-spacing", "0"); - sp_repr_css_set_property (css, "word-spacing", "0"); - sp_repr_css_set_property (css, "text-align", "center"); - sp_repr_css_set_property (css, "text-anchor", "middle"); - if(measure_repr) { - sp_repr_css_set_property (css, "fill", "#FFFFFF"); + font_size << fontsize << "pt"; + } + sp_repr_css_set_property(css, "font-size", font_size.str().c_str()); + sp_repr_css_set_property(css, "font-style", "normal"); + sp_repr_css_set_property(css, "font-weight", "normal"); + sp_repr_css_set_property(css, "line-height", "125%"); + sp_repr_css_set_property(css, "letter-spacing", "0"); + sp_repr_css_set_property(css, "word-spacing", "0"); + sp_repr_css_set_property(css, "text-align", "center"); + sp_repr_css_set_property(css, "text-anchor", "middle"); + if (measure_repr) { + sp_repr_css_set_property(css, "fill", "#FFFFFF"); } else { - sp_repr_css_set_property (css, "fill", "#000000"); + sp_repr_css_set_property(css, "fill", "#000000"); } - sp_repr_css_set_property (css, "fill-opacity", "1"); - sp_repr_css_set_property (css, "stroke", "none"); + sp_repr_css_set_property(css, "fill-opacity", "1"); + sp_repr_css_set_property(css, "stroke", "none"); Glib::ustring css_str; - sp_repr_css_write_string(css,css_str); + sp_repr_css_write_string(css, css_str); rtspan->setAttribute("style", css_str); - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); rtext->addChild(rtspan, nullptr); Inkscape::GC::release(rtspan); /* Create TEXT */ @@ -964,26 +973,26 @@ void MeasureTool::setLabelText(const char *value, Geom::Point pos, double fontsi if (!measure_repr && bbox) { Geom::Point center = bbox->midpoint(); text_item->transform *= Geom::Translate(center).inverse(); - pos += Geom::Point::polar(angle+ Geom::rad_from_deg(90), -bbox->height()); + pos += Geom::Point::polar(angle + Geom::rad_from_deg(90), -bbox->height()); } - if(measure_repr) { + if (measure_repr) { /* Create <group> */ Inkscape::XML::Node *rgroup = xml_doc->createElement("svg:g"); /* Create <rect> */ Inkscape::XML::Node *rrect = xml_doc->createElement("svg:rect"); - SPCSSAttr *css = sp_repr_css_attr_new (); + SPCSSAttr *css = sp_repr_css_attr_new(); gchar color_line[64]; - sp_svg_write_color (color_line, sizeof(color_line), background); - sp_repr_css_set_property (css, "fill", color_line); - sp_repr_css_set_property (css, "fill-opacity", "0.5"); - sp_repr_css_set_property (css, "stroke-width", "0"); + sp_svg_write_color(color_line, sizeof(color_line), background); + sp_repr_css_set_property(css, "fill", color_line); + sp_repr_css_set_property(css, "fill-opacity", "0.5"); + sp_repr_css_set_property(css, "stroke-width", "0"); Glib::ustring css_str; - sp_repr_css_write_string(css,css_str); + sp_repr_css_write_string(css, css_str); rrect->setAttribute("style", css_str); - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); sp_repr_set_svg_double(rgroup, "x", 0); sp_repr_set_svg_double(rgroup, "y", 0); - sp_repr_set_svg_double(rrect, "x", -bbox->width()/2.0); + sp_repr_set_svg_double(rrect, "x", -bbox->width() / 2.0); sp_repr_set_svg_double(rrect, "y", -bbox->height()); sp_repr_set_svg_double(rrect, "width", bbox->width() + 6); sp_repr_set_svg_double(rrect, "height", bbox->height() + 6); @@ -995,8 +1004,8 @@ void MeasureTool::setLabelText(const char *value, Geom::Point pos, double fontsi Inkscape::GC::release(rrect); SPItem *text_item_box = SP_ITEM(desktop->currentLayer()->appendChildRepr(rgroup)); Geom::Scale scale = Geom::Scale(desktop->current_zoom()).inverse(); - if(bbox && text_anchor == TEXT_ANCHOR_CENTER) { - text_item_box->transform *= Geom::Translate(bbox->midpoint() - Geom::Point(1.0,1.0)).inverse(); + if (bbox && text_anchor == TEXT_ANCHOR_CENTER) { + text_item_box->transform *= Geom::Translate(bbox->midpoint() - Geom::Point(1.0, 1.0)).inverse(); } text_item_box->transform *= scale; text_item_box->transform *= Geom::Translate(Geom::Point() - (scale.vector() * 0.5)); @@ -1020,34 +1029,34 @@ void MeasureTool::reset() { this->knot_start->hide(); this->knot_end->hide(); - for (auto & measure_tmp_item : measure_tmp_items) { + for (auto &measure_tmp_item : measure_tmp_items) { sp_canvas_item_destroy(measure_tmp_item); } measure_tmp_items.clear(); } -void MeasureTool::setMeasureCanvasText(bool is_angle, double precision, double amount, double fontsize, Glib::ustring unit_name, Geom::Point position, guint32 background, CanvasTextAnchorPositionEnum text_anchor, bool to_item, bool to_phantom, Inkscape::XML::Node *measure_repr) +void MeasureTool::setMeasureCanvasText(bool is_angle, double precision, double amount, double fontsize, + Glib::ustring unit_name, Geom::Point position, guint32 background, + CanvasTextAnchorPositionEnum text_anchor, bool to_item, bool to_phantom, + Inkscape::XML::Node *measure_repr) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; std::stringstream precision_str; precision_str.imbue(std::locale::classic()); - if(is_angle){ + if (is_angle) { precision_str << "%." << precision << "f °"; } else { precision_str << "%." << precision << "f %s"; } gchar *measure_str = g_strdup_printf(precision_str.str().c_str(), amount, unit_name.c_str()); - SPCanvasText *canvas_tooltip = sp_canvastext_new(desktop->getTempGroup(), - desktop, - position, - measure_str); + SPCanvasText *canvas_tooltip = sp_canvastext_new(desktop->getTempGroup(), desktop, position, measure_str); sp_canvastext_set_fontsize(canvas_tooltip, fontsize); canvas_tooltip->rgba = 0xffffffff; canvas_tooltip->rgba_background = background; canvas_tooltip->outline = false; canvas_tooltip->background = true; canvas_tooltip->anchor_position = text_anchor; - if(to_phantom){ + if (to_phantom) { canvas_tooltip->rgba_background = 0x4444447f; measure_phantom_items.push_back(SP_CANVAS_ITEM(canvas_tooltip)); sp_canvas_item_show(SP_CANVAS_ITEM(canvas_tooltip)); @@ -1056,30 +1065,26 @@ void MeasureTool::setMeasureCanvasText(bool is_angle, double precision, double a sp_canvas_item_show(SP_CANVAS_ITEM(canvas_tooltip)); } - if(to_item) { + if (to_item) { setLabelText(measure_str, position, fontsize, 0, background, measure_repr); } g_free(measure_str); } -void MeasureTool::setMeasureCanvasItem(Geom::Point position, bool to_item, bool to_phantom, Inkscape::XML::Node *measure_repr){ +void MeasureTool::setMeasureCanvasItem(Geom::Point position, bool to_item, bool to_phantom, + Inkscape::XML::Node *measure_repr) +{ SPDesktop *desktop = SP_ACTIVE_DESKTOP; guint32 color = 0xff0000ff; - if(to_phantom){ + if (to_phantom) { color = 0x888888ff; } - SPCanvasItem * canvasitem = sp_canvas_item_new(desktop->getTempGroup(), - SP_TYPE_CTRL, - "anchor", SP_ANCHOR_CENTER, - "size", 9, - "stroked", TRUE, - "stroke_color", color, - "mode", SP_KNOT_MODE_XOR, - "shape", SP_KNOT_SHAPE_CROSS, - NULL ); + SPCanvasItem *canvasitem = + sp_canvas_item_new(desktop->getTempGroup(), SP_TYPE_CTRL, "anchor", SP_ANCHOR_CENTER, "size", 9, "stroked", + TRUE, "stroke_color", color, "mode", SP_KNOT_MODE_XOR, "shape", SP_KNOT_SHAPE_CROSS, NULL); SP_CTRL(canvasitem)->moveto(position); - if(to_phantom){ + if (to_phantom) { measure_phantom_items.push_back(canvasitem); } else { measure_tmp_items.push_back(canvasitem); @@ -1087,44 +1092,37 @@ void MeasureTool::setMeasureCanvasItem(Geom::Point position, bool to_item, bool sp_canvas_item_show(canvasitem); sp_canvas_item_move_to_z(canvasitem, 0); - if(to_item) { + if (to_item) { setPoint(position, measure_repr); } } -void MeasureTool::setMeasureCanvasControlLine(Geom::Point start, Geom::Point end, bool to_item, bool to_phantom, Inkscape::CtrlLineType ctrl_line_type, Inkscape::XML::Node *measure_repr){ - SPDesktop *desktop = SP_ACTIVE_DESKTOP; - gint32 color = ctrl_line_type == CTLINE_PRIMARY ? 0x0000ff7f : 0xff00007f; - if(to_phantom){ - color = ctrl_line_type == CTLINE_PRIMARY ? 0x4444447f : 0x8888887f; - } - SPCtrlLine *control_line = ControlManager::getManager().createControlLine(desktop->getTempGroup(), - start, - end, - ctrl_line_type); - control_line->rgba = color; - if(to_phantom){ - measure_phantom_items.push_back(SP_CANVAS_ITEM(control_line)); - } else { - measure_tmp_items.push_back(SP_CANVAS_ITEM(control_line)); - } - sp_canvas_item_move_to_z(SP_CANVAS_ITEM(control_line), 0); - sp_canvas_item_show(SP_CANVAS_ITEM(control_line)); - if(to_item) { - setLine(start, - end, - false, - color, - measure_repr); - } +void MeasureTool::setMeasureCanvasControlLine(Geom::Point start, Geom::Point end, bool to_item, bool to_phantom, + Inkscape::CtrlLineType ctrl_line_type, Inkscape::XML::Node *measure_repr) +{ + SPDesktop *desktop = SP_ACTIVE_DESKTOP; + gint32 color = ctrl_line_type == CTLINE_PRIMARY ? 0x0000ff7f : 0xff00007f; + if (to_phantom) { + color = ctrl_line_type == CTLINE_PRIMARY ? 0x4444447f : 0x8888887f; + } + SPCtrlLine *control_line = + ControlManager::getManager().createControlLine(desktop->getTempGroup(), start, end, ctrl_line_type); + control_line->rgba = color; + if (to_phantom) { + measure_phantom_items.push_back(SP_CANVAS_ITEM(control_line)); + } else { + measure_tmp_items.push_back(SP_CANVAS_ITEM(control_line)); + } + sp_canvas_item_move_to_z(SP_CANVAS_ITEM(control_line), 0); + sp_canvas_item_show(SP_CANVAS_ITEM(control_line)); + if (to_item) { + setLine(start, end, false, color, measure_repr); + } } void MeasureTool::showItemInfoText(Geom::Point pos, gchar *measure_str, double fontsize) { - SPCanvasText *canvas_tooltip = sp_canvastext_new(desktop->getTempGroup(), - desktop, - pos, - measure_str); + SPCanvasText *canvas_tooltip = sp_canvastext_new(desktop->getTempGroup(), desktop, pos, measure_str); sp_canvastext_set_fontsize(canvas_tooltip, fontsize); canvas_tooltip->rgba = 0xffffffff; canvas_tooltip->outline = false; @@ -1138,8 +1136,8 @@ void MeasureTool::showItemInfoText(Geom::Point pos, gchar *measure_str, double f void MeasureTool::showInfoBox(Geom::Point cursor, bool into_groups) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - Inkscape::Util::Unit const * unit = desktop->getNamedView()->getDisplayUnit(); - for (auto & idx : measure_item) { + Inkscape::Util::Unit const *unit = desktop->getNamedView()->getDisplayUnit(); + for (auto &idx : measure_item) { sp_canvas_item_destroy(idx); } measure_item.clear(); @@ -1155,19 +1153,19 @@ void MeasureTool::showInfoBox(Geom::Point cursor, bool into_groups) if (!unit_name.compare("")) { unit_name = DEFAULT_UNIT_NAME; } - Geom::Scale zoom = Geom::Scale(Inkscape::Util::Quantity::convert(desktop->current_zoom(), "px", unit->abbr)).inverse(); - if(newover != over){ + Geom::Scale zoom = + Geom::Scale(Inkscape::Util::Quantity::convert(desktop->current_zoom(), "px", unit->abbr)).inverse(); + if (newover != over) { over = newover; Preferences *prefs = Preferences::get(); int prefs_bbox = prefs->getBool("/tools/bounding_box", false); SPItem::BBoxType bbox_type = !prefs_bbox ? SPItem::VISUAL_BBOX : SPItem::GEOMETRIC_BBOX; Geom::OptRect bbox = over->bounds(bbox_type); if (bbox) { - item_width = Inkscape::Util::Quantity::convert((*bbox).width() * scale, unit->abbr, unit_name); item_height = Inkscape::Util::Quantity::convert((*bbox).height() * scale, unit->abbr, unit_name); item_x = Inkscape::Util::Quantity::convert((*bbox).left(), unit->abbr, unit_name); - Geom::Point y_point(0,Inkscape::Util::Quantity::convert((*bbox).bottom() * scale, unit->abbr, "px")); + Geom::Point y_point(0, Inkscape::Util::Quantity::convert((*bbox).bottom() * scale, unit->abbr, "px")); y_point *= desktop->doc2dt(); item_y = Inkscape::Util::Quantity::convert(y_point[Geom::Y] * scale, "px", unit_name); if (SP_IS_SHAPE(over)) { @@ -1186,45 +1184,45 @@ void MeasureTool::showInfoBox(Geom::Point cursor, bool into_groups) double gap = Inkscape::Util::Quantity::convert(7 + fontsize, "px", unit->abbr); if (only_selected) { if (desktop->getSelection()->includes(over)) { - showItemInfoText(pos + (rel_position * zoom),_("Selected"),fontsize); + showItemInfoText(pos + (rel_position * zoom), _("Selected"), fontsize); } else { - showItemInfoText(pos + (rel_position * zoom),_("Not selected"),fontsize); + showItemInfoText(pos + (rel_position * zoom), _("Not selected"), fontsize); } rel_position = Geom::Point(rel_position[Geom::X], rel_position[Geom::Y] + gap); } if (SP_IS_SHAPE(over)) { - precision_str << _("Length") << ": %." << precision << "f %s"; + precision_str << _("Length") << ": %." << precision << "f %s"; measure_str = g_strdup_printf(precision_str.str().c_str(), item_length, unit_name.c_str()); precision_str.str(""); - showItemInfoText(pos + (rel_position * zoom),measure_str,fontsize); + showItemInfoText(pos + (rel_position * zoom), measure_str, fontsize); rel_position = Geom::Point(rel_position[Geom::X], rel_position[Geom::Y] + gap); } else if (SP_IS_GROUP(over)) { measure_str = _("Press 'CTRL' to measure into group"); - showItemInfoText(pos + (rel_position * zoom),measure_str,fontsize); + showItemInfoText(pos + (rel_position * zoom), measure_str, fontsize); rel_position = Geom::Point(rel_position[Geom::X], rel_position[Geom::Y] + gap); } - precision_str << "Y: %." << precision << "f %s"; + precision_str << "Y: %." << precision << "f %s"; measure_str = g_strdup_printf(precision_str.str().c_str(), item_y, unit_name.c_str()); precision_str.str(""); - showItemInfoText(pos + (rel_position * zoom),measure_str,fontsize); + showItemInfoText(pos + (rel_position * zoom), measure_str, fontsize); rel_position = Geom::Point(rel_position[Geom::X], rel_position[Geom::Y] + gap); - precision_str << "X: %." << precision << "f %s"; + precision_str << "X: %." << precision << "f %s"; measure_str = g_strdup_printf(precision_str.str().c_str(), item_x, unit_name.c_str()); precision_str.str(""); - showItemInfoText(pos + (rel_position * zoom),measure_str,fontsize); + showItemInfoText(pos + (rel_position * zoom), measure_str, fontsize); rel_position = Geom::Point(rel_position[Geom::X], rel_position[Geom::Y] + gap); precision_str << _("Height") << ": %." << precision << "f %s"; measure_str = g_strdup_printf(precision_str.str().c_str(), item_height, unit_name.c_str()); precision_str.str(""); - showItemInfoText(pos + (rel_position * zoom),measure_str,fontsize); + showItemInfoText(pos + (rel_position * zoom), measure_str, fontsize); rel_position = Geom::Point(rel_position[Geom::X], rel_position[Geom::Y] + gap); precision_str << _("Width") << ": %." << precision << "f %s"; measure_str = g_strdup_printf(precision_str.str().c_str(), item_width, unit_name.c_str()); precision_str.str(""); - showItemInfoText(pos + (rel_position * zoom),measure_str,fontsize); + showItemInfoText(pos + (rel_position * zoom), measure_str, fontsize); g_free(measure_str); } } @@ -1232,17 +1230,17 @@ void MeasureTool::showInfoBox(Geom::Point cursor, bool into_groups) void MeasureTool::showCanvasItems(bool to_guides, bool to_item, bool to_phantom, Inkscape::XML::Node *measure_repr) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if(!desktop || !start_p.isFinite() || !end_p.isFinite() || start_p == end_p) { + if (!desktop || !start_p.isFinite() || !end_p.isFinite() || start_p == end_p) { return; } writeMeasurePoint(start_p, true); writeMeasurePoint(end_p, false); - //clear previous canvas items, we'll draw new ones - for (auto & measure_tmp_item : measure_tmp_items) { + // clear previous canvas items, we'll draw new ones + for (auto &measure_tmp_item : measure_tmp_items) { sp_canvas_item_destroy(measure_tmp_item); } measure_tmp_items.clear(); - //TODO:Calculate the measure area for current length and origin + // TODO:Calculate the measure area for current length and origin // and use canvas->requestRedraw. In the calculation need a gap for outside text // maybe this remove the trash lines on measure use Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -1265,13 +1263,13 @@ void MeasureTool::showCanvasItems(bool to_guides, bool to_item, bool to_phantom, angle -= baseAngle; } - std::vector<SPItem*> items; + std::vector<SPItem *> items; SPDocument *doc = desktop->getDocument(); Geom::Rect rect(start_p_doc, end_p_doc); items = doc->getItemsPartiallyInBox(desktop->dkey, rect, false, true, false, true); Inkscape::LayerModel *layer_model = nullptr; SPObject *current_layer = nullptr; - if(desktop){ + if (desktop) { layer_model = desktop->layers; current_layer = desktop->currentLayer(); } @@ -1282,7 +1280,7 @@ void MeasureTool::showCanvasItems(bool to_guides, bool to_item, bool to_phantom, if (!desktop->getSelection()->includes(i) && only_selected) { continue; } - if(all_layers || (layer_model && layer_model->layerForObject(item) == current_layer)){ + if (all_layers || (layer_model && layer_model->layerForObject(item) == current_layer)) { if (auto shape = dynamic_cast<SPShape const *>(item)) { calculate_intersections(desktop, item, lineseg, SPCurve::copy(shape->curve()), intersection_times); } else { @@ -1326,19 +1324,19 @@ void MeasureTool::showCanvasItems(bool to_guides, bool to_item, bool to_phantom, std::vector<Geom::Point> intersections; std::sort(intersection_times.begin(), intersection_times.end()); - for (double & intersection_time : intersection_times) { + for (double &intersection_time : intersection_times) { intersections.push_back(lineseg[0].pointAt(intersection_time)); } - if(!show_in_between && intersection_times.size() > 1) { + if (!show_in_between && intersection_times.size() > 1) { Geom::Point start = lineseg[0].pointAt(intersection_times[0]); - Geom::Point end = lineseg[0].pointAt(intersection_times[intersection_times.size()-1]); + Geom::Point end = lineseg[0].pointAt(intersection_times[intersection_times.size() - 1]); intersections.clear(); intersections.push_back(start); intersections.push_back(end); } if (!prefs->getBool("/tools/measure/ignore_1st_and_last", true)) { - intersections.insert(intersections.begin(),lineseg[0].pointAt(0)); + intersections.insert(intersections.begin(), lineseg[0].pointAt(0)); intersections.push_back(lineseg[0].pointAt(1)); } std::vector<LabelPlacement> placements; @@ -1347,7 +1345,7 @@ void MeasureTool::showCanvasItems(bool to_guides, bool to_item, bool to_phantom, placement.lengthVal = (intersections[idx] - intersections[idx - 1]).length(); placement.lengthVal = Inkscape::Util::Quantity::convert(placement.lengthVal, "px", unit_name); placement.offset = dimension_offset / 2; - placement.start = desktop->doc2dt( (intersections[idx - 1] + intersections[idx]) / 2 ); + placement.start = desktop->doc2dt((intersections[idx - 1] + intersections[idx]) / 2); placement.end = placement.start - (normal * placement.offset); placements.push_back(placement); @@ -1355,28 +1353,31 @@ void MeasureTool::showCanvasItems(bool to_guides, bool to_item, bool to_phantom, int precision = prefs->getInt("/tools/measure/precision", 2); // Adjust positions repositionOverlappingLabels(placements, desktop, windowNormal, fontsize, precision); - for (auto & place : placements) { - setMeasureCanvasText(false, precision, place.lengthVal * scale, fontsize, unit_name, place.end, 0x0000007f, TEXT_ANCHOR_CENTER, to_item, to_phantom, measure_repr); + for (auto &place : placements) { + setMeasureCanvasText(false, precision, place.lengthVal * scale, fontsize, unit_name, place.end, 0x0000007f, + TEXT_ANCHOR_CENTER, to_item, to_phantom, measure_repr); } - Geom::Point angleDisplayPt = calcAngleDisplayAnchor(desktop, angle, baseAngle, - start_p, end_p, - fontsize); + Geom::Point angleDisplayPt = calcAngleDisplayAnchor(desktop, angle, baseAngle, start_p, end_p, fontsize); { - setMeasureCanvasText(true, precision, Geom::deg_from_rad(angle), fontsize, unit_name, angleDisplayPt, 0x337f337f, TEXT_ANCHOR_CENTER, to_item, to_phantom, measure_repr); + setMeasureCanvasText(true, precision, Geom::deg_from_rad(angle), fontsize, unit_name, angleDisplayPt, + 0x337f337f, TEXT_ANCHOR_CENTER, to_item, to_phantom, measure_repr); } { double totallengthval = (end_p - start_p).length(); totallengthval = Inkscape::Util::Quantity::convert(totallengthval, "px", unit_name); - Geom::Point origin = end_p + desktop->w2d(Geom::Point(3*fontsize, -fontsize)); - setMeasureCanvasText(false, precision, totallengthval * scale, fontsize, unit_name, origin, 0x3333337f, TEXT_ANCHOR_LEFT, to_item, to_phantom, measure_repr); + Geom::Point origin = end_p + desktop->w2d(Geom::Point(3 * fontsize, -fontsize)); + setMeasureCanvasText(false, precision, totallengthval * scale, fontsize, unit_name, origin, 0x3333337f, + TEXT_ANCHOR_LEFT, to_item, to_phantom, measure_repr); } if (intersections.size() > 2) { - double totallengthval = (intersections[intersections.size()-1] - intersections[0]).length(); + double totallengthval = (intersections[intersections.size() - 1] - intersections[0]).length(); totallengthval = Inkscape::Util::Quantity::convert(totallengthval, "px", unit_name); - Geom::Point origin = desktop->doc2dt((intersections[0] + intersections[intersections.size()-1])/2) + normal * dimension_offset; - setMeasureCanvasText(false, precision, totallengthval * scale, fontsize, unit_name, origin, 0x33337f7f, TEXT_ANCHOR_CENTER, to_item, to_phantom, measure_repr); + Geom::Point origin = desktop->doc2dt((intersections[0] + intersections[intersections.size() - 1]) / 2) + + normal * dimension_offset; + setMeasureCanvasText(false, precision, totallengthval * scale, fontsize, unit_name, origin, 0x33337f7f, + TEXT_ANCHOR_CENTER, to_item, to_phantom, measure_repr); } // Initial point @@ -1387,12 +1388,12 @@ void MeasureTool::showCanvasItems(bool to_guides, bool to_item, bool to_phantom, // 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) { setMeasureCanvasItem(desktop->doc2dt(intersections[idx]), to_item, to_phantom, measure_repr); - if(to_guides) { + if (to_guides) { gchar *cross_number; if (!prefs->getBool("/tools/measure/ignore_1st_and_last", true)) { - cross_number= g_strdup_printf(_("Crossing %lu"), static_cast<unsigned long>(idx)); + cross_number = g_strdup_printf(_("Crossing %lu"), static_cast<unsigned long>(idx)); } else { - cross_number= g_strdup_printf(_("Crossing %lu"), static_cast<unsigned long>(idx + 1)); + cross_number = g_strdup_printf(_("Crossing %lu"), static_cast<unsigned long>(idx + 1)); } if (!prefs->getBool("/tools/measure/ignore_1st_and_last", true) && idx == 0) { setGuide(desktop->doc2dt(intersections[idx]), angle + Geom::rad_from_deg(90), ""); @@ -1411,38 +1412,48 @@ void MeasureTool::showCanvasItems(bool to_guides, bool to_item, bool to_phantom, Geom::Point anchorEnd = start_p; anchorEnd[Geom::X] += length; if (explicit_base) { - anchorEnd *= (Geom::Affine(Geom::Translate(-start_p)) - * Geom::Affine(Geom::Rotate(baseAngle)) - * Geom::Affine(Geom::Translate(start_p))); + anchorEnd *= (Geom::Affine(Geom::Translate(-start_p)) * Geom::Affine(Geom::Rotate(baseAngle)) * + Geom::Affine(Geom::Translate(start_p))); } setMeasureCanvasControlLine(start_p, anchorEnd, to_item, to_phantom, CTLINE_SECONDARY, measure_repr); - createAngleDisplayCurve(desktop, start_p, end_p, angleDisplayPt, angle, to_phantom, measure_phantom_items, measure_tmp_items, measure_repr); + createAngleDisplayCurve(desktop, start_p, end_p, angleDisplayPt, angle, to_phantom, measure_phantom_items, + measure_tmp_items, measure_repr); } if (intersections.size() > 2) { - setMeasureCanvasControlLine(desktop->doc2dt(intersections[0]) + normal * dimension_offset, desktop->doc2dt(intersections[intersections.size() - 1]) + normal * dimension_offset, to_item, to_phantom, CTLINE_PRIMARY , measure_repr); + setMeasureCanvasControlLine(desktop->doc2dt(intersections[0]) + normal * dimension_offset, + desktop->doc2dt(intersections[intersections.size() - 1]) + + normal * dimension_offset, + to_item, to_phantom, CTLINE_PRIMARY, measure_repr); - setMeasureCanvasControlLine(desktop->doc2dt(intersections[0]), desktop->doc2dt(intersections[0]) + normal * dimension_offset, to_item, to_phantom, CTLINE_PRIMARY , measure_repr); + setMeasureCanvasControlLine(desktop->doc2dt(intersections[0]), + desktop->doc2dt(intersections[0]) + normal * dimension_offset, to_item, to_phantom, + CTLINE_PRIMARY, measure_repr); - setMeasureCanvasControlLine(desktop->doc2dt(intersections[intersections.size() - 1]), desktop->doc2dt(intersections[intersections.size() - 1]) + normal * dimension_offset, to_item, to_phantom, CTLINE_PRIMARY , measure_repr); + setMeasureCanvasControlLine(desktop->doc2dt(intersections[intersections.size() - 1]), + desktop->doc2dt(intersections[intersections.size() - 1]) + + normal * dimension_offset, + to_item, to_phantom, CTLINE_PRIMARY, measure_repr); } // call-out lines - for (auto & place : placements) { + for (auto &place : placements) { setMeasureCanvasControlLine(place.start, place.end, to_item, to_phantom, CTLINE_SECONDARY, measure_repr); } { for (size_t idx = 1; idx < intersections.size(); ++idx) { Geom::Point measure_text_pos = (intersections[idx - 1] + intersections[idx]) / 2; - setMeasureCanvasControlLine(desktop->doc2dt(measure_text_pos), desktop->doc2dt(measure_text_pos) - (normal * dimension_offset / 2), to_item, to_phantom, CTLINE_SECONDARY, measure_repr); + setMeasureCanvasControlLine(desktop->doc2dt(measure_text_pos), + desktop->doc2dt(measure_text_pos) - (normal * dimension_offset / 2), to_item, + to_phantom, CTLINE_SECONDARY, measure_repr); } } } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/measure-tool.h b/src/ui/tools/measure-tool.h index 6e4255d369ab89084b74e075d341805571da5261..7128ad6342ab22d322d22a0f34f00e46793ae3d3 100644 --- a/src/ui/tools/measure-tool.h +++ b/src/ui/tools/measure-tool.h @@ -13,14 +13,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <2geom/point.h> +#include <boost/optional.hpp> #include <cstddef> #include <sigc++/sigc++.h> -#include "ui/tools/tool-base.h" -#include <2geom/point.h> -#include "display/canvas-text.h" + #include "display/canvas-temporary-item.h" +#include "display/canvas-text.h" #include "ui/control-manager.h" -#include <boost/optional.hpp> +#include "ui/tools/tool-base.h" class SPKnot; @@ -28,7 +29,8 @@ namespace Inkscape { namespace UI { namespace Tools { -class MeasureTool : public ToolBase { +class MeasureTool : public ToolBase +{ public: MeasureTool(); ~MeasureTool() override; @@ -36,8 +38,9 @@ public: static const std::string prefsPath; void finish() override; - bool root_handler(GdkEvent* event) override; - virtual void showCanvasItems(bool to_guides = false, bool to_item = false, bool to_phantom = false, Inkscape::XML::Node *measure_repr = nullptr); + bool root_handler(GdkEvent *event) override; + virtual void showCanvasItems(bool to_guides = false, bool to_item = false, bool to_phantom = false, + Inkscape::XML::Node *measure_repr = nullptr); virtual void reverseKnots(); virtual void toGuides(); virtual void toPhantom(); @@ -46,24 +49,31 @@ public: virtual void reset(); virtual void setMarkers(); virtual void setMarker(bool isStart); - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; Geom::Point readMeasurePoint(bool is_start); void showInfoBox(Geom::Point cursor, bool into_groups); void showItemInfoText(Geom::Point pos, gchar *measure_str, double fontsize); void writeMeasurePoint(Geom::Point point, bool is_start); void setGuide(Geom::Point origin, double angle, const char *label); void setPoint(Geom::Point origin, Inkscape::XML::Node *measure_repr); - void setLine(Geom::Point start_point,Geom::Point end_point, bool markers, guint32 color, Inkscape::XML::Node *measure_repr = nullptr); - void setMeasureCanvasText(bool is_angle, double precision, double amount, double fontsize, Glib::ustring unit_name, Geom::Point position, guint32 background, CanvasTextAnchorPositionEnum text_anchor, bool to_item, bool to_phantom, Inkscape::XML::Node *measure_repr); + void setLine(Geom::Point start_point, Geom::Point end_point, bool markers, guint32 color, + Inkscape::XML::Node *measure_repr = nullptr); + void setMeasureCanvasText(bool is_angle, double precision, double amount, double fontsize, Glib::ustring unit_name, + Geom::Point position, guint32 background, CanvasTextAnchorPositionEnum text_anchor, + bool to_item, bool to_phantom, Inkscape::XML::Node *measure_repr); void setMeasureCanvasItem(Geom::Point position, bool to_item, bool to_phantom, Inkscape::XML::Node *measure_repr); - void setMeasureCanvasControlLine(Geom::Point start, Geom::Point end, bool to_item, bool to_phantom, Inkscape::CtrlLineType ctrl_line_type, Inkscape::XML::Node *measure_repr); - void setLabelText(const char *value, Geom::Point pos, double fontsize, Geom::Coord angle, guint32 background , Inkscape::XML::Node *measure_repr = nullptr, CanvasTextAnchorPositionEnum text_anchor = TEXT_ANCHOR_CENTER ); - void knotStartMovedHandler(SPKnot */*knot*/, Geom::Point const &ppointer, guint state); - void knotEndMovedHandler(SPKnot */*knot*/, Geom::Point const &ppointer, guint state); + void setMeasureCanvasControlLine(Geom::Point start, Geom::Point end, bool to_item, bool to_phantom, + Inkscape::CtrlLineType ctrl_line_type, Inkscape::XML::Node *measure_repr); + void setLabelText(const char *value, Geom::Point pos, double fontsize, Geom::Coord angle, guint32 background, + Inkscape::XML::Node *measure_repr = nullptr, + CanvasTextAnchorPositionEnum text_anchor = TEXT_ANCHOR_CENTER); + void knotStartMovedHandler(SPKnot * /*knot*/, Geom::Point const &ppointer, guint state); + void knotEndMovedHandler(SPKnot * /*knot*/, Geom::Point const &ppointer, guint state); void knotClickHandler(SPKnot *knot, guint state); - void knotUngrabbedHandler(SPKnot */*knot*/, unsigned int /*state*/); + void knotUngrabbedHandler(SPKnot * /*knot*/, unsigned int /*state*/); + private: - SPCanvasItem* grabbed; + SPCanvasItem *grabbed; boost::optional<Geom::Point> explicit_base; boost::optional<Geom::Point> last_end; SPKnot *knot_start; @@ -89,9 +99,9 @@ private: sigc::connection _knot_end_ungrabbed_connection; }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif // SEEN_SP_MEASURING_CONTEXT_H diff --git a/src/ui/tools/mesh-tool.cpp b/src/ui/tools/mesh-tool.cpp index 372e98d1b7194f4c4d6a98ef493cc89b222e65f2..97d0c7d16f2bf23da40fa6706ce7f4d747566256 100644 --- a/src/ui/tools/mesh-tool.cpp +++ b/src/ui/tools/mesh-tool.cpp @@ -17,40 +17,34 @@ //#define DEBUG_MESH - // Libraries #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> // General #include "desktop.h" +#include "display/curve.h" +#include "display/sp-ctrlcurve.h" #include "document-undo.h" #include "document.h" -#include "gradient-drag.h" #include "gradient-chemistry.h" +#include "gradient-drag.h" #include "include/macros.h" #include "message-context.h" #include "message-stack.h" -#include "rubberband.h" -#include "selection.h" -#include "snap.h" -#include "verbs.h" - -#include "display/sp-ctrlcurve.h" -#include "display/curve.h" - #include "object/sp-defs.h" #include "object/sp-mesh-gradient.h" #include "object/sp-namedview.h" #include "object/sp-text.h" +#include "rubberband.h" +#include "selection.h" +#include "snap.h" #include "style.h" - -#include "ui/pixmaps/cursor-gradient.xpm" -#include "ui/pixmaps/cursor-gradient-add.xpm" - #include "ui/control-manager.h" +#include "ui/pixmaps/cursor-gradient-add.xpm" +#include "ui/pixmaps/cursor-gradient.xpm" #include "ui/tools/mesh-tool.h" - +#include "verbs.h" using Inkscape::DocumentUndo; @@ -60,8 +54,9 @@ namespace Tools { static void sp_mesh_new_default(MeshTool &rc); -const std::string& MeshTool::getPrefsPath() { - return MeshTool::prefsPath; +const std::string &MeshTool::getPrefsPath() +{ + return MeshTool::prefsPath; } const std::string MeshTool::prefsPath = "/tools/mesh"; @@ -70,7 +65,7 @@ const std::string MeshTool::prefsPath = "/tools/mesh"; MeshTool::MeshTool() : ToolBase(cursor_gradient_xpm) -// TODO: Why are these connections stored as pointers? + // TODO: Why are these connections stored as pointers? , selcon(nullptr) , subselcon(nullptr) , cursor_addnode(false) @@ -83,12 +78,13 @@ MeshTool::MeshTool() this->tolerance = 6; } -MeshTool::~MeshTool() { +MeshTool::~MeshTool() +{ this->enableGrDrag(false); this->selcon->disconnect(); delete this->selcon; - + this->subselcon->disconnect(); delete this->subselcon; } @@ -96,22 +92,16 @@ MeshTool::~MeshTool() { // This must match GrPointType enum sp-gradient.h // We should move this to a shared header (can't simply move to gradient.h since that would require // including <glibmm/i18n.h> which messes up "N_" in extensions... argh!). -const gchar *ms_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>"), +const gchar *ms_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>"), - 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*/) { + N_("Radial gradient <b>mid stop</b>"), N_("Radial gradient <b>mid stop</b>"), 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 = this->desktop->getSelection(); @@ -119,7 +109,7 @@ void MeshTool::selection_changed(Inkscape::Selection* /*sel*/) { return; } - guint n_obj = (guint) boost::distance(selection->items()); + guint n_obj = (guint)boost::distance(selection->items()); if (!drag->isNonEmpty() || selection->isEmpty()) { return; @@ -128,40 +118,46 @@ void MeshTool::selection_changed(Inkscape::Selection* /*sel*/) { 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 + // 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 + 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); + // 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); + 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); + // 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); + // 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 @@ -169,7 +165,8 @@ void MeshTool::selection_changed(Inkscape::Selection* /*sel*/) { // Get gradient this drag belongs too.. } -void MeshTool::setup() { +void MeshTool::setup() +{ ToolBase::setup(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -180,26 +177,20 @@ void MeshTool::setup() { this->enableGrDrag(); Inkscape::Selection *selection = this->desktop->getSelection(); - this->selcon = new sigc::connection(selection->connectChanged( - sigc::mem_fun(this, &MeshTool::selection_changed) - )); + 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*)nullptr) - ) - )); + sigc::hide(sigc::bind(sigc::mem_fun(*this, &MeshTool::selection_changed), (Inkscape::Selection *)nullptr)))); sp_event_context_read(this, "show_handles"); sp_event_context_read(this, "edit_fill"); sp_event_context_read(this, "edit_stroke"); this->selection_changed(selection); - } -void MeshTool::set(const Inkscape::Preferences::Entry& value) { +void MeshTool::set(const Inkscape::Preferences::Entry &value) +{ Glib::ustring entry_name = value.getEntryName(); if (entry_name == "show_handles") { this->show_handles = value.getBool(true); @@ -212,22 +203,20 @@ void MeshTool::set(const Inkscape::Preferences::Entry& value) { } } -void -sp_mesh_context_select_next (ToolBase *event_context) +void sp_mesh_context_select_next(ToolBase *event_context) { GrDrag *drag = event_context->_grdrag; - g_assert (drag); + g_assert(drag); GrDragger *d = drag->select_next(); event_context->getDesktop()->scroll_to_point(d->point, 1.0); } -void -sp_mesh_context_select_prev (ToolBase *event_context) +void sp_mesh_context_select_prev(ToolBase *event_context) { GrDrag *drag = event_context->_grdrag; - g_assert (drag); + g_assert(drag); GrDragger *d = drag->select_prev(); @@ -237,12 +226,11 @@ sp_mesh_context_select_prev (ToolBase *event_context) /** Returns vector of control lines mouse is over. Returns only first if 'first' is true. */ -static std::vector<SPCtrlCurve *> -sp_mesh_context_over_line (MeshTool *rc, Geom::Point event_p, bool first = true) +static std::vector<SPCtrlCurve *> sp_mesh_context_over_line(MeshTool *rc, Geom::Point event_p, bool first = true) { const SPDesktop *desktop = rc->getDesktop(); - //Translate mouse point into proper coord system + // Translate mouse point into proper coord system rc->mousepoint_doc = desktop->w2d(event_p); GrDrag *drag = rc->_grdrag; @@ -250,14 +238,15 @@ sp_mesh_context_over_line (MeshTool *rc, Geom::Point event_p, bool first = true) std::vector<SPCtrlCurve *> selected; for (std::vector<SPCtrlLine *>::const_iterator l = drag->lines.begin(); l != drag->lines.end(); ++l) { - if (!SP_IS_CTRLCURVE(*l)) continue; + if (!SP_IS_CTRLCURVE(*l)) + continue; SPCtrlCurve *curve = SP_CTRLCURVE(*l); - Geom::BezierCurveN<3> b( curve->p0, curve->p1, curve->p2, curve->p3 ); - Geom::Coord coord = b.nearestTime( rc->mousepoint_doc ); // Coord == double - Geom::Point nearest = b( coord ); + Geom::BezierCurveN<3> b(curve->p0, curve->p1, curve->p2, curve->p3); + Geom::Coord coord = b.nearestTime(rc->mousepoint_doc); // Coord == double + Geom::Point nearest = b(coord); - double dist_screen = Geom::L2 (rc->mousepoint_doc - nearest) * desktop->current_zoom(); + double dist_screen = Geom::L2(rc->mousepoint_doc - nearest) * desktop->current_zoom(); if (dist_screen < rc->tolerance) { selected.push_back(curve); if (first) { @@ -268,13 +257,11 @@ sp_mesh_context_over_line (MeshTool *rc, Geom::Point event_p, bool first = true) return selected; } - /** 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*/) +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 @@ -283,12 +270,11 @@ static void sp_mesh_context_split_near_point(MeshTool *rc, SPItem *item, Geom:: const SPDesktop *desktop = rc->getDesktop(); - double tolerance = (double) rc->tolerance; + double tolerance = (double)rc->tolerance; - rc->get_drag()->addStopNearPoint (item, mouse_p, tolerance/desktop->current_zoom()); + rc->get_drag()->addStopNearPoint(item, mouse_p, tolerance / desktop->current_zoom()); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MESH, - _("Split mesh row/column")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MESH, _("Split mesh row/column")); rc->get_drag()->updateDraggers(); } @@ -296,10 +282,8 @@ static void sp_mesh_context_split_near_point(MeshTool *rc, SPItem *item, Geom:: /** Wrapper for various mesh operations that require a list of selected corner nodes. */ -void -sp_mesh_context_corner_operation (MeshTool *rc, MeshCornerOperation operation ) +void sp_mesh_context_corner_operation(MeshTool *rc, MeshCornerOperation operation) { - #ifdef DEBUG_MESH std::cout << "sp_mesh_corner_operation: entrance: " << operation << std::endl; #endif @@ -307,76 +291,76 @@ sp_mesh_context_corner_operation (MeshTool *rc, MeshCornerOperation operation ) SPDocument *doc = nullptr; GrDrag *drag = rc->_grdrag; - std::map<SPMeshGradient*, std::vector<guint> > points; - std::map<SPMeshGradient*, SPItem*> items; - std::map<SPMeshGradient*, Inkscape::PaintTarget> fill_or_stroke; + std::map<SPMeshGradient *, std::vector<guint>> points; + std::map<SPMeshGradient *, SPItem *> items; + std::map<SPMeshGradient *, Inkscape::PaintTarget> fill_or_stroke; // Get list of selected draggers for each mesh. // For all selected draggers (a dragger may include draggerables from different meshes). for (auto dragger : drag->selected) { // For all draggables of dragger (a draggable corresponds to a unique mesh). - for (auto d : dragger->draggables) { + for (auto d : dragger->draggables) { // Only mesh corners - if( d->point_type != POINT_MG_CORNER ) continue; + if (d->point_type != POINT_MG_CORNER) + continue; // Find the gradient - SPMeshGradient *gradient = SP_MESHGRADIENT( getGradient (d->item, d->fill_or_stroke) ); + SPMeshGradient *gradient = SP_MESHGRADIENT(getGradient(d->item, d->fill_or_stroke)); // Collect points together for same gradient - points[gradient].push_back( d->point_i ); + points[gradient].push_back(d->point_i); items[gradient] = d->item; - fill_or_stroke[gradient] = d->fill_or_stroke ? Inkscape::FOR_FILL: Inkscape::FOR_STROKE; + fill_or_stroke[gradient] = d->fill_or_stroke ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; } } // 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 ) { + 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 ); + 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 ); + 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 ); + 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 ); + 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] ); + noperation += mg->array.color_pick(iter->second, items[iter->first]); break; case MG_CORNER_INSERT: // std::cout << "INSERT" << std::endl; - noperation += mg->array.insert( iter->second ); + noperation += mg->array.insert(iter->second); break; default: std::cout << "sp_mesh_corner_operation: unknown operation" << std::endl; - } + } - if( noperation > 0 ) { - mg->array.write( mg ); + 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.")); drag->local_change = true; // Don't create new draggers. @@ -415,19 +399,15 @@ sp_mesh_context_corner_operation (MeshTool *rc, MeshCornerOperation operation ) // Not needed. Update is done via gr_drag_sel_modified(). // drag->updateDraggers(); - } - /** * Scale mesh to just fit into bbox of selected items. */ -void -sp_mesh_context_fit_mesh_in_bbox (MeshTool *rc) +void sp_mesh_context_fit_mesh_in_bbox(MeshTool *rc) { - #ifdef DEBUG_MESH - std::cout << "sp_mesh_context_fit_mesh_in_bbox: entrance: Entrance"<< std::endl; + std::cout << "sp_mesh_context_fit_mesh_in_bbox: entrance: Entrance" << std::endl; #endif const SPDesktop *desktop = rc->getDesktop(); @@ -439,20 +419,17 @@ sp_mesh_context_fit_mesh_in_bbox (MeshTool *rc) bool changed = false; auto itemlist = selection->items(); - for (auto i=itemlist.begin(); i!=itemlist.end(); ++i) { - + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; SPStyle *style = item->style; if (style) { - if (style->fill.isPaintserver()) { SPPaintServer *server = item->style->getFillPaintServer(); - if ( SP_IS_MESHGRADIENT(server) ) { - + if (SP_IS_MESHGRADIENT(server)) { Geom::OptRect item_bbox = item->geometricBounds(); SPMeshGradient *gradient = SP_MESHGRADIENT(server); - if (gradient->array.fill_box( item_bbox )) { + if (gradient->array.fill_box(item_bbox)) { changed = true; } } @@ -460,30 +437,27 @@ sp_mesh_context_fit_mesh_in_bbox (MeshTool *rc) if (style->stroke.isPaintserver()) { SPPaintServer *server = item->style->getStrokePaintServer(); - if ( SP_IS_MESHGRADIENT(server) ) { - + if (SP_IS_MESHGRADIENT(server)) { Geom::OptRect item_bbox = item->visualBounds(); SPMeshGradient *gradient = SP_MESHGRADIENT(server); - if (gradient->array.fill_box( item_bbox )) { + if (gradient->array.fill_box(item_bbox)) { changed = true; } } } - } } if (changed) { - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MESH, - _("Fit mesh inside bounding box")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_MESH, _("Fit mesh inside bounding box")); } } - /** Handles all keyboard and mouse input for meshs. Note: node/handle events are take care of elsewhere. */ -bool MeshTool::root_handler(GdkEvent* event) { +bool MeshTool::root_handler(GdkEvent *event) +{ static bool dragging; Inkscape::Selection *selection = desktop->getSelection(); @@ -496,467 +470,457 @@ bool MeshTool::root_handler(GdkEvent* event) { static_cast<Inkscape::PaintTarget>(prefs->getInt("/tools/mesh/newfillorstroke")); GrDrag *drag = this->_grdrag; - g_assert (drag); + g_assert(drag); gint ret = FALSE; switch (event->type) { - case GDK_2BUTTON_PRESS: + case GDK_2BUTTON_PRESS: #ifdef DEBUG_MESH - std::cout << "sp_mesh_context_root_handler: GDK_2BUTTON_PRESS" << std::endl; + 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 and no mesh, create new mesh for top selected object. + // Double click: + // If over a mesh line, divide mesh row/column + // If not over a line and no mesh, create new mesh for top selected object. - if ( event->button.button == 1 ) { + if (event->button.button == 1) { + // Are we over a mesh line? + std::vector<SPCtrlCurve *> over_line = + sp_mesh_context_over_line(this, Geom::Point(event->motion.x, event->motion.y)); - // Are we over a mesh line? - std::vector<SPCtrlCurve *> over_line = - sp_mesh_context_over_line(this, Geom::Point(event->motion.x, event->motion.y)); + if (!over_line.empty()) { + // 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, selection->items().front(), this->mousepoint_doc, + event->button.time); + } else { + // Create a new gradient with default coordinates. - if (!over_line.empty()) { - // 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, selection->items().front(), this->mousepoint_doc, event->button.time); - } else { - // Create a new gradient with default coordinates. + // Check if object already has mesh... if it does, + // don't create new mesh with click-drag. + bool has_mesh = false; + if (!selection->isEmpty()) { + SPStyle *style = selection->items().front()->style; + if (style) { + SPPaintServer *server = (fill_or_stroke_pref == Inkscape::FOR_FILL) + ? style->getFillPaintServer() + : style->getStrokePaintServer(); + if (server && SP_IS_MESHGRADIENT(server)) + has_mesh = true; + } + } - // Check if object already has mesh... if it does, - // don't create new mesh with click-drag. - bool has_mesh = false; - if (!selection->isEmpty()) { - SPStyle *style = selection->items().front()->style; - if (style) { - SPPaintServer *server = - (fill_or_stroke_pref == Inkscape::FOR_FILL) ? - style->getFillPaintServer(): - style->getStrokePaintServer(); - if (server && SP_IS_MESHGRADIENT(server)) - has_mesh = true; + if (!has_mesh) { + sp_mesh_new_default(*this); } } - if (!has_mesh) { - sp_mesh_new_default(*this); - } + ret = TRUE; } + break; - ret = TRUE; - } - break; - - case GDK_BUTTON_PRESS: + case GDK_BUTTON_PRESS: #ifdef DEBUG_MESH - std::cout << "sp_mesh_context_root_handler: GDK_BUTTON_PRESS" << std::endl; + std::cout << "sp_mesh_context_root_handler: GDK_BUTTON_PRESS" << std::endl; #endif - // Button down - // If mesh already exists, do rubber band selection. - // Else set origin for drag which will create a new gradient. - if ( event->button.button == 1 && !this->space_panning ) { - - // Are we over a mesh line? - std::vector<SPCtrlCurve *> over_line = - sp_mesh_context_over_line(this, Geom::Point(event->motion.x, event->motion.y), false); - - if (!over_line.empty()) { - for (auto it : over_line) { - SPItem *item = it->item; - Inkscape::PaintTarget fill_or_stroke = - it->is_fill ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; - GrDragger* dragger0 = drag->getDraggerFor(item, POINT_MG_CORNER, it->corner0, fill_or_stroke); - GrDragger* dragger1 = drag->getDraggerFor(item, POINT_MG_CORNER, it->corner1, fill_or_stroke); - bool add = (event->button.state & GDK_SHIFT_MASK); - bool toggle = (event->button.state & GDK_CONTROL_MASK); - if ( !add && !toggle ) { - drag->deselectAll(); + // Button down + // If mesh already exists, do rubber band selection. + // Else set origin for drag which will create a new gradient. + if (event->button.button == 1 && !this->space_panning) { + // Are we over a mesh line? + std::vector<SPCtrlCurve *> over_line = + sp_mesh_context_over_line(this, Geom::Point(event->motion.x, event->motion.y), false); + + if (!over_line.empty()) { + for (auto it : over_line) { + SPItem *item = it->item; + Inkscape::PaintTarget fill_or_stroke = it->is_fill ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; + GrDragger *dragger0 = drag->getDraggerFor(item, POINT_MG_CORNER, it->corner0, fill_or_stroke); + GrDragger *dragger1 = drag->getDraggerFor(item, POINT_MG_CORNER, it->corner1, fill_or_stroke); + bool add = (event->button.state & GDK_SHIFT_MASK); + bool toggle = (event->button.state & GDK_CONTROL_MASK); + if (!add && !toggle) { + drag->deselectAll(); + } + drag->setSelected(dragger0, true, !toggle); + drag->setSelected(dragger1, true, !toggle); } - drag->setSelected( dragger0, true, !toggle ); - drag->setSelected( dragger1, true, !toggle ); + ret = true; + break; // To avoid putting the following code in an else block. } - ret = true; - break; // To avoid putting the following code in an else block. - } - 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); - // Check if object already has mesh... if it does, - // don't create new mesh with click-drag. - bool has_mesh = false; - if (!selection->isEmpty()) { - SPStyle *style = selection->items().front()->style; - if (style) { - SPPaintServer *server = - (fill_or_stroke_pref == Inkscape::FOR_FILL) ? - style->getFillPaintServer(): - style->getStrokePaintServer(); - if (server && SP_IS_MESHGRADIENT(server)) - has_mesh = true; - } - } + Geom::Point button_w(event->button.x, event->button.y); - if (has_mesh) { - Inkscape::Rubberband::get(desktop)->start(desktop, button_dt); - } + // 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; 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); - } + dragging = true; - if (!selection->isEmpty()) { - SnapManager &m = desktop->namedview->snap_manager; - m.setup(desktop); - m.freeSnapReturnByRef(button_dt, Inkscape::SNAPSOURCE_NODE_HANDLE); - m.unSetup(); - } + Geom::Point button_dt = desktop->w2d(button_w); + // Check if object already has mesh... if it does, + // don't create new mesh with click-drag. + bool has_mesh = false; + if (!selection->isEmpty()) { + SPStyle *style = selection->items().front()->style; + if (style) { + SPPaintServer *server = (fill_or_stroke_pref == Inkscape::FOR_FILL) + ? style->getFillPaintServer() + : style->getStrokePaintServer(); + if (server && SP_IS_MESHGRADIENT(server)) + has_mesh = true; + } + } - this->origin = button_dt; + if (has_mesh) { + Inkscape::Rubberband::get(desktop)->start(desktop, button_dt); + } - ret = TRUE; - } - break; + // 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); + } - 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 { - // Do nothing. For a linear/radial gradient we follow the drag, updating the - // gradient as the end node is dragged. For a mesh gradient, the gradient is always - // created to fill the object when the drag ends. - } + if (!selection->isEmpty()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + m.freeSnapReturnByRef(button_dt, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + } - gobble_motion_events(GDK_BUTTON1_MASK); + this->origin = button_dt; - ret = TRUE; - } else { - // Not dragging + ret = TRUE; + } + break; - // Do snapping - if (!drag->mouseOver() && !selection->isEmpty()) { - SnapManager &m = desktop->namedview->snap_manager; - m.setup(desktop); + 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); - 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 - std::vector<SPCtrlCurve *> over_line = - sp_mesh_context_over_line(this, Geom::Point(event->motion.x, event->motion.y)); - - if (this->cursor_addnode && over_line.empty()) { - this->cursor_shape = cursor_gradient_xpm; - this->sp_event_context_update_cursor(); - this->cursor_addnode = false; - } else if (!this->cursor_addnode && !over_line.empty()) { - this->cursor_shape = cursor_gradient_add_xpm; - this->sp_event_context_update_cursor(); - this->cursor_addnode = true; - } - } - break; + 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 { + // Do nothing. For a linear/radial gradient we follow the drag, updating the + // gradient as the end node is dragged. For a mesh gradient, the gradient is always + // created to fill the object when the drag ends. + } - case GDK_BUTTON_RELEASE: + gobble_motion_events(GDK_BUTTON1_MASK); -#ifdef DEBUG_MESH - std::cout << "sp_mesh_context_root_handler: GDK_BUTTON_RELEASE" << std::endl; -#endif + ret = TRUE; + } else { + // Not dragging - this->xp = this->yp = 0; + // Do snapping + if (!drag->mouseOver() && !selection->isEmpty()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); - if ( event->button.button == 1 && !this->space_panning ) { + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point const motion_dt = this->desktop->w2d(motion_w); - // Check if over line - std::vector<SPCtrlCurve *> over_line = - sp_mesh_context_over_line(this, Geom::Point(event->motion.x, event->motion.y)); + m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE)); + m.unSetup(); + } - if ( (event->button.state & GDK_CONTROL_MASK) && (event->button.state & GDK_MOD1_MASK ) ) { - if (!over_line.empty()) { - sp_mesh_context_split_near_point(this, over_line[0]->item, - this->mousepoint_doc, 0); - ret = TRUE; + // 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 ); } - } else { - dragging = false; - // unless clicked with Ctrl (to enable Ctrl+doubleclick). - if (event->button.state & GDK_CONTROL_MASK) { - ret = TRUE; - break; + // Change cursor shape if over line + std::vector<SPCtrlCurve *> over_line = + sp_mesh_context_over_line(this, Geom::Point(event->motion.x, event->motion.y)); + + if (this->cursor_addnode && over_line.empty()) { + this->cursor_shape = cursor_gradient_xpm; + this->sp_event_context_update_cursor(); + this->cursor_addnode = false; + } else if (!this->cursor_addnode && !over_line.empty()) { + this->cursor_shape = cursor_gradient_add_xpm; + this->sp_event_context_update_cursor(); + this->cursor_addnode = true; } + } + break; - if (!this->within_tolerance) { + case GDK_BUTTON_RELEASE: - // Check if object already has mesh... if it does, - // don't create new mesh with click-drag. - bool has_mesh = false; - if (!selection->isEmpty()) { - SPStyle *style = selection->items().front()->style; - if (style) { - SPPaintServer *server = - (fill_or_stroke_pref == Inkscape::FOR_FILL) ? - style->getFillPaintServer(): - style->getStrokePaintServer(); - if (server && SP_IS_MESHGRADIENT(server)) - has_mesh = true; - } +#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 + std::vector<SPCtrlCurve *> over_line = + sp_mesh_context_over_line(this, Geom::Point(event->motion.x, event->motion.y)); + + if ((event->button.state & GDK_CONTROL_MASK) && (event->button.state & GDK_MOD1_MASK)) { + if (!over_line.empty()) { + sp_mesh_context_split_near_point(this, over_line[0]->item, this->mousepoint_doc, 0); + ret = TRUE; } + } else { + dragging = false; - if (!has_mesh) { - sp_mesh_new_default(*this); - } else { + // unless clicked with Ctrl (to enable Ctrl+doubleclick). + if (event->button.state & GDK_CONTROL_MASK) { + ret = TRUE; + break; + } - // we've been dragging, either create a new gradient - // or rubberband-select if we have rubberband - Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop); + if (!this->within_tolerance) { + // Check if object already has mesh... if it does, + // don't create new mesh with click-drag. + bool has_mesh = false; + if (!selection->isEmpty()) { + SPStyle *style = selection->items().front()->style; + if (style) { + SPPaintServer *server = (fill_or_stroke_pref == Inkscape::FOR_FILL) + ? style->getFillPaintServer() + : style->getStrokePaintServer(); + if (server && SP_IS_MESHGRADIENT(server)) + has_mesh = true; + } + } - if (r->is_started() && !this->within_tolerance) { - // this was a rubberband drag - if (r->getMode() == RUBBERBAND_MODE_RECT) { - Geom::OptRect const b = r->getRectangle(); - if (!(event->button.state & GDK_SHIFT_MASK)) { - drag->deselectAll(); + if (!has_mesh) { + sp_mesh_new_default(*this); + } else { + // we've been dragging, either create a new gradient + // 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(); + if (!(event->button.state & GDK_SHIFT_MASK)) { + drag->deselectAll(); + } + drag->selectRect(*b); } - drag->selectRect(*b); } } - } - } else if (this->item_to_select) { - if (!over_line.empty()) { - // 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 if (this->item_to_select) { + if (!over_line.empty()) { + // Clicked on an existing mesh line, don't change selection. This stops + // possible change in selection during a double click with overlapping objects } else { - drag->deselectAll(); - selection->set(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 { + drag->deselectAll(); + selection->set(this->item_to_select); + } } - } - } else { - if (!over_line.empty()) { - // Clicked on an existing mesh line, don't change selection. This stops - // possible change in selection during a double click with overlapping objects } else { - // click in an empty space; do the same as Esc - if (!drag->selected.empty()) { - drag->deselectAll(); + if (!over_line.empty()) { + // Clicked on an existing mesh line, don't change selection. This stops + // possible change in selection during a double click with overlapping objects } else { - selection->clear(); + // click in an empty space; do the same as Esc + if (!drag->selected.empty()) { + drag->deselectAll(); + } else { + selection->clear(); + } } } + + this->item_to_select = nullptr; + ret = TRUE; } - this->item_to_select = nullptr; - ret = TRUE; + Inkscape::Rubberband::get(desktop)->stop(); } + break; - Inkscape::Rubberband::get(desktop)->stop(); - } - break; - - case GDK_KEY_PRESS: + case GDK_KEY_PRESS: #ifdef DEBUG_MESH - std::cout << "sp_mesh_context_root_handler: GDK_KEY_PRESS" << std::endl; + std::cout << "sp_mesh_context_root_handler: GDK_KEY_PRESS" << std::endl; #endif - // FIXME: tip - switch (get_latin_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; + // FIXME: tip + switch (get_latin_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_A: + case GDK_KEY_a: + if (MOD__CTRL_ONLY(event) && drag->isNonEmpty()) { + drag->selectAll(); + ret = TRUE; + } + break; - case GDK_KEY_Escape: - if (!drag->selected.empty()) { - drag->deselectAll(); - } else { - selection->clear(); - } + case GDK_KEY_Escape: + if (!drag->selected.empty()) { + drag->deselectAll(); + } else { + selection->clear(); + } - ret = TRUE; - //TODO: make dragging escapable by Esc - break; + ret = TRUE; + // TODO: make dragging escapable by Esc + break; - // Mesh Operations -------------------------------------------- + // Mesh Operations -------------------------------------------- - case GDK_KEY_Insert: - case GDK_KEY_KP_Insert: - // with any modifiers: - sp_mesh_context_corner_operation ( this, MG_CORNER_INSERT ); - ret = TRUE; - break; + case GDK_KEY_Insert: + case GDK_KEY_KP_Insert: + // with any modifiers: + sp_mesh_context_corner_operation(this, MG_CORNER_INSERT); + ret = TRUE; + break; - case GDK_KEY_i: - case GDK_KEY_I: - if (MOD__SHIFT_ONLY(event)) { - // Shift+I - insert corners (alternate keybinding for keyboards - // that don't have the Insert key) - sp_mesh_context_corner_operation ( this, MG_CORNER_INSERT ); - ret = TRUE; - } - break; + case GDK_KEY_i: + case GDK_KEY_I: + if (MOD__SHIFT_ONLY(event)) { + // Shift+I - insert corners (alternate keybinding for keyboards + // that don't have the Insert key) + sp_mesh_context_corner_operation(this, MG_CORNER_INSERT); + ret = TRUE; + } + break; - case GDK_KEY_Delete: - case GDK_KEY_KP_Delete: - case GDK_KEY_BackSpace: - if ( !drag->selected.empty() ) { - ret = TRUE; - } - break; + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + if (!drag->selected.empty()) { + ret = TRUE; + } + break; - 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_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_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_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_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; + 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: + ret = drag->key_press_handler(event); + break; } - break; - default: - ret = drag->key_press_handler(event); break; - } - break; - - case GDK_KEY_RELEASE: + case GDK_KEY_RELEASE: #ifdef DEBUG_MESH - std::cout << "sp_mesh_context_root_handler: GDK_KEY_RELEASE" << std::endl; + std::cout << "sp_mesh_context_root_handler: GDK_KEY_RELEASE" << std::endl; #endif - switch (get_latin_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(); + switch (get_latin_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; - } - break; - default: - break; } if (!ret) { - ret = ToolBase::root_handler(event); + ret = ToolBase::root_handler(event); } return ret; } // Creates a new mesh gradient. -static void sp_mesh_new_default(MeshTool &rc) { +static void sp_mesh_new_default(MeshTool &rc) +{ const SPDesktop *desktop = rc.getDesktop(); Inkscape::Selection *selection = desktop->getSelection(); SPDocument *document = desktop->getDocument(); if (!selection->isEmpty()) { - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Inkscape::PaintTarget fill_or_stroke_pref = static_cast<Inkscape::PaintTarget>(prefs->getInt("/tools/mesh/newfillorstroke")); @@ -964,24 +928,23 @@ static void sp_mesh_new_default(MeshTool &rc) { // Ensure mesh is immediately editable. // Editing both fill and stroke at same time doesn't work well so avoid. if (fill_or_stroke_pref == Inkscape::FOR_FILL) { - prefs->setBool("/tools/mesh/edit_fill", true ); + prefs->setBool("/tools/mesh/edit_fill", true); prefs->setBool("/tools/mesh/edit_stroke", false); } else { - prefs->setBool("/tools/mesh/edit_fill", false); - prefs->setBool("/tools/mesh/edit_stroke", true ); + prefs->setBool("/tools/mesh/edit_fill", false); + prefs->setBool("/tools/mesh/edit_stroke", true); } -// HACK: reset fill-opacity - that 0.75 is annoying; BUT remove this when we have an opacity slider for all tabs + // 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"); Inkscape::XML::Document *xml_doc = document->getReprDoc(); SPDefs *defs = document->getDefs(); - auto items= selection->items(); - for(auto i=items.begin();i!=items.end();++i){ - - //FIXME: see above + auto items = selection->items(); + for (auto i = items.begin(); i != items.end(); ++i) { + // FIXME: see above sp_repr_css_change_recursive((*i)->getRepr(), css, "style"); // Create mesh element @@ -996,15 +959,14 @@ static void sp_mesh_new_default(MeshTool &rc) { // Get corresponding object SPMeshGradient *mg = static_cast<SPMeshGradient *>(document->getObjectByRepr(repr)); - mg->array.create(mg, *i, (fill_or_stroke_pref == Inkscape::FOR_FILL) ? - (*i)->geometricBounds() : (*i)->visualBounds()); + mg->array.create( + mg, *i, (fill_or_stroke_pref == Inkscape::FOR_FILL) ? (*i)->geometricBounds() : (*i)->visualBounds()); bool isText = SP_IS_TEXT(*i); - sp_style_set_property_url(*i, - ((fill_or_stroke_pref == Inkscape::FOR_FILL) ? "fill":"stroke"), - mg, isText); + sp_style_set_property_url(*i, ((fill_or_stroke_pref == Inkscape::FOR_FILL) ? "fill" : "stroke"), mg, + isText); - (*i)->requestModified(SP_OBJECT_MODIFIED_FLAG|SP_OBJECT_STYLE_MODIFIED_FLAG); + (*i)->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); } if (css) { @@ -1016,19 +978,19 @@ static void sp_mesh_new_default(MeshTool &rc) { // status text; we do not track coords because this branch is run once, not all the time // during drag - int n_objects = (int) boost::distance(selection->items()); + int n_objects = (int)boost::distance(selection->items()); 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); + 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 { - desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>objects</b> on which to create gradient.")); + desktop->getMessageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>objects</b> on which to create gradient.")); } - -} -} -} } +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/mesh-tool.h b/src/ui/tools/mesh-tool.h index 4964a022a45ba5df0bab8fc32492f831466848ba..50b35fcfc6fdfae8edcbf8d77bbbef13bddb9f59 100644 --- a/src/ui/tools/mesh-tool.h +++ b/src/ui/tools/mesh-tool.h @@ -20,18 +20,20 @@ #include <cstddef> #include <sigc++/sigc++.h> -#include "ui/tools/tool-base.h" #include "object/sp-mesh-array.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) +#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 { +class MeshTool : public ToolBase +{ public: MeshTool(); ~MeshTool() override; @@ -46,35 +48,32 @@ public: static const std::string prefsPath; void setup() override; - void set(const Inkscape::Preferences::Entry& val) override; - bool root_handler(GdkEvent* event) override; + void set(const Inkscape::Preferences::Entry &val) override; + bool root_handler(GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; private: - void selection_changed(Inkscape::Selection* sel); + void selection_changed(Inkscape::Selection *sel); bool cursor_addnode; bool node_added; bool show_handles; bool edit_fill; bool edit_stroke; - - }; void sp_mesh_context_select_next(ToolBase *event_context); void sp_mesh_context_select_prev(ToolBase *event_context); -void sp_mesh_context_corner_operation(MeshTool *event_context, MeshCornerOperation operation ); +void sp_mesh_context_corner_operation(MeshTool *event_context, MeshCornerOperation operation); void sp_mesh_context_fit_mesh_in_bbox(MeshTool *event_context); -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif // SEEN_SP_MESH_CONTEXT_H - /* Local Variables: mode:c++ diff --git a/src/ui/tools/node-tool.cpp b/src/ui/tools/node-tool.cpp index d5787385f1b1a4fca02b27f891a9e3175e5fc858..4dcfe21e22a946a3ce4f1fe0984ef3a65315f5ff 100644 --- a/src/ui/tools/node-tool.cpp +++ b/src/ui/tools/node-tool.cpp @@ -11,30 +11,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <iomanip> +#include "ui/tools/node-tool.h" -#include <glibmm/ustring.h> -#include <glib/gi18n.h> #include <gdk/gdkkeysyms.h> - - +#include <glib/gi18n.h> +#include <glibmm/ustring.h> +#include <iomanip> #include "desktop.h" -#include "document.h" -#include "message-context.h" -#include "selection-chemistry.h" -#include "selection.h" -#include "snap.h" - #include "display/canvas-bpath.h" #include "display/curve.h" #include "display/sp-canvas-group.h" - +#include "document.h" +#include "include/macros.h" #include "live_effects/effect.h" #include "live_effects/lpeobject.h" - -#include "include/macros.h" - +#include "message-context.h" #include "object/sp-clippath.h" #include "object/sp-item-group.h" #include "object/sp-mask.h" @@ -42,11 +34,12 @@ #include "object/sp-path.h" #include "object/sp-shape.h" #include "object/sp-text.h" - +#include "selection-chemistry.h" +#include "selection.h" +#include "snap.h" +#include "ui/control-manager.h" #include "ui/pixmaps/cursor-node-d.xpm" #include "ui/pixmaps/cursor-node.xpm" - -#include "ui/control-manager.h" #include "ui/shape-editor.h" // temporary! #include "ui/tool/control-point-selection.h" #include "ui/tool/curve-drag-point.h" @@ -55,7 +48,6 @@ #include "ui/tool/path-manipulator.h" #include "ui/tool/selector.h" #include "ui/tools-switch.h" -#include "ui/tools/node-tool.h" #include "ui/tools/tool-base.h" /** @struct NodeTool @@ -121,7 +113,8 @@ namespace Inkscape { namespace UI { namespace Tools { -const std::string& NodeTool::getPrefsPath() { +const std::string &NodeTool::getPrefsPath() +{ return NodeTool::prefsPath; } @@ -149,13 +142,11 @@ NodeTool::NodeTool() , 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( - d->getControls(), SP_TYPE_CANVAS_GROUP, nullptr)); + return reinterpret_cast<SPCanvasGroup *>(sp_canvas_item_new(d->getControls(), SP_TYPE_CANVAS_GROUP, nullptr)); } void destroy_group(SPCanvasGroup *g) @@ -163,7 +154,8 @@ void destroy_group(SPCanvasGroup *g) sp_canvas_item_destroy(SP_CANVAS_ITEM(g)); } -NodeTool::~NodeTool() { +NodeTool::~NodeTool() +{ this->enableGrDrag(false); if (this->flash_tempitem) { @@ -173,7 +165,7 @@ NodeTool::~NodeTool() { this->desktop->remove_temporary_canvasitem(hp); } this->_selection_changed_connection.disconnect(); - //this->_selection_modified_connection.disconnect(); + // this->_selection_modified_connection.disconnect(); this->_mouseover_changed_connection.disconnect(); this->_sizeUpdatedConn.disconnect(); @@ -192,7 +184,8 @@ NodeTool::~NodeTool() { forced_redraws_stop(); } -void NodeTool::setup() { +void NodeTool::setup() +{ ToolBase::setup(); this->_path_data = new Inkscape::UI::PathSharedData(); @@ -215,16 +208,14 @@ void NodeTool::setup() { Inkscape::Selection *selection = this->desktop->getSelection(); this->_selection_changed_connection.disconnect(); - this->_selection_changed_connection = - selection->connectChanged(sigc::mem_fun(this, &NodeTool::selection_changed)); + this->_selection_changed_connection = selection->connectChanged(sigc::mem_fun(this, &NodeTool::selection_changed)); this->_mouseover_changed_connection.disconnect(); - this->_mouseover_changed_connection = + 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->_sizeUpdatedConn = + ControlManager::getManager().connectCtrlSizeChanged(sigc::mem_fun(this, &NodeTool::handleControlUiStyleChange)); if (this->_transform_handle_group) { this->_selected_nodes = new Inkscape::UI::ControlPointSelection(this->desktop, this->_transform_handle_group); } @@ -236,22 +227,14 @@ void NodeTool::setup() { 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*)nullptr - ) - ); + sigc::bind(sigc::mem_fun(*this->desktop, &SPDesktop::emitToolSubselectionChanged), (void *)nullptr)); this->_selected_nodes->signal_selection_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*)nullptr - ))) - ); + sigc::hide(sigc::hide(sigc::bind(sigc::mem_fun(this, &NodeTool::update_tip), (GdkEvent *)nullptr)))); this->cursor_drag = false; this->show_transform_handles = true; @@ -289,7 +272,7 @@ void NodeTool::setup() { } // Clean selection on tool change -void NodeTool::finish() +void NodeTool::finish() { this->_selected_nodes->clear(); ToolBase::finish(); @@ -301,7 +284,7 @@ void sp_update_helperpath(SPDesktop *desktop) if (!desktop || !tools_isactive(desktop, TOOLS_NODES)) { return; } - Inkscape::UI::Tools::NodeTool *nt = static_cast<Inkscape::UI::Tools::NodeTool*>(desktop->event_context); + Inkscape::UI::Tools::NodeTool *nt = static_cast<Inkscape::UI::Tools::NodeTool *>(desktop->event_context); Inkscape::Selection *selection = desktop->getSelection(); for (auto hp : nt->_helperpath_tmpitem) { desktop->remove_temporary_canvasitem(hp); @@ -335,8 +318,8 @@ void sp_update_helperpath(SPDesktop *desktop) sp_canvas_item_affine_absolute(helperpath, lpeitem->i2dt_affine()); nt->_helperpath_tmpitem.emplace_back(desktop->add_temporary_canvasitem(helperpath, 0)); SPCanvasItem *helperpath_back = sp_canvas_bpath_new(desktop->getTempGroup(), c.get(), true); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(helperpath_back), 0xFFFFFF33, 3.0, SP_STROKE_LINEJOIN_MITER, - SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(helperpath_back), 0xFFFFFF33, 3.0, + SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(helperpath_back), 0, SP_WIND_RULE_NONZERO); sp_canvas_item_affine_absolute(helperpath_back, lpeitem->i2dt_affine()); nt->_helperpath_tmpitem.emplace_back(desktop->add_temporary_canvasitem(helperpath_back, 0)); @@ -346,7 +329,8 @@ void sp_update_helperpath(SPDesktop *desktop) } } -void NodeTool::set(const Inkscape::Preferences::Entry& value) { +void NodeTool::set(const Inkscape::Preferences::Entry &value) +{ Glib::ustring entry_name = value.getEntryName(); if (entry_name == "show_handles") { @@ -366,12 +350,10 @@ void NodeTool::set(const Inkscape::Preferences::Entry& value) { 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); + 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); + 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); @@ -384,9 +366,8 @@ void NodeTool::set(const Inkscape::Preferences::Entry& value) { } /** Recursively collect ShapeRecords */ -static -void gather_items(NodeTool *nt, SPItem *base, SPObject *obj, Inkscape::UI::ShapeRole role, - std::set<Inkscape::UI::ShapeRecord> &s) +static void gather_items(NodeTool *nt, SPItem *base, SPObject *obj, Inkscape::UI::ShapeRole role, + std::set<Inkscape::UI::ShapeRecord> &s) { using namespace Inkscape::UI; @@ -394,9 +375,9 @@ void gather_items(NodeTool *nt, SPItem *base, SPObject *obj, Inkscape::UI::Shape return; } - //XML Tree being used directly here while it shouldn't be. + // XML Tree being used directly here while it shouldn't be. if (role != SHAPE_ROLE_NORMAL && (SP_IS_GROUP(obj) || SP_IS_OBJECTGROUP(obj))) { - for (auto& c: obj->children) { + for (auto &c : obj->children) { gather_items(nt, base, &c, role, s); } } else if (SP_IS_ITEM(obj)) { @@ -421,25 +402,25 @@ void gather_items(NodeTool *nt, SPItem *base, SPObject *obj, Inkscape::UI::Shape } } -void NodeTool::selection_changed(Inkscape::Selection *sel) { +void NodeTool::selection_changed(Inkscape::Selection *sel) +{ using namespace Inkscape::UI; std::set<ShapeRecord> shapes; - auto items= sel->items(); - for(auto i=items.begin();i!=items.end();++i){ + auto items = sel->items(); + for (auto i = items.begin(); i != items.end(); ++i) { SPObject *obj = *i; if (SP_IS_ITEM(obj)) { - gather_items(this, nullptr, static_cast<SPItem*>(obj), SHAPE_ROLE_NORMAL, shapes); + gather_items(this, nullptr, 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(); ) - { + for (boost::ptr_map<SPItem *, ShapeEditor>::iterator i = this->_shape_editors.begin(); + i != this->_shape_editors.end();) { ShapeRecord s; s.object = dynamic_cast<SPObject *>(i->first); @@ -450,7 +431,7 @@ void NodeTool::selection_changed(Inkscape::Selection *sel) { } } - for (const auto & r : shapes) { + for (const auto &r : shapes) { if ((SP_IS_SHAPE(r.object) || SP_IS_TEXT(r.object) || SP_IS_GROUP(r.object) || SP_IS_OBJECTGROUP(r.object)) && this->_shape_editors.find(SP_ITEM(r.object)) == this->_shape_editors.end()) { ShapeEditor *si = new ShapeEditor(this->desktop, r.edit_transform); @@ -470,7 +451,8 @@ void NodeTool::selection_changed(Inkscape::Selection *sel) { // this->desktop->updateNow(); } -bool NodeTool::root_handler(GdkEvent* event) { +bool NodeTool::root_handler(GdkEvent *event) +{ /* things to handle here: * 1. selection of items * 2. passing events to manipulators @@ -494,166 +476,166 @@ bool NodeTool::root_handler(GdkEvent* event) { if (this->_selected_nodes->event(this, event)) { return true; } - switch (event->type) - { - case GDK_MOTION_NOTIFY: { - sp_update_helperpath(desktop); - SPItem *over_item = nullptr; - over_item = sp_event_context_find_item(desktop, event_point(event->button), FALSE, TRUE); - - Geom::Point const motion_w(event->motion.x, event->motion.y); - Geom::Point const motion_dt(this->desktop->w2d(motion_w)); - - SnapManager &m = this->desktop->namedview->snap_manager; - - // We will show a pre-snap indication for when the user adds a node through double-clicking - // Adding a node will only work when a path has been selected; if that's not the case then snapping is useless - if (!this->desktop->selection->isEmpty()) { - if (!(event->motion.state & GDK_SHIFT_MASK)) { - m.setup(this->desktop); - Inkscape::SnapCandidatePoint scp(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE); - m.preSnap(scp, true); - m.unSetup(); + switch (event->type) { + case GDK_MOTION_NOTIFY: { + sp_update_helperpath(desktop); + SPItem *over_item = nullptr; + over_item = sp_event_context_find_item(desktop, event_point(event->button), FALSE, TRUE); + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point const motion_dt(this->desktop->w2d(motion_w)); + + SnapManager &m = this->desktop->namedview->snap_manager; + + // We will show a pre-snap indication for when the user adds a node through double-clicking + // Adding a node will only work when a path has been selected; if that's not the case then snapping is + // useless + if (!this->desktop->selection->isEmpty()) { + if (!(event->motion.state & GDK_SHIFT_MASK)) { + m.setup(this->desktop); + Inkscape::SnapCandidatePoint scp(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE); + m.preSnap(scp, true); + m.unSetup(); + } } - } - if (over_item && 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")) { - // We want to reset flashed item to can highligh again previous one - if (!over_item && this->flashed_item) { - this->flashed_item = nullptr; - break; - } - if (!over_item || over_item == this->flashed_item) { - break; + if (over_item && 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")) { + // We want to reset flashed item to can highligh again previous one + if (!over_item && this->flashed_item) { + this->flashed_item = nullptr; + break; + } + if (!over_item || over_item == this->flashed_item) { + break; + } - if (!prefs->getBool("/tools/nodes/pathflash_selected") && over_item && selection->includes(over_item)) { - break; - } + if (!prefs->getBool("/tools/nodes/pathflash_selected") && over_item && selection->includes(over_item)) { + break; + } - if (this->flash_tempitem) { - desktop->remove_temporary_canvasitem(this->flash_tempitem); - this->flash_tempitem = nullptr; - this->flashed_item = nullptr; - } + if (this->flash_tempitem) { + desktop->remove_temporary_canvasitem(this->flash_tempitem); + this->flash_tempitem = nullptr; + this->flashed_item = nullptr; + } - auto shape = dynamic_cast<SPShape const *>(over_item); - if (!shape) { - break; // for now, handle only shapes - } + auto shape = dynamic_cast<SPShape const *>(over_item); + if (!shape) { + break; // for now, handle only shapes + } - this->flashed_item = over_item; - auto c = SPCurve::copy(shape->curveForEdit()); + this->flashed_item = over_item; + auto c = SPCurve::copy(shape->curveForEdit()); - if (!c) { - break; // break out when curve doesn't exist - } + if (!c) { + break; // break out when curve doesn't exist + } - c->transform(over_item->i2dt_affine()); - SPCanvasItem *flash = sp_canvas_bpath_new(desktop->getTempGroup(), c.get(), true); + c->transform(over_item->i2dt_affine()); + SPCanvasItem *flash = sp_canvas_bpath_new(desktop->getTempGroup(), c.get(), true); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(flash), - //prefs->getInt("/tools/nodes/highlight_color", 0xff0000ff), 1.0, - over_item->highlight_color(), 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)); - } + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(flash), + // prefs->getInt("/tools/nodes/highlight_color", 0xff0000ff), 1.0, + over_item->highlight_color(), 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)); + } } 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_latin_keyval(&event->key)) - { - case GDK_KEY_Escape: // deselect everything - if (this->_selected_nodes->empty()) { - Inkscape::SelectionHelper::selectNone(desktop); - } else { - this->_selected_nodes->clear(); + // otherwise some features cease to work + + case GDK_KEY_PRESS: + switch (get_latin_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); + // 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; - } + case GDK_KEY_RELEASE: + // ink_node_tool_update_tip(nt, event); + this->update_tip(event); 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; - - case GDK_BUTTON_RELEASE: - if (this->_selector->doubleClicked()) { - // If the selector received the doubleclick event, then we're at some distance from - // the path; otherwise, the doubleclick event would have been received by - // CurveDragPoint; we will insert nodes into the path anyway but only if we can snap - // to the path. Otherwise the position would not be very well defined. - if (!(event->motion.state & GDK_SHIFT_MASK)) { - Geom::Point const motion_w(event->motion.x, event->motion.y); - Geom::Point const motion_dt(this->desktop->w2d(motion_w)); - - SnapManager &m = this->desktop->namedview->snap_manager; - m.setup(this->desktop); - Inkscape::SnapCandidatePoint scp(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE); - Inkscape::SnappedPoint sp = m.freeSnap(scp, Geom::OptRect(), true); - m.unSetup(); - - if (sp.getSnapped()) { - // The first click of the double click will have cleared the path selection, because - // we clicked aside of the path. We need to undo this on double click - Inkscape::Selection *selection = desktop->getSelection(); - selection->addList(_previous_selection); - - // The selection has been restored, and the signal selection_changed has been emitted, - // which has again forced a restore of the _mmap variable of the MultiPathManipulator (this->_multipath) - // Now we can insert the new nodes as if nothing has happened! - this->_multipath->insertNode(this->desktop->d2w(sp.getPoint())); + case GDK_BUTTON_RELEASE: + if (this->_selector->doubleClicked()) { + // If the selector received the doubleclick event, then we're at some distance from + // the path; otherwise, the doubleclick event would have been received by + // CurveDragPoint; we will insert nodes into the path anyway but only if we can snap + // to the path. Otherwise the position would not be very well defined. + if (!(event->motion.state & GDK_SHIFT_MASK)) { + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point const motion_dt(this->desktop->w2d(motion_w)); + + SnapManager &m = this->desktop->namedview->snap_manager; + m.setup(this->desktop); + Inkscape::SnapCandidatePoint scp(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE); + Inkscape::SnappedPoint sp = m.freeSnap(scp, Geom::OptRect(), true); + m.unSetup(); + + if (sp.getSnapped()) { + // The first click of the double click will have cleared the path selection, because + // we clicked aside of the path. We need to undo this on double click + Inkscape::Selection *selection = desktop->getSelection(); + selection->addList(_previous_selection); + + // The selection has been restored, and the signal selection_changed has been emitted, + // which has again forced a restore of the _mmap variable of the MultiPathManipulator + // (this->_multipath) Now we can insert the new nodes as if nothing has happened! + this->_multipath->insertNode(this->desktop->d2w(sp.getPoint())); + } } } - } - break; + break; - default: - break; + default: + break; } // we realy dont want to stop any node operation we want to success all even the time consume it return ToolBase::root_handler(event); } -void NodeTool::update_tip(GdkEvent *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); @@ -665,11 +647,11 @@ void NodeTool::update_tip(GdkEvent *event) { 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")); + 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")); + C_("Node tool tip", "<b>Shift</b>: drag to add nodes to the selection")); } return; @@ -682,8 +664,7 @@ void NodeTool::update_tip(GdkEvent *event) { if (sz != 0) { // TODO: Use Glib::ustring::compose and remove the useless copy after string freeze char *nodestring_temp = g_strdup_printf( - ngettext("<b>%u of %u</b> node selected.", "<b>%u of %u</b> nodes selected.", total), - sz, total); + ngettext("<b>%u of %u</b> node selected.", "<b>%u of %u</b> nodes selected.", total), sz, total); Glib::ustring nodestring(nodestring_temp); g_free(nodestring_temp); @@ -707,33 +688,32 @@ void NodeTool::update_tip(GdkEvent *event) { 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)"), + char *dyntip = g_strdup_printf( + C_("Node tool tip", "%s Drag to select nodes, click to edit only this object (more: Shift)"), nodestring.c_str()); 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.c_str()); + char *dyntip = g_strdup_printf(C_("Node tool tip", "%s Drag to select nodes, click clear the selection"), + nodestring.c_str()); this->message_context->set(Inkscape::NORMAL_MESSAGE, dyntip); g_free(dyntip); } } 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")); + 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")); + 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)")); + 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")); + this->message_context->set(Inkscape::NORMAL_MESSAGE, C_("Node tool tip", "Drag to select objects to edit")); } } } @@ -741,14 +721,15 @@ void NodeTool::update_tip(GdkEvent *event) { /** * @param sel Area in desktop coordinates */ -void NodeTool::select_area(Geom::Rect const &sel, GdkEventButton *event) { +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; auto sel_doc = desktop->dt2doc() * sel; - std::vector<SPItem*> items = this->desktop->getDocument()->getItemsInBox(this->desktop->dkey, sel_doc); + std::vector<SPItem *> items = this->desktop->getDocument()->getItemsInBox(this->desktop->dkey, sel_doc); selection->setList(items); } else { if (!held_shift(*event)) { @@ -759,9 +740,10 @@ void NodeTool::select_area(Geom::Rect const &sel, GdkEventButton *event) { } } -void NodeTool::select_point(Geom::Point const &/*sel*/, GdkEventButton *event) { +void NodeTool::select_point(Geom::Point const & /*sel*/, GdkEventButton *event) +{ using namespace Inkscape::UI; // pull in event helpers - + if (!event) { return; } @@ -772,8 +754,8 @@ void NodeTool::select_point(Geom::Point const &/*sel*/, GdkEventButton *event) { 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); + 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 == nullptr) { // nothing under cursor // if no Shift, deselect @@ -797,10 +779,11 @@ void NodeTool::select_point(Geom::Point const &/*sel*/, GdkEventButton *event) { } } -void NodeTool::mouseover_changed(Inkscape::UI::ControlPoint *p) { +void NodeTool::mouseover_changed(Inkscape::UI::ControlPoint *p) +{ using Inkscape::UI::CurveDragPoint; - CurveDragPoint *cdp = dynamic_cast<CurveDragPoint*>(p); + CurveDragPoint *cdp = dynamic_cast<CurveDragPoint *>(p); if (cdp && !this->cursor_drag) { this->cursor_shape = cursor_node_d_xpm; @@ -813,13 +796,14 @@ void NodeTool::mouseover_changed(Inkscape::UI::ControlPoint *p) { } } -void NodeTool::handleControlUiStyleChange() { +void NodeTool::handleControlUiStyleChange() +{ this->_multipath->updateHandles(); } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape //} // anonymous namespace diff --git a/src/ui/tools/node-tool.h b/src/ui/tools/node-tool.h index a81ca932a43c43faf598951c311f054e8571c072..c959df04e46192ed34af14ff5415b262bf19997c 100644 --- a/src/ui/tools/node-tool.h +++ b/src/ui/tools/node-tool.h @@ -14,42 +14,45 @@ #include <boost/ptr_container/ptr_map.hpp> #include <glib.h> + #include "ui/tools/tool-base.h" // we need it to call it from Live Effect #include "selection.h" namespace Inkscape { - namespace Display { - class TemporaryItem; - } - - namespace UI { - class MultiPathManipulator; - class ControlPointSelection; - class Selector; - class ControlPoint; - - struct PathSharedData; - } +namespace Display { +class TemporaryItem; } +namespace UI { +class MultiPathManipulator; +class ControlPointSelection; +class Selector; +class ControlPoint; + +struct PathSharedData; +} // namespace UI +} // namespace Inkscape + struct SPCanvasGroup; -#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)) +#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 { +class NodeTool : public ToolBase +{ public: NodeTool(); ~NodeTool() override; - Inkscape::UI::ControlPointSelection* _selected_nodes; - Inkscape::UI::MultiPathManipulator* _multipath; + Inkscape::UI::ControlPointSelection *_selected_nodes; + Inkscape::UI::MultiPathManipulator *_multipath; std::vector<Inkscape::Display::TemporaryItem *> _helperpath_tmpitem; bool edit_clipping_paths; @@ -59,11 +62,11 @@ public: void setup() override; void finish() override; - void set(const Inkscape::Preferences::Entry& val) override; - bool root_handler(GdkEvent* event) override; + void set(const Inkscape::Preferences::Entry &val) override; + bool root_handler(GdkEvent *event) override; - const std::string& getPrefsPath() override; - boost::ptr_map<SPItem*, ShapeEditor> _shape_editors; + const std::string &getPrefsPath() override; + boost::ptr_map<SPItem *, ShapeEditor> _shape_editors; private: sigc::connection _selection_changed_connection; @@ -73,8 +76,8 @@ private: SPItem *flashed_item; Inkscape::Display::TemporaryItem *flash_tempitem; - Inkscape::UI::Selector* _selector; - Inkscape::UI::PathSharedData* _path_data; + Inkscape::UI::Selector *_selector; + Inkscape::UI::PathSharedData *_path_data; SPCanvasGroup *_transform_handle_group; SPItem *_last_over; @@ -87,8 +90,8 @@ private: bool show_transform_handles; bool single_node_transform_handles; - std::vector<SPItem*> _current_selection; - std::vector<SPItem*> _previous_selection; + std::vector<SPItem *> _current_selection; + std::vector<SPItem *> _previous_selection; void selection_changed(Inkscape::Selection *sel); @@ -99,10 +102,10 @@ private: void handleControlUiStyleChange(); }; void sp_update_helperpath(SPDesktop *desktop); -} +} // namespace Tools -} -} +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/tools/pen-tool.cpp b/src/ui/tools/pen-tool.cpp index 83b9e4d4e1ac8a0f7f11505b4d00fa19ccd662dd..cb2e7c6a28071a5d417afbc1cc0f9986839c06ea 100644 --- a/src/ui/tools/pen-tool.cpp +++ b/src/ui/tools/pen-tool.cpp @@ -17,57 +17,49 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> -#include <string> +#include "ui/tools/pen-tool.h" +#include <2geom/curves.h> +#include <cstring> #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> - -#include <2geom/curves.h> +#include <string> #include "context-fns.h" #include "desktop.h" +#include "display/canvas-bpath.h" +#include "display/curve.h" +#include "display/sodipodi-ctrl.h" +#include "display/sp-ctrlline.h" #include "include/macros.h" #include "message-context.h" #include "message-stack.h" +#include "object/sp-path.h" #include "selection-chemistry.h" #include "selection.h" #include "shortcuts.h" -#include "verbs.h" - -#include "display/canvas-bpath.h" -#include "display/curve.h" -#include "display/sodipodi-ctrl.h" -#include "display/sp-ctrlline.h" - -#include "object/sp-path.h" - -#include "ui/pixmaps/cursor-pen.xpm" - #include "ui/control-manager.h" #include "ui/draw-anchor.h" +#include "ui/pixmaps/cursor-pen.xpm" #include "ui/tools-switch.h" -#include "ui/tools/pen-tool.h" +#include "verbs.h" // we include the necessary files for BSpline & Spiro -#include "live_effects/lpeobject.h" #include "live_effects/lpeobject-reference.h" +#include "live_effects/lpeobject.h" #include "live_effects/parameter/path.h" #define INKSCAPE_LPE_SPIRO_C -#include "live_effects/lpe-spiro.h" - #include "helper/geom-nodetype.h" +#include "live_effects/lpe-spiro.h" // For handling un-continuous paths: #include "inkscape.h" - #include "live_effects/spiro.h" #define INKSCAPE_LPE_BSPLINE_C #include "live_effects/lpe-bspline.h" - using Inkscape::ControlManager; namespace Inkscape { @@ -78,7 +70,8 @@ static Geom::Point pen_drag_origin_w(0, 0); static bool pen_within_tolerance = false; const double HANDLE_CUBIC_GAP = 0.001; -const std::string& PenTool::getPrefsPath() { +const std::string &PenTool::getPrefsPath() +{ return PenTool::prefsPath; } @@ -87,13 +80,13 @@ const std::string PenTool::prefsPath = "/tools/freehand/pen"; PenTool::PenTool() : FreehandBase(cursor_pen_xpm) , p() - , previous(Geom::Point(0,0)) + , previous(Geom::Point(0, 0)) , npoints(0) , mode(MODE_CLICK) , state(POINT) , polylines_only(false) , polylines_paraxial(false) - , paraxial_angle(Geom::Point(0,0)) + , paraxial_angle(Geom::Point(0, 0)) , num_clicks(0) , expecting_clicks_for_LPE(0) , waiting_LPE(nullptr) @@ -110,7 +103,7 @@ PenTool::PenTool() PenTool::PenTool(gchar const *const *cursor_shape) : FreehandBase(cursor_shape) , p() - , previous(Geom::Point(0,0)) + , previous(Geom::Point(0, 0)) , npoints(0) , mode(MODE_CLICK) , state(POINT) @@ -125,10 +118,10 @@ PenTool::PenTool(gchar const *const *cursor_shape) , cl0(nullptr) , cl1(nullptr) , events_disabled(false) -{ -} +{} -PenTool::~PenTool() { +PenTool::~PenTool() +{ if (this->c0) { sp_canvas_item_destroy(this->c0); this->c0 = nullptr; @@ -152,7 +145,8 @@ PenTool::~PenTool() { } } -void PenTool::setPolylineMode() { +void PenTool::setPolylineMode() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); guint mode = prefs->getInt("/tools/freehand/pen/freehand-mode", 0); // change the nodes to make space for bspline mode @@ -168,7 +162,8 @@ void PenTool::setPolylineMode() { /** * Callback to initialize PenTool object. */ -void PenTool::setup() { +void PenTool::setup() +{ FreehandBase::setup(); ControlManager &mgr = ControlManager::getManager(); @@ -199,7 +194,8 @@ void PenTool::setup() { } } -void PenTool::_cancel() { +void PenTool::_cancel() +{ this->num_clicks = 0; this->state = PenTool::STOP; this->_resetColors(); @@ -216,7 +212,8 @@ void PenTool::_cancel() { /** * Finalization callback. */ -void PenTool::finish() { +void PenTool::finish() +{ sp_event_context_discard_delayed_snap_event(this); if (this->npoints != 0) { @@ -231,11 +228,12 @@ void PenTool::finish() { /** * Callback that sets key to value in pen context. */ -void PenTool::set(const Inkscape::Preferences::Entry& val) { +void PenTool::set(const Inkscape::Preferences::Entry &val) +{ Glib::ustring name = val.getEntryName(); if (name == "mode") { - if ( val.getString() == "drag" ) { + if (val.getString() == "drag") { this->mode = MODE_DRAG; } else { this->mode = MODE_CLICK; @@ -243,20 +241,21 @@ void PenTool::set(const Inkscape::Preferences::Entry& val) { } } -bool PenTool::hasWaitingLPE() { +bool PenTool::hasWaitingLPE() +{ // note: waiting_LPE_type is defined in SPDrawContext - return (this->waiting_LPE != nullptr || - this->waiting_LPE_type != Inkscape::LivePathEffect::INVALID_LPE); + return (this->waiting_LPE != nullptr || 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) { +void PenTool::_endpointSnap(Geom::Point &p, guint const state) +{ // Paraxial kicks in after first line has set the angle (before then it's a free line) bool poly = this->polylines_paraxial && !this->green_curve->is_unset(); - if ((state & GDK_CONTROL_MASK) && !poly) { //CTRL enables angular snapping + if ((state & GDK_CONTROL_MASK) && !poly) { // CTRL enables angular snapping if (this->npoints > 0) { spdc_endpoint_snap_rotation(this, p, this->p[0], state); } else { @@ -273,7 +272,8 @@ void PenTool::_endpointSnap(Geom::Point &p, guint const state) { } 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 + spdc_endpoint_snap_free(this, p, origin, + state); // pass the origin, to allow for perpendicular / tangential snapping } } } @@ -281,21 +281,22 @@ void PenTool::_endpointSnap(Geom::Point &p, guint const state) { /** * Snaps new node's handle relative to the new node. */ -void PenTool::_endpointSnapHandle(Geom::Point &p, guint const state) { - g_return_if_fail(( this->npoints == 2 || - this->npoints == 5 )); +void PenTool::_endpointSnapHandle(Geom::Point &p, guint const state) +{ + g_return_if_fail((this->npoints == 2 || this->npoints == 5)); - if ((state & GDK_CONTROL_MASK)) { //CTRL enables angular snapping + 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 + 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) { +bool PenTool::item_handler(SPItem *item, GdkEvent *event) +{ bool ret = false; switch (event->type) { @@ -319,7 +320,8 @@ bool PenTool::item_handler(SPItem* item, GdkEvent* event) { /** * Callback to handle all pen events. */ -bool PenTool::root_handler(GdkEvent* event) { +bool PenTool::root_handler(GdkEvent *event) +{ bool ret = false; switch (event->type) { @@ -357,7 +359,8 @@ bool PenTool::root_handler(GdkEvent* event) { /** * Handle mouse button press event. */ -bool PenTool::_handleButtonPress(GdkEventButton const &bevent) { +bool PenTool::_handleButtonPress(GdkEventButton const &bevent) +{ if (this->events_disabled) { // skip event processing if events are disabled return false; @@ -365,43 +368,42 @@ bool PenTool::_handleButtonPress(GdkEventButton const &bevent) { Geom::Point const event_w(bevent.x, bevent.y); Geom::Point event_dt(desktop->w2d(event_w)); - //Test whether we hit any anchor. - SPDrawAnchor * const anchor = spdc_test_inside(this, event_w); + // Test whether we hit any anchor. + SPDrawAnchor *const anchor = spdc_test_inside(this, event_w); - //with this we avoid creating a new point over the existing one - if(bevent.button != 3 && (this->spiro || this->bspline) && this->npoints > 0 && this->p[0] == this->p[3]){ - if( anchor && anchor == this->sa && this->green_curve->is_unset()){ - //remove the following line to avoid having one node on top of another + // with this we avoid creating a new point over the existing one + if (bevent.button != 3 && (this->spiro || this->bspline) && this->npoints > 0 && this->p[0] == this->p[3]) { + if (anchor && anchor == this->sa && this->green_curve->is_unset()) { + // remove the following line to avoid having one node on top of another _finishSegment(event_dt, bevent.state); _finish(true); return true; } return false; - } - + } + bool ret = false; - if (bevent.button == 1 && !this->space_panning + if (bevent.button == 1 && + !this->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, defaultMessageContext()) == false) { return true; } - if (!this->grab ) { + 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 ), - nullptr, bevent.time); + sp_canvas_item_grab( + this->grab, + (GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK), + nullptr, bevent.time); } pen_drag_origin_w = event_w; pen_within_tolerance = true; switch (this->mode) { - case PenTool::MODE_CLICK: // In click mode we add point on release switch (this->state) { @@ -425,7 +427,8 @@ bool PenTool::_handleButtonPress(GdkEventButton const &bevent) { if (this->npoints == 0) { this->_bsplineSpiroColor(); Geom::Point p; - if ((bevent.state & GDK_CONTROL_MASK) && (this->polylines_only || this->polylines_paraxial)) { + 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; @@ -433,9 +436,9 @@ bool PenTool::_handleButtonPress(GdkEventButton const &bevent) { m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE); m.unSetup(); } - spdc_create_single_dot(this, p, "/tools/freehand/pen", bevent.state); - ret = true; - break; + spdc_create_single_dot(this, p, "/tools/freehand/pen", bevent.state); + ret = true; + break; } // TODO: Perhaps it would be nicer to rearrange the following case @@ -445,7 +448,7 @@ bool PenTool::_handleButtonPress(GdkEventButton const &bevent) { this->sa = anchor; if (anchor) { - //Put the start overwrite curve always on the same direction + // Put the start overwrite curve always on the same direction if (anchor->start) { this->sa_overwrited = this->sa->curve->create_reverse(); } else { @@ -453,7 +456,7 @@ bool PenTool::_handleButtonPress(GdkEventButton const &bevent) { } this->_bsplineSpiroStartAnchor(bevent.state & GDK_SHIFT_MASK); } - if (anchor && (!this->hasWaitingLPE()|| this->bspline || this->spiro)) { + if (anchor && (!this->hasWaitingLPE() || this->bspline || this->spiro)) { // 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; @@ -462,14 +465,15 @@ bool PenTool::_handleButtonPress(GdkEventButton const &bevent) { // 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 = desktop->getSelection(); + Inkscape::Selection *const selection = desktop->getSelection(); 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")); + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, + _("Appending to selected path")); } // Create green anchor @@ -503,7 +507,8 @@ bool PenTool::_handleButtonPress(GdkEventButton const &bevent) { } } // avoid the creation of a control point so a node is created in the release event - this->state = (this->spiro || this->bspline || this->polylines_only) ? PenTool::POINT : PenTool::CONTROL; + this->state = + (this->spiro || this->bspline || this->polylines_only) ? PenTool::POINT : PenTool::CONTROL; ret = true; break; case PenTool::CONTROL: @@ -548,7 +553,8 @@ bool PenTool::_handleButtonPress(GdkEventButton const &bevent) { /** * Handle motion_notify event. */ -bool PenTool::_handleMotionNotify(GdkEventMotion const &mevent) { +bool PenTool::_handleMotionNotify(GdkEventMotion const &mevent) +{ bool ret = false; if (this->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) { @@ -563,13 +569,13 @@ bool PenTool::_handleMotionNotify(GdkEventMotion const &mevent) { Geom::Point const event_w(mevent.x, mevent.y); - //we take out the function the const "tolerance" because we need it later + // we take out the function the const "tolerance" because we need it later Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); if (pen_within_tolerance) { - if ( Geom::LInfty( event_w - pen_drag_origin_w ) < tolerance ) { - return false; // Do not drag if we're within tolerance from origin. + 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 @@ -587,7 +593,7 @@ bool PenTool::_handleMotionNotify(GdkEventMotion const &mevent) { case PenTool::MODE_CLICK: switch (this->state) { case PenTool::POINT: - if ( this->npoints != 0 ) { + if (this->npoints != 0) { // Only set point, if we are already appending this->_endpointSnap(p, mevent.state); this->_setSubsequentPoint(p, true); @@ -621,10 +627,10 @@ bool PenTool::_handleMotionNotify(GdkEventMotion const &mevent) { case PenTool::MODE_DRAG: switch (this->state) { case PenTool::POINT: - if ( this->npoints > 0 ) { + if (this->npoints > 0) { // Only set point, if we are already appending - if (!anchor) { // Snap node only if not hitting anchor + if (!anchor) { // Snap node only if not hitting anchor this->_endpointSnap(p, mevent.state); this->_setSubsequentPoint(p, true, mevent.state); } else { @@ -632,10 +638,15 @@ bool PenTool::_handleMotionNotify(GdkEventMotion const &mevent) { } if (anchor && !this->anchor_statusbar) { - if(!this->spiro && !this->bspline){ - this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Click</b> or <b>click and drag</b> to close and finish the path.")); - }else{ - this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Click</b> or <b>click and drag</b> to close and finish the path. Shift+Click make a cusp node")); + if (!this->spiro && !this->bspline) { + this->message_context->set( + Inkscape::NORMAL_MESSAGE, + _("<b>Click</b> or <b>click and drag</b> to close and finish the path.")); + } else { + this->message_context->set( + Inkscape::NORMAL_MESSAGE, + _("<b>Click</b> or <b>click and drag</b> to close and finish the " + "path. Shift+Click make a cusp node")); } this->anchor_statusbar = true; } else if (!anchor && this->anchor_statusbar) { @@ -646,16 +657,20 @@ bool PenTool::_handleMotionNotify(GdkEventMotion const &mevent) { ret = true; } else { if (anchor && !this->anchor_statusbar) { - if(!this->spiro && !this->bspline){ - this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Click</b> or <b>click and drag</b> to continue the path from this point.")); - }else{ - this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Click</b> or <b>click and drag</b> to continue the path from this point. Shift+Click make a cusp node")); + if (!this->spiro && !this->bspline) { + this->message_context->set( + Inkscape::NORMAL_MESSAGE, + _("<b>Click</b> or <b>click and drag</b> to continue the path from this point.")); + } else { + this->message_context->set( + Inkscape::NORMAL_MESSAGE, + _("<b>Click</b> or <b>click and drag</b> to continue the path from " + "this point. Shift+Click make a cusp node")); } 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 = desktop->namedview->snap_manager; @@ -698,10 +713,10 @@ bool PenTool::_handleMotionNotify(GdkEventMotion const &mevent) { break; } // calls the function "bspline_spiro_motion" when the mouse starts or stops moving - if(this->bspline){ + if (this->bspline) { this->_bsplineSpiroMotion(mevent.state); - }else{ - if ( Geom::LInfty( event_w - pen_drag_origin_w ) > (tolerance/2) || mevent.time == 0) { + } else { + if (Geom::LInfty(event_w - pen_drag_origin_w) > (tolerance / 2) || mevent.time == 0) { this->_bsplineSpiroMotion(mevent.state); pen_drag_origin_w = event_w; } @@ -713,7 +728,8 @@ bool PenTool::_handleMotionNotify(GdkEventMotion const &mevent) { /** * Handle mouse button release event. */ -bool PenTool::_handleButtonRelease(GdkEventButton const &revent) { +bool PenTool::_handleButtonRelease(GdkEventButton const &revent) +{ if (this->events_disabled) { // skip event processing if events are disabled return false; @@ -731,7 +747,8 @@ bool PenTool::_handleButtonRelease(GdkEventButton const &revent) { SPDrawAnchor *anchor = spdc_test_inside(this, event_w); // if we try to create a node in the same place as another node, we skip - if((!anchor || anchor == this->sa) && (this->spiro || this->bspline) && this->npoints > 0 && this->p[0] == this->p[3]){ + if ((!anchor || anchor == this->sa) && (this->spiro || this->bspline) && this->npoints > 0 && + this->p[0] == this->p[3]) { return true; } @@ -753,12 +770,12 @@ bool PenTool::_handleButtonRelease(GdkEventButton const &revent) { break; case PenTool::CLOSE: // End current segment - if (!anchor) { // Snap node only if not hitting anchor + if (!anchor) { // Snap node only if not hitting anchor this->_endpointSnap(p, revent.state); } this->_finishSegment(p, revent.state); // hude the guide of the penultimate node when closing the curve - if(this->spiro){ + if (this->spiro) { sp_canvas_item_hide(this->c1); } this->_finish(true); @@ -783,7 +800,7 @@ bool PenTool::_handleButtonRelease(GdkEventButton const &revent) { this->_endpointSnap(p, revent.state); this->_finishSegment(p, revent.state); // hide the penultimate node guide when closing the curve - if(this->spiro){ + if (this->spiro) { sp_canvas_item_hide(this->c1); } if (this->green_closed) { @@ -837,7 +854,8 @@ bool PenTool::_handleButtonRelease(GdkEventButton const &revent) { return ret; } -bool PenTool::_handle2ButtonPress(GdkEventButton const &bevent) { +bool PenTool::_handle2ButtonPress(GdkEventButton const &bevent) +{ bool ret = false; // only end on LMB double click. Otherwise horizontal scrolling causes ending of the path if (this->npoints != 0 && bevent.button == 1 && this->state != PenTool::CLOSE) { @@ -847,17 +865,19 @@ bool PenTool::_handle2ButtonPress(GdkEventButton const &bevent) { return ret; } -void PenTool::_redrawAll() { +void PenTool::_redrawAll() +{ // green - if (! this->green_bpaths.empty()) { + if (!this->green_bpaths.empty()) { // remove old piecewise green canvasitems - for (auto i : this->green_bpaths){ + for (auto i : this->green_bpaths) { sp_canvas_item_destroy(i); } this->green_bpaths.clear(); // one canvas bpath for all of green_curve SPCanvasItem *canvas_shape = sp_canvas_bpath_new(this->desktop->getSketch(), this->green_curve.get(), true); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvas_shape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvas_shape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, + SP_STROKE_LINECAP_BUTT); sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(canvas_shape), 0, SP_WIND_RULE_NONZERO); this->green_bpaths.push_back(canvas_shape); @@ -865,7 +885,7 @@ void PenTool::_redrawAll() { 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]); @@ -883,13 +903,11 @@ void PenTool::_redrawAll() { sp_canvas_item_hide(this->cl1); } - Geom::Curve const * last_seg = this->green_curve->last_segment(); + Geom::Curve const *last_seg = this->green_curve->last_segment(); if (last_seg) { - Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const *>( last_seg ); + Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>(last_seg); // hide the handlers in bspline and spiro modes - if ( cubic && - (*cubic)[2] != this->p[0] && !this->spiro && !this->bspline ) - { + if (cubic && (*cubic)[2] != this->p[0] && !this->spiro && !this->bspline) { Geom::Point p2 = (*cubic)[2]; SP_CTRL(this->c0)->moveto(p2); this->cl0->setCoords(p2, this->p[0]); @@ -901,12 +919,13 @@ void PenTool::_redrawAll() { } } - // simply redraw the spiro. because its a redrawing, we don't call the global function, + // simply redraw the spiro. because its a redrawing, we don't call the global function, // but we call the redrawing at the ending. - this->_bsplineSpiroBuild(); + this->_bsplineSpiroBuild(); } -void PenTool::_lastpointMove(gdouble x, gdouble y) { +void PenTool::_lastpointMove(gdouble x, gdouble y) +{ if (this->npoints != 5) return; @@ -914,7 +933,7 @@ void PenTool::_lastpointMove(gdouble x, gdouble y) { // green if (!this->green_curve->is_unset()) { - this->green_curve->last_point_additive_move( Geom::Point(x,y) ); + this->green_curve->last_point_additive_move(Geom::Point(x, y)); } else { // start anchor too if (this->green_anchor) { @@ -929,32 +948,37 @@ void PenTool::_lastpointMove(gdouble x, gdouble y) { this->_redrawAll(); } -void PenTool::_lastpointMoveScreen(gdouble x, gdouble y) { +void PenTool::_lastpointMoveScreen(gdouble x, gdouble y) +{ this->_lastpointMove(x / this->desktop->current_zoom(), y / this->desktop->current_zoom()); } -void PenTool::_lastpointToCurve() { +void PenTool::_lastpointToCurve() +{ // avoid that if the "red_curve" contains only two points ( rect ), it doesn't stop here. if (this->npoints != 5 && !this->spiro && !this->bspline) return; - this->p[1] = this->red_curve->last_segment()->initialPoint() + (1./3.)*(*this->red_curve->last_point() - this->red_curve->last_segment()->initialPoint()); - //modificate the last segment of the green curve so it creates the type of node we need - if (this->spiro||this->bspline) { + this->p[1] = this->red_curve->last_segment()->initialPoint() + + (1. / 3.) * (*this->red_curve->last_point() - this->red_curve->last_segment()->initialPoint()); + // modificate the last segment of the green curve so it creates the type of node we need + if (this->spiro || this->bspline) { if (!this->green_curve->is_unset()) { - Geom::Point A(0,0); - Geom::Point B(0,0); - Geom::Point C(0,0); - Geom::Point D(0,0); - Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>( this->green_curve->last_segment() ); - //We obtain the last segment 4 points in the previous curve - if ( cubic ){ + Geom::Point A(0, 0); + Geom::Point B(0, 0); + Geom::Point C(0, 0); + Geom::Point D(0, 0); + Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>(this->green_curve->last_segment()); + // We obtain the last segment 4 points in the previous curve + if (cubic) { A = (*cubic)[0]; B = (*cubic)[1]; if (this->spiro) { C = this->p[0] + (this->p[0] - this->p[1]); } else { - C = *this->green_curve->last_point() + (1./3.)*(this->green_curve->last_segment()->initialPoint() - *this->green_curve->last_point()); + C = *this->green_curve->last_point() + + (1. / 3.) * + (this->green_curve->last_segment()->initialPoint() - *this->green_curve->last_point()); } D = (*cubic)[3]; } else { @@ -963,23 +987,25 @@ void PenTool::_lastpointToCurve() { if (this->spiro) { C = this->p[0] + (this->p[0] - this->p[1]); } else { - C = *this->green_curve->last_point() + (1./3.)*(this->green_curve->last_segment()->initialPoint() - *this->green_curve->last_point()); + C = *this->green_curve->last_point() + + (1. / 3.) * + (this->green_curve->last_segment()->initialPoint() - *this->green_curve->last_point()); } D = *this->green_curve->last_point(); } auto previous = std::make_unique<SPCurve>(); previous->moveto(A); previous->curveto(B, C, D); - if ( this->green_curve->get_segment_count() == 1) { + if (this->green_curve->get_segment_count() == 1) { this->green_curve = std::move(previous); } else { - //we eliminate the last segment + // we eliminate the last segment this->green_curve->backspace(); - //and we add it again with the recreation + // and we add it again with the recreation green_curve->append_continuous(*previous); } } - //if the last node is an union with another curve + // if the last node is an union with another curve if (this->green_curve->is_unset() && this->sa && !this->sa->curve->is_unset()) { this->_bsplineSpiroStartAnchor(false); } @@ -988,28 +1014,28 @@ void PenTool::_lastpointToCurve() { this->_redrawAll(); } - -void PenTool::_lastpointToLine() { +void PenTool::_lastpointToLine() +{ // avoid that if the "red_curve" contains only two points ( rect) it doesn't stop here. if (this->npoints != 5 && !this->bspline) return; // modify the last segment of the green curve so the type of node we want is created. - if(this->spiro || this->bspline){ - if(!this->green_curve->is_unset()){ - Geom::Point A(0,0); - Geom::Point B(0,0); - Geom::Point C(0,0); - Geom::Point D(0,0); + if (this->spiro || this->bspline) { + if (!this->green_curve->is_unset()) { + Geom::Point A(0, 0); + Geom::Point B(0, 0); + Geom::Point C(0, 0); + Geom::Point D(0, 0); auto previous = std::make_unique<SPCurve>(); - Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const *>( this->green_curve->last_segment() ); - if ( cubic ) { + Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>(this->green_curve->last_segment()); + if (cubic) { A = this->green_curve->last_segment()->initialPoint(); B = (*cubic)[1]; C = *this->green_curve->last_point(); D = C; } else { - //We obtain the last segment 4 points in the previous curve + // We obtain the last segment 4 points in the previous curve A = this->green_curve->last_segment()->initialPoint(); B = A; C = *this->green_curve->last_point(); @@ -1017,35 +1043,35 @@ void PenTool::_lastpointToLine() { } previous->moveto(A); previous->curveto(B, C, D); - if( this->green_curve->get_segment_count() == 1){ + if (this->green_curve->get_segment_count() == 1) { this->green_curve = std::move(previous); - }else{ - //we eliminate the last segment + } else { + // we eliminate the last segment this->green_curve->backspace(); - //and we add it again with the recreation + // and we add it again with the recreation green_curve->append_continuous(*previous); } } // if the last node is an union with another curve - if(this->green_curve->is_unset() && this->sa && !this->sa->curve->is_unset()){ + if (this->green_curve->is_unset() && this->sa && !this->sa->curve->is_unset()) { this->_bsplineSpiroStartAnchor(true); } } - + this->p[1] = this->p[0]; this->_redrawAll(); } - -bool PenTool::_handleKeyPress(GdkEvent *event) { +bool PenTool::_handleKeyPress(GdkEvent *event) +{ bool ret = false; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gdouble const nudge = prefs->getDoubleLimited("/options/nudgedistance/value", 2, 0, 1000, "px"); // in px // Check for undo if we have started drawing a path. if (this->npoints > 0) { - unsigned int shortcut = sp_shortcut_get_for_event((GdkEventKey*)event); - Inkscape::Verb* verb = sp_shortcut_get_verb(shortcut); + unsigned int shortcut = sp_shortcut_get_for_event((GdkEventKey *)event); + Inkscape::Verb *verb = sp_shortcut_get_verb(shortcut); if (verb) { unsigned int vcode = verb->get_code(); if (vcode == SP_VERB_EDIT_UNDO) @@ -1053,23 +1079,20 @@ bool PenTool::_handleKeyPress(GdkEvent *event) { } } - switch (get_latin_keyval (&event->key)) { + switch (get_latin_keyval(&event->key)) { case GDK_KEY_Left: // move last point left case GDK_KEY_KP_Left: - if (!MOD__CTRL(event)) { // not ctrl + if (!MOD__CTRL(event)) { // not ctrl if (MOD__ALT(event)) { // alt if (MOD__SHIFT(event)) { this->_lastpointMoveScreen(-10, 0); // shift - } - else { + } else { this->_lastpointMoveScreen(-1, 0); // no shift } - } - else { // no alt + } else { // no alt if (MOD__SHIFT(event)) { - this->_lastpointMove(-10*nudge, 0); // shift - } - else { + this->_lastpointMove(-10 * nudge, 0); // shift + } else { this->_lastpointMove(-nudge, 0); // no shift } } @@ -1078,20 +1101,17 @@ bool PenTool::_handleKeyPress(GdkEvent *event) { break; case GDK_KEY_Up: // move last point up case GDK_KEY_KP_Up: - if (!MOD__CTRL(event)) { // not ctrl + if (!MOD__CTRL(event)) { // not ctrl if (MOD__ALT(event)) { // alt if (MOD__SHIFT(event)) { this->_lastpointMoveScreen(0, 10); // shift - } - else { + } else { this->_lastpointMoveScreen(0, 1); // no shift } - } - else { // no alt + } else { // no alt if (MOD__SHIFT(event)) { - this->_lastpointMove(0, 10*nudge); // shift - } - else { + this->_lastpointMove(0, 10 * nudge); // shift + } else { this->_lastpointMove(0, nudge); // no shift } } @@ -1100,20 +1120,17 @@ bool PenTool::_handleKeyPress(GdkEvent *event) { break; case GDK_KEY_Right: // move last point right case GDK_KEY_KP_Right: - if (!MOD__CTRL(event)) { // not ctrl + if (!MOD__CTRL(event)) { // not ctrl if (MOD__ALT(event)) { // alt if (MOD__SHIFT(event)) { this->_lastpointMoveScreen(10, 0); // shift - } - else { + } else { this->_lastpointMoveScreen(1, 0); // no shift } - } - else { // no alt + } else { // no alt if (MOD__SHIFT(event)) { - this->_lastpointMove(10*nudge, 0); // shift - } - else { + this->_lastpointMove(10 * nudge, 0); // shift + } else { this->_lastpointMove(nudge, 0); // no shift } } @@ -1122,20 +1139,17 @@ bool PenTool::_handleKeyPress(GdkEvent *event) { break; case GDK_KEY_Down: // move last point down case GDK_KEY_KP_Down: - if (!MOD__CTRL(event)) { // not ctrl + if (!MOD__CTRL(event)) { // not ctrl if (MOD__ALT(event)) { // alt if (MOD__SHIFT(event)) { this->_lastpointMoveScreen(0, -10); // shift - } - else { + } else { this->_lastpointMoveScreen(0, -1); // no shift } - } - else { // no alt + } else { // no alt if (MOD__SHIFT(event)) { - this->_lastpointMove(0, -10*nudge); // shift - } - else { + this->_lastpointMove(0, -10 * nudge); // shift + } else { this->_lastpointMove(0, -nudge); // no shift } } @@ -1143,39 +1157,39 @@ bool PenTool::_handleKeyPress(GdkEvent *event) { } 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; + /*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_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_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_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: @@ -1196,17 +1210,17 @@ bool PenTool::_handleKeyPress(GdkEvent *event) { case GDK_KEY_KP_Enter: if (this->npoints != 0) { this->ea = nullptr; // unset end anchor if set (otherwise crashes) - if(MOD__SHIFT_ONLY(event)) { + if (MOD__SHIFT_ONLY(event)) { // All this is needed to stop the last control // point dispeating and stop making an n-1 shape. Geom::Point const p(0, 0); - if(this->red_curve->is_unset()) { + if (this->red_curve->is_unset()) { this->red_curve->moveto(p); } this->_finishSegment(p, 0); this->_finish(true); } else { - this->_finish(false); + this->_finish(false); } ret = true; } @@ -1214,7 +1228,7 @@ bool PenTool::_handleKeyPress(GdkEvent *event) { case GDK_KEY_Escape: if (this->npoints != 0) { // if drawing, cancel, otherwise pass it up for deselecting - this->_cancel (); + this->_cancel(); ret = true; } break; @@ -1236,7 +1250,8 @@ bool PenTool::_handleKeyPress(GdkEvent *event) { return ret; } -void PenTool::_resetColors() { +void PenTool::_resetColors() +{ // Red this->red_curve->reset(); sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), nullptr, true); @@ -1244,7 +1259,7 @@ void PenTool::_resetColors() { this->blue_curve->reset(); sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->blue_bpath), nullptr, true); // Green - for (auto i:this->green_bpaths) { + for (auto i : this->green_bpaths) { sp_canvas_item_destroy(i); } this->green_bpaths.clear(); @@ -1260,9 +1275,9 @@ void PenTool::_resetColors() { this->red_curve_is_valid = false; } - -void PenTool::_setInitialPoint(Geom::Point const p) { - g_assert( this->npoints == 0 ); +void PenTool::_setInitialPoint(Geom::Point const p) +{ + g_assert(this->npoints == 0); this->p[0] = p; this->p[1] = p; @@ -1277,7 +1292,8 @@ void PenTool::_setInitialPoint(Geom::Point const p) { * 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) { +void PenTool::_setAngleDistanceStatusMessage(Geom::Point const p, int pc_point_to_compare, gchar const *message) +{ g_assert((pc_point_to_compare == 0) || (pc_point_to_compare == 3)); // exclude control handles g_assert(message != nullptr); @@ -1301,76 +1317,78 @@ void PenTool::_setAngleDistanceStatusMessage(Geom::Point const p, int pc_point_t this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, message, angle, dist.c_str()); } -// this function changes the colors red, green and blue making them transparent or not, depending on if spiro is being used. +// this function changes the colors red, green and blue making them transparent or not, depending on if spiro is being +// used. void PenTool::_bsplineSpiroColor() { static Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if(this->spiro){ + if (this->spiro) { this->red_color = 0xff000000; this->green_color = 0x00ff0000; - }else if(this->bspline){ + } else if (this->bspline) { this->highlight_color = SP_ITEM(this->desktop->currentLayer())->highlight_color(); - if((unsigned int)prefs->getInt("/tools/nodes/highlight_color", 0xff0000ff) == this->highlight_color){ + if ((unsigned int)prefs->getInt("/tools/nodes/highlight_color", 0xff0000ff) == this->highlight_color) { this->green_color = 0xff00007f; this->red_color = 0xff00007f; } else { this->green_color = this->highlight_color; this->red_color = this->highlight_color; } - }else{ + } else { this->highlight_color = SP_ITEM(this->desktop->currentLayer())->highlight_color(); this->red_color = 0xff00007f; - if((unsigned int)prefs->getInt("/tools/nodes/highlight_color", 0xff0000ff) == this->highlight_color){ + if ((unsigned int)prefs->getInt("/tools/nodes/highlight_color", 0xff0000ff) == this->highlight_color) { this->green_color = 0x00ff007f; } else { this->green_color = this->highlight_color; } sp_canvas_item_hide(this->blue_bpath); } - //We erase all the "green_bpaths" to recreate them after with the colour - //transparency recently modified + // We erase all the "green_bpaths" to recreate them after with the colour + // transparency recently modified if (!this->green_bpaths.empty()) { // remove old piecewise green canvasitems - for (auto i:this->green_bpaths) { + for (auto i : this->green_bpaths) { sp_canvas_item_destroy(i); } this->green_bpaths.clear(); // one canvas bpath for all of green_curve SPCanvasItem *canvas_shape = sp_canvas_bpath_new(this->desktop->getSketch(), this->green_curve.get(), true); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvas_shape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvas_shape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, + SP_STROKE_LINECAP_BUTT); sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(canvas_shape), 0, SP_WIND_RULE_NONZERO); this->green_bpaths.push_back(canvas_shape); } - 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_stroke(SP_CANVAS_BPATH(this->red_bpath), this->red_color, 1.0, SP_STROKE_LINEJOIN_MITER, + SP_STROKE_LINECAP_BUTT); } - void PenTool::_bsplineSpiro(bool shift) { - if(!this->spiro && !this->bspline){ + if (!this->spiro && !this->bspline) { return; } - shift?this->_bsplineSpiroOff():this->_bsplineSpiroOn(); + shift ? this->_bsplineSpiroOff() : this->_bsplineSpiroOn(); this->_bsplineSpiroBuild(); } void PenTool::_bsplineSpiroOn() { - if(!this->red_curve->is_unset()){ + if (!this->red_curve->is_unset()) { using Geom::X; using Geom::Y; this->npoints = 5; this->p[0] = *this->red_curve->first_point(); this->p[3] = this->red_curve->first_segment()->finalPoint(); - this->p[2] = this->p[3] + (1./3)*(this->p[0] - this->p[3]); - this->p[2] = Geom::Point(this->p[2][X] + HANDLE_CUBIC_GAP,this->p[2][Y] + HANDLE_CUBIC_GAP); + this->p[2] = this->p[3] + (1. / 3) * (this->p[0] - this->p[3]); + this->p[2] = Geom::Point(this->p[2][X] + HANDLE_CUBIC_GAP, this->p[2][Y] + HANDLE_CUBIC_GAP); } } void PenTool::_bsplineSpiroOff() { - if(!this->red_curve->is_unset()){ + if (!this->red_curve->is_unset()) { this->npoints = 5; this->p[0] = *this->red_curve->first_point(); this->p[3] = this->red_curve->first_segment()->finalPoint(); @@ -1380,41 +1398,43 @@ void PenTool::_bsplineSpiroOff() void PenTool::_bsplineSpiroStartAnchor(bool shift) { - if(this->sa->curve->is_unset()){ + if (this->sa->curve->is_unset()) { return; } LivePathEffect::LPEBSpline *lpe_bsp = nullptr; - if (SP_IS_LPE_ITEM(this->white_item) && SP_LPE_ITEM(this->white_item)->hasPathEffect()){ - Inkscape::LivePathEffect::Effect* thisEffect = SP_LPE_ITEM(this->white_item)->getPathEffectOfType(Inkscape::LivePathEffect::BSPLINE); - if(thisEffect){ - lpe_bsp = dynamic_cast<LivePathEffect::LPEBSpline*>(thisEffect->getLPEObj()->get_lpe()); + if (SP_IS_LPE_ITEM(this->white_item) && SP_LPE_ITEM(this->white_item)->hasPathEffect()) { + Inkscape::LivePathEffect::Effect *thisEffect = + SP_LPE_ITEM(this->white_item)->getPathEffectOfType(Inkscape::LivePathEffect::BSPLINE); + if (thisEffect) { + lpe_bsp = dynamic_cast<LivePathEffect::LPEBSpline *>(thisEffect->getLPEObj()->get_lpe()); } } - if(lpe_bsp){ + if (lpe_bsp) { this->bspline = true; - }else{ + } else { this->bspline = false; } LivePathEffect::LPESpiro *lpe_spi = nullptr; - if (SP_IS_LPE_ITEM(this->white_item) && SP_LPE_ITEM(this->white_item)->hasPathEffect()){ - Inkscape::LivePathEffect::Effect* thisEffect = SP_LPE_ITEM(this->white_item)->getPathEffectOfType(Inkscape::LivePathEffect::SPIRO); - if(thisEffect){ - lpe_spi = dynamic_cast<LivePathEffect::LPESpiro*>(thisEffect->getLPEObj()->get_lpe()); + if (SP_IS_LPE_ITEM(this->white_item) && SP_LPE_ITEM(this->white_item)->hasPathEffect()) { + Inkscape::LivePathEffect::Effect *thisEffect = + SP_LPE_ITEM(this->white_item)->getPathEffectOfType(Inkscape::LivePathEffect::SPIRO); + if (thisEffect) { + lpe_spi = dynamic_cast<LivePathEffect::LPESpiro *>(thisEffect->getLPEObj()->get_lpe()); } } - if(lpe_spi){ + if (lpe_spi) { this->spiro = true; - }else{ + } else { this->spiro = false; } - if(!this->spiro && !this->bspline){ + if (!this->spiro && !this->bspline) { _bsplineSpiroColor(); return; } - if(shift){ + if (shift) { this->_bsplineSpiroStartAnchorOff(); } else { this->_bsplineSpiroStartAnchorOn(); @@ -1425,102 +1445,103 @@ void PenTool::_bsplineSpiroStartAnchorOn() { using Geom::X; using Geom::Y; - Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const*>(&*this->sa_overwrited ->last_segment()); + Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>(&*this->sa_overwrited->last_segment()); auto last_segment = std::make_unique<SPCurve>(); Geom::Point point_a = this->sa_overwrited->last_segment()->initialPoint(); Geom::Point point_d = *this->sa_overwrited->last_point(); - Geom::Point point_c = point_d + (1./3)*(point_a - point_d); + Geom::Point point_c = point_d + (1. / 3) * (point_a - point_d); point_c = Geom::Point(point_c[X] + HANDLE_CUBIC_GAP, point_c[Y] + HANDLE_CUBIC_GAP); - if(cubic){ + if (cubic) { last_segment->moveto(point_a); - last_segment->curveto((*cubic)[1],point_c,point_d); - }else{ + last_segment->curveto((*cubic)[1], point_c, point_d); + } else { last_segment->moveto(point_a); - last_segment->curveto(point_a,point_c,point_d); + last_segment->curveto(point_a, point_c, point_d); } - if( this->sa_overwrited->get_segment_count() == 1){ + if (this->sa_overwrited->get_segment_count() == 1) { this->sa_overwrited = std::move(last_segment); - }else{ - //we eliminate the last segment + } else { + // we eliminate the last segment this->sa_overwrited->backspace(); - //and we add it again with the recreation + // and we add it again with the recreation sa_overwrited->append_continuous(*last_segment); } } void PenTool::_bsplineSpiroStartAnchorOff() { - Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const*>(&*this->sa_overwrited->last_segment()); - if(cubic){ + Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>(&*this->sa_overwrited->last_segment()); + if (cubic) { auto last_segment = std::make_unique<SPCurve>(); last_segment->moveto((*cubic)[0]); - last_segment->curveto((*cubic)[1],(*cubic)[3],(*cubic)[3]); - if( this->sa_overwrited->get_segment_count() == 1){ + last_segment->curveto((*cubic)[1], (*cubic)[3], (*cubic)[3]); + if (this->sa_overwrited->get_segment_count() == 1) { this->sa_overwrited = std::move(last_segment); - }else{ - //we eliminate the last segment + } else { + // we eliminate the last segment this->sa_overwrited->backspace(); - //and we add it again with the recreation + // and we add it again with the recreation sa_overwrited->append_continuous(*last_segment); } } } -void PenTool::_bsplineSpiroMotion(guint const state){ +void PenTool::_bsplineSpiroMotion(guint const state) +{ bool shift = state & GDK_SHIFT_MASK; - if(!this->spiro && !this->bspline){ + if (!this->spiro && !this->bspline) { return; } using Geom::X; using Geom::Y; - if(this->red_curve->is_unset()) return; + if (this->red_curve->is_unset()) + return; this->npoints = 5; std::unique_ptr<SPCurve> tmp_curve(new SPCurve()); - this->p[2] = this->p[3] + (1./3)*(this->p[0] - this->p[3]); - this->p[2] = Geom::Point(this->p[2][X] + HANDLE_CUBIC_GAP,this->p[2][Y] + HANDLE_CUBIC_GAP); + this->p[2] = this->p[3] + (1. / 3) * (this->p[0] - this->p[3]); + this->p[2] = Geom::Point(this->p[2][X] + HANDLE_CUBIC_GAP, this->p[2][Y] + HANDLE_CUBIC_GAP); if (this->green_curve->is_unset() && !this->sa) { - this->p[1] = this->p[0] + (1./3)*(this->p[3] - this->p[0]); + this->p[1] = this->p[0] + (1. / 3) * (this->p[3] - this->p[0]); this->p[1] = Geom::Point(this->p[1][X] + HANDLE_CUBIC_GAP, this->p[1][Y] + HANDLE_CUBIC_GAP); - if(shift){ + if (shift) { this->p[2] = this->p[3]; } - } else if (!this->green_curve->is_unset()){ + } else if (!this->green_curve->is_unset()) { tmp_curve = this->green_curve->copy(); } else { tmp_curve = this->sa_overwrited->copy(); } - if ((state & GDK_MOD1_MASK ) && previous != Geom::Point(0,0)) { //ALT drag + if ((state & GDK_MOD1_MASK) && previous != Geom::Point(0, 0)) { // ALT drag this->p[0] = this->p[0] + (this->p[3] - previous); } - if(!tmp_curve ->is_unset()){ - Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const*>(&*tmp_curve ->last_segment()); - if ((state & GDK_MOD1_MASK ) && - !Geom::are_near(*tmp_curve ->last_point(), this->p[0], 0.1)) - { + if (!tmp_curve->is_unset()) { + Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>(&*tmp_curve->last_segment()); + if ((state & GDK_MOD1_MASK) && !Geom::are_near(*tmp_curve->last_point(), this->p[0], 0.1)) { auto previous_weight_power = std::make_unique<SPCurve>(); - Geom::D2< Geom::SBasis > SBasisweight_power; - previous_weight_power->moveto(tmp_curve ->last_segment()->initialPoint()); + Geom::D2<Geom::SBasis> SBasisweight_power; + previous_weight_power->moveto(tmp_curve->last_segment()->initialPoint()); previous_weight_power->lineto(this->p[0]); SBasisweight_power = previous_weight_power->first_segment()->toSBasis(); - if( tmp_curve ->get_segment_count() == 1){ - Geom::Point initial = tmp_curve ->last_segment()->initialPoint(); + if (tmp_curve->get_segment_count() == 1) { + Geom::Point initial = tmp_curve->last_segment()->initialPoint(); tmp_curve->reset(); tmp_curve->moveto(initial); - }else{ + } else { tmp_curve->backspace(); } - if(this->bspline && cubic && !Geom::are_near((*cubic)[2],(*cubic)[3])){ - tmp_curve->curveto(SBasisweight_power.valueAt(0.33334), SBasisweight_power.valueAt(0.66667), this->p[0]); - } else if(this->bspline && cubic) { + if (this->bspline && cubic && !Geom::are_near((*cubic)[2], (*cubic)[3])) { + tmp_curve->curveto(SBasisweight_power.valueAt(0.33334), SBasisweight_power.valueAt(0.66667), + this->p[0]); + } else if (this->bspline && cubic) { tmp_curve->curveto(SBasisweight_power.valueAt(0.33334), this->p[0], this->p[0]); - } else if (cubic && !Geom::are_near((*cubic)[2],(*cubic)[3])) { + } else if (cubic && !Geom::are_near((*cubic)[2], (*cubic)[3])) { tmp_curve->curveto((*cubic)[1], (*cubic)[2] + (this->p[3] - previous), this->p[0]); - } else if (cubic){ + } else if (cubic) { tmp_curve->curveto((*cubic)[1], this->p[0], this->p[0]); } else { tmp_curve->lineto(this->p[0]); } - cubic = dynamic_cast<Geom::CubicBezier const*>(&*tmp_curve ->last_segment()); + cubic = dynamic_cast<Geom::CubicBezier const *>(&*tmp_curve->last_segment()); if (this->sa && this->green_curve->is_unset()) { this->sa_overwrited = tmp_curve->copy(); } @@ -1529,24 +1550,24 @@ void PenTool::_bsplineSpiroMotion(guint const state){ if (cubic) { if (this->bspline) { auto weight_power = std::make_unique<SPCurve>(); - Geom::D2< Geom::SBasis > SBasisweight_power; + Geom::D2<Geom::SBasis> SBasisweight_power; weight_power->moveto(this->red_curve->last_segment()->initialPoint()); weight_power->lineto(*this->red_curve->last_point()); SBasisweight_power = weight_power->first_segment()->toSBasis(); this->p[1] = SBasisweight_power.valueAt(0.33334); - if(!Geom::are_near(this->p[1],this->p[0])){ - this->p[1] = Geom::Point(this->p[1][X] + HANDLE_CUBIC_GAP,this->p[1][Y] + HANDLE_CUBIC_GAP); + if (!Geom::are_near(this->p[1], this->p[0])) { + this->p[1] = Geom::Point(this->p[1][X] + HANDLE_CUBIC_GAP, this->p[1][Y] + HANDLE_CUBIC_GAP); } else { this->p[1] = this->p[0]; } if (shift) { this->p[2] = this->p[3]; } - if(Geom::are_near((*cubic)[3], (*cubic)[2])) { + if (Geom::are_near((*cubic)[3], (*cubic)[2])) { this->p[1] = this->p[0]; } } else { - this->p[1] = (*cubic)[3] + ((*cubic)[3] - (*cubic)[2] ); + this->p[1] = (*cubic)[3] + ((*cubic)[3] - (*cubic)[2]); } } else { this->p[1] = this->p[0]; @@ -1557,27 +1578,28 @@ void PenTool::_bsplineSpiroMotion(guint const state){ previous = *this->red_curve->last_point(); auto red = std::make_unique<SPCurve>(); red->moveto(this->p[0]); - red->curveto(this->p[1],this->p[2],this->p[3]); + red->curveto(this->p[1], this->p[2], this->p[3]); sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), red.get(), true); } - - if(this->anchor_statusbar && !this->red_curve->is_unset()){ - if(shift){ + + if (this->anchor_statusbar && !this->red_curve->is_unset()) { + if (shift) { this->_bsplineSpiroEndAnchorOff(); - }else{ + } else { this->_bsplineSpiroEndAnchorOn(); } } if (!this->green_bpaths.empty()) { // remove old piecewise green canvasitems - for (auto i: this->green_bpaths) { + for (auto i : this->green_bpaths) { sp_canvas_item_destroy(i); } this->green_bpaths.clear(); } // one canvas bpath for all of green_curve SPCanvasItem *canvas_shape = sp_canvas_bpath_new(this->desktop->getSketch(), this->green_curve.get(), true); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvas_shape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvas_shape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, + SP_STROKE_LINECAP_BUTT); sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(canvas_shape), 0, SP_WIND_RULE_NONZERO); this->green_bpaths.push_back(canvas_shape); this->_bsplineSpiroBuild(); @@ -1585,52 +1607,51 @@ void PenTool::_bsplineSpiroMotion(guint const state){ void PenTool::_bsplineSpiroEndAnchorOn() { - using Geom::X; using Geom::Y; - this->p[2] = this->p[3] + (1./3)*(this->p[0] - this->p[3]); - this->p[2] = Geom::Point(this->p[2][X] + HANDLE_CUBIC_GAP,this->p[2][Y] + HANDLE_CUBIC_GAP); + this->p[2] = this->p[3] + (1. / 3) * (this->p[0] - this->p[3]); + this->p[2] = Geom::Point(this->p[2][X] + HANDLE_CUBIC_GAP, this->p[2][Y] + HANDLE_CUBIC_GAP); std::unique_ptr<SPCurve> tmp_curve(new SPCurve()); std::unique_ptr<SPCurve> last_segment(new SPCurve()); - Geom::Point point_c(0,0); - if( this->green_anchor && this->green_anchor->active ){ + Geom::Point point_c(0, 0); + if (this->green_anchor && this->green_anchor->active) { tmp_curve = this->green_curve->create_reverse(); - if(this->green_curve->get_segment_count()==0){ + if (this->green_curve->get_segment_count() == 0) { return; } - } else if(this->sa){ + } else if (this->sa) { tmp_curve = this->sa_overwrited->create_reverse(); - }else{ + } else { return; } - Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const*>(&*tmp_curve ->last_segment()); - if(this->bspline){ - point_c = *tmp_curve ->last_point() + (1./3)*(tmp_curve ->last_segment()->initialPoint() - *tmp_curve ->last_point()); + Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>(&*tmp_curve->last_segment()); + if (this->bspline) { + point_c = *tmp_curve->last_point() + + (1. / 3) * (tmp_curve->last_segment()->initialPoint() - *tmp_curve->last_point()); point_c = Geom::Point(point_c[X] + HANDLE_CUBIC_GAP, point_c[Y] + HANDLE_CUBIC_GAP); - }else{ + } else { point_c = this->p[3] + this->p[3] - this->p[2]; } - if(cubic){ + if (cubic) { last_segment->moveto((*cubic)[0]); - last_segment->curveto((*cubic)[1],point_c,(*cubic)[3]); - }else{ - last_segment->moveto(tmp_curve ->last_segment()->initialPoint()); - last_segment->lineto(*tmp_curve ->last_point()); - } - if( tmp_curve ->get_segment_count() == 1){ - tmp_curve = std::move(last_segment); - }else{ - //we eliminate the last segment - tmp_curve ->backspace(); - //and we add it again with the recreation - tmp_curve ->append_continuous(*last_segment); + last_segment->curveto((*cubic)[1], point_c, (*cubic)[3]); + } else { + last_segment->moveto(tmp_curve->last_segment()->initialPoint()); + last_segment->lineto(*tmp_curve->last_point()); + } + if (tmp_curve->get_segment_count() == 1) { + tmp_curve = std::move(last_segment); + } else { + // we eliminate the last segment + tmp_curve->backspace(); + // and we add it again with the recreation + tmp_curve->append_continuous(*last_segment); } tmp_curve = tmp_curve->create_reverse(); - if( this->green_anchor && this->green_anchor->active ) - { + if (this->green_anchor && this->green_anchor->active) { this->green_curve->reset(); this->green_curve = std::move(tmp_curve); - }else{ + } else { this->sa_overwrited->reset(); this->sa_overwrited = std::move(tmp_curve); } @@ -1638,90 +1659,88 @@ void PenTool::_bsplineSpiroEndAnchorOn() void PenTool::_bsplineSpiroEndAnchorOff() { - std::unique_ptr<SPCurve> tmp_curve(new SPCurve()); std::unique_ptr<SPCurve> last_segment(new SPCurve()); this->p[2] = this->p[3]; - if( this->green_anchor && this->green_anchor->active ){ + if (this->green_anchor && this->green_anchor->active) { tmp_curve = this->green_curve->create_reverse(); - if(this->green_curve->get_segment_count()==0){ + if (this->green_curve->get_segment_count() == 0) { return; } - } else if(this->sa){ + } else if (this->sa) { tmp_curve = this->sa_overwrited->create_reverse(); - }else{ + } else { return; } - Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const*>(&*tmp_curve ->last_segment()); - if(cubic){ + Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>(&*tmp_curve->last_segment()); + if (cubic) { last_segment->moveto((*cubic)[0]); - last_segment->curveto((*cubic)[1],(*cubic)[3],(*cubic)[3]); - }else{ - last_segment->moveto(tmp_curve ->last_segment()->initialPoint()); - last_segment->lineto(*tmp_curve ->last_point()); - } - if( tmp_curve ->get_segment_count() == 1){ - tmp_curve = std::move(last_segment); - }else{ - //we eliminate the last segment - tmp_curve ->backspace(); - //and we add it again with the recreation - tmp_curve ->append_continuous(*last_segment); + last_segment->curveto((*cubic)[1], (*cubic)[3], (*cubic)[3]); + } else { + last_segment->moveto(tmp_curve->last_segment()->initialPoint()); + last_segment->lineto(*tmp_curve->last_point()); + } + if (tmp_curve->get_segment_count() == 1) { + tmp_curve = std::move(last_segment); + } else { + // we eliminate the last segment + tmp_curve->backspace(); + // and we add it again with the recreation + tmp_curve->append_continuous(*last_segment); } tmp_curve = tmp_curve->create_reverse(); - if( this->green_anchor && this->green_anchor->active ) - { + if (this->green_anchor && this->green_anchor->active) { this->green_curve->reset(); this->green_curve = std::move(tmp_curve); - }else{ + } else { this->sa_overwrited->reset(); this->sa_overwrited = std::move(tmp_curve); } } -//prepares the curves for its transformation into BSpline curve. +// prepares the curves for its transformation into BSpline curve. void PenTool::_bsplineSpiroBuild() { - if(!this->spiro && !this->bspline){ + if (!this->spiro && !this->bspline) { return; } - //We create the base curve + // We create the base curve auto curve = std::make_unique<SPCurve>(); - //If we continuate the existing curve we add it at the start - if(this->sa && !this->sa->curve->is_unset()){ + // If we continuate the existing curve we add it at the start + if (this->sa && !this->sa->curve->is_unset()) { curve = this->sa_overwrited->copy(); } - if (!this->green_curve->is_unset()){ + if (!this->green_curve->is_unset()) { curve->append_continuous(*green_curve); } - //and the red one - if (!this->red_curve->is_unset()){ + // and the red one + if (!this->red_curve->is_unset()) { this->red_curve->reset(); this->red_curve->moveto(this->p[0]); - if(this->anchor_statusbar && !this->sa && !(this->green_anchor && this->green_anchor->active)){ - this->red_curve->curveto(this->p[1],this->p[3],this->p[3]); - }else{ - this->red_curve->curveto(this->p[1],this->p[2],this->p[3]); + if (this->anchor_statusbar && !this->sa && !(this->green_anchor && this->green_anchor->active)) { + this->red_curve->curveto(this->p[1], this->p[3], this->p[3]); + } else { + this->red_curve->curveto(this->p[1], this->p[2], this->p[3]); } sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(red_bpath), red_curve.get(), true); curve->append_continuous(*red_curve); } previous = *this->red_curve->last_point(); - if(!curve->is_unset()){ + if (!curve->is_unset()) { // close the curve if the final points of the curve are close enough - if(Geom::are_near(curve->first_path()->initialPoint(), curve->last_path()->finalPoint())){ + if (Geom::are_near(curve->first_path()->initialPoint(), curve->last_path()->finalPoint())) { curve->closepath_current(); } - //TODO: CALL TO CLONED FUNCTION SPIRO::doEffect IN lpe-spiro.cpp - //For example - //using namespace Inkscape::LivePathEffect; - //LivePathEffectObject *lpeobj = static_cast<LivePathEffectObject*> (curve); - //Effect *spr = static_cast<Effect*> ( new LPEbspline(lpeobj) ); - //spr->doEffect(curve); + // TODO: CALL TO CLONED FUNCTION SPIRO::doEffect IN lpe-spiro.cpp + // For example + // using namespace Inkscape::LivePathEffect; + // LivePathEffectObject *lpeobj = static_cast<LivePathEffectObject*> (curve); + // Effect *spr = static_cast<Effect*> ( new LPEbspline(lpeobj) ); + // spr->doEffect(curve); if (this->bspline) { Geom::PathVector hp; LivePathEffect::sp_bspline_do_effect(curve.get(), 0, hp); @@ -1730,27 +1749,28 @@ void PenTool::_bsplineSpiroBuild() } sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->blue_bpath), curve.get(), true); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->blue_bpath), this->blue_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->blue_bpath), this->blue_color, 1.0, SP_STROKE_LINEJOIN_MITER, + SP_STROKE_LINECAP_BUTT); sp_canvas_item_show(this->blue_bpath); this->blue_curve->reset(); - //We hide the holders that doesn't contribute anything - if(this->spiro){ + // We hide the holders that doesn't contribute anything + if (this->spiro) { sp_canvas_item_show(this->c1); SP_CTRL(this->c1)->moveto(this->p[0]); - }else + } else sp_canvas_item_hide(this->c1); sp_canvas_item_hide(this->cl1); sp_canvas_item_hide(this->c0); sp_canvas_item_hide(this->cl0); - }else{ - //if the curve is empty + } else { + // if the curve is empty sp_canvas_item_hide(this->blue_bpath); - } } -void PenTool::_setSubsequentPoint(Geom::Point const p, bool statusbar, guint status) { - g_assert( this->npoints != 0 ); +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. @@ -1788,40 +1808,42 @@ void PenTool::_setSubsequentPoint(Geom::Point const p, bool statusbar, guint sta if (statusbar) { gchar *message; - if(this->spiro || this->bspline){ - message = is_curve ? - _("<b>Curve segment</b>: angle %3.2f°; with <b>Shift+Click</b> cusp node,<b>ALT</b> move previous, <b>Enter</b> or <b>Shift+Enter</b> to finish" ): - _("<b>Line segment</b>: angle %3.2f°; with <b>Shift+Click</b> cusp node,<b>ALT</b> move previous, <b>Enter</b> or <b>Shift+Enter</b> to finish"); + if (this->spiro || this->bspline) { + message = is_curve ? _("<b>Curve segment</b>: angle %3.2f°; with <b>Shift+Click</b> cusp " + "node,<b>ALT</b> move previous, <b>Enter</b> or <b>Shift+Enter</b> to finish") + : _("<b>Line segment</b>: angle %3.2f°; with <b>Shift+Click</b> cusp " + "node,<b>ALT</b> move previous, <b>Enter</b> or <b>Shift+Enter</b> to finish"); this->_setAngleDistanceStatusMessage(p, 0, message); } else { - message = is_curve ? - _("<b>Curve segment</b>: angle %3.2f°, distance %s; with <b>Ctrl</b> to snap angle, <b>Enter</b> or <b>Shift+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> or <b>Shift+Enter</b> to finish the path"); + message = is_curve ? _("<b>Curve segment</b>: angle %3.2f°, distance %s; with <b>Ctrl</b> to snap " + "angle, <b>Enter</b> or <b>Shift+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> or <b>Shift+Enter</b> to finish the path"); this->_setAngleDistanceStatusMessage(p, 0, message); } - } } - -void PenTool::_setCtrl(Geom::Point const p, guint const state) { +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 ) { + 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->_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 ) ) ) { + 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; @@ -1831,39 +1853,38 @@ void PenTool::_setCtrl(Geom::Point const p, guint const state) { sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(red_bpath), red_curve.get(), true); } SP_CTRL(this->c0)->moveto(this->p[2]); - this->cl0 ->setCoords(this->p[3], 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"); + 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) { +void PenTool::_finishSegment(Geom::Point const p, guint const state) +{ if (this->polylines_paraxial) { this->nextParaxialDirection(p, this->p[0], state); } ++num_clicks; - if (!this->red_curve->is_unset()) { this->_bsplineSpiro(state & GDK_SHIFT_MASK); - if(!this->green_curve->is_unset() && - !Geom::are_near(*this->green_curve->last_point(),this->p[0])) - { - std::unique_ptr<SPCurve> lsegment(new SPCurve()); - Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const*>(&*this->green_curve->last_segment()); + if (!this->green_curve->is_unset() && !Geom::are_near(*this->green_curve->last_point(), this->p[0])) { + std::unique_ptr<SPCurve> lsegment(new SPCurve()); + Geom::CubicBezier const *cubic = + dynamic_cast<Geom::CubicBezier const *>(&*this->green_curve->last_segment()); if (cubic) { lsegment->moveto((*cubic)[0]); - lsegment->curveto((*cubic)[1], this->p[0] - ((*cubic)[2] - (*cubic)[3]), *this->red_curve->first_point()); + lsegment->curveto((*cubic)[1], this->p[0] - ((*cubic)[2] - (*cubic)[3]), + *this->red_curve->first_point()); this->green_curve->backspace(); green_curve->append_continuous(*lsegment); } @@ -1873,7 +1894,8 @@ void PenTool::_finishSegment(Geom::Point const p, guint const state) { /// \todo fixme: SPCanvasItem *canvas_shape = sp_canvas_bpath_new(this->desktop->getSketch(), curve.get(), true); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvas_shape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvas_shape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, + SP_STROKE_LINECAP_BUTT); this->green_bpaths.push_back(canvas_shape); @@ -1887,12 +1909,13 @@ void PenTool::_finishSegment(Geom::Point const p, guint const state) { // Partial fix for https://bugs.launchpad.net/inkscape/+bug/171990 // TODO: implement the redo feature -bool PenTool::_undoLastPoint() { +bool PenTool::_undoLastPoint() +{ bool ret = false; - if ( this->green_curve->is_unset() || (this->green_curve->last_segment() == nullptr) ) { + if (this->green_curve->is_unset() || (this->green_curve->last_segment() == nullptr)) { if (!this->red_curve->is_unset()) { - this->_cancel (); + this->_cancel(); ret = true; } else { // do nothing; this event should be handled upstream @@ -1901,14 +1924,14 @@ bool PenTool::_undoLastPoint() { // Reset red curve this->red_curve->reset(); // Get last segment - if ( this->green_curve->is_unset() ) { + if (this->green_curve->is_unset()) { g_warning("pen_handle_key_press, case GDK_KP_Delete: Green curve is empty"); return false; } // The code below assumes that this->green_curve has only ONE path ! - Geom::Curve const * crv = this->green_curve->last_segment(); + 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)) { + if (Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>(crv)) { this->p[1] = (*cubic)[1]; } else { @@ -1916,11 +1939,11 @@ bool PenTool::_undoLastPoint() { } // assign the value in a third of the distance of the last segment. - if (this->bspline){ - this->p[1] = this->p[0] + (1./3)*(this->p[3] - this->p[0]); + if (this->bspline) { + this->p[1] = this->p[0] + (1. / 3) * (this->p[3] - this->p[0]); } - Geom::Point const pt( (this->npoints < 4) ? crv->finalPoint() : this->p[3] ); + Geom::Point const pt((this->npoints < 4) ? crv->finalPoint() : this->p[3]); this->npoints = 2; // delete the last segment of the green curve and green bpath @@ -1942,9 +1965,9 @@ bool PenTool::_undoLastPoint() { } // assign the value of this->p[1] to the opposite of the green line last segment - if (this->spiro){ + if (this->spiro) { Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const *>(this->green_curve->last_segment()); - if ( cubic ) { + if (cubic) { this->p[1] = (*cubic)[3] + (*cubic)[3] - (*cubic)[2]; SP_CTRL(this->c1)->moveto(this->p[0]); } else { @@ -1958,19 +1981,19 @@ bool PenTool::_undoLastPoint() { sp_canvas_item_hide(this->cl1); this->state = PenTool::POINT; - if(this->polylines_paraxial) { + if (this->polylines_paraxial) { // We compare the point we're removing with the nearest horiz/vert to // see if the line was added with SHIFT or not. Geom::Point compare(pt); this->_setToNearestHorizVert(compare, 0); - if ((std::abs(compare[Geom::X] - pt[Geom::X]) > 1e-9) - || (std::abs(compare[Geom::Y] - pt[Geom::Y]) > 1e-9)) { + if ((std::abs(compare[Geom::X] - pt[Geom::X]) > 1e-9) || + (std::abs(compare[Geom::Y] - pt[Geom::Y]) > 1e-9)) { this->paraxial_angle = this->paraxial_angle.cw(); } } this->_setSubsequentPoint(pt, true); - //redraw + // redraw this->_bsplineSpiroBuild(); ret = true; } @@ -1978,13 +2001,13 @@ bool PenTool::_undoLastPoint() { return ret; } -void PenTool::_finish(gboolean const closed) { +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(); @@ -2016,17 +2039,21 @@ void PenTool::_finish(gboolean const closed) { this->_enableEvents(); } -void PenTool::_disableEvents() { +void PenTool::_disableEvents() +{ this->events_disabled = true; } -void PenTool::_enableEvents() { +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) { +void PenTool::waitForLPEMouseClicks(Inkscape::LivePathEffect::EffectType effect_type, unsigned int num_clicks, + bool use_polylines) +{ if (effect_type == Inkscape::LivePathEffect::INVALID_LPE) return; @@ -2036,7 +2063,8 @@ void PenTool::waitForLPEMouseClicks(Inkscape::LivePathEffect::EffectType effect_ this->polylines_paraxial = false; // TODO: think if this is correct for all cases } -void PenTool::nextParaxialDirection(Geom::Point const &pt, Geom::Point const &origin, guint state) { +void PenTool::nextParaxialDirection(Geom::Point const &pt, Geom::Point const &origin, guint state) +{ // // 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 @@ -2052,12 +2080,13 @@ void PenTool::nextParaxialDirection(Geom::Point const &pt, Geom::Point const &or double v = pt[Geom::Y] - origin[Geom::Y]; this->paraxial_angle = Geom::Point(h, v).ccw(); } - if(!(state & GDK_SHIFT_MASK)) { + if (!(state & GDK_SHIFT_MASK)) { this->paraxial_angle = this->paraxial_angle.ccw(); } } -void PenTool::_setToNearestHorizVert(Geom::Point &pt, guint const state) const { +void PenTool::_setToNearestHorizVert(Geom::Point &pt, guint const state) const +{ Geom::Point const origin = this->p[0]; Geom::Point const target = (state & GDK_SHIFT_MASK) ? this->paraxial_angle : this->paraxial_angle.ccw(); @@ -2068,7 +2097,8 @@ void PenTool::_setToNearestHorizVert(Geom::Point &pt, guint const state) const { SnapManager &m = this->desktop->namedview->snap_manager; Inkscape::Selection *selection = this->desktop->getSelection(); - // selection->singleItem() is the item that is currently being drawn. This item will not be snapped to (to avoid self-snapping) + // 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()); @@ -2076,9 +2106,9 @@ void PenTool::_setToNearestHorizVert(Geom::Point &pt, guint const state) const { m.unSetup(); } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/pen-tool.h b/src/ui/tools/pen-tool.h index c9eefd05f91db9ef7b50aa589087cc7cdfd63f19..587a69533fc3c04e1c3074cbe5556f07618305b5 100644 --- a/src/ui/tools/pen-tool.h +++ b/src/ui/tools/pen-tool.h @@ -10,13 +10,12 @@ #ifndef SEEN_PEN_CONTEXT_H #define SEEN_PEN_CONTEXT_H - - -#include "ui/tools/freehand-base.h" #include "live_effects/effect.h" +#include "ui/tools/freehand-base.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) +#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; @@ -27,18 +26,21 @@ namespace Tools { /** * PenTool: a context for pen tool events. */ -class PenTool : public FreehandBase { +class PenTool : public FreehandBase +{ public: PenTool(); PenTool(gchar const *const *cursor_shape); ~PenTool() override; - enum Mode { + enum Mode + { MODE_CLICK, MODE_DRAG }; - enum State { + enum State + { POINT, CONTROL, CLOSE, @@ -62,7 +64,7 @@ public: bool bspline; int num_clicks; - unsigned int expecting_clicks_for_LPE; // if positive, finish the path after this many 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; @@ -71,24 +73,25 @@ public: SPCtrlLine *cl0; SPCtrlLine *cl1; - + bool events_disabled; static const std::string prefsPath; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; void nextParaxialDirection(Geom::Point const &pt, Geom::Point const &origin, guint state); void setPolylineMode(); bool hasWaitingLPE(); - void waitForLPEMouseClicks(Inkscape::LivePathEffect::EffectType effect_type, unsigned int num_clicks, bool use_polylines = true); + void waitForLPEMouseClicks(Inkscape::LivePathEffect::EffectType effect_type, unsigned int num_clicks, + bool use_polylines = true); protected: void setup() override; void finish() override; - void set(const Inkscape::Preferences::Entry& val) override; - bool root_handler(GdkEvent* event) override; - bool item_handler(SPItem* item, GdkEvent* event) override; + void set(const Inkscape::Preferences::Entry &val) override; + bool root_handler(GdkEvent *event) override; + bool item_handler(SPItem *item, GdkEvent *event) override; private: bool _handleButtonPress(GdkEventButton const &bevent); @@ -96,27 +99,28 @@ private: bool _handleButtonRelease(GdkEventButton const &revent); bool _handle2ButtonPress(GdkEventButton const &bevent); bool _handleKeyPress(GdkEvent *event); - //this function changes the colors red, green and blue making them transparent or not depending on if the function uses spiro + // this function changes the colors red, green and blue making them transparent or not depending on if the function + // uses spiro void _bsplineSpiroColor(); - //creates a node in bspline or spiro modes + // creates a node in bspline or spiro modes void _bsplineSpiro(bool shift); - //creates a node in bspline or spiro modes + // creates a node in bspline or spiro modes void _bsplineSpiroOn(); - //creates a CUSP node + // creates a CUSP node void _bsplineSpiroOff(); - //continues the existing curve in bspline or spiro mode + // continues the existing curve in bspline or spiro mode void _bsplineSpiroStartAnchor(bool shift); - //continues the existing curve with the union node in bspline or spiro modes + // continues the existing curve with the union node in bspline or spiro modes void _bsplineSpiroStartAnchorOn(); - //continues an existing curve with the union node in CUSP mode + // continues an existing curve with the union node in CUSP mode void _bsplineSpiroStartAnchorOff(); - //modifies the "red_curve" when it detects movement + // modifies the "red_curve" when it detects movement void _bsplineSpiroMotion(guint const state); - //closes the curve with the last node in bspline or spiro mode + // closes the curve with the last node in bspline or spiro mode void _bsplineSpiroEndAnchorOn(); - //closes the curve with the last node in CUSP mode + // closes the curve with the last node in CUSP mode void _bsplineSpiroEndAnchorOff(); - //apply the effect + // apply the effect void _bsplineSpiroBuild(); void _setInitialPoint(Geom::Point const p); @@ -148,9 +152,9 @@ private: void _cancel(); }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_PEN_CONTEXT_H */ diff --git a/src/ui/tools/pencil-tool.cpp b/src/ui/tools/pencil-tool.cpp index c421b2cdda02a4b4ff7c6d4a1ae99c3e7247abb1..a2d7f1f2a192bfaf63d9e96d2cbc2f84124c93b1 100644 --- a/src/ui/tools/pencil-tool.cpp +++ b/src/ui/tools/pencil-tool.cpp @@ -17,49 +17,40 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gdk/gdkkeysyms.h> - #include "ui/tools/pencil-tool.h" + #include <2geom/bezier-utils.h> #include <2geom/circle.h> #include <2geom/sbasis-to-bezier.h> #include <2geom/svg-path-parser.h> - -#include "desktop.h" +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> #include "context-fns.h" #include "desktop-style.h" -#include "message-context.h" -#include "message-stack.h" -#include "selection-chemistry.h" -#include "selection.h" -#include "snap.h" - +#include "desktop.h" #include "display/canvas-bpath.h" #include "display/curve.h" - -#include "livarot/Path.h" // Simplify paths - +#include "livarot/Path.h" // Simplify paths #include "live_effects/lpe-powerstroke-interpolators.h" #include "live_effects/lpe-powerstroke.h" #include "live_effects/lpe-simplify.h" #include "live_effects/lpeobject.h" - +#include "message-context.h" +#include "message-stack.h" #include "object/sp-lpe-item.h" #include "object/sp-path.h" #include "path/path-boolop.h" +#include "selection-chemistry.h" +#include "selection.h" +#include "snap.h" #include "style.h" - -#include "ui/pixmaps/cursor-pencil.xpm" - #include "svg/svg.h" - #include "ui/draw-anchor.h" +#include "ui/pixmaps/cursor-pencil.xpm" #include "ui/tool/event-utils.h" - #include "xml/node.h" #include "xml/sp-css-attr.h" -#include <glibmm/i18n.h> // #include <thread> // #include <chrono> @@ -70,11 +61,15 @@ 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; } +static bool in_svg_plane(Geom::Point const &p) +{ + return Geom::LInfty(p) < 1e18; +} const double HANDLE_CUBIC_GAP = 0.01; -const std::string& PencilTool::getPrefsPath() { - return PencilTool::prefsPath; +const std::string &PencilTool::getPrefsPath() +{ + return PencilTool::prefsPath; } const std::string PencilTool::prefsPath = "/tools/freehand/pencil"; @@ -88,10 +83,10 @@ PencilTool::PencilTool() , _is_drawing(false) , sketch_n(0) , _pressure_curve(nullptr) -{ -} +{} -void PencilTool::setup() { +void PencilTool::setup() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs->getBool("/tools/freehand/pencil/selcue")) { this->enableSelectionCue(); @@ -104,14 +99,12 @@ void PencilTool::setup() { this->anchor_statusbar = false; } +PencilTool::~PencilTool() {} - -PencilTool::~PencilTool() { -} - -void PencilTool::_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); +void PencilTool::_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); is_tablet = true; } else { this->pressure = DDC_DEFAULT_PRESSURE; @@ -120,15 +113,16 @@ void PencilTool::_extinput(GdkEvent *event) { } /** 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 +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 explicitly asked for angular snapping by - //pressing CTRL + if (!(state & GDK_SHIFT_MASK)) { // SHIFT disables all snapping, except the angular snapping above + // After all, the user explicitly 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); } @@ -138,7 +132,8 @@ void PencilTool::_endpointSnap(Geom::Point &p, guint const state) { /** * Callback for handling all pencil context events. */ -bool PencilTool::root_handler(GdkEvent* event) { +bool PencilTool::root_handler(GdkEvent *event) +{ bool ret = false; this->_extinput(event); switch (event->type) { @@ -172,9 +167,10 @@ bool PencilTool::root_handler(GdkEvent* event) { return ret; } -bool PencilTool::_handleButtonPress(GdkEventButton const &bevent) { +bool PencilTool::_handleButtonPress(GdkEventButton const &bevent) +{ bool ret = false; - if ( bevent.button == 1 && !this->space_panning) { + if (bevent.button == 1 && !this->space_panning) { Inkscape::Selection *selection = desktop->getSelection(); if (Inkscape::have_viable_layer(desktop, defaultMessageContext()) == false) { @@ -184,10 +180,10 @@ bool PencilTool::_handleButtonPress(GdkEventButton const &bevent) { 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 ), - nullptr, bevent.time); + sp_canvas_item_grab( + this->grab, + (GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK), + nullptr, bevent.time); } Geom::Point const button_w(bevent.x, bevent.y); @@ -200,7 +196,7 @@ bool PencilTool::_handleButtonPress(GdkEventButton const &bevent) { if (tablet_enabled) { anchor = nullptr; } - pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y); + pencil_drag_origin_w = Geom::Point(bevent.x, bevent.y); pencil_within_tolerance = true; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); tablet_enabled = prefs->getBool("/tools/freehand/pencil/pressure", false); @@ -216,7 +212,7 @@ bool PencilTool::_handleButtonPress(GdkEventButton const &bevent) { m.setup(desktop, true); if (!(bevent.state & GDK_SHIFT_MASK)) { m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE); - } + } spdc_create_single_dot(this, p, "/tools/freehand/pencil", bevent.state); m.unSetup(); ret = true; @@ -224,7 +220,7 @@ bool PencilTool::_handleButtonPress(GdkEventButton const &bevent) { } if (anchor) { p = anchor->dp; - //Put the start overwrite curve always on the same direction + // Put the start overwrite curve always on the same direction if (anchor->start) { this->sa_overwrited = anchor->curve->create_reverse(); } else { @@ -266,7 +262,8 @@ bool PencilTool::_handleButtonPress(GdkEventButton const &bevent) { return ret; } -bool PencilTool::_handleMotionNotify(GdkEventMotion const &mevent) { +bool PencilTool::_handleMotionNotify(GdkEventMotion const &mevent) +{ 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 @@ -286,26 +283,24 @@ bool PencilTool::_handleMotionNotify(GdkEventMotion const &mevent) { // tablet event was accidentally fired without press; return ret; } - - if ( ( mevent.state & GDK_BUTTON1_MASK ) && !this->grab && this->_is_drawing) { + + if ((mevent.state & GDK_BUTTON1_MASK) && !this->grab && this->_is_drawing) { /* 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 ), - nullptr, mevent.time); + sp_canvas_item_grab( + this->grab, + (GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK), nullptr, + mevent.time); } /* Find desktop coordinates */ Geom::Point p = desktop->w2d(Geom::Point(mevent.x, mevent.y)); - - - + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (pencil_within_tolerance) { 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. + 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. } } @@ -313,8 +308,8 @@ bool PencilTool::_handleMotionNotify(GdkEventMotion const &mevent) { // (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; - - anchor = spdc_test_inside(this, Geom::Point(mevent.x,mevent.y)); + + anchor = spdc_test_inside(this, Geom::Point(mevent.x, mevent.y)); switch (this->_state) { case SP_PENCIL_CONTEXT_ADDLINE: @@ -335,20 +330,20 @@ bool PencilTool::_handleMotionNotify(GdkEventMotion const &mevent) { break; default: /* We may be idle or already freehand */ - if ( (mevent.state & GDK_BUTTON1_MASK) && this->_is_drawing ) { + if ((mevent.state & GDK_BUTTON1_MASK) && this->_is_drawing) { if (this->_state == SP_PENCIL_CONTEXT_IDLE) { sp_event_context_discard_delayed_snap_event(this); } this->_state = SP_PENCIL_CONTEXT_FREEHAND; - if ( !this->sa && !this->green_anchor ) { + if (!this->sa && !this->green_anchor) { /* Create green anchor */ this->green_anchor = sp_draw_anchor_new(this, this->green_curve.get(), TRUE, this->p[0]); } if (anchor) { p = anchor->dp; } - if ( this->_npoints != 0) { // buttonpress may have happened before we entered draw context! + 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 this->ps (apparently) // - We cannot add this point in spdc_set_startpoint, because we only need it for freehand @@ -363,7 +358,8 @@ bool PencilTool::_handleMotionNotify(GdkEventMotion const &mevent) { 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->message_context->set(Inkscape::NORMAL_MESSAGE, + _("<b>Release</b> here to close and finish the path.")); this->anchor_statusbar = true; this->ea = anchor; } else if (!anchor && this->anchor_statusbar) { @@ -377,7 +373,8 @@ bool PencilTool::_handleMotionNotify(GdkEventMotion const &mevent) { } else { if (anchor && !this->anchor_statusbar) { - this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point.")); + 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(); @@ -399,12 +396,13 @@ bool PencilTool::_handleMotionNotify(GdkEventMotion const &mevent) { return ret; } -bool PencilTool::_handleButtonRelease(GdkEventButton const &revent) { +bool PencilTool::_handleButtonRelease(GdkEventButton const &revent) +{ bool ret = false; set_high_motion_precision(false); - if ( revent.button == 1 && this->_is_drawing && !this->space_panning) { + if (revent.button == 1 && this->_is_drawing && !this->space_panning) { this->_is_drawing = false; /* Find desktop coordinates */ @@ -424,11 +422,11 @@ bool PencilTool::_handleButtonRelease(GdkEventButton const &revent) { /*Or select the down item if we are in tablet mode*/ if (is_tablet) { using namespace Inkscape::LivePathEffect; - SPItem * item = sp_event_context_find_item (desktop, Geom::Point(revent.x, revent.y), FALSE, FALSE); + SPItem *item = sp_event_context_find_item(desktop, Geom::Point(revent.x, revent.y), FALSE, FALSE); if (item && (!this->white_item || item != white_item)) { - Effect* lpe = SP_LPE_ITEM(item)->getCurrentLPE(); + Effect *lpe = SP_LPE_ITEM(item)->getCurrentLPE(); if (lpe) { - LPEPowerStroke* ps = static_cast<LPEPowerStroke*>(lpe); + LPEPowerStroke *ps = static_cast<LPEPowerStroke *>(lpe); if (ps) { desktop->selection->clear(); desktop->selection->add(item); @@ -452,7 +450,8 @@ bool PencilTool::_handleButtonRelease(GdkEventButton const &revent) { break; case SP_PENCIL_CONTEXT_FREEHAND: if (revent.state & GDK_MOD1_MASK && !tablet_enabled) { - /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */ + /* 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) { @@ -527,7 +526,8 @@ bool PencilTool::_handleButtonRelease(GdkEventButton const &revent) { return ret; } -void PencilTool::_cancel() { +void PencilTool::_cancel() +{ if (this->grab) { /* Release grab now */ sp_canvas_item_ungrab(this->grab); @@ -540,7 +540,7 @@ void PencilTool::_cancel() { this->red_curve->reset(); sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), nullptr); - for (auto i:this->green_bpaths) { + for (auto i : this->green_bpaths) { sp_canvas_item_destroy(i); } this->green_bpaths.clear(); @@ -553,7 +553,8 @@ void PencilTool::_cancel() { this->message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled")); } -bool PencilTool::_handleKeyPress(GdkEventKey const &event) { +bool PencilTool::_handleKeyPress(GdkEventKey const &event) +{ bool ret = false; switch (get_latin_keyval(&event)) { @@ -597,7 +598,9 @@ bool PencilTool::_handleKeyPress(GdkEventKey const &event) { 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.")); + 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: @@ -606,7 +609,8 @@ bool PencilTool::_handleKeyPress(GdkEventKey const &event) { return ret; } -bool PencilTool::_handleKeyRelease(GdkEventKey const &event) { +bool PencilTool::_handleKeyRelease(GdkEventKey const &event) +{ bool ret = false; switch (get_latin_keyval(&event)) { @@ -637,7 +641,8 @@ bool PencilTool::_handleKeyRelease(GdkEventKey const &event) { /** * Reset points and set new starting point. */ -void PencilTool::_setStartpoint(Geom::Point const &p) { +void PencilTool::_setStartpoint(Geom::Point const &p) +{ this->_npoints = 0; this->red_curve_is_valid = false; if (in_svg_plane(p)) { @@ -655,19 +660,18 @@ void PencilTool::_setStartpoint(Geom::Point const &p) { * Number of points is (re)set to 2 always, 2nd point is modified. * We change RED curve. */ -void PencilTool::_setEndpoint(Geom::Point const &p) { +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 ); + g_return_if_fail(this->_npoints > 0); this->red_curve->reset(); - if ( ( p == this->p[0] ) - || !in_svg_plane(p) ) - { + if ((p == this->p[0]) || !in_svg_plane(p)) { this->_npoints = 1; } else { this->p[1] = p; @@ -689,10 +693,9 @@ void PencilTool::_setEndpoint(Geom::Point const &p) { * 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_unset() || - this->red_curve->first_point() == this->red_curve->second_point()) - { +void PencilTool::_finishEndpoint() +{ + if (this->red_curve->is_unset() || this->red_curve->first_point() == this->red_curve->second_point()) { this->red_curve->reset(); if (!tablet_enabled) { sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), nullptr); @@ -705,9 +708,10 @@ void PencilTool::_finishEndpoint() { } } -static inline double square(double const x) { return x * x; } - - +static inline double square(double const x) +{ + return x * x; +} void PencilTool::addPowerStrokePencil() { @@ -823,7 +827,7 @@ void PencilTool::addPowerStrokePencil() pspreview->getRepr()->setAttribute("sort_points", "true"); pspreview->getRepr()->setAttribute("not_jump", "true"); if (!this->points.size()) { - Geom::Point default_point((path.size()/2.0), 0.5); + Geom::Point default_point((path.size() / 2.0), 0.5); this->points.push_back(default_point); } pspreview->offset_points.param_set_and_write_new_value(this->points); @@ -845,13 +849,11 @@ void PencilTool::addPowerStrokePencil() */ void PencilTool::_addFreehandPoint(Geom::Point const &p, guint /*state*/, bool last) { - g_assert( this->_npoints > 0 ); + g_assert(this->_npoints > 0); g_return_if_fail(unsigned(this->_npoints) < G_N_ELEMENTS(this->p)); double distance = 0; - if ( ( p != this->p[ this->_npoints - 1 ] ) - && in_svg_plane(p) ) - { + if ((p != this->p[this->_npoints - 1]) && in_svg_plane(p)) { this->p[this->_npoints++] = p; this->_fitAndSplit(); if (tablet_enabled) { @@ -861,7 +863,7 @@ void PencilTool::_addFreehandPoint(Geom::Point const &p, guint /*state*/, bool l } if (tablet_enabled && in_svg_plane(p)) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - double min = prefs->getIntLimited("/tools/freehand/pencil/minpressure", 0, 0, 100) / 100.0; + double min = prefs->getIntLimited("/tools/freehand/pencil/minpressure", 0, 0, 100) / 100.0; double max = prefs->getIntLimited("/tools/freehand/pencil/maxpressure", 30, 0, 100) / 100.0; if (min > max) { min = max; @@ -869,7 +871,8 @@ void PencilTool::_addFreehandPoint(Geom::Point const &p, guint /*state*/, bool l double dezoomify_factor = 0.05 * 1000 / desktop->current_zoom(); double pressure_shrunk = (((this->pressure - 0.25) * 1.25) * (max - min)) + min; double pressure_computed = std::abs(pressure_shrunk * dezoomify_factor); - double pressure_computed_scaled = std::abs(pressure_computed * desktop->getDocument()->getDocumentScale().inverse()[Geom::X]); + double pressure_computed_scaled = + std::abs(pressure_computed * desktop->getDocument()->getDocumentScale().inverse()[Geom::X]); if (p != this->p[this->_npoints - 1]) { this->_wps.emplace_back(distance, pressure_computed_scaled); } @@ -882,7 +885,8 @@ void PencilTool::_addFreehandPoint(Geom::Point const &p, guint /*state*/, bool l Geom::PathVector pressure_path = Geom::path_from_piecewise(pressure_piecewise, 0.1); Geom::PathVector previous_presure = this->_pressure_curve->get_pathvector(); if (!pressure_path.empty() && !previous_presure.empty()) { - pressure_path = sp_pathvector_boolop(pressure_path, previous_presure, bool_op_union, fill_nonZero, fill_nonZero); + pressure_path = + sp_pathvector_boolop(pressure_path, previous_presure, bool_op_union, fill_nonZero, fill_nonZero); } this->_pressure_curve->set_pathvector(pressure_path); sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(red_bpath), _pressure_curve.get()); @@ -896,7 +900,7 @@ void PencilTool::_addFreehandPoint(Geom::Point const &p, guint /*state*/, bool l void PencilTool::powerStrokeInterpolate(Geom::Path const path) { size_t ps_size = this->ps.size(); - if ( ps_size <= 1 ) { + if (ps_size <= 1) { return; } @@ -918,7 +922,7 @@ void PencilTool::powerStrokeInterpolate(Geom::Path const path) for (auto wps : this->_wps) { i++; Geom::Coord pressure = wps[Geom::Y]; - max10 = max10 > pressure ? max10 : pressure; + max10 = max10 > pressure ? max10 : pressure; min10 = min10 <= pressure ? min10 : pressure; if (!original_lenght || wps[Geom::X] > max) { break; @@ -958,9 +962,10 @@ void PencilTool::powerStrokeInterpolate(Geom::Path const path) tmp_points.clear(); } -void PencilTool::_interpolate() { +void PencilTool::_interpolate() +{ size_t ps_size = this->ps.size(); - if ( ps_size <= 1 ) { + if (ps_size <= 1) { return; } using Geom::X; @@ -968,9 +973,9 @@ void PencilTool::_interpolate() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4; bool simplify = prefs->getInt("/tools/freehand/pencil/simplify", 0); - if(simplify){ + if (simplify) { double tol2 = prefs->getDoubleLimited("/tools/freehand/pencil/base-simplify", 25.0, 0.0, 100.0) * 0.4; - tol = std::min(tol,tol2); + tol = std::min(tol, tol2); } this->green_curve->reset(); this->red_curve->reset(); @@ -992,13 +997,13 @@ void PencilTool::_interpolate() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); guint mode = prefs->getInt("/tools/freehand/pencil/freehand-mode", 0); for (int c = 0; c < n_segs; c++) { - // if we are in BSpline we modify the trace to create adhoc nodes + // if we are in BSpline we modify the trace to create adhoc nodes if (mode == 2) { - Geom::Point point_at1 = b[4 * c + 0] + (1./3) * (b[4 * c + 3] - b[4 * c + 0]); + Geom::Point point_at1 = b[4 * c + 0] + (1. / 3) * (b[4 * c + 3] - b[4 * c + 0]); point_at1 = Geom::Point(point_at1[X] + HANDLE_CUBIC_GAP, point_at1[Y] + HANDLE_CUBIC_GAP); - Geom::Point point_at2 = b[4 * c + 3] + (1./3) * (b[4 * c + 0] - b[4 * c + 3]); + Geom::Point point_at2 = b[4 * c + 3] + (1. / 3) * (b[4 * c + 0] - b[4 * c + 3]); point_at2 = Geom::Point(point_at2[X] + HANDLE_CUBIC_GAP, point_at2[Y] + HANDLE_CUBIC_GAP); - this->green_curve->curveto(point_at1,point_at2,b[4*c+3]); + this->green_curve->curveto(point_at1, point_at2, b[4 * c + 3]); } else { if (!tablet_enabled || c != n_segs - 1) { this->green_curve->curveto(b[4 * c + 1], b[4 * c + 2], b[4 * c + 3]); @@ -1020,36 +1025,35 @@ void PencilTool::_interpolate() { 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) + 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) ); + 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->_req_tangent = + ((Geom::is_zero(req_vec) || !in_svg_plane(req_vec)) ? Geom::Point(0, 0) : Geom::unit_vector(req_vec)); } } } - /* interpolates the sketched curve and tweaks the current sketch interpolation*/ -void PencilTool::_sketchInterpolate() { - if ( this->ps.size() <= 1 ) { +void PencilTool::_sketchInterpolate() +{ + if (this->ps.size() <= 1) { return; } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4; bool simplify = prefs->getInt("/tools/freehand/pencil/simplify", 0); - if(simplify){ + if (simplify) { double tol2 = prefs->getDoubleLimited("/tools/freehand/pencil/base-simplify", 25.0, 1.0, 100.0) * 0.4; - tol = std::min(tol,tol2); + tol = std::min(tol, tol2); } double 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)); @@ -1073,7 +1077,7 @@ void PencilTool::_sketchInterpolate() { 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(); + Geom::Piecewise<Geom::D2<Geom::SBasis>> fit_pwd2 = fit.toPwSb(); if (this->sketch_n > 0) { double t; @@ -1112,16 +1116,15 @@ void PencilTool::_sketchInterpolate() { /* 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) + 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) ); + 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->_req_tangent = + ((Geom::is_zero(req_vec) || !in_svg_plane(req_vec)) ? Geom::Point(0, 0) : Geom::unit_vector(req_vec)); } } @@ -1130,37 +1133,34 @@ void PencilTool::_sketchInterpolate() { this->_wps.clear(); } -void PencilTool::_fitAndSplit() { - g_assert( this->_npoints > 1 ); +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)); + g_assert(is_zero(this->_req_tangent) || is_unit_vector(this->_req_tangent)); Geom::Point const tHatEnd(0, 0); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - int const n_segs = Geom::bezier_fit_cubic_full(b, nullptr, this->p, this->_npoints, - this->_req_tangent, tHatEnd, - tolerance_sq, 1); - if ( n_segs > 0 - && unsigned(this->_npoints) < G_N_ELEMENTS(this->p) ) - { + int const n_segs = + Geom::bezier_fit_cubic_full(b, nullptr, 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]); using Geom::X; using Geom::Y; - // if we are in BSpline we modify the trace to create adhoc nodes + // if we are in BSpline we modify the trace to create adhoc nodes guint mode = prefs->getInt("/tools/freehand/pencil/freehand-mode", 0); - if(mode == 2){ - Geom::Point point_at1 = b[0] + (1./3)*(b[3] - b[0]); + if (mode == 2) { + Geom::Point point_at1 = b[0] + (1. / 3) * (b[3] - b[0]); point_at1 = Geom::Point(point_at1[X] + HANDLE_CUBIC_GAP, point_at1[Y] + HANDLE_CUBIC_GAP); - Geom::Point point_at2 = b[3] + (1./3)*(b[0] - b[3]); + Geom::Point point_at2 = b[3] + (1. / 3) * (b[0] - b[3]); point_at2 = Geom::Point(point_at2[X] + HANDLE_CUBIC_GAP, point_at2[Y] + HANDLE_CUBIC_GAP); - this->red_curve->curveto(point_at1,point_at2,b[3]); - }else{ + this->red_curve->curveto(point_at1, point_at2, b[3]); + } else { this->red_curve->curveto(b[1], b[2], b[3]); } if (!tablet_enabled) { @@ -1174,16 +1174,15 @@ void PencilTool::_fitAndSplit() { /* 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) + 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) ); + 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->_req_tangent = + ((Geom::is_zero(req_vec) || !in_svg_plane(req_vec)) ? Geom::Point(0, 0) : Geom::unit_vector(req_vec)); } green_curve->append_continuous(*red_curve); @@ -1193,12 +1192,13 @@ void PencilTool::_fitAndSplit() { SPCanvasItem *cshape = sp_canvas_bpath_new(this->desktop->getSketch(), curve.get(), true); this->highlight_color = SP_ITEM(this->desktop->currentLayer())->highlight_color(); - if((unsigned int)prefs->getInt("/tools/nodes/highlight_color", 0xff0000ff) == this->highlight_color){ + if ((unsigned int)prefs->getInt("/tools/nodes/highlight_color", 0xff0000ff) == this->highlight_color) { this->green_color = 0x00ff007f; } else { this->green_color = this->highlight_color; } - 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_stroke(SP_CANVAS_BPATH(cshape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, + SP_STROKE_LINECAP_BUTT); this->green_bpaths.push_back(cshape); @@ -1206,9 +1206,9 @@ void PencilTool::_fitAndSplit() { } } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/pencil-tool.h b/src/ui/tools/pencil-tool.h index 271265ba02028a84def2d55903a9ca75990d4e7f..24d9e14e174379abbe99bedf715daae804dd1bf3 100644 --- a/src/ui/tools/pencil-tool.h +++ b/src/ui/tools/pencil-tool.h @@ -10,30 +10,31 @@ #ifndef SEEN_PENCIL_CONTEXT_H #define SEEN_PENCIL_CONTEXT_H - -#include "ui/tools/freehand-base.h" - -#include <2geom/piecewise.h> #include <2geom/d2.h> -#include <2geom/sbasis.h> #include <2geom/pathvector.h> +#include <2geom/piecewise.h> +#include <2geom/sbasis.h> + +#include "ui/tools/freehand-base.h" // #include <future> #include <memory> class SPShape; -#define DDC_MIN_PRESSURE 0.0 -#define DDC_MAX_PRESSURE 1.0 -#define DDC_DEFAULT_PRESSURE 1.0 -#define SP_PENCIL_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::PencilTool*>((Inkscape::UI::Tools::ToolBase*)obj)) -#define SP_IS_PENCIL_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::PencilTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) +#define DDC_MIN_PRESSURE 0.0 +#define DDC_MAX_PRESSURE 1.0 +#define DDC_DEFAULT_PRESSURE 1.0 +#define SP_PENCIL_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::PencilTool *>((Inkscape::UI::Tools::ToolBase *)obj)) +#define SP_IS_PENCIL_CONTEXT(obj) \ + (dynamic_cast<const Inkscape::UI::Tools::PencilTool *>((const Inkscape::UI::Tools::ToolBase *)obj) != NULL) namespace Inkscape { namespace UI { namespace Tools { -enum PencilState { +enum PencilState +{ SP_PENCIL_CONTEXT_IDLE, SP_PENCIL_CONTEXT_ADDLINE, SP_PENCIL_CONTEXT_FREEHAND, @@ -43,7 +44,8 @@ enum PencilState { /** * PencilTool: a context for pencil tool events */ -class PencilTool : public FreehandBase { +class PencilTool : public FreehandBase +{ public: PencilTool(); ~PencilTool() override; @@ -52,15 +54,14 @@ public: std::vector<Geom::Point> points; void addPowerStrokePencil(); void powerStrokeInterpolate(Geom::Path const path); - Geom::Piecewise<Geom::D2<Geom::SBasis> > sketch_interpolation; // the current proposal from the sketched paths - unsigned sketch_n; // number of sketches done + 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; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; protected: - void setup() override; - bool root_handler(GdkEvent* event) override; + bool root_handler(GdkEvent *event) override; private: bool _handleButtonPress(GdkEventButton const &bevent); @@ -87,9 +88,9 @@ private: // std::future<bool> future; }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_PENCIL_CONTEXT_H */ diff --git a/src/ui/tools/rect-tool.cpp b/src/ui/tools/rect-tool.cpp index 9a4813075d7032fe89bd13c5eaac2bd3f0e6392f..5147fff56715d4f523cd61fc6f43315eff91a737 100644 --- a/src/ui/tools/rect-tool.cpp +++ b/src/ui/tools/rect-tool.cpp @@ -15,33 +15,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> -#include <string> +#include "ui/tools/rect-tool.h" +#include <cstring> #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> +#include <string> #include "context-fns.h" #include "desktop-style.h" #include "desktop.h" +#include "display/sp-canvas-item.h" #include "document-undo.h" #include "document.h" #include "include/macros.h" #include "message-context.h" +#include "object/sp-namedview.h" +#include "object/sp-rect.h" #include "selection-chemistry.h" #include "selection.h" -#include "verbs.h" - -#include "display/sp-canvas-item.h" - -#include "object/sp-rect.h" -#include "object/sp-namedview.h" - #include "ui/pixmaps/cursor-rect.xpm" - #include "ui/shape-editor.h" -#include "ui/tools/rect-tool.h" - +#include "verbs.h" #include "xml/node-event-vector.h" using Inkscape::DocumentUndo; @@ -50,8 +45,9 @@ namespace Inkscape { namespace UI { namespace Tools { -const std::string& RectTool::getPrefsPath() { - return RectTool::prefsPath; +const std::string &RectTool::getPrefsPath() +{ + return RectTool::prefsPath; } const std::string RectTool::prefsPath = "/tools/shapes/rect"; @@ -61,19 +57,20 @@ RectTool::RectTool() , rect(nullptr) , rx(0) , ry(0) -{ -} +{} -void RectTool::finish() { +void RectTool::finish() +{ sp_canvas_item_ungrab(SP_CANVAS_ITEM(this->desktop->acetate)); - + this->finishItem(); this->sel_changed_connection.disconnect(); ToolBase::finish(); } -RectTool::~RectTool() { +RectTool::~RectTool() +{ this->enableGrDrag(false); this->sel_changed_connection.disconnect(); @@ -91,12 +88,14 @@ RectTool::~RectTool() { * Callback that processes the "changed" signal on the selection; * destroys old and creates new knotholder. */ -void RectTool::selection_changed(Inkscape::Selection* selection) { +void RectTool::selection_changed(Inkscape::Selection *selection) +{ this->shape_editor->unset_item(); this->shape_editor->set_item(selection->singleItem()); } -void RectTool::setup() { +void RectTool::setup() +{ ToolBase::setup(); this->shape_editor = new ShapeEditor(this->desktop); @@ -107,9 +106,8 @@ void RectTool::setup() { } this->sel_changed_connection.disconnect(); - this->sel_changed_connection = this->desktop->getSelection()->connectChanged( - sigc::mem_fun(this, &RectTool::selection_changed) - ); + this->sel_changed_connection = + this->desktop->getSelection()->connectChanged(sigc::mem_fun(this, &RectTool::selection_changed)); sp_event_context_read(this, "rx"); sp_event_context_read(this, "ry"); @@ -124,38 +122,41 @@ void RectTool::setup() { } } -void RectTool::set(const Inkscape::Preferences::Entry& val) { +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" ) { + + if (name == "rx") { this->rx = val.getDoubleLimited(); // prevents NaN and +/-Inf from messing up - } else if ( name == "ry" ) { + } else if (name == "ry") { this->ry = val.getDoubleLimited(); } } -bool RectTool::item_handler(SPItem* item, GdkEvent* event) { +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); - } - break; - // motion and release are always on root (why?) - default: - break; + 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; } - ret = ToolBase::item_handler(item, event); + ret = ToolBase::item_handler(item, event); return ret; } -bool RectTool::root_handler(GdkEvent* event) { +bool RectTool::root_handler(GdkEvent *event) +{ static bool dragging; SPDesktop *desktop = this->desktop; @@ -166,196 +167,192 @@ bool RectTool::root_handler(GdkEvent* event) { 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 ), - nullptr, 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(); - } + 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), + nullptr, event->button.time); - this->item_to_select = nullptr; - ret = TRUE; - sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); - } - break; - case GDK_KEY_PRESS: - switch (get_latin_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"), - nullptr); - } - break; - case GDK_KEY_x: - case GDK_KEY_X: - if (MOD__ALT_ONLY(event)) { - desktop->setToolboxFocusTo("rect-width"); 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; - case GDK_KEY_g: - case GDK_KEY_G: - if (MOD__SHIFT_ONLY(event)) { - desktop->selection->toGuides(); - ret = true; - } - break; + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); - 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(); + 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_KEY_space: - if (dragging) { - sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); + 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(); } - // 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)); + this->item_to_select = nullptr; + ret = TRUE; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); + } break; - - default: + case GDK_KEY_PRESS: + switch (get_latin_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"), nullptr); + } + break; + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo("rect-width"); + ret = TRUE; + } + break; + + case GDK_KEY_g: + case GDK_KEY_G: + if (MOD__SHIFT_ONLY(event)) { + desktop->selection->toGuides(); + 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)); + 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; - } - break; - case GDK_KEY_RELEASE: - switch (get_latin_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(); + case GDK_KEY_RELEASE: + switch (get_latin_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; - } - break; - default: - break; } if (!ret) { - ret = ToolBase::root_handler(event); + ret = ToolBase::root_handler(event); } return ret; } -void RectTool::drag(Geom::Point const pt, guint state) { +void RectTool::drag(Geom::Point const pt, guint state) +{ SPDesktop *desktop = this->desktop; if (!this->rect) { @@ -368,7 +365,7 @@ void RectTool::drag(Geom::Point const pt, guint state) { Inkscape::XML::Node *repr = xml_doc->createElement("svg:rect"); // Set style - sp_desktop_apply_style_tool (desktop, repr, "/tools/shapes/rect", false); + sp_desktop_apply_style_tool(desktop, repr, "/tools/shapes/rect", false); this->rect = SP_RECT(desktop->currentLayer()->appendChildRepr(repr)); Inkscape::GC::release(repr); @@ -384,14 +381,14 @@ void RectTool::drag(Geom::Point const pt, guint 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); + 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)); + 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])); + this->rect->setRy(true, CLAMP(this->ry, 0, r.dimensions()[Geom::Y])); } // status text @@ -407,12 +404,12 @@ void RectTool::drag(Geom::Point const pt, guint state) { int ratio_x, ratio_y; bool is_golden_ratio = false; - if (fabs (rdimx) > fabs (rdimy)) { + if (fabs(rdimx) > fabs(rdimy)) { if (fabs(rdimx / rdimy - goldenratio) < 1e-6) { is_golden_ratio = true; } - ratio_x = (int) rint (rdimx / rdimy); + ratio_x = (int)rint(rdimx / rdimy); ratio_y = 1; } else { if (fabs(rdimy / rdimx - goldenratio) < 1e-6) { @@ -420,37 +417,43 @@ void RectTool::drag(Geom::Point const pt, guint state) { } ratio_x = 1; - ratio_y = (int) rint (rdimy / rdimx); + 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.c_str(), ys.c_str(), ratio_x, ratio_y); + _("<b>Rectangle</b>: %s × %s (constrained to ratio %d:%d); with " + "<b>Shift</b> to draw around the starting point"), + xs.c_str(), ys.c_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.c_str(), ys.c_str()); + _("<b>Rectangle</b>: %s × %s (constrained to golden ratio 1.618 : 1); " + "with <b>Shift</b> to draw around the starting point"), + xs.c_str(), ys.c_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.c_str(), ys.c_str()); + _("<b>Rectangle</b>: %s × %s (constrained to golden ratio 1 : 1.618); " + "with <b>Shift</b> to draw around the starting point"), + xs.c_str(), ys.c_str()); } } } else { this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, - _("<b>Rectangle</b>: %s × %s; with <b>Ctrl</b> to make square, integer-ratio, or golden-ratio rectangle; with <b>Shift</b> to draw around the starting point"), - xs.c_str(), ys.c_str()); + _("<b>Rectangle</b>: %s × %s; with <b>Ctrl</b> to make square, integer-ratio, " + "or golden-ratio rectangle; with <b>Shift</b> to draw around the starting point"), + xs.c_str(), ys.c_str()); } } -void RectTool::finishItem() { +void RectTool::finishItem() +{ this->message_context->clear(); if (this->rect != nullptr) { 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 + 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; } @@ -458,7 +461,7 @@ void RectTool::finishItem() { this->rect->doWriteTransform(this->rect->transform, nullptr, true); forced_redraws_stop(); - + this->desktop->getSelection()->set(this->rect); DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_RECT, _("Create rectangle")); @@ -467,7 +470,8 @@ void RectTool::finishItem() { } } -void RectTool::cancel(){ +void RectTool::cancel() +{ this->desktop->getSelection()->clear(); sp_canvas_item_ungrab(SP_CANVAS_ITEM(this->desktop->acetate)); @@ -486,9 +490,9 @@ void RectTool::cancel(){ DocumentUndo::cancel(this->desktop->getDocument()); } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/rect-tool.h b/src/ui/tools/rect-tool.h index 46330431173b92b1a8798dd61391ddadc520cfb4..495609699c0426dbf075918faa9f1ba277b357e1 100644 --- a/src/ui/tools/rect-tool.h +++ b/src/ui/tools/rect-tool.h @@ -16,9 +16,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <2geom/point.h> #include <cstddef> #include <sigc++/sigc++.h> -#include <2geom/point.h> + #include "ui/tools/tool-base.h" class SPRect; @@ -30,38 +31,39 @@ class Selection; namespace UI { namespace Tools { -class RectTool : public ToolBase { +class RectTool : public ToolBase +{ public: - RectTool(); - ~RectTool() override; + RectTool(); + ~RectTool() override; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - void finish() override; - void set(const Inkscape::Preferences::Entry& val) override; - bool root_handler(GdkEvent* event) override; - bool item_handler(SPItem* item, GdkEvent* event) override; + void setup() override; + void finish() override; + void set(const Inkscape::Preferences::Entry &val) override; + bool root_handler(GdkEvent *event) override; + bool item_handler(SPItem *item, GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; private: - SPRect *rect; - Geom::Point center; + SPRect *rect; + Geom::Point center; - gdouble rx; /* roundness radius (x direction) */ - gdouble ry; /* roundness radius (y direction) */ + gdouble rx; /* roundness radius (x direction) */ + gdouble ry; /* roundness radius (y direction) */ - sigc::connection sel_changed_connection; + sigc::connection sel_changed_connection; - void drag(Geom::Point const pt, guint state); - void finishItem(); - void cancel(); - void selection_changed(Inkscape::Selection* selection); + void drag(Geom::Point const pt, guint state); + void finishItem(); + void cancel(); + void selection_changed(Inkscape::Selection *selection); }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/tools/select-tool.cpp b/src/ui/tools/select-tool.cpp index d062367ede4e29aead48f25f0327842ee61b69b3..af9a7b275617f86f4741fdfb35572c9e2ebf3926 100644 --- a/src/ui/tools/select-tool.cpp +++ b/src/ui/tools/select-tool.cpp @@ -16,48 +16,41 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include <cstring> -#include <string> - -#include <gtkmm/widget.h> #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> +#include <gtkmm/widget.h> +#include <string> #include "desktop.h" +#include "display/drawing-item.h" +#include "display/sp-canvas-item.h" #include "document-undo.h" #include "document.h" #include "include/macros.h" #include "message-stack.h" +#include "object/box3d.h" #include "rubberband.h" #include "selection-chemistry.h" #include "selection-describer.h" #include "selection.h" #include "seltrans.h" #include "sp-cursor.h" - -#include "display/drawing-item.h" -#include "display/sp-canvas-item.h" - -#include "object/box3d.h" #include "style.h" - #include "ui/pixmaps/cursor-select-d.xpm" #include "ui/pixmaps/cursor-select-m.xpm" #include "ui/pixmaps/handles.xpm" - #include "ui/tools-switch.h" #include "ui/tools/select-tool.h" - #include "ui/widget/canvas.h" #ifdef WITH_DBUS #include "extension/dbus/document-interface.h" #endif - using Inkscape::DocumentUndo; GdkPixbuf *handles[23]; @@ -69,23 +62,24 @@ namespace Tools { static GdkCursor *CursorSelectMouseover = nullptr; static GdkCursor *CursorSelectDragging = nullptr; -static gint rb_escaped = 0; // if non-zero, rubberband was canceled by esc, so the next button release should not deselect +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 -const std::string& SelectTool::getPrefsPath() { +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) { +// 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++) { + 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); + handles[i] = gdk_pixbuf_rotate_simple(handles[i - 1], GDK_PIXBUF_ROTATE_CLOCKWISE); } } @@ -104,7 +98,7 @@ SelectTool::SelectTool() // cursors in select context CursorSelectMouseover = sp_cursor_from_xpm(cursor_select_m_xpm); CursorSelectDragging = sp_cursor_from_xpm(cursor_select_d_xpm); - + // selection handles sp_load_handles(0, 2, handle_scale_xpm); sp_load_handles(2, 2, handle_stretch_xpm); @@ -116,13 +110,13 @@ SelectTool::SelectTool() sp_load_handles(18, 4, handle_align_corner_xpm); } -//static gint xp = 0, yp = 0; // where drag started -//static gint tolerance = 0; -//static bool within_tolerance = false; +// static gint xp = 0, yp = 0; // where drag started +// static gint tolerance = 0; +// static bool within_tolerance = false; static bool is_cycling = false; - -SelectTool::~SelectTool() { +SelectTool::~SelectTool() +{ this->enableGrDrag(false); if (this->grabbed) { @@ -140,7 +134,7 @@ SelectTool::~SelectTool() { g_object_unref(CursorSelectDragging); CursorSelectDragging = nullptr; } - + if (CursorSelectMouseover) { g_object_unref(CursorSelectMouseover); CursorSelectMouseover = nullptr; @@ -154,15 +148,14 @@ SelectTool::~SelectTool() { forced_redraws_stop(); } -void SelectTool::setup() { +void SelectTool::setup() +{ ToolBase::setup(); this->_describer = new Inkscape::SelectionDescriber( - desktop->selection, - desktop->messageStack(), - _("Click selection to toggle scale/rotation handles (or Shift+s)"), - _("No objects selected. Click, Shift+click, Alt+scroll mouse on top of objects, or drag around objects to select.") - ); + desktop->selection, desktop->messageStack(), _("Click selection to toggle scale/rotation handles (or Shift+s)"), + _("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); @@ -176,7 +169,8 @@ void SelectTool::setup() { } } -void SelectTool::set(const Inkscape::Preferences::Entry& val) { +void SelectTool::set(const Inkscape::Preferences::Entry &val) +{ Glib::ustring path = val.getEntryName(); if (path == "show") { @@ -188,7 +182,8 @@ void SelectTool::set(const Inkscape::Preferences::Entry& val) { } } -bool SelectTool::sp_select_context_abort() { +bool SelectTool::sp_select_context_abort() +{ Inkscape::SelTrans *seltrans = this->_seltrans; if (this->dragging) { @@ -205,7 +200,7 @@ bool SelectTool::sp_select_context_abort() { DocumentUndo::undo(desktop->getDocument()); } - sp_object_unref( this->item, nullptr); + sp_object_unref(this->item, nullptr); } else if (this->button_press_state & GDK_CONTROL_MASK) { // NOTE: This is a workaround to a bug. // When the ctrl key is held, sc->item is not defined @@ -229,20 +224,15 @@ bool SelectTool::sp_select_context_abort() { 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) +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) +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. * @@ -259,11 +249,7 @@ sp_select_context_up_one_layer(SPDesktop *desktop) if (current_layer) { SPObject *const parent = current_layer->parent; SPGroup *current_group = dynamic_cast<SPGroup *>(current_layer); - if ( parent - && ( parent->parent - || !( current_group - && ( SPGroup::LAYER == current_group->layerMode() ) ) ) ) - { + if (parent && (parent->parent || !(current_group && (SPGroup::LAYER == current_group->layerMode())))) { desktop->setCurrentLayer(parent); if (current_group && (SPGroup::LAYER != current_group->layerMode())) { desktop->getSelection()->set(current_layer); @@ -272,7 +258,8 @@ sp_select_context_up_one_layer(SPDesktop *desktop) } } -bool SelectTool::item_handler(SPItem* item, GdkEvent* event) { +bool SelectTool::item_handler(SPItem *item, GdkEvent *event) +{ gint ret = FALSE; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -289,8 +276,8 @@ bool SelectTool::item_handler(SPItem* item, GdkEvent* event) { /* Left mousebutton */ // save drag origin - xp = (gint) event->button.x; - yp = (gint) event->button.y; + xp = (gint)event->button.x; + yp = (gint)event->button.y; within_tolerance = true; // remember what modifiers were on before button press @@ -300,22 +287,21 @@ bool SelectTool::item_handler(SPItem* item, GdkEvent* event) { // 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 (desktop->getCanvas()->gobj())); - + GdkWindow *window = gtk_widget_get_window(GTK_WIDGET(desktop->getCanvas()->gobj())); + this->dragging = TRUE; this->moved = FALSE; gdk_window_set_cursor(window, CursorSelectDragging); - // remember the clicked item in this->item: if (this->item) { sp_object_unref(this->item, nullptr); this->item = nullptr; } - this->item = sp_event_context_find_item (desktop, - Geom::Point(event->button.x, event->button.y), event->button.state & GDK_MOD1_MASK, FALSE); + 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, nullptr); rb_escaped = drag_escaped = 0; @@ -326,8 +312,9 @@ bool SelectTool::item_handler(SPItem* item, GdkEvent* event) { } 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, + 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, nullptr, event->button.time); this->grabbed = SP_CANVAS_ITEM(desktop->drawing); @@ -339,11 +326,10 @@ bool SelectTool::item_handler(SPItem* item, GdkEvent* event) { this->sp_select_context_abort(); } break; - case GDK_ENTER_NOTIFY: { if (!desktop->isWaitingCursor() && !this->dragging) { - GdkWindow* window = gtk_widget_get_window (GTK_WIDGET (desktop->getCanvas()->gobj())); + GdkWindow *window = gtk_widget_get_window(GTK_WIDGET(desktop->getCanvas()->gobj())); gdk_window_set_cursor(window, CursorSelectMouseover); } @@ -357,18 +343,18 @@ bool SelectTool::item_handler(SPItem* item, GdkEvent* event) { break; case GDK_KEY_PRESS: - if (get_latin_keyval (&event->key) == GDK_KEY_space) { + if (get_latin_keyval(&event->key) == GDK_KEY_space) { if (this->dragging && this->grabbed) { /* stamping mode: show content mode moving */ _seltrans->stamp(); ret = TRUE; } - } else if (get_latin_keyval (&event->key) == GDK_KEY_Tab) { + } else if (get_latin_keyval(&event->key) == GDK_KEY_Tab) { if (this->dragging && this->grabbed) { _seltrans->getNextClosestPoint(false); ret = TRUE; } - } else if (get_latin_keyval (&event->key) == GDK_KEY_ISO_Left_Tab) { + } else if (get_latin_keyval(&event->key) == GDK_KEY_ISO_Left_Tab) { if (this->dragging && this->grabbed) { _seltrans->getNextClosestPoint(true); ret = TRUE; @@ -387,47 +373,48 @@ bool SelectTool::item_handler(SPItem* item, GdkEvent* event) { return ret; } -void SelectTool::sp_select_context_cycle_through_items(Inkscape::Selection *selection, GdkEventScroll *scroll_event, bool shift_pressed) { - if ( this->cycling_items.empty() ) +void SelectTool::sp_select_context_cycle_through_items(Inkscape::Selection *selection, GdkEventScroll *scroll_event, + bool shift_pressed) +{ + if (this->cycling_items.empty()) return; Inkscape::DrawingItem *arenaitem; - if(cycling_cur_item) { + if (cycling_cur_item) { arenaitem = cycling_cur_item->get_arenaitem(desktop->dkey); arenaitem->setOpacity(0.3); } // Find next item and activate it - std::vector<SPItem *>::iterator next = cycling_items.end(); if ((scroll_event->direction == GDK_SCROLL_UP) || (scroll_event->direction == GDK_SCROLL_SMOOTH && scroll_event->delta_y < 0)) { - if (! cycling_cur_item) { + if (!cycling_cur_item) { next = cycling_items.begin(); } else { - next = std::find( cycling_items.begin(), cycling_items.end(), cycling_cur_item ); - g_assert (next != cycling_items.end()); + next = std::find(cycling_items.begin(), cycling_items.end(), cycling_cur_item); + g_assert(next != cycling_items.end()); next++; if (next == cycling_items.end()) { - if ( cycling_wrap ) { + if (cycling_wrap) { next = cycling_items.begin(); } else { next--; } } } - } else { - if (! cycling_cur_item) { + } else { + if (!cycling_cur_item) { next = cycling_items.end(); next--; } else { - next = std::find( cycling_items.begin(), cycling_items.end(), cycling_cur_item ); - g_assert (next != cycling_items.end()); - if (next == cycling_items.begin()){ - if ( cycling_wrap ) { + next = std::find(cycling_items.begin(), cycling_items.end(), cycling_cur_item); + g_assert(next != cycling_items.end()); + if (next == cycling_items.begin()) { + if (cycling_wrap) { next = cycling_items.end(); next--; } @@ -451,7 +438,8 @@ void SelectTool::sp_select_context_cycle_through_items(Inkscape::Selection *sele } } -void SelectTool::sp_select_context_reset_opacities() { +void SelectTool::sp_select_context_reset_opacities() +{ for (auto item : this->cycling_items_cmp) { if (item) { Inkscape::DrawingItem *arenaitem = item->get_arenaitem(desktop->dkey); @@ -465,7 +453,8 @@ void SelectTool::sp_select_context_reset_opacities() { this->cycling_cur_item = nullptr; } -bool SelectTool::root_handler(GdkEvent* event) { +bool SelectTool::root_handler(GdkEvent *event) +{ SPItem *item = nullptr; SPItem *item_at_point = nullptr, *group_at_point = nullptr, *item_in_group = nullptr; gint ret = FALSE; @@ -485,17 +474,17 @@ bool SelectTool::root_handler(GdkEvent* event) { if (!selection->isEmpty()) { SPItem *clicked_item = selection->items().front(); - if (dynamic_cast<SPGroup *>(clicked_item) && !dynamic_cast<SPBox3D *>(clicked_item)) { // enter group if it's not a 3D box + if (dynamic_cast<SPGroup *>(clicked_item) && + !dynamic_cast<SPBox3D *>(clicked_item)) { // enter group if it's not a 3D box desktop->setCurrentLayer(clicked_item); desktop->getSelection()->clear(); this->dragging = false; sp_event_context_discard_delayed_snap_event(this); - } 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); + tools_switch_by_item(desktop, clicked_item, p); } } else { sp_select_context_up_one_layer(desktop); @@ -508,8 +497,8 @@ bool SelectTool::root_handler(GdkEvent* event) { 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; + xp = (gint)event->button.x; + yp = (gint)event->button.y; within_tolerance = true; Geom::Point const button_pt(event->button.x, event->button.y); @@ -527,7 +516,8 @@ bool SelectTool::root_handler(GdkEvent* event) { } 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, + 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, nullptr, event->button.time); this->grabbed = SP_CANVAS_ITEM(desktop->acetate); @@ -546,16 +536,14 @@ bool SelectTool::root_handler(GdkEvent* event) { } break; - case GDK_MOTION_NOTIFY: - { + case GDK_MOTION_NOTIFY: { 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 ) ) { + 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 @@ -563,12 +551,14 @@ bool SelectTool::root_handler(GdkEvent* event) { // motion notify coordinates as given (no snapping back to origin) within_tolerance = false; - if ((this->button_press_state & GDK_CONTROL_MASK) || ((this->button_press_state & GDK_MOD1_MASK) && !(this->button_press_state & GDK_SHIFT_MASK) && !selection->isEmpty())) { + if ((this->button_press_state & GDK_CONTROL_MASK) || + ((this->button_press_state & GDK_MOD1_MASK) && !(this->button_press_state & GDK_SHIFT_MASK) && + !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 (desktop->getCanvas()->gobj())); + GdkWindow *window = gtk_widget_get_window(GTK_WIDGET(desktop->getCanvas()->gobj())); gdk_window_set_cursor(window, CursorSelectDragging); } @@ -591,7 +581,8 @@ bool SelectTool::root_handler(GdkEvent* event) { if (item_at_point || this->moved || this->button_press_state & GDK_MOD1_MASK) { // 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); + 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)); { @@ -604,15 +595,15 @@ bool SelectTool::root_handler(GdkEvent* event) { // 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 && item_at_point && group_at_point->isAncestorOf(item_at_point))) { group_at_point = nullptr; } - // if neither a group nor an item (possibly in a group) at point are selected, set selection to the item at point + // 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_state & GDK_MOD1_MASK)) { + (!group_at_point || !selection->includes(group_at_point)) && + !(this->button_press_state & GDK_MOD1_MASK)) { // select what is under cursor if (!_seltrans->isEmpty()) { _seltrans->resetState(); @@ -622,7 +613,8 @@ bool SelectTool::root_handler(GdkEvent* event) { 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 + } // 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; @@ -639,7 +631,6 @@ bool SelectTool::root_handler(GdkEvent* event) { } else { this->dragging = FALSE; sp_event_context_discard_delayed_snap_event(this); - } } else { @@ -647,9 +638,13 @@ bool SelectTool::root_handler(GdkEvent* event) { 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")); + 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")); + 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); @@ -663,7 +658,7 @@ bool SelectTool::root_handler(GdkEvent* event) { if ((event->button.button == 1) && (this->grabbed) && !this->space_panning) { if (this->dragging) { - GdkWindow* window; + GdkWindow *window; if (this->moved) { // item has been moved @@ -680,12 +675,13 @@ bool SelectTool::root_handler(GdkEvent* event) { _seltrans->resetState(); selection->toggle(this->item); } else { - SPObject* single = selection->single(); + SPObject *single = selection->single(); SPGroup *singleGroup = dynamic_cast<SPGroup *>(single); // without shift, increase state (i.e. toggle scale/rotation handles) if (selection->includes(this->item)) { _seltrans->increaseState(); - } else if (singleGroup && (singleGroup->layerMode() == SPGroup::LAYER) && single->isAncestorOf(this->item)) { + } else if (singleGroup && (singleGroup->layerMode() == SPGroup::LAYER) && + single->isAncestorOf(this->item)) { _seltrans->increaseState(); } else { _seltrans->resetState(); @@ -699,13 +695,13 @@ bool SelectTool::root_handler(GdkEvent* event) { } this->dragging = FALSE; - window = gtk_widget_get_window (GTK_WIDGET (desktop->getCanvas()->gobj())); + window = gtk_widget_get_window(GTK_WIDGET(desktop->getCanvas()->gobj())); gdk_window_set_cursor(window, CursorSelectMouseover); sp_event_context_discard_delayed_snap_event(this); if (this->item) { - sp_object_unref( this->item, nullptr); + sp_object_unref(this->item, nullptr); } this->item = nullptr; @@ -714,7 +710,7 @@ bool SelectTool::root_handler(GdkEvent* event) { if (r->is_started() && !within_tolerance) { // this was a rubberband drag - std::vector<SPItem*> items; + std::vector<SPItem *> items; if (r->getMode() == RUBBERBAND_MODE_RECT) { Geom::OptRect const b = r->getRectangle(); @@ -729,10 +725,10 @@ bool SelectTool::root_handler(GdkEvent* event) { if (event->button.state & GDK_SHIFT_MASK) { // with shift, add to selection - selection->addList (items); + selection->addList(items); } else { // without shift, simply select anew - selection->setList (items); + selection->setList(items); } } else { // it was just a click, or a too small rubberband @@ -747,12 +743,14 @@ bool SelectTool::root_handler(GdkEvent* event) { if (ctrl_release) { // 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); + item = + sp_event_context_find_item(desktop, Geom::Point(event->button.x, event->button.y), + event->button.state & GDK_MOD1_MASK, TRUE); } 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); + item = + sp_event_context_find_item(desktop, Geom::Point(event->button.x, event->button.y), + event->button.state & GDK_MOD1_MASK, FALSE); } if (item) { @@ -760,9 +758,10 @@ bool SelectTool::root_handler(GdkEvent* event) { item = nullptr; } - } else if ((ctrl_release || alt_release) && !rb_escaped && !drag_escaped) { // ctrl+click, alt+click - item = sp_event_context_find_item (desktop, - Geom::Point(event->button.x, event->button.y), alt_release, ctrl_release); + } else if ((ctrl_release || alt_release) && !rb_escaped && !drag_escaped) { // ctrl+click, + // alt+click + item = sp_event_context_find_item(desktop, Geom::Point(event->button.x, event->button.y), + alt_release, ctrl_release); if (item) { if (selection->includes(item)) { @@ -803,45 +802,46 @@ bool SelectTool::root_handler(GdkEvent* event) { break; case GDK_SCROLL: { + GdkEventScroll *scroll_event = (GdkEventScroll *)event; - GdkEventScroll *scroll_event = (GdkEventScroll*) event; - - if ( ! (scroll_event->state & GDK_MOD1_MASK)) // do nothing specific if alt was not pressed + if (!(scroll_event->state & GDK_MOD1_MASK)) // do nothing specific if alt was not pressed break; bool shift_pressed = scroll_event->state & GDK_SHIFT_MASK; is_cycling = true; /* Rebuild list of items underneath the mouse pointer */ - Geom::Point p = desktop->d2w(desktop->point()); + Geom::Point p = desktop->d2w(desktop->point()); SPItem *item = desktop->getItemAtPoint(p, true, nullptr); this->cycling_items.clear(); SPItem *tmp = nullptr; - while(item != nullptr) { + while (item != nullptr) { this->cycling_items.push_back(item); item = desktop->getItemAtPoint(p, true, item); - if (selection->includes(item)) tmp = item; + if (selection->includes(item)) + tmp = item; } /* Compare current item list with item list during previous scroll ... */ bool item_lists_differ = this->cycling_items != this->cycling_items_cmp; - if(item_lists_differ) { + if (item_lists_differ) { this->sp_select_context_reset_opacities(); - for (auto l : this->cycling_items_cmp) + for (auto l : this->cycling_items_cmp) selection->remove(l); // deselects the previous content of the cycling loop this->cycling_items_cmp = (this->cycling_items); // set opacities in new stack - for(auto item : this->cycling_items) { + for (auto item : this->cycling_items) { if (item) { Inkscape::DrawingItem *arenaitem = item->get_arenaitem(desktop->dkey); arenaitem->setOpacity(0.3); } } } - if(!cycling_cur_item) cycling_cur_item = tmp; + if (!cycling_cur_item) + cycling_cur_item = tmp; this->cycling_wrap = prefs->getBool("/options/selection/cycleWrap", true); @@ -850,7 +850,7 @@ bool SelectTool::root_handler(GdkEvent* event) { ret = TRUE; - GtkWindow *w =GTK_WINDOW(gtk_widget_get_toplevel( GTK_WIDGET(desktop->getCanvas()->gobj()) )); + GtkWindow *w = GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(desktop->getCanvas()->gobj()))); if (w) { gtk_window_present(w); desktop->getCanvas()->grab_focus(); @@ -859,150 +859,148 @@ bool SelectTool::root_handler(GdkEvent* event) { } case GDK_KEY_PRESS: // keybindings for select context + { { - { - guint keyval = get_latin_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)) { + guint keyval = get_latin_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 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 { - // 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")); - + 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 (desktop->getCanvas()->gobj())); + GdkWindow *window = gtk_widget_get_window(GTK_WIDGET(desktop->getCanvas()->gobj())); gdk_window_set_cursor(window, CursorSelectDragging); } //*/ break; - } + } } gdouble const nudge = prefs->getDoubleLimited("/options/nudgedistance/value", 2, 0, 1000, "px"); // in px int const snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12); auto const y_dir = desktop->yaxisdir(); - switch (get_latin_keyval (&event->key)) { + switch (get_latin_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_latin_keyval(&event->key), 0); // with any mask - + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events(get_latin_keyval(&event->key), 0); // with any mask + if (MOD__ALT(event)) { // alt if (MOD__SHIFT(event)) { - desktop->getSelection()->moveScreen(mul*-10, 0); // shift + desktop->getSelection()->moveScreen(mul * -10, 0); // shift } else { - desktop->getSelection()->moveScreen(mul*-1, 0); // no shift + desktop->getSelection()->moveScreen(mul * -1, 0); // no shift } } else { // no alt if (MOD__SHIFT(event)) { - desktop->getSelection()->move(mul*-10*nudge, 0); // shift + desktop->getSelection()->move(mul * -10 * nudge, 0); // shift } else { - desktop->getSelection()->move(mul*-nudge, 0); // no shift + desktop->getSelection()->move(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 + if (!MOD__CTRL(event)) { // not ctrl gint mul = 1 + gobble_key_events(get_latin_keyval(&event->key), 0); // with any mask mul *= -y_dir; - + if (MOD__ALT(event)) { // alt if (MOD__SHIFT(event)) { - desktop->getSelection()->moveScreen(0, mul*10); // shift + desktop->getSelection()->moveScreen(0, mul * 10); // shift } else { - desktop->getSelection()->moveScreen(0, mul*1); // no shift + desktop->getSelection()->moveScreen(0, mul * 1); // no shift } } else { // no alt if (MOD__SHIFT(event)) { - desktop->getSelection()->move(0, mul*10*nudge); // shift + desktop->getSelection()->move(0, mul * 10 * nudge); // shift } else { - desktop->getSelection()->move(0, mul*nudge); // no shift + desktop->getSelection()->move(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 + if (!MOD__CTRL(event)) { // not ctrl gint mul = 1 + gobble_key_events(get_latin_keyval(&event->key), 0); // with any mask - + if (MOD__ALT(event)) { // alt if (MOD__SHIFT(event)) { - desktop->getSelection()->moveScreen(mul*10, 0); // shift + desktop->getSelection()->moveScreen(mul * 10, 0); // shift } else { - desktop->getSelection()->moveScreen(mul*1, 0); // no shift + desktop->getSelection()->moveScreen(mul * 1, 0); // no shift } } else { // no alt if (MOD__SHIFT(event)) { - desktop->getSelection()->move(mul*10*nudge, 0); // shift + desktop->getSelection()->move(mul * 10 * nudge, 0); // shift } else { - desktop->getSelection()->move(mul*nudge, 0); // no shift + desktop->getSelection()->move(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 + if (!MOD__CTRL(event)) { // not ctrl gint mul = 1 + gobble_key_events(get_latin_keyval(&event->key), 0); // with any mask mul *= -y_dir; - + if (MOD__ALT(event)) { // alt if (MOD__SHIFT(event)) { - desktop->getSelection()->moveScreen(0, mul*-10); // shift + desktop->getSelection()->moveScreen(0, mul * -10); // shift } else { - desktop->getSelection()->moveScreen(0, mul*-1); // no shift + desktop->getSelection()->moveScreen(0, mul * -1); // no shift } } else { // no alt if (MOD__SHIFT(event)) { - desktop->getSelection()->move(0, mul*-10*nudge); // shift + desktop->getSelection()->move(0, mul * -10 * nudge); // shift } else { - desktop->getSelection()->move(0, mul*-nudge); // no shift + desktop->getSelection()->move(0, mul * -nudge); // no shift } } - + ret = TRUE; } break; - + case GDK_KEY_Escape: if (!this->sp_select_context_abort()) { selection->clear(); } - + ret = TRUE; break; @@ -1013,7 +1011,7 @@ bool SelectTool::root_handler(GdkEvent* event) { ret = TRUE; } break; - + case GDK_KEY_space: /* stamping mode: show outline mode moving */ /* FIXME: Is next condition ok? (lauris) */ @@ -1022,15 +1020,15 @@ bool SelectTool::root_handler(GdkEvent* event) { ret = TRUE; } break; - + case GDK_KEY_x: case GDK_KEY_X: if (MOD__ALT_ONLY(event)) { - desktop->setToolboxFocusTo ("select-x"); + desktop->setToolboxFocusTo("select-x"); ret = TRUE; } break; - + case GDK_KEY_bracketleft: if (MOD__ALT(event)) { gint mul = 1 + gobble_key_events(get_latin_keyval(&event->key), 0); // with any mask @@ -1038,12 +1036,12 @@ bool SelectTool::root_handler(GdkEvent* event) { } else if (MOD__CTRL(event)) { selection->rotate(-90 * y_dir); } else if (snaps) { - selection->rotate(-180.0/snaps * y_dir); + selection->rotate(-180.0 / snaps * y_dir); } - + ret = TRUE; break; - + case GDK_KEY_bracketright: if (MOD__ALT(event)) { gint mul = 1 + gobble_key_events(get_latin_keyval(&event->key), 0); // with any mask @@ -1051,9 +1049,9 @@ bool SelectTool::root_handler(GdkEvent* event) { } else if (MOD__CTRL(event)) { selection->rotate(90 * y_dir); } else if (snaps) { - selection->rotate(180.0/snaps * y_dir); + selection->rotate(180.0 / snaps * y_dir); } - + ret = TRUE; break; @@ -1062,36 +1060,38 @@ bool SelectTool::root_handler(GdkEvent* event) { if (selection->singleItem()) { SPItem *clicked_item = selection->singleItem(); SPGroup *clickedGroup = dynamic_cast<SPGroup *>(clicked_item); - if ( (clickedGroup && (clickedGroup->layerMode() != SPGroup::LAYER)) || dynamic_cast<SPBox3D *>(clicked_item)) { // enter group or a 3D box + if ((clickedGroup && (clickedGroup->layerMode() != SPGroup::LAYER)) || + dynamic_cast<SPBox3D *>(clicked_item)) { // enter group or a 3D box desktop->setCurrentLayer(clicked_item); desktop->getSelection()->clear(); } else { - this->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Selected object is not a group. Cannot enter.")); + 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)) { @@ -1099,23 +1099,20 @@ bool SelectTool::root_handler(GdkEvent* event) { ret = true; } break; - + default: break; } break; - } + } case GDK_KEY_RELEASE: { guint keyval = get_latin_keyval(&event->key); - if (key_is_a_modifier (keyval)) { + 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)); + + 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: @@ -1135,8 +1132,8 @@ bool SelectTool::root_handler(GdkEvent* event) { // 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 (desktop->getCanvas())); - //gdk_window_set_cursor(window, event_context->cursor); + // GdkWindow* window = gtk_widget_get_window (GTK_WIDGET (desktop->getCanvas())); + // gdk_window_set_cursor(window, event_context->cursor); } break; } @@ -1151,9 +1148,9 @@ bool SelectTool::root_handler(GdkEvent* event) { return ret; } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/select-tool.h b/src/ui/tools/select-tool.h index fce2bfe919b7e817b807c01e3d0ce245b983b334..d49e63d52dd5281d6614a989f50ea6f73982aa9c 100644 --- a/src/ui/tools/select-tool.h +++ b/src/ui/tools/select-tool.h @@ -15,56 +15,59 @@ #include "ui/tools/tool-base.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) +#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 SelTrans; - class SelectionDescriber; -} +class SelTrans; +class SelectionDescriber; +} // namespace Inkscape namespace Inkscape { namespace UI { namespace Tools { -class SelectTool : public ToolBase { +class SelectTool : public ToolBase +{ public: - SelectTool(); - ~SelectTool() override; + SelectTool(); + ~SelectTool() override; - bool dragging; - bool moved; - guint button_press_state; + bool dragging; + bool moved; + guint button_press_state; - std::vector<SPItem *> cycling_items; - std::vector<SPItem *> cycling_items_cmp; - SPItem *cycling_cur_item; - bool cycling_wrap; + std::vector<SPItem *> cycling_items; + std::vector<SPItem *> cycling_items_cmp; + SPItem *cycling_cur_item; + bool cycling_wrap; - SPItem *item; - SPCanvasItem *grabbed; - Inkscape::SelTrans *_seltrans; - Inkscape::SelectionDescriber *_describer; + SPItem *item; + SPCanvasItem *grabbed; + Inkscape::SelTrans *_seltrans; + Inkscape::SelectionDescriber *_describer; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - void set(const Inkscape::Preferences::Entry& val) override; - bool root_handler(GdkEvent* event) override; - bool item_handler(SPItem* item, GdkEvent* event) override; + void setup() override; + void set(const Inkscape::Preferences::Entry &val) override; + bool root_handler(GdkEvent *event) override; + bool item_handler(SPItem *item, GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; 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(); + 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(); }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/tools/spiral-tool.cpp b/src/ui/tools/spiral-tool.cpp index 326191090b89fa0fa6b9cbec77b1be35df8760c2..108c1675b50ebf71c0f07cba6766b71da455a70e 100644 --- a/src/ui/tools/spiral-tool.cpp +++ b/src/ui/tools/spiral-tool.cpp @@ -15,32 +15,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> -#include <string> +#include "ui/tools/spiral-tool.h" +#include <cstring> #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> +#include <string> #include "context-fns.h" #include "desktop-style.h" #include "desktop.h" +#include "display/sp-canvas-item.h" #include "document-undo.h" #include "document.h" -#include "message-context.h" -#include "selection.h" -#include "verbs.h" - -#include "display/sp-canvas-item.h" - #include "include/macros.h" - +#include "message-context.h" #include "object/sp-namedview.h" #include "object/sp-spiral.h" - +#include "selection.h" #include "ui/pixmaps/cursor-spiral.xpm" #include "ui/shape-editor.h" -#include "ui/tools/spiral-tool.h" - +#include "verbs.h" #include "xml/node-event-vector.h" using Inkscape::DocumentUndo; @@ -49,8 +44,9 @@ namespace Inkscape { namespace UI { namespace Tools { -const std::string& SpiralTool::getPrefsPath() { - return SpiralTool::prefsPath; +const std::string &SpiralTool::getPrefsPath() +{ + return SpiralTool::prefsPath; } const std::string SpiralTool::prefsPath = "/tools/shapes/spiral"; @@ -61,10 +57,10 @@ SpiralTool::SpiralTool() , revo(3) , exp(1) , t0(0) -{ -} +{} -void SpiralTool::finish() { +void SpiralTool::finish() +{ SPDesktop *desktop = this->desktop; sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); @@ -75,7 +71,8 @@ void SpiralTool::finish() { ToolBase::finish(); } -SpiralTool::~SpiralTool() { +SpiralTool::~SpiralTool() +{ this->enableGrDrag(false); this->sel_changed_connection.disconnect(); @@ -85,7 +82,7 @@ SpiralTool::~SpiralTool() { /* fixme: This is necessary because we do not grab */ if (this->spiral) { - this->finishItem(); + this->finishItem(); } } @@ -93,12 +90,14 @@ SpiralTool::~SpiralTool() { * Callback that processes the "changed" signal on the selection; * destroys old and creates new knotholder. */ -void SpiralTool::selection_changed(Inkscape::Selection *selection) { +void SpiralTool::selection_changed(Inkscape::Selection *selection) +{ this->shape_editor->unset_item(); this->shape_editor->set_item(selection->singleItem()); } -void SpiralTool::setup() { +void SpiralTool::setup() +{ ToolBase::setup(); sp_event_context_read(this, "expansion"); @@ -128,7 +127,8 @@ void SpiralTool::setup() { } } -void SpiralTool::set(const Inkscape::Preferences::Entry& val) { +void SpiralTool::set(const Inkscape::Preferences::Entry &val) +{ Glib::ustring name = val.getEntryName(); if (name == "expansion") { @@ -140,7 +140,8 @@ void SpiralTool::set(const Inkscape::Preferences::Entry& val) { } } -bool SpiralTool::root_handler(GdkEvent* event) { +bool SpiralTool::root_handler(GdkEvent *event) +{ static gboolean dragging; SPDesktop *desktop = this->desktop; @@ -164,11 +165,8 @@ bool SpiralTool::root_handler(GdkEvent* event) { 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 ), + (GDK_KEY_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | + GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK), nullptr, event->button.time); ret = TRUE; } @@ -176,9 +174,8 @@ bool SpiralTool::root_handler(GdkEvent* event) { 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 ) ) { + 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 @@ -243,31 +240,29 @@ bool SpiralTool::root_handler(GdkEvent* event) { 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_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"), - nullptr, - _("<b>Alt</b>: lock spiral radius")); + sp_event_show_modifier_tip(this->defaultMessageContext(), event, _("<b>Ctrl</b>: snap angle"), + nullptr, _("<b>Alt</b>: lock spiral radius")); break; case GDK_KEY_x: case GDK_KEY_X: if (MOD__ALT_ONLY(event)) { - desktop->setToolboxFocusTo ("spiral-revolutions"); + desktop->setToolboxFocusTo("spiral-revolutions"); 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; + 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) { @@ -302,7 +297,7 @@ bool SpiralTool::root_handler(GdkEvent* event) { 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_L: // Meta is when you press Shift+Alt case GDK_KEY_Meta_R: this->defaultMessageContext()->clear(); break; @@ -317,14 +312,14 @@ bool SpiralTool::root_handler(GdkEvent* event) { } if (!ret) { - ret = ToolBase::root_handler(event); + ret = ToolBase::root_handler(event); } return ret; } -void SpiralTool::drag(Geom::Point const &p, guint state) { - +void SpiralTool::drag(Geom::Point const &p, guint state) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int const snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12); @@ -361,37 +356,38 @@ void SpiralTool::drag(Geom::Point const &p, guint state) { gdouble const rad = Geom::L2(delta); // Start angle calculated from end angle and number of revolutions. - gdouble arg = Geom::atan2(delta) - 2.0*M_PI * spiral->revo; + gdouble arg = Geom::atan2(delta) - 2.0 * M_PI * spiral->revo; if (state & GDK_CONTROL_MASK) { /* Snap start angle */ - double snaps_radian = M_PI/snaps; - arg = std::round(arg/snaps_radian) * snaps_radian; + double snaps_radian = M_PI / snaps; + arg = std::round(arg / snaps_radian) * snaps_radian; } /* 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); + /*expansion*/ this->exp, + /*revolution*/ this->revo, rad, arg, + /*t0*/ this->t0); /* status text */ Inkscape::Util::Quantity q = Inkscape::Util::Quantity(rad, "px"); Glib::ustring rads = q.string(desktop->namedview->display_units); this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, - _("<b>Spiral</b>: radius %s, angle %.2f°; with <b>Ctrl</b> to snap angle"), - rads.c_str(), arg * 180/M_PI + 360*spiral->revo); + _("<b>Spiral</b>: radius %s, angle %.2f°; with <b>Ctrl</b> to snap angle"), + rads.c_str(), arg * 180 / M_PI + 360 * spiral->revo); } -void SpiralTool::finishItem() { +void SpiralTool::finishItem() +{ this->message_context->clear(); if (this->spiral != nullptr) { - 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; - } + 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); @@ -400,20 +396,21 @@ void SpiralTool::finishItem() { forced_redraws_stop(); this->desktop->getSelection()->set(this->spiral); - + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_SPIRAL, _("Create spiral")); this->spiral = nullptr; } } -void SpiralTool::cancel() { - this->desktop->getSelection()->clear(); - sp_canvas_item_ungrab(SP_CANVAS_ITEM(this->desktop->acetate)); +void SpiralTool::cancel() +{ + this->desktop->getSelection()->clear(); + sp_canvas_item_ungrab(SP_CANVAS_ITEM(this->desktop->acetate)); if (this->spiral != nullptr) { - this->spiral->deleteObject(); - this->spiral = nullptr; + this->spiral->deleteObject(); + this->spiral = nullptr; } this->within_tolerance = false; @@ -426,9 +423,9 @@ void SpiralTool::cancel() { DocumentUndo::cancel(this->desktop->getDocument()); } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/spiral-tool.h b/src/ui/tools/spiral-tool.h index fda9d57e2e3d7a9dd0825fefdca1759df6c737dc..1786262f3427f29555184f581633d9a905563223 100644 --- a/src/ui/tools/spiral-tool.h +++ b/src/ui/tools/spiral-tool.h @@ -16,12 +16,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <sigc++/connection.h> #include <2geom/point.h> +#include <sigc++/connection.h> + #include "ui/tools/tool-base.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) +#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) class SPSpiral; @@ -32,37 +34,38 @@ class Selection; namespace UI { namespace Tools { -class SpiralTool : public ToolBase { +class SpiralTool : public ToolBase +{ public: - SpiralTool(); - ~SpiralTool() override; + SpiralTool(); + ~SpiralTool() override; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - void finish() override; - void set(const Inkscape::Preferences::Entry& val) override; - bool root_handler(GdkEvent* event) override; + void setup() override; + void finish() override; + void set(const Inkscape::Preferences::Entry &val) override; + bool root_handler(GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; private: - SPSpiral * spiral; - Geom::Point center; - gdouble revo; - gdouble exp; - gdouble t0; + 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); + void drag(Geom::Point const &p, guint state); + void finishItem(); + void cancel(); + void selection_changed(Inkscape::Selection *selection); }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/tools/spray-tool.cpp b/src/ui/tools/spray-tool.cpp index cd583db460c74a7a586f165781033d4df2b7cea8..9cecd3fb617dd5205350483c67c9e6a80966a4b3 100644 --- a/src/ui/tools/spray-tool.cpp +++ b/src/ui/tools/spray-tool.cpp @@ -21,57 +21,48 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <numeric> -#include <vector> +#include "ui/tools/spray-tool.h" +#include <2geom/circle.h> #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> - -#include <2geom/circle.h> - +#include <numeric> +#include <vector> #include "context-fns.h" #include "desktop-events.h" #include "desktop-style.h" #include "desktop.h" -#include "document-undo.h" -#include "document.h" -#include "filter-chemistry.h" -#include "inkscape.h" -#include "include/macros.h" -#include "message-context.h" -#include "path-chemistry.h" -#include "selection.h" -#include "verbs.h" - #include "display/cairo-utils.h" #include "display/canvas-arena.h" #include "display/canvas-bpath.h" #include "display/curve.h" #include "display/drawing-context.h" #include "display/drawing.h" - +#include "document-undo.h" +#include "document.h" +#include "filter-chemistry.h" #include "helper/action.h" - +#include "include/macros.h" +#include "inkscape.h" +#include "message-context.h" #include "object/box3d.h" #include "object/sp-item-transform.h" - -#include "ui/pixmaps/cursor-spray.xpm" - -#include "svg/svg.h" +#include "path-chemistry.h" +#include "selection.h" #include "svg/svg-color.h" - -#include "ui/toolbar/spray-toolbar.h" -#include "ui/tools/spray-tool.h" +#include "svg/svg.h" #include "ui/dialog/dialog-manager.h" - +#include "ui/pixmaps/cursor-spray.xpm" +#include "ui/toolbar/spray-toolbar.h" +#include "verbs.h" using Inkscape::DocumentUndo; #define DDC_RED_RGBA 0xff0000ff #define DYNA_MIN_WIDTH 1.0e-6 -// Disabled in 0.91 because of Bug #1274831 (crash, spraying an object +// 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 @@ -80,7 +71,8 @@ namespace Inkscape { namespace UI { namespace Tools { -enum { +enum +{ PICK_COLOR, PICK_OPACITY, PICK_R, @@ -91,7 +83,8 @@ enum { PICK_L }; -const std::string& SprayTool::getPrefsPath() { +const std::string &SprayTool::getPrefsPath() +{ return SprayTool::prefsPath; } @@ -104,12 +97,12 @@ const std::string SprayTool::prefsPath = "/tools/spray"; */ 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) ); + // 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) +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; @@ -125,7 +118,7 @@ static void sp_spray_rotate_rel(Geom::Point c, SPDesktop */*desktop*/, SPItem *i } /* Method to scale items */ -static void sp_spray_scale_rel(Geom::Point c, SPDesktop */*desktop*/, SPItem *item, Geom::Scale const &scale) +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); @@ -175,10 +168,10 @@ SprayTool::SprayTool() , invert_picked(false) , gamma_picked(0) , rand_picked(0) -{ -} +{} -SprayTool::~SprayTool() { +SprayTool::~SprayTool() +{ object_set.clear(); this->enableGrDrag(false); this->style_set_connection.disconnect(); @@ -189,26 +182,34 @@ SprayTool::~SprayTool() { } } -void SprayTool::update_cursor(bool /*with_shift*/) { +void SprayTool::update_cursor(bool /*with_shift*/) +{ guint num = 0; gchar *sel_message = nullptr; if (!desktop->selection->isEmpty()) { - num = (guint) boost::distance(desktop->selection->items()); - sel_message = g_strdup_printf(ngettext("<b>%i</b> object selected","<b>%i</b> objects selected",num), num); + num = (guint)boost::distance(desktop->selection->items()); + 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); + 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); + 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); + 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; @@ -218,18 +219,21 @@ void SprayTool::update_cursor(bool /*with_shift*/) { g_free(sel_message); } -void SprayTool::setup() { +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::Path(Geom::Circle(0,0,1)); + /* 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::Path(Geom::Circle(0, 0, 1)); auto c = std::make_unique<SPCurve>(path); dilate_area = sp_canvas_bpath_new(desktop->getControls(), c.get()); - 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_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); } @@ -270,7 +274,8 @@ void SprayTool::setup() { sp_event_context_read(this, "no_overlap"); } -void SprayTool::setCloneTilerPrefs() { +void SprayTool::setCloneTilerPrefs() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); this->do_trace = prefs->getBool("/dialogs/clonetiler/dotrace", false); this->pick = prefs->getInt("/dialogs/clonetiler/pick"); @@ -283,7 +288,8 @@ void SprayTool::setCloneTilerPrefs() { this->gamma_picked = prefs->getDoubleLimited("/dialogs/clonetiler/gamma_picked", 0, -10, 10); } -void SprayTool::set(const Inkscape::Preferences::Entry& val) { +void SprayTool::set(const Inkscape::Preferences::Entry &val) +{ Glib::ustring path = val.getEntryName(); if (path == "mode") { @@ -307,7 +313,7 @@ void SprayTool::set(const Inkscape::Preferences::Entry& val) { 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 + // Not implemented in the toolbar and preferences yet } else if (path == "distribution") { this->distrib = val.getInt(1); } else if (path == "tilt") { @@ -317,23 +323,23 @@ void SprayTool::set(const Inkscape::Preferences::Entry& val) { } else if (path == "offset") { this->offset = val.getDoubleLimited(100.0, 0, 1000.0); } else if (path == "pick_center") { - this->pick_center = val.getBool(true); + this->pick_center = val.getBool(true); } else if (path == "pick_inverse_value") { - this->pick_inverse_value = val.getBool(false); + this->pick_inverse_value = val.getBool(false); } else if (path == "pick_fill") { - this->pick_fill = val.getBool(false); + this->pick_fill = val.getBool(false); } else if (path == "pick_stroke") { - this->pick_stroke = val.getBool(false); + this->pick_stroke = val.getBool(false); } else if (path == "pick_no_overlap") { - this->pick_no_overlap = val.getBool(false); + this->pick_no_overlap = val.getBool(false); } else if (path == "over_no_transparent") { - this->over_no_transparent = val.getBool(true); + this->over_no_transparent = val.getBool(true); } else if (path == "over_transparent") { - this->over_transparent = val.getBool(true); + this->over_transparent = val.getBool(true); } else if (path == "no_overlap") { this->no_overlap = val.getBool(false); } else if (path == "picker") { - this->picker = val.getBool(false); + this->picker = val.getBool(false); } } @@ -348,13 +354,13 @@ static void sp_spray_extinput(SprayTool *tc, GdkEvent *event) static double get_width(SprayTool *tc) { - double pressure = (tc->usepressurewidth? tc->pressure / TC_DEFAULT_PRESSURE : 1); + double pressure = (tc->usepressurewidth ? tc->pressure / TC_DEFAULT_PRESSURE : 1); return pressure * tc->width; } static double get_dilate_radius(SprayTool *tc) { - return 250 * get_width(tc)/tc->getDesktop()->current_zoom(); + return 250 * get_width(tc) / tc->getDesktop()->current_zoom(); } static double get_path_mean(SprayTool *tc) @@ -369,7 +375,7 @@ static double get_path_standard_deviation(SprayTool *tc) static double get_population(SprayTool *tc) { - double pressure = (tc->usepressurepopulation? tc->pressure / TC_DEFAULT_PRESSURE : 1); + double pressure = (tc->usepressurepopulation ? tc->pressure / TC_DEFAULT_PRESSURE : 1); return pressure * tc->population; } @@ -395,29 +401,28 @@ static double get_move_standard_deviation(SprayTool *tc) * @param[out] angle : angle of the position of the sprayed object * @param[in] a : mean * @param[in] s : standard deviation - * @param[in] choice : + * @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); + 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 ))) - { + 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 + // 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 void sp_spray_transform_path(SPItem * item, Geom::Path &path, Geom::Affine affine, Geom::Point center){ +static void sp_spray_transform_path(SPItem *item, Geom::Path &path, Geom::Affine affine, Geom::Point center) +{ path *= i2anc_affine(static_cast<SPItem *>(item->parent), nullptr).inverse(); path *= item->transform.inverse(); Geom::Affine dt2p; @@ -437,11 +442,11 @@ probability of being displaced. */ double randomize01(double val, double rand) { - double base = MIN (val - rand, 1 - 2*rand); + double base = MIN(val - rand, 1 - 2 * rand); if (base < 0) { base = 0; } - val = base + g_random_double_range (0, MIN (2 * rand, 1 - base)); + val = base + g_random_double_range(0, MIN(2 * rand, 1 - base)); return CLAMP(val, 0, 1); // this should be unnecessary with the above provisions, but just in case... } @@ -452,8 +457,8 @@ static guint32 getPickerData(Geom::IntRect area, SPDesktop *desktop) sp_canvas_arena_render_surface(SP_CANVAS_ARENA(desktop->getDrawing()), s, area); ink_cairo_surface_average_color(s, R, G, B, A); cairo_surface_destroy(s); - //this can fix the bug #1511998 if confirmed - if( A == 0 || A < 1e-6){ + // this can fix the bug #1511998 if confirmed + if (A == 0 || A < 1e-6) { R = 1; G = 1; B = 1; @@ -461,59 +466,38 @@ static guint32 getPickerData(Geom::IntRect area, SPDesktop *desktop) return SP_RGBA32_F_COMPOSE(R, G, B, A); } -static void showHidden(std::vector<SPItem *> items_down){ +static void showHidden(std::vector<SPItem *> items_down) +{ for (auto item_hidden : items_down) { item_hidden->setHidden(false); item_hidden->updateRepr(); } } -//todo: maybe move same parameter to preferences -static bool fit_item(SPDesktop *desktop, - SPItem *item, - Geom::OptRect bbox, - Geom::Point &move, - Geom::Point center, - gint mode, - double angle, - double &_scale, - double scale, - bool picker, - bool pick_center, - bool pick_inverse_value, - bool pick_fill, - bool pick_stroke, - bool pick_no_overlap, - bool over_no_transparent, - bool over_transparent, - bool no_overlap, - double offset, - SPCSSAttr *css, - bool trace_scale, - int pick, - bool do_trace, - bool pick_to_size, - bool pick_to_presence, - bool pick_to_color, - bool pick_to_opacity, - bool invert_picked, - double gamma_picked , +// todo: maybe move same parameter to preferences +static bool fit_item(SPDesktop *desktop, SPItem *item, Geom::OptRect bbox, Geom::Point &move, Geom::Point center, + gint mode, double angle, double &_scale, double scale, bool picker, bool pick_center, + bool pick_inverse_value, bool pick_fill, bool pick_stroke, bool pick_no_overlap, + bool over_no_transparent, bool over_transparent, bool no_overlap, double offset, SPCSSAttr *css, + bool trace_scale, int pick, bool do_trace, bool pick_to_size, bool pick_to_presence, + bool pick_to_color, bool pick_to_opacity, bool invert_picked, double gamma_picked, double rand_picked) { SPDocument *doc = item->document; double width = bbox->width(); double height = bbox->height(); - double offset_width = (offset * width)/100.0 - (width); - if(offset_width < 0 ){ + double offset_width = (offset * width) / 100.0 - (width); + if (offset_width < 0) { offset_width = 0; } - double offset_height = (offset * height)/100.0 - (height); - if(offset_height < 0 ){ + double offset_height = (offset * height) / 100.0 - (height); + if (offset_height < 0) { offset_height = 0; } - if(picker && pick_to_size && !trace_scale && do_trace){ + if (picker && pick_to_size && !trace_scale && do_trace) { _scale = 0.1; } - Geom::OptRect bbox_procesed = Geom::Rect(Geom::Point(bbox->left() - offset_width, bbox->top() - offset_height),Geom::Point(bbox->right() + offset_width, bbox->bottom() + offset_height)); + Geom::OptRect bbox_procesed = Geom::Rect(Geom::Point(bbox->left() - offset_width, bbox->top() - offset_height), + Geom::Point(bbox->right() + offset_width, bbox->bottom() + offset_height)); Geom::Path path; path.start(Geom::Point(bbox_procesed->left(), bbox_procesed->top())); path.appendNew<Geom::LineSegment>(Geom::Point(bbox_procesed->right(), bbox_procesed->top())); @@ -535,179 +519,181 @@ static bool fit_item(SPDesktop *desktop, Geom::IntRect area = Geom::IntRect::from_xywh(floor(mid_point[Geom::X]), floor(mid_point[Geom::Y]), 1, 1); guint32 rgba = getPickerData(area, desktop); guint32 rgba2 = 0xffffff00; - Geom::Rect rect_sprayed(desktop->d2w(Geom::Point(bbox_left_main,bbox_top_main)), desktop->d2w(Geom::Point(bbox_right_main,bbox_bottom_main))); + Geom::Rect rect_sprayed(desktop->d2w(Geom::Point(bbox_left_main, bbox_top_main)), + desktop->d2w(Geom::Point(bbox_right_main, bbox_bottom_main))); if (!rect_sprayed.hasZeroArea()) { rgba2 = getPickerData(rect_sprayed.roundOutwards(), desktop); } - if(pick_no_overlap) { - if(rgba != rgba2) { - if(mode != SPRAY_MODE_ERASER) { + if (pick_no_overlap) { + if (rgba != rgba2) { + if (mode != SPRAY_MODE_ERASER) { return false; } } } - if(!pick_center) { + if (!pick_center) { rgba = rgba2; } - if(!over_transparent && (SP_RGBA32_A_F(rgba) == 0 || SP_RGBA32_A_F(rgba) < 1e-6)) { - if(mode != SPRAY_MODE_ERASER) { + if (!over_transparent && (SP_RGBA32_A_F(rgba) == 0 || SP_RGBA32_A_F(rgba) < 1e-6)) { + if (mode != SPRAY_MODE_ERASER) { return false; } } - if(!over_no_transparent && SP_RGBA32_A_F(rgba) > 0) { - if(mode != SPRAY_MODE_ERASER) { + if (!over_no_transparent && SP_RGBA32_A_F(rgba) > 0) { + if (mode != SPRAY_MODE_ERASER) { return false; } } - if(offset < 100 ) { - offset_width = ((99.0 - offset) * width_transformed)/100.0 - width_transformed; - offset_height = ((99.0 - offset) * height_transformed)/100.0 - height_transformed; + if (offset < 100) { + offset_width = ((99.0 - offset) * width_transformed) / 100.0 - width_transformed; + offset_height = ((99.0 - offset) * height_transformed) / 100.0 - height_transformed; } else { offset_width = 0; offset_height = 0; } - std::vector<SPItem*> items_down = desktop->getDocument()->getItemsPartiallyInBox(desktop->dkey, *bbox_procesed); + std::vector<SPItem *> items_down = desktop->getDocument()->getItemsPartiallyInBox(desktop->dkey, *bbox_procesed); Inkscape::Selection *selection = desktop->getSelection(); if (selection->isEmpty()) { return false; } - std::vector<SPItem*> const items_selected(selection->items().begin(), selection->items().end()); - std::vector<SPItem*> items_down_erased; - for (std::vector<SPItem*>::const_iterator i=items_down.begin(); i!=items_down.end(); ++i) { + std::vector<SPItem *> const items_selected(selection->items().begin(), selection->items().end()); + std::vector<SPItem *> items_down_erased; + for (std::vector<SPItem *>::const_iterator i = items_down.begin(); i != items_down.end(); ++i) { SPItem *item_down = *i; Geom::OptRect bbox_down = item_down->documentVisualBounds(); double bbox_left = bbox_down->left(); double bbox_top = bbox_down->top(); - gchar const * item_down_sharp = g_strdup_printf("#%s", item_down->getId()); + gchar const *item_down_sharp = g_strdup_printf("#%s", item_down->getId()); items_down_erased.push_back(item_down); for (auto item_selected : items_selected) { - gchar const * spray_origin; - if(!item_selected->getAttribute("inkscape:spray-origin")){ + gchar const *spray_origin; + if (!item_selected->getAttribute("inkscape:spray-origin")) { spray_origin = g_strdup_printf("#%s", item_selected->getId()); } else { spray_origin = item_selected->getAttribute("inkscape:spray-origin"); } - if(strcmp(item_down_sharp, spray_origin) == 0 || - (item_down->getAttribute("inkscape:spray-origin") && - strcmp(item_down->getAttribute("inkscape:spray-origin"),spray_origin) == 0 )) - { - if(mode == SPRAY_MODE_ERASER) { - if(strcmp(item_down_sharp, spray_origin) != 0 && !selection->includes(item_down) ){ + if (strcmp(item_down_sharp, spray_origin) == 0 || + (item_down->getAttribute("inkscape:spray-origin") && + strcmp(item_down->getAttribute("inkscape:spray-origin"), spray_origin) == 0)) { + if (mode == SPRAY_MODE_ERASER) { + if (strcmp(item_down_sharp, spray_origin) != 0 && !selection->includes(item_down)) { item_down->deleteObject(); items_down_erased.pop_back(); break; } - } else if(no_overlap) { - if(!(offset_width < 0 && offset_height < 0 && std::abs(bbox_left - bbox_left_main) > std::abs(offset_width) && - std::abs(bbox_top - bbox_top_main) > std::abs(offset_height))){ - if(!no_overlap && (picker || over_transparent || over_no_transparent)){ + } else if (no_overlap) { + if (!(offset_width < 0 && offset_height < 0 && + std::abs(bbox_left - bbox_left_main) > std::abs(offset_width) && + std::abs(bbox_top - bbox_top_main) > std::abs(offset_height))) { + if (!no_overlap && (picker || over_transparent || over_no_transparent)) { showHidden(items_down); } return false; } - } else if(picker || over_transparent || over_no_transparent) { + } else if (picker || over_transparent || over_no_transparent) { item_down->setHidden(true); item_down->updateRepr(); } } } } - if(mode == SPRAY_MODE_ERASER){ - if(!no_overlap && (picker || over_transparent || over_no_transparent)){ + if (mode == SPRAY_MODE_ERASER) { + if (!no_overlap && (picker || over_transparent || over_no_transparent)) { showHidden(items_down_erased); } return false; } - if(picker || over_transparent || over_no_transparent){ - if(!no_overlap){ + if (picker || over_transparent || over_no_transparent) { + if (!no_overlap) { doc->ensureUpToDate(); rgba = getPickerData(area, desktop); if (!rect_sprayed.hasZeroArea()) { rgba2 = getPickerData(rect_sprayed.roundOutwards(), desktop); } } - if(pick_no_overlap){ - if(rgba != rgba2){ - if(!no_overlap && (picker || over_transparent || over_no_transparent)){ + if (pick_no_overlap) { + if (rgba != rgba2) { + if (!no_overlap && (picker || over_transparent || over_no_transparent)) { showHidden(items_down); } return false; } } - if(!pick_center){ + if (!pick_center) { rgba = rgba2; } double opacity = 1.0; - gchar color_string[32]; *color_string = 0; + gchar color_string[32]; + *color_string = 0; float r = SP_RGBA32_R_F(rgba); float g = SP_RGBA32_G_F(rgba); float b = SP_RGBA32_B_F(rgba); float a = SP_RGBA32_A_F(rgba); - if(!over_transparent && (a == 0 || a < 1e-6)){ - if(!no_overlap && (picker || over_transparent || over_no_transparent)){ + if (!over_transparent && (a == 0 || a < 1e-6)) { + if (!no_overlap && (picker || over_transparent || over_no_transparent)) { showHidden(items_down); } return false; } - if(!over_no_transparent && a > 0){ - if(!no_overlap && (picker || over_transparent || over_no_transparent)){ + if (!over_no_transparent && a > 0) { + if (!no_overlap && (picker || over_transparent || over_no_transparent)) { showHidden(items_down); } return false; } - if(picker && do_trace){ + if (picker && do_trace) { float hsl[3]; - SPColor::rgb_to_hsl_floatv (hsl, r, g, b); + SPColor::rgb_to_hsl_floatv(hsl, r, g, b); gdouble val = 0; switch (pick) { - case PICK_COLOR: - val = 1 - hsl[2]; // inverse lightness; to match other picks where black = max - break; - case PICK_OPACITY: - val = a; - break; - case PICK_R: - val = r; - break; - case PICK_G: - val = g; - break; - case PICK_B: - val = b; - break; - case PICK_H: - val = hsl[0]; - break; - case PICK_S: - val = hsl[1]; - break; - case PICK_L: - val = 1 - hsl[2]; - break; - default: - break; + case PICK_COLOR: + val = 1 - hsl[2]; // inverse lightness; to match other picks where black = max + break; + case PICK_OPACITY: + val = a; + break; + case PICK_R: + val = r; + break; + case PICK_G: + val = g; + break; + case PICK_B: + val = b; + break; + case PICK_H: + val = hsl[0]; + break; + case PICK_S: + val = hsl[1]; + break; + case PICK_L: + val = 1 - hsl[2]; + break; + default: + break; } if (rand_picked > 0) { - val = randomize01 (val, rand_picked); - r = randomize01 (r, rand_picked); - g = randomize01 (g, rand_picked); - b = randomize01 (b, rand_picked); + val = randomize01(val, rand_picked); + r = randomize01(r, rand_picked); + g = randomize01(g, rand_picked); + b = randomize01(b, rand_picked); } if (gamma_picked != 0) { double power; if (gamma_picked > 0) - power = 1/(1 + fabs(gamma_picked)); + power = 1 / (1 + fabs(gamma_picked)); else power = 1 + fabs(gamma_picked); - val = pow (val, power); - r = pow ((double)r, (double)power); - g = pow ((double)g, (double)power); - b = pow ((double)b, (double)power); + val = pow(val, power); + r = pow((double)r, (double)power); + g = pow((double)g, (double)power); + b = pow((double)b, (double)power); } if (invert_picked) { @@ -717,59 +703,32 @@ static bool fit_item(SPDesktop *desktop, b = 1 - b; } - val = CLAMP (val, 0, 1); - r = CLAMP (r, 0, 1); - g = CLAMP (g, 0, 1); - b = CLAMP (b, 0, 1); + val = CLAMP(val, 0, 1); + r = CLAMP(r, 0, 1); + g = CLAMP(g, 0, 1); + b = CLAMP(b, 0, 1); // recompose tweaked color rgba = SP_RGBA32_F_COMPOSE(r, g, b, a); if (pick_to_size) { - if(!trace_scale){ - if(pick_inverse_value) { + if (!trace_scale) { + if (pick_inverse_value) { _scale = 1.0 - val; } else { _scale = val; } - if(_scale == 0.0) { - if(!no_overlap && (picker || over_transparent || over_no_transparent)){ + if (_scale == 0.0) { + if (!no_overlap && (picker || over_transparent || over_no_transparent)) { showHidden(items_down); } return false; } - if(!fit_item(desktop - , item - , bbox - , move - , center - , mode - , angle - , _scale - , scale - , picker - , pick_center - , pick_inverse_value - , pick_fill - , pick_stroke - , pick_no_overlap - , over_no_transparent - , over_transparent - , no_overlap - , offset - , css - , true - , pick - , do_trace - , pick_to_size - , pick_to_presence - , pick_to_color - , pick_to_opacity - , invert_picked - , gamma_picked - , rand_picked) - ) - { - if(!no_overlap && (picker || over_transparent || over_no_transparent)){ + if (!fit_item(desktop, item, bbox, move, center, mode, angle, _scale, scale, picker, pick_center, + pick_inverse_value, pick_fill, pick_stroke, pick_no_overlap, over_no_transparent, + over_transparent, no_overlap, offset, css, true, pick, do_trace, pick_to_size, + pick_to_presence, pick_to_color, pick_to_opacity, invert_picked, gamma_picked, + rand_picked)) { + if (!no_overlap && (picker || over_transparent || over_no_transparent)) { showHidden(items_down); } return false; @@ -778,7 +737,7 @@ static bool fit_item(SPDesktop *desktop, } if (pick_to_opacity) { - if(pick_inverse_value) { + if (pick_inverse_value) { opacity *= 1.0 - val; } else { opacity *= val; @@ -789,30 +748,30 @@ static bool fit_item(SPDesktop *desktop, sp_repr_css_set_property(css, "opacity", opacity_str.str().c_str()); } if (pick_to_presence) { - if (g_random_double_range (0, 1) > val) { - //Hiding the element is a way to retain original - //behaviour of tiled clones for presence option. + if (g_random_double_range(0, 1) > val) { + // Hiding the element is a way to retain original + // behaviour of tiled clones for presence option. sp_repr_css_set_property(css, "opacity", "0"); } } if (pick_to_color) { sp_svg_write_color(color_string, sizeof(color_string), rgba); - if(pick_fill){ + if (pick_fill) { sp_repr_css_set_property(css, "fill", color_string); } - if(pick_stroke){ + if (pick_stroke) { sp_repr_css_set_property(css, "stroke", color_string); } } if (opacity < 1e-6) { // invisibly transparent, skip - if(!no_overlap && (picker || over_transparent || over_no_transparent)){ + if (!no_overlap && (picker || over_transparent || over_no_transparent)) { showHidden(items_down); } return false; } } - if(!do_trace){ - if(!pick_center){ + if (!do_trace) { + if (!pick_center) { rgba = rgba2; } if (pick_inverse_value) { @@ -826,58 +785,29 @@ static bool fit_item(SPDesktop *desktop, } rgba = SP_RGBA32_F_COMPOSE(r, g, b, a); sp_svg_write_color(color_string, sizeof(color_string), rgba); - if(pick_fill){ + if (pick_fill) { sp_repr_css_set_property(css, "fill", color_string); } - if(pick_stroke){ + if (pick_stroke) { sp_repr_css_set_property(css, "stroke", color_string); } } - if(!no_overlap && (picker || over_transparent || over_no_transparent)){ + if (!no_overlap && (picker || over_transparent || over_no_transparent)) { showHidden(items_down); } } return true; } -static bool sp_spray_recursive(SPDesktop *desktop, - Inkscape::ObjectSet *set, - SPItem *item, - Geom::Point p, - Geom::Point /*vector*/, - gint mode, - double radius, - double population, - double &scale, - double scale_variation, - bool /*reverse*/, - double mean, - double standard_deviation, - double ratio, - double tilt, - double rotation_variation, - gint _distrib, - bool no_overlap, - bool picker, - bool pick_center, - bool pick_inverse_value, - bool pick_fill, - bool pick_stroke, - bool pick_no_overlap, - bool over_no_transparent, - bool over_transparent, - double offset, - bool usepressurescale, - double pressure, - int pick, - bool do_trace, - bool pick_to_size, - bool pick_to_presence, - bool pick_to_color, - bool pick_to_opacity, - bool invert_picked, - double gamma_picked , - double rand_picked) +static bool sp_spray_recursive(SPDesktop *desktop, Inkscape::ObjectSet *set, SPItem *item, Geom::Point p, + Geom::Point /*vector*/, gint mode, double radius, double population, double &scale, + double scale_variation, bool /*reverse*/, double mean, double standard_deviation, + double ratio, double tilt, double rotation_variation, gint _distrib, bool no_overlap, + bool picker, bool pick_center, bool pick_inverse_value, bool pick_fill, bool pick_stroke, + bool pick_no_overlap, bool over_no_transparent, bool over_transparent, double offset, + bool usepressurescale, double pressure, int pick, bool do_trace, bool pick_to_size, + bool pick_to_presence, bool pick_to_color, bool pick_to_opacity, bool invert_picked, + double gamma_picked, double rand_picked) { bool did = false; @@ -891,83 +821,61 @@ static bool sp_spray_recursive(SPDesktop *desktop, } 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 ); - if(usepressurescale){ + 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); + if (usepressurescale) { _scale = pressure; } - double dr; double dp; - random_position( dr, dp, mean, standard_deviation, _distrib ); - dr=dr*radius; + double dr; + double dp; + random_position(dr, dp, mean, standard_deviation, _distrib); + dr = dr * radius; if (mode == SPRAY_MODE_COPY || mode == SPRAY_MODE_ERASER) { Geom::OptRect a = item->documentVisualBounds(); if (a) { - if(_fid <= population) - { + if (_fid <= population) { SPDocument *doc = item->document; - gchar const * spray_origin; - if(!item->getAttribute("inkscape:spray-origin")){ + gchar const *spray_origin; + if (!item->getAttribute("inkscape:spray-origin")) { spray_origin = g_strdup_printf("#%s", item->getId()); } else { spray_origin = item->getAttribute("inkscape:spray-origin"); } Geom::Point center = item->getCenter(); - 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 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()); SPCSSAttr *css = sp_repr_css_attr_new(); - if(mode == SPRAY_MODE_ERASER || no_overlap || picker || !over_transparent || !over_no_transparent){ - if(!fit_item(desktop - , item - , a - , move - , center - , mode - , angle - , _scale - , scale - , picker - , pick_center - , pick_inverse_value - , pick_fill - , pick_stroke - , pick_no_overlap - , over_no_transparent - , over_transparent - , no_overlap - , offset - , css - , false - , pick - , do_trace - , pick_to_size - , pick_to_presence - , pick_to_color - , pick_to_opacity - , invert_picked - , gamma_picked - , rand_picked)){ + if (mode == SPRAY_MODE_ERASER || no_overlap || picker || !over_transparent || !over_no_transparent) { + if (!fit_item(desktop, item, a, move, center, mode, angle, _scale, scale, picker, pick_center, + pick_inverse_value, pick_fill, pick_stroke, pick_no_overlap, over_no_transparent, + over_transparent, no_overlap, offset, css, false, pick, do_trace, pick_to_size, + pick_to_presence, pick_to_color, pick_to_opacity, invert_picked, gamma_picked, + rand_picked)) { return false; } } SPItem *item_copied; // Duplicate - Inkscape::XML::Document* xml_doc = doc->getReprDoc(); + 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); - if(!copy->attribute("inkscape:spray-origin")){ + if (!copy->attribute("inkscape:spray-origin")) { copy->setAttribute("inkscape:spray-origin", spray_origin); } parent->appendChild(copy); SPObject *new_obj = doc->getObjectByRepr(copy); - item_copied = dynamic_cast<SPItem *>(new_obj); // Conversion object->item - sp_spray_scale_rel(center,desktop, item_copied, Geom::Scale(_scale)); - sp_spray_scale_rel(center,desktop, item_copied, Geom::Scale(scale)); - sp_spray_rotate_rel(center,desktop,item_copied, Geom::Rotate(angle)); + item_copied = dynamic_cast<SPItem *>(new_obj); // Conversion object->item + sp_spray_scale_rel(center, desktop, item_copied, Geom::Scale(_scale)); + sp_spray_scale_rel(center, desktop, item_copied, Geom::Scale(scale)); + sp_spray_rotate_rel(center, desktop, item_copied, Geom::Rotate(angle)); // Move the cursor p item_copied->move_rel(Geom::Translate(move * desktop->doc2dt().withoutTranslation())); Inkscape::GC::release(copy); - if(picker){ + if (picker) { sp_desktop_apply_css_recursive(item_copied, css, true); } did = true; @@ -976,13 +884,13 @@ static bool sp_spray_recursive(SPDesktop *desktop, #ifdef ENABLE_SPRAY_MODE_SINGLE_PATH } else if (mode == SPRAY_MODE_SINGLE_PATH) { long setSize = boost::distance(set->items()); - SPItem *parent_item = setSize > 0 ? set->items().front() : nullptr; // Initial object - SPItem *unionResult = setSize > 1 ? *(++set->items().begin()) : nullptr; // Previous union - SPItem *item_copied = nullptr; // Projected object + SPItem *parent_item = setSize > 0 ? set->items().front() : nullptr; // Initial object + SPItem *unionResult = setSize > 1 ? *(++set->items().begin()) : nullptr; // Previous union + SPItem *item_copied = nullptr; // Projected object if (parent_item) { SPDocument *doc = parent_item->document; - Inkscape::XML::Document* xml_doc = doc->getReprDoc(); + Inkscape::XML::Document *xml_doc = doc->getReprDoc(); Inkscape::XML::Node *old_repr = parent_item->getRepr(); Inkscape::XML::Node *parent = old_repr->parent(); @@ -991,8 +899,8 @@ static bool sp_spray_recursive(SPDesktop *desktop, if (_fid <= population) { // Rules the population of objects sprayed // Duplicates the parent item Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc); - gchar const * spray_origin; - if(!copy->attribute("inkscape:spray-origin")){ + gchar const *spray_origin; + if (!copy->attribute("inkscape:spray-origin")) { spray_origin = g_strdup_printf("#%s", old_repr->attribute("id")); copy->setAttribute("inkscape:spray-origin", spray_origin); } else { @@ -1003,7 +911,11 @@ static bool sp_spray_recursive(SPDesktop *desktop, item_copied = dynamic_cast<SPItem *>(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 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)); @@ -1028,54 +940,31 @@ static bool sp_spray_recursive(SPDesktop *desktop, } else if (mode == SPRAY_MODE_CLONE) { Geom::OptRect a = item->documentVisualBounds(); if (a) { - if(_fid <= population) { + if (_fid <= population) { SPDocument *doc = item->document; - gchar const * spray_origin; - if(!item->getAttribute("inkscape:spray-origin")){ + gchar const *spray_origin; + if (!item->getAttribute("inkscape:spray-origin")) { spray_origin = g_strdup_printf("#%s", item->getId()); } else { spray_origin = item->getAttribute("inkscape:spray-origin"); } - Geom::Point center=item->getCenter(); - 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 = item->getCenter(); + 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()); SPCSSAttr *css = sp_repr_css_attr_new(); - if(mode == SPRAY_MODE_ERASER || no_overlap || picker || !over_transparent || !over_no_transparent){ - if(!fit_item(desktop - , item - , a - , move - , center - , mode - , angle - , _scale - , scale - , picker - , pick_center - , pick_inverse_value - , pick_fill - , pick_stroke - , pick_no_overlap - , over_no_transparent - , over_transparent - , no_overlap - , offset - , css - , true - , pick - , do_trace - , pick_to_size - , pick_to_presence - , pick_to_color - , pick_to_opacity - , invert_picked - , gamma_picked - , rand_picked)) - { + if (mode == SPRAY_MODE_ERASER || no_overlap || picker || !over_transparent || !over_no_transparent) { + if (!fit_item(desktop, item, a, move, center, mode, angle, _scale, scale, picker, pick_center, + pick_inverse_value, pick_fill, pick_stroke, pick_no_overlap, over_no_transparent, + over_transparent, no_overlap, offset, css, true, pick, do_trace, pick_to_size, + pick_to_presence, pick_to_color, pick_to_opacity, invert_picked, gamma_picked, + rand_picked)) { return false; } } SPItem *item_copied; - Inkscape::XML::Document* xml_doc = doc->getReprDoc(); + Inkscape::XML::Document *xml_doc = doc->getReprDoc(); Inkscape::XML::Node *old_repr = item->getRepr(); Inkscape::XML::Node *parent = old_repr->parent(); @@ -1084,7 +973,7 @@ static bool sp_spray_recursive(SPDesktop *desktop, // Ad the clone to the list of the parent's children parent->appendChild(clone); // Generates the link between parent and child attributes - if(!clone->attribute("inkscape:spray-origin")){ + if (!clone->attribute("inkscape:spray-origin")) { clone->setAttribute("inkscape:spray-origin", spray_origin); } gchar *href_str = g_strdup_printf("#%s", old_repr->attribute("id")); @@ -1098,7 +987,7 @@ static bool sp_spray_recursive(SPDesktop *desktop, sp_spray_scale_rel(center, desktop, item_copied, Geom::Scale(scale, scale)); sp_spray_rotate_rel(center, desktop, item_copied, Geom::Rotate(angle)); item_copied->move_rel(Geom::Translate(move * desktop->doc2dt().withoutTranslation())); - if(picker){ + if (picker) { sp_desktop_apply_css_recursive(item_copied, css, true); } Inkscape::GC::release(clone); @@ -1136,57 +1025,28 @@ static bool sp_spray_dilate(SprayTool *tc, Geom::Point /*event_p*/, Geom::Point double move_standard_deviation = get_move_standard_deviation(tc); { - std::vector<SPItem*> const items(set->items().begin(), set->items().end()); + std::vector<SPItem *> const items(set->items().begin(), set->items().end()); - for(auto item : items){ + for (auto item : items) { g_assert(item != nullptr); sp_object_ref(item); } - for(auto item : items){ + for (auto item : items) { g_assert(item != nullptr); - if (sp_spray_recursive(desktop - , set - , item - , p, vector - , tc->mode - , radius - , population - , tc->scale - , tc->scale_variation - , reverse - , move_mean - , move_standard_deviation - , tc->ratio - , tc->tilt - , tc->rotation_variation - , tc->distrib - , tc->no_overlap - , tc->picker - , tc->pick_center - , tc->pick_inverse_value - , tc->pick_fill - , tc->pick_stroke - , tc->pick_no_overlap - , tc->over_no_transparent - , tc->over_transparent - , tc->offset - , tc->usepressurescale - , get_pressure(tc) - , tc->pick - , tc->do_trace - , tc->pick_to_size - , tc->pick_to_presence - , tc->pick_to_color - , tc->pick_to_opacity - , tc->invert_picked - , tc->gamma_picked - , tc->rand_picked)) { + if (sp_spray_recursive(desktop, set, item, p, vector, tc->mode, radius, population, tc->scale, + tc->scale_variation, reverse, move_mean, move_standard_deviation, tc->ratio, + tc->tilt, tc->rotation_variation, tc->distrib, tc->no_overlap, tc->picker, + tc->pick_center, tc->pick_inverse_value, tc->pick_fill, tc->pick_stroke, + tc->pick_no_overlap, tc->over_no_transparent, tc->over_transparent, tc->offset, + tc->usepressurescale, get_pressure(tc), tc->pick, tc->do_trace, tc->pick_to_size, + tc->pick_to_presence, tc->pick_to_color, tc->pick_to_opacity, tc->invert_picked, + tc->gamma_picked, tc->rand_picked)) { did = true; } } - for(auto item : items){ + for (auto item : items) { g_assert(item != nullptr); sp_object_unref(item); } @@ -1198,17 +1058,18 @@ static bool sp_spray_dilate(SprayTool *tc, Geom::Point /*event_p*/, Geom::Point 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(tc->getDesktop()->point())); + 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(tc->getDesktop()->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 - auto tb = dynamic_cast<UI::Toolbar::SprayToolbar*>(tc->getDesktop()->get_toolbar_by_name("SprayToolbar")); + auto tb = dynamic_cast<UI::Toolbar::SprayToolbar *>(tc->getDesktop()->get_toolbar_by_name("SprayToolbar")); - if(tb) { + if (tb) { tb->set_mode(mode); } else { std::cerr << "Could not access Spray toolbar" << std::endl; @@ -1219,7 +1080,8 @@ static void sp_spray_switch_mode(SprayTool *tc, gint mode, bool with_shift) tc->update_cursor(with_shift); } -bool SprayTool::root_handler(GdkEvent* event) { +bool SprayTool::root_handler(GdkEvent *event) +{ gint ret = FALSE; switch (event->type) { @@ -1252,55 +1114,57 @@ bool SprayTool::root_handler(GdkEvent* event) { desktop->getSelection()->clear(); } - sp_spray_dilate(this, motion_w, this->last_push, Geom::Point(0,0), MOD__SHIFT(event)); + sp_spray_dilate(this, motion_w, this->last_push, 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 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))); + 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 = (guint) boost::distance(desktop->selection->items()); + num = (guint)boost::distance(desktop->selection->items()); } if (num == 0) { - this->message_context->flash(Inkscape::ERROR_MESSAGE, _("<b>Nothing selected!</b> Select objects to spray.")); + 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; + 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; + } break; /* Spray with the scroll */ case GDK_SCROLL: { if (event->scroll.state & GDK_BUTTON1_MASK) { - double temp ; + 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 const scroll_dt = desktop->point(); + ; + switch (event->scroll.direction) { case GDK_SCROLL_DOWN: case GDK_SCROLL_UP: @@ -1314,26 +1178,25 @@ bool SprayTool::root_handler(GdkEvent* event) { 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); + 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_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)); @@ -1346,24 +1209,22 @@ bool SprayTool::root_handler(GdkEvent* event) { 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)); + 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(this->desktop->getDocument(), - SP_VERB_CONTEXT_SPRAY, _("Spray with copies")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_SPRAY, _("Spray with copies")); break; case SPRAY_MODE_CLONE: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_SPRAY, _("Spray with clones")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_SPRAY, _("Spray with clones")); break; case SPRAY_MODE_SINGLE_PATH: object_set.pathUnion(true); desktop->getSelection()->add(object_set.objects().begin(), object_set.objects().end()); - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_SPRAY, _("Spray in single path")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_SPRAY, + _("Spray in single path")); break; } } @@ -1372,7 +1233,7 @@ bool SprayTool::root_handler(GdkEvent* event) { } case GDK_KEY_PRESS: - switch (get_latin_keyval (&event->key)) { + switch (get_latin_keyval(&event->key)) { case GDK_KEY_j: case GDK_KEY_J: if (MOD__SHIFT_ONLY(event)) { @@ -1491,11 +1352,11 @@ bool SprayTool::root_handler(GdkEvent* event) { break; case GDK_KEY_Control_L: case GDK_KEY_Control_R: - sp_spray_switch_mode (this, prefs->getInt("/tools/spray/mode"), MOD__SHIFT(event)); + 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)); + sp_spray_switch_mode(this, prefs->getInt("/tools/spray/mode"), MOD__SHIFT(event)); break; } } @@ -1505,18 +1366,18 @@ bool SprayTool::root_handler(GdkEvent* event) { } 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); -// } + // 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; } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: @@ -1528,4 +1389,3 @@ bool SprayTool::root_handler(GdkEvent* event) { 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 index 99497c37cd2466e2181fb4a297e8c3392ac8d28c..40329e854197add133cfc79a4fb58a1ffd9ddd79 100644 --- a/src/ui/tools/spray-tool.h +++ b/src/ui/tools/spray-tool.h @@ -22,32 +22,34 @@ */ #include <2geom/point.h> -#include "ui/tools/tool-base.h" + #include "object/object-set.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) +#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; - } - } +namespace UI { +namespace Dialog { +class Dialog; } +} // namespace UI +} // namespace Inkscape +#define SAMPLING_SIZE 8 /* fixme: ?? */ -#define SAMPLING_SIZE 8 /* fixme: ?? */ - -#define TC_MIN_PRESSURE 0.0 -#define TC_MAX_PRESSURE 1.0 -#define TC_DEFAULT_PRESSURE 0.35 +#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 { +enum +{ SPRAY_MODE_COPY, SPRAY_MODE_CLONE, SPRAY_MODE_SINGLE_PATH, @@ -55,18 +57,19 @@ enum { SPRAY_OPTION, }; -class SprayTool : public ToolBase { +class SprayTool : public ToolBase +{ public: SprayTool(); ~SprayTool() override; - //ToolBase event_context; - //Inkscape::UI::Dialog::Dialog *dialog_option;//Attribut de type SprayOptionClass, localisé dans scr/ui/dialog + // 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 dragging; /* mouse state: mouse is dragging */ bool usepressurewidth; bool usepressurepopulation; bool usepressurescale; @@ -82,7 +85,7 @@ public: double scale; double mean; double standard_deviation; - + gint distrib; gint mode; @@ -117,25 +120,23 @@ public: static const std::string prefsPath; void setup() override; - void set(const Inkscape::Preferences::Entry& val) override; + void set(const Inkscape::Preferences::Entry &val) override; virtual void setCloneTilerPrefs(); - bool root_handler(GdkEvent* event) override; + bool root_handler(GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; void update_cursor(bool /*with_shift*/); - ObjectSet* objectSet() { - return &object_set; - } + ObjectSet *objectSet() { return &object_set; } private: ObjectSet object_set; }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif @@ -149,4 +150,3 @@ private: 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 index 29c5941e98ba6b822dcd22235d18a0a7fc7da0a8..a5d074e4337785dd09f5cf39296a9665da9325df 100644 --- a/src/ui/tools/star-tool.cpp +++ b/src/ui/tools/star-tool.cpp @@ -15,33 +15,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> -#include <string> +#include "ui/tools/star-tool.h" +#include <cstring> #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> +#include <string> #include "context-fns.h" #include "desktop-style.h" #include "desktop.h" +#include "display/sp-canvas-item.h" #include "document-undo.h" #include "document.h" -#include "message-context.h" -#include "selection.h" -#include "verbs.h" - -#include "display/sp-canvas-item.h" - #include "include/macros.h" - +#include "message-context.h" #include "object/sp-namedview.h" #include "object/sp-star.h" - +#include "selection.h" #include "ui/pixmaps/cursor-star.xpm" - #include "ui/shape-editor.h" -#include "ui/tools/star-tool.h" - +#include "verbs.h" #include "xml/node-event-vector.h" using Inkscape::DocumentUndo; @@ -50,8 +44,9 @@ namespace Inkscape { namespace UI { namespace Tools { -const std::string& StarTool::getPrefsPath() { - return StarTool::prefsPath; +const std::string &StarTool::getPrefsPath() +{ + return StarTool::prefsPath; } const std::string StarTool::prefsPath = "/tools/shapes/star"; @@ -64,10 +59,10 @@ StarTool::StarTool() , isflatsided(false) , rounded(0) , randomized(0) -{ -} +{} -void StarTool::finish() { +void StarTool::finish() +{ sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); this->finishItem(); @@ -76,7 +71,8 @@ void StarTool::finish() { ToolBase::finish(); } -StarTool::~StarTool() { +StarTool::~StarTool() +{ this->enableGrDrag(false); this->sel_changed_connection.disconnect(); @@ -86,7 +82,7 @@ StarTool::~StarTool() { /* fixme: This is necessary because we do not grab */ if (this->star) { - this->finishItem(); + this->finishItem(); } } @@ -96,14 +92,16 @@ StarTool::~StarTool() { * * @param selection Should not be NULL. */ -void StarTool::selection_changed(Inkscape::Selection* selection) { - g_assert (selection != nullptr); +void StarTool::selection_changed(Inkscape::Selection *selection) +{ + g_assert(selection != nullptr); this->shape_editor->unset_item(); this->shape_editor->set_item(selection->singleItem()); } -void StarTool::setup() { +void StarTool::setup() +{ ToolBase::setup(); sp_event_context_read(this, "isflatsided"); @@ -135,7 +133,8 @@ void StarTool::setup() { } } -void StarTool::set(const Inkscape::Preferences::Entry& val) { +void StarTool::set(const Inkscape::Preferences::Entry &val) +{ Glib::ustring path = val.getEntryName(); if (path == "magnitude") { @@ -151,7 +150,8 @@ void StarTool::set(const Inkscape::Preferences::Entry& val) { } } -bool StarTool::root_handler(GdkEvent* event) { +bool StarTool::root_handler(GdkEvent *event) +{ static bool dragging; SPDesktop *desktop = this->desktop; @@ -163,125 +163,60 @@ bool StarTool::root_handler(GdkEvent* event) { 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, - nullptr, 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 + 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, + nullptr, event->button.time); + ret = TRUE; } - // 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)); + break; - this->drag(motion_dt, event->motion.state); + 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; - gobble_motion_events(GDK_BUTTON1_MASK); + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); - ret = TRUE; - } else if (!this->sp_event_context_knot_mouseover()) { - SnapManager &m = desktop->namedview->snap_manager; - m.setup(desktop); + this->drag(motion_dt, event->motion.state); - Geom::Point const motion_w(event->motion.x, event->motion.y); - Geom::Point motion_dt(desktop->w2d(motion_w)); + gobble_motion_events(GDK_BUTTON1_MASK); - 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(); - } + ret = TRUE; + } else if (!this->sp_event_context_knot_mouseover()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); - this->item_to_select = nullptr; - ret = TRUE; - sp_canvas_item_ungrab(SP_CANVAS_ITEM (desktop->acetate)); - } - break; - - case GDK_KEY_PRESS: - switch (get_latin_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"), - nullptr, - nullptr); - break; + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); - case GDK_KEY_x: - case GDK_KEY_X: - if (MOD__ALT_ONLY(event)) { - desktop->setToolboxFocusTo ("altx-star"); - ret = TRUE; + m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_NODE_HANDLE)); + m.unSetup(); } break; + case GDK_BUTTON_RELEASE: + this->xp = this->yp = 0; - 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)); - + if (event->button.button == 1 && !this->space_panning) { dragging = false; sp_event_context_discard_delayed_snap_event(this); @@ -289,46 +224,106 @@ bool StarTool::root_handler(GdkEvent* event) { 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(); } - // do not return true, so that space would work switching to selector + + this->item_to_select = nullptr; + ret = TRUE; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); } break; - case GDK_KEY_Delete: - case GDK_KEY_KP_Delete: - case GDK_KEY_BackSpace: - ret = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); + case GDK_KEY_PRESS: + switch (get_latin_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"), nullptr, nullptr); + 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)); + + 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; - default: - break; - } - break; - - case GDK_KEY_RELEASE: - switch (get_latin_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(); + case GDK_KEY_RELEASE: + switch (get_latin_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; - } - break; - - default: - break; } if (!ret) { - ret = ToolBase::root_handler(event); + ret = ToolBase::root_handler(event); } return ret; @@ -374,37 +369,38 @@ void StarTool::drag(Geom::Point p, guint state) Geom::Point const p0 = desktop->dt2doc(this->center); Geom::Point const p1 = desktop->dt2doc(pt2g); - double const sides = (gdouble) this->magnitude; + 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 */ - double snaps_radian = M_PI/snaps; - arg1 = std::round(arg1/snaps_radian) * snaps_radian; + double snaps_radian = M_PI / snaps; + arg1 = std::round(arg1 / snaps_radian) * snaps_radian; } - sp_star_position_set(this->star, this->magnitude, p0, r1, r1 * this->proportion, - arg1, arg1 + M_PI / sides, this->isflatsided, this->rounded, this->randomized); + 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"); Glib::ustring rads = q.string(desktop->namedview->display_units); this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, - ( this->isflatsided? - _("<b>Polygon</b>: radius %s, angle %.2f°; with <b>Ctrl</b> to snap angle") : - _("<b>Star</b>: radius %s, angle %.2f°; with <b>Ctrl</b> to snap angle") ), - rads.c_str(), arg1 * 180 / M_PI); + (this->isflatsided + ? _("<b>Polygon</b>: radius %s, angle %.2f°; with <b>Ctrl</b> to snap angle") + : _("<b>Star</b>: radius %s, angle %.2f°; with <b>Ctrl</b> to snap angle")), + rads.c_str(), arg1 * 180 / M_PI); } -void StarTool::finishItem() { +void StarTool::finishItem() +{ this->message_context->clear(); if (this->star != nullptr) { 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 + // 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; } @@ -418,14 +414,14 @@ void StarTool::finishItem() { forced_redraws_stop(); desktop->getSelection()->set(this->star); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_STAR, - _("Create star")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_STAR, _("Create star")); this->star = nullptr; } } -void StarTool::cancel() { +void StarTool::cancel() +{ desktop->getSelection()->clear(); sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); @@ -444,9 +440,9 @@ void StarTool::cancel() { DocumentUndo::cancel(desktop->getDocument()); } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/star-tool.h b/src/ui/tools/star-tool.h index 76daba73595e1faa19f54a90e0d5483adbcadc76..4ef2ae46194faf4088dd73816a54537ddf02d9fd 100644 --- a/src/ui/tools/star-tool.h +++ b/src/ui/tools/star-tool.h @@ -15,9 +15,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <2geom/point.h> #include <cstddef> #include <sigc++/sigc++.h> -#include <2geom/point.h> + #include "ui/tools/tool-base.h" class SPStar; @@ -29,24 +30,25 @@ class Selection; namespace UI { namespace Tools { -class StarTool : public ToolBase { +class StarTool : public ToolBase +{ public: - StarTool(); - ~StarTool() override; + StarTool(); + ~StarTool() override; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - void finish() override; - void set(const Inkscape::Preferences::Entry& val) override; - bool root_handler(GdkEvent* event) override; + void setup() override; + void finish() override; + void set(const Inkscape::Preferences::Entry &val) override; + bool root_handler(GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; private: - SPStar* star; + SPStar *star; - Geom::Point center; + Geom::Point center; /* Number of corners */ gint magnitude; @@ -65,14 +67,14 @@ private: sigc::connection sel_changed_connection; - void drag(Geom::Point p, guint state); - void finishItem(); - void cancel(); - void selection_changed(Inkscape::Selection* selection); + void drag(Geom::Point p, guint state); + void finishItem(); + void cancel(); + void selection_changed(Inkscape::Selection *selection); }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/tools/text-tool.cpp b/src/ui/tools/text-tool.cpp index bd76de79a9aacb0242a98ad6beb6ff2b2dcda269..4c21e840bcccea671fcb9743e00f37b28657bb46 100644 --- a/src/ui/tools/text-tool.cpp +++ b/src/ui/tools/text-tool.cpp @@ -14,14 +14,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gdk/gdkkeysyms.h> -#include <gtkmm/clipboard.h> -#include <glibmm/i18n.h> -#include <glibmm/regex.h> +#include "ui/tools/text-tool.h" -#include <display/sp-ctrlline.h> #include <display/sodipodi-ctrlrect.h> +#include <display/sp-ctrlline.h> #include <display/sp-ctrlquadr.h> +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> +#include <glibmm/regex.h> +#include <gtkmm/clipboard.h> #include "context-fns.h" #include "desktop-style.h" @@ -32,29 +33,23 @@ #include "inkscape.h" #include "message-context.h" #include "message-stack.h" -#include "rubberband.h" -#include "selection-chemistry.h" -#include "selection.h" -#include "text-editing.h" -#include "verbs.h" - +#include "object/sp-ellipse.h" #include "object/sp-flowtext.h" #include "object/sp-namedview.h" -#include "object/sp-text.h" #include "object/sp-rect.h" #include "object/sp-shape.h" -#include "object/sp-ellipse.h" - +#include "object/sp-text.h" +#include "rubberband.h" +#include "selection-chemistry.h" +#include "selection.h" #include "style.h" - +#include "text-editing.h" +#include "ui/control-manager.h" #include "ui/pixmaps/cursor-text-insert.xpm" #include "ui/pixmaps/cursor-text.xpm" - -#include "ui/control-manager.h" #include "ui/shape-editor.h" -#include "ui/tools/text-tool.h" #include "ui/widget/canvas.h" - +#include "verbs.h" #include "xml/attribute-record.h" #include "xml/node-event-vector.h" #include "xml/sp-css-attr.h" @@ -76,13 +71,13 @@ 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); -const std::string& TextTool::getPrefsPath() { +const std::string &TextTool::getPrefsPath() +{ return TextTool::prefsPath; } const std::string TextTool::prefsPath = "/tools/text"; - TextTool::TextTool() : ToolBase(cursor_text_xpm) , imc(nullptr) @@ -102,10 +97,10 @@ TextTool::TextTool() , creating(false) , grabbed(nullptr) , preedit_string(nullptr) -{ -} +{} -TextTool::~TextTool() { +TextTool::~TextTool() +{ delete this->shape_editor; this->shape_editor = nullptr; @@ -117,18 +112,20 @@ TextTool::~TextTool() { Inkscape::Rubberband::get(this->desktop)->stop(); } -void TextTool::setup() { - GtkSettings* settings = gtk_settings_get_default(); +void TextTool::setup() +{ + GtkSettings *settings = gtk_settings_get_default(); gint timeout = 0; - g_object_get( settings, "gtk-cursor-blink-time", &timeout, NULL ); - + g_object_get(settings, "gtk-cursor-blink-time", &timeout, NULL); + if (timeout < 0) { timeout = 200; } else { timeout /= 2; } - this->cursor = ControlManager::getManager().createControlLine(desktop->getControls(), Geom::Point(100, 0), Geom::Point(100, 100)); + this->cursor = ControlManager::getManager().createControlLine(desktop->getControls(), Geom::Point(100, 0), + Geom::Point(100, 100)); this->cursor->setRgba32(0x000000ff); sp_canvas_item_hide(this->cursor); @@ -145,7 +142,7 @@ void TextTool::setup() { 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->timeout = g_timeout_add(timeout, (GSourceFunc)sp_text_context_timeout, this); this->imc = gtk_im_multicontext_new(); if (this->imc) { @@ -158,8 +155,7 @@ void TextTool::setup() { * entered. */ gtk_im_context_set_use_preedit(this->imc, FALSE); - gtk_im_context_set_client_window(this->imc, - gtk_widget_get_window (canvas)); + 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); @@ -175,25 +171,17 @@ void TextTool::setup() { this->shape_editor = new ShapeEditor(this->desktop); SPItem *item = this->desktop->getSelection()->singleItem(); - if (item && ( - (SP_IS_FLOWTEXT(item) && SP_FLOWTEXT(item)->has_internal_frame()) || - (SP_IS_TEXT(item) && !SP_TEXT(item)->has_shape_inside()) ) - ) { + if (item && ((SP_IS_FLOWTEXT(item) && SP_FLOWTEXT(item)->has_internal_frame()) || + (SP_IS_TEXT(item) && !SP_TEXT(item)->has_shape_inside()))) { this->shape_editor->set_item(item); } - this->sel_changed_connection = desktop->getSelection()->connectChangedFirst( - sigc::mem_fun(*this, &TextTool::_selectionChanged) - ); - this->sel_modified_connection = desktop->getSelection()->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) - ); + this->sel_changed_connection = + desktop->getSelection()->connectChangedFirst(sigc::mem_fun(*this, &TextTool::_selectionChanged)); + this->sel_modified_connection = + desktop->getSelection()->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(desktop->getSelection()); @@ -206,7 +194,8 @@ void TextTool::setup() { } } -void TextTool::finish() { +void TextTool::finish() +{ if (this->desktop) { sp_signal_disconnect_by_data(this->desktop->getCanvas()->gobj(), this); } @@ -245,17 +234,18 @@ void TextTool::finish() { this->frame = nullptr; } - for (auto & text_selection_quad : this->text_selection_quads) { + for (auto &text_selection_quad : this->text_selection_quads) { sp_canvas_item_hide(text_selection_quad); sp_canvas_item_destroy(text_selection_quad); } - + this->text_selection_quads.clear(); ToolBase::finish(); } -bool TextTool::item_handler(SPItem* item, GdkEvent* event) { +bool TextTool::item_handler(SPItem *item, GdkEvent *event) +{ SPItem *item_ungrouped; gint ret = FALSE; @@ -370,8 +360,7 @@ static void sp_text_context_setup_text(TextTool *tc) text_item->updateRepr(); text_item->doWriteTransform(text_item->transform, nullptr, true); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Create text")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Create text")); } /** @@ -382,9 +371,7 @@ static void sp_text_context_setup_text(TextTool *tc) */ static void insert_uni_char(TextTool *const tc) { - g_return_if_fail(tc->unipos - && tc->unipos < sizeof(tc->uni) - && tc->uni[tc->unipos] == '\0'); + 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; @@ -392,11 +379,11 @@ static void insert_uni_char(TextTool *const tc) 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) ) ) { + 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->getDesktop()->messageStack()->flash(Inkscape::ERROR_MESSAGE, - _("Non-printable character")); + tc->getDesktop()->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); @@ -410,8 +397,7 @@ static void insert_uni_char(TextTool *const tc) 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(tc->getDesktop()->getDocument(), SP_VERB_DIALOG_TRANSFORM, - _("Insert Unicode character")); + DocumentUndo::done(tc->getDesktop()->getDocument(), SP_VERB_DIALOG_TRANSFORM, _("Insert Unicode character")); } } @@ -421,7 +407,7 @@ static void hex_to_printable_utf8_buf(char const *const ehex, char *utf8) std::stringstream ss; ss << std::hex << ehex; ss >> uv; - if (!g_unichar_isprint((gunichar) uv)) { + if (!g_unichar_isprint((gunichar)uv)) { uv = 0xfffd; } guint const len = g_unichar_to_utf8(uv, utf8); @@ -430,29 +416,36 @@ static void hex_to_printable_utf8_buf(char const *const ehex, char *utf8) static void show_curr_uni_char(TextTool *const tc) { - g_return_if_fail(tc->unipos < sizeof(tc->uni) - && tc->uni[tc->unipos] == '\0'); + 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; + 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); + 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) { +bool TextTool::root_handler(GdkEvent *event) +{ sp_canvas_item_hide(this->indicator); sp_text_context_validate_cursor_iterators(this); @@ -463,14 +456,13 @@ bool TextTool::root_handler(GdkEvent* event) { switch (event->type) { case GDK_BUTTON_PRESS: if (event->button.button == 1 && !this->space_panning) { - if (Inkscape::have_viable_layer(desktop, desktop->getMessageStack()) == false) { return TRUE; } // save drag origin - this->xp = (gint) event->button.x; - this->yp = (gint) event->button.y; + 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); @@ -484,7 +476,8 @@ bool TextTool::root_handler(GdkEvent* event) { 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, + GDK_KEY_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_BUTTON_PRESS_MASK | + GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK, nullptr, event->button.time); this->grabbed = SP_CANVAS_ITEM(desktop->acetate); this->creating = true; @@ -495,9 +488,8 @@ bool TextTool::root_handler(GdkEvent* event) { break; case GDK_MOTION_NOTIFY: { 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 ) ) { + 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 @@ -521,7 +513,8 @@ bool TextTool::root_handler(GdkEvent* event) { Inkscape::Util::Quantity y_q = Inkscape::Util::Quantity(fabs((p - this->p0)[Geom::Y]), "px"); Glib::ustring xs = x_q.string(desktop->namedview->display_units); Glib::ustring ys = y_q.string(desktop->namedview->display_units); - this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Flowed text frame</b>: %s × %s"), xs.c_str(), ys.c_str()); + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Flowed text frame</b>: %s × %s"), + xs.c_str(), ys.c_str()); } else if (!this->sp_event_context_knot_mouseover()) { SnapManager &m = desktop->namedview->snap_manager; m.setup(desktop); @@ -638,43 +631,47 @@ bool TextTool::root_handler(GdkEvent* event) { Geom::Point const top_left = desktop->get_display_area().bounds().corner(3); Geom::Point const cursor_size(0, cursor_height); Geom::Point const im_position = 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.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(desktop->d2w(cursor_size)[Geom::Y]); + im_cursor.height = (int)-floor(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->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) + // otherwise even one line won't fit; most probably a slip of hand (even if bigger than + // tolerance) if (prefs->getBool("/tools/text/use_svg2", true)) { // SVG 2 text - SPItem *text = create_text_with_rectangle (desktop, this->p0, p1); + SPItem *text = create_text_with_rectangle(desktop, this->p0, p1); desktop->getSelection()->set(text); - SPCSSAttr *css = sp_repr_css_attr(text->getRepr(), "style" ); + SPCSSAttr *css = sp_repr_css_attr(text->getRepr(), "style"); sp_repr_css_attr_unref(css); } else { // SVG 1.2 text - SPItem *ft = create_flowtext_with_internal_frame (desktop, this->p0, p1); + SPItem *ft = create_flowtext_with_internal_frame(desktop, this->p0, p1); /* Set style */ sp_desktop_apply_style_tool(desktop, ft->getRepr(), "/tools/text", true); - SPCSSAttr *css = sp_repr_css_attr(ft->getRepr(), "style" ); + SPCSSAttr *css = sp_repr_css_attr(ft->getRepr(), "style"); Geom::Affine const local(ft->i2doc_affine()); double const ex(local.descrim()); - if ( (ex != 0.0) && (ex != 1.0) ) { - sp_css_attr_scale(css, 1/ex); + if ((ex != 0.0) && (ex != 1.0)) { + sp_css_attr_scale(css, 1 / ex); } - ft->setCSS(css,"style"); + ft->setCSS(css, "style"); sp_repr_css_attr_unref(css); ft->updateRepr(); @@ -685,7 +682,9 @@ bool TextTool::root_handler(GdkEvent* event) { DocumentUndo::done(desktop->getDocument(), 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.")); + 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; @@ -696,567 +695,611 @@ bool TextTool::root_handler(GdkEvent* event) { case GDK_KEY_PRESS: { guint const group0_keyval = get_latin_keyval(&event->key); - if (group0_keyval == GDK_KEY_KP_Add || - group0_keyval == GDK_KEY_KP_Subtract) { + 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 + 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 (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; + /* 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_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_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_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; + 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; + 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().bounds(); - screenlines = (int) floor(fabs(d.min()[Geom::Y] - d.max()[Geom::Y])/spacing) - 1; - if (screenlines <= 0) - screenlines = 1; - } + 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().bounds(); + 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("TextFontFamilyAction_entry"); - return TRUE; + /* 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("TextFontFamilyAction_entry"); + 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 = + false; // we don't need it anymore, having created a real <text> } - 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 = false; // 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(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Insert no-break space")); - return TRUE; + 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(desktop->getDocument(), 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): ")); } - 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; + if (this->imc) { + gtk_im_context_reset(this->imc); } - 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(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Make bold")); + 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(desktop->getDocument(), 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(desktop->getDocument(), 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_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(desktop->getDocument(), 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_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 = false; // we don't need it anymore, having created a real <text> + } + + SPText *text_element = dynamic_cast<SPText *>(text); + if (text_element && (text_element->has_shape_inside() || text_element->has_inline_size())) { + // Handle new line like any other character. + this->text_sel_start = this->text_sel_end = + sp_te_insert(this->text, this->text_sel_start, "\n"); + } else { + // Replace new line by either <tspan sodipodi:role="line" or <flowPara>. + 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(desktop->getDocument(), 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; } - 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; + 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; } - 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 = false; // we don't need it anymore, having created a real <text> - } + iterator_pair bspace_pair; + bool success = + sp_te_delete(this->text, this->text_sel_start, this->text_sel_end, bspace_pair); - SPText* text_element = dynamic_cast<SPText*>(text); - if (text_element && (text_element->has_shape_inside() || text_element->has_inline_size())) { - // Handle new line like any other character. - this->text_sel_start = this->text_sel_end = sp_te_insert(this->text, this->text_sel_start, "\n"); + 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 { - // Replace new line by either <tspan sodipodi:role="line" or <flowPara>. - 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); + 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(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("New line")); - return TRUE; + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Backspace")); } - case GDK_KEY_BackSpace: - if (this->text) { // if nascent_object, do nothing, but return TRUE; same for all other delete and move keys + return TRUE; + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + if (this->text) { + bool noSelection = false; - 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 = 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; - } + this->text_sel_end.nextEndOfWord(); } 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; - } + this->text_sel_end.nextCursorPosition(); } - - sp_text_context_update_cursor(this); - sp_text_context_update_text_selection(this); - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Backspace")); + noSelection = true; } - 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; - } + iterator_pair del_pair; + bool success = + sp_te_delete(this->text, this->text_sel_start, this->text_sel_end, del_pair); - 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) { + 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 { - 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; - } + } 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(desktop->getDocument(), 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_latin_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::done(desktop->getDocument(), 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_latin_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(desktop->getDocument(), "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_latin_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(desktop->getDocument(), "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_latin_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(desktop->getDocument(), "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_latin_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(desktop->getDocument(), "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) { + DocumentUndo::maybeDone(desktop->getDocument(), "kern:left", SP_VERB_CONTEXT_TEXT, + _("Kern to the left")); + } else { if (MOD__CTRL(event)) - this->text_sel_end.thisStartOfShape(); + this->text_sel_end.cursorLeftWithControl(); else - this->text_sel_end.thisStartOfLine(); + this->text_sel_end.cursorLeft(); cursor_moved = true; break; } - return TRUE; - case GDK_KEY_End: - case GDK_KEY_KP_End: - if (this->text) { + } + 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_latin_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(desktop->getDocument(), "kern:right", SP_VERB_CONTEXT_TEXT, + _("Kern to the right")); + } else { if (MOD__CTRL(event)) - this->text_sel_end.nextStartOfShape(); + this->text_sel_end.cursorRightWithControl(); else - this->text_sel_end.thisEndOfLine(); + this->text_sel_end.cursorRight(); 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); + } + 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_latin_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(desktop->getDocument(), "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_Page_Up: - case GDK_KEY_KP_Page_Up: - if (this->text) { - this->text_sel_end.cursorUp(screenlines); + } + 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_latin_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(desktop->getDocument(), "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_Escape: - if (this->creating) { - this->creating = false; - if (this->grabbed) { - sp_canvas_item_ungrab(this->grabbed); - this->grabbed = nullptr; - } - Inkscape::Rubberband::get(desktop)->stop(); - } else { - desktop->getSelection()->clear(); + } + 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 = false; + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed); + this->grabbed = nullptr; } - 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); - } + Inkscape::Rubberband::get(desktop)->stop(); + } else { + desktop->getSelection()->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(this->text, this->text_sel_start, this->text_sel_end, desktop, -90); + sp_te_adjust_rotation_screen(this->text, this->text_sel_start, + this->text_sel_end, desktop, -1); } - DocumentUndo::maybeDone(desktop->getDocument(), "textrot:ccw", SP_VERB_CONTEXT_TEXT, _("Rotate counterclockwise")); - sp_text_context_update_cursor(this); - sp_text_context_update_text_selection(this); - return TRUE; + } else { + sp_te_adjust_rotation(this->text, this->text_sel_start, this->text_sel_end, + desktop, -90); } + DocumentUndo::maybeDone(desktop->getDocument(), "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); - } + } + 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(this->text, this->text_sel_start, this->text_sel_end, desktop, 90); + sp_te_adjust_rotation_screen(this->text, this->text_sel_start, + this->text_sel_end, desktop, 1); } - DocumentUndo::maybeDone(desktop->getDocument(), "textrot:cw", SP_VERB_CONTEXT_TEXT, _("Rotate clockwise")); - sp_text_context_update_cursor(this); - sp_text_context_update_text_selection(this); - return TRUE; + } else { + sp_te_adjust_rotation(this->text, this->text_sel_start, this->text_sel_end, + desktop, 90); } + DocumentUndo::maybeDone(desktop->getDocument(), "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(desktop->getDocument(), "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(desktop->getDocument(), "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_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(desktop->getDocument(), "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(desktop->getDocument(), "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(desktop->getDocument(), "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(desktop->getDocument(), "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; + 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(desktop->getDocument(), "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(desktop->getDocument(), "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; + 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, + } 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)) { + 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) { @@ -1276,7 +1319,7 @@ bool TextTool::root_handler(GdkEvent* event) { } case GDK_KEY_RELEASE: - if (!this->unimode && this->imc && gtk_im_context_filter_keypress(this->imc, (GdkEventKey*) event)) { + if (!this->unimode && this->imc && gtk_im_context_filter_keypress(this->imc, (GdkEventKey *)event)) { return TRUE; } break; @@ -1285,13 +1328,14 @@ bool TextTool::root_handler(GdkEvent* event) { } // 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 -// } + // 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); - } /** @@ -1310,11 +1354,11 @@ bool sp_text_paste_inline(ToolBase *ec) Glib::ustring const clip_text = refClipboard->wait_for_text(); if (!clip_text.empty()) { - bool is_svg2 = false; SPText *textitem = dynamic_cast<SPText *>(tc->text); if (textitem) { - is_svg2 = textitem->has_shape_inside() /*|| textitem->has_inline_size()*/; // Do now since hiding messes this up. + is_svg2 = textitem->has_shape_inside() /*|| textitem->has_inline_size()*/; // Do now since hiding messes + // this up. textitem->hide_shape_inside(); } @@ -1333,17 +1377,14 @@ bool sp_text_paste_inline(ToolBase *ec) Glib::ustring::iterator itr = text.begin(); gunichar paste_string_uchar; - while(itr != text.end()) - { + 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) { + if (paste_string_uchar >= 0x00000020 || paste_string_uchar == 0x00000009 || + paste_string_uchar == 0x0000000A || paste_string_uchar == 0x0000000D) { ++itr; } else { itr = text.erase(itr); @@ -1357,18 +1398,20 @@ bool sp_text_paste_inline(ToolBase *ec) // using indices is slow in ustrings. Whatever. Glib::ustring::size_type begin = 0; - for ( ; ; ) { + for (;;) { Glib::ustring::size_type end = text.find('\n', begin); if (end == Glib::ustring::npos || is_svg2) { // Paste everything 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()); + 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; } // Paste up to new line, add line, repeat. - 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_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; } @@ -1378,12 +1421,11 @@ bool sp_text_paste_inline(ToolBase *ec) if (flowtext) { flowtext->fix_overflow_flowregion(true); } - DocumentUndo::done(ec->getDesktop()->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Paste text")); + DocumentUndo::done(ec->getDesktop()->getDocument(), SP_VERB_CONTEXT_TEXT, _("Paste text")); return true; } - + } // FIXME: else create and select a new object under cursor! return false; @@ -1415,7 +1457,7 @@ SPCSSAttr *sp_text_get_style_at_cursor(ToolBase const *ec) 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 take_style_from_item(const_cast<SPObject *>(obj)); } return nullptr; @@ -1499,7 +1541,6 @@ bool sp_text_delete_selection(ToolBase *ec) 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 @@ -1522,11 +1563,8 @@ void TextTool::_selectionChanged(Inkscape::Selection *selection) shape_editor->unset_item(); SPItem *item = selection->singleItem(); - if (item && ( - (SP_IS_FLOWTEXT(item) && SP_FLOWTEXT(item)->has_internal_frame()) || - (SP_IS_TEXT(item) && - !(SP_TEXT(item)->has_shape_inside() && !SP_TEXT(item)->get_first_rectangle())) - )) { + if (item && ((SP_IS_FLOWTEXT(item) && SP_FLOWTEXT(item)->has_internal_frame()) || + (SP_IS_TEXT(item) && !(SP_TEXT(item)->has_shape_inside() && !SP_TEXT(item)->get_first_rectangle())))) { shape_editor->set_item(item); } @@ -1550,7 +1588,7 @@ void TextTool::_selectionChanged(Inkscape::Selection *selection) sp_text_context_update_text_selection(this); } -void TextTool::_selectionModified(Inkscape::Selection */*selection*/, guint /*flags*/) +void TextTool::_selectionModified(Inkscape::Selection * /*selection*/, guint /*flags*/) { sp_text_context_update_cursor(this); sp_text_context_update_text_selection(this); @@ -1561,7 +1599,7 @@ bool TextTool::_styleSet(SPCSSAttr const *css) if (this->text == nullptr) 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 + 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); @@ -1569,14 +1607,13 @@ bool TextTool::_styleSet(SPCSSAttr const *css) // change which requires rewriting the 'x' and 'y' attributes of the tpsans for Inkscape // multi-line text (with sodipodi:role="line"). We need to rewrite the repr after this is // done. rebuldLayout() will be called a second time unnecessarily. - SPText* sptext = dynamic_cast<SPText*>(text); + SPText *sptext = dynamic_cast<SPText *>(text); if (sptext) { sptext->rebuildLayout(); sptext->updateRepr(); } - DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Set text style")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_CONTEXT_TEXT, _("Set text style")); sp_text_context_update_cursor(this); sp_text_context_update_text_selection(this); return true; @@ -1593,7 +1630,7 @@ int TextTool::_styleQueried(SPStyle *style, int property) } sp_text_context_validate_cursor_iterators(this); - std::vector<SPItem*> styles_list; + std::vector<SPItem *> styles_list; Inkscape::Text::Layout::iterator begin_it, end_it; if (this->text_sel_start < this->text_sel_end) { @@ -1608,22 +1645,22 @@ int TextTool::_styleQueried(SPStyle *style, int property) end_it.nextCharacter(); } } - for (Inkscape::Text::Layout::iterator it = begin_it ; it < end_it ; it.nextStartOfSpan()) { + for (Inkscape::Text::Layout::iterator it = begin_it; it < end_it; it.nextStartOfSpan()) { SPObject *pos_obj = nullptr; layout->getSourceOfCharacter(it, &pos_obj); if (!pos_obj) { continue; } - if (! pos_obj->parent) // the string is not in the document anymore (deleted) + if (!pos_obj->parent) // the string is not in the document anymore (deleted) return 0; - if ( SP_IS_STRING(pos_obj) ) { - pos_obj = pos_obj->parent; // SPStrings don't have style + if (SP_IS_STRING(pos_obj)) { + pos_obj = pos_obj->parent; // SPStrings don't have style } - styles_list.insert(styles_list.begin(),(SPItem*)pos_obj); + styles_list.insert(styles_list.begin(), (SPItem *)pos_obj); } - int result = sp_desktop_query_style_from_list (styles_list, style, property); + int result = sp_desktop_query_style_from_list(styles_list, style, property); return result; } @@ -1633,19 +1670,20 @@ static void sp_text_context_validate_cursor_iterators(TextTool *tc) if (tc->text == nullptr) return; Inkscape::Text::Layout const *layout = te_get_layout(tc->text); - if (layout) { // undo can change the text length without us knowing it + 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) +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->getDesktop()) return; + if (!tc->getDesktop()) + return; - SPDesktop* desktop = tc->getDesktop(); + SPDesktop *desktop = tc->getDesktop(); if (tc->text) { Geom::Point p0, p1; @@ -1655,7 +1693,6 @@ static void sp_text_context_update_cursor(TextTool *tc, bool scroll_to_see) // scroll to show cursor if (scroll_to_see) { - // We don't want to scroll outside the text box area (i.e. when there is hidden text) // or we could end up in Timbuktu. bool scroll = true; @@ -1669,7 +1706,8 @@ static void sp_text_context_update_cursor(TextTool *tc, bool scroll_to_see) if (scroll) { Geom::Point const center = desktop->current_center(); 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 + // unlike mouse moves, here we must scroll all the way at first shot, so we override the + // autoscrollspeed desktop->scroll_to_point(d0, 1.0); else desktop->scroll_to_point(d1, 1.0); @@ -1681,14 +1719,14 @@ static void sp_text_context_update_cursor(TextTool *tc, bool scroll_to_see) /* fixme: ... need another transformation to get canvas widget coordinate space? */ if (tc->imc) { - GdkRectangle im_cursor = { 0, 0, 1, 1 }; + GdkRectangle im_cursor = {0, 0, 1, 1}; Geom::Point const top_left = desktop->get_display_area().corner(3); - Geom::Point const im_d0 = desktop->d2w(d0 - top_left); - Geom::Point const im_d1 = 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; + Geom::Point const im_d0 = desktop->d2w(d0 - top_left); + Geom::Point const im_d1 = 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); } @@ -1712,7 +1750,7 @@ static void sp_text_context_update_cursor(TextTool *tc, bool scroll_to_see) // Frame around text if (SP_IS_FLOWTEXT(tc->text)) { - SPItem *frame = SP_FLOWTEXT(tc->text)->get_frame (nullptr); // first frame only + SPItem *frame = SP_FLOWTEXT(tc->text)->get_frame(nullptr); // first frame only if (frame) { sp_canvas_item_show(tc->frame); Geom::OptRect frame_bbox = frame->desktopVisualBounds(); @@ -1722,10 +1760,13 @@ static void sp_text_context_update_cursor(TextTool *tc, bool scroll_to_see) } } - 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); + 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 if (SP_IS_TEXT(tc->text)) { - Geom::OptRect opt_frame = SP_TEXT(tc->text)->get_frame(); if (opt_frame) { @@ -1740,8 +1781,11 @@ static void sp_text_context_update_cursor(TextTool *tc, bool scroll_to_see) } } else { - - 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); + 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 { @@ -1749,7 +1793,10 @@ static void sp_text_context_update_cursor(TextTool *tc, bool scroll_to_see) sp_canvas_item_hide(tc->frame); tc->show = FALSE; if (!tc->nascent_object) { - 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 + // FIXME: this is a copy of string from tools-switch, do not desync + tc->message_context->set(Inkscape::NORMAL_MESSAGE, + _("<b>Click</b> to select or create text, <b>drag</b> to create flowed text; then " + "type.")); } } @@ -1760,9 +1807,10 @@ 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->getDesktop()) return; + if (!tc->getDesktop()) + return; - for (auto & text_selection_quad : tc->text_selection_quads) { + for (auto &text_selection_quad : tc->text_selection_quads) { sp_canvas_item_hide(text_selection_quad); sp_canvas_item_destroy(text_selection_quad); } @@ -1771,13 +1819,13 @@ static void sp_text_context_update_text_selection(TextTool *tc) std::vector<Geom::Point> quads; if (tc->text != nullptr) 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) { + for (unsigned i = 0; i < quads.size(); i += 4) { SPCanvasItem *quad_canvasitem; quad_canvasitem = sp_canvas_item_new(tc->getDesktop()->getControls(), SP_TYPE_CTRLQUADR, nullptr); // 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_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); } @@ -1807,45 +1855,46 @@ static gint sp_text_context_timeout(TextTool *tc) static void sp_text_context_forget_text(TextTool *tc) { - if (! tc->text) return; + 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 = nullptr; -/* 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(tc->desktop->getDocument(), SP_VERB_CONTEXT_TEXT, - _("Remove empty text")); + /* 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(tc->desktop->getDocument(), SP_VERB_CONTEXT_TEXT, + _("Remove empty text")); + } } - } -*/ + */ } -gint sptc_focus_in(GtkWidget *widget, GdkEventFocus */*event*/, TextTool *tc) +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) +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) +static void sptc_commit(GtkIMContext * /*imc*/, gchar *string, TextTool *tc) { if (!tc->text) { sp_text_context_setup_text(tc); @@ -1856,22 +1905,21 @@ static void sptc_commit(GtkIMContext */*imc*/, gchar *string, TextTool *tc) sp_text_context_update_cursor(tc); sp_text_context_update_text_selection(tc); - DocumentUndo::done(tc->text->document, SP_VERB_CONTEXT_TEXT, - _("Type text")); + 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) +void sp_text_context_place_cursor(TextTool *tc, SPObject *text, Inkscape::Text::Layout::iterator where) { - tc->getDesktop()->selection->set (text); + tc->getDesktop()->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) +void sp_text_context_place_cursor_at(TextTool *tc, SPObject *text, Geom::Point const p) { - tc->getDesktop()->selection->set (text); - sp_text_context_place_cursor (tc, text, sp_te_get_position_by_coords(tc->text, p)); + tc->getDesktop()->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) @@ -1881,9 +1929,9 @@ Inkscape::Text::Layout::iterator *sp_text_context_get_cursor_position(TextTool * return &(tc->text_sel_end); } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/text-tool.h b/src/ui/tools/text-tool.h index 0861a2cf14150086cd1e86bd4e611bc466ab0de7..fbc1ed1c46f88e55f29fdc16f50bed12c0455147 100644 --- a/src/ui/tools/text-tool.h +++ b/src/ui/tools/text-tool.h @@ -15,14 +15,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <2geom/point.h> #include <sigc++/connection.h> -#include "ui/tools/tool-base.h" -#include <2geom/point.h> #include "libnrtype/Layout-TNG.h" +#include "ui/tools/tool-base.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) +#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) typedef struct _GtkIMContext GtkIMContext; @@ -35,10 +36,11 @@ class Selection; namespace UI { namespace Tools { -class TextTool : public ToolBase { +class TextTool : public ToolBase +{ public: - TextTool(); - ~TextTool() override; + TextTool(); + ~TextTool() override; sigc::connection sel_changed_connection; sigc::connection sel_modified_connection; @@ -61,8 +63,9 @@ public: 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; + 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; @@ -70,22 +73,22 @@ public: 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 + 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 + Geom::Point p0; // initial point if the flowtext rect /* Preedit String */ - gchar* preedit_string; + gchar *preedit_string; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - void finish() override; - bool root_handler(GdkEvent* event) override; - bool item_handler(SPItem* item, GdkEvent* event) override; + void setup() override; + void finish() override; + bool root_handler(GdkEvent *event) override; + bool item_handler(SPItem *item, GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; private: void _selectionChanged(Inkscape::Selection *selection); @@ -100,12 +103,12 @@ SPCSSAttr *sp_text_get_style_at_cursor(ToolBase const *ec); // std::vector<SPCSSAttr*> sp_text_get_selected_style(ToolBase const *ec, unsigned *k, int *b, std::vector<unsigned> // *positions); 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); +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); -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/tools/tool-base.cpp b/src/ui/tools/tool-base.cpp index ddf0c9e9401562993c083fa0c6a529f4edbf94bf..13abd27bc0aa313594e2ee0ab789ea961d681993 100644 --- a/src/ui/tools/tool-base.cpp +++ b/src/ui/tools/tool-base.cpp @@ -15,48 +15,42 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/tools/tool-base.h" + #include <gdk/gdkkeysyms.h> #include <gdkmm/display.h> #include <glibmm/i18n.h> -#include "shortcuts.h" -#include "file.h" - #include "desktop-events.h" #include "desktop-style.h" #include "desktop.h" +#include "display/canvas-rotate.h" +#include "display/sp-canvas-group.h" +#include "file.h" #include "gradient-drag.h" -#include "knot-ptr.h" +#include "include/gtkmm_version.h" #include "include/macros.h" +#include "knot-ptr.h" #include "message-context.h" +#include "object/sp-guide.h" #include "rubberband.h" #include "selcue.h" #include "selection.h" +#include "shortcuts.h" #include "sp-cursor.h" - -#include "display/sp-canvas-group.h" -#include "display/canvas-rotate.h" - -#include "include/gtkmm_version.h" - -#include "object/sp-guide.h" - #include "ui/contextmenu.h" -#include "ui/interface.h" #include "ui/event-debug.h" -#include "ui/tool/control-point.h" +#include "ui/interface.h" #include "ui/shape-editor.h" -#include "ui/tools/tool-base.h" -#include "ui/tools-switch.h" -#include "ui/tools/lpe-tool.h" #include "ui/tool/commit-events.h" +#include "ui/tool/control-point.h" #include "ui/tool/event-utils.h" -#include "ui/tools/node-tool.h" #include "ui/tool/shape-record.h" +#include "ui/tools-switch.h" +#include "ui/tools/lpe-tool.h" +#include "ui/tools/node-tool.h" #include "ui/widget/canvas.h" - #include "widgets/desktop-widget.h" - #include "xml/node-event-vector.h" // globals for temporary switching to selector by space @@ -76,21 +70,19 @@ static guint scroll_keyval = 0; static bool latin_keys_group_valid = FALSE; static gint latin_keys_group; - namespace Inkscape { namespace UI { namespace Tools { -static void set_event_location(SPDesktop * desktop, GdkEvent * event); - +static void set_event_location(SPDesktop *desktop, GdkEvent *event); ToolBase::ToolBase(gchar const *const *cursor_shape, bool uses_snap) : _uses_snap(uses_snap) , cursor_shape(cursor_shape) -{ -} +{} -ToolBase::~ToolBase() { +ToolBase::~ToolBase() +{ if (this->pref_observer) { delete this->pref_observer; } @@ -106,13 +98,15 @@ ToolBase::~ToolBase() { * * When you override it, call this method first. */ -void ToolBase::setup() { +void ToolBase::setup() +{ this->pref_observer = new ToolPrefObserver(this->getPrefsPath(), this); Inkscape::Preferences::get()->addObserver(*(this->pref_observer)); this->sp_event_context_update_cursor(); } -void ToolBase::finish() { +void ToolBase::finish() +{ this->desktop->getCanvas()->forced_redraws_stop(); this->enableSelectionCue(false); } @@ -120,44 +114,40 @@ void ToolBase::finish() { /** * Called by our pref_observer if a preference has been changed. */ -void ToolBase::set(const Inkscape::Preferences::Entry& /*val*/) { -} - +void ToolBase::set(const Inkscape::Preferences::Entry & /*val*/) {} /** * Set the cursor to a standard GDK cursor */ -void ToolBase::sp_event_context_set_cursor(GdkCursorType cursor_type) { - +void ToolBase::sp_event_context_set_cursor(GdkCursorType cursor_type) +{ GtkWidget *w = GTK_WIDGET(this->desktop->getCanvas()->gobj()); GdkDisplay *display = gdk_display_get_default(); GdkCursor *cursor = gdk_cursor_new_for_display(display, cursor_type); if (cursor) { - gdk_window_set_cursor (gtk_widget_get_window (w), cursor); - g_object_unref (cursor); + gdk_window_set_cursor(gtk_widget_get_window(w), cursor); + g_object_unref(cursor); } } /** * Recreates and draws cursor on desktop related to ToolBase. */ -void ToolBase::sp_event_context_update_cursor() { +void ToolBase::sp_event_context_update_cursor() +{ Gtk::Widget *w = desktop->getCanvas(); if (w->get_window()) { if (cursor_shape) { - bool fillHasColor = false; + bool fillHasColor = false; bool strokeHasColor = false; - guint32 fillColor = sp_desktop_get_color_tool(desktop, getPrefsPath(), true, &fillHasColor); - guint32 strokeColor = sp_desktop_get_color_tool(desktop, getPrefsPath(), false, &strokeHasColor); - double fillOpacity = fillHasColor ? sp_desktop_get_opacity_tool(desktop, getPrefsPath(), true) :1.0; - double strokeOpacity = strokeHasColor ? sp_desktop_get_opacity_tool(desktop, getPrefsPath(), false):1.0; - - cursor = Glib::wrap(sp_cursor_from_xpm( - cursor_shape, - SP_RGBA32_C_COMPOSE(fillColor, fillOpacity), - SP_RGBA32_C_COMPOSE(strokeColor, strokeOpacity) - )); + guint32 fillColor = sp_desktop_get_color_tool(desktop, getPrefsPath(), true, &fillHasColor); + guint32 strokeColor = sp_desktop_get_color_tool(desktop, getPrefsPath(), false, &strokeHasColor); + double fillOpacity = fillHasColor ? sp_desktop_get_opacity_tool(desktop, getPrefsPath(), true) : 1.0; + double strokeOpacity = strokeHasColor ? sp_desktop_get_opacity_tool(desktop, getPrefsPath(), false) : 1.0; + + cursor = Glib::wrap(sp_cursor_from_xpm(cursor_shape, SP_RGBA32_C_COMPOSE(fillColor, fillOpacity), + SP_RGBA32_C_COMPOSE(strokeColor, strokeOpacity))); } w->get_window()->set_cursor(cursor); w->get_display()->flush(); @@ -168,15 +158,15 @@ void ToolBase::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) { +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))) { + 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 @@ -194,14 +184,14 @@ gint gobble_key_events(guint keyval, gint mask) { /** * Gobbles next motion notify events on the queue with the same mask. Returns the number of events consumed. */ -gint gobble_motion_events(gint mask) { +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)) { + while (event_next && event_next->type == GDK_MOTION_NOTIFY && (event_next->motion.state & mask)) { // kill it gdk_event_free(event_next); // get next @@ -219,7 +209,8 @@ gint gobble_motion_events(gint mask) { * Toggles current tool between active tool and selector tool. * Subroutine of sp_event_context_private_root_handler(). */ -static void sp_toggle_selector(SPDesktop *dt) { +static void sp_toggle_selector(SPDesktop *dt) +{ if (!dt->event_context) return; @@ -241,7 +232,8 @@ static void sp_toggle_selector(SPDesktop *dt) { * Toggles current tool between active tool and dropper tool. * Subroutine of sp_event_context_private_root_handler(). */ -void sp_toggle_dropper(SPDesktop *dt) { +void sp_toggle_dropper(SPDesktop *dt) +{ if (!dt->event_context) return; @@ -265,7 +257,7 @@ void sp_toggle_dropper(SPDesktop *dt) { */ static gdouble accelerate_scroll(GdkEvent *event, gdouble acceleration) { - guint32 time_diff = ((GdkEventKey *) event)->time - scroll_event_time; + 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) { @@ -274,7 +266,7 @@ static gdouble accelerate_scroll(GdkEvent *event, gdouble acceleration) scroll_multiply += acceleration; // continue acceleration } - scroll_event_time = ((GdkEventKey *) event)->time; + scroll_event_time = ((GdkEventKey *)event)->time; scroll_keyval = event->key.keyval; return scroll_multiply; @@ -284,10 +276,12 @@ static gdouble accelerate_scroll(GdkEvent *event, gdouble acceleration) * the modifier state of the supplied event. */ bool ToolBase::_keyboardMove(GdkEventKey const &event, Geom::Point const &dir) { - if (held_control(event)) return false; + if (held_control(event)) + return false; unsigned num = 1 + combine_key_events(shortcut_key(event), 0); Geom::Point delta = dir * num; - if (held_shift(event)) delta *= 10; + if (held_shift(event)) + delta *= 10; if (held_alt(event)) { delta /= desktop->current_zoom(); } else { @@ -296,17 +290,17 @@ bool ToolBase::_keyboardMove(GdkEventKey const &event, Geom::Point const &dir) delta *= nudge; } if (shape_editor && shape_editor->has_knotholder()) { - KnotHolder * knotholder = shape_editor->knotholder; + KnotHolder *knotholder = shape_editor->knotholder; if (knotholder) { knotholder->transform_selected(Geom::Translate(delta)); } } else if (tools_isactive(desktop, TOOLS_NODES)) { - Inkscape::UI::Tools::NodeTool *nt = static_cast<Inkscape::UI::Tools::NodeTool*>(desktop->event_context); + Inkscape::UI::Tools::NodeTool *nt = static_cast<Inkscape::UI::Tools::NodeTool *>(desktop->event_context); if (nt) { - for(auto i=nt->_shape_editors.begin();i!=nt->_shape_editors.end();++i){ - ShapeEditor * shape_editor = i->second; + for (auto i = nt->_shape_editors.begin(); i != nt->_shape_editors.end(); ++i) { + ShapeEditor *shape_editor = i->second; if (shape_editor && shape_editor->has_knotholder()) { - KnotHolder * knotholder = shape_editor->knotholder; + KnotHolder *knotholder = shape_editor->knotholder; if (knotholder) { knotholder->transform_selected(Geom::Translate(delta)); } @@ -317,9 +311,8 @@ bool ToolBase::_keyboardMove(GdkEventKey const &event, Geom::Point const &dir) return true; } - -bool ToolBase::root_handler(GdkEvent* event) { - +bool ToolBase::root_handler(GdkEvent *event) +{ // ui_dump_event (event, "ToolBase::root_handler"); static Geom::Point button_w; static unsigned int panning = 0; @@ -334,572 +327,564 @@ bool ToolBase::root_handler(GdkEvent* event) { gint ret = FALSE; switch (event->type) { - case GDK_2BUTTON_PRESS: - if (panning) { - panning = 0; - sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); - 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, nullptr, - event->button.time - 1); - + case GDK_2BUTTON_PRESS: + if (panning) { + panning = 0; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); ret = TRUE; + } else { + /* sp_desktop_dialog(); */ } break; - case 2: - if ((event->button.state & GDK_CONTROL_MASK) && !desktop->get_rotation_lock()) { - // On screen canvas rotation preview - - // Grab background before doing anything else - sp_canvas_rotate_start (SP_CANVAS_ROTATE(desktop->canvas_rotate), - desktop->canvas->get_backing_store()->cobj()); - sp_canvas_item_ungrab (desktop->acetate); - sp_canvas_item_show (desktop->canvas_rotate); - sp_canvas_item_grab (desktop->canvas_rotate, - GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | - GDK_BUTTON_RELEASE_MASK | - GDK_POINTER_MOTION_MASK, - nullptr, event->button.time ); - // sp_canvas_item_hide (desktop->drawing); - - } else 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; + case GDK_BUTTON_PRESS: + // save drag origin + xp = (gint)event->button.x; + yp = (gint)event->button.y; + within_tolerance = true; - sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), - GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | - GDK_POINTER_MOTION_HINT_MASK, - nullptr, event->button.time - 1); + 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, + nullptr, event->button.time - 1); + + ret = TRUE; + } + break; - ret = TRUE; - break; + case 2: + if ((event->button.state & GDK_CONTROL_MASK) && !desktop->get_rotation_lock()) { + // On screen canvas rotation preview + + // Grab background before doing anything else + sp_canvas_rotate_start(SP_CANVAS_ROTATE(desktop->canvas_rotate), + desktop->canvas->get_backing_store()->cobj()); + sp_canvas_item_ungrab(desktop->acetate); + sp_canvas_item_show(desktop->canvas_rotate); + sp_canvas_item_grab(desktop->canvas_rotate, + GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK, + nullptr, event->button.time); + // sp_canvas_item_hide (desktop->drawing); + + } else 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, + nullptr, event->button.time - 1); + } - 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; + ret = TRUE; + break; - sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), - GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK - | GDK_POINTER_MOTION_HINT_MASK, nullptr, - event->button.time); + 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, + nullptr, event->button.time); + + ret = TRUE; + } else { + sp_event_root_menu_popup(desktop, nullptr, event); + } + break; - ret = TRUE; - } else { - sp_event_root_menu_popup(desktop, nullptr, event); + default: + break; } 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, nullptr, - 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)); - ret = TRUE; - } else { - // To fix https://bugs.launchpad.net/inkscape/+bug/1458200 - // we increase the tolerance because no sensible data for panning - if (within_tolerance && (abs((gint) event->motion.x - xp) - < tolerance * 3) && (abs((gint) event->motion.y - yp) - < tolerance * 3)) { - // do not drag if we're within tolerance from origin - 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, + nullptr, event->motion.time - 1); } - // 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 ((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)); + ret = TRUE; + } else { + // To fix https://bugs.launchpad.net/inkscape/+bug/1458200 + // we increase the tolerance because no sensible data for panning + if (within_tolerance && (abs((gint)event->motion.x - xp) < tolerance * 3) && + (abs((gint)event->motion.y - yp) < tolerance * 3)) { + // do not drag if we're within tolerance from origin + break; + } - // 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)); + // 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 (panning_cursor == 0) { - panning_cursor = 1; - this->sp_event_context_set_cursor(GDK_FLEUR); - } + // 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)); - Geom::Point const motion_w(event->motion.x, event->motion.y); - Geom::Point const moved_w(motion_w - button_w); - this->desktop->scroll_relative(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 - } + if (panning_cursor == 0) { + panning_cursor = 1; + this->sp_event_context_set_cursor(GDK_FLEUR); + } - // 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 moved_w(motion_w - button_w); + this->desktop->scroll_relative(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 (Inkscape::Rubberband::get(desktop)->is_started()) { - Inkscape::Rubberband::get(desktop)->move(motion_dt); - } else { - Inkscape::Rubberband::get(desktop)->start(desktop, motion_dt); - } + 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 + } - if (zoom_rb == 2) { - gobble_motion_events(GDK_BUTTON2_MASK); - } - } - 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; - case GDK_BUTTON_RELEASE: + if (Inkscape::Rubberband::get(desktop)->is_started()) { + Inkscape::Rubberband::get(desktop)->move(motion_dt); + } else { + Inkscape::Rubberband::get(desktop)->start(desktop, motion_dt); + } - xp = yp = 0; + if (zoom_rb == 2) { + gobble_motion_events(GDK_BUTTON2_MASK); + } + } + break; - if (panning_cursor == 1) { - panning_cursor = 0; - desktop->getCanvas()->get_window()->set_cursor(cursor); - } + case GDK_BUTTON_RELEASE: - if (within_tolerance && (panning || zoom_rb)) { - zoom_rb = 0; + xp = yp = 0; - if (panning) { - panning = 0; - sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); + if (panning_cursor == 1) { + panning_cursor = 0; + desktop->getCanvas()->get_window()->set_cursor(cursor); } - Geom::Point const event_w(event->button.x, event->button.y); - Geom::Point const event_dt(desktop->w2d(event_w)); + if (within_tolerance && (panning || zoom_rb)) { + zoom_rb = 0; - 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)); + if (panning) { + panning = 0; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); + } - // 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); + Geom::Point const event_w(event->button.x, event->button.y); + Geom::Point const event_dt(desktop->w2d(event_w)); - this->desktop->scroll_relative(moved_w); - desktop->updateNow(); - ret = TRUE; - } else if (zoom_rb == event->button.button) { - zoom_rb = 0; + double const zoom_inc = prefs->getDoubleLimited("/options/zoomincrement/value", M_SQRT2, 1.01, 10); - Geom::OptRect const b = Inkscape::Rubberband::get(desktop)->getRectangle(); - Inkscape::Rubberband::get(desktop)->stop(); + desktop->zoom_relative_keep_point(event_dt, + (event->button.state & GDK_SHIFT_MASK) ? 1 / zoom_inc : zoom_inc); - if (b && !within_tolerance) { - desktop->set_display_area(*b, 10); - } + desktop->updateNow(); + ret = TRUE; + } else if (panning == event->button.button) { + panning = 0; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); - 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_latin_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 = sp_shortcut_get_for_event((GdkEventKey*)event); - ret = sp_shortcut_invoke(shortcut, desktop); - break; + // 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); - case GDK_KEY_Q: - case GDK_KEY_q: - if (desktop->quick_zoomed()) { + this->desktop->scroll_relative(moved_w); + desktop->updateNow(); ret = TRUE; - } - if (!MOD__SHIFT(event) && !MOD__CTRL(event) && !MOD__ALT(event)) { - desktop->zoom_quick(true); - ret = TRUE; - } - break; + } else if (zoom_rb == event->button.button) { + zoom_rb = 0; - case GDK_KEY_W: - case GDK_KEY_w: - case GDK_KEY_F4: - /* Close view */ - if (MOD__CTRL_ONLY(event)) { - sp_ui_close_view(nullptr); - ret = TRUE; - } - break; + Geom::OptRect const b = Inkscape::Rubberband::get(desktop)->getRectangle(); + Inkscape::Rubberband::get(desktop)->stop(); - 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)); + if (b && !within_tolerance) { + desktop->set_display_area(*b, 10); + } - gobble_key_events(get_latin_keyval(&event->key), GDK_CONTROL_MASK); - this->desktop->scroll_relative(Geom::Point(i, 0)); ret = TRUE; - } else { - ret = _keyboardMove(event->key, Geom::Point(-1, 0)); } 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)); + 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_latin_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 = sp_shortcut_get_for_event((GdkEventKey *)event); + ret = sp_shortcut_invoke(shortcut, desktop); + break; - gobble_key_events(get_latin_keyval(&event->key), GDK_CONTROL_MASK); - this->desktop->scroll_relative(Geom::Point(0, i)); - ret = TRUE; - } else { - ret = _keyboardMove(event->key, Geom::Point(0, -desktop->yaxisdir())); - } - 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_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)); + case GDK_KEY_W: + case GDK_KEY_w: + case GDK_KEY_F4: + /* Close view */ + if (MOD__CTRL_ONLY(event)) { + sp_ui_close_view(nullptr); + ret = TRUE; + } + break; - gobble_key_events(get_latin_keyval(&event->key), GDK_CONTROL_MASK); - this->desktop->scroll_relative(Geom::Point(-i, 0)); - ret = TRUE; - } else { - ret = _keyboardMove(event->key, Geom::Point(1, 0)); - } - 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)); + + gobble_key_events(get_latin_keyval(&event->key), GDK_CONTROL_MASK); + this->desktop->scroll_relative(Geom::Point(i, 0)); + ret = TRUE; + } else { + ret = _keyboardMove(event->key, Geom::Point(-1, 0)); + } + 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)); + 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)); + + gobble_key_events(get_latin_keyval(&event->key), GDK_CONTROL_MASK); + this->desktop->scroll_relative(Geom::Point(0, i)); + ret = TRUE; + } else { + ret = _keyboardMove(event->key, Geom::Point(0, -desktop->yaxisdir())); + } + break; - gobble_key_events(get_latin_keyval(&event->key), GDK_CONTROL_MASK); - this->desktop->scroll_relative(Geom::Point(0, -i)); - ret = TRUE; - } else { - ret = _keyboardMove(event->key, Geom::Point(0, desktop->yaxisdir())); - } - 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)); + + gobble_key_events(get_latin_keyval(&event->key), GDK_CONTROL_MASK); + this->desktop->scroll_relative(Geom::Point(-i, 0)); + ret = TRUE; + } else { + ret = _keyboardMove(event->key, Geom::Point(1, 0)); + } + break; - case GDK_KEY_Menu: - sp_event_root_menu_popup(desktop, nullptr, event); - 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)); + + gobble_key_events(get_latin_keyval(&event->key), GDK_CONTROL_MASK); + this->desktop->scroll_relative(Geom::Point(0, -i)); + ret = TRUE; + } else { + ret = _keyboardMove(event->key, Geom::Point(0, desktop->yaxisdir())); + } + break; - case GDK_KEY_F10: - if (MOD__SHIFT_ONLY(event)) { - sp_event_root_menu_popup(desktop, nullptr, event); - ret = TRUE; - } - break; + case GDK_KEY_Menu: + sp_event_root_menu_popup(desktop, nullptr, event); + ret = TRUE; + break; - case GDK_KEY_space: - within_tolerance = true; - xp = yp = 0; - if (!allow_panning) break; - panning = 4; - this->space_panning = true; - this->message_context->set(Inkscape::INFORMATION_MESSAGE, - _("<b>Space+mouse move</b> to pan canvas")); + case GDK_KEY_F10: + if (MOD__SHIFT_ONLY(event)) { + sp_event_root_menu_popup(desktop, nullptr, event); + ret = TRUE; + } + break; - ret = TRUE; - break; + case GDK_KEY_space: + within_tolerance = true; + xp = yp = 0; + if (!allow_panning) + break; + 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; + case GDK_KEY_z: + case GDK_KEY_Z: + if (MOD__ALT_ONLY(event)) { + desktop->zoom_grab_focus(); + ret = TRUE; + } + break; + + default: + break; } - break; + } break; - default: - break; + case GDK_KEY_RELEASE: + // Stop panning on any key release + if (this->space_panning) { + this->space_panning = false; + this->message_context->clear(); } - } - 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; - if (panning) { - panning = 0; - xp = yp = 0; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); - sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate)); + desktop->updateNow(); + } - desktop->updateNow(); - } + if (panning_cursor == 1) { + panning_cursor = 0; + desktop->getCanvas()->get_window()->set_cursor(cursor); + } - if (panning_cursor == 1) { - panning_cursor = 0; - desktop->getCanvas()->get_window()->set_cursor(cursor); - } + switch (get_latin_keyval(&event->key)) { + case GDK_KEY_space: + if (within_tolerance) { + // Space was pressed, but not panned + sp_toggle_selector(desktop); - switch (get_latin_keyval(&event->key)) { - case GDK_KEY_space: - if (within_tolerance) { - // 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; + } - // Be careful, sp_toggle_selector will delete ourselves. - // Thus, make sure we return immediately. - return true; - } + break; - break; + case GDK_KEY_Q: + case GDK_KEY_q: + if (desktop->quick_zoomed()) { + desktop->zoom_quick(false); + ret = TRUE; + } + break; - case GDK_KEY_Q: - case GDK_KEY_q: - if (desktop->quick_zoomed()) { - desktop->zoom_quick(false); - ret = TRUE; + default: + break; } break; - default: - break; - } - break; - - case GDK_SCROLL: { - bool ctrl = (event->scroll.state & GDK_CONTROL_MASK); - bool shift = (event->scroll.state & GDK_SHIFT_MASK); - bool wheelzooms = prefs->getBool("/options/wheelzooms/value"); + case GDK_SCROLL: { + bool ctrl = (event->scroll.state & GDK_CONTROL_MASK); + bool shift = (event->scroll.state & GDK_SHIFT_MASK); + bool wheelzooms = prefs->getBool("/options/wheelzooms/value"); - int constexpr WHEEL_SCROLL_DEFAULT = 40; - int const wheel_scroll = prefs->getIntLimited( - "/options/wheelscroll/value", WHEEL_SCROLL_DEFAULT, 0, 1000); + int constexpr WHEEL_SCROLL_DEFAULT = 40; + int const wheel_scroll = prefs->getIntLimited("/options/wheelscroll/value", WHEEL_SCROLL_DEFAULT, 0, 1000); - // Size of smooth-scrolls (only used in GTK+ 3) - gdouble delta_x = 0; - gdouble delta_y = 0; + // Size of smooth-scrolls (only used in GTK+ 3) + gdouble delta_x = 0; + gdouble delta_y = 0; - if ((ctrl & shift) && !desktop->get_rotation_lock()) { - /* ctrl + shift, rotate */ + if ((ctrl & shift) && !desktop->get_rotation_lock()) { + /* ctrl + shift, rotate */ - double rotate_inc = prefs->getDoubleLimited( - "/options/rotateincrement/value", 15, 1, 90, "°" ); - rotate_inc *= M_PI/180.0; + double rotate_inc = prefs->getDoubleLimited("/options/rotateincrement/value", 15, 1, 90, "°"); + rotate_inc *= M_PI / 180.0; - switch (event->scroll.direction) { - case GDK_SCROLL_UP: - // Do nothing - break; + switch (event->scroll.direction) { + case GDK_SCROLL_UP: + // Do nothing + break; - case GDK_SCROLL_DOWN: - rotate_inc = -rotate_inc; - break; + case GDK_SCROLL_DOWN: + rotate_inc = -rotate_inc; + break; - case GDK_SCROLL_SMOOTH: { - gdk_event_get_scroll_deltas(event, &delta_x, &delta_y); + case GDK_SCROLL_SMOOTH: { + gdk_event_get_scroll_deltas(event, &delta_x, &delta_y); #ifdef GDK_WINDOWING_QUARTZ - // MacBook trackpad scroll event gives pixel delta - delta_y /= WHEEL_SCROLL_DEFAULT; + // MacBook trackpad scroll event gives pixel delta + delta_y /= WHEEL_SCROLL_DEFAULT; #endif - double delta_y_clamped = CLAMP(delta_y, -1.0, 1.0); // values > 1 result in excessive rotating - rotate_inc = rotate_inc * -delta_y_clamped; - break; - } + double delta_y_clamped = CLAMP(delta_y, -1.0, 1.0); // values > 1 result in excessive rotating + rotate_inc = rotate_inc * -delta_y_clamped; + break; + } - default: - rotate_inc = 0.0; - break; - } + default: + rotate_inc = 0.0; + break; + } - if (rotate_inc != 0.0) { - Geom::Point const scroll_dt = desktop->point(); - desktop->rotate_relative_keep_point(scroll_dt, rotate_inc); - } + if (rotate_inc != 0.0) { + Geom::Point const scroll_dt = desktop->point(); + desktop->rotate_relative_keep_point(scroll_dt, rotate_inc); + } - } else if (shift && !ctrl) { - /* shift + wheel, pan left--right */ + } else if (shift && !ctrl) { + /* shift + wheel, pan left--right */ - switch (event->scroll.direction) { - case GDK_SCROLL_UP: - case GDK_SCROLL_LEFT: - desktop->scroll_relative(Geom::Point(wheel_scroll, 0)); - break; + switch (event->scroll.direction) { + case GDK_SCROLL_UP: + case GDK_SCROLL_LEFT: + desktop->scroll_relative(Geom::Point(wheel_scroll, 0)); + break; - case GDK_SCROLL_DOWN: - case GDK_SCROLL_RIGHT: - desktop->scroll_relative(Geom::Point(-wheel_scroll, 0)); - break; + case GDK_SCROLL_DOWN: + case GDK_SCROLL_RIGHT: + desktop->scroll_relative(Geom::Point(-wheel_scroll, 0)); + break; - case GDK_SCROLL_SMOOTH: { - gdk_event_get_scroll_deltas(event, &delta_x, &delta_y); + case GDK_SCROLL_SMOOTH: { + gdk_event_get_scroll_deltas(event, &delta_x, &delta_y); #ifdef GDK_WINDOWING_QUARTZ - // MacBook trackpad scroll event gives pixel delta - delta_y /= WHEEL_SCROLL_DEFAULT; + // MacBook trackpad scroll event gives pixel delta + delta_y /= WHEEL_SCROLL_DEFAULT; #endif - desktop->scroll_relative(Geom::Point(wheel_scroll * -delta_y, 0)); - break; - } + desktop->scroll_relative(Geom::Point(wheel_scroll * -delta_y, 0)); + break; + } - default: - break; - } + default: + break; + } - } else if ((ctrl && !wheelzooms) || (!ctrl && wheelzooms)) { - /* ctrl + wheel, zoom in--out */ - double rel_zoom; - double const zoom_inc = prefs->getDoubleLimited( - "/options/zoomincrement/value", M_SQRT2, 1.01, 10); + } else if ((ctrl && !wheelzooms) || (!ctrl && wheelzooms)) { + /* ctrl + wheel, zoom in--out */ + 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; + switch (event->scroll.direction) { + case GDK_SCROLL_UP: + rel_zoom = zoom_inc; + break; - case GDK_SCROLL_DOWN: - rel_zoom = 1 / zoom_inc; - break; + case GDK_SCROLL_DOWN: + rel_zoom = 1 / zoom_inc; + break; - case GDK_SCROLL_SMOOTH: { - gdk_event_get_scroll_deltas(event, &delta_x, &delta_y); + case GDK_SCROLL_SMOOTH: { + gdk_event_get_scroll_deltas(event, &delta_x, &delta_y); #ifdef GDK_WINDOWING_QUARTZ - // MacBook trackpad scroll event gives pixel delta - delta_y /= WHEEL_SCROLL_DEFAULT; + // MacBook trackpad scroll event gives pixel delta + delta_y /= WHEEL_SCROLL_DEFAULT; #endif - double delta_y_clamped = CLAMP(std::abs(delta_y), 0.0, 1.0); // values > 1 result in excessive zooming - double zoom_inc_scaled = (zoom_inc-1) * delta_y_clamped + 1; - if (delta_y < 0) { - rel_zoom = zoom_inc_scaled; - } else { - rel_zoom = 1 / zoom_inc_scaled; - } - break; - } + double delta_y_clamped = + CLAMP(std::abs(delta_y), 0.0, 1.0); // values > 1 result in excessive zooming + double zoom_inc_scaled = (zoom_inc - 1) * delta_y_clamped + 1; + if (delta_y < 0) { + rel_zoom = zoom_inc_scaled; + } else { + rel_zoom = 1 / zoom_inc_scaled; + } + break; + } - default: - rel_zoom = 0.0; - 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); - } + 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_relative(Geom::Point(0, wheel_scroll)); - break; + /* no modifier, pan up--down (left--right on multiwheel mice?) */ + } else { + switch (event->scroll.direction) { + case GDK_SCROLL_UP: + desktop->scroll_relative(Geom::Point(0, wheel_scroll)); + break; - case GDK_SCROLL_DOWN: - desktop->scroll_relative(Geom::Point(0, -wheel_scroll)); - break; + case GDK_SCROLL_DOWN: + desktop->scroll_relative(Geom::Point(0, -wheel_scroll)); + break; - case GDK_SCROLL_LEFT: - desktop->scroll_relative(Geom::Point(wheel_scroll, 0)); - break; + case GDK_SCROLL_LEFT: + desktop->scroll_relative(Geom::Point(wheel_scroll, 0)); + break; - case GDK_SCROLL_RIGHT: - desktop->scroll_relative(Geom::Point(-wheel_scroll, 0)); - break; + case GDK_SCROLL_RIGHT: + desktop->scroll_relative(Geom::Point(-wheel_scroll, 0)); + break; - case GDK_SCROLL_SMOOTH: - gdk_event_get_scroll_deltas(event, &delta_x, &delta_y); + case GDK_SCROLL_SMOOTH: + gdk_event_get_scroll_deltas(event, &delta_x, &delta_y); #ifdef GDK_WINDOWING_QUARTZ - // MacBook trackpad scroll event gives pixel delta - delta_x /= WHEEL_SCROLL_DEFAULT; - delta_y /= WHEEL_SCROLL_DEFAULT; + // MacBook trackpad scroll event gives pixel delta + delta_x /= WHEEL_SCROLL_DEFAULT; + delta_y /= WHEEL_SCROLL_DEFAULT; #endif - desktop->scroll_relative(Geom::Point(-wheel_scroll*delta_x, -wheel_scroll*delta_y)); - break; + desktop->scroll_relative(Geom::Point(-wheel_scroll * delta_x, -wheel_scroll * delta_y)); + break; + } } + break; } - break; - } - default: - break; + default: + break; } return ret; @@ -967,20 +952,21 @@ bool ToolBase::block_button(GdkEvent *event) * 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) { +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; + 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; + default: + break; } return ret; @@ -989,7 +975,8 @@ bool ToolBase::item_handler(SPItem* item, GdkEvent* event) { /** * 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 { +bool ToolBase::sp_event_context_knot_mouseover() const +{ if (this->shape_editor) { return this->shape_editor->knot_mouseover(); } @@ -1000,7 +987,8 @@ bool ToolBase::sp_event_context_knot_mouseover() const { /** * Enables/disables the ToolBase's SelCue. */ -void ToolBase::enableSelectionCue(bool enable) { +void ToolBase::enableSelectionCue(bool enable) +{ if (enable) { if (!_selcue) { _selcue = new Inkscape::SelCue(desktop); @@ -1014,7 +1002,8 @@ void ToolBase::enableSelectionCue(bool enable) { /** * Enables/disables the ToolBase's GrDrag. */ -void ToolBase::enableGrDrag(bool enable) { +void ToolBase::enableGrDrag(bool enable) +{ if (enable) { if (!_grdrag) { _grdrag = new GrDrag(desktop); @@ -1030,8 +1019,8 @@ void ToolBase::enableGrDrag(bool enable) { /** * Delete a selected GrDrag point */ -bool ToolBase::deleteSelectedDrag(bool just_one) { - +bool ToolBase::deleteSelectedDrag(bool just_one) +{ if (_grdrag && !_grdrag->selected.empty()) { _grdrag->deleteSelected(just_one); return TRUE; @@ -1041,15 +1030,16 @@ bool ToolBase::deleteSelectedDrag(bool just_one) { } /** Enable (or disable) high precision for motion events - * - * This is intended to be used by drawing tools, that need to process motion events with high accuracy - * and high update rate (for example free hand tools) - * - * With standard accuracy some intermediate motion events might be discarded - * - * Call this function when an operation that requires high accuracy is started (e.g. mouse button is pressed - * to draw a line). Make sure to call it again and restore standard precision afterwards. **/ -void ToolBase::set_high_motion_precision(bool high_precision) { + * + * This is intended to be used by drawing tools, that need to process motion events with high accuracy + * and high update rate (for example free hand tools) + * + * With standard accuracy some intermediate motion events might be discarded + * + * Call this function when an operation that requires high accuracy is started (e.g. mouse button is pressed + * to draw a line). Make sure to call it again and restore standard precision afterwards. **/ +void ToolBase::set_high_motion_precision(bool high_precision) +{ Glib::RefPtr<Gdk::Window> window = desktop->getToplevel()->get_window(); if (window) { @@ -1061,28 +1051,25 @@ void ToolBase::set_high_motion_precision(bool high_precision) { * Force canvas to fully update after interruptions. * Convenience function that just passes request to canvas. */ -void -ToolBase::forced_redraws_start(int count, bool reset) +void ToolBase::forced_redraws_start(int count, bool reset) { desktop->canvas->forced_redraws_start(count, reset); } - /** * End force canvas full updates. * Convenience function that just passes request to canvas. */ -void -ToolBase::forced_redraws_stop() +void ToolBase::forced_redraws_stop() { desktop->canvas->forced_redraws_stop(); } - /** * Calls virtual set() function of ToolBase. */ -void sp_event_context_read(ToolBase *ec, gchar const *key) { +void sp_event_context_read(ToolBase *ec, gchar const *key) +{ g_return_if_fail(ec != nullptr); g_return_if_fail(key != nullptr); @@ -1094,50 +1081,46 @@ void sp_event_context_read(ToolBase *ec, gchar const *key) { /** * Calls virtual root_handler(), the main event handling function. */ -gint sp_event_context_root_handler(ToolBase * event_context, - GdkEvent * event) +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, nullptr, nullptr, - (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->getDesktop()->namedview->snap_manager.snapprefs.setSnapPostponedGlobally(false); - break; - default: - break; + case GDK_MOTION_NOTIFY: + sp_event_context_snap_delay_handler(event_context, nullptr, nullptr, (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->getDesktop()->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 sp_event_context_virtual_root_handler(ToolBase *event_context, GdkEvent *event) +{ gint ret = false; if (event_context) { - if (event_context->block_button(event)) { return false; } - SPDesktop* desktop = event_context->getDesktop(); + SPDesktop *desktop = event_context->getDesktop(); ret = event_context->root_handler(event); set_event_location(desktop, event); @@ -1149,41 +1132,42 @@ gint sp_event_context_virtual_root_handler(ToolBase * event_context, GdkEvent * /** * Calls virtual item_handler(), the item event handling function. */ -gint sp_event_context_item_handler(ToolBase * event_context, - SPItem * item, GdkEvent * event) +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, nullptr, (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->getDesktop()->namedview->snap_manager.snapprefs.setSnapPostponedGlobally(false); - break; - default: - break; + case GDK_MOTION_NOTIFY: + sp_event_context_snap_delay_handler(event_context, (gpointer)item, nullptr, (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->getDesktop()->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 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) + 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) if (event_context->block_button(event)) { return false; } @@ -1203,7 +1187,8 @@ gint sp_event_context_virtual_item_handler(ToolBase * event_context, SPItem * it /** * Shows coordinates on status bar. */ -static void set_event_location(SPDesktop *desktop, GdkEvent *event) { +static void set_event_location(SPDesktop *desktop, GdkEvent *event) +{ if (event->type != GDK_MOTION_NOTIFY) { return; } @@ -1217,19 +1202,18 @@ static void set_event_location(SPDesktop *desktop, GdkEvent *event) { /** * Create popup menu and tell Gtk to show it. */ -void sp_event_root_menu_popup(SPDesktop *desktop, SPItem *item, GdkEvent *event) { - +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); + item = sp_event_context_find_item(desktop, Geom::Point(event->button.x, event->button.y), FALSE, FALSE); if (event->type == GDK_KEY_PRESS && !desktop->getSelection()->isEmpty()) { item = desktop->getSelection()->items().front(); } - ContextMenu* CM = new ContextMenu(desktop, item); + ContextMenu *CM = new ContextMenu(desktop, item); Gtk::Window *window = desktop->getToplevel(); if (window) { if (window->get_style_context()->has_class("dark")) { @@ -1246,35 +1230,31 @@ void sp_event_root_menu_popup(SPDesktop *desktop, SPItem *item, GdkEvent *event) } CM->show(); - switch (event->type) { - case GDK_BUTTON_PRESS: - case GDK_KEY_PRESS: - CM->popup_at_pointer(event); - break; - default: - break; + case GDK_BUTTON_PRESS: + case GDK_KEY_PRESS: + CM->popup_at_pointer(event); + 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) { +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_latin_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)); + 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 : "")); + 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); @@ -1287,8 +1267,9 @@ void sp_event_show_modifier_tip(Inkscape::MessageContext *message_context, * Try to determine the keys group of Latin layout. * Check available keymap entries for Latin 'a' key and find the minimal integer value. */ -static void update_latin_keys_group() { - GdkKeymapKey* keys; +static void update_latin_keys_group() +{ + GdkKeymapKey *keys; gint n_keys; latin_keys_group_valid = FALSE; @@ -1306,9 +1287,10 @@ static void update_latin_keys_group() { /** * Initialize Latin keys group handling. */ -void init_latin_keys_group() { - g_signal_connect(G_OBJECT(Gdk::Display::get_default()->get_keymap()), - "keys-changed", G_CALLBACK(update_latin_keys_group), NULL); +void init_latin_keys_group() +{ + g_signal_connect(G_OBJECT(Gdk::Display::get_default()->get_keymap()), "keys-changed", + G_CALLBACK(update_latin_keys_group), NULL); update_latin_keys_group(); } @@ -1318,15 +1300,14 @@ void init_latin_keys_group() { * Use this instead of simply event->keyval, so that your keyboard shortcuts * work regardless of layouts (e.g., in Cyrillic). */ -guint get_latin_keyval(GdkEventKey const *event, guint *consumed_modifiers /*= NULL*/) { +guint get_latin_keyval(GdkEventKey const *event, guint *consumed_modifiers /*= NULL*/) +{ guint keyval = 0; GdkModifierType modifiers; gint group = latin_keys_group_valid ? latin_keys_group : event->group; - gdk_keymap_translate_keyboard_state( - Gdk::Display::get_default()->get_keymap(), - event->hardware_keycode, (GdkModifierType) event->state, group, - &keyval, nullptr, nullptr, &modifiers); + gdk_keymap_translate_keyboard_state(Gdk::Display::get_default()->get_keymap(), event->hardware_keycode, + (GdkModifierType)event->state, group, &keyval, nullptr, nullptr, &modifiers); if (consumed_modifiers) { *consumed_modifiers = modifiers; @@ -1345,8 +1326,7 @@ guint get_latin_keyval(GdkEventKey const *event, guint *consumed_modifiers /*= N * 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 *sp_event_context_find_item(SPDesktop *desktop, Geom::Point const &p, bool select_under, bool into_groups) { SPItem *item = nullptr; @@ -1370,21 +1350,19 @@ SPItem *sp_event_context_find_item(SPDesktop *desktop, Geom::Point const &p, * * Honors into_groups. */ -SPItem * -sp_event_context_over_item(SPDesktop *desktop, SPItem *item, - Geom::Point const &p) { - std::vector<SPItem*> temp; +SPItem *sp_event_context_over_item(SPDesktop *desktop, SPItem *item, Geom::Point const &p) +{ + std::vector<SPItem *> temp; temp.push_back(item); SPItem *item_at_point = desktop->getItemFromListAtPointBottom(temp, p); return item_at_point; } -ShapeEditor * -sp_event_context_get_shape_editor(ToolBase *ec) { +ShapeEditor *sp_event_context_get_shape_editor(ToolBase *ec) +{ return ec->shape_editor; } - /** * 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 @@ -1396,9 +1374,8 @@ sp_event_context_get_shape_editor(ToolBase *ec) { * @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) +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; @@ -1407,9 +1384,12 @@ void sp_event_context_snap_delay_handler(ToolBase *ec, 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 + // 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->getDesktop(), TOOLS_CALLIGRAPHIC); // The snap delay will repeat the last motion event, which will lead to @@ -1422,21 +1402,20 @@ void sp_event_context_snap_delay_handler(ToolBase *ec, // 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->getDesktop() && - ec->getDesktop()->namedview->snap_manager.snapprefs.getSnapEnabledGlobally()) { + } else if (ec->getDesktop() && ec->getDesktop()->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->getDesktop()->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); + 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; + // 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. @@ -1444,17 +1423,19 @@ void sp_event_context_snap_delay_handler(ToolBase *ec, // 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 + 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. + // 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 == nullptr) { // 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 + // 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 } @@ -1473,9 +1454,10 @@ void sp_event_context_snap_delay_handler(ToolBase *ec, * 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) { +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); + DelayedSnapEvent *dse = reinterpret_cast<DelayedSnapEvent *>(data); if (dse == nullptr) { // This might occur when this method is called directly, i.e. not through the timer @@ -1503,76 +1485,69 @@ gboolean sp_event_context_snap_watchdog_callback(gpointer data) { // 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(); - check_if_knot_deleted(knot); - 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 = nullptr; - delete dse; - return false; - } - ControlPoint *point = reinterpret_cast<ControlPoint*> (pitem2); - if (point) { - if (point->position().isFinite() && (dt == point->_desktop)) { - point->_eventHandler(ec, dse->getEvent()); + 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()); } - 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::KNOT_HANDLER: { + gpointer knot = dse->getItem2(); + check_if_knot_deleted(knot); + if (knot && SP_IS_KNOT(knot)) { + sp_knot_handler_request_position(dse->getEvent(), SP_KNOT(knot)); } - } - } - 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(); - auto item2 = static_cast<Gtk::Widget *>(dse->getItem2()); - if (item && item2) { - g_assert(GTK_IS_WIDGET(item)); - g_assert(SP_IS_DESKTOP_WIDGET(item2)); - if (dse->getOrigin() == DelayedSnapEvent::GUIDE_HRULER) { - SPDesktopWidget::ruler_event(GTK_WIDGET(item), dse->getEvent(), SP_DESKTOP_WIDGET(item2), true); - } else { - SPDesktopWidget::ruler_event(GTK_WIDGET(item), dse->getEvent(), SP_DESKTOP_WIDGET(item2), false); + } break; + case DelayedSnapEvent::CONTROL_POINT_HANDLER: { + using Inkscape::UI::ControlPoint; + gpointer pitem2 = dse->getItem2(); + if (!pitem2) { + ec->_delayed_snap_event = nullptr; + delete dse; + return false; } - } - } - break; - default: - g_warning("Origin of snap-delay event has not been defined!;"); - break; + 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(); + auto item2 = static_cast<Gtk::Widget *>(dse->getItem2()); + if (item && item2) { + g_assert(GTK_IS_WIDGET(item)); + g_assert(SP_IS_DESKTOP_WIDGET(item2)); + if (dse->getOrigin() == DelayedSnapEvent::GUIDE_HRULER) { + SPDesktopWidget::ruler_event(GTK_WIDGET(item), dse->getEvent(), SP_DESKTOP_WIDGET(item2), true); + } else { + SPDesktopWidget::ruler_event(GTK_WIDGET(item), dse->getEvent(), SP_DESKTOP_WIDGET(item2), false); + } + } + } break; + default: + g_warning("Origin of snap-delay event has not been defined!;"); + break; } ec->_delayed_snap_event = nullptr; @@ -1580,18 +1555,19 @@ gboolean sp_event_context_snap_watchdog_callback(gpointer data) { ec->_dse_callback_in_process = false; - return FALSE; //Kills the timer and stops it from executing this callback over and over again. + 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) { +void sp_event_context_discard_delayed_snap_event(ToolBase *ec) +{ delete ec->_delayed_snap_event; ec->_delayed_snap_event = nullptr; ec->getDesktop()->namedview->snap_manager.snapprefs.setSnapPostponedGlobally(false); } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/tool-base.h b/src/ui/tools/tool-base.h index dd447b5e266c39f692f7a2c7acd9189be1558b40..f4565bf75a80ff9cbc52fd365401b50ba86eb56d 100644 --- a/src/ui/tools/tool-base.h +++ b/src/ui/tools/tool-base.h @@ -13,17 +13,17 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstddef> -#include <string> -#include <memory> -#include "knot.h" -#include "knotholder.h" #include <2geom/point.h> +#include <cstddef> #include <gdk/gdk.h> #include <gdkmm/cursor.h> #include <glib-object.h> +#include <memory> #include <sigc++/trackable.h> +#include <string> +#include "knot.h" +#include "knotholder.h" #include "preferences.h" class GrDrag; @@ -31,9 +31,9 @@ class SPDesktop; class SPItem; class KnotHolder; namespace Inkscape { - class MessageContext; - class SelCue; -} +class MessageContext; +class SelCue; +} // namespace Inkscape namespace Inkscape { namespace UI { @@ -47,9 +47,11 @@ class ToolBase; gboolean sp_event_context_snap_watchdog_callback(gpointer data); void sp_event_context_discard_delayed_snap_event(ToolBase *ec); -class DelayedSnapEvent { +class DelayedSnapEvent +{ public: - enum DelayedSnapEventOrigin { + enum DelayedSnapEventOrigin + { UNDEFINED_HANDLER = 0, EVENTCONTEXT_ROOT_HANDLER, EVENTCONTEXT_ITEM_HANDLER, @@ -60,7 +62,8 @@ public: GUIDE_VRULER }; - DelayedSnapEvent(ToolBase *event_context, gpointer const dse_item, gpointer dse_item2, GdkEventMotion const *event, DelayedSnapEvent::DelayedSnapEventOrigin const origin) + DelayedSnapEvent(ToolBase *event_context, gpointer const dse_item, gpointer dse_item2, GdkEventMotion const *event, + DelayedSnapEvent::DelayedSnapEventOrigin const origin) : _timer_id(0) , _event(nullptr) , _item(dse_item) @@ -76,48 +79,41 @@ public: value = value / 1000.0; // now convert this value to seconds } - _timer_id = g_timeout_add(value*1000.0, &sp_event_context_snap_watchdog_callback, this); - _event = gdk_event_copy((GdkEvent*) event); + _timer_id = g_timeout_add(value * 1000.0, &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 != nullptr) gdk_event_free(_event); // Remove the copy of the original event + ~DelayedSnapEvent() + { + if (_timer_id > 0) + g_source_remove(_timer_id); // Kill the watchdog + if (_event != nullptr) + gdk_event_free(_event); // Remove the copy of the original event } - ToolBase* getEventContext() { - return _event_context; - } + ToolBase *getEventContext() { return _event_context; } - DelayedSnapEventOrigin getOrigin() { - return _origin; - } + DelayedSnapEventOrigin getOrigin() { return _origin; } - GdkEvent* getEvent() { - return _event; - } + GdkEvent *getEvent() { return _event; } - gpointer getItem() { - return _item; - } + gpointer getItem() { return _item; } - gpointer getItem2() { - return _item2; - } + gpointer getItem2() { return _item2; } private: guint _timer_id; - GdkEvent* _event; + GdkEvent *_event; gpointer _item; gpointer _item2; DelayedSnapEventOrigin _origin; - ToolBase* _event_context; + 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); - +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. @@ -135,63 +131,58 @@ void sp_event_context_snap_delay_handler(ToolBase *ec, gpointer const dse_item, class ToolBase : public sigc::trackable { public: - ToolBase(gchar const *const *cursor_shape, bool uses_snap=true); + ToolBase(gchar const *const *cursor_shape, bool uses_snap = true); virtual ~ToolBase(); - ToolBase(const ToolBase&) = delete; - ToolBase& operator=(const ToolBase&) = delete; + ToolBase(const ToolBase &) = delete; + ToolBase &operator=(const ToolBase &) = delete; virtual void setup(); virtual void finish(); - virtual void set(const Inkscape::Preferences::Entry& val); + virtual void set(const Inkscape::Preferences::Entry &val); virtual bool root_handler(GdkEvent *event); virtual bool item_handler(SPItem *item, GdkEvent *event); bool block_button(GdkEvent *event); - virtual const std::string& getPrefsPath() = 0; - void enableSelectionCue (bool enable=true); - void enableGrDrag (bool enable=true); + virtual const std::string &getPrefsPath() = 0; + void enableSelectionCue(bool enable = true); + void enableGrDrag(bool enable = true); bool deleteSelectedDrag(bool just_one); - Inkscape::MessageContext *defaultMessageContext() const { - return message_context.get(); - } + Inkscape::MessageContext *defaultMessageContext() const { return message_context.get(); } - GrDrag *get_drag () { return _grdrag; } + GrDrag *get_drag() { return _grdrag; } void setDesktop(SPDesktop *desktop_in) { desktop = desktop_in; } SPDesktop *getDesktop() { return desktop; } - /** * An observer that relays pref changes to the derived classes. */ - class ToolPrefObserver: public Inkscape::Preferences::Observer { + class ToolPrefObserver : public Inkscape::Preferences::Observer + { public: ToolPrefObserver(Glib::ustring const &path, ToolBase *ec) : Inkscape::Preferences::Observer(path) , ec(ec) - { - } + {} - void notify(Inkscape::Preferences::Entry const &val) override { - ec->set(val); - } + void notify(Inkscape::Preferences::Entry const &val) override { ec->set(val); } private: - ToolBase * const ec; + ToolBase *const ec; }; -// private: + // private: Inkscape::Preferences::Observer *pref_observer = nullptr; Glib::RefPtr<Gdk::Cursor> cursor; - gint xp = 0; ///< where drag started - gint yp = 0; ///< where drag started + gint xp = 0; ///< where drag started + gint yp = 0; ///< where drag started gint tolerance = 0; - bool within_tolerance = false; ///< are we still within tolerance of origin + bool within_tolerance = false; ///< are we still within tolerance of origin bool _button1on = false; bool _button2on = false; bool _button3on = false; @@ -199,21 +190,22 @@ public: ///< be selected if this is a click not drag bool space_panning = false; - bool rotating_mode = false;; + bool rotating_mode = false; + ; std::unique_ptr<Inkscape::MessageContext> message_context; Inkscape::SelCue *_selcue = nullptr; GrDrag *_grdrag = nullptr; - ShapeEditor* shape_editor = nullptr; + ShapeEditor *shape_editor = nullptr; bool _dse_callback_in_process = false; bool _uses_snap = false; DelayedSnapEvent *_delayed_snap_event = nullptr; -// private: + // private: void sp_event_context_update_cursor(); protected: @@ -230,10 +222,8 @@ protected: SPDesktop *desktop = nullptr; private: - bool _keyboardMove(GdkEventKey const &event, Geom::Point const &dir); void sp_event_context_set_cursor(GdkCursorType cursor_type); - }; void sp_event_context_read(ToolBase *ec, gchar const *key); @@ -248,14 +238,14 @@ 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); +void sp_event_show_modifier_tip(Inkscape::MessageContext *message_context, GdkEvent *event, gchar const *ctrl_tip, + gchar const *shift_tip, gchar const *alt_tip); void init_latin_keys_group(); guint get_latin_keyval(GdkEventKey const *event, guint *consumed_modifiers = nullptr); -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); +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); @@ -267,7 +257,6 @@ bool sp_event_context_knot_mouseover(ToolBase *ec); #endif // SEEN_SP_EVENT_CONTEXT_H - /* Local Variables: mode:c++ diff --git a/src/ui/tools/tweak-tool.cpp b/src/ui/tools/tweak-tool.cpp index b791b70d4d531c41baf52e2550bc84b7284eebf3..1d4d4f9efcda2a912796e839dc40d233e6aea5c1 100644 --- a/src/ui/tools/tweak-tool.cpp +++ b/src/ui/tools/tweak-tool.cpp @@ -12,37 +12,30 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <numeric> +#include "ui/tools/tweak-tool.h" -#include <gtk/gtk.h> +#include <2geom/circle.h> #include <gdk/gdkkeysyms.h> #include <glibmm/i18n.h> - -#include <2geom/circle.h> +#include <gtk/gtk.h> +#include <numeric> #include "context-fns.h" #include "desktop-events.h" #include "desktop-style.h" #include "desktop.h" +#include "display/canvas-arena.h" +#include "display/canvas-bpath.h" +#include "display/curve.h" #include "document-undo.h" #include "document.h" #include "filter-chemistry.h" #include "gradient-chemistry.h" -#include "inkscape.h" #include "include/macros.h" -#include "message-context.h" -#include "path-chemistry.h" -#include "selection.h" -#include "style.h" -#include "verbs.h" - -#include "display/canvas-arena.h" -#include "display/curve.h" -#include "display/canvas-bpath.h" - +#include "inkscape.h" #include "livarot/Path.h" #include "livarot/Shape.h" - +#include "message-context.h" #include "object/box3d.h" #include "object/filters/gaussian-blur.h" #include "object/sp-flowtext.h" @@ -53,9 +46,11 @@ #include "object/sp-radial-gradient.h" #include "object/sp-stop.h" #include "object/sp-text.h" - +#include "path-chemistry.h" #include "path/path-util.h" - +#include "selection.h" +#include "style.h" +#include "svg/svg.h" #include "ui/pixmaps/cursor-tweak-attract.xpm" #include "ui/pixmaps/cursor-tweak-color.xpm" #include "ui/pixmaps/cursor-tweak-less.xpm" @@ -73,12 +68,8 @@ #include "ui/pixmaps/cursor-tweak-scale-up.xpm" #include "ui/pixmaps/cursor-tweak-thicken.xpm" #include "ui/pixmaps/cursor-tweak-thin.xpm" - -#include "svg/svg.h" - #include "ui/toolbar/tweak-toolbar.h" - -#include "ui/tools/tweak-tool.h" +#include "verbs.h" using Inkscape::DocumentUndo; @@ -90,8 +81,9 @@ namespace Inkscape { namespace UI { namespace Tools { -const std::string& TweakTool::getPrefsPath() { - return TweakTool::prefsPath; +const std::string &TweakTool::getPrefsPath() +{ + return TweakTool::prefsPath; } const std::string TweakTool::prefsPath = "/tools/tweak"; @@ -114,12 +106,12 @@ TweakTool::TweakTool() , do_s(true) , do_l(true) , do_o(false) -{ -} +{} -TweakTool::~TweakTool() { +TweakTool::~TweakTool() +{ this->enableGrDrag(false); - + this->style_set_connection.disconnect(); if (this->dilate_area) { @@ -128,116 +120,132 @@ TweakTool::~TweakTool() { } } -static bool is_transform_mode (gint mode) +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); + 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) +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) { +void TweakTool::update_cursor(bool with_shift) +{ guint num = 0; gchar *sel_message = nullptr; if (!desktop->selection->isEmpty()) { - num = (guint) boost::distance(desktop->selection->items()); - sel_message = g_strdup_printf(ngettext("<b>%i</b> object selected","<b>%i</b> objects selected",num), num); + num = (guint)boost::distance(desktop->selection->items()); + 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); + 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) { +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)); @@ -249,18 +257,21 @@ bool TweakTool::set_style(const SPCSSAttr* css) { return false; } -void TweakTool::setup() { +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::Path(Geom::Circle(0,0,1)); + /* 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::Path(Geom::Circle(0, 0, 1)); auto c = std::make_unique<SPCurve>(path); dilate_area = sp_canvas_bpath_new(desktop->getControls(), c.get()); - 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_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); } @@ -276,11 +287,11 @@ void TweakTool::setup() { sp_event_context_read(this, "dos"); sp_event_context_read(this, "doo"); - this->style_set_connection = 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) - ); - + this->style_set_connection = + 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(); @@ -290,7 +301,8 @@ void TweakTool::setup() { } } -void TweakTool::set(const Inkscape::Preferences::Entry& val) { +void TweakTool::set(const Inkscape::Preferences::Entry &val) +{ Glib::ustring path = val.getEntryName(); if (path == "width") { @@ -315,43 +327,38 @@ void TweakTool::set(const Inkscape::Preferences::Entry& val) { } } -static void -sp_tweak_extinput(TweakTool *tc, GdkEvent *event) +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); + 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) +static double get_dilate_radius(TweakTool *tc) { // 10 times the pen width: - return 500 * tc->width/tc->getDesktop()->current_zoom(); + return 500 * tc->width / tc->getDesktop()->current_zoom(); } -static double -get_path_force (TweakTool *tc) +static double get_path_force(TweakTool *tc) { - double force = 8 * (tc->usepressure? tc->pressure : TC_DEFAULT_PRESSURE) - /sqrt(tc->getDesktop()->current_zoom()); + double force = 8 * (tc->usepressure ? tc->pressure : TC_DEFAULT_PRESSURE) / sqrt(tc->getDesktop()->current_zoom()); if (force > 3) { force += 4 * (force - 3); } return force * tc->force; } -static double -get_move_force (TweakTool *tc) +static double get_move_force(TweakTool *tc) { - double force = (tc->usepressure? tc->pressure : TC_DEFAULT_PRESSURE); + 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) +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; @@ -365,13 +372,13 @@ sp_tweak_dilate_recursive (Inkscape::Selection *selection, SPItem *item, Geom::P } if (dynamic_cast<SPText *>(item) || dynamic_cast<SPFlowtext *>(item)) { - std::vector<SPItem*> items; + std::vector<SPItem *> items; items.push_back(item); - std::vector<SPItem*> selected; - std::vector<Inkscape::XML::Node*> to_select; + std::vector<SPItem *> selected; + std::vector<Inkscape::XML::Node *> to_select; SPDocument *doc = item->document; - sp_item_list_to_curves (items, selected, to_select); - SPObject* newObj = doc->getObjectByRepr(to_select[0]); + sp_item_list_to_curves(items, selected, to_select); + SPObject *newObj = doc->getObjectByRepr(to_select[0]); item = dynamic_cast<SPItem *>(newObj); g_assert(item != nullptr); selection->add(item); @@ -379,26 +386,26 @@ sp_tweak_dilate_recursive (Inkscape::Selection *selection, SPItem *item, Geom::P if (dynamic_cast<SPGroup *>(item) && !dynamic_cast<SPBox3D *>(item)) { std::vector<SPItem *> children; - for (auto& child: item->children) { + for (auto &child : item->children) { if (dynamic_cast<SPItem *>(&child)) { children.push_back(dynamic_cast<SPItem *>(&child)); } } - for (auto i = children.rbegin(); i!= children.rend(); ++i) { - SPItem *child = *i; + for (auto i = children.rbegin(); i != children.rend(); ++i) { + SPItem *child = *i; g_assert(child != nullptr); - if (sp_tweak_dilate_recursive (selection, child, p, vector, mode, radius, force, fidelity, reverse)) { + if (sp_tweak_dilate_recursive(selection, child, p, vector, mode, radius, force, fidelity, reverse)) { did = true; } } } 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; + 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; item->move_rel(Geom::Translate(move * selection->desktop()->doc2dt().withoutTranslation())); @@ -407,55 +414,55 @@ sp_tweak_dilate_recursive (Inkscape::Selection *selection, SPItem *item, Geom::P } } 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; + 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())); + Geom::Point move = + force * 0.5 * (cos(M_PI * x) + 1) * (reverse ? (a->midpoint() - p) : (p - a->midpoint())); item->move_rel(Geom::Translate(move * selection->desktop()->doc2dt().withoutTranslation())); 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 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; + 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); + Geom::Point move = force * 0.5 * (cos(M_PI * x) + 1) * Geom::Point(cos(dp) * dr, sin(dp) * dr); item->move_rel(Geom::Translate(move * selection->desktop()->doc2dt().withoutTranslation())); 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; + 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); + double scale = 1 + (reverse ? force : -force) * 0.05 * (cos(M_PI * x) + 1); item->scale_rel(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; + 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; + double angle = (reverse ? force : -force) * 0.05 * (cos(M_PI * x) + 1) * M_PI; angle *= -selection->desktop()->yaxisdir(); item->rotate_rel(Geom::Rotate(angle)); did = true; @@ -463,11 +470,11 @@ sp_tweak_dilate_recursive (Inkscape::Selection *selection, SPItem *item, Geom::P } } 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; + 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); @@ -476,7 +483,7 @@ sp_tweak_dilate_recursive (Inkscape::Selection *selection, SPItem *item, Geom::P item->deleteObject(true, true); } else { // duplicate SPDocument *doc = item->document; - Inkscape::XML::Document* xml_doc = doc->getReprDoc(); + 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(); @@ -494,7 +501,6 @@ sp_tweak_dilate_recursive (Inkscape::Selection *selection, SPItem *item, Geom::P } } else if (dynamic_cast<SPPath *>(item) || dynamic_cast<SPShape *>(item)) { - Inkscape::XML::Node *newrepr = nullptr; gint pos = 0; Inkscape::XML::Node *parent = nullptr; @@ -548,33 +554,26 @@ sp_tweak_dilate_recursive (Inkscape::Selection *selection, SPItem *item, Geom::P } if (Geom::L2(vector) != 0) { - vector = 1/Geom::L2(vector) * vector; + 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 + 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) + 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) + 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) + if (theShape->MakeTweak(tweak_mode_roughen, theRes, force, join_straight, 4.0, true, p, + Geom::Point(0, 0), radius, &i2doc) == 0) did_this = true; } @@ -585,8 +584,8 @@ sp_tweak_dilate_recursive (Inkscape::Selection *selection, SPItem *item, Geom::P res->Reset(); theRes->ConvertToForme(res); - double th_max = (0.6 - 0.59*sqrt(fidelity)) / i2doc.descrim(); - double threshold = MAX(th_max, th_max*force); + 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())); @@ -641,22 +640,20 @@ sp_tweak_dilate_recursive (Inkscape::Selection *selection, SPItem *item, Geom::P did = true; } } - } return did; } - static void -tweak_colorpaint (float *color, guint32 goal, double force, bool do_h, bool do_s, bool do_l) +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]; - SPColor::rgb_to_hsl_floatv (hsl_g, SP_RGBA32_R_F(goal), SP_RGBA32_G_F(goal), SP_RGBA32_B_F(goal)); + SPColor::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]; - SPColor::rgb_to_hsl_floatv (hsl_c, color[0], color[1], color[2]); + SPColor::rgb_to_hsl_floatv(hsl_c, color[0], color[1], color[2]); if (!do_h) { hsl_g[0] = hsl_c[0]; } @@ -666,7 +663,7 @@ tweak_colorpaint (float *color, guint32 goal, double force, bool do_h, bool do_s if (!do_l) { hsl_g[2] = hsl_c[2]; } - SPColor::hsl_to_rgb_floatv (rgb_g, hsl_g[0], hsl_g[1], hsl_g[2]); + SPColor::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); @@ -679,11 +676,10 @@ tweak_colorpaint (float *color, guint32 goal, double force, bool do_h, bool do_s } } - static void -tweak_colorjitter (float *color, double force, bool do_h, bool do_s, bool do_l) +static void tweak_colorjitter(float *color, double force, bool do_h, bool do_s, bool do_l) { float hsl_c[3]; - SPColor::rgb_to_hsl_floatv (hsl_c, color[0], color[1], color[2]); + SPColor::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; @@ -701,23 +697,21 @@ tweak_colorjitter (float *color, double force, bool do_h, bool do_s, bool do_l) hsl_c[2] += g_random_double_range(-hsl_c[2], 1 - hsl_c[2]) * force; } - SPColor::hsl_to_rgb_floatv (color, hsl_c[0], hsl_c[1], hsl_c[2]); + SPColor::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) +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); + 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); + tweak_colorjitter(color, force, do_h, do_s, do_l); } } - static void -tweak_opacity (guint mode, SPIScale24 *style_opacity, double opacity_goal, double force) +static void tweak_opacity(guint mode, SPIScale24 *style_opacity, double opacity_goal, double force) { - double opacity = SP_SCALE24_TO_FLOAT (style_opacity->value); + double opacity = SP_SCALE24_TO_FLOAT(style_opacity->value); if (mode == TWEAK_MODE_COLORPAINT) { double d = opacity_goal - opacity; @@ -729,9 +723,7 @@ tweak_opacity (guint mode, SPIScale24 *style_opacity, double opacity_goal, doubl style_opacity->value = SP_SCALE24_FROM_FLOAT(opacity); } - - static double -tweak_profile (double dist, double radius) +static double tweak_profile(double dist, double radius) { if (radius == 0) { return 0; @@ -743,13 +735,13 @@ tweak_profile (double dist, double radius) } else if (x <= 0) { return 1; } else { - return (0.5 * cos (M_PI * (pow(x, alpha))) + 0.5); + 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*/) +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); @@ -757,7 +749,7 @@ static void tweak_colors_in_gradient(SPItem *item, Inkscape::PaintTarget fill_or return; } - Geom::Affine i2d (item->i2doc_affine ()); + 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 @@ -765,7 +757,6 @@ static void tweak_colors_in_gradient(SPItem *item, Inkscape::PaintTarget fill_or SPLinearGradient *lg = dynamic_cast<SPLinearGradient *>(gradient); SPRadialGradient *rg = dynamic_cast<SPRadialGradient *>(gradient); if (lg || rg) { - double pos = 0; double r = 0; @@ -777,8 +768,8 @@ static void tweak_colors_in_gradient(SPItem *item, Inkscape::PaintTarget fill_or // 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]))); + 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; @@ -787,10 +778,9 @@ static void tweak_colors_in_gradient(SPItem *item, Inkscape::PaintTarget fill_or pos = pnorm[Geom::X] / vl; // Calculate radius in length-of-gradient-line units r = radius / vl; - } if (rg) { - Geom::Point c (rg->cx.computed, rg->cy.computed); + Geom::Point c(rg->cx.computed, rg->cy.computed); pos = Geom::L2(p - c) / rg->r.computed; r = radius / rg->r.computed; } @@ -823,7 +813,7 @@ static void tweak_colors_in_gradient(SPItem *item, Inkscape::PaintTarget fill_or double offset_l = 0; double offset_h = 0; SPObject *child_prev = nullptr; - for (auto& child: vector->children) { + for (auto &child : vector->children) { SPStop *stop = dynamic_cast<SPStop *>(&child); if (!stop) { continue; @@ -840,12 +830,10 @@ static void tweak_colors_in_gradient(SPItem *item, Inkscape::PaintTarget fill_or // 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->getColor().v.c, rgb_goal, - force * (pos_e - offset_l) / (offset_h - offset_l), - do_h, do_s, do_l); + tweak_color(mode, stop->getColor().v.c, rgb_goal, + force * (pos_e - offset_l) / (offset_h - offset_l), do_h, do_s, do_l); tweak_color(mode, prevStop->getColor().v.c, rgb_goal, - force * (offset_h - pos_e) / (offset_h - offset_l), - do_h, do_s, do_l); + force * (offset_h - pos_e) / (offset_h - offset_l), do_h, do_s, do_l); stop->updateRepr(); child_prev->updateRepr(); break; @@ -854,15 +842,13 @@ static void tweak_colors_in_gradient(SPItem *item, Inkscape::PaintTarget fill_or // paint each stop by the force from the profile curve if (offset_l <= pos_e && offset_l > pos_e - r) { tweak_color(mode, prevStop->getColor().v.c, rgb_goal, - force * tweak_profile (fabs (pos_e - offset_l), r), - do_h, do_s, do_l); + 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->getColor().v.c, rgb_goal, - force * tweak_profile (fabs (pos_e - offset_h), r), - do_h, do_s, do_l); + tweak_color(mode, stop->getColor().v.c, rgb_goal, + force * tweak_profile(fabs(pos_e - offset_h), r), do_h, do_s, do_l); stop->updateRepr(); } } @@ -878,12 +864,12 @@ static void tweak_colors_in_gradient(SPItem *item, Inkscape::PaintTarget fill_or SPMeshGradient *mg_array = dynamic_cast<SPMeshGradient *>(mg->getArray()); SPMeshNodeArray *array = &(mg_array->array); // Every third node is a corner node - for( unsigned i=0; i < array->nodes.size(); i+=3 ) { - for( unsigned j=0; j < array->nodes[i].size(); j+=3 ) { + for (unsigned i = 0; i < array->nodes.size(); i += 3) { + for (unsigned j = 0; j < array->nodes[i].size(); j += 3) { SPStop *stop = array->nodes[i][j]->stop; - double distance = Geom::L2(Geom::Point(p - array->nodes[i][j]->p)); - tweak_color (mode, stop->getColor().v.c, rgb_goal, - force * tweak_profile (distance, radius), do_h, do_s, do_l); + double distance = Geom::L2(Geom::Point(p - array->nodes[i][j]->p)); + tweak_color(mode, stop->getColor().v.c, rgb_goal, force * tweak_profile(distance, radius), do_h, + do_s, do_l); stop->updateRepr(); } } @@ -891,27 +877,20 @@ static void tweak_colors_in_gradient(SPItem *item, Inkscape::PaintTarget fill_or } } - 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) +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 (dynamic_cast<SPGroup *>(item)) { - for (auto& child: item->children) { + for (auto &child : item->children) { SPItem *childItem = dynamic_cast<SPItem *>(&child); if (childItem) { - if (sp_tweak_color_recursive (mode, childItem, 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)) { + if (sp_tweak_color_recursive(mode, childItem, 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; } } @@ -938,94 +917,93 @@ sp_tweak_color_recursive (guint mode, SPItem *item, SPItem *item_at_point, // else if no overlap of bbox and brush box, skip: } else if (!bbox->intersects(brush)) { return false; - //TODO: + // 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) { + } else { + this_force = force * tweak_profile(Geom::L2(p - center), radius); + } - if (do_blur) { - Geom::OptRect bbox = item->documentGeometricBounds(); - if (!bbox) { - return did; - } + 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 - for (auto& primitive_obj: style->getFilter()->children) { - SPFilterPrimitive *primitive = dynamic_cast<SPFilterPrimitive *>(&primitive_obj); - if (primitive) { - //if primitive is gaussianblur - SPGaussianBlur * spblur = dynamic_cast<SPGaussianBlur *>(primitive); - if (spblur) { - float num = spblur->stdDeviation.getNumber(); - blur_now += num * i2dt.descrim(); // sum all blurs in the filter + double blur_now = 0; + Geom::Affine i2dt = item->i2dt_affine(); + if (style->filter.set && style->getFilter()) { + // cycle through filter primitives + for (auto &primitive_obj : style->getFilter()->children) { + SPFilterPrimitive *primitive = dynamic_cast<SPFilterPrimitive *>(&primitive_obj); + if (primitive) { + // if primitive is gaussianblur + SPGaussianBlur *spblur = dynamic_cast<SPGaussianBlur *>(primitive); + if (spblur) { + float num = spblur->stdDeviation.getNumber(); + blur_now += num * i2dt.descrim(); // sum all blurs in the filter + } } } } - } - double perimeter = bbox->dimensions()[Geom::X] + bbox->dimensions()[Geom::Y]; - blur_now = blur_now / perimeter; + 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); + 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 } - 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_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_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); } - } - if (do_opacity && do_o) { - tweak_opacity (mode, &style->opacity, opacity_goal, this_force); } } -} -return did; + return did; } - - static bool -sp_tweak_dilate (TweakTool *tc, Geom::Point event_p, Geom::Point p, Geom::Point vector, bool reverse) +static bool sp_tweak_dilate(TweakTool *tc, Geom::Point event_p, Geom::Point p, Geom::Point vector, bool reverse) { SPDesktop *desktop = tc->getDesktop(); Inkscape::Selection *selection = desktop->getSelection(); @@ -1061,17 +1039,11 @@ sp_tweak_dilate (TweakTool *tc, Geom::Point event_p, Geom::Point p, Geom::Point SPColor::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))); + // 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; } @@ -1081,28 +1053,27 @@ sp_tweak_dilate (TweakTool *tc, Geom::Point event_p, Geom::Point p, Geom::Point return false; } double move_force = get_move_force(tc); - double color_force = MIN(sqrt(path_force)/20.0, 1); + double color_force = MIN(sqrt(path_force) / 20.0, 1); // auto items= selection->items(); - std::vector<SPItem*> items(selection->items().begin(), selection->items().end()); - for(auto item : items){ - if (is_color_mode (tc->mode)) { + std::vector<SPItem *> items(selection->items().begin(), selection->items().end()); + for (auto item : items) { + 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)) { + 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)) { + 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)) { + if (sp_tweak_dilate_recursive(selection, item, p, vector, tc->mode, radius, path_force, tc->fidelity, + reverse)) { did = true; } } @@ -1111,21 +1082,19 @@ sp_tweak_dilate (TweakTool *tc, Geom::Point event_p, Geom::Point p, Geom::Point return did; } - static void -sp_tweak_update_area (TweakTool *tc) +static void sp_tweak_update_area(TweakTool *tc) { double radius = get_dilate_radius(tc); - Geom::Affine const sm (Geom::Scale(radius, radius) * Geom::Translate(tc->getDesktop()->point())); + Geom::Affine const sm(Geom::Scale(radius, radius) * Geom::Translate(tc->getDesktop()->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) +static void sp_tweak_switch_mode(TweakTool *tc, gint mode, bool with_shift) { - auto tb = dynamic_cast<UI::Toolbar::TweakToolbar*>(tc->getDesktop()->get_toolbar_by_name("TweakToolbar")); + auto tb = dynamic_cast<UI::Toolbar::TweakToolbar *>(tc->getDesktop()->get_toolbar_by_name("TweakToolbar")); - if(tb) { + if (tb) { tb->set_mode(mode); } else { std::cerr << "Could not access Tweak toolbar" << std::endl; @@ -1136,16 +1105,15 @@ sp_tweak_switch_mode (TweakTool *tc, gint mode, bool with_shift) tc->update_cursor(with_shift); } - static void -sp_tweak_switch_mode_temporarily (TweakTool *tc, gint mode, bool 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); - auto tb = dynamic_cast<UI::Toolbar::TweakToolbar*>(tc->getDesktop()->get_toolbar_by_name("TweakToolbar")); + auto tb = dynamic_cast<UI::Toolbar::TweakToolbar *>(tc->getDesktop()->get_toolbar_by_name("TweakToolbar")); - if(tb) { + if (tb) { tb->set_mode(mode); } else { std::cerr << "Could not access Tweak toolbar" << std::endl; @@ -1158,7 +1126,8 @@ sp_tweak_switch_mode_temporarily (TweakTool *tc, gint mode, bool with_shift) tc->update_cursor(with_shift); } -bool TweakTool::root_handler(GdkEvent* event) { +bool TweakTool::root_handler(GdkEvent *event) +{ gint ret = FALSE; switch (event->type) { @@ -1170,13 +1139,11 @@ bool TweakTool::root_handler(GdkEvent* event) { break; case GDK_BUTTON_PRESS: if (event->button.button == 1 && !this->space_panning) { - if (Inkscape::have_viable_layer(desktop, defaultMessageContext()) == false) { return TRUE; } - Geom::Point const button_w(event->button.x, - event->button.y); + 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); @@ -1190,42 +1157,40 @@ bool TweakTool::root_handler(GdkEvent* event) { ret = TRUE; } break; - case GDK_MOTION_NOTIFY: - { - Geom::Point const motion_w(event->motion.x, - event->motion.y); + 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 = (guint) boost::distance(desktop->selection->items()); - } - if (num == 0) { - this->message_context->flash(Inkscape::ERROR_MESSAGE, _("<b>Nothing selected!</b> Select objects to tweak.")); - } + 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 = (guint)boost::distance(desktop->selection->items()); + } + 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; + 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: - { + } 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)); @@ -1236,70 +1201,61 @@ bool TweakTool::root_handler(GdkEvent* event) { 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)); + 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(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Move tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, _("Move tweak")); break; case TWEAK_MODE_MOVE_IN_OUT: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Move in/out tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, _("Move in/out tweak")); break; case TWEAK_MODE_MOVE_JITTER: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Move jitter tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, _("Move jitter tweak")); break; case TWEAK_MODE_SCALE: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Scale tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, _("Scale tweak")); break; case TWEAK_MODE_ROTATE: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Rotate tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, _("Rotate tweak")); break; case TWEAK_MODE_MORELESS: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Duplicate/delete tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, + _("Duplicate/delete tweak")); break; case TWEAK_MODE_PUSH: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Push path tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, _("Push path tweak")); break; case TWEAK_MODE_SHRINK_GROW: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Shrink/grow path tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, + _("Shrink/grow path tweak")); break; case TWEAK_MODE_ATTRACT_REPEL: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Attract/repel path tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, + _("Attract/repel path tweak")); break; case TWEAK_MODE_ROUGHEN: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Roughen path tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, + _("Roughen path tweak")); break; case TWEAK_MODE_COLORPAINT: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Color paint tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, _("Color paint tweak")); break; case TWEAK_MODE_COLORJITTER: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Color jitter tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, + _("Color jitter tweak")); break; case TWEAK_MODE_BLUR: - DocumentUndo::done(this->desktop->getDocument(), - SP_VERB_CONTEXT_TWEAK, _("Blur tweak")); + DocumentUndo::done(this->desktop->getDocument(), SP_VERB_CONTEXT_TWEAK, _("Blur tweak")); break; } } break; } - case GDK_KEY_PRESS: - { - switch (get_latin_keyval (&event->key)) { + case GDK_KEY_PRESS: { + switch (get_latin_keyval(&event->key)) { case GDK_KEY_m: case GDK_KEY_M: case GDK_KEY_0: @@ -1411,7 +1367,7 @@ bool TweakTool::root_handler(GdkEvent* event) { if (this->force > 1.0) { this->force = 1.0; } - desktop->setToolboxAdjustmentValue ("tweak-force", this->force * 100); + desktop->setToolboxAdjustmentValue("tweak-force", this->force * 100); ret = TRUE; } break; @@ -1422,7 +1378,7 @@ bool TweakTool::root_handler(GdkEvent* event) { if (this->force < 0.0) { this->force = 0.0; } - desktop->setToolboxAdjustmentValue ("tweak-force", this->force * 100); + desktop->setToolboxAdjustmentValue("tweak-force", this->force * 100); ret = TRUE; } break; @@ -1433,7 +1389,8 @@ bool TweakTool::root_handler(GdkEvent* event) { if (this->width > 1.0) { this->width = 1.0; } - desktop->setToolboxAdjustmentValue ("tweak-width", this->width * 100); // the same spinbutton is for alt+x + desktop->setToolboxAdjustmentValue("tweak-width", + this->width * 100); // the same spinbutton is for alt+x sp_tweak_update_area(this); ret = TRUE; } @@ -1445,7 +1402,7 @@ bool TweakTool::root_handler(GdkEvent* event) { if (this->width < 0.01) { this->width = 0.01; } - desktop->setToolboxAdjustmentValue ("tweak-width", this->width * 100); + desktop->setToolboxAdjustmentValue("tweak-width", this->width * 100); sp_tweak_update_area(this); ret = TRUE; } @@ -1453,21 +1410,21 @@ bool TweakTool::root_handler(GdkEvent* event) { case GDK_KEY_Home: case GDK_KEY_KP_Home: this->width = 0.01; - desktop->setToolboxAdjustmentValue ("tweak-width", this->width * 100); + desktop->setToolboxAdjustmentValue("tweak-width", 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 ("tweak-width", this->width * 100); + desktop->setToolboxAdjustmentValue("tweak-width", 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 ("tweak-width"); + desktop->setToolboxFocusTo("tweak-width"); ret = TRUE; } break; @@ -1501,11 +1458,11 @@ bool TweakTool::root_handler(GdkEvent* event) { break; case GDK_KEY_Control_L: case GDK_KEY_Control_R: - sp_tweak_switch_mode (this, prefs->getInt("/tools/tweak/mode"), MOD__SHIFT(event)); + 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)); + sp_tweak_switch_mode(this, prefs->getInt("/tools/tweak/mode"), MOD__SHIFT(event)); break; } } @@ -1514,15 +1471,15 @@ bool TweakTool::root_handler(GdkEvent* event) { } if (!ret) { - ret = ToolBase::root_handler(event); + ret = ToolBase::root_handler(event); } return ret; } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/tweak-tool.h b/src/ui/tools/tweak-tool.h index 677cc0bd070cfae02cd7db7261fe4e419dd037e5..c927165ee3bd267102a460448c24cc460b5baa0c 100644 --- a/src/ui/tools/tweak-tool.h +++ b/src/ui/tools/tweak-tool.h @@ -13,20 +13,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/tools/tool-base.h" #include <2geom/point.h> -#define SAMPLING_SIZE 8 /* fixme: ?? */ +#include "ui/tools/tool-base.h" + +#define SAMPLING_SIZE 8 /* fixme: ?? */ -#define TC_MIN_PRESSURE 0.0 -#define TC_MAX_PRESSURE 1.0 -#define TC_DEFAULT_PRESSURE 0.35 +#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 { +enum +{ TWEAK_MODE_MOVE, TWEAK_MODE_MOVE_IN_OUT, TWEAK_MODE_MOVE_JITTER, @@ -42,16 +44,17 @@ enum { TWEAK_MODE_BLUR }; -class TweakTool : public ToolBase { +class TweakTool : public ToolBase +{ public: - TweakTool(); - ~TweakTool() override; + TweakTool(); + ~TweakTool() override; /* extended input data */ gdouble pressure; /* attributes */ - bool dragging; /* mouse state: mouse is dragging */ + bool dragging; /* mouse state: mouse is dragging */ bool usepressure; bool usetilt; @@ -73,25 +76,25 @@ public: bool do_l; bool do_o; - sigc::connection style_set_connection; + sigc::connection style_set_connection; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - void set(const Inkscape::Preferences::Entry& val) override; - bool root_handler(GdkEvent* event) override; + void setup() override; + void set(const Inkscape::Preferences::Entry &val) override; + bool root_handler(GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; - void update_cursor(bool with_shift); + void update_cursor(bool with_shift); private: - bool set_style(const SPCSSAttr* css); + bool set_style(const SPCSSAttr *css); }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/tools/zoom-tool.cpp b/src/ui/tools/zoom-tool.cpp index 0372e8d6cfe549d3bbe9f50ef777ac006a4b408e..f12a72a1e958b777245c2891bd8469836924a272 100644 --- a/src/ui/tools/zoom-tool.cpp +++ b/src/ui/tools/zoom-tool.cpp @@ -12,26 +12,26 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/tools/zoom-tool.h" #include <gdk/gdkkeysyms.h> -#include "include/macros.h" -#include "rubberband.h" +#include "desktop.h" #include "display/sp-canvas-item.h" #include "display/sp-canvas-util.h" -#include "desktop.h" -#include "ui/pixmaps/cursor-zoom.xpm" -#include "ui/pixmaps/cursor-zoom-out.xpm" +#include "include/macros.h" +#include "rubberband.h" #include "selection-chemistry.h" - -#include "ui/tools/zoom-tool.h" +#include "ui/pixmaps/cursor-zoom-out.xpm" +#include "ui/pixmaps/cursor-zoom.xpm" namespace Inkscape { namespace UI { namespace Tools { -const std::string& ZoomTool::getPrefsPath() { - return ZoomTool::prefsPath; +const std::string &ZoomTool::getPrefsPath() +{ + return ZoomTool::prefsPath; } const std::string ZoomTool::prefsPath = "/tools/zoom"; @@ -40,14 +40,14 @@ ZoomTool::ZoomTool() : ToolBase(cursor_zoom_xpm) , grabbed(nullptr) , escaped(false) -{ -} +{} ZoomTool::~ZoomTool() = default; -void ZoomTool::finish() { - this->enableGrDrag(false); - +void ZoomTool::finish() +{ + this->enableGrDrag(false); + if (this->grabbed) { sp_canvas_item_ungrab(this->grabbed); this->grabbed = nullptr; @@ -56,7 +56,8 @@ void ZoomTool::finish() { ToolBase::finish(); } -void ZoomTool::setup() { +void ZoomTool::setup() +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs->getBool("/tools/zoom/selcue")) { @@ -70,24 +71,24 @@ void ZoomTool::setup() { ToolBase::setup(); } -bool ZoomTool::root_handler(GdkEvent* event) { +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: - { + 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; + xp = (gint)event->button.x; + yp = (gint)event->button.y; within_tolerance = true; Inkscape::Rubberband::get(desktop)->start(desktop, button_dt); @@ -96,31 +97,27 @@ bool ZoomTool::root_handler(GdkEvent* event) { ret = true; } else if (event->button.button == 3) { - double const zoom_rel( (event->button.state & GDK_SHIFT_MASK) - ? zoom_inc - : 1 / zoom_inc ); + 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_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | - GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK, + GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_BUTTON_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK, nullptr, event->button.time); this->grabbed = SP_CANVAS_ITEM(desktop->acetate); break; } - case GDK_MOTION_NOTIFY: + 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 ) ) { + 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 @@ -135,20 +132,17 @@ bool ZoomTool::root_handler(GdkEvent* event) { } break; - case GDK_BUTTON_RELEASE: - { + 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) { + if (event->button.button == 1 && !this->space_panning) { Geom::OptRect const b = Inkscape::Rubberband::get(desktop)->getRectangle(); - if (b && !within_tolerance && !(GDK_SHIFT_MASK & event->button.state) ) { + if (b && !within_tolerance && !(GDK_SHIFT_MASK & event->button.state)) { desktop->set_display_area(*b, 10); } else if (!escaped) { - double const zoom_rel( (event->button.state & GDK_SHIFT_MASK) - ? 1 / zoom_inc - : zoom_inc ); + double const zoom_rel((event->button.state & GDK_SHIFT_MASK) ? 1 / zoom_inc : zoom_inc); desktop->zoom_relative_keep_point(button_dt, zoom_rel); } @@ -157,18 +151,18 @@ bool ZoomTool::root_handler(GdkEvent* event) { } Inkscape::Rubberband::get(desktop)->stop(); - + if (this->grabbed) { sp_canvas_item_ungrab(this->grabbed); this->grabbed = nullptr; } - + xp = yp = 0; escaped = false; break; } case GDK_KEY_PRESS: - switch (get_latin_keyval (&event->key)) { + switch (get_latin_keyval(&event->key)) { case GDK_KEY_Escape: if (!Inkscape::Rubberband::get(desktop)->is_started()) { Inkscape::SelectionHelper::selectNone(desktop); @@ -202,34 +196,34 @@ bool ZoomTool::root_handler(GdkEvent* event) { break; default: - break; - } - break; - case GDK_KEY_RELEASE: - switch (get_latin_keyval (&event->key)) { - case GDK_KEY_Shift_L: - case GDK_KEY_Shift_R: + break; + } + break; + case GDK_KEY_RELEASE: + switch (get_latin_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: + default: break; } break; - default: + default: break; } if (!ret) { - ret = ToolBase::root_handler(event); + ret = ToolBase::root_handler(event); } return ret; } -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/tools/zoom-tool.h b/src/ui/tools/zoom-tool.h index 003b6be5de19a4893fa70857b331f59d3980be0d..502564dc93912b70fd1474c812daf900ce280732 100644 --- a/src/ui/tools/zoom-tool.h +++ b/src/ui/tools/zoom-tool.h @@ -16,33 +16,35 @@ #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) +#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 { +class ZoomTool : public ToolBase +{ public: - ZoomTool(); - ~ZoomTool() override; + ZoomTool(); + ~ZoomTool() override; - static const std::string prefsPath; + static const std::string prefsPath; - void setup() override; - void finish() override; - bool root_handler(GdkEvent* event) override; + void setup() override; + void finish() override; + bool root_handler(GdkEvent *event) override; - const std::string& getPrefsPath() override; + const std::string &getPrefsPath() override; private: - SPCanvasItem *grabbed; - bool escaped; + SPCanvasItem *grabbed; + bool escaped; }; -} -} -} +} // namespace Tools +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/util.cpp b/src/ui/util.cpp index 1832cf7d8ce6bfd87cbbf62591ac866ae430fde5..7e002eaf0f9c7b0c2e42862cc316e8d77337708e 100644 --- a/src/ui/util.cpp +++ b/src/ui/util.cpp @@ -19,8 +19,8 @@ Glib::ustring ink_ellipsize_text(Glib::ustring const &src, size_t maxlen) { if (src.length() > maxlen && maxlen > 8) { - size_t p1 = (size_t) maxlen / 2; - size_t p2 = (size_t) src.length() - (maxlen - p1 - 1); + size_t p1 = (size_t)maxlen / 2; + size_t p2 = (size_t)src.length() - (maxlen - p1 - 1); return src.substr(0, p1) + "…" + src.substr(p2); } return src; diff --git a/src/ui/util.h b/src/ui/util.h index 94803718ab06e9f97850cc5fb7a909c8c648ae48..9e0ae838d170628d44b41643a597443783f7888d 100644 --- a/src/ui/util.h +++ b/src/ui/util.h @@ -15,7 +15,7 @@ #include <glibmm/ustring.h> -Glib::ustring ink_ellipsize_text (Glib::ustring const &src, size_t maxlen); +Glib::ustring ink_ellipsize_text(Glib::ustring const &src, size_t maxlen); #endif diff --git a/src/ui/uxmanager.cpp b/src/ui/uxmanager.cpp index 08ee66c2cef24f5c01bed0789ee6ab58726f8d9e..b5d0b10cd176997a5c9c1595c935de66a016021b 100644 --- a/src/ui/uxmanager.cpp +++ b/src/ui/uxmanager.cpp @@ -10,51 +10,49 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "uxmanager.h" + #include <vector> -#include "widgets/desktop-widget.h" -#include "uxmanager.h" #include "desktop.h" #include "ui/monitor.h" +#include "widgets/desktop-widget.h" #include "widgets/toolbox.h" class TrackItem { public: - TrackItem() : - destroyConn(), - boxes() + TrackItem() + : destroyConn() + , boxes() {} sigc::connection destroyConn; - std::vector<GtkWidget*> boxes; + std::vector<GtkWidget *> boxes; }; -static std::vector<SPDesktop*> desktops; -static std::vector<SPDesktopWidget*> dtws; -static std::map<SPDesktop*, TrackItem> trackedBoxes; - +static std::vector<SPDesktop *> desktops; +static std::vector<SPDesktopWidget *> dtws; +static std::map<SPDesktop *, TrackItem> trackedBoxes; namespace { void desktopDestructHandler(SPDesktop *desktop) { - std::map<SPDesktop*, TrackItem>::iterator it = trackedBoxes.find(desktop); - if (it != trackedBoxes.end()) - { + std::map<SPDesktop *, TrackItem>::iterator it = trackedBoxes.find(desktop); + if (it != trackedBoxes.end()) { trackedBoxes.erase(it); } } - // TODO unify this later: -static Glib::ustring getLayoutPrefPath( Inkscape::UI::View::View *view ) +static Glib::ustring getLayoutPrefPath(Inkscape::UI::View::View *view) { Glib::ustring prefPath; - if (reinterpret_cast<SPDesktop*>(view)->is_focusMode()) { + if (reinterpret_cast<SPDesktop *>(view)->is_focusMode()) { prefPath = "/focus/"; - } else if (reinterpret_cast<SPDesktop*>(view)->is_fullscreen()) { + } else if (reinterpret_cast<SPDesktop *>(view)->is_fullscreen()) { prefPath = "/fullscreen/"; } else { prefPath = "/window/"; @@ -63,12 +61,12 @@ static Glib::ustring getLayoutPrefPath( Inkscape::UI::View::View *view ) return prefPath; } -} +} // namespace namespace Inkscape { namespace UI { -UXManager* instance = nullptr; +UXManager *instance = nullptr; class UXManagerImpl : public UXManager { @@ -76,13 +74,13 @@ public: UXManagerImpl(); ~UXManagerImpl() override; - void addTrack( SPDesktopWidget* dtw ) override; - void delTrack( SPDesktopWidget* dtw ) override; + void addTrack(SPDesktopWidget *dtw) override; + void delTrack(SPDesktopWidget *dtw) override; - void connectToDesktop( std::vector<GtkWidget *> const & toolboxes, SPDesktop *desktop ) override; + void connectToDesktop(std::vector<GtkWidget *> const &toolboxes, SPDesktop *desktop) override; - gint getDefaultTask( SPDesktop *desktop ) override; - void setTask(SPDesktop* dt, gint val) override; + gint getDefaultTask(SPDesktop *desktop) override; + void setTask(SPDesktop *dt, gint val) override; bool isWidescreen() const override; @@ -90,7 +88,7 @@ private: bool _widescreen; }; -UXManager* UXManager::getInstance() +UXManager *UXManager::getInstance() { if (!instance) { instance = new UXManagerImpl(); @@ -98,19 +96,16 @@ UXManager* UXManager::getInstance() return instance; } +UXManager::UXManager() = default; -UXManager::UXManager() -= default; - -UXManager::~UXManager() -= default; +UXManager::~UXManager() = default; -UXManagerImpl::UXManagerImpl() : - _widescreen(false) +UXManagerImpl::UXManagerImpl() + : _widescreen(false) { // Figure out if we're on a widescreen display Gdk::Rectangle monitor_geometry = Inkscape::UI::get_monitor_geometry_primary(); - int const width = monitor_geometry.get_width(); + int const width = monitor_geometry.get_width(); int const height = monitor_geometry.get_height(); if (width && height) { @@ -121,26 +116,25 @@ UXManagerImpl::UXManagerImpl() : } } -UXManagerImpl::~UXManagerImpl() -= default; +UXManagerImpl::~UXManagerImpl() = default; bool UXManagerImpl::isWidescreen() const { return _widescreen; } -gint UXManagerImpl::getDefaultTask( SPDesktop *desktop ) +gint UXManagerImpl::getDefaultTask(SPDesktop *desktop) { gint taskNum = isWidescreen() ? 2 : 0; - Glib::ustring prefPath = getLayoutPrefPath( desktop ); - taskNum = Inkscape::Preferences::get()->getInt( prefPath + "task/taskset", taskNum ); + Glib::ustring prefPath = getLayoutPrefPath(desktop); + taskNum = Inkscape::Preferences::get()->getInt(prefPath + "task/taskset", taskNum); taskNum = (taskNum < 0) ? 0 : (taskNum > 2) ? 2 : taskNum; return taskNum; } -void UXManagerImpl::setTask(SPDesktop* dt, gint val) +void UXManagerImpl::setTask(SPDesktop *dt, gint val) { for (auto dtw : dtws) { gboolean notDone = Inkscape::Preferences::get()->getBool("/options/workarounds/dynamicnotdone", false); @@ -174,40 +168,38 @@ void UXManagerImpl::setTask(SPDesktop* dt, gint val) dtw->setToolboxPosition("AuxToolbar", GTK_POS_RIGHT); } } - Glib::ustring prefPath = getLayoutPrefPath( dtw->desktop ); - Inkscape::Preferences::get()->setInt( prefPath + "task/taskset", taskNum ); + Glib::ustring prefPath = getLayoutPrefPath(dtw->desktop); + Inkscape::Preferences::get()->setInt(prefPath + "task/taskset", taskNum); } } } - -void UXManagerImpl::addTrack( SPDesktopWidget* dtw ) +void UXManagerImpl::addTrack(SPDesktopWidget *dtw) { if (std::find(dtws.begin(), dtws.end(), dtw) == dtws.end()) { dtws.push_back(dtw); } } -void UXManagerImpl::delTrack( SPDesktopWidget* dtw ) +void UXManagerImpl::delTrack(SPDesktopWidget *dtw) { - std::vector<SPDesktopWidget*>::iterator iter = std::find(dtws.begin(), dtws.end(), dtw); + std::vector<SPDesktopWidget *>::iterator iter = std::find(dtws.begin(), dtws.end(), dtw); if (iter != dtws.end()) { dtws.erase(iter); } } -void UXManagerImpl::connectToDesktop( std::vector<GtkWidget *> const & toolboxes, SPDesktop *desktop ) +void UXManagerImpl::connectToDesktop(std::vector<GtkWidget *> const &toolboxes, SPDesktop *desktop) { - if (!desktop) - { + if (!desktop) { return; } TrackItem &tracker = trackedBoxes[desktop]; - std::vector<GtkWidget*>& tracked = tracker.boxes; + std::vector<GtkWidget *> &tracked = tracker.boxes; tracker.destroyConn = desktop->connectDestroy(&desktopDestructHandler); for (auto toolbox : toolboxes) { - ToolboxFactory::setToolboxDesktop( toolbox, desktop ); + ToolboxFactory::setToolboxDesktop(toolbox, desktop); if (find(tracked.begin(), tracked.end(), toolbox) == tracked.end()) { tracked.push_back(toolbox); } @@ -217,13 +209,12 @@ void UXManagerImpl::connectToDesktop( std::vector<GtkWidget *> const & toolboxes desktops.push_back(desktop); } - gint taskNum = getDefaultTask( desktop ); + gint taskNum = getDefaultTask(desktop); // note: this will change once more options are in the task set support: - Inkscape::UI::UXManager::getInstance()->setTask( desktop, taskNum ); + Inkscape::UI::UXManager::getInstance()->setTask(desktop, taskNum); } - } // namespace UI } // namespace Inkscape diff --git a/src/ui/uxmanager.h b/src/ui/uxmanager.h index 5cb799ce995f1dbf107bbf0eda761b57b4e97477..6a1b0f97bbdd9809ca036da7f4635a2e9bdb2513 100644 --- a/src/ui/uxmanager.h +++ b/src/ui/uxmanager.h @@ -12,8 +12,8 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <vector> #include <glib.h> +#include <vector> extern "C" typedef struct _GtkWidget GtkWidget; class SPDesktop; @@ -25,21 +25,21 @@ namespace UI { class UXManager { public: - static UXManager* getInstance(); + static UXManager *getInstance(); virtual ~UXManager(); - virtual void addTrack( SPDesktopWidget* dtw ) = 0; - virtual void delTrack( SPDesktopWidget* dtw ) = 0; + virtual void addTrack(SPDesktopWidget *dtw) = 0; + virtual void delTrack(SPDesktopWidget *dtw) = 0; - virtual void connectToDesktop( std::vector<GtkWidget *> const & toolboxes, SPDesktop *desktop ) = 0; + virtual void connectToDesktop(std::vector<GtkWidget *> const &toolboxes, SPDesktop *desktop) = 0; - virtual gint getDefaultTask( SPDesktop *desktop ) = 0; - virtual void setTask( SPDesktop* dt, gint val ) = 0; + virtual gint getDefaultTask(SPDesktop *desktop) = 0; + virtual void setTask(SPDesktop *dt, gint val) = 0; virtual bool isWidescreen() const = 0; - UXManager( UXManager const & ) = delete; - UXManager & operator=( UXManager const & ) = delete; + UXManager(UXManager const &) = delete; + UXManager &operator=(UXManager const &) = delete; protected: UXManager(); diff --git a/src/ui/view/svg-view-widget.cpp b/src/ui/view/svg-view-widget.cpp index db82cb3de2013bb0281277e1485737f6ce3520f8..f3606f5a57f390c46335be9bae02d0238fae1d83 100644 --- a/src/ui/view/svg-view-widget.cpp +++ b/src/ui/view/svg-view-widget.cpp @@ -19,23 +19,18 @@ * */ -#include <iostream> - #include "svg-view-widget.h" -#include "document.h" +#include <iostream> #include "2geom/transforms.h" - +#include "display/canvas-arena.h" #include "display/sp-canvas-group.h" #include "display/sp-canvas-item.h" -#include "display/canvas-arena.h" - +#include "document.h" #include "object/sp-item.h" #include "object/sp-root.h" - #include "ui/widget/canvas.h" - #include "util/units.h" namespace Inkscape { @@ -47,8 +42,7 @@ namespace View { */ // This hasn't worked since at least 0.48. It should result in a cursor change over <a></a> links. // There should be a better way of doing this. See note in canvas-arena.cpp. -static gint arena_handler(SPCanvasArena */*arena*/, Inkscape::DrawingItem *ai, - GdkEvent *event, SVGViewWidget *svgview) +static gint arena_handler(SPCanvasArena * /*arena*/, Inkscape::DrawingItem *ai, GdkEvent *event, SVGViewWidget *svgview) { static gdouble x, y; static gboolean active = FALSE; @@ -66,12 +60,10 @@ static gint arena_handler(SPCanvasArena */*arena*/, Inkscape::DrawingItem *ai, break; case GDK_BUTTON_RELEASE: if (event->button.button == 1) { - if (active && (event->button.x == x) && - (event->button.y == y)) { + if (active && (event->button.x == x) && (event->button.y == y)) { spev.type = SPEvent::ACTIVATE; - if ( spitem != nullptr ) - { - spitem->emitEvent (spev); + if (spitem != nullptr) { + spitem->emitEvent(spev); } } } @@ -83,17 +75,15 @@ static gint arena_handler(SPCanvasArena */*arena*/, Inkscape::DrawingItem *ai, case GDK_ENTER_NOTIFY: spev.type = SPEvent::MOUSEOVER; spev.view = svgview; - if ( spitem != nullptr ) - { - spitem->emitEvent (spev); + if (spitem != nullptr) { + spitem->emitEvent(spev); } break; case GDK_LEAVE_NOTIFY: spev.type = SPEvent::MOUSEOUT; spev.view = svgview; - if ( spitem != nullptr ) - { - spitem->emitEvent (spev); + if (spitem != nullptr) { + spitem->emitEvent(spev); } break; default: @@ -103,13 +93,12 @@ static gint arena_handler(SPCanvasArena */*arena*/, Inkscape::DrawingItem *ai, return TRUE; } - /** * A light-weight widget containing an SPCanvas for rendering an SVG. * It's derived from a Gtk::ScrolledWindow like the previous C version, but that doesn't seem to be * too useful. */ -SVGViewWidget::SVGViewWidget(SPDocument* document) +SVGViewWidget::SVGViewWidget(SPDocument *document) : _document(nullptr) , _dkey(0) , _parent(nullptr) @@ -123,12 +112,11 @@ SVGViewWidget::SVGViewWidget(SPDocument* document) { _canvas = Gtk::manage(new Inkscape::UI::Widget::Canvas()); - SPCanvasItem* item = - sp_canvas_item_new(_canvas->get_canvas_item_root(), SP_TYPE_CANVAS_GROUP, nullptr); + SPCanvasItem *item = sp_canvas_item_new(_canvas->get_canvas_item_root(), SP_TYPE_CANVAS_GROUP, nullptr); _parent = SP_CANVAS_GROUP(item); - _drawing = sp_canvas_item_new (_parent, SP_TYPE_CANVAS_ARENA, nullptr); - g_signal_connect (G_OBJECT (_drawing), "arena_event", G_CALLBACK (arena_handler), this); + _drawing = sp_canvas_item_new(_parent, SP_TYPE_CANVAS_ARENA, nullptr); + g_signal_connect(G_OBJECT(_drawing), "arena_event", G_CALLBACK(arena_handler), this); setDocument(document); @@ -142,8 +130,7 @@ SVGViewWidget::~SVGViewWidget() } } -void -SVGViewWidget::setDocument(SPDocument* document) +void SVGViewWidget::setDocument(SPDocument *document) { // Clear old document if (_document) { @@ -154,31 +141,27 @@ SVGViewWidget::setDocument(SPDocument* document) if (document) { _document = document; - Inkscape::DrawingItem *ai = document->getRoot()->invoke_show( - SP_CANVAS_ARENA (_drawing)->drawing, - _dkey, - SP_ITEM_SHOW_DISPLAY); + Inkscape::DrawingItem *ai = + document->getRoot()->invoke_show(SP_CANVAS_ARENA(_drawing)->drawing, _dkey, SP_ITEM_SHOW_DISPLAY); if (ai) { - SP_CANVAS_ARENA (_drawing)->drawing.root()->prependChild(ai); + SP_CANVAS_ARENA(_drawing)->drawing.root()->prependChild(ai); } - doRescale (); + doRescale(); } } -void -SVGViewWidget::setResize(int width, int height) +void SVGViewWidget::setResize(int width, int height) { // Triggers size_allocation which calls SVGViewWidget::size_allocate. set_size_request(width, height); queue_resize(); } -void -SVGViewWidget::size_allocate(Gtk::Allocation& allocation) +void SVGViewWidget::size_allocate(Gtk::Allocation &allocation) { - double width = allocation.get_width(); + double width = allocation.get_width(); double height = allocation.get_height(); if (width < 0.0 || height < 0.0) { @@ -191,11 +174,10 @@ SVGViewWidget::size_allocate(Gtk::Allocation& allocation) _width = width; _height = height; - doRescale (); + doRescale(); } -void -SVGViewWidget::doRescale() +void SVGViewWidget::doRescale() { if (!_document) { std::cerr << "SVGViewWidget::doRescale: No document!" << std::endl; @@ -220,33 +202,31 @@ SVGViewWidget::doRescale() if (_keepaspect) { if (_hscale > _vscale) { _hscale = _vscale; - x_offset = (_width - _document->getWidth().value("px") * _vscale)/2.0; + x_offset = (_width - _document->getWidth().value("px") * _vscale) / 2.0; } else { _vscale = _hscale; - y_offset = (_height - _document->getHeight().value("px") * _hscale)/2.0; + y_offset = (_height - _document->getHeight().value("px") * _hscale) / 2.0; } } } if (_drawing) { - sp_canvas_item_affine_absolute (_drawing, Geom::Scale(_hscale, _vscale) * Geom::Translate(x_offset, y_offset)); + sp_canvas_item_affine_absolute(_drawing, Geom::Scale(_hscale, _vscale) * Geom::Translate(x_offset, y_offset)); } } -void -SVGViewWidget::mouseover() +void SVGViewWidget::mouseover() { GdkDisplay *display = gdk_display_get_default(); - GdkCursor *cursor = gdk_cursor_new_for_display(display, GDK_HAND2); - GdkWindow *window = gtk_widget_get_window (GTK_WIDGET(_canvas->gobj())); + GdkCursor *cursor = gdk_cursor_new_for_display(display, GDK_HAND2); + GdkWindow *window = gtk_widget_get_window(GTK_WIDGET(_canvas->gobj())); gdk_window_set_cursor(window, cursor); g_object_unref(cursor); } -void -SVGViewWidget::mouseout() +void SVGViewWidget::mouseout() { - GdkWindow *window = gtk_widget_get_window (GTK_WIDGET(_canvas->gobj())); + GdkWindow *window = gtk_widget_get_window(GTK_WIDGET(_canvas->gobj())); gdk_window_set_cursor(window, nullptr); } diff --git a/src/ui/view/svg-view-widget.h b/src/ui/view/svg-view-widget.h index 2939176c7293de2d86b5407ab8445826c806f3dc..1a7c17c44eb1bccd4ead0cfa408b8b07779e1ed2 100644 --- a/src/ui/view/svg-view-widget.h +++ b/src/ui/view/svg-view-widget.h @@ -17,7 +17,6 @@ #ifndef INKSCAPE_UI_SVG_VIEW_WIDGET_VARIATIONS_H #define INKSCAPE_UI_SVG_VIEW_WIDGET_VARIATIONS_H - #include <gtkmm.h> class SPDocument; @@ -36,32 +35,32 @@ namespace View { /** * A light-weight widget containing an Inkscape canvas for rendering an SVG. */ -class SVGViewWidget : public Gtk::ScrolledWindow { - +class SVGViewWidget : public Gtk::ScrolledWindow +{ public: - SVGViewWidget(SPDocument* document); + SVGViewWidget(SPDocument *document); ~SVGViewWidget() override; - void setDocument( SPDocument* document); - void setResize( int width, int height); + void setDocument(SPDocument *document); + void setResize(int width, int height); private: - void size_allocate(Gtk::Allocation& allocation); + void size_allocate(Gtk::Allocation &allocation); Inkscape::UI::Widget::Canvas *_canvas; -// From SVGView --------------------------------- + // From SVGView --------------------------------- public: - SPDocument* _document; - unsigned int _dkey; - SPCanvasGroup *_parent; - SPCanvasItem *_drawing; - double _hscale; ///< horizontal scale - double _vscale; ///< vertical scale - bool _rescale; ///< whether to rescale automatically - bool _keepaspect; - double _width; - double _height; + SPDocument *_document; + unsigned int _dkey; + SPCanvasGroup *_parent; + SPCanvasItem *_drawing; + double _hscale; ///< horizontal scale + double _vscale; ///< vertical scale + bool _rescale; ///< whether to rescale automatically + bool _keepaspect; + double _width; + double _height; /** * Helper function that sets rescale ratio. @@ -73,7 +72,6 @@ public: */ void mouseover(); void mouseout(); - }; } // Namespace View diff --git a/src/ui/view/view-widget.cpp b/src/ui/view/view-widget.cpp index 2b749cc0302ac691f093e815dc540646388274ba..1c5cc92116c9d09b2a8b66d4f852a9f0c294e4e3 100644 --- a/src/ui/view/view-widget.cpp +++ b/src/ui/view/view-widget.cpp @@ -10,9 +10,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "view.h" #include "view-widget.h" +#include "view.h" + /** * Callback to disconnect from view and destroy SPViewWidget. * @@ -37,15 +38,13 @@ void SPViewWidget::setView(view_type *view) { auto vw = this; g_return_if_fail(view != nullptr); - + g_return_if_fail(vw->view == nullptr); - + vw->view = view; Inkscape::GC::anchor(view); } - - /* Local Variables: mode:c++ diff --git a/src/ui/view/view-widget.h b/src/ui/view/view-widget.h index e67280df201fbf1d8091ad78f0b452ec4b29257d..f1c05cd552ae2f8636fb832b79790a891c8535b1 100644 --- a/src/ui/view/view-widget.h +++ b/src/ui/view/view-widget.h @@ -15,7 +15,6 @@ #include <gtkmm/eventbox.h> - namespace Inkscape { namespace UI { namespace View { @@ -28,13 +27,14 @@ class View; * SPViewWidget is a GUI widget that contain a single View. It is also * an abstract base class with little functionality of its own. */ -class SPViewWidget : public Gtk::EventBox { +class SPViewWidget : public Gtk::EventBox +{ using parent_type = Gtk::EventBox; using view_type = Inkscape::UI::View::View; view_type *view = nullptr; - public: +public: void on_unrealize() override; view_type *getView() { return view; } diff --git a/src/ui/view/view.cpp b/src/ui/view/view.cpp index 3b2b7f2298c0be0c3acd9da1c483afb48294a665..af722abd1b6d650272898fce6752b658d03ab017 100644 --- a/src/ui/view/view.cpp +++ b/src/ui/view/view.cpp @@ -11,60 +11,58 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "view.h" + #include <2geom/point.h> #include <memory> + #include "document.h" -#include "view.h" -#include "message-stack.h" +#include "inkscape.h" #include "message-context.h" +#include "message-stack.h" #include "verbs.h" -#include "inkscape.h" namespace Inkscape { namespace UI { namespace View { -static void -_onResized (double x, double y, View* v) +static void _onResized(double x, double y, View *v) { - v->onResized (x,y); + v->onResized(x, y); } -static void -_onRedrawRequested (View* v) +static void _onRedrawRequested(View *v) { v->onRedrawRequested(); } -static void -_onStatusMessage (Inkscape::MessageType type, gchar const *message, View* v) +static void _onStatusMessage(Inkscape::MessageType type, gchar const *message, View *v) { - v->onStatusMessage (type, message); + v->onStatusMessage(type, message); } -static void -_onDocumentURISet (gchar const* uri, View* v) +static void _onDocumentURISet(gchar const *uri, View *v) { - v->onDocumentURISet (uri); + v->onDocumentURISet(uri); } -static void -_onDocumentResized (double x, double y, View* v) +static void _onDocumentResized(double x, double y, View *v) { - v->onDocumentResized (x,y); + v->onDocumentResized(x, y); } //-------------------------------------------------------------------- View::View() -: _doc(nullptr) + : _doc(nullptr) { _message_stack = std::make_shared<Inkscape::MessageStack>(); _tips_message_context = std::unique_ptr<Inkscape::MessageContext>(new Inkscape::MessageContext(_message_stack)); - _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)); - - _message_changed_connection = _message_stack->connectChanged (sigc::bind (sigc::ptr_fun (&_onStatusMessage), 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)); + + _message_changed_connection = _message_stack->connectChanged(sigc::bind(sigc::ptr_fun(&_onStatusMessage), this)); } View::~View() @@ -72,7 +70,8 @@ View::~View() _close(); } -void View::_close() { +void View::_close() +{ _message_changed_connection.disconnect(); _tips_message_context = nullptr; @@ -88,21 +87,22 @@ void View::_close() { } _doc = nullptr; } - - Inkscape::Verb::delete_all_view (this); + + Inkscape::Verb::delete_all_view(this); } -void View::emitResized (double width, double height) +void View::emitResized(double width, double height) { - _resized_signal.emit (width, height); + _resized_signal.emit(width, height); } -void View::requestRedraw() +void View::requestRedraw() { _redraw_requested_signal.emit(); } -void View::setDocument(SPDocument *doc) { +void View::setDocument(SPDocument *doc) +{ g_return_if_fail(doc != nullptr); if (_doc) { @@ -117,14 +117,14 @@ void View::setDocument(SPDocument *doc) { INKSCAPE.add_document(doc); _doc = doc; - _document_uri_set_connection = - _doc->connectURISet(sigc::bind(sigc::ptr_fun(&_onDocumentURISet), this)); - _document_resized_connection = - _doc->connectResized(sigc::bind(sigc::ptr_fun(&_onDocumentResized), this)); - _document_uri_set_signal.emit( _doc->getDocumentURI() ); + _document_uri_set_connection = _doc->connectURISet(sigc::bind(sigc::ptr_fun(&_onDocumentURISet), this)); + _document_resized_connection = _doc->connectResized(sigc::bind(sigc::ptr_fun(&_onDocumentResized), this)); + _document_uri_set_signal.emit(_doc->getDocumentURI()); } -}}} +} // namespace View +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/view/view.h b/src/ui/view/view.h index 3acfd2c1c7aed844e122a3d0a540ce19155690e7..494e77af9cf8bacb41dae981ca3714dd596165ff 100644 --- a/src/ui/view/view.h +++ b/src/ui/view/view.h @@ -12,53 +12,60 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gdk/gdk.h> +#include <2geom/forward.h> #include <cstddef> +#include <gdk/gdk.h> #include <memory> #include <sigc++/connection.h> -#include "message.h" -#include "inkgc/gc-managed.h" -#include "gc-finalized.h" + #include "gc-anchored.h" -#include <2geom/forward.h> +#include "gc-finalized.h" +#include "inkgc/gc-managed.h" +#include "message.h" /** * Iterates until true or returns false. * When used as signal accumulator, stops emission if one slot returns true. */ -struct StopOnTrue { - typedef bool result_type; - - template<typename T_iterator> - result_type operator()(T_iterator first, T_iterator last) const{ - for (; first != last; ++first) - if (*first) return true; - return false; - } +struct StopOnTrue +{ + typedef bool result_type; + + template <typename T_iterator> + result_type operator()(T_iterator first, T_iterator last) const + { + for (; first != last; ++first) + if (*first) + return true; + return false; + } }; /** * Iterates until nonzero or returns 0. * When used as signal accumulator, stops emission if one slot returns nonzero. */ -struct StopOnNonZero { - typedef int result_type; - - template<typename T_iterator> - result_type operator()(T_iterator first, T_iterator last) const{ - for (; first != last; ++first) - if (*first) return *first; - return 0; - } +struct StopOnNonZero +{ + typedef int result_type; + + template <typename T_iterator> + result_type operator()(T_iterator first, T_iterator last) const + { + for (; first != last; ++first) + if (*first) + return *first; + return 0; + } }; class SPDocument; namespace Inkscape { - class MessageContext; - class MessageStack; - namespace UI { - namespace View { +class MessageContext; +class MessageStack; +namespace UI { +namespace View { /** * View is an abstract base class of all UI document views. This @@ -67,12 +74,12 @@ namespace Inkscape { * similar views. The View base class has very little functionality of * its own. */ -class View : public GC::Managed<>, - public GC::Finalized, - public GC::Anchored +class View + : public GC::Managed<> + , public GC::Finalized + , public GC::Anchored { public: - View(); /** @@ -83,23 +90,20 @@ public: void close() { _close(); } /// Returns a pointer to the view's document. - SPDocument *doc() const - { return _doc; } + SPDocument *doc() const { return _doc; } /// Returns a pointer to the view's message stack. - std::shared_ptr<Inkscape::MessageStack> messageStack() const - { return _message_stack; } + std::shared_ptr<Inkscape::MessageStack> messageStack() const { return _message_stack; } /// Returns a pointer to the view's tipsMessageContext. - Inkscape::MessageContext *tipsMessageContext() const - { return _tips_message_context.get(); } + Inkscape::MessageContext *tipsMessageContext() const { return _tips_message_context.get(); } void emitResized(gdouble width, gdouble height); void requestRedraw(); - virtual void onResized (double, double) {}; - virtual void onRedrawRequested() {}; - virtual void onStatusMessage (Inkscape::MessageType type, gchar const *message) {}; - virtual void onDocumentURISet (gchar const* uri) {}; - virtual void onDocumentResized (double, double) {}; + virtual void onResized(double, double){}; + virtual void onRedrawRequested(){}; + virtual void onStatusMessage(Inkscape::MessageType type, gchar const *message){}; + virtual void onDocumentURISet(gchar const *uri){}; + virtual void onDocumentResized(double, double){}; virtual bool shutdown() { return false; }; protected: @@ -110,19 +114,19 @@ protected: virtual void _close(); /** - * Disconnects the view from the document signals, connects the view + * Disconnects the view from the document signals, connects the view * to a new one, and emits the _document_set_signal on the view. * * This is code common to all subclasses and called from their * setDocument() methods after they are done. - * + * * @param doc The new document to connect the view to. */ virtual void setDocument(SPDocument *doc); - sigc::signal<void,double,double> _resized_signal; - sigc::signal<void,gchar const*> _document_uri_set_signal; - sigc::signal<void> _redraw_requested_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 _resized_connection; @@ -132,9 +136,11 @@ private: sigc::connection _document_resized_connection; // foreign }; -}}} +} // namespace View +} // namespace UI +} // namespace Inkscape -#endif // INKSCAPE_UI_VIEW_VIEW_H +#endif // INKSCAPE_UI_VIEW_VIEW_H /* Local Variables: diff --git a/src/ui/widget/alignment-selector.cpp b/src/ui/widget/alignment-selector.cpp index 11d11668161dacdb1b3810ba1714bd8a9287d3d7..ffdcaca4063beb4fe43dbab725a24f4c359f8aad 100644 --- a/src/ui/widget/alignment-selector.cpp +++ b/src/ui/widget/alignment-selector.cpp @@ -6,16 +6,18 @@ */ #include "ui/widget/alignment-selector.h" -#include "ui/icon-loader.h" -#include "ui/icon-names.h" #include <gtkmm/image.h> +#include "ui/icon-loader.h" +#include "ui/icon-names.h" + namespace Inkscape { namespace UI { namespace Widget { -void AlignmentSelector::setupButton(const Glib::ustring& icon, Gtk::Button& button) { +void AlignmentSelector::setupButton(const Glib::ustring &icon, Gtk::Button &button) +{ Gtk::Image *buttonIcon = Gtk::manage(sp_get_icon_image(icon, Gtk::ICON_SIZE_SMALL_TOOLBAR)); buttonIcon->show(); @@ -44,9 +46,8 @@ AlignmentSelector::AlignmentSelector() _container.set_row_homogeneous(); _container.set_column_homogeneous(true); - for(int i = 0; i < 9; ++i) { - _buttons[i].signal_clicked().connect( - sigc::bind(sigc::mem_fun(*this, &AlignmentSelector::btn_activated), i)); + for (int i = 0; i < 9; ++i) { + _buttons[i].signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &AlignmentSelector::btn_activated), i)); _container.attach(_buttons[i], i % 3, i / 3, 1, 1); } diff --git a/src/ui/widget/alignment-selector.h b/src/ui/widget/alignment-selector.h index 5bcf0fa4f555f41a2159431b4eb30159abd7f704..e8caf70b3d29c3a27e56467747e2f0e100cd5cf6 100644 --- a/src/ui/widget/alignment-selector.h +++ b/src/ui/widget/alignment-selector.h @@ -20,7 +20,7 @@ class AlignmentSelector : public Gtk::Bin { private: Gtk::Button _buttons[9]; - Gtk::Grid _container; + Gtk::Grid _container; sigc::signal<void, int> _alignmentClicked; @@ -28,7 +28,6 @@ private: void btn_activated(int index); public: - sigc::signal<void, int> &on_alignmentClicked() { return _alignmentClicked; } AlignmentSelector(); diff --git a/src/ui/widget/anchor-selector.cpp b/src/ui/widget/anchor-selector.cpp index b151a81ea8b8a0d8d70368cad5e3489a0b3ea817..ea4b482535127a03bb63e91ffc81a5970dcec74c 100644 --- a/src/ui/widget/anchor-selector.cpp +++ b/src/ui/widget/anchor-selector.cpp @@ -8,16 +8,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "ui/widget/anchor-selector.h" -#include "ui/icon-loader.h" -#include "ui/icon-names.h" #include <gtkmm/image.h> +#include "ui/icon-loader.h" +#include "ui/icon-names.h" + namespace Inkscape { namespace UI { namespace Widget { -void AnchorSelector::setupButton(const Glib::ustring& icon, Gtk::ToggleButton& button) { +void AnchorSelector::setupButton(const Glib::ustring &icon, Gtk::ToggleButton &button) +{ Gtk::Image *buttonIcon = Gtk::manage(sp_get_icon_image(icon, Gtk::ICON_SIZE_SMALL_TOOLBAR)); buttonIcon->show(); @@ -28,7 +30,7 @@ void AnchorSelector::setupButton(const Glib::ustring& icon, Gtk::ToggleButton& b } AnchorSelector::AnchorSelector() - : _container() + : _container() { set_halign(Gtk::ALIGN_CENTER); setupButton(INKSCAPE_ICON("boundingbox_top_left"), _buttons[0]); @@ -57,15 +59,14 @@ AnchorSelector::AnchorSelector() AnchorSelector::~AnchorSelector() { - // TODO Auto-generated destructor stub + // TODO Auto-generated destructor stub } void AnchorSelector::btn_activated(int index) { if (_selection == index && _buttons[index].get_active() == false) { _buttons[index].set_active(true); - } - else if (_selection != index && _buttons[index].get_active()) { + } else if (_selection != index && _buttons[index].get_active()) { int old_selection = _selection; _selection = index; _buttons[old_selection].set_active(false); diff --git a/src/ui/widget/anchor-selector.h b/src/ui/widget/anchor-selector.h index 49ce0b29fd2140a12e7d31c780be2fbc91f075a4..d499183bc0cb6741df16d4fcccbf738fda23c172 100644 --- a/src/ui/widget/anchor-selector.h +++ b/src/ui/widget/anchor-selector.h @@ -12,8 +12,8 @@ #define ANCHOR_SELECTOR_H_ #include <gtkmm/bin.h> -#include <gtkmm/togglebutton.h> #include <gtkmm/grid.h> +#include <gtkmm/togglebutton.h> namespace Inkscape { namespace UI { @@ -22,26 +22,25 @@ namespace Widget { class AnchorSelector : public Gtk::Bin { private: - Gtk::ToggleButton _buttons[9]; - int _selection; - Gtk::Grid _container; + Gtk::ToggleButton _buttons[9]; + int _selection; + Gtk::Grid _container; - sigc::signal<void> _selectionChanged; + sigc::signal<void> _selectionChanged; - void setupButton(const Glib::ustring &icon, Gtk::ToggleButton &button); - void btn_activated(int index); + void setupButton(const Glib::ustring &icon, Gtk::ToggleButton &button); + void btn_activated(int index); public: + int getHorizontalAlignment() { return _selection % 3; } + int getVerticalAlignment() { return _selection / 3; } - int getHorizontalAlignment() { return _selection % 3; } - int getVerticalAlignment() { return _selection / 3; } - - sigc::signal<void> &on_selectionChanged() { return _selectionChanged; } + sigc::signal<void> &on_selectionChanged() { return _selectionChanged; } - void setAlignment(int horizontal, int vertical); + void setAlignment(int horizontal, int vertical); - AnchorSelector(); - ~AnchorSelector() override; + AnchorSelector(); + ~AnchorSelector() override; }; } // namespace Widget diff --git a/src/ui/widget/attr-widget.h b/src/ui/widget/attr-widget.h index ce5fe12e26dcbdb334c4f44555ad4d171d3d8987..9b452200a2fb6040f10aa6b376ff7a95555e7cb8 100644 --- a/src/ui/widget/attr-widget.h +++ b/src/ui/widget/attr-widget.h @@ -36,72 +36,82 @@ enum DefaultValueType class DefaultValueHolder { DefaultValueType type; - union { + union + { double d_val; - std::vector<double>* vt_val; + std::vector<double> *vt_val; bool b_val; unsigned int uint_val; - char* cptr_val; + char *cptr_val; } value; - //FIXME remove copy ctor and assignment operator as private to avoid double free of the vector + // FIXME remove copy ctor and assignment operator as private to avoid double free of the vector public: - DefaultValueHolder () { - type = T_NONE; - } + DefaultValueHolder() { type = T_NONE; } - DefaultValueHolder (double d) { + DefaultValueHolder(double d) + { type = T_DOUBLE; value.d_val = d; } - DefaultValueHolder (std::vector<double>* d) { + DefaultValueHolder(std::vector<double> *d) + { type = T_VECT_DOUBLE; value.vt_val = d; } - DefaultValueHolder (char* c) { + DefaultValueHolder(char *c) + { type = T_CHARPTR; value.cptr_val = c; } - DefaultValueHolder (bool d) { + DefaultValueHolder(bool d) + { type = T_BOOL; value.b_val = d; } - DefaultValueHolder (unsigned int ui) { + DefaultValueHolder(unsigned int ui) + { type = T_UINT; value.uint_val = ui; } - ~DefaultValueHolder() { + ~DefaultValueHolder() + { if (type == T_VECT_DOUBLE) delete value.vt_val; } - unsigned int as_uint() { - g_assert (type == T_UINT); + unsigned int as_uint() + { + g_assert(type == T_UINT); return value.uint_val; } - bool as_bool() { - g_assert (type == T_BOOL); + bool as_bool() + { + g_assert(type == T_BOOL); return value.b_val; } - double as_double() { - g_assert (type == T_DOUBLE); + double as_double() + { + g_assert(type == T_DOUBLE); return value.d_val; } - std::vector<double>* as_vector() { - g_assert (type == T_VECT_DOUBLE); + std::vector<double> *as_vector() + { + g_assert(type == T_VECT_DOUBLE); return value.vt_val; } - char* as_charptr() { - g_assert (type == T_CHARPTR); + char *as_charptr() + { + g_assert(type == T_CHARPTR); return value.cptr_val; } }; @@ -110,52 +120,46 @@ class AttrWidget { public: AttrWidget(const SPAttr a, unsigned int value) - : _attr(a), - _default(value) + : _attr(a) + , _default(value) {} AttrWidget(const SPAttr a, double value) - : _attr(a), - _default(value) + : _attr(a) + , _default(value) {} AttrWidget(const SPAttr a, bool value) - : _attr(a), - _default(value) + : _attr(a) + , _default(value) {} - - AttrWidget(const SPAttr a, char* value) - : _attr(a), - _default(value) + + AttrWidget(const SPAttr a, char *value) + : _attr(a) + , _default(value) {} - + AttrWidget(const SPAttr a) - : _attr(a), - _default() + : _attr(a) + , _default() {} - virtual ~AttrWidget() - = default; + virtual ~AttrWidget() = default; virtual Glib::ustring get_as_attribute() const = 0; - virtual void set_from_attribute(SPObject*) = 0; + virtual void set_from_attribute(SPObject *) = 0; - SPAttr get_attribute() const - { - return _attr; - } + SPAttr get_attribute() const { return _attr; } + + sigc::signal<void> &signal_attr_changed() { return _signal; } - sigc::signal<void>& signal_attr_changed() - { - return _signal; - } protected: - DefaultValueHolder* get_default() { return &_default; } - const gchar* attribute_value(SPObject* o) const + DefaultValueHolder *get_default() { return &_default; } + const gchar *attribute_value(SPObject *o) const { - const gchar* name = (const gchar*)sp_attribute_name(_attr); - if(name && o) { - const gchar* val = o->getRepr()->attribute(name); + const gchar *name = (const gchar *)sp_attribute_name(_attr); + if (name && o) { + const gchar *val = o->getRepr()->attribute(name); return val; } return nullptr; @@ -167,9 +171,9 @@ private: sigc::signal<void> _signal; }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/widget/button.cpp b/src/ui/widget/button.cpp index f119c069f936672d9c827dddbd8ce660071ebdc3..fda7a0351314a5ca12b85e474d7292cea7a9ffa6 100644 --- a/src/ui/widget/button.cpp +++ b/src/ui/widget/button.cpp @@ -13,9 +13,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "button.h" + #include <glibmm.h> -#include "button.h" #include "helper/action-context.h" #include "helper/action.h" #include "shortcuts.h" @@ -38,8 +39,7 @@ Button::~Button() } } -void -Button::get_preferred_width_vfunc(int &minimal_width, int &natural_width) const +void Button::get_preferred_width_vfunc(int &minimal_width, int &natural_width) const { auto child = get_child(); @@ -59,8 +59,7 @@ Button::get_preferred_width_vfunc(int &minimal_width, int &natural_width) const natural_width += MAX(2, padding.get_left() + padding.get_right() + border.get_left() + border.get_right()); } -void -Button::get_preferred_height_vfunc(int &minimal_height, int &natural_height) const +void Button::get_preferred_height_vfunc(int &minimal_height, int &natural_height) const { auto child = get_child(); @@ -80,48 +79,41 @@ Button::get_preferred_height_vfunc(int &minimal_height, int &natural_height) con natural_height += MAX(2, padding.get_top() + padding.get_bottom() + border.get_top() + border.get_bottom()); } -void -Button::on_clicked() +void Button::on_clicked() { if (_type == BUTTON_TYPE_TOGGLE) { Gtk::Button::on_clicked(); } } -bool -Button::process_event(GdkEvent *event) +bool Button::process_event(GdkEvent *event) { switch (event->type) { - case GDK_2BUTTON_PRESS: - if (_doubleclick_action) { - sp_action_perform(_doubleclick_action, nullptr); - } - return true; - break; - default: - break; + case GDK_2BUTTON_PRESS: + if (_doubleclick_action) { + sp_action_perform(_doubleclick_action, nullptr); + } + return true; + break; + default: + break; } return false; } -void -Button::perform_action() +void Button::perform_action() { if (_action) { sp_action_perform(_action, nullptr); } } -Button::Button(GtkIconSize size, - ButtonType type, - SPAction *action, - SPAction *doubleclick_action) - : - _action(nullptr), - _doubleclick_action(nullptr), - _type(type), - _lsize(CLAMP(size, GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_DIALOG)) +Button::Button(GtkIconSize size, ButtonType type, SPAction *action, SPAction *doubleclick_action) + : _action(nullptr) + , _doubleclick_action(nullptr) + , _type(type) + , _lsize(CLAMP(size, GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_DIALOG)) { set_border_width(0); @@ -142,16 +134,14 @@ Button::Button(GtkIconSize size, set_relief(Gtk::RELIEF_NONE); } -void -Button::toggle_set_down(bool down) +void Button::toggle_set_down(bool down) { _on_clicked.block(); set_active(down); _on_clicked.unblock(); } -void -Button::set_doubleclick_action(SPAction *action) +void Button::set_doubleclick_action(SPAction *action) { if (_doubleclick_action) { g_object_unref(_doubleclick_action); @@ -162,8 +152,7 @@ Button::set_doubleclick_action(SPAction *action) } } -void -Button::set_action(SPAction *action) +void Button::set_action(SPAction *action) { Gtk::Widget *child; @@ -180,11 +169,9 @@ Button::set_action(SPAction *action) _action = action; if (action) { g_object_ref(action); - _c_set_active = action->signal_set_active.connect( - sigc::mem_fun(*this, &Button::action_set_active)); + _c_set_active = action->signal_set_active.connect(sigc::mem_fun(*this, &Button::action_set_active)); - _c_set_sensitive = action->signal_set_sensitive.connect( - sigc::mem_fun(*this, &Gtk::Widget::set_sensitive)); + _c_set_sensitive = action->signal_set_sensitive.connect(sigc::mem_fun(*this, &Gtk::Widget::set_sensitive)); if (action->image) { child = Glib::wrap(sp_get_icon_image(action->image, _lsize)); @@ -196,8 +183,7 @@ Button::set_action(SPAction *action) set_composed_tooltip(action); } -void -Button::action_set_active(bool active) +void Button::action_set_active(bool active) { if (_type != BUTTON_TYPE_TOGGLE) { return; @@ -209,8 +195,7 @@ Button::action_set_active(bool active) } } -void -Button::set_composed_tooltip(SPAction *action) +void Button::set_composed_tooltip(SPAction *action) { if (action) { unsigned int shortcut = sp_shortcut_get_primary(action->verb); @@ -233,16 +218,11 @@ Button::set_composed_tooltip(SPAction *action) } } -Button::Button(GtkIconSize size, - ButtonType type, - Inkscape::UI::View::View *view, - const gchar *name, - const gchar *tip) - : - _action(nullptr), - _doubleclick_action(nullptr), - _type(type), - _lsize(CLAMP(size, GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_DIALOG)) +Button::Button(GtkIconSize size, ButtonType type, Inkscape::UI::View::View *view, const gchar *name, const gchar *tip) + : _action(nullptr) + , _doubleclick_action(nullptr) + , _type(type) + , _lsize(CLAMP(size, GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_DIALOG)) { set_border_width(0); diff --git a/src/ui/widget/button.h b/src/ui/widget/button.h index 0b1bfc200cc8798e1bd94f0799b79fd5588d4e49..747576d52ce5562b719b972ccfcc5b41c3ac2356 100644 --- a/src/ui/widget/button.h +++ b/src/ui/widget/button.h @@ -25,12 +25,14 @@ class View; namespace Widget { -enum ButtonType { +enum ButtonType +{ BUTTON_TYPE_NORMAL, BUTTON_TYPE_TOGGLE }; -class Button : public Gtk::ToggleButton{ +class Button : public Gtk::ToggleButton +{ private: ButtonType _type; GtkIconSize _lsize; @@ -56,16 +58,9 @@ protected: void on_clicked() override; public: - Button(GtkIconSize size, - ButtonType type, - SPAction *action, - SPAction *doubleclick_action); - - Button(GtkIconSize size, - ButtonType type, - Inkscape::UI::View::View *view, - const gchar *name, - const gchar *tip); + Button(GtkIconSize size, ButtonType type, SPAction *action, SPAction *doubleclick_action); + + Button(GtkIconSize size, ButtonType type, Inkscape::UI::View::View *view, const gchar *name, const gchar *tip); ~Button() override; diff --git a/src/ui/widget/canvas-grid.cpp b/src/ui/widget/canvas-grid.cpp index 5b78c9d4607dc8c7adb2a5be235dac0d3df29e00..fa11af67d6360e5093831e6eed681e76becdc3e8 100644 --- a/src/ui/widget/canvas-grid.cpp +++ b/src/ui/widget/canvas-grid.cpp @@ -11,24 +11,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - // The scrollbars, and canvas are tightly coupled so it makes sense to have a dedicated // widget to handle their interactions. The buttons are along for the ride. I don't see // how to add the buttons easily via a .ui file (which would allow the user to put any // buttons they want in their place). +#include "canvas-grid.h" + #include <glibmm/i18n.h> -#include "canvas-grid.h" +#include "desktop-events.h" // Hopefully temp. +#include "desktop.h" // Hopefully temp. +#include "display/canvas-arena.h" // Hopefully temp. +#include "ui/icon-loader.h" #include "ui/widget/canvas.h" - #include "ui/widget/ink-ruler.h" -#include "ui/icon-loader.h" - -#include "widgets/desktop-widget.h" // Hopefully temp. -#include "display/canvas-arena.h" // Hopefully temp. -#include "desktop.h" // Hopefully temp. -#include "desktop-events.h" // Hopefully temp. +#include "widgets/desktop-widget.h" // Hopefully temp. namespace Inkscape { namespace UI { @@ -68,11 +66,11 @@ CanvasGrid::CanvasGrid(SPDesktopWidget *dtw) // For creating guides, etc. _hruler->signal_button_press_event().connect( - sigc::bind(sigc::mem_fun(*_dtw, &SPDesktopWidget::on_ruler_box_button_press_event), _hruler, true)); + sigc::bind(sigc::mem_fun(*_dtw, &SPDesktopWidget::on_ruler_box_button_press_event), _hruler, true)); _hruler->signal_button_release_event().connect( sigc::bind(sigc::mem_fun(*_dtw, &SPDesktopWidget::on_ruler_box_button_release_event), _hruler, true)); _hruler->signal_motion_notify_event().connect( - sigc::bind(sigc::mem_fun(*_dtw, &SPDesktopWidget::on_ruler_box_motion_notify_event), _hruler, true)); + sigc::bind(sigc::mem_fun(*_dtw, &SPDesktopWidget::on_ruler_box_motion_notify_event), _hruler, true)); // Vertical Ruler _vruler = Gtk::manage(new Inkscape::UI::Widget::Ruler(Gtk::ORIENTATION_VERTICAL)); @@ -82,11 +80,11 @@ CanvasGrid::CanvasGrid(SPDesktopWidget *dtw) // For creating guides, etc. _vruler->signal_button_press_event().connect( - sigc::bind(sigc::mem_fun(*_dtw, &SPDesktopWidget::on_ruler_box_button_press_event), _vruler, false)); + sigc::bind(sigc::mem_fun(*_dtw, &SPDesktopWidget::on_ruler_box_button_press_event), _vruler, false)); _vruler->signal_button_release_event().connect( sigc::bind(sigc::mem_fun(*_dtw, &SPDesktopWidget::on_ruler_box_button_release_event), _vruler, false)); _vruler->signal_motion_notify_event().connect( - sigc::bind(sigc::mem_fun(*_dtw, &SPDesktopWidget::on_ruler_box_motion_notify_event), _vruler, false)); + sigc::bind(sigc::mem_fun(*_dtw, &SPDesktopWidget::on_ruler_box_motion_notify_event), _vruler, false)); // Guide Lock auto image1 = Gtk::manage(new Gtk::Image("object-locked", Gtk::ICON_SIZE_MENU)); @@ -120,18 +118,18 @@ CanvasGrid::CanvasGrid(SPDesktopWidget *dtw) _sticky_zoom->set_tooltip_text(_("Zoom drawing if window size changes")); // Top row - attach(*_guide_lock, 0, 0, 1, 1); - attach(*_hruler, 1, 0, 1, 1); + attach(*_guide_lock, 0, 0, 1, 1); + attach(*_hruler, 1, 0, 1, 1); attach(*_sticky_zoom, 2, 0, 1, 1); // Middle row - attach(*_vruler, 0, 1, 1, 1); - attach(*_canvas, 1, 1, 1, 1); - attach(*_vscrollbar, 2, 1, 1, 1); + attach(*_vruler, 0, 1, 1, 1); + attach(*_canvas, 1, 1, 1, 1); + attach(*_vscrollbar, 2, 1, 1, 1); // Bottom row - attach(*_hscrollbar, 1, 2, 1, 1); - attach(*_cms_adjust, 2, 2, 1, 1); + attach(*_hscrollbar, 1, 2, 1, 1); + attach(*_cms_adjust, 2, 2, 1, 1); // Update rulers on size change. signal_size_allocate().connect(sigc::mem_fun(*this, &CanvasGrid::OnSizeAllocate)); @@ -141,32 +139,30 @@ CanvasGrid::CanvasGrid(SPDesktopWidget *dtw) // _dt2r should be a member of _canvas. // get_display_area should be a member of _canvas. -void -CanvasGrid::UpdateRulers() +void CanvasGrid::UpdateRulers() { Geom::Rect viewbox = _dtw->desktop->get_display_area(true).bounds(); // "true" means: Use integer values of the canvas for calculating the display area, similar - // to the integer values used for positioning the grid lines. (see SPCanvas::scrollTo(), + // to the integer values used for positioning the grid lines. (see SPCanvas::scrollTo(), // where ix and iy are rounded integer values; these values are stored in SPCanvasBuf->rect, - // and used for drawing the grid). By using the integer values here too, the ruler ticks + // and used for drawing the grid). By using the integer values here too, the ruler ticks // will be perfectly aligned to the grid double _dt2r = _dtw->_dt2r; Geom::Point _ruler_origin = _dtw->_ruler_origin; - double lower_x = _dt2r * (viewbox.left() - _ruler_origin[Geom::X]); + double lower_x = _dt2r * (viewbox.left() - _ruler_origin[Geom::X]); double upper_x = _dt2r * (viewbox.right() - _ruler_origin[Geom::X]); _hruler->set_range(lower_x, upper_x); double lower_y = _dt2r * (viewbox.bottom() - _ruler_origin[Geom::Y]); - double upper_y = _dt2r * (viewbox.top() - _ruler_origin[Geom::Y]); + double upper_y = _dt2r * (viewbox.top() - _ruler_origin[Geom::Y]); if (_dtw->desktop->is_yaxisdown()) { std::swap(lower_y, upper_y); } _vruler->set_range(lower_y, upper_y); } -void -CanvasGrid::ShowScrollbars(bool state) +void CanvasGrid::ShowScrollbars(bool state) { _show_scrollbars = state; @@ -185,8 +181,7 @@ CanvasGrid::ShowScrollbars(bool state) } } -void -CanvasGrid::ToggleScrollbars() +void CanvasGrid::ToggleScrollbars() { _show_scrollbars = !_show_scrollbars; ShowScrollbars(_show_scrollbars); @@ -197,8 +192,7 @@ CanvasGrid::ToggleScrollbars() prefs->setBool("/window/scrollbars/state", _show_scrollbars); } -void -CanvasGrid::ShowRulers(bool state) +void CanvasGrid::ShowRulers(bool state) { // Sticky zoom button is always shown. We must adjust canvas when rulers are toggled or canvas // won't expand fully. @@ -221,8 +215,7 @@ CanvasGrid::ShowRulers(bool state) } } -void -CanvasGrid::ToggleRulers() +void CanvasGrid::ToggleRulers() { _show_rulers = !_show_rulers; ShowRulers(_show_rulers); @@ -234,8 +227,7 @@ CanvasGrid::ToggleRulers() } // Update rulers on change of widget size, but only if allocation really changed. -void -CanvasGrid::OnSizeAllocate(Gtk::Allocation& allocation) +void CanvasGrid::OnSizeAllocate(Gtk::Allocation &allocation) { if (!(_allocation == allocation)) { // No != function defined! _allocation = allocation; @@ -244,8 +236,7 @@ CanvasGrid::OnSizeAllocate(Gtk::Allocation& allocation) } // This belong in Canvas class -bool -CanvasGrid::SignalEvent(GdkEvent *event) +bool CanvasGrid::SignalEvent(GdkEvent *event) { if (event->type == GDK_BUTTON_PRESS) { _canvas->grab_focus(); @@ -253,9 +244,9 @@ CanvasGrid::SignalEvent(GdkEvent *event) if (event->type == GDK_BUTTON_PRESS && event->button.button == 3) { if (event->button.state & GDK_SHIFT_MASK) { - sp_canvas_arena_set_sticky (SP_CANVAS_ARENA (_dtw->desktop->drawing), true); + sp_canvas_arena_set_sticky(SP_CANVAS_ARENA(_dtw->desktop->drawing), true); } else { - sp_canvas_arena_set_sticky (SP_CANVAS_ARENA (_dtw->desktop->drawing), false); + sp_canvas_arena_set_sticky(SP_CANVAS_ARENA(_dtw->desktop->drawing), false); } } @@ -266,9 +257,8 @@ CanvasGrid::SignalEvent(GdkEvent *event) // 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 ((event->type == GDK_KEY_PRESS || event->type == GDK_KEY_RELEASE) - && !_canvas->get_current_item()) { - return sp_desktop_root_handler (nullptr, event, _dtw->desktop); + if ((event->type == GDK_KEY_PRESS || event->type == GDK_KEY_RELEASE) && !_canvas->get_current_item()) { + return sp_desktop_root_handler(nullptr, event, _dtw->desktop); } } return false; @@ -279,7 +269,6 @@ CanvasGrid::SignalEvent(GdkEvent *event) // * CMS Adjust // * Guide Lock - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/canvas-grid.h b/src/ui/widget/canvas-grid.h index 24c84baa9a93f2f71c451409d181eeb17cbf9df4..bd927c416061dc752c8e8816ababe79debdeea4a 100644 --- a/src/ui/widget/canvas-grid.h +++ b/src/ui/widget/canvas-grid.h @@ -25,11 +25,10 @@ class Ruler; /** * A Gtk::Grid widget that contains rulers, scrollbars, buttons, and, of course, the canvas. - */ + */ class CanvasGrid : public Gtk::Grid { public: - CanvasGrid(SPDesktopWidget *dtw); void ShowScrollbars(bool state = true); @@ -46,14 +45,13 @@ public: Inkscape::UI::Widget::Ruler *GetVRuler() { return _hruler; }; Glib::RefPtr<Gtk::Adjustment> GetHAdj() { return _hadj; }; Glib::RefPtr<Gtk::Adjustment> GetVAdj() { return _vadj; }; - Gtk::ToggleButton *GetGuideLock() { return _guide_lock; } - Gtk::ToggleButton *GetCmsAdjust() { return _cms_adjust; } + Gtk::ToggleButton *GetGuideLock() { return _guide_lock; } + Gtk::ToggleButton *GetCmsAdjust() { return _cms_adjust; } Gtk::ToggleButton *GetStickyZoom() { return _sticky_zoom; }; private: - // Signal callbacks - void OnSizeAllocate(Gtk::Allocation& allocation); + void OnSizeAllocate(Gtk::Allocation &allocation); bool SignalEvent(GdkEvent *event); // The Widgets @@ -61,8 +59,8 @@ private: Glib::RefPtr<Gtk::Adjustment> _hadj; Glib::RefPtr<Gtk::Adjustment> _vadj; - Gtk::Scrollbar *_hscrollbar; - Gtk::Scrollbar *_vscrollbar; + Gtk::Scrollbar *_hscrollbar; + Gtk::Scrollbar *_vscrollbar; Inkscape::UI::Widget::Ruler *_hruler; Inkscape::UI::Widget::Ruler *_vruler; @@ -86,7 +84,6 @@ private: } // namespace UI } // namespace Inkscape - #endif // INKSCAPE_UI_WIDGET_CANVASGRID_H /* diff --git a/src/ui/widget/canvas.cpp b/src/ui/widget/canvas.cpp index d487b8310f5d449a9acf45930ff8bb0ed05840bc..e78cdc2e697a249fe97d1a9cc0464439da1d6315 100644 --- a/src/ui/widget/canvas.cpp +++ b/src/ui/widget/canvas.cpp @@ -11,26 +11,22 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <iostream> - -#include <glibmm/i18n.h> +#include "canvas.h" #include <2geom/rect.h> +#include <glibmm/i18n.h> +#include <iostream> -#include "canvas.h" #include "canvas-grid.h" - -#include "color.h" // Background color -#include "cms-system.h" // Color correction -#include "inkscape.h" // SP_ACTIVE_DESKTOP TEMP TEMP TEMP -#include "preferences.h" - -#include "display/sp-canvas-item.h" // Canvas group TEMP TEMP TEMP -#include "display/sp-canvas-group.h" // Canvas group TEMP TEMP TEMP -#include "display/canvas-arena.h" // Change rendering mode +#include "cms-system.h" // Color correction +#include "color.h" // Background color #include "display/cairo-utils.h" // Checkerboard background. - -#include "ui/tools/tool-base.h" // Default cursor +#include "display/canvas-arena.h" // Change rendering mode +#include "display/sp-canvas-group.h" // Canvas group TEMP TEMP TEMP +#include "display/sp-canvas-item.h" // Canvas group TEMP TEMP TEMP +#include "inkscape.h" // SP_ACTIVE_DESKTOP TEMP TEMP TEMP +#include "preferences.h" +#include "ui/tools/tool-base.h" // Default cursor /** * Helper function to update item and its children. @@ -54,8 +50,8 @@ static void sp_canvas_item_invoke_update2(SPCanvasItem *item, Geom::Affine const } if (child_flags & (SP_CANVAS_UPDATE_REQUESTED | SP_CANVAS_UPDATE_AFFINE)) { - if (SP_CANVAS_ITEM_GET_CLASS (item)->update) { - SP_CANVAS_ITEM_GET_CLASS (item)->update(item, child_affine, child_flags); + if (SP_CANVAS_ITEM_GET_CLASS(item)->update) { + SP_CANVAS_ITEM_GET_CLASS(item)->update(item, child_affine, child_flags); } } @@ -63,7 +59,8 @@ static void sp_canvas_item_invoke_update2(SPCanvasItem *item, Geom::Affine const item->need_affine = FALSE; } -struct PaintRectSetup { +struct PaintRectSetup +{ Geom::IntRect canvas_rect; gint64 start_time; int max_pixels; @@ -88,22 +85,14 @@ namespace Inkscape { namespace UI { namespace Widget { - Canvas::Canvas() { set_name("InkscapeCanvas"); // Events - add_events(Gdk::BUTTON_PRESS_MASK | - Gdk::BUTTON_RELEASE_MASK | - Gdk::ENTER_NOTIFY_MASK | - Gdk::LEAVE_NOTIFY_MASK | - Gdk::FOCUS_CHANGE_MASK | - Gdk::KEY_PRESS_MASK | - Gdk::KEY_RELEASE_MASK | - Gdk::POINTER_MOTION_MASK | - Gdk::SCROLL_MASK | - Gdk::SMOOTH_SCROLL_MASK ); + add_events(Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK | Gdk::ENTER_NOTIFY_MASK | Gdk::LEAVE_NOTIFY_MASK | + Gdk::FOCUS_CHANGE_MASK | Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK | Gdk::POINTER_MOTION_MASK | + Gdk::SCROLL_MASK | Gdk::SMOOTH_SCROLL_MASK); // Give _pick_event an initial definition. _pick_event.type = GDK_LEAVE_NOTIFY; @@ -131,28 +120,25 @@ Canvas::~Canvas() /** * Is world point inside of canvas area? */ -bool -Canvas::world_point_inside_canvas(Geom::Point const &world) +bool Canvas::world_point_inside_canvas(Geom::Point const &world) { Gtk::Allocation allocation = get_allocation(); - return ( (_x0 <= world.x()) && (world.x() < _x0 + allocation.get_width()) && - (_y0 <= world.y()) && (world.y() < _y0 + allocation.get_height()) ); + return ((_x0 <= world.x()) && (world.x() < _x0 + allocation.get_width()) && (_y0 <= world.y()) && + (world.y() < _y0 + allocation.get_height())); } /** * Translate point in canvas to world coordinates. */ -Geom::Point -Canvas::canvas_to_world(Geom::Point const &point) +Geom::Point Canvas::canvas_to_world(Geom::Point const &point) { - return Geom::Point(point[Geom::X]+ _x0, point[Geom::Y] + _y0); + return Geom::Point(point[Geom::X] + _x0, point[Geom::Y] + _y0); } /** * Return the area shown in the canvas in world coordinates. */ -Geom::Rect -Canvas::get_area_world() +Geom::Rect Canvas::get_area_world() { // This is called by desktop.cpp before Canvas::on_draw() is called (and on_realize()) so // we don't rely on stored allocation value. @@ -163,8 +149,7 @@ Canvas::get_area_world() /** * Return the area showin the canvas in world coordinates, rounded to integer values. */ -Geom::IntRect -Canvas::get_area_world_int() +Geom::IntRect Canvas::get_area_world_int() { Gtk::Allocation allocation = get_allocation(); return Geom::IntRect::from_xywh(_x0, _y0, allocation.get_width(), allocation.get_height()); @@ -173,8 +158,7 @@ Canvas::get_area_world_int() /** * Invalidate drawing and redraw during idle. */ -void -Canvas::redraw_all() +void Canvas::redraw_all() { if (_in_destruction) { std::cerr << "Canvas::redraw_all: Called after canvas destroyed!" << std::endl; @@ -187,8 +171,7 @@ Canvas::redraw_all() /** * Redraw the given area during idle. */ -void -Canvas::redraw_area(int x0, int y0, int x1, int y1) +void Canvas::redraw_area(int x0, int y0, int x1, int y1) { if (_in_destruction) { std::cerr << "Canvas::redraw_area: Called after canvas destroyed!" << std::endl; @@ -199,7 +182,7 @@ Canvas::redraw_area(int x0, int y0, int x1, int y1) return; } - Cairo::RectangleInt crect = { x0, y0, x1-x0, y1-y0 }; + Cairo::RectangleInt crect = {x0, y0, x1 - x0, y1 - y0}; _clean_region->subtract(crect); add_idle(); } @@ -207,8 +190,7 @@ Canvas::redraw_area(int x0, int y0, int x1, int y1) /** * Immediate redraw of areas needing update. */ -void -Canvas::redraw_now() +void Canvas::redraw_now() { if (_need_update) { do_update(); @@ -218,8 +200,7 @@ Canvas::redraw_now() /** * Redraw after updating canvas items. */ -void -Canvas::request_update() +void Canvas::request_update() { _need_update = true; add_idle(); @@ -230,15 +211,14 @@ Canvas::request_update() * Scroll window so drawing point 'c' is at upper left corner of canvas. * Complete redraw if 'clear' is true. */ -void -Canvas::scroll_to(Geom::Point const &c, bool clear) +void Canvas::scroll_to(Geom::Point const &c, bool clear) { int old_x0 = _x0; int old_y0 = _y0; // This is the only place the _x0 and _y0 are set! - _x0 = (int) round(c[Geom::X]); // cx might be negative, so (int)(cx + 0.5) will not do! - _y0 = (int) round(c[Geom::Y]); + _x0 = (int)round(c[Geom::X]); // cx might be negative, so (int)(cx + 0.5) will not do! + _y0 = (int)round(c[Geom::Y]); _window_origin = c; // Double value if (!_backing_store) { @@ -254,14 +234,15 @@ Canvas::scroll_to(Geom::Point const &c, bool clear) } // See if there is any overlap between canvas before and after scrolling. - Geom::IntRect old_area = Geom::IntRect::from_xywh(old_x0, old_y0, _allocation.get_width(), _allocation.get_height()); + Geom::IntRect old_area = + Geom::IntRect::from_xywh(old_x0, old_y0, _allocation.get_width(), _allocation.get_height()); Geom::IntRect new_area = old_area + Geom::IntPoint(dx, dy); bool overlap = new_area.intersects(old_area); SPCanvasArena *arena = SP_CANVAS_ARENA(SP_ACTIVE_DESKTOP->drawing); if (arena) { Geom::IntRect expanded = new_area; - Geom::IntPoint expansion(new_area.width()/2, new_area.height()/2); + Geom::IntPoint expansion(new_area.width() / 2, new_area.height() / 2); expanded.expandBy(expansion); arena->drawing.setCacheLimit(expanded, false); } @@ -278,7 +259,7 @@ Canvas::scroll_to(Geom::Point const &c, bool clear) } // Mark surface to redraw (everything outside clean region). - Cairo::RectangleInt crect = { _x0, _y0, _allocation.get_width(), _allocation.get_height() }; + Cairo::RectangleInt crect = {_x0, _y0, _allocation.get_width(), _allocation.get_height()}; _clean_region->intersect(crect); // Shouldn't the clean region be reset and then this added? // Scroll without zoom: redraw only newly exposed areas. @@ -296,8 +277,7 @@ Canvas::scroll_to(Geom::Point const &c, bool clear) /** * Return the root canvas group. */ -SPCanvasGroup* -Canvas::get_canvas_item_root() +SPCanvasGroup *Canvas::get_canvas_item_root() { return SP_CANVAS_GROUP(_root); } @@ -305,8 +285,7 @@ Canvas::get_canvas_item_root() /** * Set canvas backbround color (display only). */ -void -Canvas::set_background_color(guint32 rgba) +void Canvas::set_background_color(guint32 rgba) { double r = SP_RGBA32_R_F(rgba); double g = SP_RGBA32_G_F(rgba); @@ -321,8 +300,7 @@ Canvas::set_background_color(guint32 rgba) /** * Set canvas background to a checkerboard pattern. */ -void -Canvas::set_background_checkerboard(guint32 rgba) +void Canvas::set_background_checkerboard(guint32 rgba) { auto pattern = ink_cairo_pattern_create_checkerboard(rgba); _background = Cairo::RefPtr<Cairo::Pattern>(new Cairo::Pattern(pattern)); @@ -330,8 +308,7 @@ Canvas::set_background_checkerboard(guint32 rgba) redraw_all(); } -void -Canvas::set_render_mode(Inkscape::RenderMode mode) +void Canvas::set_render_mode(Inkscape::RenderMode mode) { if (_render_mode != mode) { _render_mode = mode; @@ -339,8 +316,7 @@ Canvas::set_render_mode(Inkscape::RenderMode mode) } } -void -Canvas::set_color_mode(Inkscape::ColorMode mode) +void Canvas::set_color_mode(Inkscape::ColorMode mode) { if (_color_mode != mode) { _color_mode = mode; @@ -348,8 +324,7 @@ Canvas::set_color_mode(Inkscape::ColorMode mode) } } -void -Canvas::set_split_mode(Inkscape::SplitMode mode) +void Canvas::set_split_mode(Inkscape::SplitMode mode) { if (_split_mode != mode) { _split_mode = mode; @@ -357,8 +332,7 @@ Canvas::set_split_mode(Inkscape::SplitMode mode) } } -void -Canvas::set_split_direction(Inkscape::SplitDirection dir) +void Canvas::set_split_direction(Inkscape::SplitDirection dir) { if (_split_direction != dir) { _split_direction = dir; @@ -366,8 +340,7 @@ Canvas::set_split_direction(Inkscape::SplitDirection dir) } } -void -Canvas::forced_redraws_start(int count, bool reset) +void Canvas::forced_redraws_start(int count, bool reset) { _forced_redraw_limit = count; if (reset) { @@ -378,8 +351,7 @@ Canvas::forced_redraws_start(int count, bool reset) /** * Clear current, grabbed, and focused items. */ -void -Canvas::canvas_item_clear(SPCanvasItem *item) +void Canvas::canvas_item_clear(SPCanvasItem *item) { if (item == _current_item) { _current_item = nullptr; @@ -394,41 +366,36 @@ Canvas::canvas_item_clear(SPCanvasItem *item) if (item == _grabbed_item) { _grabbed_item = nullptr; auto const display = Gdk::Display::get_default(); - auto const seat = display->get_default_seat(); + auto const seat = display->get_default_seat(); seat->ungrab(); } if (item == _focused_item) { _focused_item = nullptr; } - } // ============== Protected Functions ============== -void -Canvas::get_preferred_width_vfunc (int& minimum_width, int& natural_width) const +void Canvas::get_preferred_width_vfunc(int &minimum_width, int &natural_width) const { minimum_width = natural_width = 256; -} +} -void -Canvas::get_preferred_height_vfunc (int& minimum_height, int& natural_height) const +void Canvas::get_preferred_height_vfunc(int &minimum_height, int &natural_height) const { minimum_height = natural_height = 256; } // ******* Event handlers ****** -bool -Canvas::on_scroll_event(GdkEventScroll *scroll_event) +bool Canvas::on_scroll_event(GdkEventScroll *scroll_event) { // Scroll canvas and in Select Tool, cycle selection through objets under cursor. return emit_event(reinterpret_cast<GdkEvent *>(scroll_event)); } // Our own function that combines press and release. -bool -Canvas::on_button_event(GdkEventButton *button_event) +bool Canvas::on_button_event(GdkEventButton *button_event) { // Dispatch normally regardless of the event's window if an item // has a pointer grab in effect. @@ -439,15 +406,25 @@ Canvas::on_button_event(GdkEventButton *button_event) int mask = 0; switch (button_event->button) { - case 1: mask = GDK_BUTTON1_MASK; break; - case 2: mask = GDK_BUTTON1_MASK; break; - case 3: mask = GDK_BUTTON1_MASK; break; - case 4: mask = GDK_BUTTON1_MASK; break; - case 5: mask = GDK_BUTTON1_MASK; break; - default: mask = 0; // Buttons can range at least to 9 but mask defined only to 5. + case 1: + mask = GDK_BUTTON1_MASK; + break; + case 2: + mask = GDK_BUTTON1_MASK; + break; + case 3: + mask = GDK_BUTTON1_MASK; + break; + case 4: + mask = GDK_BUTTON1_MASK; + break; + case 5: + mask = GDK_BUTTON1_MASK; + break; + default: + mask = 0; // Buttons can range at least to 9 but mask defined only to 5. } - bool retval = false; switch (button_event->type) { case GDK_BUTTON_PRESS: @@ -499,20 +476,17 @@ Canvas::on_button_event(GdkEventButton *button_event) return retval; } -bool -Canvas::on_button_press_event(GdkEventButton *button_event) +bool Canvas::on_button_press_event(GdkEventButton *button_event) { return on_button_event(button_event); } -bool -Canvas::on_button_release_event(GdkEventButton *button_event) +bool Canvas::on_button_release_event(GdkEventButton *button_event) { return on_button_event(button_event); } -bool -Canvas::on_enter_notify_event(GdkEventCrossing *crossing_event) +bool Canvas::on_enter_notify_event(GdkEventCrossing *crossing_event) { auto window = get_window(); if (window->gobj() != crossing_event->window) { @@ -523,8 +497,7 @@ Canvas::on_enter_notify_event(GdkEventCrossing *crossing_event) return pick_current_item(reinterpret_cast<GdkEvent *>(crossing_event)); } -bool -Canvas::on_leave_notify_event(GdkEventCrossing *crossing_event) +bool Canvas::on_leave_notify_event(GdkEventCrossing *crossing_event) { auto window = get_window(); if (window->gobj() != crossing_event->window) { @@ -535,55 +508,46 @@ Canvas::on_leave_notify_event(GdkEventCrossing *crossing_event) return pick_current_item(reinterpret_cast<GdkEvent *>(crossing_event)); } -bool -Canvas::on_focus_in_event(GdkEventFocus *focus_event) +bool Canvas::on_focus_in_event(GdkEventFocus *focus_event) { grab_focus(); - if (_focused_item) { + if (_focused_item) { return emit_event(reinterpret_cast<GdkEvent *>(focus_event)); } return false; } -bool -Canvas::on_focus_out_event(GdkEventFocus *focus_event) +bool Canvas::on_focus_out_event(GdkEventFocus *focus_event) { - if (_focused_item) { + if (_focused_item) { return emit_event(reinterpret_cast<GdkEvent *>(focus_event)); } return false; } // Actually, key events never reach here. -bool -Canvas::on_key_press_event(GdkEventKey *key_event) +bool Canvas::on_key_press_event(GdkEventKey *key_event) { return emit_event(reinterpret_cast<GdkEvent *>(key_event)); } // Actually, key events never reach here. -bool -Canvas::on_key_release_event(GdkEventKey *key_event) +bool Canvas::on_key_release_event(GdkEventKey *key_event) { return emit_event(reinterpret_cast<GdkEvent *>(key_event)); } -bool -Canvas::on_motion_notify_event(GdkEventMotion *motion_event) +bool Canvas::on_motion_notify_event(GdkEventMotion *motion_event) { Geom::IntPoint cursor_position = Geom::IntPoint(motion_event->x, motion_event->y); // Check if we are near the edge. If so, revert to normal mode. - if ((_split_mode == Inkscape::SPLITMODE_SPLIT && _split_dragging) || - _split_mode == Inkscape::SPLITMODE_XRAY ) { - if (cursor_position.x() < 5 || - cursor_position.y() < 5 || - cursor_position.x() - _allocation.get_width() > -5 || - cursor_position.y() - _allocation.get_height() > -5 ) { - + if ((_split_mode == Inkscape::SPLITMODE_SPLIT && _split_dragging) || _split_mode == Inkscape::SPLITMODE_XRAY) { + if (cursor_position.x() < 5 || cursor_position.y() < 5 || cursor_position.x() - _allocation.get_width() > -5 || + cursor_position.y() - _allocation.get_height() > -5) { // Reset everything. _split_mode = Inkscape::SPLITMODE_NORMAL; - _split_position = Geom::Point(_allocation.get_width()/2, _allocation.get_height()/2); + _split_position = Geom::Point(_allocation.get_width() / 2, _allocation.get_height() / 2); set_cursor(); queue_draw(); SP_ACTIVE_DESKTOP->setSplitMode(_split_mode); @@ -597,7 +561,6 @@ Canvas::on_motion_notify_event(GdkEventMotion *motion_event) } if (_split_mode == Inkscape::SPLITMODE_SPLIT) { - Inkscape::SplitDirection hover_direction = Inkscape::SPLITDIRECTION_NONE; Geom::Point difference(cursor_position - _split_position); @@ -617,7 +580,6 @@ Canvas::on_motion_notify_event(GdkEventMotion *motion_event) } if (Geom::distance(cursor_position, _split_position) < 20 * _device_scale) { - // We're hovering over circle, figure out which direction we are in. if (difference.y() - difference.x() > 0) { if (difference.y() + difference.x() > 0) { @@ -640,7 +602,7 @@ Canvas::on_motion_notify_event(GdkEventMotion *motion_event) } } else { if (std::abs(difference.x()) < 3 * _device_scale) { - // We're hovering over vertical line + // We're hovering over vertical line hover_direction = Inkscape::SPLITDIRECTION_VERTICAL; } } @@ -679,8 +641,7 @@ Canvas::on_motion_notify_event(GdkEventMotion *motion_event) * * 5. Calls add_idle() to update the drawing if necessary. */ -bool -Canvas::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) +bool Canvas::on_draw(const ::Cairo::RefPtr<::Cairo::Context> &cr) { // This function should be the only place _allocation is redefined (except in on_realize())! Gtk::Allocation allocation = get_allocation(); @@ -694,19 +655,15 @@ Canvas::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) // Gdk::Window::create_similar_image_surface() creates a Cairo::Surface of type SURFACE_IMAGE_TYPE. // This is not the same as a Cairo::ImageSurface.. at least it can't be cast to it. So we can't use // that handy function (it sets device_scale automatically). - _backing_store = - Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32, - _allocation.get_width() * _device_scale, - _allocation.get_height() * _device_scale); + _backing_store = Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32, _allocation.get_width() * _device_scale, + _allocation.get_height() * _device_scale); cairo_surface_set_device_scale(_backing_store->cobj(), _device_scale, _device_scale); // No C++ API! - _outline_store = - Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32, - _allocation.get_width() * _device_scale, - _allocation.get_height() * _device_scale); + _outline_store = Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32, _allocation.get_width() * _device_scale, + _allocation.get_height() * _device_scale); cairo_surface_set_device_scale(_outline_store->cobj(), _device_scale, _device_scale); // No C++ API! - _split_position = Geom::Point(_allocation.get_width()/2, _allocation.get_height()/2); + _split_position = Geom::Point(_allocation.get_width() / 2, _allocation.get_height() / 2); } if (!(_allocation == allocation) || _device_scale != device_scale) { // "!=" for allocation not defined! @@ -720,7 +677,7 @@ Canvas::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) } // Clip the clean region to the new allocation - Cairo::RectangleInt clip = { _x0, _y0, _allocation.get_width(), _allocation.get_height() }; + Cairo::RectangleInt clip = {_x0, _y0, _allocation.get_width(), _allocation.get_height()}; _clean_region->intersect(clip); } @@ -739,18 +696,16 @@ Canvas::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) } if (_split_mode == Inkscape::SPLITMODE_SPLIT) { - // Add dividing line. cr->save(); cr->set_source_rgb(0, 0, 0); cr->set_line_width(1); - if (_split_direction == Inkscape::SPLITDIRECTION_EAST || - _split_direction == Inkscape::SPLITDIRECTION_WEST) { - cr->move_to((int)_split_position.x() + 0.5, 0); + if (_split_direction == Inkscape::SPLITDIRECTION_EAST || _split_direction == Inkscape::SPLITDIRECTION_WEST) { + cr->move_to((int)_split_position.x() + 0.5, 0); cr->line_to((int)_split_position.x() + 0.5, _allocation.get_height()); cr->stroke(); } else { - cr->move_to( 0, (int)_split_position.y() + 0.5); + cr->move_to(0, (int)_split_position.y() + 0.5); cr->line_to(_allocation.get_width(), (int)_split_position.y() + 0.5); cr->stroke(); } @@ -771,15 +726,15 @@ Canvas::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) // Position triangle. cr->translate(_split_position.x(), _split_position.y()); - cr->rotate((i+2)*M_PI/2.0); + cr->rotate((i + 2) * M_PI / 2.0); // Draw triangle. - cr->move_to(-5 * _device_scale, 8 * _device_scale); - cr->line_to( 0, 18 * _device_scale); - cr->line_to( 5 * _device_scale, 8 * _device_scale); + cr->move_to(-5 * _device_scale, 8 * _device_scale); + cr->line_to(0, 18 * _device_scale); + cr->line_to(5 * _device_scale, 8 * _device_scale); cr->close_path(); - double b = _hover_direction == (i+1) ? 0.9 : 0.7; + double b = _hover_direction == (i + 1) ? 0.9 : 0.7; cr->set_source_rgba(b, b, b, a); cr->fill(); @@ -798,20 +753,17 @@ Canvas::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) std::vector<Cairo::Rectangle> clip_rectangles; cr->copy_clip_rectangle_list(clip_rectangles); - for (auto & rectangle : clip_rectangles) { - Geom::Rect dr = Geom::Rect::from_xywh(rectangle.x + _x0, - rectangle.y + _y0, - rectangle.width, - rectangle.height); + for (auto &rectangle : clip_rectangles) { + Geom::Rect dr = Geom::Rect::from_xywh(rectangle.x + _x0, rectangle.y + _y0, rectangle.width, rectangle.height); // "rectangle" is floating point, we must convert to integer. We round outward as it's // better to have a larger dirty region to avoid artifacts. Geom::IntRect ir = dr.roundOutwards(); - Cairo::RectangleInt irect = { ir.left(), ir.top(), ir.width(), ir.height() }; + Cairo::RectangleInt irect = {ir.left(), ir.top(), ir.width(), ir.height()}; dirty_region->do_union(irect); } dirty_region->subtract(_clean_region); - + if (!dirty_region->empty()) { add_idle(); } @@ -819,8 +771,7 @@ Canvas::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) return true; } -void -Canvas::add_idle() +void Canvas::add_idle() { if (_in_destruction) { std::cerr << "Canvas::add_idle: Called after canvas destroyed!" << std::endl; @@ -829,7 +780,8 @@ Canvas::add_idle() if (get_realized() && !_idle_connection.connected()) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - guint redrawPriority = prefs->getIntLimited("/options/redrawpriority/value", G_PRIORITY_HIGH_IDLE, G_PRIORITY_HIGH_IDLE, G_PRIORITY_DEFAULT_IDLE); + guint redrawPriority = prefs->getIntLimited("/options/redrawpriority/value", G_PRIORITY_HIGH_IDLE, + G_PRIORITY_HIGH_IDLE, G_PRIORITY_DEFAULT_IDLE); // G_PRIORITY_HIGH_IDLE = 100, G_PRIORITY_DEFAULT_IDLE = 200: Higher number => lower priority. _idle_connection = Glib::signal_idle().connect(sigc::mem_fun(*this, &Canvas::on_idle), redrawPriority); @@ -837,14 +789,12 @@ Canvas::add_idle() } // Probably not needed. -void -Canvas::remove_idle() +void Canvas::remove_idle() { _idle_connection.disconnect(); } -bool -Canvas::on_idle() +bool Canvas::on_idle() { if (_in_destruction) { std::cerr << "Canvas::on_idle: Called after canvas destroyed!" << std::endl; @@ -869,8 +819,7 @@ Canvas::on_idle() } // Return true if done. -bool -Canvas::do_update() +bool Canvas::do_update() { if (!_root) { // Canvas destroyed? @@ -900,10 +849,9 @@ Canvas::do_update() return true; // FIXME } -bool -Canvas::paint() +bool Canvas::paint() { - Cairo::RectangleInt crect = { _x0, _y0, _allocation.get_width(), _allocation.get_height() }; + Cairo::RectangleInt crect = {_x0, _y0, _allocation.get_width(), _allocation.get_height()}; auto draw_region = Cairo::Region::create(crect); draw_region->subtract(_clean_region); @@ -920,8 +868,7 @@ Canvas::paint() return true; } -bool -Canvas::paint_rect(Cairo::RectangleInt& rect) +bool Canvas::paint_rect(Cairo::RectangleInt &rect) { // Find window rectangle in 'world coordinates'. Geom::IntRect canvas_rect = Geom::IntRect::from_xywh(_x0, _y0, _allocation.get_width(), _allocation.get_height()); @@ -935,8 +882,8 @@ Canvas::paint_rect(Cairo::RectangleInt& rect) // Get cursor position auto const display = Gdk::Display::get_default(); - auto const seat = display->get_default_seat(); - auto const device = seat->get_pointer(); + auto const seat = display->get_default_seat(); + auto const device = seat->get_pointer(); int x = 0; int y = 0; @@ -964,8 +911,7 @@ Canvas::paint_rect(Cairo::RectangleInt& rect) return paint_rect_internal(&setup, paint_rect); } -bool -Canvas::paint_rect_internal(PaintRectSetup const *setup, Geom::IntRect const &this_rect) +bool Canvas::paint_rect_internal(PaintRectSetup const *setup, Geom::IntRect const &this_rect) { gint64 now = g_get_monotonic_time(); gint64 elapsed = now - setup->start_time; @@ -983,9 +929,7 @@ Canvas::paint_rect_internal(PaintRectSetup const *setup, Geom::IntRect const &th // If this limit is set, and if we have aborted redraw more times than is allowed, // interrupting is blocked and we're forced to redraw full screen once // (after which we can again interrupt forced_redraw_limit times). - if (_forced_redraw_limit < 0 || - _forced_redraw_count < _forced_redraw_limit) { - + if (_forced_redraw_limit < 0 || _forced_redraw_count < _forced_redraw_limit) { if (_forced_redraw_limit != -1) { _forced_redraw_count++; } @@ -1018,8 +962,8 @@ Canvas::paint_rect_internal(PaintRectSetup const *setup, Geom::IntRect const &th paint_single_buffer(this_rect, setup->canvas_rect, _outline_store); } - Cairo::RectangleInt crect = { this_rect.left(), this_rect.top(), this_rect.width(), this_rect.height() }; - _clean_region->do_union( crect ); + Cairo::RectangleInt crect = {this_rect.left(), this_rect.top(), this_rect.width(), this_rect.height()}; + _clean_region->do_union(crect); queue_draw_area(this_rect.left() - _x0, this_rect.top() - _y0, this_rect.width(), this_rect.height()); @@ -1046,37 +990,32 @@ Canvas::paint_rect_internal(PaintRectSetup const *setup, Geom::IntRect const &th if (bw < bh || bh < 2 * TILE_SIZE) { int mid = this_rect[Geom::X].middle(); - lo = Geom::IntRect(this_rect.left(), this_rect.top(), mid, this_rect.bottom()); - hi = Geom::IntRect(mid, this_rect.top(), this_rect.right(), this_rect.bottom()); + lo = Geom::IntRect(this_rect.left(), this_rect.top(), mid, this_rect.bottom()); + hi = Geom::IntRect(mid, this_rect.top(), this_rect.right(), this_rect.bottom()); if (setup->mouse_loc[Geom::X] < mid) { // Always paint towards the mouse first - return paint_rect_internal(setup, lo) - && paint_rect_internal(setup, hi); + return paint_rect_internal(setup, lo) && paint_rect_internal(setup, hi); } else { - return paint_rect_internal(setup, hi) - && paint_rect_internal(setup, lo); + return paint_rect_internal(setup, hi) && paint_rect_internal(setup, lo); } } else { int mid = this_rect[Geom::Y].middle(); - lo = Geom::IntRect(this_rect.left(), this_rect.top(), this_rect.right(), mid ); - hi = Geom::IntRect(this_rect.left(), mid, this_rect.right(), this_rect.bottom()); + lo = Geom::IntRect(this_rect.left(), this_rect.top(), this_rect.right(), mid); + hi = Geom::IntRect(this_rect.left(), mid, this_rect.right(), this_rect.bottom()); if (setup->mouse_loc[Geom::Y] < mid) { // Always paint towards the mouse first - return paint_rect_internal(setup, lo) - && paint_rect_internal(setup, hi); + return paint_rect_internal(setup, lo) && paint_rect_internal(setup, hi); } else { - return paint_rect_internal(setup, hi) - && paint_rect_internal(setup, lo); + return paint_rect_internal(setup, hi) && paint_rect_internal(setup, lo); } } } -void -Canvas::paint_single_buffer(Geom::IntRect const &paint_rect, Geom::IntRect const &canvas_rect, - Cairo::RefPtr<Cairo::ImageSurface> &store) +void Canvas::paint_single_buffer(Geom::IntRect const &paint_rect, Geom::IntRect const &canvas_rect, + Cairo::RefPtr<Cairo::ImageSurface> &store) { if (!store) { std::cerr << "Canvas::paint_single_buffer: store not created!" << std::endl; @@ -1094,9 +1033,9 @@ Canvas::paint_single_buffer(Geom::IntRect const &paint_rect, Geom::IntRect const // Make sure the following code does not go outside of store's data assert(store->get_format() == Cairo::FORMAT_ARGB32); - assert(paint_rect.left() - _x0 >= 0); - assert(paint_rect.top() - _y0 >= 0); - assert(paint_rect.right() - _x0 <= store->get_width()); + assert(paint_rect.left() - _x0 >= 0); + assert(paint_rect.top() - _y0 >= 0); + assert(paint_rect.right() - _x0 <= store->get_width()); assert(paint_rect.bottom() - _y0 <= store->get_height()); // Create temporary surface that draws directly to store. @@ -1115,17 +1054,15 @@ Canvas::paint_single_buffer(Geom::IntRect const &paint_rect, Geom::IntRect const double x_scale = 1.0; double y_scale = 1.0; cairo_surface_get_device_scale(store->cobj(), &x_scale, &y_scale); // No C++ API! - assert (_device_scale == (int)x_scale); - assert (_device_scale == (int)y_scale); + assert(_device_scale == (int)x_scale); + assert(_device_scale == (int)y_scale); // Move to the correct row. data += stride * (paint_rect.top() - _y0) * (int)y_scale; // Move to the correct column. data += 4 * (paint_rect.left() - _x0) * (int)x_scale; - auto imgs = Cairo::ImageSurface::create(data, Cairo::FORMAT_ARGB32, - paint_rect.width() * _device_scale, - paint_rect.height() * _device_scale, - stride); + auto imgs = Cairo::ImageSurface::create(data, Cairo::FORMAT_ARGB32, paint_rect.width() * _device_scale, + paint_rect.height() * _device_scale, stride); cairo_surface_set_device_scale(imgs->cobj(), _device_scale, _device_scale); // No C++ API! auto cr = Cairo::Context::create(imgs); @@ -1148,8 +1085,8 @@ Canvas::paint_single_buffer(Geom::IntRect const &paint_rect, Geom::IntRect const if (_cms_active) { cmsHTRANSFORM transf = nullptr; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool fromDisplay = prefs->getBool( "/options/displayprofile/from_display"); - if ( fromDisplay ) { + bool fromDisplay = prefs->getBool("/options/displayprofile/from_display"); + if (fromDisplay) { transf = Inkscape::CMSSystem::getDisplayPer(_cms_key); } else { transf = Inkscape::CMSSystem::getDisplayTransform(); @@ -1159,8 +1096,8 @@ Canvas::paint_single_buffer(Geom::IntRect const &paint_rect, Geom::IntRect const imgs->flush(); unsigned char *px = imgs->get_data(); int stride = imgs->get_stride(); - for (int i=0; i<paint_rect.height(); ++i) { - unsigned char *row = px + i*stride; + for (int i = 0; i < paint_rect.height(); ++i) { + unsigned char *row = px + i * stride; Inkscape::CMSSystem::doTransform(transf, row, row, paint_rect.width()); } imgs->mark_dirty(); @@ -1181,21 +1118,17 @@ Canvas::paint_single_buffer(Geom::IntRect const &paint_rect, Geom::IntRect const // cr->stroke(); // cr->restore(); - Cairo::RectangleInt crect = { paint_rect.left(), paint_rect.top(), paint_rect.width(), paint_rect.height() }; - _clean_region->do_union( crect ); + Cairo::RectangleInt crect = {paint_rect.left(), paint_rect.top(), paint_rect.width(), paint_rect.height()}; + _clean_region->do_union(crect); queue_draw_area(paint_rect.left() - _x0, paint_rect.top() - _y0, paint_rect.width(), paint_rect.height()); } - // Shift backing store (when canvas scrolled or size changed). -void -Canvas::shift_content(Geom::IntPoint shift, Cairo::RefPtr<Cairo::ImageSurface> &store) +void Canvas::shift_content(Geom::IntPoint shift, Cairo::RefPtr<Cairo::ImageSurface> &store) { - Cairo::RefPtr<::Cairo::ImageSurface> new_store = - Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32, - _allocation.get_width() * _device_scale, - _allocation.get_height() * _device_scale); + Cairo::RefPtr<::Cairo::ImageSurface> new_store = Cairo::ImageSurface::create( + Cairo::FORMAT_ARGB32, _allocation.get_width() * _device_scale, _allocation.get_height() * _device_scale); cairo_surface_set_device_scale(new_store->cobj(), _device_scale, _device_scale); // No C++ API! @@ -1226,33 +1159,31 @@ Canvas::shift_content(Geom::IntPoint shift, Cairo::RefPtr<Cairo::ImageSurface> & // _store->write_to_png(file); } - // Sets clip path for Split and X-Ray modes. -void -Canvas::add_clippath(const Cairo::RefPtr<Cairo::Context>& cr) { - +void Canvas::add_clippath(const Cairo::RefPtr<Cairo::Context> &cr) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double radius = prefs->getIntLimited("/options/rendering/xray-radius", 100, 1, 1500); - double width = _allocation.get_width(); + double width = _allocation.get_width(); double height = _allocation.get_height(); - double sx = _split_position.x(); - double sy = _split_position.y(); + double sx = _split_position.x(); + double sy = _split_position.y(); if (_split_mode == Inkscape::SPLITMODE_SPLIT) { // We're clipping the outline region... so it's backwards. switch (_split_direction) { case Inkscape::SPLITDIRECTION_SOUTH: - cr->rectangle(0, 0, width, sy); + cr->rectangle(0, 0, width, sy); break; case Inkscape::SPLITDIRECTION_NORTH: - cr->rectangle(0, sy, width, height - sy); + cr->rectangle(0, sy, width, height - sy); break; case Inkscape::SPLITDIRECTION_EAST: - cr->rectangle(0, 0, sx, height ); + cr->rectangle(0, 0, sx, height); break; case Inkscape::SPLITDIRECTION_WEST: - cr->rectangle(sx, 0, width - sx, height ); + cr->rectangle(sx, 0, width - sx, height); break; } } else { @@ -1263,13 +1194,11 @@ Canvas::add_clippath(const Cairo::RefPtr<Cairo::Context>& cr) { } // Change cursor -void -Canvas::set_cursor() { - +void Canvas::set_cursor() +{ auto display = Gdk::Display::get_default(); switch (_hover_direction) { - case Inkscape::SPLITDIRECTION_NONE: get_window()->set_cursor(SP_ACTIVE_DESKTOP->event_context->cursor); break; @@ -1277,22 +1206,19 @@ Canvas::set_cursor() { case Inkscape::SPLITDIRECTION_NORTH: case Inkscape::SPLITDIRECTION_EAST: case Inkscape::SPLITDIRECTION_SOUTH: - case Inkscape::SPLITDIRECTION_WEST: - { + case Inkscape::SPLITDIRECTION_WEST: { auto cursor = Gdk::Cursor::create(display, "pointer"); get_window()->set_cursor(cursor); break; } - case Inkscape::SPLITDIRECTION_HORIZONTAL: - { + case Inkscape::SPLITDIRECTION_HORIZONTAL: { auto cursor = Gdk::Cursor::create(display, "ns-resize"); get_window()->set_cursor(cursor); break; } - case Inkscape::SPLITDIRECTION_VERTICAL: - { + case Inkscape::SPLITDIRECTION_VERTICAL: { auto cursor = Gdk::Cursor::create(display, "ew-resize"); get_window()->set_cursor(cursor); break; @@ -1304,7 +1230,6 @@ Canvas::set_cursor() { } } - // This routine reacts to events from the canvas. It's main purpose is to find the canvas item // closest to the cursor where the event occured and then send the event (sometimes modified) to // that item. The event then bubbles up the canvas item tree until an object handles it. If the @@ -1313,8 +1238,7 @@ Canvas::set_cursor() { // Canvas items register their interest by connecting to the "event" signal. // Example in desktop.cpp: // g_signal_connect (G_OBJECT (acetate), "event", G_CALLBACK (sp_desktop_root_handler), this); -bool -Canvas::pick_current_item(GdkEvent *event) +bool Canvas::pick_current_item(GdkEvent *event) { int button_down = 0; if (_all_enter_events == false) { @@ -1323,14 +1247,12 @@ Canvas::pick_current_item(GdkEvent *event) // If a button is down, we'll perform enter and leave events on the // current item, but not enter on any other item. This is more or // less like X pointer grabbing for canvas items. - button_down = _state & (GDK_BUTTON1_MASK | - GDK_BUTTON2_MASK | - GDK_BUTTON3_MASK | - GDK_BUTTON4_MASK | - GDK_BUTTON5_MASK); - if (!button_down) _left_grabbed_item = false; - } - + button_down = + _state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK | GDK_BUTTON4_MASK | GDK_BUTTON5_MASK); + if (!button_down) + _left_grabbed_item = false; + } + // Save the event in the canvas. This is used to synthesize enter and // leave events in case the current item changes. It is also used to // re-pick the current item if the current one gets deleted. Also, @@ -1340,16 +1262,16 @@ Canvas::pick_current_item(GdkEvent *event) // Convert to GDK_ENTER_NOTIFY // These fields have the same offsets in both types of events. - _pick_event.crossing.type = GDK_ENTER_NOTIFY; - _pick_event.crossing.window = event->motion.window; + _pick_event.crossing.type = GDK_ENTER_NOTIFY; + _pick_event.crossing.window = event->motion.window; _pick_event.crossing.send_event = event->motion.send_event; - _pick_event.crossing.subwindow = nullptr; - _pick_event.crossing.x = event->motion.x; - _pick_event.crossing.y = event->motion.y; - _pick_event.crossing.mode = GDK_CROSSING_NORMAL; - _pick_event.crossing.detail = GDK_NOTIFY_NONLINEAR; - _pick_event.crossing.focus = false; - _pick_event.crossing.state = event->motion.state; + _pick_event.crossing.subwindow = nullptr; + _pick_event.crossing.x = event->motion.x; + _pick_event.crossing.y = event->motion.y; + _pick_event.crossing.mode = GDK_CROSSING_NORMAL; + _pick_event.crossing.detail = GDK_NOTIFY_NONLINEAR; + _pick_event.crossing.focus = false; + _pick_event.crossing.state = event->motion.state; // These fields don't have the same offsets in both types of events. if (event->type == GDK_MOTION_NOTIFY) { @@ -1394,8 +1316,8 @@ Canvas::pick_current_item(GdkEvent *event) if (_split_mode == Inkscape::SPLITMODE_SPLIT) { if ((_split_direction == Inkscape::SPLITDIRECTION_NORTH && y > _split_position.y()) || (_split_direction == Inkscape::SPLITDIRECTION_SOUTH && y < _split_position.y()) || - (_split_direction == Inkscape::SPLITDIRECTION_WEST && x > _split_position.x()) || - (_split_direction == Inkscape::SPLITDIRECTION_EAST && x < _split_position.x()) ) { + (_split_direction == Inkscape::SPLITDIRECTION_WEST && x > _split_position.x()) || + (_split_direction == Inkscape::SPLITDIRECTION_EAST && x < _split_position.x())) { arena->drawing.setRenderMode(Inkscape::RENDERMODE_OUTLINE); } } @@ -1404,7 +1326,7 @@ Canvas::pick_current_item(GdkEvent *event) x += _x0; y += _y0; - sp_canvas_item_invoke_point (_root, Geom::Point(x, y), &_current_item_new); + sp_canvas_item_invoke_point(_root, Geom::Point(x, y), &_current_item_new); } } @@ -1415,9 +1337,7 @@ Canvas::pick_current_item(GdkEvent *event) // Synthesize events for old and new current items. bool retval = false; - if ( (_current_item_new != _current_item) && - _current_item != nullptr && - !_left_grabbed_item ) { + if ((_current_item_new != _current_item) && _current_item != nullptr && !_left_grabbed_item) { GdkEvent new_event; new_event = _pick_event; new_event.type = GDK_LEAVE_NOTIFY; @@ -1452,42 +1372,41 @@ Canvas::pick_current_item(GdkEvent *event) return retval; } -bool -Canvas::emit_event(GdkEvent *event) +bool Canvas::emit_event(GdkEvent *event) { int mask = 0; if (_grabbed_item) { switch (event->type) { - case GDK_ENTER_NOTIFY: - mask = GDK_ENTER_NOTIFY_MASK; - break; - case GDK_LEAVE_NOTIFY: - mask = GDK_LEAVE_NOTIFY_MASK; - break; - case GDK_MOTION_NOTIFY: - mask = GDK_POINTER_MOTION_MASK; - break; - case GDK_BUTTON_PRESS: - case GDK_2BUTTON_PRESS: - case GDK_3BUTTON_PRESS: - mask = GDK_BUTTON_PRESS_MASK; - break; - case GDK_BUTTON_RELEASE: - mask = GDK_BUTTON_RELEASE_MASK; - break; - case GDK_KEY_PRESS: - mask = GDK_KEY_PRESS_MASK; - break; - case GDK_KEY_RELEASE: - mask = GDK_KEY_RELEASE_MASK; - break; - case GDK_SCROLL: - mask = GDK_SCROLL_MASK; - mask |= GDK_SMOOTH_SCROLL_MASK; - break; - default: - mask = 0; - break; + case GDK_ENTER_NOTIFY: + mask = GDK_ENTER_NOTIFY_MASK; + break; + case GDK_LEAVE_NOTIFY: + mask = GDK_LEAVE_NOTIFY_MASK; + break; + case GDK_MOTION_NOTIFY: + mask = GDK_POINTER_MOTION_MASK; + break; + case GDK_BUTTON_PRESS: + case GDK_2BUTTON_PRESS: + case GDK_3BUTTON_PRESS: + mask = GDK_BUTTON_PRESS_MASK; + break; + case GDK_BUTTON_RELEASE: + mask = GDK_BUTTON_RELEASE_MASK; + break; + case GDK_KEY_PRESS: + mask = GDK_KEY_PRESS_MASK; + break; + case GDK_KEY_RELEASE: + mask = GDK_KEY_RELEASE_MASK; + break; + case GDK_SCROLL: + mask = GDK_SCROLL_MASK; + mask |= GDK_SMOOTH_SCROLL_MASK; + break; + default: + mask = 0; + break; } if (!(mask & _grabbed_event_mask)) { @@ -1530,19 +1449,17 @@ Canvas::emit_event(GdkEvent *event) } if (_focused_item && - ((event->type == GDK_KEY_PRESS) || - (event->type == GDK_KEY_RELEASE) || - (event->type == GDK_FOCUS_CHANGE))) { + ((event->type == GDK_KEY_PRESS) || (event->type == GDK_KEY_RELEASE) || (event->type == GDK_FOCUS_CHANGE))) { item = _focused_item; } // Propogate the event up the item hierarchy until handled. gint finished = false; // Can't be bool or "stack smashing detected"! while (item && !finished) { - g_object_ref (item); - g_signal_emit (G_OBJECT (item), item_signals[ITEM_EVENT], 0, event_copy, &finished); + g_object_ref(item); + g_signal_emit(G_OBJECT(item), item_signals[ITEM_EVENT], 0, event_copy, &finished); SPCanvasItem *parent = item->parent; - g_object_unref (item); + g_object_unref(item); item = parent; } @@ -1551,7 +1468,6 @@ Canvas::emit_event(GdkEvent *event) return finished; } - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/canvas.h b/src/ui/widget/canvas.h index 407e432bb1267a983595540c03ef72e6f9e5629d..15fed72bfca4808d32c3fea38ee0979fee3cf9af 100644 --- a/src/ui/widget/canvas.h +++ b/src/ui/widget/canvas.h @@ -15,10 +15,9 @@ #include "config.h" #endif -#include <gtkmm.h> - -#include <2geom/rect.h> #include <2geom/int-rect.h> +#include <2geom/rect.h> +#include <gtkmm.h> #include "display/rendermode.h" @@ -27,18 +26,16 @@ class SPCanvasGroup; struct PaintRectSetup; - namespace Inkscape { namespace UI { namespace Widget { /** * A Gtk::DrawingArea widget for Inkscape's canvas. - */ + */ class Canvas : public Gtk::DrawingArea { public: - Canvas(); ~Canvas() override; @@ -59,16 +56,17 @@ public: void set_background_checkerboard(guint32 rgba = 0xC4C4C4FF); void set_drawing_disabled(bool disable) { _drawing_disabled = disable; } // Disable during path ops, etc. - bool is_dragging() {return _is_dragging; } // selection-chemistry.cpp + bool is_dragging() { return _is_dragging; } // selection-chemistry.cpp // Rendering modes void set_render_mode(Inkscape::RenderMode mode); - void set_color_mode(Inkscape::ColorMode mode); - void set_split_mode(Inkscape::SplitMode mode); + void set_color_mode(Inkscape::ColorMode mode); + void set_split_mode(Inkscape::SplitMode mode); void set_split_direction(Inkscape::SplitDirection dir); #if defined(HAVE_LIBLCMS2) - void set_cms_key(std::string key) { + void set_cms_key(std::string key) + { _cms_key = key; _cms_active = !key.empty(); } @@ -85,42 +83,41 @@ public: // Canvas Items SPCanvasGroup *get_canvas_item_root(); - SPCanvasItem *get_current_item() { return _current_item; } - void set_current_item(SPCanvasItem *item) { _current_item = item; } - SPCanvasItem *get_grabbed_item() { return _grabbed_item; } - void set_grabbed_item(SPCanvasItem *item, unsigned int mask) { + SPCanvasItem *get_current_item() { return _current_item; } + void set_current_item(SPCanvasItem *item) { _current_item = item; } + SPCanvasItem *get_grabbed_item() { return _grabbed_item; } + void set_grabbed_item(SPCanvasItem *item, unsigned int mask) + { _grabbed_item = item; _grabbed_event_mask = mask; } - void set_need_repick(bool repick = true) { _need_repick = repick; } - void canvas_item_clear(SPCanvasItem *item); + void set_need_repick(bool repick = true) { _need_repick = repick; } + void canvas_item_clear(SPCanvasItem *item); // Events - void set_all_enter_events(bool on) { _all_enter_events = on; } + void set_all_enter_events(bool on) { _all_enter_events = on; } protected: - - void get_preferred_width_vfunc( int& minimum_width, int& natural_width ) const override; - void get_preferred_height_vfunc(int& minimum_height, int& natural_height) const override; + void get_preferred_width_vfunc(int &minimum_width, int &natural_width) const override; + void get_preferred_height_vfunc(int &minimum_height, int &natural_height) const override; // Event handlers - bool on_scroll_event( GdkEventScroll *scroll_event) override; - bool on_button_event( GdkEventButton *button_event); - bool on_button_press_event( GdkEventButton *button_event) override; - bool on_button_release_event(GdkEventButton *button_event) override; - bool on_enter_notify_event( GdkEventCrossing *crossing_event) override; - bool on_leave_notify_event( GdkEventCrossing *crossing_event) override; - bool on_focus_in_event( GdkEventFocus *focus_event ) override; - bool on_focus_out_event( GdkEventFocus *focus_event ) override; - bool on_key_press_event( GdkEventKey *key_event ) override; - bool on_key_release_event( GdkEventKey *key_event ) override; - bool on_motion_notify_event( GdkEventMotion *motion_event) override; + bool on_scroll_event(GdkEventScroll *scroll_event) override; + bool on_button_event(GdkEventButton *button_event); + bool on_button_press_event(GdkEventButton *button_event) override; + bool on_button_release_event(GdkEventButton *button_event) override; + bool on_enter_notify_event(GdkEventCrossing *crossing_event) override; + bool on_leave_notify_event(GdkEventCrossing *crossing_event) override; + bool on_focus_in_event(GdkEventFocus *focus_event) override; + bool on_focus_out_event(GdkEventFocus *focus_event) override; + bool on_key_press_event(GdkEventKey *key_event) override; + bool on_key_release_event(GdkEventKey *key_event) override; + bool on_motion_notify_event(GdkEventMotion *motion_event) override; // Painting - bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr) override; + bool on_draw(const Cairo::RefPtr<Cairo::Context> &cr) override; private: - // ======== Functions ======= void add_idle(); void remove_idle(); // Not needed? @@ -131,13 +128,13 @@ private: // In order they are called in painting. bool do_update(); bool paint(); - bool paint_rect(Cairo::RectangleInt& rect); + bool paint_rect(Cairo::RectangleInt &rect); bool paint_rect_internal(PaintRectSetup const *setup, Geom::IntRect const &this_rect); void paint_single_buffer(Geom::IntRect const &paint_rect, Geom::IntRect const &canvas_rect, Cairo::RefPtr<Cairo::ImageSurface> &store); void shift_content(Geom::IntPoint shift, Cairo::RefPtr<Cairo::ImageSurface> &store); - void add_clippath(const Cairo::RefPtr<Cairo::Context>& cr); + void add_clippath(const Cairo::RefPtr<Cairo::Context> &cr); void set_cursor(); // Events @@ -145,44 +142,44 @@ private: bool emit_event(GdkEvent *event); // ==== Signal callbacks ==== - sigc::connection _idle_connection; // Probably not needed (automatically disconnects). + sigc::connection _idle_connection; // Probably not needed (automatically disconnects). // ====== Data members ======= // Geometry - int _x0 = 0; ///< World coordinate of the leftmost pixels of window. - int _y0 = 0; ///< World coordinate of the topmost pixels of window. - Geom::Point _window_origin; ///< World coordinate of the upper-leftmost pixel of window. + int _x0 = 0; ///< World coordinate of the leftmost pixels of window. + int _y0 = 0; ///< World coordinate of the topmost pixels of window. + Geom::Point _window_origin; ///< World coordinate of the upper-leftmost pixel of window. - int _device_scale = 1; ///< Scale for high DPI montiors. Probably should be double. - Gtk::Allocation _allocation; ///< Canvas allocation, save so we know when it changes. + int _device_scale = 1; ///< Scale for high DPI montiors. Probably should be double. + Gtk::Allocation _allocation; ///< Canvas allocation, save so we know when it changes. // Event handling/item picking - GdkEvent _pick_event; ///< Event used to find currently selected item. - bool _need_repick = true; ///< ? - bool _in_repick = false; ///< Used internally by pick_current_item(). - bool _left_grabbed_item = false; ///< ? - bool _all_enter_events = false; ///< Keep all enter events. Only set true in connector-tool.cpp. - bool _is_dragging = false; ///< Used in selection-chemistry to block undo/redo. - int _state = 0; ///< Last know modifier state (SHIFT, CTRL, etc.). - SPCanvasItem *_current_item = nullptr; ///< Item containing cursor, nullptr if none. - SPCanvasItem *_current_item_new = nullptr; ///< Item about to become _current_item, nullptr if none. - SPCanvasItem *_grabbed_item = nullptr; ///< Item that holds a pointer grab; nullptr if none. - SPCanvasItem *_focused_item = nullptr; ///< Item that is currently focused; nullptr if none. - unsigned int _grabbed_event_mask = 0; + GdkEvent _pick_event; ///< Event used to find currently selected item. + bool _need_repick = true; ///< ? + bool _in_repick = false; ///< Used internally by pick_current_item(). + bool _left_grabbed_item = false; ///< ? + bool _all_enter_events = false; ///< Keep all enter events. Only set true in connector-tool.cpp. + bool _is_dragging = false; ///< Used in selection-chemistry to block undo/redo. + int _state = 0; ///< Last know modifier state (SHIFT, CTRL, etc.). + SPCanvasItem *_current_item = nullptr; ///< Item containing cursor, nullptr if none. + SPCanvasItem *_current_item_new = nullptr; ///< Item about to become _current_item, nullptr if none. + SPCanvasItem *_grabbed_item = nullptr; ///< Item that holds a pointer grab; nullptr if none. + SPCanvasItem *_focused_item = nullptr; ///< Item that is currently focused; nullptr if none. + unsigned int _grabbed_event_mask = 0; // Drawing - bool _drawing_disabled = false; ///< Disable drawing during critical operations + bool _drawing_disabled = false; ///< Disable drawing during critical operations bool _need_update = false; SPCanvasItem *_root = nullptr; Inkscape::RenderMode _render_mode = Inkscape::RENDERMODE_NORMAL; - Inkscape::SplitMode _split_mode = Inkscape::SPLITMODE_NORMAL; + Inkscape::SplitMode _split_mode = Inkscape::SPLITMODE_NORMAL; Geom::Point _split_position; - Inkscape::SplitDirection _split_direction = Inkscape::SPLITDIRECTION_EAST; - Inkscape::SplitDirection _hover_direction = Inkscape::SPLITDIRECTION_NONE; + Inkscape::SplitDirection _split_direction = Inkscape::SPLITDIRECTION_EAST; + Inkscape::SplitDirection _hover_direction = Inkscape::SPLITDIRECTION_NONE; bool _split_dragging = false; Geom::Point _split_drag_start; - Inkscape::ColorMode _color_mode = Inkscape::COLORMODE_NORMAL; + Inkscape::ColorMode _color_mode = Inkscape::COLORMODE_NORMAL; #if defined(HAVE_LIBLCMS2) std::string _cms_key; @@ -191,7 +188,7 @@ private: // For a GTK bug (see SelectedStyle::on_opacity_changed()). int _forced_redraw_limit = -1; - int _forced_redraw_count = 0; + int _forced_redraw_count = 0; // Some objects (e.g. grids) when destroyed will request redraws. We need to block them when canvas // is destructed. (Windows are destroyed before documents as a document may have several windows. @@ -204,17 +201,16 @@ private: Cairo::RefPtr<Cairo::ImageSurface> _backing_store; ///< The canvas image content. We draw to this then blit. Cairo::RefPtr<Cairo::ImageSurface> _outline_store; ///< The outline image if we are in split/x-ray mode. - Cairo::RefPtr<Cairo::Pattern> _background; ///< The background of the image. + Cairo::RefPtr<Cairo::Pattern> _background; ///< The background of the image. bool _background_is_checkerboard = false; - - Cairo::RefPtr<Cairo::Region> _clean_region; ///< Area of widget that has up-to-date content. + + Cairo::RefPtr<Cairo::Region> _clean_region; ///< Area of widget that has up-to-date content. }; } // namespace Widget } // namespace UI } // namespace Inkscape - #endif // INKSCAPE_UI_WIDGET_CANVAS_H /* diff --git a/src/ui/widget/clipmaskicon.cpp b/src/ui/widget/clipmaskicon.cpp index 1093c1fda28f46e674f1cb4784830aa74b967e09..0e3a2c877a12089c709ce6e90d6bab4877a25a9f 100644 --- a/src/ui/widget/clipmaskicon.cpp +++ b/src/ui/widget/clipmaskicon.cpp @@ -19,18 +19,17 @@ namespace Inkscape { namespace UI { namespace Widget { -ClipMaskIcon::ClipMaskIcon() : - Glib::ObjectBase(typeid(ClipMaskIcon)), - Gtk::CellRendererPixbuf(), - _pixClipName(INKSCAPE_ICON("path-cut")), - _pixMaskName(INKSCAPE_ICON("path-difference")), - _pixBothName(INKSCAPE_ICON("bitmap-trace")), - _property_active(*this, "active", 0), - _property_pixbuf_clip(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)), - _property_pixbuf_mask(*this, "pixbuf_off", Glib::RefPtr<Gdk::Pixbuf>(nullptr)), - _property_pixbuf_both(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) +ClipMaskIcon::ClipMaskIcon() + : Glib::ObjectBase(typeid(ClipMaskIcon)) + , Gtk::CellRendererPixbuf() + , _pixClipName(INKSCAPE_ICON("path-cut")) + , _pixMaskName(INKSCAPE_ICON("path-difference")) + , _pixBothName(INKSCAPE_ICON("bitmap-trace")) + , _property_active(*this, "active", 0) + , _property_pixbuf_clip(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) + , _property_pixbuf_mask(*this, "pixbuf_off", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) + , _property_pixbuf_both(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) { - property_mode() = Gtk::CELL_RENDERER_MODE_ACTIVATABLE; _property_pixbuf_clip = sp_get_icon_pixbuf(_pixClipName, GTK_ICON_SIZE_MENU); @@ -40,44 +39,37 @@ ClipMaskIcon::ClipMaskIcon() : property_pixbuf() = Glib::RefPtr<Gdk::Pixbuf>(nullptr); } -void ClipMaskIcon::get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const +void ClipMaskIcon::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 ClipMaskIcon::get_preferred_width_vfunc(Gtk::Widget& widget, - int& min_w, - int& nat_w) const +void ClipMaskIcon::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; } } -void ClipMaskIcon::render_vfunc( const Cairo::RefPtr<Cairo::Context>& cr, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - Gtk::CellRendererState flags ) +void ClipMaskIcon::render_vfunc(const Cairo::RefPtr<Cairo::Context> &cr, Gtk::Widget &widget, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) { - switch (_property_active.get_value()) - { + switch (_property_active.get_value()) { case 1: property_pixbuf() = _property_pixbuf_clip; break; @@ -91,20 +83,16 @@ void ClipMaskIcon::render_vfunc( const Cairo::RefPtr<Cairo::Context>& cr, property_pixbuf() = Glib::RefPtr<Gdk::Pixbuf>(nullptr); break; } - Gtk::CellRendererPixbuf::render_vfunc( cr, widget, background_area, cell_area, flags ); + Gtk::CellRendererPixbuf::render_vfunc(cr, widget, background_area, cell_area, flags); } -bool ClipMaskIcon::activate_vfunc(GdkEvent* /*event*/, - Gtk::Widget& /*widget*/, - const Glib::ustring& /*path*/, - const Gdk::Rectangle& /*background_area*/, - const Gdk::Rectangle& /*cell_area*/, +bool ClipMaskIcon::activate_vfunc(GdkEvent * /*event*/, Gtk::Widget & /*widget*/, const Glib::ustring & /*path*/, + const Gdk::Rectangle & /*background_area*/, const Gdk::Rectangle & /*cell_area*/, Gtk::CellRendererState /*flags*/) { return false; } - } // namespace Widget } // namespace UI } // namespace Inkscape @@ -119,5 +107,3 @@ bool ClipMaskIcon::activate_vfunc(GdkEvent* /*event*/, End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - - diff --git a/src/ui/widget/clipmaskicon.h b/src/ui/widget/clipmaskicon.h index d8bbe52a92cac115007386624e5e3df9a5564d8d..bdb255e3a36f99095ad4641e11a53d6564c6456e 100644 --- a/src/ui/widget/clipmaskicon.h +++ b/src/ui/widget/clipmaskicon.h @@ -10,68 +10,55 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <glibmm/property.h> #include <gtkmm/cellrendererpixbuf.h> #include <gtkmm/widget.h> -#include <glibmm/property.h> namespace Inkscape { namespace UI { namespace Widget { -class ClipMaskIcon : public Gtk::CellRendererPixbuf { +class ClipMaskIcon : public Gtk::CellRendererPixbuf +{ public: ClipMaskIcon(); - ~ClipMaskIcon() override = default;; + ~ClipMaskIcon() override = default; + ; Glib::PropertyProxy<int> property_active() { return _property_active.get_proxy(); } - Glib::PropertyProxy< Glib::RefPtr<Gdk::Pixbuf> > property_pixbuf_on(); - Glib::PropertyProxy< Glib::RefPtr<Gdk::Pixbuf> > property_pixbuf_off(); + Glib::PropertyProxy<Glib::RefPtr<Gdk::Pixbuf>> property_pixbuf_on(); + Glib::PropertyProxy<Glib::RefPtr<Gdk::Pixbuf>> property_pixbuf_off(); protected: + 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) override; - 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 ) override; + void get_preferred_width_vfunc(Gtk::Widget &widget, int &min_w, int &nat_w) const override; - void get_preferred_width_vfunc(Gtk::Widget& widget, - int& min_w, - int& nat_w) const override; - - void get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const override; - - bool activate_vfunc(GdkEvent *event, - Gtk::Widget &widget, - const Glib::ustring &path, - const Gdk::Rectangle &background_area, - const Gdk::Rectangle &cell_area, - Gtk::CellRendererState flags) override; + void get_preferred_height_vfunc(Gtk::Widget &widget, int &min_h, int &nat_h) const override; + bool activate_vfunc(GdkEvent *event, Gtk::Widget &widget, const Glib::ustring &path, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) override; private: int phys; - + Glib::ustring _pixClipName; Glib::ustring _pixMaskName; Glib::ustring _pixBothName; - + Glib::Property<int> _property_active; - Glib::Property< Glib::RefPtr<Gdk::Pixbuf> > _property_pixbuf_clip; - Glib::Property< Glib::RefPtr<Gdk::Pixbuf> > _property_pixbuf_mask; - Glib::Property< Glib::RefPtr<Gdk::Pixbuf> > _property_pixbuf_both; - + Glib::Property<Glib::RefPtr<Gdk::Pixbuf>> _property_pixbuf_clip; + Glib::Property<Glib::RefPtr<Gdk::Pixbuf>> _property_pixbuf_mask; + Glib::Property<Glib::RefPtr<Gdk::Pixbuf>> _property_pixbuf_both; }; - - } // namespace Widget } // namespace UI } // namespace Inkscape - #endif /* __UI_DIALOG_IMAGETOGGLER_H__ */ /* diff --git a/src/ui/widget/color-entry.cpp b/src/ui/widget/color-entry.cpp index 804350c6b02957eb8dde4d42271268ce75ca7ae4..1ae5da17334a1e28c412cbb0cba93d1b65095bd7 100644 --- a/src/ui/widget/color-entry.cpp +++ b/src/ui/widget/color-entry.cpp @@ -8,12 +8,12 @@ * Copyright (C) 2014 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "color-entry.h" + #include <glibmm.h> #include <glibmm/i18n.h> #include <iomanip> -#include "color-entry.h" - namespace Inkscape { namespace UI { namespace Widget { @@ -56,7 +56,7 @@ void ColorEntry::on_changed() return; } if (_updatingrgba) { - return; // Typing text into entry box + return; // Typing text into entry box } Glib::ustring text = get_text(); @@ -122,7 +122,6 @@ void ColorEntry::on_changed() g_free(str); } - void ColorEntry::_onColorChanged() { if (_updatingrgba) { @@ -142,9 +141,9 @@ void ColorEntry::_onColorChanged() _updating = false; } } -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: mode:c++ diff --git a/src/ui/widget/color-entry.h b/src/ui/widget/color-entry.h index 4df80def9cc9979a59f86efbcab6bcf984fe2178..656e0794df2702ed6c40d61e29fc161adc56a1ef 100644 --- a/src/ui/widget/color-entry.h +++ b/src/ui/widget/color-entry.h @@ -13,6 +13,7 @@ #define SEEN_COLOR_ENTRY_H #include <gtkmm/entry.h> + #include "ui/selected-color.h" namespace Inkscape { @@ -41,9 +42,9 @@ private: int _prevpos; }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif /* diff --git a/src/ui/widget/color-icc-selector.cpp b/src/ui/widget/color-icc-selector.cpp index a8046a678a29c195a37ab9faa1d652ba914229e2..79d6302455e004f450255bdec0b1bc9c2395a35d 100644 --- a/src/ui/widget/color-icc-selector.cpp +++ b/src/ui/widget/color-icc-selector.cpp @@ -8,22 +8,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif +#include <glibmm/i18n.h> +#include <gtkmm/adjustment.h> #include <set> #include <utility> -#include <gtkmm/adjustment.h> -#include <glibmm/i18n.h> - #include "colorspace.h" #include "document.h" #include "inkscape.h" #include "profile-manager.h" - #include "svg/svg-icc-color.h" - #include "ui/dialog-events.h" #include "ui/util.h" #include "ui/widget/color-icc-selector.h" @@ -33,9 +30,9 @@ #define noDEBUG_LCMS #if defined(HAVE_LIBLCMS2) -#include "object/color-profile.h" #include "cms-system.h" #include "color-profile-cms-fns.h" +#include "object/color-profile.h" #ifdef DEBUG_LCMS #include "preferences.h" @@ -44,26 +41,25 @@ #ifdef DEBUG_LCMS extern guint update_in_progress; -#define DEBUG_MESSAGE(key, ...) \ - { \ - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); \ - bool dump = prefs->getBool("/options/scislac/" #key); \ - bool dumpD = prefs->getBool("/options/scislac/" #key "D"); \ - bool dumpD2 = prefs->getBool("/options/scislac/" #key "D2"); \ - dumpD && = ((update_in_progress == 0) || dumpD2); \ - if (dump) { \ - g_message(__VA_ARGS__); \ - } \ - if (dumpD) { \ - GtkWidget *dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, \ - GTK_BUTTONS_OK, __VA_ARGS__); \ - g_signal_connect_swapped(dialog, "response", G_CALLBACK(gtk_widget_destroy), dialog); \ - gtk_widget_show_all(dialog); \ - } \ +#define DEBUG_MESSAGE(key, ...) \ + { \ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); \ + bool dump = prefs->getBool("/options/scislac/" #key); \ + bool dumpD = prefs->getBool("/options/scislac/" #key "D"); \ + bool dumpD2 = prefs->getBool("/options/scislac/" #key "D2"); \ + dumpD && = ((update_in_progress == 0) || dumpD2); \ + if (dump) { \ + g_message(__VA_ARGS__); \ + } \ + if (dumpD) { \ + GtkWidget *dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, \ + GTK_BUTTONS_OK, __VA_ARGS__); \ + g_signal_connect_swapped(dialog, "response", G_CALLBACK(gtk_widget_destroy), dialog); \ + gtk_widget_show_all(dialog); \ + } \ } #endif // DEBUG_LCMS - #define XPAD 4 #define YPAD 1 @@ -114,20 +110,17 @@ icSigCmyData #define SPACE_ID_CMY 1 #define SPACE_ID_CMYK 2 - colorspace::Component::Component() : name() , tip() , scale(1) -{ -} +{} colorspace::Component::Component(std::string name, std::string tip, guint scale) : name(std::move(name)) , tip(std::move(tip)) , scale(scale) -{ -} +{} #if defined(HAVE_LIBLCMS2) static cmsUInt16Number *getScratch() @@ -140,7 +133,7 @@ static cmsUInt16Number *getScratch() std::vector<colorspace::Component> colorspace::getColorSpaceInfo(uint32_t space) { - static std::map<cmsUInt32Number, std::vector<Component> > sets; + static std::map<cmsUInt32Number, std::vector<Component>> sets; if (sets.empty()) { sets[cmsSigXYZData].push_back(Component("_X", "X", 2)); // TYPE_XYZ_16 sets[cmsSigXYZData].push_back(Component("_Y", "Y", 1)); @@ -183,7 +176,7 @@ std::vector<colorspace::Component> colorspace::getColorSpaceInfo(uint32_t space) sets[cmsSigCmyData].push_back(Component(_("_M:"), _("Magenta"), 1)); sets[cmsSigCmyData].push_back(Component(_("_Y:"), _("Yellow"), 1)); - for (auto & set : sets) { + for (auto &set : sets) { knownColorspaces.insert(set.first); maxColorspaceComponentCount = std::max(maxColorspaceComponentCount, set.second.size()); } @@ -197,7 +190,6 @@ std::vector<colorspace::Component> colorspace::getColorSpaceInfo(uint32_t space) return target; } - std::vector<colorspace::Component> colorspace::getColorSpaceInfo(Inkscape::ColorProfile *prof) { return getColorSpaceInfo(asICColorSpaceSig(prof->getColorSpace())); @@ -212,8 +204,9 @@ namespace Widget { /** * Class containing the parts for a single color component's UI presence. */ -class ComponentUI { - public: +class ComponentUI +{ +public: ComponentUI() : _component() , _adj(nullptr) @@ -221,8 +214,7 @@ class ComponentUI { , _btn(nullptr) , _label(nullptr) , _map(nullptr) - { - } + {} ComponentUI(colorspace::Component component) : _component(std::move(component)) @@ -231,8 +223,7 @@ class ComponentUI { , _btn(nullptr) , _label(nullptr) , _map(nullptr) - { - } + {} colorspace::Component _component; Glib::RefPtr<Gtk::Adjustment> _adj; // Component adjustment @@ -245,8 +236,9 @@ class ComponentUI { /** * Class that implements the internals of the selector. */ -class ColorICCSelectorImpl { - public: +class ColorICCSelectorImpl +{ +public: ColorICCSelectorImpl(ColorICCSelector *owner, SelectedColor &color); ~ColorICCSelectorImpl(); @@ -292,8 +284,6 @@ class ColorICCSelectorImpl { #endif // defined(HAVE_LIBLCMS2) }; - - const gchar *ColorICCSelector::MODE_NAME = N_("CMS"); ColorICCSelector::ColorICCSelector(SelectedColor &color) @@ -313,8 +303,6 @@ ColorICCSelector::~ColorICCSelector() } } - - ColorICCSelectorImpl::ColorICCSelectorImpl(ColorICCSelector *owner, SelectedColor &color) : _owner(owner) , _color(color) @@ -334,8 +322,7 @@ ColorICCSelectorImpl::ColorICCSelectorImpl(ColorICCSelector *owner, SelectedColo , _profChannelCount(0) , _profChangedID(0) #endif // defined(HAVE_LIBLCMS2) -{ -} +{} ColorICCSelectorImpl::~ColorICCSelectorImpl() { @@ -357,7 +344,6 @@ void ColorICCSelector::init() // Create components row = 0; - _impl->_fixupBtn = gtk_button_new_with_label(_("Fix")); g_signal_connect(G_OBJECT(_impl->_fixupBtn), "clicked", G_CALLBACK(ColorICCSelectorImpl::_fixupHit), (gpointer)_impl); @@ -391,7 +377,6 @@ void ColorICCSelector::init() gtk_widget_set_sensitive(_impl->_profileSel, false); #endif // defined(HAVE_LIBLCMS2) - row++; // populate the data for colorspaces and channels: @@ -403,8 +388,7 @@ void ColorICCSelector::init() #if defined(HAVE_LIBLCMS2) if (i < things.size()) { _impl->_compUI.emplace_back(things[i]); - } - else { + } else { _impl->_compUI.emplace_back(); } @@ -431,8 +415,7 @@ void ColorICCSelector::init() _impl->_compUI[i]._adj = Gtk::Adjustment::create(0.0, 0.0, scaleValue, step, page, page); // Slider - _impl->_compUI[i]._slider = - Gtk::manage(new Inkscape::UI::Widget::ColorSlider(_impl->_compUI[i]._adj)); + _impl->_compUI[i]._slider = Gtk::manage(new Inkscape::UI::Widget::ColorSlider(_impl->_compUI[i]._adj)); #if defined(HAVE_LIBLCMS2) _impl->_compUI[i]._slider->set_tooltip_text((i < things.size()) ? things[i].tip.c_str() : ""); #else @@ -459,9 +442,9 @@ void ColorICCSelector::init() _impl->_compUI[i]._map = g_new(guchar, 4 * 1024); memset(_impl->_compUI[i]._map, 0x0ff, 1024 * 4); - // Signals - _impl->_compUI[i]._adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(_impl, &ColorICCSelectorImpl::_adjustmentChanged), _impl->_compUI[i]._adj)); + _impl->_compUI[i]._adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(_impl, &ColorICCSelectorImpl::_adjustmentChanged), _impl->_compUI[i]._adj)); _impl->_compUI[i]._slider->signal_grabbed.connect(sigc::mem_fun(_impl, &ColorICCSelectorImpl::_sliderGrabbed)); _impl->_compUI[i]._slider->signal_released.connect( @@ -493,7 +476,6 @@ void ColorICCSelector::init() _impl->_slider->setColors(SP_RGBA32_F_COMPOSE(1.0, 1.0, 1.0, 0.0), SP_RGBA32_F_COMPOSE(1.0, 1.0, 1.0, 0.5), SP_RGBA32_F_COMPOSE(1.0, 1.0, 1.0, 1.0)); - // Spinbutton _impl->_sbtn = gtk_spin_button_new(_impl->_adj->gobj(), 1.0, 0); gtk_widget_set_tooltip_text(_impl->_sbtn, _("Alpha (opacity)")); @@ -504,7 +486,8 @@ void ColorICCSelector::init() attachToGridOrTable(t, _impl->_sbtn, 2, row, 1, 1, false, true); // Signals - _impl->_adj->signal_value_changed().connect(sigc::bind(sigc::mem_fun(_impl, &ColorICCSelectorImpl::_adjustmentChanged), _impl->_adj)); + _impl->_adj->signal_value_changed().connect( + sigc::bind(sigc::mem_fun(_impl, &ColorICCSelectorImpl::_adjustmentChanged), _impl->_adj)); _impl->_slider->signal_grabbed.connect(sigc::mem_fun(_impl, &ColorICCSelectorImpl::_sliderGrabbed)); _impl->_slider->signal_released.connect(sigc::mem_fun(_impl, &ColorICCSelectorImpl::_sliderReleased)); @@ -550,15 +533,13 @@ void ColorICCSelectorImpl::_switchToProfile(gchar const *name) #ifdef DEBUG_LCMS g_message("Already at name [%s]", name); #endif // DEBUG_LCMS - } - else { + } else { #ifdef DEBUG_LCMS g_message("Need to switch to profile [%s]", name); #endif // DEBUG_LCMS if (tmp.icc) { tmp.icc->colors.clear(); - } - else { + } else { tmp.icc = new SVGICCColor(); } tmp.icc->colorProfile = name; @@ -567,15 +548,12 @@ void ColorICCSelectorImpl::_switchToProfile(gchar const *name) cmsHTRANSFORM trans = newProf->getTransfFromSRGB8(); if (trans) { guint32 val = _color.color().toRGBA32(0); - guchar pre[4] = { - static_cast<guchar>(SP_RGBA32_R_U(val)), - static_cast<guchar>(SP_RGBA32_G_U(val)), - static_cast<guchar>(SP_RGBA32_B_U(val)), - 255}; + guchar pre[4] = {static_cast<guchar>(SP_RGBA32_R_U(val)), static_cast<guchar>(SP_RGBA32_G_U(val)), + static_cast<guchar>(SP_RGBA32_B_U(val)), 255}; #ifdef DEBUG_LCMS g_message("Shoving in [%02x] [%02x] [%02x]", pre[0], pre[1], pre[2]); #endif // DEBUG_LCMS - cmsUInt16Number post[4] = { 0, 0, 0, 0 }; + cmsUInt16Number post[4] = {0, 0, 0, 0}; cmsDoTransform(trans, pre, post, 1); #ifdef DEBUG_LCMS g_message("got on out [%04x] [%04x] [%04x] [%04x]", post[0], post[1], post[2], post[3]); @@ -608,8 +586,7 @@ void ColorICCSelectorImpl::_switchToProfile(gchar const *name) } } } - } - else { + } else { #ifdef DEBUG_LCMS g_message("NUKE THE ICC"); #endif // DEBUG_LCMS @@ -618,8 +595,7 @@ void ColorICCSelectorImpl::_switchToProfile(gchar const *name) tmp.icc = nullptr; dirty = true; _fixupHit(nullptr, this); - } - else { + } else { #ifdef DEBUG_LCMS g_message("No icc to nuke"); #endif // DEBUG_LCMS @@ -642,22 +618,26 @@ void ColorICCSelectorImpl::_switchToProfile(gchar const *name) #endif // defined(HAVE_LIBLCMS2) #if defined(HAVE_LIBLCMS2) -struct _cmp { - bool operator()(const SPObject * const & a, const SPObject * const & b) - { - const Inkscape::ColorProfile &a_prof = reinterpret_cast<const Inkscape::ColorProfile &>(*a); - const Inkscape::ColorProfile &b_prof = reinterpret_cast<const Inkscape::ColorProfile &>(*b); - gchar *a_name_casefold = g_utf8_casefold(a_prof.name, -1 ); - gchar *b_name_casefold = g_utf8_casefold(b_prof.name, -1 ); - int result = g_strcmp0(a_name_casefold, b_name_casefold); - g_free(a_name_casefold); - g_free(b_name_casefold); - return result < 0; - } +struct _cmp +{ + bool operator()(const SPObject *const &a, const SPObject *const &b) + { + const Inkscape::ColorProfile &a_prof = reinterpret_cast<const Inkscape::ColorProfile &>(*a); + const Inkscape::ColorProfile &b_prof = reinterpret_cast<const Inkscape::ColorProfile &>(*b); + gchar *a_name_casefold = g_utf8_casefold(a_prof.name, -1); + gchar *b_name_casefold = g_utf8_casefold(b_prof.name, -1); + int result = g_strcmp0(a_name_casefold, b_name_casefold); + g_free(a_name_casefold); + g_free(b_name_casefold); + return result < 0; + } }; template <typename From, typename To> -struct static_caster { To * operator () (From * value) const { return static_cast<To *>(value); } }; +struct static_caster +{ + To *operator()(From *value) const { return static_cast<To *>(value); } +}; void ColorICCSelectorImpl::_profilesChanged(std::string const &name) { @@ -678,12 +658,10 @@ void ColorICCSelectorImpl::_profilesChanged(std::string const &name) std::vector<SPObject *> current = SP_ACTIVE_DOCUMENT->getResourceList("iccprofile"); std::set<Inkscape::ColorProfile *> _current; - std::transform(current.begin(), - current.end(), - std::inserter(_current, _current.begin()), + std::transform(current.begin(), current.end(), std::inserter(_current, _current.begin()), static_caster<SPObject, Inkscape::ColorProfile>()); - for (auto &it: _current) { + for (auto &it : _current) { Inkscape::ColorProfile *prof = it; gtk_list_store_append(store, &iter); @@ -714,7 +692,7 @@ void ColorICCSelector::on_show() void ColorICCSelector::_colorChanged() { _impl->_updating = TRUE; -// sp_color_icc_set_color( SP_COLOR_ICC( _icc ), &color ); + // sp_color_icc_set_color( SP_COLOR_ICC( _icc ), &color ); #ifdef DEBUG_LCMS g_message("/^^^^^^^^^ %p::_colorChanged(%08x:%s)", this, _impl->_color.color().toRGBA32(_impl->_color.alpha()), @@ -743,15 +721,14 @@ void ColorICCSelector::_colorChanged() if (_impl->_compUI[i]._component.scale == 256) { val = (_impl->_color.color().icc->colors[i] + 128.0) / static_cast<gdouble>(_impl->_compUI[i]._component.scale); - } - else { + } else { val = _impl->_color.color().icc->colors[i] / static_cast<gdouble>(_impl->_compUI[i]._component.scale); } } tmp[i] = val * 0x0ffff; } - guchar post[4] = { 0, 0, 0, 0 }; + guchar post[4] = {0, 0, 0, 0}; cmsHTRANSFORM trans = _impl->_prof->getTransfToSRGB8(); if (trans) { cmsDoTransform(trans, tmp, post, 1); @@ -771,7 +748,6 @@ void ColorICCSelector::_colorChanged() #endif // defined(HAVE_LIBLCMS2) _impl->_updateSliders(-1); - _impl->_updating = FALSE; #ifdef DEBUG_LCMS g_message("\\_________ %p::_colorChanged()", this); @@ -791,12 +767,11 @@ void ColorICCSelectorImpl::_setProfile(SVGICCColor *profile) _profileName.clear(); _prof = nullptr; _profChannelCount = 0; - } - else if (profile && !_prof) { + } else if (profile && !_prof) { profChanged = true; } - for (auto & i : _compUI) { + for (auto &i : _compUI) { gtk_widget_hide(i._label); i._slider->hide(); gtk_widget_hide(i._btn); @@ -850,8 +825,7 @@ void ColorICCSelectorImpl::_setProfile(SVGICCColor *profile) gtk_widget_hide(_compUI[i]._btn); } } - } - else { + } else { // Give up for now on named colors _prof = nullptr; } @@ -872,8 +846,7 @@ void ColorICCSelectorImpl::_updateSliders(gint ignore) if (_color.color().icc->colors.size() > i) { if (_compUI[i]._component.scale == 256) { val = (_color.color().icc->colors[i] + 128.0) / static_cast<gdouble>(_compUI[i]._component.scale); - } - else { + } else { val = _color.color().icc->colors[i] / static_cast<gdouble>(_compUI[i]._component.scale); } } @@ -885,7 +858,7 @@ void ColorICCSelectorImpl::_updateSliders(gint ignore) for (guint i = 0; i < _profChannelCount; i++) { if (static_cast<gint>(i) != ignore) { cmsUInt16Number *scratch = getScratch(); - cmsUInt16Number filler[4] = { 0, 0, 0, 0 }; + cmsUInt16Number filler[4] = {0, 0, 0, 0}; for (guint j = 0; j < _profChannelCount; j++) { filler[j] = 0x0ffff * ColorScales::getScaled(_compUI[j]._adj); } @@ -895,8 +868,7 @@ void ColorICCSelectorImpl::_updateSliders(gint ignore) for (guint j = 0; j < _profChannelCount; j++) { if (j == i) { *p++ = x * 0x0ffff / 1024; - } - else { + } else { *p++ = filler[j]; } } @@ -905,8 +877,7 @@ void ColorICCSelectorImpl::_updateSliders(gint ignore) cmsHTRANSFORM trans = _prof->getTransfToSRGB8(); if (trans) { cmsDoTransform(trans, scratch, _compUI[i]._map, 1024); - if (_compUI[i]._slider) - { + if (_compUI[i]._slider) { _compUI[i]._slider->setMap(_compUI[i]._map); } } @@ -926,7 +897,6 @@ void ColorICCSelectorImpl::_updateSliders(gint ignore) _slider->setColors(start, mid, end); } - void ColorICCSelectorImpl::_adjustmentChanged(Glib::RefPtr<Gtk::Adjustment> &adjustment) { #ifdef DEBUG_LCMS @@ -948,8 +918,7 @@ void ColorICCSelectorImpl::_adjustmentChanged(Glib::RefPtr<Gtk::Adjustment> &adj #ifdef DEBUG_LCMS g_message("ALPHA"); #endif // DEBUG_LCMS - } - else { + } else { #if defined(HAVE_LIBLCMS2) for (size_t i = 0; i < iccSelector->_impl->_compUI.size(); i++) { if (iccSelector->_impl->_compUI[i]._adj == adjustment) { @@ -963,12 +932,11 @@ void ColorICCSelectorImpl::_adjustmentChanged(Glib::RefPtr<Gtk::Adjustment> &adj #endif // DEBUG_LCMS } - cmsUInt16Number tmp[4]; for (guint i = 0; i < 4; i++) { tmp[i] = ColorScales::getScaled(iccSelector->_impl->_compUI[i]._adj) * 0x0ffff; } - guchar post[4] = { 0, 0, 0, 0 }; + guchar post[4] = {0, 0, 0, 0}; cmsHTRANSFORM trans = iccSelector->_impl->_prof->getTransfToSRGB8(); if (trans) { @@ -1055,10 +1023,13 @@ Gtk::Widget *ColorICCSelectorFactory::createWidget(Inkscape::UI::SelectedColor & return w; } -Glib::ustring ColorICCSelectorFactory::modeName() const { return gettext(ColorICCSelector::MODE_NAME); } -} -} +Glib::ustring ColorICCSelectorFactory::modeName() const +{ + return gettext(ColorICCSelector::MODE_NAME); } +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: mode:c++ diff --git a/src/ui/widget/color-icc-selector.h b/src/ui/widget/color-icc-selector.h index 2c5ec419b42723d8803de949cae298924762b89b..f70c2646fb697e0eacd68606f9ba38839d70b419 100644 --- a/src/ui/widget/color-icc-selector.h +++ b/src/ui/widget/color-icc-selector.h @@ -10,8 +10,8 @@ #ifndef SEEN_SP_COLOR_ICC_SELECTOR_H #define SEEN_SP_COLOR_ICC_SELECTOR_H -#include <gtkmm/widget.h> #include <gtkmm/grid.h> +#include <gtkmm/widget.h> #include "ui/selected-color.h" @@ -24,10 +24,9 @@ namespace Widget { class ColorICCSelectorImpl; -class ColorICCSelector - : public Gtk::Grid - { - public: +class ColorICCSelector : public Gtk::Grid +{ +public: static const gchar *MODE_NAME; ColorICCSelector(SelectedColor &color); @@ -35,14 +34,14 @@ class ColorICCSelector virtual void init(); - protected: +protected: void on_show() override; virtual void _colorChanged(); void _recalcColor(gboolean changing); - private: +private: friend class ColorICCSelectorImpl; // By default, disallow copy constructor and assignment operator @@ -52,15 +51,15 @@ class ColorICCSelector ColorICCSelectorImpl *_impl; }; - -class ColorICCSelectorFactory : public ColorSelectorFactory { - public: +class ColorICCSelectorFactory : public ColorSelectorFactory +{ +public: Gtk::Widget *createWidget(SelectedColor &color) const override; Glib::ustring modeName() const override; }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif // SEEN_SP_COLOR_ICC_SELECTOR_H /* diff --git a/src/ui/widget/color-notebook.cpp b/src/ui/widget/color-notebook.cpp index 474b4d28777dd7bcde8eaad70e55d9f2992d1358..48ea1bf3d865c3b4bffe2967213099d9b40f8b72 100644 --- a/src/ui/widget/color-notebook.cpp +++ b/src/ui/widget/color-notebook.cpp @@ -12,7 +12,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #undef SPCS_PREVIEW @@ -26,15 +26,12 @@ #include "cms-system.h" #include "document.h" #include "inkscape.h" +#include "object/color-profile.h" #include "preferences.h" #include "profile-manager.h" - -#include "object/color-profile.h" -#include "ui/icon-loader.h" - #include "svg/svg-icc-color.h" - #include "ui/dialog-events.h" +#include "ui/icon-loader.h" #include "ui/tools-switch.h" #include "ui/tools/tool-base.h" #include "ui/widget/color-entry.h" @@ -42,7 +39,6 @@ #include "ui/widget/color-notebook.h" #include "ui/widget/color-scales.h" #include "ui/widget/color-wheel-selector.h" - #include "widgets/spw-utilities.h" using Inkscape::CMSSystem; @@ -54,7 +50,6 @@ namespace Inkscape { namespace UI { namespace Widget { - ColorNotebook::ColorNotebook(SelectedColor &color) : Gtk::Grid() , _selected_color(color) @@ -95,9 +90,7 @@ ColorNotebook::~ColorNotebook() ColorNotebook::Page::Page(Inkscape::UI::ColorSelectorFactory *selector_factory, bool enabled_full) : selector_factory(selector_factory) , enabled_full(enabled_full) -{ -} - +{} void ColorNotebook::_initUI() { @@ -168,7 +161,6 @@ void ColorNotebook::_initUI() gtk_box_pack_start(GTK_BOX(rgbabox), _box_toomuchink, FALSE, FALSE, 2); #endif // defined(HAVE_LIBLCMS2) - /* Color picker */ GtkWidget *picker = sp_get_icon_image("color-picker", GTK_ICON_SIZE_SMALL_TOOLBAR); _btn_picker = gtk_button_new(); @@ -231,7 +223,10 @@ void ColorNotebook::_onButtonClicked(GtkWidget *widget, ColorNotebook *nb) } } -void ColorNotebook::_onSelectedColorChanged() { _updateICCButtons(); } +void ColorNotebook::_onSelectedColorChanged() +{ + _updateICCButtons(); +} void ColorNotebook::_onPageSwitched(GtkNotebook *notebook, GtkWidget *page, guint page_num, ColorNotebook *colorbook) { @@ -242,7 +237,6 @@ void ColorNotebook::_onPageSwitched(GtkNotebook *notebook, GtkWidget *page, guin } } - // TODO pass in param so as to avoid the need for SP_ACTIVE_DOCUMENT void ColorNotebook::_updateICCButtons() { @@ -282,8 +276,7 @@ void ColorNotebook::_updateICCButtons() such as misalignment and poor quality of printing in general.*/ if (ink_sum > 3.2) gtk_widget_set_sensitive(_box_toomuchink, true); - } - else { + } else { gtk_widget_hide(GTK_WIDGET(_box_toomuchink)); } } @@ -325,9 +318,9 @@ void ColorNotebook::_addPage(Page &page) g_signal_connect(G_OBJECT(_buttons[page_num]), "clicked", G_CALLBACK(_onButtonClicked), this); } } -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/widget/color-notebook.h b/src/ui/widget/color-notebook.h index c7bc7b56b7e3df453e21226143b9ab29824473e6..60b7bf7f85f09e79192d66a453563c7fa7d9f5fe 100644 --- a/src/ui/widget/color-notebook.h +++ b/src/ui/widget/color-notebook.h @@ -14,12 +14,12 @@ #define SEEN_SP_COLOR_NOTEBOOK_H #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include <boost/ptr_container/ptr_vector.hpp> -#include <gtkmm/grid.h> #include <glib.h> +#include <gtkmm/grid.h> #include "color.h" #include "ui/selected-color.h" @@ -28,15 +28,15 @@ namespace Inkscape { namespace UI { namespace Widget { -class ColorNotebook - : public Gtk::Grid +class ColorNotebook : public Gtk::Grid { public: ColorNotebook(SelectedColor &color); ~ColorNotebook() override; protected: - struct Page { + struct Page + { Page(Inkscape::UI::ColorSelectorFactory *selector_factory, bool enabled_full); Inkscape::UI::ColorSelectorFactory *selector_factory; @@ -72,9 +72,9 @@ private: ColorNotebook(const ColorNotebook &obj) = delete; ColorNotebook &operator=(const ColorNotebook &obj) = delete; }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif // SEEN_SP_COLOR_NOTEBOOK_H /* Local Variables: @@ -86,4 +86,3 @@ private: End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - diff --git a/src/ui/widget/color-picker.cpp b/src/ui/widget/color-picker.cpp index 30c8f013fe6d048a957d06e2e734d247bd08e05a..bd57ce52e7b6828f27381eb461c7228f33022d24 100644 --- a/src/ui/widget/color-picker.cpp +++ b/src/ui/widget/color-picker.cpp @@ -12,24 +12,22 @@ */ #include "color-picker.h" -#include "inkscape.h" + #include "desktop.h" -#include "document.h" #include "document-undo.h" +#include "document.h" +#include "inkscape.h" #include "ui/dialog-events.h" - #include "ui/widget/color-notebook.h" #include "verbs.h" - static bool _in_use = false; namespace Inkscape { namespace UI { namespace Widget { -ColorPicker::ColorPicker (const Glib::ustring& title, const Glib::ustring& tip, - guint32 rgba, bool undo) +ColorPicker::ColorPicker(const Glib::ustring &title, const Glib::ustring &tip, guint32 rgba, bool undo) : _preview(new ColorPreview(rgba)) , _title(title) , _rgba(rgba) @@ -39,7 +37,7 @@ ColorPicker::ColorPicker (const Glib::ustring& title, const Glib::ustring& tip, setupDialog(title); _preview->show(); add(*Gtk::manage(_preview)); - set_tooltip_text (tip); + set_tooltip_text(tip); _selected_color.signal_changed.connect(sigc::mem_fun(this, &ColorPicker::_onSelectedColorChanged)); _selected_color.signal_dragged.connect(sigc::mem_fun(this, &ColorPicker::_onSelectedColorChanged)); _selected_color.signal_released.connect(sigc::mem_fun(this, &ColorPicker::_onSelectedColorChanged)); @@ -56,25 +54,27 @@ void ColorPicker::setupDialog(const Glib::ustring &title) sp_transientize(dlg); _colorSelectorDialog.hide(); - _colorSelectorDialog.set_title (title); - _colorSelectorDialog.set_border_width (4); + _colorSelectorDialog.set_title(title); + _colorSelectorDialog.set_border_width(4); _color_selector = Gtk::manage(new ColorNotebook(_selected_color)); - _colorSelectorDialog.get_content_area()->pack_start ( - *_color_selector, true, true, 0); + _colorSelectorDialog.get_content_area()->pack_start(*_color_selector, true, true, 0); _color_selector->show(); } -void ColorPicker::setSensitive(bool sensitive) { set_sensitive(sensitive); } +void ColorPicker::setSensitive(bool sensitive) +{ + set_sensitive(sensitive); +} -void ColorPicker::setRgba32 (guint32 rgba) +void ColorPicker::setRgba32(guint32 rgba) { - if (_in_use) return; + if (_in_use) + return; - _preview->setRgba32 (rgba); + _preview->setRgba32(rgba); _rgba = rgba; - if (_color_selector) - { + if (_color_selector) { _updating = true; _selected_color.setValue(rgba); _updating = false; @@ -88,8 +88,7 @@ void ColorPicker::closeWindow() void ColorPicker::on_clicked() { - if (_color_selector) - { + if (_color_selector) { _updating = true; _selected_color.setValue(_rgba); _updating = false; @@ -101,11 +100,10 @@ void ColorPicker::on_clicked() } } -void ColorPicker::on_changed (guint32) -{ -} +void ColorPicker::on_changed(guint32) {} -void ColorPicker::_onSelectedColorChanged() { +void ColorPicker::_onSelectedColorChanged() +{ if (_updating) { return; } @@ -130,10 +128,9 @@ void ColorPicker::_onSelectedColorChanged() { _rgba = rgba; } -}//namespace Widget -}//namespace UI -}//namespace Inkscape - +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/widget/color-picker.h b/src/ui/widget/color-picker.h index 7b29ff6d7b4f9a370e18928d036a9ac654c12949..23c70f045a46c1ffb3e8d3e476b4eef3805f6a16 100644 --- a/src/ui/widget/color-picker.h +++ b/src/ui/widget/color-picker.h @@ -14,88 +14,76 @@ #ifndef __COLOR_PICKER_H__ #define __COLOR_PICKER_H__ -#include "labelled.h" - #include <cstddef> - -#include "ui/selected-color.h" -#include "ui/widget/color-preview.h" #include <gtkmm/button.h> #include <gtkmm/dialog.h> #include <gtkmm/window.h> #include <sigc++/sigc++.h> -struct SPColorSelector; +#include "labelled.h" +#include "ui/selected-color.h" +#include "ui/widget/color-preview.h" -namespace Inkscape -{ -namespace UI -{ -namespace Widget -{ +struct SPColorSelector; +namespace Inkscape { +namespace UI { +namespace Widget { -class ColorPicker : public Gtk::Button { +class ColorPicker : public Gtk::Button +{ public: - - ColorPicker (const Glib::ustring& title, - const Glib::ustring& tip, - const guint32 rgba, - bool undo); + ColorPicker(const Glib::ustring &title, const Glib::ustring &tip, const guint32 rgba, bool undo); ~ColorPicker() override; - void setRgba32 (guint32 rgba); + void setRgba32(guint32 rgba); void setSensitive(bool sensitive); void closeWindow(); - sigc::connection connectChanged (const sigc::slot<void,guint>& slot) - { return _changed_signal.connect (slot); } + sigc::connection connectChanged(const sigc::slot<void, guint> &slot) { return _changed_signal.connect(slot); } protected: - void _onSelectedColorChanged(); void on_clicked() override; - virtual void on_changed (guint32); + virtual void on_changed(guint32); ColorPreview *_preview; /*const*/ Glib::ustring _title; - sigc::signal<void,guint32> _changed_signal; - guint32 _rgba; - bool _undo; - bool _updating; + sigc::signal<void, guint32> _changed_signal; + guint32 _rgba; + bool _undo; + bool _updating; - //Dialog + // Dialog void setupDialog(const Glib::ustring &title); - //Inkscape::UI::Dialog::Dialog _colorSelectorDialog; + // Inkscape::UI::Dialog::Dialog _colorSelectorDialog; Gtk::Dialog _colorSelectorDialog; SelectedColor _selected_color; Gtk::Widget *_color_selector; }; - -class LabelledColorPicker : public Labelled { +class LabelledColorPicker : public Labelled +{ public: + LabelledColorPicker(const Glib::ustring &label, const Glib::ustring &title, const Glib::ustring &tip, + const guint32 rgba, bool undo) + : Labelled(label, tip, new ColorPicker(title, tip, rgba, undo)) + {} - LabelledColorPicker (const Glib::ustring& label, - const Glib::ustring& title, - const Glib::ustring& tip, - const guint32 rgba, - bool undo) : Labelled(label, tip, new ColorPicker(title, tip, rgba, undo)) {} - - void setRgba32 (guint32 rgba) - { static_cast<ColorPicker*>(_widget)->setRgba32 (rgba); } + void setRgba32(guint32 rgba) { static_cast<ColorPicker *>(_widget)->setRgba32(rgba); } - void closeWindow() - { static_cast<ColorPicker*>(_widget)->closeWindow (); } + void closeWindow() { static_cast<ColorPicker *>(_widget)->closeWindow(); } - sigc::connection connectChanged (const sigc::slot<void,guint>& slot) - { return static_cast<ColorPicker*>(_widget)->connectChanged(slot); } + sigc::connection connectChanged(const sigc::slot<void, guint> &slot) + { + return static_cast<ColorPicker *>(_widget)->connectChanged(slot); + } }; -}//namespace Widget -}//namespace UI -}//namespace Inkscape +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif /* !__COLOR_PICKER_H__ */ diff --git a/src/ui/widget/color-preview.cpp b/src/ui/widget/color-preview.cpp index ac8fc5788fba8a5ee21d28a8d4dbaa3b38e6bc17..172bf709bff676cb3ec22f611872292803d13e8a 100644 --- a/src/ui/widget/color-preview.cpp +++ b/src/ui/widget/color-preview.cpp @@ -11,57 +11,53 @@ */ #include "ui/widget/color-preview.h" -#include "display/cairo-utils.h" + #include <cairo.h> +#include "display/cairo-utils.h" + #define SPCP_DEFAULT_WIDTH 32 #define SPCP_DEFAULT_HEIGHT 12 namespace Inkscape { - namespace UI { - namespace Widget { +namespace UI { +namespace Widget { -ColorPreview::ColorPreview (guint32 rgba) +ColorPreview::ColorPreview(guint32 rgba) { _rgba = rgba; set_has_window(false); set_name("ColorPreview"); } -void -ColorPreview::on_size_allocate (Gtk::Allocation &all) +void ColorPreview::on_size_allocate(Gtk::Allocation &all) { - set_allocation (all); + set_allocation(all); if (get_is_drawable()) queue_draw(); } -void -ColorPreview::get_preferred_height_vfunc(int& minimum_height, int& natural_height) const +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 +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 +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 +void ColorPreview::get_preferred_width_for_height_vfunc(int /* height */, int &minimum_width, int &natural_width) const { minimum_width = natural_width = SPCP_DEFAULT_WIDTH; } -void -ColorPreview::setRgba32 (guint32 rgba) +void ColorPreview::setRgba32(guint32 rgba) { _rgba = rgba; @@ -69,24 +65,23 @@ ColorPreview::setRgba32 (guint32 rgba) queue_draw(); } -bool -ColorPreview::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) +bool ColorPreview::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) { double x, y, width, height; - const Gtk::Allocation& allocation = get_allocation(); + const Gtk::Allocation &allocation = get_allocation(); x = 0; y = 0; - width = allocation.get_width()/2.0; + width = allocation.get_width() / 2.0; height = allocation.get_height(); double radius = height / 7.5; double degrees = M_PI / 180.0; - cairo_new_sub_path (cr->cobj()); + cairo_new_sub_path(cr->cobj()); cairo_line_to(cr->cobj(), width, 0); cairo_line_to(cr->cobj(), width, height); - cairo_arc (cr->cobj(), x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees); - cairo_arc (cr->cobj(), x + radius, y + radius, radius, 180 * degrees, 270 * degrees); - cairo_close_path (cr->cobj()); + cairo_arc(cr->cobj(), x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees); + cairo_arc(cr->cobj(), x + radius, y + radius, radius, 180 * degrees, 270 * degrees); + cairo_close_path(cr->cobj()); /* Transparent area */ @@ -102,20 +97,19 @@ ColorPreview::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) x = width; - cairo_new_sub_path (cr->cobj()); - cairo_arc (cr->cobj(), x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees); - cairo_arc (cr->cobj(), x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees); + cairo_new_sub_path(cr->cobj()); + cairo_arc(cr->cobj(), x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees); + cairo_arc(cr->cobj(), x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees); cairo_line_to(cr->cobj(), x, height); cairo_line_to(cr->cobj(), x, y); - cairo_close_path (cr->cobj()); + cairo_close_path(cr->cobj()); ink_cairo_set_source_rgba32(cr->cobj(), _rgba | 0xff); cr->fill(); - + return true; } -GdkPixbuf* -ColorPreview::toPixbuf (int width, int height) +GdkPixbuf *ColorPreview::toPixbuf(int width, int height) { GdkRectangle carea; gint w2; @@ -153,11 +147,13 @@ ColorPreview::toPixbuf (int width, int height) cairo_destroy(ct); cairo_surface_flush(s); - GdkPixbuf* pixbuf = ink_pixbuf_create_from_cairo_surface(s); + GdkPixbuf *pixbuf = ink_pixbuf_create_from_cairo_surface(s); return pixbuf; } -}}} +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/widget/color-preview.h b/src/ui/widget/color-preview.h index b7895792936bc8f53711e4eba2bb1820453bce55..d50bcff0a47f462ff154e51d63d5cda3f702522a 100644 --- a/src/ui/widget/color-preview.h +++ b/src/ui/widget/color-preview.h @@ -21,20 +21,21 @@ namespace Widget { /** * A simple color preview widget, mainly used within a picker button. */ -class ColorPreview : public Gtk::Widget { +class ColorPreview : public Gtk::Widget +{ public: - ColorPreview (guint32 rgba); - void setRgba32 (guint32 rgba); - GdkPixbuf* toPixbuf (int width, int height); + ColorPreview(guint32 rgba); + void setRgba32(guint32 rgba); + GdkPixbuf *toPixbuf(int width, int height); protected: - void on_size_allocate (Gtk::Allocation &all) override; + void on_size_allocate(Gtk::Allocation &all) override; - void get_preferred_height_vfunc(int& minimum_height, int& natural_height) const override; - void get_preferred_height_for_width_vfunc(int width, int& minimum_height, int& natural_height) const override; - void get_preferred_width_vfunc(int& minimum_width, int& natural_width) const override; - void get_preferred_width_for_height_vfunc(int height, int& minimum_width, int& natural_width) const override; - bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr) override; + void get_preferred_height_vfunc(int &minimum_height, int &natural_height) const override; + void get_preferred_height_for_width_vfunc(int width, int &minimum_height, int &natural_height) const override; + void get_preferred_width_vfunc(int &minimum_width, int &natural_width) const override; + void get_preferred_width_for_height_vfunc(int height, int &minimum_width, int &natural_width) const override; + bool on_draw(const Cairo::RefPtr<Cairo::Context> &cr) override; guint32 _rgba; }; diff --git a/src/ui/widget/color-scales.cpp b/src/ui/widget/color-scales.cpp index c10d14eca65b276bb419dad1435f6b8b6cca6d4e..a5133f8830725fe7550679cc8095a750cbf8e76d 100644 --- a/src/ui/widget/color-scales.cpp +++ b/src/ui/widget/color-scales.cpp @@ -10,11 +10,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm/adjustment.h> +#include "ui/widget/color-scales.h" + #include <glibmm/i18n.h> +#include <gtkmm/adjustment.h> #include "ui/dialog-events.h" -#include "ui/widget/color-scales.h" #include "ui/widget/color-slider.h" #define CSC_CHANNEL_R (1 << 0) @@ -41,10 +42,9 @@ namespace Inkscape { namespace UI { namespace Widget { - static const gchar *sp_color_scales_hue_map(); -const gchar *ColorScales::SUBMODE_NAMES[] = { N_("None"), N_("RGB"), N_("HSL"), N_("CMYK"), N_("HSV") }; +const gchar *ColorScales::SUBMODE_NAMES[] = {N_("None"), N_("RGB"), N_("HSL"), N_("CMYK"), N_("HSV")}; ColorScales::ColorScales(SelectedColor &color, SPColorScalesMode mode) : Gtk::Grid() @@ -126,13 +126,13 @@ void ColorScales::_initUI(SPColorScalesMode mode) gtk_grid_attach(GTK_GRID(t), _b[i], 2, i, 1, 1); /* Signals */ - _a[i]->signal_value_changed().connect(sigc::bind(sigc::mem_fun(this, &ColorScales::adjustment_changed),i)); + _a[i]->signal_value_changed().connect(sigc::bind(sigc::mem_fun(this, &ColorScales::adjustment_changed), i)); _s[i]->signal_grabbed.connect(sigc::mem_fun(this, &ColorScales::_sliderAnyGrabbed)); _s[i]->signal_released.connect(sigc::mem_fun(this, &ColorScales::_sliderAnyReleased)); _s[i]->signal_value_changed.connect(sigc::mem_fun(this, &ColorScales::_sliderAnyChanged)); } - //Prevent 5th bar from being shown by PanelDialog::show_all_children + // Prevent 5th bar from being shown by PanelDialog::show_all_children gtk_widget_set_no_show_all(_l[4], TRUE); _s[4]->set_no_show_all(true); gtk_widget_set_no_show_all(_b[4], TRUE); @@ -180,7 +180,7 @@ void ColorScales::_updateDisplay() _color.color().v.c[1], _color.color().v.c[2], _color.alpha()); #endif gfloat tmp[3]; - gfloat c[5] = { 0.0, 0.0, 0.0, 0.0 }; + gfloat c[5] = {0.0, 0.0, 0.0, 0.0}; SPColor color = _color.color(); @@ -235,9 +235,9 @@ void ColorScales::setScaled(Glib::RefPtr<Gtk::Adjustment> &a, gfloat v, bool con if (constrained) { // TODO: do we want preferences for these? if (upper == 255) { - val = round(val/16) * 16; + val = round(val / 16) * 16; } else { - val = round(val/10) * 10; + val = round(val / 10) * 10; } } a->set_value(val); @@ -246,7 +246,7 @@ void ColorScales::setScaled(Glib::RefPtr<Gtk::Adjustment> &a, gfloat v, bool con void ColorScales::_setRangeLimit(gdouble upper) { _rangeLimit = upper; - for (auto & i : _a) { + for (auto &i : _a) { i->set_upper(upper); } } @@ -346,8 +346,7 @@ void ColorScales::setMode(SPColorScalesMode mode) if ((_mode == SP_COLOR_SCALES_MODE_RGB) || (_mode == SP_COLOR_SCALES_MODE_HSL) || (_mode == SP_COLOR_SCALES_MODE_CMYK) || (_mode == SP_COLOR_SCALES_MODE_HSV)) { _getRgbaFloatv(rgba); - } - else { + } else { rgba[0] = rgba[1] = rgba[2] = rgba[3] = 1.0; } @@ -492,7 +491,10 @@ void ColorScales::setMode(SPColorScalesMode mode) } } -SPColorScalesMode ColorScales::getMode() const { return _mode; } +SPColorScalesMode ColorScales::getMode() const +{ + return _mode; +} void ColorScales::_sliderAnyGrabbed() { @@ -704,8 +706,7 @@ static const gchar *sp_color_scales_hue_map() ColorScalesFactory::ColorScalesFactory(SPColorScalesMode submode) : _submode(submode) -{ -} +{} ColorScalesFactory::~ColorScalesFactory() = default; @@ -715,10 +716,11 @@ Gtk::Widget *ColorScalesFactory::createWidget(Inkscape::UI::SelectedColor &color return w; } -Glib::ustring ColorScalesFactory::modeName() const { +Glib::ustring ColorScalesFactory::modeName() const +{ return gettext(ColorScales::SUBMODE_NAMES[_submode]); } -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape diff --git a/src/ui/widget/color-scales.h b/src/ui/widget/color-scales.h index 36702f6dfdd9011a91a99d153ff147046e84d976..fd3d7460d98ec7ca2870d0dc7f24d211e7eb3c73 100644 --- a/src/ui/widget/color-scales.h +++ b/src/ui/widget/color-scales.h @@ -20,7 +20,8 @@ namespace Widget { class ColorSlider; -enum SPColorScalesMode { +enum SPColorScalesMode +{ SP_COLOR_SCALES_MODE_NONE = 0, SP_COLOR_SCALES_MODE_RGB = 1, SP_COLOR_SCALES_MODE_HSL = 2, @@ -28,8 +29,7 @@ enum SPColorScalesMode { SP_COLOR_SCALES_MODE_HSV = 4 }; -class ColorScales - : public Gtk::Grid +class ColorScales : public Gtk::Grid { public: static const gchar *SUBMODE_NAMES[]; @@ -68,10 +68,10 @@ protected: gdouble _rangeLimit; gboolean _updating : 1; gboolean _dragging : 1; - std::vector<Glib::RefPtr<Gtk::Adjustment>> _a; /* Channel adjustments */ - Inkscape::UI::Widget::ColorSlider *_s[5]; /* Channel sliders */ - GtkWidget *_b[5]; /* Spinbuttons */ - GtkWidget *_l[5]; /* Labels */ + std::vector<Glib::RefPtr<Gtk::Adjustment>> _a; /* Channel adjustments */ + Inkscape::UI::Widget::ColorSlider *_s[5]; /* Channel sliders */ + GtkWidget *_b[5]; /* Spinbuttons */ + GtkWidget *_l[5]; /* Labels */ private: // By default, disallow copy constructor and assignment operator @@ -92,9 +92,9 @@ private: SPColorScalesMode _submode; }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif /* !SEEN_SP_COLOR_SCALES_H */ /* diff --git a/src/ui/widget/color-slider.cpp b/src/ui/widget/color-slider.cpp index f4c045cd24bdb3f10a70e70b85d2ead892b44c75..6ba394776f3005d341aa9441e0fde309f51f6a94 100644 --- a/src/ui/widget/color-slider.cpp +++ b/src/ui/widget/color-slider.cpp @@ -11,14 +11,15 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "ui/widget/color-slider.h" + #include <gdkmm/cursor.h> #include <gdkmm/general.h> #include <gtkmm/adjustment.h> #include <gtkmm/stylecontext.h> -#include "ui/widget/color-scales.h" -#include "ui/widget/color-slider.h" #include "preferences.h" +#include "ui/widget/color-scales.h" static const gint SLIDER_WIDTH = 96; static const gint SLIDER_HEIGHT = 8; @@ -158,17 +159,11 @@ bool ColorSlider::on_button_press_event(GdkEventButton *event) ColorScales::setScaled(_adjustment, value, constrained); signal_dragged.emit(); - auto window = _gdk_window->gobj(); - - auto seat = gdk_event_get_seat(reinterpret_cast<GdkEvent *>(event)); - gdk_seat_grab(seat, - window, - GDK_SEAT_CAPABILITY_ALL_POINTING, - FALSE, - nullptr, - reinterpret_cast<GdkEvent *>(event), - nullptr, - nullptr); + auto window = _gdk_window->gobj(); + + auto seat = gdk_event_get_seat(reinterpret_cast<GdkEvent *>(event)); + gdk_seat_grab(seat, window, GDK_SEAT_CAPABILITY_ALL_POINTING, FALSE, nullptr, + reinterpret_cast<GdkEvent *>(event), nullptr, nullptr); } return false; @@ -208,8 +203,7 @@ void ColorSlider::setAdjustment(Glib::RefPtr<Gtk::Adjustment> adjustment) { if (!adjustment) { _adjustment = Gtk::Adjustment::create(0.0, 0.0, 1.0, 0.01, 0.0, 0.0); - } - else { + } else { adjustment->set_page_increment(0.0); adjustment->set_page_size(0.0); } @@ -232,14 +226,17 @@ void ColorSlider::setAdjustment(Glib::RefPtr<Gtk::Adjustment> adjustment) } } -void ColorSlider::_onAdjustmentChanged() { queue_draw(); } +void ColorSlider::_onAdjustmentChanged() +{ + queue_draw(); +} void ColorSlider::_onAdjustmentValueChanged() { if (_value != ColorScales::getScaled(_adjustment)) { gint cx, cy, cw, ch; auto style_context = get_style_context(); - auto allocation = get_allocation(); + auto allocation = get_allocation(); auto padding = style_context->get_padding(get_state_flags()); cx = padding.get_left(); cy = padding.get_top(); @@ -256,8 +253,7 @@ void ColorSlider::_onAdjustmentValueChanged() ax = (int)(cx + _value * cw - ARROW_SIZE / 2 - 2); ay = cy; queue_draw_area(ax, ay, ARROW_SIZE + 4, ch); - } - else { + } else { _value = ColorScales::getScaled(_adjustment); } } @@ -306,7 +302,7 @@ bool ColorSlider::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) { gboolean colorsOnTop = Inkscape::Preferences::get()->getBool("/options/workarounds/colorsontop", false); - auto allocation = get_allocation(); + auto allocation = get_allocation(); auto style_context = get_style_context(); // Draw shadow @@ -341,8 +337,7 @@ bool ColorSlider::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) Gdk::Cairo::set_source_pixbuf(cr, pb, carea.get_x(), carea.get_y()); cr->paint(); } - } - else { + } else { gint c[4], dc[4]; /* Render gradient */ diff --git a/src/ui/widget/color-slider.h b/src/ui/widget/color-slider.h index 6a0834e6fe057300a4a03968f86d37b1c4928b6c..09b47222e0c05cb22653cf3c86c914c9b2b6437e 100644 --- a/src/ui/widget/color-slider.h +++ b/src/ui/widget/color-slider.h @@ -23,7 +23,8 @@ namespace Widget { /* * A slider with colored background */ -class ColorSlider : public Gtk::Widget { +class ColorSlider : public Gtk::Widget +{ public: ColorSlider(Glib::RefPtr<Gtk::Adjustment> adjustment); ~ColorSlider() override; diff --git a/src/ui/widget/color-wheel-selector.cpp b/src/ui/widget/color-wheel-selector.cpp index 2e66d8d16f958e5a56ef6792b6bcdc3c896b1526..0b18373cafb1a5613f3524cdc23f3d64be420184 100644 --- a/src/ui/widget/color-wheel-selector.cpp +++ b/src/ui/widget/color-wheel-selector.cpp @@ -14,6 +14,7 @@ #include <gtkmm/adjustment.h> #include <gtkmm/label.h> #include <gtkmm/spinbutton.h> + #include "ui/dialog-events.h" #include "ui/widget/color-scales.h" #include "ui/widget/color-slider.h" @@ -23,11 +24,9 @@ namespace Inkscape { namespace UI { namespace Widget { - #define XPAD 4 #define YPAD 1 - const gchar *ColorWheelSelector::MODE_NAME = N_("Wheel"); ColorWheelSelector::ColorWheelSelector(SelectedColor &color) @@ -169,7 +168,7 @@ void ColorWheelSelector::_wheelChanged() return; } - double rgb[3] = { 0, 0, 0 }; + double rgb[3] = {0, 0, 0}; _wheel->get_rgb(rgb[0], rgb[1], rgb[2]); SPColor color(rgb[0], rgb[1], rgb[2]); @@ -189,7 +188,9 @@ void ColorWheelSelector::_wheelChanged() void ColorWheelSelector::_updateDisplay() { - if(_updating) { return; } + if (_updating) { + return; + } #ifdef DUMP_CHANGE_INFO g_message("ColorWheelSelector::_colorChanged( this=%p, %f, %f, %f, %f)", this, _color.color().v.c[0], @@ -198,7 +199,7 @@ void ColorWheelSelector::_updateDisplay() _updating = true; { - float hsv[3] = { 0, 0, 0 }; + float hsv[3] = {0, 0, 0}; SPColor::rgb_to_hsv_floatv(hsv, _color.color().v.c[0], _color.color().v.c[1], _color.color().v.c[2]); _wheel->set_rgb(_color.color().v.c[0], _color.color().v.c[1], _color.color().v.c[2]); } @@ -214,17 +215,19 @@ void ColorWheelSelector::_updateDisplay() _updating = false; } - Gtk::Widget *ColorWheelSelectorFactory::createWidget(Inkscape::UI::SelectedColor &color) const { Gtk::Widget *w = Gtk::manage(new ColorWheelSelector(color)); return w; } -Glib::ustring ColorWheelSelectorFactory::modeName() const { return gettext(ColorWheelSelector::MODE_NAME); } -} -} +Glib::ustring ColorWheelSelectorFactory::modeName() const +{ + return gettext(ColorWheelSelector::MODE_NAME); } +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: mode:c++ diff --git a/src/ui/widget/color-wheel-selector.h b/src/ui/widget/color-wheel-selector.h index 59cf6b626bfd030b330d35c80acdcc35d13ebac8..868326692e8909ce11b8bb13c97ad17a8b9afcd8 100644 --- a/src/ui/widget/color-wheel-selector.h +++ b/src/ui/widget/color-wheel-selector.h @@ -22,8 +22,7 @@ namespace Widget { class ColorSlider; class ColorWheel; -class ColorWheelSelector - : public Gtk::Grid +class ColorWheelSelector : public Gtk::Grid { public: static const gchar *MODE_NAME; @@ -60,14 +59,15 @@ private: sigc::connection _color_dragged_connection; }; -class ColorWheelSelectorFactory : public ColorSelectorFactory { +class ColorWheelSelectorFactory : public ColorSelectorFactory +{ public: Gtk::Widget *createWidget(SelectedColor &color) const override; Glib::ustring modeName() const override; }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif // SEEN_SP_COLOR_WHEEL_SELECTOR_H diff --git a/src/ui/widget/combo-box-entry-tool-item.cpp b/src/ui/widget/combo-box-entry-tool-item.cpp index a7a0d2dcb80780c78785dd199a1e179516d3d983..7e3d1685be5dd5bc95df01203d30f23adbe7caaa 100644 --- a/src/ui/widget/combo-box-entry-tool-item.cpp +++ b/src/ui/widget/combo-box-entry-tool-item.cpp @@ -26,13 +26,12 @@ #include "combo-box-entry-tool-item.h" -#include <iostream> #include <cstring> -#include <glibmm/ustring.h> - -#include <gtk/gtk.h> #include <gdk/gdkkeysyms.h> #include <gdkmm/display.h> +#include <glibmm/ustring.h> +#include <gtk/gtk.h> +#include <iostream> #include "ui/icon-names.h" @@ -40,50 +39,44 @@ namespace Inkscape { namespace UI { namespace Widget { -ComboBoxEntryToolItem::ComboBoxEntryToolItem(Glib::ustring name, - Glib::ustring label, - Glib::ustring tooltip, - GtkTreeModel *model, - gint entry_width, - gint extra_width, - void *cell_data_func, - void *separator_func, - GtkWidget *focusWidget) - : _label(std::move(label)), - _tooltip(std::move(tooltip)), - _model(model), - _entry_width(entry_width), - _extra_width(extra_width), - _cell_data_func(cell_data_func), - _separator_func(separator_func), - _focusWidget(focusWidget), - _active(-1), - _text(strdup("")), - _entry_completion(nullptr), - _indicator(nullptr), - _popup(false), - _info(nullptr), - _info_cb(nullptr), - _info_cb_id(0), - _info_cb_blocked(false), - _warning(nullptr), - _warning_cb(nullptr), - _warning_cb_id(0), - _warning_cb_blocked(false) +ComboBoxEntryToolItem::ComboBoxEntryToolItem(Glib::ustring name, Glib::ustring label, Glib::ustring tooltip, + GtkTreeModel *model, gint entry_width, gint extra_width, + void *cell_data_func, void *separator_func, GtkWidget *focusWidget) + : _label(std::move(label)) + , _tooltip(std::move(tooltip)) + , _model(model) + , _entry_width(entry_width) + , _extra_width(extra_width) + , _cell_data_func(cell_data_func) + , _separator_func(separator_func) + , _focusWidget(focusWidget) + , _active(-1) + , _text(strdup("")) + , _entry_completion(nullptr) + , _indicator(nullptr) + , _popup(false) + , _info(nullptr) + , _info_cb(nullptr) + , _info_cb_id(0) + , _info_cb_blocked(false) + , _warning(nullptr) + , _warning_cb(nullptr) + , _warning_cb_id(0) + , _warning_cb_blocked(false) { set_name(name); - gchar *action_name = g_strdup( get_name().c_str() ); - gchar *combobox_name = g_strjoin( nullptr, action_name, "_combobox", NULL ); - gchar *entry_name = g_strjoin( nullptr, action_name, "_entry", NULL ); - g_free( action_name ); + gchar *action_name = g_strdup(get_name().c_str()); + gchar *combobox_name = g_strjoin(nullptr, action_name, "_combobox", NULL); + gchar *entry_name = g_strjoin(nullptr, action_name, "_entry", NULL); + g_free(action_name); - GtkWidget* comboBoxEntry = gtk_combo_box_new_with_model_and_entry (_model); - gtk_combo_box_set_entry_text_column (GTK_COMBO_BOX (comboBoxEntry), 0); + GtkWidget *comboBoxEntry = gtk_combo_box_new_with_model_and_entry(_model); + gtk_combo_box_set_entry_text_column(GTK_COMBO_BOX(comboBoxEntry), 0); // Name it so we can muck with it using an RC file - gtk_widget_set_name( comboBoxEntry, combobox_name ); - g_free( combobox_name ); + gtk_widget_set_name(comboBoxEntry, combobox_name); + g_free(combobox_name); { gtk_widget_set_halign(comboBoxEntry, GTK_ALIGN_START); @@ -92,66 +85,61 @@ ComboBoxEntryToolItem::ComboBoxEntryToolItem(Glib::ustring name, add(*Glib::wrap(comboBoxEntry)); } - _combobox = GTK_COMBO_BOX (comboBoxEntry); + _combobox = GTK_COMBO_BOX(comboBoxEntry); - //gtk_combo_box_set_active( GTK_COMBO_BOX( comboBoxEntry ), ink_comboboxentry_action->active ); - gtk_combo_box_set_active( GTK_COMBO_BOX( comboBoxEntry ), 0 ); + // gtk_combo_box_set_active( GTK_COMBO_BOX( comboBoxEntry ), ink_comboboxentry_action->active ); + gtk_combo_box_set_active(GTK_COMBO_BOX(comboBoxEntry), 0); - g_signal_connect( G_OBJECT(comboBoxEntry), "changed", G_CALLBACK(combo_box_changed_cb), this ); + g_signal_connect(G_OBJECT(comboBoxEntry), "changed", G_CALLBACK(combo_box_changed_cb), this); // Optionally add separator function... - if( _separator_func != nullptr ) { - gtk_combo_box_set_row_separator_func( _combobox, - GtkTreeViewRowSeparatorFunc (_separator_func), - nullptr, nullptr ); + if (_separator_func != nullptr) { + gtk_combo_box_set_row_separator_func(_combobox, GtkTreeViewRowSeparatorFunc(_separator_func), nullptr, nullptr); } // FIXME: once gtk3 migration is done this can be removed // https://bugzilla.gnome.org/show_bug.cgi?id=734915 - gtk_widget_show_all (comboBoxEntry); + gtk_widget_show_all(comboBoxEntry); // Optionally add formatting... - if( _cell_data_func != nullptr ) { + if (_cell_data_func != nullptr) { GtkCellRenderer *cell = gtk_cell_renderer_text_new(); - gtk_cell_layout_clear( GTK_CELL_LAYOUT( comboBoxEntry ) ); - gtk_cell_layout_pack_start( GTK_CELL_LAYOUT( comboBoxEntry ), cell, true ); - gtk_cell_layout_set_cell_data_func (GTK_CELL_LAYOUT( comboBoxEntry ), cell, - GtkCellLayoutDataFunc (_cell_data_func), - nullptr, nullptr ); + gtk_cell_layout_clear(GTK_CELL_LAYOUT(comboBoxEntry)); + gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(comboBoxEntry), cell, true); + gtk_cell_layout_set_cell_data_func(GTK_CELL_LAYOUT(comboBoxEntry), cell, GtkCellLayoutDataFunc(_cell_data_func), + nullptr, nullptr); } // Optionally widen the combobox width... which widens the drop-down list in list mode. - if( _extra_width > 0 ) { + if (_extra_width > 0) { GtkRequisition req; gtk_widget_get_preferred_size(GTK_WIDGET(_combobox), &req, nullptr); - gtk_widget_set_size_request( GTK_WIDGET( _combobox ), - req.width + _extra_width, -1 ); + gtk_widget_set_size_request(GTK_WIDGET(_combobox), req.width + _extra_width, -1); } // Get reference to GtkEntry and fiddle a bit with it. - GtkWidget *child = gtk_bin_get_child( GTK_BIN(comboBoxEntry) ); + GtkWidget *child = gtk_bin_get_child(GTK_BIN(comboBoxEntry)); // Name it so we can muck with it using an RC file - gtk_widget_set_name( child, entry_name ); - g_free( entry_name ); - - if( child && GTK_IS_ENTRY( child ) ) { + gtk_widget_set_name(child, entry_name); + g_free(entry_name); + if (child && GTK_IS_ENTRY(child)) { _entry = GTK_ENTRY(child); // Change width - if( _entry_width > 0 ) { - gtk_entry_set_width_chars (GTK_ENTRY (child), _entry_width ); + if (_entry_width > 0) { + gtk_entry_set_width_chars(GTK_ENTRY(child), _entry_width); } // Add pop-up entry completion if required - if( _popup ) { + if (_popup) { popup_enable(); } // Add signal for GtkEntry to check if finished typing. - g_signal_connect( G_OBJECT(child), "activate", G_CALLBACK(entry_activate_cb), this ); - g_signal_connect( G_OBJECT(child), "key-press-event", G_CALLBACK(keypress_cb), this ); + g_signal_connect(G_OBJECT(child), "activate", G_CALLBACK(entry_activate_cb), this); + g_signal_connect(G_OBJECT(child), "key-press-event", G_CALLBACK(keypress_cb), this); } set_tooltip(_tooltip.c_str()); @@ -161,11 +149,10 @@ ComboBoxEntryToolItem::ComboBoxEntryToolItem(Glib::ustring name, // Setters/Getters --------------------------------------------------- -gchar* -ComboBoxEntryToolItem::get_active_text() +gchar *ComboBoxEntryToolItem::get_active_text() { - gchar* text = g_strdup( _text ); - return text; + gchar *text = g_strdup(_text); + return text; } /* @@ -178,243 +165,208 @@ ComboBoxEntryToolItem::get_active_text() * Text is not in the list store (i.e. default font-family is not on system): * In this case we have a row number of -1, and the text must be set by hand. */ -gboolean -ComboBoxEntryToolItem::set_active_text(const gchar* text, int row) +gboolean ComboBoxEntryToolItem::set_active_text(const gchar *text, int row) { - if( strcmp( _text, text ) != 0 ) { - g_free( _text ); - _text = g_strdup( text ); - } - - // Get active row or -1 if none - if( row < 0 ) { - row = get_active_row_from_text(this, _text); - } - _active = row; - - // Set active row, check that combobox has been created. - if( _combobox ) { - gtk_combo_box_set_active( GTK_COMBO_BOX( _combobox ), _active ); - } - - // Fiddle with entry - if( _entry ) { - - // Explicitly set text in GtkEntry box (won't be set if text not in list). - gtk_entry_set_text( _entry, text ); - - // Show or hide warning -- this might be better moved to text-toolbox.cpp - if( _info_cb_id != 0 && - !_info_cb_blocked ) { - g_signal_handler_block (G_OBJECT(_entry), - _info_cb_id ); - _info_cb_blocked = true; - } - if( _warning_cb_id != 0 && - !_warning_cb_blocked ) { - g_signal_handler_block (G_OBJECT(_entry), - _warning_cb_id ); - _warning_cb_blocked = true; + if (strcmp(_text, text) != 0) { + g_free(_text); + _text = g_strdup(text); } - bool set = false; - if( _warning != nullptr ) { - Glib::ustring missing = check_comma_separated_text(); - if( !missing.empty() ) { - gtk_entry_set_icon_from_icon_name( _entry, - GTK_ENTRY_ICON_SECONDARY, - INKSCAPE_ICON("dialog-warning") ); - // Can't add tooltip until icon set - Glib::ustring warning = _warning; - warning += ": "; - warning += missing; - gtk_entry_set_icon_tooltip_text( _entry, - GTK_ENTRY_ICON_SECONDARY, - warning.c_str() ); - - if( _warning_cb ) { - - // Add callback if we haven't already - if( _warning_cb_id == 0 ) { - _warning_cb_id = - g_signal_connect( G_OBJECT(_entry), - "icon-press", - G_CALLBACK(_warning_cb), - this); - } - // Unblock signal - if( _warning_cb_blocked ) { - g_signal_handler_unblock (G_OBJECT(_entry), - _warning_cb_id ); - _warning_cb_blocked = false; - } - } - set = true; - } + // Get active row or -1 if none + if (row < 0) { + row = get_active_row_from_text(this, _text); } - - if( !set && _info != nullptr ) { - gtk_entry_set_icon_from_icon_name( GTK_ENTRY(_entry), - GTK_ENTRY_ICON_SECONDARY, - INKSCAPE_ICON("edit-select-all") ); - gtk_entry_set_icon_tooltip_text( _entry, - GTK_ENTRY_ICON_SECONDARY, - _info ); - - if( _info_cb ) { - // Add callback if we haven't already - if( _info_cb_id == 0 ) { - _info_cb_id = - g_signal_connect( G_OBJECT(_entry), - "icon-press", - G_CALLBACK(_info_cb), - this); - } - // Unblock signal - if( _info_cb_blocked ) { - g_signal_handler_unblock (G_OBJECT(_entry), - _info_cb_id ); - _info_cb_blocked = false; - } - } - set = true; + _active = row; + + // Set active row, check that combobox has been created. + if (_combobox) { + gtk_combo_box_set_active(GTK_COMBO_BOX(_combobox), _active); } - if( !set ) { - gtk_entry_set_icon_from_icon_name( GTK_ENTRY(_entry), - GTK_ENTRY_ICON_SECONDARY, - nullptr ); + // Fiddle with entry + if (_entry) { + // Explicitly set text in GtkEntry box (won't be set if text not in list). + gtk_entry_set_text(_entry, text); + + // Show or hide warning -- this might be better moved to text-toolbox.cpp + if (_info_cb_id != 0 && !_info_cb_blocked) { + g_signal_handler_block(G_OBJECT(_entry), _info_cb_id); + _info_cb_blocked = true; + } + if (_warning_cb_id != 0 && !_warning_cb_blocked) { + g_signal_handler_block(G_OBJECT(_entry), _warning_cb_id); + _warning_cb_blocked = true; + } + + bool set = false; + if (_warning != nullptr) { + Glib::ustring missing = check_comma_separated_text(); + if (!missing.empty()) { + gtk_entry_set_icon_from_icon_name(_entry, GTK_ENTRY_ICON_SECONDARY, INKSCAPE_ICON("dialog-warning")); + // Can't add tooltip until icon set + Glib::ustring warning = _warning; + warning += ": "; + warning += missing; + gtk_entry_set_icon_tooltip_text(_entry, GTK_ENTRY_ICON_SECONDARY, warning.c_str()); + + if (_warning_cb) { + // Add callback if we haven't already + if (_warning_cb_id == 0) { + _warning_cb_id = + g_signal_connect(G_OBJECT(_entry), "icon-press", G_CALLBACK(_warning_cb), this); + } + // Unblock signal + if (_warning_cb_blocked) { + g_signal_handler_unblock(G_OBJECT(_entry), _warning_cb_id); + _warning_cb_blocked = false; + } + } + set = true; + } + } + + if (!set && _info != nullptr) { + gtk_entry_set_icon_from_icon_name(GTK_ENTRY(_entry), GTK_ENTRY_ICON_SECONDARY, + INKSCAPE_ICON("edit-select-all")); + gtk_entry_set_icon_tooltip_text(_entry, GTK_ENTRY_ICON_SECONDARY, _info); + + if (_info_cb) { + // Add callback if we haven't already + if (_info_cb_id == 0) { + _info_cb_id = g_signal_connect(G_OBJECT(_entry), "icon-press", G_CALLBACK(_info_cb), this); + } + // Unblock signal + if (_info_cb_blocked) { + g_signal_handler_unblock(G_OBJECT(_entry), _info_cb_id); + _info_cb_blocked = false; + } + } + set = true; + } + + if (!set) { + gtk_entry_set_icon_from_icon_name(GTK_ENTRY(_entry), GTK_ENTRY_ICON_SECONDARY, nullptr); + } } - } - // Return if active text in list - gboolean found = ( _active != -1 ); - return found; + // Return if active text in list + gboolean found = (_active != -1); + return found; } -void -ComboBoxEntryToolItem::set_entry_width(gint entry_width) +void ComboBoxEntryToolItem::set_entry_width(gint entry_width) { _entry_width = entry_width; // Clamp to limits - if(entry_width < -1) entry_width = -1; - if(entry_width > 100) entry_width = 100; + if (entry_width < -1) + entry_width = -1; + if (entry_width > 100) + entry_width = 100; // Widget may not have been created.... - if( _entry ) { - gtk_entry_set_width_chars( GTK_ENTRY(_entry), entry_width ); + if (_entry) { + gtk_entry_set_width_chars(GTK_ENTRY(_entry), entry_width); } } -void -ComboBoxEntryToolItem::set_extra_width( gint extra_width ) +void ComboBoxEntryToolItem::set_extra_width(gint extra_width) { _extra_width = extra_width; // Clamp to limits - if(extra_width < -1) extra_width = -1; - if(extra_width > 500) extra_width = 500; + if (extra_width < -1) + extra_width = -1; + if (extra_width > 500) + extra_width = 500; // Widget may not have been created.... - if( _combobox ) { + if (_combobox) { GtkRequisition req; gtk_widget_get_preferred_size(GTK_WIDGET(_combobox), &req, nullptr); - gtk_widget_set_size_request( GTK_WIDGET( _combobox ), req.width + _extra_width, -1 ); + gtk_widget_set_size_request(GTK_WIDGET(_combobox), req.width + _extra_width, -1); } } -void -ComboBoxEntryToolItem::focus_on_click( bool focus_on_click ) -{ +void ComboBoxEntryToolItem::focus_on_click(bool focus_on_click) +{ if (_combobox) { - gtk_widget_set_focus_on_click(GTK_WIDGET(_combobox), focus_on_click); + gtk_widget_set_focus_on_click(GTK_WIDGET(_combobox), focus_on_click); } } -void -ComboBoxEntryToolItem::popup_enable() +void ComboBoxEntryToolItem::popup_enable() { _popup = true; // Widget may not have been created.... - if( _entry ) { - + if (_entry) { // Check we don't already have a GtkEntryCompletion - if( _entry_completion ) return; + if (_entry_completion) + return; _entry_completion = gtk_entry_completion_new(); - gtk_entry_set_completion( _entry, _entry_completion ); - gtk_entry_completion_set_model( _entry_completion, _model ); - gtk_entry_completion_set_text_column( _entry_completion, 0 ); - gtk_entry_completion_set_popup_completion( _entry_completion, true ); - gtk_entry_completion_set_inline_completion( _entry_completion, false ); - gtk_entry_completion_set_inline_selection( _entry_completion, true ); + gtk_entry_set_completion(_entry, _entry_completion); + gtk_entry_completion_set_model(_entry_completion, _model); + gtk_entry_completion_set_text_column(_entry_completion, 0); + gtk_entry_completion_set_popup_completion(_entry_completion, true); + gtk_entry_completion_set_inline_completion(_entry_completion, false); + gtk_entry_completion_set_inline_selection(_entry_completion, true); - g_signal_connect (G_OBJECT (_entry_completion), "match-selected", G_CALLBACK (match_selected_cb), this); + g_signal_connect(G_OBJECT(_entry_completion), "match-selected", G_CALLBACK(match_selected_cb), this); } } -void -ComboBoxEntryToolItem::popup_disable() +void ComboBoxEntryToolItem::popup_disable() { - _popup = false; + _popup = false; - if( _entry_completion ) { - gtk_widget_destroy(GTK_WIDGET(_entry_completion)); - _entry_completion = nullptr; - } + if (_entry_completion) { + gtk_widget_destroy(GTK_WIDGET(_entry_completion)); + _entry_completion = nullptr; + } } -void -ComboBoxEntryToolItem::set_tooltip(const gchar* tooltip) +void ComboBoxEntryToolItem::set_tooltip(const gchar *tooltip) { set_tooltip_text(tooltip); - gtk_widget_set_tooltip_text ( GTK_WIDGET(_combobox), tooltip); + gtk_widget_set_tooltip_text(GTK_WIDGET(_combobox), tooltip); // Widget may not have been created.... - if( _entry ) { - gtk_widget_set_tooltip_text ( GTK_WIDGET(_entry), tooltip); + if (_entry) { + gtk_widget_set_tooltip_text(GTK_WIDGET(_entry), tooltip); } } -void -ComboBoxEntryToolItem::set_info(const gchar* info) +void ComboBoxEntryToolItem::set_info(const gchar *info) { - g_free( _info ); - _info = g_strdup( info ); + g_free(_info); + _info = g_strdup(info); // Widget may not have been created.... - if( _entry ) { - gtk_entry_set_icon_tooltip_text( GTK_ENTRY(_entry), - GTK_ENTRY_ICON_SECONDARY, - _info ); + if (_entry) { + gtk_entry_set_icon_tooltip_text(GTK_ENTRY(_entry), GTK_ENTRY_ICON_SECONDARY, _info); } } -void -ComboBoxEntryToolItem::set_info_cb(gpointer info_cb) +void ComboBoxEntryToolItem::set_info_cb(gpointer info_cb) { _info_cb = info_cb; } -void -ComboBoxEntryToolItem::set_warning(const gchar* warning) +void ComboBoxEntryToolItem::set_warning(const gchar *warning) { - g_free( _warning ); - _warning = g_strdup( warning ); - - // Widget may not have been created.... - if( _entry ) { - gtk_entry_set_icon_tooltip_text( GTK_ENTRY(_entry), - GTK_ENTRY_ICON_SECONDARY, - _warning ); - } + g_free(_warning); + _warning = g_strdup(warning); + + // Widget may not have been created.... + if (_entry) { + gtk_entry_set_icon_tooltip_text(GTK_ENTRY(_entry), GTK_ENTRY_ICON_SECONDARY, _warning); + } } -void -ComboBoxEntryToolItem::set_warning_cb(gpointer warning_cb) +void ComboBoxEntryToolItem::set_warning_cb(gpointer warning_cb) { _warning_cb = warning_cb; } @@ -425,60 +377,57 @@ ComboBoxEntryToolItem::set_warning_cb(gpointer warning_cb) // use 3d column if available to exclude row from checking (useful to // skip rows added for font-families included in doc and not on // system) -gint -ComboBoxEntryToolItem::get_active_row_from_text(ComboBoxEntryToolItem *action, - const gchar *target_text, - gboolean exclude, - gboolean ignore_case ) +gint ComboBoxEntryToolItem::get_active_row_from_text(ComboBoxEntryToolItem *action, const gchar *target_text, + gboolean exclude, gboolean ignore_case) { - // Check if text in list - gint row = 0; - gboolean found = false; - GtkTreeIter iter; - gboolean valid = gtk_tree_model_get_iter_first( action->_model, &iter ); - while ( valid ) { - - // See if we should exclude a row - gboolean check = true; // If true, font-family is on system. - if( exclude && gtk_tree_model_get_n_columns( action->_model ) > 2 ) { - gtk_tree_model_get( action->_model, &iter, 2, &check, -1 ); - } + // Check if text in list + gint row = 0; + gboolean found = false; + GtkTreeIter iter; + gboolean valid = gtk_tree_model_get_iter_first(action->_model, &iter); + while (valid) { + // See if we should exclude a row + gboolean check = true; // If true, font-family is on system. + if (exclude && gtk_tree_model_get_n_columns(action->_model) > 2) { + gtk_tree_model_get(action->_model, &iter, 2, &check, -1); + } - if( check ) { - // Get text from list entry - gchar* text = nullptr; - gtk_tree_model_get( action->_model, &iter, 0, &text, -1 ); // Column 0 - - if( !ignore_case ) { - // Case sensitive compare - if( strcmp( target_text, text ) == 0 ){ - found = true; - g_free(text); - break; - } - } else { - // Case insensitive compare - gchar* target_text_casefolded = g_utf8_casefold( target_text, -1 ); - gchar* text_casefolded = g_utf8_casefold( text, -1 ); - gboolean equal = (strcmp( target_text_casefolded, text_casefolded ) == 0 ); - g_free( text_casefolded ); - g_free( target_text_casefolded ); - if( equal ) { - found = true; - g_free(text); - break; - } - } - g_free(text); - } + if (check) { + // Get text from list entry + gchar *text = nullptr; + gtk_tree_model_get(action->_model, &iter, 0, &text, -1); // Column 0 + + if (!ignore_case) { + // Case sensitive compare + if (strcmp(target_text, text) == 0) { + found = true; + g_free(text); + break; + } + } else { + // Case insensitive compare + gchar *target_text_casefolded = g_utf8_casefold(target_text, -1); + gchar *text_casefolded = g_utf8_casefold(text, -1); + gboolean equal = (strcmp(target_text_casefolded, text_casefolded) == 0); + g_free(text_casefolded); + g_free(target_text_casefolded); + if (equal) { + found = true; + g_free(text); + break; + } + } + g_free(text); + } - ++row; - valid = gtk_tree_model_iter_next( action->_model, &iter ); - } + ++row; + valid = gtk_tree_model_iter_next(action->_model, &iter); + } - if( !found ) row = -1; + if (!found) + row = -1; - return row; + return row; } // Checks if all comma separated text fragments are in the list and @@ -493,182 +442,161 @@ ComboBoxEntryToolItem::get_active_row_from_text(ComboBoxEntryToolItem *action, // for a GtkEntry box, it is only a copy and changing it has no effect. // PangoLayout * pl = gtk_entry_get_layout( entry ); // pango_layout_set_markup( pl, "NEW STRING", -1 ); // DOESN'T WORK -Glib::ustring -ComboBoxEntryToolItem::check_comma_separated_text() +Glib::ustring ComboBoxEntryToolItem::check_comma_separated_text() { - Glib::ustring missing; + Glib::ustring missing; - // Parse fallback_list using a comma as deliminator - gchar** tokens = g_strsplit( _text, ",", 0 ); + // Parse fallback_list using a comma as deliminator + gchar **tokens = g_strsplit(_text, ",", 0); - gint i = 0; - while( tokens[i] != nullptr ) { + gint i = 0; + while (tokens[i] != nullptr) { + // Remove any surrounding white space. + g_strstrip(tokens[i]); - // Remove any surrounding white space. - g_strstrip( tokens[i] ); + if (get_active_row_from_text(this, tokens[i], true, true) == -1) { + missing += tokens[i]; + missing += ", "; + } + ++i; + } + g_strfreev(tokens); - if( get_active_row_from_text( this, tokens[i], true, true ) == -1 ) { - missing += tokens[i]; - missing += ", "; + // Remove extra comma and space from end. + if (missing.size() >= 2) { + missing.resize(missing.size() - 2); } - ++i; - } - g_strfreev( tokens ); - - // Remove extra comma and space from end. - if( missing.size() >= 2 ) { - missing.resize( missing.size()-2 ); - } - return missing; + return missing; } // Callbacks --------------------------------------------------- -void -ComboBoxEntryToolItem::combo_box_changed_cb( GtkComboBox* widget, gpointer data ) +void ComboBoxEntryToolItem::combo_box_changed_cb(GtkComboBox *widget, gpointer data) { - // Two things can happen to get here: - // An item is selected in the drop-down menu. - // Text is typed. - // We only react here if an item is selected. - - // Get action - auto action = reinterpret_cast<ComboBoxEntryToolItem *>( data ); - - // Check if item selected: - gint newActive = gtk_combo_box_get_active(widget); - if( newActive >= 0 && newActive != action->_active ) { - - action->_active = newActive; - - GtkTreeIter iter; - if( gtk_combo_box_get_active_iter( GTK_COMBO_BOX( action->_combobox ), &iter ) ) { - - gchar* text = nullptr; - gtk_tree_model_get( action->_model, &iter, 0, &text, -1 ); - gtk_entry_set_text( action->_entry, text ); + // Two things can happen to get here: + // An item is selected in the drop-down menu. + // Text is typed. + // We only react here if an item is selected. + + // Get action + auto action = reinterpret_cast<ComboBoxEntryToolItem *>(data); + + // Check if item selected: + gint newActive = gtk_combo_box_get_active(widget); + if (newActive >= 0 && newActive != action->_active) { + action->_active = newActive; + + GtkTreeIter iter; + if (gtk_combo_box_get_active_iter(GTK_COMBO_BOX(action->_combobox), &iter)) { + gchar *text = nullptr; + gtk_tree_model_get(action->_model, &iter, 0, &text, -1); + gtk_entry_set_text(action->_entry, text); + + g_free(action->_text); + action->_text = text; + } - g_free( action->_text ); - action->_text = text; + // Now let the world know + action->_signal_changed.emit(); } - - // Now let the world know - action->_signal_changed.emit(); - } } -void -ComboBoxEntryToolItem::entry_activate_cb( GtkEntry *widget, - gpointer data ) +void ComboBoxEntryToolItem::entry_activate_cb(GtkEntry *widget, gpointer data) { - // Get text from entry box.. check if it matches a menu entry. + // Get text from entry box.. check if it matches a menu entry. - // Get action - auto action = reinterpret_cast<ComboBoxEntryToolItem*>( data ); + // Get action + auto action = reinterpret_cast<ComboBoxEntryToolItem *>(data); - // Get text - g_free( action->_text ); - action->_text = g_strdup( gtk_entry_get_text( widget ) ); + // Get text + g_free(action->_text); + action->_text = g_strdup(gtk_entry_get_text(widget)); - // Get row - action->_active = - get_active_row_from_text( action, action->_text ); + // Get row + action->_active = get_active_row_from_text(action, action->_text); - // Set active row - gtk_combo_box_set_active( GTK_COMBO_BOX( action->_combobox), action->_active ); + // Set active row + gtk_combo_box_set_active(GTK_COMBO_BOX(action->_combobox), action->_active); - // Now let the world know - action->_signal_changed.emit(); + // Now let the world know + action->_signal_changed.emit(); } -gboolean -ComboBoxEntryToolItem::match_selected_cb( GtkEntryCompletion* /*widget*/, GtkTreeModel* model, GtkTreeIter* iter, gpointer data ) +gboolean ComboBoxEntryToolItem::match_selected_cb(GtkEntryCompletion * /*widget*/, GtkTreeModel *model, + GtkTreeIter *iter, gpointer data) { - // Get action - auto action = reinterpret_cast<ComboBoxEntryToolItem*>(data); - GtkEntry *entry = action->_entry; + // Get action + auto action = reinterpret_cast<ComboBoxEntryToolItem *>(data); + GtkEntry *entry = action->_entry; - if( entry) { - gchar *family = nullptr; - gtk_tree_model_get(model, iter, 0, &family, -1); + if (entry) { + gchar *family = nullptr; + gtk_tree_model_get(model, iter, 0, &family, -1); - // Set text in GtkEntry - gtk_entry_set_text (GTK_ENTRY (entry), family ); + // Set text in GtkEntry + gtk_entry_set_text(GTK_ENTRY(entry), family); - // Set text in ToolItem - g_free( action->_text ); - action->_text = family; + // Set text in ToolItem + g_free(action->_text); + action->_text = family; - // Get row - action->_active = - get_active_row_from_text( action, action->_text ); + // Get row + action->_active = get_active_row_from_text(action, action->_text); - // Set active row - gtk_combo_box_set_active( GTK_COMBO_BOX( action->_combobox), action->_active ); + // Set active row + gtk_combo_box_set_active(GTK_COMBO_BOX(action->_combobox), action->_active); - // Now let the world know - action->_signal_changed.emit(); + // Now let the world know + action->_signal_changed.emit(); - return true; - } - return false; + return true; + } + return false; } -void -ComboBoxEntryToolItem::defocus() +void ComboBoxEntryToolItem::defocus() { - if ( _focusWidget ) { - gtk_widget_grab_focus( _focusWidget ); + if (_focusWidget) { + gtk_widget_grab_focus(_focusWidget); } } -gboolean -ComboBoxEntryToolItem::keypress_cb( GtkWidget *entry, GdkEventKey *event, gpointer data ) +gboolean ComboBoxEntryToolItem::keypress_cb(GtkWidget *entry, GdkEventKey *event, gpointer data) { gboolean wasConsumed = FALSE; /* default to report event not consumed */ guint key = 0; - auto action = reinterpret_cast<ComboBoxEntryToolItem*>(data); - gdk_keymap_translate_keyboard_state( Gdk::Display::get_default()->get_keymap(), - event->hardware_keycode, (GdkModifierType)event->state, - 0, &key, nullptr, nullptr, nullptr ); + auto action = reinterpret_cast<ComboBoxEntryToolItem *>(data); + gdk_keymap_translate_keyboard_state(Gdk::Display::get_default()->get_keymap(), event->hardware_keycode, + (GdkModifierType)event->state, 0, &key, nullptr, nullptr, nullptr); - switch ( key ) { - - case GDK_KEY_Escape: - { - //gtk_spin_button_set_value( GTK_SPIN_BUTTON(widget), action->private_data->lastVal ); + switch (key) { + case GDK_KEY_Escape: { + // gtk_spin_button_set_value( GTK_SPIN_BUTTON(widget), action->private_data->lastVal ); action->defocus(); wasConsumed = TRUE; - } - break; + } break; - case GDK_KEY_Tab: - { + case GDK_KEY_Tab: { // Fire activation similar to how Return does, but also return focus to text object // itself - entry_activate_cb( GTK_ENTRY (entry), data ); + entry_activate_cb(GTK_ENTRY(entry), data); action->defocus(); wasConsumed = TRUE; - } - break; + } break; case GDK_KEY_Return: - case GDK_KEY_KP_Enter: - { + case GDK_KEY_KP_Enter: { action->defocus(); - //wasConsumed = TRUE; - } - break; - - + // wasConsumed = TRUE; + } break; } return wasConsumed; } -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/widget/combo-box-entry-tool-item.h b/src/ui/widget/combo-box-entry-tool-item.h index 94b653d0bada1533af201031cb837c1f01b49676..433f03823ab4b1619f9553683b54d5c2f967e24c 100644 --- a/src/ui/widget/combo-box-entry-tool-item.h +++ b/src/ui/widget/combo-box-entry-tool-item.h @@ -30,116 +30,105 @@ namespace Widget { /** * Creates a Gtk::ToolItem subclass that wraps a Gtk::ComboBox object. */ -class ComboBoxEntryToolItem : public Gtk::ToolItem { +class ComboBoxEntryToolItem : public Gtk::ToolItem +{ private: - Glib::ustring _tooltip; - Glib::ustring _label; - GtkTreeModel *_model; ///< Tree Model - GtkComboBox *_combobox; - GtkEntry *_entry; - gint _entry_width;// Width of GtkEntry in characters. - gint _extra_width;// Extra Width of GtkComboBox.. to widen drop-down list in list mode. - gpointer _cell_data_func; // drop-down menu format - gpointer _separator_func; - gboolean _popup; // Do we pop-up an entry-completion dialog? + Glib::ustring _tooltip; + Glib::ustring _label; + GtkTreeModel *_model; ///< Tree Model + GtkComboBox *_combobox; + GtkEntry *_entry; + gint _entry_width; // Width of GtkEntry in characters. + gint _extra_width; // Extra Width of GtkComboBox.. to widen drop-down list in list mode. + gpointer _cell_data_func; // drop-down menu format + gpointer _separator_func; + gboolean _popup; // Do we pop-up an entry-completion dialog? GtkEntryCompletion *_entry_completion; - GtkWidget *_focusWidget; ///< The widget to return focus to - - GtkWidget *_indicator; - gint _active; // Index of active menu item (-1 if not in list). - gchar *_text; // Text of active menu item or entry box. - gchar *_info; // Text for tooltip info about entry. - gpointer _info_cb; // Callback for clicking info icon. - gint _info_cb_id; - gboolean _info_cb_blocked; - gchar *_warning; // Text for tooltip warning that entry isn't in list. - gpointer _warning_cb; // Callback for clicking warning icon. - gint _warning_cb_id; - gboolean _warning_cb_blocked; + GtkWidget *_focusWidget; ///< The widget to return focus to + + GtkWidget *_indicator; + gint _active; // Index of active menu item (-1 if not in list). + gchar *_text; // Text of active menu item or entry box. + gchar *_info; // Text for tooltip info about entry. + gpointer _info_cb; // Callback for clicking info icon. + gint _info_cb_id; + gboolean _info_cb_blocked; + gchar *_warning; // Text for tooltip warning that entry isn't in list. + gpointer _warning_cb; // Callback for clicking warning icon. + gint _warning_cb_id; + gboolean _warning_cb_blocked; // Signals sigc::signal<void> _signal_changed; - void (*changed) (ComboBoxEntryToolItem* action); - void (*activated) (ComboBoxEntryToolItem* action); + void (*changed)(ComboBoxEntryToolItem *action); + void (*activated)(ComboBoxEntryToolItem *action); - static gint get_active_row_from_text(ComboBoxEntryToolItem *action, - const gchar *target_text, - gboolean exclude = false, - gboolean ignore_case = false); + static gint get_active_row_from_text(ComboBoxEntryToolItem *action, const gchar *target_text, + gboolean exclude = false, gboolean ignore_case = false); void defocus(); - static void combo_box_changed_cb( GtkComboBox* widget, gpointer data ); - static void entry_activate_cb( GtkEntry *widget, - gpointer data ); - static gboolean match_selected_cb( GtkEntryCompletion *widget, - GtkTreeModel *model, - GtkTreeIter *iter, - gpointer data); - static gboolean keypress_cb( GtkWidget *widget, - GdkEventKey *event, - gpointer data ); + static void combo_box_changed_cb(GtkComboBox *widget, gpointer data); + static void entry_activate_cb(GtkEntry *widget, gpointer data); + static gboolean match_selected_cb(GtkEntryCompletion *widget, GtkTreeModel *model, GtkTreeIter *iter, + gpointer data); + static gboolean keypress_cb(GtkWidget *widget, GdkEventKey *event, gpointer data); Glib::ustring check_comma_separated_text(); - + public: - ComboBoxEntryToolItem(const Glib::ustring name, - const Glib::ustring label, - const Glib::ustring tooltip, - GtkTreeModel *model, - gint entry_width = -1, - gint extra_width = -1, - gpointer cell_data_func = nullptr, - gpointer separator_func = nullptr, - GtkWidget* focusWidget = nullptr); - - gchar* get_active_text(); - gboolean set_active_text(const gchar* text, int row=-1); - - void set_entry_width(gint entry_width); - void set_extra_width(gint extra_width); - - void popup_enable(); - void popup_disable(); - void focus_on_click( bool focus_on_click ); - - void set_info( const gchar* info ); - void set_info_cb( gpointer info_cb ); - void set_warning( const gchar* warning_cb ); - void set_warning_cb(gpointer warning ); - void set_tooltip( const gchar* tooltip ); + ComboBoxEntryToolItem(const Glib::ustring name, const Glib::ustring label, const Glib::ustring tooltip, + GtkTreeModel *model, gint entry_width = -1, gint extra_width = -1, + gpointer cell_data_func = nullptr, gpointer separator_func = nullptr, + GtkWidget *focusWidget = nullptr); + + gchar *get_active_text(); + gboolean set_active_text(const gchar *text, int row = -1); + + void set_entry_width(gint entry_width); + void set_extra_width(gint extra_width); + + void popup_enable(); + void popup_disable(); + void focus_on_click(bool focus_on_click); + + void set_info(const gchar *info); + void set_info_cb(gpointer info_cb); + void set_warning(const gchar *warning_cb); + void set_warning_cb(gpointer warning); + void set_tooltip(const gchar *tooltip); // Accessor methods - decltype(_model) get_model() const {return _model;} - decltype(_combobox) get_combobox() const {return _combobox;} - decltype(_entry) get_entry() const {return _entry;} - decltype(_entry_width) get_entry_width() const {return _entry_width;} - decltype(_extra_width) get_extra_width() const {return _extra_width;} - decltype(_cell_data_func) get_cell_data_func() const {return _cell_data_func;} - decltype(_separator_func) get_separator_func() const {return _separator_func;} - decltype(_popup) get_popup() const {return _popup;} - decltype(_focusWidget) get_focus_widget() const {return _focusWidget;} + decltype(_model) get_model() const { return _model; } + decltype(_combobox) get_combobox() const { return _combobox; } + decltype(_entry) get_entry() const { return _entry; } + decltype(_entry_width) get_entry_width() const { return _entry_width; } + decltype(_extra_width) get_extra_width() const { return _extra_width; } + decltype(_cell_data_func) get_cell_data_func() const { return _cell_data_func; } + decltype(_separator_func) get_separator_func() const { return _separator_func; } + decltype(_popup) get_popup() const { return _popup; } + decltype(_focusWidget) get_focus_widget() const { return _focusWidget; } - decltype(_active) get_active() const {return _active;} + decltype(_active) get_active() const { return _active; } - decltype(_signal_changed) signal_changed() {return _signal_changed;} + decltype(_signal_changed) signal_changed() { return _signal_changed; } // Mutator methods - void set_model (decltype(_model) model) {_model = model;} - void set_combobox (decltype(_combobox) combobox) {_combobox = combobox;} - void set_entry (decltype(_entry) entry) {_entry = entry;} - void set_cell_data_func(decltype(_cell_data_func) cell_data_func) {_cell_data_func = cell_data_func;} - void set_separator_func(decltype(_separator_func) separator_func) {_separator_func = separator_func;} - void set_popup (decltype(_popup) popup) {_popup = popup;} - void set_focus_widget (decltype(_focusWidget) focus_widget) {_focusWidget = focus_widget;} + void set_model(decltype(_model) model) { _model = model; } + void set_combobox(decltype(_combobox) combobox) { _combobox = combobox; } + void set_entry(decltype(_entry) entry) { _entry = entry; } + void set_cell_data_func(decltype(_cell_data_func) cell_data_func) { _cell_data_func = cell_data_func; } + void set_separator_func(decltype(_separator_func) separator_func) { _separator_func = separator_func; } + void set_popup(decltype(_popup) popup) { _popup = popup; } + void set_focus_widget(decltype(_focusWidget) focus_widget) { _focusWidget = focus_widget; } // This doesn't seem right... surely we should set the active row in the Combobox too? - void set_active (decltype(_active) active) {_active = active;} + void set_active(decltype(_active) active) { _active = active; } }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif /* SEEN_INK_COMBOBOXENTRY_ACTION */ /* diff --git a/src/ui/widget/combo-enums.h b/src/ui/widget/combo-enums.h index 4647a00c282de6e5d7a2caac36e47dccbd8c552c..c34d19c73ef42d323440a9e98dd64a804bcddafa 100644 --- a/src/ui/widget/combo-enums.h +++ b/src/ui/widget/combo-enums.h @@ -12,12 +12,13 @@ #ifndef INKSCAPE_UI_WIDGET_COMBO_ENUMS_H #define INKSCAPE_UI_WIDGET_COMBO_ENUMS_H -#include "ui/widget/labelled.h" +#include <glibmm/i18n.h> #include <gtkmm/combobox.h> #include <gtkmm/liststore.h> + #include "attr-widget.h" +#include "ui/widget/labelled.h" #include "util/enums.h" -#include <glibmm/i18n.h> namespace Inkscape { namespace UI { @@ -26,21 +27,27 @@ namespace Widget { /** * Simplified management of enumerations in the UI as combobox. */ -template<typename E> class ComboBoxEnum : public Gtk::ComboBox, public AttrWidget +template <typename E> +class ComboBoxEnum + : public Gtk::ComboBox + , public AttrWidget { private: - int on_sort_compare( const Gtk::TreeModel::iterator & a, const Gtk::TreeModel::iterator & b) + int on_sort_compare(const Gtk::TreeModel::iterator &a, const Gtk::TreeModel::iterator &b) { - Glib::ustring an=(*a)[_columns.label]; - Glib::ustring bn=(*b)[_columns.label]; + Glib::ustring an = (*a)[_columns.label]; + Glib::ustring bn = (*b)[_columns.label]; return an.compare(bn); } bool _sort; public: - ComboBoxEnum(E default_value, const Util::EnumDataConverter<E>& c, const SPAttr a = SPAttr::INVALID, bool sort = true) - : AttrWidget(a, (unsigned int)default_value), setProgrammatically(false), _converter(c) + ComboBoxEnum(E default_value, const Util::EnumDataConverter<E> &c, const SPAttr a = SPAttr::INVALID, + bool sort = true) + : AttrWidget(a, (unsigned int)default_value) + , setProgrammatically(false) + , _converter(c) { _sort = sort; @@ -53,11 +60,11 @@ public: pack_start(_columns.label); // Initialize list - for(int i = 0; i < static_cast<int>(_converter._length); ++i) { + for (int i = 0; i < static_cast<int>(_converter._length); ++i) { Gtk::TreeModel::Row row = *_model->append(); - const Util::EnumData<E>* data = &_converter.data(i); + const Util::EnumData<E> *data = &_converter.data(i); row[_columns.data] = data; - row[_columns.label] = _( _converter.get_label(data->id).c_str() ); + row[_columns.label] = _(_converter.get_label(data->id).c_str()); } set_active_by_id(default_value); @@ -68,8 +75,10 @@ public: } } - ComboBoxEnum(const Util::EnumDataConverter<E>& c, const SPAttr a = SPAttr::INVALID, bool sort = true) - : AttrWidget(a, (unsigned int) 0), setProgrammatically(false), _converter(c) + ComboBoxEnum(const Util::EnumDataConverter<E> &c, const SPAttr a = SPAttr::INVALID, bool sort = true) + : AttrWidget(a, (unsigned int)0) + , setProgrammatically(false) + , _converter(c) { _sort = sort; @@ -83,11 +92,11 @@ public: pack_start(_columns.label); // Initialize list - for(unsigned int i = 0; i < _converter._length; ++i) { + for (unsigned int i = 0; i < _converter._length; ++i) { Gtk::TreeModel::Row row = *_model->append(); - const Util::EnumData<E>* data = &_converter.data(i); + const Util::EnumData<E> *data = &_converter.data(i); row[_columns.data] = data; - row[_columns.label] = _( _converter.get_label(data->id).c_str() ); + row[_columns.label] = _(_converter.get_label(data->id).c_str()); } set_active(0); @@ -98,57 +107,54 @@ public: } } - Glib::ustring get_as_attribute() const override - { - return get_active_data()->key; - } + Glib::ustring get_as_attribute() const override { return get_active_data()->key; } - void set_from_attribute(SPObject* o) override + void set_from_attribute(SPObject *o) override { setProgrammatically = true; - const gchar* val = attribute_value(o); - if(val) + const gchar *val = attribute_value(o); + if (val) set_active_by_id(_converter.get_id_from_key(val)); else set_active(get_default()->as_uint()); } - - const Util::EnumData<E>* get_active_data() const + + const Util::EnumData<E> *get_active_data() const { Gtk::TreeModel::iterator i = this->get_active(); - if(i) + if (i) return (*i)[_columns.data]; return nullptr; } - void add_row(const Glib::ustring& s) + void add_row(const Glib::ustring &s) { Gtk::TreeModel::Row row = *_model->append(); row[_columns.data] = 0; row[_columns.label] = s; } - void remove_row(E id) { + void remove_row(E id) + { Gtk::TreeModel::iterator i; - - for(i = _model->children().begin(); i != _model->children().end(); ++i) { - const Util::EnumData<E>* data = (*i)[_columns.data]; - if(data->id == id) + for (i = _model->children().begin(); i != _model->children().end(); ++i) { + const Util::EnumData<E> *data = (*i)[_columns.data]; + + if (data->id == id) break; } - if(i != _model->children().end()) + if (i != _model->children().end()) _model->erase(i); } - void set_active_by_id(E id) { + void set_active_by_id(E id) + { setProgrammatically = true; - for(Gtk::TreeModel::iterator i = _model->children().begin(); - i != _model->children().end(); ++i) - { - const Util::EnumData<E>* data = (*i)[_columns.data]; - if(data->id == id) { + for (Gtk::TreeModel::iterator i = _model->children().begin(); i != _model->children().end(); ++i) { + const Util::EnumData<E> *data = (*i)[_columns.data]; + if (data->id == id) { set_active(i); break; } @@ -157,9 +163,10 @@ public: bool on_scroll_event(GdkEventScroll *event) override { return false; } - void set_active_by_key(const Glib::ustring& key) { + void set_active_by_key(const Glib::ustring &key) + { setProgrammatically = true; - set_active_by_id( _converter.get_id_from_key(key) ); + set_active_by_id(_converter.get_id_from_key(key)); }; bool setProgrammatically; @@ -174,41 +181,34 @@ private: add(label); } - Gtk::TreeModelColumn<const Util::EnumData<E>*> data; + Gtk::TreeModelColumn<const Util::EnumData<E> *> data; Gtk::TreeModelColumn<Glib::ustring> label; }; Columns _columns; Glib::RefPtr<Gtk::ListStore> _model; - const Util::EnumDataConverter<E>& _converter; + const Util::EnumDataConverter<E> &_converter; }; - /** * Simplified management of enumerations in the UI as combobox. */ -template<typename E> class LabelledComboBoxEnum : public Labelled +template <typename E> +class LabelledComboBoxEnum : public Labelled { public: - LabelledComboBoxEnum( Glib::ustring const &label, - Glib::ustring const &tooltip, - const Util::EnumDataConverter<E>& c, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true, - bool sorted = true) + LabelledComboBoxEnum(Glib::ustring const &label, Glib::ustring const &tooltip, const Util::EnumDataConverter<E> &c, + Glib::ustring const &suffix = "", Glib::ustring const &icon = "", bool mnemonic = true, + bool sorted = true) : Labelled(label, tooltip, new ComboBoxEnum<E>(c, SPAttr::INVALID, sorted), suffix, icon, mnemonic) - { - } + {} - ComboBoxEnum<E>* getCombobox() { - return static_cast< ComboBoxEnum<E>* > (_widget); - } + ComboBoxEnum<E> *getCombobox() { return static_cast<ComboBoxEnum<E> *>(_widget); } }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/widget/combo-tool-item.cpp b/src/ui/widget/combo-tool-item.cpp index ffc7e75875aba761089d3e2922e2e446ced67d86..87c4f28915d54c33f7f6bf2fdbce0a86f5b74eac 100644 --- a/src/ui/widget/combo-tool-item.cpp +++ b/src/ui/widget/combo-tool-item.cpp @@ -8,56 +8,50 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - /** \file A combobox that can be displayed in a toolbar. */ #include "combo-tool-item.h" -#include "preferences.h" -#include <iostream> -#include <utility> -#include <gtkmm/toolitem.h> -#include <gtkmm/menuitem.h> -#include <gtkmm/radiomenuitem.h> -#include <gtkmm/combobox.h> -#include <gtkmm/menu.h> + #include <gtkmm/box.h> -#include <gtkmm/label.h> +#include <gtkmm/combobox.h> #include <gtkmm/image.h> +#include <gtkmm/label.h> +#include <gtkmm/menu.h> +#include <gtkmm/menuitem.h> +#include <gtkmm/radiomenuitem.h> +#include <gtkmm/toolitem.h> +#include <iostream> +#include <utility> + +#include "preferences.h" namespace Inkscape { namespace UI { namespace Widget { -ComboToolItem* -ComboToolItem::create(const Glib::ustring &group_label, - const Glib::ustring &tooltip, - const Glib::ustring &stock_id, - Glib::RefPtr<Gtk::ListStore> store, - bool has_entry) +ComboToolItem *ComboToolItem::create(const Glib::ustring &group_label, const Glib::ustring &tooltip, + const Glib::ustring &stock_id, Glib::RefPtr<Gtk::ListStore> store, bool has_entry) { return new ComboToolItem(group_label, tooltip, stock_id, store, has_entry); } -ComboToolItem::ComboToolItem(Glib::ustring group_label, - Glib::ustring tooltip, - Glib::ustring stock_id, - Glib::RefPtr<Gtk::ListStore> store, - bool has_entry) : - _active(-1), - _group_label(std::move( group_label )), - _tooltip(std::move( tooltip )), - _stock_id(std::move( stock_id )), - _store (std::move(store)), - _use_label (true), - _use_icon (false), - _use_pixbuf (true), - _icon_size ( Gtk::ICON_SIZE_LARGE_TOOLBAR ), - _combobox (nullptr), - _group_label_widget(nullptr), - _container(Gtk::manage(new Gtk::Box())), - _menuitem (nullptr) +ComboToolItem::ComboToolItem(Glib::ustring group_label, Glib::ustring tooltip, Glib::ustring stock_id, + Glib::RefPtr<Gtk::ListStore> store, bool has_entry) + : _active(-1) + , _group_label(std::move(group_label)) + , _tooltip(std::move(tooltip)) + , _stock_id(std::move(stock_id)) + , _store(std::move(store)) + , _use_label(true) + , _use_icon(false) + , _use_pixbuf(true) + , _icon_size(Gtk::ICON_SIZE_LARGE_TOOLBAR) + , _combobox(nullptr) + , _group_label_widget(nullptr) + , _container(Gtk::manage(new Gtk::Box())) + , _menuitem(nullptr) { add(*_container); _container->set_spacing(3); @@ -82,50 +76,42 @@ ComboToolItem::ComboToolItem(Glib::ustring group_label, } } - // Create combobox - _combobox = Gtk::manage (new Gtk::ComboBox(has_entry)); + _combobox = Gtk::manage(new Gtk::ComboBox(has_entry)); _combobox->set_model(_store); populate_combobox(); - _combobox->signal_changed().connect( - sigc::mem_fun(*this, &ComboToolItem::on_changed_combobox)); + _combobox->signal_changed().connect(sigc::mem_fun(*this, &ComboToolItem::on_changed_combobox)); _container->pack_start(*_combobox); show_all(); } -void -ComboToolItem::focus_on_click( bool focus_on_click ) -{ - _combobox->set_focus_on_click(focus_on_click); +void ComboToolItem::focus_on_click(bool focus_on_click) +{ + _combobox->set_focus_on_click(focus_on_click); } - -void -ComboToolItem::use_label(bool use_label) +void ComboToolItem::use_label(bool use_label) { _use_label = use_label; populate_combobox(); } -void -ComboToolItem::use_icon(bool use_icon) +void ComboToolItem::use_icon(bool use_icon) { _use_icon = use_icon; populate_combobox(); } -void -ComboToolItem::use_pixbuf(bool use_pixbuf) +void ComboToolItem::use_pixbuf(bool use_pixbuf) { _use_pixbuf = use_pixbuf; populate_combobox(); } -void -ComboToolItem::use_group_label(bool use_group_label) +void ComboToolItem::use_group_label(bool use_group_label) { if (use_group_label == (_group_label_widget != nullptr)) { return; @@ -142,8 +128,7 @@ ComboToolItem::use_group_label(bool use_group_label) } } -void -ComboToolItem::populate_combobox() +void ComboToolItem::populate_combobox() { _combobox->clear(); @@ -162,91 +147,87 @@ ComboToolItem::populate_combobox() } } Gtk::CellRendererPixbuf *renderer = new Gtk::CellRendererPixbuf; - renderer->set_property ("stock_size", Gtk::ICON_SIZE_LARGE_TOOLBAR); - _combobox->pack_start (*Gtk::manage(renderer), false); - _combobox->add_attribute (*renderer, "icon_name", columns.col_icon ); + renderer->set_property("stock_size", Gtk::ICON_SIZE_LARGE_TOOLBAR); + _combobox->pack_start(*Gtk::manage(renderer), false); + _combobox->add_attribute(*renderer, "icon_name", columns.col_icon); } else if (_use_pixbuf) { Gtk::CellRendererPixbuf *renderer = new Gtk::CellRendererPixbuf; - //renderer->set_property ("stock_size", Gtk::ICON_SIZE_LARGE_TOOLBAR); - _combobox->pack_start (*Gtk::manage(renderer), false); - _combobox->add_attribute (*renderer, "pixbuf", columns.col_pixbuf ); + // renderer->set_property ("stock_size", Gtk::ICON_SIZE_LARGE_TOOLBAR); + _combobox->pack_start(*Gtk::manage(renderer), false); + _combobox->add_attribute(*renderer, "pixbuf", columns.col_pixbuf); } if (_use_label) { _combobox->pack_start(columns.col_label); } - std::vector<Gtk::CellRenderer*> cells = _combobox->get_cells(); - for (auto & cell : cells) { - _combobox->add_attribute (*cell, "sensitive", columns.col_sensitive); + std::vector<Gtk::CellRenderer *> cells = _combobox->get_cells(); + for (auto &cell : cells) { + _combobox->add_attribute(*cell, "sensitive", columns.col_sensitive); } set_tooltip_text(_tooltip); _combobox->set_tooltip_text(_tooltip); - _combobox->set_active (_active); + _combobox->set_active(_active); } -void -ComboToolItem::set_active (gint active) { +void ComboToolItem::set_active(gint active) +{ if (_active != active) { - _active = active; if (_combobox) { - _combobox->set_active (active); + _combobox->set_active(active); } if (active < _radiomenuitems.size()) { - _radiomenuitems[ active ]->set_active(); + _radiomenuitems[active]->set_active(); } } } -Glib::ustring -ComboToolItem::get_active_text () { +Glib::ustring ComboToolItem::get_active_text() +{ Gtk::TreeModel::Row row = _store->children()[_active]; ComboToolItemColumns columns; Glib::ustring label = row[columns.col_label]; return label; } -bool -ComboToolItem::on_create_menu_proxy() +bool ComboToolItem::on_create_menu_proxy() { if (_menuitem == nullptr) { - - _menuitem = Gtk::manage (new Gtk::MenuItem(_group_label)); - Gtk::Menu *menu = Gtk::manage (new Gtk::Menu); + _menuitem = Gtk::manage(new Gtk::MenuItem(_group_label)); + Gtk::Menu *menu = Gtk::manage(new Gtk::Menu); Gtk::RadioButton::Group group; int index = 0; auto children = _store->children(); for (auto row : children) { ComboToolItemColumns columns; - Glib::ustring label = row[columns.col_label ]; - Glib::ustring icon = row[columns.col_icon ]; - Glib::ustring tooltip = row[columns.col_tooltip ]; - bool sensitive = row[columns.col_sensitive ]; + Glib::ustring label = row[columns.col_label]; + Glib::ustring icon = row[columns.col_icon]; + Glib::ustring tooltip = row[columns.col_tooltip]; + bool sensitive = row[columns.col_sensitive]; - Gtk::RadioMenuItem* button = Gtk::manage(new Gtk::RadioMenuItem(group)); - button->set_label (label); - button->set_tooltip_text( tooltip ); - button->set_sensitive( sensitive ); + Gtk::RadioMenuItem *button = Gtk::manage(new Gtk::RadioMenuItem(group)); + button->set_label(label); + button->set_tooltip_text(tooltip); + button->set_sensitive(sensitive); - button->signal_toggled().connect( sigc::bind<0>( - sigc::mem_fun(*this, &ComboToolItem::on_toggled_radiomenu), index++) - ); + button->signal_toggled().connect( + sigc::bind<0>(sigc::mem_fun(*this, &ComboToolItem::on_toggled_radiomenu), index++)); - menu->add (*button); + menu->add(*button); - _radiomenuitems.push_back( button ); + _radiomenuitems.push_back(button); } - if ( _active < _radiomenuitems.size()) { - _radiomenuitems[ _active ]->set_active(); + if (_active < _radiomenuitems.size()) { + _radiomenuitems[_active]->set_active(); } - - _menuitem->set_submenu (*menu); + + _menuitem->set_submenu(*menu); _menuitem->show_all(); } @@ -254,30 +235,28 @@ ComboToolItem::on_create_menu_proxy() return true; } -void -ComboToolItem::on_changed_combobox() { - +void ComboToolItem::on_changed_combobox() +{ int row = _combobox->get_active_row_number(); - set_active( row ); - _changed.emit (_active); - _changed_after.emit (_active); + set_active(row); + _changed.emit(_active); + _changed_after.emit(_active); } -void -ComboToolItem::on_toggled_radiomenu(int n) { - +void ComboToolItem::on_toggled_radiomenu(int n) +{ // toggled emitted twice, first for button toggled off, second for button toggled on. // We want to react only to the button turned on. - if ( n < _radiomenuitems.size() &&_radiomenuitems[ n ]->get_active()) { - set_active ( n ); - _changed.emit (_active); - _changed_after.emit (_active); + if (n < _radiomenuitems.size() && _radiomenuitems[n]->get_active()) { + set_active(n); + _changed.emit(_active); + _changed_after.emit(_active); } } -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: mode:c++ diff --git a/src/ui/widget/combo-tool-item.h b/src/ui/widget/combo-tool-item.h index 1fc8b00a15e4e467d1fdbd7f620f76fe70736383..bfe0c28358263bed05c6f01a993946e7d2269775 100644 --- a/src/ui/widget/combo-tool-item.h +++ b/src/ui/widget/combo-tool-item.h @@ -15,8 +15,8 @@ A combobox that can be displayed in a toolbar */ -#include <gtkmm/toolitem.h> #include <gtkmm/liststore.h> +#include <gtkmm/toolitem.h> #include <sigc++/sigc++.h> #include <vector> @@ -26,52 +26,51 @@ class ComboBox; class Label; class MenuItem; class RadioMenuItem; -} +} // namespace Gtk namespace Inkscape { namespace UI { namespace Widget { -class ComboToolItemColumns : public Gtk::TreeModel::ColumnRecord { +class ComboToolItemColumns : public Gtk::TreeModel::ColumnRecord +{ public: - ComboToolItemColumns() { - add (col_label); - add (col_value); - add (col_icon); - add (col_pixbuf); - add (col_data); // Used to store a pointer - add (col_tooltip); - add (col_sensitive); + ComboToolItemColumns() + { + add(col_label); + add(col_value); + add(col_icon); + add(col_pixbuf); + add(col_data); // Used to store a pointer + add(col_tooltip); + add(col_sensitive); } Gtk::TreeModelColumn<Glib::ustring> col_label; Gtk::TreeModelColumn<Glib::ustring> col_value; Gtk::TreeModelColumn<Glib::ustring> col_icon; - Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf> > col_pixbuf; - Gtk::TreeModelColumn<void *> col_data; + Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf>> col_pixbuf; + Gtk::TreeModelColumn<void *> col_data; Gtk::TreeModelColumn<Glib::ustring> col_tooltip; - Gtk::TreeModelColumn<bool> col_sensitive; + Gtk::TreeModelColumn<bool> col_sensitive; }; - -class ComboToolItem : public Gtk::ToolItem { - +class ComboToolItem : public Gtk::ToolItem +{ public: - static ComboToolItem* create(const Glib::ustring &label, - const Glib::ustring &tooltip, - const Glib::ustring &stock_id, - Glib::RefPtr<Gtk::ListStore> store, - bool has_entry = false); + static ComboToolItem *create(const Glib::ustring &label, const Glib::ustring &tooltip, + const Glib::ustring &stock_id, Glib::RefPtr<Gtk::ListStore> store, + bool has_entry = false); /* Style of combobox */ - void use_label( bool use_label ); - void use_icon( bool use_icon ); - void focus_on_click( bool focus_on_click ); - void use_pixbuf( bool use_pixbuf ); - void use_group_label( bool use_group_label ); // Applies to tool item only - + void use_label(bool use_label); + void use_icon(bool use_icon); + void focus_on_click(bool focus_on_click); + void use_pixbuf(bool use_pixbuf); + void use_group_label(bool use_group_label); // Applies to tool item only + gint get_active() { return _active; } Glib::ustring get_active_text(); - void set_active( gint active ); - void set_icon_size( Gtk::BuiltinIconSize size ) { _icon_size = size; } + void set_active(gint active); + void set_icon_size(Gtk::BuiltinIconSize size) { _icon_size = size; } Glib::RefPtr<Gtk::ListStore> get_store() { return _store; } @@ -84,44 +83,40 @@ protected: /* Signals */ sigc::signal<void, int> _changed; - sigc::signal<void, int> _changed_after; // Needed for unit tracker which eats _changed. + sigc::signal<void, int> _changed_after; // Needed for unit tracker which eats _changed. private: - Glib::ustring _group_label; Glib::ustring _tooltip; Glib::ustring _stock_id; Glib::RefPtr<Gtk::ListStore> _store; - gint _active; /* Active menu item/button */ + gint _active; /* Active menu item/button */ /* Style */ bool _use_label; - bool _use_icon; // Applies to menu item only + bool _use_icon; // Applies to menu item only bool _use_pixbuf; Gtk::BuiltinIconSize _icon_size; /* Combobox in tool */ - Gtk::ComboBox* _combobox; - Gtk::Label* _group_label_widget; - Gtk::Box* _container; + Gtk::ComboBox *_combobox; + Gtk::Label *_group_label_widget; + Gtk::Box *_container; - Gtk::MenuItem* _menuitem; - std::vector<Gtk::RadioMenuItem*> _radiomenuitems; + Gtk::MenuItem *_menuitem; + std::vector<Gtk::RadioMenuItem *> _radiomenuitems; /* Internal Callbacks */ void on_changed_combobox(); void on_toggled_radiomenu(int n); - ComboToolItem(Glib::ustring group_label, - Glib::ustring tooltip, - Glib::ustring stock_id, - Glib::RefPtr<Gtk::ListStore> store, - bool has_entry = false); + ComboToolItem(Glib::ustring group_label, Glib::ustring tooltip, Glib::ustring stock_id, + Glib::RefPtr<Gtk::ListStore> store, bool has_entry = false); }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif /* SEEN_COMBO_TOOL_ITEM */ /* diff --git a/src/ui/widget/dash-selector.cpp b/src/ui/widget/dash-selector.cpp index c2d0d32b4383b9d3314f3c9c2a96de2082868fa2..e9fc3d9774b1a36f72ac8c57a0924f81097e8133 100644 --- a/src/ui/widget/dash-selector.cpp +++ b/src/ui/widget/dash-selector.cpp @@ -15,18 +15,13 @@ #include "dash-selector.h" +#include <2geom/coord.h> #include <cstring> - #include <glibmm/i18n.h> -#include <2geom/coord.h> - -#include "preferences.h" - #include "display/cairo-utils.h" - +#include "preferences.h" #include "style.h" - #include "ui/dialog-events.h" #include "ui/widget/spinbutton.h" @@ -43,15 +38,15 @@ static double dash_4_1[] = {4.0, 1.0, -1.0}; static double dash_1_2[] = {1.0, 2.0, -1.0}; static double dash_1_4[] = {1.0, 4.0, -1.0}; -static size_t BD_LEN = 7; // must correspond to the number of entries in the next line +static size_t BD_LEN = 7; // must correspond to the number of entries in the next line static double *builtin_dashes[] = {dash_0, dash_1_1, dash_2_1, dash_4_1, dash_1_2, dash_1_4, nullptr}; static double **dashes = nullptr; DashSelector::DashSelector() - : preview_width(80), - preview_height(16), - preview_lineheight(2) + : preview_width(80) + , preview_height(16) + , preview_lineheight(2) { set_spacing(4); @@ -65,7 +60,7 @@ DashSelector::DashSelector() dash_combo.set_tooltip_text(_("Dash pattern")); dash_combo.get_style_context()->add_class("combobright"); dash_combo.show(); - dash_combo.signal_changed().connect( sigc::mem_fun(*this, &DashSelector::on_selection) ); + dash_combo.signal_changed().connect(sigc::mem_fun(*this, &DashSelector::on_selection)); this->pack_start(dash_combo, true, true, 0); @@ -78,9 +73,11 @@ DashSelector::DashSelector() this->pack_start(*sb, false, false, 0); - int np=0; - while (dashes[np]){ np++;} - for (int i = 0; i<np-1; i++) { // all but the custom one go this way + int np = 0; + while (dashes[np]) { + np++; + } + for (int i = 0; i < np - 1; i++) { // all but the custom one go this way // Add the dashes to the combobox Gtk::TreeModel::Row row = *(dash_store->append()); row[dash_columns.dash] = dashes[i]; @@ -88,39 +85,40 @@ DashSelector::DashSelector() } // add the custom one Gtk::TreeModel::Row row = *(dash_store->append()); - row[dash_columns.dash] = dashes[np-1]; + row[dash_columns.dash] = dashes[np - 1]; row[dash_columns.pixbuf] = Glib::wrap(sp_text_to_pixbuf((char *)"Custom")); _pattern = dashes[0]; } -DashSelector::~DashSelector() { +DashSelector::~DashSelector() +{ // FIXME: for some reason this doesn't get called; does the call to manage() in // sp_stroke_style_line_widget_new() not processed correctly? } -void DashSelector::prepareImageRenderer( Gtk::TreeModel::const_iterator const &row ) { - +void DashSelector::prepareImageRenderer(Gtk::TreeModel::const_iterator const &row) +{ Glib::RefPtr<Gdk::Pixbuf> pixbuf = (*row)[dash_columns.pixbuf]; image_renderer.property_pixbuf() = pixbuf; } -void DashSelector::init_dashes() { - +void DashSelector::init_dashes() +{ if (!dashes) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); std::vector<Glib::ustring> dash_prefs = prefs->getAllDirs(_prefs_path); - + int pos = 0; if (!dash_prefs.empty()) { SPStyle style; - dashes = g_new (double *, dash_prefs.size() + 2); // +1 for custom slot, +1 for terminator slot - - for (auto & dash_pref : dash_prefs) { - style.readFromPrefs( dash_pref ); - + dashes = g_new(double *, dash_prefs.size() + 2); // +1 for custom slot, +1 for terminator slot + + for (auto &dash_pref : dash_prefs) { + style.readFromPrefs(dash_pref); + if (!style.stroke_dasharray.values.empty()) { - dashes[pos] = g_new (double, style.stroke_dasharray.values.size() + 1); + dashes[pos] = g_new(double, style.stroke_dasharray.values.size() + 1); double *d = dashes[pos]; unsigned i = 0; for (; i < style.stroke_dasharray.values.size(); i++) { @@ -132,36 +130,39 @@ void DashSelector::init_dashes() { } pos += 1; } - } else { // This code may never execute - a new preferences.xml is created for a new user. Maybe if the user deletes dashes from preferences.xml? - dashes = g_new (double *, BD_LEN + 2); // +1 for custom slot, +1 for terminator slot + } else { // This code may never execute - a new preferences.xml is created for a new user. Maybe if the user + // deletes dashes from preferences.xml? + dashes = g_new(double *, BD_LEN + 2); // +1 for custom slot, +1 for terminator slot unsigned i; - for(i=0;i<BD_LEN;i++) { - dashes[i] = builtin_dashes[i]; + for (i = 0; i < BD_LEN; i++) { + dashes[i] = builtin_dashes[i]; } pos = BD_LEN; } // make a place to hold the custom dashes, up to 15 positions long (+ terminator) - dashes[pos] = g_new (double, 16); + dashes[pos] = g_new(double, 16); double *d = dashes[pos]; - int i=0; - for(i=0;i<15;i++){ d[i]=i; } // have to put something in there, this is a pattern hopefully nobody would choose - d[15]=-1.0; + int i = 0; + for (i = 0; i < 15; i++) { + d[i] = i; + } // have to put something in there, this is a pattern hopefully nobody would choose + d[15] = -1.0; // final terminator - dashes[++pos] = nullptr; + dashes[++pos] = nullptr; } } -void DashSelector::set_dash (int ndash, double *dash, double o) +void DashSelector::set_dash(int ndash, double *dash, double o) { - int pos = -1; // Allows custom patterns to remain unscathed by this. - int count = 0; // will hold the NULL terminator at the end of the dashes list + int pos = -1; // Allows custom patterns to remain unscathed by this. + int count = 0; // will hold the NULL terminator at the end of the dashes list if (ndash > 0) { double delta = 0.0; for (int i = 0; i < ndash; i++) delta += dash[i]; delta /= 1000.0; - for (int i = 0; dashes[i]; i++,count++) { + for (int i = 0; dashes[i]; i++, count++) { double *pattern = dashes[i]; int np = 0; while (pattern[np] >= 0.0) @@ -179,29 +180,27 @@ void DashSelector::set_dash (int ndash, double *dash, double o) } } } + } else if (ndash == 0) { + pos = 0; } - else if(ndash==0) { - pos = 0; - } - if(pos>=0){ - _pattern = dashes[pos]; - this->dash_combo.set_active(pos); - this->offset->set_value(o); - if(pos == 10) { - this->offset->set_value(10.0); - } - } - else { // Hit a custom pattern in the SVG, write it into the combobox. - count--; // the one slot for custom patterns - double *d = dashes[count]; - int i=0; - for(i=0;i< (ndash > 15 ? 15 : ndash) ;i++) { - d[i]=dash[i]; - } // store the custom pattern - d[ndash]=-1.0; //terminate it - _pattern = dashes[count]; - this->dash_combo.set_active(count); - this->offset->set_value(o); // what does this do???? + if (pos >= 0) { + _pattern = dashes[pos]; + this->dash_combo.set_active(pos); + this->offset->set_value(o); + if (pos == 10) { + this->offset->set_value(10.0); + } + } else { // Hit a custom pattern in the SVG, write it into the combobox. + count--; // the one slot for custom patterns + double *d = dashes[count]; + int i = 0; + for (i = 0; i < (ndash > 15 ? 15 : ndash); i++) { + d[i] = dash[i]; + } // store the custom pattern + d[ndash] = -1.0; // terminate it + _pattern = dashes[count]; + this->dash_combo.set_active(count); + this->offset->set_value(o); // what does this do???? } } @@ -215,8 +214,8 @@ void DashSelector::get_dash(int *ndash, double **dash, double *off) if (ndash) *ndash = nd; if (dash) { - *dash = g_new (double, nd); - memcpy (*dash, _pattern, nd * sizeof (double)); + *dash = g_new(double, nd); + memcpy(*dash, _pattern, nd * sizeof(double)); } if (off) *off = offset->get_value(); @@ -233,53 +232,54 @@ void DashSelector::get_dash(int *ndash, double **dash, double *off) /** * Fill a pixbuf with the dash pattern using standard cairo drawing */ -GdkPixbuf* DashSelector::sp_dash_to_pixbuf(double *pattern) +GdkPixbuf *DashSelector::sp_dash_to_pixbuf(double *pattern) { int n_dashes; - for (n_dashes = 0; pattern[n_dashes] >= 0.0; n_dashes ++) ; + for (n_dashes = 0; pattern[n_dashes] >= 0.0; n_dashes++) + ; cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, preview_width, preview_height); cairo_t *ct = cairo_create(s); - cairo_set_line_width (ct, preview_lineheight); - cairo_scale (ct, preview_lineheight, 1); - //cairo_set_source_rgb (ct, 0, 0, 0); - cairo_move_to (ct, 0, preview_height/2); - cairo_line_to (ct, preview_width, preview_height/2); + cairo_set_line_width(ct, preview_lineheight); + cairo_scale(ct, preview_lineheight, 1); + // cairo_set_source_rgb (ct, 0, 0, 0); + cairo_move_to(ct, 0, preview_height / 2); + cairo_line_to(ct, preview_width, preview_height / 2); cairo_set_dash(ct, pattern, n_dashes, 0); - cairo_stroke (ct); + cairo_stroke(ct); cairo_destroy(ct); cairo_surface_flush(s); - GdkPixbuf* pixbuf = ink_pixbuf_create_from_cairo_surface(s); + GdkPixbuf *pixbuf = ink_pixbuf_create_from_cairo_surface(s); return pixbuf; } /** * Fill a pixbuf with a text label using standard cairo drawing */ -GdkPixbuf* DashSelector::sp_text_to_pixbuf(char *text) +GdkPixbuf *DashSelector::sp_text_to_pixbuf(char *text) { cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, preview_width, preview_height); cairo_t *ct = cairo_create(s); - cairo_select_font_face (ct, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); - cairo_set_font_size (ct, 12.0); - cairo_set_source_rgb (ct, 0.0, 0.0, 0.0); - cairo_move_to (ct, 16.0, 13.0); - cairo_show_text (ct, text); + cairo_select_font_face(ct, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); + cairo_set_font_size(ct, 12.0); + cairo_set_source_rgb(ct, 0.0, 0.0, 0.0); + cairo_move_to(ct, 16.0, 13.0); + cairo_show_text(ct, text); - cairo_stroke (ct); + cairo_stroke(ct); cairo_destroy(ct); cairo_surface_flush(s); - GdkPixbuf* pixbuf = ink_pixbuf_create_from_cairo_surface(s); + GdkPixbuf *pixbuf = ink_pixbuf_create_from_cairo_surface(s); return pixbuf; } -void DashSelector::on_selection () +void DashSelector::on_selection() { double *pattern = dash_combo.get_active()->get_value(dash_columns.dash); _pattern = pattern; diff --git a/src/ui/widget/dash-selector.h b/src/ui/widget/dash-selector.h index ce59d9946a1a671387827519d152a82570b921c9..ce9d17e7fe969dcafba94994e2881f2a4b5dbda5 100644 --- a/src/ui/widget/dash-selector.h +++ b/src/ui/widget/dash-selector.h @@ -14,7 +14,6 @@ #include <gtkmm/box.h> #include <gtkmm/combobox.h> #include <gtkmm/liststore.h> - #include <sigc++/signal.h> namespace Inkscape { @@ -24,7 +23,8 @@ namespace Widget { /** * Class that wraps a combobox and spinbutton for selecting dash patterns. */ -class DashSelector : public Gtk::HBox { +class DashSelector : public Gtk::HBox +{ public: DashSelector(); ~DashSelector() override; @@ -38,7 +38,6 @@ public: sigc::signal<void> changed_signal; private: - /** * Initialize dashes list from preferences */ @@ -47,17 +46,17 @@ private: /** * Fill a pixbuf with the dash pattern using standard cairo drawing */ - GdkPixbuf* sp_dash_to_pixbuf(double *pattern); + GdkPixbuf *sp_dash_to_pixbuf(double *pattern); /** * Fill a pixbuf with text standard cairo drawing */ - GdkPixbuf* sp_text_to_pixbuf(char *text); + GdkPixbuf *sp_text_to_pixbuf(char *text); /** * Callback for combobox image renderer */ - void prepareImageRenderer( Gtk::TreeModel::const_iterator const &row ); + void prepareImageRenderer(Gtk::TreeModel::const_iterator const &row); /** * Callback for offset adjustment changing @@ -72,13 +71,16 @@ private: /** * Combobox columns */ - class DashColumns : public Gtk::TreeModel::ColumnRecord { + class DashColumns : public Gtk::TreeModel::ColumnRecord + { public: Gtk::TreeModelColumn<double *> dash; - Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf> > pixbuf; + Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf>> pixbuf; - DashColumns() { - add(dash); add(pixbuf); + DashColumns() + { + add(dash); + add(pixbuf); } }; DashColumns dash_columns; diff --git a/src/ui/widget/dock-item.cpp b/src/ui/widget/dock-item.cpp index db803d80e13c1b2462da8b32766e3266969e0c04..494c0c5ea8d642b050234b519f2d1b2a4d4b2620 100644 --- a/src/ui/widget/dock-item.cpp +++ b/src/ui/widget/dock-item.cpp @@ -8,43 +8,40 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/dock.h" +#include <glibmm/exceptionhandler.h> +#include <gtkmm/icontheme.h> #include "preferences.h" #include "ui/icon-loader.h" #include "ui/icon-names.h" -#include <glibmm/exceptionhandler.h> -#include <gtkmm/icontheme.h> +#include "ui/widget/dock.h" namespace Inkscape { namespace UI { namespace Widget { -DockItem::DockItem(Dock& dock, const Glib::ustring& name, const Glib::ustring& long_name, - const Glib::ustring& icon_name, State state, GdlDockPlacement placement) : - _dock(dock), - _prev_state(state), - _window(nullptr), - _x(0), - _y(0), - _grab_focus_on_realize(false), - _gdl_dock_item(nullptr) +DockItem::DockItem(Dock &dock, const Glib::ustring &name, const Glib::ustring &long_name, + const Glib::ustring &icon_name, State state, GdlDockPlacement placement) + : _dock(dock) + , _prev_state(state) + , _window(nullptr) + , _x(0) + , _y(0) + , _grab_focus_on_realize(false) + , _gdl_dock_item(nullptr) { - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); GdlDockItemBehavior gdl_dock_behavior = - (prefs->getBool("/options/dock/cancenterdock", true) ? - GDL_DOCK_ITEM_BEH_NORMAL : - GDL_DOCK_ITEM_BEH_CANT_DOCK_CENTER); - + (prefs->getBool("/options/dock/cancenterdock", true) ? GDL_DOCK_ITEM_BEH_NORMAL + : GDL_DOCK_ITEM_BEH_CANT_DOCK_CENTER); if (!icon_name.empty()) { _icon_pixbuf = sp_get_icon_pixbuf(icon_name, "/toolbox/secondary"); } - if ( _icon_pixbuf ) { - _gdl_dock_item = gdl_dock_item_new_with_pixbuf_icon( name.c_str(), long_name.c_str(), - _icon_pixbuf->gobj(), gdl_dock_behavior ); + if (_icon_pixbuf) { + _gdl_dock_item = gdl_dock_item_new_with_pixbuf_icon(name.c_str(), long_name.c_str(), _icon_pixbuf->gobj(), + gdl_dock_behavior); #ifndef WITH_GDL_3_35 // Leak a reference because GDL could crash us // https://gitlab.gnome.org/GNOME/gdl/issues/2 @@ -75,14 +72,14 @@ DockItem::DockItem(Dock& dock, const Glib::ustring& name, const Glib::ustring& l _connections.emplace_back( signal_realize().connect(sigc::mem_fun(*this, &Inkscape::UI::Widget::DockItem::_onRealize))); - _dock.addItem(*this, ( _prev_state == FLOATING_STATE || _prev_state == ICONIFIED_FLOATING_STATE ) ? GDL_DOCK_FLOATING : placement); + _dock.addItem(*this, (_prev_state == FLOATING_STATE || _prev_state == ICONIFIED_FLOATING_STATE) ? GDL_DOCK_FLOATING + : placement); if (_prev_state == ICONIFIED_FLOATING_STATE || _prev_state == ICONIFIED_DOCKED_STATE) { iconify(); } show_all(); - } DockItem::~DockItem() @@ -95,27 +92,22 @@ DockItem::~DockItem() _signal_key_press_event_connection.disconnect(); } -Gtk::Widget& -DockItem::getWidget() +Gtk::Widget &DockItem::getWidget() { return *_gdl_dock_item_wrapped; } -GtkWidget * -DockItem::gobj() +GtkWidget *DockItem::gobj() { return _gdl_dock_item; } -Gtk::VBox * -DockItem::get_vbox() +Gtk::VBox *DockItem::get_vbox() { return &_dock_item_box; } - -void -DockItem::get_position(int& x, int& y) +void DockItem::get_position(int &x, int &y) { if (getWindow()) { getWindow()->get_position(x, y); @@ -125,8 +117,7 @@ DockItem::get_position(int& x, int& y) } } -void -DockItem::get_size(int& width, int& height) +void DockItem::get_size(int &width, int &height) { if (getWindow()) { getWindow()->get_size(width, height); @@ -136,9 +127,7 @@ DockItem::get_size(int& width, int& height) } } - -void -DockItem::resize(int width, int height) +void DockItem::resize(int width, int height) { // Not needed anymore, see Dock::restoreLayout() #if 0 @@ -147,16 +136,13 @@ DockItem::resize(int width, int height) #endif } - -void -DockItem::move(int x, int y) +void DockItem::move(int x, int y) { if (_window) _window->move(x, y); } -void -DockItem::set_position(Gtk::WindowPosition position) +void DockItem::set_position(Gtk::WindowPosition position) { // Not needed anymore, see Dock::restoreLayout() #if 0 @@ -165,53 +151,42 @@ DockItem::set_position(Gtk::WindowPosition position) #endif } -void -DockItem::set_size_request(int width, int height) +void 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) { Gtk::Requisition req_natural; getWidget().get_preferred_size(req_natural, requisition); } -void -DockItem::set_title(Glib::ustring title) +void DockItem::set_title(Glib::ustring title) { - g_object_set (_gdl_dock_item, - "long-name", title.c_str(), - NULL); + g_object_set(_gdl_dock_item, "long-name", title.c_str(), NULL); - gdl_dock_item_set_tablabel(GDL_DOCK_ITEM(_gdl_dock_item), - gtk_label_new (title.c_str())); + gdl_dock_item_set_tablabel(GDL_DOCK_ITEM(_gdl_dock_item), gtk_label_new(title.c_str())); } -bool -DockItem::isAttached() const +bool DockItem::isAttached() const { - return GDL_DOCK_OBJECT_ATTACHED (_gdl_dock_item); + return GDL_DOCK_OBJECT_ATTACHED(_gdl_dock_item); } - -bool -DockItem::isFloating() const +bool DockItem::isFloating() const { - return (GTK_WIDGET(gdl_dock_object_get_toplevel(GDL_DOCK_OBJECT (_gdl_dock_item))) != - _dock.getGdlWidget()); + return (GTK_WIDGET(gdl_dock_object_get_toplevel(GDL_DOCK_OBJECT(_gdl_dock_item))) != _dock.getGdlWidget()); } -bool -DockItem::isIconified() const +bool DockItem::isIconified() const { gboolean iconified = false; g_object_get(_gdl_dock_item, "iconified", &iconified, nullptr); return iconified; } -DockItem::State -DockItem::getState() const +DockItem::State DockItem::getState() const { if (isIconified() && _prev_state == FLOATING_STATE) { return ICONIFIED_FLOATING_STATE; @@ -226,17 +201,15 @@ DockItem::getState() const return UNATTACHED; } -DockItem::State -DockItem::getPrevState() const +DockItem::State DockItem::getPrevState() const { return _prev_state; } -GdlDockPlacement -DockItem::getPlacement() const +GdlDockPlacement DockItem::getPlacement() const { GdlDockPlacement placement = GDL_DOCK_TOP; - GdlDockObject *parent = gdl_dock_object_get_parent_object (GDL_DOCK_OBJECT(_gdl_dock_item)); + GdlDockObject *parent = gdl_dock_object_get_parent_object(GDL_DOCK_OBJECT(_gdl_dock_item)); if (parent) { gdl_dock_object_child_placement(parent, GDL_DOCK_OBJECT(_gdl_dock_item), &placement); } @@ -244,32 +217,27 @@ DockItem::getPlacement() const return placement; } -void -DockItem::hide() +void DockItem::hide() { - gdl_dock_item_hide_item (GDL_DOCK_ITEM(_gdl_dock_item)); + gdl_dock_item_hide_item(GDL_DOCK_ITEM(_gdl_dock_item)); } -void -DockItem::show() +void DockItem::show() { - gdl_dock_item_show_item (GDL_DOCK_ITEM(_gdl_dock_item)); + gdl_dock_item_show_item(GDL_DOCK_ITEM(_gdl_dock_item)); } -void -DockItem::iconify() +void DockItem::iconify() { - gdl_dock_item_iconify_item (GDL_DOCK_ITEM(_gdl_dock_item)); + gdl_dock_item_iconify_item(GDL_DOCK_ITEM(_gdl_dock_item)); } -void -DockItem::show_all() +void DockItem::show_all() { gtk_widget_show_all(_gdl_dock_item); } -void -DockItem::present() +void DockItem::present() { gdl_dock_object_present(GDL_DOCK_OBJECT(_gdl_dock_item), nullptr); @@ -280,85 +248,66 @@ DockItem::present() _dock.scrollToItem(*this); } - -void -DockItem::grab_focus() +void DockItem::grab_focus() { - if (gtk_widget_get_realized (_gdl_dock_item)) { - + if (gtk_widget_get_realized(_gdl_dock_item)) { // make sure the window we're in is present Gtk::Widget *toplevel = getWidget().get_toplevel(); if (Gtk::Window *window = dynamic_cast<Gtk::Window *>(toplevel)) { window->present(); } - gtk_widget_grab_focus (_gdl_dock_item); + gtk_widget_grab_focus(_gdl_dock_item); } else { _grab_focus_on_realize = true; } } - /* Signal wrappers */ -Glib::SignalProxy0<void> -DockItem::signal_show() +Glib::SignalProxy0<void> DockItem::signal_show() { - return Glib::SignalProxy0<void>(_gdl_dock_item_wrapped, - &_signal_show_proxy); + return Glib::SignalProxy0<void>(_gdl_dock_item_wrapped, &_signal_show_proxy); } -Glib::SignalProxy0<void> -DockItem::signal_hide() +Glib::SignalProxy0<void> DockItem::signal_hide() { - return Glib::SignalProxy0<void>(_gdl_dock_item_wrapped, - &_signal_hide_proxy); + return Glib::SignalProxy0<void>(_gdl_dock_item_wrapped, &_signal_hide_proxy); } -Glib::SignalProxy1<bool, GdkEventAny *> -DockItem::signal_delete_event() +Glib::SignalProxy1<bool, GdkEventAny *> DockItem::signal_delete_event() { - return Glib::SignalProxy1<bool, GdkEventAny *>(_gdl_dock_item_wrapped, - &_signal_delete_event_proxy); + return Glib::SignalProxy1<bool, GdkEventAny *>(_gdl_dock_item_wrapped, &_signal_delete_event_proxy); } -Glib::SignalProxy0<void> -DockItem::signal_drag_begin() +Glib::SignalProxy0<void> DockItem::signal_drag_begin() { - return Glib::SignalProxy0<void>(_gdl_dock_item_wrapped, - &_signal_drag_begin_proxy); + return Glib::SignalProxy0<void>(_gdl_dock_item_wrapped, &_signal_drag_begin_proxy); } -Glib::SignalProxy1<void, bool> -DockItem::signal_drag_end() +Glib::SignalProxy1<void, bool> DockItem::signal_drag_end() { - return Glib::SignalProxy1<void, bool>(_gdl_dock_item_wrapped, - &_signal_drag_end_proxy); + return Glib::SignalProxy1<void, bool>(_gdl_dock_item_wrapped, &_signal_drag_end_proxy); } -Glib::SignalProxy0<void> -DockItem::signal_realize() +Glib::SignalProxy0<void> DockItem::signal_realize() { - return Glib::SignalProxy0<void>(_gdl_dock_item_wrapped, - &_signal_realize_proxy); + return Glib::SignalProxy0<void>(_gdl_dock_item_wrapped, &_signal_realize_proxy); } -sigc::signal<void, DockItem::State, DockItem::State> -DockItem::signal_state_changed() +sigc::signal<void, DockItem::State, DockItem::State> DockItem::signal_state_changed() { return _signal_state_changed; } -void -DockItem::_onHideWindow() +void DockItem::_onHideWindow() { if (_window) _window->get_position(_x, _y); } -void -DockItem::_onHide() +void DockItem::_onHide() { if (_prev_state == ICONIFIED_DOCKED_STATE) _prev_state = DOCKED_STATE; @@ -368,22 +317,19 @@ DockItem::_onHide() _signal_state_changed.emit(UNATTACHED, getState()); } -void -DockItem::_onShow() +void DockItem::_onShow() { _signal_state_changed.emit(UNATTACHED, getState()); } -void -DockItem::_onDragBegin() +void DockItem::_onDragBegin() { _prev_state = getState(); if (_prev_state == FLOATING_STATE) _dock.toggleDockable(getWidget().get_width(), getWidget().get_height()); } -void -DockItem::_onDragEnd(bool) +void DockItem::_onDragEnd(bool) { State state = getState(); @@ -398,8 +344,7 @@ DockItem::_onDragEnd(bool) _prev_state = state; } -void -DockItem::_onRealize() +void DockItem::_onRealize() { if (isFloating()) { auto window = dynamic_cast<Gtk::Window *>(getWidget().get_toplevel()); @@ -423,16 +368,14 @@ DockItem::_onRealize() } } -bool -DockItem::_onKeyPress(GdkEventKey *event) +bool DockItem::_onKeyPress(GdkEventKey *event) { gboolean return_value; - g_signal_emit_by_name (_gdl_dock_item, "key_press_event", event, &return_value); + g_signal_emit_by_name(_gdl_dock_item, "key_press_event", event, &return_value); return return_value; } -void -DockItem::_onStateChanged(State /*prev_state*/, State new_state) +void DockItem::_onStateChanged(State /*prev_state*/, State new_state) { _signal_hide_connection.disconnect(); _signal_key_press_event_connection.disconnect(); @@ -443,22 +386,18 @@ DockItem::_onStateChanged(State /*prev_state*/, State new_state) _signal_hide_connection = _window->signal_hide().connect(sigc::mem_fun(*this, &Inkscape::UI::Widget::DockItem::_onHideWindow)); - _signal_key_press_event_connection = - _window->signal_key_press_event().connect(sigc::mem_fun(*this, &Inkscape::UI::Widget::DockItem::_onKeyPress)); + _signal_key_press_event_connection = _window->signal_key_press_event().connect( + sigc::mem_fun(*this, &Inkscape::UI::Widget::DockItem::_onKeyPress)); } } - -bool -DockItem::_onDeleteEvent(GdkEventAny */*event*/) +bool DockItem::_onDeleteEvent(GdkEventAny * /*event*/) { hide(); return false; } - -Gtk::Window * -DockItem::getWindow() +Gtk::Window *DockItem::getWindow() { g_return_val_if_fail(_gdl_dock_item, 0); Gtk::Container *parent = getWidget().get_parent(); @@ -466,70 +405,38 @@ DockItem::getWindow() return (parent ? dynamic_cast<Gtk::Window *>(parent) : nullptr); } -const Glib::SignalProxyInfo -DockItem::_signal_show_proxy = -{ - "show", - (GCallback) &Glib::SignalProxyNormal::slot0_void_callback, - (GCallback) &Glib::SignalProxyNormal::slot0_void_callback -}; - -const Glib::SignalProxyInfo -DockItem::_signal_hide_proxy = -{ - "hide", - (GCallback) &Glib::SignalProxyNormal::slot0_void_callback, - (GCallback) &Glib::SignalProxyNormal::slot0_void_callback -}; +const Glib::SignalProxyInfo DockItem::_signal_show_proxy = {"show", + (GCallback)&Glib::SignalProxyNormal::slot0_void_callback, + (GCallback)&Glib::SignalProxyNormal::slot0_void_callback}; +const Glib::SignalProxyInfo DockItem::_signal_hide_proxy = {"hide", + (GCallback)&Glib::SignalProxyNormal::slot0_void_callback, + (GCallback)&Glib::SignalProxyNormal::slot0_void_callback}; -const Glib::SignalProxyInfo -DockItem::_signal_delete_event_proxy = -{ - "delete_event", - (GCallback) &_signal_delete_event_callback, - (GCallback) &_signal_delete_event_callback -}; +const Glib::SignalProxyInfo DockItem::_signal_delete_event_proxy = { + "delete_event", (GCallback)&_signal_delete_event_callback, (GCallback)&_signal_delete_event_callback}; +const Glib::SignalProxyInfo DockItem::_signal_drag_begin_proxy = { + "dock-drag-begin", (GCallback)&Glib::SignalProxyNormal::slot0_void_callback, + (GCallback)&Glib::SignalProxyNormal::slot0_void_callback}; -const Glib::SignalProxyInfo -DockItem::_signal_drag_begin_proxy = -{ - "dock-drag-begin", - (GCallback) &Glib::SignalProxyNormal::slot0_void_callback, - (GCallback) &Glib::SignalProxyNormal::slot0_void_callback -}; +const Glib::SignalProxyInfo DockItem::_signal_drag_end_proxy = {"dock_drag_end", (GCallback)&_signal_drag_end_callback, + (GCallback)&_signal_drag_end_callback}; +const Glib::SignalProxyInfo DockItem::_signal_realize_proxy = { + "realize", (GCallback)&Glib::SignalProxyNormal::slot0_void_callback, + (GCallback)&Glib::SignalProxyNormal::slot0_void_callback}; -const Glib::SignalProxyInfo -DockItem::_signal_drag_end_proxy = -{ - "dock_drag_end", - (GCallback) &_signal_drag_end_callback, - (GCallback) &_signal_drag_end_callback -}; - - -const Glib::SignalProxyInfo -DockItem::_signal_realize_proxy = -{ - "realize", - (GCallback) &Glib::SignalProxyNormal::slot0_void_callback, - (GCallback) &Glib::SignalProxyNormal::slot0_void_callback -}; - - -gboolean -DockItem::_signal_delete_event_callback(GtkWidget *self, GdkEventAny *event, void *data) +gboolean DockItem::_signal_delete_event_callback(GtkWidget *self, GdkEventAny *event, void *data) { using namespace Gtk; typedef sigc::slot<bool, GdkEventAny *> SlotType; - if (Glib::ObjectBase::_get_current_wrapper((GObject *) self)) { + if (Glib::ObjectBase::_get_current_wrapper((GObject *)self)) { try { - if(sigc::slot_base *const slot = Glib::SignalProxyNormal::data_to_slot(data)) - return static_cast<int>( (*static_cast<SlotType*>(slot))(event) ); - } catch(...) { + if (sigc::slot_base *const slot = Glib::SignalProxyNormal::data_to_slot(data)) + return static_cast<int>((*static_cast<SlotType *>(slot))(event)); + } catch (...) { Glib::exception_handlers_invoke(); } } @@ -538,23 +445,21 @@ DockItem::_signal_delete_event_callback(GtkWidget *self, GdkEventAny *event, voi return RType(); } -void -DockItem::_signal_drag_end_callback(GtkWidget *self, gboolean cancelled, void *data) +void DockItem::_signal_drag_end_callback(GtkWidget *self, gboolean cancelled, void *data) { using namespace Gtk; typedef sigc::slot<void, bool> SlotType; - if (Glib::ObjectBase::_get_current_wrapper((GObject *) self)) { + if (Glib::ObjectBase::_get_current_wrapper((GObject *)self)) { try { - if(sigc::slot_base *const slot = Glib::SignalProxyNormal::data_to_slot(data)) + if (sigc::slot_base *const slot = Glib::SignalProxyNormal::data_to_slot(data)) (*static_cast<SlotType *>(slot))(cancelled); - } catch(...) { + } catch (...) { Glib::exception_handlers_invoke(); } } } - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/dock-item.h b/src/ui/widget/dock-item.h index 943657fd4cd4fd6f018241765185f2e8162b47bc..67701a537488d165e3a18c14b45fc242f99dbca0 100644 --- a/src/ui/widget/dock-item.h +++ b/src/ui/widget/dock-item.h @@ -8,18 +8,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #ifndef INKSCAPE_UI_WIGET_DOCK_ITEM_H #define INKSCAPE_UI_WIGET_DOCK_ITEM_H +#include <gdl/gdl.h> #include <gtkmm/box.h> #include <gtkmm/frame.h> #include <gtkmm/window.h> -#include <gdl/gdl.h> - namespace Gtk { - class HButtonBox; +class HButtonBox; } namespace Inkscape { @@ -31,35 +29,37 @@ class Dock; /** * A custom wrapper around gdl-dock-item. */ -class DockItem { - +class DockItem +{ public: - - enum State { UNATTACHED, // item not bound to the dock (a temporary state) - FLOATING_STATE, // item not in its dock (but can be docked in other, - // e.g. floating, docks) - DOCKED_STATE, // item in its assigned dock - ICONIFIED_DOCKED_STATE, // item iconified in its assigned dock from dock - ICONIFIED_FLOATING_STATE}; // item iconified in its assigned dock from float - - DockItem(Dock& dock, const Glib::ustring& name, const Glib::ustring& long_name, - const Glib::ustring& icon_name, State state, GdlDockPlacement placement); + enum State + { + UNATTACHED, // item not bound to the dock (a temporary state) + FLOATING_STATE, // item not in its dock (but can be docked in other, + // e.g. floating, docks) + DOCKED_STATE, // item in its assigned dock + ICONIFIED_DOCKED_STATE, // item iconified in its assigned dock from dock + ICONIFIED_FLOATING_STATE + }; // item iconified in its assigned dock from float + + DockItem(Dock &dock, const Glib::ustring &name, const Glib::ustring &long_name, const Glib::ustring &icon_name, + State state, GdlDockPlacement placement); ~DockItem(); - Gtk::Widget& getWidget(); + Gtk::Widget &getWidget(); GtkWidget *gobj(); Gtk::VBox *get_vbox(); - void get_position(int& x, int& y); - void get_size(int& width, int& height); + void get_position(int &x, int &y); + void get_size(int &width, int &height); void resize(int width, int height); void move(int x, int y); void set_position(Gtk::WindowPosition); void set_size_request(int width, int height); - void size_request(Gtk::Requisition& requisition); + void size_request(Gtk::Requisition &requisition); void set_title(Glib::ustring title); bool isAttached() const; @@ -69,7 +69,7 @@ public: State getPrevState() const; GdlDockPlacement getPlacement() const; - Gtk::Window *getWindow(); //< gives the parent window, if the dock item has one (i.e. it's floating) + Gtk::Window *getWindow(); //< gives the parent window, if the dock item has one (i.e. it's floating) void hide(); void show(); @@ -92,20 +92,20 @@ public: private: std::vector<sigc::connection> _connections; - Dock &_dock; //< parent dock + Dock &_dock; //< parent dock - State _prev_state; //< last known state + State _prev_state; //< last known state - Gtk::Window *_window; //< reference to floating window, if any - int _x, _y; //< last known position of window, if floating + Gtk::Window *_window; //< reference to floating window, if any + int _x, _y; //< last known position of window, if floating - bool _grab_focus_on_realize; //< if the dock item should grab focus on the next realize + bool _grab_focus_on_realize; //< if the dock item should grab focus on the next realize GtkWidget *_gdl_dock_item; Gtk::Container *_gdl_dock_item_wrapped; Glib::RefPtr<Gdk::Pixbuf> _icon_pixbuf; - /** Interface widgets, will be packed like + /** Interface widgets, will be packed like * gdl_dock_item -> _frame -> _dock_item_box */ Gtk::Frame _frame; @@ -136,7 +136,7 @@ private: static const Glib::SignalProxyInfo _signal_realize_proxy; static gboolean _signal_delete_event_callback(GtkWidget *self, GdkEventAny *event, void *data); - static void _signal_drag_end_callback(GtkWidget* self, gboolean p0, void* data); + static void _signal_drag_end_callback(GtkWidget *self, gboolean p0, void *data); sigc::signal<void, State, State> _signal_state_changed; diff --git a/src/ui/widget/dock.cpp b/src/ui/widget/dock.cpp index 3aba481ec32c487a5ca98d15ccf65756e6341212..58d24a3ffe5e25e2b17915577bf37012f35da43d 100644 --- a/src/ui/widget/dock.cpp +++ b/src/ui/widget/dock.cpp @@ -12,18 +12,18 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif -#include "dock.h" -#include "io/resource.h" -#include "preferences.h" -#include "desktop.h" - #include <gtkmm/adjustment.h> #include <gtkmm/paned.h> #include <gtkmm/scrolledwindow.h> +#include "desktop.h" +#include "dock.h" +#include "io/resource.h" +#include "preferences.h" + namespace Inkscape { namespace UI { namespace Widget { @@ -42,19 +42,18 @@ static const char *get_docklayout_filename() } Dock::Dock(Gtk::Orientation orientation) - : _gdl_dock(gdl_dock_new()), - _gdl_dock_bar(GDL_DOCK_BAR(gdl_dock_bar_new(G_OBJECT(_gdl_dock)))), - _scrolled_window (Gtk::manage(new Gtk::ScrolledWindow)) + : _gdl_dock(gdl_dock_new()) + , _gdl_dock_bar(GDL_DOCK_BAR(gdl_dock_bar_new(G_OBJECT(_gdl_dock)))) + , _scrolled_window(Gtk::manage(new Gtk::ScrolledWindow)) { _gdl_layout = gdl_dock_layout_new(G_OBJECT(_gdl_dock)); gtk_widget_set_name(_gdl_dock, "GdlDock"); - gtk_orientable_set_orientation(GTK_ORIENTABLE(_gdl_dock_bar), - static_cast<GtkOrientation>(orientation)); + gtk_orientable_set_orientation(GTK_ORIENTABLE(_gdl_dock_bar), static_cast<GtkOrientation>(orientation)); - _dock_box = Gtk::manage(new Gtk::Box(orientation == Gtk::ORIENTATION_HORIZONTAL ? - Gtk::ORIENTATION_VERTICAL : Gtk::ORIENTATION_HORIZONTAL)); + _dock_box = Gtk::manage(new Gtk::Box(orientation == Gtk::ORIENTATION_HORIZONTAL ? Gtk::ORIENTATION_VERTICAL + : Gtk::ORIENTATION_HORIZONTAL)); _dock_box->set_name("DockBox"); _dock_box->pack_start(*Gtk::manage(Glib::wrap(GTK_WIDGET(_gdl_dock)))); _dock_box->pack_end(*Gtk::manage(Glib::wrap(GTK_WIDGET(_gdl_dock_bar))), Gtk::PACK_SHRINK); @@ -65,9 +64,8 @@ Dock::Dock(Gtk::Orientation orientation) _scrolled_window->set_size_request(0); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - GdlSwitcherStyle gdl_switcher_style = - static_cast<GdlSwitcherStyle>(prefs->getIntLimited("/options/dock/switcherstyle", - GDL_SWITCHER_STYLE_BOTH, 0, 4)); + GdlSwitcherStyle gdl_switcher_style = static_cast<GdlSwitcherStyle>( + prefs->getIntLimited("/options/dock/switcherstyle", GDL_SWITCHER_STYLE_BOTH, 0, 4)); auto filleritem = gdl_dock_item_new("filleritem", "", static_cast<GdlDockItemBehavior>( // @@ -77,19 +75,14 @@ Dock::Dock(Gtk::Orientation orientation) GDL_DOCK_ITEM_BEH_CANT_DOCK_CENTER | // GDL_DOCK_ITEM_BEH_CANT_CLOSE | GDL_DOCK_ITEM_BEH_CANT_ICONIFY | GDL_DOCK_ITEM_BEH_NO_GRIP)); - gdl_dock_add_item(GDL_DOCK(_gdl_dock), - GDL_DOCK_ITEM(filleritem), - GDL_DOCK_BOTTOM); + gdl_dock_add_item(GDL_DOCK(_gdl_dock), GDL_DOCK_ITEM(filleritem), GDL_DOCK_BOTTOM); GdlDockMaster *master = GDL_DOCK_MASTER(gdl_dock_object_get_master(GDL_DOCK_OBJECT(_gdl_dock))); - g_object_set(master, - "switcher-style", gdl_switcher_style, - NULL); + g_object_set(master, "switcher-style", gdl_switcher_style, NULL); GdlDockBarStyle gdl_dock_bar_style = - static_cast<GdlDockBarStyle>(prefs->getIntLimited("/options/dock/dockbarstyle", - GDL_DOCK_BAR_BOTH, 0, 3)); + static_cast<GdlDockBarStyle>(prefs->getIntLimited("/options/dock/dockbarstyle", GDL_DOCK_BAR_BOTH, 0, 3)); gdl_dock_bar_set_style(_gdl_dock_bar, gdl_dock_bar_style); @@ -138,18 +131,16 @@ void Dock::saveLayout() gdl_dock_layout_save_to_file(_gdl_layout, get_docklayout_filename()); } -void Dock::addItem(DockItem& item, GdlDockPlacement placement) +void Dock::addItem(DockItem &item, GdlDockPlacement placement) { _dock_items.push_back(&item); - gdl_dock_add_item(GDL_DOCK(_gdl_dock), - GDL_DOCK_ITEM(item.gobj()), - placement); + gdl_dock_add_item(GDL_DOCK(_gdl_dock), GDL_DOCK_ITEM(item.gobj()), placement); } Gtk::Widget &Dock::getWidget() { - return *_scrolled_window; + return *_scrolled_window; } Gtk::Paned *Dock::getParentPaned() @@ -213,7 +204,7 @@ void Dock::toggleDockable(int width, int height) } } -void Dock::scrollToItem(DockItem& item) +void Dock::scrollToItem(DockItem &item) { int item_x, item_y; item.getWidget().translate_coordinates(getWidget(), 0, 0, item_x, item_y); @@ -224,15 +215,12 @@ void Dock::scrollToItem(DockItem& item) if (item_y < 0) _scrolled_window->get_vadjustment()->set_value(vadjustment + item_y); else if (item_y + item_height > dock_height) - _scrolled_window->get_vadjustment()->set_value( - vadjustment + ((item_y + item_height) - dock_height)); + _scrolled_window->get_vadjustment()->set_value(vadjustment + ((item_y + item_height) - dock_height)); } -Glib::SignalProxy0<void> -Dock::signal_layout_changed() +Glib::SignalProxy0<void> Dock::signal_layout_changed() { - return Glib::SignalProxy0<void>(Glib::wrap(GTK_WIDGET(_gdl_dock)), - &_signal_layout_changed_proxy); + return Glib::SignalProxy0<void>(Glib::wrap(GTK_WIDGET(_gdl_dock)), &_signal_layout_changed_proxy); } void Dock::_onLayoutChanged() @@ -242,20 +230,14 @@ void Dock::_onLayoutChanged() } } -const Glib::SignalProxyInfo -Dock::_signal_layout_changed_proxy = -{ - "layout-changed", - (GCallback) &Glib::SignalProxyNormal::slot0_void_callback, - (GCallback) &Glib::SignalProxyNormal::slot0_void_callback -}; - +const Glib::SignalProxyInfo Dock::_signal_layout_changed_proxy = { + "layout-changed", (GCallback)&Glib::SignalProxyNormal::slot0_void_callback, + (GCallback)&Glib::SignalProxyNormal::slot0_void_callback}; } // namespace Widget } // namespace UI } // namespace Inkscape - /* Local Variables: mode:c++ diff --git a/src/ui/widget/dock.h b/src/ui/widget/dock.h index c674340f63befd26d3ea33dc7e54a9d6641f3b95..1771b38452efca5b9c315d0a262bbe1aab1f1d9e 100644 --- a/src/ui/widget/dock.h +++ b/src/ui/widget/dock.h @@ -14,6 +14,7 @@ #define INKSCAPE_UI_WIDGET_DOCK_H #include <gtkmm/box.h> + #include "ui/widget/dock-item.h" struct _GdlDock; @@ -24,27 +25,26 @@ typedef _GdlDockBar GdlDockBar; namespace Gtk { class Paned; class ScrolledWindow; -} +} // namespace Gtk namespace Inkscape { namespace UI { namespace Widget { -class Dock { - +class Dock +{ public: - - Dock(Gtk::Orientation orientation=Gtk::ORIENTATION_VERTICAL); + Dock(Gtk::Orientation orientation = Gtk::ORIENTATION_VERTICAL); ~Dock(); - void addItem(DockItem& item, GdlDockPlacement placement); + void addItem(DockItem &item, GdlDockPlacement placement); - Gtk::Widget& getWidget(); //< return the top widget + Gtk::Widget &getWidget(); //< return the top widget Gtk::Paned *getParentPaned(); - GtkWidget* getGdlWidget(); //< return the top gdl widget + GtkWidget *getGdlWidget(); //< return the top gdl widget - bool isEmpty() const; //< true iff none of the dock's items are in a docked state + bool isEmpty() const; //< true iff none of the dock's items are in a docked state bool hasIconifiedItems() const; Glib::SignalProxy0<void> signal_layout_changed(); @@ -53,10 +53,10 @@ public: void show(); /** Toggle size of dock between the previous dimensions and the ones sent as parameters */ - void toggleDockable(int width=0, int height=0); + void toggleDockable(int width = 0, int height = 0); /** Scrolls the scrolled window container to make the provided dock item visible, if needed */ - void scrollToItem(DockItem& item); + void scrollToItem(DockItem &item); //! Disconnect all signals and clear all unowned pointers void releaseAllReferences(); @@ -66,18 +66,17 @@ public: void saveLayout(); protected: - std::vector<sigc::connection> _connections; - std::vector<DockItem *> _dock_items; //< added dock items + std::vector<DockItem *> _dock_items; //< added dock items - /** Interface widgets, will be packed like + /** Interface widgets, will be packed like * _scrolled_window -> (_dock_box -> (_paned -> (_dock -> _filler) | _dock_bar)) */ - Gtk::Box *_dock_box; - GtkWidget *_gdl_dock; - GdlDockBar *_gdl_dock_bar; - GdlDockLayout *_gdl_layout; + Gtk::Box *_dock_box; + GtkWidget *_gdl_dock; + GdlDockBar *_gdl_dock_bar; + GdlDockLayout *_gdl_layout; Gtk::ScrolledWindow *_scrolled_window; /** Internal signal handlers */ @@ -95,7 +94,7 @@ protected: } // namespace UI } // namespace Inkscape -#endif //INKSCAPE_UI_DIALOG_BEHAVIOUR_H +#endif // INKSCAPE_UI_DIALOG_BEHAVIOUR_H /* Local Variables: @@ -107,4 +106,3 @@ protected: End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - diff --git a/src/ui/widget/entity-entry.cpp b/src/ui/widget/entity-entry.cpp index fcfba0eb17c0b654fd907920d2731e9eea166d7d..9f4b1e5c572471287b54b9221a828d5021a6d133 100644 --- a/src/ui/widget/entity-entry.cpp +++ b/src/ui/widget/entity-entry.cpp @@ -16,18 +16,16 @@ #include "entity-entry.h" -#include <gtkmm/scrolledwindow.h> #include <gtkmm/entry.h> +#include <gtkmm/scrolledwindow.h> #include "document-undo.h" #include "inkscape.h" +#include "object/sp-root.h" #include "preferences.h" #include "rdf.h" -#include "verbs.h" - -#include "object/sp-root.h" - #include "ui/widget/registry.h" +#include "verbs.h" namespace Inkscape { namespace UI { @@ -37,34 +35,32 @@ namespace Widget { //--------------------------------------------------- -EntityEntry* -EntityEntry::create (rdf_work_entity_t* ent, Registry& wr) +EntityEntry *EntityEntry::create(rdf_work_entity_t *ent, Registry &wr) { - g_assert (ent); - EntityEntry* obj = nullptr; - switch (ent->format) - { - case RDF_FORMAT_LINE: - obj = new EntityLineEntry (ent, wr); + g_assert(ent); + EntityEntry *obj = nullptr; + switch (ent->format) { + case RDF_FORMAT_LINE: + obj = new EntityLineEntry(ent, wr); break; - case RDF_FORMAT_MULTILINE: - obj = new EntityMultiLineEntry (ent, wr); + case RDF_FORMAT_MULTILINE: + obj = new EntityMultiLineEntry(ent, wr); break; default: - g_warning ("An unknown RDF format was requested."); + g_warning("An unknown RDF format was requested."); } - g_assert (obj); + g_assert(obj); obj->_label.show(); return obj; } -EntityEntry::EntityEntry (rdf_work_entity_t* ent, Registry& wr) - : _label(Glib::ustring(_(ent->title)), Gtk::ALIGN_END), - _packable(nullptr), - _entity(ent), _wr(&wr) -{ -} +EntityEntry::EntityEntry(rdf_work_entity_t *ent, Registry &wr) + : _label(Glib::ustring(_(ent->title)), Gtk::ALIGN_END) + , _packable(nullptr) + , _entity(ent) + , _wr(&wr) +{} EntityEntry::~EntityEntry() { @@ -74,126 +70,122 @@ EntityEntry::~EntityEntry() void EntityEntry::save_to_preferences(SPDocument *doc) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - const gchar *text = rdf_get_work_entity (doc, _entity); + 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) +EntityLineEntry::EntityLineEntry(rdf_work_entity_t *ent, Registry &wr) + : EntityEntry(ent, wr) { Gtk::Entry *e = new Gtk::Entry; - e->set_tooltip_text (_(ent->tip)); + e->set_tooltip_text(_(ent->tip)); _packable = e; - _changed_connection = e->signal_changed().connect (sigc::mem_fun (*this, &EntityLineEntry::on_changed)); + _changed_connection = e->signal_changed().connect(sigc::mem_fun(*this, &EntityLineEntry::on_changed)); } EntityLineEntry::~EntityLineEntry() { - delete static_cast<Gtk::Entry*>(_packable); + delete static_cast<Gtk::Entry *>(_packable); } void EntityLineEntry::update(SPDocument *doc) { - const char *text = rdf_get_work_entity (doc, _entity); + const char *text = rdf_get_work_entity(doc, _entity); // If RDF title is not set, get the document's <title> and set the RDF: - if ( !text && !strcmp(_entity->name, "title") && doc->getRoot() ) { + if (!text && !strcmp(_entity->name, "title") && doc->getRoot()) { text = doc->getRoot()->title(); rdf_set_work_entity(doc, _entity, text); } - static_cast<Gtk::Entry*>(_packable)->set_text (text ? text : ""); + 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()); + static_cast<Gtk::Entry *>(_packable)->set_text(text.c_str()); } } -void -EntityLineEntry::on_changed() +void EntityLineEntry::on_changed() { if (_wr->isUpdating() || !_wr->desktop()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); SPDocument *doc = _wr->desktop()->getDocument(); - Glib::ustring text = static_cast<Gtk::Entry*>(_packable)->get_text(); - if (rdf_set_work_entity (doc, _entity, text.c_str())) { + Glib::ustring text = static_cast<Gtk::Entry *>(_packable)->get_text(); + if (rdf_set_work_entity(doc, _entity, text.c_str())) { if (doc->isSensitive()) { DocumentUndo::done(doc, SP_VERB_NONE, "Document metadata updated"); } } - _wr->setUpdating (false); + _wr->setUpdating(false); } -EntityMultiLineEntry::EntityMultiLineEntry (rdf_work_entity_t* ent, Registry& wr) -: EntityEntry (ent, wr) +EntityMultiLineEntry::EntityMultiLineEntry(rdf_work_entity_t *ent, Registry &wr) + : EntityEntry(ent, wr) { Gtk::ScrolledWindow *s = new Gtk::ScrolledWindow; - s->set_policy (Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); - s->set_shadow_type (Gtk::SHADOW_IN); + s->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); + s->set_shadow_type(Gtk::SHADOW_IN); _packable = s; - _v.set_size_request (-1, 35); - _v.set_wrap_mode (Gtk::WRAP_WORD); - _v.set_accepts_tab (false); - s->add (_v); - _v.set_tooltip_text (_(ent->tip)); - _changed_connection = _v.get_buffer()->signal_changed().connect (sigc::mem_fun (*this, &EntityMultiLineEntry::on_changed)); + _v.set_size_request(-1, 35); + _v.set_wrap_mode(Gtk::WRAP_WORD); + _v.set_accepts_tab(false); + s->add(_v); + _v.set_tooltip_text(_(ent->tip)); + _changed_connection = + _v.get_buffer()->signal_changed().connect(sigc::mem_fun(*this, &EntityMultiLineEntry::on_changed)); } EntityMultiLineEntry::~EntityMultiLineEntry() { - delete static_cast<Gtk::ScrolledWindow*>(_packable); + delete static_cast<Gtk::ScrolledWindow *>(_packable); } void EntityMultiLineEntry::update(SPDocument *doc) { - const char *text = rdf_get_work_entity (doc, _entity); + const char *text = rdf_get_work_entity(doc, _entity); // If RDF title is not set, get the document's <title> and set the RDF: - if ( !text && !strcmp(_entity->name, "title") && doc->getRoot() ) { + if (!text && !strcmp(_entity->name, "title") && doc->getRoot()) { text = doc->getRoot()->title(); rdf_set_work_entity(doc, _entity, text); } - Gtk::ScrolledWindow *s = static_cast<Gtk::ScrolledWindow*>(_packable); - Gtk::TextView *tv = static_cast<Gtk::TextView*>(s->get_child()); - tv->get_buffer()->set_text (text ? text : ""); + Gtk::ScrolledWindow *s = static_cast<Gtk::ScrolledWindow *>(_packable); + Gtk::TextView *tv = static_cast<Gtk::TextView *>(s->get_child()); + 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()); + 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() +void EntityMultiLineEntry::on_changed() { if (_wr->isUpdating() || !_wr->desktop()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); SPDocument *doc = _wr->desktop()->getDocument(); - Gtk::ScrolledWindow *s = static_cast<Gtk::ScrolledWindow*>(_packable); - Gtk::TextView *tv = static_cast<Gtk::TextView*>(s->get_child()); + Gtk::ScrolledWindow *s = static_cast<Gtk::ScrolledWindow *>(_packable); + 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())) { + if (rdf_set_work_entity(doc, _entity, text.c_str())) { DocumentUndo::done(doc, SP_VERB_NONE, "Document metadata updated"); } - _wr->setUpdating (false); + _wr->setUpdating(false); } -} // namespace Dialog +} // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/entity-entry.h b/src/ui/widget/entity-entry.h index 3168e4cb8945441528f2d83b6b615b175d886295..5b97a445b4b71bb38c88f5616f19fbacae4c6844 100644 --- a/src/ui/widget/entity-entry.h +++ b/src/ui/widget/entity-entry.h @@ -26,43 +26,46 @@ namespace Widget { class Registry; -class EntityEntry { +class EntityEntry +{ public: - static EntityEntry* create (rdf_work_entity_t* ent, Registry& wr); + static EntityEntry *create(rdf_work_entity_t *ent, Registry &wr); virtual ~EntityEntry() = 0; - virtual void update (SPDocument *doc) = 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; -protected: - EntityEntry (rdf_work_entity_t* ent, Registry& wr); +protected: + EntityEntry(rdf_work_entity_t *ent, Registry &wr); sigc::connection _changed_connection; rdf_work_entity_t *_entity; Registry *_wr; }; -class EntityLineEntry : public EntityEntry { +class EntityLineEntry : public EntityEntry +{ public: - EntityLineEntry (rdf_work_entity_t* ent, Registry& wr); + EntityLineEntry(rdf_work_entity_t *ent, Registry &wr); ~EntityLineEntry() override; - void update (SPDocument *doc) override; + void update(SPDocument *doc) override; void load_from_preferences() override; protected: void on_changed() override; }; -class EntityMultiLineEntry : public EntityEntry { +class EntityMultiLineEntry : public EntityEntry +{ public: - EntityMultiLineEntry (rdf_work_entity_t* ent, Registry& wr); + EntityMultiLineEntry(rdf_work_entity_t *ent, Registry &wr); ~EntityMultiLineEntry() override; - void update (SPDocument *doc) override; + void update(SPDocument *doc) override; void load_from_preferences() override; -protected: +protected: void on_changed() override; Gtk::TextView _v; }; diff --git a/src/ui/widget/entry.cpp b/src/ui/widget/entry.cpp index e9a63c55aa50e7a683b107a03871d9a718ce0cff..ac189c23bfc0957b77473bc5f49bc8281bc5ee8f 100644 --- a/src/ui/widget/entry.cpp +++ b/src/ui/widget/entry.cpp @@ -16,15 +16,11 @@ namespace Inkscape { namespace UI { namespace Widget { -Entry::Entry( Glib::ustring const &label, Glib::ustring const &tooltip, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) +Entry::Entry(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix, + Glib::ustring const &icon, bool mnemonic) : Labelled(label, tooltip, new Gtk::Entry(), suffix, icon, mnemonic) -{ -} +{} } // namespace Widget } // namespace UI } // namespace Inkscape - diff --git a/src/ui/widget/entry.h b/src/ui/widget/entry.h index 3674d51d4582952cf64d2d9269864c78cc3e7475..fe7a48cc853507d63f139d9297f4ce7016e2ee9e 100644 --- a/src/ui/widget/entry.h +++ b/src/ui/widget/entry.h @@ -27,15 +27,12 @@ namespace Widget { class Entry : public Labelled { public: - Entry( Glib::ustring const &label, - Glib::ustring const &tooltip, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Entry(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix = "", + Glib::ustring const &icon = "", bool mnemonic = true); // TO DO: add methods to access Gtk::Entry widget - - Gtk::Entry* getEntry() {return (Gtk::Entry*)(_widget);}; + + Gtk::Entry *getEntry() { return (Gtk::Entry *)(_widget); }; }; } // namespace Widget diff --git a/src/ui/widget/fill-style.cpp b/src/ui/widget/fill-style.cpp index b3d9192fb44372a9bbafa226f956404160ebe43c..f4842f5cc77c9a5ef97c63d494bca12aab678050 100644 --- a/src/ui/widget/fill-style.cpp +++ b/src/ui/widget/fill-style.cpp @@ -19,26 +19,25 @@ #define noSP_FS_VERBOSE +#include "fill-style.h" + #include <glibmm/i18n.h> #include "desktop-style.h" #include "desktop.h" #include "document-undo.h" -#include "fill-style.h" #include "gradient-chemistry.h" #include "inkscape.h" -#include "selection.h" -#include "verbs.h" - #include "object/sp-defs.h" #include "object/sp-linear-gradient.h" #include "object/sp-mesh-gradient.h" #include "object/sp-pattern.h" #include "object/sp-radial-gradient.h" #include "object/sp-text.h" +#include "selection.h" #include "style.h" - -#include "ui/widget/canvas.h" // Forced redraws +#include "ui/widget/canvas.h" // Forced redraws +#include "verbs.h" // These can be deleted once we sort out the libart dependence. @@ -139,7 +138,6 @@ void FillNStroke::eventContextCB(SPDesktop * /*desktop*/, Inkscape::UI::Tools::T performUpdate(); } - /** * Gets the active fill or stroke style property, then sets the appropriate * color, alpha, gradient, pattern, etc. for the paint-selector. @@ -188,14 +186,13 @@ void FillNStroke::performUpdate() if (kind == FILL) { _psel->setFillrule(query.fill_rule.computed == ART_WIND_RULE_NONZERO - ? UI::Widget::PaintSelector::FILLRULE_NONZERO - : UI::Widget::PaintSelector::FILLRULE_EVENODD); + ? UI::Widget::PaintSelector::FILLRULE_NONZERO + : UI::Widget::PaintSelector::FILLRULE_EVENODD); } if (targPaint.set && targPaint.isColor()) { _psel->setColorAlpha(targPaint.value.color, SP_SCALE24_TO_FLOAT(targOpacity.value)); } else if (targPaint.set && targPaint.isPaintserver()) { - SPPaintServer *server = (kind == FILL) ? query.getFillPaintServer() : query.getStrokePaintServer(); if (server) { @@ -332,8 +329,7 @@ void FillNStroke::dragFromPaint() case UI::Widget::PaintSelector::MODE_SOLID_COLOR: { // local change, do not update from selection _drag_id = g_timeout_add_full(G_PRIORITY_DEFAULT, 100, dragDelayCB, this, nullptr); - _psel->setFlatColor(_desktop, - (kind == FILL) ? "fill" : "stroke", + _psel->setFlatColor(_desktop, (kind == FILL) ? "fill" : "stroke", (kind == FILL) ? "fill-opacity" : "stroke-opacity"); DocumentUndo::maybeDone(_desktop->doc(), (kind == FILL) ? undo_F_label : undo_S_label, SP_VERB_DIALOG_FILL_STROKE, @@ -372,7 +368,7 @@ void FillNStroke::updateFromPaint() } _update = true; - auto document = _desktop->getDocument(); + auto document = _desktop->getDocument(); auto selection = _desktop->getSelection(); std::vector<SPItem *> const items(selection->items().begin(), selection->items().end()); @@ -476,8 +472,8 @@ void FillNStroke::updateFromPaint() if (!vector) { auto gr = sp_gradient_vector_for_object( - document, _desktop, item, - (kind == FILL) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE, createSwatch); + document, _desktop, item, (kind == FILL) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE, + createSwatch); if (gr && createSwatch) { gr->setSwatch(); } @@ -532,7 +528,6 @@ void FillNStroke::updateFromPaint() auto mesh = _psel->getMeshGradient(); for (auto item : items) { - // FIXME: see above if (kind == FILL) { sp_repr_css_change_recursive(item->getRepr(), css, "style"); @@ -612,10 +607,8 @@ void FillNStroke::updateFromPaint() case UI::Widget::PaintSelector::MODE_PATTERN: if (!items.empty()) { - auto pattern = _psel->getPattern(); if (!pattern) { - /* No Pattern in paint selector should mean that we just * changed mode - don't do jack. */ diff --git a/src/ui/widget/fill-style.h b/src/ui/widget/fill-style.h index 35bf4de1e87d4ebe732d163c7fd5a733018376d1..4e697c8e0d065986cf24c512d65b5b48f96ddd8d 100644 --- a/src/ui/widget/fill-style.h +++ b/src/ui/widget/fill-style.h @@ -15,10 +15,10 @@ #ifndef SEEN_DIALOGS_SP_FILL_STYLE_H #define SEEN_DIALOGS_SP_FILL_STYLE_H -#include "ui/widget/paint-selector.h" - #include <gtkmm/box.h> +#include "ui/widget/paint-selector.h" + namespace Gtk { class Widget; } @@ -33,14 +33,15 @@ class ToolBase; namespace Widget { -class FillNStroke : public Gtk::Box { - private: +class FillNStroke : public Gtk::Box +{ +private: FillOrStroke kind; - SPDesktop *_desktop = nullptr; - PaintSelector *_psel = nullptr; - guint32 _last_drag = 0; - guint _drag_id = 0; - bool _update = false; + SPDesktop *_desktop = nullptr; + PaintSelector *_psel = nullptr; + guint32 _last_drag = 0; + guint _drag_id = 0; + bool _update = false; sigc::connection selectChangedConn; sigc::connection subselChangedConn; @@ -59,7 +60,7 @@ class FillNStroke : public Gtk::Box { void performUpdate(); - public: +public: FillNStroke(FillOrStroke k); ~FillNStroke() override; diff --git a/src/ui/widget/filter-effect-chooser.cpp b/src/ui/widget/filter-effect-chooser.cpp index 4785ca15e520ec277d661e577b9f9bbe05363ede..e0785677861d3a4df389107c21779ef6d06f5c7b 100644 --- a/src/ui/widget/filter-effect-chooser.cpp +++ b/src/ui/widget/filter-effect-chooser.cpp @@ -18,27 +18,25 @@ namespace Inkscape { const EnumData<SPBlendMode> SPBlendModeData[SP_CSS_BLEND_ENDMODE] = { - { SP_CSS_BLEND_NORMAL, _("Normal"), "normal" }, - { SP_CSS_BLEND_MULTIPLY, _("Multiply"), "multiply" }, - { SP_CSS_BLEND_SCREEN, _("Screen"), "screen" }, - { SP_CSS_BLEND_DARKEN, _("Darken"), "darken" }, - { SP_CSS_BLEND_LIGHTEN, _("Lighten"), "lighten" }, + {SP_CSS_BLEND_NORMAL, _("Normal"), "normal"}, + {SP_CSS_BLEND_MULTIPLY, _("Multiply"), "multiply"}, + {SP_CSS_BLEND_SCREEN, _("Screen"), "screen"}, + {SP_CSS_BLEND_DARKEN, _("Darken"), "darken"}, + {SP_CSS_BLEND_LIGHTEN, _("Lighten"), "lighten"}, // New in Compositing and Blending Level 1 - { SP_CSS_BLEND_OVERLAY, _("Overlay"), "overlay" }, - { SP_CSS_BLEND_COLORDODGE, _("Color Dodge"), "color-dodge" }, - { SP_CSS_BLEND_COLORBURN, _("Color Burn"), "color-burn" }, - { SP_CSS_BLEND_HARDLIGHT, _("Hard Light"), "hard-light" }, - { SP_CSS_BLEND_SOFTLIGHT, _("Soft Light"), "soft-light" }, - { SP_CSS_BLEND_DIFFERENCE, _("Difference"), "difference" }, - { SP_CSS_BLEND_EXCLUSION, _("Exclusion"), "exclusion" }, - { SP_CSS_BLEND_HUE, _("Hue"), "hue" }, - { SP_CSS_BLEND_SATURATION, _("Saturation"), "saturation" }, - { SP_CSS_BLEND_COLOR, _("Color"), "color" }, - { SP_CSS_BLEND_LUMINOSITY, _("Luminosity"), "luminosity" } -}; + {SP_CSS_BLEND_OVERLAY, _("Overlay"), "overlay"}, + {SP_CSS_BLEND_COLORDODGE, _("Color Dodge"), "color-dodge"}, + {SP_CSS_BLEND_COLORBURN, _("Color Burn"), "color-burn"}, + {SP_CSS_BLEND_HARDLIGHT, _("Hard Light"), "hard-light"}, + {SP_CSS_BLEND_SOFTLIGHT, _("Soft Light"), "soft-light"}, + {SP_CSS_BLEND_DIFFERENCE, _("Difference"), "difference"}, + {SP_CSS_BLEND_EXCLUSION, _("Exclusion"), "exclusion"}, + {SP_CSS_BLEND_HUE, _("Hue"), "hue"}, + {SP_CSS_BLEND_SATURATION, _("Saturation"), "saturation"}, + {SP_CSS_BLEND_COLOR, _("Color"), "color"}, + {SP_CSS_BLEND_LUMINOSITY, _("Luminosity"), "luminosity"}}; const EnumDataConverter<SPBlendMode> SPBlendModeConverter(SPBlendModeData, SP_CSS_BLEND_ENDMODE); - namespace UI { namespace Widget { @@ -66,13 +64,13 @@ SimpleFilterModifier::SimpleFilterModifier(int flags) _hb_blend.pack_start(_lb_blend, false, false, 5); _hb_blend.pack_start(_blend, false, false, 5); /* - * For best fit inkscape-browsers with no GUI to isolation we need all groups, - * clones and symbols with isolation == isolate to not show to the user of - * Inkscape a "strange" behabiour from the designer point of view. - * Is strange because only happends when object not has clip, mask, - * filter, blending or opacity . - * Anyway the feature is a no-gui feature and render as spected. - */ + * For best fit inkscape-browsers with no GUI to isolation we need all groups, + * clones and symbols with isolation == isolate to not show to the user of + * Inkscape a "strange" behabiour from the designer point of view. + * Is strange because only happends when object not has clip, mask, + * filter, blending or opacity . + * Anyway the feature is a no-gui feature and render as spected. + */ /* if (flags & ISOLATION) { _isolation.property_active() = false; _hb_blend.pack_start(_isolation, false, false, 5); @@ -80,7 +78,7 @@ SimpleFilterModifier::SimpleFilterModifier(int flags) _isolation.set_tooltip_text("Don't blend childrens with objects behind"); _lb_isolation.set_tooltip_text("Don't blend childrens with objects behind"); } */ - Gtk::Separator *separator = Gtk::manage(new Gtk::Separator()); + Gtk::Separator *separator = Gtk::manage(new Gtk::Separator()); separator->set_margin_top(8); separator->set_margin_bottom(8); add(*separator); @@ -110,7 +108,7 @@ sigc::signal<void> &SimpleFilterModifier::signal_isolation_changed() return _signal_null; } -sigc::signal<void>& SimpleFilterModifier::signal_blend_changed() +sigc::signal<void> &SimpleFilterModifier::signal_blend_changed() { if (_notify) { return _signal_blend_changed; @@ -119,13 +117,13 @@ sigc::signal<void>& SimpleFilterModifier::signal_blend_changed() return _signal_null; } -sigc::signal<void>& SimpleFilterModifier::signal_blur_changed() +sigc::signal<void> &SimpleFilterModifier::signal_blur_changed() { // we dont use notifi to block use aberaje for multiple return _signal_blur_changed; } -sigc::signal<void>& SimpleFilterModifier::signal_opacity_changed() +sigc::signal<void> &SimpleFilterModifier::signal_opacity_changed() { // we dont use notifi to block use averaje for multiple return _signal_opacity_changed; @@ -178,9 +176,9 @@ void SimpleFilterModifier::set_opacity_value(const double val) _opacity.set_value(val); } -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/widget/filter-effect-chooser.h b/src/ui/widget/filter-effect-chooser.h index cbbe2b54e7d666c7fb2dae34865c84155c453120..7a6ba8aedd0457444b228a0985247fbb794b7da5 100644 --- a/src/ui/widget/filter-effect-chooser.h +++ b/src/ui/widget/filter-effect-chooser.h @@ -33,30 +33,37 @@ namespace Widget { /* Allows basic control over feBlend and feGaussianBlur effects as well as opacity. * Common for Object, Layers, and Fill and Stroke dialogs. -*/ + */ class SimpleFilterModifier : public Gtk::VBox { public: - enum Flags { NONE = 0, BLUR = 1, OPACITY = 2, BLEND = 4, ISOLATION = 16 }; + enum Flags + { + NONE = 0, + BLUR = 1, + OPACITY = 2, + BLEND = 4, + ISOLATION = 16 + }; - SimpleFilterModifier(int flags); + SimpleFilterModifier(int flags); - sigc::signal<void> &signal_blend_changed(); - sigc::signal<void> &signal_blur_changed(); - sigc::signal<void> &signal_opacity_changed(); - sigc::signal<void> &signal_isolation_changed(); + sigc::signal<void> &signal_blend_changed(); + sigc::signal<void> &signal_blur_changed(); + sigc::signal<void> &signal_opacity_changed(); + sigc::signal<void> &signal_isolation_changed(); - SPIsolation get_isolation_mode(); - void set_isolation_mode(const SPIsolation, bool notify); + SPIsolation get_isolation_mode(); + void set_isolation_mode(const SPIsolation, bool notify); - SPBlendMode get_blend_mode(); - void set_blend_mode(const SPBlendMode, bool notify); + SPBlendMode get_blend_mode(); + void set_blend_mode(const SPBlendMode, bool notify); - double get_blur_value() const; - void set_blur_value(const double); + double get_blur_value() const; + void set_blur_value(const double); - double get_opacity_value() const; - void set_opacity_value(const double); + double get_opacity_value() const; + void set_opacity_value(const double); private: int _flags; @@ -77,9 +84,9 @@ private: sigc::signal<void> _signal_isolation_changed; }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/widget/font-button.cpp b/src/ui/widget/font-button.cpp index e0a140aeaf0f61ca6ae85e296228f4bf372f495c..95607cadf11f1a92982d8e232383a489b112ee2e 100644 --- a/src/ui/widget/font-button.cpp +++ b/src/ui/widget/font-button.cpp @@ -7,41 +7,35 @@ #include "font-button.h" #include <glibmm/i18n.h> - #include <gtkmm/fontbutton.h> namespace Inkscape { namespace UI { namespace Widget { -FontButton::FontButton(Glib::ustring const &label, Glib::ustring const &tooltip, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) - : Labelled(label, tooltip, new Gtk::FontButton("Sans 10"), suffix, icon, mnemonic) -{ -} +FontButton::FontButton(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix, + Glib::ustring const &icon, bool mnemonic) + : Labelled(label, tooltip, new Gtk::FontButton("Sans 10"), suffix, icon, mnemonic) +{} Glib::ustring FontButton::getValue() const { g_assert(_widget != nullptr); - return static_cast<Gtk::FontButton*>(_widget)->get_font_name(); + return static_cast<Gtk::FontButton *>(_widget)->get_font_name(); } - -void FontButton::setValue (Glib::ustring fontspec) +void FontButton::setValue(Glib::ustring fontspec) { g_assert(_widget != nullptr); - static_cast<Gtk::FontButton*>(_widget)->set_font_name(fontspec); + static_cast<Gtk::FontButton *>(_widget)->set_font_name(fontspec); } Glib::SignalProxy0<void> FontButton::signal_font_value_changed() { g_assert(_widget != nullptr); - return static_cast<Gtk::FontButton*>(_widget)->signal_font_set(); + return static_cast<Gtk::FontButton *>(_widget)->signal_font_set(); } - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/font-button.h b/src/ui/widget/font-button.h index a53b7d6f16d6a31c21363a918905f2972d0e927b..4e950f11cb8b7565ead1cd13b7b16a701c61cc37 100644 --- a/src/ui/widget/font-button.h +++ b/src/ui/widget/font-button.h @@ -31,17 +31,14 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to false). */ - FontButton( Glib::ustring const &label, - Glib::ustring const &tooltip, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + FontButton(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix = "", + Glib::ustring const &icon = "", bool mnemonic = true); Glib::ustring getValue() const; - void setValue (Glib::ustring fontspec); + void setValue(Glib::ustring fontspec); /** - * Signal raised when the font button's value changes. - */ + * Signal raised when the font button's value changes. + */ Glib::SignalProxy0<void> signal_font_value_changed(); }; diff --git a/src/ui/widget/font-selector-toolbar.cpp b/src/ui/widget/font-selector-toolbar.cpp index 68c5e790059bc023f546f71c5de169aa1ce8aeac..796d2b0bfb6b3c525b585bb0a1c0e81678dc63fe 100644 --- a/src/ui/widget/font-selector-toolbar.cpp +++ b/src/ui/widget/font-selector-toolbar.cpp @@ -8,20 +8,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "font-selector-toolbar.h" + +#include <gdkmm/display.h> #include <glibmm/i18n.h> #include <glibmm/regex.h> -#include <gdkmm/display.h> -#include "font-selector-toolbar.h" - -#include "libnrtype/font-lister.h" #include "libnrtype/font-instance.h" - +#include "libnrtype/font-lister.h" #include "ui/icon-names.h" // For updating from selection -#include "inkscape.h" #include "desktop.h" +#include "inkscape.h" #include "object/sp-text.h" // TEMP TEMP TEMP @@ -34,66 +33,65 @@ * * Change the setToolboxFocusTo() argument in tools/text-tool to point to that widget name */ -void family_cell_data_func(const Gtk::TreeModel::const_iterator iter, Gtk::CellRendererText* cell ) { - - Inkscape::FontLister* font_lister = Inkscape::FontLister::get_instance(); +void family_cell_data_func(const Gtk::TreeModel::const_iterator iter, Gtk::CellRendererText *cell) +{ + Inkscape::FontLister *font_lister = Inkscape::FontLister::get_instance(); Glib::ustring markup = font_lister->get_font_family_markup(iter); // std::cout << "Markup: " << markup << std::endl; - cell->set_property ("markup", markup); + cell->set_property("markup", markup); } namespace Inkscape { namespace UI { namespace Widget { -FontSelectorToolbar::FontSelectorToolbar () - : Gtk::Grid () - , family_combo (true) // true => with text entry. - , style_combo (true) - , signal_block (false) +FontSelectorToolbar::FontSelectorToolbar() + : Gtk::Grid() + , family_combo(true) // true => with text entry. + , style_combo(true) + , signal_block(false) { - - Inkscape::FontLister* font_lister = Inkscape::FontLister::get_instance(); + Inkscape::FontLister *font_lister = Inkscape::FontLister::get_instance(); // Font family - family_combo.set_model (font_lister->get_font_list()); - family_combo.set_entry_text_column (0); - family_combo.set_name ("FontSelectorToolBar: Family"); - family_combo.set_row_separator_func (&font_lister_separator_func); + family_combo.set_model(font_lister->get_font_list()); + family_combo.set_entry_text_column(0); + family_combo.set_name("FontSelectorToolBar: Family"); + family_combo.set_row_separator_func(&font_lister_separator_func); family_combo.clear(); // Clears all CellRenderer mappings. - family_combo.set_cell_data_func (family_cell, - sigc::bind(sigc::ptr_fun(family_cell_data_func), &family_cell)); - family_combo.pack_start (family_cell); - + family_combo.set_cell_data_func(family_cell, sigc::bind(sigc::ptr_fun(family_cell_data_func), &family_cell)); + family_combo.pack_start(family_cell); - Gtk::Entry* entry = family_combo.get_entry(); - entry->signal_icon_press().connect (sigc::mem_fun(*this, &FontSelectorToolbar::on_icon_pressed)); - entry->signal_key_press_event().connect (sigc::mem_fun(*this, &FontSelectorToolbar::on_key_press_event), false); // false => connect first + Gtk::Entry *entry = family_combo.get_entry(); + entry->signal_icon_press().connect(sigc::mem_fun(*this, &FontSelectorToolbar::on_icon_pressed)); + entry->signal_key_press_event().connect(sigc::mem_fun(*this, &FontSelectorToolbar::on_key_press_event), + false); // false => connect first Glib::RefPtr<Gtk::EntryCompletion> completion = Gtk::EntryCompletion::create(); - completion->set_model (font_lister->get_font_list()); - completion->set_text_column (0); - completion->set_popup_completion (); - completion->set_inline_completion (false); - completion->set_inline_selection (); - // completion->signal_match_selected().connect(sigc::mem_fun(*this, &FontSelectorToolbar::on_match_selected), false); // false => connect before default handler. - entry->set_completion (completion); + completion->set_model(font_lister->get_font_list()); + completion->set_text_column(0); + completion->set_popup_completion(); + completion->set_inline_completion(false); + completion->set_inline_selection(); + // completion->signal_match_selected().connect(sigc::mem_fun(*this, &FontSelectorToolbar::on_match_selected), + // false); // false => connect before default handler. + entry->set_completion(completion); // Style - style_combo.set_model (font_lister->get_style_list()); - style_combo.set_name ("FontSelectorToolbar: Style"); + style_combo.set_model(font_lister->get_style_list()); + style_combo.set_name("FontSelectorToolbar: Style"); // Grid - set_name ("FontSelectorToolbar: Grid"); - attach (family_combo, 0, 0, 1, 1); - attach (style_combo, 1, 0, 1, 1); + set_name("FontSelectorToolbar: Grid"); + attach(family_combo, 0, 0, 1, 1); + attach(style_combo, 1, 0, 1, 1); // Add signals - family_combo.signal_changed().connect (sigc::mem_fun(*this, &FontSelectorToolbar::on_family_changed)); - style_combo.signal_changed().connect (sigc::mem_fun(*this, &FontSelectorToolbar::on_style_changed)); - + family_combo.signal_changed().connect(sigc::mem_fun(*this, &FontSelectorToolbar::on_family_changed)); + style_combo.signal_changed().connect(sigc::mem_fun(*this, &FontSelectorToolbar::on_style_changed)); + show_all_children(); // Initialize font family lists. (May already be done.) Should be done on document change. @@ -103,22 +101,21 @@ FontSelectorToolbar::FontSelectorToolbar () font_lister->connectUpdate(sigc::mem_fun(*this, &FontSelectorToolbar::update_font)); } - // Update GUI based on font-selector values. -void -FontSelectorToolbar::update_font () +void FontSelectorToolbar::update_font() { - if (signal_block) return; + if (signal_block) + return; signal_block = true; - Inkscape::FontLister* font_lister = Inkscape::FontLister::get_instance(); + Inkscape::FontLister *font_lister = Inkscape::FontLister::get_instance(); Gtk::TreeModel::Row row; // Set font family. try { - row = font_lister->get_row_for_font (); - family_combo.set_active (row); + row = font_lister->get_row_for_font(); + family_combo.set_active(row); } catch (...) { std::cerr << "FontSelectorToolbar::update_font: Couldn't find row for family: " << font_lister->get_font_family() << std::endl; @@ -126,27 +123,27 @@ FontSelectorToolbar::update_font () // Set style. try { - row = font_lister->get_row_for_style (); - style_combo.set_active (row); + row = font_lister->get_row_for_style(); + style_combo.set_active(row); } catch (...) { - std::cerr << "FontSelectorToolbar::update_font: Couldn't find row for style: " - << font_lister->get_font_style() << std::endl; + std::cerr << "FontSelectorToolbar::update_font: Couldn't find row for style: " << font_lister->get_font_style() + << std::endl; } // Check for missing fonts. Glib::ustring missing_fonts = get_missing_fonts(); // Add an icon to end of entry. - Gtk::Entry* entry = family_combo.get_entry(); + Gtk::Entry *entry = family_combo.get_entry(); if (missing_fonts.empty()) { // If no missing fonts, add icon for selecting all objects with this font-family. - entry->set_icon_from_icon_name (INKSCAPE_ICON("edit-select-all"), Gtk::ENTRY_ICON_SECONDARY); - entry->set_icon_tooltip_text (_("Select all text with this text family"), Gtk::ENTRY_ICON_SECONDARY); + entry->set_icon_from_icon_name(INKSCAPE_ICON("edit-select-all"), Gtk::ENTRY_ICON_SECONDARY); + entry->set_icon_tooltip_text(_("Select all text with this text family"), Gtk::ENTRY_ICON_SECONDARY); } else { // If missing fonts, add warning icon. - Glib::ustring warning = _("Font not found on system: ") + missing_fonts; - entry->set_icon_from_icon_name (INKSCAPE_ICON("dialog-warning"), Gtk::ENTRY_ICON_SECONDARY); - entry->set_icon_tooltip_text (warning, Gtk::ENTRY_ICON_SECONDARY); + Glib::ustring warning = _("Font not found on system: ") + missing_fonts; + entry->set_icon_from_icon_name(INKSCAPE_ICON("dialog-warning"), Gtk::ENTRY_ICON_SECONDARY); + entry->set_icon_tooltip_text(warning, Gtk::ENTRY_ICON_SECONDARY); } signal_block = false; @@ -154,23 +151,22 @@ FontSelectorToolbar::update_font () // Get comma separated list of fonts in font-family that are not on system. // To do, move to font-lister. -Glib::ustring -FontSelectorToolbar::get_missing_fonts () +Glib::ustring FontSelectorToolbar::get_missing_fonts() { // Get font list in text entry which may be a font stack (with fallbacks). Glib::ustring font_list = family_combo.get_entry_text(); Glib::ustring missing_font_list; - Inkscape::FontLister* font_lister = Inkscape::FontLister::get_instance(); + Inkscape::FontLister *font_lister = Inkscape::FontLister::get_instance(); std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s*,\\s*", font_list); - for (auto token: tokens) { + for (auto token : tokens) { bool found = false; Gtk::TreeModel::Children children = font_lister->get_font_list()->children(); - for (auto iter2: children) { + for (auto iter2 : children) { Gtk::TreeModel::Row row2 = *iter2; Glib::ustring family2 = row2[font_lister->FontList.family]; - bool onSystem2 = row2[font_lister->FontList.onSystem]; + bool onSystem2 = row2[font_lister->FontList.onSystem]; // CSS dictates that font family names are case insensitive. // This should really implement full Unicode case unfolding. if (onSystem2 && token.casefold().compare(family2.casefold()) == 0) { @@ -193,20 +189,19 @@ FontSelectorToolbar::get_missing_fonts () return missing_font_list; } - // Callbacks // Need to update style list -void -FontSelectorToolbar::on_family_changed() { - - if (signal_block) return; +void FontSelectorToolbar::on_family_changed() +{ + if (signal_block) + return; signal_block = true; Glib::ustring family = family_combo.get_entry_text(); Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); - fontlister->set_font_family (family); + fontlister->set_font_family(family); signal_block = false; @@ -214,16 +209,16 @@ FontSelectorToolbar::on_family_changed() { changed_emit(); } -void -FontSelectorToolbar::on_style_changed() { - - if (signal_block) return; +void FontSelectorToolbar::on_style_changed() +{ + if (signal_block) + return; signal_block = true; Glib::ustring style = style_combo.get_entry_text(); Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); - fontlister->set_font_style (style); + fontlister->set_font_style(style); signal_block = false; @@ -231,8 +226,8 @@ FontSelectorToolbar::on_style_changed() { changed_emit(); } -void -FontSelectorToolbar::on_icon_pressed (Gtk::EntryIconPosition icon_position, const GdkEventButton* event) { +void FontSelectorToolbar::on_icon_pressed(Gtk::EntryIconPosition icon_position, const GdkEventButton *event) +{ std::cout << "FontSelectorToolbar::on_entry_icon_pressed" << std::endl; std::cout << " .... Should select all items with same font-family. FIXME" << std::endl; // Call equivalent of sp_text_toolbox_select_cb() in text-toolbar.cpp @@ -252,37 +247,31 @@ FontSelectorToolbar::on_icon_pressed (Gtk::EntryIconPosition icon_position, cons // } // Return focus to canvas. -bool -FontSelectorToolbar::on_key_press_event (GdkEventKey* key_event) +bool FontSelectorToolbar::on_key_press_event(GdkEventKey *key_event) { bool consumed = false; unsigned int key = 0; - gdk_keymap_translate_keyboard_state( Gdk::Display::get_default()->get_keymap(), - key_event->hardware_keycode, - (GdkModifierType)key_event->state, - 0, &key, nullptr, nullptr, nullptr ); - - switch ( key ) { + gdk_keymap_translate_keyboard_state(Gdk::Display::get_default()->get_keymap(), key_event->hardware_keycode, + (GdkModifierType)key_event->state, 0, &key, nullptr, nullptr, nullptr); + switch (key) { case GDK_KEY_Escape: case GDK_KEY_Return: - case GDK_KEY_KP_Enter: - { + case GDK_KEY_KP_Enter: { // Defocus std::cerr << "FontSelectorToolbar::on_key_press_event: Defocus: FIXME" << std::endl; consumed = true; - } - break; + } break; } return consumed; // Leave it to default handler if false. } -void -FontSelectorToolbar::changed_emit() { +void FontSelectorToolbar::changed_emit() +{ signal_block = true; - changed_signal.emit (); + changed_signal.emit(); signal_block = false; } diff --git a/src/ui/widget/font-selector-toolbar.h b/src/ui/widget/font-selector-toolbar.h index 53cdcea56892c0b93572945322a3a8d32c08cbfc..f0656bc2b213bd2547839cf5788b9099bf455721 100644 --- a/src/ui/widget/font-selector-toolbar.h +++ b/src/ui/widget/font-selector-toolbar.h @@ -26,9 +26,9 @@ #ifndef INKSCAPE_UI_WIDGET_FONT_SELECTOR_TOOLBAR_H #define INKSCAPE_UI_WIDGET_FONT_SELECTOR_TOOLBAR_H +#include <gtkmm/comboboxtext.h> #include <gtkmm/grid.h> #include <gtkmm/treeview.h> -#include <gtkmm/comboboxtext.h> namespace Inkscape { namespace UI { @@ -51,35 +51,31 @@ namespace Widget { */ class FontSelectorToolbar : public Gtk::Grid { - public: - /** * Constructor */ - FontSelectorToolbar (); + FontSelectorToolbar(); protected: - // Font family - Gtk::ComboBox family_combo; + Gtk::ComboBox family_combo; Gtk::CellRendererText family_cell; // Font style - Gtk::ComboBoxText style_combo; + Gtk::ComboBoxText style_combo; Gtk::CellRendererText style_cell; private: - // Make a list of missing fonts for tooltip and for warning icon. - Glib::ustring get_missing_fonts (); + Glib::ustring get_missing_fonts(); // Signal handlers void on_family_changed(); void on_style_changed(); - void on_icon_pressed (Gtk::EntryIconPosition icon_position, const GdkEventButton* event); + void on_icon_pressed(Gtk::EntryIconPosition icon_position, const GdkEventButton *event); // bool on_match_selected (const Gtk::TreeModel::iterator& iter); - bool on_key_press_event (GdkEventKey* key_event) override; + bool on_key_press_event(GdkEventKey *key_event) override; // Signals sigc::signal<void> changed_signal; @@ -87,21 +83,17 @@ private: bool signal_block; public: - /** * Update GUI based on font-selector values. */ - void update_font (); + void update_font(); /** * Let others know that user has changed GUI settings. */ - sigc::connection connectChanged(sigc::slot<void> slot) { - return changed_signal.connect(slot); - } + sigc::connection connectChanged(sigc::slot<void> slot) { return changed_signal.connect(slot); } }; - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/font-selector.cpp b/src/ui/widget/font-selector.cpp index df13fa3905ab82add44b02b910621d3f98ab49fb..90d61e4a6aa98375a22bbcc6a56c6f05884d0ce3 100644 --- a/src/ui/widget/font-selector.cpp +++ b/src/ui/widget/font-selector.cpp @@ -8,100 +8,99 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "font-selector.h" + #include <glibmm/i18n.h> #include <glibmm/markup.h> -#include "font-selector.h" - -#include "libnrtype/font-lister.h" #include "libnrtype/font-instance.h" +#include "libnrtype/font-lister.h" // For updating from selection -#include "inkscape.h" #include "desktop.h" +#include "inkscape.h" #include "object/sp-text.h" namespace Inkscape { namespace UI { namespace Widget { -FontSelector::FontSelector (bool with_size, bool with_variations) - : Gtk::Grid () - , family_frame (_("Font family")) - , style_frame (C_("Font selector", "Style")) - , size_label (_("Font size")) - , size_combobox (true) // With entry - , signal_block (false) - , font_size (18) +FontSelector::FontSelector(bool with_size, bool with_variations) + : Gtk::Grid() + , family_frame(_("Font family")) + , style_frame(C_("Font selector", "Style")) + , size_label(_("Font size")) + , size_combobox(true) // With entry + , signal_block(false) + , font_size(18) { - - Inkscape::FontLister* font_lister = Inkscape::FontLister::get_instance(); + Inkscape::FontLister *font_lister = Inkscape::FontLister::get_instance(); // Font family - family_treecolumn.pack_start (family_cell, false); - family_treecolumn.set_fixed_width (200); - family_treecolumn.add_attribute (family_cell, "text", 0); - family_treecolumn.set_cell_data_func (family_cell, &font_lister_cell_data_func); + family_treecolumn.pack_start(family_cell, false); + family_treecolumn.set_fixed_width(200); + family_treecolumn.add_attribute(family_cell, "text", 0); + family_treecolumn.set_cell_data_func(family_cell, &font_lister_cell_data_func); - family_treeview.set_row_separator_func (&font_lister_separator_func); - family_treeview.set_model (font_lister->get_font_list()); - family_treeview.set_name ("FontSelector: Family"); - family_treeview.set_headers_visible (false); - family_treeview.append_column (family_treecolumn); + family_treeview.set_row_separator_func(&font_lister_separator_func); + family_treeview.set_model(font_lister->get_font_list()); + family_treeview.set_name("FontSelector: Family"); + family_treeview.set_headers_visible(false); + family_treeview.append_column(family_treecolumn); - family_scroll.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); - family_scroll.add (family_treeview); + family_scroll.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); + family_scroll.add(family_treeview); - family_frame.set_hexpand (true); - family_frame.set_vexpand (true); - family_frame.add (family_scroll); + family_frame.set_hexpand(true); + family_frame.set_vexpand(true); + family_frame.add(family_scroll); // Style - style_treecolumn.pack_start (style_cell, false); - style_treecolumn.add_attribute (style_cell, "text", 0); - style_treecolumn.set_cell_data_func (style_cell, sigc::mem_fun(*this, &FontSelector::style_cell_data_func)); - style_treecolumn.set_title ("Face"); - style_treecolumn.set_resizable (true); + style_treecolumn.pack_start(style_cell, false); + style_treecolumn.add_attribute(style_cell, "text", 0); + style_treecolumn.set_cell_data_func(style_cell, sigc::mem_fun(*this, &FontSelector::style_cell_data_func)); + style_treecolumn.set_title("Face"); + style_treecolumn.set_resizable(true); - style_treeview.set_model (font_lister->get_style_list()); - style_treeview.set_name ("FontSelectorStyle"); - style_treeview.append_column ("CSS", font_lister->FontStyleList.cssStyle); - style_treeview.append_column (style_treecolumn); + style_treeview.set_model(font_lister->get_style_list()); + style_treeview.set_name("FontSelectorStyle"); + style_treeview.append_column("CSS", font_lister->FontStyleList.cssStyle); + style_treeview.append_column(style_treecolumn); - style_treeview.get_column(0)->set_resizable (true); + style_treeview.get_column(0)->set_resizable(true); - style_scroll.set_policy (Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); - style_scroll.add (style_treeview); + style_scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); + style_scroll.add(style_treeview); - style_frame.set_hexpand (true); - style_frame.set_vexpand (true); - style_frame.add (style_scroll); + style_frame.set_hexpand(true); + style_frame.set_vexpand(true); + style_frame.add(style_scroll); // Size - size_combobox.set_name ("FontSelectorSize"); + size_combobox.set_name("FontSelectorSize"); set_sizes(); - size_combobox.set_active_text( "18" ); + size_combobox.set_active_text("18"); // Font Variations - font_variations.set_vexpand (true); - font_variations_scroll.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); - font_variations_scroll.add (font_variations); + font_variations.set_vexpand(true); + font_variations_scroll.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); + font_variations_scroll.add(font_variations); // Grid - set_name ("FontSelectorGrid"); + set_name("FontSelectorGrid"); set_row_spacing(4); set_column_spacing(4); // Add extra columns to the "family frame" to change space distribution // by prioritizing font family over styles const int extra = 4; - attach (family_frame, 0, 0, 1 + extra, 2); - attach (style_frame, 1 + extra, 0, 2, 1); + attach(family_frame, 0, 0, 1 + extra, 2); + attach(style_frame, 1 + extra, 0, 2, 1); if (with_size) { // Glyph panel does not use size. - attach (size_label, 1 + extra, 1, 1, 1); - attach (size_combobox, 2 + extra, 1, 1, 1); + attach(size_label, 1 + extra, 1, 1, 1); + attach(size_combobox, 2 + extra, 1, 1, 1); } if (with_variations) { // Glyphs panel does not use variations. - attach (font_variations_scroll, 0, 2, 3 + extra, 1); + attach(font_variations_scroll, 0, 2, 3 + extra, 1); } // Add signals @@ -116,59 +115,51 @@ FontSelector::FontSelector (bool with_size, bool with_variations) font_lister->update_font_list(SP_ACTIVE_DESKTOP->getDocument()); } -void -FontSelector::set_sizes () +void FontSelector::set_sizes() { size_combobox.remove_all(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int unit = prefs->getInt("/options/font/unitType", SP_CSS_UNIT_PT); - int sizes[] = { - 4, 6, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 28, - 32, 36, 40, 48, 56, 64, 72, 144 - }; + int sizes[] = {4, 6, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 48, 56, 64, 72, 144}; // Array must be same length as SPCSSUnit in style-internal.h // PX PT PC MM CM IN EM EX % - double ratios[] = {1, 1, 1, 10, 4, 40, 100, 16, 8, 0.16}; + double ratios[] = {1, 1, 1, 10, 4, 40, 100, 16, 8, 0.16}; - for (int i : sizes) - { - double size = i/ratios[unit]; - size_combobox.append( Glib::ustring::format(size) ); + for (int i : sizes) { + double size = i / ratios[unit]; + size_combobox.append(Glib::ustring::format(size)); } } -void -FontSelector::set_fontsize_tooltip() +void FontSelector::set_fontsize_tooltip() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int unit = prefs->getInt("/options/font/unitType", SP_CSS_UNIT_PT); Glib::ustring tooltip = Glib::ustring::format(_("Font size"), " (", sp_style_get_css_unit_string(unit), ")"); - size_combobox.set_tooltip_text (tooltip); + size_combobox.set_tooltip_text(tooltip); } // Update GUI. // We keep a private copy of the style list as the font-family in widget is only temporary // until the "Apply" button is set so the style list can be different from that in // FontLister. -void -FontSelector::update_font () +void FontSelector::update_font() { signal_block = true; Inkscape::FontLister *font_lister = Inkscape::FontLister::get_instance(); Gtk::TreePath path; Glib::ustring family = font_lister->get_font_family(); - Glib::ustring style = font_lister->get_font_style(); + Glib::ustring style = font_lister->get_font_style(); // Set font family try { - path = font_lister->get_row_for_font (family); + path = font_lister->get_row_for_font(family); } catch (...) { - std::cerr << "FontSelector::update_font: Couldn't find row for font-family: " - << family << std::endl; + std::cerr << "FontSelector::update_font: Couldn't find row for font-family: " << family << std::endl; path.clear(); path.push_back(0); } @@ -177,12 +168,12 @@ FontSelector::update_font () Gtk::TreeViewColumn *currentColumn; family_treeview.get_cursor(currentPath, currentColumn); if (currentPath.empty() || !font_lister->is_path_for_font(currentPath, family)) { - family_treeview.set_cursor (path); - family_treeview.scroll_to_row (path); + family_treeview.set_cursor(path); + family_treeview.scroll_to_row(path); } // Get font-lister style list for selected family - Gtk::TreeModel::Row row = *(family_treeview.get_model()->get_iter (path)); + Gtk::TreeModel::Row row = *(family_treeview.get_model()->get_iter(path)); GList *styles; row.get_value(1, styles); @@ -190,19 +181,19 @@ FontSelector::update_font () Gtk::TreeModel::iterator match; FontLister::FontStyleListClass FontStyleList; Glib::RefPtr<Gtk::ListStore> local_style_list_store = Gtk::ListStore::create(FontStyleList); - for ( ; styles; styles = styles->next ) { + for (; styles; styles = styles->next) { Gtk::TreeModel::iterator treeModelIter = local_style_list_store->append(); (*treeModelIter)[FontStyleList.cssStyle] = ((StyleNames *)styles->data)->CssName; (*treeModelIter)[FontStyleList.displayStyle] = ((StyleNames *)styles->data)->DisplayName; - if (style == ((StyleNames*)styles->data)->CssName) { + if (style == ((StyleNames *)styles->data)->CssName) { match = treeModelIter; } } // Attach store to tree view and select row. - style_treeview.set_model (local_style_list_store); + style_treeview.set_model(local_style_list_store); if (match) { - style_treeview.get_selection()->select (match); + style_treeview.get_selection()->select(match); } Glib::ustring fontspec = font_lister->get_fontspec(); @@ -211,30 +202,27 @@ FontSelector::update_font () signal_block = false; } -void -FontSelector::update_size (double size) +void FontSelector::update_size(double size) { signal_block = true; // Set font size std::stringstream ss; ss << size; - size_combobox.get_entry()->set_text( ss.str() ); + size_combobox.get_entry()->set_text(ss.str()); font_size = size; // Store value set_fontsize_tooltip(); signal_block = false; } - // If use_variations is true (default), we get variation values from variations widget otherwise we // get values from CSS widget (we need to be able to keep the two widgets synchronized both ways). -Glib::ustring -FontSelector::get_fontspec(bool use_variations) { - +Glib::ustring FontSelector::get_fontspec(bool use_variations) +{ // Build new fontspec from GUI settings - Glib::ustring family = "Sans"; // Default...family list may not have been constructed. - Gtk::TreeModel::iterator iter = family_treeview.get_selection()->get_selected(); + Glib::ustring family = "Sans"; // Default...family list may not have been constructed. + Gtk::TreeModel::iterator iter = family_treeview.get_selection()->get_selected(); if (iter) { (*iter).get_value(0, family); } @@ -259,7 +247,7 @@ FontSelector::get_fontspec(bool use_variations) { // Clip any font_variation data in 'style' as we'll replace it. auto pos = style.find('@'); if (pos != Glib::ustring::npos) { - style.erase (pos, style.length()-1); + style.erase(pos, style.length() - 1); } Glib::ustring variations = font_variations.get_pango_string(); @@ -276,11 +264,10 @@ FontSelector::get_fontspec(bool use_variations) { return fontspec; } -void -FontSelector::style_cell_data_func (Gtk::CellRenderer *renderer, Gtk::TreeIter const &iter) +void FontSelector::style_cell_data_func(Gtk::CellRenderer *renderer, Gtk::TreeIter const &iter) { - Glib::ustring family = "Sans"; // Default...family list may not have been constructed. - Gtk::TreeModel::iterator iter_family = family_treeview.get_selection()->get_selected(); + Glib::ustring family = "Sans"; // Default...family list may not have been constructed. + Gtk::TreeModel::iterator iter_family = family_treeview.get_selection()->get_selected(); if (iter_family) { (*iter_family).get_value(0, family); } @@ -288,8 +275,8 @@ FontSelector::style_cell_data_func (Gtk::CellRenderer *renderer, Gtk::TreeIter c Glib::ustring style = "Normal"; (*iter).get_value(1, style); - Glib::ustring style_escaped = Glib::Markup::escape_text( style ); - Glib::ustring font_desc = Glib::Markup::escape_text( family + ", " + style ); + Glib::ustring style_escaped = Glib::Markup::escape_text(style); + Glib::ustring font_desc = Glib::Markup::escape_text(family + ", " + style); Glib::ustring markup; markup = "<span font='" + font_desc + "'>" + style_escaped + "</span>"; @@ -298,15 +285,14 @@ FontSelector::style_cell_data_func (Gtk::CellRenderer *renderer, Gtk::TreeIter c renderer->set_property("markup", markup); } - // Callbacks // Need to update style list -void -FontSelector::on_family_changed() { - - if (signal_block) return; +void FontSelector::on_family_changed() +{ + if (signal_block) + return; signal_block = true; Glib::RefPtr<Gtk::TreeModel> model; @@ -321,7 +307,7 @@ FontSelector::on_family_changed() { Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); fontlister->ensureRowStyles(model, iter); - Gtk::TreeModel::Row row = *iter; + Gtk::TreeModel::Row row = *iter; // Get family name Glib::ustring family; @@ -333,29 +319,29 @@ FontSelector::on_family_changed() { // Find best style match for selected family with current style (e.g. of selected text). Glib::ustring style = fontlister->get_font_style(); - Glib::ustring best = fontlister->get_best_style_match (family, style); + Glib::ustring best = fontlister->get_best_style_match(family, style); // Create are own store of styles for selected font-family (the font-family selected // in the dialog may not be the same as stored in the font-lister class until the // "Apply" button is triggered). Gtk::TreeModel::iterator it_best; FontLister::FontStyleListClass FontStyleList; - Glib::RefPtr<Gtk::ListStore> local_style_list_store = Gtk::ListStore::create(FontStyleList); + Glib::RefPtr<Gtk::ListStore> local_style_list_store = Gtk::ListStore::create(FontStyleList); // Build list and find best match. - for ( ; styles; styles = styles->next ) { + for (; styles; styles = styles->next) { Gtk::TreeModel::iterator treeModelIter = local_style_list_store->append(); (*treeModelIter)[FontStyleList.cssStyle] = ((StyleNames *)styles->data)->CssName; (*treeModelIter)[FontStyleList.displayStyle] = ((StyleNames *)styles->data)->DisplayName; - if (best == ((StyleNames*)styles->data)->CssName) { + if (best == ((StyleNames *)styles->data)->CssName) { it_best = treeModelIter; } } // Attach store to tree view and select row. - style_treeview.set_model (local_style_list_store); + style_treeview.set_model(local_style_list_store); if (it_best) { - style_treeview.get_selection()->select (it_best); + style_treeview.get_selection()->select(it_best); } signal_block = false; @@ -364,13 +350,14 @@ FontSelector::on_family_changed() { changed_emit(); } -void -FontSelector::on_style_changed() { - if (signal_block) return; +void FontSelector::on_style_changed() +{ + if (signal_block) + return; // Update variations widget if new style selected from style widget. signal_block = true; - Glib::ustring fontspec = get_fontspec( false ); + Glib::ustring fontspec = get_fontspec(false); update_variations(fontspec); signal_block = false; @@ -378,24 +365,23 @@ FontSelector::on_style_changed() { changed_emit(); } -void -FontSelector::on_size_changed() { - - if (signal_block) return; +void FontSelector::on_size_changed() +{ + if (signal_block) + return; double size; Glib::ustring input = size_combobox.get_active_text(); try { - size = std::stod (input); - } - catch (std::invalid_argument) { + size = std::stod(input); + } catch (std::invalid_argument) { std::cerr << "FontSelector::on_size_changed: Invalid input: " << input << std::endl; size = -1; } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); // Arbitrary: Text and Font preview freezes with huge font sizes. - int max_size = prefs->getInt("/dialogs/textandfont/maxFontSize", 10000); + int max_size = prefs->getInt("/dialogs/textandfont/maxFontSize", 10000); if (size <= 0) { return; @@ -410,23 +396,24 @@ FontSelector::on_size_changed() { } } -void -FontSelector::on_variations_changed() { - - if (signal_block) return; +void FontSelector::on_variations_changed() +{ + if (signal_block) + return; // Let world know changed_emit(); } -void -FontSelector::changed_emit() { +void FontSelector::changed_emit() +{ signal_block = true; - signal_changed.emit (get_fontspec()); + signal_changed.emit(get_fontspec()); signal_block = false; } -void FontSelector::update_variations(const Glib::ustring& fontspec) { +void FontSelector::update_variations(const Glib::ustring &fontspec) +{ font_variations.update(fontspec); // Check if there are any variations available; if not, don't expand font_variations_scroll diff --git a/src/ui/widget/font-selector.h b/src/ui/widget/font-selector.h index 137d4116bb95644fb7205cc90142cfcabce145ae..04330ae7f6f865f839b59c998e5ddef037874063 100644 --- a/src/ui/widget/font-selector.h +++ b/src/ui/widget/font-selector.h @@ -29,12 +29,12 @@ #ifndef INKSCAPE_UI_WIDGET_FONT_SELECTOR_H #define INKSCAPE_UI_WIDGET_FONT_SELECTOR_H -#include <gtkmm/grid.h> +#include <gtkmm/comboboxtext.h> #include <gtkmm/frame.h> +#include <gtkmm/grid.h> +#include <gtkmm/label.h> #include <gtkmm/scrolledwindow.h> #include <gtkmm/treeview.h> -#include <gtkmm/label.h> -#include <gtkmm/comboboxtext.h> #include "ui/widget/font-variations.h" @@ -59,46 +59,42 @@ namespace Widget { */ class FontSelector : public Gtk::Grid { - public: - /** * Constructor */ - FontSelector (bool with_size = true, bool with_variations = true); + FontSelector(bool with_size = true, bool with_variations = true); protected: - // Font family - Gtk::Frame family_frame; + Gtk::Frame family_frame; Gtk::ScrolledWindow family_scroll; - Gtk::TreeView family_treeview; + Gtk::TreeView family_treeview; Gtk::TreeViewColumn family_treecolumn; Gtk::CellRendererText family_cell; // Font style - Gtk::Frame style_frame; + Gtk::Frame style_frame; Gtk::ScrolledWindow style_scroll; - Gtk::TreeView style_treeview; + Gtk::TreeView style_treeview; Gtk::TreeViewColumn style_treecolumn; Gtk::CellRendererText style_cell; // Font size - Gtk::Label size_label; - Gtk::ComboBoxText size_combobox; + Gtk::Label size_label; + Gtk::ComboBoxText size_combobox; // Font variations Gtk::ScrolledWindow font_variations_scroll; - FontVariations font_variations; + FontVariations font_variations; private: - // Set sizes in font size combobox. void set_sizes(); void set_fontsize_tooltip(); // Use font style when listing style names. - void style_cell_data_func (Gtk::CellRenderer *renderer, Gtk::TreeIter const &iter); + void style_cell_data_func(Gtk::CellRenderer *renderer, Gtk::TreeIter const &iter); // Signal handlers void on_family_changed(); @@ -115,15 +111,14 @@ private: double font_size; // control font variations update and UI element size - void update_variations(const Glib::ustring& fontspec); + void update_variations(const Glib::ustring &fontspec); public: - /** * Update GUI based on fontspec */ - void update_font (); - void update_size (double size); + void update_font(); + void update_size(double size); /** * Get fontspec based on current settings. (Does not handle size, yet.) @@ -139,12 +134,9 @@ public: * Let others know that user has changed GUI settings. * (Used to enable 'Apply' and 'Default' buttons.) */ - sigc::connection connectChanged(sigc::slot<void, Glib::ustring> slot) { - return signal_changed.connect(slot); - } + sigc::connection connectChanged(sigc::slot<void, Glib::ustring> slot) { return signal_changed.connect(slot); } }; - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/font-variants.cpp b/src/ui/widget/font-variants.cpp index 80e554a0dadb978867ca0d29eeb60cd3fc596ff4..3e20e5f73d3821303e4957aecdc924bd4f75e0e4 100644 --- a/src/ui/widget/font-variants.cpp +++ b/src/ui/widget/font-variants.cpp @@ -8,13 +8,12 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm.h> -#include <glibmm/i18n.h> +#include "font-variants.h" +#include <glibmm/i18n.h> +#include <gtkmm.h> #include <libnrtype/font-instance.h> -#include "font-variants.h" - // For updating from selection #include "desktop.h" #include "object/sp-text.h" @@ -23,226 +22,225 @@ namespace Inkscape { namespace UI { namespace Widget { - // A simple class to handle UI for one feature. We could of derived this from Gtk::HBox but by - // attaching widgets directly to Gtk::Grid, we keep columns lined up (which may or may not be a - // good thing). - class Feature - { - public: - Feature( const Glib::ustring& name, OTSubstitution& glyphs, int options, Glib::ustring family, Gtk::Grid& grid, int &row, FontVariants* parent) - : _name (name) - , _options (options) - { - Gtk::Label* table_name = Gtk::manage (new Gtk::Label()); - table_name->set_markup ("\"" + name + "\" "); - - grid.attach (*table_name, 0, row, 1, 1); - - Gtk::FlowBox* flow_box = nullptr; - Gtk::ScrolledWindow* scrolled_window = nullptr; - if (options > 2) { - // If there are more than 2 option, pack them into a flowbox instead of directly putting them in the grid. - // Some fonts might have a table with many options (Bungee Hairline table 'ornm' has 113 entries). - flow_box = Gtk::manage (new Gtk::FlowBox()); - flow_box->set_selection_mode(); // Turn off selection - flow_box->set_homogeneous(); - flow_box->set_max_children_per_line (100); // Override default value - flow_box->set_min_children_per_line (10); // Override default value - - // We pack this into a scrollbar... otherwise the minimum height is set to what is required to fit all - // flow box children into the flow box when the flow box has minimum width. (Crazy if you ask me!) - scrolled_window = Gtk::manage (new Gtk::ScrolledWindow()); - scrolled_window->set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); - scrolled_window->add(*flow_box); - } - - Gtk::RadioButton::Group group; - for (int i = 0; i < options; ++i) { - - // Create radio button and create or add to button group. - Gtk::RadioButton* button = Gtk::manage (new Gtk::RadioButton()); - if (i == 0) { - group = button->get_group(); - } else { - button->set_group (group); - } - button->signal_clicked().connect ( sigc::mem_fun(*parent, &FontVariants::feature_callback) ); - buttons.push_back (button); - - // Create label. - Gtk::Label* label = Gtk::manage (new Gtk::Label()); - - // Restrict label width (some fonts have lots of alternatives). - label->set_line_wrap( true ); - label->set_line_wrap_mode( Pango::WRAP_WORD_CHAR ); - label->set_ellipsize( Pango::ELLIPSIZE_END ); - label->set_lines(3); - label->set_hexpand(); - - Glib::ustring markup; - markup += "<span font_family='"; - markup += family; - markup += "' font_features='"; - markup += name; - markup += " "; - markup += std::to_string (i); - markup += "'>"; - markup += Glib::Markup::escape_text (glyphs.input); - markup += "</span>"; - label->set_markup (markup); - - // Add button and label to widget - if (!flow_box) { - // Attach directly to grid (keeps things aligned row-to-row). - grid.attach (*button, 2*i+1, row, 1, 1); - grid.attach (*label, 2*i+2, row, 1, 1); - } else { - // Pack into FlowBox - - // Pack button and label into a box so they stay together. - Gtk::Box* box = Gtk::manage (new Gtk::Box()); - box->add(*button); - box->add(*label); - - flow_box->add(*box); - } - } - - if (scrolled_window) { - grid.attach (*scrolled_window, 1, row, 4, 1); - } - } - - Glib::ustring - get_css() - { - int i = 0; - for (auto b: buttons) { - if (b->get_active()) { - if (i == 0) { - // Features are always off by default (for those handled here). - return ""; - } else if (i == 1) { - // Feature without value has implied value of 1. - return ("\"" + _name + "\", "); - } else { - // Feature with value greater than 1 must be explicitly set. - return ("\"" + _name + "\" " + std::to_string (i) + ", "); - } - } - ++i; - } - return ""; - } - - void - set_active(int i) - { - if (i < buttons.size()) { - buttons[i]->set_active(); - } - } - - private: - Glib::ustring _name; - int _options; - std::vector <Gtk::RadioButton*> buttons; - }; - - FontVariants::FontVariants () : - Gtk::VBox (), - _ligatures_frame ( Glib::ustring(C_("Font feature", "Ligatures" )) ), - _ligatures_common ( Glib::ustring(C_("Font feature", "Common" )) ), - _ligatures_discretionary ( Glib::ustring(C_("Font feature", "Discretionary")) ), - _ligatures_historical ( Glib::ustring(C_("Font feature", "Historical" )) ), - _ligatures_contextual ( Glib::ustring(C_("Font feature", "Contextual" )) ), - - _position_frame ( Glib::ustring(C_("Font feature", "Position" )) ), - _position_normal ( Glib::ustring(C_("Font feature", "Normal" )) ), - _position_sub ( Glib::ustring(C_("Font feature", "Subscript" )) ), - _position_super ( Glib::ustring(C_("Font feature", "Superscript" )) ), - - _caps_frame ( Glib::ustring(C_("Font feature", "Capitals" )) ), - _caps_normal ( Glib::ustring(C_("Font feature", "Normal" )) ), - _caps_small ( Glib::ustring(C_("Font feature", "Small" )) ), - _caps_all_small ( Glib::ustring(C_("Font feature", "All small" )) ), - _caps_petite ( Glib::ustring(C_("Font feature", "Petite" )) ), - _caps_all_petite ( Glib::ustring(C_("Font feature", "All petite" )) ), - _caps_unicase ( Glib::ustring(C_("Font feature", "Unicase" )) ), - _caps_titling ( Glib::ustring(C_("Font feature", "Titling" )) ), - - _numeric_frame ( Glib::ustring(C_("Font feature", "Numeric" )) ), - _numeric_lining ( Glib::ustring(C_("Font feature", "Lining" )) ), - _numeric_old_style ( Glib::ustring(C_("Font feature", "Old Style" )) ), - _numeric_default_style ( Glib::ustring(C_("Font feature", "Default Style")) ), - _numeric_proportional ( Glib::ustring(C_("Font feature", "Proportional" )) ), - _numeric_tabular ( Glib::ustring(C_("Font feature", "Tabular" )) ), - _numeric_default_width ( Glib::ustring(C_("Font feature", "Default Width")) ), - _numeric_diagonal ( Glib::ustring(C_("Font feature", "Diagonal" )) ), - _numeric_stacked ( Glib::ustring(C_("Font feature", "Stacked" )) ), - _numeric_default_fractions( Glib::ustring(C_("Font feature", "Default Fractions")) ), - _numeric_ordinal ( Glib::ustring(C_("Font feature", "Ordinal" )) ), - _numeric_slashed_zero ( Glib::ustring(C_("Font feature", "Slashed Zero" )) ), - - _asian_frame ( Glib::ustring(C_("Font feature", "East Asian" )) ), - _asian_default_variant ( Glib::ustring(C_("Font feature", "Default" )) ), - _asian_jis78 ( Glib::ustring(C_("Font feature", "JIS78" )) ), - _asian_jis83 ( Glib::ustring(C_("Font feature", "JIS83" )) ), - _asian_jis90 ( Glib::ustring(C_("Font feature", "JIS90" )) ), - _asian_jis04 ( Glib::ustring(C_("Font feature", "JIS04" )) ), - _asian_simplified ( Glib::ustring(C_("Font feature", "Simplified" )) ), - _asian_traditional ( Glib::ustring(C_("Font feature", "Traditional" )) ), - _asian_default_width ( Glib::ustring(C_("Font feature", "Default" )) ), - _asian_full_width ( Glib::ustring(C_("Font feature", "Full Width" )) ), - _asian_proportional_width ( Glib::ustring(C_("Font feature", "Proportional" )) ), - _asian_ruby ( Glib::ustring(C_("Font feature", "Ruby" )) ), - - _feature_frame ( Glib::ustring(C_("Font feature", "Feature Settings")) ), - _feature_label ( Glib::ustring(C_("Font feature", "Selection has different Feature Settings!")) ), - - _ligatures_changed( false ), - _position_changed( false ), - _caps_changed( false ), - _numeric_changed( false ), - _asian_changed( false ) - - { - - set_name ( "FontVariants" ); +// A simple class to handle UI for one feature. We could of derived this from Gtk::HBox but by +// attaching widgets directly to Gtk::Grid, we keep columns lined up (which may or may not be a +// good thing). +class Feature +{ +public: + Feature(const Glib::ustring &name, OTSubstitution &glyphs, int options, Glib::ustring family, Gtk::Grid &grid, + int &row, FontVariants *parent) + : _name(name) + , _options(options) + { + Gtk::Label *table_name = Gtk::manage(new Gtk::Label()); + table_name->set_markup("\"" + name + "\" "); + + grid.attach(*table_name, 0, row, 1, 1); + + Gtk::FlowBox *flow_box = nullptr; + Gtk::ScrolledWindow *scrolled_window = nullptr; + if (options > 2) { + // If there are more than 2 option, pack them into a flowbox instead of directly putting them in the grid. + // Some fonts might have a table with many options (Bungee Hairline table 'ornm' has 113 entries). + flow_box = Gtk::manage(new Gtk::FlowBox()); + flow_box->set_selection_mode(); // Turn off selection + flow_box->set_homogeneous(); + flow_box->set_max_children_per_line(100); // Override default value + flow_box->set_min_children_per_line(10); // Override default value + + // We pack this into a scrollbar... otherwise the minimum height is set to what is required to fit all + // flow box children into the flow box when the flow box has minimum width. (Crazy if you ask me!) + scrolled_window = Gtk::manage(new Gtk::ScrolledWindow()); + scrolled_window->set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); + scrolled_window->add(*flow_box); + } + + Gtk::RadioButton::Group group; + for (int i = 0; i < options; ++i) { + // Create radio button and create or add to button group. + Gtk::RadioButton *button = Gtk::manage(new Gtk::RadioButton()); + if (i == 0) { + group = button->get_group(); + } else { + button->set_group(group); + } + button->signal_clicked().connect(sigc::mem_fun(*parent, &FontVariants::feature_callback)); + buttons.push_back(button); + + // Create label. + Gtk::Label *label = Gtk::manage(new Gtk::Label()); + + // Restrict label width (some fonts have lots of alternatives). + label->set_line_wrap(true); + label->set_line_wrap_mode(Pango::WRAP_WORD_CHAR); + label->set_ellipsize(Pango::ELLIPSIZE_END); + label->set_lines(3); + label->set_hexpand(); + + Glib::ustring markup; + markup += "<span font_family='"; + markup += family; + markup += "' font_features='"; + markup += name; + markup += " "; + markup += std::to_string(i); + markup += "'>"; + markup += Glib::Markup::escape_text(glyphs.input); + markup += "</span>"; + label->set_markup(markup); + + // Add button and label to widget + if (!flow_box) { + // Attach directly to grid (keeps things aligned row-to-row). + grid.attach(*button, 2 * i + 1, row, 1, 1); + grid.attach(*label, 2 * i + 2, row, 1, 1); + } else { + // Pack into FlowBox + + // Pack button and label into a box so they stay together. + Gtk::Box *box = Gtk::manage(new Gtk::Box()); + box->add(*button); + box->add(*label); + + flow_box->add(*box); + } + } + + if (scrolled_window) { + grid.attach(*scrolled_window, 1, row, 4, 1); + } + } + + Glib::ustring get_css() + { + int i = 0; + for (auto b : buttons) { + if (b->get_active()) { + if (i == 0) { + // Features are always off by default (for those handled here). + return ""; + } else if (i == 1) { + // Feature without value has implied value of 1. + return ("\"" + _name + "\", "); + } else { + // Feature with value greater than 1 must be explicitly set. + return ("\"" + _name + "\" " + std::to_string(i) + ", "); + } + } + ++i; + } + return ""; + } + + void set_active(int i) + { + if (i < buttons.size()) { + buttons[i]->set_active(); + } + } + +private: + Glib::ustring _name; + int _options; + std::vector<Gtk::RadioButton *> buttons; +}; + +FontVariants::FontVariants() + : Gtk::VBox() + , _ligatures_frame(Glib::ustring(C_("Font feature", "Ligatures"))) + , _ligatures_common(Glib::ustring(C_("Font feature", "Common"))) + , _ligatures_discretionary(Glib::ustring(C_("Font feature", "Discretionary"))) + , _ligatures_historical(Glib::ustring(C_("Font feature", "Historical"))) + , _ligatures_contextual(Glib::ustring(C_("Font feature", "Contextual"))) + , + + _position_frame(Glib::ustring(C_("Font feature", "Position"))) + , _position_normal(Glib::ustring(C_("Font feature", "Normal"))) + , _position_sub(Glib::ustring(C_("Font feature", "Subscript"))) + , _position_super(Glib::ustring(C_("Font feature", "Superscript"))) + , + + _caps_frame(Glib::ustring(C_("Font feature", "Capitals"))) + , _caps_normal(Glib::ustring(C_("Font feature", "Normal"))) + , _caps_small(Glib::ustring(C_("Font feature", "Small"))) + , _caps_all_small(Glib::ustring(C_("Font feature", "All small"))) + , _caps_petite(Glib::ustring(C_("Font feature", "Petite"))) + , _caps_all_petite(Glib::ustring(C_("Font feature", "All petite"))) + , _caps_unicase(Glib::ustring(C_("Font feature", "Unicase"))) + , _caps_titling(Glib::ustring(C_("Font feature", "Titling"))) + , + + _numeric_frame(Glib::ustring(C_("Font feature", "Numeric"))) + , _numeric_lining(Glib::ustring(C_("Font feature", "Lining"))) + , _numeric_old_style(Glib::ustring(C_("Font feature", "Old Style"))) + , _numeric_default_style(Glib::ustring(C_("Font feature", "Default Style"))) + , _numeric_proportional(Glib::ustring(C_("Font feature", "Proportional"))) + , _numeric_tabular(Glib::ustring(C_("Font feature", "Tabular"))) + , _numeric_default_width(Glib::ustring(C_("Font feature", "Default Width"))) + , _numeric_diagonal(Glib::ustring(C_("Font feature", "Diagonal"))) + , _numeric_stacked(Glib::ustring(C_("Font feature", "Stacked"))) + , _numeric_default_fractions(Glib::ustring(C_("Font feature", "Default Fractions"))) + , _numeric_ordinal(Glib::ustring(C_("Font feature", "Ordinal"))) + , _numeric_slashed_zero(Glib::ustring(C_("Font feature", "Slashed Zero"))) + , + + _asian_frame(Glib::ustring(C_("Font feature", "East Asian"))) + , _asian_default_variant(Glib::ustring(C_("Font feature", "Default"))) + , _asian_jis78(Glib::ustring(C_("Font feature", "JIS78"))) + , _asian_jis83(Glib::ustring(C_("Font feature", "JIS83"))) + , _asian_jis90(Glib::ustring(C_("Font feature", "JIS90"))) + , _asian_jis04(Glib::ustring(C_("Font feature", "JIS04"))) + , _asian_simplified(Glib::ustring(C_("Font feature", "Simplified"))) + , _asian_traditional(Glib::ustring(C_("Font feature", "Traditional"))) + , _asian_default_width(Glib::ustring(C_("Font feature", "Default"))) + , _asian_full_width(Glib::ustring(C_("Font feature", "Full Width"))) + , _asian_proportional_width(Glib::ustring(C_("Font feature", "Proportional"))) + , _asian_ruby(Glib::ustring(C_("Font feature", "Ruby"))) + , + + _feature_frame(Glib::ustring(C_("Font feature", "Feature Settings"))) + , _feature_label(Glib::ustring(C_("Font feature", "Selection has different Feature Settings!"))) + , + + _ligatures_changed(false) + , _position_changed(false) + , _caps_changed(false) + , _numeric_changed(false) + , _asian_changed(false) + +{ + set_name("FontVariants"); // Ligatures -------------------------- // Add tooltips - _ligatures_common.set_tooltip_text( - _("Common ligatures. On by default. OpenType tables: 'liga', 'clig'")); - _ligatures_discretionary.set_tooltip_text( - _("Discretionary ligatures. Off by default. OpenType table: 'dlig'")); - _ligatures_historical.set_tooltip_text( - _("Historical ligatures. Off by default. OpenType table: 'hlig'")); - _ligatures_contextual.set_tooltip_text( - _("Contextual forms. On by default. OpenType table: 'calt'")); + _ligatures_common.set_tooltip_text(_("Common ligatures. On by default. OpenType tables: 'liga', 'clig'")); + _ligatures_discretionary.set_tooltip_text(_("Discretionary ligatures. Off by default. OpenType table: 'dlig'")); + _ligatures_historical.set_tooltip_text(_("Historical ligatures. Off by default. OpenType table: 'hlig'")); + _ligatures_contextual.set_tooltip_text(_("Contextual forms. On by default. OpenType table: 'calt'")); // Add signals - _ligatures_common.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::ligatures_callback) ); - _ligatures_discretionary.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::ligatures_callback) ); - _ligatures_historical.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::ligatures_callback) ); - _ligatures_contextual.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::ligatures_callback) ); + _ligatures_common.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::ligatures_callback)); + _ligatures_discretionary.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::ligatures_callback)); + _ligatures_historical.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::ligatures_callback)); + _ligatures_contextual.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::ligatures_callback)); // Restrict label widths (some fonts have lots of ligatures). Must also set ellipsize mode. - _ligatures_label_common.set_max_width_chars( 60 ); - _ligatures_label_discretionary.set_max_width_chars( 60 ); - _ligatures_label_historical.set_max_width_chars( 60 ); - _ligatures_label_contextual.set_max_width_chars( 60 ); + _ligatures_label_common.set_max_width_chars(60); + _ligatures_label_discretionary.set_max_width_chars(60); + _ligatures_label_historical.set_max_width_chars(60); + _ligatures_label_contextual.set_max_width_chars(60); - _ligatures_label_common.set_ellipsize( Pango::ELLIPSIZE_END ); - _ligatures_label_discretionary.set_ellipsize( Pango::ELLIPSIZE_END ); - _ligatures_label_historical.set_ellipsize( Pango::ELLIPSIZE_END ); - _ligatures_label_contextual.set_ellipsize( Pango::ELLIPSIZE_END ); + _ligatures_label_common.set_ellipsize(Pango::ELLIPSIZE_END); + _ligatures_label_discretionary.set_ellipsize(Pango::ELLIPSIZE_END); + _ligatures_label_historical.set_ellipsize(Pango::ELLIPSIZE_END); + _ligatures_label_contextual.set_ellipsize(Pango::ELLIPSIZE_END); - _ligatures_label_common.set_lines( 5 ); - _ligatures_label_discretionary.set_lines( 5 ); - _ligatures_label_historical.set_lines( 5 ); - _ligatures_label_contextual.set_lines( 5 ); + _ligatures_label_common.set_lines(5); + _ligatures_label_discretionary.set_lines(5); + _ligatures_label_historical.set_lines(5); + _ligatures_label_contextual.set_lines(5); // Allow user to select characters. Not useful as this selects the ligatures. // _ligatures_label_common.set_selectable( true ); @@ -251,29 +249,29 @@ namespace Widget { // _ligatures_label_contextual.set_selectable( true ); // Add to frame - _ligatures_grid.attach( _ligatures_common, 0, 0, 1, 1); - _ligatures_grid.attach( _ligatures_discretionary, 0, 1, 1, 1); - _ligatures_grid.attach( _ligatures_historical, 0, 2, 1, 1); - _ligatures_grid.attach( _ligatures_contextual, 0, 3, 1, 1); - _ligatures_grid.attach( _ligatures_label_common, 1, 0, 1, 1); - _ligatures_grid.attach( _ligatures_label_discretionary, 1, 1, 1, 1); - _ligatures_grid.attach( _ligatures_label_historical, 1, 2, 1, 1); - _ligatures_grid.attach( _ligatures_label_contextual, 1, 3, 1, 1); + _ligatures_grid.attach(_ligatures_common, 0, 0, 1, 1); + _ligatures_grid.attach(_ligatures_discretionary, 0, 1, 1, 1); + _ligatures_grid.attach(_ligatures_historical, 0, 2, 1, 1); + _ligatures_grid.attach(_ligatures_contextual, 0, 3, 1, 1); + _ligatures_grid.attach(_ligatures_label_common, 1, 0, 1, 1); + _ligatures_grid.attach(_ligatures_label_discretionary, 1, 1, 1, 1); + _ligatures_grid.attach(_ligatures_label_historical, 1, 2, 1, 1); + _ligatures_grid.attach(_ligatures_label_contextual, 1, 3, 1, 1); _ligatures_grid.set_margin_start(15); _ligatures_grid.set_margin_end(15); - _ligatures_frame.add( _ligatures_grid ); - pack_start( _ligatures_frame, Gtk::PACK_SHRINK ); + _ligatures_frame.add(_ligatures_grid); + pack_start(_ligatures_frame, Gtk::PACK_SHRINK); ligatures_init(); - + // Position ---------------------------------- // Add tooltips - _position_normal.set_tooltip_text( _("Normal position.")); - _position_sub.set_tooltip_text( _("Subscript. OpenType table: 'subs'") ); - _position_super.set_tooltip_text( _("Superscript. OpenType table: 'sups'") ); + _position_normal.set_tooltip_text(_("Normal position.")); + _position_sub.set_tooltip_text(_("Subscript. OpenType table: 'subs'")); + _position_super.set_tooltip_text(_("Superscript. OpenType table: 'sups'")); // Group buttons Gtk::RadioButton::Group position_group = _position_normal.get_group(); @@ -281,33 +279,36 @@ namespace Widget { _position_super.set_group(position_group); // Add signals - _position_normal.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::position_callback) ); - _position_sub.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::position_callback) ); - _position_super.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::position_callback) ); + _position_normal.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::position_callback)); + _position_sub.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::position_callback)); + _position_super.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::position_callback)); // Add to frame - _position_grid.attach( _position_normal, 0, 0, 1, 1); - _position_grid.attach( _position_sub, 1, 0, 1, 1); - _position_grid.attach( _position_super, 2, 0, 1, 1); + _position_grid.attach(_position_normal, 0, 0, 1, 1); + _position_grid.attach(_position_sub, 1, 0, 1, 1); + _position_grid.attach(_position_super, 2, 0, 1, 1); _position_grid.set_margin_start(15); _position_grid.set_margin_end(15); - _position_frame.add( _position_grid ); - pack_start( _position_frame, Gtk::PACK_SHRINK ); + _position_frame.add(_position_grid); + pack_start(_position_frame, Gtk::PACK_SHRINK); position_init(); // Caps ---------------------------------- // Add tooltips - _caps_normal.set_tooltip_text( _("Normal capitalization.")); - _caps_small.set_tooltip_text( _("Small-caps (lowercase). OpenType table: 'smcp'")); - _caps_all_small.set_tooltip_text( _("All small-caps (uppercase and lowercase). OpenType tables: 'c2sc' and 'smcp'")); - _caps_petite.set_tooltip_text( _("Petite-caps (lowercase). OpenType table: 'pcap'")); - _caps_all_petite.set_tooltip_text( _("All petite-caps (uppercase and lowercase). OpenType tables: 'c2sc' and 'pcap'")); - _caps_unicase.set_tooltip_text( _("Unicase (small caps for uppercase, normal for lowercase). OpenType table: 'unic'")); - _caps_titling.set_tooltip_text( _("Titling caps (lighter-weight uppercase for use in titles). OpenType table: 'titl'")); + _caps_normal.set_tooltip_text(_("Normal capitalization.")); + _caps_small.set_tooltip_text(_("Small-caps (lowercase). OpenType table: 'smcp'")); + _caps_all_small.set_tooltip_text(_("All small-caps (uppercase and lowercase). OpenType tables: 'c2sc' and 'smcp'")); + _caps_petite.set_tooltip_text(_("Petite-caps (lowercase). OpenType table: 'pcap'")); + _caps_all_petite.set_tooltip_text( + _("All petite-caps (uppercase and lowercase). OpenType tables: 'c2sc' and 'pcap'")); + _caps_unicase.set_tooltip_text( + _("Unicase (small caps for uppercase, normal for lowercase). OpenType table: 'unic'")); + _caps_titling.set_tooltip_text( + _("Titling caps (lighter-weight uppercase for use in titles). OpenType table: 'titl'")); // Group buttons Gtk::RadioButton::Group caps_group = _caps_normal.get_group(); @@ -319,45 +320,45 @@ namespace Widget { _caps_titling.set_group(caps_group); // Add signals - _caps_normal.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::caps_callback) ); - _caps_small.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::caps_callback) ); - _caps_all_small.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::caps_callback) ); - _caps_petite.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::caps_callback) ); - _caps_all_petite.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::caps_callback) ); - _caps_unicase.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::caps_callback) ); - _caps_titling.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::caps_callback) ); + _caps_normal.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::caps_callback)); + _caps_small.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::caps_callback)); + _caps_all_small.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::caps_callback)); + _caps_petite.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::caps_callback)); + _caps_all_petite.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::caps_callback)); + _caps_unicase.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::caps_callback)); + _caps_titling.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::caps_callback)); // Add to frame - _caps_grid.attach( _caps_normal, 0, 0, 1, 1); - _caps_grid.attach( _caps_unicase, 1, 0, 1, 1); - _caps_grid.attach( _caps_titling, 2, 0, 1, 1); - _caps_grid.attach( _caps_small, 0, 1, 1, 1); - _caps_grid.attach( _caps_all_small, 1, 1, 1, 1); - _caps_grid.attach( _caps_petite, 2, 1, 1, 1); - _caps_grid.attach( _caps_all_petite, 3, 1, 1, 1); + _caps_grid.attach(_caps_normal, 0, 0, 1, 1); + _caps_grid.attach(_caps_unicase, 1, 0, 1, 1); + _caps_grid.attach(_caps_titling, 2, 0, 1, 1); + _caps_grid.attach(_caps_small, 0, 1, 1, 1); + _caps_grid.attach(_caps_all_small, 1, 1, 1, 1); + _caps_grid.attach(_caps_petite, 2, 1, 1, 1); + _caps_grid.attach(_caps_all_petite, 3, 1, 1, 1); _caps_grid.set_margin_start(15); _caps_grid.set_margin_end(15); - _caps_frame.add( _caps_grid ); - pack_start( _caps_frame, Gtk::PACK_SHRINK ); + _caps_frame.add(_caps_grid); + pack_start(_caps_frame, Gtk::PACK_SHRINK); caps_init(); // Numeric ------------------------------ // Add tooltips - _numeric_default_style.set_tooltip_text( _("Normal style.")); - _numeric_lining.set_tooltip_text( _("Lining numerals. OpenType table: 'lnum'")); - _numeric_old_style.set_tooltip_text( _("Old style numerals. OpenType table: 'onum'")); - _numeric_default_width.set_tooltip_text( _("Normal widths.")); - _numeric_proportional.set_tooltip_text( _("Proportional width numerals. OpenType table: 'pnum'")); - _numeric_tabular.set_tooltip_text( _("Same width numerals. OpenType table: 'tnum'")); - _numeric_default_fractions.set_tooltip_text( _("Normal fractions.")); - _numeric_diagonal.set_tooltip_text( _("Diagonal fractions. OpenType table: 'frac'")); - _numeric_stacked.set_tooltip_text( _("Stacked fractions. OpenType table: 'afrc'")); - _numeric_ordinal.set_tooltip_text( _("Ordinals (raised 'th', etc.). OpenType table: 'ordn'")); - _numeric_slashed_zero.set_tooltip_text( _("Slashed zeros. OpenType table: 'zero'")); + _numeric_default_style.set_tooltip_text(_("Normal style.")); + _numeric_lining.set_tooltip_text(_("Lining numerals. OpenType table: 'lnum'")); + _numeric_old_style.set_tooltip_text(_("Old style numerals. OpenType table: 'onum'")); + _numeric_default_width.set_tooltip_text(_("Normal widths.")); + _numeric_proportional.set_tooltip_text(_("Proportional width numerals. OpenType table: 'pnum'")); + _numeric_tabular.set_tooltip_text(_("Same width numerals. OpenType table: 'tnum'")); + _numeric_default_fractions.set_tooltip_text(_("Normal fractions.")); + _numeric_diagonal.set_tooltip_text(_("Diagonal fractions. OpenType table: 'frac'")); + _numeric_stacked.set_tooltip_text(_("Stacked fractions. OpenType table: 'afrc'")); + _numeric_ordinal.set_tooltip_text(_("Ordinals (raised 'th', etc.). OpenType table: 'ordn'")); + _numeric_slashed_zero.set_tooltip_text(_("Slashed zeros. OpenType table: 'zero'")); // Group buttons Gtk::RadioButton::Group style_group = _numeric_default_style.get_group(); @@ -373,95 +374,95 @@ namespace Widget { _numeric_stacked.set_group(fraction_group); // Add signals - _numeric_default_style.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::numeric_callback) ); - _numeric_lining.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::numeric_callback) ); - _numeric_old_style.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::numeric_callback) ); - _numeric_default_width.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::numeric_callback) ); - _numeric_proportional.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::numeric_callback) ); - _numeric_tabular.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::numeric_callback) ); - _numeric_default_fractions.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::numeric_callback) ); - _numeric_diagonal.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::numeric_callback) ); - _numeric_stacked.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::numeric_callback) ); - _numeric_ordinal.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::numeric_callback) ); - _numeric_slashed_zero.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::numeric_callback) ); + _numeric_default_style.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::numeric_callback)); + _numeric_lining.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::numeric_callback)); + _numeric_old_style.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::numeric_callback)); + _numeric_default_width.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::numeric_callback)); + _numeric_proportional.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::numeric_callback)); + _numeric_tabular.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::numeric_callback)); + _numeric_default_fractions.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::numeric_callback)); + _numeric_diagonal.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::numeric_callback)); + _numeric_stacked.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::numeric_callback)); + _numeric_ordinal.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::numeric_callback)); + _numeric_slashed_zero.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::numeric_callback)); // Add to frame - _numeric_grid.attach (_numeric_default_style, 0, 0, 1, 1); - _numeric_grid.attach (_numeric_lining, 1, 0, 1, 1); - _numeric_grid.attach (_numeric_lining_label, 2, 0, 1, 1); - _numeric_grid.attach (_numeric_old_style, 3, 0, 1, 1); - _numeric_grid.attach (_numeric_old_style_label, 4, 0, 1, 1); - - _numeric_grid.attach (_numeric_default_width, 0, 1, 1, 1); - _numeric_grid.attach (_numeric_proportional, 1, 1, 1, 1); - _numeric_grid.attach (_numeric_proportional_label, 2, 1, 1, 1); - _numeric_grid.attach (_numeric_tabular, 3, 1, 1, 1); - _numeric_grid.attach (_numeric_tabular_label, 4, 1, 1, 1); - - _numeric_grid.attach (_numeric_default_fractions, 0, 2, 1, 1); - _numeric_grid.attach (_numeric_diagonal, 1, 2, 1, 1); - _numeric_grid.attach (_numeric_diagonal_label, 2, 2, 1, 1); - _numeric_grid.attach (_numeric_stacked, 3, 2, 1, 1); - _numeric_grid.attach (_numeric_stacked_label, 4, 2, 1, 1); - - _numeric_grid.attach (_numeric_ordinal, 0, 3, 1, 1); - _numeric_grid.attach (_numeric_ordinal_label, 1, 3, 4, 1); - - _numeric_grid.attach (_numeric_slashed_zero, 0, 4, 1, 1); - _numeric_grid.attach (_numeric_slashed_zero_label, 1, 4, 1, 1); + _numeric_grid.attach(_numeric_default_style, 0, 0, 1, 1); + _numeric_grid.attach(_numeric_lining, 1, 0, 1, 1); + _numeric_grid.attach(_numeric_lining_label, 2, 0, 1, 1); + _numeric_grid.attach(_numeric_old_style, 3, 0, 1, 1); + _numeric_grid.attach(_numeric_old_style_label, 4, 0, 1, 1); + + _numeric_grid.attach(_numeric_default_width, 0, 1, 1, 1); + _numeric_grid.attach(_numeric_proportional, 1, 1, 1, 1); + _numeric_grid.attach(_numeric_proportional_label, 2, 1, 1, 1); + _numeric_grid.attach(_numeric_tabular, 3, 1, 1, 1); + _numeric_grid.attach(_numeric_tabular_label, 4, 1, 1, 1); + + _numeric_grid.attach(_numeric_default_fractions, 0, 2, 1, 1); + _numeric_grid.attach(_numeric_diagonal, 1, 2, 1, 1); + _numeric_grid.attach(_numeric_diagonal_label, 2, 2, 1, 1); + _numeric_grid.attach(_numeric_stacked, 3, 2, 1, 1); + _numeric_grid.attach(_numeric_stacked_label, 4, 2, 1, 1); + + _numeric_grid.attach(_numeric_ordinal, 0, 3, 1, 1); + _numeric_grid.attach(_numeric_ordinal_label, 1, 3, 4, 1); + + _numeric_grid.attach(_numeric_slashed_zero, 0, 4, 1, 1); + _numeric_grid.attach(_numeric_slashed_zero_label, 1, 4, 1, 1); _numeric_grid.set_margin_start(15); _numeric_grid.set_margin_end(15); - _numeric_frame.add( _numeric_grid ); - pack_start( _numeric_frame, Gtk::PACK_SHRINK ); - + _numeric_frame.add(_numeric_grid); + pack_start(_numeric_frame, Gtk::PACK_SHRINK); + // East Asian // Add tooltips - _asian_default_variant.set_tooltip_text ( _("Default variant.")); - _asian_jis78.set_tooltip_text( _("JIS78 forms. OpenType table: 'jp78'.")); - _asian_jis83.set_tooltip_text( _("JIS83 forms. OpenType table: 'jp83'.")); - _asian_jis90.set_tooltip_text( _("JIS90 forms. OpenType table: 'jp90'.")); - _asian_jis04.set_tooltip_text( _("JIS2004 forms. OpenType table: 'jp04'.")); - _asian_simplified.set_tooltip_text( _("Simplified forms. OpenType table: 'smpl'.")); - _asian_traditional.set_tooltip_text( _("Traditional forms. OpenType table: 'trad'.")); - _asian_default_width.set_tooltip_text ( _("Default width.")); - _asian_full_width.set_tooltip_text( _("Full width variants. OpenType table: 'fwid'.")); + _asian_default_variant.set_tooltip_text(_("Default variant.")); + _asian_jis78.set_tooltip_text(_("JIS78 forms. OpenType table: 'jp78'.")); + _asian_jis83.set_tooltip_text(_("JIS83 forms. OpenType table: 'jp83'.")); + _asian_jis90.set_tooltip_text(_("JIS90 forms. OpenType table: 'jp90'.")); + _asian_jis04.set_tooltip_text(_("JIS2004 forms. OpenType table: 'jp04'.")); + _asian_simplified.set_tooltip_text(_("Simplified forms. OpenType table: 'smpl'.")); + _asian_traditional.set_tooltip_text(_("Traditional forms. OpenType table: 'trad'.")); + _asian_default_width.set_tooltip_text(_("Default width.")); + _asian_full_width.set_tooltip_text(_("Full width variants. OpenType table: 'fwid'.")); _asian_proportional_width.set_tooltip_text(_("Proportional width variants. OpenType table: 'pwid'.")); - _asian_ruby.set_tooltip_text( _("Ruby variants. OpenType table: 'ruby'.")); + _asian_ruby.set_tooltip_text(_("Ruby variants. OpenType table: 'ruby'.")); // Add signals - _asian_default_variant.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::asian_callback) ); - _asian_jis78.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::asian_callback) ); - _asian_jis83.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::asian_callback) ); - _asian_jis90.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::asian_callback) ); - _asian_jis04.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::asian_callback) ); - _asian_simplified.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::asian_callback) ); - _asian_traditional.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::asian_callback) ); - _asian_default_width.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::asian_callback) ); - _asian_full_width.signal_clicked().connect ( sigc::mem_fun(*this, &FontVariants::asian_callback) ); - _asian_proportional_width.signal_clicked().connect (sigc::mem_fun(*this, &FontVariants::asian_callback) ); - _asian_ruby.signal_clicked().connect( sigc::mem_fun(*this, &FontVariants::asian_callback) ); + _asian_default_variant.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::asian_callback)); + _asian_jis78.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::asian_callback)); + _asian_jis83.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::asian_callback)); + _asian_jis90.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::asian_callback)); + _asian_jis04.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::asian_callback)); + _asian_simplified.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::asian_callback)); + _asian_traditional.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::asian_callback)); + _asian_default_width.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::asian_callback)); + _asian_full_width.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::asian_callback)); + _asian_proportional_width.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::asian_callback)); + _asian_ruby.signal_clicked().connect(sigc::mem_fun(*this, &FontVariants::asian_callback)); // Add to frame - _asian_grid.attach (_asian_default_variant, 0, 0, 1, 1); - _asian_grid.attach (_asian_jis78, 1, 0, 1, 1); - _asian_grid.attach (_asian_jis83, 2, 0, 1, 1); - _asian_grid.attach (_asian_jis90, 1, 1, 1, 1); - _asian_grid.attach (_asian_jis04, 2, 1, 1, 1); - _asian_grid.attach (_asian_simplified, 1, 2, 1, 1); - _asian_grid.attach (_asian_traditional, 2, 2, 1, 1); - _asian_grid.attach (_asian_default_width, 0, 3, 1, 1); - _asian_grid.attach (_asian_full_width, 1, 3, 1, 1); - _asian_grid.attach (_asian_proportional_width, 2, 3, 1, 1); - _asian_grid.attach (_asian_ruby, 0, 4, 1, 1); + _asian_grid.attach(_asian_default_variant, 0, 0, 1, 1); + _asian_grid.attach(_asian_jis78, 1, 0, 1, 1); + _asian_grid.attach(_asian_jis83, 2, 0, 1, 1); + _asian_grid.attach(_asian_jis90, 1, 1, 1, 1); + _asian_grid.attach(_asian_jis04, 2, 1, 1, 1); + _asian_grid.attach(_asian_simplified, 1, 2, 1, 1); + _asian_grid.attach(_asian_traditional, 2, 2, 1, 1); + _asian_grid.attach(_asian_default_width, 0, 3, 1, 1); + _asian_grid.attach(_asian_full_width, 1, 3, 1, 1); + _asian_grid.attach(_asian_proportional_width, 2, 3, 1, 1); + _asian_grid.attach(_asian_ruby, 0, 4, 1, 1); _asian_grid.set_margin_start(15); _asian_grid.set_margin_end(15); - _asian_frame.add( _asian_grid ); - pack_start( _asian_frame, Gtk::PACK_SHRINK ); + _asian_frame.add(_asian_grid); + pack_start(_asian_frame, Gtk::PACK_SHRINK); // Group Buttons Gtk::RadioButton::Group asian_variant_group = _asian_default_variant.get_group(); @@ -473,972 +474,1063 @@ namespace Widget { _asian_traditional.set_group(asian_variant_group); Gtk::RadioButton::Group asian_width_group = _asian_default_width.get_group(); - _asian_full_width.set_group (asian_width_group); - _asian_proportional_width.set_group (asian_width_group); + _asian_full_width.set_group(asian_width_group); + _asian_proportional_width.set_group(asian_width_group); // Feature settings --------------------- // Add tooltips - _feature_entry.set_tooltip_text( _("Feature settings in CSS form (e.g. \"wxyz\" or \"wxyz\" 3).")); + _feature_entry.set_tooltip_text(_("Feature settings in CSS form (e.g. \"wxyz\" or \"wxyz\" 3).")); - _feature_substitutions.set_justify( Gtk::JUSTIFY_LEFT ); - _feature_substitutions.set_line_wrap( true ); - _feature_substitutions.set_line_wrap_mode( Pango::WRAP_WORD_CHAR ); + _feature_substitutions.set_justify(Gtk::JUSTIFY_LEFT); + _feature_substitutions.set_line_wrap(true); + _feature_substitutions.set_line_wrap_mode(Pango::WRAP_WORD_CHAR); - _feature_list.set_justify( Gtk::JUSTIFY_LEFT ); - _feature_list.set_line_wrap( true ); + _feature_list.set_justify(Gtk::JUSTIFY_LEFT); + _feature_list.set_line_wrap(true); // Add to frame - _feature_vbox.pack_start( _feature_grid, Gtk::PACK_SHRINK ); - _feature_vbox.pack_start( _feature_entry, Gtk::PACK_SHRINK ); - _feature_vbox.pack_start( _feature_label, Gtk::PACK_SHRINK ); - _feature_vbox.pack_start( _feature_substitutions, Gtk::PACK_SHRINK ); - _feature_vbox.pack_start( _feature_list, Gtk::PACK_SHRINK ); + _feature_vbox.pack_start(_feature_grid, Gtk::PACK_SHRINK); + _feature_vbox.pack_start(_feature_entry, Gtk::PACK_SHRINK); + _feature_vbox.pack_start(_feature_label, Gtk::PACK_SHRINK); + _feature_vbox.pack_start(_feature_substitutions, Gtk::PACK_SHRINK); + _feature_vbox.pack_start(_feature_list, Gtk::PACK_SHRINK); _feature_vbox.set_margin_start(15); _feature_vbox.set_margin_end(15); - _feature_frame.add( _feature_vbox ); - pack_start( _feature_frame, Gtk::PACK_SHRINK ); + _feature_frame.add(_feature_vbox); + pack_start(_feature_frame, Gtk::PACK_SHRINK); // Add signals //_feature_entry.signal_key_press_event().connect ( sigc::mem_fun(*this, &FontVariants::feature_callback) ); - _feature_entry.signal_changed().connect( sigc::mem_fun(*this, &FontVariants::feature_callback) ); - + _feature_entry.signal_changed().connect(sigc::mem_fun(*this, &FontVariants::feature_callback)); + show_all_children(); +} + +void FontVariants::ligatures_init() +{ + // std::cout << "FontVariants::ligatures_init()" << std::endl; +} + +void FontVariants::ligatures_callback() +{ + // std::cout << "FontVariants::ligatures_callback()" << std::endl; + _ligatures_changed = true; + _changed_signal.emit(); +} + +void FontVariants::position_init() +{ + // std::cout << "FontVariants::position_init()" << std::endl; +} + +void FontVariants::position_callback() +{ + // std::cout << "FontVariants::position_callback()" << std::endl; + _position_changed = true; + _changed_signal.emit(); +} + +void FontVariants::caps_init() +{ + // std::cout << "FontVariants::caps_init()" << std::endl; +} + +void FontVariants::caps_callback() +{ + // std::cout << "FontVariants::caps_callback()" << std::endl; + _caps_changed = true; + _changed_signal.emit(); +} + +void FontVariants::numeric_init() +{ + // std::cout << "FontVariants::numeric_init()" << std::endl; +} + +void FontVariants::numeric_callback() +{ + // std::cout << "FontVariants::numeric_callback()" << std::endl; + _numeric_changed = true; + _changed_signal.emit(); +} + +void FontVariants::asian_init() +{ + // std::cout << "FontVariants::asian_init()" << std::endl; +} + +void FontVariants::asian_callback() +{ + // std::cout << "FontVariants::asian_callback()" << std::endl; + _asian_changed = true; + _changed_signal.emit(); +} + +void FontVariants::feature_init() +{ + // std::cout << "FontVariants::feature_init()" << std::endl; +} + +void FontVariants::feature_callback() +{ + // std::cout << "FontVariants::feature_callback()" << std::endl; + _feature_changed = true; + _changed_signal.emit(); +} + +// Update GUI based on query. +void FontVariants::update(SPStyle const *query, bool different_features, Glib::ustring &font_spec) +{ + update_opentype(font_spec); + + _ligatures_all = query->font_variant_ligatures.computed; + _ligatures_mix = query->font_variant_ligatures.value; + + _ligatures_common.set_active(_ligatures_all & SP_CSS_FONT_VARIANT_LIGATURES_COMMON); + _ligatures_discretionary.set_active(_ligatures_all & SP_CSS_FONT_VARIANT_LIGATURES_DISCRETIONARY); + _ligatures_historical.set_active(_ligatures_all & SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL); + _ligatures_contextual.set_active(_ligatures_all & SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL); + + _ligatures_common.set_inconsistent(_ligatures_mix & SP_CSS_FONT_VARIANT_LIGATURES_COMMON); + _ligatures_discretionary.set_inconsistent(_ligatures_mix & SP_CSS_FONT_VARIANT_LIGATURES_DISCRETIONARY); + _ligatures_historical.set_inconsistent(_ligatures_mix & SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL); + _ligatures_contextual.set_inconsistent(_ligatures_mix & SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL); + + _position_all = query->font_variant_position.computed; + _position_mix = query->font_variant_position.value; + + _position_normal.set_active(_position_all & SP_CSS_FONT_VARIANT_POSITION_NORMAL); + _position_sub.set_active(_position_all & SP_CSS_FONT_VARIANT_POSITION_SUB); + _position_super.set_active(_position_all & SP_CSS_FONT_VARIANT_POSITION_SUPER); + + _position_normal.set_inconsistent(_position_mix & SP_CSS_FONT_VARIANT_POSITION_NORMAL); + _position_sub.set_inconsistent(_position_mix & SP_CSS_FONT_VARIANT_POSITION_SUB); + _position_super.set_inconsistent(_position_mix & SP_CSS_FONT_VARIANT_POSITION_SUPER); + + _caps_all = query->font_variant_caps.computed; + _caps_mix = query->font_variant_caps.value; + + _caps_normal.set_active(_caps_all & SP_CSS_FONT_VARIANT_CAPS_NORMAL); + _caps_small.set_active(_caps_all & SP_CSS_FONT_VARIANT_CAPS_SMALL); + _caps_all_small.set_active(_caps_all & SP_CSS_FONT_VARIANT_CAPS_ALL_SMALL); + _caps_petite.set_active(_caps_all & SP_CSS_FONT_VARIANT_CAPS_PETITE); + _caps_all_petite.set_active(_caps_all & SP_CSS_FONT_VARIANT_CAPS_ALL_PETITE); + _caps_unicase.set_active(_caps_all & SP_CSS_FONT_VARIANT_CAPS_UNICASE); + _caps_titling.set_active(_caps_all & SP_CSS_FONT_VARIANT_CAPS_TITLING); + + _caps_normal.set_inconsistent(_caps_mix & SP_CSS_FONT_VARIANT_CAPS_NORMAL); + _caps_small.set_inconsistent(_caps_mix & SP_CSS_FONT_VARIANT_CAPS_SMALL); + _caps_all_small.set_inconsistent(_caps_mix & SP_CSS_FONT_VARIANT_CAPS_ALL_SMALL); + _caps_petite.set_inconsistent(_caps_mix & SP_CSS_FONT_VARIANT_CAPS_PETITE); + _caps_all_petite.set_inconsistent(_caps_mix & SP_CSS_FONT_VARIANT_CAPS_ALL_PETITE); + _caps_unicase.set_inconsistent(_caps_mix & SP_CSS_FONT_VARIANT_CAPS_UNICASE); + _caps_titling.set_inconsistent(_caps_mix & SP_CSS_FONT_VARIANT_CAPS_TITLING); + + _numeric_all = query->font_variant_numeric.computed; + _numeric_mix = query->font_variant_numeric.value; + + if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_LINING_NUMS) { + _numeric_lining.set_active(); + } else if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_OLDSTYLE_NUMS) { + _numeric_old_style.set_active(); + } else { + _numeric_default_style.set_active(); + } + + if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_PROPORTIONAL_NUMS) { + _numeric_proportional.set_active(); + } else if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_TABULAR_NUMS) { + _numeric_tabular.set_active(); + } else { + _numeric_default_width.set_active(); + } + + if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_DIAGONAL_FRACTIONS) { + _numeric_diagonal.set_active(); + } else if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_STACKED_FRACTIONS) { + _numeric_stacked.set_active(); + } else { + _numeric_default_fractions.set_active(); + } + + _numeric_ordinal.set_active(_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_ORDINAL); + _numeric_slashed_zero.set_active(_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_SLASHED_ZERO); + + _numeric_lining.set_inconsistent(_numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_LINING_NUMS); + _numeric_old_style.set_inconsistent(_numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_OLDSTYLE_NUMS); + _numeric_proportional.set_inconsistent(_numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_PROPORTIONAL_NUMS); + _numeric_tabular.set_inconsistent(_numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_TABULAR_NUMS); + _numeric_diagonal.set_inconsistent(_numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_DIAGONAL_FRACTIONS); + _numeric_stacked.set_inconsistent(_numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_STACKED_FRACTIONS); + _numeric_ordinal.set_inconsistent(_numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_ORDINAL); + _numeric_slashed_zero.set_inconsistent(_numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_SLASHED_ZERO); + + _asian_all = query->font_variant_east_asian.computed; + _asian_mix = query->font_variant_east_asian.value; + + if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS78) { + _asian_jis78.set_active(); + } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS83) { + _asian_jis83.set_active(); + } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS90) { + _asian_jis90.set_active(); + } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS04) { + _asian_jis04.set_active(); + } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_SIMPLIFIED) { + _asian_simplified.set_active(); + } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_TRADITIONAL) { + _asian_traditional.set_active(); + } else { + _asian_default_variant.set_active(); + } + + if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_FULL_WIDTH) { + _asian_full_width.set_active(); + } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_PROPORTIONAL_WIDTH) { + _asian_proportional_width.set_active(); + } else { + _asian_default_width.set_active(); + } + + _asian_ruby.set_active(_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_RUBY); + + _asian_jis78.set_inconsistent(_asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS78); + _asian_jis83.set_inconsistent(_asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS83); + _asian_jis90.set_inconsistent(_asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS90); + _asian_jis04.set_inconsistent(_asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS04); + _asian_simplified.set_inconsistent(_asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_SIMPLIFIED); + _asian_traditional.set_inconsistent(_asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_TRADITIONAL); + _asian_full_width.set_inconsistent(_asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_FULL_WIDTH); + _asian_proportional_width.set_inconsistent(_asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_PROPORTIONAL_WIDTH); + _asian_ruby.set_inconsistent(_asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_RUBY); + + // Fix me: Should match a space if second part matches. ---, + // : Add boundary to 'on' and 'off'. v + Glib::RefPtr<Glib::Regex> regex = Glib::Regex::create("\"(\\w{4})\"\\s*([0-9]+|on|off|)"); + Glib::MatchInfo matchInfo; + std::string setting; + + // Set feature radiobutton (if it exists) or add to _feature_entry string. + char const *val = query->font_feature_settings.value(); + if (val) { + std::vector<Glib::ustring> tokens = Glib::Regex::split_simple("\\s*,\\s*", val); + + for (auto token : tokens) { + regex->match(token, matchInfo); + if (matchInfo.matches()) { + Glib::ustring table = matchInfo.fetch(1); + Glib::ustring value = matchInfo.fetch(2); + + if (_features.find(table) != _features.end()) { + int v = 0; + if (value == "0" || value == "off") + v = 0; + else if (value == "1" || value == "on" || value.empty()) + v = 1; + else + v = std::stoi(value); + _features[table]->set_active(v); + } else { + setting += token + ", "; + } + } + } + } + + // Remove final ", " + if (setting.length() > 1) { + setting.pop_back(); + setting.pop_back(); + } + + // Tables without radiobuttons. + _feature_entry.set_text(setting); + + if (different_features) { + _feature_label.show(); + } else { + _feature_label.hide(); + } +} + +// Update GUI based on OpenType tables of selected font (which may be changed in font selector tab). +void FontVariants::update_opentype(Glib::ustring &font_spec) +{ + // Disable/Enable based on available OpenType tables. + font_instance *res = font_factory::Default()->FaceFromFontSpecification(font_spec.c_str()); + if (res) { + std::map<Glib::ustring, OTSubstitution>::iterator it; + + if ((it = res->openTypeTables.find("liga")) != res->openTypeTables.end() || + (it = res->openTypeTables.find("clig")) != res->openTypeTables.end()) { + _ligatures_common.set_sensitive(); + } else { + _ligatures_common.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("dlig")) != res->openTypeTables.end()) { + _ligatures_discretionary.set_sensitive(); + } else { + _ligatures_discretionary.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("hlig")) != res->openTypeTables.end()) { + _ligatures_historical.set_sensitive(); + } else { + _ligatures_historical.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("calt")) != res->openTypeTables.end()) { + _ligatures_contextual.set_sensitive(); + } else { + _ligatures_contextual.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("subs")) != res->openTypeTables.end()) { + _position_sub.set_sensitive(); + } else { + _position_sub.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("sups")) != res->openTypeTables.end()) { + _position_super.set_sensitive(); + } else { + _position_super.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("smcp")) != res->openTypeTables.end()) { + _caps_small.set_sensitive(); + } else { + _caps_small.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("c2sc")) != res->openTypeTables.end() && + (it = res->openTypeTables.find("smcp")) != res->openTypeTables.end()) { + _caps_all_small.set_sensitive(); + } else { + _caps_all_small.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("pcap")) != res->openTypeTables.end()) { + _caps_petite.set_sensitive(); + } else { + _caps_petite.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("c2sc")) != res->openTypeTables.end() && + (it = res->openTypeTables.find("pcap")) != res->openTypeTables.end()) { + _caps_all_petite.set_sensitive(); + } else { + _caps_all_petite.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("unic")) != res->openTypeTables.end()) { + _caps_unicase.set_sensitive(); + } else { + _caps_unicase.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("titl")) != res->openTypeTables.end()) { + _caps_titling.set_sensitive(); + } else { + _caps_titling.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("lnum")) != res->openTypeTables.end()) { + _numeric_lining.set_sensitive(); + } else { + _numeric_lining.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("onum")) != res->openTypeTables.end()) { + _numeric_old_style.set_sensitive(); + } else { + _numeric_old_style.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("pnum")) != res->openTypeTables.end()) { + _numeric_proportional.set_sensitive(); + } else { + _numeric_proportional.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("tnum")) != res->openTypeTables.end()) { + _numeric_tabular.set_sensitive(); + } else { + _numeric_tabular.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("frac")) != res->openTypeTables.end()) { + _numeric_diagonal.set_sensitive(); + } else { + _numeric_diagonal.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("afrac")) != res->openTypeTables.end()) { + _numeric_stacked.set_sensitive(); + } else { + _numeric_stacked.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("ordn")) != res->openTypeTables.end()) { + _numeric_ordinal.set_sensitive(); + } else { + _numeric_ordinal.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("zero")) != res->openTypeTables.end()) { + _numeric_slashed_zero.set_sensitive(); + } else { + _numeric_slashed_zero.set_sensitive(false); + } + + // East-Asian + if ((it = res->openTypeTables.find("jp78")) != res->openTypeTables.end()) { + _asian_jis78.set_sensitive(); + } else { + _asian_jis78.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("jp83")) != res->openTypeTables.end()) { + _asian_jis83.set_sensitive(); + } else { + _asian_jis83.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("jp90")) != res->openTypeTables.end()) { + _asian_jis90.set_sensitive(); + } else { + _asian_jis90.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("jp04")) != res->openTypeTables.end()) { + _asian_jis04.set_sensitive(); + } else { + _asian_jis04.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("smpl")) != res->openTypeTables.end()) { + _asian_simplified.set_sensitive(); + } else { + _asian_simplified.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("trad")) != res->openTypeTables.end()) { + _asian_traditional.set_sensitive(); + } else { + _asian_traditional.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("fwid")) != res->openTypeTables.end()) { + _asian_full_width.set_sensitive(); + } else { + _asian_full_width.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("pwid")) != res->openTypeTables.end()) { + _asian_proportional_width.set_sensitive(); + } else { + _asian_proportional_width.set_sensitive(false); + } + + if ((it = res->openTypeTables.find("ruby")) != res->openTypeTables.end()) { + _asian_ruby.set_sensitive(); + } else { + _asian_ruby.set_sensitive(false); + } + + // List available ligatures + Glib::ustring markup_liga; + Glib::ustring markup_dlig; + Glib::ustring markup_hlig; + Glib::ustring markup_calt; + + for (auto table : res->openTypeTables) { + if (table.first == "liga" || table.first == "clig" || table.first == "dlig" || table.first == "hgli" || + table.first == "calt") { + Glib::ustring markup; + markup += "<span font_family='"; + markup += sp_font_description_get_family(res->descr); + markup += "'>"; + markup += Glib::Markup::escape_text(table.second.output); + markup += "</span>"; + + if (table.first == "liga") + markup_liga += markup; + if (table.first == "clig") + markup_liga += markup; + if (table.first == "dlig") + markup_dlig += markup; + if (table.first == "hlig") + markup_hlig += markup; + if (table.first == "calt") + markup_calt += markup; + } + } + + _ligatures_label_common.set_markup(markup_liga.c_str()); + _ligatures_label_discretionary.set_markup(markup_dlig.c_str()); + _ligatures_label_historical.set_markup(markup_hlig.c_str()); + _ligatures_label_contextual.set_markup(markup_calt.c_str()); + + // List available numeric variants + Glib::ustring markup_lnum; + Glib::ustring markup_onum; + Glib::ustring markup_pnum; + Glib::ustring markup_tnum; + Glib::ustring markup_frac; + Glib::ustring markup_afrc; + Glib::ustring markup_ordn; + Glib::ustring markup_zero; + + for (auto table : res->openTypeTables) { + Glib::ustring markup; + markup += "<span font_family='"; + markup += sp_font_description_get_family(res->descr); + markup += "' font_features='"; + markup += table.first; + markup += "'>"; + if (table.first == "lnum" || table.first == "onum" || table.first == "pnum" || table.first == "tnum") + markup += "0123456789"; + if (table.first == "zero") + markup += "0"; + if (table.first == "ordn") + markup += "[" + table.second.before + "]" + table.second.output; + if (table.first == "frac" || table.first == "afrc") + markup += "1/2 2/3 3/4 4/5 5/6"; // Can we do better? + markup += "</span>"; + + if (table.first == "lnum") + markup_lnum += markup; + if (table.first == "onum") + markup_onum += markup; + if (table.first == "pnum") + markup_pnum += markup; + if (table.first == "tnum") + markup_tnum += markup; + if (table.first == "frac") + markup_frac += markup; + if (table.first == "afrc") + markup_afrc += markup; + if (table.first == "ordn") + markup_ordn += markup; + if (table.first == "zero") + markup_zero += markup; + } + + _numeric_lining_label.set_markup(markup_lnum.c_str()); + _numeric_old_style_label.set_markup(markup_onum.c_str()); + _numeric_proportional_label.set_markup(markup_pnum.c_str()); + _numeric_tabular_label.set_markup(markup_tnum.c_str()); + _numeric_diagonal_label.set_markup(markup_frac.c_str()); + _numeric_stacked_label.set_markup(markup_afrc.c_str()); + _numeric_ordinal_label.set_markup(markup_ordn.c_str()); + _numeric_slashed_zero_label.set_markup(markup_zero.c_str()); + + // Make list of tables not handled above. + std::map<Glib::ustring, OTSubstitution> table_copy = res->openTypeTables; + if ((it = table_copy.find("liga")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("clig")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("dlig")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("hlig")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("calt")) != table_copy.end()) + table_copy.erase(it); + + if ((it = table_copy.find("subs")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("sups")) != table_copy.end()) + table_copy.erase(it); + + if ((it = table_copy.find("smcp")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("c2sc")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("pcap")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("c2pc")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("unic")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("titl")) != table_copy.end()) + table_copy.erase(it); + + if ((it = table_copy.find("lnum")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("onum")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("pnum")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("tnum")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("frac")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("afrc")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("ordn")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("zero")) != table_copy.end()) + table_copy.erase(it); + + if ((it = table_copy.find("jp78")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("jp83")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("jp90")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("jp04")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("smpl")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("trad")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("fwid")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("pwid")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("ruby")) != table_copy.end()) + table_copy.erase(it); + + // An incomplete list of tables that should not be exposed to the user: + if ((it = table_copy.find("abvf")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("abvs")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("akhn")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("blwf")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("blws")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("ccmp")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("cjct")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("dnom")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("dtls")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("fina")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("half")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("haln")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("init")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("isol")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("locl")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("medi")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("nukt")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("numr")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("pref")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("pres")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("pstf")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("psts")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("rlig")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("rkrf")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("rphf")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("rtlm")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("ssty")) != table_copy.end()) + table_copy.erase(it); + if ((it = table_copy.find("vatu")) != table_copy.end()) + table_copy.erase(it); + + // Clear out old features + auto children = _feature_grid.get_children(); + for (auto child : children) { + _feature_grid.remove(*child); + } + _features.clear(); + + std::string markup; + int grid_row = 0; + + // GSUB lookup type 1 (1 to 1 mapping). + for (auto table : res->openTypeTables) { + if (table.first == "case" || table.first == "hist" || + (table.first[0] == 's' && table.first[1] == 's' && !(table.first[2] == 't'))) { + if ((it = table_copy.find(table.first)) != table_copy.end()) + table_copy.erase(it); + + _features[table.first] = + new Feature(table.first, table.second, 2, sp_font_description_get_family(res->descr), _feature_grid, + grid_row, this); + grid_row++; + } + } + + // GSUB lookup type 3 (1 to many mapping). Optionally type 1. + for (auto table : res->openTypeTables) { + if (table.first == "salt" || table.first == "swsh" || table.first == "cwsh" || table.first == "ornm" || + table.first == "nalt" || (table.first[0] == 'c' && table.first[1] == 'v')) { + if (table.second.input.length() == 0) { + // This can happen if a table is not in the 'DFLT' script and 'dflt' language. + // We should be using the 'lang' attribute to find the correct tables. + // std::cerr << "FontVariants::open_type_update: " + // << table.first << " has no entries!" << std::endl; + continue; + } + + if ((it = table_copy.find(table.first)) != table_copy.end()) + table_copy.erase(it); + + // Our lame attempt at determining number of alternative glyphs for one glyph: + int number = table.second.output.length() / table.second.input.length(); + if (number < 1) { + number = 1; // Must have at least on/off, see comment above about 'lang' attribute. + // std::cout << table.first << " " + // << table.second.output.length() << "/" + // << table.second.input.length() << "=" + // << number << std::endl; + } + + _features[table.first] = + new Feature(table.first, table.second, number + 1, sp_font_description_get_family(res->descr), + _feature_grid, grid_row, this); + grid_row++; + } + } + + _feature_grid.show_all(); + + _feature_substitutions.set_markup(markup.c_str()); + + std::string ott_list = "OpenType tables not included above: "; + for (it = table_copy.begin(); it != table_copy.end(); ++it) { + ott_list += it->first; + ott_list += ", "; + } + + if (table_copy.size() > 0) { + ott_list.pop_back(); + ott_list.pop_back(); + _feature_list.set_text(ott_list.c_str()); + } else { + _feature_list.set_text(""); + } + + } else { + std::cerr << "FontVariants::update(): Couldn't find font_instance for: " << font_spec << std::endl; + } + + _ligatures_changed = false; + _position_changed = false; + _caps_changed = false; + _numeric_changed = false; + _feature_changed = false; +} + +void FontVariants::fill_css(SPCSSAttr *css) +{ + // Ligatures + bool common = _ligatures_common.get_active(); + bool discretionary = _ligatures_discretionary.get_active(); + bool historical = _ligatures_historical.get_active(); + bool contextual = _ligatures_contextual.get_active(); + + if (!common && !discretionary && !historical && !contextual) { + sp_repr_css_set_property(css, "font-variant-ligatures", "none"); + } else if (common && !discretionary && !historical && contextual) { + sp_repr_css_set_property(css, "font-variant-ligatures", "normal"); + } else { + Glib::ustring css_string; + if (!common) + css_string += "no-common-ligatures "; + if (discretionary) + css_string += "discretionary-ligatures "; + if (historical) + css_string += "historical-ligatures "; + if (!contextual) + css_string += "no-contextual "; + sp_repr_css_set_property(css, "font-variant-ligatures", css_string.c_str()); + } + + // Position + { + unsigned position_new = SP_CSS_FONT_VARIANT_POSITION_NORMAL; + Glib::ustring css_string; + if (_position_normal.get_active()) { + css_string = "normal"; + } else if (_position_sub.get_active()) { + css_string = "sub"; + position_new = SP_CSS_FONT_VARIANT_POSITION_SUB; + } else if (_position_super.get_active()) { + css_string = "super"; + position_new = SP_CSS_FONT_VARIANT_POSITION_SUPER; + } + + // 'if' may not be necessary... need to test. + if ((_position_all != position_new) || ((_position_mix != 0) && _position_changed)) { + sp_repr_css_set_property(css, "font-variant-position", css_string.c_str()); + } + } + + // Caps + { + // unsigned caps_new; + Glib::ustring css_string; + if (_caps_normal.get_active()) { + css_string = "normal"; + // caps_new = SP_CSS_FONT_VARIANT_CAPS_NORMAL; + } else if (_caps_small.get_active()) { + css_string = "small-caps"; + // caps_new = SP_CSS_FONT_VARIANT_CAPS_SMALL; + } else if (_caps_all_small.get_active()) { + css_string = "all-small-caps"; + // caps_new = SP_CSS_FONT_VARIANT_CAPS_ALL_SMALL; + } else if (_caps_petite.get_active()) { + css_string = "petite"; + // caps_new = SP_CSS_FONT_VARIANT_CAPS_PETITE; + } else if (_caps_all_petite.get_active()) { + css_string = "all-petite"; + // caps_new = SP_CSS_FONT_VARIANT_CAPS_ALL_PETITE; + } else if (_caps_unicase.get_active()) { + css_string = "unicase"; + // caps_new = SP_CSS_FONT_VARIANT_CAPS_UNICASE; + } else if (_caps_titling.get_active()) { + css_string = "titling"; + // caps_new = SP_CSS_FONT_VARIANT_CAPS_TITLING; + //} else { + // caps_new = SP_CSS_FONT_VARIANT_CAPS_NORMAL; + } + + // May not be necessary... need to test. + // if( (_caps_all != caps_new) || ((_caps_mix != 0) && _caps_changed) ) { + sp_repr_css_set_property(css, "font-variant-caps", css_string.c_str()); + //} + } + + // Numeric + bool default_style = _numeric_default_style.get_active(); + bool lining = _numeric_lining.get_active(); + bool old_style = _numeric_old_style.get_active(); + + bool default_width = _numeric_default_width.get_active(); + bool proportional = _numeric_proportional.get_active(); + bool tabular = _numeric_tabular.get_active(); + + bool default_fractions = _numeric_default_fractions.get_active(); + bool diagonal = _numeric_diagonal.get_active(); + bool stacked = _numeric_stacked.get_active(); + + bool ordinal = _numeric_ordinal.get_active(); + bool slashed_zero = _numeric_slashed_zero.get_active(); + + if (default_style & default_width & default_fractions & !ordinal & !slashed_zero) { + sp_repr_css_set_property(css, "font-variant-numeric", "normal"); + } else { + Glib::ustring css_string; + if (lining) + css_string += "lining-nums "; + if (old_style) + css_string += "oldstyle-nums "; + if (proportional) + css_string += "proportional-nums "; + if (tabular) + css_string += "tabular-nums "; + if (diagonal) + css_string += "diagonal-fractions "; + if (stacked) + css_string += "stacked-fractions "; + if (ordinal) + css_string += "ordinal "; + if (slashed_zero) + css_string += "slashed-zero "; + sp_repr_css_set_property(css, "font-variant-numeric", css_string.c_str()); + } - } - - void - FontVariants::ligatures_init() { - // std::cout << "FontVariants::ligatures_init()" << std::endl; - } - - void - FontVariants::ligatures_callback() { - // std::cout << "FontVariants::ligatures_callback()" << std::endl; - _ligatures_changed = true; - _changed_signal.emit(); - } - - void - FontVariants::position_init() { - // std::cout << "FontVariants::position_init()" << std::endl; - } - - void - FontVariants::position_callback() { - // std::cout << "FontVariants::position_callback()" << std::endl; - _position_changed = true; - _changed_signal.emit(); - } - - void - FontVariants::caps_init() { - // std::cout << "FontVariants::caps_init()" << std::endl; - } - - void - FontVariants::caps_callback() { - // std::cout << "FontVariants::caps_callback()" << std::endl; - _caps_changed = true; - _changed_signal.emit(); - } - - void - FontVariants::numeric_init() { - // std::cout << "FontVariants::numeric_init()" << std::endl; - } - - void - FontVariants::numeric_callback() { - // std::cout << "FontVariants::numeric_callback()" << std::endl; - _numeric_changed = true; - _changed_signal.emit(); - } - - void - FontVariants::asian_init() { - // std::cout << "FontVariants::asian_init()" << std::endl; - } - - void - FontVariants::asian_callback() { - // std::cout << "FontVariants::asian_callback()" << std::endl; - _asian_changed = true; - _changed_signal.emit(); - } - - void - FontVariants::feature_init() { - // std::cout << "FontVariants::feature_init()" << std::endl; - } - - void - FontVariants::feature_callback() { - // std::cout << "FontVariants::feature_callback()" << std::endl; - _feature_changed = true; - _changed_signal.emit(); - } - - // Update GUI based on query. - void - FontVariants::update( SPStyle const *query, bool different_features, Glib::ustring& font_spec ) { - - update_opentype( font_spec ); - - _ligatures_all = query->font_variant_ligatures.computed; - _ligatures_mix = query->font_variant_ligatures.value; - - _ligatures_common.set_active( _ligatures_all & SP_CSS_FONT_VARIANT_LIGATURES_COMMON ); - _ligatures_discretionary.set_active(_ligatures_all & SP_CSS_FONT_VARIANT_LIGATURES_DISCRETIONARY ); - _ligatures_historical.set_active( _ligatures_all & SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL ); - _ligatures_contextual.set_active( _ligatures_all & SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL ); - - _ligatures_common.set_inconsistent( _ligatures_mix & SP_CSS_FONT_VARIANT_LIGATURES_COMMON ); - _ligatures_discretionary.set_inconsistent( _ligatures_mix & SP_CSS_FONT_VARIANT_LIGATURES_DISCRETIONARY ); - _ligatures_historical.set_inconsistent( _ligatures_mix & SP_CSS_FONT_VARIANT_LIGATURES_HISTORICAL ); - _ligatures_contextual.set_inconsistent( _ligatures_mix & SP_CSS_FONT_VARIANT_LIGATURES_CONTEXTUAL ); - - _position_all = query->font_variant_position.computed; - _position_mix = query->font_variant_position.value; - - _position_normal.set_active( _position_all & SP_CSS_FONT_VARIANT_POSITION_NORMAL ); - _position_sub.set_active( _position_all & SP_CSS_FONT_VARIANT_POSITION_SUB ); - _position_super.set_active( _position_all & SP_CSS_FONT_VARIANT_POSITION_SUPER ); - - _position_normal.set_inconsistent( _position_mix & SP_CSS_FONT_VARIANT_POSITION_NORMAL ); - _position_sub.set_inconsistent( _position_mix & SP_CSS_FONT_VARIANT_POSITION_SUB ); - _position_super.set_inconsistent( _position_mix & SP_CSS_FONT_VARIANT_POSITION_SUPER ); - - _caps_all = query->font_variant_caps.computed; - _caps_mix = query->font_variant_caps.value; - - _caps_normal.set_active( _caps_all & SP_CSS_FONT_VARIANT_CAPS_NORMAL ); - _caps_small.set_active( _caps_all & SP_CSS_FONT_VARIANT_CAPS_SMALL ); - _caps_all_small.set_active( _caps_all & SP_CSS_FONT_VARIANT_CAPS_ALL_SMALL ); - _caps_petite.set_active( _caps_all & SP_CSS_FONT_VARIANT_CAPS_PETITE ); - _caps_all_petite.set_active( _caps_all & SP_CSS_FONT_VARIANT_CAPS_ALL_PETITE ); - _caps_unicase.set_active( _caps_all & SP_CSS_FONT_VARIANT_CAPS_UNICASE ); - _caps_titling.set_active( _caps_all & SP_CSS_FONT_VARIANT_CAPS_TITLING ); - - _caps_normal.set_inconsistent( _caps_mix & SP_CSS_FONT_VARIANT_CAPS_NORMAL ); - _caps_small.set_inconsistent( _caps_mix & SP_CSS_FONT_VARIANT_CAPS_SMALL ); - _caps_all_small.set_inconsistent( _caps_mix & SP_CSS_FONT_VARIANT_CAPS_ALL_SMALL ); - _caps_petite.set_inconsistent( _caps_mix & SP_CSS_FONT_VARIANT_CAPS_PETITE ); - _caps_all_petite.set_inconsistent( _caps_mix & SP_CSS_FONT_VARIANT_CAPS_ALL_PETITE ); - _caps_unicase.set_inconsistent( _caps_mix & SP_CSS_FONT_VARIANT_CAPS_UNICASE ); - _caps_titling.set_inconsistent( _caps_mix & SP_CSS_FONT_VARIANT_CAPS_TITLING ); - - _numeric_all = query->font_variant_numeric.computed; - _numeric_mix = query->font_variant_numeric.value; - - if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_LINING_NUMS) { - _numeric_lining.set_active(); - } else if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_OLDSTYLE_NUMS) { - _numeric_old_style.set_active(); - } else { - _numeric_default_style.set_active(); - } - - if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_PROPORTIONAL_NUMS) { - _numeric_proportional.set_active(); - } else if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_TABULAR_NUMS) { - _numeric_tabular.set_active(); - } else { - _numeric_default_width.set_active(); - } - - if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_DIAGONAL_FRACTIONS) { - _numeric_diagonal.set_active(); - } else if (_numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_STACKED_FRACTIONS) { - _numeric_stacked.set_active(); - } else { - _numeric_default_fractions.set_active(); - } - - _numeric_ordinal.set_active( _numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_ORDINAL ); - _numeric_slashed_zero.set_active( _numeric_all & SP_CSS_FONT_VARIANT_NUMERIC_SLASHED_ZERO ); - - - _numeric_lining.set_inconsistent( _numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_LINING_NUMS ); - _numeric_old_style.set_inconsistent( _numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_OLDSTYLE_NUMS ); - _numeric_proportional.set_inconsistent( _numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_PROPORTIONAL_NUMS ); - _numeric_tabular.set_inconsistent( _numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_TABULAR_NUMS ); - _numeric_diagonal.set_inconsistent( _numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_DIAGONAL_FRACTIONS ); - _numeric_stacked.set_inconsistent( _numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_STACKED_FRACTIONS ); - _numeric_ordinal.set_inconsistent( _numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_ORDINAL ); - _numeric_slashed_zero.set_inconsistent( _numeric_mix & SP_CSS_FONT_VARIANT_NUMERIC_SLASHED_ZERO ); - - _asian_all = query->font_variant_east_asian.computed; - _asian_mix = query->font_variant_east_asian.value; - - if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS78) { - _asian_jis78.set_active(); - } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS83) { - _asian_jis83.set_active(); - } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS90) { - _asian_jis90.set_active(); - } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS04) { - _asian_jis04.set_active(); - } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_SIMPLIFIED) { - _asian_simplified.set_active(); - } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_TRADITIONAL) { - _asian_traditional.set_active(); - } else { - _asian_default_variant.set_active(); - } - - if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_FULL_WIDTH) { - _asian_full_width.set_active(); - } else if (_asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_PROPORTIONAL_WIDTH) { - _asian_proportional_width.set_active(); - } else { - _asian_default_width.set_active(); - } - - _asian_ruby.set_active ( _asian_all & SP_CSS_FONT_VARIANT_EAST_ASIAN_RUBY ); - - _asian_jis78.set_inconsistent( _asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS78); - _asian_jis83.set_inconsistent( _asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS83); - _asian_jis90.set_inconsistent( _asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS90); - _asian_jis04.set_inconsistent( _asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_JIS04); - _asian_simplified.set_inconsistent( _asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_SIMPLIFIED); - _asian_traditional.set_inconsistent( _asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_TRADITIONAL); - _asian_full_width.set_inconsistent( _asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_FULL_WIDTH); - _asian_proportional_width.set_inconsistent(_asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_PROPORTIONAL_WIDTH); - _asian_ruby.set_inconsistent( _asian_mix & SP_CSS_FONT_VARIANT_EAST_ASIAN_RUBY); - - // Fix me: Should match a space if second part matches. ---, - // : Add boundary to 'on' and 'off'. v - Glib::RefPtr<Glib::Regex> regex = Glib::Regex::create("\"(\\w{4})\"\\s*([0-9]+|on|off|)"); - Glib::MatchInfo matchInfo; - std::string setting; - - // Set feature radiobutton (if it exists) or add to _feature_entry string. - char const *val = query->font_feature_settings.value(); - if (val) { - - std::vector<Glib::ustring> tokens = - Glib::Regex::split_simple("\\s*,\\s*", val); - - for (auto token: tokens) { - regex->match(token, matchInfo); - if (matchInfo.matches()) { - Glib::ustring table = matchInfo.fetch(1); - Glib::ustring value = matchInfo.fetch(2); - - if (_features.find(table) != _features.end()) { - int v = 0; - if (value == "0" || value == "off") v = 0; - else if (value == "1" || value == "on" || value.empty() ) v = 1; - else v = std::stoi(value); - _features[table]->set_active(v); - } else { - setting += token + ", "; - } - } - } - } - - // Remove final ", " - if (setting.length() > 1) { - setting.pop_back(); - setting.pop_back(); - } - - // Tables without radiobuttons. - _feature_entry.set_text( setting ); - - if( different_features ) { - _feature_label.show(); - } else { - _feature_label.hide(); - } - } - - // Update GUI based on OpenType tables of selected font (which may be changed in font selector tab). - void - FontVariants::update_opentype (Glib::ustring& font_spec) { - - // Disable/Enable based on available OpenType tables. - font_instance* res = font_factory::Default()->FaceFromFontSpecification( font_spec.c_str() ); - if( res ) { - - std::map<Glib::ustring, OTSubstitution>::iterator it; - - if((it = res->openTypeTables.find("liga"))!= res->openTypeTables.end() || - (it = res->openTypeTables.find("clig"))!= res->openTypeTables.end()) { - _ligatures_common.set_sensitive(); - } else { - _ligatures_common.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("dlig"))!= res->openTypeTables.end()) { - _ligatures_discretionary.set_sensitive(); - } else { - _ligatures_discretionary.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("hlig"))!= res->openTypeTables.end()) { - _ligatures_historical.set_sensitive(); - } else { - _ligatures_historical.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("calt"))!= res->openTypeTables.end()) { - _ligatures_contextual.set_sensitive(); - } else { - _ligatures_contextual.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("subs"))!= res->openTypeTables.end()) { - _position_sub.set_sensitive(); - } else { - _position_sub.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("sups"))!= res->openTypeTables.end()) { - _position_super.set_sensitive(); - } else { - _position_super.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("smcp"))!= res->openTypeTables.end()) { - _caps_small.set_sensitive(); - } else { - _caps_small.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("c2sc"))!= res->openTypeTables.end() && - (it = res->openTypeTables.find("smcp"))!= res->openTypeTables.end()) { - _caps_all_small.set_sensitive(); - } else { - _caps_all_small.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("pcap"))!= res->openTypeTables.end()) { - _caps_petite.set_sensitive(); - } else { - _caps_petite.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("c2sc"))!= res->openTypeTables.end() && - (it = res->openTypeTables.find("pcap"))!= res->openTypeTables.end()) { - _caps_all_petite.set_sensitive(); - } else { - _caps_all_petite.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("unic"))!= res->openTypeTables.end()) { - _caps_unicase.set_sensitive(); - } else { - _caps_unicase.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("titl"))!= res->openTypeTables.end()) { - _caps_titling.set_sensitive(); - } else { - _caps_titling.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("lnum"))!= res->openTypeTables.end()) { - _numeric_lining.set_sensitive(); - } else { - _numeric_lining.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("onum"))!= res->openTypeTables.end()) { - _numeric_old_style.set_sensitive(); - } else { - _numeric_old_style.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("pnum"))!= res->openTypeTables.end()) { - _numeric_proportional.set_sensitive(); - } else { - _numeric_proportional.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("tnum"))!= res->openTypeTables.end()) { - _numeric_tabular.set_sensitive(); - } else { - _numeric_tabular.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("frac"))!= res->openTypeTables.end()) { - _numeric_diagonal.set_sensitive(); - } else { - _numeric_diagonal.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("afrac"))!= res->openTypeTables.end()) { - _numeric_stacked.set_sensitive(); - } else { - _numeric_stacked.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("ordn"))!= res->openTypeTables.end()) { - _numeric_ordinal.set_sensitive(); - } else { - _numeric_ordinal.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("zero"))!= res->openTypeTables.end()) { - _numeric_slashed_zero.set_sensitive(); - } else { - _numeric_slashed_zero.set_sensitive( false ); - } - - // East-Asian - if((it = res->openTypeTables.find("jp78"))!= res->openTypeTables.end()) { - _asian_jis78.set_sensitive(); - } else { - _asian_jis78.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("jp83"))!= res->openTypeTables.end()) { - _asian_jis83.set_sensitive(); - } else { - _asian_jis83.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("jp90"))!= res->openTypeTables.end()) { - _asian_jis90.set_sensitive(); - } else { - _asian_jis90.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("jp04"))!= res->openTypeTables.end()) { - _asian_jis04.set_sensitive(); - } else { - _asian_jis04.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("smpl"))!= res->openTypeTables.end()) { - _asian_simplified.set_sensitive(); - } else { - _asian_simplified.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("trad"))!= res->openTypeTables.end()) { - _asian_traditional.set_sensitive(); - } else { - _asian_traditional.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("fwid"))!= res->openTypeTables.end()) { - _asian_full_width.set_sensitive(); - } else { - _asian_full_width.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("pwid"))!= res->openTypeTables.end()) { - _asian_proportional_width.set_sensitive(); - } else { - _asian_proportional_width.set_sensitive( false ); - } - - if((it = res->openTypeTables.find("ruby"))!= res->openTypeTables.end()) { - _asian_ruby.set_sensitive(); - } else { - _asian_ruby.set_sensitive( false ); - } - - // List available ligatures - Glib::ustring markup_liga; - Glib::ustring markup_dlig; - Glib::ustring markup_hlig; - Glib::ustring markup_calt; - - for (auto table: res->openTypeTables) { - - if (table.first == "liga" || - table.first == "clig" || - table.first == "dlig" || - table.first == "hgli" || - table.first == "calt") { - - Glib::ustring markup; - markup += "<span font_family='"; - markup += sp_font_description_get_family(res->descr); - markup += "'>"; - markup += Glib::Markup::escape_text(table.second.output); - markup += "</span>"; - - if (table.first == "liga") markup_liga += markup; - if (table.first == "clig") markup_liga += markup; - if (table.first == "dlig") markup_dlig += markup; - if (table.first == "hlig") markup_hlig += markup; - if (table.first == "calt") markup_calt += markup; - } - } - - _ligatures_label_common.set_markup ( markup_liga.c_str() ); - _ligatures_label_discretionary.set_markup ( markup_dlig.c_str() ); - _ligatures_label_historical.set_markup ( markup_hlig.c_str() ); - _ligatures_label_contextual.set_markup ( markup_calt.c_str() ); - - // List available numeric variants - Glib::ustring markup_lnum; - Glib::ustring markup_onum; - Glib::ustring markup_pnum; - Glib::ustring markup_tnum; - Glib::ustring markup_frac; - Glib::ustring markup_afrc; - Glib::ustring markup_ordn; - Glib::ustring markup_zero; - - for (auto table: res->openTypeTables) { - - Glib::ustring markup; - markup += "<span font_family='"; - markup += sp_font_description_get_family(res->descr); - markup += "' font_features='"; - markup += table.first; - markup += "'>"; - if (table.first == "lnum" || - table.first == "onum" || - table.first == "pnum" || - table.first == "tnum") markup += "0123456789"; - if (table.first == "zero") markup += "0"; - if (table.first == "ordn") markup += "[" + table.second.before + "]" + table.second.output; - if (table.first == "frac" || - table.first == "afrc" ) markup += "1/2 2/3 3/4 4/5 5/6"; // Can we do better? - markup += "</span>"; - - if (table.first == "lnum") markup_lnum += markup; - if (table.first == "onum") markup_onum += markup; - if (table.first == "pnum") markup_pnum += markup; - if (table.first == "tnum") markup_tnum += markup; - if (table.first == "frac") markup_frac += markup; - if (table.first == "afrc") markup_afrc += markup; - if (table.first == "ordn") markup_ordn += markup; - if (table.first == "zero") markup_zero += markup; - } - - _numeric_lining_label.set_markup ( markup_lnum.c_str() ); - _numeric_old_style_label.set_markup ( markup_onum.c_str() ); - _numeric_proportional_label.set_markup ( markup_pnum.c_str() ); - _numeric_tabular_label.set_markup ( markup_tnum.c_str() ); - _numeric_diagonal_label.set_markup ( markup_frac.c_str() ); - _numeric_stacked_label.set_markup ( markup_afrc.c_str() ); - _numeric_ordinal_label.set_markup ( markup_ordn.c_str() ); - _numeric_slashed_zero_label.set_markup ( markup_zero.c_str() ); - - // Make list of tables not handled above. - std::map<Glib::ustring, OTSubstitution> table_copy = res->openTypeTables; - if( (it = table_copy.find("liga")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("clig")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("dlig")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("hlig")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("calt")) != table_copy.end() ) table_copy.erase( it ); - - if( (it = table_copy.find("subs")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("sups")) != table_copy.end() ) table_copy.erase( it ); - - if( (it = table_copy.find("smcp")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("c2sc")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("pcap")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("c2pc")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("unic")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("titl")) != table_copy.end() ) table_copy.erase( it ); - - if( (it = table_copy.find("lnum")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("onum")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("pnum")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("tnum")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("frac")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("afrc")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("ordn")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("zero")) != table_copy.end() ) table_copy.erase( it ); - - if( (it = table_copy.find("jp78")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("jp83")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("jp90")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("jp04")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("smpl")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("trad")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("fwid")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("pwid")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("ruby")) != table_copy.end() ) table_copy.erase( it ); - - // An incomplete list of tables that should not be exposed to the user: - if( (it = table_copy.find("abvf")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("abvs")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("akhn")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("blwf")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("blws")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("ccmp")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("cjct")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("dnom")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("dtls")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("fina")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("half")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("haln")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("init")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("isol")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("locl")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("medi")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("nukt")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("numr")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("pref")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("pres")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("pstf")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("psts")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("rlig")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("rkrf")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("rphf")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("rtlm")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("ssty")) != table_copy.end() ) table_copy.erase( it ); - if( (it = table_copy.find("vatu")) != table_copy.end() ) table_copy.erase( it ); - - // Clear out old features - auto children = _feature_grid.get_children(); - for (auto child: children) { - _feature_grid.remove (*child); - } - _features.clear(); - - std::string markup; - int grid_row = 0; - - // GSUB lookup type 1 (1 to 1 mapping). - for (auto table: res->openTypeTables) { - if (table.first == "case" || - table.first == "hist" || - (table.first[0] == 's' && table.first[1] == 's' && !(table.first[2] == 't'))) { - - if( (it = table_copy.find(table.first)) != table_copy.end() ) table_copy.erase( it ); - - _features[table.first] = new Feature (table.first, table.second, 2, - sp_font_description_get_family(res->descr), - _feature_grid, grid_row, this); - grid_row++; - } - } - - // GSUB lookup type 3 (1 to many mapping). Optionally type 1. - for (auto table: res->openTypeTables) { - if (table.first == "salt" || - table.first == "swsh" || - table.first == "cwsh" || - table.first == "ornm" || - table.first == "nalt" || - (table.first[0] == 'c' && table.first[1] == 'v')) { - - if (table.second.input.length() == 0) { - // This can happen if a table is not in the 'DFLT' script and 'dflt' language. - // We should be using the 'lang' attribute to find the correct tables. - // std::cerr << "FontVariants::open_type_update: " - // << table.first << " has no entries!" << std::endl; - continue; - } - - if( (it = table_copy.find(table.first)) != table_copy.end() ) table_copy.erase( it ); - - // Our lame attempt at determining number of alternative glyphs for one glyph: - int number = table.second.output.length() / table.second.input.length(); - if (number < 1) { - number = 1; // Must have at least on/off, see comment above about 'lang' attribute. - // std::cout << table.first << " " - // << table.second.output.length() << "/" - // << table.second.input.length() << "=" - // << number << std::endl; - } - - _features[table.first] = new Feature (table.first, table.second, number+1, - sp_font_description_get_family(res->descr), - _feature_grid, grid_row, this); - grid_row++; - } - } - - _feature_grid.show_all(); - - _feature_substitutions.set_markup ( markup.c_str() ); - - std::string ott_list = "OpenType tables not included above: "; - for(it = table_copy.begin(); it != table_copy.end(); ++it) { - ott_list += it->first; - ott_list += ", "; - } - - if (table_copy.size() > 0) { - ott_list.pop_back(); - ott_list.pop_back(); - _feature_list.set_text( ott_list.c_str() ); - } else { - _feature_list.set_text( "" ); - } - - } else { - std::cerr << "FontVariants::update(): Couldn't find font_instance for: " - << font_spec << std::endl; - } - - _ligatures_changed = false; - _position_changed = false; - _caps_changed = false; - _numeric_changed = false; - _feature_changed = false; - } - - void - FontVariants::fill_css( SPCSSAttr *css ) { - - // Ligatures - bool common = _ligatures_common.get_active(); - bool discretionary = _ligatures_discretionary.get_active(); - bool historical = _ligatures_historical.get_active(); - bool contextual = _ligatures_contextual.get_active(); - - if( !common && !discretionary && !historical && !contextual ) { - sp_repr_css_set_property(css, "font-variant-ligatures", "none" ); - } else if ( common && !discretionary && !historical && contextual ) { - sp_repr_css_set_property(css, "font-variant-ligatures", "normal" ); - } else { - Glib::ustring css_string; - if ( !common ) - css_string += "no-common-ligatures "; - if ( discretionary ) - css_string += "discretionary-ligatures "; - if ( historical ) - css_string += "historical-ligatures "; - if ( !contextual ) - css_string += "no-contextual "; - sp_repr_css_set_property(css, "font-variant-ligatures", css_string.c_str() ); - } - - // Position - { - unsigned position_new = SP_CSS_FONT_VARIANT_POSITION_NORMAL; - Glib::ustring css_string; - if( _position_normal.get_active() ) { - css_string = "normal"; - } else if( _position_sub.get_active() ) { - css_string = "sub"; - position_new = SP_CSS_FONT_VARIANT_POSITION_SUB; - } else if( _position_super.get_active() ) { - css_string = "super"; - position_new = SP_CSS_FONT_VARIANT_POSITION_SUPER; - } - - // 'if' may not be necessary... need to test. - if( (_position_all != position_new) || ((_position_mix != 0) && _position_changed) ) { - sp_repr_css_set_property(css, "font-variant-position", css_string.c_str() ); - } - } - - // Caps - { - //unsigned caps_new; - Glib::ustring css_string; - if( _caps_normal.get_active() ) { - css_string = "normal"; - // caps_new = SP_CSS_FONT_VARIANT_CAPS_NORMAL; - } else if( _caps_small.get_active() ) { - css_string = "small-caps"; - // caps_new = SP_CSS_FONT_VARIANT_CAPS_SMALL; - } else if( _caps_all_small.get_active() ) { - css_string = "all-small-caps"; - // caps_new = SP_CSS_FONT_VARIANT_CAPS_ALL_SMALL; - } else if( _caps_petite.get_active() ) { - css_string = "petite"; - // caps_new = SP_CSS_FONT_VARIANT_CAPS_PETITE; - } else if( _caps_all_petite.get_active() ) { - css_string = "all-petite"; - // caps_new = SP_CSS_FONT_VARIANT_CAPS_ALL_PETITE; - } else if( _caps_unicase.get_active() ) { - css_string = "unicase"; - // caps_new = SP_CSS_FONT_VARIANT_CAPS_UNICASE; - } else if( _caps_titling.get_active() ) { - css_string = "titling"; - // caps_new = SP_CSS_FONT_VARIANT_CAPS_TITLING; - //} else { - // caps_new = SP_CSS_FONT_VARIANT_CAPS_NORMAL; - } - - // May not be necessary... need to test. - //if( (_caps_all != caps_new) || ((_caps_mix != 0) && _caps_changed) ) { - sp_repr_css_set_property(css, "font-variant-caps", css_string.c_str() ); - //} - } - - // Numeric - bool default_style = _numeric_default_style.get_active(); - bool lining = _numeric_lining.get_active(); - bool old_style = _numeric_old_style.get_active(); - - bool default_width = _numeric_default_width.get_active(); - bool proportional = _numeric_proportional.get_active(); - bool tabular = _numeric_tabular.get_active(); - - bool default_fractions = _numeric_default_fractions.get_active(); - bool diagonal = _numeric_diagonal.get_active(); - bool stacked = _numeric_stacked.get_active(); - - bool ordinal = _numeric_ordinal.get_active(); - bool slashed_zero = _numeric_slashed_zero.get_active(); - - if (default_style & default_width & default_fractions & !ordinal & !slashed_zero) { - sp_repr_css_set_property(css, "font-variant-numeric", "normal"); - } else { - Glib::ustring css_string; - if ( lining ) - css_string += "lining-nums "; - if ( old_style ) - css_string += "oldstyle-nums "; - if ( proportional ) - css_string += "proportional-nums "; - if ( tabular ) - css_string += "tabular-nums "; - if ( diagonal ) - css_string += "diagonal-fractions "; - if ( stacked ) - css_string += "stacked-fractions "; - if ( ordinal ) - css_string += "ordinal "; - if ( slashed_zero ) - css_string += "slashed-zero "; - sp_repr_css_set_property(css, "font-variant-numeric", css_string.c_str() ); - } - - // East Asian - bool jis78 = _asian_jis78.get_active(); - bool jis83 = _asian_jis83.get_active(); - bool jis90 = _asian_jis90.get_active(); - bool jis04 = _asian_jis04.get_active(); - bool simplified = _asian_simplified.get_active(); - bool traditional = _asian_traditional.get_active(); - bool asian_width = _asian_default_width.get_active(); - bool fwid = _asian_full_width.get_active(); - bool pwid = _asian_proportional_width.get_active(); - bool ruby = _asian_ruby.get_active(); - - if (default_style & asian_width & !ruby) { - sp_repr_css_set_property(css, "font-variant-east-asian", "normal"); - } else { - Glib::ustring css_string; - if (jis78) css_string += "jis78 "; - if (jis83) css_string += "jis83 "; - if (jis90) css_string += "jis90 "; - if (jis04) css_string += "jis04 "; - if (simplified) css_string += "simplfied "; - if (traditional) css_string += "traditional "; - - if (fwid) css_string += "fwid "; - if (pwid) css_string += "pwid "; - - if (ruby) css_string += "ruby "; - - sp_repr_css_set_property(css, "font-variant-east-asian", css_string.c_str() ); - } - - // Feature settings - Glib::ustring feature_string; - for (auto i: _features) { - feature_string += i.second->get_css(); - } - - feature_string += _feature_entry.get_text(); - // std::cout << "feature_string: " << feature_string << std::endl; - - if (!feature_string.empty()) { - sp_repr_css_set_property(css, "font-feature-settings", feature_string.c_str()); - } else { - sp_repr_css_unset_property(css, "font-feature-settings"); - } - } - - Glib::ustring - FontVariants::get_markup() { - - Glib::ustring markup; - - // Ligatures - bool common = _ligatures_common.get_active(); - bool discretionary = _ligatures_discretionary.get_active(); - bool historical = _ligatures_historical.get_active(); - bool contextual = _ligatures_contextual.get_active(); - - if (!common) markup += "liga=0,clig=0,"; // On by default. - if (discretionary) markup += "dlig=1,"; - if (historical) markup += "hlig=1,"; - if (contextual) markup += "calt=1,"; - - // Position - if ( _position_sub.get_active() ) markup += "subs=1,"; - else if ( _position_super.get_active() ) markup += "sups=1,"; - - // Caps - if ( _caps_small.get_active() ) markup += "smcp=1,"; - else if ( _caps_all_small.get_active() ) markup += "c2sc=1,smcp=1,"; - else if ( _caps_petite.get_active() ) markup += "pcap=1,"; - else if ( _caps_all_petite.get_active() ) markup += "c2pc=1,pcap=1,"; - else if ( _caps_unicase.get_active() ) markup += "unic=1,"; - else if ( _caps_titling.get_active() ) markup += "titl=1,"; - - // Numeric - bool lining = _numeric_lining.get_active(); - bool old_style = _numeric_old_style.get_active(); - - bool proportional = _numeric_proportional.get_active(); - bool tabular = _numeric_tabular.get_active(); - - bool diagonal = _numeric_diagonal.get_active(); - bool stacked = _numeric_stacked.get_active(); - - bool ordinal = _numeric_ordinal.get_active(); - bool slashed_zero = _numeric_slashed_zero.get_active(); - - if (lining) markup += "lnum=1,"; - if (old_style) markup += "onum=1,"; - if (proportional) markup += "pnum=1,"; - if (tabular) markup += "tnum=1,"; - if (diagonal) markup += "frac=1,"; - if (stacked) markup += "afrc=1,"; - if (ordinal) markup += "ordn=1,"; - if (slashed_zero) markup += "zero=1,"; - - // East Asian - bool jis78 = _asian_jis78.get_active(); - bool jis83 = _asian_jis83.get_active(); - bool jis90 = _asian_jis90.get_active(); - bool jis04 = _asian_jis04.get_active(); - bool simplified = _asian_simplified.get_active(); - bool traditional = _asian_traditional.get_active(); - //bool asian_width = _asian_default_width.get_active(); - bool fwid = _asian_full_width.get_active(); - bool pwid = _asian_proportional_width.get_active(); - bool ruby = _asian_ruby.get_active(); - - if (jis78 ) markup += "jp78=1,"; - if (jis83 ) markup += "jp83=1,"; - if (jis90 ) markup += "jp90=1,"; - if (jis04 ) markup += "jp04=1,"; - if (simplified ) markup += "smpl=1,"; - if (traditional ) markup += "trad=1,"; - - if (fwid ) markup += "fwid=1,"; - if (pwid ) markup += "pwid=1,"; - - if (ruby ) markup += "ruby=1,"; - - // Feature settings - Glib::ustring feature_string; - for (auto i: _features) { - feature_string += i.second->get_css(); - } - - feature_string += _feature_entry.get_text(); - if (!feature_string.empty()) { - markup += feature_string; - } - - // std::cout << "|" << markup << "|" << std::endl; - return markup; - } + // East Asian + bool jis78 = _asian_jis78.get_active(); + bool jis83 = _asian_jis83.get_active(); + bool jis90 = _asian_jis90.get_active(); + bool jis04 = _asian_jis04.get_active(); + bool simplified = _asian_simplified.get_active(); + bool traditional = _asian_traditional.get_active(); + bool asian_width = _asian_default_width.get_active(); + bool fwid = _asian_full_width.get_active(); + bool pwid = _asian_proportional_width.get_active(); + bool ruby = _asian_ruby.get_active(); + + if (default_style & asian_width & !ruby) { + sp_repr_css_set_property(css, "font-variant-east-asian", "normal"); + } else { + Glib::ustring css_string; + if (jis78) + css_string += "jis78 "; + if (jis83) + css_string += "jis83 "; + if (jis90) + css_string += "jis90 "; + if (jis04) + css_string += "jis04 "; + if (simplified) + css_string += "simplfied "; + if (traditional) + css_string += "traditional "; + + if (fwid) + css_string += "fwid "; + if (pwid) + css_string += "pwid "; + + if (ruby) + css_string += "ruby "; + + sp_repr_css_set_property(css, "font-variant-east-asian", css_string.c_str()); + } + + // Feature settings + Glib::ustring feature_string; + for (auto i : _features) { + feature_string += i.second->get_css(); + } + + feature_string += _feature_entry.get_text(); + // std::cout << "feature_string: " << feature_string << std::endl; + + if (!feature_string.empty()) { + sp_repr_css_set_property(css, "font-feature-settings", feature_string.c_str()); + } else { + sp_repr_css_unset_property(css, "font-feature-settings"); + } +} + +Glib::ustring FontVariants::get_markup() +{ + Glib::ustring markup; + + // Ligatures + bool common = _ligatures_common.get_active(); + bool discretionary = _ligatures_discretionary.get_active(); + bool historical = _ligatures_historical.get_active(); + bool contextual = _ligatures_contextual.get_active(); + + if (!common) + markup += "liga=0,clig=0,"; // On by default. + if (discretionary) + markup += "dlig=1,"; + if (historical) + markup += "hlig=1,"; + if (contextual) + markup += "calt=1,"; + + // Position + if (_position_sub.get_active()) + markup += "subs=1,"; + else if (_position_super.get_active()) + markup += "sups=1,"; + + // Caps + if (_caps_small.get_active()) + markup += "smcp=1,"; + else if (_caps_all_small.get_active()) + markup += "c2sc=1,smcp=1,"; + else if (_caps_petite.get_active()) + markup += "pcap=1,"; + else if (_caps_all_petite.get_active()) + markup += "c2pc=1,pcap=1,"; + else if (_caps_unicase.get_active()) + markup += "unic=1,"; + else if (_caps_titling.get_active()) + markup += "titl=1,"; + + // Numeric + bool lining = _numeric_lining.get_active(); + bool old_style = _numeric_old_style.get_active(); + + bool proportional = _numeric_proportional.get_active(); + bool tabular = _numeric_tabular.get_active(); + + bool diagonal = _numeric_diagonal.get_active(); + bool stacked = _numeric_stacked.get_active(); + + bool ordinal = _numeric_ordinal.get_active(); + bool slashed_zero = _numeric_slashed_zero.get_active(); + + if (lining) + markup += "lnum=1,"; + if (old_style) + markup += "onum=1,"; + if (proportional) + markup += "pnum=1,"; + if (tabular) + markup += "tnum=1,"; + if (diagonal) + markup += "frac=1,"; + if (stacked) + markup += "afrc=1,"; + if (ordinal) + markup += "ordn=1,"; + if (slashed_zero) + markup += "zero=1,"; + + // East Asian + bool jis78 = _asian_jis78.get_active(); + bool jis83 = _asian_jis83.get_active(); + bool jis90 = _asian_jis90.get_active(); + bool jis04 = _asian_jis04.get_active(); + bool simplified = _asian_simplified.get_active(); + bool traditional = _asian_traditional.get_active(); + // bool asian_width = _asian_default_width.get_active(); + bool fwid = _asian_full_width.get_active(); + bool pwid = _asian_proportional_width.get_active(); + bool ruby = _asian_ruby.get_active(); + + if (jis78) + markup += "jp78=1,"; + if (jis83) + markup += "jp83=1,"; + if (jis90) + markup += "jp90=1,"; + if (jis04) + markup += "jp04=1,"; + if (simplified) + markup += "smpl=1,"; + if (traditional) + markup += "trad=1,"; + + if (fwid) + markup += "fwid=1,"; + if (pwid) + markup += "pwid=1,"; + + if (ruby) + markup += "ruby=1,"; + + // Feature settings + Glib::ustring feature_string; + for (auto i : _features) { + feature_string += i.second->get_css(); + } + + feature_string += _feature_entry.get_text(); + if (!feature_string.empty()) { + markup += feature_string; + } + + // std::cout << "|" << markup << "|" << std::endl; + return markup; +} } // namespace Widget } // namespace UI diff --git a/src/ui/widget/font-variants.h b/src/ui/widget/font-variants.h index c3201a2ef5311713202cab7c21efe8cc5c2bf90b..4fbfc12daa37a9675880d73cbc96376538737811 100644 --- a/src/ui/widget/font-variants.h +++ b/src/ui/widget/font-variants.h @@ -11,12 +11,12 @@ #ifndef INKSCAPE_UI_WIDGET_FONT_VARIANT_H #define INKSCAPE_UI_WIDGET_FONT_VARIANT_H -#include <gtkmm/expander.h> #include <gtkmm/checkbutton.h> -#include <gtkmm/radiobutton.h> #include <gtkmm/entry.h> +#include <gtkmm/expander.h> #include <gtkmm/grid.h> #include <gtkmm/hvbox.h> +#include <gtkmm/radiobutton.h> class SPDesktop; class SPObject; @@ -34,9 +34,7 @@ class Feature; */ class FontVariants : public Gtk::VBox { - public: - /** * Constructor */ @@ -44,89 +42,89 @@ public: protected: // Ligatures: To start, use four check buttons. - Gtk::Expander _ligatures_frame; - Gtk::Grid _ligatures_grid; - Gtk::CheckButton _ligatures_common; - Gtk::CheckButton _ligatures_discretionary; - Gtk::CheckButton _ligatures_historical; - Gtk::CheckButton _ligatures_contextual; - Gtk::Label _ligatures_label_common; - Gtk::Label _ligatures_label_discretionary; - Gtk::Label _ligatures_label_historical; - Gtk::Label _ligatures_label_contextual; + Gtk::Expander _ligatures_frame; + Gtk::Grid _ligatures_grid; + Gtk::CheckButton _ligatures_common; + Gtk::CheckButton _ligatures_discretionary; + Gtk::CheckButton _ligatures_historical; + Gtk::CheckButton _ligatures_contextual; + Gtk::Label _ligatures_label_common; + Gtk::Label _ligatures_label_discretionary; + Gtk::Label _ligatures_label_historical; + Gtk::Label _ligatures_label_contextual; // Position: Exclusive options - Gtk::Expander _position_frame; - Gtk::Grid _position_grid; - Gtk::RadioButton _position_normal; - Gtk::RadioButton _position_sub; - Gtk::RadioButton _position_super; - + Gtk::Expander _position_frame; + Gtk::Grid _position_grid; + Gtk::RadioButton _position_normal; + Gtk::RadioButton _position_sub; + Gtk::RadioButton _position_super; + // Caps: Exclusive options (maybe a dropdown menu to save space?) - Gtk::Expander _caps_frame; - Gtk::Grid _caps_grid; - Gtk::RadioButton _caps_normal; - Gtk::RadioButton _caps_small; - Gtk::RadioButton _caps_all_small; - Gtk::RadioButton _caps_petite; - Gtk::RadioButton _caps_all_petite; - Gtk::RadioButton _caps_unicase; - Gtk::RadioButton _caps_titling; + Gtk::Expander _caps_frame; + Gtk::Grid _caps_grid; + Gtk::RadioButton _caps_normal; + Gtk::RadioButton _caps_small; + Gtk::RadioButton _caps_all_small; + Gtk::RadioButton _caps_petite; + Gtk::RadioButton _caps_all_petite; + Gtk::RadioButton _caps_unicase; + Gtk::RadioButton _caps_titling; // Numeric: Complicated! - Gtk::Expander _numeric_frame; - Gtk::Grid _numeric_grid; + Gtk::Expander _numeric_frame; + Gtk::Grid _numeric_grid; - Gtk::RadioButton _numeric_default_style; - Gtk::RadioButton _numeric_lining; - Gtk::Label _numeric_lining_label; - Gtk::RadioButton _numeric_old_style; - Gtk::Label _numeric_old_style_label; + Gtk::RadioButton _numeric_default_style; + Gtk::RadioButton _numeric_lining; + Gtk::Label _numeric_lining_label; + Gtk::RadioButton _numeric_old_style; + Gtk::Label _numeric_old_style_label; - Gtk::RadioButton _numeric_default_width; - Gtk::RadioButton _numeric_proportional; - Gtk::Label _numeric_proportional_label; - Gtk::RadioButton _numeric_tabular; - Gtk::Label _numeric_tabular_label; + Gtk::RadioButton _numeric_default_width; + Gtk::RadioButton _numeric_proportional; + Gtk::Label _numeric_proportional_label; + Gtk::RadioButton _numeric_tabular; + Gtk::Label _numeric_tabular_label; - Gtk::RadioButton _numeric_default_fractions; - Gtk::RadioButton _numeric_diagonal; - Gtk::Label _numeric_diagonal_label; - Gtk::RadioButton _numeric_stacked; - Gtk::Label _numeric_stacked_label; + Gtk::RadioButton _numeric_default_fractions; + Gtk::RadioButton _numeric_diagonal; + Gtk::Label _numeric_diagonal_label; + Gtk::RadioButton _numeric_stacked; + Gtk::Label _numeric_stacked_label; - Gtk::CheckButton _numeric_ordinal; - Gtk::Label _numeric_ordinal_label; + Gtk::CheckButton _numeric_ordinal; + Gtk::Label _numeric_ordinal_label; - Gtk::CheckButton _numeric_slashed_zero; - Gtk::Label _numeric_slashed_zero_label; + Gtk::CheckButton _numeric_slashed_zero; + Gtk::Label _numeric_slashed_zero_label; // East Asian: Complicated! - Gtk::Expander _asian_frame; - Gtk::Grid _asian_grid; + Gtk::Expander _asian_frame; + Gtk::Grid _asian_grid; - Gtk::RadioButton _asian_default_variant; - Gtk::RadioButton _asian_jis78; - Gtk::RadioButton _asian_jis83; - Gtk::RadioButton _asian_jis90; - Gtk::RadioButton _asian_jis04; - Gtk::RadioButton _asian_simplified; - Gtk::RadioButton _asian_traditional; + Gtk::RadioButton _asian_default_variant; + Gtk::RadioButton _asian_jis78; + Gtk::RadioButton _asian_jis83; + Gtk::RadioButton _asian_jis90; + Gtk::RadioButton _asian_jis04; + Gtk::RadioButton _asian_simplified; + Gtk::RadioButton _asian_traditional; - Gtk::RadioButton _asian_default_width; - Gtk::RadioButton _asian_full_width; - Gtk::RadioButton _asian_proportional_width; + Gtk::RadioButton _asian_default_width; + Gtk::RadioButton _asian_full_width; + Gtk::RadioButton _asian_proportional_width; - Gtk::CheckButton _asian_ruby; + Gtk::CheckButton _asian_ruby; // ----- - Gtk::Expander _feature_frame; - Gtk::Grid _feature_grid; - Gtk::VBox _feature_vbox; - Gtk::Entry _feature_entry; - Gtk::Label _feature_label; - Gtk::Label _feature_list; - Gtk::Label _feature_substitutions; + Gtk::Expander _feature_frame; + Gtk::Grid _feature_grid; + Gtk::VBox _feature_vbox; + Gtk::Entry _feature_entry; + Gtk::Label _feature_label; + Gtk::Label _feature_list; + Gtk::Label _feature_substitutions; private: void ligatures_init(); @@ -145,6 +143,7 @@ private: void asian_callback(); void feature_init(); + public: void feature_callback(); @@ -169,26 +168,25 @@ private: bool _feature_changed; bool _asian_changed; - std::map<std::string, Feature*> _features; + std::map<std::string, Feature *> _features; sigc::signal<void> _changed_signal; public: - /** * Update GUI based on query results. */ - void update( SPStyle const *query, bool different_features, Glib::ustring& font_spec ); + void update(SPStyle const *query, bool different_features, Glib::ustring &font_spec); /** * Update GUI based on OpenType features of selected font. */ - void update_opentype( Glib::ustring& font_spec ); + void update_opentype(Glib::ustring &font_spec); /** * Fill SPCSSAttr based on settings of buttons. */ - void fill_css( SPCSSAttr* css ); + void fill_css(SPCSSAttr *css); /** * Get CSS string for markup. @@ -199,12 +197,9 @@ public: * Let others know that user has changed GUI settings. * (Used to enable 'Apply' and 'Default' buttons.) */ - sigc::connection connectChanged(sigc::slot<void> slot) { - return _changed_signal.connect(slot); - } + sigc::connection connectChanged(sigc::slot<void> slot) { return _changed_signal.connect(slot); } }; - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/font-variations.cpp b/src/ui/widget/font-variations.cpp index fae5cc3ad5b2ef52b886264ed3daa2761f078eac..37729da4a7bdffebbd610b5c9ea6f6e66d422a83 100644 --- a/src/ui/widget/font-variations.cpp +++ b/src/ui/widget/font-variations.cpp @@ -9,16 +9,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <iostream> -#include <iomanip> +#include "font-variations.h" -#include <gtkmm.h> #include <glibmm/i18n.h> - +#include <gtkmm.h> +#include <iomanip> +#include <iostream> #include <libnrtype/font-instance.h> -#include "font-variations.h" - // For updating from selection #include "desktop.h" #include "object/sp-text.h" @@ -27,92 +25,90 @@ namespace Inkscape { namespace UI { namespace Widget { -FontVariationAxis::FontVariationAxis (Glib::ustring name, OTVarAxis& axis) - : name (name) +FontVariationAxis::FontVariationAxis(Glib::ustring name, OTVarAxis &axis) + : name(name) { - // std::cout << "FontVariationAxis::FontVariationAxis:: " // << " name: " << name // << " min: " << axis.minimum // << " max: " << axis.maximum // << " val: " << axis.set_val << std::endl; - label = Gtk::manage( new Gtk::Label( name ) ); - add( *label ); + label = Gtk::manage(new Gtk::Label(name)); + add(*label); - precision = 2 - int( log10(axis.maximum - axis.minimum)); - if (precision < 0) precision = 0; + precision = 2 - int(log10(axis.maximum - axis.minimum)); + if (precision < 0) + precision = 0; - scale = Gtk::manage( new Gtk::Scale() ); - scale->set_range (axis.minimum, axis.maximum); - scale->set_value (axis.set_val); - scale->set_digits (precision); + scale = Gtk::manage(new Gtk::Scale()); + scale->set_range(axis.minimum, axis.maximum); + scale->set_value(axis.set_val); + scale->set_digits(precision); scale->set_hexpand(true); - add( *scale ); + add(*scale); } - // ------------------------------------------------------------- // -FontVariations::FontVariations () : - Gtk::Grid () +FontVariations::FontVariations() + : Gtk::Grid() { // std::cout << "FontVariations::FontVariations" << std::endl; - set_orientation( Gtk::ORIENTATION_VERTICAL ); - set_name ("FontVariations"); + set_orientation(Gtk::ORIENTATION_VERTICAL); + set_name("FontVariations"); size_group = Gtk::SizeGroup::create(Gtk::SIZE_GROUP_HORIZONTAL); show_all_children(); } - // Update GUI based on query. -void -FontVariations::update (const Glib::ustring& font_spec) { - - font_instance* res = font_factory::Default()->FaceFromFontSpecification (font_spec.c_str()); +void FontVariations::update(const Glib::ustring &font_spec) +{ + font_instance *res = font_factory::Default()->FaceFromFontSpecification(font_spec.c_str()); auto children = get_children(); - for (auto child: children) { - remove ( *child ); + for (auto child : children) { + remove(*child); } axes.clear(); - for (auto a: res->openTypeVarAxes) { + for (auto a : res->openTypeVarAxes) { // std::cout << "Creating axis: " << a.first << std::endl; - FontVariationAxis* axis = Gtk::manage( new FontVariationAxis( a.first, a.second )); - axes.push_back( axis ); - add( *axis ); - size_group->add_widget( *(axis->get_label()) ); // Keep labels the same width - axis->get_scale()->signal_value_changed().connect( - sigc::mem_fun(*this, &FontVariations::on_variations_change) - ); + FontVariationAxis *axis = Gtk::manage(new FontVariationAxis(a.first, a.second)); + axes.push_back(axis); + add(*axis); + size_group->add_widget(*(axis->get_label())); // Keep labels the same width + axis->get_scale()->signal_value_changed().connect(sigc::mem_fun(*this, &FontVariations::on_variations_change)); } show_all_children(); } -void -FontVariations::fill_css( SPCSSAttr *css ) { - +void FontVariations::fill_css(SPCSSAttr *css) +{ // Eventually will want to favor using 'font-weight', etc. but at the moment these // can't handle "fractional" values. See CSS Fonts Module Level 4. sp_repr_css_set_property(css, "font-variation-settings", get_css_string().c_str()); } -Glib::ustring -FontVariations::get_css_string() { - +Glib::ustring FontVariations::get_css_string() +{ Glib::ustring css_string; - for (auto axis: axes) { + for (auto axis : axes) { Glib::ustring name = axis->get_name(); // Translate the "named" axes. (Additional names in 'stat' table, may need to handle them.) - if (name == "Width") name = "wdth"; // 'font-stretch' - if (name == "Weight") name = "wght"; // 'font-weight' - if (name == "Optical size") name = "opsz"; // 'font-optical-sizing' Can trigger glyph substitution. - if (name == "Slant") name = "slnt"; // 'font-style' - if (name == "Italic") name = "ital"; // 'font-style' Toggles from Roman to Italic. + if (name == "Width") + name = "wdth"; // 'font-stretch' + if (name == "Weight") + name = "wght"; // 'font-weight' + if (name == "Optical size") + name = "opsz"; // 'font-optical-sizing' Can trigger glyph substitution. + if (name == "Slant") + name = "slnt"; // 'font-style' + if (name == "Italic") + name = "ital"; // 'font-style' Toggles from Roman to Italic. std::stringstream value; value << std::fixed << std::setprecision(axis->get_precision()) << axis->get_value(); @@ -122,44 +118,49 @@ FontVariations::get_css_string() { return css_string; } -Glib::ustring -FontVariations::get_pango_string() { - +Glib::ustring FontVariations::get_pango_string() +{ Glib::ustring pango_string; if (!axes.empty()) { - pango_string += "@"; - for (auto axis: axes) { - if (axis->get_value() == 0) continue; // TEMP: Should check against default value. + for (auto axis : axes) { + if (axis->get_value() == 0) + continue; // TEMP: Should check against default value. Glib::ustring name = axis->get_name(); // Translate the "named" axes. (Additional names in 'stat' table, may need to handle them.) - if (name == "Width") name = "wdth"; // 'font-stretch' - if (name == "Weight") name = "wght"; // 'font-weight' - if (name == "Optical size") name = "opsz"; // 'font-optical-sizing' Can trigger glyph substitution. - if (name == "Slant") name = "slnt"; // 'font-style' - if (name == "Italic") name = "ital"; // 'font-style' Toggles from Roman to Italic. + if (name == "Width") + name = "wdth"; // 'font-stretch' + if (name == "Weight") + name = "wght"; // 'font-weight' + if (name == "Optical size") + name = "opsz"; // 'font-optical-sizing' Can trigger glyph substitution. + if (name == "Slant") + name = "slnt"; // 'font-style' + if (name == "Italic") + name = "ital"; // 'font-style' Toggles from Roman to Italic. std::stringstream value; value << std::fixed << std::setprecision(axis->get_precision()) << axis->get_value(); pango_string += name + "=" + value.str() + ","; } - pango_string.erase (pango_string.size() - 1); // Erase last ',' + pango_string.erase(pango_string.size() - 1); // Erase last ',' } return pango_string; } -void -FontVariations::on_variations_change() { +void FontVariations::on_variations_change() +{ // std::cout << "FontVariations::on_variations_change: " << get_css_string() << std::endl;; - signal_changed.emit (); + signal_changed.emit(); } -bool FontVariations::variations_present() const { +bool FontVariations::variations_present() const +{ return !axes.empty(); } diff --git a/src/ui/widget/font-variations.h b/src/ui/widget/font-variations.h index a3d38962cc39da100ff8eb563c55ff0b825945c0..3293928407208c783b9d13bc0f7cd50f6b7c6281 100644 --- a/src/ui/widget/font-variations.h +++ b/src/ui/widget/font-variations.h @@ -13,38 +13,35 @@ #define INKSCAPE_UI_WIDGET_FONT_VARIATIONS_H #include <gtkmm/grid.h> -#include <gtkmm/sizegroup.h> #include <gtkmm/label.h> #include <gtkmm/scale.h> +#include <gtkmm/sizegroup.h> #include "libnrtype/OpenTypeUtil.h" - #include "style.h" namespace Inkscape { namespace UI { namespace Widget { - /** * A widget for a single axis: Label and Slider */ class FontVariationAxis : public Gtk::Grid { public: - FontVariationAxis(Glib::ustring name, OTVarAxis& axis); + FontVariationAxis(Glib::ustring name, OTVarAxis &axis); Glib::ustring get_name() { return name; } - Gtk::Label* get_label() { return label; } + Gtk::Label *get_label() { return label; } double get_value() { return scale->get_value(); } int get_precision() { return precision; } - Gtk::Scale* get_scale() { return scale; } + Gtk::Scale *get_scale() { return scale; } private: - // Widgets Glib::ustring name; - Gtk::Label* label; - Gtk::Scale* scale; + Gtk::Label *label; + Gtk::Scale *scale; int precision; @@ -57,27 +54,23 @@ private: */ class FontVariations : public Gtk::Grid { - public: - /** * Constructor */ FontVariations(); protected: - public: - /** * Update GUI. */ - void update(const Glib::ustring& font_spec); + void update(const Glib::ustring &font_spec); /** * Fill SPCSSAttr based on settings of buttons. */ - void fill_css( SPCSSAttr* css ); + void fill_css(SPCSSAttr *css); /** * Get CSS String @@ -92,22 +85,18 @@ public: * Let others know that user has changed GUI settings. * (Used to enable 'Apply' and 'Default' buttons.) */ - sigc::connection connectChanged(sigc::slot<void> slot) { - return signal_changed.connect(slot); - } + sigc::connection connectChanged(sigc::slot<void> slot) { return signal_changed.connect(slot); } // return true if there are some variations present bool variations_present() const; private: - - std::vector<FontVariationAxis*> axes; + std::vector<FontVariationAxis *> axes; Glib::RefPtr<Gtk::SizeGroup> size_group; sigc::signal<void> signal_changed; }; - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/frame.cpp b/src/ui/widget/frame.cpp index eac4e221b232ce1569f544c030a77191cd222650..75e7f4fd2ebe8f682d439de9a9324665ff01c9eb 100644 --- a/src/ui/widget/frame.cpp +++ b/src/ui/widget/frame.cpp @@ -10,14 +10,13 @@ #include "frame.h" - // Inkscape::UI::Widget::Frame namespace Inkscape { namespace UI { namespace Widget { -Frame::Frame(Glib::ustring const &label_text /*= ""*/, gboolean label_bold /*= TRUE*/ ) +Frame::Frame(Glib::ustring const &label_text /*= ""*/, gboolean label_bold /*= TRUE*/) : _label(label_text, Gtk::ALIGN_END, Gtk::ALIGN_CENTER, true) { set_shadow_type(Gtk::SHADOW_NONE); @@ -26,16 +25,14 @@ Frame::Frame(Glib::ustring const &label_text /*= ""*/, gboolean label_bold /*= T set_label(label_text, label_bold); } -void -Frame::add(Widget& widget) +void Frame::add(Widget &widget) { Gtk::Frame::add(widget); set_padding(4, 0, 8, 0); show_all_children(); } -void -Frame::set_label(const Glib::ustring &label_text, gboolean label_bold /*= TRUE*/) +void Frame::set_label(const Glib::ustring &label_text, gboolean label_bold /*= TRUE*/) { if (label_bold) { _label.set_markup(Glib::ustring("<b>") + label_text + "</b>"); @@ -44,13 +41,11 @@ 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) +void Frame::set_padding(guint padding_top, guint padding_bottom, guint padding_left, guint padding_right) { auto child = get_child(); - if(child) - { + if (child) { child->set_margin_top(padding_top); child->set_margin_bottom(padding_bottom); child->set_margin_start(padding_left); @@ -58,8 +53,7 @@ Frame::set_padding (guint padding_top, guint padding_bottom, guint padding_left, } } -Gtk::Label const * -Frame::get_label_widget() const +Gtk::Label const *Frame::get_label_widget() const { return &_label; } diff --git a/src/ui/widget/frame.h b/src/ui/widget/frame.h index b2934b6443b3adda51e4fda5a6e9acab031ee70b..e63ec4301951418e37136d387a393b358bf17454 100644 --- a/src/ui/widget/frame.h +++ b/src/ui/widget/frame.h @@ -25,7 +25,6 @@ namespace Widget { class Frame : public Gtk::Frame { public: - /** * Construct a Frame Widget. * @@ -41,7 +40,7 @@ public: /** * Add a widget to this frame */ - void add(Widget& widget) override; + void add(Widget &widget) override; /** * Set the frame label text and if bold or not @@ -51,10 +50,10 @@ public: /** * Set the frame padding */ - void set_padding (guint padding_top, guint padding_bottom, guint padding_left, guint padding_right); + void set_padding(guint padding_top, guint padding_bottom, guint padding_left, guint padding_right); protected: - Gtk::Label _label; + Gtk::Label _label; }; } // namespace Widget diff --git a/src/ui/widget/gradient-image.cpp b/src/ui/widget/gradient-image.cpp index 662082bfba20c60850ff3e8758786bfe7915a3ee..8ae1cc4a5e4737c17f19baeb3f65e99645dbce8a 100644 --- a/src/ui/widget/gradient-image.cpp +++ b/src/ui/widget/gradient-image.cpp @@ -11,17 +11,14 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <sigc++/sigc++.h> - -#include <glibmm/refptr.h> -#include <gdkmm/pixbuf.h> +#include "gradient-image.h" #include <cairomm/surface.h> - -#include "gradient-image.h" +#include <gdkmm/pixbuf.h> +#include <glibmm/refptr.h> +#include <sigc++/sigc++.h> #include "display/cairo-utils.h" - #include "object/sp-gradient.h" #include "object/sp-stop.h" @@ -44,34 +41,30 @@ GradientImage::~GradientImage() } } -void -GradientImage::size_request(GtkRequisition *requisition) const +void GradientImage::size_request(GtkRequisition *requisition) const { requisition->width = 54; requisition->height = 12; } -void -GradientImage::get_preferred_width_vfunc(int &minimal_width, int &natural_width) const +void GradientImage::get_preferred_width_vfunc(int &minimal_width, int &natural_width) const { GtkRequisition requisition; size_request(&requisition); minimal_width = natural_width = requisition.width; } -void -GradientImage::get_preferred_height_vfunc(int &minimal_height, int &natural_height) const +void GradientImage::get_preferred_height_vfunc(int &minimal_height, int &natural_height) const { GtkRequisition requisition; size_request(&requisition); minimal_height = natural_height = requisition.height; } -bool -GradientImage::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) +bool GradientImage::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) { auto allocation = get_allocation(); - + cairo_pattern_t *check = ink_cairo_pattern_create_checkerboard(); auto ct = cr->cobj(); @@ -85,12 +78,11 @@ GradientImage::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) cairo_paint(ct); cairo_pattern_destroy(p); } - + return true; } -void -GradientImage::set_gradient(SPGradient *gradient) +void GradientImage::set_gradient(SPGradient *gradient) { if (_gradient) { _release_connection.disconnect(); @@ -107,8 +99,7 @@ GradientImage::set_gradient(SPGradient *gradient) update(); } -void -GradientImage::gradient_release(SPObject *) +void GradientImage::gradient_release(SPObject *) { if (_gradient) { _release_connection.disconnect(); @@ -120,14 +111,12 @@ GradientImage::gradient_release(SPObject *) update(); } -void -GradientImage::gradient_modified(SPObject *, guint /*flags*/) +void GradientImage::gradient_modified(SPObject *, guint /*flags*/) { update(); } -void -GradientImage::update() +void GradientImage::update() { if (get_is_drawable()) { queue_draw(); @@ -138,8 +127,7 @@ GradientImage::update() } // namespace UI } // namespace Inkscape -GdkPixbuf* -sp_gradient_to_pixbuf (SPGradient *gr, int width, int height) +GdkPixbuf *sp_gradient_to_pixbuf(SPGradient *gr, int width, int height) { cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); cairo_t *ct = cairo_create(s); @@ -164,9 +152,7 @@ sp_gradient_to_pixbuf (SPGradient *gr, int width, int height) return pixbuf; } - -Glib::RefPtr<Gdk::Pixbuf> -sp_gradient_to_pixbuf_ref (SPGradient *gr, int width, int height) +Glib::RefPtr<Gdk::Pixbuf> sp_gradient_to_pixbuf_ref(SPGradient *gr, int width, int height) { cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); cairo_t *ct = cairo_create(s); @@ -187,17 +173,14 @@ sp_gradient_to_pixbuf_ref (SPGradient *gr, int width, int height) cairo_surface_flush(s); Cairo::RefPtr<Cairo::Surface> sref = Cairo::RefPtr<Cairo::Surface>(new Cairo::Surface(s)); - Glib::RefPtr<Gdk::Pixbuf> pixbuf = - Gdk::Pixbuf::create(sref, 0, 0, width, height); + Glib::RefPtr<Gdk::Pixbuf> pixbuf = Gdk::Pixbuf::create(sref, 0, 0, width, height); cairo_surface_destroy(s); return pixbuf; } - -Glib::RefPtr<Gdk::Pixbuf> -sp_gradstop_to_pixbuf_ref (SPStop *stop, int width, int height) +Glib::RefPtr<Gdk::Pixbuf> sp_gradstop_to_pixbuf_ref(SPStop *stop, int width, int height) { cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); cairo_t *ct = cairo_create(s); @@ -211,12 +194,12 @@ sp_gradstop_to_pixbuf_ref (SPStop *stop, int width, int height) if (stop) { /* Alpha area */ - cairo_rectangle(ct, 0, 0, width/2, height); + cairo_rectangle(ct, 0, 0, width / 2, height); ink_cairo_set_source_rgba32(ct, stop->get_rgba32()); cairo_fill(ct); /* Solid area */ - cairo_rectangle(ct, width/2, 0, width, height); + cairo_rectangle(ct, width / 2, 0, width, height); ink_cairo_set_source_rgba32(ct, stop->get_rgba32() | 0xff); cairo_fill(ct); } @@ -225,16 +208,13 @@ sp_gradstop_to_pixbuf_ref (SPStop *stop, int width, int height) cairo_surface_flush(s); Cairo::RefPtr<Cairo::Surface> sref = Cairo::RefPtr<Cairo::Surface>(new Cairo::Surface(s)); - Glib::RefPtr<Gdk::Pixbuf> pixbuf = - Gdk::Pixbuf::create(sref, 0, 0, width, height); + Glib::RefPtr<Gdk::Pixbuf> pixbuf = Gdk::Pixbuf::create(sref, 0, 0, width, height); cairo_surface_destroy(s); return pixbuf; } - - /* Local Variables: mode:c++ diff --git a/src/ui/widget/gradient-image.h b/src/ui/widget/gradient-image.h index d583dbe3a8f83edc87034504495af03d0b412b94..0543145be2f004fabad90053fff80f6669c46d6b 100644 --- a/src/ui/widget/gradient-image.h +++ b/src/ui/widget/gradient-image.h @@ -22,7 +22,7 @@ class SPObject; class SPStop; namespace Gdk { - class Pixbuf; +class Pixbuf; } #include <sigc++/connection.h> @@ -30,8 +30,9 @@ namespace Gdk { namespace Inkscape { namespace UI { namespace Widget { -class GradientImage : public Gtk::Widget { - private: +class GradientImage : public Gtk::Widget +{ +private: SPGradient *_gradient; sigc::connection _release_connection; @@ -42,12 +43,12 @@ class GradientImage : public Gtk::Widget { void update(); void size_request(GtkRequisition *requisition) const; - protected: +protected: void get_preferred_width_vfunc(int &minimum_width, int &natural_width) const override; void get_preferred_height_vfunc(int &minimum_height, int &natural_height) const override; bool on_draw(const Cairo::RefPtr<Cairo::Context> &cr) override; - public: +public: GradientImage(SPGradient *gradient); ~GradientImage() override; @@ -58,9 +59,9 @@ class GradientImage : public Gtk::Widget { } // namespace UI } // namespace Inkscape -GdkPixbuf *sp_gradient_to_pixbuf (SPGradient *gr, int width, int height); -Glib::RefPtr<Gdk::Pixbuf> sp_gradient_to_pixbuf_ref (SPGradient *gr, int width, int height); -Glib::RefPtr<Gdk::Pixbuf> sp_gradstop_to_pixbuf_ref (SPStop *gr, int width, int height); +GdkPixbuf *sp_gradient_to_pixbuf(SPGradient *gr, int width, int height); +Glib::RefPtr<Gdk::Pixbuf> sp_gradient_to_pixbuf_ref(SPGradient *gr, int width, int height); +Glib::RefPtr<Gdk::Pixbuf> sp_gradstop_to_pixbuf_ref(SPStop *gr, int width, int height); #endif diff --git a/src/ui/widget/gradient-selector.cpp b/src/ui/widget/gradient-selector.cpp index 109ed593c2b39792ac4cd6cfe46752f8a794f5b9..ec872300575d02ace5205b54918b3b55db19203a 100644 --- a/src/ui/widget/gradient-selector.cpp +++ b/src/ui/widget/gradient-selector.cpp @@ -21,20 +21,16 @@ #include "document-undo.h" #include "document.h" #include "gradient-chemistry.h" +#include "helper/action.h" #include "id-clash.h" #include "inkscape.h" -#include "preferences.h" -#include "verbs.h" - #include "object/sp-defs.h" +#include "preferences.h" #include "style.h" - -#include "helper/action.h" #include "ui/icon-loader.h" - #include "ui/icon-names.h" - #include "ui/widget/gradient-vector-selector.h" +#include "verbs.h" namespace Inkscape { namespace UI { @@ -96,7 +92,8 @@ GradientSelector::GradientSelector() name_column->signal_clicked().connect(sigc::mem_fun(this, &GradientSelector::onTreeNameColClick)); count_column->signal_clicked().connect(sigc::mem_fun(this, &GradientSelector::onTreeCountColClick)); - auto tree_select_connection = _treeview->get_selection()->signal_changed().connect(sigc::mem_fun(this, &GradientSelector::onTreeSelection)); + auto tree_select_connection = + _treeview->get_selection()->signal_changed().connect(sigc::mem_fun(this, &GradientSelector::onTreeSelection)); _vectors->set_tree_select_connection(tree_select_connection); _text_renderer->signal_edited().connect(sigc::mem_fun(this, &GradientSelector::onGradientRename)); @@ -110,7 +107,6 @@ GradientSelector::GradientSelector() pack_start(*_scrolled_window, true, true, 4); - /* Create box for buttons */ auto hb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0)); hb->set_homogeneous(false); @@ -185,11 +181,20 @@ void GradientSelector::setMode(SelectorMode mode) } } -void GradientSelector::setUnits(SPGradientUnits units) { _gradientUnits = units; } +void GradientSelector::setUnits(SPGradientUnits units) +{ + _gradientUnits = units; +} -SPGradientUnits GradientSelector::getUnits() { return _gradientUnits; } +SPGradientUnits GradientSelector::getUnits() +{ + return _gradientUnits; +} -SPGradientSpread GradientSelector::getSpread() { return _gradientSpread; } +SPGradientSpread GradientSelector::getSpread() +{ + return _gradientSpread; +} void GradientSelector::onGradientRename(const Glib::ustring &path_string, const Glib::ustring &new_text) { @@ -223,7 +228,6 @@ void GradientSelector::onTreeNameColClick() column->set_sort_column(_columns->name); } - void GradientSelector::onTreeCountColClick() { auto column = _treeview->get_column(2); @@ -398,7 +402,6 @@ void GradientSelector::setVector(SPDocument *doc, SPGradient *vector) } } } else if (_mode != MODE_SWATCH) { - for (auto &swatch_widget : _swatch_widgets) { swatch_widget->hide(); } @@ -434,7 +437,6 @@ SPGradient *GradientSelector::getVector() return _vectors->get_gradient(); } - void GradientSelector::vector_set(SPGradient *gr) { if (!_blocked) { @@ -446,7 +448,6 @@ void GradientSelector::vector_set(SPGradient *gr) } } - void GradientSelector::delete_vector_clicked() { const auto selection = _treeview->get_selection(); diff --git a/src/ui/widget/gradient-selector.h b/src/ui/widget/gradient-selector.h index df6d2850a90d929222ace68c7d2a4c6d0a293f79..fa54b589d997342bb452f64c43a585a8f3228cfe 100644 --- a/src/ui/widget/gradient-selector.h +++ b/src/ui/widget/gradient-selector.h @@ -19,10 +19,10 @@ #include <gtkmm/box.h> #include <gtkmm/liststore.h> #include <gtkmm/scrolledwindow.h> +#include <vector> #include "object/sp-gradient-spread.h" #include "object/sp-gradient-units.h" -#include <vector> class SPDocument; class SPGradient; @@ -35,18 +35,24 @@ class ScrolledWindow; class TreeView; } // namespace Gtk - namespace Inkscape { namespace UI { namespace Widget { class GradientVectorSelector; -class GradientSelector : public Gtk::Box { - public: - enum SelectorMode { MODE_LINEAR, MODE_RADIAL, MODE_SWATCH }; +class GradientSelector : public Gtk::Box +{ +public: + enum SelectorMode + { + MODE_LINEAR, + MODE_RADIAL, + MODE_SWATCH + }; - class ModelColumns : public Gtk::TreeModel::ColumnRecord { - public: + class ModelColumns : public Gtk::TreeModel::ColumnRecord + { + public: ModelColumns() { add(name); @@ -64,8 +70,7 @@ class GradientSelector : public Gtk::Box { Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf>> pixbuf; }; - - private: +private: sigc::signal<void> _signal_grabbed; sigc::signal<void> _signal_dragged; sigc::signal<void> _signal_released; @@ -119,7 +124,7 @@ class GradientSelector : public Gtk::Box { void delete_vector_clicked(); void vector_set(SPGradient *gr); - public: +public: GradientSelector(); inline decltype(_signal_changed) signal_changed() const { return _signal_changed; } @@ -142,7 +147,6 @@ class GradientSelector : public Gtk::Box { #endif // SEEN_GRADIENT_SELECTOR_H - /* Local Variables: mode:c++ diff --git a/src/ui/widget/gradient-vector-selector.cpp b/src/ui/widget/gradient-vector-selector.cpp index 5ecd9d468f80e9da9ae6f1586373099e7e04d63e..95e61b3120c06402212d9f2a17463c545dc69f11 100644 --- a/src/ui/widget/gradient-vector-selector.cpp +++ b/src/ui/widget/gradient-vector-selector.cpp @@ -22,44 +22,38 @@ #include "ui/widget/gradient-vector-selector.h" -#include <set> - #include <glibmm.h> #include <glibmm/i18n.h> +#include <set> -#include "gradient-chemistry.h" -#include "inkscape.h" -#include "preferences.h" #include "desktop.h" #include "document-undo.h" -#include "layer-manager.h" +#include "gradient-chemistry.h" #include "include/macros.h" -#include "selection-chemistry.h" -#include "verbs.h" - +#include "inkscape.h" #include "io/resource.h" - +#include "layer-manager.h" #include "object/sp-defs.h" #include "object/sp-linear-gradient.h" #include "object/sp-radial-gradient.h" #include "object/sp-root.h" #include "object/sp-stop.h" +#include "preferences.h" +#include "selection-chemistry.h" #include "style.h" - #include "svg/css-ostringstream.h" - #include "ui/dialog-events.h" #include "ui/selected-color.h" #include "ui/widget/color-notebook.h" #include "ui/widget/color-preview.h" #include "ui/widget/gradient-image.h" - +#include "verbs.h" #include "xml/repr.h" using Inkscape::DocumentUndo; using Inkscape::UI::SelectedColor; -void gr_get_usage_counts(SPDocument *doc, std::map<SPGradient *, gint> *mapUsageCount ); +void gr_get_usage_counts(SPDocument *doc, std::map<SPGradient *, gint> *mapUsageCount); unsigned long sp_gradient_to_hhssll(SPGradient *gr); // TODO FIXME kill these globals!!! @@ -99,10 +93,10 @@ GradientVectorSelector::~GradientVectorSelector() void GradientVectorSelector::set_gradient(SPDocument *doc, SPGradient *gr) { -// g_message("sp_gradient_vector_selector_set_gradient(%p, %p, %p) [%s] %d %d", gvs, doc, gr, -// (gr ? gr->getId():"N/A"), -// (gr ? gr->isSwatch() : -1), -// (gr ? gr->isSolid() : -1)); + // g_message("sp_gradient_vector_selector_set_gradient(%p, %p, %p) [%s] %d %d", gvs, doc, gr, + // (gr ? gr->getId():"N/A"), + // (gr ? gr->isSwatch() : -1), + // (gr ? gr->isSolid() : -1)); static gboolean suppress = FALSE; g_return_if_fail(!gr || (doc != nullptr)); @@ -124,16 +118,20 @@ void GradientVectorSelector::set_gradient(SPDocument *doc, SPGradient *gr) // Connect signals if (doc) { - _defs_release_connection = doc->getDefs()->connectRelease(sigc::mem_fun(this, &GradientVectorSelector::defs_release)); - _defs_modified_connection = doc->getDefs()->connectModified(sigc::mem_fun(this, &GradientVectorSelector::defs_modified)); + _defs_release_connection = + doc->getDefs()->connectRelease(sigc::mem_fun(this, &GradientVectorSelector::defs_release)); + _defs_modified_connection = + doc->getDefs()->connectModified(sigc::mem_fun(this, &GradientVectorSelector::defs_modified)); } if (gr) { - _gradient_release_connection = gr->connectRelease(sigc::mem_fun(this, &GradientVectorSelector::gradient_release)); + _gradient_release_connection = + gr->connectRelease(sigc::mem_fun(this, &GradientVectorSelector::gradient_release)); } _doc = doc; _gr = gr; rebuild_gui_full(); - if (!suppress) _signal_vector_set.emit(gr); + if (!suppress) + _signal_vector_set.emit(gr); } else if (gr != _gr) { // Harder case - keep document, rebuild list and stuff // fixme: (Lauris) @@ -146,8 +144,7 @@ void GradientVectorSelector::set_gradient(SPDocument *doc, SPGradient *gr) /* The case of setting NULL -> NULL is not very interesting */ } -void -GradientVectorSelector::gradient_release(SPObject * /*obj*/) +void GradientVectorSelector::gradient_release(SPObject * /*obj*/) { /* Disconnect gradient */ if (_gr) { @@ -159,8 +156,7 @@ GradientVectorSelector::gradient_release(SPObject * /*obj*/) rebuild_gui_full(); } -void -GradientVectorSelector::defs_release(SPObject * /*defs*/) +void GradientVectorSelector::defs_release(SPObject * /*defs*/) { _doc = nullptr; @@ -177,15 +173,13 @@ GradientVectorSelector::defs_release(SPObject * /*defs*/) rebuild_gui_full(); } -void -GradientVectorSelector::defs_modified(SPObject *defs, guint flags) +void GradientVectorSelector::defs_modified(SPObject *defs, guint flags) { /* fixme: We probably have to check some flags here (Lauris) */ rebuild_gui_full(); } -void -GradientVectorSelector::rebuild_gui_full() +void GradientVectorSelector::rebuild_gui_full() { _tree_select_connection.block(); @@ -197,8 +191,8 @@ GradientVectorSelector::rebuild_gui_full() if (_gr) { auto gradients = _gr->document->getResourceList("gradient"); for (auto gradient : gradients) { - SPGradient* grad = SP_GRADIENT(gradient); - if ( grad->hasStops() && (grad->isSwatch() == _swatched) ) { + SPGradient *grad = SP_GRADIENT(gradient); + if (grad->hasStops() && (grad->isSwatch() == _swatched)) { gl.push_back(SP_GRADIENT(gradient)); } } @@ -218,12 +212,12 @@ GradientVectorSelector::rebuild_gui_full() } else if (!_gr) { Gtk::TreeModel::Row row = *(_store->append()); - row[_columns->name] = _("No gradient selected"); + row[_columns->name] = _("No gradient selected"); } else { - for (auto gr:gl) { + for (auto gr : gl) { unsigned long hhssll = sp_gradient_to_hhssll(gr); - GdkPixbuf *pixb = sp_gradient_to_pixbuf (gr, 64, 18); + GdkPixbuf *pixb = sp_gradient_to_pixbuf(gr, 64, 18); Glib::ustring label = gr_prepare_label(gr); Gtk::TreeModel::Row row = *(_store->append()); @@ -238,8 +232,7 @@ GradientVectorSelector::rebuild_gui_full() _tree_select_connection.unblock(); } -void -GradientVectorSelector::setSwatched() +void GradientVectorSelector::setSwatched() { _swatched = true; rebuild_gui_full(); @@ -256,9 +249,9 @@ Glib::ustring gr_prepare_label(SPObject *obj) id = obj->getRepr()->name(); } - if (strlen(id) > 14 && (!strncmp (id, "linearGradient", 14) || !strncmp (id, "radialGradient", 14))) - return gr_ellipsize_text(id+14, 35); - return gr_ellipsize_text (id, 35); + if (strlen(id) > 14 && (!strncmp(id, "linearGradient", 14) || !strncmp(id, "radialGradient", 14))) + return gr_ellipsize_text(id + 14, 35); + return gr_ellipsize_text(id, 35); } /* @@ -268,14 +261,13 @@ Glib::ustring gr_prepare_label(SPObject *obj) Glib::ustring gr_ellipsize_text(Glib::ustring const &src, size_t maxlen) { if (src.length() > maxlen && maxlen > 8) { - size_t p1 = (size_t) maxlen / 2; - size_t p2 = (size_t) src.length() - (maxlen - p1 - 1); + size_t p1 = (size_t)maxlen / 2; + size_t p2 = (size_t)src.length() - (maxlen - p1 - 1); return src.substr(0, p1) + "…" + src.substr(p2); } return src; } - /* * Return a "HHSSLL" version of the first stop color so we can sort by it */ @@ -284,14 +276,14 @@ unsigned long sp_gradient_to_hhssll(SPGradient *gr) SPStop *stop = gr->getFirstStop(); unsigned long rgba = stop->get_rgba32(); float hsl[3]; - SPColor::rgb_to_hsl_floatv (hsl, SP_RGBA32_R_F(rgba), SP_RGBA32_G_F(rgba), SP_RGBA32_B_F(rgba)); + SPColor::rgb_to_hsl_floatv(hsl, SP_RGBA32_R_F(rgba), SP_RGBA32_G_F(rgba), SP_RGBA32_B_F(rgba)); - return ((int)(hsl[0]*100 * 10000)) + ((int)(hsl[1]*100 * 100)) + ((int)(hsl[2]*100 * 1)); + return ((int)(hsl[0] * 100 * 10000)) + ((int)(hsl[1] * 100 * 100)) + ((int)(hsl[2] * 100 * 1)); } -static void get_all_doc_items(std::vector<SPItem*> &list, SPObject *from) +static void get_all_doc_items(std::vector<SPItem *> &list, SPObject *from) { - for (auto& child: from->children) { + for (auto &child : from->children) { if (SP_IS_ITEM(&child)) { list.push_back(SP_ITEM(&child)); } @@ -302,17 +294,15 @@ static void get_all_doc_items(std::vector<SPItem*> &list, SPObject *from) /* * Return a SPItem's gradient */ -static SPGradient * gr_item_get_gradient(SPItem *item, gboolean fillorstroke) +static SPGradient *gr_item_get_gradient(SPItem *item, gboolean fillorstroke) { SPIPaint *item_paint = item->style->getFillOrStroke(fillorstroke); if (item_paint->isPaintserver()) { - - SPPaintServer *item_server = (fillorstroke) ? - item->style->getFillPaintServer() : item->style->getStrokePaintServer(); + SPPaintServer *item_server = + (fillorstroke) ? item->style->getFillPaintServer() : item->style->getStrokePaintServer(); if (SP_IS_LINEARGRADIENT(item_server) || SP_IS_RADIALGRADIENT(item_server) || - (SP_IS_GRADIENT(item_server) && SP_GRADIENT(item_server)->getVector()->isSwatch())) { - + (SP_IS_GRADIENT(item_server) && SP_GRADIENT(item_server)->getVector()->isSwatch())) { return SP_GRADIENT(item_server)->getVector(); } } @@ -323,7 +313,7 @@ static SPGradient * gr_item_get_gradient(SPItem *item, gboolean fillorstroke) /* * Map each gradient to its usage count for both fill and stroke styles */ -void gr_get_usage_counts(SPDocument *doc, std::map<SPGradient *, gint> *mapUsageCount ) +void gr_get_usage_counts(SPDocument *doc, std::map<SPGradient *, gint> *mapUsageCount) { if (!doc) return; @@ -331,7 +321,7 @@ void gr_get_usage_counts(SPDocument *doc, std::map<SPGradient *, gint> *mapUsage std::vector<SPItem *> all_list; get_all_doc_items(all_list, doc->getRoot()); - for (auto item:all_list) { + for (auto item : all_list) { if (!item->getId()) continue; SPGradient *gr = nullptr; diff --git a/src/ui/widget/gradient-vector-selector.h b/src/ui/widget/gradient-vector-selector.h index ae76f0c7ec5b8a55523982a4aa6355ba6e0f0141..585a61fcacf1469b073cb5e47c591da000ca5ffb 100644 --- a/src/ui/widget/gradient-vector-selector.h +++ b/src/ui/widget/gradient-vector-selector.h @@ -16,11 +16,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "ui/widget/gradient-selector.h" - #include <gtkmm/liststore.h> #include <sigc++/connection.h> +#include "ui/widget/gradient-selector.h" + class SPDocument; class SPObject; class SPGradient; @@ -30,13 +30,14 @@ namespace Inkscape { namespace UI { namespace Widget { -class GradientVectorSelector : public Gtk::Box { - private: - bool _idlabel = true; +class GradientVectorSelector : public Gtk::Box +{ +private: + bool _idlabel = true; bool _swatched = false; SPDocument *_doc = nullptr; - SPGradient *_gr = nullptr; + SPGradient *_gr = nullptr; /* Gradient vectors store */ Glib::RefPtr<Gtk::ListStore> _store; @@ -54,17 +55,17 @@ class GradientVectorSelector : public Gtk::Box { void defs_modified(SPObject *defs, guint flags); void rebuild_gui_full(); - public: +public: GradientVectorSelector(SPDocument *doc, SPGradient *gradient); ~GradientVectorSelector() override; void setSwatched(); void set_gradient(SPDocument *doc, SPGradient *gr); - inline decltype(_columns) get_columns() const { return _columns; } - inline decltype(_doc) get_document() const { return _doc; } - inline decltype(_gr) get_gradient() const { return _gr; } - inline decltype(_store) get_store() const { return _store; } + inline decltype(_columns) get_columns() const { return _columns; } + inline decltype(_doc) get_document() const { return _doc; } + inline decltype(_gr) get_gradient() const { return _gr; } + inline decltype(_store) get_store() const { return _store; } inline decltype(_signal_vector_set) signal_vector_set() const { return _signal_vector_set; } @@ -75,7 +76,7 @@ class GradientVectorSelector : public Gtk::Box { } // namespace UI } // namespace Inkscape -Glib::ustring gr_prepare_label (SPObject *obj); +Glib::ustring gr_prepare_label(SPObject *obj); Glib::ustring gr_ellipsize_text(Glib::ustring const &src, size_t maxlen); #endif // SEEN_GRADIENT_VECTOR_H diff --git a/src/ui/widget/highlight-picker.cpp b/src/ui/widget/highlight-picker.cpp index f35e405c7b83d5c58fe14d77bc55bb6ce7809c0e..c8fb10a8d6b3dc653eb757e0e147397960636147 100644 --- a/src/ui/widget/highlight-picker.cpp +++ b/src/ui/widget/highlight-picker.cpp @@ -8,64 +8,56 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "highlight-picker.h" + #include <glibmm.h> #include <gtkmm/icontheme.h> #include "display/cairo-utils.h" -#include "highlight-picker.h" - namespace Inkscape { namespace UI { namespace Widget { -HighlightPicker::HighlightPicker() : - Glib::ObjectBase(typeid(HighlightPicker)), - Gtk::CellRendererPixbuf(), - _property_active(*this, "active", 0) +HighlightPicker::HighlightPicker() + : Glib::ObjectBase(typeid(HighlightPicker)) + , Gtk::CellRendererPixbuf() + , _property_active(*this, "active", 0) { - property_mode() = Gtk::CELL_RENDERER_MODE_ACTIVATABLE; } -HighlightPicker::~HighlightPicker() -= default; +HighlightPicker::~HighlightPicker() = default; -void HighlightPicker::get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const +void HighlightPicker::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 HighlightPicker::get_preferred_width_vfunc(Gtk::Widget& widget, - int& min_w, - int& nat_w) const +void HighlightPicker::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; } } -void HighlightPicker::render_vfunc( const Cairo::RefPtr<Cairo::Context>& cr, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - Gtk::CellRendererState flags ) +void HighlightPicker::render_vfunc(const Cairo::RefPtr<Cairo::Context> &cr, Gtk::Widget &widget, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) { GdkRectangle carea; @@ -99,24 +91,19 @@ void HighlightPicker::render_vfunc( const Cairo::RefPtr<Cairo::Context>& cr, 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, - 10, 20, cairo_image_surface_get_stride(s), - ink_cairo_pixbuf_cleanup, s); + + GdkPixbuf *pixbuf = gdk_pixbuf_new_from_data(cairo_image_surface_get_data(s), GDK_COLORSPACE_RGB, TRUE, 8, 10, 20, + cairo_image_surface_get_stride(s), ink_cairo_pixbuf_cleanup, s); convert_pixbuf_argb32_to_normal(pixbuf); - + property_pixbuf() = Glib::wrap(pixbuf); - Gtk::CellRendererPixbuf::render_vfunc( cr, widget, background_area, cell_area, flags ); + Gtk::CellRendererPixbuf::render_vfunc(cr, widget, background_area, cell_area, flags); } -bool HighlightPicker::activate_vfunc(GdkEvent* /*event*/, - Gtk::Widget& /*widget*/, - const Glib::ustring& /*path*/, - const Gdk::Rectangle& /*background_area*/, - const Gdk::Rectangle& /*cell_area*/, +bool HighlightPicker::activate_vfunc(GdkEvent * /*event*/, Gtk::Widget & /*widget*/, const Glib::ustring & /*path*/, + const Gdk::Rectangle & /*background_area*/, const Gdk::Rectangle & /*cell_area*/, Gtk::CellRendererState /*flags*/) -{ +{ return false; } @@ -124,35 +111,27 @@ bool HighlightPicker::activate_vfunc(GdkEvent* /*event*/, } // namespace UI } // namespace Inkscape -//should be okay to put this here +// should be okay to put this here /** * Converts GdkPixbuf's data to premultiplied ARGB. * This function will convert a GdkPixbuf in place into Cairo's native pixel format. * Note that this is a hack intended to save memory. When the pixbuf is in Cairo's format, * using it with GTK will result in corrupted drawings. */ -void -convert_pixbuf_normal_to_argb32(GdkPixbuf *pb) +void convert_pixbuf_normal_to_argb32(GdkPixbuf *pb) { - convert_pixels_pixbuf_to_argb32( - gdk_pixbuf_get_pixels(pb), - gdk_pixbuf_get_width(pb), - gdk_pixbuf_get_height(pb), - gdk_pixbuf_get_rowstride(pb)); + convert_pixels_pixbuf_to_argb32(gdk_pixbuf_get_pixels(pb), gdk_pixbuf_get_width(pb), gdk_pixbuf_get_height(pb), + gdk_pixbuf_get_rowstride(pb)); } /** * Converts GdkPixbuf's data back to its native format. * Once this is done, the pixbuf can be used with GTK again. */ -void -convert_pixbuf_argb32_to_normal(GdkPixbuf *pb) +void convert_pixbuf_argb32_to_normal(GdkPixbuf *pb) { - convert_pixels_argb32_to_pixbuf( - gdk_pixbuf_get_pixels(pb), - gdk_pixbuf_get_width(pb), - gdk_pixbuf_get_height(pb), - gdk_pixbuf_get_rowstride(pb)); + convert_pixels_argb32_to_pixbuf(gdk_pixbuf_get_pixels(pb), gdk_pixbuf_get_width(pb), gdk_pixbuf_get_height(pb), + gdk_pixbuf_get_rowstride(pb)); } /* @@ -165,5 +144,3 @@ convert_pixbuf_argb32_to_normal(GdkPixbuf *pb) End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - - diff --git a/src/ui/widget/highlight-picker.h b/src/ui/widget/highlight-picker.h index 0b77a235f64c63973eba30233fb287018ca29e4d..d6a16fbbde426ce3700f1845a4ee928787a015aa 100644 --- a/src/ui/widget/highlight-picker.h +++ b/src/ui/widget/highlight-picker.h @@ -10,15 +10,16 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <glibmm/property.h> #include <gtkmm/cellrendererpixbuf.h> #include <gtkmm/widget.h> -#include <glibmm/property.h> namespace Inkscape { namespace UI { namespace Widget { -class HighlightPicker : public Gtk::CellRendererPixbuf { +class HighlightPicker : public Gtk::CellRendererPixbuf +{ public: HighlightPicker(); ~HighlightPicker() override; @@ -26,39 +27,26 @@ public: Glib::PropertyProxy<guint32> property_active() { return _property_active.get_proxy(); } protected: - 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 ) override; + 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) override; + + void get_preferred_width_vfunc(Gtk::Widget &widget, int &min_w, int &nat_w) const override; - void get_preferred_width_vfunc(Gtk::Widget& widget, - int& min_w, - int& nat_w) const override; - - void get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const override; + void get_preferred_height_vfunc(Gtk::Widget &widget, int &min_h, int &nat_h) const override; - bool activate_vfunc(GdkEvent *event, - Gtk::Widget &widget, - const Glib::ustring &path, - const Gdk::Rectangle &background_area, - const Gdk::Rectangle &cell_area, - Gtk::CellRendererState flags) override; + bool activate_vfunc(GdkEvent *event, Gtk::Widget &widget, const Glib::ustring &path, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) override; private: - Glib::Property<guint32> _property_active; }; - - } // namespace Widget } // namespace UI } // namespace Inkscape - #endif /* __UI_DIALOG_IMAGETOGGLER_H__ */ /* diff --git a/src/ui/widget/iconrenderer.cpp b/src/ui/widget/iconrenderer.cpp index 4ca250ef2ac4a694d857bfb89b3f96e96eb789f6..8443549a11fc8c09c1894491a42e0c403fb78b33 100644 --- a/src/ui/widget/iconrenderer.cpp +++ b/src/ui/widget/iconrenderer.cpp @@ -20,10 +20,10 @@ namespace Inkscape { namespace UI { namespace Widget { -IconRenderer::IconRenderer() : - Glib::ObjectBase(typeid(IconRenderer)), - Gtk::CellRendererPixbuf(), - _property_icon(*this, "icon", 0) +IconRenderer::IconRenderer() + : Glib::ObjectBase(typeid(IconRenderer)) + , Gtk::CellRendererPixbuf() + , _property_icon(*this, "icon", 0) { property_mode() = Gtk::CELL_RENDERER_MODE_ACTIVATABLE; set_pixbuf(); @@ -37,53 +37,44 @@ IconRenderer::type_signal_activated IconRenderer::signal_activated() return m_signal_activated; } -void IconRenderer::get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const +void IconRenderer::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 IconRenderer::get_preferred_width_vfunc(Gtk::Widget& widget, - int& min_w, - int& nat_w) const +void IconRenderer::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; } } -void IconRenderer::render_vfunc( const Cairo::RefPtr<Cairo::Context>& cr, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - Gtk::CellRendererState flags ) +void IconRenderer::render_vfunc(const Cairo::RefPtr<Cairo::Context> &cr, Gtk::Widget &widget, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) { set_pixbuf(); - - Gtk::CellRendererPixbuf::render_vfunc( cr, widget, background_area, cell_area, flags ); + + Gtk::CellRendererPixbuf::render_vfunc(cr, widget, background_area, cell_area, flags); } -bool IconRenderer::activate_vfunc(GdkEvent* /*event*/, - Gtk::Widget& /*widget*/, - const Glib::ustring& path, - const Gdk::Rectangle& /*background_area*/, - const Gdk::Rectangle& /*cell_area*/, - Gtk::CellRendererState /*flags*/) +bool IconRenderer::activate_vfunc(GdkEvent * /*event*/, Gtk::Widget & /*widget*/, const Glib::ustring &path, + const Gdk::Rectangle & /*background_area*/, const Gdk::Rectangle & /*cell_area*/, + Gtk::CellRendererState /*flags*/) { m_signal_activated.emit(path); return true; @@ -97,14 +88,13 @@ void IconRenderer::add_icon(Glib::ustring name) void IconRenderer::set_pixbuf() { int icon_index = property_icon().get_value(); - if(icon_index >= 0 && icon_index < _icons.size()) { + if (icon_index >= 0 && icon_index < _icons.size()) { property_pixbuf() = _icons[icon_index]; } else { property_pixbuf() = sp_get_icon_pixbuf("image-missing", GTK_ICON_SIZE_BUTTON); } } - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/iconrenderer.h b/src/ui/widget/iconrenderer.h index 662ce5b1992d653d27b93254eca3aec99a39164c..6de41424785f8f118eff7f2ef6168e3f85cac90e 100644 --- a/src/ui/widget/iconrenderer.h +++ b/src/ui/widget/iconrenderer.h @@ -11,65 +11,55 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <glibmm/property.h> #include <gtkmm/cellrendererpixbuf.h> #include <gtkmm/widget.h> -#include <glibmm/property.h> namespace Inkscape { namespace UI { namespace Widget { -class IconRenderer : public Gtk::CellRendererPixbuf { +class IconRenderer : public Gtk::CellRendererPixbuf +{ public: IconRenderer(); - ~IconRenderer() override = default;; + ~IconRenderer() override = default; + ; Glib::PropertyProxy<int> property_icon() { return _property_icon.get_proxy(); } - Glib::PropertyProxy< Glib::RefPtr<Gdk::Pixbuf> > property_pixbuf_on(); - Glib::PropertyProxy< Glib::RefPtr<Gdk::Pixbuf> > property_pixbuf_off(); + Glib::PropertyProxy<Glib::RefPtr<Gdk::Pixbuf>> property_pixbuf_on(); + Glib::PropertyProxy<Glib::RefPtr<Gdk::Pixbuf>> property_pixbuf_off(); void add_icon(Glib::ustring name); typedef sigc::signal<void, Glib::ustring> type_signal_activated; type_signal_activated signal_activated(); + protected: type_signal_activated m_signal_activated; - 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 ) override; + 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) override; + + void get_preferred_width_vfunc(Gtk::Widget &widget, int &min_w, int &nat_w) const override; - void get_preferred_width_vfunc(Gtk::Widget& widget, - int& min_w, - int& nat_w) const override; - - void get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const override; + void get_preferred_height_vfunc(Gtk::Widget &widget, int &min_h, int &nat_h) const override; - bool activate_vfunc(GdkEvent *event, - Gtk::Widget &widget, - const Glib::ustring &path, - const Gdk::Rectangle &background_area, - const Gdk::Rectangle &cell_area, - Gtk::CellRendererState flags) override; + bool activate_vfunc(GdkEvent *event, Gtk::Widget &widget, const Glib::ustring &path, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) override; private: - Glib::Property<int> _property_icon; std::vector<Glib::RefPtr<Gdk::Pixbuf>> _icons; void set_pixbuf(); }; - - } // namespace Widget } // namespace UI } // namespace Inkscape - #endif /* __UI_DIALOG_IMAGETOGGLER_H__ */ /* diff --git a/src/ui/widget/imagetoggler.cpp b/src/ui/widget/imagetoggler.cpp index a1d258eb2daae3c561b444215e9c1a00848d53a8..3319310e6d81f49a37ec61028446b3df7d28fe36 100644 --- a/src/ui/widget/imagetoggler.cpp +++ b/src/ui/widget/imagetoggler.cpp @@ -9,28 +9,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #include "ui/widget/imagetoggler.h" +#include <iostream> + #include "ui/icon-loader.h" #include "ui/icon-names.h" #include "widgets/toolbox.h" -#include <iostream> - namespace Inkscape { namespace UI { namespace Widget { -ImageToggler::ImageToggler( char const* on, char const* off) : - Glib::ObjectBase(typeid(ImageToggler)), - Gtk::CellRendererPixbuf(), - _pixOnName(on), - _pixOffName(off), - _property_active(*this, "active", false), - _property_activatable(*this, "activatable", true), - _property_pixbuf_on(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)), - _property_pixbuf_off(*this, "pixbuf_off", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) +ImageToggler::ImageToggler(char const *on, char const *off) + : Glib::ObjectBase(typeid(ImageToggler)) + , Gtk::CellRendererPixbuf() + , _pixOnName(on) + , _pixOffName(off) + , _property_active(*this, "active", false) + , _property_activatable(*this, "activatable", true) + , _property_pixbuf_on(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) + , _property_pixbuf_off(*this, "pixbuf_off", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) { property_mode() = Gtk::CELL_RENDERER_MODE_ACTIVATABLE; @@ -40,53 +39,43 @@ ImageToggler::ImageToggler( char const* on, char const* off) : property_pixbuf() = _property_pixbuf_off.get_value(); } -void ImageToggler::get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const +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 +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; } } -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 ) +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) { property_pixbuf() = _property_active.get_value() ? _property_pixbuf_on : _property_pixbuf_off; - Gtk::CellRendererPixbuf::render_vfunc( cr, widget, background_area, cell_area, flags ); + Gtk::CellRendererPixbuf::render_vfunc(cr, widget, background_area, cell_area, flags); } -bool -ImageToggler::activate_vfunc(GdkEvent* event, - Gtk::Widget& /*widget*/, - const Glib::ustring& path, - const Gdk::Rectangle& /*background_area*/, - const Gdk::Rectangle& /*cell_area*/, - Gtk::CellRendererState /*flags*/) +bool ImageToggler::activate_vfunc(GdkEvent *event, Gtk::Widget & /*widget*/, const Glib::ustring &path, + const Gdk::Rectangle & /*background_area*/, const Gdk::Rectangle & /*cell_area*/, + Gtk::CellRendererState /*flags*/) { _signal_pre_toggle.emit(event); _signal_toggled.emit(path); @@ -94,7 +83,6 @@ ImageToggler::activate_vfunc(GdkEvent* event, return false; } - } // namespace Widget } // namespace UI } // namespace Inkscape @@ -109,5 +97,3 @@ ImageToggler::activate_vfunc(GdkEvent* event, End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - - diff --git a/src/ui/widget/imagetoggler.h b/src/ui/widget/imagetoggler.h index a03ee37dcbe74c5ef1e434808c722548f006787a..d3c649e7a215da41324da1ecc906d607b588bb67 100644 --- a/src/ui/widget/imagetoggler.h +++ b/src/ui/widget/imagetoggler.h @@ -11,49 +11,41 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <glibmm/property.h> #include <gtkmm/cellrendererpixbuf.h> #include <gtkmm/widget.h> -#include <glibmm/property.h> namespace Inkscape { namespace UI { namespace Widget { -class ImageToggler : public Gtk::CellRendererPixbuf { +class ImageToggler : public Gtk::CellRendererPixbuf +{ public: - ImageToggler( char const *on, char const *off); - ~ImageToggler() override = default;; + ImageToggler(char const *on, char const *off); + ~ImageToggler() override = default; + ; - sigc::signal<void, const Glib::ustring&> signal_toggled() { return _signal_toggled;} - sigc::signal<void, GdkEvent const *> signal_pre_toggle() { return _signal_pre_toggle; } + sigc::signal<void, const Glib::ustring &> signal_toggled() { return _signal_toggled; } + sigc::signal<void, GdkEvent const *> signal_pre_toggle() { return _signal_pre_toggle; } Glib::PropertyProxy<bool> property_active() { return _property_active.get_proxy(); } Glib::PropertyProxy<bool> property_activatable() { return _property_activatable.get_proxy(); } - Glib::PropertyProxy< Glib::RefPtr<Gdk::Pixbuf> > property_pixbuf_on(); - Glib::PropertyProxy< Glib::RefPtr<Gdk::Pixbuf> > property_pixbuf_off(); + Glib::PropertyProxy<Glib::RefPtr<Gdk::Pixbuf>> property_pixbuf_on(); + Glib::PropertyProxy<Glib::RefPtr<Gdk::Pixbuf>> property_pixbuf_off(); protected: - 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 ) override; + 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) override; - void get_preferred_width_vfunc(Gtk::Widget& widget, - int& min_w, - int& nat_w) const override; - - void get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const override; + void get_preferred_width_vfunc(Gtk::Widget &widget, int &min_w, int &nat_w) const override; - bool activate_vfunc(GdkEvent *event, - Gtk::Widget &widget, - const Glib::ustring &path, - const Gdk::Rectangle &background_area, - const Gdk::Rectangle &cell_area, - Gtk::CellRendererState flags) override; + void get_preferred_height_vfunc(Gtk::Widget &widget, int &min_h, int &nat_h) const override; + bool activate_vfunc(GdkEvent *event, Gtk::Widget &widget, const Glib::ustring &path, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) override; private: Glib::ustring _pixOnName; @@ -61,20 +53,17 @@ private: Glib::Property<bool> _property_active; Glib::Property<bool> _property_activatable; - Glib::Property< Glib::RefPtr<Gdk::Pixbuf> > _property_pixbuf_on; - Glib::Property< Glib::RefPtr<Gdk::Pixbuf> > _property_pixbuf_off; + Glib::Property<Glib::RefPtr<Gdk::Pixbuf>> _property_pixbuf_on; + Glib::Property<Glib::RefPtr<Gdk::Pixbuf>> _property_pixbuf_off; - sigc::signal<void, const Glib::ustring&> _signal_toggled; + sigc::signal<void, const Glib::ustring &> _signal_toggled; sigc::signal<void, GdkEvent const *> _signal_pre_toggle; }; - - } // namespace Widget } // namespace UI } // namespace Inkscape - #endif /* __UI_DIALOG_IMAGETOGGLER_H__ */ /* diff --git a/src/ui/widget/ink-color-wheel.cpp b/src/ui/widget/ink-color-wheel.cpp index 8788ad37486b0ab3ad5ec4485f36106abb1ad42c..3fc353cf442769a99261a379da18caf86c3a6fea 100644 --- a/src/ui/widget/ink-color-wheel.cpp +++ b/src/ui/widget/ink-color-wheel.cpp @@ -11,15 +11,28 @@ #include "ink-color-wheel.h" // A point with a color value. -class color_point { +class color_point +{ public: - color_point() : x(0), y(0), r(0), g(0), b(0) {}; - color_point(double x, double y, double r, double g, double b) : x(x), y(y), r(r), g(g), b(b) {}; - color_point(double x, double y, guint32 color) : x(x), y(y), - r(((color & 0xff0000) >> 16)/255.0), - g(((color & 0xff00) >> 8)/255.0), - b(((color & 0xff) )/255.0) {}; - guint32 get_color() { return (int(r*255) << 16 | int(g*255) << 8 | int(b*255)); }; + color_point() + : x(0) + , y(0) + , r(0) + , g(0) + , b(0){}; + color_point(double x, double y, double r, double g, double b) + : x(x) + , y(y) + , r(r) + , g(g) + , b(b){}; + color_point(double x, double y, guint32 color) + : x(x) + , y(y) + , r(((color & 0xff0000) >> 16) / 255.0) + , g(((color & 0xff00) >> 8) / 255.0) + , b(((color & 0xff)) / 255.0){}; + guint32 get_color() { return (int(r * 255) << 16 | int(g * 255) << 8 | int(b * 255)); }; double x; double y; double r; @@ -27,15 +40,18 @@ public: double b; }; -inline double lerp(const double& v0, const double& v1, const double& t0, const double&t1, const double& t) { +inline double lerp(const double &v0, const double &v1, const double &t0, const double &t1, const double &t) +{ double s = 0; if (t0 != t1) { - s = (t - t0)/(t1 - t0); + s = (t - t0) / (t1 - t0); } return (1.0 - s) * v0 + s * v1; } -inline color_point lerp(const color_point& v0, const color_point& v1, const double &t0, const double &t1, const double& t) { +inline color_point lerp(const color_point &v0, const color_point &v1, const double &t0, const double &t1, + const double &t) +{ double x = lerp(v0.x, v1.x, t0, t1, t); double y = lerp(v0.y, v1.y, t0, t1, t); double r = lerp(v0.r, v1.r, t0, t1, t); @@ -44,18 +60,19 @@ inline color_point lerp(const color_point& v0, const color_point& v1, const doub return (color_point(x, y, r, g, b)); } -inline double clamp(const double& value, const double& min, const double& max) { - if (value < min) return min; - if (value > max) return max; +inline double clamp(const double &value, const double &min, const double &max) +{ + if (value < min) + return min; + if (value > max) + return max; return value; } // h, s, and v in range 0 to 1. Returns rgb value useful for use in Cairo. -guint32 hsv_to_rgb(double h, double s, double v) { - - if (h < 0.0 || h > 1.0 || - s < 0.0 || s > 1.0 || - v < 0.0 || v > 1.0) { +guint32 hsv_to_rgb(double h, double s, double v) +{ + if (h < 0.0 || h > 1.0 || s < 0.0 || s > 1.0 || v < 0.0 || v > 1.0) { std::cerr << "ColorWheel: hsv_to_rgb: input out of bounds: (0-1)" << " h: " << h << " s: " << s << " v: " << v << std::endl; return 0x0; @@ -66,7 +83,8 @@ guint32 hsv_to_rgb(double h, double s, double v) { double b = v; if (s != 0.0) { - if (h == 1.0) h = 0.0; + if (h == 1.0) + h = 0.0; h *= 6.0; double f = h - (int)h; @@ -75,26 +93,49 @@ guint32 hsv_to_rgb(double h, double s, double v) { double t = v * (1.0 - s * (1.0 - f)); switch ((int)h) { - case 0: r = v; g = t; b = p; break; - case 1: r = q; g = v; b = p; break; - case 2: r = p; g = v; b = t; break; - case 3: r = p; g = q; b = v; break; - case 4: r = t; g = p; b = v; break; - case 5: r = v; g = p; b = q; break; - default: g_assert_not_reached(); + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + default: + g_assert_not_reached(); } } - guint32 rgb = (((int)floor (r*255 + 0.5) << 16) | - ((int)floor (g*255 + 0.5) << 8) | - ((int)floor (b*255 + 0.5) )); + guint32 rgb = (((int)floor(r * 255 + 0.5) << 16) | ((int)floor(g * 255 + 0.5) << 8) | ((int)floor(b * 255 + 0.5))); return rgb; } double luminance(guint32 color) { - double r(((color & 0xff0000) >> 16)/255.0); - double g(((color & 0xff00) >> 8)/255.0); - double b(((color & 0xff) )/255.0); + double r(((color & 0xff0000) >> 16) / 255.0); + double g(((color & 0xff00) >> 8) / 255.0); + double b(((color & 0xff)) / 255.0); return (r * 0.2125 + g * 0.7154 + b * 0.0721); } @@ -111,15 +152,11 @@ ColorWheel::ColorWheel() , _focus_on_ring(true) { set_name("ColorWheel"); - add_events(Gdk::BUTTON_PRESS_MASK | - Gdk::BUTTON_RELEASE_MASK | - Gdk::BUTTON_MOTION_MASK | - Gdk::KEY_PRESS_MASK ); + add_events(Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK | Gdk::BUTTON_MOTION_MASK | Gdk::KEY_PRESS_MASK); set_can_focus(); } -void -ColorWheel::set_rgb(const double& r, const double&g, const double&b, bool override_hue) +void ColorWheel::set_rgb(const double &r, const double &g, const double &b, bool override_hue) { double Min = std::min({r, g, b}); double Max = std::max({r, g, b}); @@ -130,11 +167,11 @@ ColorWheel::set_rgb(const double& r, const double&g, const double&b, bool overri } } else { if (Max == r) { - _hue = ((g-b)/(Max-Min) )/6.0; + _hue = ((g - b) / (Max - Min)) / 6.0; } else if (Max == g) { - _hue = ((b-r)/(Max-Min) + 2)/6.0; + _hue = ((b - r) / (Max - Min) + 2) / 6.0; } else { - _hue = ((r-g)/(Max-Min) + 4)/6.0; + _hue = ((r - g) / (Max - Min) + 4) / 6.0; } if (_hue < 0.0) { _hue += 1.0; @@ -143,66 +180,63 @@ ColorWheel::set_rgb(const double& r, const double&g, const double&b, bool overri if (Max == 0) { _saturation = 0; } else { - _saturation = (Max - Min)/Max; + _saturation = (Max - Min) / Max; } } -void -ColorWheel::get_rgb(double& r, double& g, double& b) +void ColorWheel::get_rgb(double &r, double &g, double &b) { guint32 color = get_rgb(); - r = ((color & 0xff0000) >> 16)/255.0; - g = ((color & 0x00ff00) >> 8)/255.0; - b = ((color & 0x0000ff) )/255.0; + r = ((color & 0xff0000) >> 16) / 255.0; + g = ((color & 0x00ff00) >> 8) / 255.0; + b = ((color & 0x0000ff)) / 255.0; } -guint32 -ColorWheel::get_rgb() +guint32 ColorWheel::get_rgb() { return hsv_to_rgb(_hue, _saturation, _value); } /** - * Paints padding for an edge of the triangle, - * using the (vertically) closest point. - * - * @param p0 A corner of the triangle. Not the same corner as p1 - * @param p1 A corner of the triangle. Not the same corner as p0 - * @param padding The height of the padding - * @param pad_upwards True if padding is above the line - * @param buffer Array that the triangle is painted to - * @param height Height of buffer - * @param stride Stride of buffer -*/ -void -draw_vertical_padding(color_point p0, color_point p1, int padding, bool pad_upwards, - guint32 *buffer, int height, int stride); + * Paints padding for an edge of the triangle, + * using the (vertically) closest point. + * + * @param p0 A corner of the triangle. Not the same corner as p1 + * @param p1 A corner of the triangle. Not the same corner as p0 + * @param padding The height of the padding + * @param pad_upwards True if padding is above the line + * @param buffer Array that the triangle is painted to + * @param height Height of buffer + * @param stride Stride of buffer + */ +void draw_vertical_padding(color_point p0, color_point p1, int padding, bool pad_upwards, guint32 *buffer, int height, + int stride); -bool -ColorWheel::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { +bool ColorWheel::on_draw(const ::Cairo::RefPtr<::Cairo::Context> &cr) +{ Gtk::Allocation allocation = get_allocation(); - const int width = allocation.get_width(); + const int width = allocation.get_width(); const int height = allocation.get_height(); const int stride = Cairo::ImageSurface::format_stride_for_width(Cairo::FORMAT_RGB24, width); - int cx = width/2; - int cy = height/2; + int cx = width / 2; + int cy = height / 2; int focus_line_width; int focus_padding; get_style_property("focus-line-width", focus_line_width); - get_style_property("focus-padding", focus_padding); + get_style_property("focus-padding", focus_padding); // Paint ring - guint32* buffer_ring = g_new (guint32, height * stride / 4); - double r_max = std::min( width, height)/2.0 - 2 * (focus_line_width + focus_padding); + guint32 *buffer_ring = g_new(guint32, height * stride / 4); + double r_max = std::min(width, height) / 2.0 - 2 * (focus_line_width + focus_padding); double r_min = r_max * (1.0 - _ring_width); - double r2_max = (r_max+1) * (r_max+1); // Must expand a bit to avoid edge effects. - double r2_min = (r_min-1) * (r_min-1); // Must shrink a bit to avoid edge effects. + double r2_max = (r_max + 1) * (r_max + 1); // Must expand a bit to avoid edge effects. + double r2_min = (r_min - 1) * (r_min - 1); // Must shrink a bit to avoid edge effects. for (int i = 0; i < height; ++i) { - guint32* p = buffer_ring + i * width; + guint32 *p = buffer_ring + i * width; double dy = (cy - i); for (int j = 0; j < width; ++j) { double dx = (j - cx); @@ -210,11 +244,11 @@ ColorWheel::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { if (r2 < r2_min || r2 > r2_max) { *p++ = 0; // Save calculation time. } else { - double angle = atan2 (dy, dx); + double angle = atan2(dy, dx); if (angle < 0.0) { angle += 2.0 * M_PI; } - double hue = angle/(2.0 * M_PI); + double hue = angle / (2.0 * M_PI); *p++ = hsv_to_rgb(hue, 1.0, 1.0); } @@ -222,31 +256,29 @@ ColorWheel::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { } Cairo::RefPtr<::Cairo::ImageSurface> source_ring = - ::Cairo::ImageSurface::create((unsigned char *)buffer_ring, - Cairo::FORMAT_RGB24, - width, height, stride); + ::Cairo::ImageSurface::create((unsigned char *)buffer_ring, Cairo::FORMAT_RGB24, width, height, stride); cr->set_antialias(Cairo::ANTIALIAS_SUBPIXEL); // Paint line on ring in source (so it gets clipped by stroke). double l = 0.0; guint32 color_on_ring = hsv_to_rgb(_hue, 1.0, 1.0); - if (luminance(color_on_ring) < 0.5) l = 1.0; + if (luminance(color_on_ring) < 0.5) + l = 1.0; Cairo::RefPtr<::Cairo::Context> cr_source_ring = ::Cairo::Context::create(source_ring); cr_source_ring->set_source_rgb(l, l, l); - cr_source_ring->move_to (cx, cy); - cr_source_ring->line_to (cx + cos(_hue * M_PI * 2.0) * r_max+1, - cy - sin(_hue * M_PI * 2.0) * r_max+1); + cr_source_ring->move_to(cx, cy); + cr_source_ring->line_to(cx + cos(_hue * M_PI * 2.0) * r_max + 1, cy - sin(_hue * M_PI * 2.0) * r_max + 1); cr_source_ring->stroke(); // Paint with ring surface, clipping to ring. cr->save(); cr->set_source(source_ring, 0, 0); - cr->set_line_width (r_max - r_min); + cr->set_line_width(r_max - r_min); cr->begin_new_path(); - cr->arc(cx, cy, (r_max + r_min)/2.0, 0, 2.0 * M_PI); + cr->arc(cx, cy, (r_max + r_min) / 2.0, 0, 2.0 * M_PI); cr->stroke(); cr->restore(); @@ -257,7 +289,7 @@ ColorWheel::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { Glib::RefPtr<Gtk::StyleContext> style_context = get_style_context(); style_context->render_focus(cr, 0, 0, width, height); } - + // Paint triangle. /* The triangle is painted by first finding color points on the * edges of the triangle at the same y value via linearly @@ -277,9 +309,9 @@ ColorWheel::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { guint32 color1 = hsv_to_rgb(_hue, 1.0, 0.0); guint32 color2 = hsv_to_rgb(_hue, 0.0, 1.0); - color_point p0 (x0, y0, color0); - color_point p1 (x1, y1, color1); - color_point p2 (x2, y2, color2); + color_point p0(x0, y0, color0); + color_point p1(x1, y1, color1); + color_point p2(x2, y2, color2); // Reorder so we paint from top down. if (p1.y > p2.y) { @@ -294,13 +326,12 @@ ColorWheel::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { std::swap(p0, p1); } - guint32* buffer_triangle = g_new (guint32, height * stride / 4); + guint32 *buffer_triangle = g_new(guint32, height * stride / 4); for (int y = 0; y < height; ++y) { guint32 *p = buffer_triangle + y * (stride / 4); - if (p0.y <= y+padding && y-padding < p2.y) { - + if (p0.y <= y + padding && y - padding < p2.y) { // Get values on side at position y. color_point side0; double y_inter = clamp(y, p0.y, p2.y); @@ -313,11 +344,11 @@ ColorWheel::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { // side0 should be on left if (side0.x > side1.x) { - std::swap (side0, side1); + std::swap(side0, side1); } int x_start = std::max(0, int(side0.x)); - int x_end = std::min(int(side1.x), width); + int x_end = std::min(int(side1.x), width); for (int x = 0; x < width; ++x) { if (x <= x_start) { @@ -345,9 +376,7 @@ ColorWheel::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { draw_vertical_padding(p1, p2, padding, pad_upwards, buffer_triangle, height, stride / 4); Cairo::RefPtr<::Cairo::ImageSurface> source_triangle = - ::Cairo::ImageSurface::create((unsigned char *)buffer_triangle, - Cairo::FORMAT_RGB24, - width, height, stride); + ::Cairo::ImageSurface::create((unsigned char *)buffer_triangle, Cairo::FORMAT_RGB24, width, height, stride); // Paint with triangle surface, clipping to triangle. cr->save(); @@ -362,12 +391,13 @@ ColorWheel::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { g_free(buffer_triangle); // Draw marker - double mx = x1 + (x2-x1) * _value + (x0-x2) * _saturation * _value; - double my = y1 + (y2-y1) * _value + (y0-y2) * _saturation * _value; + double mx = x1 + (x2 - x1) * _value + (x0 - x2) * _saturation * _value; + double my = y1 + (y2 - y1) * _value + (y0 - y2) * _saturation * _value; double a = 0.0; guint32 color_at_marker = get_rgb(); - if (luminance(color_at_marker) < 0.5) a = 1.0; + if (luminance(color_at_marker) < 0.5) + a = 1.0; cr->set_source_rgb(a, a, a); cr->begin_new_path(); @@ -377,9 +407,9 @@ ColorWheel::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { // Draw focus if (has_focus() && !_focus_on_ring) { Glib::RefPtr<Gtk::StyleContext> style_context = get_style_context(); - style_context->render_focus(cr, mx-4, my-4, 8, 8); // This doesn't seem to work. + style_context->render_focus(cr, mx - 4, my - 4, 8, 8); // This doesn't seem to work. cr->set_line_width(0.5); - cr->set_source_rgb(1-a, 1-a, 1-a); + cr->set_source_rgb(1 - a, 1 - a, 1 - a); cr->begin_new_path(); cr->arc(mx, my, 7, 0, 2 * M_PI); cr->stroke(); @@ -388,9 +418,8 @@ ColorWheel::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { return true; } -void -draw_vertical_padding(color_point p0, color_point p1, int padding, bool pad_upwards, - guint32 *buffer, int height, int stride) +void draw_vertical_padding(color_point p0, color_point p1, int padding, bool pad_upwards, guint32 *buffer, int height, + int stride) { // skip if horizontal padding is more accurate, e.g. if the edge is vertical double gradient = (p1.y - p0.y) / (p1.x - p0.x); @@ -431,24 +460,21 @@ draw_vertical_padding(color_point p0, color_point p1, int padding, bool pad_upwa } // Find triangle corners given hue and radius. -void -ColorWheel::triangle_corners(double &x0, double &y0, - double &x1, double &y1, - double &x2, double &y2) +void ColorWheel::triangle_corners(double &x0, double &y0, double &x1, double &y1, double &x2, double &y2) { Gtk::Allocation allocation = get_allocation(); - const int width = allocation.get_width(); + const int width = allocation.get_width(); const int height = allocation.get_height(); - int cx = width/2; - int cy = height/2; + int cx = width / 2; + int cy = height / 2; int focus_line_width; int focus_padding; get_style_property("focus-line-width", focus_line_width); - get_style_property("focus-padding", focus_padding); + get_style_property("focus-padding", focus_padding); - double r_max = std::min( width, height)/2.0 - 2 * (focus_line_width + focus_padding); + double r_max = std::min(width, height) / 2.0 - 2 * (focus_line_width + focus_padding); double r_min = r_max * (1.0 - _ring_width); double angle = _hue * 2.0 * M_PI; @@ -461,55 +487,53 @@ ColorWheel::triangle_corners(double &x0, double &y0, y2 = cy - sin(angle + 4.0 * M_PI / 3.0) * r_min; } -void -ColorWheel::set_from_xy(const double& x, const double& y) +void ColorWheel::set_from_xy(const double &x, const double &y) { Gtk::Allocation allocation = get_allocation(); - const int width = allocation.get_width(); + const int width = allocation.get_width(); const int height = allocation.get_height(); - double cx = width/2.0; - double cy = height/2.0; + double cx = width / 2.0; + double cy = height / 2.0; double r = std::min(cx, cy) * (1 - _ring_width); // We calculate RGB value under the cursor by rotating the cursor // and triangle by the hue value and looking at position in the // now right pointing triangle. - double angle = _hue * 2 * M_PI; + double angle = _hue * 2 * M_PI; double Sin = sin(angle); double Cos = cos(angle); - double xp = ((x-cx) * Cos - (y-cy) * Sin) / r; - double yp = ((x-cx) * Sin + (y-cy) * Cos) / r; + double xp = ((x - cx) * Cos - (y - cy) * Sin) / r; + double yp = ((x - cx) * Sin + (y - cy) * Cos) / r; double xt = lerp(0.0, 1.0, -0.5, 1.0, xp); xt = clamp(xt, 0, 1); - double dy = (1-xt) * cos(M_PI/6.0); + double dy = (1 - xt) * cos(M_PI / 6.0); double yt = lerp(0.0, 1.0, -dy, dy, yp); yt = clamp(yt, 0, 1); - color_point c0(0, 0, yt, yt, yt); // Grey point along base. - color_point c1(0, 0, hsv_to_rgb(_hue, 1, 1)); // Hue point at apex + color_point c0(0, 0, yt, yt, yt); // Grey point along base. + color_point c1(0, 0, hsv_to_rgb(_hue, 1, 1)); // Hue point at apex color_point c = lerp(c0, c1, 0, 1, xt); set_rgb(c.r, c.g, c.b, false); // Don't override previous hue. } -bool -ColorWheel::is_in_ring(const double& x, const double& y) +bool ColorWheel::is_in_ring(const double &x, const double &y) { Gtk::Allocation allocation = get_allocation(); - const int width = allocation.get_width(); + const int width = allocation.get_width(); const int height = allocation.get_height(); - int cx = width/2; - int cy = height/2; + int cx = width / 2; + int cy = height / 2; int focus_line_width; int focus_padding; get_style_property("focus-line-width", focus_line_width); - get_style_property("focus-padding", focus_padding); + get_style_property("focus-padding", focus_padding); - double r_max = std::min( width, height)/2.0 - 2 * (focus_line_width + focus_padding); + double r_max = std::min(width, height) / 2.0 - 2 * (focus_line_width + focus_padding); double r_min = r_max * (1.0 - _ring_width); double r2_max = r_max * r_max; double r2_min = r_min * r_min; @@ -517,25 +541,23 @@ ColorWheel::is_in_ring(const double& x, const double& y) double dx = x - cx; double dy = y - cy; double r2 = dx * dx + dy * dy; - + return (r2_min < r2 && r2 < r2_max); } -bool -ColorWheel::is_in_triangle(const double& x, const double& y) +bool ColorWheel::is_in_triangle(const double &x, const double &y) { double x0, y0, x1, y1, x2, y2; triangle_corners(x0, y0, x1, y1, x2, y2); - double det = (x2-x1) * (y0-y1) - (y2-y1) * (x0-x1); - double s = ((x -x1) * (y0-y1) - (y -y1) * (x0-x1)) / det; - double t = ((x2-x1) * (y -y1) - (y2-y1) * (x -x1)) / det; + double det = (x2 - x1) * (y0 - y1) - (y2 - y1) * (x0 - x1); + double s = ((x - x1) * (y0 - y1) - (y - y1) * (x0 - x1)) / det; + double t = ((x2 - x1) * (y - y1) - (y2 - y1) * (x - x1)) / det; - return (s >= 0.0 && t >= 0.0 && s+t <= 1.0); + return (s >= 0.0 && t >= 0.0 && s + t <= 1.0); } -bool -ColorWheel::on_focus(Gtk::DirectionType direction) +bool ColorWheel::on_focus(Gtk::DirectionType direction) { // In forward direction, focus passes from no focus to ring focus to triangle focus to no focus. if (!has_focus()) { @@ -567,19 +589,18 @@ ColorWheel::on_focus(Gtk::DirectionType direction) break; } - queue_draw(); // Update focus indicators. + queue_draw(); // Update focus indicators. return keep_focus; } -bool -ColorWheel::on_button_press_event(GdkEventButton* event) +bool ColorWheel::on_button_press_event(GdkEventButton *event) { // Seat is automatically grabbed. double x = event->x; double y = event->y; - if (is_in_ring(x, y) ) { + if (is_in_ring(x, y)) { _mode = DRAG_H; grab_focus(); _focus_on_ring = true; @@ -596,29 +617,27 @@ ColorWheel::on_button_press_event(GdkEventButton* event) return false; } -bool -ColorWheel::on_button_release_event(GdkEventButton* event) +bool ColorWheel::on_button_release_event(GdkEventButton *event) { _mode = DRAG_NONE; return true; } -bool -ColorWheel::on_motion_notify_event(GdkEventMotion* event) +bool ColorWheel::on_motion_notify_event(GdkEventMotion *event) { double x = event->x; double y = event->y; Gtk::Allocation allocation = get_allocation(); - const int width = allocation.get_width(); + const int width = allocation.get_width(); const int height = allocation.get_height(); - double cx = width/2.0; - double cy = height/2.0; + double cx = width / 2.0; + double cy = height / 2.0; if (_mode == DRAG_H) { - - double angle = -atan2(y-cy, x-cx); - if (angle < 0) angle += 2.0 * M_PI; + double angle = -atan2(y - cy, x - cx); + if (angle < 0) + angle += 2.0 * M_PI; _hue = angle / (2.0 * M_PI); queue_draw(); @@ -627,7 +646,6 @@ ColorWheel::on_motion_notify_event(GdkEventMotion* event) } if (_mode == DRAG_SV) { - set_from_xy(x, y); _signal_color_changed.emit(); queue_draw(); @@ -637,29 +655,24 @@ ColorWheel::on_motion_notify_event(GdkEventMotion* event) return false; } -bool -ColorWheel::on_key_press_event(GdkEventKey* key_event) +bool ColorWheel::on_key_press_event(GdkEventKey *key_event) { bool consumed = false; unsigned int key = 0; - gdk_keymap_translate_keyboard_state( Gdk::Display::get_default()->get_keymap(), - key_event->hardware_keycode, - (GdkModifierType)key_event->state, - 0, &key, nullptr, nullptr, nullptr ); + gdk_keymap_translate_keyboard_state(Gdk::Display::get_default()->get_keymap(), key_event->hardware_keycode, + (GdkModifierType)key_event->state, 0, &key, nullptr, nullptr, nullptr); double x0, y0, x1, y1, x2, y2; triangle_corners(x0, y0, x1, y1, x2, y2); // Marker position - double mx = x1 + (x2-x1) * _value + (x0-x2) * _saturation * _value; - double my = y1 + (y2-y1) * _value + (y0-y2) * _saturation * _value; - + double mx = x1 + (x2 - x1) * _value + (x0 - x2) * _saturation * _value; + double my = y1 + (y2 - y1) * _value + (y0 - y2) * _saturation * _value; - const double delta_hue = 2.0/360.0; + const double delta_hue = 2.0 / 360.0; switch (key) { - case GDK_KEY_Up: case GDK_KEY_KP_Up: if (_focus_on_ring) { @@ -703,12 +716,13 @@ ColorWheel::on_key_press_event(GdkEventKey* key_event) } consumed = true; break; - } if (consumed) { - if (_hue >= 1.0) _hue -= 1.0; - if (_hue < 0.0) _hue += 1.0; + if (_hue >= 1.0) + _hue -= 1.0; + if (_hue < 0.0) + _hue += 1.0; _signal_color_changed.emit(); queue_draw(); } @@ -716,15 +730,14 @@ ColorWheel::on_key_press_event(GdkEventKey* key_event) return consumed; } -sigc::signal<void> -ColorWheel::signal_color_changed() +sigc::signal<void> ColorWheel::signal_color_changed() { return _signal_color_changed; } -} // Namespace Inkscape -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/widget/ink-color-wheel.h b/src/ui/widget/ink-color-wheel.h index c6333b7024a59bb0de84335fc799dd1fd9a43474..bc205f05f7abcee4341e4e44fbc28c2755e074d8 100644 --- a/src/ui/widget/ink-color-wheel.h +++ b/src/ui/widget/ink-color-wheel.h @@ -19,46 +19,45 @@ namespace Inkscape { namespace UI { namespace Widget { - + class ColorWheel : public Gtk::DrawingArea { public: ColorWheel(); - void set_rgb(const double& r, const double& g, const double& b, bool override_hue = true); - void get_rgb(double& r, double& g, double& b); + void set_rgb(const double &r, const double &g, const double &b, bool override_hue = true); + void get_rgb(double &r, double &g, double &b); guint32 get_rgb(); - bool is_adjusting() {return _mode != DRAG_NONE;} + bool is_adjusting() { return _mode != DRAG_NONE; } protected: - bool on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) override; + bool on_draw(const ::Cairo::RefPtr<::Cairo::Context> &cr) override; private: - void triangle_corners(double& x0, double& y0, - double& x1, double& y1, - double& x2, double& y2); - void set_from_xy(const double& x, const double& y); - bool is_in_ring( const double& x, const double& y); - bool is_in_triangle(const double& x, const double& y); + void triangle_corners(double &x0, double &y0, double &x1, double &y1, double &x2, double &y2); + void set_from_xy(const double &x, const double &y); + bool is_in_ring(const double &x, const double &y); + bool is_in_triangle(const double &x, const double &y); - enum DragMode { + enum DragMode + { DRAG_NONE, DRAG_H, DRAG_SV }; - double _hue; // Range [0,1) + double _hue; // Range [0,1) double _saturation; double _value; double _ring_width; DragMode _mode; - bool _focus_on_ring; + bool _focus_on_ring; // Callbacks bool on_focus(Gtk::DirectionType direction) override; - bool on_button_press_event(GdkEventButton* event) override; - bool on_button_release_event(GdkEventButton* event) override; - bool on_motion_notify_event(GdkEventMotion* event) override; - bool on_key_press_event(GdkEventKey* key_event) override; + bool on_button_press_event(GdkEventButton *event) override; + bool on_button_release_event(GdkEventButton *event) override; + bool on_motion_notify_event(GdkEventMotion *event) override; + bool on_key_press_event(GdkEventKey *key_event) override; // Signals public: @@ -66,12 +65,11 @@ public: protected: sigc::signal<void> _signal_color_changed; - }; -} // Namespace Inkscape -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif // INK_COLOR_WHEEL_H /* diff --git a/src/ui/widget/ink-flow-box.cpp b/src/ui/widget/ink-flow-box.cpp index 8485dd932eb661c3837f7dc28ddb9682f576a5f1..a41ab9041263a2bfb4702754203ad240b25e7a4e 100644 --- a/src/ui/widget/ink-flow-box.cpp +++ b/src/ui/widget/ink-flow-box.cpp @@ -11,11 +11,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "preferences.h" -#include "ui/icon-loader.h" #include "ui/widget/ink-flow-box.h" + #include <gtkmm/adjustment.h> +#include "preferences.h" +#include "ui/icon-loader.h" + namespace Inkscape { namespace UI { namespace Widget { diff --git a/src/ui/widget/ink-flow-box.h b/src/ui/widget/ink-flow-box.h index be84ee9882b2175618250374d572f72538093f99..24650a5e4462bfdc3256603797106f57b4aea4d6 100644 --- a/src/ui/widget/ink-flow-box.h +++ b/src/ui/widget/ink-flow-box.h @@ -29,8 +29,9 @@ namespace Widget { * A flowbox widget with filter controller for dialogs. */ -class InkFlowBox : public Gtk::VBox { - public: +class InkFlowBox : public Gtk::VBox +{ +public: InkFlowBox(const gchar *name); ~InkFlowBox() override; void insert(Gtk::Widget *widget, Glib::ustring label, gint pos, bool active, int minwidth); @@ -43,7 +44,7 @@ class InkFlowBox : public Gtk::VBox { * Construct a InkFlowBox. */ - private: +private: Gtk::FlowBox _flowbox; Gtk::ActionBar _controller; gint showing; diff --git a/src/ui/widget/ink-ruler.cpp b/src/ui/widget/ink-ruler.cpp index 392b261c2756e4048345fe60d65c18f0295de7df..557e7a9377f1da18916799bbbc04add59035f5f1 100644 --- a/src/ui/widget/ink-ruler.cpp +++ b/src/ui/widget/ink-ruler.cpp @@ -12,28 +12,26 @@ #include "ink-ruler.h" -#include <iostream> #include <cmath> +#include <iostream> #include "util/units.h" struct SPRulerMetric { - gdouble ruler_scale[16]; - gint subdivide[5]; + gdouble ruler_scale[16]; + gint subdivide[5]; }; // Ruler metric for general use. static SPRulerMetric const ruler_metric_general = { - { 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000 }, - { 1, 5, 10, 50, 100 } -}; + {1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000}, + {1, 5, 10, 50, 100}}; // Ruler metric for inch scales. static SPRulerMetric const ruler_metric_inches = { - { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 }, - { 1, 2, 4, 8, 16 } -}; + {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768}, + {1, 2, 4, 8, 16}}; // Half width of pointer triangle. static double half_width = 5.0; @@ -55,16 +53,14 @@ Ruler::Ruler(Gtk::Orientation orientation) { set_name("InkRuler"); - set_events(Gdk::POINTER_MOTION_MASK | - Gdk::BUTTON_PRESS_MASK | // For guide creation - Gdk::BUTTON_RELEASE_MASK ); + set_events(Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_PRESS_MASK | // For guide creation + Gdk::BUTTON_RELEASE_MASK); signal_motion_notify_event().connect(sigc::mem_fun(*this, &Ruler::draw_marker_callback)); } // Set display unit for ruler. -void -Ruler::set_unit(Inkscape::Util::Unit const *unit) +void Ruler::set_unit(Inkscape::Util::Unit const *unit) { if (_unit != unit) { _unit = unit; @@ -75,11 +71,9 @@ Ruler::set_unit(Inkscape::Util::Unit const *unit) } // Set range for ruler, update ticks. -void -Ruler::set_range(const double& lower, const double& upper) +void Ruler::set_range(const double &lower, const double &upper) { if (_lower != lower || _upper != upper) { - _lower = lower; _upper = upper; _max_size = _upper - _lower; @@ -94,18 +88,16 @@ Ruler::set_range(const double& lower, const double& upper) // Add a widget (i.e. canvas) to monitor. Note, we don't worry about removing this signal as // our ruler is tied tightly to the canvas, if one is destroyed, so is the other. -void -Ruler::add_track_widget(Gtk::Widget& widget) +void Ruler::add_track_widget(Gtk::Widget &widget) { - widget.signal_motion_notify_event().connect(sigc::mem_fun(*this, &Ruler::draw_marker_callback), false); // false => connect first + widget.signal_motion_notify_event().connect(sigc::mem_fun(*this, &Ruler::draw_marker_callback), + false); // false => connect first } - // Draws marker in response to motion events from canvas. Position is defined in ruler pixel // coordinates. The routine assumes that the ruler is the same width (height) as the canvas. If // not, one could use Gtk::Widget::translate_coordinates() to convert the coordinates. -bool -Ruler::draw_marker_callback(GdkEventMotion* motion_event) +bool Ruler::draw_marker_callback(GdkEventMotion *motion_event) { double position = 0; if (_orientation == Gtk::ORIENTATION_HORIZONTAL) { @@ -115,7 +107,6 @@ Ruler::draw_marker_callback(GdkEventMotion* motion_event) } if (position != _position) { - _position = position; // Find region to repaint (old and new marker positions). @@ -132,10 +123,8 @@ Ruler::draw_marker_callback(GdkEventMotion* motion_event) return false; } - // Find smallest dimension of ruler based on font size. -void -Ruler::size_request (Gtk::Requisition& requisition) const +void Ruler::size_request(Gtk::Requisition &requisition) const { // Get border size Glib::RefPtr<Gtk::StyleContext> style_context = get_style_context(); @@ -149,7 +138,7 @@ Ruler::size_request (Gtk::Requisition& requisition) const } int size = 2 + font_size * 2.0; // Room for labels and ticks - + int width = border.get_left() + border.get_right(); int height = border.get_top() + border.get_bottom(); @@ -166,16 +155,14 @@ Ruler::size_request (Gtk::Requisition& requisition) const requisition.height = height; } -void -Ruler::get_preferred_width_vfunc (int& minimum_width, int& natural_width) const +void Ruler::get_preferred_width_vfunc(int &minimum_width, int &natural_width) const { Gtk::Requisition requisition; size_request(requisition); minimum_width = natural_width = requisition.width; -} +} -void -Ruler::get_preferred_height_vfunc (int& minimum_height, int& natural_height) const +void Ruler::get_preferred_height_vfunc(int &minimum_height, int &natural_height) const { Gtk::Requisition requisition; size_request(requisition); @@ -186,10 +173,8 @@ Ruler::get_preferred_height_vfunc (int& minimum_height, int& natural_height) con // Note: in principle, there should not be a border (ruler ends should match canvas ends). If there // is a border, we calculate tick position ignoring border width at ends of ruler but move the // ticks and position marker inside the border. -bool -Ruler::draw_scale(const::Cairo::RefPtr<::Cairo::Context>& cr_in) +bool Ruler::draw_scale(const ::Cairo::RefPtr<::Cairo::Context> &cr_in) { - // Get style information Glib::RefPtr<Gtk::StyleContext> style_context = get_style_context(); Gtk::Border border = style_context->get_border(get_state_flags()); @@ -202,7 +187,7 @@ Ruler::draw_scale(const::Cairo::RefPtr<::Cairo::Context>& cr_in) } Gtk::Allocation allocation = get_allocation(); - int awidth = allocation.get_width(); + int awidth = allocation.get_width(); int aheight = allocation.get_height(); // if (allocation.get_x() != 0 || allocation.get_y() != 0) { @@ -222,14 +207,14 @@ Ruler::draw_scale(const::Cairo::RefPtr<::Cairo::Context>& cr_in) Gdk::Cairo::set_source_rgba(cr, foreground); // Ruler size (only smallest dimension used later). - int rwidth = awidth - (border.get_left() + border.get_right()); - int rheight = aheight - (border.get_top() + border.get_bottom()); + int rwidth = awidth - (border.get_left() + border.get_right()); + int rheight = aheight - (border.get_top() + border.get_bottom()); // Draw bottom/right line of ruler if (_orientation == Gtk::ORIENTATION_HORIZONTAL) { - cr->rectangle( 0, aheight - border.get_bottom() - 1, awidth, 1); + cr->rectangle(0, aheight - border.get_bottom() - 1, awidth, 1); } else { - cr->rectangle( awidth - border.get_left() - 1, 0, 1, aheight); + cr->rectangle(awidth - border.get_left() - 1, 0, 1, aheight); std::swap(awidth, aheight); std::swap(rwidth, rheight); } @@ -239,12 +224,12 @@ Ruler::draw_scale(const::Cairo::RefPtr<::Cairo::Context>& cr_in) // Figure out scale. Largest ticks must be far enough apart to fit largest text in vertical ruler. // We actually require twice the distance. - unsigned int scale = std::ceil (_max_size); // Largest number + unsigned int scale = std::ceil(_max_size); // Largest number Glib::ustring scale_text = std::to_string(scale); unsigned int digits = scale_text.length() + 1; // Add one for negative sign. unsigned int minimum = digits * font_size * 2; - double pixels_per_unit = awidth/_max_size; // pixel per distance + double pixels_per_unit = awidth / _max_size; // pixel per distance SPRulerMetric ruler_metric = ruler_metric_general; if (_unit == Inkscape::Util::unit_table.getUnit("in")) { @@ -252,32 +237,35 @@ Ruler::draw_scale(const::Cairo::RefPtr<::Cairo::Context>& cr_in) } unsigned scale_index; - for (scale_index = 0; scale_index < G_N_ELEMENTS (ruler_metric.ruler_scale)-1; ++scale_index) { - if (ruler_metric.ruler_scale[scale_index] * std::abs (pixels_per_unit) > minimum) break; + for (scale_index = 0; scale_index < G_N_ELEMENTS(ruler_metric.ruler_scale) - 1; ++scale_index) { + if (ruler_metric.ruler_scale[scale_index] * std::abs(pixels_per_unit) > minimum) + break; } // Now we find out what is the subdivide index for the closest ticks we can draw unsigned divide_index; - for (divide_index = 0; divide_index < G_N_ELEMENTS (ruler_metric.subdivide)-1; ++divide_index) { - if (ruler_metric.ruler_scale[scale_index] * std::abs (pixels_per_unit) < 5 * ruler_metric.subdivide[divide_index+1]) break; + for (divide_index = 0; divide_index < G_N_ELEMENTS(ruler_metric.subdivide) - 1; ++divide_index) { + if (ruler_metric.ruler_scale[scale_index] * std::abs(pixels_per_unit) < + 5 * ruler_metric.subdivide[divide_index + 1]) + break; } // We'll loop over all ticks. - double pixels_per_tick = pixels_per_unit * - ruler_metric.ruler_scale[scale_index] / ruler_metric.subdivide[divide_index]; + double pixels_per_tick = + pixels_per_unit * ruler_metric.ruler_scale[scale_index] / ruler_metric.subdivide[divide_index]; - double units_per_tick = pixels_per_tick/pixels_per_unit; - double ticks_per_unit = 1.0/units_per_tick; + double units_per_tick = pixels_per_tick / pixels_per_unit; + double ticks_per_unit = 1.0 / units_per_tick; // Find first and last ticks int start = 0; int end = 0; if (_lower < _upper) { - start = std::floor (_lower * ticks_per_unit); - end = std::ceil (_upper * ticks_per_unit); + start = std::floor(_lower * ticks_per_unit); + end = std::ceil(_upper * ticks_per_unit); } else { - start = std::floor (_upper * ticks_per_unit); - end = std::ceil (_lower * ticks_per_unit); + start = std::floor(_upper * ticks_per_unit); + end = std::ceil(_lower * ticks_per_unit); } // std::cout << " start: " << start @@ -287,22 +275,21 @@ Ruler::draw_scale(const::Cairo::RefPtr<::Cairo::Context>& cr_in) // << std::endl; // Loop over all ticks - for (int i = start; i < end+1; ++i) { - + for (int i = start; i < end + 1; ++i) { // Position of tick (add 0.5 to center tick on pixel). - double position = std::floor(i*pixels_per_tick - _lower*pixels_per_unit) + 0.5; + double position = std::floor(i * pixels_per_tick - _lower * pixels_per_unit) + 0.5; // Height of tick int height = rheight; for (int j = divide_index; j > 0; --j) { - if (i%ruler_metric.subdivide[j] == 0) break; - height = height/2 + 1; + if (i % ruler_metric.subdivide[j] == 0) + break; + height = height / 2 + 1; } // Draw text for major ticks. - if (i%ruler_metric.subdivide[divide_index] == 0) { - - int label_value = std::round(i*units_per_tick); + if (i % ruler_metric.subdivide[divide_index] == 0) { + int label_value = std::round(i * units_per_tick); Glib::ustring label = std::to_string(label_value); Glib::RefPtr<Pango::Layout> layout = create_pango_layout(""); @@ -310,10 +297,10 @@ Ruler::draw_scale(const::Cairo::RefPtr<::Cairo::Context>& cr_in) if (_orientation == Gtk::ORIENTATION_HORIZONTAL) { layout->set_text(label); - cr->move_to (position+2, border.get_top()); + cr->move_to(position + 2, border.get_top()); layout->show_in_cairo_context(cr); } else { - cr->move_to (border.get_left(), position); + cr->move_to(border.get_left(), position); int n = 0; for (char const &c : label) { std::string s(1, c); @@ -321,8 +308,8 @@ Ruler::draw_scale(const::Cairo::RefPtr<::Cairo::Context>& cr_in) int text_width; int text_height; layout->get_pixel_size(text_width, text_height); - cr->move_to(border.get_left() + (aheight-text_width)/2.0 - 1, - position + n*0.7*text_height - 1); + cr->move_to(border.get_left() + (aheight - text_width) / 2.0 - 1, + position + n * 0.7 * text_height - 1); layout->show_in_cairo_context(cr); ++n; } @@ -346,7 +333,7 @@ Ruler::draw_scale(const::Cairo::RefPtr<::Cairo::Context>& cr_in) cr->line_to(position, rheight + border.get_top()); } else { cr->move_to(rheight + border.get_left() - height, position); - cr->line_to(rheight + border.get_left(), position); + cr->line_to(rheight + border.get_left(), position); } cr->stroke(); } @@ -357,17 +344,15 @@ Ruler::draw_scale(const::Cairo::RefPtr<::Cairo::Context>& cr_in) } // Draw position marker, we use doubles here. -void -Ruler::draw_marker(const Cairo::RefPtr<::Cairo::Context>& cr) +void Ruler::draw_marker(const Cairo::RefPtr<::Cairo::Context> &cr) { - // Get style information Glib::RefPtr<Gtk::StyleContext> style_context = get_style_context(); Gtk::Border border = style_context->get_border(get_state_flags()); Gdk::RGBA foreground = style_context->get_color(get_state_flags()); Gtk::Allocation allocation = get_allocation(); - const int awidth = allocation.get_width(); + const int awidth = allocation.get_width(); const int aheight = allocation.get_height(); // Temp (to verify our redraw rectangle encloses position marker). @@ -379,13 +364,13 @@ Ruler::draw_marker(const Cairo::RefPtr<::Cairo::Context>& cr) Gdk::Cairo::set_source_rgba(cr, foreground); if (_orientation == Gtk::ORIENTATION_HORIZONTAL) { double offset = aheight - border.get_bottom(); - cr->move_to(_position, offset); + cr->move_to(_position, offset); cr->line_to(_position - half_width, offset - half_width); cr->line_to(_position + half_width, offset - half_width); cr->close_path(); - } else { + } else { double offset = awidth - border.get_right(); - cr->move_to(offset, _position); + cr->move_to(offset, _position); cr->line_to(offset - half_width, _position - half_width); cr->line_to(offset - half_width, _position + half_width); cr->close_path(); @@ -395,19 +380,18 @@ Ruler::draw_marker(const Cairo::RefPtr<::Cairo::Context>& cr) // This is a pixel aligned integer rectangle that encloses the position marker. Used to define the // redraw area. -Cairo::RectangleInt -Ruler::marker_rect() +Cairo::RectangleInt Ruler::marker_rect() { // Get border size Glib::RefPtr<Gtk::StyleContext> style_context = get_style_context(); Gtk::Border border = style_context->get_border(get_state_flags()); Gtk::Allocation allocation = get_allocation(); - const int awidth = allocation.get_width(); + const int awidth = allocation.get_width(); const int aheight = allocation.get_height(); - int rwidth = awidth - border.get_left() - border.get_right(); - int rheight = aheight - border.get_top() - border.get_bottom(); + int rwidth = awidth - border.get_left() - border.get_right(); + int rheight = aheight - border.get_top() - border.get_bottom(); Cairo::RectangleInt rect; rect.x = 0; @@ -419,12 +403,12 @@ Ruler::marker_rect() if (_orientation == Gtk::ORIENTATION_HORIZONTAL) { rect.x = std::floor(_position - half_width); rect.y = std::floor(border.get_top() + rheight - half_width); - rect.width = std::ceil(half_width * 2.0 + 1); + rect.width = std::ceil(half_width * 2.0 + 1); rect.height = std::ceil(half_width); } else { rect.x = std::floor(border.get_left() + rwidth - half_width); rect.y = std::floor(_position - half_width); - rect.width = std::ceil(half_width); + rect.width = std::ceil(half_width); rect.height = std::ceil(half_width * 2.0 + 1); } @@ -432,25 +416,23 @@ Ruler::marker_rect() } // Draw the ruler using the tick backing store. -bool -Ruler::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { - +bool Ruler::on_draw(const ::Cairo::RefPtr<::Cairo::Context> &cr) +{ if (!_backing_store_valid) { - draw_scale (cr); + draw_scale(cr); } - cr->set_source (_backing_store, 0, 0); + cr->set_source(_backing_store, 0, 0); cr->paint(); - draw_marker (cr); + draw_marker(cr); return true; } // Update ruler on style change (font-size, etc.) -void -Ruler::on_style_updated() { - +void Ruler::on_style_updated() +{ Gtk::DrawingArea::on_style_updated(); _backing_store_valid = false; // If font-size changed we need to regenerate store. @@ -459,9 +441,9 @@ Ruler::on_style_updated() { queue_draw(); } -} // Namespace Inkscape -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/widget/ink-ruler.h b/src/ui/widget/ink-ruler.h index 0b9f9af5ac6e084c2c1e23e0af020a547f91e636..989c2e53403bd1260c88ce263f565f73375f114d 100644 --- a/src/ui/widget/ink-ruler.h +++ b/src/ui/widget/ink-ruler.h @@ -19,53 +19,53 @@ namespace Inkscape { namespace Util { class Unit; } -} +} // namespace Inkscape namespace Inkscape { namespace UI { namespace Widget { - + class Ruler : public Gtk::DrawingArea { public: Ruler(Gtk::Orientation orientation); void set_unit(Inkscape::Util::Unit const *unit); - void set_range(const double& lower, const double& upper); + void set_range(const double &lower, const double &upper); - void add_track_widget(Gtk::Widget& widget); - bool draw_marker_callback(GdkEventMotion* motion_event); + void add_track_widget(Gtk::Widget &widget); + bool draw_marker_callback(GdkEventMotion *motion_event); - void size_request(Gtk::Requisition& requisition) const; - void get_preferred_width_vfunc( int& minimum_width, int& natural_width ) const override; - void get_preferred_height_vfunc(int& minimum_height, int& natural_height) const override; + void size_request(Gtk::Requisition &requisition) const; + void get_preferred_width_vfunc(int &minimum_width, int &natural_width) const override; + void get_preferred_height_vfunc(int &minimum_height, int &natural_height) const override; protected: - bool draw_scale(const Cairo::RefPtr<::Cairo::Context>& cr); - void draw_marker(const Cairo::RefPtr<::Cairo::Context>& cr); + bool draw_scale(const Cairo::RefPtr<::Cairo::Context> &cr); + void draw_marker(const Cairo::RefPtr<::Cairo::Context> &cr); Cairo::RectangleInt marker_rect(); - bool on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) override; + bool on_draw(const ::Cairo::RefPtr<::Cairo::Context> &cr) override; void on_style_updated() override; private: - Gtk::Orientation _orientation; + Gtk::Orientation _orientation; - Inkscape::Util::Unit const* _unit; + Inkscape::Util::Unit const *_unit; double _lower; double _upper; double _position; double _max_size; double _font_scale; - bool _backing_store_valid; + bool _backing_store_valid; Cairo::RefPtr<::Cairo::Surface> _backing_store; Cairo::RectangleInt _rect; }; -} // Namespace Inkscape -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif // INK_RULER_H /* diff --git a/src/ui/widget/ink-spinscale.cpp b/src/ui/widget/ink-spinscale.cpp index 116ffec7d81e5b5dc109f0c19e4562130ba22008..e5cd69328431057e2777cac580a5116b8d4d3bd5 100644 --- a/src/ui/widget/ink-spinscale.cpp +++ b/src/ui/widget/ink-spinscale.cpp @@ -17,268 +17,249 @@ */ #include "ink-spinscale.h" -#include <gdkmm/general.h> + +#include <gdk/gdk.h> #include <gdkmm/cursor.h> #include <gdkmm/event.h> - +#include <gdkmm/general.h> #include <gtkmm/spinbutton.h> - -#include <gdk/gdk.h> - #include <iostream> #include <utility> -InkScale::InkScale(Glib::RefPtr<Gtk::Adjustment> adjustment, Gtk::SpinButton* spinbutton) - : Glib::ObjectBase("InkScale") - , Gtk::Scale(adjustment) - , _spinbutton(spinbutton) - , _dragging(false) - , _drag_start(0) - , _drag_offset(0) +InkScale::InkScale(Glib::RefPtr<Gtk::Adjustment> adjustment, Gtk::SpinButton *spinbutton) + : Glib::ObjectBase("InkScale") + , Gtk::Scale(adjustment) + , _spinbutton(spinbutton) + , _dragging(false) + , _drag_start(0) + , _drag_offset(0) { - set_name("InkScale"); - // std::cout << "GType name: " << G_OBJECT_TYPE_NAME(gobj()) << std::endl; + set_name("InkScale"); + // std::cout << "GType name: " << G_OBJECT_TYPE_NAME(gobj()) << std::endl; } -void -InkScale::set_label(Glib::ustring label) { - _label = label; +void InkScale::set_label(Glib::ustring label) +{ + _label = label; } -bool -InkScale::on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) { - - Gtk::Range::on_draw(cr); - - // Get SpinButton style info... - auto style_spin = _spinbutton->get_style_context(); - auto state_spin = style_spin->get_state(); - Gdk::RGBA text_color = style_spin->get_color( state_spin ); - - // Create Pango layout. - auto layout_label = create_pango_layout(_label); - layout_label->set_ellipsize( Pango::ELLIPSIZE_END ); - layout_label->set_width(PANGO_SCALE * get_width()); - - // Get y location of SpinButton text (to match vertical position of SpinButton text). - int x, y; - _spinbutton->get_layout_offsets(x, y); - - // Fill widget proportional to value. - double fraction = get_fraction(); - - // Get trough rectangle and clipping point for text. - Gdk::Rectangle slider_area = get_range_rect(); - double clip_text_x = slider_area.get_x() + slider_area.get_width() * fraction; - - // Render text in normal text color. - cr->save(); - cr->rectangle(clip_text_x, 0, get_width(), get_height()); - cr->clip(); - Gdk::Cairo::set_source_rgba(cr, text_color); - //cr->set_source_rgba(0, 0, 0, 1); - cr->move_to(5, y ); - layout_label->show_in_cairo_context(cr); - cr->restore(); - - // Render text, clipped, in white over bar (TODO: use same color as SpinButton progress bar). - cr->save(); - cr->rectangle(0, 0, clip_text_x, get_height()); - cr->clip(); - cr->set_source_rgba(1, 1, 1, 1); - cr->move_to(5, y); - layout_label->show_in_cairo_context(cr); - cr->restore(); - - return true; -} +bool InkScale::on_draw(const ::Cairo::RefPtr<::Cairo::Context> &cr) +{ + Gtk::Range::on_draw(cr); + + // Get SpinButton style info... + auto style_spin = _spinbutton->get_style_context(); + auto state_spin = style_spin->get_state(); + Gdk::RGBA text_color = style_spin->get_color(state_spin); + + // Create Pango layout. + auto layout_label = create_pango_layout(_label); + layout_label->set_ellipsize(Pango::ELLIPSIZE_END); + layout_label->set_width(PANGO_SCALE * get_width()); + + // Get y location of SpinButton text (to match vertical position of SpinButton text). + int x, y; + _spinbutton->get_layout_offsets(x, y); + + // Fill widget proportional to value. + double fraction = get_fraction(); + + // Get trough rectangle and clipping point for text. + Gdk::Rectangle slider_area = get_range_rect(); + double clip_text_x = slider_area.get_x() + slider_area.get_width() * fraction; + + // Render text in normal text color. + cr->save(); + cr->rectangle(clip_text_x, 0, get_width(), get_height()); + cr->clip(); + Gdk::Cairo::set_source_rgba(cr, text_color); + // cr->set_source_rgba(0, 0, 0, 1); + cr->move_to(5, y); + layout_label->show_in_cairo_context(cr); + cr->restore(); + + // Render text, clipped, in white over bar (TODO: use same color as SpinButton progress bar). + cr->save(); + cr->rectangle(0, 0, clip_text_x, get_height()); + cr->clip(); + cr->set_source_rgba(1, 1, 1, 1); + cr->move_to(5, y); + layout_label->show_in_cairo_context(cr); + cr->restore(); -bool -InkScale::on_button_press_event(GdkEventButton* button_event) { + return true; +} - if (! (button_event->state & GDK_MOD1_MASK) ) { - bool constrained = button_event->state & GDK_CONTROL_MASK; - set_adjustment_value(button_event->x, constrained); - } +bool InkScale::on_button_press_event(GdkEventButton *button_event) +{ + if (!(button_event->state & GDK_MOD1_MASK)) { + bool constrained = button_event->state & GDK_CONTROL_MASK; + set_adjustment_value(button_event->x, constrained); + } - // Dragging must be initialized after any adjustment due to button press. - _dragging = true; - _drag_start = button_event->x; - _drag_offset = get_width() * get_fraction(); + // Dragging must be initialized after any adjustment due to button press. + _dragging = true; + _drag_start = button_event->x; + _drag_offset = get_width() * get_fraction(); - return true; + return true; } -bool -InkScale::on_button_release_event(GdkEventButton* button_event) { - - _dragging = false; - return true; +bool InkScale::on_button_release_event(GdkEventButton *button_event) +{ + _dragging = false; + return true; } -bool -InkScale::on_motion_notify_event(GdkEventMotion* motion_event) { - - double x = motion_event->x; - - if (_dragging) { - - if (! (motion_event->state & GDK_MOD1_MASK) ) { - // Absolute change - bool constrained = motion_event->state & GDK_CONTROL_MASK; - set_adjustment_value(x, constrained); - } else { - // Relative change - double xx = (_drag_offset + (x - _drag_start) * 0.1); - set_adjustment_value(xx); +bool InkScale::on_motion_notify_event(GdkEventMotion *motion_event) +{ + double x = motion_event->x; + + if (_dragging) { + if (!(motion_event->state & GDK_MOD1_MASK)) { + // Absolute change + bool constrained = motion_event->state & GDK_CONTROL_MASK; + set_adjustment_value(x, constrained); + } else { + // Relative change + double xx = (_drag_offset + (x - _drag_start) * 0.1); + set_adjustment_value(xx); + } + return true; } - return true; - } - if (! (motion_event->state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK))) { + if (!(motion_event->state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK))) { + auto display = get_display(); + auto cursor = Gdk::Cursor::create(display, Gdk::SB_UP_ARROW); + // Get Gdk::window (not Gtk::window).. set cursor for entire window. + // Would need to unset with leave event. + // get_window()->set_cursor( cursor ); - auto display = get_display(); - auto cursor = Gdk::Cursor::create(display, Gdk::SB_UP_ARROW); - // Get Gdk::window (not Gtk::window).. set cursor for entire window. - // Would need to unset with leave event. - // get_window()->set_cursor( cursor ); + // Can't see how to do this the C++ way since GdkEventMotion + // is a structure with a C window member. There is a gdkmm + // wrapping function for Gdk::EventMotion but only in unstable. - // Can't see how to do this the C++ way since GdkEventMotion - // is a structure with a C window member. There is a gdkmm - // wrapping function for Gdk::EventMotion but only in unstable. - - // If the cursor theme doesn't have the `sb_up_arrow` cursor then the pointer will be NULL - if (cursor) - gdk_window_set_cursor( motion_event->window, cursor->gobj() ); - } + // If the cursor theme doesn't have the `sb_up_arrow` cursor then the pointer will be NULL + if (cursor) + gdk_window_set_cursor(motion_event->window, cursor->gobj()); + } - return false; + return false; } -double -InkScale::get_fraction() { - - Glib::RefPtr<Gtk::Adjustment> adjustment = get_adjustment(); - double upper = adjustment->get_upper(); - double lower = adjustment->get_lower(); - double value = adjustment->get_value(); - double fraction = (value - lower)/(upper - lower); +double InkScale::get_fraction() +{ + Glib::RefPtr<Gtk::Adjustment> adjustment = get_adjustment(); + double upper = adjustment->get_upper(); + double lower = adjustment->get_lower(); + double value = adjustment->get_value(); + double fraction = (value - lower) / (upper - lower); - return fraction; + return fraction; } -void -InkScale::set_adjustment_value(double x, bool constrained) { - - Glib::RefPtr<Gtk::Adjustment> adjustment = get_adjustment(); - double upper = adjustment->get_upper(); - double lower = adjustment->get_lower(); - double range = upper-lower; - - Gdk::Rectangle slider_area = get_range_rect(); - double fraction = (x - slider_area.get_x()) / (double)slider_area.get_width(); - double value = fraction * range + lower; - - if (constrained) { - // TODO: do we want preferences for (any of) these? - if (fmod(range+1,16) == 0) { - value = round(value/16) * 16; - } else if (range >= 1000 && fmod(upper,100) == 0) { - value = round(value/100) * 100; - } else if (range >= 100 && fmod(upper,10) == 0) { - value = round(value/10) * 10; - } else if (range > 20 && fmod(upper,5) == 0) { - value = round(value/5) * 5; - } else if (range > 2) { - value = round(value); - } else if (range <= 2) { - value = round(value*10) / 10; +void InkScale::set_adjustment_value(double x, bool constrained) +{ + Glib::RefPtr<Gtk::Adjustment> adjustment = get_adjustment(); + double upper = adjustment->get_upper(); + double lower = adjustment->get_lower(); + double range = upper - lower; + + Gdk::Rectangle slider_area = get_range_rect(); + double fraction = (x - slider_area.get_x()) / (double)slider_area.get_width(); + double value = fraction * range + lower; + + if (constrained) { + // TODO: do we want preferences for (any of) these? + if (fmod(range + 1, 16) == 0) { + value = round(value / 16) * 16; + } else if (range >= 1000 && fmod(upper, 100) == 0) { + value = round(value / 100) * 100; + } else if (range >= 100 && fmod(upper, 10) == 0) { + value = round(value / 10) * 10; + } else if (range > 20 && fmod(upper, 5) == 0) { + value = round(value / 5) * 5; + } else if (range > 2) { + value = round(value); + } else if (range <= 2) { + value = round(value * 10) / 10; + } } - } - adjustment->set_value( value ); + adjustment->set_value(value); } /*******************************************************************/ -InkSpinScale::InkSpinScale(double value, double lower, - double upper, double step_increment, - double page_increment, double page_size) +InkSpinScale::InkSpinScale(double value, double lower, double upper, double step_increment, double page_increment, + double page_size) { - set_name("InkSpinScale"); + set_name("InkSpinScale"); - g_assert (upper - lower > 0); + g_assert(upper - lower > 0); - _adjustment = Gtk::Adjustment::create(value, - lower, - upper, - step_increment, - page_increment, - page_size); + _adjustment = Gtk::Adjustment::create(value, lower, upper, step_increment, page_increment, page_size); - _spinbutton = Gtk::manage(new Gtk::SpinButton(_adjustment)); - _spinbutton->set_numeric(); - _spinbutton->signal_key_release_event().connect(sigc::mem_fun(*this,&InkSpinScale::on_key_release_event),false); + _spinbutton = Gtk::manage(new Gtk::SpinButton(_adjustment)); + _spinbutton->set_numeric(); + _spinbutton->signal_key_release_event().connect(sigc::mem_fun(*this, &InkSpinScale::on_key_release_event), false); - _scale = Gtk::manage(new InkScale(_adjustment, _spinbutton)); - _scale->set_draw_value(false); + _scale = Gtk::manage(new InkScale(_adjustment, _spinbutton)); + _scale->set_draw_value(false); - pack_end( *_spinbutton, Gtk::PACK_SHRINK ); - pack_end( *_scale, Gtk::PACK_EXPAND_WIDGET ); + pack_end(*_spinbutton, Gtk::PACK_SHRINK); + pack_end(*_scale, Gtk::PACK_EXPAND_WIDGET); } InkSpinScale::InkSpinScale(Glib::RefPtr<Gtk::Adjustment> adjustment) - : _adjustment(std::move(adjustment)) + : _adjustment(std::move(adjustment)) { - set_name("InkSpinScale"); + set_name("InkSpinScale"); - g_assert (_adjustment->get_upper() - _adjustment->get_lower() > 0); + g_assert(_adjustment->get_upper() - _adjustment->get_lower() > 0); - _spinbutton = Gtk::manage(new Gtk::SpinButton(_adjustment)); - _spinbutton->set_numeric(); + _spinbutton = Gtk::manage(new Gtk::SpinButton(_adjustment)); + _spinbutton->set_numeric(); - _scale = Gtk::manage(new InkScale(_adjustment, _spinbutton)); - _scale->set_draw_value(false); + _scale = Gtk::manage(new InkScale(_adjustment, _spinbutton)); + _scale->set_draw_value(false); - pack_end( *_spinbutton, Gtk::PACK_SHRINK ); - pack_end( *_scale, Gtk::PACK_EXPAND_WIDGET ); + pack_end(*_spinbutton, Gtk::PACK_SHRINK); + pack_end(*_scale, Gtk::PACK_EXPAND_WIDGET); } -void -InkSpinScale::set_label(Glib::ustring label) { - _scale->set_label(label); +void InkSpinScale::set_label(Glib::ustring label) +{ + _scale->set_label(label); } -void -InkSpinScale::set_digits(int digits) { - _spinbutton->set_digits(digits); +void InkSpinScale::set_digits(int digits) +{ + _spinbutton->set_digits(digits); } -int -InkSpinScale::get_digits() const { - return _spinbutton->get_digits(); +int InkSpinScale::get_digits() const +{ + return _spinbutton->get_digits(); } -void -InkSpinScale::set_focus_widget(GtkWidget * focus_widget) { - _focus_widget = focus_widget; +void InkSpinScale::set_focus_widget(GtkWidget *focus_widget) +{ + _focus_widget = focus_widget; } // Return focus to canvas. -bool -InkSpinScale::on_key_release_event(GdkEventKey* key_event) { - - switch (key_event->keyval) { - case GDK_KEY_Escape: - case GDK_KEY_Return: - case GDK_KEY_KP_Enter: - { - if (_focus_widget) { - gtk_widget_grab_focus( _focus_widget ); - } +bool InkSpinScale::on_key_release_event(GdkEventKey *key_event) +{ + switch (key_event->keyval) { + case GDK_KEY_Escape: + case GDK_KEY_Return: + case GDK_KEY_KP_Enter: { + if (_focus_widget) { + gtk_widget_grab_focus(_focus_widget); + } + } break; } - break; - } - return false; + return false; } diff --git a/src/ui/widget/ink-spinscale.h b/src/ui/widget/ink-spinscale.h index ada7efd294099f0570a7d8e3c13491a450801889..c132711bc1b2fe7d39da74a2ce5bd0c540f93659 100644 --- a/src/ui/widget/ink-spinscale.h +++ b/src/ui/widget/ink-spinscale.h @@ -20,77 +20,69 @@ */ #include <glibmm/ustring.h> - #include <gtkmm/box.h> #include <gtkmm/scale.h> namespace Gtk { - class SpinButton; +class SpinButton; } class InkScale : public Gtk::Scale { - public: - InkScale(Glib::RefPtr<Gtk::Adjustment>, Gtk::SpinButton* spinbutton); - ~InkScale() override = default;; - - void set_label(Glib::ustring label); - - bool on_draw(const::Cairo::RefPtr<::Cairo::Context>& cr) override; +public: + InkScale(Glib::RefPtr<Gtk::Adjustment>, Gtk::SpinButton *spinbutton); + ~InkScale() override = default; + ; - protected: + void set_label(Glib::ustring label); - bool on_button_press_event(GdkEventButton* button_event) override; - bool on_button_release_event(GdkEventButton* button_event) override; - bool on_motion_notify_event(GdkEventMotion* motion_event) override; + bool on_draw(const ::Cairo::RefPtr<::Cairo::Context> &cr) override; - private: +protected: + bool on_button_press_event(GdkEventButton *button_event) override; + bool on_button_release_event(GdkEventButton *button_event) override; + bool on_motion_notify_event(GdkEventMotion *motion_event) override; - double get_fraction(); - void set_adjustment_value(double x, bool constrained = false); +private: + double get_fraction(); + void set_adjustment_value(double x, bool constrained = false); - Gtk::SpinButton * _spinbutton; // Needed to get placement/text color. - Glib::ustring _label; + Gtk::SpinButton *_spinbutton; // Needed to get placement/text color. + Glib::ustring _label; - bool _dragging; - double _drag_start; - double _drag_offset; + bool _dragging; + double _drag_start; + double _drag_offset; }; class InkSpinScale : public Gtk::Box { - public: - - // Create an InkSpinScale with a new adjustment. - InkSpinScale(double value, - double lower, - double upper, - double step_increment = 1, - double page_increment = 10, - double page_size = 0); - - // Create an InkSpinScale with a preexisting adjustment. - InkSpinScale(Glib::RefPtr<Gtk::Adjustment>); - - ~InkSpinScale() override = default;; +public: + // Create an InkSpinScale with a new adjustment. + InkSpinScale(double value, double lower, double upper, double step_increment = 1, double page_increment = 10, + double page_size = 0); - void set_label(Glib::ustring label); - void set_digits(int digits); - int get_digits() const; - void set_focus_widget(GtkWidget *focus_widget); - Glib::RefPtr<Gtk::Adjustment> get_adjustment() { return _adjustment; }; + // Create an InkSpinScale with a preexisting adjustment. + InkSpinScale(Glib::RefPtr<Gtk::Adjustment>); - protected: + ~InkSpinScale() override = default; + ; - InkScale* _scale; - Gtk::SpinButton* _spinbutton; - Glib::RefPtr<Gtk::Adjustment> _adjustment; - GtkWidget* _focus_widget = nullptr; + void set_label(Glib::ustring label); + void set_digits(int digits); + int get_digits() const; + void set_focus_widget(GtkWidget *focus_widget); + Glib::RefPtr<Gtk::Adjustment> get_adjustment() { return _adjustment; }; - bool on_key_release_event(GdkEventKey* key_event) override; +protected: + InkScale *_scale; + Gtk::SpinButton *_spinbutton; + Glib::RefPtr<Gtk::Adjustment> _adjustment; + GtkWidget *_focus_widget = nullptr; - private: + bool on_key_release_event(GdkEventKey *key_event) override; +private: }; #endif // INK_SPINSCALE_H diff --git a/src/ui/widget/insertordericon.cpp b/src/ui/widget/insertordericon.cpp index 0a21f3c3773d0e19a168f85bb2969bf3e74cf03e..658d09d470cd29e90803ef573984648a59cead5c 100644 --- a/src/ui/widget/insertordericon.cpp +++ b/src/ui/widget/insertordericon.cpp @@ -19,16 +19,15 @@ namespace Inkscape { namespace UI { namespace Widget { -InsertOrderIcon::InsertOrderIcon() : - Glib::ObjectBase(typeid(InsertOrderIcon)), - Gtk::CellRendererPixbuf(), - _pixTopName(INKSCAPE_ICON("insert-top")), - _pixBottomName(INKSCAPE_ICON("insert-bottom")), - _property_active(*this, "active", 0), - _property_pixbuf_top(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)), - _property_pixbuf_bottom(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) +InsertOrderIcon::InsertOrderIcon() + : Glib::ObjectBase(typeid(InsertOrderIcon)) + , Gtk::CellRendererPixbuf() + , _pixTopName(INKSCAPE_ICON("insert-top")) + , _pixBottomName(INKSCAPE_ICON("insert-bottom")) + , _property_active(*this, "active", 0) + , _property_pixbuf_top(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) + , _property_pixbuf_bottom(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) { - property_mode() = Gtk::CELL_RENDERER_MODE_ACTIVATABLE; _property_pixbuf_top = sp_get_icon_pixbuf(_pixTopName, GTK_ICON_SIZE_MENU); @@ -37,45 +36,37 @@ InsertOrderIcon::InsertOrderIcon() : property_pixbuf() = Glib::RefPtr<Gdk::Pixbuf>(nullptr); } - -void InsertOrderIcon::get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const +void InsertOrderIcon::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 InsertOrderIcon::get_preferred_width_vfunc(Gtk::Widget& widget, - int& min_w, - int& nat_w) const +void InsertOrderIcon::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; } } -void InsertOrderIcon::render_vfunc( const Cairo::RefPtr<Cairo::Context>& cr, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - Gtk::CellRendererState flags ) +void InsertOrderIcon::render_vfunc(const Cairo::RefPtr<Cairo::Context> &cr, Gtk::Widget &widget, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) { - switch (_property_active.get_value()) - { + switch (_property_active.get_value()) { case 1: property_pixbuf() = _property_pixbuf_top; break; @@ -86,20 +77,16 @@ void InsertOrderIcon::render_vfunc( const Cairo::RefPtr<Cairo::Context>& cr, property_pixbuf() = Glib::RefPtr<Gdk::Pixbuf>(nullptr); break; } - Gtk::CellRendererPixbuf::render_vfunc( cr, widget, background_area, cell_area, flags ); + Gtk::CellRendererPixbuf::render_vfunc(cr, widget, background_area, cell_area, flags); } -bool InsertOrderIcon::activate_vfunc(GdkEvent* /*event*/, - Gtk::Widget& /*widget*/, - const Glib::ustring& /*path*/, - const Gdk::Rectangle& /*background_area*/, - const Gdk::Rectangle& /*cell_area*/, +bool InsertOrderIcon::activate_vfunc(GdkEvent * /*event*/, Gtk::Widget & /*widget*/, const Glib::ustring & /*path*/, + const Gdk::Rectangle & /*background_area*/, const Gdk::Rectangle & /*cell_area*/, Gtk::CellRendererState /*flags*/) { return false; } - } // namespace Widget } // namespace UI } // namespace Inkscape @@ -114,5 +101,3 @@ bool InsertOrderIcon::activate_vfunc(GdkEvent* /*event*/, End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - - diff --git a/src/ui/widget/insertordericon.h b/src/ui/widget/insertordericon.h index 7ca1cefec1f5ea579d6d45ddbd72c4f4c51d1b70..5198e64f31112c3ac1cf314de1e0875cf4f0cd84 100644 --- a/src/ui/widget/insertordericon.h +++ b/src/ui/widget/insertordericon.h @@ -10,67 +10,53 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <glibmm/property.h> #include <gtkmm/cellrendererpixbuf.h> #include <gtkmm/widget.h> -#include <glibmm/property.h> - namespace Inkscape { namespace UI { namespace Widget { -class InsertOrderIcon : public Gtk::CellRendererPixbuf { +class InsertOrderIcon : public Gtk::CellRendererPixbuf +{ public: InsertOrderIcon(); - ~InsertOrderIcon() override = default;; + ~InsertOrderIcon() override = default; + ; Glib::PropertyProxy<int> property_active() { return _property_active.get_proxy(); } - Glib::PropertyProxy< Glib::RefPtr<Gdk::Pixbuf> > property_pixbuf_on(); - Glib::PropertyProxy< Glib::RefPtr<Gdk::Pixbuf> > property_pixbuf_off(); + Glib::PropertyProxy<Glib::RefPtr<Gdk::Pixbuf>> property_pixbuf_on(); + Glib::PropertyProxy<Glib::RefPtr<Gdk::Pixbuf>> property_pixbuf_off(); protected: + 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) override; - 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 ) override; + void get_preferred_width_vfunc(Gtk::Widget &widget, int &min_w, int &nat_w) const override; - void get_preferred_width_vfunc(Gtk::Widget& widget, - int& min_w, - int& nat_w) const override; - - void get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const override; - - bool activate_vfunc(GdkEvent *event, - Gtk::Widget &widget, - const Glib::ustring &path, - const Gdk::Rectangle &background_area, - const Gdk::Rectangle &cell_area, - Gtk::CellRendererState flags) override; + void get_preferred_height_vfunc(Gtk::Widget &widget, int &min_h, int &nat_h) const override; + bool activate_vfunc(GdkEvent *event, Gtk::Widget &widget, const Glib::ustring &path, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) override; private: int phys; - + Glib::ustring _pixTopName; Glib::ustring _pixBottomName; - + Glib::Property<int> _property_active; - Glib::Property< Glib::RefPtr<Gdk::Pixbuf> > _property_pixbuf_top; - Glib::Property< Glib::RefPtr<Gdk::Pixbuf> > _property_pixbuf_bottom; - + Glib::Property<Glib::RefPtr<Gdk::Pixbuf>> _property_pixbuf_top; + Glib::Property<Glib::RefPtr<Gdk::Pixbuf>> _property_pixbuf_bottom; }; - - } // namespace Widget } // namespace UI } // namespace Inkscape - #endif /* __UI_DIALOG_IMAGETOGGLER_H__ */ /* diff --git a/src/ui/widget/label-tool-item.cpp b/src/ui/widget/label-tool-item.cpp index 979cfa235c793c6fdd1f90bc3020dee9b6d3104d..5ed02ffc7ba94fd419ff90d06c9a6305dc69f808 100644 --- a/src/ui/widget/label-tool-item.cpp +++ b/src/ui/widget/label-tool-item.cpp @@ -22,7 +22,7 @@ namespace Widget { * \param[in] label The text to display in the label * \param[in] mnemonic True if text should use a mnemonic */ -LabelToolItem::LabelToolItem(const Glib::ustring& label, bool mnemonic) +LabelToolItem::LabelToolItem(const Glib::ustring &label, bool mnemonic) : _label(Gtk::manage(new Gtk::Label(label, mnemonic))) { add(*_label); @@ -34,8 +34,7 @@ LabelToolItem::LabelToolItem(const Glib::ustring& label, bool mnemonic) * * \param[in] str The markup text */ -void -LabelToolItem::set_markup(const Glib::ustring& str) +void LabelToolItem::set_markup(const Glib::ustring &str) { _label->set_markup(str); } @@ -45,15 +44,14 @@ LabelToolItem::set_markup(const Glib::ustring& str) * * \param[in] setting true if the label text should be parsed for markup */ -void -LabelToolItem::set_use_markup(bool setting) +void LabelToolItem::set_use_markup(bool setting) { _label->set_use_markup(setting); } -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: mode:c++ diff --git a/src/ui/widget/label-tool-item.h b/src/ui/widget/label-tool-item.h index 1fe68920663c7783e6c88a8aa6cfcdaaba8fc6c0..c69e643d90e95e4f441a48f751cc70b56e87a862 100644 --- a/src/ui/widget/label-tool-item.h +++ b/src/ui/widget/label-tool-item.h @@ -24,19 +24,20 @@ namespace Widget { /** * \brief A label that can be added to a toolbar */ -class LabelToolItem : public Gtk::ToolItem { +class LabelToolItem : public Gtk::ToolItem +{ private: Gtk::Label *_label; public: - LabelToolItem(const Glib::ustring& label, bool mnemonic = false); + LabelToolItem(const Glib::ustring &label, bool mnemonic = false); - void set_markup(const Glib::ustring& str); + void set_markup(const Glib::ustring &str); void set_use_markup(bool setting = true); }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif /* diff --git a/src/ui/widget/labelled.cpp b/src/ui/widget/labelled.cpp index 54a56e4b483eb160b869976952c90b02585dac70..a4220beb5946f4d393efb3e546ffdcab4e8e70a5 100644 --- a/src/ui/widget/labelled.cpp +++ b/src/ui/widget/labelled.cpp @@ -10,22 +10,21 @@ */ #include "labelled.h" -#include "ui/icon-loader.h" + #include <gtkmm/image.h> #include <gtkmm/label.h> +#include "ui/icon-loader.h" + namespace Inkscape { namespace UI { namespace Widget { -Labelled::Labelled(Glib::ustring const &label, Glib::ustring const &tooltip, - Gtk::Widget *widget, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) - : _widget(widget), - _label(new Gtk::Label(label, Gtk::ALIGN_START, Gtk::ALIGN_CENTER, mnemonic)), - _suffix(nullptr) +Labelled::Labelled(Glib::ustring const &label, Glib::ustring const &tooltip, Gtk::Widget *widget, + Glib::ustring const &suffix, Glib::ustring const &icon, bool mnemonic) + : _widget(widget) + , _label(new Gtk::Label(label, Gtk::ALIGN_START, Gtk::ALIGN_CENTER, mnemonic)) + , _suffix(nullptr) { g_assert(g_utf8_validate(icon.c_str(), -1, nullptr)); if (icon != "") { @@ -45,46 +44,38 @@ Labelled::Labelled(Glib::ustring const &label, Glib::ustring const &tooltip, widget->set_tooltip_text(tooltip); } - void Labelled::setWidgetSizeRequest(int width, int height) { if (_widget) _widget->set_size_request(width, height); - - } -Gtk::Label const * -Labelled::getLabel() const +Gtk::Label const *Labelled::getLabel() const { return _label; } -void -Labelled::setLabelText(const Glib::ustring &str) +void Labelled::setLabelText(const Glib::ustring &str) { _label->set_text(str); } -void -Labelled::setTooltipText(const Glib::ustring &tooltip) +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 ) +bool Labelled::on_mnemonic_activate(bool group_cycling) { - return _widget->mnemonic_activate ( group_cycling ); + return _widget->mnemonic_activate(group_cycling); } -void -Labelled::set_hexpand(bool expand) +void Labelled::set_hexpand(bool expand) { // should only have 2 children, but second child may not be _widget - child_property_pack_type(*get_children().back()) = expand ? Gtk::PACK_END - : Gtk::PACK_START; - + child_property_pack_type(*get_children().back()) = expand ? Gtk::PACK_END : Gtk::PACK_START; + Gtk::HBox::set_hexpand(expand); } diff --git a/src/ui/widget/labelled.h b/src/ui/widget/labelled.h index 113d2e2be7b9779fc1a67a35dad4f95e1ff27bbb..ee45ebe163c5dc92e03495f81eb4e82be334cfab 100644 --- a/src/ui/widget/labelled.h +++ b/src/ui/widget/labelled.h @@ -17,7 +17,7 @@ namespace Gtk { class Image; class Label; -} +} // namespace Gtk namespace Inkscape { namespace UI { @@ -29,10 +29,10 @@ namespace Widget { class Labelled : public Gtk::HBox { protected: - Gtk::Widget *_widget; - Gtk::Label *_label; - Gtk::Label *_suffix; - Gtk::Image *_icon; + Gtk::Widget *_widget; + Gtk::Label *_label; + Gtk::Label *_suffix; + Gtk::Image *_icon; public: /** @@ -47,11 +47,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to true). */ - Labelled(Glib::ustring const &label, Glib::ustring const &tooltip, - Gtk::Widget *widget, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Labelled(Glib::ustring const &label, Glib::ustring const &tooltip, Gtk::Widget *widget, + Glib::ustring const &suffix = "", Glib::ustring const &icon = "", bool mnemonic = true); /** * Allow the setting of the width of the labelled widget @@ -67,7 +64,7 @@ public: void set_hexpand(bool expand = true); private: - bool on_mnemonic_activate( bool group_cycling ) override; + bool on_mnemonic_activate(bool group_cycling) override; }; } // namespace Widget diff --git a/src/ui/widget/layer-selector.cpp b/src/ui/widget/layer-selector.cpp index e0ce1952ce52f67ee0b3f4fa7ab0cad30ad5809e..fe95b6e66db2c57555fb59b61769f0d4b72e4235 100644 --- a/src/ui/widget/layer-selector.cpp +++ b/src/ui/widget/layer-selector.cpp @@ -11,28 +11,23 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> -#include <string> - #include <boost/range/adaptor/filtered.hpp> #include <boost/range/adaptor/reversed.hpp> - +#include <cstring> #include <glibmm/i18n.h> +#include <string> #include "desktop.h" #include "document-undo.h" #include "document.h" #include "layer-manager.h" -#include "verbs.h" - #include "ui/dialog/layer-properties.h" #include "ui/icon-loader.h" #include "ui/icon-names.h" #include "ui/util.h" #include "ui/widget/canvas.h" // Focus widget - #include "util/reverse-list.h" - +#include "verbs.h" #include "xml/node-event-vector.h" namespace Inkscape { @@ -41,10 +36,12 @@ namespace Widget { namespace { -class AlternateIcons : public Gtk::HBox { +class AlternateIcons : public Gtk::HBox +{ public: AlternateIcons(Gtk::BuiltinIconSize size, Glib::ustring const &a, Glib::ustring const &b) - : _a(nullptr), _b(nullptr) + : _a(nullptr) + , _b(nullptr) { set_name("AlternateIcons"); if (!a.empty()) { @@ -61,7 +58,8 @@ public: } bool state() const { return _state; } - void setState(bool state) { + void setState(bool state) + { _state = state; if (_state) { if (_a) { @@ -86,7 +84,7 @@ private: bool _state; }; -} +} // namespace /** LayerSelector constructor. Creates lock and hide buttons, * initializes the layer dropdown selector with a label renderer, @@ -94,46 +92,33 @@ private: * selector is changed. */ LayerSelector::LayerSelector(SPDesktop *desktop) -: _desktop(nullptr), _layer(nullptr) + : _desktop(nullptr) + , _layer(nullptr) { set_name("LayerSelector"); AlternateIcons *label; - label = Gtk::manage(new AlternateIcons(Gtk::ICON_SIZE_MENU, - INKSCAPE_ICON("object-visible"), INKSCAPE_ICON("object-hidden"))); + label = Gtk::manage( + new AlternateIcons(Gtk::ICON_SIZE_MENU, INKSCAPE_ICON("object-visible"), INKSCAPE_ICON("object-hidden"))); _visibility_toggle.add(*label); _visibility_toggle.signal_toggled().connect( - sigc::compose( - sigc::mem_fun(*label, &AlternateIcons::setState), - sigc::mem_fun(_visibility_toggle, &Gtk::ToggleButton::get_active) - ) - ); + sigc::compose(sigc::mem_fun(*label, &AlternateIcons::setState), + sigc::mem_fun(_visibility_toggle, &Gtk::ToggleButton::get_active))); _visibility_toggled_connection = _visibility_toggle.signal_toggled().connect( - sigc::compose( - sigc::mem_fun(*this, &LayerSelector::_hideLayer), - sigc::mem_fun(_visibility_toggle, &Gtk::ToggleButton::get_active) - ) - ); + sigc::compose(sigc::mem_fun(*this, &LayerSelector::_hideLayer), + sigc::mem_fun(_visibility_toggle, &Gtk::ToggleButton::get_active))); _visibility_toggle.set_relief(Gtk::RELIEF_NONE); _visibility_toggle.set_tooltip_text(_("Toggle current layer visibility")); pack_start(_visibility_toggle, Gtk::PACK_EXPAND_PADDING); - label = Gtk::manage(new AlternateIcons(Gtk::ICON_SIZE_MENU, - INKSCAPE_ICON("object-unlocked"), INKSCAPE_ICON("object-locked"))); + label = Gtk::manage( + new AlternateIcons(Gtk::ICON_SIZE_MENU, INKSCAPE_ICON("object-unlocked"), INKSCAPE_ICON("object-locked"))); _lock_toggle.add(*label); - _lock_toggle.signal_toggled().connect( - sigc::compose( - sigc::mem_fun(*label, &AlternateIcons::setState), - sigc::mem_fun(_lock_toggle, &Gtk::ToggleButton::get_active) - ) - ); - _lock_toggled_connection = _lock_toggle.signal_toggled().connect( - sigc::compose( - sigc::mem_fun(*this, &LayerSelector::_lockLayer), - sigc::mem_fun(_lock_toggle, &Gtk::ToggleButton::get_active) - ) - ); + _lock_toggle.signal_toggled().connect(sigc::compose(sigc::mem_fun(*label, &AlternateIcons::setState), + sigc::mem_fun(_lock_toggle, &Gtk::ToggleButton::get_active))); + _lock_toggled_connection = _lock_toggle.signal_toggled().connect(sigc::compose( + sigc::mem_fun(*this, &LayerSelector::_lockLayer), sigc::mem_fun(_lock_toggle, &Gtk::ToggleButton::get_active))); _lock_toggle.set_relief(Gtk::RELIEF_NONE); _lock_toggle.set_tooltip_text(_("Lock or unlock current layer")); @@ -145,20 +130,17 @@ LayerSelector::LayerSelector(SPDesktop *desktop) _layer_model = Gtk::ListStore::create(_model_columns); _selector.set_model(_layer_model); _selector.pack_start(_label_renderer); - _selector.set_cell_data_func( - _label_renderer, - sigc::mem_fun(*this, &LayerSelector::_prepareLabelRenderer) - ); - - _selection_changed_connection = _selector.signal_changed().connect( - sigc::mem_fun(*this, &LayerSelector::_setDesktopLayer) - ); + _selector.set_cell_data_func(_label_renderer, sigc::mem_fun(*this, &LayerSelector::_prepareLabelRenderer)); + + _selection_changed_connection = + _selector.signal_changed().connect(sigc::mem_fun(*this, &LayerSelector::_setDesktopLayer)); setDesktop(desktop); } /** Destructor - disconnects signal handler */ -LayerSelector::~LayerSelector() { +LayerSelector::~LayerSelector() +{ setDesktop(nullptr); _selection_changed_connection.disconnect(); } @@ -168,31 +150,34 @@ LayerSelector::~LayerSelector() { * given \a desktop, and attaches its signals to this one. * Then it selects the current layer for the desktop. */ -void LayerSelector::setDesktop(SPDesktop *desktop) { - if ( desktop == _desktop ) { +void LayerSelector::setDesktop(SPDesktop *desktop) +{ + if (desktop == _desktop) { return; } if (_desktop) { -// _desktop_shutdown_connection.disconnect(); + // _desktop_shutdown_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); + // g_signal_handlers_disconnect_by_func(_desktop, (gpointer)&detach, this); } _desktop = desktop; if (_desktop) { // TODO we need a different signal for this, really..s -// _desktop_shutdown_connection = _desktop->connectShutdown( -// sigc::bind (sigc::ptr_fun (detach), this)); -// g_signal_connect_after(_desktop, "shutdown", GCallback(detach), this); + // _desktop_shutdown_connection = _desktop->connectShutdown( + // sigc::bind (sigc::ptr_fun (detach), this)); + // g_signal_connect_after(_desktop, "shutdown", GCallback(detach), this); 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) ); + 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()); @@ -201,31 +186,37 @@ void LayerSelector::setDesktop(SPDesktop *desktop) { namespace { -class is_layer { +class is_layer +{ public: - is_layer(SPDesktop *desktop) : _desktop(desktop) {} - bool operator()(SPObject &object) const { - return _desktop->isLayer(&object); - } + is_layer(SPDesktop *desktop) + : _desktop(desktop) + {} + bool operator()(SPObject &object) const { return _desktop->isLayer(&object); } + private: SPDesktop *_desktop; }; -class column_matches_object { +class column_matches_object +{ public: - column_matches_object(Gtk::TreeModelColumn<SPObject *> const &column, - SPObject &object) - : _column(column), _object(object) {} - bool operator()(Gtk::TreeModel::const_iterator const &iter) const { - SPObject *current=(*iter)[_column]; + column_matches_object(Gtk::TreeModelColumn<SPObject *> const &column, SPObject &object) + : _column(column) + , _object(object) + {} + bool operator()(Gtk::TreeModel::const_iterator const &iter) const + { + SPObject *current = (*iter)[_column]; return current == &_object; } + private: Gtk::TreeModelColumn<SPObject *> const &_column; SPObject &_object; }; -} +} // namespace void LayerSelector::_layersChanged() { @@ -240,9 +231,10 @@ void LayerSelector::_layersChanged() /** Selects the given layer in the dropdown selector. */ -void LayerSelector::_selectLayer(SPObject *layer) { - using Inkscape::Util::List; +void LayerSelector::_selectLayer(SPObject *layer) +{ using Inkscape::Util::cons; + using Inkscape::Util::List; using Inkscape::Util::reverse_list; _selection_changed_connection.block(); @@ -255,7 +247,7 @@ void LayerSelector::_selectLayer(SPObject *layer) { _layer_model->erase(first_row); } - SPObject *root=_desktop->currentRoot(); + SPObject *root = _desktop->currentRoot(); if (_layer) { sp_object_unref(_layer, nullptr); @@ -263,21 +255,16 @@ void LayerSelector::_selectLayer(SPObject *layer) { } if (layer) { - List<SPObject &> hierarchy=reverse_list<SPObject::ParentIterator>(layer, root); - if ( layer == root ) { + List<SPObject &> hierarchy = reverse_list<SPObject::ParentIterator>(layer, root); + if (layer == root) { _buildEntries(0, cons(*root, hierarchy)); } else if (hierarchy) { _buildSiblingEntries(0, *root, hierarchy); } - Gtk::TreeIter row( - std::find_if( - _layer_model->children().begin(), - _layer_model->children().end(), - column_matches_object(_model_columns.object, *layer) - ) - ); - if ( row != _layer_model->children().end() ) { + Gtk::TreeIter row(std::find_if(_layer_model->children().begin(), _layer_model->children().end(), + column_matches_object(_model_columns.object, *layer))); + if (row != _layer_model->children().end()) { _selector.set_active(row); } @@ -285,16 +272,16 @@ void LayerSelector::_selectLayer(SPObject *layer) { sp_object_ref(_layer, nullptr); } - if ( !layer || layer == root ) { + if (!layer || layer == root) { _visibility_toggle.set_sensitive(false); _visibility_toggle.set_active(false); _lock_toggle.set_sensitive(false); _lock_toggle.set_active(false); } else { _visibility_toggle.set_sensitive(true); - _visibility_toggle.set_active(( SP_IS_ITEM(layer) ? SP_ITEM(layer)->isHidden() : false )); + _visibility_toggle.set_active((SP_IS_ITEM(layer) ? SP_ITEM(layer)->isHidden() : false)); _lock_toggle.set_sensitive(true); - _lock_toggle.set_active(( SP_IS_ITEM(layer) ? SP_ITEM(layer)->isLocked() : false )); + _lock_toggle.set_active((SP_IS_ITEM(layer) ? SP_ITEM(layer)->isLocked() : false)); } _lock_toggled_connection.unblock(); @@ -304,10 +291,11 @@ void LayerSelector::_selectLayer(SPObject *layer) { /** Sets the current desktop layer to the actively selected layer. */ -void LayerSelector::_setDesktopLayer() { +void LayerSelector::_setDesktopLayer() +{ Gtk::ListStore::iterator selected(_selector.get_active()); - SPObject *layer=_selector.get_active()->get_value(_model_columns.object); - if ( _desktop && layer ) { + SPObject *layer = _selector.get_active()->get_value(_model_columns.object); + if (_desktop && layer) { _current_layer_changed_connection.block(); _layers_changed_connection.block(); @@ -326,97 +314,90 @@ void LayerSelector::_setDesktopLayer() { /** Creates rows in the _layer_model data structure for each item * in \a hierarchy, to a given \a depth. */ -void LayerSelector::_buildEntries(unsigned depth, - Inkscape::Util::List<SPObject &> hierarchy) +void LayerSelector::_buildEntries(unsigned depth, Inkscape::Util::List<SPObject &> hierarchy) { using Inkscape::Util::List; using Inkscape::Util::rest; _buildEntry(depth, *hierarchy); - List<SPObject &> remainder=rest(hierarchy); + List<SPObject &> remainder = rest(hierarchy); if (remainder) { - _buildEntries(depth+1, remainder); + _buildEntries(depth + 1, remainder); } else { - _buildSiblingEntries(depth+1, *hierarchy, remainder); + _buildSiblingEntries(depth + 1, *hierarchy, remainder); } } /** Creates entries in the _layer_model data structure for * all siblings of the first child in \a parent. */ -void LayerSelector::_buildSiblingEntries( - unsigned depth, SPObject &parent, - Inkscape::Util::List<SPObject &> hierarchy -) { +void LayerSelector::_buildSiblingEntries(unsigned depth, SPObject &parent, Inkscape::Util::List<SPObject &> hierarchy) +{ using Inkscape::Util::rest; auto siblings = parent.children | boost::adaptors::filtered(is_layer(_desktop)) | boost::adaptors::reversed; - SPObject *layer( hierarchy ? &*hierarchy : nullptr ); + SPObject *layer(hierarchy ? &*hierarchy : nullptr); - for (auto& sib: siblings) { + for (auto &sib : siblings) { _buildEntry(depth, sib); - if ( &sib == layer ) { - _buildSiblingEntries(depth+1, *layer, rest(hierarchy)); + if (&sib == layer) { + _buildSiblingEntries(depth + 1, *layer, rest(hierarchy)); } } } namespace { -struct Callbacks { +struct Callbacks +{ sigc::slot<void> update_row; sigc::slot<void> update_list; }; -void attribute_changed(Inkscape::XML::Node */*repr*/, gchar const *name, - gchar const */*old_value*/, gchar const */*new_value*/, - bool /*is_interactive*/, void *data) +void attribute_changed(Inkscape::XML::Node * /*repr*/, gchar const *name, gchar const * /*old_value*/, + gchar const * /*new_value*/, bool /*is_interactive*/, void *data) { - if ( !std::strcmp(name, "inkscape:groupmode") ) { + if (!std::strcmp(name, "inkscape:groupmode")) { reinterpret_cast<Callbacks *>(data)->update_list(); } else { reinterpret_cast<Callbacks *>(data)->update_row(); } } -void node_added(Inkscape::XML::Node */*parent*/, Inkscape::XML::Node *child, Inkscape::XML::Node */*ref*/, void *data) { - gchar const *mode=child->attribute("inkscape:groupmode"); - if ( mode && !std::strcmp(mode, "layer") ) { +void node_added(Inkscape::XML::Node * /*parent*/, Inkscape::XML::Node *child, Inkscape::XML::Node * /*ref*/, void *data) +{ + gchar const *mode = child->attribute("inkscape:groupmode"); + if (mode && !std::strcmp(mode, "layer")) { reinterpret_cast<Callbacks *>(data)->update_list(); } } -void node_removed(Inkscape::XML::Node */*parent*/, Inkscape::XML::Node *child, Inkscape::XML::Node */*ref*/, void *data) { - gchar const *mode=child->attribute("inkscape:groupmode"); - if ( mode && !std::strcmp(mode, "layer") ) { +void node_removed(Inkscape::XML::Node * /*parent*/, Inkscape::XML::Node *child, Inkscape::XML::Node * /*ref*/, + void *data) +{ + gchar const *mode = child->attribute("inkscape:groupmode"); + if (mode && !std::strcmp(mode, "layer")) { reinterpret_cast<Callbacks *>(data)->update_list(); } } -void node_reordered(Inkscape::XML::Node */*parent*/, Inkscape::XML::Node *child, - Inkscape::XML::Node */*old_ref*/, Inkscape::XML::Node */*new_ref*/, - void *data) +void node_reordered(Inkscape::XML::Node * /*parent*/, Inkscape::XML::Node *child, Inkscape::XML::Node * /*old_ref*/, + Inkscape::XML::Node * /*new_ref*/, void *data) { - gchar const *mode=child->attribute("inkscape:groupmode"); - if ( mode && !std::strcmp(mode, "layer") ) { + gchar const *mode = child->attribute("inkscape:groupmode"); + if (mode && !std::strcmp(mode, "layer")) { reinterpret_cast<Callbacks *>(data)->update_list(); } } -void update_row_for_object(SPObject *object, - Gtk::TreeModelColumn<SPObject *> const &column, +void update_row_for_object(SPObject *object, Gtk::TreeModelColumn<SPObject *> const &column, Glib::RefPtr<Gtk::ListStore> const &model) { Gtk::TreeIter row( - std::find_if( - model->children().begin(), - model->children().end(), - column_matches_object(column, *object) - ) - ); - if ( row != model->children().end() ) { + std::find_if(model->children().begin(), model->children().end(), column_matches_object(column, *object))); + if (row != model->children().end()) { model->row_changed(model->get_path(row), row); } } @@ -426,24 +407,25 @@ void rebuild_all_rows(sigc::slot<void, SPObject *> rebuild, SPDesktop *desktop) rebuild(desktop->currentLayer()); } -} +} // namespace -void LayerSelector::_protectUpdate(sigc::slot<void> slot) { - bool visibility_blocked=_visibility_toggled_connection.blocked(); - bool lock_blocked=_lock_toggled_connection.blocked(); +void LayerSelector::_protectUpdate(sigc::slot<void> slot) +{ + bool visibility_blocked = _visibility_toggled_connection.blocked(); + bool lock_blocked = _lock_toggled_connection.blocked(); _visibility_toggled_connection.block(true); _lock_toggled_connection.block(true); slot(); SPObject *layer = _desktop ? _desktop->currentLayer() : nullptr; - if ( layer ) { - bool wantedValue = ( SP_IS_ITEM(layer) ? SP_ITEM(layer)->isLocked() : false ); - if ( _lock_toggle.get_active() != wantedValue ) { - _lock_toggle.set_active( wantedValue ); + if (layer) { + bool wantedValue = (SP_IS_ITEM(layer) ? SP_ITEM(layer)->isLocked() : false); + if (_lock_toggle.get_active() != wantedValue) { + _lock_toggle.set_active(wantedValue); } - wantedValue = ( SP_IS_ITEM(layer) ? SP_ITEM(layer)->isHidden() : false ); - if ( _visibility_toggle.get_active() != wantedValue ) { - _visibility_toggle.set_active( wantedValue ); + wantedValue = (SP_IS_ITEM(layer) ? SP_ITEM(layer)->isHidden() : false); + if (_visibility_toggle.get_active() != wantedValue) { + _visibility_toggle.set_active(wantedValue); } } _visibility_toggled_connection.block(visibility_blocked); @@ -452,47 +434,28 @@ void LayerSelector::_protectUpdate(sigc::slot<void> slot) { /** Builds and appends a row in the layer model object. */ -void LayerSelector::_buildEntry(unsigned depth, SPObject &object) { +void LayerSelector::_buildEntry(unsigned depth, SPObject &object) +{ Inkscape::XML::NodeEventVector *vector; - Callbacks *callbacks=new Callbacks(); + Callbacks *callbacks = new Callbacks(); - callbacks->update_row = sigc::bind( - sigc::mem_fun(*this, &LayerSelector::_protectUpdate), - sigc::bind( - sigc::ptr_fun(&update_row_for_object), - &object, _model_columns.object, _layer_model - ) - ); + callbacks->update_row = + sigc::bind(sigc::mem_fun(*this, &LayerSelector::_protectUpdate), + sigc::bind(sigc::ptr_fun(&update_row_for_object), &object, _model_columns.object, _layer_model)); - SPObject *layer=_desktop->currentLayer(); - if ( (&object == layer) || (&object == layer->parent) ) { + SPObject *layer = _desktop->currentLayer(); + if ((&object == layer) || (&object == layer->parent)) { callbacks->update_list = sigc::bind( sigc::mem_fun(*this, &LayerSelector::_protectUpdate), - sigc::bind( - sigc::ptr_fun(&rebuild_all_rows), - sigc::mem_fun(*this, &LayerSelector::_selectLayer), - _desktop - ) - ); - - Inkscape::XML::NodeEventVector events = { - &node_added, - &node_removed, - &attribute_changed, - nullptr, - &node_reordered - }; + sigc::bind(sigc::ptr_fun(&rebuild_all_rows), sigc::mem_fun(*this, &LayerSelector::_selectLayer), _desktop)); + + Inkscape::XML::NodeEventVector events = {&node_added, &node_removed, &attribute_changed, nullptr, + &node_reordered}; vector = new Inkscape::XML::NodeEventVector(events); } else { - Inkscape::XML::NodeEventVector events = { - nullptr, - nullptr, - &attribute_changed, - nullptr, - nullptr - }; + Inkscape::XML::NodeEventVector events = {nullptr, nullptr, &attribute_changed, nullptr, nullptr}; vector = new Inkscape::XML::NodeEventVector(events); } @@ -515,13 +478,14 @@ void LayerSelector::_buildEntry(unsigned depth, SPObject &object) { /** Removes a row from the _model_columns object, disconnecting listeners * on the slot. */ -void LayerSelector::_destroyEntry(Gtk::ListStore::iterator const &row) { - Callbacks *callbacks=reinterpret_cast<Callbacks *>(row->get_value(_model_columns.callbacks)); - SPObject *object=row->get_value(_model_columns.object); +void LayerSelector::_destroyEntry(Gtk::ListStore::iterator const &row) +{ + Callbacks *callbacks = reinterpret_cast<Callbacks *>(row->get_value(_model_columns.callbacks)); + SPObject *object = row->get_value(_model_columns.object); if (object) { sp_object_unref(object, nullptr); } - Inkscape::XML::Node *repr=row->get_value(_model_columns.repr); + Inkscape::XML::Node *repr = row->get_value(_model_columns.repr); if (repr) { sp_repr_remove_listener_by_data(repr, callbacks); Inkscape::GC::release(repr); @@ -531,39 +495,34 @@ void LayerSelector::_destroyEntry(Gtk::ListStore::iterator const &row) { /** Formats the label for a given layer row */ -void LayerSelector::_prepareLabelRenderer( - Gtk::TreeModel::const_iterator const &row -) { - unsigned depth=(*row)[_model_columns.depth]; - SPObject *object=(*row)[_model_columns.object]; +void LayerSelector::_prepareLabelRenderer(Gtk::TreeModel::const_iterator const &row) +{ + unsigned depth = (*row)[_model_columns.depth]; + SPObject *object = (*row)[_model_columns.object]; bool label_defaulted(false); // TODO: when the currently selected row is removed, // (or before one has been selected) something appears to // "invent" an iterator with null data and try to render it; // where does it come from, and how can we avoid it? - if ( object && object->getRepr() ) { - SPObject *layer=( _desktop ? _desktop->currentLayer() : nullptr ); - SPObject *root=( _desktop ? _desktop->currentRoot() : nullptr ); + if (object && object->getRepr()) { + SPObject *layer = (_desktop ? _desktop->currentLayer() : nullptr); + SPObject *root = (_desktop ? _desktop->currentRoot() : nullptr); - bool isancestor = !( (layer && (object->parent == layer->parent)) || ((layer == root) && (object->parent == root))); + bool isancestor = + !((layer && (object->parent == layer->parent)) || ((layer == root) && (object->parent == root))); - bool iscurrent = ( (object == layer) && (object != root) ); + bool iscurrent = ((object == layer) && (object != root)); - gchar *format = g_strdup_printf ( + gchar *format = g_strdup_printf( "<span size=\"smaller\" %s><tt>%*s%s</tt>%s%s%s%%s%s%s%s</span>", - ( _desktop && _desktop->itemIsHidden (SP_ITEM(object)) ? "foreground=\"gray50\"" : "" ), - depth, "", ( iscurrent ? "•" : " " ), - ( iscurrent ? "<b>" : "" ), - ( SP_ITEM(object)->isLocked() ? "[" : "" ), - ( isancestor ? "<small>" : "" ), - ( isancestor ? "</small>" : "" ), - ( SP_ITEM(object)->isLocked() ? "]" : "" ), - ( iscurrent ? "</b>" : "" ) - ); + (_desktop && _desktop->itemIsHidden(SP_ITEM(object)) ? "foreground=\"gray50\"" : ""), depth, "", + (iscurrent ? "•" : " "), (iscurrent ? "<b>" : ""), (SP_ITEM(object)->isLocked() ? "[" : ""), + (isancestor ? "<small>" : ""), (isancestor ? "</small>" : ""), (SP_ITEM(object)->isLocked() ? "]" : ""), + (iscurrent ? "</b>" : "")); gchar const *label; - if ( object != root ) { + if (object != root) { label = object->label(); if (!object->label()) { label = object->defaultLabel(); @@ -573,7 +532,7 @@ void LayerSelector::_prepareLabelRenderer( label = _("(root)"); } - gchar *text = g_markup_printf_escaped(format, ink_ellipsize_text (label, 50).c_str()); + gchar *text = g_markup_printf_escaped(format, ink_ellipsize_text(label, 50).c_str()); _label_renderer.property_markup() = text; g_free(text); g_free(format); @@ -582,25 +541,22 @@ void LayerSelector::_prepareLabelRenderer( } _label_renderer.property_ypad() = 1; - _label_renderer.property_style() = ( label_defaulted ? - Pango::STYLE_ITALIC : - Pango::STYLE_NORMAL ); - + _label_renderer.property_style() = (label_defaulted ? Pango::STYLE_ITALIC : Pango::STYLE_NORMAL); } -void LayerSelector::_lockLayer(bool lock) { - if ( _layer && SP_IS_ITEM(_layer) ) { +void LayerSelector::_lockLayer(bool lock) +{ + if (_layer && SP_IS_ITEM(_layer)) { SP_ITEM(_layer)->setLocked(lock); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_NONE, - lock? _("Lock layer") : _("Unlock layer")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_NONE, lock ? _("Lock layer") : _("Unlock layer")); } } -void LayerSelector::_hideLayer(bool hide) { - if ( _layer && SP_IS_ITEM(_layer) ) { +void LayerSelector::_hideLayer(bool hide) +{ + if (_layer && SP_IS_ITEM(_layer)) { SP_ITEM(_layer)->setHidden(hide); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_NONE, - hide? _("Hide layer") : _("Unhide layer")); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_NONE, hide ? _("Hide layer") : _("Unhide layer")); } } diff --git a/src/ui/widget/layer-selector.h b/src/ui/widget/layer-selector.h index eadfce206047061223f810542aed7d94fd657da0..0b6f3739e9312b18aa249eb1a02223e5b752da15 100644 --- a/src/ui/widget/layer-selector.h +++ b/src/ui/widget/layer-selector.h @@ -14,12 +14,13 @@ #define SEEN_INKSCAPE_WIDGETS_LAYER_SELECTOR #include <gtkmm/box.h> +#include <gtkmm/cellrenderertext.h> #include <gtkmm/combobox.h> +#include <gtkmm/liststore.h> #include <gtkmm/togglebutton.h> -#include <gtkmm/cellrenderertext.h> #include <gtkmm/treemodel.h> -#include <gtkmm/liststore.h> #include <sigc++/slot.h> + #include "util/list.h" class SPDesktop; @@ -29,8 +30,7 @@ namespace Inkscape { namespace XML { class Node; } -} - +} // namespace Inkscape namespace Inkscape { namespace UI { @@ -38,7 +38,8 @@ namespace Widget { class DocumentTreeModel; -class LayerSelector : public Gtk::HBox { +class LayerSelector : public Gtk::HBox +{ public: LayerSelector(SPDesktop *desktop = nullptr); ~LayerSelector() override; @@ -47,15 +48,20 @@ public: void setDesktop(SPDesktop *desktop); private: - class LayerModelColumns : public Gtk::TreeModel::ColumnRecord { + class LayerModelColumns : public Gtk::TreeModel::ColumnRecord + { public: Gtk::TreeModelColumn<unsigned> depth; Gtk::TreeModelColumn<SPObject *> object; Gtk::TreeModelColumn<Inkscape::XML::Node *> repr; Gtk::TreeModelColumn<void *> callbacks; - LayerModelColumns() { - add(depth); add(object); add(repr); add(callbacks); + LayerModelColumns() + { + add(depth); + add(object); + add(repr); + add(callbacks); } }; @@ -69,7 +75,7 @@ private: Gtk::CellRendererText _label_renderer; Glib::RefPtr<Gtk::ListStore> _layer_model; -// sigc::connection _desktop_shutdown_connection; + // sigc::connection _desktop_shutdown_connection; sigc::connection _layers_changed_connection; sigc::connection _current_layer_changed_connection; sigc::connection _selection_changed_connection; @@ -84,11 +90,8 @@ private: void _setDesktopLayer(); void _buildEntry(unsigned depth, SPObject &object); - void _buildEntries(unsigned depth, - Inkscape::Util::List<SPObject &> hierarchy); - void _buildSiblingEntries(unsigned depth, - SPObject &parent, - Inkscape::Util::List<SPObject &> hierarchy); + void _buildEntries(unsigned depth, Inkscape::Util::List<SPObject &> hierarchy); + void _buildSiblingEntries(unsigned depth, SPObject &parent, Inkscape::Util::List<SPObject &> hierarchy); void _protectUpdate(sigc::slot<void> slot); void _destroyEntry(Gtk::ListStore::iterator const &row); void _hideLayer(bool hide); diff --git a/src/ui/widget/layertypeicon.cpp b/src/ui/widget/layertypeicon.cpp index d8b13788e3e07edb3874b6b042024ac71cf6ecdd..9b523cbb65aadc59209a92e1fee96e81b2893b5b 100644 --- a/src/ui/widget/layertypeicon.cpp +++ b/src/ui/widget/layertypeicon.cpp @@ -18,19 +18,18 @@ namespace Inkscape { namespace UI { namespace Widget { -LayerTypeIcon::LayerTypeIcon() : - Glib::ObjectBase(typeid(LayerTypeIcon)), - Gtk::CellRendererPixbuf(), - _pixLayerName(INKSCAPE_ICON("dialog-layers")), - _pixGroupName(INKSCAPE_ICON("layer-duplicate")), - _pixPathName(INKSCAPE_ICON("layer-rename")), - _property_active(*this, "active", false), - _property_activatable(*this, "activatable", true), - _property_pixbuf_layer(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)), - _property_pixbuf_group(*this, "pixbuf_off", Glib::RefPtr<Gdk::Pixbuf>(nullptr)), - _property_pixbuf_path(*this, "pixbuf_off", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) +LayerTypeIcon::LayerTypeIcon() + : Glib::ObjectBase(typeid(LayerTypeIcon)) + , Gtk::CellRendererPixbuf() + , _pixLayerName(INKSCAPE_ICON("dialog-layers")) + , _pixGroupName(INKSCAPE_ICON("layer-duplicate")) + , _pixPathName(INKSCAPE_ICON("layer-rename")) + , _property_active(*this, "active", false) + , _property_activatable(*this, "activatable", true) + , _property_pixbuf_layer(*this, "pixbuf_on", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) + , _property_pixbuf_group(*this, "pixbuf_off", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) + , _property_pixbuf_path(*this, "pixbuf_off", Glib::RefPtr<Gdk::Pixbuf>(nullptr)) { - property_mode() = Gtk::CELL_RENDERER_MODE_ACTIVATABLE; _property_pixbuf_layer = sp_get_icon_pixbuf(_pixLayerName, GTK_ICON_SIZE_MENU); @@ -40,53 +39,45 @@ LayerTypeIcon::LayerTypeIcon() : property_pixbuf() = _property_pixbuf_path.get_value(); } -void LayerTypeIcon::get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const +void LayerTypeIcon::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 LayerTypeIcon::get_preferred_width_vfunc(Gtk::Widget& widget, - int& min_w, - int& nat_w) const +void LayerTypeIcon::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; } } -void LayerTypeIcon::render_vfunc( const Cairo::RefPtr<Cairo::Context>& cr, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - Gtk::CellRendererState flags ) +void LayerTypeIcon::render_vfunc(const Cairo::RefPtr<Cairo::Context> &cr, Gtk::Widget &widget, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) { - property_pixbuf() = _property_active.get_value() == 1 ? _property_pixbuf_group : (_property_active.get_value() == 2 ? _property_pixbuf_layer : _property_pixbuf_path); - Gtk::CellRendererPixbuf::render_vfunc( cr, widget, background_area, cell_area, flags ); + property_pixbuf() = _property_active.get_value() == 1 + ? _property_pixbuf_group + : (_property_active.get_value() == 2 ? _property_pixbuf_layer : _property_pixbuf_path); + Gtk::CellRendererPixbuf::render_vfunc(cr, widget, background_area, cell_area, flags); } -bool -LayerTypeIcon::activate_vfunc(GdkEvent* event, - Gtk::Widget& /*widget*/, - const Glib::ustring& path, - const Gdk::Rectangle& /*background_area*/, - const Gdk::Rectangle& /*cell_area*/, - Gtk::CellRendererState /*flags*/) +bool LayerTypeIcon::activate_vfunc(GdkEvent *event, Gtk::Widget & /*widget*/, const Glib::ustring &path, + const Gdk::Rectangle & /*background_area*/, const Gdk::Rectangle & /*cell_area*/, + Gtk::CellRendererState /*flags*/) { _signal_pre_toggle.emit(event); _signal_toggled.emit(path); @@ -94,7 +85,6 @@ LayerTypeIcon::activate_vfunc(GdkEvent* event, return false; } - } // namespace Widget } // namespace UI } // namespace Inkscape @@ -109,5 +99,3 @@ LayerTypeIcon::activate_vfunc(GdkEvent* event, End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - - diff --git a/src/ui/widget/layertypeicon.h b/src/ui/widget/layertypeicon.h index 7dccf4c7db8c1dedaeb8f4eb2faf9840d04b4825..cf7926dbde78df14e5df7a30dccea49a5cd0bcc1 100644 --- a/src/ui/widget/layertypeicon.h +++ b/src/ui/widget/layertypeicon.h @@ -10,73 +10,61 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include <glibmm/property.h> #include <gtkmm/cellrendererpixbuf.h> #include <gtkmm/widget.h> -#include <glibmm/property.h> namespace Inkscape { namespace UI { namespace Widget { -class LayerTypeIcon : public Gtk::CellRendererPixbuf { +class LayerTypeIcon : public Gtk::CellRendererPixbuf +{ public: LayerTypeIcon(); - ~LayerTypeIcon() override = default;; + ~LayerTypeIcon() override = default; + ; - sigc::signal<void, const Glib::ustring&> signal_toggled() { return _signal_toggled;} - sigc::signal<void, GdkEvent const *> signal_pre_toggle() { return _signal_pre_toggle; } + sigc::signal<void, const Glib::ustring &> signal_toggled() { return _signal_toggled; } + sigc::signal<void, GdkEvent const *> signal_pre_toggle() { return _signal_pre_toggle; } Glib::PropertyProxy<int> property_active() { return _property_active.get_proxy(); } Glib::PropertyProxy<int> property_activatable() { return _property_activatable.get_proxy(); } - Glib::PropertyProxy< Glib::RefPtr<Gdk::Pixbuf> > property_pixbuf_on(); - Glib::PropertyProxy< Glib::RefPtr<Gdk::Pixbuf> > property_pixbuf_off(); + Glib::PropertyProxy<Glib::RefPtr<Gdk::Pixbuf>> property_pixbuf_on(); + Glib::PropertyProxy<Glib::RefPtr<Gdk::Pixbuf>> property_pixbuf_off(); protected: - 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 ) override; + 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) override; - void get_preferred_width_vfunc(Gtk::Widget& widget, - int& min_w, - int& nat_w) const override; - - void get_preferred_height_vfunc(Gtk::Widget& widget, - int& min_h, - int& nat_h) const override; + void get_preferred_width_vfunc(Gtk::Widget &widget, int &min_w, int &nat_w) const override; - bool activate_vfunc(GdkEvent *event, - Gtk::Widget &widget, - const Glib::ustring &path, - const Gdk::Rectangle &background_area, - const Gdk::Rectangle &cell_area, - Gtk::CellRendererState flags) override; + void get_preferred_height_vfunc(Gtk::Widget &widget, int &min_h, int &nat_h) const override; + bool activate_vfunc(GdkEvent *event, Gtk::Widget &widget, const Glib::ustring &path, + const Gdk::Rectangle &background_area, const Gdk::Rectangle &cell_area, + Gtk::CellRendererState flags) override; private: Glib::ustring _pixLayerName; Glib::ustring _pixGroupName; Glib::ustring _pixPathName; - + Glib::Property<int> _property_active; Glib::Property<int> _property_activatable; - Glib::Property< Glib::RefPtr<Gdk::Pixbuf> > _property_pixbuf_layer; - Glib::Property< Glib::RefPtr<Gdk::Pixbuf> > _property_pixbuf_group; - Glib::Property< Glib::RefPtr<Gdk::Pixbuf> > _property_pixbuf_path; - - sigc::signal<void, const Glib::ustring&> _signal_toggled; - sigc::signal<void, GdkEvent const *> _signal_pre_toggle; + Glib::Property<Glib::RefPtr<Gdk::Pixbuf>> _property_pixbuf_layer; + Glib::Property<Glib::RefPtr<Gdk::Pixbuf>> _property_pixbuf_group; + Glib::Property<Glib::RefPtr<Gdk::Pixbuf>> _property_pixbuf_path; + sigc::signal<void, const Glib::ustring &> _signal_toggled; + sigc::signal<void, GdkEvent const *> _signal_pre_toggle; }; - - } // namespace Widget } // namespace UI } // namespace Inkscape - #endif /* __UI_DIALOG_IMAGETOGGLER_H__ */ /* diff --git a/src/ui/widget/licensor.cpp b/src/ui/widget/licensor.cpp index f33ba8a9828b9e36e4637e7ea411f124421a4a4d..24d129a0038b9f70b2b3d4e8cd125d21766bc7a8 100644 --- a/src/ui/widget/licensor.cpp +++ b/src/ui/widget/licensor.cpp @@ -18,41 +18,44 @@ #include <gtkmm/entry.h> #include <gtkmm/radiobutton.h> +#include "document-undo.h" +#include "inkscape.h" +#include "rdf.h" #include "ui/widget/entity-entry.h" #include "ui/widget/registry.h" -#include "rdf.h" -#include "inkscape.h" -#include "document-undo.h" #include "verbs.h" - namespace Inkscape { namespace UI { namespace Widget { //=================================================== -const struct rdf_license_t _proprietary_license = - {_("Proprietary"), "", nullptr}; +const struct rdf_license_t _proprietary_license = {_("Proprietary"), "", nullptr}; -const struct rdf_license_t _other_license = - {Q_("MetadataLicence|Other"), "", nullptr}; +const struct rdf_license_t _other_license = {Q_("MetadataLicence|Other"), "", nullptr}; -class LicenseItem : public Gtk::RadioButton { +class LicenseItem : public Gtk::RadioButton +{ public: - LicenseItem (struct rdf_license_t const* license, EntityEntry* entity, Registry &wr, Gtk::RadioButtonGroup *group); + LicenseItem(struct rdf_license_t const *license, EntityEntry *entity, Registry &wr, Gtk::RadioButtonGroup *group); + protected: void on_toggled() override; struct rdf_license_t const *_lic; - EntityEntry *_eep; - Registry &_wr; + EntityEntry *_eep; + 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) +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) { if (group) { - set_group (*group); + set_group(*group); } } @@ -62,86 +65,83 @@ void LicenseItem::on_toggled() if (_wr.isUpdating() || !_wr.desktop()) return; - _wr.setUpdating (true); + _wr.setUpdating(true); SPDocument *doc = _wr.desktop()->getDocument(); - rdf_set_license (doc, _lic->details ? _lic : nullptr); + rdf_set_license(doc, _lic->details ? _lic : nullptr); if (doc->isSensitive()) { DocumentUndo::done(doc, SP_VERB_NONE, _("Document license updated")); } - _wr.setUpdating (false); - static_cast<Gtk::Entry*>(_eep->_packable)->set_text (_lic->uri); + _wr.setUpdating(false); + static_cast<Gtk::Entry *>(_eep->_packable)->set_text(_lic->uri); _eep->on_changed(); } //--------------------------------------------------- Licensor::Licensor() -: Gtk::VBox(false,4), - _eentry (nullptr) -{ -} + : Gtk::VBox(false, 4) + , _eentry(nullptr) +{} Licensor::~Licensor() { - if (_eentry) delete _eentry; + if (_eentry) + delete _eentry; } -void Licensor::init (Registry& wr) +void Licensor::init(Registry &wr) { /* add license-specific metadata entry areas */ - rdf_work_entity_t* entity = rdf_find_entity ( "license_uri" ); - _eentry = EntityEntry::create (entity, wr); + rdf_work_entity_t *entity = rdf_find_entity("license_uri"); + _eentry = EntityEntry::create(entity, wr); LicenseItem *i; - wr.setUpdating (true); - i = Gtk::manage (new LicenseItem (&_proprietary_license, _eentry, wr, nullptr)); + wr.setUpdating(true); + i = Gtk::manage(new LicenseItem(&_proprietary_license, _eentry, wr, nullptr)); Gtk::RadioButtonGroup group = i->get_group(); - add (*i); + add(*i); LicenseItem *pd = i; - for (struct rdf_license_t * license = rdf_licenses; - license && license->name; - license++) { - i = Gtk::manage (new LicenseItem (license, _eentry, wr, &group)); + for (struct rdf_license_t *license = rdf_licenses; license && license->name; license++) { + i = Gtk::manage(new LicenseItem(license, _eentry, wr, &group)); add(*i); } // add Other at the end before the URI field for the confused ppl. - LicenseItem *io = Gtk::manage (new LicenseItem (&_other_license, _eentry, wr, &group)); - add (*io); + LicenseItem *io = Gtk::manage(new LicenseItem(&_other_license, _eentry, wr, &group)); + add(*io); pd->set_active(); - wr.setUpdating (false); + wr.setUpdating(false); - Gtk::HBox *box = Gtk::manage (new Gtk::HBox); - pack_start (*box, true, true, 0); + Gtk::HBox *box = Gtk::manage(new Gtk::HBox); + pack_start(*box, true, true, 0); - box->pack_start (_eentry->_label, false, false, 5); - box->pack_start (*_eentry->_packable, true, true, 0); + box->pack_start(_eentry->_label, false, false, 5); + box->pack_start(*_eentry->_packable, true, true, 0); show_all_children(); } -void Licensor::update (SPDocument *doc) +void Licensor::update(SPDocument *doc) { /* identify the license info */ - struct rdf_license_t * license = rdf_get_license (doc); + struct rdf_license_t *license = rdf_get_license(doc); if (license) { int i; - for (i=0; rdf_licenses[i].name; i++) - if (license == &rdf_licenses[i]) + for (i = 0; rdf_licenses[i].name; i++) + if (license == &rdf_licenses[i]) break; - static_cast<LicenseItem*>(get_children()[i+1])->set_active(); - } - else { - static_cast<LicenseItem*>(get_children()[0])->set_active(); + static_cast<LicenseItem *>(get_children()[i + 1])->set_active(); + } else { + static_cast<LicenseItem *>(get_children()[0])->set_active(); } - + /* update the URI */ - _eentry->update (doc); + _eentry->update(doc); } -} // namespace Dialog +} // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/licensor.h b/src/ui/widget/licensor.h index 3e1f0dae99aeaea34de11fbff499bedce86f871a..e0ffd7463e787363960b115c14fd5f27f89c5ef2 100644 --- a/src/ui/widget/licensor.h +++ b/src/ui/widget/licensor.h @@ -16,29 +16,28 @@ class SPDocument; namespace Inkscape { - namespace UI { - namespace Widget { +namespace UI { +namespace Widget { class EntityEntry; class Registry; - /** * Widget for specifying a document's license; part of document * preferences dialog. */ -class Licensor : public Gtk::VBox { +class Licensor : public Gtk::VBox +{ public: Licensor(); ~Licensor() override; - void init (Registry&); - void update (SPDocument *doc); + void init(Registry &); + void update(SPDocument *doc); -protected: - EntityEntry *_eentry; +protected: + EntityEntry *_eentry; }; - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/marker-combo-box.cpp b/src/ui/widget/marker-combo-box.cpp index 9c7bb64ba751be3f4cad50f77fa6241850242ee8..cad603797cd3a6fb69b944585dc76f5f0c4d49e3 100644 --- a/src/ui/widget/marker-combo-box.cpp +++ b/src/ui/widget/marker-combo-box.cpp @@ -20,23 +20,18 @@ #include <gtkmm/icontheme.h> #include "desktop-style.h" -#include "path-prefix.h" - #include "helper/stock-items.h" -#include "ui/icon-loader.h" - #include "io/resource.h" #include "io/sys.h" - #include "object/sp-defs.h" #include "object/sp-marker.h" #include "object/sp-root.h" +#include "path-prefix.h" #include "style.h" - #include "ui/cache/svg_preview_cache.h" #include "ui/dialog-events.h" +#include "ui/icon-loader.h" #include "ui/util.h" - #include "ui/widget/spinbutton.h" #include "ui/widget/stroke-style.h" @@ -46,14 +41,13 @@ namespace Inkscape { namespace UI { namespace Widget { -MarkerComboBox::MarkerComboBox(gchar const *id, int l) : - Gtk::ComboBox(), - combo_id(id), - loc(l), - updating(false), - markerCount(0) +MarkerComboBox::MarkerComboBox(gchar const *id, int l) + : Gtk::ComboBox() + , combo_id(id) + , loc(l) + , updating(false) + , markerCount(0) { - marker_store = Gtk::ListStore::create(marker_columns); set_model(marker_store); pack_start(image_renderer, false); @@ -61,7 +55,7 @@ MarkerComboBox::MarkerComboBox(gchar const *id, int l) : gtk_combo_box_set_row_separator_func(GTK_COMBO_BOX(gobj()), MarkerComboBox::separator_cb, nullptr, nullptr); empty_image = sp_get_icon_image("no-marker", Gtk::ICON_SIZE_SMALL_TOOLBAR); - sandbox = ink_markers_preview_doc (); + sandbox = ink_markers_preview_doc(); init_combo(); this->get_style_context()->add_class("combobright"); @@ -69,7 +63,8 @@ MarkerComboBox::MarkerComboBox(gchar const *id, int l) : show(); } -MarkerComboBox::~MarkerComboBox() { +MarkerComboBox::~MarkerComboBox() +{ delete combo_id; delete sandbox; delete empty_image; @@ -82,7 +77,6 @@ MarkerComboBox::~MarkerComboBox() { void MarkerComboBox::setDocument(SPDocument *document) { if (doc != document) { - if (doc) { modified_connection.disconnect(); } @@ -90,21 +84,20 @@ void MarkerComboBox::setDocument(SPDocument *document) doc = document; if (doc) { - modified_connection = doc->getDefs()->connectModified( sigc::hide(sigc::hide(sigc::bind(sigc::ptr_fun(&MarkerComboBox::handleDefsModified), this))) ); + modified_connection = doc->getDefs()->connectModified( + sigc::hide(sigc::hide(sigc::bind(sigc::ptr_fun(&MarkerComboBox::handleDefsModified), this)))); } refreshHistory(); } } -void -MarkerComboBox::handleDefsModified(MarkerComboBox *self) +void MarkerComboBox::handleDefsModified(MarkerComboBox *self) { self->refreshHistory(); } -void -MarkerComboBox::refreshHistory() +void MarkerComboBox::refreshHistory() { if (updating) return; @@ -117,7 +110,7 @@ MarkerComboBox::refreshHistory() * Seems to be no way to get notified of changes just to markers, * so listen to changes in all defs and check if the number of markers has changed here * to avoid unnecessary refreshes when things like gradients change - */ + */ if (markerCount != ml.size()) { auto iter = get_active(); const char *active = iter ? iter->get_value(marker_columns.marker) : nullptr; @@ -132,8 +125,7 @@ MarkerComboBox::refreshHistory() /** * Init the combobox widget to display markers from markers.svg */ -void -MarkerComboBox::init_combo() +void MarkerComboBox::init_combo() { if (updating) return; @@ -176,24 +168,21 @@ void MarkerComboBox::set_current(SPObject *marker) if (marker != nullptr) { gchar *markname = g_strdup(marker->getRepr()->attribute("id")); set_selected(markname); - g_free (markname); - } - else { + g_free(markname); + } else { set_selected(nullptr); } updating = false; - } /** * Return a uri string representing the current selected marker used for setting the marker style in the document */ -const gchar * MarkerComboBox::get_active_marker_uri() +const gchar *MarkerComboBox::get_active_marker_uri() { /* Get Marker */ const gchar *markid = get_active()->get_value(marker_columns.marker); - if (!markid) - { + if (!markid) { return nullptr; } @@ -202,12 +191,9 @@ const gchar * MarkerComboBox::get_active_marker_uri() bool stockid = get_active()->get_value(marker_columns.stock); gchar *markurn; - if (stockid) - { - markurn = g_strconcat("urn:inkscape:marker:",markid,NULL); - } - else - { + if (stockid) { + markurn = g_strconcat("urn:inkscape:marker:", markid, NULL); + } else { markurn = g_strdup(markid); } SPObject *mark = get_stock_item(markurn, stockid); @@ -223,8 +209,8 @@ const gchar * MarkerComboBox::get_active_marker_uri() return marker; } -void MarkerComboBox::set_active_history() { - +void MarkerComboBox::set_active_history() +{ const gchar *markid = get_active()->get_value(marker_columns.marker); // If forked from a stockid, add the stockid @@ -236,22 +222,19 @@ void MarkerComboBox::set_active_history() { set_selected(markid); } - -void MarkerComboBox::set_selected(const gchar *name, gboolean retry/*=true*/) { - +void MarkerComboBox::set_selected(const gchar *name, gboolean retry /*=true*/) +{ if (!name) { set_active(0); return; } - for(Gtk::TreeIter iter = marker_store->children().begin(); - iter != marker_store->children().end(); ++iter) { - Gtk::TreeModel::Row row = (*iter); - if (row[marker_columns.marker] && - !strcmp(row[marker_columns.marker], name)) { - set_active(iter); - return; - } + for (Gtk::TreeIter iter = marker_store->children().begin(); iter != marker_store->children().end(); ++iter) { + Gtk::TreeModel::Row row = (*iter); + if (row[marker_columns.marker] && !strcmp(row[marker_columns.marker], name)) { + set_active(iter); + return; + } } // Didn't find it in the list, try refreshing from the doc @@ -261,7 +244,6 @@ void MarkerComboBox::set_selected(const gchar *name, gboolean retry/*=true*/) { } } - /** * Pick up all markers from source, except those that are in * current_doc (if non-NULL), and add items to the combo. @@ -279,7 +261,7 @@ void MarkerComboBox::sp_marker_list_from_doc(SPDocument *source, gboolean histor * Returns a list of markers in the defs of the given source document as a vector * Returns NULL if there are no markers in the document. */ -std::vector<SPMarker *> MarkerComboBox::get_marker_list (SPDocument *source) +std::vector<SPMarker *> MarkerComboBox::get_marker_list(SPDocument *source) { std::vector<SPMarker *> ml; if (source == nullptr) @@ -290,8 +272,7 @@ std::vector<SPMarker *> MarkerComboBox::get_marker_list (SPDocument *source) return ml; } - for (auto& child: defs->children) - { + for (auto &child : defs->children) { if (SP_IS_MARKER(&child)) { ml.push_back(SP_MARKER(&child)); } @@ -302,17 +283,16 @@ std::vector<SPMarker *> MarkerComboBox::get_marker_list (SPDocument *source) /** * Remove history or non-history markers from the combo */ -void MarkerComboBox::remove_markers (gboolean history) +void MarkerComboBox::remove_markers(gboolean history) { // Having the model set causes assertions when erasing rows, temporarily disconnect unset_model(); - for(Gtk::TreeIter iter = marker_store->children().begin(); - iter != marker_store->children().end(); ++iter) { - Gtk::TreeModel::Row row = (*iter); - if (row[marker_columns.history] == history && row[marker_columns.separator] == false) { - marker_store->erase(iter); - iter = marker_store->children().begin(); - } + for (Gtk::TreeIter iter = marker_store->children().begin(); iter != marker_store->children().end(); ++iter) { + Gtk::TreeModel::Row row = (*iter); + if (row[marker_columns.history] == history && row[marker_columns.separator] == false) { + marker_store->erase(iter); + iter = marker_store->children().begin(); + } } set_model(marker_store); @@ -321,7 +301,7 @@ void MarkerComboBox::remove_markers (gboolean history) /** * Adds markers in marker_list to the combo */ -void MarkerComboBox::add_markers (std::vector<SPMarker *> const& marker_list, SPDocument *source, gboolean history) +void MarkerComboBox::add_markers(std::vector<SPMarker *> const &marker_list, SPDocument *source, gboolean history) { // Do this here, outside of loop, to speed up preview generation: Inkscape::Drawing drawing; @@ -329,12 +309,11 @@ void MarkerComboBox::add_markers (std::vector<SPMarker *> const& marker_list, SP drawing.setRoot(sandbox->getRoot()->invoke_show(drawing, visionkey, SP_ITEM_SHOW_DISPLAY)); // Find the separator, Gtk::TreeIter sep_iter; - for(Gtk::TreeIter iter = marker_store->children().begin(); - iter != marker_store->children().end(); ++iter) { - Gtk::TreeModel::Row row = (*iter); - if (row[marker_columns.separator]) { - sep_iter = iter; - } + for (Gtk::TreeIter iter = marker_store->children().begin(); iter != marker_store->children().end(); ++iter) { + Gtk::TreeModel::Row row = (*iter); + if (row[marker_columns.separator]) { + sep_iter = iter; + } } if (history) { @@ -348,13 +327,13 @@ void MarkerComboBox::add_markers (std::vector<SPMarker *> const& marker_list, SP row[marker_columns.separator] = false; } - for (auto i:marker_list) { - + for (auto i : marker_list) { Inkscape::XML::Node *repr = i->getRepr(); - gchar const *markid = repr->attribute("inkscape:stockid") ? repr->attribute("inkscape:stockid") : repr->attribute("id"); + gchar const *markid = + repr->attribute("inkscape:stockid") ? repr->attribute("inkscape:stockid") : repr->attribute("id"); // generate preview - Gtk::Image *prv = create_marker_image (24, repr->attribute("id"), source, drawing, visionkey); + Gtk::Image *prv = create_marker_image(24, repr->attribute("id"), source, drawing, visionkey); prv->show(); // Add history before separator, others after @@ -372,7 +351,6 @@ void MarkerComboBox::add_markers (std::vector<SPMarker *> const& marker_list, SP row[marker_columns.image] = prv; row[marker_columns.history] = history; row[marker_columns.separator] = false; - } sandbox->getRoot()->invoke_hide(visionkey); @@ -381,12 +359,11 @@ void MarkerComboBox::add_markers (std::vector<SPMarker *> const& marker_list, SP /* * Remove from the cache and recreate a marker image */ -void -MarkerComboBox::update_marker_image(gchar const *mname) +void MarkerComboBox::update_marker_image(gchar const *mname) { gchar *cache_name = g_strconcat(combo_id, mname, NULL); Glib::ustring key = svg_preview_cache.cache_key(doc->getDocumentURI(), cache_name, 24); - g_free (cache_name); + g_free(cache_name); svg_preview_cache.remove_preview_from_cache(key); Inkscape::Drawing drawing; @@ -398,24 +375,21 @@ MarkerComboBox::update_marker_image(gchar const *mname) } sandbox->getRoot()->invoke_hide(visionkey); - for(const auto & iter : marker_store->children()) { - Gtk::TreeModel::Row row = iter; - if (row[marker_columns.marker] && row[marker_columns.history] && - !strcmp(row[marker_columns.marker], mname)) { - row[marker_columns.image] = prv; - return; - } + for (const auto &iter : marker_store->children()) { + Gtk::TreeModel::Row row = iter; + if (row[marker_columns.marker] && row[marker_columns.history] && !strcmp(row[marker_columns.marker], mname)) { + row[marker_columns.image] = prv; + return; + } } - } /** * Creates a copy of the marker named mname, determines its visible and renderable * area in the bounding box, and then renders it. This allows us to fill in * preview images of each marker in the marker combobox. */ -Gtk::Image * -MarkerComboBox::create_marker_image(unsigned psize, gchar const *mname, - SPDocument *source, Inkscape::Drawing &drawing, unsigned /*visionkey*/) +Gtk::Image *MarkerComboBox::create_marker_image(unsigned psize, gchar const *mname, SPDocument *source, + Inkscape::Drawing &drawing, unsigned /*visionkey*/) { // Retrieve the marker named 'mname' from the source SVG document SPObject const *marker = source->getObjectById(mname); @@ -426,9 +400,9 @@ MarkerComboBox::create_marker_image(unsigned psize, gchar const *mname, /* Get from cache right away */ gchar *cache_name = g_strconcat(combo_id, mname, NULL); Glib::ustring key = svg_preview_cache.cache_key(source->getDocumentURI(), cache_name, psize); - g_free (cache_name); + g_free(cache_name); GdkPixbuf *pixbuf = svg_preview_cache.get_preview_from_cache(key); // no ref created - if(pixbuf) { + if (pixbuf) { Gtk::Image *pb = Glib::wrap(GTK_IMAGE(gtk_image_new_from_pixbuf(pixbuf))); return pb; } @@ -453,10 +427,10 @@ MarkerComboBox::create_marker_image(unsigned psize, gchar const *mname, // If the marker color is a url link to a pattern or gradient copy that too SPObject *mk = source->getObjectById(mname); SPCSSAttr *css_marker = sp_css_attr_from_object(mk->firstChild(), SP_STYLE_FLAG_ALWAYS); - //const char *mfill = sp_repr_css_property(css_marker, "fill", "none"); + // const char *mfill = sp_repr_css_property(css_marker, "fill", "none"); const char *mstroke = sp_repr_css_property(css_marker, "fill", "none"); - if (!strncmp (mstroke, "url(", 4)) { + if (!strncmp(mstroke, "url(", 4)) { SPObject *linkObj = getMarkerObj(mstroke, source); if (linkObj) { Inkscape::XML::Node *grepr = linkObj->getRepr()->duplicate(xml_doc); @@ -468,7 +442,7 @@ MarkerComboBox::create_marker_image(unsigned psize, gchar const *mname, Inkscape::GC::release(grepr); if (SP_IS_GRADIENT(linkObj)) { - SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (SP_GRADIENT(linkObj), false); + SPGradient *vector = sp_gradient_get_forked_vector_if_necessary(SP_GRADIENT(linkObj), false); if (vector) { Inkscape::XML::Node *grepr = vector->getRepr()->duplicate(xml_doc); SPObject *oldmarker = sandbox->getObjectById(vector->getId()); @@ -482,10 +456,10 @@ MarkerComboBox::create_marker_image(unsigned psize, gchar const *mname, } } -// Uncomment this to get the sandbox documents saved (useful for debugging) - //FILE *fp = fopen (g_strconcat(combo_id, mname, ".svg", NULL), "w"); - //sp_repr_save_stream(sandbox->getReprDoc(), fp); - //fclose (fp); + // Uncomment this to get the sandbox documents saved (useful for debugging) + // FILE *fp = fopen (g_strconcat(combo_id, mname, ".svg", NULL), "w"); + // sp_repr_save_stream(sandbox->getReprDoc(), fp); + // fclose (fp); // object to render; note that the id is the same as that of the combo we're building SPObject *object = sandbox->getObjectById(combo_id); @@ -514,8 +488,8 @@ MarkerComboBox::create_marker_image(unsigned psize, gchar const *mname, return pb; } -void MarkerComboBox::prepareImageRenderer( Gtk::TreeModel::const_iterator const &row ) { - +void MarkerComboBox::prepareImageRenderer(Gtk::TreeModel::const_iterator const &row) +{ Gtk::Image *image = (*row)[marker_columns.image]; if (image) image_renderer.property_pixbuf() = image->get_pixbuf(); @@ -523,8 +497,8 @@ void MarkerComboBox::prepareImageRenderer( Gtk::TreeModel::const_iterator const image_renderer.property_pixbuf() = empty_image->get_pixbuf(); } -gboolean MarkerComboBox::separator_cb (GtkTreeModel *model, GtkTreeIter *iter, gpointer /*data*/) { - +gboolean MarkerComboBox::separator_cb(GtkTreeModel *model, GtkTreeIter *iter, gpointer /*data*/) +{ gboolean sep = FALSE; gtk_tree_model_get(model, iter, 4, &sep, -1); return sep; @@ -533,9 +507,9 @@ gboolean MarkerComboBox::separator_cb (GtkTreeModel *model, GtkTreeIter *iter, g /** * Returns a new document containing default start, mid, and end markers. */ -SPDocument *MarkerComboBox::ink_markers_preview_doc () +SPDocument *MarkerComboBox::ink_markers_preview_doc() { -gchar const *buffer = R"A( + gchar const *buffer = R"A( <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="MarkerSample"> @@ -563,7 +537,7 @@ gchar const *buffer = R"A( </svg> )A"; - return SPDocument::createNewDocFromMem (buffer, strlen(buffer), FALSE); + return SPDocument::createNewDocFromMem(buffer, strlen(buffer), FALSE); } } // namespace Widget diff --git a/src/ui/widget/marker-combo-box.h b/src/ui/widget/marker-combo-box.h index c354c65609f086d5f6cfc2f96e52b5259234f442..2ca6523b2be8fdec0d12fb6dce6734a3b5bc54cc 100644 --- a/src/ui/widget/marker-combo-box.h +++ b/src/ui/widget/marker-combo-box.h @@ -10,26 +10,23 @@ * * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <vector> - #include <gtkmm/box.h> #include <gtkmm/combobox.h> #include <gtkmm/liststore.h> - #include <sigc++/signal.h> +#include <vector> +#include "display/drawing.h" #include "document.h" #include "inkscape.h" -#include "display/drawing.h" - class SPMarker; namespace Gtk { class Container; class Adjustment; -} +} // namespace Gtk namespace Inkscape { namespace UI { @@ -38,7 +35,8 @@ namespace Widget { /** * ComboBox derived class for selecting stroke markers. */ -class MarkerComboBox : public Gtk::ComboBox { +class MarkerComboBox : public Gtk::ComboBox +{ public: MarkerComboBox(gchar const *id, int loc); ~MarkerComboBox() override; @@ -49,7 +47,7 @@ public: void set_current(SPObject *marker); void set_active_history(); - void set_selected(const gchar *name, gboolean retry=true); + void set_selected(const gchar *name, gboolean retry = true); const gchar *get_active_marker_uri(); bool update() { return updating; }; gchar const *get_id() { return combo_id; }; @@ -57,8 +55,6 @@ public: int get_loc() { return loc; }; private: - - Glib::RefPtr<Gtk::ListStore> marker_store; gchar const *combo_id; int loc; @@ -66,39 +62,46 @@ private: guint markerCount; SPDocument *doc = nullptr; SPDocument *sandbox; - Gtk::Image *empty_image; + Gtk::Image *empty_image; Gtk::CellRendererPixbuf image_renderer; - class MarkerColumns : public Gtk::TreeModel::ColumnRecord { + class MarkerColumns : public Gtk::TreeModel::ColumnRecord + { public: Gtk::TreeModelColumn<Glib::ustring> label; - Gtk::TreeModelColumn<const gchar *> marker; // ustring doesn't work here on windows due to unicode + Gtk::TreeModelColumn<const gchar *> marker; // ustring doesn't work here on windows due to unicode Gtk::TreeModelColumn<gboolean> stock; Gtk::TreeModelColumn<Gtk::Image *> image; Gtk::TreeModelColumn<gboolean> history; Gtk::TreeModelColumn<gboolean> separator; - MarkerColumns() { - add(label); add(stock); add(marker); add(history); add(separator); add(image); + MarkerColumns() + { + add(label); + add(stock); + add(marker); + add(history); + add(separator); + add(image); } }; MarkerColumns marker_columns; void init_combo(); void set_history(Gtk::TreeModel::Row match_row); - void sp_marker_list_from_doc(SPDocument *source, gboolean history); - std::vector <SPMarker*> get_marker_list (SPDocument *source); - void add_markers (std::vector<SPMarker *> const& marker_list, SPDocument *source, gboolean history); - void remove_markers (gboolean history); - SPDocument *ink_markers_preview_doc (); - Gtk::Image * create_marker_image(unsigned psize, gchar const *mname, - SPDocument *source, Inkscape::Drawing &drawing, unsigned /*visionkey*/); + void sp_marker_list_from_doc(SPDocument *source, gboolean history); + std::vector<SPMarker *> get_marker_list(SPDocument *source); + void add_markers(std::vector<SPMarker *> const &marker_list, SPDocument *source, gboolean history); + void remove_markers(gboolean history); + SPDocument *ink_markers_preview_doc(); + Gtk::Image *create_marker_image(unsigned psize, gchar const *mname, SPDocument *source, Inkscape::Drawing &drawing, + unsigned /*visionkey*/); /* * Callbacks for drawing the combo box */ - void prepareImageRenderer( Gtk::TreeModel::const_iterator const &row ); - static gboolean separator_cb (GtkTreeModel *model, GtkTreeIter *iter, gpointer data); + void prepareImageRenderer(Gtk::TreeModel::const_iterator const &row); + static gboolean separator_cb(GtkTreeModel *model, GtkTreeIter *iter, gpointer data); static void handleDefsModified(MarkerComboBox *self); diff --git a/src/ui/widget/notebook-page.cpp b/src/ui/widget/notebook-page.cpp index a189d782683cfe23b5f1f54b8dbf96e8a098cdd0..f9b916c6e781bd227d14c08af82d28b73715cb2d 100644 --- a/src/ui/widget/notebook-page.cpp +++ b/src/ui/widget/notebook-page.cpp @@ -12,14 +12,14 @@ #include "notebook-page.h" -# include <gtkmm/grid.h> +#include <gtkmm/grid.h> namespace Inkscape { namespace UI { namespace Widget { NotebookPage::NotebookPage(int n_rows, int n_columns, bool expand, bool fill, guint padding) - :_table(Gtk::manage(new Gtk::Grid())) + : _table(Gtk::manage(new Gtk::Grid())) { set_name("NotebookPage"); set_border_width(4); diff --git a/src/ui/widget/notebook-page.h b/src/ui/widget/notebook-page.h index cc11d3056138095b0df5565f88fdaa89b09188be..c8214f6d085764311a323b22f1ca988dee7fbbbb 100644 --- a/src/ui/widget/notebook-page.h +++ b/src/ui/widget/notebook-page.h @@ -27,15 +27,14 @@ namespace Widget { class NotebookPage : public Gtk::VBox { public: - NotebookPage(); /** * Construct a NotebookPage. */ - NotebookPage(int n_rows, int n_columns, bool expand=false, bool fill=false, guint padding=0); + NotebookPage(int n_rows, int n_columns, bool expand = false, bool fill = false, guint padding = 0); - Gtk::Grid& table() { return *_table; } + Gtk::Grid &table() { return *_table; } protected: Gtk::Grid *_table; diff --git a/src/ui/widget/object-composite-settings.cpp b/src/ui/widget/object-composite-settings.cpp index 60e84d71c6d2da772b78a3d39b69559cfe8f0dca..b703c9843261082875502288694a0840f52162ae 100644 --- a/src/ui/widget/object-composite-settings.cpp +++ b/src/ui/widget/object-composite-settings.cpp @@ -15,18 +15,17 @@ #include "ui/widget/object-composite-settings.h" -#include "desktop.h" - #include "desktop-style.h" -#include "document.h" +#include "desktop.h" #include "document-undo.h" +#include "document.h" #include "filter-chemistry.h" #include "inkscape.h" +#include "object/filters/blend.h" #include "style.h" #include "svg/css-ostringstream.h" -#include "verbs.h" -#include "object/filters/blend.h" #include "ui/widget/style-subject.h" +#include "verbs.h" constexpr double BLUR_MULTIPLIER = 4.0; @@ -35,33 +34,38 @@ namespace UI { namespace Widget { ObjectCompositeSettings::ObjectCompositeSettings(unsigned int verb_code, char const *history_prefix, int flags) -: _verb_code(verb_code), - _blend_tag(Glib::ustring(history_prefix) + ":blend"), - _blur_tag(Glib::ustring(history_prefix) + ":blur"), - _opacity_tag(Glib::ustring(history_prefix) + ":opacity"), - _isolation_tag(Glib::ustring(history_prefix) + ":isolation"), - _filter_modifier(flags), - _blocked(false) + : _verb_code(verb_code) + , _blend_tag(Glib::ustring(history_prefix) + ":blend") + , _blur_tag(Glib::ustring(history_prefix) + ":blur") + , _opacity_tag(Glib::ustring(history_prefix) + ":opacity") + , _isolation_tag(Glib::ustring(history_prefix) + ":isolation") + , _filter_modifier(flags) + , _blocked(false) { - set_name( "ObjectCompositeSettings"); + set_name("ObjectCompositeSettings"); // Filter Effects pack_start(_filter_modifier, false, false, 2); - _filter_modifier.signal_blend_changed().connect(sigc::mem_fun(*this, &ObjectCompositeSettings::_blendBlurValueChanged)); - _filter_modifier.signal_blur_changed().connect(sigc::mem_fun(*this, &ObjectCompositeSettings::_blendBlurValueChanged)); - _filter_modifier.signal_opacity_changed().connect(sigc::mem_fun(*this, &ObjectCompositeSettings::_opacityValueChanged)); + _filter_modifier.signal_blend_changed().connect( + sigc::mem_fun(*this, &ObjectCompositeSettings::_blendBlurValueChanged)); + _filter_modifier.signal_blur_changed().connect( + sigc::mem_fun(*this, &ObjectCompositeSettings::_blendBlurValueChanged)); + _filter_modifier.signal_opacity_changed().connect( + sigc::mem_fun(*this, &ObjectCompositeSettings::_opacityValueChanged)); _filter_modifier.signal_isolation_changed().connect( sigc::mem_fun(*this, &ObjectCompositeSettings::_isolationValueChanged)); show_all_children(); } -ObjectCompositeSettings::~ObjectCompositeSettings() { +ObjectCompositeSettings::~ObjectCompositeSettings() +{ setSubject(nullptr); } -void ObjectCompositeSettings::setSubject(StyleSubject *subject) { +void ObjectCompositeSettings::setSubject(StyleSubject *subject) +{ _subject_changed.disconnect(); if (subject) { _subject = subject; @@ -75,8 +79,7 @@ void ObjectCompositeSettings::setSubject(StyleSubject *subject) { // If both blend and blur are used in a dialog where more than one object can // be selected then this should be split into separate functions for blend and // blur (like in the Objects dialog). -void -ObjectCompositeSettings::_blendBlurValueChanged() +void ObjectCompositeSettings::_blendBlurValueChanged() { if (!_subject) { return; @@ -95,23 +98,26 @@ ObjectCompositeSettings::_blendBlurValueChanged() Geom::OptRect bbox = _subject->getBounds(SPItem::GEOMETRIC_BBOX); double radius; if (bbox) { - double perimeter = bbox->dimensions()[Geom::X] + bbox->dimensions()[Geom::Y]; // fixme: this is only half the perimeter, is that correct? + double perimeter = bbox->dimensions()[Geom::X] + + bbox->dimensions()[Geom::Y]; // fixme: this is only half the perimeter, is that correct? double blur_value = _filter_modifier.get_blur_value() / 100.0; radius = blur_value * blur_value * perimeter / BLUR_MULTIPLIER; } else { radius = 0; } - //apply created filter to every selected item - std::vector<SPObject*> sel = _subject->list(); + // apply created filter to every selected item + std::vector<SPObject *> sel = _subject->list(); for (auto i : sel) { if (!SP_IS_ITEM(i)) { continue; } - SPItem * item = SP_ITEM(i); + SPItem *item = SP_ITEM(i); SPStyle *style = item->style; g_assert(style != nullptr); - bool change_blend = (item->style->mix_blend_mode.set ? item->style->mix_blend_mode.value : SP_CSS_BLEND_NORMAL) != _filter_modifier.get_blend_mode(); + bool change_blend = + (item->style->mix_blend_mode.set ? item->style->mix_blend_mode.value : SP_CSS_BLEND_NORMAL) != + _filter_modifier.get_blend_mode(); // < 1.0 filter based blend removal if (!item->style->mix_blend_mode.set && item->style->filter.set && item->style->getFilter()) { remove_filter_legacy_blend(item); @@ -119,32 +125,29 @@ ObjectCompositeSettings::_blendBlurValueChanged() item->style->mix_blend_mode.set = TRUE; if (item->style->isolation.value == SP_CSS_ISOLATION_ISOLATE) { item->style->mix_blend_mode.value = SP_CSS_BLEND_NORMAL; - } else { + } else { item->style->mix_blend_mode.value = _filter_modifier.get_blend_mode(); } - if (radius == 0 && item->style->filter.set - && filter_is_single_gaussian_blur(item->style->getFilter())) { + if (radius == 0 && item->style->filter.set && filter_is_single_gaussian_blur(item->style->getFilter())) { remove_filter(item, false); } else if (radius != 0) { SPFilter *filter = modify_filter_gaussian_blur_from_item(document, item, radius); sp_style_set_property_url(item, "filter", filter, false); - } - if (change_blend) { //we do blend so we need update display style + } + if (change_blend) { // we do blend so we need update display style item->updateRepr(SP_OBJECT_WRITE_NO_CHILDREN | SP_OBJECT_WRITE_EXT); } else { item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); } } - DocumentUndo::maybeDone(document, _blur_tag.c_str(), _verb_code, - _("Change blur/blend filter")); + DocumentUndo::maybeDone(document, _blur_tag.c_str(), _verb_code, _("Change blur/blend filter")); _blocked = false; } -void -ObjectCompositeSettings::_opacityValueChanged() +void ObjectCompositeSettings::_opacityValueChanged() { if (!_subject) { return; @@ -159,18 +162,17 @@ ObjectCompositeSettings::_opacityValueChanged() return; _blocked = true; - SPCSSAttr *css = sp_repr_css_attr_new (); + SPCSSAttr *css = sp_repr_css_attr_new(); Inkscape::CSSOStringStream os; - os << CLAMP (_filter_modifier.get_opacity_value() / 100, 0.0, 1.0); - sp_repr_css_set_property (css, "opacity", os.str().c_str()); + os << CLAMP(_filter_modifier.get_opacity_value() / 100, 0.0, 1.0); + sp_repr_css_set_property(css, "opacity", os.str().c_str()); _subject->setCSS(css); - sp_repr_css_attr_unref (css); + sp_repr_css_attr_unref(css); - DocumentUndo::maybeDone(desktop->getDocument(), _opacity_tag.c_str(), _verb_code, - _("Change opacity")); + DocumentUndo::maybeDone(desktop->getDocument(), _opacity_tag.c_str(), _verb_code, _("Change opacity")); _blocked = false; } @@ -205,8 +207,8 @@ void ObjectCompositeSettings::_isolationValueChanged() _blocked = false; } -void -ObjectCompositeSettings::_subjectChanged() { +void ObjectCompositeSettings::_subjectChanged() +{ if (!_subject) { return; } @@ -232,7 +234,7 @@ ObjectCompositeSettings::_subjectChanged() { break; } - //query now for current filter mode and average blurring of selection + // query now for current filter mode and average blurring of selection const int isolation_result = _subject->queryStyle(&query, QUERY_STYLE_PROPERTY_ISOLATION); switch (isolation_result) { case QUERY_STYLE_NOTHING: @@ -250,7 +252,7 @@ ObjectCompositeSettings::_subjectChanged() { // query now for current filter mode and average blurring of selection const int blend_result = _subject->queryStyle(&query, QUERY_STYLE_PROPERTY_BLEND); - switch(blend_result) { + switch (blend_result) { case QUERY_STYLE_NOTHING: _filter_modifier.set_blend_mode(SP_CSS_BLEND_NORMAL, false); break; @@ -285,19 +287,18 @@ ObjectCompositeSettings::_subjectChanged() { } // If we have nothing selected, disable dialog. - if (result == QUERY_STYLE_NOTHING && - blend_result == QUERY_STYLE_NOTHING ) { - _filter_modifier.set_sensitive( false ); + if (result == QUERY_STYLE_NOTHING && blend_result == QUERY_STYLE_NOTHING) { + _filter_modifier.set_sensitive(false); } else { - _filter_modifier.set_sensitive( true ); + _filter_modifier.set_sensitive(true); } _blocked = false; } -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/widget/object-composite-settings.h b/src/ui/widget/object-composite-settings.h index 29e6c83c49eda9b7719f5cbde6a1c987d02b11fd..f3271c703d509d23d1c55e0740e33ac4a0db3e34 100644 --- a/src/ui/widget/object-composite-settings.h +++ b/src/ui/widget/object-composite-settings.h @@ -12,11 +12,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm/box.h> +#include <glibmm/ustring.h> #include <gtkmm/adjustment.h> +#include <gtkmm/box.h> #include <gtkmm/label.h> #include <gtkmm/scale.h> -#include <glibmm/ustring.h> #include "ui/widget/filter-effect-chooser.h" @@ -33,7 +33,8 @@ class StyleSubject; /* * A widget for controlling object compositing (filter, opacity, etc.) */ -class ObjectCompositeSettings : public Gtk::VBox { +class ObjectCompositeSettings : public Gtk::VBox +{ public: ObjectCompositeSettings(unsigned int verb_code, char const *history_prefix, int flags); ~ObjectCompositeSettings() override; @@ -41,11 +42,11 @@ public: void setSubject(StyleSubject *subject); private: - unsigned int _verb_code; - Glib::ustring _blend_tag; - Glib::ustring _blur_tag; - Glib::ustring _opacity_tag; - Glib::ustring _isolation_tag; + unsigned int _verb_code; + Glib::ustring _blend_tag; + Glib::ustring _blur_tag; + Glib::ustring _opacity_tag; + Glib::ustring _isolation_tag; StyleSubject *_subject = nullptr; @@ -54,7 +55,7 @@ private: bool _blocked; gulong _desktop_activated; sigc::connection _subject_changed; - + static void _on_desktop_activate(SPDesktop *desktop, ObjectCompositeSettings *w); static void _on_desktop_deactivate(SPDesktop *desktop, ObjectCompositeSettings *w); void _subjectChanged(); @@ -63,9 +64,9 @@ private: void _isolationValueChanged(); }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/widget/page-sizer.cpp b/src/ui/widget/page-sizer.cpp index 080deab9fef415ca19bbbdd90cf9a1ff62f6ef1d..a6a81d7adfa9561a439c777de89988b5c2a6d2ea 100644 --- a/src/ui/widget/page-sizer.cpp +++ b/src/ui/widget/page-sizer.cpp @@ -19,19 +19,20 @@ */ #include "page-sizer.h" -#include "pages-skeleton.h" + #include <glib.h> #include <glibmm/i18n.h> -#include "verbs.h" + #include "helper/action.h" -#include "object/sp-root.h" #include "io/resource.h" +#include "object/sp-root.h" +#include "pages-skeleton.h" +#include "verbs.h" namespace Inkscape { namespace UI { namespace Widget { - //######################################################################## //# P A G E S I Z E R //######################################################################## @@ -39,30 +40,33 @@ namespace Widget { /** * Constructor */ -PageSizer::PageSizer(Registry & _wr) - : Gtk::VBox(false,4), - _dimensionUnits( _("U_nits:"), "units", _wr ), - _dimensionWidth( _("_Width:"), _("Width of paper"), "width", _dimensionUnits, _wr ), - _dimensionHeight( _("_Height:"), _("Height of paper"), "height", _dimensionUnits, _wr ), - _marginLock( _("Loc_k margins"), _("Lock margins"), "lock-margins", _wr, false, nullptr, nullptr), - _lock_icon(), - _marginTop( _("T_op:"), _("Top margin"), "fit-margin-top", _wr ), - _marginLeft( _("L_eft:"), _("Left margin"), "fit-margin-left", _wr), - _marginRight( _("Ri_ght:"), _("Right margin"), "fit-margin-right", _wr), - _marginBottom( _("Botto_m:"), _("Bottom margin"), "fit-margin-bottom", _wr), - _lockMarginUpdate(false), - _scaleX(_("Scale _x:"), _("Scale X"), "scale-x", _wr), - _scaleY(_("Scale _y:"), _("While SVG allows non-uniform scaling it is recommended to use only uniform scaling in Inkscape. To set a non-uniform scaling, set the 'viewBox' directly."), "scale-y", _wr), - _lockScaleUpdate(false), - _viewboxX(_("X:"), _("X"), "viewbox-x", _wr), - _viewboxY(_("Y:"), _("Y"), "viewbox-y", _wr), - _viewboxW(_("Width:"), _("Width"), "viewbox-width", _wr), - _viewboxH(_("Height:"), _("Height"), "viewbox-height", _wr), - _lockViewboxUpdate(false), - _widgetRegistry(&_wr) +PageSizer::PageSizer(Registry &_wr) + : Gtk::VBox(false, 4) + , _dimensionUnits(_("U_nits:"), "units", _wr) + , _dimensionWidth(_("_Width:"), _("Width of paper"), "width", _dimensionUnits, _wr) + , _dimensionHeight(_("_Height:"), _("Height of paper"), "height", _dimensionUnits, _wr) + , _marginLock(_("Loc_k margins"), _("Lock margins"), "lock-margins", _wr, false, nullptr, nullptr) + , _lock_icon() + , _marginTop(_("T_op:"), _("Top margin"), "fit-margin-top", _wr) + , _marginLeft(_("L_eft:"), _("Left margin"), "fit-margin-left", _wr) + , _marginRight(_("Ri_ght:"), _("Right margin"), "fit-margin-right", _wr) + , _marginBottom(_("Botto_m:"), _("Bottom margin"), "fit-margin-bottom", _wr) + , _lockMarginUpdate(false) + , _scaleX(_("Scale _x:"), _("Scale X"), "scale-x", _wr) + , _scaleY(_("Scale _y:"), + _("While SVG allows non-uniform scaling it is recommended to use only uniform scaling in Inkscape. To " + "set a non-uniform scaling, set the 'viewBox' directly."), + "scale-y", _wr) + , _lockScaleUpdate(false) + , _viewboxX(_("X:"), _("X"), "viewbox-x", _wr) + , _viewboxY(_("Y:"), _("Y"), "viewbox-y", _wr) + , _viewboxW(_("Width:"), _("Width"), "viewbox-width", _wr) + , _viewboxH(_("Height:"), _("Height"), "viewbox-height", _wr) + , _lockViewboxUpdate(false) + , _widgetRegistry(&_wr) { // set precision of scalar entry boxes - _wr.setUpdating (true); + _wr.setUpdating(true); _dimensionWidth.setDigits(5); _dimensionHeight.setDigits(5); _marginTop.setDigits(5); @@ -75,37 +79,33 @@ PageSizer::PageSizer(Registry & _wr) _viewboxY.setDigits(5); _viewboxW.setDigits(5); _viewboxH.setDigits(5); - _dimensionWidth.setRange( 0.00001, 10000000 ); - _dimensionHeight.setRange( 0.00001, 10000000 ); - _scaleX.setRange( 0.00001, 100000 ); - _scaleY.setRange( 0.00001, 100000 ); - _viewboxX.setRange( -10000000, 10000000 ); - _viewboxY.setRange( -10000000, 10000000 ); - _viewboxW.setRange( 0.00001, 10000000 ); - _viewboxH.setRange( 0.00001, 10000000 ); + _dimensionWidth.setRange(0.00001, 10000000); + _dimensionHeight.setRange(0.00001, 10000000); + _scaleX.setRange(0.00001, 100000); + _scaleY.setRange(0.00001, 100000); + _viewboxX.setRange(-10000000, 10000000); + _viewboxY.setRange(-10000000, 10000000); + _viewboxW.setRange(0.00001, 10000000); + _viewboxH.setRange(0.00001, 10000000); - _scaleY.set_sensitive (false); // We only want to display Y scale. + _scaleY.set_sensitive(false); // We only want to display Y scale. - _wr.setUpdating (false); + _wr.setUpdating(false); //# Set up the Paper Size combo box _paperSizeListStore = Gtk::ListStore::create(_paperSizeListColumns); _paperSizeList.set_model(_paperSizeListStore); - _paperSizeList.append_column(_("Name"), - _paperSizeListColumns.nameColumn); - _paperSizeList.append_column(_("Description"), - _paperSizeListColumns.descColumn); + _paperSizeList.append_column(_("Name"), _paperSizeListColumns.nameColumn); + _paperSizeList.append_column(_("Description"), _paperSizeListColumns.descColumn); _paperSizeList.set_headers_visible(false); _paperSizeListSelection = _paperSizeList.get_selection(); _paper_size_list_connection = - _paperSizeListSelection->signal_changed().connect ( - sigc::mem_fun (*this, &PageSizer::on_paper_size_list_changed)); + _paperSizeListSelection->signal_changed().connect(sigc::mem_fun(*this, &PageSizer::on_paper_size_list_changed)); _paperSizeListScroller.add(_paperSizeList); _paperSizeListScroller.set_shadow_type(Gtk::SHADOW_IN); _paperSizeListScroller.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS); _paperSizeListScroller.set_size_request(-1, 130); - char *path = Inkscape::IO::Resource::profile_path("pages.csv"); if (!g_file_test(path, G_FILE_TEST_EXISTS)) { if (!g_file_set_contents(path, pages_skeleton, -1, nullptr)) { @@ -115,14 +115,13 @@ PageSizer::PageSizer(Registry & _wr) gchar *content = nullptr; if (g_file_get_contents(path, &content, nullptr, nullptr)) { - gchar **lines = g_strsplit_set(content, "\n", 0); for (int i = 0; lines && lines[i]; ++i) { gchar **line = g_strsplit_set(lines[i], ",", 5); - if (!line[0] || !line[1] || !line[2] || !line[3] || line[0][0]=='#') + if (!line[0] || !line[1] || !line[2] || !line[3] || line[0][0] == '#') continue; - //name, width, height, unit + // name, width, height, unit double width = g_ascii_strtod(line[1], nullptr); double height = g_ascii_strtod(line[2], nullptr); g_strstrip(line[0]); @@ -144,27 +143,27 @@ PageSizer::PageSizer(Registry & _wr) } g_free(path); - pack_start (_paperSizeListScroller, true, true, 0); + pack_start(_paperSizeListScroller, true, true, 0); //## Set up orientation radio buttons - pack_start (_orientationBox, false, false, 0); + pack_start(_orientationBox, false, false, 0); _orientationLabel.set_label(_("Orientation:")); _orientationBox.pack_start(_orientationLabel, false, false, 0); _landscapeButton.set_use_underline(); _landscapeButton.set_label(_("_Landscape")); _landscapeButton.set_active(true); Gtk::RadioButton::Group group = _landscapeButton.get_group(); - _orientationBox.pack_end (_landscapeButton, false, false, 5); + _orientationBox.pack_end(_landscapeButton, false, false, 5); _portraitButton.set_use_underline(); _portraitButton.set_label(_("_Portrait")); _portraitButton.set_active(true); - _orientationBox.pack_end (_portraitButton, false, false, 5); - _portraitButton.set_group (group); - _portraitButton.set_active (true); + _orientationBox.pack_end(_portraitButton, false, false, 5); + _portraitButton.set_group(group); + _portraitButton.set_active(true); //## Set up custom size frame _customFrame.set_label(_("Custom size")); - pack_start (_customFrame, false, false, 0); + pack_start(_customFrame, false, false, 0); _customFrame.add(_customDimTable); _customDimTable.set_border_width(4); @@ -173,9 +172,9 @@ PageSizer::PageSizer(Registry & _wr) _dimensionHeight.set_halign(Gtk::ALIGN_CENTER); _dimensionUnits.set_halign(Gtk::ALIGN_END); - _customDimTable.attach(_dimensionWidth, 0, 0, 1, 1); - _customDimTable.attach(_dimensionHeight, 1, 0, 1, 1); - _customDimTable.attach(_dimensionUnits, 2, 0, 1, 1); + _customDimTable.attach(_dimensionWidth, 0, 0, 1, 1); + _customDimTable.attach(_dimensionHeight, 1, 0, 1, 1); + _customDimTable.attach(_dimensionUnits, 2, 0, 1, 1); _customDimTable.attach(_fitPageMarginExpander, 0, 1, 3, 1); @@ -201,7 +200,7 @@ PageSizer::PageSizer(Registry & _wr) _marginBox.add(_marginLabel); _marginBox.add(_marginLock); _marginBox.set_halign(Gtk::ALIGN_CENTER); - _marginTable.attach(_marginBox, 1, 1, 1, 1); + _marginTable.attach(_marginBox, 1, 1, 1, 1); //### margins _marginTop.set_halign(Gtk::ALIGN_CENTER); @@ -209,33 +208,33 @@ PageSizer::PageSizer(Registry & _wr) _marginRight.set_halign(Gtk::ALIGN_END); _marginBottom.set_halign(Gtk::ALIGN_CENTER); - _marginTable.attach(_marginTop, 0, 0, 3, 1); - _marginTable.attach(_marginLeft, 0, 1, 1, 1); - _marginTable.attach(_marginRight, 2, 1, 1, 1); - _marginTable.attach(_marginBottom, 0, 2, 3, 1); + _marginTable.attach(_marginTop, 0, 0, 3, 1); + _marginTable.attach(_marginLeft, 0, 1, 1, 1); + _marginTable.attach(_marginRight, 2, 1, 1, 1); + _marginTable.attach(_marginBottom, 0, 2, 3, 1); //### fit page to drawing button _fitPageButton.set_use_underline(); _fitPageButton.set_label(_("_Resize page to drawing or selection (Ctrl+Shift+R)")); - _fitPageButton.set_tooltip_text(_("Resize the page to fit the current selection, or the entire drawing if there is no selection")); + _fitPageButton.set_tooltip_text( + _("Resize the page to fit the current selection, or the entire drawing if there is no selection")); _fitPageButton.set_hexpand(); _fitPageButton.set_halign(Gtk::ALIGN_CENTER); - _marginTable.attach(_fitPageButton, 0, 3, 3, 1); - + _marginTable.attach(_fitPageButton, 0, 3, 3, 1); //## Set up scale frame _scaleFrame.set_label(_("Scale")); - pack_start (_scaleFrame, false, false, 0); + pack_start(_scaleFrame, false, false, 0); _scaleFrame.add(_scaleTable); _scaleTable.set_border_width(4); _scaleTable.set_row_spacing(4); _scaleTable.set_column_spacing(4); - _scaleTable.attach(_scaleX, 0, 0, 1, 1); - _scaleTable.attach(_scaleY, 1, 0, 1, 1); - _scaleTable.attach(_scaleLabel, 2, 0, 1, 1); + _scaleTable.attach(_scaleX, 0, 0, 1, 1); + _scaleTable.attach(_scaleY, 1, 0, 1, 1); + _scaleTable.attach(_scaleLabel, 2, 0, 1, 1); _viewboxExpander.set_hexpand(); _scaleTable.attach(_viewboxExpander, 0, 2, 3, 1); @@ -253,48 +252,54 @@ PageSizer::PageSizer(Registry & _wr) _viewboxW.set_halign(Gtk::ALIGN_END); _viewboxH.set_halign(Gtk::ALIGN_END); _viewboxSpacer.set_hexpand(); - _viewboxTable.attach(_viewboxX, 0, 0, 1, 1); - _viewboxTable.attach(_viewboxY, 1, 0, 1, 1); - _viewboxTable.attach(_viewboxW, 0, 1, 1, 1); - _viewboxTable.attach(_viewboxH, 1, 1, 1, 1); + _viewboxTable.attach(_viewboxX, 0, 0, 1, 1); + _viewboxTable.attach(_viewboxY, 1, 0, 1, 1); + _viewboxTable.attach(_viewboxW, 0, 1, 1, 1); + _viewboxTable.attach(_viewboxH, 1, 1, 1, 1); _viewboxTable.attach(_viewboxSpacer, 2, 0, 3, 1); } - /** * Destructor */ -PageSizer::~PageSizer() -= default; - - +PageSizer::~PageSizer() = default; /** * Initialize or reset this widget */ -void -PageSizer::init () +void PageSizer::init() { - _landscape_connection = _landscapeButton.signal_toggled().connect (sigc::mem_fun (*this, &PageSizer::on_landscape)); - _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)); + _landscape_connection = _landscapeButton.signal_toggled().connect(sigc::mem_fun(*this, &PageSizer::on_landscape)); + _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)); - _changeds_connection = _scaleX.signal_value_changed().connect (sigc::mem_fun (*this, &PageSizer::on_scale_changed)); - _changedvx_connection = _viewboxX.signal_value_changed().connect (sigc::mem_fun (*this, &PageSizer::on_viewbox_changed)); - _changedvy_connection = _viewboxY.signal_value_changed().connect (sigc::mem_fun (*this, &PageSizer::on_viewbox_changed)); - _changedvw_connection = _viewboxW.signal_value_changed().connect (sigc::mem_fun (*this, &PageSizer::on_viewbox_changed)); - _changedvh_connection = _viewboxH.signal_value_changed().connect (sigc::mem_fun (*this, &PageSizer::on_viewbox_changed)); - _changedlk_connection = _marginLock.signal_toggled().connect (sigc::mem_fun (*this, &PageSizer::on_margin_lock_changed)); - _changedmt_connection = _marginTop.signal_value_changed().connect (sigc::bind<RegisteredScalar*>(sigc::mem_fun (*this, &PageSizer::on_margin_changed), &_marginTop)); - _changedmb_connection = _marginBottom.signal_value_changed().connect (sigc::bind<RegisteredScalar*>(sigc::mem_fun (*this, &PageSizer::on_margin_changed), &_marginBottom)); - _changedml_connection = _marginLeft.signal_value_changed().connect (sigc::bind<RegisteredScalar*>(sigc::mem_fun (*this, &PageSizer::on_margin_changed), &_marginLeft)); - _changedmr_connection = _marginRight.signal_value_changed().connect (sigc::bind<RegisteredScalar*>(sigc::mem_fun (*this, &PageSizer::on_margin_changed), &_marginRight)); + _changeds_connection = _scaleX.signal_value_changed().connect(sigc::mem_fun(*this, &PageSizer::on_scale_changed)); + _changedvx_connection = + _viewboxX.signal_value_changed().connect(sigc::mem_fun(*this, &PageSizer::on_viewbox_changed)); + _changedvy_connection = + _viewboxY.signal_value_changed().connect(sigc::mem_fun(*this, &PageSizer::on_viewbox_changed)); + _changedvw_connection = + _viewboxW.signal_value_changed().connect(sigc::mem_fun(*this, &PageSizer::on_viewbox_changed)); + _changedvh_connection = + _viewboxH.signal_value_changed().connect(sigc::mem_fun(*this, &PageSizer::on_viewbox_changed)); + _changedlk_connection = + _marginLock.signal_toggled().connect(sigc::mem_fun(*this, &PageSizer::on_margin_lock_changed)); + _changedmt_connection = _marginTop.signal_value_changed().connect( + sigc::bind<RegisteredScalar *>(sigc::mem_fun(*this, &PageSizer::on_margin_changed), &_marginTop)); + _changedmb_connection = _marginBottom.signal_value_changed().connect( + sigc::bind<RegisteredScalar *>(sigc::mem_fun(*this, &PageSizer::on_margin_changed), &_marginBottom)); + _changedml_connection = _marginLeft.signal_value_changed().connect( + sigc::bind<RegisteredScalar *>(sigc::mem_fun(*this, &PageSizer::on_margin_changed), &_marginLeft)); + _changedmr_connection = _marginRight.signal_value_changed().connect( + sigc::bind<RegisteredScalar *>(sigc::mem_fun(*this, &PageSizer::on_margin_changed), &_marginRight)); show_all_children(); } - /** * Set document dimensions (if not called by Doc prop's update()) and * set the PageSizer's widgets and text entries accordingly. If @@ -304,8 +309,7 @@ PageSizer::init () * \param w, h * \param changeList whether to modify the paper size list */ -void -PageSizer::setDim (Inkscape::Util::Quantity w, Inkscape::Util::Quantity h, bool changeList, bool changeSize) +void PageSizer::setDim(Inkscape::Util::Quantity w, Inkscape::Util::Quantity h, bool changeList, bool changeSize) { static bool _called = false; if (_called) { @@ -327,7 +331,7 @@ PageSizer::setDim (Inkscape::Util::Quantity w, Inkscape::Util::Quantity h, bool if (dt && !_widgetRegistry->isUpdating()) { SPDocument *doc = dt->getDocument(); Inkscape::Util::Quantity const old_height = doc->getHeight(); - doc->setWidthAndHeight (w, h, changeSize); + doc->setWidthAndHeight(w, h, changeSize); // 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 if (changeSize && !doc->is_yaxisdown()) { @@ -337,29 +341,27 @@ PageSizer::setDim (Inkscape::Util::Quantity w, Inkscape::Util::Quantity h, bool DocumentUndo::done(doc, SP_VERB_NONE, _("Set page size")); } - if ( w != h ) { + if (w != h) { _landscapeButton.set_sensitive(true); - _portraitButton.set_sensitive (true); - _landscape = ( w > h ); + _portraitButton.set_sensitive(true); + _landscape = (w > h); _landscapeButton.set_active(_landscape ? true : false); - _portraitButton.set_active (_landscape ? false : true); + _portraitButton.set_active(_landscape ? false : true); } else { _landscapeButton.set_sensitive(false); - _portraitButton.set_sensitive (false); + _portraitButton.set_sensitive(false); } - if (changeList) - { + if (changeList) { Gtk::TreeModel::Row row = (*find_paper_size(w, h)); if (row) _paperSizeListSelection->select(row); - } + } _dimensionWidth.setUnit(w.unit->abbr); - _dimensionWidth.setValue (w.quantity); + _dimensionWidth.setValue(w.quantity); _dimensionHeight.setUnit(h.unit->abbr); - _dimensionHeight.setValue (h.quantity); - + _dimensionHeight.setValue(h.quantity); _paper_size_list_connection.unblock(); _landscape_connection.unblock(); @@ -374,8 +376,7 @@ PageSizer::setDim (Inkscape::Util::Quantity w, Inkscape::Util::Quantity h, bool * Updates the scalar widgets for the fit margins. (Just changes the value * of the ui widgets to match the xml). */ -void -PageSizer::updateFitMarginsUI(Inkscape::XML::Node *nv_repr) +void PageSizer::updateFitMarginsUI(Inkscape::XML::Node *nv_repr) { if (!_lockMarginUpdate) { double value = 0.0; @@ -394,7 +395,6 @@ PageSizer::updateFitMarginsUI(Inkscape::XML::Node *nv_repr) } } - /** * Returns an iterator pointing to a row in paperSizeListStore which * contains a paper of the specified size, or @@ -402,33 +402,31 @@ PageSizer::updateFitMarginsUI(Inkscape::XML::Node *nv_repr) * * The code is not tested for the case where w and h have different units. */ -Gtk::ListStore::iterator -PageSizer::find_paper_size (Inkscape::Util::Quantity w, Inkscape::Util::Quantity h) const +Gtk::ListStore::iterator PageSizer::find_paper_size(Inkscape::Util::Quantity w, Inkscape::Util::Quantity h) const { // The code below assumes that w < h, so make sure that's the case: - if ( h < w ) { - std::swap(h,w); + if (h < w) { + std::swap(h, w); } std::map<Glib::ustring, PaperSize>::const_iterator iter; - for (iter = _paperSizeTable.begin() ; - iter != _paperSizeTable.end() ; ++iter) { + for (iter = _paperSizeTable.begin(); iter != _paperSizeTable.end(); ++iter) { PaperSize paper = iter->second; - Inkscape::Util::Quantity smallX (paper.smaller, paper.unit); - Inkscape::Util::Quantity largeX (paper.larger, paper.unit); + Inkscape::Util::Quantity smallX(paper.smaller, paper.unit); + Inkscape::Util::Quantity largeX(paper.larger, paper.unit); // account for landscape formats (e.g. business cards) if (largeX < smallX) { std::swap(largeX, smallX); } - if ( are_near(w, smallX, 0.1) && are_near(h, largeX, 0.1) ) { + 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 != pend; ++p) { + for (; p != pend; ++p) { if ((*p)[_paperSizeListColumns.nameColumn] == paper.name) { return p; } @@ -438,13 +436,10 @@ PageSizer::find_paper_size (Inkscape::Util::Quantity w, Inkscape::Util::Quantity return _paperSizeListStore->children().end(); } - - /** * Tell the desktop to fit the page size to the selection or drawing. */ -void -PageSizer::fire_fit_canvas_to_selection_or_drawing() +void PageSizer::fire_fit_canvas_to_selection_or_drawing() { SPDesktop *dt = _widgetRegistry->desktop(); if (!dt) { @@ -454,9 +449,7 @@ PageSizer::fire_fit_canvas_to_selection_or_drawing() SPNamedView *nv; Inkscape::XML::Node *nv_repr; - if ((doc = dt->getDocument()) - && (nv = sp_document_namedview(doc, nullptr)) - && (nv_repr = nv->getRepr())) { + if ((doc = dt->getDocument()) && (nv = sp_document_namedview(doc, nullptr)) && (nv_repr = nv->getRepr())) { _lockMarginUpdate = true; sp_repr_set_svg_double(nv_repr, "fit-margin-top", _marginTop.getValue()); sp_repr_set_svg_double(nv_repr, "fit-margin-left", _marginLeft.getValue()); @@ -465,7 +458,7 @@ PageSizer::fire_fit_canvas_to_selection_or_drawing() _lockMarginUpdate = false; } - Verb *verb = Verb::get( SP_VERB_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(Inkscape::ActionContext(dt)); if (action) { @@ -474,25 +467,20 @@ PageSizer::fire_fit_canvas_to_selection_or_drawing() } } - - /** * Paper Size list callback for when a user changes the selection */ -void -PageSizer::on_paper_size_list_changed() +void PageSizer::on_paper_size_list_changed() { - //Glib::ustring name = _paperSizeList.get_active_text(); + // Glib::ustring name = _paperSizeList.get_active_text(); Gtk::TreeModel::iterator miter = _paperSizeListSelection->get_selected(); - if(!miter) - { - //error? + if (!miter) { + // error? return; - } + } Gtk::TreeModel::Row row = *miter; Glib::ustring name = row[_paperSizeListColumns.nameColumn]; - std::map<Glib::ustring, PaperSize>::const_iterator piter = - _paperSizeTable.find(name); + std::map<Glib::ustring, PaperSize>::const_iterator piter = _paperSizeTable.find(name); if (piter == _paperSizeTable.end()) { g_warning("paper size '%s' not found in table", name.c_str()); return; @@ -501,7 +489,7 @@ PageSizer::on_paper_size_list_changed() Inkscape::Util::Quantity w = Inkscape::Util::Quantity(paper.smaller, paper.unit); Inkscape::Util::Quantity h = Inkscape::Util::Quantity(paper.larger, paper.unit); - if ( w > h ) { + if (w > h) { // enforce landscape mode if this is desired for the given page format _landscape = true; } else { @@ -510,52 +498,44 @@ PageSizer::on_paper_size_list_changed() } if ((_landscape && (w < h)) || (!_landscape && (w > h))) - setDim (h, w, false); + setDim(h, w, false); else - setDim (w, h, false); - + setDim(w, h, false); } - /** * Portrait button callback */ -void -PageSizer::on_portrait() +void PageSizer::on_portrait() { if (!_portraitButton.get_active()) return; 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); + setDim(h, w); } } - /** * Landscape button callback */ -void -PageSizer::on_landscape() +void PageSizer::on_landscape() { if (!_landscapeButton.get_active()) return; 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); + setDim(h, w); } } - /** * Update scale widgets */ -void -PageSizer::updateScaleUI() +void PageSizer::updateScaleUI() { - static bool _called = false; if (_called) { return; @@ -578,15 +558,13 @@ PageSizer::updateScaleUI() SPNamedView *nv = dt->getNamedView(); std::stringstream ss; - ss << _("User units per ") << nv->display_units->abbr << "." ; - _scaleLabel.set_text( ss.str() ); - - if( !_lockScaleUpdate ) { + ss << _("User units per ") << nv->display_units->abbr << "."; + _scaleLabel.set_text(ss.str()); - double scaleX_inv = - Inkscape::Util::Quantity::convert( scale[Geom::X], "px", nv->display_units ); - if( scaleX_inv > 0 ) { - _scaleX.setValue(1.0/scaleX_inv); + if (!_lockScaleUpdate) { + double scaleX_inv = Inkscape::Util::Quantity::convert(scale[Geom::X], "px", nv->display_units); + if (scaleX_inv > 0) { + _scaleX.setValue(1.0 / scaleX_inv); } else { // Should never happen std::cerr << "PageSizer::updateScaleUI(): Invalid scale value: " << scaleX_inv << std::endl; @@ -594,11 +572,10 @@ PageSizer::updateScaleUI() } } - { // Don't need to lock as scaleY widget not linked to callback. - double scaleY_inv = - Inkscape::Util::Quantity::convert( scale[Geom::Y], "px", nv->display_units ); - if( scaleY_inv > 0 ) { - _scaleY.setValue(1.0/scaleY_inv); + { // Don't need to lock as scaleY widget not linked to callback. + double scaleY_inv = Inkscape::Util::Quantity::convert(scale[Geom::Y], "px", nv->display_units); + if (scaleY_inv > 0) { + _scaleY.setValue(1.0 / scaleY_inv); } else { // Should never happen std::cerr << "PageSizer::updateScaleUI(): Invalid scale value: " << scaleY_inv << std::endl; @@ -606,18 +583,18 @@ PageSizer::updateScaleUI() } } - if( !_lockViewboxUpdate ) { + if (!_lockViewboxUpdate) { Geom::Rect viewBox = doc->getViewBox(); - _viewboxX.setValue( viewBox.min()[Geom::X] ); - _viewboxY.setValue( viewBox.min()[Geom::Y] ); - _viewboxW.setValue( viewBox.width() ); - _viewboxH.setValue( viewBox.height() ); + _viewboxX.setValue(viewBox.min()[Geom::X]); + _viewboxY.setValue(viewBox.min()[Geom::Y]); + _viewboxW.setValue(viewBox.width()); + _viewboxH.setValue(viewBox.height()); } } else { // Should never happen std::cerr << "PageSizer::updateScaleUI(): No active desktop." << std::endl; - _scaleLabel.set_text( "Unknown scale" ); + _scaleLabel.set_text("Unknown scale"); } _changeds_connection.unblock(); @@ -629,49 +606,47 @@ PageSizer::updateScaleUI() _called = false; } - /** * Callback for the dimension widgets */ -void -PageSizer::on_value_changed() +void PageSizer::on_value_changed() { - if (_widgetRegistry->isUpdating()) return; - if (_unit != _dimensionUnits.getUnit()->abbr) return; - setDim (Inkscape::Util::Quantity(_dimensionWidth.getValue(""), _dimensionUnits.getUnit()), - Inkscape::Util::Quantity(_dimensionHeight.getValue(""), _dimensionUnits.getUnit())); + if (_widgetRegistry->isUpdating()) + return; + 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() +void PageSizer::on_units_changed() { - if (_widgetRegistry->isUpdating()) return; + if (_widgetRegistry->isUpdating()) + return; _unit = _dimensionUnits.getUnit()->abbr; - setDim (Inkscape::Util::Quantity(_dimensionWidth.getValue(""), _dimensionUnits.getUnit()), - Inkscape::Util::Quantity(_dimensionHeight.getValue(""), _dimensionUnits.getUnit()), - true, false); + setDim(Inkscape::Util::Quantity(_dimensionWidth.getValue(""), _dimensionUnits.getUnit()), + Inkscape::Util::Quantity(_dimensionHeight.getValue(""), _dimensionUnits.getUnit()), true, false); } /** * Callback for scale widgets */ -void -PageSizer::on_scale_changed() +void PageSizer::on_scale_changed() { - if (_widgetRegistry->isUpdating()) return; + if (_widgetRegistry->isUpdating()) + return; double value = _scaleX.getValue(); - if( value > 0 ) { - + if (value > 0) { SPDesktop *dt = _widgetRegistry->desktop(); if (dt) { SPDocument *doc = dt->getDocument(); SPNamedView *nv = dt->getNamedView(); - double scaleX_inv = Inkscape::Util::Quantity(1.0/value, nv->display_units ).value("px"); + double scaleX_inv = Inkscape::Util::Quantity(1.0 / value, nv->display_units).value("px"); _lockScaleUpdate = true; - doc->setDocumentScale( 1.0/scaleX_inv ); + doc->setDocumentScale(1.0 / scaleX_inv); updateScaleUI(); _lockScaleUpdate = false; DocumentUndo::done(doc, SP_VERB_NONE, _("Set page scale")); @@ -682,43 +657,40 @@ PageSizer::on_scale_changed() /** * Callback for viewbox widgets */ -void -PageSizer::on_viewbox_changed() +void PageSizer::on_viewbox_changed() { - if (_widgetRegistry->isUpdating()) return; + if (_widgetRegistry->isUpdating()) + return; double viewboxX = _viewboxX.getValue(); double viewboxY = _viewboxY.getValue(); double viewboxW = _viewboxW.getValue(); double viewboxH = _viewboxH.getValue(); - if( viewboxW > 0 && viewboxH > 0) { + if (viewboxW > 0 && viewboxH > 0) { SPDesktop *dt = _widgetRegistry->desktop(); if (dt) { SPDocument *doc = dt->getDocument(); _lockViewboxUpdate = true; - doc->setViewBox( Geom::Rect::from_xywh( viewboxX, viewboxY, viewboxW, viewboxH ) ); + doc->setViewBox(Geom::Rect::from_xywh(viewboxX, viewboxY, viewboxW, viewboxH)); updateScaleUI(); _lockViewboxUpdate = false; DocumentUndo::done(doc, SP_VERB_NONE, _("Set 'viewBox'")); } } else { - std::cerr - << "PageSizer::on_viewbox_changed(): width and height must both be greater than zero." - << std::endl; + std::cerr << "PageSizer::on_viewbox_changed(): width and height must both be greater than zero." << std::endl; } } -void -PageSizer::on_margin_lock_changed() +void PageSizer::on_margin_lock_changed() { if (_marginLock.get_active()) { _lock_icon.set_from_icon_name("object-locked", Gtk::ICON_SIZE_LARGE_TOOLBAR); - double left = _marginLeft.getValue(); - double right = _marginRight.getValue(); - double top = _marginTop.getValue(); - //double bottom = _marginBottom.getValue(); - if (Geom::are_near(left,right)) { + double left = _marginLeft.getValue(); + double right = _marginRight.getValue(); + double top = _marginTop.getValue(); + // double bottom = _marginBottom.getValue(); + if (Geom::are_near(left, right)) { if (Geom::are_near(left, top)) { on_margin_changed(&_marginBottom); } else { @@ -736,11 +708,11 @@ PageSizer::on_margin_lock_changed() } } -void -PageSizer::on_margin_changed(RegisteredScalar* widg) +void PageSizer::on_margin_changed(RegisteredScalar *widg) { double value = widg->getValue(); - if (_widgetRegistry->isUpdating()) return; + if (_widgetRegistry->isUpdating()) + return; if (_marginLock.get_active() && !_lockMarginUpdate) { _lockMarginUpdate = true; _marginLeft.setValue(value); diff --git a/src/ui/widget/page-sizer.h b/src/ui/widget/page-sizer.h index b399835b7d683c4b35b162ae91ea2df25fb55a72..f5376df3f4a0cd0c604dd3fb6f99876cd42bac83 100644 --- a/src/ui/widget/page-sizer.h +++ b/src/ui/widget/page-sizer.h @@ -12,19 +12,18 @@ #define INKSCAPE_UI_WIDGET_PAGE_SIZER_H #include <cstddef> -#include "ui/widget/registered-widget.h" -#include <sigc++/sigc++.h> - -#include "util/units.h" - #include <gtkmm/expander.h> #include <gtkmm/frame.h> #include <gtkmm/grid.h> #include <gtkmm/liststore.h> -#include <gtkmm/scrolledwindow.h> #include <gtkmm/radiobutton.h> +#include <gtkmm/scrolledwindow.h> +#include <sigc++/sigc++.h> + +#include "ui/widget/registered-widget.h" +#include "util/units.h" -namespace Inkscape { +namespace Inkscape { namespace XML { class Node; } @@ -36,106 +35,95 @@ class Registry; /** * Data class used to store common paper dimensions. Used to make - * PageSizer's _paperSizeTable. - */ + * PageSizer's _paperSizeTable. + */ class PaperSize { public: - /** * Default constructor */ - PaperSize() - { init(); } + PaperSize() { init(); } /** * Main constructor. Use this one. */ - PaperSize(const Glib::ustring &nameArg, - double smallerArg, - double largerArg, - Inkscape::Util::Unit const *unitArg) - { - name = nameArg; - smaller = smallerArg; - larger = largerArg; - unit = unitArg; - } + PaperSize(const Glib::ustring &nameArg, double smallerArg, double largerArg, Inkscape::Util::Unit const *unitArg) + { + name = nameArg; + smaller = smallerArg; + larger = largerArg; + unit = unitArg; + } /** * Copy constructor */ - PaperSize(const PaperSize &other) - { assign(other); } - + PaperSize(const PaperSize &other) { assign(other); } + /** * Assignment operator - */ + */ PaperSize &operator=(const PaperSize &other) - { assign(other); return *this; } + { + assign(other); + return *this; + } /** * Destructor - */ - virtual ~PaperSize() - = default; - + */ + virtual ~PaperSize() = default; + /** * Name of this paper specification - */ + */ Glib::ustring name; - + /** * The lesser of the two dimensions - */ + */ double smaller; - + /** * The greater of the two dimensions - */ + */ double larger; - + /** * The units (px, pt, mm, etc) of this specification - */ + */ Inkscape::Util::Unit const *unit; /// pointer to object in UnitTable, do not delete private: - - void init() - { - name = ""; - smaller = 0.0; - larger = 0.0; - unit = unit_table.getUnit("px"); - } - - void assign(const PaperSize &other) - { - name = other.name; - smaller = other.smaller; - larger = other.larger; - unit = other.unit; - } - + void init() + { + name = ""; + smaller = 0.0; + larger = 0.0; + unit = unit_table.getUnit("px"); + } + + void assign(const PaperSize &other) + { + name = other.name; + smaller = other.smaller; + larger = other.larger; + unit = other.unit; + } }; - - - - /** * A compound widget that allows the user to select the desired - * page size. This widget is used in DocumentPreferences - */ + * page size. This widget is used in DocumentPreferences + */ class PageSizer : public Gtk::VBox { public: - /** * Constructor */ - PageSizer(Registry & _wr); + PageSizer(Registry &_wr); /** * Destructor @@ -144,155 +132,155 @@ public: /** * Set up or reset this widget - */ - void init (); - + */ + void init(); + /** * Set the page size to the given dimensions. If 'changeList' is * true, then reset the paper size list to the closest match */ - void setDim (Inkscape::Util::Quantity w, Inkscape::Util::Quantity h, bool changeList=true, bool changeSize=true); - + void setDim(Inkscape::Util::Quantity w, Inkscape::Util::Quantity h, bool changeList = true, bool changeSize = true); + /** * Updates the scalar widgets for the fit margins. (Just changes the value * of the ui widgets to match the xml). */ void updateFitMarginsUI(Inkscape::XML::Node *nv_repr); - + /** * Updates the margin widgets. If lock widget is active */ - void on_margin_changed(RegisteredScalar* widg); - + void on_margin_changed(RegisteredScalar *widg); + void on_margin_lock_changed(); - + /** * Updates the scale widgets. (Just changes the values of the ui widgets.) */ void updateScaleUI(); protected: - /** * Our handy table of all 'standard' paper sizes. - */ + */ std::map<Glib::ustring, PaperSize> _paperSizeTable; /** * Find the closest standard paper size in the table, to the */ - Gtk::ListStore::iterator find_paper_size (Inkscape::Util::Quantity w, Inkscape::Util::Quantity 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(); - + //### The Paper Size selection list Gtk::HBox _paperSizeListBox; Gtk::Label _paperSizeListLabel; class PaperSizeColumns : public Gtk::TreeModel::ColumnRecord + { + public: + PaperSizeColumns() { - public: - PaperSizeColumns() - { add(nameColumn); add(descColumn); } - Gtk::TreeModelColumn<Glib::ustring> nameColumn; - Gtk::TreeModelColumn<Glib::ustring> descColumn; - }; + add(nameColumn); + add(descColumn); + } + Gtk::TreeModelColumn<Glib::ustring> nameColumn; + Gtk::TreeModelColumn<Glib::ustring> descColumn; + }; PaperSizeColumns _paperSizeListColumns; Glib::RefPtr<Gtk::ListStore> _paperSizeListStore; Gtk::TreeView _paperSizeList; Glib::RefPtr<Gtk::TreeSelection> _paperSizeListSelection; - Gtk::ScrolledWindow _paperSizeListScroller; - //callback + Gtk::ScrolledWindow _paperSizeListScroller; + // callback void on_paper_size_list_changed(); - sigc::connection _paper_size_list_connection; - + sigc::connection _paper_size_list_connection; + //### Portrait or landscape orientation - Gtk::HBox _orientationBox; - Gtk::Label _orientationLabel; - Gtk::RadioButton _portraitButton; - Gtk::RadioButton _landscapeButton; - //callbacks + Gtk::HBox _orientationBox; + Gtk::Label _orientationLabel; + Gtk::RadioButton _portraitButton; + Gtk::RadioButton _landscapeButton; + // callbacks void on_portrait(); void on_landscape(); - sigc::connection _portrait_connection; - sigc::connection _landscape_connection; + sigc::connection _portrait_connection; + sigc::connection _landscape_connection; //### Custom size frame - Gtk::Frame _customFrame; - Gtk::Grid _customDimTable; + Gtk::Frame _customFrame; + Gtk::Grid _customDimTable; - RegisteredUnitMenu _dimensionUnits; + RegisteredUnitMenu _dimensionUnits; RegisteredScalarUnit _dimensionWidth; RegisteredScalarUnit _dimensionHeight; //### Fit Page options - Gtk::Expander _fitPageMarginExpander; + Gtk::Expander _fitPageMarginExpander; - Gtk::Grid _marginTable; - Gtk::Box _marginBox; - Gtk::Label _marginLabel; + Gtk::Grid _marginTable; + Gtk::Box _marginBox; + Gtk::Label _marginLabel; RegisteredToggleButton _marginLock; - Gtk::Image _lock_icon; - RegisteredScalar _marginTop; - RegisteredScalar _marginLeft; - RegisteredScalar _marginRight; - RegisteredScalar _marginBottom; - Gtk::Button _fitPageButton; - bool _lockMarginUpdate; + Gtk::Image _lock_icon; + RegisteredScalar _marginTop; + RegisteredScalar _marginLeft; + RegisteredScalar _marginRight; + RegisteredScalar _marginBottom; + Gtk::Button _fitPageButton; + bool _lockMarginUpdate; // Document scale - Gtk::Frame _scaleFrame; - Gtk::Grid _scaleTable; + Gtk::Frame _scaleFrame; + Gtk::Grid _scaleTable; - Gtk::Label _scaleLabel; - RegisteredScalar _scaleX; - RegisteredScalar _scaleY; - bool _lockScaleUpdate; + Gtk::Label _scaleLabel; + RegisteredScalar _scaleX; + RegisteredScalar _scaleY; + bool _lockScaleUpdate; // Viewbox - Gtk::Expander _viewboxExpander; - Gtk::Grid _viewboxTable; + Gtk::Expander _viewboxExpander; + Gtk::Grid _viewboxTable; - RegisteredScalar _viewboxX; - RegisteredScalar _viewboxY; - RegisteredScalar _viewboxW; - RegisteredScalar _viewboxH; - Gtk::Box _viewboxSpacer; - bool _lockViewboxUpdate; + RegisteredScalar _viewboxX; + RegisteredScalar _viewboxY; + RegisteredScalar _viewboxW; + RegisteredScalar _viewboxH; + Gtk::Box _viewboxSpacer; + bool _lockViewboxUpdate; - //callback + // callback void on_value_changed(); void on_units_changed(); void on_scale_changed(); void on_viewbox_changed(); - sigc::connection _changedw_connection; - sigc::connection _changedh_connection; - sigc::connection _changedu_connection; - sigc::connection _changeds_connection; - sigc::connection _changedvx_connection; - sigc::connection _changedvy_connection; - sigc::connection _changedvw_connection; - sigc::connection _changedvh_connection; - sigc::connection _changedlk_connection; - sigc::connection _changedmt_connection; - sigc::connection _changedmb_connection; - sigc::connection _changedml_connection; - sigc::connection _changedmr_connection; - - Registry *_widgetRegistry; + sigc::connection _changedw_connection; + sigc::connection _changedh_connection; + sigc::connection _changedu_connection; + sigc::connection _changeds_connection; + sigc::connection _changedvx_connection; + sigc::connection _changedvy_connection; + sigc::connection _changedvw_connection; + sigc::connection _changedvh_connection; + sigc::connection _changedlk_connection; + sigc::connection _changedmt_connection; + sigc::connection _changedmb_connection; + sigc::connection _changedml_connection; + sigc::connection _changedmr_connection; + + Registry *_widgetRegistry; //### state - whether we are currently landscape or portrait - bool _landscape; - - Glib::ustring _unit; + bool _landscape; + Glib::ustring _unit; }; } // namespace Widget } // namespace UI } // namespace Inkscape - #endif // INKSCAPE_UI_WIDGET_PAGE_SIZER_H /* diff --git a/src/ui/widget/pages-skeleton.h b/src/ui/widget/pages-skeleton.h index 4beda5cba11c07ae18f06fecb6ad3a40c8ca672c..d966e34fe48055058166ca725210fc442fea19d1 100644 --- a/src/ui/widget/pages-skeleton.h +++ b/src/ui/widget/pages-skeleton.h @@ -21,56 +21,53 @@ #ifndef SEEN_PAGES_SKELETON_H #define SEEN_PAGES_SKELETON_H +/** \note + * The ISO page sizes in the table below differ from ghostscript's idea of page sizes (by + * less than 1pt). Being off by <1pt should be OK for most purposes, but may cause fuzziness + * (antialiasing) problems when printing to 72dpi or 144dpi printers or bitmap files due to + * postscript's different coordinate system (y=0 meaning bottom of page in postscript and top + * of page in SVG). I haven't looked into whether this does in fact cause fuzziness, I merely + * note the possibility. Rounding done by extension/internal/ps.cpp (e.g. floor/ceil calls) + * will also affect whether fuzziness occurs. + * + * The remainder of this comment discusses the origin of the numbers used for ISO page sizes in + * this table and in ghostscript. + * + * The versions here, in mm, are the official sizes according to + * <a href="http://en.wikipedia.org/wiki/Paper_sizes">http://en.wikipedia.org/wiki/Paper_sizes</a> + * at 2005-01-25. (The ISO entries in the below table + * were produced mechanically from the table on that page.) + * + * (The rule seems to be that A0, B0, ..., D0. sizes are rounded to the nearest number of mm + * from the "theoretical size" (i.e. 1000 * sqrt(2) or pow(2.0, .25) or the like), whereas + * going from e.g. A0 to A1 always take the floor of halving -- which by chance coincides + * exactly with flooring the "theoretical size" for n != 0 instead of the rounding to nearest + * done for n==0.) + * + * Ghostscript paper sizes are given in gs_statd.ps according to gs(1). gs_statd.ps always + * uses an integer number ofpt: sometimes gs_statd.ps rounds to nearest (e.g. a1), sometimes + * floors (e.g. a10), sometimes ceils (e.g. a8). + * + * I'm not sure how ghostscript's gs_statd.ps was calculated: it isn't just rounding the + * "theoretical size" of each page topt (see a0), nor is it rounding the a0 size times an + * appropriate power of two (see a1). Possibly it was prepared manually, with a human applying + * inconsistent rounding rules when converting from mm to pt. + */ +/** \todo + * Should we include the JIS B series (used in Japan) + * (JIS B0 is sometimes called JB0, and similarly for JB1 etc)? + * Should we exclude B7--B10 and A7--10 to make the list smaller ? + * Should we include any of the ISO C, D and E series (see below) ? + */ - /** \note - * The ISO page sizes in the table below differ from ghostscript's idea of page sizes (by - * less than 1pt). Being off by <1pt should be OK for most purposes, but may cause fuzziness - * (antialiasing) problems when printing to 72dpi or 144dpi printers or bitmap files due to - * postscript's different coordinate system (y=0 meaning bottom of page in postscript and top - * of page in SVG). I haven't looked into whether this does in fact cause fuzziness, I merely - * note the possibility. Rounding done by extension/internal/ps.cpp (e.g. floor/ceil calls) - * will also affect whether fuzziness occurs. - * - * The remainder of this comment discusses the origin of the numbers used for ISO page sizes in - * this table and in ghostscript. - * - * The versions here, in mm, are the official sizes according to - * <a href="http://en.wikipedia.org/wiki/Paper_sizes">http://en.wikipedia.org/wiki/Paper_sizes</a> - * at 2005-01-25. (The ISO entries in the below table - * were produced mechanically from the table on that page.) - * - * (The rule seems to be that A0, B0, ..., D0. sizes are rounded to the nearest number of mm - * from the "theoretical size" (i.e. 1000 * sqrt(2) or pow(2.0, .25) or the like), whereas - * going from e.g. A0 to A1 always take the floor of halving -- which by chance coincides - * exactly with flooring the "theoretical size" for n != 0 instead of the rounding to nearest - * done for n==0.) - * - * Ghostscript paper sizes are given in gs_statd.ps according to gs(1). gs_statd.ps always - * uses an integer number ofpt: sometimes gs_statd.ps rounds to nearest (e.g. a1), sometimes - * floors (e.g. a10), sometimes ceils (e.g. a8). - * - * I'm not sure how ghostscript's gs_statd.ps was calculated: it isn't just rounding the - * "theoretical size" of each page topt (see a0), nor is it rounding the a0 size times an - * appropriate power of two (see a1). Possibly it was prepared manually, with a human applying - * inconsistent rounding rules when converting from mm to pt. - */ - /** \todo - * Should we include the JIS B series (used in Japan) - * (JIS B0 is sometimes called JB0, and similarly for JB1 etc)? - * Should we exclude B7--B10 and A7--10 to make the list smaller ? - * Should we include any of the ISO C, D and E series (see below) ? - */ - - - - /* See http://www.hbp.com/content/PCR_envelopes.cfm for a much larger list of US envelope - sizes. */ - /* 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'. */ +/* See http://www.hbp.com/content/PCR_envelopes.cfm for a much larger list of US envelope + sizes. */ +/* 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'. */ static char const pages_skeleton[] = R"(#Inkscape page sizes #NAME, WIDTH, HEIGHT, UNIT diff --git a/src/ui/widget/paint-selector.cpp b/src/ui/widget/paint-selector.cpp index 7c9875bfcd7ebee7f4ecc54b8dd4cb05611b0948..f95b66eff15c08d4e202ad2242c0ff3a18ce184b 100644 --- a/src/ui/widget/paint-selector.cpp +++ b/src/ui/widget/paint-selector.cpp @@ -16,42 +16,34 @@ #define noSP_PS_VERBOSE +#include "paint-selector.h" + #include <cstring> +#include <glibmm/fileutils.h> +#include <glibmm/i18n.h> #include <string> #include <vector> -#include <glibmm/i18n.h> -#include <glibmm/fileutils.h> - #include "desktop-style.h" -#include "inkscape.h" -#include "paint-selector.h" -#include "path-prefix.h" - #include "helper/stock-items.h" -#include "ui/icon-loader.h" - -#include "style.h" - -#include "io/sys.h" +#include "inkscape.h" #include "io/resource.h" - +#include "io/sys.h" #include "object/sp-hatch.h" #include "object/sp-linear-gradient.h" #include "object/sp-mesh-gradient.h" #include "object/sp-pattern.h" #include "object/sp-radial-gradient.h" #include "object/sp-stop.h" - +#include "path-prefix.h" +#include "style.h" #include "svg/css-ostringstream.h" - +#include "ui/icon-loader.h" #include "ui/icon-names.h" #include "ui/widget/color-notebook.h" #include "ui/widget/gradient-selector.h" #include "ui/widget/swatch-selector.h" - #include "widgets/widget-sizes.h" - #include "xml/repr.h" #ifdef SP_PS_VERBOSE @@ -85,11 +77,12 @@ namespace Inkscape { namespace UI { namespace Widget { -class FillRuleRadioButton : public Gtk::RadioButton { - private: +class FillRuleRadioButton : public Gtk::RadioButton +{ +private: PaintSelector::FillRule _fillrule; - public: +public: FillRuleRadioButton() : Gtk::RadioButton() {} @@ -102,11 +95,12 @@ class FillRuleRadioButton : public Gtk::RadioButton { inline PaintSelector::FillRule get_fillrule() const { return _fillrule; } }; -class StyleToggleButton : public Gtk::ToggleButton { - private: +class StyleToggleButton : public Gtk::ToggleButton +{ +private: PaintSelector::Mode _style; - public: +public: inline void set_style(PaintSelector::Mode style) { _style = style; } inline PaintSelector::Mode get_style() const { return _style; } }; @@ -213,7 +207,6 @@ PaintSelector::PaintSelector(FillOrStroke kind) // gtk_container_set_border_width(GTK_CONTAINER(psel->frame), 0); pack_start(*_frame, true, true, 0); - /* Last used color */ _selected_color = new SelectedColor; _updating_color = false; @@ -437,7 +430,6 @@ void PaintSelector::getGradientProperties(SPGradientUnits &units, SPGradientSpre spread = gsel->getSpread(); } - /** * \post (alpha == NULL) || (*alpha in [0.0, 1.0]). */ @@ -460,7 +452,6 @@ SPGradient *PaintSelector::getGradientVector() return vect; } - void PaintSelector::pushAttrsToGradient(SPGradient *gr) const { SPGradientUnits units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX; @@ -517,7 +508,10 @@ void PaintSelector::set_mode_none() /* Color paint */ -void PaintSelector::onSelectedColorGrabbed() { _signal_grabbed.emit(); } +void PaintSelector::onSelectedColorGrabbed() +{ + _signal_grabbed.emit(); +} void PaintSelector::onSelectedColorDragged() { @@ -528,7 +522,10 @@ void PaintSelector::onSelectedColorDragged() _signal_dragged.emit(); } -void PaintSelector::onSelectedColorReleased() { _signal_released.emit(); } +void PaintSelector::onSelectedColorReleased() +{ + _signal_released.emit(); +} void PaintSelector::onSelectedColorChanged() { @@ -569,7 +566,6 @@ void PaintSelector::set_mode_color(PaintSelector::Mode /*mode*/) /* Already have color selector */ // Do nothing } else { - clear_frame(); /* Create new color selector */ /* Create vbox */ @@ -597,13 +593,25 @@ void PaintSelector::set_mode_color(PaintSelector::Mode /*mode*/) /* Gradient */ -void PaintSelector::gradient_grabbed() { _signal_grabbed.emit(); } +void PaintSelector::gradient_grabbed() +{ + _signal_grabbed.emit(); +} -void PaintSelector::gradient_dragged() { _signal_dragged.emit(); } +void PaintSelector::gradient_dragged() +{ + _signal_dragged.emit(); +} -void PaintSelector::gradient_released() { _signal_released.emit(); } +void PaintSelector::gradient_released() +{ + _signal_released.emit(); +} -void PaintSelector::gradient_changed(SPGradient * /* gr */) { _signal_changed.emit(); } +void PaintSelector::gradient_changed(SPGradient * /* gr */) +{ + _signal_changed.emit(); +} void PaintSelector::set_mode_gradient(PaintSelector::Mode mode) { @@ -633,7 +641,8 @@ void PaintSelector::set_mode_gradient(PaintSelector::Mode mode) // We should now have a valid GradientSelector so we can use it auto gsel = dynamic_cast<GradientSelector *>(_selector); - if (!gsel) g_warning("No GradientSelector found"); + if (!gsel) + g_warning("No GradientSelector found"); /* Actually we have to set option menu history here */ if (mode == PaintSelector::MODE_GRADIENT_LINEAR) { @@ -658,8 +667,10 @@ void PaintSelector::mesh_destroy(GtkWidget *widget, PaintSelector * /*psel*/) g_object_unref(G_OBJECT(widget)); } -void PaintSelector::mesh_change(GtkWidget * /*widget*/, PaintSelector *psel) { psel->_signal_changed.emit(); } - +void PaintSelector::mesh_change(GtkWidget * /*widget*/, PaintSelector *psel) +{ + psel->_signal_changed.emit(); +} /** * Returns a list of meshes in the defs of the given source document as a vector @@ -670,7 +681,6 @@ static std::vector<SPMeshGradient *> ink_mesh_list_get(SPDocument *source) if (source == nullptr) return pl; - std::vector<SPObject *> meshes = source->getResourceList("gradient"); for (auto meshe : meshes) { if (SP_IS_MESHGRADIENT(meshe) && SP_GRADIENT(meshe) == SP_GRADIENT(meshe)->getArray()) { // only if this is a @@ -690,7 +700,6 @@ static void sp_mesh_menu_build(GtkWidget *combo, std::vector<SPMeshGradient *> & GtkTreeIter iter; for (auto i : mesh_list) { - Inkscape::XML::Node *repr = i->getRepr(); gchar const *meshid = repr->attribute("id"); @@ -720,7 +729,6 @@ static void sp_mesh_list_from_doc(GtkWidget *combo, SPDocument * /*current_doc*/ sp_mesh_menu_build(combo, pl, source); } - static void ink_mesh_menu_populate_menu(GtkWidget *combo, SPDocument *doc) { static SPDocument *meshes_doc = nullptr; @@ -755,7 +763,6 @@ static void ink_mesh_menu_populate_menu(GtkWidget *combo, SPDocument *doc) // } } - static GtkWidget *ink_mesh_menu(GtkWidget *combo) { SPDocument *doc = SP_ACTIVE_DOCUMENT; @@ -764,14 +771,12 @@ static GtkWidget *ink_mesh_menu(GtkWidget *combo) GtkTreeIter iter; if (!doc) { - gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, COMBO_COL_LABEL, _("No document selected"), COMBO_COL_STOCK, false, COMBO_COL_MESH, "", COMBO_COL_SEP, false, -1); gtk_widget_set_sensitive(combo, FALSE); } else { - ink_mesh_menu_populate_menu(combo, doc); gtk_widget_set_sensitive(combo, TRUE); } @@ -789,7 +794,6 @@ static GtkWidget *ink_mesh_menu(GtkWidget *combo) return combo; } - /*update mesh list*/ void PaintSelector::updateMeshList(SPMeshGradient *mesh) { @@ -936,7 +940,6 @@ SPMeshGradient *PaintSelector::getMeshGradient() SPMeshGradient *mesh = nullptr; if (strcmp(meshid, "none")) { - gchar *mesh_name; if (stockid) { mesh_name = g_strconcat("urn:inkscape:mesh:", meshid, NULL); @@ -981,8 +984,10 @@ void PaintSelector::pattern_destroy(GtkWidget *widget, PaintSelector * /*psel*/) g_object_unref(G_OBJECT(widget)); } -void PaintSelector::pattern_change(GtkWidget * /*widget*/, PaintSelector *psel) { psel->_signal_changed.emit(); } - +void PaintSelector::pattern_change(GtkWidget * /*widget*/, PaintSelector *psel) +{ + psel->_signal_changed.emit(); +} /** * Returns a list of patterns in the defs of the given source document as a vector @@ -1013,7 +1018,6 @@ static void sp_pattern_menu_build(GtkWidget *combo, std::vector<SPPattern *> &pl GtkTreeIter iter; for (auto i = pl.rbegin(); i != pl.rend(); ++i) { - Inkscape::XML::Node *repr = (*i)->getRepr(); // label for combobox @@ -1048,7 +1052,6 @@ static void sp_pattern_list_from_doc(GtkWidget *combo, SPDocument * /*current_do sp_pattern_menu_build(combo, pl, source); } - static void ink_pattern_menu_populate_menu(GtkWidget *combo, SPDocument *doc) { static SPDocument *patterns_doc = nullptr; @@ -1081,7 +1084,6 @@ static void ink_pattern_menu_populate_menu(GtkWidget *combo, SPDocument *doc) } } - static GtkWidget *ink_pattern_menu(GtkWidget *combo) { SPDocument *doc = SP_ACTIVE_DOCUMENT; @@ -1090,14 +1092,12 @@ static GtkWidget *ink_pattern_menu(GtkWidget *combo) GtkTreeIter iter; if (!doc) { - gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, COMBO_COL_LABEL, _("No document selected"), COMBO_COL_STOCK, false, COMBO_COL_PATTERN, "", COMBO_COL_SEP, false, -1); gtk_widget_set_sensitive(combo, FALSE); } else { - ink_pattern_menu_populate_menu(combo, doc); gtk_widget_set_sensitive(combo, TRUE); } @@ -1115,7 +1115,6 @@ static GtkWidget *ink_pattern_menu(GtkWidget *combo) return combo; } - /*update pattern list*/ void PaintSelector::updatePatternList(SPPattern *pattern) { @@ -1253,7 +1252,6 @@ void PaintSelector::set_mode_hatch(PaintSelector::Mode mode) gboolean PaintSelector::isSeparator(GtkTreeModel *model, GtkTreeIter *iter, gpointer /*data*/) { - gboolean sep = FALSE; gtk_tree_model_get(model, iter, COMBO_COL_SEP, &sep, -1); return sep; @@ -1393,7 +1391,6 @@ PaintSelector::Mode PaintSelector::getModeForStyle(SPStyle const &style, FillOrS (SP_IS_GRADIENT(server) && SP_GRADIENT(server)->getVector()->isSwatch() ? "Y" : "n")); #endif // SP_PS_VERBOSE - if (server && SP_IS_GRADIENT(server) && SP_GRADIENT(server)->getVector()->isSwatch()) { mode = MODE_SWATCH; } else if (SP_IS_LINEARGRADIENT(server)) { diff --git a/src/ui/widget/paint-selector.h b/src/ui/widget/paint-selector.h index d4cabb5a4f354541f07a63468d1f0c70d8c87a9f..66b057938c179df2fa86b568acbcda3a38971c2f 100644 --- a/src/ui/widget/paint-selector.h +++ b/src/ui/widget/paint-selector.h @@ -12,14 +12,13 @@ #ifndef SEEN_SP_PAINT_SELECTOR_H #define SEEN_SP_PAINT_SELECTOR_H -#include "color.h" -#include "fill-or-stroke.h" #include <glib.h> #include <gtkmm/box.h> +#include "color.h" +#include "fill-or-stroke.h" #include "object/sp-gradient-spread.h" #include "object/sp-gradient-units.h" - #include "ui/selected-color.h" class SPGradient; @@ -47,9 +46,11 @@ class GradientSelector; /** * Generic paint selector widget. */ -class PaintSelector : public Gtk::Box { - public: - enum Mode { +class PaintSelector : public Gtk::Box +{ +public: + enum Mode + { MODE_EMPTY, MODE_MULTIPLE, MODE_NONE, @@ -65,9 +66,13 @@ class PaintSelector : public Gtk::Box { MODE_UNSET }; - enum FillRule { FILLRULE_NONZERO, FILLRULE_EVENODD }; + enum FillRule + { + FILLRULE_NONZERO, + FILLRULE_EVENODD + }; - private: +private: bool _update = false; Mode _mode; @@ -105,7 +110,7 @@ class PaintSelector : public Gtk::Box { static gboolean isSeparator(GtkTreeModel *model, GtkTreeIter *iter, gpointer data); - private: +private: sigc::signal<void, FillRule> _signal_fillrule_changed; sigc::signal<void> _signal_dragged; sigc::signal<void, Mode> _signal_mode_changed; @@ -147,7 +152,7 @@ class PaintSelector : public Gtk::Box { static void pattern_change(GtkWidget *widget, PaintSelector *psel); static void pattern_destroy(GtkWidget *widget, PaintSelector *psel); - public: +public: PaintSelector(FillOrStroke kind); ~PaintSelector() override; @@ -187,7 +192,8 @@ class PaintSelector : public Gtk::Box { SPPattern *getPattern(); }; -enum { +enum +{ COMBO_COL_LABEL = 0, COMBO_COL_STOCK = 1, COMBO_COL_PATTERN = 2, diff --git a/src/ui/widget/panel.cpp b/src/ui/widget/panel.cpp index 9f90e88123197870f4ac6313573e91683ba2f51e..2b6c4e2a69a1f903bfa5b961f32f599abb0090ca 100644 --- a/src/ui/widget/panel.cpp +++ b/src/ui/widget/panel.cpp @@ -12,38 +12,33 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm/dialog.h> // for Gtk::RESPONSE_* +#include "panel.h" #include <glibmm/i18n.h> +#include <gtkmm/dialog.h> // for Gtk::RESPONSE_* -#include "panel.h" #include "desktop.h" - -#include "inkscape.h" #include "inkscape-window.h" +#include "inkscape.h" #include "preview.h" namespace Inkscape { namespace UI { namespace Widget { -void Panel::prep() { - GtkIconSize sizes[] = { - GTK_ICON_SIZE_MENU, - GTK_ICON_SIZE_MENU, - GTK_ICON_SIZE_SMALL_TOOLBAR, - GTK_ICON_SIZE_BUTTON, - GTK_ICON_SIZE_DND, // Not used by options, but included to make the last size larger - GTK_ICON_SIZE_DIALOG - }; - Preview::set_size_mappings( G_N_ELEMENTS(sizes), sizes ); +void Panel::prep() +{ + GtkIconSize sizes[] = {GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_SMALL_TOOLBAR, GTK_ICON_SIZE_BUTTON, + GTK_ICON_SIZE_DND, // Not used by options, but included to make the last size larger + GTK_ICON_SIZE_DIALOG}; + Preview::set_size_mappings(G_N_ELEMENTS(sizes), sizes); } -Panel::Panel(gchar const *prefs_path, int verb_num) : - _prefs_path(prefs_path), - _desktop(nullptr), - _verb_num(verb_num), - _action_area(nullptr) +Panel::Panel(gchar const *prefs_path, int verb_num) + : _prefs_path(prefs_path) + , _desktop(nullptr) + , _verb_num(verb_num) + , _action_area(nullptr) { set_name("InkscapePanel"); set_orientation(Gtk::ORIENTATION_VERTICAL); @@ -68,7 +63,8 @@ Panel::Panel(gchar const *prefs_path, int verb_num) : show_all_children(); } -void Panel::_setContents(Gtk::Box *contents) { +void Panel::_setContents(Gtk::Box *contents) +{ if (_contents) { // unlinke `Gtk::Container::remove`, this will delete `_contents` if it is `Gtk::manage`d gtk_container_remove(Container::gobj(), _contents->Gtk::Widget::gobj()); @@ -135,7 +131,7 @@ Gtk::Button *Panel::addResponseButton(const Glib::ustring &button_text, int resp _action_area->pack_end(*button); if (pack_start) { - _action_area->set_child_secondary(*button , true); + _action_area->set_child_secondary(*button, true); } if (response_id != 0) { @@ -153,20 +149,17 @@ void Panel::setResponseSensitive(int response_id, bool setting) _response_map[response_id]->set_sensitive(setting); } -sigc::signal<void, SPDesktop *, SPDocument *> & -Panel::signalDocumentReplaced() +sigc::signal<void, SPDesktop *, SPDocument *> &Panel::signalDocumentReplaced() { return _signal_document_replaced; } -sigc::signal<void, SPDesktop *> & -Panel::signalActivateDesktop() +sigc::signal<void, SPDesktop *> &Panel::signalActivateDesktop() { return _signal_activate_desktop; } -sigc::signal<void, SPDesktop *> & -Panel::signalDeactiveDesktop() +sigc::signal<void, SPDesktop *> &Panel::signalDeactiveDesktop() { return _signal_deactive_desktop; } diff --git a/src/ui/widget/panel.h b/src/ui/widget/panel.h index 5b93a2b0784864a02ee28558e8bc58abd1046e91..7828547bb6f19f3edc9ae70e19c636fef76d667d 100644 --- a/src/ui/widget/panel.h +++ b/src/ui/widget/panel.h @@ -21,9 +21,9 @@ class SPDesktop; class SPDocument; namespace Gtk { - class Button; - class ButtonBox; -} +class Button; +class ButtonBox; +} // namespace Gtk struct InkscapeApplication; @@ -46,7 +46,8 @@ namespace Widget { * @see UI::Dialog::DesktopTracker to handle desktop change, selection change and selected object modifications. * @see UI::Dialog::DialogManager manages the dialogs within inkscape. */ -class Panel : public Gtk::Box { +class Panel : public Gtk::Box +{ public: static void prep(); @@ -60,10 +61,10 @@ public: ~Panel() override = default; gchar const *getPrefsPath() const; - + int const &getVerb() const; - virtual void present(); //< request to be present + virtual void present(); //< request to be present void restorePanelPrefs(); @@ -76,7 +77,7 @@ 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, bool pack_start=false); + Gtk::Button *addResponseButton(const Glib::ustring &button_text, int response_id, bool pack_start = false); void setResponseSensitive(int response_id, bool setting); /* Return signals. Signals emitted by PanelDialog. */ @@ -104,19 +105,19 @@ protected: /* Signals */ sigc::signal<void, int> _signal_response; - sigc::signal<void> _signal_present; + sigc::signal<void> _signal_present; sigc::signal<void, SPDesktop *, SPDocument *> _signal_document_replaced; sigc::signal<void, SPDesktop *> _signal_activate_desktop; sigc::signal<void, SPDesktop *> _signal_deactive_desktop; private: - SPDesktop *_desktop; + SPDesktop *_desktop; void on_activate_desktop(SPDesktop *); - int _verb_num; + int _verb_num; - Gtk::Box *_contents; - Gtk::ButtonBox *_action_area; //< stores response buttons + Gtk::Box *_contents; + Gtk::ButtonBox *_action_area; //< stores response buttons /* A map to store which widget that emits a certain response signal */ typedef std::map<int, Gtk::Widget *> ResponseMap; diff --git a/src/ui/widget/point.cpp b/src/ui/widget/point.cpp index e0d6eed1c322872d230547503d7835cf3563ba6b..4d4ccb58cbdb7ad92fe24894f22aae1b1ceef1dd 100644 --- a/src/ui/widget/point.cpp +++ b/src/ui/widget/point.cpp @@ -18,46 +18,37 @@ namespace Inkscape { namespace UI { namespace Widget { -Point::Point(Glib::ustring const &label, Glib::ustring const &tooltip, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) - : Labelled(label, tooltip, new Gtk::VBox(), suffix, icon, mnemonic), - xwidget("X:",""), - ywidget("Y:","") -{ - static_cast<Gtk::VBox*>(_widget)->pack_start(xwidget, true, true); - static_cast<Gtk::VBox*>(_widget)->pack_start(ywidget, true, true); - static_cast<Gtk::VBox*>(_widget)->show_all_children(); -} - -Point::Point(Glib::ustring const &label, Glib::ustring const &tooltip, - unsigned digits, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) - : Labelled(label, tooltip, new Gtk::VBox(), suffix, icon, mnemonic), - xwidget("X:","", digits), - ywidget("Y:","", digits) -{ - static_cast<Gtk::VBox*>(_widget)->pack_start(xwidget, true, true); - static_cast<Gtk::VBox*>(_widget)->pack_start(ywidget, true, true); - static_cast<Gtk::VBox*>(_widget)->show_all_children(); -} - -Point::Point(Glib::ustring const &label, Glib::ustring const &tooltip, - Glib::RefPtr<Gtk::Adjustment> &adjust, - unsigned digits, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) - : Labelled(label, tooltip, new Gtk::VBox(), suffix, icon, mnemonic), - xwidget("X:","", adjust, digits), - ywidget("Y:","", adjust, digits) -{ - static_cast<Gtk::VBox*>(_widget)->pack_start(xwidget, true, true); - static_cast<Gtk::VBox*>(_widget)->pack_start(ywidget, true, true); - static_cast<Gtk::VBox*>(_widget)->show_all_children(); +Point::Point(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix, + Glib::ustring const &icon, bool mnemonic) + : Labelled(label, tooltip, new Gtk::VBox(), suffix, icon, mnemonic) + , xwidget("X:", "") + , ywidget("Y:", "") +{ + static_cast<Gtk::VBox *>(_widget)->pack_start(xwidget, true, true); + static_cast<Gtk::VBox *>(_widget)->pack_start(ywidget, true, true); + static_cast<Gtk::VBox *>(_widget)->show_all_children(); +} + +Point::Point(Glib::ustring const &label, Glib::ustring const &tooltip, unsigned digits, Glib::ustring const &suffix, + Glib::ustring const &icon, bool mnemonic) + : Labelled(label, tooltip, new Gtk::VBox(), suffix, icon, mnemonic) + , xwidget("X:", "", digits) + , ywidget("Y:", "", digits) +{ + static_cast<Gtk::VBox *>(_widget)->pack_start(xwidget, true, true); + static_cast<Gtk::VBox *>(_widget)->pack_start(ywidget, true, true); + static_cast<Gtk::VBox *>(_widget)->show_all_children(); +} + +Point::Point(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::RefPtr<Gtk::Adjustment> &adjust, + unsigned digits, Glib::ustring const &suffix, Glib::ustring const &icon, bool mnemonic) + : Labelled(label, tooltip, new Gtk::VBox(), suffix, icon, mnemonic) + , xwidget("X:", "", adjust, digits) + , ywidget("Y:", "", adjust, digits) +{ + static_cast<Gtk::VBox *>(_widget)->pack_start(xwidget, true, true); + static_cast<Gtk::VBox *>(_widget)->pack_start(ywidget, true, true); + static_cast<Gtk::VBox *>(_widget)->show_all_children(); } unsigned Point::getDigits() const @@ -97,7 +88,7 @@ double Point::getYValue() const Geom::Point Point::getValue() const { - return Geom::Point( getXValue() , getYValue() ); + return Geom::Point(getXValue(), getYValue()); } int Point::getXValueAsInt() const @@ -110,7 +101,6 @@ int Point::getYValueAsInt() const return ywidget.getValueAsInt(); } - void Point::setDigits(unsigned digits) { xwidget.setDigits(digits); @@ -129,7 +119,7 @@ void Point::setRange(double min, double max) ywidget.setRange(min, max); } -void Point::setValue(Geom::Point const & p) +void Point::setValue(Geom::Point const &p) { xwidget.setValue(p[0]); ywidget.setValue(p[1]); @@ -141,7 +131,7 @@ void Point::update() ywidget.update(); } -bool Point::setProgrammatically() +bool Point::setProgrammatically() { return (xwidget.setProgrammatically || ywidget.setProgrammatically); } @@ -152,7 +142,6 @@ void Point::clearProgrammatically() ywidget.setProgrammatically = false; } - Glib::SignalProxy0<void> Point::signal_x_value_changed() { return xwidget.signal_value_changed(); @@ -163,7 +152,6 @@ Glib::SignalProxy0<void> Point::signal_y_value_changed() return ywidget.signal_value_changed(); } - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/point.h b/src/ui/widget/point.h index 018be5bbff706933372799d03990ad90de39b8cd..6162089941eddb0811f31775ba7010012fa56e74 100644 --- a/src/ui/widget/point.h +++ b/src/ui/widget/point.h @@ -14,8 +14,9 @@ #ifndef INKSCAPE_UI_WIDGET_POINT_H #define INKSCAPE_UI_WIDGET_POINT_H -#include "ui/widget/labelled.h" #include <2geom/point.h> + +#include "ui/widget/labelled.h" #include "ui/widget/scalar.h" namespace Gtk { @@ -33,8 +34,6 @@ namespace Widget { class Point : public Labelled { public: - - /** * Construct a Point Widget. * @@ -45,11 +44,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to false). */ - Point( Glib::ustring const &label, - Glib::ustring const &tooltip, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Point(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix = "", + Glib::ustring const &icon = "", bool mnemonic = true); /** * Construct a Point Widget. @@ -62,12 +58,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to false). */ - Point( Glib::ustring const &label, - Glib::ustring const &tooltip, - unsigned digits, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Point(Glib::ustring const &label, Glib::ustring const &tooltip, unsigned digits, Glib::ustring const &suffix = "", + Glib::ustring const &icon = "", bool mnemonic = true); /** * Construct a Point Widget. @@ -81,13 +73,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to true). */ - Point( Glib::ustring const &label, - Glib::ustring const &tooltip, - Glib::RefPtr<Gtk::Adjustment> &adjust, - unsigned digits = 0, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Point(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::RefPtr<Gtk::Adjustment> &adjust, + unsigned digits = 0, Glib::ustring const &suffix = "", Glib::ustring const &icon = "", bool mnemonic = true); /** * Fetches the precision of the spin button. @@ -97,65 +84,65 @@ public: /** * Gets the current step increment used by the spin button. */ - double getStep() const; + double getStep() const; /** * Gets the current page increment used by the spin button. */ - double getPage() const; + double getPage() const; /** * Gets the minimum range value allowed for the spin button. */ - double getRangeMin() const; + double getRangeMin() const; /** * Gets the maximum range value allowed for the spin button. */ - double getRangeMax() const; + double getRangeMax() const; - bool getSnapToTicks() const; + bool getSnapToTicks() const; /** * Get the value in the spin_button. */ - double getXValue() const; + double getXValue() const; - double getYValue() const; + double getYValue() const; Geom::Point getValue() const; /** * Get the value spin_button represented as an integer. */ - int getXValueAsInt() const; + int getXValueAsInt() const; - int getYValueAsInt() const; + int getYValueAsInt() const; /** * Sets the precision to be displayed by the spin button. */ - void setDigits(unsigned digits); + void setDigits(unsigned digits); /** * Sets the step and page increments for the spin button. */ - void setIncrements(double step, double page); + void setIncrements(double step, double page); /** * Sets the minimum and maximum range allowed for the spin button. */ - void setRange(double min, double max); + void setRange(double min, double max); /** * Sets the value of the spin button. */ - void setValue(Geom::Point const & p); + void setValue(Geom::Point const &p); /** * Manually forces an update of the spin button. */ - void update(); + void update(); /** * Signal raised when the spin button's value changes. diff --git a/src/ui/widget/preferences-widget.cpp b/src/ui/widget/preferences-widget.cpp index 4ccae659e7ef7ada21b4e5efaf8d1b4128b90c83..4946e0a38fd1be1af15e522ea6f769fb1a48bd10 100644 --- a/src/ui/widget/preferences-widget.cpp +++ b/src/ui/widget/preferences-widget.cpp @@ -11,32 +11,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/i18n.h> +#include "ui/widget/preferences-widget.h" + #include <glibmm/convert.h> +#include <glibmm/i18n.h> #include <glibmm/regex.h> - #include <gtkmm/box.h> #include <gtkmm/frame.h> #include <gtkmm/scale.h> #include <gtkmm/table.h> - #include "desktop.h" +#include "include/gtkmm_version.h" #include "inkscape.h" +#include "io/sys.h" #include "message-stack.h" #include "preferences.h" #include "selcue.h" #include "selection-chemistry.h" -#include "verbs.h" - -#include "include/gtkmm_version.h" - -#include "io/sys.h" - #include "ui/dialog/filedialog.h" #include "ui/icon-loader.h" -#include "ui/widget/preferences-widget.h" - +#include "verbs.h" #ifdef _WIN32 #include <windows.h> @@ -68,36 +63,29 @@ DialogPage::DialogPage() * \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) +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) { if (tip != "") - widget.set_tooltip_text (tip); - + widget.set_tooltip_text(tip); + auto hb = Gtk::manage(new Gtk::Box()); hb->set_spacing(12); hb->set_hexpand(true); hb->pack_start(widget, expand_widget, expand_widget); - - // Pack an additional widget into a box with the widget if desired + + // Pack an additional widget into a box with the widget if desired if (other_widget) hb->pack_start(*other_widget, expand_widget, expand_widget); - + hb->set_valign(Gtk::ALIGN_CENTER); - + // 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)); + 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); label_widget->set_markup(label_widget->get_text()); - + if (indent) { label_widget->set_margin_start(12); } @@ -108,14 +96,13 @@ void DialogPage::add_line(bool indent, } // Now add the widget to the bottom of the dialog - if (label == "") - { + if (label == "") { if (indent) { hb->set_margin_start(12); } add(*hb); - + GValue width = G_VALUE_INIT; g_value_init(&width, G_TYPE_INT); g_value_set_int(&width, 2); @@ -123,46 +110,43 @@ void DialogPage::add_line(bool indent, } // Add a label on the right of the widget if desired - if (suffix != "") - { - Gtk::Label* suffix_widget = Gtk::manage(new Gtk::Label(suffix , Gtk::ALIGN_START , Gtk::ALIGN_CENTER, true)); + if (suffix != "") { + Gtk::Label *suffix_widget = Gtk::manage(new Gtk::Label(suffix, Gtk::ALIGN_START, Gtk::ALIGN_CENTER, true)); suffix_widget->set_markup(suffix_widget->get_text()); - hb->pack_start(*suffix_widget,false,false); + hb->pack_start(*suffix_widget, false, false); } - } void DialogPage::add_group_header(Glib::ustring name) { - if (name != "") - { - 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)); - + if (name != "") { + 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)); + label_widget->set_use_markup(true); label_widget->set_valign(Gtk::ALIGN_CENTER); add(*label_widget); } } -void DialogPage::set_tip(Gtk::Widget& widget, Glib::ustring const &tip) +void DialogPage::set_tip(Gtk::Widget &widget, Glib::ustring const &tip) { - widget.set_tooltip_text (tip); + widget.set_tooltip_text(tip); } -void PrefCheckButton::init(Glib::ustring const &label, Glib::ustring const &prefs_path, - bool default_value) +void PrefCheckButton::init(Glib::ustring const &label, Glib::ustring const &prefs_path, bool default_value) { _prefs_path = prefs_path; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); this->set_label(label); - this->set_active( prefs->getBool(_prefs_path, default_value) ); + this->set_active(prefs->getBool(_prefs_path, default_value)); } void PrefCheckButton::on_toggled() { this->changed_signal.emit(this->get_active()); - if (this->get_visible()) //only take action if the user toggled it + if (this->get_visible()) // only take action if the user toggled it { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setBool(_prefs_path, this->get_active()); @@ -170,43 +154,41 @@ void PrefCheckButton::on_toggled() } void PrefRadioButton::init(Glib::ustring const &label, Glib::ustring const &prefs_path, - Glib::ustring const &string_value, bool default_value, PrefRadioButton* group_member) + Glib::ustring const &string_value, bool default_value, PrefRadioButton *group_member) { _prefs_path = prefs_path; _value_type = VAL_STRING; _string_value = string_value; (void)default_value; this->set_label(label); - if (group_member) - { + if (group_member) { Gtk::RadioButtonGroup rbg = group_member->get_group(); this->set_group(rbg); } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring val = prefs->getString(_prefs_path); - if ( !val.empty() ) + if (!val.empty()) this->set_active(val == _string_value); else - this->set_active( false ); + this->set_active(false); } -void PrefRadioButton::init(Glib::ustring const &label, Glib::ustring const &prefs_path, - int int_value, bool default_value, PrefRadioButton* group_member) +void PrefRadioButton::init(Glib::ustring const &label, Glib::ustring const &prefs_path, int int_value, + bool default_value, PrefRadioButton *group_member) { _prefs_path = prefs_path; _value_type = VAL_INT; _int_value = int_value; this->set_label(label); - if (group_member) - { + if (group_member) { Gtk::RadioButtonGroup rbg = group_member->get_group(); this->set_group(rbg); } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (default_value) - this->set_active( prefs->getInt(_prefs_path, int_value) == _int_value ); + this->set_active(prefs->getInt(_prefs_path, int_value) == _int_value); else - this->set_active( prefs->getInt(_prefs_path, int_value + 1) == _int_value ); + this->set_active(prefs->getInt(_prefs_path, int_value + 1) == _int_value); } void PrefRadioButton::on_toggled() @@ -214,18 +196,17 @@ void PrefRadioButton::on_toggled() this->changed_signal.emit(this->get_active()); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (this->get_visible() && this->get_active() ) //only take action if toggled by user (to active) + if (this->get_visible() && this->get_active()) // only take action if toggled by user (to active) { - if ( _value_type == VAL_STRING ) + if (_value_type == VAL_STRING) prefs->setString(_prefs_path, _string_value); - else if ( _value_type == VAL_INT ) + else if (_value_type == VAL_INT) prefs->setInt(_prefs_path, _int_value); } } -void PrefSpinButton::init(Glib::ustring const &prefs_path, - double lower, double upper, double step_increment, double /*page_increment*/, - double default_value, bool is_int, bool is_percent) +void PrefSpinButton::init(Glib::ustring const &prefs_path, double lower, double upper, double step_increment, + double /*page_increment*/, double default_value, bool is_int, bool is_percent) { _prefs_path = prefs_path; _is_int = is_int; @@ -234,17 +215,17 @@ void PrefSpinButton::init(Glib::ustring const &prefs_path, double value; if (is_int) { if (is_percent) { - value = 100 * prefs->getDoubleLimited(prefs_path, default_value, lower/100.0, upper/100.0); + value = 100 * prefs->getDoubleLimited(prefs_path, default_value, lower / 100.0, upper / 100.0); } else { - value = (double) prefs->getIntLimited(prefs_path, (int) default_value, (int) lower, (int) upper); + value = (double)prefs->getIntLimited(prefs_path, (int)default_value, (int)lower, (int)upper); } } else { value = prefs->getDoubleLimited(prefs_path, default_value, lower, upper); } - this->set_range (lower, upper); - this->set_increments (step_increment, 0); - this->set_value (value); + this->set_range(lower, upper); + this->set_increments(step_increment, 0); + this->set_value(value); this->set_width_chars(6); if (is_int) this->set_digits(0); @@ -252,19 +233,18 @@ void PrefSpinButton::init(Glib::ustring const &prefs_path, this->set_digits(4); else this->set_digits(2); - } void PrefSpinButton::on_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (this->get_visible()) //only take action if user changed value + if (this->get_visible()) // only take action if user changed value { if (_is_int) { if (_is_percent) { - prefs->setDouble(_prefs_path, this->get_value()/100.0); + prefs->setDouble(_prefs_path, this->get_value() / 100.0); } else { - prefs->setInt(_prefs_path, (int) this->get_value()); + prefs->setInt(_prefs_path, (int)this->get_value()); } } else { prefs->setDouble(_prefs_path, this->get_value()); @@ -272,17 +252,16 @@ void PrefSpinButton::on_value_changed() } } -void PrefSpinUnit::init(Glib::ustring const &prefs_path, - double lower, double upper, double step_increment, - double default_value, UnitType unit_type, Glib::ustring const &default_unit) +void PrefSpinUnit::init(Glib::ustring const &prefs_path, double lower, double upper, double step_increment, + double default_value, UnitType unit_type, Glib::ustring const &default_unit) { _prefs_path = prefs_path; _is_percent = (unit_type == UNIT_TYPE_DIMENSIONLESS); resetUnitType(unit_type); setUnit(default_unit); - setRange (lower, upper); /// @fixme this disregards changes of units - setIncrements (step_increment, 0); + setRange(lower, upper); /// @fixme this disregards changes of units + setIncrements(step_increment, 0); if (step_increment < 0.1) { setDigits(4); } else { @@ -305,7 +284,7 @@ void PrefSpinUnit::init(Glib::ustring const &prefs_path, void PrefSpinUnit::on_my_value_changed() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (getWidget()->get_visible()) //only take action if user changed value + if (getWidget()->get_visible()) // only take action if user changed value { prefs->setDoubleUnit(_prefs_path, getValue(getUnit()->abbr), getUnit()->abbr); } @@ -314,9 +293,9 @@ void PrefSpinUnit::on_my_value_changed() const double ZoomCorrRuler::textsize = 7; const double ZoomCorrRuler::textpadding = 5; -ZoomCorrRuler::ZoomCorrRuler(int width, int height) : - _unitconv(1.0), - _border(5) +ZoomCorrRuler::ZoomCorrRuler(int width, int height) + : _unitconv(1.0) + , _border(5) { set_size(width, height); } @@ -325,15 +304,15 @@ void ZoomCorrRuler::set_size(int x, int y) { _min_width = x; _height = y; - set_size_request(x + _border*2, y + _border*2); + set_size_request(x + _border * 2, y + _border * 2); } // The following two functions are borrowed from 2geom's toy-framework-2; if they are useful in // other locations, we should perhaps make them (or adapted versions of them) publicly available -static void -draw_text(cairo_t *cr, Geom::Point loc, const char* txt, bool bottom = false, - double fontsize = ZoomCorrRuler::textsize, std::string fontdesc = "Sans") { - PangoLayout* layout = pango_cairo_create_layout (cr); +static void draw_text(cairo_t *cr, Geom::Point loc, const char *txt, bool bottom = false, + double fontsize = ZoomCorrRuler::textsize, std::string fontdesc = "Sans") +{ + PangoLayout *layout = pango_cairo_create_layout(cr); pango_layout_set_text(layout, txt, -1); // set font and size @@ -342,7 +321,7 @@ draw_text(cairo_t *cr, Geom::Point loc, const char* txt, bool bottom = false, fontdesc = fontdesc + " " + sizestr.str(); PangoFontDescription *font_desc = pango_font_description_from_string(fontdesc.c_str()); pango_layout_set_font_description(layout, font_desc); - pango_font_description_free (font_desc); + pango_font_description_free(font_desc); PangoRectangle logical_extent; pango_layout_get_pixel_extents(layout, nullptr, &logical_extent); @@ -350,8 +329,8 @@ draw_text(cairo_t *cr, Geom::Point loc, const char* txt, bool bottom = false, pango_cairo_show_layout(cr, layout); } -static void -draw_number(cairo_t *cr, Geom::Point pos, double num) { +static void draw_number(cairo_t *cr, Geom::Point pos, double num) +{ std::ostringstream number; number << num; draw_text(cr, pos, number.str().c_str(), true); @@ -361,8 +340,8 @@ draw_number(cairo_t *cr, Geom::Point pos, double num) { * \arg dist The distance between consecutive minor marks * \arg major_interval Number of marks after which to draw a major mark */ -void -ZoomCorrRuler::draw_marks(Cairo::RefPtr<Cairo::Context> cr, double dist, int major_interval) { +void ZoomCorrRuler::draw_marks(Cairo::RefPtr<Cairo::Context> cr, double dist, int major_interval) +{ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); const double zoomcorr = prefs->getDouble("/options/zoomcorrection/value", 1.0); double mark = 0; @@ -383,8 +362,8 @@ ZoomCorrRuler::draw_marks(Cairo::RefPtr<Cairo::Context> cr, double dist, int maj } } -bool -ZoomCorrRuler::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) { +bool ZoomCorrRuler::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) +{ Glib::RefPtr<Gdk::Window> window = get_window(); int w = window->get_width(); @@ -392,15 +371,15 @@ ZoomCorrRuler::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) { cr->set_source_rgb(1.0, 1.0, 1.0); cr->set_fill_rule(Cairo::FILL_RULE_WINDING); - cr->rectangle(0, 0, w, _height + _border*2); + cr->rectangle(0, 0, w, _height + _border * 2); cr->fill(); cr->set_source_rgb(0.0, 0.0, 0.0); cr->set_line_width(0.5); cr->translate(_border, _border); // so that we have a small white border around the ruler - cr->move_to (0, _height); - cr->line_to (_drawing_width, _height); + cr->move_to(0, _height); + cr->line_to(_drawing_width, _height); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring abbr = prefs->getString("/options/zoomcorrection/unit"); @@ -424,11 +403,9 @@ ZoomCorrRuler::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) { return true; } - -void -ZoomCorrRulerSlider::on_slider_value_changed() +void ZoomCorrRulerSlider::on_slider_value_changed() { - if (this->get_visible() || freeze) //only take action if user changed value + if (this->get_visible() || freeze) // only take action if user changed value { freeze = true; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -439,10 +416,9 @@ ZoomCorrRulerSlider::on_slider_value_changed() } } -void -ZoomCorrRulerSlider::on_spinbutton_value_changed() +void ZoomCorrRulerSlider::on_spinbutton_value_changed() { - if (this->get_visible() || freeze) //only take action if user changed value + if (this->get_visible() || freeze) // only take action if user changed value { freeze = true; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -453,8 +429,8 @@ ZoomCorrRulerSlider::on_spinbutton_value_changed() } } -void -ZoomCorrRulerSlider::on_unit_changed() { +void ZoomCorrRulerSlider::on_unit_changed() +{ if (!_unit.get_sensitive()) { // when the unit menu is initialized, the unit is set to the default but // it needs to be reset later so we don't perform the change in this case @@ -469,15 +445,13 @@ ZoomCorrRulerSlider::on_unit_changed() { } } -bool ZoomCorrRulerSlider::on_mnemonic_activate ( bool group_cycling ) +bool ZoomCorrRulerSlider::on_mnemonic_activate(bool group_cycling) { - return _sb.mnemonic_activate ( 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) +void ZoomCorrRulerSlider::init(int ruler_width, int ruler_height, double lower, double upper, double step_increment, + double page_increment, double default_value) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double value = prefs->getDoubleLimited("/options/zoomcorrection/value", default_value, lower, upper) * 100.0; @@ -489,18 +463,18 @@ ZoomCorrRulerSlider::init(int ruler_width, int ruler_height, double lower, doubl _slider = Gtk::manage(new Gtk::Scale(Gtk::ORIENTATION_HORIZONTAL)); _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_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)); _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)); - _sb.set_range (lower, upper); - _sb.set_increments (step_increment, 0); - _sb.set_value (value); + _sb.set_range(lower, upper); + _sb.set_increments(step_increment, 0); + _sb.set_value(value); _sb.set_digits(2); _sb.set_halign(Gtk::ALIGN_CENTER); _sb.set_valign(Gtk::ALIGN_END); @@ -514,17 +488,16 @@ ZoomCorrRulerSlider::init(int ruler_width, int ruler_height, double lower, doubl auto table = Gtk::manage(new Gtk::Grid()); table->attach(*_slider, 0, 0, 1, 1); - table->attach(_sb, 1, 0, 1, 1); - table->attach(_ruler, 0, 1, 1, 1); - table->attach(_unit, 1, 1, 1, 1); + table->attach(_sb, 1, 0, 1, 1); + table->attach(_ruler, 0, 1, 1, 1); + table->attach(_unit, 1, 1, 1, 1); pack_start(*table, Gtk::PACK_SHRINK); } -void -PrefSlider::on_slider_value_changed() +void PrefSlider::on_slider_value_changed() { - if (this->get_visible() || freeze) //only take action if user changed value + if (this->get_visible() || freeze) // only take action if user changed value { freeze = true; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -534,10 +507,9 @@ PrefSlider::on_slider_value_changed() } } -void -PrefSlider::on_spinbutton_value_changed() +void PrefSlider::on_spinbutton_value_changed() { - if (this->get_visible() || freeze) //only take action if user changed value + if (this->get_visible() || freeze) // only take action if user changed value { freeze = true; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -547,14 +519,13 @@ PrefSlider::on_spinbutton_value_changed() } } -bool PrefSlider::on_mnemonic_activate ( bool group_cycling ) +bool PrefSlider::on_mnemonic_activate(bool group_cycling) { - return _sb.mnemonic_activate ( 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) +void PrefSlider::init(Glib::ustring const &prefs_path, double lower, double upper, double step_increment, + double page_increment, double default_value, int digits) { _prefs_path = prefs_path; @@ -565,16 +536,16 @@ PrefSlider::init(Glib::ustring const &prefs_path, _slider = Gtk::manage(new Gtk::Scale(Gtk::ORIENTATION_HORIZONTAL)); - _slider->set_range (lower, upper); - _slider->set_increments (step_increment, page_increment); - _slider->set_value (value); + _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); - _sb.set_increments (step_increment, 0); - _sb.set_value (value); + _sb.set_range(lower, upper); + _sb.set_increments(step_increment, 0); + _sb.set_value(value); _sb.set_digits(digits); _sb.set_halign(Gtk::ALIGN_CENTER); _sb.set_valign(Gtk::ALIGN_END); @@ -582,21 +553,20 @@ PrefSlider::init(Glib::ustring const &prefs_path, auto table = Gtk::manage(new Gtk::Grid()); _slider->set_hexpand(); table->attach(*_slider, 0, 0, 1, 1); - table->attach(_sb, 1, 0, 1, 1); + table->attach(_sb, 1, 0, 1, 1); this->pack_start(*table, Gtk::PACK_EXPAND_WIDGET); } -void PrefCombo::init(Glib::ustring const &prefs_path, - Glib::ustring labels[], int values[], int num_items, int default_value) +void PrefCombo::init(Glib::ustring const &prefs_path, Glib::ustring labels[], int values[], int num_items, + int default_value) { _prefs_path = prefs_path; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int row = 0; int value = prefs->getInt(_prefs_path, default_value); - for (int i = 0 ; i < num_items; ++i) - { + for (int i = 0; i < num_items; ++i) { this->append(labels[i]); _values.push_back(values[i]); if (value == values[i]) @@ -605,20 +575,18 @@ void PrefCombo::init(Glib::ustring const &prefs_path, this->set_active(row); } -void PrefCombo::init(Glib::ustring const &prefs_path, - Glib::ustring labels[], Glib::ustring values[], int num_items, Glib::ustring default_value) +void PrefCombo::init(Glib::ustring const &prefs_path, Glib::ustring labels[], Glib::ustring values[], int num_items, + Glib::ustring default_value) { _prefs_path = prefs_path; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int row = 0; Glib::ustring value = prefs->getString(_prefs_path); - if(value.empty()) - { + if (value.empty()) { value = default_value; } - for (int i = 0 ; i < num_items; ++i) - { + for (int i = 0; i < num_items; ++i) { this->append(labels[i]); _ustr_values.push_back(values[i]); if (value == values[i]) @@ -680,22 +648,18 @@ void PrefCombo::init(Glib::ustring const &prefs_path, std::vector<Glib::ustring> void PrefCombo::on_changed() { - if (this->get_visible()) //only take action if user changed value + if (this->get_visible()) // only take action if user changed value { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if(!_values.empty()) - { + if (!_values.empty()) { prefs->setInt(_prefs_path, _values[this->get_active_row_number()]); - } - else - { + } else { prefs->setString(_prefs_path, _ustr_values[this->get_active_row_number()]); } } } -void PrefEntryButtonHBox::init(Glib::ustring const &prefs_path, - bool visibility, Glib::ustring const &default_string) +void PrefEntryButtonHBox::init(Glib::ustring const &prefs_path, bool visibility, Glib::ustring const &default_string) { _prefs_path = prefs_path; _default_string = default_string; @@ -707,15 +671,13 @@ void PrefEntryButtonHBox::init(Glib::ustring const &prefs_path, relatedEntry->set_text(prefs->getString(_prefs_path)); this->pack_start(*relatedEntry); this->pack_start(*relatedButton); - relatedButton->signal_clicked().connect( - sigc::mem_fun(*this, &PrefEntryButtonHBox::onRelatedButtonClickedCallback)); - relatedEntry->signal_changed().connect( - sigc::mem_fun(*this, &PrefEntryButtonHBox::onRelatedEntryChangedCallback)); + relatedButton->signal_clicked().connect(sigc::mem_fun(*this, &PrefEntryButtonHBox::onRelatedButtonClickedCallback)); + relatedEntry->signal_changed().connect(sigc::mem_fun(*this, &PrefEntryButtonHBox::onRelatedEntryChangedCallback)); } void PrefEntryButtonHBox::onRelatedEntryChangedCallback() { - if (this->get_visible()) //only take action if user changed value + if (this->get_visible()) // only take action if user changed value { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setString(_prefs_path, relatedEntry->get_text()); @@ -724,7 +686,7 @@ void PrefEntryButtonHBox::onRelatedEntryChangedCallback() void PrefEntryButtonHBox::onRelatedButtonClickedCallback() { - if (this->get_visible()) //only take action if user changed value + if (this->get_visible()) // only take action if user changed value { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setString(_prefs_path, _default_string); @@ -732,90 +694,83 @@ void PrefEntryButtonHBox::onRelatedButtonClickedCallback() } } -bool PrefEntryButtonHBox::on_mnemonic_activate ( bool group_cycling ) +bool PrefEntryButtonHBox::on_mnemonic_activate(bool group_cycling) { - return relatedEntry->mnemonic_activate ( group_cycling ); + return relatedEntry->mnemonic_activate(group_cycling); } -void PrefEntryFileButtonHBox::init(Glib::ustring const &prefs_path, - bool visibility) +void PrefEntryFileButtonHBox::init(Glib::ustring const &prefs_path, bool visibility) { _prefs_path = prefs_path; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - + relatedEntry = new Gtk::Entry(); relatedEntry->set_invisible_char('*'); relatedEntry->set_visibility(visibility); relatedEntry->set_text(prefs->getString(_prefs_path)); - + relatedButton = new Gtk::Button(); - Gtk::HBox* pixlabel = new Gtk::HBox(false, 3); + Gtk::HBox *pixlabel = new Gtk::HBox(false, 3); Gtk::Image *im = sp_get_icon_image("applications-graphics", Gtk::ICON_SIZE_BUTTON); pixlabel->pack_start(*im); Gtk::Label *l = new Gtk::Label(); l->set_markup_with_mnemonic(_("_Browse...")); pixlabel->pack_start(*l); - relatedButton->add(*pixlabel); + relatedButton->add(*pixlabel); this->pack_end(*relatedButton, false, false, 4); this->pack_start(*relatedEntry, true, true, 0); relatedButton->signal_clicked().connect( - sigc::mem_fun(*this, &PrefEntryFileButtonHBox::onRelatedButtonClickedCallback)); + sigc::mem_fun(*this, &PrefEntryFileButtonHBox::onRelatedButtonClickedCallback)); relatedEntry->signal_changed().connect( - sigc::mem_fun(*this, &PrefEntryFileButtonHBox::onRelatedEntryChangedCallback)); + sigc::mem_fun(*this, &PrefEntryFileButtonHBox::onRelatedEntryChangedCallback)); } void PrefEntryFileButtonHBox::onRelatedEntryChangedCallback() { - if (this->get_visible()) //only take action if user changed value + if (this->get_visible()) // only take action if user changed value { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setString(_prefs_path, relatedEntry->get_text()); } } -static Inkscape::UI::Dialog::FileOpenDialog * selectPrefsFileInstance = nullptr; +static Inkscape::UI::Dialog::FileOpenDialog *selectPrefsFileInstance = nullptr; void PrefEntryFileButtonHBox::onRelatedButtonClickedCallback() { - if (this->get_visible()) //only take action if user changed value + if (this->get_visible()) // only take action if user changed value { //# 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; - + 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))) + if (!Inkscape::IO::file_test(open_path.c_str(), (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) open_path = ""; #ifdef _WIN32 //# If no open path, default to our win32 documents folder - if (open_path.empty()) - { + if (open_path.empty()) { // The path to the My Documents folder is read from the // value "HKEY_CURRENT_USER\Software\Windows\CurrentVersion\Explorer\Shell Folders\Personal" HKEY key = NULL; - if(RegOpenKeyExA(HKEY_CURRENT_USER, - "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", - 0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) - { + if (RegOpenKeyExA(HKEY_CURRENT_USER, + "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", 0, + KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) { WCHAR utf16path[_MAX_PATH]; DWORD value_type; DWORD data_size = sizeof(utf16path); - if(RegQueryValueExW(key, L"Personal", NULL, &value_type, - (BYTE*)utf16path, &data_size) == ERROR_SUCCESS) - { + if (RegQueryValueExW(key, L"Personal", NULL, &value_type, (BYTE *)utf16path, &data_size) == + ERROR_SUCCESS) { g_assert(value_type == REG_SZ); - gchar *utf8path = g_utf16_to_utf8( - (const gunichar2*)utf16path, -1, NULL, NULL, NULL); - if(utf8path) - { + gchar *utf8path = g_utf16_to_utf8((const gunichar2 *)utf16path, -1, NULL, NULL, NULL); + if (utf8path) { open_path = Glib::ustring(utf8path); g_free(utf8path); } @@ -825,8 +780,7 @@ void PrefEntryFileButtonHBox::onRelatedButtonClickedCallback() #endif //# If no open path, default to our home directory - if (open_path.empty()) - { + if (open_path.empty()) { open_path = g_get_home_dir(); open_path.append(G_DIR_SEPARATOR_S); } @@ -834,43 +788,38 @@ void PrefEntryFileButtonHBox::onRelatedButtonClickedCallback() //# Create a dialog SPDesktop *desktop = SP_ACTIVE_DESKTOP; if (!selectPrefsFileInstance) { - selectPrefsFileInstance = - Inkscape::UI::Dialog::FileOpenDialog::create( - *desktop->getToplevel(), - open_path, - Inkscape::UI::Dialog::EXE_TYPES, - _("Select a bitmap editor")); + selectPrefsFileInstance = Inkscape::UI::Dialog::FileOpenDialog::create( + *desktop->getToplevel(), open_path, Inkscape::UI::Dialog::EXE_TYPES, _("Select a bitmap editor")); } - + //# Show the dialog bool const success = selectPrefsFileInstance->show(); - + if (!success) { return; } - + //# User selected something. Get name and type Glib::ustring fileName = selectPrefsFileInstance->getFilename(); - if (!fileName.empty()) - { + if (!fileName.empty()) { Glib::ustring newFileName = Glib::filename_to_utf8(fileName); - if ( newFileName.size() > 0) + if (newFileName.size() > 0) open_path = newFileName; else - g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" ); + g_warning("ERROR CONVERTING OPEN FILENAME TO UTF-8"); prefs->setString(_prefs_path, open_path); } - + relatedEntry->set_text(fileName); } } -bool PrefEntryFileButtonHBox::on_mnemonic_activate ( bool group_cycling ) +bool PrefEntryFileButtonHBox::on_mnemonic_activate(bool group_cycling) { - return relatedEntry->mnemonic_activate ( group_cycling ); + return relatedEntry->mnemonic_activate(group_cycling); } void PrefOpenFolder::init(Glib::ustring const &entry_string, Glib::ustring const &tooltip) @@ -899,11 +848,11 @@ void PrefOpenFolder::onRelatedButtonClickedCallback() #ifdef _WIN32 ShellExecute(NULL, "open", relatedEntry->get_text().c_str(), NULL, NULL, SW_SHOWDEFAULT); #elif defined(__APPLE__) - std::vector<std::string> argv = { "open", relatedEntry->get_text().raw() }; + std::vector<std::string> argv = {"open", relatedEntry->get_text().raw()}; Glib::spawn_async("", argv, Glib::SpawnFlags::SPAWN_SEARCH_PATH); #else gchar *path = g_filename_to_uri(relatedEntry->get_text().c_str(), NULL, NULL); - std::vector<std::string> argv = { "xdg-open", path }; + std::vector<std::string> argv = {"xdg-open", path}; Glib::spawn_async("", argv, Glib::SpawnFlags::SPAWN_SEARCH_PATH); g_free(path); #endif @@ -935,7 +884,7 @@ void PrefEntry::init(Glib::ustring const &prefs_path, bool visibility) void PrefEntry::on_changed() { - if (this->get_visible()) //only take action if user changed value + if (this->get_visible()) // only take action if user changed value { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setString(_prefs_path, this->get_text()); @@ -962,30 +911,29 @@ void PrefMultiEntry::init(Glib::ustring const &prefs_path, int height) void PrefMultiEntry::on_changed() { - if (get_visible()) //only take action if user changed value + if (get_visible()) // only take action if user changed value { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring value = _text.get_buffer()->get_text(); value = Glib::Regex::create("\\n")->replace_literal(value, 0, "|", (Glib::RegexMatchFlags)0); prefs->setString(_prefs_path, value); - } + } } -void PrefColorPicker::init(Glib::ustring const &label, Glib::ustring const &prefs_path, - guint32 default_rgba) +void PrefColorPicker::init(Glib::ustring const &label, Glib::ustring const &prefs_path, guint32 default_rgba) { _prefs_path = prefs_path; _title = label; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - this->setRgba32( prefs->getInt(_prefs_path, (int)default_rgba) ); + this->setRgba32(prefs->getInt(_prefs_path, (int)default_rgba)); } -void PrefColorPicker::on_changed (guint32 rgba) +void PrefColorPicker::on_changed(guint32 rgba) { - if (this->get_visible()) //only take action if the user toggled it + if (this->get_visible()) // only take action if the user toggled it { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setInt(_prefs_path, (int) rgba); + prefs->setInt(_prefs_path, (int)rgba); } } @@ -999,7 +947,7 @@ void PrefUnit::init(Glib::ustring const &prefs_path) void PrefUnit::on_changed() { - if (this->get_visible()) //only take action if user changed value + if (this->get_visible()) // only take action if user changed value { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setString(_prefs_path, getUnitAbbr()); diff --git a/src/ui/widget/preferences-widget.h b/src/ui/widget/preferences-widget.h index 3e132c05fc061bd20517b29d73f2439c8a82fe35..36e46e6bfe169ee2304bdba64725019b75bd690f 100644 --- a/src/ui/widget/preferences-widget.h +++ b/src/ui/widget/preferences-widget.h @@ -16,25 +16,23 @@ #ifndef INKSCAPE_UI_WIDGET_INKSCAPE_PREFERENCES_H #define INKSCAPE_UI_WIDGET_INKSCAPE_PREFERENCES_H -#include <iostream> -#include <vector> - -#include <gtkmm/filechooserbutton.h> -#include "ui/widget/spinbutton.h" #include <cstddef> -#include <sigc++/sigc++.h> #include <gtkmm/checkbutton.h> -#include <gtkmm/radiobutton.h> -#include <gtkmm/scrolledwindow.h> -#include <gtkmm/textview.h> #include <gtkmm/comboboxtext.h> #include <gtkmm/drawingarea.h> +#include <gtkmm/filechooserbutton.h> #include <gtkmm/grid.h> +#include <gtkmm/radiobutton.h> +#include <gtkmm/scrolledwindow.h> +#include <gtkmm/textview.h> +#include <iostream> +#include <sigc++/sigc++.h> +#include <vector> #include "ui/widget/color-picker.h" -#include "ui/widget/unit-menu.h" -#include "ui/widget/spinbutton.h" #include "ui/widget/scalar-unit.h" +#include "ui/widget/spinbutton.h" +#include "ui/widget/unit-menu.h" namespace Gtk { class Scale; @@ -47,9 +45,9 @@ namespace Widget { class PrefCheckButton : public Gtk::CheckButton { public: - void init(Glib::ustring const &label, Glib::ustring const &prefs_path, - bool default_value); + void init(Glib::ustring const &label, Glib::ustring const &prefs_path, bool default_value); sigc::signal<void, bool> changed_signal; + protected: Glib::ustring _prefs_path; void on_toggled() override; @@ -58,11 +56,12 @@ protected: class PrefRadioButton : public Gtk::RadioButton { public: - void init(Glib::ustring const &label, Glib::ustring const &prefs_path, - int int_value, bool default_value, PrefRadioButton* group_member); - void init(Glib::ustring const &label, Glib::ustring const &prefs_path, - Glib::ustring const &string_value, bool default_value, PrefRadioButton* group_member); + void init(Glib::ustring const &label, Glib::ustring const &prefs_path, int int_value, bool default_value, + PrefRadioButton *group_member); + void init(Glib::ustring const &label, Glib::ustring const &prefs_path, Glib::ustring const &string_value, + bool default_value, PrefRadioButton *group_member); sigc::signal<void, bool> changed_signal; + protected: Glib::ustring _prefs_path; Glib::ustring _string_value; @@ -79,9 +78,9 @@ protected: class PrefSpinButton : public SpinButton { public: - void init(Glib::ustring const &prefs_path, - double lower, double upper, double step_increment, double page_increment, + void init(Glib::ustring const &prefs_path, double lower, double upper, double step_increment, double page_increment, double default_value, bool is_int, bool is_percent); + protected: Glib::ustring _prefs_path; bool _is_int; @@ -92,31 +91,32 @@ protected: class PrefSpinUnit : public ScalarUnit { public: - PrefSpinUnit() : ScalarUnit("", "") {}; + PrefSpinUnit() + : ScalarUnit("", ""){}; - void init(Glib::ustring const &prefs_path, - double lower, double upper, double step_increment, - double default_value, + void init(Glib::ustring const &prefs_path, double lower, double upper, double step_increment, double default_value, UnitType unit_type, Glib::ustring const &default_unit); + protected: Glib::ustring _prefs_path; bool _is_percent; void on_my_value_changed(); }; -class ZoomCorrRuler : public Gtk::DrawingArea { +class ZoomCorrRuler : public Gtk::DrawingArea +{ public: ZoomCorrRuler(int width = 100, int height = 20); void set_size(int x, int y); void set_unit_conversion(double conv) { _unitconv = conv; } - int width() { return _min_width + _border*2; } + int width() { return _min_width + _border * 2; } static const double textsize; static const double textpadding; private: - bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr) override; + bool on_draw(const Cairo::RefPtr<Cairo::Context> &cr) override; void draw_marks(Cairo::RefPtr<Cairo::Context> cr, double dist, int major_interval); @@ -130,54 +130,52 @@ private: class ZoomCorrRulerSlider : public Gtk::VBox { public: - void init(int ruler_width, int ruler_height, double lower, double upper, - double step_increment, double page_increment, double default_value); + void init(int ruler_width, int ruler_height, double lower, double upper, double step_increment, + double page_increment, double default_value); private: void on_slider_value_changed(); void on_spinbutton_value_changed(); void on_unit_changed(); - bool on_mnemonic_activate( bool group_cycling ) override; + bool on_mnemonic_activate(bool group_cycling) override; Inkscape::UI::Widget::SpinButton _sb; - UnitMenu _unit; - Gtk::Scale* _slider; - ZoomCorrRuler _ruler; + UnitMenu _unit; + Gtk::Scale *_slider; + ZoomCorrRuler _ruler; bool freeze; // used to block recursive updates of slider and spinbutton }; class PrefSlider : public Gtk::HBox { public: - void init(Glib::ustring const &prefs_path, - double lower, double upper, double step_increment, double page_increment, double default_value, int digits); + void init(Glib::ustring const &prefs_path, double lower, double upper, double step_increment, double page_increment, + double default_value, int digits); private: void on_slider_value_changed(); void on_spinbutton_value_changed(); - bool on_mnemonic_activate( bool group_cycling ) override; + bool on_mnemonic_activate(bool group_cycling) override; Glib::ustring _prefs_path; Inkscape::UI::Widget::SpinButton _sb; - Gtk::Scale* _slider; + Gtk::Scale *_slider; bool freeze; // used to block recursive updates of slider and spinbutton }; - class PrefCombo : public Gtk::ComboBoxText { public: - void init(Glib::ustring const &prefs_path, - Glib::ustring labels[], int values[], int num_items, int default_value); + void init(Glib::ustring const &prefs_path, Glib::ustring labels[], int values[], int num_items, int default_value); /** * Initialize a combo box. * second form uses strings as key values. */ - void init(Glib::ustring const &prefs_path, - Glib::ustring labels[], Glib::ustring values[], int num_items, Glib::ustring default_value); + void init(Glib::ustring const &prefs_path, Glib::ustring labels[], Glib::ustring values[], int num_items, + Glib::ustring default_value); /** * Initialize a combo box. * with vectors. @@ -188,10 +186,10 @@ public: void init(Glib::ustring const &prefs_path, std::vector<Glib::ustring> labels, std::vector<Glib::ustring> values, Glib::ustring default_value); - protected: +protected: Glib::ustring _prefs_path; std::vector<int> _values; - std::vector<Glib::ustring> _ustr_values; ///< string key values used optionally instead of numeric _values + std::vector<Glib::ustring> _ustr_values; ///< string key values used optionally instead of numeric _values void on_changed() override; }; @@ -199,6 +197,7 @@ class PrefEntry : public Gtk::Entry { public: void init(Glib::ustring const &prefs_path, bool mask); + protected: Glib::ustring _prefs_path; void on_changed() override; @@ -208,17 +207,17 @@ class PrefMultiEntry : public Gtk::ScrolledWindow { public: void init(Glib::ustring const &prefs_path, int height); + protected: - Glib::ustring _prefs_path; - Gtk::TextView _text; + Glib::ustring _prefs_path; + Gtk::TextView _text; void on_changed(); }; class PrefEntryButtonHBox : public Gtk::HBox { public: - void init(Glib::ustring const &prefs_path, - bool mask, Glib::ustring const &default_string); + void init(Glib::ustring const &prefs_path, bool mask, Glib::ustring const &default_string); protected: Glib::ustring _prefs_path; @@ -227,28 +226,29 @@ protected: Gtk::Entry *relatedEntry; void onRelatedEntryChangedCallback(); void onRelatedButtonClickedCallback(); - bool on_mnemonic_activate( bool group_cycling ) override; + bool on_mnemonic_activate(bool group_cycling) override; }; class PrefEntryFileButtonHBox : public Gtk::HBox { public: - void init(Glib::ustring const &prefs_path, - bool mask); + void init(Glib::ustring const &prefs_path, bool mask); + protected: Glib::ustring _prefs_path; Gtk::Button *relatedButton; Gtk::Entry *relatedEntry; void onRelatedEntryChangedCallback(); void onRelatedButtonClickedCallback(); - bool on_mnemonic_activate( bool group_cycling ) override; + bool on_mnemonic_activate(bool group_cycling) override; }; -class PrefOpenFolder : public Gtk::HBox { - public: +class PrefOpenFolder : public Gtk::HBox +{ +public: void init(Glib::ustring const &entry_string, Glib::ustring const &tooltip); - protected: +protected: Gtk::Button *relatedButton; Gtk::Entry *relatedEntry; void onRelatedButtonClickedCallback(); @@ -267,21 +267,23 @@ protected: class PrefColorPicker : public ColorPicker { public: - PrefColorPicker() : ColorPicker("", "", 0, false) {}; - ~PrefColorPicker() override = default;; + PrefColorPicker() + : ColorPicker("", "", 0, false){}; + ~PrefColorPicker() override = default; + ; - void init(Glib::ustring const &abel, Glib::ustring const &prefs_path, - guint32 default_rgba); + void init(Glib::ustring const &abel, Glib::ustring const &prefs_path, guint32 default_rgba); protected: Glib::ustring _prefs_path; - void on_changed (guint32 rgba) override; + void on_changed(guint32 rgba) override; }; class PrefUnit : public UnitMenu { public: void init(Glib::ustring const &prefs_path); + protected: Glib::ustring _prefs_path; void on_changed() override; @@ -291,17 +293,17 @@ class DialogPage : public Gtk::Grid { 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, Gtk::Widget *other_widget = nullptr); + 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 = nullptr); void add_group_header(Glib::ustring name); void set_tip(Gtk::Widget &widget, Glib::ustring const &tip); }; - } // namespace Widget } // namespace UI } // namespace Inkscape -#endif //INKSCAPE_UI_WIDGET_INKSCAPE_PREFERENCES_H +#endif // INKSCAPE_UI_WIDGET_INKSCAPE_PREFERENCES_H /* Local Variables: diff --git a/src/ui/widget/preview.cpp b/src/ui/widget/preview.cpp index a56639c43af2e88207e0e39070d35c71f8285a34..712b89e1390da993afe35bdd40c746e65fb08057 100644 --- a/src/ui/widget/preview.cpp +++ b/src/ui/widget/preview.cpp @@ -35,9 +35,11 @@ * * ***** END LICENSE BLOCK ***** */ +#include "preview.h" + #include <algorithm> #include <gdkmm/general.h> -#include "preview.h" + #include "preferences.h" namespace Inkscape { @@ -52,8 +54,7 @@ namespace Widget { #define PREVIEW_MAX_RATIO 500 -void -Preview::set_color(int r, int g, int b ) +void Preview::set_color(int r, int g, int b) { _r = r; _g = g; @@ -62,16 +63,13 @@ Preview::set_color(int r, int g, int b ) queue_draw(); } - -void -Preview::set_pixbuf(const Glib::RefPtr<Gdk::Pixbuf> &pixbuf) +void Preview::set_pixbuf(const Glib::RefPtr<Gdk::Pixbuf> &pixbuf) { _previewPixbuf = pixbuf; queue_draw(); - if (_scaled) - { + if (_scaled) { _scaled.reset(); } @@ -82,8 +80,7 @@ Preview::set_pixbuf(const Glib::RefPtr<Gdk::Pixbuf> &pixbuf) static gboolean setupDone = FALSE; static GtkRequisition sizeThings[PREVIEW_SIZE_NEXTFREE]; -void -Preview::set_size_mappings( guint count, GtkIconSize const* sizes ) +void Preview::set_size_mappings(guint count, GtkIconSize const *sizes) { gint width = 0; gint height = 0; @@ -92,13 +89,13 @@ Preview::set_size_mappings( guint count, GtkIconSize const* sizes ) guint i = 0; guint delta = 0; - for ( i = 0; i < count; ++i ) { - gboolean worked = gtk_icon_size_lookup( sizes[i], &width, &height ); - if ( worked ) { - if ( width < smallest ) { + for (i = 0; i < count; ++i) { + gboolean worked = gtk_icon_size_lookup(sizes[i], &width, &height); + if (worked) { + if (width < smallest) { smallest = width; } - if ( width > largest ) { + if (width > largest) { largest = width; } } @@ -108,8 +105,8 @@ Preview::set_size_mappings( guint count, GtkIconSize const* sizes ) delta = largest - smallest; - for ( i = 0; i < G_N_ELEMENTS(sizeThings); ++i ) { - guint val = smallest + ( (i * delta) / (G_N_ELEMENTS(sizeThings) - 1) ); + for (i = 0; i < G_N_ELEMENTS(sizeThings); ++i) { + guint val = smallest + ((i * delta) / (G_N_ELEMENTS(sizeThings) - 1)); sizeThings[i].width = val; sizeThings[i].height = val; } @@ -117,33 +114,27 @@ Preview::set_size_mappings( guint count, GtkIconSize const* sizes ) setupDone = TRUE; } -void -Preview::size_request(GtkRequisition* req) const +void Preview::size_request(GtkRequisition *req) const { - int width = 0; - int height = 0; - - if ( !setupDone ) { - GtkIconSize sizes[] = { - GTK_ICON_SIZE_MENU, - GTK_ICON_SIZE_SMALL_TOOLBAR, - GTK_ICON_SIZE_LARGE_TOOLBAR, - GTK_ICON_SIZE_BUTTON, - GTK_ICON_SIZE_DIALOG - }; - set_size_mappings( G_N_ELEMENTS(sizes), sizes ); + int width = 0; + int height = 0; + + if (!setupDone) { + GtkIconSize sizes[] = {GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_SMALL_TOOLBAR, GTK_ICON_SIZE_LARGE_TOOLBAR, + GTK_ICON_SIZE_BUTTON, GTK_ICON_SIZE_DIALOG}; + set_size_mappings(G_N_ELEMENTS(sizes), sizes); } width = sizeThings[_size].width; height = sizeThings[_size].height; - if ( _view == VIEW_TYPE_LIST ) { + if (_view == VIEW_TYPE_LIST) { width *= 3; } - if ( _ratio != 100 ) { + if (_ratio != 100) { width = (width * _ratio) / 100; - if ( width < 0 ) { + if (width < 0) { width = 1; } } @@ -152,24 +143,21 @@ Preview::size_request(GtkRequisition* req) const req->height = height; } -void -Preview::get_preferred_width_vfunc(int &minimal_width, int &natural_width) const +void Preview::get_preferred_width_vfunc(int &minimal_width, int &natural_width) const { GtkRequisition requisition; size_request(&requisition); minimal_width = natural_width = requisition.width; } -void -Preview::get_preferred_height_vfunc(int &minimal_height, int &natural_height) const +void Preview::get_preferred_height_vfunc(int &minimal_height, int &natural_height) const { GtkRequisition requisition; size_request(&requisition); minimal_height = natural_height = requisition.height; } -bool -Preview::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) +bool Preview::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) { auto allocation = get_allocation(); @@ -191,13 +179,9 @@ Preview::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) auto context = get_style_context(); - context->render_frame(cr, - 0, 0, - allocation.get_width(), allocation.get_height()); + context->render_frame(cr, 0, 0, allocation.get_width(), allocation.get_height()); - context->render_background(cr, - 0, 0, - allocation.get_width(), allocation.get_height()); + context->render_background(cr, 0, 0, allocation.get_width(), allocation.get_height()); // Border if (_border != BORDER_NONE) { @@ -206,24 +190,21 @@ Preview::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) cr->fill(); } - cr->set_source_rgb(_r/65535.0, _g/65535.0, _b/65535.0 ); - cr->rectangle(insetLeft, insetTop, allocation.get_width() - (insetLeft + insetRight), allocation.get_height() - (insetTop + insetBottom)); + cr->set_source_rgb(_r / 65535.0, _g / 65535.0, _b / 65535.0); + cr->rectangle(insetLeft, insetTop, allocation.get_width() - (insetLeft + insetRight), + allocation.get_height() - (insetTop + insetBottom)); cr->fill(); - if (_previewPixbuf ) - { + if (_previewPixbuf) { if ((allocation.get_width() != _scaledW) || (allocation.get_height() != _scaledH)) { - if (_scaled) - { + if (_scaled) { _scaled.reset(); } _scaledW = allocation.get_width() - (insetLeft + insetRight); _scaledH = allocation.get_height() - (insetTop + insetBottom); - _scaled = _previewPixbuf->scale_simple(_scaledW, - _scaledH, - Gdk::INTERP_BILINEAR); + _scaled = _previewPixbuf->scale_simple(_scaledW, _scaledH, Gdk::INTERP_BILINEAR); } Glib::RefPtr<Gdk::Pixbuf> pix = (_scaled) ? _scaled : _previewPixbuf; @@ -239,113 +220,83 @@ Preview::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) cr->paint(); } - if (_linked) - { + if (_linked) { /* Draw arrow */ - GdkRectangle possible = {insetLeft, - insetTop, - (allocation.get_width() - (insetLeft + insetRight)), - (allocation.get_height() - (insetTop + insetBottom)) - }; + GdkRectangle possible = {insetLeft, insetTop, (allocation.get_width() - (insetLeft + insetRight)), + (allocation.get_height() - (insetTop + insetBottom))}; - GdkRectangle area = {possible.x, - possible.y, - possible.width / 2, - possible.height / 2 }; + GdkRectangle area = {possible.x, possible.y, possible.width / 2, possible.height / 2}; /* Make it square */ - if ( area.width > area.height ) + if (area.width > area.height) area.width = area.height; - if ( area.height > area.width ) + if (area.height > area.width) area.height = area.width; /* Center it horizontally */ - if ( area.width < possible.width ) { + if (area.width < possible.width) { int diff = (possible.width - area.width) / 2; area.x += diff; } - if (_linked & PREVIEW_LINK_IN) - { + if (_linked & PREVIEW_LINK_IN) { context->render_arrow(cr, G_PI, // Down-pointing arrow - area.x, area.y, - std::min(area.width, area.height) - ); + area.x, area.y, std::min(area.width, area.height)); } - if (_linked & PREVIEW_LINK_OUT) - { + if (_linked & PREVIEW_LINK_OUT) { GdkRectangle otherArea = {area.x, area.y, area.width, area.height}; - if ( otherArea.height < possible.height ) { + if (otherArea.height < possible.height) { otherArea.y = possible.y + (possible.height - otherArea.height); } context->render_arrow(cr, G_PI, // Down-pointing arrow - otherArea.x, otherArea.y, - std::min(otherArea.width, otherArea.height) - ); + otherArea.x, otherArea.y, std::min(otherArea.width, otherArea.height)); } - if (_linked & PREVIEW_LINK_OTHER) - { + if (_linked & PREVIEW_LINK_OTHER) { GdkRectangle otherArea = {insetLeft, area.y, area.width, area.height}; - if ( otherArea.height < possible.height ) { + if (otherArea.height < possible.height) { otherArea.y = possible.y + (possible.height - otherArea.height) / 2; } context->render_arrow(cr, - 1.5*G_PI, // Left-pointing arrow - otherArea.x, otherArea.y, - std::min(otherArea.width, otherArea.height) - ); + 1.5 * G_PI, // Left-pointing arrow + otherArea.x, otherArea.y, std::min(otherArea.width, otherArea.height)); } - - if (_linked & PREVIEW_FILL) - { - GdkRectangle otherArea = {possible.x + ((possible.width / 4) - (area.width / 2)), - area.y, - area.width, area.height}; - if ( otherArea.height < possible.height ) { + if (_linked & PREVIEW_FILL) { + GdkRectangle otherArea = {possible.x + ((possible.width / 4) - (area.width / 2)), area.y, area.width, + area.height}; + if (otherArea.height < possible.height) { otherArea.y = possible.y + (possible.height - otherArea.height) / 2; } - context->render_check(cr, - otherArea.x, otherArea.y, - otherArea.width, otherArea.height ); + context->render_check(cr, otherArea.x, otherArea.y, otherArea.width, otherArea.height); } - if (_linked & PREVIEW_STROKE) - { - GdkRectangle otherArea = {possible.x + (((possible.width * 3) / 4) - (area.width / 2)), - area.y, - area.width, area.height}; - if ( otherArea.height < possible.height ) { + if (_linked & PREVIEW_STROKE) { + GdkRectangle otherArea = {possible.x + (((possible.width * 3) / 4) - (area.width / 2)), area.y, area.width, + area.height}; + if (otherArea.height < possible.height) { otherArea.y = possible.y + (possible.height - otherArea.height) / 2; } // This should be a diamond too? - context->render_check(cr, - otherArea.x, otherArea.y, - otherArea.width, otherArea.height ); + context->render_check(cr, otherArea.x, otherArea.y, otherArea.width, otherArea.height); } } - - if ( has_focus() ) { + if (has_focus()) { allocation = get_allocation(); - context->render_focus(cr, - 0 + 1, 0 + 1, - allocation.get_width() - 2, allocation.get_height() - 2 ); + context->render_focus(cr, 0 + 1, 0 + 1, allocation.get_width() - 2, allocation.get_height() - 2); } return false; } - -bool -Preview::on_enter_notify_event(GdkEventCrossing* event ) +bool Preview::on_enter_notify_event(GdkEventCrossing *event) { _within = true; set_state_flags(_hot ? Gtk::STATE_FLAG_ACTIVE : Gtk::STATE_FLAG_PRELIGHT, false); @@ -353,8 +304,7 @@ Preview::on_enter_notify_event(GdkEventCrossing* event ) return false; } -bool -Preview::on_leave_notify_event(GdkEventCrossing* event) +bool Preview::on_leave_notify_event(GdkEventCrossing *event) { _within = false; set_state_flags(Gtk::STATE_FLAG_NORMAL, false); @@ -362,21 +312,16 @@ Preview::on_leave_notify_event(GdkEventCrossing* event) return false; } -bool -Preview::on_button_press_event(GdkEventButton *event) +bool Preview::on_button_press_event(GdkEventButton *event) { - if (_takesFocus && !has_focus() ) - { + if (_takesFocus && !has_focus()) { grab_focus(); } - if ( event->button == PRIME_BUTTON_MAGIC_NUMBER || - event->button == 2 ) - { + if (event->button == PRIME_BUTTON_MAGIC_NUMBER || event->button == 2) { _hot = true; - if ( _within ) - { + if (_within) { set_state_flags(Gtk::STATE_FLAG_ACTIVE, false); } } @@ -384,25 +329,17 @@ Preview::on_button_press_event(GdkEventButton *event) return false; } -bool -Preview::on_button_release_event(GdkEventButton* event) +bool Preview::on_button_release_event(GdkEventButton *event) { _hot = false; set_state_flags(Gtk::STATE_FLAG_NORMAL, false); - if (_within && - (event->button == PRIME_BUTTON_MAGIC_NUMBER || - event->button == 2)) - { - gboolean isAlt = ( ((event->state & GDK_SHIFT_MASK) == GDK_SHIFT_MASK) || - (event->button == 2)); + if (_within && (event->button == PRIME_BUTTON_MAGIC_NUMBER || event->button == 2)) { + gboolean isAlt = (((event->state & GDK_SHIFT_MASK) == GDK_SHIFT_MASK) || (event->button == 2)); - if ( isAlt ) - { + if (isAlt) { _signal_alt_clicked(2); - } - else - { + } else { _signal_clicked.emit(); } } @@ -410,80 +347,66 @@ Preview::on_button_release_event(GdkEventButton* event) return false; } -void -Preview::set_linked(LinkType link) +void Preview::set_linked(LinkType link) { link = (LinkType)(link & PREVIEW_LINK_ALL); - if (link != _linked) - { + if (link != _linked) { _linked = link; queue_draw(); } } -LinkType -Preview::get_linked() const +LinkType Preview::get_linked() const { return (LinkType)_linked; } -void -Preview::set_details(ViewType view, - PreviewSize size, - guint ratio, - guint border) +void Preview::set_details(ViewType view, PreviewSize size, guint ratio, guint border) { - _view = view; + _view = view; - if ( size > PREVIEW_SIZE_LAST ) - { + if (size > PREVIEW_SIZE_LAST) { size = PREVIEW_SIZE_LAST; } _size = size; - if ( ratio > PREVIEW_MAX_RATIO ) - { + if (ratio > PREVIEW_MAX_RATIO) { ratio = PREVIEW_MAX_RATIO; } - _ratio = ratio; + _ratio = ratio; _border = border; queue_draw(); } Preview::Preview() - : _r(0x80), - _g(0x80), - _b(0xcc), - _scaledW(0), - _scaledH(0), - _hot(false), - _within(false), - _takesFocus(false), - _view(VIEW_TYPE_LIST), - _size(PREVIEW_SIZE_SMALL), - _ratio(100), - _border(BORDER_NONE), - _previewPixbuf(nullptr), - _scaled(nullptr), - _linked(PREVIEW_LINK_NONE) + : _r(0x80) + , _g(0x80) + , _b(0xcc) + , _scaledW(0) + , _scaledH(0) + , _hot(false) + , _within(false) + , _takesFocus(false) + , _view(VIEW_TYPE_LIST) + , _size(PREVIEW_SIZE_SMALL) + , _ratio(100) + , _border(BORDER_NONE) + , _previewPixbuf(nullptr) + , _scaled(nullptr) + , _linked(PREVIEW_LINK_NONE) { set_can_focus(true); set_receives_default(true); set_sensitive(true); - add_events(Gdk::BUTTON_PRESS_MASK - |Gdk::BUTTON_RELEASE_MASK - |Gdk::KEY_PRESS_MASK - |Gdk::KEY_RELEASE_MASK - |Gdk::FOCUS_CHANGE_MASK - |Gdk::ENTER_NOTIFY_MASK - |Gdk::LEAVE_NOTIFY_MASK ); + add_events(Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK | Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK | + Gdk::FOCUS_CHANGE_MASK | Gdk::ENTER_NOTIFY_MASK | Gdk::LEAVE_NOTIFY_MASK); } } // namespace Widget diff --git a/src/ui/widget/preview.h b/src/ui/widget/preview.h index b455367a96eb11c47944b9fba58eb10232eab8db..2c1b678b18fbd44b9ee7f7b7c8a13c35a02d826c 100644 --- a/src/ui/widget/preview.h +++ b/src/ui/widget/preview.h @@ -49,7 +49,8 @@ namespace Inkscape { namespace UI { namespace Widget { -enum PreviewStyle { +enum PreviewStyle +{ PREVIEW_STYLE_ICON = 0, PREVIEW_STYLE_PREVIEW, PREVIEW_STYLE_NAME, @@ -60,12 +61,14 @@ enum PreviewStyle { PREVIEW_STYLE_PREVIEW_BLURB }; -enum ViewType { +enum ViewType +{ VIEW_TYPE_LIST = 0, VIEW_TYPE_GRID }; -enum PreviewSize { +enum PreviewSize +{ PREVIEW_SIZE_TINY = 0, PREVIEW_SIZE_SMALL, PREVIEW_SIZE_MEDIUM, @@ -74,40 +77,43 @@ enum PreviewSize { PREVIEW_SIZE_HUGE }; -enum LinkType { - PREVIEW_LINK_NONE = 0, - PREVIEW_LINK_IN = 1, - PREVIEW_LINK_OUT = 2, - PREVIEW_LINK_OTHER = 4, - PREVIEW_FILL = 8, - PREVIEW_STROKE = 16, - PREVIEW_LINK_ALL = 31 +enum LinkType +{ + PREVIEW_LINK_NONE = 0, + PREVIEW_LINK_IN = 1, + PREVIEW_LINK_OUT = 2, + PREVIEW_LINK_OTHER = 4, + PREVIEW_FILL = 8, + PREVIEW_STROKE = 16, + PREVIEW_LINK_ALL = 31 }; -enum BorderStyle { +enum BorderStyle +{ BORDER_NONE = 0, BORDER_SOLID, BORDER_WIDE, BORDER_SOLID_LAST_ROW, }; -class Preview : public Gtk::DrawingArea { +class Preview : public Gtk::DrawingArea +{ private: - int _scaledW; - int _scaledH; - - int _r; - int _g; - int _b; - - bool _hot; - bool _within; - bool _takesFocus; ///< flag to grab focus when clicked - ViewType _view; - PreviewSize _size; - unsigned int _ratio; - LinkType _linked; - unsigned int _border; + int _scaledW; + int _scaledH; + + int _r; + int _g; + int _b; + + bool _hot; + bool _within; + bool _takesFocus; ///< flag to grab focus when clicked + ViewType _view; + PreviewSize _size; + unsigned int _ratio; + LinkType _linked; + unsigned int _border; Glib::RefPtr<Gdk::Pixbuf> _previewPixbuf; Glib::RefPtr<Gdk::Pixbuf> _scaled; @@ -124,25 +130,22 @@ protected: bool on_draw(const Cairo::RefPtr<Cairo::Context> &cr) override; bool on_button_press_event(GdkEventButton *button_event) override; bool on_button_release_event(GdkEventButton *button_event) override; - bool on_enter_notify_event(GdkEventCrossing* event ) override; - bool on_leave_notify_event(GdkEventCrossing* event ) override; + bool on_enter_notify_event(GdkEventCrossing *event) override; + bool on_leave_notify_event(GdkEventCrossing *event) override; public: Preview(); - bool get_focus_on_click() const {return _takesFocus;} - void set_focus_on_click(bool focus_on_click) {_takesFocus = focus_on_click;} + bool get_focus_on_click() const { return _takesFocus; } + void set_focus_on_click(bool focus_on_click) { _takesFocus = focus_on_click; } LinkType get_linked() const; void set_linked(LinkType link); - void set_details(ViewType view, - PreviewSize size, - guint ratio, - guint border); + void set_details(ViewType view, PreviewSize size, guint ratio, guint border); void set_color(int r, int g, int b); void set_pixbuf(const Glib::RefPtr<Gdk::Pixbuf> &pixbuf); - static void set_size_mappings(guint count, GtkIconSize const* sizes); + static void set_size_mappings(guint count, GtkIconSize const *sizes); - decltype(_signal_clicked) signal_clicked() {return _signal_clicked;} - decltype(_signal_alt_clicked) signal_alt_clicked() {return _signal_alt_clicked;} + decltype(_signal_clicked) signal_clicked() { return _signal_clicked; } + decltype(_signal_alt_clicked) signal_alt_clicked() { return _signal_alt_clicked; } }; } // namespace Widget diff --git a/src/ui/widget/random.cpp b/src/ui/widget/random.cpp index 495a778a311460d91d84975c8f94548fa5b065c5..ca1b8b868c45ed922f6d0d3b3ccac441639d8213 100644 --- a/src/ui/widget/random.cpp +++ b/src/ui/widget/random.cpp @@ -11,43 +11,35 @@ */ #include "random.h" -#include "ui/icon-loader.h" -#include <glibmm/i18n.h> +#include <glibmm/i18n.h> #include <gtkmm/button.h> #include <gtkmm/image.h> +#include "ui/icon-loader.h" + namespace Inkscape { namespace UI { namespace Widget { -Random::Random(Glib::ustring const &label, Glib::ustring const &tooltip, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) +Random::Random(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix, + Glib::ustring const &icon, bool mnemonic) : Scalar(label, tooltip, suffix, icon, mnemonic) { startseed = 0; addReseedButton(); } -Random::Random(Glib::ustring const &label, Glib::ustring const &tooltip, - unsigned digits, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) +Random::Random(Glib::ustring const &label, Glib::ustring const &tooltip, unsigned digits, Glib::ustring const &suffix, + Glib::ustring const &icon, bool mnemonic) : Scalar(label, tooltip, digits, suffix, icon, mnemonic) { startseed = 0; addReseedButton(); } -Random::Random(Glib::ustring const &label, Glib::ustring const &tooltip, - Glib::RefPtr<Gtk::Adjustment> &adjust, - unsigned digits, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) +Random::Random(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::RefPtr<Gtk::Adjustment> &adjust, + unsigned digits, Glib::ustring const &suffix, Glib::ustring const &icon, bool mnemonic) : Scalar(label, tooltip, adjust, digits, suffix, icon, mnemonic) { startseed = 0; @@ -67,19 +59,19 @@ void Random::setStartSeed(long newseed) void Random::addReseedButton() { Gtk::Image *pIcon = Gtk::manage(sp_get_icon_image("randomize", Gtk::ICON_SIZE_BUTTON)); - Gtk::Button * pButton = Gtk::manage(new Gtk::Button()); + 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, &Random::onReseedButtonClick)); - pButton->set_tooltip_text(_("Reseed the random number generator; this creates a different sequence of random numbers.")); + pButton->set_tooltip_text( + _("Reseed the random number generator; this creates a different sequence of random numbers.")); pack_start(*pButton, Gtk::PACK_SHRINK, 0); } -void -Random::onReseedButtonClick() +void Random::onReseedButtonClick() { startseed = g_random_int(); signal_reseeded.emit(); diff --git a/src/ui/widget/random.h b/src/ui/widget/random.h index 2648cb2e22b229c58bbbbb23c8c19575b76a23c1..b510ecb4c18b5b41ad0e8e23cd92e875a9865a1e 100644 --- a/src/ui/widget/random.h +++ b/src/ui/widget/random.h @@ -21,13 +21,12 @@ namespace Widget { * A labelled text box, with spin buttons and optional * icon or suffix, for entering arbitrary number values. It adds an extra * number called "startseed", that is not UI edittable, but should be put in SVG. - * This does NOT generate a random number, but provides merely the saving of + * This does NOT generate a random number, but provides merely the saving of * the startseed value. */ class Random : public Scalar { public: - /** * Construct a Random scalar Widget. * @@ -38,11 +37,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to false). */ - Random(Glib::ustring const &label, - Glib::ustring const &tooltip, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Random(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix = "", + Glib::ustring const &icon = "", bool mnemonic = true); /** * Construct a Random Scalar Widget. @@ -55,12 +51,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to false). */ - Random(Glib::ustring const &label, - Glib::ustring const &tooltip, - unsigned digits, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Random(Glib::ustring const &label, Glib::ustring const &tooltip, unsigned digits, Glib::ustring const &suffix = "", + Glib::ustring const &icon = "", bool mnemonic = true); /** * Construct a Random Scalar Widget. @@ -74,13 +66,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to true). */ - Random(Glib::ustring const &label, - Glib::ustring const &tooltip, - Glib::RefPtr<Gtk::Adjustment> &adjust, - unsigned digits = 0, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Random(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::RefPtr<Gtk::Adjustment> &adjust, + unsigned digits = 0, Glib::ustring const &suffix = "", Glib::ustring const &icon = "", bool mnemonic = true); /** * Gets the startseed. @@ -92,13 +79,12 @@ public: */ void setStartSeed(long newseed); - sigc::signal <void> signal_reseeded; + sigc::signal<void> signal_reseeded; protected: long startseed; private: - /** * Add reseed button to the widget. */ diff --git a/src/ui/widget/registered-enums.h b/src/ui/widget/registered-enums.h index b0cc199510819e9e691ed4f6d7fc54db4831a389..994828a7460744aa674889861712d9351a7c390d 100644 --- a/src/ui/widget/registered-enums.h +++ b/src/ui/widget/registered-enums.h @@ -21,69 +21,57 @@ namespace Widget { /** * Simplified management of enumerations in the UI as combobox. */ -template<typename E> class RegisteredEnum : public RegisteredWidget< LabelledComboBoxEnum<E> > +template <typename E> +class RegisteredEnum : public RegisteredWidget<LabelledComboBoxEnum<E>> { public: - ~RegisteredEnum() override { - _changed_connection.disconnect(); - } + ~RegisteredEnum() override { _changed_connection.disconnect(); } - RegisteredEnum ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - const Util::EnumDataConverter<E>& c, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr, - bool sorted = true ) - : RegisteredWidget< LabelledComboBoxEnum<E> >(label, tip, c, (const Glib::ustring &)"", (const Glib::ustring &)"", true, sorted) + RegisteredEnum(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + const Util::EnumDataConverter<E> &c, Registry &wr, Inkscape::XML::Node *repr_in = nullptr, + SPDocument *doc_in = nullptr, bool sorted = true) + : RegisteredWidget<LabelledComboBoxEnum<E>>(label, tip, c, (const Glib::ustring &)"", (const Glib::ustring &)"", + true, sorted) { - RegisteredWidget< LabelledComboBoxEnum<E> >::init_parent(key, wr, repr_in, doc_in); - _changed_connection = combobox()->signal_changed().connect (sigc::mem_fun (*this, &RegisteredEnum::on_changed)); + RegisteredWidget<LabelledComboBoxEnum<E>>::init_parent(key, wr, repr_in, doc_in); + _changed_connection = combobox()->signal_changed().connect(sigc::mem_fun(*this, &RegisteredEnum::on_changed)); } - void set_active_by_id (E id) { - combobox()->set_active_by_id(id); - }; + void set_active_by_id(E id) { combobox()->set_active_by_id(id); }; - void set_active_by_key (const Glib::ustring& key) { - combobox()->set_active_by_key(key); - } + void set_active_by_key(const Glib::ustring &key) { combobox()->set_active_by_key(key); } - inline const Util::EnumData<E>* get_active_data() { - combobox()->get_active_data(); - } + inline const Util::EnumData<E> *get_active_data() { combobox()->get_active_data(); } - ComboBoxEnum<E> * combobox() { - return LabelledComboBoxEnum<E>::getCombobox(); - } + ComboBoxEnum<E> *combobox() { return LabelledComboBoxEnum<E>::getCombobox(); } sigc::connection _changed_connection; protected: - void on_changed() { + void on_changed() + { if (combobox()->setProgrammatically) { combobox()->setProgrammatically = false; return; } - if (RegisteredWidget< LabelledComboBoxEnum<E> >::_wr->isUpdating()) + if (RegisteredWidget<LabelledComboBoxEnum<E>>::_wr->isUpdating()) return; - RegisteredWidget< LabelledComboBoxEnum<E> >::_wr->setUpdating (true); + RegisteredWidget<LabelledComboBoxEnum<E>>::_wr->setUpdating(true); - const Util::EnumData<E>* data = combobox()->get_active_data(); + const Util::EnumData<E> *data = combobox()->get_active_data(); if (data) { - RegisteredWidget< LabelledComboBoxEnum<E> >::write_to_xml(data->key.c_str()); + RegisteredWidget<LabelledComboBoxEnum<E>>::write_to_xml(data->key.c_str()); } - RegisteredWidget< LabelledComboBoxEnum<E> >::_wr->setUpdating (false); + RegisteredWidget<LabelledComboBoxEnum<E>>::_wr->setUpdating(false); } }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif diff --git a/src/ui/widget/registered-widget.cpp b/src/ui/widget/registered-widget.cpp index 10920805f6b0aacc673a968c1089c277753f6418..1eba456069f418de186d280a80adabe75c25f233 100644 --- a/src/ui/widget/registered-widget.cpp +++ b/src/ui/widget/registered-widget.cpp @@ -18,12 +18,10 @@ #include <gtkmm/radiobutton.h> -#include "verbs.h" - #include "object/sp-root.h" - -#include "svg/svg-color.h" #include "svg/stringstream.h" +#include "svg/svg-color.h" +#include "verbs.h" namespace Inkscape { namespace UI { @@ -38,7 +36,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, char const *active_str, char const *inactive_str) +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) @@ -47,33 +48,33 @@ RegisteredCheckButton::RegisteredCheckButton (const Glib::ustring& label, const setProgrammatically = false; - set_tooltip_text (tip); + set_tooltip_text(tip); Gtk::Label *l = new Gtk::Label(); l->set_markup(label); - l->set_use_underline (true); - add (*manage (l)); + l->set_use_underline(true); + add(*manage(l)); - if(right) set_halign(Gtk::ALIGN_END); - else set_halign(Gtk::ALIGN_START); + if (right) + set_halign(Gtk::ALIGN_END); + else + set_halign(Gtk::ALIGN_START); set_valign(Gtk::ALIGN_CENTER); - _toggled_connection = signal_toggled().connect (sigc::mem_fun (*this, &RegisteredCheckButton::on_toggled)); + _toggled_connection = signal_toggled().connect(sigc::mem_fun(*this, &RegisteredCheckButton::on_toggled)); } -void -RegisteredCheckButton::setActive (bool b) +void RegisteredCheckButton::setActive(bool b) { setProgrammatically = true; - set_active (b); - //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) { + set_active(b); + // 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(b); } setProgrammatically = false; } -void -RegisteredCheckButton::on_toggled() +void RegisteredCheckButton::on_toggled() { if (setProgrammatically) { setProgrammatically = false; @@ -82,15 +83,15 @@ RegisteredCheckButton::on_toggled() if (_wr->isUpdating()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); 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) { + // 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()); } - _wr->setUpdating (false); + _wr->setUpdating(false); } /*######################################### @@ -102,34 +103,37 @@ RegisteredToggleButton::~RegisteredToggleButton() _toggled_connection.disconnect(); } -RegisteredToggleButton::RegisteredToggleButton (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 *icon_active, char const *icon_inactive) +RegisteredToggleButton::RegisteredToggleButton(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 *icon_active, char const *icon_inactive) : RegisteredWidget<Gtk::ToggleButton>() { init_parent(key, wr, repr_in, doc_in); setProgrammatically = false; - set_tooltip_text (tip); + set_tooltip_text(tip); - if(right) set_halign(Gtk::ALIGN_END); - else set_halign(Gtk::ALIGN_START); + if (right) + set_halign(Gtk::ALIGN_END); + else + set_halign(Gtk::ALIGN_START); set_valign(Gtk::ALIGN_CENTER); - _toggled_connection = signal_toggled().connect (sigc::mem_fun (*this, &RegisteredToggleButton::on_toggled)); + _toggled_connection = signal_toggled().connect(sigc::mem_fun(*this, &RegisteredToggleButton::on_toggled)); } -void -RegisteredToggleButton::setActive (bool b) +void RegisteredToggleButton::setActive(bool b) { setProgrammatically = true; - set_active (b); - //The slave button is greyed out if the master button is untoggled - for (std::list<Gtk::Widget*>::const_iterator i = _slavewidgets.begin(); i != _slavewidgets.end(); ++i) { + set_active(b); + // The slave button is greyed out if the master button is untoggled + for (std::list<Gtk::Widget *>::const_iterator i = _slavewidgets.begin(); i != _slavewidgets.end(); ++i) { (*i)->set_sensitive(b); } setProgrammatically = false; } -void -RegisteredToggleButton::on_toggled() +void RegisteredToggleButton::on_toggled() { if (setProgrammatically) { setProgrammatically = false; @@ -138,15 +142,15 @@ RegisteredToggleButton::on_toggled() if (_wr->isUpdating()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); write_to_xml(get_active() ? "true" : "false"); - //The slave button is greyed out if the master button is untoggled - for (std::list<Gtk::Widget*>::const_iterator i = _slavewidgets.begin(); i != _slavewidgets.end(); ++i) { + // The slave button is greyed out if the master button is untoggled + for (std::list<Gtk::Widget *>::const_iterator i = _slavewidgets.begin(); i != _slavewidgets.end(); ++i) { (*i)->set_sensitive(get_active()); } - _wr->setUpdating (false); + _wr->setUpdating(false); } /*######################################### @@ -158,23 +162,23 @@ RegisteredUnitMenu::~RegisteredUnitMenu() _changed_connection.disconnect(); } -RegisteredUnitMenu::RegisteredUnitMenu (const Glib::ustring& label, const Glib::ustring& key, Registry& wr, Inkscape::XML::Node* repr_in, SPDocument *doc_in) - : RegisteredWidget<Labelled> (label, "" /*tooltip*/, new UnitMenu()) +RegisteredUnitMenu::RegisteredUnitMenu(const Glib::ustring &label, const Glib::ustring &key, Registry &wr, + Inkscape::XML::Node *repr_in, SPDocument *doc_in) + : RegisteredWidget<Labelled>(label, "" /*tooltip*/, new UnitMenu()) { init_parent(key, wr, repr_in, doc_in); - getUnitMenu()->setUnitType (UNIT_TYPE_LINEAR); - _changed_connection = getUnitMenu()->signal_changed().connect (sigc::mem_fun (*this, &RegisteredUnitMenu::on_changed)); + getUnitMenu()->setUnitType(UNIT_TYPE_LINEAR); + _changed_connection = + getUnitMenu()->signal_changed().connect(sigc::mem_fun(*this, &RegisteredUnitMenu::on_changed)); } -void -RegisteredUnitMenu::setUnit (Glib::ustring unit) +void RegisteredUnitMenu::setUnit(Glib::ustring unit) { getUnitMenu()->setUnit(unit); } -void -RegisteredUnitMenu::on_changed() +void RegisteredUnitMenu::on_changed() { if (_wr->isUpdating()) return; @@ -182,14 +186,13 @@ RegisteredUnitMenu::on_changed() Inkscape::SVGOStringStream os; os << getUnitMenu()->getUnitAbbr(); - _wr->setUpdating (true); + _wr->setUpdating(true); write_to_xml(os.str().c_str()); - _wr->setUpdating (false); + _wr->setUpdating(false); } - /*######################################### * Registered SCALARUNIT */ @@ -199,25 +202,26 @@ RegisteredScalarUnit::~RegisteredScalarUnit() _value_changed_connection.disconnect(); } -RegisteredScalarUnit::RegisteredScalarUnit (const Glib::ustring& label, const Glib::ustring& tip, const Glib::ustring& key, const RegisteredUnitMenu &rum, Registry& wr, Inkscape::XML::Node* repr_in, SPDocument *doc_in, RSU_UserUnits user_units) - : RegisteredWidget<ScalarUnit>(label, tip, UNIT_TYPE_LINEAR, "", "", rum.getUnitMenu()), - _um(nullptr) +RegisteredScalarUnit::RegisteredScalarUnit(const Glib::ustring &label, const Glib::ustring &tip, + const Glib::ustring &key, const RegisteredUnitMenu &rum, Registry &wr, + Inkscape::XML::Node *repr_in, SPDocument *doc_in, RSU_UserUnits user_units) + : RegisteredWidget<ScalarUnit>(label, tip, UNIT_TYPE_LINEAR, "", "", rum.getUnitMenu()) + , _um(nullptr) { init_parent(key, wr, repr_in, doc_in); setProgrammatically = false; - initScalar (-1e6, 1e6); - setUnit (rum.getUnitMenu()->getUnitAbbr()); - setDigits (2); + initScalar(-1e6, 1e6); + setUnit(rum.getUnitMenu()->getUnitAbbr()); + setDigits(2); _um = rum.getUnitMenu(); _user_units = user_units; - _value_changed_connection = signal_value_changed().connect (sigc::mem_fun (*this, &RegisteredScalarUnit::on_value_changed)); + _value_changed_connection = + signal_value_changed().connect(sigc::mem_fun(*this, &RegisteredScalarUnit::on_value_changed)); } - -void -RegisteredScalarUnit::on_value_changed() +void RegisteredScalarUnit::on_value_changed() { if (setProgrammatically) { setProgrammatically = false; @@ -227,7 +231,7 @@ RegisteredScalarUnit::on_value_changed() if (_wr->isUpdating()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); Inkscape::SVGOStringStream os; if (_user_units != RSU_none) { @@ -237,9 +241,13 @@ RegisteredScalarUnit::on_value_changed() SPRoot *root = doc->getRoot(); if (root->viewBox_set) { // check to see if scaling is uniform - if(Geom::are_near((root->viewBox.width() * root->height.computed) / (root->width.computed * root->viewBox.height()), 1.0, Geom::EPSILON)) { - scale = (root->viewBox.width() / root->width.computed + root->viewBox.height() / root->height.computed)/2.0; - } else if (_user_units == RSU_x) { + if (Geom::are_near((root->viewBox.width() * root->height.computed) / + (root->width.computed * root->viewBox.height()), + 1.0, Geom::EPSILON)) { + scale = (root->viewBox.width() / root->width.computed + + root->viewBox.height() / root->height.computed) / + 2.0; + } else if (_user_units == RSU_x) { scale = root->viewBox.width() / root->width.computed; } else { scale = root->viewBox.height() / root->height.computed; @@ -255,10 +263,9 @@ RegisteredScalarUnit::on_value_changed() } write_to_xml(os.str().c_str()); - _wr->setUpdating (false); + _wr->setUpdating(false); } - /*######################################### * Registered SCALAR */ @@ -268,22 +275,21 @@ RegisteredScalar::~RegisteredScalar() _value_changed_connection.disconnect(); } -RegisteredScalar::RegisteredScalar ( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Registry& wr, Inkscape::XML::Node* repr_in, - SPDocument * doc_in ) +RegisteredScalar::RegisteredScalar(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Registry &wr, Inkscape::XML::Node *repr_in, SPDocument *doc_in) : RegisteredWidget<Scalar>(label, tip) { init_parent(key, wr, repr_in, doc_in); setProgrammatically = false; - setRange (-1e6, 1e6); - setDigits (2); + setRange(-1e6, 1e6); + setDigits(2); setIncrements(0.1, 1.0); - _value_changed_connection = signal_value_changed().connect (sigc::mem_fun (*this, &RegisteredScalar::on_value_changed)); + _value_changed_connection = + signal_value_changed().connect(sigc::mem_fun(*this, &RegisteredScalar::on_value_changed)); } -void -RegisteredScalar::on_value_changed() +void RegisteredScalar::on_value_changed() { if (setProgrammatically) { setProgrammatically = false; @@ -292,21 +298,20 @@ RegisteredScalar::on_value_changed() if (_wr->isUpdating()) { return; } - _wr->setUpdating (true); + _wr->setUpdating(true); Inkscape::SVGOStringStream os; - //Force exact 0 if decimals over to 6 - double val = getValue() < 1e-6 && getValue() > -1e-6?0.0:getValue(); + // Force exact 0 if decimals over to 6 + double val = getValue() < 1e-6 && getValue() > -1e-6 ? 0.0 : getValue(); os << val; - //TODO: Test is ok remove this sensitives - //also removed in registered text and in registered random - //set_sensitive(false); + // TODO: Test is ok remove this sensitives + // also removed in registered text and in registered random + // set_sensitive(false); write_to_xml(os.str().c_str()); - //set_sensitive(true); - _wr->setUpdating (false); + // set_sensitive(true); + _wr->setUpdating(false); } - /*######################################### * Registered TEXT */ @@ -316,19 +321,17 @@ RegisteredText::~RegisteredText() _activate_connection.disconnect(); } -RegisteredText::RegisteredText ( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Registry& wr, Inkscape::XML::Node* repr_in, - SPDocument * doc_in ) +RegisteredText::RegisteredText(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Registry &wr, Inkscape::XML::Node *repr_in, SPDocument *doc_in) : RegisteredWidget<Text>(label, tip) { init_parent(key, wr, repr_in, doc_in); setProgrammatically = false; - _activate_connection = signal_activate().connect (sigc::mem_fun (*this, &RegisteredText::on_activate)); + _activate_connection = signal_activate().connect(sigc::mem_fun(*this, &RegisteredText::on_activate)); } -void -RegisteredText::on_activate() +void RegisteredText::on_activate() { if (setProgrammatically) { setProgrammatically = false; @@ -338,34 +341,29 @@ RegisteredText::on_activate() if (_wr->isUpdating()) { return; } - _wr->setUpdating (true); + _wr->setUpdating(true); Glib::ustring str(getText()); Inkscape::SVGOStringStream os; os << str; write_to_xml(os.str().c_str()); - _wr->setUpdating (false); + _wr->setUpdating(false); } - /*######################################### * Registered COLORPICKER */ -RegisteredColorPicker::RegisteredColorPicker(const Glib::ustring& label, - const Glib::ustring& title, - const Glib::ustring& tip, - const Glib::ustring& ckey, - const Glib::ustring& akey, - Registry& wr, - Inkscape::XML::Node* repr_in, +RegisteredColorPicker::RegisteredColorPicker(const Glib::ustring &label, const Glib::ustring &title, + const Glib::ustring &tip, const Glib::ustring &ckey, + const Glib::ustring &akey, Registry &wr, Inkscape::XML::Node *repr_in, SPDocument *doc_in) - : RegisteredWidget<LabelledColorPicker> (label, title, tip, 0, true) + : RegisteredWidget<LabelledColorPicker>(label, title, tip, 0, true) { init_parent("", wr, repr_in, doc_in); _ckey = ckey; _akey = akey; - _changed_connection = connectChanged (sigc::mem_fun (*this, &RegisteredColorPicker::on_changed)); + _changed_connection = connectChanged(sigc::mem_fun(*this, &RegisteredColorPicker::on_changed)); } RegisteredColorPicker::~RegisteredColorPicker() @@ -373,25 +371,22 @@ RegisteredColorPicker::~RegisteredColorPicker() _changed_connection.disconnect(); } -void -RegisteredColorPicker::setRgba32 (guint32 rgba) +void RegisteredColorPicker::setRgba32(guint32 rgba) { - LabelledColorPicker::setRgba32 (rgba); + LabelledColorPicker::setRgba32(rgba); } -void -RegisteredColorPicker::closeWindow() +void RegisteredColorPicker::closeWindow() { LabelledColorPicker::closeWindow(); } -void -RegisteredColorPicker::on_changed (guint32 rgba) +void RegisteredColorPicker::on_changed(guint32 rgba) { if (_wr->isUpdating()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); // Use local repr here. When repr is specified, use that one, but // if repr==NULL, get the repr of namedview of active desktop. @@ -407,7 +402,7 @@ RegisteredColorPicker::on_changed (guint32 rgba) local_doc = dt->getDocument(); } gchar c[32]; - if (_akey == _ckey + "_opacity_LPE") { //For LPE parameter we want stored with alpha + if (_akey == _ckey + "_opacity_LPE") { // For LPE parameter we want stored with alpha sprintf(c, "#%08x", rgba); } else { sp_svg_write_color(c, sizeof(c), rgba); @@ -422,10 +417,9 @@ RegisteredColorPicker::on_changed (guint32 rgba) DocumentUndo::done(local_doc, SP_VERB_NONE, /* TODO: annotate */ "registered-widget.cpp: RegisteredColorPicker::on_changed"); - _wr->setUpdating (false); + _wr->setUpdating(false); } - /*######################################### * Registered SUFFIXEDINTEGER */ @@ -435,21 +429,23 @@ RegisteredSuffixedInteger::~RegisteredSuffixedInteger() _changed_connection.disconnect(); } -RegisteredSuffixedInteger::RegisteredSuffixedInteger (const Glib::ustring& label, const Glib::ustring& tip, const Glib::ustring& suffix, const Glib::ustring& key, Registry& wr, Inkscape::XML::Node* repr_in, SPDocument *doc_in) - : RegisteredWidget<Scalar>(label, tip, 0, suffix), - setProgrammatically(false) +RegisteredSuffixedInteger::RegisteredSuffixedInteger(const Glib::ustring &label, const Glib::ustring &tip, + const Glib::ustring &suffix, const Glib::ustring &key, + Registry &wr, Inkscape::XML::Node *repr_in, SPDocument *doc_in) + : RegisteredWidget<Scalar>(label, tip, 0, suffix) + , setProgrammatically(false) { init_parent(key, wr, repr_in, doc_in); - setRange (0, 1e6); - setDigits (0); + setRange(0, 1e6); + setDigits(0); setIncrements(1, 10); - _changed_connection = signal_value_changed().connect (sigc::mem_fun(*this, &RegisteredSuffixedInteger::on_value_changed)); + _changed_connection = + signal_value_changed().connect(sigc::mem_fun(*this, &RegisteredSuffixedInteger::on_value_changed)); } -void -RegisteredSuffixedInteger::on_value_changed() +void RegisteredSuffixedInteger::on_value_changed() { if (setProgrammatically) { setProgrammatically = false; @@ -459,17 +455,16 @@ RegisteredSuffixedInteger::on_value_changed() if (_wr->isUpdating()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); Inkscape::SVGOStringStream os; os << getValue(); write_to_xml(os.str().c_str()); - _wr->setUpdating (false); + _wr->setUpdating(false); } - /*######################################### * Registered RADIOBUTTONPAIR */ @@ -479,13 +474,13 @@ RegisteredRadioButtonPair::~RegisteredRadioButtonPair() _changed_connection.disconnect(); } -RegisteredRadioButtonPair::RegisteredRadioButtonPair (const Glib::ustring& label, - const Glib::ustring& label1, const Glib::ustring& label2, - const Glib::ustring& tip1, const Glib::ustring& tip2, - const Glib::ustring& key, Registry& wr, Inkscape::XML::Node* repr_in, SPDocument *doc_in) - : RegisteredWidget<Gtk::HBox>(), - _rb1(nullptr), - _rb2(nullptr) +RegisteredRadioButtonPair::RegisteredRadioButtonPair(const Glib::ustring &label, const Glib::ustring &label1, + const Glib::ustring &label2, const Glib::ustring &tip1, + const Glib::ustring &tip2, const Glib::ustring &key, Registry &wr, + Inkscape::XML::Node *repr_in, SPDocument *doc_in) + : RegisteredWidget<Gtk::HBox>() + , _rb1(nullptr) + , _rb2(nullptr) { init_parent(key, wr, repr_in, doc_in); @@ -493,18 +488,18 @@ RegisteredRadioButtonPair::RegisteredRadioButtonPair (const Glib::ustring& label add(*Gtk::manage(new Gtk::Label(label))); _rb1 = Gtk::manage(new Gtk::RadioButton(label1, true)); - add (*_rb1); + add(*_rb1); Gtk::RadioButtonGroup group = _rb1->get_group(); _rb2 = Gtk::manage(new Gtk::RadioButton(group, label2, true)); - add (*_rb2); + add(*_rb2); _rb2->set_active(); _rb1->set_tooltip_text(tip1); _rb2->set_tooltip_text(tip2); - _changed_connection = _rb1->signal_toggled().connect (sigc::mem_fun (*this, &RegisteredRadioButtonPair::on_value_changed)); + _changed_connection = + _rb1->signal_toggled().connect(sigc::mem_fun(*this, &RegisteredRadioButtonPair::on_value_changed)); } -void -RegisteredRadioButtonPair::setValue (bool second) +void RegisteredRadioButtonPair::setValue(bool second) { if (!_rb1 || !_rb2) return; @@ -517,8 +512,7 @@ RegisteredRadioButtonPair::setValue (bool second) } } -void -RegisteredRadioButtonPair::on_value_changed() +void RegisteredRadioButtonPair::on_value_changed() { if (setProgrammatically) { setProgrammatically = false; @@ -528,15 +522,14 @@ RegisteredRadioButtonPair::on_value_changed() if (_wr->isUpdating()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); bool second = _rb2->get_active(); write_to_xml(second ? "true" : "false"); - _wr->setUpdating (false); + _wr->setUpdating(false); } - /*######################################### * Registered POINT */ @@ -547,22 +540,22 @@ RegisteredPoint::~RegisteredPoint() _value_y_changed_connection.disconnect(); } -RegisteredPoint::RegisteredPoint ( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Registry& wr, Inkscape::XML::Node* repr_in, - SPDocument* doc_in ) - : RegisteredWidget<Point> (label, tip) +RegisteredPoint::RegisteredPoint(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Registry &wr, Inkscape::XML::Node *repr_in, SPDocument *doc_in) + : RegisteredWidget<Point>(label, tip) { init_parent(key, wr, repr_in, doc_in); - setRange (-1e6, 1e6); - setDigits (2); + setRange(-1e6, 1e6); + setDigits(2); setIncrements(0.1, 1.0); - _value_x_changed_connection = signal_x_value_changed().connect (sigc::mem_fun (*this, &RegisteredPoint::on_value_changed)); - _value_y_changed_connection = signal_y_value_changed().connect (sigc::mem_fun (*this, &RegisteredPoint::on_value_changed)); + _value_x_changed_connection = + signal_x_value_changed().connect(sigc::mem_fun(*this, &RegisteredPoint::on_value_changed)); + _value_y_changed_connection = + signal_y_value_changed().connect(sigc::mem_fun(*this, &RegisteredPoint::on_value_changed)); } -void -RegisteredPoint::on_value_changed() +void RegisteredPoint::on_value_changed() { if (setProgrammatically()) { clearProgrammatically(); @@ -572,14 +565,14 @@ RegisteredPoint::on_value_changed() if (_wr->isUpdating()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); Inkscape::SVGOStringStream os; os << getXValue() << "," << getYValue(); write_to_xml(os.str().c_str()); - _wr->setUpdating (false); + _wr->setUpdating(false); } /*######################################### @@ -592,33 +585,33 @@ RegisteredTransformedPoint::~RegisteredTransformedPoint() _value_y_changed_connection.disconnect(); } -RegisteredTransformedPoint::RegisteredTransformedPoint ( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Registry& wr, Inkscape::XML::Node* repr_in, - SPDocument* doc_in ) - : RegisteredWidget<Point> (label, tip), - to_svg(Geom::identity()) +RegisteredTransformedPoint::RegisteredTransformedPoint(const Glib::ustring &label, const Glib::ustring &tip, + const Glib::ustring &key, Registry &wr, + Inkscape::XML::Node *repr_in, SPDocument *doc_in) + : RegisteredWidget<Point>(label, tip) + , to_svg(Geom::identity()) { init_parent(key, wr, repr_in, doc_in); - setRange (-1e6, 1e6); - setDigits (2); + setRange(-1e6, 1e6); + setDigits(2); setIncrements(0.1, 1.0); - _value_x_changed_connection = signal_x_value_changed().connect (sigc::mem_fun (*this, &RegisteredTransformedPoint::on_value_changed)); - _value_y_changed_connection = signal_y_value_changed().connect (sigc::mem_fun (*this, &RegisteredTransformedPoint::on_value_changed)); + _value_x_changed_connection = + signal_x_value_changed().connect(sigc::mem_fun(*this, &RegisteredTransformedPoint::on_value_changed)); + _value_y_changed_connection = + signal_y_value_changed().connect(sigc::mem_fun(*this, &RegisteredTransformedPoint::on_value_changed)); } -void -RegisteredTransformedPoint::setValue(Geom::Point const & p) +void RegisteredTransformedPoint::setValue(Geom::Point const &p) { Geom::Point new_p = p * to_svg.inverse(); - Point::setValue(new_p); // the Point widget should display things in canvas coordinates + Point::setValue(new_p); // the Point widget should display things in canvas coordinates } -void -RegisteredTransformedPoint::setTransform(Geom::Affine const & canvas_to_svg) +void RegisteredTransformedPoint::setTransform(Geom::Affine const &canvas_to_svg) { // check if matrix is singular / has inverse - if ( ! canvas_to_svg.isSingular() ) { + if (!canvas_to_svg.isSingular()) { to_svg = canvas_to_svg; } else { // set back to default @@ -626,8 +619,7 @@ RegisteredTransformedPoint::setTransform(Geom::Affine const & canvas_to_svg) } } -void -RegisteredTransformedPoint::on_value_changed() +void RegisteredTransformedPoint::on_value_changed() { if (setProgrammatically()) { clearProgrammatically(); @@ -637,7 +629,7 @@ RegisteredTransformedPoint::on_value_changed() if (_wr->isUpdating()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); Geom::Point pos = getValue() * to_svg; @@ -646,7 +638,7 @@ RegisteredTransformedPoint::on_value_changed() write_to_xml(os.str().c_str()); - _wr->setUpdating (false); + _wr->setUpdating(false); } /*######################################### @@ -659,36 +651,35 @@ RegisteredVector::~RegisteredVector() _value_y_changed_connection.disconnect(); } -RegisteredVector::RegisteredVector ( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Registry& wr, Inkscape::XML::Node* repr_in, - SPDocument* doc_in ) - : RegisteredWidget<Point> (label, tip), - _polar_coords(false) +RegisteredVector::RegisteredVector(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Registry &wr, Inkscape::XML::Node *repr_in, SPDocument *doc_in) + : RegisteredWidget<Point>(label, tip) + , _polar_coords(false) { init_parent(key, wr, repr_in, doc_in); - setRange (-1e6, 1e6); - setDigits (2); + setRange(-1e6, 1e6); + setDigits(2); setIncrements(0.1, 1.0); - _value_x_changed_connection = signal_x_value_changed().connect (sigc::mem_fun (*this, &RegisteredVector::on_value_changed)); - _value_y_changed_connection = signal_y_value_changed().connect (sigc::mem_fun (*this, &RegisteredVector::on_value_changed)); + _value_x_changed_connection = + signal_x_value_changed().connect(sigc::mem_fun(*this, &RegisteredVector::on_value_changed)); + _value_y_changed_connection = + signal_y_value_changed().connect(sigc::mem_fun(*this, &RegisteredVector::on_value_changed)); } -void -RegisteredVector::setValue(Geom::Point const & p) +void RegisteredVector::setValue(Geom::Point const &p) { if (!_polar_coords) { Point::setValue(p); } else { Geom::Point polar; - polar[Geom::X] = atan2(p) *180/M_PI; + polar[Geom::X] = atan2(p) * 180 / M_PI; polar[Geom::Y] = p.length(); Point::setValue(polar); } } -void -RegisteredVector::setValue(Geom::Point const & p, Geom::Point const & origin) +void RegisteredVector::setValue(Geom::Point const &p, Geom::Point const &origin) { RegisteredVector::setValue(p); _origin = origin; @@ -706,8 +697,7 @@ void RegisteredVector::setPolarCoords(bool polar_coords) } } -void -RegisteredVector::on_value_changed() +void RegisteredVector::on_value_changed() { if (setProgrammatically()) { clearProgrammatically(); @@ -717,12 +707,12 @@ RegisteredVector::on_value_changed() if (_wr->isUpdating()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); Geom::Point origin = _origin; Geom::Point vector = getValue(); if (_polar_coords) { - vector = Geom::Point::polar(vector[Geom::X]*M_PI/180, vector[Geom::Y]); + vector = Geom::Point::polar(vector[Geom::X] * M_PI / 180, vector[Geom::Y]); } Inkscape::SVGOStringStream os; @@ -730,7 +720,7 @@ RegisteredVector::on_value_changed() write_to_xml(os.str().c_str()); - _wr->setUpdating (false); + _wr->setUpdating(false); } /*######################################### @@ -743,30 +733,28 @@ RegisteredRandom::~RegisteredRandom() _reseeded_connection.disconnect(); } -RegisteredRandom::RegisteredRandom ( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Registry& wr, Inkscape::XML::Node* repr_in, - SPDocument * doc_in ) - : RegisteredWidget<Random> (label, tip) +RegisteredRandom::RegisteredRandom(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Registry &wr, Inkscape::XML::Node *repr_in, SPDocument *doc_in) + : RegisteredWidget<Random>(label, tip) { init_parent(key, wr, repr_in, doc_in); setProgrammatically = false; - setRange (-1e6, 1e6); - setDigits (2); + setRange(-1e6, 1e6); + setDigits(2); setIncrements(0.1, 1.0); - _value_changed_connection = signal_value_changed().connect (sigc::mem_fun (*this, &RegisteredRandom::on_value_changed)); + _value_changed_connection = + signal_value_changed().connect(sigc::mem_fun(*this, &RegisteredRandom::on_value_changed)); _reseeded_connection = signal_reseeded.connect(sigc::mem_fun(*this, &RegisteredRandom::on_value_changed)); } -void -RegisteredRandom::setValue (double val, long startseed) +void RegisteredRandom::setValue(double val, long startseed) { - Scalar::setValue (val); + Scalar::setValue(val); setStartSeed(startseed); } -void -RegisteredRandom::on_value_changed() +void RegisteredRandom::on_value_changed() { if (setProgrammatically) { setProgrammatically = false; @@ -776,14 +764,14 @@ RegisteredRandom::on_value_changed() if (_wr->isUpdating()) { return; } - _wr->setUpdating (true); + _wr->setUpdating(true); Inkscape::SVGOStringStream os; - //Force exact 0 if decimals over to 6 - double val = getValue() < 1e-6 && getValue() > -1e-6?0.0:getValue(); + // Force exact 0 if decimals over to 6 + double val = getValue() < 1e-6 && getValue() > -1e-6 ? 0.0 : getValue(); os << val << ';' << getStartSeed(); write_to_xml(os.str().c_str()); - _wr->setUpdating (false); + _wr->setUpdating(false); } /*######################################### @@ -795,39 +783,37 @@ RegisteredFontButton::~RegisteredFontButton() _signal_font_set.disconnect(); } -RegisteredFontButton::RegisteredFontButton ( const Glib::ustring& label, const Glib::ustring& tip, - const Glib::ustring& key, Registry& wr, Inkscape::XML::Node* repr_in, - SPDocument* doc_in ) +RegisteredFontButton::RegisteredFontButton(const Glib::ustring &label, const Glib::ustring &tip, + const Glib::ustring &key, Registry &wr, Inkscape::XML::Node *repr_in, + SPDocument *doc_in) : RegisteredWidget<FontButton>(label, tip) { init_parent(key, wr, repr_in, doc_in); - _signal_font_set = signal_font_value_changed().connect (sigc::mem_fun (*this, &RegisteredFontButton::on_value_changed)); + _signal_font_set = + signal_font_value_changed().connect(sigc::mem_fun(*this, &RegisteredFontButton::on_value_changed)); } -void -RegisteredFontButton::setValue (Glib::ustring fontspec) +void RegisteredFontButton::setValue(Glib::ustring fontspec) { FontButton::setValue(fontspec); } -void -RegisteredFontButton::on_value_changed() +void RegisteredFontButton::on_value_changed() { - if (_wr->isUpdating()) return; - _wr->setUpdating (true); + _wr->setUpdating(true); Inkscape::SVGOStringStream os; os << getValue(); write_to_xml(os.str().c_str()); - _wr->setUpdating (false); + _wr->setUpdating(false); } -} // namespace Dialog +} // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/registered-widget.h b/src/ui/widget/registered-widget.h index 1519ed76eaf3c2c1b5718badbefb4817539c1526..eb246d8548e5617be60dd83d5210462525bf21ba 100644 --- a/src/ui/widget/registered-widget.h +++ b/src/ui/widget/registered-widget.h @@ -14,33 +14,31 @@ #define INKSCAPE_UI_WIDGET_REGISTERED_WIDGET__H_ #include <2geom/affine.h> -#include "xml/node.h" -#include "registry.h" +#include <gtkmm/checkbutton.h> -#include "ui/widget/scalar.h" -#include "ui/widget/scalar-unit.h" +#include "desktop.h" +#include "document-undo.h" +#include "document.h" +#include "inkscape.h" +#include "object/sp-namedview.h" +#include "registry.h" +#include "ui/widget/color-picker.h" +#include "ui/widget/font-button.h" #include "ui/widget/point.h" -#include "ui/widget/text.h" #include "ui/widget/random.h" +#include "ui/widget/scalar-unit.h" +#include "ui/widget/scalar.h" +#include "ui/widget/text.h" #include "ui/widget/unit-menu.h" -#include "ui/widget/font-button.h" -#include "ui/widget/color-picker.h" -#include "inkscape.h" - -#include "document.h" -#include "document-undo.h" -#include "desktop.h" -#include "object/sp-namedview.h" - -#include <gtkmm/checkbutton.h> +#include "xml/node.h" class SPDocument; namespace Gtk { - class HScale; - class RadioButton; - class SpinButton; -} +class HScale; +class RadioButton; +class SpinButton; +} // namespace Gtk namespace Inkscape { namespace UI { @@ -49,7 +47,8 @@ namespace Widget { class Registry; template <class W> -class RegisteredWidget : public W { +class RegisteredWidget : public W +{ public: void set_undo_parameters(const unsigned int _event_type, Glib::ustring _event_description) { @@ -63,47 +62,90 @@ public: doc = document; } - bool is_updating() {if (_wr) return _wr->isUpdating(); else return false;} + bool is_updating() + { + if (_wr) + return _wr->isUpdating(); + else + return false; + } protected: - RegisteredWidget() : W() { construct(); } - template< typename A > - explicit RegisteredWidget( A& a ): W( a ) { construct(); } - template< typename A, typename B > - RegisteredWidget( A& a, B& b ): W( a, b ) { construct(); } - template< typename A, typename B, typename C > - RegisteredWidget( A& a, B& b, C* c ): W( a, b, c ) { construct(); } - template< typename A, typename B, typename C > - RegisteredWidget( A& a, B& b, C& c ): W( a, b, c ) { construct(); } - template< typename A, typename B, typename C, typename D > - RegisteredWidget( A& a, B& b, C c, D d ): W( a, b, c, d ) { construct(); } - template< typename A, typename B, typename C, typename D, typename E > - RegisteredWidget( A& a, B& b, C& c, D d, E e ): W( a, b, c, d, e ) { construct(); } - template< typename A, typename B, typename C, typename D, typename E , typename F> - RegisteredWidget( A& a, B& b, C c, D& d, E& e, F* f): W( a, b, c, d, e, f) { construct(); } - template< typename A, typename B, typename C, typename D, typename E , typename F, typename G> - RegisteredWidget( A& a, B& b, C& c, D& d, E& e, F f, G& g): W( a, b, c, d, e, f, g) { construct(); } - - ~RegisteredWidget() override = default;; - - void init_parent(const Glib::ustring& key, Registry& wr, Inkscape::XML::Node* repr_in, SPDocument *doc_in) + RegisteredWidget() + : W() + { + construct(); + } + template <typename A> + explicit RegisteredWidget(A &a) + : W(a) + { + construct(); + } + template <typename A, typename B> + RegisteredWidget(A &a, B &b) + : W(a, b) + { + construct(); + } + template <typename A, typename B, typename C> + RegisteredWidget(A &a, B &b, C *c) + : W(a, b, c) + { + construct(); + } + template <typename A, typename B, typename C> + RegisteredWidget(A &a, B &b, C &c) + : W(a, b, c) + { + construct(); + } + template <typename A, typename B, typename C, typename D> + RegisteredWidget(A &a, B &b, C c, D d) + : W(a, b, c, d) + { + construct(); + } + template <typename A, typename B, typename C, typename D, typename E> + RegisteredWidget(A &a, B &b, C &c, D d, E e) + : W(a, b, c, d, e) + { + construct(); + } + template <typename A, typename B, typename C, typename D, typename E, typename F> + RegisteredWidget(A &a, B &b, C c, D &d, E &e, F *f) + : W(a, b, c, d, e, f) + { + construct(); + } + template <typename A, typename B, typename C, typename D, typename E, typename F, typename G> + RegisteredWidget(A &a, B &b, C &c, D &d, E &e, F f, G &g) + : W(a, b, c, d, e, f, g) + { + construct(); + } + + ~RegisteredWidget() override = default; + ; + + void init_parent(const Glib::ustring &key, Registry &wr, Inkscape::XML::Node *repr_in, SPDocument *doc_in) { _wr = ≀ _key = key; repr = repr_in; doc = doc_in; - if (repr && !doc) // doc cannot be NULL when repr is not NULL + if (repr && !doc) // doc cannot be NULL when repr is not NULL g_warning("Initialization of registered widget using defined repr but with doc==NULL"); } - void write_to_xml(const char * svgstr) + void write_to_xml(const char *svgstr) { // Use local repr here. When repr is specified, use that one, but // if repr==NULL, get the repr of namedview of active desktop. Inkscape::XML::Node *local_repr = repr; SPDocument *local_doc = doc; if (!local_repr) { - SPDesktop* dt = _wr->desktop(); + SPDesktop *dt = _wr->desktop(); if (!dt) { return; } @@ -113,12 +155,12 @@ protected: bool saved = DocumentUndo::getUndoSensitive(local_doc); DocumentUndo::setUndoSensitive(local_doc, false); - const char * svgstr_old = local_repr->attribute(_key.c_str()); + const char *svgstr_old = local_repr->attribute(_key.c_str()); if (!write_undo) { local_repr->setAttribute(_key, svgstr); } DocumentUndo::setUndoSensitive(local_doc, saved); - if (svgstr_old && svgstr && strcmp(svgstr_old,svgstr)) { + if (svgstr_old && svgstr && strcmp(svgstr_old, svgstr)) { local_doc->setModifiedSinceSave(); } @@ -128,87 +170,88 @@ protected: } } - Registry * _wr; + Registry *_wr; Glib::ustring _key; - Inkscape::XML::Node * repr; - SPDocument * doc; + Inkscape::XML::Node *repr; + SPDocument *doc; unsigned int event_type; Glib::ustring event_description; bool write_undo; private: - void construct() { + void construct() + { _wr = nullptr; repr = nullptr; doc = nullptr; write_undo = false; - event_type = 0; //SP_VERB_INVALID + event_type = 0; // SP_VERB_INVALID } }; //####################################################### -class RegisteredCheckButton : public RegisteredWidget<Gtk::CheckButton> { +class RegisteredCheckButton : public RegisteredWidget<Gtk::CheckButton> +{ public: ~RegisteredCheckButton() override; - RegisteredCheckButton (const Glib::ustring& label, const Glib::ustring& tip, const Glib::ustring& key, Registry& wr, bool right=false, Inkscape::XML::Node* repr_in=nullptr, SPDocument *doc_in=nullptr, char const *active_str = "true", char const *inactive_str = "false"); + RegisteredCheckButton(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, Registry &wr, + bool right = false, Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr, + char const *active_str = "true", char const *inactive_str = "false"); - void setActive (bool); + void setActive(bool); - std::list<Gtk::Widget*> _slavewidgets; + std::list<Gtk::Widget *> _slavewidgets; // a slave button is only sensitive when the master button is active // i.e. a slave button is greyed-out when the master button is not checked - void setSlaveWidgets(std::list<Gtk::Widget*> btns) { - _slavewidgets = btns; - } + void setSlaveWidgets(std::list<Gtk::Widget *> btns) { _slavewidgets = btns; } bool setProgrammatically; // true if the value was set by setActive, not changed by the user; - // if a callback checks it, it must reset it back to false + // if a callback checks it, it must reset it back to false protected: char const *_active_str, *_inactive_str; - sigc::connection _toggled_connection; + sigc::connection _toggled_connection; void on_toggled() override; }; -class RegisteredToggleButton : public RegisteredWidget<Gtk::ToggleButton> { +class RegisteredToggleButton : public RegisteredWidget<Gtk::ToggleButton> +{ public: ~RegisteredToggleButton() override; - RegisteredToggleButton (const Glib::ustring& label, const Glib::ustring& tip, const Glib::ustring& key, Registry& wr, bool right=true, Inkscape::XML::Node* repr_in=nullptr, SPDocument *doc_in=nullptr, char const *icon_active = "true", char const *icon_inactive = "false"); + RegisteredToggleButton(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, Registry &wr, + bool right = true, Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr, + char const *icon_active = "true", char const *icon_inactive = "false"); - void setActive (bool); + void setActive(bool); - std::list<Gtk::Widget*> _slavewidgets; + std::list<Gtk::Widget *> _slavewidgets; // a slave button is only sensitive when the master button is active // i.e. a slave button is greyed-out when the master button is not checked - void setSlaveWidgets(std::list<Gtk::Widget*> btns) { - _slavewidgets = btns; - } + void setSlaveWidgets(std::list<Gtk::Widget *> btns) { _slavewidgets = btns; } bool setProgrammatically; // true if the value was set by setActive, not changed by the user; - // if a callback checks it, it must reset it back to false + // if a callback checks it, it must reset it back to false protected: - sigc::connection _toggled_connection; + sigc::connection _toggled_connection; void on_toggled() override; }; -class RegisteredUnitMenu : public RegisteredWidget<Labelled> { +class RegisteredUnitMenu : public RegisteredWidget<Labelled> +{ public: ~RegisteredUnitMenu() override; - RegisteredUnitMenu ( const Glib::ustring& label, - const Glib::ustring& key, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr ); - - void setUnit (const Glib::ustring); - Unit const * getUnit() const { return static_cast<UnitMenu*>(_widget)->getUnit(); }; - UnitMenu* getUnitMenu() const { return static_cast<UnitMenu*>(_widget); }; + RegisteredUnitMenu(const Glib::ustring &label, const Glib::ustring &key, Registry &wr, + Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr); + + 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; protected: @@ -217,228 +260,190 @@ protected: // Allow RegisteredScalarUnit to output lengths in 'user units' (which may have direction dependent // scale factors). -enum RSU_UserUnits { +enum RSU_UserUnits +{ RSU_none, RSU_x, RSU_y }; -class RegisteredScalarUnit : public RegisteredWidget<ScalarUnit> { +class RegisteredScalarUnit : public RegisteredWidget<ScalarUnit> +{ public: ~RegisteredScalarUnit() override; - RegisteredScalarUnit ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - const RegisteredUnitMenu &rum, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr, - RSU_UserUnits _user_units = RSU_none ); + RegisteredScalarUnit(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + const RegisteredUnitMenu &rum, Registry &wr, Inkscape::XML::Node *repr_in = nullptr, + SPDocument *doc_in = nullptr, RSU_UserUnits _user_units = RSU_none); protected: - sigc::connection _value_changed_connection; - UnitMenu *_um; + sigc::connection _value_changed_connection; + UnitMenu *_um; void on_value_changed(); RSU_UserUnits _user_units; }; -class RegisteredScalar : public RegisteredWidget<Scalar> { +class RegisteredScalar : public RegisteredWidget<Scalar> +{ public: ~RegisteredScalar() override; - RegisteredScalar (const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr ); + RegisteredScalar(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, Registry &wr, + Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr); + protected: sigc::connection _value_changed_connection; void on_value_changed(); }; -class RegisteredText : public RegisteredWidget<Text> { +class RegisteredText : public RegisteredWidget<Text> +{ public: ~RegisteredText() override; - RegisteredText (const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr ); + RegisteredText(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, Registry &wr, + Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr); protected: - sigc::connection _activate_connection; + sigc::connection _activate_connection; void on_activate(); }; -class RegisteredColorPicker : public RegisteredWidget<LabelledColorPicker> { +class RegisteredColorPicker : public RegisteredWidget<LabelledColorPicker> +{ public: ~RegisteredColorPicker() override; - RegisteredColorPicker (const Glib::ustring& label, - const Glib::ustring& title, - const Glib::ustring& tip, - const Glib::ustring& ckey, - const Glib::ustring& akey, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr); + RegisteredColorPicker(const Glib::ustring &label, const Glib::ustring &title, const Glib::ustring &tip, + const Glib::ustring &ckey, const Glib::ustring &akey, Registry &wr, + Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr); - void setRgba32 (guint32); + void setRgba32(guint32); void closeWindow(); protected: Glib::ustring _ckey, _akey; - void on_changed (guint32); + void on_changed(guint32); sigc::connection _changed_connection; }; -class RegisteredSuffixedInteger : public RegisteredWidget<Scalar> { +class RegisteredSuffixedInteger : public RegisteredWidget<Scalar> +{ public: ~RegisteredSuffixedInteger() override; - RegisteredSuffixedInteger ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& suffix, - const Glib::ustring& key, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr ); + RegisteredSuffixedInteger(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &suffix, + const Glib::ustring &key, Registry &wr, Inkscape::XML::Node *repr_in = nullptr, + SPDocument *doc_in = nullptr); bool setProgrammatically; // true if the value was set by setValue, not changed by the user; - // if a callback checks it, it must reset it back to false + // if a callback checks it, it must reset it back to false protected: sigc::connection _changed_connection; void on_value_changed(); }; -class RegisteredRadioButtonPair : public RegisteredWidget<Gtk::HBox> { +class RegisteredRadioButtonPair : public RegisteredWidget<Gtk::HBox> +{ public: ~RegisteredRadioButtonPair() override; - RegisteredRadioButtonPair ( const Glib::ustring& label, - const Glib::ustring& label1, - const Glib::ustring& label2, - const Glib::ustring& tip1, - const Glib::ustring& tip2, - const Glib::ustring& key, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr ); - - void setValue (bool second); + RegisteredRadioButtonPair(const Glib::ustring &label, const Glib::ustring &label1, const Glib::ustring &label2, + const Glib::ustring &tip1, const Glib::ustring &tip2, const Glib::ustring &key, + Registry &wr, Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr); + + void setValue(bool second); bool setProgrammatically; // true if the value was set by setValue, not changed by the user; - // if a callback checks it, it must reset it back to false + // if a callback checks it, it must reset it back to false protected: Gtk::RadioButton *_rb1, *_rb2; sigc::connection _changed_connection; void on_value_changed(); }; -class RegisteredPoint : public RegisteredWidget<Point> { +class RegisteredPoint : public RegisteredWidget<Point> +{ public: ~RegisteredPoint() override; - RegisteredPoint ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr ); + RegisteredPoint(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, Registry &wr, + Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr); protected: - sigc::connection _value_x_changed_connection; - sigc::connection _value_y_changed_connection; + sigc::connection _value_x_changed_connection; + sigc::connection _value_y_changed_connection; void on_value_changed(); }; - -class RegisteredTransformedPoint : public RegisteredWidget<Point> { +class RegisteredTransformedPoint : public RegisteredWidget<Point> +{ public: ~RegisteredTransformedPoint() override; - RegisteredTransformedPoint ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr ); + RegisteredTransformedPoint(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, + Registry &wr, Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr); // redefine setValue, because transform must be applied - void setValue(Geom::Point const & p); + void setValue(Geom::Point const &p); - void setTransform(Geom::Affine const & canvas_to_svg); + void setTransform(Geom::Affine const &canvas_to_svg); protected: - sigc::connection _value_x_changed_connection; - sigc::connection _value_y_changed_connection; + sigc::connection _value_x_changed_connection; + sigc::connection _value_y_changed_connection; void on_value_changed(); Geom::Affine to_svg; }; - -class RegisteredVector : public RegisteredWidget<Point> { +class RegisteredVector : public RegisteredWidget<Point> +{ public: ~RegisteredVector() override; - RegisteredVector (const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr ); + RegisteredVector(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, Registry &wr, + Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr); // redefine setValue, because transform must be applied - void setValue(Geom::Point const & p); - void setValue(Geom::Point const & p, Geom::Point const & origin); + void setValue(Geom::Point const &p); + void setValue(Geom::Point const &p, Geom::Point const &origin); /** * Changes the widgets text to polar coordinates. The SVG output will still be a normal carthesian vector. - * Careful: when calling getValue(), the return value's X-coord will be the angle, Y-value will be the distance/length. - * After changing the coords type (polar/non-polar), the value has to be reset (setValue). + * Careful: when calling getValue(), the return value's X-coord will be the angle, Y-value will be the + * distance/length. After changing the coords type (polar/non-polar), the value has to be reset (setValue). */ void setPolarCoords(bool polar_coords = true); protected: - sigc::connection _value_x_changed_connection; - sigc::connection _value_y_changed_connection; + sigc::connection _value_x_changed_connection; + sigc::connection _value_y_changed_connection; void on_value_changed(); Geom::Point _origin; bool _polar_coords; }; - -class RegisteredRandom : public RegisteredWidget<Random> { +class RegisteredRandom : public RegisteredWidget<Random> +{ public: ~RegisteredRandom() override; - RegisteredRandom ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr); + RegisteredRandom(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, Registry &wr, + Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr); - void setValue (double val, long startseed); + void setValue(double val, long startseed); protected: - sigc::connection _value_changed_connection; - sigc::connection _reseeded_connection; + sigc::connection _value_changed_connection; + sigc::connection _reseeded_connection; void on_value_changed(); }; -class RegisteredFontButton : public RegisteredWidget<FontButton> { +class RegisteredFontButton : public RegisteredWidget<FontButton> +{ public: ~RegisteredFontButton() override; - RegisteredFontButton ( const Glib::ustring& label, - const Glib::ustring& tip, - const Glib::ustring& key, - Registry& wr, - Inkscape::XML::Node* repr_in = nullptr, - SPDocument *doc_in = nullptr); + RegisteredFontButton(const Glib::ustring &label, const Glib::ustring &tip, const Glib::ustring &key, Registry &wr, + Inkscape::XML::Node *repr_in = nullptr, SPDocument *doc_in = nullptr); - void setValue (Glib::ustring fontspec); + void setValue(Glib::ustring fontspec); protected: - sigc::connection _signal_font_set; + sigc::connection _signal_font_set; void on_value_changed(); }; diff --git a/src/ui/widget/registry.cpp b/src/ui/widget/registry.cpp index 4bc8e005324740fd7a0d0f30a3e6f13fb7061a46..23bc77230a574286495a11e7f157259aa1b726b1 100644 --- a/src/ui/widget/registry.cpp +++ b/src/ui/widget/registry.cpp @@ -18,18 +18,18 @@ namespace Widget { //--------------------------------------------------- -Registry::Registry() : _updating(false) {} +Registry::Registry() + : _updating(false) +{} Registry::~Registry() = default; -bool -Registry::isUpdating() +bool Registry::isUpdating() { return _updating; } -void -Registry::setUpdating (bool upd) +void Registry::setUpdating(bool upd) { _updating = upd; } @@ -41,8 +41,7 @@ void Registry::setDesktop(SPDesktop *desktop) //==================================================== - -} // namespace Dialog +} // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/registry.h b/src/ui/widget/registry.h index e6a190d0ef81447eea300a45576ee07e1741ce80..94344d5ac2fd9b0b4348d376cc0291f69c60a06b 100644 --- a/src/ui/widget/registry.h +++ b/src/ui/widget/registry.h @@ -15,14 +15,15 @@ class SPDesktop; namespace Inkscape { namespace UI { namespace Widget { - -class Registry { + +class Registry +{ public: Registry(); ~Registry(); - - bool isUpdating(); - void setUpdating (bool); + + bool isUpdating(); + void setUpdating(bool); SPDesktop *desktop() const { return _desktop; } void setDesktop(SPDesktop *desktop); @@ -33,9 +34,9 @@ protected: SPDesktop *_desktop = nullptr; }; -} // namespace Dialog -} // namespace UI } // namespace Widget +} // namespace UI +} // namespace Inkscape #endif // INKSCAPE_UI_WIDGET_REGISTRY__H diff --git a/src/ui/widget/rendering-options.cpp b/src/ui/widget/rendering-options.cpp index 549f494f15aa6564283c6b943bd8d20936a13b9a..d256150e3765ee1395b8b928c72846ec53d02d75 100644 --- a/src/ui/widget/rendering-options.cpp +++ b/src/ui/widget/rendering-options.cpp @@ -9,12 +9,13 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "rendering-options.h" + +#include <glibmm/i18n.h> #include <gtkmm.h> #include "preferences.h" -#include "rendering-options.h" #include "util/units.h" -#include <glibmm/i18n.h> namespace Inkscape { namespace UI { @@ -25,83 +26,76 @@ void RenderingOptions::_toggled() _frame_bitmap.set_sensitive(as_bitmap()); } -RenderingOptions::RenderingOptions () : - Gtk::VBox (), - _frame_backends ( Glib::ustring(_("Backend")) ), - _radio_vector ( Glib::ustring(_("Vector")) ), - _radio_bitmap ( Glib::ustring(_("Bitmap")) ), - _frame_bitmap ( Glib::ustring(_("Bitmap options")) ), - _dpi( _("DPI"), - Glib::ustring(_("Preferred resolution of rendering, " - "in dots per inch.")), - 1, - Glib::ustring(""), Glib::ustring(""), - false) +RenderingOptions::RenderingOptions() + : Gtk::VBox() + , _frame_backends(Glib::ustring(_("Backend"))) + , _radio_vector(Glib::ustring(_("Vector"))) + , _radio_bitmap(Glib::ustring(_("Bitmap"))) + , _frame_bitmap(Glib::ustring(_("Bitmap options"))) + , _dpi(_("DPI"), + Glib::ustring(_("Preferred resolution of rendering, " + "in dots per inch.")), + 1, Glib::ustring(""), Glib::ustring(""), false) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); // set up tooltips - _radio_vector.set_tooltip_text( - _("Render using Cairo vector operations. " - "The resulting image is usually smaller in file " - "size and can be arbitrarily scaled, but some " - "filter effects will not be correctly rendered.")); - _radio_bitmap.set_tooltip_text( - _("Render everything as bitmap. The resulting image " - "is usually larger in file size and cannot be " - "arbitrarily scaled without quality loss, but all " - "objects will be rendered exactly as displayed.")); + _radio_vector.set_tooltip_text(_("Render using Cairo vector operations. " + "The resulting image is usually smaller in file " + "size and can be arbitrarily scaled, but some " + "filter effects will not be correctly rendered.")); + _radio_bitmap.set_tooltip_text(_("Render everything as bitmap. The resulting image " + "is usually larger in file size and cannot be " + "arbitrarily scaled without quality loss, but all " + "objects will be rendered exactly as displayed.")); set_border_width(2); - Gtk::RadioButtonGroup group = _radio_vector.get_group (); - _radio_bitmap.set_group (group); + Gtk::RadioButtonGroup group = _radio_vector.get_group(); + _radio_bitmap.set_group(group); _radio_bitmap.signal_toggled().connect(sigc::mem_fun(*this, &RenderingOptions::_toggled)); - + // default to vector operations if (prefs->getBool("/dialogs/printing/asbitmap", false)) { _radio_bitmap.set_active(); } else { _radio_vector.set_active(); } - + // configure default DPI - _dpi.setRange(Inkscape::Util::Quantity::convert(1, "in", "pt"),2400.0); - _dpi.setValue(prefs->getDouble("/dialogs/printing/dpi", - Inkscape::Util::Quantity::convert(1, "in", "pt"))); - _dpi.setIncrements(1.0,10.0); + _dpi.setRange(Inkscape::Util::Quantity::convert(1, "in", "pt"), 2400.0); + _dpi.setValue(prefs->getDouble("/dialogs/printing/dpi", Inkscape::Util::Quantity::convert(1, "in", "pt"))); + _dpi.setIncrements(1.0, 10.0); _dpi.setDigits(0); _dpi.update(); // fill frames - Gtk::VBox *box_vector = Gtk::manage( new Gtk::VBox () ); - box_vector->set_border_width (2); - box_vector->add (_radio_vector); - box_vector->add (_radio_bitmap); - _frame_backends.add (*box_vector); + Gtk::VBox *box_vector = Gtk::manage(new Gtk::VBox()); + box_vector->set_border_width(2); + box_vector->add(_radio_vector); + box_vector->add(_radio_bitmap); + _frame_backends.add(*box_vector); - Gtk::HBox *box_bitmap = Gtk::manage( new Gtk::HBox () ); - box_bitmap->set_border_width (2); - box_bitmap->add (_dpi); - _frame_bitmap.add (*box_bitmap); + Gtk::HBox *box_bitmap = Gtk::manage(new Gtk::HBox()); + box_bitmap->set_border_width(2); + box_bitmap->add(_dpi); + _frame_bitmap.add(*box_bitmap); // fill up container - add (_frame_backends); - add (_frame_bitmap); + add(_frame_backends); + add(_frame_bitmap); // initialize states _toggled(); - show_all_children (); + show_all_children(); } -bool -RenderingOptions::as_bitmap () +bool RenderingOptions::as_bitmap() { return _radio_bitmap.get_active(); } -double -RenderingOptions::bitmap_dpi () +double RenderingOptions::bitmap_dpi() { return _dpi.getValue(); } diff --git a/src/ui/widget/rendering-options.h b/src/ui/widget/rendering-options.h index 2e10ff3545be8518bef8f7754eb67bad46be41c5..8acf885353720033ff2d8ba717826d20b523e6b7 100644 --- a/src/ui/widget/rendering-options.h +++ b/src/ui/widget/rendering-options.h @@ -12,11 +12,11 @@ #ifndef INKSCAPE_UI_WIDGET_RENDERING_OPTIONS_H #define INKSCAPE_UI_WIDGET_RENDERING_OPTIONS_H -#include "scalar.h" - #include <gtkmm/frame.h> #include <gtkmm/radiobutton.h> +#include "scalar.h" + namespace Inkscape { namespace UI { namespace Widget { @@ -27,24 +27,23 @@ namespace Widget { class RenderingOptions : public Gtk::VBox { public: - /** * Construct a Rendering Options widget. */ RenderingOptions(); - bool as_bitmap(); // should we render as a bitmap? - double bitmap_dpi(); // at what DPI should we render the bitmap? + bool as_bitmap(); // should we render as a bitmap? + double bitmap_dpi(); // at what DPI should we render the bitmap? protected: // Radio buttons to select desired rendering - Gtk::Frame _frame_backends; + Gtk::Frame _frame_backends; Gtk::RadioButton _radio_vector; Gtk::RadioButton _radio_bitmap; // Bitmap options - Gtk::Frame _frame_bitmap; - Scalar _dpi; // DPI of bitmap to render + Gtk::Frame _frame_bitmap; + Scalar _dpi; // DPI of bitmap to render // callback for bitmap button void _toggled(); @@ -56,7 +55,7 @@ protected: #endif // INKSCAPE_UI_WIDGET_RENDERING_OPTIONS_H -/* +/* Local Variables: mode:c++ c-file-style:"stroustrup" diff --git a/src/ui/widget/rotateable.cpp b/src/ui/widget/rotateable.cpp index 639f8d1a86b1da51e7a506ee61d858aac1a1d5c1..9a680044266b7d11dad64d629ae6250bb76d8ac8 100644 --- a/src/ui/widget/rotateable.cpp +++ b/src/ui/widget/rotateable.cpp @@ -8,36 +8,38 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "rotateable.h" + +#include <2geom/point.h> #include <gtkmm/box.h> #include <gtkmm/eventbox.h> -#include <2geom/point.h> + #include "ui/tools/tool-base.h" -#include "rotateable.h" namespace Inkscape { namespace UI { namespace Widget { -Rotateable::Rotateable(): - axis(-M_PI/4), - maxdecl(M_PI/4) +Rotateable::Rotateable() + : axis(-M_PI / 4) + , maxdecl(M_PI / 4) { - dragging = false; - working = false; - scrolling = false; - modifier = 0; - current_axis = axis; + 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)); gtk_widget_add_events(GTK_WIDGET(gobj()), GDK_SCROLL_MASK | GDK_SMOOTH_SCROLL_MASK); signal_scroll_event().connect(sigc::mem_fun(*this, &Rotateable::on_scroll)); - } -bool Rotateable::on_click(GdkEventButton *event) { - if (event->button == 1) { +bool Rotateable::on_click(GdkEventButton *event) +{ + if (event->button == 1) { drag_started_x = event->x; drag_started_y = event->y; modifier = get_single_modifier(modifier, event->state); @@ -49,9 +51,9 @@ bool Rotateable::on_click(GdkEventButton *event) { return false; } -guint Rotateable::get_single_modifier(guint old, guint state) { - - if (old == 0 || old == 3) { +guint Rotateable::get_single_modifier(guint old, guint state) +{ + if (old == 0 || old == 3) { if (state & GDK_CONTROL_MASK) return 1; // ctrl if (state & GDK_SHIFT_MASK) @@ -59,7 +61,7 @@ guint Rotateable::get_single_modifier(guint old, guint state) { if (state & GDK_MOD1_MASK) return 3; // alt return 0; - } else { + } else { if (!(state & GDK_CONTROL_MASK) && !(state & GDK_SHIFT_MASK)) { if (state & GDK_MOD1_MASK) return 3; // alt @@ -70,49 +72,49 @@ guint Rotateable::get_single_modifier(guint old, guint state) { if (state & GDK_SHIFT_MASK && !(state & GDK_CONTROL_MASK)) return 2; // shift if (state & GDK_MOD1_MASK && !(state & GDK_CONTROL_MASK)) - return 3; // alt + return 3; // alt return 1; } if (old == 2) { if (state & GDK_CONTROL_MASK && !(state & GDK_SHIFT_MASK)) return 1; // ctrl if (state & GDK_MOD1_MASK && !(state & GDK_SHIFT_MASK)) - return 3; // alt + return 3; // alt return 2; } return old; - } + } } - -bool Rotateable::on_motion(GdkEventMotion *event) { - if (dragging) { +bool Rotateable::on_motion(GdkEventMotion *event) +{ + if (dragging) { double dist = Geom::L2(Geom::Point(event->x, event->y) - Geom::Point(drag_started_x, drag_started_y)); double angle = atan2(event->y - drag_started_y, event->x - drag_started_x); if (dist > 20) { working = true; - 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 - if (modifier != get_single_modifier(modifier, event->state)) { + if (modifier != get_single_modifier(modifier, event->state)) { // user has switched modifiers in mid drag, close past drag and start a new // one, redefining axis temporarily do_release(force, modifier); current_axis = angle; - modifier = get_single_modifier(modifier, event->state); + modifier = get_single_modifier(modifier, event->state); } else { do_motion(force, modifier); } } Inkscape::UI::Tools::gobble_motion_events(GDK_BUTTON1_MASK); return true; - } - return false; + } + return false; } - -bool Rotateable::on_release(GdkEventButton *event) { - if (dragging && working) { +bool Rotateable::on_release(GdkEventButton *event) +{ + 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); if (fabs(force) < 0.002) @@ -128,7 +130,7 @@ bool Rotateable::on_release(GdkEventButton *event) { return false; } -bool Rotateable::on_scroll(GdkEventScroll* event) +bool Rotateable::on_scroll(GdkEventScroll *event) { double change = 0.0; @@ -162,8 +164,6 @@ bool Rotateable::on_scroll(GdkEventScroll* event) Rotateable::~Rotateable() = default; - - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/rotateable.h b/src/ui/widget/rotateable.h index c174a09f11a16c43c0a43fca578157651323ae69..4e233b798d8c2d0a9f9d4512b7d2f7fdcc6663fe 100644 --- a/src/ui/widget/rotateable.h +++ b/src/ui/widget/rotateable.h @@ -11,9 +11,9 @@ #ifndef INKSCAPE_UI_ROTATEABLE_H #define INKSCAPE_UI_ROTATEABLE_H +#include <glibmm/i18n.h> #include <gtkmm/box.h> #include <gtkmm/eventbox.h> -#include <glibmm/i18n.h> namespace Inkscape { namespace UI { @@ -22,7 +22,7 @@ namespace Widget { /** * Widget adjustable by dragging it to rotate away from a zero-change axis. */ -class Rotateable: public Gtk::EventBox +class Rotateable : public Gtk::EventBox { public: Rotateable(); @@ -32,7 +32,7 @@ public: bool on_click(GdkEventButton *event); bool on_motion(GdkEventMotion *event); bool on_release(GdkEventButton *event); - bool on_scroll(GdkEventScroll* event); + bool on_scroll(GdkEventScroll *event); double axis; double current_axis; @@ -46,11 +46,11 @@ private: bool dragging; bool working; - guint get_single_modifier(guint old, guint state); + guint get_single_modifier(guint old, 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*/) {} + 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/scalar-unit.cpp b/src/ui/widget/scalar-unit.cpp index dd5ac4bbbcb30b606105e6a698d8aec311a15c16..70094775b6690a6026390c7f927793690d9e9c45 100644 --- a/src/ui/widget/scalar-unit.cpp +++ b/src/ui/widget/scalar-unit.cpp @@ -11,6 +11,7 @@ */ #include "scalar-unit.h" + #include "spinbutton.h" using Inkscape::Util::unit_table; @@ -19,17 +20,13 @@ namespace Inkscape { namespace UI { namespace Widget { -ScalarUnit::ScalarUnit(Glib::ustring const &label, Glib::ustring const &tooltip, - UnitType unit_type, - Glib::ustring const &suffix, - Glib::ustring const &icon, - UnitMenu *unit_menu, - bool mnemonic) - : Scalar(label, tooltip, suffix, icon, mnemonic), - _unit_menu(unit_menu), - _hundred_percent(0), - _absolute_is_increment(false), - _percentage_is_increment(false) +ScalarUnit::ScalarUnit(Glib::ustring const &label, Glib::ustring const &tooltip, UnitType unit_type, + Glib::ustring const &suffix, Glib::ustring const &icon, UnitMenu *unit_menu, bool mnemonic) + : Scalar(label, tooltip, suffix, icon, mnemonic) + , _unit_menu(unit_menu) + , _hundred_percent(0) + , _absolute_is_increment(false) + , _percentage_is_increment(false) { if (_unit_menu == nullptr) { _unit_menu = new UnitMenu(); @@ -42,40 +39,33 @@ ScalarUnit::ScalarUnit(Glib::ustring const &label, Glib::ustring const &tooltip, widget_holder->pack_start(*Gtk::manage(_unit_menu), Gtk::PACK_SHRINK); pack_start(*Gtk::manage(widget_holder), Gtk::PACK_SHRINK); } - _unit_menu->signal_changed() - .connect_notify(sigc::mem_fun(*this, &ScalarUnit::on_unit_changed)); + _unit_menu->signal_changed().connect_notify(sigc::mem_fun(*this, &ScalarUnit::on_unit_changed)); - static_cast<SpinButton*>(_widget)->setUnitMenu(_unit_menu); + static_cast<SpinButton *>(_widget)->setUnitMenu(_unit_menu); lastUnits = _unit_menu->getUnitAbbr(); } -ScalarUnit::ScalarUnit(Glib::ustring const &label, Glib::ustring const &tooltip, - ScalarUnit &take_unitmenu, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) - : Scalar(label, tooltip, suffix, icon, mnemonic), - _unit_menu(take_unitmenu._unit_menu), - _hundred_percent(0), - _absolute_is_increment(false), - _percentage_is_increment(false) +ScalarUnit::ScalarUnit(Glib::ustring const &label, Glib::ustring const &tooltip, ScalarUnit &take_unitmenu, + Glib::ustring const &suffix, Glib::ustring const &icon, bool mnemonic) + : Scalar(label, tooltip, suffix, icon, mnemonic) + , _unit_menu(take_unitmenu._unit_menu) + , _hundred_percent(0) + , _absolute_is_increment(false) + , _percentage_is_increment(false) { - _unit_menu->signal_changed() - .connect_notify(sigc::mem_fun(*this, &ScalarUnit::on_unit_changed)); + _unit_menu->signal_changed().connect_notify(sigc::mem_fun(*this, &ScalarUnit::on_unit_changed)); - static_cast<SpinButton*>(_widget)->setUnitMenu(_unit_menu); + static_cast<SpinButton *>(_widget)->setUnitMenu(_unit_menu); lastUnits = _unit_menu->getUnitAbbr(); } - void ScalarUnit::initScalar(double min_value, double max_value) { g_assert(_unit_menu != nullptr); Scalar::setDigits(_unit_menu->getDefaultDigits()); - Scalar::setIncrements(_unit_menu->getDefaultStep(), - _unit_menu->getDefaultPage()); + Scalar::setIncrements(_unit_menu->getDefaultStep(), _unit_menu->getDefaultPage()); Scalar::setRange(min_value, max_value); } @@ -104,7 +94,7 @@ void ScalarUnit::resetUnitType(UnitType unit_type) lastUnits = _unit_menu->getUnitAbbr(); } -Unit const * ScalarUnit::getUnit() const +Unit const *ScalarUnit::getUnit() const { g_assert(_unit_menu != nullptr); return _unit_menu->getUnit(); @@ -155,10 +145,9 @@ double ScalarUnit::getValue(Glib::ustring const &unit_name) const void ScalarUnit::grabFocusAndSelectEntry() { _widget->grab_focus(); - static_cast<SpinButton*>(_widget)->select_region(0, 20); + static_cast<SpinButton *>(_widget)->select_region(0, 20); } - void ScalarUnit::setHundredPercent(double number) { _hundred_percent = number; @@ -179,10 +168,10 @@ double ScalarUnit::PercentageToAbsolute(double value) // convert from percent to absolute double convertedVal = 0; double hundred_converted = _hundred_percent / _unit_menu->getConversion("px"); // _hundred_percent is in px - if (_percentage_is_increment) + if (_percentage_is_increment) value += 100; convertedVal = 0.01 * hundred_converted * value; - if (_absolute_is_increment) + if (_absolute_is_increment) convertedVal -= hundred_converted; return convertedVal; @@ -195,14 +184,15 @@ double ScalarUnit::AbsoluteToPercentage(double value) if (_hundred_percent == 0) { if (_percentage_is_increment) convertedVal = 0; - else + else convertedVal = 100; } else { - double hundred_converted = _hundred_percent / _unit_menu->getConversion("px", lastUnits); // _hundred_percent is in px - if (_absolute_is_increment) + double hundred_converted = + _hundred_percent / _unit_menu->getConversion("px", lastUnits); // _hundred_percent is in px + if (_absolute_is_increment) value += hundred_converted; convertedVal = 100 * value / hundred_converted; - if (_percentage_is_increment) + if (_percentage_is_increment) convertedVal -= 100; } @@ -215,14 +205,12 @@ double ScalarUnit::getAsPercentage() return convertedVal; } - -void ScalarUnit::setFromPercentage(double value) +void ScalarUnit::setFromPercentage(double value) { double absolute = PercentageToAbsolute(value); Scalar::setValue(absolute); } - void ScalarUnit::on_unit_changed() { g_assert(_unit_menu != nullptr); diff --git a/src/ui/widget/scalar-unit.h b/src/ui/widget/scalar-unit.h index e82c41d045d539f8d4708e2f157c9bc0ae67d140..81ec96c69d1dd54e495a0cd067b7955b5fe3f29a 100644 --- a/src/ui/widget/scalar-unit.h +++ b/src/ui/widget/scalar-unit.h @@ -49,11 +49,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to true). */ - ScalarUnit(Glib::ustring const &label, Glib::ustring const &tooltip, - UnitType unit_type = UNIT_TYPE_LINEAR, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - UnitMenu *unit_menu = nullptr, + ScalarUnit(Glib::ustring const &label, Glib::ustring const &tooltip, UnitType unit_type = UNIT_TYPE_LINEAR, + Glib::ustring const &suffix = "", Glib::ustring const &icon = "", UnitMenu *unit_menu = nullptr, bool mnemonic = true); /** @@ -68,73 +65,70 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to true). */ - ScalarUnit(Glib::ustring const &label, Glib::ustring const &tooltip, - ScalarUnit &take_unitmenu, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + ScalarUnit(Glib::ustring const &label, Glib::ustring const &tooltip, ScalarUnit &take_unitmenu, + Glib::ustring const &suffix = "", Glib::ustring const &icon = "", bool mnemonic = true); /** * Initializes the scalar based on the settings in _unit_menu. * Requires that _unit_menu has already been initialized. */ - void initScalar(double min_value, double max_value); + void initScalar(double min_value, double max_value); /** * Gets the object for the currently selected unit. */ - Unit const * getUnit() const; + Unit const *getUnit() const; /** * Gets the UnitType ID for the unit. */ - UnitType getUnitType() const; + UnitType getUnitType() const; /** * Returns the value in the given unit system. */ - double getValue(Glib::ustring const &units) const; + double getValue(Glib::ustring const &units) const; /** * Sets the unit for the ScalarUnit widget. */ - bool setUnit(Glib::ustring const &units); + bool setUnit(Glib::ustring const &units); /** * Adds the unit type to the ScalarUnit widget. */ - void setUnitType(UnitType unit_type); + void setUnitType(UnitType unit_type); /** * Resets the unit type for the ScalarUnit widget. */ - void resetUnitType(UnitType unit_type); + void resetUnitType(UnitType unit_type); /** * Sets the number and unit system. */ - void setValue(double number, Glib::ustring const &units); + void setValue(double number, Glib::ustring const &units); /** * Convert and sets the number only and keeps the current unit. */ - void setValueKeepUnit(double number, Glib::ustring const &units); + void setValueKeepUnit(double number, Glib::ustring const &units); /** * Sets the number only. */ - void setValue(double number); + void setValue(double number); /** * Grab focus, and select the text that is in the entry field. */ - void grabFocusAndSelectEntry(); + void grabFocusAndSelectEntry(); - void setHundredPercent(double number); + void setHundredPercent(double number); - void setAbsoluteIsIncrement(bool value); + void setAbsoluteIsIncrement(bool value); - void setPercentageIsIncrement(bool value); + void setPercentageIsIncrement(bool value); /** * Convert value from % to absolute, using _hundred_percent and *_is_increment flags. @@ -162,13 +156,15 @@ public: void on_unit_changed(); protected: - UnitMenu *_unit_menu; + UnitMenu *_unit_menu; double _hundred_percent; // the length that corresponds to 100%, in px, for %-to/from-absolute conversions - bool _absolute_is_increment; // if true, 120% with _hundred_percent=100px gets converted to/from 20px; otherwise, to/from 120px - bool _percentage_is_increment; // if true, 120px with _hundred_percent=100px gets converted to/from 20%; otherwise, to/from 120% - // if both are true, 20px is converted to/from 20% if _hundred_percent=100px + bool _absolute_is_increment; // if true, 120% with _hundred_percent=100px gets converted to/from 20px; otherwise, + // to/from 120px + bool _percentage_is_increment; // if true, 120px with _hundred_percent=100px gets converted to/from 20%; otherwise, + // to/from 120% if both are true, 20px is converted to/from 20% if + // _hundred_percent=100px Glib::ustring lastUnits; // previously selected unit, for conversions }; diff --git a/src/ui/widget/scalar.cpp b/src/ui/widget/scalar.cpp index 471de497c66174f7a81c8e1ca3afff792ba8be7c..70138d3f01cc0106142e876f5fa0324d9bf517e6 100644 --- a/src/ui/widget/scalar.cpp +++ b/src/ui/widget/scalar.cpp @@ -12,54 +12,44 @@ */ #include "scalar.h" -#include "spinbutton.h" + #include <gtkmm/scale.h> +#include "spinbutton.h" + namespace Inkscape { namespace UI { namespace Widget { -Scalar::Scalar(Glib::ustring const &label, Glib::ustring const &tooltip, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) - : Labelled(label, tooltip, new SpinButton(), suffix, icon, mnemonic), - setProgrammatically(false) -{ -} +Scalar::Scalar(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix, + Glib::ustring const &icon, bool mnemonic) + : Labelled(label, tooltip, new SpinButton(), suffix, icon, mnemonic) + , setProgrammatically(false) +{} -Scalar::Scalar(Glib::ustring const &label, Glib::ustring const &tooltip, - unsigned digits, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) - : Labelled(label, tooltip, new SpinButton(0.0, digits), suffix, icon, mnemonic), - setProgrammatically(false) -{ -} +Scalar::Scalar(Glib::ustring const &label, Glib::ustring const &tooltip, unsigned digits, Glib::ustring const &suffix, + Glib::ustring const &icon, bool mnemonic) + : Labelled(label, tooltip, new SpinButton(0.0, digits), suffix, icon, mnemonic) + , setProgrammatically(false) +{} -Scalar::Scalar(Glib::ustring const &label, Glib::ustring const &tooltip, - Glib::RefPtr<Gtk::Adjustment> &adjust, - unsigned digits, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) - : Labelled(label, tooltip, new SpinButton(adjust, 0.0, digits), suffix, icon, mnemonic), - setProgrammatically(false) -{ -} +Scalar::Scalar(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::RefPtr<Gtk::Adjustment> &adjust, + unsigned digits, Glib::ustring const &suffix, Glib::ustring const &icon, bool mnemonic) + : Labelled(label, tooltip, new SpinButton(adjust, 0.0, digits), suffix, icon, mnemonic) + , setProgrammatically(false) +{} unsigned Scalar::getDigits() const { g_assert(_widget != nullptr); - return static_cast<SpinButton*>(_widget)->get_digits(); + return static_cast<SpinButton *>(_widget)->get_digits(); } double Scalar::getStep() const { g_assert(_widget != nullptr); double step, page; - static_cast<SpinButton*>(_widget)->get_increments(step, page); + static_cast<SpinButton *>(_widget)->get_increments(step, page); return step; } @@ -67,7 +57,7 @@ double Scalar::getPage() const { g_assert(_widget != nullptr); double step, page; - static_cast<SpinButton*>(_widget)->get_increments(step, page); + static_cast<SpinButton *>(_widget)->get_increments(step, page); return page; } @@ -75,7 +65,7 @@ double Scalar::getRangeMin() const { g_assert(_widget != nullptr); double min, max; - static_cast<SpinButton*>(_widget)->get_range(min, max); + static_cast<SpinButton *>(_widget)->get_range(min, max); return min; } @@ -83,39 +73,38 @@ double Scalar::getRangeMax() const { g_assert(_widget != nullptr); double min, max; - static_cast<SpinButton*>(_widget)->get_range(min, max); + static_cast<SpinButton *>(_widget)->get_range(min, max); return max; } double Scalar::getValue() const { g_assert(_widget != nullptr); - return static_cast<SpinButton*>(_widget)->get_value(); + return static_cast<SpinButton *>(_widget)->get_value(); } int Scalar::getValueAsInt() const { g_assert(_widget != nullptr); - return static_cast<SpinButton*>(_widget)->get_value_as_int(); + return static_cast<SpinButton *>(_widget)->get_value_as_int(); } - void Scalar::setDigits(unsigned digits) { g_assert(_widget != nullptr); - static_cast<SpinButton*>(_widget)->set_digits(digits); + static_cast<SpinButton *>(_widget)->set_digits(digits); } void Scalar::setIncrements(double step, double /*page*/) { g_assert(_widget != nullptr); - static_cast<SpinButton*>(_widget)->set_increments(step, 0); + static_cast<SpinButton *>(_widget)->set_increments(step, 0); } void Scalar::setRange(double min, double max) { g_assert(_widget != nullptr); - static_cast<SpinButton*>(_widget)->set_range(min, max); + static_cast<SpinButton *>(_widget)->set_range(min, max); } void Scalar::setValue(double value, bool setProg) @@ -124,39 +113,38 @@ void Scalar::setValue(double value, bool setProg) if (setProg) { setProgrammatically = true; // callback is supposed to reset back, if it cares } - static_cast<SpinButton*>(_widget)->set_value(value); + static_cast<SpinButton *>(_widget)->set_value(value); } void Scalar::setWidthChars(unsigned chars) { g_assert(_widget != NULL); - static_cast<SpinButton*>(_widget)->set_width_chars(chars); + static_cast<SpinButton *>(_widget)->set_width_chars(chars); } void Scalar::update() { g_assert(_widget != nullptr); - static_cast<SpinButton*>(_widget)->update(); + static_cast<SpinButton *>(_widget)->update(); } void Scalar::addSlider() { - auto scale = new Gtk::Scale(static_cast<SpinButton*>(_widget)->get_adjustment()); + auto scale = new Gtk::Scale(static_cast<SpinButton *>(_widget)->get_adjustment()); scale->set_draw_value(false); - add (*manage (scale)); + add(*manage(scale)); } Glib::SignalProxy0<void> Scalar::signal_value_changed() { - return static_cast<SpinButton*>(_widget)->signal_value_changed(); + return static_cast<SpinButton *>(_widget)->signal_value_changed(); } -Glib::SignalProxy1<bool, GdkEventButton*> Scalar::signal_button_release_event() +Glib::SignalProxy1<bool, GdkEventButton *> Scalar::signal_button_release_event() { - return static_cast<SpinButton*>(_widget)->signal_button_release_event(); + return static_cast<SpinButton *>(_widget)->signal_button_release_event(); } - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/scalar.h b/src/ui/widget/scalar.h index 29a14d15ab9a3caa913dea9103d0aefbd524457c..7f6d0cc755c760d98d31631da0e722e93c9e921a 100644 --- a/src/ui/widget/scalar.h +++ b/src/ui/widget/scalar.h @@ -36,11 +36,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to false). */ - Scalar(Glib::ustring const &label, - Glib::ustring const &tooltip, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Scalar(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix = "", + Glib::ustring const &icon = "", bool mnemonic = true); /** * Construct a Scalar Widget. @@ -53,12 +50,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to false). */ - Scalar(Glib::ustring const &label, - Glib::ustring const &tooltip, - unsigned digits, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Scalar(Glib::ustring const &label, Glib::ustring const &tooltip, unsigned digits, Glib::ustring const &suffix = "", + Glib::ustring const &icon = "", bool mnemonic = true); /** * Construct a Scalar Widget. @@ -72,13 +65,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to true). */ - Scalar(Glib::ustring const &label, - Glib::ustring const &tooltip, - Glib::RefPtr<Gtk::Adjustment> &adjust, - unsigned digits = 0, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Scalar(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::RefPtr<Gtk::Adjustment> &adjust, + unsigned digits = 0, Glib::ustring const &suffix = "", Glib::ustring const &icon = "", bool mnemonic = true); /** * Fetches the precision of the spin button. @@ -88,70 +76,70 @@ public: /** * Gets the current step increment used by the spin button. */ - double getStep() const; + double getStep() const; /** * Gets the current page increment used by the spin button. */ - double getPage() const; + double getPage() const; /** * Gets the minimum range value allowed for the spin button. */ - double getRangeMin() const; + double getRangeMin() const; /** * Gets the maximum range value allowed for the spin button. */ - double getRangeMax() const; + double getRangeMax() const; - bool getSnapToTicks() const; + bool getSnapToTicks() const; /** * Get the value in the spin_button. */ - double getValue() const; + double getValue() const; /** * Get the value spin_button represented as an integer. */ - int getValueAsInt() const; + int getValueAsInt() const; /** * Sets the precision to be displayed by the spin button. */ - void setDigits(unsigned digits); + void setDigits(unsigned digits); /** * Sets the step and page increments for the spin button. * @todo Remove the second parameter - deprecated */ - void setIncrements(double step, double page); + void setIncrements(double step, double page); /** * Sets the minimum and maximum range allowed for the spin button. */ - void setRange(double min, double max); + void setRange(double min, double max); /** * Sets the value of the spin button. */ - void setValue(double value, bool setProg = true); + void setValue(double value, bool setProg = true); /** * Sets the width of the spin button by number of characters. */ - void setWidthChars(unsigned chars); + void setWidthChars(unsigned chars); /** * Manually forces an update of the spin button. */ - void update(); + void update(); /** * Adds a slider (HScale) to the left of the spinbox. */ - void addSlider(); + void addSlider(); /** * Signal raised when the spin button's value changes. @@ -161,7 +149,7 @@ public: /** * Signal raised when the spin button's pressed. */ - Glib::SignalProxy1<bool, GdkEventButton*> signal_button_release_event(); + Glib::SignalProxy1<bool, GdkEventButton *> signal_button_release_event(); /** * true if the value was set by setValue, not changed by the user; diff --git a/src/ui/widget/selected-style.cpp b/src/ui/widget/selected-style.cpp index 33260c23ee314faeb2199e219385d06d9d532253..7e66aa9082dbdf0564ea68c591e8a9fd4952ed33 100644 --- a/src/ui/widget/selected-style.cpp +++ b/src/ui/widget/selected-style.cpp @@ -12,78 +12,68 @@ #include "selected-style.h" -#include <vector> - #include <gtkmm/separatormenuitem.h> - +#include <vector> #include "desktop-style.h" #include "document-undo.h" #include "gradient-chemistry.h" -#include "message-context.h" -#include "selection.h" -#include "sp-cursor.h" - #include "include/gtkmm_version.h" - +#include "message-context.h" #include "object/sp-hatch.h" #include "object/sp-linear-gradient.h" #include "object/sp-mesh-gradient.h" #include "object/sp-namedview.h" #include "object/sp-pattern.h" #include "object/sp-radial-gradient.h" +#include "selection.h" +#include "sp-cursor.h" #include "style.h" - -#include "ui/pixmaps/cursor-adj-a.xpm" -#include "ui/pixmaps/cursor-adj-h.xpm" -#include "ui/pixmaps/cursor-adj-l.xpm" -#include "ui/pixmaps/cursor-adj-s.xpm" - #include "svg/css-ostringstream.h" #include "svg/svg-color.h" - #include "ui/dialog/dialog-manager.h" #include "ui/dialog/fill-and-stroke.h" #include "ui/dialog/panel-dialog.h" +#include "ui/pixmaps/cursor-adj-a.xpm" +#include "ui/pixmaps/cursor-adj-h.xpm" +#include "ui/pixmaps/cursor-adj-l.xpm" +#include "ui/pixmaps/cursor-adj-s.xpm" #include "ui/tools/tool-base.h" -#include "ui/widget/canvas.h" // Forced redraws. +#include "ui/widget/canvas.h" // Forced redraws. #include "ui/widget/color-preview.h" #include "ui/widget/gradient-image.h" - #include "widgets/ege-paint-def.h" #include "widgets/spw-utilities.h" #include "widgets/widget-sizes.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"}; +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"}; -static void -ss_selection_changed (Inkscape::Selection *, gpointer data) +static void ss_selection_changed(Inkscape::Selection *, gpointer data) { - Inkscape::UI::Widget::SelectedStyle *ss = (Inkscape::UI::Widget::SelectedStyle *) data; + Inkscape::UI::Widget::SelectedStyle *ss = (Inkscape::UI::Widget::SelectedStyle *)data; ss->update(); } -static void -ss_selection_modified( Inkscape::Selection *selection, guint flags, gpointer data ) +static void ss_selection_modified(Inkscape::Selection *selection, guint flags, gpointer data) { // Don't update the style when dragging or doing non-style related changes if (flags & (SP_OBJECT_STYLE_MODIFIED_FLAG)) { - ss_selection_changed (selection, data); + ss_selection_changed(selection, data); } } -static void -ss_subselection_changed( gpointer /*dragger*/, gpointer data ) +static void ss_subselection_changed(gpointer /*dragger*/, gpointer data) { - ss_selection_changed (nullptr, data); + ss_selection_changed(nullptr, data); } namespace { -void clearTooltip( Gtk::Widget &widget ) +void clearTooltip(Gtk::Widget &widget) { widget.set_tooltip_text(""); widget.set_has_tooltip(false); @@ -95,26 +85,25 @@ namespace Inkscape { namespace UI { namespace Widget { - -struct DropTracker { - SelectedStyle* parent; +struct DropTracker +{ + SelectedStyle *parent; int item; }; /* Drag and Drop */ -enum ui_drop_target_info { +enum ui_drop_target_info +{ APP_OSWB_COLOR }; -//TODO: warning: deprecated conversion from string constant to ‘gchar*’ +// TODO: warning: deprecated conversion from string constant to ‘gchar*’ // -//Turn out to be warnings that we should probably leave in place. The +// Turn out to be warnings that we should probably leave in place. The // 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 const GtkTargetEntry ui_drop_target_entries [] = { - {g_strdup("application/x-oswb-color"), 0, APP_OSWB_COLOR} -}; +static const GtkTargetEntry ui_drop_target_entries[] = {{g_strdup("application/x-oswb-color"), 0, APP_OSWB_COLOR}}; static guint nui_drop_target_entries = G_N_ELEMENTS(ui_drop_target_entries); @@ -173,39 +162,39 @@ SelectedStyle::SelectedStyle(bool /*layout*/) _table.set_row_spacing(0); for (int i = SS_FILL; i <= SS_STROKE; i++) { - - _na[i].set_markup (_("N/A")); + _na[i].set_markup(_("N/A")); _na[i].show_all(); __na[i] = (_("Nothing selected")); if (i == SS_FILL) { - _none[i].set_markup (C_("Fill", "<i>None</i>")); + _none[i].set_markup(C_("Fill", "<i>None</i>")); } else { - _none[i].set_markup (C_("Stroke", "<i>None</i>")); + _none[i].set_markup(C_("Stroke", "<i>None</i>")); } _none[i].show_all(); - __none[i] = (i == SS_FILL)? (C_("Fill and stroke", "No fill, middle-click for black fill")) : (C_("Fill and stroke", "No stroke, middle-click for black stroke")); + __none[i] = (i == SS_FILL) ? (C_("Fill and stroke", "No fill, middle-click for black fill")) + : (C_("Fill and stroke", "No stroke, middle-click for black stroke")); - _pattern[i].set_markup (_("Pattern")); + _pattern[i].set_markup(_("Pattern")); _pattern[i].show_all(); - __pattern[i] = (i == SS_FILL)? (_("Pattern (fill)")) : (_("Pattern (stroke)")); + __pattern[i] = (i == SS_FILL) ? (_("Pattern (fill)")) : (_("Pattern (stroke)")); _hatch[i].set_markup(_("Hatch")); _hatch[i].show_all(); __hatch[i] = (i == SS_FILL) ? (_("Hatch (fill)")) : (_("Hatch (stroke)")); - _lgradient[i].set_markup (_("<b>L</b>")); + _lgradient[i].set_markup(_("<b>L</b>")); _lgradient[i].show_all(); - __lgradient[i] = (i == SS_FILL)? (_("Linear gradient (fill)")) : (_("Linear gradient (stroke)")); + __lgradient[i] = (i == SS_FILL) ? (_("Linear gradient (fill)")) : (_("Linear gradient (stroke)")); _gradient_preview_l[i] = Gtk::manage(new GradientImage(nullptr)); _gradient_box_l[i].pack_start(_lgradient[i]); _gradient_box_l[i].pack_start(*_gradient_preview_l[i]); _gradient_box_l[i].show_all(); - _rgradient[i].set_markup (_("<b>R</b>")); + _rgradient[i].set_markup(_("<b>R</b>")); _rgradient[i].show_all(); - __rgradient[i] = (i == SS_FILL)? (_("Radial gradient (fill)")) : (_("Radial gradient (stroke)")); + __rgradient[i] = (i == SS_FILL) ? (_("Radial gradient (fill)")) : (_("Radial gradient (stroke)")); _gradient_preview_r[i] = Gtk::manage(new GradientImage(nullptr)); _gradient_box_r[i].pack_start(_rgradient[i]); @@ -213,9 +202,9 @@ SelectedStyle::SelectedStyle(bool /*layout*/) _gradient_box_r[i].show_all(); #ifdef WITH_MESH - _mgradient[i].set_markup (_("<b>M</b>")); + _mgradient[i].set_markup(_("<b>M</b>")); _mgradient[i].show_all(); - __mgradient[i] = (i == SS_FILL)? (_("Mesh gradient (fill)")) : (_("Mesh gradient (stroke)")); + __mgradient[i] = (i == SS_FILL) ? (_("Mesh gradient (fill)")) : (_("Mesh gradient (stroke)")); _gradient_preview_m[i] = Gtk::manage(new GradientImage(nullptr)); _gradient_box_m[i].pack_start(_mgradient[i]); @@ -223,94 +212,98 @@ SelectedStyle::SelectedStyle(bool /*layout*/) _gradient_box_m[i].show_all(); #endif - _many[i].set_markup (_("Different")); + _many[i].set_markup(_("Different")); _many[i].show_all(); - __many[i] = (i == SS_FILL)? (_("Different fills")) : (_("Different strokes")); + __many[i] = (i == SS_FILL) ? (_("Different fills")) : (_("Different strokes")); - _unset[i].set_markup (_("<b>Unset</b>")); + _unset[i].set_markup(_("<b>Unset</b>")); _unset[i].show_all(); - __unset[i] = (i == SS_FILL)? (_("Unset fill")) : (_("Unset stroke")); + __unset[i] = (i == SS_FILL) ? (_("Unset fill")) : (_("Unset stroke")); - _color_preview[i] = new Inkscape::UI::Widget::ColorPreview (0); - __color[i] = (i == SS_FILL)? (_("Flat color (fill)")) : (_("Flat color (stroke)")); + _color_preview[i] = new Inkscape::UI::Widget::ColorPreview(0); + __color[i] = (i == SS_FILL) ? (_("Flat color (fill)")) : (_("Flat color (stroke)")); // TRANSLATORS: A means "Averaged" - _averaged[i].set_markup (_("<b>a</b>")); + _averaged[i].set_markup(_("<b>a</b>")); _averaged[i].show_all(); - __averaged[i] = (i == SS_FILL)? (_("Fill is averaged over selected objects")) : (_("Stroke is averaged over selected objects")); + __averaged[i] = (i == SS_FILL) ? (_("Fill is averaged over selected objects")) + : (_("Stroke is averaged over selected objects")); // TRANSLATORS: M means "Multiple" - _multiple[i].set_markup (_("<b>m</b>")); + _multiple[i].set_markup(_("<b>m</b>")); _multiple[i].show_all(); - __multiple[i] = (i == SS_FILL)? (_("Multiple selected objects have the same fill")) : (_("Multiple selected objects have the same stroke")); + __multiple[i] = (i == SS_FILL) ? (_("Multiple selected objects have the same fill")) + : (_("Multiple selected objects have the same stroke")); - _popup_edit[i].add(*(new Gtk::Label((i == SS_FILL)? _("Edit fill...") : _("Edit stroke..."), Gtk::ALIGN_START))); - _popup_edit[i].signal_activate().connect(sigc::mem_fun(*this, - (i == SS_FILL)? &SelectedStyle::on_fill_edit : &SelectedStyle::on_stroke_edit )); + _popup_edit[i].add( + *(new Gtk::Label((i == SS_FILL) ? _("Edit fill...") : _("Edit stroke..."), Gtk::ALIGN_START))); + _popup_edit[i].signal_activate().connect( + sigc::mem_fun(*this, (i == SS_FILL) ? &SelectedStyle::on_fill_edit : &SelectedStyle::on_stroke_edit)); _popup_lastused[i].add(*(new Gtk::Label(_("Last set color"), Gtk::ALIGN_START))); - _popup_lastused[i].signal_activate().connect(sigc::mem_fun(*this, - (i == SS_FILL)? &SelectedStyle::on_fill_lastused : &SelectedStyle::on_stroke_lastused )); + _popup_lastused[i].signal_activate().connect(sigc::mem_fun( + *this, (i == SS_FILL) ? &SelectedStyle::on_fill_lastused : &SelectedStyle::on_stroke_lastused)); _popup_lastselected[i].add(*(new Gtk::Label(_("Last selected color"), Gtk::ALIGN_START))); - _popup_lastselected[i].signal_activate().connect(sigc::mem_fun(*this, - (i == SS_FILL)? &SelectedStyle::on_fill_lastselected : &SelectedStyle::on_stroke_lastselected )); + _popup_lastselected[i].signal_activate().connect(sigc::mem_fun( + *this, (i == SS_FILL) ? &SelectedStyle::on_fill_lastselected : &SelectedStyle::on_stroke_lastselected)); _popup_invert[i].add(*(new Gtk::Label(_("Invert"), Gtk::ALIGN_START))); - _popup_invert[i].signal_activate().connect(sigc::mem_fun(*this, - (i == SS_FILL)? &SelectedStyle::on_fill_invert : &SelectedStyle::on_stroke_invert )); + _popup_invert[i].signal_activate().connect( + sigc::mem_fun(*this, (i == SS_FILL) ? &SelectedStyle::on_fill_invert : &SelectedStyle::on_stroke_invert)); _popup_white[i].add(*(new Gtk::Label(_("White"), Gtk::ALIGN_START))); - _popup_white[i].signal_activate().connect(sigc::mem_fun(*this, - (i == SS_FILL)? &SelectedStyle::on_fill_white : &SelectedStyle::on_stroke_white )); + _popup_white[i].signal_activate().connect( + sigc::mem_fun(*this, (i == SS_FILL) ? &SelectedStyle::on_fill_white : &SelectedStyle::on_stroke_white)); _popup_black[i].add(*(new Gtk::Label(_("Black"), Gtk::ALIGN_START))); - _popup_black[i].signal_activate().connect(sigc::mem_fun(*this, - (i == SS_FILL)? &SelectedStyle::on_fill_black : &SelectedStyle::on_stroke_black )); + _popup_black[i].signal_activate().connect( + sigc::mem_fun(*this, (i == SS_FILL) ? &SelectedStyle::on_fill_black : &SelectedStyle::on_stroke_black)); _popup_copy[i].add(*(new Gtk::Label(_("Copy color"), Gtk::ALIGN_START))); - _popup_copy[i].signal_activate().connect(sigc::mem_fun(*this, - (i == SS_FILL)? &SelectedStyle::on_fill_copy : &SelectedStyle::on_stroke_copy )); + _popup_copy[i].signal_activate().connect( + sigc::mem_fun(*this, (i == SS_FILL) ? &SelectedStyle::on_fill_copy : &SelectedStyle::on_stroke_copy)); _popup_paste[i].add(*(new Gtk::Label(_("Paste color"), Gtk::ALIGN_START))); - _popup_paste[i].signal_activate().connect(sigc::mem_fun(*this, - (i == SS_FILL)? &SelectedStyle::on_fill_paste : &SelectedStyle::on_stroke_paste )); + _popup_paste[i].signal_activate().connect( + sigc::mem_fun(*this, (i == SS_FILL) ? &SelectedStyle::on_fill_paste : &SelectedStyle::on_stroke_paste)); _popup_swap[i].add(*(new Gtk::Label(_("Swap fill and stroke"), Gtk::ALIGN_START))); - _popup_swap[i].signal_activate().connect(sigc::mem_fun(*this, - &SelectedStyle::on_fillstroke_swap)); - - _popup_opaque[i].add(*(new Gtk::Label((i == SS_FILL)? _("Make fill opaque") : _("Make stroke opaque"), Gtk::ALIGN_START))); - _popup_opaque[i].signal_activate().connect(sigc::mem_fun(*this, - (i == SS_FILL)? &SelectedStyle::on_fill_opaque : &SelectedStyle::on_stroke_opaque )); - - //TRANSLATORS COMMENT: unset is a verb here - _popup_unset[i].add(*(new Gtk::Label((i == SS_FILL)? _("Unset fill") : _("Unset stroke"), Gtk::ALIGN_START))); - _popup_unset[i].signal_activate().connect(sigc::mem_fun(*this, - (i == SS_FILL)? &SelectedStyle::on_fill_unset : &SelectedStyle::on_stroke_unset )); - - _popup_remove[i].add(*(new Gtk::Label((i == SS_FILL)? _("Remove fill") : _("Remove stroke"), Gtk::ALIGN_START))); - _popup_remove[i].signal_activate().connect(sigc::mem_fun(*this, - (i == SS_FILL)? &SelectedStyle::on_fill_remove : &SelectedStyle::on_stroke_remove )); - - _popup[i].attach(_popup_edit[i], 0,1, 0,1); - _popup[i].attach(*(new Gtk::SeparatorMenuItem()), 0,1, 1,2); - _popup[i].attach(_popup_lastused[i], 0,1, 2,3); - _popup[i].attach(_popup_lastselected[i], 0,1, 3,4); - _popup[i].attach(*(new Gtk::SeparatorMenuItem()), 0,1, 4,5); - _popup[i].attach(_popup_invert[i], 0,1, 5,6); - _popup[i].attach(*(new Gtk::SeparatorMenuItem()), 0,1, 6,7); - _popup[i].attach(_popup_white[i], 0,1, 7,8); - _popup[i].attach(_popup_black[i], 0,1, 8,9); - _popup[i].attach(*(new Gtk::SeparatorMenuItem()), 0,1, 9,10); - _popup[i].attach(_popup_copy[i], 0,1, 10,11); + _popup_swap[i].signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::on_fillstroke_swap)); + + _popup_opaque[i].add( + *(new Gtk::Label((i == SS_FILL) ? _("Make fill opaque") : _("Make stroke opaque"), Gtk::ALIGN_START))); + _popup_opaque[i].signal_activate().connect( + sigc::mem_fun(*this, (i == SS_FILL) ? &SelectedStyle::on_fill_opaque : &SelectedStyle::on_stroke_opaque)); + + // TRANSLATORS COMMENT: unset is a verb here + _popup_unset[i].add(*(new Gtk::Label((i == SS_FILL) ? _("Unset fill") : _("Unset stroke"), Gtk::ALIGN_START))); + _popup_unset[i].signal_activate().connect( + sigc::mem_fun(*this, (i == SS_FILL) ? &SelectedStyle::on_fill_unset : &SelectedStyle::on_stroke_unset)); + + _popup_remove[i].add( + *(new Gtk::Label((i == SS_FILL) ? _("Remove fill") : _("Remove stroke"), Gtk::ALIGN_START))); + _popup_remove[i].signal_activate().connect( + sigc::mem_fun(*this, (i == SS_FILL) ? &SelectedStyle::on_fill_remove : &SelectedStyle::on_stroke_remove)); + + _popup[i].attach(_popup_edit[i], 0, 1, 0, 1); + _popup[i].attach(*(new Gtk::SeparatorMenuItem()), 0, 1, 1, 2); + _popup[i].attach(_popup_lastused[i], 0, 1, 2, 3); + _popup[i].attach(_popup_lastselected[i], 0, 1, 3, 4); + _popup[i].attach(*(new Gtk::SeparatorMenuItem()), 0, 1, 4, 5); + _popup[i].attach(_popup_invert[i], 0, 1, 5, 6); + _popup[i].attach(*(new Gtk::SeparatorMenuItem()), 0, 1, 6, 7); + _popup[i].attach(_popup_white[i], 0, 1, 7, 8); + _popup[i].attach(_popup_black[i], 0, 1, 8, 9); + _popup[i].attach(*(new Gtk::SeparatorMenuItem()), 0, 1, 9, 10); + _popup[i].attach(_popup_copy[i], 0, 1, 10, 11); _popup_copy[i].set_sensitive(false); - _popup[i].attach(_popup_paste[i], 0,1, 11,12); - _popup[i].attach(_popup_swap[i], 0,1, 12,13); - _popup[i].attach(*(new Gtk::SeparatorMenuItem()), 0,1, 13,14); - _popup[i].attach(_popup_opaque[i], 0,1, 14,15); - _popup[i].attach(_popup_unset[i], 0,1, 15,16); - _popup[i].attach(_popup_remove[i], 0,1, 16,17); + _popup[i].attach(_popup_paste[i], 0, 1, 11, 12); + _popup[i].attach(_popup_swap[i], 0, 1, 12, 13); + _popup[i].attach(*(new Gtk::SeparatorMenuItem()), 0, 1, 13, 14); + _popup[i].attach(_popup_opaque[i], 0, 1, 14, 15); + _popup[i].attach(_popup_unset[i], 0, 1, 15, 16); + _popup[i].attach(_popup_remove[i], 0, 1, 16, 17); _popup[i].show_all(); _mode[i] = SS_NA; @@ -321,34 +314,35 @@ SelectedStyle::SelectedStyle(bool /*layout*/) 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()) { + while (iter != m.end()) { Gtk::RadioMenuItem *mi = Gtk::manage(new Gtk::RadioMenuItem(_sw_group)); mi->add(*(new Gtk::Label(iter->first, Gtk::ALIGN_START))); _unit_mis.push_back(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); + 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, row, row+1); + _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], Gtk::ALIGN_START))); mi->signal_activate().connect(sigc::bind<int>(sigc::mem_fun(*this, &SelectedStyle::on_popup_preset), i)); - _popup_sw.attach(*mi, 0,1, row, row+1); + _popup_sw.attach(*mi, 0, 1, row, row + 1); row++; } - _popup_sw.attach(*(new Gtk::SeparatorMenuItem()), 0,1, row, row+1); + _popup_sw.attach(*(new Gtk::SeparatorMenuItem()), 0, 1, row, row + 1); row++; _popup_sw_remove.add(*(new Gtk::Label(_("Remove"), Gtk::ALIGN_START))); _popup_sw_remove.signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::on_stroke_remove)); - _popup_sw.attach(_popup_sw_remove, 0,1, row, row+1); + _popup_sw.attach(_popup_sw_remove, 0, 1, row, row + 1); row++; _popup_sw.show_all(); @@ -367,8 +361,8 @@ SelectedStyle::SelectedStyle(bool /*layout*/) _stroke.pack_start(_stroke_width_place, Gtk::PACK_SHRINK); _opacity_sb.set_adjustment(_opacity_adjustment); - _opacity_sb.set_size_request (SELECTED_STYLE_SB_WIDTH, -1); - _opacity_sb.set_sensitive (false); + _opacity_sb.set_size_request(SELECTED_STYLE_SB_WIDTH, -1); + _opacity_sb.set_sensitive(false); _table.attach(_fill_label, 0, 0, 1, 1); _table.attach(_stroke_label, 0, 1, 1, 1); @@ -386,25 +380,19 @@ SelectedStyle::SelectedStyle(bool /*layout*/) pack_start(_table, true, true, 2); - set_size_request (SELECTED_STYLE_WIDTH, -1); + set_size_request(SELECTED_STYLE_WIDTH, -1); _drop[SS_FILL] = new DropTracker(); - ((DropTracker*)_drop[SS_FILL])->parent = this; - ((DropTracker*)_drop[SS_FILL])->item = SS_FILL; + ((DropTracker *)_drop[SS_FILL])->parent = this; + ((DropTracker *)_drop[SS_FILL])->item = SS_FILL; _drop[SS_STROKE] = new DropTracker(); - ((DropTracker*)_drop[SS_STROKE])->parent = this; - ((DropTracker*)_drop[SS_STROKE])->item = SS_STROKE; + ((DropTracker *)_drop[SS_STROKE])->parent = this; + ((DropTracker *)_drop[SS_STROKE])->item = SS_STROKE; - g_signal_connect(_stroke_place.gobj(), - "drag_data_received", - G_CALLBACK(dragDataReceived), - _drop[SS_STROKE]); + g_signal_connect(_stroke_place.gobj(), "drag_data_received", G_CALLBACK(dragDataReceived), _drop[SS_STROKE]); - g_signal_connect(_fill_place.gobj(), - "drag_data_received", - G_CALLBACK(dragDataReceived), - _drop[SS_FILL]); + g_signal_connect(_fill_place.gobj(), "drag_data_received", G_CALLBACK(dragDataReceived), _drop[SS_FILL]); _fill_place.signal_button_release_event().connect(sigc::mem_fun(*this, &SelectedStyle::on_fill_click)); _stroke_place.signal_button_release_event().connect(sigc::mem_fun(*this, &SelectedStyle::on_stroke_click)); @@ -432,37 +420,27 @@ SelectedStyle::~SelectedStyle() delete _color_preview[i]; } - delete (DropTracker*)_drop[SS_FILL]; - delete (DropTracker*)_drop[SS_STROKE]; + delete (DropTracker *)_drop[SS_FILL]; + delete (DropTracker *)_drop[SS_STROKE]; } -void -SelectedStyle::setDesktop(SPDesktop *desktop) +void SelectedStyle::setDesktop(SPDesktop *desktop) { _desktop = desktop; Inkscape::Selection *selection = desktop->getSelection(); - selection_changed_connection = new sigc::connection (selection->connectChanged( - sigc::bind ( - sigc::ptr_fun(&ss_selection_changed), - this ) - )); - selection_modified_connection = new sigc::connection (selection->connectModified( - sigc::bind ( - sigc::ptr_fun(&ss_selection_modified), - this ) - )); - subselection_changed_connection = new sigc::connection (desktop->connectToolSubselectionChanged( - sigc::bind ( - sigc::ptr_fun(&ss_subselection_changed), - this ) - )); + selection_changed_connection = + new sigc::connection(selection->connectChanged(sigc::bind(sigc::ptr_fun(&ss_selection_changed), this))); + selection_modified_connection = + new sigc::connection(selection->connectModified(sigc::bind(sigc::ptr_fun(&ss_selection_modified), this))); + subselection_changed_connection = new sigc::connection( + desktop->connectToolSubselectionChanged(sigc::bind(sigc::ptr_fun(&ss_subselection_changed), this))); _sw_unit = desktop->getNamedView()->display_units; // Set the doc default unit active in the units list - for ( auto mi:_unit_mis ) { + for (auto mi : _unit_mis) { if (mi && mi->get_label() == _sw_unit->abbr) { mi->set_active(); break; @@ -470,15 +448,10 @@ SelectedStyle::setDesktop(SPDesktop *desktop) } } -void SelectedStyle::dragDataReceived( GtkWidget */*widget*/, - GdkDragContext */*drag_context*/, - gint /*x*/, gint /*y*/, - GtkSelectionData *data, - guint /*info*/, - guint /*event_time*/, - gpointer user_data ) +void SelectedStyle::dragDataReceived(GtkWidget * /*widget*/, GdkDragContext * /*drag_context*/, gint /*x*/, gint /*y*/, + GtkSelectionData *data, guint /*info*/, guint /*event_time*/, gpointer user_data) { - DropTracker* tracker = (DropTracker*)user_data; + DropTracker *tracker = (DropTracker *)user_data; // copied from drag-and-drop.cpp, case APP_OSWB_COLOR bool worked = false; @@ -487,8 +460,7 @@ void SelectedStyle::dragDataReceived( GtkWidget */*widget*/, ege::PaintDef color; worked = color.fromMIMEData("application/x-oswb-color", reinterpret_cast<char const *>(gtk_selection_data_get_data(data)), - gtk_selection_data_get_length(data), - gtk_selection_data_get_format(data)); + gtk_selection_data_get_length(data), gtk_selection_data_get_format(data)); if (worked) { if (color.getType() == ege::PaintDef::CLEAR) { colorspec = ""; // TODO check if this is sufficient @@ -499,7 +471,7 @@ void SelectedStyle::dragDataReceived( GtkWidget */*widget*/, unsigned int g = color.getG(); unsigned int b = color.getB(); - gchar* tmp = g_strdup_printf("#%02x%02x%02x", r, g, b); + gchar *tmp = g_strdup_printf("#%02x%02x%02x", r, g, b); colorspec = tmp; g_free(tmp); } @@ -507,7 +479,7 @@ void SelectedStyle::dragDataReceived( GtkWidget */*widget*/, } if (worked) { SPCSSAttr *css = sp_repr_css_attr_new(); - sp_repr_css_set_property(css, (tracker->item == SS_FILL) ? "fill":"stroke", colorspec.c_str()); + sp_repr_css_set_property(css, (tracker->item == SS_FILL) ? "fill" : "stroke", colorspec.c_str()); sp_desktop_set_style(tracker->parent->_desktop, css); sp_repr_css_attr_unref(css); @@ -515,215 +487,207 @@ void SelectedStyle::dragDataReceived( GtkWidget */*widget*/, } } -void SelectedStyle::on_fill_remove() { - SPCSSAttr *css = sp_repr_css_attr_new (); - sp_repr_css_set_property (css, "fill", "none"); - sp_desktop_set_style (_desktop, css, true, true); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Remove fill")); +void SelectedStyle::on_fill_remove() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "fill", "none"); + sp_desktop_set_style(_desktop, css, true, true); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Remove fill")); } -void SelectedStyle::on_stroke_remove() { - SPCSSAttr *css = sp_repr_css_attr_new (); - sp_repr_css_set_property (css, "stroke", "none"); - sp_desktop_set_style (_desktop, css, true, true); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Remove stroke")); +void SelectedStyle::on_stroke_remove() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "stroke", "none"); + sp_desktop_set_style(_desktop, css, true, true); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Remove stroke")); } -void SelectedStyle::on_fill_unset() { - SPCSSAttr *css = sp_repr_css_attr_new (); - sp_repr_css_unset_property (css, "fill"); - sp_desktop_set_style (_desktop, css, true, true); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Unset fill")); +void SelectedStyle::on_fill_unset() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_unset_property(css, "fill"); + sp_desktop_set_style(_desktop, css, true, true); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Unset fill")); } -void SelectedStyle::on_stroke_unset() { - SPCSSAttr *css = sp_repr_css_attr_new (); - sp_repr_css_unset_property (css, "stroke"); - sp_repr_css_unset_property (css, "stroke-opacity"); - sp_repr_css_unset_property (css, "stroke-width"); - sp_repr_css_unset_property (css, "stroke-miterlimit"); - sp_repr_css_unset_property (css, "stroke-linejoin"); - sp_repr_css_unset_property (css, "stroke-linecap"); - sp_repr_css_unset_property (css, "stroke-dashoffset"); - sp_repr_css_unset_property (css, "stroke-dasharray"); - sp_desktop_set_style (_desktop, css, true, true); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Unset stroke")); +void SelectedStyle::on_stroke_unset() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_unset_property(css, "stroke"); + sp_repr_css_unset_property(css, "stroke-opacity"); + sp_repr_css_unset_property(css, "stroke-width"); + sp_repr_css_unset_property(css, "stroke-miterlimit"); + sp_repr_css_unset_property(css, "stroke-linejoin"); + sp_repr_css_unset_property(css, "stroke-linecap"); + sp_repr_css_unset_property(css, "stroke-dashoffset"); + sp_repr_css_unset_property(css, "stroke-dasharray"); + sp_desktop_set_style(_desktop, css, true, true); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Unset stroke")); } -void SelectedStyle::on_fill_opaque() { - SPCSSAttr *css = sp_repr_css_attr_new (); - sp_repr_css_set_property (css, "fill-opacity", "1"); - sp_desktop_set_style (_desktop, css, true); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Make fill opaque")); +void SelectedStyle::on_fill_opaque() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "fill-opacity", "1"); + sp_desktop_set_style(_desktop, css, true); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Make fill opaque")); } -void SelectedStyle::on_stroke_opaque() { - SPCSSAttr *css = sp_repr_css_attr_new (); - sp_repr_css_set_property (css, "stroke-opacity", "1"); - sp_desktop_set_style (_desktop, css, true); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Make fill opaque")); +void SelectedStyle::on_stroke_opaque() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "stroke-opacity", "1"); + sp_desktop_set_style(_desktop, css, true); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Make fill opaque")); } -void SelectedStyle::on_fill_lastused() { - SPCSSAttr *css = sp_repr_css_attr_new (); +void SelectedStyle::on_fill_lastused() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); guint32 color = sp_desktop_get_color(_desktop, true); gchar c[64]; - sp_svg_write_color (c, sizeof(c), color); - sp_repr_css_set_property (css, "fill", c); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Apply last set color to fill")); + sp_svg_write_color(c, sizeof(c), color); + sp_repr_css_set_property(css, "fill", c); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Apply last set color to fill")); } -void SelectedStyle::on_stroke_lastused() { - SPCSSAttr *css = sp_repr_css_attr_new (); +void SelectedStyle::on_stroke_lastused() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); guint32 color = sp_desktop_get_color(_desktop, false); gchar c[64]; - sp_svg_write_color (c, sizeof(c), color); - sp_repr_css_set_property (css, "stroke", c); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Apply last set color to stroke")); + sp_svg_write_color(c, sizeof(c), color); + sp_repr_css_set_property(css, "stroke", c); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Apply last set color to stroke")); } -void SelectedStyle::on_fill_lastselected() { - SPCSSAttr *css = sp_repr_css_attr_new (); +void SelectedStyle::on_fill_lastselected() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); gchar c[64]; - sp_svg_write_color (c, sizeof(c), _lastselected[SS_FILL]); - sp_repr_css_set_property (css, "fill", c); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Apply last selected color to fill")); + sp_svg_write_color(c, sizeof(c), _lastselected[SS_FILL]); + sp_repr_css_set_property(css, "fill", c); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Apply last selected color to fill")); } -void SelectedStyle::on_stroke_lastselected() { - SPCSSAttr *css = sp_repr_css_attr_new (); +void SelectedStyle::on_stroke_lastselected() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); gchar c[64]; - sp_svg_write_color (c, sizeof(c), _lastselected[SS_STROKE]); - sp_repr_css_set_property (css, "stroke", c); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Apply last selected color to stroke")); + sp_svg_write_color(c, sizeof(c), _lastselected[SS_STROKE]); + sp_repr_css_set_property(css, "stroke", c); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Apply last selected color to stroke")); } -void SelectedStyle::on_fill_invert() { - SPCSSAttr *css = sp_repr_css_attr_new (); +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( - (255 - SP_RGBA32_R_U(color)), - (255 - SP_RGBA32_G_U(color)), - (255 - SP_RGBA32_B_U(color)), - SP_RGBA32_A_U(color) - ) - ); - sp_repr_css_set_property (css, "fill", c); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Invert fill")); + if (_mode[SS_FILL] != SS_COLOR) + return; + sp_svg_write_color(c, sizeof(c), + SP_RGBA32_U_COMPOSE((255 - SP_RGBA32_R_U(color)), (255 - SP_RGBA32_G_U(color)), + (255 - SP_RGBA32_B_U(color)), SP_RGBA32_A_U(color))); + sp_repr_css_set_property(css, "fill", c); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Invert fill")); } -void SelectedStyle::on_stroke_invert() { - SPCSSAttr *css = sp_repr_css_attr_new (); +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( - (255 - SP_RGBA32_R_U(color)), - (255 - SP_RGBA32_G_U(color)), - (255 - SP_RGBA32_B_U(color)), - SP_RGBA32_A_U(color) - ) - ); - sp_repr_css_set_property (css, "stroke", c); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Invert stroke")); + if (_mode[SS_STROKE] != SS_COLOR) + return; + sp_svg_write_color(c, sizeof(c), + SP_RGBA32_U_COMPOSE((255 - SP_RGBA32_R_U(color)), (255 - SP_RGBA32_G_U(color)), + (255 - SP_RGBA32_B_U(color)), SP_RGBA32_A_U(color))); + sp_repr_css_set_property(css, "stroke", c); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Invert stroke")); } -void SelectedStyle::on_fill_white() { - SPCSSAttr *css = sp_repr_css_attr_new (); +void SelectedStyle::on_fill_white() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); gchar c[64]; - sp_svg_write_color (c, sizeof(c), 0xffffffff); - sp_repr_css_set_property (css, "fill", c); - sp_repr_css_set_property (css, "fill-opacity", "1"); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("White fill")); + sp_svg_write_color(c, sizeof(c), 0xffffffff); + sp_repr_css_set_property(css, "fill", c); + sp_repr_css_set_property(css, "fill-opacity", "1"); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("White fill")); } -void SelectedStyle::on_stroke_white() { - SPCSSAttr *css = sp_repr_css_attr_new (); +void SelectedStyle::on_stroke_white() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); gchar c[64]; - sp_svg_write_color (c, sizeof(c), 0xffffffff); - sp_repr_css_set_property (css, "stroke", c); - sp_repr_css_set_property (css, "stroke-opacity", "1"); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("White stroke")); + sp_svg_write_color(c, sizeof(c), 0xffffffff); + sp_repr_css_set_property(css, "stroke", c); + sp_repr_css_set_property(css, "stroke-opacity", "1"); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("White stroke")); } -void SelectedStyle::on_fill_black() { - SPCSSAttr *css = sp_repr_css_attr_new (); +void SelectedStyle::on_fill_black() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); gchar c[64]; - sp_svg_write_color (c, sizeof(c), 0x000000ff); - sp_repr_css_set_property (css, "fill", c); - sp_repr_css_set_property (css, "fill-opacity", "1.0"); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Black fill")); + sp_svg_write_color(c, sizeof(c), 0x000000ff); + sp_repr_css_set_property(css, "fill", c); + sp_repr_css_set_property(css, "fill-opacity", "1.0"); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Black fill")); } -void SelectedStyle::on_stroke_black() { - SPCSSAttr *css = sp_repr_css_attr_new (); +void SelectedStyle::on_stroke_black() +{ + SPCSSAttr *css = sp_repr_css_attr_new(); gchar c[64]; - sp_svg_write_color (c, sizeof(c), 0x000000ff); - sp_repr_css_set_property (css, "stroke", c); - sp_repr_css_set_property (css, "stroke-opacity", "1.0"); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Black stroke")); + sp_svg_write_color(c, sizeof(c), 0x000000ff); + sp_repr_css_set_property(css, "stroke", c); + sp_repr_css_set_property(css, "stroke-opacity", "1.0"); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Black stroke")); } -void SelectedStyle::on_fill_copy() { +void SelectedStyle::on_fill_copy() +{ if (_mode[SS_FILL] == SS_COLOR) { gchar c[64]; - sp_svg_write_color (c, sizeof(c), _thisselected[SS_FILL]); + sp_svg_write_color(c, sizeof(c), _thisselected[SS_FILL]); Glib::ustring text; text += c; if (!text.empty()) { @@ -733,10 +697,11 @@ void SelectedStyle::on_fill_copy() { } } -void SelectedStyle::on_stroke_copy() { +void SelectedStyle::on_stroke_copy() +{ if (_mode[SS_STROKE] == SS_COLOR) { gchar c[64]; - sp_svg_write_color (c, sizeof(c), _thisselected[SS_STROKE]); + sp_svg_write_color(c, sizeof(c), _thisselected[SS_STROKE]); Glib::ustring text; text += c; if (!text.empty()) { @@ -746,58 +711,62 @@ void SelectedStyle::on_stroke_copy() { } } -void SelectedStyle::on_fill_paste() { +void SelectedStyle::on_fill_paste() +{ Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get(); Glib::ustring const text = refClipboard->wait_for_text(); if (!text.empty()) { - guint32 color = sp_svg_read_color(text.c_str(), 0x000000ff); // impossible value, as SVG color cannot have opacity - if (color == 0x000000ff) // failed to parse color string + guint32 color = + sp_svg_read_color(text.c_str(), 0x000000ff); // impossible value, as SVG color cannot have opacity + if (color == 0x000000ff) // failed to parse color string return; - SPCSSAttr *css = sp_repr_css_attr_new (); - sp_repr_css_set_property (css, "fill", text.c_str()); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Paste fill")); + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "fill", text.c_str()); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Paste fill")); } } -void SelectedStyle::on_stroke_paste() { +void SelectedStyle::on_stroke_paste() +{ Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get(); Glib::ustring const text = refClipboard->wait_for_text(); if (!text.empty()) { - guint32 color = sp_svg_read_color(text.c_str(), 0x000000ff); // impossible value, as SVG color cannot have opacity - if (color == 0x000000ff) // failed to parse color string + guint32 color = + sp_svg_read_color(text.c_str(), 0x000000ff); // impossible value, as SVG color cannot have opacity + if (color == 0x000000ff) // failed to parse color string return; - SPCSSAttr *css = sp_repr_css_attr_new (); - sp_repr_css_set_property (css, "stroke", text.c_str()); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Paste stroke")); + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "stroke", text.c_str()); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Paste stroke")); } } -void SelectedStyle::on_fillstroke_swap() { +void SelectedStyle::on_fillstroke_swap() +{ _desktop->getSelection()->swapFillStroke(); } -void SelectedStyle::on_fill_edit() { +void SelectedStyle::on_fill_edit() +{ if (Dialog::FillAndStroke *fs = get_fill_and_stroke_panel(_desktop)) fs->showPageFill(); } -void SelectedStyle::on_stroke_edit() { +void SelectedStyle::on_stroke_edit() +{ if (Dialog::FillAndStroke *fs = get_fill_and_stroke_panel(_desktop)) fs->showPageStrokePaint(); } -bool -SelectedStyle::on_fill_click(GdkEventButton *event) +bool SelectedStyle::on_fill_click(GdkEventButton *event) { if (event->button == 1) { // click, open fill&stroke @@ -816,8 +785,7 @@ SelectedStyle::on_fill_click(GdkEventButton *event) return true; } -bool -SelectedStyle::on_stroke_click(GdkEventButton *event) +bool SelectedStyle::on_stroke_click(GdkEventButton *event) { if (event->button == 1) { // click, open fill&stroke if (Dialog::FillAndStroke *fs = get_fill_and_stroke_panel(_desktop)) @@ -834,8 +802,7 @@ SelectedStyle::on_stroke_click(GdkEventButton *event) return true; } -bool -SelectedStyle::on_sw_click(GdkEventButton *event) +bool SelectedStyle::on_sw_click(GdkEventButton *event) { if (event->button == 1) { // click, open fill&stroke if (Dialog::FillAndStroke *fs = get_fill_and_stroke_panel(_desktop)) @@ -848,30 +815,30 @@ SelectedStyle::on_sw_click(GdkEventButton *event) return true; } -bool -SelectedStyle::on_opacity_click(GdkEventButton *event) +bool SelectedStyle::on_opacity_click(GdkEventButton *event) { if (event->button == 2) { // middle click - const char* opacity = _opacity_sb.get_value() < 50? "0.5" : (_opacity_sb.get_value() == 100? "0" : "1"); - SPCSSAttr *css = sp_repr_css_attr_new (); - sp_repr_css_set_property (css, "opacity", opacity); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, - _("Change opacity")); + const char *opacity = _opacity_sb.get_value() < 50 ? "0.5" : (_opacity_sb.get_value() == 100 ? "0" : "1"); + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "opacity", opacity); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_FILL_STROKE, _("Change opacity")); return true; } return false; } -void SelectedStyle::on_popup_units(Inkscape::Util::Unit const *unit) { +void SelectedStyle::on_popup_units(Inkscape::Util::Unit const *unit) +{ _sw_unit = unit; update(); } -void SelectedStyle::on_popup_preset(int i) { - SPCSSAttr *css = sp_repr_css_attr_new (); +void SelectedStyle::on_popup_preset(int i) +{ + SPCSSAttr *css = sp_repr_css_attr_new(); gdouble w; if (_sw_unit) { w = Inkscape::Util::Quantity::convert(_sw_presets[i], _sw_unit, "px"); @@ -880,16 +847,14 @@ void SelectedStyle::on_popup_preset(int i) { } Inkscape::CSSOStringStream os; os << w; - sp_repr_css_set_property (css, "stroke-width", os.str().c_str()); + sp_repr_css_set_property(css, "stroke-width", os.str().c_str()); // FIXME: update dash patterns! - sp_desktop_set_style (_desktop, css, true); - sp_repr_css_attr_unref (css); - DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_SWATCHES, - _("Change stroke width")); + sp_desktop_set_style(_desktop, css, true); + sp_repr_css_attr_unref(css); + DocumentUndo::done(_desktop->getDocument(), SP_VERB_DIALOG_SWATCHES, _("Change stroke width")); } -void -SelectedStyle::update() +void SelectedStyle::update() { if (_desktop == nullptr) return; @@ -898,8 +863,8 @@ SelectedStyle::update() SPStyle query(_desktop->getDocument()); for (int i = SS_FILL; i <= SS_STROKE; i++) { - Gtk::EventBox *place = (i == SS_FILL)? &_fill_place : &_stroke_place; - Gtk::EventBox *flag_place = (i == SS_FILL)? &_fill_flag_place : &_stroke_flag_place; + Gtk::EventBox *place = (i == SS_FILL) ? &_fill_place : &_stroke_place; + Gtk::EventBox *flag_place = (i == SS_FILL) ? &_fill_flag_place : &_stroke_flag_place; place->remove(); flag_place->remove(); @@ -912,193 +877,206 @@ SelectedStyle::update() _popup_copy[i].set_sensitive(false); - // query style from desktop. This returns a result flag and fills query with the style of subselection, if any, or selection - int result = sp_desktop_query_style (_desktop, &query, - (i == SS_FILL)? QUERY_STYLE_PROPERTY_FILL : QUERY_STYLE_PROPERTY_STROKE); + // query style from desktop. This returns a result flag and fills query with the style of subselection, if any, + // or selection + int result = sp_desktop_query_style(_desktop, &query, + (i == SS_FILL) ? QUERY_STYLE_PROPERTY_FILL : QUERY_STYLE_PROPERTY_STROKE); switch (result) { - case QUERY_STYLE_NOTHING: - place->add(_na[i]); - place->set_tooltip_text(__na[i]); - _mode[i] = SS_NA; - if ( _dropEnabled[i] ) { - gtk_drag_dest_unset( GTK_WIDGET((i==SS_FILL) ? _fill_place.gobj():_stroke_place.gobj()) ); - _dropEnabled[i] = false; - } - break; - case QUERY_STYLE_SINGLE: - case QUERY_STYLE_MULTIPLE_AVERAGED: - case QUERY_STYLE_MULTIPLE_SAME: - if ( !_dropEnabled[i] ) { - gtk_drag_dest_set( GTK_WIDGET( (i==SS_FILL) ? _fill_place.gobj():_stroke_place.gobj()), - GTK_DEST_DEFAULT_ALL, - ui_drop_target_entries, - nui_drop_target_entries, - GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) ); - _dropEnabled[i] = true; - } - SPIPaint *paint; - if (i == SS_FILL) { - paint = &(query.fill); - } else { - paint = &(query.stroke); - } - if (paint->set && paint->isPaintserver()) { - SPPaintServer *server = (i == SS_FILL)? SP_STYLE_FILL_SERVER (&query) : SP_STYLE_STROKE_SERVER (&query); - if ( server ) { - Inkscape::XML::Node *srepr = server->getRepr(); - _paintserver_id[i] += "url(#"; - _paintserver_id[i] += srepr->attribute("id"); - _paintserver_id[i] += ")"; - - if (SP_IS_LINEARGRADIENT(server)) { - SPGradient *vector = SP_GRADIENT(server)->getVector(); - _gradient_preview_l[i]->set_gradient(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(); - _gradient_preview_r[i]->set_gradient(vector); - place->add(_gradient_box_r[i]); - place->set_tooltip_text(__rgradient[i]); - _mode[i] = SS_RGRADIENT; + case QUERY_STYLE_NOTHING: + place->add(_na[i]); + place->set_tooltip_text(__na[i]); + _mode[i] = SS_NA; + if (_dropEnabled[i]) { + gtk_drag_dest_unset(GTK_WIDGET((i == SS_FILL) ? _fill_place.gobj() : _stroke_place.gobj())); + _dropEnabled[i] = false; + } + break; + case QUERY_STYLE_SINGLE: + case QUERY_STYLE_MULTIPLE_AVERAGED: + case QUERY_STYLE_MULTIPLE_SAME: + if (!_dropEnabled[i]) { + gtk_drag_dest_set(GTK_WIDGET((i == SS_FILL) ? _fill_place.gobj() : _stroke_place.gobj()), + GTK_DEST_DEFAULT_ALL, ui_drop_target_entries, nui_drop_target_entries, + GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE)); + _dropEnabled[i] = true; + } + SPIPaint *paint; + if (i == SS_FILL) { + paint = &(query.fill); + } else { + paint = &(query.stroke); + } + if (paint->set && paint->isPaintserver()) { + SPPaintServer *server = + (i == SS_FILL) ? SP_STYLE_FILL_SERVER(&query) : SP_STYLE_STROKE_SERVER(&query); + if (server) { + Inkscape::XML::Node *srepr = server->getRepr(); + _paintserver_id[i] += "url(#"; + _paintserver_id[i] += srepr->attribute("id"); + _paintserver_id[i] += ")"; + + if (SP_IS_LINEARGRADIENT(server)) { + SPGradient *vector = SP_GRADIENT(server)->getVector(); + _gradient_preview_l[i]->set_gradient(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(); + _gradient_preview_r[i]->set_gradient(vector); + place->add(_gradient_box_r[i]); + place->set_tooltip_text(__rgradient[i]); + _mode[i] = SS_RGRADIENT; #ifdef WITH_MESH - } else if (SP_IS_MESHGRADIENT(server)) { - SPGradient *array = SP_GRADIENT(server)->getArray(); - _gradient_preview_m[i]->set_gradient(array); - place->add(_gradient_box_m[i]); - place->set_tooltip_text(__mgradient[i]); - _mode[i] = SS_MGRADIENT; + } else if (SP_IS_MESHGRADIENT(server)) { + SPGradient *array = SP_GRADIENT(server)->getArray(); + _gradient_preview_m[i]->set_gradient(array); + place->add(_gradient_box_m[i]); + place->set_tooltip_text(__mgradient[i]); + _mode[i] = SS_MGRADIENT; #endif - } else if (SP_IS_PATTERN(server)) { - place->add(_pattern[i]); - place->set_tooltip_text(__pattern[i]); - _mode[i] = SS_PATTERN; - } else if (SP_IS_HATCH(server)) { - place->add(_hatch[i]); - place->set_tooltip_text(__hatch[i]); - _mode[i] = SS_HATCH; + } else if (SP_IS_PATTERN(server)) { + place->add(_pattern[i]); + place->set_tooltip_text(__pattern[i]); + _mode[i] = SS_PATTERN; + } else if (SP_IS_HATCH(server)) { + place->add(_hatch[i]); + place->set_tooltip_text(__hatch[i]); + _mode[i] = SS_HATCH; + } + } else { + g_warning("file %s: line %d: Unknown paint server", __FILE__, __LINE__); } - } else { - g_warning ("file %s: line %d: Unknown paint server", __FILE__, __LINE__); + } else if (paint->set && paint->isColor()) { + 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; // include opacity + ((Inkscape::UI::Widget::ColorPreview *)_color_preview[i])->setRgba32(color); + _color_preview[i]->show_all(); + place->add(*_color_preview[i]); + gchar c_string[64]; + g_snprintf(c_string, 64, "%06x/%.3g", color >> 8, SP_RGBA32_A_F(color)); + place->set_tooltip_text(__color[i] + ": " + c_string + + _(", drag to adjust, middle-click to remove")); + _mode[i] = SS_COLOR; + _popup_copy[i].set_sensitive(true); + + } else if (paint->set && paint->isNone()) { + place->add(_none[i]); + place->set_tooltip_text(__none[i]); + _mode[i] = SS_NONE; + } else if (!paint->set) { + place->add(_unset[i]); + place->set_tooltip_text(__unset[i]); + _mode[i] = SS_UNSET; } - } else if (paint->set && paint->isColor()) { - 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; // include opacity - ((Inkscape::UI::Widget::ColorPreview*)_color_preview[i])->setRgba32 (color); - _color_preview[i]->show_all(); - place->add(*_color_preview[i]); - gchar c_string[64]; - g_snprintf (c_string, 64, "%06x/%.3g", color >> 8, SP_RGBA32_A_F(color)); - place->set_tooltip_text(__color[i] + ": " + c_string + _(", drag to adjust, middle-click to remove")); - _mode[i] = SS_COLOR; - _popup_copy[i].set_sensitive(true); - - } else if (paint->set && paint->isNone()) { - place->add(_none[i]); - place->set_tooltip_text(__none[i]); - _mode[i] = SS_NONE; - } else if (!paint->set) { - place->add(_unset[i]); - place->set_tooltip_text(__unset[i]); - _mode[i] = SS_UNSET; - } - if (result == QUERY_STYLE_MULTIPLE_AVERAGED) { - flag_place->add(_averaged[i]); - flag_place->set_tooltip_text(__averaged[i]); - } else if (result == QUERY_STYLE_MULTIPLE_SAME) { - flag_place->add(_multiple[i]); - flag_place->set_tooltip_text(__multiple[i]); - } - break; - case QUERY_STYLE_MULTIPLE_DIFFERENT: - place->add(_many[i]); - place->set_tooltip_text(__many[i]); - _mode[i] = SS_MANY; - break; - default: - break; + if (result == QUERY_STYLE_MULTIPLE_AVERAGED) { + flag_place->add(_averaged[i]); + flag_place->set_tooltip_text(__averaged[i]); + } else if (result == QUERY_STYLE_MULTIPLE_SAME) { + flag_place->add(_multiple[i]); + flag_place->set_tooltip_text(__multiple[i]); + } + break; + case QUERY_STYLE_MULTIPLE_DIFFERENT: + place->add(_many[i]); + place->set_tooltip_text(__many[i]); + _mode[i] = SS_MANY; + break; + default: + break; } } -// Now query opacity + // Now query opacity clearTooltip(_opacity_place); clearTooltip(_opacity_sb); - int result = sp_desktop_query_style (_desktop, &query, QUERY_STYLE_PROPERTY_MASTEROPACITY); + int result = sp_desktop_query_style(_desktop, &query, QUERY_STYLE_PROPERTY_MASTEROPACITY); switch (result) { - case QUERY_STYLE_NOTHING: - _opacity_place.set_tooltip_text(_("Nothing selected")); - _opacity_sb.set_tooltip_text(_("Nothing selected")); - _opacity_sb.set_sensitive(false); - break; - case QUERY_STYLE_SINGLE: - case QUERY_STYLE_MULTIPLE_AVERAGED: - case QUERY_STYLE_MULTIPLE_SAME: - _opacity_place.set_tooltip_text(_("Opacity (%)")); - _opacity_sb.set_tooltip_text(_("Opacity (%)")); - if (_opacity_blocked) break; - _opacity_blocked = true; - _opacity_sb.set_sensitive(true); - _opacity_adjustment->set_value(SP_SCALE24_TO_FLOAT(query.opacity.value) * 100); - _opacity_blocked = false; - break; + case QUERY_STYLE_NOTHING: + _opacity_place.set_tooltip_text(_("Nothing selected")); + _opacity_sb.set_tooltip_text(_("Nothing selected")); + _opacity_sb.set_sensitive(false); + break; + case QUERY_STYLE_SINGLE: + case QUERY_STYLE_MULTIPLE_AVERAGED: + case QUERY_STYLE_MULTIPLE_SAME: + _opacity_place.set_tooltip_text(_("Opacity (%)")); + _opacity_sb.set_tooltip_text(_("Opacity (%)")); + if (_opacity_blocked) + break; + _opacity_blocked = true; + _opacity_sb.set_sensitive(true); + _opacity_adjustment->set_value(SP_SCALE24_TO_FLOAT(query.opacity.value) * 100); + _opacity_blocked = false; + break; } -// Now query stroke_width - int result_sw = sp_desktop_query_style (_desktop, &query, QUERY_STYLE_PROPERTY_STROKEWIDTH); + // Now query stroke_width + int result_sw = sp_desktop_query_style(_desktop, &query, QUERY_STYLE_PROPERTY_STROKEWIDTH); switch (result_sw) { - case QUERY_STYLE_NOTHING: - _stroke_width.set_markup(""); - current_stroke_width = 0; - break; - case QUERY_STYLE_SINGLE: - case QUERY_STYLE_MULTIPLE_AVERAGED: - case QUERY_STYLE_MULTIPLE_SAME: - { - double w; - if (_sw_unit) { - w = Inkscape::Util::Quantity::convert(query.stroke_width.computed, "px", _sw_unit); - } else { - w = query.stroke_width.computed; - } - current_stroke_width = w; + case QUERY_STYLE_NOTHING: + _stroke_width.set_markup(""); + current_stroke_width = 0; + break; + case QUERY_STYLE_SINGLE: + case QUERY_STYLE_MULTIPLE_AVERAGED: + case QUERY_STYLE_MULTIPLE_SAME: { + double w; + if (_sw_unit) { + w = Inkscape::Util::Quantity::convert(query.stroke_width.computed, "px", _sw_unit); + } else { + w = query.stroke_width.computed; + } + current_stroke_width = w; - { - gchar *str = g_strdup_printf(" %#.3g", w); - if (str[strlen(str) - 1] == ',' || str[strlen(str) - 1] == '.') { - str[strlen(str)-1] = '\0'; + { + gchar *str = g_strdup_printf(" %#.3g", w); + if (str[strlen(str) - 1] == ',' || str[strlen(str) - 1] == '.') { + str[strlen(str) - 1] = '\0'; + } + _stroke_width.set_markup(str); + g_free(str); } - _stroke_width.set_markup(str); - g_free (str); - } - { - gchar *str = g_strdup_printf(_("Stroke width: %.5g%s%s"), - w, - _sw_unit? _sw_unit->abbr.c_str() : "px", - (result_sw == QUERY_STYLE_MULTIPLE_AVERAGED)? - _(" (averaged)") : ""); - _stroke_width_place.set_tooltip_text(str); - g_free (str); + { + gchar *str = g_strdup_printf(_("Stroke width: %.5g%s%s"), w, _sw_unit ? _sw_unit->abbr.c_str() : "px", + (result_sw == QUERY_STYLE_MULTIPLE_AVERAGED) ? _(" (averaged)") : ""); + _stroke_width_place.set_tooltip_text(str); + g_free(str); + } + break; } - break; - } - default: - break; + default: + break; } } -void SelectedStyle::opacity_0() {_opacity_sb.set_value(0);} -void SelectedStyle::opacity_025() {_opacity_sb.set_value(25);} -void SelectedStyle::opacity_05() {_opacity_sb.set_value(50);} -void SelectedStyle::opacity_075() {_opacity_sb.set_value(75);} -void SelectedStyle::opacity_1() {_opacity_sb.set_value(100);} - -void SelectedStyle::on_opacity_menu (Gtk::Menu *menu) { +void SelectedStyle::opacity_0() +{ + _opacity_sb.set_value(0); +} +void SelectedStyle::opacity_025() +{ + _opacity_sb.set_value(25); +} +void SelectedStyle::opacity_05() +{ + _opacity_sb.set_value(50); +} +void SelectedStyle::opacity_075() +{ + _opacity_sb.set_value(75); +} +void SelectedStyle::opacity_1() +{ + _opacity_sb.set_value(100); +} +void SelectedStyle::on_opacity_menu(Gtk::Menu *menu) +{ std::vector<Gtk::Widget *> children = menu->get_children(); for (auto iter : children) { menu->remove(*iter); @@ -1107,47 +1085,47 @@ void SelectedStyle::on_opacity_menu (Gtk::Menu *menu) { { Gtk::MenuItem *item = new Gtk::MenuItem; item->add(*(new Gtk::Label(_("0 (transparent)"), Gtk::ALIGN_START, Gtk::ALIGN_START))); - item->signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::opacity_0 )); + item->signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::opacity_0)); menu->add(*item); } { Gtk::MenuItem *item = new Gtk::MenuItem; item->add(*(new Gtk::Label("25%", Gtk::ALIGN_START, Gtk::ALIGN_START))); - item->signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::opacity_025 )); + item->signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::opacity_025)); menu->add(*item); } { Gtk::MenuItem *item = new Gtk::MenuItem; item->add(*(new Gtk::Label("50%", Gtk::ALIGN_START, Gtk::ALIGN_START))); - item->signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::opacity_05 )); + item->signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::opacity_05)); menu->add(*item); } { Gtk::MenuItem *item = new Gtk::MenuItem; item->add(*(new Gtk::Label("75%", Gtk::ALIGN_START, Gtk::ALIGN_START))); - item->signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::opacity_075 )); + item->signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::opacity_075)); menu->add(*item); } { Gtk::MenuItem *item = new Gtk::MenuItem; item->add(*(new Gtk::Label(_("100% (opaque)"), Gtk::ALIGN_START, Gtk::ALIGN_START))); - item->signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::opacity_1 )); + item->signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::opacity_1)); menu->add(*item); } menu->show_all(); } -void SelectedStyle::on_opacity_changed () +void SelectedStyle::on_opacity_changed() { g_return_if_fail(_desktop); // TODO this shouldn't happen! if (_opacity_blocked) return; _opacity_blocked = true; - SPCSSAttr *css = sp_repr_css_attr_new (); + SPCSSAttr *css = sp_repr_css_attr_new(); Inkscape::CSSOStringStream os; - os << CLAMP ((_opacity_adjustment->get_value() / 100), 0.0, 1.0); - sp_repr_css_set_property (css, "opacity", os.str().c_str()); + os << CLAMP((_opacity_adjustment->get_value() / 100), 0.0, 1.0); + sp_repr_css_set_property(css, "opacity", os.str().c_str()); // FIXME: workaround for GTK breakage: display interruptibility sometimes results in GTK // sending multiple value-changed events. As if when Inkscape interrupts redraw for main loop @@ -1157,8 +1135,8 @@ void SelectedStyle::on_opacity_changed () // or 0.0. (And no, this is not a race with ::update, I checked that.) // Sigh. So we disable interruptibility while we're setting the new value. _desktop->getCanvas()->forced_redraws_start(0); - sp_desktop_set_style (_desktop, css); - sp_repr_css_attr_unref (css); + sp_desktop_set_style(_desktop, css); + sp_repr_css_attr_unref(css); DocumentUndo::maybeDone(_desktop->getDocument(), "fillstroke:opacity", SP_VERB_DIALOG_FILL_STROKE, _("Change opacity")); // resume interruptibility @@ -1168,24 +1146,22 @@ void SelectedStyle::on_opacity_changed () /* ============================================= RotateableSwatch */ -RotateableSwatch::RotateableSwatch(SelectedStyle *parent, guint mode) : - fillstroke(mode), - parent(parent), - startcolor(0), - startcolor_set(false), - undokey("ssrot1"), - cr(nullptr), - cr_set(false) +RotateableSwatch::RotateableSwatch(SelectedStyle *parent, guint mode) + : fillstroke(mode) + , parent(parent) + , startcolor(0) + , startcolor_set(false) + , undokey("ssrot1") + , cr(nullptr) + , cr_set(false) -{ -} +{} RotateableSwatch::~RotateableSwatch() = default; -double -RotateableSwatch::color_adjust(float *hsla, double by, guint32 cc, guint modifier) +double RotateableSwatch::color_adjust(float *hsla, double by, guint32 cc, guint modifier) { - SPColor::rgb_to_hsl_floatv (hsla, SP_RGBA32_R_F(cc), SP_RGBA32_G_F(cc), SP_RGBA32_B_F(cc)); + SPColor::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 @@ -1206,7 +1182,7 @@ RotateableSwatch::color_adjust(float *hsla, double by, guint32 cc, guint modifie diff = hsla[2] - old; } else if (modifier == 3) { // alpha double old = hsla[3]; - hsla[3] += by/2; + hsla[3] += by / 2; if (hsla[3] < 0) { hsla[3] = 0; } else if (hsla[3] > 1) { @@ -1215,7 +1191,7 @@ RotateableSwatch::color_adjust(float *hsla, double by, guint32 cc, guint modifie diff = hsla[3] - old; } else { // hue double old = hsla[0]; - hsla[0] += by/2; + hsla[0] += by / 2; while (hsla[0] < 0) hsla[0] += 1; while (hsla[0] > 1) @@ -1224,34 +1200,30 @@ RotateableSwatch::color_adjust(float *hsla, double by, guint32 cc, guint modifie } float rgb[3]; - SPColor::hsl_to_rgb_floatv (rgb, hsla[0], hsla[1], hsla[2]); + SPColor::hsl_to_rgb_floatv(rgb, hsla[0], hsla[1], hsla[2]); gchar c[64]; - sp_svg_write_color (c, sizeof(c), - SP_RGBA32_U_COMPOSE( - (SP_COLOR_F_TO_U(rgb[0])), - (SP_COLOR_F_TO_U(rgb[1])), - (SP_COLOR_F_TO_U(rgb[2])), - 0xff - ) - ); + sp_svg_write_color( + c, sizeof(c), + SP_RGBA32_U_COMPOSE((SP_COLOR_F_TO_U(rgb[0])), (SP_COLOR_F_TO_U(rgb[1])), (SP_COLOR_F_TO_U(rgb[2])), 0xff)); - SPCSSAttr *css = sp_repr_css_attr_new (); + SPCSSAttr *css = sp_repr_css_attr_new(); 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()); + 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_repr_css_set_property(css, (fillstroke == SS_FILL) ? "fill" : "stroke", c); } - sp_desktop_set_style (parent->getDesktop(), css); - sp_repr_css_attr_unref (css); + sp_desktop_set_style(parent->getDesktop(), css); + sp_repr_css_attr_unref(css); return diff; } -void -RotateableSwatch::do_motion(double by, guint modifier) { +void RotateableSwatch::do_motion(double by, guint modifier) +{ if (parent->_mode[fillstroke] != SS_COLOR) return; @@ -1293,40 +1265,55 @@ RotateableSwatch::do_motion(double by, guint modifier) { diff = color_adjust(hsla, by, cc, modifier); if (modifier == 3) { // alpha - DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, - SP_VERB_DIALOG_FILL_STROKE, (_("Adjust alpha"))); + DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), 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); + 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(parent->getDesktop()->getDocument(), undokey, - SP_VERB_DIALOG_FILL_STROKE, (_("Adjust saturation"))); + DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, SP_VERB_DIALOG_FILL_STROKE, + (_("Adjust saturation"))); 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); + 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(parent->getDesktop()->getDocument(), undokey, - SP_VERB_DIALOG_FILL_STROKE, (_("Adjust lightness"))); + DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, SP_VERB_DIALOG_FILL_STROKE, + (_("Adjust lightness"))); 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); + 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(parent->getDesktop()->getDocument(), undokey, - SP_VERB_DIALOG_FILL_STROKE, (_("Adjust hue"))); + DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, SP_VERB_DIALOG_FILL_STROKE, + (_("Adjust hue"))); 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); + 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_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) { +void RotateableSwatch::do_release(double by, guint modifier) +{ if (parent->_mode[fillstroke] != SS_COLOR) return; @@ -1337,26 +1324,26 @@ RotateableSwatch::do_release(double by, guint modifier) { GtkWidget *w = GTK_WIDGET(gobj()); gdk_window_set_cursor(gtk_widget_get_window(w), nullptr); if (cr) { - g_object_unref(cr); - cr = nullptr; + g_object_unref(cr); + cr = nullptr; } cr_set = false; } if (modifier == 3) { // alpha - DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, - SP_VERB_DIALOG_FILL_STROKE, ("Adjust alpha")); + DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, SP_VERB_DIALOG_FILL_STROKE, + ("Adjust alpha")); } else if (modifier == 2) { // saturation - DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, - SP_VERB_DIALOG_FILL_STROKE, ("Adjust saturation")); + DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, SP_VERB_DIALOG_FILL_STROKE, + ("Adjust saturation")); } else if (modifier == 1) { // lightness - DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, - SP_VERB_DIALOG_FILL_STROKE, ("Adjust lightness")); + DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, SP_VERB_DIALOG_FILL_STROKE, + ("Adjust lightness")); } else { // hue - DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, - SP_VERB_DIALOG_FILL_STROKE, ("Adjust hue")); + DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, SP_VERB_DIALOG_FILL_STROKE, + ("Adjust hue")); } if (!strcmp(undokey, "ssrot1")) { @@ -1371,44 +1358,41 @@ RotateableSwatch::do_release(double by, guint modifier) { /* ============================================= RotateableStrokeWidth */ -RotateableStrokeWidth::RotateableStrokeWidth(SelectedStyle *parent) : - parent(parent), - startvalue(0), - startvalue_set(false), - undokey("swrot1") -{ -} +RotateableStrokeWidth::RotateableStrokeWidth(SelectedStyle *parent) + : parent(parent) + , startvalue(0) + , startvalue_set(false) + , undokey("swrot1") +{} RotateableStrokeWidth::~RotateableStrokeWidth() = default; -double -RotateableStrokeWidth::value_adjust(double current, double by, guint /*modifier*/, bool final) +double RotateableStrokeWidth::value_adjust(double current, double by, guint /*modifier*/, bool final) { double newval; // by is -1..1 - double max_f = 50; // maximum width is (current * max_f), minimum - zero - newval = current * (std::exp(std::log(max_f-1) * (by+1)) - 1) / (max_f-2); + double max_f = 50; // maximum width is (current * max_f), minimum - zero + newval = current * (std::exp(std::log(max_f - 1) * (by + 1)) - 1) / (max_f - 2); - SPCSSAttr *css = sp_repr_css_attr_new (); + SPCSSAttr *css = sp_repr_css_attr_new(); if (final && newval < 1e-6) { // if dragged into zero and this is the final adjust on mouse release, delete stroke; // if it's not final, leave it a chance to increase again (which is not possible with "none") - sp_repr_css_set_property (css, "stroke", "none"); + sp_repr_css_set_property(css, "stroke", "none"); } else { newval = Inkscape::Util::Quantity::convert(newval, parent->_sw_unit, "px"); Inkscape::CSSOStringStream os; os << newval; - sp_repr_css_set_property (css, "stroke-width", os.str().c_str()); + sp_repr_css_set_property(css, "stroke-width", os.str().c_str()); } - sp_desktop_set_style (parent->getDesktop(), css); - sp_repr_css_attr_unref (css); + sp_desktop_set_style(parent->getDesktop(), css); + sp_repr_css_attr_unref(css); return newval - current; } -void -RotateableStrokeWidth::do_motion(double by, guint modifier) { - +void RotateableStrokeWidth::do_motion(double by, guint modifier) +{ // if this is the first motion after a mouse grab, remember the current width if (!startvalue_set) { startvalue = parent->current_stroke_width; @@ -1422,22 +1406,23 @@ RotateableStrokeWidth::do_motion(double by, guint modifier) { if (modifier == 3) { // Alt, do nothing } else { double diff = value_adjust(startvalue, by, modifier, false); - DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), 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); + DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), 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); } } -void -RotateableStrokeWidth::do_release(double by, guint modifier) { - +void RotateableStrokeWidth::do_release(double by, guint modifier) +{ if (modifier == 3) { // do nothing } else { value_adjust(startvalue, by, modifier, true); startvalue_set = false; - DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, - SP_VERB_DIALOG_FILL_STROKE, (_("Adjust stroke width"))); + DocumentUndo::maybeDone(parent->getDesktop()->getDocument(), undokey, SP_VERB_DIALOG_FILL_STROKE, + (_("Adjust stroke width"))); } if (!strcmp(undokey, "swrot1")) { @@ -1448,21 +1433,21 @@ RotateableStrokeWidth::do_release(double by, guint modifier) { parent->getDesktop()->event_context->message_context->clear(); } -void -RotateableStrokeWidth::do_scroll(double by, guint modifier) { - do_motion(by/10.0, modifier); +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) { if (Dialog::PanelDialogBase *panel_dialog = - dynamic_cast<Dialog::PanelDialogBase *>(desktop->_dlg_mgr->getDialog("FillAndStroke"))) { + dynamic_cast<Dialog::PanelDialogBase *>(desktop->_dlg_mgr->getDialog("FillAndStroke"))) { try { - Dialog::FillAndStroke &fill_and_stroke = - dynamic_cast<Dialog::FillAndStroke &>(panel_dialog->getPanel()); + Dialog::FillAndStroke &fill_and_stroke = dynamic_cast<Dialog::FillAndStroke &>(panel_dialog->getPanel()); return &fill_and_stroke; - } catch (std::exception &e) { } + } catch (std::exception &e) { + } } return nullptr; diff --git a/src/ui/widget/selected-style.h b/src/ui/widget/selected-style.h index 52674a9c13bd0a5b7254d94787b4b19ae25a24e1..07a2d41136e7e3b160ac2e51bc6e5932ad0aa18d 100644 --- a/src/ui/widget/selected-style.h +++ b/src/ui/widget/selected-style.h @@ -12,36 +12,35 @@ #ifndef INKSCAPE_UI_CURRENT_STYLE_H #define INKSCAPE_UI_CURRENT_STYLE_H +#include <cstddef> +#include <gtkmm/adjustment.h> #include <gtkmm/box.h> +#include <gtkmm/enums.h> +#include <gtkmm/eventbox.h> #include <gtkmm/grid.h> - #include <gtkmm/label.h> -#include <gtkmm/eventbox.h> -#include <gtkmm/enums.h> #include <gtkmm/menu.h> #include <gtkmm/menuitem.h> -#include <gtkmm/adjustment.h> #include <gtkmm/radiobuttongroup.h> #include <gtkmm/radiomenuitem.h> -#include "ui/widget/spinbutton.h" - -#include <cstddef> #include <sigc++/sigc++.h> #include "rotateable.h" +#include "ui/widget/spinbutton.h" class SPDesktop; namespace Inkscape { namespace Util { - class Unit; +class Unit; } namespace UI { namespace Widget { -enum { +enum +{ SS_NA, SS_NONE, SS_UNSET, @@ -56,7 +55,8 @@ enum { SS_HATCH }; -enum { +enum +{ SS_FILL, SS_STROKE }; @@ -64,16 +64,17 @@ enum { class GradientImage; class SelectedStyle; -class RotateableSwatch : public Rotateable { - public: +class RotateableSwatch : public Rotateable +{ +public: RotateableSwatch(SelectedStyle *parent, guint mode); ~RotateableSwatch() override; - double color_adjust (float *hsl, double by, guint32 cc, guint state); + double color_adjust(float *hsl, double by, guint32 cc, guint state); - void do_motion (double by, guint state) override; - void do_release (double by, guint state) override; - void do_scroll (double by, guint state) override; + void do_motion(double by, guint state) override; + void do_release(double by, guint state) override; + void do_scroll(double by, guint state) override; private: guint fillstroke; @@ -89,15 +90,16 @@ private: bool cr_set; }; -class RotateableStrokeWidth : public Rotateable { - public: +class RotateableStrokeWidth : public Rotateable +{ +public: RotateableStrokeWidth(SelectedStyle *parent); ~RotateableStrokeWidth() override; double value_adjust(double current, double by, guint modifier, bool final); - void do_motion (double by, guint state) override; - void do_release (double by, guint state) override; - void do_scroll (double by, guint state) override; + void do_motion(double by, guint state) override; + void do_release(double by, guint state) override; + void do_scroll(double by, guint state) override; private: SelectedStyle *parent; @@ -119,7 +121,7 @@ public: ~SelectedStyle() override; void setDesktop(SPDesktop *desktop); - SPDesktop *getDesktop() {return _desktop;} + SPDesktop *getDesktop() { return _desktop; } void update(); guint32 _lastselected[2]; @@ -207,13 +209,8 @@ protected: sigc::connection *selection_modified_connection; sigc::connection *subselection_changed_connection; - static void dragDataReceived( GtkWidget *widget, - GdkDragContext *drag_context, - gint x, gint y, - GtkSelectionData *data, - guint info, - guint event_time, - gpointer user_data ); + static void dragDataReceived(GtkWidget *widget, GdkDragContext *drag_context, gint x, gint y, + GtkSelectionData *data, guint info, guint event_time, gpointer user_data); bool on_fill_click(GdkEventButton *event); bool on_stroke_click(GdkEventButton *event); @@ -269,7 +266,7 @@ protected: Gtk::Menu _popup_sw; Gtk::RadioButtonGroup _sw_group; - std::vector<Gtk::RadioMenuItem*> _unit_mis; + std::vector<Gtk::RadioMenuItem *> _unit_mis; void on_popup_units(Inkscape::Util::Unit const *u); void on_popup_preset(int i); Gtk::MenuItem _popup_sw_remove; @@ -278,7 +275,6 @@ protected: bool _dropEnabled[2]; }; - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/spin-button-tool-item.cpp b/src/ui/widget/spin-button-tool-item.cpp index 90dcbe26e65614b658dddba09f6004c4bee604aa..4fa10ec53f750601b9fb21715286c90cfd39a442 100644 --- a/src/ui/widget/spin-button-tool-item.cpp +++ b/src/ui/widget/spin-button-tool-item.cpp @@ -3,12 +3,11 @@ #include "spin-button-tool-item.h" #include <algorithm> +#include <cmath> #include <gtkmm/box.h> #include <gtkmm/image.h> #include <gtkmm/radiomenuitem.h> #include <gtkmm/toolbar.h> - -#include <cmath> #include <utility> #include "spinbutton.h" @@ -26,8 +25,7 @@ namespace Widget { * \detail This just logs the current value of the spin-button * and sets the _transfer_focus flag */ -bool -SpinButtonToolItem::on_btn_focus_in_event(GdkEventFocus * /* focus_event */) +bool SpinButtonToolItem::on_btn_focus_in_event(GdkEventFocus * /* focus_event */) { _last_val = _btn->get_value(); _transfer_focus = true; @@ -42,8 +40,7 @@ SpinButtonToolItem::on_btn_focus_in_event(GdkEventFocus * /* focus_event */) * * \detail This just unsets the _transfer_focus flag */ -bool -SpinButtonToolItem::on_btn_focus_out_event(GdkEventFocus * /* focus_event */) +bool SpinButtonToolItem::on_btn_focus_out_event(GdkEventFocus * /* focus_event */) { _transfer_focus = false; @@ -58,97 +55,77 @@ SpinButtonToolItem::on_btn_focus_out_event(GdkEventFocus * /* focus_event */) * \detail If the ESC key was pressed, restore the last value and defocus. * If the Enter key was pressed, just defocus. */ -bool -SpinButtonToolItem::on_btn_key_press_event(GdkEventKey *key_event) +bool SpinButtonToolItem::on_btn_key_press_event(GdkEventKey *key_event) { bool was_consumed = false; // Whether event has been consumed or not auto display = Gdk::Display::get_default(); - auto keymap = display->get_keymap(); + auto keymap = display->get_keymap(); guint key = 0; gdk_keymap_translate_keyboard_state(keymap, key_event->hardware_keycode, - static_cast<GdkModifierType>(key_event->state), - 0, &key, 0, 0, 0); + static_cast<GdkModifierType>(key_event->state), 0, &key, 0, 0, 0); auto val = _btn->get_value(); - switch(key) { - case GDK_KEY_Escape: - { + switch (key) { + case GDK_KEY_Escape: { _transfer_focus = true; _btn->set_value(_last_val); defocus(); was_consumed = true; - } - break; + } break; case GDK_KEY_Return: - case GDK_KEY_KP_Enter: - { + case GDK_KEY_KP_Enter: { _transfer_focus = true; defocus(); was_consumed = true; - } - break; + } break; - case GDK_KEY_Tab: - { + case GDK_KEY_Tab: { _transfer_focus = false; was_consumed = process_tab(1); - } - break; + } break; - case GDK_KEY_ISO_Left_Tab: - { + case GDK_KEY_ISO_Left_Tab: { _transfer_focus = false; was_consumed = process_tab(-1); - } - break; + } break; // TODO: Enable variable step-size if this is ever used case GDK_KEY_Up: - case GDK_KEY_KP_Up: - { + case GDK_KEY_KP_Up: { _transfer_focus = false; - _btn->set_value(val+1); - was_consumed=true; - } - break; + _btn->set_value(val + 1); + was_consumed = true; + } break; case GDK_KEY_Down: - case GDK_KEY_KP_Down: - { + case GDK_KEY_KP_Down: { _transfer_focus = false; - _btn->set_value(val-1); - was_consumed=true; - } - break; + _btn->set_value(val - 1); + was_consumed = true; + } break; case GDK_KEY_Page_Up: - case GDK_KEY_KP_Page_Up: - { + case GDK_KEY_KP_Page_Up: { _transfer_focus = false; - _btn->set_value(val+10); - was_consumed=true; - } - break; + _btn->set_value(val + 10); + was_consumed = true; + } break; case GDK_KEY_Page_Down: - case GDK_KEY_KP_Page_Down: - { + case GDK_KEY_KP_Page_Down: { _transfer_focus = false; - _btn->set_value(val-10); - was_consumed=true; - } - break; + _btn->set_value(val - 10); + was_consumed = true; + } break; case GDK_KEY_z: - case GDK_KEY_Z: - { + case GDK_KEY_Z: { _transfer_focus = false; _btn->set_value(_last_val); was_consumed = true; - } - break; + } break; } return was_consumed; @@ -159,10 +136,9 @@ SpinButtonToolItem::on_btn_key_press_event(GdkEventKey *key_event) * * \details This only has an effect if the _transfer_focus flag and the _focus_widget are set */ -void -SpinButtonToolItem::defocus() +void SpinButtonToolItem::defocus() { - if(_transfer_focus && _focus_widget) { + if (_transfer_focus && _focus_widget) { _focus_widget->grab_focus(); } } @@ -172,11 +148,11 @@ SpinButtonToolItem::defocus() * * \param increment[in] The number of places to shift within the toolbar */ -bool -SpinButtonToolItem::process_tab(int increment) +bool SpinButtonToolItem::process_tab(int increment) { // If the increment is zero, do nothing - if(increment == 0) return true; + if (increment == 0) + return true; // Here, we're working through the widget hierarchy: // Toolbar @@ -194,25 +170,23 @@ SpinButtonToolItem::process_tab(int increment) if (toolbar) { // Get the index of the current item within the toolbar and the total number of items auto my_index = toolbar->get_item_index(*this); - auto n_items = toolbar->get_n_items(); + auto n_items = toolbar->get_n_items(); auto test_index = my_index + increment; // The index of the item we want to check // Loop through tool items as long as we're within the limits of the toolbar and // we haven't yet found our new item to focus on - while(test_index > 0 && test_index <= n_items && !handled) { - + while (test_index > 0 && test_index <= n_items && !handled) { auto tool_item = toolbar->get_nth_item(test_index); - if(tool_item) { + if (tool_item) { // There are now two options that we support: - if(dynamic_cast<SpinButtonToolItem *>(tool_item)) { + if (dynamic_cast<SpinButtonToolItem *>(tool_item)) { // (1) The tool item is a SpinButtonToolItem, in which case, we just pass // focus to its spin-button dynamic_cast<SpinButtonToolItem *>(tool_item)->grab_button_focus(); handled = true; - } - else if(dynamic_cast<Gtk::SpinButton *>(tool_item->get_child())) { + } else if (dynamic_cast<Gtk::SpinButton *>(tool_item->get_child())) { // (2) The tool item contains a plain Gtk::SpinButton, in which case we // pass focus directly to it tool_item->get_child()->grab_focus(); @@ -231,17 +205,14 @@ SpinButtonToolItem::process_tab(int increment) * * \details Sets the adjustment to the desired value */ -void -SpinButtonToolItem::on_numeric_menu_item_toggled(double value) +void SpinButtonToolItem::on_numeric_menu_item_toggled(double value) { auto adj = _btn->get_adjustment(); adj->set_value(value); } -Gtk::RadioMenuItem * -SpinButtonToolItem::create_numeric_menu_item(Gtk::RadioButtonGroup *group, - double value, - const Glib::ustring& label) +Gtk::RadioMenuItem *SpinButtonToolItem::create_numeric_menu_item(Gtk::RadioButtonGroup *group, double value, + const Glib::ustring &label) { // Represent the value as a string std::ostringstream ss; @@ -266,8 +237,7 @@ SpinButtonToolItem::create_numeric_menu_item(Gtk::RadioButtonGroup *group, * * \details Each of these values represents a snap-point for the adjustment's value */ -Gtk::Menu * -SpinButtonToolItem::create_numeric_menu() +Gtk::Menu *SpinButtonToolItem::create_numeric_menu() { auto numeric_menu = Gtk::manage(new Gtk::Menu()); @@ -306,7 +276,7 @@ SpinButtonToolItem::create_numeric_menu() values.emplace(lower, ""); } - auto add_item = [&numeric_menu, this, &group, adj_value](ValueLabel value){ + auto add_item = [&numeric_menu, this, &group, adj_value](ValueLabel value) { auto numeric_menu_item = create_numeric_menu_item(&group, value.first, value.second); numeric_menu->append(*numeric_menu_item); @@ -332,8 +302,7 @@ SpinButtonToolItem::create_numeric_menu() * runs if the toolitem is unable to fit on the toolbar, and * must be represented by a menu item instead. */ -bool -SpinButtonToolItem::on_create_menu_proxy() +bool SpinButtonToolItem::on_create_menu_proxy() { // The main menu-item. It just contains the label that normally appears // next to the spin-button, and an indicator for a sub-menu. @@ -355,15 +324,12 @@ SpinButtonToolItem::on_create_menu_proxy() * \param[in] climb_rate The climb rate for the spin button (default = 0) * \param[in] digits Number of decimal places to display */ -SpinButtonToolItem::SpinButtonToolItem(const Glib::ustring name, - const Glib::ustring& label_text, - Glib::RefPtr<Gtk::Adjustment>& adjustment, - double climb_rate, - int digits) - : _btn(Gtk::manage(new SpinButton(adjustment, climb_rate, digits))), - _name(std::move(name)), - _label_text(label_text), - _digits(digits) +SpinButtonToolItem::SpinButtonToolItem(const Glib::ustring name, const Glib::ustring &label_text, + Glib::RefPtr<Gtk::Adjustment> &adjustment, double climb_rate, int digits) + : _btn(Gtk::manage(new SpinButton(adjustment, climb_rate, digits))) + , _name(std::move(name)) + , _label_text(label_text) + , _digits(digits) { set_margin_start(3); set_margin_end(3); @@ -399,13 +365,12 @@ SpinButtonToolItem::SpinButtonToolItem(const Glib::ustring name, show_all(); } -void -SpinButtonToolItem::set_icon(const Glib::ustring& icon_name) +void SpinButtonToolItem::set_icon(const Glib::ustring &icon_name) { _hbox->remove(*_label); _icon = Gtk::manage(sp_get_icon_image(icon_name, Gtk::ICON_SIZE_SMALL_TOOLBAR)); - if(_icon) { + if (_icon) { _hbox->pack_start(*_icon); _hbox->reorder_child(*_icon, 0); } @@ -413,11 +378,10 @@ SpinButtonToolItem::set_icon(const Glib::ustring& icon_name) show_all(); } -bool -SpinButtonToolItem::on_btn_button_press_event(const GdkEventButton *button_event) +bool SpinButtonToolItem::on_btn_button_press_event(const GdkEventButton *button_event) { if (gdk_event_triggers_context_menu(reinterpret_cast<const GdkEvent *>(button_event)) && - button_event->type == GDK_BUTTON_PRESS) { + button_event->type == GDK_BUTTON_PRESS) { do_popup_menu(button_event); return true; } @@ -425,8 +389,7 @@ SpinButtonToolItem::on_btn_button_press_event(const GdkEventButton *button_event return false; } -void -SpinButtonToolItem::do_popup_menu(const GdkEventButton *button_event) +void SpinButtonToolItem::do_popup_menu(const GdkEventButton *button_event) { auto menu = create_numeric_menu(); menu->attach_to_widget(*_btn); @@ -437,8 +400,7 @@ SpinButtonToolItem::do_popup_menu(const GdkEventButton *button_event) /** * \brief Create a popup menu */ -bool -SpinButtonToolItem::on_popup_menu() +bool SpinButtonToolItem::on_popup_menu() { do_popup_menu(nullptr); return true; @@ -447,8 +409,7 @@ SpinButtonToolItem::on_popup_menu() /** * \brief Transfers focus to the child spinbutton by default */ -void -SpinButtonToolItem::on_grab_focus() +void SpinButtonToolItem::on_grab_focus() { grab_button_focus(); } @@ -458,8 +419,7 @@ SpinButtonToolItem::on_grab_focus() * * \param[in] text The tooltip to display */ -void -SpinButtonToolItem::set_all_tooltip_text(const Glib::ustring& text) +void SpinButtonToolItem::set_all_tooltip_text(const Glib::ustring &text) { set_tooltip_text(text); _btn->set_tooltip_text(text); @@ -470,8 +430,7 @@ SpinButtonToolItem::set_all_tooltip_text(const Glib::ustring& text) * * \param widget The widget that will gain focus */ -void -SpinButtonToolItem::set_focus_widget(Gtk::Widget *widget) +void SpinButtonToolItem::set_focus_widget(Gtk::Widget *widget) { _focus_widget = widget; } @@ -479,8 +438,7 @@ SpinButtonToolItem::set_focus_widget(Gtk::Widget *widget) /** * \brief Grab focus on the spin-button widget */ -void -SpinButtonToolItem::grab_button_focus() +void SpinButtonToolItem::grab_button_focus() { _btn->grab_focus(); } @@ -488,8 +446,8 @@ SpinButtonToolItem::grab_button_focus() /** * \brief A wrapper of Geom::decimal_round to remember precision */ -double -SpinButtonToolItem::round_to_precision(double value) { +double SpinButtonToolItem::round_to_precision(double value) +{ return Geom::decimal_round(value, _digits); } @@ -503,11 +461,9 @@ SpinButtonToolItem::round_to_precision(double value) { * This is discouraged in favor of other overloads of the function, due to error prone * usage. Using two vectors for related data, undermining encapsulation. */ -void -SpinButtonToolItem::set_custom_numeric_menu_data(const std::vector<double>& values, - const std::vector<Glib::ustring>& labels) +void SpinButtonToolItem::set_custom_numeric_menu_data(const std::vector<double> &values, + const std::vector<Glib::ustring> &labels) { - if (values.size() != labels.size() && !labels.empty()) { g_warning("Cannot add custom menu items. Value and label arrays are different sizes"); return; @@ -536,15 +492,14 @@ SpinButtonToolItem::set_custom_numeric_menu_data(const std::vector<double>& * \detail Should be used when most of the values have an associated label (densely labeled data) * */ -void -SpinButtonToolItem::set_custom_numeric_menu_data(const std::vector<ValueLabel>& value_labels) { +void SpinButtonToolItem::set_custom_numeric_menu_data(const std::vector<ValueLabel> &value_labels) +{ _custom_menu_data.clear(); - for(const auto& value_label : value_labels) { + for (const auto &value_label : value_labels) { _custom_menu_data.emplace(round_to_precision(value_label.first), value_label.second); } } - /** * \brief Set numeric data options for Radio menu (sparsely labeled data). * @@ -556,33 +511,41 @@ SpinButtonToolItem::set_custom_numeric_menu_data(const std::vector<ValueLabel>& * preferred. Avoid using duplicate values intentionally though. * */ -void -SpinButtonToolItem::set_custom_numeric_menu_data(const std::vector<double> &values, +void SpinButtonToolItem::set_custom_numeric_menu_data(const std::vector<double> &values, const std::unordered_map<double, Glib::ustring> &sparse_labels) { _custom_menu_data.clear(); - for(const auto& value_label : sparse_labels) { + for (const auto &value_label : sparse_labels) { _custom_menu_data.emplace(round_to_precision(value_label.first), value_label.second); } - for(const auto& value : values) { + for (const auto &value : values) { _custom_menu_data.emplace(round_to_precision(value), ""); } - } +void SpinButtonToolItem::show_upper_limit(bool show) +{ + _show_upper_limit = show; +} -void SpinButtonToolItem::show_upper_limit(bool show) { _show_upper_limit = show; } - -void SpinButtonToolItem::show_lower_limit(bool show) { _show_lower_limit = show; } +void SpinButtonToolItem::show_lower_limit(bool show) +{ + _show_lower_limit = show; +} -void SpinButtonToolItem::show_limits(bool show) { _show_upper_limit = _show_lower_limit = show; } +void SpinButtonToolItem::show_limits(bool show) +{ + _show_upper_limit = _show_lower_limit = show; +} -void SpinButtonToolItem::sort_decreasing(bool decreasing) { _sort_decreasing = decreasing; } +void SpinButtonToolItem::sort_decreasing(bool decreasing) +{ + _sort_decreasing = decreasing; +} -Glib::RefPtr<Gtk::Adjustment> -SpinButtonToolItem::get_adjustment() +Glib::RefPtr<Gtk::Adjustment> SpinButtonToolItem::get_adjustment() { return _btn->get_adjustment(); } diff --git a/src/ui/widget/spin-button-tool-item.h b/src/ui/widget/spin-button-tool-item.h index dbf98c745744f0b5dc28b4458e3258e3c7cfa4d2..6f2d9e05a3b7e9143fb2c53321a29c02153ce1f9 100644 --- a/src/ui/widget/spin-button-tool-item.h +++ b/src/ui/widget/spin-button-tool-item.h @@ -12,7 +12,7 @@ namespace Gtk { class Box; class RadioButtonGroup; class RadioMenuItem; -} +} // namespace Gtk namespace Inkscape { namespace UI { @@ -29,18 +29,18 @@ private: using ValueLabel = std::pair<double, Glib::ustring>; using NumericMenuData = std::map<double, Glib::ustring>; - Glib::ustring _name; ///< A unique ID for the widget (NOT translatable) - SpinButton *_btn; ///< The spin-button within the widget - Glib::ustring _label_text; ///< A string to use in labels for the widget (translatable) - double _last_val = 0.0; ///< The last value of the adjustment - bool _transfer_focus = false; ///< Whether or not to transfer focus + Glib::ustring _name; ///< A unique ID for the widget (NOT translatable) + SpinButton *_btn; ///< The spin-button within the widget + Glib::ustring _label_text; ///< A string to use in labels for the widget (translatable) + double _last_val = 0.0; ///< The last value of the adjustment + bool _transfer_focus = false; ///< Whether or not to transfer focus - Gtk::Box *_hbox; ///< Horizontal box, to store widgets - Gtk::Widget *_label; ///< A text label to describe the setting - Gtk::Widget *_icon; ///< An icon to describe the setting + Gtk::Box *_hbox; ///< Horizontal box, to store widgets + Gtk::Widget *_label; ///< A text label to describe the setting + Gtk::Widget *_icon; ///< An icon to describe the setting /** A widget that grabs focus when this one loses it */ - Gtk::Widget * _focus_widget = nullptr; + Gtk::Widget *_focus_widget = nullptr; // Custom values and labels to add to the numeric popup-menu NumericMenuData _custom_menu_data; @@ -59,9 +59,9 @@ private: double round_to_precision(double value); // Event handlers - bool on_btn_focus_in_event(GdkEventFocus *focus_event); + bool on_btn_focus_in_event(GdkEventFocus *focus_event); bool on_btn_focus_out_event(GdkEventFocus *focus_event); - bool on_btn_key_press_event(GdkEventKey *key_event); + bool on_btn_key_press_event(GdkEventKey *key_event); bool on_btn_button_press_event(const GdkEventButton *button_event); bool on_popup_menu(); void do_popup_menu(const GdkEventButton *button_event); @@ -71,42 +71,38 @@ private: void on_numeric_menu_item_toggled(double value); - Gtk::Menu * create_numeric_menu(); + Gtk::Menu *create_numeric_menu(); - Gtk::RadioMenuItem * create_numeric_menu_item(Gtk::RadioButtonGroup *group, - double value, - const Glib::ustring& label = ""); + Gtk::RadioMenuItem *create_numeric_menu_item(Gtk::RadioButtonGroup *group, double value, + const Glib::ustring &label = ""); protected: bool on_create_menu_proxy() override; void on_grab_focus() override; public: - SpinButtonToolItem(const Glib::ustring name, - const Glib::ustring& label_text, - Glib::RefPtr<Gtk::Adjustment>& adjustment, - double climb_rate = 0.1, - int digits = 3); + SpinButtonToolItem(const Glib::ustring name, const Glib::ustring &label_text, + Glib::RefPtr<Gtk::Adjustment> &adjustment, double climb_rate = 0.1, int digits = 3); - void set_all_tooltip_text(const Glib::ustring& text); + void set_all_tooltip_text(const Glib::ustring &text); void set_focus_widget(Gtk::Widget *widget); void grab_button_focus(); - void set_custom_numeric_menu_data(const std::vector<double>& values, - const std::vector<Glib::ustring>& labels = std::vector<Glib::ustring>()); + void set_custom_numeric_menu_data(const std::vector<double> &values, + const std::vector<Glib::ustring> &labels = std::vector<Glib::ustring>()); void set_custom_numeric_menu_data(const std::vector<ValueLabel> &value_labels); - void set_custom_numeric_menu_data(const std::vector<double>& values, - const std::unordered_map<double, Glib::ustring>& sparse_labels); + void set_custom_numeric_menu_data(const std::vector<double> &values, + const std::unordered_map<double, Glib::ustring> &sparse_labels); Glib::RefPtr<Gtk::Adjustment> get_adjustment(); - void set_icon(const Glib::ustring& icon_name); + void set_icon(const Glib::ustring &icon_name); // display limits void show_upper_limit(bool show = true); void show_lower_limit(bool show = true); - void show_limits (bool show = true); + void show_limits(bool show = true); // sorting order void sort_decreasing(bool decreasing = true); diff --git a/src/ui/widget/spin-scale.cpp b/src/ui/widget/spin-scale.cpp index 2f4e2de521d0071b8ccf995aa660eae06038bfe8..6f68b4cd77c62f1e3b3eae8e46fe73dcc2c5a4c9 100644 --- a/src/ui/widget/spin-scale.cpp +++ b/src/ui/widget/spin-scale.cpp @@ -17,18 +17,16 @@ namespace Inkscape { namespace UI { namespace Widget { -SpinScale::SpinScale(const Glib::ustring label, double value, - double lower, double upper, - double step_increment, double page_increment, int digits, - const SPAttr a, const Glib::ustring tip_text) +SpinScale::SpinScale(const Glib::ustring label, double value, double lower, double upper, double step_increment, + double page_increment, int digits, const SPAttr a, const Glib::ustring tip_text) : AttrWidget(a, value) , _inkspinscale(value, lower, upper, step_increment, page_increment, 0) { set_name("SpinScale"); - _inkspinscale.set_label (label); - _inkspinscale.set_digits (digits); - _inkspinscale.set_tooltip_text (tip_text); + _inkspinscale.set_label(label); + _inkspinscale.set_digits(digits); + _inkspinscale.set_tooltip_text(tip_text); _adjustment = _inkspinscale.get_adjustment(); @@ -39,17 +37,16 @@ SpinScale::SpinScale(const Glib::ustring label, double value, show_all_children(); } -SpinScale::SpinScale(const Glib::ustring label, - Glib::RefPtr<Gtk::Adjustment> adjustment, int digits, - const SPAttr a, const Glib::ustring tip_text) +SpinScale::SpinScale(const Glib::ustring label, Glib::RefPtr<Gtk::Adjustment> adjustment, int digits, const SPAttr a, + const Glib::ustring tip_text) : AttrWidget(a, 0.0) , _inkspinscale(adjustment) { set_name("SpinScale"); - _inkspinscale.set_label (label); - _inkspinscale.set_digits (digits); - _inkspinscale.set_tooltip_text (tip_text); + _inkspinscale.set_label(label); + _inkspinscale.set_digits(digits); + _inkspinscale.set_tooltip_text(tip_text); _adjustment = _inkspinscale.get_adjustment(); @@ -64,15 +61,15 @@ Glib::ustring SpinScale::get_as_attribute() const { const double val = _adjustment->get_value(); - if( _inkspinscale.get_digits() == 0) + if (_inkspinscale.get_digits() == 0) return Glib::Ascii::dtostr((int)val); else return Glib::Ascii::dtostr(val); } -void SpinScale::set_from_attribute(SPObject* o) +void SpinScale::set_from_attribute(SPObject *o) { - const gchar* val = attribute_value(o); + const gchar *val = attribute_value(o); if (val) _adjustment->set_value(Glib::Ascii::strtod(val)); else @@ -109,17 +106,15 @@ decltype(SpinScale::_adjustment) SpinScale::get_adjustment() return _adjustment; } - -DualSpinScale::DualSpinScale(const Glib::ustring label1, const Glib::ustring label2, - double value, double lower, double upper, - double step_increment, double page_increment, int digits, - const SPAttr a, +DualSpinScale::DualSpinScale(const Glib::ustring label1, const Glib::ustring label2, double value, double lower, + double upper, double step_increment, double page_increment, int digits, const SPAttr a, const Glib::ustring tip_text1, const Glib::ustring tip_text2) - : AttrWidget(a), - _s1(label1, value, lower, upper, step_increment, page_increment, digits, SPAttr::INVALID, tip_text1), - _s2(label2, value, lower, upper, step_increment, page_increment, digits, SPAttr::INVALID, tip_text2), - //TRANSLATORS: "Link" means to _link_ two sliders together - _link(C_("Sliders", "Link")) + : AttrWidget(a) + , _s1(label1, value, lower, upper, step_increment, page_increment, digits, SPAttr::INVALID, tip_text1) + , _s2(label2, value, lower, upper, step_increment, page_increment, digits, SPAttr::INVALID, tip_text2) + , + // TRANSLATORS: "Link" means to _link_ two sliders together + _link(C_("Sliders", "Link")) { set_name("DualSpinScale"); signal_value_changed().connect(signal_attr_changed().make_slot()); @@ -130,7 +125,7 @@ DualSpinScale::DualSpinScale(const Glib::ustring label1, const Glib::ustring lab _link.signal_toggled().connect(sigc::mem_fun(*this, &DualSpinScale::link_toggled)); - Gtk::Box* vb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL)); + Gtk::Box *vb = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL)); vb->add(_s1); vb->add(_s2); pack_start(*vb); @@ -142,24 +137,24 @@ DualSpinScale::DualSpinScale(const Glib::ustring label1, const Glib::ustring lab Glib::ustring DualSpinScale::get_as_attribute() const { - if(_link.get_active()) + 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) +void DualSpinScale::set_from_attribute(SPObject *o) { - const gchar* val = attribute_value(o); - if(val) { + const gchar *val = attribute_value(o); + if (val) { // Split val into parts - gchar** toks = g_strsplit(val, " ", 2); + gchar **toks = g_strsplit(val, " ", 2); - if(toks) { + if (toks) { double v1 = 0.0, v2 = 0.0; - if(toks[0]) + if (toks[0]) v1 = v2 = Glib::Ascii::strtod(toks[0]); - if(toks[1]) + if (toks[1]) v2 = Glib::Ascii::strtod(toks[1]); _link.set_active(toks[1] == nullptr); @@ -172,27 +167,27 @@ void DualSpinScale::set_from_attribute(SPObject* o) } } -sigc::signal<void>& DualSpinScale::signal_value_changed() +sigc::signal<void> &DualSpinScale::signal_value_changed() { return _signal_value_changed; } -const SpinScale& DualSpinScale::get_SpinScale1() const +const SpinScale &DualSpinScale::get_SpinScale1() const { return _s1; } -SpinScale& DualSpinScale::get_SpinScale1() +SpinScale &DualSpinScale::get_SpinScale1() { return _s1; } -const SpinScale& DualSpinScale::get_SpinScale2() const +const SpinScale &DualSpinScale::get_SpinScale2() const { return _s2; } -SpinScale& DualSpinScale::get_SpinScale2() +SpinScale &DualSpinScale::get_SpinScale2() { return _s2; } @@ -205,11 +200,10 @@ void DualSpinScale::link_toggled() void DualSpinScale::update_linked() { - if(_link.get_active()) + if (_link.get_active()) _s2.set_value(_s1.get_value()); } - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/spin-scale.h b/src/ui/widget/spin-scale.h index 259b5bd391dc7df9a769d22977659e9991c56fcf..a506a90082d97dee0b163aaf1b79d0cfbf9a876b 100644 --- a/src/ui/widget/spin-scale.h +++ b/src/ui/widget/spin-scale.h @@ -14,6 +14,7 @@ #include <gtkmm/adjustment.h> #include <gtkmm/box.h> #include <gtkmm/togglebutton.h> + #include "attr-widget.h" #include "ink-spinscale.h" @@ -25,29 +26,27 @@ namespace Widget { * Wrap the InkSpinScale class and attach an attribute. * A combo widget with label, scale slider, spinbutton, and adjustment; */ -class SpinScale : public Gtk::Box, public AttrWidget +class SpinScale + : public Gtk::Box + , public AttrWidget { - public: - SpinScale(const Glib::ustring label, double value, - double lower, double upper, - double step_increment, double page_increment, int digits, - const SPAttr a = SPAttr::INVALID, const Glib::ustring tip_text = ""); + SpinScale(const Glib::ustring label, double value, double lower, double upper, double step_increment, + double page_increment, int digits, const SPAttr a = SPAttr::INVALID, const Glib::ustring tip_text = ""); // Used by extensions - SpinScale(const Glib::ustring label, - Glib::RefPtr<Gtk::Adjustment> adjustment, int digits, + SpinScale(const Glib::ustring label, Glib::RefPtr<Gtk::Adjustment> adjustment, int digits, const SPAttr a = SPAttr::INVALID, const Glib::ustring tip_text = ""); Glib::ustring get_as_attribute() const override; - void set_from_attribute(SPObject*) override; + void set_from_attribute(SPObject *) override; // Shortcuts to _adjustment Glib::SignalProxy0<void> signal_value_changed(); double get_value() const; void set_value(const double); void set_focuswidget(GtkWidget *widget); - + private: Glib::RefPtr<Gtk::Adjustment> _adjustment; InkSpinScale _inkspinscale; @@ -57,33 +56,32 @@ public: decltype(_adjustment) get_adjustment(); }; - /** * Contains two SpinScales for controlling number-opt-number attributes. * * @see SpinScale */ -class DualSpinScale : public Gtk::Box, public AttrWidget +class DualSpinScale + : public Gtk::Box + , public AttrWidget { public: - DualSpinScale(const Glib::ustring label1, const Glib::ustring label2, - double value, double lower, double upper, - double step_increment, double page_increment, int digits, - const SPAttr a, + DualSpinScale(const Glib::ustring label1, const Glib::ustring label2, double value, double lower, double upper, + double step_increment, double page_increment, int digits, const SPAttr a, const Glib::ustring tip_text1, const Glib::ustring tip_text2); Glib::ustring get_as_attribute() const override; - void set_from_attribute(SPObject*) override; + void set_from_attribute(SPObject *) override; - sigc::signal<void>& signal_value_changed(); + sigc::signal<void> &signal_value_changed(); - const SpinScale& get_SpinScale1() const; - SpinScale& get_SpinScale1(); + const SpinScale &get_SpinScale1() const; + SpinScale &get_SpinScale1(); - const SpinScale& get_SpinScale2() const; - SpinScale& get_SpinScale2(); + const SpinScale &get_SpinScale2() const; + SpinScale &get_SpinScale2(); - //void remove_scale(); + // void remove_scale(); private: void link_toggled(); void update_linked(); diff --git a/src/ui/widget/spin-slider.cpp b/src/ui/widget/spin-slider.cpp index f1e5fb70d67ead3b2b2ef576a6822835e579fe66..35b5546d57d1b667147ef3c1b4ae6bbc8fa3b821 100644 --- a/src/ui/widget/spin-slider.cpp +++ b/src/ui/widget/spin-slider.cpp @@ -18,18 +18,19 @@ namespace Inkscape { namespace UI { namespace Widget { -SpinSlider::SpinSlider(double value, double lower, double upper, double step_inc, - double climb_rate, int digits, const SPAttr a, const char* tip_text) - : AttrWidget(a, value), - _adjustment(Gtk::Adjustment::create(value, lower, upper, step_inc)), - _scale(_adjustment), _spin(_adjustment, climb_rate, digits) +SpinSlider::SpinSlider(double value, double lower, double upper, double step_inc, double climb_rate, int digits, + const SPAttr a, const char *tip_text) + : AttrWidget(a, value) + , _adjustment(Gtk::Adjustment::create(value, lower, upper, step_inc)) + , _scale(_adjustment) + , _spin(_adjustment, climb_rate, digits) { set_name("SpinSlider"); signal_value_changed().connect(signal_attr_changed().make_slot()); pack_start(_scale); pack_start(_spin, false, false); - if (tip_text){ + if (tip_text) { _scale.set_tooltip_text(tip_text); _spin.set_tooltip_text(tip_text); } @@ -43,16 +44,16 @@ Glib::ustring SpinSlider::get_as_attribute() const { const auto val = _adjustment->get_value(); - if(_spin.get_digits() == 0) + if (_spin.get_digits() == 0) return Glib::Ascii::dtostr((int)val); else return Glib::Ascii::dtostr(val); } -void SpinSlider::set_from_attribute(SPObject* o) +void SpinSlider::set_from_attribute(SPObject *o) { - const gchar* val = attribute_value(o); - if(val) + const gchar *val = attribute_value(o); + if (val) _adjustment->set_value(Glib::Ascii::strtod(val)); else _adjustment->set_value(get_default()->as_double()); @@ -83,21 +84,21 @@ decltype(SpinSlider::_adjustment) SpinSlider::get_adjustment() return _adjustment; } -const Gtk::Scale& SpinSlider::get_scale() const +const Gtk::Scale &SpinSlider::get_scale() const { return _scale; } -Gtk::Scale& SpinSlider::get_scale() +Gtk::Scale &SpinSlider::get_scale() { return _scale; } -const Inkscape::UI::Widget::SpinButton& SpinSlider::get_spin_button() const +const Inkscape::UI::Widget::SpinButton &SpinSlider::get_spin_button() const { return _spin; } -Inkscape::UI::Widget::SpinButton& SpinSlider::get_spin_button() +Inkscape::UI::Widget::SpinButton &SpinSlider::get_spin_button() { return _spin; } @@ -107,13 +108,14 @@ void SpinSlider::remove_scale() remove(_scale); } -DualSpinSlider::DualSpinSlider(double value, double lower, double upper, double step_inc, - double climb_rate, int digits, const SPAttr a, char* tip_text1, char* tip_text2) - : AttrWidget(a), - _s1(value, lower, upper, step_inc, climb_rate, digits, SPAttr::INVALID, tip_text1), - _s2(value, lower, upper, step_inc, climb_rate, digits, SPAttr::INVALID, tip_text2), - //TRANSLATORS: "Link" means to _link_ two sliders together - _link(C_("Sliders", "Link")) +DualSpinSlider::DualSpinSlider(double value, double lower, double upper, double step_inc, double climb_rate, int digits, + const SPAttr a, char *tip_text1, char *tip_text2) + : AttrWidget(a) + , _s1(value, lower, upper, step_inc, climb_rate, digits, SPAttr::INVALID, tip_text1) + , _s2(value, lower, upper, step_inc, climb_rate, digits, SPAttr::INVALID, tip_text2) + , + // TRANSLATORS: "Link" means to _link_ two sliders together + _link(C_("Sliders", "Link")) { signal_value_changed().connect(signal_attr_changed().make_slot()); @@ -122,7 +124,7 @@ DualSpinSlider::DualSpinSlider(double value, double lower, double upper, double _s1.get_adjustment()->signal_value_changed().connect(sigc::mem_fun(*this, &DualSpinSlider::update_linked)); _link.signal_toggled().connect(sigc::mem_fun(*this, &DualSpinSlider::link_toggled)); - Gtk::VBox* vb = Gtk::manage(new Gtk::VBox); + Gtk::VBox *vb = Gtk::manage(new Gtk::VBox); vb->add(_s1); vb->add(_s2); pack_start(*vb); @@ -134,24 +136,24 @@ DualSpinSlider::DualSpinSlider(double value, double lower, double upper, double Glib::ustring DualSpinSlider::get_as_attribute() const { - if(_link.get_active()) + if (_link.get_active()) return _s1.get_as_attribute(); else return _s1.get_as_attribute() + " " + _s2.get_as_attribute(); } -void DualSpinSlider::set_from_attribute(SPObject* o) +void DualSpinSlider::set_from_attribute(SPObject *o) { - const gchar* val = attribute_value(o); - if(val) { + const gchar *val = attribute_value(o); + if (val) { // Split val into parts - gchar** toks = g_strsplit(val, " ", 2); + gchar **toks = g_strsplit(val, " ", 2); - if(toks) { + if (toks) { double v1 = 0.0, v2 = 0.0; - if(toks[0]) + if (toks[0]) v1 = v2 = Glib::Ascii::strtod(toks[0]); - if(toks[1]) + if (toks[1]) v2 = Glib::Ascii::strtod(toks[1]); _link.set_active(toks[1] == nullptr); @@ -164,27 +166,27 @@ void DualSpinSlider::set_from_attribute(SPObject* o) } } -sigc::signal<void>& DualSpinSlider::signal_value_changed() +sigc::signal<void> &DualSpinSlider::signal_value_changed() { return _signal_value_changed; } -const SpinSlider& DualSpinSlider::get_spinslider1() const +const SpinSlider &DualSpinSlider::get_spinslider1() const { return _s1; } -SpinSlider& DualSpinSlider::get_spinslider1() +SpinSlider &DualSpinSlider::get_spinslider1() { return _s1; } -const SpinSlider& DualSpinSlider::get_spinslider2() const +const SpinSlider &DualSpinSlider::get_spinslider2() const { return _s2; } -SpinSlider& DualSpinSlider::get_spinslider2() +SpinSlider &DualSpinSlider::get_spinslider2() { return _s2; } @@ -203,7 +205,7 @@ void DualSpinSlider::link_toggled() void DualSpinSlider::update_linked() { - if(_link.get_active()) + if (_link.get_active()) _s2.set_value(_s1.get_value()); } diff --git a/src/ui/widget/spin-slider.h b/src/ui/widget/spin-slider.h index e9348e1dc94e772ec9cdea3a9687fcc0415927e8..fd8b0d247e8baa06611f9c359a49d1a8266c3039 100644 --- a/src/ui/widget/spin-slider.h +++ b/src/ui/widget/spin-slider.h @@ -15,8 +15,9 @@ #include <gtkmm/box.h> #include <gtkmm/scale.h> #include <gtkmm/togglebutton.h> -#include "spinbutton.h" + #include "attr-widget.h" +#include "spinbutton.h" namespace Inkscape { namespace UI { @@ -25,28 +26,31 @@ namespace Widget { /** * Groups an HScale and a SpinButton together using the same Adjustment. */ -class SpinSlider : public Gtk::HBox, public AttrWidget +class SpinSlider + : public Gtk::HBox + , public AttrWidget { public: - SpinSlider(double value, double lower, double upper, double step_inc, - double climb_rate, int digits, const SPAttr a = SPAttr::INVALID, const char* tip_text = nullptr); + SpinSlider(double value, double lower, double upper, double step_inc, double climb_rate, int digits, + const SPAttr a = SPAttr::INVALID, const char *tip_text = nullptr); Glib::ustring get_as_attribute() const override; - void set_from_attribute(SPObject*) override; + void set_from_attribute(SPObject *) override; // Shortcuts to _adjustment Glib::SignalProxy0<void> signal_value_changed(); double get_value() const; void set_value(const double); - const Gtk::Scale& get_scale() const; - Gtk::Scale& get_scale(); + const Gtk::Scale &get_scale() const; + Gtk::Scale &get_scale(); - const Inkscape::UI::Widget::SpinButton& get_spin_button() const; - Inkscape::UI::Widget::SpinButton& get_spin_button(); + const Inkscape::UI::Widget::SpinButton &get_spin_button() const; + Inkscape::UI::Widget::SpinButton &get_spin_button(); // Change the SpinSlider into a SpinButton with AttrWidget support) void remove_scale(); + private: Glib::RefPtr<Gtk::Adjustment> _adjustment; Gtk::Scale _scale; @@ -62,24 +66,27 @@ public: * * @see SpinSlider */ -class DualSpinSlider : public Gtk::HBox, public AttrWidget +class DualSpinSlider + : public Gtk::HBox + , public AttrWidget { public: - DualSpinSlider(double value, double lower, double upper, double step_inc, - double climb_rate, int digits, const SPAttr, char* tip_text1, char* tip_text2); + DualSpinSlider(double value, double lower, double upper, double step_inc, double climb_rate, int digits, + const SPAttr, char *tip_text1, char *tip_text2); Glib::ustring get_as_attribute() const override; - void set_from_attribute(SPObject*) override; + void set_from_attribute(SPObject *) override; - sigc::signal<void>& signal_value_changed(); + sigc::signal<void> &signal_value_changed(); - const SpinSlider& get_spinslider1() const; - SpinSlider& get_spinslider1(); + const SpinSlider &get_spinslider1() const; + SpinSlider &get_spinslider1(); - const SpinSlider& get_spinslider2() const; - SpinSlider& get_spinslider2(); + const SpinSlider &get_spinslider2() const; + SpinSlider &get_spinslider2(); void remove_scale(); + private: void link_toggled(); void update_linked(); diff --git a/src/ui/widget/spinbutton.cpp b/src/ui/widget/spinbutton.cpp index 5920c5e77ad5ad83c46d57bb5331abece4ef7b66..80f1b283c85f48d781bb6cdc6e8e5024f35a61fd 100644 --- a/src/ui/widget/spinbutton.cpp +++ b/src/ui/widget/spinbutton.cpp @@ -9,18 +9,18 @@ */ #include "spinbutton.h" + +#include "ui/tools/tool-base.h" #include "unit-menu.h" #include "unit-tracker.h" #include "util/expression-evaluator.h" -#include "ui/tools/tool-base.h" namespace Inkscape { namespace UI { namespace Widget { - -void -SpinButton::connect_signals() { +void SpinButton::connect_signals() +{ signal_input().connect(sigc::mem_fun(this, &SpinButton::on_input)); signal_focus_in_event().connect(sigc::mem_fun(this, &SpinButton::on_my_focus_in_event)); signal_key_press_event().connect(sigc::mem_fun(this, &SpinButton::on_my_key_press_event)); @@ -29,9 +29,10 @@ SpinButton::connect_signals() { set_focus_on_click(true); }; -int SpinButton::on_input(double* newvalue) +int SpinButton::on_input(double *newvalue) { - if (_dont_evaluate) return false; + if (_dont_evaluate) + return false; try { Inkscape::Util::EvaluatorQuantity result; @@ -45,17 +46,17 @@ int SpinButton::on_input(double* newvalue) 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) ) { - throw Inkscape::Util::EvaluatorException("Input dimensions do not match with parameter dimensions.",""); + if (result.dimension != (unit->isAbsolute() ? 1 : 0)) { + throw Inkscape::Util::EvaluatorException("Input dimensions do not match with parameter dimensions.", + ""); } } else { Inkscape::Util::ExpressionEvaluator eval = Inkscape::Util::ExpressionEvaluator(get_text().c_str(), nullptr); result = eval.evaluate(); } *newvalue = result.value; - } - catch(Inkscape::Util::EvaluatorException &e) { - g_message ("%s", e.what()); + } catch (Inkscape::Util::EvaluatorException &e) { + g_message("%s", e.what()); return false; } @@ -63,14 +64,12 @@ int SpinButton::on_input(double* newvalue) return true; } -bool SpinButton::on_my_focus_in_event(GdkEventFocus* /*event*/) +bool SpinButton::on_my_focus_in_event(GdkEventFocus * /*event*/) { _on_focus_in_value = get_value(); return false; // do not consume the event } - - bool SpinButton::on_scroll_event(GdkEventScroll *event) { if (!is_focus()) { @@ -96,35 +95,35 @@ bool SpinButton::on_scroll_event(GdkEventScroll *event) return true; } -bool SpinButton::on_my_key_press_event(GdkEventKey* event) +bool SpinButton::on_my_key_press_event(GdkEventKey *event) { - switch (Inkscape::UI::Tools::get_latin_keyval (event)) { - case GDK_KEY_Escape: // defocus - undo(); - defocus(); - return true; // I consumed the event - break; - case GDK_KEY_Return: // defocus - case GDK_KEY_KP_Enter: - defocus(); - return true; - break; - case GDK_KEY_Tab: - case GDK_KEY_ISO_Left_Tab: - // set the flag meaning "do not leave toolbar when changing value" - _stay = true; - return false; - break; - case GDK_KEY_z: - case GDK_KEY_Z: - _stay = true; - if (event->state & GDK_CONTROL_MASK) { + switch (Inkscape::UI::Tools::get_latin_keyval(event)) { + case GDK_KEY_Escape: // defocus undo(); + defocus(); return true; // I consumed the event - } - break; - default: - break; + break; + case GDK_KEY_Return: // defocus + case GDK_KEY_KP_Enter: + defocus(); + return true; + break; + case GDK_KEY_Tab: + case GDK_KEY_ISO_Left_Tab: + // set the flag meaning "do not leave toolbar when changing value" + _stay = true; + return false; + break; + case GDK_KEY_z: + case GDK_KEY_Z: + _stay = true; + if (event->state & GDK_CONTROL_MASK) { + undo(); + return true; // I consumed the event + } + break; + default: + break; } return false; // do not consume the event diff --git a/src/ui/widget/spinbutton.h b/src/ui/widget/spinbutton.h index 72b41a2cd71b93b26582395fdfbe3ffcc80fb071..c3787c79c74cc083481799f2d399c6df7b6348a6 100644 --- a/src/ui/widget/spinbutton.h +++ b/src/ui/widget/spinbutton.h @@ -24,71 +24,72 @@ class UnitTracker; * SpinButton widget, that allows entry of simple math expressions (also units, when linked with UnitMenu), * and allows entry of both '.' and ',' for the decimal, even when in numeric mode. * - * Calling "set_numeric()" effectively disables the expression parsing. If no unit menu is linked, all unitlike characters are ignored. + * Calling "set_numeric()" effectively disables the expression parsing. If no unit menu is linked, all unitlike + * characters are ignored. */ class SpinButton : public Gtk::SpinButton { public: - SpinButton(double climb_rate = 0.0, guint digits = 0) - : Gtk::SpinButton(climb_rate, digits) - { - connect_signals(); - }; + SpinButton(double climb_rate = 0.0, guint digits = 0) + : Gtk::SpinButton(climb_rate, digits) + { + connect_signals(); + }; - explicit SpinButton(Glib::RefPtr<Gtk::Adjustment>& adjustment, double climb_rate = 0.0, guint digits = 0) - : Gtk::SpinButton(adjustment, climb_rate, digits) - { - connect_signals(); - }; + explicit SpinButton(Glib::RefPtr<Gtk::Adjustment> &adjustment, double climb_rate = 0.0, guint digits = 0) + : Gtk::SpinButton(adjustment, climb_rate, digits) + { + connect_signals(); + }; - ~SpinButton() override = default; + ~SpinButton() override = default; - // noncopyable - SpinButton(const SpinButton&) = delete; - SpinButton& operator=(const SpinButton&) = delete; + // noncopyable + SpinButton(const SpinButton &) = delete; + SpinButton &operator=(const SpinButton &) = delete; - void setUnitMenu(UnitMenu* unit_menu) { _unit_menu = unit_menu; }; - - void addUnitTracker(UnitTracker* ut) { _unit_tracker = ut; }; + void setUnitMenu(UnitMenu *unit_menu) { _unit_menu = unit_menu; }; - // TODO: Might be better to just have a default value and a reset() method? - inline void set_zeroable(const bool zeroable = true) { _zeroable = zeroable; } - inline void set_oneable(const bool oneable = true) { _oneable = oneable; } + void addUnitTracker(UnitTracker *ut) { _unit_tracker = ut; }; - inline bool get_zeroable() const { return _zeroable; } - inline bool get_oneable() const { return _oneable; } + // TODO: Might be better to just have a default value and a reset() method? + inline void set_zeroable(const bool zeroable = true) { _zeroable = zeroable; } + inline void set_oneable(const bool oneable = true) { _oneable = oneable; } - void defocus(); + inline bool get_zeroable() const { return _zeroable; } + inline bool get_oneable() const { return _oneable; } + + void defocus(); protected: - UnitMenu *_unit_menu = nullptr; ///< Linked unit menu for unit conversion in entered expressions. - UnitTracker *_unit_tracker = nullptr; ///< Linked unit tracker for unit conversion in entered expressions. - double _on_focus_in_value = 0.; - Gtk::Widget *_defocus_widget = nullptr; ///< Widget that should grab focus when the spinbutton defocuses + UnitMenu *_unit_menu = nullptr; ///< Linked unit menu for unit conversion in entered expressions. + UnitTracker *_unit_tracker = nullptr; ///< Linked unit tracker for unit conversion in entered expressions. + double _on_focus_in_value = 0.; + Gtk::Widget *_defocus_widget = nullptr; ///< Widget that should grab focus when the spinbutton defocuses - bool _zeroable = false; ///< Reset-value should be zero - bool _oneable = false; ///< Reset-value should be one + bool _zeroable = false; ///< Reset-value should be zero + bool _oneable = false; ///< Reset-value should be one - bool _stay = false; ///< Whether to ignore defocusing - bool _dont_evaluate = false; ///< Don't attempt to evaluate expressions + bool _stay = false; ///< Whether to ignore defocusing + bool _dont_evaluate = false; ///< Don't attempt to evaluate expressions - void connect_signals(); + void connect_signals(); /** * This callback function should try to convert the entered text to a number and write it to newvalue. * It calls a method to evaluate the (potential) mathematical expression. * * @retval false No conversion done, continue with default handler. - * @retval true Conversion successful, don't call default handler. + * @retval true Conversion successful, don't call default handler. */ - int on_input(double* newvalue) override; + int on_input(double *newvalue) override; /** * When focus is obtained, save the value to enable undo later. * @retval false continue with default handler. - * @retval true don't call default handler. + * @retval true don't call default handler. */ - bool on_my_focus_in_event(GdkEventFocus* event); + bool on_my_focus_in_event(GdkEventFocus *event); /** * When scroll is done. @@ -101,16 +102,16 @@ protected: * Handle specific keypress events, like Ctrl+Z. * * @retval false continue with default handler. - * @retval true don't call default handler. + * @retval true don't call default handler. */ - bool on_my_key_press_event(GdkEventKey* event); + bool on_my_key_press_event(GdkEventKey *event); /** * Undo the editing, by resetting the value upon when the spinbutton got focus. */ void undo(); - public: +public: inline void set_defocus_widget(const decltype(_defocus_widget) widget) { _defocus_widget = widget; } inline void set_dont_evaluate(bool flag) { _dont_evaluate = flag; } }; diff --git a/src/ui/widget/stroke-style.cpp b/src/ui/widget/stroke-style.cpp index efaa8b3aacf765fcdd3f89dc5837bc0efae8daa7..607a6ebfa89d7a3d3275e9b951c3db57baff9a7b 100644 --- a/src/ui/widget/stroke-style.cpp +++ b/src/ui/widget/stroke-style.cpp @@ -25,14 +25,11 @@ #include "object/sp-rect.h" #include "object/sp-stop.h" #include "object/sp-text.h" - #include "svg/svg-color.h" - #include "ui/icon-loader.h" #include "ui/widget/dash-selector.h" #include "ui/widget/marker-combo-box.h" #include "ui/widget/unit-menu.h" - #include "widgets/style-utils.h" using Inkscape::DocumentUndo; @@ -44,7 +41,7 @@ using Inkscape::Util::unit_table; * \return Buffer containing the actual name, allocated from GLib; * the caller should free the buffer when they no longer need it. */ -SPObject* getMarkerObj(gchar const *n, SPDocument *doc) +SPObject *getMarkerObj(gchar const *n, SPDocument *doc) { gchar const *p = n; while (*p != '\0' && *p != '#') { @@ -65,7 +62,7 @@ SPObject* getMarkerObj(gchar const *n, SPDocument *doc) return nullptr; } - gchar* b = g_strdup(p); + gchar *b = g_strdup(p); b[c] = '\0'; // FIXME: get the document from the object and let the caller pass it in @@ -87,14 +84,11 @@ namespace Widget { * \param[in] button_type The type of stroke-style radio button (join/cap) * \param[in] stroke_style The style attribute to associate with the button */ -StrokeStyle::StrokeStyleButton::StrokeStyleButton(Gtk::RadioButtonGroup &grp, - char const *icon, - StrokeStyleButtonType button_type, - gchar const *stroke_style) - : - Gtk::RadioButton(grp), - button_type(button_type), - stroke_style(stroke_style) +StrokeStyle::StrokeStyleButton::StrokeStyleButton(Gtk::RadioButtonGroup &grp, char const *icon, + StrokeStyleButtonType button_type, gchar const *stroke_style) + : Gtk::RadioButton(grp) + , button_type(button_type) + , stroke_style(stroke_style) { show(); set_mode(false); @@ -105,26 +99,26 @@ StrokeStyle::StrokeStyleButton::StrokeStyleButton(Gtk::RadioButtonGroup &grp, add(*px); } -StrokeStyle::StrokeStyle() : - Gtk::Box(), - miterLimitSpin(), - widthSpin(), - unitSelector(), - joinMiter(), - joinRound(), - joinBevel(), - capButt(), - capRound(), - capSquare(), - dashSelector(), - update(false), - desktop(nullptr), - selectChangedConn(), - selectModifiedConn(), - startMarkerConn(), - midMarkerConn(), - endMarkerConn(), - _old_unit(nullptr) +StrokeStyle::StrokeStyle() + : Gtk::Box() + , miterLimitSpin() + , widthSpin() + , unitSelector() + , joinMiter() + , joinRound() + , joinBevel() + , capButt() + , capRound() + , capSquare() + , dashSelector() + , update(false) + , desktop(nullptr) + , selectChangedConn() + , selectModifiedConn() + , startMarkerConn() + , midMarkerConn() + , endMarkerConn() + , _old_unit(nullptr) { table = new Gtk::Grid(); table->set_border_width(4); @@ -137,16 +131,16 @@ StrokeStyle::StrokeStyle() : Gtk::HBox *hb; gint i = 0; - //spw_label(t, C_("Stroke width", "_Width:"), 0, i); + // spw_label(t, C_("Stroke width", "_Width:"), 0, i); hb = spw_hbox(table, 3, 1, i); -// TODO: when this is gtkmmified, use an Inkscape::UI::Widget::ScalarUnit instead of the separate -// spinbutton and unit selector for stroke width. In sp_stroke_style_line_update, use -// setHundredPercent to remember the averaged width corresponding to 100%. Then the -// stroke_width_set_unit will be removed (because ScalarUnit takes care of conversions itself), and -// with it, the two remaining calls of stroke_average_width, allowing us to get rid of that -// function in desktop-style. + // TODO: when this is gtkmmified, use an Inkscape::UI::Widget::ScalarUnit instead of the separate + // spinbutton and unit selector for stroke width. In sp_stroke_style_line_update, use + // setHundredPercent to remember the averaged width corresponding to 100%. Then the + // stroke_width_set_unit will be removed (because ScalarUnit takes care of conversions itself), and + // with it, the two remaining calls of stroke_average_width, allowing us to get rid of that + // function in desktop-style. widthAdj = new Glib::RefPtr<Gtk::Adjustment>(Gtk::Adjustment::create(1.0, 0.0, 1000.0, 0.1, 10.0, 0.0)); widthSpin = new Inkscape::UI::Widget::SpinButton(*widthAdj, 0.1, 3); widthSpin->set_tooltip_text(_("Stroke width")); @@ -169,7 +163,7 @@ StrokeStyle::StrokeStyle() : } widthSpin->setUnitMenu(unitSelector); unitChangedConn = unitSelector->signal_changed().connect(sigc::mem_fun(*this, &StrokeStyle::unitChangedCB)); - + us->show(); hb->pack_start(*us, FALSE, FALSE, 0); @@ -177,11 +171,11 @@ StrokeStyle::StrokeStyle() : i++; /* Dash */ - spw_label(table, _("Dashes:"), 0, i, nullptr); //no mnemonic for now - //decide what to do: - // implement a set_mnemonic_source function in the - // Inkscape::UI::Widget::DashSelector class, so that we do not have to - // expose any of the underlying widgets? + spw_label(table, _("Dashes:"), 0, i, nullptr); // no mnemonic for now + // decide what to do: + // implement a set_mnemonic_source function in the + // Inkscape::UI::Widget::DashSelector class, so that we do not have + // to expose any of the underlying widgets? dashSelector = Gtk::manage(new Inkscape::UI::Widget::DashSelector); dashSelector->show(); @@ -204,27 +198,26 @@ StrokeStyle::StrokeStyle() : startMarkerCombo = Gtk::manage(new MarkerComboBox("marker-start", SP_MARKER_LOC_START)); startMarkerCombo->set_tooltip_text(_("Start Markers are drawn on the first node of a path or shape")); - startMarkerConn = startMarkerCombo->signal_changed().connect( - sigc::bind<MarkerComboBox *, StrokeStyle *, SPMarkerLoc>( - sigc::ptr_fun(&StrokeStyle::markerSelectCB), startMarkerCombo, this, SP_MARKER_LOC_START)); + startMarkerConn = + startMarkerCombo->signal_changed().connect(sigc::bind<MarkerComboBox *, StrokeStyle *, SPMarkerLoc>( + sigc::ptr_fun(&StrokeStyle::markerSelectCB), startMarkerCombo, this, SP_MARKER_LOC_START)); startMarkerCombo->show(); hb->pack_start(*startMarkerCombo, true, true, 0); midMarkerCombo = Gtk::manage(new MarkerComboBox("marker-mid", SP_MARKER_LOC_MID)); - midMarkerCombo->set_tooltip_text(_("Mid Markers are drawn on every node of a path or shape except the first and last nodes")); - midMarkerConn = midMarkerCombo->signal_changed().connect( - sigc::bind<MarkerComboBox *, StrokeStyle *, SPMarkerLoc>( - sigc::ptr_fun(&StrokeStyle::markerSelectCB), midMarkerCombo, this, SP_MARKER_LOC_MID)); + midMarkerCombo->set_tooltip_text( + _("Mid Markers are drawn on every node of a path or shape except the first and last nodes")); + midMarkerConn = midMarkerCombo->signal_changed().connect(sigc::bind<MarkerComboBox *, StrokeStyle *, SPMarkerLoc>( + sigc::ptr_fun(&StrokeStyle::markerSelectCB), midMarkerCombo, this, SP_MARKER_LOC_MID)); midMarkerCombo->show(); hb->pack_start(*midMarkerCombo, true, true, 0); endMarkerCombo = Gtk::manage(new MarkerComboBox("marker-end", SP_MARKER_LOC_END)); endMarkerCombo->set_tooltip_text(_("End Markers are drawn on the last node of a path or shape")); - endMarkerConn = endMarkerCombo->signal_changed().connect( - sigc::bind<MarkerComboBox *, StrokeStyle *, SPMarkerLoc>( - sigc::ptr_fun(&StrokeStyle::markerSelectCB), endMarkerCombo, this, SP_MARKER_LOC_END)); + endMarkerConn = endMarkerCombo->signal_changed().connect(sigc::bind<MarkerComboBox *, StrokeStyle *, SPMarkerLoc>( + sigc::ptr_fun(&StrokeStyle::markerSelectCB), endMarkerCombo, this, SP_MARKER_LOC_END)); endMarkerCombo->show(); hb->pack_start(*endMarkerCombo, true, true, 0); @@ -240,24 +233,21 @@ StrokeStyle::StrokeStyle() : Gtk::RadioButtonGroup joinGrp; - joinRound = makeRadioButton(joinGrp, INKSCAPE_ICON("stroke-join-round"), - hb, STROKE_STYLE_BUTTON_JOIN, "round"); + joinRound = makeRadioButton(joinGrp, INKSCAPE_ICON("stroke-join-round"), hb, STROKE_STYLE_BUTTON_JOIN, "round"); // TRANSLATORS: Round join: joining lines with a rounded corner. // For an example, draw a triangle with a large stroke width and modify the // "Join" option (in the Fill and Stroke dialog). joinRound->set_tooltip_text(_("Round join")); - joinBevel = makeRadioButton(joinGrp, INKSCAPE_ICON("stroke-join-bevel"), - hb, STROKE_STYLE_BUTTON_JOIN, "bevel"); + joinBevel = makeRadioButton(joinGrp, INKSCAPE_ICON("stroke-join-bevel"), hb, STROKE_STYLE_BUTTON_JOIN, "bevel"); // TRANSLATORS: Bevel join: joining lines with a blunted (flattened) corner. // For an example, draw a triangle with a large stroke width and modify the // "Join" option (in the Fill and Stroke dialog). joinBevel->set_tooltip_text(_("Bevel join")); - joinMiter = makeRadioButton(joinGrp, INKSCAPE_ICON("stroke-join-miter"), - hb, STROKE_STYLE_BUTTON_JOIN, "miter"); + joinMiter = makeRadioButton(joinGrp, INKSCAPE_ICON("stroke-join-miter"), hb, STROKE_STYLE_BUTTON_JOIN, "miter"); // TRANSLATORS: Miter join: joining lines with a sharp (pointed) corner. // For an example, draw a triangle with a large stroke width and modify the @@ -271,7 +261,7 @@ StrokeStyle::StrokeStyle() : // spike that extends well beyond the connection point. The purpose of the // miter limit is to cut off such spikes (i.e. convert them into bevels) // when they become too long. - //spw_label(t, _("Miter _limit:"), 0, i); + // spw_label(t, _("Miter _limit:"), 0, i); miterLimitAdj = new Glib::RefPtr<Gtk::Adjustment>(Gtk::Adjustment::create(4.0, 0.0, 100.0, 0.1, 10.0, 0.0)); miterLimitSpin = new Inkscape::UI::Widget::SpinButton(*miterLimitAdj, 0.1, 2); miterLimitSpin->set_tooltip_text(_("Maximum length of the miter (in units of stroke width)")); @@ -284,29 +274,26 @@ StrokeStyle::StrokeStyle() : /* Cap type */ // TRANSLATORS: cap type specifies the shape for the ends of lines - //spw_label(t, _("_Cap:"), 0, i); + // spw_label(t, _("_Cap:"), 0, i); spw_label(table, _("Cap:"), 0, i, nullptr); hb = spw_hbox(table, 3, 1, i); Gtk::RadioButtonGroup capGrp; - capButt = makeRadioButton(capGrp, INKSCAPE_ICON("stroke-cap-butt"), - hb, STROKE_STYLE_BUTTON_CAP, "butt"); + capButt = makeRadioButton(capGrp, INKSCAPE_ICON("stroke-cap-butt"), hb, STROKE_STYLE_BUTTON_CAP, "butt"); // TRANSLATORS: Butt cap: the line shape does not extend beyond the end point // of the line; the ends of the line are square capButt->set_tooltip_text(_("Butt cap")); - capRound = makeRadioButton(capGrp, INKSCAPE_ICON("stroke-cap-round"), - hb, STROKE_STYLE_BUTTON_CAP, "round"); + capRound = makeRadioButton(capGrp, INKSCAPE_ICON("stroke-cap-round"), hb, STROKE_STYLE_BUTTON_CAP, "round"); // TRANSLATORS: Round cap: the line shape extends beyond the end point of the // line; the ends of the line are rounded capRound->set_tooltip_text(_("Round cap")); - capSquare = makeRadioButton(capGrp, INKSCAPE_ICON("stroke-cap-square"), - hb, STROKE_STYLE_BUTTON_CAP, "square"); + capSquare = makeRadioButton(capGrp, INKSCAPE_ICON("stroke-cap-square"), hb, STROKE_STYLE_BUTTON_CAP, "square"); // TRANSLATORS: Square cap: the line shape extends beyond the end point of the // line; the ends of the line are square @@ -322,33 +309,33 @@ StrokeStyle::StrokeStyle() : Gtk::RadioButtonGroup paintOrderGrp; - paintOrderFSM = makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-fsm"), - hb, STROKE_STYLE_BUTTON_ORDER, "normal"); - paintOrderFSM->set_tooltip_text(_("Fill, Stroke, Markers")); + paintOrderFSM = + makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-fsm"), hb, STROKE_STYLE_BUTTON_ORDER, "normal"); + paintOrderFSM->set_tooltip_text(_("Fill, Stroke, Markers")); - paintOrderSFM = makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-sfm"), - hb, STROKE_STYLE_BUTTON_ORDER, "stroke fill markers"); - paintOrderSFM->set_tooltip_text(_("Stroke, Fill, Markers")); + paintOrderSFM = makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-sfm"), hb, STROKE_STYLE_BUTTON_ORDER, + "stroke fill markers"); + paintOrderSFM->set_tooltip_text(_("Stroke, Fill, Markers")); - paintOrderFMS = makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-fms"), - hb, STROKE_STYLE_BUTTON_ORDER, "fill markers stroke"); - paintOrderFMS->set_tooltip_text(_("Fill, Markers, Stroke")); + paintOrderFMS = makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-fms"), hb, STROKE_STYLE_BUTTON_ORDER, + "fill markers stroke"); + paintOrderFMS->set_tooltip_text(_("Fill, Markers, Stroke")); i++; hb = spw_hbox(table, 4, 1, i); - paintOrderMFS = makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-mfs"), - hb, STROKE_STYLE_BUTTON_ORDER, "markers fill stroke"); - paintOrderMFS->set_tooltip_text(_("Markers, Fill, Stroke")); + paintOrderMFS = makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-mfs"), hb, STROKE_STYLE_BUTTON_ORDER, + "markers fill stroke"); + paintOrderMFS->set_tooltip_text(_("Markers, Fill, Stroke")); - paintOrderSMF = makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-smf"), - hb, STROKE_STYLE_BUTTON_ORDER, "stroke markers fill"); - paintOrderSMF->set_tooltip_text(_("Stroke, Markers, Fill")); + paintOrderSMF = makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-smf"), hb, STROKE_STYLE_BUTTON_ORDER, + "stroke markers fill"); + paintOrderSMF->set_tooltip_text(_("Stroke, Markers, Fill")); - paintOrderMSF = makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-msf"), - hb, STROKE_STYLE_BUTTON_ORDER, "markers stroke fill"); - paintOrderMSF->set_tooltip_text(_("Markers, Stroke, Fill")); + paintOrderMSF = makeRadioButton(paintOrderGrp, INKSCAPE_ICON("paint-order-msf"), hb, STROKE_STYLE_BUTTON_ORDER, + "markers stroke fill"); + paintOrderMSF->set_tooltip_text(_("Markers, Stroke, Fill")); i++; } @@ -362,7 +349,6 @@ StrokeStyle::~StrokeStyle() void StrokeStyle::setDesktop(SPDesktop *desktop) { if (this->desktop != desktop) { - if (this->desktop) { selectModifiedConn.disconnect(); selectChangedConn.disconnect(); @@ -375,8 +361,10 @@ void StrokeStyle::setDesktop(SPDesktop *desktop) } if (desktop->selection) { - selectChangedConn = desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &StrokeStyle::selectionChangedCB))); - selectModifiedConn = desktop->selection->connectModified(sigc::hide<0>(sigc::mem_fun(*this, &StrokeStyle::selectionModifiedCB))); + selectChangedConn = + desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &StrokeStyle::selectionChangedCB))); + selectModifiedConn = desktop->selection->connectModified( + sigc::hide<0>(sigc::mem_fun(*this, &StrokeStyle::selectionModifiedCB))); } _document_replaced_connection = @@ -390,12 +378,11 @@ void StrokeStyle::setDesktop(SPDesktop *desktop) void StrokeStyle::_handleDocumentReplaced(SPDesktop *, SPDocument *document) { - for (MarkerComboBox *combo : { startMarkerCombo, midMarkerCombo, endMarkerCombo }) { + for (MarkerComboBox *combo : {startMarkerCombo, midMarkerCombo, endMarkerCombo}) { combo->setDocument(document); } } - /** * Helper function for creating stroke-style radio buttons. * @@ -408,30 +395,26 @@ void StrokeStyle::_handleDocumentReplaced(SPDesktop *, SPDocument *document) * \details After instantiating the button, it is added to a container box and * a handler for the toggle event is connected. */ -StrokeStyle::StrokeStyleButton * -StrokeStyle::makeRadioButton(Gtk::RadioButtonGroup &grp, - char const *icon, - Gtk::HBox *hb, - StrokeStyleButtonType button_type, - gchar const *stroke_style) +StrokeStyle::StrokeStyleButton *StrokeStyle::makeRadioButton(Gtk::RadioButtonGroup &grp, char const *icon, + Gtk::HBox *hb, StrokeStyleButtonType button_type, + gchar const *stroke_style) { g_assert(icon != nullptr); - g_assert(hb != nullptr); + g_assert(hb != nullptr); StrokeStyleButton *tb = new StrokeStyleButton(grp, icon, button_type, stroke_style); hb->pack_start(*tb, false, false, 0); - tb->signal_toggled().connect(sigc::bind<StrokeStyleButton *, StrokeStyle *>( - sigc::ptr_fun(&StrokeStyle::buttonToggledCB), tb, this)); + tb->signal_toggled().connect( + sigc::bind<StrokeStyleButton *, StrokeStyle *>(sigc::ptr_fun(&StrokeStyle::buttonToggledCB), tb, this)); return tb; } bool StrokeStyle::shouldMarkersBeUpdated() { - return startMarkerCombo->update() || midMarkerCombo->update() || - endMarkerCombo->update(); + return startMarkerCombo->update() || midMarkerCombo->update() || endMarkerCombo->update(); } /** @@ -455,19 +438,18 @@ void StrokeStyle::markerSelectCB(MarkerComboBox *marker_combo, StrokeStyle *spw, /* Get Marker */ gchar const *marker = marker_combo->get_active_marker_uri(); - SPCSSAttr *css = sp_repr_css_attr_new(); gchar const *combo_id = marker_combo->get_id(); sp_repr_css_set_property(css, combo_id, marker); // Also update the marker combobox, so the document's markers // show up at the top of the combobox -// sp_stroke_style_line_update( SP_WIDGET(spw), desktop ? desktop->getSelection() : NULL); - //spw->updateMarkerHist(which); + // sp_stroke_style_line_update( SP_WIDGET(spw), desktop ? desktop->getSelection() : NULL); + // spw->updateMarkerHist(which); Inkscape::Selection *selection = spw->desktop->getSelection(); - auto itemlist= selection->items(); - for(auto i=itemlist.begin();i!=itemlist.end();++i){ + auto itemlist = selection->items(); + for (auto i = itemlist.begin(); i != itemlist.end(); ++i) { SPItem *item = *i; if (!SP_IS_SHAPE(item) || SP_IS_RECT(item)) { // can't set marker to rect, until it's converted to using <path> continue; @@ -532,8 +514,7 @@ void StrokeStyle::unitChangedCB() * Callback for when stroke style widget is modified. * Triggers update action. */ -void -StrokeStyle::selectionModifiedCB(guint flags) +void StrokeStyle::selectionModifiedCB(guint flags) { // We care deeply about only updating when the style is updated // if we update on other flags, we slow inkscape down when dragging @@ -546,8 +527,7 @@ StrokeStyle::selectionModifiedCB(guint flags) * Callback for when stroke style widget is changed. * Triggers update action. */ -void -StrokeStyle::selectionChangedCB() +void StrokeStyle::selectionChangedCB() { updateLine(); } @@ -556,8 +536,7 @@ StrokeStyle::selectionChangedCB() * Fork marker if necessary and set the referencing items url to the new marker * Return the new marker */ -SPObject * -StrokeStyle::forkMarker(SPObject *marker, int loc, SPItem *item) +SPObject *StrokeStyle::forkMarker(SPObject *marker, int loc, SPItem *item) { if (!item || !marker) { return nullptr; @@ -572,8 +551,7 @@ StrokeStyle::forkMarker(SPObject *marker, int loc, SPItem *item) Glib::ustring urlId = Glib::ustring::format("url(#", marker->getRepr()->attribute("id"), ")"); unsigned int refs = 0; for (int i = SP_MARKER_LOC_START; i < SP_MARKER_LOC_QTY; i++) { - if (item->style->marker_ptrs[i]->set && - !strcmp(urlId.c_str(), item->style->marker_ptrs[i]->value())) { + if (item->style->marker_ptrs[i]->set && !strcmp(urlId.c_str(), item->style->marker_ptrs[i]->value())) { refs++; } } @@ -604,10 +582,8 @@ StrokeStyle::forkMarker(SPObject *marker, int loc, SPItem *item) * 3. If the marker has fill color, use the marker fill color * */ -void -StrokeStyle::setMarkerColor(SPObject *marker, int loc, SPItem *item) +void StrokeStyle::setMarkerColor(SPObject *marker, int loc, SPItem *item) { - if (!item || !marker) { return; } @@ -616,7 +592,7 @@ StrokeStyle::setMarkerColor(SPObject *marker, int loc, SPItem *item) gboolean colorStock = prefs->getBool("/options/markers/colorStockMarkers", true); gboolean colorCustom = prefs->getBool("/options/markers/colorCustomMarkers", false); const gchar *stock = marker->getRepr()->attribute("inkscape:isstock"); - gboolean isStock = (stock && !strcmp(stock,"true")); + gboolean isStock = (stock && !strcmp(stock, "true")); if (isStock ? !colorStock : !colorCustom) { return; @@ -648,20 +624,19 @@ StrokeStyle::setMarkerColor(SPObject *marker, int loc, SPItem *item) sp_repr_css_set_property(css, "stroke", lstroke); sp_repr_css_set_property(css, "stroke-opacity", lstroke_opacity); - if (strcmp(lfill, "none") ) { + if (strcmp(lfill, "none")) { // 1. If the line has fill, use that for the marker fill sp_repr_css_set_property(css, "fill", lfill); sp_repr_css_set_property(css, "fill-opacity", lfill_opacity); - } - else if (mfill && mstroke && !strcmp(mfill, mstroke) && mfill[0] == '#' && strcmp(mfill, "#ffffff")) { - // 2. If the marker has same fill and stroke assume its solid. use line stroke for both fill and stroke the line stroke + } else if (mfill && mstroke && !strcmp(mfill, mstroke) && mfill[0] == '#' && strcmp(mfill, "#ffffff")) { + // 2. If the marker has same fill and stroke assume its solid. use line stroke for both fill and stroke the line + // stroke sp_repr_css_set_property(css, "fill", lstroke); sp_repr_css_set_property(css, "fill-opacity", lstroke_opacity); - } - else if (mfill && mfill[0] == '#' && strcmp(mfill, "#000000")) { + } else if (mfill && mfill[0] == '#' && strcmp(mfill, "#000000")) { // 3. If the marker has fill color, use the marker fill color sp_repr_css_set_property(css, "fill", mfill); - //sp_repr_css_set_property(css, "fill-opacity", mfill_opacity); + // sp_repr_css_set_property(css, "fill-opacity", mfill_opacity); } sp_repr_css_change_recursive(marker->firstChild()->getRepr(), css, "style"); @@ -674,16 +649,13 @@ StrokeStyle::setMarkerColor(SPObject *marker, int loc, SPItem *item) sp_repr_css_attr_unref(css); css = nullptr; - - } /* * Get the fill or stroke color of the item * If its a gradient, then return first or last stop color */ -const char * -StrokeStyle::getItemColorForMarker(SPItem *item, Inkscape::PaintTarget fill_or_stroke, int loc) +const char *StrokeStyle::getItemColorForMarker(SPItem *item, Inkscape::PaintTarget fill_or_stroke, int loc) { SPCSSAttr *css_item = sp_css_attr_from_object(item, SP_STYLE_FLAG_ALWAYS); const char *color; @@ -692,7 +664,7 @@ StrokeStyle::getItemColorForMarker(SPItem *item, Inkscape::PaintTarget fill_or_s else color = sp_repr_css_property(css_item, "stroke", "none"); - if (!strncmp (color, "url(", 4)) { + if (!strncmp(color, "url(", 4)) { // If the item has a gradient use the first stop color for the marker SPGradient *grad = getGradient(item, fill_or_stroke); @@ -707,7 +679,7 @@ StrokeStyle::getItemColorForMarker(SPItem *item, Inkscape::PaintTarget fill_or_s gchar c[64]; sp_svg_write_color(c, sizeof(c), c1); color = g_strdup(c); - //lstroke_opacity = Glib::ustring::format(stop->opacity).c_str(); + // lstroke_opacity = Glib::ustring::format(stop->opacity).c_str(); } } } @@ -716,8 +688,7 @@ StrokeStyle::getItemColorForMarker(SPItem *item, Inkscape::PaintTarget fill_or_s /** * Sets selector widgets' dash style from an SPStyle object. */ -void -StrokeStyle::setDashSelectorFromStyle(Inkscape::UI::Widget::DashSelector *dsel, SPStyle *style) +void StrokeStyle::setDashSelectorFromStyle(Inkscape::UI::Widget::DashSelector *dsel, SPStyle *style) { if (!style->stroke_dasharray.values.empty()) { double d[64]; @@ -746,8 +717,7 @@ StrokeStyle::setDashSelectorFromStyle(Inkscape::UI::Widget::DashSelector *dsel, /** * Sets the join type for a line, and updates the stroke style widget's buttons */ -void -StrokeStyle::setJoinType (unsigned const jointype) +void StrokeStyle::setJoinType(unsigned const jointype) { Gtk::RadioButton *tb = nullptr; switch (jointype) { @@ -772,8 +742,7 @@ StrokeStyle::setJoinType (unsigned const jointype) /** * Sets the cap type for a line, and updates the stroke style widget's buttons */ -void -StrokeStyle::setCapType (unsigned const captype) +void StrokeStyle::setCapType(unsigned const captype) { Gtk::RadioButton *tb = nullptr; switch (captype) { @@ -798,16 +767,14 @@ StrokeStyle::setCapType (unsigned const captype) /** * Sets the cap type for a line, and updates the stroke style widget's buttons */ -void -StrokeStyle::setPaintOrder (gchar const *paint_order) +void StrokeStyle::setPaintOrder(gchar const *paint_order) { Gtk::RadioButton *tb = paintOrderFSM; SPIPaintOrder temp; - temp.read( paint_order ); + temp.read(paint_order); if (temp.layer[0] != SP_CSS_PAINT_ORDER_NORMAL) { - if (temp.layer[0] == SP_CSS_PAINT_ORDER_FILL) { if (temp.layer[1] == SP_CSS_PAINT_ORDER_STROKE) { tb = paintOrderFSM; @@ -827,7 +794,6 @@ StrokeStyle::setPaintOrder (gchar const *paint_order) tb = paintOrderMFS; } } - } setPaintOrderButtons(tb); } @@ -836,8 +802,7 @@ StrokeStyle::setPaintOrder (gchar const *paint_order) * Callback for when stroke style widget is updated, including markers, cap type, * join type, etc. */ -void -StrokeStyle::updateLine() +void StrokeStyle::updateLine() { if (update) { return; @@ -913,25 +878,25 @@ StrokeStyle::updateLine() (*miterLimitAdj)->set_value(query.stroke_miterlimit.value); // TODO: reflect averagedness? using Inkscape::is_query_style_updateable; - if (! is_query_style_updateable(result_join)) { + if (!is_query_style_updateable(result_join)) { setJoinType(query.stroke_linejoin.value); } else { setJoinButtons(nullptr); } - if (! is_query_style_updateable(result_cap)) { - setCapType (query.stroke_linecap.value); + if (!is_query_style_updateable(result_cap)) { + setCapType(query.stroke_linecap.value); } else { setCapButtons(nullptr); } - if (! is_query_style_updateable(result_order)) { - setPaintOrder (query.paint_order.value); + if (!is_query_style_updateable(result_order)) { + setPaintOrder(query.paint_order.value); } else { - setPaintOrder (nullptr); + setPaintOrder(nullptr); } - std::vector<SPItem*> const objects(sel->items().begin(), sel->items().end()); + std::vector<SPItem *> const objects(sel->items().begin(), sel->items().end()); if (objects.size()) { SPObject *const object = objects[0]; SPStyle *const style = object->style; @@ -949,10 +914,7 @@ StrokeStyle::updateLine() /** * Sets a line's dash properties in a CSS style object. */ -void -StrokeStyle::setScaledDash(SPCSSAttr *css, - int ndash, double *dash, double offset, - double scale) +void StrokeStyle::setScaledDash(SPCSSAttr *css, int ndash, double *dash, double offset, double scale) { if (ndash > 0) { Inkscape::CSSOStringStream osarray; @@ -973,7 +935,8 @@ StrokeStyle::setScaledDash(SPCSSAttr *css, } } -static inline double calcScaleLineWidth(const double width_typed, SPItem *const item, Inkscape::Util::Unit const *const unit) +static inline double calcScaleLineWidth(const double width_typed, SPItem *const item, + Inkscape::Util::Unit const *const unit) { if (unit->type == Inkscape::Util::UNIT_TYPE_LINEAR) { return Inkscape::Util::Quantity::convert(width_typed, unit, "px"); @@ -986,8 +949,7 @@ static inline double calcScaleLineWidth(const double width_typed, SPItem *const /** * Sets line properties like width, dashes, markers, etc. on all currently selected items. */ -void -StrokeStyle::scaleLine() +void StrokeStyle::scaleLine() { if (!desktop) { return; @@ -998,10 +960,10 @@ StrokeStyle::scaleLine() } update = true; - + SPDocument *document = desktop->getDocument(); Inkscape::Selection *selection = desktop->getSelection(); - auto items= selection->items(); + auto items = selection->items(); /* TODO: Create some standardized method */ SPCSSAttr *css = sp_repr_css_attr_new(); @@ -1016,7 +978,7 @@ StrokeStyle::scaleLine() int ndash; dashSelector->get_dash(&ndash, &dash, &offset); - for(auto i=items.begin();i!=items.end();++i){ + for (auto i = items.begin(); i != items.end(); ++i) { /* Set stroke width */ const double width = calcScaleLineWidth(width_typed, (*i), unit); @@ -1037,11 +999,10 @@ StrokeStyle::scaleLine() gboolean scale = prefs->getBool("/options/dash/scale", true); if (scale) { setScaledDash(css, ndash, dash, offset, width); - } - else { + } else { setScaledDash(css, ndash, dash, offset, document->getDocumentScale()[0]); } - sp_desktop_apply_css_recursive ((*i), css, true); + sp_desktop_apply_css_recursive((*i), css, true); } g_free(dash); @@ -1050,18 +1011,16 @@ StrokeStyle::scaleLine() // reset to 100 percent (*widthAdj)->set_value(100.0); } - } // we have already changed the items, so set style without changing selection // FIXME: move the above stroke-setting stuff, including percentages, to desktop-style - sp_desktop_set_style (desktop, css, false); + sp_desktop_set_style(desktop, css, false); sp_repr_css_attr_unref(css); css = nullptr; - DocumentUndo::done(document, SP_VERB_DIALOG_FILL_STROKE, - _("Set stroke style")); + DocumentUndo::done(document, SP_VERB_DIALOG_FILL_STROKE, _("Set stroke style")); update = false; } @@ -1070,8 +1029,7 @@ StrokeStyle::scaleLine() * Callback for when the stroke style's width changes. * Causes all line styles to be applied to all selected items. */ -void -StrokeStyle::widthChangedCB() +void StrokeStyle::widthChangedCB() { if (update) { return; @@ -1084,8 +1042,7 @@ StrokeStyle::widthChangedCB() * Callback for when the stroke style's miterlimit changes. * Causes all line styles to be applied to all selected items. */ -void -StrokeStyle::miterLimitChangedCB() +void StrokeStyle::miterLimitChangedCB() { if (update) { return; @@ -1099,8 +1056,7 @@ StrokeStyle::miterLimitChangedCB() * Causes all line styles to be applied to all selected items. */ -void -StrokeStyle::lineDashChangedCB() +void StrokeStyle::lineDashChangedCB() { if (update) { return; @@ -1131,20 +1087,20 @@ void StrokeStyle::buttonToggledCB(StrokeStyleButton *tb, StrokeStyle *spw) SPCSSAttr *css = sp_repr_css_attr_new(); switch (tb->get_button_type()) { - case STROKE_STYLE_BUTTON_JOIN: + case STROKE_STYLE_BUTTON_JOIN: sp_repr_css_set_property(css, "stroke-linejoin", tb->get_stroke_style()); - sp_desktop_set_style (spw->desktop, css); + sp_desktop_set_style(spw->desktop, css); spw->setJoinButtons(tb); break; case STROKE_STYLE_BUTTON_CAP: sp_repr_css_set_property(css, "stroke-linecap", tb->get_stroke_style()); - sp_desktop_set_style (spw->desktop, css); + sp_desktop_set_style(spw->desktop, css); spw->setCapButtons(tb); break; case STROKE_STYLE_BUTTON_ORDER: sp_repr_css_set_property(css, "paint-order", tb->get_stroke_style()); - sp_desktop_set_style (spw->desktop, css); - //spw->setPaintButtons(tb); + sp_desktop_set_style(spw->desktop, css); + // spw->setPaintButtons(tb); } sp_repr_css_attr_unref(css); @@ -1157,8 +1113,7 @@ void StrokeStyle::buttonToggledCB(StrokeStyleButton *tb, StrokeStyle *spw) /** * Updates the join style toggle buttons */ -void -StrokeStyle::setJoinButtons(Gtk::ToggleButton *active) +void StrokeStyle::setJoinButtons(Gtk::ToggleButton *active) { joinMiter->set_active(active == joinMiter); miterLimitSpin->set_sensitive(active == joinMiter); @@ -1169,20 +1124,17 @@ StrokeStyle::setJoinButtons(Gtk::ToggleButton *active) /** * Updates the cap style toggle buttons */ -void -StrokeStyle::setCapButtons(Gtk::ToggleButton *active) +void StrokeStyle::setCapButtons(Gtk::ToggleButton *active) { capButt->set_active(active == capButt); capRound->set_active(active == capRound); capSquare->set_active(active == capSquare); } - /** * Updates the paint order style toggle buttons */ -void -StrokeStyle::setPaintOrderButtons(Gtk::ToggleButton *active) +void StrokeStyle::setPaintOrderButtons(Gtk::ToggleButton *active) { paintOrderFSM->set_active(active == paintOrderFSM); paintOrderSFM->set_active(active == paintOrderSFM); @@ -1192,12 +1144,11 @@ StrokeStyle::setPaintOrderButtons(Gtk::ToggleButton *active) paintOrderMSF->set_active(active == paintOrderMSF); } - /** * Recursively builds a simple list from an arbitrarily complex selection * of items and grouped items */ -static void buildGroupedItemList(SPObject *element, std::vector<SPObject*> &simple_list) +static void buildGroupedItemList(SPObject *element, std::vector<SPObject *> &simple_list) { if (SP_IS_GROUP(element)) { for (SPObject *i = element->firstChild(); i; i = i->getNext()) { @@ -1208,19 +1159,19 @@ static void buildGroupedItemList(SPObject *element, std::vector<SPObject*> &simp } } - /** * Updates the marker combobox to highlight the appropriate marker and scroll to * that marker. */ -void -StrokeStyle::updateAllMarkers(std::vector<SPItem*> const &objects, bool skip_undo) +void StrokeStyle::updateAllMarkers(std::vector<SPItem *> const &objects, bool skip_undo) { - struct { MarkerComboBox *key; int loc; } const keyloc[] = { - { startMarkerCombo, SP_MARKER_LOC_START }, - { midMarkerCombo, SP_MARKER_LOC_MID }, - { endMarkerCombo, SP_MARKER_LOC_END } - }; + struct + { + MarkerComboBox *key; + int loc; + } const keyloc[] = {{startMarkerCombo, SP_MARKER_LOC_START}, + {midMarkerCombo, SP_MARKER_LOC_MID}, + {endMarkerCombo, SP_MARKER_LOC_END}}; bool all_texts = true; @@ -1281,8 +1232,7 @@ StrokeStyle::updateAllMarkers(std::vector<SPItem*> const &objects, bool skip_und if (!skip_undo) { SPDocument *document = desktop->getDocument(); - DocumentUndo::maybeDone(document, "UaM", SP_VERB_DIALOG_FILL_STROKE, - _("Set marker color")); + DocumentUndo::maybeDone(document, "UaM", SP_VERB_DIALOG_FILL_STROKE, _("Set marker color")); } } } @@ -1291,14 +1241,12 @@ StrokeStyle::updateAllMarkers(std::vector<SPItem*> const &objects, bool skip_und // Scroll the combobox to that marker combo->set_current(marker); } - } } // namespace Widget } // namespace UI } // namespace Inkscape - /* Local Variables: mode:c++ diff --git a/src/ui/widget/stroke-style.h b/src/ui/widget/stroke-style.h index 4dcbd4a9dce2909dbd59ba021a89065533c91837..c9d7da9fd67cc385acb4b218d3d770f257a48f99 100644 --- a/src/ui/widget/stroke-style.h +++ b/src/ui/widget/stroke-style.h @@ -22,62 +22,53 @@ #include <gtkmm/grid.h> #include <gtkmm/radiobutton.h> - #include "desktop-style.h" #include "desktop.h" +#include "display/drawing.h" #include "document-undo.h" #include "fill-style.h" // to get sp_fill_style_widget_set_desktop #include "gradient-chemistry.h" +#include "helper/stock-items.h" #include "inkscape.h" +#include "io/sys.h" #include "path-prefix.h" #include "preferences.h" #include "selection.h" #include "style.h" -#include "verbs.h" - -#include "display/drawing.h" - -#include "helper/stock-items.h" - -#include "io/sys.h" - #include "svg/css-ostringstream.h" - #include "ui/cache/svg_preview_cache.h" #include "ui/dialog-events.h" #include "ui/icon-names.h" #include "ui/widget/spinbutton.h" - +#include "verbs.h" #include "widgets/spw-utilities.h" - #include "xml/repr.h" namespace Gtk { class Widget; class Container; -} +} // namespace Gtk namespace Inkscape { - namespace Util { - class Unit; - } - namespace UI { - namespace Widget { - class DashSelector; - class MarkerComboBox; - class UnitMenu; - } - } +namespace Util { +class Unit; } +namespace UI { +namespace Widget { +class DashSelector; +class MarkerComboBox; +class UnitMenu; +} // namespace Widget +} // namespace UI +} // namespace Inkscape -struct { gchar const *key; gint value; } const SPMarkerNames[] = { - {"marker-all", SP_MARKER_LOC}, - {"marker-start", SP_MARKER_LOC_START}, - {"marker-mid", SP_MARKER_LOC_MID}, - {"marker-end", SP_MARKER_LOC_END}, - {"", SP_MARKER_LOC_QTY}, - {nullptr, -1} -}; +struct +{ + gchar const *key; + gint value; +} const SPMarkerNames[] = {{"marker-all", SP_MARKER_LOC}, {"marker-start", SP_MARKER_LOC_START}, + {"marker-mid", SP_MARKER_LOC_MID}, {"marker-end", SP_MARKER_LOC_END}, + {"", SP_MARKER_LOC_QTY}, {nullptr, -1}}; SPObject *getMarkerObj(gchar const *n, SPDocument *doc); @@ -95,41 +86,41 @@ public: private: /** List of valid types for the stroke-style radio-button widget */ - enum StrokeStyleButtonType { + enum StrokeStyleButtonType + { STROKE_STYLE_BUTTON_JOIN, ///< A button to set the line-join style STROKE_STYLE_BUTTON_CAP, ///< A button to set the line-cap style STROKE_STYLE_BUTTON_ORDER ///< A button to set the paint-order style }; - + /** * A custom radio-button for setting the stroke style. It can be configured * to set either the join or cap style by setting the button_type field. */ - class StrokeStyleButton : public Gtk::RadioButton { - public: - StrokeStyleButton(Gtk::RadioButtonGroup &grp, - char const *icon, - StrokeStyleButtonType button_type, - gchar const *stroke_style); - - /** Get the type (line/cap) of the stroke-style button */ - inline StrokeStyleButtonType get_button_type() {return button_type;} - - /** Get the stroke style attribute associated with the button */ - inline gchar const * get_stroke_style() {return stroke_style;} - - private: - StrokeStyleButtonType button_type; ///< The type (line/cap) of the button - gchar const *stroke_style; ///< The stroke style associated with the button + class StrokeStyleButton : public Gtk::RadioButton + { + public: + StrokeStyleButton(Gtk::RadioButtonGroup &grp, char const *icon, StrokeStyleButtonType button_type, + gchar const *stroke_style); + + /** Get the type (line/cap) of the stroke-style button */ + inline StrokeStyleButtonType get_button_type() { return button_type; } + + /** Get the stroke style attribute associated with the button */ + inline gchar const *get_stroke_style() { return stroke_style; } + + private: + StrokeStyleButtonType button_type; ///< The type (line/cap) of the button + gchar const *stroke_style; ///< The stroke style associated with the button }; void updateLine(); - void updateAllMarkers(std::vector<SPItem*> const &objects, bool skip_undo = false); + void updateAllMarkers(std::vector<SPItem *> const &objects, bool skip_undo = false); void updateMarkerHist(SPMarkerLoc const which); void setDashSelectorFromStyle(Inkscape::UI::Widget::DashSelector *dsel, SPStyle *style); - void setJoinType (unsigned const jointype); - void setCapType (unsigned const captype); - void setPaintOrder (gchar const *paint_order); + void setJoinType(unsigned const jointype); + void setCapType(unsigned const captype); + void setPaintOrder(gchar const *paint_order); void setJoinButtons(Gtk::ToggleButton *active); void setCapButtons(Gtk::ToggleButton *active); void setPaintOrderButtons(Gtk::ToggleButton *active); @@ -139,11 +130,8 @@ private: SPObject *forkMarker(SPObject *marker, int loc, SPItem *item); const char *getItemColorForMarker(SPItem *item, Inkscape::PaintTarget fill_or_stroke, int loc); - StrokeStyleButton * makeRadioButton(Gtk::RadioButtonGroup &grp, - char const *icon, - Gtk::HBox *hb, - StrokeStyleButtonType button_type, - gchar const *stroke_style); + StrokeStyleButton *makeRadioButton(Gtk::RadioButtonGroup &grp, char const *icon, Gtk::HBox *hb, + StrokeStyleButtonType button_type, gchar const *stroke_style); // Callback functions void selectionModifiedCB(guint flags); @@ -156,7 +144,6 @@ private: static void markerSelectCB(MarkerComboBox *marker_combo, StrokeStyle *spw, SPMarkerLoc const which); static void buttonToggledCB(StrokeStyleButton *tb, StrokeStyle *spw); - MarkerComboBox *startMarkerCombo; MarkerComboBox *midMarkerCombo; MarkerComboBox *endMarkerCombo; @@ -188,7 +175,7 @@ private: sigc::connection midMarkerConn; sigc::connection endMarkerConn; sigc::connection unitChangedConn; - + Inkscape::Util::Unit const *_old_unit; void _handleDocumentReplaced(SPDesktop *, SPDocument *); diff --git a/src/ui/widget/style-subject.cpp b/src/ui/widget/style-subject.cpp index 9c30a423c7e6d397eaaa199e1ac8cb19c9356bcf..036a6470f4b3a4d3c3e593976216237d0ddc3e04 100644 --- a/src/ui/widget/style-subject.cpp +++ b/src/ui/widget/style-subject.cpp @@ -8,24 +8,26 @@ #include "style-subject.h" -#include "desktop.h" #include "desktop-style.h" +#include "desktop.h" #include "selection.h" - #include "xml/sp-css-attr.h" namespace Inkscape { namespace UI { namespace Widget { -StyleSubject::StyleSubject() : _desktop(nullptr) { -} +StyleSubject::StyleSubject() + : _desktop(nullptr) +{} -StyleSubject::~StyleSubject() { +StyleSubject::~StyleSubject() +{ setDesktop(nullptr); } -void StyleSubject::setDesktop(SPDesktop *desktop) { +void StyleSubject::setDesktop(SPDesktop *desktop) +{ if (desktop != _desktop) { if (desktop) { GC::anchor(desktop); @@ -43,7 +45,8 @@ StyleSubject::Selection::Selection() = default; StyleSubject::Selection::~Selection() = default; -Inkscape::Selection *StyleSubject::Selection::_getSelection() const { +Inkscape::Selection *StyleSubject::Selection::_getSelection() const +{ SPDesktop *desktop = getDesktop(); if (desktop) { return desktop->getSelection(); @@ -52,16 +55,18 @@ Inkscape::Selection *StyleSubject::Selection::_getSelection() const { } } -std::vector<SPObject*> StyleSubject::Selection::list() { +std::vector<SPObject *> StyleSubject::Selection::list() +{ Inkscape::Selection *selection = _getSelection(); - if(selection) { + if (selection) { return std::vector<SPObject *>(selection->objects().begin(), selection->objects().end()); } - return std::vector<SPObject*>(); + return std::vector<SPObject *>(); } -Geom::OptRect StyleSubject::Selection::getBounds(SPItem::BBoxType type) { +Geom::OptRect StyleSubject::Selection::getBounds(SPItem::BBoxType type) +{ Inkscape::Selection *selection = _getSelection(); if (selection) { return selection->bounds(type); @@ -70,7 +75,8 @@ Geom::OptRect StyleSubject::Selection::getBounds(SPItem::BBoxType type) { } } -int StyleSubject::Selection::queryStyle(SPStyle *query, int property) { +int StyleSubject::Selection::queryStyle(SPStyle *query, int property) +{ SPDesktop *desktop = getDesktop(); if (desktop) { return sp_desktop_query_style(desktop, query, property); @@ -79,12 +85,14 @@ int StyleSubject::Selection::queryStyle(SPStyle *query, int property) { } } -void StyleSubject::Selection::_afterDesktopSwitch(SPDesktop *desktop) { +void StyleSubject::Selection::_afterDesktopSwitch(SPDesktop *desktop) +{ _sel_changed.disconnect(); _subsel_changed.disconnect(); _sel_modified.disconnect(); if (desktop) { - _subsel_changed = desktop->connectToolSubselectionChanged(sigc::hide(sigc::mem_fun(*this, &Selection::_emitChanged))); + _subsel_changed = + desktop->connectToolSubselectionChanged(sigc::hide(sigc::mem_fun(*this, &Selection::_emitChanged))); Inkscape::Selection *selection = desktop->getSelection(); if (selection) { _sel_changed = selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &Selection::_emitChanged))); @@ -93,20 +101,23 @@ void StyleSubject::Selection::_afterDesktopSwitch(SPDesktop *desktop) { } } -void StyleSubject::Selection::setCSS(SPCSSAttr *css) { +void StyleSubject::Selection::setCSS(SPCSSAttr *css) +{ SPDesktop *desktop = getDesktop(); if (desktop) { sp_desktop_set_style(desktop, css); } } -StyleSubject::CurrentLayer::CurrentLayer() { +StyleSubject::CurrentLayer::CurrentLayer() +{ _element = nullptr; } StyleSubject::CurrentLayer::~CurrentLayer() = default; -void StyleSubject::CurrentLayer::_setLayer(SPObject *layer) { +void StyleSubject::CurrentLayer::_setLayer(SPObject *layer) +{ _layer_release.disconnect(); _layer_modified.disconnect(); if (_element) { @@ -115,28 +126,33 @@ void StyleSubject::CurrentLayer::_setLayer(SPObject *layer) { _element = layer; if (layer) { sp_object_ref(layer, nullptr); - _layer_release = layer->connectRelease(sigc::hide(sigc::bind(sigc::mem_fun(*this, &CurrentLayer::_setLayer), (SPObject *)nullptr))); - _layer_modified = layer->connectModified(sigc::hide(sigc::hide(sigc::mem_fun(*this, &CurrentLayer::_emitChanged)))); + _layer_release = layer->connectRelease( + sigc::hide(sigc::bind(sigc::mem_fun(*this, &CurrentLayer::_setLayer), (SPObject *)nullptr))); + _layer_modified = + layer->connectModified(sigc::hide(sigc::hide(sigc::mem_fun(*this, &CurrentLayer::_emitChanged)))); } _emitChanged(); } -SPObject *StyleSubject::CurrentLayer::_getLayer() const { +SPObject *StyleSubject::CurrentLayer::_getLayer() const +{ return _element; } -SPObject *StyleSubject::CurrentLayer::_getLayerSList() const { - return _element; - +SPObject *StyleSubject::CurrentLayer::_getLayerSList() const +{ + return _element; } -std::vector<SPObject*> StyleSubject::CurrentLayer::list(){ - std::vector<SPObject*> list; +std::vector<SPObject *> StyleSubject::CurrentLayer::list() +{ + std::vector<SPObject *> list; list.push_back(_element); return list; } -Geom::OptRect StyleSubject::CurrentLayer::getBounds(SPItem::BBoxType type) { +Geom::OptRect StyleSubject::CurrentLayer::getBounds(SPItem::BBoxType type) +{ SPObject *layer = _getLayer(); if (layer && SP_IS_ITEM(layer)) { return SP_ITEM(layer)->desktopBounds(type); @@ -145,25 +161,28 @@ Geom::OptRect StyleSubject::CurrentLayer::getBounds(SPItem::BBoxType type) { } } -int StyleSubject::CurrentLayer::queryStyle(SPStyle *query, int property) { - std::vector<SPItem*> list; - SPObject* i=_getLayerSList(); +int StyleSubject::CurrentLayer::queryStyle(SPStyle *query, int property) +{ + std::vector<SPItem *> list; + SPObject *i = _getLayerSList(); if (i) { - list.push_back((SPItem*)i); + list.push_back((SPItem *)i); return sp_desktop_query_style_from_list(list, query, property); } else { return QUERY_STYLE_NOTHING; } } -void StyleSubject::CurrentLayer::setCSS(SPCSSAttr *css) { +void StyleSubject::CurrentLayer::setCSS(SPCSSAttr *css) +{ SPObject *layer = _getLayer(); if (layer) { sp_desktop_apply_css_recursive(layer, css, true); } } -void StyleSubject::CurrentLayer::_afterDesktopSwitch(SPDesktop *desktop) { +void StyleSubject::CurrentLayer::_afterDesktopSwitch(SPDesktop *desktop) +{ _layer_switched.disconnect(); if (desktop) { _layer_switched = desktop->connectCurrentLayerChanged(sigc::mem_fun(*this, &CurrentLayer::_setLayer)); @@ -173,9 +192,9 @@ void StyleSubject::CurrentLayer::_afterDesktopSwitch(SPDesktop *desktop) { } } -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape /* Local Variables: diff --git a/src/ui/widget/style-subject.h b/src/ui/widget/style-subject.h index c2f2b3f93ee118d0c40f15253ba292ff49270f61..bfe6aaeae392fc5030c9ebdc17102e49bb37df67 100644 --- a/src/ui/widget/style-subject.h +++ b/src/ui/widget/style-subject.h @@ -11,15 +11,15 @@ #ifndef SEEN_INKSCAPE_UI_WIDGET_STYLE_SUBJECT_H #define SEEN_INKSCAPE_UI_WIDGET_STYLE_SUBJECT_H -#include <boost/optional.hpp> #include <2geom/rect.h> +#include <boost/optional.hpp> #include <cstddef> #include <sigc++/sigc++.h> #include "object/sp-item.h" -#include "object/sp-tag.h" -#include "object/sp-tag-use.h" #include "object/sp-tag-use-reference.h" +#include "object/sp-tag-use.h" +#include "object/sp-tag.h" class SPDesktop; class SPObject; @@ -34,12 +34,12 @@ namespace Inkscape { namespace UI { namespace Widget { -class StyleSubject { +class StyleSubject +{ public: class Selection; class CurrentLayer; - StyleSubject(); virtual ~StyleSubject(); @@ -49,16 +49,15 @@ public: virtual Geom::OptRect getBounds(SPItem::BBoxType type) = 0; virtual int queryStyle(SPStyle *query, int property) = 0; virtual void setCSS(SPCSSAttr *css) = 0; - virtual std::vector<SPObject*> list(){return std::vector<SPObject*>();}; + virtual std::vector<SPObject *> list() { return std::vector<SPObject *>(); }; - sigc::connection connectChanged(sigc::signal<void>::slot_type slot) { - return _changed_signal.connect(slot); - } + sigc::connection connectChanged(sigc::signal<void>::slot_type slot) { return _changed_signal.connect(slot); } protected: - virtual void _afterDesktopSwitch(SPDesktop */*desktop*/) {} + virtual void _afterDesktopSwitch(SPDesktop * /*desktop*/) {} void _emitChanged() { _changed_signal.emit(); } - void _emitModified(Inkscape::Selection* selection, guint flags) { + void _emitModified(Inkscape::Selection *selection, guint flags) + { // Do not say this object has styles unless it's style has been modified if (flags & (SP_OBJECT_STYLE_MODIFIED_FLAG)) { _emitChanged(); @@ -70,7 +69,8 @@ private: SPDesktop *_desktop; }; -class StyleSubject::Selection : public StyleSubject { +class StyleSubject::Selection : public StyleSubject +{ public: Selection(); ~Selection() override; @@ -78,7 +78,7 @@ public: Geom::OptRect getBounds(SPItem::BBoxType type) override; int queryStyle(SPStyle *query, int property) override; void setCSS(SPCSSAttr *css) override; - std::vector<SPObject*> list() override; + std::vector<SPObject *> list() override; protected: void _afterDesktopSwitch(SPDesktop *desktop) override; @@ -91,7 +91,8 @@ private: sigc::connection _sel_modified; }; -class StyleSubject::CurrentLayer : public StyleSubject { +class StyleSubject::CurrentLayer : public StyleSubject +{ public: CurrentLayer(); ~CurrentLayer() override; @@ -99,7 +100,7 @@ public: Geom::OptRect getBounds(SPItem::BBoxType type) override; int queryStyle(SPStyle *query, int property) override; void setCSS(SPCSSAttr *css) override; - std::vector<SPObject*> list() override; + std::vector<SPObject *> list() override; protected: void _afterDesktopSwitch(SPDesktop *desktop) override; @@ -112,12 +113,12 @@ private: sigc::connection _layer_switched; sigc::connection _layer_release; sigc::connection _layer_modified; - mutable SPObject* _element; + mutable SPObject *_element; }; -} -} -} +} // namespace Widget +} // namespace UI +} // namespace Inkscape #endif // SEEN_INKSCAPE_UI_WIDGET_STYLE_SUBJECT_H diff --git a/src/ui/widget/style-swatch.cpp b/src/ui/widget/style-swatch.cpp index eebebae3260d75a44cfed3ab578e2a4aee5b97b5..1dff21e6e643dc601aafcc30d6af6cfb064324e9 100644 --- a/src/ui/widget/style-swatch.cpp +++ b/src/ui/widget/style-swatch.cpp @@ -17,25 +17,21 @@ #include <glibmm/i18n.h> #include <gtkmm/grid.h> +#include "helper/action.h" #include "inkscape.h" -#include "verbs.h" - #include "object/sp-linear-gradient.h" #include "object/sp-pattern.h" #include "object/sp-radial-gradient.h" #include "style.h" - -#include "helper/action.h" - #include "ui/widget/color-preview.h" #include "util/units.h" - +#include "verbs.h" #include "widgets/spw-utilities.h" #include "widgets/widget-sizes.h" - #include "xml/sp-css-attr.h" -enum { +enum +{ SS_FILL, SS_STROKE }; @@ -47,13 +43,15 @@ namespace Widget { /** * Watches whether the tool uses the current style. */ -class StyleSwatch::ToolObserver : public Inkscape::Preferences::Observer { +class StyleSwatch::ToolObserver : public Inkscape::Preferences::Observer +{ public: - ToolObserver(Glib::ustring const &path, StyleSwatch &ss) : - Observer(path), - _style_swatch(ss) + ToolObserver(Glib::ustring const &path, StyleSwatch &ss) + : Observer(path) + , _style_swatch(ss) {} void notify(Inkscape::Preferences::Entry const &val) override; + private: StyleSwatch &_style_swatch; }; @@ -61,20 +59,23 @@ private: /** * Watches for changes in the observed style pref. */ -class StyleSwatch::StyleObserver : public Inkscape::Preferences::Observer { +class StyleSwatch::StyleObserver : public Inkscape::Preferences::Observer +{ public: - StyleObserver(Glib::ustring const &path, StyleSwatch &ss) : - Observer(path), - _style_swatch(ss) + StyleObserver(Glib::ustring const &path, StyleSwatch &ss) + : Observer(path) + , _style_swatch(ss) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); this->notify(prefs->getEntry(path)); } - void notify(Inkscape::Preferences::Entry const &val) override { + void notify(Inkscape::Preferences::Entry const &val) override + { SPCSSAttr *css = val.getInheritedStyle(); _style_swatch.setStyle(css); sp_repr_css_attr_unref(css); } + private: StyleSwatch &_style_swatch; }; @@ -84,11 +85,12 @@ void StyleSwatch::ToolObserver::notify(Inkscape::Preferences::Entry const &val) bool usecurrent = val.getBool(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (_style_swatch._style_obs) delete _style_swatch._style_obs; + if (_style_swatch._style_obs) + delete _style_swatch._style_obs; if (usecurrent) { _style_swatch._style_obs = new StyleObserver("/desktop/style", _style_swatch); - + // If desktop's last-set style is empty, a tool uses its own fixed style even if set to use // last-set (so long as it's empty). To correctly show this, we get the tool's style // if the desktop's style is empty. @@ -106,17 +108,16 @@ void StyleSwatch::ToolObserver::notify(Inkscape::Preferences::Entry const &val) } StyleSwatch::StyleSwatch(SPCSSAttr *css, gchar const *main_tip) - : - _desktop(nullptr), - _verb_t(0), - _css(nullptr), - _tool_obs(nullptr), - _style_obs(nullptr), - _table(Gtk::manage(new Gtk::Grid())), - _sw_unit(nullptr) + : _desktop(nullptr) + , _verb_t(0) + , _css(nullptr) + , _tool_obs(nullptr) + , _style_obs(nullptr) + , _table(Gtk::manage(new Gtk::Grid())) + , _sw_unit(nullptr) { set_name("StyleSwatch"); - + _label[SS_FILL].set_markup(_("Fill:")); _label[SS_STROKE].set_markup(_("Stroke:")); @@ -128,7 +129,7 @@ StyleSwatch::StyleSwatch(SPCSSAttr *css, gchar const *main_tip) _label[i].set_margin_start(0); _label[i].set_margin_end(0); - _color_preview[i] = new Inkscape::UI::Widget::ColorPreview (0); + _color_preview[i] = new Inkscape::UI::Widget::ColorPreview(0); } _opacity_value.set_halign(Gtk::ALIGN_START); @@ -144,45 +145,45 @@ StyleSwatch::StyleSwatch(SPCSSAttr *css, gchar const *main_tip) _stroke.pack_start(_place[SS_STROKE]); _stroke_width_place.add(_stroke_width); _stroke.pack_start(_stroke_width_place, Gtk::PACK_SHRINK); - + _opacity_place.add(_opacity_value); - _table->attach(_label[SS_FILL], 0, 0, 1, 1); + _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); + _table->attach(_place[SS_FILL], 1, 0, 1, 1); + _table->attach(_stroke, 1, 1, 1, 1); + _table->attach(_opacity_place, 2, 0, 1, 2); _swatch.add(*_table); pack_start(_swatch, true, true, 0); - set_size_request (STYLE_SWATCH_WIDTH, -1); + set_size_request(STYLE_SWATCH_WIDTH, -1); - setStyle (css); + setStyle(css); _swatch.signal_button_press_event().connect(sigc::mem_fun(*this, &StyleSwatch::on_click)); - if (main_tip) - { + if (main_tip) { _swatch.set_tooltip_text(main_tip); } } -void StyleSwatch::setClickVerb(sp_verb_t verb_t) { +void StyleSwatch::setClickVerb(sp_verb_t verb_t) +{ _verb_t = verb_t; } -void StyleSwatch::setDesktop(SPDesktop *desktop) { +void StyleSwatch::setDesktop(SPDesktop *desktop) +{ _desktop = desktop; } -bool -StyleSwatch::on_click(GdkEventButton */*event*/) +bool 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::ActionContext((Inkscape::UI::View::View *) this->_desktop)); - sp_action_perform (action, nullptr); + SPAction *action = verb->get_action(Inkscape::ActionContext((Inkscape::UI::View::View *)this->_desktop)); + sp_action_perform(action, nullptr); return true; } return false; @@ -191,21 +192,22 @@ StyleSwatch::on_click(GdkEventButton */*event*/) StyleSwatch::~StyleSwatch() { if (_css) - sp_repr_css_attr_unref (_css); + sp_repr_css_attr_unref(_css); for (int i = SS_FILL; i <= SS_STROKE; i++) { delete _color_preview[i]; } - if (_style_obs) delete _style_obs; - if (_tool_obs) delete _tool_obs; + if (_style_obs) + delete _style_obs; + if (_tool_obs) + delete _tool_obs; } -void -StyleSwatch::setWatchedTool(const char *path, bool synthesize) +void StyleSwatch::setWatchedTool(const char *path, bool synthesize) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - + if (_tool_obs) { delete _tool_obs; _tool_obs = nullptr; @@ -218,7 +220,7 @@ StyleSwatch::setWatchedTool(const char *path, bool synthesize) } else { _tool_path = ""; } - + // hack until there is a real synthesize events function for prefs, // which shouldn't be hard to write once there is sufficient need for it if (synthesize && _tool_obs) { @@ -226,11 +228,10 @@ StyleSwatch::setWatchedTool(const char *path, bool synthesize) } } - void StyleSwatch::setStyle(SPCSSAttr *css) { if (_css) - sp_repr_css_attr_unref (_css); + sp_repr_css_attr_unref(_css); if (!css) return; @@ -239,13 +240,13 @@ void StyleSwatch::setStyle(SPCSSAttr *css) sp_repr_css_merge(_css, css); Glib::ustring css_string; - sp_repr_css_write_string (_css, css_string); + sp_repr_css_write_string(_css, css_string); SPStyle style(_desktop ? _desktop->getDocument() : nullptr); if (!css_string.empty()) { style.mergeString(css_string.c_str()); } - setStyle (&style); + setStyle(&style); } void StyleSwatch::setStyle(SPStyle *query) @@ -266,49 +267,55 @@ void StyleSwatch::setStyle(SPStyle *query) } if (paint->set && paint->isPaintserver()) { - SPPaintServer *server = (i == SS_FILL)? SP_STYLE_FILL_SERVER (query) : SP_STYLE_STROKE_SERVER (query); + SPPaintServer *server = (i == SS_FILL) ? SP_STYLE_FILL_SERVER(query) : SP_STYLE_STROKE_SERVER(query); - if (SP_IS_LINEARGRADIENT (server)) { + if (SP_IS_LINEARGRADIENT(server)) { _value[i].set_markup(_("L Gradient")); place->add(_value[i]); - place->set_tooltip_text((i == SS_FILL)? (_("Linear gradient (fill)")) : (_("Linear gradient (stroke)"))); - } else if (SP_IS_RADIALGRADIENT (server)) { + place->set_tooltip_text((i == SS_FILL) ? (_("Linear gradient (fill)")) + : (_("Linear gradient (stroke)"))); + } else if (SP_IS_RADIALGRADIENT(server)) { _value[i].set_markup(_("R Gradient")); place->add(_value[i]); - place->set_tooltip_text((i == SS_FILL)? (_("Radial gradient (fill)")) : (_("Radial gradient (stroke)"))); - } else if (SP_IS_PATTERN (server)) { + place->set_tooltip_text((i == SS_FILL) ? (_("Radial gradient (fill)")) + : (_("Radial gradient (stroke)"))); + } else if (SP_IS_PATTERN(server)) { _value[i].set_markup(_("Pattern")); place->add(_value[i]); - place->set_tooltip_text((i == SS_FILL)? (_("Pattern (fill)")) : (_("Pattern (stroke)"))); + place->set_tooltip_text((i == SS_FILL) ? (_("Pattern (fill)")) : (_("Pattern (stroke)"))); } } else if (paint->set && paint->isColor()) { - guint32 color = paint->value.color.toRGBA32( SP_SCALE24_TO_FLOAT ((i == SS_FILL)? query->fill_opacity.value : query->stroke_opacity.value) ); - ((Inkscape::UI::Widget::ColorPreview*)_color_preview[i])->setRgba32 (color); + guint32 color = paint->value.color.toRGBA32( + SP_SCALE24_TO_FLOAT((i == SS_FILL) ? query->fill_opacity.value : query->stroke_opacity.value)); + ((Inkscape::UI::Widget::ColorPreview *)_color_preview[i])->setRgba32(color); _color_preview[i]->show_all(); place->add(*_color_preview[i]); gchar *tip; if (i == SS_FILL) { - tip = g_strdup_printf (_("Fill: %06x/%.3g"), color >> 8, SP_RGBA32_A_F(color)); + tip = g_strdup_printf(_("Fill: %06x/%.3g"), color >> 8, SP_RGBA32_A_F(color)); } else { - tip = g_strdup_printf (_("Stroke: %06x/%.3g"), color >> 8, SP_RGBA32_A_F(color)); + tip = g_strdup_printf(_("Stroke: %06x/%.3g"), color >> 8, SP_RGBA32_A_F(color)); } place->set_tooltip_text(tip); - g_free (tip); + g_free(tip); } else if (paint->set && paint->isNone()) { _value[i].set_markup(C_("Fill and stroke", "<i>None</i>")); place->add(_value[i]); - place->set_tooltip_text((i == SS_FILL)? (C_("Fill and stroke", "No fill")) : (C_("Fill and stroke", "No stroke"))); - if (i == SS_STROKE) has_stroke = false; + place->set_tooltip_text((i == SS_FILL) ? (C_("Fill and stroke", "No fill")) + : (C_("Fill and stroke", "No stroke"))); + if (i == SS_STROKE) + has_stroke = false; } else if (!paint->set) { _value[i].set_markup(_("<b>Unset</b>")); place->add(_value[i]); - place->set_tooltip_text((i == SS_FILL)? (_("Unset fill")) : (_("Unset stroke"))); - if (i == SS_STROKE) has_stroke = false; + place->set_tooltip_text((i == SS_FILL) ? (_("Unset fill")) : (_("Unset stroke"))); + if (i == SS_STROKE) + has_stroke = false; } } -// Now query stroke_width + // Now query stroke_width if (has_stroke) { double w; if (_sw_unit) { @@ -320,14 +327,12 @@ void StyleSwatch::setStyle(SPStyle *query) { gchar *str = g_strdup_printf(" %.3g", w); _stroke_width.set_markup(str); - g_free (str); + g_free(str); } { - gchar *str = g_strdup_printf(_("Stroke width: %.5g%s"), - w, - _sw_unit? _sw_unit->abbr.c_str() : "px"); + gchar *str = g_strdup_printf(_("Stroke width: %.5g%s"), w, _sw_unit ? _sw_unit->abbr.c_str() : "px"); _stroke_width_place.set_tooltip_text(str); - g_free (str); + g_free(str); } } else { _stroke_width_place.set_tooltip_text(""); @@ -339,14 +344,14 @@ void StyleSwatch::setStyle(SPStyle *query) if (op != 1) { { gchar *str; - str = g_strdup_printf(_("O: %2.0f"), (op*100.0)); - _opacity_value.set_markup (str); - g_free (str); + str = g_strdup_printf(_("O: %2.0f"), (op * 100.0)); + _opacity_value.set_markup(str); + g_free(str); } { - gchar *str = g_strdup_printf(_("Opacity: %2.1f %%"), (op*100.0)); + gchar *str = g_strdup_printf(_("Opacity: %2.1f %%"), (op * 100.0)); _opacity_place.set_tooltip_text(str); - g_free (str); + g_free(str); } } else { _opacity_place.set_tooltip_text(""); diff --git a/src/ui/widget/style-swatch.h b/src/ui/widget/style-swatch.h index 4c7dc51b58568c11f71ec0d6fc88a6086b262217..a84401b099b8cb38ddc71048d34b762197db8ad2 100644 --- a/src/ui/widget/style-swatch.h +++ b/src/ui/widget/style-swatch.h @@ -15,9 +15,9 @@ #define INKSCAPE_UI_CURRENT_STYLE_H #include <gtkmm/box.h> -#include <gtkmm/label.h> -#include <gtkmm/eventbox.h> #include <gtkmm/enums.h> +#include <gtkmm/eventbox.h> +#include <gtkmm/label.h> #include "desktop.h" #include "preferences.h" @@ -32,7 +32,7 @@ class Grid; namespace Inkscape { namespace Util { - class Unit; +class Unit; } namespace UI { @@ -41,7 +41,7 @@ namespace Widget { class StyleSwatch : public Gtk::HBox { public: - StyleSwatch (SPCSSAttr *attr, gchar const *main_tip); + StyleSwatch(SPCSSAttr *attr, gchar const *main_tip); ~StyleSwatch() override; @@ -49,7 +49,7 @@ public: void setStyle(SPCSSAttr *attr); SPCSSAttr *getStyle(); - void setWatchedTool (const char *path, bool synthesize); + void setWatchedTool(const char *path, bool synthesize); void setClickVerb(sp_verb_t verb_t); void setDesktop(SPDesktop *desktop); @@ -83,10 +83,9 @@ private: Inkscape::Util::Unit *_sw_unit; -friend class ToolObserver; + friend class ToolObserver; }; - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/swatch-selector.cpp b/src/ui/widget/swatch-selector.cpp index 9a351498ee05e6401b2b89d6c8f5b56ba2f07d03..0c4908ef745e2f1fe3d022001611cdfaf9b8e6c1 100644 --- a/src/ui/widget/swatch-selector.cpp +++ b/src/ui/widget/swatch-selector.cpp @@ -15,26 +15,22 @@ #include "document-undo.h" #include "document.h" #include "gradient-chemistry.h" -#include "verbs.h" - #include "object/sp-stop.h" - #include "svg/css-ostringstream.h" #include "svg/svg-color.h" - #include "ui/widget/color-notebook.h" #include "ui/widget/gradient-selector.h" - +#include "verbs.h" #include "xml/node.h" namespace Inkscape { namespace UI { namespace Widget { -SwatchSelector::SwatchSelector() : - Gtk::VBox(), - _gsel(nullptr), - _updating_color(false) +SwatchSelector::SwatchSelector() + : Gtk::VBox() + , _gsel(nullptr) + , _updating_color(false) { using Inkscape::UI::Widget::ColorNotebook; @@ -83,39 +79,37 @@ void SwatchSelector::_changedCb() ngr->ensureVector(); - - SPStop* stop = ngr->getFirstStop(); + SPStop *stop = ngr->getFirstStop(); if (stop) { SPColor color = _selected_color.color(); gfloat alpha = _selected_color.alpha(); - guint32 rgb = color.toRGBA32( 0x00 ); + guint32 rgb = color.toRGBA32(0x00); // TODO replace with generic shared code that also handles icc-color Inkscape::CSSOStringStream os; gchar c[64]; sp_svg_write_color(c, sizeof(c), rgb); - os << "stop-color:" << c << ";stop-opacity:" << static_cast<gdouble>(alpha) <<";"; + os << "stop-color:" << c << ";stop-opacity:" << static_cast<gdouble>(alpha) << ";"; stop->setAttribute("style", os.str()); - DocumentUndo::done(ngr->document, SP_VERB_CONTEXT_GRADIENT, - _("Change swatch color")); + DocumentUndo::done(ngr->document, SP_VERB_CONTEXT_GRADIENT, _("Change swatch color")); } } } -void SwatchSelector::connectchangedHandler( GCallback handler, void *data ) +void SwatchSelector::connectchangedHandler(GCallback handler, void *data) { - GObject* obj = G_OBJECT(_gsel); - g_signal_connect( obj, "changed", handler, data ); + GObject *obj = G_OBJECT(_gsel); + g_signal_connect(obj, "changed", handler, data); } -void SwatchSelector::setVector(SPDocument */*doc*/, SPGradient *vector) +void SwatchSelector::setVector(SPDocument * /*doc*/, SPGradient *vector) { - //GtkVBox * box = gobj(); + // GtkVBox * box = gobj(); _gsel->setVector((vector) ? vector->document : nullptr, vector); - if ( vector && vector->isSolid() ) { - SPStop* stop = vector->getFirstStop(); + if (vector && vector->isSolid()) { + SPStop *stop = vector->getFirstStop(); guint32 const colorVal = stop->get_rgba32(); _updating_color = true; @@ -123,19 +117,17 @@ void SwatchSelector::setVector(SPDocument */*doc*/, SPGradient *vector) _updating_color = false; // gtk_widget_show_all( GTK_WIDGET(_csel) ); } else { - //gtk_widget_hide( GTK_WIDGET(_csel) ); + // gtk_widget_hide( GTK_WIDGET(_csel) ); } -/* -*/ + /* + */ } } // namespace Widget } // namespace UI } // namespace Inkscape - - /* Local Variables: mode:c++ diff --git a/src/ui/widget/swatch-selector.h b/src/ui/widget/swatch-selector.h index d64320d944515df4df23422e044e3ab74c8b392a..755dd69c38a15b166085052a437821056d3f312f 100644 --- a/src/ui/widget/swatch-selector.h +++ b/src/ui/widget/swatch-selector.h @@ -11,6 +11,7 @@ #define SEEN_SP_SWATCH_SELECTOR_H #include <gtkmm/box.h> + #include "ui/selected-color.h" class SPDocument; @@ -28,7 +29,7 @@ public: SwatchSelector(); ~SwatchSelector() override; - void connectchangedHandler( GCallback handler, void *data ); + void connectchangedHandler(GCallback handler, void *data); void setVector(SPDocument *doc, SPGradient *vector); @@ -45,7 +46,6 @@ private: bool _updating_color; }; - } // namespace Widget } // namespace UI } // namespace Inkscape @@ -62,4 +62,3 @@ private: End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : - diff --git a/src/ui/widget/text.cpp b/src/ui/widget/text.cpp index 656ec45e2e2369a555713d7d6ed2ed579a37b937..e6411d7f6d162b27783c0ac4326c018961d9a7cf 100644 --- a/src/ui/widget/text.cpp +++ b/src/ui/widget/text.cpp @@ -10,40 +10,37 @@ */ #include "text.h" + #include <gtkmm/entry.h> namespace Inkscape { namespace UI { namespace Widget { -Text::Text(Glib::ustring const &label, Glib::ustring const &tooltip, - Glib::ustring const &suffix, - Glib::ustring const &icon, - bool mnemonic) - : Labelled(label, tooltip, new Gtk::Entry(), suffix, icon, mnemonic), - setProgrammatically(false) -{ -} +Text::Text(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix, + Glib::ustring const &icon, bool mnemonic) + : Labelled(label, tooltip, new Gtk::Entry(), suffix, icon, mnemonic) + , setProgrammatically(false) +{} Glib::ustring const Text::getText() const { g_assert(_widget != nullptr); - return static_cast<Gtk::Entry*>(_widget)->get_text(); + return static_cast<Gtk::Entry *>(_widget)->get_text(); } void Text::setText(Glib::ustring const text) { g_assert(_widget != nullptr); - setProgrammatically = true; // callback is supposed to reset back, if it cares - static_cast<Gtk::Entry*>(_widget)->set_text(text); // FIXME: set correctly + setProgrammatically = true; // callback is supposed to reset back, if it cares + static_cast<Gtk::Entry *>(_widget)->set_text(text); // FIXME: set correctly } Glib::SignalProxy0<void> Text::signal_activate() { - return static_cast<Gtk::Entry*>(_widget)->signal_activate(); + return static_cast<Gtk::Entry *>(_widget)->signal_activate(); } - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/text.h b/src/ui/widget/text.h index 87c93572c970888ff3ce2d6e2746cb33a3466d8a..575fdaf99381aea62fdf891de51ea1da34f48e76 100644 --- a/src/ui/widget/text.h +++ b/src/ui/widget/text.h @@ -14,7 +14,6 @@ #include "labelled.h" - namespace Inkscape { namespace UI { namespace Widget { @@ -25,7 +24,6 @@ namespace Widget { class Text : public Labelled { public: - /** * Construct a Text Widget. * @@ -36,11 +34,8 @@ public: * indicates the next character should be used for the * mnemonic accelerator key (defaults to false). */ - Text(Glib::ustring const &label, - Glib::ustring const &tooltip, - Glib::ustring const &suffix = "", - Glib::ustring const &icon = "", - bool mnemonic = true); + Text(Glib::ustring const &label, Glib::ustring const &tooltip, Glib::ustring const &suffix = "", + Glib::ustring const &icon = "", bool mnemonic = true); /** * Get the text in the entry. diff --git a/src/ui/widget/tolerance-slider.cpp b/src/ui/widget/tolerance-slider.cpp index 4b2456f93c1e95f3343a0f8e77e3e2bb69952047..550ae2082c606ea9da462bf359e5b8dad60e1bae 100644 --- a/src/ui/widget/tolerance-slider.cpp +++ b/src/ui/widget/tolerance-slider.cpp @@ -11,23 +11,19 @@ #include "tolerance-slider.h" -#include "registry.h" - #include <gtkmm/adjustment.h> #include <gtkmm/box.h> #include <gtkmm/label.h> #include <gtkmm/radiobutton.h> #include <gtkmm/scale.h> -#include "inkscape.h" -#include "document.h" -#include "document-undo.h" #include "desktop.h" - +#include "document-undo.h" +#include "document.h" +#include "inkscape.h" #include "object/sp-namedview.h" - +#include "registry.h" #include "svg/stringstream.h" - #include "xml/repr.h" namespace Inkscape { @@ -38,37 +34,40 @@ namespace Widget { //--------------------------------------------------- - - //==================================================== -ToleranceSlider::ToleranceSlider(const Glib::ustring& label1, const Glib::ustring& label2, const Glib::ustring& label3, const Glib::ustring& tip1, const Glib::ustring& tip2, const Glib::ustring& tip3, const Glib::ustring& key, Registry& wr) -: _vbox(nullptr) +ToleranceSlider::ToleranceSlider(const Glib::ustring &label1, const Glib::ustring &label2, const Glib::ustring &label3, + const Glib::ustring &tip1, const Glib::ustring &tip2, const Glib::ustring &tip3, + const Glib::ustring &key, Registry &wr) + : _vbox(nullptr) { init(label1, label2, label3, tip1, tip2, tip3, key, wr); } ToleranceSlider::~ToleranceSlider() { - if (_vbox) delete _vbox; + if (_vbox) + delete _vbox; _scale_changed_connection.disconnect(); } -void ToleranceSlider::init (const Glib::ustring& label1, const Glib::ustring& label2, const Glib::ustring& label3, const Glib::ustring& tip1, const Glib::ustring& tip2, const Glib::ustring& tip3, const Glib::ustring& key, Registry& wr) +void ToleranceSlider::init(const Glib::ustring &label1, const Glib::ustring &label2, const Glib::ustring &label3, + const Glib::ustring &tip1, const Glib::ustring &tip2, const Glib::ustring &tip3, + const Glib::ustring &key, Registry &wr) { // hbox = label + slider // - // e.g. + // e.g. // // snap distance |-------X---| 37 - + // vbox = checkbutton // + // hbox - + _vbox = new Gtk::VBox; _hbox = Gtk::manage(new Gtk::HBox); - + Gtk::Label *theLabel1 = Gtk::manage(new Gtk::Label(label1)); theLabel1->set_use_underline(); theLabel1->set_halign(Gtk::ALIGN_START); @@ -79,112 +78,107 @@ void ToleranceSlider::init (const Glib::ustring& label1, const Glib::ustring& la _hscale = Gtk::manage(new Gtk::Scale(Gtk::ORIENTATION_HORIZONTAL)); _hscale->set_range(1.0, 51.0); - theLabel1->set_mnemonic_widget (*_hscale); - _hscale->set_draw_value (true); - _hscale->set_value_pos (Gtk::POS_RIGHT); - _hscale->set_size_request (100, -1); + theLabel1->set_mnemonic_widget(*_hscale); + _hscale->set_draw_value(true); + _hscale->set_value_pos(Gtk::POS_RIGHT); + _hscale->set_size_request(100, -1); _old_val = 10; - _hscale->set_value (_old_val); - _hscale->set_tooltip_text (tip1); - _hbox->add (*_hscale); - - + _hscale->set_value(_old_val); + _hscale->set_tooltip_text(tip1); + _hbox->add(*_hscale); + Gtk::Label *theLabel2 = Gtk::manage(new Gtk::Label(label2)); theLabel2->set_use_underline(); Gtk::Label *theLabel3 = Gtk::manage(new Gtk::Label(label3)); - theLabel3->set_use_underline(); + theLabel3->set_use_underline(); _button1 = Gtk::manage(new Gtk::RadioButton); _radio_button_group = _button1->get_group(); _button2 = Gtk::manage(new Gtk::RadioButton); - _button2->set_group(_radio_button_group); - _button1->set_tooltip_text (tip2); - _button2->set_tooltip_text (tip3); - _button1->add (*theLabel3); + _button2->set_group(_radio_button_group); + _button1->set_tooltip_text(tip2); + _button2->set_tooltip_text(tip3); + _button1->add(*theLabel3); _button1->set_halign(Gtk::ALIGN_START); _button1->set_valign(Gtk::ALIGN_CENTER); - _button2->add (*theLabel2); + _button2->add(*theLabel2); _button2->set_halign(Gtk::ALIGN_START); _button2->set_valign(Gtk::ALIGN_CENTER); - - _vbox->add (*_button1); - _vbox->add (*_button2); - // Here we need some extra pixels to get the vertical spacing right. Why? - _vbox->pack_end(*_hbox, true, true, 3); // add 3 px. + + _vbox->add(*_button1); + _vbox->add(*_button2); + // Here we need some extra pixels to get the vertical spacing right. Why? + _vbox->pack_end(*_hbox, true, true, 3); // add 3 px. _key = key; - _scale_changed_connection = _hscale->signal_value_changed().connect (sigc::mem_fun (*this, &ToleranceSlider::on_scale_changed)); - _btn_toggled_connection = _button2->signal_toggled().connect (sigc::mem_fun (*this, &ToleranceSlider::on_toggled)); + _scale_changed_connection = + _hscale->signal_value_changed().connect(sigc::mem_fun(*this, &ToleranceSlider::on_scale_changed)); + _btn_toggled_connection = _button2->signal_toggled().connect(sigc::mem_fun(*this, &ToleranceSlider::on_toggled)); _wr = ≀ _vbox->show_all_children(); } -void ToleranceSlider::setValue (double val) +void ToleranceSlider::setValue(double val) { auto adj = _hscale->get_adjustment(); - adj->set_lower (1.0); - adj->set_upper (51.0); - adj->set_step_increment (1.0); + adj->set_lower(1.0); + adj->set_upper(51.0); + adj->set_step_increment(1.0); if (val > 9999.9) // magic value 10000.0 { - _button1->set_active (true); - _button2->set_active (false); - _hbox->set_sensitive (false); + _button1->set_active(true); + _button2->set_active(false); + _hbox->set_sensitive(false); val = 50.0; + } else { + _button1->set_active(false); + _button2->set_active(true); + _hbox->set_sensitive(true); } - else - { - _button1->set_active (false); - _button2->set_active (true); - _hbox->set_sensitive (true); - } - _hscale->set_value (val); + _hscale->set_value(val); _hbox->show_all(); } -void ToleranceSlider::setLimits (double theMin, double theMax) +void ToleranceSlider::setLimits(double theMin, double theMax) { - _hscale->set_range (theMin, theMax); - _hscale->get_adjustment()->set_step_increment (1); + _hscale->set_range(theMin, theMax); + _hscale->get_adjustment()->set_step_increment(1); } void ToleranceSlider::on_scale_changed() { - update (_hscale->get_value()); + update(_hscale->get_value()); } void ToleranceSlider::on_toggled() { - if (!_button2->get_active()) - { + if (!_button2->get_active()) { _old_val = _hscale->get_value(); - _hbox->set_sensitive (false); + _hbox->set_sensitive(false); _hbox->show_all(); - setValue (10000.0); - update (10000.0); - } - else - { - _hbox->set_sensitive (true); + setValue(10000.0); + update(10000.0); + } else { + _hbox->set_sensitive(true); _hbox->show_all(); - setValue (_old_val); - update (_old_val); + setValue(_old_val); + update(_old_val); } } -void ToleranceSlider::update (double val) +void ToleranceSlider::update(double val) { if (_wr->isUpdating()) return; SPDesktop *dt = _wr->desktop(); - if (!dt) + if (!dt) return; Inkscape::SVGOStringStream os; os << val; - _wr->setUpdating (true); + _wr->setUpdating(true); SPDocument *doc = dt->getDocument(); bool saved = DocumentUndo::getUndoSensitive(doc); @@ -194,12 +188,11 @@ void ToleranceSlider::update (double val) DocumentUndo::setUndoSensitive(doc, saved); doc->setModifiedSinceSave(); - - _wr->setUpdating (false); -} + _wr->setUpdating(false); +} -} // namespace Dialog +} // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/tolerance-slider.h b/src/ui/widget/tolerance-slider.h index 1c4af1d37de68297e02bb76ea008606952785feb..b476663f53ebfd2870efef08ff13233148fe4d7d 100644 --- a/src/ui/widget/tolerance-slider.h +++ b/src/ui/widget/tolerance-slider.h @@ -18,7 +18,7 @@ class RadioButton; class Scale; class VBox; class HBox; -} +} // namespace Gtk namespace Inkscape { namespace UI { @@ -30,47 +30,38 @@ class Registry; * Implementation of tolerance slider widget. * This widget is part of the Document properties dialog. */ -class ToleranceSlider { +class ToleranceSlider +{ public: - ToleranceSlider(const Glib::ustring& label1, - const Glib::ustring& label2, - const Glib::ustring& label3, - const Glib::ustring& tip1, - const Glib::ustring& tip2, - const Glib::ustring& tip3, - const Glib::ustring& key, - Registry& wr); + ToleranceSlider(const Glib::ustring &label1, const Glib::ustring &label2, const Glib::ustring &label3, + const Glib::ustring &tip1, const Glib::ustring &tip2, const Glib::ustring &tip3, + const Glib::ustring &key, Registry &wr); ~ToleranceSlider(); - void setValue (double); - void setLimits (double, double); - Gtk::VBox* _vbox; + void setValue(double); + void setLimits(double, double); + Gtk::VBox *_vbox; + private: - void init (const Glib::ustring& label1, - const Glib::ustring& label2, - const Glib::ustring& label3, - const Glib::ustring& tip1, - const Glib::ustring& tip2, - const Glib::ustring& tip3, - const Glib::ustring& key, - Registry& wr); + void init(const Glib::ustring &label1, const Glib::ustring &label2, const Glib::ustring &label3, + const Glib::ustring &tip1, const Glib::ustring &tip2, const Glib::ustring &tip3, const Glib::ustring &key, + Registry &wr); protected: void on_scale_changed(); void on_toggled(); - void update (double val); - Gtk::HBox *_hbox; - Gtk::Scale *_hscale; + void update(double val); + Gtk::HBox *_hbox; + Gtk::Scale *_hscale; Gtk::RadioButtonGroup _radio_button_group; - Gtk::RadioButton *_button1; - Gtk::RadioButton *_button2; - Registry *_wr; - Glib::ustring _key; - sigc::connection _scale_changed_connection; - sigc::connection _btn_toggled_connection; + Gtk::RadioButton *_button1; + Gtk::RadioButton *_button2; + Registry *_wr; + Glib::ustring _key; + sigc::connection _scale_changed_connection; + sigc::connection _btn_toggled_connection; double _old_val; }; - } // namespace Widget } // namespace UI } // namespace Inkscape diff --git a/src/ui/widget/unit-menu.cpp b/src/ui/widget/unit-menu.cpp index aaf565fadf6edb82dd52f89a897e79b5d70cb81f..fb74121376f7461b6594c73c8b63589f87aa34e5 100644 --- a/src/ui/widget/unit-menu.cpp +++ b/src/ui/widget/unit-menu.cpp @@ -8,17 +8,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cmath> - #include "unit-menu.h" +#include <cmath> + using Inkscape::Util::unit_table; namespace Inkscape { namespace UI { namespace Widget { -UnitMenu::UnitMenu() : _type(UNIT_TYPE_NONE) +UnitMenu::UnitMenu() + : _type(UNIT_TYPE_NONE) { set_active(0); gtk_widget_add_events(GTK_WIDGET(gobj()), GDK_SCROLL_MASK | GDK_SMOOTH_SCROLL_MASK); @@ -27,12 +28,12 @@ UnitMenu::UnitMenu() : _type(UNIT_TYPE_NONE) UnitMenu::~UnitMenu() = default; -bool UnitMenu::setUnitType(UnitType unit_type) +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); - for (auto & i : m) { + for (auto &i : m) { append(i.first); } _type = unit_type; @@ -41,20 +42,20 @@ bool UnitMenu::setUnitType(UnitType unit_type) return true; } -bool UnitMenu::resetUnitType(UnitType unit_type) +bool UnitMenu::resetUnitType(UnitType unit_type) { remove_all(); return setUnitType(unit_type); } -void UnitMenu::addUnit(Unit const& u) +void UnitMenu::addUnit(Unit const &u) { unit_table.addUnit(u, false); append(u.abbr); } -Unit const * UnitMenu::getUnit() const +Unit const *UnitMenu::getUnit() const { if (get_active_text() == "") { g_assert(_type != UNIT_TYPE_NONE); @@ -63,7 +64,7 @@ Unit const * UnitMenu::getUnit() const return unit_table.getUnit(get_active_text()); } -bool UnitMenu::setUnit(Glib::ustring const & unit) +bool UnitMenu::setUnit(Glib::ustring const &unit) { // TODO: Determine if 'unit' is available in the dropdown. // If not, return false @@ -85,7 +86,7 @@ UnitType UnitMenu::getUnitType() const return getUnit()->type; } -double UnitMenu::getUnitFactor() const +double UnitMenu::getUnitFactor() const { return getUnit()->factor; } @@ -96,8 +97,8 @@ int UnitMenu::getDefaultDigits() const } 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); } @@ -112,11 +113,10 @@ double UnitMenu::getConversion(Glib::ustring const &new_unit_abbr, Glib::ustring 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); + 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) { + if (old_factor < 0.0000001 || new_unit->factor < 0.0000001) { // TODO: Should we assert here? return 0.00; } @@ -134,7 +134,10 @@ bool UnitMenu::isRadial() const return getUnitType() == UNIT_TYPE_RADIAL; } -bool UnitMenu::on_scroll_event(GdkEventScroll *event) { return false; } +bool UnitMenu::on_scroll_event(GdkEventScroll *event) +{ + return false; +} } // namespace Widget } // namespace UI diff --git a/src/ui/widget/unit-menu.h b/src/ui/widget/unit-menu.h index b8e3ab7fab7f90e9c8c71daf6299a934c5649d6b..26972e8fb5d4cdb04a25500157da42b90d55d149 100644 --- a/src/ui/widget/unit-menu.h +++ b/src/ui/widget/unit-menu.h @@ -12,6 +12,7 @@ #define INKSCAPE_UI_WIDGET_UNIT_H #include <gtkmm/comboboxtext.h> + #include "util/units.h" using namespace Inkscape::Util; @@ -26,7 +27,6 @@ namespace Widget { class UnitMenu : public Gtk::ComboBoxText { public: - /** * Construct a UnitMenu */ @@ -40,7 +40,7 @@ public: * to the dropdown widget. It causes the primary unit for the given * unit_type to be selected. */ - bool setUnitType(UnitType unit_type); + bool setUnitType(UnitType unit_type); /** * Removes all unit entries, then adds the unit type to the widget. @@ -49,25 +49,25 @@ public: * to the dropdown widget. It causes the primary unit for the given * unit_type to be selected. */ - bool resetUnitType(UnitType unit_type); + bool resetUnitType(UnitType unit_type); /** * Adds a unit, possibly user-defined, to the menu. */ - void addUnit(Unit const& u); + void addUnit(Unit const &u); /** - * Sets the dropdown widget to the given unit abbreviation. - * Returns true if the unit was selectable, false if not + * Sets the dropdown widget to the given unit abbreviation. + * Returns true if the unit was selectable, false if not * (i.e., if the unit was not present in the widget). */ - bool setUnit(Glib::ustring const &unit); + bool setUnit(Glib::ustring const &unit); /** * Returns the Unit object corresponding to the current selection * in the dropdown widget. */ - Unit const * getUnit() const; + Unit const *getUnit() const; /** * Returns the abbreviated unit name of the selected unit. @@ -77,51 +77,51 @@ public: /** * Returns the UnitType of the selected unit. */ - UnitType getUnitType() const; + UnitType getUnitType() const; /** * Returns the unit factor for the selected unit. */ - double getUnitFactor() const; + double getUnitFactor() const; /** * Returns the recommended number of digits for displaying - * numbers of this unit type. + * numbers of this unit type. */ - int getDefaultDigits() const; + int getDefaultDigits() const; /** * Returns the recommended step size in spin buttons * displaying units of this type. */ - double getDefaultStep() const; + double getDefaultStep() const; /** * Returns the recommended page size (when hitting pgup/pgdn) * in spin buttons displaying units of this type. */ - double getDefaultPage() const; + double getDefaultPage() const; /** * Returns the conversion factor required to convert values * of the currently selected unit into units of type * new_unit_abbr. */ - double getConversion(Glib::ustring const &new_unit_abbr, Glib::ustring const &old_unit_abbr = "no_unit") const; + double getConversion(Glib::ustring const &new_unit_abbr, Glib::ustring const &old_unit_abbr = "no_unit") const; /** - * Returns true if the selected unit is not dimensionless + * Returns true if the selected unit is not dimensionless * (false for %, true for px, pt, cm, etc). */ - bool isAbsolute() const; + bool isAbsolute() const; /** * Returns true if the selected unit is radial (deg or rad). */ - bool isRadial() const; + bool isRadial() const; protected: - UnitType _type; + UnitType _type; /** * block scroll from widget if is inside a scrolled window. */ diff --git a/src/ui/widget/unit-tracker.cpp b/src/ui/widget/unit-tracker.cpp index 252fd8c86298ffa46845c6c06c1c18ca59a3cc1a..6247b8668746df568f1bb83aa9110b0fe5b68384 100644 --- a/src/ui/widget/unit-tracker.cpp +++ b/src/ui/widget/unit-tracker.cpp @@ -14,45 +14,44 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "unit-tracker.h" + #include <algorithm> #include <iostream> -#include "unit-tracker.h" - #include "combo-tool-item.h" #define COLUMN_STRING 0 -using Inkscape::Util::UnitTable; using Inkscape::Util::unit_table; +using Inkscape::Util::UnitTable; namespace Inkscape { namespace UI { namespace Widget { -UnitTracker::UnitTracker(UnitType unit_type) : - _active(0), - _isUpdating(false), - _activeUnit(nullptr), - _activeUnitInitialized(false), - _store(nullptr), - _priorValues() +UnitTracker::UnitTracker(UnitType unit_type) + : _active(0) + , _isUpdating(false) + , _activeUnit(nullptr) + , _activeUnitInitialized(false) + , _store(nullptr) + , _priorValues() { UnitTable::UnitMap m = unit_table.units(unit_type); - + ComboToolItemColumns columns; _store = Gtk::ListStore::create(columns); Gtk::TreeModel::Row row; - for (auto & m_iter : m) { - + for (auto &m_iter : m) { Glib::ustring unit = m_iter.first; row = *(_store->append()); - row[columns.col_label ] = unit; - row[columns.col_value ] = unit; - row[columns.col_tooltip ] = (""); - row[columns.col_icon ] = "NotUsed"; + row[columns.col_label] = unit; + row[columns.col_value] = unit; + row[columns.col_tooltip] = (""); + row[columns.col_icon] = "NotUsed"; row[columns.col_sensitive] = true; } @@ -81,7 +80,7 @@ bool UnitTracker::isUpdating() const return _isUpdating; } -Inkscape::Util::Unit const * UnitTracker::getActiveUnit() const +Inkscape::Util::Unit const *UnitTracker::getActiveUnit() const { return _activeUnit; } @@ -98,13 +97,12 @@ void UnitTracker::changeLabel(Glib::ustring new_label, gint pos, bool onlylabel) void UnitTracker::setActiveUnit(Inkscape::Util::Unit const *unit) { if (unit) { - ComboToolItemColumns columns; int index = 0; - for (auto& row: _store->children() ) { + for (auto &row : _store->children()) { Glib::ustring storedUnit = row[columns.col_value]; - if (!unit->abbr.compare (storedUnit)) { - _setActive (index); + if (!unit->abbr.compare(storedUnit)) { + _setActive(index); break; } index++; @@ -120,7 +118,7 @@ void UnitTracker::setActiveUnitByAbbr(gchar const *abbr) void UnitTracker::addAdjustment(GtkAdjustment *adj) { - if (std::find(_adjList.begin(),_adjList.end(),adj) == _adjList.end()) { + if (std::find(_adjList.begin(), _adjList.end(), adj) == _adjList.end()) { g_object_weak_ref(G_OBJECT(adj), _adjustmentFinalizedCB, this); _adjList.push_back(adj); } else { @@ -134,10 +132,10 @@ void UnitTracker::addUnit(Inkscape::Util::Unit const *u) Gtk::TreeModel::Row row; row = *(_store->append()); - row[columns.col_label ] = u ? u->abbr.c_str() : ""; - row[columns.col_value ] = u ? u->abbr.c_str() : ""; - row[columns.col_tooltip ] = (""); - row[columns.col_icon ] = "NotUsed"; + row[columns.col_label] = u ? u->abbr.c_str() : ""; + row[columns.col_value] = u ? u->abbr.c_str() : ""; + row[columns.col_tooltip] = (""); + row[columns.col_icon] = "NotUsed"; row[columns.col_sensitive] = true; } @@ -147,15 +145,14 @@ void UnitTracker::prependUnit(Inkscape::Util::Unit const *u) Gtk::TreeModel::Row row; row = *(_store->prepend()); - row[columns.col_label ] = u ? u->abbr.c_str() : ""; - row[columns.col_value ] = u ? u->abbr.c_str() : ""; - row[columns.col_tooltip ] = (""); - row[columns.col_icon ] = "NotUsed"; + row[columns.col_label] = u ? u->abbr.c_str() : ""; + row[columns.col_value] = u ? u->abbr.c_str() : ""; + row[columns.col_tooltip] = (""); + row[columns.col_icon] = "NotUsed"; row[columns.col_sensitive] = true; /* Re-shuffle our default selection here (_active gets out of sync) */ setActiveUnit(_activeUnit); - } void UnitTracker::setFullVal(GtkAdjustment *adj, gdouble val) @@ -163,16 +160,14 @@ void UnitTracker::setFullVal(GtkAdjustment *adj, gdouble val) _priorValues[adj] = val; } -ComboToolItem * -UnitTracker::create_tool_item(Glib::ustring const &label, - Glib::ustring const &tooltip) +ComboToolItem *UnitTracker::create_tool_item(Glib::ustring const &label, Glib::ustring const &tooltip) { auto combo = ComboToolItem::create(label, tooltip, "NotUsed", _store); combo->set_active(_active); combo->signal_changed().connect(sigc::mem_fun(*this, &UnitTracker::_unitChangedCB)); combo->set_name("unit-tracker"); _combo_list.push_back(combo); - return combo; + return combo; } void UnitTracker::_unitChangedCB(int active) @@ -190,8 +185,8 @@ void UnitTracker::_adjustmentFinalizedCB(gpointer data, GObject *where_the_objec void UnitTracker::_adjustmentFinalized(GObject *where_the_object_was) { - GtkAdjustment* adj = (GtkAdjustment*)(where_the_object_was); - auto it = std::find(_adjList.begin(),_adjList.end(), adj); + GtkAdjustment *adj = (GtkAdjustment *)(where_the_object_was); + auto it = std::find(_adjList.begin(), _adjList.end(), adj); if (it != _adjList.end()) { _adjList.erase(it); } else { @@ -201,29 +196,28 @@ void UnitTracker::_adjustmentFinalized(GObject *where_the_object_was) void UnitTracker::_setActive(gint active) { - if ( active != _active || !_activeUnitInitialized ) { + if (active != _active || !_activeUnitInitialized) { gint oldActive = _active; if (_store) { - // Find old and new units ComboToolItemColumns columns; int index = 0; - Glib::ustring oldAbbr( "NotFound" ); - Glib::ustring newAbbr( "NotFound" ); - for (auto& row: _store->children() ) { + Glib::ustring oldAbbr("NotFound"); + Glib::ustring newAbbr("NotFound"); + for (auto &row : _store->children()) { if (index == _active) { oldAbbr = row[columns.col_value]; } if (index == active) { newAbbr = row[columns.col_value]; } - if (newAbbr != "NotFound" && oldAbbr != "NotFound") break; + if (newAbbr != "NotFound" && oldAbbr != "NotFound") + break; ++index; } if (oldAbbr != "NotFound") { - if (newAbbr != "NotFound") { Inkscape::Util::Unit const *oldUnit = unit_table.getUnit(oldAbbr); Inkscape::Util::Unit const *newUnit = unit_table.getUnit(newAbbr); @@ -237,14 +231,15 @@ void UnitTracker::_setActive(gint active) } } else { - std::cerr << "UnitTracker::_setActive: Did not find old unit: " << oldActive - << " new: " << active << std::endl; + std::cerr << "UnitTracker::_setActive: Did not find old unit: " << oldActive << " new: " << active + << std::endl; } } _active = active; for (auto combo : _combo_list) { - if(combo) combo->set_active(active); + if (combo) + combo->set_active(active); } _activeUnitInitialized = true; @@ -254,18 +249,16 @@ void UnitTracker::_setActive(gint active) void UnitTracker::_fixupAdjustments(Inkscape::Util::Unit const *oldUnit, Inkscape::Util::Unit const *newUnit) { _isUpdating = true; - for ( auto adj : _adjList ) { + for (auto adj : _adjList) { 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) ) - { + 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) ) - { + } 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); } diff --git a/src/ui/widget/unit-tracker.h b/src/ui/widget/unit-tracker.h index b85da0623aa2a0f7d830bf623c2c23edca01ca77..439428927b8ffe1b436dc2b50a474de3e3fdcb81 100644 --- a/src/ui/widget/unit-tracker.h +++ b/src/ui/widget/unit-tracker.h @@ -16,26 +16,26 @@ #ifndef INKSCAPE_UI_WIDGET_UNIT_TRACKER_H #define INKSCAPE_UI_WIDGET_UNIT_TRACKER_H +#include <gtkmm/liststore.h> #include <map> #include <vector> -#include <gtkmm/liststore.h> - #include "util/units.h" using Inkscape::Util::Unit; using Inkscape::Util::UnitType; -typedef struct _GObject GObject; +typedef struct _GObject GObject; typedef struct _GtkAdjustment GtkAdjustment; -typedef struct _GtkListStore GtkListStore; +typedef struct _GtkListStore GtkListStore; namespace Inkscape { namespace UI { namespace Widget { class ComboToolItem; -class UnitTracker { +class UnitTracker +{ public: UnitTracker(UnitType unit_type); virtual ~UnitTracker(); @@ -44,7 +44,7 @@ public: void setActiveUnit(Inkscape::Util::Unit const *unit); void setActiveUnitByAbbr(gchar const *abbr); - Inkscape::Util::Unit const * getActiveUnit() const; + Inkscape::Util::Unit const *getActiveUnit() const; void addUnit(Inkscape::Util::Unit const *u); void addAdjustment(GtkAdjustment *adj); @@ -52,8 +52,7 @@ public: void setFullVal(GtkAdjustment *adj, gdouble val); void changeLabel(Glib::ustring new_label, gint pos, bool onlylabel = false); - ComboToolItem *create_tool_item(Glib::ustring const &label, - Glib::ustring const &tooltip); + ComboToolItem *create_tool_item(Glib::ustring const &label, Glib::ustring const &tooltip); protected: UnitType _type; @@ -76,8 +75,8 @@ private: Glib::RefPtr<Gtk::ListStore> _store; std::vector<ComboToolItem *> _combo_list; - std::vector<GtkAdjustment*> _adjList; - std::map <GtkAdjustment *, gdouble> _priorValues; + std::vector<GtkAdjustment *> _adjList; + std::map<GtkAdjustment *, gdouble> _priorValues; }; } // namespace Widget diff --git a/src/unclump.cpp b/src/unclump.cpp index 6b134c0abdf81ade5cfe3f8ca44eb1d196a9c305..9577c78f63ad92e012d71017bd2aa0879485334b 100644 --- a/src/unclump.cpp +++ b/src/unclump.cpp @@ -12,31 +12,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <algorithm> -#include <map> +#include "unclump.h" #include <2geom/transforms.h> - -#include "unclump.h" +#include <algorithm> +#include <map> #include "object/sp-item.h" - // Taking bbox of an item is an expensive operation, and we need to do it many times, so here we // cache the centers, widths, and heights of items -//FIXME: make a class with these cashes as members instead of globals +// FIXME: make a class with these cashes as members instead of globals std::map<const gchar *, Geom::Point> c_cache; std::map<const gchar *, Geom::Point> wh_cache; /** Center of bbox of item */ -static Geom::Point -unclump_center (SPItem *item) +static Geom::Point unclump_center(SPItem *item) { std::map<const gchar *, Geom::Point>::iterator i = c_cache.find(item->getId()); - if ( i != c_cache.end() ) { + if (i != c_cache.end()) { return i->second; } @@ -51,12 +48,11 @@ unclump_center (SPItem *item) } } -static Geom::Point -unclump_wh (SPItem *item) +static Geom::Point unclump_wh(SPItem *item) { Geom::Point wh; std::map<const gchar *, Geom::Point>::iterator i = wh_cache.find(item->getId()); - if ( i != wh_cache.end() ) { + if (i != wh_cache.end()) { wh = i->second; } else { Geom::OptRect r = item->desktopVisualBounds(); @@ -76,117 +72,116 @@ Distance between "edges" of item1 and item2. An item is considered to be an elli so its radius (distance from center to edge) depends on the w/h and the angle towards the other item. May be negative if the edge of item1 is between the center and the edge of item2. */ -static double -unclump_dist (SPItem *item1, SPItem *item2) +static double unclump_dist(SPItem *item1, SPItem *item2) { - Geom::Point c1 = unclump_center (item1); - Geom::Point c2 = unclump_center (item2); - - Geom::Point wh1 = unclump_wh (item1); - Geom::Point wh2 = unclump_wh (item2); - - // angle from each item's center to the other's, unsqueezed by its w/h, normalized to 0..pi/2 - double a1 = atan2 ((c2 - c1)[Geom::Y], (c2 - c1)[Geom::X] * wh1[Geom::Y]/wh1[Geom::X]); - a1 = fabs (a1); - if (a1 > M_PI/2) a1 = M_PI - a1; - - double a2 = atan2 ((c1 - c2)[Geom::Y], (c1 - c2)[Geom::X] * wh2[Geom::Y]/wh2[Geom::X]); - a2 = fabs (a2); - if (a2 > M_PI/2) a2 = M_PI - a2; - - // get the radius of each item for the given angle - double r1 = 0.5 * (wh1[Geom::X] + (wh1[Geom::Y] - wh1[Geom::X]) * (a1/(M_PI/2))); - double r2 = 0.5 * (wh2[Geom::X] + (wh2[Geom::Y] - wh2[Geom::X]) * (a2/(M_PI/2))); - - // dist between centers minus angle-adjusted radii - double dist_r = (Geom::L2 (c2 - c1) - r1 - r2); - - double stretch1 = wh1[Geom::Y]/wh1[Geom::X]; - double stretch2 = wh2[Geom::Y]/wh2[Geom::X]; - - if ((stretch1 > 1.5 || stretch1 < 0.66) && (stretch2 > 1.5 || stretch2 < 0.66)) { - - std::vector<double> dists; - dists.push_back (dist_r); - - // If both objects are not circle-like, find dists between four corners - std::vector<Geom::Point> c1_points(2); - { - double y_closest; - if (c2[Geom::Y] > c1[Geom::Y] + wh1[Geom::Y]/2) { - y_closest = c1[Geom::Y] + wh1[Geom::Y]/2; - } else if (c2[Geom::Y] < c1[Geom::Y] - wh1[Geom::Y]/2) { - y_closest = c1[Geom::Y] - wh1[Geom::Y]/2; - } else { - y_closest = c2[Geom::Y]; - } - c1_points[0] = Geom::Point (c1[Geom::X], y_closest); - double x_closest; - if (c2[Geom::X] > c1[Geom::X] + wh1[Geom::X]/2) { - x_closest = c1[Geom::X] + wh1[Geom::X]/2; - } else if (c2[Geom::X] < c1[Geom::X] - wh1[Geom::X]/2) { - x_closest = c1[Geom::X] - wh1[Geom::X]/2; - } else { - x_closest = c2[Geom::X]; - } - c1_points[1] = Geom::Point (x_closest, c1[Geom::Y]); - } - - - std::vector<Geom::Point> c2_points(2); - { - double y_closest; - if (c1[Geom::Y] > c2[Geom::Y] + wh2[Geom::Y]/2) { - y_closest = c2[Geom::Y] + wh2[Geom::Y]/2; - } else if (c1[Geom::Y] < c2[Geom::Y] - wh2[Geom::Y]/2) { - y_closest = c2[Geom::Y] - wh2[Geom::Y]/2; - } else { - y_closest = c1[Geom::Y]; - } - c2_points[0] = Geom::Point (c2[Geom::X], y_closest); - double x_closest; - if (c1[Geom::X] > c2[Geom::X] + wh2[Geom::X]/2) { - x_closest = c2[Geom::X] + wh2[Geom::X]/2; - } else if (c1[Geom::X] < c2[Geom::X] - wh2[Geom::X]/2) { - x_closest = c2[Geom::X] - wh2[Geom::X]/2; - } else { - x_closest = c1[Geom::X]; - } - c2_points[1] = Geom::Point (x_closest, c2[Geom::Y]); - } - - for (int i = 0; i < 2; i ++) { - for (int j = 0; j < 2; j ++) { - dists.push_back (Geom::L2 (c1_points[i] - c2_points[j])); - } - } - - // return the minimum of all dists - return *std::min_element(dists.begin(), dists.end()); - } else { - return dist_r; - } + Geom::Point c1 = unclump_center(item1); + Geom::Point c2 = unclump_center(item2); + + Geom::Point wh1 = unclump_wh(item1); + Geom::Point wh2 = unclump_wh(item2); + + // angle from each item's center to the other's, unsqueezed by its w/h, normalized to 0..pi/2 + double a1 = atan2((c2 - c1)[Geom::Y], (c2 - c1)[Geom::X] * wh1[Geom::Y] / wh1[Geom::X]); + a1 = fabs(a1); + if (a1 > M_PI / 2) + a1 = M_PI - a1; + + double a2 = atan2((c1 - c2)[Geom::Y], (c1 - c2)[Geom::X] * wh2[Geom::Y] / wh2[Geom::X]); + a2 = fabs(a2); + if (a2 > M_PI / 2) + a2 = M_PI - a2; + + // get the radius of each item for the given angle + double r1 = 0.5 * (wh1[Geom::X] + (wh1[Geom::Y] - wh1[Geom::X]) * (a1 / (M_PI / 2))); + double r2 = 0.5 * (wh2[Geom::X] + (wh2[Geom::Y] - wh2[Geom::X]) * (a2 / (M_PI / 2))); + + // dist between centers minus angle-adjusted radii + double dist_r = (Geom::L2(c2 - c1) - r1 - r2); + + double stretch1 = wh1[Geom::Y] / wh1[Geom::X]; + double stretch2 = wh2[Geom::Y] / wh2[Geom::X]; + + if ((stretch1 > 1.5 || stretch1 < 0.66) && (stretch2 > 1.5 || stretch2 < 0.66)) { + std::vector<double> dists; + dists.push_back(dist_r); + + // If both objects are not circle-like, find dists between four corners + std::vector<Geom::Point> c1_points(2); + { + double y_closest; + if (c2[Geom::Y] > c1[Geom::Y] + wh1[Geom::Y] / 2) { + y_closest = c1[Geom::Y] + wh1[Geom::Y] / 2; + } else if (c2[Geom::Y] < c1[Geom::Y] - wh1[Geom::Y] / 2) { + y_closest = c1[Geom::Y] - wh1[Geom::Y] / 2; + } else { + y_closest = c2[Geom::Y]; + } + c1_points[0] = Geom::Point(c1[Geom::X], y_closest); + double x_closest; + if (c2[Geom::X] > c1[Geom::X] + wh1[Geom::X] / 2) { + x_closest = c1[Geom::X] + wh1[Geom::X] / 2; + } else if (c2[Geom::X] < c1[Geom::X] - wh1[Geom::X] / 2) { + x_closest = c1[Geom::X] - wh1[Geom::X] / 2; + } else { + x_closest = c2[Geom::X]; + } + c1_points[1] = Geom::Point(x_closest, c1[Geom::Y]); + } + + std::vector<Geom::Point> c2_points(2); + { + double y_closest; + if (c1[Geom::Y] > c2[Geom::Y] + wh2[Geom::Y] / 2) { + y_closest = c2[Geom::Y] + wh2[Geom::Y] / 2; + } else if (c1[Geom::Y] < c2[Geom::Y] - wh2[Geom::Y] / 2) { + y_closest = c2[Geom::Y] - wh2[Geom::Y] / 2; + } else { + y_closest = c1[Geom::Y]; + } + c2_points[0] = Geom::Point(c2[Geom::X], y_closest); + double x_closest; + if (c1[Geom::X] > c2[Geom::X] + wh2[Geom::X] / 2) { + x_closest = c2[Geom::X] + wh2[Geom::X] / 2; + } else if (c1[Geom::X] < c2[Geom::X] - wh2[Geom::X] / 2) { + x_closest = c2[Geom::X] - wh2[Geom::X] / 2; + } else { + x_closest = c1[Geom::X]; + } + c2_points[1] = Geom::Point(x_closest, c2[Geom::Y]); + } + + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + dists.push_back(Geom::L2(c1_points[i] - c2_points[j])); + } + } + + // return the minimum of all dists + return *std::min_element(dists.begin(), dists.end()); + } else { + return dist_r; + } } /** Average unclump_dist from item to others */ -static double unclump_average (SPItem *item, std::list<SPItem*> &others) +static double unclump_average(SPItem *item, std::list<SPItem *> &others) { int n = 0; double sum = 0; - for (std::list<SPItem*>::const_iterator i = others.begin(); i != others.end();++i) { + for (std::list<SPItem *>::const_iterator i = others.begin(); i != others.end(); ++i) { SPItem *other = *i; if (other == item) continue; n++; - sum += unclump_dist (item, other); + sum += unclump_dist(item, other); } if (n != 0) - return sum/n; + return sum / n; else return 0; } @@ -194,19 +189,19 @@ static double unclump_average (SPItem *item, std::list<SPItem*> &others) /** Closest to item among others */ -static SPItem *unclump_closest (SPItem *item, std::list<SPItem*> &others) +static SPItem *unclump_closest(SPItem *item, std::list<SPItem *> &others) { double min = HUGE_VAL; SPItem *closest = nullptr; - for (std::list<SPItem*>::const_iterator i = others.begin(); i != others.end();++i) { - SPItem *other = *i; + for (std::list<SPItem *>::const_iterator i = others.begin(); i != others.end(); ++i) { + SPItem *other = *i; if (other == item) continue; - double dist = unclump_dist (item, other); - if (dist < min && fabs (dist) < 1e6) { + double dist = unclump_dist(item, other); + if (dist < min && fabs(dist) < 1e6) { min = dist; closest = other; } @@ -218,18 +213,18 @@ static SPItem *unclump_closest (SPItem *item, std::list<SPItem*> &others) /** Most distant from item among others */ -static SPItem *unclump_farest (SPItem *item, std::list<SPItem*> &others) +static SPItem *unclump_farest(SPItem *item, std::list<SPItem *> &others) { double max = -HUGE_VAL; SPItem *farest = nullptr; - for (std::list<SPItem*>::const_iterator i = others.begin(); i != others.end();++i) { + for (std::list<SPItem *>::const_iterator i = others.begin(); i != others.end(); ++i) { SPItem *other = *i; if (other == item) continue; - double dist = unclump_dist (item, other); - if (dist > max && fabs (dist) < 1e6) { + double dist = unclump_dist(item, other); + if (dist > max && fabs(dist) < 1e6) { max = dist; farest = other; } @@ -243,11 +238,10 @@ Removes from the \a rest list those items that are "behind" \a closest as seen f i.e. those on the other side of the line through \a closest perpendicular to the direction from \a item to \a closest. Returns a newly created list which must be freed. */ -static std::vector<SPItem*> -unclump_remove_behind (SPItem *item, SPItem *closest, std::list<SPItem*> &rest) +static std::vector<SPItem *> unclump_remove_behind(SPItem *item, SPItem *closest, std::list<SPItem *> &rest) { - Geom::Point it = unclump_center (item); - Geom::Point p1 = unclump_center (closest); + Geom::Point it = unclump_center(item); + Geom::Point p1 = unclump_center(closest); // perpendicular through closest to the direction to item: Geom::Point perp = Geom::rot90(it - p1); @@ -261,14 +255,14 @@ unclump_remove_behind (SPItem *item, SPItem *closest, std::list<SPItem*> &rest) // substitute the item into it: double val_item = A * it[Geom::X] + B * it[Geom::Y] + C; - std::vector<SPItem*> out; - for (std::list<SPItem*>::const_reverse_iterator i = rest.rbegin(); i != rest.rend();++i) { + std::vector<SPItem *> out; + for (std::list<SPItem *>::const_reverse_iterator i = rest.rbegin(); i != rest.rend(); ++i) { SPItem *other = *i; if (other == item) continue; - Geom::Point o = unclump_center (other); + Geom::Point o = unclump_center(other); double val_other = A * o[Geom::X] + B * o[Geom::Y] + C; if (val_item * val_other <= 1e-6) { @@ -284,21 +278,21 @@ unclump_remove_behind (SPItem *item, SPItem *closest, std::list<SPItem*> &rest) /** Moves \a what away from \a from by \a dist */ -static void -unclump_push (SPItem *from, SPItem *what, double dist) +static void unclump_push(SPItem *from, SPItem *what, double dist) { - Geom::Point it = unclump_center (what); - Geom::Point p = unclump_center (from); - Geom::Point by = dist * Geom::unit_vector (- (p - it)); + Geom::Point it = unclump_center(what); + Geom::Point p = unclump_center(from); + Geom::Point by = dist * Geom::unit_vector(-(p - it)); - Geom::Affine move = Geom::Translate (by); + Geom::Affine move = Geom::Translate(by); std::map<const gchar *, Geom::Point>::iterator i = c_cache.find(what->getId()); - if ( i != c_cache.end() ) { + if (i != c_cache.end()) { i->second *= move; } - //g_print ("push %s at %g,%g from %g,%g by %g,%g, dist %g\n", what->getId(), it[Geom::X],it[Geom::Y], p[Geom::X],p[Geom::Y], by[Geom::X],by[Geom::Y], dist); + // g_print ("push %s at %g,%g from %g,%g by %g,%g, dist %g\n", what->getId(), it[Geom::X],it[Geom::Y], + // p[Geom::X],p[Geom::Y], by[Geom::X],by[Geom::Y], dist); what->set_i2d_affine(what->i2dt_affine() * move); what->doWriteTransform(what->transform); @@ -307,57 +301,56 @@ unclump_push (SPItem *from, SPItem *what, double dist) /** Moves \a what towards \a to by \a dist */ -static void -unclump_pull (SPItem *to, SPItem *what, double dist) +static void unclump_pull(SPItem *to, SPItem *what, double dist) { - Geom::Point it = unclump_center (what); - Geom::Point p = unclump_center (to); - Geom::Point by = dist * Geom::unit_vector (p - it); + Geom::Point it = unclump_center(what); + Geom::Point p = unclump_center(to); + Geom::Point by = dist * Geom::unit_vector(p - it); - Geom::Affine move = Geom::Translate (by); + Geom::Affine move = Geom::Translate(by); std::map<const gchar *, Geom::Point>::iterator i = c_cache.find(what->getId()); - if ( i != c_cache.end() ) { + if (i != c_cache.end()) { i->second *= move; } - //g_print ("pull %s at %g,%g to %g,%g by %g,%g, dist %g\n", what->getId(), it[Geom::X],it[Geom::Y], p[Geom::X],p[Geom::Y], by[Geom::X],by[Geom::Y], dist); + // g_print ("pull %s at %g,%g to %g,%g by %g,%g, dist %g\n", what->getId(), it[Geom::X],it[Geom::Y], + // p[Geom::X],p[Geom::Y], by[Geom::X],by[Geom::Y], dist); what->set_i2d_affine(what->i2dt_affine() * move); what->doWriteTransform(what->transform); } - /** Unclumps the items in \a items, reducing local unevenness in their distribution. Produces an effect similar to "engraver dots". The only distribution which is unchanged by unclumping is a hexagonal grid. May be called repeatedly for stronger effect. */ -void -unclump (std::vector<SPItem*> &items) +void unclump(std::vector<SPItem *> &items) { c_cache.clear(); wh_cache.clear(); - for (std::vector<SPItem*>::const_iterator i = items.begin(); i != items.end();++i) { // for each original/clone x: + for (std::vector<SPItem *>::const_iterator i = items.begin(); i != items.end(); + ++i) { // for each original/clone x: SPItem *item = *i; - std::list<SPItem*> nei; + std::list<SPItem *> nei; - std::list<SPItem*> rest; - for (int i=0; i < static_cast<int>(items.size()); i++) { + std::list<SPItem *> rest; + for (int i = 0; i < static_cast<int>(items.size()); i++) { rest.push_front(items[items.size() - i - 1]); } rest.remove(item); while (!rest.empty()) { - SPItem *closest = unclump_closest (item, rest); + SPItem *closest = unclump_closest(item, rest); if (closest) { nei.push_front(closest); rest.remove(closest); - std::vector<SPItem*> new_rest = unclump_remove_behind (item, closest, rest); + std::vector<SPItem *> new_rest = unclump_remove_behind(item, closest, rest); rest.clear(); - for (int i=0; i < static_cast<int>(new_rest.size()); i++) { + for (int i = 0; i < static_cast<int>(new_rest.size()); i++) { rest.push_front(new_rest[new_rest.size() - i - 1]); } } else { @@ -365,22 +358,24 @@ unclump (std::vector<SPItem*> &items) } } - if ( (nei.size()) >= 2) { - double ave = unclump_average (item, nei); + if ((nei.size()) >= 2) { + double ave = unclump_average(item, nei); - SPItem *closest = unclump_closest (item, nei); - SPItem *farest = unclump_farest (item, nei); + SPItem *closest = unclump_closest(item, nei); + SPItem *farest = unclump_farest(item, nei); - double dist_closest = unclump_dist (closest, item); - double dist_farest = unclump_dist (farest, item); + double dist_closest = unclump_dist(closest, item); + double dist_farest = unclump_dist(farest, item); - //g_print ("NEI %d for item %s closest %s at %g farest %s at %g ave %g\n", g_slist_length(nei), item->getId(), closest->getId(), dist_closest, farest->getId(), dist_farest, ave); + // g_print ("NEI %d for item %s closest %s at %g farest %s at %g ave %g\n", g_slist_length(nei), + // item->getId(), closest->getId(), dist_closest, farest->getId(), dist_farest, ave); - if (fabs (ave) < 1e6 && fabs (dist_closest) < 1e6 && fabs (dist_farest) < 1e6) { // otherwise the items are bogus + if (fabs(ave) < 1e6 && fabs(dist_closest) < 1e6 && fabs(dist_farest) < 1e6) { // otherwise the items are + // bogus // increase these coefficients to make unclumping more aggressive and less stable // the pull coefficient is a bit bigger to counteract the long-term expansion trend - unclump_push (closest, item, 0.3 * (ave - dist_closest)); - unclump_pull (farest, item, 0.35 * (dist_farest - ave)); + unclump_push(closest, item, 0.3 * (ave - dist_closest)); + unclump_pull(farest, item, 0.35 * (dist_farest - ave)); } } } diff --git a/src/unclump.h b/src/unclump.h index 823a83e0cc702ec6ebddda8591860ba673d51579..313e12de34bd60bc83996735b29da8ab96a9c821 100644 --- a/src/unclump.h +++ b/src/unclump.h @@ -16,7 +16,7 @@ class SPItem; -void unclump(std::vector<SPItem*> &items); +void unclump(std::vector<SPItem *> &items); #endif /* !UNCLUMP_H_SEEN */ diff --git a/src/undo-stack-observer.h b/src/undo-stack-observer.h index 0d277800b5807250dd1f48f1dd88688254b3da2a..63bb4112b014e04e9a76d77b5abba0bcac7a010b 100644 --- a/src/undo-stack-observer.h +++ b/src/undo-stack-observer.h @@ -31,44 +31,44 @@ struct Event; * UndoStackObservers should not be used on their own. Instead, they should be registered * with a CompositeUndoStackObserver. */ -class UndoStackObserver : public GC::Managed<> { +class UndoStackObserver : public GC::Managed<> +{ public: - UndoStackObserver() = default; - virtual ~UndoStackObserver() = default; + UndoStackObserver() = default; + virtual ~UndoStackObserver() = default; - /** - * Triggered when the user issues an undo command. - * - * \param log Pointer to an Event describing the undone event. - */ - virtual void notifyUndoEvent(Event* log) = 0; + /** + * Triggered when the user issues an undo command. + * + * \param log Pointer to an Event describing the undone event. + */ + virtual void notifyUndoEvent(Event *log) = 0; - /** - * Triggered when the user issues a redo command. - * - * \param log Pointer to an Event describing the redone event. - */ - virtual void notifyRedoEvent(Event* log) = 0; + /** + * Triggered when the user issues a redo command. + * + * \param log Pointer to an Event describing the redone event. + */ + virtual void notifyRedoEvent(Event *log) = 0; - /** - * Triggered when a set of transactions is committed to the undo log. - * - * \param log Pointer to an Event describing the committed events. - */ - virtual void notifyUndoCommitEvent(Event* log) = 0; + /** + * Triggered when a set of transactions is committed to the undo log. + * + * \param log Pointer to an Event describing the committed events. + */ + virtual void notifyUndoCommitEvent(Event *log) = 0; - /** - * Triggered when the undo log is cleared. - */ - virtual void notifyClearUndoEvent() = 0; - - /** - * Triggered when the redo log is cleared. - */ - virtual void notifyClearRedoEvent() = 0; + /** + * Triggered when the undo log is cleared. + */ + virtual void notifyClearUndoEvent() = 0; + /** + * Triggered when the redo log is cleared. + */ + virtual void notifyClearRedoEvent() = 0; }; -} +} // namespace Inkscape #endif // SEEN_UNDO_COMMIT_OBSERVER_H diff --git a/src/unicoderange.cpp b/src/unicoderange.cpp index ca1a3f67cd314986d5c2b9e92c6bc0c8ac678c54..1d66b2cee3bbe271376512695493fe1fe234f2dd 100644 --- a/src/unicoderange.cpp +++ b/src/unicoderange.cpp @@ -12,124 +12,145 @@ #include <cstdlib> #include <cstring> -static unsigned int hex2int(char* s){ - int res=0; - int i=0, mul=1; - while(s[i+1]!='\0') i++; +static unsigned int hex2int(char *s) +{ + int res = 0; + int i = 0, mul = 1; + while (s[i + 1] != '\0') + i++; - while(i>=0){ - if (s[i] >= 'A' && s[i] <= 'F') res += mul * (s[i]-'A'+10); - if (s[i] >= 'a' && s[i] <= 'f') res += mul * (s[i]-'a'+10); - if (s[i] >= '0' && s[i] <= '9') res += mul * (s[i]-'0'); + while (i >= 0) { + if (s[i] >= 'A' && s[i] <= 'F') + res += mul * (s[i] - 'A' + 10); + if (s[i] >= 'a' && s[i] <= 'f') + res += mul * (s[i] - 'a' + 10); + if (s[i] >= '0' && s[i] <= '9') + res += mul * (s[i] - '0'); i--; - mul*=16; + mul *= 16; } return res; } -UnicodeRange::UnicodeRange(const gchar* value){ - if (!value) return; - gchar* val = (gchar*) value; - while(val[0] != '\0'){ - if (val[0]=='U' && val[1]=='+'){ - val += add_range(val+2); +UnicodeRange::UnicodeRange(const gchar *value) +{ + if (!value) + return; + gchar *val = (gchar *)value; + while (val[0] != '\0') { + if (val[0] == 'U' && val[1] == '+') { + val += add_range(val + 2); } else { this->unichars.push_back(g_utf8_get_char(&val[0])); val++; } - //skip spaces or commas - while(val[0]==' ' || val[0]==',') val++; + // skip spaces or commas + while (val[0] == ' ' || val[0] == ',') + val++; } } -int UnicodeRange::add_range(gchar* val){ - Urange r; - int i=0, count=0; - while(val[i]!='\0' && val[i]!='-' && val[i]!=' ' && val[i]!=','){ +int UnicodeRange::add_range(gchar *val) +{ + Urange r; + int i = 0, count = 0; + while (val[i] != '\0' && val[i] != '-' && val[i] != ' ' && val[i] != ',') { + i++; + } + r.start = (gchar *)malloc((i + 1) * sizeof(gchar)); + strncpy(r.start, val, i); + r.start[i] = '\0'; + val += i; + count += i; + i = 0; + if (val[0] == '-') { + val++; + while (val[i] != '\0' && val[i] != '-' && val[i] != ' ' && val[i] != ',') i++; - } - r.start = (gchar*) malloc((i+1)*sizeof(gchar)); - strncpy(r.start, val, i); - r.start[i] = '\0'; - val+=i; - count+=i; - i=0; - if (val[0]=='-'){ - val++; - while(val[i]!='\0' && val[i]!='-' && val[i]!=' ' && val[i]!=',') i++; - r.end = (gchar*) malloc((i+1)*sizeof(gchar)); - strncpy(r.end, val, i); - r.end[i] = '\0'; - // val+=i; - count+=i; - } else { - r.end=nullptr; - } - this->range.push_back(r); - return count+1; + r.end = (gchar *)malloc((i + 1) * sizeof(gchar)); + strncpy(r.end, val, i); + r.end[i] = '\0'; + // val+=i; + count += i; + } else { + r.end = nullptr; + } + this->range.push_back(r); + return count + 1; } -bool UnicodeRange::contains(gchar unicode){ - for(unsigned int unichar : this->unichars){ - if (static_cast<gunichar>(unicode) == unichar){ +bool UnicodeRange::contains(gchar unicode) +{ + for (unsigned int unichar : this->unichars) { + if (static_cast<gunichar>(unicode) == unichar) { return true; } } unsigned int unival; - unival = g_utf8_get_char (&unicode); + unival = g_utf8_get_char(&unicode); char uni[9] = "00000000"; - uni[8]= '\0'; - for (unsigned int i=7; unival>0; i--){ + uni[8] = '\0'; + for (unsigned int i = 7; unival > 0; i--) { unsigned char val = unival & 0xf; unival = unival >> 4; - if (val < 10) uni[i] = '0' + val; - else uni[i] = 'A'+ val - 10; + if (val < 10) + uni[i] = '0' + val; + else + uni[i] = 'A' + val - 10; } bool found; - for(auto r : this->range){ - if (r.end){ - if (unival >= hex2int(r.start) && unival <= hex2int(r.end)) return true; + for (auto r : this->range) { + if (r.end) { + if (unival >= hex2int(r.start) && unival <= hex2int(r.end)) + return true; } else { found = true; - int p=0; - while (r.start[p]!='\0') p++; + int p = 0; + while (r.start[p] != '\0') + p++; p--; - for (int pos=8;p>=0;pos--,p--){ - if (uni[pos]!='?' && uni[pos]!=r.start[p]) found = false; + for (int pos = 8; p >= 0; pos--, p--) { + if (uni[pos] != '?' && uni[pos] != r.start[p]) + found = false; } - if (found) return true; + if (found) + return true; } } return false; } -Glib::ustring UnicodeRange::attribute_string(){ +Glib::ustring UnicodeRange::attribute_string() +{ Glib::ustring result; unsigned int i; - for(i=0; i<this->unichars.size(); i++){ + for (i = 0; i < this->unichars.size(); i++) { result += this->unichars[i]; - if (i!=this->unichars.size()-1) result += ","; + if (i != this->unichars.size() - 1) + result += ","; } - for(i=0; i<this->range.size(); i++){ + for (i = 0; i < this->range.size(); i++) { result += "U+" + Glib::ustring(this->range[i].start); - if (this->range[i].end) result += "-" + Glib::ustring(this->range[i].end); - if (i!=this->range.size()-1) result += ", "; + if (this->range[i].end) + result += "-" + Glib::ustring(this->range[i].end); + if (i != this->range.size() - 1) + result += ", "; } return result; } -gunichar UnicodeRange::sample_glyph(){ - //This could be better +gunichar UnicodeRange::sample_glyph() +{ + // This could be better if (!unichars.empty()) return unichars[0]; if (!range.empty()) return hex2int(range[0].start); - return (gunichar) ' '; + return (gunichar)' '; } - diff --git a/src/unicoderange.h b/src/unicoderange.h index 8a756310ff5935b3f7f4e687cc38261251aac96c..9ace2901bcb21b556ddb84fa9bb6c88ed6f647b3 100644 --- a/src/unicoderange.h +++ b/src/unicoderange.h @@ -13,21 +13,22 @@ // A type which can hold any UTF-32 or UCS-4 character code. typedef unsigned int gunichar; -struct Urange{ - char* start; - char* end; +struct Urange +{ + char *start; + char *end; }; -class UnicodeRange{ +class UnicodeRange +{ public: -UnicodeRange(const char* val); -int add_range(char* val); -bool contains(char unicode); -Glib::ustring attribute_string(); -gunichar sample_glyph(); + UnicodeRange(const char *val); + int add_range(char *val); + bool contains(char unicode); + Glib::ustring attribute_string(); + gunichar sample_glyph(); private: -std::vector<Urange> range; -std::vector<gunichar> unichars; + std::vector<Urange> range; + std::vector<gunichar> unichars; }; - diff --git a/src/util/const_char_ptr.h b/src/util/const_char_ptr.h index 872ca6720b01835dcf515164ebf5e7024babbb9a..0b06ffb59965e710d0f19a7ff3f805132faccd32 100644 --- a/src/util/const_char_ptr.h +++ b/src/util/const_char_ptr.h @@ -14,6 +14,7 @@ #define SEEN_INKSCAPE_UTIL_CONST_CHAR_PTR_H #include <glibmm/ustring.h> #include <string> + #include "share.h" namespace Inkscape { @@ -23,29 +24,37 @@ namespace Util { * Non-owning reference to 'const char*' * Main-purpose: avoid overloads of type `f(char*, str&)`, `f(str&, char*)`, `f(char*, char*)`, ... */ -class const_char_ptr{ +class const_char_ptr +{ public: - const_char_ptr() noexcept: m_data(nullptr){}; - const_char_ptr(std::nullptr_t): const_char_ptr() {}; - const_char_ptr(const char* const data) noexcept: m_data(data) {}; - const_char_ptr(const Glib::ustring& str) noexcept: const_char_ptr(str.c_str()) {}; - const_char_ptr(const std::string& str) noexcept: const_char_ptr(str.c_str()) {}; - const_char_ptr(const ptr_shared& shared) : const_char_ptr(static_cast<const char* const>(shared)) {}; + const_char_ptr() noexcept + : m_data(nullptr){}; + const_char_ptr(std::nullptr_t) + : const_char_ptr(){}; + const_char_ptr(const char *const data) noexcept + : m_data(data){}; + const_char_ptr(const Glib::ustring &str) noexcept + : const_char_ptr(str.c_str()){}; + const_char_ptr(const std::string &str) noexcept + : const_char_ptr(str.c_str()){}; + const_char_ptr(const ptr_shared &shared) + : const_char_ptr(static_cast<const char *const>(shared)){}; + + const char *data() const noexcept { return m_data; } - const char * data() const noexcept { return m_data; } private: - const char * const m_data = nullptr; + const char *const m_data = nullptr; }; -} -} +} // namespace Util +} // namespace Inkscape #endif // SEEN_INKSCAPE_UTIL_CONST_CHAR_PTR_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: \ No newline at end of file + /* + 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: \ No newline at end of file diff --git a/src/util/copy.h b/src/util/copy.h index 60681320803d6a343b7158a52e39e8fdf5c0df15..fc4b3c6bebfb7a6c2c508399c4dd2893e9c89860 100644 --- a/src/util/copy.h +++ b/src/util/copy.h @@ -18,23 +18,26 @@ namespace Inkscape { namespace Traits { template <typename T> -struct Copy { +struct Copy +{ typedef T Type; }; template <typename T> -struct Copy<T const> { +struct Copy<T const> +{ typedef T Type; }; template <typename T> -struct Copy<T &> { +struct Copy<T &> +{ typedef T &Type; }; -} +} // namespace Traits -} +} // namespace Inkscape #endif /* diff --git a/src/util/enums.h b/src/util/enums.h index 46c4d5e8bee79b4b8ae1e026197e97b6f2057635..c0194c16777a9a8ecdec65ae918abce26d8e18fb 100644 --- a/src/util/enums.h +++ b/src/util/enums.h @@ -22,7 +22,7 @@ namespace Util { * When initializing the EnumData struct, you cannot use _(...) to translate strings. * Instead, one must use N_(...) and do the translation every time the string is retrieved. */ -template<typename E> +template <typename E> struct EnumData { E id; @@ -38,39 +38,41 @@ const Glib::ustring empty_string(""); * @note that get_id_from_key and get_id_from_label return 0 if it cannot find an entry for that key string. * @note that get_label and get_key return an empty string when the requested id is not in the list. */ -template<typename E> class EnumDataConverter +template <typename E> +class EnumDataConverter { public: typedef EnumData<E> Data; - EnumDataConverter(const EnumData<E>* cd, const unsigned int length) - : _length(length), _data(cd) + EnumDataConverter(const EnumData<E> *cd, const unsigned int length) + : _length(length) + , _data(cd) {} - E get_id_from_label(const Glib::ustring& label) const + E get_id_from_label(const Glib::ustring &label) const { - for(unsigned int i = 0; i < _length; ++i) { - if(_data[i].label == label) + for (unsigned int i = 0; i < _length; ++i) { + if (_data[i].label == label) return _data[i].id; } return (E)0; } - E get_id_from_key(const Glib::ustring& key) const + E get_id_from_key(const Glib::ustring &key) const { - for(unsigned int i = 0; i < _length; ++i) { - if(_data[i].key == key) + for (unsigned int i = 0; i < _length; ++i) { + if (_data[i].key == key) return _data[i].id; } return (E)0; } - bool is_valid_key(const Glib::ustring& key) const + bool is_valid_key(const Glib::ustring &key) const { - for(unsigned int i = 0; i < _length; ++i) { - if(_data[i].key == key) + for (unsigned int i = 0; i < _length; ++i) { + if (_data[i].key == key) return true; } @@ -79,46 +81,43 @@ public: bool is_valid_id(const E id) const { - for(unsigned int i = 0; i < _length; ++i) { - if(_data[i].id == id) + for (unsigned int i = 0; i < _length; ++i) { + if (_data[i].id == id) return true; } return false; } - const Glib::ustring& get_label(const E id) const + const Glib::ustring &get_label(const E id) const { - for(unsigned int i = 0; i < _length; ++i) { - if(_data[i].id == id) + for (unsigned int i = 0; i < _length; ++i) { + if (_data[i].id == id) return _data[i].label; } return empty_string; } - const Glib::ustring& get_key(const E id) const + const Glib::ustring &get_key(const E id) const { - for(unsigned int i = 0; i < _length; ++i) { - if(_data[i].id == id) + for (unsigned int i = 0; i < _length; ++i) { + if (_data[i].id == id) return _data[i].key; } return empty_string; } - const EnumData<E>& data(const unsigned int i) const - { - return _data[i]; - } + const EnumData<E> &data(const unsigned int i) const { return _data[i]; } const unsigned int _length; + private: - const EnumData<E>* _data; + const EnumData<E> *_data; }; - -} -} +} // namespace Util +} // namespace Inkscape #endif diff --git a/src/util/expression-evaluator.cpp b/src/util/expression-evaluator.cpp index 24a56b772800d914c903defc8f1d7c38ae04f533..d23aacb8b3c98ab56a9a5c3058eeca1c8c20c70f 100644 --- a/src/util/expression-evaluator.cpp +++ b/src/util/expression-evaluator.cpp @@ -28,23 +28,22 @@ */ #include "util/expression-evaluator.h" -#include "util/units.h" - -#include <glib/gconvert.h> #include <cmath> #include <cstring> +#include <glib/gconvert.h> + +#include "util/units.h" using Inkscape::Util::unit_table; namespace Inkscape { namespace Util { -EvaluatorQuantity::EvaluatorQuantity(double value, unsigned int dimension) : - value(value), - dimension(dimension) -{ -} +EvaluatorQuantity::EvaluatorQuantity(double value, unsigned int dimension) + : value(value) + , dimension(dimension) +{} EvaluatorToken::EvaluatorToken() { @@ -52,12 +51,12 @@ EvaluatorToken::EvaluatorToken() value.fl = 0; } -ExpressionEvaluator::ExpressionEvaluator(const char *string, Unit const *unit) : - string(g_locale_to_utf8(string,-1,nullptr,nullptr,nullptr)), - unit(unit) +ExpressionEvaluator::ExpressionEvaluator(const char *string, Unit const *unit) + : string(g_locale_to_utf8(string, -1, nullptr, nullptr, nullptr)) + , unit(unit) { - current_token.type = TOKEN_END; - + current_token.type = TOKEN_END; + // Preload symbol parseNextToken(); } @@ -81,26 +80,26 @@ EvaluatorQuantity ExpressionEvaluator::evaluate() if (!g_utf8_validate(string, -1, nullptr)) { throw EvaluatorException("Invalid UTF8 string", nullptr); } - + EvaluatorQuantity result = EvaluatorQuantity(); EvaluatorQuantity default_unit_factor; - + // Empty expression evaluates to 0 if (acceptToken(TOKEN_END, nullptr)) { return result; } - + result = evaluateExpression(); - + // There should be nothing left to parse by now isExpected(TOKEN_END, nullptr); - + resolveUnit(nullptr, &default_unit_factor, unit); - + // Entire expression is dimensionless, apply default unit if applicable - if ( result.dimension == 0 && default_unit_factor.dimension != 0 ) { - result.value /= default_unit_factor.value; - result.dimension = default_unit_factor.dimension; + if (result.dimension == 0 && default_unit_factor.dimension != 0) { + result.value /= default_unit_factor.value; + result.dimension = default_unit_factor.dimension; } return result; } @@ -109,40 +108,33 @@ EvaluatorQuantity ExpressionEvaluator::evaluateExpression() { bool subtract; EvaluatorQuantity evaluated_terms; - + evaluated_terms = evaluateTerm(); - + // Continue evaluating terms, chained with + or -. - for (subtract = FALSE; - acceptToken('+', nullptr) || (subtract = acceptToken('-', nullptr)); - subtract = FALSE) - { + for (subtract = FALSE; acceptToken('+', nullptr) || (subtract = acceptToken('-', nullptr)); subtract = FALSE) { EvaluatorQuantity new_term = evaluateTerm(); - + // If dimensions mismatch, attempt default unit assignment - if ( new_term.dimension != evaluated_terms.dimension ) { + if (new_term.dimension != evaluated_terms.dimension) { EvaluatorQuantity default_unit_factor; - + resolveUnit(nullptr, &default_unit_factor, unit); - - if ( new_term.dimension == 0 - && evaluated_terms.dimension == default_unit_factor.dimension ) - { - new_term.value /= default_unit_factor.value; - new_term.dimension = default_unit_factor.dimension; - } else if ( evaluated_terms.dimension == 0 - && new_term.dimension == default_unit_factor.dimension ) - { - evaluated_terms.value /= default_unit_factor.value; - evaluated_terms.dimension = default_unit_factor.dimension; + + if (new_term.dimension == 0 && evaluated_terms.dimension == default_unit_factor.dimension) { + new_term.value /= default_unit_factor.value; + new_term.dimension = default_unit_factor.dimension; + } else if (evaluated_terms.dimension == 0 && new_term.dimension == default_unit_factor.dimension) { + evaluated_terms.value /= default_unit_factor.value; + evaluated_terms.dimension = default_unit_factor.dimension; } else { throwError("Dimension mismatch during addition"); } } - + evaluated_terms.value += (subtract ? -new_term.value : new_term.value); } - + return evaluated_terms; } @@ -150,41 +142,37 @@ EvaluatorQuantity ExpressionEvaluator::evaluateTerm() { bool division; EvaluatorQuantity evaluated_exp_terms = evaluateExpTerm(); - - for ( division = false; - acceptToken('*', nullptr) || (division = acceptToken('/', nullptr)); - division = false ) - { + + for (division = false; acceptToken('*', nullptr) || (division = acceptToken('/', nullptr)); division = false) { EvaluatorQuantity new_exp_term = evaluateExpTerm(); - + if (division) { - evaluated_exp_terms.value /= new_exp_term.value; + evaluated_exp_terms.value /= new_exp_term.value; evaluated_exp_terms.dimension -= new_exp_term.dimension; } else { - evaluated_exp_terms.value *= new_exp_term.value; + evaluated_exp_terms.value *= new_exp_term.value; evaluated_exp_terms.dimension += new_exp_term.dimension; } } - + return evaluated_exp_terms; } EvaluatorQuantity ExpressionEvaluator::evaluateExpTerm() { EvaluatorQuantity evaluated_signed_factors = evaluateSignedFactor(); - - while(acceptToken('^', nullptr)) { + + while (acceptToken('^', nullptr)) { EvaluatorQuantity new_signed_factor = evaluateSignedFactor(); - + if (new_signed_factor.dimension == 0) { - evaluated_signed_factors.value = pow(evaluated_signed_factors.value, - new_signed_factor.value); + evaluated_signed_factors.value = pow(evaluated_signed_factors.value, new_signed_factor.value); evaluated_signed_factors.dimension *= new_signed_factor.value; } else { throwError("Unit in exponent"); } } - + return evaluated_signed_factors; } @@ -192,17 +180,17 @@ EvaluatorQuantity ExpressionEvaluator::evaluateSignedFactor() { EvaluatorQuantity result; bool negate = FALSE; - + if (!acceptToken('+', nullptr)) { - negate = acceptToken ('-', nullptr); + negate = acceptToken('-', nullptr); } - + result = evaluateFactor(); - + if (negate) { result.value = -result.value; } - + return result; } @@ -213,8 +201,7 @@ EvaluatorQuantity ExpressionEvaluator::evaluateFactor() if (acceptToken(TOKEN_END, &consumed_token)) { return evaluated_factor; - } - else if (acceptToken(TOKEN_NUM, &consumed_token)) { + } else if (acceptToken(TOKEN_NUM, &consumed_token)) { evaluated_factor.value = consumed_token.value.fl; } else if (acceptToken('(', nullptr)) { evaluated_factor = evaluateExpression(); @@ -222,60 +209,59 @@ EvaluatorQuantity ExpressionEvaluator::evaluateFactor() } else { throwError("Expected number or '('"); } - - if ( current_token.type == TOKEN_IDENTIFIER ) { + + if (current_token.type == TOKEN_IDENTIFIER) { char *identifier; EvaluatorQuantity result; - + acceptToken(TOKEN_ANY, &consumed_token); - + identifier = g_newa(char, consumed_token.value.size + 1); - + strncpy(identifier, consumed_token.value.c, consumed_token.value.size); identifier[consumed_token.value.size] = '\0'; - + if (resolveUnit(identifier, &result, unit)) { - evaluated_factor.value /= result.value; - evaluated_factor.dimension += result.dimension; + evaluated_factor.value /= result.value; + evaluated_factor.dimension += result.dimension; } else { throwError("Unit was not resolved"); } } - + return evaluated_factor; } -bool ExpressionEvaluator::acceptToken(TokenType token_type, - EvaluatorToken *consumed_token) +bool ExpressionEvaluator::acceptToken(TokenType token_type, EvaluatorToken *consumed_token) { bool existed = FALSE; - - if ( token_type == current_token.type || token_type == TOKEN_ANY ) { + + if (token_type == current_token.type || token_type == TOKEN_ANY) { existed = TRUE; - + if (consumed_token) { *consumed_token = current_token; } - + // Parse next token parseNextToken(); } - + return existed; } void ExpressionEvaluator::parseNextToken() { const char *s; - + movePastWhiteSpace(); s = string; start_of_current_token = s; - - if ( !s || s[0] == '\0' ) { + + if (!s || s[0] == '\0') { // We're all done current_token.type = TOKEN_END; - } else if ( s[0] == '+' || s[0] == '-' ) { + } else if (s[0] == '+' || s[0] == '-') { // Snatch these before the g_strtod() does, otherwise they might // be used in a numeric conversion. acceptTokenCount(1, s[0]); @@ -283,18 +269,18 @@ void ExpressionEvaluator::parseNextToken() // Attempt to parse a numeric value char *endptr = nullptr; gdouble value = g_strtod(s, &endptr); - - if ( endptr && endptr != s ) { + + if (endptr && endptr != s) { // A numeric could be parsed, use it current_token.value.fl = value; - + current_token.type = TOKEN_NUM; - string = endptr; + string = endptr; } else if (isUnitIdentifierStart(s[0])) { // Unit identifier current_token.value.c = s; current_token.value.size = getIdentifierSize(s, 0); - + acceptTokenCount(current_token.value.size, TOKEN_IDENTIFIER); } else { // Everything else is a single character token @@ -303,14 +289,13 @@ void ExpressionEvaluator::parseNextToken() } } -void ExpressionEvaluator::acceptTokenCount (int count, TokenType token_type) +void ExpressionEvaluator::acceptTokenCount(int count, TokenType token_type) { - current_token.type = token_type; - string += count; + current_token.type = token_type; + string += count; } -void ExpressionEvaluator::isExpected(TokenType token_type, - EvaluatorToken *value) +void ExpressionEvaluator::isExpected(TokenType token_type, EvaluatorToken *value) { if (!acceptToken(token_type, value)) { throwError("Unexpected token"); @@ -322,7 +307,7 @@ void ExpressionEvaluator::movePastWhiteSpace() if (!string) { return; } - + while (g_ascii_isspace(*string)) { string++; } @@ -330,9 +315,7 @@ void ExpressionEvaluator::movePastWhiteSpace() bool ExpressionEvaluator::isUnitIdentifierStart(gunichar c) { - return (g_unichar_isalpha (c) - || c == (gunichar) '%' - || c == (gunichar) '\''); + return (g_unichar_isalpha(c) || c == (gunichar)'%' || c == (gunichar)'\''); } /** @@ -345,35 +328,33 @@ bool ExpressionEvaluator::isUnitIdentifierStart(gunichar c) **/ int ExpressionEvaluator::getIdentifierSize(const char *string, int start_offset) { - const char *start = g_utf8_offset_to_pointer(string, start_offset); - const char *s = start; - gunichar c = g_utf8_get_char(s); - int length = 0; - + const char *start = g_utf8_offset_to_pointer(string, start_offset); + const char *s = start; + gunichar c = g_utf8_get_char(s); + int length = 0; + if (isUnitIdentifierStart(c)) { - s = g_utf8_next_char (s); - c = g_utf8_get_char (s); + s = g_utf8_next_char(s); + c = g_utf8_get_char(s); length++; - - while ( isUnitIdentifierStart (c) || g_unichar_isdigit (c) ) { + + while (isUnitIdentifierStart(c) || g_unichar_isdigit(c)) { s = g_utf8_next_char(s); c = g_utf8_get_char(s); length++; } } - + return g_utf8_offset_to_pointer(start, length) - start; } -bool ExpressionEvaluator::resolveUnit (const char* identifier, - EvaluatorQuantity *result, - Unit const* unit) +bool ExpressionEvaluator::resolveUnit(const char *identifier, EvaluatorQuantity *result, Unit const *unit) { if (!unit) { result->value = 1; result->dimension = 1; return true; - }else if (!identifier) { + } else if (!identifier) { result->value = 1; result->dimension = unit->isAbsolute() ? 1 : 0; return true; diff --git a/src/util/expression-evaluator.h b/src/util/expression-evaluator.h index a45ad5a73cfa3e81907d6f5f0536516f0d90dcfb..a1a5aecdc94f261b165202023a7814fd108fe840 100644 --- a/src/util/expression-evaluator.h +++ b/src/util/expression-evaluator.h @@ -30,12 +30,12 @@ #ifndef INKSCAPE_UTIL_EXPRESSION_EVALUATOR_H #define INKSCAPE_UTIL_EXPRESSION_EVALUATOR_H -#include "util/units.h" - #include <exception> #include <sstream> #include <string> +#include "util/units.h" + /** * @file * Expression evaluator: A straightforward recursive @@ -94,7 +94,7 @@ class EvaluatorQuantity { public: EvaluatorQuantity(double value = 0, unsigned int dimension = 0); - + double value; unsigned int dimension; }; @@ -102,11 +102,12 @@ public: /** * TokenType */ -enum { - TOKEN_NUM = 30000, - TOKEN_IDENTIFIER = 30001, - TOKEN_ANY = 40000, - TOKEN_END = 50000 +enum +{ + TOKEN_NUM = 30000, + TOKEN_IDENTIFIER = 30001, + TOKEN_ANY = 40000, + TOKEN_END = 50000 }; typedef int TokenType; @@ -117,12 +118,14 @@ class EvaluatorToken { public: EvaluatorToken(); - + TokenType type; - - union { + + union + { double fl; - struct { + struct + { const char *c; int size; }; @@ -138,43 +141,45 @@ class ExpressionEvaluator { public: ExpressionEvaluator(const char *string, Unit const *unit = nullptr); - + EvaluatorQuantity evaluate(); private: const char *string; Unit const *unit; - + EvaluatorToken current_token; const char *start_of_current_token; - + EvaluatorQuantity evaluateExpression(); EvaluatorQuantity evaluateTerm(); EvaluatorQuantity evaluateExpTerm(); EvaluatorQuantity evaluateSignedFactor(); EvaluatorQuantity evaluateFactor(); - + bool acceptToken(TokenType token_type, EvaluatorToken *consumed_token); void parseNextToken(); void acceptTokenCount(int count, TokenType token_type); void isExpected(TokenType token_type, EvaluatorToken *value); - + void movePastWhiteSpace(); - + static bool isUnitIdentifierStart(gunichar c); static int getIdentifierSize(const char *s, int start); - + static bool resolveUnit(const char *identifier, EvaluatorQuantity *result, Unit const *unit); - + void throwError(const char *msg); }; /** * Special exception class for the expression evaluator. */ -class EvaluatorException : public std::exception { +class EvaluatorException : public std::exception +{ public: - EvaluatorException(const char *message, const char *at_position) { + EvaluatorException(const char *message, const char *at_position) + { std::ostringstream os; const char *token = at_position ? at_position : "<End of input>"; os << "Expression evaluator error: " << message << " at '" << token << "'"; @@ -183,14 +188,13 @@ public: ~EvaluatorException() noexcept override = default; // necessary to destroy the string object!!! - const char *what() const noexcept override { - return msgstr.c_str(); - } + const char *what() const noexcept override { return msgstr.c_str(); } + protected: std::string msgstr; }; -} -} +} // namespace Util +} // namespace Inkscape #endif // INKSCAPE_UTIL_EXPRESSION_EVALUATOR_H diff --git a/src/util/find-if-before.h b/src/util/find-if-before.h index 6d15fdfa614d2a6510234f24eecc3224be91c06f..f5d38c11c0a211f442e1c705400e3401e071ea15 100644 --- a/src/util/find-if-before.h +++ b/src/util/find-if-before.h @@ -22,21 +22,19 @@ namespace Inkscape { namespace Algorithms { template <typename ForwardIterator, typename UnaryPredicate> -inline ForwardIterator find_if_before(ForwardIterator start, - ForwardIterator end, - UnaryPredicate pred) +inline ForwardIterator find_if_before(ForwardIterator start, ForwardIterator end, UnaryPredicate pred) { - ForwardIterator before=end; - while ( start != end && !pred(*start) ) { + ForwardIterator before = end; + while (start != end && !pred(*start)) { before = start; ++start; } - return ( start != end ) ? before : end; + return (start != end) ? before : end; } -} +} // namespace Algorithms -} +} // namespace Inkscape #endif diff --git a/src/util/find-last-if.h b/src/util/find-last-if.h index 1402de74ed56e08aeff4e877dd39fc9dda63326e..d6eb3a76e3064dac13f2484f27358632fdead64b 100644 --- a/src/util/find-last-if.h +++ b/src/util/find-last-if.h @@ -20,13 +20,12 @@ namespace Inkscape { namespace Algorithms { template <typename ForwardIterator, typename UnaryPredicate> -inline ForwardIterator find_last_if(ForwardIterator start, ForwardIterator end, - UnaryPredicate pred) +inline ForwardIterator find_last_if(ForwardIterator start, ForwardIterator end, UnaryPredicate pred) { ForwardIterator last_found(end); - while ( start != end ) { + while (start != end) { start = std::find_if(start, end, pred); - if ( start != end ) { + if (start != end) { last_found = start; ++start; } @@ -34,9 +33,9 @@ inline ForwardIterator find_last_if(ForwardIterator start, ForwardIterator end, return last_found; } -} +} // namespace Algorithms -} +} // namespace Inkscape #endif diff --git a/src/util/fixed_point.h b/src/util/fixed_point.h index 5bb0dde920367d4ab1de9a6864cdc379b3fbdc9e..592f338e825abeb9975951bb1bc68ef7adb8e709 100644 --- a/src/util/fixed_point.h +++ b/src/util/fixed_point.h @@ -13,92 +13,212 @@ #ifndef SEEN_INKSCAPE_UTIL_FIXED_POINT_H #define SEEN_INKSCAPE_UTIL_FIXED_POINT_H -#include "util/reference.h" -#include <cmath> #include <algorithm> +#include <cmath> #include <limits> +#include "util/reference.h" + namespace Inkscape { namespace Util { template <typename T, unsigned int precision> -class FixedPoint { +class FixedPoint +{ public: FixedPoint() = default; - FixedPoint(const FixedPoint& value) : v(value.v) {} - FixedPoint(char value) : v(static_cast<T>(value)<<precision) {} - FixedPoint(unsigned char value) : v(static_cast<T>(value)<<precision) {} - FixedPoint(short value) : v(static_cast<T>(value)<<precision) {} - FixedPoint(unsigned short value) : v(static_cast<T>(value)<<precision) {} - FixedPoint(int value) : v(static_cast<T>(value)<<precision) {} - FixedPoint(unsigned int value) : v(static_cast<T>(value)<<precision) {} - FixedPoint(double value) : v(static_cast<T>(floor(value*(1<<precision)))) {} - - FixedPoint& operator+=(FixedPoint val) { v += val.v; return *this; } - FixedPoint& operator-=(FixedPoint val) { v -= val.v; return *this; } - FixedPoint& operator*=(FixedPoint val) { - const unsigned int half_size = 8*sizeof(T)/2; - const T al = v&((1<<half_size)-1), bl = val.v&((1<<half_size)-1); - const T ah = v>>half_size, bh = val.v>>half_size; - v = static_cast<unsigned int>(al*bl)>>precision; - if ( half_size >= precision ) { - v += ((al*bh)+(ah*bl)+((ah*bh)<<half_size))<<(half_size-precision); + FixedPoint(const FixedPoint &value) + : v(value.v) + {} + FixedPoint(char value) + : v(static_cast<T>(value) << precision) + {} + FixedPoint(unsigned char value) + : v(static_cast<T>(value) << precision) + {} + FixedPoint(short value) + : v(static_cast<T>(value) << precision) + {} + FixedPoint(unsigned short value) + : v(static_cast<T>(value) << precision) + {} + FixedPoint(int value) + : v(static_cast<T>(value) << precision) + {} + FixedPoint(unsigned int value) + : v(static_cast<T>(value) << precision) + {} + FixedPoint(double value) + : v(static_cast<T>(floor(value * (1 << precision)))) + {} + + FixedPoint &operator+=(FixedPoint val) + { + v += val.v; + return *this; + } + FixedPoint &operator-=(FixedPoint val) + { + v -= val.v; + return *this; + } + FixedPoint &operator*=(FixedPoint val) + { + const unsigned int half_size = 8 * sizeof(T) / 2; + const T al = v & ((1 << half_size) - 1), bl = val.v & ((1 << half_size) - 1); + const T ah = v >> half_size, bh = val.v >> half_size; + v = static_cast<unsigned int>(al * bl) >> precision; + if (half_size >= precision) { + v += ((al * bh) + (ah * bl) + ((ah * bh) << half_size)) << (half_size - precision); } else { - v += ((al*bh)+(ah*bl))>>(precision-half_size); - v += (ah*bh)<<(2*half_size-precision); + v += ((al * bh) + (ah * bl)) >> (precision - half_size); + v += (ah * bh) << (2 * half_size - precision); } return *this; } - FixedPoint& operator*=(char val) { v *= val; return *this; } - FixedPoint& operator*=(unsigned char val) { v *= val; return *this; } - FixedPoint& operator*=(short val) { v *= val; return *this; } - FixedPoint& operator*=(unsigned short val) { v *= val; return *this; } - FixedPoint& operator*=(int val) { v *= val; return *this; } - FixedPoint& operator*=(unsigned int val) { v *= val; return *this; } - - FixedPoint operator+(FixedPoint val) const { FixedPoint r(*this); return r+=val; } - FixedPoint operator-(FixedPoint val) const { FixedPoint r(*this); return r-=val; } - FixedPoint operator*(FixedPoint val) const { FixedPoint r(*this); return r*=val; } - - FixedPoint operator*(char val) const { FixedPoint r(*this); return r*=val; } - FixedPoint operator*(unsigned char val) const { FixedPoint r(*this); return r*=val; } - FixedPoint operator*(short val) const { FixedPoint r(*this); return r*=val; } - FixedPoint operator*(unsigned short val) const { FixedPoint r(*this); return r*=val; } - FixedPoint operator*(int val) const { FixedPoint r(*this); return r*=val; } - FixedPoint operator*(unsigned int val) const { FixedPoint r(*this); return r*=val; } - - float operator*(float val) const { return static_cast<float>(*this)*val; } - double operator*(double val) const { return static_cast<double>(*this)*val; } - - operator char() const { return v>>precision; } - operator unsigned char() const { return v>>precision; } - operator short() const { return v>>precision; } - operator unsigned short() const { return v>>precision; } - operator int() const { return v>>precision; } - operator unsigned int() const { return v>>precision; } - - operator float() const { return ldexpf(v,-precision); } - operator double() const { return ldexp(v,-precision); } + FixedPoint &operator*=(char val) + { + v *= val; + return *this; + } + FixedPoint &operator*=(unsigned char val) + { + v *= val; + return *this; + } + FixedPoint &operator*=(short val) + { + v *= val; + return *this; + } + FixedPoint &operator*=(unsigned short val) + { + v *= val; + return *this; + } + FixedPoint &operator*=(int val) + { + v *= val; + return *this; + } + FixedPoint &operator*=(unsigned int val) + { + v *= val; + return *this; + } + + FixedPoint operator+(FixedPoint val) const + { + FixedPoint r(*this); + return r += val; + } + FixedPoint operator-(FixedPoint val) const + { + FixedPoint r(*this); + return r -= val; + } + FixedPoint operator*(FixedPoint val) const + { + FixedPoint r(*this); + return r *= val; + } + + FixedPoint operator*(char val) const + { + FixedPoint r(*this); + return r *= val; + } + FixedPoint operator*(unsigned char val) const + { + FixedPoint r(*this); + return r *= val; + } + FixedPoint operator*(short val) const + { + FixedPoint r(*this); + return r *= val; + } + FixedPoint operator*(unsigned short val) const + { + FixedPoint r(*this); + return r *= val; + } + FixedPoint operator*(int val) const + { + FixedPoint r(*this); + return r *= val; + } + FixedPoint operator*(unsigned int val) const + { + FixedPoint r(*this); + return r *= val; + } + + float operator*(float val) const { return static_cast<float>(*this) * val; } + double operator*(double val) const { return static_cast<double>(*this) * val; } + + operator char() const { return v >> precision; } + operator unsigned char() const { return v >> precision; } + operator short() const { return v >> precision; } + operator unsigned short() const { return v >> precision; } + operator int() const { return v >> precision; } + operator unsigned int() const { return v >> precision; } + + operator float() const { return ldexpf(v, -precision); } + operator double() const { return ldexp(v, -precision); } + private: T v; }; -template<typename T, unsigned int precision> FixedPoint<T,precision> operator *(char a, FixedPoint<T,precision> b) { return b*=a; } -template<typename T, unsigned int precision> FixedPoint<T,precision> operator *(unsigned char a, FixedPoint<T,precision> b) { return b*=a; } -template<typename T, unsigned int precision> FixedPoint<T,precision> operator *(short a, FixedPoint<T,precision> b) { return b*=a; } -template<typename T, unsigned int precision> FixedPoint<T,precision> operator *(unsigned short a, FixedPoint<T,precision> b) { return b*=a; } -template<typename T, unsigned int precision> FixedPoint<T,precision> operator *(int a, FixedPoint<T,precision> b) { return b*=a; } -template<typename T, unsigned int precision> FixedPoint<T,precision> operator *(unsigned int a, FixedPoint<T,precision> b) { return b*=a; } - -template<typename T, unsigned int precision> float operator *(float a, FixedPoint<T,precision> b) { return b*a; } -template<typename T, unsigned int precision> double operator *(double a, FixedPoint<T,precision> b) { return b*a; } - +template <typename T, unsigned int precision> +FixedPoint<T, precision> operator*(char a, FixedPoint<T, precision> b) +{ + return b *= a; +} +template <typename T, unsigned int precision> +FixedPoint<T, precision> operator*(unsigned char a, FixedPoint<T, precision> b) +{ + return b *= a; +} +template <typename T, unsigned int precision> +FixedPoint<T, precision> operator*(short a, FixedPoint<T, precision> b) +{ + return b *= a; +} +template <typename T, unsigned int precision> +FixedPoint<T, precision> operator*(unsigned short a, FixedPoint<T, precision> b) +{ + return b *= a; +} +template <typename T, unsigned int precision> +FixedPoint<T, precision> operator*(int a, FixedPoint<T, precision> b) +{ + return b *= a; +} +template <typename T, unsigned int precision> +FixedPoint<T, precision> operator*(unsigned int a, FixedPoint<T, precision> b) +{ + return b *= a; } +template <typename T, unsigned int precision> +float operator*(float a, FixedPoint<T, precision> b) +{ + return b * a; +} +template <typename T, unsigned int precision> +double operator*(double a, FixedPoint<T, precision> b) +{ + return b * a; } +} // namespace Util + +} // namespace Inkscape + #endif /* Local Variables: diff --git a/src/util/format.h b/src/util/format.h index b38f3a64aba3a1cf08473864f1341f9114a765bb..0b0535a0db579e9ad2f70a1d9e943af5d34a7ff5 100644 --- a/src/util/format.h +++ b/src/util/format.h @@ -15,34 +15,37 @@ #include <cstdarg> #include <glib.h> + #include "util/share.h" namespace Inkscape { namespace Util { -inline ptr_shared vformat(char const *format, va_list args) { - char *temp=g_strdup_vprintf(format, args); - ptr_shared result=share_string(temp); +inline ptr_shared vformat(char const *format, va_list args) +{ + char *temp = g_strdup_vprintf(format, args); + ptr_shared result = share_string(temp); g_free(temp); return result; } - // needed since G_GNUC_PRINTF can only be used on a declaration - ptr_shared format(char const *format, ...) G_GNUC_PRINTF(1,2); -inline ptr_shared format(char const *format, ...) { +// needed since G_GNUC_PRINTF can only be used on a declaration +ptr_shared format(char const *format, ...) G_GNUC_PRINTF(1, 2); +inline ptr_shared format(char const *format, ...) +{ va_list args; va_start(args, format); - ptr_shared result=vformat(format, args); + ptr_shared result = vformat(format, args); va_end(args); return result; } -} +} // namespace Util -} +} // namespace Inkscape #endif /* diff --git a/src/util/forward-pointer-iterator.h b/src/util/forward-pointer-iterator.h index 9fe3bb852ef1088516d01f88018febeabe7e1f6b..dc0a752396634409869675e0454cd6db062eed77 100644 --- a/src/util/forward-pointer-iterator.h +++ b/src/util/forward-pointer-iterator.h @@ -15,8 +15,9 @@ #ifndef SEEN_INKSCAPE_UTIL_FORWARD_POINTER_ITERATOR_H #define SEEN_INKSCAPE_UTIL_FORWARD_POINTER_ITERATOR_H -#include <iterator> #include <cstddef> +#include <iterator> + #include "util/reference.h" namespace Inkscape { @@ -27,7 +28,8 @@ template <typename BaseType, typename Strategy> class ForwardPointerIterator; template <typename BaseType, typename Strategy> -class ForwardPointerIterator<BaseType const, Strategy> { +class ForwardPointerIterator<BaseType const, Strategy> +{ public: typedef std::forward_iterator_tag iterator_category; typedef typename Traits::Reference<BaseType const>::LValue value_type; @@ -39,24 +41,24 @@ public: typedef ForwardPointerIterator<BaseType const, Strategy> Self; ForwardPointerIterator() = default; - ForwardPointerIterator(pointer p) : _p(p) {} + ForwardPointerIterator(pointer p) + : _p(p) + {} operator pointer() const { return _p; } reference operator*() const { return *_p; } pointer operator->() const { return _p; } - bool operator==(Self const &other) const { - return _p == other._p; - } - bool operator!=(Self const &other) const { - return _p != other._p; - } + bool operator==(Self const &other) const { return _p == other._p; } + bool operator!=(Self const &other) const { return _p != other._p; } - Self &operator++() { + Self &operator++() + { _p = Strategy::next(_p); return *this; } - Self operator++(int) { + Self operator++(int) + { Self old(*this); operator++(); return old; @@ -69,8 +71,7 @@ private: }; template <typename BaseType, typename Strategy> -class ForwardPointerIterator -: public ForwardPointerIterator<BaseType const, Strategy> +class ForwardPointerIterator : public ForwardPointerIterator<BaseType const, Strategy> { public: typedef typename Traits::Reference<BaseType>::LValue value_type; @@ -81,33 +82,33 @@ public: typedef ForwardPointerIterator<BaseType const, Strategy> Ancestor; typedef ForwardPointerIterator<BaseType, Strategy> Self; - ForwardPointerIterator() : Ancestor() {} - ForwardPointerIterator(pointer p) : Ancestor(p) {} + ForwardPointerIterator() + : Ancestor() + {} + ForwardPointerIterator(pointer p) + : Ancestor(p) + {} - operator pointer() const { - return const_cast<pointer>(Ancestor::operator->()); - } - reference operator*() const { - return const_cast<reference>(Ancestor::operator*()); - } - pointer operator->() const { - return const_cast<pointer>(Ancestor::operator->()); - } + operator pointer() const { return const_cast<pointer>(Ancestor::operator->()); } + reference operator*() const { return const_cast<reference>(Ancestor::operator*()); } + pointer operator->() const { return const_cast<pointer>(Ancestor::operator->()); } - Self &operator++() { + Self &operator++() + { Ancestor::operator++(); return *this; } - Self operator++(int) { + Self operator++(int) + { Self old(*this); operator++(); return old; } }; -} +} // namespace Util -} +} // namespace Inkscape #endif /* diff --git a/src/util/list-copy.h b/src/util/list-copy.h index 51e6af4ebd7229a8a98155626c632cc4e3dfbd9a..90d533dcc7c3058e860d56395280b0961ce1a678 100644 --- a/src/util/list-copy.h +++ b/src/util/list-copy.h @@ -14,6 +14,7 @@ #define SEEN_INKSCAPE_TRAITS_LIST_COPY_H #include <iterator> + #include "util/copy.h" #include "util/list.h" @@ -22,16 +23,15 @@ namespace Inkscape { namespace Traits { template <typename InputIterator> -struct ListCopy { - typedef typename Copy< - typename std::iterator_traits<InputIterator>::value_type - >::Type ResultValue; +struct ListCopy +{ + typedef typename Copy<typename std::iterator_traits<InputIterator>::value_type>::Type ResultValue; typedef typename Util::MutableList<ResultValue> ResultList; }; -} +} // namespace Traits -} +} // namespace Inkscape #endif /* diff --git a/src/util/list.h b/src/util/list.h index 68f410bf1d68f96a9b317b45b633dbce090dec31..287f6c92cfbe4973170654c2e577cf41ee2a91fc 100644 --- a/src/util/list.h +++ b/src/util/list.h @@ -13,6 +13,7 @@ #include <cstddef> #include <iterator> + #include "inkgc/gc-managed.h" #include "util/reference.h" @@ -22,17 +23,22 @@ namespace Util { /// Generic ListCell for Inkscape::Util::List. template <typename T> -struct ListCell : public GC::Managed<> { +struct ListCell : public GC::Managed<> +{ ListCell() = default; ListCell(typename Traits::Reference<T>::RValue v, ListCell *n) - : value(v), next(n) {} + : value(v) + , next(n) + {} T value; ListCell *next; }; -template <typename T> class List; -template <typename T> class MutableList; +template <typename T> +class List; +template <typename T> +class MutableList; template <typename T> bool is_empty(List<T> const &list); @@ -47,12 +53,12 @@ template <typename T> MutableList<T> &rest(MutableList<T> const &list); template <typename T> -MutableList<T> const &set_rest(MutableList<T> const &list, - MutableList<T> const &rest); +MutableList<T> const &set_rest(MutableList<T> const &list, MutableList<T> const &rest); /// Helper template. template <typename T> -class List<T const> { +class List<T const> +{ public: typedef std::forward_iterator_tag iterator_category; typedef T const value_type; @@ -61,27 +67,28 @@ public: typedef typename Traits::Reference<value_type>::RValue const_reference; typedef typename Traits::Reference<value_type>::Pointer pointer; - List() : _cell(nullptr) {} - explicit List(const_reference value, List const &next=List()) - : _cell(new ListCell<T>(value, next._cell)) {} + List() + : _cell(nullptr) + {} + explicit List(const_reference value, List const &next = List()) + : _cell(new ListCell<T>(value, next._cell)) + {} operator bool() const { return this->_cell; } reference operator*() const { return this->_cell->value; } pointer operator->() const { return &this->_cell->value; } - bool operator==(List const &other) const { - return this->_cell == other._cell; - } - bool operator!=(List const &other) const { - return this->_cell != other._cell; - } + bool operator==(List const &other) const { return this->_cell == other._cell; } + bool operator!=(List const &other) const { return this->_cell != other._cell; } - List &operator++() { + List &operator++() + { this->_cell = this->_cell->next; return *this; } - List operator++(int) { + List operator++(int) + { List old(*this); this->_cell = this->_cell->next; return old; @@ -97,7 +104,7 @@ protected: /** * Generic linked list. - * + * * These lists are designed to store simple values like pointers, * references, and scalar values. While they can be used to directly * store more complex objects, destructors for those objects will not @@ -118,25 +125,31 @@ protected: * <code> List<int>() </code> */ template <typename T> -class List : public List<T const> { +class List : public List<T const> +{ public: typedef T value_type; typedef typename Traits::Reference<value_type>::LValue reference; typedef typename Traits::Reference<value_type>::RValue const_reference; typedef typename Traits::Reference<value_type>::Pointer pointer; - List() : List<T const>() {} - explicit List(const_reference value, List const &next=List()) - : List<T const>(value, next) {} + List() + : List<T const>() + {} + explicit List(const_reference value, List const &next = List()) + : List<T const>(value, next) + {} reference operator*() const { return this->_cell->value; } pointer operator->() const { return &this->_cell->value; } - List &operator++() { + List &operator++() + { this->_cell = this->_cell->next; return *this; } - List operator++(int) { + List operator++(int) + { List old(*this); this->_cell = this->_cell->next; return old; @@ -149,7 +162,8 @@ public: /// Helper template. template <typename T> -class List<T &> { +class List<T &> +{ public: typedef std::forward_iterator_tag iterator_category; typedef T &value_type; @@ -158,27 +172,28 @@ public: typedef typename Traits::Reference<value_type>::RValue const_reference; typedef typename Traits::Reference<value_type>::Pointer pointer; - List() : _cell(nullptr) {} - List(const_reference value, List const &next=List()) - : _cell(new ListCell<T &>(value, next._cell)) {} + List() + : _cell(nullptr) + {} + List(const_reference value, List const &next = List()) + : _cell(new ListCell<T &>(value, next._cell)) + {} operator bool() const { return this->_cell; } reference operator*() const { return this->_cell->value; } pointer operator->() const { return &this->_cell->value; } - bool operator==(List const &other) const { - return this->_cell == other._cell; - } - bool operator!=(List const &other) const { - return this->_cell != other._cell; - } + bool operator==(List const &other) const { return this->_cell == other._cell; } + bool operator!=(List const &other) const { return this->_cell != other._cell; } - List &operator++() { + List &operator++() + { this->_cell = this->_cell->next; return *this; } - List operator++(int) { + List operator++(int) + { List old(*this); this->_cell = this->_cell->next; return old; @@ -192,9 +207,9 @@ protected: ListCell<T &> *_cell; }; -/** +/** * Generic MutableList. - * + * * Like a linked list, but one whose tail can be exchanged for * another later by using set_rest() or assignment through rest() * as an lvalue. It's otherwise identical to the "non-mutable" form. @@ -204,31 +219,33 @@ protected: * <code> MutableList<int>() </code> */ template <typename T> -class MutableList : public List<T> { +class MutableList : public List<T> +{ public: MutableList() = default; - explicit MutableList(typename List<T>::const_reference value, - MutableList const &next=MutableList()) - : List<T>(value, next) {} + explicit MutableList(typename List<T>::const_reference value, MutableList const &next = MutableList()) + : List<T>(value, next) + {} - MutableList &operator++() { + MutableList &operator++() + { this->_cell = this->_cell->next; return *this; } - MutableList operator++(int) { + MutableList operator++(int) + { MutableList old(*this); this->_cell = this->_cell->next; return old; } friend MutableList &rest<>(MutableList const &); - friend MutableList const &set_rest<>(MutableList const &, - MutableList const &); + friend MutableList const &set_rest<>(MutableList const &, MutableList const &); }; /** * Creates a (non-empty) linked list. - * + * * Creates a new linked list with a copy of the given value (\a first) * in its first element; the remainder of the list will be the list * provided as \a rest. @@ -248,8 +265,7 @@ public: * */ template <typename T> -inline List<T> cons(typename Traits::Reference<T>::RValue first, - List<T> const &rest) +inline List<T> cons(typename Traits::Reference<T>::RValue first, List<T> const &rest) { return List<T>(first, rest); } @@ -278,8 +294,7 @@ inline List<T> cons(typename Traits::Reference<T>::RValue first, * @return a new list */ template <typename T> -inline MutableList<T> cons(typename Traits::Reference<T>::RValue first, - MutableList<T> const &rest) +inline MutableList<T> cons(typename Traits::Reference<T>::RValue first, MutableList<T> const &rest) { return MutableList<T>(first, rest); } @@ -295,7 +310,10 @@ inline MutableList<T> cons(typename Traits::Reference<T>::RValue first, * @return true if the list is empty, false otherwise. */ template <typename T> -inline bool is_empty(List<T> const &list) { return !list._cell; } +inline bool is_empty(List<T> const &list) +{ + return !list._cell; +} /** * Returns the first value in a linked list. @@ -307,7 +325,7 @@ inline bool is_empty(List<T> const &list) { return !list._cell; } * can be used as an lvalue. * * For example: - * + * * first(list) = value; * * The results of calling this on an empty list are undefined. @@ -320,7 +338,8 @@ inline bool is_empty(List<T> const &list) { return !list._cell; } * @return a reference to the first value in the list */ template <typename T> -inline typename List<T>::reference first(List<T> const &list) { +inline typename List<T>::reference first(List<T> const &list) +{ return list._cell->value; } @@ -341,7 +360,8 @@ inline typename List<T>::reference first(List<T> const &list) { * @return the remainder of the list */ template <typename T> -inline List<T> const &rest(List<T> const &list) { +inline List<T> const &rest(List<T> const &list) +{ return reinterpret_cast<List<T> const &>(list._cell->next); } @@ -367,13 +387,14 @@ inline List<T> const &rest(List<T> const &list) { * @return a reference to the remainder of the list */ template <typename T> -inline MutableList<T> &rest(MutableList<T> const &list) { +inline MutableList<T> &rest(MutableList<T> const &list) +{ return reinterpret_cast<MutableList<T> &>(list._cell->next); } /** * Sets a new tail for an existing linked list. - * + * * Sets the tail of the given MutableList<>, corresponding to the * second argument of cons(). * @@ -389,16 +410,15 @@ inline MutableList<T> &rest(MutableList<T> const &list) { * @return the new tail */ template <typename T> -inline MutableList<T> const &set_rest(MutableList<T> const &list, - MutableList<T> const &rest) +inline MutableList<T> const &set_rest(MutableList<T> const &list, MutableList<T> const &rest) { list._cell->next = rest._cell; return reinterpret_cast<MutableList<T> &>(list._cell->next); } -} +} // namespace Util -} +} // namespace Inkscape #endif /* diff --git a/src/util/longest-common-suffix.h b/src/util/longest-common-suffix.h index bc72e6f8cbf5008b7c290726c1023bd9882329e5..839771efb1f9c7dd19f087ffea71a7505df0f0c5 100644 --- a/src/util/longest-common-suffix.h +++ b/src/util/longest-common-suffix.h @@ -13,8 +13,9 @@ #ifndef SEEN_INKSCAPE_ALGORITHMS_LONGEST_COMMON_SUFFIX_H #define SEEN_INKSCAPE_ALGORITHMS_LONGEST_COMMON_SUFFIX_H -#include <iterator> #include <functional> +#include <iterator> + #include "util/list.h" namespace Inkscape { @@ -32,48 +33,46 @@ namespace Algorithms { */ template <typename ForwardIterator> -ForwardIterator longest_common_suffix(ForwardIterator a, ForwardIterator b, - ForwardIterator end) +ForwardIterator longest_common_suffix(ForwardIterator a, ForwardIterator b, ForwardIterator end) { typedef typename std::iterator_traits<ForwardIterator>::value_type value_type; return longest_common_suffix(a, b, end, std::equal_to<value_type>()); } template <typename ForwardIterator, typename BinaryPredicate> -ForwardIterator longest_common_suffix(ForwardIterator a, ForwardIterator b, - ForwardIterator end, BinaryPredicate pred) +ForwardIterator longest_common_suffix(ForwardIterator a, ForwardIterator b, ForwardIterator end, BinaryPredicate pred) { - if ( a == end || b == end ) { + if (a == end || b == end) { return end; } /* Handle in O(1) time the common cases of identical lists or tails. */ { /* identical lists? */ - if ( a == b ) { + if (a == b) { return a; } /* identical tails? */ ForwardIterator tail_a(a); ForwardIterator tail_b(b); - if ( ++tail_a == ++tail_b ) { + if (++tail_a == ++tail_b) { return tail_a; } } /* Build parallel lists of suffixes, ordered by increasing length. */ - using Inkscape::Util::List; using Inkscape::Util::cons; - ForwardIterator lists[2] = { a, b }; + using Inkscape::Util::List; + ForwardIterator lists[2] = {a, b}; List<ForwardIterator> suffixes[2]; - for ( int i=0 ; i < 2 ; i++ ) { - for ( ForwardIterator iter(lists[i]) ; iter != end ; ++iter ) { - if ( iter == lists[1-i] ) { + for (int i = 0; i < 2; i++) { + for (ForwardIterator iter(lists[i]); iter != end; ++iter) { + if (iter == lists[1 - i]) { // the other list is a suffix of this one - return lists[1-i]; + return lists[1 - i]; } suffixes[i] = cons(iter, suffixes[i]); @@ -86,9 +85,7 @@ ForwardIterator longest_common_suffix(ForwardIterator a, ForwardIterator b, ForwardIterator longest_common(end); - while ( suffixes[0] && suffixes[1] && - pred(**suffixes[0], **suffixes[1]) ) - { + while (suffixes[0] && suffixes[1] && pred(**suffixes[0], **suffixes[1])) { longest_common = *suffixes[0]; ++suffixes[0]; ++suffixes[1]; @@ -97,9 +94,9 @@ ForwardIterator longest_common_suffix(ForwardIterator a, ForwardIterator b, return longest_common; } -} +} // namespace Algorithms -} +} // namespace Inkscape #endif /* !SEEN_INKSCAPE_ALGORITHMS_LONGEST_COMMON_SUFFIX_H */ diff --git a/src/util/reference.h b/src/util/reference.h index b4a123b936d8d48a91775e65b6c261d586ee3a81..46885530de297332413a55a2f75f875ea4971974 100644 --- a/src/util/reference.h +++ b/src/util/reference.h @@ -18,7 +18,8 @@ namespace Inkscape { namespace Traits { template <typename T> -struct Reference { +struct Reference +{ typedef T const &RValue; typedef T &LValue; typedef T *Pointer; @@ -26,16 +27,17 @@ struct Reference { }; template <typename T> -struct Reference<T &> { +struct Reference<T &> +{ typedef T &RValue; typedef T &LValue; typedef T *Pointer; typedef T const *ConstPointer; }; -} +} // namespace Traits -} +} // namespace Inkscape #endif /* diff --git a/src/util/reverse-list.h b/src/util/reverse-list.h index c0164085bf300dcdab9470a765d6f6c33a16a54a..a57a780fa1cd9ffbad80c6f626b7da8b867485f6 100644 --- a/src/util/reverse-list.h +++ b/src/util/reverse-list.h @@ -13,18 +13,18 @@ #ifndef SEEN_INKSCAPE_UTIL_REVERSE_LIST_H #define SEEN_INKSCAPE_UTIL_REVERSE_LIST_H -#include "util/list.h" #include "util/list-copy.h" +#include "util/list.h" namespace Inkscape { namespace Util { template <typename InputIterator> -inline typename Traits::ListCopy<InputIterator>::ResultList -reverse_list(InputIterator start, InputIterator end) { +inline typename Traits::ListCopy<InputIterator>::ResultList reverse_list(InputIterator start, InputIterator end) +{ typename Traits::ListCopy<InputIterator>::ResultList head; - while ( start != end ) { + while (start != end) { head = cons(*start, head); ++start; } @@ -32,18 +32,16 @@ reverse_list(InputIterator start, InputIterator end) { } template <typename T> -inline typename Traits::ListCopy<List<T> >::ResultList -reverse_list(List<T> const &list) { +inline typename Traits::ListCopy<List<T>>::ResultList reverse_list(List<T> const &list) +{ return reverse_list(list, List<T>()); } template <typename T> -inline MutableList<T> -reverse_list_in_place(MutableList<T> start, - MutableList<T> end=MutableList<T>()) +inline MutableList<T> reverse_list_in_place(MutableList<T> start, MutableList<T> end = MutableList<T>()) { - MutableList<T> reversed(end); - while ( start != end ) { + MutableList<T> reversed(end); + while (start != end) { MutableList<T> temp(start); ++start; set_rest(temp, reversed); @@ -52,9 +50,9 @@ reverse_list_in_place(MutableList<T> start, return reversed; } -} +} // namespace Util -} +} // namespace Inkscape #endif /* diff --git a/src/util/share.cpp b/src/util/share.cpp index 6c436dcf8c1bc3826601c1a8bf247f37f805d280..70f9dd6244678c0ad7f62174bf5d129b874b8321 100644 --- a/src/util/share.cpp +++ b/src/util/share.cpp @@ -12,26 +12,29 @@ */ #include "util/share.h" + #include <glib.h> namespace Inkscape { namespace Util { -ptr_shared share_string(char const *string) { +ptr_shared share_string(char const *string) +{ g_return_val_if_fail(string != nullptr, share_unsafe(nullptr)); return share_string(string, std::strlen(string)); } -ptr_shared share_string(char const *string, std::size_t length) { +ptr_shared share_string(char const *string, std::size_t length) +{ g_return_val_if_fail(string != nullptr, share_unsafe(nullptr)); - char *new_string=new (GC::ATOMIC) char[length+1]; + char *new_string = new (GC::ATOMIC) char[length + 1]; std::memcpy(new_string, string, length); new_string[length] = 0; return share_unsafe(new_string); } -} -} +} // namespace Util +} // namespace Inkscape /* Local Variables: diff --git a/src/util/share.h b/src/util/share.h index e8b9fb12bf86ce3abbee5cb8791fe55536bfda11..837de749cba7f4488be6d4f6dc35af41d729f608 100644 --- a/src/util/share.h +++ b/src/util/share.h @@ -14,18 +14,21 @@ #ifndef SEEN_INKSCAPE_UTIL_SHARE_H #define SEEN_INKSCAPE_UTIL_SHARE_H -#include "inkgc/gc-core.h" -#include <cstring> #include <cstddef> +#include <cstring> + +#include "inkgc/gc-core.h" namespace Inkscape { namespace Util { -class ptr_shared { +class ptr_shared +{ public: - - ptr_shared() : _string(nullptr) {} - ptr_shared(ptr_shared const &other) = default; + ptr_shared() + : _string(nullptr) + {} + ptr_shared(ptr_shared const &other) = default; operator char const *() const { return _string; } operator bool() const { return _string; } @@ -33,71 +36,61 @@ public: char const *pointer() const { return _string; } char const &operator[](int i) const { return _string[i]; } - ptr_shared operator+(int i) const { - return share_unsafe(_string+i); - } - ptr_shared operator-(int i) const { - return share_unsafe(_string-i); - } - //WARNING: No bounds checking in += and -= functions. Moving the pointer - //past the end of the string and then back could probably cause the garbage - //collector to deallocate the string inbetween, as there's temporary no - //valid reference pointing into the allocated space. - ptr_shared &operator+=(int i) { + ptr_shared operator+(int i) const { return share_unsafe(_string + i); } + ptr_shared operator-(int i) const { return share_unsafe(_string - i); } + // WARNING: No bounds checking in += and -= functions. Moving the pointer + // past the end of the string and then back could probably cause the garbage + // collector to deallocate the string inbetween, as there's temporary no + // valid reference pointing into the allocated space. + ptr_shared &operator+=(int i) + { _string += i; return *this; } - ptr_shared &operator-=(int i) { + ptr_shared &operator-=(int i) + { _string -= i; return *this; } - std::ptrdiff_t operator-(ptr_shared const &other) { - return _string - other._string; - } + std::ptrdiff_t operator-(ptr_shared const &other) { return _string - other._string; } ptr_shared &operator=(ptr_shared const &other) = default; - bool operator==(ptr_shared const &other) const { - return _string == other._string; - } - bool operator!=(ptr_shared const &other) const { - return _string != other._string; - } - bool operator>(ptr_shared const &other) const { - return _string > other._string; - } - bool operator<(ptr_shared const &other) const { - return _string < other._string; - } + bool operator==(ptr_shared const &other) const { return _string == other._string; } + bool operator!=(ptr_shared const &other) const { return _string != other._string; } + bool operator>(ptr_shared const &other) const { return _string > other._string; } + bool operator<(ptr_shared const &other) const { return _string < other._string; } - friend ptr_shared share_unsafe(char const *string); + friend ptr_shared share_unsafe(char const *string); private: - ptr_shared(char const *string) : _string(string) {} - static ptr_shared share_unsafe(char const *string) { - return ptr_shared(string); - } - - //This class (and code using it) assumes that it never has to free this - //pointer, and that the memory it points to will not be freed as long as a - //ptr_shared pointing to it exists. + ptr_shared(char const *string) + : _string(string) + {} + static ptr_shared share_unsafe(char const *string) { return ptr_shared(string); } + + // This class (and code using it) assumes that it never has to free this + // pointer, and that the memory it points to will not be freed as long as a + // ptr_shared pointing to it exists. char const *_string; }; ptr_shared share_string(char const *string); ptr_shared share_string(char const *string, std::size_t length); -inline ptr_shared share_unsafe(char const *string) { +inline ptr_shared share_unsafe(char const *string) +{ return ptr_shared::share_unsafe(string); } -//TODO: Do we need this function? -inline ptr_shared share_static_string(char const *string) { +// TODO: Do we need this function? +inline ptr_shared share_static_string(char const *string) +{ return share_unsafe(string); } -} -} +} // namespace Util +} // namespace Inkscape #endif /* diff --git a/src/util/signal-blocker.h b/src/util/signal-blocker.h index 8fb62569a05072a2f3be5c10cebf6a3a5e6f41de..fdb5283a2de2d6db77293b5ab26d1c3f21fb65bc 100644 --- a/src/util/signal-blocker.h +++ b/src/util/signal-blocker.h @@ -13,8 +13,8 @@ #ifndef SEEN_INKSCAPE_UTIL_SIGNAL_BLOCKER_H #define SEEN_INKSCAPE_UTIL_SIGNAL_BLOCKER_H -#include <string> #include <sigc++/connection.h> +#include <string> /** * Base RAII blocker for sgic++ signals. @@ -26,12 +26,11 @@ public: * Creates a new instance that if the signal is currently unblocked will block * it until this instance is destructed and then will unblock it. */ - SignalBlocker( sigc::connection *connection ) : - _connection(connection), - _wasBlocked(_connection->blocked()) + SignalBlocker(sigc::connection *connection) + : _connection(connection) + , _wasBlocked(_connection->blocked()) { - if (!_wasBlocked) - { + if (!_wasBlocked) { _connection->block(); } } @@ -42,8 +41,7 @@ public: */ ~SignalBlocker() { - if (!_wasBlocked) - { + if (!_wasBlocked) { _connection->block(false); } } @@ -51,8 +49,8 @@ public: private: // noncopyable, nonassignable SignalBlocker(SignalBlocker const &other) = delete; - SignalBlocker& operator=(SignalBlocker const &other) = delete; - + SignalBlocker &operator=(SignalBlocker const &other) = delete; + sigc::connection *_connection; bool _wasBlocked; }; diff --git a/src/util/units.cpp b/src/util/units.cpp index 478e9dc8ae80d138c9525964f454f44ff2e93b04..878b78c558c1e8b593af9cac4f5510d9e3d92925 100644 --- a/src/util/units.cpp +++ b/src/util/units.cpp @@ -10,69 +10,65 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cmath> +#include "util/units.h" + +#include <2geom/coord.h> #include <cerrno> -#include <iomanip> -#include <iostream> -#include <utility> -#include <unordered_map> +#include <cmath> #include <glib.h> -#include <glibmm/regex.h> #include <glibmm/fileutils.h> #include <glibmm/markup.h> - -#include <2geom/coord.h> +#include <glibmm/regex.h> +#include <iomanip> +#include <iostream> +#include <unordered_map> +#include <utility> #include "io/resource.h" -#include "util/units.h" #include "path-prefix.h" #include "streq.h" using Inkscape::Util::UNIT_TYPE_DIMENSIONLESS; +using Inkscape::Util::UNIT_TYPE_FONT_HEIGHT; using Inkscape::Util::UNIT_TYPE_LINEAR; using Inkscape::Util::UNIT_TYPE_RADIAL; -using Inkscape::Util::UNIT_TYPE_FONT_HEIGHT; -namespace -{ +namespace { -#define MAKE_UNIT_CODE(a, b) \ - ((((unsigned)(a) & 0xdf) << 8) | ((unsigned)(b) & 0xdf)) +#define MAKE_UNIT_CODE(a, b) ((((unsigned)(a)&0xdf) << 8) | ((unsigned)(b)&0xdf)) -enum UnitCode { - UNIT_CODE_PX = MAKE_UNIT_CODE('p','x'), - UNIT_CODE_PT = MAKE_UNIT_CODE('p','t'), - UNIT_CODE_PC = MAKE_UNIT_CODE('p','c'), - UNIT_CODE_MM = MAKE_UNIT_CODE('m','m'), - UNIT_CODE_CM = MAKE_UNIT_CODE('c','m'), - UNIT_CODE_IN = MAKE_UNIT_CODE('i','n'), - UNIT_CODE_EM = MAKE_UNIT_CODE('e','m'), - UNIT_CODE_EX = MAKE_UNIT_CODE('e','x'), - UNIT_CODE_PERCENT = MAKE_UNIT_CODE('%',0) +enum UnitCode +{ + UNIT_CODE_PX = MAKE_UNIT_CODE('p', 'x'), + UNIT_CODE_PT = MAKE_UNIT_CODE('p', 't'), + UNIT_CODE_PC = MAKE_UNIT_CODE('p', 'c'), + UNIT_CODE_MM = MAKE_UNIT_CODE('m', 'm'), + UNIT_CODE_CM = MAKE_UNIT_CODE('c', 'm'), + UNIT_CODE_IN = MAKE_UNIT_CODE('i', 'n'), + UNIT_CODE_EM = MAKE_UNIT_CODE('e', 'm'), + UNIT_CODE_EX = MAKE_UNIT_CODE('e', 'x'), + UNIT_CODE_PERCENT = MAKE_UNIT_CODE('%', 0) }; // TODO: convert to constexpr in C++11, so that the above constants can be eliminated -inline unsigned make_unit_code(char const *str) { - if (!str || str[0] == 0) return 0; +inline unsigned make_unit_code(char const *str) +{ + if (!str || str[0] == 0) + return 0; return MAKE_UNIT_CODE(str[0], str[1]); } - // This must match SVGLength::Unit -unsigned const svg_length_lookup[] = { - 0, - UNIT_CODE_PX, - UNIT_CODE_PT, - UNIT_CODE_PC, - UNIT_CODE_MM, - UNIT_CODE_CM, - UNIT_CODE_IN, - UNIT_CODE_EM, - UNIT_CODE_EX, - UNIT_CODE_PERCENT -}; - - +unsigned const svg_length_lookup[] = {0, + UNIT_CODE_PX, + UNIT_CODE_PT, + UNIT_CODE_PC, + UNIT_CODE_MM, + UNIT_CODE_CM, + UNIT_CODE_IN, + UNIT_CODE_EM, + UNIT_CODE_EX, + UNIT_CODE_PERCENT}; // maps unit codes obtained from their abbreviations to their SVGLength unit indexes typedef std::unordered_map<unsigned, SVGLength::Unit> UnitCodeLookup; @@ -88,8 +84,6 @@ UnitCodeLookup make_unit_code_lookup() UnitCodeLookup const unit_code_lookup = make_unit_code_lookup(); - - typedef std::unordered_map<Glib::ustring, Inkscape::Util::UnitType> TypeMap; /** A std::map that gives the data type value for the string version. @@ -134,30 +128,25 @@ public: Unit unit; }; -UnitParser::UnitParser(UnitTable *table) : - tbl(table), - primary(false), - skip(false) -{ -} +UnitParser::UnitParser(UnitTable *table) + : tbl(table) + , primary(false) + , skip(false) +{} #define BUFSIZE (255) -Unit::Unit() : - type(UNIT_TYPE_DIMENSIONLESS), // should this or NONE be the default? - factor(1.0), - name(), - name_plural(), - abbr(), - description() -{ -} - -Unit::Unit(UnitType type, - double factor, - Glib::ustring name, - Glib::ustring name_plural, - Glib::ustring abbr, +Unit::Unit() + : type(UNIT_TYPE_DIMENSIONLESS) + , // should this or NONE be the default? + factor(1.0) + , name() + , name_plural() + , abbr() + , description() +{} + +Unit::Unit(UnitType type, double factor, Glib::ustring name, Glib::ustring name_plural, Glib::ustring abbr, Glib::ustring description) : type(type) , factor(factor) @@ -227,27 +216,25 @@ double Unit::convert(double from_dist, Unit const *to) const // Percentage if (to->type == UNIT_TYPE_DIMENSIONLESS) { return from_dist * to->factor; - } - + } + // Incompatible units if (type != to->type) { - return -1; - } - + return -1; + } + // Compatible units return from_dist * factor / to->factor; } double Unit::convert(double from_dist, Glib::ustring const &to) const { return convert(from_dist, unit_table.getUnit(to)); -} +} double Unit::convert(double from_dist, char const *to) const { return convert(from_dist, unit_table.getUnit(to)); } - - Unit UnitTable::_empty_unit; UnitTable::UnitTable() @@ -259,8 +246,7 @@ UnitTable::UnitTable() UnitTable::~UnitTable() { - for (auto & iter : _unit_map) - { + for (auto &iter : _unit_map) { delete iter.second; } } @@ -348,7 +334,7 @@ Quantity UnitTable::parseQuantity(Glib::ustring const &q) const return qty; } -/* UNSAFE while passing around pointers to the Unit objects in this table +/* UNSAFE while passing around pointers to the Unit objects in this table bool UnitTable::deleteUnit(Unit const &u) { bool deleted = false; @@ -389,7 +375,8 @@ Glib::ustring UnitTable::primary(UnitType type) const return _primary_unit[type]; } -bool UnitTable::load(std::string const &filename) { +bool UnitTable::load(std::string const &filename) +{ UnitParser uparser(this); Glib::Markup::ParseContext ctx(uparser); @@ -417,7 +404,7 @@ bool UnitTable::save(std::string const &filename) { Inkscape::Util::UnitTable unit_table; -void UnitParser::on_start_element(Ctx &/*ctx*/, Glib::ustring const &name, AttrMap const &attrs) +void UnitParser::on_start_element(Ctx & /*ctx*/, Glib::ustring const &name, AttrMap const &attrs) { if (name == "unit") { // reset for next use @@ -459,7 +446,7 @@ void UnitParser::on_text(Ctx &ctx, Glib::ustring const &text) } } -void UnitParser::on_end_element(Ctx &/*ctx*/, Glib::ustring const &name) +void UnitParser::on_end_element(Ctx & /*ctx*/, Glib::ustring const &name) { if (name == "unit" && !skip) { tbl->addUnit(unit, primary); @@ -467,20 +454,17 @@ void UnitParser::on_end_element(Ctx &/*ctx*/, Glib::ustring const &name) } Quantity::Quantity(double q, Unit const *u) - : unit(u) - , quantity(q) -{ -} + : unit(u) + , quantity(q) +{} Quantity::Quantity(double q, Glib::ustring const &u) - : unit(unit_table.getUnit(u.c_str())) - , quantity(q) -{ -} + : unit(unit_table.getUnit(u.c_str())) + , quantity(q) +{} Quantity::Quantity(double q, char const *u) - : unit(unit_table.getUnit(u)) - , quantity(q) -{ -} + : unit(unit_table.getUnit(u)) + , quantity(q) +{} bool Quantity::compatibleWith(Unit const *u) const { @@ -508,13 +492,16 @@ double Quantity::value(char const *u) const return value(unit_table.getUnit(u)); } -Glib::ustring Quantity::string(Unit const *u) const { +Glib::ustring Quantity::string(Unit const *u) const +{ return Glib::ustring::format(std::fixed, std::setprecision(2), value(u)) + " " + u->abbr; } -Glib::ustring Quantity::string(Glib::ustring const &u) const { +Glib::ustring Quantity::string(Glib::ustring const &u) const +{ return string(unit_table.getUnit(u.c_str())); } -Glib::ustring Quantity::string() const { +Glib::ustring Quantity::string() const +{ return string(unit); } diff --git a/src/util/units.h b/src/util/units.h index 48478c77c5a9b3a1246201834af31cd65d99f6a1..2a0f226bd79b32133aad1d14e6d49009208006c9 100644 --- a/src/util/units.h +++ b/src/util/units.h @@ -14,10 +14,11 @@ #ifndef INKSCAPE_UTIL_UNITS_H #define INKSCAPE_UTIL_UNITS_H -#include <unordered_map> +#include <2geom/coord.h> #include <boost/operators.hpp> #include <glibmm/ustring.h> -#include <2geom/coord.h> +#include <unordered_map> + #include "svg/svg-length.h" #ifndef DOXYGEN_SHOULD_SKIP_THIS @@ -26,10 +27,9 @@ namespace std { template <> -struct hash<Glib::ustring> : public std::unary_function<Glib::ustring, std::size_t> { - std::size_t operator()(Glib::ustring const &s) const { - return hash<std::string>()(s.raw()); - } +struct hash<Glib::ustring> : public std::unary_function<Glib::ustring, std::size_t> +{ + std::size_t operator()(Glib::ustring const &s) const { return hash<std::string>()(s.raw()); } }; } // namespace std @@ -38,8 +38,9 @@ struct hash<Glib::ustring> : public std::unary_function<Glib::ustring, std::size namespace Inkscape { namespace Util { -enum UnitType { - UNIT_TYPE_DIMENSIONLESS, /* Percentage */ +enum UnitType +{ + UNIT_TYPE_DIMENSIONLESS, /* Percentage */ UNIT_TYPE_LINEAR, UNIT_TYPE_LINEAR_SCALED, UNIT_TYPE_RADIAL, @@ -51,43 +52,38 @@ enum UnitType { const char DEG[] = "°"; -class Unit - : boost::equality_comparable<Unit> +class Unit : boost::equality_comparable<Unit> { public: Unit(); - Unit(UnitType type, - double factor, - Glib::ustring name, - Glib::ustring name_plural, - Glib::ustring abbr, + Unit(UnitType type, double factor, Glib::ustring name, Glib::ustring name_plural, Glib::ustring abbr, Glib::ustring description); void clear(); - bool isAbsolute() const { return type != UNIT_TYPE_DIMENSIONLESS; } + bool isAbsolute() const { return type != UNIT_TYPE_DIMENSIONLESS; } /** * Returns the suggested precision to use for displaying numbers * of this unit. */ - int defaultDigits() const; + int defaultDigits() const; /** Checks if a unit is compatible with the specified unit. */ - bool compatibleWith(Unit const *u) const; - bool compatibleWith(Glib::ustring const &) const; - bool compatibleWith(char const *) const; - - UnitType type; - double factor; - Glib::ustring name; - Glib::ustring name_plural; - Glib::ustring abbr; - Glib::ustring description; - + bool compatibleWith(Unit const *u) const; + bool compatibleWith(Glib::ustring const &) const; + bool compatibleWith(char const *) const; + + UnitType type; + double factor; + Glib::ustring name; + Glib::ustring name_plural; + Glib::ustring abbr; + Glib::ustring description; + /** Check if units are equal. */ bool operator==(Unit const &other) const; - + /** Get SVG unit code. */ int svgUnit() const; @@ -97,34 +93,33 @@ public: double convert(double from_dist, char const *to) const; }; -class Quantity - : boost::totally_ordered<Quantity> +class Quantity : boost::totally_ordered<Quantity> { public: Unit const *unit; double quantity; - + /** Initialize a quantity. */ Quantity(double q, Unit const *u); Quantity(double q, Glib::ustring const &u); Quantity(double q, char const *u); - + /** Checks if a quantity is compatible with the specified unit. */ bool compatibleWith(Unit const *u) const; bool compatibleWith(Glib::ustring const &u) const; bool compatibleWith(char const *u) const; - + /** Return the quantity's value in the specified unit. */ double value(Unit const *u) const; double value(Glib::ustring const &u) const; double value(char const *u) const; - + /** Return a printable string of the value in the specified unit. */ Glib::ustring string(Unit const *u) const; Glib::ustring string(Glib::ustring const &u) const; Glib::ustring string() const; - - /** Convert distances. + + /** Convert distances. no NULL check is performed on the passed pointers to Unit objects! */ static double convert(double from_dist, Unit const *from, Unit const *to); static double convert(double from_dist, Glib::ustring const &from, Unit const *to); @@ -137,12 +132,13 @@ public: bool operator==(Quantity const &other) const; }; -inline bool are_near(Quantity const &a, Quantity const &b, double eps=Geom::EPSILON) +inline bool are_near(Quantity const &a, Quantity const &b, double eps = Geom::EPSILON) { return Geom::are_near(a.quantity, b.value(a.unit), eps); } -class UnitTable { +class UnitTable +{ public: /** * Initializes the unit tables and identifies the primary unit types. @@ -153,10 +149,10 @@ public: virtual ~UnitTable(); typedef std::unordered_map<Glib::ustring, Unit> UnitMap; - typedef std::unordered_map<unsigned, Unit*> UnitCodeMap; + typedef std::unordered_map<unsigned, Unit *> UnitCodeMap; /** Add a new unit to the table */ - void addUnit(Unit const &u, bool primary); + void addUnit(Unit const &u, bool primary); /** Retrieve a given unit based on its string identifier */ Unit const *getUnit(Glib::ustring const &name) const; @@ -164,19 +160,19 @@ public: /** Try to find a unit based on its conversion factor to the primary */ Unit const *findUnit(double factor, UnitType type) const; - + /** Retrieve a given unit based on its SVGLength unit */ Unit const *getUnit(SVGLength::Unit u) const; - + /** Retrieve a quantity based on its string identifier */ Quantity parseQuantity(Glib::ustring const &q) const; /** Remove a unit definition from the given unit type table * / * DISABLED, unsafe with the current passing around pointers to Unit objects in this table */ - //bool deleteUnit(Unit const &u); + // bool deleteUnit(Unit const &u); /** Returns true if the given string 'name' is a valid unit in the table */ - bool hasUnit(Glib::ustring const &name) const; + bool hasUnit(Glib::ustring const &name) const; /** Provides an iteratable list of items in the given unit table */ UnitMap units(UnitType type) const; @@ -184,9 +180,9 @@ public: /** Returns the default unit abbr for the given type */ Glib::ustring primary(UnitType type) const; - double getScale() const; + double getScale() const; - void setScale(); + void setScale(); /** Load units from an XML file. * @@ -195,22 +191,21 @@ public: * * @param filename file to be loaded */ - bool load(std::string const &filename); + bool load(std::string const &filename); /* * Saves the current UnitTable to the given file. */ - //bool save(std::string const &filename); + // bool save(std::string const &filename); protected: - UnitCodeMap _unit_map; - Glib::ustring _primary_unit[UNIT_TYPE_QTY]; + UnitCodeMap _unit_map; + Glib::ustring _primary_unit[UNIT_TYPE_QTY]; - double _linear_scale; - static Unit _empty_unit; + double _linear_scale; + static Unit _empty_unit; private: UnitTable(UnitTable const &t); UnitTable operator=(UnitTable const &t); - }; extern UnitTable unit_table; diff --git a/src/util/ziptool.cpp b/src/util/ziptool.cpp index dc873962413f491789b8e74c67c58cf7d660e495..260b07021670b829ba0afcf4062722189f2be239 100644 --- a/src/util/ziptool.cpp +++ b/src/util/ziptool.cpp @@ -37,21 +37,14 @@ * on ZLib and Info-Zip. Enjoy. */ +#include "ziptool.h" -#include <cstdio> #include <cstdarg> +#include <cstdio> #include <ctime> - #include <string> #include <utility> -#include "ziptool.h" - - - - - - //######################################################################## //# A D L E R 3 2 //######################################################################## @@ -67,8 +60,7 @@ Adler32::Adler32() /** * Destructor */ -Adler32::~Adler32() -= default; +Adler32::~Adler32() = default; /** * Reset Adler-32 checksum to initial value. @@ -97,7 +89,6 @@ void Adler32::update(char *str) update((unsigned char)*str++); } - /** * Returns current checksum value. */ @@ -106,8 +97,6 @@ unsigned long Adler32::getValue() return value & 0xffffffffL; } - - //######################################################################## //# C R C 3 2 //######################################################################## @@ -123,8 +112,7 @@ Crc32::Crc32() /** * Destructor */ -Crc32::~Crc32() -= default; +Crc32::~Crc32() = default; static bool crc_table_ready = false; static unsigned long crc_table[256]; @@ -136,22 +124,19 @@ static void makeCrcTable() { if (crc_table_ready) return; - for (int n = 0; n < 256; n++) - { + for (int n = 0; n < 256; n++) { unsigned long c = n; - for (int k = 8; --k >= 0; ) - { + for (int k = 8; --k >= 0;) { if ((c & 1) != 0) c = 0xedb88320 ^ (c >> 1); else c >>= 1; - } - crc_table[n] = c; } + crc_table[n] = c; + } crc_table_ready = true; } - /** * Reset CRC-32 checksum to initial value. */ @@ -170,7 +155,6 @@ void Crc32::update(unsigned char b) value = ~c; } - void Crc32::update(char *str) { if (str) @@ -181,14 +165,12 @@ void Crc32::update(char *str) void Crc32::update(const std::vector<unsigned char> &buf) { std::vector<unsigned char>::const_iterator iter; - for (iter=buf.begin() ; iter!=buf.end() ; ++iter) - { + for (iter = buf.begin(); iter != buf.end(); ++iter) { unsigned char ch = *iter; update(ch); - } + } } - /** * Returns current checksum value. */ @@ -201,7 +183,6 @@ unsigned long Crc32::getValue() //# I N F L A T E R //######################################################################## - /** * */ @@ -217,42 +198,39 @@ struct Huffman class Inflater { public: - Inflater(); virtual ~Inflater(); - static const int MAXBITS = 15; // max bits in a code + static const int MAXBITS = 15; // max bits in a code static const int MAXLCODES = 286; // max number of literal/length codes - static const int MAXDCODES = 30; // max number of distance codes - static const int MAXCODES = 316; // max codes lengths to read + static const int MAXDCODES = 30; // max number of distance codes + static const int MAXCODES = 316; // max codes lengths to read static const int FIXLCODES = 288; // number of fixed literal/length codes /** * */ - bool inflate(std::vector<unsigned char> &destination, - std::vector<unsigned char> &source); + bool inflate(std::vector<unsigned char> &destination, std::vector<unsigned char> &source); private: - /** * */ void error(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; +#ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) +#endif + ; /** * */ void trace(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; +#ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) +#endif + ; /** * @@ -294,34 +272,29 @@ private: */ bool doDynamic(); + std::vector<unsigned char> dest; - std::vector<unsigned char>dest; - - std::vector<unsigned char>src; - unsigned long srcPos; //current read position + std::vector<unsigned char> src; + unsigned long srcPos; // current read position int bitBuf; int bitCnt; - }; - /** * */ -Inflater::Inflater() : - dest(), - src(), - srcPos(0), - bitBuf(0), - bitCnt(0) -{ -} +Inflater::Inflater() + : dest() + , src() + , srcPos(0) + , bitBuf(0) + , bitCnt(0) +{} /** * */ -Inflater::~Inflater() -= default; +Inflater::~Inflater() = default; /** * @@ -349,16 +322,14 @@ void Inflater::trace(char const *fmt, ...) va_end(args); } - /** * */ void Inflater::dump() { - for (unsigned char i : dest) - { + for (unsigned char i : dest) { fputc(i, stdout); - } + } } /** @@ -370,28 +341,26 @@ int Inflater::buildHuffman(Huffman *h, int *length, int n) for (int len = 0; len <= MAXBITS; len++) h->count[len] = 0; for (int symbol = 0; symbol < n; symbol++) - (h->count[length[symbol]])++; // assumes lengths are within bounds - if (h->count[0] == n) // no codes! - { + (h->count[length[symbol]])++; // assumes lengths are within bounds + if (h->count[0] == n) // no codes! + { error("huffman tree will result in failed decode"); return -1; - } + } // check for an over-subscribed or incomplete set of lengths - int left = 1; // number of possible codes left of current length - for (int len = 1; len <= MAXBITS; len++) - { - left <<= 1; // one more bit, double codes left - left -= h->count[len]; // deduct count from possible codes - if (left < 0) - { + int left = 1; // number of possible codes left of current length + for (int len = 1; len <= MAXBITS; len++) { + left <<= 1; // one more bit, double codes left + left -= h->count[len]; // deduct count from possible codes + if (left < 0) { error("huffman over subscribed"); return -1; - } } + } // generate offsets into symbol table for each length for sorting - int offs[MAXBITS+1]; //offsets in symbol table for each length + int offs[MAXBITS + 1]; // offsets in symbol table for each length offs[1] = 0; for (int len = 1; len < MAXBITS; len++) offs[len + 1] = offs[len] + h->count[len]; @@ -408,7 +377,6 @@ int Inflater::buildHuffman(Huffman *h, int *length, int n) return left; } - /** * */ @@ -416,71 +384,64 @@ bool Inflater::getBits(int requiredBits, int *oval) { long val = bitBuf; - //add more bytes if needed - while (bitCnt < requiredBits) - { - if (srcPos >= src.size()) - { + // add more bytes if needed + while (bitCnt < requiredBits) { + if (srcPos >= src.size()) { error("premature end of input"); return false; - } + } val |= ((long)(src[srcPos++])) << bitCnt; bitCnt += 8; - } + } - //update the buffer and return the data - bitBuf = (int)(val >> requiredBits); + // update the buffer and return the data + bitBuf = (int)(val >> requiredBits); bitCnt -= requiredBits; *oval = (int)(val & ((1L << requiredBits) - 1)); return true; } - /** * */ int Inflater::doDecode(Huffman *h) { - int bitTmp = bitBuf; - int left = bitCnt; - int code = 0; - int first = 0; - int index = 0; - int len = 1; + int bitTmp = bitBuf; + int left = bitCnt; + int code = 0; + int first = 0; + int index = 0; + int len = 1; int *next = h->count + 1; - while (true) - { - while (left--) - { - code |= bitTmp & 1; + while (true) { + while (left--) { + code |= bitTmp & 1; bitTmp >>= 1; - int count = *next++; - if (code < first + count) - { /* if length len, return symbol */ + int count = *next++; + if (code < first + count) { /* if length len, return symbol */ bitBuf = bitTmp; bitCnt = (bitCnt - len) & 7; return h->symbol[index + (code - first)]; - } - index += count; - first += count; + } + index += count; + first += count; first <<= 1; - code <<= 1; + code <<= 1; len++; - } - left = (MAXBITS+1) - len; + } + left = (MAXBITS + 1) - len; if (left == 0) break; - if (srcPos >= src.size()) - { + if (srcPos >= src.size()) { error("premature end of input"); dump(); return -1; - } + } bitTmp = src[srcPos++]; if (left > 8) left = 8; - } + } error("no end of block found"); return -1; @@ -491,75 +452,65 @@ int Inflater::doDecode(Huffman *h) */ bool Inflater::doCodes(Huffman *lencode, Huffman *distcode) { - static const int lens[29] = { // Size base for length codes 257..285 - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; - static const int lext[29] = { // Extra bits for length codes 257..285 - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, - 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; - static const int dists[30] = { // Offset base for distance codes 0..29 - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577}; - static const int dext[30] = { // Extra bits for distance codes 0..29 - 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, - 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, - 12, 12, 13, 13}; - - //decode literals and length/distance pairs - while (true) - { + static const int lens[29] = {// Size base for length codes 257..285 + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, + 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; + static const int lext[29] = {// Extra bits for length codes 257..285 + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; + static const int dists[30] = {// Offset base for distance codes 0..29 + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, + 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, + 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; + static const int dext[30] = {// Extra bits for distance codes 0..29 + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, + 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; + + // decode literals and length/distance pairs + while (true) { int symbol = doDecode(lencode); if (symbol == 256) break; - if (symbol < 0) - { + if (symbol < 0) { return false; - } - if (symbol < 256) //literal - { + } + if (symbol < 256) // literal + { dest.push_back(symbol); - } - else if (symbol > 256)//length - { + } else if (symbol > 256) // length + { symbol -= 257; - if (symbol >= 29) - { + if (symbol >= 29) { error("invalid fixed code"); return false; - } + } int ret; if (!getBits(lext[symbol], &ret)) return false; int len = lens[symbol] + ret; - symbol = doDecode(distcode);//distance - if (symbol < 0) - { + symbol = doDecode(distcode); // distance + if (symbol < 0) { return false; - } + } if (!getBits(dext[symbol], &ret)) return false; unsigned int dist = dists[symbol] + ret; - if (dist > dest.size()) - { + if (dist > dest.size()) { error("distance too far back %d/%d", dist, dest.size()); dump(); - //printf("pos:%d\n", srcPos); + // printf("pos:%d\n", srcPos); return false; - } + } // copy length bytes from distance bytes back - //dest.push_back('{'); - while (len--) - { + // dest.push_back('{'); + while (len--) { dest.push_back(dest[dest.size() - dist]); - } - //dest.push_back('}'); - } + // dest.push_back('}'); } + } return true; } @@ -568,36 +519,32 @@ bool Inflater::doCodes(Huffman *lencode, Huffman *distcode) */ bool Inflater::doStored() { - //trace("### stored ###"); + // trace("### stored ###"); // clear bits from current byte bitBuf = 0; bitCnt = 0; // length - if (srcPos + 4 > src.size()) - { + if (srcPos + 4 > src.size()) { error("not enough input"); return false; - } + } int len = src[srcPos++]; len |= src[srcPos++] << 8; - //trace("### len:%d", len); + // trace("### len:%d", len); // check complement - if (src[srcPos++] != (~len & 0xff) || - src[srcPos++] != ((~len >> 8) & 0xff)) - { + if (src[srcPos++] != (~len & 0xff) || src[srcPos++] != ((~len >> 8) & 0xff)) { error("twos complement for storage size do not match"); return false; - } + } // copy data - if (srcPos + len > src.size()) - { + if (srcPos + len > src.size()) { error("Not enough input for stored block"); return false; - } + } while (len--) dest.push_back(src[srcPos++]); @@ -608,29 +555,28 @@ bool Inflater::doStored() */ bool Inflater::doFixed() { - //trace("### fixed ###"); + // trace("### fixed ###"); static bool firstTime = true; - static int lencnt[MAXBITS+1], lensym[FIXLCODES]; - static int distcnt[MAXBITS+1], distsym[MAXDCODES]; + static int lencnt[MAXBITS + 1], lensym[FIXLCODES]; + static int distcnt[MAXBITS + 1], distsym[MAXDCODES]; static Huffman lencode = {lencnt, lensym}; static Huffman distcode = {distcnt, distsym}; - if (firstTime) - { + if (firstTime) { firstTime = false; int lengths[FIXLCODES]; // literal/length table int symbol = 0; - for ( ; symbol < 144; symbol++) + for (; symbol < 144; symbol++) lengths[symbol] = 8; - for ( ; symbol < 256; symbol++) + for (; symbol < 256; symbol++) lengths[symbol] = 9; - for ( ; symbol < 280; symbol++) + for (; symbol < 280; symbol++) lengths[symbol] = 7; - for ( ; symbol < FIXLCODES; symbol++) + for (; symbol < FIXLCODES; symbol++) lengths[symbol] = 8; buildHuffman(&lencode, lengths, FIXLCODES); @@ -638,7 +584,7 @@ bool Inflater::doFixed() for (int symbol = 0; symbol < MAXDCODES; symbol++) lengths[symbol] = 5; buildHuffman(&distcode, lengths, MAXDCODES); - } + } // decode data until end-of-block code bool ret = doCodes(&lencode, &distcode); @@ -649,41 +595,39 @@ bool Inflater::doFixed() */ bool Inflater::doDynamic() { - //trace("### dynamic ###"); - int lengths[MAXCODES]; // descriptor code lengths - int lencnt[MAXBITS+1], lensym[MAXLCODES]; // lencode memory - int distcnt[MAXBITS+1], distsym[MAXDCODES]; // distcode memory - Huffman lencode = {lencnt, lensym}; // length code + // trace("### dynamic ###"); + int lengths[MAXCODES]; // descriptor code lengths + int lencnt[MAXBITS + 1], lensym[MAXLCODES]; // lencode memory + int distcnt[MAXBITS + 1], distsym[MAXDCODES]; // distcode memory + Huffman lencode = {lencnt, lensym}; // length code Huffman distcode = {distcnt, distsym}; // distance code - static const int order[19] = // permutation of code length codes + static const int order[19] = // permutation of code length codes {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; // get number of lengths in each table, check lengths int ret; if (!getBits(5, &ret)) return false; - int nlen = ret + 257; + int nlen = ret + 257; if (!getBits(5, &ret)) return false; int ndist = ret + 1; if (!getBits(4, &ret)) return false; int ncode = ret + 4; - if (nlen > MAXLCODES || ndist > MAXDCODES) - { + if (nlen > MAXLCODES || ndist > MAXDCODES) { error("Bad codes"); return false; - } + } // get code length code lengths int index = 0; - for ( ; index < ncode; index++) - { + for (; index < ncode; index++) { if (!getBits(3, &ret)) return false; lengths[order[index]] = ret; - } - for ( ; index < 19; index++) + } + for (; index < 19; index++) lengths[order[index]] = 0; // build huffman table for code lengths codes @@ -692,62 +636,53 @@ bool Inflater::doDynamic() // read length/literal and distance code length tables index = 0; - while (index < nlen + ndist) - { + while (index < nlen + ndist) { int symbol = doDecode(&lencode); - if (symbol < 16) // length in 0..15 + if (symbol < 16) // length in 0..15 lengths[index++] = symbol; - else - { // repeat instruction - int len = 0; // assume repeating zeros - if (symbol == 16) - { // repeat last length 3..6 times - if (index == 0) - { + else { // repeat instruction + int len = 0; // assume repeating zeros + if (symbol == 16) { // repeat last length 3..6 times + if (index == 0) { error("no last length"); return false; - } - len = lengths[index - 1];// last length + } + len = lengths[index - 1]; // last length if (!getBits(2, &ret)) return false; symbol = 3 + ret; - } - else if (symbol == 17) // repeat zero 3..10 times - { + } else if (symbol == 17) // repeat zero 3..10 times + { if (!getBits(3, &ret)) return false; symbol = 3 + ret; - } - else // == 18, repeat zero 11..138 times - { + } else // == 18, repeat zero 11..138 times + { if (!getBits(7, &ret)) return false; symbol = 11 + ret; - } - if (index + symbol > nlen + ndist) - { + } + if (index + symbol > nlen + ndist) { error("too many lengths"); return false; - } - while (symbol--) // repeat last or zero symbol times - lengths[index++] = len; } + while (symbol--) // repeat last or zero symbol times + lengths[index++] = len; } + } // build huffman table for literal/length codes int err = buildHuffman(&lencode, lengths, nlen); - if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1)) - { + if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1)) { error("incomplete length codes"); - //return false; - } + // return false; + } // build huffman table for distance codes err = buildHuffman(&distcode, lengths + nlen, ndist); - if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1)) - { + if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1)) { error("incomplete dist codes"); return false; - } + } // decode data until end-of-block code bool retn = doCodes(&lencode, &distcode); @@ -756,8 +691,7 @@ bool Inflater::doDynamic() /** */ -bool Inflater::inflate(std::vector<unsigned char> &destination, - std::vector<unsigned char> &source) +bool Inflater::inflate(std::vector<unsigned char> &destination, std::vector<unsigned char> &source) { dest.clear(); src = source; @@ -765,16 +699,14 @@ bool Inflater::inflate(std::vector<unsigned char> &destination, bitBuf = 0; bitCnt = 0; - while (true) - { + while (true) { int last; // one if last block if (!getBits(1, &last)) return false; int type; // block type 0..3 if (!getBits(2, &type)) return false; - switch (type) - { + switch (type) { case 0: if (!doStored()) return false; @@ -790,31 +722,24 @@ bool Inflater::inflate(std::vector<unsigned char> &destination, default: error("Unknown block type %d", type); return false; - } + } if (last) break; - } + } destination = dest; return true; } - - - - - //######################################################################## //# D E F L A T E R //######################################################################## - #define DEFLATER_BUF_SIZE 32768 class Deflater { public: - /** * */ @@ -848,25 +773,23 @@ public: /** * */ - bool deflate(std::vector<unsigned char> &dest, - const std::vector<unsigned char> &src); + bool deflate(std::vector<unsigned char> &dest, const std::vector<unsigned char> &src); void encodeDistStatic(unsigned int len, unsigned int dist); private: - - //debug messages + // debug messages void error(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; +#ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) +#endif + ; void trace(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; +#ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) +#endif + ; bool compressWindow(); @@ -898,16 +821,14 @@ private: void encodeLiteralStatic(unsigned int ch); unsigned char windowBuf[DEFLATER_BUF_SIZE]; - //assume 32-bit ints + // assume 32-bit ints unsigned int windowHashBuf[DEFLATER_BUF_SIZE]; }; - //######################################################################## //# A P I //######################################################################## - /** * */ @@ -919,8 +840,7 @@ Deflater::Deflater() /** * */ -Deflater::~Deflater() -= default; +Deflater::~Deflater() = default; /** * @@ -930,13 +850,12 @@ void Deflater::reset() compressed.clear(); uncompressed.clear(); window.clear(); - windowPos = 0; + windowPos = 0; outputBitBuf = 0; outputNrBits = 0; - for (int k=0; k<DEFLATER_BUF_SIZE; k++) - { - windowBuf[k]=0; - windowHashBuf[k]=0; + for (int k = 0; k < DEFLATER_BUF_SIZE; k++) { + windowBuf[k] = 0; + windowHashBuf[k] = 0; } } @@ -965,12 +884,10 @@ std::vector<unsigned char> &Deflater::getCompressed() return compressed; } - /** * */ -bool Deflater::deflate(std::vector<unsigned char> &dest, - const std::vector<unsigned char> &src) +bool Deflater::deflate(std::vector<unsigned char> &dest, const std::vector<unsigned char> &src) { reset(); uncompressed = src; @@ -980,17 +897,10 @@ bool Deflater::deflate(std::vector<unsigned char> &dest, return true; } - - - - - - //######################################################################## //# W O R K I N G C O D E //######################################################################## - //############################# //# M E S S A G E S //############################# @@ -1021,9 +931,6 @@ void Deflater::trace(char const *fmt, ...) va_end(args); } - - - //############################# //# O U T P U T //############################# @@ -1043,8 +950,8 @@ void Deflater::put(int ch) */ void Deflater::putWord(int ch) { - int lo = (ch ) & 0xff; - int hi = (ch>>8) & 0xff; + int lo = (ch)&0xff; + int hi = (ch >> 8) & 0xff; put(lo); put(hi); } @@ -1054,10 +961,9 @@ void Deflater::putWord(int ch) */ void Deflater::putFlush() { - if (outputNrBits > 0) - { + if (outputNrBits > 0) { put(outputBitBuf & 0xff); - } + } outputBitBuf = 0; outputNrBits = 0; } @@ -1067,83 +973,65 @@ void Deflater::putFlush() */ void Deflater::putBits(unsigned int ch, unsigned int bitsWanted) { - //trace("n:%4u, %d\n", ch, bitsWanted); + // trace("n:%4u, %d\n", ch, bitsWanted); - while (bitsWanted--) - { - //add bits to position 7. shift right - outputBitBuf = (outputBitBuf>>1) + (ch<<7 & 0x80); + while (bitsWanted--) { + // add bits to position 7. shift right + outputBitBuf = (outputBitBuf >> 1) + (ch << 7 & 0x80); ch >>= 1; outputNrBits++; - if (outputNrBits >= 8) - { + if (outputNrBits >= 8) { unsigned char b = outputBitBuf & 0xff; - //printf("b:%02x\n", b); + // printf("b:%02x\n", b); put(b); - } } + } } static unsigned int bitReverse(unsigned int code, unsigned int nrBits) { unsigned int outb = 0; - while (nrBits--) - { + while (nrBits--) { outb = (outb << 1) | (code & 0x01); code >>= 1; - } + } return outb; } - /** * */ void Deflater::putBitsR(unsigned int ch, unsigned int bitsWanted) { - //trace("r:%4u, %d", ch, bitsWanted); + // trace("r:%4u, %d", ch, bitsWanted); unsigned int rcode = bitReverse(ch, bitsWanted); putBits(rcode, bitsWanted); - } - //############################# //# E N C O D E //############################# - - void Deflater::encodeLiteralStatic(unsigned int ch) { - //trace("c: %d", ch); - - if (ch < 144) - { - putBitsR(ch + 0x0030 , 8); // 00110000 - } - else if (ch < 256) - { - putBitsR(ch - 144 + 0x0190 , 9); // 110010000 - } - else if (ch < 280) - { - putBitsR(ch - 256 + 0x0000 , 7); // 0000000 - } - else if (ch < 288) - { - putBitsR(ch - 280 + 0x00c0 , 8); // 11000000 - } - else //out of range - { + // trace("c: %d", ch); + + if (ch < 144) { + putBitsR(ch + 0x0030, 8); // 00110000 + } else if (ch < 256) { + putBitsR(ch - 144 + 0x0190, 9); // 110010000 + } else if (ch < 280) { + putBitsR(ch - 256 + 0x0000, 7); // 0000000 + } else if (ch < 288) { + putBitsR(ch - 280 + 0x00c0, 8); // 11000000 + } else // out of range + { error("Literal out of range: %d", ch); - } - + } } - struct LenBase { unsigned int base; @@ -1151,8 +1039,7 @@ struct LenBase unsigned int bits; }; -LenBase lenBases[] = -{ +LenBase lenBases[] = { // clang-format off { 3, 1, 0 }, { 4, 1, 0 }, @@ -1193,8 +1080,7 @@ struct DistBase unsigned int bits; }; -DistBase distBases[] = -{ +DistBase distBases[] = { // clang-format off { 1, 1, 0 }, { 2, 1, 0 }, @@ -1231,74 +1117,63 @@ DistBase distBases[] = void Deflater::encodeDistStatic(unsigned int len, unsigned int dist) { - //## Output length - if (len < 3 || len > 258) - { + if (len < 3 || len > 258) { error("Length out of range:%d", len); return; - } + } bool found = false; - for (int i=0 ; i<29 ; i++) - { - unsigned int base = lenBases[i].base; + for (int i = 0; i < 29; i++) { + unsigned int base = lenBases[i].base; unsigned int range = lenBases[i].range; - if (base + range > len) - { + if (base + range > len) { unsigned int lenCode = 257 + i; - unsigned int length = len - base; - //trace("--- %d %d %d %d", len, base, range, length); + unsigned int length = len - base; + // trace("--- %d %d %d %d", len, base, range, length); encodeLiteralStatic(lenCode); putBits(length, lenBases[i].bits); found = true; break; - } } - if (!found) - { + } + if (!found) { error("Length not found in table:%d", len); return; - } + } //## Output distance - if (dist < 4 || dist > 32768) - { + if (dist < 4 || dist > 32768) { error("Distance out of range:%d", dist); return; - } + } found = false; - for (int i=0 ; i<30 ; i++) - { - unsigned int base = distBases[i].base; + for (int i = 0; i < 30; i++) { + unsigned int base = distBases[i].base; unsigned int range = distBases[i].range; - if (base + range > dist) - { + if (base + range > dist) { unsigned int distCode = i; unsigned int distance = dist - base; - //error("--- %d %d %d %d", dist, base, range, distance); + // error("--- %d %d %d %d", dist, base, range, distance); putBitsR(distCode, 5); putBits(distance, distBases[i].bits); found = true; break; - } } - if (!found) - { + } + if (!found) { error("Distance not found in table:%d", dist); return; - } + } } - //############################# //# C O M P R E S S //############################# - /** * This method does the dirty work of dictionary * compression. Basically it looks for redundant @@ -1312,54 +1187,46 @@ bool Deflater::compressWindow() //### Compress as much of the window as possible unsigned int hash = 0; - //Have each value be a long with the byte at this position, - //plus the 3 bytes after it in the window - for (int i=windowSize-1 ; i>=0 ; i--) - { + // Have each value be a long with the byte at this position, + // plus the 3 bytes after it in the window + for (int i = windowSize - 1; i >= 0; i--) { unsigned char ch = window[i]; windowBuf[i] = ch; - hash = ((hash<<8) & 0xffffff00) | ch; + hash = ((hash << 8) & 0xffffff00) | ch; windowHashBuf[i] = hash; - } + } - while (windowPos < windowSize - 3) - { + while (windowPos < windowSize - 3) { //### Find best match, if any - unsigned int bestMatchLen = 0; + unsigned int bestMatchLen = 0; unsigned int bestMatchDist = 0; - if (windowPos >= 4) - { - for (unsigned int lookBack=0 ; lookBack<windowPos-4 ; lookBack++) - { - //Check 4-char hashes first, before continuing with string - if (windowHashBuf[lookBack] == windowHashBuf[windowPos]) - { - unsigned int lookAhead=4; + if (windowPos >= 4) { + for (unsigned int lookBack = 0; lookBack < windowPos - 4; lookBack++) { + // Check 4-char hashes first, before continuing with string + if (windowHashBuf[lookBack] == windowHashBuf[windowPos]) { + unsigned int lookAhead = 4; unsigned int lookAheadMax = windowSize - 4 - windowPos; - if (lookBack + lookAheadMax >= windowPos -4 ) + if (lookBack + lookAheadMax >= windowPos - 4) lookAheadMax = windowPos - 4 - lookBack; if (lookAheadMax > 258) lookAheadMax = 258; - unsigned char *wp = &(windowBuf[windowPos+4]); - unsigned char *lb = &(windowBuf[lookBack+4]); - while (lookAhead<lookAheadMax) - { + unsigned char *wp = &(windowBuf[windowPos + 4]); + unsigned char *lb = &(windowBuf[lookBack + 4]); + while (lookAhead < lookAheadMax) { if (*lb++ != *wp++) break; lookAhead++; - } - if (lookAhead > bestMatchLen) - { - bestMatchLen = lookAhead; + } + if (lookAhead > bestMatchLen) { + bestMatchLen = lookAhead; bestMatchDist = windowPos - lookBack; - } } } } - if (bestMatchLen > 3) - { - //Distance encode - //trace("### distance"); + } + if (bestMatchLen > 3) { + // Distance encode + // trace("### distance"); /* printf("### 1 '"); for (int i=0 ; i < bestMatchLen ; i++) @@ -1371,15 +1238,13 @@ bool Deflater::compressWindow() */ encodeDistStatic(bestMatchLen, bestMatchDist); windowPos += bestMatchLen; - } - else - { - //Literal encode - //trace("### literal"); + } else { + // Literal encode + // trace("### literal"); encodeLiteralStatic(windowBuf[windowPos]); windowPos++; - } } + } while (windowPos < windowSize) encodeLiteralStatic(windowBuf[windowPos++]); @@ -1388,44 +1253,37 @@ bool Deflater::compressWindow() return true; } - /** * */ bool Deflater::compress() { - //trace("compress"); + // trace("compress"); unsigned long total = 0L; windowPos = 0; std::vector<unsigned char>::iterator iter; - for (iter = uncompressed.begin(); iter != uncompressed.end() ; ) - { + for (iter = uncompressed.begin(); iter != uncompressed.end();) { total += windowPos; trace("total:%ld", total); if (windowPos > window.size()) windowPos = window.size(); - window.erase(window.begin() , window.begin()+windowPos); - while (window.size() < 32768 && iter != uncompressed.end()) - { + window.erase(window.begin(), window.begin() + windowPos); + while (window.size() < 32768 && iter != uncompressed.end()) { window.push_back(*iter); ++iter; - } + } if (window.size() >= 32768) - putBits(0x00, 1); //0 -- more blocks + putBits(0x00, 1); // 0 -- more blocks else - putBits(0x01, 1); //1 -- last block - putBits(0x01, 2); //01 -- static trees + putBits(0x01, 1); // 1 -- last block + putBits(0x01, 2); // 01 -- static trees if (!compressWindow()) return false; - } + } putFlush(); return true; } - - - - //######################################################################## //# G Z I P F I L E //######################################################################## @@ -1433,20 +1291,18 @@ bool Deflater::compress() /** * Constructor */ -GzipFile::GzipFile() : - data(), - fileName(), - fileBuf(), - fileBufPos(0), - compressionMethod(0) -{ -} +GzipFile::GzipFile() + : data() + , fileName() + , fileBuf() + , fileBufPos(0) + , compressionMethod(0) +{} /** * Destructor */ -GzipFile::~GzipFile() -= default; +GzipFile::~GzipFile() = default; /** * Print error messages @@ -1522,8 +1378,6 @@ void GzipFile::setFileName(const std::string &val) fileName = val; } - - //##################################### //# U T I L I T Y //##################################### @@ -1533,26 +1387,22 @@ void GzipFile::setFileName(const std::string &val) */ bool GzipFile::loadFile(const std::string &fName) { - FILE *f = fopen(fName.c_str() , "rb"); - if (!f) - { + FILE *f = fopen(fName.c_str(), "rb"); + if (!f) { error("Cannot open file %s", fName.c_str()); return false; - } - while (true) - { + } + while (true) { int ch = fgetc(f); if (ch < 0) break; data.push_back(ch); - } + } fclose(f); setFileName(fName); return true; } - - //##################################### //# W R I T E //##################################### @@ -1566,22 +1416,18 @@ bool GzipFile::putByte(unsigned char ch) return true; } - - /** * */ bool GzipFile::putLong(unsigned long val) { - fileBuf.push_back( (unsigned char)((val ) & 0xff)); - fileBuf.push_back( (unsigned char)((val>> 8) & 0xff)); - fileBuf.push_back( (unsigned char)((val>>16) & 0xff)); - fileBuf.push_back( (unsigned char)((val>>24) & 0xff)); + fileBuf.push_back((unsigned char)((val)&0xff)); + fileBuf.push_back((unsigned char)((val >> 8) & 0xff)); + fileBuf.push_back((unsigned char)((val >> 16) & 0xff)); + fileBuf.push_back((unsigned char)((val >> 24) & 0xff)); return true; } - - /** * */ @@ -1589,39 +1435,36 @@ bool GzipFile::write() { fileBuf.clear(); - putByte(0x1f); //magic - putByte(0x8b); //magic - putByte( 8); //compression method - putByte(0x08); //flags. say we have a crc and file name + putByte(0x1f); // magic + putByte(0x8b); // magic + putByte(8); // compression method + putByte(0x08); // flags. say we have a crc and file name - unsigned long ltime = (unsigned long) time(nullptr); + unsigned long ltime = (unsigned long)time(nullptr); putLong(ltime); - //xfl + // xfl putByte(0); - //OS + // OS putByte(0); - //file name + // file name for (char i : fileName) putByte(i); putByte(0); - - //compress + // compress std::vector<unsigned char> compBuf; Deflater deflater; - if (!deflater.deflate(compBuf, data)) - { + if (!deflater.deflate(compBuf, data)) { return false; - } + } std::vector<unsigned char>::iterator iter; - for (iter=compBuf.begin() ; iter!=compBuf.end() ; ++iter) - { + for (iter = compBuf.begin(); iter != compBuf.end(); ++iter) { unsigned char ch = *iter; putByte(ch); - } + } Crc32 crcEngine; crcEngine.update(data); @@ -1633,7 +1476,6 @@ bool GzipFile::write() return true; } - /** * */ @@ -1646,7 +1488,6 @@ bool GzipFile::writeBuffer(std::vector<unsigned char> &outBuf) return true; } - /** * */ @@ -1658,27 +1499,24 @@ bool GzipFile::writeFile(const std::string &fileName) if (!f) return false; std::vector<unsigned char>::iterator iter; - for (iter=fileBuf.begin() ; iter!=fileBuf.end() ; ++iter) - { + for (iter = fileBuf.begin(); iter != fileBuf.end(); ++iter) { unsigned char ch = *iter; fputc(ch, f); - } + } fclose(f); return true; } - //##################################### //# R E A D //##################################### bool GzipFile::getByte(unsigned char *ch) { - if (fileBufPos >= fileBuf.size()) - { + if (fileBufPos >= fileBuf.size()) { error("unexpected end of data"); return false; - } + } *ch = fileBuf[fileBufPos++]; return true; } @@ -1694,10 +1532,7 @@ bool GzipFile::getLong(unsigned long *val) int ch2 = fileBuf[fileBufPos++]; int ch3 = fileBuf[fileBufPos++]; int ch4 = fileBuf[fileBufPos++]; - *val = ((ch4<<24) & 0xff000000L) | - ((ch3<<16) & 0x00ff0000L) | - ((ch2<< 8) & 0x0000ff00L) | - ((ch1 ) & 0x000000ffL); + *val = ((ch4 << 24) & 0xff000000L) | ((ch3 << 16) & 0x00ff0000L) | ((ch2 << 8) & 0x0000ff00L) | ((ch1)&0x000000ffL); return true; } @@ -1707,21 +1542,19 @@ bool GzipFile::read() unsigned char ch; - //magic cookie + // magic cookie if (!getByte(&ch)) return false; - if (ch != 0x1f) - { + if (ch != 0x1f) { error("bad gzip header"); return false; - } + } if (!getByte(&ch)) return false; - if (ch != 0x8b) - { + if (ch != 0x8b) { error("bad gzip header"); return false; - } + } //## compression method if (!getByte(&ch)) @@ -1731,128 +1564,113 @@ bool GzipFile::read() //## flags if (!getByte(&ch)) return false; - //bool ftext = ch & 0x01; - bool fhcrc = ch & 0x02; - bool fextra = ch & 0x04; - bool fname = ch & 0x08; + // bool ftext = ch & 0x01; + bool fhcrc = ch & 0x02; + bool fextra = ch & 0x04; + bool fname = ch & 0x08; bool fcomment = ch & 0x10; - //trace("cm:%d ftext:%d fhcrc:%d fextra:%d fname:%d fcomment:%d", + // trace("cm:%d ftext:%d fhcrc:%d fextra:%d fname:%d fcomment:%d", // cm, ftext, fhcrc, fextra, fname, fcomment); //## file time unsigned long ltime; if (!getLong(<ime)) return false; - //time_t mtime = (time_t)ltime; + // time_t mtime = (time_t)ltime; //## XFL if (!getByte(&ch)) return false; - //int xfl = ch; + // int xfl = ch; //## OS if (!getByte(&ch)) return false; - //int os = ch; + // int os = ch; - //std::string timestr = ctime(&mtime); - //trace("xfl:%d os:%d mtime:%s", xfl, os, timestr.c_str()); + // std::string timestr = ctime(&mtime); + // trace("xfl:%d os:%d mtime:%s", xfl, os, timestr.c_str()); - if (fextra) - { + if (fextra) { if (!getByte(&ch)) return false; long xlen = ch; if (!getByte(&ch)) return false; xlen = (xlen << 8) + ch; - for (long l=0 ; l<xlen ; l++) - { + for (long l = 0; l < xlen; l++) { if (!getByte(&ch)) return false; - } } + } - if (fname) - { + if (fname) { fileName = ""; - while (true) - { + while (true) { if (!getByte(&ch)) return false; - if (ch==0) + if (ch == 0) break; fileName.push_back(ch); - } } + } - if (fcomment) - { - while (true) - { + if (fcomment) { + while (true) { if (!getByte(&ch)) return false; - if (ch==0) + if (ch == 0) break; - } } + } - if (fhcrc) - { + if (fhcrc) { if (!getByte(&ch)) return false; if (!getByte(&ch)) return false; - } + } - //read remainder of stream - //compressed data runs up until 8 bytes before end of buffer + // read remainder of stream + // compressed data runs up until 8 bytes before end of buffer std::vector<unsigned char> compBuf; - while (fileBufPos < fileBuf.size() - 8) - { + while (fileBufPos < fileBuf.size() - 8) { if (!getByte(&ch)) return false; compBuf.push_back(ch); - } - //uncompress + } + // uncompress data.clear(); Inflater inflater; - if (!inflater.inflate(data, compBuf)) - { + if (!inflater.inflate(data, compBuf)) { return false; - } + } - //Get the CRC and compare + // Get the CRC and compare Crc32 crcEngine; crcEngine.update(data); unsigned long calcCrc = crcEngine.getValue(); unsigned long givenCrc; if (!getLong(&givenCrc)) return false; - if (givenCrc != calcCrc) - { - error("Specified crc, %ud, not what received: %ud", - givenCrc, calcCrc); + if (givenCrc != calcCrc) { + error("Specified crc, %ud, not what received: %ud", givenCrc, calcCrc); return false; - } + } - //Get the file size and compare + // Get the file size and compare unsigned long givenFileSize; if (!getLong(&givenFileSize)) return false; - if (givenFileSize != data.size()) - { - error("Specified data size, %ld, not what received: %ld", - givenFileSize, data.size()); + if (givenFileSize != data.size()) { + error("Specified data size, %ld, not what received: %ld", givenFileSize, data.size()); return false; - } + } return true; } - - /** * */ @@ -1864,7 +1682,6 @@ bool GzipFile::readBuffer(const std::vector<unsigned char> &inbuf) return true; } - /** * */ @@ -1874,26 +1691,18 @@ bool GzipFile::readFile(const std::string &fileName) FILE *f = fopen(fileName.c_str(), "rb"); if (!f) return false; - while (true) - { + while (true) { int ch = fgetc(f); if (ch < 0) break; fileBuf.push_back(ch); - } + } fclose(f); if (!read()) return false; return true; } - - - - - - - //######################################################################## //# Z I P F I L E //######################################################################## @@ -1901,38 +1710,33 @@ bool GzipFile::readFile(const std::string &fileName) /** * Constructor */ -ZipEntry::ZipEntry() : - crc (0L), - fileName (), - comment (), - compressionMethod (8), - compressedData (), - uncompressedData (), - position (0) -{ -} +ZipEntry::ZipEntry() + : crc(0L) + , fileName() + , comment() + , compressionMethod(8) + , compressedData() + , uncompressedData() + , position(0) +{} /** * */ -ZipEntry::ZipEntry(std::string fileNameArg, - std::string commentArg) : - crc (0L), - fileName (std::move(fileNameArg)), - comment (std::move(commentArg)), - compressionMethod (8), - compressedData (), - uncompressedData (), - position (0) -{ -} +ZipEntry::ZipEntry(std::string fileNameArg, std::string commentArg) + : crc(0L) + , fileName(std::move(fileNameArg)) + , comment(std::move(commentArg)) + , compressionMethod(8) + , compressedData() + , uncompressedData() + , position(0) +{} /** * Destructor */ -ZipEntry::~ZipEntry() -= default; - +ZipEntry::~ZipEntry() = default; /** * @@ -2068,73 +1872,58 @@ void ZipEntry::finish() { Crc32 c32; std::vector<unsigned char>::iterator iter; - for (iter = uncompressedData.begin() ; - iter!= uncompressedData.end() ; ++iter) - { + for (iter = uncompressedData.begin(); iter != uncompressedData.end(); ++iter) { unsigned char ch = *iter; c32.update(ch); - } + } crc = c32.getValue(); - switch (compressionMethod) + switch (compressionMethod) { + case 0: // none { - case 0: //none - { - for (iter = uncompressedData.begin() ; - iter!= uncompressedData.end() ; ++iter) - { + for (iter = uncompressedData.begin(); iter != uncompressedData.end(); ++iter) { unsigned char ch = *iter; compressedData.push_back(ch); - } - break; } - case 8: //deflate - { - Deflater deflater; - if (!deflater.deflate(compressedData, uncompressedData)) - { - //some error - } break; + } + case 8: // deflate + { + Deflater deflater; + if (!deflater.deflate(compressedData, uncompressedData)) { + // some error } - default: - { - printf("error: unknown compression method %d\n", - compressionMethod); - } + break; + } + default: { + printf("error: unknown compression method %d\n", compressionMethod); } + } } - - - /** * */ -bool ZipEntry::readFile(const std::string &fileNameArg, - const std::string &commentArg) +bool ZipEntry::readFile(const std::string &fileNameArg, const std::string &commentArg) { crc = 0L; uncompressedData.clear(); fileName = fileNameArg; - comment = commentArg; + comment = commentArg; FILE *f = fopen(fileName.c_str(), "rb"); - if (!f) - { + if (!f) { return false; - } - while (true) - { + } + while (true) { int ch = fgetc(f); if (ch < 0) break; uncompressedData.push_back((unsigned char)ch); - } + } fclose(f); finish(); return true; } - /** * */ @@ -2151,22 +1940,15 @@ unsigned long ZipEntry::getPosition() return position; } - - - - - - /** * Constructor */ -ZipFile::ZipFile() : - entries(), - fileBuf(), - fileBufPos(0), - comment() -{ -} +ZipFile::ZipFile() + : entries() + , fileBuf() + , fileBufPos(0) + , comment() +{} /** * Destructor @@ -2174,11 +1956,10 @@ ZipFile::ZipFile() : ZipFile::~ZipFile() { std::vector<ZipEntry *>::iterator iter; - for (iter=entries.begin() ; iter!=entries.end() ; ++iter) - { + for (iter = entries.begin(); iter != entries.end(); ++iter) { ZipEntry *entry = *iter; delete entry; - } + } entries.clear(); } @@ -2198,7 +1979,6 @@ std::string ZipFile::getComment() return comment; } - /** * */ @@ -2207,8 +1987,6 @@ std::vector<ZipEntry *> &ZipFile::getEntries() return entries; } - - //##################################### //# M E S S A G E S //##################################### @@ -2240,32 +2018,27 @@ void ZipFile::trace(char const *fmt, ...) /** * */ -ZipEntry *ZipFile::addFile(const std::string &fileName, - const std::string &comment) +ZipEntry *ZipFile::addFile(const std::string &fileName, const std::string &comment) { ZipEntry *ze = new ZipEntry(); - if (!ze->readFile(fileName, comment)) - { + if (!ze->readFile(fileName, comment)) { delete ze; return nullptr; - } + } entries.push_back(ze); return ze; } - /** * */ -ZipEntry *ZipFile::newEntry(const std::string &fileName, - const std::string &comment) +ZipEntry *ZipFile::newEntry(const std::string &fileName, const std::string &comment) { ZipEntry *ze = new ZipEntry(fileName, comment); entries.push_back(ze); return ze; } - //##################################### //# W R I T E //##################################### @@ -2275,21 +2048,20 @@ ZipEntry *ZipFile::newEntry(const std::string &fileName, */ bool ZipFile::putLong(unsigned long val) { - fileBuf.push_back( ((int)(val )) & 0xff); - fileBuf.push_back( ((int)(val>> 8)) & 0xff); - fileBuf.push_back( ((int)(val>>16)) & 0xff); - fileBuf.push_back( ((int)(val>>24)) & 0xff); + fileBuf.push_back(((int)(val)) & 0xff); + fileBuf.push_back(((int)(val >> 8)) & 0xff); + fileBuf.push_back(((int)(val >> 16)) & 0xff); + fileBuf.push_back(((int)(val >> 24)) & 0xff); return true; } - /** * */ bool ZipFile::putInt(unsigned int val) { - fileBuf.push_back( (val ) & 0xff); - fileBuf.push_back( (val>> 8) & 0xff); + fileBuf.push_back((val)&0xff); + fileBuf.push_back((val >> 8) & 0xff); return true; } @@ -2308,28 +2080,27 @@ bool ZipFile::putByte(unsigned char val) bool ZipFile::writeFileData() { std::vector<ZipEntry *>::iterator iter; - for (iter = entries.begin() ; iter != entries.end() ; ++iter) - { + for (iter = entries.begin(); iter != entries.end(); ++iter) { ZipEntry *entry = *iter; entry->setPosition(fileBuf.size()); //##### HEADER std::string fname = entry->getFileName(); putLong(0x04034b50L); - putInt(20); //versionNeeded - putInt(0); //gpBitFlag - //putInt(0); //compression method - putInt(entry->getCompressionMethod()); //compression method - putInt(0); //mod time - putInt(0); //mod date - putLong(entry->getCrc()); //crc32 + putInt(20); // versionNeeded + putInt(0); // gpBitFlag + // putInt(0); //compression method + putInt(entry->getCompressionMethod()); // compression method + putInt(0); // mod time + putInt(0); // mod date + putLong(entry->getCrc()); // crc32 putLong(entry->getCompressedSize()); putLong(entry->getUncompressedSize()); - putInt(fname.size());//fileName length - putInt(8);//extra field length - //file name + putInt(fname.size()); // fileName length + putInt(8); // extra field length + // file name for (char i : fname) putByte((unsigned char)i); - //extra field + // extra field putInt(0x7855); putInt(4); putInt(100); @@ -2338,12 +2109,11 @@ bool ZipFile::writeFileData() //##### DATA std::vector<unsigned char> &buf = entry->getCompressedData(); std::vector<unsigned char>::iterator iter; - for (iter = buf.begin() ; iter != buf.end() ; ++iter) - { - unsigned char ch = (unsigned char) *iter; + for (iter = buf.begin(); iter != buf.end(); ++iter) { + unsigned char ch = (unsigned char)*iter; putByte(ch); - } } + } return true; } @@ -2354,56 +2124,53 @@ bool ZipFile::writeCentralDirectory() { unsigned long cdPosition = fileBuf.size(); std::vector<ZipEntry *>::iterator iter; - for (iter = entries.begin() ; iter != entries.end() ; ++iter) - { + for (iter = entries.begin(); iter != entries.end(); ++iter) { ZipEntry *entry = *iter; - std::string fname = entry->getFileName(); + std::string fname = entry->getFileName(); std::string ecomment = entry->getComment(); - putLong(0x02014b50L); //magic cookie - putInt(2386); //versionMadeBy - putInt(20); //versionNeeded - putInt(0); //gpBitFlag - putInt(entry->getCompressionMethod()); //compression method - putInt(0); //mod time - putInt(0); //mod date - putLong(entry->getCrc()); //crc32 + putLong(0x02014b50L); // magic cookie + putInt(2386); // versionMadeBy + putInt(20); // versionNeeded + putInt(0); // gpBitFlag + putInt(entry->getCompressionMethod()); // compression method + putInt(0); // mod time + putInt(0); // mod date + putLong(entry->getCrc()); // crc32 putLong(entry->getCompressedSize()); putLong(entry->getUncompressedSize()); - putInt(fname.size());//fileName length - putInt(4);//extra field length - putInt(ecomment.size());//comment length - putInt(0); //disk number start - putInt(0); //internal attributes - putLong(0); //external attributes + putInt(fname.size()); // fileName length + putInt(4); // extra field length + putInt(ecomment.size()); // comment length + putInt(0); // disk number start + putInt(0); // internal attributes + putLong(0); // external attributes putLong(entry->getPosition()); - //file name + // file name for (char i : fname) putByte((unsigned char)i); - //extra field + // extra field putInt(0x7855); putInt(0); - //comment + // comment for (char i : ecomment) putByte((unsigned char)i); - } + } unsigned long cdSize = fileBuf.size() - cdPosition; putLong(0x06054b50L); - putInt(0);//number of this disk - putInt(0);//nr of disk with central dir - putInt(entries.size()); //number of entries on this disk - putInt(entries.size()); //number of entries total - putLong(cdSize); //size of central dir - putLong(cdPosition); //position of central dir - putInt(comment.size());//comment size + putInt(0); // number of this disk + putInt(0); // nr of disk with central dir + putInt(entries.size()); // number of entries on this disk + putInt(entries.size()); // number of entries total + putLong(cdSize); // size of central dir + putLong(cdPosition); // position of central dir + putInt(comment.size()); // comment size for (char i : comment) putByte(i); return true; } - - /** * */ @@ -2417,7 +2184,6 @@ bool ZipFile::write() return true; } - /** * */ @@ -2430,7 +2196,6 @@ bool ZipFile::writeBuffer(std::vector<unsigned char> &outBuf) return true; } - /** * */ @@ -2442,11 +2207,10 @@ bool ZipFile::writeFile(const std::string &fileName) if (!f) return false; std::vector<unsigned char>::iterator iter; - for (iter=fileBuf.begin() ; iter!=fileBuf.end() ; ++iter) - { + for (iter = fileBuf.begin(); iter != fileBuf.end(); ++iter) { unsigned char ch = *iter; fputc(ch, f); - } + } fclose(f); return true; } @@ -2466,10 +2230,7 @@ bool ZipFile::getLong(unsigned long *val) int ch2 = fileBuf[fileBufPos++]; int ch3 = fileBuf[fileBufPos++]; int ch4 = fileBuf[fileBufPos++]; - *val = ((ch4<<24) & 0xff000000L) | - ((ch3<<16) & 0x00ff0000L) | - ((ch2<< 8) & 0x0000ff00L) | - ((ch1 ) & 0x000000ffL); + *val = ((ch4 << 24) & 0xff000000L) | ((ch3 << 16) & 0x00ff0000L) | ((ch2 << 8) & 0x0000ff00L) | ((ch1)&0x000000ffL); return true; } @@ -2482,12 +2243,10 @@ bool ZipFile::getInt(unsigned int *val) return false; int ch1 = fileBuf[fileBufPos++]; int ch2 = fileBuf[fileBufPos++]; - *val = ((ch2<< 8) & 0xff00) | - ((ch1 ) & 0x00ff); + *val = ((ch2 << 8) & 0xff00) | ((ch1)&0x00ff); return true; } - /** * */ @@ -2499,165 +2258,145 @@ bool ZipFile::getByte(unsigned char *val) return true; } - /** * */ bool ZipFile::readFileData() { - //printf("#################################################\n"); - //printf("###D A T A\n"); - //printf("#################################################\n"); - while (true) - { + // printf("#################################################\n"); + // printf("###D A T A\n"); + // printf("#################################################\n"); + while (true) { unsigned long magicCookie; - if (!getLong(&magicCookie)) - { + if (!getLong(&magicCookie)) { error("magic cookie not found"); break; - } + } trace("###Cookie:%lx", magicCookie); - if (magicCookie == 0x02014b50L) //central directory + if (magicCookie == 0x02014b50L) // central directory break; - if (magicCookie != 0x04034b50L) - { + if (magicCookie != 0x04034b50L) { error("file header not found"); return false; - } + } unsigned int versionNeeded; - if (!getInt(&versionNeeded)) - { + if (!getInt(&versionNeeded)) { error("bad version needed found"); return false; - } + } unsigned int gpBitFlag; - if (!getInt(&gpBitFlag)) - { + if (!getInt(&gpBitFlag)) { error("bad bit flag found"); return false; - } + } unsigned int compressionMethod; - if (!getInt(&compressionMethod)) - { + if (!getInt(&compressionMethod)) { error("bad compressionMethod found"); return false; - } + } unsigned int modTime; - if (!getInt(&modTime)) - { + if (!getInt(&modTime)) { error("bad modTime found"); return false; - } + } unsigned int modDate; - if (!getInt(&modDate)) - { + if (!getInt(&modDate)) { error("bad modDate found"); return false; - } + } unsigned long crc32; - if (!getLong(&crc32)) - { + if (!getLong(&crc32)) { error("bad crc32 found"); return false; - } + } unsigned long compressedSize; - if (!getLong(&compressedSize)) - { + if (!getLong(&compressedSize)) { error("bad compressedSize found"); return false; - } + } unsigned long uncompressedSize; - if (!getLong(&uncompressedSize)) - { + if (!getLong(&uncompressedSize)) { error("bad uncompressedSize found"); return false; - } + } unsigned int fileNameLength; - if (!getInt(&fileNameLength)) - { + if (!getInt(&fileNameLength)) { error("bad fileNameLength found"); return false; - } + } unsigned int extraFieldLength; - if (!getInt(&extraFieldLength)) - { + if (!getInt(&extraFieldLength)) { error("bad extraFieldLength found"); return false; - } + } std::string fileName; - for (unsigned int i=0 ; i<fileNameLength ; i++) - { + for (unsigned int i = 0; i < fileNameLength; i++) { unsigned char ch; if (!getByte(&ch)) break; fileName.push_back(ch); - } + } std::string extraField; - for (unsigned int i=0 ; i<extraFieldLength ; i++) - { + for (unsigned int i = 0; i < extraFieldLength; i++) { unsigned char ch; if (!getByte(&ch)) break; extraField.push_back(ch); - } + } trace("######################### DATA"); - trace("FileName :%d:%s" , fileName.size(), fileName.c_str()); - trace("Extra field :%d:%s" , extraField.size(), extraField.c_str()); - trace("Version needed :%d" , versionNeeded); - trace("Bitflag :%d" , gpBitFlag); - trace("Compression Method :%d" , compressionMethod); - trace("Mod time :%d" , modTime); - trace("Mod date :%d" , modDate); + trace("FileName :%d:%s", fileName.size(), fileName.c_str()); + trace("Extra field :%d:%s", extraField.size(), extraField.c_str()); + trace("Version needed :%d", versionNeeded); + trace("Bitflag :%d", gpBitFlag); + trace("Compression Method :%d", compressionMethod); + trace("Mod time :%d", modTime); + trace("Mod date :%d", modDate); trace("CRC :%lx", crc32); trace("Compressed size :%ld", compressedSize); trace("Uncompressed size :%ld", uncompressedSize); //#### Uncompress the data std::vector<unsigned char> compBuf; - if (gpBitFlag & 0x8)//bit 3 was set. means we don't know compressed size - { + if (gpBitFlag & 0x8) // bit 3 was set. means we don't know compressed size + { unsigned char c1, c2, c3, c4; c2 = c3 = c4 = 0; - while (true) - { + while (true) { unsigned char ch; - if (!getByte(&ch)) - { + if (!getByte(&ch)) { error("premature end of data"); break; - } + } compBuf.push_back(ch); - c1 = c2; c2 = c3; c3 = c4; c4 = ch; - if (c1 == 0x50 && c2 == 0x4b && c3 == 0x07 && c4 == 0x08) - { + c1 = c2; + c2 = c3; + c3 = c4; + c4 = ch; + if (c1 == 0x50 && c2 == 0x4b && c3 == 0x07 && c4 == 0x08) { trace("found end of compressed data"); - //remove the cookie - compBuf.erase(compBuf.end() -4, compBuf.end()); + // remove the cookie + compBuf.erase(compBuf.end() - 4, compBuf.end()); break; - } } } - else - { - for (unsigned long bnr = 0 ; bnr < compressedSize ; bnr++) - { + } else { + for (unsigned long bnr = 0; bnr < compressedSize; bnr++) { unsigned char ch; - if (!getByte(&ch)) - { + if (!getByte(&ch)) { error("premature end of data"); break; - } - compBuf.push_back(ch); } + compBuf.push_back(ch); } + } printf("### data: "); - for (int i=0 ; i<10 ; i++) + for (int i = 0; i < 10; i++) printf("%02x ", compBuf[i] & 0xff); printf("\n"); - if (gpBitFlag & 0x8)//only if bit 3 set - { + if (gpBitFlag & 0x8) // only if bit 3 set + { /* this cookie was read in the loop above unsigned long dataDescriptorSignature ; if (!getLong(&dataDescriptorSignature)) @@ -2669,60 +2408,51 @@ bool ZipFile::readFileData() } */ unsigned long crc32; - if (!getLong(&crc32)) - { + if (!getLong(&crc32)) { error("bad crc32 found"); return false; - } + } unsigned long compressedSize; - if (!getLong(&compressedSize)) - { + if (!getLong(&compressedSize)) { error("bad compressedSize found"); return false; - } + } unsigned long uncompressedSize; - if (!getLong(&uncompressedSize)) - { + if (!getLong(&uncompressedSize)) { error("bad uncompressedSize found"); return false; - } - }//bit 3 was set - //break; + } + } // bit 3 was set + // break; std::vector<unsigned char> uncompBuf; - switch (compressionMethod) + switch (compressionMethod) { + case 8: // deflate { - case 8: //deflate - { Inflater inflater; - if (!inflater.inflate(uncompBuf, compBuf)) - { + if (!inflater.inflate(uncompBuf, compBuf)) { return false; - } - break; } - default: - { + break; + } + default: { error("Unimplemented compression method %d", compressionMethod); return false; - } } + } - if (uncompressedSize != uncompBuf.size()) - { - error("Size mismatch. Expected %ld, received %ld", - uncompressedSize, uncompBuf.size()); + if (uncompressedSize != uncompBuf.size()) { + error("Size mismatch. Expected %ld, received %ld", uncompressedSize, uncompBuf.size()); return false; - } + } Crc32 crcEngine; crcEngine.update(uncompBuf); unsigned long crc = crcEngine.getValue(); - if (crc != crc32) - { + if (crc != crc32) { error("Crc mismatch. Calculated %08ux, received %08ux", crc, crc32); return false; - } + } ZipEntry *ze = new ZipEntry(fileName, comment); ze->setCompressionMethod(compressionMethod); @@ -2730,267 +2460,228 @@ bool ZipFile::readFileData() ze->setUncompressedData(uncompBuf); ze->setCrc(crc); entries.push_back(ze); - - - } + } return true; } - /** * */ bool ZipFile::readCentralDirectory() { - //printf("#################################################\n"); - //printf("###D I R E C T O R Y\n"); - //printf("#################################################\n"); - while (true) - { - //We start with a central directory cookie already - //Check at the bottom of the loop. + // printf("#################################################\n"); + // printf("###D I R E C T O R Y\n"); + // printf("#################################################\n"); + while (true) { + // We start with a central directory cookie already + // Check at the bottom of the loop. unsigned int version; - if (!getInt(&version)) - { + if (!getInt(&version)) { error("bad version found"); return false; - } + } unsigned int versionNeeded; - if (!getInt(&versionNeeded)) - { + if (!getInt(&versionNeeded)) { error("bad version found"); return false; - } + } unsigned int gpBitFlag; - if (!getInt(&gpBitFlag)) - { + if (!getInt(&gpBitFlag)) { error("bad bit flag found"); return false; - } + } unsigned int compressionMethod; - if (!getInt(&compressionMethod)) - { + if (!getInt(&compressionMethod)) { error("bad compressionMethod found"); return false; - } + } unsigned int modTime; - if (!getInt(&modTime)) - { + if (!getInt(&modTime)) { error("bad modTime found"); return false; - } + } unsigned int modDate; - if (!getInt(&modDate)) - { + if (!getInt(&modDate)) { error("bad modDate found"); return false; - } + } unsigned long crc32; - if (!getLong(&crc32)) - { + if (!getLong(&crc32)) { error("bad crc32 found"); return false; - } + } unsigned long compressedSize; - if (!getLong(&compressedSize)) - { + if (!getLong(&compressedSize)) { error("bad compressedSize found"); return false; - } + } unsigned long uncompressedSize; - if (!getLong(&uncompressedSize)) - { + if (!getLong(&uncompressedSize)) { error("bad uncompressedSize found"); return false; - } + } unsigned int fileNameLength; - if (!getInt(&fileNameLength)) - { + if (!getInt(&fileNameLength)) { error("bad fileNameLength found"); return false; - } + } unsigned int extraFieldLength; - if (!getInt(&extraFieldLength)) - { + if (!getInt(&extraFieldLength)) { error("bad extraFieldLength found"); return false; - } + } unsigned int fileCommentLength; - if (!getInt(&fileCommentLength)) - { + if (!getInt(&fileCommentLength)) { error("bad fileCommentLength found"); return false; - } + } unsigned int diskNumberStart; - if (!getInt(&diskNumberStart)) - { + if (!getInt(&diskNumberStart)) { error("bad diskNumberStart found"); return false; - } + } unsigned int internalFileAttributes; - if (!getInt(&internalFileAttributes)) - { + if (!getInt(&internalFileAttributes)) { error("bad internalFileAttributes found"); return false; - } + } unsigned long externalFileAttributes; - if (!getLong(&externalFileAttributes)) - { + if (!getLong(&externalFileAttributes)) { error("bad externalFileAttributes found"); return false; - } + } unsigned long localHeaderOffset; - if (!getLong(&localHeaderOffset)) - { + if (!getLong(&localHeaderOffset)) { error("bad localHeaderOffset found"); return false; - } + } std::string fileName; - for (unsigned int i=0 ; i<fileNameLength ; i++) - { + for (unsigned int i = 0; i < fileNameLength; i++) { unsigned char ch; if (!getByte(&ch)) break; fileName.push_back(ch); - } + } std::string extraField; - for (unsigned int i=0 ; i<extraFieldLength ; i++) - { + for (unsigned int i = 0; i < extraFieldLength; i++) { unsigned char ch; if (!getByte(&ch)) break; extraField.push_back(ch); - } + } std::string fileComment; - for (unsigned int i=0 ; i<fileCommentLength ; i++) - { + for (unsigned int i = 0; i < fileCommentLength; i++) { unsigned char ch; if (!getByte(&ch)) break; fileComment.push_back(ch); - } + } trace("######################### ENTRY"); - trace("FileName :%s" , fileName.c_str()); - trace("Extra field :%s" , extraField.c_str()); - trace("File comment :%s" , fileComment.c_str()); - trace("Version :%d" , version); - trace("Version needed :%d" , versionNeeded); - trace("Bitflag :%d" , gpBitFlag); - trace("Compression Method :%d" , compressionMethod); - trace("Mod time :%d" , modTime); - trace("Mod date :%d" , modDate); + trace("FileName :%s", fileName.c_str()); + trace("Extra field :%s", extraField.c_str()); + trace("File comment :%s", fileComment.c_str()); + trace("Version :%d", version); + trace("Version needed :%d", versionNeeded); + trace("Bitflag :%d", gpBitFlag); + trace("Compression Method :%d", compressionMethod); + trace("Mod time :%d", modTime); + trace("Mod date :%d", modDate); trace("CRC :%lx", crc32); trace("Compressed size :%ld", compressedSize); trace("Uncompressed size :%ld", uncompressedSize); trace("Disk nr start :%ld", diskNumberStart); trace("Header offset :%ld", localHeaderOffset); - unsigned long magicCookie; - if (!getLong(&magicCookie)) - { + if (!getLong(&magicCookie)) { error("magic cookie not found"); return false; - } + } trace("###Cookie:%lx", magicCookie); - if (magicCookie == 0x06054b50L) //end of central directory + if (magicCookie == 0x06054b50L) // end of central directory break; - else if (magicCookie == 0x05054b50L) //signature - { + else if (magicCookie == 0x05054b50L) // signature + { //## Digital Signature unsigned int signatureSize; - if (!getInt(&signatureSize)) - { + if (!getInt(&signatureSize)) { error("bad signatureSize found"); return false; - } + } std::string digitalSignature; - for (unsigned int i=0 ; i<signatureSize ; i++) - { + for (unsigned int i = 0; i < signatureSize; i++) { unsigned char ch; if (!getByte(&ch)) break; digitalSignature.push_back(ch); - } - trace("######## SIGNATURE :'%s'" , digitalSignature.c_str()); } - else if (magicCookie != 0x02014b50L) //central directory - { + trace("######## SIGNATURE :'%s'", digitalSignature.c_str()); + } else if (magicCookie != 0x02014b50L) // central directory + { error("directory file header not found"); return false; - } } + } unsigned int diskNr; - if (!getInt(&diskNr)) - { + if (!getInt(&diskNr)) { error("bad diskNr found"); return false; - } + } unsigned int diskWithCd; - if (!getInt(&diskWithCd)) - { + if (!getInt(&diskWithCd)) { error("bad diskWithCd found"); return false; - } + } unsigned int nrEntriesDisk; - if (!getInt(&nrEntriesDisk)) - { + if (!getInt(&nrEntriesDisk)) { error("bad nrEntriesDisk found"); return false; - } + } unsigned int nrEntriesTotal; - if (!getInt(&nrEntriesTotal)) - { + if (!getInt(&nrEntriesTotal)) { error("bad nrEntriesTotal found"); return false; - } + } unsigned long cdSize; - if (!getLong(&cdSize)) - { + if (!getLong(&cdSize)) { error("bad cdSize found"); return false; - } + } unsigned long cdPos; - if (!getLong(&cdPos)) - { + if (!getLong(&cdPos)) { error("bad cdPos found"); return false; - } + } unsigned int commentSize; - if (!getInt(&commentSize)) - { + if (!getInt(&commentSize)) { error("bad commentSize found"); return false; - } + } comment = ""; - for (unsigned int i=0 ; i<commentSize ; i++) - { + for (unsigned int i = 0; i < commentSize; i++) { unsigned char ch; if (!getByte(&ch)) break; comment.push_back(ch); - } - trace("######## Zip Comment :'%s'" , comment.c_str()); + } + trace("######## Zip Comment :'%s'", comment.c_str()); return true; } - /** * */ bool ZipFile::read() { fileBufPos = 0; - if (!readFileData()) - { + if (!readFileData()) { return false; - } - if (!readCentralDirectory()) - { + } + if (!readCentralDirectory()) { return false; - } + } return true; } @@ -3005,7 +2696,6 @@ bool ZipFile::readBuffer(const std::vector<unsigned char> &inbuf) return true; } - /** * */ @@ -3015,29 +2705,18 @@ bool ZipFile::readFile(const std::string &fileName) FILE *f = fopen(fileName.c_str(), "rb"); if (!f) return false; - while (true) - { + while (true) { int ch = fgetc(f); if (ch < 0) break; fileBuf.push_back(ch); - } + } fclose(f); if (!read()) return false; return true; } - - - - - - - - //######################################################################## //# E N D O F F I L E //######################################################################## - - diff --git a/src/util/ziptool.h b/src/util/ziptool.h index 26aaac81cff25029ab92ec1f0764aacffc780574..62b804bc967f6cc85075ce457beada1bc37e4779 100644 --- a/src/util/ziptool.h +++ b/src/util/ziptool.h @@ -39,11 +39,8 @@ * on ZLib and Info-Zip. Enjoy. */ - - -#include <vector> #include <string> - +#include <vector> //######################################################################## //# A D L E R 3 2 @@ -52,7 +49,6 @@ class Adler32 { public: - Adler32(); virtual ~Adler32(); @@ -66,12 +62,9 @@ public: unsigned long getValue(); private: - unsigned long value; - }; - //######################################################################## //# C R C 3 2 //######################################################################## @@ -79,7 +72,6 @@ private: class Crc32 { public: - Crc32(); virtual ~Crc32(); @@ -95,16 +87,9 @@ public: unsigned long getValue(); private: - unsigned long value; - }; - - - - - //######################################################################## //# G Z I P S T R E A M S //######################################################################## @@ -112,7 +97,6 @@ private: class GzipFile { public: - /** * */ @@ -153,7 +137,6 @@ public: */ virtual void setFileName(const std::string &val); - //###################### //# U T I L I T Y //###################### @@ -182,12 +165,10 @@ public: */ virtual bool writeFile(const std::string &fileName); - //###################### //# R E A D //###################### - /** * */ @@ -203,25 +184,22 @@ public: */ virtual bool loadFile(const std::string &fileName); - - private: - std::vector<unsigned char> data; std::string fileName; - //debug messages + // debug messages void error(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; +#ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) +#endif + ; void trace(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; +#ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) +#endif + ; std::vector<unsigned char> fileBuf; unsigned long fileBufPos; @@ -235,21 +213,16 @@ private: int compressionMethod; }; - - - //######################################################################## //# Z I P F I L E //######################################################################## - /** * */ class ZipEntry { public: - /** * */ @@ -258,8 +231,7 @@ public: /** * */ - ZipEntry(std::string fileName, - std::string comment); + ZipEntry(std::string fileName, std::string comment); /** * @@ -350,8 +322,7 @@ public: /** * */ - virtual bool readFile(const std::string &fileNameArg, - const std::string &commentArg); + virtual bool readFile(const std::string &fileNameArg, const std::string &commentArg); /** * @@ -364,7 +335,6 @@ public: virtual unsigned long getPosition(); private: - unsigned long crc; std::string fileName; @@ -378,14 +348,6 @@ private: unsigned long position; }; - - - - - - - - /** * This class sits over the zlib and gzip code to * implement a PKWare or Info-Zip .zip file reader and @@ -394,7 +356,6 @@ private: class ZipFile { public: - /** * */ @@ -424,7 +385,6 @@ public: */ std::vector<ZipEntry *> &getEntries(); - //###################### //# U T I L I T Y //###################### @@ -432,14 +392,12 @@ public: /** * */ - virtual ZipEntry *addFile(const std::string &fileNameArg, - const std::string &commentArg); + virtual ZipEntry *addFile(const std::string &fileNameArg, const std::string &commentArg); /** * */ - virtual ZipEntry *newEntry(const std::string &fileNameArg, - const std::string &commentArg); + virtual ZipEntry *newEntry(const std::string &fileNameArg, const std::string &commentArg); //###################### //# W R I T E @@ -460,12 +418,10 @@ public: */ virtual bool writeFile(const std::string &fileName); - //###################### //# R E A D //###################### - /** * */ @@ -481,20 +437,18 @@ public: */ virtual bool readFile(const std::string &fileName); - private: - - //debug messages + // debug messages void error(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; +#ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) +#endif + ; void trace(char const *fmt, ...) - #ifdef G_GNUC_PRINTF - G_GNUC_PRINTF(2, 3) - #endif - ; +#ifdef G_GNUC_PRINTF + G_GNUC_PRINTF(2, 3) +#endif + ; //# Private writing methods @@ -508,7 +462,6 @@ private: */ bool putInt(unsigned int val); - /** * */ @@ -524,7 +477,6 @@ private: */ bool writeCentralDirectory(); - //# Private reading methods /** @@ -552,7 +504,6 @@ private: */ bool readCentralDirectory(); - std::vector<ZipEntry *> entries; std::vector<unsigned char> fileBuf; @@ -561,15 +512,8 @@ private: std::string comment; }; - - - - - #endif // SEEN_ZIPTOOL_H - //######################################################################## //# E N D O F F I L E //######################################################################## - diff --git a/src/vanishing-point.cpp b/src/vanishing-point.cpp index 3cea5a3efe1df717482329efa075d1d48a5fdcfc..bf1c32fd19402d5a17793d2f7b4356919cb73dd6 100644 --- a/src/vanishing-point.cpp +++ b/src/vanishing-point.cpp @@ -14,30 +14,27 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glibmm/i18n.h> - #include "vanishing-point.h" -#include "desktop.h" -#include "document-undo.h" -#include "perspective-line.h" -#include "snap.h" -#include "verbs.h" +#include <glibmm/i18n.h> +#include "desktop.h" #include "display/sp-canvas-item.h" #include "display/sp-ctrlline.h" - -#include "object/sp-namedview.h" +#include "document-undo.h" #include "object/box3d.h" - +#include "object/sp-namedview.h" +#include "perspective-line.h" +#include "snap.h" #include "ui/shape-editor.h" #include "ui/tools/tool-base.h" +#include "verbs.h" +using Inkscape::ControlManager; using Inkscape::CTLINE_PRIMARY; using Inkscape::CTLINE_SECONDARY; using Inkscape::CTLINE_TERTIARY; using Inkscape::CTRL_TYPE_ANCHOR; -using Inkscape::ControlManager; using Inkscape::CtrlLineType; using Inkscape::DocumentUndo; @@ -77,7 +74,7 @@ static void vp_drag_sel_modified(Inkscape::Selection * /*selection*/, guint /*fl static bool have_VPs_of_same_perspective(VPDragger *dr1, VPDragger *dr2) { - for (auto & vp : dr1->vps) { + for (auto &vp : dr1->vps) { if (dr2->hasPerspective(vp.get_perspective())) { return true; } @@ -112,13 +109,14 @@ static void vp_knot_moved_handler(SPKnot *knot, Geom::Point const &ppointer, gui sel_boxes = sel_vp->selectedBoxes(SP_ACTIVE_DESKTOP->getSelection()); // we create a new perspective ... - Persp3D *new_persp = Persp3D::create_xml_element(dragger->parent->document, old_persp->perspective_impl); + Persp3D *new_persp = + Persp3D::create_xml_element(dragger->parent->document, old_persp->perspective_impl); /* ... unlink the boxes from the old one and FIXME: We need to unlink the _un_selected boxes of each VP so that the correct boxes are kept with the VP being moved */ std::list<SPBox3D *> bx_lst = old_persp->list_of_boxes(); - for (auto & box : bx_lst) { + for (auto &box : bx_lst) { if (std::find(sel_boxes.begin(), sel_boxes.end(), box) == sel_boxes.end()) { /* if a box in the VP is unselected, move it to the newly created perspective so that it doesn't get dragged **/ @@ -146,7 +144,7 @@ static void vp_knot_moved_handler(SPKnot *knot, Geom::Point const &ppointer, gui // update positions ... (this is needed so that the perspectives are detected as identical) // FIXME: This is called a bit too often, isn't it? - for (auto & vp : dragger->vps) { + for (auto &vp : dragger->vps) { vp.set_pos(d_new->point); } @@ -225,7 +223,7 @@ static void vp_knot_ungrabbed_handler(SPKnot *knot, guint /*state*/, gpointer da dragger->dragging_started = false; - for (auto & vp : dragger->vps) { + for (auto &vp : dragger->vps) { vp.set_pos(knot->pos); vp.updateBoxReprs(); vp.updatePerspRepr(); @@ -332,8 +330,7 @@ void VPDragger::updateTip() "with <b>Shift</b> to separate selected box(es)", num), num); - } - else { + } else { // This won't make sense any more when infinite VPs are not shown on the canvas, // but currently we update the status message anyway this->knot->tip = g_strdup_printf(ngettext("<b>Infinite</b> vanishing point shared by <b>%d</b> box", @@ -342,8 +339,7 @@ void VPDragger::updateTip() num), num); } - } - else { + } else { int length = this->vps.size(); char *desc1 = g_strdup_printf("Collection of <b>%d</b> vanishing points ", length); char *desc2 = g_strdup_printf( @@ -386,7 +382,7 @@ void VPDragger::removeVP(VanishingPoint const &vp) VanishingPoint *VPDragger::findVPWithBox(SPBox3D *box) { - for (auto & vp : vps) { + for (auto &vp : vps) { if (vp.hasBox(box)) { return &vp; } @@ -417,7 +413,7 @@ std::set<VanishingPoint *> VPDragger::VPsOfSelectedBoxes() guint VPDragger::numberOfBoxes() { guint num = 0; - for (auto & vp : vps) { + for (auto &vp : vps) { num += vp.numberOfBoxes(); } return num; @@ -425,7 +421,7 @@ guint VPDragger::numberOfBoxes() bool VPDragger::hasPerspective(const Persp3D *persp) { - for (auto & vp : vps) { + for (auto &vp : vps) { if (persp->perspectives_coincide(vp.get_perspective())) { return true; } @@ -458,21 +454,21 @@ void VPDragger::mergePerspectives() void VPDragger::updateBoxDisplays() { - for (auto & vp : this->vps) { + for (auto &vp : this->vps) { vp.updateBoxDisplays(); } } void VPDragger::updateVPs(Geom::Point const &pt) { - for (auto & vp : this->vps) { + for (auto &vp : this->vps) { vp.set_pos(pt); } } void VPDragger::updateZOrders() { - for (auto & vp : this->vps) { + for (auto &vp : this->vps) { vp.get_perspective()->update_z_orders(); } } @@ -480,7 +476,7 @@ void VPDragger::updateZOrders() void VPDragger::printVPs() { g_print("VPDragger at position (%f, %f):\n", point[Geom::X], point[Geom::Y]); - for (auto & vp : this->vps) { + for (auto &vp : this->vps) { g_print(" VP %s\n", vp.axisString()); } } @@ -496,11 +492,11 @@ VPDrag::VPDrag(SPDocument *document) this->dragging = false; this->sel_changed_connection = - this->selection->connectChanged(sigc::bind(sigc::ptr_fun(&vp_drag_sel_changed), (gpointer) this) + this->selection->connectChanged(sigc::bind(sigc::ptr_fun(&vp_drag_sel_changed), (gpointer)this) - ); + ); this->sel_modified_connection = - this->selection->connectModified(sigc::bind(sigc::ptr_fun(&vp_drag_sel_modified), (gpointer) this)); + this->selection->connectModified(sigc::bind(sigc::ptr_fun(&vp_drag_sel_modified), (gpointer)this)); this->updateDraggers(); this->updateLines(); @@ -631,7 +627,7 @@ void VPDrag::updateBoxHandles() void VPDrag::updateBoxReprs() { for (auto dragger : this->draggers) { - for (auto & vp : dragger->vps) { + for (auto &vp : dragger->vps) { vp.updateBoxReprs(); } } @@ -640,13 +636,12 @@ void VPDrag::updateBoxReprs() void VPDrag::updateBoxDisplays() { for (auto dragger : this->draggers) { - for (auto & vp : dragger->vps) { + for (auto &vp : dragger->vps) { vp.updateBoxDisplays(); } } } - /** * Depending on the value of all_lines, draw the front and/or rear perspective lines starting from the given corners. */ @@ -688,8 +683,7 @@ void VPDrag::drawLinesForFace(const SPBox3D *box, this->addLine(corners[2], pt, type); this->addLine(corners[3], pt, type); } - } - else { + } else { // draw perspective lines for infinite VPs boost::optional<Geom::Point> pts[NUM_CORNERS]; Persp3D *persp = box->get_perspective(); @@ -745,7 +739,7 @@ void VPDrag::swap_perspectives_of_VPs(Persp3D *persp2, Persp3D *persp1) { // iterate over all VP in all draggers and replace persp2 with persp1 for (auto dragger : this->draggers) { - for (auto & vp : dragger->vps) { + for (auto &vp : dragger->vps) { if (vp.get_perspective() == persp2) { vp.set_perspective(persp1); } diff --git a/src/vanishing-point.h b/src/vanishing-point.h index 73d7e959b412cd196702ffa9ba37ffc6eb3f8a2f..c6eac9b5c79cf320a9f6acc59b01db8e7095cb6e 100644 --- a/src/vanishing-point.h +++ b/src/vanishing-point.h @@ -18,17 +18,16 @@ #include <set> #include "knot.h" -#include "selection.h" - #include "object/persp3d.h" - +#include "selection.h" #include "ui/control-manager.h" // TODO break enums out separately class SPBox3D; namespace Box3D { -enum VPState { +enum VPState +{ VP_FINITE = 0, // perspective lines meet in the VP VP_INFINITE // perspective lines are parallel }; @@ -39,72 +38,84 @@ enum VPState { * are rather linked to the parent perspective). */ // FIXME: Don't store the box in the VP but rather the perspective (and link the box to it)!! -class VanishingPoint { +class VanishingPoint +{ public: - VanishingPoint() : my_counter(VanishingPoint::global_counter++), _persp(nullptr), _axis(Proj::NONE) {} - VanishingPoint(Persp3D *persp, Proj::Axis axis) : my_counter(VanishingPoint::global_counter++), _persp(persp), _axis(axis) {} - VanishingPoint(const VanishingPoint &other) : my_counter(VanishingPoint::global_counter++), _persp(other._persp), _axis(other._axis) {} + VanishingPoint() + : my_counter(VanishingPoint::global_counter++) + , _persp(nullptr) + , _axis(Proj::NONE) + {} + VanishingPoint(Persp3D *persp, Proj::Axis axis) + : my_counter(VanishingPoint::global_counter++) + , _persp(persp) + , _axis(axis) + {} + VanishingPoint(const VanishingPoint &other) + : my_counter(VanishingPoint::global_counter++) + , _persp(other._persp) + , _axis(other._axis) + {} inline VanishingPoint &operator=(VanishingPoint const &rhs) = default; - inline bool operator==(VanishingPoint const &rhs) const { + inline bool operator==(VanishingPoint const &rhs) const + { /* vanishing points coincide if they belong to the same perspective */ return (_persp == rhs._persp && _axis == rhs._axis); } - inline bool operator<(VanishingPoint const &rhs) const { - return my_counter < rhs.my_counter; - } + inline bool operator<(VanishingPoint const &rhs) const { return my_counter < rhs.my_counter; } - inline void set(Persp3D *persp, Proj::Axis axis) { + inline void set(Persp3D *persp, Proj::Axis axis) + { _persp = persp; _axis = axis; } void set_pos(Proj::Pt2 const &pt); - inline bool is_finite() const { - g_return_val_if_fail (_persp, false); - return _persp->get_VP (_axis).is_finite(); - } - inline Geom::Point get_pos() const { - g_return_val_if_fail (_persp, Geom::Point (Geom::infinity(), Geom::infinity())); - return _persp->get_VP (_axis).affine(); + inline bool is_finite() const + { + g_return_val_if_fail(_persp, false); + return _persp->get_VP(_axis).is_finite(); } - inline Persp3D * get_perspective() const { - return _persp; - } - inline Persp3D * set_perspective(Persp3D *persp) { - return _persp = persp; + inline Geom::Point get_pos() const + { + g_return_val_if_fail(_persp, Geom::Point(Geom::infinity(), Geom::infinity())); + return _persp->get_VP(_axis).affine(); } + inline Persp3D *get_perspective() const { return _persp; } + inline Persp3D *set_perspective(Persp3D *persp) { return _persp = persp; } - inline bool hasBox (SPBox3D *box) { - return _persp->has_box(box); - } - inline unsigned int numberOfBoxes() const { - return _persp->num_boxes(); - } + inline bool hasBox(SPBox3D *box) { return _persp->has_box(box); } + inline unsigned int numberOfBoxes() const { return _persp->num_boxes(); } /* returns all selected boxes sharing this perspective */ std::list<SPBox3D *> selectedBoxes(Inkscape::Selection *sel); - inline void updateBoxDisplays() const { - g_return_if_fail (_persp); + inline void updateBoxDisplays() const + { + g_return_if_fail(_persp); _persp->update_box_displays(); } - inline void updateBoxReprs() const { - g_return_if_fail (_persp); + inline void updateBoxReprs() const + { + g_return_if_fail(_persp); _persp->update_box_reprs(); } - inline void updatePerspRepr() const { - g_return_if_fail (_persp); + inline void updatePerspRepr() const + { + g_return_if_fail(_persp); SP_OBJECT(_persp)->updateRepr(SP_OBJECT_WRITE_EXT); } - inline void printPt() const { - g_return_if_fail (_persp); - _persp->get_VP (_axis).print(""); + inline void printPt() const + { + g_return_if_fail(_persp); + _persp->get_VP(_axis).print(""); } - inline char const *axisString () { return Proj::string_from_axis(_axis); } + inline char const *axisString() { return Proj::string_from_axis(_axis); } unsigned int my_counter; - static unsigned int global_counter; // FIXME: Only to implement operator< so that we can merge lists. Do this in a better way!! + static unsigned int global_counter; // FIXME: Only to implement operator< so that we can merge lists. Do this in a + // better way!! private: Persp3D *_persp; Proj::Axis _axis; @@ -112,7 +123,8 @@ private: struct VPDrag; -struct VPDragger { +struct VPDragger +{ public: VPDragger(VPDrag *parent, Geom::Point p, VanishingPoint &vp); ~VPDragger(); @@ -136,7 +148,7 @@ public: unsigned int numberOfBoxes(); // the number of boxes linked to all VPs of the dragger VanishingPoint *findVPWithBox(SPBox3D *box); - std::set<VanishingPoint*> VPsOfSelectedBoxes(); + std::set<VanishingPoint *> VPsOfSelectedBoxes(); bool hasPerspective(const Persp3D *persp); void mergePerspectives(); // remove duplicate perspectives @@ -153,12 +165,13 @@ private: sigc::connection _ungrabbed_connection; }; -struct VPDrag { +struct VPDrag +{ public: VPDrag(SPDocument *document); ~VPDrag(); - VPDragger *getDraggerFor (VanishingPoint const &vp); + VPDragger *getDraggerFor(VanishingPoint const &vp); bool dragging; @@ -172,28 +185,28 @@ public: * Also, they should make use of the info in a VanishingPoint structure (regarding boxes * and perspectives) rather than each time iterating over the whole list of selected items? */ - void updateDraggers (); - void updateLines (); - void updateBoxHandles (); - void updateBoxReprs (); - void updateBoxDisplays (); - void drawLinesForFace (const SPBox3D *box, Proj::Axis axis); //, guint corner1, guint corner2, guint corner3, guint corner4); - bool show_lines; /* whether perspective lines are drawn at all */ - unsigned int front_or_rear_lines; /* whether we draw perspective lines from all corners or only the - front/rear corners (indicated by the first/second bit, respectively */ - + void updateDraggers(); + void updateLines(); + void updateBoxHandles(); + void updateBoxReprs(); + void updateBoxDisplays(); + void drawLinesForFace(const SPBox3D *box, + Proj::Axis axis); //, guint corner1, guint corner2, guint corner3, guint corner4); + bool show_lines; /* whether perspective lines are drawn at all */ + unsigned int front_or_rear_lines; /* whether we draw perspective lines from all corners or only the + front/rear corners (indicated by the first/second bit, respectively */ inline bool hasEmptySelection() { return this->selection->isEmpty(); } - bool allBoxesAreSelected (VPDragger *dragger); + bool allBoxesAreSelected(VPDragger *dragger); // FIXME: Should this be private? (It's the case with the corresponding function in gradient-drag.h) // But vp_knot_grabbed_handler - void addDragger (VanishingPoint &vp); + void addDragger(VanishingPoint &vp); void swap_perspectives_of_VPs(Persp3D *persp2, Persp3D *persp1); private: - //void deselect_all(); + // void deselect_all(); /** * Create a line from p1 to p2 and add it to the lines list. @@ -207,7 +220,6 @@ private: } // namespace Box3D - #endif /* !SEEN_VANISHING_POINT_H */ /* diff --git a/src/verbs.cpp b/src/verbs.cpp index 19ffc62561fcfe30a3f9c7f8e29a6995dc7036d0..16a333b298e169793259864b82b891720d12d418 100644 --- a/src/verbs.cpp +++ b/src/verbs.cpp @@ -34,41 +34,33 @@ #include <gtkmm/messagedialog.h> #include "desktop.h" - +#include "display/curve.h" #include "document.h" +#include "extension/effect.h" #include "file.h" #include "gradient-drag.h" #include "help.h" +#include "helper/action.h" #include "inkscape.h" #include "layer-fns.h" #include "layer-manager.h" -#include "message-stack.h" -#include "path-chemistry.h" -#include "selection-chemistry.h" -#include "seltrans.h" -#include "shortcuts.h" -#include "text-chemistry.h" - -#include "display/curve.h" - -#include "extension/effect.h" - -#include "helper/action.h" - #include "live_effects/effect.h" #include "live_effects/lpe-powerclip.h" #include "live_effects/lpe-powermask.h" - +#include "message-stack.h" #include "object/sp-defs.h" #include "object/sp-flowtext.h" #include "object/sp-guide.h" #include "object/sp-namedview.h" #include "object/sp-object.h" - +#include "path-chemistry.h" #include "path/path-offset.h" #include "path/path-outline.h" #include "path/path-simplify.h" - +#include "selection-chemistry.h" +#include "seltrans.h" +#include "shortcuts.h" +#include "text-chemistry.h" #include "ui/dialog/align-and-distribute.h" #include "ui/dialog/clonetiler.h" #include "ui/dialog/dialog-manager.h" @@ -92,7 +84,7 @@ #include "ui/tools/freehand-base.h" #include "ui/tools/node-tool.h" #include "ui/tools/select-tool.h" -#include "ui/widget/canvas.h" // Canvas area +#include "ui/widget/canvas.h" // Canvas area using Inkscape::DocumentUndo; using Inkscape::UI::Dialog::ActionAlign; @@ -108,12 +100,12 @@ gchar *sp_action_get_title(SPAction const *action) gchar *ret = g_new(gchar, len + 1); unsigned ri = 0; - for (unsigned si = 0 ; ; si++) { + for (unsigned si = 0;; si++) { int const c = src[si]; // Ignore Unicode Character "…" (U+2026) - if ( c == '\xE2' && si + 2 < len && src[si+1] == '\x80' && src[si+2] == '\xA6' ) { + if (c == '\xE2' && si + 2 < len && src[si + 1] == '\x80' && src[si + 2] == '\xA6') { si += 2; - } else if ( c != '_' && c != '.' ) { + } else if (c != '_' && c != '.') { ret[ri] = c; ri++; if (c == '\0') { @@ -129,231 +121,218 @@ namespace Inkscape { /** * A class to encompass all of the verbs which deal with file operations. */ -class FileVerb : public Verb { +class FileVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - FileVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("File")) - { } + FileVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("File")) + {} }; // FileVerb class /** * A class to encompass all of the verbs which deal with edit operations. */ -class EditVerb : public Verb { +class EditVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - EditVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("Edit")) - { } + EditVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("Edit")) + {} }; // EditVerb class /** * A class to encompass all of the verbs which deal with selection operations. */ -class SelectionVerb : public Verb { +class SelectionVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - SelectionVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("Selection")) - { } + SelectionVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("Selection")) + {} }; // SelectionVerb class /** * A class to encompass all of the verbs which deal with layer operations. */ -class LayerVerb : public Verb { +class LayerVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - LayerVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("Layer")) - { } + LayerVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("Layer")) + {} }; // LayerVerb class /** * A class to encompass all of the verbs which deal with operations related to objects. */ -class ObjectVerb : public Verb { +class ObjectVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - ObjectVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("Object")) - { } + ObjectVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("Object")) + {} }; // ObjectVerb class /** * A class to encompass all of the verbs which deal with operations relative to context. */ -class ContextVerb : public Verb { +class ContextVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - ContextVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("Context")) - { } + ContextVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("Context")) + {} }; // ContextVerb class /** * A class to encompass all of the verbs which deal with zoom operations. */ -class ZoomVerb : public Verb { +class ZoomVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - ZoomVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("View")) - { } + ZoomVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("View")) + {} }; // ZoomVerb class - /** * A class to encompass all of the verbs which deal with dialog operations. */ -class DialogVerb : public Verb { +class DialogVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - DialogVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("Dialog")) - { } + DialogVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("Dialog")) + {} }; // DialogVerb class /** * A class to encompass all of the verbs which deal with help operations. */ -class HelpVerb : public Verb { +class HelpVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - HelpVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("Help")) - { } + HelpVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("Help")) + {} }; // HelpVerb class /** * A class to encompass all of the verbs which open an URL. */ -class HelpUrlVerb : public HelpVerb { +class HelpUrlVerb : public HelpVerb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the HelpVerb initializer with the same parameters. */ - HelpUrlVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - HelpVerb(code, id, name, tip, image) - { } + HelpUrlVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : HelpVerb(code, id, name, tip, image) + {} }; // HelpUrlVerb class /** * A class to encompass all of the verbs which deal with tutorial operations. */ -class TutorialVerb : public Verb { +class TutorialVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - TutorialVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("Help")) - { } + TutorialVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("Help")) + {} }; // TutorialVerb class /** * A class to encompass all of the verbs which deal with text operations. */ -class TextVerb : public Verb { +class TextVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - TextVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("Text")) - { } -}; //TextVerb : public Verb + TextVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("Text")) + {} +}; // TextVerb : public Verb Verb::VerbTable Verb::_verbs; Verb::VerbIDTable Verb::_verb_ids; @@ -368,17 +347,17 @@ Verb::VerbIDTable Verb::_verb_ids; * each call it is incremented. The list of allocated verbs is kept * in the \c _verbs hashtable which is indexed by the \c code. */ -Verb::Verb(gchar const *id, gchar const *name, gchar const *tip, gchar const *image, gchar const *group) : - _actions(nullptr), - _id(id), - _name(name), - _tip(tip), - _full_tip(nullptr), - _shortcut(0), - _image(image), - _code(0), - _group(group), - _default_sensitive(false) +Verb::Verb(gchar const *id, gchar const *name, gchar const *tip, gchar const *image, gchar const *group) + : _actions(nullptr) + , _id(id) + , _name(name) + , _tip(tip) + , _full_tip(nullptr) + , _shortcut(0) + , _image(image) + , _code(0) + , _group(group) + , _default_sensitive(false) { static int count = SP_VERB_LAST; @@ -415,7 +394,7 @@ Verb::~Verb() */ SPAction *Verb::make_action(Inkscape::ActionContext const & /*context*/) { - //std::cout << "make_action" << std::endl; + // std::cout << "make_action" << std::endl; return nullptr; } @@ -426,9 +405,9 @@ SPAction *Verb::make_action(Inkscape::ActionContext const & /*context*/) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *FileVerb::make_action(Inkscape::ActionContext const & context) +SPAction *FileVerb::make_action(Inkscape::ActionContext const &context) { - //std::cout << "fileverb: make_action: " << &perform << std::endl; + // std::cout << "fileverb: make_action: " << &perform << std::endl; return make_action_helper(context, &perform); } @@ -440,9 +419,9 @@ SPAction *FileVerb::make_action(Inkscape::ActionContext const & context) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *EditVerb::make_action(Inkscape::ActionContext const & context) +SPAction *EditVerb::make_action(Inkscape::ActionContext const &context) { - //std::cout << "editverb: make_action: " << &perform << std::endl; + // std::cout << "editverb: make_action: " << &perform << std::endl; return make_action_helper(context, &perform); } @@ -454,7 +433,7 @@ SPAction *EditVerb::make_action(Inkscape::ActionContext const & context) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *SelectionVerb::make_action(Inkscape::ActionContext const & context) +SPAction *SelectionVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform); } @@ -467,7 +446,7 @@ SPAction *SelectionVerb::make_action(Inkscape::ActionContext const & context) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *LayerVerb::make_action(Inkscape::ActionContext const & context) +SPAction *LayerVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform); } @@ -480,7 +459,7 @@ SPAction *LayerVerb::make_action(Inkscape::ActionContext const & context) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *ObjectVerb::make_action(Inkscape::ActionContext const & context) +SPAction *ObjectVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform); } @@ -493,7 +472,7 @@ SPAction *ObjectVerb::make_action(Inkscape::ActionContext const & context) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *ContextVerb::make_action(Inkscape::ActionContext const & context) +SPAction *ContextVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform); } @@ -506,7 +485,7 @@ SPAction *ContextVerb::make_action(Inkscape::ActionContext const & context) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *ZoomVerb::make_action(Inkscape::ActionContext const & context) +SPAction *ZoomVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform); } @@ -519,7 +498,7 @@ SPAction *ZoomVerb::make_action(Inkscape::ActionContext const & context) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *DialogVerb::make_action(Inkscape::ActionContext const & context) +SPAction *DialogVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform); } @@ -532,7 +511,7 @@ SPAction *DialogVerb::make_action(Inkscape::ActionContext const & context) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *HelpVerb::make_action(Inkscape::ActionContext const & context) +SPAction *HelpVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform); } @@ -545,7 +524,7 @@ SPAction *HelpVerb::make_action(Inkscape::ActionContext const & context) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *HelpUrlVerb::make_action(Inkscape::ActionContext const & context) +SPAction *HelpUrlVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform); } @@ -558,7 +537,7 @@ SPAction *HelpUrlVerb::make_action(Inkscape::ActionContext const & context) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *TutorialVerb::make_action(Inkscape::ActionContext const & context) +SPAction *TutorialVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform); } @@ -571,7 +550,7 @@ SPAction *TutorialVerb::make_action(Inkscape::ActionContext const & context) * @param context Which context the action should be created for. * @return The built action. */ -SPAction *TextVerb::make_action(Inkscape::ActionContext const & context) +SPAction *TextVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform); } @@ -591,22 +570,19 @@ SPAction *TextVerb::make_action(Inkscape::ActionContext const & context) * @param vector The function vector for the verb. * @return The created action. */ -SPAction *Verb::make_action_helper(Inkscape::ActionContext const & context, void (*perform_fun)(SPAction *, void *), void *in_pntr) +SPAction *Verb::make_action_helper(Inkscape::ActionContext const &context, void (*perform_fun)(SPAction *, void *), + void *in_pntr) { SPAction *action; - //std::cout << "Adding action: " << _code << std::endl; - action = sp_action_new(context, _id, _(_name), - _(_tip), _image, this); + // std::cout << "Adding action: " << _code << std::endl; + action = sp_action_new(context, _id, _(_name), _(_tip), _image, this); - if (action == nullptr) return nullptr; + if (action == nullptr) + return nullptr; - action->signal_perform.connect( - sigc::bind( - sigc::bind( - sigc::ptr_fun(perform_fun), - in_pntr ? in_pntr : reinterpret_cast<void*>(_code)), - action)); + action->signal_perform.connect(sigc::bind( + sigc::bind(sigc::ptr_fun(perform_fun), in_pntr ? in_pntr : reinterpret_cast<void *>(_code)), action)); return action; } @@ -631,11 +607,11 @@ SPAction *Verb::make_action_helper(Inkscape::ActionContext const & context, void * @param context The action context which this action relates to. * @return The action, or NULL if there is an error. */ -SPAction *Verb::get_action(Inkscape::ActionContext const & context) +SPAction *Verb::get_action(Inkscape::ActionContext const &context) { SPAction *action = nullptr; - if ( _actions == nullptr ) { + if (_actions == nullptr) { _actions = new ActionTable; } ActionTable::iterator action_found = _actions->find(context.getView()); @@ -645,13 +621,13 @@ SPAction *Verb::get_action(Inkscape::ActionContext const & context) } else { action = this->make_action(context); - if (action == nullptr) printf("Hmm, NULL in %s\n", _name); + if (action == nullptr) + printf("Hmm, NULL in %s\n", _name); if (!_default_sensitive) { sp_action_set_sensitive(action, 0); } else { for (ActionTable::iterator cur_action = _actions->begin(); - cur_action != _actions->end() && context.getView() != nullptr; - ++cur_action) { + cur_action != _actions->end() && context.getView() != nullptr; ++cur_action) { if (cur_action->first != nullptr && cur_action->first->doc() == context.getDocument()) { sp_action_set_sensitive(action, cur_action->second->sensitive); break; @@ -679,7 +655,7 @@ void Verb::sensitive(SPDocument *in_doc, bool in_sensitive) { // printf("Setting sensitivity of \"%s\" to %d\n", _name, in_sensitive); if (_actions != nullptr) { - for (auto & _action : *_actions) { + for (auto &_action : *_actions) { if (in_doc == nullptr || (_action.first != nullptr && _action.first->doc() == in_doc)) { sp_action_set_sensitive(_action.second, in_sensitive ? 1 : 0); } @@ -701,13 +677,13 @@ gchar const *Verb::get_tip() gchar const *result = nullptr; if (_tip) { unsigned int shortcut = sp_shortcut_get_primary(this); - if ( (shortcut != _shortcut) || !_full_tip) { + if ((shortcut != _shortcut) || !_full_tip) { if (_full_tip) { g_free(_full_tip); _full_tip = nullptr; } _shortcut = shortcut; - gchar* shortcutString = sp_shortcut_get_label(shortcut); + gchar *shortcutString = sp_shortcut_get_label(shortcut); if (shortcutString) { _full_tip = g_strdup_printf("%s (%s)", _(_tip), shortcutString); g_free(shortcutString); @@ -722,11 +698,10 @@ gchar const *Verb::get_tip() return result; } -void -Verb::name(SPDocument *in_doc, Glib::ustring in_name) +void Verb::name(SPDocument *in_doc, Glib::ustring in_name) { if (_actions != nullptr) { - for (auto & _action : *_actions) { + for (auto &_action : *_actions) { if (in_doc == nullptr || (_action.first != nullptr && _action.first->doc() == in_doc)) { sp_action_set_name(_action.second, in_name); } @@ -746,8 +721,10 @@ Verb::name(SPDocument *in_doc, Glib::ustring in_name) */ void Verb::delete_view(Inkscape::UI::View::View *view) { - if (_actions == nullptr) return; - if (_actions->empty()) return; + if (_actions == nullptr) + return; + if (_actions->empty()) + return; #if 0 static int count = 0; @@ -780,11 +757,11 @@ void Verb::delete_all_view(Inkscape::UI::View::View *view) { for (int i = 0; i <= SP_VERB_LAST; i++) { if (_base_verbs[i]) - _base_verbs[i]->delete_view(view); + _base_verbs[i]->delete_view(view); } if (!_verbs.empty()) { - for (auto & _verb : _verbs) { + for (auto &_verb : _verbs) { Inkscape::Verb *verbpntr = _verb.second; // std::cout << "Delete In Verb: " << verbpntr->_name << std::endl; verbpntr->delete_view(view); @@ -835,9 +812,9 @@ Verb *Verb::getbyid(gchar const *id, bool verbose) if (verb == nullptr #ifndef WITH_GSPELL - && strcmp(id, "DialogSpellcheck") != 0 + && strcmp(id, "DialogSpellcheck") != 0 #endif - ) { + ) { if (verbose) printf("Unable to find: %s\n", id); } @@ -903,13 +880,13 @@ void FileVerb::perform(SPAction *action, void *data) sp_file_print(*parent); break; case SP_VERB_FILE_IMPORT: - prefs->setBool("/options/onimport",true); + prefs->setBool("/options/onimport", true); sp_file_import(*parent); - prefs->setBool("/options/onimport",false); + prefs->setBool("/options/onimport", false); break; -// case SP_VERB_FILE_EXPORT: -// sp_file_export_dialog(*parent); -// break; + // case SP_VERB_FILE_EXPORT: + // sp_file_export_dialog(*parent); + // break; case SP_VERB_FILE_NEXT_DESKTOP: INKSCAPE.switch_desktops_next(); break; @@ -926,7 +903,6 @@ void FileVerb::perform(SPAction *action, void *data) break; } - } // end of sp_verb_action_file_perform() /** @@ -971,7 +947,7 @@ void EditVerb::perform(SPAction *action, void *data) dt->selection->pasteStyle(); break; case SP_VERB_EDIT_PASTE_SIZE: - dt->selection->pasteSize(true,true); + dt->selection->pasteSize(true, true); break; case SP_VERB_EDIT_PASTE_SIZE_X: dt->selection->pasteSize(true, false); @@ -1144,35 +1120,29 @@ void SelectionVerb::perform(SPAction *action, void *data) selection->toCurves(true); selection->pathSlice(); break; - case SP_VERB_SELECTION_GROW: - { + case SP_VERB_SELECTION_GROW: { // FIXME these and the other grow/shrink they should use gobble_key_events. // the problem is how to get access to which key, if any, to gobble. selection->scale(prefs->getDoubleLimited("/options/defaultscale/value", 2, 0, 1000)); break; } - case SP_VERB_SELECTION_GROW_SCREEN: - { + case SP_VERB_SELECTION_GROW_SCREEN: { selection->scaleScreen(2); break; } - case SP_VERB_SELECTION_GROW_DOUBLE: - { + case SP_VERB_SELECTION_GROW_DOUBLE: { selection->scaleTimes(2); break; } - case SP_VERB_SELECTION_SHRINK: - { + case SP_VERB_SELECTION_SHRINK: { selection->scale(-prefs->getDoubleLimited("/options/defaultscale/value", 2, 0, 1000)); break; } - case SP_VERB_SELECTION_SHRINK_SCREEN: - { + case SP_VERB_SELECTION_SHRINK_SCREEN: { selection->scaleScreen(-2); break; } - case SP_VERB_SELECTION_SHRINK_HALVE: - { + case SP_VERB_SELECTION_SHRINK_HALVE: { selection->scaleTimes(0.5); break; } @@ -1201,7 +1171,7 @@ void SelectionVerb::perform(SPAction *action, void *data) selection->ungroup(); break; case SP_VERB_SELECTION_UNGROUP_POP_SELECTION: - selection->popFromGroup(); + selection->popFromGroup(); break; case SP_VERB_SELECTION_FILL_BETWEEN_MANY: selection->fillBetweenMany(); @@ -1295,7 +1265,7 @@ void SelectionVerb::perform(SPAction *action, void *data) selection->breakApart(); break; case SP_VERB_SELECTION_ARRANGE: - dt->_dlg_mgr->showDialog("TileDialog"); //FIXME: denis: What's this string (to be changed) + dt->_dlg_mgr->showDialog("TileDialog"); // FIXME: denis: What's this string (to be changed) break; default: break; @@ -1312,7 +1282,7 @@ void LayerVerb::perform(SPAction *action, void *data) SPDesktop *dt = sp_action_get_desktop(action); size_t verb = reinterpret_cast<std::size_t>(data); - if ( !dt->currentLayer() ) { + if (!dt->currentLayer()) { return; } @@ -1326,11 +1296,10 @@ void LayerVerb::perform(SPAction *action, void *data) break; } case SP_VERB_LAYER_NEXT: { - SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); + SPObject *next = Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); if (next) { dt->setCurrentLayer(next); - DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_NEXT, - _("Switch to next layer")); + DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_NEXT, _("Switch to next layer")); dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Switched to next layer.")); } else { dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Cannot go past last layer.")); @@ -1338,11 +1307,10 @@ void LayerVerb::perform(SPAction *action, void *data) break; } case SP_VERB_LAYER_PREV: { - SPObject *prev=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); + SPObject *prev = Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); if (prev) { dt->setCurrentLayer(prev); - DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_PREV, - _("Switch to previous layer")); + DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_PREV, _("Switch to previous layer")); dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Switched to previous layer.")); } else { dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Cannot go before first layer.")); @@ -1365,12 +1333,12 @@ void LayerVerb::perform(SPAction *action, void *data) case SP_VERB_LAYER_TO_BOTTOM: case SP_VERB_LAYER_RAISE: case SP_VERB_LAYER_LOWER: { - if ( dt->currentLayer() == dt->currentRoot() ) { + if (dt->currentLayer() == dt->currentRoot()) { dt->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("No current layer.")); return; } - SPItem *layer=SP_ITEM(dt->currentLayer()); + SPItem *layer = SP_ITEM(dt->currentLayer()); g_return_if_fail(layer != nullptr); SPObject *old_pos = layer->getNext(); @@ -1390,7 +1358,7 @@ void LayerVerb::perform(SPAction *action, void *data) break; } - if ( layer->getNext() != old_pos ) { + if (layer->getNext() != old_pos) { char const *message = nullptr; Glib::ustring description = ""; switch (verb) { @@ -1414,7 +1382,7 @@ void LayerVerb::perform(SPAction *action, void *data) DocumentUndo::done(dt->getDocument(), verb, description); if (message) { dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, message); - g_free((void *) message); + g_free((void *)message); } } else { dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Cannot move layer any further.")); @@ -1423,12 +1391,10 @@ void LayerVerb::perform(SPAction *action, void *data) break; } case SP_VERB_LAYER_DUPLICATE: { - if ( dt->currentLayer() != dt->currentRoot() ) { - + if (dt->currentLayer() != dt->currentRoot()) { dt->selection->duplicate(true, true); - DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_DUPLICATE, - _("Duplicate layer")); + DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_DUPLICATE, _("Duplicate layer")); // TRANSLATORS: this means "The layer has been duplicated." dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Duplicated layer.")); @@ -1438,7 +1404,7 @@ void LayerVerb::perform(SPAction *action, void *data) break; } case SP_VERB_LAYER_DELETE: { - if ( dt->currentLayer() != dt->currentRoot() ) { + if (dt->currentLayer() != dt->currentRoot()) { dt->getSelection()->clear(); SPObject *old_layer = dt->currentLayer(); SPObject *old_parent = old_layer->parent; @@ -1446,20 +1412,15 @@ void LayerVerb::perform(SPAction *action, void *data) SPObject *survivor = Inkscape::previous_layer(dt->currentRoot(), old_layer); if (survivor != nullptr && survivor->parent == old_layer) { - while (survivor != nullptr && - survivor->parent != old_parent && - survivor->parent != old_parent_parent) - { + while (survivor != nullptr && survivor->parent != old_parent && + survivor->parent != old_parent_parent) { survivor = Inkscape::previous_layer(dt->currentRoot(), survivor); } } if (survivor == nullptr || (survivor->parent != old_parent && survivor->parent != old_layer)) { survivor = Inkscape::next_layer(dt->currentRoot(), old_layer); - while (survivor != nullptr && - survivor != old_parent && - survivor->parent != old_parent) - { + while (survivor != nullptr && survivor != old_parent && survivor->parent != old_parent) { survivor = Inkscape::next_layer(dt->currentRoot(), survivor); } } @@ -1475,8 +1436,7 @@ void LayerVerb::perform(SPAction *action, void *data) dt->setCurrentLayer(survivor); } - DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_DELETE, - _("Delete layer")); + DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_DELETE, _("Delete layer")); // TRANSLATORS: this means "The layer has been deleted." dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Deleted layer.")); @@ -1486,54 +1446,54 @@ void LayerVerb::perform(SPAction *action, void *data) break; } case SP_VERB_LAYER_SOLO: { - if ( dt->currentLayer() == dt->currentRoot() ) { + if (dt->currentLayer() == dt->currentRoot()) { dt->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("No current layer.")); } else { - dt->toggleLayerSolo( dt->currentLayer() ); + dt->toggleLayerSolo(dt->currentLayer()); DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_SOLO, _("Toggle layer solo")); } break; } case SP_VERB_LAYER_SHOW_ALL: { - dt->toggleHideAllLayers( false ); + dt->toggleHideAllLayers(false); DocumentUndo::maybeDone(dt->getDocument(), "layer:showall", SP_VERB_LAYER_SHOW_ALL, _("Show all layers")); break; } case SP_VERB_LAYER_HIDE_ALL: { - dt->toggleHideAllLayers( true ); + dt->toggleHideAllLayers(true); DocumentUndo::maybeDone(dt->getDocument(), "layer:hideall", SP_VERB_LAYER_HIDE_ALL, _("Hide all layers")); break; } case SP_VERB_LAYER_LOCK_ALL: { - dt->toggleLockAllLayers( true ); + dt->toggleLockAllLayers(true); DocumentUndo::maybeDone(dt->getDocument(), "layer:lockall", SP_VERB_LAYER_LOCK_ALL, _("Lock all layers")); break; } case SP_VERB_LAYER_LOCK_OTHERS: { - if ( dt->currentLayer() == dt->currentRoot() ) { + if (dt->currentLayer() == dt->currentRoot()) { dt->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("No current layer.")); } else { - dt->toggleLockOtherLayers( dt->currentLayer() ); + dt->toggleLockOtherLayers(dt->currentLayer()); DocumentUndo::done(dt->getDocument(), SP_VERB_LAYER_LOCK_OTHERS, _("Lock other layers")); } break; } case SP_VERB_LAYER_UNLOCK_ALL: { - dt->toggleLockAllLayers( false ); - DocumentUndo::maybeDone(dt->getDocument(), "layer:unlockall", SP_VERB_LAYER_UNLOCK_ALL, _("Unlock all layers")); + dt->toggleLockAllLayers(false); + DocumentUndo::maybeDone(dt->getDocument(), "layer:unlockall", SP_VERB_LAYER_UNLOCK_ALL, + _("Unlock all layers")); break; } case SP_VERB_LAYER_TOGGLE_LOCK: case SP_VERB_LAYER_TOGGLE_HIDE: { - if ( dt->currentLayer() == dt->currentRoot() ) { + if (dt->currentLayer() == dt->currentRoot()) { dt->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("No current layer.")); } else { - if ( verb == SP_VERB_LAYER_TOGGLE_HIDE ){ + if (verb == SP_VERB_LAYER_TOGGLE_HIDE) { SP_ITEM(dt->currentLayer())->setHidden(!SP_ITEM(dt->currentLayer())->isHidden()); } else { SP_ITEM(dt->currentLayer())->setLocked(!SP_ITEM(dt->currentLayer())->isLocked()); } - } } } @@ -1544,7 +1504,7 @@ void LayerVerb::perform(SPAction *action, void *data) /** * Decode the verb code and take appropriate action. */ -void ObjectVerb::perform( SPAction *action, void *data) +void ObjectVerb::perform(SPAction *action, void *data) { SPDesktop *dt = sp_action_get_desktop(action); Inkscape::Selection *sel = sp_action_get_selection(action); @@ -1602,13 +1562,11 @@ void ObjectVerb::perform( SPAction *action, void *data) break; case SP_VERB_OBJECT_FLIP_HORIZONTAL: sel->setScaleRelative(center, Geom::Scale(-1.0, 1.0)); - DocumentUndo::done(dt->getDocument(), SP_VERB_OBJECT_FLIP_HORIZONTAL, - _("Flip horizontally")); + DocumentUndo::done(dt->getDocument(), SP_VERB_OBJECT_FLIP_HORIZONTAL, _("Flip horizontally")); break; case SP_VERB_OBJECT_FLIP_VERTICAL: sel->setScaleRelative(center, Geom::Scale(1.0, -1.0)); - DocumentUndo::done(dt->getDocument(), SP_VERB_OBJECT_FLIP_VERTICAL, - _("Flip vertically")); + DocumentUndo::done(dt->getDocument(), SP_VERB_OBJECT_FLIP_VERTICAL, _("Flip vertically")); break; case SP_VERB_OBJECT_SET_MASK: sel->setMask(false, false); @@ -1644,7 +1602,7 @@ void ObjectVerb::perform( SPAction *action, void *data) Inkscape::LivePathEffect::sp_remove_powerclip(sp_action_get_selection(action)); sel->unsetMask(true); DocumentUndo::done(dt->getDocument(), SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path")); - + break; default: break; @@ -1669,9 +1627,8 @@ void ContextVerb::perform(SPAction *action, void *data) /** \todo !!! hopefully this can go away soon and actions can look after * themselves */ - for (vidx = SP_VERB_CONTEXT_SELECT; vidx <= SP_VERB_CONTEXT_LPETOOL_PREFS; vidx++) - { - SPAction *tool_action= get((sp_verb_t)vidx)->get_action(action->context); + for (vidx = SP_VERB_CONTEXT_SELECT; vidx <= SP_VERB_CONTEXT_LPETOOL_PREFS; vidx++) { + SPAction *tool_action = get((sp_verb_t)vidx)->get_action(action->context); if (tool_action) { sp_action_set_active(tool_action, vidx == (int)verb); } @@ -1734,7 +1691,7 @@ void ContextVerb::perform(SPAction *action, void *data) Inkscape::UI::Tools::sp_toggle_dropper(dt); // Functionality defined in event-context.cpp break; case SP_VERB_CONTEXT_CONNECTOR: - tools_switch(dt, TOOLS_CONNECTOR); + tools_switch(dt, TOOLS_CONNECTOR); break; case SP_VERB_CONTEXT_PAINTBUCKET: tools_switch(dt, TOOLS_PAINTBUCKET); @@ -1831,7 +1788,7 @@ void ContextVerb::perform(SPAction *action, void *data) dt->_dlg_mgr->showDialog("InkscapePreferences"); break; case SP_VERB_CONTEXT_LPETOOL_PREFS: - g_print ("TODO: Create preferences page for LPETool\n"); + g_print("TODO: Create preferences page for LPETool\n"); prefs->setInt("/dialogs/preferences/page", PREFS_PAGE_TOOLS_LPETOOL); dt->_dlg_mgr->showDialog("InkscapePreferences"); break; @@ -1866,7 +1823,7 @@ void ContextVerb::perform(SPAction *action, void *data) /** * Decode the verb code and take appropriate action. */ -void TextVerb::perform(SPAction *action, void */*data*/) +void TextVerb::perform(SPAction *action, void * /*data*/) { g_return_if_fail(ensure_desktop_valid(action)); SPDesktop *dt = sp_action_get_desktop(action); @@ -1889,63 +1846,57 @@ void ZoomVerb::perform(SPAction *action, void *data) SPDocument *doc = dt->getDocument(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - gdouble zoom_inc = - prefs->getDoubleLimited( "/options/zoomincrement/value", M_SQRT2, 1.01, 10 ); - gdouble rotate_inc = - prefs->getDoubleLimited( "/options/rotateincrement/value", 15, 1, 90, "°" ); - rotate_inc *= M_PI/180.0; + gdouble zoom_inc = prefs->getDoubleLimited("/options/zoomincrement/value", M_SQRT2, 1.01, 10); + gdouble rotate_inc = prefs->getDoubleLimited("/options/rotateincrement/value", 15, 1, 90, "°"); + rotate_inc *= M_PI / 180.0; double zcorr = prefs->getDouble("/options/zoomcorrection/value", 1.0); - //Geom::Rect const d = dt->get_display_area(); + // Geom::Rect const d = dt->get_display_area(); Geom::Rect const d_canvas = dt->getCanvas()->get_area_world(); Geom::Point midpoint = dt->w2d(d_canvas.midpoint()); // Midpoint of drawing on canvas. switch (reinterpret_cast<std::size_t>(data)) { - case SP_VERB_ZOOM_IN: - { - gint mul = 1 + Inkscape::UI::Tools::gobble_key_events( - GDK_KEY_KP_Add, 0); // with any mask + case SP_VERB_ZOOM_IN: { + gint mul = 1 + Inkscape::UI::Tools::gobble_key_events(GDK_KEY_KP_Add, 0); // with any mask // FIXME what if zoom out is bound to something other than subtract? // While drawing with the pen/pencil tool, zoom towards the end of the unfinished path if (tools_isactive(dt, TOOLS_FREEHAND_PENCIL) || tools_isactive(dt, TOOLS_FREEHAND_PEN)) { SPCurve const *rc = SP_DRAW_CONTEXT(ec)->red_curve.get(); if (!rc->is_empty()) { - Geom::Point const zoom_to (*rc->last_point()); - dt->zoom_relative_keep_point(zoom_to, mul*zoom_inc); + Geom::Point const zoom_to(*rc->last_point()); + dt->zoom_relative_keep_point(zoom_to, mul * zoom_inc); break; } } - dt->zoom_relative_center_point( midpoint, mul*zoom_inc); + dt->zoom_relative_center_point(midpoint, mul * zoom_inc); break; } - case SP_VERB_ZOOM_OUT: - { - gint mul = 1 + Inkscape::UI::Tools::gobble_key_events( - GDK_KEY_KP_Subtract, 0); // with any mask + case SP_VERB_ZOOM_OUT: { + gint mul = 1 + Inkscape::UI::Tools::gobble_key_events(GDK_KEY_KP_Subtract, 0); // with any mask // While drawing with the pen/pencil tool, zoom away from the end of the unfinished path if (tools_isactive(dt, TOOLS_FREEHAND_PENCIL) || tools_isactive(dt, TOOLS_FREEHAND_PEN)) { SPCurve const *rc = SP_DRAW_CONTEXT(ec)->red_curve.get(); if (!rc->is_empty()) { - Geom::Point const zoom_to (*rc->last_point()); - dt->zoom_relative_keep_point(zoom_to, 1 / (mul*zoom_inc)); + Geom::Point const zoom_to(*rc->last_point()); + dt->zoom_relative_keep_point(zoom_to, 1 / (mul * zoom_inc)); break; } } - dt->zoom_relative_center_point( midpoint, 1 / (mul*zoom_inc) ); + dt->zoom_relative_center_point(midpoint, 1 / (mul * zoom_inc)); break; } case SP_VERB_ZOOM_1_1: - dt->zoom_absolute_center_point( midpoint, 1.0 * zcorr ); + dt->zoom_absolute_center_point(midpoint, 1.0 * zcorr); break; case SP_VERB_ZOOM_1_2: - dt->zoom_absolute_center_point( midpoint, 0.5 * zcorr ); + dt->zoom_absolute_center_point(midpoint, 0.5 * zcorr); break; case SP_VERB_ZOOM_2_1: - dt->zoom_absolute_center_point( midpoint, 2.0 * zcorr ); + dt->zoom_absolute_center_point(midpoint, 2.0 * zcorr); break; case SP_VERB_ZOOM_PAGE: dt->zoom_page(); @@ -1971,14 +1922,13 @@ void ZoomVerb::perform(SPAction *action, void *data) case SP_VERB_TOGGLE_ROTATION_LOCK: dt->toggle_rotation_lock(); break; - case SP_VERB_ROTATE_CW: - { - gint mul = 1 + Inkscape::UI::Tools::gobble_key_events( GDK_KEY_parenleft, 0); + case SP_VERB_ROTATE_CW: { + gint mul = 1 + Inkscape::UI::Tools::gobble_key_events(GDK_KEY_parenleft, 0); // While drawing with the pen/pencil tool, rotate towards the end of the unfinished path if (tools_isactive(dt, TOOLS_FREEHAND_PENCIL) || tools_isactive(dt, TOOLS_FREEHAND_PEN)) { SPCurve const *rc = SP_DRAW_CONTEXT(ec)->red_curve.get(); if (!rc->is_empty()) { - Geom::Point const rotate_to (*rc->last_point()); + Geom::Point const rotate_to(*rc->last_point()); dt->rotate_relative_keep_point(rotate_to, mul * rotate_inc); break; } @@ -1987,14 +1937,13 @@ void ZoomVerb::perform(SPAction *action, void *data) dt->rotate_relative_center_point(midpoint, mul * rotate_inc); break; } - case SP_VERB_ROTATE_CCW: - { - gint mul = 1 + Inkscape::UI::Tools::gobble_key_events( GDK_KEY_parenright, 0); + case SP_VERB_ROTATE_CCW: { + gint mul = 1 + Inkscape::UI::Tools::gobble_key_events(GDK_KEY_parenright, 0); // While drawing with the pen/pencil tool, rotate towards the end of the unfinished path if (tools_isactive(dt, TOOLS_FREEHAND_PENCIL) || tools_isactive(dt, TOOLS_FREEHAND_PEN)) { SPCurve const *rc = SP_DRAW_CONTEXT(ec)->red_curve.get(); if (!rc->is_empty()) { - Geom::Point const rotate_to (*rc->last_point()); + Geom::Point const rotate_to(*rc->last_point()); dt->rotate_relative_keep_point(rotate_to, -mul * rotate_inc); break; } @@ -2006,39 +1955,37 @@ void ZoomVerb::perform(SPAction *action, void *data) case SP_VERB_ROTATE_ZERO: dt->rotate_absolute_center_point(midpoint, 0.0); break; - case SP_VERB_FLIP_HORIZONTAL: - { + case SP_VERB_FLIP_HORIZONTAL: { // While drawing with the pen/pencil tool, flip towards the end of the unfinished path if (tools_isactive(dt, TOOLS_FREEHAND_PENCIL) || tools_isactive(dt, TOOLS_FREEHAND_PEN)) { SPCurve const *rc = SP_DRAW_CONTEXT(ec)->red_curve.get(); if (!rc->is_empty()) { - Geom::Point const flip_to (*rc->last_point()); + Geom::Point const flip_to(*rc->last_point()); dt->flip_relative_keep_point(flip_to, SPDesktop::FLIP_HORIZONTAL); break; } } - dt->flip_relative_center_point( midpoint, SPDesktop::FLIP_HORIZONTAL); + dt->flip_relative_center_point(midpoint, SPDesktop::FLIP_HORIZONTAL); break; } - case SP_VERB_FLIP_VERTICAL: - { - /* gint mul = 1 + */ Inkscape::UI::Tools::gobble_key_events( GDK_KEY_parenright, 0); + case SP_VERB_FLIP_VERTICAL: { + /* gint mul = 1 + */ Inkscape::UI::Tools::gobble_key_events(GDK_KEY_parenright, 0); // While drawing with the pen/pencil tool, flip towards the end of the unfinished path if (tools_isactive(dt, TOOLS_FREEHAND_PENCIL) || tools_isactive(dt, TOOLS_FREEHAND_PEN)) { SPCurve const *rc = SP_DRAW_CONTEXT(ec)->red_curve.get(); if (!rc->is_empty()) { - Geom::Point const flip_to (*rc->last_point()); + Geom::Point const flip_to(*rc->last_point()); dt->flip_relative_keep_point(flip_to, SPDesktop::FLIP_VERTICAL); break; } } - dt->flip_relative_center_point( midpoint, SPDesktop::FLIP_VERTICAL); + dt->flip_relative_center_point(midpoint, SPDesktop::FLIP_VERTICAL); break; } case SP_VERB_FLIP_NONE: - dt->flip_absolute_center_point( midpoint, SPDesktop::FLIP_NONE); + dt->flip_absolute_center_point(midpoint, SPDesktop::FLIP_NONE); break; case SP_VERB_TOGGLE_RULERS: dt->toggleRulers(); @@ -2067,8 +2014,7 @@ void ZoomVerb::perform(SPAction *action, void *data) case SP_VERB_TOGGLE_GUIDES: sp_namedview_toggle_guides(doc, dt->namedview); break; - case SP_VERB_TOGGLE_SNAPPING: - { + case SP_VERB_TOGGLE_SNAPPING: { DocumentUndo::ScopedInsensitive _no_undo(doc); dt->toggleSnapGlobal(); break; @@ -2110,9 +2056,9 @@ void ZoomVerb::perform(SPAction *action, void *data) case SP_VERB_VIEW_COLOR_MODE_GRAYSCALE: dt->setDisplayColorModeGrayscale(); break; -// case SP_VERB_VIEW_COLOR_MODE_PRINT_COLORS_PREVIEW: -// dt->setDisplayColorModePrintColorsPreview(); -// break; + // case SP_VERB_VIEW_COLOR_MODE_PRINT_COLORS_PREVIEW: + // dt->setDisplayColorModePrintColorsPreview(); + // break; case SP_VERB_VIEW_COLOR_MODE_TOGGLE: dt->displayColorModeToggle(); break; @@ -2149,9 +2095,9 @@ void DialogVerb::perform(SPAction *action, void *data) switch (reinterpret_cast<std::size_t>(data)) { case SP_VERB_DIALOG_PROTOTYPE: dt->_dlg_mgr->showDialog("Prototype"); - break; + break; case SP_VERB_DIALOG_DISPLAY: - //sp_display_dialog(); + // sp_display_dialog(); dt->_dlg_mgr->showDialog("InkscapePreferences"); break; case SP_VERB_DIALOG_NAMEDVIEW: @@ -2209,15 +2155,15 @@ void DialogVerb::perform(SPAction *action, void *data) dt->_dlg_mgr->dialogs_toggle(); break; case SP_VERB_DIALOG_CLONETILER: - //clonetiler_dialog(); + // clonetiler_dialog(); dt->_dlg_mgr->showDialog("CloneTiler"); break; case SP_VERB_DIALOG_ATTR: - //sp_item_dialog(); + // sp_item_dialog(); dt->_dlg_mgr->showDialog("ObjectAttributes"); break; case SP_VERB_DIALOG_ITEM: - //sp_item_dialog(); + // sp_item_dialog(); dt->_dlg_mgr->showDialog("ObjectProperties"); break; case SP_VERB_DIALOG_INPUT: @@ -2378,19 +2324,18 @@ void TutorialVerb::perform(SPAction *action, void *data) /** * A class to represent the last effect issued. */ -class EffectLastVerb : public Verb { +class EffectLastVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - EffectLastVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("Extensions")) + EffectLastVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("Extensions")) { set_default_sensitive(false); } @@ -2404,7 +2349,7 @@ public: * @param context Which context the action should be created for. * @return The built action. */ -SPAction *EffectLastVerb::make_action(Inkscape::ActionContext const & context) +SPAction *EffectLastVerb::make_action(Inkscape::ActionContext const &context) { return make_action_helper(context, &perform); } @@ -2419,7 +2364,8 @@ void EffectLastVerb::perform(SPAction *action, void *data) Inkscape::Extension::Effect *effect = Inkscape::Extension::Effect::get_last_effect(); - if (effect == nullptr) return; + if (effect == nullptr) + return; switch (reinterpret_cast<std::size_t>(data)) { case SP_VERB_EFFECT_LAST_PREF: @@ -2441,20 +2387,19 @@ void EffectLastVerb::perform(SPAction *action, void *data) /** * A class to represent the canvas fitting verbs. */ -class FitCanvasVerb : public Verb { +class FitCanvasVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - FitCanvasVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("View")) - { } + FitCanvasVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("View")) + {} }; // FitCanvasVerb class /** @@ -2465,7 +2410,7 @@ public: * @param context Which context the action should be created for. * @return The built action. */ -SPAction *FitCanvasVerb::make_action(Inkscape::ActionContext const & context) +SPAction *FitCanvasVerb::make_action(Inkscape::ActionContext const &context) { SPAction *action = make_action_helper(context, &perform); return action; @@ -2479,7 +2424,8 @@ void FitCanvasVerb::perform(SPAction *action, void *data) g_return_if_fail(ensure_desktop_valid(action)); SPDesktop *dt = sp_action_get_desktop(action); SPDocument *doc = dt->getDocument(); - if (!doc) return; + if (!doc) + return; switch (reinterpret_cast<std::size_t>(data)) { case SP_VERB_FIT_CANVAS_TO_SELECTION: @@ -2499,25 +2445,23 @@ void FitCanvasVerb::perform(SPAction *action, void *data) } // *********** End Fit Canvas ********** - // *********** Lock'N'Hide ********** /** * A class to represent the object unlocking and unhiding verbs. */ -class LockAndHideVerb : public Verb { +class LockAndHideVerb : public Verb +{ private: static void perform(SPAction *action, void *mydata); + protected: - SPAction *make_action(Inkscape::ActionContext const & context) override; + SPAction *make_action(Inkscape::ActionContext const &context) override; + public: /** Use the Verb initializer with the same parameters. */ - LockAndHideVerb(unsigned int const code, - gchar const *id, - gchar const *name, - gchar const *tip, - gchar const *image) : - Verb(code, id, name, tip, image, _("Layer")) + LockAndHideVerb(unsigned int const code, gchar const *id, gchar const *name, gchar const *tip, gchar const *image) + : Verb(code, id, name, tip, image, _("Layer")) { set_default_sensitive(true); } @@ -2531,7 +2475,7 @@ public: * @param context Which context the action should be created for. * @return The built action. */ -SPAction *LockAndHideVerb::make_action(Inkscape::ActionContext const & context) +SPAction *LockAndHideVerb::make_action(Inkscape::ActionContext const &context) { SPAction *action = make_action_helper(context, &perform); return action; @@ -2545,7 +2489,8 @@ void LockAndHideVerb::perform(SPAction *action, void *data) g_return_if_fail(ensure_desktop_valid(action)); SPDesktop *dt = sp_action_get_desktop(action); SPDocument *doc = dt->getDocument(); - if (!doc) return; + if (!doc) + return; switch (reinterpret_cast<std::size_t>(data)) { case SP_VERB_UNLOCK_ALL: @@ -2572,7 +2517,6 @@ void LockAndHideVerb::perform(SPAction *action, void *data) } // *********** End Lock'N'Hide ********** - // these must be in the same order as the SP_VERB_* enum in "verbs.h" Verb *Verb::_base_verbs[] = { // Header @@ -2629,15 +2573,20 @@ Verb *Verb::_base_verbs[] = { new EditVerb(SP_VERB_EDIT_PASTE_SIZE, "EditPasteSize", N_("Paste Si_ze"), N_("Scale selection to match the size of the copied object"), INKSCAPE_ICON("edit-paste-size")), new EditVerb(SP_VERB_EDIT_PASTE_SIZE_X, "EditPasteWidth", N_("Paste _Width"), - N_("Scale selection horizontally to match the width of the copied object"), INKSCAPE_ICON("edit-paste-width")), + N_("Scale selection horizontally to match the width of the copied object"), + INKSCAPE_ICON("edit-paste-width")), new EditVerb(SP_VERB_EDIT_PASTE_SIZE_Y, "EditPasteHeight", N_("Paste _Height"), - N_("Scale selection vertically to match the height of the copied object"), INKSCAPE_ICON("edit-paste-height")), + N_("Scale selection vertically to match the height of the copied object"), + INKSCAPE_ICON("edit-paste-height")), new EditVerb(SP_VERB_EDIT_PASTE_SIZE_SEPARATELY, "EditPasteSizeSeparately", N_("Paste Size Separately"), - N_("Scale each selected object to match the size of the copied object"), INKSCAPE_ICON("edit-paste-size-separately")), + N_("Scale each selected object to match the size of the copied object"), + INKSCAPE_ICON("edit-paste-size-separately")), new EditVerb(SP_VERB_EDIT_PASTE_SIZE_SEPARATELY_X, "EditPasteWidthSeparately", N_("Paste Width Separately"), - N_("Scale each selected object horizontally to match the width of the copied object"), INKSCAPE_ICON("edit-paste-width-separately")), + N_("Scale each selected object horizontally to match the width of the copied object"), + INKSCAPE_ICON("edit-paste-width-separately")), new EditVerb(SP_VERB_EDIT_PASTE_SIZE_SEPARATELY_Y, "EditPasteHeightSeparately", N_("Paste Height Separately"), - N_("Scale each selected object vertically to match the height of the copied object"), INKSCAPE_ICON("edit-paste-height-separately")), + N_("Scale each selected object vertically to match the height of the copied object"), + INKSCAPE_ICON("edit-paste-height-separately")), new EditVerb(SP_VERB_EDIT_PASTE_IN_PLACE, "EditPasteInPlace", N_("Paste _In Place"), N_("Paste objects from clipboard to the original location"), INKSCAPE_ICON("edit-paste-in-place")), new EditVerb(SP_VERB_EDIT_PASTE_LIVEPATHEFFECT, "PasteLivePathEffect", N_("Paste Path _Effect"), @@ -2659,11 +2608,13 @@ Verb *Verb::_base_verbs[] = { N_("Unlink all clones in the selection, even if they are in groups."), INKSCAPE_ICON("edit-clone-unlink")), new EditVerb(SP_VERB_EDIT_RELINK_CLONE, "EditRelinkClone", N_("Relink to Copied"), - N_("Relink the selected clones to the object currently on the clipboard"), INKSCAPE_ICON("edit-clone-link")), + N_("Relink the selected clones to the object currently on the clipboard"), + INKSCAPE_ICON("edit-clone-link")), new EditVerb(SP_VERB_EDIT_CLONE_SELECT_ORIGINAL, "EditCloneSelectOriginal", N_("Select _Original"), N_("Select the object to which the selected clone is linked"), INKSCAPE_ICON("edit-select-original")), new EditVerb(SP_VERB_EDIT_CLONE_ORIGINAL_PATH_LPE, "EditCloneOriginalPathLPE", N_("Clone original path (LPE)"), - N_("Creates a new path, applies the Clone original LPE, and refers it to the selected path"), INKSCAPE_ICON("edit-clone-link-lpe")), + N_("Creates a new path, applies the Clone original LPE, and refers it to the selected path"), + INKSCAPE_ICON("edit-clone-link-lpe")), new EditVerb(SP_VERB_EDIT_SELECTION_2_MARKER, "ObjectsToMarker", N_("Objects to _Marker"), N_("Convert selection to a line marker"), nullptr), new EditVerb(SP_VERB_EDIT_SELECTION_2_GUIDES, "ObjectsToGuides", N_("Objects to Gu_ides"), @@ -2686,7 +2637,8 @@ Verb *Verb::_base_verbs[] = { N_("Select all objects with the same fill and stroke as the selected objects"), INKSCAPE_ICON("edit-select-same-fill-and-stroke")), new EditVerb(SP_VERB_EDIT_SELECT_SAME_FILL_COLOR, "EditSelectSameFillColor", N_("_Fill Color"), - N_("Select all objects with the same fill as the selected objects"), INKSCAPE_ICON("edit-select-same-fill")), + N_("Select all objects with the same fill as the selected objects"), + INKSCAPE_ICON("edit-select-same-fill")), new EditVerb(SP_VERB_EDIT_SELECT_SAME_STROKE_COLOR, "EditSelectSameStrokeColor", N_("_Stroke Color"), N_("Select all objects with the same stroke as the selected objects"), INKSCAPE_ICON("edit-select-same-stroke-color")), @@ -2730,13 +2682,11 @@ Verb *Verb::_base_verbs[] = { new SelectionVerb(SP_VERB_SELECTION_LOWER, "SelectionLower", N_("_Lower"), N_("Lower selection one step"), INKSCAPE_ICON("selection-lower")), - new SelectionVerb(SP_VERB_SELECTION_STACK_UP, "SelectionStackUp", N_("_Stack up"), N_("Stack selection one step up"), INKSCAPE_ICON("layer-raise")), new SelectionVerb(SP_VERB_SELECTION_STACK_DOWN, "SelectionStackDown", N_("_Stack down"), N_("Stack selection one step down"), INKSCAPE_ICON("layer-lower")), - new SelectionVerb(SP_VERB_SELECTION_GROUP, "SelectionGroup", N_("_Group"), N_("Group selected objects"), INKSCAPE_ICON("object-group")), new SelectionVerb(SP_VERB_SELECTION_UNGROUP, "SelectionUnGroup", N_("_Ungroup"), N_("Ungroup selected groups"), @@ -3039,7 +2989,6 @@ Verb *Verb::_base_verbs[] = { INKSCAPE_ICON("object-flip-vertical")), new ZoomVerb(SP_VERB_FLIP_NONE, "FlipNone", N_("Reset Flip"), N_("Undo any flip"), nullptr), - // WHY ARE THE FOLLOWING ZoomVerbs??? // View @@ -3050,8 +2999,8 @@ Verb *Verb::_base_verbs[] = { INKSCAPE_ICON("show-grid")), new ZoomVerb(SP_VERB_TOGGLE_GUIDES, "ToggleGuides", N_("G_uides"), N_("Show or hide guides (drag from a ruler to create a guide)"), INKSCAPE_ICON("show-guides")), - new ZoomVerb(SP_VERB_TOGGLE_ROTATION_LOCK, "ToggleRotationLock", N_("Lock rotation"), - N_("Lock canvas rotation"), nullptr), + new ZoomVerb(SP_VERB_TOGGLE_ROTATION_LOCK, "ToggleRotationLock", N_("Lock rotation"), N_("Lock canvas rotation"), + nullptr), new ZoomVerb(SP_VERB_TOGGLE_SNAPPING, "ToggleSnapGlobal", N_("Snap"), N_("Enable snapping"), INKSCAPE_ICON("snap")), new ZoomVerb(SP_VERB_TOGGLE_COMMANDS_TOOLBAR, "ToggleCommandsToolbar", N_("_Commands Bar"), N_("Show or hide the Commands bar (under the menu)"), nullptr), @@ -3196,24 +3145,21 @@ Verb *Verb::_base_verbs[] = { // Help URLs // TODO: Better tooltips - new HelpUrlVerb(SP_VERB_HELP_URL_ASK_QUESTION, "HelpUrlAskQuestion", - N_("Ask Us a Question"), N_("Ask Us a Question"), nullptr), - new HelpUrlVerb(SP_VERB_HELP_URL_MAN, "HelpUrlMan", - N_("Command Line Options"), N_("Command Line Options"), nullptr), - new HelpUrlVerb(SP_VERB_HELP_URL_FAQ, "HelpUrlFAQ", - N_("FAQ"), N_("FAQ"), nullptr), - new HelpUrlVerb(SP_VERB_HELP_URL_KEYS, "HelpUrlKeys", - N_("Keys and Mouse Reference"), N_("Keys and Mouse Reference"), nullptr), - new HelpUrlVerb(SP_VERB_HELP_URL_RELEASE_NOTES, "HelpUrlReleaseNotes", - N_("New in This Version"), N_("New in This Version"), nullptr), - new HelpUrlVerb(SP_VERB_HELP_URL_REPORT_BUG, "HelpUrlReportBug", - N_("Report a Bug"), N_("Report a Bug"), nullptr), - new HelpUrlVerb(SP_VERB_HELP_URL_MANUAL, "HelpUrlManual", - N_("Inkscape Manual"), N_("Inkscape Manual"), nullptr), - new HelpUrlVerb(SP_VERB_HELP_URL_SVG11_SPEC, "HelpUrlSvg11Spec", - N_("SVG 1.1 Specification"), N_("SVG 1.1 Specification"), nullptr), - new HelpUrlVerb(SP_VERB_HELP_URL_SVG2_SPEC, "HelpUrlSvg2Spec", - N_("SVG 2 Specification"), N_("SVG 2 Specification"), nullptr), + new HelpUrlVerb(SP_VERB_HELP_URL_ASK_QUESTION, "HelpUrlAskQuestion", N_("Ask Us a Question"), + N_("Ask Us a Question"), nullptr), + new HelpUrlVerb(SP_VERB_HELP_URL_MAN, "HelpUrlMan", N_("Command Line Options"), N_("Command Line Options"), + nullptr), + new HelpUrlVerb(SP_VERB_HELP_URL_FAQ, "HelpUrlFAQ", N_("FAQ"), N_("FAQ"), nullptr), + new HelpUrlVerb(SP_VERB_HELP_URL_KEYS, "HelpUrlKeys", N_("Keys and Mouse Reference"), + N_("Keys and Mouse Reference"), nullptr), + new HelpUrlVerb(SP_VERB_HELP_URL_RELEASE_NOTES, "HelpUrlReleaseNotes", N_("New in This Version"), + N_("New in This Version"), nullptr), + new HelpUrlVerb(SP_VERB_HELP_URL_REPORT_BUG, "HelpUrlReportBug", N_("Report a Bug"), N_("Report a Bug"), nullptr), + new HelpUrlVerb(SP_VERB_HELP_URL_MANUAL, "HelpUrlManual", N_("Inkscape Manual"), N_("Inkscape Manual"), nullptr), + new HelpUrlVerb(SP_VERB_HELP_URL_SVG11_SPEC, "HelpUrlSvg11Spec", N_("SVG 1.1 Specification"), + N_("SVG 1.1 Specification"), nullptr), + new HelpUrlVerb(SP_VERB_HELP_URL_SVG2_SPEC, "HelpUrlSvg2Spec", N_("SVG 2 Specification"), N_("SVG 2 Specification"), + nullptr), // Tutorials new TutorialVerb(SP_VERB_TUTORIAL_BASIC, "TutorialsBasic", N_("Inkscape: _Basic"), @@ -3304,22 +3250,14 @@ Verb *Verb::_base_verbs[] = { N_("Align top edges of objects to the bottom edge of the anchor"), N_("Align top edges of objects to the bottom edge of the anchor"), INKSCAPE_ICON("align-vertical-top")), - new ContextVerb(SP_VERB_ALIGN_BOTH_TOP_LEFT, "AlignBothTopLeft", - N_("Align top-left corners"), - N_("Align top-left corners"), - INKSCAPE_ICON("align-vertical-top-to-anchor")), - new ContextVerb(SP_VERB_ALIGN_BOTH_TOP_RIGHT, "AlignBothTopRight", - N_("Align top-right corners"), - N_("Align top-right corners"), - INKSCAPE_ICON("align-vertical-top-to-anchor")), - new ContextVerb(SP_VERB_ALIGN_BOTH_BOTTOM_RIGHT, "AlignBothBottomRight", - N_("Align bottom-right corners"), - N_("Align bottom-right corners"), - INKSCAPE_ICON("align-vertical-bottom-to-anchor")), - new ContextVerb(SP_VERB_ALIGN_BOTH_BOTTOM_LEFT, "AlignBothBottomLeft", - N_("Align bottom-left corners"), - N_("Align bottom-left corners"), - INKSCAPE_ICON("align-vertical-bottom-to-anchor")), + new ContextVerb(SP_VERB_ALIGN_BOTH_TOP_LEFT, "AlignBothTopLeft", N_("Align top-left corners"), + N_("Align top-left corners"), INKSCAPE_ICON("align-vertical-top-to-anchor")), + new ContextVerb(SP_VERB_ALIGN_BOTH_TOP_RIGHT, "AlignBothTopRight", N_("Align top-right corners"), + N_("Align top-right corners"), INKSCAPE_ICON("align-vertical-top-to-anchor")), + new ContextVerb(SP_VERB_ALIGN_BOTH_BOTTOM_RIGHT, "AlignBothBottomRight", N_("Align bottom-right corners"), + N_("Align bottom-right corners"), INKSCAPE_ICON("align-vertical-bottom-to-anchor")), + new ContextVerb(SP_VERB_ALIGN_BOTH_BOTTOM_LEFT, "AlignBothBottomLeft", N_("Align bottom-left corners"), + N_("Align bottom-left corners"), INKSCAPE_ICON("align-vertical-bottom-to-anchor")), new ContextVerb(SP_VERB_ALIGN_BOTH_TOP_LEFT_TO_ANCHOR, "AlignBothTopLeftToAnchor", N_("Align top-left corners of objects to the bottom-right corner of the anchor"), N_("Align top-left corners of objects to the bottom-right corner of the anchor"), @@ -3340,21 +3278,17 @@ Verb *Verb::_base_verbs[] = { N_("Center on horizontal and vertical axis"), N_("Center on horizontal and vertical axis"), INKSCAPE_ICON("align-vertical-center")), - // Footer - new Verb(SP_VERB_LAST, " '\"invalid id", nullptr, nullptr, nullptr, nullptr) -}; - -std::vector<Inkscape::Verb *> -Verb::getList () { + new Verb(SP_VERB_LAST, " '\"invalid id", nullptr, nullptr, nullptr, nullptr)}; +std::vector<Inkscape::Verb *> Verb::getList() +{ std::vector<Verb *> verbs; // Go through the dynamic verb table - for (auto & _verb : _verbs) { - Verb * verb = _verb.second; - if (verb->get_code() == SP_VERB_INVALID || - verb->get_code() == SP_VERB_NONE || - verb->get_code() == SP_VERB_LAST) { + for (auto &_verb : _verbs) { + Verb *verb = _verb.second; + if (verb->get_code() == SP_VERB_INVALID || verb->get_code() == SP_VERB_NONE || + verb->get_code() == SP_VERB_LAST) { continue; } @@ -3364,24 +3298,23 @@ Verb::getList () { return verbs; }; -void -Verb::list () { +void Verb::list() +{ // Go through the dynamic verb table - for (auto & _verb : _verbs) { - Verb * verb = _verb.second; - if (verb->get_code() == SP_VERB_INVALID || - verb->get_code() == SP_VERB_NONE || - verb->get_code() == SP_VERB_LAST) { + for (auto &_verb : _verbs) { + Verb *verb = _verb.second; + if (verb->get_code() == SP_VERB_INVALID || verb->get_code() == SP_VERB_NONE || + verb->get_code() == SP_VERB_LAST) { continue; } - printf("%s: %s\n", verb->get_id(), verb->get_tip()? verb->get_tip() : verb->get_name()); + printf("%s: %s\n", verb->get_id(), verb->get_tip() ? verb->get_tip() : verb->get_name()); } return; }; -} // namespace Inkscape +} // namespace Inkscape /* Local Variables: diff --git a/src/verbs.h b/src/verbs.h index 42f331f0ecea1d23464a553fbd96c0dadc1e6aee..4569aaded20e984b3119d0b2e40afb7a18afeb65 100644 --- a/src/verbs.h +++ b/src/verbs.h @@ -14,12 +14,12 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include <cstring> -#include <string> #include <glibmm/ustring.h> +#include <string> struct SPAction; class SPDocument; @@ -40,7 +40,8 @@ class View; * which are defined statically in the verb files. There may be * other verbs which are defined dynamically also. */ -enum { +enum +{ /* Header */ SP_VERB_INVALID, /**< A dummy verb to represent doing something wrong. */ SP_VERB_NONE, /**< A dummy verb to represent not having a verb. */ @@ -408,7 +409,7 @@ enum { SP_VERB_LAST }; -char *sp_action_get_title (const SPAction *action); +char *sp_action_get_title(const SPAction *action); #include <map> #include <vector> @@ -420,7 +421,8 @@ namespace Inkscape { * these are 'action factories' as they are used to create * individual actions that are based on a given view. */ -class Verb { +class Verb +{ private: /** An easy to use definition of the table of verbs by code. */ typedef std::map<unsigned int, Inkscape::Verb *> VerbTable; @@ -430,14 +432,16 @@ private: /** The table of statically created verbs which are mostly 'base verbs'. */ - static Verb * _base_verbs[SP_VERB_LAST + 1]; + static Verb *_base_verbs[SP_VERB_LAST + 1]; /* Plus one because there is an entry for SP_VERB_LAST */ /** A string comparison function to be used in the Verb ID lookup to find the different verbs in the hash map. */ - struct ltstr { - bool operator()(const char* s1, const char* s2) const { - if ( (s1 == nullptr) && (s2 != nullptr) ) { + struct ltstr + { + bool operator()(const char *s1, const char *s2) const + { + if ((s1 == nullptr) && (s2 != nullptr)) { return true; } else if (s1 == nullptr || s2 == nullptr) { return false; @@ -457,33 +461,33 @@ private: typedef std::map<Inkscape::UI::View::View *, SPAction *> ActionTable; /** A list of all the actions that have been created for this verb. It is referenced by the view that they are created for. */ - ActionTable * _actions; + ActionTable *_actions; /** A unique textual ID for the verb. */ - char const * _id; + char const *_id; /** The full name of the verb. (shown on menu entries) */ - char const * _name; + char const *_name; /** Tooltip for the verb. */ - char const * _tip; + char const *_tip; - char * _full_tip; // includes shortcut + char *_full_tip; // includes shortcut unsigned int _shortcut; /** Name of the image that represents the verb. */ - char const * _image; + char const *_image; /** * Unique numerical representation of the verb. In most cases * it is a value from the anonymous enum at the top of this * file. */ - unsigned int _code; + unsigned int _code; /** Name of the group the verb belongs to. */ - char const * _group; + char const *_group; /** * Whether this verb is set to default to sensitive or @@ -492,7 +496,6 @@ private: bool _default_sensitive; protected: - /** * Allows for preliminary setting of the \c _default_sensitive * value without effecting existing actions. @@ -502,47 +505,53 @@ protected: * * @param in_val New value. */ - bool set_default_sensitive (bool in_val) { return _default_sensitive = in_val; } + bool set_default_sensitive(bool in_val) { return _default_sensitive = in_val; } public: - /** Accessor to get the \c _default_sensitive value. */ - bool get_default_sensitive () { return _default_sensitive; } + bool get_default_sensitive() { return _default_sensitive; } /** Accessor to get the internal variable. */ - unsigned int get_code () { return _code; } + unsigned int get_code() { return _code; } /** Accessor to get the internal variable. */ - char const * get_id () { return _id; } + char const *get_id() { return _id; } /** Accessor to get the internal variable. */ - char const * get_name () { return _name; } + char const *get_name() { return _name; } /** Accessor to get the internal variable. */ - char const * get_short_tip () { return _tip; }; + char const *get_short_tip() { return _tip; }; /** Accessor to get the internal variable. */ - char const * get_tip () ; + char const *get_tip(); /** Accessor to get the internal variable. */ - char const * get_image () { return _image; } + char const *get_image() { return _image; } /** Get the verbs group */ - char const * get_group () { return _group; } + char const *get_group() { return _group; } /** Set the name after initialization. */ - char const * set_name (char const * name) { _name = name; return _name; } + char const *set_name(char const *name) + { + _name = name; + return _name; + } /** Set the tooltip after initialization. */ - char const * set_tip (char const * tip) { _tip = tip; return _tip; } - + char const *set_tip(char const *tip) + { + _tip = tip; + return _tip; + } protected: - SPAction *make_action_helper (Inkscape::ActionContext const & context, void (*perform_fun)(SPAction *, void *), void *in_pntr = nullptr); - virtual SPAction *make_action (Inkscape::ActionContext const & context); + SPAction *make_action_helper(Inkscape::ActionContext const &context, void (*perform_fun)(SPAction *, void *), + void *in_pntr = nullptr); + virtual SPAction *make_action(Inkscape::ActionContext const &context); public: - /** * Inititalizes the Verb with the parameters. * @@ -564,35 +573,31 @@ public: * @param tip Goes to \c _tip. * @param image Goes to \c _image. */ - Verb(const unsigned int code, - char const * id, - char const * name, - char const * tip, - char const * image, - char const * group) : - _actions(nullptr), - _id(id), - _name(name), - _tip(tip), - _full_tip(nullptr), - _shortcut(0), - _image(image), - _code(code), - _group(group), - _default_sensitive(true) + Verb(const unsigned int code, char const *id, char const *name, char const *tip, char const *image, + char const *group) + : _actions(nullptr) + , _id(id) + , _name(name) + , _tip(tip) + , _full_tip(nullptr) + , _shortcut(0) + , _image(image) + , _code(code) + , _group(group) + , _default_sensitive(true) { _verbs.insert(VerbTable::value_type(_code, this)); _verb_ids.insert(VerbIDTable::value_type(_id, this)); } - Verb (char const * id, char const * name, char const * tip, char const * image, char const * group); - virtual ~Verb (); + Verb(char const *id, char const *name, char const *tip, char const *image, char const *group); + virtual ~Verb(); - SPAction * get_action(Inkscape::ActionContext const & context); + SPAction *get_action(Inkscape::ActionContext const &context); private: - static Verb * get_search (unsigned int code); -public: + static Verb *get_search(unsigned int code); +public: /** * A function to turn a code into a verb. * @@ -605,29 +610,29 @@ public: * @param code The code to be translated * @return A pointer to a verb object or a NULL if not found. */ - static Verb * get (unsigned int code) { + static Verb *get(unsigned int code) + { if (code <= SP_VERB_LAST) { return _base_verbs[code]; } else { return get_search(code); } } - static Verb * getbyid (gchar const * id, bool verbose = true); + static Verb *getbyid(gchar const *id, bool verbose = true); /** * Print a message to stderr indicating that this verb needs a GUI to run */ static bool ensure_desktop_valid(SPAction *action); - static void delete_all_view (Inkscape::UI::View::View * view); - void delete_view (Inkscape::UI::View::View * view); + static void delete_all_view(Inkscape::UI::View::View *view); + void delete_view(Inkscape::UI::View::View *view); - void sensitive (SPDocument * in_doc = nullptr, bool in_sensitive = true); - void name (SPDocument * in_doc = nullptr, Glib::ustring in_name = ""); + void sensitive(SPDocument *in_doc = nullptr, bool in_sensitive = true); + void name(SPDocument *in_doc = nullptr, Glib::ustring in_name = ""); -// Yes, multiple public, protected and private sections are bad. We'll clean that up later + // Yes, multiple public, protected and private sections are bad. We'll clean that up later protected: - /** * Returns the size of the internal base verb array. * @@ -637,16 +642,15 @@ protected: * * @return The size in elements of the internal base array. */ - static int _getBaseListSize() {return G_N_ELEMENTS(_base_verbs);} + static int _getBaseListSize() { return G_N_ELEMENTS(_base_verbs); } public: - static void list (); - static std::vector<Inkscape::Verb *>getList (); + static void list(); + static std::vector<Inkscape::Verb *> getList(); }; /* Verb class */ - -} /* Inkscape namespace */ +} // namespace Inkscape #endif // SEEN_SP_VERBS_H diff --git a/src/version.cpp b/src/version.cpp index 7133ca3f53244e28f509b34127de64b3d3eb83e6..458bb4172403424853a0a9ee76b17f000b3903fe 100644 --- a/src/version.cpp +++ b/src/version.cpp @@ -13,9 +13,10 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "version.h" + #include <glib.h> #include <sstream> -#include "version.h" bool sp_version_from_string(const char *string, Inkscape::Version *version) { @@ -23,25 +24,22 @@ bool sp_version_from_string(const char *string, Inkscape::Version *version) return false; } - try - { + try { std::stringstream ss; // Throw exception if error. ss.exceptions(std::ios::failbit | std::ios::badbit); ss << string; ss >> version->_major; - char tmp=0; + char tmp = 0; ss >> tmp; - ss >>version->_minor; + ss >> version->_minor; // Don't throw exception if failbit gets set (empty string OK). ss.exceptions(std::ios::goodbit); getline(ss, version->_tail); return true; - } - catch(...) - { + } catch (...) { version->_major = 0; version->_minor = 0; version->_tail.clear(); @@ -54,19 +52,14 @@ char *sp_version_to_string(Inkscape::Version version) return g_strdup_printf("%u.%u%s", version._major, version._minor, version._tail.c_str()); } -bool sp_version_inside_range(Inkscape::Version version, - unsigned major_min, unsigned minor_min, - unsigned major_max, unsigned minor_max) +bool sp_version_inside_range(Inkscape::Version version, unsigned major_min, unsigned minor_min, unsigned major_max, + unsigned minor_max) { - if ( version._major < major_min || version._major > major_max ) { + if (version._major < major_min || version._major > major_max) { return false; - } else if ( version._major == major_min && - version._minor <= minor_min ) - { + } else if (version._major == major_min && version._minor <= minor_min) { return false; - } else if ( version._major == major_max && - version._minor >= minor_max ) - { + } else if (version._major == major_max && version._minor >= minor_max) { return false; } else { return true; diff --git a/src/version.h b/src/version.h index ecf10b10983474d9989fd93f9a423d6792bb022a..9327611a3321f606c59b388acd3e3974467d8455 100644 --- a/src/version.h +++ b/src/version.h @@ -18,30 +18,32 @@ namespace Inkscape { -class Version { +class Version +{ public: - - Version() : _major(0), _minor(0) {} + Version() + : _major(0) + , _minor(0) + {} // Note: somebody pollutes our namespace with major() and minor() - Version(unsigned mj, unsigned mn) : _major(mj), _minor(mn) {} - - bool operator>(Version const &other) const { - return _major > other._major || - ( _major == other._major && _minor > other._minor ); + Version(unsigned mj, unsigned mn) + : _major(mj) + , _minor(mn) + {} + + bool operator>(Version const &other) const + { + return _major > other._major || (_major == other._major && _minor > other._minor); } - bool operator==(Version const &other) const { - return _major == other._major && _minor == other._minor; - } + bool operator==(Version const &other) const { return _major == other._major && _minor == other._minor; } - bool operator!=(Version const &other) const { - return _major != other._major || _minor != other._minor; - } + bool operator!=(Version const &other) const { return _major != other._major || _minor != other._minor; } - bool operator<(Version const &other) const { - return _major < other._major || - ( _major == other._major && _minor < other._minor ); + bool operator<(Version const &other) const + { + return _major < other._major || (_major == other._major && _minor < other._minor); } unsigned int _major; @@ -49,15 +51,14 @@ public: std::string _tail; // Development version }; -} +} // namespace Inkscape bool sp_version_from_string(const char *string, Inkscape::Version *version); char *sp_version_to_string(Inkscape::Version version); -bool sp_version_inside_range(Inkscape::Version version, - unsigned major_min, unsigned minor_min, - unsigned major_max, unsigned minor_max); +bool sp_version_inside_range(Inkscape::Version version, unsigned major_min, unsigned minor_min, unsigned major_max, + unsigned minor_max); #endif // SEEN_INKSCAPE_VERSION_H /* diff --git a/src/widgets/desktop-widget.cpp b/src/widgets/desktop-widget.cpp index 36635094dcd7dce68b946aac31a1e53795e73e03..a08bbfc79e3d4f4c22844e4b8aa41d520ae6439f 100644 --- a/src/widgets/desktop-widget.cpp +++ b/src/widgets/desktop-widget.cpp @@ -22,7 +22,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif #include <2geom/rect.h> @@ -33,24 +33,18 @@ #include "desktop-events.h" #include "desktop-widget.h" #include "desktop.h" -#include "document-undo.h" -#include "ege-color-prof-tracker.h" -#include "file.h" -#include "inkscape-version.h" -#include "verbs.h" - #include "display/canvas-arena.h" #include "display/canvas-axonomgrid.h" #include "display/guideline.h" - +#include "document-undo.h" +#include "ege-color-prof-tracker.h" #include "extension/db.h" - +#include "file.h" #include "helper/action.h" - +#include "inkscape-version.h" #include "object/sp-image.h" #include "object/sp-namedview.h" #include "object/sp-root.h" - #include "ui/dialog/dialog-manager.h" #include "ui/dialog/swatches.h" #include "ui/icon-loader.h" @@ -58,18 +52,18 @@ #include "ui/tools/box3d-tool.h" #include "ui/uxmanager.h" #include "ui/widget/button.h" -#include "ui/widget/canvas.h" #include "ui/widget/canvas-grid.h" +#include "ui/widget/canvas.h" #include "ui/widget/dock.h" #include "ui/widget/ink-ruler.h" #include "ui/widget/layer-selector.h" #include "ui/widget/selected-style.h" #include "ui/widget/spin-button-tool-item.h" #include "ui/widget/unit-tracker.h" +#include "verbs.h" // TEMP #include "ui/desktop/menubar.h" - #include "util/units.h" // We're in the "widgets" directory, so no need to explicitly prefix these: @@ -82,60 +76,65 @@ #endif using Inkscape::DocumentUndo; -using Inkscape::UI::Widget::UnitTracker; -using Inkscape::UI::UXManager; using Inkscape::UI::ToolboxFactory; +using Inkscape::UI::UXManager; +using Inkscape::UI::Widget::UnitTracker; using Inkscape::Util::unit_table; - //--------------------------------------------------------------------- /* SPDesktopWidget */ -class CMSPrefWatcher { +class CMSPrefWatcher +{ public: - CMSPrefWatcher() : - _dpw(*this), - _spw(*this), - _tracker(ege_color_prof_tracker_new(nullptr)) + CMSPrefWatcher() + : _dpw(*this) + , _spw(*this) + , _tracker(ege_color_prof_tracker_new(nullptr)) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - g_signal_connect( G_OBJECT(_tracker), "modified", G_CALLBACK(hook), this ); + g_signal_connect(G_OBJECT(_tracker), "modified", G_CALLBACK(hook), this); prefs->addObserver(_dpw); prefs->addObserver(_spw); } virtual ~CMSPrefWatcher() = default; - //virtual void notify(PrefValue &); - void add( SPDesktopWidget* dtw ) { - _widget_list.push_back(dtw); - } - void remove( SPDesktopWidget* dtw ) { - _widget_list.remove(dtw); - } + // virtual void notify(PrefValue &); + void add(SPDesktopWidget *dtw) { _widget_list.push_back(dtw); } + void remove(SPDesktopWidget *dtw) { _widget_list.remove(dtw); } private: static void hook(EgeColorProfTracker *tracker, gint b, CMSPrefWatcher *watcher); - class DisplayProfileWatcher : public Inkscape::Preferences::Observer { + class DisplayProfileWatcher : public Inkscape::Preferences::Observer + { public: - DisplayProfileWatcher(CMSPrefWatcher &pw) : Observer("/options/displayprofile"), _pw(pw) {} - void notify(Inkscape::Preferences::Entry const &/*val*/) override { + DisplayProfileWatcher(CMSPrefWatcher &pw) + : Observer("/options/displayprofile") + , _pw(pw) + {} + void notify(Inkscape::Preferences::Entry const & /*val*/) override + { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); _pw._setCmsSensitive(!prefs->getString("/options/displayprofile/uri").empty()); _pw._refreshAll(); } + private: CMSPrefWatcher &_pw; }; DisplayProfileWatcher _dpw; - class SoftProofWatcher : public Inkscape::Preferences::Observer { + class SoftProofWatcher : public Inkscape::Preferences::Observer + { public: - SoftProofWatcher(CMSPrefWatcher &pw) : Observer("/options/softproof"), _pw(pw) {} - void notify(Inkscape::Preferences::Entry const &) override { - _pw._refreshAll(); - } + SoftProofWatcher(CMSPrefWatcher &pw) + : Observer("/options/softproof") + , _pw(pw) + {} + void notify(Inkscape::Preferences::Entry const &) override { _pw._refreshAll(); } + private: CMSPrefWatcher &_pw; }; @@ -145,7 +144,7 @@ private: void _refreshAll(); void _setCmsSensitive(bool value); - std::list<SPDesktopWidget*> _widget_list; + std::list<SPDesktopWidget *> _widget_list; EgeColorProfTracker *_tracker; friend class DisplayProfileWatcher; @@ -155,16 +154,14 @@ private: #if defined(HAVE_LIBLCMS2) void CMSPrefWatcher::hook(EgeColorProfTracker * /*tracker*/, gint monitor, CMSPrefWatcher * /*watcher*/) { - unsigned char* buf = nullptr; + unsigned char *buf = nullptr; guint len = 0; - ege_color_prof_tracker_get_profile_for( monitor, reinterpret_cast<gpointer*>(&buf), &len ); - Glib::ustring id = Inkscape::CMSSystem::setDisplayPer( buf, len, monitor ); + ege_color_prof_tracker_get_profile_for(monitor, reinterpret_cast<gpointer *>(&buf), &len); + Glib::ustring id = Inkscape::CMSSystem::setDisplayPer(buf, len, monitor); } #else -void CMSPrefWatcher::hook(EgeColorProfTracker * /*tracker*/, gint /*monitor*/, CMSPrefWatcher * /*watcher*/) -{ -} +void CMSPrefWatcher::hook(EgeColorProfTracker * /*tracker*/, gint /*monitor*/, CMSPrefWatcher * /*watcher*/) {} #endif // defined(HAVE_LIBLCMS2) /// @todo Use conditional compilation in saner places. The whole PrefWatcher @@ -172,7 +169,7 @@ void CMSPrefWatcher::hook(EgeColorProfTracker * /*tracker*/, gint /*monitor*/, C void CMSPrefWatcher::_refreshAll() { #if defined(HAVE_LIBLCMS2) - for (auto & it : _widget_list) { + for (auto &it : _widget_list) { it->requestCanvasUpdate(); } #endif // defined(HAVE_LIBLCMS2) @@ -181,21 +178,20 @@ void CMSPrefWatcher::_refreshAll() void CMSPrefWatcher::_setCmsSensitive(bool enabled) { #if defined(HAVE_LIBLCMS2) - for ( auto dtw : _widget_list ) { + for (auto dtw : _widget_list) { auto cms_adj = dtw->get_canvas_grid()->GetCmsAdjust(); - if ( cms_adj->get_sensitive() != enabled ) { + if (cms_adj->get_sensitive() != enabled) { dtw->cms_adjust_set_sensitive(enabled); } } #else - (void) enabled; + (void)enabled; #endif // defined(HAVE_LIBLCMS2) } -static CMSPrefWatcher* watcher = nullptr; +static CMSPrefWatcher *watcher = nullptr; -void -SPDesktopWidget::setMessage (Inkscape::MessageType type, const gchar *message) +void SPDesktopWidget::setMessage(Inkscape::MessageType type, const gchar *message) { _select_status->set_markup(message ? message : ""); @@ -207,8 +203,7 @@ SPDesktopWidget::setMessage (Inkscape::MessageType type, const gchar *message) _select_status->set_tooltip_text(_select_status->get_text()); } -Geom::Point -SPDesktopWidget::window_get_pointer() +Geom::Point SPDesktopWidget::window_get_pointer() { int x, y; auto window = _canvas->get_window(); @@ -254,14 +249,14 @@ SPDesktopWidget::SPDesktopWidget() dtw->_vbox->pack_end(*Glib::wrap(dtw->aux_toolbox), false, true); dtw->snap_toolbox = ToolboxFactory::createSnapToolbox(); - ToolboxFactory::setOrientation( dtw->snap_toolbox, GTK_ORIENTATION_VERTICAL ); + ToolboxFactory::setOrientation(dtw->snap_toolbox, GTK_ORIENTATION_VERTICAL); dtw->_hbox->pack_end(*Glib::wrap(dtw->snap_toolbox), false, true); dtw->commands_toolbox = ToolboxFactory::createCommandsToolbox(); dtw->_vbox->pack_end(*Glib::wrap(dtw->commands_toolbox), false, true); dtw->tool_toolbox = ToolboxFactory::createToolToolbox(); - ToolboxFactory::setOrientation( dtw->tool_toolbox, GTK_ORIENTATION_VERTICAL ); + ToolboxFactory::setOrientation(dtw->tool_toolbox, GTK_ORIENTATION_VERTICAL); dtw->_hbox->pack_start(*Glib::wrap(dtw->tool_toolbox), false, true); /* Canvas Grid (canvas, rulers, scrollbars, etc.) */ @@ -276,9 +271,8 @@ SPDesktopWidget::SPDesktopWidget() #endif // defined(HAVE_LIBLCMS2) /* Dock */ - bool create_dock = - prefs->getIntLimited("/options/dialogtype/value", Inkscape::UI::Dialog::FLOATING, 0, 1) == - Inkscape::UI::Dialog::DOCK; + bool create_dock = prefs->getIntLimited("/options/dialogtype/value", Inkscape::UI::Dialog::FLOATING, 0, 1) == + Inkscape::UI::Dialog::DOCK; if (create_dock) { dtw->_dock = new Inkscape::UI::Widget::Dock(); @@ -289,7 +283,7 @@ SPDesktopWidget::SPDesktopWidget() paned->pack2(dtw->_dock->getWidget(), Gtk::FILL); /* Prevent the paned from catching F6 and F8 by unsetting the default callbacks */ - if (GtkPanedClass *paned_class = GTK_PANED_CLASS (G_OBJECT_GET_CLASS (paned->gobj()))) { + if (GtkPanedClass *paned_class = GTK_PANED_CLASS(G_OBJECT_GET_CLASS(paned->gobj()))) { paned_class->cycle_child_focus = nullptr; paned_class->cycle_handle_focus = nullptr; } @@ -311,8 +305,7 @@ SPDesktopWidget::SPDesktopWidget() dtw->_statusbar->pack_start(*dtw->_selected_style, false, false); // Separator - dtw->_statusbar->pack_start(*Gtk::manage(new Gtk::Separator(Gtk::ORIENTATION_VERTICAL)), - false, false); + dtw->_statusbar->pack_start(*Gtk::manage(new Gtk::Separator(Gtk::ORIENTATION_VERTICAL)), false, false); // Layer Selector dtw->layer_selector = Gtk::manage(new Inkscape::UI::Widget::LayerSelector(nullptr)); @@ -328,13 +321,14 @@ SPDesktopWidget::SPDesktopWidget() dtw->_select_status->set_size_request(1, -1); // Display the initial welcome message in the statusbar - dtw->_select_status->set_markup(_("<b>Welcome to Inkscape!</b> Use shape or freehand tools to create objects; use selector (arrow) to move or transform them.")); + dtw->_select_status->set_markup(_("<b>Welcome to Inkscape!</b> Use shape or freehand tools to create objects; use " + "selector (arrow) to move or transform them.")); dtw->_statusbar->pack_start(*dtw->_select_status, true, true); - // Zoom status spinbutton --------------- - auto zoom_adj = Gtk::Adjustment::create(100.0, log(SP_DESKTOP_ZOOM_MIN)/log(2), log(SP_DESKTOP_ZOOM_MAX)/log(2), 0.1); + auto zoom_adj = + Gtk::Adjustment::create(100.0, log(SP_DESKTOP_ZOOM_MIN) / log(2), log(SP_DESKTOP_ZOOM_MAX) / log(2), 0.1); dtw->_zoom_status = Gtk::manage(new Inkscape::UI::Widget::SpinButton(zoom_adj)); dtw->_zoom_status->set_defocus_widget(dtw->_canvas); @@ -345,14 +339,21 @@ SPDesktopWidget::SPDesktopWidget() dtw->_zoom_status->set_update_policy(Gtk::UPDATE_ALWAYS); // Callbacks - dtw->_zoom_status_input_connection = dtw->_zoom_status->signal_input().connect(sigc::mem_fun(dtw, &SPDesktopWidget::zoom_input)); - dtw->_zoom_status_output_connection = dtw->_zoom_status->signal_output().connect(sigc::mem_fun(dtw, &SPDesktopWidget::zoom_output)); - dtw->_zoom_status_value_changed_connection = dtw->_zoom_status->signal_value_changed().connect(sigc::mem_fun(dtw, &SPDesktopWidget::zoom_value_changed)); - dtw->_zoom_status_populate_popup_connection = dtw->_zoom_status->signal_populate_popup().connect(sigc::mem_fun(dtw, &SPDesktopWidget::zoom_populate_popup)); + dtw->_zoom_status_input_connection = + dtw->_zoom_status->signal_input().connect(sigc::mem_fun(dtw, &SPDesktopWidget::zoom_input)); + dtw->_zoom_status_output_connection = + dtw->_zoom_status->signal_output().connect(sigc::mem_fun(dtw, &SPDesktopWidget::zoom_output)); + dtw->_zoom_status_value_changed_connection = + dtw->_zoom_status->signal_value_changed().connect(sigc::mem_fun(dtw, &SPDesktopWidget::zoom_value_changed)); + dtw->_zoom_status_populate_popup_connection = + dtw->_zoom_status->signal_populate_popup().connect(sigc::mem_fun(dtw, &SPDesktopWidget::zoom_populate_popup)); // Style auto css_provider_spinbutton = Gtk::CssProvider::create(); - css_provider_spinbutton->load_from_data("* { padding-left: 2px; padding-right: 2px; padding-top: 0px; padding-bottom: 0px;}"); // Shouldn't this be in a style sheet? Used also by rotate. + css_provider_spinbutton->load_from_data( + "* { padding-left: 2px; padding-right: 2px; padding-top: 0px; padding-bottom: 0px;}"); // Shouldn't this be in a + // style sheet? Used also + // by rotate. dtw->_zoom_status->set_name("ZoomStatus"); auto context_zoom = dtw->_zoom_status->get_style_context(); @@ -377,17 +378,20 @@ SPDesktopWidget::SPDesktopWidget() dtw->_rotation_status->set_update_policy(Gtk::UPDATE_ALWAYS); // Callbacks - dtw->_rotation_status_input_connection = dtw->_rotation_status->signal_input().connect(sigc::mem_fun(dtw, &SPDesktopWidget::rotation_input), false); - dtw->_rotation_status_output_connection = dtw->_rotation_status->signal_output().connect(sigc::mem_fun(dtw, &SPDesktopWidget::rotation_output)); - dtw->_rotation_status_value_changed_connection = dtw->_rotation_status->signal_value_changed().connect(sigc::mem_fun(dtw, &SPDesktopWidget::rotation_value_changed)); - dtw->_rotation_status_populate_popup_connection = dtw->_rotation_status->signal_populate_popup().connect(sigc::mem_fun(dtw, &SPDesktopWidget::rotation_populate_popup)); + dtw->_rotation_status_input_connection = + dtw->_rotation_status->signal_input().connect(sigc::mem_fun(dtw, &SPDesktopWidget::rotation_input), false); + dtw->_rotation_status_output_connection = + dtw->_rotation_status->signal_output().connect(sigc::mem_fun(dtw, &SPDesktopWidget::rotation_output)); + dtw->_rotation_status_value_changed_connection = dtw->_rotation_status->signal_value_changed().connect( + sigc::mem_fun(dtw, &SPDesktopWidget::rotation_value_changed)); + dtw->_rotation_status_populate_popup_connection = dtw->_rotation_status->signal_populate_popup().connect( + sigc::mem_fun(dtw, &SPDesktopWidget::rotation_populate_popup)); // Style dtw->_rotation_status->set_name("RotationStatus"); auto context_rotation = dtw->_rotation_status->get_style_context(); context_rotation->add_provider(css_provider_spinbutton, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); - // Cursor coordinates dtw->_coord_status = Gtk::manage(new Gtk::Grid()); dtw->_coord_status->set_name("CoordinateAndZStatus"); @@ -433,13 +437,13 @@ SPDesktopWidget::SPDesktopWidget() // --------------- Color Management ---------------- // dtw->_tracker = ege_color_prof_tracker_new(GTK_WIDGET(dtw->layer_selector->gobj())); #if defined(HAVE_LIBLCMS2) - bool fromDisplay = prefs->getBool( "/options/displayprofile/from_display"); - if ( fromDisplay ) { + bool fromDisplay = prefs->getBool("/options/displayprofile/from_display"); + if (fromDisplay) { auto id = Inkscape::CMSSystem::getDisplayId(0); dtw->_canvas->set_cms_key(id); dtw->cms_adjust_set_sensitive(!id.empty()); } - g_signal_connect( G_OBJECT(dtw->_tracker), "changed", G_CALLBACK(SPDesktopWidget::color_profile_event), dtw ); + g_signal_connect(G_OBJECT(dtw->_tracker), "changed", G_CALLBACK(SPDesktopWidget::color_profile_event), dtw); #endif // defined(HAVE_LIBLCMS2) // ------------------ Finish Up -------------------- // @@ -452,15 +456,14 @@ SPDesktopWidget::SPDesktopWidget() * Called before SPDesktopWidget destruction. * (Might be called more than once) */ -void -SPDesktopWidget::on_unrealize() +void SPDesktopWidget::on_unrealize() { auto dtw = this; UXManager::getInstance()->delTrack(dtw); if (dtw->desktop) { - if ( watcher ) { + if (watcher) { watcher->remove(dtw); } @@ -491,7 +494,7 @@ SPDesktopWidget::on_unrealize() INKSCAPE.remove_desktop(dtw->desktop); // clears selection and event_context dtw->modified_connection.disconnect(); dtw->desktop->destroy(); - Inkscape::GC::release (dtw->desktop); + Inkscape::GC::release(dtw->desktop); dtw->desktop = nullptr; } @@ -509,11 +512,9 @@ SPDesktopWidget::~SPDesktopWidget() * The title has form file name: desktop number - Inkscape. * The desktop number is only shown if it's 2 or higher, */ -void -SPDesktopWidget::updateTitle(gchar const* uri) +void SPDesktopWidget::updateTitle(gchar const *uri) { if (window) { - SPDocument *doc = this->desktop->doc(); std::string Name; @@ -538,8 +539,8 @@ SPDesktopWidget::updateTitle(gchar const* uri) } if (desktop->getColorMode() != Inkscape::COLORMODE_NORMAL && - desktop->getMode() != Inkscape::RENDERMODE_NORMAL) { - Name += ", "; + desktop->getMode() != Inkscape::RENDERMODE_NORMAL) { + Name += ", "; } if (desktop->getColorMode() == Inkscape::COLORMODE_GRAYSCALE) { @@ -548,7 +549,7 @@ SPDesktopWidget::updateTitle(gchar const* uri) Name += N_("print colors preview"); } - if (*Name.rbegin() == '(') { // Can not use C++11 .back() or .pop_back() with ustring! + if (*Name.rbegin() == '(') { // Can not use C++11 .back() or .pop_back() with ustring! Name.erase(Name.size() - 2); } else { Name += ")"; @@ -567,12 +568,11 @@ SPDesktopWidget::updateTitle(gchar const* uri) gdl_dock_master_foreach_toplevel(master, FALSE, (GFunc)gdl_dock_object_set_long_name, (void *)Name.c_str()); } - window->set_title (Name); + window->set_title(Name); } } -Inkscape::UI::Widget::Dock* -SPDesktopWidget::getDock() +Inkscape::UI::Widget::Dock *SPDesktopWidget::getDock() { return _dock; } @@ -603,7 +603,7 @@ void SPDesktopWidget::on_size_allocate(Gtk::Allocation &allocation) double newshortside = _canvas->get_area_world().minExtent(); zoom *= newshortside / oldshortside; } - dtw->desktop->zoom_absolute_center_point (midpoint, zoom); + dtw->desktop->zoom_absolute_center_point(midpoint, zoom); } else { parent_type::on_size_allocate(allocation); } @@ -632,11 +632,12 @@ void SPDesktopWidget::on_realize() parent_type::on_realize(); - Geom::Rect d = Geom::Rect::from_xywh(Geom::Point(0,0), (dtw->desktop->doc())->getDimensions()); + Geom::Rect d = Geom::Rect::from_xywh(Geom::Point(0, 0), (dtw->desktop->doc())->getDimensions()); - if (d.width() < 1.0 || d.height() < 1.0) return; + if (d.width() < 1.0 || d.height() < 1.0) + return; - dtw->desktop->set_display_area (d, 10); + dtw->desktop->set_display_area(d, 10); dtw->updateNamedview(); gchar *gtkThemeName; @@ -687,11 +688,7 @@ void SPDesktopWidget::on_realize() // move some items to "Inkscape" menu unsigned app_menu_verbs[] = { - SP_VERB_NONE, - SP_VERB_DIALOG_INPUT, - SP_VERB_DIALOG_DISPLAY, - SP_VERB_NONE, - SP_VERB_HELP_ABOUT, + SP_VERB_NONE, SP_VERB_DIALOG_INPUT, SP_VERB_DIALOG_DISPLAY, SP_VERB_NONE, SP_VERB_HELP_ABOUT, }; for (auto verb : app_menu_verbs) { GtkWidget *menuitem = nullptr; @@ -719,17 +716,17 @@ void SPDesktopWidget::updateNamedview() // connected twice rather than disconnecting the first connection modified_connection.disconnect(); - modified_connection = desktop->namedview->connectModified(sigc::mem_fun(*this, &SPDesktopWidget::namedviewModified)); + modified_connection = + desktop->namedview->connectModified(sigc::mem_fun(*this, &SPDesktopWidget::namedviewModified)); namedviewModified(desktop->namedview, SP_OBJECT_MODIFIED_FLAG); - updateTitle( desktop->doc()->getDocumentName() ); + updateTitle(desktop->doc()->getDocumentName()); } /** * Callback to handle desktop widget event. */ -gint -SPDesktopWidget::event(GtkWidget *widget, GdkEvent *event, SPDesktopWidget *dtw) +gint SPDesktopWidget::event(GtkWidget *widget, GdkEvent *event, SPDesktopWidget *dtw) { if (event->type == GDK_BUTTON_PRESS) { // defocus any spinbuttons @@ -738,9 +735,9 @@ SPDesktopWidget::event(GtkWidget *widget, GdkEvent *event, SPDesktopWidget *dtw) if ((event->type == GDK_BUTTON_PRESS) && (event->button.button == 3)) { if (event->button.state & GDK_SHIFT_MASK) { - sp_canvas_arena_set_sticky (SP_CANVAS_ARENA (dtw->desktop->drawing), TRUE); + sp_canvas_arena_set_sticky(SP_CANVAS_ARENA(dtw->desktop->drawing), TRUE); } else { - sp_canvas_arena_set_sticky (SP_CANVAS_ARENA (dtw->desktop->drawing), FALSE); + sp_canvas_arena_set_sticky(SP_CANVAS_ARENA(dtw->desktop->drawing), FALSE); } } @@ -751,9 +748,8 @@ SPDesktopWidget::event(GtkWidget *widget, GdkEvent *event, SPDesktopWidget *dtw) // 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 ((event->type == GDK_KEY_PRESS || event->type == GDK_KEY_RELEASE) - && !dtw->_canvas->get_current_item()) { - return sp_desktop_root_handler (nullptr, event, dtw->desktop); + if ((event->type == GDK_KEY_PRESS || event->type == GDK_KEY_RELEASE) && !dtw->_canvas->get_current_item()) { + return sp_desktop_root_handler(nullptr, event, dtw->desktop); } } @@ -761,8 +757,7 @@ SPDesktopWidget::event(GtkWidget *widget, GdkEvent *event, SPDesktopWidget *dtw) } #if defined(HAVE_LIBLCMS2) -void -SPDesktopWidget::color_profile_event(EgeColorProfTracker */*tracker*/, SPDesktopWidget *dtw) +void SPDesktopWidget::color_profile_event(EgeColorProfTracker * /*tracker*/, SPDesktopWidget *dtw) { // Handle profile changes GdkWindow *window = dtw->get_window()->gobj(); @@ -778,81 +773,75 @@ SPDesktopWidget::color_profile_event(EgeColorProfTracker */*tracker*/, SPDesktop // Now loop through the set of monitors and figure out whether this monitor matches for (int i_monitor = 0; i_monitor < n_monitors; ++i_monitor) { auto monitor_at_index = gdk_display_get_monitor(display, i_monitor); - if (monitor_at_index == monitor) monitorNum = i_monitor; + if (monitor_at_index == monitor) + monitorNum = i_monitor; } - Glib::ustring id = Inkscape::CMSSystem::getDisplayId( monitorNum ); + Glib::ustring id = Inkscape::CMSSystem::getDisplayId(monitorNum); dtw->_canvas->set_cms_key(id); dtw->requestCanvasUpdate(); dtw->cms_adjust_set_sensitive(!id.empty()); } -#else // defined(HAVE_LIBLCMS2) -void sp_dtw_color_profile_event(EgeColorProfTracker */*tracker*/, SPDesktopWidget * /*dtw*/) -{ -} +#else // defined(HAVE_LIBLCMS2) +void sp_dtw_color_profile_event(EgeColorProfTracker * /*tracker*/, SPDesktopWidget * /*dtw*/) {} #endif // defined(HAVE_LIBLCMS2) -void -SPDesktopWidget::update_guides_lock() +void SPDesktopWidget::update_guides_lock() { bool down = _canvas_grid->GetGuideLock()->get_active(); - auto doc = desktop->getDocument(); - auto nv = desktop->getNamedView(); + auto doc = desktop->getDocument(); + auto nv = desktop->getNamedView(); - if ( down != nv->lockguides ) { + if (down != nv->lockguides) { nv->lockguides = down; sp_namedview_guides_toggle_lock(doc, nv); if (down) { - setMessage (Inkscape::NORMAL_MESSAGE, _("Locked all guides")); + setMessage(Inkscape::NORMAL_MESSAGE, _("Locked all guides")); } else { - setMessage (Inkscape::NORMAL_MESSAGE, _("Unlocked all guides")); + setMessage(Inkscape::NORMAL_MESSAGE, _("Unlocked all guides")); } } } #if defined(HAVE_LIBLCMS2) -void -SPDesktopWidget::cms_adjust_toggled() +void SPDesktopWidget::cms_adjust_toggled() { auto _cms_adjust = _canvas_grid->GetCmsAdjust(); bool down = _cms_adjust->get_active(); - if ( down != _canvas->get_cms_active() ) { + if (down != _canvas->get_cms_active()) { _canvas->set_cms_active(down); desktop->redrawDesktop(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setBool("/options/displayprofile/enable", down); if (down) { - setMessage (Inkscape::NORMAL_MESSAGE, _("Color-managed display is <b>enabled</b> in this window")); + setMessage(Inkscape::NORMAL_MESSAGE, _("Color-managed display is <b>enabled</b> in this window")); } else { - setMessage (Inkscape::NORMAL_MESSAGE, _("Color-managed display is <b>disabled</b> in this window")); + setMessage(Inkscape::NORMAL_MESSAGE, _("Color-managed display is <b>disabled</b> in this window")); } } } #endif // defined(HAVE_LIBLCMS2) -void -SPDesktopWidget::cms_adjust_set_sensitive(bool enabled) +void SPDesktopWidget::cms_adjust_set_sensitive(bool enabled) { - Inkscape::Verb* verb = Inkscape::Verb::get( SP_VERB_VIEW_CMS_TOGGLE ); - if ( verb ) { + Inkscape::Verb *verb = Inkscape::Verb::get(SP_VERB_VIEW_CMS_TOGGLE); + if (verb) { SPAction *act = verb->get_action(Inkscape::ActionContext(getView())); - if ( act ) { - sp_action_set_sensitive( act, enabled ); + if (act) { + sp_action_set_sensitive(act, enabled); } } _canvas_grid->GetCmsAdjust()->set_sensitive(enabled); } -void -sp_dtw_desktop_activate (SPDesktopWidget */*dtw*/) +void sp_dtw_desktop_activate(SPDesktopWidget * /*dtw*/) { /* update active desktop indicator */ } -void -sp_dtw_desktop_deactivate (SPDesktopWidget */*dtw*/) +void sp_dtw_desktop_deactivate(SPDesktopWidget * /*dtw*/) { /* update inactive desktop indicator */ } @@ -863,8 +852,7 @@ sp_dtw_desktop_deactivate (SPDesktopWidget */*dtw*/) * to save, discard, or cancel. Returns TRUE if the shutdown operation * is cancelled or if the save is cancelled or fails, FALSE otherwise. */ -bool -SPDesktopWidget::shutdown() +bool SPDesktopWidget::shutdown() { g_assert(desktop != nullptr); @@ -876,12 +864,13 @@ SPDesktopWidget::shutdown() _("<span weight=\"bold\" size=\"larger\">Save changes to document \"%s\" before closing?</span>\n\n" "If you close without saving, your changes will be discarded."), doc->getDocumentName()); - Gtk::MessageDialog dialog = Gtk::MessageDialog(*toplevel_window, message, true, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE); + Gtk::MessageDialog dialog = + Gtk::MessageDialog(*toplevel_window, message, true, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE); dialog.property_destroy_with_parent() = true; // fix for bug lp:168809 Gtk::Container *ma = dialog.get_message_area(); - std::vector<Gtk::Widget*> ma_labels = ma->get_children(); + std::vector<Gtk::Widget *> ma_labels = ma->get_children(); ma_labels[0]->set_can_focus(false); Gtk::Button close_button(_("Close _without saving"), true); @@ -895,37 +884,38 @@ SPDesktopWidget::shutdown() gint response = dialog.run(); switch (response) { - case GTK_RESPONSE_YES: - { - sp_namedview_document_from_window(desktop); - if (!sp_file_save_document(*window, doc.get())) { - // save dialog cancelled or save failed - return TRUE; - } + case GTK_RESPONSE_YES: { + sp_namedview_document_from_window(desktop); + if (!sp_file_save_document(*window, doc.get())) { + // save dialog cancelled or save failed + return TRUE; + } - break; - } - case GTK_RESPONSE_NO: - break; - default: // cancel pressed, or dialog was closed - return TRUE; - break; + break; + } + case GTK_RESPONSE_NO: + break; + default: // cancel pressed, or dialog was closed + return TRUE; + break; } } /* Code to check data loss */ bool allow_data_loss = FALSE; while (doc->getReprRoot()->attribute("inkscape:dataloss") != nullptr && allow_data_loss == FALSE) { auto toplevel_window = window; - Glib::ustring message = g_markup_printf_escaped( - _("<span weight=\"bold\" size=\"larger\">The file \"%s\" was saved with a format that may cause data loss!</span>\n\n" - "Do you want to save this file as Inkscape SVG?"), - doc->getDocumentName() ? doc->getDocumentName() : "Unnamed"); - Gtk::MessageDialog dialog = Gtk::MessageDialog(*toplevel_window, message, true, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE); + Glib::ustring message = + g_markup_printf_escaped(_("<span weight=\"bold\" size=\"larger\">The file \"%s\" was saved with a " + "format that may cause data loss!</span>\n\n" + "Do you want to save this file as Inkscape SVG?"), + doc->getDocumentName() ? doc->getDocumentName() : "Unnamed"); + Gtk::MessageDialog dialog = + Gtk::MessageDialog(*toplevel_window, message, true, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE); dialog.property_destroy_with_parent() = true; // fix for bug lp:168809 Gtk::Container *ma = dialog.get_message_area(); - std::vector<Gtk::Widget*> ma_labels = ma->get_children(); + std::vector<Gtk::Widget *> ma_labels = ma->get_children(); ma_labels[0]->set_can_focus(false); Gtk::Button close_button(_("Close _without saving"), true); @@ -943,21 +933,20 @@ SPDesktopWidget::shutdown() gint response = dialog.run(); switch (response) { - case GTK_RESPONSE_YES: - { - if (!sp_file_save_dialog(*window, doc.get(), Inkscape::Extension::FILE_SAVE_METHOD_INKSCAPE_SVG)) { - // save dialog cancelled or save failed - return TRUE; - } + case GTK_RESPONSE_YES: { + if (!sp_file_save_dialog(*window, doc.get(), Inkscape::Extension::FILE_SAVE_METHOD_INKSCAPE_SVG)) { + // save dialog cancelled or save failed + return TRUE; + } - break; - } - case GTK_RESPONSE_NO: - allow_data_loss = TRUE; - break; - default: // cancel pressed, or dialog was closed - return TRUE; - break; + break; + } + case GTK_RESPONSE_NO: + allow_data_loss = TRUE; + break; + default: // cancel pressed, or dialog was closed + return TRUE; + break; } } } @@ -997,47 +986,43 @@ void SPDesktopWidget::storeDesktopPosition() /** * \pre this->desktop->main != 0 */ -void -SPDesktopWidget::requestCanvasUpdate() { +void SPDesktopWidget::requestCanvasUpdate() +{ // ^^ also this->desktop != 0 g_return_if_fail(this->desktop != nullptr); g_return_if_fail(this->desktop->main != nullptr); - gtk_widget_queue_draw (GTK_WIDGET (SP_CANVAS_ITEM (this->desktop->main)->canvas->gobj())); + gtk_widget_queue_draw(GTK_WIDGET(SP_CANVAS_ITEM(this->desktop->main)->canvas->gobj())); } -void -SPDesktopWidget::requestCanvasUpdateAndWait() { +void SPDesktopWidget::requestCanvasUpdateAndWait() +{ requestCanvasUpdate(); while (gtk_events_pending()) - gtk_main_iteration_do(FALSE); - + gtk_main_iteration_do(FALSE); } -void -SPDesktopWidget::enableInteraction() +void SPDesktopWidget::enableInteraction() { - g_return_if_fail(_interaction_disabled_counter > 0); + g_return_if_fail(_interaction_disabled_counter > 0); - _interaction_disabled_counter--; + _interaction_disabled_counter--; - if (_interaction_disabled_counter == 0) { - this->set_sensitive(); - } + if (_interaction_disabled_counter == 0) { + this->set_sensitive(); + } } -void -SPDesktopWidget::disableInteraction() +void SPDesktopWidget::disableInteraction() { - if (_interaction_disabled_counter == 0) { - this->set_sensitive(false); - } + if (_interaction_disabled_counter == 0) { + this->set_sensitive(false); + } - _interaction_disabled_counter++; + _interaction_disabled_counter++; } -void -SPDesktopWidget::setCoordinateStatus(Geom::Point p) +void SPDesktopWidget::setCoordinateStatus(Geom::Point p) { gchar *cstr; cstr = g_strdup_printf("%7.2f", _dt2r * p[Geom::X]); @@ -1049,38 +1034,32 @@ SPDesktopWidget::setCoordinateStatus(Geom::Point p) g_free(cstr); } -void -SPDesktopWidget::letZoomGrabFocus() +void SPDesktopWidget::letZoomGrabFocus() { - if (_zoom_status) _zoom_status->grab_focus(); + if (_zoom_status) + _zoom_status->grab_focus(); } -void -SPDesktopWidget::getWindowGeometry (gint &x, gint &y, gint &w, gint &h) +void SPDesktopWidget::getWindowGeometry(gint &x, gint &y, gint &w, gint &h) { - if (window) - { - window->get_size (w, h); - window->get_position (x, y); + if (window) { + window->get_size(w, h); + window->get_position(x, y); } } -void -SPDesktopWidget::setWindowPosition (Geom::Point p) +void SPDesktopWidget::setWindowPosition(Geom::Point p) { - if (window) - { - window->move (gint(round(p[Geom::X])), gint(round(p[Geom::Y]))); + if (window) { + window->move(gint(round(p[Geom::X])), gint(round(p[Geom::Y]))); } } -void -SPDesktopWidget::setWindowSize (gint w, gint h) +void SPDesktopWidget::setWindowSize(gint w, gint h) { - if (window) - { - window->set_default_size (w, h); - window->resize (w, h); + if (window) { + window->set_default_size(w, h); + window->resize(w, h); } } @@ -1090,13 +1069,11 @@ SPDesktopWidget::setWindowSize (gint w, gint h) * the document window. The document window must be restored by rightclicking * the taskbar button and pressing "Restore" */ -void -SPDesktopWidget::setWindowTransient (void *p, int transient_policy) +void SPDesktopWidget::setWindowTransient(void *p, int transient_policy) { - if (window) - { + if (window) { GtkWindow *w = GTK_WINDOW(window->gobj()); - gtk_window_set_transient_for (GTK_WINDOW(p), w); + gtk_window_set_transient_for(GTK_WINDOW(p), w); /* * This enables "aggressive" transientization, @@ -1107,22 +1084,20 @@ SPDesktopWidget::setWindowTransient (void *p, int transient_policy) */ if (transient_policy == 2) // without this, a transient window not always emerges on top - gtk_window_present (w); + gtk_window_present(w); } } -void -SPDesktopWidget::presentWindow() +void SPDesktopWidget::presentWindow() { if (window) window->present(); } -bool SPDesktopWidget::showInfoDialog( Glib::ustring const &message ) +bool SPDesktopWidget::showInfoDialog(Glib::ustring const &message) { bool result = false; - if (window) - { + if (window) { Gtk::MessageDialog dialog(*window, message, false, Gtk::MESSAGE_INFO, Gtk::BUTTONS_OK); dialog.property_destroy_with_parent() = true; dialog.set_name("InfoDialog"); @@ -1132,9 +1107,9 @@ bool SPDesktopWidget::showInfoDialog( Glib::ustring const &message ) return result; } -bool SPDesktopWidget::warnDialog (Glib::ustring const &text) +bool SPDesktopWidget::warnDialog(Glib::ustring const &text) { - Gtk::MessageDialog dialog (*window, text, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK_CANCEL); + Gtk::MessageDialog dialog(*window, text, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK_CANCEL); gint response = dialog.run(); if (response == Gtk::RESPONSE_OK) return true; @@ -1142,8 +1117,7 @@ bool SPDesktopWidget::warnDialog (Glib::ustring const &text) return false; } -void -SPDesktopWidget::iconify() +void SPDesktopWidget::iconify() { GtkWindow *topw = GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(_canvas->gobj()))); if (GTK_IS_WINDOW(topw)) { @@ -1155,8 +1129,7 @@ SPDesktopWidget::iconify() } } -void -SPDesktopWidget::maximize() +void SPDesktopWidget::maximize() { GtkWindow *topw = GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(_canvas->gobj()))); if (GTK_IS_WINDOW(topw)) { @@ -1166,8 +1139,7 @@ SPDesktopWidget::maximize() // Save geometry to prefs before maximizing so that // something useful is stored there, because GTK doesn't maintain // a separate non-maximized size. - if (!desktop->is_iconified() && !desktop->is_fullscreen()) - { + if (!desktop->is_iconified() && !desktop->is_fullscreen()) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gint w = -1; gint h, x, y; @@ -1183,8 +1155,7 @@ SPDesktopWidget::maximize() } } -void -SPDesktopWidget::fullscreen() +void SPDesktopWidget::fullscreen() { GtkWindow *topw = GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(_canvas->gobj()))); if (GTK_IS_WINDOW(topw)) { @@ -1195,8 +1166,7 @@ SPDesktopWidget::fullscreen() // Save geometry to prefs before maximizing so that // something useful is stored there, because GTK doesn't maintain // a separate non-maximized size. - if (!desktop->is_iconified() && !desktop->is_maximized()) - { + if (!desktop->is_iconified() && !desktop->is_maximized()) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gint w, h, x, y; getWindowGeometry(x, y, w, h); @@ -1229,19 +1199,19 @@ void SPDesktopWidget::layoutWidgets() } if (!prefs->getBool(pref_root + "commands/state", true)) { - gtk_widget_hide (dtw->commands_toolbox); + gtk_widget_hide(dtw->commands_toolbox); } else { - gtk_widget_show_all (dtw->commands_toolbox); + gtk_widget_show_all(dtw->commands_toolbox); } if (!prefs->getBool(pref_root + "snaptoolbox/state", true)) { - gtk_widget_hide (dtw->snap_toolbox); + gtk_widget_hide(dtw->snap_toolbox); } else { - gtk_widget_show_all (dtw->snap_toolbox); + gtk_widget_show_all(dtw->snap_toolbox); } if (!prefs->getBool(pref_root + "toppanel/state", true)) { - gtk_widget_hide (dtw->aux_toolbox); + gtk_widget_hide(dtw->aux_toolbox); } else { // we cannot just show_all because that will show all tools' panels; // this is a function from toolbox.cpp that shows only the current tool's panel @@ -1249,9 +1219,9 @@ void SPDesktopWidget::layoutWidgets() } if (!prefs->getBool(pref_root + "toolbox/state", true)) { - gtk_widget_hide (dtw->tool_toolbox); + gtk_widget_hide(dtw->tool_toolbox); } else { - gtk_widget_show_all (dtw->tool_toolbox); + gtk_widget_show_all(dtw->tool_toolbox); } if (!prefs->getBool(pref_root + "statusbar/state", true)) { @@ -1267,44 +1237,41 @@ void SPDesktopWidget::layoutWidgets() } _canvas_grid->ShowScrollbars(prefs->getBool(pref_root + "scrollbars/state", true)); - _canvas_grid->ShowRulers( prefs->getBool(pref_root + "rulers/state", true)); + _canvas_grid->ShowRulers(prefs->getBool(pref_root + "rulers/state", true)); } -Gtk::Toolbar * -SPDesktopWidget::get_toolbar_by_name(const Glib::ustring& name) +Gtk::Toolbar *SPDesktopWidget::get_toolbar_by_name(const Glib::ustring &name) { // The name is actually attached to the GtkGrid that contains // the toolbar, so we need to get the grid first auto widget = sp_search_by_name_recursive(Glib::wrap(aux_toolbox), name); - auto grid = dynamic_cast<Gtk::Grid*>(widget); + auto grid = dynamic_cast<Gtk::Grid *>(widget); - if (!grid) return nullptr; + if (!grid) + return nullptr; - auto child = grid->get_child_at(0,0); - auto tb = dynamic_cast<Gtk::Toolbar*>(child); + auto child = grid->get_child_at(0, 0); + auto tb = dynamic_cast<Gtk::Toolbar *>(child); return tb; } -void -SPDesktopWidget::setToolboxFocusTo (const gchar* label) +void SPDesktopWidget::setToolboxFocusTo(const gchar *label) { // First try looking for a named widget auto hb = sp_search_by_name_recursive(Glib::wrap(aux_toolbox), label); // Fallback to looking for a named data member (deprecated) if (!hb) { - hb = Glib::wrap(GTK_WIDGET(sp_search_by_data_recursive(aux_toolbox, (gpointer) label))); + hb = Glib::wrap(GTK_WIDGET(sp_search_by_data_recursive(aux_toolbox, (gpointer)label))); } - if (hb) - { + if (hb) { hb->grab_focus(); } } -void -SPDesktopWidget::setToolboxAdjustmentValue (gchar const *id, double value) +void SPDesktopWidget::setToolboxAdjustmentValue(gchar const *id, double value) { // First try looking for a named widget auto hb = sp_search_by_name_recursive(Glib::wrap(aux_toolbox), id); @@ -1318,40 +1285,40 @@ SPDesktopWidget::setToolboxAdjustmentValue (gchar const *id, double value) auto sb = dynamic_cast<Inkscape::UI::Widget::SpinButtonToolItem *>(hb); auto a = sb->get_adjustment(); - if(a) a->set_value(value); + if (a) + a->set_value(value); } - else g_warning ("Could not find GtkAdjustment for %s\n", id); + else + g_warning("Could not find GtkAdjustment for %s\n", id); } - -bool -SPDesktopWidget::isToolboxButtonActive (const gchar* id) +bool SPDesktopWidget::isToolboxButtonActive(const gchar *id) { bool isActive = false; - gpointer thing = sp_search_by_data_recursive(aux_toolbox, (gpointer) id); - if ( !thing ) { - //g_message( "Unable to locate item for {%s}", id ); - } else if ( GTK_IS_TOGGLE_BUTTON(thing) ) { + gpointer thing = sp_search_by_data_recursive(aux_toolbox, (gpointer)id); + if (!thing) { + // g_message( "Unable to locate item for {%s}", id ); + } else if (GTK_IS_TOGGLE_BUTTON(thing)) { GtkToggleButton *b = GTK_TOGGLE_BUTTON(thing); - isActive = gtk_toggle_button_get_active( b ) != 0; - } else if ( GTK_IS_TOGGLE_ACTION(thing) ) { - GtkToggleAction* act = GTK_TOGGLE_ACTION(thing); - isActive = gtk_toggle_action_get_active( act ) != 0; - } else if ( GTK_IS_TOGGLE_TOOL_BUTTON(thing) ) { + isActive = gtk_toggle_button_get_active(b) != 0; + } else if (GTK_IS_TOGGLE_ACTION(thing)) { + GtkToggleAction *act = GTK_TOGGLE_ACTION(thing); + isActive = gtk_toggle_action_get_active(act) != 0; + } else if (GTK_IS_TOGGLE_TOOL_BUTTON(thing)) { GtkToggleToolButton *b = GTK_TOGGLE_TOOL_BUTTON(thing); - isActive = gtk_toggle_tool_button_get_active( b ) != 0; + isActive = gtk_toggle_tool_button_get_active(b) != 0; } else { - //g_message( "Item for {%s} is of an unsupported type", id ); + // g_message( "Item for {%s} is of an unsupported type", id ); } return isActive; } -void SPDesktopWidget::setToolboxPosition(Glib::ustring const& id, GtkPositionType pos) +void SPDesktopWidget::setToolboxPosition(Glib::ustring const &id, GtkPositionType pos) { // Note - later on these won't be individual member variables. - GtkWidget* toolbox = nullptr; + GtkWidget *toolbox = nullptr; if (id == "ToolToolbar") { toolbox = tool_toolbox; } else if (id == "AuxToolbar") { @@ -1362,12 +1329,11 @@ void SPDesktopWidget::setToolboxPosition(Glib::ustring const& id, GtkPositionTyp toolbox = snap_toolbox; } - if (toolbox) { - switch(pos) { + switch (pos) { case GTK_POS_TOP: case GTK_POS_BOTTOM: - if ( gtk_widget_is_ancestor(toolbox, GTK_WIDGET(_hbox->gobj())) ) { + if (gtk_widget_is_ancestor(toolbox, GTK_WIDGET(_hbox->gobj()))) { // Removing a widget can reduce ref count to zero g_object_ref(G_OBJECT(toolbox)); _hbox->remove(*Glib::wrap(toolbox)); @@ -1381,7 +1347,7 @@ void SPDesktopWidget::setToolboxPosition(Glib::ustring const& id, GtkPositionTyp break; case GTK_POS_LEFT: case GTK_POS_RIGHT: - if ( !gtk_widget_is_ancestor(toolbox, GTK_WIDGET(_hbox->gobj())) ) { + if (!gtk_widget_is_ancestor(toolbox, GTK_WIDGET(_hbox->gobj()))) { g_object_ref(G_OBJECT(toolbox)); _vbox->remove(*Glib::wrap(toolbox)); _hbox->add(*Glib::wrap(toolbox)); @@ -1390,7 +1356,7 @@ void SPDesktopWidget::setToolboxPosition(Glib::ustring const& id, GtkPositionTyp // Function doesn't seem to be in Gtkmm wrapper yet gtk_box_set_child_packing(_hbox->gobj(), toolbox, FALSE, TRUE, 0, GTK_PACK_START); if (pos == GTK_POS_LEFT) { - _hbox->reorder_child(*Glib::wrap(toolbox), 0 ); + _hbox->reorder_child(*Glib::wrap(toolbox), 0); } } ToolboxFactory::setOrientation(toolbox, GTK_ORIENTATION_VERTICAL); @@ -1399,7 +1365,6 @@ void SPDesktopWidget::setToolboxPosition(Glib::ustring const& id, GtkPositionTyp } } - SPDesktopWidget::SPDesktopWidget(SPDocument *document) : SPDesktopWidget() { @@ -1409,12 +1374,12 @@ SPDesktopWidget::SPDesktopWidget(SPDocument *document) dtw->_dt2r = 1. / namedview->display_units->factor; - dtw->_ruler_origin = Geom::Point(0,0); //namedview->gridorigin; Why was the grid origin used here? + dtw->_ruler_origin = Geom::Point(0, 0); // namedview->gridorigin; Why was the grid origin used here? // This section seems backwards! dtw->desktop = new SPDesktop(); - dtw->desktop->init (namedview, dtw->_canvas, this); - INKSCAPE.add_desktop (dtw->desktop); + dtw->desktop->init(namedview, dtw->_canvas, this); + INKSCAPE.add_desktop(dtw->desktop); // Add the shape geometry to libavoid for autorouting connectors. // This needs desktop set for its spacing preferences. @@ -1446,27 +1411,24 @@ SPDesktopWidget::SPDesktopWidget(SPDocument *document) toolboxes.push_back(dtw->commands_toolbox); toolboxes.push_back(dtw->snap_toolbox); - dtw->_panels->setDesktop( dtw->desktop ); + dtw->_panels->setDesktop(dtw->desktop); UXManager::getInstance()->addTrack(dtw); - UXManager::getInstance()->connectToDesktop( toolboxes, dtw->desktop ); + UXManager::getInstance()->connectToDesktop(toolboxes, dtw->desktop); } - -void -SPDesktopWidget::update_rulers() +void SPDesktopWidget::update_rulers() { _canvas_grid->UpdateRulers(); } - void SPDesktopWidget::namedviewModified(SPObject *obj, guint flags) { - SPNamedView *nv=SP_NAMEDVIEW(obj); + SPNamedView *nv = SP_NAMEDVIEW(obj); if (flags & SP_OBJECT_MODIFIED_FLAG) { _dt2r = 1. / nv->display_units->factor; - _ruler_origin = Geom::Point(0,0); //nv->gridorigin; Why was the grid origin used here? + _ruler_origin = Geom::Point(0, 0); // nv->gridorigin; Why was the grid origin used here? _canvas_grid->GetVRuler()->set_unit(nv->getDisplayUnit()); _canvas_grid->GetHRuler()->set_unit(nv->getDisplayUnit()); @@ -1486,37 +1448,35 @@ void SPDesktopWidget::namedviewModified(SPObject *obj, guint flags) * This should solve: https://bugs.launchpad.net/inkscape/+bug/362995 */ if (GTK_IS_CONTAINER(aux_toolbox)) { - std::vector<Gtk::Widget*> ch = Glib::wrap(GTK_CONTAINER(aux_toolbox))->get_children(); - for (auto i:ch) { + std::vector<Gtk::Widget *> ch = Glib::wrap(GTK_CONTAINER(aux_toolbox))->get_children(); + for (auto i : ch) { if (GTK_IS_CONTAINER(i->gobj())) { - std::vector<Gtk::Widget*> grch = dynamic_cast<Gtk::Container*>(i)->get_children(); - for (auto j:grch) { - + std::vector<Gtk::Widget *> grch = dynamic_cast<Gtk::Container *>(i)->get_children(); + for (auto j : grch) { if (!GTK_IS_WIDGET(j->gobj())) // wasn't a widget continue; // Don't apply to text toolbar. We want to be able to // use different units for text. (Bug 1562217) const Glib::ustring name = j->get_name(); - if ( name == "TextToolbar" || name == "MeasureToolbar") + if (name == "TextToolbar" || name == "MeasureToolbar") continue; - auto tracker = dynamic_cast<UnitTracker*>(sp_search_by_name_recursive(j, "unit-tracker")); + auto tracker = dynamic_cast<UnitTracker *>(sp_search_by_name_recursive(j, "unit-tracker")); if (tracker) { // it's null when inkscape is first opened - tracker->setActiveUnit( nv->display_units ); + tracker->setActiveUnit(nv->display_units); } } // grandchildren - } // if child is a container - } // children - } // if aux_toolbox is a container + } // if child is a container + } // children + } // if aux_toolbox is a container ToolboxFactory::updateSnapToolbox(this->desktop, nullptr, this->snap_toolbox); } } -void -SPDesktopWidget::on_adjustment_value_changed() +void SPDesktopWidget::on_adjustment_value_changed() { if (update) return; @@ -1524,119 +1484,112 @@ SPDesktopWidget::on_adjustment_value_changed() update = true; // Do not call canvas->scrollTo directly... messes up 'offset'. - desktop->scroll_absolute( Geom::Point(_canvas_grid->GetHAdj()->get_value(), - _canvas_grid->GetVAdj()->get_value()), false); + desktop->scroll_absolute(Geom::Point(_canvas_grid->GetHAdj()->get_value(), _canvas_grid->GetVAdj()->get_value()), + false); update = false; } /* we make the desktop window with focus active, signal is connected in interface.c */ -bool SPDesktopWidget::onFocusInEvent(GdkEventFocus*) +bool SPDesktopWidget::onFocusInEvent(GdkEventFocus *) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (prefs->getBool("/options/bitmapautoreload/value", true)) { std::vector<SPObject *> imageList = (desktop->doc())->getResourceList("image"); for (auto it : imageList) { - SPImage* image = SP_IMAGE(it); + SPImage *image = SP_IMAGE(it); image->refresh_if_outdated(); } } - INKSCAPE.activate_desktop (desktop); + INKSCAPE.activate_desktop(desktop); return false; } // ------------------------ Zoom ------------------------ -static gdouble -sp_dtw_zoom_value_to_display (gdouble value) +static gdouble sp_dtw_zoom_value_to_display(gdouble value) { - return floor (10 * (pow (2, value) * 100.0 + 0.05)) / 10; + return floor(10 * (pow(2, value) * 100.0 + 0.05)) / 10; } -static gdouble -sp_dtw_zoom_display_to_value (gdouble value) +static gdouble sp_dtw_zoom_display_to_value(gdouble value) { - return log (value / 100.0) / log (2); + return log(value / 100.0) / log(2); } -int -SPDesktopWidget::zoom_input(double *new_val) +int SPDesktopWidget::zoom_input(double *new_val) { gchar *b = g_strdup(_zoom_status->get_text().c_str()); - gchar *comma = g_strstr_len (b, -1, ","); + gchar *comma = g_strstr_len(b, -1, ","); if (comma) { *comma = '.'; } - char *oldlocale = g_strdup (setlocale(LC_NUMERIC, nullptr)); - setlocale (LC_NUMERIC, "C"); - gdouble new_typed = atof (b); - setlocale (LC_NUMERIC, oldlocale); - g_free (oldlocale); - g_free (b); + char *oldlocale = g_strdup(setlocale(LC_NUMERIC, nullptr)); + setlocale(LC_NUMERIC, "C"); + gdouble new_typed = atof(b); + setlocale(LC_NUMERIC, oldlocale); + g_free(oldlocale); + g_free(b); - *new_val = sp_dtw_zoom_display_to_value (new_typed); + *new_val = sp_dtw_zoom_display_to_value(new_typed); return TRUE; } -bool -SPDesktopWidget::zoom_output() +bool SPDesktopWidget::zoom_output() { gchar b[64]; - double val = sp_dtw_zoom_value_to_display (_zoom_status->get_value()); + double val = sp_dtw_zoom_value_to_display(_zoom_status->get_value()); if (val < 10) { - g_snprintf (b, 64, "%4.1f%%", val); + g_snprintf(b, 64, "%4.1f%%", val); } else { - g_snprintf (b, 64, "%4.0f%%", val); + g_snprintf(b, 64, "%4.0f%%", val); } _zoom_status->set_text(b); return true; } -void -SPDesktopWidget::zoom_value_changed() +void SPDesktopWidget::zoom_value_changed() { - double const zoom_factor = pow (2, _zoom_status->get_value()); + double const zoom_factor = pow(2, _zoom_status->get_value()); // Zoom around center of window Geom::Rect const d_canvas = _canvas->get_area_world(); Geom::Point midpoint = desktop->w2d(d_canvas.midpoint()); _zoom_status_value_changed_connection.block(); - desktop->zoom_absolute_center_point (midpoint, zoom_factor); + desktop->zoom_absolute_center_point(midpoint, zoom_factor); _zoom_status_value_changed_connection.unblock(); _zoom_status->defocus(); } -void -SPDesktopWidget::zoom_menu_handler(double factor) +void SPDesktopWidget::zoom_menu_handler(double factor) { desktop->zoom_absolute_center_point(desktop->current_center(), factor); } -void -SPDesktopWidget::zoom_populate_popup(Gtk::Menu *menu) +void SPDesktopWidget::zoom_populate_popup(Gtk::Menu *menu) { - for ( auto iter : menu->get_children()) { + for (auto iter : menu->get_children()) { menu->remove(*iter); } auto item_1000 = Gtk::manage(new Gtk::MenuItem("1000%")); - auto item_500 = Gtk::manage(new Gtk::MenuItem("500%")); - auto item_200 = Gtk::manage(new Gtk::MenuItem("200%")); - auto item_100 = Gtk::manage(new Gtk::MenuItem("100%")); - auto item_50 = Gtk::manage(new Gtk::MenuItem( "50%")); - auto item_25 = Gtk::manage(new Gtk::MenuItem( "25%")); - auto item_10 = Gtk::manage(new Gtk::MenuItem( "10%")); + auto item_500 = Gtk::manage(new Gtk::MenuItem("500%")); + auto item_200 = Gtk::manage(new Gtk::MenuItem("200%")); + auto item_100 = Gtk::manage(new Gtk::MenuItem("100%")); + auto item_50 = Gtk::manage(new Gtk::MenuItem("50%")); + auto item_25 = Gtk::manage(new Gtk::MenuItem("25%")); + auto item_10 = Gtk::manage(new Gtk::MenuItem("10%")); item_1000->signal_activate().connect(sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 10.00)); - item_500->signal_activate().connect( sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 5.00)); - item_200->signal_activate().connect( sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 2.00)); - item_100->signal_activate().connect( sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 1.00)); - item_50->signal_activate().connect( sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 0.50)); - item_25->signal_activate().connect( sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 0.25)); - item_10->signal_activate().connect( sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 0.10)); + item_500->signal_activate().connect(sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 5.00)); + item_200->signal_activate().connect(sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 2.00)); + item_100->signal_activate().connect(sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 1.00)); + item_50->signal_activate().connect(sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 0.50)); + item_25->signal_activate().connect(sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 0.25)); + item_10->signal_activate().connect(sigc::bind(sigc::mem_fun(this, &SPDesktopWidget::zoom_menu_handler), 0.10)); menu->append(*item_1000); menu->append(*item_500); @@ -1668,17 +1621,13 @@ SPDesktopWidget::zoom_populate_popup(Gtk::Menu *menu) menu->show_all(); } - -void -SPDesktopWidget::sticky_zoom_toggled() +void SPDesktopWidget::sticky_zoom_toggled() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setBool("/options/stickyzoom/value", _canvas_grid->GetStickyZoom()->get_active()); } - -void -SPDesktopWidget::update_zoom() +void SPDesktopWidget::update_zoom() { _zoom_status_value_changed_connection.block(); _zoom_status->set_value(log(desktop->current_zoom()) / log(2)); @@ -1686,46 +1635,44 @@ SPDesktopWidget::update_zoom() _zoom_status_value_changed_connection.unblock(); } - // ---------------------- Rotation ------------------------ -int -SPDesktopWidget::rotation_input(double *new_val) +int SPDesktopWidget::rotation_input(double *new_val) { auto *b = g_strdup(_rotation_status->get_text().c_str()); - gchar *comma = g_strstr_len (b, -1, ","); + gchar *comma = g_strstr_len(b, -1, ","); if (comma) { *comma = '.'; } - char *oldlocale = g_strdup (setlocale(LC_NUMERIC, nullptr)); - setlocale (LC_NUMERIC, "C"); - gdouble new_value = atof (b); - setlocale (LC_NUMERIC, oldlocale); - g_free (oldlocale); - g_free (b); + char *oldlocale = g_strdup(setlocale(LC_NUMERIC, nullptr)); + setlocale(LC_NUMERIC, "C"); + gdouble new_value = atof(b); + setlocale(LC_NUMERIC, oldlocale); + g_free(oldlocale); + g_free(b); *new_val = new_value; return true; } -bool -SPDesktopWidget::rotation_output() +bool SPDesktopWidget::rotation_output() { gchar b[64]; double val = _rotation_status->get_value(); - if (val < -180) val += 360; - if (val > 180) val -= 360; + if (val < -180) + val += 360; + if (val > 180) + val -= 360; - g_snprintf (b, 64, "%7.2f°", val); + g_snprintf(b, 64, "%7.2f°", val); _rotation_status->set_text(b); return true; } -void -SPDesktopWidget::rotation_value_changed() +void SPDesktopWidget::rotation_value_changed() { double const rotate_factor = M_PI / 180.0 * _rotation_status->get_value(); // std::cout << "SPDesktopWidget::rotation_value_changed: " @@ -1736,34 +1683,34 @@ SPDesktopWidget::rotation_value_changed() Geom::Rect const d_canvas = _canvas->get_area_world(); _rotation_status_value_changed_connection.block(); Geom::Point midpoint = desktop->w2d(d_canvas.midpoint()); - desktop->rotate_absolute_center_point (midpoint, rotate_factor); + desktop->rotate_absolute_center_point(midpoint, rotate_factor); _rotation_status_value_changed_connection.unblock(); _rotation_status->defocus(); } -void -SPDesktopWidget::rotation_populate_popup(Gtk::Menu *menu) +void SPDesktopWidget::rotation_populate_popup(Gtk::Menu *menu) { - for ( auto iter : menu->get_children()) { + for (auto iter : menu->get_children()) { menu->remove(*iter); } auto item_m135 = Gtk::manage(new Gtk::MenuItem("-135°")); - auto item_m90 = Gtk::manage(new Gtk::MenuItem( "-90°")); - auto item_m45 = Gtk::manage(new Gtk::MenuItem( "-45°")); - auto item_0 = Gtk::manage(new Gtk::MenuItem( "0°")); - auto item_p45 = Gtk::manage(new Gtk::MenuItem( "45°")); - auto item_p90 = Gtk::manage(new Gtk::MenuItem( "90°")); - auto item_p135 = Gtk::manage(new Gtk::MenuItem( "135°")); - auto item_p180 = Gtk::manage(new Gtk::MenuItem( "180°")); - - item_m135->signal_activate().connect(sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), -135)); - item_m90->signal_activate().connect( sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), -90)); - item_m45->signal_activate().connect( sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), -45)); - item_0->signal_activate().connect( sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), 0)); - item_p45->signal_activate().connect( sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), 45)); - item_p90->signal_activate().connect( sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), 90)); + auto item_m90 = Gtk::manage(new Gtk::MenuItem("-90°")); + auto item_m45 = Gtk::manage(new Gtk::MenuItem("-45°")); + auto item_0 = Gtk::manage(new Gtk::MenuItem("0°")); + auto item_p45 = Gtk::manage(new Gtk::MenuItem("45°")); + auto item_p90 = Gtk::manage(new Gtk::MenuItem("90°")); + auto item_p135 = Gtk::manage(new Gtk::MenuItem("135°")); + auto item_p180 = Gtk::manage(new Gtk::MenuItem("180°")); + + item_m135->signal_activate().connect( + sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), -135)); + item_m90->signal_activate().connect(sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), -90)); + item_m45->signal_activate().connect(sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), -45)); + item_0->signal_activate().connect(sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), 0)); + item_p45->signal_activate().connect(sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), 45)); + item_p90->signal_activate().connect(sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), 90)); item_p135->signal_activate().connect(sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), 135)); item_p180->signal_activate().connect(sigc::bind(sigc::mem_fun(_rotation_status, &Gtk::SpinButton::set_value), 180)); @@ -1779,42 +1726,34 @@ SPDesktopWidget::rotation_populate_popup(Gtk::Menu *menu) menu->show_all(); } - -void -SPDesktopWidget::update_rotation() +void SPDesktopWidget::update_rotation() { _rotation_status_value_changed_connection.block(); _rotation_status->set_value(desktop->current_rotation() / M_PI * 180.0); _rotation_status->queue_draw(); _rotation_status_value_changed_connection.unblock(); - } - // --------------- Rulers/Scrollbars/Etc. ----------------- -void -SPDesktopWidget::toggle_rulers() +void SPDesktopWidget::toggle_rulers() { // TODO: Turn into action and remove this function. _canvas_grid->ToggleRulers(); } -void -SPDesktopWidget::toggle_scrollbars() +void SPDesktopWidget::toggle_scrollbars() { // TODO: Turn into action and remove this function. _canvas_grid->ToggleScrollbars(); } -bool -SPDesktopWidget::get_color_prof_adj_enabled() const +bool SPDesktopWidget::get_color_prof_adj_enabled() const { auto _cms_adjust = _canvas_grid->GetCmsAdjust(); return _cms_adjust->get_sensitive() && _cms_adjust->get_active(); } -void -SPDesktopWidget::toggle_color_prof_adj() +void SPDesktopWidget::toggle_color_prof_adj() { auto _cms_adjust = _canvas_grid->GetCmsAdjust(); if (_cms_adjust->get_sensitive()) { @@ -1823,32 +1762,28 @@ SPDesktopWidget::toggle_color_prof_adj() } } -static void -set_adjustment (Glib::RefPtr<Gtk::Adjustment> &adj, double l, double u, double ps, double si, double pi) +static void set_adjustment(Glib::RefPtr<Gtk::Adjustment> &adj, double l, double u, double ps, double si, double pi) { - if ((l != adj->get_lower()) || - (u != adj->get_upper()) || - (ps != adj->get_page_size()) || - (si != adj->get_step_increment()) || - (pi != adj->get_page_increment())) { - adj->set_lower(l); - adj->set_upper(u); - adj->set_page_size(ps); - adj->set_step_increment(si); - adj->set_page_increment(pi); + if ((l != adj->get_lower()) || (u != adj->get_upper()) || (ps != adj->get_page_size()) || + (si != adj->get_step_increment()) || (pi != adj->get_page_increment())) { + adj->set_lower(l); + adj->set_upper(u); + adj->set_page_size(ps); + adj->set_step_increment(si); + adj->set_page_increment(pi); } } -void -SPDesktopWidget::update_scrollbars(double scale) +void SPDesktopWidget::update_scrollbars(double scale) { - if (update) return; + if (update) + return; update = true; /* The desktop region we always show unconditionally */ SPDocument *doc = desktop->doc(); - Geom::Rect darea ( Geom::Point(-doc->getWidth().value("px"), -doc->getHeight().value("px")), - Geom::Point(2 * doc->getWidth().value("px"), 2 * doc->getHeight().value("px")) ); + Geom::Rect darea(Geom::Point(-doc->getWidth().value("px"), -doc->getHeight().value("px")), + Geom::Point(2 * doc->getWidth().value("px"), 2 * doc->getHeight().value("px"))); Geom::OptRect deskarea; if (Inkscape::Preferences::get()->getInt("/tools/bounding_box") == 0) { @@ -1859,8 +1794,8 @@ SPDesktopWidget::update_scrollbars(double scale) /* Canvas region we always show unconditionally */ double const y_dir = desktop->yaxisdir(); - Geom::Rect carea( Geom::Point(deskarea->left() * scale - 64, (deskarea->top() * scale + 64) * y_dir), - Geom::Point(deskarea->right() * scale + 64, (deskarea->bottom() * scale - 64) * y_dir) ); + Geom::Rect carea(Geom::Point(deskarea->left() * scale - 64, (deskarea->top() * scale + 64) * y_dir), + Geom::Point(deskarea->right() * scale + 64, (deskarea->bottom() * scale - 64) * y_dir)); Geom::Rect viewbox = _canvas->get_area_world(); @@ -1869,56 +1804,50 @@ SPDesktopWidget::update_scrollbars(double scale) auto _hadj = _canvas_grid->GetHAdj(); auto _vadj = _canvas_grid->GetVAdj(); - set_adjustment(_hadj, carea.min()[Geom::X], carea.max()[Geom::X], - viewbox.dimensions()[Geom::X], - 0.1 * viewbox.dimensions()[Geom::X], - viewbox.dimensions()[Geom::X]); + set_adjustment(_hadj, carea.min()[Geom::X], carea.max()[Geom::X], viewbox.dimensions()[Geom::X], + 0.1 * viewbox.dimensions()[Geom::X], viewbox.dimensions()[Geom::X]); _hadj->set_value(viewbox.min()[Geom::X]); - set_adjustment(_vadj, carea.min()[Geom::Y], carea.max()[Geom::Y], - viewbox.dimensions()[Geom::Y], - 0.1 * viewbox.dimensions()[Geom::Y], - viewbox.dimensions()[Geom::Y]); + set_adjustment(_vadj, carea.min()[Geom::Y], carea.max()[Geom::Y], viewbox.dimensions()[Geom::Y], + 0.1 * viewbox.dimensions()[Geom::Y], viewbox.dimensions()[Geom::Y]); _vadj->set_value(viewbox.min()[Geom::Y]); update = false; } // TODO: Remove this. -bool -SPDesktopWidget::get_sticky_zoom_active() const +bool SPDesktopWidget::get_sticky_zoom_active() const { return _canvas_grid->GetStickyZoom()->get_active(); } -gint -SPDesktopWidget::ruler_event(GtkWidget *widget, GdkEvent *event, SPDesktopWidget *dtw, bool horiz) +gint SPDesktopWidget::ruler_event(GtkWidget *widget, GdkEvent *event, SPDesktopWidget *dtw, bool horiz) { switch (event->type) { - case GDK_BUTTON_PRESS: - dtw->on_ruler_box_button_press_event(&event->button, Glib::wrap(widget), horiz); - break; - case GDK_MOTION_NOTIFY: - dtw->on_ruler_box_motion_notify_event(&event->motion, Glib::wrap(widget), horiz); - break; - case GDK_BUTTON_RELEASE: - dtw->on_ruler_box_button_release_event(&event->button, Glib::wrap(widget), horiz); - break; - default: + case GDK_BUTTON_PRESS: + dtw->on_ruler_box_button_press_event(&event->button, Glib::wrap(widget), horiz); + break; + case GDK_MOTION_NOTIFY: + dtw->on_ruler_box_motion_notify_event(&event->motion, Glib::wrap(widget), horiz); + break; + case GDK_BUTTON_RELEASE: + dtw->on_ruler_box_button_release_event(&event->button, Glib::wrap(widget), horiz); + break; + default: break; } return FALSE; } -bool -SPDesktopWidget::on_ruler_box_motion_notify_event(GdkEventMotion *event, Gtk::Widget *widget, bool horiz) +bool SPDesktopWidget::on_ruler_box_motion_notify_event(GdkEventMotion *event, Gtk::Widget *widget, bool horiz) { if (horiz) { - sp_event_context_snap_delay_handler(desktop->event_context, (gpointer) widget->gobj(), (gpointer) this, event, Inkscape::UI::Tools::DelayedSnapEvent::GUIDE_HRULER); - } - else { - sp_event_context_snap_delay_handler(desktop->event_context, (gpointer) widget->gobj(), (gpointer) this, event, Inkscape::UI::Tools::DelayedSnapEvent::GUIDE_VRULER); + sp_event_context_snap_delay_handler(desktop->event_context, (gpointer)widget->gobj(), (gpointer)this, event, + Inkscape::UI::Tools::DelayedSnapEvent::GUIDE_HRULER); + } else { + sp_event_context_snap_delay_handler(desktop->event_context, (gpointer)widget->gobj(), (gpointer)this, event, + Inkscape::UI::Tools::DelayedSnapEvent::GUIDE_VRULER); } int wx, wy; @@ -1938,8 +1867,7 @@ SPDesktopWidget::on_ruler_box_motion_notify_event(GdkEventMotion *event, Gtk::Wi Inkscape::Preferences *prefs = Inkscape::Preferences::get(); gint tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); - if ( ( abs( (gint) event->x - _xp ) < tolerance ) - && ( abs( (gint) event->y - _yp ) < tolerance ) ) { + if ((abs((gint)event->x - _xp) < tolerance) && (abs((gint)event->y - _yp) < tolerance)) { return false; } @@ -1963,8 +1891,7 @@ SPDesktopWidget::on_ruler_box_motion_notify_event(GdkEventMotion *event, Gtk::Wi } // End guide creation or toggle guides on/off. -bool -SPDesktopWidget::on_ruler_box_button_release_event(GdkEventButton *event, Gtk::Widget *widget, bool horiz) +bool SPDesktopWidget::on_ruler_box_button_release_event(GdkEventButton *event, Gtk::Widget *widget, bool horiz) { int wx, wy; @@ -2007,16 +1934,15 @@ SPDesktopWidget::on_ruler_box_button_release_event(GdkEventButton *event, Gtk::W } SPRoot *root = desktop->doc()->getRoot(); - if( root->viewBox_set ) { - newx = newx * root->viewBox.width() / root->width.computed; + if (root->viewBox_set) { + newx = newx * root->viewBox.width() / root->width.computed; newy = newy * root->viewBox.height() / root->height.computed; } - sp_repr_set_point(repr, "position", Geom::Point( newx, newy )); + sp_repr_set_point(repr, "position", Geom::Point(newx, newy)); sp_repr_set_point(repr, "orientation", _normal); desktop->namedview->appendChild(repr); Inkscape::GC::release(repr); - DocumentUndo::done(desktop->getDocument(), SP_VERB_NONE, - _("Create guide")); + DocumentUndo::done(desktop->getDocument(), SP_VERB_NONE, _("Create guide")); } desktop->set_coordinate_status(event_dt); @@ -2033,8 +1959,7 @@ SPDesktopWidget::on_ruler_box_button_release_event(GdkEventButton *event, Gtk::W } // Start guide creation by dragging from ruler. -bool -SPDesktopWidget::on_ruler_box_button_press_event(GdkEventButton *event, Gtk::Widget *widget, bool horiz) +bool SPDesktopWidget::on_ruler_box_button_press_event(GdkEventButton *event, Gtk::Widget *widget, bool horiz) { if (_ruler_clicked) // event triggerred on a double click: do no process the click return false; @@ -2054,21 +1979,21 @@ SPDesktopWidget::on_ruler_box_button_press_event(GdkEventButton *event, Gtk::Wid _ruler_clicked = true; _ruler_dragged = false; // save click origin - _xp = (gint) event->x; - _yp = (gint) event->y; + _xp = (gint)event->x; + _yp = (gint)event->y; Geom::Point const event_w(_canvas->canvas_to_world(event_win)); Geom::Point const event_dt(desktop->w2d(event_w)); // calculate the normal of the guidelines when dragged from the edges of rulers. auto const y_dir = desktop->yaxisdir(); - Geom::Point normal_bl_to_tr(1., y_dir); //bottomleft to topright - Geom::Point normal_tr_to_bl(-1., y_dir); //topright to bottomleft + Geom::Point normal_bl_to_tr(1., y_dir); // bottomleft to topright + Geom::Point normal_tr_to_bl(-1., y_dir); // topright to bottomleft normal_bl_to_tr.normalize(); normal_tr_to_bl.normalize(); - Inkscape::CanvasGrid * grid = sp_namedview_get_first_enabled_grid(desktop->namedview); - if (grid){ - if (grid->getGridType() == Inkscape::GRID_AXONOMETRIC ) { + Inkscape::CanvasGrid *grid = sp_namedview_get_first_enabled_grid(desktop->namedview); + if (grid) { + if (grid->getGridType() == Inkscape::GRID_AXONOMETRIC) { Inkscape::CanvasAxonomGrid *axonomgrid = dynamic_cast<Inkscape::CanvasAxonomGrid *>(grid); if (event->state & GDK_CONTROL_MASK) { // guidelines normal to gridlines @@ -2086,7 +2011,7 @@ SPDesktopWidget::on_ruler_box_button_press_event(GdkEventButton *event, Gtk::Wid } else if (wx > width - 50) { _normal = normal_tr_to_bl; } else { - _normal = Geom::Point(0.,1.); + _normal = Geom::Point(0., 1.); } } else { if (wy < 50) { @@ -2094,7 +2019,7 @@ SPDesktopWidget::on_ruler_box_button_press_event(GdkEventButton *event, Gtk::Wid } else if (wy > height - 50) { _normal = normal_tr_to_bl; } else { - _normal = Geom::Point(1.,0.); + _normal = Geom::Point(1., 0.); } } @@ -2104,21 +2029,15 @@ SPDesktopWidget::on_ruler_box_button_press_event(GdkEventButton *event, Gtk::Wid // Ruler grabs all events until button release. auto window = widget->get_window()->gobj(); auto seat = gdk_device_get_seat(event->device); - gdk_seat_grab(seat, - window, - GDK_SEAT_CAPABILITY_ALL_POINTING, - FALSE, - nullptr, - (GdkEvent*)event, - nullptr, - nullptr); + gdk_seat_grab(seat, window, GDK_SEAT_CAPABILITY_ALL_POINTING, FALSE, nullptr, (GdkEvent *)event, nullptr, + nullptr); } return false; } -void -SPDesktopWidget::ruler_snap_new_guide(SPDesktop *desktop, SPCanvasItem * /*guide*/, Geom::Point &event_dt, Geom::Point &normal) +void SPDesktopWidget::ruler_snap_new_guide(SPDesktop *desktop, SPCanvasItem * /*guide*/, Geom::Point &event_dt, + Geom::Point &normal) { SnapManager &m = desktop->namedview->snap_manager; m.setup(desktop); @@ -2142,7 +2061,7 @@ SPDesktopWidget::ruler_snap_new_guide(SPDesktop *desktop, SPCanvasItem * /*guide } } if (!(pref_tang || pref_perp)) { // if we don't want to snap either perpendicularly or tangentially, then - normal = normal_orig; // we must restore the normal to it's original state + normal = normal_orig; // we must restore the normal to it's original state } // Restore the preferences m.snapprefs.setSnapPerp(pref_perp); diff --git a/src/widgets/desktop-widget.h b/src/widgets/desktop-widget.h index 600576ee47af11854deda9e70aa3ed6bc21244c9..e295c82e6f6081d17c12abfa6776e09662b81350 100644 --- a/src/widgets/desktop-widget.h +++ b/src/widgets/desktop-widget.h @@ -16,18 +16,17 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" // only include where actually required! +#include "config.h" // only include where actually required! #endif +#include <2geom/point.h> +#include <cstddef> #include <gtkmm.h> +#include <sigc++/connection.h> #include "message.h" #include "ui/view/view-widget.h" -#include <cstddef> -#include <sigc++/connection.h> -#include <2geom/point.h> - // forward declaration typedef struct _EgeColorProfTracker EgeColorProfTracker; @@ -44,43 +43,44 @@ class SwatchesPanel; } // namespace Dialog namespace Widget { - class Button; - class Canvas; - class CanvasGrid; - class LayerSelector; - class SelectedStyle; - class SpinButton; - class Ruler; - class Dock; +class Button; +class Canvas; +class CanvasGrid; +class LayerSelector; +class SelectedStyle; +class SpinButton; +class Ruler; +class Dock; } // namespace Widget } // namespace UI } // namespace Inkscape -#define SP_DESKTOP_WIDGET(o) dynamic_cast<SPDesktopWidget*>(o) +#define SP_DESKTOP_WIDGET(o) dynamic_cast<SPDesktopWidget *>(o) #define SP_IS_DESKTOP_WIDGET(o) bool(dynamic_cast<SPDesktopWidget const *>(o)) void sp_desktop_widget_show_decorations(SPDesktopWidget *dtw, gboolean show); -void sp_desktop_widget_update_hruler (SPDesktopWidget *dtw); -void sp_desktop_widget_update_vruler (SPDesktopWidget *dtw); +void sp_desktop_widget_update_hruler(SPDesktopWidget *dtw); +void sp_desktop_widget_update_vruler(SPDesktopWidget *dtw); /* Show/hide rulers & scrollbars */ -void sp_desktop_widget_update_scrollbars (SPDesktopWidget *dtw, double scale); +void sp_desktop_widget_update_scrollbars(SPDesktopWidget *dtw, double scale); -void sp_dtw_desktop_activate (SPDesktopWidget *dtw); -void sp_dtw_desktop_deactivate (SPDesktopWidget *dtw); +void sp_dtw_desktop_activate(SPDesktopWidget *dtw); +void sp_dtw_desktop_deactivate(SPDesktopWidget *dtw); /// A GtkEventBox on an SPDesktop. -class SPDesktopWidget : public SPViewWidget { +class SPDesktopWidget : public SPViewWidget +{ using parent_type = SPViewWidget; SPDesktopWidget(); - public: +public: SPDesktopWidget(SPDocument *document); ~SPDesktopWidget() override; - Inkscape::UI::Widget::CanvasGrid *get_canvas_grid() { return _canvas_grid; } // Temp, I hope! - Inkscape::UI::Widget::Canvas *get_canvas() { return _canvas; } + Inkscape::UI::Widget::CanvasGrid *get_canvas_grid() { return _canvas_grid; } // Temp, I hope! + Inkscape::UI::Widget::Canvas *get_canvas() { return _canvas; } void on_size_allocate(Gtk::Allocation &) override; void on_realize() override; @@ -100,17 +100,17 @@ private: bool update = false; SPCanvasItem *_active_guide = nullptr; ///< The guide currently being handled during a ruler event - Geom::Point _normal; ///< Normal to the guide currently being handled during ruler event - int _xp = 0; ///< x coordinate for start of drag - int _yp = 0; ///< y coordinate for start of drag + Geom::Point _normal; ///< Normal to the guide currently being handled during ruler event + int _xp = 0; ///< x coordinate for start of drag + int _yp = 0; ///< y coordinate for start of drag // The root vbox of the window layout. Gtk::Box *_vbox; Gtk::Box *_hbox; - Gtk::MenuBar *_menubar; // TEMP - Gtk::Box *_statusbar; + Gtk::MenuBar *_menubar; // TEMP + Gtk::Box *_statusbar; Inkscape::UI::Dialog::SwatchesPanel *_panels; @@ -136,7 +136,6 @@ private: Inkscape::UI::Widget::Dock *_dock = nullptr; - Inkscape::UI::Widget::SelectedStyle *_selected_style; /** A grid for display the canvas, rulers, and scrollbars. */ @@ -156,25 +155,25 @@ private: public: Inkscape::UI::Widget::LayerSelector *layer_selector; - EgeColorProfTracker* _tracker; + EgeColorProfTracker *_tracker; void setMessage(Inkscape::MessageType type, gchar const *message); Geom::Point window_get_pointer(); bool shutdown(); - void viewSetPosition (Geom::Point p); + void viewSetPosition(Geom::Point p); void letZoomGrabFocus(); - void getWindowGeometry (gint &x, gint &y, gint &w, gint &h); - void setWindowPosition (Geom::Point p); - void setWindowSize (gint w, gint h); - void setWindowTransient (void *p, int transient_policy); + void getWindowGeometry(gint &x, gint &y, gint &w, gint &h); + void setWindowPosition(Geom::Point p); + void setWindowSize(gint w, gint h); + void setWindowTransient(void *p, int transient_policy); void presentWindow(); - bool showInfoDialog( Glib::ustring const &message ); - bool warnDialog (Glib::ustring const &text); - Gtk::Toolbar* get_toolbar_by_name(const Glib::ustring& name); - void setToolboxFocusTo (gchar const *); - void setToolboxAdjustmentValue (gchar const * id, double value); - bool isToolboxButtonActive (gchar const *id); - void setToolboxPosition(Glib::ustring const& id, GtkPositionType pos); + bool showInfoDialog(Glib::ustring const &message); + bool warnDialog(Glib::ustring const &text); + Gtk::Toolbar *get_toolbar_by_name(const Glib::ustring &name); + void setToolboxFocusTo(gchar const *); + void setToolboxAdjustmentValue(gchar const *id, double value); + bool isToolboxButtonActive(gchar const *id); + void setToolboxPosition(Glib::ustring const &id, GtkPositionType pos); void setCoordinateStatus(Geom::Point p); void storeDesktopPosition(); void requestCanvasUpdate(); @@ -182,11 +181,11 @@ public: void enableInteraction(); void disableInteraction(); void updateTitle(gchar const *uri); - bool onFocusInEvent(GdkEventFocus*); + bool onFocusInEvent(GdkEventFocus *); Gtk::MenuBar *menubar() { return _menubar; } - Inkscape::UI::Widget::Dock* getDock(); + Inkscape::UI::Widget::Dock *getDock(); void updateNamedview(); void update_guides_lock(); @@ -227,15 +226,17 @@ private: bool rotation_output(); void rotation_value_changed(); void rotation_populate_popup(Gtk::Menu *menu); - //void canvas_tbl_size_allocate(Gtk::Allocation &allocation); + // void canvas_tbl_size_allocate(Gtk::Allocation &allocation); #if defined(HAVE_LIBLCMS2) public: void cms_adjust_toggled(); + private: static void color_profile_event(EgeColorProfTracker *tracker, SPDesktopWidget *dtw); #endif - static void ruler_snap_new_guide(SPDesktop *desktop, SPCanvasItem *guide, Geom::Point &event_dt, Geom::Point &normal); + static void ruler_snap_new_guide(SPDesktop *desktop, SPCanvasItem *guide, Geom::Point &event_dt, + Geom::Point &normal); static gint event(GtkWidget *widget, GdkEvent *event, SPDesktopWidget *dtw); public: // Move to CanvasGrid diff --git a/src/widgets/ege-paint-def.cpp b/src/widgets/ege-paint-def.cpp index fa654cb729f1c6414a0358afd4890684a87afc1b..d3ddea5e5575fe090186a13b062d4d397ec8e5e3 100644 --- a/src/widgets/ege-paint-def.cpp +++ b/src/widgets/ege-paint-def.cpp @@ -35,17 +35,16 @@ * * ***** END LICENSE BLOCK ***** */ -#include <libintl.h> - #include <cstdint> -#include <string> -#include <iostream> -#include <sstream> -#include <cstring> #include <cstdio> -#include <utility> +#include <cstring> #include <glibmm/i18n.h> #include <glibmm/stringutils.h> +#include <iostream> +#include <libintl.h> +#include <sstream> +#include <string> +#include <utility> #if !defined(_) #define _(s) gettext(s) @@ -53,32 +52,30 @@ #include "ege-paint-def.h" -namespace ege -{ +namespace ege { static std::string mimeTEXT("text/plain"); static std::string mimeX_COLOR("application/x-color"); static std::string mimeOSWB_COLOR("application/x-oswb-color"); -PaintDef::PaintDef() : - descr(_("none")), - type(NONE), - r(0), - g(0), - b(0), - editable(false), - _listeners() -{ -} +PaintDef::PaintDef() + : descr(_("none")) + , type(NONE) + , r(0) + , g(0) + , b(0) + , editable(false) + , _listeners() +{} -PaintDef::PaintDef( ColorType type ) : - descr(), - type(type), - r(0), - g(0), - b(0), - editable(false), - _listeners() +PaintDef::PaintDef(ColorType type) + : descr() + , type(type) + , r(0) + , g(0) + , b(0) + , editable(false) + , _listeners() { switch (type) { case CLEAR: @@ -93,50 +90,51 @@ PaintDef::PaintDef( ColorType type ) : } } -PaintDef::PaintDef( unsigned int r, unsigned int g, unsigned int b, std::string description ) : - descr(std::move(description)), - type(RGB), - r(r), - g(g), - b(b), - editable(false), - _listeners() -{ -} +PaintDef::PaintDef(unsigned int r, unsigned int g, unsigned int b, std::string description) + : descr(std::move(description)) + , type(RGB) + , r(r) + , g(g) + , b(b) + , editable(false) + , _listeners() +{} -PaintDef::~PaintDef() -= default; +PaintDef::~PaintDef() = default; -PaintDef::PaintDef( PaintDef const &other ) +PaintDef::PaintDef(PaintDef const &other) { - if ( this != &other ) { + if (this != &other) { *this = other; } } -PaintDef& PaintDef::operator=( PaintDef const &other ) +PaintDef &PaintDef::operator=(PaintDef const &other) { - if ( this != & other ) - { + if (this != &other) { type = other.type; r = other.r; g = other.g; b = other.b; descr = other.descr; editable = other.editable; - //TODO: _listeners should be assigned a value + // TODO: _listeners should be assigned a value } return *this; } -class PaintDef::HookData { +class PaintDef::HookData +{ public: - HookData( ColorCallback cb, void* data ) {_cb = cb; _data = data;} + HookData(ColorCallback cb, void *data) + { + _cb = cb; + _data = data; + } ColorCallback _cb; - void* _data; + void *_data; }; - std::vector<std::string> PaintDef::getMIMETypes() { std::vector<std::string> listing; @@ -146,45 +144,40 @@ std::vector<std::string> PaintDef::getMIMETypes() return listing; } -void PaintDef::getMIMEData(std::string const & type, char*& dest, int& len, int& format) +void PaintDef::getMIMEData(std::string const &type, char *&dest, int &len, int &format) { - if ( type == mimeTEXT ) { + if (type == mimeTEXT) { dest = new char[8]; - snprintf( dest, 8, "#%02x%02x%02x", getR(), getG(), getB() ); + snprintf(dest, 8, "#%02x%02x%02x", getR(), getG(), getB()); dest[7] = 0; len = 8; format = 8; - } else if ( type == mimeX_COLOR ) { - uint16_t* tmp = new uint16_t[4]; + } else if (type == mimeX_COLOR) { + uint16_t *tmp = new uint16_t[4]; tmp[0] = (getR() << 8) | getR(); tmp[1] = (getG() << 8) | getG(); tmp[2] = (getB() << 8) | getB(); tmp[3] = 0xffff; - dest = reinterpret_cast<char*>(tmp); + dest = reinterpret_cast<char *>(tmp); len = 8; format = 16; - } else if ( type == mimeOSWB_COLOR ) { + } else if (type == mimeOSWB_COLOR) { std::string tmp("<paint>"); - switch ( getType() ) { - case ege::PaintDef::NONE: - { + switch (getType()) { + case ege::PaintDef::NONE: { tmp += "<nocolor/>"; - } - break; - case ege::PaintDef::CLEAR: - { + } break; + case ege::PaintDef::CLEAR: { tmp += "<clear/>"; - } - break; - default: - { + } break; + default: { tmp += std::string("<color name=\"") + descr + "\">"; tmp += "<sRGB r=\""; - tmp += Glib::Ascii::dtostr(getR()/255.0); + tmp += Glib::Ascii::dtostr(getR() / 255.0); tmp += "\" g=\""; - tmp += Glib::Ascii::dtostr(getG()/255.0); + tmp += Glib::Ascii::dtostr(getG() / 255.0); tmp += "\" b=\""; - tmp += Glib::Ascii::dtostr(getB()/255.0); + tmp += Glib::Ascii::dtostr(getB() / 255.0); tmp += "\"/>"; tmp += "</color>"; } @@ -202,19 +195,16 @@ void PaintDef::getMIMEData(std::string const & type, char*& dest, int& len, int& } } -bool PaintDef::fromMIMEData(std::string const & type, char const * data, int len, int /*format*/) +bool PaintDef::fromMIMEData(std::string const &type, char const *data, int len, int /*format*/) { bool worked = false; bool changed = false; - if ( type == mimeTEXT ) { - } else if ( type == mimeX_COLOR ) { - } else if ( type == mimeOSWB_COLOR ) { + if (type == mimeTEXT) { + } else if (type == mimeX_COLOR) { + } else if (type == mimeOSWB_COLOR) { std::string xml(data, len); - if ( xml.find("<nocolor/>") != std::string::npos ) { - if ( (this->type != ege::PaintDef::NONE) - || (this->r != 0) - || (this->g != 0) - || (this->b != 0) ) { + if (xml.find("<nocolor/>") != std::string::npos) { + if ((this->type != ege::PaintDef::NONE) || (this->r != 0) || (this->g != 0) || (this->b != 0)) { this->type = ege::PaintDef::NONE; this->r = 0; this->g = 0; @@ -224,7 +214,7 @@ bool PaintDef::fromMIMEData(std::string const & type, char const * data, int len worked = true; } else { size_t pos = xml.find("<sRGB"); - if ( pos != std::string::npos ) { + if (pos != std::string::npos) { size_t endPos = xml.find(">", pos); std::string srgb = xml.substr(pos, endPos); this->type = ege::PaintDef::RGB; @@ -245,7 +235,7 @@ bool PaintDef::fromMIMEData(std::string const & type, char const * data, int len } size_t pos = xml.find("<color "); - if ( pos != std::string::npos ) { + if (pos != std::string::npos) { size_t endPos = xml.find(">", pos); std::string colorTag = xml.substr(pos, endPos); @@ -261,46 +251,39 @@ bool PaintDef::fromMIMEData(std::string const & type, char const * data, int len } } } - if ( changed ) { + if (changed) { // beware of callbacks changing things - for (auto & _listener : _listeners) - { - if ( _listener->_cb ) - { - _listener->_cb( _listener->_data ); + for (auto &_listener : _listeners) { + if (_listener->_cb) { + _listener->_cb(_listener->_data); } } } return worked; } -void PaintDef::setRGB( unsigned int r, unsigned int g, unsigned int b ) +void PaintDef::setRGB(unsigned int r, unsigned int g, unsigned int b) { - if ( r != this->r || g != this->g || b != this->b ) { + if (r != this->r || g != this->g || b != this->b) { this->r = r; this->g = g; this->b = b; // beware of callbacks changing things - for (auto & _listener : _listeners) - { - if ( _listener->_cb ) - { - _listener->_cb( _listener->_data ); + for (auto &_listener : _listeners) { + if (_listener->_cb) { + _listener->_cb(_listener->_data); } } } } -void PaintDef::addCallback( ColorCallback cb, void* data ) -{ - _listeners.push_back( new HookData(cb, data) ); -} - -void PaintDef::removeCallback( ColorCallback /*cb*/, void* /*data*/ ) +void PaintDef::addCallback(ColorCallback cb, void *data) { + _listeners.push_back(new HookData(cb, data)); } +void PaintDef::removeCallback(ColorCallback /*cb*/, void * /*data*/) {} } // namespace ege diff --git a/src/widgets/ege-paint-def.h b/src/widgets/ege-paint-def.h index 63643c53a0e24ce10dce87a083500cfa7ccba92c..fb7c421ef6676aaf0daeb07ed7a7d5bb8889e66d 100644 --- a/src/widgets/ege-paint-def.h +++ b/src/widgets/ege-paint-def.h @@ -41,11 +41,9 @@ #include <string> #include <vector> -namespace ege -{ - -typedef void (*ColorCallback)( void* data ); +namespace ege { +typedef void (*ColorCallback)(void *data); /** * Pure data representation of a color definition. @@ -53,32 +51,37 @@ typedef void (*ColorCallback)( void* data ); class PaintDef { public: - enum ColorType{CLEAR, NONE, RGB}; + enum ColorType + { + CLEAR, + NONE, + RGB + }; PaintDef(); PaintDef(ColorType type); - PaintDef( unsigned int r, unsigned int g, unsigned int b, std::string description ); + PaintDef(unsigned int r, unsigned int g, unsigned int b, std::string description); virtual ~PaintDef(); - PaintDef( PaintDef const &other ); - virtual PaintDef& operator=( PaintDef const &other ); + PaintDef(PaintDef const &other); + virtual PaintDef &operator=(PaintDef const &other); ColorType getType() const { return type; } std::vector<std::string> getMIMETypes(); - void getMIMEData(std::string const & type, char*& dest, int& len, int& format); - bool fromMIMEData(std::string const & type, char const * data, int len, int format); + void getMIMEData(std::string const &type, char *&dest, int &len, int &format); + bool fromMIMEData(std::string const &type, char const *data, int len, int format); - void setRGB( unsigned int r, unsigned int g, unsigned int b ); + void setRGB(unsigned int r, unsigned int g, unsigned int b); unsigned int getR() const { return r; } unsigned int getG() const { return g; } unsigned int getB() const { return b; } - void addCallback( ColorCallback cb, void* data ); - void removeCallback( ColorCallback cb, void* data ); + void addCallback(ColorCallback cb, void *data); + void removeCallback(ColorCallback cb, void *data); bool isEditable() const { return editable; } - void setEditable( bool edit ) { editable = edit; } + void setEditable(bool edit) { editable = edit; } std::string descr; @@ -92,10 +95,9 @@ protected: private: class HookData; - std::vector<HookData*> _listeners; + std::vector<HookData *> _listeners; }; - } // namespace ege #endif // SEEN_EGE_PAINT_DEF_H diff --git a/src/widgets/ink-action.cpp b/src/widgets/ink-action.cpp index 33bb971eed4379ea91003f980eb35dd906cadf76..b1eec0f9c0ce2e0cf5a1db557fc7b8a6bfb8639d 100644 --- a/src/widgets/ink-action.cpp +++ b/src/widgets/ink-action.cpp @@ -8,36 +8,38 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ #include "ink-action.h" -#include "ui/icon-loader.h" + #include <gtk/gtk.h> -static void ink_action_finalize( GObject* obj ); -static void ink_action_get_property( GObject* obj, guint propId, GValue* value, GParamSpec * pspec ); -static void ink_action_set_property( GObject* obj, guint propId, const GValue *value, GParamSpec* pspec ); +#include "ui/icon-loader.h" + +static void ink_action_finalize(GObject *obj); +static void ink_action_get_property(GObject *obj, guint propId, GValue *value, GParamSpec *pspec); +static void ink_action_set_property(GObject *obj, guint propId, const GValue *value, GParamSpec *pspec); -static GtkWidget* ink_action_create_menu_item( GtkAction* action ); -static GtkWidget* ink_action_create_tool_item( GtkAction* action ); +static GtkWidget *ink_action_create_menu_item(GtkAction *action); +static GtkWidget *ink_action_create_tool_item(GtkAction *action); typedef struct { - gchar* iconId; + gchar *iconId; GtkIconSize iconSize; } InkActionPrivate; -#define INK_ACTION_GET_PRIVATE( o ) \ - reinterpret_cast<InkActionPrivate *>(ink_action_get_instance_private (o)) +#define INK_ACTION_GET_PRIVATE(o) reinterpret_cast<InkActionPrivate *>(ink_action_get_instance_private(o)) G_DEFINE_TYPE_WITH_PRIVATE(InkAction, ink_action, GTK_TYPE_ACTION); -enum { +enum +{ PROP_INK_ID = 1, PROP_INK_SIZE }; -static void ink_action_class_init( InkActionClass* klass ) +static void ink_action_class_init(InkActionClass *klass) { - if ( klass ) { - GObjectClass * objClass = G_OBJECT_CLASS( klass ); + if (klass) { + GObjectClass *objClass = G_OBJECT_CLASS(klass); objClass->finalize = ink_action_finalize; objClass->get_property = ink_action_get_property; @@ -48,141 +50,116 @@ static void ink_action_class_init( InkActionClass* klass ) /*klass->parent_class.connect_proxy = connect_proxy;*/ /*klass->parent_class.disconnect_proxy = disconnect_proxy;*/ - g_object_class_install_property( objClass, - PROP_INK_ID, - g_param_spec_string( "iconId", - "Icon ID", - "The id for the icon", - "", - (GParamFlags)(G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT) ) ); - - g_object_class_install_property( objClass, - PROP_INK_SIZE, - g_param_spec_int( "iconSize", - "Icon Size", - "The size the icon", - (int)GTK_ICON_SIZE_MENU, - (int)GTK_ICON_SIZE_DIALOG, - (int)GTK_ICON_SIZE_SMALL_TOOLBAR, - (GParamFlags)(G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT) ) ); + g_object_class_install_property( + objClass, PROP_INK_ID, + g_param_spec_string("iconId", "Icon ID", "The id for the icon", "", + (GParamFlags)(G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT))); + + g_object_class_install_property( + objClass, PROP_INK_SIZE, + g_param_spec_int("iconSize", "Icon Size", "The size the icon", (int)GTK_ICON_SIZE_MENU, + (int)GTK_ICON_SIZE_DIALOG, (int)GTK_ICON_SIZE_SMALL_TOOLBAR, + (GParamFlags)(G_PARAM_READABLE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT))); } } -static void ink_action_init( InkAction* action ) +static void ink_action_init(InkAction *action) { - auto priv = INK_ACTION_GET_PRIVATE (action); + auto priv = INK_ACTION_GET_PRIVATE(action); priv->iconId = nullptr; priv->iconSize = GTK_ICON_SIZE_SMALL_TOOLBAR; } -static void ink_action_finalize( GObject* obj ) +static void ink_action_finalize(GObject *obj) { - InkAction* action = INK_ACTION( obj ); - auto priv = INK_ACTION_GET_PRIVATE (action); - - g_free( priv->iconId ); - g_free( priv ); + InkAction *action = INK_ACTION(obj); + auto priv = INK_ACTION_GET_PRIVATE(action); + g_free(priv->iconId); + g_free(priv); } -//Any strings passed in should already be localised -InkAction* ink_action_new( const gchar *name, - const gchar *label, - const gchar *tooltip, - const gchar *inkId, - GtkIconSize size ) +// Any strings passed in should already be localised +InkAction *ink_action_new(const gchar *name, const gchar *label, const gchar *tooltip, const gchar *inkId, + GtkIconSize size) { - GObject* obj = (GObject*)g_object_new( INK_ACTION_TYPE, - "name", name, - "label", label, - "tooltip", tooltip, - "iconId", inkId, - "iconSize", size, - NULL ); + GObject *obj = (GObject *)g_object_new(INK_ACTION_TYPE, "name", name, "label", label, "tooltip", tooltip, "iconId", + inkId, "iconSize", size, NULL); - InkAction* action = INK_ACTION( obj ); + InkAction *action = INK_ACTION(obj); return action; } -static void ink_action_get_property( GObject* obj, guint propId, GValue* value, GParamSpec * pspec ) +static void ink_action_get_property(GObject *obj, guint propId, GValue *value, GParamSpec *pspec) { - InkAction* action = INK_ACTION( obj ); - auto priv = INK_ACTION_GET_PRIVATE (action); + InkAction *action = INK_ACTION(obj); + auto priv = INK_ACTION_GET_PRIVATE(action); - switch ( propId ) { - case PROP_INK_ID: - { - g_value_set_string( value, priv->iconId ); - } - break; + switch (propId) { + case PROP_INK_ID: { + g_value_set_string(value, priv->iconId); + } break; - case PROP_INK_SIZE: - { - g_value_set_int( value, priv->iconSize ); - } - break; + case PROP_INK_SIZE: { + g_value_set_int(value, priv->iconSize); + } break; default: - G_OBJECT_WARN_INVALID_PROPERTY_ID( obj, propId, pspec ); + G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, propId, pspec); } } -void ink_action_set_property( GObject* obj, guint propId, const GValue *value, GParamSpec* pspec ) +void ink_action_set_property(GObject *obj, guint propId, const GValue *value, GParamSpec *pspec) { - InkAction* action = INK_ACTION( obj ); - auto priv = INK_ACTION_GET_PRIVATE (action); - - switch ( propId ) { - case PROP_INK_ID: - { - gchar* tmp = priv->iconId; - priv->iconId = g_value_dup_string( value ); - g_free( tmp ); - } - break; - - case PROP_INK_SIZE: - { - priv->iconSize = (GtkIconSize)g_value_get_int( value ); - } - break; - - default: - { - G_OBJECT_WARN_INVALID_PROPERTY_ID( obj, propId, pspec ); + InkAction *action = INK_ACTION(obj); + auto priv = INK_ACTION_GET_PRIVATE(action); + + switch (propId) { + case PROP_INK_ID: { + gchar *tmp = priv->iconId; + priv->iconId = g_value_dup_string(value); + g_free(tmp); + } break; + + case PROP_INK_SIZE: { + priv->iconSize = (GtkIconSize)g_value_get_int(value); + } break; + + default: { + G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, propId, pspec); } } } -static GtkWidget* ink_action_create_menu_item( GtkAction* action ) +static GtkWidget *ink_action_create_menu_item(GtkAction *action) { - GtkWidget* item = GTK_ACTION_CLASS(ink_action_parent_class)->create_menu_item( action ); + GtkWidget *item = GTK_ACTION_CLASS(ink_action_parent_class)->create_menu_item(action); return item; } -static GtkWidget* ink_action_create_tool_item( GtkAction* action ) +static GtkWidget *ink_action_create_tool_item(GtkAction *action) { - InkAction* act = INK_ACTION( action ); - auto priv = INK_ACTION_GET_PRIVATE (act); - GtkWidget* item = GTK_ACTION_CLASS(ink_action_parent_class)->create_tool_item(action); + InkAction *act = INK_ACTION(action); + auto priv = INK_ACTION_GET_PRIVATE(act); + GtkWidget *item = GTK_ACTION_CLASS(ink_action_parent_class)->create_tool_item(action); - if ( priv->iconId ) { - if ( GTK_IS_TOOL_BUTTON(item) ) { - GtkToolButton* button = GTK_TOOL_BUTTON(item); + if (priv->iconId) { + if (GTK_IS_TOOL_BUTTON(item)) { + GtkToolButton *button = GTK_TOOL_BUTTON(item); GtkWidget *child = sp_get_icon_image(priv->iconId, priv->iconSize); - gtk_tool_button_set_icon_widget( button, child ); + gtk_tool_button_set_icon_widget(button, child); } else { // For now trigger a warning but don't do anything else - GtkToolButton* button = GTK_TOOL_BUTTON(item); + GtkToolButton *button = GTK_TOOL_BUTTON(item); (void)button; } } // TODO investigate if needed - gtk_widget_show_all( item ); + gtk_widget_show_all(item); return item; } diff --git a/src/widgets/ink-action.h b/src/widgets/ink-action.h index d97afe13e31fd62585df11d5092353aeba5ee318..62ba0f9d02cfa7d250662643a2d4ebb9c918f00d 100644 --- a/src/widgets/ink-action.h +++ b/src/widgets/ink-action.h @@ -11,20 +11,21 @@ #define SEEN_INK_ACTION #include <gtk/gtk.h> + #include "attributes.h" /* Equivalent to GTK Actions of the same type, but can support Inkscape SVG icons */ G_BEGIN_DECLS -#define INK_ACTION_TYPE ( ink_action_get_type() ) -#define INK_ACTION( obj ) ( G_TYPE_CHECK_INSTANCE_CAST( (obj), INK_ACTION_TYPE, InkAction) ) -#define INK_ACTION_CLASS( klass ) ( G_TYPE_CHECK_CLASS_CAST( (klass), INK_ACTION_TYPE, InkActionClass) ) -#define IS_INK_ACTION( obj ) ( G_TYPE_CHECK_INSTANCE_TYPE( (obj), INK_ACTION_TYPE) ) -#define IS_INK_ACTION_CLASS( klass ) ( G_TYPE_CHECK_CLASS_TYPE( (klass), INK_ACTION_TYPE) ) -#define INK_ACTION_GET_CLASS( obj ) ( G_TYPE_INSTANCE_GET_CLASS( (obj), INK_ACTION_TYPE, InkActionClass) ) +#define INK_ACTION_TYPE (ink_action_get_type()) +#define INK_ACTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), INK_ACTION_TYPE, InkAction)) +#define INK_ACTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), INK_ACTION_TYPE, InkActionClass)) +#define IS_INK_ACTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), INK_ACTION_TYPE)) +#define IS_INK_ACTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), INK_ACTION_TYPE)) +#define INK_ACTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), INK_ACTION_TYPE, InkActionClass)) -typedef struct _InkAction InkAction; +typedef struct _InkAction InkAction; typedef struct _InkActionClass InkActionClass; struct _InkAction @@ -37,14 +38,10 @@ struct _InkActionClass GtkActionClass parent_class; }; -GType ink_action_get_type( void ); - -InkAction* ink_action_new( const gchar *name, - const gchar *label, - const gchar *tooltip, - const gchar *inkId, - GtkIconSize size ); +GType ink_action_get_type(void); +InkAction *ink_action_new(const gchar *name, const gchar *label, const gchar *tooltip, const gchar *inkId, + GtkIconSize size); G_END_DECLS diff --git a/src/widgets/sp-attribute-widget.cpp b/src/widgets/sp-attribute-widget.cpp index a82d06dd60b41dbff6dd58c7cd4ad608666f3464..1dae2a1e251fd0335eb9b1bc1ac516be45926e52 100644 --- a/src/widgets/sp-attribute-widget.cpp +++ b/src/widgets/sp-attribute-widget.cpp @@ -13,21 +13,18 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-attribute-widget.h" + #include <glibmm/i18n.h> #include <gtkmm/entry.h> #include <gtkmm/grid.h> -#include "sp-attribute-widget.h" - -#include "include/macros.h" -#include "document.h" #include "document-undo.h" -#include "verbs.h" - +#include "document.h" #include "include/gtkmm_version.h" - +#include "include/macros.h" #include "object/sp-object.h" - +#include "verbs.h" #include "xml/repr.h" using Inkscape::DocumentUndo; @@ -38,108 +35,98 @@ using Inkscape::DocumentUndo; * sp_attribute_table_entry_changed set the object property * to the new value and updates history. It is a callback from * the entries created by SPAttributeTable. - * + * * @param editable pointer to the entry box. * @param spat pointer to the SPAttributeTable instance. */ -static void sp_attribute_table_entry_changed (Gtk::Entry *editable, SPAttributeTable *spat); +static void sp_attribute_table_entry_changed(Gtk::Entry *editable, SPAttributeTable *spat); /** * Callback for a modification of the selected object (size, color, properties, etc.). * * sp_attribute_table_object_modified rereads the object properties * and shows the values in the entry boxes. It is a callback from a * connection of the SPObject. - * + * * @param object the SPObject to which this instance is referring to. * @param flags gives the applied modifications * @param spat pointer to the SPAttributeTable instance. */ -static void sp_attribute_table_object_modified (SPObject *object, guint flags, SPAttributeTable *spaw); +static void sp_attribute_table_object_modified(SPObject *object, guint flags, SPAttributeTable *spaw); /** * Callback for the deletion of the selected object. * - * sp_attribute_table_object_release invalidates all data of + * sp_attribute_table_object_release invalidates all data of * SPAttributeTable and disables the widget. */ -static void sp_attribute_table_object_release (SPObject */*object*/, SPAttributeTable *spat); +static void sp_attribute_table_object_release(SPObject * /*object*/, SPAttributeTable *spat); #define XPAD 4 #define YPAD 0 - -SPAttributeTable::SPAttributeTable () : - _object(nullptr), - blocked(false), - table(nullptr), - _attributes(), - _entries(), - modified_connection(), - release_connection() -{ -} - -SPAttributeTable::SPAttributeTable (SPObject *object, std::vector<Glib::ustring> &labels, std::vector<Glib::ustring> &attributes, GtkWidget* parent) : - _object(nullptr), - blocked(false), - table(nullptr), - _attributes(), - _entries(), - modified_connection(), - release_connection() +SPAttributeTable::SPAttributeTable() + : _object(nullptr) + , blocked(false) + , table(nullptr) + , _attributes() + , _entries() + , modified_connection() + , release_connection() +{} + +SPAttributeTable::SPAttributeTable(SPObject *object, std::vector<Glib::ustring> &labels, + std::vector<Glib::ustring> &attributes, GtkWidget *parent) + : _object(nullptr) + , blocked(false) + , table(nullptr) + , _attributes() + , _entries() + , modified_connection() + , release_connection() { set_object(object, labels, attributes, parent); } -SPAttributeTable::~SPAttributeTable () +SPAttributeTable::~SPAttributeTable() { clear(); } void SPAttributeTable::clear() { - if (table) - { - std::vector<Gtk::Widget*> ch = table->get_children(); - for (int i = (ch.size())-1; i >=0 ; i--) - { + if (table) { + std::vector<Gtk::Widget *> ch = table->get_children(); + for (int i = (ch.size()) - 1; i >= 0; i--) { Gtk::Widget *w = ch[i]; ch.pop_back(); - if (w != nullptr) - { - try - { - sp_signal_disconnect_by_data (w->gobj(), this); + if (w != nullptr) { + try { + sp_signal_disconnect_by_data(w->gobj(), this); delete w; - } - catch(...) - { + } catch (...) { } } } ch.clear(); _attributes.clear(); _entries.clear(); - + delete table; table = nullptr; } - if (_object) - { + if (_object) { modified_connection.disconnect(); release_connection.disconnect(); _object = nullptr; } } -void SPAttributeTable::set_object(SPObject *object, - std::vector<Glib::ustring> &labels, - std::vector<Glib::ustring> &attributes, - GtkWidget* parent) +void SPAttributeTable::set_object(SPObject *object, std::vector<Glib::ustring> &labels, + std::vector<Glib::ustring> &attributes, GtkWidget *parent) { - g_return_if_fail (!object || SP_IS_OBJECT (object)); - g_return_if_fail (!object || !labels.empty() || !attributes.empty()); - g_return_if_fail (labels.size() == attributes.size()); + g_return_if_fail(!object || SP_IS_OBJECT(object)); + g_return_if_fail(!object || !labels.empty() || !attributes.empty()); + g_return_if_fail(labels.size() == attributes.size()); clear(); _object = object; @@ -148,19 +135,21 @@ void SPAttributeTable::set_object(SPObject *object, blocked = true; // Set up object - modified_connection = object->connectModified(sigc::bind<2>(sigc::ptr_fun(&sp_attribute_table_object_modified), this)); - release_connection = object->connectRelease (sigc::bind<1>(sigc::ptr_fun(&sp_attribute_table_object_release), this)); + modified_connection = + object->connectModified(sigc::bind<2>(sigc::ptr_fun(&sp_attribute_table_object_modified), this)); + release_connection = + object->connectRelease(sigc::bind<1>(sigc::ptr_fun(&sp_attribute_table_object_release), this)); // Create table table = new Gtk::Grid(); if (!(parent == nullptr)) - gtk_container_add(GTK_CONTAINER(parent), (GtkWidget*)table->gobj()); - + gtk_container_add(GTK_CONTAINER(parent), (GtkWidget *)table->gobj()); + // Fill rows _attributes = attributes; for (guint i = 0; i < (attributes.size()); i++) { - Gtk::Label *ll = new Gtk::Label (_(labels[i].c_str())); + Gtk::Label *ll = new Gtk::Label(_(labels[i].c_str())); ll->show(); ll->set_halign(Gtk::ALIGN_START); ll->set_valign(Gtk::ALIGN_CENTER); @@ -174,7 +163,7 @@ void SPAttributeTable::set_object(SPObject *object, Gtk::Entry *ee = new Gtk::Entry(); ee->show(); const gchar *val = object->getRepr()->attribute(attributes[i].c_str()); - ee->set_text (val ? val : (const gchar *) ""); + ee->set_text(val ? val : (const gchar *)""); ee->set_hexpand(); ee->set_vexpand(); ee->set_margin_start(XPAD); @@ -184,21 +173,18 @@ void SPAttributeTable::set_object(SPObject *object, table->attach(*ee, 1, i, 1, 1); _entries.push_back(ee); - g_signal_connect ( ee->gobj(), "changed", - G_CALLBACK (sp_attribute_table_entry_changed), - this ); + g_signal_connect(ee->gobj(), "changed", G_CALLBACK(sp_attribute_table_entry_changed), this); } /* Show table */ - table->show (); + table->show(); blocked = false; } } void SPAttributeTable::change_object(SPObject *object) { - g_return_if_fail (!object || SP_IS_OBJECT (object)); - if (_object) - { + g_return_if_fail(!object || SP_IS_OBJECT(object)); + if (_object) { modified_connection.disconnect(); release_connection.disconnect(); _object = nullptr; @@ -209,47 +195,44 @@ void SPAttributeTable::change_object(SPObject *object) blocked = true; // Set up object - modified_connection = _object->connectModified(sigc::bind<2>(sigc::ptr_fun(&sp_attribute_table_object_modified), this)); - release_connection = _object->connectRelease (sigc::bind<1>(sigc::ptr_fun(&sp_attribute_table_object_release), this)); + modified_connection = + _object->connectModified(sigc::bind<2>(sigc::ptr_fun(&sp_attribute_table_object_modified), this)); + release_connection = + _object->connectRelease(sigc::bind<1>(sigc::ptr_fun(&sp_attribute_table_object_release), this)); for (guint i = 0; i < (_attributes.size()); i++) { const gchar *val = _object->getRepr()->attribute(_attributes[i].c_str()); _entries[i]->set_text(val ? val : ""); } - + blocked = false; } - } void SPAttributeTable::reread_properties() { blocked = true; - for (guint i = 0; i < (_attributes.size()); i++) - { + for (guint i = 0; i < (_attributes.size()); i++) { const gchar *val = _object->getRepr()->attribute(_attributes[i].c_str()); _entries[i]->set_text(val ? val : ""); } - blocked = false; + blocked = false; } -static void sp_attribute_table_object_modified ( SPObject */*object*/, - guint flags, - SPAttributeTable *spat ) +static void sp_attribute_table_object_modified(SPObject * /*object*/, guint flags, SPAttributeTable *spat) { - if (flags & SP_OBJECT_MODIFIED_FLAG) - { + if (flags & SP_OBJECT_MODIFIED_FLAG) { std::vector<Glib::ustring> attributes = spat->get_attributes(); std::vector<Gtk::Entry *> entries = spat->get_entries(); - Glib::ustring text=""; + Glib::ustring text = ""; for (guint i = 0; i < (attributes.size()); i++) { - Gtk::Entry* e = entries[i]; + Gtk::Entry *e = entries[i]; const gchar *val = spat->_object->getRepr()->attribute(attributes[i].c_str()); - text = e->get_text (); + text = e->get_text(); if (val || !text.empty()) { if (text != val) { // We are different spat->blocked = true; - e->set_text (val ? val : (const gchar *) ""); + e->set_text(val ? val : (const gchar *)""); spat->blocked = false; } } @@ -258,37 +241,34 @@ static void sp_attribute_table_object_modified ( SPObject */*object*/, } // end of sp_attribute_table_object_modified() -static void sp_attribute_table_entry_changed ( Gtk::Entry *editable, - SPAttributeTable *spat ) +static void sp_attribute_table_entry_changed(Gtk::Entry *editable, SPAttributeTable *spat) { - if (!spat->blocked) - { + if (!spat->blocked) { std::vector<Glib::ustring> attributes = spat->get_attributes(); std::vector<Gtk::Entry *> entries = spat->get_entries(); for (guint i = 0; i < (attributes.size()); i++) { Gtk::Entry *e = entries[i]; - if ((GtkWidget*)editable == (GtkWidget*)e->gobj()) { + if ((GtkWidget *)editable == (GtkWidget *)e->gobj()) { spat->blocked = true; - Glib::ustring text = e->get_text (); + Glib::ustring text = e->get_text(); if (spat->_object) { spat->_object->getRepr()->setAttribute(attributes[i], text); - DocumentUndo::done(spat->_object->document, SP_VERB_NONE, - _("Set attribute")); + DocumentUndo::done(spat->_object->document, SP_VERB_NONE, _("Set attribute")); } spat->blocked = false; return; } } - g_warning ("file %s: line %d: Entry signalled change, but there is no such entry", __FILE__, __LINE__); + g_warning("file %s: line %d: Entry signalled change, but there is no such entry", __FILE__, __LINE__); } } // end of sp_attribute_table_entry_changed() -static void sp_attribute_table_object_release (SPObject */*object*/, SPAttributeTable *spat) +static void sp_attribute_table_object_release(SPObject * /*object*/, SPAttributeTable *spat) { std::vector<Glib::ustring> labels; std::vector<Glib::ustring> attributes; - spat->set_object (nullptr, labels, attributes, nullptr); + spat->set_object(nullptr, labels, attributes, nullptr); } /* diff --git a/src/widgets/sp-attribute-widget.h b/src/widgets/sp-attribute-widget.h index f43fe84e70e459c9fef611a31da82e41f4b80d87..8d98f20b661b724a65c3bf81be3dc2757d94122d 100644 --- a/src/widgets/sp-attribute-widget.h +++ b/src/widgets/sp-attribute-widget.h @@ -16,22 +16,22 @@ #ifndef SEEN_DIALOGS_SP_ATTRIBUTE_WIDGET_H #define SEEN_DIALOGS_SP_ATTRIBUTE_WIDGET_H -#include <gtkmm/widget.h> #include <cstddef> +#include <gtkmm/widget.h> #include <sigc++/connection.h> namespace Gtk { class Entry; class Grid; -} +} // namespace Gtk namespace Inkscape { namespace XML { class Node; } -} +} // namespace Inkscape -class SPObject; +class SPObject; /** * A base class for dialogs to enter the value of several properties. @@ -40,44 +40,49 @@ class SPObject; * an object. For each property, it creates an entry next to a label and * positiones these labels and entries one by one below each other. */ -class SPAttributeTable : public Gtk::Widget { +class SPAttributeTable : public Gtk::Widget +{ public: /** * Constructor defaulting to no content. */ - SPAttributeTable (); - + SPAttributeTable(); + /** * Constructor referring to a specific object. * * This constructor initializes all data fields and creates the necessary widgets. * set_object is called for this purpose. - * - * @param object the SPObject to which this instance is referring to. It should be the object that is currently selected and whose properties are being shown by this SPAttributeTable instance. + * + * @param object the SPObject to which this instance is referring to. It should be the object that is currently + * selected and whose properties are being shown by this SPAttributeTable instance. * @param labels list of labels to be shown for the different attributes. * @param attributes list of attributes whose value can be edited. * @param parent the parent object owning the SPAttributeTable instance. - * + * * @see set_object */ - SPAttributeTable (SPObject *object, std::vector<Glib::ustring> &labels, std::vector<Glib::ustring> &attributes, GtkWidget* parent); - - ~SPAttributeTable () override; - + SPAttributeTable(SPObject *object, std::vector<Glib::ustring> &labels, std::vector<Glib::ustring> &attributes, + GtkWidget *parent); + + ~SPAttributeTable() override; + /** * Sets class properties and creates child widgets * * set_object initializes all data fields, creates links to the * SPOject item and creates the necessary widgets. For n properties * n labels and n entries are created and shown in tabular format. - * - * @param object the SPObject to which this instance is referring to. It should be the object that is currently selected and whose properties are being shown by this SPAttribuTable instance. + * + * @param object the SPObject to which this instance is referring to. It should be the object that is currently + * selected and whose properties are being shown by this SPAttribuTable instance. * @param labels list of labels to be shown for the different attributes. * @param attributes list of attributes whose value can be edited. * @param parent the parent object owning the SPAttributeTable instance. */ - void set_object(SPObject *object, std::vector<Glib::ustring> &labels, std::vector<Glib::ustring> &attributes, GtkWidget* parent); - + void set_object(SPObject *object, std::vector<Glib::ustring> &labels, std::vector<Glib::ustring> &attributes, + GtkWidget *parent); + /** * Update values in entry boxes on change of object. * @@ -87,41 +92,42 @@ public: * the parent class (holding the SPAttributeTable instance). This function * should only be called when the number of properties/entries nor * the labels do not change. - * - * @param object the SPObject to which this instance is referring to. It should be the object that is currently selected and whose properties are being shown by this SPAttribuTable instance. + * + * @param object the SPObject to which this instance is referring to. It should be the object that is currently + * selected and whose properties are being shown by this SPAttribuTable instance. */ void change_object(SPObject *object); - + /** * Clears data of SPAttributeTable instance, destroys all child widgets and closes connections. */ void clear(); - + /** * Reads the object attributes. - * + * * Reads the object attributes and shows the new object attributes in the * entry boxes. Caution: function should only be used when which there is * no change in which objects are selected. */ void reread_properties(); - - /** + + /** * Gives access to the attributes list. */ - std::vector<Glib::ustring> get_attributes() {return _attributes;}; - - /** + std::vector<Glib::ustring> get_attributes() { return _attributes; }; + + /** * Gives access to the Gtk::Entry list. */ - std::vector<Gtk::Entry *> get_entries() {return _entries;}; - - /** + std::vector<Gtk::Entry *> get_entries() { return _entries; }; + + /** * Stores pointer to the selected object. */ SPObject *_object; - - /** + + /** * Indicates whether SPAttributeTable is processing callbacks and whether it should accept any updating. */ bool blocked; @@ -130,29 +136,29 @@ private: /** * Container widget for the dynamically created child widgets (labels and entry boxes). */ - Gtk::Grid *table; - + Gtk::Grid *table; + /** * List of attributes. - * + * * _attributes stores the attribute names of the selected object that - * are valid and can be modified through this widget. + * are valid and can be modified through this widget. */ std::vector<Glib::ustring> _attributes; - /** + /** * List of pointers to the respective entry boxes. - * + * * _entries stores pointers to the dynamically created entry boxes in which - * the user can midify the attributes of the selected object. + * the user can midify the attributes of the selected object. */ std::vector<Gtk::Entry *> _entries; - - /** + + /** * Sets the callback for a modification of the selection. */ sigc::connection modified_connection; - - /** + + /** * Sets the callback for the deletion of the selected object. */ sigc::connection release_connection; diff --git a/src/widgets/sp-xmlview-tree.cpp b/src/widgets/sp-xmlview-tree.cpp index 1f4f4b46bcd7fefc0601911ef5977cca990e230a..ffda3142fdd0eec9223b966e876874b5cadd961a 100644 --- a/src/widgets/sp-xmlview-tree.cpp +++ b/src/widgets/sp-xmlview-tree.cpp @@ -10,17 +10,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "sp-xmlview-tree.h" + #include <cstring> #include <gmodule.h> #include "xml/node-event-vector.h" -#include "sp-xmlview-tree.h" namespace { -struct NodeData { - SPXMLViewTree * tree; - GtkTreeRowReference *rowref; - Inkscape::XML::Node * repr; +struct NodeData +{ + SPXMLViewTree *tree; + GtkTreeRowReference *rowref; + Inkscape::XML::Node *repr; bool expanded = false; //< true if tree view has been expanded to this node bool dragging = false; @@ -32,29 +34,41 @@ struct NodeData { Inkscape::XML::Node *dragging_repr = nullptr; } // namespace -enum { STORE_TEXT_COL = 0, STORE_DATA_COL, STORE_N_COLS }; +enum +{ + STORE_TEXT_COL = 0, + STORE_DATA_COL, + STORE_N_COLS +}; -static void sp_xmlview_tree_destroy(GtkWidget * object); +static void sp_xmlview_tree_destroy(GtkWidget *object); static NodeData *sp_xmlview_tree_node_get_data(GtkTreeModel *model, GtkTreeIter *iter); static void add_node(SPXMLViewTree *tree, GtkTreeIter *parent, GtkTreeIter *before, Inkscape::XML::Node *repr); -static void element_child_added (Inkscape::XML::Node * repr, Inkscape::XML::Node * child, Inkscape::XML::Node * ref, gpointer data); -static void element_attr_changed (Inkscape::XML::Node * repr, const gchar * key, const gchar * old_value, const gchar * new_value, bool is_interactive, gpointer data); -static void element_child_removed (Inkscape::XML::Node * repr, Inkscape::XML::Node * child, Inkscape::XML::Node * ref, gpointer data); -static void element_order_changed (Inkscape::XML::Node * repr, Inkscape::XML::Node * child, Inkscape::XML::Node * oldref, Inkscape::XML::Node * newref, gpointer data); -static void element_name_changed (Inkscape::XML::Node* repr, gchar const* oldname, gchar const* newname, gpointer data); -static void element_attr_or_name_change_update(Inkscape::XML::Node* repr, NodeData* data); - -static void text_content_changed (Inkscape::XML::Node * repr, const gchar * old_content, const gchar * new_content, gpointer data); -static void comment_content_changed (Inkscape::XML::Node * repr, const gchar * old_content, const gchar * new_content, gpointer data); -static void pi_content_changed (Inkscape::XML::Node * repr, const gchar * old_content, const gchar * new_content, gpointer data); - -static gboolean ref_to_sibling (NodeData *node, Inkscape::XML::Node * ref, GtkTreeIter *); -static gboolean repr_to_child (NodeData *node, Inkscape::XML::Node * repr, GtkTreeIter *); +static void element_child_added(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, + gpointer data); +static void element_attr_changed(Inkscape::XML::Node *repr, const gchar *key, const gchar *old_value, + const gchar *new_value, bool is_interactive, gpointer data); +static void element_child_removed(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, + gpointer data); +static void element_order_changed(Inkscape::XML::Node *repr, Inkscape::XML::Node *child, Inkscape::XML::Node *oldref, + Inkscape::XML::Node *newref, gpointer data); +static void element_name_changed(Inkscape::XML::Node *repr, gchar const *oldname, gchar const *newname, gpointer data); +static void element_attr_or_name_change_update(Inkscape::XML::Node *repr, NodeData *data); + +static void text_content_changed(Inkscape::XML::Node *repr, const gchar *old_content, const gchar *new_content, + gpointer data); +static void comment_content_changed(Inkscape::XML::Node *repr, const gchar *old_content, const gchar *new_content, + gpointer data); +static void pi_content_changed(Inkscape::XML::Node *repr, const gchar *old_content, const gchar *new_content, + gpointer data); + +static gboolean ref_to_sibling(NodeData *node, Inkscape::XML::Node *ref, GtkTreeIter *); +static gboolean repr_to_child(NodeData *node, Inkscape::XML::Node *repr, GtkTreeIter *); static GtkTreeRowReference *tree_iter_to_ref(SPXMLViewTree *, GtkTreeIter *); -static gboolean tree_ref_to_iter (SPXMLViewTree * tree, GtkTreeIter* iter, GtkTreeRowReference *ref); +static gboolean tree_ref_to_iter(SPXMLViewTree *tree, GtkTreeIter *iter, GtkTreeRowReference *ref); static gboolean search_equal_func(GtkTreeModel *, gint column, const gchar *key, GtkTreeIter *, gpointer search_data); static gboolean foreach_func(GtkTreeModel *, GtkTreePath *, GtkTreeIter *, gpointer user_data); @@ -64,40 +78,35 @@ static void on_drag_begin(GtkWidget *, GdkDragContext *, gpointer userdata); static void on_drag_end(GtkWidget *, GdkDragContext *, gpointer userdata); static gboolean do_drag_motion(GtkWidget *, GdkDragContext *, gint x, gint y, guint time, gpointer user_data); -static const Inkscape::XML::NodeEventVector element_repr_events = { - element_child_added, - element_child_removed, - element_attr_changed, - nullptr, /* content_changed */ - element_order_changed, - element_name_changed -}; +static const Inkscape::XML::NodeEventVector element_repr_events = {element_child_added, element_child_removed, + element_attr_changed, nullptr, /* content_changed */ + element_order_changed, element_name_changed}; static const Inkscape::XML::NodeEventVector text_repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - nullptr, /* attr_changed */ - text_content_changed, - nullptr /* order_changed */, - nullptr /* element_name_changed */ + nullptr, /* child_added */ + nullptr, /* child_removed */ + nullptr, /* attr_changed */ + text_content_changed, + nullptr /* order_changed */, + nullptr /* element_name_changed */ }; static const Inkscape::XML::NodeEventVector comment_repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - nullptr, /* attr_changed */ - comment_content_changed, - nullptr /* order_changed */, - nullptr /* element_name_changed */ + nullptr, /* child_added */ + nullptr, /* child_removed */ + nullptr, /* attr_changed */ + comment_content_changed, + nullptr /* order_changed */, + nullptr /* element_name_changed */ }; static const Inkscape::XML::NodeEventVector pi_repr_events = { - nullptr, /* child_added */ - nullptr, /* child_removed */ - nullptr, /* attr_changed */ - pi_content_changed, - nullptr /* order_changed */, - nullptr /* element_name_changed */ + nullptr, /* child_added */ + nullptr, /* child_removed */ + nullptr, /* attr_changed */ + pi_content_changed, + nullptr /* order_changed */, + nullptr /* element_name_changed */ }; /** @@ -154,26 +163,26 @@ static gboolean on_test_expand_row( // return false; } -GtkWidget *sp_xmlview_tree_new(Inkscape::XML::Node * repr, void * /*factory*/, void * /*data*/) +GtkWidget *sp_xmlview_tree_new(Inkscape::XML::Node *repr, void * /*factory*/, void * /*data*/) { - SPXMLViewTree *tree = SP_XMLVIEW_TREE(g_object_new (SP_TYPE_XMLVIEW_TREE, nullptr)); + SPXMLViewTree *tree = SP_XMLVIEW_TREE(g_object_new(SP_TYPE_XMLVIEW_TREE, nullptr)); - gtk_tree_view_set_headers_visible (GTK_TREE_VIEW(tree), FALSE); - gtk_tree_view_set_reorderable (GTK_TREE_VIEW(tree), TRUE); - gtk_tree_view_set_enable_search (GTK_TREE_VIEW(tree), TRUE); - gtk_tree_view_set_search_equal_func (GTK_TREE_VIEW(tree), search_equal_func, nullptr, nullptr); + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree), FALSE); + gtk_tree_view_set_reorderable(GTK_TREE_VIEW(tree), TRUE); + gtk_tree_view_set_enable_search(GTK_TREE_VIEW(tree), TRUE); + gtk_tree_view_set_search_equal_func(GTK_TREE_VIEW(tree), search_equal_func, nullptr, nullptr); - GtkCellRenderer *renderer = gtk_cell_renderer_text_new (); - GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes ("", renderer, "text", STORE_TEXT_COL, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (tree), column); - gtk_cell_renderer_set_padding (renderer, 2, 0); - gtk_tree_view_column_set_sizing (column, GTK_TREE_VIEW_COLUMN_AUTOSIZE); + GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes("", renderer, "text", STORE_TEXT_COL, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column); + gtk_cell_renderer_set_padding(renderer, 2, 0); + gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE); - sp_xmlview_tree_set_repr (tree, repr); + sp_xmlview_tree_set_repr(tree, repr); g_signal_connect(GTK_TREE_VIEW(tree), "drag-begin", G_CALLBACK(on_drag_begin), tree); g_signal_connect(GTK_TREE_VIEW(tree), "drag-end", G_CALLBACK(on_drag_end), tree); - g_signal_connect(GTK_TREE_VIEW(tree), "drag-motion", G_CALLBACK(do_drag_motion), tree); + g_signal_connect(GTK_TREE_VIEW(tree), "drag-motion", G_CALLBACK(do_drag_motion), tree); g_signal_connect(GTK_TREE_VIEW(tree), "test-expand-row", G_CALLBACK(on_test_expand_row), nullptr); return GTK_WIDGET(tree); @@ -181,54 +190,46 @@ GtkWidget *sp_xmlview_tree_new(Inkscape::XML::Node * repr, void * /*factory*/, v G_DEFINE_TYPE(SPXMLViewTree, sp_xmlview_tree, GTK_TYPE_TREE_VIEW); -void sp_xmlview_tree_class_init(SPXMLViewTreeClass * klass) +void sp_xmlview_tree_class_init(SPXMLViewTreeClass *klass) { auto widget_class = GTK_WIDGET_CLASS(klass); widget_class->destroy = sp_xmlview_tree_destroy; - + // Signal for when a tree drag and drop has completed - g_signal_new ( "tree_move", - G_TYPE_FROM_CLASS(klass), - G_SIGNAL_RUN_FIRST, - 0, - nullptr, nullptr, - g_cclosure_marshal_VOID__UINT, - G_TYPE_NONE, 1, - G_TYPE_UINT); + g_signal_new("tree_move", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_FIRST, 0, nullptr, nullptr, + g_cclosure_marshal_VOID__UINT, G_TYPE_NONE, 1, G_TYPE_UINT); } -void -sp_xmlview_tree_init (SPXMLViewTree * tree) +void sp_xmlview_tree_init(SPXMLViewTree *tree) { - tree->repr = nullptr; - tree->blocked = 0; + tree->repr = nullptr; + tree->blocked = 0; } -void sp_xmlview_tree_destroy(GtkWidget * object) +void sp_xmlview_tree_destroy(GtkWidget *object) { - SPXMLViewTree * tree = SP_XMLVIEW_TREE (object); + SPXMLViewTree *tree = SP_XMLVIEW_TREE(object); - sp_xmlview_tree_set_repr (tree, nullptr); + sp_xmlview_tree_set_repr(tree, nullptr); - GTK_WIDGET_CLASS(sp_xmlview_tree_parent_class)->destroy (object); + GTK_WIDGET_CLASS(sp_xmlview_tree_parent_class)->destroy(object); } /* * Add a new row to the tree */ -void -add_node (SPXMLViewTree * tree, GtkTreeIter *parent, GtkTreeIter *before, Inkscape::XML::Node * repr) +void add_node(SPXMLViewTree *tree, GtkTreeIter *parent, GtkTreeIter *before, Inkscape::XML::Node *repr) { - const Inkscape::XML::NodeEventVector * vec; + const Inkscape::XML::NodeEventVector *vec; - g_assert (tree != nullptr); + g_assert(tree != nullptr); if (before && !gtk_tree_store_iter_is_valid(tree->store, before)) { before = nullptr; } - GtkTreeIter iter; - gtk_tree_store_insert_before (tree->store, &iter, parent, before); + GtkTreeIter iter; + gtk_tree_store_insert_before(tree->store, &iter, parent, before); if (!gtk_tree_store_iter_is_valid(tree->store, &iter)) { return; @@ -241,30 +242,30 @@ add_node (SPXMLViewTree * tree, GtkTreeIter *parent, GtkTreeIter *before, Inksca auto data = new NodeData(tree, &iter, repr); - g_assert (data != nullptr); + g_assert(data != nullptr); gtk_tree_store_set(tree->store, &iter, STORE_DATA_COL, data, -1); - if ( repr->type() == Inkscape::XML::TEXT_NODE ) { - vec = &text_repr_events; - } else if ( repr->type() == Inkscape::XML::COMMENT_NODE ) { - vec = &comment_repr_events; - } else if ( repr->type() == Inkscape::XML::PI_NODE ) { - vec = &pi_repr_events; - } else if ( repr->type() == Inkscape::XML::ELEMENT_NODE ) { - vec = &element_repr_events; - } else { - vec = nullptr; - } - - if (vec) { - /* cheat a little to get the text updated on nodes without id */ + if (repr->type() == Inkscape::XML::TEXT_NODE) { + vec = &text_repr_events; + } else if (repr->type() == Inkscape::XML::COMMENT_NODE) { + vec = &comment_repr_events; + } else if (repr->type() == Inkscape::XML::PI_NODE) { + vec = &pi_repr_events; + } else if (repr->type() == Inkscape::XML::ELEMENT_NODE) { + vec = &element_repr_events; + } else { + vec = nullptr; + } + + if (vec) { + /* cheat a little to get the text updated on nodes without id */ if (repr->type() == Inkscape::XML::ELEMENT_NODE && repr->attribute("id") == nullptr) { - element_attr_changed (repr, "id", nullptr, nullptr, false, data); - } - sp_repr_add_listener (repr, vec, data); - sp_repr_synthesize_events (repr, vec, data); - } + element_attr_changed(repr, "id", nullptr, nullptr, false, data); + } + sp_repr_add_listener(repr, vec, data); + sp_repr_synthesize_events(repr, vec, data); + } } static gboolean remove_all_listeners(GtkTreeModel *model, GtkTreePath *, GtkTreeIter *iter, gpointer) @@ -293,19 +294,21 @@ NodeData::~NodeData() gtk_tree_row_reference_free(rowref); } -void element_child_added (Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node * child, Inkscape::XML::Node * ref, gpointer ptr) +void element_child_added(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node *child, Inkscape::XML::Node *ref, + gpointer ptr) { NodeData *data = static_cast<NodeData *>(ptr); GtkTreeIter before; - if (data->tree->blocked) return; + if (data->tree->blocked) + return; - if (!ref_to_sibling (data, ref, &before)) { + if (!ref_to_sibling(data, ref, &before)) { return; } GtkTreeIter data_iter; - tree_ref_to_iter(data->tree, &data_iter, data->rowref); + tree_ref_to_iter(data->tree, &data_iter, data->rowref); if (!data->expanded) { auto model = GTK_TREE_MODEL(data->tree->store); @@ -319,50 +322,46 @@ void element_child_added (Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node * } } - add_node (data->tree, &data_iter, &before, child); + add_node(data->tree, &data_iter, &before, child); } -void element_attr_changed( - Inkscape::XML::Node* repr, gchar const* key, - gchar const* /*old_value*/, gchar const* /*new_value*/, bool /*is_interactive*/, - gpointer ptr) +void element_attr_changed(Inkscape::XML::Node *repr, gchar const *key, gchar const * /*old_value*/, + gchar const * /*new_value*/, bool /*is_interactive*/, gpointer ptr) { - if (0 != strcmp (key, "id") && 0 != strcmp (key, "inkscape:label")) + if (0 != strcmp(key, "id") && 0 != strcmp(key, "inkscape:label")) return; - element_attr_or_name_change_update(repr, static_cast<NodeData*>(ptr)); + element_attr_or_name_change_update(repr, static_cast<NodeData *>(ptr)); } -void element_name_changed( - Inkscape::XML::Node* repr, - gchar const* /*oldname*/, gchar const* /*newname*/, gpointer ptr) +void element_name_changed(Inkscape::XML::Node *repr, gchar const * /*oldname*/, gchar const * /*newname*/, gpointer ptr) { - element_attr_or_name_change_update(repr, static_cast<NodeData*>(ptr)); + element_attr_or_name_change_update(repr, static_cast<NodeData *>(ptr)); } -void element_attr_or_name_change_update(Inkscape::XML::Node* repr, NodeData* data) +void element_attr_or_name_change_update(Inkscape::XML::Node *repr, NodeData *data) { if (data->tree->blocked) { return; } - gchar const* node_name = repr->name(); - gchar const* id_value = repr->attribute("id"); - gchar const* label_value = repr->attribute("inkscape:label"); - gchar* display_text; + gchar const *node_name = repr->name(); + gchar const *id_value = repr->attribute("id"); + gchar const *label_value = repr->attribute("inkscape:label"); + gchar *display_text; if (id_value && label_value) { - display_text = g_strdup_printf ("<%s id=\"%s\" inkscape:label=\"%s\">", node_name, id_value, label_value); + display_text = g_strdup_printf("<%s id=\"%s\" inkscape:label=\"%s\">", node_name, id_value, label_value); } else if (id_value) { - display_text = g_strdup_printf ("<%s id=\"%s\">", node_name, id_value); + display_text = g_strdup_printf("<%s id=\"%s\">", node_name, id_value); } else if (label_value) { - display_text = g_strdup_printf ("<%s inkscape:label=\"%s\">", node_name, label_value); + display_text = g_strdup_printf("<%s inkscape:label=\"%s\">", node_name, label_value); } else { - display_text = g_strdup_printf ("<%s>", node_name); + display_text = g_strdup_printf("<%s>", node_name); } GtkTreeIter iter; - if (tree_ref_to_iter(data->tree, &iter, data->rowref)) { - gtk_tree_store_set (GTK_TREE_STORE(data->tree->store), &iter, STORE_TEXT_COL, display_text, -1); + if (tree_ref_to_iter(data->tree, &iter, data->rowref)) { + gtk_tree_store_set(GTK_TREE_STORE(data->tree->store), &iter, STORE_TEXT_COL, display_text, -1); } g_free(display_text); @@ -373,7 +372,8 @@ void element_child_removed(Inkscape::XML::Node *repr, Inkscape::XML::Node *child { NodeData *data = static_cast<NodeData *>(ptr); - if (data->tree->blocked) return; + if (data->tree->blocked) + return; GtkTreeIter iter; if (repr_to_child(data, child, &iter)) { @@ -392,21 +392,23 @@ void element_child_removed(Inkscape::XML::Node *repr, Inkscape::XML::Node *child #endif } -void element_order_changed(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node * child, Inkscape::XML::Node * /*oldref*/, Inkscape::XML::Node * newref, gpointer ptr) +void element_order_changed(Inkscape::XML::Node * /*repr*/, Inkscape::XML::Node *child, Inkscape::XML::Node * /*oldref*/, + Inkscape::XML::Node *newref, gpointer ptr) { NodeData *data = static_cast<NodeData *>(ptr); GtkTreeIter before, node; - if (data->tree->blocked) return; + if (data->tree->blocked) + return; - ref_to_sibling (data, newref, &before); - repr_to_child (data, child, &node); + ref_to_sibling(data, newref, &before); + repr_to_child(data, child, &node); if (gtk_tree_store_iter_is_valid(data->tree->store, &before)) { - gtk_tree_store_move_before (data->tree->store, &node, &before); + gtk_tree_store_move_before(data->tree->store, &node, &before); } else { - repr_to_child (data, newref, &before); - gtk_tree_store_move_after (data->tree->store, &node, &before); + repr_to_child(data, newref, &before); + gtk_tree_store_move_after(data->tree->store, &node, &before); } } @@ -440,47 +442,53 @@ static void sp_remove_newlines_and_tabs(std::string &val, size_t const maxlen = } } -void text_content_changed(Inkscape::XML::Node * /*repr*/, const gchar * /*old_content*/, const gchar * new_content, gpointer ptr) +void text_content_changed(Inkscape::XML::Node * /*repr*/, const gchar * /*old_content*/, const gchar *new_content, + gpointer ptr) { NodeData *data = static_cast<NodeData *>(ptr); - if (data->tree->blocked) return; + if (data->tree->blocked) + return; auto nolinecontent = std::string("\"").append(new_content).append("\""); sp_remove_newlines_and_tabs(nolinecontent); GtkTreeIter iter; - if (tree_ref_to_iter(data->tree, &iter, data->rowref)) { + if (tree_ref_to_iter(data->tree, &iter, data->rowref)) { gtk_tree_store_set(GTK_TREE_STORE(data->tree->store), &iter, STORE_TEXT_COL, nolinecontent.c_str(), -1); } } -void comment_content_changed(Inkscape::XML::Node * /*repr*/, const gchar * /*old_content*/, const gchar *new_content, gpointer ptr) +void comment_content_changed(Inkscape::XML::Node * /*repr*/, const gchar * /*old_content*/, const gchar *new_content, + gpointer ptr) { - NodeData *data = static_cast<NodeData*>(ptr); + NodeData *data = static_cast<NodeData *>(ptr); - if (data->tree->blocked) return; + if (data->tree->blocked) + return; auto nolinecontent = std::string("<!--").append(new_content).append("-->"); sp_remove_newlines_and_tabs(nolinecontent); GtkTreeIter iter; - if (tree_ref_to_iter(data->tree, &iter, data->rowref)) { + if (tree_ref_to_iter(data->tree, &iter, data->rowref)) { gtk_tree_store_set(GTK_TREE_STORE(data->tree->store), &iter, STORE_TEXT_COL, nolinecontent.c_str(), -1); } } -void pi_content_changed(Inkscape::XML::Node *repr, const gchar * /*old_content*/, const gchar *new_content, gpointer ptr) +void pi_content_changed(Inkscape::XML::Node *repr, const gchar * /*old_content*/, const gchar *new_content, + gpointer ptr) { NodeData *data = static_cast<NodeData *>(ptr); - if (data->tree->blocked) return; + if (data->tree->blocked) + return; auto nolinecontent = std::string("<?").append(repr->name()).append(" ").append(new_content).append("?>"); sp_remove_newlines_and_tabs(nolinecontent); GtkTreeIter iter; - if (tree_ref_to_iter(data->tree, &iter, data->rowref)) { + if (tree_ref_to_iter(data->tree, &iter, data->rowref)) { gtk_tree_store_set(GTK_TREE_STORE(data->tree->store), &iter, STORE_TEXT_COL, nolinecontent.c_str(), -1); } } @@ -566,7 +574,7 @@ void on_row_changed(GtkTreeModel *tree_model, GtkTreePath *path, GtkTreeIter *it GtkTreeIter new_parent; if (!gtk_tree_model_iter_parent(tree_model, &new_parent, iter)) { - //No parent of drop location + // No parent of drop location return; } @@ -611,27 +619,27 @@ void on_row_changed(GtkTreeModel *tree_model, GtkTreePath *path, GtkTreeIter *it /* * Set iter to ref or node data's child with the same repr or first child */ -gboolean ref_to_sibling (NodeData *data, Inkscape::XML::Node *repr, GtkTreeIter *iter) +gboolean ref_to_sibling(NodeData *data, Inkscape::XML::Node *repr, GtkTreeIter *iter) { - if (repr) { - if (!repr_to_child (data, repr, iter)) { + if (repr) { + if (!repr_to_child(data, repr, iter)) { return false; } - gtk_tree_model_iter_next (GTK_TREE_MODEL(data->tree->store), iter); - } else { - GtkTreeIter data_iter; - if (!tree_ref_to_iter(data->tree, &data_iter, data->rowref)) { - return false; - } - gtk_tree_model_iter_children(GTK_TREE_MODEL(data->tree->store), iter, &data_iter); - } - return true; + gtk_tree_model_iter_next(GTK_TREE_MODEL(data->tree->store), iter); + } else { + GtkTreeIter data_iter; + if (!tree_ref_to_iter(data->tree, &data_iter, data->rowref)) { + return false; + } + gtk_tree_model_iter_children(GTK_TREE_MODEL(data->tree->store), iter, &data_iter); + } + return true; } /* * Set iter to the node data's child with the same repr */ -gboolean repr_to_child (NodeData *data, Inkscape::XML::Node * repr, GtkTreeIter *iter) +gboolean repr_to_child(NodeData *data, Inkscape::XML::Node *repr, GtkTreeIter *iter) { GtkTreeIter data_iter; GtkTreeModel *model = GTK_TREE_MODEL(data->tree->store); @@ -644,19 +652,19 @@ gboolean repr_to_child (NodeData *data, Inkscape::XML::Node * repr, GtkTreeIter /* * The node we are looking for is likely to be the last one, so check it first. */ - gint n_children = gtk_tree_model_iter_n_children (model, &data_iter); + gint n_children = gtk_tree_model_iter_n_children(model, &data_iter); if (n_children > 1) { - valid = gtk_tree_model_iter_nth_child (model, iter, &data_iter, n_children-1); - if (valid && sp_xmlview_tree_node_get_repr (model, iter) == repr) { - //g_message("repr_to_child hit %d", n_children); + valid = gtk_tree_model_iter_nth_child(model, iter, &data_iter, n_children - 1); + if (valid && sp_xmlview_tree_node_get_repr(model, iter) == repr) { + // g_message("repr_to_child hit %d", n_children); return valid; } } valid = gtk_tree_model_iter_children(model, iter, &data_iter); - while (valid && sp_xmlview_tree_node_get_repr (model, iter) != repr) { + while (valid && sp_xmlview_tree_node_get_repr(model, iter) != repr) { valid = gtk_tree_model_iter_next(model, iter); - } + } return valid; } @@ -664,10 +672,10 @@ gboolean repr_to_child (NodeData *data, Inkscape::XML::Node * repr, GtkTreeIter /* * Get a matching GtkTreeRowReference for a GtkTreeIter */ -GtkTreeRowReference *tree_iter_to_ref (SPXMLViewTree * tree, GtkTreeIter* iter) +GtkTreeRowReference *tree_iter_to_ref(SPXMLViewTree *tree, GtkTreeIter *iter) { - GtkTreePath* path = gtk_tree_model_get_path(GTK_TREE_MODEL(tree->store), iter); - GtkTreeRowReference *ref = gtk_tree_row_reference_new(GTK_TREE_MODEL(tree->store), path); + GtkTreePath *path = gtk_tree_model_get_path(GTK_TREE_MODEL(tree->store), iter); + GtkTreeRowReference *ref = gtk_tree_row_reference_new(GTK_TREE_MODEL(tree->store), path); gtk_tree_path_free(path); return ref; @@ -676,9 +684,9 @@ GtkTreeRowReference *tree_iter_to_ref (SPXMLViewTree * tree, GtkTreeIter* iter) /* * Get a matching GtkTreeIter for a GtkTreeRowReference */ -gboolean tree_ref_to_iter (SPXMLViewTree * tree, GtkTreeIter* iter, GtkTreeRowReference *ref) +gboolean tree_ref_to_iter(SPXMLViewTree *tree, GtkTreeIter *iter, GtkTreeRowReference *ref) { - GtkTreePath* path = gtk_tree_row_reference_get_path(ref); + GtkTreePath *path = gtk_tree_row_reference_get_path(ref); if (!path) { return false; } @@ -696,7 +704,7 @@ gboolean do_drag_motion(GtkWidget *widget, GdkDragContext *context, gint x, gint { GtkTreePath *path = nullptr; GtkTreeViewDropPosition pos; - gtk_tree_view_get_dest_row_at_pos (GTK_TREE_VIEW(widget), x, y, &path, &pos); + gtk_tree_view_get_dest_row_at_pos(GTK_TREE_VIEW(widget), x, y, &path, &pos); int action = 0; @@ -752,7 +760,7 @@ finally: } gtk_tree_path_free(path); - gdk_drag_status (context, (GdkDragAction)action, time); + gdk_drag_status(context, (GdkDragAction)action, time); return (action == 0); } @@ -760,10 +768,10 @@ finally: /* * Set the tree selection and scroll to the row with the given repr */ -void -sp_xmlview_tree_set_repr (SPXMLViewTree * tree, Inkscape::XML::Node * repr) +void sp_xmlview_tree_set_repr(SPXMLViewTree *tree, Inkscape::XML::Node *repr) { - if ( tree->repr == repr ) return; + if (tree->repr == repr) + return; if (tree->store) { gtk_tree_view_set_model(GTK_TREE_VIEW(tree), nullptr); @@ -783,12 +791,12 @@ sp_xmlview_tree_set_repr (SPXMLViewTree * tree, Inkscape::XML::Node * repr) add_node(tree, nullptr, nullptr, repr); // Set the tree model here, after all data is inserted - gtk_tree_view_set_model (GTK_TREE_VIEW(tree), GTK_TREE_MODEL(tree->store)); + gtk_tree_view_set_model(GTK_TREE_VIEW(tree), GTK_TREE_MODEL(tree->store)); g_signal_connect(G_OBJECT(tree->store), "row-changed", G_CALLBACK(on_row_changed), tree); GtkTreePath *path = gtk_tree_path_new_from_indices(0, -1); - gtk_tree_view_expand_to_path (GTK_TREE_VIEW(tree), path); - gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW(tree), path, nullptr, true, 0.5, 0.0); + gtk_tree_view_expand_to_path(GTK_TREE_VIEW(tree), path); + gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(tree), path, nullptr, true, 0.5, 0.0); gtk_tree_path_free(path); } } @@ -806,14 +814,14 @@ NodeData *sp_xmlview_tree_node_get_data(GtkTreeModel *model, GtkTreeIter *iter) /* * Return the repr at a given GtkTreeIter position */ -Inkscape::XML::Node * -sp_xmlview_tree_node_get_repr (GtkTreeModel *model, GtkTreeIter * iter) +Inkscape::XML::Node *sp_xmlview_tree_node_get_repr(GtkTreeModel *model, GtkTreeIter *iter) { NodeData *data = sp_xmlview_tree_node_get_data(model, iter); return data ? data->repr : nullptr; } -struct IterByReprData { +struct IterByReprData +{ const Inkscape::XML::Node *repr; //< in GtkTreeIter *iter; //< out }; @@ -822,11 +830,10 @@ struct IterByReprData { * Find a GtkTreeIter position in the tree by repr * @return True if the node was found */ -gboolean -sp_xmlview_tree_get_repr_node (SPXMLViewTree * tree, Inkscape::XML::Node * repr, GtkTreeIter *iter) +gboolean sp_xmlview_tree_get_repr_node(SPXMLViewTree *tree, Inkscape::XML::Node *repr, GtkTreeIter *iter) { iter->stamp = 0; // invalidate iterator - IterByReprData funcdata = { repr, iter }; + IterByReprData funcdata = {repr, iter}; gtk_tree_model_foreach(GTK_TREE_MODEL(tree->store), foreach_func, &funcdata); return iter->stamp != 0; } @@ -846,7 +853,8 @@ gboolean foreach_func(GtkTreeModel *model, GtkTreePath * /*path*/, GtkTreeIter * * Callback function for string searches in the tree * Return a match on any substring */ -gboolean search_equal_func(GtkTreeModel *model, gint /*column*/, const gchar *key, GtkTreeIter *iter, gpointer /*search_data*/) +gboolean search_equal_func(GtkTreeModel *model, gint /*column*/, const gchar *key, GtkTreeIter *iter, + gpointer /*search_data*/) { gchar *text = nullptr; gtk_tree_model_get(model, iter, STORE_TEXT_COL, &text, -1); diff --git a/src/widgets/sp-xmlview-tree.h b/src/widgets/sp-xmlview-tree.h index 36ea43f1c57c76e43577f4ec1f7d400143bf6a6e..36173fa049b63049f815dad3917eb2edf0019277 100644 --- a/src/widgets/sp-xmlview-tree.h +++ b/src/widgets/sp-xmlview-tree.h @@ -11,8 +11,8 @@ #ifndef SEEN_SP_XMLVIEW_TREE_H #define SEEN_SP_XMLVIEW_TREE_H -#include <gtk/gtk.h> #include <glib.h> +#include <gtk/gtk.h> namespace Inkscape::XML { class Node; @@ -22,37 +22,36 @@ class Node; * Specialization of GtkTreeView for the XML editor */ -#define SP_TYPE_XMLVIEW_TREE (sp_xmlview_tree_get_type ()) -#define SP_XMLVIEW_TREE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), SP_TYPE_XMLVIEW_TREE, SPXMLViewTree)) -#define SP_IS_XMLVIEW_TREE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), SP_TYPE_XMLVIEW_TREE)) -#define SP_XMLVIEW_TREE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), SP_TYPE_XMLVIEW_TREE)) +#define SP_TYPE_XMLVIEW_TREE (sp_xmlview_tree_get_type()) +#define SP_XMLVIEW_TREE(o) (G_TYPE_CHECK_INSTANCE_CAST((o), SP_TYPE_XMLVIEW_TREE, SPXMLViewTree)) +#define SP_IS_XMLVIEW_TREE(o) (G_TYPE_CHECK_INSTANCE_TYPE((o), SP_TYPE_XMLVIEW_TREE)) +#define SP_XMLVIEW_TREE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE((k), SP_TYPE_XMLVIEW_TREE)) struct SPXMLViewTree; struct SPXMLViewTreeClass; struct SPXMLViewTree { - GtkTreeView tree; - GtkTreeStore *store; - Inkscape::XML::Node * repr; - gint blocked; + GtkTreeView tree; + GtkTreeStore *store; + Inkscape::XML::Node *repr; + gint blocked; }; struct SPXMLViewTreeClass { - GtkTreeViewClass parent_class; + GtkTreeViewClass parent_class; }; -GType sp_xmlview_tree_get_type (); -GtkWidget * sp_xmlview_tree_new (Inkscape::XML::Node * repr, void * factory, void * data); - -#define SP_XMLVIEW_TREE_REPR(tree) (SP_XMLVIEW_TREE (tree)->repr) +GType sp_xmlview_tree_get_type(); +GtkWidget *sp_xmlview_tree_new(Inkscape::XML::Node *repr, void *factory, void *data); -void sp_xmlview_tree_set_repr (SPXMLViewTree * tree, Inkscape::XML::Node * repr); +#define SP_XMLVIEW_TREE_REPR(tree) (SP_XMLVIEW_TREE(tree)->repr) -Inkscape::XML::Node * sp_xmlview_tree_node_get_repr (GtkTreeModel *model, GtkTreeIter * node); -gboolean sp_xmlview_tree_get_repr_node (SPXMLViewTree * tree, Inkscape::XML::Node * repr, GtkTreeIter *node); +void sp_xmlview_tree_set_repr(SPXMLViewTree *tree, Inkscape::XML::Node *repr); +Inkscape::XML::Node *sp_xmlview_tree_node_get_repr(GtkTreeModel *model, GtkTreeIter *node); +gboolean sp_xmlview_tree_get_repr_node(SPXMLViewTree *tree, Inkscape::XML::Node *repr, GtkTreeIter *node); #endif // !SEEN_SP_XMLVIEW_TREE_H diff --git a/src/widgets/spw-utilities.cpp b/src/widgets/spw-utilities.cpp index 38759ef26e5aa6f050ed034df0e833d2b1854f63..51cb800241117e5f6384de76f1f465f8786aafee 100644 --- a/src/widgets/spw-utilities.cpp +++ b/src/widgets/spw-utilities.cpp @@ -11,59 +11,58 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> -#include <string> +#include "spw-utilities.h" +#include <cstring> #include <gtkmm/box.h> -#include <gtkmm/label.h> #include <gtkmm/grid.h> +#include <gtkmm/label.h> +#include <string> #include "selection.h" -#include "spw-utilities.h" - /** * Creates a label widget with the given text, at the given col, row * position in the table. */ -Gtk::Label * spw_label(Gtk::Grid *table, const gchar *label_text, int col, int row, Gtk::Widget* target) +Gtk::Label *spw_label(Gtk::Grid *table, const gchar *label_text, int col, int row, Gtk::Widget *target) { - Gtk::Label *label_widget = new Gtk::Label(); - g_assert(label_widget != nullptr); - if (target != nullptr) { - label_widget->set_text_with_mnemonic(label_text); - label_widget->set_mnemonic_widget(*target); - } else { - label_widget->set_text(label_text); - } - label_widget->show(); - - label_widget->set_halign(Gtk::ALIGN_START); - label_widget->set_valign(Gtk::ALIGN_CENTER); - label_widget->set_margin_start(4); - label_widget->set_margin_end(4); - - table->attach(*label_widget, col, row, 1, 1); - - return label_widget; + Gtk::Label *label_widget = new Gtk::Label(); + g_assert(label_widget != nullptr); + if (target != nullptr) { + label_widget->set_text_with_mnemonic(label_text); + label_widget->set_mnemonic_widget(*target); + } else { + label_widget->set_text(label_text); + } + label_widget->show(); + + label_widget->set_halign(Gtk::ALIGN_START); + label_widget->set_valign(Gtk::ALIGN_CENTER); + label_widget->set_margin_start(4); + label_widget->set_margin_end(4); + + table->attach(*label_widget, col, row, 1, 1); + + return label_widget; } /** * Creates a horizontal layout manager with 4-pixel spacing between children * and space for 'width' columns. */ -Gtk::HBox * spw_hbox(Gtk::Grid * table, int width, int col, int row) +Gtk::HBox *spw_hbox(Gtk::Grid *table, int width, int col, int row) { - /* Create a new hbox with a 4-pixel spacing between children */ - Gtk::HBox *hb = new Gtk::HBox(false, 4); - g_assert(hb != nullptr); - hb->show(); - hb->set_hexpand(); - hb->set_halign(Gtk::ALIGN_FILL); - hb->set_valign(Gtk::ALIGN_CENTER); - table->attach(*hb, col, row, width, 1); - - return hb; + /* Create a new hbox with a 4-pixel spacing between children */ + Gtk::HBox *hb = new Gtk::HBox(false, 4); + g_assert(hb != nullptr); + hb->show(); + hb->set_hexpand(); + hb->set_halign(Gtk::ALIGN_FILL); + hb->set_valign(Gtk::ALIGN_CENTER); + table->attach(*hb, col, row, width, 1); + + return hb; } /** @@ -74,15 +73,17 @@ gpointer sp_search_by_data_recursive(GtkWidget *w, gpointer key) gpointer r = nullptr; if (w && G_IS_OBJECT(w)) { - r = g_object_get_data(G_OBJECT(w), (gchar *) key); + r = g_object_get_data(G_OBJECT(w), (gchar *)key); } - if (r) return r; + if (r) + return r; if (GTK_IS_CONTAINER(w)) { - std::vector<Gtk::Widget*> children = Glib::wrap(GTK_CONTAINER(w))->get_children(); - for (auto i:children) { + std::vector<Gtk::Widget *> children = Glib::wrap(GTK_CONTAINER(w))->get_children(); + for (auto i : children) { r = sp_search_by_data_recursive(GTK_WIDGET(i->gobj()), key); - if (r) return r; + if (r) + return r; } } @@ -97,20 +98,17 @@ gpointer sp_search_by_data_recursive(GtkWidget *w, gpointer key) * * \return The specified child widget, or nullptr if it cannot be found */ -Gtk::Widget * -sp_search_by_name_recursive(Gtk::Widget *parent, const Glib::ustring& name) +Gtk::Widget *sp_search_by_name_recursive(Gtk::Widget *parent, const Glib::ustring &name) { auto parent_bin = dynamic_cast<Gtk::Bin *>(parent); auto parent_container = dynamic_cast<Gtk::Container *>(parent); if (parent && parent->get_name() == name) { return parent; - } - else if (parent_bin) { + } else if (parent_bin) { auto child = parent_bin->get_child(); return sp_search_by_name_recursive(child, name); - } - else if (parent_container) { + } else if (parent_container) { auto children = parent_container->get_children(); for (auto child : children) { @@ -133,15 +131,17 @@ GtkWidget *sp_search_by_value_recursive(GtkWidget *w, gchar *key, gchar *value) gchar *r = nullptr; if (w && G_IS_OBJECT(w)) { - r = (gchar *) g_object_get_data(G_OBJECT(w), key); + r = (gchar *)g_object_get_data(G_OBJECT(w), key); } - if (r && !strcmp (r, value)) return w; + if (r && !strcmp(r, value)) + return w; if (GTK_IS_CONTAINER(w)) { - std::vector<Gtk::Widget*> children = Glib::wrap(GTK_CONTAINER(w))->get_children(); - for (auto i:children) { + std::vector<Gtk::Widget *> children = Glib::wrap(GTK_CONTAINER(w))->get_children(); + for (auto i : children) { GtkWidget *child = sp_search_by_value_recursive(GTK_WIDGET(i->gobj()), key, value); - if (child) return child; + if (child) + return child; } } diff --git a/src/widgets/spw-utilities.h b/src/widgets/spw-utilities.h index eae547772dc987daa60da3fcda10190727e46eae..ea5ad8a3c0b13dff92a5292ae801a90bf0d1bae3 100644 --- a/src/widgets/spw-utilities.h +++ b/src/widgets/spw-utilities.h @@ -24,20 +24,19 @@ #include <gtk/gtk.h> namespace Gtk { - class Label; - class Grid; - class HBox; - class Widget; -} +class Label; +class Grid; +class HBox; +class Widget; +} // namespace Gtk -Gtk::Label * spw_label(Gtk::Grid *table, gchar const *label_text, int col, int row, Gtk::Widget *target); -Gtk::HBox * spw_hbox(Gtk::Grid *table, int width, int col, int row); +Gtk::Label *spw_label(Gtk::Grid *table, gchar const *label_text, int col, int row, Gtk::Widget *target); +Gtk::HBox *spw_hbox(Gtk::Grid *table, int width, int col, int row); gpointer sp_search_by_data_recursive(GtkWidget *w, gpointer data); GtkWidget *sp_search_by_value_recursive(GtkWidget *w, gchar *key, gchar *value); -Gtk::Widget * sp_search_by_name_recursive(Gtk::Widget *parent, - const Glib::ustring& name); +Gtk::Widget *sp_search_by_name_recursive(Gtk::Widget *parent, const Glib::ustring &name); #endif /* diff --git a/src/widgets/style-utils.h b/src/widgets/style-utils.h index 1557218d7fe07a159f9cf841cd396bb005925ba1..c5dfe6e339e5b4c0471b2b5238feab3c0074b20d 100644 --- a/src/widgets/style-utils.h +++ b/src/widgets/style-utils.h @@ -16,9 +16,10 @@ #include "desktop-style.h" namespace Inkscape { - inline bool is_query_style_updateable(const int style) { - return (style == QUERY_STYLE_MULTIPLE_DIFFERENT || style == QUERY_STYLE_NOTHING); - } +inline bool is_query_style_updateable(const int style) +{ + return (style == QUERY_STYLE_MULTIPLE_DIFFERENT || style == QUERY_STYLE_NOTHING); +} } // namespace Inkscape #endif // SEEN_DIALOGS_STYLE_UTILS_H diff --git a/src/widgets/toolbox.cpp b/src/widgets/toolbox.cpp index eeb5b3f169ee79c47b123dfcf52819606d60ae2f..2bb45c9f17b70502d6669dd95f27ec69c3d93fb7 100644 --- a/src/widgets/toolbox.cpp +++ b/src/widgets/toolbox.cpp @@ -28,43 +28,25 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <gtkmm/box.h> +#include "toolbox.h" + +#include <glibmm/i18n.h> #include <gtkmm/action.h> #include <gtkmm/actiongroup.h> +#include <gtkmm/box.h> #include <gtkmm/toolitem.h> -#include <glibmm/i18n.h> #include "desktop-style.h" #include "desktop.h" #include "document-undo.h" -#include "inkscape.h" -#include "verbs.h" - -#include "ink-action.h" - #include "helper/action.h" #include "helper/verb-action.h" - #include "include/gtkmm_version.h" - +#include "ink-action.h" +#include "inkscape.h" #include "io/resource.h" - #include "object/sp-namedview.h" - #include "ui/icon-names.h" -#include "ui/tools-switch.h" -#include "ui/uxmanager.h" -#include "ui/widget/button.h" -#include "ui/widget/spinbutton.h" -#include "ui/widget/style-swatch.h" -#include "ui/widget/unit-tracker.h" - -#include "widgets/spw-utilities.h" -#include "widgets/widget-sizes.h" - -#include "xml/attribute-record.h" -#include "xml/node-event-vector.h" - #include "ui/toolbar/arc-toolbar.h" #include "ui/toolbar/box3d-toolbar.h" #include "ui/toolbar/calligraphy-toolbar.h" @@ -73,30 +55,38 @@ #include "ui/toolbar/eraser-toolbar.h" #include "ui/toolbar/gradient-toolbar.h" #include "ui/toolbar/lpe-toolbar.h" -#include "ui/toolbar/mesh-toolbar.h" #include "ui/toolbar/measure-toolbar.h" +#include "ui/toolbar/mesh-toolbar.h" #include "ui/toolbar/node-toolbar.h" -#include "ui/toolbar/rect-toolbar.h" #include "ui/toolbar/paintbucket-toolbar.h" #include "ui/toolbar/pencil-toolbar.h" +#include "ui/toolbar/rect-toolbar.h" #include "ui/toolbar/select-toolbar.h" #include "ui/toolbar/snap-toolbar.h" -#include "ui/toolbar/spray-toolbar.h" #include "ui/toolbar/spiral-toolbar.h" +#include "ui/toolbar/spray-toolbar.h" #include "ui/toolbar/star-toolbar.h" -#include "ui/toolbar/tweak-toolbar.h" #include "ui/toolbar/text-toolbar.h" +#include "ui/toolbar/tweak-toolbar.h" #include "ui/toolbar/zoom-toolbar.h" - -#include "toolbox.h" - +#include "ui/tools-switch.h" #include "ui/tools/tool-base.h" +#include "ui/uxmanager.h" +#include "ui/widget/button.h" +#include "ui/widget/spinbutton.h" +#include "ui/widget/style-swatch.h" +#include "ui/widget/unit-tracker.h" +#include "verbs.h" +#include "widgets/spw-utilities.h" +#include "widgets/widget-sizes.h" +#include "xml/attribute-record.h" +#include "xml/node-event-vector.h" //#define DEBUG_TEXT -using Inkscape::UI::UXManager; using Inkscape::DocumentUndo; using Inkscape::UI::ToolboxFactory; +using Inkscape::UI::UXManager; using Inkscape::UI::Tools::ToolBase; using Inkscape::IO::Resource::get_filename; @@ -105,7 +95,8 @@ using Inkscape::IO::Resource::UIS; typedef void (*SetupFunction)(GtkWidget *toolbox, SPDesktop *desktop); typedef void (*UpdateFunction)(SPDesktop *desktop, ToolBase *eventcontext, GtkWidget *toolbox); -enum BarId { +enum BarId +{ BAR_TOOL = 0, BAR_AUX, BAR_COMMANDS, @@ -115,28 +106,26 @@ enum BarId { #define BAR_ID_KEY "BarIdValue" #define HANDLE_POS_MARK "x-inkscape-pos" -GtkIconSize ToolboxFactory::prefToSize( Glib::ustring const &path, int base ) { - static GtkIconSize sizeChoices[] = { - GTK_ICON_SIZE_LARGE_TOOLBAR, - GTK_ICON_SIZE_SMALL_TOOLBAR, - GTK_ICON_SIZE_DND, - GTK_ICON_SIZE_DIALOG - }; +GtkIconSize ToolboxFactory::prefToSize(Glib::ustring const &path, int base) +{ + static GtkIconSize sizeChoices[] = {GTK_ICON_SIZE_LARGE_TOOLBAR, GTK_ICON_SIZE_SMALL_TOOLBAR, GTK_ICON_SIZE_DND, + GTK_ICON_SIZE_DIALOG}; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - int index = prefs->getIntLimited( path, base, 0, G_N_ELEMENTS(sizeChoices) ); + int index = prefs->getIntLimited(path, base, 0, G_N_ELEMENTS(sizeChoices)); return sizeChoices[index]; } Gtk::IconSize ToolboxFactory::prefToSize_mm(Glib::ustring const &path, int base) { - static Gtk::IconSize sizeChoices[] = { Gtk::ICON_SIZE_LARGE_TOOLBAR, Gtk::ICON_SIZE_SMALL_TOOLBAR, - Gtk::ICON_SIZE_DND, Gtk::ICON_SIZE_DIALOG }; + static Gtk::IconSize sizeChoices[] = {Gtk::ICON_SIZE_LARGE_TOOLBAR, Gtk::ICON_SIZE_SMALL_TOOLBAR, + Gtk::ICON_SIZE_DND, Gtk::ICON_SIZE_DIALOG}; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int index = prefs->getIntLimited(path, base, 0, G_N_ELEMENTS(sizeChoices)); return sizeChoices[index]; } -static struct { +static struct +{ gchar const *type_name; gchar const *data_name; sp_verb_t verb; @@ -169,7 +158,8 @@ static struct { // clang-format on }; -static struct { +static struct +{ gchar const *type_name; gchar const *data_name; GtkWidget *(*create_func)(SPDesktop *desktop); @@ -230,8 +220,7 @@ static struct { // clang-format on }; - -static Glib::RefPtr<Gtk::ActionGroup> create_or_fetch_actions( SPDesktop* desktop ); +static Glib::RefPtr<Gtk::ActionGroup> create_or_fetch_actions(SPDesktop *desktop); static void setup_snap_toolbox(GtkWidget *toolbox, SPDesktop *desktop); @@ -244,129 +233,96 @@ static void update_aux_toolbox(SPDesktop *desktop, ToolBase *eventcontext, GtkWi static void setup_commands_toolbox(GtkWidget *toolbox, SPDesktop *desktop); static void update_commands_toolbox(SPDesktop *desktop, ToolBase *eventcontext, GtkWidget *toolbox); -static void trigger_sp_action( GtkAction* /*act*/, gpointer user_data ) +static void trigger_sp_action(GtkAction * /*act*/, gpointer user_data) { - SPAction* targetAction = SP_ACTION(user_data); - if ( targetAction ) { - sp_action_perform( targetAction, nullptr ); + SPAction *targetAction = SP_ACTION(user_data); + if (targetAction) { + sp_action_perform(targetAction, nullptr); } } -static GtkAction* create_action_for_verb( Inkscape::Verb* verb, Inkscape::UI::View::View* view, GtkIconSize size ) +static GtkAction *create_action_for_verb(Inkscape::Verb *verb, Inkscape::UI::View::View *view, GtkIconSize size) { - GtkAction* act = nullptr; + GtkAction *act = nullptr; - SPAction* targetAction = verb->get_action(Inkscape::ActionContext(view)); - InkAction* inky = ink_action_new( verb->get_id(), _(verb->get_name()), verb->get_tip(), verb->get_image(), size ); + SPAction *targetAction = verb->get_action(Inkscape::ActionContext(view)); + InkAction *inky = ink_action_new(verb->get_id(), _(verb->get_name()), verb->get_tip(), verb->get_image(), size); act = GTK_ACTION(inky); - gtk_action_set_sensitive( act, targetAction->sensitive ); + gtk_action_set_sensitive(act, targetAction->sensitive); - g_signal_connect( G_OBJECT(inky), "activate", G_CALLBACK(trigger_sp_action), targetAction ); + g_signal_connect(G_OBJECT(inky), "activate", G_CALLBACK(trigger_sp_action), targetAction); // FIXME: memory leak: this is not unrefed anywhere g_object_ref(G_OBJECT(targetAction)); - g_object_set_data_full(G_OBJECT(inky), "SPAction", (void*) targetAction, (GDestroyNotify) &g_object_unref); + g_object_set_data_full(G_OBJECT(inky), "SPAction", (void *)targetAction, (GDestroyNotify)&g_object_unref); targetAction->signal_set_sensitive.connect( - sigc::bind<0>( - sigc::ptr_fun(>k_action_set_sensitive), - GTK_ACTION(inky))); + sigc::bind<0>(sigc::ptr_fun(>k_action_set_sensitive), GTK_ACTION(inky))); return act; } -static std::map<SPDesktop*, Glib::RefPtr<Gtk::ActionGroup> > groups; +static std::map<SPDesktop *, Glib::RefPtr<Gtk::ActionGroup>> groups; static void desktopDestructHandler(SPDesktop *desktop) { - std::map<SPDesktop*, Glib::RefPtr<Gtk::ActionGroup> >::iterator it = groups.find(desktop); - if (it != groups.end()) - { + std::map<SPDesktop *, Glib::RefPtr<Gtk::ActionGroup>>::iterator it = groups.find(desktop); + if (it != groups.end()) { groups.erase(it); } } -static Glib::RefPtr<Gtk::ActionGroup> create_or_fetch_actions( SPDesktop* desktop ) +static Glib::RefPtr<Gtk::ActionGroup> create_or_fetch_actions(SPDesktop *desktop) { Inkscape::UI::View::View *view = desktop; gint verbsToUse[] = { // disabled until we have icons for them: - //find - //SP_VERB_EDIT_TILE, - //SP_VERB_EDIT_UNTILE, - SP_VERB_DIALOG_ALIGN_DISTRIBUTE, - SP_VERB_DIALOG_DISPLAY, - SP_VERB_DIALOG_FILL_STROKE, - SP_VERB_DIALOG_NAMEDVIEW, - SP_VERB_DIALOG_TEXT, - SP_VERB_DIALOG_XML_EDITOR, - SP_VERB_DIALOG_SELECTORS, - SP_VERB_DIALOG_LAYERS, - SP_VERB_EDIT_CLONE, - SP_VERB_EDIT_COPY, - SP_VERB_EDIT_CUT, - SP_VERB_EDIT_DUPLICATE, - SP_VERB_EDIT_PASTE, - SP_VERB_EDIT_REDO, - SP_VERB_EDIT_UNDO, - SP_VERB_EDIT_UNLINK_CLONE, - //SP_VERB_FILE_EXPORT, - SP_VERB_DIALOG_EXPORT, - SP_VERB_FILE_IMPORT, - SP_VERB_FILE_NEW, - SP_VERB_FILE_OPEN, - SP_VERB_FILE_PRINT, - SP_VERB_FILE_SAVE, - SP_VERB_OBJECT_TO_CURVE, - SP_VERB_SELECTION_GROUP, - SP_VERB_SELECTION_OUTLINE, - SP_VERB_SELECTION_UNGROUP, - SP_VERB_ZOOM_1_1, - SP_VERB_ZOOM_1_2, - SP_VERB_ZOOM_2_1, - SP_VERB_ZOOM_DRAWING, - SP_VERB_ZOOM_IN, - SP_VERB_ZOOM_NEXT, - SP_VERB_ZOOM_OUT, - SP_VERB_ZOOM_PAGE, - SP_VERB_ZOOM_PAGE_WIDTH, - SP_VERB_ZOOM_PREV, - SP_VERB_ZOOM_SELECTION, - SP_VERB_ZOOM_CENTER_PAGE - }; + // find + // SP_VERB_EDIT_TILE, + // SP_VERB_EDIT_UNTILE, + SP_VERB_DIALOG_ALIGN_DISTRIBUTE, SP_VERB_DIALOG_DISPLAY, SP_VERB_DIALOG_FILL_STROKE, SP_VERB_DIALOG_NAMEDVIEW, + SP_VERB_DIALOG_TEXT, SP_VERB_DIALOG_XML_EDITOR, SP_VERB_DIALOG_SELECTORS, SP_VERB_DIALOG_LAYERS, + SP_VERB_EDIT_CLONE, SP_VERB_EDIT_COPY, SP_VERB_EDIT_CUT, SP_VERB_EDIT_DUPLICATE, SP_VERB_EDIT_PASTE, + SP_VERB_EDIT_REDO, SP_VERB_EDIT_UNDO, SP_VERB_EDIT_UNLINK_CLONE, + // SP_VERB_FILE_EXPORT, + SP_VERB_DIALOG_EXPORT, SP_VERB_FILE_IMPORT, SP_VERB_FILE_NEW, SP_VERB_FILE_OPEN, SP_VERB_FILE_PRINT, + SP_VERB_FILE_SAVE, SP_VERB_OBJECT_TO_CURVE, SP_VERB_SELECTION_GROUP, SP_VERB_SELECTION_OUTLINE, + SP_VERB_SELECTION_UNGROUP, SP_VERB_ZOOM_1_1, SP_VERB_ZOOM_1_2, SP_VERB_ZOOM_2_1, SP_VERB_ZOOM_DRAWING, + SP_VERB_ZOOM_IN, SP_VERB_ZOOM_NEXT, SP_VERB_ZOOM_OUT, SP_VERB_ZOOM_PAGE, SP_VERB_ZOOM_PAGE_WIDTH, + SP_VERB_ZOOM_PREV, SP_VERB_ZOOM_SELECTION, SP_VERB_ZOOM_CENTER_PAGE}; GtkIconSize toolboxSize = ToolboxFactory::prefToSize("/toolbox/small"); Glib::RefPtr<Gtk::ActionGroup> mainActions; - if (desktop == nullptr) - { + if (desktop == nullptr) { return mainActions; } - if ( groups.find(desktop) != groups.end() ) { + if (groups.find(desktop) != groups.end()) { mainActions = groups[desktop]; } - if ( !mainActions ) { + if (!mainActions) { mainActions = Gtk::ActionGroup::create("main"); groups[desktop] = mainActions; desktop->connectDestroy(&desktopDestructHandler); } for (int i : verbsToUse) { - Inkscape::Verb* verb = Inkscape::Verb::get(i); - if ( verb ) { + Inkscape::Verb *verb = Inkscape::Verb::get(i); + if (verb) { if (!mainActions->get_action(verb->get_id())) { - GtkAction* act = create_action_for_verb( verb, view, toolboxSize ); + GtkAction *act = create_action_for_verb(verb, view, toolboxSize); mainActions->add(Glib::wrap(act)); } } } - if ( !mainActions->get_action("ToolZoom") ) { - for ( guint i = 0; i < G_N_ELEMENTS(tools) && tools[i].type_name; i++ ) { - Glib::RefPtr<VerbAction> va = VerbAction::create(Inkscape::Verb::get(tools[i].verb), Inkscape::Verb::get(tools[i].doubleclick_verb), view); - if ( va ) { + if (!mainActions->get_action("ToolZoom")) { + for (guint i = 0; i < G_N_ELEMENTS(tools) && tools[i].type_name; i++) { + Glib::RefPtr<VerbAction> va = VerbAction::create(Inkscape::Verb::get(tools[i].verb), + Inkscape::Verb::get(tools[i].doubleclick_verb), view); + if (va) { mainActions->add(va); - if ( i == 0 ) { + if (i == 0) { va->set_active(true); } } else { @@ -382,8 +338,7 @@ static Glib::RefPtr<Gtk::ActionGroup> create_or_fetch_actions( SPDesktop* deskto return mainActions; } - -static GtkWidget* toolboxNewCommon( GtkWidget* tb, BarId id, GtkPositionType /*handlePos*/ ) +static GtkWidget *toolboxNewCommon(GtkWidget *tb, BarId id, GtkPositionType /*handlePos*/) { g_object_set_data(G_OBJECT(tb), "desktop", nullptr); @@ -395,7 +350,7 @@ static GtkWidget* toolboxNewCommon( GtkWidget* tb, BarId id, GtkPositionType /*h gtk_container_add(GTK_CONTAINER(hb), tb); gtk_widget_show(GTK_WIDGET(tb)); - sigc::connection* conn = new sigc::connection; + sigc::connection *conn = new sigc::connection; g_object_set_data(G_OBJECT(hb), "event_context_connection", conn); gpointer val = GINT_TO_POINTER(id); @@ -410,7 +365,7 @@ GtkWidget *ToolboxFactory::createToolToolbox() gtk_widget_set_name(tb, "ToolToolbox"); gtk_box_set_homogeneous(GTK_BOX(tb), FALSE); - return toolboxNewCommon( tb, BAR_TOOL, GTK_POS_TOP ); + return toolboxNewCommon(tb, BAR_TOOL, GTK_POS_TOP); } GtkWidget *ToolboxFactory::createAuxToolbox() @@ -419,7 +374,7 @@ GtkWidget *ToolboxFactory::createAuxToolbox() gtk_widget_set_name(tb, "AuxToolbox"); gtk_box_set_homogeneous(GTK_BOX(tb), FALSE); - return toolboxNewCommon( tb, BAR_AUX, GTK_POS_LEFT ); + return toolboxNewCommon(tb, BAR_AUX, GTK_POS_LEFT); } //#################################### @@ -432,7 +387,7 @@ GtkWidget *ToolboxFactory::createCommandsToolbox() gtk_widget_set_name(tb, "CommandsToolbox"); gtk_box_set_homogeneous(GTK_BOX(tb), FALSE); - return toolboxNewCommon( tb, BAR_COMMANDS, GTK_POS_LEFT ); + return toolboxNewCommon(tb, BAR_COMMANDS, GTK_POS_LEFT); } GtkWidget *ToolboxFactory::createSnapToolbox() @@ -441,15 +396,15 @@ GtkWidget *ToolboxFactory::createSnapToolbox() gtk_widget_set_name(tb, "SnapToolbox"); gtk_box_set_homogeneous(GTK_BOX(tb), FALSE); - return toolboxNewCommon( tb, BAR_SNAP, GTK_POS_LEFT ); + return toolboxNewCommon(tb, BAR_SNAP, GTK_POS_LEFT); } void ToolboxFactory::setToolboxDesktop(GtkWidget *toolbox, SPDesktop *desktop) { - sigc::connection *conn = static_cast<sigc::connection*>(g_object_get_data(G_OBJECT(toolbox), - "event_context_connection")); + sigc::connection *conn = + static_cast<sigc::connection *>(g_object_get_data(G_OBJECT(toolbox), "event_context_connection")); - BarId id = static_cast<BarId>( GPOINTER_TO_INT(g_object_get_data(G_OBJECT(toolbox), BAR_ID_KEY)) ); + BarId id = static_cast<BarId>(GPOINTER_TO_INT(g_object_get_data(G_OBJECT(toolbox), BAR_ID_KEY))); SetupFunction setup_func = nullptr; UpdateFunction update_func = nullptr; @@ -480,12 +435,12 @@ void ToolboxFactory::setToolboxDesktop(GtkWidget *toolbox, SPDesktop *desktop) } gpointer ptr = g_object_get_data(G_OBJECT(toolbox), "desktop"); - SPDesktop *old_desktop = static_cast<SPDesktop*>(ptr); + SPDesktop *old_desktop = static_cast<SPDesktop *>(ptr); if (old_desktop) { - std::vector<Gtk::Widget*> children = Glib::wrap(GTK_CONTAINER(toolbox))->get_children(); - for ( auto i:children ) { - gtk_container_remove( GTK_CONTAINER(toolbox), i->gobj() ); + std::vector<Gtk::Widget *> children = Glib::wrap(GTK_CONTAINER(toolbox))->get_children(); + for (auto i : children) { + gtk_container_remove(GTK_CONTAINER(toolbox), i->gobj()); } } @@ -495,64 +450,62 @@ void ToolboxFactory::setToolboxDesktop(GtkWidget *toolbox, SPDesktop *desktop) gtk_widget_set_sensitive(toolbox, TRUE); setup_func(toolbox, desktop); update_func(desktop, desktop->event_context, toolbox); - *conn = desktop->connectEventContextChanged(sigc::bind (sigc::ptr_fun(update_func), toolbox)); + *conn = desktop->connectEventContextChanged(sigc::bind(sigc::ptr_fun(update_func), toolbox)); } else { gtk_widget_set_sensitive(toolbox, FALSE); } } // end of sp_toolbox_set_desktop() - -static void setupToolboxCommon( GtkWidget *toolbox, - SPDesktop *desktop, - gchar const *ui_file, - gchar const* toolbarName, - gchar const* sizePref ) +static void setupToolboxCommon(GtkWidget *toolbox, SPDesktop *desktop, gchar const *ui_file, gchar const *toolbarName, + gchar const *sizePref) { - Glib::RefPtr<Gtk::ActionGroup> mainActions = create_or_fetch_actions( desktop ); + Glib::RefPtr<Gtk::ActionGroup> mainActions = create_or_fetch_actions(desktop); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - GtkUIManager* mgr = gtk_ui_manager_new(); - GError* err = nullptr; + GtkUIManager *mgr = gtk_ui_manager_new(); + GError *err = nullptr; GtkOrientation orientation = GTK_ORIENTATION_HORIZONTAL; - gtk_ui_manager_insert_action_group( mgr, mainActions->gobj(), 0 ); + gtk_ui_manager_insert_action_group(mgr, mainActions->gobj(), 0); Glib::ustring filename = get_filename(UIS, ui_file); - gtk_ui_manager_add_ui_from_file( mgr, filename.c_str(), &err ); - if(err) { + gtk_ui_manager_add_ui_from_file(mgr, filename.c_str(), &err); + if (err) { g_warning("Failed to load %s: %s", filename.c_str(), err->message); g_error_free(err); return; } - GtkWidget* toolBar = gtk_ui_manager_get_widget( mgr, toolbarName ); - if ( prefs->getBool("/toolbox/icononly", true) ) { - gtk_toolbar_set_style( GTK_TOOLBAR(toolBar), GTK_TOOLBAR_ICONS ); + GtkWidget *toolBar = gtk_ui_manager_get_widget(mgr, toolbarName); + if (prefs->getBool("/toolbox/icononly", true)) { + gtk_toolbar_set_style(GTK_TOOLBAR(toolBar), GTK_TOOLBAR_ICONS); } GtkIconSize toolboxSize = ToolboxFactory::prefToSize(sizePref); - gtk_toolbar_set_icon_size( GTK_TOOLBAR(toolBar), static_cast<GtkIconSize>(toolboxSize) ); + gtk_toolbar_set_icon_size(GTK_TOOLBAR(toolBar), static_cast<GtkIconSize>(toolboxSize)); - GtkPositionType pos = static_cast<GtkPositionType>(GPOINTER_TO_INT(g_object_get_data( G_OBJECT(toolbox), HANDLE_POS_MARK ))); - orientation = ((pos == GTK_POS_LEFT) || (pos == GTK_POS_RIGHT)) ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL; - gtk_orientable_set_orientation (GTK_ORIENTABLE(toolBar), orientation); + GtkPositionType pos = + static_cast<GtkPositionType>(GPOINTER_TO_INT(g_object_get_data(G_OBJECT(toolbox), HANDLE_POS_MARK))); + orientation = + ((pos == GTK_POS_LEFT) || (pos == GTK_POS_RIGHT)) ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL; + gtk_orientable_set_orientation(GTK_ORIENTABLE(toolBar), orientation); gtk_toolbar_set_show_arrow(GTK_TOOLBAR(toolBar), TRUE); g_object_set_data(G_OBJECT(toolBar), "desktop", nullptr); - GtkWidget* child = gtk_bin_get_child(GTK_BIN(toolbox)); - if ( child ) { - gtk_container_remove( GTK_CONTAINER(toolbox), child ); + GtkWidget *child = gtk_bin_get_child(GTK_BIN(toolbox)); + if (child) { + gtk_container_remove(GTK_CONTAINER(toolbox), child); } - gtk_container_add( GTK_CONTAINER(toolbox), toolBar ); + gtk_container_add(GTK_CONTAINER(toolbox), toolBar); } #define noDUMP_DETAILS 1 -void ToolboxFactory::setOrientation(GtkWidget* toolbox, GtkOrientation orientation) +void ToolboxFactory::setOrientation(GtkWidget *toolbox, GtkOrientation orientation) { #if DUMP_DETAILS g_message("Set orientation for %p to be %d", toolbox, orientation); @@ -567,7 +520,7 @@ void ToolboxFactory::setOrientation(GtkWidget* toolbox, GtkOrientation orientati #if DUMP_DETAILS g_message(" is a BIN"); #endif // DUMP_DETAILS - GtkWidget* child = gtk_bin_get_child(GTK_BIN(toolbox)); + GtkWidget *child = gtk_bin_get_child(GTK_BIN(toolbox)); if (child) { #if DUMP_DETAILS GType type2 = G_OBJECT_TYPE(child); @@ -579,35 +532,34 @@ void ToolboxFactory::setOrientation(GtkWidget* toolbox, GtkOrientation orientati g_message(" is a BOX"); #endif // DUMP_DETAILS - std::vector<Gtk::Widget*> children = Glib::wrap(GTK_CONTAINER(child))->get_children(); + std::vector<Gtk::Widget *> children = Glib::wrap(GTK_CONTAINER(child))->get_children(); if (!children.empty()) { - for (auto curr:children) { - GtkWidget* child2 = curr->gobj(); + for (auto curr : children) { + GtkWidget *child2 = curr->gobj(); #if DUMP_DETAILS GType type3 = G_OBJECT_TYPE(child2); g_message(" child2 [%s]", g_type_name(type3)); #endif // DUMP_DETAILS if (GTK_IS_CONTAINER(child2)) { - std::vector<Gtk::Widget*> children2 = Glib::wrap(GTK_CONTAINER(child2))->get_children(); + std::vector<Gtk::Widget *> children2 = Glib::wrap(GTK_CONTAINER(child2))->get_children(); if (!children2.empty()) { - for (auto curr2:children2) { - GtkWidget* child3 = curr2->gobj(); + for (auto curr2 : children2) { + GtkWidget *child3 = curr2->gobj(); #if DUMP_DETAILS GType type4 = G_OBJECT_TYPE(child3); g_message(" child3 [%s]", g_type_name(type4)); #endif // DUMP_DETAILS if (GTK_IS_TOOLBAR(child3)) { - GtkToolbar* childBar = GTK_TOOLBAR(child3); + GtkToolbar *childBar = GTK_TOOLBAR(child3); gtk_orientable_set_orientation(GTK_ORIENTABLE(childBar), orientation); } } } } - if (GTK_IS_TOOLBAR(child2)) { - GtkToolbar* childBar = GTK_TOOLBAR(child2); + GtkToolbar *childBar = GTK_TOOLBAR(child2); gtk_orientable_set_orientation(GTK_ORIENTABLE(childBar), orientation); } else { g_message("need to add dynamic switch"); @@ -618,8 +570,8 @@ void ToolboxFactory::setOrientation(GtkWidget* toolbox, GtkOrientation orientati g_object_set_data(G_OBJECT(toolbox), HANDLE_POS_MARK, GINT_TO_POINTER(pos)); } } else if (GTK_IS_TOOLBAR(child)) { - GtkToolbar* toolbar = GTK_TOOLBAR(child); - gtk_orientable_set_orientation( GTK_ORIENTABLE(toolbar), orientation ); + GtkToolbar *toolbar = GTK_TOOLBAR(child); + gtk_orientable_set_orientation(GTK_ORIENTABLE(toolbar), orientation); } } } @@ -630,19 +582,19 @@ void setup_tool_toolbox(GtkWidget *toolbox, SPDesktop *desktop) setupToolboxCommon(toolbox, desktop, "toolbar-tool.ui", "/ui/ToolToolbar", "/toolbox/tools/small"); } -void update_tool_toolbox( SPDesktop *desktop, ToolBase *eventcontext, GtkWidget * /*toolbox*/ ) +void update_tool_toolbox(SPDesktop *desktop, ToolBase *eventcontext, GtkWidget * /*toolbox*/) { - gchar const *const tname = ( eventcontext - ? eventcontext->getPrefsPath().c_str() //g_type_name(G_OBJECT_TYPE(eventcontext)) - : nullptr ); - Glib::RefPtr<Gtk::ActionGroup> mainActions = create_or_fetch_actions( desktop ); - - for (int i = 0 ; tools[i].type_name ; i++ ) { - Glib::RefPtr<Gtk::Action> act = mainActions->get_action( Inkscape::Verb::get(tools[i].verb)->get_id() ); - if ( act ) { + gchar const *const tname = + (eventcontext ? eventcontext->getPrefsPath().c_str() // g_type_name(G_OBJECT_TYPE(eventcontext)) + : nullptr); + Glib::RefPtr<Gtk::ActionGroup> mainActions = create_or_fetch_actions(desktop); + + for (int i = 0; tools[i].type_name; i++) { + Glib::RefPtr<Gtk::Action> act = mainActions->get_action(Inkscape::Verb::get(tools[i].verb)->get_id()); + if (act) { bool setActive = tname && !strcmp(tname, tools[i].type_name); Glib::RefPtr<VerbAction> verbAct = Glib::RefPtr<VerbAction>::cast_dynamic(act); - if ( verbAct ) { + if (verbAct) { verbAct->set_active(setActive); } } @@ -665,43 +617,43 @@ void setup_aux_toolbox(GtkWidget *toolbox, SPDesktop *desktop) // Loop through all the toolboxes and create them using either // their "create" methods. - for (int i = 0 ; aux_toolboxes[i].type_name ; i++ ) { + for (int i = 0; aux_toolboxes[i].type_name; i++) { if (aux_toolboxes[i].create_func) { GtkWidget *sub_toolbox = aux_toolboxes[i].create_func(desktop); - gtk_widget_set_name( sub_toolbox, "SubToolBox" ); + gtk_widget_set_name(sub_toolbox, "SubToolBox"); auto holder = gtk_grid_new(); gtk_grid_attach(GTK_GRID(holder), sub_toolbox, 0, 0, 1, 1); // This part is just for styling - if ( prefs->getBool( "/toolbox/icononly", true) ) { - gtk_toolbar_set_style( GTK_TOOLBAR(sub_toolbox), GTK_TOOLBAR_ICONS ); + if (prefs->getBool("/toolbox/icononly", true)) { + gtk_toolbar_set_style(GTK_TOOLBAR(sub_toolbox), GTK_TOOLBAR_ICONS); } GtkIconSize toolboxSize = ToolboxFactory::prefToSize("/toolbox/small"); - gtk_toolbar_set_icon_size( GTK_TOOLBAR(sub_toolbox), static_cast<GtkIconSize>(toolboxSize) ); + gtk_toolbar_set_icon_size(GTK_TOOLBAR(sub_toolbox), static_cast<GtkIconSize>(toolboxSize)); gtk_widget_set_hexpand(sub_toolbox, TRUE); // Add a swatch widget if one was specified - if ( aux_toolboxes[i].swatch_verb_id != SP_VERB_INVALID ) { - auto swatch = new Inkscape::UI::Widget::StyleSwatch( nullptr, _(aux_toolboxes[i].swatch_tip) ); - swatch->setDesktop( desktop ); - swatch->setClickVerb( aux_toolboxes[i].swatch_verb_id ); - swatch->setWatchedTool( aux_toolboxes[i].swatch_tool, true ); + if (aux_toolboxes[i].swatch_verb_id != SP_VERB_INVALID) { + auto swatch = new Inkscape::UI::Widget::StyleSwatch(nullptr, _(aux_toolboxes[i].swatch_tip)); + swatch->setDesktop(desktop); + swatch->setClickVerb(aux_toolboxes[i].swatch_verb_id); + swatch->setWatchedTool(aux_toolboxes[i].swatch_tool, true); swatch->set_margin_start(AUX_BETWEEN_BUTTON_GROUPS); swatch->set_margin_end(AUX_BETWEEN_BUTTON_GROUPS); swatch->set_margin_top(AUX_SPACING); swatch->set_margin_bottom(AUX_SPACING); - auto swatch_ = GTK_WIDGET( swatch->gobj() ); - gtk_grid_attach( GTK_GRID(holder), swatch_, 1, 0, 1, 1); + auto swatch_ = GTK_WIDGET(swatch->gobj()); + gtk_grid_attach(GTK_GRID(holder), swatch_, 1, 0, 1, 1); } // Add the new toolbar into the toolbox (i.e., make it the visible toolbar) // and also store a pointer to it inside the toolbox. This allows the // active toolbar to be changed. gtk_container_add(GTK_CONTAINER(toolbox), holder); - gtk_widget_set_name( holder, aux_toolboxes[i].ui_name ); + gtk_widget_set_name(holder, aux_toolboxes[i].ui_name); // TODO: We could make the toolbox a custom subclass of GtkEventBox // so that we can store a list of toolbars, rather than using @@ -717,10 +669,10 @@ void setup_aux_toolbox(GtkWidget *toolbox, SPDesktop *desktop) void update_aux_toolbox(SPDesktop * /*desktop*/, ToolBase *eventcontext, GtkWidget *toolbox) { - gchar const *tname = ( eventcontext - ? eventcontext->getPrefsPath().c_str() //g_type_name(G_OBJECT_TYPE(eventcontext)) - : nullptr ); - for (int i = 0 ; aux_toolboxes[i].type_name ; i++ ) { + gchar const *tname = + (eventcontext ? eventcontext->getPrefsPath().c_str() // g_type_name(G_OBJECT_TYPE(eventcontext)) + : nullptr); + for (int i = 0; aux_toolboxes[i].type_name; i++) { GtkWidget *sub_toolbox = GTK_WIDGET(g_object_get_data(G_OBJECT(toolbox), aux_toolboxes[i].data_name)); if (tname && !strcmp(tname, aux_toolboxes[i].type_name)) { gtk_widget_show_now(sub_toolbox); @@ -728,15 +680,15 @@ void update_aux_toolbox(SPDesktop * /*desktop*/, ToolBase *eventcontext, GtkWidg } else { gtk_widget_hide(sub_toolbox); } - //FIX issue #Inkscape686 + // FIX issue #Inkscape686 GtkAllocation allocation; gtk_widget_get_allocation(sub_toolbox, &allocation); gtk_widget_size_allocate(sub_toolbox, &allocation); } - //FIX issue #Inkscape125 + // FIX issue #Inkscape125 GtkAllocation allocation; gtk_widget_get_allocation(toolbox, &allocation); - gtk_widget_size_allocate(toolbox, &allocation); + gtk_widget_size_allocate(toolbox, &allocation); } void setup_commands_toolbox(GtkWidget *toolbox, SPDesktop *desktop) @@ -744,9 +696,7 @@ void setup_commands_toolbox(GtkWidget *toolbox, SPDesktop *desktop) setupToolboxCommon(toolbox, desktop, "toolbar-commands.ui", "/ui/CommandsToolbar", "/toolbox/small"); } -void update_commands_toolbox(SPDesktop * /*desktop*/, ToolBase * /*eventcontext*/, GtkWidget * /*toolbox*/) -{ -} +void update_commands_toolbox(SPDesktop * /*desktop*/, ToolBase * /*eventcontext*/, GtkWidget * /*toolbox*/) {} void setup_snap_toolbox(GtkWidget *toolbox, SPDesktop *desktop) { @@ -754,31 +704,33 @@ void setup_snap_toolbox(GtkWidget *toolbox, SPDesktop *desktop) auto toolBar = Inkscape::UI::Toolbar::SnapToolbar::create(desktop); auto prefs = Inkscape::Preferences::get(); - if ( prefs->getBool("/toolbox/icononly", true) ) { - gtk_toolbar_set_style( GTK_TOOLBAR(toolBar), GTK_TOOLBAR_ICONS ); + if (prefs->getBool("/toolbox/icononly", true)) { + gtk_toolbar_set_style(GTK_TOOLBAR(toolBar), GTK_TOOLBAR_ICONS); } GtkIconSize toolboxSize = ToolboxFactory::prefToSize(sizePref.c_str()); - gtk_toolbar_set_icon_size( GTK_TOOLBAR(toolBar), static_cast<GtkIconSize>(toolboxSize) ); + gtk_toolbar_set_icon_size(GTK_TOOLBAR(toolBar), static_cast<GtkIconSize>(toolboxSize)); - GtkPositionType pos = static_cast<GtkPositionType>(GPOINTER_TO_INT(g_object_get_data( G_OBJECT(toolbox), HANDLE_POS_MARK ))); - auto orientation = ((pos == GTK_POS_LEFT) || (pos == GTK_POS_RIGHT)) ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL; - gtk_orientable_set_orientation (GTK_ORIENTABLE(toolBar), orientation); + GtkPositionType pos = + static_cast<GtkPositionType>(GPOINTER_TO_INT(g_object_get_data(G_OBJECT(toolbox), HANDLE_POS_MARK))); + auto orientation = + ((pos == GTK_POS_LEFT) || (pos == GTK_POS_RIGHT)) ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL; + gtk_orientable_set_orientation(GTK_ORIENTABLE(toolBar), orientation); gtk_toolbar_set_show_arrow(GTK_TOOLBAR(toolBar), TRUE); - GtkWidget* child = gtk_bin_get_child(GTK_BIN(toolbox)); - if ( child ) { - gtk_container_remove( GTK_CONTAINER(toolbox), child ); + GtkWidget *child = gtk_bin_get_child(GTK_BIN(toolbox)); + if (child) { + gtk_container_remove(GTK_CONTAINER(toolbox), child); } - gtk_container_add( GTK_CONTAINER(toolbox), toolBar ); + gtk_container_add(GTK_CONTAINER(toolbox), toolBar); } -Glib::ustring ToolboxFactory::getToolboxName(GtkWidget* toolbox) +Glib::ustring ToolboxFactory::getToolboxName(GtkWidget *toolbox) { Glib::ustring name; - BarId id = static_cast<BarId>( GPOINTER_TO_INT(g_object_get_data(G_OBJECT(toolbox), BAR_ID_KEY)) ); - switch(id) { + BarId id = static_cast<BarId>(GPOINTER_TO_INT(g_object_get_data(G_OBJECT(toolbox), BAR_ID_KEY))); + switch (id) { case BAR_TOOL: name = "ToolToolbar"; break; @@ -798,7 +750,8 @@ Glib::ustring ToolboxFactory::getToolboxName(GtkWidget* toolbox) void ToolboxFactory::updateSnapToolbox(SPDesktop *desktop, ToolBase * /*eventcontext*/, GtkWidget *toolbox) { - auto tb = dynamic_cast<Inkscape::UI::Toolbar::SnapToolbar*>(Glib::wrap(GTK_TOOLBAR(gtk_bin_get_child(GTK_BIN(toolbox))))); + auto tb = dynamic_cast<Inkscape::UI::Toolbar::SnapToolbar *>( + Glib::wrap(GTK_TOOLBAR(gtk_bin_get_child(GTK_BIN(toolbox))))); if (!tb) { std::cerr << "Can't get snap toolbar" << std::endl; @@ -822,7 +775,6 @@ void ToolboxFactory::showAuxToolbox(GtkWidget *toolbox_toplevel) #define MODE_LABEL_WIDTH 70 - /* Local Variables: mode:c++ diff --git a/src/widgets/toolbox.h b/src/widgets/toolbox.h index f3ec74dca14109d9dd0a38f5c60d08ba051efdab..4f00326d8c7a74a95ff23162edf538bb2955d9a6 100644 --- a/src/widgets/toolbox.h +++ b/src/widgets/toolbox.h @@ -31,14 +31,14 @@ namespace Tools { class ToolBase; } -} -} +} // namespace UI +} // namespace Inkscape namespace Inkscape { namespace UI { namespace Widget { - class UnitTracker; +class UnitTracker; } /** @@ -48,27 +48,24 @@ class ToolboxFactory { public: static void setToolboxDesktop(GtkWidget *toolbox, SPDesktop *desktop); - static void setOrientation(GtkWidget* toolbox, GtkOrientation orientation); - static void showAuxToolbox(GtkWidget* toolbox); + static void setOrientation(GtkWidget *toolbox, GtkOrientation orientation); + static void showAuxToolbox(GtkWidget *toolbox); static GtkWidget *createToolToolbox(); static GtkWidget *createAuxToolbox(); static GtkWidget *createCommandsToolbox(); static GtkWidget *createSnapToolbox(); - - static Glib::ustring getToolboxName(GtkWidget* toolbox); + static Glib::ustring getToolboxName(GtkWidget *toolbox); static void updateSnapToolbox(SPDesktop *desktop, Inkscape::UI::Tools::ToolBase *eventcontext, GtkWidget *toolbox); - static GtkIconSize prefToSize(Glib::ustring const &path, int base = 0 ); + static GtkIconSize prefToSize(Glib::ustring const &path, int base = 0); static Gtk::IconSize prefToSize_mm(Glib::ustring const &path, int base = 0); ToolboxFactory() = delete; }; - - } // namespace UI } // namespace Inkscape diff --git a/src/xml/attribute-record.h b/src/xml/attribute-record.h index 68080403e0efa34ad34db1b7c1fa4ed6e3f6ced8..e9fe24971cf7b2ec7fe9095fd4b8543960927697 100644 --- a/src/xml/attribute-record.h +++ b/src/xml/attribute-record.h @@ -15,6 +15,7 @@ #define SEEN_XML_SP_REPR_ATTR_H #include <glib.h> + #include "inkgc/gc-managed.h" #include "util/share.h" @@ -30,9 +31,12 @@ namespace XML { * Internally, the attributes of each node in the XML tree are * represented by this structure. */ -struct AttributeRecord : public Inkscape::GC::Managed<> { +struct AttributeRecord : public Inkscape::GC::Managed<> +{ AttributeRecord(GQuark k, Inkscape::Util::ptr_shared v) - : key(k), value(v) {} + : key(k) + , value(v) + {} /** @brief GQuark corresponding to the name of the attribute */ GQuark key; @@ -42,8 +46,8 @@ struct AttributeRecord : public Inkscape::GC::Managed<> { // accept default copy constructor and assignment operator }; -} -} +} // namespace XML +} // namespace Inkscape #endif /* !SEEN_XML_SP_REPR_ATTR_H */ diff --git a/src/xml/comment-node.h b/src/xml/comment-node.h index 3298152157ef534377903be0db4980388c4db8cc..4c0bea8afdc42e4cceadad00ce11a9623548d67d 100644 --- a/src/xml/comment-node.h +++ b/src/xml/comment-node.h @@ -10,11 +10,11 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ - #ifndef SEEN_INKSCAPE_XML_COMMENT_NODE_H #define SEEN_INKSCAPE_XML_COMMENT_NODE_H #include <glib.h> + #include "xml/simple-node.h" namespace Inkscape { @@ -24,25 +24,27 @@ namespace XML { /** * @brief Comment node, e.g. <!-- Some comment --> */ -struct CommentNode : public SimpleNode { +struct CommentNode : public SimpleNode +{ CommentNode(Util::ptr_shared content, Document *doc) - : SimpleNode(g_quark_from_static_string("comment"), doc) + : SimpleNode(g_quark_from_static_string("comment"), doc) { setContent(content); } CommentNode(CommentNode const &other, Document *doc) - : SimpleNode(other, doc) {} + : SimpleNode(other, doc) + {} Inkscape::XML::NodeType type() const override { return Inkscape::XML::COMMENT_NODE; } protected: - SimpleNode *_duplicate(Document* doc) const override { return new CommentNode(*this, doc); } + SimpleNode *_duplicate(Document *doc) const override { return new CommentNode(*this, doc); } }; -} +} // namespace XML -} +} // namespace Inkscape #endif /* diff --git a/src/xml/composite-node-observer.cpp b/src/xml/composite-node-observer.cpp index 36121ba7e4bcf5face4cb3cb615afab85bcbc36f..5750000d5d30e8bceb25bd3dc5aae214db0fe80c 100644 --- a/src/xml/composite-node-observer.cpp +++ b/src/xml/composite-node-observer.cpp @@ -21,14 +21,15 @@ * */ +#include "xml/composite-node-observer.h" + #include <cstring> #include <glib.h> -#include "util/find-if-before.h" -#include "xml/composite-node-observer.h" -#include "xml/node-event-vector.h" #include "debug/event-tracker.h" #include "debug/simple-event.h" +#include "util/find-if-before.h" +#include "xml/node-event-vector.h" namespace Inkscape { @@ -37,8 +38,7 @@ namespace XML { void CompositeNodeObserver::notifyChildAdded(Node &node, Node &child, Node *prev) { _startIteration(); - for (auto & iter : _active) - { + for (auto &iter : _active) { if (!iter.marked) { iter.observer.notifyChildAdded(node, child, prev); } @@ -46,12 +46,10 @@ void CompositeNodeObserver::notifyChildAdded(Node &node, Node &child, Node *prev _finishIteration(); } -void CompositeNodeObserver::notifyChildRemoved(Node &node, Node &child, - Node *prev) +void CompositeNodeObserver::notifyChildRemoved(Node &node, Node &child, Node *prev) { _startIteration(); - for (auto & iter : _active) - { + for (auto &iter : _active) { if (!iter.marked) { iter.observer.notifyChildRemoved(node, child, prev); } @@ -59,13 +57,10 @@ void CompositeNodeObserver::notifyChildRemoved(Node &node, Node &child, _finishIteration(); } -void CompositeNodeObserver::notifyChildOrderChanged(Node &node, Node &child, - Node *old_prev, - Node *new_prev) +void CompositeNodeObserver::notifyChildOrderChanged(Node &node, Node &child, Node *old_prev, Node *new_prev) { _startIteration(); - for (auto & iter : _active) - { + for (auto &iter : _active) { if (!iter.marked) { iter.observer.notifyChildOrderChanged(node, child, old_prev, new_prev); } @@ -73,13 +68,10 @@ void CompositeNodeObserver::notifyChildOrderChanged(Node &node, Node &child, _finishIteration(); } -void CompositeNodeObserver::notifyContentChanged( - Node &node, - Util::ptr_shared old_content, Util::ptr_shared new_content -) { +void CompositeNodeObserver::notifyContentChanged(Node &node, Util::ptr_shared old_content, Util::ptr_shared new_content) +{ _startIteration(); - for (auto & iter : _active) - { + for (auto &iter : _active) { if (!iter.marked) { iter.observer.notifyContentChanged(node, old_content, new_content); } @@ -87,13 +79,11 @@ void CompositeNodeObserver::notifyContentChanged( _finishIteration(); } -void CompositeNodeObserver::notifyAttributeChanged( - Node &node, GQuark name, - Util::ptr_shared old_value, Util::ptr_shared new_value -) { +void CompositeNodeObserver::notifyAttributeChanged(Node &node, GQuark name, Util::ptr_shared old_value, + Util::ptr_shared new_value) +{ _startIteration(); - for (auto & iter : _active) - { + for (auto &iter : _active) { if (!iter.marked) { iter.observer.notifyAttributeChanged(node, name, old_value, new_value); } @@ -101,10 +91,10 @@ void CompositeNodeObserver::notifyAttributeChanged( _finishIteration(); } -void CompositeNodeObserver::notifyElementNameChanged(Node& node, GQuark old_name, GQuark new_name) +void CompositeNodeObserver::notifyElementNameChanged(Node &node, GQuark old_name, GQuark new_name) { _startIteration(); - for (auto& iter : _active) { + for (auto &iter : _active) { if (!iter.marked) { iter.observer.notifyElementNameChanged(node, old_name, new_name); } @@ -112,7 +102,8 @@ void CompositeNodeObserver::notifyElementNameChanged(Node& node, GQuark old_name _finishIteration(); } -void CompositeNodeObserver::add(NodeObserver &observer) { +void CompositeNodeObserver::add(NodeObserver &observer) +{ if (_iterating) { _pending.emplace_back(observer); } else { @@ -122,57 +113,68 @@ void CompositeNodeObserver::add(NodeObserver &observer) { namespace { -class VectorNodeObserver : public NodeObserver, public GC::Managed<> { +class VectorNodeObserver + : public NodeObserver + , public GC::Managed<> +{ public: VectorNodeObserver(NodeEventVector const &v, void *d) - : vector(v), data(d) {} + : vector(v) + , data(d) + {} NodeEventVector const &vector; - void * const data; + void *const data; - void notifyChildAdded(Node &node, Node &child, Node *prev) override { + void notifyChildAdded(Node &node, Node &child, Node *prev) override + { if (vector.child_added) { vector.child_added(&node, &child, prev, data); } } - void notifyChildRemoved(Node &node, Node &child, Node *prev) override { + void notifyChildRemoved(Node &node, Node &child, Node *prev) override + { if (vector.child_removed) { vector.child_removed(&node, &child, prev, data); } } - void notifyChildOrderChanged(Node &node, Node &child, Node *old_prev, Node *new_prev) override { + void notifyChildOrderChanged(Node &node, Node &child, Node *old_prev, Node *new_prev) override + { if (vector.order_changed) { vector.order_changed(&node, &child, old_prev, new_prev, data); } } - void notifyContentChanged(Node &node, Util::ptr_shared old_content, Util::ptr_shared new_content) override { + void notifyContentChanged(Node &node, Util::ptr_shared old_content, Util::ptr_shared new_content) override + { if (vector.content_changed) { vector.content_changed(&node, old_content, new_content, data); } } - void notifyAttributeChanged(Node &node, GQuark name, Util::ptr_shared old_value, Util::ptr_shared new_value) override { + void notifyAttributeChanged(Node &node, GQuark name, Util::ptr_shared old_value, + Util::ptr_shared new_value) override + { if (vector.attr_changed) { vector.attr_changed(&node, g_quark_to_string(name), old_value, new_value, false, data); } } - void notifyElementNameChanged(Node& node, GQuark old_name, GQuark new_name) override { + void notifyElementNameChanged(Node &node, GQuark old_name, GQuark new_name) override + { if (vector.element_name_changed) { vector.element_name_changed(&node, g_quark_to_string(old_name), g_quark_to_string(new_name), data); } } }; -} +} // namespace -void CompositeNodeObserver::addListener(NodeEventVector const &vector, - void *data) +void CompositeNodeObserver::addListener(NodeEventVector const &vector, void *data) { - Debug::EventTracker<Debug::SimpleEvent<Debug::Event::XML> > tracker("add-listener"); + Debug::EventTracker<Debug::SimpleEvent<Debug::Event::XML>> tracker("add-listener"); add(*(new VectorNodeObserver(vector, data))); } @@ -182,24 +184,22 @@ typedef CompositeNodeObserver::ObserverRecord ObserverRecord; typedef CompositeNodeObserver::ObserverRecordList ObserverRecordList; template <typename ObserverPredicate> -struct unmarked_record_satisfying { +struct unmarked_record_satisfying +{ ObserverPredicate predicate; - unmarked_record_satisfying(ObserverPredicate p) : predicate(p) {} - bool operator()(ObserverRecord const &record) { - return !record.marked && predicate(record.observer); - } + unmarked_record_satisfying(ObserverPredicate p) + : predicate(p) + {} + bool operator()(ObserverRecord const &record) { return !record.marked && predicate(record.observer); } }; template <typename Predicate> -bool mark_one(ObserverRecordList &observers, unsigned &marked_count, - Predicate p) +bool mark_one(ObserverRecordList &observers, unsigned &marked_count, Predicate p) { - ObserverRecordList::iterator found=std::find_if( - observers.begin(), observers.end(), - unmarked_record_satisfying<Predicate>(p) - ); + ObserverRecordList::iterator found = + std::find_if(observers.begin(), observers.end(), unmarked_record_satisfying<Predicate>(p)); - if ( found != observers.end() ) { + if (found != observers.end()) { ++marked_count; found->marked = true; return true; @@ -209,15 +209,12 @@ bool mark_one(ObserverRecordList &observers, unsigned &marked_count, } template <typename Predicate> -bool remove_one(ObserverRecordList &observers, unsigned &/*marked_count*/, - Predicate p) +bool remove_one(ObserverRecordList &observers, unsigned & /*marked_count*/, Predicate p) { - ObserverRecordList::iterator found = std::find_if( - observers.begin(), observers.end(), - unmarked_record_satisfying<Predicate>(p) - ); + ObserverRecordList::iterator found = + std::find_if(observers.begin(), observers.end(), unmarked_record_satisfying<Predicate>(p)); - if ( found != observers.end() ) { + if (found != observers.end()) { observers.erase(found); return true; } else { @@ -225,7 +222,10 @@ bool remove_one(ObserverRecordList &observers, unsigned &/*marked_count*/, } } -bool is_marked(ObserverRecord const &record) { return record.marked; } +bool is_marked(ObserverRecord const &record) +{ + return record.marked; +} void remove_all_marked(ObserverRecordList &observers, unsigned &marked_count) { @@ -237,9 +237,10 @@ void remove_all_marked(ObserverRecordList &observers, unsigned &marked_count) } } -} +} // namespace -void CompositeNodeObserver::_finishIteration() { +void CompositeNodeObserver::_finishIteration() +{ if (!--_iterating) { remove_all_marked(_active, _active_marked); remove_all_marked(_pending, _pending_marked); @@ -250,35 +251,39 @@ void CompositeNodeObserver::_finishIteration() { namespace { -struct eql_observer { +struct eql_observer +{ NodeObserver const &observer; - eql_observer(NodeObserver const &o) : observer(o) {} - bool operator()(NodeObserver const &other) { - return &observer == &other; - } + eql_observer(NodeObserver const &o) + : observer(o) + {} + bool operator()(NodeObserver const &other) { return &observer == &other; } }; -} +} // namespace -void CompositeNodeObserver::remove(NodeObserver &observer) { +void CompositeNodeObserver::remove(NodeObserver &observer) +{ eql_observer p(observer); if (_iterating) { - mark_one(_active, _active_marked, p) || - mark_one(_pending, _pending_marked, p); + mark_one(_active, _active_marked, p) || mark_one(_pending, _pending_marked, p); } else { - remove_one(_active, _active_marked, p) || - remove_one(_pending, _pending_marked, p); + remove_one(_active, _active_marked, p) || remove_one(_pending, _pending_marked, p); } } namespace { -struct vector_data_matches { - void * const data; - vector_data_matches(void *d) : data(d) {} - - bool operator()(NodeObserver const &observer) { - VectorNodeObserver const *vo=dynamic_cast<VectorNodeObserver const *>(&observer); +struct vector_data_matches +{ + void *const data; + vector_data_matches(void *d) + : data(d) + {} + + bool operator()(NodeObserver const &observer) + { + VectorNodeObserver const *vo = dynamic_cast<VectorNodeObserver const *>(&observer); bool OK = false; if (vo) { if (vo && vo->data == data) { @@ -289,23 +294,22 @@ struct vector_data_matches { } }; -} +} // namespace -void CompositeNodeObserver::removeListenerByData(void *data) { - Debug::EventTracker<Debug::SimpleEvent<Debug::Event::XML> > tracker("remove-listener-by-data"); +void CompositeNodeObserver::removeListenerByData(void *data) +{ + Debug::EventTracker<Debug::SimpleEvent<Debug::Event::XML>> tracker("remove-listener-by-data"); vector_data_matches p(data); if (_iterating) { - mark_one(_active, _active_marked, p) || - mark_one(_pending, _pending_marked, p); + mark_one(_active, _active_marked, p) || mark_one(_pending, _pending_marked, p); } else { - remove_one(_active, _active_marked, p) || - remove_one(_pending, _pending_marked, p); + remove_one(_active, _active_marked, p) || remove_one(_pending, _pending_marked, p); } } - -} -} +} // namespace XML + +} // namespace Inkscape /* Local Variables: diff --git a/src/xml/composite-node-observer.h b/src/xml/composite-node-observer.h index 7a8c7d5ae778e043a2f4245a3416e2442170db33..656c15e2db1665107eb695cc11d4774605dd2a9b 100644 --- a/src/xml/composite-node-observer.h +++ b/src/xml/composite-node-observer.h @@ -13,10 +13,11 @@ #ifndef SEEN_INKSCAPE_XML_COMPOSITE_NODE_OBSERVER_H #define SEEN_INKSCAPE_XML_COMPOSITE_NODE_OBSERVER_H +#include <list> + #include "inkgc/gc-alloc.h" #include "inkgc/gc-managed.h" #include "xml/node-observer.h" -#include <list> namespace Inkscape { @@ -32,10 +33,17 @@ struct NodeEventVector; * allows an observer to remove itself from this object during a method call. * For the documentation of callback methods, see NodeObserver. */ -class CompositeNodeObserver : public NodeObserver, public GC::Managed<> { +class CompositeNodeObserver + : public NodeObserver + , public GC::Managed<> +{ public: - struct ObserverRecord : public GC::Managed<> { - explicit ObserverRecord(NodeObserver &o) : observer(o), marked(false) {} + struct ObserverRecord : public GC::Managed<> + { + explicit ObserverRecord(NodeObserver &o) + : observer(o) + , marked(false) + {} NodeObserver &observer; bool marked; //< if marked for removal @@ -43,7 +51,10 @@ public: typedef std::list<ObserverRecord, Inkscape::GC::Alloc<ObserverRecord, Inkscape::GC::MANUAL>> ObserverRecordList; CompositeNodeObserver() - : _iterating(0), _active_marked(0), _pending_marked(0) {} + : _iterating(0) + , _active_marked(0) + , _pending_marked(0) + {} /** * @brief Add an observer to the list @@ -65,23 +76,19 @@ public: * @deprecated Use remove() instead */ void removeListenerByData(void *data); - + void notifyChildAdded(Node &node, Node &child, Node *prev) override; void notifyChildRemoved(Node &node, Node &child, Node *prev) override; - void notifyChildOrderChanged(Node &node, Node &child, - Node *old_prev, Node *new_prev) override; + void notifyChildOrderChanged(Node &node, Node &child, Node *old_prev, Node *new_prev) override; - void notifyContentChanged(Node &node, - Util::ptr_shared old_content, - Util::ptr_shared new_content) override; + void notifyContentChanged(Node &node, Util::ptr_shared old_content, Util::ptr_shared new_content) override; - void notifyAttributeChanged(Node &node, GQuark name, - Util::ptr_shared old_value, + void notifyAttributeChanged(Node &node, GQuark name, Util::ptr_shared old_value, Util::ptr_shared new_value) override; - void notifyElementNameChanged(Node& node, GQuark old_name, GQuark new_name) override; + void notifyElementNameChanged(Node &node, GQuark old_name, GQuark new_name) override; private: unsigned _iterating; diff --git a/src/xml/croco-node-iface.cpp b/src/xml/croco-node-iface.cpp index 390c7b13ed8269f3af61d2f31ec4caaf417d0cad..76052eaf9e3e387313263bd94b93aab04f7c2ce2 100644 --- a/src/xml/croco-node-iface.cpp +++ b/src/xml/croco-node-iface.cpp @@ -7,15 +7,15 @@ * Copyright (C) 2018 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "xml/croco-node-iface.h" + #include <cstring> -#include <string> #include <glib.h> +#include <string> -#include "xml/croco-node-iface.h" #include "xml/node.h" -static char const * -local_part(char const *const qname) +static char const *local_part(char const *const qname) { char const *ret = std::strrchr(qname, ':'); if (ret) @@ -29,9 +29,18 @@ namespace XML { extern "C" { -static CRXMLNodePtr get_parent(CRXMLNodePtr n) { return static_cast<Node const *>(n)->parent(); } -static CRXMLNodePtr get_first_child(CRXMLNodePtr n) { return static_cast<Node const *>(n)->firstChild(); } -static CRXMLNodePtr get_next(CRXMLNodePtr n) { return static_cast<Node const *>(n)->next(); } +static CRXMLNodePtr get_parent(CRXMLNodePtr n) +{ + return static_cast<Node const *>(n)->parent(); +} +static CRXMLNodePtr get_first_child(CRXMLNodePtr n) +{ + return static_cast<Node const *>(n)->firstChild(); +} +static CRXMLNodePtr get_next(CRXMLNodePtr n) +{ + return static_cast<Node const *>(n)->next(); +} static CRXMLNodePtr get_prev(CRXMLNodePtr cn) { @@ -49,8 +58,14 @@ static char *get_attr(CRXMLNodePtr n, char const *a) return g_strdup(static_cast<Node const *>(n)->attribute(a)); } -static char const *get_local_name(CRXMLNodePtr n) { return local_part(static_cast<Node const *>(n)->name()); } -static gboolean is_element_node(CRXMLNodePtr n) { return static_cast<Node const *>(n)->type() == ELEMENT_NODE; } +static char const *get_local_name(CRXMLNodePtr n) +{ + return local_part(static_cast<Node const *>(n)->name()); +} +static gboolean is_element_node(CRXMLNodePtr n) +{ + return static_cast<Node const *>(n)->type() == ELEMENT_NODE; +} } /** @@ -59,20 +74,11 @@ static gboolean is_element_node(CRXMLNodePtr n) { return static_cast<Node const * This structure defines operations on Inkscape::XML::Node used by the libcroco * CSS parsing library. */ -CRNodeIface const croco_node_iface = { - get_parent, - get_first_child, - get_next, - get_prev, - get_local_name, - get_attr, - g_free, - is_element_node -}; - -} -} +CRNodeIface const croco_node_iface = {get_parent, get_first_child, get_next, get_prev, + get_local_name, get_attr, g_free, is_element_node}; +} // namespace XML +} // namespace Inkscape /* Local Variables: diff --git a/src/xml/croco-node-iface.h b/src/xml/croco-node-iface.h index 2965adef644f365e13ab6689296c016d72b8af0f..90ef432608f42175c1e55f1f8b9ae8a4c1d795ea 100644 --- a/src/xml/croco-node-iface.h +++ b/src/xml/croco-node-iface.h @@ -16,6 +16,6 @@ namespace Inkscape { namespace XML { extern CRNodeIface const croco_node_iface; } -} +} // namespace Inkscape #endif /* !INKSCAPE_SP_REPR_NODE_IFACE_H */ diff --git a/src/xml/document.h b/src/xml/document.h index 92878b26ea9fa99551efb627933077e8a0a3396f..b2f148b2fdf0e77a6fbed200c9b20bae40490da6 100644 --- a/src/xml/document.h +++ b/src/xml/document.h @@ -38,7 +38,8 @@ namespace XML { * "restore point" by calling beginTransaction() again. There can be only one active * transaction at a time for a given document. */ -struct Document : virtual public Node { +struct Document : virtual public Node +{ public: /** * @name Document transactions @@ -48,14 +49,14 @@ public: * @brief Checks whether there is an active transaction for this document * @return true if there's an established transaction for this document, false otherwise */ - virtual bool inTransaction()=0; + virtual bool inTransaction() = 0; /** * @brief Begin a transaction and start recording changes * * By calling this method you effectively establish a resotre point. * You can undo all changes made to the document after this call using rollback(). */ - virtual void beginTransaction()=0; + virtual void beginTransaction() = 0; /** * @brief Restore the state of the document prior to the transaction * @@ -63,13 +64,13 @@ public: * restoring the document state from before the transaction. For some implementations, * this function may do nothing. */ - virtual void rollback()=0; + virtual void rollback() = 0; /** * @brief Commit a transaction and discard change data * * This method finishes the active transaction and discards the recorded changes. */ - virtual void commit()=0; + virtual void commit() = 0; /** * @brief Commit a transaction and store the events for later use * @@ -80,18 +81,18 @@ public: * * @return Event chain describing the changes, or NULL */ - virtual Event *commitUndoable()=0; + virtual Event *commitUndoable() = 0; /*@}*/ /** * @name Create new nodes * @{ */ - virtual Node *createElement(char const *name)=0; - virtual Node *createTextNode(char const *content)=0; - virtual Node *createTextNode(char const *content, bool is_CData)=0; - virtual Node *createComment(char const *content)=0; - virtual Node *createPI(char const *target, char const *content)=0; + virtual Node *createElement(char const *name) = 0; + virtual Node *createTextNode(char const *content) = 0; + virtual Node *createTextNode(char const *content, bool is_CData) = 0; + virtual Node *createComment(char const *content) = 0; + virtual Node *createPI(char const *target, char const *content) = 0; /*@}*/ /** @@ -100,11 +101,11 @@ public: * This is an implementation detail that should not be used outside of node implementations. * It should be made non-public in the future. */ - virtual NodeObserver *logger()=0; + virtual NodeObserver *logger() = 0; }; -} -} +} // namespace XML +} // namespace Inkscape #endif /* diff --git a/src/xml/element-node.h b/src/xml/element-node.h index 376790feb230bfc0e59edf621880fb39b60a19ad..fbd21aa0c7c9d75aaa961c8f5234799749f0a4e3 100644 --- a/src/xml/element-node.h +++ b/src/xml/element-node.h @@ -22,22 +22,25 @@ namespace XML { /** * @brief Element node, e.g. <group /> */ -class ElementNode : public SimpleNode { +class ElementNode : public SimpleNode +{ public: ElementNode(int code, Document *doc) - : SimpleNode(code, doc) {} + : SimpleNode(code, doc) + {} ElementNode(ElementNode const &other, Document *doc) - : SimpleNode(other, doc) {} + : SimpleNode(other, doc) + {} Inkscape::XML::NodeType type() const override { return Inkscape::XML::ELEMENT_NODE; } protected: - SimpleNode *_duplicate(Document* doc) const override { return new ElementNode(*this, doc); } + SimpleNode *_duplicate(Document *doc) const override { return new ElementNode(*this, doc); } }; -} +} // namespace XML -} +} // namespace Inkscape #endif /* diff --git a/src/xml/event-fns.h b/src/xml/event-fns.h index f3a6e522e32fb4e81acad0582a6bc08e2d84c3bd..31bae866b635c8b6bf07c4a16478c3421ea39ff0 100644 --- a/src/xml/event-fns.h +++ b/src/xml/event-fns.h @@ -20,18 +20,18 @@ class NodeObserver; void replay_log_to_observer(Event const *log, NodeObserver &observer); void undo_log_to_observer(Event const *log, NodeObserver &observer); -} -} +} // namespace XML +} // namespace Inkscape -void sp_repr_begin_transaction (Inkscape::XML::Document *doc); -void sp_repr_rollback (Inkscape::XML::Document *doc); -void sp_repr_commit (Inkscape::XML::Document *doc); -Inkscape::XML::Event *sp_repr_commit_undoable (Inkscape::XML::Document *doc); +void sp_repr_begin_transaction(Inkscape::XML::Document *doc); +void sp_repr_rollback(Inkscape::XML::Document *doc); +void sp_repr_commit(Inkscape::XML::Document *doc); +Inkscape::XML::Event *sp_repr_commit_undoable(Inkscape::XML::Document *doc); -void sp_repr_undo_log (Inkscape::XML::Event *log); -void sp_repr_replay_log (Inkscape::XML::Event *log); -Inkscape::XML::Event *sp_repr_coalesce_log (Inkscape::XML::Event *a, Inkscape::XML::Event *b); -void sp_repr_free_log (Inkscape::XML::Event *log); +void sp_repr_undo_log(Inkscape::XML::Event *log); +void sp_repr_replay_log(Inkscape::XML::Event *log); +Inkscape::XML::Event *sp_repr_coalesce_log(Inkscape::XML::Event *a, Inkscape::XML::Event *b); +void sp_repr_free_log(Inkscape::XML::Event *log); void sp_repr_debug_print_log(Inkscape::XML::Event const *log); #endif diff --git a/src/xml/event.cpp b/src/xml/event.cpp index 86e042a2bfb26f5f6f0de788c1658e630d21697b..e18bacdd219d487a6235506673d4063ac1a0eed5 100644 --- a/src/xml/event.cpp +++ b/src/xml/event.cpp @@ -14,69 +14,66 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <glib.h> // g_assert() +#include "event.h" + #include <cstdio> +#include <glib.h> // g_assert() -#include "event.h" +#include "debug/event-tracker.h" +#include "debug/simple-event.h" #include "event-fns.h" #include "util/reverse-list.h" #include "xml/document.h" #include "xml/node-observer.h" -#include "debug/event-tracker.h" -#include "debug/simple-event.h" using Inkscape::Util::List; using Inkscape::Util::reverse_list; -int Inkscape::XML::Event::_next_serial=0; +int Inkscape::XML::Event::_next_serial = 0; -void -sp_repr_begin_transaction (Inkscape::XML::Document *doc) +void sp_repr_begin_transaction(Inkscape::XML::Document *doc) { - using Inkscape::Debug::SimpleEvent; - using Inkscape::Debug::EventTracker; using Inkscape::Debug::Event; + using Inkscape::Debug::EventTracker; + using Inkscape::Debug::SimpleEvent; - EventTracker<SimpleEvent<Event::XML> > tracker("begin-transaction"); + EventTracker<SimpleEvent<Event::XML>> tracker("begin-transaction"); g_assert(doc != nullptr); doc->beginTransaction(); } -void -sp_repr_rollback (Inkscape::XML::Document *doc) +void sp_repr_rollback(Inkscape::XML::Document *doc) { - using Inkscape::Debug::SimpleEvent; - using Inkscape::Debug::EventTracker; using Inkscape::Debug::Event; + using Inkscape::Debug::EventTracker; + using Inkscape::Debug::SimpleEvent; - EventTracker<SimpleEvent<Event::XML> > tracker("rollback"); + EventTracker<SimpleEvent<Event::XML>> tracker("rollback"); g_assert(doc != nullptr); doc->rollback(); } -void -sp_repr_commit (Inkscape::XML::Document *doc) +void sp_repr_commit(Inkscape::XML::Document *doc) { - using Inkscape::Debug::SimpleEvent; - using Inkscape::Debug::EventTracker; using Inkscape::Debug::Event; + using Inkscape::Debug::EventTracker; + using Inkscape::Debug::SimpleEvent; - EventTracker<SimpleEvent<Event::XML> > tracker("commit"); + EventTracker<SimpleEvent<Event::XML>> tracker("commit"); g_assert(doc != nullptr); doc->commit(); } -Inkscape::XML::Event * -sp_repr_commit_undoable (Inkscape::XML::Document *doc) +Inkscape::XML::Event *sp_repr_commit_undoable(Inkscape::XML::Document *doc) { - using Inkscape::Debug::SimpleEvent; - using Inkscape::Debug::EventTracker; using Inkscape::Debug::Event; + using Inkscape::Debug::EventTracker; + using Inkscape::Debug::SimpleEvent; - EventTracker<SimpleEvent<Event::XML> > tracker("commit"); + EventTracker<SimpleEvent<Event::XML>> tracker("commit"); g_assert(doc != nullptr); return doc->commitUndoable(); @@ -84,67 +81,60 @@ sp_repr_commit_undoable (Inkscape::XML::Document *doc) namespace { -class LogPerformer : public Inkscape::XML::NodeObserver { +class LogPerformer : public Inkscape::XML::NodeObserver +{ public: typedef Inkscape::XML::Node Node; - static LogPerformer &instance() { + static LogPerformer &instance() + { static LogPerformer singleton; return singleton; } - void notifyChildAdded(Node &parent, Node &child, Node *ref) override { - parent.addChild(&child, ref); - } + void notifyChildAdded(Node &parent, Node &child, Node *ref) override { parent.addChild(&child, ref); } - void notifyChildRemoved(Node &parent, Node &child, Node */*old_ref*/) override { - parent.removeChild(&child); - } + void notifyChildRemoved(Node &parent, Node &child, Node * /*old_ref*/) override { parent.removeChild(&child); } - void notifyChildOrderChanged(Node &parent, Node &child, - Node */*old_ref*/, Node *new_ref) override + void notifyChildOrderChanged(Node &parent, Node &child, Node * /*old_ref*/, Node *new_ref) override { parent.changeOrder(&child, new_ref); } - void notifyAttributeChanged(Node &node, GQuark name, - Inkscape::Util::ptr_shared /*old_value*/, - Inkscape::Util::ptr_shared new_value) override + void notifyAttributeChanged(Node &node, GQuark name, Inkscape::Util::ptr_shared /*old_value*/, + Inkscape::Util::ptr_shared new_value) override { node.setAttribute(g_quark_to_string(name), new_value); } - void notifyContentChanged(Node &node, - Inkscape::Util::ptr_shared /*old_value*/, - Inkscape::Util::ptr_shared new_value) override + void notifyContentChanged(Node &node, Inkscape::Util::ptr_shared /*old_value*/, + Inkscape::Util::ptr_shared new_value) override { node.setContent(new_value); } - void notifyElementNameChanged(Node& node, GQuark /*old_value*/, GQuark new_value) override + void notifyElementNameChanged(Node &node, GQuark /*old_value*/, GQuark new_value) override { node.setCodeUnsafe(new_value); } }; -} +} // namespace -void Inkscape::XML::undo_log_to_observer( - Inkscape::XML::Event const *log, - Inkscape::XML::NodeObserver &observer -) { - for ( Event const *action = log ; action ; action = action->next ) { +void Inkscape::XML::undo_log_to_observer(Inkscape::XML::Event const *log, Inkscape::XML::NodeObserver &observer) +{ + for (Event const *action = log; action; action = action->next) { action->undoOne(observer); } } -void sp_repr_undo_log (Inkscape::XML::Event *log) +void sp_repr_undo_log(Inkscape::XML::Event *log) { - using Inkscape::Debug::SimpleEvent; - using Inkscape::Debug::EventTracker; using Inkscape::Debug::Event; + using Inkscape::Debug::EventTracker; + using Inkscape::Debug::SimpleEvent; - EventTracker<SimpleEvent<Event::XML> > tracker("undo-log"); + EventTracker<SimpleEvent<Event::XML>> tracker("undo-log"); if (log) { if (log->repr) { @@ -155,61 +145,51 @@ void sp_repr_undo_log (Inkscape::XML::Event *log) Inkscape::XML::undo_log_to_observer(log, LogPerformer::instance()); } -void Inkscape::XML::EventAdd::_undoOne( - Inkscape::XML::NodeObserver &observer -) const { +void Inkscape::XML::EventAdd::_undoOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyChildRemoved(*this->repr, *this->child, this->ref); } -void Inkscape::XML::EventDel::_undoOne( - Inkscape::XML::NodeObserver &observer -) const { +void Inkscape::XML::EventDel::_undoOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyChildAdded(*this->repr, *this->child, this->ref); } -void Inkscape::XML::EventChgAttr::_undoOne( - Inkscape::XML::NodeObserver &observer -) const { +void Inkscape::XML::EventChgAttr::_undoOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyAttributeChanged(*this->repr, this->key, this->newval, this->oldval); } -void Inkscape::XML::EventChgContent::_undoOne( - Inkscape::XML::NodeObserver &observer -) const { +void Inkscape::XML::EventChgContent::_undoOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyContentChanged(*this->repr, this->newval, this->oldval); } -void Inkscape::XML::EventChgOrder::_undoOne( - Inkscape::XML::NodeObserver &observer -) const { +void Inkscape::XML::EventChgOrder::_undoOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyChildOrderChanged(*this->repr, *this->child, this->newref, this->oldref); } -void Inkscape::XML::EventChgElementName::_undoOne( - Inkscape::XML::NodeObserver& observer -) const { +void Inkscape::XML::EventChgElementName::_undoOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyElementNameChanged(*this->repr, this->new_name, this->old_name); } -void Inkscape::XML::replay_log_to_observer( - Inkscape::XML::Event const *log, - Inkscape::XML::NodeObserver &observer -) { - List<Inkscape::XML::Event const &> reversed = - reverse_list<Inkscape::XML::Event::ConstIterator>(log, nullptr); - for ( ; reversed ; ++reversed ) { +void Inkscape::XML::replay_log_to_observer(Inkscape::XML::Event const *log, Inkscape::XML::NodeObserver &observer) +{ + List<Inkscape::XML::Event const &> reversed = reverse_list<Inkscape::XML::Event::ConstIterator>(log, nullptr); + for (; reversed; ++reversed) { reversed->replayOne(observer); } } -void -sp_repr_replay_log (Inkscape::XML::Event *log) +void sp_repr_replay_log(Inkscape::XML::Event *log) { - using Inkscape::Debug::SimpleEvent; - using Inkscape::Debug::EventTracker; using Inkscape::Debug::Event; + using Inkscape::Debug::EventTracker; + using Inkscape::Debug::SimpleEvent; - EventTracker<SimpleEvent<Event::XML> > tracker("replay-log"); + EventTracker<SimpleEvent<Event::XML>> tracker("replay-log"); if (log) { if (log->repr->document()) { @@ -220,56 +200,51 @@ sp_repr_replay_log (Inkscape::XML::Event *log) Inkscape::XML::replay_log_to_observer(log, LogPerformer::instance()); } -void Inkscape::XML::EventAdd::_replayOne( - Inkscape::XML::NodeObserver &observer -) const { +void Inkscape::XML::EventAdd::_replayOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyChildAdded(*this->repr, *this->child, this->ref); } -void Inkscape::XML::EventDel::_replayOne( - Inkscape::XML::NodeObserver &observer -) const { +void Inkscape::XML::EventDel::_replayOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyChildRemoved(*this->repr, *this->child, this->ref); } -void Inkscape::XML::EventChgAttr::_replayOne( - Inkscape::XML::NodeObserver &observer -) const { +void Inkscape::XML::EventChgAttr::_replayOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyAttributeChanged(*this->repr, this->key, this->oldval, this->newval); } -void Inkscape::XML::EventChgContent::_replayOne( - Inkscape::XML::NodeObserver &observer -) const { +void Inkscape::XML::EventChgContent::_replayOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyContentChanged(*this->repr, this->oldval, this->newval); } -void Inkscape::XML::EventChgOrder::_replayOne( - Inkscape::XML::NodeObserver &observer -) const { +void Inkscape::XML::EventChgOrder::_replayOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyChildOrderChanged(*this->repr, *this->child, this->oldref, this->newref); } -void Inkscape::XML::EventChgElementName::_replayOne( - Inkscape::XML::NodeObserver &observer -) const { +void Inkscape::XML::EventChgElementName::_replayOne(Inkscape::XML::NodeObserver &observer) const +{ observer.notifyElementNameChanged(*this->repr, this->new_name, this->old_name); } -Inkscape::XML::Event * -sp_repr_coalesce_log (Inkscape::XML::Event *a, Inkscape::XML::Event *b) +Inkscape::XML::Event *sp_repr_coalesce_log(Inkscape::XML::Event *a, Inkscape::XML::Event *b) { Inkscape::XML::Event *action; Inkscape::XML::Event **prev_ptr; - if (!b) return a; - if (!a) return b; + if (!b) + return a; + if (!a) + return b; /* find the earliest action in the second log */ /* (also noting the pointer that references it, so we can * replace it later) */ prev_ptr = &b; - for ( action = b ; action->next ; action = action->next ) { + for (action = b; action->next; action = action->next) { prev_ptr = &action->next; } @@ -282,8 +257,7 @@ sp_repr_coalesce_log (Inkscape::XML::Event *a, Inkscape::XML::Event *b) return b; } -void -sp_repr_free_log (Inkscape::XML::Event *log) +void sp_repr_free_log(Inkscape::XML::Event *log) { while (log) { Inkscape::XML::Event *action; @@ -295,33 +269,35 @@ sp_repr_free_log (Inkscape::XML::Event *log) namespace { -template <typename T> struct ActionRelations; +template <typename T> +struct ActionRelations; template <> -struct ActionRelations<Inkscape::XML::EventAdd> { +struct ActionRelations<Inkscape::XML::EventAdd> +{ typedef Inkscape::XML::EventDel Opposite; }; template <> -struct ActionRelations<Inkscape::XML::EventDel> { +struct ActionRelations<Inkscape::XML::EventDel> +{ typedef Inkscape::XML::EventAdd Opposite; }; template <typename A> -Inkscape::XML::Event *cancel_add_or_remove(A *action) { +Inkscape::XML::Event *cancel_add_or_remove(A *action) +{ typedef typename ActionRelations<A>::Opposite Opposite; - Opposite *opposite=dynamic_cast<Opposite *>(action->next); + Opposite *opposite = dynamic_cast<Opposite *>(action->next); bool OK = false; - if (opposite){ - if (opposite->repr == action->repr && - opposite->child == action->child && - opposite->ref == action->ref ) { + if (opposite) { + if (opposite->repr == action->repr && opposite->child == action->child && opposite->ref == action->ref) { OK = true; } } - if (OK){ - Inkscape::XML::Event *remaining=opposite->next; + if (OK) { + Inkscape::XML::Event *remaining = opposite->next; delete opposite; delete action; @@ -331,24 +307,25 @@ Inkscape::XML::Event *cancel_add_or_remove(A *action) { return action; } } -} +} // namespace -Inkscape::XML::Event *Inkscape::XML::EventAdd::_optimizeOne() { +Inkscape::XML::Event *Inkscape::XML::EventAdd::_optimizeOne() +{ return cancel_add_or_remove(this); } -Inkscape::XML::Event *Inkscape::XML::EventDel::_optimizeOne() { +Inkscape::XML::Event *Inkscape::XML::EventDel::_optimizeOne() +{ return cancel_add_or_remove(this); } -Inkscape::XML::Event *Inkscape::XML::EventChgAttr::_optimizeOne() { - Inkscape::XML::EventChgAttr *chg_attr=dynamic_cast<Inkscape::XML::EventChgAttr *>(this->next); +Inkscape::XML::Event *Inkscape::XML::EventChgAttr::_optimizeOne() +{ + Inkscape::XML::EventChgAttr *chg_attr = dynamic_cast<Inkscape::XML::EventChgAttr *>(this->next); /* consecutive chgattrs on the same key can be combined */ - if ( chg_attr) { - if ( chg_attr->repr == this->repr && - chg_attr->key == this->key ) - { + if (chg_attr) { + if (chg_attr->repr == this->repr && chg_attr->key == this->key) { /* replace our oldval with the prior action's */ this->oldval = chg_attr->oldval; @@ -361,12 +338,13 @@ Inkscape::XML::Event *Inkscape::XML::EventChgAttr::_optimizeOne() { return this; } -Inkscape::XML::Event *Inkscape::XML::EventChgContent::_optimizeOne() { - Inkscape::XML::EventChgContent *chg_content=dynamic_cast<Inkscape::XML::EventChgContent *>(this->next); +Inkscape::XML::Event *Inkscape::XML::EventChgContent::_optimizeOne() +{ + Inkscape::XML::EventChgContent *chg_content = dynamic_cast<Inkscape::XML::EventChgContent *>(this->next); /* consecutive content changes can be combined */ if (chg_content) { - if (chg_content->repr == this->repr ) { + if (chg_content->repr == this->repr) { /* replace our oldval with the prior action's */ this->oldval = chg_content->oldval; @@ -379,22 +357,22 @@ Inkscape::XML::Event *Inkscape::XML::EventChgContent::_optimizeOne() { return this; } -Inkscape::XML::Event *Inkscape::XML::EventChgOrder::_optimizeOne() { - Inkscape::XML::EventChgOrder *chg_order=dynamic_cast<Inkscape::XML::EventChgOrder *>(this->next); +Inkscape::XML::Event *Inkscape::XML::EventChgOrder::_optimizeOne() +{ + Inkscape::XML::EventChgOrder *chg_order = dynamic_cast<Inkscape::XML::EventChgOrder *>(this->next); /* consecutive chgorders for the same child may be combined or * canceled out */ bool OK = false; if (chg_order) { - if (chg_order->repr == this->repr && - chg_order->child == this->child ){ + if (chg_order->repr == this->repr && chg_order->child == this->child) { OK = true; } } - if (OK) { - if ( chg_order->oldref == this->newref ) { + if (OK) { + if (chg_order->oldref == this->newref) { /* cancel them out */ - Inkscape::XML::Event *after=chg_order->next; + Inkscape::XML::Event *after = chg_order->next; delete chg_order; delete this; @@ -415,8 +393,9 @@ Inkscape::XML::Event *Inkscape::XML::EventChgOrder::_optimizeOne() { } } -Inkscape::XML::Event* Inkscape::XML::EventChgElementName::_optimizeOne() { - auto next_chg_element_name = dynamic_cast<Inkscape::XML::EventChgElementName*>(this->next); +Inkscape::XML::Event *Inkscape::XML::EventChgElementName::_optimizeOne() +{ + auto next_chg_element_name = dynamic_cast<Inkscape::XML::EventChgElementName *>(this->next); if (next_chg_element_name && next_chg_element_name->repr == this->repr) { // Combine name changes to the same element. this->old_name = next_chg_element_name->old_name; @@ -428,33 +407,36 @@ Inkscape::XML::Event* Inkscape::XML::EventChgElementName::_optimizeOne() { namespace { -class LogPrinter : public Inkscape::XML::NodeObserver { +class LogPrinter : public Inkscape::XML::NodeObserver +{ public: typedef Inkscape::XML::Node Node; - static LogPrinter &instance() { + static LogPrinter &instance() + { static LogPrinter singleton; return singleton; } - static Glib::ustring node_to_string(Node const &node) { + static Glib::ustring node_to_string(Node const &node) + { Glib::ustring result; - char const *type_name=nullptr; + char const *type_name = nullptr; switch (node.type()) { - case Inkscape::XML::DOCUMENT_NODE: - type_name = "Document"; - break; - case Inkscape::XML::ELEMENT_NODE: - type_name = "Element"; - break; - case Inkscape::XML::TEXT_NODE: - type_name = "Text"; - break; - case Inkscape::XML::COMMENT_NODE: - type_name = "Comment"; - break; - default: - g_assert_not_reached(); + case Inkscape::XML::DOCUMENT_NODE: + type_name = "Document"; + break; + case Inkscape::XML::ELEMENT_NODE: + type_name = "Element"; + break; + case Inkscape::XML::TEXT_NODE: + type_name = "Text"; + break; + case Inkscape::XML::COMMENT_NODE: + type_name = "Comment"; + break; + default: + g_assert_not_reached(); } char buffer[40]; result.append("#<"); @@ -467,7 +449,8 @@ public: return result; } - static Glib::ustring ref_to_string(Node *ref) { + static Glib::ustring ref_to_string(Node *ref) + { if (ref) { return node_to_string(*ref); } else { @@ -475,34 +458,36 @@ public: } } - void notifyChildAdded(Node &parent, Node &child, Node *ref) override { - g_warning("Event: Added %s to %s after %s", node_to_string(parent).c_str(), node_to_string(child).c_str(), ref_to_string(ref).c_str()); + void notifyChildAdded(Node &parent, Node &child, Node *ref) override + { + g_warning("Event: Added %s to %s after %s", node_to_string(parent).c_str(), node_to_string(child).c_str(), + ref_to_string(ref).c_str()); } - void notifyChildRemoved(Node &parent, Node &child, Node */*ref*/) override { + void notifyChildRemoved(Node &parent, Node &child, Node * /*ref*/) override + { g_warning("Event: Removed %s from %s", node_to_string(parent).c_str(), node_to_string(child).c_str()); } - void notifyChildOrderChanged(Node &parent, Node &child, - Node */*old_ref*/, Node *new_ref) override + void notifyChildOrderChanged(Node &parent, Node &child, Node * /*old_ref*/, Node *new_ref) override { - g_warning("Event: Moved %s after %s in %s", node_to_string(child).c_str(), ref_to_string(new_ref).c_str(), node_to_string(parent).c_str()); + g_warning("Event: Moved %s after %s in %s", node_to_string(child).c_str(), ref_to_string(new_ref).c_str(), + node_to_string(parent).c_str()); } - void notifyAttributeChanged(Node &node, GQuark name, - Inkscape::Util::ptr_shared /*old_value*/, - Inkscape::Util::ptr_shared new_value) override + void notifyAttributeChanged(Node &node, GQuark name, Inkscape::Util::ptr_shared /*old_value*/, + Inkscape::Util::ptr_shared new_value) override { if (new_value) { - g_warning("Event: Set attribute %s to \"%s\" on %s", g_quark_to_string(name), new_value.pointer(), node_to_string(node).c_str()); + g_warning("Event: Set attribute %s to \"%s\" on %s", g_quark_to_string(name), new_value.pointer(), + node_to_string(node).c_str()); } else { g_warning("Event: Unset attribute %s on %s", g_quark_to_string(name), node_to_string(node).c_str()); } } - void notifyContentChanged(Node &node, - Inkscape::Util::ptr_shared /*old_value*/, - Inkscape::Util::ptr_shared new_value) override + void notifyContentChanged(Node &node, Inkscape::Util::ptr_shared /*old_value*/, + Inkscape::Util::ptr_shared new_value) override { if (new_value) { g_warning("Event: Set content of %s to \"%s\"", node_to_string(node).c_str(), new_value.pointer()); @@ -511,16 +496,16 @@ public: } } - void notifyElementNameChanged(Node& node, GQuark old_value, GQuark new_value) override + void notifyElementNameChanged(Node &node, GQuark old_value, GQuark new_value) override { - g_warning("Event: Changed name of %s from %s to %s\n", - node_to_string(node).c_str(), g_quark_to_string(old_value), g_quark_to_string(new_value)); + g_warning("Event: Changed name of %s from %s to %s\n", node_to_string(node).c_str(), + g_quark_to_string(old_value), g_quark_to_string(new_value)); } }; -} +} // namespace -void sp_repr_debug_print_log(Inkscape::XML::Event const *log) { +void sp_repr_debug_print_log(Inkscape::XML::Event const *log) +{ Inkscape::XML::replay_log_to_observer(log, LogPrinter::instance()); } - diff --git a/src/xml/event.h b/src/xml/event.h index 4256eea0d8661dfc830e0fbb42d5dc258012bc6f..9ca69dee3ea76ff5128f6a2e80ac74dd6379a0f4 100644 --- a/src/xml/event.h +++ b/src/xml/event.h @@ -15,11 +15,11 @@ typedef unsigned int GQuark; #include <glibmm/ustring.h> - #include <iterator> -#include "util/share.h" -#include "util/forward-pointer-iterator.h" + #include "inkgc/gc-managed.h" +#include "util/forward-pointer-iterator.h" +#include "util/share.h" #include "xml/node.h" namespace Inkscape { @@ -48,15 +48,14 @@ namespace XML { * Event logs are built by appending to the front, so by walking the list one iterates over * the events in reverse chronological order. */ -class Event -: public Inkscape::GC::Managed<Inkscape::GC::SCANNED, Inkscape::GC::MANUAL> +class Event : public Inkscape::GC::Managed<Inkscape::GC::SCANNED, Inkscape::GC::MANUAL> { -public: +public: virtual ~Event() = default; /** * @brief Pointer to the next event in the event chain - * + * * Note that the event this pointer points to actually happened before this event. * This is because the event log is built by appending to the front. */ @@ -74,10 +73,9 @@ public: */ Node *repr; - struct IteratorStrategy { - static Event const *next(Event const *action) { - return action->next; - } + struct IteratorStrategy + { + static Event const *next(Event const *action) { return action->next; } }; typedef Inkscape::Util::ForwardPointerIterator<Event, IteratorStrategy> Iterator; @@ -94,25 +92,24 @@ public: * This method notifies the specified observer of an action opposite to the one that * is described by this event. */ - void undoOne(NodeObserver &observer) const { - _undoOne(observer); - } + void undoOne(NodeObserver &observer) const { _undoOne(observer); } /** * @brief Replay this event to an observer * * This method notifies the specified event of the same action that it describes. */ - void replayOne(NodeObserver &observer) const { - _replayOne(observer); - } + void replayOne(NodeObserver &observer) const { _replayOne(observer); } protected: Event(Node *r, Event *n) - : next(n), serial(_next_serial++), repr(r) {} + : next(n) + , serial(_next_serial++) + , repr(r) + {} - virtual Event *_optimizeOne()=0; - virtual void _undoOne(NodeObserver &) const=0; - virtual void _replayOne(NodeObserver &) const=0; + virtual Event *_optimizeOne() = 0; + virtual void _undoOne(NodeObserver &) const = 0; + virtual void _replayOne(NodeObserver &) const = 0; private: static int _next_serial; @@ -121,10 +118,14 @@ private: /** * @brief Object representing child addition */ -class EventAdd : public Event { +class EventAdd : public Event +{ public: EventAdd(Node *repr, Node *c, Node *rr, Event *next) - : Event(repr, next), child(c), ref(rr) {} + : Event(repr, next) + , child(c) + , ref(rr) + {} /// The added child node Node *child; @@ -140,10 +141,14 @@ private: /** * @brief Object representing child removal */ -class EventDel : public Event { +class EventDel : public Event +{ public: EventDel(Node *repr, Node *c, Node *rr, Event *next) - : Event(repr, next), child(c), ref(rr) {} + : Event(repr, next) + , child(c) + , ref(rr) + {} /// The child node that was removed Node *child; @@ -159,14 +164,15 @@ private: /** * @brief Object representing attribute change */ -class EventChgAttr : public Event { +class EventChgAttr : public Event +{ public: - EventChgAttr(Node *repr, GQuark k, - Inkscape::Util::ptr_shared ov, - Inkscape::Util::ptr_shared nv, - Event *next) - : Event(repr, next), key(k), - oldval(ov), newval(nv) {} + EventChgAttr(Node *repr, GQuark k, Inkscape::Util::ptr_shared ov, Inkscape::Util::ptr_shared nv, Event *next) + : Event(repr, next) + , key(k) + , oldval(ov) + , newval(nv) + {} /// GQuark corresponding to the changed attribute's name GQuark key; @@ -184,13 +190,14 @@ private: /** * @brief Object representing content change */ -class EventChgContent : public Event { +class EventChgContent : public Event +{ public: - EventChgContent(Node *repr, - Inkscape::Util::ptr_shared ov, - Inkscape::Util::ptr_shared nv, - Event *next) - : Event(repr, next), oldval(ov), newval(nv) {} + EventChgContent(Node *repr, Inkscape::Util::ptr_shared ov, Inkscape::Util::ptr_shared nv, Event *next) + : Event(repr, next) + , oldval(ov) + , newval(nv) + {} /// Content of the node before the change Inkscape::Util::ptr_shared oldval; @@ -206,11 +213,15 @@ private: /** * @brief Object representing child order change */ -class EventChgOrder : public Event { +class EventChgOrder : public Event +{ public: EventChgOrder(Node *repr, Node *c, Node *orr, Node *nrr, Event *next) - : Event(repr, next), child(c), - oldref(orr), newref(nrr) {} + : Event(repr, next) + , child(c) + , oldref(orr) + , newref(nrr) + {} /// The node that was relocated in sibling order Node *child; @@ -228,10 +239,14 @@ private: /** * @brief Object representing element name change. */ -class EventChgElementName : public Event { +class EventChgElementName : public Event +{ public: - EventChgElementName(Node* repr, GQuark old_name, GQuark new_name, Event* next) - : Event(repr, next), old_name(old_name), new_name(new_name) {} + EventChgElementName(Node *repr, GQuark old_name, GQuark new_name, Event *next) + : Event(repr, next) + , old_name(old_name) + , new_name(new_name) + {} /// GQuark corresponding to the old element name. GQuark old_name; @@ -239,13 +254,13 @@ public: GQuark new_name; private: - Event* _optimizeOne() override; - void _undoOne(NodeObserver& observer) const override; - void _replayOne(NodeObserver& observer) const override; + Event *_optimizeOne() override; + void _undoOne(NodeObserver &observer) const override; + void _replayOne(NodeObserver &observer) const override; }; -} -} +} // namespace XML +} // namespace Inkscape #endif /* diff --git a/src/xml/helper-observer.cpp b/src/xml/helper-observer.cpp index 05161e9ca91f093e659bb2a3609c01d0c21eb8d6..22c627cf411659cf622f2a48924f1c8394b77101 100644 --- a/src/xml/helper-observer.cpp +++ b/src/xml/helper-observer.cpp @@ -26,19 +26,19 @@ SignalObserver::~SignalObserver() } // Add this observer to the SPObject and remove it from any previous object -void SignalObserver::set(SPObject* o) +void SignalObserver::set(SPObject *o) { - // XML Tree being used directly in this function in the following code - // while it shouldn't be - // Pointer to object is stored, so refcounting should be increased/decreased - if(_oldsel) { + // XML Tree being used directly in this function in the following code + // while it shouldn't be + // Pointer to object is stored, so refcounting should be increased/decreased + if (_oldsel) { if (_oldsel->getRepr()) { _oldsel->getRepr()->removeObserver(*this); } sp_object_unref(_oldsel); _oldsel = nullptr; } - if(o) { + if (o) { if (o->getRepr()) { o->getRepr()->addObserver(*this); sp_object_ref(o); @@ -47,31 +47,37 @@ void SignalObserver::set(SPObject* o) } } -void SignalObserver::notifyChildAdded(XML::Node&, XML::Node&, XML::Node*) -{ signal_changed()(); } +void SignalObserver::notifyChildAdded(XML::Node &, XML::Node &, XML::Node *) +{ + signal_changed()(); +} -void SignalObserver::notifyChildRemoved(XML::Node&, XML::Node&, XML::Node*) -{ signal_changed()(); } +void SignalObserver::notifyChildRemoved(XML::Node &, XML::Node &, XML::Node *) +{ + signal_changed()(); +} -void SignalObserver::notifyChildOrderChanged(XML::Node&, XML::Node&, XML::Node*, XML::Node*) -{ signal_changed()(); } +void SignalObserver::notifyChildOrderChanged(XML::Node &, XML::Node &, XML::Node *, XML::Node *) +{ + signal_changed()(); +} -void SignalObserver::notifyContentChanged(XML::Node&, Util::ptr_shared, Util::ptr_shared) -{} +void SignalObserver::notifyContentChanged(XML::Node &, Util::ptr_shared, Util::ptr_shared) {} -void SignalObserver::notifyAttributeChanged(XML::Node&, GQuark, Util::ptr_shared, Util::ptr_shared) -{ signal_changed()(); } +void SignalObserver::notifyAttributeChanged(XML::Node &, GQuark, Util::ptr_shared, Util::ptr_shared) +{ + signal_changed()(); +} -void SignalObserver::notifyElementNameChanged(Node&, GQuark, GQuark) +void SignalObserver::notifyElementNameChanged(Node &, GQuark, GQuark) { signal_changed()(); } -sigc::signal<void>& SignalObserver::signal_changed() +sigc::signal<void> &SignalObserver::signal_changed() { return _signal_changed; } -} //namespace XML -} //namespace Inkscape - +} // namespace XML +} // namespace Inkscape diff --git a/src/xml/helper-observer.h b/src/xml/helper-observer.h index 4bf172bd28cc8d1cda4e14e26ca50a99f792d7a8..7f4d3afe5cee14a36c09cda8a4492464dfadfa2a 100644 --- a/src/xml/helper-observer.h +++ b/src/xml/helper-observer.h @@ -24,27 +24,29 @@ namespace XML { class Node; // Very simple observer that just emits a signal if anything happens to a node -class SignalObserver : public NodeObserver { +class SignalObserver : public NodeObserver +{ public: SignalObserver(); ~SignalObserver() override; // Add this observer to the SPObject and remove it from any previous object - void set(SPObject* o); - void notifyChildAdded(Node&, Node&, Node*) override; - void notifyChildRemoved(Node&, Node&, Node*) override; - void notifyChildOrderChanged(Node&, Node&, Node*, Node*) override; - void notifyContentChanged(Node&, Util::ptr_shared, Util::ptr_shared) override; - void notifyAttributeChanged(Node&, GQuark, Util::ptr_shared, Util::ptr_shared) override; - void notifyElementNameChanged(Node&, GQuark, GQuark) override; - sigc::signal<void>& signal_changed(); + void set(SPObject *o); + void notifyChildAdded(Node &, Node &, Node *) override; + void notifyChildRemoved(Node &, Node &, Node *) override; + void notifyChildOrderChanged(Node &, Node &, Node *, Node *) override; + void notifyContentChanged(Node &, Util::ptr_shared, Util::ptr_shared) override; + void notifyAttributeChanged(Node &, GQuark, Util::ptr_shared, Util::ptr_shared) override; + void notifyElementNameChanged(Node &, GQuark, GQuark) override; + sigc::signal<void> &signal_changed(); + private: sigc::signal<void> _signal_changed; - SPObject* _oldsel; + SPObject *_oldsel; }; -} -} +} // namespace XML +} // namespace Inkscape #endif //#ifndef __XML_HELPER_OBSERVER__ diff --git a/src/xml/invalid-operation-exception.h b/src/xml/invalid-operation-exception.h index e43529e14052ef59bb950a3faf1a77857b8e2ad3..a014bc8f1017419209c83b552ef8847df42f6d56 100644 --- a/src/xml/invalid-operation-exception.h +++ b/src/xml/invalid-operation-exception.h @@ -20,16 +20,17 @@ namespace Inkscape { namespace XML { -class InvalidOperationException : public std::logic_error { +class InvalidOperationException : public std::logic_error +{ public: - InvalidOperationException(std::string const &message) : - std::logic_error(message) - { } + InvalidOperationException(std::string const &message) + : std::logic_error(message) + {} }; -} +} // namespace XML -} +} // namespace Inkscape #endif diff --git a/src/xml/log-builder.cpp b/src/xml/log-builder.cpp index 3fd831a9c00b8bd73e5ee8d3169446de5298f72a..9b161e5c4d58f5635062146fdcccdec801b4c5e6 100644 --- a/src/xml/log-builder.cpp +++ b/src/xml/log-builder.cpp @@ -11,64 +11,64 @@ */ #include "xml/log-builder.h" -#include "xml/event.h" + #include "xml/event-fns.h" +#include "xml/event.h" namespace Inkscape { namespace XML { -void LogBuilder::discard() { +void LogBuilder::discard() +{ sp_repr_free_log(_log); _log = nullptr; } -Event *LogBuilder::detach() { - Event *log=_log; +Event *LogBuilder::detach() +{ + Event *log = _log; _log = nullptr; return log; } -void LogBuilder::addChild(Node &node, Node &child, Node *prev) { +void LogBuilder::addChild(Node &node, Node &child, Node *prev) +{ _log = new Inkscape::XML::EventAdd(&node, &child, prev, _log); _log = _log->optimizeOne(); } -void LogBuilder::removeChild(Node &node, Node &child, Node *prev) { +void LogBuilder::removeChild(Node &node, Node &child, Node *prev) +{ _log = new Inkscape::XML::EventDel(&node, &child, prev, _log); _log = _log->optimizeOne(); } -void LogBuilder::setChildOrder(Node &node, Node &child, - Node *old_prev, Node *new_prev) +void LogBuilder::setChildOrder(Node &node, Node &child, Node *old_prev, Node *new_prev) { _log = new Inkscape::XML::EventChgOrder(&node, &child, old_prev, new_prev, _log); _log = _log->optimizeOne(); } -void LogBuilder::setContent(Node &node, - Util::ptr_shared old_content, - Util::ptr_shared new_content) +void LogBuilder::setContent(Node &node, Util::ptr_shared old_content, Util::ptr_shared new_content) { _log = new Inkscape::XML::EventChgContent(&node, old_content, new_content, _log); _log = _log->optimizeOne(); } -void LogBuilder::setAttribute(Node &node, GQuark name, - Util::ptr_shared old_value, - Util::ptr_shared new_value) +void LogBuilder::setAttribute(Node &node, GQuark name, Util::ptr_shared old_value, Util::ptr_shared new_value) { _log = new Inkscape::XML::EventChgAttr(&node, name, old_value, new_value, _log); _log = _log->optimizeOne(); } -void LogBuilder::setElementName(Node& node, GQuark old_name, GQuark new_name) +void LogBuilder::setElementName(Node &node, GQuark old_name, GQuark new_name) { _log = new Inkscape::XML::EventChgElementName(&node, old_name, new_name, _log); _log = _log->optimizeOne(); } -} -} +} // namespace XML +} // namespace Inkscape /* Local Variables: diff --git a/src/xml/log-builder.h b/src/xml/log-builder.h index bd7628bb25e173364b6147cef49cebda3228480f..7d42290b3fdfed4a51ef24101cff67bb952c0efd 100644 --- a/src/xml/log-builder.h +++ b/src/xml/log-builder.h @@ -29,9 +29,12 @@ class Node; * Calling detach() then returns the built log. Calling discard() will clear all the events * recorded so far. */ -class LogBuilder { +class LogBuilder +{ public: - LogBuilder() : _log(nullptr) {} + LogBuilder() + : _log(nullptr) + {} ~LogBuilder() { discard(); } /** @name Manipulate the recorded event log @@ -53,26 +56,21 @@ public: void removeChild(Node &node, Node &child, Node *prev); - void setChildOrder(Node &node, Node &child, - Node *old_prev, Node *new_prev); + void setChildOrder(Node &node, Node &child, Node *old_prev, Node *new_prev); - void setContent(Node &node, - Util::ptr_shared old_content, - Util::ptr_shared new_content); + void setContent(Node &node, Util::ptr_shared old_content, Util::ptr_shared new_content); - void setAttribute(Node &node, GQuark name, - Util::ptr_shared old_value, - Util::ptr_shared new_value); + void setAttribute(Node &node, GQuark name, Util::ptr_shared old_value, Util::ptr_shared new_value); - void setElementName(Node& node, GQuark old_name, GQuark new_name); + void setElementName(Node &node, GQuark old_name, GQuark new_name); /*@}*/ private: Event *_log; }; -} -} +} // namespace XML +} // namespace Inkscape #endif /* diff --git a/src/xml/node-event-vector.h b/src/xml/node-event-vector.h index 263751e59e135b7746f8f30fe3c054751b9170e3..b9af1763b17afa6e66dbc42671b1ebc967111035 100644 --- a/src/xml/node-event-vector.h +++ b/src/xml/node-event-vector.h @@ -21,28 +21,32 @@ namespace Inkscape { namespace XML { struct NodeEventVector; } -} +} // namespace Inkscape /** * @brief Generate events corresponding to the node's state * @deprecated Use Node::synthesizeEvents(NodeObserver &) instead */ -inline void sp_repr_synthesize_events (Inkscape::XML::Node *repr, const Inkscape::XML::NodeEventVector *vector, void* data) { - repr->synthesizeEvents(vector, data); +inline void sp_repr_synthesize_events(Inkscape::XML::Node *repr, const Inkscape::XML::NodeEventVector *vector, + void *data) +{ + repr->synthesizeEvents(vector, data); } /** * @brief Add a set of callbacks for node state changes and its associated data * @deprecated Use Node::addObserver() instead - */ -inline void sp_repr_add_listener (Inkscape::XML::Node *repr, const Inkscape::XML::NodeEventVector *vector, void* data) { - repr->addListener(vector, data); + */ +inline void sp_repr_add_listener(Inkscape::XML::Node *repr, const Inkscape::XML::NodeEventVector *vector, void *data) +{ + repr->addListener(vector, data); } /** * @brief Remove a set of callbacks based on associated data * @deprecated Use Node::removeObserver() instead */ -inline void sp_repr_remove_listener_by_data (Inkscape::XML::Node *repr, void* data) { - repr->removeListenerByData(data); +inline void sp_repr_remove_listener_by_data(Inkscape::XML::Node *repr, void *data) +{ + repr->removeListenerByData(data); } namespace Inkscape { @@ -52,17 +56,19 @@ namespace XML { * @brief Structure holding callbacks for node state changes * @deprecated Derive an observer object from the NodeObserver class instead */ -struct NodeEventVector { - /* Immediate signals */ - void (* child_added) (Node *repr, Node *child, Node *ref, void* data); - void (* child_removed) (Node *repr, Node *child, Node *ref, void* data); - void (* attr_changed) (Node *repr, char const *key, char const *oldval, char const *newval, bool is_interactive, void* data); - void (* content_changed) (Node *repr, char const *oldcontent, char const *newcontent, void * data); - void (* order_changed) (Node *repr, Node *child, Node *oldref, Node *newref, void* data); - void (* element_name_changed) (Node* repr, char const* oldname, char const* newname, void* data); +struct NodeEventVector +{ + /* Immediate signals */ + void (*child_added)(Node *repr, Node *child, Node *ref, void *data); + void (*child_removed)(Node *repr, Node *child, Node *ref, void *data); + void (*attr_changed)(Node *repr, char const *key, char const *oldval, char const *newval, bool is_interactive, + void *data); + void (*content_changed)(Node *repr, char const *oldcontent, char const *newcontent, void *data); + void (*order_changed)(Node *repr, Node *child, Node *oldref, Node *newref, void *data); + void (*element_name_changed)(Node *repr, char const *oldname, char const *newname, void *data); }; -} -} +} // namespace XML +} // namespace Inkscape #endif diff --git a/src/xml/node-fns.cpp b/src/xml/node-fns.cpp index c996cfd97630c342c2714a97e24270b6b0979585..492d76ebf9b54dcd454674bd2179ddf96678a50e 100644 --- a/src/xml/node-fns.cpp +++ b/src/xml/node-fns.cpp @@ -10,14 +10,15 @@ #ifdef HAVE_CONFIG_H #endif -#include <map> +#include "node-fns.h" + #include <cstring> -#include <string> #include <glib.h> // g_assert() +#include <map> +#include <string> -#include "xml/node-iterators.h" #include "util/find-if-before.h" -#include "node-fns.h" +#include "xml/node-iterators.h" namespace Inkscape { namespace XML { @@ -26,68 +27,69 @@ namespace XML { namespace { -bool id_permitted_internal(GQuark qname) { - char const *qname_s=g_quark_to_string(qname); - return !strncmp("svg:", qname_s, 4) || !strncmp("sodipodi:", qname_s, 9) || - !strncmp("inkscape:", qname_s, 9); +bool id_permitted_internal(GQuark qname) +{ + char const *qname_s = g_quark_to_string(qname); + return !strncmp("svg:", qname_s, 4) || !strncmp("sodipodi:", qname_s, 9) || !strncmp("inkscape:", qname_s, 9); } - -bool id_permitted_internal_memoized(GQuark qname) { +bool id_permitted_internal_memoized(GQuark qname) +{ typedef std::map<GQuark, bool> IdPermittedMap; static IdPermittedMap id_permitted_names; IdPermittedMap::iterator found; found = id_permitted_names.find(qname); - if ( found != id_permitted_names.end() ) { + if (found != id_permitted_names.end()) { return found->second; } else { - bool permitted=id_permitted_internal(qname); + bool permitted = id_permitted_internal(qname); id_permitted_names[qname] = permitted; return permitted; } } -} +} // namespace -bool id_permitted(Node const *node) { +bool id_permitted(Node const *node) +{ g_return_val_if_fail(node != nullptr, false); - if ( node->type() != ELEMENT_NODE ) { + if (node->type() != ELEMENT_NODE) { return false; } return id_permitted_internal_memoized((GQuark)node->code()); } -struct node_matches { - node_matches(Node const &n) : node(n) {} +struct node_matches +{ + node_matches(Node const &n) + : node(n) + {} bool operator()(Node const &other) { return &other == &node; } Node const &node; }; // documentation moved to header -Node *previous_node(Node *node) { +Node *previous_node(Node *node) +{ return node->prev(); using Inkscape::Algorithms::find_if_before; - if ( !node || !node->parent() ) { + if (!node || !node->parent()) { return nullptr; } - Node *previous=find_if_before<NodeSiblingIterator>( - node->parent()->firstChild(), nullptr, node_matches(*node) - ); + Node *previous = find_if_before<NodeSiblingIterator>(node->parent()->firstChild(), nullptr, node_matches(*node)); - g_assert(previous == nullptr - ? node->parent()->firstChild() == node - : previous->next() == node); + g_assert(previous == nullptr ? node->parent()->firstChild() == node : previous->next() == node); return previous; } -} -} +} // namespace XML +} // namespace Inkscape /* Local Variables: diff --git a/src/xml/node-fns.h b/src/xml/node-fns.h index 82724e21e6d46b8d1861b9595f2b6377e0f5c8a1..80be18f9aa265edd907cc00c2daee09a291d0122 100644 --- a/src/xml/node-fns.h +++ b/src/xml/node-fns.h @@ -28,11 +28,13 @@ bool id_permitted(Node const *node); * @return The next node in sibling order * @relates Inkscape::XML::Node */ -inline Node *next_node(Node *node) { - return ( node ? node->next() : nullptr ); +inline Node *next_node(Node *node) +{ + return (node ? node->next() : nullptr); } -inline Node const *next_node(Node const *node) { - return ( node ? node->next() : nullptr ); +inline Node const *next_node(Node const *node) +{ + return (node ? node->next() : nullptr); } //@} @@ -48,7 +50,8 @@ inline Node const *next_node(Node const *node) { * @relates Inkscape::XML::Node */ Node *previous_node(Node *node); -inline Node const *previous_node(Node const *node) { +inline Node const *previous_node(Node const *node) +{ return previous_node(const_cast<Node *>(node)); } //@} @@ -60,16 +63,18 @@ inline Node const *previous_node(Node const *node) { * @return The node's parent * @relates Inkscape::XML::Node */ -inline Node *parent_node(Node *node) { - return ( node ? node->parent() : nullptr ); +inline Node *parent_node(Node *node) +{ + return (node ? node->parent() : nullptr); } -inline Node const *parent_node(Node const *node) { - return ( node ? node->parent() : nullptr ); +inline Node const *parent_node(Node const *node) +{ + return (node ? node->parent() : nullptr); } //@} -} -} +} // namespace XML +} // namespace Inkscape #endif /* !SEEN_XML_NODE_FNS_H */ /* diff --git a/src/xml/node-iterators.h b/src/xml/node-iterators.h index 11c9450b00da27eb8d400e3ec95a29b975d8ab3c..2252b526f2eb793de1106d4cbdd103298ef2ab0e 100644 --- a/src/xml/node-iterators.h +++ b/src/xml/node-iterators.h @@ -19,36 +19,26 @@ namespace Inkscape { namespace XML { -struct NodeSiblingIteratorStrategy { - static Node const *next(Node const *node) { - return ( node ? node->next() : nullptr ); - } +struct NodeSiblingIteratorStrategy +{ + static Node const *next(Node const *node) { return (node ? node->next() : nullptr); } }; -struct NodeParentIteratorStrategy { - static Node const *next(Node const *node) { - return ( node ? node->parent() : nullptr ); - } +struct NodeParentIteratorStrategy +{ + static Node const *next(Node const *node) { return (node ? node->parent() : nullptr); } }; -typedef Inkscape::Util::ForwardPointerIterator<Node, - NodeSiblingIteratorStrategy> - NodeSiblingIterator; +typedef Inkscape::Util::ForwardPointerIterator<Node, NodeSiblingIteratorStrategy> NodeSiblingIterator; -typedef Inkscape::Util::ForwardPointerIterator<Node const, - NodeSiblingIteratorStrategy> - NodeConstSiblingIterator; +typedef Inkscape::Util::ForwardPointerIterator<Node const, NodeSiblingIteratorStrategy> NodeConstSiblingIterator; -typedef Inkscape::Util::ForwardPointerIterator<Node, - NodeParentIteratorStrategy> - NodeParentIterator; +typedef Inkscape::Util::ForwardPointerIterator<Node, NodeParentIteratorStrategy> NodeParentIterator; -typedef Inkscape::Util::ForwardPointerIterator<Node const, - NodeParentIteratorStrategy> - NodeConstParentIterator; +typedef Inkscape::Util::ForwardPointerIterator<Node const, NodeParentIteratorStrategy> NodeConstParentIterator; -} -} +} // namespace XML +} // namespace Inkscape #endif /* diff --git a/src/xml/node-observer.h b/src/xml/node-observer.h index e3173a8463f382d7148fe9be24a3fc0c4ccdaee1..55acc0c9c388be18d45dc8f00f49a4e9738ae8d0 100644 --- a/src/xml/node-observer.h +++ b/src/xml/node-observer.h @@ -47,10 +47,12 @@ class Node; * on construction and unregister itself on destruction. This will ensure there are * no dangling references. */ -class NodeObserver { +class NodeObserver +{ protected: /* the constructor is protected to prevent instantiation */ NodeObserver() = default; + public: virtual ~NodeObserver() = default; @@ -66,7 +68,8 @@ public: * @param child The newly added child node * @param prev The node after which the new child was inserted into the sibling order, or NULL */ - virtual void notifyChildAdded(Node &node, Node &child, Node *prev) { + virtual void notifyChildAdded(Node &node, Node &child, Node *prev) + { INK_UNUSED(node); INK_UNUSED(child); INK_UNUSED(prev); @@ -82,7 +85,8 @@ public: * @param child The removed child node * @param prev The node that was before the removed node in sibling order, or NULL */ - virtual void notifyChildRemoved(Node &node, Node &child, Node *prev) { + virtual void notifyChildRemoved(Node &node, Node &child, Node *prev) + { INK_UNUSED(node); INK_UNUSED(child); INK_UNUSED(prev); @@ -101,8 +105,8 @@ public: * @param old_prev The node that was before @c child prior to the order change * @param new_prev The node that is before @c child after the order change */ - virtual void notifyChildOrderChanged(Node &node, Node &child, - Node *old_prev, Node *new_prev) { + virtual void notifyChildOrderChanged(Node &node, Node &child, Node *old_prev, Node *new_prev) + { INK_UNUSED(node); INK_UNUSED(child); INK_UNUSED(old_prev); @@ -119,9 +123,8 @@ public: * @param old_content Old content of @c node * @param new_content New content of @c node */ - virtual void notifyContentChanged(Node &node, - Util::ptr_shared old_content, - Util::ptr_shared new_content) { + virtual void notifyContentChanged(Node &node, Util::ptr_shared old_content, Util::ptr_shared new_content) + { INK_UNUSED(node); INK_UNUSED(old_content); INK_UNUSED(new_content); @@ -137,9 +140,8 @@ public: * @param old_value Old value of the modified attribute * @param new_value New value of the modified attribute */ - virtual void notifyAttributeChanged(Node &node, GQuark name, - Util::ptr_shared old_value, - Util::ptr_shared new_value) { + virtual void notifyAttributeChanged(Node &node, GQuark name, Util::ptr_shared old_value, Util::ptr_shared new_value) + { INK_UNUSED(node); INK_UNUSED(name); INK_UNUSED(old_value); @@ -155,12 +157,12 @@ public: * @param old_name GQuark corresponding to the old element name. * @param new_name GQuark corresponding to the new element name. */ - virtual void notifyElementNameChanged(Node& node, GQuark old_name, GQuark new_name) { + virtual void notifyElementNameChanged(Node &node, GQuark old_name, GQuark new_name) + { INK_UNUSED(node); INK_UNUSED(old_name); INK_UNUSED(new_name); } - }; } // namespace XML diff --git a/src/xml/node.h b/src/xml/node.h index 62360aa90724163ca0c9a5eb7099197d025d38d5..a61072dfc021bdccde6130013bdafcefb61bdc16 100644 --- a/src/xml/node.h +++ b/src/xml/node.h @@ -14,27 +14,28 @@ #define SEEN_INKSCAPE_XML_NODE_H #include "gc-anchored.h" -#include "util/list.h" #include "util/const_char_ptr.h" +#include "util/list.h" namespace Inkscape { namespace XML { struct AttributeRecord; struct Document; -class Event; -class NodeObserver; +class Event; +class NodeObserver; struct NodeEventVector; /** * @brief Enumeration containing all supported node types. */ -enum NodeType { +enum NodeType +{ DOCUMENT_NODE, ///< Top-level document node. Do not confuse with the root node. - ELEMENT_NODE, ///< Regular element node, e.g. <group />. + ELEMENT_NODE, ///< Regular element node, e.g. <group />. TEXT_NODE, ///< Text node, e.g. "Some text" in <group>Some text</group> is represented by a text node. COMMENT_NODE, ///< Comment node, e.g. <!-- some comment --> - PI_NODE ///< Processing instruction node, e.g. <?xml version="1.0" encoding="utf-8" standalone="no"?> + PI_NODE ///< Processing instruction node, e.g. <?xml version="1.0" encoding="utf-8" standalone="no"?> }; // careful; GC::Anchored should only appear once in the inheritance @@ -70,7 +71,8 @@ enum NodeType { * @see Inkscape::XML::Document * @see Inkscape::XML::NodeObserver */ -class Node : public Inkscape::GC::Anchored { +class Node : public Inkscape::GC::Anchored +{ public: Node() = default; ~Node() override = default; @@ -84,7 +86,7 @@ public: * @brief Get the type of the node * @return NodeType enumeration member corresponding to the type of the node. */ - virtual NodeType type() const=0; + virtual NodeType type() const = 0; /** * @brief Get the name of the element node @@ -94,13 +96,13 @@ public: * * @return Name for element nodes, NULL for others */ - virtual char const *name() const=0; + virtual char const *name() const = 0; /** * @brief Get the integer code corresponding to the node's name * @return GQuark code corresponding to the name */ - virtual int code() const=0; - + virtual int code() const = 0; + /** * @brief Get the index of this node in parent's child order * @@ -109,14 +111,14 @@ public: * * @return The node's index, or 0 if the node does not have a parent */ - virtual unsigned position() const=0; + virtual unsigned position() const = 0; /** * @brief Get the number of children of this node * @return The number of children */ - virtual unsigned childCount() const=0; - + virtual unsigned childCount() const = 0; + /** * @brief Get the content of a text or comment node * @@ -125,8 +127,8 @@ public: * * @return The node's content */ - virtual char const *content() const=0; - + virtual char const *content() const = 0; + /** * @brief Get the string representation of a node's attribute * @@ -138,8 +140,8 @@ public: * * @param key The name of the node's attribute */ - virtual char const *attribute(char const *key) const=0; - + virtual char const *attribute(char const *key) const = 0; + /** * @brief Get a list of the node's attributes * @@ -149,7 +151,7 @@ public: * @todo This method should return std::map<Glib::Quark const, gchar const *> * or something similar with a custom allocator */ - virtual Inkscape::Util::List<AttributeRecord const> attributeList() const=0; + virtual Inkscape::Util::List<AttributeRecord const> attributeList() const = 0; /** * @brief Check whether this node has any attribute that matches a string @@ -162,15 +164,15 @@ public: * @param partial_name The string to match against all attributes * @return true if there is such an attribute, false otherwise */ - virtual bool matchAttributeName(char const *partial_name) const=0; + virtual bool matchAttributeName(char const *partial_name) const = 0; /*@}*/ - + /** * @name Modify the node * @{ */ - + /** * @brief Set the position of this node in parent's child order * @@ -178,8 +180,8 @@ public: * * @param pos The new position in parent's child order */ - virtual void setPosition(int pos)=0; - + virtual void setPosition(int pos) = 0; + /** * @brief Set the content of a text or comment node * @@ -187,8 +189,8 @@ public: * * @param value The node's new content */ - virtual void setContent(char const *value)=0; - + virtual void setContent(char const *value) = 0; + //@{ /** * @brief Change an attribute of this node @@ -200,8 +202,8 @@ public: * @param is_interactive Ignored */ - void setAttribute(Inkscape::Util::const_char_ptr key, - Inkscape::Util::const_char_ptr value) { + void setAttribute(Inkscape::Util::const_char_ptr key, Inkscape::Util::const_char_ptr value) + { this->setAttributeImpl(key.data(), value.data()); } @@ -212,22 +214,19 @@ public: * @param value The new value of the attribute * */ - void setAttributeOrRemoveIfEmpty(Inkscape::Util::const_char_ptr key, - Inkscape::Util::const_char_ptr value) { + void setAttributeOrRemoveIfEmpty(Inkscape::Util::const_char_ptr key, Inkscape::Util::const_char_ptr value) + { this->setAttributeImpl(key.data(), - (value.data() == nullptr || value.data()[0]=='\0') ? nullptr : value.data()); + (value.data() == nullptr || value.data()[0] == '\0') ? nullptr : value.data()); } - /** * @brief Remove an attribute of this node * * @param key Name of the attribute to delete * */ - void removeAttribute(Inkscape::Util::const_char_ptr key) { - this->setAttributeImpl(key.data(), nullptr); - } + void removeAttribute(Inkscape::Util::const_char_ptr key) { this->setAttributeImpl(key.data(), nullptr); } //@} /** @@ -239,22 +238,21 @@ public: * the name of this node */ virtual void setCodeUnsafe(int code) = 0; - + /*@}*/ - /** * @name Traverse the XML tree * @{ */ - + //@{ /** * @brief Get the node's associated document * @return The document to which the node belongs. Never NULL. */ - virtual Document *document()=0; - virtual Document const *document() const=0; + virtual Document *document() = 0; + virtual Document const *document() const = 0; //@} //@{ @@ -269,8 +267,8 @@ public: * * @return A pointer to the root element node, or NULL if the node is detached */ - virtual Node *root()=0; - virtual Node const *root() const=0; + virtual Node *root() = 0; + virtual Node const *root() const = 0; //@} //@{ @@ -281,8 +279,8 @@ public: * * @return Pointer to the parent, or NULL */ - virtual Node *parent()=0; - virtual Node const *parent() const=0; + virtual Node *parent() = 0; + virtual Node const *parent() const = 0; //@} //@{ @@ -296,10 +294,10 @@ public: * @return Pointer to the next sibling, or NULL * @see Inkscape::XML::previous_node() */ - virtual Node *next()=0; - virtual Node const *next() const=0; - virtual Node *prev()=0; - virtual Node const *prev() const=0; + virtual Node *next() = 0; + virtual Node const *next() const = 0; + virtual Node *prev() = 0; + virtual Node const *prev() const = 0; //@} //@{ @@ -310,10 +308,10 @@ public: * * @return Pointer to the first child, or NULL */ - virtual Node *firstChild()=0; - virtual Node const *firstChild() const=0; + virtual Node *firstChild() = 0; + virtual Node const *firstChild() const = 0; //@} - + //@{ /** * @brief Get the last child of this node @@ -322,10 +320,10 @@ public: * * @return Pointer to the last child, or NULL */ - virtual Node *lastChild()=0; - virtual Node const *lastChild() const=0; + virtual Node *lastChild() = 0; + virtual Node const *lastChild() const = 0; //@} - + //@{ /** * @brief Get the child of this node with a given index @@ -335,12 +333,12 @@ public: * @param index The zero-based index of the child to retrieve * @return Pointer to the appropriate child, or NULL */ - virtual Node *nthChild(unsigned index)=0; - virtual Node const *nthChild(unsigned index) const=0; + virtual Node *nthChild(unsigned index) = 0; + virtual Node const *nthChild(unsigned index) const = 0; //@} - + /*@}*/ - + /** * @name Manipulate the XML tree * @{ @@ -357,7 +355,7 @@ public: * @param doc The document in which the duplicate should be created * @return A pointer to the duplicated node */ - virtual Node *duplicate(Document *doc) const=0; + virtual Node *duplicate(Document *doc) const = 0; /** * @brief Insert another node as a child of this node @@ -368,7 +366,7 @@ public: * @param child The node to insert * @param after The node after which the inserted node should be placed, or NULL */ - virtual void addChild(Node *child, Node *after)=0; + virtual void addChild(Node *child, Node *after) = 0; /** * @brief Insert another node as a child of this node @@ -388,8 +386,8 @@ public: * @brief Append a node as the last child of this node * @param child The node to append */ - virtual void appendChild(Node *child)=0; - + virtual void appendChild(Node *child) = 0; + /** * @brief Remove a child of this node * @@ -400,8 +398,8 @@ public: * * @param child The child to remove */ - virtual void removeChild(Node *child)=0; - + virtual void removeChild(Node *child) = 0; + /** * @brief Move a given node in this node's child order * @@ -410,22 +408,21 @@ public: * @param child The node to move in the order * @param after The sibling node after which the moved node should be placed */ - virtual void changeOrder(Node *child, Node *after)=0; + virtual void changeOrder(Node *child, Node *after) = 0; - /** + /** * @brief Remove all elements that not in src node * @param src The node to check for elements into this node * @param key The attribute to use as the identity attribute */ - virtual void cleanOriginal(Node *src, gchar const *key)=0; - + virtual void cleanOriginal(Node *src, gchar const *key) = 0; - /** + /** * @brief Compare 2 nodes equality * @param other The other node to compare * @param recursive Recursive mode check */ - virtual bool equal(Node const *other, bool recursive)=0; + virtual bool equal(Node const *other, bool recursive) = 0; /** * @brief Merge all children of another node with the current * @@ -443,10 +440,9 @@ public: * @param key If clean callback to cleanOriginal */ - virtual void mergeFrom(Node const *src, char const *key, bool extension = false, bool clean = false)=0; - - /*@}*/ + virtual void mergeFrom(Node const *src, char const *key, bool extension = false, bool clean = false) = 0; + /*@}*/ /** * @name Notify observers about operations on the node @@ -463,12 +459,12 @@ public: * * @param observer The observer object */ - virtual void addObserver(NodeObserver &observer)=0; + virtual void addObserver(NodeObserver &observer) = 0; /** * @brief Remove an object from the list of observers * @param observer The object to be removed */ - virtual void removeObserver(NodeObserver &observer)=0; + virtual void removeObserver(NodeObserver &observer) = 0; /** * @brief Generate a sequence of events corresponding to the state of this node * @@ -479,7 +475,7 @@ public: * * @param observer The node observer to notify of the events */ - virtual void synthesizeEvents(NodeObserver &observer)=0; + virtual void synthesizeEvents(NodeObserver &observer) = 0; /** * @brief Add an object that will be notified of the changes to this node and its descendants @@ -491,42 +487,44 @@ public: * * @param observer The observer object */ - virtual void addSubtreeObserver(NodeObserver &observer)=0; - + virtual void addSubtreeObserver(NodeObserver &observer) = 0; + /** * @brief Remove an object from the subtree observers list * @param observer The object to be removed */ - virtual void removeSubtreeObserver(NodeObserver &observer)=0; + virtual void removeSubtreeObserver(NodeObserver &observer) = 0; /** * @brief Add a set node change callbacks with an associated data * @deprecated Use addObserver(NodeObserver &) instead */ - virtual void addListener(NodeEventVector const *vector, void *data)=0; + virtual void addListener(NodeEventVector const *vector, void *data) = 0; /** * @brief Remove a set of node change callbacks by their associated data * @deprecated Use removeObserver(NodeObserver &) instead */ - virtual void removeListenerByData(void *data)=0; + virtual void removeListenerByData(void *data) = 0; /** * @brief Generate a sequence of events corresponding to the state of this node * @deprecated Use synthesizeEvents(NodeObserver &) instead */ - virtual void synthesizeEvents(NodeEventVector const *vector, void *data)=0; + virtual void synthesizeEvents(NodeEventVector const *vector, void *data) = 0; + + virtual void recursivePrintTree(unsigned level) = 0; - virtual void recursivePrintTree(unsigned level)=0; - /*@}*/ protected: - Node(Node const &) : Anchored() {} + Node(Node const &) + : Anchored() + {} - virtual void setAttributeImpl(char const *key, char const *value)=0; + virtual void setAttributeImpl(char const *key, char const *value) = 0; }; -} -} +} // namespace XML +} // namespace Inkscape #endif /* diff --git a/src/xml/pi-node.h b/src/xml/pi-node.h index 2ec7942eab14ee6bdb2ad328d70f35635f6e8545..abc5427e0390823b9a644caf7e560e720f62541b 100644 --- a/src/xml/pi-node.h +++ b/src/xml/pi-node.h @@ -21,24 +21,26 @@ namespace XML { /** * @brief Processing instruction node, e.g. <?xml version="1.0" encoding="utf-8" standalone="no"?> */ -struct PINode : public SimpleNode { +struct PINode : public SimpleNode +{ PINode(GQuark target, Util::ptr_shared content, Document *doc) - : SimpleNode(target, doc) + : SimpleNode(target, doc) { setContent(content); } PINode(PINode const &other, Document *doc) - : SimpleNode(other, doc) {} + : SimpleNode(other, doc) + {} Inkscape::XML::NodeType type() const override { return Inkscape::XML::PI_NODE; } protected: - SimpleNode *_duplicate(Document* doc) const override { return new PINode(*this, doc); } + SimpleNode *_duplicate(Document *doc) const override { return new PINode(*this, doc); } }; -} +} // namespace XML -} +} // namespace Inkscape #endif /* diff --git a/src/xml/quote-test.h b/src/xml/quote-test.h index 7e08b8ddcb194d601f5c784961fbfcb8b89168f7..1f9bba21b0af5a0360fc7456677bb3e62669d89e 100644 --- a/src/xml/quote-test.h +++ b/src/xml/quote-test.h @@ -8,68 +8,51 @@ * Copyright (C) 2013 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cxxtest/TestSuite.h> -#include "streq.h" - - #include <cstring> +#include <cxxtest/TestSuite.h> #include <functional> #include "quote.h" +#include "streq.h" class XmlQuoteTest : public CxxTest::TestSuite { public: - - XmlQuoteTest() - { - } + XmlQuoteTest() {} virtual ~XmlQuoteTest() {} -// createSuite and destroySuite get us per-suite setup and teardown -// without us having to worry about static initialization order, etc. + // createSuite and destroySuite get us per-suite setup and teardown + // without us having to worry about static initialization order, etc. static XmlQuoteTest *createSuite() { return new XmlQuoteTest(); } - static void destroySuite( XmlQuoteTest *suite ) { delete suite; } + static void destroySuite(XmlQuoteTest *suite) { delete suite; } void testXmlQuotedStrlen() { - struct { + struct + { char const *s; size_t len; - } cases[] = { - {"", 0}, - {"x", 1}, - {"Foo", 3}, - {"\"", 6}, - {"&", 5}, - {"<", 4}, - {">", 4}, - {"a\"b", 8}, - {"a\"b<c>d;!@#$%^*(\\)?", 30} - }; - for(size_t i=0; i<G_N_ELEMENTS(cases); i++) { - TS_ASSERT_EQUALS( xml_quoted_strlen(cases[i].s) , cases[i].len ); + } cases[] = {{"", 0}, {"x", 1}, {"Foo", 3}, + {"\"", 6}, {"&", 5}, {"<", 4}, + {">", 4}, {"a\"b", 8}, {"a\"b<c>d;!@#$%^*(\\)?", 30}}; + for (size_t i = 0; i < G_N_ELEMENTS(cases); i++) { + TS_ASSERT_EQUALS(xml_quoted_strlen(cases[i].s), cases[i].len); } } void testXmlQuoteStrdup() { - struct { - char const * s1; - char const * s2; - } cases[] = { - {"", ""}, - {"x", "x"}, - {"Foo", "Foo"}, - {"\"", """}, - {"&", "&"}, - {"<", "<"}, - {">", ">"}, - {"a\"b<c>d;!@#$%^*(\\)?", "a"b<c>d;!@#$%^*(\\)?"} - }; - for(size_t i=0; i<G_N_ELEMENTS(cases); i++) { - char* str = xml_quote_strdup(cases[i].s1); - TS_ASSERT_RELATION( streq_rel, cases[i].s2, str ); + struct + { + char const *s1; + char const *s2; + } cases[] = {{"", ""}, {"x", "x"}, + {"Foo", "Foo"}, {"\"", """}, + {"&", "&"}, {"<", "<"}, + {">", ">"}, {"a\"b<c>d;!@#$%^*(\\)?", "a"b<c>d;!@#$%^*(\\)?"}}; + for (size_t i = 0; i < G_N_ELEMENTS(cases); i++) { + char *str = xml_quote_strdup(cases[i].s1); + TS_ASSERT_RELATION(streq_rel, cases[i].s2, str); g_free(str); } } diff --git a/src/xml/quote.cpp b/src/xml/quote.cpp index 148cb9d30afe48a72001655fde55bc5d20ef54bf..afdc3808e3bfe1b8ee1d72c0f3f554fa7d911be1 100644 --- a/src/xml/quote.cpp +++ b/src/xml/quote.cpp @@ -11,30 +11,32 @@ */ #include "xml/quote.h" + #include <cstring> #include <glib.h> /// Returns the length of the string after quoting the characters <code>"&<></code>. size_t xml_quoted_strlen(char const *val) { - if (!val) return 0; + if (!val) + return 0; size_t len = 0; for (char const *valp = val; *valp; ++valp) { switch (*valp) { - case '"': - len += 6; // " - break; - case '&': - len += 5; // & - break; - case '<': - case '>': - len += 4; // < or > - break; - default: - ++len; - break; + case '"': + len += 6; // " + break; + case '&': + len += 5; // & + break; + case '<': + case '>': + len += 4; // < or > + break; + default: + ++len; + break; } } return len; @@ -43,30 +45,30 @@ size_t xml_quoted_strlen(char const *val) char *xml_quote_strdup(char const *src) { size_t len = xml_quoted_strlen(src); - char *result = static_cast<char*>(g_malloc(len + 1)); + char *result = static_cast<char *>(g_malloc(len + 1)); char *resp = result; for (char const *srcp = src; *srcp; ++srcp) { - switch(*srcp) { - case '"': - strcpy(resp, """); - resp += 6; - break; - case '&': - strcpy(resp, "&"); - resp += 5; - break; - case '<': - strcpy(resp, "<"); - resp += 4; - break; - case '>': - strcpy(resp, ">"); - resp += 4; - break; - default: - *resp++ = *srcp; - break; + switch (*srcp) { + case '"': + strcpy(resp, """); + resp += 6; + break; + case '&': + strcpy(resp, "&"); + resp += 5; + break; + case '<': + strcpy(resp, "<"); + resp += 4; + break; + case '>': + strcpy(resp, ">"); + resp += 4; + break; + default: + *resp++ = *srcp; + break; } } *resp = 0; @@ -75,7 +77,6 @@ char *xml_quote_strdup(char const *src) // quote: ", &, <, > - /* Local Variables: mode:c++ diff --git a/src/xml/quote.h b/src/xml/quote.h index a2e5950d2024f2f0c4aafec4644883e8209183db..8bb8ca6d5335ddcc6ee7b8bc31a21517a5197c47 100644 --- a/src/xml/quote.h +++ b/src/xml/quote.h @@ -15,5 +15,4 @@ size_t xml_quoted_strlen(char const *val); char *xml_quote_strdup(char const *src); - #endif /* !SEEN_XML_QUOTE_H */ diff --git a/src/xml/rebase-hrefs.cpp b/src/xml/rebase-hrefs.cpp index b6f7e5505e15596cf3244396ec5bd3078beb7c98..bfa7ec7c8de4f7b808c5b8ac5a8a56f7da40e62c 100644 --- a/src/xml/rebase-hrefs.cpp +++ b/src/xml/rebase-hrefs.cpp @@ -8,21 +8,19 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "xml/rebase-hrefs.h" + #include <glibmm/convert.h> #include <glibmm/miscutils.h> #include <glibmm/uriutils.h> -#include "../document.h" /* Unfortunately there's a separate xml/document.h. */ -#include "streq.h" - +#include "../document.h" /* Unfortunately there's a separate xml/document.h. */ #include "io/dir-util.h" #include "io/sys.h" - #include "object/sp-object.h" #include "object/uri.h" - +#include "streq.h" #include "xml/node.h" -#include "xml/rebase-hrefs.h" using Inkscape::XML::AttributeRecord; @@ -33,7 +31,7 @@ static bool href_needs_rebasing(std::string const &href) { bool ret = true; - if ( href.empty() || (href[0] == '#') ) { + if (href.empty() || (href[0] == '#')) { ret = false; /* False (no change) is the right behaviour even when the base URI differs from the * document URI: RFC 3986 defines empty string relative URL as referring to the containing @@ -41,7 +39,7 @@ static bool href_needs_rebasing(std::string const &href) } else { /* Don't change data or http hrefs. */ std::string scheme = Glib::uri_parse_scheme(href); - if ( !scheme.empty() ) { + if (!scheme.empty()) { /* Assume it shouldn't be changed. This is probably wrong if the scheme is `file' * (or if the scheme of the new base is non-file, though I believe that never * happens at the time of writing), but that's rare, and we won't try too hard to @@ -56,16 +54,14 @@ static bool href_needs_rebasing(std::string const &href) } Inkscape::Util::List<AttributeRecord const> -Inkscape::XML::rebase_href_attrs(gchar const *const old_abs_base, - gchar const *const new_abs_base, +Inkscape::XML::rebase_href_attrs(gchar const *const old_abs_base, gchar const *const new_abs_base, Inkscape::Util::List<AttributeRecord const> attributes) { - using Inkscape::Util::List; using Inkscape::Util::cons; + using Inkscape::Util::List; using Inkscape::Util::ptr_shared; using Inkscape::Util::share_string; - if (old_abs_base == new_abs_base) { return attributes; } @@ -119,13 +115,13 @@ Inkscape::XML::rebase_href_attrs(gchar const *const old_abs_base, auto new_href = uri.str(baseuri.c_str()); - ret = cons(AttributeRecord(href_key, share_string(new_href.c_str())), ret); // Check if this is safe/copied or if it is only held. + ret = cons(AttributeRecord(href_key, share_string(new_href.c_str())), + ret); // Check if this is safe/copied or if it is only held. if (sp_absref) { /* We assume that if there wasn't previously a sodipodi:absref attribute * then we shouldn't create one. */ - ret = cons(AttributeRecord(absref_key, ( streq(abs_href.c_str(), sp_absref) - ? sp_absref - : share_string(abs_href.c_str()) )), + ret = cons(AttributeRecord(absref_key, + (streq(abs_href.c_str(), sp_absref) ? sp_absref : share_string(abs_href.c_str()))), ret); } @@ -213,7 +209,6 @@ void Inkscape::XML::rebase_hrefs(SPDocument *const doc, gchar const *const new_b doc->setDocumentBase(new_base); } - /* Local Variables: mode:c++ diff --git a/src/xml/rebase-hrefs.h b/src/xml/rebase-hrefs.h index afab3e4d2e069650ef02b22048f1b1a522d4e84d..a2ffa2d512ad729cde24409b88569e6d65097da6 100644 --- a/src/xml/rebase-hrefs.h +++ b/src/xml/rebase-hrefs.h @@ -31,22 +31,19 @@ void rebase_hrefs(SPDocument *doc, char const *new_base, bool spns); * * Note that old_abs_base and new_abs_base must each be non-NULL, absolute directory paths. */ -Inkscape::Util::List<AttributeRecord const> rebase_href_attrs( - char const *old_abs_base, - char const *new_abs_base, - Inkscape::Util::List<AttributeRecord const> attributes); - +Inkscape::Util::List<AttributeRecord const> rebase_href_attrs(char const *old_abs_base, char const *new_abs_base, + Inkscape::Util::List<AttributeRecord const> attributes); // /** // * . // * @return a non-empty replacement href if needed, empty otherwise. // */ -// std::string rebase_href_attrs( std::string const &oldAbsBase, std::string const &newAbsBase, gchar const *href, gchar const *absref = 0 ); +// std::string rebase_href_attrs( std::string const &oldAbsBase, std::string const &newAbsBase, gchar const *href, gchar +// const *absref = 0 ); } // namespace XML } // namespace Inkscape - #endif /* !REBASE_HREFS_H_SEEN */ /* diff --git a/src/xml/repr-action-test.h b/src/xml/repr-action-test.h index 29df246e2ff00b6ed4e9c6eb6489af935805f8de..68f84b25b29e16876b3a73225cf886f8e543074f 100644 --- a/src/xml/repr-action-test.h +++ b/src/xml/repr-action-test.h @@ -7,15 +7,14 @@ * Copyright (C) 2012 Authors * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cxxtest/TestSuite.h> - #include <cstdlib> +#include <cxxtest/TestSuite.h> #include <glib.h> -#include "repr.h" #include "event-fns.h" +#include "repr.h" -static void * const null_ptr = 0; +static void *const null_ptr = 0; class XmlReprActionTest : public CxxTest::TestSuite { @@ -23,7 +22,6 @@ class XmlReprActionTest : public CxxTest::TestSuite Inkscape::XML::Node *a, *b, *c, *root; public: - XmlReprActionTest() { Inkscape::GC::init(); @@ -37,21 +35,21 @@ public: } virtual ~XmlReprActionTest() {} -// createSuite and destroySuite get us per-suite setup and teardown -// without us having to worry about static initialization order, etc. + // createSuite and destroySuite get us per-suite setup and teardown + // without us having to worry about static initialization order, etc. static XmlReprActionTest *createSuite() { return new XmlReprActionTest(); } - static void destroySuite( XmlReprActionTest *suite ) { delete suite; } + static void destroySuite(XmlReprActionTest *suite) { delete suite; } void testRollbackOfNodeAddition() { sp_repr_begin_transaction(document); - TS_ASSERT_EQUALS(a->parent() , null_ptr); + TS_ASSERT_EQUALS(a->parent(), null_ptr); root->appendChild(a); - TS_ASSERT_EQUALS(a->parent() , root); + TS_ASSERT_EQUALS(a->parent(), root); sp_repr_rollback(document); - TS_ASSERT_EQUALS(a->parent() , null_ptr); + TS_ASSERT_EQUALS(a->parent(), null_ptr); } void testRollbackOfNodeRemoval() @@ -59,13 +57,13 @@ public: root->appendChild(a); sp_repr_begin_transaction(document); - TS_ASSERT_EQUALS(a->parent() , root); + TS_ASSERT_EQUALS(a->parent(), root); sp_repr_unparent(a); - TS_ASSERT_EQUALS(a->parent() , null_ptr); + TS_ASSERT_EQUALS(a->parent(), null_ptr); sp_repr_rollback(document); - TS_ASSERT_EQUALS(a->parent() , root); + TS_ASSERT_EQUALS(a->parent(), root); sp_repr_unparent(a); } @@ -77,19 +75,19 @@ public: root->appendChild(c); sp_repr_begin_transaction(document); - TS_ASSERT_EQUALS(a->next() , b); - TS_ASSERT_EQUALS(b->next() , c); - TS_ASSERT_EQUALS(c->next() , null_ptr); + TS_ASSERT_EQUALS(a->next(), b); + TS_ASSERT_EQUALS(b->next(), c); + TS_ASSERT_EQUALS(c->next(), null_ptr); root->changeOrder(b, c); - TS_ASSERT_EQUALS(a->next() , c); - TS_ASSERT_EQUALS(b->next() , null_ptr); - TS_ASSERT_EQUALS(c->next() , b); + TS_ASSERT_EQUALS(a->next(), c); + TS_ASSERT_EQUALS(b->next(), null_ptr); + TS_ASSERT_EQUALS(c->next(), b); sp_repr_rollback(document); - TS_ASSERT_EQUALS(a->next() , b); - TS_ASSERT_EQUALS(b->next() , c); - TS_ASSERT_EQUALS(c->next() , null_ptr); + TS_ASSERT_EQUALS(a->next(), b); + TS_ASSERT_EQUALS(b->next(), c); + TS_ASSERT_EQUALS(c->next(), null_ptr); sp_repr_unparent(a); sp_repr_unparent(b); diff --git a/src/xml/repr-css.cpp b/src/xml/repr-css.cpp index f1b1e0c203071681656dc215cf822adab27b60c3..6c5308a34f08cc7ec8dfa1da1e5d1cade12244b1 100644 --- a/src/xml/repr-css.cpp +++ b/src/xml/repr-css.cpp @@ -28,37 +28,39 @@ #define SP_REPR_CSS_C #include <cstring> -#include <string> -#include <sstream> - #include <glibmm/ustring.h> +#include <sstream> +#include <string> #include "3rdparty/libcroco/cr-declaration.h" - #include "svg/css-ostringstream.h" - #include "xml/repr.h" #include "xml/simple-document.h" #include "xml/sp-css-attr.h" using Inkscape::Util::List; using Inkscape::XML::AttributeRecord; -using Inkscape::XML::SimpleNode; +using Inkscape::XML::Document; using Inkscape::XML::Node; using Inkscape::XML::NodeType; -using Inkscape::XML::Document; +using Inkscape::XML::SimpleNode; -struct SPCSSAttrImpl : public SimpleNode, public SPCSSAttr { +struct SPCSSAttrImpl + : public SimpleNode + , public SPCSSAttr +{ public: SPCSSAttrImpl(Document *doc) - : SimpleNode(g_quark_from_static_string("css"), doc) {} + : SimpleNode(g_quark_from_static_string("css"), doc) + {} SPCSSAttrImpl(SPCSSAttrImpl const &other, Document *doc) - : SimpleNode(other, doc) {} + : SimpleNode(other, doc) + {} NodeType type() const override { return Inkscape::XML::ELEMENT_NODE; } protected: - SimpleNode *_duplicate(Document* doc) const override { return new SPCSSAttrImpl(*this, doc); } + SimpleNode *_duplicate(Document *doc) const override { return new SPCSSAttrImpl(*this, doc); } }; static void sp_repr_css_add_components(SPCSSAttr *css, Node const *repr, gchar const *attr); @@ -68,7 +70,7 @@ static void sp_repr_css_add_components(SPCSSAttr *css, Node const *repr, gchar c */ SPCSSAttr *sp_repr_css_attr_new() { - static Inkscape::XML::Document *attr_doc=nullptr; + static Inkscape::XML::Document *attr_doc = nullptr; if (!attr_doc) { attr_doc = new Inkscape::XML::SimpleDocument(); } @@ -81,7 +83,7 @@ SPCSSAttr *sp_repr_css_attr_new() void sp_repr_css_attr_unref(SPCSSAttr *css) { g_assert(css != nullptr); - Inkscape::GC::release((Node *) css); + Inkscape::GC::release((Node *)css); } /** @@ -100,7 +102,6 @@ SPCSSAttr *sp_repr_css_attr(Node const *repr, gchar const *attr) return css; } - /** * Attempt to parse the passed string as a hexadecimal RGB or RGBA color. * @param text The Glib::ustring to parse @@ -108,28 +109,28 @@ SPCSSAttr *sp_repr_css_attr(Node const *repr, gchar const *attr) */ SPCSSAttr *sp_repr_css_attr_parse_color_to_fill(const Glib::ustring &text) { -// TODO reuse existing code instead of replicating here. + // TODO reuse existing code instead of replicating here. Glib::ustring::size_type len = text.bytes(); char *str = const_cast<char *>(text.data()); bool attempt_alpha = false; - if ( !str || ( *str == '\0' ) ) { + if (!str || (*str == '\0')) { return nullptr; // this is OK due to boolean short-circuit } // those conditionals guard against parsing e.g. the string "fab" as "fab000" // (incomplete color) and "45fab71" as "45fab710" (incomplete alpha) - if ( *str == '#' ) { - if ( len < 7 ) { + if (*str == '#') { + if (len < 7) { return nullptr; } - if ( len >= 9 ) { + if (len >= 9) { attempt_alpha = true; } } else { - if ( len < 6 ) { + if (len < 6) { return nullptr; } - if ( len >= 8 ) { + if (len >= 8) { attempt_alpha = true; } } @@ -137,16 +138,16 @@ SPCSSAttr *sp_repr_css_attr_parse_color_to_fill(const Glib::ustring &text) unsigned int color = 0, alpha = 0xff; // skip a leading #, if present - if ( *str == '#' ) { + if (*str == '#') { ++str; } // try to parse first 6 digits int res = sscanf(str, "%6x", &color); - if ( res && ( res != EOF ) ) { - if (attempt_alpha) {// try to parse alpha if there's enough characters + if (res && (res != EOF)) { + if (attempt_alpha) { // try to parse alpha if there's enough characters sscanf(str + 6, "%2x", &alpha); - if ( !res || res == EOF ) { + if (!res || res == EOF) { alpha = 0xff; } } @@ -158,7 +159,7 @@ SPCSSAttr *sp_repr_css_attr_parse_color_to_fill(const Glib::ustring &text) g_snprintf(color_str, 16, "#%06x", color); sp_repr_css_set_property(color_css, "fill", color_str); - float opacity = static_cast<float>(alpha)/static_cast<float>(0xff); + float opacity = static_cast<float>(alpha) / static_cast<float>(0xff); if (opacity > 1.0) { opacity = 1.0; // safeguard } @@ -170,10 +171,9 @@ SPCSSAttr *sp_repr_css_attr_parse_color_to_fill(const Glib::ustring &text) return nullptr; } - /** * Adds an attribute to an existing SPCSAttr with the cascaded value including all parents. - */ + */ static void sp_repr_css_attr_inherited_recursive(SPCSSAttr *css, Node const *repr, gchar const *attr) { const Node *parent = repr->parent(); @@ -203,7 +203,7 @@ SPCSSAttr *sp_repr_css_attr_inherited(Node const *repr, gchar const *attr) /** * Adds components (style properties) to an existing SPCSAttr from the specified attribute's data * (nominally a style attribute). - * + * */ static void sp_repr_css_add_components(SPCSSAttr *css, Node const *repr, gchar const *attr) { @@ -225,9 +225,7 @@ char const *sp_repr_css_property(SPCSSAttr *css, gchar const *name, gchar const g_assert(name != nullptr); char const *attr = ((Node *)css)->attribute(name); - return ( attr == nullptr - ? defval - : attr ); + return (attr == nullptr ? defval : attr); } /** @@ -259,7 +257,6 @@ bool sp_repr_css_property_is_unset(SPCSSAttr *css, gchar const *name) return (attr && !strcmp(attr, "inkscape:unset")); } - /** * Set a style property to a new value (e.g. fill to #ffff00). */ @@ -268,7 +265,7 @@ void sp_repr_css_set_property(SPCSSAttr *css, gchar const *name, gchar const *va g_assert(css != nullptr); g_assert(name != nullptr); - ((Node *) css)->setAttribute(name, value); + ((Node *)css)->setAttribute(name, value); } /** @@ -279,7 +276,7 @@ void sp_repr_css_unset_property(SPCSSAttr *css, gchar const *name) g_assert(css != nullptr); g_assert(name != nullptr); - ((Node *) css)->setAttribute(name, "inkscape:unset"); + ((Node *)css)->setAttribute(name, "inkscape:unset"); } /** @@ -289,9 +286,9 @@ double sp_repr_css_double_property(SPCSSAttr *css, gchar const *name, double def { g_assert(css != nullptr); g_assert(name != nullptr); - + double val = defval; - sp_repr_get_double((Node *) css, name, &val); + sp_repr_get_double((Node *)css, name, &val); return val; } @@ -301,9 +298,7 @@ double sp_repr_css_double_property(SPCSSAttr *css, gchar const *name, double def void sp_repr_css_write_string(SPCSSAttr *css, Glib::ustring &str) { str.clear(); - for ( List<AttributeRecord const> iter = css->attributeList() ; - iter ; ++iter ) - { + for (List<AttributeRecord const> iter = css->attributeList(); iter; ++iter) { if (iter->value && !strcmp(iter->value, "inkscape:unset")) { continue; } @@ -344,12 +339,10 @@ void sp_repr_css_set(Node *repr, SPCSSAttr *css, gchar const *attr) */ void sp_repr_css_print(SPCSSAttr *css) { - for ( List<AttributeRecord const> iter = css->attributeList() ; - iter ; ++iter ) - { - gchar const * key = g_quark_to_string(iter->key); - gchar const * val = iter->value; - g_print("%s:\t%s\n",key,val); + for (List<AttributeRecord const> iter = css->attributeList(); iter; ++iter) { + gchar const *key = g_quark_to_string(iter->key); + gchar const *val = iter->value; + g_print("%s:\t%s\n", key, val); } } @@ -375,31 +368,30 @@ static void sp_repr_css_merge_from_decl(SPCSSAttr *css, CRDeclaration const *con { guchar *const str_value_unsigned = cr_term_to_string(decl->value); - Glib::ustring value( reinterpret_cast<gchar *>(str_value_unsigned ) ); + Glib::ustring value(reinterpret_cast<gchar *>(str_value_unsigned)); g_free(str_value_unsigned); Glib::ustring::size_type pos = 0; - while( (pos=value.find("\"",pos)) != Glib::ustring::npos) { - value.replace(pos,1,"'"); + while ((pos = value.find("\"", pos)) != Glib::ustring::npos) { + value.replace(pos, 1, "'"); ++pos; } Glib::ustring units; /* - * Problem with parsing of units em and ex, like font-size "1.2em" and "3.4ex" - * stringstream thinks they are in scientific "e" notation and fails - * Must be a better way using std::fixed, precision etc - * - * HACK for now is to strip off em and ex units and add them back at the end - */ + * Problem with parsing of units em and ex, like font-size "1.2em" and "3.4ex" + * stringstream thinks they are in scientific "e" notation and fails + * Must be a better way using std::fixed, precision etc + * + * HACK for now is to strip off em and ex units and add them back at the end + */ int le = value.length(); if (le > 2) { - units = value.substr(le-2, 2); + units = value.substr(le - 2, 2); if ((units == "em") || (units == "ex")) { - value = value.substr(0, le-2); - } - else { + value = value.substr(0, le - 2); + } else { units.clear(); } } @@ -408,7 +400,7 @@ static void sp_repr_css_merge_from_decl(SPCSSAttr *css, CRDeclaration const *con // CSSOStringStream is used here to write valid CSS (as in sp_style_write_string). This has // the additional benefit of respecting the numerical precision set in the SVG Output // preferences. We assume any numerical part comes first (if not, the whole string is copied). - std::stringstream ss( value ); + std::stringstream ss(value); double number = 0; std::string characters; std::string temp; @@ -417,19 +409,20 @@ static void sp_repr_css_merge_from_decl(SPCSSAttr *css, CRDeclaration const *con ss.clear(); ss.seekg(0); // work-around for a bug in libc++ (see lp:1300271) } - while( !(ss >> temp).eof() ) { + while (!(ss >> temp).eof()) { characters += temp; characters += " "; } characters += temp; Inkscape::CSSOStringStream os; - if( number_valid ) os << number; + if (number_valid) + os << number; os << characters; if (!units.empty()) { os << units; - //g_message("sp_repr_css_merge_from_decl looks like em or ex units %s --> %s", str_value, os.str().c_str()); + // g_message("sp_repr_css_merge_from_decl looks like em or ex units %s --> %s", str_value, os.str().c_str()); } - ((Node *) css)->setAttribute(decl->property->stryng->str, os.str()); + ((Node *)css)->setAttribute(decl->property->stryng->str, os.str()); } /** @@ -455,8 +448,8 @@ static void sp_repr_css_merge_from_decl_list(SPCSSAttr *css, CRDeclaration const void sp_repr_css_attr_add_from_string(SPCSSAttr *css, gchar const *p) { if (p != nullptr) { - CRDeclaration *const decl_list - = cr_declaration_parse_list_from_buf(reinterpret_cast<guchar const *>(p), CR_UTF_8); + CRDeclaration *const decl_list = + cr_declaration_parse_list_from_buf(reinterpret_cast<guchar const *>(p), CR_UTF_8); if (decl_list) { sp_repr_css_merge_from_decl_list(css, decl_list); cr_declaration_destroy(decl_list); @@ -498,11 +491,11 @@ void sp_repr_css_change_recursive(Node *repr, SPCSSAttr *css, gchar const *attr) /** * Return a new SPCSSAttr with all the properties found in the input SPCSSAttr unset. */ -SPCSSAttr* sp_repr_css_attr_unset_all(SPCSSAttr *css) +SPCSSAttr *sp_repr_css_attr_unset_all(SPCSSAttr *css) { - SPCSSAttr* css_unset = sp_repr_css_attr_new(); - for ( List<AttributeRecord const> iter = css->attributeList() ; iter ; ++iter ) { - sp_repr_css_set_property (css_unset, g_quark_to_string(iter->key), "inkscape:unset"); + SPCSSAttr *css_unset = sp_repr_css_attr_new(); + for (List<AttributeRecord const> iter = css->attributeList(); iter; ++iter) { + sp_repr_css_set_property(css_unset, g_quark_to_string(iter->key), "inkscape:unset"); } return css_unset; } diff --git a/src/xml/repr-io.cpp b/src/xml/repr-io.cpp index 9d18895a5d7767954e097beaff1187aa42329731..6315716577b6652b84870e877e9160dcda8ccb36 100644 --- a/src/xml/repr-io.cpp +++ b/src/xml/repr-io.cpp @@ -12,139 +12,128 @@ */ #include <cstring> -#include <string> -#include <stdexcept> - +#include <glibmm/miscutils.h> #include <libxml/parser.h> #include <libxml/xinclude.h> +#include <stdexcept> +#include <string> -#include "xml/repr.h" +#include "attribute-rel-util.h" +#include "attribute-sort-util.h" +#include "extension/extension.h" +#include "io/stream/gzipstream.h" +#include "io/stream/stringstream.h" +#include "io/stream/uristream.h" +#include "io/sys.h" +#include "preferences.h" #include "xml/attribute-record.h" #include "xml/rebase-hrefs.h" +#include "xml/repr.h" #include "xml/simple-document.h" #include "xml/text-node.h" -#include "io/sys.h" -#include "io/stream/stringstream.h" -#include "io/stream/gzipstream.h" -#include "io/stream/uristream.h" - -#include "extension/extension.h" - -#include "attribute-rel-util.h" -#include "attribute-sort-util.h" - -#include "preferences.h" - -#include <glibmm/miscutils.h> - using Inkscape::IO::Writer; -using Inkscape::Util::List; using Inkscape::Util::cons; +using Inkscape::Util::List; +using Inkscape::XML::AttributeRecord; using Inkscape::XML::Document; -using Inkscape::XML::SimpleDocument; using Inkscape::XML::Node; -using Inkscape::XML::AttributeRecord; using Inkscape::XML::rebase_href_attrs; +using Inkscape::XML::SimpleDocument; -Document *sp_repr_do_read (xmlDocPtr doc, const gchar *default_ns); -static Node *sp_repr_svg_read_node (Document *xml_doc, xmlNodePtr node, const gchar *default_ns, std::map<std::string, std::string> &prefix_map); -static gint sp_repr_qualified_name (gchar *p, gint len, xmlNsPtr ns, const xmlChar *name, const gchar *default_ns, std::map<std::string, std::string> &prefix_map); -static void sp_repr_write_stream_root_element(Node *repr, Writer &out, - bool add_whitespace, gchar const *default_ns, - int inlineattrs, int indent, - gchar const *old_href_abs_base, +Document *sp_repr_do_read(xmlDocPtr doc, const gchar *default_ns); +static Node *sp_repr_svg_read_node(Document *xml_doc, xmlNodePtr node, const gchar *default_ns, + std::map<std::string, std::string> &prefix_map); +static gint sp_repr_qualified_name(gchar *p, gint len, xmlNsPtr ns, const xmlChar *name, const gchar *default_ns, + std::map<std::string, std::string> &prefix_map); +static void sp_repr_write_stream_root_element(Node *repr, Writer &out, bool add_whitespace, gchar const *default_ns, + int inlineattrs, int indent, gchar const *old_href_abs_base, gchar const *new_href_abs_base); -static void sp_repr_write_stream_element(Node *repr, Writer &out, - gint indent_level, bool add_whitespace, - Glib::QueryQuark elide_prefix, - List<AttributeRecord const> attributes, - int inlineattrs, int indent, - gchar const *old_href_abs_base, +static void sp_repr_write_stream_element(Node *repr, Writer &out, gint indent_level, bool add_whitespace, + Glib::QueryQuark elide_prefix, List<AttributeRecord const> attributes, + int inlineattrs, int indent, gchar const *old_href_abs_base, gchar const *new_href_abs_base); - class XmlSource { public: XmlSource() - : filename(nullptr), - encoding(nullptr), - fp(nullptr), - firstFewLen(0), - LoadEntities(false), - cachedData(), - cachedPos(0), - instr(nullptr), - gzin(nullptr) + : filename(nullptr) + , encoding(nullptr) + , fp(nullptr) + , firstFewLen(0) + , LoadEntities(false) + , cachedData() + , cachedPos(0) + , instr(nullptr) + , gzin(nullptr) { - for (unsigned char & k : firstFew) - { - k=0; + for (unsigned char &k : firstFew) { + k = 0; } } virtual ~XmlSource() { close(); - if ( encoding ) { + if (encoding) { g_free(encoding); encoding = nullptr; } } - int setFile( char const * filename, bool load_entities ); + int setFile(char const *filename, bool load_entities); xmlDocPtr readXml(); - static int readCb( void * context, char * buffer, int len ); - static int closeCb( void * context ); + static int readCb(void *context, char *buffer, int len); + static int closeCb(void *context); - char const* getEncoding() const { return encoding; } - int read( char * buffer, int len ); + char const *getEncoding() const { return encoding; } + int read(char *buffer, int len); int close(); + private: - const char* filename; - char* encoding; - FILE* fp; + const char *filename; + char *encoding; + FILE *fp; unsigned char firstFew[4]; int firstFewLen; bool LoadEntities; // Checks for SYSTEM Entities (requires cached data) std::string cachedData; unsigned int cachedPos; - Inkscape::IO::FileInputStream* instr; - Inkscape::IO::GzipInputStream* gzin; + Inkscape::IO::FileInputStream *instr; + Inkscape::IO::GzipInputStream *gzin; }; -int XmlSource::setFile(char const *filename, bool load_entities=false) +int XmlSource::setFile(char const *filename, bool load_entities = false) { int retVal = -1; this->filename = filename; fp = Inkscape::IO::fopen_utf8name(filename, "r"); - if ( fp ) { + if (fp) { // First peek in the file to see what it is - memset( firstFew, 0, sizeof(firstFew) ); + memset(firstFew, 0, sizeof(firstFew)); - size_t some = fread( firstFew, 1, 4, fp ); - if ( fp ) { + size_t some = fread(firstFew, 1, 4, fp); + if (fp) { // first check for compression - if ( (some >= 2) && (firstFew[0] == 0x1f) && (firstFew[1] == 0x8b) ) { - //g_message(" the file being read is gzip'd. extract it"); + if ((some >= 2) && (firstFew[0] == 0x1f) && (firstFew[1] == 0x8b)) { + // g_message(" the file being read is gzip'd. extract it"); fclose(fp); fp = nullptr; fp = Inkscape::IO::fopen_utf8name(filename, "r"); instr = new Inkscape::IO::FileInputStream(fp); gzin = new Inkscape::IO::GzipInputStream(*instr); - memset( firstFew, 0, sizeof(firstFew) ); + memset(firstFew, 0, sizeof(firstFew)); some = 0; int single = 0; - while ( some < 4 && single >= 0 ) - { + while (some < 4 && single >= 0) { single = gzin->get(); - if ( single >= 0 ) { + if (single >= 0) { firstFew[some++] = 0x0ff & single; } else { break; @@ -153,19 +142,19 @@ int XmlSource::setFile(char const *filename, bool load_entities=false) } int encSkip = 0; - if ( (some >= 2) &&(firstFew[0] == 0xfe) && (firstFew[1] == 0xff) ) { + if ((some >= 2) && (firstFew[0] == 0xfe) && (firstFew[1] == 0xff)) { encoding = g_strdup("UTF-16BE"); encSkip = 2; - } else if ( (some >= 2) && (firstFew[0] == 0xff) && (firstFew[1] == 0xfe) ) { + } else if ((some >= 2) && (firstFew[0] == 0xff) && (firstFew[1] == 0xfe)) { encoding = g_strdup("UTF-16LE"); encSkip = 2; - } else if ( (some >= 3) && (firstFew[0] == 0xef) && (firstFew[1] == 0xbb) && (firstFew[2] == 0xbf) ) { + } else if ((some >= 3) && (firstFew[0] == 0xef) && (firstFew[1] == 0xbb) && (firstFew[2] == 0xbf)) { encoding = g_strdup("UTF-8"); encSkip = 3; } - if ( encSkip ) { - memmove( firstFew, firstFew + encSkip, (some - encSkip) ); + if (encSkip) { + memmove(firstFew, firstFew + encSkip, (some - encSkip)); some -= encSkip; } @@ -173,15 +162,16 @@ int XmlSource::setFile(char const *filename, bool load_entities=false) retVal = 0; // no error } } - if(load_entities) { + if (load_entities) { this->cachedData = std::string(""); this->cachedPos = 0; // First get data from file in typical way (cache it all) - char *buffer = new char [4096]; - while(true) { + char *buffer = new char[4096]; + while (true) { int len = this->read(buffer, 4096); - if(len <= 0) break; + if (len <= 0) + break; buffer[len] = 0; this->cachedData += buffer; } @@ -191,16 +181,15 @@ int XmlSource::setFile(char const *filename, bool load_entities=false) GMatchInfo *info; gint start, end; - GRegex *regex = g_regex_new( - "<!ENTITY\\s+[^>\\s]+\\s+(SYSTEM|PUBLIC\\s+\"[^>\"]+\")\\s+\"[^>\"]+\"\\s*>", - G_REGEX_CASELESS, G_REGEX_MATCH_NEWLINE_ANY, nullptr); + GRegex *regex = g_regex_new("<!ENTITY\\s+[^>\\s]+\\s+(SYSTEM|PUBLIC\\s+\"[^>\"]+\")\\s+\"[^>\"]+\"\\s*>", + G_REGEX_CASELESS, G_REGEX_MATCH_NEWLINE_ANY, nullptr); - g_regex_match (regex, this->cachedData.c_str(), G_REGEX_MATCH_NEWLINE_ANY, &info); + g_regex_match(regex, this->cachedData.c_str(), G_REGEX_MATCH_NEWLINE_ANY, &info); - while (g_match_info_matches (info)) { - if (g_match_info_fetch_pos (info, 1, &start, &end)) + while (g_match_info_matches(info)) { + if (g_match_info_fetch_pos(info, 1, &start, &end)) this->cachedData.erase(start, end - start); - g_match_info_next (info, nullptr); + g_match_info_next(info, nullptr); } g_match_info_free(info); g_regex_unref(regex); @@ -216,13 +205,14 @@ xmlDocPtr XmlSource::readXml() Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool allowNetAccess = prefs->getBool("/options/externalresources/xml/allow_net_access", false); - if (!allowNetAccess) parse_options |= XML_PARSE_NONET; + if (!allowNetAccess) + parse_options |= XML_PARSE_NONET; // Allow NOENT only if we're filtering out SYSTEM and PUBLIC entities - if (LoadEntities) parse_options |= XML_PARSE_NOENT; + if (LoadEntities) + parse_options |= XML_PARSE_NOENT; - auto doc = xmlReadIO( readCb, closeCb, this, - filename, getEncoding(), parse_options); + auto doc = xmlReadIO(readCb, closeCb, this, filename, getEncoding(), parse_options); if (doc && doc->properties && xmlXIncludeProcessFlags(doc, XML_PARSE_NOXINCNODE) < 0) { g_warning("XInclude processing failed for %s", filename); @@ -231,32 +221,32 @@ xmlDocPtr XmlSource::readXml() return doc; } -int XmlSource::readCb( void * context, char * buffer, int len ) +int XmlSource::readCb(void *context, char *buffer, int len) { int retVal = -1; - if ( context ) { - XmlSource* self = static_cast<XmlSource*>(context); - retVal = self->read( buffer, len ); + if (context) { + XmlSource *self = static_cast<XmlSource *>(context); + retVal = self->read(buffer, len); } return retVal; } -int XmlSource::closeCb(void * context) +int XmlSource::closeCb(void *context) { - if ( context ) { - XmlSource* self = static_cast<XmlSource*>(context); + if (context) { + XmlSource *self = static_cast<XmlSource *>(context); self->close(); } return 0; } -int XmlSource::read( char *buffer, int len ) +int XmlSource::read(char *buffer, int len) { int retVal = 0; size_t got = 0; - if ( LoadEntities ) { + if (LoadEntities) { if (cachedPos >= cachedData.length()) { return -1; } else { @@ -264,32 +254,31 @@ int XmlSource::read( char *buffer, int len ) cachedPos += retVal; return retVal; // Do NOT continue. } - } else if ( firstFewLen > 0 ) { + } else if (firstFewLen > 0) { int some = (len < firstFewLen) ? len : firstFewLen; - memcpy( buffer, firstFew, some ); - if ( len < firstFewLen ) { - memmove( firstFew, firstFew + some, (firstFewLen - some) ); + memcpy(buffer, firstFew, some); + if (len < firstFewLen) { + memmove(firstFew, firstFew + some, (firstFewLen - some)); } firstFewLen -= some; got = some; - } else if ( gzin ) { + } else if (gzin) { int single = 0; - while ( (static_cast<int>(got) < len) && (single >= 0) ) - { + while ((static_cast<int>(got) < len) && (single >= 0)) { single = gzin->get(); - if ( single >= 0 ) { + if (single >= 0) { buffer[got++] = 0x0ff & single; } else { break; } } } else { - got = fread( buffer, 1, len, fp ); + got = fread(buffer, 1, len, fp); } - if ( feof(fp) ) { + if (feof(fp)) { retVal = got; - } else if ( ferror(fp) ) { + } else if (ferror(fp)) { retVal = -1; } else { retVal = got; @@ -300,18 +289,18 @@ int XmlSource::read( char *buffer, int len ) int XmlSource::close() { - if ( gzin ) { + if (gzin) { gzin->close(); delete gzin; gzin = nullptr; } - if ( instr ) { + if (instr) { instr->close(); fp = nullptr; delete instr; instr = nullptr; } - if ( fp ) { + if (fp) { fclose(fp); fp = nullptr; } @@ -322,10 +311,10 @@ int XmlSource::close() * Reads XML from a file, and returns the Document. * The default namespace can also be specified, if desired. */ -Document *sp_repr_read_file (const gchar * filename, const gchar *default_ns) +Document *sp_repr_read_file(const gchar *filename, const gchar *default_ns) { xmlDocPtr doc = nullptr; - Document * rdoc = nullptr; + Document *rdoc = nullptr; xmlSubstituteEntitiesDefault(1); @@ -341,9 +330,9 @@ Document *sp_repr_read_file (const gchar * filename, const gchar *default_ns) // TODO: bulia, please look over gsize bytesRead = 0; gsize bytesWritten = 0; - GError* error = nullptr; + GError *error = nullptr; // TODO: need to replace with our own fopen and reading - gchar* localFilename = g_filename_from_utf8(filename, -1, &bytesRead, &bytesWritten, &error); + gchar *localFilename = g_filename_from_utf8(filename, -1, &bytesRead, &bytesWritten, &error); g_return_val_if_fail(localFilename != nullptr, NULL); Inkscape::IO::dump_fopen_call(filename, "N"); @@ -377,25 +366,27 @@ Document *sp_repr_read_file (const gchar * filename, const gchar *default_ns) /** * Reads and parses XML from a buffer, returning it as an Document */ -Document *sp_repr_read_mem (const gchar * buffer, gint length, const gchar *default_ns) +Document *sp_repr_read_mem(const gchar *buffer, gint length, const gchar *default_ns) { xmlDocPtr doc; - Document * rdoc; + Document *rdoc; xmlSubstituteEntitiesDefault(1); - g_return_val_if_fail (buffer != nullptr, NULL); + g_return_val_if_fail(buffer != nullptr, NULL); int parser_options = XML_PARSE_HUGE | XML_PARSE_RECOVER; - parser_options |= XML_PARSE_NONET; // TODO: should we allow network access? - // proper solution would be to check the preference "/options/externalresources/xml/allow_net_access" - // as done in XmlSource::readXml which gets called by the analogous sp_repr_read_file() - // but sp_repr_read_mem() seems to be called in locations where Inkscape::Preferences::get() fails badly - doc = xmlReadMemory (const_cast<gchar *>(buffer), length, nullptr, nullptr, parser_options); - - rdoc = sp_repr_do_read (doc, default_ns); + parser_options |= + XML_PARSE_NONET; // TODO: should we allow network access? + // proper solution would be to check the preference + // "/options/externalresources/xml/allow_net_access" as done in XmlSource::readXml which gets + // called by the analogous sp_repr_read_file() but sp_repr_read_mem() seems to be called in + // locations where Inkscape::Preferences::get() fails badly + doc = xmlReadMemory(const_cast<gchar *>(buffer), length, nullptr, nullptr, parser_options); + + rdoc = sp_repr_do_read(doc, default_ns); if (doc) { - xmlFreeDoc (doc); + xmlFreeDoc(doc); } return rdoc; } @@ -403,36 +394,35 @@ Document *sp_repr_read_mem (const gchar * buffer, gint length, const gchar *defa /** * Reads and parses XML from a buffer, returning it as an Document */ -Document *sp_repr_read_buf (const Glib::ustring &buf, const gchar *default_ns) +Document *sp_repr_read_buf(const Glib::ustring &buf, const gchar *default_ns) { return sp_repr_read_mem(buf.c_str(), buf.size(), default_ns); } - namespace Inkscape { -struct compare_quark_ids { - bool operator()(Glib::QueryQuark const &a, Glib::QueryQuark const &b) const { - return a.id() < b.id(); - } +struct compare_quark_ids +{ + bool operator()(Glib::QueryQuark const &a, Glib::QueryQuark const &b) const { return a.id() < b.id(); } }; -} +} // namespace Inkscape namespace { typedef std::map<Glib::QueryQuark, Glib::QueryQuark, Inkscape::compare_quark_ids> PrefixMap; -Glib::QueryQuark qname_prefix(Glib::QueryQuark qname) { +Glib::QueryQuark qname_prefix(Glib::QueryQuark qname) +{ static PrefixMap prefix_map; PrefixMap::iterator iter = prefix_map.find(qname); - if ( iter != prefix_map.end() ) { + if (iter != prefix_map.end()) { return (*iter).second; } else { - gchar const *name_string=g_quark_to_string(qname); - gchar const *prefix_end=strchr(name_string, ':'); + gchar const *name_string = g_quark_to_string(qname); + gchar const *prefix_end = strchr(name_string, ':'); if (prefix_end) { - Glib::Quark prefix=Glib::ustring(name_string, prefix_end); + Glib::Quark prefix = Glib::ustring(name_string, prefix_end); prefix_map.insert(PrefixMap::value_type(qname, prefix)); return prefix; } else { @@ -441,35 +431,36 @@ Glib::QueryQuark qname_prefix(Glib::QueryQuark qname) { } } -} +} // namespace namespace { -void promote_to_namespace(Node *repr, const gchar *prefix) { - if ( repr->type() == Inkscape::XML::ELEMENT_NODE ) { +void promote_to_namespace(Node *repr, const gchar *prefix) +{ + if (repr->type() == Inkscape::XML::ELEMENT_NODE) { GQuark code = repr->code(); if (!qname_prefix(code).id()) { gchar *svg_name = g_strconcat(prefix, ":", g_quark_to_string(code), NULL); repr->setCodeUnsafe(g_quark_from_string(svg_name)); g_free(svg_name); } - for ( Node *child = repr->firstChild() ; child ; child = child->next() ) { + for (Node *child = repr->firstChild(); child; child = child->next()) { promote_to_namespace(child, prefix); } } } -} +} // namespace /** * Reads in a XML file to create a Document */ -Document *sp_repr_do_read (xmlDocPtr doc, const gchar *default_ns) +Document *sp_repr_do_read(xmlDocPtr doc, const gchar *default_ns) { if (doc == nullptr) { return nullptr; } - xmlNodePtr node=xmlDocGetRootElement (doc); + xmlNodePtr node = xmlDocGetRootElement(doc); if (node == nullptr) { return nullptr; } @@ -478,10 +469,10 @@ Document *sp_repr_do_read (xmlDocPtr doc, const gchar *default_ns) Document *rdoc = new Inkscape::XML::SimpleDocument(); - Node *root=nullptr; - for ( node = doc->children ; node != nullptr ; node = node->next ) { + Node *root = nullptr; + for (node = doc->children; node != nullptr; node = node->next) { if (node->type == XML_ELEMENT_NODE) { - Node *repr=sp_repr_svg_read_node(rdoc, node, default_ns, prefix_map); + Node *repr = sp_repr_svg_read_node(rdoc, node, default_ns, prefix_map); rdoc->appendChild(repr); Inkscape::GC::release(repr); @@ -491,8 +482,8 @@ Document *sp_repr_do_read (xmlDocPtr doc, const gchar *default_ns) root = nullptr; break; } - } else if ( node->type == XML_COMMENT_NODE || node->type == XML_PI_NODE ) { - Node *repr=sp_repr_svg_read_node(rdoc, node, default_ns, prefix_map); + } else if (node->type == XML_COMMENT_NODE || node->type == XML_PI_NODE) { + Node *repr = sp_repr_svg_read_node(rdoc, node, default_ns, prefix_map); rdoc->appendChild(repr); Inkscape::GC::release(repr); } @@ -501,24 +492,23 @@ Document *sp_repr_do_read (xmlDocPtr doc, const gchar *default_ns) if (root != nullptr) { /* promote elements of some XML documents that don't use namespaces * into their default namespace */ - if ( default_ns && !strchr(root->name(), ':') ) { - if ( !strcmp(default_ns, SP_SVG_NS_URI) ) { + if (default_ns && !strchr(root->name(), ':')) { + if (!strcmp(default_ns, SP_SVG_NS_URI)) { promote_to_namespace(root, "svg"); } - if ( !strcmp(default_ns, INKSCAPE_EXTENSION_URI) ) { + if (!strcmp(default_ns, INKSCAPE_EXTENSION_URI)) { promote_to_namespace(root, INKSCAPE_EXTENSION_NS_NC); } } - // Clean unnecessary attributes and style properties from SVG documents. (Controlled by // preferences.) Note: internal Inkscape svg files will also be cleaned (filters.svg, // icons.svg). How can one tell if a file is internal? - if ( !strcmp(root->name(), "svg:svg" ) ) { + if (!strcmp(root->name(), "svg:svg")) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool clean = prefs->getBool("/options/svgoutput/check_on_reading"); - if( clean ) { - sp_attribute_clean_tree( root ); + if (clean) { + sp_attribute_clean_tree(root); } } } @@ -526,38 +516,37 @@ Document *sp_repr_do_read (xmlDocPtr doc, const gchar *default_ns) return rdoc; } -gint sp_repr_qualified_name (gchar *p, gint len, xmlNsPtr ns, const xmlChar *name, const gchar */*default_ns*/, std::map<std::string, std::string> &prefix_map) +gint sp_repr_qualified_name(gchar *p, gint len, xmlNsPtr ns, const xmlChar *name, const gchar * /*default_ns*/, + std::map<std::string, std::string> &prefix_map) { const xmlChar *prefix; - if (ns){ - if (ns->href ) { - prefix = reinterpret_cast<const xmlChar*>( sp_xml_ns_uri_prefix(reinterpret_cast<const gchar*>(ns->href), - reinterpret_cast<const char*>(ns->prefix)) ); - prefix_map[reinterpret_cast<const char*>(prefix)] = reinterpret_cast<const char*>(ns->href); - } - else { + if (ns) { + if (ns->href) { + prefix = reinterpret_cast<const xmlChar *>(sp_xml_ns_uri_prefix( + reinterpret_cast<const gchar *>(ns->href), reinterpret_cast<const char *>(ns->prefix))); + prefix_map[reinterpret_cast<const char *>(prefix)] = reinterpret_cast<const char *>(ns->href); + } else { prefix = nullptr; } - } - else { + } else { prefix = nullptr; } if (prefix) { - return g_snprintf (p, len, "%s:%s", reinterpret_cast<const gchar*>(prefix), name); + return g_snprintf(p, len, "%s:%s", reinterpret_cast<const gchar *>(prefix), name); } else { - return g_snprintf (p, len, "%s", name); + return g_snprintf(p, len, "%s", name); } } -static Node *sp_repr_svg_read_node (Document *xml_doc, xmlNodePtr node, const gchar *default_ns, std::map<std::string, std::string> &prefix_map) +static Node *sp_repr_svg_read_node(Document *xml_doc, xmlNodePtr node, const gchar *default_ns, + std::map<std::string, std::string> &prefix_map) { xmlAttrPtr prop; xmlNodePtr child; gchar c[256]; if (node->type == XML_TEXT_NODE || node->type == XML_CDATA_SECTION_NODE) { - if (node->content == nullptr || *(node->content) == '\0') { return nullptr; // empty text node } @@ -565,19 +554,18 @@ static Node *sp_repr_svg_read_node (Document *xml_doc, xmlNodePtr node, const gc // Since libxml2 2.9.0, only element nodes are checked, thus check parent. // Note: this only handles XML's rules for white space. SVG's specific rules // are handled in sp-string.cpp. - bool preserve = (xmlNodeGetSpacePreserve (node->parent) == 1); + bool preserve = (xmlNodeGetSpacePreserve(node->parent) == 1); xmlChar *p; - for (p = node->content; *p && g_ascii_isspace (*p) && !preserve; p++) + for (p = node->content; *p && g_ascii_isspace(*p) && !preserve; p++) ; // skip all whitespace - if (!(*p)) { // this is an all-whitespace node, and preserve == default + if (!(*p)) { // this is an all-whitespace node, and preserve == default return nullptr; // we do not preserve all-whitespace nodes unless we are asked to } // We keep track of original node type so that CDATA sections are preserved on output. - return xml_doc->createTextNode(reinterpret_cast<gchar *>(node->content), - node->type == XML_CDATA_SECTION_NODE ); + return xml_doc->createTextNode(reinterpret_cast<gchar *>(node->content), node->type == XML_CDATA_SECTION_NODE); } if (node->type == XML_COMMENT_NODE) { @@ -593,24 +581,24 @@ static Node *sp_repr_svg_read_node (Document *xml_doc, xmlNodePtr node, const gc return nullptr; } - sp_repr_qualified_name (c, 256, node->ns, node->name, default_ns, prefix_map); + sp_repr_qualified_name(c, 256, node->ns, node->name, default_ns, prefix_map); Node *repr = xml_doc->createElement(c); /* TODO remember node->ns->prefix if node->ns != NULL */ for (prop = node->properties; prop != nullptr; prop = prop->next) { if (prop->children) { - sp_repr_qualified_name (c, 256, prop->ns, prop->name, default_ns, prefix_map); - repr->setAttribute(c, reinterpret_cast<gchar*>(prop->children->content)); + sp_repr_qualified_name(c, 256, prop->ns, prop->name, default_ns, prefix_map); + repr->setAttribute(c, reinterpret_cast<gchar *>(prop->children->content)); /* TODO remember prop->ns->prefix if prop->ns != NULL */ } } if (node->content) { - repr->setContent(reinterpret_cast<gchar*>(node->content)); + repr->setContent(reinterpret_cast<gchar *>(node->content)); } for (child = node->xmlChildrenNode; child != nullptr; child = child->next) { - Node *crepr = sp_repr_svg_read_node (xml_doc, child, default_ns, prefix_map); + Node *crepr = sp_repr_svg_read_node(xml_doc, child, default_ns, prefix_map); if (crepr) { repr->appendChild(crepr); Inkscape::GC::release(crepr); @@ -620,44 +608,38 @@ static Node *sp_repr_svg_read_node (Document *xml_doc, xmlNodePtr node, const gc return repr; } - -static void sp_repr_save_writer(Document *doc, Inkscape::IO::Writer *out, - gchar const *default_ns, - gchar const *old_href_abs_base, - gchar const *new_href_abs_base) +static void sp_repr_save_writer(Document *doc, Inkscape::IO::Writer *out, gchar const *default_ns, + gchar const *old_href_abs_base, gchar const *new_href_abs_base) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool inlineattrs = prefs->getBool("/options/svgoutput/inlineattrs"); int indent = prefs->getInt("/options/svgoutput/indent", 2); /* fixme: do this The Right Way */ - out->writeString( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" ); + out->writeString("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"); const gchar *str = static_cast<Node *>(doc)->attribute("doctype"); if (str) { - out->writeString( str ); + out->writeString(str); } - for (Node *repr = sp_repr_document_first_child(doc); - repr; repr = repr->next()) - { + for (Node *repr = sp_repr_document_first_child(doc); repr; repr = repr->next()) { Inkscape::XML::NodeType const node_type = repr->type(); - if ( node_type == Inkscape::XML::ELEMENT_NODE ) { - sp_repr_write_stream_root_element(repr, *out, TRUE, default_ns, inlineattrs, indent, - old_href_abs_base, new_href_abs_base); + if (node_type == Inkscape::XML::ELEMENT_NODE) { + sp_repr_write_stream_root_element(repr, *out, TRUE, default_ns, inlineattrs, indent, old_href_abs_base, + new_href_abs_base); } else { - sp_repr_write_stream(repr, *out, 0, TRUE, GQuark(0), inlineattrs, indent, - old_href_abs_base, new_href_abs_base); - if ( node_type == Inkscape::XML::COMMENT_NODE ) { + sp_repr_write_stream(repr, *out, 0, TRUE, GQuark(0), inlineattrs, indent, old_href_abs_base, + new_href_abs_base); + if (node_type == Inkscape::XML::COMMENT_NODE) { out->writeChar('\n'); } } } } - Glib::ustring sp_repr_save_buf(Document *doc) -{ +{ Inkscape::IO::StringOutputStream souts; Inkscape::IO::OutputStreamWriter outs(souts); @@ -669,14 +651,13 @@ Glib::ustring sp_repr_save_buf(Document *doc) return buf; } - void sp_repr_save_stream(Document *doc, FILE *fp, gchar const *default_ns, bool compress, - gchar const *const old_href_abs_base, - gchar const *const new_href_abs_base) + gchar const *const old_href_abs_base, gchar const *const new_href_abs_base) { Inkscape::IO::FileOutputStream bout(fp); Inkscape::IO::GzipOutputStream *gout = compress ? new Inkscape::IO::GzipOutputStream(bout) : nullptr; - Inkscape::IO::OutputStreamWriter *out = compress ? new Inkscape::IO::OutputStreamWriter( *gout ) : new Inkscape::IO::OutputStreamWriter( bout ); + Inkscape::IO::OutputStreamWriter *out = + compress ? new Inkscape::IO::OutputStreamWriter(*gout) : new Inkscape::IO::OutputStreamWriter(bout); sp_repr_save_writer(doc, out, default_ns, old_href_abs_base, new_href_abs_base); @@ -684,8 +665,6 @@ void sp_repr_save_stream(Document *doc, FILE *fp, gchar const *default_ns, bool delete gout; } - - /** * Returns true if file successfully saved. * @@ -695,7 +674,7 @@ void sp_repr_save_stream(Document *doc, FILE *fp, gchar const *default_ns, bool * xlink:href attributes. */ bool sp_repr_save_rebased_file(Document *doc, gchar const *const filename, gchar const *default_ns, - gchar const *old_base, gchar const *for_filename) + gchar const *old_base, gchar const *for_filename) { if (!filename) { return false; @@ -704,11 +683,10 @@ bool sp_repr_save_rebased_file(Document *doc, gchar const *const filename, gchar bool compress; { size_t const filename_len = strlen(filename); - compress = ( filename_len > 5 - && strcasecmp(".svgz", filename + filename_len - 5) == 0 ); + compress = (filename_len > 5 && strcasecmp(".svgz", filename + filename_len - 5) == 0); } - Inkscape::IO::dump_fopen_call( filename, "B" ); + Inkscape::IO::dump_fopen_call(filename, "B"); FILE *file = Inkscape::IO::fopen_utf8name(filename, "w"); if (file == nullptr) { return false; @@ -739,7 +717,7 @@ bool sp_repr_save_rebased_file(Document *doc, gchar const *const filename, gchar } sp_repr_save_stream(doc, file, default_ns, compress, old_href_abs_base.c_str(), new_href_abs_base.c_str()); - if (fclose (file) != 0) { + if (fclose(file) != 0) { return false; } @@ -754,26 +732,35 @@ bool sp_repr_save_file(Document *doc, gchar const *const filename, gchar const * return sp_repr_save_rebased_file(doc, filename, default_ns, nullptr, nullptr); } - /* (No doubt this function already exists elsewhere.) */ -static void repr_quote_write (Writer &out, const gchar * val) +static void repr_quote_write(Writer &out, const gchar *val) { if (val) { for (; *val != '\0'; val++) { switch (*val) { - case '"': out.writeString( """ ); break; - case '&': out.writeString( "&" ); break; - case '<': out.writeString( "<" ); break; - case '>': out.writeString( ">" ); break; - default: out.writeChar( *val ); break; + case '"': + out.writeString("""); + break; + case '&': + out.writeString("&"); + break; + case '<': + out.writeString("<"); + break; + case '>': + out.writeString(">"); + break; + default: + out.writeChar(*val); + break; } } } } -static void repr_write_comment( Writer &out, const gchar * val, bool addWhitespace, gint indentLevel, int indent ) +static void repr_write_comment(Writer &out, const gchar *val, bool addWhitespace, gint indentLevel, int indent) { - if ( indentLevel > 16 ) { + if (indentLevel > 16) { indentLevel = 16; } if (addWhitespace && indent) { @@ -796,14 +783,15 @@ namespace { typedef std::map<Glib::QueryQuark, gchar const *, Inkscape::compare_quark_ids> LocalNameMap; typedef std::map<Glib::QueryQuark, Inkscape::Util::ptr_shared, Inkscape::compare_quark_ids> NSMap; -gchar const *qname_local_name(Glib::QueryQuark qname) { +gchar const *qname_local_name(Glib::QueryQuark qname) +{ static LocalNameMap local_name_map; LocalNameMap::iterator iter = local_name_map.find(qname); - if ( iter != local_name_map.end() ) { + if (iter != local_name_map.end()) { return (*iter).second; } else { - gchar const *name_string=g_quark_to_string(qname); - gchar const *prefix_end=strchr(name_string, ':'); + gchar const *name_string = g_quark_to_string(qname); + gchar const *prefix_end = strchr(name_string, ':'); if (prefix_end) { return prefix_end + 1; } else { @@ -812,19 +800,20 @@ gchar const *qname_local_name(Glib::QueryQuark qname) { } } -void add_ns_map_entry(NSMap &ns_map, Glib::QueryQuark prefix) { +void add_ns_map_entry(NSMap &ns_map, Glib::QueryQuark prefix) +{ using Inkscape::Util::ptr_shared; using Inkscape::Util::share_unsafe; static const Glib::QueryQuark xml_prefix("xml"); - NSMap::iterator iter=ns_map.find(prefix); - if ( iter == ns_map.end() ) { + NSMap::iterator iter = ns_map.find(prefix); + if (iter == ns_map.end()) { if (prefix.id()) { - gchar const *uri=sp_xml_ns_prefix_uri(g_quark_to_string(prefix)); + gchar const *uri = sp_xml_ns_prefix_uri(g_quark_to_string(prefix)); if (uri) { ns_map.insert(NSMap::value_type(prefix, share_unsafe(uri))); - } else if ( prefix != xml_prefix ) { + } else if (prefix != xml_prefix) { g_warning("No namespace known for normalized prefix %s", g_quark_to_string(prefix)); } } else { @@ -833,32 +822,27 @@ void add_ns_map_entry(NSMap &ns_map, Glib::QueryQuark prefix) { } } -void populate_ns_map(NSMap &ns_map, Node &repr) { - if ( repr.type() == Inkscape::XML::ELEMENT_NODE ) { +void populate_ns_map(NSMap &ns_map, Node &repr) +{ + if (repr.type() == Inkscape::XML::ELEMENT_NODE) { add_ns_map_entry(ns_map, qname_prefix(repr.code())); - for ( List<AttributeRecord const> iter=repr.attributeList() ; - iter ; ++iter ) - { - Glib::QueryQuark prefix=qname_prefix(iter->key); + for (List<AttributeRecord const> iter = repr.attributeList(); iter; ++iter) { + Glib::QueryQuark prefix = qname_prefix(iter->key); if (prefix.id()) { add_ns_map_entry(ns_map, prefix); } } - for ( Node *child=repr.firstChild() ; - child ; child = child->next() ) - { + for (Node *child = repr.firstChild(); child; child = child->next()) { populate_ns_map(ns_map, *child); } } } -} +} // namespace -static void sp_repr_write_stream_root_element(Node *repr, Writer &out, - bool add_whitespace, gchar const *default_ns, - int inlineattrs, int indent, - gchar const *const old_href_base, - gchar const *const new_href_base) +static void sp_repr_write_stream_root_element(Node *repr, Writer &out, bool add_whitespace, gchar const *default_ns, + int inlineattrs, int indent, gchar const *const old_href_base, + gchar const *const new_href_base) { using Inkscape::Util::ptr_shared; @@ -867,35 +851,37 @@ static void sp_repr_write_stream_root_element(Node *repr, Writer &out, // Clean unnecessary attributes and stype properties. (Controlled by preferences.) Inkscape::Preferences *prefs = Inkscape::Preferences::get(); bool clean = prefs->getBool("/options/svgoutput/check_on_writing"); - if (clean) sp_attribute_clean_tree( repr ); + if (clean) + sp_attribute_clean_tree(repr); // Sort attributes in a canonical order (helps with "diffing" SVG files).only if not set disable optimizations - bool sort = !prefs->getBool("/options/svgoutput/disable_optimizations") && prefs->getBool("/options/svgoutput/sort_attributes"); - if (sort) sp_attribute_sort_tree( *repr ); + bool sort = !prefs->getBool("/options/svgoutput/disable_optimizations") && + prefs->getBool("/options/svgoutput/sort_attributes"); + if (sort) + sp_attribute_sort_tree(*repr); - Glib::QueryQuark xml_prefix=g_quark_from_static_string("xml"); + Glib::QueryQuark xml_prefix = g_quark_from_static_string("xml"); NSMap ns_map; populate_ns_map(ns_map, *repr); - Glib::QueryQuark elide_prefix=GQuark(0); - if ( default_ns && ns_map.find(GQuark(0)) == ns_map.end() ) { + Glib::QueryQuark elide_prefix = GQuark(0); + if (default_ns && ns_map.find(GQuark(0)) == ns_map.end()) { elide_prefix = g_quark_from_string(sp_xml_ns_uri_prefix(default_ns, nullptr)); } - List<AttributeRecord const> attributes=repr->attributeList(); - for (auto & iter : ns_map) - { - Glib::QueryQuark prefix=iter.first; - ptr_shared ns_uri=iter.second; + List<AttributeRecord const> attributes = repr->attributeList(); + for (auto &iter : ns_map) { + Glib::QueryQuark prefix = iter.first; + ptr_shared ns_uri = iter.second; if (prefix.id()) { - if ( prefix != xml_prefix ) { - if ( elide_prefix == prefix ) { + if (prefix != xml_prefix) { + if (elide_prefix == prefix) { attributes = cons(AttributeRecord(g_quark_from_static_string("xmlns"), ns_uri), attributes); } - Glib::ustring attr_name="xmlns:"; + Glib::ustring attr_name = "xmlns:"; attr_name.append(g_quark_to_string(prefix)); GQuark key = g_quark_from_string(attr_name.c_str()); attributes = cons(AttributeRecord(key, ns_uri), attributes); @@ -907,40 +893,35 @@ static void sp_repr_write_stream_root_element(Node *repr, Writer &out, } } - return sp_repr_write_stream_element(repr, out, 0, add_whitespace, elide_prefix, attributes, - inlineattrs, indent, old_href_base, new_href_base); + return sp_repr_write_stream_element(repr, out, 0, add_whitespace, elide_prefix, attributes, inlineattrs, indent, + old_href_base, new_href_base); } -void sp_repr_write_stream( Node *repr, Writer &out, gint indent_level, - bool add_whitespace, Glib::QueryQuark elide_prefix, - int inlineattrs, int indent, - gchar const *const old_href_base, - gchar const *const new_href_base) +void sp_repr_write_stream(Node *repr, Writer &out, gint indent_level, bool add_whitespace, + Glib::QueryQuark elide_prefix, int inlineattrs, int indent, gchar const *const old_href_base, + gchar const *const new_href_base) { switch (repr->type()) { case Inkscape::XML::TEXT_NODE: { - if( dynamic_cast<const Inkscape::XML::TextNode *>(repr)->is_CData() ) { + if (dynamic_cast<const Inkscape::XML::TextNode *>(repr)->is_CData()) { // Preserve CDATA sections, not converting '&' to &, etc. - out.printf( "<![CDATA[%s]]>", repr->content() ); + out.printf("<![CDATA[%s]]>", repr->content()); } else { - repr_quote_write( out, repr->content() ); + repr_quote_write(out, repr->content()); } break; } case Inkscape::XML::COMMENT_NODE: { - repr_write_comment( out, repr->content(), add_whitespace, indent_level, indent ); + repr_write_comment(out, repr->content(), add_whitespace, indent_level, indent); break; } case Inkscape::XML::PI_NODE: { - out.printf( "<?%s %s?>", repr->name(), repr->content() ); + out.printf("<?%s %s?>", repr->name(), repr->content()); break; } case Inkscape::XML::ELEMENT_NODE: { - sp_repr_write_stream_element( repr, out, indent_level, - add_whitespace, elide_prefix, - repr->attributeList(), - inlineattrs, indent, - old_href_base, new_href_base); + sp_repr_write_stream_element(repr, out, indent_level, add_whitespace, elide_prefix, repr->attributeList(), + inlineattrs, indent, old_href_base, new_href_base); break; } case Inkscape::XML::DOCUMENT_NODE: { @@ -953,22 +934,17 @@ void sp_repr_write_stream( Node *repr, Writer &out, gint indent_level, } } - -void sp_repr_write_stream_element( Node * repr, Writer & out, - gint indent_level, bool add_whitespace, - Glib::QueryQuark elide_prefix, - List<AttributeRecord const> attributes, - int inlineattrs, int indent, - gchar const *old_href_base, - gchar const *new_href_base ) +void sp_repr_write_stream_element(Node *repr, Writer &out, gint indent_level, bool add_whitespace, + Glib::QueryQuark elide_prefix, List<AttributeRecord const> attributes, + int inlineattrs, int indent, gchar const *old_href_base, gchar const *new_href_base) { Node *child = nullptr; bool loose = false; bool const add_whitespace_parent = add_whitespace; - g_return_if_fail (repr != nullptr); + g_return_if_fail(repr != nullptr); - if ( indent_level > 16 ) { + if (indent_level > 16) { indent_level = 16; } @@ -982,17 +958,16 @@ void sp_repr_write_stream_element( Node * repr, Writer & out, GQuark code = repr->code(); gchar const *element_name; - if ( elide_prefix == qname_prefix(code) ) { + if (elide_prefix == qname_prefix(code)) { element_name = qname_local_name(code); } else { element_name = g_quark_to_string(code); } - out.printf( "<%s", element_name ); + out.printf("<%s", element_name); // If this is a <text> element, suppress formatting whitespace // for its content and children: - if (strcmp(repr->name(), "svg:text") == 0 || - strcmp(repr->name(), "svg:flowRoot") == 0) { + if (strcmp(repr->name(), "svg:text") == 0 || strcmp(repr->name(), "svg:flowRoot") == 0) { add_whitespace = false; } else { // Suppress formatting whitespace for xml:space="preserve" @@ -1004,15 +979,12 @@ void sp_repr_write_stream_element( Node * repr, Writer & out, } } - for ( List<AttributeRecord const> iter = rebase_href_attrs(old_href_base, new_href_base, - attributes); - iter ; ++iter ) - { + for (List<AttributeRecord const> iter = rebase_href_attrs(old_href_base, new_href_base, attributes); iter; ++iter) { if (!inlineattrs) { out.writeChar('\n'); if (indent) { - for ( gint i = 0 ; i < indent_level + 1 ; i++ ) { - for ( gint j = 0 ; j < indent ; j++ ) { + for (gint i = 0; i < indent_level + 1; i++) { + for (gint j = 0; j < indent; j++) { out.writeChar(' '); } } @@ -1024,7 +996,7 @@ void sp_repr_write_stream_element( Node * repr, Writer & out, } loose = TRUE; - for (child = repr->firstChild() ; child != nullptr; child = child->next()) { + for (child = repr->firstChild(); child != nullptr; child = child->next()) { if (child->type() == Inkscape::XML::TEXT_NODE) { loose = FALSE; break; @@ -1037,21 +1009,20 @@ void sp_repr_write_stream_element( Node * repr, Writer & out, out.writeChar('\n'); } for (child = repr->firstChild(); child != nullptr; child = child->next()) { - sp_repr_write_stream(child, out, ( loose ? indent_level + 1 : 0 ), - add_whitespace, elide_prefix, inlineattrs, indent, - old_href_base, new_href_base); + sp_repr_write_stream(child, out, (loose ? indent_level + 1 : 0), add_whitespace, elide_prefix, inlineattrs, + indent, old_href_base, new_href_base); } if (loose && add_whitespace && indent) { for (gint i = 0; i < indent_level; i++) { - for ( gint j = 0 ; j < indent ; j++ ) { + for (gint j = 0; j < indent; j++) { out.writeChar(' '); } } } - out.printf( "</%s>", element_name ); + out.printf("</%s>", element_name); } else { - out.writeString( " />" ); + out.writeString(" />"); } if (add_whitespace_parent) { @@ -1059,7 +1030,6 @@ void sp_repr_write_stream_element( Node * repr, Writer & out, } } - /* Local Variables: mode:c++ diff --git a/src/xml/repr-sorting.cpp b/src/xml/repr-sorting.cpp index 325b2a6c1a86f32f593549b32aa687b1b4d28b30..126508ef4639f05241cf82e58557e8bba06d6de9 100644 --- a/src/xml/repr-sorting.cpp +++ b/src/xml/repr-sorting.cpp @@ -8,29 +8,31 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "repr-sorting.h" + #include "util/longest-common-suffix.h" -#include "xml/repr.h" #include "xml/node-iterators.h" -#include "repr-sorting.h" +#include "xml/repr.h" static bool same_repr(Inkscape::XML::Node const &a, Inkscape::XML::Node const &b) { - /* todo: I'm not certain that it's legal to take the address of a reference. Check the exact wording of the spec on this matter. */ + /* todo: I'm not certain that it's legal to take the address of a reference. Check the exact wording of the spec on + * this matter. */ return &a == &b; } Inkscape::XML::Node const *LCA(Inkscape::XML::Node const *a, Inkscape::XML::Node const *b) { using Inkscape::Algorithms::longest_common_suffix; - Inkscape::XML::Node const *ancestor = longest_common_suffix<Inkscape::XML::NodeConstParentIterator>( - a, b, nullptr, &same_repr); + Inkscape::XML::Node const *ancestor = + longest_common_suffix<Inkscape::XML::NodeConstParentIterator>(a, b, nullptr, &same_repr); bool OK = false; if (ancestor) { if (ancestor->type() != Inkscape::XML::DOCUMENT_NODE) { OK = true; } } - if ( OK ) { + if (OK) { return ancestor; } else { return nullptr; @@ -39,14 +41,15 @@ Inkscape::XML::Node const *LCA(Inkscape::XML::Node const *a, Inkscape::XML::Node Inkscape::XML::Node *LCA(Inkscape::XML::Node *a, Inkscape::XML::Node *b) { - Inkscape::XML::Node const *tmp = LCA(const_cast<Inkscape::XML::Node const *>(a), const_cast<Inkscape::XML::Node const *>(b)); + Inkscape::XML::Node const *tmp = + LCA(const_cast<Inkscape::XML::Node const *>(a), const_cast<Inkscape::XML::Node const *>(b)); return const_cast<Inkscape::XML::Node *>(tmp); } Inkscape::XML::Node const *AncetreFils(Inkscape::XML::Node const *descendent, Inkscape::XML::Node const *ancestor) { Inkscape::XML::Node const *result = nullptr; - if ( descendent && ancestor ) { + if (descendent && ancestor) { if (descendent->parent() == ancestor) { result = descendent; } else { @@ -58,7 +61,8 @@ Inkscape::XML::Node const *AncetreFils(Inkscape::XML::Node const *descendent, In Inkscape::XML::Node *AncetreFils(Inkscape::XML::Node *descendent, Inkscape::XML::Node *ancestor) { - Inkscape::XML::Node const * tmp = AncetreFils(const_cast<Inkscape::XML::Node const*>(descendent), const_cast<Inkscape::XML::Node const*>(ancestor)); + Inkscape::XML::Node const *tmp = AncetreFils(const_cast<Inkscape::XML::Node const *>(descendent), + const_cast<Inkscape::XML::Node const *>(ancestor)); return const_cast<Inkscape::XML::Node *>(tmp); } diff --git a/src/xml/repr-sorting.h b/src/xml/repr-sorting.h index c11162381c0d700e66ae21985662b5bb4fb1a85b..355ab4eefa07b76b2d2900a0b53496d9a4ea8516 100644 --- a/src/xml/repr-sorting.h +++ b/src/xml/repr-sorting.h @@ -24,7 +24,6 @@ class Node; } // namespace XML } // namespace Inkscape - Inkscape::XML::Node *LCA(Inkscape::XML::Node *a, Inkscape::XML::Node *b); Inkscape::XML::Node const *LCA(Inkscape::XML::Node const *a, Inkscape::XML::Node const *b); diff --git a/src/xml/repr-util.cpp b/src/xml/repr-util.cpp index fa0fad061d76730f21f25de72799821afedb388e..03cb6f927303d29c11945935b8ad1eca36679b89 100644 --- a/src/xml/repr-util.cpp +++ b/src/xml/repr-util.cpp @@ -16,23 +16,20 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include <cstring> +#include <2geom/point.h> #include <cstdlib> - - +#include <cstring> #include <glib.h> #include <glibmm.h> -#include <2geom/point.h> -#include "svg/stringstream.h" #include "svg/css-ostringstream.h" +#include "svg/stringstream.h" #include "svg/svg-length.h" - -#include "xml/repr.h" #include "xml/repr-sorting.h" +#include "xml/repr.h" - -struct SPXMLNs { +struct SPXMLNs +{ SPXMLNs *next; unsigned int uri, prefix; }; @@ -42,15 +39,15 @@ struct SPXMLNs { #####################*/ #ifndef FALSE -# define FALSE 0 +#define FALSE 0 #endif #ifndef TRUE -# define TRUE (!FALSE) +#define TRUE (!FALSE) #endif #ifndef MAX -# define MAX(a,b) (((a) < (b)) ? (b) : (a)) +#define MAX(a, b) (((a) < (b)) ? (b) : (a)) #endif /*##################### @@ -68,7 +65,7 @@ static char *sp_xml_ns_auto_prefix(char const *uri); * SPXMLNs */ -static SPXMLNs *namespaces=nullptr; +static SPXMLNs *namespaces = nullptr; /* * There are the prefixes to use for the XML namespaces defined @@ -106,9 +103,9 @@ static void sp_xml_ns_register_defaults() defaults[6].prefix = g_quark_from_static_string("dc"); defaults[6].next = &defaults[8]; - //defaults[7].uri = g_quark_from_static_string("https://inkscape.org/namespaces/deprecated/osb"); - //defaults[7].prefix = g_quark_from_static_string("osb"); - //defaults[7].next = &defaults[8]; + // defaults[7].uri = g_quark_from_static_string("https://inkscape.org/namespaces/deprecated/osb"); + // defaults[7].prefix = g_quark_from_static_string("osb"); + // defaults[7].next = &defaults[8]; // Inkscape versions prior to 0.44 would write this namespace // URI instead of the correct sodipodi namespace; by adding this @@ -152,7 +149,7 @@ char *sp_xml_ns_auto_prefix(char const *uri) new_prefix = g_strndup(start, end - start); if (sp_xml_ns_prefix_uri(new_prefix)) { char *temp; - int counter=0; + int counter = 0; do { temp = g_strdup_printf("%s%d", new_prefix, counter++); } while (sp_xml_ns_prefix_uri(temp)); @@ -166,7 +163,8 @@ gchar const *sp_xml_ns_uri_prefix(gchar const *uri, gchar const *suggested) { char const *prefix; - if (!uri) return nullptr; + if (!uri) + return nullptr; if (!namespaces) { sp_xml_ns_register_defaults(); @@ -174,8 +172,8 @@ gchar const *sp_xml_ns_uri_prefix(gchar const *uri, gchar const *suggested) GQuark const key = g_quark_from_string(uri); prefix = nullptr; - for ( SPXMLNs *iter=namespaces ; iter ; iter = iter->next ) { - if ( iter->uri == key ) { + for (SPXMLNs *iter = namespaces; iter; iter = iter->next) { + if (iter->uri == key) { prefix = g_quark_to_string(iter->prefix); break; } @@ -185,14 +183,13 @@ gchar const *sp_xml_ns_uri_prefix(gchar const *uri, gchar const *suggested) char *new_prefix; SPXMLNs *ns; if (suggested) { - GQuark const prefix_key=g_quark_from_string(suggested); + GQuark const prefix_key = g_quark_from_string(suggested); - SPXMLNs *found=namespaces; + SPXMLNs *found = namespaces; while (found) { if (found->prefix != prefix_key) { found = found->next; - } - else { + } else { break; } } @@ -207,7 +204,7 @@ gchar const *sp_xml_ns_uri_prefix(gchar const *uri, gchar const *suggested) } ns = g_new(SPXMLNs, 1); - g_assert( ns != nullptr ); + g_assert(ns != nullptr); ns->uri = g_quark_from_string(uri); ns->prefix = g_quark_from_string(new_prefix); @@ -227,7 +224,8 @@ gchar const *sp_xml_ns_prefix_uri(gchar const *prefix) SPXMLNs *iter; char const *uri; - if (!prefix) return nullptr; + if (!prefix) + return nullptr; if (!namespaces) { sp_xml_ns_register_defaults(); @@ -235,8 +233,8 @@ gchar const *sp_xml_ns_prefix_uri(gchar const *prefix) GQuark const key = g_quark_from_string(prefix); uri = nullptr; - for ( iter = namespaces ; iter ; iter = iter->next ) { - if ( iter->prefix == key ) { + for (iter = namespaces; iter; iter = iter->next) { + if (iter->prefix == key) { uri = g_quark_to_string(iter->uri); break; } @@ -280,8 +278,10 @@ int sp_repr_compare_position(Inkscape::XML::Node const *first, Inkscape::XML::No } } - if (p1 > p2) return 1; - if (p1 < p2) return -1; + if (p1 > p2) + return 1; + if (p1 < p2) + return -1; return 0; /* effic: Assuming that the parent--child relationship is consistent @@ -301,11 +301,11 @@ int sp_repr_compare_position(Inkscape::XML::Node const *first, Inkscape::XML::No pjrm */ } -bool sp_repr_compare_position_bool(Inkscape::XML::Node const *first, Inkscape::XML::Node const *second){ - return sp_repr_compare_position(first, second)<0; +bool sp_repr_compare_position_bool(Inkscape::XML::Node const *first, Inkscape::XML::Node const *second) +{ + return sp_repr_compare_position(first, second) < 0; } - /** * Find an element node using an unique attribute. * @@ -317,16 +317,12 @@ bool sp_repr_compare_position_bool(Inkscape::XML::Node const *first, Inkscape::X * @param value The value of the attribute to look for * @relatesalso Inkscape::XML::Node */ -Inkscape::XML::Node *sp_repr_lookup_child(Inkscape::XML::Node *repr, - gchar const *key, - gchar const *value) +Inkscape::XML::Node *sp_repr_lookup_child(Inkscape::XML::Node *repr, gchar const *key, gchar const *value) { g_return_val_if_fail(repr != nullptr, NULL); - for ( Inkscape::XML::Node *child = repr->firstChild() ; child ; child = child->next() ) { + for (Inkscape::XML::Node *child = repr->firstChild(); child; child = child->next()) { gchar const *child_value = child->attribute(key); - if ( (child_value == value) || - (value && child_value && !strcmp(child_value, value)) ) - { + if ((child_value == value) || (value && child_value && !strcmp(child_value, value))) { return child; } } @@ -336,34 +332,30 @@ Inkscape::XML::Node *sp_repr_lookup_child(Inkscape::XML::Node *repr, /** * Recursive version of sp_repr_lookup_child(). */ -Inkscape::XML::Node const *sp_repr_lookup_descendant(Inkscape::XML::Node const *repr, - gchar const *key, +Inkscape::XML::Node const *sp_repr_lookup_descendant(Inkscape::XML::Node const *repr, gchar const *key, gchar const *value) { Inkscape::XML::Node const *found = nullptr; g_return_val_if_fail(repr != nullptr, NULL); gchar const *repr_value = repr->attribute(key); - if ( (repr_value == value) || - (repr_value && value && strcmp(repr_value, value) == 0) ) { + if ((repr_value == value) || (repr_value && value && strcmp(repr_value, value) == 0)) { found = repr; } else { - for (Inkscape::XML::Node const *child = repr->firstChild() ; child && !found; child = child->next() ) { - found = sp_repr_lookup_descendant( child, key, value ); + for (Inkscape::XML::Node const *child = repr->firstChild(); child && !found; child = child->next()) { + found = sp_repr_lookup_descendant(child, key, value); } } return found; } - -Inkscape::XML::Node *sp_repr_lookup_descendant(Inkscape::XML::Node *repr, - gchar const *key, - gchar const *value) +Inkscape::XML::Node *sp_repr_lookup_descendant(Inkscape::XML::Node *repr, gchar const *key, gchar const *value) { - Inkscape::XML::Node const *found = sp_repr_lookup_descendant( const_cast<Inkscape::XML::Node const *>(repr), key, value ); + Inkscape::XML::Node const *found = + sp_repr_lookup_descendant(const_cast<Inkscape::XML::Node const *>(repr), key, value); return const_cast<Inkscape::XML::Node *>(found); } -Inkscape::XML::Node const *sp_repr_lookup_name( Inkscape::XML::Node const *repr, gchar const *name, gint maxdepth ) +Inkscape::XML::Node const *sp_repr_lookup_name(Inkscape::XML::Node const *repr, gchar const *name, gint maxdepth) { Inkscape::XML::Node const *found = nullptr; g_return_val_if_fail(repr != nullptr, NULL); @@ -371,28 +363,30 @@ Inkscape::XML::Node const *sp_repr_lookup_name( Inkscape::XML::Node const *repr, GQuark const quark = g_quark_from_string(name); - if ( (GQuark)repr->code() == quark ) { + if ((GQuark)repr->code() == quark) { found = repr; - } else if ( maxdepth != 0 ) { + } else if (maxdepth != 0) { // maxdepth == -1 means unlimited - if ( maxdepth == -1 ) { + if (maxdepth == -1) { maxdepth = 0; } - for (Inkscape::XML::Node const *child = repr->firstChild() ; child && !found; child = child->next() ) { - found = sp_repr_lookup_name( child, name, maxdepth - 1 ); + for (Inkscape::XML::Node const *child = repr->firstChild(); child && !found; child = child->next()) { + found = sp_repr_lookup_name(child, name, maxdepth - 1); } } return found; } -Inkscape::XML::Node *sp_repr_lookup_name( Inkscape::XML::Node *repr, gchar const *name, gint maxdepth ) +Inkscape::XML::Node *sp_repr_lookup_name(Inkscape::XML::Node *repr, gchar const *name, gint maxdepth) { - Inkscape::XML::Node const *found = sp_repr_lookup_name( const_cast<Inkscape::XML::Node const *>(repr), name, maxdepth ); + Inkscape::XML::Node const *found = + sp_repr_lookup_name(const_cast<Inkscape::XML::Node const *>(repr), name, maxdepth); return const_cast<Inkscape::XML::Node *>(found); } -std::vector<Inkscape::XML::Node const *> sp_repr_lookup_name_many( Inkscape::XML::Node const *repr, gchar const *name, gint maxdepth ) +std::vector<Inkscape::XML::Node const *> sp_repr_lookup_name_many(Inkscape::XML::Node const *repr, gchar const *name, + gint maxdepth) { std::vector<Inkscape::XML::Node const *> nodes; std::vector<Inkscape::XML::Node const *> found; @@ -401,18 +395,18 @@ std::vector<Inkscape::XML::Node const *> sp_repr_lookup_name_many( Inkscape::XML GQuark const quark = g_quark_from_string(name); - if ( (GQuark)repr->code() == quark ) { + if ((GQuark)repr->code() == quark) { nodes.push_back(repr); } - if ( maxdepth != 0 ) { + if (maxdepth != 0) { // maxdepth == -1 means unlimited - if ( maxdepth == -1 ) { + if (maxdepth == -1) { maxdepth = 0; } - for (Inkscape::XML::Node const *child = repr->firstChild() ; child; child = child->next() ) { - found = sp_repr_lookup_name_many( child, name, maxdepth - 1); + for (Inkscape::XML::Node const *child = repr->firstChild(); child; child = child->next()) { + found = sp_repr_lookup_name_many(child, name, maxdepth - 1); nodes.insert(nodes.end(), found.begin(), found.end()); } } @@ -420,27 +414,27 @@ std::vector<Inkscape::XML::Node const *> sp_repr_lookup_name_many( Inkscape::XML return nodes; } -std::vector<Inkscape::XML::Node *> -sp_repr_lookup_property_many( Inkscape::XML::Node *repr, Glib::ustring const& property, - Glib::ustring const &value, int maxdepth ) +std::vector<Inkscape::XML::Node *> sp_repr_lookup_property_many(Inkscape::XML::Node *repr, + Glib::ustring const &property, + Glib::ustring const &value, int maxdepth) { std::vector<Inkscape::XML::Node *> nodes; std::vector<Inkscape::XML::Node *> found; - g_return_val_if_fail(repr != nullptr, nodes); + g_return_val_if_fail(repr != nullptr, nodes); - SPCSSAttr* css = sp_repr_css_attr (repr, "style"); - if (value == sp_repr_css_property (css, property, "")) { + SPCSSAttr *css = sp_repr_css_attr(repr, "style"); + if (value == sp_repr_css_property(css, property, "")) { nodes.push_back(repr); } - if ( maxdepth != 0 ) { + if (maxdepth != 0) { // maxdepth == -1 means unlimited - if ( maxdepth == -1 ) { + if (maxdepth == -1) { maxdepth = 0; } - for (Inkscape::XML::Node *child = repr->firstChild() ; child; child = child->next() ) { - found = sp_repr_lookup_property_many( child, property, value, maxdepth - 1); + for (Inkscape::XML::Node *child = repr->firstChild(); child; child = child->next()) { + found = sp_repr_lookup_property_many(child, property, value, maxdepth - 1); nodes.insert(nodes.end(), found.begin(), found.end()); } } @@ -453,13 +447,19 @@ sp_repr_lookup_property_many( Inkscape::XML::Node *repr, Glib::ustring const& pr */ bool sp_repr_is_meta_element(const Inkscape::XML::Node *node) { - if (node == nullptr) return false; - if (node->type() != Inkscape::XML::ELEMENT_NODE) return false; + if (node == nullptr) + return false; + if (node->type() != Inkscape::XML::ELEMENT_NODE) + return false; gchar const *name = node->name(); - if (name == nullptr) return false; - if (!std::strcmp(name, "svg:title")) return true; - if (!std::strcmp(name, "svg:desc")) return true; - if (!std::strcmp(name, "svg:metadata")) return true; + if (name == nullptr) + return false; + if (!std::strcmp(name, "svg:title")) + return true; + if (!std::strcmp(name, "svg:desc")) + return true; + if (!std::strcmp(name, "svg:metadata")) + return true; return false; } @@ -480,9 +480,7 @@ unsigned int sp_repr_get_boolean(Inkscape::XML::Node *repr, gchar const *key, un v = repr->attribute(key); if (v != nullptr) { - if (!g_ascii_strcasecmp(v, "true") || - !g_ascii_strcasecmp(v, "yes" ) || - !g_ascii_strcasecmp(v, "y" ) || + if (!g_ascii_strcasecmp(v, "true") || !g_ascii_strcasecmp(v, "yes") || !g_ascii_strcasecmp(v, "y") || (atoi(v) != 0)) { *val = TRUE; } else { @@ -577,7 +575,7 @@ unsigned int sp_repr_set_svg_double(Inkscape::XML::Node *repr, gchar const *key, { g_return_val_if_fail(repr != nullptr, FALSE); g_return_val_if_fail(key != nullptr, FALSE); - g_return_val_if_fail(val==val, FALSE);//tests for nan + g_return_val_if_fail(val == val, FALSE); // tests for nan Inkscape::SVGOStringStream os; os << val; @@ -586,9 +584,10 @@ unsigned int sp_repr_set_svg_double(Inkscape::XML::Node *repr, gchar const *key, return true; } -unsigned int sp_repr_set_svg_non_default_double(Inkscape::XML::Node *repr, gchar const *key, double val, double default_value) +unsigned int sp_repr_set_svg_non_default_double(Inkscape::XML::Node *repr, gchar const *key, double val, + double default_value) { - if (val==default_value){ + if (val == default_value) { repr->removeAttribute(key); return true; } @@ -609,7 +608,7 @@ unsigned int sp_repr_set_svg_length(Inkscape::XML::Node *repr, gchar const *key, return true; } -unsigned sp_repr_set_point(Inkscape::XML::Node *repr, gchar const *key, Geom::Point const & val) +unsigned sp_repr_set_point(Inkscape::XML::Node *repr, gchar const *key, Geom::Point const &val) { g_return_val_if_fail(repr != nullptr, FALSE); g_return_val_if_fail(key != nullptr, FALSE); @@ -631,18 +630,18 @@ unsigned int sp_repr_get_point(Inkscape::XML::Node *repr, gchar const *key, Geom g_return_val_if_fail(v != nullptr, FALSE); - gchar ** strarray = g_strsplit(v, ",", 2); + gchar **strarray = g_strsplit(v, ",", 2); if (strarray && strarray[0] && strarray[1]) { double newx, newy; newx = g_ascii_strtod(strarray[0], nullptr); newy = g_ascii_strtod(strarray[1], nullptr); - g_strfreev (strarray); + g_strfreev(strarray); *val = Geom::Point(newx, newy); return TRUE; } - g_strfreev (strarray); + g_strfreev(strarray); return FALSE; } diff --git a/src/xml/repr.cpp b/src/xml/repr.cpp index 89885865c7fc38c035f3df73c4110f74ab8149dd..b5ee513d6a3ba3de07a5172148c8d270a105e701 100644 --- a/src/xml/repr.cpp +++ b/src/xml/repr.cpp @@ -17,19 +17,19 @@ #define noREPR_VERBOSE +#include "xml/repr.h" + #include <cstring> -#include "xml/repr.h" -#include "xml/text-node.h" -#include "xml/element-node.h" #include "xml/comment-node.h" +#include "xml/element-node.h" #include "xml/simple-document.h" +#include "xml/text-node.h" using Inkscape::Util::share_string; /// Returns new document having as first child a node named rootname. -Inkscape::XML::Document * -sp_repr_document_new(char const *rootname) +Inkscape::XML::Document *sp_repr_document_new(char const *rootname) { Inkscape::XML::Document *doc = new Inkscape::XML::SimpleDocument(); if (!strcmp(rootname, "svg:svg")) { diff --git a/src/xml/repr.h b/src/xml/repr.h index 359d64e072c21f5314e8238f988322eb8d2c32d2..f25f2e01dbd308ae5120803ca4a4fbe977a194b3 100644 --- a/src/xml/repr.h +++ b/src/xml/repr.h @@ -15,11 +15,11 @@ #ifndef SEEN_SP_REPR_H #define SEEN_SP_REPR_H -#include <vector> #include <glibmm/quark.h> +#include <vector> -#include "xml/node.h" #include "xml/document.h" +#include "xml/node.h" #define SP_SODIPODI_NS_URI "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" #define SP_BROKEN_SODIPODI_NS_URI "http://inkscape.sourceforge.net/DTD/sodipodi-0.dtd" @@ -54,26 +54,21 @@ Inkscape::XML::Document *sp_repr_document_new(char const *rootname); Inkscape::XML::Document *sp_repr_read_file(char const *filename, char const *default_ns); Inkscape::XML::Document *sp_repr_read_mem(char const *buffer, int length, char const *default_ns); -void sp_repr_write_stream(Inkscape::XML::Node *repr, Inkscape::IO::Writer &out, - int indent_level, bool add_whitespace, Glib::QueryQuark elide_prefix, - int inlineattrs, int indent, - char const *old_href_base = nullptr, - char const *new_href_base = nullptr); -Inkscape::XML::Document *sp_repr_read_buf (const Glib::ustring &buf, const char *default_ns); +void sp_repr_write_stream(Inkscape::XML::Node *repr, Inkscape::IO::Writer &out, int indent_level, bool add_whitespace, + Glib::QueryQuark elide_prefix, int inlineattrs, int indent, + char const *old_href_base = nullptr, char const *new_href_base = nullptr); +Inkscape::XML::Document *sp_repr_read_buf(const Glib::ustring &buf, const char *default_ns); Glib::ustring sp_repr_save_buf(Inkscape::XML::Document *doc); // TODO convert to std::string -void sp_repr_save_stream(Inkscape::XML::Document *doc, FILE *to_file, - char const *default_ns = nullptr, bool compress = false, - char const *old_href_base = nullptr, +void sp_repr_save_stream(Inkscape::XML::Document *doc, FILE *to_file, char const *default_ns = nullptr, + bool compress = false, char const *old_href_base = nullptr, char const *new_href_base = nullptr); -bool sp_repr_save_file(Inkscape::XML::Document *doc, char const *filename, char const *default_ns=nullptr); -bool sp_repr_save_rebased_file(Inkscape::XML::Document *doc, char const *filename_utf8, - char const *default_ns, +bool sp_repr_save_file(Inkscape::XML::Document *doc, char const *filename, char const *default_ns = nullptr); +bool sp_repr_save_rebased_file(Inkscape::XML::Document *doc, char const *filename_utf8, char const *default_ns, char const *old_base, char const *new_base_filename); - /* CSS stuff */ SPCSSAttr *sp_repr_css_attr_new(); @@ -100,9 +95,10 @@ void sp_repr_css_print(SPCSSAttr *css); /* Utility finctions */ /// Remove \a repr from children of its parent node. -inline void sp_repr_unparent(Inkscape::XML::Node *repr) { +inline void sp_repr_unparent(Inkscape::XML::Node *repr) +{ if (repr) { - Inkscape::XML::Node *parent=repr->parent(); + Inkscape::XML::Node *parent = repr->parent(); if (parent) { parent->removeChild(repr); } @@ -119,12 +115,13 @@ unsigned sp_repr_set_boolean(Inkscape::XML::Node *repr, char const *key, unsigne unsigned sp_repr_set_int(Inkscape::XML::Node *repr, char const *key, int val); unsigned sp_repr_set_css_double(Inkscape::XML::Node *repr, char const *key, double val); unsigned sp_repr_set_svg_double(Inkscape::XML::Node *repr, char const *key, double val); -unsigned sp_repr_set_svg_non_default_double(Inkscape::XML::Node *repr, char const *key, double val, double default_value); +unsigned sp_repr_set_svg_non_default_double(Inkscape::XML::Node *repr, char const *key, double val, + double default_value); unsigned sp_repr_set_svg_length(Inkscape::XML::Node *repr, char const *key, SVGLength &val); -unsigned sp_repr_set_point(Inkscape::XML::Node *repr, char const *key, Geom::Point const & val); +unsigned sp_repr_set_point(Inkscape::XML::Node *repr, char const *key, Geom::Point const &val); unsigned sp_repr_get_point(Inkscape::XML::Node *repr, char const *key, Geom::Point *val); -//c++-style comparison : returns (bool)(a<b) +// c++-style comparison : returns (bool)(a<b) int sp_repr_compare_position(Inkscape::XML::Node const *first, Inkscape::XML::Node const *second); bool sp_repr_compare_position_bool(Inkscape::XML::Node const *first, Inkscape::XML::Node const *second); @@ -141,51 +138,42 @@ bool sp_repr_compare_position_bool(Inkscape::XML::Node const *first, Inkscape::X * @return A pointer to the matching Inkscape::XML::Node * @relatesalso Inkscape::XML::Node */ -Inkscape::XML::Node *sp_repr_lookup_name(Inkscape::XML::Node *repr, - char const *name, - int maxdepth = -1); +Inkscape::XML::Node *sp_repr_lookup_name(Inkscape::XML::Node *repr, char const *name, int maxdepth = -1); -Inkscape::XML::Node const *sp_repr_lookup_name(Inkscape::XML::Node const *repr, - char const *name, - int maxdepth = -1); +Inkscape::XML::Node const *sp_repr_lookup_name(Inkscape::XML::Node const *repr, char const *name, int maxdepth = -1); -std::vector<Inkscape::XML::Node const *> sp_repr_lookup_name_many(Inkscape::XML::Node const *repr, - char const *name, +std::vector<Inkscape::XML::Node const *> sp_repr_lookup_name_many(Inkscape::XML::Node const *repr, char const *name, int maxdepth = -1); // Find an element node using an unique attribute. -Inkscape::XML::Node *sp_repr_lookup_child(Inkscape::XML::Node *repr, - char const *key, - char const *value); +Inkscape::XML::Node *sp_repr_lookup_child(Inkscape::XML::Node *repr, char const *key, char const *value); // Find an element node using an unique attribute recursively. -Inkscape::XML::Node *sp_repr_lookup_descendant(Inkscape::XML::Node *repr, - char const *key, - char const *value); +Inkscape::XML::Node *sp_repr_lookup_descendant(Inkscape::XML::Node *repr, char const *key, char const *value); -Inkscape::XML::Node const *sp_repr_lookup_descendant(Inkscape::XML::Node const *repr, - char const *key, +Inkscape::XML::Node const *sp_repr_lookup_descendant(Inkscape::XML::Node const *repr, char const *key, char const *value); // Find element nodes using a property value. std::vector<Inkscape::XML::Node *> sp_repr_lookup_property_many(Inkscape::XML::Node *repr, Glib::ustring const &property, - Glib::ustring const &value, - int maxdepth = -1); + Glib::ustring const &value, int maxdepth = -1); -inline Inkscape::XML::Node *sp_repr_document_first_child(Inkscape::XML::Document const *doc) { +inline Inkscape::XML::Node *sp_repr_document_first_child(Inkscape::XML::Document const *doc) +{ return const_cast<Inkscape::XML::Node *>(doc->firstChild()); } -inline bool sp_repr_is_def(Inkscape::XML::Node const *node) { - return node->parent() != nullptr && - node->parent()->name() != nullptr && - strcmp("svg:defs", node->parent()->name()) == 0; +inline bool sp_repr_is_def(Inkscape::XML::Node const *node) +{ + return node->parent() != nullptr && node->parent()->name() != nullptr && + strcmp("svg:defs", node->parent()->name()) == 0; } -inline bool sp_repr_is_layer(Inkscape::XML::Node const *node) { +inline bool sp_repr_is_layer(Inkscape::XML::Node const *node) +{ return node->attribute("inkscape:groupmode") != nullptr && - strcmp("layer", node->attribute("inkscape:groupmode")) == 0; + strcmp("layer", node->attribute("inkscape:groupmode")) == 0; } /** @@ -200,13 +188,12 @@ inline bool sp_repr_is_layer(Inkscape::XML::Node const *node) { * @relatesalso Inkscape::XML::Node */ template <typename Visitor> -void sp_repr_visit_descendants(Inkscape::XML::Node *node, Visitor visitor) { +void sp_repr_visit_descendants(Inkscape::XML::Node *node, Visitor visitor) +{ if (!visitor(node)) { return; } - for (Inkscape::XML::Node *child = node->firstChild(); - child != nullptr; - child = child->next()) { + for (Inkscape::XML::Node *child = node->firstChild(); child != nullptr; child = child->next()) { sp_repr_visit_descendants(child, visitor); } } @@ -223,13 +210,13 @@ void sp_repr_visit_descendants(Inkscape::XML::Node *node, Visitor visitor) { * @relatesalso Inkscape::XML::Node */ template <typename Visitor> -void sp_repr_visit_descendants(Inkscape::XML::Node *a, Inkscape::XML::Node *b, Visitor visitor) { +void sp_repr_visit_descendants(Inkscape::XML::Node *a, Inkscape::XML::Node *b, Visitor visitor) +{ if (!visitor(a, b)) { return; } - for (Inkscape::XML::Node *ac = a->firstChild(), *bc = b->firstChild(); - ac != nullptr && bc != nullptr; - ac = ac->next(), bc = bc->next()) { + for (Inkscape::XML::Node *ac = a->firstChild(), *bc = b->firstChild(); ac != nullptr && bc != nullptr; + ac = ac->next(), bc = bc->next()) { sp_repr_visit_descendants(ac, bc, visitor); } } diff --git a/src/xml/simple-document.cpp b/src/xml/simple-document.cpp index c1227ac08c133da635fddced7a8d6f356ee18165..659b02c023127a62739dd2bc252184b458b87224 100644 --- a/src/xml/simple-document.cpp +++ b/src/xml/simple-document.cpp @@ -10,25 +10,28 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ +#include "xml/simple-document.h" + #include <glib.h> // g_assert() -#include "xml/simple-document.h" -#include "xml/event-fns.h" -#include "xml/element-node.h" -#include "xml/text-node.h" #include "xml/comment-node.h" +#include "xml/element-node.h" +#include "xml/event-fns.h" #include "xml/pi-node.h" +#include "xml/text-node.h" namespace Inkscape { namespace XML { -void SimpleDocument::beginTransaction() { +void SimpleDocument::beginTransaction() +{ g_assert(!_in_transaction); _in_transaction = true; } -void SimpleDocument::rollback() { +void SimpleDocument::rollback() +{ g_assert(_in_transaction); _in_transaction = false; Event *log = _log_builder.detach(); @@ -36,78 +39,74 @@ void SimpleDocument::rollback() { sp_repr_free_log(log); } -void SimpleDocument::commit() { +void SimpleDocument::commit() +{ g_assert(_in_transaction); _in_transaction = false; _log_builder.discard(); } -Inkscape::XML::Event *SimpleDocument::commitUndoable() { +Inkscape::XML::Event *SimpleDocument::commitUndoable() +{ g_assert(_in_transaction); _in_transaction = false; return _log_builder.detach(); } -Node *SimpleDocument::createElement(char const *name) { +Node *SimpleDocument::createElement(char const *name) +{ return new ElementNode(g_quark_from_string(name), this); } -Node *SimpleDocument::createTextNode(char const *content) { +Node *SimpleDocument::createTextNode(char const *content) +{ return new TextNode(Util::share_string(content), this); } -Node *SimpleDocument::createTextNode(char const *content, bool const is_CData) { +Node *SimpleDocument::createTextNode(char const *content, bool const is_CData) +{ return new TextNode(Util::share_string(content), this, is_CData); } -Node *SimpleDocument::createComment(char const *content) { +Node *SimpleDocument::createComment(char const *content) +{ return new CommentNode(Util::share_string(content), this); } -Node *SimpleDocument::createPI(char const *target, char const *content) { +Node *SimpleDocument::createPI(char const *target, char const *content) +{ return new PINode(g_quark_from_string(target), Util::share_string(content), this); } -void SimpleDocument::notifyChildAdded(Node &parent, - Node &child, - Node *prev) +void SimpleDocument::notifyChildAdded(Node &parent, Node &child, Node *prev) { if (_in_transaction) { _log_builder.addChild(parent, child, prev); } } -void SimpleDocument::notifyChildRemoved(Node &parent, - Node &child, - Node *prev) +void SimpleDocument::notifyChildRemoved(Node &parent, Node &child, Node *prev) { if (_in_transaction) { _log_builder.removeChild(parent, child, prev); } } -void SimpleDocument::notifyChildOrderChanged(Node &parent, - Node &child, - Node *old_prev, - Node *new_prev) +void SimpleDocument::notifyChildOrderChanged(Node &parent, Node &child, Node *old_prev, Node *new_prev) { if (_in_transaction) { _log_builder.setChildOrder(parent, child, old_prev, new_prev); } } -void SimpleDocument::notifyContentChanged(Node &node, - Util::ptr_shared old_content, - Util::ptr_shared new_content) +void SimpleDocument::notifyContentChanged(Node &node, Util::ptr_shared old_content, Util::ptr_shared new_content) { if (_in_transaction) { _log_builder.setContent(node, old_content, new_content); } } -void SimpleDocument::notifyAttributeChanged(Node &node, - GQuark name, - Util::ptr_shared old_value, +void SimpleDocument::notifyAttributeChanged(Node &node, GQuark name, Util::ptr_shared old_value, Util::ptr_shared new_value) { if (_in_transaction) { @@ -115,7 +114,7 @@ void SimpleDocument::notifyAttributeChanged(Node &node, } } -void SimpleDocument::notifyElementNameChanged(Node& node, GQuark old_name, GQuark new_name) +void SimpleDocument::notifyElementNameChanged(Node &node, GQuark old_name, GQuark new_name) { if (_in_transaction) { _log_builder.setElementName(node, old_name, new_name); diff --git a/src/xml/simple-document.h b/src/xml/simple-document.h index 5dc175093deee340aa32fdce1491365f6acec2e8..f50ecc7107c422a4a7ca5154695c2310e4e43fcd 100644 --- a/src/xml/simple-document.h +++ b/src/xml/simple-document.h @@ -14,22 +14,25 @@ #define SEEN_INKSCAPE_XML_SIMPLE_DOCUMENT_H #include "xml/document.h" -#include "xml/simple-node.h" -#include "xml/node-observer.h" #include "xml/log-builder.h" +#include "xml/node-observer.h" +#include "xml/simple-node.h" namespace Inkscape { namespace XML { -class SimpleDocument : public SimpleNode, - public Document, - public NodeObserver +class SimpleDocument + : public SimpleNode + , public Document + , public NodeObserver { public: explicit SimpleDocument() - : SimpleNode(g_quark_from_static_string("xml"), this), - _in_transaction(false), _is_CData(false) {} + : SimpleNode(g_quark_from_static_string("xml"), this) + , _in_transaction(false) + , _is_CData(false) + {} NodeType type() const override { return Inkscape::XML::DOCUMENT_NODE; } @@ -50,29 +53,26 @@ public: void notifyChildRemoved(Node &parent, Node &child, Node *prev) override; - void notifyChildOrderChanged(Node &parent, Node &child, - Node *old_prev, Node *new_prev) override; + void notifyChildOrderChanged(Node &parent, Node &child, Node *old_prev, Node *new_prev) override; - void notifyContentChanged(Node &node, - Util::ptr_shared old_content, - Util::ptr_shared new_content) override; + void notifyContentChanged(Node &node, Util::ptr_shared old_content, Util::ptr_shared new_content) override; - void notifyAttributeChanged(Node &node, GQuark name, - Util::ptr_shared old_value, + void notifyAttributeChanged(Node &node, GQuark name, Util::ptr_shared old_value, Util::ptr_shared new_value) override; - void notifyElementNameChanged(Node& node, GQuark old_name, GQuark new_name) override; + void notifyElementNameChanged(Node &node, GQuark old_name, GQuark new_name) override; protected: SimpleDocument(SimpleDocument const &doc) - : Node(), SimpleNode(doc), Document(), NodeObserver(), - _in_transaction(false), - _is_CData(false){} - - SimpleNode *_duplicate(Document* /*doc*/) const override - { - return new SimpleDocument(*this); - } + : Node() + , SimpleNode(doc) + , Document() + , NodeObserver() + , _in_transaction(false) + , _is_CData(false) + {} + + SimpleNode *_duplicate(Document * /*doc*/) const override { return new SimpleDocument(*this); } NodeObserver *logger() override { return this; } private: @@ -81,9 +81,9 @@ private: bool _is_CData; }; -} +} // namespace XML -} +} // namespace Inkscape #endif /* diff --git a/src/xml/simple-node.cpp b/src/xml/simple-node.cpp index a3e8e2414601f01cb461651aec48aa1f929a53da..2bb979a083a54e51a9b7d3d80d06420b22528ded 100644 --- a/src/xml/simple-node.cpp +++ b/src/xml/simple-node.cpp @@ -40,28 +40,29 @@ namespace XML { namespace { -std::shared_ptr<std::string> stringify_node(Node const &node) { +std::shared_ptr<std::string> stringify_node(Node const &node) +{ gchar *string; switch (node.type()) { - case ELEMENT_NODE: { - char const *id=node.attribute("id"); - if (id) { - string = g_strdup_printf("element(%p)=%s(#%s)", &node, node.name(), id); - } else { - string = g_strdup_printf("element(%p)=%s", &node, node.name()); - } - } break; - case TEXT_NODE: - string = g_strdup_printf("text(%p)=%s", &node, node.content()); - break; - case COMMENT_NODE: - string = g_strdup_printf("comment(%p)=<!--%s-->", &node, node.content()); - break; - case DOCUMENT_NODE: - string = g_strdup_printf("document(%p)", &node); - break; - default: - string = g_strdup_printf("unknown(%p)", &node); + case ELEMENT_NODE: { + char const *id = node.attribute("id"); + if (id) { + string = g_strdup_printf("element(%p)=%s(#%s)", &node, node.name(), id); + } else { + string = g_strdup_printf("element(%p)=%s", &node, node.name()); + } + } break; + case TEXT_NODE: + string = g_strdup_printf("text(%p)=%s", &node, node.content()); + break; + case COMMENT_NODE: + string = g_strdup_printf("comment(%p)=<!--%s-->", &node, node.content()); + break; + case DOCUMENT_NODE: + string = g_strdup_printf("document(%p)", &node); + break; + default: + string = g_strdup_printf("unknown(%p)", &node); } std::shared_ptr<std::string> result = std::make_shared<std::string>(string); g_free(string); @@ -70,45 +71,48 @@ std::shared_ptr<std::string> stringify_node(Node const &node) { typedef Debug::SimpleEvent<Debug::Event::XML> DebugXML; -class DebugXMLNode : public DebugXML { +class DebugXMLNode : public DebugXML +{ public: DebugXMLNode(Node const &node, char const *name) - : DebugXML(name) + : DebugXML(name) { _addProperty("node", stringify_node(node)); } }; -class DebugAddChild : public DebugXMLNode { +class DebugAddChild : public DebugXMLNode +{ public: DebugAddChild(Node const &node, Node const &child, Node const *prev) - : DebugXMLNode(node, "add-child") + : DebugXMLNode(node, "add-child") { _addProperty("child", stringify_node(child)); - _addProperty("position", prev ? prev->position() + 1 : 0 ); + _addProperty("position", prev ? prev->position() + 1 : 0); } }; -class DebugRemoveChild : public DebugXMLNode { +class DebugRemoveChild : public DebugXMLNode +{ public: DebugRemoveChild(Node const &node, Node const &child) - : DebugXMLNode(node, "remove-child") + : DebugXMLNode(node, "remove-child") { _addProperty("child", stringify_node(child)); } }; -class DebugSetChildPosition : public DebugXMLNode { +class DebugSetChildPosition : public DebugXMLNode +{ public: - DebugSetChildPosition(Node const &node, Node const &child, - Node const *old_prev, Node const *new_prev) - : DebugXMLNode(node, "set-child-position") + DebugSetChildPosition(Node const &node, Node const &child, Node const *old_prev, Node const *new_prev) + : DebugXMLNode(node, "set-child-position") { _addProperty("child", stringify_node(child)); - unsigned old_position = ( old_prev ? old_prev->position() : 0 ); - unsigned position = ( new_prev ? new_prev->position() : 0 ); - if ( position > old_position ) { + unsigned old_position = (old_prev ? old_prev->position() : 0); + unsigned position = (new_prev ? new_prev->position() : 0); + if (position > old_position) { --position; } @@ -116,67 +120,72 @@ public: } }; -class DebugSetContent : public DebugXMLNode { +class DebugSetContent : public DebugXMLNode +{ public: - DebugSetContent(Node const &node, - Util::ptr_shared content) - : DebugXMLNode(node, "set-content") + DebugSetContent(Node const &node, Util::ptr_shared content) + : DebugXMLNode(node, "set-content") { _addProperty("content", content.pointer()); } }; -class DebugClearContent : public DebugXMLNode { +class DebugClearContent : public DebugXMLNode +{ public: DebugClearContent(Node const &node) - : DebugXMLNode(node, "clear-content") + : DebugXMLNode(node, "clear-content") {} }; -class DebugSetAttribute : public DebugXMLNode { +class DebugSetAttribute : public DebugXMLNode +{ public: - DebugSetAttribute(Node const &node, - GQuark name, - Util::ptr_shared value) - : DebugXMLNode(node, "set-attribute") + DebugSetAttribute(Node const &node, GQuark name, Util::ptr_shared value) + : DebugXMLNode(node, "set-attribute") { _addProperty("name", g_quark_to_string(name)); _addProperty("value", value.pointer()); } }; -class DebugClearAttribute : public DebugXMLNode { +class DebugClearAttribute : public DebugXMLNode +{ public: DebugClearAttribute(Node const &node, GQuark name) - : DebugXMLNode(node, "clear-attribute") + : DebugXMLNode(node, "clear-attribute") { _addProperty("name", g_quark_to_string(name)); } }; -class DebugSetElementName : public DebugXMLNode { +class DebugSetElementName : public DebugXMLNode +{ public: - DebugSetElementName(Node const& node, GQuark name) - : DebugXMLNode(node, "set-name") + DebugSetElementName(Node const &node, GQuark name) + : DebugXMLNode(node, "set-name") { _addProperty("name", g_quark_to_string(name)); } }; -} +} // namespace -using Util::ptr_shared; -using Util::share_string; -using Util::share_unsafe; +using Util::cons; using Util::List; using Util::MutableList; -using Util::cons; +using Util::ptr_shared; using Util::rest; using Util::set_rest; +using Util::share_string; +using Util::share_unsafe; SimpleNode::SimpleNode(int code, Document *document) -: Node(), _name(code), _attributes(), _child_count(0), - _cached_positions_valid(false) + : Node() + , _name(code) + , _attributes() + , _child_count(0) + , _cached_positions_valid(false) { g_assert(document != nullptr); @@ -188,11 +197,13 @@ SimpleNode::SimpleNode(int code, Document *document) } SimpleNode::SimpleNode(SimpleNode const &node, Document *document) -: Node(), - _cached_position(node._cached_position), - _name(node._name), _attributes(), _content(node._content), - _child_count(node._child_count), - _cached_positions_valid(node._cached_positions_valid) + : Node() + , _cached_position(node._cached_position) + , _name(node._name) + , _attributes() + , _content(node._content) + , _child_count(node._child_count) + , _cached_positions_valid(node._cached_positions_valid) { g_assert(document != nullptr); @@ -200,10 +211,8 @@ SimpleNode::SimpleNode(SimpleNode const &node, Document *document) _parent = _next = _prev = nullptr; _first_child = _last_child = nullptr; - for ( SimpleNode *child = node._first_child ; - child != nullptr ; child = child->_next ) - { - SimpleNode *child_copy=dynamic_cast<SimpleNode *>(child->duplicate(document)); + for (SimpleNode *child = node._first_child; child != nullptr; child = child->_next) { + SimpleNode *child_copy = dynamic_cast<SimpleNode *>(child->duplicate(document)); child_copy->_setParent(this); if (_last_child) { // not the first iteration @@ -217,32 +226,31 @@ SimpleNode::SimpleNode(SimpleNode const &node, Document *document) child_copy->release(); // release to avoid a leak } - for ( List<AttributeRecord const> iter = node._attributes ; - iter ; ++iter ) - { + for (List<AttributeRecord const> iter = node._attributes; iter; ++iter) { _attributes = cons(*iter, _attributes); } _observers.add(_subtree_observers); } -gchar const *SimpleNode::name() const { +gchar const *SimpleNode::name() const +{ return g_quark_to_string(_name); } -gchar const *SimpleNode::content() const { +gchar const *SimpleNode::content() const +{ return this->_content; } -gchar const *SimpleNode::attribute(gchar const *name) const { +gchar const *SimpleNode::attribute(gchar const *name) const +{ g_return_val_if_fail(name != nullptr, NULL); GQuark const key = g_quark_from_string(name); - for ( List<AttributeRecord const> iter = _attributes ; - iter ; ++iter ) - { - if ( iter->key == key ) { + for (List<AttributeRecord const> iter = _attributes; iter; ++iter) { + if (iter->key == key) { return iter->value; } } @@ -250,17 +258,17 @@ gchar const *SimpleNode::attribute(gchar const *name) const { return nullptr; } -unsigned SimpleNode::position() const { +unsigned SimpleNode::position() const +{ g_return_val_if_fail(_parent != nullptr, 0); return _parent->_childPosition(*this); } -unsigned SimpleNode::_childPosition(SimpleNode const &child) const { +unsigned SimpleNode::_childPosition(SimpleNode const &child) const +{ if (!_cached_positions_valid) { - unsigned position=0; - for ( SimpleNode *sibling = _first_child ; - sibling ; sibling = sibling->_next ) - { + unsigned position = 0; + for (SimpleNode *sibling = _first_child; sibling; sibling = sibling->_next) { sibling->_cached_position = position; position++; } @@ -269,20 +277,20 @@ unsigned SimpleNode::_childPosition(SimpleNode const &child) const { return child._cached_position; } -Node *SimpleNode::nthChild(unsigned index) { +Node *SimpleNode::nthChild(unsigned index) +{ SimpleNode *child = _first_child; - for ( ; index > 0 && child ; child = child->_next ) { + for (; index > 0 && child; child = child->_next) { index--; } return child; } -bool SimpleNode::matchAttributeName(gchar const *partial_name) const { +bool SimpleNode::matchAttributeName(gchar const *partial_name) const +{ g_return_val_if_fail(partial_name != nullptr, false); - for ( List<AttributeRecord const> iter = _attributes ; - iter ; ++iter ) - { + for (List<AttributeRecord const> iter = _attributes; iter; ++iter) { gchar const *name = g_quark_to_string(iter->key); if (std::strstr(name, partial_name)) { return true; @@ -292,7 +300,8 @@ bool SimpleNode::matchAttributeName(gchar const *partial_name) const { return false; } -void SimpleNode::_setParent(SimpleNode *parent) { +void SimpleNode::_setParent(SimpleNode *parent) +{ if (_parent) { _subtree_observers.remove(_parent->_subtree_observers); } @@ -302,9 +311,10 @@ void SimpleNode::_setParent(SimpleNode *parent) { } } -void SimpleNode::setContent(gchar const *content) { - ptr_shared old_content=_content; - ptr_shared new_content = ( content ? share_string(content) : ptr_shared() ); +void SimpleNode::setContent(gchar const *content) +{ + ptr_shared old_content = _content; + ptr_shared new_content = (content ? share_string(content) : ptr_shared()); Debug::EventTracker<> tracker; if (new_content) { @@ -315,14 +325,13 @@ void SimpleNode::setContent(gchar const *content) { _content = new_content; - if ( _content != old_content ) { + if (_content != old_content) { _document->logger()->notifyContentChanged(*this, old_content, _content); _observers.notifyContentChanged(*this, old_content, _content); } } -void -SimpleNode::setAttributeImpl(gchar const *name, gchar const *value) +void SimpleNode::setAttributeImpl(gchar const *name, gchar const *value) { g_return_if_fail(name && *name); @@ -331,35 +340,33 @@ SimpleNode::setAttributeImpl(gchar const *name, gchar const *value) // Check usefulness of attributes on elements in the svg namespace, optionally don't add them to tree. Glib::ustring element = g_quark_to_string(_name); - //g_message("setAttribute: %s: %s: %s", element.c_str(), name, value); - gchar* cleaned_value = g_strdup( value ); + // g_message("setAttribute: %s: %s: %s", element.c_str(), name, value); + gchar *cleaned_value = g_strdup(value); // Only check elements in SVG name space and don't block setting attribute to NULL. - if( element.substr(0,4) == "svg:" && value != nullptr) { - + if (element.substr(0, 4) == "svg:" && value != nullptr) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if( prefs->getBool("/options/svgoutput/check_on_editing") ) { - + if (prefs->getBool("/options/svgoutput/check_on_editing")) { gchar const *id_char = attribute("id"); - Glib::ustring id = (id_char == nullptr ? "" : id_char ); + Glib::ustring id = (id_char == nullptr ? "" : id_char); unsigned int flags = sp_attribute_clean_get_prefs(); - bool attr_warn = flags & SP_ATTRCLEAN_ATTR_WARN; + bool attr_warn = flags & SP_ATTRCLEAN_ATTR_WARN; bool attr_remove = flags & SP_ATTRCLEAN_ATTR_REMOVE; // Check attributes - if( (attr_warn || attr_remove) && value != nullptr ) { - bool is_useful = sp_attribute_check_attribute( element, id, name, attr_warn ); - if( !is_useful && attr_remove ) { - g_free( cleaned_value ); + if ((attr_warn || attr_remove) && value != nullptr) { + bool is_useful = sp_attribute_check_attribute(element, id, name, attr_warn); + if (!is_useful && attr_remove) { + g_free(cleaned_value); return; // Don't add to tree. } } // Check style properties -- Note: if element is not yet inserted into // tree (and thus has no parent), default values will not be tested. - if( !strcmp( name, "style" ) && (flags >= SP_ATTRCLEAN_STYLE_WARN) ) { - g_free( cleaned_value ); - cleaned_value = g_strdup( sp_attribute_clean_style( this, value, flags ).c_str() ); + if (!strcmp(name, "style") && (flags >= SP_ATTRCLEAN_STYLE_WARN)) { + g_free(cleaned_value); + cleaned_value = g_strdup(sp_attribute_clean_style(this, value, flags).c_str()); // if( g_strcmp0( value, cleaned_value ) ) { // g_warning( "SimpleNode::setAttribute: %s", id.c_str() ); // g_warning( " original: %s", value); @@ -373,17 +380,17 @@ SimpleNode::setAttributeImpl(gchar const *name, gchar const *value) MutableList<AttributeRecord> ref; MutableList<AttributeRecord> existing; - for ( existing = _attributes ; existing ; ++existing ) { - if ( existing->key == key ) { + for (existing = _attributes; existing; ++existing) { + if (existing->key == key) { break; } ref = existing; } Debug::EventTracker<> tracker; - ptr_shared old_value=( existing ? existing->value : ptr_shared() ); + ptr_shared old_value = (existing ? existing->value : ptr_shared()); - ptr_shared new_value=ptr_shared(); + ptr_shared new_value = ptr_shared(); if (cleaned_value) { new_value = share_string(cleaned_value); tracker.set<DebugSetAttribute>(*this, key, new_value); @@ -408,15 +415,16 @@ SimpleNode::setAttributeImpl(gchar const *name, gchar const *value) } } - if ( new_value != old_value && (!old_value || !new_value || strcmp(old_value, new_value))) { + if (new_value != old_value && (!old_value || !new_value || strcmp(old_value, new_value))) { _document->logger()->notifyAttributeChanged(*this, key, old_value, new_value); _observers.notifyAttributeChanged(*this, key, old_value, new_value); - //g_warning( "setAttribute notified: %s: %s: %s: %s", name, element.c_str(), old_value, new_value ); + // g_warning( "setAttribute notified: %s: %s: %s: %s", name, element.c_str(), old_value, new_value ); } - g_free( cleaned_value ); + g_free(cleaned_value); } -void SimpleNode::setCodeUnsafe(int code) { +void SimpleNode::setCodeUnsafe(int code) +{ GQuark old_code = static_cast<GQuark>(_name); GQuark new_code = static_cast<GQuark>(code); @@ -431,13 +439,14 @@ void SimpleNode::setCodeUnsafe(int code) { } } -void SimpleNode::addChild(Node *generic_child, Node *generic_ref) { +void SimpleNode::addChild(Node *generic_child, Node *generic_ref) +{ g_assert(generic_child); g_assert(generic_child->document() == _document); g_assert(!generic_ref || generic_ref->document() == _document); - SimpleNode *child=dynamic_cast<SimpleNode *>(generic_child); - SimpleNode *ref=dynamic_cast<SimpleNode *>(generic_ref); + SimpleNode *child = dynamic_cast<SimpleNode *>(generic_child); + SimpleNode *ref = dynamic_cast<SimpleNode *>(generic_ref); g_assert(!ref || ref->_parent == this); g_assert(!child->_parent); @@ -451,7 +460,8 @@ void SimpleNode::addChild(Node *generic_child, Node *generic_ref) { child->_prev = ref; } else { - if(_first_child) _first_child->_prev = child; + if (_first_child) + _first_child->_prev = child; next = _first_child; _first_child = child; } @@ -480,12 +490,13 @@ void SimpleNode::addChild(Node *generic_child, Node *generic_ref) { _observers.notifyChildAdded(*this, *child, ref); } -void SimpleNode::removeChild(Node *generic_child) { +void SimpleNode::removeChild(Node *generic_child) +{ g_assert(generic_child); g_assert(generic_child->document() == _document); - SimpleNode *child=dynamic_cast<SimpleNode *>(generic_child); - SimpleNode *ref=child->_prev; + SimpleNode *child = dynamic_cast<SimpleNode *>(generic_child); + SimpleNode *ref = child->_prev; SimpleNode *next = child->_next; g_assert(child->_parent == this); @@ -514,23 +525,26 @@ void SimpleNode::removeChild(Node *generic_child) { _observers.notifyChildRemoved(*this, *child, ref); } -void SimpleNode::changeOrder(Node *generic_child, Node *generic_ref) { +void SimpleNode::changeOrder(Node *generic_child, Node *generic_ref) +{ g_assert(generic_child); g_assert(generic_child->document() == this->_document); g_assert(!generic_ref || generic_ref->document() == this->_document); - SimpleNode *const child=dynamic_cast<SimpleNode *>(generic_child); - SimpleNode *const ref=dynamic_cast<SimpleNode *>(generic_ref); + SimpleNode *const child = dynamic_cast<SimpleNode *>(generic_child); + SimpleNode *const ref = dynamic_cast<SimpleNode *>(generic_ref); g_return_if_fail(child->parent() == this); g_return_if_fail(child != ref); g_return_if_fail(!ref || ref->parent() == this); - SimpleNode *const prev= child->_prev; + SimpleNode *const prev = child->_prev; Debug::EventTracker<DebugSetChildPosition> tracker(*this, *child, prev, ref); - if (prev == ref) { return; } + if (prev == ref) { + return; + } SimpleNode *next; @@ -558,7 +572,7 @@ void SimpleNode::changeOrder(Node *generic_child, Node *generic_ref) { child->_prev = ref; child->_next = next; - + if (next) { next->_prev = child; } else { @@ -571,17 +585,16 @@ void SimpleNode::changeOrder(Node *generic_child, Node *generic_ref) { _observers.notifyChildOrderChanged(*this, *child, prev, ref); } -void SimpleNode::setPosition(int pos) { +void SimpleNode::setPosition(int pos) +{ g_return_if_fail(_parent != nullptr); // a position beyond the end of the list means the end of the list; // a negative position is the same as an infinitely large position - SimpleNode *ref=nullptr; - for ( SimpleNode *sibling = _parent->_first_child ; - sibling && pos ; sibling = sibling->_next ) - { - if ( sibling != this ) { + SimpleNode *ref = nullptr; + for (SimpleNode *sibling = _parent->_first_child; sibling && pos; sibling = sibling->_next) { + if (sibling != this) { ref = sibling; pos--; } @@ -592,49 +605,50 @@ void SimpleNode::setPosition(int pos) { namespace { -void child_added(Node *node, Node *child, Node *ref, void *data) { +void child_added(Node *node, Node *child, Node *ref, void *data) +{ reinterpret_cast<NodeObserver *>(data)->notifyChildAdded(*node, *child, ref); } -void child_removed(Node *node, Node *child, Node *ref, void *data) { +void child_removed(Node *node, Node *child, Node *ref, void *data) +{ reinterpret_cast<NodeObserver *>(data)->notifyChildRemoved(*node, *child, ref); } -void content_changed(Node *node, gchar const *old_content, gchar const *new_content, void *data) { - reinterpret_cast<NodeObserver *>(data)->notifyContentChanged(*node, Util::share_unsafe((const char *)old_content), Util::share_unsafe((const char *)new_content)); +void content_changed(Node *node, gchar const *old_content, gchar const *new_content, void *data) +{ + reinterpret_cast<NodeObserver *>(data)->notifyContentChanged(*node, Util::share_unsafe((const char *)old_content), + Util::share_unsafe((const char *)new_content)); } -void attr_changed(Node *node, gchar const *name, gchar const *old_value, gchar const *new_value, bool /*is_interactive*/, void *data) { - reinterpret_cast<NodeObserver *>(data)->notifyAttributeChanged(*node, g_quark_from_string(name), Util::share_unsafe((const char *)old_value), Util::share_unsafe((const char *)new_value)); +void attr_changed(Node *node, gchar const *name, gchar const *old_value, gchar const *new_value, + bool /*is_interactive*/, void *data) +{ + reinterpret_cast<NodeObserver *>(data)->notifyAttributeChanged(*node, g_quark_from_string(name), + Util::share_unsafe((const char *)old_value), + Util::share_unsafe((const char *)new_value)); } -void order_changed(Node *node, Node *child, Node *old_ref, Node *new_ref, void *data) { +void order_changed(Node *node, Node *child, Node *old_ref, Node *new_ref, void *data) +{ reinterpret_cast<NodeObserver *>(data)->notifyChildOrderChanged(*node, *child, old_ref, new_ref); } -const NodeEventVector OBSERVER_EVENT_VECTOR = { - &child_added, - &child_removed, - &attr_changed, - &content_changed, - &order_changed -}; +const NodeEventVector OBSERVER_EVENT_VECTOR = {&child_added, &child_removed, &attr_changed, &content_changed, + &order_changed}; -}; +}; // namespace -void SimpleNode::synthesizeEvents(NodeEventVector const *vector, void *data) { +void SimpleNode::synthesizeEvents(NodeEventVector const *vector, void *data) +{ if (vector->attr_changed) { - for ( List<AttributeRecord const> iter = _attributes ; - iter ; ++iter ) - { + for (List<AttributeRecord const> iter = _attributes; iter; ++iter) { vector->attr_changed(this, g_quark_to_string(iter->key), nullptr, iter->value, false, data); } } if (vector->child_added) { SimpleNode *ref = nullptr; - for ( SimpleNode *child = this->_first_child ; - child ; child = child->_next ) - { + for (SimpleNode *child = this->_first_child; child; child = child->_next) { vector->child_added(this, child, ref, data); ref = child; } @@ -644,12 +658,13 @@ void SimpleNode::synthesizeEvents(NodeEventVector const *vector, void *data) { } } -void SimpleNode::synthesizeEvents(NodeObserver &observer) { +void SimpleNode::synthesizeEvents(NodeObserver &observer) +{ synthesizeEvents(&OBSERVER_EVENT_VECTOR, &observer); } -void SimpleNode::recursivePrintTree(unsigned level) { - +void SimpleNode::recursivePrintTree(unsigned level) +{ if (level == 0) { std::cout << "XML Node Tree" << std::endl; } @@ -657,43 +672,42 @@ void SimpleNode::recursivePrintTree(unsigned level) { for (unsigned i = 0; i < level; ++i) { std::cout << " "; } - char const *id=attribute("id"); + char const *id = attribute("id"); if (id) { std::cout << id << std::endl; } else { std::cout << name() << std::endl; } for (SimpleNode *child = _first_child; child != nullptr; child = child->_next) { - child->recursivePrintTree( level+1 ); + child->recursivePrintTree(level + 1); } } -Node *SimpleNode::root() { - Node *parent=this; +Node *SimpleNode::root() +{ + Node *parent = this; while (parent->parent()) { parent = parent->parent(); } - if ( parent->type() == DOCUMENT_NODE ) { - for ( Node *child = _document->firstChild() ; - child ; child = child->next() ) - { - if ( child->type() == ELEMENT_NODE ) { + if (parent->type() == DOCUMENT_NODE) { + for (Node *child = _document->firstChild(); child; child = child->next()) { + if (child->type() == ELEMENT_NODE) { return child; } } return nullptr; - } else if ( parent->type() == ELEMENT_NODE ) { + } else if (parent->type() == ELEMENT_NODE) { return parent; } else { return nullptr; } } -void SimpleNode::cleanOriginal(Node *src, gchar const *key){ +void SimpleNode::cleanOriginal(Node *src, gchar const *key) +{ std::vector<Node *> to_delete; - for ( Node *child = this->firstChild() ; child != nullptr ; child = child->next() ) - { + for (Node *child = this->firstChild(); child != nullptr; child = child->next()) { gchar const *id = child->attribute(key); if (id) { Node *rch = sp_repr_lookup_child(src, key, id); @@ -706,13 +720,14 @@ void SimpleNode::cleanOriginal(Node *src, gchar const *key){ to_delete.push_back(child); } } - for (auto & i : to_delete) { + for (auto &i : to_delete) { removeChild(i); } } -bool SimpleNode::equal(Node const *other, bool recursive) { - if(strcmp(name(),other->name())!= 0){ +bool SimpleNode::equal(Node const *other, bool recursive) +{ + if (strcmp(name(), other->name()) != 0) { return false; } if (!(strcmp("sodipodi:namedview", name()))) { @@ -721,16 +736,14 @@ bool SimpleNode::equal(Node const *other, bool recursive) { guint orig_length = 0; guint other_length = 0; - if(content() && other->content() && strcmp(content(), other->content()) != 0){ + if (content() && other->content() && strcmp(content(), other->content()) != 0) { return false; } for (List<AttributeRecord const> orig_attr = attributeList(); orig_attr; ++orig_attr) { for (List<AttributeRecord const> other_attr = other->attributeList(); other_attr; ++other_attr) { - const gchar * key_orig = g_quark_to_string(orig_attr->key); - const gchar * key_other = g_quark_to_string(other_attr->key); - if (!strcmp(key_orig, key_other) && - !strcmp(orig_attr->value, other_attr->value)) - { + const gchar *key_orig = g_quark_to_string(orig_attr->key); + const gchar *key_other = g_quark_to_string(other_attr->key); + if (!strcmp(key_orig, key_other) && !strcmp(orig_attr->value, other_attr->value)) { other_length++; break; } @@ -741,17 +754,14 @@ bool SimpleNode::equal(Node const *other, bool recursive) { return false; } if (recursive) { - //NOTE: for faster the childs need to be in the same order + // NOTE: for faster the childs need to be in the same order Node const *other_child = other->firstChild(); - for ( Node *child = firstChild(); - child; - child = child->next()) - { + for (Node *child = firstChild(); child; child = child->next()) { if (!child->equal(other_child, recursive)) { return false; } other_child = other_child->next(); - if(!other_child) { + if (!other_child) { return false; } } @@ -759,53 +769,51 @@ bool SimpleNode::equal(Node const *other, bool recursive) { return true; } -void SimpleNode::mergeFrom(Node const *src, gchar const *key, bool extension, bool clean) { +void SimpleNode::mergeFrom(Node const *src, gchar const *key, bool extension, bool clean) +{ g_return_if_fail(src != nullptr); g_return_if_fail(key != nullptr); g_assert(src != this); setContent(src->content()); - if(_parent) { + if (_parent) { setPosition(src->position()); } if (clean) { - Node * srcp = const_cast<Node *>(src); + Node *srcp = const_cast<Node *>(src); cleanOriginal(srcp, key); } - for ( Node const *child = src->firstChild() ; child != nullptr ; child = child->next() ) - { + for (Node const *child = src->firstChild(); child != nullptr; child = child->next()) { gchar const *id = child->attribute(key); if (id) { - Node *rch=sp_repr_lookup_child(this, key, id); + Node *rch = sp_repr_lookup_child(this, key, id); if (rch && (!extension || rch->equal(child, false))) { rch->mergeFrom(child, key, extension); continue; } else { - if(rch) { + if (rch) { removeChild(rch); } } } { guint pos = child->position(); - Node *rch=child->duplicate(_document); + Node *rch = child->duplicate(_document); addChildAtPos(rch, pos); rch->release(); } } - for ( List<AttributeRecord const> iter = src->attributeList() ; - iter ; ++iter ) - { + for (List<AttributeRecord const> iter = src->attributeList(); iter; ++iter) { setAttribute(g_quark_to_string(iter->key), iter->value); } } -} +} // namespace XML -} +} // namespace Inkscape /* Local Variables: diff --git a/src/xml/simple-node.h b/src/xml/simple-node.h index 73af3fa88fca5cb27c497ceb52d31afc7a80d927..09fa3e96694e0df7f0762be037c4a45851816970 100644 --- a/src/xml/simple-node.h +++ b/src/xml/simple-node.h @@ -18,9 +18,9 @@ #include <cassert> #include <iostream> -#include "xml/node.h" #include "xml/attribute-record.h" #include "xml/composite-node-observer.h" +#include "xml/node.h" namespace Inkscape { @@ -32,7 +32,8 @@ namespace XML { * @see Inkscape::XML::Node */ class SimpleNode -: virtual public Node, public Inkscape::GC::Managed<> + : virtual public Node + , public Inkscape::GC::Managed<> { public: char const *name() const override; @@ -40,16 +41,12 @@ public: void setCodeUnsafe(int code) override; Document *document() override { return _document; } - Document const *document() const override { - return const_cast<SimpleNode *>(this)->document(); - } + Document const *document() const override { return const_cast<SimpleNode *>(this)->document(); } - Node *duplicate(Document* doc) const override { return _duplicate(doc); } + Node *duplicate(Document *doc) const override { return _duplicate(doc); } Node *root() override; - Node const *root() const override { - return const_cast<SimpleNode *>(this)->root(); - } + Node const *root() const override { return const_cast<SimpleNode *>(this)->root(); } Node *parent() override { return _parent; } Node const *parent() const override { return _parent; } @@ -66,14 +63,10 @@ public: unsigned childCount() const override { return _child_count; } Node *nthChild(unsigned index) override; - Node const *nthChild(unsigned index) const override { - return const_cast<SimpleNode *>(this)->nthChild(index); - } + Node const *nthChild(unsigned index) const override { return const_cast<SimpleNode *>(this)->nthChild(index); } void addChild(Node *child, Node *ref) override; - void appendChild(Node *child) override { - SimpleNode::addChild(child, _last_child); - } + void appendChild(Node *child) override { SimpleNode::addChild(child, _last_child); } void removeChild(Node *child) override; void changeOrder(Node *child, Node *ref) override; @@ -90,33 +83,22 @@ public: bool equal(Node const *other, bool recursive) override; void mergeFrom(Node const *src, char const *key, bool extension = false, bool clean = false) override; - Inkscape::Util::List<AttributeRecord const> attributeList() const override { - return _attributes; - } + Inkscape::Util::List<AttributeRecord const> attributeList() const override { return _attributes; } void synthesizeEvents(NodeEventVector const *vector, void *data) override; void synthesizeEvents(NodeObserver &observer) override; - void addListener(NodeEventVector const *vector, void *data) override { + void addListener(NodeEventVector const *vector, void *data) override + { assert(vector != NULL); _observers.addListener(*vector, data); } - void addObserver(NodeObserver &observer) override { - _observers.add(observer); - } - void removeListenerByData(void *data) override { - _observers.removeListenerByData(data); - } - void removeObserver(NodeObserver &observer) override { - _observers.remove(observer); - } + void addObserver(NodeObserver &observer) override { _observers.add(observer); } + void removeListenerByData(void *data) override { _observers.removeListenerByData(data); } + void removeObserver(NodeObserver &observer) override { _observers.remove(observer); } - void addSubtreeObserver(NodeObserver &observer) override { - _subtree_observers.add(observer); - } - void removeSubtreeObserver(NodeObserver &observer) override { - _subtree_observers.remove(observer); - } + void addSubtreeObserver(NodeObserver &observer) override { _subtree_observers.add(observer); } + void removeSubtreeObserver(NodeObserver &observer) override { _subtree_observers.remove(observer); } void recursivePrintTree(unsigned level = 0) override; @@ -124,7 +106,7 @@ protected: SimpleNode(int code, Document *document); SimpleNode(SimpleNode const &repr, Document *document); - virtual SimpleNode *_duplicate(Document *doc) const=0; + virtual SimpleNode *_duplicate(Document *doc) const = 0; void setAttributeImpl(char const *key, char const *value) override; private: @@ -154,9 +136,9 @@ private: CompositeNodeObserver _subtree_observers; }; -} +} // namespace XML -} +} // namespace Inkscape #endif /* diff --git a/src/xml/sp-css-attr.h b/src/xml/sp-css-attr.h index 07db9caa86daecde2709e45e8cc4eafd058db833..925d79eaa60d46762344353e139d76c50d54f31c 100644 --- a/src/xml/sp-css-attr.h +++ b/src/xml/sp-css-attr.h @@ -15,7 +15,8 @@ #include "xml/node.h" -class SPCSSAttr : virtual public Inkscape::XML::Node { +class SPCSSAttr : virtual public Inkscape::XML::Node +{ }; #endif diff --git a/src/xml/subtree.cpp b/src/xml/subtree.cpp index 5340c2af997f8efe0edde6379f36560ec7d534fb..5ed48264452e7faf0a12ee5bc8a1eb91d24b0dab 100644 --- a/src/xml/subtree.cpp +++ b/src/xml/subtree.cpp @@ -10,46 +10,54 @@ * Released under GNU GPL v2+, read the file 'COPYING' for more information. */ -#include "xml/node.h" #include "xml/subtree.h" + #include "xml/node-iterators.h" +#include "xml/node.h" namespace Inkscape { namespace XML { -Subtree::Subtree(Node &root) : _root(root) { +Subtree::Subtree(Node &root) + : _root(root) +{ _root.addSubtreeObserver(_observers); } -Subtree::~Subtree() { +Subtree::~Subtree() +{ _root.removeSubtreeObserver(_observers); } namespace { -void synthesize_events_recursive(Node &node, NodeObserver &observer) { +void synthesize_events_recursive(Node &node, NodeObserver &observer) +{ node.synthesizeEvents(observer); - for ( NodeSiblingIterator iter = node.firstChild() ; iter ; ++iter ) { + for (NodeSiblingIterator iter = node.firstChild(); iter; ++iter) { synthesize_events_recursive(*iter, observer); } } -} +} // namespace -void Subtree::synthesizeEvents(NodeObserver &observer) { +void Subtree::synthesizeEvents(NodeObserver &observer) +{ synthesize_events_recursive(_root, observer); } -void Subtree::addObserver(NodeObserver &observer) { +void Subtree::addObserver(NodeObserver &observer) +{ _observers.add(observer); } -void Subtree::removeObserver(NodeObserver &observer) { - _observers.remove(observer); +void Subtree::removeObserver(NodeObserver &observer) +{ + _observers.remove(observer); } -} -} +} // namespace XML +} // namespace Inkscape /* Local Variables: diff --git a/src/xml/subtree.h b/src/xml/subtree.h index ef4002ade98adff7bcccf72cc24f99002edd219e..f67e973b21e1ebf9c9fc410784089e34efd704fb 100644 --- a/src/xml/subtree.h +++ b/src/xml/subtree.h @@ -26,7 +26,8 @@ namespace XML { * Currently the only such operations are adding and removing subtree observers * and synthesizing events for the entire subtree. */ -class Subtree : public GC::Managed<GC::SCANNED, GC::MANUAL> { +class Subtree : public GC::Managed<GC::SCANNED, GC::MANUAL> +{ public: Subtree(Node &root); ~Subtree(); @@ -58,8 +59,8 @@ private: CompositeNodeObserver _observers; }; -} -} +} // namespace XML +} // namespace Inkscape #endif /* diff --git a/src/xml/text-node.h b/src/xml/text-node.h index 58b12f34da085636c934b79d9463bdfd04510ad5..9fc6b7ed4be3e9e85562fd5a42ab57b393838c66 100644 --- a/src/xml/text-node.h +++ b/src/xml/text-node.h @@ -12,6 +12,7 @@ #define SEEN_INKSCAPE_XML_TEXT_NODE_H #include <glib.h> + #include "xml/simple-node.h" namespace Inkscape { @@ -21,35 +22,37 @@ namespace XML { /** * @brief Text node, e.g. "Some text" in <group>Some text</group> */ -struct TextNode : public SimpleNode { +struct TextNode : public SimpleNode +{ TextNode(Util::ptr_shared content, Document *doc) - : SimpleNode(g_quark_from_static_string("string"), doc) + : SimpleNode(g_quark_from_static_string("string"), doc) { setContent(content); _is_CData = false; } TextNode(Util::ptr_shared content, Document *doc, bool is_CData) - : SimpleNode(g_quark_from_static_string("string"), doc) + : SimpleNode(g_quark_from_static_string("string"), doc) { setContent(content); _is_CData = is_CData; } TextNode(TextNode const &other, Document *doc) - : SimpleNode(other, doc) { - _is_CData = other._is_CData; + : SimpleNode(other, doc) + { + _is_CData = other._is_CData; } Inkscape::XML::NodeType type() const override { return Inkscape::XML::TEXT_NODE; } bool is_CData() const { return _is_CData; } protected: - SimpleNode *_duplicate(Document* doc) const override { return new TextNode(*this, doc); } + SimpleNode *_duplicate(Document *doc) const override { return new TextNode(*this, doc); } bool _is_CData; }; -} +} // namespace XML -} +} // namespace Inkscape #endif /*